A Short Primer On “extra_requires“ in setup.py - To include optional installation capabilities in your Python module’s setup.py file, you can use the extras_require parameter. The extras_require parameter allows you to define groups of optional dependencies that users can install by specifying an extra name when running pip install. Here’s an example setup.py file that includes an optional dependency group for running tests: […]
Monitor Your Raspberry Pi with Flask: Free Disk Space and Latest File - Are you tired of manually checking your Raspberry Pi’s disk space and latest files? With a few lines of Python code and the Flask web framework, you can create a simple application that monitors your Raspberry Pi for you. In this post, we will walk through the code that monitors the free disk space on […]
Travel the World from Your Desktop: How to Use Python to Switch Up Your Wallpaper - Are you tired of staring at the same old desktop background on your Windows laptop every day? Do you have a collection of beautiful travel pictures that you’d love to see on your screen instead? If you answered yes to both of these questions, then you’re in luck! In this post, I’ll show you how […]

How to Enable CORS in Django - My Django learning app deployed on raspberrypi for kids was functioning smoothly when accessed from a home network. However, when we had to travel to Kolkata, and the app was promoted to a PythonAnywhere server. This move brought about a new challenge, as the app started to face issues with Cross-Origin Resource Sharing (CORS). I […]
Handling Multiple Inputs with argparse in Python Scripts - The problem. ffmpeg allows multiple inputs to be specified using the same keyword, like this: Let’s say you are trying to write a script in python that accepts multiple input sources and does something with each one, as follows: How do we do this in argparse? Using argparse, you are facing an issue as each […]
How to Suppress Terminal Window For Python Scripts - In windows python scripts are executed by python.exe by default. This executable opens a terminal, which stays open even if the program uses a GUI. What to do if you do not want this to happen? Well use the extension .pyw. This will cause the script to be executed by pythonw.exe by default. pythonw.exe suppresses […]








Python Logger Printing Multiple Times - This is my standard boilerplate code for adding any logging functionality in an app. This makes starting and working on projects super easy. But sometimes if the project involves multiples modules, there is an annoying little thing that the log is printed multiple times on the console. In one particular project, which was using multiple […]

JSON to Named Tuple - You have a JSON file and you are tired of getting the JSON just as a plain vanilla dictionary, then the following code using the namedtuple available in the collections module in standard python can come to your rescue Here’s an example Observe the convert definition. Now one can access its elements like Hope this […]
Rendering Matplotlib Graphs in Django - If you have seen my post on the expense Django app, the dashboard is rendered using matplotlib’s static files which are passed on runtime to the webpage HTML. See this here in action. All the png images are generated on the fly and sent to the browser to display. Here’s the simple code stript down […]













Number Puzzle and Few learnings - In April 2013, in my quest for sharpening my python skills, I wrote the below program to replicate the numbers puzzle game I have played during my childhood. Found this on my old hard disk which I was cleaning recently. Looking at it now I find lot of issues with it. Use of global variables […]
Simple Gems of Python - This functionality of Python is one I have applied in many of my pet projects and scripts. Do you know about it.
Two Important Reason for Testing are … - Back in 2020 during the start of the first wave in the UK, before the lockdown, I gave a quick talk on testing with Pytest to a few developer’s colleagues in the office. Few slides were titled why test and elaborated on various (more like 8) reasons for why we should write tests? Two reasons […]
Best Practice for Writing Tests for Argparse - If you write serious python apps for the end consumers, you ultimately end up writing argparse or similar CLI tools. Once written, this needs to be unit tested, so what is the best way to test the parsers? There are many different ways that can be done based on one’s application. For me, I have […]
How to Get System Ideal Time for Windows System - Two years ago faced a problem where my python application needed to know if the system is ideal or not. After experimenting with several options, finally settled on the following solution via this All done with python standard library. I love python’s battery included philosophy. Here’s a quick demo of the function I have used […]
Intel MKL FATAL ERROR - Last August, I got a new system from the office and I took this opportunity to upgrade my python 3.5 to python 3.7. Everything was working fine except for this error I searched for mkl_intel_thread.dll and could see them in the correct env folder. Many in StackOverflow advised moving the dll one folder up. Since […]
4-7-8 - This was one of the forwards from the HR team when the pandemic started for everyone’s well being. 4-7-8 Breathing technique to calm your mind. It was cool and just for the sake of it, did develop a mini-app in python that helps do this from command line. Here’s a demo. Works in windows, Linux […]

How to Determine Memory usage of a Python Function - In enginnering software development or other software developement projects, most programmers are solving a problem and this always starts by writing a naive implementation and then optimizing it in various ways. Many a times, instead of focusing on timing, we are also interested in memory usage so we can explore those tradeoffs of caching a […]
Determine if a given string is a URL - Recently while working on a side project in python and web, needed to find if a string is a url or not? Here’s a solution using python standard library Love this simple small snippets using the standard library. Do you know of such a hidden gem?

