FUSE is a powerful Linux kernel module that lets you implement your own filesystems entirely in user space. No
kernel hacking required. With it, building your own virtual filesystem becomes surprisingly achievable and even… fun.
In today’s article, we’ll build a filesystem that’s powered entirely by HTTP. Every file operation — reading a
file, listing a directory, even getting file metadata — will be handled by a REST API. On the client side, we’ll
use libcurl to perform HTTP calls from C, and on the server side, a simple Python Flask app will serve as our
in-memory file store.
Along the way, you’ll learn how to:
Use FUSE to handle filesystem operations in user space
Make REST calls from C using libcurl
Create a minimal RESTful backend for serving file content
Mount and interact with your filesystem like any other directory
Up in my github repository I have added this project if you’d like to pull it down and try
it. It’s called restfs.
Let’s get into it.
Defining a FUSE Filesystem
Every FUSE-based filesystem starts with a fuse_operations struct. This is essentially a table of function pointers —
you provide implementations for the operations you want your filesystem to support.
This tells FUSE: “When someone calls stat() on a file, use restfs_getattr. When they list a directory, use
restfs_readdir, and so on.”
Let’s break these down:
getattr: Fills in a struct stat with metadata about a file or directory — size, mode, timestamps, etc. It’s the equivalent of stat(2).
readdir: Lists the contents of a directory. It’s how ls knows what to show.
open: Verifies that a file can be opened. You don’t need to return a file descriptor — just confirm the file exists and is readable.
read: Reads data from a file into a buffer. This is where the real I/O happens.
Each function corresponds to a familiar POSIX operation. For this demo, we’re implementing just the basics — enough to
mount the FS, ls it, and cat a file.
If you leave an operation out, FUSE assumes it’s unsupported — for example, we haven’t implemented write, mkdir,
or unlink, so the filesystem will be effectively read-only.
Making REST Calls from C with libcurl
To interact with our HTTP-based server, we use libcurl, a powerful and flexible HTTP client library for C. In
restfs, we wrap libcurl in a helper function called http_io() that performs an HTTP request and returns a parsed
response object.
CURLOPT_CUSTOMREQUEST lets us specify GET, POST, PUT, DELETE, etc.
If a body is provided (e.g. for POST/PUT), we pass it in using CURLOPT_POSTFIELDS.
CURLOPT_WRITEFUNCTION and CURLOPT_WRITEDATA capture the server’s response into a buffer.
Headers are added manually to indicate we’re sending/expecting JSON.
After the call, we extract the HTTP status code and clean up.
The result is returned as a _rest_response struct:
struct_rest_response{intstatus;json_object*json;char*data;// raw response bodysize_tlength;// response size in bytes};
This makes it easy to access either the full raw data or a parsed JSON object depending on the use case.
To parse the JSON responses from the server, we use the json-c library — a
lightweight and widely used C library for working with JSON data. This allows us to easily extract fields like
st_mode, st_size, or timestamps directly from the server’s responses.
To simplify calling common HTTP methods, we define a few handy macros:
This layer abstracts away the curl boilerplate so each FUSE handler can focus on interpreting the result.
The Backend
So far we’ve focused on the FUSE client — how file operations are translated into HTTP requests. But for the system to
work, we need something on the other side of the wire to respond.
Enter: a minimal Python server built with Flask.
This server acts as a fake in-memory filesystem. It knows nothing about actual disk files — it just stores a few
predefined paths and returns metadata and file contents in response to requests.
Let’s look at the key parts:
A Python dictionary (fs) holds a small set of files and their byte contents.
The /getattr endpoint returns a JSON version of struct stat for a given file path.
The /readdir endpoint lists all available files (we only support the root directory).
The /read endpoint returns a slice of the file contents, based on offset and size.
This is enough to make ls and cat work on the mounted filesystem. The client calls getattr and readdir to
explore the directory, and uses read to pull down bytes from the file.
End to End
With the server running and the client compiled, we can now bring it all together.
Start the Flask server in one terminal:
python server.py
Then, in another terminal, create a mountpoint and run the restfs client:
Now try interacting with your mounted filesystem just like any other directory:
➜ restmnt ls -l
total 1
-rw-r--r-- 1 michael michael 6 Jan 1 1970 data.bin
-rw-r--r-- 1 michael michael 15 Jan 1 1970 hello.txt
➜ restmnt cat hello.txt
Hello, RESTFS!
You should see logs from the server indicating incoming requests:
Under the hood, every file operation is being translated into a REST call, logged by the Flask server, and fulfilled
by your in-memory dictionary.
This is where the whole thing becomes delightfully real — you’ve mounted an HTTP API as if it were a native part of
your filesystem.
Conclusion
restfs is a fun and minimal example of what FUSE can unlock — filesystems that aren’t really filesystems at all.
Instead of reading from disk, we’re routing every file operation over HTTP, backed by a tiny REST server.
While this project is intentionally lightweight and a bit absurd, the underlying ideas are surprisingly practical.
FUSE is widely used for things like encrypted filesystems, network mounts, and user-space views over application state.
And libcurl remains a workhorse for robust HTTP communication in C programs.
What you’ve seen here is just the start. You could extend restfs to support writing files, persisting data to disk,
mounting a remote object store, or even representing entirely virtual data (like logs, metrics, or debug views).
Sometimes the best way to understand a system is to reinvent it — badly, on purpose.
When simulating physical systems—whether it’s a bouncing ball, orbiting planets, or particles under gravity—accurately
updating positions and velocities over time is crucial. This process is known as time integration, and it’s the
backbone of most game physics and real-time simulations.
In this post, we’ll explore two fundamental methods for time integration: Euler’s method and Runge-Kutta 4 (RK4).
We’ll go through how each of these methods is represented mathemtically, and then we’ll translate that into code.
We’ll build a small visual simulation in Python using pygame to see how the two methods behave differently when
applied to the same system.
The Simulation
Our simulation consists of a central massive object (a “sun”) and several orbiting bodies, similar to a simplified
solar system. Each body is influenced by the gravitational pull of the others, and we update their positions and
velocities in each frame of the simulation loop.
At the heart of this simulation lies a decision: how should we advance these objects forward in time? This is where the
integration method comes in.
Euler’s Method
Euler’s method is the simplest way to update motion over time. It uses the current velocity to update position, and the
current acceleration to update velocity:
This is easy to implement, but has a major downside: error accumulates quickly, especially in systems with strong
forces or rapidly changing directions.
Here’s an example of it running:
RK4
Runge-Kutta 4 (RK4) improves on Euler by sampling the system at multiple points within a single timestep. It estimates
what will happen halfway through the step, not just at the beginning. This gives a much better approximation of curved
motion and reduces numerical instability.
Runge-Kutta 4 samples the derivative at four points:
RK4 requires more code and computation, but the visual payoff is immediately clear: smoother orbits, fewer explosions,
and longer-lasting simulations.
Here’s an example of it running:
Trade-offs
Euler is fast and simple. It’s great for prototyping, simple games, or systems where precision isn’t critical.
RK4 is more accurate and stable, especially in chaotic or sensitive systems—but it’s computationally more expensive.
In real-time applications (like games), you’ll need to weigh performance vs. quality.
Also, both methods depend heavily on the size of the timestep. Larger steps amplify error; smaller ones improve
accuracy at the cost of performance.
Conclusion
Switching from Euler to RK4 doesn’t just mean writing more code—it fundamentally changes how your simulation evolves over time. If you’re seeing odd behaviors like spiraling orbits, exploding systems, or jittery motion, trying a higher-order integrator like RK4 might fix it.
Or, it might inspire a deeper dive into the world of numerical simulation—welcome to the rabbit hole!
You can find the full code listing here as a gist,
so you can tweak and run it for yourself.
I recently decided to dip my toes into ClojureScript. As someone who enjoys exploring different language ecosystems, I
figured getting a basic “Hello, World!” running in the browser would be a fun starting point. It turns out that even
this small journey taught me quite a bit about how ClojureScript projects are wired together.
This post captures my first successful setup: a minimal ClojureScript app compiled with lein-cljsbuild, rendering
output in the browser console.
A Rough Start
I began with the following command to create a new, blank project:
lein new cljtest
First job from here is to organise dependencies, and configure the build system for the project.
project.clj
There’s a few things to understand in the configuration of the project:
We add org.clojure/clojurescript "1.11.132" as a dependency
To assist with our builds, we add the plugin lein-cljsbuild "1.1.8"
The source path is normally src, but we change this for ClojureScript to src-cljs
The output will be javascript output for a website, and all of our web assets go into resources/public
We have two different build configurations here: dev and prod.
The dev configuration focuses on being much quicker to build so that the change / update cycle during development is
quicker. Source maps, pretty printing, and no optimisations provide the verbose output appropriate for debugging.
The prod configuration applies all the optimisations. This build is slower, but produces one single output file:
main.js. This is the configuration that you use to “ship” your application.
Your First ClojureScript File
Place this in src-cljs/cljtest/core.cljs:
(ns cljtest.core)
(enable-console-print!)
(println "Hello from ClojureScript!")
Then open resources/public/index.html in your browser, and check the developer console — you should see your message.
If you want to iterate while coding:
lein cljsbuild auto dev
When you’re ready to build a production bundle:
lein cljsbuild once prod
Then you can simplify the HTML:
<script src="js/main.js"></script>
No goog.require needed — it all gets bundled.
Step it up
Next, we’ll step up to something a little more useful. We’ll put together a table of names that we can add, edit,
delete, etc. Just a really simple CRUD style application.
In order to do this, we’re going to rely on a pretty cool library called reagent.
names is the currentl list of names. next-id gives us the next value that we’ll use an ID when adding a new
record. editing-id and edit-text manage the state for updates.
Table
We can now render our table using a simple function:
The table renders all of the names, as well and handles the create case. The edit case is a little more complex and
requires a function of its own. The name-row function manages this complexity for us.
<!doctype html><html><head><metacharset="utf-8"><title>cljtest</title></head><body><h1>cljtest</h1><!-- This is our new element! --><divid="app"></div><script src="js/out/goog/base.js"></script><script src="js/main.js"></script><script>goog.require('cljtest.core');cljtest.core.init();</script></body></html>
Conclusion
This journey started with a humble goal: get a simple ClojureScript app running in the browser. Along the way, I
tripped over version mismatches, namespace assumptions, and nested anonymous functions — but I also discovered the
elegance of Reagent and the power of functional UIs in ClojureScript.
While the setup using lein-cljsbuild and Reagent 1.0.0 may feel a bit dated, it’s still a solid way to learn the
fundamentals. From here, I’m looking forward to exploring more advanced tooling like Shadow CLJS, integrating external
JavaScript libraries, and building more interactive UIs.
This was my first real toe-dip into ClojureScript, and already I’m hooked. Stay tuned — there’s more to come.
Natural language processing (NLP) has gone through several paradigm shifts:
Bag-of-Words — treated text as unordered word counts; no sequence information. We’ve spoken about this previously.
Word Embeddings (word2vec, GloVe) — learned fixed-vector representations that captured meaning. We’ve looked at these previously.
RNNs, LSTMs, GRUs — processed sequences token-by-token, retaining a hidden state; struggled with long-range dependencies due to vanishing gradients.
Seq2Seq with Attention — attention helped the model “focus” on relevant input tokens; a leap in translation and summarization.
Transformers (Vaswani et al., 2017 — “Attention Is All You Need”) — replaced recurrence entirely with self-attention, allowing parallelization and longer context handling.
Transformers didn’t just improve accuracy; they unlocked the ability to scale models massively.
In this post, we’ll walk though an understanding of the transformer architecture by implementing a GPT-style
Transformer from scratch in PyTorch, from tokenization to text generation.
The goal: make the architecture concrete and understandable, not magical.
Overview
At a high level, our model will:
Tokenize text into integers.
Map tokens to dense embeddings + positional encodings.
Apply self-attention to mix contextual information.
Use feed-forward networks for per-token transformations.
Wrap attention + FFN in Transformer Blocks with residual connections and layer normalization.
Project back to vocabulary logits.
Generate text autoregressively.
graph TD
A[Text Input] --> B[Tokenizer]
B --> C[Token Embeddings + Positional Encoding]
C --> D[Transformer Block × N]
D --> E[Linear Projection to Vocabulary Size]
E --> F[Softmax Probabilities]
F --> G[Sample / Argmax Next Token]
G -->|Loop| C
Tokenization
Before our model can process text, we need to turn characters into numbers it can work with — a process called
tokenization. In this example, we use a simple byte-level tokenizer, which treats every UTF-8 byte as its own token.
This keeps the implementation minimal while still being able to represent any possible text without building a custom
vocabulary.
classByteTokenizer:"""
UTF-8 bytes <-> ints in [0..255].
NOTE: For production models you'd use a subword tokenizer (BPE, SentencePiece).
"""def__init__(self)->None:self.vocab_size=256defencode(self,text:str)->list[int]:returnlist(text.encode("utf-8"))defdecode(self,ids:list[int])->str:returnbytes(ids).decode("utf-8",errors="ignore")
Once we have token IDs, we map them into embedding vectors — learned dense representations that capture meaning in
a continuous space. Each token ID indexes a row in an embedding matrix, turning a discrete integer into a trainable
vector of size \(d_{\text{model}}\). Because self-attention alone has no sense of order, we also add
positional embeddings, giving the model information about each token’s position within the sequence.
That equation means each token computes a similarity score with all other tokens (via \(QK^\top\)), scales it
by \(\sqrt{d_k}\) to stabilize gradients, turns the scores into probabilities with softmax, and then uses those
probabilities to take a weighted sum of the value vectors \(V\) to produce its new representation.
Multi-head attention runs this in parallel on different projections.
Linear layer: expands to \(\text{mult} \times d_{\text{model}}\).
GELU activation: introduces non-linearity.
Linear layer: projects back to \(d_{\text{model}}\).
Dropout: randomly zeroes some activations during training for regularization.
Transformer Block
A Transformer block applies pre-layer normalization, then runs the data through either a multi-head self-attention
layer or a feed-forward network (FFN), and adds a residual connection after each. This structure is stacked multiple
times to deepen the model.
graph TD
A[Input] --> B[LayerNorm]
B --> C[Multi-Head Self-Attention]
C --> D[Residual Add]
D --> E[LayerNorm]
E --> F[Feed-Forward Network]
F --> G[Residual Add]
G --> H[Output to Next Block]
After token and position embeddings are summed, the data flows through a stack of Transformer blocks, each applying
self-attention and a feed-forward transformation with residual connections.
Once all blocks have run, we apply a final LayerNorm to normalize the hidden state vectors and keep training stable.
From there, each token’s hidden vector is projected back into vocabulary space — producing a vector of raw
scores (logits) for each possible token in the vocabulary.
We also use weight tying here: the projection matrix for mapping hidden vectors to logits is the same matrix as
the token embedding layer’s weights.
This reduces the number of parameters, ensures a consistent mapping between tokens and embeddings, and has been shown
to improve generalization.
Mathematically, weight tying can be expressed as:
\[\text{logits} = H \cdot E^\top\]
where \(H\) is the matrix of hidden states from the final Transformer layer, and \(E\) is the embedding matrix
from the input token embedding layer. This means the output projection reuses (shares) the same weights as the input
embedding, just transposed.
This method performs autoregressive text generation: we start with some initial tokens, repeatedly predict the
next token, append it, and feed the result back into the model.
Key concepts:
Autoregressive: generation proceeds one token at a time, conditioning on all tokens so far.
Temperature: scales the logits before softmax; values < 1.0 make predictions sharper/more confident, > 1.0 make them more random.
Top-k filtering: keeps only the k highest-probability tokens and sets all others to negative infinity before sampling, which limits randomness to plausible options.
Step-by-step in generate():
Crop context: keep only the last block_size tokens to match the model’s maximum context window.
Forward pass: get logits for each position in the sequence.
Select last step’s logits: we only want the prediction for the next token.
Adjust for temperature (optional).
Apply top-k filtering (optional).
Softmax: convert logits into a probability distribution.
Sample: randomly choose the next token according to the probabilities.
Append: add the new token to the sequence and repeat.
This loop continues until max_new_tokens tokens have been generated.
That concludes the entire stack that we need. We can start to ask questions of this very basic model. Just remember,
this is a tiny model so results are not going to be amazing, but it will give you a sense of how these tokens are
generated.
After training briefly on a small excerpt of Moby Dick plus a few Q/A lines, we can get:
Q: Why does he go to sea?
A: To drive off the spleen and regulate the circulation.
Even a tiny model learns local structure.
Conclusion
Even though this isn’t the perfect model that will challenge all of the big guys, I hope this has been a bit of a step
by step walkthough on how the transformer architecture is put together.
A full version of the code referenced in this article can be found here.
The code here includes the training loop so you can run it end-to-end.
D-Bus (Desktop Bus) is an inter-process communication (IPC) system
used on Linux and other Unix-like systems. It allows different programs — even running as different users — to send
messages and signals to each other without needing to know each other’s implementation details.
Main ideas
Message bus: A daemon (dbus-daemon) runs in the background and acts as a router for messages between applications.
Two main buses:
System bus – for communication between system services and user programs (e.g., NetworkManager, systemd, BlueZ).
Session bus – for communication between applications in a user’s desktop session (e.g., a file manager talking to a thumbnailer).
Communication model:
Method calls – like function calls between processes.
Interfaces – namespaces for methods/signals (e.g., org.freedesktop.NetworkManager.Device).
Here’s a visual representation of the architecture:
flowchart LR
subgraph AppLayer[User Applications]
A1[App 1]
A2[App 2]
end
subgraph DBusDaemon[D-Bus Daemon Message Bus]
D1[System Bus]
D2[Session Bus]
end
subgraph SysServices[System Services]
S1[NetworkManager]
S2[BlueZ Bluetooth]
S3[systemd-logind]
end
%% Connections
A1 --method calls or signals--> D2
A2 --method calls or signals--> D2
S1 --method calls or signals--> D1
S2 --method calls or signals--> D1
S3 --method calls or signals--> D1
%% Cross communication
D1 <-->|routes messages| A1
D1 <-->|routes messages| A2
D2 <-->|routes messages| A1
D2 <-->|routes messages| A2
%% System bus to service connections
D1 <-->|routes messages| S1
D1 <-->|routes messages| S2
D1 <-->|routes messages| S3
User applications call methods or raise signals to a Session Bus inside the D-Bus Daemon. In turn,
these messages are routed to System Services, with responses sent back to the applications via the bus.
D-Bus removes the need for each program to implement its own custom IPC protocol. It’s widely supported by desktop
environments, system services, and embedded Linux stacks.
In this article, we’ll walk through some basic D-Bus usage, building up to a few practical use cases.
busctl
busctl lets you interact with D-Bus from the terminal. According to the man page:
busctl may be used to introspect and monitor the D-Bus bus.
We can start by listing all connected peers:
busctl list
This shows a list of service names for software and services currently on your system’s bus.
Devices
If you have NetworkManager running, you’ll see org.freedesktop.NetworkManager in the list.
You can query all available devices with:
Tip:gdbus is part of the glib2 or glib2-tools package on many distributions.
This performs a method call on a D-Bus object.
--dest — The bus name (service) to talk to.
--object-path — The specific object inside that service.
--method — The method we want to invoke.
This method’s signature is s u s s s as a{sv} i, meaning:
Code
Type Description
Example Value
Meaning
s
string
"my-app"
Application name
u
uint32
0
Notification ID (0 = new)
s
string
""
Icon name/path
s
string
"Build finished"
Title
s
string
"All tests passed"
Body text
as
array of strings
'[]'
Action identifiers
a{sv}
dict<string, variant>
'{"urgency": <byte 1>}'
Hints (0=low, 1=normal, 2=critical)
i
int32
5000
Timeout (ms)
Monitoring
D-Bus also lets you watch messages as they pass through.
To monitor all system bus messages (root may be required):
busctl monitor --system
To filter for a specific destination:
busctl monitor org.freedesktop.NetworkManager
These commands stream events to your console in real time.
Conclusion
D-Bus is a quiet but powerful layer in modern Linux desktops and servers. Whether you’re inspecting running services,
wiring up automation, or building new desktop features, learning to speak D-Bus gives you a direct line into the heart
of the system. Once you’ve mastered a few core commands, the rest is just exploring available services and
imagining what you can automate next.