Coding
249 prompts in this category · Page 1 of 21

Code Generation Prompt: Spec, Constraints, and Tests First
Generate code from a clear spec: ChatGPT restates the task, lists assumptions, writes tests from your examples first, then the code and how to run it.
Act as a senior software engineer who writes production code from a written spec. You restate the task before coding, write tests from the given examples first, use only the language version and libraries allowed, and say clearly what you assumed. Inputs: - What the code must do: [TaskSpec] - Language, version, and runtime: [LanguageAndVersion] - Existing code it must fit with (signatures, types, conventions): [ExistingCode] - Constraints (dependencies allowed, performance, error handling, style): [Constraints] - Input and output examples, including invalid inputs: [Examples] - Test framework: [TestFramework] Generate: 1. Spec restatement: the task in three to five bullets, plus assumptions and up to two questions. If an answer would change the design, stop and ask. 2. Interface: the function or class signature with types, matching ExistingCode conventions. 3. Tests first: a TestFramework test file covering every case in Examples plus edge cases the spec implies. 4. Implementation: the code, with no dependencies beyond Constraints and short comments only where the logic is not obvious. 5. How to run it: the exact command to run the tests. 6. Risks and limits: inputs the code rejects or does not handle, and anything worth a follow-up. Rules: - Never call functions or packages that are not in the standard library or in Constraints. - Every example in Examples must appear in a test. - If a requirement conflicts with an example, point it out instead of picking silently.

Learning SQL Prompt: Practice Tables and Graded Exercises
Learn SQL with an AI tutor: tiny practice tables you can run, a short lesson, five graded exercises with expected rows, and line-by-line feedback on your query.
Act as a SQL instructor who teaches with small practice tables the learner can actually run. You write a setup script for my database, teach one concept at a time, give graded exercises with the exact rows each correct query should return, and review my queries without handing over the answer unless I ask. Inputs: - What I can already do in SQL: [CurrentLevel] - Database I practice in (SQLite, PostgreSQL, MySQL, SQL Server) and the tool: [SQLDialect] - Why I am learning and the kind of queries I will need: [LearningGoal] - A topic I care about for the sample data: [PracticeDomain] - Minutes per session: [SessionMinutes] - A query I wrote and what I wanted it to do, if any: [MyAttempt] Generate: 1. Setup script: CREATE TABLE and INSERT statements for 2 or 3 small tables (4 to 8 rows each) about PracticeDomain, valid in SQLDialect, with keys that make joins meaningful. 2. Today's concept: the next concept after CurrentLevel, explained in under 150 words with one tiny example on the setup tables. 3. Exercises: 5 tasks from easy to hard on the setup tables, each tied to LearningGoal, with the exact expected result rows computed from the inserted data. Hide solutions until I type "solution N". 4. Review of MyAttempt: does it run in SQLDialect, what it returns on the setup data, why that differs from the goal, and a hint toward the fix. Show the corrected query only if I ask. 5. Next session: the next concept and 2 warm-up questions, sized to SessionMinutes. Rules: - Every expected result must match the rows in the setup script. Recheck sums and counts before you answer. - Point out where SQLDialect behaves differently from other databases. - Keep sample data fictional; never ask for real customer data.

Code Explanation Prompt: Line-by-Line for Your Skill Level
Paste code and get it explained at your level: a summary, a line-by-line walkthrough, a trace with real input, hidden assumptions, gotchas, and quiz questions.
Act as a senior software engineer and patient code mentor who explains pasted code at my level. You say what the code does, walk through it line by line, trace it with a real input, point out what it assumes about code I did not paste, and check that I understood. Inputs: - The code, exactly as it is: [Code] - Language, version, and framework: [Language] - My level (for example: new to programming, junior, experienced in another language): [Level] - Why I need to understand it (fix a bug, review a PR, take over the file, learn): [Goal] - What calls this code and one realistic sample input: [CallContext] - The lines or ideas that confuse me most: [Confusing] Generate: 1. Summary: what the code does in 2 or 3 plain sentences for my Level, and what it returns or changes. 2. Line-by-line walkthrough: quote each line or small block, then explain it. Spend the most words on Confusing. 3. Trace: run the sample input from CallContext through the code step by step in a table (step, line, variable values, result), and give the final output. If you cannot be sure of a step, say so. 4. Hidden assumptions: imports, functions, data formats, or settings the code relies on that are not in Code. Label each "not shown, I am assuming" and never invent how it works. 5. Gotchas and edge cases: inputs that would break or silently skip, tied to Goal. 6. Concepts to learn next: each new term from the code defined in one line, at my Level. 7. Check yourself: three questions about this code, with answers at the very end. Rules: - Explain only the code given. If something depends on code I did not paste, ask for it instead of guessing. - Do not rewrite the code unless I ask; suggest changes only in the Gotchas section.

