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

标签:#tutorial

找到 371 篇相关文章

AI 资讯

Inbox Zero for Devs: How I Built a JavaScript Script to Destroy Gmail Spam

Hey dev community! 👋 As developers, our inboxes often turn into a graveyard of job alerts (LinkedIn, Indeed, ZipRecruiter) and tech newsletters we subscribe to with the intention of "reading later" but never actually open. The result? Important emails get lost, and we get the dreaded "Account storage is almost full" notification. Recently, I hit that wall. I had thousands of accumulated emails. While Gmail allows you to create filters for incoming mail, it doesn't have a native feature to say: "Delete this email automatically after 7 days" . So, I decided to solve it the way we solve everything: by writing some code. 🛠️ The Solution: Google Apps Script + JavaScript Since the Google Workspace ecosystem runs on a JavaScript-based environment, I put together a custom script. Fun fact: a simple loop originally failed due to Google's strict 6-minute execution limit. To fix this, I optimized the code to process emails in batches of 100 , preventing the server from timing out. Here is the final production-ready script: function cleanSpamTsunami() { // 1. Loop to delete ALL Job Board emails in batches of 100 var continueJobSearch = true; while (continueJobSearch) { var jobThreads = GmailApp.search('computrabajo OR indeed OR linkedin OR OCC OR neuvoo OR talent.com OR jooble', 0, 100); if (jobThreads.length > 0) { Logger.log('Deleting a batch of ' + jobThreads.length + ' job alert emails...'); GmailApp.moveThreadsToTrash(jobThreads); } else { Logger.log('No more job alerts found!'); continueJobSearch = false; // Break the loop } } // 2. Loop to delete old Newsletters (older than 7 days) in batches of 100 var continueNewsletters = true; while (continueNewsletters) { var newsletterThreads = GmailApp.search('unsubscribe OR "cancelar suscripción" older_than:7d', 0, 100); if (newsletterThreads.length > 0) { Logger.log('Deleting a batch of ' + newsletterThreads.length + ' old newsletters...'); GmailApp.moveThreadsToTrash(newsletterThreads); } else { Logger.log('No more old newslett

2026-06-25 原文 →
AI 资讯

The Missing Manual: 160+ free Dev guides on debugging, Programming, infrastructure, AI and more

There's a specific kind of bad documentation that I think we've all suffered through. You search for "what is a goroutine" or "how do database transactions work" and you get one of two things: either a six-page academic paper that assumes you already know the answer, or a tutorial so watered-down it covers nothing real. What you actually want is someone like that senior engineer at your company the one who, when you finally work up the nerve to ask a dumb question, sits down and actually explains the thing. Not just the what, but the why. Not just the happy path, but the part where you'll get confused at 2am and what to do about it. I've been building that resource. It's called The Missing Manual. Here's the pitch in one sentence: it's a free, growing library of developer guides written like advice from a battle-hardened friend who genuinely wants you to understand the thing, not just copy the code. Some examples of what's in there right now: Reading a Stack Trace at 2am — starts with "that wall of text is not an attack, it's a map," then teaches you the four-step method that works in Python, JavaScript, Java, or whatever you're using. Includes the site-packages/ vs your-own-code trick that turns 40-line traces into 2-line ones. Go From Zero - covers the basics, but also the deep stuff that most Go tutorials skip: what the GMP scheduler actually does, how escape analysis decides what lives on the heap, why goroutines are cheap in a way OS threads aren't. Mental-model-first, the whole way through. Docker Without the Magic - doesn't just show you docker run. Explains what a namespace and a cgroup actually are, so when Docker does something weird, you have somewhere to start. Why Is My Query Slow? - the real answer, including EXPLAIN, index cardinality, the N+1 problem, and what "using index" in a query plan actually means vs what you want it to mean. There are 160+ guides across debugging, databases, infrastructure, networking, APIs, AI/ML, performance, and programmin

2026-06-25 原文 →
AI 资讯

Legacy code não envelhece como vinho: quanto mais espera, pior fica

Semana passada eu passei três horas debugando um bug que deveria levar 20 minutos. O problema? Um módulo de validação escrito em 2019 que ninguém mexe "porque funciona". Spoiler: não funcionava mais, e quando finalmente abri o arquivo, encontrei um // TODO: refactor this datado de 2020. Por que legacy vira bola de neve A indústria trata código legado como se fosse dívida técnica opcional — algo que você paga "quando tiver tempo". Mas código legado se comporta mais como mofo: se espalha, contamina áreas adjacentes, e quanto mais você ignora, mais cara fica a limpeza. O ciclo é previsível: você herda um projeto ou feature antiga, vê que está "meio bagunçado mas roda", adiciona sua feature com um if a mais, e segue em frente. Seis meses depois, outra pessoa faz o mesmo. Um ano depois, aquele arquivo tem 800 linhas, cinco níveis de if aninhados, e zero testes. Ninguém mais entende o fluxo completo, então cada mudança vira uma sessão de especulação: "se eu mexer aqui, quebra ali?" O custo real de esperar Esse código "que funciona" tem um custo oculto que aparece em três formas: Velocidade de desenvolvimento despenca. Features que deveriam levar dois dias levam uma semana porque você passa mais tempo entendendo o contexto do que escrevendo código novo. Bugs aumentam exponencialmente. Código sem testes e com lógica embolada é um gerador de regressões. Você corrige um edge case e quebra outro que nem sabia que existava. Onboarding vira tortura. Novo dev no time? Boa sorte explicando por que aquele service tem três formas diferentes de fazer autenticação, ou por que a mesma validação está copiada em sete lugares. Sinais de que você está sentado em cima de uma bomba Nem todo código antigo é legacy tóxico. Aqui estão os red flags que indicam que você precisa agir agora: // Red flag #1: comentários mentirosos ou inúteis function processPayment ( order ) { // Process the payment const user = order . user ; // TODO: fix this later // HACK: don't touch this, breaks prod if ( user

2026-06-24 原文 →
AI 资讯

How to Fetch Real-Time Options Chain Data in Python (Without Paying $99/mo)

If you've ever tried to pull live options data into a Python script, you've probably hit the same wall I did: the cheapest real-time providers start at $99/mo. Here's how to do it for $20/mo — or free if you stay within 1,000 credits/day. What You'll Need Python 3.8+ requests library ( pip install requests ) An API key from market-option.com (free tier available, no card required) Fetching a Full Options Chain import os import requests API_KEY = os . environ [ " MARKET_OPTIONS_KEY " ] BASE_URL = " https://market-option.com/api/v1 " def get_chain ( ticker : str ) -> list [ dict ]: res = requests . get ( f " { BASE_URL } /options/chain/ { ticker } " , params = { " apiKey " : API_KEY }, ) res . raise_for_status () return res . json ()[ " results " ] contracts = get_chain ( " SPY " ) print ( f " { len ( contracts ) } contracts returned " ) print ( contracts [ 0 ]) Each contract in results looks like this: { "details" : { "contract_type" : "call" , "strike_price" : 530 , "expiration_date" : "2026-01-17" , "ticker" : "O:SPY260117C00530000" }, "last_quote" : { "bid" : 3.45 , "ask" : 3.50 , "midpoint" : 3.475 }, "greeks" : { "delta" : 0.42 , "gamma" : 0.031 , "theta" : -0.18 , "vega" : 0.29 }, "implied_volatility" : 0.182 , "open_interest" : 12418 } Filtering by Expiration and Strike def get_near_the_money ( ticker : str , expiration : str , spot : float , width : float = 0.05 ): """ Return contracts within ±width% of spot price. """ contracts = get_chain ( ticker ) low = spot * ( 1 - width ) high = spot * ( 1 + width ) return [ c for c in contracts if c [ " details " ][ " expiration_date " ] == expiration and low <= c [ " details " ][ " strike_price " ] <= high ] atm = get_near_the_money ( " SPY " , " 2026-01-17 " , spot = 530 ) for c in atm : print ( c [ " details " ][ " strike_price " ], c [ " details " ][ " contract_type " ], c [ " last_quote " ][ " bid " ], c [ " greeks " ][ " delta " ], ) Scanning for High IV Contracts def high_iv_scan ( ticker : str , iv_threshold :

2026-06-24 原文 →
AI 资讯

Git com múltiplas contas: configure trabalho e pessoal no mesmo computador

Você já fez um commit no repositório do trabalho e percebeu que estava com o seu e-mail pessoal? Ou o contrário? Esse é um dos erros mais comuns de quem usa Git com múltiplas contas no mesmo computador. Neste tutorial você vai aprender a configurar tudo corretamente, de uma vez, usando chaves SSH separadas e .gitconfig condicional — sem gambiarras. O problema Por padrão o Git usa uma configuração global: git config --global user.name "Seu Nome" git config --global user.email "seu@email.com" Isso significa que todos os repositórios no seu computador usam o mesmo usuário. Quando você tem contas separadas (ex: joao@empresa.com no GitLab da empresa e joao@gmail.com no GitLab pessoal), os commits vão sair com o e-mail errado. A solução profissional envolve duas partes: Chaves SSH separadas para cada conta .gitconfig condicional que aplica o usuário certo — e a chave SSH certa — por pasta Passo 1 — Gerar as chaves SSH Abra o terminal e gere uma chave para cada conta. Use nomes diferentes para não sobrescrever: # Chave para a conta pessoal ssh-keygen -t ed25519 -C "joao@gmail.com" -f ~/.ssh/id_ed25519_pessoal # Chave para a conta do trabalho ssh-keygen -t ed25519 -C "joao@empresa.com" -f ~/.ssh/id_ed25519_trabalho 💡 Por que ed25519 ? É o algoritmo mais moderno, mais seguro e recomendado pelo GitHub, GitLab e Bitbucket. Evite RSA a menos que seu servidor seja muito antigo. Ao final você terá quatro arquivos em ~/.ssh/ : id_ed25519_pessoal ← chave privada (nunca compartilhe) id_ed25519_pessoal.pub ← chave pública (você registra no GitLab) id_ed25519_trabalho id_ed25519_trabalho.pub Passo 2 — Registrar as chaves no GitLab Para cada conta: Copie o conteúdo da chave pública: # Pessoal cat ~/.ssh/id_ed25519_pessoal.pub # Trabalho cat ~/.ssh/id_ed25519_trabalho.pub Acesse Settings → SSH and GPG keys → New SSH key na conta correspondente e cole o conteúdo. Faça isso nas duas contas , cada uma com a sua respectiva chave pública. Passo 3 — Configurar o Git por pasta (o pulo do gato)

2026-06-24 原文 →
AI 资讯

Why I Stopped Picking AI Models by Hype and Started Picking by Speed

Why I Stopped Picking AI Models by Hype and Started Picking by Speed Three months ago I almost lost a $14,000 retainer because my chatbot felt sluggish. The client didn't say "your TTFT is too high." They said "it feels dumb." That's freelancer code for "users are bouncing and I'm about to find someone else." I rebuilt that bot in a weekend using a model I'd never even heard of six weeks earlier, dropped average response time from 1.4 seconds to under 300ms, and the client renewed for another six months. That single pivot paid for my rent. So I went down a rabbit hole. I ran the same speed test on every model I could get my hands on through Global API's unified endpoint. Fifteen models. Same prompt. Same regions. Ten iterations each. I'm writing this up because if you're billing by the hour or running a side hustle on a shoestring, speed isn't a vanity metric — it's a profit metric. Let me show you what I found. The Setup (How I Actually Ran the Tests) I'm not a researcher with a rack of GPUs. I'm a guy with a M2 MacBook, a $19/mo Hetzner box, and a stopwatch in the form of Python's time.perf_counter() . Here's how I kept it honest. Date window: All tests run on May 20, 2026 Regions tested: US East (Ohio) and Asia (Singapore) Prompt used: "Explain recursion in 200 words" — boring on purpose, because boring prompts are where most apps actually live Output length: Roughly 150 tokens per run Iterations: 10 runs per model per region, average recorded Streaming: Yes, SSE throughout Endpoint: Global API at https://global-apis.com/v1 I measured two things: TTFT (time to first token — the lag before the user sees anything move) and sustained tokens per second (how fast the words actually arrive after that). Both matter. TTFT is the "is this thing broken?" feeling. Tokens per second is the "is this thing fast?" feeling. Here's the script I used, stripped down to the essentials: import time import requests from statistics import mean API_KEY = " your-global-api-key " BASE_URL

2026-06-24 原文 →
AI 资讯

How to Use Chinese LLMs (Qwen, DeepSeek, GLM) Without a Chinese Phone Number

How to Use Chinese LLMs Without a Chinese Phone Number If you've tried signing up for any Chinese AI service, you've seen the same message: Please enter your phone number (+86) to receive a verification code. This single requirement blocks most overseas developers from accessing some of the best-performing and most cost-effective LLMs on the market. This guide covers every workaround I've found — from least to most practical. The Problem China's major AI labs produce world-class models: DeepSeek — DeepSeek V4-Pro matches GPT-4o within 3-5% on coding benchmarks Qwen (Alibaba) — Qwen 3.7-Max beats GPT-4o on long-context tasks (256K tokens) GLM (ZhipuAI) — GLM-4.5 is competitive with Claude for reasoning tasks Baichuan — Strong for Chinese-language generation But every single one requires: A +86 Chinese phone number for registration Alipay or WeChat Pay for billing Chinese-language documentation Method 1: Virtual Chinese Phone Numbers (Fragile) Services like SMS-activate and 5sim offer temporary Chinese phone numbers for ~$1-2. The problem: Chinese providers have gotten aggressive about flagging virtual numbers. Your account gets banned within days. You lose any balance you've added. ❌ Not recommended — too unreliable for production use. Method 2: Third-Party Gateway Services (Recommended) The most practical solution is a gateway that handles the China-side complexity for you. These services: Maintain their own Chinese accounts and infrastructure Register with real Chinese business entities Handle Alipay/WeChat billing on their end Expose everything through a standard OpenAI-compatible API What this means for you: Sign up with email (no phone number needed) Pay via Stripe or PayPal Get a standard API key Use the OpenAI Python/Node.js SDK as-is Migration example (Python): # Before — can't access Chinese models at all # client = OpenAI(api_key="...") # Only works for OpenAI # After — full access to Chinese models client = OpenAI ( base_url = " https://api.tokenmaster.com

2026-06-24 原文 →
AI 资讯

How to Access DeepSeek API from Outside China (2026 Guide)

How to Access DeepSeek API from Outside China (2026 Guide) DeepSeek has quietly become one of the best open-weight LLM families available. Their V4-Pro model matches GPT-4o within 3-5% on coding benchmarks (HumanEval, MBPP) while costing roughly 90% less per token. The problem? Actually getting access as an overseas developer. The Registration Wall If you try to sign up for DeepSeek's official API directly, you'll hit this: ✕ +86 phone number required for SMS verification ✕ Alipay or WeChat Pay only — no Stripe, no PayPal ✕ Documentation is primarily in Chinese ✕ VPN required and it drops mid-request ✕ Different auth system than OpenAI This isn't a minor inconvenience — it's a hard blocker for most overseas developers. I spent a full weekend trying to work around it before finding a solution that actually worked for production use. Option 1: DIY Proxy (Not Recommended) You could technically set up a Chinese VPS as a relay, register through a Chinese friend's number, and proxy requests. I tried this approach. Problems: Your Chinese VPS adds 100-300ms latency You're responsible for keeping the integration working If your Chinese friend's number gets flagged, you're locked out No SLA, no support, no monitoring Payment still requires Alipay — you need a Chinese bank account or a friend After a weekend of futzing with this, I abandoned it. Not production-ready. Option 2: Third-Party Gateway (What I Use) There are now services that handle the China-side complexity and expose DeepSeek through a standard OpenAI-compatible API. They handle: Chinese phone number verification Alipay/WeChat payment (you pay via Stripe instead) API routing with global edge caching Load balancing across multiple Chinese providers Setup is literally two lines: # Before: Direct OpenAI client = OpenAI ( base_url = " https://api.openai.com/v1 " , api_key = OPENAI_KEY ) # After: Via gateway client = OpenAI ( base_url = " https://api.tokenmaster.com/v1 " , api_key = TM_KEY ) That's it. Same SDK, same i

2026-06-24 原文 →
AI 资讯

Exploring Polymarket's 1-Hour Markets: Data Analysis, Mispricing Opportunities, and Automated Trading Strategies

Prediction markets have become increasingly popular among traders looking for alternative ways to speculate on asset movements. While much of the attention has been focused on short-term 5-minute and 15-minute markets, I believe one of the most overlooked opportunities right now is the 1-hour market on Polymarket. In this article, I'll share some of my ongoing research, explain how I'm collecting and analyzing market data, discuss potential arbitrage and mispricing opportunities, and show how automation can help traders capitalize on these inefficiencies. Why I'm Focusing on the 1-Hour Market Many traders are currently concentrated on the 15-minute Bitcoin prediction markets. While these markets can be profitable, competition has increased significantly, and recent fee changes have made certain strategies less attractive. The 1-hour markets, however, present a different opportunity. These markets offer: Longer trading windows More time to manage positions Higher flexibility for order placement Potentially lower competition No trading fees on some hourly markets Because of the longer duration, traders have more time to identify inefficiencies and execute strategies that may be difficult to implement in shorter timeframes. Collecting Market Data Directly from Polymarket One of the projects I've been working on involves collecting market data directly from Polymarket and monitoring token price movements in real time. Rather than relying solely on the displayed market prices, I use blockchain-based data sources that can provide updates faster than the front-end interface. This allows me to analyze: YES token price swings NO token price swings Order book movements Temporary mispricings Combined token costs The goal is to understand how both sides of a market move throughout the trading period and identify situations where the combined cost of YES and NO tokens falls below $1. Understanding YES and NO Token Swings One interesting metric I track is the lowest price reached

2026-06-24 原文 →
AI 资讯

Playwright versus WordPress's "admin email confirmation" screen — how automation can clear the 6-month gate

If you drive the WordPress admin via Playwright for long enough, one day a screen you've never seen before will appear after login , and everything downstream stops working. Is admin@example.com still the correct admin email address? [ Yes, the email is correct ] [ Change the address ] That's WordPress's admin email confirmation screen . Roughly every six months, after the admin user logs in, this confirmation screen gets injected — standard behavior since WP 4.9. A human just clicks once. An automation script can't see it without explicit handling. Why automation gets stuck A straightforward Playwright login looks like: page . fill ( ' #user_login ' , user ) page . fill ( ' #user_pass ' , pwd ) page . click ( ' input[type= " submit " ] ' ) page . wait_for_load_state ( ' domcontentloaded ' ) # Assumes we're on the dashboard page . goto ( ' /wp-admin/plugins.php ' ) But on a "confirmation day," the URL right after wait_for_load_state is something like /wp-admin/profile.php?...action=confirm_admin_email... — the confirmation screen. You thought you were navigating to the plugins page, but the DOM you expected isn't there. Subsequent selectors fail, and everything downstream cascades into failure. A specific selector identifies the screen WordPress's confirmation screen has a uniquely-named submit button: <input type= "submit" name= "correct-admin-email" value= "Yes, the email is correct" /> If input[name="correct-admin-email"] exists on the page, you're on the confirmation screen. The same selector serves as both the detection signal and the click target , so handling is only a few lines: admin_email_confirm = page . locator ( ' input[type= " submit " ][name= " correct-admin-email " ] ' ) if admin_email_confirm . count () > 0 : logger . info ( " Confirmation screen detected — clicking ' email is correct '" ) admin_email_confirm . first . click () page . wait_for_load_state ( ' domcontentloaded ' , timeout = 30000 ) Insert this after the post-login wait_for_load_state

2026-06-24 原文 →
AI 资讯

Fixing “Git Divergent Branches” on a Production Server (Real DevOps Debugging Walkthrough)

One of the most confusing errors you can face while deploying a Node.js or Docker-based application is: fatal: Need to specify how to reconcile divergent branches At first glance, it looks like a Git bug. In reality, it is Git doing exactly what it should do, protecting you from overwriting history. In this article, I’ll break down a real production incident where a deployment failed due to divergent Git branches, how we diagnosed it, and the correct DevOps fix. The Problem A simple deployment script was running: git pull docker compose down --remove-orphans docker compose up --build -d But it failed with: fatal: Need to specify how to reconcile divergent branches This stopped deployment completely. What Git Was Telling Us To understand the issue, we ran: git rev-list --left-right --count HEAD...origin/main Output: 1 16 This means: 1 commit exists locally on the server 16 commits exist on GitHub So the branches had diverged. Why This Happens (Important) This usually happens when: Someone runs git commit directly on a server A previous deployment used git pull with merge commits History between local and remote is no longer linear Git refuses to guess whether you want to: Merge Rebase Or reject changes So it throws an error. Deep Diagnosis We inspected the commits: git log --oneline origin/main..HEAD Result: 6d9046b Merge pull request #222 Then: git log --oneline HEAD..origin/main Showed multiple new GitHub PR merges. Conclusion: The server was behind GitHub The “local commit” was already part of repo history No real production changes existed on server The Real Fix (Production Safe) For deployment servers, you should NEVER rely on git pull . Instead, use a deterministic reset: git fetch origin git reset --hard origin/main Then redeploy: docker compose down --remove-orphans docker compose up --build -d Why This Works This approach ensures: Server always matches GitHub exactly No merge conflicts in production No accidental local commits survive Fully reproducible depl

2026-06-24 原文 →
AI 资讯

Styling the Vertical - Achieving Parity

Note : This article is one of a series demonstrating building a React navigational component from scratch while considering accessibility through the process. The articles are accompanied by a GitHub repository with releases tied to one or more articles; each builds on the previous one until a fully implemented navigation component is complete. Each release and its associated tag contain fully runnable code for the article. The code discussed in this article is available in the release. and may be downloaded at release 0.9.0 . A page showcasing these base components may be run locally through this release. While code examples are written in JavaScript for brevity, all actual code is written in Typescript and targets React 19.x, all while using vanilla CSS. Examples use Next.js v16.x, which is not required to run the navigation component.] The design requirements for this release are available . -— Content Links Introduction Layout Appearance <nav / > Generic Styling Reimagining Focus and Hover Achieving Parity aria-current Refinements Summary Introduction With only one more release coming up and the horizontal layout styling complete, now is the time to focus on completing vertical layout styling. Most of the layout itself was completed in an earlier release and described in the article Laying it all out on the vertical . When styling a component, care must be taken to ensure parity with the information provided by screen readers through some aria attributes. For instance, a navigation component must set the aria-current="page" attribute on a link whose href points to the current page. In the example being shown, the link in question is the "by Era" link, under Find Your Next Story and Tales. ) While screen reader users hear which button or link is the item currently capturing focus, styling is needed to achieve the same for screen users. Visual styling is necessary to guarantee that visual and auditory/tactile users have the same information. Layout @layer system-c

