Awesome Cursor Rules Collection

Showing 1081-1092 of 2626 matches

TypeScript
Python
# AI Assistant Rules

## Core Behaviors

MUST Keep responses concise and conversational without exception
MUST Use casual but professional language at all times
MUST Provide only direct, actionable responses
MUST Maintain clarity and precision in all responses
MUST Support all suggestions with concrete examples
NEVER Use filler words like "certainly", "definitely", etc. under any circumstances
NEVER Include unnecessary apologies or overly formal language whatsoever
NEVER Make vague or ambiguous suggestions in any context
NEVER Leave any recommendation open to interpretation
NEVER Skip over important technical details

## Code Assistance

MUST Tag every code block with both language and filepath without exception
MUST Show complete context around all code changes
MUST Thoroughly analyze impact on all connected components
MUST Validate suggestions against existing patterns
MUST Test suggestions for compatibility

## Learned Best Practices

MUST Tag all code blocks with complete filepath and language information
MUST Provide full context for every code change
MUST Include complete file contents for new files
MUST Implement proper thread safety in audio processing
MUST Follow established error handling patterns
MUST Maintain consistent event emission patterns

## Common Pitfalls

NEVER Modify code without considering the event bus architecture
NEVER Mix synchronous and asynchronous patterns
NEVER Leave resource cleanup unhandled
NEVER Allow disconnected signal/slot connections
NEVER Break UI theme consistency
NEVER Bypass the manager registry pattern

## Response Format

MUST Use markdown formatting for all responses
MUST Include language and filepath in every code block
MUST Group all related changes together
MUST Provide relevant context for all changes
MUST Keep all explanations focused and actionable

## Error Handling

MUST Implement comprehensive error handling
MUST Account for all possible edge cases
MUST Follow established logging patterns
MUST Include proper resource cleanup
MUST Validate error recovery paths

## Project-Specific

MUST Design all changes around the event-driven architecture
MUST Adhere to the manager registry pattern without exception
MUST Ensure audio pipeline compatibility
MUST Follow UI theme specifications exactly
MUST Maintain all signal/slot connection patterns

## Environment Variables

MUST Use COMPANY_API_KEY naming convention for all API keys
MUST Assume environment variables are pre-loaded
NEVER Use dotenv or similar environment loading libraries

## Settings Files

MUST Use YAML format for all settings and configuration files
MUST Include proper YAML validation in config loading
MUST Follow established YAML structure patterns
MUST Document all YAML configuration options
MUST Maintain backwards compatibility in YAML schemas

## Documentation URLs

MUST Reference these official documentation sources:

Core Libraries:

- PyQt6: https://doc.qt.io/qtforpython-6/
- OpenAI API: https://platform.openai.com/docs
- Anthropic API: https://docs.anthropic.com/claude/
- Deepgram: https://developers.deepgram.com/docs/
- ElevenLabs: https://docs.elevenlabs.io/

Audio Processing:

- PyAudio: https://people.csail.mit.edu/hubert/pyaudio/docs/
- SoundDevice: https://python-sounddevice.readthedocs.io/
- pyttsx3: https://pyttsx3.readthedocs.io/
- pydub: https://github.com/jiaaro/pydub#documentation
- soundfile: https://pysoundfile.readthedocs.io/

Utility Libraries:

- pyautogui: https://pyautogui.readthedocs.io/
- pyperclip: https://pyperclip.readthedocs.io/
- numpy: https://numpy.org/doc/
- flask: https://flask.palletsprojects.com/
- PyYAML: https://pyyaml.org/wiki/PyYAMLDocumentation

MUST Consult relevant documentation when implementing features
MUST Keep documentation references up to date
MUST Follow each library's best practices and conventions
MUST Document any deviations from standard library patterns
NEVER Implement features without consulting official documentation

## Audio Configuration

MUST Use device default sample rate from PyAudio device info
MUST Handle sample rate validation gracefully
MUST Log sample rate detection and usage
MUST NOT Force specific sample rates without checking device capabilities

Example device sample rate detection:

```python
device_info = self._audio.get_device_info_by_index(config.device_id)
sample_rate = int(device_info["defaultSampleRate"])
```

## Audio Stream Management

- MUST Use device's default sample rate from PyAudio device info (never hardcode)
- MUST Configure buffer size as multiple of chunk size (typically 4x) to prevent overflow
- MUST Set exception_on_overflow=False in PyAudio read operations for graceful handling

Example buffer size configuration:

```python
self._buffer_size = config.chunk_size * 4
```

## Audio Stream Shutdown

MUST Follow exact shutdown sequence:

- Set stop flag first
- Process all buffered data using get_read_available()
- Stop stream only after buffer empty
- Close stream and cleanup resources
- Reset all state flags

Example proper shutdown:

```python
# First set flags
self._stop_requested = True
self._is_processing = True

# Process remaining buffer
while self._stream.is_active() and self._stream.get_read_available() > 0:
    data = self._stream.read(chunk_size, exception_on_overflow=False)
    if data:
        process_and_store_audio(data)

# Only then stop stream
self._stream.stop_stream()
self._stream.close()
```

