今日已更新 233 条资讯 | 累计 20205 条内容
关于我们

标签:#tutorial

找到 373 篇相关文章

AI 资讯

Event-Handling-Basics

Event Handling Basics in euv Project Code: https://github.com/euv-dev/euv euv is a Rust + WASM frontend UI framework that enables developers to build interactive web applications using the power of reactive signals and the html! macro. One of the most critical aspects of any UI framework is how it handles user interactions. In this article, we will take a deep dive into euv's event handling system — from inline closures to native event handlers, from input events to form changes, and from the comprehensive list of supported event names to utility functions that simplify common patterns. Table of Contents Inline Closure Events NativeEventHandler Input Events Form Change Events Supported Event Names Accessing Event Data Utility Functions for Event Handling Putting It All Together Inline Closure Events The most straightforward way to handle events in euv is through inline closures. You define the event handler directly within the html! macro using the move |event: Event| { ... } syntax. html! { button { onclick : move | event : Event | { } "Click me" } } This pattern is ideal for simple, self-contained event handlers that don't need to be reused across multiple components. The move keyword ensures that any captured variables (like signals) are moved into the closure, which is essential for the Rust ownership model. Inline closures work with any event type — not just onclick . You can use them for keyboard events, focus events, mouse events, and more. The closure receives an Event object that you can inspect to extract relevant data. NativeEventHandler For more complex scenarios where you need reusable event handlers or want to define handlers outside the html! macro, euv provides the NativeEventHandler type. This allows you to create named, parameterized event handler functions. pub fn counter_on_increment ( counter : Signal < i32 > ) -> NativeEventHandler { NativeEventHandler :: create ( "click" , move | _event : Event | { let current : i32 = counter .get (); counter

2026-06-20 原文 →
AI 资讯

Metadata Routing

Stop Fighting Scikit-Learn Pipelines: How Metadata Routing Fixes Sample Weights & Groups A couple of months ago, I stumbled upon this video by Vincent D. Warmerdam about metadata routing in scikit-learn. I'll be honest, I had no idea what "metadata routing" even meant, but Vincent's explanation completely changed how I think about building ML pipelines. The video showed me that one of the most frustrating problems in scikit-learn; passing sample weights and groups through complex pipelines finally had an elegant solution. It piqued my curiosity enough that I dove deep into the feature, tested it extensively, and honestly, I was surprised by how little coverage this gets in technical blogs and articles. So I figured, why not write about it myself and share what I learned? If you've ever struggled with imbalanced datasets, grouped cross-validation, or just wanted to pass custom information through your pipelines, this article is for you. Let's start from the very beginning. What is "Metadata" in Machine Learning? Let's start with a concrete example. You're building a credit card fraud detection model with this data: # Your training data X = transaction_features # Amount, merchant, time, location, etc. y = is_fraud # 0 = legitimate, 1 = fraud # But you also have additional information: sample_weights = [ 1.0 , 1.0 , 10.0 , 1.0 , ...] # Fraud transactions weighted 10x customer_ids = [ 101 , 102 , 101 , 103 , ...] # Which customer made each transaction Metadata is the "extra information" beyond your features (X) and labels (y): sample_weight : How important is each transaction? (Fraud = 10x more important) groups : Which customer does each transaction belong to? (For proper cross-validation) Custom metadata : Transaction timestamps, confidence scores, data quality flags, etc. Why Metadata Matters: The Credit Card Fraud Problem Imagine you're building a fraud detection system for a financial company. You have: Imbalanced data : 99% legitimate transactions, 1% fraudulent T

2026-06-20 原文 →
AI 资讯

How I Got a $340 AWS Bill from a Side Project (And What I Built to Prevent It)

The invoice arrived on a Tuesday morning. $340. For a side project I'd built in a weekend. A small LLM-powered summarization tool — users paste text, model returns a summary. I'd done the math before launching: roughly $0.002 per request, ~500 requests/day, around $30/month. Totally fine. What I hadn't accounted for: system_prompt_tokens = 800 requests_per_day = 2000 # not 500 — it went viral in a group chat input_price_per_1M = 2.50 # GPT-4o daily_cost = (800 * 2000 / 1_000_000) * 2.50 = $4.00/day → $120/month just from system prompts Plus the actual user input tokens. Plus output tokens. $340 later, I had learned my lesson. The Real Problem: API Pricing Is Designed to Be Hard to Compare Every provider uses different units: OpenAI → per million tokens (input vs output, different rates) Pinecone → read units + write units + storage GB/month Stripe → % of transaction + fixed fee + monthly platform fee AWS Lambda → per GB-second + per request + data transfer None of it is comparable at a glance. You end up either building a spreadsheet from scratch every time or just guessing — and guessing gets expensive. What I Built After the invoice incident I started keeping a cost estimation spreadsheet. It grew. Eventually I turned it into APICalculators.com — 16 free, browser-based calculators covering the infrastructure decisions most AI/SaaS developers face: LLM APIs GPT-4o, Claude Sonnet, Gemini Flash, Llama — cost by model, context length, daily volume Side-by-side comparison at your exact usage Vector Databases Pinecone vs Qdrant vs Supabase vs Weaviate Enter index size + queries/day → monthly cost Serverless AWS Lambda vs Cloudflare Workers vs Vercel Functions Cost at your invocation volume and memory config Auth Providers Clerk vs Auth0 vs Supabase Auth vs Cognito Monthly cost by MAU tier Payment Processors Stripe vs Paddle vs Lemon Squeezy Real fee comparison on your transaction volume The System Prompt Problem, Solved in 30 Seconds Here's what the LLM cost calculator

