Code Snippets (Beta)

A collection of code snippets for software developers.

Django TrimCharField Django

A CharField that ignores leading and trailing spaces in data

from django.db import models

class TrimCharField(models.CharField):
    """CharField that ignores leading and trailing spaces in data"""

    def get_prep_value(self, value):
        original_value = super(TrimCharField, self).get_prep_value(value)
        if original_value:
            return original_value.strip()

    def pre_save(self, model_instance, add):
        original_value = super(TrimCharField, self).pre_save(model_instance, add)
        if original_value:
            return original_value.strip()

Create a Result from optional value-error pair Swift

If you use ObjC APIs that have optionals for both value and error in their callback handlers, this extension to map them into a Result type might be useful.

public extension Result {
    init(value: Success?, error: Failure?) {
        switch (value, error) {
        case (let value?, _):
            self = .success(value)
        case (_, let error?):
            self = .failure(error)
            fatalError("Both value and error are nil") // or fallback to a generic error

Use first(where:) Swift

Use first(where:) to get the first element of the sequence that satisfies the given predicate.

let numbers = [1, 2, 7, 3, 4, 5, 6, 7]

let firstSeven = numbers.first { $0 == 7 }

// Instead of:
// let firstSeven = numbers.filter({ $0 == 7 }).first

Multiple levels sorting with tuples Swift

Use tuples to sort Comparable objects based on multiple properties. Example: sorting contacts by surname; then by name, to see all names from the same family in a row.

struct Person {
    let name: String
    let surname: String

extension Person: Comparable {
    static func < (lhs: Person, rhs: Person) -> Bool {
        // Compare tuples instead of properties 😉   
        (lhs.surname, < (rhs.surname,

let names = [
    Person(name: "Zelda", surname: "Appleseed"),
    Person(name: "Donald", surname: "Stevens"),
    Person(name: "John", surname: "Appleseed"),
    Person(name: "Steven", surname: "Appleseed"),
    Person(name: "Michael", surname: "Bowden")

print(names.sorted().map { "\($ \($0.surname)" })

/* prints:
    "John Appleseed",
    "Steven Appleseed",
    "Zelda Appleseed",
    "Michael Bowden",
    "Donald Stevens"

Use property observers Swift

Use Swift's property observers to observe and respond to changes in a property’s value. Both `willSet` and `didSet` takes a default parameter to get new and old values

var language: String = "ObjC" {
    willSet(newValue) {
        print("willSet \(language) to \(newValue)")
    didSet(oldValue) {
        print("didSet \(oldValue) to \(language)")

language = "Swift"

/* prints:
willSet ObjC to Swift
didSet ObjC to Swift

Generics in typealias Swift

Use a generic type in type aliases to increase code reusability. Notice how the same type alias is used for all Post, [Post], and [Book] 😎

enum APIError: Error {  }
struct Post {  }
struct Book {  }

typealias Handler<Response> = (Result<Response, APIError>) -> Void

func fetchPost(id: Int, _ completion: Handler<Post>) {  }
func fetchPosts(_ completion: Handler<[Post]>) {  }
func fetchBooks(_ completion: Handler<[Book]>) {  }

The ~= operator Swift

Use the ~= operator in Swift to check for patterns. Say you have an array and you want to get an object at index in a safe way

var index = 1
var tribes = ["BOWSER", "WM", "Ragnarök"]

// You can replace this:
// if index >= 0 && index < tribes.count {
//    print(tribes[index])
// }

// With this
if 0..<tribes.count ~= index {

Pull submodules after cloning repo Git

Pull submodules in a git repo after cloning.

git pull --recurse-submodules

Updating a feature branch Git

Bring your feature branch up to date with master.

git checkout master
git fetch -p origin
git merge origin/master
git checkout <feature-branch>
git merge master
git push origin <feature-branch>

Dark mode change detection JS

Respond to appearance changes in system preference live in the browser in macOS 10.14+ and iOS 13+. Hint: try toggling dark mode on and off and observe this website 😉

window.matchMedia('(prefers-color-scheme: dark)').addListener(({ matches }) => {
  if (matches) {
    console.log("dark theme");
  } else {
    console.log("light theme");

Make trailing slash optional in Django Django

Make trailing space optional in Django by overriding `SimpleRouter` in your ``

# In your

class OptionalSlashRouter(SimpleRouter):
  def __init__(self):
    self.trailing_slash = "/?"
    super(SimpleRouter, self).__init__()

router = OptionalSlashRouter()

Remove trailing slash from URL Nginx

Avoid duplicate content in your website analytics by removing the trailing slash from URL using Nginx

rewrite ^/(.*)/$ /$1 permanent;

# Example
server {
  listen 80;
  rewrite ^/(.*)/$ /$1 permanent;

Remove all node_modules directories Shell

Remove all node_modules directories before taking a backup of your files to make your life easier :)

find / -name node_modules -exec rm -rf {} +

LOC Per Author Git

Get number of lines contributed per each author in a git repository

git ls-files | while read f; do git blame --line-porcelain $f | grep '^author '; done | sort -f | uniq -ic | sort -n

Git Commits Per Author Git

Get number of commits in a git repository per author.

git shortlog -sn --all

List of countries JS

List of all countries - suitable for a contact page.

      "Aland Islands",
      "American Samoa",
      "Antigua and Barbuda",
      "Bonaire, Saint Eustatius and Saba",
      "Bosnia and Herzegovina",
      "Bouvet Island",
      "British Indian Ocean Territory",
      "British Virgin Islands",
      "Burkina Faso",
      "Cape Verde",
      "Cayman Islands",
      "Central African Republic",
      "Christmas Island",
      "Cocos Islands",
      "Cook Islands",
      "Costa Rica",
      "Czech Republic",
      "Democratic Republic of the Congo",
      "Dominican Republic",
      "East Timor",
      "El Salvador",
      "Equatorial Guinea",
      "Falkland Islands",
      "Faroe Islands",
      "French Guiana",
      "French Polynesia",
      "French Southern Territories",
      "Heard Island and McDonald Islands",
      "Hong Kong",
      "Isle of Man",
      "Ivory Coast",
      "Marshall Islands",
      "New Caledonia",
      "New Zealand",
      "Norfolk Island",
      "North Korea",
      "Northern Mariana Islands",
      "Papua New Guinea",
      "Puerto Rico",
      "Republic of the Congo",
      "Saint Barthelemy",
      "Saint Helena",
      "Saint Kitts and Nevis",
      "Saint Lucia",
      "Saint Martin",
      "Saint Pierre and Miquelon",
      "Saint Vincent and the Grenadines",
      "San Marino",
      "Sao Tome and Principe",
      "Saudi Arabia",
      "Sierra Leone",
      "Sint Maarten",
      "Solomon Islands",
      "South Africa",
      "South Georgia and the South Sandwich Islands",
      "South Korea",
      "South Sudan",
      "Sri Lanka",
      "Svalbard and Jan Mayen",
      "Trinidad and Tobago",
      "Turks and Caicos Islands",
      "U.S.Virgin Islands",
      "United Arab Emirates",
      "United Kingdom",
      "United States Minor Outlying Islands",
      "United States",
      "Wallis and Futuna",
      "Western Sahara",

Encode string and replace /%20/ with + JS

Encode string and replace /%20/ with + to be used in a URL

encodeURI(query).replace(/%20/g, '+');

Set navigation and tab bar titles SwiftUI

Set navigation and tab bar titles, Similar to UINavigationItem and UITabBarItem in UIKit

import SwiftUI

struct MyView : View {
    var body: some View {
        NavigationView {
            Text("Hello world!")
                .navigationBarTitle(Text("Navigation title"))
        .tabItem {
            VStack {
                Image(systemName: "circle.fill")
                Text("Tab bar title")

Embed Views in a TabbedView SwiftUI

Embed Views in a TabbedView, similar to UITabBarController in UIKit

import SwiftUI

struct ContentView : View {
    @State private var selection = 0
    var body: some View {
        TabView(selection: $selection) {

Initialize UIColor from HEX value Swift

A simple Swift extension to initialize UIColor from a hex string taking into consideration edge cases and hex representation variations

extension UIColor {
    convenience init?(hex: String) {
        var hexString = hex
        if hexString.hasPrefix("#") { // Remove the '#' prefix if added.
            let start = hexString.index(hexString.startIndex, offsetBy: 1)
            hexString = String(hexString[start...])
        if hexString.lowercased().hasPrefix("0x") { // Remove the '0x' prefix if added.
            let start = hexString.index(hexString.startIndex, offsetBy: 2)
            hexString = String(hexString[start...])
        let r, g, b, a: CGFloat
        let scanner = Scanner(string: hexString)
        var hexNumber: UInt64 = 0
        guard scanner.scanHexInt64(&hexNumber) else { return nil } // Make sure the strinng is a hex code.
        switch hexString.count {
        case 3, 4: // Color is in short hex format
            var updatedHexString = ""
            hexString.forEach { updatedHexString.append(String(repeating: String($0), count: 2)) }
            hexString = updatedHexString
            self.init(hex: hexString)
        case 6: // Color is in hex format without alpha.
            r = CGFloat((hexNumber & 0xFF0000) >> 16) / 255.0
            g = CGFloat((hexNumber & 0x00FF00) >> 8) / 255.0
            b = CGFloat(hexNumber & 0x0000FF) / 255.0
            a = 1.0
            self.init(red: r, green: g, blue: b, alpha: a)
        case 8: // Color is in hex format with alpha.
            r = CGFloat((hexNumber & 0xFF000000) >> 24) / 255.0
            g = CGFloat((hexNumber & 0x00FF0000) >> 16) / 255.0
            b = CGFloat((hexNumber & 0x0000FF00) >> 8) / 255.0
            a = CGFloat(hexNumber & 0x000000FF) / 255.0
            self.init(red: r, green: g, blue: b, alpha: a)
        default: // Invalid format.
            return nil

Get iOS application icon Swift

Get the icon for an iOS application

var appIcon: UIImage? {
  guard let icons = Bundle.main.infoDictionary?["CFBundleIcons"] as? [String: Any] else { return nil }
  guard let primaryIcon = icons["CFBundlePrimaryIcon"] as? [String: Any] else { return nil }
  guard let iconFiles = primaryIcon["CFBundleIconFiles"] as? [String] else { return nil }
  guard let lastIcon = iconFiles.last else { return nil }
  return UIImage(named: lastIcon)

Validate email address format Swift

Check whether a string has a validate email address format or not.

extension String {
    var isValidEmailAddress: Bool {
        guard !isEmpty else { return false }
        let regex = #"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"#
        guard let match = range(of: regex, options: .regularExpression, range: nil, locale: nil) else { return false }
        let aCount = distance(from: match.lowerBound, to: match.upperBound)
        return aCount == count

Check if object is Empty JS

Check if an object is Empty

function isEmpty(object) {
  return Object.getOwnPropertyNames(object).length === 0

Copy String To Clipboard JS

Copy a string to clipboard

function copyToClipboard(str) {
  var el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', ''); = {position: 'absolute', left: '-9999px'};

Create an array from a given object JS

Create an array from a given object

function arrayFromObject(obj, key = 'id') {
  return Object.keys(obj).map(key => (obj[key]));

Create an object from a given array JS

Create an object from a given array

function objectFromArray(arr, key = 'id') {
  if (arr && arr.length) {
    return arr.reduce((v, i) => {
      v[i[key]] = i;
      return v;
    }, {});
  return {};

Install Homebrew Shell

Install Homebrew

/usr/bin/ruby -e "$(curl -fsSL"

Sync a fork from original repository Git

Sync a fork of a repository to keep it up-to-date with the upstream repository.

git fetch upstream
git checkout master
git merge upstream/master
git push master

Save and retrieve Codable objects to UserDefaults Swift

Because why not 😂

public extension UserDefaults {
    public func object<T: Codable>(_ type: T.Type, with key: String, usingDecoder decoder: JSONDecoder = JSONDecoder()) -> T? {
        guard let data = value(forKey: key) as? Data else { return nil }
        return try? decoder.decode(type.self, from: data)

    public func set<T: Codable>(object: T, forKey key: String, usingEncoder encoder: JSONEncoder = JSONEncoder()) {
        let data = try? encoder.encode(object)
        set(data, forKey: key)

Decode Bool from Int or String Swift

Because, you know, sometimes the backend guys send us a 1 or TRUE and expect us to map it to native Bool object, well, they are kinda right, it shouldn't matter that much

public extension KeyedDecodingContainer where Key: CodingKey {
    public func decodeBoolAsIntOrString(forKey key: K) throws -> Bool {
        if let bool = try? decode(Bool.self, forKey: key) {
            return bool
        if let bool = try? decode(String.self, forKey: key) {
            return bool == "1"
        let int = try decode(Int.self, forKey: key)
        return int == 1

    public func decodeBoolAsIntOrStringIfPresent(forKey key: K) throws -> Bool? {
        if let bool = try? decodeIfPresent(Bool.self, forKey: key) {
            return bool
        if let bool = try? decodeIfPresent(String.self, forKey: key) {
            return bool == "1"
        if let int = try? decodeIfPresent(Int.self, forKey: key) {
            return int == 1
        return nil

Extensions Wrapper Swift

Use the power of protocols and generic types to avoid extension conflicts

public struct ExtensionsWrapper<Base> {
    public var base: Base
    public init(_ base: Base) {
        self.base = base

public protocol ExtensionsCompatible {
    associatedtype CompatibleType
    static var ext: ExtensionsWrapper<CompatibleType>.Type { get set }
    var ext: ExtensionsWrapper<CompatibleType> { get set }

extension ExtensionsCompatible {
    public var ext: ExtensionsWrapper<Self> {
        get {
            return ExtensionsWrapper(self)
        set {}

    public static var ext: ExtensionsWrapper<Self>.Type {
        get {
            return ExtensionsWrapper<Self>.self
        set {}

extension UILabel: ExtensionsCompatible {}

extension ExtensionsWrapper where Base: UILabel {
    public var trimmedText: String? {
        let aText = base.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
        if aText.isEmpty { return nil }
        return aText

Safe Collection Subscript Swift

Safe subscript protects the collection from out of bounds error by using optionals.

extension Collection {
    subscript(safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil

This is a fully integrated open-source project that uses NextJS, Redux, and Django to build. Grab your copy from Github

Copyright © 2020 Omar Albeik. All rights reserved.