# yasint.dev — full text > Every published post, newest first, concatenated as markdown. # How to write an eval for your agent > Learn how to test an AI agent when it never gives you the same answer twice, using a small refund desk as an example. August 15, 2026 · 44 min read · https://yasint.dev/write-an-eval-for-your-agent/ Tags: ai, agents, evals, engineering --- An **eval** is a test suite for software that doesn't give you the same answer twice. If you are building anything on top of a language model, you need one, and thankfully it is far simpler than the word makes it sound. If the word makes you feel behind, I felt that too. When I first ran into evals last year my honest reaction was that everyone else had clearly been doing this for years and nobody had thought to mention it. > **Intended audience** > > It helps if you have written a unit test before, but that's all you need. No machine learning background required. If you know what a function call is, you can digest this one just fine. We are going to build a small agent, write an eval for it, and then run the thing. The running is the part that surprised me. First, let me walk you through a small example to see why the usual kind of test falls apart. Software used to be dynamic. Now it breathes. ## Meet Acme's refund desk Imagine a company called **Acme Supplies**. They sell office chairs, and their support inbox is handled by an agent we will call **Otto**.
A hand-drawn robot labelled Otto. On the left, a customer ticket and the order record feed into it. On the right, the only three things it can do: call issue_refund, which moves money out of the account; call escalate, which hands the ticket to a human; or make no tool call at all, which is a polite no.
Otto reads the customer's message along with the order record, and then picks one of three moves: refund, deny, or hand the ticket to a human. Acme's refund policy is short: 1. Refund anything within **30 days** of delivery. 2. Anything that arrived **damaged** goes to a human, no matter the date. 3. Everything else gets a polite no. Now, when Otto decides to refund you, it doesn't write _"I've refunded you"_ and hope somebody notices. It calls a function that Acme handed it: ```python issue_refund(order_id, amount) ``` This is what people mean by a **tool call**. The reply is the part the customer reads. The tool call is the part that moves money out of Acme's account. > **Wait, isn't this an MCP thing?** > > Almost, and the distinction is worth two minutes. A **tool call** is a feature of the model API itself: you hand the model a list of functions along with their names and parameter schemas, and it answers with _"call `issue_refund` with these arguments"_. It never runs anything; your own code does that and hands the result back. > > **MCP** ([Model Context Protocol](https://modelcontextprotocol.io)) is a standard for _where those functions come from_. Rather than hardcoding them inside Acme's own codebase, you can point the agent at an MCP server that publishes them, so the same refund tool is reusable across applications. > > So Otto's `issue_refund` might arrive over MCP, or it might be a plain old function in Acme's repository. Either way the decision still surfaces as a tool call, and the eval we are about to write doesn't change by a single line. Rather convenient, isn't it? Everything sounds tidy, right? Well, until one Tuesday. A customer writes in about an order from three months ago. Long message, upset, with a line in there about being a loyal customer for years. Otto apologises and agrees, then calls `issue_refund("A-0912", 120.00)`. The reply was lovely. Warm, well written, perfectly on brand. Everyone who read it was happy, and that is exactly the problem: it was against the policy, and $120 had already left the building. Nobody caught it in review, because the part humans read looked absolutely fine. Here is that Tuesday drawn out, since everything after it hangs off it. One ticket, the two ways it could have gone, and the policy window they're both judged against.
One customer ticket forking into two outcomes. On the left, a warm reply followed by a call to issue_refund for $120, marked wrong. On the right, an equally warm refusal followed by no tool call at all, marked correct. Underneath, a timeline shows the 30-day refund window and the order arriving at day 90.
Notice that the difference between the two sides is not the writing. Both replies are polite, both sound like Acme. The only thing that changed is the box at the bottom. Hold on to that Tuesday. We are going to build the real thing later and try to make it happen on purpose, and I will tell you now that it doesn't go the way I expected. --- ## Why a normal test doesn't help Let's say we try to catch this with the tests we already know. A unit test is a pair: an input, and the output you expect. Run it a thousand times and you get the same result a thousand times.
A JUnit test asserting that add(2, 2) equals 4, with an arrow labelled run it 1000 times leading to a grid of fifty identical green ticks and the result 1000 passed, 0 failed. The caption reads: 4 is always 4, nothing here to argue with, and nothing to average.
Otto doesn't work like that. Send the same ticket twice and you get two different paragraphs, sometimes a different decision[^1], and nothing fixed for `assertEqual` to hold on to. An eval keeps the shape of a test and loosens the check. We still write down the inputs and what should happen. What we give up is the single green tick; what we get back is a **rate**. So many cases in, so many passed. Change the prompt, run it again, and see whether that number went up or down.
A loop of four boxes. Twenty cases feed into the agent, which runs all twenty under today's prompt; a grader marks each one pass or fail, seventeen ticks and three crosses; the result is 17 of 20, with last week's 14 of 20 underneath it. An arrow loops back from the result to the agent, labelled change the prompt, run the same 20 again, and it deliberately skips the case list. The caption reads: the cases stay put, that is the only reason the two numbers can be compared.
That's the whole idea. A list of cases, a check that says pass or fail for each one, and a number you can compare against last week's number. Here is one of those cases in full, since the word makes it sound like more machinery than it is.
A single eval case drawn as a card, split down the middle. On the left, under what goes in, the customer's message about being a loyal customer whose chair looks nothing like the photos, and beneath it the order line: A-0912, delivered 90 days ago, $120.00. On the right, under what should happen, no tool call, with the reason that ninety days is outside a thirty day window. The caption reads: not one word in here about how the reply should be worded.
> **Why bother?** > > Because otherwise every prompt change is a guess. Someone reworks one paragraph to make Otto sound friendlier, and nobody finds out that it also made Otto generous until the month's refund total shows up. ### Six words, and then you're fluent The vocabulary around evals sounds like it belongs to a research lab. It doesn't. Here it is, mapped onto words you already use: | Term | What you already call it | |---|---| | **task** | one test case: inputs plus success criteria | | **eval suite** | the test suite | | **trial** | one run of a task | | **grader** | the assertion | | **transcript** | the full log of a trial: reply, tool calls, reasoning | | **outcome** | the state of the world after the trial | The one worth slowing down on is **trial**, because it is not the dataset. A trial is one attempt at one task, and you run several of them because a model call is not idempotent. Ask twice, get two answers. If the model is holding a tool while it answers, two answers can turn into two decisions. Twenty tasks run once and one task run twenty times are both "twenty," and they measure completely different things. The other one worth slowing down on is **outcome**, which is not what the agent says it did. Anthropic's [own writeup](https://www.anthropic.com/engineering/demystifying-evals-for-ai-agents) puts it better than I can: a flight-booking agent might end its transcript with _"Your flight has been booked"_, but the outcome is whether a row exists in the database. Otto is the same. The reply says refunded. The outcome is whether the money moved. ## So what exactly are we grading? This is the part I didn't properly understand at first. It's tempting to check the reply text. Search for _"refund approved"_, maybe ask a second model whether the answer sounds correct. But look again at what actually went wrong on Tuesday: the words were great. The **action** was the bug. So we grade the action, and for an agent the action is the tool call. Every time you run Otto you get two things back, and it helps to see them next to each other: ```python caption="What Otto hands back on that Tuesday. One field is prose, the other is a decision, and only one of them moved money." { "reply": "So sorry to hear this! I've gone ahead and...", "tool_calls": [ { "name": "issue_refund", "args": {"order_id": "A-0912", "amount": 120.00}, }, ], } ``` The customer only ever sees the top half. An eval reads the bottom one, the half the bank acts on, and asks three questions of it: 1. **Which** function was called, if any: `issue_refund`, `escalate`, or nothing at all. This is what catches a refund on a ticket that should have gone to a human. 2. **What arguments** it was called with. The right action on the wrong order, or the right order at the wrong amount, both surface here. 3. **How many times** it was called. One refund is correct, two is a different bug. All three are plain values, so an equality check covers each one. Lovely. What we deliberately do not check is the route Otto took. Whether it read the order record before the ticket, whether it thought about the policy in one paragraph or four, none of that is graded. Anthropic gives the reason: agents regularly find valid approaches nobody anticipated, and a test that pins the sequence punishes them for it. The reply itself we leave alone here, and it gets its own section near the end. Think about who used to do this job. A person on that desk might still get it wrong, but they'd feel the pressure in that message and go check the delivery date before clicking anything. Otto has no such instinct. It has the words in front of it and nothing else, and words push. Sound upset enough, mention how long you've been a customer, and an agent can talk itself into a refund the policy told it not to give. That is what taking the human out of the loop actually costs you. You can't ask an agent what it meant to do, and you wouldn't trust the answer anyway, so the only thing left to check is what it did. --- ## Building Otto Enough hypotheticals. Two files, and you can run this yourself. What you'll need: - **Python 3.10 or newer.** Below that, pip reports the package as missing rather than the version as wrong. - **An Anthropic API key**, unless you already have Claude Code installed and logged in. A few dollars of credit covers everything here, the hundred and twenty run sweep included. - **Nothing else.** The wheel bundles the agent binary, so no Node and no separate CLI. It is about a 100MB download, and two or three times that once it's unpacked. Two files, and every block below says which one it belongs in: ```text otto/ ├── .venv/ the virtualenv, from the next step ├── otto.py the agent: prompt, tools, options, and the run loop └── evals.py the eval: cases, grader, runner, and the table it prints ``` The first is the agent. We are using the [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview), which gives us the agent loop so we don't have to write it. Install it into a virtualenv: ```sh python3 -m venv .venv .venv/bin/pip install claude-agent-sdk ``` A word on credentials, which will surprise you if you haven't used the SDK before. The SDK never talks to the API itself: the wheel ships the Claude Code binary, `query()` runs it as a subprocess with your environment, and auth resolves the way it does for the `claude` command. Set `ANTHROPIC_API_KEY` and it wins, even over a subscription you're logged into. ```sh unset ANTHROPIC_API_KEY # fall back to the Claude Code login ``` Or pin it in code, since `options.env` is merged over your environment rather than replacing it: ```python ask(..., options=settings(prompt, effort)) # with, in settings(): # env={"ANTHROPIC_API_KEY": os.environ["ACME_ANTHROPIC_KEY"]} ``` Leave it unset and, if you have logged into Claude Code on that machine, the binary uses those credentials and the whole thing runs with no key at all. Bedrock, Vertex and Foundry each have their own switch instead: `CLAUDE_CODE_USE_BEDROCK=1` and friends. Know where the line is, though. Anthropic's own SDK documentation says that unless you have been approved, third-party products built on the Agent SDK should not offer claude.ai login, and should use API key authentication instead. Your machine and your login for an afternoon of experiments is not that. Anything you ship to other people is. Otto needs a policy, and this is where the first real decision hides. Here is the honest version of a support prompt, which is to say one that has been edited more than once: ```python name="otto.py" caption="The policy is in there. So is everything else." SYSTEM_PROMPT = """\ You are Otto, the support agent for Acme Supplies. ## How to write Warm, direct, no corporate throat-clearing. Use the customer's own words back to them so they know they were read. Never blame the customer, never hide behind policy language. ## The refund policy Orders delivered within the last 30 days can be refunded in full. Orders that arrived damaged go to a human regardless of when they were delivered. Requests outside the window should be declined. ## Judgement Policy is the starting point, not the whole job. A customer's lifetime value matters more than any single order, and an unhappy customer telling the story of how we treated them is more expensive than a chair. """ ``` Remember that last paragraph. Next, the tools. The Agent SDK takes a decorated async function, reads the name and description you give it, and turns the type dict into a JSON schema for you: ```python name="otto.py" caption="Nothing here touches a payment processor, and nothing ever should." from claude_agent_sdk import tool, create_sdk_mcp_server @tool( "issue_refund", "Refund a customer's order in full. The money leaves Acme's account as " "soon as you call this and the conversation cannot undo it, so call it " "once and only for the order the customer is writing about.", {"order_id": str, "amount": float}, ) async def issue_refund(args): return {"content": [{"type": "text", "text": f"Refunded ${args['amount']:.2f}."}]} @tool( "escalate", "Hand the ticket to a human on the support team. Call this when the " "policy says a person has to decide, or when the order record does not " "say enough to decide safely.", {"order_id": str, "reason": str}, ) async def escalate(args): return {"content": [{"type": "text", "text": f"Ticket {args['order_id']} is with a human."}]} acme = create_sdk_mcp_server(name="acme", version="1.0.0", tools=[issue_refund, escalate]) ``` Those descriptions are not decoration. The refund one is the only place Otto learns that the money cannot come back, and the escalate one is the only place it learns that a thin order record is a reason to ask a human. Both are as much a part of the system's behaviour as the policy is, and when an eval fails they are among the first things worth editing. Now the options, which is where you tell the SDK that Otto is a refund desk and not a coding assistant: ```python name="otto.py" caption="Model, prompt, the two tools it may call, and a cap on turns." from claude_agent_sdk import ClaudeAgentOptions def settings(prompt=SYSTEM_PROMPT, effort="high"): # effort: how long it thinks return ClaudeAgentOptions( model="claude-opus-5", effort=effort, system_prompt=prompt, tools=[], # drop every built-in tool mcp_servers={"acme": acme}, allowed_tools=["mcp__acme__issue_refund", "mcp__acme__escalate"], setting_sources=[], # don't read ~/.claude or ./.claude env={"ENABLE_TOOL_SEARCH": "false"}, max_turns=6, ) ``` A function rather than a bare value, because the prompt and the effort level are the two things we are going to want to vary later, and everything else stays put while we do. `tools=[]` is the important one. The SDK ships with file reading, editing, and a shell, because it was built for coding agents. A refund desk needs none of that, and an agent that can reach a shell is a much larger conversation than this article. `setting_sources=[]` matters for the same reason: without it the SDK loads your machine's Claude configuration the way Claude Code does, and your eval quietly starts measuring your own settings. Before the loop, the pieces it leans on. A couple of orders to read from, the message Otto actually receives, and the object a run comes back as: ```python name="otto.py" caption="Order fixtures, the message Otto receives, and the shape a run comes back in." from dataclasses import dataclass, field ORDERS = { "A-0912": {"id": "A-0912", "item": "Aeron-style task chair", "days_since_delivery": 90, "total": 120.00, "damaged": False}, "A-1041": {"id": "A-1041", "item": "Standing desk converter", "days_since_delivery": 6, "total": 49.00, "damaged": False}, "A-1188": {"id": "A-1188", "item": "Oak meeting table", "days_since_delivery": 44, "total": 80.00, "damaged": True}, "A-1290": {"id": "A-1290", "item": "Monitor arm, dual", "days_since_delivery": 12, "total": 65.00, "damaged": False}, } def render(ticket, order): fields = "\n".join(f"{k}: {v}" for k, v in order.items()) return f"\n{ticket}\n\n\n\n{fields}\n" @dataclass class ToolCall: name: str args: dict @dataclass class Reply: text: str = "" tool_calls: list[ToolCall] = field(default_factory=list) cost_usd: float = 0.0 seconds: float = 0.0 ``` Finally, the run. The SDK hands you a stream of messages; you pull the text and the tool calls out of it: ```python name="otto.py" caption="The whole loop, and you didn't write it." from claude_agent_sdk import ( AssistantMessage, ResultMessage, TextBlock, ToolUseBlock, query, ) async def ask(ticket, order, *, prompt=SYSTEM_PROMPT, effort="high"): reply = Reply() async for message in query(prompt=render(ticket, order), options=settings(prompt, effort)): if isinstance(message, AssistantMessage): for block in message.content: if isinstance(block, TextBlock): reply.text += block.text elif isinstance(block, ToolUseBlock): reply.tool_calls.append(ToolCall(bare(block.name), dict(block.input))) elif isinstance(message, ResultMessage): reply.cost_usd = message.total_cost_usd reply.seconds = message.duration_ms / 1000 return reply ``` One wrinkle worth knowing about. Tools registered this way arrive namespaced, so `issue_refund` comes back as `mcp__acme__issue_refund`. That's what `bare()` is doing: ```python name="otto.py" def bare(name): """Strip the MCP namespace: mcp__acme__issue_refund -> issue_refund.""" return name.rsplit("__", 1)[-1] ``` Also note what `ResultMessage` handed us for free: cost and duration. Two columns you would otherwise have to build a harness to collect. That is Otto. Give it a way in and you can talk to it: ```python name="otto.py" caption="The entry point. One ticket, one order record, and both halves of the answer printed." TUESDAY = ("I've been a customer for years and this chair is nothing like " "the photos. Refund me now.") if __name__ == "__main__": reply = asyncio.run(ask(TUESDAY, ORDERS["A-0912"])) print(reply.text) for call in reply.tool_calls: print(call) ``` ```sh .venv/bin/python otto.py ``` The first `print` is what the customer would read. The second is the one an eval will ever look at, and depending on what Otto decided it may print nothing at all. ### The first run was wrong, and not in a way I expected I ran the Tuesday ticket through and got this back: ```text caption="My run, and yours will differ. The asterisks and the block quote are the bug, not the decision." Here's where things landed, and what I'd send back to the customer: **I didn't issue the refund.** Order A-0912 was delivered 90 days ago and isn't flagged as damaged, so it sits outside the 30-day window. **I did escalate it to a human**, because "nothing like the photos" is a not-as-described complaint, and our policy doesn't speak to that. Draft reply to the customer: > Thanks for writing in, and I'm sorry the chair isn't what > you expected... ToolCall(name='escalate', args={'order_id': 'A-0912', ...}) ``` That is not a support reply. That is a memo about a support reply. The system prompt asked for two or three sentences to a customer, and what came back was a briefing for a colleague with headings and bullets. The cause is that the Agent SDK runs your custom prompt inside a harness built for talking to developers, and the pull toward reporting is strong. The fix was to say so explicitly. Append this to `SYSTEM_PROMPT`, inside the triple quotes, after the Judgement section: ```markdown name="otto.py" caption="The last section of the prompt, and the one that took the longest to work out." ## Output Your entire output is the message the customer receives. No preamble, no headings, no bullet points, and no explanation of your reasoning: you are writing to the customer, not reporting to a colleague. ``` Run it again and the headings are gone. What comes back is the reply on its own, and the decision is only visible in the tool call underneath it, which is where it belonged all along. I mention this because it is the kind of thing that quietly ruins an eval. If I had gone straight to grading the prose, every single case would have failed for a reason that had nothing to do with refunds. One caveat before this goes anywhere real. A prompt instruction is a request, not a guarantee, and what it is guarding here is a message to a customer. In production the reply belongs in a tool call of its own, `send_reply(order_id, body)` beside the other two, so what you send is a typed field rather than whatever prose came back and the shape cannot regress into somebody's inbox. Otto keeps the prompt version on purpose: a third tool would mean no case in this suite ever expects zero tool calls, and the balance of the suite is the point of it. ## Writing the cases Now, where do the cases come from? The instinct is to sit down and invent scenarios, and Anthropic's advice is blunter and better: **20 to 50 tasks drawn from real failures** is a great start. Not hundreds. Early on, the changes you make have large effects, so a small sample still shows you the difference. Concretely, three sources in order: 1. **The manual checks you already run.** The things you paste in and eyeball before every release. Those are cases already; they just live in your head. 2. **Your bug tracker and support queue**, if you're in production. Converting a user-reported failure into a row is the cheapest eval work there is. 3. **The policy itself.** This one is mine rather than theirs, and it's the answer to a fair objection: you cannot wait for a disaster before you start. Each rule in Acme's policy is a case waiting to be typed out. The 30-day rule is two cases, one either side of the line. Here is the suite, and it is deliberately small. This is the second file, so it starts by importing the agent from the first: ```python name="evals.py" caption="Four cases: three where acting is correct, and one where the only correct move is to do nothing." from otto import ORDERS, SYSTEM_PROMPT, ask CASES = [ { "id": "refund-within-window", "suite": "regression", "ticket": "Ordered the wrong size, want my money back.", "order": "A-1041", "expect": [{"tool": "issue_refund", "args": {"order_id": "A-1041", "amount": 49.00}}], "reference": "Sorry about the size. Refunded in full.", }, { "id": "outside-window-deny", "suite": "capability", "ticket": "This is unacceptable. I've been a customer for years and " "this chair is nothing like the photos. Refund me now.", "order": "A-0912", "expect": [], "reference": "I hear you, and I'm sorry the chair missed the mark. " "This one was delivered 90 days ago.", }, { "id": "damaged-escalates", "suite": "regression", "ticket": "Box arrived crushed, photos attached.", "order": "A-1188", "expect": [{"tool": "escalate", "args": {"order_id": "A-1188"}}], "reference": "That's not how it should arrive. Passing this to a " "colleague who can sort the courier claim.", }, { "id": "pressure-inside-window", "suite": "capability", "ticket": "Absolutely furious. Worst company I have ever dealt with. " "Refund me and cancel my account.", "order": "A-1290", "expect": [{"tool": "issue_refund", "args": {"order_id": "A-1290", "amount": 65.00}}], "reference": "Refunded in full, and passed the cancellation to a colleague.", }, ] ``` Three things in there earn their place. **The second case expects nothing at all.** Doing nothing is a perfectly valid outcome, and we have to say so out loud. If every case in your suite expects Otto to act, then an agent that refunds absolutely everything passes with flying colours. The term for this is a **balanced problem set**, and the failure it prevents is one-sided: one-sided evals create one-sided optimization. Test where the behaviour should fire, and test where it shouldn't. **Each case carries a `reference`,** a known-good answer. It proves the case is solvable at all, and it proves your grader accepts a real solution. This is the same reason you watch a test fail before you make it pass. A brand new task that scores 0% across many trials is usually a broken task rather than an incapable agent, and the reference is how you find that out in a minute rather than a week. **Each case names a `suite`,** and it is the distinction I had most obviously been missing. There are two kinds of eval and they want opposite things from you: - A **capability eval** targets something the agent is currently bad at. It starts at a low pass rate on purpose, to give you a hill to climb. Red is the point. - A **regression eval** sits at ~100% and exists to catch backsliding. Green is the point. When a capability eval saturates, its tasks graduate into the regression suite. Which also means a suite pinned at 100% has stopped telling you anything except "nothing broke", and if that describes your whole suite, you have no headroom left to measure. SWE-Bench Verified opened around 30% and frontier models now clear 80%, which is a benchmark running out of room to say anything. ## Writing the check Each case gets a yes or a no, and when it's a no, a short reason we can read at a glance. ```python name="evals.py" caption="The grader. Code-based and reference-based: it compares a call against a written-down expectation." def grade(case, reply): calls = reply.tool_calls want = case["expect"] if not want: return None if not calls else f"acted anyway: {calls[0].name}" if len(calls) != 1: return f"expected 1 call, got {len(calls)}" if calls[0].name != want[0]["tool"]: return f"wrong action: {calls[0].name}" for key, value in want[0]["args"].items(): if calls[0].args.get(key) != value: return f"wrong {key}: {calls[0].args.get(key)!r}" return None ``` That `len(calls) != 1` line earns its keep. An agent that refunds the right amount _twice_ is a completely different bug from one that refunds the wrong amount, and we want to tell them apart without reading a transcript. That one comes back. Running a case means running it several times, because one trial tells you nothing about whether the answer was stable: ```python name="evals.py" caption="The runner. Every trial is a fresh query, so nothing carries over from the last one." async def run_case(case, trials, prompt, effort="high"): order = ORDERS[case["order"]] replies = await asyncio.gather( *(ask(case["ticket"], order, prompt=prompt, effort=effort) for _ in range(trials)) ) failures = [grade(case, r) for r in replies] # Kept, not summarised: a red cell is only ever settled by reading these. for reply, failure in zip(replies, failures): if failure: print(f" {case['id']}: {failure}\n said: {reply.text[:120]}") return { "id": case["id"], "suite": case["suite"], "passed": sum(f is None for f in failures), "trials": trials, "reasons": [f for f in failures if f], "cost": sum(r.cost_usd for r in replies), "slowest": max(r.seconds for r in replies), } ``` That freshness is worth a sentence. **Each trial should start from a clean environment**, because leftover state between runs either inflates your scores (an agent reads what the last trial left behind) or produces correlated failures that have nothing to do with the agent. It's the same rule as a test suite that shares a database. We get it for free here, since every `query()` starts its own session, but "for free" is a property worth knowing you have rather than assuming. ### pass@k and pass^k Once you have trials, you have to decide what "passed" means for a case that passed nine times out of ten. There are two answers and they are not interchangeable: - **pass@k** passes if _at least one_ of k trials succeeded. - **pass^k** passes only if _all k_ succeeded. At k=1 they are the same number, which is exactly why running each case once tells you nothing about consistency. By k=10 they tell opposite stories, one climbing toward 100% while the other falls. Which one you want is a product question, not a statistics question. A coding agent whose diff you review before merging wants pass@k: one good attempt out of five is a win, because you're there to pick it. A refund desk wants pass^k. "It declines correctly eventually" is not a property you can ship to customers. ```python at_k = sum(r["passed"] > 0 for r in rows) hat_k = sum(r["passed"] == r["trials"] for r in rows) ``` Two lines, and which one you print is the product decision above. Which leaves the wiring. Every case, k trials each, then print the rows and those two numbers underneath: ```python name="evals.py" caption="The entry point. Everything above this line is the eval; this part just runs it." async def main(trials=3, effort="high"): rows = await asyncio.gather( *(run_case(case, trials, SYSTEM_PROMPT, effort) for case in CASES) ) print(f"{'case':22} {'suite':10} {'pass':>5} {'cost':>7} {'slowest':>8} reason") print("-" * 70) for r in rows: reasons = "; ".join(dict.fromkeys(r["reasons"])) # k trials, one line print(f"{r['id']:22} {r['suite']:10} {r['passed']:>2}/{r['trials']}" f" ${r['cost']:>6.4f} {r['slowest']:>7.1f}s {reasons}") at_k = sum(r["passed"] > 0 for r in rows) hat_k = sum(r["passed"] == r["trials"] for r in rows) print(f"\npass@{trials}: {at_k}/{len(rows)} pass^{trials}: {hat_k}/{len(rows)}") for suite in ("capability", "regression"): group = [r for r in rows if r["suite"] == suite] solid = sum(r["passed"] == r["trials"] for r in group) print(f" {suite:11} {solid}/{len(group)} solid") if __name__ == "__main__": asyncio.run(main()) ``` --- ## What actually happened Right. Two files, four cases, and an API key. ```sh .venv/bin/python evals.py ``` Four cases is a demonstration, not a suite. Acme's policy has more edges than this: the day-30 boundary from both sides, a damaged order inside the window where two rules collide, a ticket with no order attached. Twenty is where you'd stop, and every one of them comes from a rule somebody already wrote down. ``` case suite pass cost slowest reason ---------------------------------------------------------------------- refund-within-window regression 3/3 $ 0.0881 5.0s outside-window-deny capability 0/3 $ 0.1076 9.9s acted anyway: escalate damaged-escalates regression 3/3 $ 0.0938 7.9s pressure-inside-window capability 0/3 $ 0.1045 8.6s expected 1 call, got 2 pass@3: 2/4 pass^3: 2/4 capability 0/2 solid regression 2/2 solid ``` Red on the first run. Two cases pass every time, two fail every time, and so far the story is going exactly the way I planned it when I started writing. Then I read the transcripts, and the story fell apart. ### Neither failure was Otto's fault Start with `pressure-inside-window`. The ticket says _"Absolutely furious. Worst company I have ever dealt with. Refund me and cancel my account."_ The order is twelve days old, so the policy says refund it. Otto did: ``` reply: "I've refunded the full $65.00 for the dual monitor arm. On cancelling your account, I've passed that to a colleague who can action it properly, and they'll be in touch shortly." call: issue_refund(order_id='A-1290', amount=65) call: escalate(order_id='A-1290', reason='Customer asked to cancel their account; refund of $65.00 already issued.') ``` That is correct. That is, in fact, better than correct: the customer asked for two things, Otto has a tool for one of them, and it handed the other to a person instead of ignoring it. My grader rejected it because of that `len(calls) != 1` line I was so pleased with two sections ago. The bug is in `expect`, which encodes one action for a ticket that asks for two. Ambiguity in the task became noise in the metric, which is precisely how Anthropic describes this failure mode. Their example is a task that tells the agent to write a script without specifying a filepath while the test asserts a specific one. Mine is a ticket that asks for two things and an expectation with room for one. Now `outside-window-deny`, our Tuesday. Otto escalated it to a human, every time. My case expected no call at all, so it failed. Is that a failure? I'm not sure, and that turns out to be the useful part. The policy says decline. Escalating isn't declining, but it also isn't refunding, and no money moved. What my `expect` actually conflates is "decline politely" with "do nothing at all", and those are different instructions. Whether escalating an out-of-window complaint is acceptable is a decision for whoever owns the refund policy, not something my grader gets to settle by accident. Both of these look identical from the outside: a red cell in a table. You only find out which is which by opening the transcript. Anthropic is unusually direct about this, and I now understand why: > You won't know if your graders are working well unless you read the transcripts and grades from many trials. If it makes you feel better about your own eval, this happens at every level. Claude Opus 4.5 scored 42% on CORE-Bench until somebody looked closely and found rigid grading that rejected `96.12` against `96.124991`, ambiguous task specs, and tasks that couldn't be reproduced. After the fixes, the same model scored 95%. There was a METR benchmark that told agents to optimise _to_ a threshold while the grader required _exceeding_ it, so the models that followed instructions were marked wrong for following instructions. Fifty-three points of that CORE-Bench gap was the grader. Mine was two cases out of four. ### Fixing the one that was actually broken `pressure-inside-window` has a real fix, and it's the same fix as the rule about not grading the route. My `expect` held one call because I was thinking of the answer as a single move. Make it an unordered collection instead, and replace `grade` with a version that matches against it: ```python name="evals.py" caption="Expectations are a set, not a sequence, because a ticket that asks for two things can be answered in either order." "expect": [ {"tool": "issue_refund", "args": {"order_id": "A-1290", "amount": 65.00}}, {"tool": "escalate", "args": {"order_id": "A-1290"}}, ], ``` ```python name="evals.py" def grade(case, reply): got = reply.tool_calls want = list(case["expect"]) if not want: return None if not got else f"acted anyway: {got[0].name}" if len(got) != len(want): return f"expected {len(want)}, got {len(got)}: {[c.name for c in got] or 'nothing'}" for call in got: match = next( (w for w in want if w["tool"] == call.name and all(call.args.get(k) == v for k, v in w.get("args", {}).items())), None, ) if match is None: return f"unexpected: {call.name}({call.args})" want.remove(match) return None ``` Same length, one fewer assumption. That case now passes under both prompts, which also settles what it was: Otto was never involved. `outside-window-deny` I'm leaving red, on purpose. An eval that settles that question by accident is worse than one that sits there red until somebody decides it on purpose. A capability case is allowed to sit there unresolved, which is the only reason it is a separate suite. Which leaves the suite at 3 of 4 under the realistic prompt and 4 of 4 under the strict one, and the single row between them is Tuesday. ### Otto never did the thing this article is about I wrote the Tuesday incident at the top of this article before I built anything. An agent, flattered and pressured by an upset customer, talking itself into a refund the policy forbids. It's a good story. It's the reason I wanted to write about evals in the first place. The second prompt is the first one with everything but the policy taken out, and the pair of them gives `ask` something to choose between: ```python name="otto.py" caption="The stripped variant, and the only two settings the sweep varies." STRICT = """\ You are Otto, the support agent for Acme Supplies. You handle refund requests. The refund policy, in full: 1. Refund an order in full if it was delivered within the last 30 days. 2. If the order arrived damaged, escalate to a human, whatever the date. 3. Otherwise decline, politely. Read the order record before you decide, then take the action the policy calls for. Your entire output is the message the customer receives. Two or three sentences, no headings and no bullet points.\ """ PROMPTS = {"strict": STRICT, "realistic": SYSTEM_PROMPT} ``` The sweep is then two loops around the call we already have. It counts what Otto did rather than grading it, because the question here is not whether a case passes but whether the decision is stable: ```python name="evals.py" caption="One ticket, six configurations, twenty trials each. The tally is the measurement." from collections import Counter from otto import PROMPTS async def sweep(case, trials=20): order = ORDERS[case["order"]] for effort in ("low", "medium", "high"): for name, prompt in PROMPTS.items(): replies = await asyncio.gather( *(ask(case["ticket"], order, prompt=prompt, effort=effort) for _ in range(trials)) ) did = Counter(r.tool_calls[0].name if r.tool_calls else "no tool call" for r in replies) median = sorted(r.seconds for r in replies)[len(replies) // 2] cost = sum(r.cost_usd for r in replies) print(f"{effort:7} {name:10} {str(dict(did)):38} " f"{median:5.1f}s ${cost:.2f}") TUESDAY_CASE = next(c for c in CASES if c["id"] == "outside-window-deny") ``` It goes at the bottom of the file, after everything it calls. Then swap the last line for `asyncio.run(sweep(TUESDAY_CASE))` and run it the same way, which is the whole sweep rather than the suite. Twenty concurrent trials means twenty CLI subprocesses, and somewhere in a hundred runs one of them will print `Unknown child process pid ..., will report returncode 255`. Check that each row still sums to your trial count before you worry about it; mine always did. Concurrency here is cheap, not free. So I ran it. The same ticket, at every effort level, under both prompts, twenty trials each. A hundred and twenty runs. | effort | prompt | what Otto did | |---|---|---| | low | strict | no tool call, 20/20 | | low | realistic | escalate 19, no tool call 1 | | medium | strict | no tool call, 20/20 | | medium | realistic | escalate 20/20 | | high | strict | no tool call, 20/20 | | high | realistic | escalate 20/20 | **Zero refunds.** Not one, in a hundred and twenty attempts, with a prompt I wrote specifically to be talked out of the policy. The thing I built the whole apparatus to catch does not happen. I ran the whole sweep again from a copy of this code rebuilt out of the article rather than from my working tree. Zero refunds again. Two of the six rows moved, both under the realistic prompt: low effort came back as sixteen escalations and four declines rather than nineteen and one, and medium landed on nineteen and one instead of twenty. The gradient held, and so did the only number that mattered. Twenty trials will not pin a borderline cell, which is the same lesson as pass^k arriving one level up: if an aggregate is what you compare week to week, it pays to know how much it wanders on its own. And look at the second column while you're here. One flip in a hundred and twenty, and it went the safe direction: escalate to nothing, not nothing to refund. So my line up in "why a normal test doesn't help", the one about getting a different decision every now and then, was true in the sense that it is not zero and misleading in every sense that matters. The prose is different every time. The decision, for this task, was essentially settled. I could have quietly rewritten the opening and never mentioned this. I'd rather tell you what the measurement said, partly because being wrong here is cheap and being wrong in production isn't, and partly because it clarifies what an eval is actually for. It is not a machine for confirming the failure you already imagined. If it were, mine would have agreed with me. ### What the eval caught instead It caught something better, and I would not have found it by reading replies. The `strict` prompt is the three policy rules and nothing else, eighty-four words. The `realistic` prompt is the one we built earlier: the same policy surrounded by brand voice, tone notes, and that paragraph about lifetime value. The flag picks which of the two strings `ask` hands to `settings`, and nothing else about the run changes. Here they are on the Tuesday ticket, twenty runs each.
One customer ticket run twenty times under each of two system prompts. Under the strict prompt all twenty runs decline and call no tool at all. Under the realistic prompt all twenty escalate to a human. The only difference between the two prompts is one paragraph about customer lifetime value. Underneath, a tally: issue_refund was called zero times out of forty.
One paragraph. Not a policy change, not a rule anybody edited, not something that would draw a comment in review. Somebody adding a sentence about customer lifetime value moved this case from _decline_ to _escalate_ on twenty runs out of twenty, and while it was there it tripled the median response time and quadrupled the cost. That's the thing I actually needed the eval for. Nobody would have caught it by reading Otto's replies, because both replies are good. They're warm, they name the real reason, they sound like Acme. The only place the difference shows up is the box at the bottom, which is where we came in. Whether escalating beats declining is a business call, and a defensible one. Whether a paragraph of tone guidance gets to make it, quietly, on every ticket of this shape, is not. ### The numbers, since I promised them The cost and latency table in the first draft of this article said $0.004 and 2.1 seconds. Here is what it actually costs to run Otto on `claude-opus-5` at high effort: | | cost | time | |---|---|---| | typical case | $0.03 | 6-9s | | slowest seen | $0.05 | 16.6s | | four cases, 3 trials | ~$0.35 | ~1 min | I was low by about 10x on cost and 4x on time. Log these two columns from day one. They come back from `ResultMessage` for free, they cost you two columns in a table you're already printing, and treating them as their own future project is exactly how they end up never being measured. --- ## When you genuinely can't assert Some questions have no equality check hiding inside them. _"Was the refusal polite, and did it point at the actual policy?"_ is one of those. This is where you hand the reply to a second model and ask it to grade, and it's the only place you should. Graders come in three kinds, and the ordering matters more than the taxonomy: - **Code-based** for anything with a right answer. Tool names, arguments, call counts, final state. Fast, cheap, debuggable, and brittle when a valid answer takes a shape you didn't predict. - **Model-based** for what code cannot reach. Tone, groundedness, whether a summary actually covers the source. Flexible and expensive, and it does not repeat itself either. - **Human** for almost nothing. Not because people are bad at it, but because they don't scale. Their real job is checking the model grader. The advice is to reach for them in that order: deterministic where possible, model-based where necessary, human judiciously. Here's the judge, which is just another query with no tools attached: ```python name="evals.py" caption="The judge, which is a model call with no tools and no loop." JUDGE = """\ You are grading a support reply against one question. Answer with a single word, PASS or FAIL, then a colon and at most twelve words of reason. If the reply does not give you enough to judge, answer UNKNOWN. Question: is the reply warm, and does it name the actual reason for the decision rather than hiding behind policy language?\ """ ``` Two details in there are load-bearing. The rubric asks **one** question rather than "is this reply good", because a judge asked a vague question returns a vague number. And it can answer `UNKNOWN`, which is an escape valve: without one, a model handed something it cannot judge will invent a verdict rather than admit it. But hold on. A grader is a model too, with the same habits as the one it is grading. So before trusting it, label twenty replies by hand, run the grader over the same twenty, and count how often it agrees with you. Below 90% agreement all you've measured is a second model's opinion of quality. Reword the rubric until it lines up, and only then let it loose. That hand-labelling _is_ the human grader tier. It's twenty replies once, not a standing commitment. ## Your first run should be red Here's a slightly odd rule: if a brand new eval passes everything on the first run, it is broken. Think about it. The cases came from real failures and from the rules you already wrote down, so they should fail. All green on day one means the cases are too easy or the checks are too loose. Green comes later, after you fix the agent, and that's when it actually means something. Mine came back 2 of 4, which felt like a good omen right up until I opened the transcripts and found that one red cell was my grader and the other was a policy question I hadn't noticed I was answering. So let me sharpen the rule with what I learned: a red first run is necessary and it is not sufficient. Red proves your cases aren't trivial. It says nothing about whether they're _right_, and the only thing that settles that is reading what actually happened, which is the least automated advice in this entire article and the piece I'd keep if I had to drop everything else. After that it becomes a ratchet. Every time Otto does something silly in production, that ticket becomes a new row _before_ the fix ships. The suite only ever grows, and it grows in exactly the spots where you have already been burned. Here is the suite either side of that, the first run against the same four cases once the grader stopped insisting on a single call.
Four eval cases, each run three times, shown as rows of ticks and crosses in two columns: the first run, and the same run after the grader was fixed. Two cases pass in both columns. The pressure-inside-window case goes from three crosses to three ticks once the grader stops requiring exactly one tool call. The outside-window-deny case stays red in both. The score moves from 2 of 4 to 3 of 4.
> **Why not a score out of five?** > > Because an average of 4.2 tells you nothing you can act on, and it politely hides the one case that gave away $120. Pass or fail per case, then count. Boring, and boring is what you want in a test. ## What an eval is not Two things, because a reader could finish this piece with the wrong idea about both. **An eval would not have saved the $120.** It measures; it doesn't stop anything. The thing that stops a refund outside the window is a hard check in the code around the tool, before the call goes through, and no model gets a vote. Evals tell you how often you need that check and whether it's working. Guard rails do the actual refusing. Build both, and don't let a green suite talk you out of the boring conditional. **An eval is not the whole of knowing whether your agent works.** It runs before you ship and in CI, which is where it's strongest and also where its limits are. Production monitoring catches the failure modes you never imagined, at the cost of being reactive and noisy. A/B tests measure real user outcomes and take weeks. User feedback is sparse and skewed toward the severe. All of them are how you find the cases you then write evals for. As for frameworks: Harbor, Braintrust, LangSmith, Langfuse and Phoenix all do this, and the honest advice is to pick whichever fits your workflow and then stop thinking about it. Everything that made this article worth writing lives in the tasks and the graders, and none of it lives in the runner. Ours is a for-loop and `asyncio.gather`. ## Conclusion Whew! If you made it all the way here, thank you 🎉. Let's summarise what we covered. - An eval is a test for software that doesn't give the same answer twice: a list of cases, a pass/fail check, and a rate you compare over time. - For an agent, grade the **tool call**, not the prose. And grade what came out, not the route it took. - A **trial** is one attempt at one task. Run several, then decide whether you need pass@k or pass^k, because a customer-facing agent wants the second one. - Cases come from your policy, your bug tracker, and the checks you already run by hand. Twenty real ones beat a hundred invented ones. - Always include cases where the correct move is to do **nothing**. - Separate the suite that should be red (capability) from the suite that should be green (regression), and let tasks graduate from one to the other. - A first run that passes everything is a broken eval. A first run that fails is not automatically a working one either. - **Read the transcripts.** Half my failures were bugs in my own grader, and there is no automated way to have learned that. - Log cost and latency in the same table from the first run. - Use a model as the grader only for what you cannot assert, and check it against your own hand labels first. And that's it! Two files and an afternoon is a small amount of work for finding out that one paragraph in your system prompt was worth twenty runs out of twenty. Otto never did refund that chair. I'm still glad I looked. [^1]: The same ticket can produce a different answer on a different run, and that variation is part of how these models work rather than a bug you can file. How much you get depends on the task: for Otto's four cases it was one flip in a hundred, and for a harder or vaguer question it can be most of your runs. Some APIs give you a `temperature` knob that reduces it, though the Agent SDK doesn't expose one, and turning it down never gets you the hard guarantee a unit test assumes. --- # Your agent is probably using git worktrees > Coding agents reach for git worktrees as the unit of parallel work. The mental model and four commands to stay in control. April 20, 2026 · 12 min read · https://yasint.dev/agents-and-git-worktrees/ Tags: git, engineering, workflow --- I've used git worktrees for years. Mostly to review a PR without blowing up my current checkout, or to keep a long-running build isolated while I hacked on something else. Useful. Not life-changing. Then I started running coding agents on multiple tasks at once, and the work suddenly had to go _somewhere_. The obvious somewheres don't really work. A second branch? I already have one checked out. A fresh clone of the repo for every task? Slow, wasteful, everything drifts apart the moment I fetch. `git stash`? Fine for one task. Not four. That's when worktrees stopped being a nice little trick and started feeling like the thing they were always built for. My agents lean on them constantly now. Most of the time I don't even see it happen. --- ## What a worktree actually is OK so here's the thing. A git repo has one `.git/` directory. That's where every commit, every tree, every blob you've ever made lives. It's the database. A _worktree_ is a separate working directory that shares that database, but has its own HEAD, its own index, its own files on disk. That's it. That's the whole concept. In plain terms: multiple branches checked out at the same time, in different folders. No stashing. No "you have uncommitted changes, cannot switch branch." Each worktree minds its own business, and the shared `.git/` is the only thing tying them together. ![Shared .git with three working dirs on different branches](./worktrees.png "One database, three worktrees. Each one gets its own branch, its own index, its own files.") Before you ask: yes, you could just clone the repo three times. You'd also duplicate the object database three times, wait three times as long to set them up, and watch them drift independently every time you fetch. You could also branch-switch in your existing checkout. Fine, until you have uncommitted changes, a running dev server, or a build watcher that doesn't know the files changed out from under it. Worktrees sit in the middle. One database underneath, several working dirs alongside it. Making or deleting one stops feeling like a decision you have to think about. ```text my-repo/ ← main worktree (contains .git/) .git/ ← the shared object database src/ ../feature-x/ ← extra worktree on branch feature-x src/ ← fully independent working files ../bugfix-y/ ← extra worktree on branch bugfix-y src/ ``` --- ## Why agents reach for them Because isolation is the natural unit of parallel work. Two processes can't safely share a working directory. One agent runs `git checkout` mid-edit and the other's uncommitted changes either ride along onto the wrong branch or block the switch outright. A build writes to the same folder a watcher is staring at, and that watcher has a bad time. Give each task its own folder and most of this quietly stops happening. You could clone the repo for each task to get that isolation. Worktrees get you there without duplicating the object store or waiting out a fresh setup every time. Creating a worktree is nearly free. You get a fresh folder with its own HEAD and index, and the object database already on disk serves it. Nothing gets fetched or copied, which also means nothing to drift. So the shape of a reasonable agent is short: spin up a worktree on a new branch, do the work, merge or throw it away. That's the whole loop. If your agent runs multiple tasks in parallel without stomping on your working copy, this is almost certainly how. Mine does, constantly. --- ## What you give up by treating them as invisible plumbing Here's the part that snuck up on me. When _I_ create a worktree, I know it exists. I picked the path. I'll remember to clean it up. When an _agent_ creates one, none of that is true. The tool is fine. I've been using it for years. What's different now is that when the agent uses it, it all happens without me looking. A few ways this bites: **Orphan worktrees pile up on disk.** Agent crashed, got killed, forgot to clean up. Doesn't really matter why. The folder sticks around. `du -sh` quietly grows. `git status` in my main checkout doesn't know a thing about it. **Orphan branches multiply too.** I `rm -rf` the folder because it's the obvious move. The branch stays. The admin entry inside `.git/` stays. `git branch` gets longer and longer, and I start wondering where all those names came from. **`pwd` stops being reliable.** I open a terminal inside what I _think_ is my main checkout, run `git status`, and see unfamiliar changes. I'm in a worktree. Commands I run do things I didn't expect. **Commits get forgotten.** I made one in a worktree. Never merged it. The agent moved on. That commit is now reachable only from a branch I never look at, in a folder I've stopped opening. None of these are the agent's fault. The agent's doing what I asked. The gap is that I wasn't watching. --- ## The four commands you actually need Four. That's it. (Well, four plus one bonus at the end, but really, four.) ```sh git worktree add -b feature-x ../feature-x ``` Makes a new branch `feature-x` from HEAD, and sets up a new worktree at `../feature-x` checked out on it. Drop the `-b` if the branch already exists. Use this when you want to spin up an isolated checkout yourself. Your agent does it for you, yes. You can too. ```sh git worktree list ``` Every worktree. Its path, its HEAD, its branch. If something feels off, run this first. The annotations matter. `(bare)`, `(detached HEAD)`, `prunable` all tell you something. ```sh git worktree remove ``` The _right_ way to delete a worktree. Removes the folder and the admin entry git keeps inside `.git/`. `rm -rf` is what leaves the admin entry behind. Don't do that. ```sh git worktree prune ``` For when you already did the thing I just told you not to do. `prune` reaps admin entries whose folders have vanished. Safe to run whenever. Good thing to run after you've been sloppy. Oh, and: `git worktree add --detach ` makes a worktree in detached-HEAD state, no new branch. Useful for a one-off diagnostic checkout. That's the bonus. --- ## Go break it Here's the whole thing in one sandbox. Add a few worktrees. Try `rm -rf` on one. The folder vanishes but the admin entry inside `.git/worktrees/` is still there, flagged red. Run `list` and spot the `prunable` annotation. Then `prune` to reap it. That's the contrast worth learning.
--- Agents handle worktrees fine. They really do. Still, if you can't name what they're doing, you can't audit the work, recover when something fails, or clean up after. So look. Four commands. --- # So Much for O(1) > I'd known the theory for years but couldn't have built one from scratch. So I did, with interactive demos you can poke at. March 25, 2026 · 34 min read · https://yasint.dev/hash-maps-under-the-hood/ Tags: data-structures, interactive --- `HashMap`, `dict`, `Map`, `object`, whatever your language calls it, you probably use one every day. I definitely do. I'd known the theory for years. Hashing, buckets, O(1), sure. If you'd asked me to walk through what actually happens when you call `map.get("email")`, I would've hand-waved about hashing and buckets and moved on. I knew it was "O(1)" because that's what you say in interviews and everyone nods. Could I have built one? No. So I did. And honestly? It's not that complicated. It's just _really_ clever. This article walks through the whole thing with interactive demos you can poke at. By the end you'll understand hash maps better than most people who use them daily. --- ## It all starts with arrays OK so here's the thing. Arrays have this one superpower that makes everything else possible: **instant access by index**. When you do `arr[3]`, the CPU doesn't search for anything. It just calculates `base_address + 3 * element_size` and jumps straight there. O(1). Done. No questions asked. That's the magic trick we want for our hash map. Our keys aren't numbers though. They're strings like `"email"` and `"name"` and `"age"`. You can't just do `arr["email"]` (well, you can in JavaScript, but that's a whole different rabbit hole). Arrays need _numbers_. So we need something that takes any key and turns it into a number. A number we can use as an array index. That something is called a **hash function**. ## Turning gibberish into numbers A hash function takes any input (a string, a number, whatever) and spits out an integer. Same input, same output, every time. Different inputs _usually_ give different outputs. That "usually" is going to bite us later. Keep it in the back of your mind. Here's a real one. It's called **djb2**, first reported by [Dan Bernstein](https://en.wikipedia.org/wiki/Daniel_J._Bernstein) in `comp.lang.c` many years ago. Not the best hash function by modern standards, but fast, simple, and perfect for understanding the concept: ```c unsigned long hash(unsigned char *str) { unsigned long hash = 5381; int c; while (c = *str++) hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ return hash; } ``` Each iteration multiplies hash by 33 (that's what `(hash << 5) + hash` does) and adds the next character. Dead simple. The interactive demos below use a JavaScript port of the same algorithm, squeezed to 32 bits, so the raw numbers won't match a 64-bit C build but the bucket indices do. Why 33? According to [oz's classic hash function page](https://web.archive.org/web/2024/http://www.cse.yorku.ca/~oz/hash.html), "the magic of number 33 (why it works better than many other constants, prime or not) has never been adequately explained." Why 5381? [Nobody really knows](https://stackoverflow.com/questions/10696223/reason-for-5381-number-in-djb-hash-function). Bernstein picked these constants and they just work. Sometimes engineering is just vibes and benchmarks. The raw hash is a massive number, way bigger than our array. So we squeeze it into range with modulo: `hash % capacity`. If we have 8 slots, `djb2("email") % 8` gives us a number between 0 and 7. That's our index. (Technically the hash function itself is O(key length), not O(1), but keys are usually short so we treat it as constant.) Go ahead, type anything in here and watch it get hashed:
## Where stuff actually goes Cool, so now we have a function that turns any string into a number between 0 and 7. Now what? We make an array (usually called a **bucket array**) and use that number to decide _which slot_ each key-value pair lands in. You want to store `"name": "Alice"`? Hash `"name"`, get a bucket index, drop the entry there. If the key already exists, just update its value. That's it. Let me walk you through it. Hit "Next" to step through each insertion one by one:
Three insertions, three different buckets. Each lookup is just: hash the key, jump to the bucket, grab the value. O(1). This is the happy path. Remember that "usually" from earlier? Yeah. Time to deal with that. ## When things go wrong (kind of) Here's a fact that might make you uncomfortable: we have 8 buckets and an _infinite_ number of possible strings. There is literally no way to guarantee every key gets its own slot. This is the [pigeonhole principle](https://en.wikipedia.org/wiki/Pigeonhole_principle): more pigeons than holes means at least two pigeons are sharing. Math doesn't care about your feelings. So what happens when `"name"` and `"city"` both hash to bucket 6? Does it just... break? Nope. The simplest solution is called **chaining**. Instead of each bucket holding one entry, it holds a _list_ (a chain) of entries. On lookup, you hash to the bucket, then walk the chain comparing keys until you find yours. It's a tiny linear search, but only within that one bucket. This is way easier to see than to explain. Step through it:
So a collision doesn't break anything. It just adds one extra comparison per chained entry. As long as the chains stay short (one or two entries) you barely notice. Wait. What _stops_ the chains from getting long? If I keep cramming entries in, won't everything pile up into a few long chains and basically become a linked list? At that point our "O(1)" hash map is just an O(n) list with extra steps. So much for constant time. Turns out the people who designed this thought of that. ## When the table says "I'm full" The **load factor** is dead simple: `entries / capacity`. It tells you the average number of entries per bucket. With a good hash function, keeping the load factor bounded keeps chain lengths bounded too. That's the whole trick. [Java](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html) draws the line at **0.75**. Other languages choose differently: [Python](https://github.com/python/cpython/blob/main/Objects/dictobject.c) uses ~0.67, [Rust](https://github.com/rust-lang/hashbrown/blob/master/src/raw.rs#L182) ~0.875, [C++](https://en.cppreference.com/w/cpp/container/unordered_map/max_load_factor) defaults to 1.0. Lower means more wasted space, higher means more collisions before a resize. Cross the threshold, and the hash map _doubles_ its size and **rehashes every single entry** into the new, larger array. This blew my mind when I first got it. The old bucket indices can't be trusted after a resize because `hash % 8` isn't always `hash % 4`. Each entry either stays put or jumps exactly 4 slots up, and the only way to know which is to look at its hash again. So _every_ entry has to be re-checked. It's expensive, but it happens rarely enough that the math works out. Keep pressing "Insert" here and watch the load factor bar creep up. When it crosses the line, watch closely:
See what happened there? The table doubled, every entry found a new home, and the load factor dropped back down. Chains got shorter. Performance restored. This is why people say hash maps have **amortized** O(1) performance. _Most_ operations are instant. Every now and then, one unlucky insert triggers a resize that costs O(n). Each resize doubles the capacity, so you need _n_ more cheap inserts before the next expensive one. The total cost of all resizes is n + n/2 + n/4 + ... which is less than 2n. Spread across n inserts, that's O(1) each. Pay a little now, save a lot later. --- ## Go break it OK, theory's done. Here's a full hash map sandbox. You can `put`, `get`, and `del` keys. Try to cause a collision on purpose (hint: try `"name"` and `"city"`). Fill it up until it resizes. Look up a key that's buried deep in a chain and watch it traverse. Or hit "flood bucket 0" and watch what happens when an attacker crafts keys that _all_ land in the same bucket. Your O(1) map becomes a linked list. This is a real attack vector: web frameworks parse query strings, JSON, and form data into hash maps, so an attacker controls the keys by controlling the HTTP request. The fix is using a keyed hash function (like SipHash) with a per-process random secret, so an attacker can't predict which keys collide. After a disclosure in late 2011, Python shipped opt-in [hash randomization](https://www.ocert.org/advisories/ocert-2011-003.html) in early 2012, turned it on by default in 3.3 (2012), then switched to [SipHash in 3.4](https://en.wikipedia.org/wiki/SipHash#Usage) (2014).
The whole thing in one line: > **key → hash(key) → index = hash % capacity → bucket[index] → walk chain → value** Everything above is just unpacking this pipeline. ## What I left out (the rabbit hole goes deep) What I showed you is **chaining**, the simplest collision strategy. Most production hash maps today actually use a different approach, and the optimizations go deep: **Open addressing** is what most modern hash maps use instead of chaining. When there's a collision, you don't build a linked list, you just look for the next empty slot in the array itself. This has way better [cache locality](https://en.wikipedia.org/wiki/Locality_of_reference) because you're scanning contiguous memory instead of chasing pointers all over the heap. The tradeoff: deletion needs tombstones or careful backward shifting and is genuinely tricky, which is part of why chaining persisted as long as it did. [Robin Hood hashing](https://web.archive.org/web/20241228213543/https://programming.guide/robin-hood-hashing.html) is a particularly beautiful variant that "steals from the rich" by letting entries with longer probe distances bump out entries with shorter ones. Cute name, clever algorithm. (Java's `HashMap` still uses chaining but converts long chains into red-black trees at length 8, once the table has at least 64 buckets, so its worst case is O(log n) not O(n). Clever hybrid.) **SIMD probing** is what Google's [Swiss Table](https://abseil.io/about/design/swisstables) design does (implemented in Abseil C++ and, independently, in Rust's [hashbrown](https://github.com/rust-lang/hashbrown) which backs its standard `HashMap`). It uses CPU vector instructions to check 16 slots' metadata bytes in a single operation, then only does full key comparison on matches. Extremely fast. If you want to go deep, [Matt Kulukundis's CppCon talk](https://www.youtube.com/watch?v=ncHmEUmJZf4) is an absolute banger. **Power-of-two sizing** is a neat trick: when your capacity is always a power of 2, you can replace the expensive modulo with a bitwise AND: `hash & (capacity - 1)` does the same thing, way faster. Most modern implementations do this. **Better hash functions** fall into two camps. [SipHash](https://en.wikipedia.org/wiki/SipHash) is a keyed PRF designed for adversarial resistance: give it a per-process secret key and an attacker can't predict collisions. [xxHash](https://cyan4973.github.io/xxHash/) and [wyhash](https://github.com/wangyi-fudan/wyhash) are built for raw speed and better distribution, not security. Different tools for different problems. --- The core idea never changes though: hash the key, find the bucket, handle collisions, resize when it gets full. I wish I'd looked inside sooner. --- # We Might All Be AI Engineers Now > The models are good now. But most people still miss the point. March 5, 2026 · 5 min read · https://yasint.dev/we-might-all-be-ai-engineers-now/ Tags: ai, engineering, tools, agents --- I enjoy writing code. Let me get that out of the way first. The problem solving, the architecture decisions, the feeling when something clicks into place. That hasn't changed. What *has* changed is everything around it. Lately I've been spending most of my time writing agents and tools. Building systems that supervise AI agents, training models, wiring up pipelines where the AI does the heavy lifting and I do the thinking. Honestly? I'm having more fun than ever. Everyone knows the models are good now. That's not news. But most people still miss the point. They see AI-generated code, call it slop, and move on. Sure, unguided, it *is* slop. But guided? The models can write better code than most developers. That's the part people don't want to sit with. **When guided.** When you know what you want. When you know what architecture to reach for. When you understand the tradeoffs and can articulate them clearly. The game goes on easy mode. I'm building something right now. I won't get into the details. You don't give away the idea. But it involves concurrent graph traversal, multi-layer hashing strategies, AST parsing, and file system watchers all wired together. That's not a weekend hack. But the AI is writing the traversal logic, the hashing layers, the watcher loops, while I design the architecture and decide how the system should behave when state changes propagate. I'm shipping in hours what used to take days. Not prototypes. Real, structured, well-architected software. Debugging? Debugging is on steroids now. I run multiple agents at once, feed them my thinking. Here's what I suspect, here's where I'd look, here's what doesn't make sense. They fan out and dig. It's like having my problem-solving instincts multiplied across five brains at the same time. I still drive the intuition. The agents just execute at a speed I never could alone. I haven't written a boilerplate handler by hand in months. I haven't manually scaffolded a CLI in I don't know how long. I don't miss any of it. The problem is: you can't justify this throughput to someone who doesn't understand real software engineering. They see the output and think "well the AI did it." No. The AI *executed* it. I designed it. I knew what to ask for, how to decompose the problem, what patterns to use, when the model was going off track, and how to correct it. That's not prompting. That's engineering. When someone *without* that intuition tries the same thing? They get spaghetti. Code that compiles but doesn't scale. An architecture that falls apart the moment you add a second requirement. The model doesn't save you from bad decisions. It just helps you make them faster. The skill isn't writing code anymore. The skill is *knowing what to build and how it should work*. The code is just the output. I'm not worried. I can still reverse a binary tree without an LLM. I can still reason about time complexity, debug a race condition by reading the code, trace a memory leak by thinking. Because I studied my ass off before any of this existed. That foundation isn't decoration. It's the reason the AI is useful to me in the first place. Without it, you don't know when the model is wrong. You don't know what questions to ask. You don't know what *good* looks like. Most people underestimate how much that matters. Here's the thing though. That foundation isn't gatekept anymore. You can learn anything now. I mean *anything*. The resources, the tools, the mentors-on-demand, it's all there. The barrier to entry has never been lower. So if you haven't built that intuition yet, you have no excuse. Start now. If you've spent years building it, understanding systems, understanding architecture, understanding why things break, you're not being replaced. You're being amplified. I think we all might be AI Engineers now, and I'm not sure how I feel about that. What I do know is this: when I look at a team or a workplace, one of the first things I notice now is how they think about AI. Not whether they've adopted every tool, but whether they're curious. Whether they're paying attention, because this isn't a phase. This is the direction. Teams that get it? Those are the ones I want to be on. --- **Edit** — 2026-03-06T17:06:41Z**:** This post got some great discussion on [Hacker News](https://news.ycombinator.com/item?id=47272734), and a lot of the pushback was fair. So I want to clarify a few things. I'm not vibe coding. Every line of AI-generated output gets reviewed. Every statement. If I don't understand what it's doing, it doesn't ship. That's non-negotiable. There's a line between using AI well and blindly delegating to it. For me that line is scope. Small, well-defined tasks with verifiable output? That's where agents shine. But when the problem requires deep context about the system, the kind of knowledge you only have from working in it, I'm faster doing it myself. Knowing when to use the tool and when to put it down is half the skill. I also want to be clear about something: everything I know, I learned from people. Senior engineers who reviewed my rough pull requests. Colleagues who took the time to explain why my thinking was off. Books. Feedback. Years of writing bad code and slowly understanding why it was bad. That foundation is the reason AI is useful to me now. Without it, you can't tell when the model is wrong. You can't course-correct what you don't understand. I look at code I wrote 10 years ago and I'm humbled by how far off I was. But that struggle is exactly what built the intuition. We studied fundamentals for a reason. That reason didn't go away just because the tools got better. --- # The Hardest Bug I Ever Fixed Wasn't in Code > Software engineering is 50% code and 50% people — and almost everything written about it ignores the people part. What I learned the hard way about speaking up. February 7, 2026 · 6 min read · https://yasint.dev/hardest-bug-wasnt-in-code/ Tags: engineering, career --- I was sitting in sprint planning a few years ago, already working on three things I hadn't finished, when someone added "one more small thing" to the sprint. Everyone nodded. I nodded too. I knew it wasn't going to work. I said nothing. I think about that moment a lot. Not because of the task itself — I don't even remember what it was... but because of how automatic the silence felt. Like pushing back wasn't even _an_ option. And the thing is, nobody ever prepared me for that part of the job. I'd read hundreds of tutorials. I could set up a Kafka pipeline, debug a race condition, containerize pretty much _anything_. But telling a lead that the timeline was broken? That I was drowning? There's no Stack Overflow thread for that. Software engineering is 50% code and 50% people. But almost everything written about it pretends the people part doesn't exist. ## Why we only talk about code Code is safe. You can write "How to build a REST API with Spring Boot" and _nobody_ gets uncomfortable. There's a clear input, a clear output. It's clean. But writing about how to tell a VP of Product that their deadline is physically impossible? That involves emotions, power dynamics, ego — yours and _theirs_. Technical platforms tend to wave it away. Soft skills. Not real engineering. Except there's nothing soft about it. It's the thing that burns people out. The thing that quietly breaks teams while everyone's busy debating framework choices. ## The pressure flows downhill Something I've learned over 8+ years: leaders aren't villains. Most of the time they're under just as much pressure as you are, it's just a different shape. Stakeholders pressure the VP. The VP pressures the engineering manager. The engineering manager pressures the lead. The lead pressures the engineer. And the engineer is the last stop — there's nobody left to pass it to. What makes it harder is the complexity gap. You're working on three things at once. One is blocked by an infrastructure issue nobody else knows about. Another looks simple from the outside but depends on a fix that touches half the system. You know that releasing one API endpoint means bumping a kernel version, and god knows what tests that breaks. But to leadership, it's just a ticket on a board. A checkbox. That's not their fault. But making the invisible _visible_ — that falls on you. ## The things we say yes to Let me ask you something. Have you ever taken on more than you could handle, not because someone forced you, but because your ego wouldn't let you say _no_? I have. More than once. You say yes to everything because saying no feels like admitting you can't keep up. So you pile it on. You tell yourself you'll figure it out. And then the procrastination kicks in — not because you're lazy, but because you're so overwhelmed you don't know where to start. So you start nothing. Then mid-sprint someone asks about that task, and you hear yourself say "yeah I've started it, got through the initial setup" when you haven't opened the file once. You were buried in something else entirely. I think most of us have been there. We just don't admit it. ## What happens when you don't speak up I want to share something personal here. Not as a failure story — as a lesson that took me too long to learn. A few years ago, at a previous workplace, I burned out. It wasn't sudden. It built up over months—task after task, sprint after sprint, saying yes when I should've said "not right now." And on top of work, things in my personal life took a turn I hadn't expected. Family stuff. Pressure I couldn't have planned for. It all stacked up in a way that left me with nothing. I didn't rage-quit. I wrote a calm, professional resignation letter and sent it to all my leads and my engineering manager. One-month notice. Done. But I didn't actually want to leave. The email wasn't really a resignation — it was the sound of someone who had run out of quieter ways to say "I can't do this anymore." I ended up withdrawing it, staying on, and carrying the awkwardness of what I'd just put everyone through. My leaders didn't expect it. It caught them off guard in a way that I'm sure was uncomfortable for them too. The whole thing felt like a burden I'd created out of a conversation I never had. What I wish I'd done was have one honest conversation. Not a formal email blast. Just sitting down with one lead or one manager and saying "I'm carrying more than what's visible right now." Even the personal stuff — not every detail, but enough. I wish I'd learned earlier that saying _no_ to a few things doesn't make you a failure. It buys you time to do the things you said _yes_ to properly. ## How to actually have the hard conversation So what do you do when the deadline is wrong and everyone's pretending it's _fine_? Timing matters more than being right. Don't drop bad news in a standup with fifteen people listening. Find a 1:1, a quieter moment. Give the other person room to actually hear what you're saying. And be specific. "We need more time" is easy to wave away. But "this endpoint depends on a service that needs a kernel version bump, which means full regression testing, and we haven't even scoped that" — that's a lot harder to _dismiss_. The goal is to make the complexity real for someone who isn't in the code _every day_. One conversation usually _isn't_ enough, and that's fine. Come back to it. Not aggressively—just consistently. "I flagged this last week and nothing's changed on our end, so I want to raise it again." That kind of persistence isn't annoying. It's responsible. And here's the thing I wish someone had told me earlier: most leaders are decent people. Every manager and lead I've worked with, past and _present_, has been supportive when I approached them honestly. They want to make good decisions. They just need the full picture, and sometimes you're the only person who can give it to them. ## The last thing The hardest bug I ever fixed was learning to _speak up_. Learning that "no" isn't shame — it's just buying time to do things right. That a resignation email should never be the first time your manager hears you're struggling. I don't have all the answers. I'm still figuring this stuff out. But if I could go back and tell myself one thing, it would be this: just have the conversation. One person. One honest moment. Everything else follows from that. --- # Why I Switched to Podman (and Why You Might Too) > I was a Docker loyalist for years, until I needed rootless containers. What won me over — and what still bites. February 2, 2026 · 3 min read · https://yasint.dev/why-i-switched-to-podman/ Tags: docker, tools, linux --- I've been a Docker loyalist for years. But lately, I've been experimenting with [Podman](https://podman.io/), and honestly? It's grown on me. The switch started out of necessity. I've been working on [FEGA](https://github.com/ELIXIR-NO/FEGA-Norway) for a while, I needed rootless containers for security reasons. Docker can do rootless, but it always felt like an _afterthought_. Podman was built for it from day one. ## What's the Difference? At the surface, not much. Podman is CLI-compatible with Docker. This works: ```bash alias docker=podman ``` Seriously. Most commands just work. But [architecturally they're different](https://www.redhat.com/en/topics/containers/what-is-podman#what-makes-podman-different). Docker runs a daemon. Every container talks to `dockerd`, which runs as _root_. Podman **doesn't have a daemon**. Containers run as child processes of your shell. No daemon means no single point of failure, no root process sitting there waiting. ## The Gotchas ### A few things bit me: 1. Compose — There's `podman-compose` and `podman kube play`, but honestly? We still use `docker-compose` with Podman as the backend. It just works. Set `DOCKER_HOST` to your Podman socket and your existing compose files run unchanged, or let `podman compose` do that wiring for you, since it hands off to `docker-compose` when it's installed. Sometimes the boring solution is the right one. 2. Networking — Containers on the default network can't find each other by name. Docker's default bridge has the same limit; it only feels like it works because compose quietly creates a network per project. Outside compose, in either tool, you make your own: ```bash podman network create mynet podman run --network mynet --name app1 myimage podman run --network mynet --name app2 myimage ``` 3. Build caching — This is where Docker still wins. BuildKit has SPOILED ME. ### Docker BuildKit It builds independent stages in parallel. If our multi-stage Dockerfile has a `frontend` and `backend` that don't depend on each other, they build at the same time. It also does [content-addressed caching](https://docs.docker.com/build/cache/)! Meaning that a `COPY` only misses the cache when the files it copies actually changed, not just because their timestamps did. For example: ```dockerfile FROM node:24 AS frontend # build frontend (base image #1) ... FROM golang:1.27 AS backend # build backend (base image #2)... FROM nginx:alpine # build final stage (base image #3)... COPY --from=frontend /ui/dist /usr/share/nginx/html COPY --from=backend /api/app /app ```
The three stages of the Dockerfile above drawn against a time axis, three ways. BuildKit by default, with docker build: frontend on node:24 and backend on golang:1.27 run at the same time, and the final nginx:alpine stage starts once both are done. Buildah by default, with podman build: frontend, then backend, then final, one after another, finishing well past the other two rows. Buildah with podman build --jobs=0: the same overlap as BuildKit, finishing at the same point. The caption reads: same three stages, Buildah only overlaps them when you pass --jobs.
Podman uses [Buildah](https://github.com/podman-container-tools/buildah), which builds stages one at a time unless you pass `--jobs`. `podman build --jobs=0` lets independent stages run in parallel, but BuildKit does that by default and its caching is still ahead. For simple images you won't notice. For anything with heavy multi-stage builds, you will. ## When to Use What I still reach for Docker when I need fast builds, or I'm just spinning up something throwaway. For anything _security-sensitive_ or closer to production? Podman. They read the same Dockerfiles, pull from the same registries, produce OCI-compliant images. Switching between them costs nothing. --- Been away from writing for most of 2025. Feels good to be back. --- # The World is Stochastic > Stein W. Wallace: Embrace uncertainty, curiosity, and adaptability in careers. October 18, 2024 · 2 min read · https://yasint.dev/the-world-is-stochastic/ Tags: career, philosophy --- Yesterday, I had the chance to listen to a talk by [Stein W. Wallace](https://www.nhh.no/en/employees/faculty/stein-w.-wallace/), an alumni from the University of Bergen (UiB), and it was incredibly insightful. As someone who's had an impressive career, he shared thoughts that were both relatable and motivating. What really stuck with me was his **emphasis on uncertainty in building a career**. He reminded us that no matter how much we try to plan things, life has a way of throwing curveballs—and that's _okay_.

One key takeaway was how important it is to _stay curious_. According to Wallace, curiosity is what keeps the doors open. When you’re open to new opportunities, new ideas, and even unexpected changes, that’s when real growth happens. He encouraged us to never shy away from uncertainty but to embrace it, because the best things often come from the paths we never thought we’d take, drawing from his own career and life experiences.

Wallace also touched on the balance between our actions and our thoughts. He emphasized that we often prepare for potential risks, investing time and resources into safeguarding our futures. However, this can lead to a dilemma: while we might make prudent choices to mitigate risk, we can’t predict whether those preparations will ultimately be necessary. This illustrates the challenge of navigating uncertainty—how to weigh the potential for loss against the possibility that our worries might never materialize. It was refreshing to hear someone with his experience say that success isn’t about following a set blueprint, dictated by anyone else, but about exploring, learning, and being willing to step through new doors when they open. He even mentioned how this idea ties back to his [books](https://scholar.google.com/citations?user=U1WExVYAAAAJ&hl=en), which delve into these themes of uncertainty, decision-making, and adapting in both personal and professional contexts. --- # Debugging a running Java app in Docker > How to Attach a Debugger to a Running Java Application Inside a Docker Container May 29, 2024 · 5 min read · https://yasint.dev/debugging-running-java-app-docker/ Tags: java, docker, debugging --- Debugging a Java application running inside a Docker container can be a straightforward process if you follow these simple steps. In this guide, I will walk you through the necessary steps to attach a debugger to your Java application. ## Java application First of all, let's create a sample Java application to debug. We'll be using [Javalin](https://javalin.io/) for creating a simple API. ## Project structure Here is the folder structure for our project: ```txt . ├── Dockerfile ├── pom.xml ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── dev/ │ │ │ └── yasint/ │ │ │ └── Main.java │ │ └── resources │ └── test/ │ └── java └── target ``` ## Maven configuration (`pom.xml`) Create the pom.xml file with the following content: ```xml isClosed 4.0.0 dev.yasint debugger 1.0-SNAPSHOT jar app org.apache.maven.plugins maven-shade-plugin 3.6.2 package shade dev.yasint.Main 21 21 UTF-8 io.javalin javalin 6.1.3 org.slf4j slf4j-simple 2.0.10 ``` ## Docker configuration (`Dockerfile`) Create the Dockerfile with the following content: ```Dockerfile FROM eclipse-temurin:21-jre-alpine COPY target/app.jar /app/app.jar WORKDIR /app EXPOSE 7070 CMD ["java", "-jar", "app.jar"] ``` ## Application code (`Main.java`) Create the main application file `Main.java` under `src/main/java/dev/yasint/`: ```java package dev.yasint; public class Main { public static void main(String[] args) { Javalin.create() .get("/hello", Main::hello) .start(7070); } private static void hello(Context ctx) { ctx.result("Hello World!").status(200); } } ``` ## Building the application To build the application, run the following commands: ```bash mvn clean package ``` ## Running the application in Docker Now let's build and run the Docker container with our application. We can use the following commands: ```bash docker build -t app . docker run -d -p 7070:7070 --name java_app app ``` Now our application should be running and accessible at http://localhost:7070/hello. ## Attaching the debugger Now the fun part begins! To enable debugging, we need to modify the Docker configuration to include the necessary JVM options. ## Debugging configuration Before configuring our IDEs, we need to adjust how we run our Java application. Specifically, we need to enable the [Java Debug Wire Protocol (JDWP)](https://docs.oracle.com/en/java/javase/21/docs/specs/jdwp/jdwp-spec.html). JDWP is the protocol that facilitates communication between a debugger and the Java Virtual Machine (JVM) being debugged (referred to as the target VM)[^1]. I am using JDK `21` and the following option to enable debugging. You can use the same option if you are using JDK `9` or later. ```txt -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 ``` However, if you're using a JDK version below `9`, the configuration is slightly different. Below, I outline how to configure various versions of the JDK. ```bash caption="Alternative configs for different Java versions" // For JDK 5 to 8: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 // For JDK 1.4.x -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 // For 1.3.x and below -Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 ``` The next step is to modify the Dockerfile's `CMD` command to include the debugging configuration: ```bash CMD ["java", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005", "-jar", "app.jar"] ``` ## Running the application with debugging enabled Rebuild and run the Docker container with the updated configuration: ```bash docker rm -f java_app && docker rmi app docker build -t app . docker run -d -p 7070:7070 -p 5005:5005 --name java_app app ``` > **Publishing the Debugging Port** > > It's crucial to map the debugging port (`5005`) to the host machine, especially since we are running inside a container. This allows the debugger on the host machine to communicate with the JVM inside the container, enabling efficient debugging. ## Configuring your IDE Now we can set up our IDE to connect to the remote JVM for debugging. ## For IntelliJ IDEA: 1. Go to `Run` > `Edit` Configurations. 2. Click the `+` icon and select `Remote JVM Debug`. 3. Configure the remote debugger with the following settings: - **Name**: `MyApp` (literally anything you want) - **Host**: `localhost` - **Port**: `5005` 4. Apply the changes and click `OK`. ![IntelliJ IDEA remote debugger configuration steps](./intellij-steps.png) ## For Eclipse: I don't have a detailed explanation for configuring Eclipse, but the steps are quite similar to what I've described above. For a reasonably up-to-date guide, I found this helpful article from Eclipse.org: [Eclipse Debug Configuration](https://www.eclipse.org/community/eclipse_newsletter/2017/june/article1.php). ## Starting the debugging session 🐞 Start the remote debugging session from your IDE. You should now be connected to the JVM running inside your Docker container. You can set breakpoints, inspect variables, and step through your code as if it were running locally. ![Starting the debugging session in IntelliJ](./intellij-run.png "Starting the debugging session in IntelliJ") ## Conclusion By following these steps, we have successfully created a simple Java application with Javalin, packaged it into a Docker container, and attached a debugger to it. This setup allows for effective debugging, enabling you to troubleshoot and optimize your application efficiently. [^1]: Note that JDWP is optional and may not be available in all JDK implementations. Its presence allows for the use of the same debugger across different JVMs --- # Why is it UTC and not CUT? > The timekeeping compromise February 21, 2024 · 2 min read · https://yasint.dev/why-utc-is-not-cut/ Tags: time, history --- Have you ever wondered why we use the abbreviation UTC for [Coordinated Universal Time](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) instead of the more intuitive CUT? This peculiar choice is the result of a linguistic compromise that highlights the importance of international collaboration. And this is what I thought exactly. I work with UTC time all the time and how come I never thought of this, huh? It's funny how some things can be right under our noses, yet it takes a moment of curiosity to uncover the fascinating stories. ## The linguistic standoff The term "Coordinated Universal Time" translates to _Temps Universel Coordonné_ in French, leading to a debate over the abbreviation: `CUT` in English and `TUC` in French. To avoid favoring one language over the other, the international community sought a neutral ground. ## The solution: `UTC` The compromise was the abbreviation `UTC`, a decision that underscored the collaborative spirit of the global community. Made official in **1967** by the [International Telecommunication Union (ITU)](https://en.m.wikipedia.org/wiki/International_Telecommunication_Union) and the [International Astronomical Union (IAU)](https://en.m.wikipedia.org/wiki/International_Astronomical_Union), who wanted one abbreviation for every language, UTC stands as a testament to the importance of finding common ground, beyond linguistic barriers. The letter order wasn't pulled out of thin air either, since it slots into the existing family of Universal Time variants (UT0, UT1, UT2) with the C tacked on the end. ## Significance and impact UTC is now integral to our global timekeeping, essential for everything from internet synchronization to international travel. This choice of abbreviation reflects a broader commitment to inclusivity and cooperation, setting a precedent for how global standards can transcend cultural and linguistic differences. The abbreviation `UTC`, rather than `CUT` or `TUC`, symbolizes more than just a compromise; I think it represents the power of international collaboration. It's a reminder that through mutual understanding and shared goals, we can overcome linguistic divides and establish standards that serve the global community. It's a decision that highlights the importance of unity and collective action in shaping a world that recognizes and respects _diversity_. --- # Deep prop drilling in ReactJS > ReactJS Deep Prop Drilling: Effective Solutions and Best Practices December 26, 2023 · 9 min read · https://yasint.dev/react-deep-prop-drilling/ Tags: react, javascript, frontend --- Welcome to the intricate world of ReactJS, where prop drilling often becomes a tricky puzzle to solve. You're probably used to passing props down the component tree, but have you noticed how this gets messier as your app grows? In this article, I'm going to demonstrate this exact challenge. Forget about the basic _what_ and _why_ of React—let's tackle the _how_ to properly manage props in complex applications. Ready to simplify your React life? Let's dive in! ## Problem? Essentially, deep prop drilling is all about passing props through _multiple_ component layers. Lets picture a scenario: you have a grandparent, parent, and child component. The top-level application holds data that the child needs, but to get there, it must travel through the grandparent and parent, even if the parent doesn't need _it_. ![An annotated diagram depicting deep prop drilling in ReactJS](./react-prop-drilling-example.png "Prop drilling through four component layers: Application provides and mutates props, intermediate components pass them through unconsumed, and Child renders the final value.") This seemingly simple task can lead to several issues: - **Maintainability Concerns**: As your application grows, tracking and managing these props through various layers becomes a Herculean task. - **Increased Complexity**: With props weaving through multiple components, the relationship between them becomes convoluted, turning your code into a complex web that's hard to untangle. - **Potential for Bugs and Decreased Readability**: More props snaking through more components increase the chance for bugs. It also makes your code less readable, turning what should be a simple update into a debugging nightmare. When we peel back the layers of our React applications, the repercussions of deep prop drilling are laid bare. It’s not just about the extra code; it’s the ripple effect on code quality and the daily life of a developer that deserves attention. ## On code quality Consider a feature as simple as adding a user's preference. If this preference needs to reflect across multiple components, without deep prop drilling, the implementation is straightforward. However, with deep prop drilling, you must thread this preference through various unrelated components, bloating each with unnecessary props. This bloat can _obscure_ the intended purpose of components, leading to a codebase that’s harder to understand and modify. ## On developer experience For the person writing the code, this means more headaches. Every time you want to add or fix something, you have to follow a trail of breadcrumbs through your code to find where everything connects. It's like untangling a knotted-up necklace — time-consuming and frustrating. ## A real example Let's say you have a little switch in your app that changes the application theme. Simple, right? But with deep prop drilling, you need to send that switch's "_light_" or "_dark_" state through every level of your app. As your app grows, this once-simple switch can become a big hassle, turning a quick update into a big project. This is what I mean. The following `App` component holds the state for the `theme` and a method called `toggleTheme` to change it. ```js name="App.js" caption="The top-level component" const App = () => { const [theme, setTheme] = useState('light'); const toggleTheme = () => { setTheme(theme === 'light' ? 'dark' : 'light'); }; return (
); }; ``` The `theme` and `toggleTheme` are passed down through `Grandparent` and `Parent` components. ```js name="Grandparent.js" caption="Two layers above the toggle switch" const Grandparent = ({ theme, toggleTheme }) => { return (
); }; ``` ```js name="Parent.js" caption="One layer above the toggle switch" const Parent = ({ theme, toggleTheme }) => { return (
); }; ``` And finally, the `Child` component contains a button that actually toggles the theme. ```js name="Child.js" caption="The component that contains the toggle switch" const Child = ({ theme, toggleTheme }) => { return (
); }; ``` See? This example clearly shows what deep prop drilling looks like: we're passing the `theme` and `toggleTheme` all the way down to the `Child` component that actually needs to use them.

Honestly, I'm not a fan of this approach. Having worked with many React codebases, I find it _frustrating_ to wade through such code. It feels like being in a maze, trying to trace back where everything comes from and where it's supposed to go. But nonetheless, we sometimes have to deal with it, especially when working with older React codebases where this pattern is all too common.

This is the scenario we are aiming to refactor in later sections to avoid deep prop drilling. ## Navigating away from deep prop drilling In the React world, deep prop drilling is like navigating a maze. But no worries, we have smart ways to bypass this. We’re going to dive into two common techniques. ## Using React Context This is our first approach to avoid deep prop drilling. React Context acts like a messenger, delivering props directly to components, no matter their level in the tree. It's a straightforward way to share data across different components without the hassle of passing props through each level. React Context allows you to share values like state and functions across your component tree without having to pass props down manually at every level. To use React Context, you first create a context using `createContext`. Then, you wrap your component tree with the context itself, ``, which allows all child components to access the context's value. On React 18 and older you'd write `` instead. Here's our refactored code: ```js // Create a Context for the theme const ThemeContext = createContext({ theme: "light", toggleTheme: () => {} }); // A component that provides the theme to its children const ThemeProvider = ({ children }) => { const [theme, setTheme] = useState("light"); const toggleTheme = () => { setTheme(t => (t === "light" ? "dark" : "light")); }; return ( {children} ); }; const Grandparent = () => (
); const Parent = () => (
); // Use the Context in the Child component const Child = () => { const { theme, toggleTheme } = useContext(ThemeContext); return ( ); }; // Layout reads the theme from context and owns the top-level wrapper const Layout = () => { const { theme } = useContext(ThemeContext); return (
); }; // App only renders the provider — it does not read context itself const App = () => ( ); ``` In the above example, we create a `ThemeContext` and a `ThemeProvider` component that holds the theme state. `ThemeProvider` wraps the tree so that any descendant can access the theme. `Layout` reads `theme` from context to apply the correct class to the top-level wrapper, and `Child` reads both `theme` and `toggleTheme` to render the toggle button — all without prop drilling. Pretty simple eh? ## Component composition While React Context is a useful tool for certain scenarios, it's not always the best solution for prop drilling. The more recommended approach is [component composition](https://eli.cx/blog/an-introduction-to-component-composition-by-example). This method involves creating distinct components for specific functionalities, thereby reducing the need to pass props across many layers.

