Code Snippets (Beta)

A collection of code snippets for software developers.

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 `urls.py`

# In your urls.py

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;
  server_name www.mysite.com;
  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.

[
      "Afghanistan",
      "Aland Islands",
      "Albania",
      "Algeria",
      "American Samoa",
      "Andorra",
      "Angola",
      "Anguilla",
      "Antarctica",
      "Antigua and Barbuda",
      "Argentina",
      "Armenia",
      "Aruba",
      "Australia",
      "Austria",
      "Azerbaijan",
      "Bahamas",
      "Bahrain",
      "Bangladesh",
      "Barbados",
      "Belarus",
      "Belgium",
      "Belize",
      "Benin",
      "Bermuda",
      "Bhutan",
      "Bolivia",
      "Bonaire, Saint Eustatius and Saba",
      "Bosnia and Herzegovina",
      "Botswana",
      "Bouvet Island",
      "Brazil",
      "British Indian Ocean Territory",
      "British Virgin Islands",
      "Brunei",
      "Bulgaria",
      "Burkina Faso",
      "Burundi",
      "Cambodia",
      "Cameroon",
      "Canada",
      "Cape Verde",
      "Cayman Islands",
      "Central African Republic",
      "Chad",
      "Chile",
      "China",
      "Christmas Island",
      "Cocos Islands",
      "Colombia",
      "Comoros",
      "Cook Islands",
      "Costa Rica",
      "Croatia",
      "Cuba",
      "Curacao",
      "Cyprus",
      "Czech Republic",
      "Democratic Republic of the Congo",
      "Denmark",
      "Djibouti",
      "Dominica",
      "Dominican Republic",
      "East Timor",
      "Ecuador",
      "Egypt",
      "El Salvador",
      "Equatorial Guinea",
      "Eritrea",
      "Estonia",
      "Ethiopia",
      "Falkland Islands",
      "Faroe Islands",
      "Fiji",
      "Finland",
      "France",
      "French Guiana",
      "French Polynesia",
      "French Southern Territories",
      "Gabon",
      "Gambia",
      "Georgia",
      "Germany",
      "Ghana",
      "Gibraltar",
      "Greece",
      "Greenland",
      "Grenada",
      "Guadeloupe",
      "Guam",
      "Guatemala",
      "Guernsey",
      "Guinea",
      "Guinea-Bissau",
      "Guyana",
      "Haiti",
      "Heard Island and McDonald Islands",
      "Honduras",
      "Hong Kong",
      "Hungary",
      "Iceland",
      "India",
      "Indonesia",
      "Iran",
      "Iraq",
      "Ireland",
      "Isle of Man",
      "Israel",
      "Italy",
      "Ivory Coast",
      "Jamaica",
      "Japan",
      "Jersey",
      "Jordan",
      "Kazakhstan",
      "Kenya",
      "Kiribati",
      "Kosovo",
      "Kuwait",
      "Kyrgyzstan",
      "Laos",
      "Latvia",
      "Lebanon",
      "Lesotho",
      "Liberia",
      "Libya",
      "Liechtenstein",
      "Lithuania",
      "Luxembourg",
      "Macao",
      "Macedonia",
      "Madagascar",
      "Malawi",
      "Malaysia",
      "Maldives",
      "Mali",
      "Malta",
      "Marshall Islands",
      "Martinique",
      "Mauritania",
      "Mauritius",
      "Mayotte",
      "Mexico",
      "Micronesia",
      "Moldova",
      "Monaco",
      "Mongolia",
      "Montenegro",
      "Montserrat",
      "Morocco",
      "Mozambique",
      "Myanmar",
      "Namibia",
      "Nauru",
      "Nepal",
      "Netherlands",
      "New Caledonia",
      "New Zealand",
      "Nicaragua",
      "Niger",
      "Nigeria",
      "Niue",
      "Norfolk Island",
      "North Korea",
      "Northern Mariana Islands",
      "Norway",
      "Oman",
      "Pakistan",
      "Palau",
      "Palestine",
      "Panama",
      "Papua New Guinea",
      "Paraguay",
      "Peru",
      "Philippines",
      "Pitcairn",
      "Poland",
      "Portugal",
      "Puerto Rico",
      "Qatar",
      "Republic of the Congo",
      "Reunion",
      "Romania",
      "Russia",
      "Rwanda",
      "Saint Barthelemy",
      "Saint Helena",
      "Saint Kitts and Nevis",
      "Saint Lucia",
      "Saint Martin",
      "Saint Pierre and Miquelon",
      "Saint Vincent and the Grenadines",
      "Samoa",
      "San Marino",
      "Sao Tome and Principe",
      "Saudi Arabia",
      "Senegal",
      "Serbia",
      "Seychelles",
      "Sierra Leone",
      "Singapore",
      "Sint Maarten",
      "Slovakia",
      "Slovenia",
      "Solomon Islands",
      "Somalia",
      "South Africa",
      "South Georgia and the South Sandwich Islands",
      "South Korea",
      "South Sudan",
      "Spain",
      "Sri Lanka",
      "Sudan",
      "Suriname",
      "Svalbard and Jan Mayen",
      "Swaziland",
      "Sweden",
      "Switzerland",
      "Syria",
      "Taiwan",
      "Tajikistan",
      "Tanzania",
      "Thailand",
      "Togo",
      "Tokelau",
      "Tonga",
      "Trinidad and Tobago",
      "Tunisia",
      "Turkey",
      "Turkmenistan",
      "Turks and Caicos Islands",
      "Tuvalu",
      "U.S.Virgin Islands",
      "Uganda",
      "Ukraine",
      "United Arab Emirates",
      "United Kingdom",
      "United States Minor Outlying Islands",
      "United States",
      "Uruguay",
      "Uzbekistan",
      "Vanuatu",
      "Vatican",
      "Venezuela",
      "Vietnam",
      "Wallis and Futuna",
      "Western Sahara",
      "Yemen",
      "Zambia",
      "Zimbabwe"
]

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) {
            View1().tag(0)
            View2().tag(1)
            View3().tag(2)
        }
    }
}

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', '');
  el.style = {position: 'absolute', left: '-9999px'};
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
}

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 https://raw.githubusercontent.com/Homebrew/install/master/install)"

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 © 2019 Omar Albeik. All rights reserved.