S

@supriyo_biswas

Convert env vars to "gcloud compute instances create-with-container" format

Python
3 years ago
def get_string(dct): if len(dct) == 0: return '' result = ['^'] for index, key in enumerate(dct): value = dct[key] if index == 0: result.append(f'@^{key}={value}') else:

Negative bitshift

C
3 years ago
#include <stdio.h> union A { char c[4]; int x; }; int main() { union A a; a.x = 65536;

Nodejs net.Blocklist bug

NodeJS
3 years ago
console.log('Node version ' + process.version) const net = require('net') const reservedIPBlocklist = new net.BlockList() reservedIPBlocklist.addSubnet('1.1.1.1', 32, 'ipv4') for (const ip of ["10.0.0.1", "1.1.1.1", "4.3.2.4", "27.192.11.1", "192.168.1.9"]) { console.log(ip, reservedIPBlocklist.check(ip, 'ipv4'))

Doubly linked list implementation

NodeJS
3 years ago
const assert = require('node:assert').strict class Node { constructor(value) { this.value = value this.prev = null this.next = null } unlink() {

Pagination items

NodeJS
4 years ago
function getPaginationItems(x, n) { const result = [] const start = Math.max(1, x - 2) const end = Math.min(start + 2, n) if (start > 1) { result.push(1) } if (start > 2) { result.push('...') }

Extract YAML blocks from Markdown content without regex

NodeJS
4 years ago
// const data = ` // --- // hello: world // foo: bar // --- // hello: world // --- // # Some article title

Chunk, enumerate and range generator methods in JS

NodeJS
4 years ago
function * chunk(iterable, maxSize) { let result = [] for (const item of iterable) { result.push(item) if (result.length === maxSize) { yield result result = [] } } if (result.length > 0) {

Private fields in Javascript

NodeJS
4 years ago
class Foo { #y constructor(x) { this.x = x this.#y = x * 2 } } const f = new Foo(10) console.log(f)

Splitting an array in chunks

NodeJS
4 years ago
function chunk(arr, maxSize) { const result = [] for (let i = 0; i < arr.length; i += maxSize) { result.push(arr.slice(i, i + maxSize)) } return result } function range(start, stop) { const result = []

"awaiting" in loops without async/await

NodeJS
4 years ago
function foo(message, delay) { return new Promise(resolve => { setTimeout(() => { console.log(`${message} after sleeping for ${delay}ms`) resolve() }, delay) }) } // Instead of doing this:

Reading a file line by line

NodeJS
4 years ago
const { writeFile } = require('fs/promises') const { createReadStream } = require('fs') const { createInterface } = require('readline') const data = ` --- hello: world foo: bar --- hello: world

Extract YAML blocks from Markdown content (WIP)

NodeJS
4 years ago
const data = ` --- hello: world foo: bar --- hello: world --- # Some article title

Indenting a string

NodeJS
4 years ago
function indentString(str, n) { return str.split("\n").map(x => " ".repeat(n) + x).join("\n") } const data = `foo bar baz qux buzz `

Deferring promise execution

NodeJS
4 years ago
async function foo(x) { console.log("foo", x) } async function bar(x) { throw new Error("bar" + x) } class DeferredPromiseExecutor { constructor() {

Avoiding callback hell

NodeJS
4 years ago
function foo() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("foo") }, 100) }) } function bar() { return new Promise((resolve, reject) => {

Regex validation - letters and numbers only

Go
4 years ago
package main import ( "fmt" "regexp" ) func main() { s1 := "FooBar" s2 := "Foo/Bar"

UUID regex

Java
4 years ago
import java.util.regex.Matcher; import java.util.regex.Pattern; class Main { public static void main(String[] args) { String[] uuids = { "8fff4739-5f85-452d-8955-b0b0ace74bf7", "a1234567-1023-4984-9429-029183c02b1", "a1234567-1023-4984-9429-029183c02b1f", "hello",

Working with SimpleDateFormat

Java
4 years ago
import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; class Main { public static void main(String[] args) throws Exception { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); System.out.println("Formatting a date");

Mocking classes

Java
4 years ago
import java.util.*; import java.lang.*; import java.io.*; class A { public void foo() { System.out.println("foo"); } }

Random user agent generator

Python
4 years ago
import random def make_safari_user_agent(): result = 'Mozilla/5.0 ' platform = random.randint(0, 1) if platform == 0: result += ( '(Macintosh; Intel Mac OS X 10_%d_%d) AppleWebKit/605.1.15 ' + '(KHTML, like Gecko) Version/%d.%d Safari/605.1.15' ) % (