Planet dgplug

July 05, 2020

Nabarun Pal

Running Tor Proxy with Docker

Today I was testing dns-tor-proxy which required a SOCKS5 Tor proxy and realized I never ran a Tor service on my current machine. I use Tor browser almost daily for browsing websites I have absolutely no trust on, but not the standalone Tor proxy. In this article, I will try to set one up using the system package as well as inside a Docker container. What is a Tor proxy? A Tor proxy is a SOCKS5 proxy which routes your traffic through the Tor network.

July 05, 2020 10:15 AM

Kushal Das

dns-tor-proxy 0.2.0 aka DoH release

I just now released 0.2.0 of the dns-tor-proxy tool. The main feature of this release is DNS over HTTPS support. At first I started writing it from scratch, and then decided to use modified code from the amazing dns-over-https project instead.


demo of the DoH support in the tool

✦ ❯ ./dns-tor-proxy -h
Usage of ./dns-tor-proxy:
      --doh                 Use DoH servers as upstream.
      --dohaddress string   The DoH server address. (default "")
  -h, --help                Prints the help message and exists.
      --port int            Port on which the tool will listen. (default 53)
      --proxy string        The Tor SOCKS5 proxy to connect locally, IP:PORT format. (default "")
      --server string       The DNS server to connect IP:PORT format. (default "")
  -v, --version             Prints the version and exists.
Make sure that your Tor process is running and has a SOCKS proxy enabled.

Now you can pass --doh flag to enable DoH server usage, by default it will use But you can pass any server using --dohaddress flag. I found the following servers are working well over Tor.

  • https://dns4torpnlfs2ifuz2s2yf3fc7rdmsbhm6rw75euj35pac6ap25zgqad.onion/dns-query

The release also has a binary executable for Linux x86_64. You can verify the executable using the signature file available in the release page.

July 05, 2020 05:31 AM

July 02, 2020

Jason Braganza (Work)

Emacs, Day 05

Practiced moving around with the Emacs keys for 30 mins

by Mario Jason Braganza at July 02, 2020 12:06 PM

July 01, 2020

Kushal Das

Introducing dns-tor-proxy, a new way to do all of your DNS calls over Tor

dns-tor-proxy is a small DNS server which you can run in your local system along with the Tor process. It will use the SOCKS5 proxy provided from Tor, and route all of your DNS queries over encrypted connections via Tor.

By default the tool will use (from Cloudflare) as the upstream server, but as the network calls will happen over Tor, this will provide you better privacy than using directly.

In this first release I am only providing source packages, maybe in future I will add binaries so that people can download and use them directly.


In the following demo I am building the tool, running it at port 5300, and then using dig to find the IP addresses for and

demo of dns tor proxy

The -h flag will show you all the available configurable options.

./dns-tor-proxy -h

Usage of ./dns-tor-proxy:
  -h, --help            Prints the help message and exists.
      --port int        Port on which the tool will listen. (default 53)
      --proxy string    The Tor SOCKS5 proxy to connect locally,  IP:PORT format. (default "")
      --server string   The DNS server to connect IP:PORT format. (default "")
  -v, --version         Prints the version and exists.
Make sure that your Tor process is running and has a SOCKS proxy enabled.

July 01, 2020 04:20 AM

June 30, 2020

Nabarun Pal

It's always DNS!

Context I was running Airflow inside a Kubernetes cluster but the Airflow pods were not able to connect with the PostgreSQL database running inside the cluster. The following was consistently seen in the Airflow logs, although the postgres-airflow service was up and running. sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "postgres-airflow" to address: Temporary failure in name resolution For the rest of this post, we will assume that all the user run components inside the cluster are running perfectly and focus on what is causing the name resolution errors.

June 30, 2020 12:00 AM

June 22, 2020

Anwesha Das

PyLadies India embarked its journey

PyLadies India embarked its journey

20th June 2020 marked a new beginning for PyLadies in India. We had our first meetup.


I started my journey with PyLadies in 2016 as an organizer of PyLadies Pune. It began with a personal itch of the lawyer who wanted to learn Python. I revived the PyLadies Pune. We had meetups within our local limits, and everything was hunky-dory.

But PyCon India 2016 gave us the platform to peep into more larger picture. The Pythonistas in India, though divided by language, culture, geographical location nevertheless, our stories are similar. Men predominate the Indian Python community (then and so as now, unfortunately). And the community members who identify themselves as women found their place in that small PyLadies Pune booth. We shared our stories, our journey, and found out how similar they were. From the first day where I was going and telling who are we “PyLadies” and getting some not so good reaction. At the end of the conference, there was acceptance, respect, and recognition by the same people. We ended PyCon India 2016 in success with the initiation of one new chapter, PyLadies Delhi. And we realized united we stand. From then every PyCon India, we had at least a new chapter coming up. With a little bit of push, support, and help, I had some amazing ladies coming up, leading, and sharing the Pyladies baton in India. Now we have 8 + PyLadies chapters in India and many more to come. They make me feel happy, proud. But more than that, I think I have them to lean on, with whom the future of PyLadies India is safe and secure.

The chapters were running fine in their places and with a meeting every year in PyCon India. We were somewhat happy. But we felt the need for a united organization, with all the chapters being a part of it. It will be the face of PyLadies in India. A place where we will decide the future course of us, PyLadies in India. The talks were on for quite sometimes, but now the pandemic has allowed us to embark on this journey. In these times, it is a necessity to move all our meetups to an online platform. Also, it has given us every chapter to increase their reach and not be bound by the local limits.

But it came with a bunch of challenges to the chapter organizers -
a. to decide on the online platform,
b. increase the bandwidth of organizers to help set up the platform and run the online event,
c. it has opened up a lot more choice of sessions for PyLadies across India and Globe to attend and be a part of.

So in the above circumstances, we, different PyLadies chapters in India, have decided to come up with a single meetup. Each month all the chapters in India will put up a session together. But of course, if any chapter wants to have their meet up, they are free to do it. There is no rationing on the meetups. The only thing we will have to try to make sure that we do not collide on the dates. So here are we with the first Pyladies India session. It will not be an exaggeration to state that we owe this pandemic for this :)

The team got into planning and working for the same. Social media, Creatives, preparing the platform for the broadcast, av, and other settings. I, along with my amazing PyLadies Nancy, Sakshi, Vaishnavi, and Niharika, were busy and on our toes. The choice of my speaker for the first PyLadies India session was natural. We were unanimous the First Women C-Python Core Developer to be our speaker. All of us wanted Marriata. And I can not thank her enough for being ever helpful and saying yes to come to take the session, and all it took me to message her. We wanted the session introductory, so the people who are starting their journey with PyLadies India will be able to start and grow with us. So she suggested that for a tutorial on Github Bots and we readily agreed to the idea.

The plan for 20th was all set. I will introduce us, PyLadies India. Then Marriata will let us know what is happening in the field of Global PyLadies, she will take the session on Github Bot, and I will moderate the whole session. But my health (umm age) pulled my excitement down. I had to undergo gum and tooth surgery, which needed me not to talk. Then Niharika came into rescue. She gave the voice to my thoughts.

The session ended in all happy note. The people very well received Marriata’s session for being detailed and smooth.

We can not wait to meet again, follow us on Twitter, Instagram, and subscribe to our youtube channel. Some of us now may want to thank the pandemic for this opportunity :) Thank you, PyLadies, au revoir.

by Anwesha Das at June 22, 2020 09:36 AM

Robin Schubert

Python + pandas + matplotlib vs. R + tidyverse - a quick comparison


When I started this blog post, my intention was to compare basic data wrangling and plotting in Python and R. I write most of my code in Python, doing mostly scientific stuff, data wrangling, basic statistics and plots. However, although the pandas framework has been built to resemble R's data.frame class, the functional programming style that R provides with the tidyverse - or rather with the %>% operator of the magittr package - often give a way more natural feeling when handling data.

To be honest, I was sure, that the tidyverse packages would out-perform pandas; however, looking at the code snippets now, I must admit that the difference is less obvious than I previously thought. Still, in more complex situations, Python code - in comparison - looks more verbose, while R seems to be more concise and consistent.

Plotting may be a different story, but to make a fair comparison here, I would have to take the variety of plotting libraries into account that the Python ecosystem offers, however this would be far out of the scope of this post.

The ggplot2 package on the other hand, has been developed as an implementation of"Grammar of Graphics", a philosophy by Leland Wilkinson that divides visualizations into semantic components. This implementation provides an huge flexibility, as we'll see later.

Setting it up

Traditionally, the popular iris data set is used to demonstrate data wrangling, but in the given situation let's play around with the Johns Hopkins University COVID-19 data from github. As an example, the time series of global confirmed cases can be accessed here.

Let's set up our working environments and load the three data sets confirmed, recovered and deaths in R and Python.



base_url <- ""
confirmed <- read.csv(paste0(base_url, "time_series_covid19_confirmed_global.csv"))
recovered <- read.csv(paste0(base_url, "time_series_covid19_recovered_global.csv"))
deaths <- read.csv(paste0(base_url, "time_series_covid19_deaths_global.csv"))


##   Province.State      country.Region      Lat     Long X1.22.20 X1.23.20   ...
## 1                        Afghanistan  33.0000  65.0000        0        0
## 2                            Albania  41.1533  20.1683        0        0
## 3                            Algeria  28.0339   1.6596        0        0
## 4                            Andorra  42.5063   1.5218        0        0
## 5                             Angola -11.2027  17.8739        0        0
## 6                Antigua and Barbuda  17.0608 -61.7964        0        0
## ...


import pandas as pd

base_url = ""
confirmed = pd.read_csv(base_url + "time_series_covid19_confirmed_global.csv")
recovered = pd.read_csv(base_url + "time_series_covid19_recovered_global.csv")
deaths = pd.read_csv(base_url + "time_series_covid19_deaths_global.csv")