2026-06-19 原文 →
AI 资讯

Unit Test AI Guide — Zero Hallucination, Cross-Stack Standard

Focus: Unit Tests ONLY — no integration, no E2E Stacks: Node.js (NestJS/Express) · React.js · Python · Angular · Laravel Goal: AI generates unit tests consistently, deterministically, without hallucination IDE: Cursor (Primary) + Claude (Secondary) Part 1 — Best Single Library Per Stack (Final Decision) Do not mix libraries. Pick one per stack, configure it fully, never deviate. | Stack | Library | Why This One | |---|---|---| | Node.js / NestJS / Express | Jest | Native DI mocking, @nestjs/testing built around it, widest ecosystem | | React.js | Vitest + @testing-library/react | Native Vite/ESM support, Jest-compatible API, 3–10x faster | | Python | pytest | De facto standard, fixture system eliminates boilerplate, best plugin ecosystem | | Angular | Jest (replace Karma) | Karma is deprecated in Angular 17+; Jest is the official migration target | | Laravel | Pest | Modern syntax, built on PHPUnit, higher signal-to-noise ratio | Rule: If someone suggests a second library for the same stack, reject it. One library per stack, configured once, followed always. Part 2 — IDE: Cursor (Only Choice for This Goal) Why Cursor and Not VS Code / WebStorm | Capability | Cursor | VS Code + Copilot | WebStorm | |---|---|---|---| | Project-level AI rules | ✅ .cursor/rules/ | ❌ | ❌ | | Codebase-aware context | ✅ @codebase | Partial | Partial | | Run terminal + read output | ✅ Composer | ❌ | ❌ | | Multi-file generation | ✅ Agent mode | Limited | ❌ | | Custom instructions per filetype | ✅ | ❌ | ❌ | | MCP server integration | ✅ | ❌ | ❌ | Cursor's .cursor/rules/ system is the only IDE-native mechanism that injects persistent, project-scoped instructions into every AI interaction — this is what prevents hallucination at the source. Cursor Setup for This Project project-root/ ├── .cursor/ │ └── rules/ │ ├── unit-test-global.mdc ← applies to all files │ ├── unit-test-nestjs.mdc ← applies to *.service.ts, *.guard.ts │ ├── unit-test-react.mdc ← applies to *.tsx, *.component.tsx │ ├── unit-t

2026-06-19 原文 →
AI 资讯

Exploring 5-Minute Prediction Markets: Data, Speed, and Building an Edge

The “5-minute market” concept is gaining attention because of how fast new prediction rounds appear and how quickly volume builds up. Each cycle is short, which creates both opportunity and risk for anyone trying to analyze or trade it. In this article, I’ll break down how I’ve been approaching this space from a data perspective, how I’m thinking about building an edge, and the tools I’ve been experimenting with. What is the 5-minute market? A 5-minute market is a fast-cycle prediction or trading window where outcomes resolve quickly and new markets appear frequently. Compared to longer timeframes (like 15-minute markets), these shorter cycles: Generate more trading opportunities per hour Require faster data collection and processing Make latency and execution extremely important Increase noise in price action Because of this, traditional slow analysis often doesn’t work well here. Data collection approach My current setup focuses on continuously pulling market data in real time. The idea is simple: Connect to a market data source (I’m using a Gamma API as part of the pipeline) Stream or request live market updates Store order book + price movement data Aggregate it into 5-minute windows for analysis The goal is to build a dataset that can later be used for backtesting and feature extraction. Right now, I’m mainly focusing on a single asset (PPC) to keep things simple while testing the pipeline. Where the potential edge might come from The key question is: can we predict short 5-minute movements better than random chance? Some areas I’m exploring: 1. Order book behavior Tracking: Liquidity changes Bid/ask imbalances Sudden volume spikes 2. Session-based behavior Some traders observe patterns during different market sessions: Asian session behavior London session volatility Overlap periods These may or may not hold in 5-minute markets, but they’re worth testing. 3. Micro momentum patterns Since markets reset frequently, short momentum bursts might matter more than lo

