Display 2D array

#for visual purpose : with row/col labels
def data_frame(ary,rows,cols):
	frame = pd.DataFrame(ary,columns=cols)
	frame.insert(0,'x', rows )
	return frame

SINGLETON factory

You can define Singleton class manually, but if you want to create multiple different Singleton classes on the fly then you can use the function below :

#Factory : to create Singleton classes
def singleton(new_klass, klass): 

	def new(cls, *args, **kvargs):
		if not hasattr(cls, 'instance'):
			cls.instance = klass(*args, **kvargs)
		return cls.instance

	globals()[new_klass] = type(new_klass, (object,), {'__new__' : new})

Deep REDUCE

#apply different reduce-fun at every lvl of hierarchy
#! on firt call len(lol) must be > 2
def deep_reduce(funs, LoL):

	def isi(a): return isinstance(a, (list,tuple,types.GeneratorType)) #or is_iter(a)
	def calc(a,b):
		# print('--=', funs[0],a,b)
		a1 = deep_reduce(funs[1:], a) if isi(a) else a
		b1 = deep_reduce(funs[1:], b) if isi(b) else b
		return funs[0](a1,b1)	

	if isi(LoL): return reduce(calc,LoL)
	else: return LoL

Check if INTEGER

#.isdigit() and .isnumeric() dont detect negative ints
def is_int(astr):
	isit = True
	try: int(astr)
	except ValueError: isit = False	
	return isit

Progress bar

def progress(percent=0, width=30):
    left = width * percent // 100
    right = width - left
    print('\r[', '#' * left, ' ' * right, ']',
          f' {percent:.0f}%',
          sep='', end='', flush=True)

Bi-directional dictionary

import os
import json

class BiDict(dict):
	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		self.inverse = {}
		for key, value in self.items():
			self.inverse.setdefault(value,key) 

	def __setitem__(self, key, value):
		if key in self : del self.inverse[self[key]]
		super().__setitem__(key, value)
		self.inverse.setdefault(value,key)		

	def __delitem__(self, key):
		value = self[key]
		if value in self.inverse : del self.inverse[value]
		super().__delitem__(key)

	def pop(self,key):
		value = super().pop(key)
		self.inverse.pop(value)
		return value

	def load(self, path, name):
		assert os.path.isdir(path), f'dir: {path} does not exists'

		full = f'{path}/{name}'
		with open(full,'r') as fh : self.__init__(json.load(fh))


	def save(self, path, name):
		assert os.path.isdir(path), f'dir: {path} does not exists'

		full = f'{path}/{name}'
		with open(full,'w') as fh :
			json.dump(self, fh, sort_keys=True, indent=2)

class AttrBiDict(BiDict):
	def __init__(self, *args, **kwargs):
		super(AttrBiDict, self).__init__(*args, **kwargs)
		self.__dict__ = self

	def __hash__(self): return hash(str(self))
	def __eq__(self,other): return self.__hash__() == other.__hash__()

Generate all permuted pairs in all positions

The question is how to generate all permutations of sequence of numbers. The caveat is to generate the numbers in all positions i.e. [X,Y] and [Y,X], but best to show how it works …

:- initialization(main).

%% for list of items
ppairs(Lst,[A,B]) :- 
   is_list(Lst), length(Lst,N), 
   between(1,N,X), between(1,N,Y), nth1(X,Lst,A), nth1(Y,Lst,B).
%% for numbers
ppairs(N,Pair) :- integer(N), ppairs(1,N,Pair).
ppairs(From, To, [X, Y]) :- between(From, To, X), between(From, To, Y).

main :- 
  %% all pairs of 1 .. 3
  findall(P,ppairs(3,P),L), write(L), write('\n'),
  %% all pairs of a,b,c
  findall(P2,ppairs([a,b,c],P2),L2), write(L2).


----

[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
[[a,a],[a,b],[a,c],[b,a],[b,b],[b,c],[c,a],[c,b],[c,c]]

Java : chop and chomp

Perl have very handy Functions to clean up trailing garbage in Strings …

  • chop : deletes the last character of a string. Useful when you append delimiter in a loop, so that the last addition has to be cleaned up
  • chomp : removes trailing sequence of the same character. if the character/s at the end do not match the specs nothing is deleted. Useful to cleanup new-lines/s at the end. Normally happens when reading from file.

Here are those useful Functions implemented for Java :

public class Main {
  
  public static <ARG> void say(ARG arg) { System.out.println(arg); }

  //removing trailing characters
  public static String chomp(String str, Character repl) {
    int ix = str.length();
    for (int i=ix-1; i >= 0; i-- ){
      if (str.charAt(i) != repl) break;
      ix = i;
    }
    return str.substring(0,ix);
  }
  
  //default case, removing trailing newlines
  public static String chomp(String str) {
    return chomp(str,'\n');
  }  

  //hardcut  
  public static String chop(String str) {
    return str.substring(0,str.length()-1);
  }
  
  public static void main(String[] args) {
    say(chomp("hi...",'.'));
    say(chomp("hello\n\n",'\n'));
    say(chomp("hello\n\n"));
    say(chop("howdy."));
    say(chomp("hi...++",'.'));      
  }
}

------

hi
hello
hello
howdy
hi...++

Timing code

This one is quick.

Java

Here is how you do it :

import java.lang.Thread;  

public class Main {
  public static void main(String[] args)  throws Exception {
        
    long startTime = System.nanoTime();
    Thread.sleep(3000);
    long endTime = System.nanoTime();
    //divide by 1000000 to get milliseconds.
    int duration = (int) ((endTime - startTime) / (1000000 * 1000));  

    System.out.println("it took: " + duration + " secs");
  }
}

-----

it took: 3 secs

Prolog

?- numlist(1, 100, L).
L = [1, 2, 3, 4, 5, 6, 7, 8, 9|...].

?- time(numlist(1, 100, L)).
% 105 inferences, 0.000 CPU in 0.000 seconds (94% CPU, 1126344 Lips)
L = [1, 2, 3, 4, 5, 6, 7, 8, 9|...].

Python

For Python look at this post : Timing code execution