AI 资讯
# 📓 TanStack Query: Core Concepts & Summary
1. Introduction: What is TanStack Query? TanStack Query (formerly React Query) is a framework-agnostic state management library designed specifically to manage Server State —handling data fetching, caching, background updating, and cache invalidation. 2. Server State vs. Client State & The Memory Reality Client State: Owned and controlled entirely by the browser (e.g., isModalOpen , selected UI theme). Server State: Owned by the remote backend database (e.g., user profiles, posts, cart items). The browser only holds a read-only temporary snapshot . Where is data physically stored? Physical Location: By default, cached data lives strictly in the browser tab's JavaScript RAM (In-Memory) . Backend ("The Server"): Refers to your remote API/database (regardless of whether it runs on Kubernetes, Docker containers, serverless functions, or bare metal). Optional Persistence: You can opt to sync this RAM cache to localStorage , sessionStorage , or IndexedDB using TanStack Query Persisters. import React , { useState } from ' react ' ; import { QueryClient , QueryClientProvider , useQuery , useMutation , useQueryClient , } from ' @tanstack/react-query ' ; // 1. Initialize QueryClient (manages the RAM cache) const queryClient = new QueryClient ({ defaultOptions : { queries : { staleTime : 10000 , // Data stays fresh in RAM for 10 seconds }, }, }); // Mock API functions async function fetchPost ( postId ) { const res = await fetch ( `[https://jsonplaceholder.typicode.com/posts/$](https://jsonplaceholder.typicode.com/posts/$){postId}` ); if ( ! res . ok ) throw new Error ( ' Network error ' ); return res . json (); } async function createPost ( newPost ) { const res = await fetch ( ' [https://jsonplaceholder.typicode.com/posts](https://jsonplaceholder.typicode.com/posts) ' , { method : ' POST ' , headers : { ' Content-Type ' : ' application/json ' }, body : JSON . stringify ( newPost ), }); return res . json (); } // 2. Query Component (Fetching & Reading Data) function PostViewe
AI 资讯
Why I Built Yet Another JavaScript Date Picker
Every developer has had this moment. You need a date picker, so you start searching. You find one that's perfect... until you realize it requires React. Or Vue. Or jQuery. Or an entire date library just to select a few dates. After trying several solutions, I kept asking myself: Why is such a common UI component often more complicated than it needs to be? So I decided to build my own. Meet RollDate . The Goal I didn't want to create "another date picker." I wanted to build something that I would actually enjoy using in my own projects. The goals were simple: Infinite scroll Zero framework dependencies Simple API Modern UI Mobile-friendly scrolling TypeScript support Easy customization Good documentation Why Scrolling? Most date pickers rely on clicking tiny arrows or dropdowns. On mobile devices, this often feels awkward. I wanted something closer to native mobile pickers, where changing the month or year is just a smooth scroll. That became one of RollDate's core ideas. More Than Just Picking a Date While building the component, I realized different projects need different selection modes. So instead of maintaining separate components, RollDate supports: Single date selection Date range selection Multiple date selection The API stays the same regardless of the mode. new RollDate ( " #date " , { selectType : " range " }); Optional Time Picker Many date pickers force you to install another plugin if you need time selection. I wanted it built in. RollDate supports: 24-hour mode 12-hour AM/PM mode Configurable minute steps Enable it with one option. new RollDate ( " #date " , { enableTime : true }); Dependency-Free One of the main design goals was keeping the library independent. No React. No Vue. No jQuery. No Moment.js. No Day.js. Just plain JavaScript. That means it works almost anywhere: Vanilla JavaScript React Vue Angular Svelte Astro ...or any framework capable of using DOM components. A Better Developer Experience I care a lot about developer experience. That's
AI 资讯
Why Most Web Change Monitors Fail: Solving DOM Mutations and False Positives
If you have ever tried building a website change detection system or visual testing tool, you’ve likely stumbled into the "False Positive Trap." You configure a cron job to monitor a target URL, take snapshots every 15 minutes, and compare them. But within hours, your inbox is flooded with alerts for: Tailwind CSS dynamic hash class mutations (e.g. class="bg-blue-500_a3f9" turning into class="bg-blue-500_b81c" after a deployment) Lazy-loaded images rendering at offset offsets Anti-bot verification scripts altering invisible DOM nodes Hydration mismatches in React/Vue single-page applications At PageWatch.tech , solving these exact edge cases was the primary focus of our engineering roadmap. In this article, I’ll share the 3 core algorithmic fixes we implemented to achieve reliable, noise-free website change monitoring. 🛑 Problem 1: Structural Hash Instability in Modern Frameworks Modern frontend frameworks like Next.js, Nuxt, and Remix insert dynamic build IDs, hydration keys, and inline CSS chunk hashes into the HTML structure. For example, a innocent paragraph tag might look like this today: <p class= "text-gray-700 css-1a2b3c" data-reactroot= "" > Product Price: $99 </p> And like this tomorrow after a routine production deployment: <p class= "text-gray-700 css-9x8y7z" data-reactroot= "" > Product Price: $99 </p> A standard raw string comparison flags this as a critical change even though zero user-facing content changed . The Solution: Attribute Normalization & CSS Class Sanitization Before computing DOM structural hashes, we run a normalize pass that strips generated hashes and framework-specific attributes: import * as htmlparser2 from " htmlparser2 " ; /** * Normalizes dynamic framework attributes and hashed CSS classes * before running DOM diff calculations. */ export function normalizeDOMNode ( node : any ): void { if ( node . attribs ) { // 1. Remove hydration and framework metadata const volatileAttrs = [ " data-reactroot " , " data-reactid " , " data-hydr
AI 资讯
Deep Learning & Computer Vision in Web Diffing: Solving Layout Shifts with Neural Embeddings and SSIM
When engineers talk about visual regression or website change monitoring, pixel-level diffing algorithms (like pixelmatch or Euclidean RGB distance) are usually the default solution. However, in real-world web environments, pixel-by-pixel comparisons fundamentally fail under normal user interactions and dynamic rendering conditions: Elastic Layout Shifts: A single 20px dynamic banner inserted at the top of a page pushes every subsequent DOM element down, causing 100% of the downstream pixels to fail a pixelmatch test, even if the content itself hasn't changed. Sub-Pixel Anti-Aliasing Jitter: Operating systems (macOS vs. Linux vs. Windows) render font glyphs with subtle sub-pixel anti-aliasing variations, creating thousands of false-positive pixel deltas. Semantic vs. Cosmetic Changes: Changing a single word in a paragraph should trigger a localized alert, but a minor color gradient shift in a hero image shouldn't trigger an emergency notification. At PageWatch.tech , we solved this by combining classical Structural Similarity (SSIM) , ORB Feature Alignment , and Siamese Neural Networks (SNN) for latent-space semantic comparison. In this article, I will dive into the mathematics, neural network architectures, and TypeScript implementation of our computer vision diff pipeline. 🧮 1. Beyond Pixel Comparison: Structural Similarity Index (SSIM) Unlike raw Mean Squared Error (MSE), SSIM measures visual change based on human perception across three dimensions: Luminance , Contrast , and Structure . Mathematically, the SSIM between two image windows $x$ and $y$ is defined as: $$\text{SSIM}(x, y) = \frac{(2\mu_x\mu_y + C_1)(2\sigma_{xy} + C_2)}{(\mu_x^2 + \mu_y^2 + C_1)(\sigma_x^2 + \sigma_y^2 + C_2)}$$ Where: $\mu_x, \mu_y$ are the local pixel mean intensities. $\sigma_x^2, \sigma_y^2$ are the local variances. $\sigma_{xy}$ is the covariance between $x$ and $y$. $C_1, C_2$ are stabilization constants. TypeScript Implementation of SSIM Window Sliding Below is a snippet of how
开发者
🐍 Snake - rendered with 576 browser windows [warning - this WILL hurt your eyes...and PC!]
I have been quiet lately I know - but don't worry I haven't forgotten you all and how much you like...
AI 资讯
Letting a stranger contact a car owner without giving them the number
Letting a stranger contact a car owner without giving them the number There is a small, very common problem in Indian cities that turns out to be a surprisingly good systems design exercise. A car is parked badly. It is blocking a gate, a driveway, another car. Someone needs the owner to move it, right now. The traditional fix is a phone number written on a sticker on the windscreen. That works. It also means a stranger — any stranger, forever — has the owner's personal number. Why the sticker is worse than it looks Once a number is visible on a windscreen, a few things follow: It gets scraped. Numbers on vehicles end up in marketing lists. It cannot be revoked. Change your number and every sticker you own is now wrong. It has no context. A 2am call could be a genuine emergency or someone who saw the number three months ago. It is a safety issue for some owners in a way it is not for others. A number attached to a vehicle, at a known parking spot, at predictable times, is more information than most people realise they are publishing. So the requirement is oddly specific: a stranger must be able to reach the owner, immediately, without ever learning how to reach them again. That constraint is what makes this interesting. The naive version, and why it fails First instinct: put a QR code on the vehicle that opens a page with a "call owner" button, and put the number behind the button. This solves nothing. The number is still in the page source. Anyone who wants it can get it, and now you have added a scan step for the honest majority while stopping none of the dishonest minority. Second instinct: put a contact form behind the QR. The stranger types a message, the owner gets a notification. Better on privacy, useless in practice. The person needs the car moved in the next ninety seconds. They are not filling in a form and waiting for an email. If the fast path is not there, they go back to writing an angry note. The real requirement is synchronous contact with asynchron
AI 资讯
How to Add Watermarks to PDFs in the Browser with Vue 3 and pdf-lib
Watermarking a PDF — adding semi-transparent text over pages — sounds like something only desktop software handles. But with pdf-lib and a bit of canvas math, you can build a fully browser-based watermark tool. This post walks through the implementation details, including text rendering, rotation, and multi-page support. Why client-side? Traditional watermark tools upload your file, process it on a server, and send the result back. For documents that might be confidential or contain sensitive information, this introduces an unnecessary privacy risk. A browser-based approach: Processes everything locally Keeps files on the user's device Works offline after loading Avoids server-side bandwidth costs The stack Vue 3 + Composition API pdf-lib for PDF manipulation and watermarks PDF.js ( pdfjs-dist ) for preview rendering Vite for bundling Adding a text watermark pdf-lib provides a built-in PDFDocument.embedFont() method for custom fonts and page.drawText() for placing text. Here's how to add a rotated, semi-transparent watermark across all pages: < script setup lang= "ts" > import { ref } from ' vue ' import { PDFDocument , rgb , StandardFonts } from ' pdf-lib ' const file = ref < File | null > ( null ) const watermarkText = ref ( ' DRAFT ' ) const opacity = ref ( 0.3 ) const fontSize = ref ( 72 ) const rotationDeg = ref ( - 45 ) const applying = ref ( false ) async function handleFileUpload ( selected : File ) { file . value = selected } async function applyWatermark () { if ( ! file . value ) return applying . value = true try { const arrayBuffer = await file . value . arrayBuffer () const pdfDoc = await PDFDocument . load ( arrayBuffer ) // Embed the Helvetica font — required for correct rendering const helveticaFont = await pdfDoc . embedFont ( StandardFonts . HelveticaBold ) const pages = pdfDoc . getPages () pages . forEach (( page ) => { const { width , height } = page . getSize () page . drawText ( watermarkText . value , { x : ( width - helveticaFont . widthOfT
AI 资讯
Why You Should Try Nano Kit
Hi, my name is Dan, I'm a frontend engineer and open-source maintainer. I've spent the last couple of years building Nano Kit — a lightweight, modular state management ecosystem for modern web apps: signals-based stores , a router , data fetching , i18n , and SSR support , all built on the same tiny reactive core. It recently hit 1.0 , and in this post I want to give you four honest reasons to try it. 1. It's fast At the heart of Nano Kit is a push-pull reactivity system based on the algorithm from alien-signals — one of the fastest signal implementations in the JavaScript ecosystem. I didn't use alien-signals directly, though. Nano Kit needed things it doesn't provide, so I built a dedicated fork called Agera : Signal lifecycles — you can listen to signal activation and deactivation, which powers Nano Kit's mountable stores (run setup logic on first listener, clean up on last). Real tree-shaking — Agera is designed so that only the code you use ends up in your bundle; alien-signals is not well tree-shakable. The result keeps almost all of alien-signals' raw speed. Here is how @nano_kit/store compares to other popular state management libraries in a reactivity benchmark : Library Latency avg (ns) Throughput avg (ops/s) alien-signals 294.00 ± 2.24% 3,559,763 @nano_kit/store 303.55 ± 0.75% 3,365,816 svelte/store 428.58 ± 0.61% 2,479,118 rxjs 454.74 ± 0.07% 2,250,397 nanostores 1,373.2 ± 5.96% 952,399 mobx 3,474.7 ± 1.86% 306,094 valtio 5,041.3 ± 11.46% 254,109 jotai 9,454.6 ± 16.45% 157,853 effector 24,885 ± 11.78% 62,744 @reatom/core 59,430 ± 15.61% 22,741 Benchmark was run on AMD Ryzen 5 PRO 3400G with Node.js v24.14.1 That's ~3.5× faster than nanostores and an order of magnitude faster than most atomic state managers — while shipping lifecycles and mountable stores on top. 2. It's small Nano Kit exists largely because of Nano Stores . I love its philosophy: atomic stores, mountable resources, logic moved out of components, and an obsessive focus on bundle size. Nan
AI 资讯
I Built a Self-Hostable URL Shortener Because Bitly Now Charges $10/Month for Basic Links
In 2023, Bitly's free plan gave you 100 links per month with full analytics. In 2025, they slashed it to 5 links per month . Five. And they started showing full-screen interstitial ads before redirecting — even on links you created years ago. In 2026, their cheapest paid plan is $10/month — just to shorten links without ads. I was paying $120/year to turn long URLs into short ones. A problem that takes 3 lines of code to solve. So I solved it myself. For free. Forever. Introducing ZipLink ZipLink is a fast, self-hostable URL shortener built with Next.js and Firebase. Deploy it once, use it forever. No monthly fees. No link limits. No ads. No "upgrade to unlock analytics." Your links. Your data. Your domain. Your rules. https://yourdomain.com/abc123 → https://some-really-long-url.com/path/to/thing?utm=whatever That's it. That's the product. Except you own it completely. The State of URL Shorteners in 2026 (It's Embarrassing) Let me show you what the "industry leaders" are charging for what is essentially a database lookup: The Comparison Table Feature Bitly Rebrandly Short.io Dub.co TinyURL Pro ZipLink Monthly cost $10-$300/mo $13-$349/mo $19-$149/mo $24-$299/mo $9.99/mo $0 Annual cost $96-$2,388/yr $156-$4,188/yr $228-$1,788/yr $288-$3,588/yr $119.88/yr $0 Free tier links 5/month 10/month 1,000 total 25/month Unlimited (no analytics) Unlimited Custom domain Paid only Free (1 domain) Required Paid only Paid only Yes (yours) Click analytics Paid only Paid only Free (basic) Paid only Paid only Full, free Link expiration Paid only Paid only Yes Yes No Yes Password protection Enterprise only Paid only Paid Paid No Yes API access Paid only Paid only Yes Yes Paid Full, free QR codes 2 free, then paid Paid Yes Paid Paid Unlimited Self-hostable No No No Yes (complex) No Yes (simple) Data ownership Their servers Their servers Their servers Their servers Their servers Your Firebase Ads/interstitials Yes (free tier) No No No Yes (free tier) Never Links disappear if you stop pay
AI 资讯
Unhandled Promise Rejections in Node.js: Why They Silently Kill Jobs
A background worker sits quietly for weeks, chewing through a job queue without incident, and then one Tuesday afternoon it disappears mid-batch, taking forty in-flight jobs down with it. No stack trace pointing at the offending line, no alert until a customer notices their export never finished. Nine times out of ten, the culprit is one of the most under-discussed failure modes in server-side JavaScript: unhandled promise rejections. They are easy to introduce, easy to miss in code review, and in modern Node.js they no longer just print a warning — they can end your process outright. This post walks through what unhandled promise rejections actually are at the engine level, why they are far more dangerous in long-running Node.js services than in typical web requests, how Node's default behavior around them has shifted over the years, and the concrete patterns you can use to stop them from quietly killing your jobs. What an Unhandled Promise Rejection Actually Is At the JavaScript engine level, a promise is a state machine with three possible states: pending, fulfilled, or rejected. When an async operation fails — a network call times out, a database query throws, a JSON parse blows up — the promise representing that operation transitions to the rejected state and carries a reason, usually an Error object. That's all a rejection is: a value flowing down the promise's error channel instead of its success channel. The engine only considers a rejection "handled" if, by the time it does its bookkeeping (which happens on a microtask checkpoint, not synchronously), there is a .catch() handler, a second argument to .then() , or a surrounding try/catch around an await somewhere in that promise's chain. If none of those exist anywhere in the chain, the rejection is classified as unhandled. This is the precise, narrow definition of unhandled promise rejections: a promise that reaches the rejected state with zero handlers attached anywhere along its chain of consumers. It's wo
AI 资讯
I Let My AI Assistant Read and Reply to My Emails for a Week. Here’s What Actually Happened.
An AI can write a perfect email in seconds. Having a real back-and-forth conversation is much harder. Sarah runs a salon. She has an AI assistant that emails her customers when a slot opens up. Last Friday, a customer canceled his booking. The assistant sent an email: "We have an opening tomorrow at 2 PM. Want it?" The customer replied in a minute: "Yes, book it!" The assistant never saw that reply. The slot stayed open. The customer never got a confirmation. This happens more than people realise — not because it's hard to receive email, but because most setups were never wired to close the loop. Sending is easy. Wiring the whole loop isn't. To be fair, receiving and parsing email isn't some unsolved problem — providers like SendGrid, Mailgun, and Postmark have offered inbound email parsing for years. Point your domain at them, and they'll hand you the clean message. But those webhooks only push the message once. There's no inbox to check back later, and no built-in way to link a reply to the right conversation. You have to build that part yourself — and you still can't run any of it on your own servers. There's a second issue too. AI assistants sometimes send a slightly odd reply — nothing harmful, just a little off. Many managed email providers watch for exactly that pattern, and can suspend an account fast. One strange sentence, and Sarah's whole booking system could go dark with no warning. What a real AI assistant needs For an assistant like Sarah's to actually hold a conversation, a few things need to work together: Replies need to land somewhere the AI can read them They need to arrive clean, not messy They need to stay linked to the right conversation The AI needs to reply back from the same email address All of it needs to run on infrastructure you control, not three different vendors This is what we built Reloop for Reloop puts that whole loop in one place, self-hosted. When Sarah's customer replied "Yes, book it!", Reloop caught the reply, cleaned it up,
AI 资讯
Building Profitable Niche Lifestyle Stores: A Developer's Guide to E-Commerce Essentials
Building Profitable Niche Lifestyle Stores: A Developer's Guide to E-Commerce Essentials Launching a niche lifestyle e-commerce store is more than just setting up a storefront—it's a technical challenge that requires thoughtful architecture, performance optimization, and strategic content planning. Whether you're building a store for outdoor gear, fashion accessories, or humor products like humor24.se , here's what developers need to know. Choose the Right Tech Stack Most profitable niche stores run on WordPress + WooCommerce + a performance-focused theme (like Blocksy). This combination offers: Flexibility : Extend functionality without rewrites SEO-friendly : Built-in structured data support Cost-effective : No complex deployment infrastructure needed Content integration : Blog + products on the same platform Use a headless CMS approach only if you have compelling reasons (high-traffic requirements, complex frontend needs). For 99% of niche stores, the overhead isn't worth it. Core Web Vitals = Revenue Google's Core Updates consistently penalize slow stores. Prioritize: LCP (Largest Contentful Paint) < 2.5s : Optimize images (WebP/AVIF format), lazy load below-fold content, defer non-critical CSS INP (Interaction to Next Paint) < 200ms : Minimize main thread blocking, defer JavaScript CLS (Cumulative Layout Shift) < 0.1 : Use fixed image dimensions, avoid late-loading ads/widgets # Generate WebP variants of product images convert image.jpg -quality 80 image.webp # Check your Core Web Vitals # Use PageSpeed Insights API or Lighthouse CI in your deployment pipeline Each 0.1s improvement in LCP can yield 3-5% conversion uplift. Performance is a feature. Structured Data Wins Traffic Rich snippets dramatically improve click-through rates. Implement: Product schema : name , price , availability , image , brand , AggregateRating BreadcrumbList : Navigation structure FAQ schema : If you have FAQs (47% higher CTR for FAQ snippets) { "@context" : "https://schema.org/" , "@t
AI 资讯
How AI Endpoints Change the Traditional API Flow
As a backend developer, I have build hundreds of endpoints, so the typical endpoint flow is deeply ingrained in how I think about web applications. But when I started building AI-powered endpoints, I noticed an interesting shift. At first, AI endpoints looked like simple proxy endpoints with some configuration for connecting to a model: API receives request ↓ send prompt to model ↓ receive response ↓ return it to the client And it worked well until I found out that passing a prompt directly from the client was not a good idea. The endpoint could be misused for a completely different purpose, allowing someone else to consume my AI usage credits. Then I realized that the input also needed limits. Sending a large context for a specific task costs more and may produce unexpected results. So when I started looking closer, especially when I needed reliable structured output and predictable application behavior, I quickly realized that it was not that simple. Validation was no longer only guarding execution, it had also become a post-processing step. AI models are probabilistic. Even with the same input, they may return different outputs, omit required information, misunderstand instructions or return something that is technically valid but logically wrong. And because every token has a price, I cannot simply retry the request and hope for a better result. That was when I started questioning whether AI endpoints should be designed in the same way as conventional Web API endpoints. Table of Contents Conventional Web API Endpoint Flow AI-powered Web API Endpoint Flow What This Difference Changes Unpredictable Latency Retry Logic Idempotency and Side Effects Testing AI Endpoints The Output Contract Observability and Cost Summary Conventional Web API Endpoint Flow A conventional Web API endpoint usually follows a similar flow: validate request ↓ execute business logic ↓ return representation The first phase is request validation. We validate the incoming data against property
AI 资讯
Next.js 16 Cache Components: use cache, PPR, and When to Reach for Each
Next.js 16 shipped Cache Components - the feature that finally lets a single route mix static HTML, cached data, and per-request dynamic content without splitting it into separate pages. It is Partial Prerendering (PPR) made stable, plus a new use cache directive that replaces the old unstable_cache and the awkward route-segment config flags. This guide covers what changed, the three content types you now think in, and the runtime-data rule that trips up almost everyone on day one. What actually changed If you were using the experimental PPR flag, it is gone. Cache Components is a single config switch, and it turns on the whole model - static shell, cached segments, and streamed dynamic content in one route. // next.config.ts import type { NextConfig } from ' next ' const nextConfig : NextConfig = { cacheComponents : true , // replaces experimental.ppr } export default nextConfig Once it is on, every piece of your route falls into one of three buckets. The whole mental model is learning which bucket each component belongs in. The three content types Static - synchronous code, imports, and pure markup. Prerendered at build time and served instantly from the CDN. Your header, nav, and layout shell. Cached - async data that does not need to be fresh on every request. Marked with use cache . Think product lists, blog posts, dashboard stats. Dynamic - runtime data that must be fresh (cookies, headers, per-user state). Wrapped in Suspense so it streams in after the shell paints. import { Suspense } from ' react ' import { cookies } from ' next/headers ' import { cacheLife } from ' next/cache ' export default function DashboardPage () { return ( <> { /* Static - instant from the CDN */ } < header >< h1 > Dashboard </ h1 ></ header > { /* Cached - fast, revalidates hourly */ } < Stats /> { /* Dynamic - streams in with fresh data */ } < Suspense fallback = { < NotificationsSkeleton /> } > < Notifications /> </ Suspense > </> ) } async function Stats () { ' use cache ' cacheL
AI 资讯
Build a Crypto Payment Support Desk
Most developers think about crypto payments as a checkout problem. Generate an invoice. Show a payment page. Wait for a webhook. Mark the order as paid. That is the clean version. Real merchants do not live in the clean version. They live in support tickets. A customer says they paid, but the order is still pending. A payment arrives after the invoice expires. Someone sends the right amount on the wrong network. A webhook fails. A customer underpays. A support agent cannot tell whether the issue is customer error, blockchain delay, invoice expiry, fulfillment failure, or an internal system bug. This is where developers can build a real product. A Crypto Payment Support Desk is a support and operations layer for merchants that accept crypto payments. It helps support teams search payments, inspect payment timelines, classify issues, explain statuses to customers, escalate real problems, and reduce the amount of manual investigation required for every crypto payment ticket. In this article, I will use OxaPay as the example payment infrastructure because its documentation exposes the primitives needed to build this kind of product: invoice generation, payment status callbacks, HMAC-signed webhooks, payment information lookup, payment history, static addresses, SDKs, plugins, and automation integrations. This is not a generic “add crypto payments to your app” article. It is a blueprint for developers who want to build a support-facing product that merchants may actually pay for. The business idea The idea is simple: Build a support desk that sits between a merchant's payment system, order system, and support team. The merchant already accepts crypto payments. The problem is that their support team cannot quickly answer payment-related questions. Your product gives them one place to investigate cases like: “The customer says they paid, but the order is unpaid.” “The invoice expired, but a transaction later appeared.” “The payment is underpaid.” “The webhook was received,
开发者
Roll your own file-based router in under 50 lines of code
Nowadays, web frameworks come with ✨ magic ✨. Some more than others, but all of them have some. The...
AI 资讯
Character consistency isn't a seed trick: a 2-stage image pipeline that actually locks the face
If you're building an app that generates the same character across many scenes, you've probably hit the wall already: seeds drift, LoRA training is heavy and slow, and "same character, new pose" prompting quietly changes the face. The approach that actually holds up in production is a 2-stage pipeline — generate one canonical base image , then edit from that base as the reference for every new scene. Consistency comes from the reference, not the seed. Below: why the common approaches drift, how the 2-stage pipeline works, the async job queue that makes it deployable, and the serverless-GPU setup that keeps it affordable. There's a free, runnable slice of the whole transport layer at the end. Why the obvious approaches drift Seeds. A seed pins the noise , not the identity . Re-use a seed with the same prompt and you get the same image — but that's reproduction, not consistency. The moment you change the prompt ("now she's in a café"), the denoising path changes and the face re-rolls with it. Seeds give you determinism for identical inputs; they give you nothing for new scenes . Prompt-only ("the same woman as before"). The model has no memory. Every generation is a fresh sample from the distribution your words describe. "Same face as last time" isn't in the prompt vocabulary — there is no last time. LoRA per character. This one actually works — that's why everyone suggests it — but look at what it costs in an app context: curate 15–40 images per character, run a training job per character, store and load adapter weights per character, and repeat all of it whenever a user creates someone new. For a personal project, fine. For an app where users create characters on demand, you just signed up to run a training farm. The 2-stage pipeline The fix is embarrassingly direct once you see it: Stage 1 — CAST Stage 2 — RE-SCENE (repeat forever) text-to-image image-edit model "describe character" → base image + "put them in a café" → scene 1 = base image base image + "walking in
AI 资讯
Tried building GitHub's search box in Go
Hello, I'm Maneshwar. I'm building git-lrc, a Micro AI code reviewer that runs on every commit. It is...
AI 资讯
Python's Object Model in Depth: Why Two Lines That Look the Same Behave Differently
Two lines of code. Same variable. Same operator. Completely different behavior. a = [ 1 , 2 , 3 ] b = a b += [ 4 ] # line A print ( a ) # [1, 2, 3, 4] x = 1 y = x y += 1 # line B print ( x ) # 1 Line A changes a . Line B does not change x . The only difference is whether the variable holds a mutable or immutable object. To understand why this happens, you need to understand how Python actually represents variables internally. Variables Are Not Boxes The box metaphor is how most introductory programming courses explain variables: a variable is a box that holds a value. You put 5 into the box called x . Later you can replace it with 10. In Python this metaphor is accurate for immutable types and dangerously misleading for mutable types. The more accurate model: a Python variable is a name that is bound to an object. The object exists independently of the name. Multiple names can be bound to the same object. Binding a name to a new object does not affect the old object or other names that reference it. You can inspect this directly: a = [ 1 , 2 , 3 ] b = a print ( id ( a ) == id ( b )) # True -- same object, two names x = 5 y = x print ( id ( x ) == id ( y )) # True -- both point to integer object 5 Both cases start the same: two names pointing to the same object. What happens next depends on whether you mutate the object or rebind the name. Two Fundamental Operations Every operation on a Python object falls into one of two categories. Mutation : the object at a given memory address is modified. All names pointing to that address see the change. Rebinding : a name is pointed at a different memory address. Other names pointing to the original address are unaffected. List methods like .append() , .extend() , .sort() , and item assignment lst[i] = x are mutations. Assignment with = is rebinding. The += operator is either mutation or rebinding depending on whether __iadd__ is implemented and the object is mutable. Tracing Through the Object Graph a = [[ 1 , 2 ], [ 3 , 4 ]]
AI 资讯
Beyond "Chat": Architecting Intelligence with Skills and Specification Engineering
Remember the days when we used to dump all our CSS and JavaScript into a single index.html file? That's exactly what a "Mega-Prompt" is today: an unmanageable monolith. A few weeks ago, while working on the orchestration of Vibrisse Agent (my local AI agent), I hit this exact wall. I was trying to stabilize a complex task by adding instructions to a 500-line system prompt. The more rules I added, the more the model forgot the older ones. The industry has sold us the myth of the Mega-Prompt. Those famous "50 ultimate prompts" or massive blocks of incantatory text are a technical dead end. Creative writing doesn't scale in production. As a web developer, my conviction is simple: to build reliable applications, we must stop "talking" to the machine and start configuring it. This is the shift from Prompt Engineering to Context Engineering . Context Engineering: Typing and Structure The first mistake with LLMs is mixing instructions (the logic) and context (the data) into an unstructured stream of text. It's the cognitive equivalent of spaghetti code. The solution? A strict separation of concerns. A highly effective technique (documented by Anthropic, but applicable to any model, including local SLMs), is XML Tagging . Here is the "dirty" approach (classic chat): You are a security expert. Analyze this authentication code, be strict, don't write a summary, check for XSS and SQLi vulnerabilities. Here is the code: function login() { ... } And here is the "engineering" approach: <role> Application Security Expert </role> <instructions> 1. Analyze the code provided in <context> . 2. Identify vulnerabilities (focus: XSS, SQLi). 3. Do not produce an introductory summary. </instructions> <context> function login() { ... } </context> Typing the language via tags creates clear boundaries. The model knows exactly where the directive is and where the data is. The Power of Exemplars (Few-Shot Prompting) Even with clear instructions, AI can drift in output format or tone. This is wh