2026-06-19 原文 →
AI 资讯

How I Cut My Multimodal AI Costs by 97% — A Freelancer's Guide

How I Cut My Multimodal AI Costs by 97% — A Freelancer's Guide Last month I almost killed a side gig because of a single line item on an invoice. A client wanted me to build a document-processing tool that could read scanned PDFs, pull text out of photos, and answer questions about charts. Easy enough — except I'd quoted the job assuming I'd use GPT-4o for the vision work. When I actually ran the numbers, I realized the API bill would eat my entire margin. I'd be working for free. Maybe worse. So I did what every freelancer does when the big-name vendor gets too expensive: I went hunting. And I landed on Global API, which routes to a bunch of multimodal models I've honestly never heard clients talk about. After a few weeks of testing, I figured out which ones are worth my billable hours and which ones aren't. This is everything I learned, plus the exact code I'm shipping to clients. Why Multimodal Even Matters for Solo Devs Two years ago, "multimodal" was a buzzword you'd hear at conferences. In 2026 it's table stakes. I've personally used vision models to: OCR receipts for an expense-tracking app (boring but pays the rent) Convert screenshots of legacy code into editable source for a Y2K-era company migration Read bar charts from PDF reports for a finance client who hates spreadsheets Analyze medical imaging samples for a startup MVP (this one was scary) Every one of those jobs started as a quick conversation with a prospect and turned into real invoices because I could say yes. The bottleneck was never capability — it was always cost. When GPT-4o charges north of $10/M output tokens, a single 2,000-token response on a tricky chart costs me about two cents. Multiply by 10,000 images per month and you've got a $200 API line item before you've paid yourself. That's a problem when the whole job is worth $400. So I tested every multimodal model I could find on Global API. Here's the lineup I ended up evaluating. The Contenders Nine models, three providers, one freelanc

2026-06-19 原文 →
AI 资讯

What is Generative AI? Understanding the Foundation of Modern AI Agents #2

Everyone is talking about AI Agents. But before you build an AI Agent, there is one concept you absolutely need to understand: Generative AI. Generative AI is the technology that transformed software from systems that simply follow rules into systems that can understand language, generate responses, reason through instructions, and assist users in a natural way. As part of my new course: Develop Your First AI Agent with Microsoft Foundry I published the first lesson where we explore the journey from traditional software to Generative AI and understand why modern AI Agents became possible. 🎥 Watch the video here: Why This Topic Matters Many developers jump directly into AI Agents, prompts, tools, and frameworks. However, without understanding the evolution of AI, it becomes difficult to understand: Why AI Agents exist Why Large Language Models are important Why prompts work Why tools are needed How modern AI systems actually operate In this lesson, we start from first principles and build the foundation required for the rest of the course. What You'll Learn Traditional Software For decades, software followed a simple pattern: Input → Rules → Output Developers explicitly defined every behavior. This worked well until humans started interacting with software using natural language. Why Rule-Based Systems Break Imagine building a dietician chatbot. Users might ask: What should I eat? Suggest a healthy breakfast. What foods contain protein? Can I eat oats daily? All of these questions are similar. Yet they are phrased differently. Supporting thousands of variations quickly becomes impossible with manually written rules. Predictive AI Machine Learning introduced a new approach. Instead of writing rules, we train models using data. Examples include: Spam Detection Fraud Detection Recommendation Systems Predictive AI can make decisions. But it still cannot create content. Prediction vs Creation A predictive model can answer: Fraud probability: 87% But can it explain why? Ca

2026-06-19 原文 →
AI 资讯

The hard part of national ID OCR isn't the OCR

