AI 资讯
Why phpMyAdmin migrations break plugin settings — and why `wp search-replace` doesn’t
After a domain migration or HTTPS switch, "all plugin settings are gone" or "Elementor layouts are broken" is a common outcome. The cause, in most cases, is running a string replacement against the WordPress database without accounting for PHP serialized data. WordPress stores plugin configurations, custom field values, and widget settings in PHP’s serialized format. Standard SQL replacements — phpMyAdmin’s find-and-replace, raw UPDATE statements, sed on a .sql dump — rewrite the string value without updating the length metadata that serialization embeds alongside it. The result is a database that appears intact but returns false on every read of the affected values. wp search-replace handles this correctly. Understanding why makes the pre- and post-execution steps more deliberate. What PHP serialization stores alongside the value A serialized entry in WordPress looks like this: a : 2 : { s : 4 : "home" ; s : 22 : "http://example.com/top" ; s : 5 : "title" ; s : 8 : "My Site" ;} The segment s:22:"http://example.com/top" means "a string of 22 bytes." The s:N: prefix records the byte length. When a simple string replacement changes http://example.com to https://example.com : Before: s:22:"http://example.com/top" (22 bytes) After: s:22:"https://example.com/top" (23 bytes) The s:22 stays unchanged even though the actual string is now 23 bytes. PHP’s unserialize() detects this mismatch and returns false . The plugin reads false instead of its configuration array and behaves as though the settings were never saved. phpMyAdmin’s find-and-replace executes a SQL UPDATE at the storage layer. No PHP context exists there — it can’t know the column contains serialized data, and it doesn’t adjust the length prefix. How wp search-replace handles it wp search-replace operates at the PHP layer, not the SQL layer: Reads each column value Checks whether it’s serialized using is_serialized() If serialized: calls unserialize() to expand it into a PHP array or object Applies the string r
AI 资讯
One OpenAI-Compatible Endpoint for Multiple LLM Providers: A Practical Setup Guide
When an application starts using more than one language model provider, the hard part is rarely the first API call. The hard part is everything that follows: separate credentials, different request shapes, provider-specific errors, billing dashboards, and model migrations scattered across the codebase. A useful way to reduce that surface area is to keep one OpenAI-compatible client contract and move provider choice into configuration. This guide shows the smallest working setup with Routara , plus the production checks I recommend before sending real traffic. 1. Keep the SDK, change the endpoint If your project already uses the OpenAI Python SDK, the client initialization is the only part that needs to change: import os from openai import OpenAI client = OpenAI ( api_key = os . environ [ " ROUTARA_API_KEY " ], base_url = " https://api.routara.ai/v1 " , ) response = client . chat . completions . create ( model = " deepseek-chat " , messages = [ { " role " : " user " , " content " : " Explain idempotency in two sentences. " } ], ) print ( response . choices [ 0 ]. message . content ) Store the key in an environment variable. Do not put it in browser code, a public repository, screenshots, or support messages. The same pattern works in Node.js: import OpenAI from " openai " ; const client = new OpenAI ({ apiKey : process . env . ROUTARA_API_KEY , baseURL : " https://api.routara.ai/v1 " , }); const result = await client . chat . completions . create ({ model : " deepseek-chat " , messages : [{ role : " user " , content : " Return one short test sentence. " }], }); console . log ( result . choices [ 0 ]. message . content ); 2. Treat model IDs as configuration Do not spread model names throughout the application. Put them in environment variables or a typed configuration object: model_id = os . environ . get ( " ROUTARA_MODEL " , " deepseek-chat " ) That makes model evaluation and rollback much safer. Routara's live model catalog is the source of truth for current availa
AI 资讯
BUILDING GREENWOOD ACADEMY DATABASE USING POSTGRESQL
INTODUCTION Creating Greenwood academy database is essential for managing the students, subject and exam results efficiently. PostgreSQL, a powerful open-source relational database system, offers the perfect foundation for such a project. The main areas areas in SQL covered in this projects are : 1. DDL (Data Definition Language) DDL commands define, modify, and change the physical structure of database objects like tables and schemas. The first step is to create a greenwood academy schema using the create command. create schema greenwood_academy ; set search_path to greenwood_academy ; Next is to crete tables in the schema; The schema has 3 tables students,subject and exam results. create table greenwood_academy . students ( student_id INT PRIMARY key , first_name VARCHAR ( 50 ) NOT null , last_name VARCHAR ( 50 ) NOT null , gender VARCHAR ( 1 ), date_of_birth DATE , class VARCHAR ( 10 ), city VARCHAR ( 50 ) ); create table greenwood_academy . subject ( subject_id INT PRIMARY key , subject_name VARCHAR ( 100 ) NOT null unique , department VARCHAR ( 50 ), teacher_name VARCHAR ( 100 ), credits INT ); create table greenwood_academy . exam_results ( result_id INT PRIMARY key , student_id INT NOT null , subject_id INT NOT null , marks INT NOT null , exam_date DATE , grade VARCHAR ( 2 ) ); ALTER - This command changes the structure of tables in a database. Core Actions You Can Perform Add columns : Insert a new column and its data type into a table. The school realised that the nthey forgot to add phone numbers in the students table. The following command is used to add the data alter table greenwood_academy . students add column phone_number VARCHAR ( 20 ); Rename colums : Change the name of a table or a column. The column credit has to be changed to credit hours alter table greenwood_academy . subject rename column credits to credit_hours ; Drop columns : Delete an unwanted column from a table. Later the school relised that the phone number column is nolonger needed. a
AI 资讯
From GitHub Issue to Pull Request: Running Claude Code Unattended
You already run Claude Code by hand: copy issues into a prompt, watch it work, check the diff, and if something breaks halfway through, you restart it. This works fine for one task at a time, but it falls apart when you have 10 tasks simultaneously. Claude Code is good at handling routine engineering tasks: bug fixes, dependency bumps, and small features, when the prompt is clear and the task is scoped. But when it comes to scaling, you need an infrastructure with isolated workspaces, retry logic, state that survives a restart, and tracker integration, not to waste time on babysitting. Sortie removes the manual work. You label an issue, Sortie picks it up, creates an isolated workspace, runs the agent, retries it if it stalls, and opens a pull request when it's done. This article describes how to set the entire process from an empty directory to a GitHub issue turning into a PR without you touching the keyboard in between. What you need A GitHub repository you control Export two environment variables: ANTHROPIC_API_KEY - authenticates Claude Code GITHUB_TOKEN - it's read by tracker.api_key: $GITHUB_TOKEN for polling/updating issues, and it's the same token gh pr create inside the after_run hook uses to open the PR, so it needs Issues: read/write, Contents: read, and Pull requests: read/write scopes on that repository, all on one fine-grained PAT. Push access to the repository over SSH. The after_create hook below clones with git@github.com:... , so git authenticates with your SSH key, not with GITHUB_TOKEN . Verify with ssh -T git@github.com . If you'd rather stay on one credential, swap the clone URL for https://${GITHUB_TOKEN}@github.com/yourorg/yourrepo.git and give the token Contents: read/write. In your repository, create the agent-ready label — you need it to exist before you can put it on an issue, and query_filter finds nothing without it. Creating in-progress , review , and done up front is also worth doing: GitHub does create a missing label when Sortie ap
AI 资讯
🏢 Building Enterprise-Ready AI Agents 🤖 — A Practical Field Guide 📚
How to design, ship, and operate an AI agent that is reliable, efficient, performant, scalable, and secure enough to serve real companies — from a 5-person startup to a 50,000-person enterprise. This guide distills hard-won lessons from production agents (Claude Code, OpenHands, SWE-agent, GoClaw, Hermes, nanobot, PicoClaw, ZeroClaw, Multica, Paperclip) and grounds them in current engineering guidance from Anthropic and OpenAI plus the security and compliance standards you'll actually be audited against (OWASP Top 10 for Agentic Applications, NIST AI RMF, the EU AI Act, and 2025–2026 prompt-injection research). It focuses on the parts most articles skip: the enterprise tax — governance, security, compliance, integration, cost control, and the operating model — that separates a demo from a system a CISO will sign off on. 📖 How to use this guide Read Parts 0–2 to decide whether and what to build. Most failed agent projects die here. Read Parts 3–7 for the architecture and reliability engineering. Read Parts 8–10 for the enterprise gates: security, compliance, multi-tenancy, observability, cost. Read Parts 11–15 for delivery, scale & rollout: deployment topologies (SaaS/self-hosted/hybrid), how to adopt from pilot to org-wide, how to handle thousands of concurrent requests, the operating model, and a 30/60/90 plan. Every part ends with an ✅ Actionable checklist . Skim those for a design review. 📋 Table of Contents 🧮 Part 0 — The Core Equation 🧭 Part 1 — Decide Before You Build: Workflow vs Agent, Build vs Buy 🏛️ Part 2 — The Enterprise Tax: What Actually Changes 🏗️ Part 3 — Reference Architecture: The Layered Stack 🔄 Part 4 — The Reliable Kernel: The Agent Loop 🛠️ Part 5 — Tools & Enterprise Integration 🧠 Part 6 — Context & Memory: The Cost Center 🛟 Part 7 — Reliability Engineering 🔐 Part 8 — Security, Compliance & Governance 🧱 Part 9 — Multi-Tenancy & Isolation 📊 Part 10 — Observability, Evals & Cost Governance 🚀 Part 11 — Deployment & Delivery Models 📈 Part 12 — The
AI 资讯
Migrating a Rich Text Editor : CKEditor 5 to SynapEditor (with code)
Disclosure: I work on the team behind SynapEditor. 🧩 TL;DR: Moving from CKEditor 5 to SynapEditor is a one-to-one swap in three steps: installation, toolbar config, and content/event APIs. The main reason to consider it is Office document fidelity (Word, PowerPoint, Excel import/export). Full runnable example at the end. Switching rich text editors sounds like a big job, but most of the work is a straightforward, one-to-one swap. This guide walks through moving an existing CKEditor 5 integration over to SynapEditor: loading the library, wiring up the toolbar and content APIs, and a complete working example you can copy and run. ⚖️ Which is better: CKEditor or SynapEditor? Both CKEditor and SynapEditor are mature, capable editors. If you already have CKEditor running, it clearly does a lot right. So the question isn't really "which is better" in the abstract, it's which one fits where your product is heading. Two things tend to drive the decision: 📜 Licensing and support. CKEditor 4 reached end of life in 2023, and security fixes now sit behind a paid Extended Support agreement. If you're revisiting the integration anyway, it's a natural moment to reconsider the editor itself. 📄 Office documents. This is where SynapEditor differs most. It imports a broad range of office formats: MS Word (.doc, .docx), PowerPoint (.ppt, .pptx), Excel (.xls, .xlsx, ODT, and HTML, and exports back to Word (.docx) with formatting preserved. If your users upload real documents and expect the layout to survive, that's worth weighing. CKEditor 5 SynapEditor Core editing ✅ ✅ CKEditor 4 still supported Paid ESM only n/a Word / PPT / Excel import-export Limited ✅ Native With that out of the way, let's migrate. 📋 What you'll need [ ] An existing CKEditor 5 integration [ ] A SynapEditor license and API key (free at Get Started ) [ ] About 15 minutes for a basic swap ⚙️ 1. Installation CKEditor 5 loads from a single script. SynapEditor loads from a script and a stylesheet: the UI is styled by tha
AI 资讯
React useDeepCompareEffect: Fix useEffect Object Dependencies (2026)
React useDeepCompareEffect: Fix useEffect Object Dependencies (2026) You wire up a fetch. The endpoint takes a query object, so you pass it in the dependency array. The effect fires, sets state, the component re-renders, the query object is rebuilt — a brand-new object with identical contents — and the effect fires again. You have written an infinite loop, and React thinks it did exactly what you asked. function Results ({ term , page }: Props ) { const [ rows , setRows ] = useState ([]); const query = { term , page , sort : ' desc ' }; // new object, every render useEffect (() => { fetchRows ( query ). then ( setRows ); // setRows → re-render → new query → 🔁 }, [ query ]); } useDeepCompareEffect from @reactuses/core is a drop-in replacement for useEffect that compares dependencies by value instead of by reference. Same signature, same cleanup semantics — the effect just stops firing when nothing actually changed. Everything below is the real implementation, TypeScript-first, including the parts that cost you something. Why useEffect Can't See It React compares dependency arrays with Object.is , element by element. For primitives that's exactly what you want: 5 is 5 , 'desc' is 'desc' . For anything with an identity — objects, arrays, Date s, Map s, functions — it compares the reference , and a literal written inside a component body produces a fresh reference on every single render: Object . is ({ term : ' react ' }, { term : ' react ' }); // false — different objects So the dependency "changed" on every render, by React's definition. This isn't a bug in useEffect ; reference equality is the only comparison that's O(1), and React runs it on every render of every component. The cost of value comparison is real, and React declines to pay it on your behalf. Which leaves you paying it — one way or another. The Usual Workarounds, and Where They Fray Memoize the object. Correct, and the right answer when there's one dependency: const query = useMemo (() => ({ term , page
AI 资讯
Deploying to AWS Lightsail with a Docker image from ECR
Lightsail is a good home for a single small container: flat pricing, bandwidth included, and none of the VPC/security-group ceremony of EC2. The one rough edge is pulling a private image from Amazon ECR , because a standard Lightsail instance can't authenticate to ECR the way EC2 can. This post walks the whole path. The pipeline we're building: docker build ──push──> ECR (private repo) ──pull──> Lightsail instance ──run──> container What you'll need An AWS account and the AWS CLI installed locally. Docker installed locally (to build) and on the Lightsail box (to run). A Dockerfile that produces a runnable image. If you're deploying a Next.js app, a standalone output image works well. 1. Create the ECR repository ECR is a private Docker registry. Create one repository per image: aws ecr create-repository \ --repository-name project-name \ --region us-east-1 Note the repositoryUri in the output — it looks like: <account-id>.dkr.ecr.us-east-1.amazonaws.com/project-name You'll use that URI everywhere below. Export it to save typing: export ECR_URI = <account-id>.dkr.ecr.us-east-1.amazonaws.com/project-name export AWS_REGION = us-east-1 2. Build the image locally First, the Dockerfile . This is a multi-stage build for a Next.js app using output: "standalone" — the first stage installs dependencies and builds, the second copies only the traced runtime files into a slim image that runs as a non-root user: FROM node:24-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build FROM node:24-alpine WORKDIR /app ENV NODE_ENV=production ENV PORT=3000 ENV HOSTNAME=0.0.0.0 # Standalone output ships only the traced files needed to run the server. # public and .next/static are not included by default and must be copied in. # --chown makes the files writable by the non-root user so Next.js can write # its runtime cache to /app/.next/cache. COPY --from=builder --chown=node:node /app/public ./public COPY --from=builder --chown=node:node /app/.next/stand
AI 资讯
Run Kubernetes in Docker on Ubuntu for Local Development
There's a delightfully literal answer to "Kubernetes with Docker": kind — Kubernetes IN Docker. Each node is a Docker container running a full Kubernetes node image. On an Ubuntu workstation it gives you a real, throwaway, multi-node cluster in about 30 seconds. It's my default for local dev and for CI. Prerequisites on Ubuntu You need Docker Engine and kubectl . If you don't have Docker yet: sudo apt-get update && sudo apt-get install -y docker.io sudo usermod -aG docker $USER && newgrp docker # run docker without sudo Install kind (single static binary): curl -fsSLo ./kind https://kind.sigs.k8s.io/dl/latest/kind-linux-amd64 chmod +x ./kind && sudo mv ./kind /usr/local/bin/kind kind version A one-command cluster kind create cluster --name dev kubectl cluster-info --context kind-dev docker ps # you'll see a dev-control-plane container — that's your node kind wrote a kubeconfig context for you. Tear the whole thing down just as fast: kind delete cluster --name dev A realistic multi-node cluster Most bugs only show up with more than one node (scheduling, affinity, PodDisruptionBudgets). Define it in a config file: # kind-cluster.yaml kind : Cluster apiVersion : kind.x-k8s.io/v1alpha4 nodes : - role : control-plane kubeadmConfigPatches : - | kind: InitConfiguration nodeRegistration: kubeletExtraArgs: node-labels: "ingress-ready=true" extraPortMappings : - containerPort : 80 hostPort : 8080 protocol : TCP - role : worker - role : worker kind create cluster --name dev --config kind-cluster.yaml kubectl get nodes The extraPortMappings bit is the trick people miss: it forwards a port from your Ubuntu host into the control-plane container, so an ingress controller inside the cluster is reachable at http://localhost:8080 . Loading a locally-built image (no registry needed) This is kind 's best feature for the Docker workflow. Build with Docker, push straight into the cluster's nodes — no registry round-trip: docker build -t myapp:dev . kind load docker-image myapp:dev --name
AI 资讯
Git Worktrees: Replace Your Pile of Clones with One Manageable Repository
Table Of Contents What is a Git worktree? Why use worktrees instead of several clones? A practical directory convention Everyday Git worktree commands Consolidating several independent clones Safety rules before starting Phase 1: Inventory every clone Phase 2: Choose the canonical repository Phase 3: Decide what each clone should become Phase 4: Convert one clone Moving a worktree Recovering a deleted .git worktree file When should a worktree be locked? When should git worktree prune be used? Final validation Quick reference Closing thoughts Have you ever ended up with a directory structure like this? ~/src/project ~/src2/project ~/src3/project ~/src4/project Each directory started innocently enough. One was for main . Another was for a feature branch. A third contained a half-finished experiment. The fourth had several untracked test files you were afraid to lose. Eventually, each clone had its own: stale view of the remote repository, duplicated Git history, local-only commits, modified files, ignored test artifacts, and unknown relationship to the others. Git worktrees are designed to solve this problem. A worktree gives you multiple checked-out working directories backed by one shared Git repository. Each working directory can have its own branch and uncommitted changes, while commits, branches, tags, remotes, and fetched objects remain shared. This article covers two things: How to use Git worktrees during normal development. How to safely consolidate several independent clones into one worktree-based layout without losing local work. The shell examples are written to work in both Bash and zsh . What is a Git worktree? A normal Git clone contains: the object database, commit history, branches, tags, remotes, remote-tracking references, and one checked-out working directory. A linked worktree adds another checked-out working directory to that same repository. For example: ~/src/project main ~/src/project-FEATURE-123 FEATURE-123 ~/src/project-HOTFIX-456 HOTFIX-45
开源项目
🛠️ How to Run a Privacy-First, Browser-Based Stream Downloader (FlowPick) — A Hands-On Tutorial
Hey folks 👋 If you've ever wanted to save a video lecture, a livestream replay, or a podcast episode for offline listening, you've probably run into the usual options: sketchy "online video parser" websites that ask you to paste your link into their server, or desktop apps that want you to sign up and upload stuff. Neither feels great when the whole point is your content. I went looking for something better and ended up working with FlowPick — an open-source, privacy-first media downloader that runs entirely in your browser. No uploads, no accounts, no telemetry. Everything (sniffing, downloading, merging, transcoding) happens client-side with FFmpeg compiled to WebAssembly. In this tutorial we'll: Clone and run FlowPick locally Download our first HLS ( .m3u8 ) and DASH ( .mpd ) stream Build and deploy it Poke at the internals so we can customize it If you just want to try it without installing anything, there's a hosted version at https://flowpick.net (more below). The full source is on GitHub: https://github.com/ezwebtools/flowpick . 🔗 Repo: https://github.com/ezwebtools/flowpick · Live tools: https://flowpick.net A 30-second primer: what are HLS and DASH? Before we touch code, two words you'll see everywhere in this space: HLS (HTTP Live Streaming) uses a .m3u8 manifest that lists small .ts (or fMP4) segments. Common for live streams and a lot of video platforms. DASH (Dynamic Adaptive Streaming over HTTP) uses a .mpd manifest; video and audio usually travel as separate .m4s tracks. YouTube and Bilibili lean on this. The key idea: the "video" isn't one file. It's a playlist pointing at dozens (sometimes hundreds) of tiny segments. A downloader's job is to fetch all the segments, decrypt them if needed, and stitch them back into one playable file. That's exactly what FlowPick does — in the browser. What FlowPick is, in one paragraph FlowPick is a Nuxt 4 app that ships in two shapes: A browser extension that sniffs media from the current tab's network requests. An
AI 资讯
AVIF vs WebP vs JPEG: Real Benchmarks (2026)
I compressed 100 photos through 3 formats. Here's the actual data. A 2MB JPEG photo. Convert it to WebP — now it's 480KB. Convert it to AVIF — now it's 310KB. Same visual quality. Three different file sizes. I've spent the last 2 weeks building an image compression tool, so I've seen thousands of these comparisons. Here's what the numbers actually say, and what it means for your website. The Setup I took 50 real-world photos and 50 screenshots/design assets — not synthetic test images, but actual files people would upload: Photos : vacation shots (JPEG, 2-8MB), product photos, portrait selfies Graphics : PNG screenshots (1-4MB), logos, UI mockups, illustrations Source sizes : 500KB to 12MB, average ~3.2MB Each image was compressed through JPEG (quality 85%), WebP (quality 80%), and AVIF (quality 65%) — settings that produce visually identical results on a 2x retina display. The Numbers Format Avg Compressed Size Reduction vs Original Reduction vs JPEG Browser Support Original 3.2 MB — — 100% JPEG (q85) 820 KB 74.4% — 100% WebP (q80) 480 KB 85.0% 41.5% smaller than JPEG 96.8% AVIF (q65) 310 KB 90.3% 62.2% smaller than JPEG 93.1% The headline : WebP halves your JPEG size. AVIF halves WebP again. Photo Results (JPEG source, 50 images) For photographs — the most common use case — here's what happened: Format Avg Size Best Case Worst Case JPEG q85 820 KB 180 KB 3.1 MB WebP q80 480 KB 95 KB 1.8 MB AVIF q65 310 KB 60 KB 1.2 MB What this means : On an average product page with 6 photos: JPEG: 6 × 820KB = 4.9 MB WebP: 6 × 480KB = 2.9 MB (saves 2 MB) AVIF: 6 × 310KB = 1.9 MB (saves 3 MB) On a 4G connection (10 Mbps), that's the difference between 4 seconds and 1.5 seconds to load all images. On a product page, that's the difference between a bounce and a sale. Screenshot/Graphics Results (PNG source, 50 images) PNGs are a different story. Lossy WebP and AVIF can crush PNGs — but only if you're OK losing pixel-perfect accuracy. Format Avg Size Notes Original PNG 1.4 MB Lossles
AI 资讯
Serverless ML Deployment: From Jupyter Notebook to Global API in 10 Minutes (No MLOps Expert Needed!)
Tired of deployments eating up your day? Stop wasting hours. I'm going to show you how to take your Python ML model from a Jupyter notebook to a live, production-ready API in just 10 minutes. Seriously. No MLOps guru required! You've felt that high, right? Building an awesome machine learning model. You nail it. Then… deployment. You hit a wall. How do you get this thing out there so people (or other apps) can actually use it? The leap from your notebook to a real-world, working API can feel like hacking your way through a jungle. Infrastructure setup. Dependency messes. Scaling nightmares. It's a pain. But what if you didn't need weeks, or even days, for that? What if you could close that gap in a mere 10 minutes? Welcome to Serverless ML Deployment . It's fast. It scales. It's simple. The MLOps Maze & Your Escape Route Traditional ML deployment looks like this: Provisioning servers: Picking machines, OS, setting up networks. Dependency management: Making sure every library is just right, versioned correctly. API development: Writing the actual server code, handling requests. Containerization: Wrapping it all in Docker (and Docker itself isn't trivial). Orchestration: Managing containers, scaling them up or down. Load balancing. Monitoring & Maintenance: Watching performance, patching, updates. That's a lot. Every step is another chance for things to go wrong, another delay. This is exactly where serverless technology swoops in. It wipes away almost all that underlying infrastructure. You get to focus on your model. Your predictions. That's it. Why Serverless is Your ML Deployment Secret Weapon When you use serverless for ML deployment, you get some killer advantages: Crazy Fast Deployment: Pre-configured setups mean you're live in minutes. Not hours. Not days. Scales Like Magic (Mostly!): Traffic spikes? No problem. Serverless automatically grows your API to handle it. No requests? Zero cost. It just works. Save Big Bucks: You only pay when your API is actually ru
AI 资讯
Your ML Model Died in Production. Here's Why.
Did your ML model look amazing in your notebook but tank in the real world? Good. Let's talk about the nasty surprises that trip up model deployments and why that "Train & Forget" approach is bleeding companies dry. It's a story we hear too often. You've spent weeks, maybe months, building some fancy machine learning model. The numbers were off the charts in your Jupyter notebook, validation? Nailed it. You even impressed the suits in the demo. "Eureka!" you thought. "We've built a game-changer!" You felt like a genius. A goddamn genius. Then comes deployment. Your model goes live, supposed to conquer the real world – predicting churn, optimizing logistics, detecting fraud. But instead of delivering... anything? It chokes. It starts to suck. Predictions go wild. That promised ROI? Gone. Poof. What went wrong? You, my friend, might have fallen into the "Train & Forget" trap. This nasty habit in machine learning thinks deployment is the END. Spoiler: it's just the start. It assumes that once a model is trained and deployed, it'll just... work. Forever. Without any ongoing care. And in the messy, unpredictable real world, that assumption is a guaranteed disaster. Millions down the drain. Why You're Tempted to "Train & Forget" (And Why You Shouldn't) Why do so many organizations, despite good intentions, make this mistake? A few reasons: Initial Success Bias: Those great numbers in your sandbox? They make you cocky. Pressure to Deploy: Business urgency often wants it out yesterday. Who cares if it breaks tomorrow? Resource Constraints: Teams might lack the dedicated MLOps engineers or the tech to support ongoing model management. Misunderstanding ML as Software: Thinking ML is like regular software (deploy once, patch occasionally)? It's not. It breathes data. The reality? An ML model's journey starts after it's live. The real world is a messy, evolving place, and your model better be ready. Beyond Your Laptop: What Kills Your Model In Production The gap between develop
AI 资讯
🚀Backend Internals #5: Stop Installing Everything Globally—Understand Local vs Global npm Packages
One of the most confusing topics for beginners in Node.js isn't Express, APIs, or asynchronous programming—it's understanding where npm packages should be installed. When I started learning Node.js, I thought there were only two commands: npm install package-name and npm install -g package-name I knew they both installed packages, but I had no idea when to use which one . Eventually, I realized they solve two completely different problems. If you're learning Node.js, this article will save you from one of the most common beginner mistakes. First, What Does npm Actually Do? npm (Node Package Manager) is the package manager that comes with Node.js. It helps you: Install libraries Manage project dependencies Update packages Share your own packages Run project scripts Whenever you install a package, npm has to decide where to install it. That's where local and global installations come in. Local Installation (The Default) When you run: npm install express npm installs Express inside your current project . Your folder now looks something like this: my-project/ │ ├── node_modules/ ├── package.json ├── package-lock.json └── app.js It also adds Express to your package.json : { "dependencies" : { "express" : "^5.0.0" } } This means: Express belongs to this project. Anyone who clones your repository can simply run: npm install and npm installs everything automatically. That's exactly what you want for project dependencies. Why Local Installation Matters Imagine you're building an API. Your code contains: const express = require ( " express " ); Now imagine another developer clones your project. If Express was installed locally, they only need to run: npm install Everything works. If it wasn't, they'll see something like: Cannot find module 'express' because the dependency isn't part of the project. That's why libraries your application depends on should almost always be installed locally. Global Installation Now consider this command: npm install -g nodemon This installs node
AI 资讯
Como crear Roles de Usuarios RBAC Plano PHP MySQL
Guía crear Roles de Usuario usando RBAC Plano con PHP MySQL Agustin RamosJul 24, 2026PHP Stuffs El control de acceso basado en roles (RBAC) es utilizado en la mayoría de los sistemas para definir qué puede hacer cada usuario. En su versión más simple, conocida como RBAC plano, no es necesaria una tabla de permisos: cada usuario tiene un único rol, representado por un número, y ese número es el que determina qué se le permite hacer dentro del sistema. En esta guía es construido un módulo de RBAC plano completo, con base de datos, conexión, lógica de validación y ejemplos de uso, usando solo PHP y MySQL. Si necesitas repasar los fundamentos antes de continuar, puedes consultar nuestra guía de PHP y MySQL. Qué es el RBAC plano En este modelo, cada rol es representado por un ID numérico. La regla que se sigue en esta guía es simple: entre más bajo el número, mayor es el nivel de acceso. 1 = admin (mayor nivel de acceso) 2 = subadmin 3 = encargado 4 = empleado (menor nivel de acceso) Con esta lógica, validar “solo administradores o superiores” se reduce a una simple comparación: role_id <= 2. Base de datos Son necesarias únicamente dos tablas: rol y user. La columna role_id, dentro de user, es la que define el nivel de acceso de cada persona. Todo este bloque está guardado en el archivo schema.sql. Cómo ejecutarlo: copia todo el bloque de código y pégalo directamente en tu consola de MySQL (o en phpMyAdmin / MySQL Workbench). Esto crea la base de datos rbac_plano, sus tablas y los datos de ejemplo automáticamente. -- schema.sql CREATE DATABASE rbac_plano; USE rbac_plano; -- Tabla rol. -- El ID es usado como nivel: entre más bajo, más privilegios. CREATE TABLE rol ( id TINYINT UNSIGNED PRIMARY KEY, name VARCHAR(50) NOT NULL UNIQUE ); -- Se insertan los 4 roles base del sistema. INSERT INTO rol (id, name) VALUES (1, 'admin'), (2, 'subadmin'), (3, 'encargado'), (4, 'empleado'); -- Tabla user. -- Cada usuario tiene un único role_id (no hay tabla de permisos). CREATE TABLE us
AI 资讯
How We Built Precise Translation and Language Identification for AI Book Translation
How we tackled 精准翻译与语言识别 (precise translation and language identification) for AI-powered book translation. The Problem: Garbage In, Garbage Out When we first launched LectuLibre, our AI book translation service, we thought the hardest part would be fine-tuning LLM prompts for literary quality. But we quickly discovered a more fundamental hurdle: if the source language of an uploaded book is misidentified, no amount of prompt engineering can salvage the translation. Users upload EPUBs and PDFs from all over the world. Some contain metadata specifying the language, but many don't. Others are multilingual books, or have prefaces in a different language. Our initial language detection using Python's langdetect library was correct only about 85% of the time on real-world uploads. That 15% error rate meant entirely garbled translations, frustrated users, and wasted LLM API credits. We needed something far more robust—what we internally call 精准翻译与语言识别 (precise translation and language identification). Here’s how we built it. The Language Detection Pipeline: From 85% to 98% Accuracy Our first instinct was to try heavier models like fastText's pre-trained language identification model, which is known for high accuracy. But when we tested it on book excerpts, we hit a new problem: short paragraphs or dialogues in one language embedded in a book of another language (e.g., French phrases in an English novel) would throw off chunk-level detection. We realized that we needed a two-tier approach: book-level language detection with confidence scoring, and per-chunk verification before translation. Combining Multiple Detectors with Voting We created a LanguageDetector class that runs several detectors and picks the majority vote, with a fallback to user-specified language when available. The detectors we use are: fastText with the official lid.176.bin model (loaded once, not per request) langdetect , which is lightweight and good for long texts cld3 (Compact Language Detector 3) fr
AI 资讯
How to Check SPF, DKIM, and DMARC Records in Python
If your app sends email — transactional or marketing — three DNS records decide whether it lands in the inbox or the spam folder: SPF , DKIM , and DMARC . Here's how to look them up and sanity-check them in Python, no third-party API required. Install the one dependency: pip install dnspython SPF: who is allowed to send SPF lives in a TXT record on the domain itself and starts with v=spf1 . import dns.resolver def get_spf ( domain ): for rec in dns . resolver . resolve ( domain , " TXT " ): txt = b "" . join ( rec . strings ). decode () if txt . startswith ( " v=spf1 " ): return txt return None print ( get_spf ( " github.com " )) # v=spf1 ip4:... include:_spf.google.com ~all A quick gotcha worth checking: SPF allows at most 10 DNS-querying mechanisms ( include , a , mx , ptr , exists , redirect ). Go over and receivers return permerror , which quietly breaks authentication: def spf_lookup_count ( spf ): return sum ( spf . count ( m ) for m in ( " include: " , " a: " , " mx: " , " ptr " , " exists: " , " redirect= " )) spf = get_spf ( " example.com " ) if spf and spf_lookup_count ( spf ) > 10 : print ( " ⚠️ SPF exceeds the 10-lookup limit " ) DMARC: the policy that ties it together DMARC is a TXT record on the _dmarc. subdomain and starts with v=DMARC1 . def get_dmarc ( domain ): try : for rec in dns . resolver . resolve ( f " _dmarc. { domain } " , " TXT " ): txt = b "" . join ( rec . strings ). decode () if txt . startswith ( " v=DMARC1 " ): return dict ( kv . strip (). split ( " = " , 1 ) for kv in txt . split ( " ; " ) if " = " in kv ) except dns . resolver . NXDOMAIN : return None print ( get_dmarc ( " github.com " )) # {'v': 'DMARC1', 'p': 'reject', 'rua': 'mailto:...'} The key field is p : none (monitor only), quarantine (spam folder), or reject (bounce). If a domain sends real mail but has p=none , it's not protected against spoofing yet. DKIM: the signature key DKIM is trickier because you need the selector — a label chosen by the sender that lives at SELECT
开发者
Rotating Residential Proxies in Python: requests, Scrapy & Sticky Sessions
When you scrape at any real volume, the bottleneck is rarely your code — it's the target site's rate limiting and IP bans. Rotating residential proxies solve this by routing each request through a different real-user IP. Here's how to wire them into requests and Scrapy in Python, including the sticky-session trick most tutorials skip. The proxy URL format A residential proxy is just an authenticated HTTP/SOCKS endpoint. With a pool gateway, you target a country and control session behavior through the username , not separate endpoints: http://USERNAME_country-us_session-a1b2c3_lifetime-30:PASSWORD@proxy.gproxy.net:1000 country-us — exit country (ISO code) session-a1b2c3 — a sticky-session id; reuse it to keep the same IP , change it to rotate lifetime-30 — how many minutes that session's IP stays fixed Basic request through a rotating proxy import requests USER = " USERNAME " PWD = " PASSWORD " def proxy ( country = " us " , session = None , lifetime = 30 ): tag = f " _country- { country } " if session : tag += f " _session- { session } _lifetime- { lifetime } " url = f " http:// { USER }{ tag } : { PWD } @proxy.gproxy.net:1000 " return { " http " : url , " https " : url } # New IP on every call (no session id): r = requests . get ( " https://api.ipify.org?format=json " , proxies = proxy (), timeout = 30 ) print ( r . json ()[ " ip " ]) Run it in a loop and you'll see a different IP each time — the gateway rotates automatically when no session id is present. Sticky sessions: keep one IP across requests Some flows (login, multi-step checkouts, paginated results behind a cookie) break if your IP changes mid-session. Pin the IP by passing a stable session id: import uuid sess = uuid . uuid4 (). hex [: 8 ] # one id for the whole flow p = proxy ( country = " de " , session = sess , lifetime = 30 ) s = requests . Session () s . proxies . update ( p ) s . get ( " https://example.com/login " ) s . post ( " https://example.com/login " , data = {...}) # same exit IP When you
AI 资讯
How to Evaluate MCP Servers Before Installing Them (A Practical Checklist)
The MCP (Model Context Protocol) ecosystem is growing fast. There are now hundreds of MCP servers available — but how do you know which ones are worth installing? After building and evaluating 60+ MCP servers ourselves, we developed a practical checklist that saved us from shipping broken tools. Here's the framework we use. The Problem Most MCP server listings tell you what the server does. Very few tell you how well it does it. You install something that sounds perfect, then discover: It activates on the wrong prompts (false positives) It pulls irrelevant context (retrieval drift) It sounds confident but gives wrong answers (ungrounded reasoning) It never improves from feedback Sound familiar? The 5-Dimension Evaluation Checklist Before installing any MCP server, ask these questions: 1. Trigger Precision Question: Does this server activate when (and only when) it should? Red flags: Overly broad trigger descriptions ("use for anything related to X") No documented activation conditions Activates on common words that appear in unrelated contexts Green flags: Specific, documented trigger scenarios Clear non-activation cases listed Tested against diverse prompts 2. Retrieval Quality Question: Does it pull the right context for the task? Red flags: Returns large chunks without filtering No citation or source tracking Retrieves plausible but outdated information Green flags: Targeted, minimal context retrieval Source attribution for every piece of context Version-aware (knows when data might be stale) 3. Reasoning Grounding Question: Are its conclusions tied to actual data? Red flags: Generates advice without referencing specific inputs Can't explain its reasoning chain Confident answers that contradict its own retrieved context Green flags: Every conclusion references specific evidence Explicitly flags uncertainty Gracefully handles missing information 4. Output Usefulness Question: Does the output actually solve your problem? Red flags: Generic responses that could appl