AI 资讯
Calling a TypeScript Backend Without Integration Code - A Simple Task Tracker with Graftcode
Most developers building frontend applications spend a lot of time writing code that communicates with their backend due to the traditional approach (using APIs). This is not because the logic is hard to implement, but because the communication itself is complex. When using standard APIs, we build routes, define request and response models, generate clients, and keep multiple layers on track with application updates. Instead of exposing backend functionality through REST endpoints and consuming it through HTTP clients, Graftcode exposes backend methods directly and generates packages that applications can install and use as dependencies. The result is a communication model that is like you are calling a library rather than consuming an API with strongly typed clients. Working with Graftcode is very simple: install your library and call its functions. In this article, we'll be building a simple task tracker or to-do list application using React and a TypeScript backend to see what working with Graftcode looks like. In this blog post, we will learn the following: Why API layers require you to maintain APIs manually How Graftcode exposes backend functionality through Graftcode Gateway How Graftcode Vision helps discover backend capabilities Familiarity with APIs and fetch() requests How React applications can use TypeScript backend logic without building API routes Why strongly-typed backend packages can improve developer experience Prerequisites Let’s get our hands a bit dirty, but before we do, there are some need-to-haves to get you started. Let’s have a look at that in this section: Latest Node version installed on your machine Basic knowledge of React and TypeScript Familiarity with how APIs and fetch requests work (for understanding how easy Graftcode’s approach is) A Graftcode account Graftcode gateway installed on your local machine With these prerequisites, you’ll first understand why most to-do list applications rely heavily on APIs for their logic and what c
开发者
React useEventListener Hook: Type-Safe DOM Events (2026)
Here's a modal close-on-Escape that quietly does the wrong thing: function Modal ({ onClose }: { onClose : () => void }) { useEffect (() => { const onKey = ( e : KeyboardEvent ) => { if ( e . key === " Escape " ) onClose (); }; window . addEventListener ( " keydown " , onKey ); return () => window . removeEventListener ( " keydown " , onKey ); }, [ onClose ]); return < div role = "dialog" > … </ div >; } If the parent passes an inline onClose={() => setOpen(false)} — and it almost always does — onClose is a new function on every render, so this effect tears the listener down and adds a fresh one on every single render of the parent. Drop onClose from the deps to stop the churn and you get the other bug: the listener now holds the first render's onClose forever, and closing the modal calls a stale closure. You can't win this with a dependency array, because the two things you want are in direct conflict: subscribe once , but always run the newest handler . The fix is to separate them — register the listener on a stable identity, and call through a ref that's kept current. useEventListener from @reactuses/core is that split, packaged. This post covers what it actually does under the hood, the four ways to name a target, exactly what TypeScript infers for each one (this part surprises people), the options that don't retrigger, and the two gotchas worth knowing before you ship it. Quick Start npm install @reactuses/core import { useEventListener } from " @reactuses/core " ; function Modal ({ onClose }: { onClose : () => void }) { useEventListener ( " keydown " , ( e ) => { if ( e . key === " Escape " ) onClose (); }); return < div role = "dialog" > … </ div >; } That's the whole fix. No dependency array, no useCallback on the parent, no cleanup to remember. The listener is added to window once when the component mounts and removed when it unmounts; the arrow function you passed is re-created on every render and it doesn't matter, because the listener never re-registers
AI 资讯
How to Fix 'command not found' (Without Reinstalling Everything)
Adapted from the Command Line Essentials Companion Guide . You install something, open a fresh terminal, type the command, and get bash: python3: command not found — or on Windows, 'python3' is not recognized as an internal or external command . The installer said it finished successfully. You can probably even find the program in your applications folder. And yet the terminal insists it doesn't exist. The instinct at this point is usually to reinstall, or install a second copy from somewhere else, hoping one of them "takes." That almost never fixes it, because reinstalling doesn't address what's actually wrong. What the error is actually telling you When you type a command, the shell doesn't scan your whole computer looking for it. It checks a specific, ordered list of directories — stored in an environment variable called PATH — and stops at the first match it finds. command not found doesn't mean the program doesn't exist anywhere on your machine. It means none of the directories in that list happen to contain it. That distinction matters, because it splits into three genuinely different problems: A typo. gerp isn't a command; grep is. This is the most common cause by a wide margin, and the easiest to rule out first. It isn't installed at all. The program genuinely doesn't exist on this machine yet. It's installed, but not somewhere the shell is looking. This is the one that catches people off guard — the software is sitting on disk, correctly installed, just outside every directory PATH currently checks. Reinstalling only ever fixes cause 2. If your actual problem is 1 or 3, a second install just gives you a second copy of a program that was never the issue. The fix, step by step Check for a typo first. Read the command back character by character. It sounds too simple to be worth a step, but it resolves this error more often than everything else combined. Confirm whether it's installed at all , independent of whether the shell can currently find it: which pytho
AI 资讯
5 Common Subnetting Mistakes That Break Real Networks
Subnetting errors rarely announce themselves as "bad math." More often, two devices make different decisions about whether a destination is local, a route points at the wrong boundary, or a cloud/VPN design contains two networks that cannot be unambiguously routed. These five failure modes are worth recognizing in live configurations. 1. The two hosts use different masks Consider Host A at 192.168.10.10/24 and Host B at 192.168.11.10/16 . A calculates that B is outside 192.168.10.0/24 , so A sends the packet to its default gateway. B calculates that A is inside 192.168.0.0/16 , so B treats A as local and tries ARP directly. The result can be asymmetric: one direction follows a router, while the reply is sent directly or never reaches the expected gateway. Check the actual prefix on both interfaces, not just the dotted decimal mask shown in a diagram. ip -br addr ip route ping -c 3 192.168.11.10 Correct the prefix so both endpoints agree, or intentionally route between two correctly defined subnets. 2. Overlapping subnets are assigned to different networks Suppose a branch uses 10.20.0.0/16 , while a cloud VPC or VPN peer also uses 10.20.0.0/16 . The problem is not that either mask is mathematically invalid. The problem is that a router cannot distinguish "the branch's 10.20.5.0/24 " from "the cloud's 10.20.5.0/24 " if both are reachable through different paths. Symptoms include traffic taking the wrong tunnel, routes that cannot be installed, or a VPN that connects but cannot reach some subnets. Inventory both sides of a tunnel and compare the complete network/prefix pairs. A longer, more specific route may make one destination appear to work while hiding the underlying overlap. ip route ip route get 10.20.5.25 traceroute -n 10.20.5.25 The durable correction is renumbering or using an intentional translation/design boundary. Adding increasingly specific routes is usually a brittle workaround. This is also why I prefer teaching subnetting inside routing and troublesh
AI 资讯
The excluded-plugin setting that Playwright ignored — fixing browser-mode updates and false residual warnings
The symptom In browser-mode maintenance (Playwright, no SSH), plugins marked as "excluded from update checks" were still being updated. After the run, a "plugin updates remaining" WARNING email arrived every time. The excluded plugins were intentionally left behind, but the residual check treated them as unfinished updates and fired a warning — a two-part problem: wrong behavior and a misleading alert. SSH path vs. Playwright path On SSH-capable sites, WP-CLI's --skip-plugins flag carries the ignored_plugins list into the update command. That path already excluded them correctly. The Playwright path was different. browser_update_remaining_plugins() worked by clicking the "select all" checkbox on update-core.php and submitting the form — no filtering at all. # Before: select-all, ignored_plugins never consulted page . check ( ' input[name= " action " ][value= " update-selected-plugins " ] ' ) for cb in page . query_selector_all ( ' input[name= " checked[] " ] ' ): cb . check () This function is the chokepoint for two flows: pure browser-mode updates ( run_browser_update_flow ) and the browser residual pass that runs after SSH updates ( run_browser_residual_update , on by default). So even SSH sites could have excluded plugins updated by the residual pass. Browser-driven bulk updates are also outside the scope of pinpoint rollback, meaning there is no automatic recovery if a wrong update goes through. Fix 1 — _ignored_plugin_slugs() and _plugin_slug_from_checkbox_value() When excluded plugins are configured, the fix replaces the select-all approach with per-checkbox evaluation. def _ignored_plugin_slugs ( site : dict ) -> set [ str ]: raw = site . get ( " ignored_plugins " , "" ) return { s . strip (). lower () for s in raw . split ( " , " ) if s . strip ()} def _plugin_slug_from_checkbox_value ( value : str ) -> str : return value . split ( " / " )[ 0 ]. strip (). lower () if " / " in value else value . strip (). lower () Plugin checkboxes on update-core.php use a va
AI 资讯
Deploying Multiple Python Bots to a Single Railway Container
A tutorial for running two or more python bots on Railway inside one container and one service, with independent crash recovery for each. Deploying Multiple Python Bots to a Single Railway Container If you're running more than one Python bot — say, a Telegram ingestion bot and a Discord notification bot that share a database — deploying each as its own Railway service means double the hosting cost and double the configuration for something that's logically one unit. This tutorial covers deploying both bots inside a single Railway container, with each one still getting fully independent crash recovery. Table of Contents Why Two Services Is Usually Overkill The Naive Fix and Why It Falls Short Step 1: Install StayPresent Step 2: Structure Your Project Step 3: Configure Multiple Bots in One Entry Point Step 4: Read Railway's Assigned Port Step 5: Deploy as a Single Railway Service Verifying Both Bots Are Running FAQs Conclusion Why Two Services Is Usually Overkill Railway (like most PaaS platforms) charges per service, and each service needs its own configuration, environment variables, and deployment pipeline. If two bots are closely related — sharing a database, a queue, or just conceptually belonging to the same project — running them as two separate Railway services duplicates all of that for no real benefit. The Naive Fix and Why It Falls Short A common first instinct is a shell script: python telegram_bot.py & python discord_bot.py & wait This runs both, but there's no real process supervision here — if telegram_bot.py crashes, nothing restarts it, and you still haven't solved Railway's HTTP port requirement, since neither script opens one. Step 1: Install StayPresent pip install staypresent[prod] # requirements.txt staypresent[prod] Step 2: Structure Your Project project/ ├── main.py ├── telegram_bot.py ├── discord_bot.py ├── requirements.txt Both bot scripts stay exactly as they are — nothing about their internal logic needs to change. Step 3: Configure Multipl
AI 资讯
How to Stop Your Discord Bot From Sleeping on Render's Free Tier
A step-by-step tutorial to stop a discord bot from sleeping on Render's free tier — the real cause, the fix, and a working code example. How to Stop Your Discord Bot From Sleeping on Render's Free Tier You've deployed your Discord bot to Render's free tier, it worked for a bit, and now it's going offline — sometimes after a few minutes, sometimes randomly. This is one of the most common issues developers hit deploying a bot for the first time, and it has a specific, well-understood cause and a fix you can ship in under ten minutes. Table of Contents Why This Happens on Render Specifically Confirming This Is Your Actual Problem Step 1: Install StayPresent Step 2: Wrap Your Bot's Entry Point Step 3: Read Render's Assigned Port Step 4: Set Your Render Start Command Step 5 (Optional): Prevent Inactivity Sleep Specifically Verifying It Worked FAQs Conclusion Why This Happens on Render Specifically Render's free-tier web services are checked for health over HTTP, and free services also spin down after a period without incoming traffic. A discord.py bot connects outward to Discord's gateway — it never opens an HTTP port of its own, which is completely normal bot behavior. Render's health checker, seeing nothing respond on the expected port, has no way to know the bot is actually working fine internally. It just sees silence, and reacts accordingly. Confirming This Is Your Actual Problem If your bot's entry point goes straight into bot.run(TOKEN) with nothing else, and Render's dashboard shows the deployment as unhealthy or repeatedly restarting with no matching error in your bot's own logs, this is almost certainly it. Step 1: Install StayPresent pip install staypresent[prod] Add it to your requirements.txt as well: staypresent[prod] discord.py Step 2: Wrap Your Bot's Entry Point Keep your existing bot code in bot.py completely unchanged. Create a new main.py : import os import staypresent staypresent . web . json ({ " status " : " running " }) staypresent . run ( " bot.py
AI 资讯
Perry Mason in: The Case of the Drifting Timer
Perry Mason in: The Case of the Drifting Timer Opening Statement You need a reactive "current time" in your Vue 3 app. A schedule grid with a red line showing "now." A live clock. A dashboard that updates every minute. Every Vue developer reaches for setInterval first. It works. But "works" and "works well" are different things. This is the story of taking a naive timer from "it ticks" to production-grade — and the four iterations it took to get there. The prosecution calls four exhibits. Let's begin. Exhibit A: The Memory Leak const currentTime = ref ( new Date ()) onMounted (() => { setInterval (() => { currentTime . value = new Date () }, 60000 ) }) It works. Sort of. The defense rests — but the prosecution is just getting started. Exhibits of negligence: The interval is never cleared. When the component unmounts, the timer keeps firing every 60 seconds forever — updating a ref nothing reads anymore, and holding its closure (and everything the ref references) in memory for the lifetime of the page. Silent. Invisible. The kind of leak that shows up in production after a user navigates around your app for 20 minutes. Exhibit B: Component-Only Cleanup const currentTime = ref ( new Date ()) let timeInterval = null onMounted (() => { currentTime . value = new Date () timeInterval = setInterval (() => { currentTime . value = new Date () }, 60000 ) }) onUnmounted (() => { if ( timeInterval ) clearInterval ( timeInterval ) }) Now we clean up. The interval is stored in a variable, cleared on unmount. A step forward. But onUnmounted has a scope limitation worth understanding: The limitation: onUnmounted only works inside components. If someone calls this logic from a Pinia store or outside a component's setup() context, onUnmounted never fires. The timer leaks silently. (Composables called synchronously during setup() are fine — Vue's docs recommend exactly that. The problem is when there's no component instance at all.) The timer fires 60 seconds after load , not at the t
开发者
Implementing IN statements using JooqTemplate
@Service public class SimpleUserService { @Autowired private JooqTemplate jt ; public List < user > selectUserInDept ( UserParam param ) { //If deptIDs==null or deptIDs. isEmpty automatically ignores this query condition // SELECT * FROM user_table WHERE name LIKE '%?%' AND dept_id IN (?,?...); return jt . queryv ( "user_table" , User . class , "name%" , param . getName (), "dept_id:in" , param . getDeptIds ()); } public List < user > selectUserNotInDept ( UserParam param ) { // SELECT * FROM user_table WHERE name LIKE '%?%' AND dept_id NOT IN (?,?...); return jt . queryv ( "user_table" , User . class , "name%" , param . getName (), "dept_id:notin" , param . getDeptIds ()); } }
开发者
Automatiza tareas repetitivas con un bot en Python
Cada tarea manual y repetitiva que haces cada semana es tiempo (y dinero) que un script de Python puede recuperarte. La automatización no es solo para grandes empresas. Primero: ¿qué vale la pena automatizar? Busca tareas repetitivas, basadas en reglas y frecuentes . Algunos ejemplos habituales: Descargar y consolidar informes cada mañana. Copiar datos entre una web y una hoja de cálculo. Enviar recordatorios o alertas. Vigilar precios o cambios en una página. Una regla práctica: si puedes explicar la tarea como una lista de pasos sin excepciones, probablemente se puede automatizar. Las herramientas del ecosistema Python requests / httpx para hablar con APIs y webs. BeautifulSoup / Playwright para web scraping (Playwright cuando la página carga con JavaScript). pandas para transformar datos. APScheduler o cron para ejecutarlo en un horario. Bots de Telegram o Discord para recibir avisos donde ya estás. Un ejemplo mínimo Vigilar el título de una página y avisar si cambia: import requests from bs4 import BeautifulSoup def titulo ( url ): html = requests . get ( url , timeout = 10 ). text return BeautifulSoup ( html , " html.parser " ). title . string . strip () anterior = titulo ( " https://example.com " ) # ...ejecutado por cron cada hora... actual = titulo ( " https://example.com " ) if actual != anterior : print ( " ¡Cambió! " ) # aquí enviarías un mensaje de Telegram De script a bot fiable Un script que corre en tu portátil es un buen comienzo, pero un bot fiable vive en un servidor, registra lo que hace, maneja errores (reintentos, tiempos de espera) y te avisa si algo falla. Ese salto —de experimento a herramienta en la que confías— es donde más aporta un desarrollador. ¿Tienes una tarea que odias hacer a mano? Probablemente se pueda automatizar. Cuéntame cuál es y te digo cómo abordarla: contacto .
开发者
Introducción a los Data Lakes Parte 2
En el post anterior exploramos qué es un Data Lake y por qué son tan importantes en el ecosistema de datos actual. Ahora es momento de ensuciarnos las manos y ver exactamente qué servicios de AWS necesitamos para construir un Data Lake completamente serverless y cómo orquestarlos. Los Servicios Fundamentales Un Data Lake serverless en AWS se construye sobre cinco pilares fundamentales que trabajan en conjunto para crear una solución escalable y costo-eficiente: Storage Procesamiento Catalogo Seguridad Explotación Amazon S3 - El Corazón del Storage S3 no es solo nuestro sistema de archivos, es la piedra angular del Data Lake. Aquí almacenamos tanto los datos crudos como los procesados, y su organización es crucial para el rendimiento y los costos. Estructura de carpetas de un data lake estandar: data-lake-bucket/ ├── raw/ # Datos sin procesar │ ├── year=2024/ │ ├── month=12/ │ └── day=15/ ├── processed/ # Datos transformados │ ├── bronze/ # Limpieza básica │ ├── year=2024/ │ ├── month=12/ │ └── day=15/ │ ├── silver/ # Transformaciones de negocio │ ├── year=2024/ │ ├── month=12/ │ └── day=15/ │ └── gold/ # Datos listos para consumo │ ├── year=2024/ │ ├── month=12/ │ └── day=15/ └── athena-results/ # Resultados de queries Notarás que todo el data lake se encuentra en un mismo bucket, esto es lo más recomendable ya que S3 tiene un límite de 100 bucket que podemos crear por cuenta (no importa la región, ya que S3 es un servicio global) Configuraciones clave en S3: Versionado habilitado para auditoría y rollback Lifecycle policies para optimizar costos (Standard → IA → Glacier) Server-side encryption con KMS para seguridad si es necesario. Cross-region replication para disaster recovery AWS Glue - El Motor de Transformación Glue es suite de servicios de data serverless que maneja tanto el descubrimiento de esquemas como las transformaciones de datos. Componentes principales: Glue Jobs : Herramienta predilecta para ejecutar ETLs, nos permite procesar y transformar los dato
AI 资讯
AI Incident Copilot Guide for GCC Operations
🚀 Technical Briefing: This tutorial is part of our deep-dive series on Agentic Workflows at Gate of AI . For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the original article here . <p>Tutorial</p> <h1>Design a Safer AI Incident Copilot for GCC Operations</h1> <p>An AI incident copilot can help an operations team turn approved engineering facts into a clearer draft for stakeholders. It should not be treated as an autonomous incident commander, a source of truth, or an automatic publishing system. This tutorial explains how to define a safe operating model before choosing a framework, model provider, deployment platform, or integration.</p> <h2>Why incident copilots need a security-first design</h2> <p>During an incident, teams work under pressure. They need to communicate what is happening, who may be affected, what mitigation is under way, and when the next update will arrive. These messages must be accurate, calm, and consistent. An AI assistant may help prepare a first draft, but it can also amplify mistakes if it is allowed to infer missing facts, read untrusted material, or publish messages without review.</p> <p>The available security research on Copilot-style systems is a direct reason to design cautiously. Researchers have demonstrated ways AI systems can be manipulated to provide false references to files, extract some private data, and bypass security protections. The same research describes proof-of-concept abuse that can turn an AI assistant into an automated spear-phishing mechanism after an attacker gains the necessary access. These are not minor quality issues. They show that an AI feature connected to organizational information can become a security boundary.</p> <p>For an incident copilot, the safest initial scope is deliberately narrow: accept a small set of verified facts supplied by an authorized incident lead, create a draft in a fixed communication format, and require a human to review and pub
AI 资讯
DNS Troubleshooting with dig: The Commands DevOps Engineers Actually Need
A surprising share of "the app is down" pages resolve to a name-resolution problem, not a broken service. The service is fine; the client can't turn a name into an address. dig is the precision tool for proving that in seconds instead of guessing. Think about it as a resolution chain, not "is DNS broken" When a name fails, work the chain: which resolver did the client ask, what did that resolver return, and does it match what authoritative DNS actually says? Most incidents live in the gap between those three. The method is boring and reliable: observe the symptom, form a hypothesis about where in the chain it breaks, test with one query, read the evidence, fix, then validate. The single most important habit: query the name from the same host and the same resolver the app uses. Running dig from your laptop proves nothing about what the pod or VM sees. The record types worth knowing You don't need all of them, but you need to recognize them: A / AAAA — name to IPv4 / IPv6 address. The usual suspect. CNAME — an alias pointing at another name. A stale or wrong CNAME sends traffic somewhere unexpected. MX — mail routing. TXT — SPF, DKIM, domain verification, and other metadata. NS — which servers are authoritative for a zone. SOA — the zone's serial and TTL defaults; the serial tells you whether a change has propagated. PTR — reverse lookup, IP back to name. The commands that actually earn their place Start with the quick answer, then get precise. dig +short api.internal.example.com +short strips everything except the answer. If it prints an IP, resolution works from this host. If it prints nothing, you have a real failure to chase. Empty output is a signal, not an error. dig api.internal.example.com A The full form. Read the status in the header: NOERROR with an ANSWER section is good; NXDOMAIN means the name genuinely doesn't exist; SERVFAIL points at a broken upstream or DNSSEC issue. Also note which SERVER answered at the bottom — that's the resolver you're actually
AI 资讯
React useScrollLock Hook: Lock Body Scroll for Modals (2026)
Your modal is open, centered, perfect. Then someone flicks the overlay and the page behind it scrolls away underneath. Everyone's first fix is the same three lines: useEffect (() => { document . body . style . overflow = open ? " hidden " : "" ; }, [ open ]); It works on your laptop. Then the bug reports arrive: On iPhone the page still moves. iOS Safari rubber-band scrolls the document by touch even with overflow: hidden on <body> . Something else got wiped. "" isn't necessarily what was there before — you just erased whatever your design system or CSS-in-JS had set inline. Two overlays, one frozen page. A drawer and a lightbox both own body.style.overflow ; close them in the wrong order and the page never scrolls again. The layout jumps the instant the desktop scrollbar disappears. useScrollLock from @reactuses/core is those three lines with the hard parts handled: it restores the exact inline overflow it replaced, adds a touchmove guard on iOS that still lets your modal's own content scroll, exposes the lock as React state you can render off, and works on any element — not just <body> . This post covers what it actually does line by line, why overflow: hidden is not enough on iOS, how it compares to the position: fixed and body:has(dialog[open]) approaches, and the six gotchas that show up in real apps. Quick Start npm install @reactuses/core import { useScrollLock } from " @reactuses/core " ; import { useEffect } from " react " ; function Modal ({ open , onClose , children }: ModalProps ) { // a getter, not `document.body` — see the SSR gotcha below const [, setLocked ] = useScrollLock (() => document . body ); useEffect (() => { setLocked ( open ); return () => setLocked ( false ); // release even if we unmount while open }, [ open , setLocked ]); if ( ! open ) return null ; return ( < div className = "overlay" onClick = { onClose } > < div className = "sheet" onClick = { e => e . stopPropagation () } > { children } </ div > </ div > ); } The signature: const [
AI 资讯
Tokens per Second Benchmarks Explained: What You're Actually Measuring
What tok/s really measures, how concurrency changes it, and why a single-user benchmark is not the whole story for local LLM performance. A Few Moments Later… How Fast Is "Fast"? Every interface in the world of local AI eventually shows you that dreaded spinner, and on the wrong setup it sits there long enough that your brain supplies the meme: "A few moments later…" That pause is a number wearing a disguise. Somewhere inside your machine, the model is grinding out tokens — fragments of words — and the only question that matters is how many of them it produces per second. Tokens per second (tok/s) is the universal speedometer of local LLMs, quoted in every benchmark and every GPU review. But it is also one of the most misleading numbers in the field, because the same model can measure 45 tok/s or 793 tok/s depending on how you test it. This guide explains what the number actually means, why it moves so dramatically, and how to read a benchmark without fooling yourself. What a Token Actually Is Before speed makes sense, the unit has to. Models do not read words; they read tokens, which are chunks of text roughly three-quarters of a character on average in English. The word "calculator" might be one token or three, depending on the tokenizer, and this is not idle trivia — it is the reason the same prompt can cost a different amount across providers, as the Token Counter Calculator shows in practice. Because tokens are the unit of both billing and speed, "tokens per second" is the single number that connects all three corners of the local AI decision: how fast the model answers (tok/s), how big the model is (parameters), and what it costs to run (hardware amortized over time). A model doing 50 tok/s reads roughly 100-150 words per second — comfortably faster than you can read. A model stuck at 5 tok/s feels like a slow internet connection in 1998. The Single-User Number Is Not the Whole Story Here is the trap: most consumer benchmarks report tok/s at one user, one requ
AI 资讯
GPT-4o Mini Fine-Tuning: Evaluation-First Guide
🚀 Technical Briefing: This tutorial is part of our deep-dive series on Agentic Workflows at Gate of AI . For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the original article here . An evaluation-first guide to deciding whether GPT-4o mini fine-tuning is justified for a narrowly defined language task. This article uses the available research context rather than assuming unverified API capabilities, model snapshots, pricing, or deployment features. GPT-4o Mini Fine-Tuning: Start With Evidence, Not an Upload Fine-tuning is often presented as the next step after prompt engineering, but the available evidence does not support treating it as an automatic upgrade. Before preparing a dataset or committing to a training workflow, define the task, establish a baseline, select measures that reflect the real objective, and decide what result would justify changing the system. The verified research context is especially relevant for text transformation. A TREC 2024 Plain Language Adaptation of Biomedical Abstracts study evaluated prompt engineering, a two-AI-agent approach, and fine-tuning with OpenAI GPT-4o and GPT-4o mini models. Its objective was to simplify biomedical abstracts for a K-8 audience, approximately 13- to 14-year-old students. The study used qualitative assessments for simplicity, accuracy, completeness, and brevity on 5-point Likert scales, together with readability measures including Flesch-Kincaid grade level and the SMOG Index. Its results are a useful warning against simplistic claims. Prompt engineering with GPT-4o mini and the two-agent approach showed stronger qualitative performance in that evaluation. Fine-tuned models excelled in accuracy and completeness, but were less simple. The paper also reported that GPT-4o mini prompt engineering outperformed the evaluated iterative two-agent and GPT-4o fine-tuning approaches on its qualitative results. That is not a universal verdict on fine-tuning. It is ev
开源项目
.NET 10 dotnet tool exec: Pin the Version and Feed in CI
A CI step that says dotnet tool exec Some.Tool looks isolated, but it is not fully reproducible. Without a version, the command can resolve the latest package from the configured feeds. Machine-level NuGet settings can also change which feeds participate. I use .NET 10 dotnet tool exec with an exact @version and an explicit feed policy when I want one-shot tooling without a global install or a committed tool manifest. The command is stable from the .NET 10.0.100 SDK onward. Microsoft describes it as a temporary invocation: the package is downloaded to the NuGet cache, executed, and left out of PATH . That is convenient for CI, but temporary installation does not automatically mean deterministic selection. Why .NET 10 dotnet tool exec can drift The official command reference documents three useful selection modes: Some.Tool can resolve the latest version when no local manifest supplies one. Some.Tool@2.* stays on a major version, but still floats within that range. Some.Tool@2.4.1 requests one exact package version. For CI, I prefer the third form. A new tool release should arrive through a reviewed change, not because the next clean runner happened to restore later. The feed is a separate input. --add-source adds another source, and NuGet can query feeds in parallel. If the same package and version exists on more than one feed, the fastest response can win. That may be acceptable for interactive experimentation. It is a poor default for a build gate. .NET 10 is currently an active LTS channel . I still pin the SDK used by CI as well, because a package pin controls the tool package, not the CLI that resolves and launches it. Pin the version and feed together For a repository policy, I give dotnet tool exec a checked-in NuGet.Config . This sample uses a generated local feed, so it needs no credentials or external package call: <?xml version="1.0" encoding="utf-8"?> <configuration> <config> <add key= "globalPackagesFolder" value= "./artifacts/global-packages" /> </conf
AI 资讯
NiceGUI: crea una aplicación web en Python sin escribir JavaScript
Si sabes Python pero el frontend te frena, NiceGUI es una de las mejores noticias de los últimos años: te permite construir aplicaciones web completas —con botones, formularios, gráficos y navegación— usando solo Python. ¿Qué es NiceGUI? Es un framework construido sobre FastAPI (backend) y Quasar/Vue (frontend). Tú escribes Python; NiceGUI genera la interfaz en el navegador y mantiene sincronizado el estado por ti. No necesitas HTML, CSS ni JavaScript para empezar. Lo simple que es Una app con un botón que muestra un mensaje son literalmente cuatro líneas: from nicegui import ui ui . button ( ' Saludar ' , on_click = lambda : ui . notify ( ' ¡Hola! ' )) ui . run () La jerarquía de la interfaz se expresa con context managers , que reflejan cómo se anidan los elementos: with ui . card (): ui . label ( ' Iniciar sesión ' ). classes ( ' text-xl font-bold ' ) usuario = ui . input ( ' Usuario ' ) clave = ui . input ( ' Clave ' , password = True ) ui . button ( ' Entrar ' , on_click = lambda : entrar ( usuario . value , clave . value )) Añadir estado reactivo, formularios, tablas o rutas ( @ui.page('/panel') ) es igual de directo. ¿Para qué es ideal? MVPs y prototipos: validar una idea en días, no semanas. Dashboards internos y paneles de datos. Herramientas internas para tu equipo, sin montar un frontend aparte. Demos de modelos de IA o scripts que necesitan una interfaz. ¿Cuándo NO es la mejor opción? NiceGUI renderiza en el cliente, así que para sitios donde el SEO del contenido es crítico (un blog, una landing pública que debe posicionar) conviene complementarlo con buenas meta etiquetas y datos estructurados, o valorar renderizado en servidor. Para aplicaciones, dashboards y herramientas internas es una elección excelente y muy productiva. Rendimiento y despliegue Una app NiceGUI se despliega como cualquier app de FastAPI/Uvicorn, normalmente detrás de nginx con systemd. Sirve los estáticos desde nginx y usa ui.run(show=False) en producción para no abrir un navegador
AI 资讯
Your verifier will be gamed by the thing it verifies
Two agents finish the same task and report back. Fixed. The migration now handles null values. It wrote the code. It never ran it. Fixed. Added a null-handling layer, refactored the migration runner into a strategy pattern, and introduced a validation module. Every word true. All of it works. None of it asked for, and that strategy pattern is now yours to maintain forever. Point your code-review agent at both. If it checks claims against the repository — does this code exist, do the tests pass, did the commit land — it catches the first instantly and passes the second without hesitation. If it compares the work against the original request, it catches the second and misses the first entirely , because the described work is exactly what was asked for and simply does not exist. Neither reviewer is broken. They answer different questions. Most teams build one reviewer, point it at everything, and never ask which question it is asking. So I built reviewers that named what they were hunting. That worked, briefly, and then taught me something worse. The agent optimised for the check The verifier existed because of a specific behaviour I kept seeing: an agent would route a claim through a check and then present the check's approval as though it were independent confirmation. Not fabrication — something subtler. Authority laundering. The claim arrives pre-validated, and the validation is the thing you now argue with instead of the claim. Once a verifier existed, the behaviour adapted. The agent shaped its submission to fit what the verifier checked, collected the pass, and cited it. The gate had become a target, and the work had become the thing that fit through the gate. I first saw this in one model. Months later, after version changes and a rebuilt roster, I watched a different model — different vendor, different architecture — do the same thing on the same day I was writing this. Which is why "know your model's failure mode" is weak advice Models do fail in characterist
AI 资讯
Distributed Locking in Practice: Guarantees, Failure Scenarios and Better Alternatives (2/4)
In this article, we'll explore the mechanisms to solve the coordination problem. 8. Introducing Leases To address the problem of permanent ownership, distributed systems typically replace it with temporary ownership. This concept is known as a lease . Instead of granting indefinite control over a resource, the coordination service assigns ownership for a limited period of time. Rather than stating, “You own this resource until you explicitly release it,” the system instead says, “You own this resource for the next 30 seconds.” This changes the interaction model significantly. Acquire Lease | v Execute Work | v Renew Lease | v Continue Processing As long as the application remains healthy, it periodically renews the lease to maintain ownership. If the application crashes or becomes unresponsive, it can no longer renew the lease. Once the lease duration expires, ownership is automatically revoked. At that point, another application becomes eligible to acquire the lease and continue the work. Leases solve a critical problem in distributed systems: they prevent abandoned locks from blocking progress indefinitely . The system can recover automatically without manual intervention. However, while leases improve availability, they also introduce a new class of subtle and more complex problems. Leases Depend on Time To understand the next challenge, assume the lease duration is thirty seconds. Application A successfully acquires the lease. Lease Granted Duration = 30 seconds After twenty seconds, the JVM begins a long Full Garbage Collection cycle. This pause lasts forty seconds, significantly longer than the lease duration. The timeline now becomes problematic. Lease Granted | | Processing | | GC Pause (40 sec) | | Lease Expires While Application A is paused, the lease expires. During this time, another application requests access to the same resource. The coordination service observes that the previous lease has expired and therefore grants ownership to Application B. Appl