You wire up OCR for your KYC flow, point it at a national ID card, and get back a clean { name, idNumber, dateOfBirth } . Ship it. Then you onboard your second country — and it falls apart. Fields you mapped don't exist. The name comes back as garbled Latin. The date of birth says the year 2567. Here's the thing nobody tells you when you start: the hard part of national ID OCR isn't the OCR. It's that every country's ID is a different document. A model that reads text off a card is table stakes. Turning 30 countries' cards into data your system can actually use is where the work is. Let me show you the three axes of variation that will bite you, then how to architect so they don't. Axis 1: the fields are different There is no universal "national ID" schema, because the cards themselves don't agree on what to print. A Thai ID card prints the holder's religion . A German ID card prints height and eye color . A Chinese ID card prints ethnicity and the issuing authority. None of these are edge cases — they're core fields on those documents. So the instinct to define one IdCard type with a fixed set of columns is wrong from day one. Either you drop information that some countries consider essential, or you end up with a sparse table full of null s and country-specific special-casing. And it's not just which fields exist — it's what they're called and how they're split. The same "name" concept might come back as a single full-name string on one card and as separate given/family fields on another, sometimes in two scripts at once. Your data model has to treat "the field set depends on the country" as a first-class fact, not an afterthought. Axis 2: the script is different If your users are global, a lot of their names are not in the Latin alphabet — Chinese, Thai, Arabic, and more. The naive move is to transliterate everything to Latin "so it's consistent." Don't. Transliteration is lossy and ambiguous: multiple native spellings collapse to the same Latin form, diacritics

2026-06-19 原文 →
AI 资讯

Structuring TypeScript: Interfaces, Type Aliases, Enums, and Object Types

Structuring TypeScript: Interfaces, Type Aliases, Enums, and Object Types You've learned TypeScript's primitive types and the basics of type inference here . Now it's time to model real-world data — users, orders, API responses, configuration objects. That's where interfaces, type aliases, and enums come in. These three features are what make TypeScript genuinely powerful for building applications. Let's dig in. Object Types: Describing the Shape of Data Before we get to interfaces, let's understand object types. When you want to describe the structure of an object, you define what properties it has and what types those properties are: // Inline object type annotation function displayUser ( user : { name : string ; age : number ; email : string }): void { console . log ( ` ${ user . name } ( ${ user . age } ) — ${ user . email } ` ); } This works, but it's messy to repeat everywhere. That's why we use type aliases and interfaces to name and reuse these shapes. Type Aliases: Naming a Type A type alias gives a name to any type — primitives, unions, objects, or combinations: // Alias for a primitive union type ID = string | number ; // Alias for an object shape type User = { id : ID ; name : string ; age : number ; email : string ; }; // Now use it anywhere const user : User = { id : 1 , name : " Ramesh " , age : 31 , email : " ramesh@example.com " , }; function getUser ( id : ID ): User { // ... fetch user logic } Type aliases are flexible — they can represent almost anything. Interfaces: Defining Object Contracts An interface is specifically designed to describe the shape of an object. Syntax is slightly different: interface User { id : number ; name : string ; age : number ; email : string ; } const user : User = { id : 1 , name : " Ramesh " , age : 31 , email : " ramesh@example.com " , }; Optional and Readonly Properties Properties can be marked as optional ( ? ) or read-only ( readonly ): interface UserProfile { readonly id : number ; // Can't be changed after cre

2026-06-19 原文 →
AI 资讯

TypeScript Types Demystified: Simple Types, Special Types, and Type Inference

TypeScript Types Demystified: Simple Types, Special Types, and Type Inference In the first post , we covered why TypeScript exists and how to write your first program. Now it's time to get comfortable with the type system itself — the foundation everything else is built on. By the end of this post, you'll know how to type variables, arrays, and function parameters correctly. You'll also understand the "special" types that trip up most beginners: any , unknown , never , and void . The Core Primitive Types TypeScript's basic types map directly to JavaScript's primitives: // string let firstName : string = " Ramesh " ; let greeting : string = `Hello, ${ firstName } ` ; // number (no separate int/float — it's all number) let age : number = 31 ; let price : number = 9.99 ; let hex : number = 0xFF ; // boolean let isLoggedIn : boolean = true ; let hasAccess : boolean = false ; These are the types you'll use most often. Simple, predictable, and exactly what you'd expect. Type Inference: TypeScript Does the Work You don't always have to write the type. TypeScript infers it from the value you assign: let city = " Chennai " ; // TypeScript infers: string let year = 2026 ; // TypeScript infers: number let isActive = true ; // TypeScript infers: boolean Once inferred, that type is locked in: let city = " Chennai " ; city = 42 ; // ❌ Error: Type 'number' is not assignable to type 'string' Rule of thumb: Let TypeScript infer types for local variables. Write explicit annotations for function parameters and return types. // Let inference work for variables const scores = [ 95 , 87 , 72 ]; // inferred as number[] // Be explicit for function signatures function calculateAverage ( scores : number []): number { return scores . reduce (( a , b ) => a + b , 0 ) / scores . length ; } Explicit vs Inferred — When to Choose Each // ✅ Explicit annotation — good for function params & return types function formatName ( first : string , last : string ): string { return ` ${ first } ${ last } ` ;

2026-06-19 原文 →
AI 资讯

TypeScript Explained: Why Every JavaScript Developer Should Care

