RSSAmplifier

Blog

Roman Cheplyaka

Articles by Roman Cheplyaka

ro-che.infoRSS feed ↗172 posts

Latest posts

Що брати з собою на БЗВП?

Пакуєте речі на БЗВП і не знаєте, що брати або докупляти? Сподіваюсь, що цей список речей з коментарями стане вам у нагоді. Для контексту, я проходив БЗВП влітку 2026 року, на 5-му році своєї військової служби 1 , в одному з навчальних центрів НГУ. Загалом побутові умови можуть сильно відрізнятися між навчальними центрами. Мені пощастило: ми проживали в сучасній казармі, з душами, пральними…

Рейтинги шахових розрядів і звань

Якщо ви переважно граєте в шахи онлайн, ви могли задаватися питанням, якому шаховому розряду або званню відповідає ваш рівень гри. Отже, я провів невеличкий аналіз, щоб визначити приблизний діапазон рейтингів FIDE, який відповідає кожному розряду і званню в Україні. Оцінити свій рейтинг FIDE можна, скориставшись chessmonitor.com або chess-analysis.org . Розряд/звання Від (10%) Медіана До (90%) III…

Alice and Bob flipping coins puzzle

Daniel Litt on Twitter suggests a puzzle with a surprising answer: Flip a fair coin 100 times—it gives a sequence of heads (H) and tails (T). For each HH in the sequence of flips, Alice gets a point; for each HT, Bob does, so e.g. for the sequence THHHT Alice gets 2 points and Bob gets 1 point. Who is most likely to win? — Daniel Litt ( @littmath ) March 16, 2024 Like many others, I intuitively…

Sum of random cards puzzle

Here’s a nice puzzle, via Christian Lawson-Perfect and Tanya Khovanova : There are 100 cards with integers from 1 to 100. You have three possible scenarios: you pick 18, 19, or 20 cards at random. For each scenario, you need to estimate the probability that the sum of the cards is even. You do not need to do the exact calculation; you just need to say whether the probability is less than, equal…

AeroPress Go measurements. What volume do AeroPress marks correspond to?

As a new owner of an AeroPress Go coffee brewer, I was surprised not to be able to find (either in the manufacturer’s manual or online) what the circle marks on the AeroPress chamber correspond to, or how much ground coffee fits into the included scoop. So here are my own measurements. They all assume the non-inverted brewing method with a single standard paper filter. AeroPress Go Chamber volume…

How much current does an active bass guitar draw from a 9V battery?

The 9V battery in my bass guitar tends to die rather often, and so I wanted to measure how much current the bass draws. My bass is a Squier Jazz Bass with an active on-board preamp but passive pickups (there are only two wires going to the pickups, as shown below). Some basses have active pickups, and so their measurements may not be comparable to mine. The electronics inside my bass So here are…

A data structure puzzle

Jarno Alanko offered this puzzle on twitter: Fun but difficult data structure puzzle with an elegant solution: Suppose we have an oracle to a permutation f on n elements. Describe a data structure taking O(sqrt(n)) space that can compute the inverse f^(-1)(x) for any x in O(sqrt(n)) time. — Jarno N. Alanko ( @jnalanko ) May 22, 2021 Here’s my solution. It’s a programmer’s solution: it assumes that…

Understanding modern Linux routing (and wg-quick)

Back in the old days, I could just type route (or, later, ip route ) in my Linux terminal and get an accurate picture of all my routes. This is no longer the case. For instance, the machine where I’m writing this is connected to the Mullvad VPN via the Wireguard protocol using the wg-quick script. I’m pretty sure all my traffic goes through Mullvad, yet you wouldn’t be able to tell this from my ip…

My podcast editing workflow in REAPER

I divide podcast post-production into two parts: Editing: cutting and moving the audio around. This includes reducing pauses (or sometimes adding them), removing parts that didn’t turn out interesting, and cutting out some excessive filler sounds. The goal here is to make the conversation concise, engaging, and easy to listen to. Mixing: figuring out which plugins/effects to apply so that the…

