diff --git a/public/data/python.json b/public/data/python.json index 427fa3a8..7b2d32c4 100644 --- a/public/data/python.json +++ b/public/data/python.json @@ -84,6 +84,186 @@ ], "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": "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": "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" } ] }, @@ -145,6 +325,74 @@ ], "tags": ["python", "list", "duplicates", "utility"], "author": "dostonnabotov" + }, + { + "title": "Find Duplicates in a List", + "description": "Identifies duplicate elements in a list.", + "code": [ + "def find_duplicates(lst):", + " seen = set()", + " duplicates = set()", + " for item in lst:", + " if item in seen:", + " duplicates.add(item)", + " else:", + " seen.add(item)", + " return list(duplicates)", + "", + "# Usage:", + "data = [1, 2, 3, 2, 4, 5, 1]", + "print(find_duplicates(data)) # Output: [1, 2]" + ], + "tags": ["python", "list", "duplicates", "utility"], + "author": "axorax" + }, + { + "title": "Partition List", + "description": "Partitions a list into sublists of a given size.", + "code": [ + "def partition_list(lst, size):", + " for i in range(0, len(lst), size):", + " yield lst[i:i + size]", + "", + "# Usage:", + "data = [1, 2, 3, 4, 5, 6, 7]", + "partitions = list(partition_list(data, 3))", + "print(partitions) # Output: [[1, 2, 3], [4, 5, 6], [7]]" + ], + "tags": ["python", "list", "partition", "utility"], + "author": "axorax" + }, + { + "title": "Find Intersection of Two Lists", + "description": "Finds the common elements between two lists.", + "code": [ + "def list_intersection(lst1, lst2):", + " return [item for item in lst1 if item in lst2]", + "", + "# Usage:", + "list_a = [1, 2, 3, 4]", + "list_b = [3, 4, 5, 6]", + "print(list_intersection(list_a, list_b)) # Output: [3, 4]" + ], + "tags": ["python", "list", "intersection", "utility"], + "author": "axorax" + }, + { + "title": "Find Maximum Difference in List", + "description": "Finds the maximum difference between any two elements in a list.", + "code": [ + "def max_difference(lst):", + " if not lst or len(lst) < 2:", + " return 0", + " return max(lst) - min(lst)", + "", + "# Usage:", + "data = [10, 3, 5, 20, 7]", + "print(max_difference(data)) # Output: 17" + ], + "tags": ["python", "list", "difference", "utility"], + "author": "axorax" } ] }, @@ -187,13 +435,17 @@ "import os", "", "def find_files(directory, file_type):", - " file_type = file_type.lower()", - " found_files = []", + " file_type = file_type.lower() # Convert file_type to lowercase", + " found_files = []", + "", + " for root, _, files in os.walk(directory):", + " for file in files:", + " file_ext = os.path.splitext(file)[1].lower()", + " if file_ext == file_type:", + " full_path = os.path.join(root, file)", + " found_files.append(full_path)", "", - " for entry in os.scandir(directory):", - " if entry.is_file() and entry.name.lower().endswith(file_type):", - " found_files.append(entry.name)", - " return found_files", + " return found_files", "", "# Example Usage:", "pdf_files = find_files('/path/to/your/directory', '.pdf')", @@ -201,6 +453,116 @@ ], "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": "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" } ] }, @@ -239,6 +601,84 @@ ], "tags": ["python", "math", "prime", "check"], "author": "dostonnabotov" + }, + { + "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": "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" } ] }, @@ -283,6 +723,22 @@ ], "tags": ["python", "random", "string", "utility"], "author": "dostonnabotov" + }, + { + "title": "Convert Bytes to Human-Readable Format", + "description": "Converts a size in bytes to a human-readable format.", + "code": [ + "def bytes_to_human_readable(num):", + " for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:", + " if num < 1024:", + " return f\"{num:.2f} {unit}\"", + " num /= 1024", + "", + "# Usage:", + "print(bytes_to_human_readable(123456789)) # Output: '117.74 MB'" + ], + "tags": ["python", "bytes", "format", "utility"], + "author": "axorax" } ] }, @@ -322,6 +778,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" } ] }, @@ -407,6 +988,72 @@ ], "tags": ["python", "error-handling", "division", "utility"], "author": "e3nviction" + }, + { + "title": "Retry Function Execution on Exception", + "description": "Retries a function execution a specified number of times if it raises an exception.", + "code": [ + "import time", + "", + "def retry(func, retries=3, delay=1):", + " for attempt in range(retries):", + " try:", + " return func()", + " except Exception as e:", + " print(f\"Attempt {attempt + 1} failed: {e}\")", + " time.sleep(delay)", + " raise Exception(\"All retry attempts failed\")", + "", + "# Usage:", + "def unstable_function():", + " raise ValueError(\"Simulated failure\")", + "", + "# Retry 3 times with 2 seconds delay:", + "try:", + " retry(unstable_function, retries=3, delay=2)", + "except Exception as e:", + " print(e) # Output: All retry attempts failed" + ], + "tags": ["python", "error-handling", "retry", "utility"], + "author": "axorax" + }, + { + "title": "Validate Input with Exception Handling", + "description": "Validates user input and handles invalid input gracefully.", + "code": [ + "def validate_positive_integer(input_value):", + " try:", + " value = int(input_value)", + " if value < 0:", + " raise ValueError(\"The number must be positive\")", + " return value", + " except ValueError as e:", + " return f\"Invalid input: {e}\"", + "", + "# Usage:", + "print(validate_positive_integer('10')) # Output: 10", + "print(validate_positive_integer('-5')) # Output: Invalid input: The number must be positive", + "print(validate_positive_integer('abc')) # Output: Invalid input: invalid literal for int() with base 10: 'abc'" + ], + "tags": ["python", "error-handling", "validation", "utility"], + "author": "axorax" + }, + { + "title": "Handle File Not Found Error", + "description": "Attempts to open a file and handles the case where the file does not exist.", + "code": [ + "def read_file_safe(filepath):", + " try:", + " with open(filepath, 'r') as file:", + " return file.read()", + " except FileNotFoundError:", + " return \"File not found!\"", + "", + "# Usage:", + "print(read_file_safe('nonexistent.txt')) # Output: 'File not found!'" + ], + "tags": ["python", "error-handling", "file", "utility"], + "author": "axorax" } ] }, @@ -445,6 +1092,96 @@ ], "tags": ["python", "datetime", "utility"], "author": "e3nviction" + }, + { + "title": "Generate Date Range List", + "description": "Generates a list of dates between two given dates.", + "code": [ + "from datetime import datetime, timedelta", + "", + "def generate_date_range(start_date, end_date):", + " if start_date > end_date:", + " raise ValueError(\"start_date must be before end_date\")", + "", + " current_date = start_date", + " date_list = []", + " while current_date <= end_date:", + " date_list.append(current_date)", + " current_date += timedelta(days=1)", + "", + " return date_list", + "", + "# Usage:", + "start = datetime(2023, 1, 1)", + "end = datetime(2023, 1, 5)", + "dates = generate_date_range(start, end)", + "for d in dates:", + " print(d.strftime('%Y-%m-%d'))", + "# Output: '2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'" + ], + "tags": ["python", "datetime", "range", "utility"], + "author": "axorax" + }, + { + "title": "Determine Day of the Week", + "description": "Calculates the day of the week for a given date.", + "code": [ + "from datetime import datetime", + "", + "def get_day_of_week(date):", + " days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']", + " try:", + " return days[date.weekday()]", + " except IndexError:", + " raise ValueError(\"Invalid date\")", + "", + "# Usage:", + "date = datetime(2023, 1, 1)", + "day = get_day_of_week(date)", + "print(day) # Output: 'Sunday'" + ], + "tags": ["python", "datetime", "weekday", "utility"], + "author": "axorax" + }, + { + "title": "Check if Date is a Weekend", + "description": "Checks whether a given date falls on a weekend.", + "code": [ + "from datetime import datetime", + "", + "def is_weekend(date):", + " try:", + " return date.weekday() >= 5 # Saturday = 5, Sunday = 6", + " except AttributeError:", + " raise TypeError(\"Input must be a datetime object\")", + "", + "# Usage:", + "date = datetime(2023, 1, 1)", + "weekend = is_weekend(date)", + "print(weekend) # Output: True (Sunday)" + ], + "tags": ["python", "datetime", "weekend", "utility"], + "author": "axorax" + }, + { + "title": "Get Number of Days in a Month", + "description": "Determines the number of days in a specific month and year.", + "code": [ + "from calendar import monthrange", + "from datetime import datetime", + "", + "def get_days_in_month(year, month):", + " try:", + " return monthrange(year, month)[1]", + " except ValueError as e:", + " raise ValueError(f\"Invalid month or year: {e}\")", + "", + "# Usage:", + "days = get_days_in_month(2023, 2)", + "print(days) # Output: 28 (for non-leap year February)" + ], + "tags": ["python", "datetime", "calendar", "utility"], + "author": "axorax" } ] }