## Audio Buffer Processing

MUST Process all buffered audio before stream closure
MUST Use consistent sample rate throughout processing
MUST Maintain audio quality during shutdown
MUST Log buffer metrics during processing
MUST Handle all exceptions during buffer processing
MUST Reset state in finally block
MUST Clean up resources on error
MUST Maintain consistent state after errors

## Audio Stream Pitfalls

NEVER Stop stream before processing remaining buffer
NEVER Discard buffered audio data during shutdown
NEVER Close stream while data is still available
NEVER Skip audio processing during shutdown
NEVER Mix buffer sizes during processing
NEVER Leave streams open after errors

## Logging Conventions

- MUST Use logging prefixes for clarity:
  - `===` for section boundaries and major state changes
  - `>>>` for important events and successful operations
  - `!!!` for errors and warnings
- MUST Include detailed audio metrics in debug logs (sample rates, buffer sizes, min/max values)
- MUST Log all transcription pipeline stages: audio capture, processing, transcription, and UI updates

## Audio Transcription Pipeline

- MUST Follow these steps for audio transcription:

  1. Use PyAudio's paFloat32 format for raw audio capture
  2. Buffer at least 2 seconds of audio before processing
  3. Normalize audio data to [-1, 1] range before resampling
  4. Resample audio to 16kHz for Whisper compatibility
  5. Maintain 0.5 second overlap between processing chunks

- MUST Handle sample rate conversion:

  - Detect source sample rate from first audio chunk
  - Always resample to 16kHz for Whisper
  - Use scipy.signal.resample for high-quality resampling

- MUST Implement proper buffer management:
  - Store raw audio chunks in list instead of bytearray
  - Calculate total samples across all chunks
  - Keep overlap from previous processing window
  - Clear buffer after processing to prevent memory growth

Example audio processing sequence:

```python
# Convert bytes to numpy array
chunk_data = np.frombuffer(chunk, dtype=np.float32)

# Normalize if needed
if np.max(np.abs(audio_data)) > 1.0:
    audio_data = audio_data / np.max(np.abs(audio_data))

# Resample to target rate
resampled = signal.resample(audio_data, target_length)
```

## Async/Await Best Practices

MUST Define WebSocket event handlers as async functions when using async queues or event buses
MUST Use iscoroutinefunction to properly handle mixed sync/async callbacks in event systems
MUST Maintain clear async boundaries between real-time audio capture and network services
MUST Handle WebSocket connection lifecycle with proper async/await patterns

# Deepgram-Specific Patterns

MUST Create Deepgram WebSocket connections in two steps:

1. Create live client: `live_client = client.listen.live.v("1")`
2. Start connection without await: `connection = live_client.start(options)`
   MUST Register event handlers on live client before starting connection
   MUST Use sync event registration with async handlers:

```python
# Correct pattern:
live_client = client.listen.live.v("1")
async def on_message(msg): ...
live_client.on("Results", on_message)
connection = live_client.start(options)
```

NEVER Mix sync and async callbacks without explicit handling
NEVER Use recursive event emission in error handlers
NEVER Await the start() method of Deepgram WebSocket connections
NEVER Register handlers after starting the connection
flask
openai
python
websockets
dotdevdotdev/voice-assistant

Used in 1 repository

TypeScript
# [Project Name]

Every time you choose to apply a rule(s), explicitly state the rule(s) in the output. You can abbreviate the rule description to a single word or phrase.

## Project Context

Web multiplayer party game where players trade stocks to maximize their net worth.

- Game takes 10 rounds with 5 phases. Player with hiest cash and stocks cost wins.
  - Players submit buy/sell orders for stocks
  - Orders are executed in chronological order, each affecting the stock price on execution
  - Event effects are revealed which affect stock prices or dividends
  - Dividends are paid out to players depending on their stock holdings
  - New event summary is shown to players allowing to guess the effects
- Game lobby initiated on the host device that provides gameplay overview
- Players can join lobby from their own devices to submit orders and see their cash and portfolio

## Code Style and Structure

- Write concise, technical TypeScript code with accurate examples
- Use functional and declarative programming patterns; avoid classes
- Prefer iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError)
- Structure repository files as follows:

```
app/                    # Next JS pages
├── game/               # Player's game pages
├── join/               # Page for joining a game
├── lobby/              # Game lobby pages and their creation
components/             # Shared React components
├── ui/                 # shadcn ui components
lib/
├── types/
    ├── supabase.ts     # Types representing supabase tables. Do not change without updating database schema
    └── ...
├── hooks/              # Custom React hooks
├── openai.ts           # Methods to generate events using OpenAI
└── ...
```

## Tech Stack

- Next.js 13
- React
- TypeScript
- Shadcn UI
- Supabase

## Naming Conventions

- Use lowercase with dashes for directories (e.g., components/form-wizard)
- Favor named exports for components and utilities
- Use PascalCase for component files (e.g., VisaForm.tsx)
- Use camelCase for utility files (e.g., formValidator.ts)

## TypeScript Usage

