From 151c71ddd87d00aebe221005fd43a5371996223e Mon Sep 17 00:00:00 2001 From: Axorax Date: Tue, 31 Dec 2024 16:15:51 +0600 Subject: [PATCH 1/5] Add more JS snippets --- public/data/javascript.json | 90 +++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/public/data/javascript.json b/public/data/javascript.json index 9e8877e3..b2345d85 100644 --- a/public/data/javascript.json +++ b/public/data/javascript.json @@ -184,6 +184,96 @@ ], "tags": ["string", "whitespace"], "author": "axorax" + }, + { + "title": "Pad String on Both Sides", + "description": "Pads a string on both sides with a specified character until it reaches the desired length.", + "code": [ + "function padString(str, length, char = ' ') {", + " const totalPad = length - str.length;", + " const padStart = Math.floor(totalPad / 2);", + " const padEnd = totalPad - padStart;", + " return char.repeat(padStart) + str + char.repeat(padEnd);", + "}", + "", + "// Example usage:", + "console.log(padString('hello', 10, '*')); // Output: '**hello***'" + ], + "tags": ["string", "pad", "manipulation"], + "author": "axorax" + }, + { + "title": "Convert String to Snake Case", + "description": "Converts a given string into snake_case.", + "code": [ + "function toSnakeCase(str) {", + " return str.replace(/([a-z])([A-Z])/g, '$1_$2')", + " .replace(/\\s+/g, '_')", + " .toLowerCase();", + "}", + "", + "// Example usage:", + "console.log(toSnakeCase('Hello World Test')); // Output: 'hello_world_test'" + ], + "tags": ["string", "case", "snake_case"], + "author": "axorax" + }, + { + "title": "Remove Vowels from a String", + "description": "Removes all vowels from a given string.", + "code": [ + "function removeVowels(str) {", + " return str.replace(/[aeiouAEIOU]/g, '');", + "}", + "", + "// Example usage:", + "console.log(removeVowels('Hello World')); // Output: 'Hll Wrld'" + ], + "tags": ["string", "remove", "vowels"], + "author": "axorax" + }, + { + "title": "Mask Sensitive Information", + "description": "Masks parts of a sensitive string, like a credit card or email address.", + "code": [ + "function maskSensitiveInfo(str, visibleCount = 4, maskChar = '*') {", + " return str.slice(0, visibleCount) + maskChar.repeat(Math.max(0, str.length - visibleCount));", + "}", + "", + "// Example usage:", + "console.log(maskSensitiveInfo('123456789', 4)); // Output: '1234*****'", + "console.log(maskSensitiveInfo('example@mail.com', 2, '#')); // Output: 'ex#############'" + ], + "tags": ["string", "mask", "sensitive"], + "author": "axorax" + }, + { + "title": "Extract Initials from Name", + "description": "Extracts and returns the initials from a full name.", + "code": [ + "function getInitials(name) {", + " return name.split(' ').map(part => part.charAt(0).toUpperCase()).join('');", + "}", + "", + "// Example usage:", + "console.log(getInitials('John Doe')); // Output: 'JD'" + ], + "tags": ["string", "initials", "name"], + "author": "axorax" + }, + { + "title": "Convert Tabs to Spaces", + "description": "Converts all tab characters in a string to spaces.", + "code": [ + "function tabsToSpaces(str, spacesPerTab = 4) {", + " return str.replace(/\\t/g, ' '.repeat(spacesPerTab));", + "}", + "", + "// Example usage:", + "console.log(tabsToSpaces('Hello\\tWorld', 2)); // Output: 'Hello World'" + ], + "tags": ["string", "tabs", "spaces"], + "author": "axorax" } ] }, From 013edbe44f0c58d5257c1170195a8805290dcfa7 Mon Sep 17 00:00:00 2001 From: Axorax Date: Tue, 31 Dec 2024 16:45:40 +0600 Subject: [PATCH 2/5] Add more snippets for JS and PY --- public/data/javascript.json | 285 ++++++++++++++++++ public/data/python.json | 585 ++++++++++++++++++++++++++++++++++++ 2 files changed, 870 insertions(+) diff --git a/public/data/javascript.json b/public/data/javascript.json index e60bcf97..49481bf3 100644 --- a/public/data/javascript.json +++ b/public/data/javascript.json @@ -341,6 +341,206 @@ ], "tags": ["javascript", "array", "unique", "utility"], "author": "realvishalrana" + }, + { + "title": "Merge Objects Deeply", + "description": "Deeply merges two or more objects, including nested properties.", + "code": [ + "function deepMerge(...objects) {", + " return objects.reduce((acc, obj) => {", + " Object.keys(obj).forEach(key => {", + " if (typeof obj[key] === 'object' && obj[key] !== null) {", + " acc[key] = deepMerge(acc[key] || {}, obj[key]);", + " } else {", + " acc[key] = obj[key];", + " }", + " });", + " return acc;", + " }, {});", + "}", + "", + "// Usage:", + "const obj1 = { a: 1, b: { c: 2 } };", + "const obj2 = { b: { d: 3 }, e: 4 };", + "console.log(deepMerge(obj1, obj2)); // Output: { a: 1, b: { c: 2, d: 3 }, e: 4 }" + ], + "tags": ["javascript", "object", "merge", "deep"], + "author": "axorax" + }, + { + "title": "Omit Keys from Object", + "description": "Creates a new object with specific keys omitted.", + "code": [ + "function omitKeys(obj, keys) {", + " return Object.fromEntries(", + " Object.entries(obj).filter(([key]) => !keys.includes(key))", + " );", + "}", + "", + "// Usage:", + "const obj = { a: 1, b: 2, c: 3 };", + "console.log(omitKeys(obj, ['b', 'c'])); // Output: { a: 1 }" + ], + "tags": ["javascript", "object", "omit", "utility"], + "author": "axorax" + }, + { + "title": "Convert Object to Query String", + "description": "Converts an object to a query string for use in URLs.", + "code": [ + "function toQueryString(obj) {", + " return Object.entries(obj)", + " .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value))", + " .join('&');", + "}", + "", + "// Usage:", + "const params = { search: 'test', page: 1 };", + "console.log(toQueryString(params)); // Output: 'search=test&page=1'" + ], + "tags": ["javascript", "object", "query string", "url"], + "author": "axorax" + }, + { + "title": "Flatten Nested Object", + "description": "Flattens a nested object into a single-level object with dot notation for keys.", + "code": [ + "function flattenObject(obj, prefix = '') {", + " return Object.keys(obj).reduce((acc, key) => {", + " const fullPath = prefix ? `${prefix}.${key}` : key;", + " if (typeof obj[key] === 'object' && obj[key] !== null) {", + " Object.assign(acc, flattenObject(obj[key], fullPath));", + " } else {", + " acc[fullPath] = obj[key];", + " }", + " return acc;", + " }, {});", + "}", + "", + "// Usage:", + "const nestedObj = { a: { b: { c: 1 }, d: 2 }, e: 3 };", + "console.log(flattenObject(nestedObj)); // Output: { 'a.b.c': 1, 'a.d': 2, e: 3 }" + ], + "tags": ["javascript", "object", "flatten", "utility"], + "author": "axorax" + }, + { + "title": "Pick Keys from Object", + "description": "Creates a new object with only the specified keys.", + "code": [ + "function pickKeys(obj, keys) {", + " return Object.fromEntries(", + " Object.entries(obj).filter(([key]) => keys.includes(key))", + " );", + "}", + "", + "// Usage:", + "const obj = { a: 1, b: 2, c: 3 };", + "console.log(pickKeys(obj, ['a', 'c'])); // Output: { a: 1, c: 3 }" + ], + "tags": ["javascript", "object", "pick", "utility"], + "author": "axorax" + }, + { + "title": "Check if Object is Empty", + "description": "Checks whether an object has no own enumerable properties.", + "code": [ + "function isEmptyObject(obj) {", + " return Object.keys(obj).length === 0;", + "}", + "", + "// Usage:", + "console.log(isEmptyObject({})); // Output: true", + "console.log(isEmptyObject({ a: 1 })); // Output: false" + ], + "tags": ["javascript", "object", "check", "empty"], + "author": "axorax" + }, + { + "title": "Invert Object Keys and Values", + "description": "Creates a new object by swapping keys and values of the given object.", + "code": [ + "function invertObject(obj) {", + " return Object.fromEntries(", + " Object.entries(obj).map(([key, value]) => [value, key])", + " );", + "}", + "", + "// Usage:", + "const obj = { a: 1, b: 2, c: 3 };", + "console.log(invertObject(obj)); // Output: { '1': 'a', '2': 'b', '3': 'c' }" + ], + "tags": ["javascript", "object", "invert", "utility"], + "author": "axorax" + }, + { + "title": "Clone Object Shallowly", + "description": "Creates a shallow copy of an object.", + "code": [ + "function shallowClone(obj) {", + " return { ...obj };", + "}", + "", + "// Usage:", + "const obj = { a: 1, b: 2 };", + "const clone = shallowClone(obj);", + "console.log(clone); // Output: { a: 1, b: 2 }" + ], + "tags": ["javascript", "object", "clone", "shallow"], + "author": "axorax" + }, + { + "title": "Count Properties in Object", + "description": "Counts the number of own properties in an object.", + "code": [ + "function countProperties(obj) {", + " return Object.keys(obj).length;", + "}", + "", + "// Usage:", + "const obj = { a: 1, b: 2, c: 3 };", + "console.log(countProperties(obj)); // Output: 3" + ], + "tags": ["javascript", "object", "count", "properties"], + "author": "axorax" + }, + { + "title": "Compare Two Objects Shallowly", + "description": "Compares two objects shallowly and returns whether they are equal.", + "code": [ + "function shallowEqual(obj1, obj2) {", + " const keys1 = Object.keys(obj1);", + " const keys2 = Object.keys(obj2);", + " if (keys1.length !== keys2.length) return false;", + " return keys1.every(key => obj1[key] === obj2[key]);", + "}", + "", + "// Usage:", + "const obj1 = { a: 1, b: 2 };", + "const obj2 = { a: 1, b: 2 };", + "const obj3 = { a: 1, b: 3 };", + "console.log(shallowEqual(obj1, obj2)); // Output: true", + "console.log(shallowEqual(obj1, obj3)); // Output: false" + ], + "tags": ["javascript", "object", "compare", "shallow"], + "author": "axorax" + }, + { + "title": "Freeze Object", + "description": "Freezes an object to make it immutable.", + "code": [ + "function freezeObject(obj) {", + " return Object.freeze(obj);", + "}", + "", + "// Usage:", + "const obj = { a: 1, b: 2 };", + "const frozenObj = freezeObject(obj);", + "frozenObj.a = 42; // This will fail silently in strict mode.", + "console.log(frozenObj.a); // Output: 1" + ], + "tags": ["javascript", "object", "freeze", "immutable"], + "author": "axorax" } ] }, @@ -418,6 +618,91 @@ "utility" ], "author": "Yugveer06" + }, + { + "title": "Get Current Timestamp", + "description": "Retrieves the current timestamp in milliseconds since January 1, 1970.", + "code": [ + "const getCurrentTimestamp = () => Date.now();", + "", + "// Usage:", + "console.log(getCurrentTimestamp()); // Output: 1691825935839 (example)" + ], + "tags": ["javascript", "date", "timestamp", "utility"], + "author": "axorax" + }, + { + "title": "Check Leap Year", + "description": "Determines if a given year is a leap year.", + "code": [ + "const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;", + "", + "// Usage:", + "console.log(isLeapYear(2024)); // Output: true", + "console.log(isLeapYear(2023)); // Output: false" + ], + "tags": ["javascript", "date", "leap-year", "utility"], + "author": "axorax" + }, + { + "title": "Add Days to a Date", + "description": "Adds a specified number of days to a given date.", + "code": [ + "const addDays = (date, days) => {", + " const result = new Date(date);", + " result.setDate(result.getDate() + days);", + " return result;", + "};", + "", + "// Usage:", + "const today = new Date();", + "console.log(addDays(today, 10)); // Output: Date object 10 days ahead" + ], + "tags": ["javascript", "date", "add-days", "utility"], + "author": "axorax" + }, + { + "title": "Start of the Day", + "description": "Returns the start of the day (midnight) for a given date.", + "code": [ + "const startOfDay = (date) => new Date(date.setHours(0, 0, 0, 0));", + "", + "// Usage:", + "const today = new Date();", + "console.log(startOfDay(today)); // Output: Date object for midnight" + ], + "tags": ["javascript", "date", "start-of-day", "utility"], + "author": "axorax" + }, + { + "title": "Get Days in Month", + "description": "Calculates the number of days in a specific month of a given year.", + "code": [ + "const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();", + "", + "// Usage:", + "console.log(getDaysInMonth(2024, 1)); // Output: 29 (February in a leap year)", + "console.log(getDaysInMonth(2023, 1)); // Output: 28" + ], + "tags": ["javascript", "date", "days-in-month", "utility"], + "author": "axorax" + }, + { + "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.", + "code": [ + "const getDayOfYear = (date) => {", + " const startOfYear = new Date(date.getFullYear(), 0, 0);", + " const diff = date - startOfYear + (startOfYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000;", + " return Math.floor(diff / (1000 * 60 * 60 * 24));", + "};", + "", + "// Usage:", + "const today = new Date('2024-12-31');", + "console.log(getDayOfYear(today)); // Output: 366 (in a leap year)" + ], + "tags": ["javascript", "date", "day-of-year", "utility"], + "author": "axorax" } ] }, diff --git a/public/data/python.json b/public/data/python.json index dd8596f7..eb169337 100644 --- a/public/data/python.json +++ b/public/data/python.json @@ -84,6 +84,212 @@ ], "tags": ["python", "string", "punctuation", "remove", "utility"], "author": "SteliosGee" + }, + { + "title": "Capitalize Words", + "description": "Capitalizes the first letter of each word in a string.", + "code": [ + "def capitalize_words(s):", + " return ' '.join(word.capitalize() for word in s.split())", + "", + "# Usage:", + "print(capitalize_words('hello world')) # Output: 'Hello World'" + ], + "tags": ["python", "string", "capitalize", "utility"], + "author": "axorax" + }, + { + "title": "Find Longest Word", + "description": "Finds the longest word in a string.", + "code": [ + "def find_longest_word(s):", + " words = s.split()", + " return max(words, key=len) if words else ''", + "", + "# Usage:", + "print(find_longest_word('The quick brown fox')) # Output: 'quick'" + ], + "tags": ["python", "string", "longest-word", "utility"], + "author": "axorax" + }, + { + "title": "Remove Duplicate Characters", + "description": "Removes duplicate characters from a string while maintaining the order.", + "code": [ + "def remove_duplicate_chars(s):", + " seen = set()", + " return ''.join(char for char in s if not (char in seen or seen.add(char)))", + "", + "# Usage:", + "print(remove_duplicate_chars('programming')) # Output: 'progamin'" + ], + "tags": ["python", "string", "duplicates", "remove", "utility"], + "author": "axorax" + }, + { + "title": "Count Words", + "description": "Counts the number of words in a string.", + "code": [ + "def count_words(s):", + " return len(s.split())", + "", + "# Usage:", + "print(count_words('The quick brown fox')) # Output: 4" + ], + "tags": ["python", "string", "word-count", "utility"], + "author": "axorax" + }, + { + "title": "Replace Substring", + "description": "Replaces all occurrences of a substring in a string with another substring.", + "code": [ + "def replace_substring(s, old, new):", + " return s.replace(old, new)", + "", + "# Usage:", + "print(replace_substring('hello world', 'world', 'Python')) # Output: 'hello Python'" + ], + "tags": ["python", "string", "replace", "utility"], + "author": "axorax" + }, + { + "title": "Split Camel Case", + "description": "Splits a camel case string into separate words.", + "code": [ + "import re", + "", + "def split_camel_case(s):", + " return ' '.join(re.findall(r'[A-Z][a-z]*|[a-z]+', s))", + "", + "# Usage:", + "print(split_camel_case('camelCaseString')) # Output: 'camel Case String'" + ], + "tags": ["python", "string", "camel-case", "split", "utility"], + "author": "axorax" + }, + { + "title": "Count Character Frequency", + "description": "Counts the frequency of each character in a string.", + "code": [ + "from collections import Counter", + "", + "def char_frequency(s):", + " return dict(Counter(s))", + "", + "# Usage:", + "print(char_frequency('hello')) # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}" + ], + "tags": ["python", "string", "character-frequency", "utility"], + "author": "axorax" + }, + { + "title": "Remove Whitespace", + "description": "Removes all whitespace from a string.", + "code": [ + "def remove_whitespace(s):", + " return ''.join(s.split())", + "", + "# Usage:", + "print(remove_whitespace('hello world')) # Output: 'helloworld'" + ], + "tags": ["python", "string", "whitespace", "remove", "utility"], + "author": "axorax" + }, + { + "title": "Swap Case", + "description": "Swaps the case of all characters in a string.", + "code": [ + "def swap_case(s):", + " return s.swapcase()", + "", + "# Usage:", + "print(swap_case('Hello World')) # Output: 'hELLO wORLD'" + ], + "tags": ["python", "string", "case", "swap", "utility"], + "author": "axorax" + }, + { + "title": "Find All Substrings", + "description": "Finds all substrings of a given string.", + "code": [ + "def find_substrings(s):", + " substrings = []", + " for i in range(len(s)):", + " for j in range(i + 1, len(s) + 1):", + " substrings.append(s[i:j])", + " return substrings", + "", + "# Usage:", + "print(find_substrings('abc')) # Output: ['a', 'ab', 'abc', 'b', 'bc', 'c']" + ], + "tags": ["python", "string", "substring", "find", "utility"], + "author": "axorax" + }, + { + "title": "Convert Snake Case to Camel Case", + "description": "Converts a snake_case string to camelCase.", + "code": [ + "def snake_to_camel(s):", + " parts = s.split('_')", + " return parts[0] + ''.join(word.capitalize() for word in parts[1:])", + "", + "# Usage:", + "print(snake_to_camel('hello_world')) # Output: 'helloWorld'" + ], + "tags": ["python", "string", "snake-case", "camel-case", "convert", "utility"], + "author": "axorax" + }, + { + "title": "Remove Specific Characters", + "description": "Removes specific characters from a string.", + "code": [ + "def remove_chars(s, chars):", + " return ''.join(c for c in s if c not in chars)", + "", + "# Usage:", + "print(remove_chars('hello world', 'eo')) # Output: 'hll wrld'" + ], + "tags": ["python", "string", "remove", "characters", "utility"], + "author": "axorax" + }, + { + "title": "Find Unique Characters", + "description": "Finds all unique characters in a string.", + "code": [ + "def find_unique_chars(s):", + " return ''.join(sorted(set(s)))", + "", + "# Usage:", + "print(find_unique_chars('banana')) # Output: 'abn'" + ], + "tags": ["python", "string", "unique", "characters", "utility"], + "author": "axorax" + }, + { + "title": "Convert String to ASCII", + "description": "Converts a string into its ASCII representation.", + "code": [ + "def string_to_ascii(s):", + " return [ord(char) for char in s]", + "", + "# Usage:", + "print(string_to_ascii('hello')) # Output: [104, 101, 108, 108, 111]" + ], + "tags": ["python", "string", "ascii", "convert", "utility"], + "author": "axorax" + }, + { + "title": "Truncate String", + "description": "Truncates a string to a specified length and adds an ellipsis.", + "code": [ + "def truncate_string(s, length):", + " return s[:length] + '...' if len(s) > length else s", + "", + "# Usage:", + "print(truncate_string('This is a long string', 10)) # Output: 'This is a ...'" + ], + "tags": ["python", "string", "truncate", "utility"], + "author": "axorax" } ] }, @@ -205,6 +411,135 @@ ], "tags": ["python", "os", "filesystem", "file_search"], "author": "Jackeastern" + }, + { + "title": "Append to File", + "description": "Appends content to the end of a file.", + "code": [ + "def append_to_file(filepath, content):", + " with open(filepath, 'a') as file:", + " file.write(content + '\\n')", + "", + "# Usage:", + "append_to_file('example.txt', 'This is an appended line.')" + ], + "tags": ["python", "file", "append", "utility"], + "author": "axorax" + }, + { + "title": "Check if File Exists", + "description": "Checks if a file exists at the specified path.", + "code": [ + "import os", + "", + "def file_exists(filepath):", + " return os.path.isfile(filepath)", + "", + "# Usage:", + "print(file_exists('example.txt')) # Output: True or False" + ], + "tags": ["python", "file", "exists", "check", "utility"], + "author": "axorax" + }, + { + "title": "Delete File", + "description": "Deletes a file at the specified path.", + "code": [ + "import os", + "", + "def delete_file(filepath):", + " if os.path.exists(filepath):", + " os.remove(filepath)", + " print(f'File {filepath} deleted.')", + " else:", + " print(f'File {filepath} does not exist.')", + "", + "# Usage:", + "delete_file('example.txt')" + ], + "tags": ["python", "file", "delete", "utility"], + "author": "axorax" + }, + { + "title": "Copy File", + "description": "Copies a file from source to destination.", + "code": [ + "import shutil", + "", + "def copy_file(src, dest):", + " shutil.copy(src, dest)", + "", + "# Usage:", + "copy_file('example.txt', 'copy_of_example.txt')" + ], + "tags": ["python", "file", "copy", "utility"], + "author": "axorax" + }, + { + "title": "Rename File", + "description": "Renames a file from its current name to a new name.", + "code": [ + "import os", + "", + "def rename_file(old_name, new_name):", + " if os.path.exists(old_name):", + " os.rename(old_name, new_name)", + " print(f'File renamed from {old_name} to {new_name}')", + " else:", + " print(f'File {old_name} does not exist.')", + "", + "# Usage:", + "rename_file('example.txt', 'new_example.txt')" + ], + "tags": ["python", "file", "rename", "utility"], + "author": "axorax" + }, + { + "title": "List Files in Directory", + "description": "Lists all files in a specified directory.", + "code": [ + "import os", + "", + "def list_files(directory):", + " return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]", + "", + "# Usage:", + "files = list_files('/path/to/directory')", + "print(files)" + ], + "tags": ["python", "file", "list", "directory", "utility"], + "author": "axorax" + }, + { + "title": "Get File Extension", + "description": "Gets the extension of a file.", + "code": [ + "import os", + "", + "def get_file_extension(filepath):", + " return os.path.splitext(filepath)[1]", + "", + "# Usage:", + "print(get_file_extension('example.txt')) # Output: '.txt'" + ], + "tags": ["python", "file", "extension", "utility"], + "author": "axorax" + }, + { + "title": "Read File in Chunks", + "description": "Reads a file in chunks of a specified size.", + "code": [ + "def read_file_in_chunks(filepath, chunk_size):", + " with open(filepath, 'r') as file:", + " while chunk := file.read(chunk_size):", + " yield chunk", + "", + "# Usage:", + "for chunk in read_file_in_chunks('example.txt', 1024):", + " print(chunk)" + ], + "tags": ["python", "file", "read", "chunks", "utility"], + "author": "axorax" } ] }, @@ -243,6 +578,131 @@ ], "tags": ["python", "math", "prime", "check"], "author": "dostonnabotov" + }, + { + "title": "Generate Fibonacci Sequence", + "description": "Generates a Fibonacci sequence up to a given number of terms.", + "code": [ + "def generate_fibonacci(n):", + " sequence = [0, 1]", + " for _ in range(2, n):", + " sequence.append(sequence[-1] + sequence[-2])", + " return sequence[:n]", + "", + "# Usage:", + "print(generate_fibonacci(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]" + ], + "tags": ["python", "math", "fibonacci", "sequence"], + "author": "axorax" + }, + { + "title": "Check Perfect Square", + "description": "Checks if a number is a perfect square.", + "code": [ + "def is_perfect_square(n):", + " if n < 0:", + " return False", + " root = int(n**0.5)", + " return root * root == n", + "", + "# Usage:", + "print(is_perfect_square(16)) # Output: True", + "print(is_perfect_square(20)) # Output: False" + ], + "tags": ["python", "math", "perfect square", "check"], + "author": "axorax" + }, + { + "title": "Convert Binary to Decimal", + "description": "Converts a binary string to its decimal equivalent.", + "code": [ + "def binary_to_decimal(binary_str):", + " return int(binary_str, 2)", + "", + "# Usage:", + "print(binary_to_decimal('1010')) # Output: 10", + "print(binary_to_decimal('1101')) # Output: 13" + ], + "tags": ["python", "math", "binary", "decimal", "conversion"], + "author": "axorax" + }, + { + "title": "Generate Random Number", + "description": "Generates a random number within a given range.", + "code": [ + "import random", + "", + "def generate_random_number(start, end):", + " return random.randint(start, end)", + "", + "# Usage:", + "print(generate_random_number(1, 100)) # Output: A random number between 1 and 100" + ], + "tags": ["python", "math", "random", "utility"], + "author": "axorax" + }, + { + "title": "Calculate GCD (Greatest Common Divisor)", + "description": "Calculates the greatest common divisor (GCD) of two numbers using Euclid's algorithm.", + "code": [ + "def gcd(a, b):", + " while b:", + " a, b = b, a % b", + " return a", + "", + "# Usage:", + "print(gcd(56, 98)) # Output: 14", + "print(gcd(101, 10)) # Output: 1" + ], + "tags": ["python", "math", "gcd", "algorithm"], + "author": "axorax" + }, + { + "title": "Find LCM (Least Common Multiple)", + "description": "Calculates the least common multiple (LCM) of two numbers.", + "code": [ + "def lcm(a, b):", + " return abs(a * b) // gcd(a, b)", + "", + "# Usage:", + "print(lcm(12, 15)) # Output: 60", + "print(lcm(7, 5)) # Output: 35" + ], + "tags": ["python", "math", "lcm", "gcd", "utility"], + "author": "axorax" + }, + { + "title": "Solve Quadratic Equation", + "description": "Solves a quadratic equation ax^2 + bx + c = 0 and returns the roots.", + "code": [ + "import cmath", + "", + "def solve_quadratic(a, b, c):", + " discriminant = cmath.sqrt(b**2 - 4 * a * c)", + " root1 = (-b + discriminant) / (2 * a)", + " root2 = (-b - discriminant) / (2 * a)", + " return root1, root2", + "", + "# Usage:", + "print(solve_quadratic(1, -3, 2)) # Output: ((2+0j), (1+0j))", + "print(solve_quadratic(1, 2, 5)) # Output: ((-1+2j), (-1-2j))" + ], + "tags": ["python", "math", "quadratic", "equation", "solver"], + "author": "axorax" + }, + { + "title": "Calculate Compound Interest", + "description": "Calculates compound interest for a given principal amount, rate, and time period.", + "code": [ + "def compound_interest(principal, rate, time, n=1):", + " return principal * (1 + rate / n) ** (n * time)", + "", + "# Usage:", + "print(compound_interest(1000, 0.05, 5)) # Output: 1276.2815625000003", + "print(compound_interest(1000, 0.05, 5, 12)) # Output: 1283.68" + ], + "tags": ["python", "math", "compound interest", "finance"], + "author": "axorax" } ] }, @@ -326,6 +786,131 @@ ], "tags": ["python", "json", "file", "write"], "author": "e3nviction" + }, + { + "title": "Update JSON File", + "description": "Updates an existing JSON file with new data or modifies the existing values.", + "code": [ + "import json", + "", + "def update_json(filepath, new_data):", + " # Read the existing JSON data", + " with open(filepath, 'r') as file:", + " data = json.load(file)", + "", + " # Update the data with the new content", + " data.update(new_data)", + "", + " # Write the updated data back to the JSON file", + " with open(filepath, 'w') as file:", + " json.dump(data, file, indent=4)", + "", + "# Usage:", + "new_data = {'age': 31}", + "update_json('data.json', new_data)" + ], + "tags": ["python", "json", "update", "file"], + "author": "axorax" + }, + { + "title": "Merge Multiple JSON Files", + "description": "Merges multiple JSON files into one and writes the merged data into a new file.", + "code": [ + "import json", + "", + "def merge_json_files(filepaths, output_filepath):", + " merged_data = []", + "", + " # Read each JSON file and merge their data", + " for filepath in filepaths:", + " with open(filepath, 'r') as file:", + " data = json.load(file)", + " merged_data.extend(data)", + "", + " # Write the merged data into a new file", + " with open(output_filepath, 'w') as file:", + " json.dump(merged_data, file, indent=4)", + "", + "# Usage:", + "files_to_merge = ['file1.json', 'file2.json']", + "merge_json_files(files_to_merge, 'merged.json')" + ], + "tags": ["python", "json", "merge", "file"], + "author": "axorax" + }, + { + "title": "Filter JSON Data", + "description": "Filters a JSON object based on a condition and returns the filtered data.", + "code": [ + "import json", + "", + "def filter_json_data(filepath, condition):", + " with open(filepath, 'r') as file:", + " data = json.load(file)", + "", + " # Filter data based on the provided condition", + " filtered_data = [item for item in data if condition(item)]", + "", + " return filtered_data", + "", + "# Usage:", + "condition = lambda x: x['age'] > 25", + "filtered = filter_json_data('data.json', condition)", + "print(filtered)" + ], + "tags": ["python", "json", "filter", "data"], + "author": "axorax" + }, + { + "title": "Validate JSON Schema", + "description": "Validates a JSON object against a predefined schema.", + "code": [ + "import jsonschema", + "from jsonschema import validate", + "", + "def validate_json_schema(data, schema):", + " try:", + " validate(instance=data, schema=schema)", + " return True # Data is valid", + " except jsonschema.exceptions.ValidationError as err:", + " return False # Data is invalid", + "", + "# Usage:", + "schema = {", + " 'type': 'object',", + " 'properties': {", + " 'name': {'type': 'string'},", + " 'age': {'type': 'integer'}", + " },", + " 'required': ['name', 'age']", + "}", + "data = {'name': 'John', 'age': 30}", + "is_valid = validate_json_schema(data, schema)", + "print(is_valid) # Output: True" + ], + "tags": ["python", "json", "validation", "schema"], + "author": "axorax" + }, + { + "title": "Flatten Nested JSON", + "description": "Flattens a nested JSON object into a flat dictionary.", + "code": [ + "def flatten_json(nested_json, prefix=''):", + " flat_dict = {}", + " for key, value in nested_json.items():", + " if isinstance(value, dict):", + " flat_dict.update(flatten_json(value, prefix + key + '.'))", + " else:", + " flat_dict[prefix + key] = value", + " return flat_dict", + "", + "# Usage:", + "nested_json = {'name': 'John', 'address': {'city': 'New York', 'zip': '10001'}}", + "flattened = flatten_json(nested_json)", + "print(flattened) # Output: {'name': 'John', 'address.city': 'New York', 'address.zip': '10001'}" + ], + "tags": ["python", "json", "flatten", "nested"], + "author": "axorax" } ] }, From f2f81d6425196436bc6904174de113a8d4f5254e Mon Sep 17 00:00:00 2001 From: Axorax Date: Tue, 31 Dec 2024 16:54:35 +0600 Subject: [PATCH 3/5] Add Java --- public/data/_index.json | 4 ++ public/data/java.json | 129 ++++++++++++++++++++++++++++++++++++++++ public/icons/java.svg | 14 +++++ 3 files changed, 147 insertions(+) create mode 100644 public/data/java.json create mode 100644 public/icons/java.svg diff --git a/public/data/_index.json b/public/data/_index.json index 0521f16f..4fd797a3 100644 --- a/public/data/_index.json +++ b/public/data/_index.json @@ -22,5 +22,9 @@ { "lang": "Rust", "icon": "/icons/rust.svg" + }, + { + "lang": "Java", + "icon": "/icons/java.svg" } ] diff --git a/public/data/java.json b/public/data/java.json new file mode 100644 index 00000000..2d38bc93 --- /dev/null +++ b/public/data/java.json @@ -0,0 +1,129 @@ +[ + { + "categoryName": "Basics", + "snippets": [ + { + "title": "Hello, World!", + "description": "Prints Hello, World! to the terminal.", + "code": [ + "public class HelloWorld {", + " public static void main(String[] args) {", + " // Output: \"Hello, World!\"", + " System.out.println(\"Hello, World!\");", + " }", + "}" + ], + "tags": ["java", "hello-world"], + "author": "axorax" + } + ] + }, + { + "categoryName": "String Manipulation", + "snippets": [ + { + "title": "Reverse String", + "description": "Reverses the characters in a string.", + "code": [ + "public class StringManipulation {", + " public static String reverseString(String s) {", + " StringBuilder reversed = new StringBuilder(s);", + " return reversed.reverse().toString();", + " }", + "", + " // Usage:", + " public static void main(String[] args) {", + " System.out.println(reverseString('hello')); // Output: 'olleh'", + " }", + "}" + ], + "tags": ["java", "string", "reverse", "utility"], + "author": "axorax" + }, + { + "title": "Check Palindrome", + "description": "Checks if a string is a palindrome.", + "code": [ + "public class StringManipulation {", + " public static boolean isPalindrome(String s) {", + " String cleanString = s.replaceAll(\"\\s+\", \"\").toLowerCase();", + " StringBuilder reversed = new StringBuilder(cleanString);", + " return cleanString.equals(reversed.reverse().toString());", + " }", + "", + " // Usage:", + " public static void main(String[] args) {", + " System.out.println(isPalindrome('A man a plan a canal Panama')); // Output: true", + " }", + "}" + ], + "tags": ["java", "string", "palindrome", "check"], + "author": "axorax" + }, + { + "title": "Count Vowels", + "description": "Counts the number of vowels in a string.", + "code": [ + "public class StringManipulation {", + " public static int countVowels(String s) {", + " int count = 0;", + " String vowels = 'aeiouAEIOU';", + " for (int i = 0; i < s.length(); i++) {", + " if (vowels.indexOf(s.charAt(i)) != -1) {", + " count++;", + " }", + " }", + " return count;", + " }", + "", + " // Usage:", + " public static void main(String[] args) {", + " System.out.println(countVowels('hello')); // Output: 2", + " }", + "}" + ], + "tags": ["java", "string", "vowels", "count"], + "author": "axorax" + }, + { + "title": "Find Substring First Occurrence", + "description": "Finds the first occurrence of a substring in a string.", + "code": [ + "public class StringManipulation {", + " public static int findSubstring(String s, String substring) {", + " return s.indexOf(substring);", + " }", + "", + " // Usage:", + " public static void main(String[] args) {", + " System.out.println(findSubstring('hello world', 'world')); // Output: 6", + " }", + "}" + ], + "tags": ["java", "string", "substring", "search"], + "author": "axorax" + }, + { + "title": "Capitalize First Letter", + "description": "Capitalizes the first letter of a string.", + "code": [ + "public class StringManipulation {", + " public static String capitalizeFirstLetter(String s) {", + " if (s == null || s.isEmpty()) {", + " return s;", + " }", + " return s.substring(0, 1).toUpperCase() + s.substring(1);", + " }", + "", + " // Usage:", + " public static void main(String[] args) {", + " System.out.println(capitalizeFirstLetter('hello')); // Output: 'Hello'", + " }", + "}" + ], + "tags": ["java", "string", "capitalize", "utility"], + "author": "axorax" + } + ] + } +] \ No newline at end of file diff --git a/public/icons/java.svg b/public/icons/java.svg new file mode 100644 index 00000000..b46e1999 --- /dev/null +++ b/public/icons/java.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file From 5b332a0937ca8b6dd1021afac703ae2dcf7ceedb Mon Sep 17 00:00:00 2001 From: Axorax Date: Tue, 31 Dec 2024 17:12:14 +0600 Subject: [PATCH 4/5] remove java --- public/data/_index.json | 4 -- public/data/java.json | 129 ---------------------------------------- public/icons/java.svg | 14 ----- 3 files changed, 147 deletions(-) delete mode 100644 public/data/java.json delete mode 100644 public/icons/java.svg diff --git a/public/data/_index.json b/public/data/_index.json index 4fd797a3..0521f16f 100644 --- a/public/data/_index.json +++ b/public/data/_index.json @@ -22,9 +22,5 @@ { "lang": "Rust", "icon": "/icons/rust.svg" - }, - { - "lang": "Java", - "icon": "/icons/java.svg" } ] diff --git a/public/data/java.json b/public/data/java.json deleted file mode 100644 index 2d38bc93..00000000 --- a/public/data/java.json +++ /dev/null @@ -1,129 +0,0 @@ -[ - { - "categoryName": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "code": [ - "public class HelloWorld {", - " public static void main(String[] args) {", - " // Output: \"Hello, World!\"", - " System.out.println(\"Hello, World!\");", - " }", - "}" - ], - "tags": ["java", "hello-world"], - "author": "axorax" - } - ] - }, - { - "categoryName": "String Manipulation", - "snippets": [ - { - "title": "Reverse String", - "description": "Reverses the characters in a string.", - "code": [ - "public class StringManipulation {", - " public static String reverseString(String s) {", - " StringBuilder reversed = new StringBuilder(s);", - " return reversed.reverse().toString();", - " }", - "", - " // Usage:", - " public static void main(String[] args) {", - " System.out.println(reverseString('hello')); // Output: 'olleh'", - " }", - "}" - ], - "tags": ["java", "string", "reverse", "utility"], - "author": "axorax" - }, - { - "title": "Check Palindrome", - "description": "Checks if a string is a palindrome.", - "code": [ - "public class StringManipulation {", - " public static boolean isPalindrome(String s) {", - " String cleanString = s.replaceAll(\"\\s+\", \"\").toLowerCase();", - " StringBuilder reversed = new StringBuilder(cleanString);", - " return cleanString.equals(reversed.reverse().toString());", - " }", - "", - " // Usage:", - " public static void main(String[] args) {", - " System.out.println(isPalindrome('A man a plan a canal Panama')); // Output: true", - " }", - "}" - ], - "tags": ["java", "string", "palindrome", "check"], - "author": "axorax" - }, - { - "title": "Count Vowels", - "description": "Counts the number of vowels in a string.", - "code": [ - "public class StringManipulation {", - " public static int countVowels(String s) {", - " int count = 0;", - " String vowels = 'aeiouAEIOU';", - " for (int i = 0; i < s.length(); i++) {", - " if (vowels.indexOf(s.charAt(i)) != -1) {", - " count++;", - " }", - " }", - " return count;", - " }", - "", - " // Usage:", - " public static void main(String[] args) {", - " System.out.println(countVowels('hello')); // Output: 2", - " }", - "}" - ], - "tags": ["java", "string", "vowels", "count"], - "author": "axorax" - }, - { - "title": "Find Substring First Occurrence", - "description": "Finds the first occurrence of a substring in a string.", - "code": [ - "public class StringManipulation {", - " public static int findSubstring(String s, String substring) {", - " return s.indexOf(substring);", - " }", - "", - " // Usage:", - " public static void main(String[] args) {", - " System.out.println(findSubstring('hello world', 'world')); // Output: 6", - " }", - "}" - ], - "tags": ["java", "string", "substring", "search"], - "author": "axorax" - }, - { - "title": "Capitalize First Letter", - "description": "Capitalizes the first letter of a string.", - "code": [ - "public class StringManipulation {", - " public static String capitalizeFirstLetter(String s) {", - " if (s == null || s.isEmpty()) {", - " return s;", - " }", - " return s.substring(0, 1).toUpperCase() + s.substring(1);", - " }", - "", - " // Usage:", - " public static void main(String[] args) {", - " System.out.println(capitalizeFirstLetter('hello')); // Output: 'Hello'", - " }", - "}" - ], - "tags": ["java", "string", "capitalize", "utility"], - "author": "axorax" - } - ] - } -] \ No newline at end of file diff --git a/public/icons/java.svg b/public/icons/java.svg deleted file mode 100644 index b46e1999..00000000 --- a/public/icons/java.svg +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file From 9332601511a90ce2a9d59f7103da795300244524 Mon Sep 17 00:00:00 2001 From: Axorax Date: Tue, 31 Dec 2024 17:15:08 +0600 Subject: [PATCH 5/5] Add JavaScript snippets --- public/data/python.json | 585 ---------------------------------------- 1 file changed, 585 deletions(-) diff --git a/public/data/python.json b/public/data/python.json index eb169337..dd8596f7 100644 --- a/public/data/python.json +++ b/public/data/python.json @@ -84,212 +84,6 @@ ], "tags": ["python", "string", "punctuation", "remove", "utility"], "author": "SteliosGee" - }, - { - "title": "Capitalize Words", - "description": "Capitalizes the first letter of each word in a string.", - "code": [ - "def capitalize_words(s):", - " return ' '.join(word.capitalize() for word in s.split())", - "", - "# Usage:", - "print(capitalize_words('hello world')) # Output: 'Hello World'" - ], - "tags": ["python", "string", "capitalize", "utility"], - "author": "axorax" - }, - { - "title": "Find Longest Word", - "description": "Finds the longest word in a string.", - "code": [ - "def find_longest_word(s):", - " words = s.split()", - " return max(words, key=len) if words else ''", - "", - "# Usage:", - "print(find_longest_word('The quick brown fox')) # Output: 'quick'" - ], - "tags": ["python", "string", "longest-word", "utility"], - "author": "axorax" - }, - { - "title": "Remove Duplicate Characters", - "description": "Removes duplicate characters from a string while maintaining the order.", - "code": [ - "def remove_duplicate_chars(s):", - " seen = set()", - " return ''.join(char for char in s if not (char in seen or seen.add(char)))", - "", - "# Usage:", - "print(remove_duplicate_chars('programming')) # Output: 'progamin'" - ], - "tags": ["python", "string", "duplicates", "remove", "utility"], - "author": "axorax" - }, - { - "title": "Count Words", - "description": "Counts the number of words in a string.", - "code": [ - "def count_words(s):", - " return len(s.split())", - "", - "# Usage:", - "print(count_words('The quick brown fox')) # Output: 4" - ], - "tags": ["python", "string", "word-count", "utility"], - "author": "axorax" - }, - { - "title": "Replace Substring", - "description": "Replaces all occurrences of a substring in a string with another substring.", - "code": [ - "def replace_substring(s, old, new):", - " return s.replace(old, new)", - "", - "# Usage:", - "print(replace_substring('hello world', 'world', 'Python')) # Output: 'hello Python'" - ], - "tags": ["python", "string", "replace", "utility"], - "author": "axorax" - }, - { - "title": "Split Camel Case", - "description": "Splits a camel case string into separate words.", - "code": [ - "import re", - "", - "def split_camel_case(s):", - " return ' '.join(re.findall(r'[A-Z][a-z]*|[a-z]+', s))", - "", - "# Usage:", - "print(split_camel_case('camelCaseString')) # Output: 'camel Case String'" - ], - "tags": ["python", "string", "camel-case", "split", "utility"], - "author": "axorax" - }, - { - "title": "Count Character Frequency", - "description": "Counts the frequency of each character in a string.", - "code": [ - "from collections import Counter", - "", - "def char_frequency(s):", - " return dict(Counter(s))", - "", - "# Usage:", - "print(char_frequency('hello')) # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}" - ], - "tags": ["python", "string", "character-frequency", "utility"], - "author": "axorax" - }, - { - "title": "Remove Whitespace", - "description": "Removes all whitespace from a string.", - "code": [ - "def remove_whitespace(s):", - " return ''.join(s.split())", - "", - "# Usage:", - "print(remove_whitespace('hello world')) # Output: 'helloworld'" - ], - "tags": ["python", "string", "whitespace", "remove", "utility"], - "author": "axorax" - }, - { - "title": "Swap Case", - "description": "Swaps the case of all characters in a string.", - "code": [ - "def swap_case(s):", - " return s.swapcase()", - "", - "# Usage:", - "print(swap_case('Hello World')) # Output: 'hELLO wORLD'" - ], - "tags": ["python", "string", "case", "swap", "utility"], - "author": "axorax" - }, - { - "title": "Find All Substrings", - "description": "Finds all substrings of a given string.", - "code": [ - "def find_substrings(s):", - " substrings = []", - " for i in range(len(s)):", - " for j in range(i + 1, len(s) + 1):", - " substrings.append(s[i:j])", - " return substrings", - "", - "# Usage:", - "print(find_substrings('abc')) # Output: ['a', 'ab', 'abc', 'b', 'bc', 'c']" - ], - "tags": ["python", "string", "substring", "find", "utility"], - "author": "axorax" - }, - { - "title": "Convert Snake Case to Camel Case", - "description": "Converts a snake_case string to camelCase.", - "code": [ - "def snake_to_camel(s):", - " parts = s.split('_')", - " return parts[0] + ''.join(word.capitalize() for word in parts[1:])", - "", - "# Usage:", - "print(snake_to_camel('hello_world')) # Output: 'helloWorld'" - ], - "tags": ["python", "string", "snake-case", "camel-case", "convert", "utility"], - "author": "axorax" - }, - { - "title": "Remove Specific Characters", - "description": "Removes specific characters from a string.", - "code": [ - "def remove_chars(s, chars):", - " return ''.join(c for c in s if c not in chars)", - "", - "# Usage:", - "print(remove_chars('hello world', 'eo')) # Output: 'hll wrld'" - ], - "tags": ["python", "string", "remove", "characters", "utility"], - "author": "axorax" - }, - { - "title": "Find Unique Characters", - "description": "Finds all unique characters in a string.", - "code": [ - "def find_unique_chars(s):", - " return ''.join(sorted(set(s)))", - "", - "# Usage:", - "print(find_unique_chars('banana')) # Output: 'abn'" - ], - "tags": ["python", "string", "unique", "characters", "utility"], - "author": "axorax" - }, - { - "title": "Convert String to ASCII", - "description": "Converts a string into its ASCII representation.", - "code": [ - "def string_to_ascii(s):", - " return [ord(char) for char in s]", - "", - "# Usage:", - "print(string_to_ascii('hello')) # Output: [104, 101, 108, 108, 111]" - ], - "tags": ["python", "string", "ascii", "convert", "utility"], - "author": "axorax" - }, - { - "title": "Truncate String", - "description": "Truncates a string to a specified length and adds an ellipsis.", - "code": [ - "def truncate_string(s, length):", - " return s[:length] + '...' if len(s) > length else s", - "", - "# Usage:", - "print(truncate_string('This is a long string', 10)) # Output: 'This is a ...'" - ], - "tags": ["python", "string", "truncate", "utility"], - "author": "axorax" } ] }, @@ -411,135 +205,6 @@ ], "tags": ["python", "os", "filesystem", "file_search"], "author": "Jackeastern" - }, - { - "title": "Append to File", - "description": "Appends content to the end of a file.", - "code": [ - "def append_to_file(filepath, content):", - " with open(filepath, 'a') as file:", - " file.write(content + '\\n')", - "", - "# Usage:", - "append_to_file('example.txt', 'This is an appended line.')" - ], - "tags": ["python", "file", "append", "utility"], - "author": "axorax" - }, - { - "title": "Check if File Exists", - "description": "Checks if a file exists at the specified path.", - "code": [ - "import os", - "", - "def file_exists(filepath):", - " return os.path.isfile(filepath)", - "", - "# Usage:", - "print(file_exists('example.txt')) # Output: True or False" - ], - "tags": ["python", "file", "exists", "check", "utility"], - "author": "axorax" - }, - { - "title": "Delete File", - "description": "Deletes a file at the specified path.", - "code": [ - "import os", - "", - "def delete_file(filepath):", - " if os.path.exists(filepath):", - " os.remove(filepath)", - " print(f'File {filepath} deleted.')", - " else:", - " print(f'File {filepath} does not exist.')", - "", - "# Usage:", - "delete_file('example.txt')" - ], - "tags": ["python", "file", "delete", "utility"], - "author": "axorax" - }, - { - "title": "Copy File", - "description": "Copies a file from source to destination.", - "code": [ - "import shutil", - "", - "def copy_file(src, dest):", - " shutil.copy(src, dest)", - "", - "# Usage:", - "copy_file('example.txt', 'copy_of_example.txt')" - ], - "tags": ["python", "file", "copy", "utility"], - "author": "axorax" - }, - { - "title": "Rename File", - "description": "Renames a file from its current name to a new name.", - "code": [ - "import os", - "", - "def rename_file(old_name, new_name):", - " if os.path.exists(old_name):", - " os.rename(old_name, new_name)", - " print(f'File renamed from {old_name} to {new_name}')", - " else:", - " print(f'File {old_name} does not exist.')", - "", - "# Usage:", - "rename_file('example.txt', 'new_example.txt')" - ], - "tags": ["python", "file", "rename", "utility"], - "author": "axorax" - }, - { - "title": "List Files in Directory", - "description": "Lists all files in a specified directory.", - "code": [ - "import os", - "", - "def list_files(directory):", - " return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]", - "", - "# Usage:", - "files = list_files('/path/to/directory')", - "print(files)" - ], - "tags": ["python", "file", "list", "directory", "utility"], - "author": "axorax" - }, - { - "title": "Get File Extension", - "description": "Gets the extension of a file.", - "code": [ - "import os", - "", - "def get_file_extension(filepath):", - " return os.path.splitext(filepath)[1]", - "", - "# Usage:", - "print(get_file_extension('example.txt')) # Output: '.txt'" - ], - "tags": ["python", "file", "extension", "utility"], - "author": "axorax" - }, - { - "title": "Read File in Chunks", - "description": "Reads a file in chunks of a specified size.", - "code": [ - "def read_file_in_chunks(filepath, chunk_size):", - " with open(filepath, 'r') as file:", - " while chunk := file.read(chunk_size):", - " yield chunk", - "", - "# Usage:", - "for chunk in read_file_in_chunks('example.txt', 1024):", - " print(chunk)" - ], - "tags": ["python", "file", "read", "chunks", "utility"], - "author": "axorax" } ] }, @@ -578,131 +243,6 @@ ], "tags": ["python", "math", "prime", "check"], "author": "dostonnabotov" - }, - { - "title": "Generate Fibonacci Sequence", - "description": "Generates a Fibonacci sequence up to a given number of terms.", - "code": [ - "def generate_fibonacci(n):", - " sequence = [0, 1]", - " for _ in range(2, n):", - " sequence.append(sequence[-1] + sequence[-2])", - " return sequence[:n]", - "", - "# Usage:", - "print(generate_fibonacci(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]" - ], - "tags": ["python", "math", "fibonacci", "sequence"], - "author": "axorax" - }, - { - "title": "Check Perfect Square", - "description": "Checks if a number is a perfect square.", - "code": [ - "def is_perfect_square(n):", - " if n < 0:", - " return False", - " root = int(n**0.5)", - " return root * root == n", - "", - "# Usage:", - "print(is_perfect_square(16)) # Output: True", - "print(is_perfect_square(20)) # Output: False" - ], - "tags": ["python", "math", "perfect square", "check"], - "author": "axorax" - }, - { - "title": "Convert Binary to Decimal", - "description": "Converts a binary string to its decimal equivalent.", - "code": [ - "def binary_to_decimal(binary_str):", - " return int(binary_str, 2)", - "", - "# Usage:", - "print(binary_to_decimal('1010')) # Output: 10", - "print(binary_to_decimal('1101')) # Output: 13" - ], - "tags": ["python", "math", "binary", "decimal", "conversion"], - "author": "axorax" - }, - { - "title": "Generate Random Number", - "description": "Generates a random number within a given range.", - "code": [ - "import random", - "", - "def generate_random_number(start, end):", - " return random.randint(start, end)", - "", - "# Usage:", - "print(generate_random_number(1, 100)) # Output: A random number between 1 and 100" - ], - "tags": ["python", "math", "random", "utility"], - "author": "axorax" - }, - { - "title": "Calculate GCD (Greatest Common Divisor)", - "description": "Calculates the greatest common divisor (GCD) of two numbers using Euclid's algorithm.", - "code": [ - "def gcd(a, b):", - " while b:", - " a, b = b, a % b", - " return a", - "", - "# Usage:", - "print(gcd(56, 98)) # Output: 14", - "print(gcd(101, 10)) # Output: 1" - ], - "tags": ["python", "math", "gcd", "algorithm"], - "author": "axorax" - }, - { - "title": "Find LCM (Least Common Multiple)", - "description": "Calculates the least common multiple (LCM) of two numbers.", - "code": [ - "def lcm(a, b):", - " return abs(a * b) // gcd(a, b)", - "", - "# Usage:", - "print(lcm(12, 15)) # Output: 60", - "print(lcm(7, 5)) # Output: 35" - ], - "tags": ["python", "math", "lcm", "gcd", "utility"], - "author": "axorax" - }, - { - "title": "Solve Quadratic Equation", - "description": "Solves a quadratic equation ax^2 + bx + c = 0 and returns the roots.", - "code": [ - "import cmath", - "", - "def solve_quadratic(a, b, c):", - " discriminant = cmath.sqrt(b**2 - 4 * a * c)", - " root1 = (-b + discriminant) / (2 * a)", - " root2 = (-b - discriminant) / (2 * a)", - " return root1, root2", - "", - "# Usage:", - "print(solve_quadratic(1, -3, 2)) # Output: ((2+0j), (1+0j))", - "print(solve_quadratic(1, 2, 5)) # Output: ((-1+2j), (-1-2j))" - ], - "tags": ["python", "math", "quadratic", "equation", "solver"], - "author": "axorax" - }, - { - "title": "Calculate Compound Interest", - "description": "Calculates compound interest for a given principal amount, rate, and time period.", - "code": [ - "def compound_interest(principal, rate, time, n=1):", - " return principal * (1 + rate / n) ** (n * time)", - "", - "# Usage:", - "print(compound_interest(1000, 0.05, 5)) # Output: 1276.2815625000003", - "print(compound_interest(1000, 0.05, 5, 12)) # Output: 1283.68" - ], - "tags": ["python", "math", "compound interest", "finance"], - "author": "axorax" } ] }, @@ -786,131 +326,6 @@ ], "tags": ["python", "json", "file", "write"], "author": "e3nviction" - }, - { - "title": "Update JSON File", - "description": "Updates an existing JSON file with new data or modifies the existing values.", - "code": [ - "import json", - "", - "def update_json(filepath, new_data):", - " # Read the existing JSON data", - " with open(filepath, 'r') as file:", - " data = json.load(file)", - "", - " # Update the data with the new content", - " data.update(new_data)", - "", - " # Write the updated data back to the JSON file", - " with open(filepath, 'w') as file:", - " json.dump(data, file, indent=4)", - "", - "# Usage:", - "new_data = {'age': 31}", - "update_json('data.json', new_data)" - ], - "tags": ["python", "json", "update", "file"], - "author": "axorax" - }, - { - "title": "Merge Multiple JSON Files", - "description": "Merges multiple JSON files into one and writes the merged data into a new file.", - "code": [ - "import json", - "", - "def merge_json_files(filepaths, output_filepath):", - " merged_data = []", - "", - " # Read each JSON file and merge their data", - " for filepath in filepaths:", - " with open(filepath, 'r') as file:", - " data = json.load(file)", - " merged_data.extend(data)", - "", - " # Write the merged data into a new file", - " with open(output_filepath, 'w') as file:", - " json.dump(merged_data, file, indent=4)", - "", - "# Usage:", - "files_to_merge = ['file1.json', 'file2.json']", - "merge_json_files(files_to_merge, 'merged.json')" - ], - "tags": ["python", "json", "merge", "file"], - "author": "axorax" - }, - { - "title": "Filter JSON Data", - "description": "Filters a JSON object based on a condition and returns the filtered data.", - "code": [ - "import json", - "", - "def filter_json_data(filepath, condition):", - " with open(filepath, 'r') as file:", - " data = json.load(file)", - "", - " # Filter data based on the provided condition", - " filtered_data = [item for item in data if condition(item)]", - "", - " return filtered_data", - "", - "# Usage:", - "condition = lambda x: x['age'] > 25", - "filtered = filter_json_data('data.json', condition)", - "print(filtered)" - ], - "tags": ["python", "json", "filter", "data"], - "author": "axorax" - }, - { - "title": "Validate JSON Schema", - "description": "Validates a JSON object against a predefined schema.", - "code": [ - "import jsonschema", - "from jsonschema import validate", - "", - "def validate_json_schema(data, schema):", - " try:", - " validate(instance=data, schema=schema)", - " return True # Data is valid", - " except jsonschema.exceptions.ValidationError as err:", - " return False # Data is invalid", - "", - "# Usage:", - "schema = {", - " 'type': 'object',", - " 'properties': {", - " 'name': {'type': 'string'},", - " 'age': {'type': 'integer'}", - " },", - " 'required': ['name', 'age']", - "}", - "data = {'name': 'John', 'age': 30}", - "is_valid = validate_json_schema(data, schema)", - "print(is_valid) # Output: True" - ], - "tags": ["python", "json", "validation", "schema"], - "author": "axorax" - }, - { - "title": "Flatten Nested JSON", - "description": "Flattens a nested JSON object into a flat dictionary.", - "code": [ - "def flatten_json(nested_json, prefix=''):", - " flat_dict = {}", - " for key, value in nested_json.items():", - " if isinstance(value, dict):", - " flat_dict.update(flatten_json(value, prefix + key + '.'))", - " else:", - " flat_dict[prefix + key] = value", - " return flat_dict", - "", - "# Usage:", - "nested_json = {'name': 'John', 'address': {'city': 'New York', 'zip': '10001'}}", - "flattened = flatten_json(nested_json)", - "print(flattened) # Output: {'name': 'John', 'address.city': 'New York', 'address.zip': '10001'}" - ], - "tags": ["python", "json", "flatten", "nested"], - "author": "axorax" } ] },