Reading/Writing wav files with Python - Problem: You want to read and manipulate sound (*.wav) files but since you are on a company-controlled system, you are not allowed to install pyaudio or other excellent audio packages. How do you solve this using basic standard python package? Solution: Example: These two functions recently helped me in a personal machine learning project. I […]

Starter code for Using Tensorboard - I have been using keras for multiple years now at home on my personal projects, one things that I have used very little is the tensorboard, mostly because I run the models on my home system and the console output more than satisfies my needs. But now I am planning to use it regularly. So […]
Few ipython %run magics I can’t live without - If you are not using ipython I strongly encourage you to stop reading and get ipython. From the time I have discovered it, 8 years back, i haven’t looked back. This is my default python console. Even jupyter hasn’t replaced it. Why? you ask. And here’s a list of ipython’s %run magics options that I […]
Working with PDF in python - I have a love hate relationship with the pdf format. I like the convenience of the portability but its hard to work with you if you need the data. And because of the portability, most of data coming my ways mostly is in pdf format, so i have come to rely on the an excellent […]
Record Screen With Python - There a tons of screen recording software available in the market, but you don’t want to install one more software for just one usage. Or sometimes installing a freeware or a paid ware is not allowed. What to do? you improvise. If you know and have python on your system, you are in luck. This […]
Winsay - The thing I like about MacBook is that it comes with simple features/apps in-built that makes life easy. And being forced to use windows at office I have tried to use python as the bridge to fix these gaps. One of the feature I like about mac for entertaining kids, and to relax my eyes […]

