instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add docstrings to improve code quality | #!/usr/bin/env python3
import argparse
import sys
import subprocess
import json
def check_yt_dlp():
try:
subprocess.run(["yt-dlp", "--version"], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
print("yt-dlp not found. Installing...")
subproc... | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+YouTube Video Downloader
+Downloads videos from YouTube with customizable quality and format options.
+"""
import argparse
import sys
@@ -7,6 +11,7 @@
def check_yt_dlp():
+ """Check if yt-dlp is installed, install if not."""
try:
subprocess.r... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/video-downloader/scripts/download_video.py |
Add clean documentation to messy code | #!/usr/bin/env python3
from PIL import Image, ImageDraw, ImageFont
from typing import Optional
# Typography scale - proportional sizing system
TYPOGRAPHY_SCALE = {
'h1': 60, # Large headers
'h2': 48, # Medium headers
'h3': 36, # Small headers
'title': 50, # Title text
'body': 28,... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Typography System - Professional text rendering with outlines, shadows, and effects.
+
+This module provides high-quality text rendering that looks crisp and professional
+in GIFs, with outlines for readability and effects for visual impact.
+"""
from PIL import ... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/typography.py |
Add docstrings to existing functions | #!/usr/bin/env python3
import html
import random
import shutil
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from defusedxml import minidom
from ooxml.scripts.pack import pack_document
from ooxml.scripts.validation.docx import DOCXSchemaValidator
from ooxml.scripts.validation.redlin... | --- +++ @@ -1,4 +1,30 @@ #!/usr/bin/env python3
+"""
+Library for working with Word documents: comments, tracked changes, and editing.
+
+Usage:
+ from skills.docx.scripts.document import Document
+
+ # Initialize
+ doc = Document('workspace/unpacked')
+ doc = Document('workspace/unpacked', author="John Doe... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/docx/scripts/document.py |
Add docstrings to improve collaboration | #!/usr/bin/env python3
import sys
from pathlib import Path
import math
sys.path.append(str(Path(__file__).parent.parent))
from PIL import Image, ImageFilter
from core.gif_builder import GIFBuilder
from core.frame_composer import create_blank_frame, draw_emoji_enhanced
from core.easing import interpolate
def create... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Zoom Animation - Scale objects dramatically for emphasis.
+
+Creates zoom in, zoom out, and dramatic scaling effects.
+"""
import sys
from pathlib import Path
@@ -25,6 +30,25 @@ frame_height: int = 480,
bg_color: tuple[int, int, int] = (255, 255, 255)
)... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/zoom.py |
Write clean docstrings for readability | #!/usr/bin/env python3
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from PIL import Image
import numpy as np
from core.gif_builder import GIFBuilder
from core.frame_composer import create_blank_frame, draw_emoji_enhanced, draw_circle
from core.easing import interpolate
def... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Morph Animation - Transform between different emojis or shapes.
+
+Creates smooth transitions and transformations.
+"""
import sys
from pathlib import Path
@@ -24,6 +29,24 @@ frame_height: int = 480,
bg_color: tuple[int, int, int] = (255, 255, 255)
) ->... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/morph.py |
Improve documentation using docstrings | #!/usr/bin/env python3
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from PIL import Image
from core.gif_builder import GIFBuilder
from core.frame_composer import create_blank_frame, draw_emoji_enhanced
from core.easing import interpolate
def create_slide_animation(
obj... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Slide Animation - Slide elements in from edges with overshoot/bounce.
+
+Creates smooth entrance and exit animations.
+"""
import sys
from pathlib import Path
@@ -24,6 +29,25 @@ frame_height: int = 480,
bg_color: tuple[int, int, int] = (255, 255, 255)
)... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/slide.py |
Improve documentation using docstrings | #!/usr/bin/env python3
import argparse
import shutil
import subprocess
import sys
import tempfile
import defusedxml.minidom
import zipfile
from pathlib import Path
def main():
parser = argparse.ArgumentParser(description="Pack a directory into an Office file")
parser.add_argument("input_directory", help="Unp... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Tool to pack a directory into a .docx, .pptx, or .xlsx file with XML formatting undone.
+
+Example usage:
+ python pack.py <input_directory> <office_file> [--force]
+"""
import argparse
import shutil
@@ -37,6 +43,16 @@
def pack_document(input_dir, output_... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/ooxml/scripts/pack.py |
Add minimal docstrings for each function | #!/usr/bin/env python3
import sys
from pathlib import Path
SKILL_TEMPLATE = """---
name: {skill_name}
description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.]
---
# {skill_title}
#... | --- +++ @@ -1,4 +1,15 @@ #!/usr/bin/env python3
+"""
+Skill Initializer - Creates a new skill from template
+
+Usage:
+ init_skill.py <skill-name> --path <path>
+
+Examples:
+ init_skill.py my-new-skill --path skills/public
+ init_skill.py my-api-helper --path skills/private
+ init_skill.py custom-skill --p... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/skill-creator/scripts/init_skill.py |
Create structured documentation for my script | #!/usr/bin/env python3
import sys
import zipfile
from pathlib import Path
from quick_validate import validate_skill
def package_skill(skill_path, output_dir=None):
skill_path = Path(skill_path).resolve()
# Validate skill folder exists
if not skill_path.exists():
print(f"❌ Error: Skill folder not... | --- +++ @@ -1,4 +1,14 @@ #!/usr/bin/env python3
+"""
+Skill Packager - Creates a distributable zip file of a skill folder
+
+Usage:
+ python utils/package_skill.py <path/to/skill-folder> [output-directory]
+
+Example:
+ python utils/package_skill.py skills/public/my-skill
+ python utils/package_skill.py skills... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/skill-creator/scripts/package_skill.py |
Generate docstrings for this script | #!/usr/bin/env python3
import sys
from pathlib import Path
import math
sys.path.append(str(Path(__file__).parent.parent))
from PIL import Image, ImageOps, ImageDraw
import numpy as np
def apply_kaleidoscope(frame: Image.Image, segments: int = 8,
center: tuple[int, int] | None = None) -> Imag... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Kaleidoscope Effect - Create mirror/rotation effects.
+
+Apply kaleidoscope effects to frames or objects for psychedelic visuals.
+"""
import sys
from pathlib import Path
@@ -12,6 +17,17 @@
def apply_kaleidoscope(frame: Image.Image, segments: int = 8,
... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/kaleidoscope.py |
Add docstrings for utility scripts | #!/usr/bin/env python3
from pathlib import Path
def check_slack_size(gif_path: str | Path, is_emoji: bool = True) -> tuple[bool, dict]:
gif_path = Path(gif_path)
if not gif_path.exists():
return False, {'error': f'File not found: {gif_path}'}
size_bytes = gif_path.stat().st_size
size_kb = s... | --- +++ @@ -1,9 +1,24 @@ #!/usr/bin/env python3
+"""
+Validators - Check if GIFs meet Slack's requirements.
+
+These validators help ensure your GIFs meet Slack's size and dimension constraints.
+"""
from pathlib import Path
def check_slack_size(gif_path: str | Path, is_emoji: bool = True) -> tuple[bool, dict]:... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/validators.py |
Add docstrings to improve collaboration | #!/usr/bin/env python3
import json
import sys
import subprocess
import os
import platform
from pathlib import Path
from openpyxl import load_workbook
def setup_libreoffice_macro():
if platform.system() == 'Darwin':
macro_dir = os.path.expanduser('~/Library/Application Support/LibreOffice/4/user/basic/Sta... | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+Excel Formula Recalculation Script
+Recalculates all formulas in an Excel file using LibreOffice
+"""
import json
import sys
@@ -10,6 +14,7 @@
def setup_libreoffice_macro():
+ """Setup LibreOffice macro for recalculation if not already configured"""
i... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/xlsx/recalc.py |
Add verbose docstrings with examples | #!/usr/bin/env python3
import sys
from pathlib import Path
import math
sys.path.append(str(Path(__file__).parent.parent))
from PIL import Image
from core.gif_builder import GIFBuilder
from core.frame_composer import create_blank_frame, draw_emoji_enhanced
from core.easing import interpolate
def create_flip_animati... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Flip Animation - 3D-style card flip and rotation effects.
+
+Creates horizontal and vertical flips with perspective.
+"""
import sys
from pathlib import Path
@@ -24,6 +29,24 @@ frame_height: int = 480,
bg_color: tuple[int, int, int] = (255, 255, 255)
) ... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/flip.py |
Write docstrings for utility functions |
import re
from pathlib import Path
import lxml.etree
class BaseSchemaValidator:
# Elements whose 'id' attributes must be unique within their file
# Format: element_name -> (attribute_name, scope)
# scope can be 'file' (unique within file) or 'global' (unique across all files)
UNIQUE_ID_REQUIREMENTS... | --- +++ @@ -1,3 +1,6 @@+"""
+Base validator with common validation logic for document files.
+"""
import re
from pathlib import Path
@@ -6,6 +9,7 @@
class BaseSchemaValidator:
+ """Base validator with common validation logic for document files."""
# Elements whose 'id' attributes must be unique within... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/docx/ooxml/scripts/validation/base.py |
Include argument descriptions in docstrings | #!/usr/bin/env python3
import html
from pathlib import Path
from typing import Optional, Union
import defusedxml.minidom
import defusedxml.sax
class XMLEditor:
def __init__(self, xml_path):
self.xml_path = Path(xml_path)
if not self.xml_path.exists():
raise ValueError(f"XML file not... | --- +++ @@ -1,4 +1,34 @@ #!/usr/bin/env python3
+"""
+Utilities for editing OOXML documents.
+
+This module provides XMLEditor, a tool for manipulating XML files with support for
+line-number-based node finding and DOM manipulation. Each element is automatically
+annotated with its original line and column position dur... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/docx/scripts/utilities.py |
Please document this code using docstrings | #!/usr/bin/env python3
import sys
from pathlib import Path
import math
import random
sys.path.append(str(Path(__file__).parent.parent))
from PIL import Image, ImageDraw
import numpy as np
from core.gif_builder import GIFBuilder
from core.frame_composer import create_blank_frame, draw_emoji_enhanced
from core.visual_... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Explode Animation - Break objects into pieces that fly outward.
+
+Creates explosion, shatter, and particle burst effects.
+"""
import sys
from pathlib import Path
@@ -27,6 +32,24 @@ frame_height: int = 480,
bg_color: tuple[int, int, int] = (255, 255, 25... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/explode.py |
Generate missing documentation strings | #!/usr/bin/env python3
import math
def linear(t: float) -> float:
return t
def ease_in_quad(t: float) -> float:
return t * t
def ease_out_quad(t: float) -> float:
return t * (2 - t)
def ease_in_out_quad(t: float) -> float:
if t < 0.5:
return 2 * t * t
return -1 + (4 - 2 * t) * t
d... | --- +++ @@ -1,45 +1,60 @@ #!/usr/bin/env python3
+"""
+Easing Functions - Timing functions for smooth animations.
+
+Provides various easing functions for natural motion and timing.
+All functions take a value t (0.0 to 1.0) and return eased value (0.0 to 1.0).
+"""
import math
def linear(t: float) -> float:
+ ... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/easing.py |
Add inline docstrings for readability |
import re
from .base import BaseSchemaValidator
class PPTXSchemaValidator(BaseSchemaValidator):
# PowerPoint presentation namespace
PRESENTATIONML_NAMESPACE = (
"http://schemas.openxmlformats.org/presentationml/2006/main"
)
# PowerPoint-specific element to relationship type mappings
EL... | --- +++ @@ -1,3 +1,6 @@+"""
+Validator for PowerPoint presentation XML files against XSD schemas.
+"""
import re
@@ -5,6 +8,7 @@
class PPTXSchemaValidator(BaseSchemaValidator):
+ """Validator for PowerPoint presentation XML files against XSD schemas."""
# PowerPoint presentation namespace
PRESEN... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/ooxml/scripts/validation/pptx.py |
Write docstrings describing each step | import json
import sys
from pypdf import PdfReader, PdfWriter
from pypdf.annotations import FreeText
# Fills a PDF by adding text annotations defined in `fields.json`. See forms.md.
def transform_coordinates(bbox, image_width, image_height, pdf_width, pdf_height):
# Image coordinates: origin at top-left, y inc... | --- +++ @@ -9,6 +9,7 @@
def transform_coordinates(bbox, image_width, image_height, pdf_width, pdf_height):
+ """Transform bounding box from image coordinates to PDF coordinates"""
# Image coordinates: origin at top-left, y increases downward
# PDF coordinates: origin at bottom-left, y increases upward
... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pdf/scripts/fill_pdf_form_with_annotations.py |
Add clean documentation to messy code | #!/usr/bin/env python3
from PIL import Image, ImageDraw, ImageFilter
import numpy as np
import math
import random
from typing import Optional
class Particle:
def __init__(self, x: float, y: float, vx: float, vy: float,
lifetime: float, color: tuple[int, int, int],
size: int = 3... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Visual Effects - Particles, motion blur, impacts, and other effects for GIFs.
+
+This module provides high-impact visual effects that make animations feel
+professional and dynamic while keeping file sizes reasonable.
+"""
from PIL import Image, ImageDraw, ImageF... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/visual_effects.py |
Generate documentation strings for clarity | #!/usr/bin/env python3
from typing import Optional
import colorsys
# Professional color palettes - hand-picked for GIF compression and visual appeal
VIBRANT = {
'primary': (255, 68, 68), # Bright red
'secondary': (255, 168, 0), # Bright orange
'accent': (0, 168, 255), # Bright blue
'... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Color Palettes - Professional, harmonious color schemes for GIFs.
+
+Using consistent, well-designed color palettes makes GIFs look professional
+and polished instead of random and amateurish.
+"""
from typing import Optional
import colorsys
@@ -100,10 +106,30 @... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/color_palettes.py |
Please document this code using docstrings | #!/usr/bin/env python3
import argparse
import shutil
import sys
from copy import deepcopy
from pathlib import Path
import six
from pptx import Presentation
def main():
parser = argparse.ArgumentParser(
description="Rearrange PowerPoint slides based on a sequence of indices.",
formatter_class=arg... | --- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3
+"""
+Rearrange PowerPoint slides based on a sequence of indices.
+
+Usage:
+ python rearrange.py template.pptx output.pptx 0,34,34,50,52
+
+This will create output.pptx using slides from template.pptx in the specified order.
+Slides can be repeated (e.g., 34 appears t... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/scripts/rearrange.py |
Create documentation for each function signature | #!/usr/bin/env python3
import argparse
import json
import platform
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
from PIL import Image, ImageDraw, ImageFont
from pptx import Presentation
from pptx.enum.text import PP_ALIGN
from pptx.sh... | --- +++ @@ -1,4 +1,26 @@ #!/usr/bin/env python3
+"""
+Extract structured text content from PowerPoint presentations.
+
+This module provides functionality to:
+- Extract all text content from PowerPoint shapes
+- Preserve paragraph formatting (alignment, bullets, fonts, spacing)
+- Handle nested GroupShapes recursively... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/scripts/inventory.py |
Write reusable docstrings | #!/usr/bin/env python3
import sys
from pathlib import Path
import math
sys.path.append(str(Path(__file__).parent.parent))
from PIL import Image
from core.gif_builder import GIFBuilder
from core.frame_composer import create_blank_frame, draw_emoji_enhanced
from core.easing import interpolate
def create_wiggle_anima... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Wiggle Animation - Smooth, organic wobbling and jiggling motions.
+
+Creates playful, elastic movements that are smoother than shake.
+"""
import sys
from pathlib import Path
@@ -24,6 +29,24 @@ frame_height: int = 480,
bg_color: tuple[int, int, int] = (2... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/wiggle.py |
Generate docstrings for each module | #!/usr/bin/env python3
import sys
from pathlib import Path
# Add parent directory to path
sys.path.append(str(Path(__file__).parent.parent))
from core.gif_builder import GIFBuilder
from core.frame_composer import create_blank_frame, draw_circle, draw_emoji
from core.easing import ease_out_bounce, interpolate
def c... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Bounce Animation Template - Creates bouncing motion for objects.
+
+Use this to make objects bounce up and down or horizontally with realistic physics.
+"""
import sys
from pathlib import Path
@@ -22,6 +27,23 @@ frame_height: int = 480,
bg_color: tuple[i... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/bounce.py |
Add docstrings to incomplete code | #!/usr/bin/env python3
import sys
from pathlib import Path
import math
sys.path.append(str(Path(__file__).parent.parent))
from core.gif_builder import GIFBuilder
from core.frame_composer import create_blank_frame, draw_circle, draw_emoji_enhanced
from core.easing import interpolate, calculate_arc_motion
def create... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Move Animation - Move objects along paths with various motion types.
+
+Provides flexible movement primitives for objects along linear, arc, or custom paths.
+"""
import sys
from pathlib import Path
@@ -24,6 +29,25 @@ frame_height: int = 480,
bg_color: t... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/move.py |
Write docstrings describing each step | #!/usr/bin/env python3
import argparse
import subprocess
import sys
import tempfile
from pathlib import Path
from inventory import extract_text_inventory
from PIL import Image, ImageDraw, ImageFont
from pptx import Presentation
# Constants
THUMBNAIL_WIDTH = 300 # Fixed thumbnail width in pixels
CONVERSION_DPI = 100... | --- +++ @@ -1,4 +1,44 @@ #!/usr/bin/env python3
+"""
+Create thumbnail grids from PowerPoint presentation slides.
+
+Creates a grid layout of slide thumbnails with configurable columns (max 6).
+Each grid contains up to cols×(cols+1) images. For presentations with more
+slides, multiple numbered grid files are created ... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/scripts/thumbnail.py |
Write docstrings that follow conventions | #!/usr/bin/env python3
import sys
from pathlib import Path
import math
sys.path.append(str(Path(__file__).parent.parent))
from PIL import Image
from core.gif_builder import GIFBuilder
from core.frame_composer import create_blank_frame, draw_emoji_enhanced, draw_circle
from core.easing import interpolate
def create... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Spin Animation - Rotate objects continuously or with variation.
+
+Creates spinning, rotating, and wobbling effects.
+"""
import sys
from pathlib import Path
@@ -24,6 +29,24 @@ frame_height: int = 480,
bg_color: tuple[int, int, int] = (255, 255, 255)
) ... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/spin.py |
Write docstrings describing each step | #!/usr/bin/env python3
from pathlib import Path
from typing import Optional
import imageio.v3 as imageio
from PIL import Image
import numpy as np
class GIFBuilder:
def __init__(self, width: int = 480, height: int = 480, fps: int = 15):
self.width = width
self.height = height
self.fps = f... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+GIF Builder - Core module for assembling frames into GIFs optimized for Slack.
+
+This module provides the main interface for creating GIFs from programmatically
+generated frames, with automatic optimization for Slack's requirements.
+"""
from pathlib import Pat... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/gif_builder.py |
Add return value explanations in docstrings | #!/usr/bin/env python3
import sys
from pathlib import Path
import math
sys.path.append(str(Path(__file__).parent.parent))
from PIL import Image
from core.gif_builder import GIFBuilder
from core.frame_composer import create_blank_frame, draw_emoji_enhanced, draw_circle
from core.easing import interpolate
def create... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Pulse Animation - Scale objects rhythmically for emphasis.
+
+Creates pulsing, heartbeat, and throbbing effects.
+"""
import sys
from pathlib import Path
@@ -24,6 +29,24 @@ frame_height: int = 480,
bg_color: tuple[int, int, int] = (255, 255, 255)
) -> l... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/pulse.py |
Write docstrings for algorithm functions | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import json
import os
from datetime import datetime
from pathlib import Path
from core import search, DATA_DIR
# ============ CONFIGURATION ============
REASONING_FILE = "ui-reasoning.csv"
SEARCH_CONFIG = {
"product": {"max_results": 1},
"style": {"m... | --- +++ @@ -1,5 +1,17 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+Design System Generator - Aggregates search results and applies reasoning
+to generate comprehensive design system recommendations.
+
+Usage:
+ from design_system import generate_design_system
+ result = generate_design_system("SaaS da... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/cli/assets/scripts/design_system.py |
Generate docstrings with parameter types | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import json
import sys
from pathlib import Path
# Add parent directory for imports
sys.path.insert(0, str(Path(__file__).parent))
from core import search, search_all, get_cip_brief, CSV_CONFIG
def format_results(results, domain):
if not results:
... | --- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+CIP Design Search CLI - Search corporate identity design guidelines
+"""
import argparse
import json
@@ -12,6 +15,7 @@
def format_results(results, domain):
+ """Format search results for display"""
if not results:
ret... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/cip/search.py |
Annotate my code with docstrings | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import re
from pathlib import Path
from math import log
from collections import defaultdict
# ============ CONFIGURATION ============
DATA_DIR = Path(__file__).parent.parent / "data"
MAX_RESULTS = 3
CSV_CONFIG = {
"style": {
"file": "styles.csv",
... | --- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+UI/UX Pro Max Core - BM25 search engine for UI/UX style guides
+"""
import csv
import re
@@ -84,6 +87,7 @@
# ============ BM25 IMPLEMENTATION ============
class BM25:
+ """BM25 ranking algorithm for text search"""
def __init_... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/src/ui-ux-pro-max/scripts/core.py |
Generate consistent documentation across files | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import sys
import io
from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack
from design_system import generate_design_system, persist_design_system
# Force UTF-8 for stdout/stderr to handle emojis on Windows (cp1252 default)
if s... | --- +++ @@ -1,100 +1,114 @@-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-
-import argparse
-import sys
-import io
-from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack
-from design_system import generate_design_system, persist_design_system
-
-# Force UTF-8 for stdout/stderr to handle em... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/src/ui-ux-pro-max/scripts/search.py |
Create docstrings for all classes and functions | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import re
from pathlib import Path
from math import log
from collections import defaultdict
# ============ CONFIGURATION ============
DATA_DIR = Path(__file__).parent.parent / "data"
MAX_RESULTS = 3
CSV_CONFIG = {
"strategy": {
"file": "slide-stra... | --- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+Slide Search Core - BM25 search engine for slide design databases
+"""
import csv
import re
@@ -39,6 +42,7 @@
# ============ BM25 IMPLEMENTATION ============
class BM25:
+ """BM25 ranking algorithm for text search"""
def __in... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design-system/scripts/slide_search_core.py |
Add docstrings following best practices | #!/usr/bin/env python3
import csv, os, json
BASE = os.path.dirname(os.path.abspath(__file__))
# ─── Color derivation helpers ────────────────────────────────────────────────
def h2r(h):
h = h.lstrip("#")
return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
def r2h(r, g, b):
return f"#{max(0,min(255,int(r))... | --- +++ @@ -1,4 +1,12 @@ #!/usr/bin/env python3
+"""
+Sync colors.csv and ui-reasoning.csv with the updated products.csv (161 entries).
+- Remove deleted product types
+- Rename mismatched entries
+- Add new entries for missing product types
+- Keep colors.csv aligned 1:1 with products.csv
+- Renumber everything
+"""
... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/src/ui-ux-pro-max/data/_sync_all.py |
Improve documentation using docstrings | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import json
import os
import re
import sys
import time
from pathlib import Path
from datetime import datetime
def load_env():
env_paths = [
Path(__file__).parent.parent.parent / ".env",
Path.home() / ".claude" / "skills" / ".env",
... | --- +++ @@ -1,5 +1,18 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+Icon Generation Script using Gemini 3.1 Pro Preview API
+Generates SVG icons via text generation (SVG is XML text format)
+
+Model: gemini-3.1-pro-preview - best thinking, token efficiency, factual consistency
+
+Usage:
+ python generate.... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/icon/generate.py |
Auto-generate documentation strings for this file | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import os
import sys
import time
from pathlib import Path
from datetime import datetime
# Load environment variables
def load_env():
env_paths = [
Path(__file__).parent.parent.parent / ".env",
Path.home() / ".claude" / "skills" / ".env... | --- +++ @@ -1,5 +1,22 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+Logo Generation Script using Gemini Nano Banana API
+Uses Gemini 2.5 Flash Image and Gemini 3 Pro Image Preview models
+
+Models:
+- Nano Banana (default): gemini-2.5-flash-image - fast, high-volume, low-latency
+- Nano Banana Pro (--pro): g... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/logo/generate.py |
Fill in missing docstrings in my code | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
from core import CSV_CONFIG, MAX_RESULTS, search, search_all
def format_output(result):
if "error" in result:
return f"Error: {result['error']}"
output = []
output.append(f"## Logo Design Search Results")
output.append(f"**Domain... | --- +++ @@ -1,11 +1,19 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+Logo Design Search - CLI for searching logo design guidelines
+Usage: python search.py "<query>" [--domain <domain>] [--max-results 3]
+ python search.py "<query>" --design-brief [-p "Brand Name"]
+
+Domains: style, color, industry
+"... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/logo/search.py |
Expand my code with proper documentation strings | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import json
import argparse
from slide_search_core import (
search, search_all, AVAILABLE_DOMAINS,
search_with_context, get_layout_for_goal, get_typography_for_slide,
get_color_for_emotion, get_background_config
)
def format_result(result, domain)... | --- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+Slide Search CLI - Search slide design databases for strategies, layouts, copy, and charts
+"""
import sys
import json
@@ -12,6 +15,7 @@
def format_result(result, domain):
+ """Format a single search result for display"""
outp... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design-system/scripts/search-slides.py |
Create documentation for each function signature | #!/usr/bin/env python3
import argparse
import json
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional
class TailwindConfigGenerator:
def __init__(
self,
typescript: bool = True,
framework: str = "react",
output_path: Optional[Path] = None,
):
... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Tailwind CSS Configuration Generator
+
+Generate tailwind.config.js/ts with custom theme configuration.
+Supports colors, fonts, spacing, breakpoints, and plugin recommendations.
+"""
import argparse
import json
@@ -8,6 +14,7 @@
class TailwindConfigGenerator... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/ui-styling/scripts/tailwind_config_gen.py |
Provide docstrings following PEP 257 | #!/usr/bin/env python3
import re
import json
import sys
from pathlib import Path
from typing import Dict, List, Tuple, Optional
# Project root relative to this script
PROJECT_ROOT = Path(__file__).parent.parent.parent.parent.parent
TOKENS_JSON_PATH = PROJECT_ROOT / 'assets' / 'design-tokens.json'
TOKENS_CSS_PATH = PR... | --- +++ @@ -1,4 +1,16 @@ #!/usr/bin/env python3
+"""
+HTML Design Token Validator
+Ensures all HTML assets (slides, infographics, etc.) use design tokens.
+Source of truth: assets/design-tokens.css
+
+Usage:
+ python html-token-validator.py # Validate all HTML assets
+ python html-token-validator.p... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design-system/scripts/html-token-validator.py |
Write docstrings describing each step | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import re
from pathlib import Path
from math import log
from collections import defaultdict
# ============ CONFIGURATION ============
DATA_DIR = Path(__file__).parent.parent / "data"
MAX_RESULTS = 3
CSV_CONFIG = {
"style": {
"file": "styles.csv",
... | --- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+UI/UX Pro Max Core - BM25 search engine for UI/UX style guides
+"""
import csv
import re
@@ -79,6 +82,7 @@
# ============ BM25 IMPLEMENTATION ============
class BM25:
+ """BM25 ranking algorithm for text search"""
def __init_... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/cli/assets/scripts/core.py |
Provide clean and structured docstrings | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import json
import os
import sys
import base64
from pathlib import Path
from datetime import datetime
# Add parent directory for imports
sys.path.insert(0, str(Path(__file__).parent))
from core import search, get_cip_brief
# Deliverable descriptions for ... | --- +++ @@ -1,5 +1,11 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+CIP HTML Presentation Renderer
+
+Generates a professional HTML presentation from CIP mockup images
+with detailed descriptions, concepts, and brand guidelines.
+"""
import argparse
import json
@@ -91,6 +97,7 @@
def get_image_base64(... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/cip/render-html.py |
Add docstrings for internal functions | #!/usr/bin/env python3
import sys
import subprocess
from pathlib import Path
SCRIPT_DIR = Path(__file__).parent
UNIFIED_VALIDATOR = SCRIPT_DIR / 'html-token-validator.py'
def main():
args = sys.argv[1:]
# If no files specified, default to slides type
if not args or all(arg.startswith('-') for arg in ar... | --- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3
+"""
+Slide Token Validator (Legacy Wrapper)
+Now delegates to html-token-validator.py for unified HTML validation.
+
+For new usage, prefer:
+ python html-token-validator.py --type slides
+ python html-token-validator.py --type infographics
+ python html-token-validat... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design-system/scripts/slide-token-validator.py |
Generate consistent docstrings | #!/usr/bin/env python3
import json
import csv
import re
import sys
from pathlib import Path
# Project root relative to this script
PROJECT_ROOT = Path(__file__).parent.parent.parent.parent.parent
TOKENS_PATH = PROJECT_ROOT / 'assets' / 'design-tokens.json'
BACKGROUNDS_CSV = Path(__file__).parent.parent / 'data' / 'sl... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Background Image Fetcher
+Fetches real images from Pexels for slide backgrounds.
+Uses web scraping (no API key required) or WebFetch tool integration.
+"""
import json
import csv
@@ -13,6 +18,7 @@
def resolve_token_reference(ref: str, tokens: dict) -> str:
+... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design-system/scripts/fetch-background.py |
Generate NumPy-style docstrings | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import re
from pathlib import Path
from math import log
from collections import defaultdict
# ============ CONFIGURATION ============
DATA_DIR = Path(__file__).parent.parent.parent / "data" / "cip"
MAX_RESULTS = 3
CSV_CONFIG = {
"deliverable": {
"... | --- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+CIP Design Core - BM25 search engine for Corporate Identity Program design guidelines
+"""
import csv
import re
@@ -37,6 +40,7 @@
# ============ BM25 IMPLEMENTATION ============
class BM25:
+ """BM25 ranking algorithm for text searc... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/cip/core.py |
Add docstrings for production code | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import json
import os
import sys
from pathlib import Path
from datetime import datetime
# Add parent directory for imports
sys.path.insert(0, str(Path(__file__).parent))
from core import search, get_cip_brief
# Model options
MODELS = {
"flash": "gemi... | --- +++ @@ -1,5 +1,18 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+CIP Design Generator - Generate corporate identity mockups using Gemini Nano Banana
+
+Uses Gemini's native image generation (Nano Banana Flash/Pro) for high-quality mockups.
+Supports text-and-image-to-image generation for using actual bran... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/cip/generate.py |
Add inline docstrings for readability | #!/usr/bin/env python3
import argparse
import json
import subprocess
import sys
from pathlib import Path
from typing import List, Optional
class ShadcnInstaller:
def __init__(self, project_root: Optional[Path] = None, dry_run: bool = False):
self.project_root = project_root or Path.cwd()
self.dr... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+shadcn/ui Component Installer
+
+Add shadcn/ui components to project with automatic dependency handling.
+Wraps shadcn CLI for programmatic component installation.
+"""
import argparse
import json
@@ -9,16 +15,36 @@
class ShadcnInstaller:
+ """Handle shad... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/ui-styling/scripts/shadcn_add.py |
Generate descriptive docstrings automatically | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import json
from pathlib import Path
from datetime import datetime
# Paths
SCRIPT_DIR = Path(__file__).parent
DATA_DIR = SCRIPT_DIR.parent / "data"
TOKENS_CSS = Path(__file__).resolve().parents[4] / "assets" / "design-tokens.css"
TOKENS_JSON = Path(__file... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+Slide Generator - Generates HTML slides using design tokens
+ALL styles MUST use CSS variables from design-tokens.css
+NO hardcoded colors, fonts, or spacing allowed
+"""
import argparse
import json
@@ -404,6 +409,7 @@ # ============ SLI... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design-system/scripts/generate-slide.py |
Add docstrings for internal functions | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import re
from pathlib import Path
from math import log
from collections import defaultdict
# ============ CONFIGURATION ============
DATA_DIR = Path(__file__).parent.parent.parent / "data" / "logo"
MAX_RESULTS = 3
CSV_CONFIG = {
"style": {
"file"... | --- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+Logo Design Core - BM25 search engine for logo design guidelines
+"""
import csv
import re
@@ -32,6 +35,7 @@
# ============ BM25 IMPLEMENTATION ============
class BM25:
+ """BM25 ranking algorithm for text search"""
def __ini... | https://raw.githubusercontent.com/nextlevelbuilder/ui-ux-pro-max-skill/HEAD/.claude/skills/design/scripts/logo/core.py |
Provide clean and structured docstrings | # if someone hits a 404, redirect them to another location
def send_http_302_temporary_redirect(cli, new_path):
cli.reply(b"redirecting...", 302, headers={"Location": new_path})
def send_http_301_permanent_redirect(cli, new_path):
cli.reply(b"redirecting...", 301, headers={"Location": new_path})
def send_... | --- +++ @@ -2,18 +2,40 @@
def send_http_302_temporary_redirect(cli, new_path):
+ """
+ replies with an HTTP 302, which is a temporary redirect;
+ "new_path" can be any of the following:
+ - "http://a.com/" would redirect to another website,
+ - "/foo/bar" would redirect to /foo/bar on the same se... | https://raw.githubusercontent.com/9001/copyparty/HEAD/bin/handlers/redirect.py |
Generate descriptive docstrings automatically | # coding: utf-8
from __future__ import print_function, unicode_literals
import socket
import time
import ipaddress
from ipaddress import (
IPv4Address,
IPv4Network,
IPv6Address,
IPv6Network,
ip_address,
ip_network,
)
from .__init__ import MACOS, TYPE_CHECKING
from .util import IP6_LL, IP64_LL... | --- +++ @@ -32,6 +32,7 @@
class MC_Sck(object):
+ """there is one socket for each server ip"""
def __init__(
self,
@@ -66,6 +67,7 @@ port: int,
vinit: bool,
) -> None:
+ """disable ipv%d by setting mc_grp_%d empty"""
self.hub = hub
self.Srv = Srv
... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/multicast.py |
Document functions with clear intent | # coding: utf-8
from __future__ import print_function, unicode_literals
import ctypes
import platform
import socket
import sys
import ipaddress
if True: # pylint: disable=using-constant-test
from typing import Callable, List, Optional, Union
PY2 = sys.version_info < (3,)
if not PY2:
U: Callable[[str], str... | --- +++ @@ -21,6 +21,15 @@
class Adapter(object):
+ """
+ Represents a network interface device controller (NIC), such as a
+ network card. An adapter can have multiple IPs.
+
+ On Linux aliasing (multiple IPs per physical NIC) is implemented
+ by creating 'virtual' adapters, each represented by an i... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/stolen/ifaddr/_shared.py |
Help me comply with documentation standards | # coding: utf-8
from __future__ import print_function, unicode_literals
import hashlib
import math
import os
import re
import socket
import sys
import threading
import time
import queue
from .__init__ import ANYWIN, CORES, EXE, MACOS, PY2, TYPE_CHECKING, EnvParams, unicode
try:
MNFE = ModuleNotFoundError
except... | --- +++ @@ -102,6 +102,10 @@
class HttpSrv(object):
+ """
+ handles incoming connections using HttpConn to process http,
+ relying on MpSrv for performance (HttpSrv is just plain threads)
+ """
def __init__(self, broker: "BrokerCli", nid: Optional[int]) -> None:
self.broker = broker
@@ -... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/httpsrv.py |
Document functions with detailed explanations | # coding: utf-8
from __future__ import print_function, unicode_literals
import errno
import re
import select
import socket
import time
from .__init__ import TYPE_CHECKING
from .multicast import MC_Sck, MCast
from .util import CachedSet, formatdate, html_escape, min_ex
if TYPE_CHECKING:
from .broker_util import B... | --- +++ @@ -30,6 +30,7 @@
class SSDPr(object):
+ """generates http responses for httpcli"""
def __init__(self, broker: "BrokerCli") -> None:
self.broker = broker
@@ -87,6 +88,7 @@
class SSDPd(MCast):
+ """communicates with ssdp clients over multicast"""
def __init__(self, hub: "SvcH... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/ssdp.py |
Generate NumPy-style docstrings | # coding: utf-8
from __future__ import print_function, unicode_literals
import re
import stat
import tarfile
from queue import Queue
from .authsrv import AuthSrv
from .bos import bos
from .sutil import StreamArc, errdesc
from .util import Daemon, fsenc, min_ex
if True: # pylint: disable=using-constant-test
fro... | --- +++ @@ -19,6 +19,7 @@
class QFile(object): # inherit io.StringIO for painful typing
+ """file-like object which buffers writes into a queue"""
def __init__(self) -> None:
self.q: Queue[Optional[bytes]] = Queue(64)
@@ -39,6 +40,7 @@
class StreamTar(StreamArc):
+ """construct in-memory ... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/star.py |
Add docstrings with type hints explained | #!/usr/bin/env python3
# coding: utf-8
from __future__ import print_function, unicode_literals
"""copyparty: http file sharing hub (py2/py3)"""
__author__ = "ed <copyparty@ocv.me>"
__copyright__ = 2019
__license__ = "MIT"
__url__ = "https://github.com/9001/copyparty/"
import argparse
import base64
import locale
impor... | --- +++ @@ -110,6 +110,10 @@ super(RiceFormatter, self).__init__(*args, **kwargs)
def _get_help_string(self, action: argparse.Action) -> str:
+ """
+ same as ArgumentDefaultsHelpFormatter(HelpFormatter)
+ except the help += [...] line now has colors
+ """
fmt = "\033[... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/__main__.py |
Help me write clear docstrings | # coding: utf-8
from __future__ import print_function, unicode_literals
import threading
import time
import traceback
import queue
from .__init__ import CORES, TYPE_CHECKING
from .broker_mpw import MpWorker
from .broker_util import ExceptionalQueue, NotExQueue, try_exec
from .util import Daemon, mp
if TYPE_CHECKING... | --- +++ @@ -33,6 +33,7 @@
class BrokerMp(object):
+ """external api; manages MpWorkers"""
def __init__(self, hub: "SvcHub") -> None:
self.hub = hub
@@ -85,6 +86,7 @@ proc.q_pend.put((0, "reload_sessions", []))
def collector(self, proc: MProcess) -> None:
+ """receive mes... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/broker_mp.py |
Document this code for team use | # coding: utf-8
from __future__ import print_function, unicode_literals
import argparse
from queue import Queue
from .__init__ import TYPE_CHECKING
from .authsrv import AuthSrv
from .util import HMaccas, Pebkac
if True: # pylint: disable=using-constant-test
from typing import Any, Optional, Union
from .ut... | --- +++ @@ -33,6 +33,9 @@
class NotExQueue(object):
+ """
+ BrokerThr uses this instead of ExceptionalQueue; 7x faster
+ """
def __init__(self, rv: Any) -> None:
self.rv = rv
@@ -42,6 +45,10 @@
class BrokerCli(object):
+ """
+ helps mypy understand httpsrv.broker but still fails a... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/broker_util.py |
Create docstrings for each class method | #!/usr/bin/env python3
from __future__ import print_function, unicode_literals
S_VERSION = "2.19"
S_BUILD_DT = "2026-01-18"
"""
u2c.py: upload to copyparty
2021, ed <irc.rizon.net>, MIT-Licensed
https://github.com/9001/copyparty/blob/hovudstraum/bin/u2c.py
- dependencies: no
- supports python 2.6, 2.7, and 3.3 throu... | --- +++ @@ -245,6 +245,7 @@
class File(object):
+ """an up2k upload task; represents a single file"""
def __init__(self, top, rel, size, lmod):
self.top = top # type: bytes
@@ -277,6 +278,7 @@
class FileSlice(object):
+ """file-like object providing a fixed window into a file"""
de... | https://raw.githubusercontent.com/9001/copyparty/HEAD/bin/u2c.py |
Help me add docstrings to my project | # coding: utf-8
from __future__ import print_function, unicode_literals
import argparse
import base64
import hashlib
import json
import os
import re
import stat
import sys
import threading
import time
from datetime import datetime
from .__init__ import ANYWIN, MACOS, PY2, TYPE_CHECKING, WINDOWS, E
from .bos import bo... | --- +++ @@ -401,6 +401,7 @@
class VFS(object):
+ """single level in the virtual fs"""
def __init__(
self,
@@ -499,6 +500,7 @@ v.get_all_vols(vols, nodes, aps, vps)
def add(self, src: str, dst: str, dst0: str) -> "VFS":
+ """get existing, or add new path to the vfs"""
... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/authsrv.py |
Create docstrings for each class method | # coding: utf-8
# This code is released under the Python license and the BSD 2-clause license
import codecs
import platform
import sys
PY3 = sys.version_info > (3,)
WINDOWS = platform.system() == "Windows"
FS_ERRORS = "surrogateescape"
if True: # pylint: disable=using-constant-test
from typing import Any
if... | --- +++ @@ -1,5 +1,14 @@ # coding: utf-8
+"""
+This is Victor Stinner's pure-Python implementation of PEP 383: the "surrogateescape" error
+handler of Python 3.
+
+Scissored from the python-future module to avoid 4.4MB of additional dependencies:
+https://github.com/PythonCharmers/python-future/blob/e12549c42ed3a38ec... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/stolen/surrogateescape.py |
Generate consistent documentation across files | # coding: utf-8
from __future__ import print_function, unicode_literals
import argparse
import atexit
import errno
import json
import logging
import os
import re
import shlex
import signal
import socket
import string
import sys
import threading
import time
from datetime import datetime
# from inspect import currentfr... | --- +++ @@ -110,6 +110,15 @@
class SvcHub(object):
+ """
+ Hosts all services which cannot be parallelized due to reliance on monolithic resources.
+ Creates a Broker which does most of the heavy stuff; hosted services can use this to perform work:
+ hub.broker.<say|ask>(destination, args_list).
+
+... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/svchub.py |
Add docstrings to improve code quality | # coding: utf-8
from __future__ import print_function, unicode_literals
import calendar
import stat
import time
from .authsrv import AuthSrv
from .bos import bos
from .sutil import StreamArc, errdesc
from .util import VPTL_WIN, min_ex, sanitize_to, spack, sunpack, yieldfile, zlib
if True: # pylint: disable=using-co... | --- +++ @@ -62,6 +62,11 @@ icrc32: int,
pre_crc: bool,
) -> bytes:
+ """
+ does regular file headers
+ and the central directory meme if h_pos is set
+ (h_pos = absolute position of the regular header)
+ """
# appnote 4.5 / zip 3.0 (2008) / unzip 6.0 (2009) says to add z64
# extinfo... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/szip.py |
Improve my code by adding docstrings | # coding: utf-8
from __future__ import print_function, unicode_literals
import errno
import hashlib
import json
import math
import os
import re
import shutil
import stat
import subprocess as sp
import sys
import tempfile
import threading
import time
import traceback
from copy import deepcopy
from queue import Queue
... | --- +++ @@ -126,6 +126,7 @@
class Mpqe(object):
+ """pending files to tag-scan"""
def __init__(
self,
@@ -274,6 +275,7 @@ self.reloading = False
def _reload(self, rescan_all_vols: bool) -> None:
+ """mutex(main) me"""
self.log("reload #{} scheduled".format(self.gid ... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/up2k.py |
Add structured docstrings to improve clarity | #!/usr/bin/env python3
# coding: latin-1
from __future__ import print_function, unicode_literals
import re, os, sys, time, shutil, signal, tarfile, hashlib, platform, tempfile, traceback
import subprocess as sp
"""
to edit this file, use HxD or "vim -b"
(there is compressed stuff at the end)
run me with python 2.7... | --- +++ @@ -51,6 +51,7 @@
def testptn1():
+ """test: creates a test-pattern for encode()"""
import struct
buf = b""
@@ -88,6 +89,7 @@
def testchk(cdata):
+ """test: verifies that `data` yields testptn"""
import struct
cbuf = b""
@@ -141,6 +143,7 @@
def encode(data, size, cksum,... | https://raw.githubusercontent.com/9001/copyparty/HEAD/scripts/sfx.py |
Write proper docstrings for these functions | # coding: utf-8
from __future__ import print_function, unicode_literals
import argparse
import base64
import binascii
import codecs
import errno
import hashlib
import hmac
import json
import logging
import math
import mimetypes
import os
import platform
import re
import select
import shutil
import signal
import socket... | --- +++ @@ -925,6 +925,10 @@ strict_cidr=False,
defer_mutex=False,
) -> None:
+ """
+ ips: list of plain ipv4/ipv6 IPs, not cidr
+ cidrs: list of cidr-notation IPs (ip/prefix)
+ """
# fails multiprocessing; defer assignment
self.mutex: Optional[threa... | https://raw.githubusercontent.com/9001/copyparty/HEAD/copyparty/util.py |
Write docstrings describing each step | from typing import Union
class Node:
pass
class A(Node):
pass
class B(Node):
pass
class C(A, B):
pass
class Visitor:
def visit(self, node: Union[A, C, B], *args, **kwargs) -> None:
meth = None
for cls in node.__class__.__mro__:
meth_name = "visit_" + cls.__name_... | --- +++ @@ -1,3 +1,19 @@+"""
+http://peter-hoffmann.com/2010/extrinsic-visitor-pattern-python-inheritance.html
+
+*TL;DR
+Separates an algorithm from an object structure on which it operates.
+
+An interesting recipe could be found in
+Brian Jones, David Beazley "Python Cookbook" (2013):
+- "8.21. Implementing the Visi... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/visitor.py |
Add verbose docstrings with examples |
class UnsupportedMessageType(BaseException):
pass
class UnsupportedState(BaseException):
pass
class UnsupportedTransition(BaseException):
pass
class HierachicalStateMachine:
def __init__(self):
self._active_state = Active(self) # Unit.Inservice.Active()
self._standby_state = Sta... | --- +++ @@ -1,3 +1,12 @@+"""
+Implementation of the HSM (hierarchical state machine) or
+NFSM (nested finite state machine) C++ example from
+http://www.eventhelix.com/RealtimeMantra/HierarchicalStateMachine.htm#.VwqLVEL950w
+in Python
+
+- single source 'message type' for state transition changes
+- message type consi... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/other/hsm/hsm.py |
Add docstrings that explain inputs and outputs |
import random
from typing import Type
class Pet:
def __init__(self, name: str) -> None:
self.name = name
def speak(self) -> None:
raise NotImplementedError
def __str__(self) -> str:
raise NotImplementedError
class Dog(Pet):
def speak(self) -> None:
print("woof")
... | --- +++ @@ -1,3 +1,34 @@+"""
+*What is this pattern about?
+
+In Java and other languages, the Abstract Factory Pattern serves to provide an interface for
+creating related/dependent objects without need to specify their
+actual class.
+
+The idea is to abstract the creation of objects depending on business
+logic, pla... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/abstract_factory.py |
Add docstrings to improve collaboration |
from __future__ import annotations
from typing import Any
class Prototype:
def __init__(self, value: str = "default", **attrs: Any) -> None:
self.value = value
self.__dict__.update(attrs)
def clone(self, **attrs: Any) -> Prototype:
# Python in Practice, Mark Summerfield
# co... | --- +++ @@ -1,3 +1,25 @@+"""
+*What is this pattern about?
+This patterns aims to reduce the number of classes required by an
+application. Instead of relying on subclasses it creates objects by
+copying a prototypical instance at run-time.
+
+This is useful as it makes it easier to derive new kinds of objects,
+when i... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/prototype.py |
Document this script properly |
from typing import Dict
class Borg:
_shared_state: Dict[str, str] = {}
def __init__(self) -> None:
self.__dict__ = self._shared_state
class YourBorg(Borg):
def __init__(self, state: str = None) -> None:
super().__init__()
if state:
self.state = state
else:
... | --- +++ @@ -1,3 +1,37 @@+"""
+*What is this pattern about?
+The Borg pattern (also known as the Monostate pattern) is a way to
+implement singleton behavior, but instead of having only one instance
+of a class, there are multiple instances that share the same state. In
+other words, the focus is on sharing state instea... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/borg.py |
Add professional docstrings to my codebase |
from __future__ import annotations
class Provider:
def __init__(self) -> None:
self.msg_queue = []
self.subscribers = {}
def notify(self, msg: str) -> None:
self.msg_queue.append(msg)
def subscribe(self, msg: str, subscriber: Subscriber) -> None:
self.subscribers.setdefa... | --- +++ @@ -1,3 +1,8 @@+"""
+Reference:
+http://www.slideshare.net/ishraqabd/publish-subscribe-model-overview-13368808
+Author: https://github.com/HanWenfang
+"""
from __future__ import annotations
@@ -47,9 +52,44 @@
def main():
+ """
+ >>> message_center = Provider()
+
+ >>> fftv = Publisher(message_... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/publish_subscribe.py |
Improve my code by adding docstrings |
import datetime
from typing import Callable
class ConstructorInjection:
def __init__(self, time_provider: Callable) -> None:
self.time_provider = time_provider
def get_current_time_as_html_fragment(self) -> str:
current_time = self.time_provider()
current_time_as_html_fragment = '<sp... | --- +++ @@ -1,3 +1,27 @@+"""
+Dependency Injection (DI) is a technique whereby one object supplies the dependencies (services)
+to another object (client).
+It allows to decouple objects: no need to change client code simply because an object it depends on
+needs to be changed to a different one. (Open/Closed principle... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/dependency_injection.py |
Add concise docstrings to each method |
from typing import Callable, TypeVar, Any, Dict
T = TypeVar("T")
class Dog:
def __init__(self) -> None:
self.name = "Dog"
def bark(self) -> str:
return "woof!"
class Cat:
def __init__(self) -> None:
self.name = "Cat"
def meow(self) -> str:
return "meow!"
class H... | --- +++ @@ -1,3 +1,32 @@+"""
+*What is this pattern about?
+The Adapter pattern provides a different interface for a class. We can
+think about it as a cable adapter that allows you to charge a phone
+somewhere that has outlets in a different shape. Following this idea,
+the Adapter pattern is useful to integrate class... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/adapter.py |
Can you add docstrings to this Python file? | from typing import Union
# ConcreteImplementor 1/2
class DrawingAPI1:
def draw_circle(self, x: int, y: int, radius: float) -> None:
print(f"API1.circle at {x}:{y} radius {radius}")
# ConcreteImplementor 2/2
class DrawingAPI2:
def draw_circle(self, x: int, y: int, radius: float) -> None:
prin... | --- +++ @@ -1,3 +1,10 @@+"""
+*References:
+http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Bridge_Pattern#Python
+
+*TL;DR
+Decouples an abstraction from its implementation.
+"""
from typing import Union
@@ -33,9 +40,18 @@
def main():
+ """
+ >>> shapes = (CircleShape(1, 2, 3, DrawingAPI1(... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/bridge.py |
Write reusable docstrings |
from __future__ import annotations
class State:
def scan(self) -> None:
self.pos += 1
if self.pos == len(self.stations):
self.pos = 0
print(f"Scanning... Station is {self.stations[self.pos]} {self.name}")
class AmState(State):
def __init__(self, radio: Radio) -> None:
... | --- +++ @@ -1,10 +1,21 @@+"""
+Implementation of the state pattern
+
+http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
+
+*TL;DR
+Implements state as a derived class of the state pattern interface.
+Implements state transitions by invoking methods from the pattern's superclass.
+"""
from __futu... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/state.py |
Add documentation for all methods |
from abc import ABC, abstractmethod
from typing import Optional, Tuple
class Handler(ABC):
def __init__(self, successor: Optional["Handler"] = None):
self.successor = successor
def handle(self, request: int) -> None:
res = self.check_range(request)
if not res and self.successor:
... | --- +++ @@ -1,3 +1,26 @@+"""
+*What is this pattern about?
+
+The Chain of responsibility is an object oriented version of the
+`if ... elif ... elif ... else ...` idiom, with the
+benefit that the condition–action blocks can be dynamically rearranged
+and reconfigured at runtime.
+
+This pattern aims to decouple the s... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/chain_of_responsibility.py |
Write docstrings including parameters and return values |
from abc import ABC, abstractmethod
import random
class AbstractExpert(ABC):
@abstractmethod
def __init__(self, blackboard) -> None:
self.blackboard = blackboard
@property
@abstractmethod
def is_eager_to_contribute(self) -> int:
raise NotImplementedError("Must provide implementa... | --- +++ @@ -1,9 +1,20 @@+"""
+@author: Eugene Duboviy <eugene.dubovoy@gmail.com> | github.com/duboviy
+
+In Blackboard pattern several specialised sub-systems (knowledge sources)
+assemble their knowledge to build a possibly partial or approximate solution.
+In this way, the sub-systems work together to solve the probl... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/other/blackboard.py |
Add detailed docstrings explaining each function |
from copy import copy, deepcopy
from typing import Any, Callable, List, Type
def memento(obj: Any, deep: bool = False) -> Callable:
state = deepcopy(obj.__dict__) if deep else copy(obj.__dict__)
def restore() -> None:
obj.__dict__.clear()
obj.__dict__.update(state)
return restore
clas... | --- +++ @@ -1,3 +1,9 @@+"""
+http://code.activestate.com/recipes/413838-memento-closure/
+
+*TL;DR
+Provides the ability to restore an object to its previous state.
+"""
from copy import copy, deepcopy
from typing import Any, Callable, List, Type
@@ -14,6 +20,10 @@
class Transaction:
+ """A transaction guard... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/memento.py |
Help me comply with documentation standards |
from __future__ import annotations
from typing import Any, Callable
class Delegator:
def __init__(self, delegate: Delegate) -> None:
self.delegate = delegate
def __getattr__(self, name: str) -> Any | Callable:
attr = getattr(self.delegate, name)
if not callable(attr):
... | --- +++ @@ -1,3 +1,10 @@+"""
+Reference: https://en.wikipedia.org/wiki/Delegation_pattern
+Author: https://github.com/IuryAlves
+
+*TL;DR
+Allows object composition to achieve the same code reuse as inheritance.
+"""
from __future__ import annotations
@@ -5,6 +12,23 @@
class Delegator:
+ """
+ >>> delega... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/fundamental/delegation_pattern.py |
Add docstrings to clarify complex logic |
from typing import List, Union
class HideFileCommand:
def __init__(self) -> None:
# an array of files hidden, to undo them as needed
self._hidden_files: List[str] = []
def execute(self, filename: str) -> None:
print(f"hiding {filename}")
self._hidden_files.append(filename)
... | --- +++ @@ -1,8 +1,32 @@+"""
+Command pattern decouples the object invoking a job from the one who knows
+how to do it. As mentioned in the GoF book, a good example is in menu items.
+You have a menu that has lots of items. Each item is responsible for doing a
+special thing and you want your menu item just call the ex... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/command.py |
Generate consistent docstrings |
from abc import abstractmethod
from typing import Union
class Specification:
def and_specification(self, candidate):
raise NotImplementedError()
def or_specification(self, candidate):
raise NotImplementedError()
def not_specification(self):
raise NotImplementedError()
@abst... | --- +++ @@ -1,3 +1,9 @@+"""
+@author: Gordeev Andrey <gordeev.and.and@gmail.com>
+
+*TL;DR
+Provides recombination business logic by chaining together using boolean logic.
+"""
from abc import abstractmethod
from typing import Union
@@ -81,9 +87,24 @@
def main():
+ """
+ >>> andrey = User()
+ >>> ivan ... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/specification.py |
Create docstrings for all classes and functions |
from abc import ABC, abstractmethod
from typing import List
class Graphic(ABC):
@abstractmethod
def render(self) -> None:
raise NotImplementedError("You should implement this!")
class CompositeGraphic(Graphic):
def __init__(self) -> None:
self.graphics: List[Graphic] = []
def rende... | --- +++ @@ -1,3 +1,30 @@+"""
+*What is this pattern about?
+The composite pattern describes a group of objects that is treated the
+same way as a single instance of the same type of object. The intent of
+a composite is to "compose" objects into tree structures to represent
+part-whole hierarchies. Implementing the com... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/composite.py |
Document classes and their methods |
def count_to(count: int):
numbers = ["one", "two", "three", "four", "five"]
yield from numbers[:count]
# Test the generator
def count_to_two() -> None:
return count_to(2)
def count_to_five() -> None:
return count_to(5)
def main():
if __name__ == "__main__":
import doctest
doctest.test... | --- +++ @@ -1,6 +1,14 @@+"""
+http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
+Implementation of the iterator pattern with a generator
+
+*TL;DR
+Traverses a container and accesses the container's elements.
+"""
def count_to(count: int):
+ """Counts by word numbers, up to a maximum of fiv... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/iterator.py |
Write docstrings for algorithm functions |
# observer.py
from __future__ import annotations
from typing import List
class Observer:
def update(self, subject: Subject) -> None:
pass
class Subject:
_observers: List[Observer]
def __init__(self) -> None:
self._observers = []
def attach(self, observer: Observer) -> None:
... | --- +++ @@ -1,3 +1,13 @@+"""
+http://code.activestate.com/recipes/131499-observer-pattern/
+
+*TL;DR
+Maintains a list of dependents and notifies them of any state changes.
+
+*Examples in Python ecosystem:
+Django Signals: https://docs.djangoproject.com/en/3.1/topics/signals/
+Flask Signals: https://flask.palletsproje... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/observer.py |
Create simple docstrings for beginners |
class TextTag:
def __init__(self, text: str) -> None:
self._text = text
def render(self) -> str:
return self._text
class BoldWrapper(TextTag):
def __init__(self, wrapped: TextTag) -> None:
self._wrapped = wrapped
def render(self) -> str:
return f"<b>{self._wrapped... | --- +++ @@ -1,6 +1,32 @@+"""
+*What is this pattern about?
+The Decorator pattern is used to dynamically add a new feature to an
+object without changing its implementation. It differs from
+inheritance because the new feature is added only to that particular
+object, not to the entire subclass.
+
+*What does this exam... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/decorator.py |
Write docstrings for backend logic |
from typing import Dict, KeysView, Optional, Union
class Data:
products = {
"milk": {"price": 1.50, "quantity": 10},
"eggs": {"price": 0.20, "quantity": 100},
"cheese": {"price": 2.00, "quantity": 10},
}
def __get__(self, obj, klas):
print("(Fetching from Data Store)")
... | --- +++ @@ -1,8 +1,13 @@+"""
+*TL;DR
+Separates presentation, application processing, and data management functions.
+"""
from typing import Dict, KeysView, Optional, Union
class Data:
+ """Data Store Class"""
products = {
"milk": {"price": 1.50, "quantity": 10},
@@ -16,6 +21,7 @@
class B... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/3-tier.py |
Generate docstrings for script automation |
import weakref
class Card:
# Could be a simple dict.
# With WeakValueDictionary garbage collection can reclaim the object
# when there are no other references to it.
_pool: weakref.WeakValueDictionary = weakref.WeakValueDictionary()
def __new__(cls, value: str, suit: str):
# If the obje... | --- +++ @@ -1,8 +1,35 @@+"""
+*What is this pattern about?
+This pattern aims to minimise the number of objects that are needed by
+a program at run-time. A Flyweight is an object shared by multiple
+contexts, and is indistinguishable from an object that is not shared.
+
+The state of a Flyweight should not be affected... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/flyweight.py |
Add docstrings for better understanding |
from __future__ import annotations
from typing import Any
class MobileView:
def show_index_page(self) -> None:
print("Displaying mobile index page")
class TabletView:
def show_index_page(self) -> None:
print("Displaying tablet index page")
class Dispatcher:
def __init__(self) -> None... | --- +++ @@ -1,3 +1,9 @@+"""
+@author: Gordeev Andrey <gordeev.and.and@gmail.com>
+
+*TL;DR
+Provides a centralized entry point that controls and manages request handling.
+"""
from __future__ import annotations
@@ -20,6 +26,12 @@ self.tablet_view = TabletView()
def dispatch(self, request: Request) -... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/front_controller.py |
Generate consistent documentation across files |
import functools
from typing import Callable, Type
class lazy_property:
def __init__(self, function: Callable) -> None:
self.function = function
functools.update_wrapper(self, function)
def __get__(self, obj: "Person", type_: Type["Person"]) -> str:
if obj is None:
return... | --- +++ @@ -1,3 +1,23 @@+"""
+Lazily-evaluated property pattern in Python.
+
+https://en.wikipedia.org/wiki/Lazy_evaluation
+
+*References:
+bottle
+https://github.com/bottlepy/bottle/blob/cafc15419cbb4a6cb748e6ecdccf92893bb25ce5/bottle.py#L270
+django
+https://github.com/django/django/blob/ffd18732f3ee9e6f0374aff9ccf3... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/lazy_evaluation.py |
Generate consistent docstrings |
from __future__ import annotations
class NumberWords:
_WORD_MAP = (
"one",
"two",
"three",
"four",
"five",
)
def __init__(self, start: int, stop: int) -> None:
self.start = start
self.stop = stop
def __iter__(self) -> NumberWords: # this mak... | --- +++ @@ -1,8 +1,15 @@+"""
+Implementation of the iterator pattern using the iterator protocol from Python
+
+*TL;DR
+Traverses a container and accesses the container's elements.
+"""
from __future__ import annotations
class NumberWords:
+ """Counts by word numbers, up to a maximum of five"""
_WORD_... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/iterator_alt.py |
Add return value explanations in docstrings |
from typing import Union
class Subject:
def do_the_job(self, user: str) -> None:
raise NotImplementedError()
class RealSubject(Subject):
def do_the_job(self, user: str) -> None:
print(f"I am doing the job for {user}")
class Proxy(Subject):
def __init__(self) -> None:
self._r... | --- +++ @@ -1,14 +1,42 @@+"""
+*What is this pattern about?
+Proxy is used in places where you want to add functionality to a class without
+changing its interface. The main class is called `Real Subject`. A client should
+use the proxy or the real subject without any code change, so both must have the
+same interface.... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/proxy.py |
Include argument descriptions in docstrings |
# Abstract Building
class Building:
def __init__(self) -> None:
self.build_floor()
self.build_size()
def build_floor(self):
raise NotImplementedError
def build_size(self):
raise NotImplementedError
def __repr__(self) -> str:
return "Floor: {0.floor} | Size: ... | --- +++ @@ -1,3 +1,32 @@+"""
+What is this pattern about?
+It decouples the creation of a complex object and its representation,
+so that the same process can be reused to build objects from the same
+family.
+This is useful when you must separate the specification of an object
+from its actual representation (generall... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/builder.py |
Add docstrings including usage examples |
from __future__ import annotations
from typing import Callable
class DiscountStrategyValidator: # Descriptor class for check perform
@staticmethod
def validate(obj: Order, value: Callable) -> bool:
try:
if obj.price - value(obj) < 0:
raise ValueError(
... | --- +++ @@ -1,3 +1,11 @@+"""
+*What is this pattern about?
+Define a family of algorithms, encapsulate each one, and make them interchangeable.
+Strategy lets the algorithm vary independently from clients that use it.
+
+*TL;DR
+Enables selecting an algorithm at runtime.
+"""
from __future__ import annotations
@@ ... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/strategy.py |
Create docstrings for reusable components |
from typing import Dict, Protocol, Type
class Localizer(Protocol):
def localize(self, msg: str) -> str: ...
class GreekLocalizer:
def __init__(self) -> None:
self.translations = {"dog": "σκύλος", "cat": "γάτα"}
def localize(self, msg: str) -> str:
return self.translations.get(msg, msg... | --- +++ @@ -1,3 +1,26 @@+"""*What is this pattern about?
+A Factory is an object for creating other objects.
+
+*What does this example do?
+The code shows a way to localize words in two languages: English and
+Greek. "get_localizer" is the factory function that constructs a
+localizer depending on the language chosen.... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/creational/factory.py |
Create docstrings for each class method |
from abc import ABC, abstractmethod
from typing import Dict, List, Union, Any
from inspect import signature
from sys import argv
class Model(ABC):
@abstractmethod
def __iter__(self) -> Any:
pass
@abstractmethod
def get(self, item: str) -> dict:
pass
@property
@abstractmetho... | --- +++ @@ -1,3 +1,7 @@+"""
+*TL;DR
+Separates data in GUIs from the ways it is presented, and accepted.
+"""
from abc import ABC, abstractmethod
from typing import Dict, List, Union, Any
@@ -6,6 +10,7 @@
class Model(ABC):
+ """The Model is the data layer of the application."""
@abstractmethod
de... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/mvc.py |
Create docstrings for reusable components |
import math
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
class Circle:
def __init__(self, radius, position: Position):
self.radius = radius
self.position = position
class Rectangle:
def __init__(self, width, height, position: Position):
se... | --- +++ @@ -1,8 +1,30 @@+"""
+Implementation of the Servant design pattern.
+
+The Servant design pattern is a behavioral pattern used to offer functionality
+to a group of classes without requiring them to inherit from a base class.
+
+This pattern involves creating a Servant class that provides certain services
+or f... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/behavioral/servant.py |
Document this module using docstrings | import weakref
class FlyweightMeta(type):
def __new__(mcs, name, parents, dct):
dct["pool"] = weakref.WeakValueDictionary()
return super().__new__(mcs, name, parents, dct)
@staticmethod
def _serialize_params(cls, *args, **kwargs):
args_list = list(map(str, args))
args_list... | --- +++ @@ -3,11 +3,24 @@
class FlyweightMeta(type):
def __new__(mcs, name, parents, dct):
+ """
+ Set up object pool
+
+ :param name: class name
+ :param parents: class parents
+ :param dct: dict: includes class attributes, class methods,
+ static methods, etc
+ ... | https://raw.githubusercontent.com/faif/python-patterns/HEAD/patterns/structural/flyweight_with_metaclass.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.