TypeScript Explained: Why Every JavaScript Developer Should Care You've been writing JavaScript for years. It works. So why bother with TypeScript? That's what I thought too — until I spent two days debugging a production bug that turned out to be a simple typo in a property name. A bug TypeScript would have caught in milliseconds. In this post, I'll explain what TypeScript is, why it exists, and how to write your very first TypeScript program. No fluff — just what you actually need to know. What Is TypeScript? TypeScript is JavaScript with types added on top. That's really it. It was created by Microsoft in 2012 and has since become one of the most popular tools in the JavaScript ecosystem — used by teams at Google, Airbnb, Slack, and countless others. Here's the key thing to understand: TypeScript is not a replacement for JavaScript . It compiles down to plain JavaScript. Every browser, Node.js server, and JavaScript runtime runs the same JS it always has. TypeScript just helps you write better code before that happens. JavaScript vs TypeScript — A Side-by-Side Look Let's say you're writing a function to greet a user: JavaScript: function greetUser ( name ) { return " Hello, " + name . toUpperCase (); } greetUser ( 42 ); // Runtime error: name.toUpperCase is not a function You won't discover this mistake until the code runs — possibly in production, in front of real users. TypeScript: function greetUser ( name : string ): string { return " Hello, " + name . toUpperCase (); } greetUser ( 42 ); // ❌ Error: Argument of type 'number' is not assignable to parameter of type 'string' TypeScript catches this immediately in your editor — before you even run the code. That : string annotation tells TypeScript exactly what type name should be. Why Use TypeScript? The Real Benefits 1. Catch Bugs Early The most obvious benefit. Instead of runtime errors that crash your app, TypeScript surfaces type errors at compile time — while you're still writing code. 2. Better Autocomplet

2026-06-19 原文 →
AI 资讯

Building a Kubernetes Cluster on Red Hat Enterprise Linux 10: A kubeadm Guide

Introduction In this post, I'll walk you through deploying a production-ready Kubernetes cluster on Red Hat Enterprise Linux 10 using kubeadm. This lab was inspired by Anthony E. Nocentino's excellent Certified Kubernetes Administrator (CKA): Using kubadm to Install a Basic Cluster training course, which is part of the official Certified Kubernetes Administrator (CKA) path on Pluralsight . ⭐ Shout-out: Anthony is a fantastic trainer! His course uses Ubuntu 22.04 as the base OS. I adapted his approach to work on RHEL 10, adding some additional considerations specific to Red Hat's ecosystem. One intentional decision in this setup: I deployed Kubernetes v1.35 and CRI-O v1.35, which wasn't the latest version available at installation time. This was purposeful. Anthony's course includes a dedicated section on upgrading clusters, and using a slightly older baseline makes that learning path clearer. The upgrade procedures (not covered here) are what really solidify your understanding of cluster lifecycle management. Lab Infrastructure Overview Nodes Configuration Node Role RAM vCPUs IP Address rh-cp1 Control Plane 12 GiB 2 192.168.110.120 rh-node1 Worker 6 GiB 2 192.168.110.121 rh-node2 Worker 6 GiB 2 192.168.110.122 rh-node3 Worker 6 GiB 2 192.168.110.123 Note: The IP address schema is just an example and what was more convenient for me. Supporting Infrastructure A dedicated utilities VM (also RHEL 10) provides essential services: DNS (BIND/named) NTP (chrony) HTTP (Apache/httpd) DHCP (Kea) This centralized infrastructure simplifies name resolution across all cluster nodes. But this is not essential for this project. You can, instead, ensure the nodes are able to reach each other updating the file /etc/hosts on all nodes. Prerequisites & OS Preparation Before diving into Kubernetes, we need consistent node preparation across all machines . 1. System Registration and Updates $ sudo subscription-manager register --username <username> --password <password> $ sudo dnf update

2026-06-19 原文 →
AI 资讯

Agent Framework RAG for Agents: Giving Your Agent the Right Context

This is Part 13 of my series on the Microsoft Agent Framework. You can read the original post over on lukaswalter.dev . In the previous article , we looked at workflows. Workflows make sense when the process itself needs structure: state, checkpoints, events, human approvals, and resumable execution. This post is the bridge from Agent Framework into RAG. I plan on doing a full RAG deep dive sometime later. The practical question for now is smaller: How do I connect an Agent Framework agent to private application knowledge without stuffing every document into the prompt? For agents, RAG is less about adding more text and more about giving the agent a controlled retrieval path. The agent should fetch the right context at the point where it needs it. Agents do not know your private data Your company documents, product catalog, tickets, rules, policies, runbooks, and internal knowledge base live outside the model. The model has generic knowledge. Your application has private knowledge. Treat those as separate systems. You can paste some private data into the prompt, and for a demo that may be enough. But this falls apart quickly: full documents are expensive to send repeatedly long prompts are fragile stale documents may sit next to current ones users may not be allowed to see every source long context still needs selection The last point is easy to underestimate. A larger context window lets you send more text. It does not decide which text is correct, current, relevant, or permitted. Do not give the agent all knowledge. Give it the right context at the moment it needs it. Retrieval owns that job. The minimal RAG shape The basic RAG loop is small: user question -> retrieve relevant chunks -> pass chunks to the agent -> agent answers using that context For documents, the longer pipeline usually looks like this: documents -> chunks -> embeddings -> vector store -> search -> retrieved context -> agent response Documents are split into smaller chunks. Those chunks are embe