Numpy to Json - I don’t know why I have this snippet of code as a text file. This is something that I have used in few of the api endpoints. A pattern so common, so putting it here as a reference.
Few Not So Common but Useful git commands - Git is a versatile tool. It has a lot of things that can make it productive to use. Here’s a list of a few commands that I use in git on a monthly basis for my git repositories. git fsck -> Files system check git gc -> Garbage collection git diff –stat -> Only stats […]
Spellings: How to get good at it? - As my school friends will attest, spellings were never a strong suit for me. Most of this could be because I was lazy and never paid attention to it when reading. I liked reading but never looked at the spellings. I forgot about this until few years back when I began finding my kids getting […]
AVI to GIF with python - Problem: You have an AVI file that you want to convert to gif. Lets complicate this question by constraining that you want to get some frames and you want to crop a certain area of the video. Solution using python Here’s the simple code to do the conversion of the entire video to gif Here’s […]
Determining screen locked of a system using python’s standard library - I think, apart from the ease of use, python’s batteries include philosopy is one of the reason its has become so popular. Here’s another cool functionality that we needed in one of our app that was trying to maximise the usage of computing resources when the user has locked his computer. The problem, Get to […]
File and Folder Comparison with Python - Python standard library modules are incedible. There’s a small gem to compare files and directories. Its useful Say you have two ascii files and you want to do a file comparision, don’t worry, use python. To compare two directories, use filecmp module has utilities for comparing files and directories. It consists of the following. Refer […]
One-liner in Python to get the Directories - Python’s standard library is powerful and can be used for a lot of good things. Here’s a simple one-liner to collect all the directories from a path. What are your favourite one-liners that you tend to regularly use in python?
Get All Info About a Python Environment - Conda makes creating environments easy and if you are anything like me, over the course of time you end up having many enviroements and it becomes difficult to knwo what is what. Basic hygine is to make environemnet names unique and descriptive. But even then knowing what an environment has becomes difficult. Here’s a general […]
Starter Argparse and Setup.py templates - I tend to develop my python scripts as small apps, this way I can call and use them from every where in command line without relying on the calling the python scripts Here’s a template of the setup.py and argparse template that I always start with. Setup.py example is for making the application as a […]
Few common things to look out for while converting python 2 to python 3 - If you are converting your python2 code to python 3 manually. apart from the print statement, here are few things that i encountered. xrange is not available in python 3, simply used range 2. dict_keys in python 2 was a list and were iterable, but in python 3 you get the following error If you […]
Split text after nth occurrence of character - python never fails to amaze me. You have to keep using and and you find these little gems hidden in it. Suppose you have a string like this you want to split the numbers and the tags, meaning at the fourth occurance of comma, how will you do it? simple. this returns a list like […]
Get Outlook Entries With Python 3 - This was an old post, and was written in python 2, but that refused to work in python3 as pointed by win Today found some time to look at this and fixed the code. So here’s new improved code that works both in python 2 and python3. The new code gives user the ability to […]
Memory Profile Your code with Ipython - Lets say you have a function that you want check the memory usage in python. This can be evaluated with another IPython extension, the memory_profiler. The memory profiler extension contains two useful magic functions: the %memit magic and the %mprun function. %memit magic gives the peak and total memory used by a function, while %mprun […]
Get Activation from scikit-learn’s neural network model - I have a simple multilayer perceptron that I use on my work computer. It works well with the and has 95% accuracy on top 5 basis. It’s a delight to see it work, but I want to get more insights on what is happening inside it, one way to make it work is to see […]
Shutil make_archive to Rescue - Shutil to rescue I am amazed at the versatility of the shutil library, one usage that i discovered recently was its ability to create archives. Previously I was always using zipfile module from python but make_archive function of shutil is such an intuitive function to use. With a single line you can take backup of […]
Computer Name in Python 3 ways - Problem: Get the computer name in python without using any external module or library Solution:
Shutil to Rescue - As part of my work, need to run simulations which are driven by python’s sub process module is the work horse for this. But there’s a problem. On Windows,the subprocess module doesn’t look in the PATH unless you pass shell=True. However, shell=True can be a security risk if you’re passing arguments that may come from […]
Get Screen Size With Python Standard Library - Batteries included!! The best thing about python is the batteries included. ctypes is one such versatile module. Here’s how to use ctypes to get screen size
Sound Alarm When Program Execution Completes in Python - Often one faces a situation where your code takes extremely long to run and you don’t want to be staring at it all the time but want to know when it is done. In engineering analysis, simulation take a long time to run and the python driver program take a long time to finish and […]
Simple numpy trick to check if vector is increasing - Problem: How to check if a 1d vector is increasing……. Solution: where xp is a vector of numbers. I love numpy. When is it going to a be standard module in python?
Shelve it with python - One of the little gems hidden in python standard library is shelve. The shelve module can be used as a simple persistent storage option for Python objects when a relational database is overkill. The shelf is accessed by keys, just as with a dictionary. The values are pickled and written to a database created and […]
Participate in the 2018 Python Developer Survey - If you use python in your work or hobby projects, please consider participating in the 2018 python developer survey. Reposting a PSF-Community email as a PSA Excerpt from an email to the psf-community@python.org and psf-members-announce@python.org mailing lists: As some of you may have seen, the 2018 Python Developer Survey is available. If you haven’t taken […]
Outlook Calendar Entries for a Day with Python - For me it is not the mobile. It is the email, which is the most distraction application in office. The variable reward system has become a habit. I tried closing it but then I keep missing meetings etc. So had to keep it open just so the reminders for meetings show up. Only reason I […]
Mosaic Plot in Python - I am sure everyone one of us has seen charts like this. Any management training you attend, a version of this chart is bound to sneak up in the presentation, often in lecture notes or hands on activity. These charts are a good representation of categorical entries. A mosaic plot allows visualizing multivariate categorical data […]
Timeline in Python with Matplotlib - Was documenting a series of events and after the list was complete, thought of showing them on a timeline. After an hour two, fiddling with python standard libraries this is what I had. Format of the data The code as always available at this GitHub
Detect Outliers with Matplotlib - Problem: You have a huge large multivariate data and want to get list of outliers? Outlier detection is a significant statistical process and lot of theory under pining but there is a simple, quick way to do this is using the Inter-quartile (IQR) rule. Read the linked PDF for a simple example summary Solution: bloxplot_stats […]
Q in Statsmodels - If you are coming from R, you will love the formula API of statsmodels that work in a similar way. I love it and been using it for quite some time since last year. It’s good to test quick regression and GLM models and works on pandas dataframe which, at least in my case, are […]
Numpy Arrays to Numpy Arrays Records - Recently working with hdf5 format and the datasets in the format requires the arrays to be records. What does that mean? NumPy provides powerful capabilities to create arrays of structured datatype. These arrays permit one to manipulate the data by named fields. One defines a structured array through the dtype object. Creating them from list […]
Cross Validation Score with Statsmodels - Recently was working with a limited set of data. Using statsmodels , employed a regression model on the data. To test the confidence in the model needed to do cross validation. The solution that immediately sprang to mind was the cross_val_score function from sci-kit learn library. However, that function is not applicable on statsmodels object. […]
Parsing date – a simple example - Problem: Let’s say we have a data like the below image, it can be anything, from IOT sensors data to something like the below expense log. If the data has day, month and year as separate columns, as shown below, how to read this kind of data log with pandas and create date as the […]
Variable length list to Numpy array - Suppose you have a variable length list and you want to convert it to a numb array What is the efficient way to convert this list to a numpy array? My first answer was using pandas and this is what I did? This worked and I moved on to my other problem, but then realised […]
Panda Time index vs DateTime and Inconveniences - Sometimes convenience becomes a handicap. Saw this first hand later last month. Was so used to using Pandas DataFrame and the Timeindex object that when I had to move back to a system which didn’t have pandas I was struggling to get a simplified day of year, day of week and week of year from […]
Updated Binary STL File Reader - A recent comment on the post titled binary stl file reader in numpy prompted me to revisit the code and while I was looking at it , I updated the same for code to view the loaded stl file. The above picture shows the result. The code as usual available on github from here
Joint plot with Matplotlib - Today I am releasing a simple module to create joint plot with Matplotlib on github. Joint plot is available in the excellent seaborn library but unfortunately it’s not always available on many systems. Recently I needed this functionality, so wrote this simple module with matplotlib. The functionality is almost similar to seaborn but with limited feature. […]
Quarterly Results Analysis with Python - Every quarter when results come out, I spend sufficient hours looking at the financial results of the stocks I am tracking to elicit nagging comments from my better half. So developed this simple python script which does the analysis and generates me the PDF which I email to myself to look at during office commute. […]
OD Command in Windows with Python - I have seen OD command for last two years but had never bothered to look it up. It always remained under the surface. Life went on well without it, until now. During a recent debugging crisis, had to resort to this command for an efficient way to check binary results. All the while had to […]
Get Mount Drive from mount path in windows - Things that are simple in Linux and UNIX based system always end up becoming a head ache in windows, but unfortunately most of our work-life runs on windows. And if you don’t have admin rights to install specialized modules in your python installation, then here’s a hacked version of routine that should do the job.
Few Python Regex for FORTRAN Code - Most of my day job involves Fortran code and finding quick details is a regular need. Here are four regex in python that I have been using for some time now. Sharing it here. To Find Subroutines and Functions To Find All Call Statements To Find Variables (Integer, Double Precision, Logical, Real) […]
Simple trick to read mixed format data with numpy’s genfromtxt - Suppose your data is like the following Let’s load it with numpy using genfromtxt This prints the following Numeric data is read but not quite as what we wanted. Notice the NaN. You can supply genfromtxt the datatypes using the keyword format like dtype=([(‘f0’, ‘<i4’), (‘f1’, ‘<i4’), (‘f2’, ‘<i4’), (‘f3’, ‘<f8’), (‘f4’, ‘|S14’)]) But that […]
Quick Gantt Chart with Matplotlib - The problem: You need a quick Gantt chart for a quick proposal report and you dint have any project planner software installed. Solution: While there are many different ways, you only have access to python, well Here’s a simple Gantt chart plotter with just matplotlib. Not for rigorous use but a good substitute to make […]
Biplot in Python revisited. - Mark sent a recent email complaining the previous biplot code not working. Though I was not able to replicate his errors,but from the error message figured the error was due to the PCA numbers supplied. That reminded me of the simplification task that I intended to do on the previous version to make it work […]
Visualizing 3d Triangles With Pure Matplotlib Function - The problem: STL file is read, you want to do a quick sanity check if it’s correct and don’t have access to VTK or third party STL viewer. Solution: Use matplotlib to visualize the STL. Here’s a simple matplotlib script to visualize the STL triangles.
Matlab to Python – some code examples - Two years back, I was converting a matlab script to python, here are some of the errors that I encountered during the conversion. Found them documented in that converted script, posting them here for wider audience. Matlab to Python 1. () to [] SyntaxError: can’t assign to function call 2. 1 to 0 IndexError: index […]
Pdf With Matplotlib - I thought everyone knew about but i was surprised this this little feature of matplotlib is not that known as widely as I assumed. We all know we can save a plot from matplotlib to pdf but there other little feature hiding in the backends where we can write out a multiple page pdf Here’s […]
Biplot with Python - I have plotted Biplot in Matlab and have created it using fortran in the past. Last month, while playing with PCA, needed to plot biplots in python. Unlike MATLAB, there is no straight forward implementation of biplot in python, so wrote a simple python function to plot it given score and coefficients from a principal […]
FEM in Python A Simple Start Guide - Wrote this a couple of months back. Yet another tutorial in python, if you are interested in finite element analysis. Nicely goes with this excellent tutorial on FEM. Click the below link to view the tutorial. FEM with Python
What can Software Teams Learn From Aviation? - This pycon talk combines my two passions, aviation and software development. Grab a cold coffee and watch this very interesting talk. Just a little over half an hour, if you have any interest in any of this two stream, you will like the talk. What can Python-based software teams learn from aviation? Why should software […]
Pingback: Untar a Tar File With Python | SukhbinderSingh.com
Pingback: Coming to Numpy from Matlab – bookmark this | SukhbinderSingh.com
Pingback: Fortran from python – Python Binding for Fortran Code | SukhbinderSingh.com
Pingback: Spiral Approach to Learning | SukhbinderSingh.com