2026-06-23 原文 →
AI 资讯

How to Build a Tool that Track Which World Cup Players Are Blowing Up on Social Media

Every World Cup there's a moment. Some player nobody outside their domestic league had heard of scores an absolute screamer in a knockout match, and by the time they've finished celebrating, their follower count is climbing like a rocket. I always found that fascinating, but I could never see it happening in real time. By the time the "X gained 3 million followers!" tweets show up, the surge is already over. So this tournament I built a little tracker that snapshots player follower counts on a schedule and shows me the growth curve as it happens. Here's how it works. Why the official APIs were a dead end My first instinct was to do this "properly" with official APIs. That died fast: Instagram's Graph API won't give you follower counts for accounts you don't own. TikTok's research API is academics-only and takes weeks of applications. X's API now starts at $100/month. I just wanted public follower counts — numbers anyone can see by opening the app. I didn't want a data partnership and a legal review. I ended up using SociaVault , which wraps the public profile data from each platform behind one API and one key. One request, one credit, JSON back. The shared client Everything runs through one tiny helper: // Node 18+ has fetch built in const API_KEY = process . env . SOCIAVAULT_API_KEY ; const BASE = " https://api.sociavault.com " ; async function sv ( path , params ) { const url = new URL ( BASE + path ); Object . entries ( params ). forEach (([ k , v ]) => url . searchParams . set ( k , v )); const res = await fetch ( url , { headers : { " X-API-Key " : API_KEY } }); if ( ! res . ok ) throw new Error ( ` ${ res . status } ${ await res . text ()} ` ); return res . json (); } Grabbing follower counts across platforms Each platform nests the count slightly differently, so I use fallback chains to stay defensive: async function instagramFollowers ( username ) { const data = await sv ( " /v1/scrape/instagram/profile " , { username }); const p = data . data ?. user ?? dat

