Snippets


Truncate text to oneline if parent can overflow.truncate.css
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
Scroll element into viewcenter-element.js
document.getElementById('ELEMENT_ID').scrollIntoView({
    behavior: 'smooth',
    block: 'center',
    inline: 'center'
});
Encode and decode URIencode-decode.js
const encodedString = encodeURI(stringToEncode);
const decodedString = decodeURI(encodedString);
Delete DynamoDB table if existsdelete-table.py
import boto3

client = boto3.session.Session().client('dynamodb')
existing_tables = client.list_tables()
if 'TABLE_NAME' in existing_tables['TableNames']:
    print('Table already exists. Deleting table.')
    client.delete_table(
        TableName='TABLE_NAME'
    )

    waiter = client.get_waiter('table_not_exists')
    waiter.wait(
        TableName='TABLE_NAME',
        WaiterConfig={
            'Delay': 60,
            'MaxAttempts': 30
        }
    )

    print('Table deleted.')
Export DynamoDB table to S3 using boto3export-table.py
import boto3

client = boto3.session.Session().client('dynamodb')
table_description = client.describe_table(
    TableName='TABLE_NAME'
)
export_arn = client.export_table_to_point_in_time(
    TableArn=table_description['Table']['TableArn'],
    S3Bucket='BUCKET_NAME',
    S3Prefix='PREFIX_NAME',
    ExportFormat='DYNAMODB_JSON',
    ExportType='FULL_EXPORT',
)['ExportDescription']['ExportArn']

while True:
    description = client.describe_export(
        ExportArn=export_arn
    )
    status = description['ExportDescription']['ExportStatus']

    if status == 'FAILED':
        print(description['ExportDescription']['FailureMessage'])
        sys.exit()
    elif status == 'IN_PROGRESS':
        print('Export still in progress. Checking again after 1 minute.')
        time.sleep(60)
    else:
        print('Export completed.')
        break
Turn on Point-In-Time Recovery for DynamoDB using boto3toggle-pitr.py
import boto3

client = boto3.session.Session().client('dynamodb')
client.update_continuous_backups(
    TableName='TABLE_NAME,
    PointInTimeRecoverySpecification={
        'PointInTimeRecoveryEnabled': True
    }
)
Print Color in Pythonprint_color.py
def print_warning(message):
    print('\033[93m' + str(message) + '.\033[0m')

def print_error(message):
    print('\033[91m' + str(message) + '.\033[0m')
Logging in Pythonlog.py
import logging

logging.basicConfig(filename=str(time.time()) + '.log', level=logging.INFO)

def log(message):
    logging.info(str(datetime.now()) + ': ' + message)
Processes in Pythonprocesses.py
from multiprocessing import Process

def start_processes(items, param):
    processes = []

    for item in items:
        process = Process(target=do_something, args=(item,param,))
        processes.append(process)
        process.start()

    for process in processes:
        process.join()

def do_something(item, param):
    print('do something')
Threads in Pythonthreads.py
from threading import Thread

def start_threads(items, param):
    threads = []

    for item in items:
        thread = Thread(target=do_something, args=(item,param,))
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

def do_something(item, param):
    print('do something')
Measure total script timetimer.py
import time

start = time.time()
print(round((time.time() - start) / 60, 2), 'minutes.')
Listen to URL changeurl-change.js
this.urlObserver = new MutationObserver(() => {
    if (window.location.href !== previousUrl) {
        previousUrl = window.location.href;
        console.info('URL CHANGED!');
    }
});

this.urlObserver.observe(document, { subtree: true, childList: true });
Sanitize user inputsanitize.ts
/**
 * Sanitizes the provided input
 * @param input The input to be sanitized
 */
static sanitize(input: string): string {
    return input ? input.replaceAll(/(<([^>]+)>)/gi, '') : '';
}
Copy to Clipboardcopy.js
navigator.clipboard.writeText(text);
URL Parameter Serviceurl-parameter.service.ts
import { inject } from 'aurelia-dependency-injection';
import { Router } from 'aurelia-router';

/**
 * This class handles store management through URL parameters
 */
export class UrlParameterService {
    constructor(@inject(Router) private router: Router) {}

    /**
     * Gets the value of the URL parameter
     * @param key Parameter name to retrieve
     * @returns Parameter value
     */
    get(key: string): string {
        const url = new URL(window.location.href);

        return url.searchParams.get(key);
    }

    /**
     * Adds or updates URL parameter value
     * @param key Name of the parameter
     * @param value Parameter value
     */
    set(key: string, value: string): void {
        const url = new URL(window.location.href);
        url.searchParams.set(key, value);

        this.updateNavigation(url);
    }

    /**
     * Removes an existing URL parameter entry
     * @param key Name of the parameter to remove
     */
    remove(key: string): void {
        const newUrl = new URL(window.location.origin + window.location.pathname);
        const oldUrl = new URL(window.location.href);
        for (const [parameter, value] of oldUrl.searchParams.entries()) {
            if (parameter !== key) {
                newUrl.searchParams.set(parameter, value);
            }
        }

        this.updateNavigation(newUrl);
    }

