AI 资讯
# Building a Lightweight Product Filter with Vanilla JavaScript
Building a Lightweight Product Filter with Vanilla JavaScript While building a small e-commerce project, I wanted users to filter products instantly without refreshing the page. Instead of relying on a frontend framework, I opted for a simple solution using HTML data attributes, vanilla JavaScript, and a little CSS. The goal was straightforward: let visitors filter items by size while keeping the interface fast, responsive, and easy to maintain. HTML Structure Each product card stores its information in data-* attributes. This keeps the markup clean and makes filtering straightforward. <div class= "filters" > <button class= "filter-btn" data-filter= "all" > All </button> <button class= "filter-btn" data-filter= "small" > S </button> <button class= "filter-btn" data-filter= "medium" > M </button> <button class= "filter-btn" data-filter= "large" > L </button> </div> <div class= "product-grid" > <div class= "product-card" data-size= "medium" data-style= "cargo" > Cargo Shorts </div> <div class= "product-card" data-size= "large" data-style= "chino" > Chino Shorts </div> <!-- More product cards --> </div> Using data attributes means you can add new filter categories later without changing your overall structure. JavaScript Filtering Logic The filtering logic listens for button clicks and simply shows or hides product cards based on the selected size. const filterButtons = document . querySelectorAll ( " .filter-btn " ); const productCards = document . querySelectorAll ( " .product-card " ); filterButtons . forEach (( button ) => { button . addEventListener ( " click " , () => { const filterValue = button . dataset . filter ; productCards . forEach (( card ) => { const cardSize = card . dataset . size ; if ( filterValue === " all " || cardSize === filterValue ) { card . classList . remove ( " hidden " ); } else { card . classList . add ( " hidden " ); } }); filterButtons . forEach (( btn ) => btn . classList . remove ( " active " )); button . classList . add ( " active "
AI 资讯
An Introduction to Neural Networks
Hi guys ! I'm a new developer who's interested in data science and artificial intelligence. To showcase what I learnt thus far, I've started writing articles, with my first one being published here ! One of the most difficult parts of getting into machine learning was the overload of terminology that tutorials had, even when explaining basic concepts such as how a neural network itself would function. Because of this, I've written an article (see above) that simplifies it while ensuring the main concepts are sufficiently explained; it requires no mathematical background and will only take less than 5 minutes to read ! I hope you find it informative and well written, and I highly welcome any suggestions or corrections that might be suggested to improve my future articles !
AI 资讯
Seven things to check before a WordPress major upgrade — before "patch what breaks after" becomes a disaster
WordPress major version upgrades (5.x → 6.x, and eventually 6.x → 7.x) are a different animal from minor releases. Minor releases (like 6.4.1 → 6.4.2) are mostly bug fixes with low compatibility risk. Majors land API deprecations, raised PHP minimum requirements, and core block replacements all at once — and those things hit operations hard. The " just hit Update in the admin and patch whatever breaks " workflow can survive on a single personal site, but it tends to fall apart under multi-site maintenance — simultaneous failures across sites overwhelm root-cause triage. This post collects the things worth verifying before you run a major upgrade, as a seven-item checklist . 1. Has the minimum PHP version been raised? Major WordPress releases sometimes raise the minimum supported PHP version (6.6 lifted it to PHP 7.2.24, and a future 7.0 will very likely require PHP 8.x). What matters operationally isn't just the server's PHP version and WordPress's stated minimum — it's the intersection with the PHP versions your plugins and themes actually run on . You can usually upgrade your server's PHP, but older themes and plugins not running on new PHP isn't rare. A subtle failure mode here: traps like PHP 8.2+ deprecated warnings leaking into older WP-CLI JSON output , where nothing visibly errors but your operational tooling silently breaks. Before upgrading, run wp plugin list --format=json on the production PHP environment and verify you're getting clean JSON. That one check catches a lot of post-upgrade pain. 2. Audit "Tested up to" for every plugin Each plugin's readme.txt carries a Tested up to: X.X line — the developer's declaration of the highest WordPress version they've actually tested against . It's the first signal for major-upgrade compatibility audits. WP-CLI gives you the inventory in one shot: wp plugin list --fields = name,version,update_version,update --format = table Plugins where "Tested up to" is old AND no updates in the last year deserve scrutiny. Acti
AI 资讯
Adaptive Thinking Killed My Token Budget Code: Migrating Off budget_tokens
I had a tidy little helper that computed a thinking budget based on input size. Something like "give the model 30% of the context as thinking room." It worked great on Opus 4.5. Then I tried to point it at Opus 4.8 and got a 400. The whole concept I had built around is gone in the current models. Here is what replaced it and how I migrated. What broke The old pattern looked like this: // Opus 4.5 and earlier const response = await client . messages . create ({ model : " claude-opus-4-5 " , max_tokens : 16000 , thinking : { type : " enabled " , budget_tokens : 8000 }, messages , }); On Opus 4.7, 4.8, and Fable 5, thinking: { type: "enabled", budget_tokens: N } returns a 400. The fixed token budget is dead. The replacement is adaptive thinking, where the model decides how much to think, plus an effort knob that controls overall token spend. // Opus 4.8 const response = await client . messages . create ({ model : " claude-opus-4-8 " , max_tokens : 16000 , thinking : { type : " adaptive " }, output_config : { effort : " high " }, // low | medium | high | xhigh | max messages , }); Why this is actually better (after I got over it) My old budget code was a guess dressed up as a calculation. I had no real basis for "30% of context." I picked it because it felt reasonable and the outputs looked fine. Adaptive thinking moves that decision to the model, which sees the actual problem. The mental model shift: budget_tokens controlled how much the model could think. effort controls how much it thinks and acts . They are not the same axis, so there is no clean 1:1 mapping. I stopped trying to translate "8000 tokens" into an effort level and instead picked based on the workload. How I chose effort levels After running my own evals, here is where I landed: Workload Effort Notes Classification, routing low Fast, scoped, not intelligence-sensitive Most app traffic medium to high The balance point Coding and agentic loops xhigh Best for these; it is the Claude Code default Correctness
AI 资讯
Build a Local LLM Chatbot with Ollama and Python
Build a Local LLM Chatbot with Ollama and Python Build a Local LLM Chatbot with Ollama and Python Imagine typing a question into your chatbot and getting a response in milliseconds, completely offline, with zero data leaving your machine. No API keys, no monthly subscription fees, and no privacy concerns about your data being sent to a cloud server. This isn’t a futuristic dream—it’s the reality of running a Local Large Language Model (LLM) on your own computer. With the rise of tools like Ollama , building a private AI chatbot in Python has become as simple as installing a few packages and writing a short script. Let’s dive in and build one together. Why Go Local? Before we write any code, it’s worth understanding why running an LLM locally is a game-changer. Cloud-based AI services like OpenAI or Anthropic are powerful, but they come with trade-offs: you pay per token, your data is processed on their servers, and you’re dependent on their uptime. A local LLM flips this model. You download the model once, run it on your hardware, and you have full control. Ollama is the engine that makes this accessible. It’s a lightweight, open-source tool that simplifies running LLMs like Llama 3, Phi 3, or Mistral on macOS, Linux, and Windows. It handles model downloads, memory management, and inference, exposing a simple API that Python can easily interact with [1][2]. Step 1: Install Ollama and Pull a Model The first step is getting Ollama on your machine. Visit ollama.com , click Download , and install the version for your operating system [2]. Once installed, verify it’s working by opening your terminal or Command Prompt and running: ollama --version If you see a version number, you’re ready to go. Next, you need a model. Ollama supports dozens of open-source models, but for a beginner-friendly chatbot, Llama 3.2 is a great choice. It’s small, fast, and surprisingly capable. To download it, run: ollama pull llama3.2 This command fetches the model and stores it locally. Depen
开发者
Learn 7 common MongoDB query mistakes with simple find() examples, including $or, $in, nested fields, dates, and text search.
7 MongoDB Query Mistakes That Return the Wrong Results VisuaLeaf VisuaLeaf VisuaLeaf Follow Jul 14 7 MongoDB Query Mistakes That Return the Wrong Results # mongodb # coding # software # database 3 reactions Add Comment 5 min read
AI 资讯
I Wish I Ran the Numbers on Open Source AI APIs Sooner
I Wish I Ran the Numbers on Open Source AI APIs Sooner Three months ago I would have told you self-hosting was the obvious move. "Open source means free, right?" I said that to a client while quoting them $3,500 for a GPU server setup. They smiled politely and went with someone else. That rejection sent me down a rabbit hole I wish I'd started years earlier, because the actual math — not the vibes-based math freelancers like me tend to do — completely flips the script. If you're running a solo practice or a tiny shop, you probably bill every minute of GPU babysitting straight out of your own pocket. That's time you could be shipping features, pitching clients, or — if we're being honest — sleeping. So let me walk you through what I learned the hard way, with all the pricing left exactly where it belongs. The Open Source Lineup That Actually Matters Right Now When I started this research, I assumed "open source AI API" was an oxymoron. If you're calling an API, somebody owns the server, so what's even the point of being open? Turns out the point is massive: open-weight models accessible through an API give you the pricing transparency of self-hosting without the DevOps funeral you're planning for your weekends. Here's the pricing matrix I put together from Global API's public rates. These are output token prices (input is usually cheaper), and yes — they're shockingly low compared to GPT-4o territory. Model License Output Price Self-Host Range DeepSeek V4 Flash Open weights $0.25/M $500-2,000/mo DeepSeek V3.2 Open weights $0.38/M $800-3,000/mo Qwen3-32B Apache 2.0 $0.28/M $400-1,500/mo Qwen3-8B Apache 2.0 $0.01/M $200-800/mo Qwen3.5-27B Apache 2.0 $0.19/M $300-1,200/mo ByteDance Seed-OSS-36B Open weights $0.20/M $500-2,000/mo GLM-4-32B Open weights $0.56/M $400-1,500/mo GLM-4-9B Open weights $0.01/M $200-800/mo Hunyuan-A13B Open weights $0.57/M $300-1,000/mo Ling-Flash-2.0 Open weights $0.50/M $300-1,000/mo Look at Qwen3-8B and GLM-4-9B at $0.01/M output tokens. A mi
AI 资讯
My MCP Server Kept Crashing. Here's the Error Recovery Pattern That Saved It.
I spent three days wondering why my MCP server would just... stop. No crash logs. No error messages. Clients connected fine, then after a few hours, every tool call returned silence. Turns out the Model Context Protocol (MCP) spec doesn't force you to handle errors — it assumes you will. But the reference implementations are minimal. Your server starts healthy, then bit by bit, things go wrong. A network blip. A malformed tool argument. An external API timeout. And suddenly your AI agent is staring at a blank response. Here's the pattern I ended up with. It's not clever. It just works. The Fix Start with a wrapper around your tool handlers. Every MCP server framework has some kind of tool registration — this works for the official Python SDK, the TypeScript SDK, and most community frameworks: from mcp.server import Server from mcp.types import ErrorData , INTERNAL_ERROR , INVALID_PARAMS import traceback import json class ResilientMCPServer ( Server ): """ An MCP server that doesn ' t silently die. """ async def call_tool ( self , name : str , arguments : dict ): try : result = await super (). call_tool ( name , arguments ) return result except ( ConnectionError , TimeoutError ) as e : # Network-level issues — reconnect and retry self . _reconnect () return self . _error_response ( f " Connection lost while executing { name } : { e } " ) except ValueError as e : # Bad arguments from the client — tell them clearly return self . _error_response ( f " Invalid arguments for { name } : { e } " , code = INVALID_PARAMS ) except Exception as e : # Everything else — log, don't crash traceback . print_exc () return self . _error_response ( f " Tool { name } failed: { e } " , code = INTERNAL_ERROR ) def _error_response ( self , message : str , code : int = INTERNAL_ERROR ): return { " content " : [{ " type " : " text " , " text " : f " ERROR: { message } " }], " isError " : True } def _reconnect ( self ): """ Reset transport layer without restarting the server. """ # Your recon
AI 资讯
Python Redis: Caching and Fast Data Structures
Python Redis: Caching and Fast Data Structures Redis is an in-memory data store used for caching, session storage, pub/sub messaging, leaderboards, rate limiting, and more. With redis-py 's async client, it integrates cleanly into any asyncio application. Installation pip install redis[hiredis] # hiredis is a C parser — 2-5× faster protocol parsing Connect and Verify import asyncio import redis.asyncio as aioredis from datetime import timedelta import json REDIS_URL = " redis://localhost:6379/0 " async def get_redis () -> aioredis . Redis : client = aioredis . from_url ( REDIS_URL , encoding = " utf-8 " , decode_responses = True , socket_connect_timeout = 5 , socket_timeout = 5 , retry_on_timeout = True , ) pong = await client . ping () print ( f " Redis connected: { pong } " ) return client Strings — Basic Cache with TTL async def cache_set ( r : aioredis . Redis , key : str , value : str , ttl : int = 300 ) -> None : await r . set ( key , value , ex = ttl ) async def cache_get ( r : aioredis . Redis , key : str ) -> str | None : return await r . get ( key ) # Cache-aside pattern async def get_user_profile ( r : aioredis . Redis , user_id : int , db ) -> dict : cache_key = f " user:profile: { user_id } " cached = await r . get ( cache_key ) if cached : print ( f " Cache HIT for user { user_id } " ) return json . loads ( cached ) print ( f " Cache MISS for user { user_id } — querying DB " ) user = await db . fetch_user ( user_id ) # your DB call if user : await r . set ( cache_key , json . dumps ( user ), ex = 600 ) return user or {} # Atomic counter async def increment_page_views ( r : aioredis . Redis , page : str ) -> int : key = f " views: { page } " count = await r . incr ( key ) await r . expire ( key , 86400 ) # reset counter after 24 h return count Hashes — Structured Objects async def save_session ( r : aioredis . Redis , session_id : str , data : dict , ttl : int = 3600 ) -> None : key = f " session: { session_id } " await r . hset ( key , mapping = data )
AI 资讯
🍪 Cookies and CORS — When Are Cookies Actually Sent?
In the previous article , we briefly discussed the relationship between Cookies and CORS . In this article, we'll take a closer look at how browsers decide whether a Cookie should be included in a Cross-Origin request. One of the most common misconceptions is that once CORS is configured correctly, Cookies are automatically sent with every request. In reality, that's not how browsers work. 📌 Default Browser Behavior When a Cross-Origin request is made using fetch() or XMLHttpRequest , browsers do not send Cookies, Authorization headers, or other credentials by default. For example: fetch ( " https://api.example.com/profile " ) Even if the user is already logged into api.example.com , the browser will not include any Cookies with this request. This default behavior helps prevent authentication data from being unintentionally leaked across different Origins. 📌 How Can We Send Cookies? If you want the browser to include Cookies in a Cross-Origin request, you must explicitly use the credentials option. For example: fetch ( " https://api.example.com/profile " , { credentials : " include " }) Using credentials: "include" does not guarantee that Cookies will be sent. Instead, it tells the browser: "If there are any Cookies that are eligible to be sent with this request, include them." 📌 What Makes a Cookie Eligible? Even with credentials: "include" , the browser still evaluates the Cookie before sending it. Some of the most important checks include: Domain Path SameSite For example: If the Cookie's Domain doesn't match the request destination, it won't be sent. If the request path doesn't satisfy the Cookie's Path attribute, it won't be sent. If the Cookie's SameSite policy blocks Cross-Site requests, it won't be sent. In other words, credentials is only the first requirement , not the final decision. 📌 Server Configuration Matters Too If your application expects JavaScript to access the response while using Cookies, the server must also be configured correctly. For exampl
AI 资讯
JavaScript Event Loop Explained: The Complete Guide
You've written setTimeout(fn, 0) expecting it to run "immediately." It didn't. A Promise.then() you scheduled a line later ran first, and somewhere a for loop of 50,000 iterations froze your UI for a full second despite every function being "async." None of this is a bug. It's the JavaScript event loop doing exactly what it always does — you just haven't seen the mechanism yet. What you'll learn By the end of this guide you'll be able to: Explain, precisely, why microtasks (Promises) always run before macrotasks ( setTimeout , setInterval ) — even at a zero delay Predict the exact console output order of any mix of synchronous code, setTimeout , and await Diagnose a frozen UI as a blocked call stack, not a "slow async function" Choose correctly between queueMicrotask , setTimeout(fn, 0) , and requestAnimationFrame for a given timing need Avoid the two most common event-loop bugs: microtask starvation and accidental serial await s in a loop Who this is for: you've written async / await and used setTimeout , but you want the model that makes their interaction predictable instead of memorized. Contents Why the JavaScript event loop exists The mental model Stage 1: the call stack and blocking code Stage 2: Web APIs and the macrotask queue Stage 3: Promises and the microtask queue Stage 4: async/await is sugar, not magic Stage 5: rendering, and Node's extra queues Edge cases and gotchas Best practices FAQ Cheat sheet Key takeaways Why the JavaScript event loop exists JavaScript runs on a single thread. One call stack, one thing executing at a time, no parallel function calls in the same realm. That's a deliberate design — it means you never need locks or mutexes to protect a shared variable — but it creates an obvious problem: how does a single-threaded language do anything concurrent, like waiting on a network response, without freezing the entire page while it waits? Here's the naive expectation, and why it would be a disaster if JavaScript worked this way: console . l
AI 资讯
Improve Performance by Loading Videos Only When They're Needed
Videos are one of the heaviest assets you can add to a web page. Loading videos too early can significantly impact your application's performance. The good news is that modern browsers are starting to support lazy loading for video elements , allowing you to defer loading until users are likely to watch them. However, there's one important thing to know: 👉 This feature is not yet part of the Baseline web platform , so browser support is still limited. At the time of writing, lazy loading for <video> elements is supported in Chromium-based browsers such as Google Chrome , Microsoft Edge , and Opera , while browsers like Firefox and Safari do not yet support it natively. In this article, we'll explore: What lazy loading videos is Why it's important for web performance How to implement it Browser support considerations Best practices for optimizing video loading Let's dive in. 🤔 What Is Lazy Loading for Videos? Lazy loading means delaying the loading of a resource until it's actually needed. Instead of downloading every video immediately during page load, the browser waits until the video is close to entering the viewport. This helps reduce: initial network requests bandwidth usage page load time memory consumption Especially on pages with multiple videos, the difference can be significant. 🟢 What Problem Does It Solve? Imagine an e-commerce page with several product videos. Without lazy loading: every video starts downloading immediately bandwidth is consumed even for videos users never watch page rendering may become slower This negatively impacts; Largest Contentful Paint (LCP), Time to Interactive (TTI), and overall user experience. Most visitors won't watch every video on the page. So why load them all? Lazy loading ensures videos are fetched only when they're actually needed. 🟢 How to Lazy Load a Video The easiest approach is using the loading="lazy" attribute. Example: <video controls loading= "lazy" poster= "/preview.jpg" > <source src= "/video.mp4" type= "vide
AI 资讯
I Tested Direct Provider APIs vs Aggregators — Here's the Truth
I Tested Direct Provider APIs vs Aggregators — Here's the Truth Six months ago I was staring at a $48,000 invoice from an AI provider that shall not be named. We had committed to a six-month contract because the sales rep promised "priority routing" and "negotiated rates." What we got instead was a rate hike, an outage during our biggest product launch, and a support team that took 72 hours to respond. That was the moment I decided to stop signing contracts with AI providers entirely. This is the playbook I wish someone had handed me on day one — the architecture decisions, the math, and the code that lets a small team punch way above its weight class without betting the company on a single vendor. The Trap Most Startups Fall Into When I started my last company, I did what every founder does. I read the docs, got an API key, shipped a feature. The model worked, the demo went well, the investors nodded. Then we hit production traffic and the bills started arriving like clockwork. Here's what nobody tells you about going direct to a model provider as a startup: The pricing page you see on the website is the retail price. The actual cost of running production workloads includes rate limits you didn't anticipate, caching you forgot to implement, context windows that blow up your token count, and prompt engineering iterations that look cheap per call but compound fast. I watched one team burn $20K in a single weekend because they were streaming completions without setting a max_tokens guardrail. Direct providers also lock you into their ecosystem. Their SDK, their tools, their prompt format, their authentication scheme. The moment you want to A/B test a different model — which you will, probably next quarter — you're rewriting integration code instead of shipping features. And then there's the geopolitical mess. Some of the best models in 2026 come from providers that don't accept US credit cards. I've personally lost an afternoon trying to sign up for an account that re
AI 资讯
SQL: Data Constraints
Introdução Validar dados é uma responsabilidade que pode ficar na aplicação, no banco de dados, ou em ambos. Deixar tudo na aplicação é arriscado: diferentes sistemas podem acessar o mesmo banco, migrações podem rodar diretamente, um bug pode deixar passar um valor inválido. Constraints são regras definidas no próprio banco de dados — uma camada de proteção que age independente de quem está escrevendo os dados. PRIMARY KEY A chave primária identifica cada linha de forma única. Ela combina duas restrições implicitamente: NOT NULL e UNIQUE . Nenhuma linha pode ter o mesmo valor de chave primária, e nenhuma pode tê-la nula. CREATE TABLE clientes ( id INT PRIMARY KEY , nome VARCHAR ( 100 ) NOT NULL ); Quando a chave primária envolve mais de uma coluna, ela é declarada separadamente: CREATE TABLE matriculas ( aluno_id INT , curso_id INT , PRIMARY KEY ( aluno_id , curso_id ) ); Na maioria dos bancos, é comum usar uma chave primária auto-incremental para não precisar gerenciar os IDs manualmente: -- PostgreSQL id SERIAL PRIMARY KEY -- MySQL id INT AUTO_INCREMENTPRIMARY KEY -- SQL padrão (suportado por ambos) id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY FOREIGN KEY A chave estrangeira garante integridade referencial : um valor só pode existir numa coluna se ele existir como chave primária na tabela referenciada. É o que torna os relacionamentos entre tabelas confiáveis. CREATE TABLE pedidos ( id INT PRIMARY KEY , cliente_idINT REFERENCES clientes ( id ) ); Tentar inserir um pedido com cliente_id = 99 quando não existe cliente com esse id resulta em erro imediato. O banco rejeita a operação antes mesmo de ela chegar ao disco. O comportamento quando o registro referenciado é deletado pode ser configurado: CREATE TABLE pedidos ( id INT PRIMARY KEY , cliente_id INT REFERENCES clientes ( id ) ON DELETE CASCADE -- deleta os pedidos junto com o cliente ON UPDATE CASCADE -- atualiza o cliente_id se o id do cliente mudar ); As opções disponíveis são: Opção Comportamento RESTRICT
AI 资讯
SQL: Aggregate Queries
Introdução Consultas individuais respondem perguntas como "qual o email do cliente 42?". Mas as perguntas mais valiosas em qualquer sistema são de outro tipo: "qual o produto mais vendido?", "qual a receita média por pedido?", "quantos clientes se cadastraram esse mês?". Para responder isso, o SQL oferece as funções de agregação — operações que recebem um conjunto de linhas e devolvem um único valor resumido. Para os exemplos a seguir, considere esta tabela: pedidos: | id | cliente | produto | categoria | quantidade | valor | |----|------------|-------------|--------------|------------|--------| | 1 | Ana Lima | Notebook | Eletrônicos | 1 | 3500.00| | 2 | Ana Lima | Mouse | Periféricos | 2 | 80.00| | 3 | Bruno Melo | Teclado | Periféricos | 1 | 150.00| | 4 | Bruno Melo | Notebook | Eletrônicos | 1 | 3500.00| | 5 | Carla Nunes| Monitor | Eletrônicos | 2 | 1200.00| | 6 | Carla Nunes| Mouse | Periféricos | 1 | 80.00| As Funções de Agregação COUNT Conta o número de linhas — ou de valores não nulos em uma coluna específica. -- Total de pedidos SELECT COUNT ( * ) AS total_pedidosFROM pedidos ; -- Resultado: 6 -- Clientes distintos que fizeram pedidos SELECT COUNT ( DISTINCT cliente ) AS clientes_unicosFROM pedidos ; -- Resultado: 3 COUNT(*) conta todas as linhas, incluindo as que têm nulos. COUNT(coluna) conta apenas as linhas onde aquela coluna não é nula. COUNT(DISTINCT coluna) conta valores únicos — útil para saber quantos clientes, produtos ou categorias distintos aparecem no resultado. SUM Soma os valores de uma coluna numérica. -- Receita total SELECT SUM ( valor ) AS receita_total FROM pedidos ; -- Resultado: 8510.00 -- Total de itens vendidos SELECT SUM ( quantidade ) AS itens_vendidos FROM pedidos ; -- Resultado: 8 AVG Calcula a média aritmética dos valores. -- Valor médio por pedido SELECT AVG ( valor ) AS ticket_medio FROM pedidos ; -- Resultado: 1418.33 AVG ignora valores nulos automaticamente — calcula a média apenas sobre os registros que têm valor preenchid
AI 资讯
Using WebSockets to Convert BTC to USD and Reais (BRL)
If you need real-time BTC conversion (USD and BRL), polling an API every few seconds is usually not enough. A better approach is streaming quotes with WebSockets and calculating conversions as events arrive. Why WebSockets for BTC conversion? With WebSockets, your app keeps one open connection and receives new prices instantly. Benefits: Lower latency than polling Fewer HTTP requests Better user experience for real-time values Trade-offs: You must handle reconnects Need heartbeat/health checks Must validate and normalize incoming messages Real-time conversion model For BTC conversion, a common model is: Stream BTC/USD Stream USD/BRL Calculate BTC/BRL = BTC/USD × USD/BRL This avoids waiting for a separate BTC/BRL endpoint and keeps conversion logic transparent What is a “tick”? A tick is one market update event. Example: BTCUSD changed to 64210.50 at timestamp t . In this article, each tick has: pair : market identifier ( BTCUSD , USDBRL ) price : latest value for that pair ts : event timestamp Why this matters: conversion state should always be derived from the latest ticks . Minimal WebSocket client (TypeScript) This client only transports responsibilities: Connect Receive messages Parse and normalize into a consistent shape Notify listeners Reconnect on disconnect type MarketTick = { pair : string ; // e.g. "BTCUSD" or "USDBRL" price : number ; ts : number ; }; class WsFeedClient { private ws ?: WebSocket ; private listeners : Array < ( tick : MarketTick ) => void > = []; constructor ( private readonly url : string ) {} connect () { this . ws = new WebSocket ( this . url ); this . ws . onopen = () => console . log ( " [ws] connected " ); this . ws . onmessage = ( event ) => { try { const data = JSON . parse ( String ( event . data )); // Normalize external payload into internal contract const tick : MarketTick = { pair : String ( data . pair ), price : Number ( data . price ), ts : Number ( data . ts ), }; // Basic guard if ( ! tick . pair || Number . isNaN ( tick
AI 资讯
I Built an AI Agent with Claude's Tool-Use Loop (Web Search, SQL, and More)
"AI agent" gets thrown around so much I figured I should just build one instead of reading more threads about it. The core idea turned out to be small: you put Claude in a loop and hand it some tools. It picks a tool, you run it, you hand back the result, and it keeps going until it has an answer. Code is here if you want to skip ahead: claude-research-agent . What it can do Give it a task and it works out the steps on its own. Mine can: search the web (no API key for this part, it just hits DuckDuckGo's HTML page) open a URL and pull the readable text out do math without me trusting eval run read-only SQL against a SQLite file read local files, but only inside the project folder save findings to a notes file The loop is basically the whole thing Honestly this is most of it: messages = [{ " role " : " user " , " content " : user_message }] for _ in range ( MAX_STEPS ): response = client . messages . create ( model = " claude-sonnet-5 " , max_tokens = 2048 , tools = TOOL_SCHEMAS , messages = messages , ) messages . append ({ " role " : " assistant " , " content " : response . content }) if response . stop_reason != " tool_use " : return final_text ( response ) tool_results = [] for block in response . content : if block . type == " tool_use " : result = run_tool ( block . name , block . input ) tool_results . append ({ " type " : " tool_result " , " tool_use_id " : block . id , " content " : result , }) messages . append ({ " role " : " user " , " content " : tool_results }) The thing to watch is stop_reason . If Claude says tool_use , it wants you to run something. You run it, drop the result back into the conversation as a tool_result , and loop. When it stops asking for tools, you're done. The MAX_STEPS cap is just there so a confused agent can't spin forever. Tools are just functions Each tool is a Python function plus a little JSON schema telling Claude when to reach for it. Want a new capability? Write a function, add its schema. The loop never changes, which w
AI 资讯
Kiponos Java SDK 5.0 What’s New — Developer Guide
Kiponos Java SDK 5.0 What’s New — Developer Guide This is the technical companion to the 5.0 milestone announcement: what changed, how modes behave, how to read config with the Folder API, and how to upgrade cleanly. Version 5.0.0.260710 Maven group io.kiponos Artifacts sdk-boot-3 (recommended), sdk-boot-2 (legacy) Released 2026-07-12 (Maven Central) Happy product story: SDK 5.0 milestone post . 1. Summary for busy engineers 5.0 productizes client reliability using a classic state pattern behind a stable facade: Mode When Config reads Mutations / hooks Notes Ready Connected to hub Live in-memory tree Full Production happy path Offline Disconnected but LKG available Last Known Good (read-only) No-op / ignored Survives hub blips without inventing values Safe Fail-closed Empty / null-safe No-op Diagnostic dumps must not overwrite LKG Public entry remains: Kiponos kiponos = Kiponos . createForCurrentTeam (); You do not receive mode instances as the API surface. Modes switch internally. Query with: kiponos . getCurrentMode (); kiponos . isReadyMode (); kiponos . isOfflineMode (); kiponos . isSafeMode (); 2. Install Gradle — Boot 3 repositories { mavenCentral () } dependencies { implementation 'io.kiponos:sdk-boot-3:5.0.0.260710' } Gradle — Boot 2 implementation 'io.kiponos:sdk-boot-2:5.0.0.260710' Runtime inputs Input Mechanism Identity env KIPONOS_ID Access env KIPONOS_ACCESS Profile / tree slice JVM -Dkiponos="['App']['1.0.0']['dev']['base']" Tokens and profile come from the Kiponos Connect screen for your team. sdk-common is not a separate app dependency for consumers — boot jars include shared classes (fat-jar pattern). 3. Architecture (state pattern) Application code │ ▼ Kiponos / KiponosBase ◄── stable facade (one reference for app lifetime) │ ▼ volatile SdkState ├── ReadyMode* → live WebSocket + full Folder ops ├── OfflineMode* → LKG reads only └── SafeMode* → fail-closed + safe diagnostic dump Design rule: never return Ready/Offline/Safe objects to callers. Retur
AI 资讯
The Developer's Guide to Picking the Right Coding LLM at Scale
The Developer's Guide to Picking the Right Coding LLM at Scale Six months ago, I was staring at our monthly AI bill — $14,000 and climbing fast. We were using the "premium" model for everything, including trivial code completions. That night, I built a small internal benchmark to figure out which models actually earn their cost. What I learned reshaped how we think about AI tooling, vendor lock-in, and what "production-ready" really means. Here's the raw truth from my testing rig, what we shipped, and how we cut costs by 70% without touching output quality. Why I Stopped Trusting Default Recommendations Every vendor says their model is the best. Every benchmark site ranks things differently. Most "best of" lists are either sponsored or built on vibes. I needed numbers that matched my actual workflow: generating Python services, debugging JavaScript race conditions, implementing TypeScript algorithms, and reviewing Go for security. So I took ten models, threw identical prompts at them, and scored them myself. No vendor PR. No cherry-picked examples. Just the same five tasks, run the same way, scored on the same rubric. Here are the ten models I tested, with their output pricing per million tokens — because at scale, that's the metric that decides whether your AI strategy is viable or a margin killer. Model Provider Output $/M DeepSeek V4 Flash DeepSeek $0.25 DeepSeek Coder DeepSeek $0.25 Qwen3-Coder-30B Qwen $0.35 DeepSeek V4 Pro DeepSeek $0.78 DeepSeek-R1 DeepSeek $2.50 Kimi K2.5 Moonshot $3.00 GLM-5 Zhipu $1.92 Qwen3-32B Qwen $0.28 Hunyuan-Turbo Tencent $0.57 Ga-Standard GA Routing $0.20 Before you ask: yes, I tested against the originals. I also tested against Global API's unified routing layer, which lets you hit any of these through one endpoint. More on that later — it became the architectural decision that actually saved us. My Benchmark Methodology (No Marketing Fluff) I built five tasks that mirror what my engineers actually do every week. Not synthetic acad
AI 资讯
Power BI DAX Essential Functions — Explained with Examples
If you’ve ever struggled with CALCULATE() or wondered why SUMX() behaves differently from SUM() , this guide is for you. DAX (Data Analysis Expressions) is the language that powers Power BI , Analysis Services , and Power Pivot — enabling dynamic calculations, filtering, and time intelligence. Below is a categorized cheat sheet of essential DAX functions , plus examples showing how to use each in real-world Power BI scenarios. Filtering & Context These functions control how filters are applied and evaluated in your calculations. Function Example Description CALCULATE() CALCULATE(SUM(Sales[Amount]), Region[Name] = "Nairobi") Changes filter context to calculate total sales for Nairobi. FILTER() FILTER(Sales, Sales[Amount] > 10000) Returns a table filtered by condition. ALL() CALCULATE(SUM(Sales[Amount]), ALL(Region)) Ignores filters on Region. REMOVEFILTERS() CALCULATE(SUM(Sales[Amount]), REMOVEFILTERS(Region)) Removes filters from Region. VALUES() VALUES(Customer[City]) Returns unique list of cities. SELECTEDVALUE() SELECTEDVALUE(Product[Category], "All") Returns selected category or “All” if none. TREATAS() TREATAS(VALUES(Temp[City]), Customer[City]) Applies one table’s values as filters on another. KEEPFILTERS() CALCULATE(SUM(Sales[Amount]), KEEPFILTERS(Product[Category] = "Electronics")) Keeps existing filters and adds new ones. ALLSELECTED() CALCULATE(SUM(Sales[Amount]), ALLSELECTED(Region)) Respects user selections in visuals. ALLEXCEPT() CALCULATE(SUM(Sales[Amount]), ALLEXCEPT(Sales, Sales[Year])) Removes all filters except Year. Aggregation Summarize or aggregate data across rows or columns. Function Example Description SUM() SUM(Sales[Amount]) Adds all sales amounts. AVERAGE() AVERAGE(Sales[Amount]) Calculates mean value. COUNT() COUNT(Customer[ID]) Counts non-blank entries. COUNTROWS() COUNTROWS(Sales) Counts rows in a table. DISTINCTCOUNT() DISTINCTCOUNT(Customer[ID]) Counts unique customers. MIN() MIN(Sales[Amount]) Finds smallest sale. MAX() MAX(Sales[Amo