2026-06-23 原文 →
AI 资讯

Why Your Ubuntu Laptop Lags, and How to Fix It for Free

My main work laptop is a Dell from 2017 with 8 GB of RAM. For weeks it had been crawling, freezing for whole seconds while I worked, and every so often it would simply switch itself off in the middle of a task. If you have ever lost unsaved work to a laptop that powers down on its own, you know exactly how frustrating that is. So I sat down and fixed it properly. The first thing I learned is worth saying up front: a slow, crashing laptop is usually two different problems wearing the same costume . Treat them as one and you will chase your tail. Separate them, and both become fixable. Everything below is free and copy-paste ready. It was tested on Ubuntu 24.04 LTS, and it applies to almost any older Linux machine. The honest disclaimer: Nobody can promise an old laptop will never lag. Software cannot add cores or memory that are not physically there. But you can absolutely stop the freezes and shutdowns completely and make everyday work feel smooth. That is the realistic, achievable goal. 0. Diagnose first, do not guess The biggest mistake is blindly applying "speed up Ubuntu" tweaks before knowing what is actually wrong. Spend five minutes measuring. Your lag has one of four common causes: heat, memory, disk, or a dying battery . Check temperature (the usual cause of random shutdowns): sudo apt install lm-sensors -y sudo sensors-detect --auto sensors Watch the Core temperatures while you work. If they spike past 90 to 100 °C right before a crash, you have a thermal problem, not a software one. Check memory (the usual cause of freezing): free -h sudo apt install htop -y htop In htop , watch the Mem and Swp bars during normal use. If memory pins near your limit and swap fills up, that thrashing is your freeze. Check disk space (a quiet killer): df -h / A root partition above 90% full makes Linux lag and turn unstable. Small SSDs fill up fast. Read the crash logs and battery health: # What went wrong during the previous (crashed) session journalctl -b -1 -p err --no-pa