StateT vs. IORef: a benchmark

Sometimes I’m writing an IO loop in Haskell, and I need some sort of a counter or accumulator. The two main options are to use a mutable reference (IORef) or to put a StateT transformer on top the IO monad. I was curious, though, if there was a difference in efficiency between these two approaches. Intuitively, IORefs are dedicated heap objects, while a StateT transformer’s state becomes “just” a…

Laptop vs. desktop for compiling Haskell code

I’ve been using various laptops as daily drivers for the last 12 years, and I’ve never felt they were inadequate — until this year. There were a few things that made me put together a desktop PC last month, but a big reason was to improve my Haskell compilation experience on big projects. So let’s test how fast Haskell code compiles on a laptop vs. a desktop. Specs Laptop Desktop CPU Intel Core…

system2 in R considered inadequate

When you need to run another program (executable) from your program, there are two different ways to go about it: to run the executable directly, or to go through the shell. “Going through the shell” means that instead of running the executable you want to run, your program will run the shell, /bin/sh , which in turn will be told (via the -c option) to run the executable you want. Why would one…

Sort directories by the newest file

If you need to clean up a file system (especially your $HOME directory from some ancient dot-files), it may be useful to sort the top-level directories by the last modified time of any file inside them. Here’s the command I came up with: find -printf '%T@/%P\n' | awk -F / \ '{t[$2] = t[$2] > $1 ? t[$2] : $1} END { PROCINFO["sorted_in"] = "@val_num_asc"; for (key in t) { printf "%s\t%s\n",…

Don't buy tempered glass PC cases

For my new desktop PC, I got the PURE BASE 500 Window Black case from “be quiet!”. On the first day of trying to use it, here’s what happened after a small bump of the edge against the floor: Shattered glass side panel of a desktop case It may not be obvious from the picture, but it’s not like the panel was usable in this state: it started to crumble even while I was carrying it to the trash can.…

Avoid the months() and years() functions from lubridate

lubridate is an R/tidyverse package for dealing with dates and times. One of its nice features is the date arithmetics: you can take a date, such as ymd("2020-08-30") , add an interval (such as days(10) ), and get a new date ( "2020-09-09" ). In addition to days() , you can modify dates with months() and years() . However, I would argue you almost never want to use these two functions. I am…

Configuring PulseAudio for Audient EVO 4