#   Province/State Country/Region      Lat     Long  1/22/20  1/23/20  1/24/20  ...
# 0            NaN    Afghanistan  33.0000  65.0000        0        0        0  ...
# 1            NaN        Albania  41.1533  20.1683        0        0        0  ...
# 2            NaN        Algeria  28.0339   1.6596        0        0        0  ...
# 3            NaN        Andorra  42.5063   1.5218        0        0        0  ...
# 4            NaN         Angola -11.2027  17.8739        0        0        0  ...

So far, so similar. When looking at the loaded data sets, we see that the format is kind of ugly. These are time series with names of states and countries in the first two columns, latitude and longitude coordinates in the third and forth, and one column per day for the following rest of the set, containing the numbers of confirmed / recovered / deaths reported for the country/region.

To make working with the data easier, I want to transform them to a long format, having a single column date with all the dates and a column confirmed (or recovered and deaths respectively) with the corresponding number of cases.

In R we could do the following:

confirmed_long <- confirmed %>%
    c(-`Province.State`, -`Country.Region`, -Lat, -Long),
    values_to="confirmed") %>%
  mutate(date = as.Date(date, format = "X%m.%d.%y"))


##   Province.State Country.Region   Lat  Long date       confirmed
##   <fct>          <fct>          <dbl> <dbl> <date>         <int>
## 1 ""             Afghanistan       33    65 2020-01-22         0
## 2 ""             Afghanistan       33    65 2020-01-23         0
## 3 ""             Afghanistan       33    65 2020-01-24         0
## 4 ""             Afghanistan       33    65 2020-01-25         0
## 5 ""             Afghanistan       33    65 2020-01-26         0
## 6 ""             Afghanistan       33    65 2020-01-27         0

very similarly in Python:

