S

@supriyo_biswas

Parsing date and time

Go
4 years ago
package main import ( "fmt" "time" ) func main() { ts := "Sat Feb 26 17:00:35 2022" layout := "Mon Jan 02 15:04:05 2006"

Returning subclass with base class in return type

Java
4 years ago
import java.util.*; import java.lang.*; import java.io.*; class Base { } class A extends Base { protected int a; protected int b;

Performance measurement API

NodeJS
4 years ago
const { performance } = require('perf_hooks'); function doSomeLongRunningProcess() { let result = 0 for (let i = 0; i < 45000; i++) { result += i } } performance.mark('A')

Python variable dumper

Python
4 years ago
# From: https://github.com/supriyo-biswas/vardumper/blob/master/dump.py import inspect from sys import stdout def _should_dump_repr(obj): return inspect.ismethod(obj) \ or inspect.isfunction(obj) \ or inspect.isgenerator(obj) \ or inspect.istraceback(obj) \

Quoting shell characters

Go
4 years ago
package main import ( "fmt" "regexp" ) var shellQuoteRegex = regexp.MustCompile("([&; \t\n<>|'\"])") func shellQuote(s string) string {

Find closest value in BST

Python
4 years ago
# Write a function that takes in a Binary Search Tree (BST) and a target # integer value and returns the closest value to that target value contained # in the BST. You can assume that there will only be one closest value. # Each BST node has an integer value, a left child node, and a right child node. # A node is said to be a valid BST node if and only if it satisfies the BST # property: its value is strictly greater than the values of every node to its # left; its value is less than or equal

Non-constructible change

Python
4 years ago
# Given an array of positive integers representing the values of coins # in your possession, write a function that returns the minimum amount # of change (the minimum sum of money) that you cannot create. The given # coins can have any positive integer value and aren't necessarily unique # (i.e., you can have multiple coins of the same value). # For example, if you're given coins = [1, 2, 5], the minimum amount of change # that you can't create is 4. If you're given no coins, the minimum amoun

Sorted squared array

Python
4 years ago
# Write a function that takes in a non-empty array of integers that are # sorted in ascending order and returns a new array of the same length # with the squares of the original integers also sorted in ascending order. # Sample Input # array = [1, 2, 3, 5, 6, 8, 9] # Sample Output # [1, 4, 9, 25, 36, 64, 81] # Solution 1: Time complexity: O(n), Space complexity: O(n) space including

Validate subsequence

Python
4 years ago
# Given two non-empty arrays of integers, write a function that # determines whether the second array is a subsequence of the first one. # A subsequence of an array is a set of numbers that aren't necessarily # adjacent in the array but that are in the same order as they appear in # the array. For instance, the numbers [1, 3, 4] form a subsequence of the # array [1, 2, 3, 4], and so do the numbers [2, 4]. Note that a single number # in an array and the array itself are both valid subsequences

Two number sum

Python
4 years ago
# Write a function that takes in a non-empty array of distinct integers # and an integer representing a target sum. If any two numbers in the # input array sum up to the target sum, the function should return them in # an array, in any order. # If no two numbers sum up to the target sum, the function should return an # empty array. # Note that the target sum has to be obtained by summing two different # integers in the array; you can't add a single integer to itself in order

256 colors demo

Python
4 years ago
# Printing in color with Python # Pure Python 3.x demo, 256 colors # Works with bash under Linux and MacOS fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m" bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m" def print_six(row, format, end="\n"): for col in range(6): color = row*6 + col - 2

chunk characters into groups of 4

Python
4 years ago
import secrets def chunk(s): result = '' for i, char in enumerate(s): if i % 4 == 0 and i % len(s) != 0: result += '-' result += char return result

Password hashing performance

PHP
4 years ago
<?php function timeit(callable $func, array $args, int $times = 50000) { if ($times < 1) { throw new InvalidArgumentException('times must be greater than 1'); } $total = 0;

Awaiting a promise from many functions

NodeJS
5 years ago
let bar = null let fooPromise = null const foo = () => new Promise(resolve => setTimeout(() => { bar = 123 resolve(4000) }, 5000)) const func1 = async (id) => { if (fooPromise === null) {

Condition matcher

Python
5 years ago
import re def match_condition(rule, s): if s == None: return False elif rule[0] == '/' and rule[-1] == '/': return bool(re.search(rule[1:-1], s)) elif rule[0] == '/' and rule[-2:] == '/i': return bool(re.search(rule[1:-2], s, re.I))

Inspecting the sockaddr_in6 structure

C
5 years ago
#include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> int main() { // a sockaddr_in6 stores ipv6 addresses. printf("struct sockaddr_in6: %lu\n\n", sizeof(struct sockaddr_in6)); printf("-> sa_family_t sin6_family: %lu\n", sizeof(sa_family_t)); printf("-> in_port_t sin6_port: %lu\n", sizeof(in_port_t));

Generating SMTP responses

Python
5 years ago
def smtp_response(code, lines): response = [] for i in range(len(lines) - 1): response.append(b'%i-%s\r\n' % (code, lines[i].encode())) response.append(b'%i %s\r\n' % (code, lines[-1].encode())) return b''.join(response) if __name__ == '__main__':

Parsing SMTP commands

Python
5 years ago
import re def parse_command(cmd): result = [] for part in re.split(rb'\s+', cmd): result.append(re.sub(rb'^(\w+)', lambda p: p[1].lower(), part).decode()) return result if __name__ == '__main__':

R plot test

R
6 years ago
x1 <- seq(-4, 4, 0.1) x1 y1 <- exp(2*x1) y1 plot(x1, y1, xlab = "X", ylab = "Y")

fix_array

PHP
6 years ago
<?php function fix_array(array $a) { $result = []; foreach ($a as $char => $values) { foreach ($values as $lang => $value) { $result[$lang][$value] = $char; }