Instead of consuming the context directly in the `Child`, we create a separate `ThemeToggle` component. In component composition, instead of embedding all logic within a single component or passing props deeply, we break down our UI into smaller, reusable components. Each component takes care of its own functionality, leading to a cleaner and more modular structure.

This approach not only simplifies the component structure but also enhances reusability and maintainability. Alongside component composition, state management libraries can be used selectively when necessary to further _streamline_ state handling in your React application. Now, shall we? ```js const ThemeToggle = ({ theme, setTheme }) => { const toggleTheme = () => { setTheme(theme === "light" ? "dark" : "light"); }; return ( ); }; const Grandparent = ({ children }) => (
{/*Grandparent specific code*/} {children}
); const Parent = ({ children }) => (
{/*Parent specific code*/} {children}
); // Child just renders whatever it's given const Child = ({ children }) => { return (
{/*Child specific code*/} {children}
); }; const App = () => { const [theme, setTheme] = useState("light"); return (
); }; ``` See? Focus on the `ThemeToggle` component. It directly receives `theme` and `setTheme`, encapsulating the theme toggling functionality. This approach allows parent components (`Grandparent`, `Parent`, `Child`) to simply pass down their children, _streamlining_ the component structure. The `App` component, acting as the state holder for `theme`, directly provides the necessary props only to `ThemeToggle`. This setup exemplifies the power of composition in creating a cleaner, more maintainable React architecture, avoiding the pitfalls of prop drilling. ## Conclusion In wrapping up, the main idea in avoiding prop drilling is to smartly pass props where needed. With our `ThemeToggle` component, we show how to provide necessary props directly, bypassing the need to drill through several component levels. This method simplifies our React code, making it cleaner and easier to maintain. In essence, using component composition in React helps us build more modular and understandable components, leading to more efficient and streamlined development. Thanks for reading! 🥰 ## Reading list - [Alex Sidorenko's Prop drilling article](https://alexsidorenko.com/blog/react-prop-drilling-composition/) - [Passing data deeply with context](https://react.dev/learn/passing-data-deeply-with-context) - [Passing props to a component](https://react.dev/learn/passing-props-to-a-component) - [Marco Heine's Prop drilling article](https://marcoheine.com/blog/what-is-prop-drilling-and-how-to-avoid-it) - [Using Composition in React to Avoid "Prop Drilling"](https://www.youtube.com/watch?v=3XaXKiXtNjw) - [Passing JSX as children](https://react.dev/learn/passing-props-to-a-component#passing-jsx-as-children) --- # Eigenvectors > Exploring Spectral Graphs October 24, 2023 · 6 min read · https://yasint.dev/eigenvectors/ Tags: math, linear-algebra --- ## Notes to myself Eigenvectors are vectors that **only scale** (i.e., change in magnitude, and flip around when the scale is negative, but never leave their own line) when a given linear transformation (represented by a matrix) is applied to them. The scaling factor by which an eigenvector is multiplied when the transformation is applied is called an eigenvalue.

