S

@supriyo_biswas

View individual bits of a float

Java
3 years ago
import java.util.*; import java.lang.*; import java.io.*; class Main { public static String padLeftZeros(String inputString, int length) { if (inputString.length() >= length) { return inputString; } StringBuilder sb = new StringBuilder();

Query string serialization

NodeJS
3 years ago
function makeQueryString(params) { let result = [] for (const key in params) { if (!key) { continue } const values = params[key] for (const value of Array.isArray(values) ? values: [values]) { if (!value) { continue

curl timing breakdown

Bash
3 years ago
#!/bin/bash curl -L \ --output /dev/null \ --silent \ --show-error \ --write-out 'lookup: %{time_namelookup}\nconnect: %{time_connect}\nappconnect: %{time_appconnect}\npretransfer: %{time_pretransfer}\nredirect: %{time_redirect}\nstarttransfer: %{time_starttransfer}\ntotal: %{time_total}\n' \ http://example.com

Topological sort with loops

Python
3 years ago
import sys from pprint import pprint def topological_sort_visit(graph, node, node_list): if node in graph: if graph[node]['mark'] == 2: return if graph[node]['mark'] == 1: # there are cycles in our graph. don't go down this path

Find nearest prime less than n

Python
3 years ago
from math import floor, sqrt def prime(n): if (n & 1): n -= 2 else: n -= 1 i,j = 0,3

Private members

NodeJS
3 years ago
class Foo { #a = 0 a() { this.#a++ return this.#a } } const foo = new Foo() console.log(foo.a())

Base path of a glob pattern

NodeJS
3 years ago
// given a glob pattern, find the base path for all files that match the glob // Example: // Input: 'foo/bar/baz/**/qux/*.css' // Output: 'foo/bar/baz' const path = require('path') function getBaseOfGlobPattern(pattern) { let index = -1

DateTimeFormatter and instants (part 2)

Java
3 years ago
import java.time.format.*; import java.time.*; import java.util.*; class Main { public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HHmmss") .withZone(ZoneId.of("UTC")); String input = "20220926 053459";

Comparators

Java
3 years ago
import java.util.*; class Main { public static void main(String[] args) { ArrayList<Integer> l = new ArrayList<>(); l.add(5); l.add(10); l.add(3); l.add(4); l.sort((a, b) -> b - a);

Form generator

Python
3 years ago
import json import sys import re def camel_case(x): return re.sub('(^_+|_+$)', '', re.sub(r'[^a-zA-Z0-9]+', '_', x.strip().lower())) def generate_form(defn): result = '' for name, value in defn.items():

Decorators in Python

Python
3 years ago
class A: def __init__(self, value): self.value = value def __repr__(self): return f'A (value={self.value})' def deco(fn): def wrapper(*args, **kwargs): return A(fn(*args, **kwargs))

Encrypting data with AES-256-GCM

NodeJS
3 years ago
const crypto = require('crypto') function encrypt(plaintext, key) { const plaintextJson = JSON.stringify(plaintext) const iv = crypto.randomBytes(12) const cipher = crypto.createCipheriv('aes-256-gcm', key, iv) const enc = Buffer.concat([cipher.update(plaintextJson, 'utf8'), cipher.final()]) return [enc, iv, cipher.getAuthTag()].map(e => e.toString('base64')).join('~')

Using DateTimeFormatter

Java
3 years ago
import java.time.format.*; import java.time.*; import java.util.*; class Main { public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z") .withZone(ZoneId.of("UTC")); System.out.println("print current time");

Static blocks

Java
3 years ago
class Foo { static { System.out.println("static"); } static void bar() { System.out.println("bar"); } }

Enum toString()

Java
3 years ago
import java.util.*; import java.lang.*; import java.io.*; enum Fruit { APPLE("Apple"), ORANGE("Orange"), PEAR("Pear"), LEMON("Lemon");

Camel case text

NodeJS
3 years ago
function camelCase(text) { return text.replace(/[-_]\w/g, text => text[1].toUpperCase()) } console.log(camelCase('hello-world'))

Parsing into AST

NodeJS
3 years ago
function parse (input) { const result = {} const re = /(\w[\w-]*)(\([^\)]+\))?(?=:|$)/g let match while ((match = re.exec(input)) !== null) { if (match[2]) { const args = [] for (const item of match[2].slice(1, -1).split(',')) { const number = parseInt(item, 10) args.push(Number.isNaN(number) ? item : number)

Lambda expressions in Java

Java
3 years ago
interface TwoIntegerOperation { int run(int a, int b); } interface OneIntegerOperation { int run(int a); } class Main { public static void main(String[] args) {

Reading a file line by line

NodeJS
3 years ago
// https://stackoverflow.com/a/32599033 const { createReadStream } = require('fs') const { createInterface } = require('readline') async function main() { const input = createReadStream('/etc/passwd') const rl = createInterface({ input, crlfDelay: Infinity }) for await (const line of rl) { console.log(JSON.stringify(line))

printf left padding

Java
3 years ago
import java.util.*; import java.lang.*; import java.io.*; // The main method must be in a class named "Main". class Main { public static void main(String[] args) { for (int i = 1; i <= 10000; i *= 10) { System.out.printf("%-5d test", i); }