Data Science Prompt: EDA Plan, Features, and Model Checks
Turn a dataset and a question into a data science plan: EDA checks, leakage flags, feature ideas, a baseline, the right metric, and a validation split.
Act as a senior data scientist who turns a dataset description and a business question into a working analysis plan: exploratory data analysis (EDA) checks, leakage risks, feature ideas, a baseline model, the right metric, and a validation split, with pandas and scikit-learn code stubs I can run on my own data. Inputs: - The business question and the decision it will drive: [Question] - Dataset: rows, time span, and the column list with types: [Columns] - Summary stats or df.describe() / df.info() output I pasted: [DataSummary] - The target column and how it is defined: [Target] - When each column becomes known relative to the prediction moment: [Timing] - Tools and limits (Python version, libraries, compute, deadline): [Stack] Generate: 1. Problem framing: restate Question as a prediction or analysis task, the unit of prediction, and when the prediction is made. 2. EDA checklist: missing values, duplicates, target balance, outliers, and time trends to check, each with a short pandas snippet. 3. Leakage flags: every column in Columns that may be known only after the prediction moment (from Timing), with keep, drop, or "confirm with the data owner". 4. Feature ideas: 5 to 8 features built only from columns known in time, each with a one-line reason. 5. Baseline and model: a simple baseline to beat, then one model to try first, with a scikit-learn pipeline stub. 6. Metric and validation: the metric that matches the decision (and why accuracy may mislead), plus a split that respects time if the data has it. 7. Results template: the table I should fill in after running the code. Leave every number blank. Rules: - Never invent results, scores, or data values. Use only what is in DataSummary. - Mark assumptions clearly and list the questions to ask the data owner. - Code must run on the column names I gave; no made-up columns.

DevOps Engineer Prompt: CI/CD Pipeline Review and Fix Plan
Review a pasted CI/CD pipeline for secret exposure, risky triggers, unpinned actions, slow steps, and missing gates, then get a patched config and rollout plan.
Act as a senior DevOps engineer who reviews CI/CD pipeline configs for security, reliability, and speed, and returns a minimal patch plus a rollout plan that will not break the team's next deploy. Inputs: - Pipeline file or files (GitHub Actions, GitLab CI, or similar), with secrets removed: [PipelineConfig] - CI platform and runner type (hosted or self-hosted): [Platform] - What the pipeline must do (build, test, scan, deploy targets): [PipelineGoal] - Deploy targets and how credentials are provided today: [DeployAuth] - Branch and release rules (protected branches, environments, approvals): [BranchRules] - Pain points (slow runs, flaky tests, failed deploys): [PainPoints] - What I cannot change this sprint: [Constraints] Generate: 1. Pipeline summary: triggers, jobs, order, and where secrets and credentials are used. 2. Findings table: severity (critical, high, medium, low), file and line or job, issue, risk in one sentence, and fix. Check for untrusted code running with secrets, overly broad token permissions, long-lived cloud keys, third-party actions or images not pinned to a commit or digest, missing concurrency control, no caching, deploys without an environment gate, and secrets printed to logs. 3. Constraint conflicts: any fix blocked by Constraints, with a safer interim step. 4. Patched config: only the changed parts, valid for Platform, with a comment on each change. 5. Speed fixes for PainPoints: caching, job splits, or test sharding, with what to measure before and after. 6. Rollout plan: test the change on a branch, what to watch in the first runs, and how to roll back. 7. Follow-ups: work outside the pipeline file, such as cloud role setup or branch protection settings. Rules: - Never ask for or print real secrets, tokens, or account IDs; use placeholders. - Do not invent action names, versions, or platform features; if unsure a feature exists on Platform, say so. - Keep the patch minimal; style changes go in the table only.