- Use TypeScript for all code; prefer interfaces over types
- Avoid enums; use const objects with 'as const' assertion
- Use functional components with TypeScript interfaces
- Use absolute imports for all files @/...
- Avoid try/catch blocks unless there's good reason to translate or handle error in that abstraction
- Use explicit return types for all functions

## UI and Styling

- Use Shadcn UI and `npx shadcn@latest add <component-name>` command (not shadcn-ui) to add new shadcn components

## Database

- Do not make any assumptions about the database structure; always request this information from the user
- If you need information about the database structure, write plain sql queries code blocks that user will execute in supabase web console
- When updating database structure, write sql queries code blocks to execute in supabase web console

## Error Handling

- Implement proper error boundaries
- Log errors appropriately for debugging
- Provide user-friendly error messages
- Handle network failures gracefully
css
golang
javascript
less
next.js
openai
react
shadcn/ui
+2 more
egor-sergeev/party-market

Used in 1 repository

TypeScript
You are an expert in TypeScript, Next.js App Router, React, Prisma, Postgres, Clerk/nextjs@4.29.12, Shadcn UI, and Tailwind CSS.

Code Style and Structure

- Use the style and structure that is already used in the current folder structure.
- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Structure files: exported component, subcomponents, helpers, static content, types.
- Always uses stable versions of the different packages.

Naming Conventions

- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Favor named exports for components.

TypeScript Usage

- Use TypeScript for all code; prefer interfaces over types.
- Avoid enums; use maps instead.
- Use functional components with TypeScript interfaces.

Syntax and Formatting

- Use the "function" keyword for pure functions.
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
- Use declarative JSX.

UI and Styling

- Use Shadcn UI, and Tailwind CSS for components and styling.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.

Performance Optimization

- Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
- Wrap client components in Suspense with fallback.

Follow Next.js docs for Data Fetching, Rendering, and Routing.
clerk
css
javascript
next.js
postgresql
prisma
react
shadcn/ui
+2 more
kdgs-develop/kdgs-admin-dashboard

Used in 1 repository

Python
You are an expert in Python, Django (v5), Django REST Framework, Accounting & Finance, and scalable web application development.
Key Principles
- Follow The Twelve-Factor App principles for building scalable, maintainable, and portable web applications.
- Write clear, technical responses with precise Django and DRF examples.
- Use Django's built-in features and tools wherever possible to leverage its full capabilities.
- Prioritize readability and maintainability; follow Django's coding style guide (PEP 8 compliance).
- Use descriptive variable and function names; adhere to naming conventions (e.g., lowercase with underscores for functions and variables).
- Structure your project in a modular way using Django apps to promote reusability and separation of concerns.
Django/Python
- Use Django's class-based views (CBVs) for more complex views; prefer function-based views (FBVs) for simpler logic.
- Leverage Django's ORM for database interactions; avoid raw SQL queries unless necessary for performance.
- Use Django's built-in user model and authentication framework for user management.
- Utilize Django's form and model form classes for form handling and validation.
- Follow the MVT (Model-View-Template) pattern strictly for clear separation of concerns.
- Use middleware judiciously to handle cross-cutting concerns like authentication, logging, and caching.
Error Handling and Validation
- Implement error handling at the view level and use Django's built-in error handling mechanisms.
- Use Django's validation framework to validate form and model data.
- Prefer try-except blocks for handling exceptions in business logic and views.
- Customize error pages (e.g., 404, 500) to improve user experience and provide helpful information.
- Use Django signals to decouple error handling and logging from core business logic.
Dependencies
- Django
- Django REST Framework (for API development)
- Celery (for background tasks)
- Redis (for caching and task queues)
- PostgreSQL or MySQL (preferred databases for production)
Django-Specific Guidelines
- Use DRF serializers for JSON responses.
- Keep business logic in models and forms; keep views light and focused on request handling.
- Use Django's URL dispatcher (urls.py) to define clear and RESTful URL patterns.
- Apply Django's security best practices (e.g., CSRF protection, SQL injection protection, XSS prevention).
- Leverage Django's caching framework to optimize performance for frequently accessed data.
- Use Django's middleware for common tasks such as authentication, logging, and security.
Performance Optimization
- Optimize query performance using Django ORM's select_related and prefetch_related for related object fetching.
- Use Django's cache framework with backend support (e.g., Redis or Memcached) to reduce database load.
- Implement database indexing and query optimization techniques for better performance.
- Use asynchronous views and background tasks (via Celery) for I/O-bound or long-running operations.
- Optimize static file handling with Django's static file management system (e.g., WhiteNoise or CDN integration).
Key Conventions
1. Follow Django's "Convention Over Configuration" principle for reducing boilerplate code.
2. Prioritize security and performance optimization in every stage of development.
3. Maintain a clear and logical project structure to enhance readability and maintainability.

Refer to Django version 5 documentation for best practices in views, models, forms, and security considerations.
Use standard implementations for financial calculations and accounting rules as per Indian Accounting Standards.
django
dockerfile
golang
html
less
mysql
postgresql
python
+3 more

First seen in:

rithviknishad/ilgi

Used in 1 repository