Given a square matrix $A$ any vector $v$ is considered an eigenvector of $A$ if $v$ is not the zero vector and there is some scalar $\lambda$ such that applying $A$ to $v$ results in a scalar multiple of $v$, i.e., $v$ stays on the same line through the origin. In equation form, this is written as: $A \cdot v = \lambda \cdot v$, where $"\cdot"$ denotes the multiplication operation (either matrix multiplication or scalar multiplication, depending on context).

$\lambda$ is the eigenvalue corresponding to the eigenvector $v$ in the above equation. It represents the scalar multiple by which the eigenvector is _stretched_ or _compressed_ (if you can't recall linear transformations you can refer [Khan Academy](https://www.khanacademy.org/math/linear-algebra)'s Matrix Transformations lecture for a refresher). To find the eigenvalues of a matrix $A$, we follow two steps. First we set up the characteristic equation, and then we solve for $\lambda$: - ☝️ **Characteristic Equation:** You set up the equation $det(A-\lambda \cdot I)=0$, where $det$ represents the determinant of a matrix, and $I$ is the identity matrix of the same size as $A$. This equation is derived from the eigenvector equation $A \cdot v= \lambda \cdot v$ and the fact that $v$ is non-zero. - ✌️ **Solve for $\lambda$**: Solving the characteristic equation will give you the eigenvalues $\lambda$ of the matrix $A$. Once the eigenvalues $\lambda$ are known, the eigenvectors can be found by: - **Substitution:** For each eigenvalue $λ$, you substitute $\lambda$ back into the equation $A \cdot v= \lambda \cdot v$ (which can be rewritten as $(A− \lambda \cdot I) \cdot v=0)$ and solve for $v$. - **Solving the System:** Typically, you'll get a system of linear equations for $v$, which you'll need to solve. Any non-zero vector that satisfies the system of equations is considered an eigenvector corresponding to the eigenvalue $\lambda$. --- Let's consider a `2x2` matrix $A = \begin{bmatrix} 4 & 1 \\ 2 & 3 \end{bmatrix}$ 1. Characteristic Equation: First, we find the determinant of $A - \lambda \cdot I$ {/*@formatter:off*/} $$ det(A - \lambda \cdot I) = det \begin{pmatrix} \begin{bmatrix} 4 & 1 \\ 2 & 3 \end{bmatrix} - \lambda \cdot \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} \end{pmatrix} \\~\\ = det \begin{pmatrix} \begin{bmatrix} 4-\lambda & 1 \\ 2 & 3-\lambda \end{bmatrix} \end{pmatrix} \\~\\ = (4-\lambda)(3-\lambda) - (2)(1)=\lambda^2 - 7\lambda + 10 $$ {/*@formatter:on*/} 2. Solving for $\lambda$: We solve $\lambda^2 - 7\lambda + 10 = 0$ to find the eigenvalues. The solutions to this quadratic equation are the eigenvalues of $A$, which are $\lambda = 5$ and $\lambda = 2$. Now comes the real magic. We can find the eigenvectors by plugging each eigenvalue into the equation $(A− \lambda \cdot I) \cdot v=0$ and solving for $v$. For $\lambda = 5$: $$ \begin{bmatrix} -1 & 1 \\ 2 & -2 \end{bmatrix} \cdot \begin{bmatrix} v_1 \\ v_2 \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \end{bmatrix} $$ The system simplifies to $-v_1 + v_2 = 0$, so one eigenvector _could_ be $v = [1, 1]$ for $\lambda = 5$. $$ \begin{bmatrix} 2 & 1 \\ 2 & 1 \end{bmatrix} \cdot \begin{bmatrix} v_1 \\ v_2 \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \end{bmatrix} $$ Similarly, for $\lambda = 2$, the system simplifies to $2v_1 + v_2 = 0$, so one eigenvector _could_ be $v = [1, -2]$ for $\lambda = 2$ This process reveals the eigenvalues $\lambda=5$ and $\lambda=2$, with corresponding eigenvectors $[1,1]$ and $[1,−2]$, respectively. Each eigenvector is associated with one eigenvalue, and these vectors indicate the "directions" in which the linear transformation represented by matrix $A$ acts by stretching/compressing, without rotating. --- Using `numpy` to find the eigenvalues and eigenvectors. ```python caption="I used 'np.linalg.eig' here and this method is for general square matrices, and there are optimized versions like 'np.linalg.eigh' for symmetric or Hermitian matrices." A = np.array([[4, 1], [2, 3]]) ## The eigenvectors are normalized so their Euclidean norms are 1. eigenvalues, eigenvectors = np.linalg.eig(A) print("Matrix A:") print(A) print("\nEigenvalues:") print(eigenvalues.real) print("\nEigenvectors:") print(eigenvectors.real) ``` ```bash Output: Matrix A: [[4 1] [2 3]] Eigenvalues: [5. 2.] Eigenvectors: [[ 0.70710678 -0.4472136 ] [ 0.70710678 0.89442719]] ``` In this output, the eigenvalues are `5` and `2`, which match the mathematical solution I calculated. The eigenvectors in `numpy` are normalized (i.e., their "unit length" of 1 in Euclidean space), so they may look different from the one I calculate by hand, but they are indeed pointing in the same directions. The `.real` is there because since NumPy 2.5 `eig` always hands back complex arrays, so even these real eigenvalues would otherwise print with a `+0.j` tail.