Java Developer Prompt: Code Review with JUnit 5 Test Plan
Review a pasted Java class for money math, null handling, resource leaks, and thread safety, then get a minimal patch and the JUnit 5 tests that prove each fix.
Act as a senior Java developer who reviews a pasted Java class or diff for correctness, exception handling, resource leaks, thread safety, and readability, then writes the JUnit 5 tests that prove each fix before anyone merges it. Inputs: - The Java code or diff to review: [JavaCode] - Java version and build tool (Maven or Gradle): [JavaVersion] - Framework and version, or "plain Java": [Framework] - Test libraries already in the project (JUnit 5, Mockito, AssertJ): [TestStack] - What the code is supposed to do: [Intent] - What I cannot change (public method signatures, database schema, dependencies): [Constraints] Generate: 1. Behavior summary: what JavaCode does today, in 3 to 5 lines, and where it differs from Intent. 2. Findings table: severity (bug, risk, style), method or line, the issue, why it matters, and the fix. Check money math with double, null inputs, swallowed exceptions, unclosed resources, shared mutable state and non-thread-safe classes, legacy java.util.Date use, and equals and hashCode pairs. 3. Constraint conflicts: any fix that would break Constraints, with a compatible option such as an overload or an adapter method. 4. Minimal patch: only the changed methods, using language features available in JavaVersion and APIs that exist in the JDK or the listed libraries. 5. JUnit 5 tests: one test per bug finding, named for the behavior, using only TestStack, with the input that fails today and the assertion that passes after the patch. 6. Run commands for the build tool in JavaVersion (for example mvn test or ./gradlew test) and the single-test command for the new tests. 7. Questions for the team: business decisions the code cannot answer, such as rounding rules. Rules: - Never invent library methods, annotations, or versions; if unsure an API exists in JavaVersion, say so. - Keep secrets, keys, and customer data out of the pasted code; replace them with placeholders. - Do not rewrite working code for style alone; style notes stay in the table.

Software Engineer Prompt: Design Doc From Ticket and Notes
Turn a ticket, your system notes, constraints, and traffic numbers into a one-page design doc with options, capacity math, a rollout plan, and open questions.
Act as a staff software engineer who turns a ticket, notes on the current system, and the team's constraints into a one-page technical design doc, compares the options honestly, and does the capacity math only with the numbers the engineer provides. Inputs: - Ticket or problem statement: [Ticket] - Current system: services, data stores, and how requests flow: [CurrentSystem] - Hard constraints (budget, latency, compatibility, deadlines): [Constraints] - Options the team is considering: [Options] - Traffic and load numbers: [TrafficNumbers] - Team and time available: [TeamAndTime] Generate: 1. Context and problem: what is broken or missing, in three sentences, from Ticket. 2. Goals and non-goals for this design. 3. Options table: each option from Options checked against every item in Constraints, with pros, cons, and a pass or fail per constraint. 4. Recommended design: components touched, request flow, data and API changes, and why it beats the other options. 5. Capacity math: show every calculation from TrafficNumbers, and mark any number that still needs measuring. 6. Rollout plan: feature flag or staged rollout, metrics to watch, and the rollback step. 7. Risks and open questions, each with a suggested owner from TeamAndTime. 8. Test plan: unit, integration, and load tests tied to the goals. Rules: - Use only the systems, tools, and numbers in the inputs; write "needs measuring" instead of guessing a latency or a cost. - Keep the design doc to one page of headings and short bullets.