2026-06-18 原文 →
AI 资讯

Preparing Specs for AI Coding Agents

AI coding agents now edit repositories, run commands, and produce branches. That makes the spec before the work more important: it carries the context, boundaries, and success criteria the agent needs. What a good coding-agent spec includes Specs are becoming more important because AI coding agents are no longer only answering questions. They are reading repositories, editing files, running commands, producing branches, and asking humans to review the result. That changes what a prompt needs to become. When an assistant only answers a question, a private prompt can be enough. When an agent changes a shared codebase, the prompt becomes an assignment. And an assignment needs more than good wording. It needs the right context, boundaries, examples, and a way to judge whether the work matched the original intent. That is the practical reason to prepare a spec before sending a coding agent into a repository. The spec does not need to be long. It does need to tell the agent what problem it is solving, what behavior should change, what must not change, and how the result will be reviewed. At minimum, a good coding-agent spec should give the agent five things: the context behind the task the behavior that should change the constraints the agent should preserve examples or scenarios that define correctness the validation evidence a reviewer should inspect This is the useful idea behind spec-driven development, behavior scenarios, issue templates, lightweight design docs, OpenSpec, GitHub Spec Kit, and many internal engineering proposal formats. The specific framework matters less than the shape of the spec: the agent should receive enough context to act, and the team should receive enough structure to review the result. The spec is not a nicer prompt. It is the prepared assignment between human intent and machine execution. Prompts are good at starting work. Specs are better at carrying it. A private prompt is optimized for immediacy. It lives in a chat session. It can inclu

2026-06-18 原文 →
AI 资讯

How to Integrate Apache Kafka with Spring Boot: A Production-Ready Guide

When a Spring Boot service needs to talk to another service without waiting on a synchronous HTTP call, message queues are the usual answer. Apache Kafka has become the default choice for this in most backend teams, but a lot of tutorials stop at a "hello world" producer and consumer that would never survive a real production load. Things like consumer retries, error handling, serialization of real objects, and graceful shutdown get skipped, and those are exactly the parts that page you at 2 a.m. In this tutorial, you will build a Spring Boot application that produces and consumes JSON messages over Kafka. You will configure a producer and a consumer, send a typed object instead of a plain string, handle deserialization errors so one bad message does not block your whole consumer group, and verify the whole thing works end to end. By the end, you will have a small but realistic messaging setup you can build on. Prerequisites To follow along, you will need: Java 17 or later installed. You can check your version by running java -version . A Spring Boot 3.x project. You can generate one at start.spring.io with the Spring for Apache Kafka dependency added. A running Kafka broker. The quickest way to get one locally is Docker, which the first step covers. Basic familiarity with Spring Boot, including how @Component and application.yml work. Step 1 — Running Kafka Locally with Docker Before writing any code, you need a broker to talk to. Running Kafka by hand involves Zookeeper, broker configuration, and a fair amount of setup, so you will use Docker Compose to bring up a single-broker cluster instead. Create a file named docker-compose.yml in your project root: services : kafka : image : apache/kafka:3.7.0 container_name : kafka ports : - " 9092:9092" environment : KAFKA_NODE_ID : 1 KAFKA_PROCESS_ROLES : broker,controller KAFKA_LISTENERS : PLAINTEXT://:9092,CONTROLLER://:9093 KAFKA_ADVERTISED_LISTENERS : PLAINTEXT://localhost:9092 KAFKA_CONTROLLER_LISTENER_NAMES : CONTRO

2026-06-18 原文 →
AI 资讯

Gas Optimization That Doesn't Break Security: Storage, Calldata, and the Traps