confirmed_long = pd.melt(
    id_vars = ["Province/State", "Country/Region", "Lat", "Long"],
    var_name = "date",
    value_name = "confirmed")\
    .assign(date = lambda x: pd.to_datetime(


#   Province/State Country/Region      Lat     Long       date  confirmed
# 0            NaN    Afghanistan  33.0000  65.0000 2020-01-22          0
# 1            NaN        Albania  41.1533  20.1683 2020-01-22          0
# 2            NaN        Algeria  28.0339   1.6596 2020-01-22          0
# 3            NaN        Andorra  42.5063   1.5218 2020-01-22          0
# 4            NaN         Angola -11.2027  17.8739 2020-01-22          0

As you can see, I took the opportunity to also parse the strings in the date column to datetime. While in R we can pipe the output of the previous command into the next with the %>% operator, we achieve a very similar affect using pandas' assign function.

We can do the same with the remaining two data sets. However, we have plenty of redundant information, since all three data sets will be the same apart from the confirmed, reconvered and deaths columns. So let's merge them into one data frame. Also I don't care about single provinces and states but rather want to sum up the data country-wise. This will mess up our latitudes and longitudes, so I just drop them here.


covid_long <- confirmed_long %>%
  left_join(recovered_long) %>%
  left_join(deaths_long) %>%
  select(-Lat, -Long, -Province.State) %>%
  group_by(Country.Region, date) %>%


covid_long = pd.merge(

We're ready to look at some plots. I would like to see a line plot that shows us the numbers of confirmed, recovered and death cases against the time, on a log transformed scale. Different countries should be coded in colors, the confirmed, recovered and deaths lines should be coded in line styles.

Let's have a look at the Python code first:

# first I merge the three data sets into one, drop some columns
# I'm not interested in and sum the numbers by country, as I don't
# want to look at specific states here.

covid_long = pd.merge(
    .drop(["Lat", "Long"], axis = 1)\
    .groupby(["Country/Region", "date"])\

# I define a list of three countries I want to see in the plot

countries = ["US", "Germany", "India"]

# and set the y-scale of my axes object to log scale, since we expect
# exponential growth

fig, ax = plt.subplots()

for country in countries:
    covid_long.query('`Country/Region` == @country')\
              .plot(x="date", y="confirmed", ax=ax, label=country)

So far, these are just the numbers of confirmed cases. For plots in matplotlib, I know no better way than to plot the different countries sequentially or in a loop. To add the other cases, I add another loop.

# to plot confirmed, recovered and deaths cases in one plot
# we have to put a little effort into it

# we need a set of colors for our countries and a set of styles
# for the different status attributes

colors = plt.get_cmap('Set1', len(countries))

styles = ['-', '--', '.']

fig, ax = plt.subplots()

for i, status in enumerate(['confirmed', 'recovered', 'deaths']):
    for j, country in enumerate(countries):
        covid_long.query('`Country/Region` == @country')\
                            label=f"{country} - {status}",

While this is a bit messy in a single plot, we can use multiple subplots instead of line style, to show different status.

# we can split this up into multiple subplots for better overview

fig, ax = plt.subplots(3, 1)

for i, status in enumerate(['confirmed', 'recovered', 'deaths']):
    for j, country in enumerate(countries):
        covid_long.query('`Country/Region` == @country')\

Finally, I want to compute the deviation of confirmed cases, to get the daily growth. Here's how I would do it with pandas:

# we pivot the table and compute the deviation. I don't know
# a more elegant way that to do it in multiple steps

covid_even_longer = pd.melt(
    id_vars = ["Country/Region", "date"],
    var_name = "status",
    value_name = "count")

covid_even_longer.loc[:, 'lagged'] = (covid_even_longer\
                                      .sort_values(by=['date'], ascending=True)\
                                      .groupby(['Country/Region', 'status'])['count']\

covid_even_longer = covid_even_longer\
    .assign(deviation = lambda x: x['lagged'] - x['count'])

fig, ax = plt.subplots()

for i, country in enumerate(countries):
    covid_even_longer.query('`Country/Region` == @country and status == "confirmed"')\

So now to have a direct comparison, here's the tidyverse way to achieve the above results:

## we define a vector of countries we want to look at
countries <- c("US", "Germany", "India")

## plot the confirmed, recovered and deaths cases in one plot
## we again pivot our table and make use of ggplots aesthetics

covid_long %>%
  filter(Country.Region %in% countries) %>%
  pivot_longer(cols = c("confirmed", "recovered", "deaths"),
               names_to = "status",
               values_to = "count") %>%
  ggplot(aes(x = date, y = count, color = Country.Region)) +
    geom_line(aes(linetype = status), size = 1.2) +

## this looks a bit chaotic in a single plot, we can also use
## facet_grid to break this up into sub-plots

covid_long %>%
  filter(Country.Region %in% countries) %>%
  pivot_longer(cols = c("confirmed", "recovered", "deaths"),
               names_to = "status",
               values_to = "count") %>%
  ggplot(aes(x = date, y = count, color = Country.Region)) +
    facet_grid("status") +
    geom_line(size = 1.2) +

## it's easy to on-the-fly calculate a deviation to get daily
## change rates by groups and pipe the resulting dataframe into
## the plotting function again

covid_long %>%
  filter(Country.Region %in% countries) %>%
  pivot_longer(cols = c("confirmed", "recovered", "deaths"),
               names_to = "status",
               values_to = "count") %>%
  group_by(Country.Region, status) %>%
  mutate(deviation = lead(count) - count) %>%
  ungroup() %>%
  filter(status == "confirmed") %>%
  ggplot(aes(x = date, y = deviation, color = Country.Region)) +
    geom_line(aes(linetype = status), size = 1.2)


While there hardly any difference visible for simpler data transformations, merging and pivoting, the Python syntax becomes quite verbose when plotting slightly more complex data. The R workflow in contrast is straight forward, readable and arguably more beautiful.

Visualization in semantic letters allows to focus on what to show, not how. No loops necessary. It's not necessary to create as many temporary variables, since it simply doesn't take many extra steps to achieve what I want. Computing and adding new columns in my data frame is just done on the fly.

Of course, there is much more you can do with both libraries. I haven't touched theming at all, nor different plot types. However, this is a fairly common set-up that I have to deal with in my daily work, so although not a complete comparison, it should be a relevant one.

by Robin Schubert at June 22, 2020 12:00 AM

June 20, 2020

Jason Braganza (Personal)

We Need To Talk About the British Empire

It’s an Audible Original.
And it’s “free”, if you are an Audible member.

A look into what Empire means today.
It’s a series of engaging podcast episodes on what being a part of the British Empire meant/means for its subjects and its descendants, with stories from across the globe.

My only quibble being they did not go deep enough.
The people being interviewed are mostly, subject descendants of British origin (and not as I would expect, an actual survivor from the partition or someone here in India, or Somali coast or Sierra Leone.)

No one knows much of the aftermath of Partion and there’s a lovely little story, tightly told that illustrates the horrors of the period.
Somalia was used, abused, robbed of all they had and then left to find for itself.
Bunce Island, in Sierra Leone was home to a slaver’s bay, where the island hosted a prison for the captured natives who were branded and sold as slaves and a golf course for the gora sahibs.

What struck me (from the interviews and some of the reviews) is that the British have no clue of the generational ramifications of their actions.
They think that enough time has passed by, it’s all water under the bridge and we ought to have picked ourselves by our bootstraps by now.
I realise why Tharoor demanded reparations.

At about three hours, it’s well worth a listen.

by Mario Jason Braganza at June 20, 2020 10:43 AM

June 17, 2020

Jason Braganza (Personal)

A Tale of Two Cities

Just the two popular ones here …
Dickens writes such fluid prose here, I would quote the whole book.

It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way--in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.

It is a far, far better thing that I do, than I have ever done; it is a far, far better rest that I go to than I have ever known.

by Mario Jason Braganza at June 17, 2020 12:26 PM

Anwesha Das

Software Licenses : Legalese to English

When I was doing a licensing survey in the Fedora ecosystem. I asked a few developers, "What is license according to them?" I got some interesting answers:

"I do not care about the license; it bores me." - a super senior developer says this. (not a very good example to follow)

"You have to fill up the name of a license to make the package in Fedora unless they won't accept the package" (sadly)

"License is something that protects your code." (Ahh finally some optimism)

The answer appeared as a ray of hope to me that yes, there are developers (still) who do care about code ( both their code and law).

But most of the developers (if not all) see licenses as long, huge legal documents filled with complicated words and some never-ending sentences. There are certain tags that people tend to associate with licenses like: MIT is permissive, GPL is strict, BSD is secure. Instead of going through the license document itself, developers choose the license for their project; based on these mental tags, they tag to it.

From today I am going to start a series to explaining different kinds of software licenses. The series will translate legalese into English. Together we will try to understand the Licenses and it's permissions one by one.

Before that, let us know what Open Source License and why it is essential?

Open Sourced software or hardware is the software or hardware that released under open source licenses. Open Source Licenses grant certain Intellectual Property Rights, in this case, Copyright, to their users.

The phrase Open Source software or hardware points to a software or hardware which

  • has its source code, design open and available to anybody and they can
  • examine,
  • modify
  • enhance and
  • share.

Open source projects products and communities based on the ethos of

  • collaboration, open and free exchange, and community sharing. Which results in a transparent process and better product or process. Open source Licenses stand in opposite to Closed Source/ Proprietary Licenses. For the last few years, there has been a surge in the usage of Open Source Licenses because

  • the product, process, or initiative is having open source licenses believed to be secure and stable.

  • the community has the control behind it.

  • the collaborative efforts produce a better product.

  • trains the programmers, designers to be better at their job through mentorship and community efforts.

Licenses lie at the very core of the Open source and Free Software community. But though many times we say “Open Source” and “Free and Open Source”(FOSS) in the same breath. But they are very different from each other, in the permissions and restrictions.

Choosing a license a developer marks the limit of its product, selects the community he wants to work with. So it is of utmost importance for them to know well. From the next post of this series, we will thrive to that goal.

by Anwesha Das at June 17, 2020 06:07 AM

June 07, 2020

Kuntal Majumder

Transitioning to Windows

So, recently I started using windows for work. Why? There are a couple of reasons, one that I needed to use MSVC, that is the Microsoft Visual C++ toolchain and the other being, I wasn’t quite comfortable to ifdef stuff for making it work on GCC aka, the GNU counterpart of MSVC.

June 07, 2020 02:38 PM

Robin Schubert

Painless handling and migration on multiple PostgreSQL instances

Touching databases has always been something that made my heart beat a little bit faster. Although I've become more comfortable with SQL syntax over the years, and I do my backups regularly and diligently, migrations still feel like there is some magic happening that I never fully understood.

I'm running PostgreSQL on an Ubuntu Server 18.04 that is used by several applications. Over time, updates to the system brought with them multiple PostgreSQL updates. However, the apt upgrade won't migrate my databases when upgrading, rather it will spawn a new PostgreSQL instance with a new major version which listens on a new port.

Right now, I have three of those instances running (9.3, 9.6 and 10), listening on the ports 5432 (the default), 5433 and 5434, respectively:

sudo netstat -tulpn | grep postgres

tcp     0   0*      LISTEN   1573/postgres
tcp     0   0*      LISTEN   1572/postgres
tcp     0   0*      LISTEN   1651/postgres

The instances are used by different services, the PostgreSQL 10 has been freshly installed with the last apt upgrade and is currently rather empty:

ps fax | grep postgres

 1572 ?  S    0:02 /usr/lib/postgresql/9.5/bin/postgres\
     -D /var/lib/postgresql/9.5/main\
     -c config_file=/etc/postgresql/9.5/main/postgresql.conf
 2182 ?  Ss   0:00  \_ postgres: checkpointer process
 2183 ?  Ss   0:00  \_ postgres: writer process
 2184 ?  Ss   0:00  \_ postgres: wal writer process
 2185 ?  Ss   0:01  \_ postgres: autovacuum launcher process
 2186 ?  Ss   0:09  \_ postgres: stats collector process
 4516 ?  Ss   0:59  \_ postgres: gitlab gitlabhq_production idle
 4517 ?  Ss   0:26  \_ postgres: gitlab gitlabhq_production idle
22295 ?  Ss   0:00  \_ postgres: jiradbuser jiradb idle

 1573 ?  S    0:01 /usr/lib/postgresql/9.3/bin/postgres\
     -D /var/lib/postgresql/9.3/main\
     -c config_file=/etc/postgresql/9.3/main/postgresql.conf
 2158 ?  Ss   0:00  \_ postgres: checkpointer process
 2159 ?  Ss   0:00  \_ postgres: writer process
 2160 ?  Ss   0:00  \_ postgres: wal writer process
 2161 ?  Ss   0:01  \_ postgres: autovacuum launcher process
 2162 ?  Ss   0:02  \_ postgres: stats collector process
 2654 ?  Ss   0:00  \_ postgres: gitea gitea idle

 1651 ?  S    0:01 /usr/lib/postgresql/10/bin/postgres\
     -D /var/lib/postgresql/10/main\
     -c config_file=/etc/postgresql/10/main/postgresql.conf
 2088 ?  Ss   0:00  \_ postgres: checkpointer process
 2089 ?  Ss   0:00  \_ postgres: writer process
 2090 ?  Ss   0:00  \_ postgres: wal writer process
 2092 ?  Ss   0:00  \_ postgres: autovacuum launcher process
 2093 ?  Ss   0:02  \_ postgres: stats collector process
 2094 ?  Ss   0:00  \_ postgres: bgworker: logical replication launcher

One thing that took me a while to fully get the grasp of it: Each server version comes with its own set of client tools you want to use to handle your instance. However, I didn't understand how this works and how I access these different versions.

Let's start with the example of dumping a database to disk for backup purpose. The pg_dump command is the tool of choice here, however, there is no pg_dump9.3 or pg_dump10 to be found anywhere in your $PATH. Instead, pg_dump is a link to /usr/share/postgresql-common/pg_wrapper, a perl script which determines the name of the command it has been called with and executes it with the evaluated given flags, options and switches.

Default database settings for that command can also be specified in either of ~/.postgresqlrc or /etc/postgresql-commen/user_clusters.

To specify the version of the client tool we want to use, we provide the --cluster option to our pg_wrapper.

The following commands will be run as postgres user:

sudo -iu postgres

postgres@ubuntuRechenknecht:~$ pg_dump --version
pg_dump (PostgreSQL) 9.3.16

postgres@ubuntuRechenknecht:~$ pg_dump --cluster 9.5/main --version
pg_dump (PostgreSQL) 9.5.19

postgres@ubuntuRechenknecht:~$ pg_dump --cluster 10/main --version
pg_dump (PostgreSQL) 10.12 (Ubuntu 10.12-0ubuntu0.18.04.1)

Similarly, we can connect to our databases with psql, which is another pg_wrapper-handled command:

postgres@ubuntuRechenknecht:~$ psql
psql (10.12 (Ubuntu 10.12-0ubuntu0.18.04.1), server 9.3.16)
Type "help" for help.

postgres> \q

postgres@ubuntuRechenknecht:~$ psql --cluster 9.5/main
psql (10.12 (Ubuntu 10.12-0ubuntu0.18.04.1), server 9.5.19)
Type "help" for help.

postgres> \q

postgres@ubuntuRechenknecht:~$ psql --cluster 10/main
psql (10.12 (Ubuntu 10.12-0ubuntu0.18.04.1))
Type "help" for help.

Although you could also connect to your instance of choice by specifying the port number like this

postgres@ubuntuRechenknecht:~$ psql --port 5434
psql (10.12 (Ubuntu 10.12-0ubuntu0.18.04.1))
Type "help" for help.

Migrating a database from one instance to the other

Migrating a PostgreSQL database can be as simple as dumping in from the one instance and pushing it into the other. Just a few things that should be considered:

  1. The version of pg_dump should always be the version of the target database, to avoid incompatibilities.
  2. The target database needs to be created, along with the roles and permissions needed to import the dump.

In my case, I had to migrate the database from our gitlab instance, since it did not meet the minimum PostgreSQL version that is required to actually run the latest gitlab (yes, also PostgreSQL 10 does not meet that requirement, but it works while 9.5 does not).

To dump the database from the old 9.5 instance with the new 10 client, I need to specify both, cluster and port:

pg_dump --cluster 10/main --port 5433 gitlabhq_production > /tmp/gitlabhq_production

I create the new database on the target instance, and set up the role and permissions needed for gitlab:

createdb --cluster 10/main gitlabhq_production

psql --cluster 10/main
postgres> CREATE ROLE gitlab WITH PASSWORD '********';
postgres> GRANT ALL ON DATABASE gitlabhq_production TO gitlab;

Now the database is ready to be fed with the dump:

psql --port 5434 gitlabhq_production < /tmp/gitlabhq_production

In case of gitlab, the final step would be to update the database port in the gitlab configuration file /etc/gitlab/gitlab.rb

gitlab_rails['db_port'] = 5434

and let gitlab reconfigure itself

sudo gitlab-ctl reconfigure

I feel much more confident now that I know how to handle my different PostgreSQL instances. Next I guess I will have to take some of them down, which I had avoided so far.

by Robin Schubert at June 07, 2020 12:00 AM

May 23, 2020

Bhavin Gandhi

Monitoring workstation with Prometheus

Prometheus is a monitoring system and a time series database. It can collect metrics from different places and store it as series of values over time. It uses pull based mechanism to collect the metrics. Applications can expose the metrics in a plain text format using HTTP server, which is then fetched by Prometheus. Fetching of metrics is called scraping. For other systems which don’t expose the metrics in Prometheus exposition format, we can use exporters.

by Bhavin Gandhi ( at May 23, 2020 02:32 PM

May 12, 2020

Bhavin Gandhi

How to manipulate JSON using jq

JavaScript Object Notation, often referred as JSON is a data representation format which is human readable and easy to parse for machines. Personally, I find it hard to comprehend huge JSON files. In this blog post, I will be talking about the tool called jq. It’s a CLI tool to parse and manipulate JSON objects/files. How I started using jq In the past one year, I have been writing a lot of shell scripts (mostly for bash).

by Bhavin Gandhi ( at May 12, 2020 05:45 PM

May 09, 2020

Kuntal Majumder

Krita Weekly #14

After an anxious month, I am writing a Krita Weekly again and probably this would be my last one too, though I hope not. Let’s start by talking about bugs. Unlike the trend going about the last couple of months, the numbers have taken a serious dip.

May 09, 2020 04:12 PM

May 06, 2020

May 02, 2020

Abhilash Raj

Why did my machine reboot?

Yesterday, I was trying to debug why my server running Plex rebooted and wasn't able to figure it out. There are several new commands that I discovered, the best of which is called last.

This article was really useful.


who command prints which users are currently logged in:

$ who   
maxking  tty2         2020-04-30 22:17 (tty2)

But, you can use it with -b to figure out the last reboot time:

$ who -b       
         system boot  2020-04-30 22:16


last command prints a bunch of useful information, including

  • Time of last reboot, last reboot
  • time of last shutdown last shutdown
  • All the system restart/shutdown events and run level changes last -x

It also has a bunch of useful flags like, --present which also prints which users were present at the time (I really liked this one!)

$ last -p 14:40                                                                                                                                                                         1 ↵
maxking  tty2         tty2             Thu Apr 30 22:17   still logged in
reboot   system boot  5.6.7-300.fc32.x Thu Apr 30 22:16   still running

useful logs

I also found this stackexchange answer with a lot of useful log files that have information related to reboots like Kernel messages, systemd-journal etc.

by Abhilash Raj at May 02, 2020 11:11 PM

April 11, 2020

Shakthi Kannan

Using Docker with Ansible

[Published in Open Source For You (OSFY) magazine, October 2017 edition.]

This article is the eighth in the DevOps series. In this issue, we shall learn to set up Docker in the host system and use it with Ansible.


Docker provides operating system level virtualisation in the form of containers. These containers allow you to run standalone applications in an isolated environment. The three important features of Docker containers are isolation, portability and repeatability. All along we have used Parabola GNU/Linux-libre as the host system, and executed Ansible scripts on target Virtual Machines (VM) such as CentOS and Ubuntu.

Docker containers are extremely lightweight and fast to launch. You can also specify the amount of resources that you need such as CPU, memory and network. The Docker technology was launched in 2013, and released under the Apache 2.0 license. It is implemented using the Go programming language. A number of frameworks have been built on top of Docker for managing these cluster of servers. The Apache Mesos project, Google’s Kubernetes, and the Docker Swarm project are popular examples. These are ideal for running stateless applications and help you to easily scale them horizontally.


The Ansible version used on the host system (Parabola GNU/Linux-libre x86_64) is Internet access should be available on the host system. The ansible/ folder contains the following file:



The following playbook is used to install Docker on the host system:

- name: Setup Docker
  hosts: localhost
  gather_facts: true
  become: true
  tags: [setup]

    - name: Update the software package repository
        update_cache: yes

    - name: Install dependencies
        name: "{{ item }}"
        state: latest
        - python2-docker
        - docker

    - service:
        name: docker
        state: started

    - name: Run the hello-world container
        name: hello-world
        image: library/hello-world

The Parabola package repository is updated before proceeding to install the dependencies. The python2-docker package is required for use with Ansible. Hence, it is installed along with the docker package. The Docker daemon service is then started and the library/hello-world container is fetched and executed. A sample invocation and execution of the above playbook is shown below:

$ ansible-playbook playbooks/configuration/docker.yml -K --tags=setup
SUDO password: 

PLAY [Setup Docker] *************************************************************

TASK [Gathering Facts] **********************************************************
ok: [localhost]

TASK [Update the software package repository] ***********************************
changed: [localhost]

TASK [Install dependencies] *****************************************************
ok: [localhost] => (item=python2-docker)
ok: [localhost] => (item=docker)

TASK [service] ******************************************************************
ok: [localhost]

TASK [Run the hello-world container] ********************************************
changed: [localhost]

PLAY RECAP **********************************************************************
localhost                  : ok=5    changed=2    unreachable=0    failed=0   

With verbose ’-v’ option to ansible-playbook, you will see an entry for LogPath, such as /var/lib/docker/containers//-json.log. In this log file you will see the output of the execution of the hello-world container. This output is the same when you run the container manually as shown below:

$ sudo docker run hello-world

Hello from Docker!

This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:

For more examples and ideas, visit:


A Deep Learning (DL) Docker project is available ( with support for frameworks, libraries and software tools. We can use Ansible to build the entire DL container from the source code of the tools. The base OS of the container is Ubuntu 14.04, and will include the following software packages:

  • Tensorflow
  • Caffe
  • Theano
  • Keras
  • Lasagne
  • Torch
  • iPython/Jupyter Notebook
  • Numpy
  • SciPy
  • Pandas
  • Scikit Learn
  • Matplotlib
  • OpenCV

The playbook to build the DL Docker image is given below:

- name: Build the dl-docker image
  hosts: localhost
  gather_facts: true
  become: true
  tags: [deep-learning]

    DL_BUILD_DIR: "/tmp/dl-docker"
    DL_DOCKER_NAME: "floydhub/dl-docker"

    - name: Download dl-docker
        dest: "{{ DL_BUILD_DIR }}"

    - name: Build image and with buildargs
         path: "{{ DL_BUILD_DIR }}"
         name: "{{ DL_DOCKER_NAME }}"
         dockerfile: Dockerfile.cpu
           tag: "{{ DL_DOCKER_NAME }}:cpu"

We first clone the Deep Learning docker project sources. The docker_image module in Ansible helps us to build, load and pull images. We then use the Dockerfile.cpu file to build a Docker image targeting the CPU. If you have a GPU in your system, you can use the Dockerfile.gpu file. The above playbook can be invoked using the following command:

$ ansible-playbook playbooks/configuration/docker.yml -K --tags=deep-learning

Depending on the CPU and RAM you have, it will take considerable amount of time to build the image with all the software. So be patient!

Jupyter Notebook

The built dl-docker image contains Jupyter notebook which can be launched when you start the container. An Ansible playbook for the same is provided below:

- name: Start Jupyter notebook
  hosts: localhost
  gather_facts: true
  become: true
  tags: [notebook]

    DL_DOCKER_NAME: "floydhub/dl-docker"

    - name: Run container for Jupyter notebook
        name: "dl-docker-notebook"
        image: "{{ DL_DOCKER_NAME }}:cpu"
        state: started
        command: sh

You can invoke the playbook using the following command:

$ ansible-playbook playbooks/configuration/docker.yml -K --tags=notebook

The Dockerfile already exposes the port 8888, and hence you do not need to specify the same in the above docker_container configuration. After you run the playbook, using the ‘docker ps’ command on the host system, you can obtain the container ID as indicated below:

$ sudo docker ps
CONTAINER ID        IMAGE                    COMMAND               CREATED             STATUS              PORTS                NAMES
a876ad5af751        floydhub/dl-docker:cpu   "sh"   11 minutes ago      Up 4 minutes        6006/tcp, 8888/tcp   dl-docker-notebook

You can now login to the running container using the following command:

$ sudo docker exec -it a876 /bin/bash

You can then run an ‘ifconfig’ command to find the local IP address (“” in this case), and then open in a browser on your host system to see the Jupyter Notebook. A screenshot is shown in Figure 1:

Jupyter Notebook


TensorBoard consists of a suite of visualization tools to understand the TensorFlow programs. It is installed and available inside the Docker container. After you login to the Docker container, at the root prompt, you can start Tensorboard by passing it a log directory as shown below:

# tensorboard --logdir=./log

You can then open in a browser on your host system to see the Tensorboard dashboard as shown in Figure 2:


Docker Image Facts

The docker_image_facts Ansible module provides useful information about a Docker image. We can use it to obtain the image facts for our dl-docker container as shown below:

- name: Get Docker image facts
  hosts: localhost
  gather_facts: true
  become: true
  tags: [facts]

    DL_DOCKER_NAME: "floydhub/dl-docker"

    - name: Get image facts
        name: "{{ DL_DOCKER_NAME }}:cpu"

The above playbook can be invoked as follows:

$ ANSIBLE_STDOUT_CALLBACK=json ansible-playbook playbooks/configuration/docker.yml -K --tags=facts 

The ANSIBLE_STDOUT_CALLBACK environment variable is set to ‘json’ to produce a JSON output for readability. Some important image facts from the invocation of the above playbook are shown below:

"Architecture": "amd64", 
"Author": "Sai Soundararaj <>", 

"Config": {

"Cmd": [

"Env": [

"ExposedPorts": {
   "6006/tcp": {}, 
   "8888/tcp": {}

"Created": "2016-06-13T18:13:17.247218209Z", 
"DockerVersion": "1.11.1", 

"Os": "linux", 

"task": { "name": "Get image facts" }

You are encouraged to read the ‘Getting Started with Docker’ user guide available at to know more about using Docker with Ansible.

April 11, 2020 06:30 PM

March 27, 2020

Pradyun Gedam

Testing the next-gen pip dependency resolver

This is an attempt to summarize the broader software architecture around dependency resolution in pip and how testing is being done around this area.

The motivation behind writing this, is to make sure all the developers working on this project are on the same page, and to have a written record about the state of affairs.


The “legacy” resolver in pip, is implemented as part of pip’s codebase and has been a part of it for many years. It’s very tightly coupled with the existing code, isn’t easy to work with and has severe backward compatibility concerns with modifying directly – which is why we’re implementing a separate “new” resolver in this project, instead of trying to improve the existing one.

The “new” resolver that is under development, is not implemented as part of pip’s codebase; not completely anyway. We’re using an abstraction that separates all the metadata-generation-and-handling stuff vs the core algorithm. This allows us to work on the core algorithm logic (i.e. the NP-hard search problem) separately from pip-specific logic (eg. download, building etc). The abstraction and core algorithm are written/maintained in right now. The pip-specific logic for implementing the “other side” of the abstraction is in


In terms of testing, we have dependency-resolution-related tests in both resolvelib and pip.


The tests in resolvelib are intended more as “check if the algorithm does things correctly” and even contains tests that are agnostic to the Python ecosystem (eg. we’ve borrowed tests from Ruby, Swift etc). The goal here is to make sure that the core algorithm we implement is capable of generating correct answers (for example: not getting stuck in looping on the same “requirement”, not revisiting rejected nodes etc).


The tests in pip is where I’ll start needing more words to explain what’s happening. :)

YAML-based tests

We have “YAML” tests which I’d written back in 2017, as a format to easily write tests for pip’s new resolver when we implement it. However, since we didn’t have a need for it to be working completely back then (there wasn’t a new resolver to test with it!), the “harness” for running these tests isn’t complete and would likely need some work to be as feature complete as we’d want it to be, for writing good tests.

YAML tests:
YAML test “harness”: and

“new” resolver tests

unit tests

We have some unit tests for the new resolver implementation. These cover very basic “sanity checks” to ensure it follows the “contract” of the abstraction, like “do the candidates returned by a requirement actually satisfy that requirement?”. These likely don’t need to be touched, since they’re fairly well scoped and test fairly low-level details (i.e. ideal for unit tests).

New resolver unit tests:

functional tests

We also have “new resolver functional tests”, which are written as part of the current work. These exist since how-to-work-with-YAML-tests was not an easy question to answer and there needs to be work done (both on the YAML format, as well as the YAML test harness) to flag which tests should run with which resolver (both, only legacy, only new) and make it possible to put run these tests in CI easily.

New resolver functional tests:


These files test all the functionality of the install command (like: does it use the right build dependencies, does it download the correct files, does it write the correct metadata etc). There might be some dependency-resolution-related tests in test_install*.py files.

These files contain a lot of tests so, ideally, at some point, someone would go through and de-duplicate tests from this as well.

How can you help?

If you use pip, there are a multiple ways that you can help us!

Thanks to Paul Moore and Tzu-Ping for help in reviewing and writing this post, as well as Sumana Harihareswara for suggesting to put this up on my blog!

March 27, 2020 12:00 AM

March 01, 2020

Farhaan Bukhsh

Android Services

From past few days I have been dwelling in android to make a utility, an application that I can be used when I am reading and article or when I am researching about something.

The premise lies around on the fact that the application itself doesn’t have a screen but what it plays around is on background activity. So it silently keeps on running and when an interrupt comes it performs an action.

Since I am not very well versed with how to make an android of such kind, I searched and found out about the component which does this and it’s called a Service. This is very similar to the concept of linux services or daemons.

The application I am designing is basically a combination of overlay activity and background services. Hence I wouldn’t say that there will be no user interaction at all but it will be really minimal and user doesn’t have a inherent knowledge about the service.

So it was time to do some more reading on android services.

Service is an application component that can perform long-running operations in the background, and it doesn’t provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application.


This was something that I really wanted, now there are a few caveats to this blogpost that is my understanding and knowledge about android application development. So I would tell you take things with a pinch of salt and let me know if there is anything wrong with my understanding.

When I read more about services I got to know there are 3 kinds of them:


This is how you see spotify music work, even when the application is not in the display you can change songs through notification and there is one level of user interaction involved with this.


Services with which user don’t want to know about or interact, like updating a database, fetching some resources etc.


Bound services are the one which are attach to the user activity, the quickest example I can give is music player, you don’t want the music to stop when you switch application and in the mean time you want to control the music when you switch back to the application.

Mostly people use services so that all the heavy lifting is done in the background. I had a unique case what I wanted is a service that keeps running and observing, when something is changed or when it is poked then react to it.

If you have seen the design of facebook messenger, the chat heads comes to life only when you have a message, this was somewhat the use case.

The biggest thing that I learnt is android doesn’t allow you run a background service without notifying the user. This is a new addition the happened after Android Oreo.


There are two kinds of implementation that android provides,

The former as it’s name suggest is used to spawn service and is attached to the main thread. While IntentSrvice is something more peculiar where you can divide the work and do it without actually make your application wait for something. For example suppose you are playing a game and you are in middle of level 1, now an IntentService can be used to spawn to download and keep all the data required for level 2 without affecting your game play.

Another amazing thing about services is that, it is a singleton, that means however time you are going to start a service, you are not going to interact with too many objects, it’s the same class which you are going to talk to.


These are few of the learning that I got about services in android, I didn’t put much code here because most of them is available in the references. I enjoyed my time learning about how services are designed and how they are manged internally in android. Let me know what you think about it.

Till then, Keep Hacking!


by fardroid23 at March 01, 2020 05:01 PM

February 21, 2020

Farhaan Bukhsh

Word Embeddings Simplified

Recently I have been dwelling with a lot of NLP problems and jargons. The more I read about it the more I find it intriguing and beautiful of how we humans try to transfer this knowledge of a language to machines.

How much ever we try because of our laid back nature we try to use already existing knowledge or existing materials to be used to make machines understand a given language.

But machines as we know it can only understand digits or lets be more precise binary(0s and 1s). When I first laid my hands on NLP this was my first question, how does a machine understand that something is a word or sentence or a character.

I am still a learner in this field(and life 😝) but what I could understand information that we are going to use has to be converted into binary or some kind of a numerical representation for a machine to understand.

There are various ways to “encode” this information into numerical form and that is what is called word embeddings.

What are word embeddings?

Word embedding is the collective name for a set of language modeling and feature learning techniques in natural language processing (NLP) where words or phrases from the vocabulary are mapped to vectors of real numbers. Conceptually it involves a mathematical embedding from a space with many dimensions per word to a continuous vector space with a much lower dimension.


In short word embedding is a way to convert a textual information into numerical form so that it can help us analyse it.

Analysis like similarity between words or sentences, understand the context in which a phrase or word is being spoken etc.

How are they formed?

Lets try to convert a given sentence into a numerical form:

A quick brown fox jumps over the lazy dog

How do we convert the above sentence into a numerical form such that our machine or even we can perform operations on it. And its hard to figure out the mathematics of language but we can always try.

So lets try, what we can do is, get all unique words and sort the words in the sentences and then makes a list of them. But then how do we get a numerical representation for it. It’s time for us to visit our long lost friend – Matrix.

Let’s get the words in proper order i.e unique and sorted

Now we will try to convert these words into numerical form using some matrix concepts(mostly representation) so that we can make a word look different from another word.

If you see there are totally 10 words and so we took 10 blocks to represent it. In a more mathematical term each representation is called a vector and the dimension of this vector is 1 x 10. So each word in this universe can be represented by a vector of that dimension and we can now carry operations on it to get our desired result.

Few prominent operations are how similar are two vectors or how different are two vectors. We can dive into that later.

Now the method that we just followed is a very brute force way of doing this and is officially called as One-Hot Encoding or Count Vectorizing.

Why we do this?

Now the way we encoded above words can be really useless because it’s just a representation and it doesn’t have any other idea so we don’t know how two words are related or are they morphologically similar etc.

The prime reason we want to have encoding is to find similar words, gauge the context of the topics etc.

There are various other techniques which actually produce intelligent embeddings that has an idea about what is going on.

As Hunter puts it

When constructing a word embedding space, typically the goal is to capture some sort of relationship in that space, be it meaning, morphology, context, or some other kind of relationship

and a lot of other embeddings like Elmo, USE etc. does a good job at that.

As we go ahead and explore more embeddings you will see it goes on becoming more complex. There are layers of training models introduced etc.

We even have sentence embeddings which are way different from just word embeddings.


This was just a tip of the iceberg or may be not even that but I thought it will be helpful for someone who is starting their exploration because it took time for me to get around this concept. Thanks a lot for reading.

Happy Hacking!


by fardroid23 at February 21, 2020 06:47 AM

February 19, 2020

Pradyun Gedam

OSS Work update #8

I’m trying to post these roughly once a month. Here’s the January post.

I am working on open source projects, as part of an internship at FOSSEE and as a part of grant-funded work on pip’s dependency resolver.

Work I did (Jan 6 - Feb 5)


  • Co-worked with another developer, in person, for 1 week, on pip!
  • Triaged pip’s issue tracker (a lot).
  • Spend some time improving pip’s test suite infrastructure.
  • Investigated Python 2 usage, to identify anomalies.
  • Helped with virtualenv 20.0 release (kinda!).
  • Invested effort to improve pip’s test suite
  • Helped aggregate test cases for pip’s next generation resolver.


  • Managed the pip 20.0 release fiasco.
  • Helped the UX folks get started with working on pip.

Additional notes on challenges

January has been a very productive month.

Most of the challenges have been the logistics around work, not the work as such.

My health has been pretty good and there’s a certain flow to my work that I’m enjoying now. Turns out, if you like what you’re doing, you tend to be pretty productive! :)

As long as I remember to push my blog posts to the repository, they’ll actually go live on the day they’re supposed to.

Goals for February 2020


  • Internal Cleansing: AKA Technical debt down payment.
  • Issue triage: Triage a fair number of issues on pip’s issue tracker.
  • Technical Documentation: improving pip’s technical documentation, for contributors and developers


  • Help all the other contractors to get up to “full speed” for working on pip
  • Get PyPA to participate in GSoC 2020
  • Python Packaging Summit at PyCon US 2020: help organization.
  • Move forward on Python Packaging Governance

Other commitments


Help us

How can you help us?

  • provide test cases where the latest released version of pip (19.3.1, at the time of writing) fails to resolve dependencies properly (on zazo’s issue tracker). They will help us design and test the new resolver.
  • talk with your company about becoming a PSF sponsor. The Fundable Packaging Improvements page lists fairly well-scoped projects that would happen much faster if we get funding to achieve them.
  • Have an interview with our UX expert, who is working to improve usability of Python Packaging tooling.

February 19, 2020 12:00 AM

February 10, 2020


Building up simple monitoring on Healthchecks

I talked previously about deploying my own simple monitoring system.

Now that it's up, I'm only using it for my backups. That's a good use, for sure, but I know I can do better.

So I went digging.

Read more… (2 min remaining to read)

by Elia el Lazkani at February 10, 2020 11:00 PM

February 08, 2020


Simple cron monitoring with HealthChecks

In a previous post, I showed you how you can automate your borg backups with borgmatic.

After I started using borgmatic for my backups and hooked it to a cron running every 2 hours, I got interested into knowing what's happening to my backups at all times.

My experience comes handy in here, I know I need a monitoring system. I also know that traditional monitoring systems are too complex for my use case.

I need something simple. I need something I can deploy myself.

Read more… (2 min remaining to read)

by Elia el Lazkani at February 08, 2020 11:00 PM

January 19, 2020

Rahul Jha

"isn't a title of this post" isn't a title of this post

[NOTE: This post originally appeared on, and has been posted here with due permission.]

In the early part of the last century, when David Hilbert was working on stricter formalization of geometry than Euclid, Georg Cantor had worked out a theory of different types of infinities, the theory of sets. This theory would soon unveil a series of confusing paradoxes, leading to a crisis in the Mathematics community  regarding the stability of the foundational principles of the math of that time.

Central to these paradoxes was the Russell’s paradox (or more generally, as we’d talk about later, the Epimenides Paradox). Let’s see what it is.

In those simpler times, you were allowed to define a set if you could describe it in English. And, owing to mathematicians’ predilection for self-reference, sets could contain other sets.

Russell then, came up with this:

\(R\)  is a set of all the sets which do not contain themselves.

The question was "Does \(R \) contain itself?" If it doesn’t, then according to the second half of the definition it should. But if it does, then it no longer meets the definition.

The same can symbolically be represented as:

Let \(R = \{ x \mid x \not \in x \} \), then \(R \in R \iff R \not \in R \)

Cue mind exploding.

“Grelling’s paradox” is a startling variant which uses adjectives instead of sets. If adjectives are divided into two classes, autological (self-descriptive) and heterological (non-self-descriptive), then, is ‘heterological’ heterological? Try it!

Epimenides Paradox

Or, the so-called Liar Paradox was another such paradox which shred apart whatever concept of ‘computability’ was, at that time - the notion that things could either be true or false.

Epimenides was a Cretan, who made one immortal statement:

“All Cretans are liars.”

If all Cretans are liars, and Epimenides was a Cretan, then he was lying when he said that “All Cretans are liars”. But wait, if he was lying then, how can we ‘prove’ that he wasn’t lying about lying? Ein?

This is what makes it a paradox: A statement so rudely violating the assumed dichotomy of statements into true and false, because if you tentatively think it’s true, it backfires on you and make you think that it is false. And a similar backfire occurs if you assume that the statement is false. Go ahead, try it!

If you look closely, there is one common culprit in all of these paradoxes, namely ‘self-reference’. Let’s look at it more closely.

Strange Loopiness

If self-reference, or what Douglas Hofstadter - whose prolific work on the subject matter has inspired this blog post - calls ‘Strange Loopiness’ was the source of all these paradoxes, it made perfect sense to just banish self-reference, or anything which allowed it to occur. Russell and Whitehead, two rebel mathematicians of the time, who subscribed to this point of view, set forward and undertook the mammoth exercise, namely “Principia Mathematica”, which we as we will see in a little while, was utterly demolished by Gödel’s findings.

The main thing which made it difficult to ban self-reference was that it was hard to pin point where exactly did the self-reference occur. It may as well be spread out over several steps, as in this ‘expanded’ version of Epimenides:

The next statement is a lie.

The previous statement is true.

Russell and Whitehead, in P.M. then, came up with a multi-hierarchy set theory to deal with this. The basic idea was that a set of the lowest ‘type’ could only contain ‘objects’ as members (not sets). A set of the next type could then only either contain objects, or sets of lower types. This, implicitly banished self-reference.

Since, all sets must have a type, a set ‘which contains all sets which are not members of themselves’ is not a set at all, and thus you can say that Russell’s paradox was dealt with.

Similarly, if an attempt is made towards applying the expanded Epimenides to this theory, it must fail as well, for the first sentence to make a reference to the second one, it has to be hierarchically above it - in which case, the second one can’t loop back to the first one.

Thirty one years after David Hilbert set before the academia to rigorously demonstrate that the system defined in Principia Mathematica was both consistent (contradiction-free) and complete (i.e. every true statement could be evaluated to true within the methods provided by P.M.), Gödel published his famous Incompleteness Theorem. By importing the Epimenides Paradox right into the heart of P.M., he proved that not just the axiomatic system developed by Russell and Whitehead, but none of the axiomatic systems whatsoever were complete without being inconsistent.

Clear enough, P.M. lost it’s charm in the realm of academics.

Before Gödel’s work too, P.M. wasn’t particularly loved as well.


It isn’t just limited to this blog post, but we humans, in general, have a diet for self-reference - and this quirky theory severely limits our ability to abstract away details - something which we love, not only as programmers, but as linguists too - so much so, that the preceding paragraph, “It isn’t … this blog … we humans …” would be doubly forbidden because the ‘right’ to mention ‘this blog post’ is limited only to something which is hierarchically above blog posts, ‘metablog-posts’. Secondly, me (presumably a human) belonging to the class ‘we’ can’t mention ‘we’ either.

Since, we humans, love self-reference so much, let’s discuss some ways in which it can be expressed in written form.

One way of making such a strange loop, and perhaps the ‘simplest’ is using the word ‘this’. Here:

  • This sentence is made up of eight words.
  • This sentence refers to itself, and is therefore useless.
  • This blog post is so good.
  • This sentence conveys you the meaning of ‘this’.
  • This sentence is a lie. (Epimenides Paradox)

Another amusing trick for creating a self-reference without using the word ‘this sentence’ is to quote the sentence inside itself.

Someone may come up with:

The sentence ‘The sentence contains five words’ contains five words.

But, such an attempt must fail, for to quote a finite sentence inside itself would mean that the sentence is smaller than itself. However, infinite sentences can be self-referenced this way.

The sentence
    "The sentence
        "The sentence
        is infinitely long"
    is infinitely long"
is infinitely long"

There’s a third method as well, which you already saw in the title - the Quine method. The term ‘Quine’ was coined by Douglas Hofstadter in his book “Gödel Escher, Bach” (which heavily inspires this blog post). When using this, the self-reference is ‘generated’ by describing a typographical entity, isomorphic to the quine sentence itself. This description is carried in two parts - one is a set of ‘instructions’ about how to ‘build’ the sentence, and the other, the ‘template’ contains information about the construction materials required.

The Quine version of Epimenides would be:

“yields falsehood when preceded by it’s quotation” yields falsehood when preceded by it’s quotation

Before going on with ‘quining’, let’s take a moment and realize how awfully powerful our cognitive capacities are, and what goes in our head when a cognitive payload full of self-references is delivered - in order to decipher it, we not only need to know the language, but also need to work out the referent of the phrase analogous to ‘this sentence’ in that language. This parsing depends on our complex, yet totally assimilated ability to handle the language.

The idea of referring to itself is quite mind-blowing, and we keep doing it all the time — perhaps, why it feels so ‘easy’ for us to do so. But, we aren’t born that way, we grow that way. This could better be realized by telling someone much younger “This sentence is wrong.”. They’d probably be confused - What sentence is wrong?. The reason why it’s so simple for self-reference to occur, and hence allow paradoxes, in our language, is well, our language. It allows our brain to do the heavy lifting of what the author is trying to get through us, without being verbose.

Back to Quines.

Reproducing itself

Now, that we are aware of how ‘quines’ can manifest as self-reference, it would be interesting to see how the same technique can be used by a computer program to ‘reproduce’ itself.

To make it further interesting, we shall choose the language most apt for the purpose - brainfuck:


Running that program above produces itself as the output. I agree, it isn’t the most descriptive program in the world, so written in Python below, is the nearest we can go to describe what’s happening inside those horrible chains of +’s and >’s:

THREE_QUOTES = '"' * 3

def eniuq(template): print(

eniuq("""THREE_QUOTES = '"' * 3

def eniuq(template): print(


The first line generates """ on the fly, which marks multiline strings in Python.

Next two lines define the eniuq function, which prints the argument template twice - once, plain and then surrounded with triple quotes.

The last 4 lines cleverly call this function so that the output of the program is the source code itself.

Since we are printing in an order opposite of quining, the name of the function is ‘quine’ reversed -> eniuq (name stolen from Hofstadter again)

Remember the discussion about how self-reference capitalizes on the processor? What if ‘quining’ was a built-in feature of the language, providing what we in programmer lingo call ‘syntactic sugar’?

Let’s assume that an asterisk, * in the brainfuck interpreter would copy the instructions before executing them, what would then be the output of the following program?


It’d be an asterisk again. You could make an argument that this is silly, and should be counted as ‘cheating’. But, it’s the same as relying on the processor, like using “this sentence” to refer to this sentence - you rely on your brain to do the inference for you.

What if eniuq was a builtin keyword in Python? A perfect self-rep was then just be a call away:


What if quine was a verb in the English language? We could reduce a lot of explicit cognitive processes required for inference. The Epimenides paradox would then be:

“yields falsehood if quined” yields falsehood if quined

Now, that we are talking about self-rep, here’s one last piece of entertainment for you.

The Tupper’s self-referential formula

This formula is defined through an inequality:

\({1 \over 2} < \left\lfloor \mathrm{mod}\left(\left\lfloor {y \over 17} \right\rfloor 2^{-17 \lfloor x \rfloor - \mathrm{mod}(\lfloor y\rfloor, 17)},2\right)\right\rfloor\)

If you take that absurd thing above, and move around in the cartesian plane for the coordinates \(0 \le x \le 106, k \le y \le k + 17\), where \(k\) is a 544 digit integer (just hold on with me here), color every pixel black for True, and white otherwise, you'd get:

This doesn't end here. If \(k\) is now replaced with another integer containing 291 digits, we get yours truly:

January 19, 2020 06:30 PM

October 31, 2019

Shakthi Kannan

TeX User Group Conference 2019, Palo Alto

The Tex User Group 2019 conference was held between August 9-11, 2019 at Sheraton Palo Alto Hotel, in Palo Alto, California.


I wanted to attend TUG 2019 for two main reasons - to present my work on the “XeTeX Book Template”, and also to meet my favourite computer scientist, Prof. Donald Knuth. He does not travel much, so, it was one of those rare opportunities for me to meet him in person. His creation of the TeX computer typesetting system, where you can represent any character mathematically, and also be able to program and transform it is beautiful, powerful and the best typesetting software in the world. I have been using TeX extensively for my documentation and presentations over the years.

Day I

I reached the hotel venue only in the afternoon of Friday, August 9, 2019, as I was also visiting Mountain View/San Jose on official work. I quickly checked into the hotel and completed my conference registration formalities. When I entered the hall, Rishi T from STM Document Engineering Private Limited, Thiruvananthapuram was presenting a talk on “Neptune - a proofing framework for LaTeX authors”. His talk was followed by an excellent poetic narration by Pavneet Arora, who happened to be a Vim user, but, also mentioned that he was eager to listen to my talk on XeTeX and GNU Emacs.

After a short break, Shreevatsa R, shared his experiences on trying to understand the TeX source code, and the lessons learnt in the process. It was a very informative, user experience report on the challenges he faced in navigating and learning the TeX code. Petr Sojka, from Masaryk University, Czech Republic, shared his students’ experience in using TeX with a detailed field report. I then proceeded to give my talk on the “XeTeX Book Template” on creating multi-lingual books using GNU Emacs and XeTeX. It was well received by the audience. The final talk of the day was by Jim Hefferon, who analysed different LaTeX group questions from newbies and in StackExchange, and gave a wonderful summary of what newbies want. He is a professor of Mathematics at Saint Michael’s College, and is well-known for his book on Linear Algebra, prepared using LaTeX. It was good to meet him, as he is also a Free Software contributor.

The TUG Annual General Meeting followed with discussions on how to grow the TeX community, the challenges faced, membership fees, financial reports, and plan for the next TeX user group conference.

Day II

The second day of the conference began with Petr Sojka and Ondřej Sojka presenting on “The unreasonable effectiveness of pattern generation”. They discussed the Czech hyphenation patterns along with a pattern generation case study. This talk was followed by Arthur Reutenauer presenting on “Hyphenation patterns in TeX Live and beyond”. David Fuchs, a student who worked with Prof. Donald Knuth on the TeX project in 1978, then presented on “What six orders of magnitude of space-time buys you”, where he discussed the design trade-offs in TeX implementation between olden days and present day hardware.

After a short break, Tom Rokicki, who was also a student at Stanford and worked with Donald Knuth on TeX, gave an excellent presentation on searching and copying text in PDF documents generated by TeX for Type-3 bitmap fonts. This session was followed by Martin Ruckert’s talk on “The design of the HINT file format”, which is intended as a replacement of the DVI or PDF file format for on-screen reading of TeX output. He has also authored a book on the subject - “HINT: The File Format: Reflowable Output for TeX”. Doug McKenna had implemented an interactive iOS math book with his own TeX interpreter library. This allows you to dynamically interact with the typeset document in a PDF-free ebook format, and also export the same. We then took a group photo:

Group photo

I then had to go to Stanford, so missed the post-lunch sessions, but, returned for the banquet dinner in the evening. I was able to meet and talk with Prof. Donald E. Knuth in person. Here is a memorable photo!

With Prof. Donald Knuth

He was given a few gifts at the dinner, and he stood up and thanked everyone and said that “He stood on the shoulders of giants like Isaac Newton and Albert Einstein.”

Gift to Prof. Donald Knuth< />

I had a chance to meet a number of other people who valued the beauty, precision and usefulness of TeX. Douglas Johnson had come to the conference from Savannah, Georgia and is involved in the publishing industry. Rohit Khare, from Google, who is active in the Representational State Transfer (ReST) community shared his experiences with typesetting. Nathaniel Stemen is a software developer at Overleaf, which is used by a number of university students as an online, collaborative LaTeX editor. Joseph Weening, who was also once a student to Prof. Donald Knuth, and is at present a Research Staff member at the Institute for Defense Analyses Center for Communications Research in La Jolla, California (IDA/CCR-L) shared his experiences in working with the TeX project.


The final day of the event began with Antoine Bossard talking on “A glance at CJK support with XeTeX and LuaTeX”. He is an Associate Professor of the Graduate School of Science, Kanagawa University, Japan. He has been conducting research regarding Japanese characters and their memorisation. This session was followed by a talk by Jaeyoung Choi on “FreeType MF Module 2: Integration of Metafont and TeX-oriented bitmap fonts inside FreeType”. Jennifer Claudio then presented the challenges in improving Hangul to English translation.

After a short break, Rishi T presented “TeXFolio - a framework to typeset XML documents using TeX”. Boris Veytsman then presented the findings on research done at the College of Information and Computer Science, University of Massachusetts, Amherst on “BibTeX-based dataset generation for training citation parsers”. The last talk before lunch was by Didier Verna on “Quickref: A stress test for Texinfo”. He teaches at École Pour l’Informatique et les Techniques Avancées, and is a maintainer of XEmacs, Gnus and BBDB. He also an avid Lisper and one of the organizers of the European Lisp Symposium!

After lunch, Uwe Ziegenhagen demonstrated on using LaTeX to prepare and automate exams. This was followed by a field report by Yusuke Terada, on how they use TeX to develop a digital exam grading system at large scale in Japan. Chris Rowley, from the LaTeX project, then spoke on “Accessibility in the LaTeX kernel - experiments in tagged PDF”. Ross Moore joined remotely for the final session of the day to present on “LaTeX 508 - creating accessible PDFs”. The videos of both of these last two talks are available online.

A number of TeX books were made available for free for the participants, and I grabbed quite a few, including a LaTeX manual written by Leslie Lamport. Overall, it was a wonderful event, and it was nice to meet so many like-minded Free Software people.

A special thanks to Karl Berry, who put in a lot of effort in organizing the conference, but, could not make it to due to a car accident.

The TeX User Group Conference in 2020 is scheduled to be held at my alma mater, Rochester Institute of Technology.

October 31, 2019 03:00 PM

October 16, 2019

September 24, 2019

Rahul Jha

A panegyric about my mentor, Omar Bhai

I was still up at this unearthly hour, thinking about life for a while now - fumbled thoughts about where I had come, where I started, and quite expectedly, Omar Bhai, your name popped in.

The stream continued. I started thinking about everything I’ve learned from you and was surprised with merely the sheer volume of thoughts that followed. I felt nostalgic!

I made a mental note to type this out the next day.

I wanted to do this when we said our final goodbyes and you left for the States, but thank God, I didn’t - I knew that I would miss you, but never could I have guessed that it would be so overwhelming - I would’ve never written it as passionately as I do today.

For those of you who don’t already know him, here’s a picture:

Omar Khursheed

I’m a little emotional right now, so please bear with me.

You have been warned - the words “thank you” and “thanks” appear irritatingly often below. I tried changing, but none other has quite the same essence.

How do I begin thanking you?

Well, let’s start with this - thank you for kicking me on my behind, albeit civilly, whenever I would speak nuisance (read chauvinism). I can’t thank you enough for that!

I still can’t quite get how you tolerated the bigot I was and managed to be calm and polite. Thank You for teaching me what tolerance is!

Another thing which I learnt from you was what it meant to be privileged. I can no longer see things the way I used to, and this has made a huge difference. Thank You!

I saw you through your bad times and your good. The way you tackled problems, and how easy you made it look. Well, it taught me [drum roll] how to think (before acting and not the other way round). Thank You for that too!

And, thank you for buying me books, and even more so, lending away so many of them! and even more so, educating me about why to read books and how to read them. I love your collection.

You showed all of us, young folks, how powerful effective communication is. Thank You again for that! I know, you never agree on this, but you are one hell of a speaker. I’ve always been a fan of you and your puns.

I wasn’t preparing for the GRE, but I sat in your sessions anyways, just to see you speak. The way you connect with the audience is just brilliant.

For all the advice you gave me on my relationships with people - telling me to back off when I was being toxic and dragging me off when I was on the receiving side - I owe you big time. Thank You!

Also, a hearty thank you for making me taste the best thing ever - yes, fried cheese it is. :D

Fried Cheese

Thank You for putting your trust and confidence in me!

Thank you for all of this, and much more!

Yours Truly, Rahul

September 24, 2019 06:30 PM

September 11, 2019

Priyanka Saggu

Some pending logs!

September 11, 2019

It’s been a very long time since I wrote here for the last.

The reason is nothing big but mainly because:

  1. Apparently, I was not able to finish some tasks in time that I used to write about.
  2. I was not well for a long time that could be an another reason .
  3. Besides, life happened in many ways which ultimately left me working on some other things first, because they seemed to be *important* for the time.

And, yes, there is no denying the fact that I was procastinating too because writing seems to be really hard at most times.

Though I had worked on many things throughout the time and I’ll try to write them here as short and quick logs below.

This one question always came up, many times, the students managed to destroy their systems by doing random things. rm -rf is always one of the various commands in this regard.

Kushal Das
  • While I was doing the above task, at one time I ruined my local system’s mail server configs and actually ended up doing something which kushal writes about in one of his recent post (quoted above). I was using the command rm -rf to clean some of the left-over dependencies of some mail packages, but that eventually resulted into machine being crashed. It was not the end of the mess this time. I made an another extremely big mistake meanwhile. I was trying to back up the crashed system, into an external hard disk using dd. But because I had never used dd before, so again I did something wrong and this time, I ended up losing ~500 GBs of backed up data. This is “the biggest mistake” and “the biggest lesson” I have learnt so far. 😔😭 (now I know why one should have multiple backups) And as there was absolutely no way of getting that much data back, the last thing I did was, formatting the hard-disk into 2 partitions, one with ext4 file system for linux backup and the other one as ntfs for everything else.

Thank you so much jasonbraganza for all the help and extremely useful suggestions during the time. 🙂

  • Okay, now after all the hassle bustle above, I got something really nice. This time, I received the “Raspberry Pi 4, 4GB, Complete Kit ” from kushal.

Thank you very much kushal for the RPi and an another huge thanks for providing me with all the guidance and support that made me reach to even what I am today. 🙂

  • During the same time, I attended a dgplug guest session from utkarsh2102. This session gave me a “really” good beginner’s insight of how things actually work in Debian Project. I owe a big thanks to utkarsh2102 as well, for he so nicely voluteered me from there onwards, to actually start with Debian project. I have started with DPMT and have done packaging 4 python modules so far. And now, I am looking forward to start contributing to Debian Ruby Team as well.

  • With the start of september, I spent some time solving some basic Python problems from kushal’s lymworkbook. Those issues were related to some really simply sys-admins work. But for me, working around and wrapping them in Python was a whole lot of learning. I hope I will continue to solve some more problems/issues from the lab.

  • And lastly (and currently), I am back to reading and implementing concepts from Ops School curriculum.

Voila, finally, I finish compiling up the logs from some last 20 days of work and other stuffs. (and thus, I am eventually finishing my long pending task of writing this post here as well).

I will definitely try to be more consistent with my writing from now onwards. 🙂

That’s all for now. o/

by priyankasaggu119 at September 11, 2019 05:28 PM

August 29, 2019

Sayan Chowdhury

Why I prefer SSH for Git?

Why I prefer SSH for Git?

In my last blog, I quoted

I'm an advocate of using SSH authentication and connecting to services like Github, Gitlab, and many others.

On this, I received a bunch of messages over IRC asking why do I prefer SSH for Git over HTTPS.

I find the Github documentation quite helpful when it comes down to learning the basic operation of using Git and Github. So, what has Github to say about "SSH v/s HTTPS"?

Github earlier used to recommend using SSH, but they later changed it to HTTPS. The reason for the Github's current recommendation could be:

  • Ease to start with: HTTPS is very easy to start with, as you don't have to set up your SSH keys separately. Once the account is created, you can just go over and start working with repositories. Though, the first issue that you hit is that you need to enter your username/password for every operation that you need to perform with git. This can be overcome by caching or storing the password using Git's credential storage. If you cache, then it is cached in memory for a limited period after which it is flushed so you need to enter your credentials again. I would not advise storing the password, as it is stored as plain-text on disk.
  • Easily accessible: HTTPS in comparison to SSH is easily accessible. Why? You may ask. The reason is a lot of times SSH ports are blocked behind a firewall and the only option left for you might be HTTPS. This is a very common scenario I've seen in the Indian colleges and a few IT companies.

Why do I recommend SSH-way?

SSH keys provide Github with a way to trust a computer. For every machine that I have, I maintain a separate set of keys. I upload the public keys to Github or whichever Git-forge I'm using. I also maintain a separate set of keys for the websites. So, for example, if I have 2 machines and I use Github and Pagure then I end up maintaining 4 keys. This is like a 1-to-1 connection of the website and the machine.

SSH is secure until you end up losing your private key. If you do end up losing your key, even then you can just login using your username/password and delete the particular key from Github. I agree, that the attacker can do nasty things but that would be limited to repositories and you would have control of your account to quickly mitigate the problem.

On the other side, if you end up losing your Github username/password to an attacker, you lose everything.

I also once benefitted from using SSH with Github, but IMO, exposing that also exposes a vulnerability so I'll just keep it a secret :)

Also, if you are on a network that has SSH blocked, you can always tunnel it over HTTPS.

But, above all, do use 2-factor authentication that Github provides. It's an extra layer of security to your account.

If you have other thoughts on the topic, do let me know over twitter @yudocaa, or drop me an email.

Photo by Christian Wiediger on Unsplash

by Sayan Chowdhury at August 29, 2019 11:55 AM

August 26, 2019

Saptak Sengupta

Configuring Jest with React and Babel

Jest is a really good frontend testing framework and works great with React and Babel out of the box, along with Enzyme for component testing. But, imports with React and Babel can often be filled with nasty imports. I wrote in a previous blog about how to make better more cleaner imports using some webpack tweaks.

But the problem appears when we try to write Jest and Enzyme tests with them. Because Babel can now longer understand and parse the imports. And without Babel parsing them and converting to ES5, jest cannot test the components. So we actually need a mix of Babel configuration and Jest configuration.

Note: This post assumes you already have jest, babel-jest and babel/plugin-transform-modules-commonjs packages installed using your favorite javascript package manager.

Basically, the workaround is first we need to resolve the cleaner imports into the absolute paths for the import using Jest configurations, and then use the Babel configurations to parse the rest code (without the modules) to ES5.

The configuration files look something like these:


module.exports = api => {
const isTest = api.env('test');
if (isTest) {
return {
presets: [
modules: false,
plugins: [
} else {
return {
presets: [
modules: false,


module.exports = {
moduleNameMapper: {
'^~/(.*)$': '<rootDir>/path/to/jsRoot/$1'

So let's go through the code a little.

In babel.config.js, we make a check to see if the code is right now in test environment. This is helpful because
  1. Jest sets the environment to "test" when running a test so it is easily identifiable
  2. It ensures that the test configuration don't mess up with the non test configurations in our Webpack config (or any other configuration you are using)
So in this case, I am returning the exact same Babel configuration that I need in my Webpack config in non-test environment.

In the test configuration for Babel, we are using a plugin "@babel/plugin-transform-modules-commonjs". This is needed to parse all the non component imports like React, etc. along with parsing the components from ES6 to ES5 after jest does the path resolution. So it helps to convert the modules from ES6 to ES5.

Now, let's see the jest.config.js. The jest configuration allows us to do something called moduleNameMapper. This is a very useful configuration in many different usecases. It basically allows us to convert the module names or paths we use for module import to something that jest understands (or in our case, something that the Babel plugin can parse). 

So, the left hand part of the attribute contains a regular expression which matches the pattern we are using for imports. Since our imports look something like '~/path/from/jsRoot/Component', so the regular expression to capture all such imports is '^~/(.*)$'. Now, to convert them to absolute paths, we need to append '<rootDir>/path/to/jsRoot/' in front of the component path.

And, voila! That should allow Jest to properly parse, convert to ES5 and then test.

The best part? We can use the cleaner imports even in the .test.js files and this configuration will work perfectly with that too.

by SaptakS ( at August 26, 2019 06:16 AM

Making cleaner imports with Webpack and Babel

You can bring in modules from different javascript file using require based javascript code, or normal Babel parse-able imports. But the code with these imports often become a little bad because of relative imports like:

import Component from '../../path/to/Component'

But a better, more cleaner way of writing ES6 imports is

import Component from '~/path/from/jsRoot/Component'

This hugely avoids the bad relative paths  for importing depending on where the component files are. Now, this is not parse-able by babel itself. But you can parse this by webpack itself using it's resolve attribute. So your webpack should have these two segments of code:

resolve: {
        alias: {
            '~': __dirname + '/path/to/jsRoot',
            modernizr$: path.resolve(__dirname, '.modernizrrc')
        extensions: ['.js', '.jsx'],
        modules: ['node_modules']


module: {
        rules: [
                test: /\.jsx?$/,
                use: [
                        loader: 'babel-loader',
                        query: {
                            presets: [
                                ['@babel/preset-env', { modules: false }]

The {modules: false} ensures that babel-preset-env doesn't handle the parsing of the module imports. You can check the following comment in a webpack issue to know more about this.

by SaptakS ( at August 26, 2019 05:56 AM

July 29, 2019

Sayan Chowdhury

Force git to use git:// instead of https://

Force git to use git:// instead of https://

I'm an advocate of using SSH authentication and connecting to services like Github, Gitlab, and many others. I do make sure that the use the git:// URL while cloning the repo but sometimes I do make mistake of using the https:// instead. Only to later realise when git prompts me to enter my username to authenticate the SSH connection. This is when I have to manually reset my git remote URL.

Today, I found a cleaner solution to this problem. I can use insteadOf to enforce the connection via SSH.

git config --global url."".insteadOf ""

This creates an entry in your .gitconfig:

[url ""]
	insteadOf =

Photo by Yancy Min on Unsplash

by Sayan Chowdhury at July 29, 2019 06:52 AM

April 08, 2019


Increasing Postgres column name length

This blog is more like a bookmark for me, the solution was scavenged from internet. Recently I have been working on an analytics project where I had to generate pivot transpose tables from the data. Now this is the first time I faced the limitations set on postgres database. Since its a pivot, one of my column would be transposed and used as column names here, this is where things started breaking. Writing to postgres failed with error stating column names are not unique. After some digging I realized Postgres has a column name limitation of 63 bytes and anything more than that will be truncated hence post truncate multiple keys became the same causing this issue.

Next step was to look at the data in my column, it ranged from 20-300 characters long. I checked with redshift and Bigquery they had similar limitations too, 128 bytes. After looking for sometime found a solution, downloaded the postgres source, changed NAMEDATALEN to 301(remember column name length is always NAMEDATALEN – 1) src/include/pg_config_manual.h, followed the steps from postgres docs to compile the source and install and run postgres. This has been tested on Postgres 9.6 as of now and it works.

Next up I faced issues with maximum number columns, my pivot table had 1968 columns and postgres has a limitation of 1600 total columns. According to this answer I looked into the source comments and that looked quite overwhelming 😛 . Also I do not have a control over how many columns will be there post pivot so no matter whatever value i set , in future i might need more columns, so instead I handled the scenario in my application code to split the data across multiple tables and store them.



by subho at April 08, 2019 09:25 AM