2026-06-23 原文 →
AI 资讯

Building a Cross-Border Price-Comparison Agent: A Live Build Log

Why a build log (and not another tutorial) Every AI shopping tutorial shows the same thing: install the SDK, call a tool, ship. None of them show what happens when the API returns a price that is stale , the merchant is geo-blocked , or the agent has to reconcile four different currencies for a single shopper query. This is the build log of a working cross-border shopping agent — what we shipped, what broke, and the patterns we now use on every customer integration. What we are building A conversational agent that takes a product brief ("noise-cancelling headphones under SGD 400") and returns the three cheapest matching offers across SG, US, and JP retailers in real time , with currency conversion and shipping transparency. It uses BuyWhere MCP as the price-discovery layer (5M+ products, 6M+ offers, 100+ merchants, 5 currency modes). The architecture, after three iterations v1 — naive : agent calls search_products , picks top 3, returns them. Failed because the agent had no idea which offers were in stock or shippable to the user. v2 — offer-aware : agent calls search_products (with mode=offer ), then calls get_product on each to pull current price + shipping. Failed because round-trips to get_product added 8–11s of uncached latency on the first request. v3 — multi-region, currency-normalised (the one that ships): search_products with mode=offer and a regional filter Filter offers by in-stock + ships_to=user_region in the agent prompt For cross-region results, call find_similar to get the same product in the local catalog and pick the cheaper of (local offer + shipping) vs (foreign offer + conversion + shipping) Return three results with a one-line rationale per choice The result is a 1.2–2.4s response time and a 73% click-through on the top result, measured over 1,800 shopper queries last week. Three patterns we use on every integration now 1. Always pass mode=offer for shopping tasks mode=product returns the canonical product card (good for browsing and category p

2026-06-23 原文 →
AI 资讯

When WP admin shows a plugin update but WP-CLI doesn't — making automation see proprietary updaters

You open the "Updates" page in WordPress admin and see that Elementor Pro / ACF Pro / vk-blocks-pro have updates available. Then you run wp plugin update --all from your automation, and those exact plugins don't update. The asymmetry — "the admin sees it; WP-CLI doesn't" — traces back to how WordPress detects updates and how premium plugins layer proprietary update mechanisms on top of that. Here's the mechanism and how an automation tool can adapt. WordPress update detection is held by a transient cache WordPress doesn't decide "is there an update?" on every request. It caches the answer in the wp_options table as a transient, valid for up to 12 hours. The key entries: _site_transient_update_plugins — latest plugin versions _site_transient_update_themes — themes _site_transient_update_core — core If those transients are stale, even a version that just shipped on wordpress.org reads as "no update needed." WP-CLI consults the same transients, so stale cache = WP-CLI misses the update too . In one customer environment on ConoHa WING, we reproduced "version X is on wordpress.org, WP-CLI doesn't see it" directly. Trap 1 and fix 1 — force-refresh the transients before listing updates The first step was simple: at the start of a maintenance run, delete the three transients before querying the update list . def _flush_update_transients ( self , conn , wp_cmd , wp_path , site_name ): """ Delete update transients between DB backup and update step """ for t in ( " update_plugins " , " update_themes " , " update_core " ): conn . run ( f " { wp_cmd } transient delete { t } --path= { wp_path } " , warn = True , hide = True , ) Deleting the transients triggers a rebuild on the next wp plugin list --update=available . During the rebuild, WordPress reaches out to wordpress.org, so the returned list reflects the current release state . That handled the "we were just reading a stale cache" cases. But it didn't help with premium plugins. Trap 2 — with --skip-plugins , Pro updater filt

2026-06-23 原文 →
AI 资讯

Query ধীর গতিতে চলছে, কিভাবে খুঁজে বের করবেন সমস্যাটা? (পর্ব ৩)

আমার colleague এখন প্ল্যান দেখতে পারছে। Scan types বুঝতে পারছে। Join types বুঝতে পারছে। Estimate আর actual এর gap দেখতে পারছে। BUFFERS ও দেখছে। কিন্তু সে প্রশ্ন করল। এসব দেখে কি করব? Step by step কোন পথে যাব? আমি বললাম। পাঁচটা step আছে। অর্ডার অনুযায়ী। পর্ব ২ এ আমি বলেছিলাম scan types, join types, estimate আর actual এর gap। BUFFERS কি। এবার আসি সমাধান এ। Diagnostic Workflow আপনার কাছে একটা slow query এসেছে। কিভাবে debug করবেন? এই পাঁচটা প্রশ্ন করুন অর্ডার অনুযায়ী। ৯০% slow query প্রথম বা দ্বিতীয় ধাপেই solve হয়ে যায়। ১. Deepest Seq Scan দেখুন Table বড় কি না? Filter selective কি না? Missing index থাকলে add করুন। আজই শুরু করুন যখন একটা Seq Scan দেখবেন big table এ, প্রথমে WHERE clause টা check করুন। Selective কি না? ৫% এর কম row return হওয়ার কথা? যদি তাই হয়, index missing। CREATE INDEX idx_name ON table(column) run করুন। ২. Join types দেখুন কোনো Nested Loop আছে কিন্তু দুই পাশেই বড় table? Hash Join force করুন বা ডান পাশে index add করুন। আজই শুরু করুন Nested Loop দেখলে ডান পাশের table এ index check করুন। যদি না থাকে, create করুন। Index থাকা সত্ত্বেও planner Nested Loop use করছে? SET enable_nestloop = off temporarily disable করে দেখুন। Hash Join আসবে কি না। ৩. Row estimates দেখুন Estimate vs actual ১০x এর বেশি difference? ANALYZE table দিন বা predicate rewrite করুন। আজই শুরু করুন rows=1 estimate কিন্তু rows=100000 actual দেখলে ANALYZE tablename run করুন। Statistics refresh হবে। তারপর plan আবার দেখুন। যদি তাও না আসে, WHERE clause rewrite করুন। Function call থাকলে remove করুন। Type mismatch থাকলে fix করুন। ৪. BUFFERS add করুন কোনো node এ অনেক disk reads? Caching investigate করুন। আজই শুরু করুন EXPLAIN (ANALYZE, BUFFERS) run করে দেখুন shared read high কোথায়। সেই node টাই bottleneck। Index add করলে reads কমবে। Pre-warm cache করতে পারেন। Data pre-load করতে পারেন। ৫. Sorts আর hashes দেখুন কোনো spill-to-disk আছে? work_mem raise করুন বা sort eliminate করুন। আজই শুরু করুন Plan এ external merge Disk: 421MB দেখলে spill-to-disk হয়েছে। SET work_mem = '256MB' temporarily rais

2026-06-22 原文 →
AI 资讯

Clean Architecture in .NET 8: A 2026 Starter Template with 4 Projects, EF Core, and JWT Auth

I joined a team where the controller was 800 lines long, the business rules were scattered between the controller and the DbContext , and "to run the tests, spin up a SQL Server in Docker" was a sentence I heard every week. The fix was Clean Architecture. The argument I had with the team lead was about how to actually structure it. We argued for two weeks. Then I built this template so the next person wouldn't have to. This is the Clean Architecture .NET 8 starter template I wish someone had handed me on day one. Four projects, strict dependency direction, domain entities that own their own invariants, and an Application layer you can unit test with Moq — no database required. The whole repo is on GitHub , MIT-licensed, runs with dotnet run , and ships with xUnit tests, JWT auth, Swagger, Docker, and CI. This post is the explanation of why each project exists, what goes in it, and what I learned the hard way about getting Clean Architecture right in .NET. The problem Clean Architecture solves The naive way to build a .NET Web API is one project, one folder structure, and "everything talks to everything": MyApp/ Controllers/ ProductsController.cs ← HTTP stuff OrdersController.cs ← HTTP stuff + business rules Services/ ProductService.cs ← business rules + DbContext.SaveChanges Data/ AppDbContext.cs ← EF Core, entities Models/ Product.cs ← POCO with public setters This works for the first 1,000 lines. By 5,000 lines, the controller is doing five things at once. By 10,000, "to test this, I need a database" is the answer to every test question, and your CI takes 20 minutes because every test run spins up SQL Server. Clean Architecture says: separate the business rules from the HTTP boundary, separate the database from the business rules, and enforce it with project references. A controller is allowed to call a service. A service is allowed to call a repository. A repository is allowed to know about EF Core. Nothing is allowed to know about anything "above" it in the chai

2026-06-22 原文 →
AI 资讯

Detect AI-Generated PDFs: What Works and What Does Not

Originally published at htpbe.tech . The version on htpbe.tech stays in sync with the latest detection algorithm — refer to it for the canonical text. Accounts payable teams are receiving receipts generated by ChatGPT plugins. HR platforms are seeing payslips rendered by Python scripts. Insurance claims contain repair estimates that no shop ever issued. The documents look correct. The logos match. The numbers are plausible. The question is: what can actually be detected, and what cannot? The honest answer requires separating two things that are often confused under the phrase “AI-generated document detection.” Two distinct problems called "AI-generated document detection" When people ask how to detect an AI-generated document, they usually mean one of two distinct things: Content classification asks: was the text in this document written by an AI language model? This is what tools like GPTZero and Turnitin’s AI detector do. They analyze writing style, token probability distributions, and linguistic patterns to estimate whether a human or a model produced the text. Structural forensics asks: was this PDF file generated by a real institutional system, or did it come from a headless browser, a PDF library, or a consumer tool? This is what HTPBE does. It reads the binary structure of the file — producer metadata, xref patterns, font embedding, object numbering — and checks whether those patterns match how legitimate institutional software generates documents. These are not the same problem. A document can contain AI-written text and still come from a real corporate system. A document can contain entirely human-written text and still have been rendered by Puppeteer an hour ago. The structural check and the content check answer different questions. HTPBE does structural forensics. It does not classify text. This article explains what that distinction means in practice, what the structural approach reliably catches, and where its limits are. What structural forensics detec

2026-06-22 原文 →