Gas optimization is satisfying. You shave a few thousand gas off a function and feel clever. But some optimizations trade away safety in ways that are not obvious, and I have seen "optimized" contracts that introduced vulnerabilities. Here are the gas wins that are genuinely free, the ones that cost you safety, and how to tell the difference. Where gas actually goes Before optimizing, know what is expensive. Storage operations dominate. Writing a fresh storage slot ( SSTORE from zero to non-zero) costs a lot; reading storage ( SLOAD ) is cheaper but still meaningful; computation in memory is cheap by comparison. So the highest-leverage optimizations are about touching storage less. Free win 1: cache storage reads in memory If you read the same storage variable multiple times in a function, each read is an SLOAD . Read it once into a local variable instead: // WASTEFUL: reads storage `total` three times function distribute() external { require(total > 0, "empty"); uint256 share = total / count; emit Distributed(total); } // OPTIMIZED: one SLOAD, two memory reads function distribute() external { uint256 _total = total; // single storage read require(_total > 0, "empty"); uint256 share = _total / count; emit Distributed(_total); } This is free in the sense that it changes nothing about correctness. The value is identical; you just read it once. Pure win. Free win 2: calldata instead of memory for read-only arrays For external function arguments you only read (never modify), calldata is cheaper than memory because it skips the copy: // memory copies the whole array into memory function process(uint256[] memory ids) external { ... } // calldata reads directly from the transaction data, no copy function process(uint256[] calldata ids) external { ... } Again, free. If you do not mutate the array, calldata is strictly better. Free win 3: storage packing Solidity packs multiple variables into one 32-byte slot if they fit and are adjacent. Order your storage variables so smal

2026-06-18 原文 →
AI 资讯

Windows ortamında Python geliştirme ve operasyon yönetimi için “çekirdek CLI komutları”

1. Python Ortam Kontrolü (Windows CLI) Python sürüm kontrol python --version py --version where python pip kontrol pip --version python -m pip --version pip güncelleme (kritik) python -m pip install --upgrade pip 2. Python Çalıştırma Mekanizması (Windows Standard) Script çalıştırma python app.py Py launcher ile sürüm seçme py app.py py -3 .12 app.py py -3 .11 app.py Modül çalıştırma python -m mymodule 3. Sanal Ortam (venv) – Kurumsal Standart Oluşturma python -m venv venv Aktivasyon (PowerShell) venv \S cripts \A ctivate.ps1 Aktivasyon (CMD) venv \S cripts \a ctivate.bat Deaktivasyon deactivate Sanal ortam kontrol where python where pip pip list 4. requirements.txt Yönetimi Oluşturma pip freeze > requirements.txt Kurulum pip install -r requirements.txt Güncelleme pip install --upgrade -r requirements.txt 5. Paket Yönetimi (pip Core Set) Paket yükleme pip install requests Versiyon sabitleme pip install requests == 2.31.0 Paket kaldırma pip uninstall requests Listeleme pip list Güncellenebilir paketler pip list --outdated 6. Windows .env Yönetimi (Konfigürasyon Standardı) .env dosyası oluşturma notepad .env Örnek içerik DEBUG=True API_KEY=123456 DB_URL=localhost Python tarafı (.env kullanımı) pip install python-dotenv from dotenv import load_dotenv import os load_dotenv () api_key = os . getenv ( " API_KEY " ) print ( api_key ) 7. Sistem Komutları ve Process Yönetimi Process listeleme tasklist Python process filtreleme tasklist | findstr python Process sonlandırma taskkill /PID 1234 /F Python process kill taskkill /IM python.exe /F 8. Dosya İşlemleri (CLI seviyesinde) Dosya listesi dir Klasör değiştirme cd project Dosya silme del file.txt Klasör silme rmdir /S /Q folder 9. Log ve Debug Yönetimi Dosya log izleme (PowerShell) Get-Content app.log -Wait Son satırlar Get-Content app.log -Tail 100 Filtreleme Select-String "ERROR" app.log 10. Uzaktan Erişim (Windows → SSH) SSH bağlantı ssh user@server_ip Dosya gönderme scp app.py user@server_ip:C: \U sers \u ser \ Klasör gön

2026-06-18 原文 →
AI 资讯

Building AI Agents with Agno — I Actually Ran It with Gemini and Built-in Tools

