Snippets

Like most programmers, I keep going to some projects to copy some bits of code. From now on, I'm going to list them in one place.

Bash

Gource

Make a video of the evolution of a git repo

gource \
--hide dirnames,filenames \
--seconds-per-day 0.1 \
--auto-skip-seconds 1 -1280x720 -o - |
ffmpeg \
-y -r 60 -f image2pipe\
-vcodec ppm -i -\
-vcodec libx264 \
-preset ultrafast \
-pix_fmt yuv420p \
-crf 1 \
-threads 0 \
-bf 0 \
gource.mp4

Python

Custom Errors

To create custom errors

class AgeNotInRangeError(Exception):
"""
Exception raised for errors in the input age.

- age - age which caused the error
- message - explanation of the error
"""


def __init__(self, age, message="Age is not in range"):
self.age = age
self.message = message
super().__init__(self.message)

def __str__(self):
return f'{self.age} -> {self.message}'


age = int(input("Enter age amount: "))
if age <= 18:
raise AgeNotInRangeError(age)

Tests

To do some test-driven development, create a file at tests/test_{name}.py with some tests:

import unittest

class TestEvents(unittest.TestCase):
def test_{name}(self):
self.assertEqual(1, 1)

To run the tests, use python -m unittest discover -s tests/

Django

Create a model with a created_at and udpated_at:

class MyModel(models.Model):
# ...
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

Typescript and/or javascript

Custom Errors

To create custom errors

class HttpStatusError extends Error {
private data: Errors
private status: number

constructor(status: number, data: Errors) {
const message = `Got status ${status} for request`
super(message)
this.name = 'HttpStatusError'
this.data = data
this.status = status
}
}

To use and throw them

throw new HttpStatusError(500, { error: 'Try again later' })

Later, to catch and use them

if (err instanceof HttpStatusError) {
// ...
}

if (err.name == 'HttpStatusError') {
// ...
}

React

Dump some variable so we can visually inspect it:

<pre>{JSON.stringify(variable, null, 4)}</pre>

Tailwind

Rows and columns

<div class="container mx-auto max-w-6xl mt-8">
<div class="flex border border-blue-600 -mx-4">
<div class="w-1/4 border border-red-600 mx-4">1</div>
<div class="w-1/4 border border-red-600 mx-4">2</div>
<div class="w-1/4 border border-red-600 mx-4">3</div>
<div class="w-1/4 border border-red-600 mx-4">4</div>
</div>
</div>

By the way, I write about software development, web development, and Django. If you liked this post and were wondering how to get more... Join my inner circle (aka newsletter) in easy (and fast!) 4 steps.

  1. Fill your email.
  2. Fill your name (but only if you want).
  3. Smash the button. As hard as you can.
  4. There is no 4th step.

Add your name to join my inner circle (also known as newsletter 💌)

And that's a wrap. I hope you like it (I really do). If you did, hit one of those share buttons and spread it on your socials.