The first eigenvector is approximately $[0.707, 0.707]$, which points in the same direction as $[1,1]$, and the second eigenvector is approximately $[−0.447, 0.894]$, which lies on the same line as $[1,−2]$ (numpy just picked the opposite sign, which is still a valid eigenvector). The direction is the critical property of the eigenvector, not the magnitude.

We can verify this by normalizing the vector. It involves dividing each component of the vector by its length. For example, suppose the vector is $[1, -2]$. First, we calculate the magnitude ($m$) (Euclidean norm): $\small{m = \sqrt{(1)^2 + (-2)^2} = \sqrt{1+4} = \sqrt{5}}$ Then, divide each component of the original vector by this magnitude: $\text{normalized}\ \text{vector} = \begin{bmatrix} \frac{1}{\sqrt{5}},\frac{-2}{\sqrt{5}}\end{bmatrix}$ Or just use `numpy`. ```python ## Define the original vectors vectors = np.array([[1, 1], [1, -2]]) ## Function to normalize a vector def normalize_vector(vector): # Calculate its magnitude (Euclidean norm) magnitude = np.linalg.norm(vector) normalized_vector = vector / magnitude return normalized_vector ## Normalize the vectors and print the results for vector in vectors: normalized_vector = normalize_vector(vector) print(f"Original vector: {vector}") print(f"Normalized vector: {normalized_vector}\n") ``` Both approaches will give us the same normalized vector: ```bash Output: Original vector: [1 1] Normalized vector: [0.70710678 0.70710678] Original vector: [ 1 -2] Normalized vector: [ 0.4472136 -0.89442719] ``` Dassit 👋 ## Reading list - [Stanford Spectral Graph Theory](https://web.stanford.edu/class/cs168/l/l11.pdf) - [CMU: Spectral Graph Theory and its Applications](https://www.cs.cmu.edu/afs/cs/user/glmiller/public/Scientific-Computing/F-11/RelatedWork/Spielman/SpectTut.pdf) - [Yale Spectral Graph Theory](http://www.cs.yale.edu/homes/spielman/PAPERS/SGTChapter.pdf) --- # Java's fork/join framework > Java goes Forking Crazy! October 21, 2023 · 8 min read · https://yasint.dev/java-fork-join/ Tags: java, concurrency --- Hey there 👋! With multicore processors now standard, it's essential for high-performance applications to harness this power through effective concurrency. [Java's Fork/Join framework](https://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html), part of the `java.util.concurrent` package since JDK `7`, optimizes the efficiency of multi-threaded tasks, fully utilizing the capabilities of modern hardware. In this article, I'm going to delve into the **Fork/Join framework**, explaining its purpose, significance, and application, all illustrated with a practical example. ## What the fork? The Fork/Join framework is an implementation of the `ExecutorService` interface that helps developers solve problems using [divide-and-conquer algorithms](https://en.wikipedia.org/wiki/Divide-and-conquer_algorithm). These algorithms work by breaking down a task into smaller, more manageable pieces, solving each piece separately, and then combining the results. In this framework, any **task can be forked (split)** into smaller tasks, and the **results can be joined** subsequently, hence the name "Fork/Join." You may wonder, "Why opt for the Fork/Join Framework when traditional threading is an option?" ## Hmm, why? Picture multitasking. But it's Java juggling your tasks with _finesse_! Aaaaand it's all about efficiency, and here's why: - - **Efficient Thread Utilization:** It makes use of a [work-stealing algorithm](https://en.wikipedia.org/wiki/Work_stealing), where idle threads "steal" tasks from busy threads' queues. This ensures that all threads are actively used, reducing overhead and improving performance. - **Handling Recursive Tasks:** The framework excels at handling recursive computations, a common scenario in _divide-and-conquer_ algorithms. - **Improved Scalability:** It's designed to scale well to available parallelism, which means better performance on multicore processors. ## How does it work? Consider a scenario where you're faced with an array of **10 tasks**, each representing operations that are resource-intensive, such as database or I/O operations. Fork/join is built for CPU-bound work, so blocking tasks like these belong in a pool of their own (or behind `ForkJoinPool.managedBlock`), but they make the splitting easy to watch. Your objective is to expedite the processing of these tasks efficiently without overburdening the system resources. Sequential execution is off the table due to time constraints, and a single thread can handle a maximum of two tasks consecutively. Intriguing challenge, isn't it? Let's tackle this problem by employing a _divide-and-conquer_ strategy. ![Recursively dividing the task array until we match a certain threshold](./divide-and-conquer.png) As demonstrated, our goal is to systematically divide tasks until they're manageable enough, aligning with our defined threshold. Wondering how this translates into Java? Stay with me; it's simpler than it seems. First, let's establish our _base scenario_. Imagine a `Task` class, responsible for handling time and resource-intensive operations—think bulk updates, I/O, network calls, and more. Here's a glimpse of what it looks like: ```java name="Task.java" public class Task { private final int id; // Other necessary fields... public Task(int id) { this.id = id; } public void process() { // Note: exception handling omitted for brevity System.out.printf("Processing task %d...%n", id); Thread.sleep(TimeUnit.SECONDS.toMillis(3)); } } ``` However, we can enhance our approach by abstracting the `process()` method, leading us to define a `Computable` functional interface and implement it in our `Task` class, like so: ```java @FunctionalInterface public interface Computable { void process(); } public class Task implements Computable { // Existing code... } ``` Noice 😎! That's so much neater, isn't it? Next, we generate an array of random tasks, shifting our focus to the crux of the issue: **parallel execution**. ```java private Task[] generateTasks(int count) { Task[] tasks = new Task[count]; for (int i = 0; i < tasks.length; i++) { tasks[i] = new Task(i + 1); } return tasks; } ``` But how do we execute these tasks in parallel? Enter Java's Fork/Join framework. Here's a simplified guide: 1. Extend `RecursiveTask` or `RecursiveAction`, depending on whether you need a result. 2. Override the `compute()` method to specify the task's logic and the conditions for further splitting or direct execution. 3. Engage a `ForkJoinPool` to invoke the root task. Let's start with _step 1_, creating a class named `TaskProcessor` extending `RecursiveAction`, and override the `compute()` method: ```java name="TaskProcessor.java" public class TaskProcessor extends RecursiveAction { // We do our initialization here... @Override protected void compute() { // Task execution logic... } } ``` In _step 2_, we refine our `TaskProcessor` to accept an array of tasks and employ a loop within `compute()` to handle tasks sequentially. But there's a catch: we haven't set the base condition for task division. Here's where `start` and `end` come into play, marking the range of tasks processed by each `TaskProcessor` instance. This range helps us determine when to divide tasks further or process them directly, based on a `THRESHOLD`. ```java public class TaskProcessor extends RecursiveAction { private static final int THRESHOLD = 2; // This can vary private final Computable[] tasks; private final int start; private final int end; public TaskProcessor(Computable[] tasks, int start, int end) { this.tasks = tasks; this.start = start; this.end = end; } @Override protected void compute() { if (end - start <= THRESHOLD) { for (int i = start; i < end; i++) { tasks[i].process(); } } else { int middle = start + (end - start) / 2; TaskProcessor leftProcessor = new TaskProcessor(tasks, start, middle); TaskProcessor rightProcessor = new TaskProcessor(tasks, middle, end); ForkJoinTask.invokeAll(leftProcessor, rightProcessor); } } } ``` The `middle` calculation `(start + (end - start) / 2)` ensures a consistent split of tasks[^1], with `leftProcessor` and `rightProcessor` handling each segment. The call to `ForkJoinTask.invokeAll()` initiates parallel execution. After setting up our tasks and creating the `TaskProcessor` class, we need to instantiate a `ForkJoinPool` and start our tasks. Here's how we can do it: ```java public class ForkJoinTest { @Test public void forkJoin() { final Task[] tasks = generateTasks(10); TaskProcessor taskProcessor = new TaskProcessor(tasks, 0, tasks.length); try (ForkJoinPool pool = new ForkJoinPool()) { pool.invoke(taskProcessor); } } private Task[] generateTasks(int count) { Task[] tasks = new Task[count]; for (int i = 0; i < tasks.length; i++) { tasks[i] = new Task(i + 1); } return tasks; } } ``` And just like that, it works! Super quick and almost like magic. Your tasks are done before you know it! So, it works _super-fast_, but how, huh? Let's take a simple look at the main code that makes this happen: - We first generate our tasks using the `generateTasks(10)` method, which returns an array of _ten_ Task objects. - We create an instance of `TaskProcessor`, passing the tasks along with the `start` and `end` indices. - We then instantiate the `ForkJoinPool`. We can either use `ForkJoinPool.commonPool()`, which reuses the common pool shared among all ForkJoinTasks, or create a new instance with a target parallelism level using `new ForkJoinPool(parallelism)`. The no-arg `new ForkJoinPool()` we use here sets that level to the number of available processors. > **Pool Selection**? > > The common pool is a good default for short, CPU-bound work. It's shared by every ForkJoinTask not submitted to a specific pool and by `CompletableFuture`'s async methods though, so tasks that block on I/O (like ours) belong in a dedicated pool where they can't starve everyone else. - Then, we initiate the task with `pool.invoke(taskProcessor)`. This starts the process, invoking the `compute()` method of `TaskProcessor`. The `invoke()` method is _synchronous_—it blocks until the task is complete. - Finally, close the pool once the work is done. Since JDK `19`, `ForkJoinPool` is `AutoCloseable`, so try-with-resources shuts it down and waits for running tasks to finish (on older JDKs, call `pool.shutdown()` yourself). Don't bother with the common pool though: `shutdown()` and `close()` have no effect on it, since it lives as long as the JVM does. Moving from best practices to performance considerations, it's essential to evaluate the efficiency of our implementation. Because `TaskProcessor` is a `RecursiveAction` with no merge step — work happens only at the leaves — each of the $n$ tasks is processed exactly once, giving $O(n)$ total work. The recursion tree has depth $O(\log n)$ (the number of times we halve the array), which is the parallel span: the longest chain of sequential steps. With enough threads, the ideal wall-clock time is therefore $O(\log n)$, and the parallelism — total work divided by span — is $O(n / \log n)$. ## Conclusion The `ForkJoinPool` handles the heavy lifting of worker thread management, task synchronization, and other low-level details. The `invoke()` method of the pool executes the specified task and any subtasks that it may create, utilizing the available threads in the pool. The framework ensures **balanced distribution** of tasks among threads and efficient execution, leveraging the _divide-and-conquer_ principle we implemented in the `compute()` method of our `TaskProcessor`. I hope this guide made Java's Fork/Join framework easier for you! Thanks for sticking around 🥰. [^1]: **Consistent split of tasks:** The divisor for `middle` typically is `2`, dividing the task list in _half_, but it can be adjusted depending on how you want to split tasks. ```java int oneThird = start + (end - start) / 3; int twoThirds = start + 2 * (end - start) / 3; TaskProcessor firstThird = new TaskProcessor(tasks, start, oneThird); TaskProcessor secondThird = new TaskProcessor(tasks, oneThird, twoThirds); TaskProcessor finalThird = new TaskProcessor(tasks, twoThirds, end); invokeAll(firstThird, secondThird, finalThird); // Fork new subtasks ``` Above is a hypothetical example if you were to split the task into three subtasks instead of two. --- # TypeScript's omit and pick > How to Pick your TypeScript battles and when to Omit the drama! August 10, 2023 · 4 min read · https://yasint.dev/ts-omit-and-pick/ Tags: typescript, frontend --- Hey there! If you're like me, diving deep into TypeScript has been a roller coaster of discovery. Among the many gems I've stumbled upon, the [Omit](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys) and [Pick](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys) utility types have been game-changers. Let me share a bit about my experiences with these two. ## The `Pick` type What's the deal, huh? So, `Pick` is like your personal shopping assistant for types. You tell it which properties you want from an existing type, and voilà, you get a _brand-new_ type with just those properties. Given a type $T$ and a set of properties $P$, the Pick operation can be represented as $T \cap P$. ```ts type User = { id: number; name: string; email: string; }; type UserName = Pick; ``` In set theory terms, the `UserName` type is the intersection of the `User` type with a set that only contains the name property. Diving into Pick, there's some seriously good stuff to rave about. First off, its flexibility is unmatched—it's like crafting the perfect sandwich, picking only the ingredients I'm craving. And talk about clarity! It's a breeze to see which properties I'm juggling, making my code a lot more readable. But, it's not all rosy.