If you've ever felt like LangChain was too heavy, you're not alone. The dependency tree is enormous. Abstraction layers pile up. At some point you lose track of what's actually happening underneath. That frustration has pushed a lot of people toward lighter alternatives — frameworks that prove you can build a capable agent without a hundred transitive dependencies. Agno is one of those alternatives. It started as Phidata and rebranded in early 2025. I spent an afternoon installing Agno v2.6.17 in a clean sandbox and running through Calculator tools, Wikipedia retrieval, Pydantic structured output, and a two-agent Team. I'll share the real execution logs and, more importantly, the traps I hit that the docs don't warn you about. What Agno Is and Where It Came from Phidata built a solid reputation as "the Python framework for AI assistants." When it rebranded to Agno in 2025, the design philosophy got articulated more clearly around three ideas. Model-agnostic from day one. Over 70 LLMs — OpenAI, Anthropic, Google, Ollama, Cohere — can plug in with the same code structure. Swap the model, keep the agent logic. Multimodal as a default. Text, image, audio, video agents all use the same API surface. You don't need a different abstraction layer for each modality. Multi-agent orchestration as a first-class citizen. The Team class is built in. You can switch between coordinate , route , and collaborate modes with a single parameter change. Reading that, I thought: "How is this different from LangChain?" The answer showed up when I actually wrote code. Agno favors composition over class inheritance. One agent takes about 6 lines to set up. There's far less boilerplate to wade through. Installation: No Dependency Hell pip install agno google-genai ddgs wikipedia The agno package installs just the core. Tools require their own extra dependencies — wikipedia for the Wikipedia tool, google-genai for Gemini. This lazy-loading approach keeps the base install clean. $ python3 -c "im

2026-06-18 原文 →
AI 资讯

Building GitHub-Inspired Version Control and Forking Without Duplicating Project Files

One of the challenges I faced while building my LaTeX Writer project was implementing version control and project forking in a storage-efficient way. A typical LaTeX project contains multiple files. Even a simple project usually has a "main.tex" file, bibliography files, images, style files, and other supporting documents. If I stored a complete copy of every file for every version or fork, storage requirements would grow rapidly. Imagine a project with four files and ten versions. Storing the entire project for every version would mean storing the same files repeatedly, even when only one line changed. Forking would create an even bigger problem because every fork would require another complete copy of the project. Instead of accepting this inefficiency, I started researching how large platforms solve the same problem. GitHub was the obvious inspiration. Learning from GitHub GitHub does not store a complete copy of a repository every time a change is made. Instead, it stores content separately and uses references to connect files, commits, and repositories. This idea became the foundation for my own implementation. Project Structure Whenever a new project is created, a default file called "main.tex" is generated automatically. The project itself does not directly contain file contents. Instead, it stores metadata such as: Project ID Owner ID Root Folder ID File References Each file also has its own metadata record containing: File ID File Name Blob ID Project ID Owner ID Folder ID The actual content is not stored inside the file metadata. Instead, the content lives inside a separate entity called a Blob. Loading a Project When the editor loads a project, it reconstructs the directory structure using metadata. The process works like this: Retrieve the project's Root Folder ID. Find all folders belonging to that folder hierarchy. Find all files belonging to each folder. Build the directory tree for the frontend. Because files and folders are stored independently, the

2026-06-18 原文 →
开发者

Limn Engine — Complete API Reference

📚 Limn Engine — Complete API Reference Quick Navigation Class Purpose Level Display Canvas, game loop, input, camera, scenes 🟢 L1 Component Every visible game object 🟢 L1 Camera Viewport control (follow, shake, zoom) 🟡 L2 move Movement, physics, particles, helpers 🟢 L1 state Read-only query helpers 🟢 L1 TileMap Grid-based levels 🟡 L2 Tctxt Rich text with backgrounds 🟢 L1 Sound Single audio file 🟢 L1 SoundManager Multiple sounds, volume control 🔴 L4 ParticleSystem Emit, burst, continuous emitters 🟠 L3 Sprite Spritesheet animation 🟡 L2 Display The heart of every Limn Engine game. Creates the canvas, runs the game loop, captures input, manages the camera, and controls scenes. Constructor const display = new Display (); Properties Property Type Description .canvas HTMLCanvasElement The game canvas .context CanvasRenderingContext2D 2D drawing context .keys Array Boolean array indexed by keyCode .scene Number Current active scene (default 0) .camera Camera Attached camera instance .deltaTime Number Time since last frame (seconds) .fps Number Current frames per second .frameNo Number Total frames elapsed .x / .y Number false Methods Method Parameters Description .start(w, h, node) width, height, parentNode Initialise canvas and start game loop .perform() — Activate dual-canvas pipeline (call before .start() ) .add(comp, scene) Component, scene number Register a Component for rendering .stop() — Pause the game loop .scale(w, h) width, height Resize canvas after start .backgroundColor(color) CSS color Set background colour .lgradient(dir, c1, c2) direction, color, color Linear gradient background .rgradient(c1, c2) color, color Radial gradient background .fullScreen() — Enter fullscreen .exitScreen() — Exit fullscreen .tileMap() — Build TileMap from display.map and display.tile Usage const display = new Display (); display . perform (); display . start ( 800 , 600 ); display . backgroundColor ( " #0a0a2a " ); const player = new Component ( 40 , 40 , " blue " , 100 , 100 ); d

2026-06-18 原文 →