    /**
     * Updates the current navigation
     * @param url URL object to navigate to
     */
    private updateNavigation(url: URL): void {
        this.router.navigate(`${this.router.currentInstruction.fragment}${url.search}`);
    }
}
File Servicefile.service.ts
/**
 * This class is used to handle files from the API
 */
export class FileService {
    /**
     * Creates and downloads file
     * @param filename Default name of the file on save
     * @param type Type of the file to save as
     * @param content File content in bytes
     */
    downloadFile(filename: string, type: string, content: string): void {
        // Create blob with file content
        const fileData = new Blob([this.encodeArrayBuffer(content)], { type });

        // Create a hidden HTML element to perform download
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(fileData);
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    /**
     * Encodes file content to array buffer
     * @param content File content string
     * @returns Array buffer to create blob with
     */
    private encodeArrayBuffer(content: string): Uint8Array {
        // Decode a string of Base64-encoded data into bytes
        const binaryString = window.atob(content);

        // Create an array of unicode values
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
            const asciiValue = binaryString.charCodeAt(i);
            bytes[i] = asciiValue;
        }

        return bytes;
    }
}
Type Guardtype-guard.ts
/**
 * Type guard to check whether provided animal is a dog
 * @param animal Animal object to check
 * @returns Whether animal is a dog
 */
private isDog(animal: any): animal is Dog {
    return !!animal.isCute;
}
CSS Resetreset.css
html {
    box-sizing: border-box;
    font-size: 16px;
}

*, *:before, *:after {
    box-sizing: inherit;
}

body, h1, h2, h3, h4, h5, h6, p, ol, ul {
    margin: 0;
    padding: 0;
    font-weight: normal;
}

ol, ul {
    list-style: none;
}

img {
    max-width: 100%;
    height: auto;
}
Generate GUIDgenerate-guid.js
const guid = crypto.randomUUID();
Remove duplicate strings from arrayunique-strings.js
const uniqueStrings = [...new Set(['a', 'b', 'a'])]
How to parse current URLurl.js
// https://ui.dev/get-current-url-javascript/?comments=false

const {
    host, hostname, href, origin, pathname, port, protocol, search
} = window.location

host // "ui.dev"
hostname // "ui"
href // "https://ui.dev/get-current-url-javascript/?comments=false"
origin // "https://ui.dev"
pathname // "/get-current-url-javascript/""
port // ""
protocol // "https:"
search // "?comments=false"
Create a unique filename in case of duplicatesunique-filename.ts
/**
 * Sets unique file name to avoid duplicates or overrides
 * @param originalName Full filename of the original to duplicate from
 * @param existingNames Full filenames of all existing files
 */
static generateDuplicateFilename(originalName: string, existingNames: string[]): string {
    const [originalFileName, extension] = originalName.split('.');
    let editedFileName = originalFileName;
    if (existingNames.some((existingName) => existingName.split('.')[0] === originalFileName)) {
        let index = 1;
        do {
            editedFileName = `${originalFileName} (${index++})`;
        } while (existingNames.some((existingName) => existingName.split('.')[0] === editedFileName));
    }

    return `${editedFileName}.${extension}`;
}
Recommend VSCode extensions for a projectextensions.json
{
    "recommendations": [
        "dbaeumer.vscode-eslint",
        "esbenp.prettier-vscode",
        "ecmel.vscode-html-css",
        "sibiraj-s.vscode-scss-formatter",
        "formulahendry.auto-rename-tag",
        "kamikillerto.vscode-colorize",
        "deque-systems.vscode-axe-linter",
        "streetsidesoftware.code-spell-checker",
        "aaron-bond.better-comments",
        "vincaslt.highlight-matching-tag",
        "oderwat.indent-rainbow",
        "christian-kohler.path-intellisense",
        "YoavBls.pretty-ts-errors"
    ]
}
Since I always forget the new deep copy methoddeep-copy.js
structuredClone(object);
Open HTML snippet in a new tabopen-html.js
const windowUrl = URL.createObjectURL(new Blob([htmlString], { type: 'text/html' }));
const openedWindow = window.open(windowUrl);
openedWindow.document.close();
Global state manager for your sitemailbox.service.ts
import { BehaviorSubject } from 'rxjs';

/**
 * Stores global states
 */
export class MailboxService {
    /** Stores state of whether page is loading */
    isPageLoading = new BehaviorSubject<boolean>(false);

    /** Listen to page loading state changes */
    isPageLoading$ = this.isPageLoading.asObservable();
}
Style your scrollbarscrollbar.css
::-webkit-scrollbar {
    width: 8px;
}

::-webkit-scrollbar-thumb {
    border-radius: 5px;
    background-color: #c0c0c0;
}
Change highlight colorhighlight.css
::selection {
    background: #fce38a;
}
Adds NES cursor to your website.nes.css
.nes * {
  cursor: url(https://raw.githubusercontent.com/nostalgic-css/NES.css/develop/assets/cursor.png), auto !important;
}

.nes a,
.nes button {
  cursor: url(https://raw.githubusercontent.com/nostalgic-css/NES.css/develop/assets/cursor-click.png), pointer !important;
}
My favorite font settingsfont.css
html {
  font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial,
    Noto Sans, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", Segoe UI Symbol, "Noto Color Emoji";
  font-feature-settings: normal;
}