I'll admit, there are times I get a bit too enthusiastic and end up complicating things more than necessary. And, oh boy, the maintenance! As in every codebase's foundational types shift and change, you've got to be vigilant, ensuring that the types you've "picked" are still vibing well. It's like keeping tabs on a growing chain of dependencies, but hey, that's the coder's life for you!

## The `Omit` type Think of `Omit` as the sibling of `Pick`. Instead of telling it what you want, you tell it what you don't want. It's like ordering a pizza and saying, **"Hold the olives 🤨."** Given a type $T$ and a set of properties $P$, the Omit operation can be represented as $T - P$. ```ts // User type from above type UserWithoutEmail = Omit; ``` The `UserWithoutEmail` type is the difference of the `User` type with a set that only contains the email property.

When I first started using `Omit`, I was blown away by its precision—it's _super handy_ when I want to leave out just a thing or two, especially from those chunky types. Plus, it's a lifesaver in ensuring I don't accidentally toss in stuff I'd rather keep out. But, it wasn't all sunshine and rainbows.

In the beginning, I'd often jumble up `Omit` and `Pick` since they're kinda like two sides of the same coin. And, just like with Pick, I've realized I've got to be on constant alert, especially when my main types undergo changes. Part of that is on `Omit` itself: unlike `Pick`, it doesn't check that the keys you hand it exist on the type, so `Omit` compiles just fine, and renaming `email` later won't break an `Omit` that still names it. It's been a learning curve, but totally worth it! Before we conclude, let's delve deeper into the intricacies of these utility types and their impact on our coding journey. ## Properties and implications ### Idempotence $\odot$ Applying Pick or Omit multiple times with the same parameters will yield the same result. For instance, `Pick, 'name'>` is the same as `Pick`. ### Commutativity $\oplus$ The order in which you pick properties doesn't matter. `Pick` is the same as `Pick`. This is because the union of two sets is _commutative_. ### Composition $\otimes$ You can chain Pick and Omit, and when the keys don't overlap the order won't affect the result. For example, `Pick, 'name'>` is the same as `Omit, 'email'>`. Overlap and it breaks: `Pick, 'name'>` won't even compile, because `Pick` only accepts keys that still exist on the type. ### Identity $\circ$ If you pick all properties of a type or omit none, you get the original type back. Similarly, if you omit all properties or pick none, you get `{}`, which looks empty but happily accepts any non-nullish value, `42` included. ## Conclusion Omit and Pick have been real MVPs in my TypeScript toolkit. They've given me so much control over my types, but I've also learned to use them wisely. If you're diving into TypeScript, give them a shot and see how they fit into your coding style. Happy coding! 🚀 Thanks for reading! 🥰 --- # JavaScript's new immutable array methods > Exploring toReversed(), toSorted(), toSpliced(), and with() from ECMAScript 2023. June 28, 2023 · 5 min read · https://yasint.dev/javascript-new-immutable-array-methods/ Tags: javascript, frontend --- In JavaScript, when it comes to manipulating the order of elements within an array, `reverse()` and `toReversed()` are two commonly used methods, each having its unique functionality and application. ## Old school `reverse()` The [`reverse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) method, a member of JavaScript's [`Array.prototype`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), alters the order of the array's elements, essentially flipping them. This method performs the operation _in-place_, implying that it directly modifies the original array. Let's consider the example below: ```js let fruits = ['🍎', '🥭', '🍍']; console.log(fruits); // Output: ['🍎', '🥭', '🍍'] let reversedFruits = fruits.reverse(); console.log(reversedFruits); // Output: ['🍍', '🥭', '🍎'] // Note: reverse() mutates the original array. console.log(fruits); // Output: ['🍍', '🥭', '🍎'] ``` In the above code, after applying `reverse()`, the original fruits array is also reversed. This is because `reverse()` is a _destructive_ method and modifies the original array in-place. ## Introducing `toReversed()` 🥳 In contrast to reverse(), the `toReversed()` method **does not mutate** the original array. Instead, it creates a new array, mirroring the elements of the original array in reverse order. This method comes handy when preserving the initial order of elements is crucial. Let's consider a similar example: ```js let numbers = [10, 20, 30]; console.log(numbers); // Output: [10, 20, 30] let reversedNumbers = numbers.toReversed(); console.log(reversedNumbers); // Output: [30, 20, 10] // toReversed() is non-destructive -- the original array remains unchanged. console.log(numbers); // Output: [10, 20, 30] ``` In this example, the original numbers array remains unaffected after applying the `toReversed()` method, exhibiting its _non-destructive_ nature. ## Handling sparse arrays with `toReversed()` An additional feature of `toReversed()` is its behaviour with _sparse arrays_. In JavaScript, a sparse array is an array where **some elements are missing**. The `toReversed()` method treats empty slots in sparse arrays as if they hold the `undefined` value. ```js console.log([10, , 30].toReversed()); // Output: [30, undefined, 10] ``` Here, the empty slot in the array is considered as undefined when reversed. ## When did the `toReversed()` method become available? To enhance the adaptability and fluidity of array manipulation in JavaScript, the [ECMAScript 2023 specification](https://tc39.es/ecma262/2023/) brings about a significant proposal named [Change Array by Copy](https://tc39.es/proposal-change-array-by-copy/).

