AI 资讯
AI人工智能最新资讯、模型发布、研究进展
共 12735 篇 · 第 39/637 页
OpenAI admits its models hacked Hugging Face on their own
Open source AI platform Hugging Face revealed a security breach a few days ago. Turns out OpenAI's models were the culprit.
Ebook Reviewer Wanted: Help Me Find What's Gone Stale
Technical books have a shelf life that nobody prints on the cover. A cookbook from 2018 still works. A history book from 2018 still works. A Laravel book from 2018 will teach you a middleware pattern that was replaced twice, recommend a package whose maintainer archived it, and show you a test suite in a syntax that no longer runs. I've written a series of ebooks on PHP, OOP, SOLID, design patterns, Laravel conventions, testing with Pest, application architecture, and AI-assisted development. There are also two aimed at kids learning to code. Every one of them was correct when I wrote it. That is a much weaker claim than "correct now," and I'd rather find the gap myself than have a reader find it for me. So: I'm opening the series to technical reviewers before the final edition ships. Applications close Sunday, 26 July. Why I can't do this alone Not because I lack the time. Because I lack the distance. When you write a technical book, you build a mental model of the reader and then you write to that model for months. The model is always partly wrong, and you are the last person who can see how. You skip a step because it's obvious to you. You keep an example that made sense when you drafted the chapter and no longer matches the surrounding code. You cite a package because it was the right answer for a project you shipped two years ago, and you never checked whether it's still maintained. None of this shows up on a reread. Rereading your own work is mostly pattern-matching against your own memory. You see what you meant, not what you wrote. A reviewer who has never seen the manuscript reads what's actually on the page. That's the whole value, and it's not something more effort on my side can substitute for. What the job actually is You pick one book from the series. You read it properly — not skim it — and you flag what's broken. Four things in particular: Things that are outdated. The framework moved, the syntax changed, there's now a cleaner way to do the same thin
The future of AI coding isn't better prompts. It's better engineering constraints.
Over the past few months, I've noticed that most discussions around AI coding assistants focus on prompts. People share: .cursorrules AGENTS.md CLAUDE.md long prompt templates custom instructions The assumption is always the same: "If I explain my engineering practices clearly enough, the AI will follow them." For simple projects, that works. For real software projects, it eventually breaks down. The problem isn't intelligence. It's governance. Every AI coding assistant eventually produces something like this: giant functions skipped tests undocumented architectural decisions ignored security practices direct commits inconsistent commit messages missing pull request descriptions Not because the model suddenly became "worse". Because nothing prevents it from taking shortcuts. Exactly like humans. We already solved this problem... for humans. Professional software engineering has never relied on trust. Instead, we built systems that enforce discipline. We don't ask developers to: write tests We fail CI. We don't ask them to: use meaningful commit messages We reject the commit. We don't ask them: not to push directly to production Protected branches make it impossible. Engineering isn't based on trust. It's based on constraints. Yet with AI... ...we went backwards. Instead of constraints, we write instructions. We create increasingly sophisticated prompt files hoping the assistant will remember them. Always write tests. Always document architectural decisions. Use GitHub Flow. Follow OWASP. Keep functions below 40 lines. Never commit directly to main. Those aren't guarantees. They're suggestions. And suggestions are eventually ignored. Rules are not enforcement. Recently I came across an article making a simple observation: Rules without enforcement are just hopes. That sentence stayed with me. It perfectly describes the current state of AI-assisted development. An AI may fully understand your engineering rules. It may even agree with them. But unless something checks
Voice Agent Turn-Taking: Stop Live AI Calls From Talking Over Users
Voice agents do not usually fail because the model is “not smart enough.” They fail in the awkward half-second where the user pauses, breathes, corrects themselves, or interrupts while the AI is still talking. That tiny moment decides whether the product feels useful or robotic. If your live AI call cuts people off, talks over them, ignores barge-in, or waits so long that users repeat themselves, no prompt will save the experience. The fix is not one magic model. It is a turn-taking system: audio signals, semantic checks, interruption rules, streaming, and metrics that work together. This guide walks through a practical voice agent turn-taking design you can ship in a real product. Why turn-taking is the real voice agent bottleneck Text chat is forgiving. A user types. The model answers. If the response takes two seconds, the user may still wait. Voice is different. Humans expect conversation to move quickly. A delay feels like confusion. An early response feels rude. Talking over the user feels broken. A production voice agent has to answer three questions again and again: Is the user still speaking? Is the user finished enough for the agent to respond? If the user interrupts, should the agent stop, listen, or continue? Most teams start with a simple pipeline: Microphone -> Speech-to-text -> LLM -> Text-to-speech -> Speaker That is enough for a demo. It is not enough for a live workflow where the caller changes their mind, uses filler words, speaks in a noisy room, or interrupts because the AI misunderstood them. The practical goal is not “lowest latency at any cost.” The goal is comfortable turn timing : fast enough to feel alive, patient enough to avoid cutting people off, and interruptible enough to recover when the user takes control. Research signals behind this topic Recent AI platform activity points toward live agents moving from demos into production workflows: Product launches are emphasizing embedded live agents that can see, speak, and operate inside so
The Hard Part of a Global Birth-Chart Calculator Was Time
A birth-chart form looks simple: ask for a date, time, and place, then calculate. The interface may be simple. The input is not. 1992-11-01 01:30 does not identify one universal instant. It is a wall-clock reading that only becomes meaningful after you resolve the place, the historical time-zone rule, and any daylight-saving transition. If the time is unknown, inventing a convenient default can create chart features that were never supported by the user’s data. I ran into these problems while building AstroZen , a Next.js application that calculates a BaZi Four Pillars chart and a Western natal chart before generating an optional interpretation. The most important architectural decision was this: Calculation is an evidence pipeline. Interpretation is a separate layer. This post explains the calculation pipeline, the failure modes I had to remove, and why “unknown” must remain unknown. 1. A city name is not a coordinate Early prototypes often use a short city list or a default coordinate. That works for a layout demo, but it is not acceptable once location affects the result. Names are ambiguous: Paris can mean France or Texas. Springfield needs a state or region. Country abbreviations come in several forms. A valid city must resolve to both coordinates and a time-zone identifier. AstroZen sends the submitted city to Open-Meteo’s geocoding service, then scores the returned candidates against the requested country and optional region hint. It keeps the following structured result: type ResolvedPlace = { name : string ; region : string | null ; country : string ; countryCode : string ; latitude : number ; longitude : number ; timeZone : string ; // IANA, for example "Europe/Madrid" }; Candidate selection considers exact city-name matches, country matches, an optional region hint, and population as a small tie-breaker. Population never replaces the country check. The more important rule is what happens when resolution fails: if ( ! selected || ! countryMatches ( selecte
Is Your AI Agent Production-Ready? Define the Bar First
Every team shipping an agent has the same meeting. Someone asks "is it ready?" and the room splits. One person saw a great demo. Another watched it invent a refund policy an hour ago. The argument runs in circles because nobody agreed what "ready" means, so the loudest opinion wins and the agent ships on a vibe. Making an AI agent production-ready is not a moment of confidence. It is a bar you write down before you build, then measure against. This post is about that bar: why agents need a different one than the services you already ship, and how to define it so "is it ready?" becomes a number instead of an argument. Why "production-ready" breaks for agents For a normal service, "production-ready" is settled. Correct output for valid input, handles errors, meets a latency target, has tests and a rollback. You know the shape of done. An agent breaks three of those assumptions at once: It is non-deterministic. The same input can produce different output, so "correct" becomes "acceptably right, often enough." Its failure surface is open-ended. A function fails in ways you enumerated; an agent fails in ways you never imagined, because it composes language, tools, and judgment on the fly. Its worst case is not a 500 error. It is a confident wrong answer that looks right, which is far more expensive than a crash, because a crash at least tells you it failed. So the honest question is not "is the agent correct." It is "is the agent acceptably wrong, safely, within budget, and repeatably enough to trust." That question has four parts, and each is a line on your bar. The four lines of the bar Write these down before you build. If you cannot fill them in, you do not have a spec, you have a wish. Task success. On a fixed set of real tasks , not the happy-path demo, what fraction must the agent complete correctly? Pick the number. 85 percent means one in seven users gets a wrong answer. Acceptable for this job, or fireable? Decide on purpose. Failure acceptability. Not all wron
从FROST到FROST-SOP:如何用家族治理模型打造你的"AI分身"?
从FROST到FROST-SOP:如何用家族治理模型打造你的"AI分身"? 作者 :神通说 日期 :2026-07-22 主题 :双项目联动 | 周三轮换 阅读时间 :10分钟 开场:一人公司的终极困境 你是否有这样的体验? 每天醒来,脑子里塞满了要做的事: 写推广文章 回复客户咨询 跟进项目进度 整理会议纪要 复盘昨天数据 一个人做公司,听起来很自由。实际上, 自由职业者的时间比上班族更碎片 ——因为所有事情都堆在你一个人身上,没有任何分工。 我一直在思考一个问题: 能不能用AI Agent来"复制"自己? 不是那种"给你一堆提示词让你自己写"的AI工具,而是真正能 自主执行任务、自动汇报结果、帮你分担80%重复工作 的数字分身。 这个想法最终落地成了两个项目: FROST 和 FROST-SOP 。 第一站:FROST的家族治理模型——AI Agent应该像家族一样分工 FROST 的核心理念来自一个观察: 自然界最稳定的组织形式不是公司,而是家族。 家族有清晰的分工: 祖辈定规矩,不亲自下场 父辈协调全局,分配任务 子辈执行具体事务 把这个逻辑映射到 AI Agent,就是 FROST 的家族治理模型: ┌─────────────────────────────────────────────────────┐ │ 👑 君主(你) │ │ └── 发布任务、查看结果,不干预执行 │ │ │ │ 👴 祖辈(主Agent) │ │ └── 常驻、全局编排、拆解任务 │ │ ↓ │ │ 🕵️ 斥候(侦查Agent) │ │ └── 外出狩猎、收集情报、快速验证 │ │ ↓ │ │ ⚔️ 府兵(执行Agent) │ │ └── 领命执行、重复劳动、汇报结果 │ │ ↑ │ │ 📜 长老(监督Agent) │ │ └── 记录过程、沉淀教训、审计合规 │ └─────────────────────────────────────────────────────┘ 关键洞察: 祖辈是唯一"常驻"的,其他都是动态生成、执行完就解散的临时角色。 这个模型解决了一个核心问题: 谁来决定"这件事该派给谁"? 答案是: 祖辈 。它不需要亲自执行,只需要决定"派谁去"和"怎么汇报"。 第二站:用FROST的四个原子,理解Agent的本质 FROST 只有四个核心概念,却能构建出完整的家族治理系统: from frost.core import Store , Agent , skill_set , skill_get # 四个原子: # 1. Store(记忆)—— Agent的工作空间 store = Store () # 2. Skill(能力)—— 纯函数,无状态 def collect_daily_tasks ( context ): """ 收集今日任务 """ tasks = [ " 写推广文章 " , " 回复客户 " , " 跟进项目 " ] context [ " tasks " ] = tasks return context def execute_task ( context ): """ 执行单个任务 """ current_task = context . get ( " current_task " , "" ) context [ " result " ] = f " 已完成: { current_task } " return context # 3. Agent(细胞)—— 包裹记忆和能力 daily_agent = Agent ( " daily_worker " , store , skills = { " collect " : collect_daily_tasks , " execute " : execute_task }) # 4. SOP(宪法)—— 定义执行顺序 result = daily_agent . run ( sop_steps = [ " collect " , " execute " ], initial_context = { " current_task " : " 写推广文章 " } ) print ( result [ " result " ]) # 输出:已完成: 写推广文章 这四个原子教会我们什么? Store 解决"记忆"问题——Agent需要上下文 Skill 解决"能力"问题——每个动作必须是可复用的单元 Agent 解决"封装"问题——把记忆和能力绑定在一起 SOP 解决"秩序"问题——让执行顺序可控可审计 理解了这四个原子,你就理解了 Agent 的本质—— 它不是魔法,是结构化的委托系统 。 第三站:FROST-SOP——把家族治理变成生产系统 FR
Next.js 16 on Cloudflare Workers: what broke and what didn't
I shipped a Next.js 16 app on Cloudflare Workers via OpenNext. Not a demo. A real product with streaming chat, server components, D1 at the edge, and anonymous user sessions. Here is what broke, what barely worked, and what turned out to be surprisingly fine. The stack Next.js 16.2 (App Router) @opennextjs/cloudflare 1.19 D1 for SQLite at the edge Streaming chat via the AI binding (DeepSeek-V3 through a Workers proxy) React 19 Tailwind CSS 4 No auth wall, no OAuth, no database on the origin The site runs a few thousand sessions a week across ~30 persona pages, blog posts, guides, and learning content. Most pages are statically generated. The chat interaction is server-rendered components with streaming responses. What worked surprisingly well Static generation and ISR Pages, blogs, guides, persona pages — everything that does not need user-specific rendering — runs as static HTML at deploy time. Next.js 16 with generateStaticParams and fetch caching worked without modification. OpenNext handles the Cloudflare output format. The build step produces something Workers can serve. Revalidations are limited to Workers' cache API, but since most content changes at deploy time, I never hit that limit in production. The one caveat: revalidateTag() does not work the same way in a Workers runtime. Tags are Node.js memory constructs, and Workers are stateless. If you depend on tag-based revalidation for content updates, you need to either trigger deploys or accept stale-while-revalidate behavior from the CDN. D1 at the edge D1 was the least surprising part of the stack. SQL queries from Next.js route handlers feel like calling a regular database. Sessions store in D1, messages store in D1, and the latency is low enough that restoring a full chat thread from 30 messages takes under 200ms cold. The only sharp edge: D1 connections count against your Worker's concurrent request limit in development. With Next.js making its own fetch calls for compilation, I hit the D1 connection ce
The Anthropic-Physical Intelligence rumor roiling AI Twitter
Anthropic and OpenAI's aggressive 2026 acquisition sprees set the stage for a weekend rumor.
I Couldn’t Fix My LLM Costs Until I Measured Tokens Per Feature
My LLM bill kept growing, so I did what seemed obvious: I looked for a cheaper model. That helped a little, but it didn't explain why the bill was growing. The dashboard could tell me how many tokens the application used. It couldn't tell me what those tokens were doing. Were they coming from chat? Document summaries? Background classification? An agent retrying the same tool call? I was trying to optimize a total without knowing which product feature created it. The useful unit wasn't tokens per model . It was tokens per feature . Model-level totals hid the real problem A provider dashboard usually groups usage by model, API key, project, or time period. That is useful for billing, but not always for product decisions. Imagine an application with four LLM-powered features: interactive chat document summarization support-ticket classification an agent that prepares weekly reports If the bill increases by 30%, the model name doesn't explain which feature changed. Maybe chat traffic grew. Maybe summarization started sending entire documents instead of selected sections. Maybe the classifier received a much larger system prompt. Maybe the report agent retried after tool failures and generated the same plan several times. Those problems require completely different fixes. Switching every request to a cheaper model would reduce the bill, but it could also hide the engineering mistake. Tag every request with a feature I started giving every LLM call a small amount of application context: const context = { feature : " document_summary " , operation : " initial_summary " , customer_tier : " pro " }; The model provider doesn't need these fields. They belong in the application's usage record. I avoid using individual user IDs as the primary grouping dimension. For cost analysis, a product feature, workflow, or operation is normally more useful and creates fewer privacy problems. A practical record looks like this: { "timestamp" : "2026-07-22T03:12:48.201Z" , "feature" : "docu
reconmatch: offline transaction matching for people who reconcile for a living
reconmatch is a local-first transaction matching engine for accountants, bookkeepers, and controllers. Two CSVs in — books vs bank, invoices vs payments — a scored, auditable match report out. No account, no upload, no network call. Repo: github.com/SybilGambleyyu/reconmatch The unglamorous pain If you close books for a living, you already know the scene: two windows open, a bank CSV on the left, a general-ledger export on the right, and an afternoon disappearing into "which deposit is which invoice." Bank feeds help until they do not. The hard cases are ordinary: One deposit that covers three invoices Two payouts that sum to one sales batch on the books A check number in the memo on one side and a dedicated column on the other "ACH ACME CORP INV 1042" vs "Invoice payment ACME Corp" An orphan the feed never explained Enterprise close tools charge enterprise prices and want the data in their cloud. For a CPA firm or bookkeeper sitting on confidential client ledgers, "just upload the CSV" is often a non-starter. Spreadsheet VLOOKUP falls over on partial payments and batch deposits. What reconmatch does Matching runs in deterministic phases so the same inputs always produce the same proposals: Exact / reference-strong — amount within tolerance, date in window, shared invoice/check/wire token Amount + date — numbers line up even when memos are noise Fuzzy description — token overlap plus sequence similarity (pure Python stdlib) Group 1:N and N:1 — one line equals the sum of several on the other side Every accepted match carries a score and human-readable reasons suitable for a workpaper. Unmatched lines stay unmatched — the tool does not invent a story for them. pip install git+https://github.com/SybilGambleyyu/reconmatch.git reconmatch books.csv bank.csv -o ./march-recon Outputs: plain-text report, matches CSV, unmatched CSV, and full JSON. Zero required third-party dependencies. Python 3.10+. Library use from reconmatch import MatchConfig , match_transactions from rec
Why I Switched to Plain Text Accounting
Why I Switched to Plain Text Accounting Mint is shutting down. After 10 years of financial tracking, I am losing my data again. This time, I switched to plain text accounting with Beancount. The Problem with Traditional Apps Traditional financial apps have several issues: Export limitations : They only provide summary reports, not raw transaction data Proprietary formats : Data is stored in closed databases that require specific software to read Platform lock-in : Different systems are incompatible with each other Financial records are long-term. Over the past decade, dozens of financial apps have shut down, leaving users with years of records wiped out. The Plain Text Solution Plain text accounting with Beancount offers a different approach: Data Sovereignty Your data belongs to you. You can: Open it with any text editor Read it directly as a human Access it permanently, without depending on specific software Process it freely and completely Migrate with near-zero cost Future-Proof Plain text files will remain readable decades from now. They do not depend on any company staying in business or maintaining compatibility with legacy systems. Making the Switch The learning curve was worth it. I now have: Complete control over my financial data No vendor lock-in Confidence that my records will exist as long as I want them to Your data, your sovereignty. PersonalFinance #Fintech #DataSovereignty #Beancount
Zero failures isn't zero risk: the rule of three for evals
The rule of three for evals says zero failures in N runs is a count, not a rate. With 0 failures in N independent runs, the exact 95% upper bound on the true failure rate is 1 - 0.05^(1/N) , which 3/N approximates. After 100 clean runs you still cannot rule out a 2.95% rate, about 1 in 34. Here is the reading that bites you. Your eval harness runs the agent 100 times, prints "0 failures," and the tile goes green. Someone screenshots it into the launch thread. The unspoken translation is "the failure rate is zero." It is not what the data says. I wrote a small script to make the gap concrete, so I ran a real gate over 200 deterministic agent runs first, counted honestly, and got the dashboard everyone trusts: gate: spend<=budget over 200 deterministic agent runs observed failures: 0 (distinct scenarios: 200) naive point rate : 0.00% binomial SE: 0.00 pp naive 95% CI : [0.00%, 0.00%] <- zero width: false certainty Look at the standard error. For a zero count the binomial SE is sqrt(0*1/200) , which is exactly 0, so the naive 95% interval collapses to [0.00%, 0.00%] . A zero-width confidence interval. The math is telling you it is completely certain, from 200 samples, that the true rate is precisely zero. That is obviously wrong, and it is the exact shape of every "all green" board I have ever trusted too much. TL;DR "0 failures in N runs" is an observed count, not a rate. The naive binomial SE of a zero count is 0, which is why a green board looks like proof and isn't. The honest number is the one-sided upper bound. With 0 failures in N runs, the 95% upper confidence limit on the true failure rate is 1 - 0.05^(1/N) . The rule of three, 3/N , approximates it and rounds the risk slightly up. At N=30 the bound is 9.50% (about 1 in 11). At N=100 it is 2.95% (1 in 34). At N=1000 it is 0.30% (1 in 334). Zero failures in 30 runs is compatible with a 1-in-11 true failure rate. To rule out a 0.1% rate at 95% you need about 2995 clean runs, not 50. "We ran it fifty times" and "
How We Translate Entire Books with LLMs Without Losing Context
Solving the context-window puzzle for book-length AI translation. At LectuLibre, we set out to build a service that translates entire books using large language models. The idea is simple: upload an EPUB or PDF, choose a language, and receive a polished translation. But behind the scenes, translating a hundred-thousand-word novel with LLMs isn't straightforward. The core challenge is context — LLMs have limited context windows, and books are long. Simply chopping the text into chunks and feeding each one independently leads to incoherent output. Character names change, pronouns lose referents, and tone veers wildly. Here’s how we solved that with a chunking strategy that preserves context, and the Python code that makes it tick. The Problem: Long Documents vs. Short Context Windows Modern LLMs like Claude 3 Opus can handle 200,000 tokens of context, while DeepSeek-V2 offers 128,000 tokens. That’s a lot — but a 50,000-word English novel translates to roughly 67,000 tokens (using Claude’s tokenizer). That just fits, but what about a 150,000-word fantasy epic? Even when it fits, sending an entire book in one prompt is costly, slow, and often degrades attention quality on long texts. The prevailing approach is to chunk the document. Naive chunking — say, splitting by a fixed token count — creates hard boundaries. One chunk ends, another begins, and the LLM has no idea what happened before. The result reads like a patchwork of isolated translations. We needed a method that gives each chunk enough surrounding context without exceeding token limits or breaking the bank. Our Approach: Sliding Window + Context Retrieval via Embeddings We adopted a two‑pronged strategy: Overlapping chunks : each chunk shares some sentences with the previous one, so the LLM can transition smoothly. Injected context : for every chunk, we retrieve and prepend the most relevant previous chunks, determined by embedding similarity. This way, the model always has a sense of what’s happening before a
canitbebuilt
Your hardware idea, inspected. Verdict, BOM, 3D model. Discussion | Link
Running PostgreSQL with Docker
Installing Postgres directly on your machine works, but it gets messy fast once you're juggling multiple projects that each want different versions, extensions, or seed data. Docker sidesteps all of that you get a clean, disposable Postgres instance per project, and your host machine stays untouched. This guide covers running Postgres in Docker for local development: quick one-off containers, docker-compose for anything you'll come back to, persistent data, and a few things that trip people up. 1. The quickest way to get a Postgres instance running docker run --name my-postgres \ -e POSTGRES_PASSWORD = secret \ -e POSTGRES_USER = devuser \ -e POSTGRES_DB = myapp \ -p 5432:5432 \ -d postgres:16 Breaking that down: --name my-postgres — a friendly name so you can reference the container later instead of a random hash POSTGRES_PASSWORD — required; the container won't start without it POSTGRES_USER / POSTGRES_DB — optional; default to postgres if omitted -p 5432:5432 — maps container port 5432 to host port 5432 -d — detached, runs in the background postgres:16 — pin a version; avoid latest since it can silently jump major versions later Check it's running: docker ps Connect with psql (if installed locally) or from inside the container: docker exec -it my-postgres psql -U devuser -d myapp 2. Using docker-compose for anything persistent For a real project, docker-compose.yml is the better default , it's version-controlled, reproducible, and easy to extend with more services later (Redis, pgAdmin, your app itself). services : db : image : postgres:16 container_name : myapp-postgres restart : unless-stopped environment : POSTGRES_USER : devuser POSTGRES_PASSWORD : secret POSTGRES_DB : myapp ports : - " 5432:5432" volumes : - pgdata:/var/lib/postgresql/data volumes : pgdata : Start it: docker compose up -d Stop it (keeps data): docker compose down Stop and wipe data: docker compose down -v 3. Why the volume matters Without a named volume, all data lives inside the container's
How an AI Anime Is Created
GORM: Dev's Guide to Go's Most Popular ORM
If you're working with Go services that talk to a relational database, chances are you've bumped into GORM . It's the most widely used ORM in the Go ecosystem, and for good reason. It wraps a lot of the tedium of database/sql ,manual scanning, hand-written migrations, string-built queries in a much friendlier API. This article walks through GORM from setup to the patterns you'll actually use day to day: models, migrations, CRUD, associations, transactions, and a few gotchas that trip people up. Why reach for an ORM in Go ? Go's standard database/sql package is deliberately low-level. You write SQL strings, manually scan rows into structs, and manage connections yourself. That's fine for small projects, but it gets repetitive fast once you have a dozen tables and endpoints that all need similar create/read/update/delete logic. GORM sits on top of database/sql and gives you: Struct-based models mapped to tables Auto migrations A chainable query builder Associations (has-one, has-many, many-to-many, belongs-to) Hooks (before/after create, update, delete) Built-in support for transactions, connection pooling, and prepared statements It supports PostgreSQL, MySQL, SQLite, SQL Server, and more, through swappable drivers. Installation go get -u gorm.io/gorm go get -u gorm.io/driver/postgres Swap postgres for mysql , sqlite , or sqlserver depending on your database. Connecting to a database package main import ( "log" "gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger" ) func main () { dsn := "host=localhost user=postgres password=secret dbname=myapp port=5432 sslmode=disable" db , err := gorm . Open ( postgres . Open ( dsn ), & gorm . Config { Logger : logger . Default . LogMode ( logger . Info ), }) if err != nil { log . Fatalf ( "failed to connect to database: %v" , err ) } sqlDB , err := db . DB () if err != nil { log . Fatalf ( "failed to get generic db object: %v" , err ) } sqlDB . SetMaxOpenConns ( 25 ) sqlDB . SetMaxIdleConns ( 10 ) } That db.DB() call gi
Write Code You Can Still Read 6 Months Later
I'm AlanWu. I'm in junior high. I've written a lot of bad code. Here's what I changed to make it less bad. 1. Name things like a human // Don't do this int d ; // days? distance? damage? int cnt = 0 ; // "cnt" — you know, the classic vector < int > v ; // v of what // Do this int daysUntilDeadline ; int errorCount = 0 ; vector < int > studentScores ; Full words, no abbreviations. idx instead of i in loops is fine. But sz for size, cnt for count, ptr for pointer — just type the word. You're not being charged by the character. 2. Functions should do one thing If you need the word "and" to describe a function, split it. // Bad: does two things, name lies void loadAndValidateConfig () { readFile (); checkSyntax (); } // Better Config loadConfig ( string path ) { return parseConfig ( readFile ( path )); } bool validateConfig ( const Config & cfg ) { return cfg . width > 0 && cfg . height > 0 ; } My rule of thumb: if a function is longer than what fits on one screen, break it. If I can't describe what it does in one sentence without "and", break it. 3. Comments explain WHY, not WHAT // Bad — tells me what the code already says // Loop through all students for ( auto & s : students ) { s . score += 5 ; } // Good — tells me WHY, which the code can't // Extra credit: 5 points for submitting early for ( auto & s : students ) { s . score += 5 ; } If you're writing a comment that just restates the next line of code, delete it. The only comments worth keeping are the ones that answer "why did I do it this way?" 4. Don't nest too deep // Bad — 3 levels deep, I've already forgotten what the top level was for ( auto & student : students ) { if ( student . hasSubmitted ()) { for ( auto & answer : student . answers ) { if ( answer . isCorrect ()) { score ++ ; } } } } // Better — flatten with early exits for ( auto & student : students ) { if ( ! student . hasSubmitted ()) continue ; for ( auto & answer : student . answers ) { if ( ! answer . isCorrect ()) continue ; score ++ ; } } Al