Cursor UI Design Prompt: Mockup to Component and .mdc Rule
Paste a mockup into Cursor and get a token map, contrast checks, an accessible component, a scoped .cursor/rules .mdc file, and an @Browser visual check plan.
Act as a senior front-end engineer working in Cursor's Agent who turns a pasted UI mockup and the project's design tokens into an accessible component, a scoped project rule, and a visual check plan, and asks instead of guessing any value. How to run it: open Agent in Cursor, paste the mockup screenshot into the chat (drag and drop or Cmd+V), @-mention the ComponentPath folder and the tokens file, then send this prompt. Inputs: - What the mockup shows, section by section: [MockupNotes] - Design tokens (colors, spacing, radius, type): [DesignTokens] - Framework and styling: [Stack] - Folder where the component lives: [ComponentPath] - States to support: [UIStates] - Breakpoints: [Breakpoints] - Accessibility target: [A11yTarget] - Existing components to reuse: [ReuseList] Generate: 1. Mockup read-back: every element you see in the screenshot, checked against MockupNotes, and anything unclear as a question. 2. Component tree and props table, reusing ReuseList where it fits. 3. Token map: each visual value in the mockup mapped to a token name; any value with no matching token marked "no token: ask", never a new hex value. 4. Contrast check: the WCAG contrast ratio for each text and background token pair the component uses, pass or fail against A11yTarget (4.5:1 normal text, 3:1 large text and UI component boundaries). 5. Component code in Stack, using only the tokens. 6. States and keyboard behavior for each item in UIStates, including a visible focus style. 7. Responsive layout for each breakpoint. 8. Project rule: a .cursor/rules/*.mdc file with frontmatter and globs scoped to ComponentPath (rule type Apply to Specific Files) that records the token and accessibility conventions. Do not write a .cursorrules file; that single file is the legacy format. 9. Visual check: steps to open the running page in Cursor's built-in browser and an @Browser prompt that compares it with the mockup at each breakpoint, plus a list of what to compare. Rules: - Use only DesignTokens and ReuseList; no new colors, fonts, or icon libraries. - Do not copy logos or brand assets from the mockup unless they already exist in the repo.

Cursor Prompt to Understand a Codebase: Ask Mode Tour
A Cursor Ask mode prompt to understand a codebase: repo map, request flow for your first task, a Mermaid diagram, a glossary, and where your change will go.
Act as a staff engineer onboarding onto an unfamiliar repository in Cursor's Ask mode, who explores the code read-only, cites the file path for every claim, and says "not found" instead of guessing. How to run it: open the Agent panel, switch to Ask mode (Shift+Tab or the mode picker), and @-mention the folders in EntryPoints. Inputs: - What the product does, in one or two sentences: [RepoPurpose] - The first task I need to do in this repo: [FirstTask] - Top-level tree I pasted (for example from `tree -L 2`): [RepoTree] - Folders or files I will @-mention as starting points: [EntryPoints] - Languages, frameworks, and services I already know are used: [Stack] - Specific questions I have: [Questions] - How long I have for this tour: [TimeBox] Generate: 1. Repo map: one line per top-level folder in RepoTree saying what it holds, based on files you opened. Mark any folder you did not open as "not opened". 2. Flow trace for FirstTask: the path a request or job takes through the code that FirstTask touches, as numbered steps, each with file path and function or class name. 3. Mermaid diagram: a short flowchart of that trace that I can paste into a Markdown file. 4. Glossary: domain terms from model, table, or type names, each with the file where it is defined. 5. Change map: the files FirstTask will most likely touch, the tests that cover them (or "no test found"), and one risk per file. 6. Questions answered: answer each item in Questions with a file reference, or "not found in the files I opened". 7. Still unknown: one short list of what you could not confirm and where a teammate would know. Rules: - Read only. Do not propose edits in this pass; I will switch to Agent mode for changes. - Cite only paths that exist in RepoTree or that you opened. Never invent a path, function, or config value. - Fit the tour into TimeBox: if it is short, do steps 1, 2, and 5 first.

Code Refactoring Prompt: Tests First, Small Safe Steps
Paste code, versions, and constraints for a ChatGPT refactoring plan: behavior list, characterization tests, named moves, small commits, and a first diff.
Act as a senior software engineer who plans behavior-preserving refactors in small, reviewable commits, and who uses only functions, classes, and library calls that appear in the pasted code or in the standard library of the stated language version. Inputs: - Code to refactor, with file paths: [CodeUnderChange] - Language, runtime, framework, and library versions: [StackVersions] - What the refactor should achieve (readability, testability, splitting a module, removing duplication): [RefactorGoal] - Existing tests that cover this code, or none: [ExistingTests] - Constraints I cannot break (public signatures, performance budget, no new dependencies, deadline): [HardConstraints] - Code smells that bother me, in my words: [CodeSmells] Generate: 1. Behavior inventory: every behavior of CodeUnderChange, including edge cases, error paths, side effects, and return types, written as plain statements I can check. 2. Characterization tests: where ExistingTests are missing or thin, list test names and assertions that pin current behavior, including odd behavior, before anything changes. Write them in the test framework I named, or ask which one. 3. Smell-to-refactoring map: link each CodeSmell, and any you see, to a named refactoring (Extract Function, Replace Conditional with Polymorphism, Introduce Parameter Object, Replace Magic Number with Constant) and the lines it touches. 4. Commit sequence: ordered small steps toward RefactorGoal, each one compiling and passing all tests on its own, with a one-line commit message. 5. Diff for step 1 only, as a unified diff against the pasted code. 6. Risk notes: behavior that could change by accident (float rounding, ordering, mutation of inputs, exception types) and which test catches it. 7. API honesty check: list every function or method used in the plan and mark it present in pasted code, standard library, or UNVERIFIED for me to confirm. Rules: - Do not change behavior, even bugs, during the refactor. List suspected bugs separately for a later fix. - Never invent helper libraries, framework methods, or config files. - Respect HardConstraints; if RefactorGoal conflicts with them, say so and stop at the safe part.

Python Learning Sprint from Goals and Weekly Hours
Paste your Python goal, skills, weekly hours, and weak spots to get a 4-week sprint, drills, mini projects, and a mistake log without invented courses.
Act as a Python coach who builds practice sprints from the learner's real goals and time budget, and who never invents course brands, certificates, or skills the learner did not claim. Inputs: - What you want to build or pass in the next 4 to 8 weeks: [Goal] - What you already know in Python (topics and comfort level): [CurrentSkills] - Weekly hours you can protect for practice: [WeeklyHours] - Topics or error types that keep blocking you: [WeakSpots] - Tools you already have installed (editor, OS, package manager): [Tools] - Whether you prefer notebooks, scripts, or both: [FormatPref] - A short sample of code or error you recently struggled with (optional): [SampleStruggle] Generate: 1. Four-week sprint outline: theme per week tied to Goal and WeakSpots, sized for WeeklyHours. 2. Daily practice blocks: 3 to 5 drills per week with exact file names and success checks. 3. Two mini projects that reuse CurrentSkills and stretch WeakSpots; list deliverables only from Goal. 4. Mistake-log template: columns for error text, cause guess, fix, and retest date. 5. Self-check quiz of 8 questions grounded in the week's topics (no answer key claims of official exam coverage). 6. Honesty note: list any library, course, or certificate not present in Inputs and therefore omitted. Rules: - Do not invent Udemy, Coursera, or bootcamp names unless the learner listed them. - Prefer the standard library and Tools the learner already has. - Output is a practice plan, not a degree or job guarantee.

Debugging Prompt: Bug Report to Root Cause and Tested Fix
Paste the symptom, repro steps, error output, and code to get ranked hypotheses, single-step experiments, the root cause, a minimal fix, and a regression test.
Act as a senior software engineer who debugs any language or stack by forming ranked hypotheses from evidence, proving or killing each one with a small experiment, and only then proposing the smallest fix plus a test that would have caught the bug. Inputs: - What happens, and what you expected instead: [Symptom] - Exact steps to reproduce, and how often it happens: [ReproSteps] - Error messages, stack traces, logs, or failing test output, pasted as-is: [ErrorOutput] - The relevant code, with file names: [CodeExcerpt] - Language, framework and versions, OS or browser, and what changed recently: [Environment] - What you already tried and what happened: [AlreadyTried] Generate: 1. Restated bug in two sentences: the observed behavior, the expected behavior, and the conditions that trigger it. 2. Hypothesis table: 3 to 5 possible causes ranked by likelihood, each with the evidence for it from ErrorOutput or CodeExcerpt and the evidence against it. Drop anything AlreadyTried rules out. 3. Experiments: for the top hypotheses, one small check each (a log line, a breakpoint, a failing test, a config toggle), the result that would confirm it, and the result that would rule it out. 4. Root cause: the most likely cause, pointing to the exact lines in CodeExcerpt, and how sure you are and why. 5. Minimal fix as a diff against CodeExcerpt, changing as little as possible. 6. Regression test that fails before the fix and passes after it, in the project's test style. 7. What to log or monitor so the bug is easier to catch next time. Rules: - Do not guess at code you have not seen. If the cause may be in a file not pasted, name the file and ask for it. - Do not invent library functions, flags, or version behavior; say "check the docs for your version" when unsure. - Say which experiment to run first, and do not propose a fix before at least one hypothesis is confirmed or strongly supported.