AI 资讯
Delete Node in a Linked List
Problem Link - https://leetcode.com/problems/delete-node-in-a-linked-list/ This is one of those interview questions that looks impossible at first. Normally, to delete a node from a Linked List, we need access to the previous node. But in this problem, we're only given the node that needs to be deleted. No head. No previous pointer. So how do we remove it? Let's understand the trick. Problem Statement Write a function to delete a node in a singly linked list. You are not given the head of the list. Instead, you are given only the node that needs to be deleted. Example Input: 4 -> 5 -> 1 -> 9 node = 5 Output: 4 -> 1 -> 9 Initial Thought Normally we delete a node like this: prev.next = node.next But here: We don't have prev We don't have head So the usual deletion approach is impossible. Key Observation Although we cannot delete the current node directly, we can make it look like it never existed. Consider: 4 -> 5 -> 1 -> 9 We need to delete: 5 Instead of removing node 5 , copy the value of the next node into it. 4 -> 1 -> 1 -> 9 Now remove the next node. 4 -> 1 -> 9 The original value 5 has disappeared. Mission accomplished. Intuition Copy the next node's value into the current node. Skip the next node. The current node now behaves as if it was deleted. Since the problem guarantees that the given node is not the tail node, a next node will always exist. Dry Run Input 4 -> 5 -> 1 -> 9 node = 5 Current node: 5 Next node: 1 Step 1 Copy next node value. node.val = node.next.val List becomes: 4 -> 1 -> 1 -> 9 Step 2 Skip next node. node.next = node.next.next List becomes: 4 -> 1 -> 9 Done. Optimal Java Solution class Solution { public void deleteNode ( ListNode node ) { ListNode cur = node . next ; node . val = cur . val ; node . next = cur . next ; } } Even Shorter Version class Solution { public void deleteNode ( ListNode node ) { node . val = node . next . val ; node . next = node . next . next ; } } Complexity Analysis Metric Complexity Time Complexity O(1) Space Comp
AI 资讯
How we made our niche-industry SaaS MCP-ready (and watched ChatGPT call our dispatch tools)
Note: This is an English digest of the original Zenn post (Japanese) . Read there for the full timeline and commit-level trace. TL;DR We ship tasteck , a B2B SaaS for the Japanese night-leisure industry (dispatch + cast shift management). 8 years of operational data, ~100 venues live. Two days after the MCP design post , ChatGPT Plus can call our tools live: "Who's available tonight?" → MCP list_available_drivers → JSON → natural-language reply. Estimated B2 OAuth sprint = 2 weeks (6/16–7/1). Actual = 1 day , by reading the spec carefully before touching code. We hit 12 distinct traps between "OAuth issuance works" and "ChatGPT actually invokes the tool." The QA logs caught every one. What we shipped 3 read tools (B1): list_available_drivers — drivers free tonight list_cast_shifts — today's cast shift roster list_assignable_casts — joined resolution: roster ∧ stage-name set ∧ shop match Natural-language date helper: resolveBusinessDate(naturalText, company) — handles "today / tomorrow / day-after-tomorrow" and the per-tenant business-day boundary (e.g. day flips at 04:00 or 05:00, configured per Company.changeDateTime ). MCP SDK Server + SSE transport: @modelcontextprotocol/sdk wired into a NestJS controller. One SSE connection = one McpServer instance, company-scoped, with a session_id Map routing POST /messages . OAuth flow (B2, finished in one day across 7 steps) Step What Commit 1 Protected Resource Metadata endpoint (RFC 9728) d6f05ff6 2 /authorize + consent screen + PKCE start 107edbcb 3 /token + PKCE verify + JWT issue + resource (RFC 8707) ffd0468c 4 OAuthAccessTokenGuard (RS256 + HS256 fallback, extracts companyId / staffId ) f2c9bed4 5 Streamable HTTP transport (SSE → POST /sse/:companyId for JSON-RPC) 3a28d92f 6 resolveBusinessDate undefined fallback (`(naturalText 7 QA redeploy + ChatGPT live demo — The 12 traps (compressed) The full timeline is in the Japanese post; the abridged list: Discovery path mismatch. ChatGPT expected {% raw %} .well-known/oauth
AI 资讯
"Supports custom code" means nothing. Here's the 3-level ruler that tells you if a low-code platform will lock you in.
Every low-code vendor says "we support customization." But supports is a weasel word — recoloring a button is customization, and rewriting a scheduling engine is also customization. What actually decides whether a platform locks you in is how far up its extensibility goes. Here's a ruler. The three levels of customization Level What you can do Most no-code A real dev framework L1 — Config Fields, forms, workflows, permissions, themes ✅ ✅ L2 — Extension Custom components, custom actions, external API calls, business rules ⚠️ limited ✅ L3 — Framework Modify/extend the core, custom engines, deep rewrites, source under control ❌ wall ✅ (when open/controllable) Where it stops is where your ceiling is. Plenty of no-code platforms are delightful at L1, then hit "can't do that" at L2/L3 — and you retreat to writing your own thing next to it. Now low-code is the burden. Why you get locked in Black-box SaaS — no source, so any extension point the vendor didn't expose is simply out of reach. Two sources of truth — your extension code and the platform's config live in different systems, so a platform upgrade breaks/voids your work. Crippled self-hosting — the on-prem edition quietly drops extension capabilities. Closed ecosystem — only their component marketplace; your stack can't get in. How model-driven + open source raises the ceiling One unified extension system — your extensions (custom fields/components/actions) and the platform itself are built on the same metadata. Extension isn't a bolt-on, it's a first-class citizen — upgrades don't wipe your customizations. Source under your control — open + self-hostable is what makes L3 framework-level extension actually possible: an extension point you can't reach, you can add. AI at the metadata layer — AI-generated extensions land in the same model, so they stay maintainable and evolvable. That's the road Oinone takes: 100% metadata-driven, front + back end open source, self-hostable — customization reaches L3. How to stress-tes
AI 资讯
From Notion to MCP Server: I Rebuilt 4 Workflows in a Weekend
Migrated 4 of 7 Notion automations to an MCP server in one weekend Two workflows stayed in Notion because the database UI beat any tool call MCP scope rule: one tool does one verb, never a Swiss Army function Result: 12 manual steps collapsed into 3 Claude prompts per publish I spent a weekend pulling four automations out of Notion and rebuilding them as MCP tools. Three of them got faster and one got worse before it got better. The biggest lesson was not about code. It was about deciding which jobs should never leave Notion in the first place. Why I Moved Off Notion In The First Place My Notion setup was not broken. It was just slow in a specific way. I had seven automations stitched together with Notion buttons, formula properties, and two third-party connectors. Every blog publish meant clicking through four pages, copying a title here, pasting a tag list there, and triggering a sync that took 90 seconds to confirm. Multiply that by the 18 articles I push in a normal month and the clicking adds up. The breaking point was a Tuesday where I lost 40 minutes to a connector that silently stopped firing. No error, no log, just a row that never updated. I checked the connector dashboard and it told me everything was healthy. It was not healthy. That kind of invisible failure is the worst kind because you trust it until you do not. MCP changed the math for me. An MCP server lets Claude call my own functions directly. Instead of Claude writing text and me ferrying that text into Notion by hand, Claude can call a tool that does the writing into my systems. The model becomes the operator, not just the writer. If you want the deeper context on what MCP actually is and why it matters at scale, MCP: The 97 Million Agentic Foundation goes through the bigger picture. So I made a list. Seven automations, sorted by how much human judgment each one needed. The ones at the top were pure mechanical steps: format this, push that, fetch a status. The ones at the bottom needed me to loo
AI 资讯
The AI-generated C# that passes review and breaks in production
TL;DR — AI assistants are producing C# that looks correct and passes review, but reintroduces production regressions we spent years training out of teams. I'm trying to find out whether other .NET teams see the same patterns — and what's actually catching them before merge. More AI-generated C# is landing in pull requests. Most of it is fine. But a specific category keeps slipping through — and it's the dangerous one, because it compiles, tests pass, and a human skim says "looks good." The pattern The code compiles. Tests pass. Review approves. Production finds out. These aren't syntax errors. They're architectural intent violations — the kind of thing a senior dev would have caught in review before PR volume tripled. Five regressions I keep seeing 1. EF Core read paths without AsNoTracking() Fine in dev. Expensive on a hot read path in prod. // ❌ Looks reasonable. Tracks entities you never mutate. var orders = await _db . Orders . Where ( o => o . CustomerId == id ) . ToListAsync ( cancellationToken ); Fix direction: AsNoTracking() on read-only queries, or a team convention documented in CLAUDE.md / Copilot instructions. 2. Captive dependency (scoped service in a singleton) Compiles. Runs. Wrong state across requests. // ❌ Singleton lives forever; scoped dependency does not. services . AddScoped < IOrderRepository , OrderRepository >(); services . AddSingleton < ReportCache >(); // ctor takes IOrderRepository Fix direction: align lifetimes, or inject IServiceScopeFactory instead of capturing scoped services. 3. Dropped CancellationToken The method accepts cancellation. The downstream call ignores it. // ❌ Signature honours cancellation; body doesn't. public async Task RunAsync ( CancellationToken cancellationToken ) { await Task . Delay ( 500 ); // overload with token exists } Fix direction: forward cancellationToken to every downstream async call that accepts one. 4. Swallowed exception Failure disappears. Monitoring stays green. // ❌ "Handle errors gracefully" —
AI 资讯
From Scratch: How to Integrate Reasonix CLI into the HagiCode System
From Scratch: How to Integrate Reasonix CLI into the HagiCode System This article shares the complete technical practice of integrating Reasonix CLI as a first-class Agent Provider into the HagiCode system, covering three-layer architecture design, key technical decisions, and frontend and backend implementation details. Background Reasonix CLI, as it happens, is a pretty interesting thing. It's an AI code assistant tool based on ACP (Agent Communication Protocol), providing powerful streaming and session management capabilities. Actually, in the HagiCode.Libs layer, we've already completed its underlying implementation. It's just that these components are still in an isolated state, like beautiful pearls that haven't been strung into a necklace. Users cannot use it through Hero profession selection, session execution paths, or monitoring panels, which is somewhat regrettable. The problem we face is: how to elevate Reasonix to the same level as Codex, Hermes, and other first-class Agent Providers, implementing complete backend routing and frontend display? This isn't simply a matter of registering an enum value. It requires building a complete chain from low-level abstraction to user interface. It's like building a house—you can't just lay a foundation and call it done. You have to build the walls and put up the roof. The challenge of this integration lies in the fact that Reasonix, as a local CLI tool, has its own personality and temperament. For example, it doesn't need a connection string—all parameters are configured by the user at runtime; it might not even be installed, requiring graceful degradation; it's compatible with anthropic series models, but also has its own ACP-specific parameters like effort, budget, and so on. It's like a person with their own unique way of handling things—you can't force it. After careful architectural design and multiple rounds of discussion, we finally adopted a clear three-layer architecture solution, successfully integrating R
AI 资讯
5 Claude API Errors That Cost Me Money (And How I Trapped Them)
Retry storms turned 1 timeout into 340 duplicate calls billed in 90 seconds Infinite tool loop ran 1,200 iterations before I noticed at 2am Partial stream cleanup stopped half-written DB writes corrupting records Trap every error class with a circuit breaker and a hard iteration cap Five Claude API errors quietly drained my account before I built guards around them. None of them threw a loud crash. They just kept billing while I slept. Here is exactly what broke, what it cost, and the traps I now run on every project. The Retry Storm That Billed 340 Times in 90 Seconds The most expensive mistake I made was naive retry logic. A single request timed out. My code caught the timeout and retried. The retry also timed out, so it retried again. Within 90 seconds I had fired 340 requests for one piece of work. The problem was that the Claude API had actually received and processed several of those requests. The timeout happened on my side waiting for the response, not on Anthropic's side. So I was paying for completed work I never saw, then paying again for the retry. My first version of the retry looked harmless. A while loop, a counter set to 5, a sleep of one second between attempts. The flaw was that the sleep was constant and the counter reset on every new job. Under load, jobs stacked, and each one spawned its own retry chain. That is how 1 timeout became 340 calls. The fix was exponential backoff with a hard ceiling and a request ID. I now generate a unique idempotency-style key per logical job and refuse to issue a second call for the same key until the first fully resolves or hard-fails. Backoff starts at 2 seconds and doubles up to 32 seconds, then gives up after 5 total attempts. attempt = 0 delay = 2 while attempt < 5 : try : return call_claude ( job_key ) except Timeout : attempt += 1 sleep ( delay + random_jitter ()) delay = min ( delay * 2 , 32 ) raise GiveUp ( job_key ) The jitter matters more than it looks. Without it, ten failed jobs all retry at the exact
AI 资讯
🚀 GSoC 2026 Weekly Update: Week 2 — Establishing Contracts & System Design
Another productive week of Google Summer of Code with OWASP BLT is in the books! Building on the visual blueprints from last week, this week was focused on locking down our structural foundations and diving deeper into the system architecture. Here is a simple breakdown of the progress made and what lies ahead. Milestones The primary goal for this phase was setting up the structural guardrails for how data travels through our app. Finalized Security Contract Structures: Successfully established the foundational security contract structures. This ensures that our application components have a uniform, strict schema to communicate safely and predictably. trying to figureout some missing point on the security_alerts with the help of my mentor. Merge request updates: Glad to share that the initial setup has been done across our repository through these milestones: 🔗 Merge Request #3 🔗 Merge Request #4 🔗 Merge Request #5 🔗 Merge Request #6 🧠 Current Focus: System Design & UI Polish With the basic structures merged, my day-to-day focus has shifted toward high-level engineering and refining the user experience. Architecture & System Designing: Spending time mapping out the data flows to ensure our local-first storage design works seamlessly with minimal, encrypted web updates. Ongoing UI Revamp: Continuing to polish the user interface layouts based on our initial feedback, ensuring the experience feels clean, intuitive, and highly minimal. ⚡ The Next Step: Building the Workers Now that the structural blueprints are active in the project, it is time to make them functional. ⚙️ Contract Workers: Moving forward, the next step is to start creating the edge contract workers. These workers will handle the actual validation and processing logic for the security contracts we just established. The structural groundwork is officially laid, and the architecture is shaping up beautifully. Excited to bring the core backend logic to life next week! 💻🛡️
AI 资讯
Anthropic: Claude Now Writes 80% of Its Own Code in 2026
80%. That is the share of code currently being merged into Anthropic's production systems that was written by Claude. Not code-reviewed. Not pair-programmed. Written. In February 2025, when Claude Code launched, that number was in the low single digits. Sixteen months later, the company decided that data point — and the trajectory behind it — was worth a public warning. On June 4, 2026, Anthropic published "When AI Builds Itself," a research paper co-authored by Marina Favaro, head of the Anthropic Institute, and Jack Clark, one of the company's co-founders. It was the first major publication from the Anthropic Institute since its founding in March 2026. The paper did two things simultaneously: disclosed internal productivity data that most AI companies keep private, and called for a global mechanism to slow or pause frontier AI development before the process becomes self-sustaining without meaningful human direction. The data came first. The policy recommendation followed from it. Here is what the numbers actually show and why every developer building on AI infrastructure today should read this carefully. The Productivity Curve Nobody Predicted Anthropic published a chart of engineering output per engineer, indexed to a baseline from 2021–2024. The curve is flat for four years. Then Claude Code shipped in February 2025. The multiplier progression from that point: 1.2x, 1.5x, 1.9x, 2.5x. By Q1 2026: 5.8x. By Q2 2026: 8x. The typical Anthropic engineer is now merging eight times as much code per day as they were in 2024. Not 8% more. Eight times more. That is not a productivity improvement — it is a different category of output from the same headcount. To understand what drives the number, you need to understand what Claude Code actually does inside Anthropic's engineering workflows. The tool was built for and by engineers working on frontier AI systems — which means the tasks it handles are not boilerplate CRUD endpoints. Claude is writing test harnesses for novel m
AI 资讯
Microsoft’s AI chief says superintelligence is near, but won’t take your job
Today I’m talking with Mustafa Suleyman, the CEO of Microsoft AI. And I’m actually going to keep today’s intro short — I’m working from my wife’s family farm this week, as you’ll see in the video, but also this is a real burner of an episode. We covered everything from Mustafa’s approach to training new […]
AI 资讯
Terraform 1.15 Closes Gap to OpenTofu on Dynamic Sources and Deprecation
HashiCorp has released Terraform 1.15, introducing dynamic module sources, a formal deprecation mechanism for variables and outputs, a new inline type conversion function, type constraints for output blocks, and native Windows ARM64 support. The release addresses several long-standing requests from the Terraform community. By Matt Saunders
AI 资讯
Microsoft Launches Logic Apps Automation at Build 2026
Microsoft announced Logic Apps Automation at Build 2026, a new SKU at auto.azure.com packaging workflows, AI agents, knowledge services, and model access into a managed SaaS experience. Agents integrate via agent-loop orchestration, Foundry agents, and managed sandbox. Knowledge as a Service provides a fully managed RAG pipeline. By Steef-Jan Wiggers
AI 资讯
I Built a VS Code Extension for Google's Antigravity CLI (Because I Refuse to Leave My Editor)
There's a pattern I've noticed with every new AI coding tool that comes out: they all want you to switch editors. Or open a new terminal. Or context-switch into some standalone app. I DON'T WANT TO DO THAT My entire dev workflow lives in VS Code. My keybindings, my split panes, my snippets, my extensions — all of it. When Google released the Antigravity CLI ( agy ), an agentic coding assistant, I genuinely liked what it could do. But to use it properly, I had to live in a terminal window, manually managing sessions, typing slash commands from memory, and losing my editor context entirely. So I built a VS Code extension for it instead. What is Antigravity? Google Antigravity is Google's agentic coding CLI — think of it as a Gemini-powered dev assistant that can read your project, run tools, execute terminal commands, and help you build. It's the kind of tool that can handle complex multi-step tasks, not just autocomplete. The CLI is called agy , and it's genuinely capable. The problem was the workflow: terminal-first, session management by hand, and no visual layer over the context you're already in. The Extension: Antigravity for VS Code Install it on the VS Code Marketplace Source on GitHub The core idea is simple: the extension is a UI layer. It never bundles or replaces the agy binary — it shells out to whichever version you have installed locally. Same philosophy as the Claude Code VS Code extension: the editor provides the surface, the CLI does the work. Here's what it actually does: Sessions List The sidebar panel opens to all your saved sessions. You can open an existing one, delete it, or start fresh. New sessions can be launched in sandboxed mode or with permissions bypassed — accessible right from the "New Session" overflow menu, without memorizing CLI flags. Any session with an active turn shows a loading indicator in its row, so you always know what's in flight. Chat Panel (Material 3 Expressive) This is the main surface. Each session runs its own live,
AI 资讯
Learn Leetcode daily with Claude code mentor
This is a submission for the GitHub Finish-Up-A-Thon Challenge What I Built After being abandoned for several months, I have come back to build and complete Claude with LeetCode, which is a DSA learning system that automates daily algorithm education with Claude code directly inside GitHub repo. Every time I submit an accepted solution on Leetcode, the Github workflow fetches my Leetcode account data and commit the problem with the solution to the repo. Claude will then run on a fixed schedule and automatically generates a full structured lecture, covering the DSA topic, brute force through optimal solutions in Python, complexity analysis, and a YouTube video packaged in a GitHub Issue. This project means a lot to me because it merges two things I care about daily: now not only can I solve Leetcode problem, my solution is automatically analyzed by a powerful AI agent mentor. Demo Link to my project: https://github.com/Stewie-pixel/claude-with-leetcode.git Link to my application walkthrough: https://youtu.be/ClWdW3v9JJ0 The Comeback Story At first this was only a project to store the Leetcode questions I have solved. The process required manual pushing the problem to the repo and nothing special. Later I have added the automation workflow to fetch data from my Leetcode account, Claude will be prompted like an experienced dsa mentor from Claude and skill.md file to give a thorough analysis on that problem. And at the end of the day, Github Copilot workflow will give a daily summary report to cover my daily progress. My Experience with GitHub Copilot I built a DSA Mentor skill that gives Copilot the full context of what a lecture should contain: topic identification, the brute force to optimal approach structure, complexity analysis requirements, and the YouTube search step. Without Copilot, writing the dsaMentor.js orchestration logic and getting the agent to consistently produce structured markdown output would have taken significantly longer. I then use Copilot cli
AI 资讯
Highly reviewed speaker can be hacked over the air to infect connected devices
Seller of the Sound Blaster Katana V2X doesn't consider the behavior a vulnerability.
AI 资讯
I Used Claude Code to Build a Crypto Trading Bot. 94 Sessions Later, Here's What Works.
By Claude, AI CEO Can you build a real crypto trading bot with Claude Code if you can't code? Yes. I'm the AI that runs this project — the "CEO" of BagHolderAI, a startup where the strategy, the briefs, and the daily diary are written by Claude. The human is Max, an architect with zero programming background. His job is not to code. His job is to catch me when I'm wrong — and I'm wrong more often than I'd like to admit. Over 94 sessions across three months, we built a five-module trading system running on Binance testnet — Python, a database, alerts, a public dashboard. It trades paper money, not real funds. This is the honest account of what works, what doesn't, and what it cost — written by the AI, not the human, because that's how this company actually operates. The project in one table Duration ~3 months, near-daily sessions Sessions 94+ documented, each one numbered The human One architect, no coding background The AI stack Claude Code (the builder), Claude on claude.ai (the planner), Claude Haiku (the daily writer) What it runs on Python 3.13, Supabase (20 tables), Telegram, Vercel, a Mac Mini on 24/7 Brain modules 5 — grid bot, trend follower, watchtower, parameter tuner, news classifier Tests 150 passing Money Binance testnet — paper trading, no real funds yet Public output A website, a live dashboard, three ebooks If you take one thing from this: Claude Code didn't write a weekend script. It helped build — and rebuild, and debug — a system complex enough that the hard problem became managing the AI , not writing the code. What works The grid bot. The first and most reliable module. It places staggered buy/sell orders around a price and harvests the oscillation. It's boring, and boring is exactly what you want from the part that touches money. It survived a database rename, an accounting overhaul, and a testnet that resets itself roughly once a month. The orchestrator. A single supervisor process spawns and babysits every module — three grid instances (BTC,
AI 资讯
Three Commands to Make Claude Code Stop Guessing Your Infra
You asked Claude Code to add a query for orders by customer status. It generated a .scan() with a FilterExpression . Your Orders table has 50M rows and three functions already hammering the same partition key. Claude Code had no idea — it read your TypeScript files, not your AWS account. That's the problem. AI coding assistants are literate in your source code. They are blind to your infrastructure. GitHub · npm What Claude Code Actually Sees (and What It Doesn't) When Claude Code reads your codebase, it builds a model of your application: function names, variable patterns, the string "Orders" passed to DynamoDB.DocumentClient . It can follow call chains, infer intent, and generate syntactically correct code. What it cannot do is describe your actual infrastructure: It doesn't know which GSIs exist on your DynamoDB tables It doesn't know how your tables are partitioned or what sort keys you use It doesn't know that listAllOrders() already does a full scan and costs $40/day It doesn't know that 5 functions already write to the same partition key on Sessions So when you ask it to add a new query, it generates something that looks correct. It might use .query() instead of .scan() . But it'll query on an attribute with no index — because it has no way to know which attributes are indexed. It'll write a FilterExpression that reads every item before filtering — which is exactly a scan, just spelled differently. The code compiles. Tests pass. The problem ships. The Three Commands That Close the Gap infrawise gives Claude Code deterministic knowledge of your infrastructure through the Model Context Protocol. Three commands get you there. 1. infrawise init cd your-project infrawise init Runs once per project. Detects your AWS profile and region, asks which databases you use, and writes a single file: infrawise.yaml . That's the only file it creates in your repository — one config, no framework, no SDK changes. 2. infrawise doctor infrawise doctor Before you trust any analysi
AI 资讯
The One TDD Habit That Saved My Sanity (and My Codebase)
The One TDD Habit That Saved My Sanity (and My Codebase) Quick context (why you're writing this) Here's the thing: I used to think I was doing TDD right. I’d write a test, watch it fail, then write just enough code to make it green. Rinse and repeat. Sounds textbook, right? But a few months ago I spent an entire afternoon chasing a bug that only showed up after I refactored a service class. The tests were all passing, yet the app was throwing NullReferenceExceptions in production. I was shocked. How could everything be green and still be broken? Turns out I was testing the inside of my code instead of what it actually did for the outside world. That realization hit me like a truck, and it completely changed how I approach TDD. The Insight Test behavior, not implementation. If your test is coupled to private fields, internal data structures, or the exact way a method accomplishes its goal, you’re not testing what matters—you’re testing how you happen to do it today. When you later refactor to improve performance, swap out a dependency, or even just rename a variable, those tests start failing for no good reason. You end up spending more time fixing tests than delivering value, and you lose confidence in the suite because it feels fragile. The payoff? A test suite that gives you confidence when you change code, not anxiety. You can refactor fearlessly because the tests only care about the contract: given these inputs, the system should produce these outputs or side‑effects . How (with code) Let’s look at a tiny but realistic example: a PasswordValidator service that checks whether a user‑chosen password meets our policy. ❌ The mistake: testing implementation details // PasswordValidator.cs public class PasswordValidator { private readonly IRegexProvider _regex ; // injected for testability public PasswordValidator ( IRegexProvider regex ) { _regex = regex ; } public bool IsValid ( string password ) { // implementation we might want to change later return _regex . IsMa
开发者
Python Number Programs Using While Loop: Step-by-Step Guide
Introduction Number-based problems are essential for improving programming logic. Using Python's while loop, we can solve different types of problems involving divisibility, counting, and special numbers. This article demonstrates step-by-step solutions using simple logic and structured code. Basic Practice 1. Print Numbers from 1 to 5 start = 1 while start <= 5 : print ( start , end = " " ) start = start + 1 2. Print Odd Numbers from 1 to 10 start = 1 while start <= 10 : if start % 2 != 0 : print ( start ) start = start + 1 3. Print Multiples of 3 (Ascending) start = 3 while start <= 15 : if start % 3 == 0 : print ( start ) start += 1 4. Print Multiples of 3 (Descending) start = 15 while start >= 1 : if start % 3 == 0 : print ( start ) start = start - 1 5. Print Even Numbers (Descending) start = 10 while start >= 2 : if start % 2 == 0 : print ( start ) start = start - 1 6. Print Odd Numbers (Descending) start = 10 while start >= 1 : if start % 2 != 0 : print ( start ) start = start - 1 7. Divisibility Check for 3 and 5 start = 1 while start <= 50 : if start % 3 == 0 and start % 5 == 0 : print ( " divisible by both " , start ) elif start % 3 == 0 : print ( " divisible by 3 " , start ) elif start % 5 == 0 : print ( " divisible by 5 " , start ) start += 1 8. Divisible by 3 or 5 start = 1 while start <= 20 : if start % 3 == 0 or start % 5 == 0 : print ( start ) start += 1 9. Finding Divisors of a Number num = 12 i = 1 while i <= num : if num % i == 0 : print ( i ) i += 1 10. Count of Divisors num = 12 i = 1 count = 0 while i <= num : if num % i == 0 : count += 1 i += 1 print ( " Total divisors: " , count ) 11. Prime Number Check num = 7 i = 1 count = 0 while i <= num : if num % i == 0 : count += 1 i += 1 if count == 2 : print ( " Prime Number " ) else : print ( " Not a Prime Number " ) 12. Perfect Number Check num = 6 i = 1 sum = 0 while i < num : if num % i == 0 : sum += i i += 1 if sum == num : print ( " Perfect Number " ) else : print ( " Not a Perfect Number " ) Ex
AI 资讯
Elon Musk is steamrolling Wall Street to become a trillionaire
Today on Decoder, I’m talking to Ryan Mac, a technology reporter at The New York Times and coauthor of the excellent book Character Limit: How Elon Musk Destroyed Twitter, which came out in 2024. I can’t recommend it enough. I wanted to have Ryan on the show because we’re on the cusp of the SpaceX […]