@supriyo_biswas

Check varying bits for Random.nextFloat()

updated November 23, 2022 · Java
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();
        while (sb.length() < length - inputString.length()) {
            sb.append('0');
        }
        sb.append(inputString);
    
        return sb.toString();
    }

    public static void main(String[] args) {

View individual bits of a float

updated November 23, 2022 · Java
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();
        while (sb.length() < length - inputString.length()) {
            sb.append('0');
        }
        sb.append(inputString);
    
        return sb.toString();
    }

    public static void main(String[] args) {

Query string serialization

updated November 23, 2022 · NodeJS
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
            }
            result.push(encodeURI(key) + '=' + encodeURI(value))
        }
    }
    return result.join('&')
}

console.log(makeQueryString({'foo': '1', 'bar': '2', 'baz': ['a', 'b']}))

curl timing breakdown

November 19, 2022 · Bash
#!/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://[Log in to view URL]

Topological sort with loops

updated November 17, 2022 · Python
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
            return
            
        graph[node]['mark'] = 1
        for child in graph[node]['children']:
            topological_sort_visit(graph, child, node_list)

        graph[node]['mark'] = 2

    # since 

Find nearest prime less than n

updated November 15, 2022 · Python
from math import floor, sqrt

def prime(n):
	if (n & 1):
		n -= 2
	else:
		n -= 1
	
	i,j = 0,3

	for i in range(n, 2, -2):
		if i % 2 == 0:
			continue

		while j <= floor(sqrt(i)) + 1:
			if i % j == 0:
				break
			j += 2

		if (j > floor(sqrt(i))):
			return i

	return 2

print(prime(int(input())))

Private members

November 14, 2022 · NodeJS
class Foo {
    #a = 0
    a() {
        this.#a++
        return this.#a
    }
}

const foo = new Foo()
console.log(foo.a())
console.log(foo.a())

Base path of a glob pattern

updated October 26, 2022 · NodeJS
// 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
    const parts = pattern.split(/[\/\\]+/)
    for (let i = 0; i < parts.length; i++) {
        if (/[*?]|\[.+\]/.test(parts[i])) {
            index = i
            break
        }
    }
    return index === - 1 ? '' : path.join(...parts.slice(0, index))
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";
        long inputSeconds = ZonedDateTime.parse(input, formatter).toInstant().getEpochSecond();
        long nowSeconds = Instant.now().getEpochSecond();

        System.out.println("now = " + nowSeconds)

Comparators

updated September 17, 2022 · Java
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);
        // l.sort((a, b) -> {
        //   if (a == b) {
        //     return 0;
        //   }
        //   if (a > b) {
        //     return -1;
        //   }
        //   return 1;
        // });
        System.out.println(l);
    }
}

Form generator

updated September 08, 2022 · Python
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():
        ftype = value[0]
        if ftype != 'check':
            result += f'<div className="flex flex-row items-center">{name}</div>\n<div className="col-span-3">\n'
        else:
            result += '<div className="col-span-1 md:col-span-4">\n'

        if ftype == 'text':
  

Decorators in Python

August 26, 2022 · Python
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))
    return wrapper

@deco
def add(a, b):
    return a + b
    
print(add(10, 20))

Encrypting data with AES-256-GCM

updated August 11, 2022 · NodeJS
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('~')
}

function decrypt(ciphertext, key) {
    const [enc, iv, authTag] = ciphertext.split('~').map(e => Buf

Using DateTimeFormatter

updated August 10, 2022 · Java
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");
        Date now = new Date();
        
        ZonedDateTime zdt = now.toInstant().atZone(ZoneId.of("UTC"));
        
        System.out.printf("%s %s\n", now.getClass(), now);
        Syst

Static blocks

updated August 09, 2022 · Java
class Foo {
    static {
        System.out.println("static");
    }
    
    static void bar() {
        System.out.println("bar");
    }
}

class Main {
    public static void main(String[] args) {
        System.out.println("main");
        Foo.bar();
    }
}

Enum toString()

updated July 26, 2022 · Java
import java.util.*;
import java.lang.*;
import java.io.*;

enum Fruit {
    APPLE("Apple"),
    ORANGE("Orange"),
    PEAR("Pear"),
    LEMON("Lemon");
    
    private final String text;
    
    Fruit(final String text) {
        this.text = text;
    }
    
    @Override
    public String toString() {
        return this.text;
    }
}

class Main {
    public static void main(String[] args) {
        System.out.println(Fruit.APPLE);
    }
}

Camel case text

updated July 22, 2022 · NodeJS
function camelCase(text) {
    return text.replace(/[-_]\w/g, text => text[1].toUpperCase())
}

console.log(camelCase('hello-world'))

Parsing into AST

updated July 25, 2022 · NodeJS
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)
      }
      result[match[1]] = args
    } else {
      result[match[1]] = true
    }
  }
  return result
}

const input = 'abcd java:run(java:bar)

Lambda expressions in Java

updated July 22, 2022 · Java
interface TwoIntegerOperation {
    int run(int a, int b);
}

interface OneIntegerOperation {
    int run(int a);
}

class Main {
    public static void main(String[] args) {
        TwoIntegerOperation add = (a, b) -> a + b;
        TwoIntegerOperation subtract = (a, b) -> a - b;
        
        System.out.println("3 + 2 = " + add.run(3, 2));
        System.out.println("4 - 3 = " + subtract.run(4, 5));
        
        OneIntegerOperation increment = (int a) -> a + 1;
        System.out.print

Reading a file line by line

July 18, 2022 · NodeJS
// https://[Log in to view URL]

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))
    }
}

main().catch(console.error)