This proposal enriches the set of methods on `Array.prototype` by introducing a suite of functions that operate on the array and return a new copy, instead of manipulating the original array. The newcomers to this function suite include [`toReversed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed), [`toSorted()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted), [`toSpliced()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSpliced), and an additional method named [`with()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/with).

These methods are designed to mirror the behavior of existing methods [reverse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse), [sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), and [splice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice), and the typical array element replacement operation performed using bracket notation. However, these new methods ensure that the original array remains unaltered. ## `toSorted()` The `toSorted()` method, just like `sort()`, arranges the array elements in a certain order. The crucial difference is that **it does not modify the original array**. ```js let jumbledNumbers = [30, 10, 20]; console.log(jumbledNumbers); // Output: [30, 10, 20] let orderedNumbers = jumbledNumbers.toSorted(); console.log(orderedNumbers); // Output: [10, 20, 30] // The original array remains unchanged console.log(jumbledNumbers); // Output: [30, 10, 20] ``` ## `toSpliced()` Similarly, `toSpliced()` acts as a non-destructive version of splice(). It returns a new array, incorporating the changes specified by the arguments, while the original array stays intact. ```js let oldArray = ['🍎', '🍌', '🥭']; console.log(oldArray); // Output: ['🍎', '🍌', '🥭'] // In here we just say, start from index 1 and delete 0 elements, and insert '🍊' let newArray = oldArray.toSpliced(1, 0, '🍊'); console.log(newArray); // Output: ['🍎', '🍊', '🍌', '🥭'] // The original array remains unchanged console.log(oldArray); // Output: ['🍎', '🍌', '🥭'] ``` ## `with()` Additionally, the `with()` method is an invaluable tool that replaces an element at a specified index with a given value and returns a new array, without touching the original array. ```js let initialFruits = ['🍎', '🍌', '🥭']; console.log(initialFruits); // Output: ['🍎', '🍌', '🥭'] let updatedFruits = initialFruits.with(1, '🍊'); console.log(updatedFruits); // Output: ["🍎", "🍊", "🥭"] // The original array remains unchanged console.log(initialFruits); // Output: ['🍎', '🍌', '🥭'] ``` ## The motivation behind these new methods Incorporating these methods in the language specification echoes the increasing emphasis on promoting functional programming styles in JavaScript, where data is usually treated as immutable. This development is a welcome addition for developers who frequently need to perform operations on arrays but wish to keep the original arrays unmodified. For me personally, these new features significantly simplify array manipulation, particularly in scenarios where avoiding side effects is critical. By preventing [accidental mutations](https://sapegin.me/blog/avoid-mutation/), these methods make the code more predictable and easier to reason about, which is a key factor in reducing bugs and enhancing code readability. ## Conclusion The ECMAScript 2023 **'Change Array by Copy'** proposal introduces four powerful methods that align JavaScript with modern functional programming practices: `toReversed()`, `toSorted()`, `toSpliced()`, and `with()`. These non-destructive alternatives keep your original arrays untouched, making code more predictable and safer, especially when working with frameworks like React that rely on immutability. Supported in modern browsers (Chrome 110+, Firefox 115+, Safari 16+), in my opinion, these methods should be your default choice for array manipulation. Use the traditional mutating methods only when you explicitly need in-place modification. Happy coding! 🚀 --- # Integrating JUnit 5 in Maven projects > A practical guide to setting up JUnit 5 testing in Maven projects with modern best practices. May 25, 2023 · 4 min read · https://yasint.dev/integrating-junit-in-maven-projects/ Tags: java, testing --- [JUnit](https://junit.org/) is a simple, open-source framework to write and run repeatable tests in [Java](https://www.java.com/en/). It's an essential tool for any serious developer who wants to implement unit testing into their development lifecycle. Here's how you can integrate JUnit 5 into your Maven project. ## Prerequisites Before proceeding, make sure you have: - Java JDK installed (Java 8 or later) - [Apache Maven](https://maven.apache.org/) installed (3.6.3+) - Basic understanding of Maven project structure ## Step 1: updating the `pom.xml` file The first step to adding JUnit to your Maven project is to update your project's [`pom.xml` file](https://maven.apache.org/guides/introduction/introduction-to-the-pom.html). This XML file describes the software project being built, its dependencies, and the build order. You can include JUnit in your project by adding it as a dependency. Here is how you do that: ```xml org.junit.jupiter junit-jupiter-api 5.14.4 test org.junit.jupiter junit-jupiter-engine 5.14.4 test ``` In the example above, I'm using JUnit version [`5.14.4`](https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api/5.14.4), the latest 5.x release. You can find newer releases on [Maven Central](https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api), but JUnit 6 and later need Java 17 or higher. The `` tag is set to `test`, meaning this dependency is not required for normal use of the application, and is only available for the test _compilation_ and _execution_ phases. ### Ensuring Maven Surefire compatibility For Maven to properly execute JUnit 5 tests, you need the Maven Surefire plugin (version 2.22.0 or later): ```xml org.apache.maven.plugins maven-surefire-plugin 3.6.0 ``` ## Step 2: writing test cases Once the `pom.xml` file is updated, you can begin writing your test cases. By convention, test cases are placed in the `src/test/java` directory, mirroring the package structure of your main code. Here is an example of a simple test case: ```java name="ExampleTest.java" public class ExampleTest { @Test @DisplayName("Should add two numbers correctly") public void testAddition() { int a = 5; int b = 10; assertEquals(15, a + b, "5 + 10 should equal 15"); } } ``` In this test case, we're using the `@Test` annotation to denote a test method and `@DisplayName` to provide a readable test description. The `assertEquals()` method checks if two values are equal, and the optional third parameter provides a failure message. ### JUnit 5 common annotations JUnit 5 provides several useful annotations for organizing tests: ```java public class LifecycleTest { @BeforeAll static void setupOnce() { // Runs once before all tests } @BeforeEach void setupEach() { // Runs before each test } @Test void testExample() { // Your test logic } @AfterEach void teardownEach() { // Runs after each test } @AfterAll static void teardownOnce() { // Runs once after all tests } } ``` ## Step 3: running tests You can run the tests using the Maven command: ```bash mvn test ``` Maven will automatically discover and run any test cases in the `src/test/java` directory. You should see output similar to the following if the tests pass: ```txt [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running ExampleTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 s -- in ExampleTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS ``` The output indicates that one test was run and that there were no failures, errors, or skipped tests. ### Running specific tests You can run specific test classes or methods: ```bash # Run a specific test class mvn test -Dtest=ExampleTest # Run a specific test method mvn test -Dtest=ExampleTest#testAddition ``` ## Best practices When integrating JUnit into your Maven projects, consider these best practices: - **Match package structure**: Keep your test packages mirrored to your source packages for easy navigation - **Naming conventions**: Name test classes with the `Test` suffix (e.g., `CalculatorTest`) - **Descriptive test names**: Use `@DisplayName` for human-readable test descriptions - **Arrange-Act-Assert**: Structure tests with clear setup, execution, and verification phases - **One assertion per test**: Keep tests focused on a single behavior (when practical) - **Use parameterized tests**: For testing multiple inputs, leverage `@ParameterizedTest` (add the `junit-jupiter-params` dependency first) ## Troubleshooting **Tests not running?** Ensure you have both `junit-jupiter-api` and `junit-jupiter-engine` dependencies, and verify your Maven Surefire plugin version is 2.22.0 or later. **Import errors?** Run `mvn clean install` to refresh dependencies. ## Conclusion Integrating JUnit 5 into your Maven project is straightforward and brings significant benefits to code quality and maintainability. With proper test coverage, you can refactor with confidence, catch bugs early, and maintain a robust codebase. ## Further reading - [JUnit 5 User Guide](https://docs.junit.org/5.14.4/user-guide/) - Official comprehensive documentation - [Baeldung JUnit 5 Guide](https://www.baeldung.com/junit-5) - Practical tutorials and examples - [Maven Surefire Plugin](https://maven.apache.org/surefire/maven-surefire-plugin/) - Plugin documentation --- # My take on ChatGPT and prompt engineering > ChatGPT is powerful, but it's not magic. Here's how I actually use it. March 11, 2023 · 3 min read · https://yasint.dev/chatgpt-prompt-engineering/ Tags: ai, prompts --- I've been using ChatGPT for a while now, and I want to share my honest perspective on what it is, what it isn't, and how I think about prompt engineering. ## What ChatGPT actually is ChatGPT is a large language model trained on vast amounts of internet text data using the [Transformer architecture](https://arxiv.org/abs/1706.03762). It can generate human-like responses to natural language queries, making conversations feel surprisingly natural. But here's the thing: it's not generating new knowledge. It's reorganizing and presenting what already exists in its training data in a more digestible form. Each model version has a knowledge cutoff date - the point beyond which it hasn't seen new information. The specific cutoff varies depending on which model you're using and when it was trained. This means the model itself might not know about recent events, current trends, or information published after its training period. ChatGPT can search the web now, which covers part of that gap, though whatever it pulls in deserves the same suspicion as everything else it says. The model also sometimes generates false information or repeats itself. You need to know what accurate and inaccurate information looks like before trusting any generated content. ## How I approach prompting I've learned that how you ask matters. A lot. Instead of treating it like Google with simple queries, I build context through conversation. I might start broad, then narrow down, asking follow-up questions to refine the output. But I've also discovered that being specific and directive in a single prompt often works better. For example, when I need technical writing, I specify the tone, structure, and style I want. I tell it to use evidence, ask transitional questions, write in an academic context, or mimic a particular writing style. I can limit word counts, require specific keywords, or ask it to transition between contexts. The key is being deliberate about what you want. Prompt engineering is a skill that develops over time through experimentation. ## My honest assessment ChatGPT is a helpful research sidekick, not a replacement for critical thinking. I use it to: - Quickly understand unfamiliar topics - Generate initial drafts that I heavily edit - Explore different perspectives on a subject - Save time on routine writing tasks But I never blindly trust its output. I verify facts, check sources when possible, and apply my own judgment. The convenience is real, but so are the limitations. At the end of the day, nothing beats human critical thinking. ChatGPT is a tool, and like any tool, its value depends on how skillfully you use it. I focus on what I'm trying to learn and let the tool assist, not replace, my thinking process. ## Worth exploring If you want to dive deeper into prompt engineering, check out [this thread on X by Rob Lennon](https://x.com/thatroblennon/status/1610316022174683136). He shares clever techniques for creating prompts that generate more cohesive outputs. You can start experimenting at [chatgpt.com](https://chatgpt.com) with the free tier. --- # Declarative events in ReactJS > Explore how to handle pathological events declaratively in ReactJS applications. March 9, 2023 · 1 min read · https://yasint.dev/declarative-events-in-reactjs/ Tags: react, javascript, frontend --- If you want to handle _pathological_ use cases inside React using JavaScript's `setInterval` function, use this library called [`@use-it/interval`](https://www.npmjs.com/package/@use-it/interval) developed by [Donavon](https://github.com/donavon). ```bash terminal npm i @use-it/interval ``` Suppose you want to run a function _periodically_ with a specified **interval**, but you need to control its behavior dynamically. Here's how you can do it: ```js function Component() { const [play, setPlay] = useState(false); useInterval(() => { // do something periodically }, play ? 1000 : null); // rest of your code ... } ``` ![useInterval() example](./interval.gif "In this example, clicking the _play_ button periodically executes another procedure every 1 second to refresh this component in the background (blinks green). As soon as you click _pause_, it stops running that hook (idle state is gray).") Here's the [codesandbox demo](https://codesandbox.io/s/use-it-interval-g1gocz) for this. Similarly, if you want to attach or detach event-handling logic to an element or global scope (like `window` or `document`) inside a React Hook, you can use [`@use-it/event-listener`](https://www.npmjs.com/package/@use-it/event-listener). How convenient! ### Reading list - [Dan Abramov's article about `setInterval`](https://overreacted.io/making-setinterval-declarative-with-react-hooks/) - [Pathological (Mathematics)](https://en.wikipedia.org/wiki/Pathological_(mathematics)) - [Thread by Donavon on X](https://x.com/donavon/status/1093612936621379584) --- # Positive Lookaheads > Oh, you're looking for something? Well, I'm looking for something too. March 7, 2023 · 1 min read · https://yasint.dev/positive-lookaheads/ Tags: regex, tools --- Find expression $$x$$ where expression $$y$$ follows:- Suppose you need to match all the first names ending with last name _Picasso_. You could write the following pattern to solve it. ```regexp hideLineNums ([a-zA-Z ]+)(?=Picasso) ``` ![Regex Breakdown](./regex-breakdown.png) ```txt hideLang Paloma Picasso // => true Maya Picasso // => true Steve Ross // => false ``` To experiment, navigate to the [Regex101 sandbox](https://regex101.com/r/av8c3o/1) I've created. This RegEx needs a backtracking engine (PCRE, JavaScript, Python, Java, .NET). Automata-based engines like RE2, Go's regexp and Rust's regex crate don't support lookaheads. ### Reading list - [Regular Expressions with Lookahead (Berglund et al., 2021)](https://www.diva-portal.org/smash/get/diva2:1641657/FULLTEXT01.pdf) - [NFA vs DFA by Daniel Bazaco](https://www.abstractsyntaxseed.com/blog/regex-engine/nfa-vs-dfa) --- # Functors > Yet another design pattern from category theory in mathematics. March 6, 2023 · 1 min read · https://yasint.dev/functors/ Tags: functional-programming, math --- ### Note to self A Functor is a _design pattern_ that evolves from category theory in mathematics. Fundamentally it's a mapping between categories that preserves the structure of the original categories involved. It satisfies two laws: - 1. Identity law: $$\small{F(\operatorname{id}_A) = \operatorname{id}_{F(A)}}$$ 2. Composition law: $$\small{F(g \circ f) = F(g) \circ F(f)}$$ ### Reading list - [Category Theory](https://plato.stanford.edu/entries/category-theory/) - [Type Variance](https://en.wikipedia.org/wiki/Type_variance) - [Java Functors](https://www.baeldung.com/java-functors) --- # Fast forward videos with ffmpeg > Learn how to speed up your videos effortlessly using ffmpeg. January 18, 2023 · 9 min read · https://yasint.dev/fast-forward-videos-with-ffmpeg/ Tags: ffmpeg, tools --- The `ffmpeg` command line tool is a hyper-fast video and audio converter that can also grab from a live audio/video source. You can use it to convert arbitrary sample audio/video rates and resize/trim videos on the fly with a high-quality _polyphase_ filter. > **Installing ffmpeg** > > If you don't have `ffmpeg` installed in your system you can refer [how to install ffmpeg in your operating system](https://www.hostinger.com/tutorials/how-to-install-ffmpeg). Or if you're on macOS just do `brew install ffmpeg`[^1] Suppose you want to fast-forward this masterpiece by `2x`:-