For about a month now, I’ve been using the Audient EVO 4 audio interface. One of its features is “audio loopback”, where it can capture your computer audio and send it as if it were coming from your microphone. Unfortunately, when used with its default PulseAudio configuration on Linux, this feature is turned on by default. As a result, your peers on a video call will be hearing themselves (unless…

How I integrate ghcid with vim/neovim

ghcid by Neil Mitchell is a simple but robust tool to get instant error messages for your Haskell code. For the most part, it doesn’t require any integration with your editor or IDE, which is exactly what makes it robust—if you can run ghci, you can run ghcid. There’s one feature though for which the editor and ghcid have to talk to one another: the ability to quickly jump to the location of the…

Which dynamic mic should you buy?

Shawn Milochik has published a cool blind test of dynamic microphones . Go take it yourself and choose which ones you prefer. But also, if you don’t have time for that or would like to know what I think, here’s my rating of Shawn’s dynamic mics based on his recordings. Favorite Shure SM7B ($400) Very good Samson Q2U ($60) Electro-Voice RE20 ($450) Good Behringer XM8500 ($23) Sennheiser MD 441U…

Visualizing Haskell heap profiles in 2020

Heap profiling is a feature of the Glasgow Haskell Compiler (GHC) that lets a program record its own memory usage by type, module, cost center, or other attribute, and write it to a program.hp file. Here I review the existing tools—and introduce a new one—for visualizing and analyzing these profiles. hp2ps hp2ps is the standard heap profile visualizer, as it comes bundled with GHC. Run it as hp2ps…

Compile and link a Haskell package against a local C library

Let’s say you want to build a Haskell package with a locally built version of a C library for testing/debugging purposes. Doing this is easy once you know the right option names, but finding this information took me some time, so I’m recording it here for the reference. Let’s say the headers of your local library are in /home/user/src/mylib/include and the library files ( *.so or *.a ) are in…

Binomial coefficients via integer division

Daniel Lemire explains how to compute binomial coefficients using only integer multiplications. The binomial coefficient \(n \choose k\) is defined as \[ {n \choose k} = \frac{n!}{k! (n-k)!} = \frac{n(n-1)\cdots(n-k+1)}{1\cdot 2\cdots k}. \] Daniel’s strategy of computing binomial coefficients consists of two steps. First, he expresses the binomial coefficient as an iterative computation \[…

Does micro-USB cable affect charging speed?

How much does a micro-USB cable affect the charging speed of your phone? Should you pay extra for a premium-quality cable? To find this out, I ran a small experiment. The experimental setup For this experiment, I tried all combinations of four micro-USB cables I had lying around, two USB chargers, and three devices to be charged: a Sony smartphone running Android, a Samsung tablet also running…

Break on NaN in gdb

Recently I had to debug a case where, somewhere during a numerically-intensive computation (solving an ordinary differential equation), a value would become NaN (“not a number”). This happens, for example, when taking a logarithm or a square root of a negative number, dividing 0 by 0, stuff like that. However, I had no idea where and why NaNs appeared in this particular program. So here I’ll show…

Significance level vs. the type I error chance, or how to interpret conditionals

One of the 12 p-value misconceptions states: With a \(P = .05\) threshold for significance, the chance of a type I error will be 5%. I find this to be a particularly counter-intuitive one. Recall that the type I error occurs when we reject the null hypothesis if the null hypothesis is in fact true. Therefore, the chance of committing a type I error is \(p(\text{reject } H_0 | H_0\text{ is true})\)…

Bioinformatics events in Europe in 2020

Here are some conferences and summer schools that will take place in Europe in 2020 and may be of interest to fellow bioinformaticians. Previous editions: 2018 , 2019 . Event Dates Location Early registration price Early registration deadline Data Structures in Bioinformatics February 3–5 Rennes, France Free January 20 Woodstock.Bio February 13–14 Tel-Aviv, Israel Free Applied Bioinformatics in…

Long-term reminders

By long-term reminders I mean things that are not actionable right now, but at some point in the future become important to take care of: cancel a subscription or a credit card, renew a passport/visa/driver’s license etc. At one point I used nudgemail for this. However, I ran into a pretty serious date parsing/scheduling bug: I had two reminders, one for October 6 and one for October 20, and both…

A blind microphone comparison

Like many other podcasters, I like obsessing over different microphones and watching mic reviews. Unfortunately, most of these reviews are not blind, and so your impression is inevitably affected by how the microphone looks, what its price is, opinions you’ve heard about the mic etc. So here’s a blind test of the three microphones that I currently own. Feel free to tell me both your subjective…

A curious associativity of the <$> operator

The <$> operator in Haskell is an infix synonym for fmap and has the type (<$>) :: Functor f => (a -> b) -> f a -> f b For example: > negate <$> Just 5 Just ( - 5 ) Like all other operators, <$> has a fixity , which can be infixl , infixr , or infix . The fixity defines how an expression like abs <$> negate <$> Just 5 is parsed. If <$> were defined as infix , then the above expression wouldn’t…

Decompose ContT

Can we decompose a ContT action into separate acquire and release functions? Motivation Consider some resource, such as a file handle, socket, database connection etc. The two actions common to all resources are acquiring and releasing. There are two ways to represent these actions: as a pair of functions acquireResource :: IO Resource releaseResource :: Resource -> IO () or as a single function…

Why would you use ContT?

The ContT transformer is one of the more exotic and less used transformers provided by mtl. The Control.Monad.Cont module now even includes the following warning: Before using the Continuation monad, be sure that you have a firm understanding of continuation-passing style and that continuations represent the best solution to your particular design problem. Many algorithms which require…

How (not) to convert CDouble to Double

What’s wrong with the following code? module Acos ( acos ) where import Prelude hiding (acos) import Foreign.C.Types ( CDouble (..)) foreign import ccall "math.h acos" c_acos :: CDouble -> CDouble acos :: Double -> Double acos = realToFrac . c_acos . realToFrac If you use QuickCheck to test the equivalence of Acos.acos and Prelude.acos , you’ll quickly find a counterexample: > Prelude.acos 1.1 NaN…

Fix a torrent file encoding

Sometimes, when you open a torrent file, the non-Latin letters in the file names will appear garbled. Apparently, some programs write the utf-8 name in the field path.utf-8 and write the field path in some other encoding. I wrote a small Perl script that fixes such torrent files by copying the path.utf-8 field into the path field. To fix the torrent file: Download the script . Make sure you have…

Lazy validation

Why lazy validation? The Validation applicative functor is a convenient tool for checking anything for errors. It’s similar to the Either type, but its Applicative instance works differently. Whereas an Either computation stops at the very first Left value, a Validation computation continues, collecting all other errors so they all can be presented to the user at once. I gave a more detailed…

Surprises of the Haskell module system (part 2)

It’s been 6 years since I published Surprises of the Haskell module system (part 1) , so I thought it was time to follow through on the implicit promise and publish part 2. Exporting constructors without data type Is it possible to export a data constructor without exporting its parent data type? To be clear, there’s probably no good reason to want to do that, but it’s a fun puzzle, and we’ll…

A better noise gate

A noise gate is a type of sound effect. It detects the parts of the audio signal with very low volume, where nothing is happening apart from the background noise, and either reduces the volume further or silences it completely. It doesn’t remove the noise from under the speech—that’s called noise reduction —but it removes the noise between the phrases. Back when audio processing was analog and…

Homology, similarity, and alignment

Although homology, similarity, and alignment are all relatively well defined notions in biology and computer science, scientists sometimes get confused about their meaning or the relationships between them. The results range from annoyed colleagues to very annoyed colleagues . So let’s sort these things out. Definitions To keep things simple and concrete, I’ll be mostly talking about DNA…

Bioinformatics events in Europe in 2019

Continuing the tradition from last year , here are some conferences and summer schools that will take place in Europe in 2019 and may be of interest to fellow bioinformaticians. I’ll be doing more curation this time, so the list will be shorter but with higher signal to noise ratio. Event Dates Location Early registration price Early registration deadline Revolutionizing Next-Generation Sequencing…

Tasty 1.2 supports dependencies between tests

Tasty ( GitHub , Hackage ) is a versatile and extensible testing framework for Haskell. Using tasty, you can quickly create a test suite consisting of unit tests, property tests and golden tests . Users of tasty benefit from automatic parallelism, a rich filtering language to choose which tests to run, sharing resources between tests and more. Tasty 1.2 adds another long-awaited feature:…

How do I record a podcast remotely? SquadCast vs. Zencastr vs. Cast vs. other options

One of the most frequent questions beginner (and many experienced) podcasters have is “how do I record a podcast with my co-hosts/guests being far away?” If you want a simple recommendation, then use SquadCast . This is my own service of choice since July 2020, and so far I’ve been pretty happy with it. If you want to explore other options, first let me explain which factors to look at when…

How to pass a logical matrix to RStan

I ran into this problem with RStan today, and I’m sure I’ve had it at least once in the past, and it took me a ridiculously long time to figure out, so I’m documenting it here. Suppose you need to pass a multidimensional logical array to RStan ( events in the example below). The details of the model don’t matter; let’s say it’s a simple beta-binomial model: model <- stan_model ( auto_write = T,…

Estimating the fraction of recurring events

Sometimes you have a collection of events and the number of times each of them occurred. Each event is either unique, i.e. occurring only once, or recurring. You don’t know which events are unique or recurring, but you want to estimate the fraction of recurring events. I’ll give two examples, one from everyday life and one from bioinformatics. Everyday life example. Let’s say you’re a small…

logit() and logistic() functions in R

In statistics, a pair of standard functions logit() and logistic() are defined as follows: \[ \begin{align*} \operatorname{logit}(p) &= \log\frac{p}{1-p}; \\ \operatorname{logistic}(x) &= \frac{1}{1+\exp(-x)}. \end{align*} \] Given the ubiquity of these functions, it may be puzzling and frustrating for an R user that there are no pre-defined functions logit() and logistic() in R. > logit(0.6)…

Can you cheat the Brier score?

The Brier score is a common way of judging probabilistic forecasts. If you have several people or teams each giving probabilities to various events, you can judge how well they are doing by comparing their Brier scores: lower scores correspond to more accurate predictions. However, there is a critical assumption behind the Brier score: that all forecasters compete on the same set of events. Some…

Probability of a regex occurrence

Given a regular expression \(R\) and a random string \(L\) of length \(n\) , what is the probability that \(R\) matches somewhere in \(L\) ? This seems like an intimidating problem at first, but I was surprised how easy it becomes after a couple of insights. The first insight is to turn a regex into a DFA . This moves us from “how can I possibly know whether a regex matches?” to “feed the string…

Combine ChIP-seq peaks from multiple replicates via consensus voting

As in most of biology, having biological replicates in ChIP-seq experiments is important to ensure external validity . Or, in simpler words, your low-q-value peak from a single sample only means that the peak was definitely there in this one sample. Without replicates, you don’t know if this peak is reliably there across samples or was specific to that one sample at that one time. So, in order to…

Sometimes all you need is to cut adapters

When you see a FastQC box like this, you know that something is wrong. FastQC summary box But what exactly? Overrepresented sequences may indicate adapters (although, ironically, the Adapter Content is one of the few green check marks here), and duplicated sequences could be removed, but what do you do about the GC levels, per base sequence content, and per tile quality bias? Here’s the table of…

Encrypted reminders with Nudgemail

I use Trello as my main GTD tool, and it works great for the short-term stuff. Sometimes, however, I have a task that I won’t be able to do until 4 months later. While I could create a Trello card and set its due date to October 20th, I will keep seeing it every time I review my trello board. Each time I’ll be reminded of this relatively unpleasant task, adding up to a significant mental cost. The…

QuickCheck vs. SmallCheck

QuickCheck and SmallCheck are the two classical libraries for property testing in Haskell. There are newer developments, like SmartCheck and Hedgehog , but I haven’t tried them much yet. So here is my take on the comparative strengths and weaknesses of the current versions of QuickCheck and SmallCheck (2.11.3 and 1.1.4, respectively). Being the maintainer of SmallCheck, I am obviously somewhat…

Disable Sony What's New notifications

If you have a Sony smartphone, you noticed the annoying notifications from Sony’s built-in WhatsNew app. They look like this: Sony also made it impossible to disable the app or block the notifications through the usual means. Where normally you’d see an option to block all of the app’s notifications or disable the app itself, there are no such options for WhatsNew. So for a long time I assumed…

What is this weird math letter?

Occasionally I would read a mathematics paper or book and see a strange calligraphic symbol that I have no idea how to pronounce. Like here: Or here: This is a problem because I, as most other people, struggle to read what I can’t pronounce even when not reading aloud. When you encounter a symbol like this (which belongs to a family of typefaces called formal scripts ), just look it up in the…