{{(quickSearchResults.length>10)?'10+':(quickSearchResults.length)}} {{(quickSearchResults.length==1)?'result':'results'}}
{{result.title}} {{result.timeStamp | mysql2ymd }}
I am sorry, no such article was written yet.
Converting pipe-separated values in a list of maps
1 files attached: asPsv.java
public List<Map<String, String>> asPsv() {
        List<Map<String, String>> result = new ArrayList<>();
        String[] lines = Arrays.stream(this.asString().split("[\\r\\n]"))
                .filter(line -> line.length() > 0)
                .filter(line -> !line.startsWith("|--"))
                .filter(line -> line.charAt(0) != '#').toArray(String[]::new);
        String[] header = lines[0].split("\\|");
        for (int lineIndex = 1; lineIndex < lines.length; lineIndex++) {
            Map<String, String> currentRow = new HashMap<>();
            String[] currentCells = lines[lineIndex].split("\\|");
            for (int columnIdx = 0; columnIdx < currentCells.length; columnIdx++) {
                if (columnIdx < header.length)
                    currentRow.put(header[columnIdx].trim(), currentCells[columnIdx].trim());
        return result;
JSON report appender
1 files attached: JsonLogger.java
import com.google.gson.Gson;
import groovy.json.JsonSlurper;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class JsonLogger {
    private final Path path;
    private final File file;

    public JsonLogger(File file) {
        this.file = file;
        this.path = file.toPath();

    public void add(Map data) {
        if (!file.exists()) {
            if (!file.getParentFile().exists())
        String text = new Gson().toJson(data);
        TryRun(() -> Files.write(path, Collections.singleton(text), StandardCharsets.UTF_8, StandardOpenOption.APPEND));

    public List<Map> readAll() {
        return TryGet(() -> Files.readAllLines(path).stream().map(row -> (Map) new JsonSlurper().parseText(row)).collect(Collectors.toList()));
Oracle JDBC wrapper
3 files attached: OracleJdbcConnector.java OracleJdbcRowset .java sample.groovy
OracleJdbcConnector.java OracleJdbcRowset .java sample.groovy
def conn=new OracleJdbcConnector(URL,USER,PASS);
println conn.select("select 1+? from dual where 2=?",3,4);
println conn.execute("update table where field=? and expr=?+4",value1,value2);
Digitize/dedigitize - data to image and reverse
Simple way to convert text/byte data to image and reverse.
2 files attached: Dedigitizer.java Digitizer.gsp
Dedigitizer.java Digitizer.gsp
Why you don't need a browser plugin to control online video speed
Why you don't need a browser plugin to control online video speed:
If you have an HTML 5 modern browser with proper support for media (videos in this example) you may control the speed of the videos by simple JavaScript snippets that you may put in your favourites bar.
3 files attached: decrease.js reset.js increase.js
decrease.js reset.js
Simple compression/decompression functions for byte arrays
1 files attached: Compression.java
package eu.sorescu.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class Compression {
    public static byte[] compress(byte[] in) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zipOut = new java.util.zip.ZipOutputStream(baos);
        zipOut.putNextEntry(new java.util.zip.ZipEntry("data"));
        return baos.toByteArray();

    public static byte[] decompress(byte[] in) throws IOException {
        ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(in));
        return zis.readAllBytes();
simple XLSX parser in Java - returns a map with a list of rows for each sheet
1 files attached: XlsxReader.java
package eu.sorescu.io;

import eu.sorescu.lang.Try;
import groovy.lang.Tuple2;
import groovy.util.Node;
import groovy.util.XmlParser;
import groovy.xml.QName;
import org.codehaus.groovy.runtime.ArrayUtil;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class XlsxReader {
    private final Map<String, byte[]> zipFiles;
    private static XmlParser XML_PARSER = Try.Throw((Try.SmartSupplier<XmlParser>) XmlParser::new);

    public XlsxReader(File file) throws IOException {
        ZipFile zip = new ZipFile(file);
        zipFiles = zip.stream().collect(Collectors.toMap(ZipEntry::getName, it -> Try.Throw(() -> zip.getInputStream(it).readAllBytes())));

    private Node getXmlFile(String name) {
        return Try.Throw(() -> XML_PARSER.parse(new ByteArrayInputStream(zipFiles.get(name))));

    private static Tuple2<Integer, Integer> cellName2coordinates(String cellName) {
        int row = Integer.parseInt(cellName.replaceAll("[A-Z]+", ""));
        final int[] col = {0};
        new StringBuffer(cellName.replaceAll("\\d+", "")).reverse().toString().chars()
                .forEach(c -> col[0] = col[0] * 26 + c - 'A' + 1);
        return new Tuple2<>(row - 1, col[0] - 1);

    public Map<String, List<List<Object>>> getData() {
        Map<String, List<List<Object>>> result = new HashMap<>();
        Node workbook = getXmlFile("xl/workbook.xml");
        Node relations = getXmlFile("xl/_rels/workbook.xml.rels");
        Function<String, QName> q = it -> new QName("http://schemas.openxmlformats.org/spreadsheetml/2006/main", it);
        Function<String, QName> r = it -> new QName("http://schemas.openxmlformats.org/officeDocument/2006/relationships", it);
        Function<String, QName> rels = it -> new QName("http://schemas.openxmlformats.org/package/2006/relationships", it);
        Function<String, QName> s = it -> new QName("http://schemas.openxmlformats.org/spreadsheetml/2006/main", it);
        workbook.getAt(q.apply("sheets")).getAt(q.apply("sheet")).stream().forEach(workbookEntry -> {
            String sheetName = String.valueOf(((Node) workbookEntry).attribute("name"));
            result.put(sheetName, new ArrayList<>());
            String sheetId = String.valueOf(((Node) workbookEntry).attribute(r.apply("id")));
            String sheetPath = String.valueOf(relations.getAt(rels.apply("Relationship")).stream()
                    .filter(it -> ((Node) it).attribute("Id").equals(sheetId))
                    .map(it -> ((Node) it).attribute("Target"))
            Node sheet = getXmlFile("xl/" + sheetPath);
            sheet.getAt(s.apply("sheetData")).getAt(s.apply("row")).forEach(row -> {
                ((Node) row).getAt(s.apply("c")).forEach(cell -> {
                    Node v = (Node) ((Node) cell).getAt(s.apply("v")).get(0);
                    String cellName = (String) ((Node) cell).attribute(("r"));
                    Tuple2<Integer, Integer> coordinates = cellName2coordinates(cellName);
                    while (result.get(sheetName).size() <= coordinates.getFirst())
                        result.get(sheetName).add(new ArrayList<>());
                    while (result.get(sheetName).get(coordinates.getFirst()).size() <= coordinates.getSecond())
                    result.get(sheetName).get(coordinates.getFirst()).set(coordinates.getSecond(), v.text());
        return result;

    public static void main(String[] args) throws IOException {
        XlsxReader xlsx = new XlsxReader(new File("c:\\Users\\dsorescu.DBDC\\Desktop\\Book1.xlsx"));
        System.out.println(new String(xlsx.zipFiles.get("xl/workbook.xml")));
Sample code that prompts when new server certificates found, and if confirmed, they are saved on disk for further usage.
1 files attached: SSLTest.java
package main;

import sun.misc.BASE64Encoder;
import sun.misc.IOUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.callback.ConfirmationCallback;
import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.stream.Stream;

public class SSLTest{
    interface FlexSupplier<T>{
        T get() throws Throwable;

    private static <T> T Try(FlexSupplier<T> function){
            return function.get();
        }catch(Throwable throwable){
            throw new RuntimeException(throwable);

    private static X509Certificate[] getSavedCertificates(){
        CertificateFactory x509=Try(()->CertificateFactory.getInstance("X.509"));
        return Stream.of(new File("c:\\workingFolder").listFiles())
                       .map(it->Try(()->new FileInputStream(it)))

    private static void saveCertificate(X509Certificate certificate){
        Try(()->Files.write(new File("c:\\workingFolder\\"+certificate.getSerialNumber()+".cer").toPath(),certificate.getEncoded()));

    private static boolean matches(X509Certificate savedCertificate,X509Certificate newCertificate){
            return true;
            return true;
        }catch(Throwable t){
            return false;

    private static void validateCertificate(X509Certificate it){
        System.out.println("Checking certificate: "+it.getSubjectDN());
        for(X509Certificate saved : getSavedCertificates())
                System.out.println("Matched by: "+saved.getSubjectDN()+" by "+saved.getIssuerDN());
        System.out.println("Not matched!!!");
        else throw new RuntimeException("Certificate rejected");

    private static boolean promptFor(Certificate it){
        X509Certificate x=(X509Certificate)it;
        String message=x.getNotBefore()+"-"+x.getNotAfter()+"\r\n";
        message+=x.getIssuerDN()+" by "+x.getIssuerX500Principal()+"\r\n";
        message+=new BASE64Encoder().encode(x.getSignature());
        return JOptionPane.showConfirmDialog(null,message)==ConfirmationCallback.YES;

    public static void main(String[] args) throws IOException{
        URL url;
        url=new URL("https://host/domain");
        HttpsURLConnection con=(HttpsURLConnection)url.openConnection();
        System.out.println(new String(IOUtils.readFully(con.getInputStream(),-1,true)));

    public static void trustSavedCertificates(){
        TrustManager[] trustAllCerts=new TrustManager[]{
                new X509TrustManager(){
                    public X509Certificate[] getAcceptedIssuers(){
                        return null;

                    public void checkClientTrusted(X509Certificate[] certs,String authType){

                    public void checkServerTrusted(X509Certificate[] certs,String authType){
                        for(X509Certificate cert : certs)
            SSLContext sslContext=SSLContext.getInstance("SSL");
            sslContext.init(null,trustAllCerts,new SecureRandom());
        }catch(Exception e){

How to retrieve server certificates, save them, and use their public keys to validate new connections
How to retrieve server certificates, save them, and use their public keys to validate new connections
3 files attached: SSLTest.java findCertificates.java validateUsingCertificates.java
SSLTest.java findCertificates.java
URL url = new URL("https://server/");
List<String> certificateStrings = getAllCertificateStrings(url);
// save the relevant certificates on your disk
URL url = new URL("https://server/");
List<String> certificateStrings = getAllCertificateStrings(url);// or load them from disk
List<PublicKey> publicKeys = certificateStrings.stream().map(it -> Try(() -> base64certificate2publicKey(it))).collect(Collectors.toList());
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
System.out.println(new String(IOUtils.readFully(con.getInputStream(), -1, true)));
Basic NTLM for HTTP server-side without third message validation on issuing server
1 files attached: NTLM.java
package dms.net.http;

import java.io.IOException;
import java.util.Random;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class NTLM {
	private static final NTLM NTLM_0 = new NTLM(0, new byte[0]);
	private byte[] data;
	public final int version;
	public final String challenge;
	public String domain;
	public String workstation;
	public String userName;
	public String host="";
	public String ip="";

	public static NTLM getNTLM(String auth) {
		byte[] data;
		NTLM result = NTLM_0;
		if (auth == null)
			return result;
		try {
			data = new BASE64Decoder().decodeBuffer(auth.substring(5));
		} catch (IOException e) {
			return result;
		int version = data[8] + data[9] * 256;
		if (version == 0)
			return result;
		return new NTLM(version, data);

	private NTLM(int version, byte[] data$) {
		this.version = version;
		this.data = data$;
		if (this.version == 0) {
			challenge = "NTLM";
		} else if (this.version == 1) {
			challenge = "NTLM "
					+ new BASE64Encoder().encodeBuffer(
							new byte[] { 'N', 'T', 'L', 'M', 'S', 'S', 'P', 0,
									2, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 1,
									(byte) 0x82, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8,
									0, 0, 0, (byte) new Random().nextInt(100), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
									0, 0, 'N', 'T', 'N', 'E', 'T' }).trim();
			if (!readAsciiString(0, 8).equals("NTLMSSP\0"))
			if (readInt(8) != 1)
			this.domain = readSecurityBuffer(16);
			this.workstation = readSecurityBuffer(24);
		} else if (this.version == 3) {
			challenge = null;
			if (!readAsciiString(0, 8).equals("NTLMSSP\0"))
			if (readInt(8) != 3)
			this.domain = readSecurityBuffer(28);
			this.workstation = readSecurityBuffer(44);
			this.userName = readSecurityBuffer(36);
		} else {
			challenge = null;

	private String readAsciiString(int pos, int len) {
		char[] result = new char[len];
		for (int i = 0; i < len; i++)
			result[i] = (char) this.data[pos + i];
		return new String(result);

	private int readInt(int pos) {
		int result = 0;
		for (int i = 0; i < 4; i++)
			result = this.data[pos++] << 24 | (0x00ffffff & (result >> 8));
		return result;

	private short readShort(int pos) {
		short result = 0;
		for (int i = 0; i < 2; i++)
			result = (short) (this.data[pos++] << 8 | (result >> 8));
		return result;

	private String readSecurityBuffer(int pos) {
		String result = "";
		int length = readShort(pos);
		readShort(pos + 2);
		int offset = readInt(pos + 4);
		try {
			String temp = readAsciiString(offset, length);
			for (int i = 0; i < temp.length(); i++)
				if (temp.charAt(i) != 0)
					result += temp.charAt(i);
		} catch (ArrayIndexOutOfBoundsException e) {
			throw e;
		return result;
Easy wrapper for querying the LDAP from Java
Easy wrapper for querying the LDAP from Java using only JDK.
2 files attached: LdapConnector.java SampleUsage.groovy
LdapConnector.java SampleUsage.groovy
List<Map<String, List<?>>> getAllLdapUserGroups() { connector["(&(cn=GROUP_*)(objectclass=groupOfUniqueNames))"] }

 public LdapRecord getAt(User user) {
        List<LdapRecord> result = connector['uid=' + user.uid];
        if (result.size() == 0) return null;
        if (result.size() == 1) return result.first()
        throw new IllegalArgumentException("Too many results found for $user")

 public static void main(String[] args) {
        println ApiTest.$$.ldap.allUserGroups
Scriptless Angular toggle snippet
Not really scriptless - Angular runs the script.
No need to define variable in scope.
1 files attached: angularScriptlessToggle.html
<table class='table table-bordered table-hover table-condensed table-compressed table-striped' style='width:auto; float:right'>
				<caption ng-click='toggleSummaryTable = !toggleSummaryTable'>Summary aggregate</caption>
				<thead ng-show='toggleSummaryTable'>
						<th ng-repeat='header in logData.summary.headers'>{{header}}</th>
				<tbody ng-show='toggleSummaryTable'>
					<tr ng-repeat='record in logData.summary.data'>
						<td ng-repeat='header in logData.summary.headers'>{{record[header]}}</td>
regular expression custom jQuery selector
1 files attached: jQuery.matches.js
var REGEXP_CACHE = {};

jQuery.expr[":"].matches = function (obj, index, meta, stack) {
    var expression = meta[3];
    var regexp = REGEXP_CACHE[expression] = REGEXP_CACHE[expression] || new RegExp("^" + expression + "$", "gim");
    var jElem = jQuery(obj);
    return (regexp.test((String(jElem.text())).trim()))
        || (regexp.test((String(jElem.val())).trim()))
        || (regexp.test((String(jElem.attr("placeholder"))).trim()))
sQuery - DOM proximity relevance
sQuery - easier way to identify HTML objects by jQuery CSS selectors. Identification based on DOM proximity relevance.
1 files attached: sQuery.js
building an animation in R based on images from a folder
1 files attached: animationDraft.r
cameras <- c('Poarta','Curte')
for(camera in cameras){
  cameraDays <- list.files(cameraFolder)
  for(cameraDay in cameraDays){
    magick::image_write(animation,paste("c:\\users\\dragosmateis\\desktop\\ccc",camera,cameraDay,sep="_"),format = )
How to hide Spock stack traces when running tests written in Groovy.
2 files attached: IgnoreStackraceElements.groovy MyException.java
static {
        StackTraceUtils.addClassTest({ String className ->
            if (className.startsWith("org.spockframework.")) return false;
            return null;
import org.codehaus.groovy.runtime.StackTraceUtils;
public class MyException extends RuntimeException {
    public MyException(String message, Object... suppressed) {
        for (Object t : suppressed)
            if (t instanceof Throwable) this.addSuppressed(StackTraceUtils.deepSanitize((Throwable) t));
Scala JSON Comparator
4 files attached: JsonComparator.scala left.json right.json output.txt
import scala.io.Source
import scala.util.parsing.json._

object JsonComparator {
  def compare(left: Any, right: Any, path: java.lang.String = ""): List[String] = (left, right) match {
    case (l: Number, r: Number) => if (l == r) Nil else s"$path: $l != $r" :: Nil
    case (l: String, r: String) => if (l == r) Nil else s"$path: $l != $r" :: Nil
    case (l: Set[_], r: Set[_]) => if (l == r) Nil else s"$path: $l != $r" :: Nil
    case (l: List[_], r: List[_]) =>
      if (l == r) Nil
      else if (l.length != r.length) s"$path.length: ${l.length} vs. ${r.length}" :: Nil
      else l.indices.toList.filter(it => l(it) != r(it)).flatMap(it => compare(l(it), r(it), s"$path[$it]"))
    case (l: Map[String, _], r: Map[String, _]) =>
      if (l == r) Nil
      else if (l.size != r.size) s"$path.count: ${l.size} != ${r.size}" :: Nil
      else if (l.keySet != r.keySet) s"$path.keys: ${l.keySet} != ${r.keySet}" :: Nil
      else l.keySet.toList.filter(it => l(it) != r(it)).flatMap(it => compare(l(it), r(it), s"$path/$it"))
    case _ =>
      s"$path: $left[${if (left == null) left else left.getClass}] vs. $right[${if (right == null) right else right.getClass}]" :: Nil

  def main(args: Array[java.lang.String]): Unit = {
    val left = JSON.parseFull(Source.fromResource("left.json").mkString)
    val right = JSON.parseFull(Source.fromResource("right.json").mkString)
    compare(left.get, right.get).foreach(println)
    compare(left.get, left.get).foreach(println)
{"node1": [1, 2, ["q","w"], "e"], "node2": {"node3": "value4","null": null}, "node3": 3, "node4": 4, "node5": 5.5}
{"node1": [1, "3", ["q", "w", 0], "e"], "node2": {"node3": "value4", "null": "null"}, "node3": "3", "node4": 4, "node5": 5.6}
/node1[1]: 2.0[class java.lang.Double] vs. 3[class java.lang.String]
/node1[2].length: 2 vs. 3
/node3: 3.0[class java.lang.Double] vs. 3[class java.lang.String]
/node2/null: null[null] vs. null[class java.lang.String]
/node5: 5.5 != 5.6
More compact of generic node filtering in browser
"abc" - shows only those containing "abc".
"abc def" - shows only those containing both, "abc", and "def".
"abc !def" - shows those containing "abc" and do not contain "def".
"ab|cd !ef|gh" - shows those that contain "ab" or "cd" and don't contain "ef", either "gh".
1 files attached: filterNodes.js
function filterNodes(jQuerySet,value){
	let strContainsAnyOf=(haystack,needle)=>!needle.every(it=>haystack.indexOf(it)<0)
	var count=0;
	var values=value.split(" ").map(it=>unescape(it)).filter(it=>it!='').filter(it=>it!='!');
	let expectations={}
	for(let value of values)
	for(let node of jQuerySet.toArray()){
		var nodeValue=(''+node.innerHTML).toUpperCase().replace(/<[^>]+>/g, '');
		var visible=true;
		for(let value in expectations)
	return count;
Browser singletons - how to ensure a script is loaded only once
Browser singletons - how to ensure a script is loaded only once
1 files attached: require_once.js
window[Symbol.for('d1702070851-LESS loaded')]||addResource("//cdnjs.cloudflare.com/ajax/libs/less.js/2.5.1/less.min.js","js");
	window[Symbol.for('d1702070851-LESS loaded')]=true;
How to simply add less scripts to the web pages (without server-side compilation)
2 files attached: headerManipulation.js sample.js
function createNode(nodeName,attributes){
	var node=document.createElement(nodeName);
	for(var k in attributes)
function addResource(path,extension){
	if(extension=='css')return createNode('link',{rel:'stylesheet',type:'text/css',href:path});
	if(extension=='js')return createNode('script',{src:path});
	if(extension=='less')return createNode('link',{rel:'stylesheet',type:'text/less',href:path});
	throw "Extension not supported: "+extension;
Simple function to select an HTML node on clicking (works on Chrome)
Simple function to select an HTML node on clicking (works on Chrome)
1 files attached: selectText.js
function selectText(element) {
    var selection = window.getSelection();
    var range = document.createRange();
Self-generated certificate for Java HTTPS socket
Step 1:
Run the key_generator.cmd by putting the machine name for the first/last name.
2 files attached: key_generator.cmd HttpsConfigurator.java
set path=%path%;"c:\Program Files\Java\<jdk>\bin"
keytool -genkey -keyalg RSA -alias <host> -keystore <host>.jks -storepass <host> -validity 360 -keysize 2048
keytool -v -export -file <host>.cer -keystore <host>.jks -alias <host>
InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), port);
com.sun.net.httpserver.HttpsServer httpsServer = com.sun.net.httpserver.HttpsServer.create(address, 0);
SSLContext sslContext = SSLContext.getInstance("TLS");
char[] password = "<host>".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
// keytool -genkey -keyalg RSA -alias HOSTNAME -keystore HOSTNAME.jks -storepass HOSTNAME -validity 360 -keysize 2048
// keytool -v -export -file HOSTNAME.cer -keystore HOSTNAME.jks -alias HOSTNAME
FileInputStream fis = new FileInputStream("c:\\<path>\\<host>.jks");
ks.load(fis, password);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, "<host>".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
	public void configure(HttpsParameters params) {
		try {
			SSLContext c = SSLContext.getDefault();
			SSLEngine engine = c.createSSLEngine();
			SSLParameters defaultSSLParameters = c.getDefaultSSLParameters();
		} catch (Exception ex) {
HttpHandler handler = new HttpHandler(""+port);
httpsServer.createContext("/", handler);
ExecutorService executor = Executors.newFixedThreadPool(50);
JUnit runner multiple levels test organization
Draft of a JUnit test executor that allows grouping tests on arbitrary deep tree.
3 files attached: SorescuParametrized.java TestData.java TestClass.java
package eu.sorescu.junit;

import org.junit.runner.Runner;
import org.junit.runners.Parameterized;
import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParametersFactory;
import org.junit.runners.parameterized.ParametersRunnerFactory;
import org.junit.runners.parameterized.TestWithParameters;

import java.util.*;
import java.util.stream.Collectors;

import org.junit.runners.model.FrameworkMethod;

public class SorescuParameterized extends Parameterized {

    public SorescuParameterized(Class<?> klass) throws Throwable {
        this(klass, 0, null, klass.getSimpleName());

    public String getName() {
        return this.name;

    private final String name;

    public SorescuParameterized(Class<?> klass, final int depth, List<TestData> subset, String name) throws Throwable {
        this.name = System.identityHashCode(this) + "." + name + "a.b.c.d" + "." + name;
        if (subset == null) subset = (List<TestData>) this.getParametersMethod().invokeExplosively(null);
        if (depth >= 3) {
            runners = Collections.unmodifiableList(createRunnersForParameters(subset));
        } else {
            runners = new ArrayList<>();
            HashMap<Object, List<TestData>> hashParameters = new HashMap<>();
            for (TestData vector : subset) {
                String key = String.valueOf(vector.segments.get(depth));
                if (!hashParameters.containsKey(key))
                    hashParameters.put(key, new ArrayList<>());
            try {
                for (Object key : hashParameters.keySet())
                    runners.add(new SorescuParameterized(klass, depth + 1, hashParameters.get(key), String.valueOf(key)));
            } catch (Throwable throwable) {
                throw new RuntimeException(throwable);

    private static final ParametersRunnerFactory DEFAULT_FACTORY = new BlockJUnit4ClassRunnerWithParametersFactory();
    private final List<Runner> runners;

    protected List<Runner> getChildren() {
        return this.runners;

    private FrameworkMethod getParametersMethod() throws Exception {
        List<FrameworkMethod> methods = this.getTestClass().getAnnotatedMethods(Parameterized.Parameters.class);
        Optional<FrameworkMethod> method = methods.stream().filter(it -> it.isStatic() && it.isPublic()).findAny();
        return method.orElseThrow(() -> new Exception("No public static parameters method on class " + this.getTestClass().getName()));

    private List<Runner> createRunnersForParameters(List<TestData> allParameters) throws Exception {
        ArrayList<Runner> runners = new ArrayList<>();
        for (Object test : this.createTestsForParameters(allParameters))
            runners.add(DEFAULT_FACTORY.createRunnerForTestWithParameters((TestWithParameters) test));
        return runners;

    private List<TestWithParameters> createTestsForParameters(List<TestData> allParameters) throws Exception {
        int i = 0;
        ArrayList<TestWithParameters> children = new ArrayList<>();
        for (TestData parametersOfSingleTest : allParameters) {
            children.add(_createTestWithParameters(this.getTestClass(), ++i, parametersOfSingleTest));
        return children;

    private TestWithParameters _createTestWithParameters(org.junit.runners.model.TestClass testClass, int index, TestData parameters) {
        String name = "" + index + "." + parameters.segments.stream().map(String::valueOf).collect(Collectors.joining());
        return new TestWithParameters("[" + name + "]", testClass, Collections.singletonList(parameters));
package eu.sorescu.junit;

import java.util.ArrayList;
import java.util.List;

public class TestData {
    public TestData(Object[] segments) {
        this.segments = new ArrayList();
        for (Object s : segments)

    public List<Object> getSegments() {
        return segments;
package eu.sorescu.junit

import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized

@TypeChecked @CompileStatic
public class TestClass {
    private  TestData td;
    public TestClass(TestData td){
    @Parameterized.Parameters(name='{index} {0} {1}')
    public static List<Object[]> data() {
        def a=[]
        for(def i=0;i<9;i++) {
            a.add(new TestData(i, i + 1, i + 2,i+4))
            a.add(new TestData(i, i + 1, i + 3,i+4))
            a.add(new TestData(i, i + 2, i + 4,i+4))
        return a

    public void f1() {
        if(td.segments.get(1).equals(2))throw new RuntimeException("EEE"+td.segments.get(1));
        println "testRun f1 "+td.segments
    public void f2() {
        println "testRun f2 "+td.segments
Basic POM for fast Groovy/Java compilation in IDEA
The speed is accomplished by using the Eclipse Groovy compiler for Java code (in one single process, without waiting for Groovy stub generation).
1 files attached: pom.xml
Groovy XLSX reader
1 files attached: XlsxReader.groovy
package eu.sorescu

import groovy.transform.Memoized
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.util.zip.ZipFile;

class XlsxReader {
    ZipFile zf;

    public XlsxReader(File file) { this.zf = new ZipFile(file); }

    public Node getXml(String path) throws IOException, ParserConfigurationException, SAXException {
        new XmlParser(false, false).parse(zf.getInputStream(zf.getEntry(path)))

    public String[] getSharedStrings() {
        return this.getXml("xl/sharedStrings.xml").si*.t*.text()

    public ArrayList<String> getSheetNames() throws IOException {
        return this.getXml("xl/workbook.xml").sheets.sheet*.'@name'

    public static int[] l2c(String l) {
        String letters = l.replaceAll(/\d+/, '')
        int row = (l.replaceAll(/[^\d]+/, '') as int) - 1
        if (letters.length() == 1) return [row, letters.codePointAt(0) - 65];
        if (letters.length() == 2) return [row, (letters.codePointAt(1) - 64) * 26 + (letters.codePointAt(0) - 65)]
        throw new RuntimeException("Not supported: " + letters)

    public List<List<String>> getSheet(String sheetName) {
        def rid = this.getXml("xl/workbook.xml").sheets.sheet.find { it.'@name' == sheetName }.'@r:id'
        String sheetPath = this.getXml("xl/_rels/workbook.xml.rels").Relationship.find { it.'@Id' == rid }.'@Target'
        List<List<String>> result = new ArrayList<>();
        def res = this.getXml('xl/' + sheetPath)
        res.sheetData.row.each { row ->
            row.c.each { c ->
                if (c.v) {
                    int[] coordinates = l2c(c.'@r' as String)
                    String value = c.v.text()
                    if (c.'@t' == 's') value = sharedStrings[value as int]
                    try {
                        if (!result[coordinates[0]]) result[coordinates[0]] = []
                        result[coordinates[0]][coordinates[1]] = String.valueOf(value).intern()
                    } catch (Throwable ignored) {
                        println sheetName + " " + sheetPath + " " + coord + " " + value
        for (int i = 0; i < result.size(); i++)
            result[i] = result[i] ?: []
        return result
Groovy binary coverage algorithm for a list
2 files attached: binaryCoverage.groovy test.groovy
def binaryCoverage={list->
	int listLength=list.size()
	int bitSize=32-Integer.numberOfLeadingZeros(listLength)
	return (0..<bitSize).collect{bit->(0..<listLength).findAll{!(it&(1<<bit))}.collect{list[it]}}
def list=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
assert binaryCoverage(list)==[[0, 2, 4, 6, 8, 10, 12, 14], [0, 1, 4, 5, 8, 9, 12, 13], [0, 1, 2, 3, 8, 9, 10, 11], [0, 1, 2, 3, 4, 5, 6, 7]]
Simple python HTTP server
Simple HTTP server in Pyhton that on a side serves static pages, on another side it serves interpreted Python code (.pyp files).
Before executing each page, it also executes __before__.py (that in my case takes care of authentication handling and routing - attached).
2 files attached: http.py __before__.py
import BaseHTTPServer
import SimpleHTTPServer
import cgi
import os
import Cookie
import re

open("http.lock", "w")

def executeTemplate(templatePath,context):
		for pair in template.split('?>'):
	exec(''.join(code))in context,locals
class CustomHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
	def do_GET(self):
		print("http {0} {1}".format(self.path,os.path.exists("."+self.path)))
			return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
			context['println']=lambda x: self.wfile.write(x)
			if "Cookie" in self.headers:
			exec(open('http/__before__.py', 'r').read())in context
			if context['cookie']:
			for key,value in context['response']['headers'].iteritems():
			except Exception as inst:
				self.wfile.write("</pre></script></textarea></script><pre style='color:red'>"+cgi.escape(inst.__repr__(),True)+"</pre><a href='/'>Back home</a>")

httpd=server(("", 3187), handler)
How to convert a folder of ordered JPEG files in a simple AVI MPeg video
1 files attached: convertFolderOfJpegsToMpegAviFile.python
import cv2,os,os.path
def archiveFolder(folderPath):
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')#XVID
    if os.path.exists(folderPath+".avi"): os.remove(folderPath+'.avi')
    out = cv2.VideoWriter(folderPath+'.avi',fourcc,20,(320,200))
    for fileName in os.listdir(folderPath):
        if fileName.endswith(".txt"):continue
        if fileName.endswith(".db"):continue
        if not fileName.endswith('.jpg'):raise Exception(fileName)
        img= cv2.resize(img, (320, 200))
        font = cv2.FONT_HERSHEY_PLAIN
        cv2.putText(img,fileName,(0,20), font, 1,(0,128,255),1)
        print fileName
    print "Releasing..."
JOptionPane for multiple selected value that scroll in dialogue box (using JTable)
1 files attached: JOptionPaneSmartReplacement.groovy
import groovy.transform.TypeChecked

import javax.swing.JButton
import javax.swing.JDialog
import javax.swing.JFrame
import javax.swing.JScrollPane
import javax.swing.JTable
import javax.swing.JTextField
import javax.swing.RowFilter
import javax.swing.event.ListSelectionListener
import javax.swing.table.AbstractTableModel
import javax.swing.table.TableModel
import javax.swing.table.TableRowSorter
import java.awt.BorderLayout
import java.awt.Dialog
import java.awt.Dimension
import java.awt.event.ActionListener
import java.awt.event.KeyListener

public class Q1 {
    public static void main(String[] args) {
        println showDialog("title", (1..100).collect { "qwe" + it }).join("; ")

    public static List<String> showDialog(String title, List<String> options) {
        def selection = []
        def dialog = new JDialog(null, title, Dialog.ModalityType.TOOLKIT_MODAL);
        dialog.defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE
        dialog.layout = new BorderLayout()
        def text = new JTextField()
        def button = new JButton("Select");
        TableModel dataModel = [getColumnCount: { -> 1 }, getRowCount: { -> options.size()
        }, getValueAt                         : { int row, int col -> options[row] }] as AbstractTableModel
        def table = new JTable(dataModel);

        dialog.add(text, BorderLayout.PAGE_START)
        dialog.add(button, BorderLayout.PAGE_END)
        def scroll = new JScrollPane(table)
        dialog.add(scroll, BorderLayout.CENTER)

        button.addActionListener([actionPerformed: { dialog.dispose() }] as ActionListener)

        def sorter = new TableRowSorter(dataModel);
        table.selectionModel.addListSelectionListener([valueChanged: {
            selection = (0..options.size() - 1).collect {
                table.selectionModel.isSelectedIndex(it) ? options[it] : null
            }.findAll { it != null }
            button.text = selection.size() + " selected. " + selection.join(", ")
        }] as ListSelectionListener)
        text.addKeyListener([keyPressed: {}, keyTyped: {}, keyReleased: {
            sorter.setRowFilter(RowFilter.regexFilter(text.getText(), 0));
        }] as KeyListener)
        dialog.size = dialog.preferredSize = new Dimension(200, 640)
        dialog.locationRelativeTo = null
        dialog.visible = true
        return selection
Groovy tuple orthogonal coverage filter
Groovy filtering of tuples to ensure orthogonal coverage (by one field) ordered by relevance descending.
2 files attached: orthoCover.groovy sample.groovy
orthoCover.groovy sample.groovy
assert orthoCover([[a:1,b:2],[a:2,b:3,c:4],[a:4,b:5],[a:2,b:2]])==[[a:2, b:3, c:4], [a:4, b:5],[a:1, b:2]]
Groovy simple cartesian product
1 files attached: cartesian.groovy
public List cartesian(Collection... collections) {
        collections = collections.collect { collection -> collection.collect { [it] } }
        def result = collections.first()
        collections.drop(1).each { collection ->
            result = result.collect { left -> collection.collect { right -> left + right } }.sum()
        return result
My too-simple-to-be-true PBKDF2 one-way encryption and password checking
Configurables: the iteration count, salt size, and hash size lengths are hard-coded....
1 files attached: PBKDF2.cs
public static string Hash(string password)
            using (var deriveBytes = new Rfc2898DeriveBytes(password, 16, 1000))
                return Convert.ToBase64String(new byte[1].Concat(deriveBytes.Salt).Concat(deriveBytes.GetBytes(32)).ToArray());

        public static bool CheckHash(string hashBase64, string password)
            var hash = Convert.FromBase64String(hashBase64);
            using (var deriveBytes = new Rfc2898DeriveBytes(password, hash.Skip(1).Take(16).ToArray(), 1000))
                return hash.Skip(1).Skip(16).Take(32).SequenceEqual(deriveBytes.GetBytes(32));
Simple ZIP Archiver
My too-simple-to-be-true file archiver (basic options).
It just takes a list of files and returns the zip file contents as byte array (no optimization, and all is performed in memory).
1 files attached: Zip.groovy
def packFiles={List sources->
	def baos=new ByteArrayOutputStream()
	def zipOut = new java.util.zip.ZipOutputStream(baos)
	for (def source : sources) {
		zipOut.putNextEntry(new java.util.zip.ZipEntry(source.name))
	return baos.toByteArray()
Zip dearchiver for JVM
My simple Zip dearchiver. It was written in Groovy, but intuitevely convertible to Java 8 with Lambdas.
Reason I wrote it: Windows Firewall refused dearchiving some sensitive files.
1 files attached: T.groovy
import groovy.transform.TypeChecked;
import sun.misc.IOUtils;

import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

class T {
    public static void main(String[] args) {
        def folder="C:\\Users\\dsorescu\\Documents\\My Received Files";
        ZipFile zip=new ZipFile(folder+"\\"+"MY_SECRET_ZIP_FILE_NAME.zip");
        zip.entries().each {ZipEntry entry->
            File f=new File(folder+"\\"+entry.name);
                FileOutputStream fos=new FileOutputStream(f);
Simple file-on-disk JSON db
1 files attached: Heap.java
package eu.sorescu.db;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

import groovy.json.JsonOutput;
import groovy.json.internal.JsonParserCharArray;

public class Heap {
    private static final long serialVersionUID = -5685880176240431312L;
    final File folder;
    private String joinedPath = "";

    public Heap(String... path) throws IOException {
        if (path.length == 1)
            if (path[0].length() == 0)
                path = new String[0];
        for (String aPath : path) this.joinedPath += "\\" + URLEncoder.encode(aPath, "UTF-8");
        folder = new File("heap" + this.joinedPath + "\\");

    private File file(String arg0) {
        try {
            String encodedName = encode(arg0);
            return new File(folder, encodedName);
        } catch (IOException e) {
            throw new IllegalAccessError("heap://" + joinedPath + "/" + arg0);

    public Object[] list() {
        File[] files = folder.listFiles();
        ArrayList<String> result = new ArrayList<>();
        try {
            if (files != null)
                for (File file : files)
                    if (file.isFile())
        } catch (IOException e) {
            throw new NullPointerException(e.toString());
        Object[] vector = result.toArray(new String[result.size()]);
        return vector;

    public String[] listHeaps() throws IOException {
        File[] files = folder.listFiles();
        ArrayList<String> result = new ArrayList<>();
        if (files != null)
            for (File file : files)
                if (file.isDirectory())
        return result.toArray(new String[result.size()]);

    // @Override
    public Object get(final Object arg0) {
        if (arg0 == null)
            throw new NullPointerException("d1012150913 Heap " + folder
                    + ": argument null");
        if (!(arg0 instanceof String))
            throw new NullPointerException("d1012150914 Heap " + folder + ": "
                    + arg0.getClass().getName() + " only String");
        return get((String) arg0);

    public Object get(final String arg0, Object defaultValue) {
        Object result = get(arg0);
        if (result == null)
            result = defaultValue;
        return result;

    private Object get(final String arg0) {
        try {
            File f = file(arg0);
            byte[] data = Files.readAllBytes(f.toPath());
            return new JsonParserCharArray().parse(data);
        } catch (Throwable ignored) {
        return null;

    public long getSize(String arg0) {
        try {
            return file(arg0).length();
        } catch (Throwable t) {
            return 0;

    public boolean has(String arg0) {
        if (arg0 == null)
            return false;
        File file = file(arg0);
        return file != null && file(arg0).exists();

    public String put(Object value) {
        return put(null, value);

    private static SimpleDateFormat TIME_STAMP = new SimpleDateFormat(

    public String put(String key, Object value) {
        if ((key == null) || (key.length() == 0))
            key = UUID.randomUUID().toString() + "_"
                    + TIME_STAMP.format(new Date());
        write(file(key), value);
        return key;

    public void delete(String arg0) {

    private static void write(File file, Object value)
        String ser = JsonOutput.prettyPrint(JsonOutput.toJson(value));
        try {
            Files.write(file.toPath(), ser.getBytes(), StandardOpenOption.CREATE);
        } catch (Throwable t) {
            throw new RuntimeException(t);

    private static String encode(String k) throws UnsupportedEncodingException {
        return URLEncoder.encode(k, "UTF-8");

    private static String decode(String k) throws UnsupportedEncodingException {
        return URLDecoder.decode(k, "UTF-8");
How I am looking for classes that extend a base class
1 files attached: Classes.java
public static Class[] classes(Class scope) throws IOException, URISyntaxException {
        Path root = new File(JUnitExecutor.class.getResource("/").toURI()).toPath();
        return Files.walk(root, FileVisitOption.FOLLOW_LINKS).map(path -> root.relativize(path))
                .filter(path -> path.toString().endsWith(".class"))
                .map(path -> path.toString())
                .map(path -> path.toString().substring(0, path.length() - 6).replace('\\', '.'))
                .map(path -> getClass(path))
                .filter(clazz -> scope.isAssignableFrom(clazz))
                .filter(clazz -> clazz != scope)
                .toArray(c -> new Class[c]);

    private static Class getClass(String className) {
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new ClassFormatError(className);
Simple stream copy function
Simple function to copy a stream to another.
1 files attached: CopyStream.java
public static void copyStream(InputStream is, OutputStream os) throws IOException {
        try (
                ReadableByteChannel input = Channels.newChannel(is);
                WritableByteChannel output = Channels.newChannel(os)
        ) {
            final ByteBuffer buffer = ByteBuffer.allocateDirect(65536);
            while (input.read(buffer) != -1) {
            while (buffer.hasRemaining())
My SSH URL Handler for Java
How I implemented my own SSH protocol handler in Java, to write code like in attached sample.
3 files attached: Sample.java Handler.java SSHURLConnection.java
new java.net.URL("ssh://user:password@host/?ls ~/desktop/").openConnection().getInputStream();
Handler.java SSHURLConnection.java
How much do you know about .NET?
1 files attached: Program.cs
namespace ConsoleApplication3
    class Program
        static void Main(string[] args)
            float nan = float.NaN;
            Console.WriteLine(Object.Equals(nan, nan));//true
            Console.WriteLine(Object.ReferenceEquals(nan, nan));//false
            Console.WriteLine(nan == nan);//false
            Object nano = float.NaN;
            Console.WriteLine(Object.Equals(nano, nano));//true
            Console.WriteLine(Object.ReferenceEquals(nano, nano));//true
            Console.WriteLine(nano == nano);//true
Ranorex C# automation for MFC Windows GUI
The following code supposes you have Ranorex linked to your C# solution.
3 files attached: Main.script Repository.properties Program.cs
rem call main
type @login.password schilling
click @login.ok
click title=Schilling;text=Firmavalg
click title=Schilling;innertext=SPS.UK$,href=4$
doubleClick title=Schilling;text=Main.menu
doubleClick title=Schilling;text=Publisher
doubleClick title=Schilling;text=Product.management
REM Step 1
click title=Schilling;*=Product.management.project

rem ocr_click Project 3 0.5
type /form[@title~'^Product\smanagement\s-\sedit']/?/?/container[@caption~'^Product\smanagement\s-\sedit']/element/element[6]/text[@class='Edit'] 21321131231

REM Step 3
click *=Product.management;text=Create.project$
REM Step 4
click *=Product.management;*=Create.project;*=Other.projects..F7.
click *=Product.management;text=Get.serial.number
click *=Product.management;text=Accept$
rem ocr_click @Name: 0.5 0.5
REM 10
rem type *=Product.management;*=Save.project.as CrashCourseCardiology\t\t\t\t\t\t\t\tCrash
type @pm.edit.saveas.new-project-number {ts}
type @pm.edit.saveas.name "Crash Course Cardiology"
type @pm.edit.saveas.title "Crash Course Cardiology"
rem click on title
type @pm.edit.saveas.main-group 07
type @pm.edit.saveas.sub-group 021
type @pm.edit.saveas.dimension-1 002

click @pm.edit.saveas.new-project-number
click @pm.edit.saveas.name
click @pm.edit.saveas.new-project-number
click @pm.edit.saveas.name

click "*=Product.management;text=Create project$"
rem click "/form[@title='Error']/button[@text='OK']"
rem click "*=Product.management;text=Create project$"	
click "/form[@title='Question']/button[@text='&Yes']"

click @pm.edit.details.tab

wait 1000
clickAt @pm.edit.details.stackholders 100 20
clickAt @pm.edit.details.stackholders 10 20
clickAt @pm.edit.details.stackholders 100 20
wait 1000
type "/form[@title~'^Product\ management\ -\ edit']/?/?/container[@caption~'^Product\ management\ -\ edit']/?/?/container[@caption='Details']/?/?/container[@caption='Stakeholders']/?/?/element[@class='OaseGrid']/element/element[4]/text[@class='Edit']" "R"
wait 1000
clickAt @pm.edit.details.stackholders 200 20
wait 200
clickAt @pm.edit.details.stackholders 200 20
type "/form[@title~'^Product\ management\ -\ edit']/?/?/container[@caption~'^Product\ management\ -\ edit']/?/?/container[@caption='Details']/?/?/container[@caption='Stakeholders']/?/?/element[@class='OaseGrid']/element/element[31]/text[@class='Edit']" "Aut"
rem wait 1000
rem clickAt @pm.edit.details.stackholders 300 20
rem clickAt @pm.edit.details.stackholders 10 20
rem clickAt @pm.edit.details.stackholders 300 20
rem type "/form[@title~'^Product\ management\ -\ edit']/?/?/container[@caption~'^Product\ management\ -\ edit']/?/?/container[@caption='Details']/?/?/container[@caption='Stakeholders']/?/?/element[@class='OaseGrid']/element/element[4]/text[@class='Edit']" "Author	"
wait 1000
clickAt @pm.edit.details.stackholders 700 20
wait 200
clickAt @pm.edit.details.stackholders 700 20
type "/form[@title~'^Product\ management\ -\ edit']/?/?/container[@caption~'^Product\ management\ -\ edit']/?/?/container[@caption='Details']/?/?/container[@caption='Stakeholders']/?/?/element[@class='OaseGrid']/element/element[22]/text[@class='Edit']" "p2012-009"
rem Aut	Author	p2012-009	

click @pm.edit.texts.tab

click @pm.edit.calculation.tab

type @pm.edit.calculation.version 3
type @pm.edit.calculation.price 9
click @pm.edit.calculation.version
click @pm.edit.calculation.price
click *=Product.management;text=Accept$
Repository.properties Program.cs
Basic image recognition function in Java
Simple algorithm to find the (first) position of a smaller image in a larger one. Tip: to run faster, you may check for diagonal or few random points inside the small image before comparing all the other pixels.
1 files attached: ImageDetector.java
package eu.sorescu.mmx;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;

public class ImageDetector {
	public static Rectangle getImagePosition(BufferedImage bigImage,
			BufferedImage smallImage) {
		int w1 = bigImage.getWidth();
		int h1 = bigImage.getHeight();
		int w2 = smallImage.getWidth();
		int h2 = smallImage.getHeight();
		int[] bigPixels = bigImage.getRGB(0, 0, w1, h1, null, 0, w1);
		int[] smallPixels = smallImage.getRGB(0, 0, w2, h2, null, 0, w2);
		for (int x1 = 0; x1 <= w1 - w2; x1++)
			imageLoop: for (int y1 = 0; y1 <= h1 - h2; y1++) {
				for (int y2 = 0; y2 < h2; y2++)
					if (!compare(bigPixels, smallPixels, w1 * (y1 + y2) + x1,
							w2 * y2, w2))
						continue imageLoop;
				return new Rectangle(x1, y1, w2, h2);
		return null;

	private static boolean compare(int[] array1, int[] array2, int a1, int a2,
			int length) {
		for (int i = 0; i < length; i++)
			if (array1[a1 + i] != array2[a2 + i])
				return false;
		return true;
My too-simple-to-be-true SMTP web server
My minimal SMTP server in JAVA - I needed it during email functionality tests because:
  • does not require mailbox creation in order to receive an email on any email address;
  • integrated with a minimal HTML page, I can instantly query for the message once it was sent, without waiting for virus scanning, etc.;
  • the server is domain-agnostic (it does not matter on what domain I send the email, as long as it reaches my machine);
  • I have full access to the email source immediately it reached the server, so the automated software can analyse subtle details under the hood of the email representation (alternate representations, email hidden headers, etc.).
All the code is invoked in SMTPServer.
2 files attached: SMTPThread.java SMTPServer.java
SMTPThread.java SMTPServer.java
Parallel JUnit execution runner - just annotate your @Parametrized class with @Parallelized
1 files attached: Parallelized.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.junit.runners.Parameterized;
import org.junit.runners.model.RunnerScheduler;

public class Parallelized extends Parameterized {

	private static class ThreadPoolScheduler implements RunnerScheduler {
		private ExecutorService executor;

		public ThreadPoolScheduler() {
			int numThreads = GenericTestCase.getIntProperty("threads");
			executor = Executors.newFixedThreadPool(numThreads);

		public void finished() {
			try {
				executor.awaitTermination(10, TimeUnit.MINUTES);
			} catch (InterruptedException exc) {
				throw new RuntimeException(exc);

		public void schedule(Runnable childStatement) {

	public Parallelized(Class klass) throws Throwable {
		setScheduler(new ThreadPoolScheduler());
My Java-Groovy joint builder (based on the UberCompile ant task)
(Some of the) Advantages:
  • No Maven or Gradle required;
  • No dependency (except JAVA_HOME and required JARs);
  • Can compile interdependent Java and Groovy code;
(Some of the) Disadvantages:
  • you need to indicate the path to the JARs;
  • Designed to work on Sun VMs;
The eu.sorescu.reflect.JARLoader is written based on Runtime dynamic loading of JARs.
1 files attached: GroovyProjectCompiler.java
How to make Java ignore the certificate errors
1 files attached: SSLUtil.java
package dms.os;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashSet;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public final class SSLUtil {
	private static HashSet<KeyManager> keyManagers = new HashSet<KeyManager>();
	static {
	public static TrustManager[] _trustManagers = new TrustManager[] { new X509TrustManager() {
		private final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

		public void checkClientTrusted(X509Certificate[] chain, String authType) {

		public void checkServerTrusted(X509Certificate[] chain, String authType) {

		public X509Certificate[] getAcceptedIssuers() {
			return (_AcceptedIssuers);
	} };

	public static void addClientCertificate(byte[] data, String password)
			throws KeyManagementException, NoSuchAlgorithmException,
			UnrecoverableKeyException, KeyStoreException, CertificateException,
			FileNotFoundException, IOException {
		SSLContext context = SSLContext.getInstance("TLS");
		for (KeyManager km : getKeyManagers(data, password))
		context.init(keyManagers.toArray(new KeyManager[keyManagers.size()]),
				_trustManagers, new SecureRandom());

	private static KeyManager[] getKeyManagers(byte[] data, String password)
			throws UnrecoverableKeyException, KeyStoreException,
			NoSuchAlgorithmException, CertificateException,
			FileNotFoundException, IOException {
		KeyManagerFactory tmf = null;
		char[] passwKey = password.toCharArray();
		KeyStore ts = KeyStore.getInstance("PKCS12");
		ts.load(new ByteArrayInputStream(data), passwKey);
		tmf = KeyManagerFactory.getInstance("SunX509");
		tmf.init(ts, passwKey);
		return tmf.getKeyManagers();

	public static void trustAllHosts() {

		HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
			public boolean verify(String hostname,
					javax.net.ssl.SSLSession session) {
				return (true);
Java class overloading/reloading - how two objects apparently belonging to the same class but they do not
Questions and answers for people that understand the code below:
  • why didn't I reload some java.lang.XXX? Because I needed to start the instrumentation agent to manipulate the AST - extra lines in article due to the standard Sun JVM behaviour on class loader priority imposed by the ClassLoader.getSystemClassLoader(); laziness...
  • Why didn't I reload also the AbstractButton so that my button can access it? Because the access octopus would spread far away...
  • Why could I reload a class that otherwise was accessible by the standard JVM class loader? The Oracle site says you cannot...; answer - I broke the Class Loading priority  convention - it's a convention, not an imposed rule to ask first the ClassLoader.parent.; second - I indicated explicitly the class loader I wanted to use.
  • Who would use such a thing?!? Java Web Start, Java Applets, and java Servlet containers, at least. :)
Expected outcome:
class hashCode
check if new JButton().getClass() == our class
Original class: true
Artificial class: false
toString for classes
originalClass: class javax.swing.JButton
artificialClass: class javax.swing.JButton
Check if classes are the same...
artificialButton.getClass() == button.getClass(): false
syntheticObject instanceof JButton: false
java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JButton
Cannot cast from class javax.swing.JButton to class javax.swing.JButton!?!
This is the genuine button toString(): javax.swing.JButton[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@5abbfa4c,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=,defaultCapable=true]
java.lang.IllegalAccessError: tried to access field javax.swing.AbstractButton.defaultCapable from class javax.swing.JButton
Cannot run toString for the artificial button because:
AbstractButton.defaultCapable is hidden for classes that don't inherit the AbstractButton.
And our artificialButton JButton tried to access the AbstractButton protected field.
And that AbstractButton is the JVM standard class loader - remember if (name.equals("javax.swing.JButton"))?
1 files attached: Test.java
Windows Media Encoder 9 - small, efficient, and powerful enough for screen capturing and streaming
Open the link http://www.microsoft.com/en-us/download/details.aspx?id=17792; choose downloading; next next next... accept T&C... next next next... install...
Wait few seconds, and you're done.
Once you start the program, choose Capture screen option, then choose between Specific window, Region of the screen, or Entire screen.
Then, enjoy the recording and the very small size of the encoded file - but still capturing all the details from your display.
Runtime dynamic loading of JARs (valid only on Sun JVMs)
Shortest (as of now) way for me to dynamically load classes from JARs that are not defined in the project.
public static synchronized void loadJAR(File jar) throws ClassNotFoundException {
	try {
		URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
		URL url = jar.toURI().toURL();
		if (Arrays.asList(loader.getURLs()).contains(url))
		Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { java.net.URL.class });
		method.invoke(loader, new Object[] { url });
	} catch (final ReflectiveOperationException e) {
		throw new ClassFormatError(e.getMessage());
	} catch (final java.net.MalformedURLException e) {
		throw new ClassNotFoundException(e.getMessage());
How to make OAuth Facebook login on your site and how to query FB for your customer's information
It is ssupposed you already have the base_facebook.php, facebook.php, and fb_ca_chain_bundle.crt in their corresponding paths and included as required.
1 files attached: IdentityProviders.php
abstract class IdentityProviderInterface{
	public $name;
	public function __construct($name){
	public function getName(){
		return $this->name;
	abstract public function getLabel();
	abstract public function getIconUrl();
	abstract public function getLink();
	abstract public function login();
	abstract public function logout();
	public function getUser(){
		return @$_SESSION['contact']['id'];
class OAuthFB extends IdentityProviderInterface{
	function __construct(){
		//$this->data=array('icon'=>'//facebook.com/favicon.ico','label'=>'Facebook','protocol'=>'OAuth-FB', 'login'=>'https://www.facebook.com/dialog/oauth','logout'=>'http://www.facebook.com/logout.php');
	public function getLabel(){
		return 'Facebook';
	public function getIconUrl(){
		return '//facebook.com/favicon.ico';
	public function getLink(){
			return "?FederatedIdentityProvider=facebook";
	public function login(){
		$facebook=new Facebook(array('appId'=>'*****************','secret'=>'*****************'));
				$userProfile= $facebook->api('/me');// the "me" represents the customer's profile, as you query the FB on the customer's behalf
			}catch(Exception $e){
		}?><!DOCTYPE html><html xmlns:fb="http://www.facebook.com/2008/fbml"><body><fb:login-button></fb:login-button><div id="fb-root"></div>
		<script>window.fbAsyncInit=function(){FB.init({appId:'<?php echo $facebook->getAppID()?>',cookie:true,xfbml:true,oauth:true});
		(function(){var e=document.createElement('script');e.async=true;e.src=document.location.protocol+'//connect.facebook.net/en_US/all.js';document.getElementById('fb-root').appendChild(e);}());
	public function logout(){
		$facebook=new Facebook(array('appId'=>'*****************','secret'=>'*****************'));
			header('Location: '.$facebook->getLogoutUrl());
Simple Java headless browser that keeps track of cookies - to make easier crowling the sites that require authentication
Sample minimal headless browser in java.
1 files attached: HeadlessBrowser.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import org.postgresql.util.Base64;

//import org.apache.commons.io.IOUtils;

public class HeadlessBrowser {
	private List<String> cookie = null;

	private HttpURLConnection getConnection(String url, String... headers)
			throws MalformedURLException, IOException {
		HttpURLConnection connection;
		connection = (HttpURLConnection) new URL(url).openConnection();
		if (cookie != null)
			for (int i = 0; i < cookie.size(); i++)
				connection.addRequestProperty("Cookie", cookie.get(i));
		if (headers != null)
			for (String header : headers) {
				int kvPos = header.indexOf(':');
				connection.setRequestProperty(header.substring(0, kvPos),
						header.substring(kvPos + 1));
				"HeadlessBrowser/1402211648 (+http://dragos-matei.sorescu.eu)");
		return connection;

	public Response get(String url,String...headers) throws IOException {
		HttpURLConnection connection = getConnection(url,headers);
		Response response = new Response(connection.getHeaderFields(),
		List<String> setCookie = response.headerFields.get("Set-Cookie");
		if (setCookie != null)
			cookie = setCookie;
		return response;

	public Response post(String url, String postBody, String... headers)
			throws IOException {
		HttpURLConnection connection = getConnection(url, headers);
		Response response;
		try {
			response = new Response(connection.getHeaderFields(),
		} catch (Throwable t) {
			response = new Response(connection.getHeaderFields(),

		List<String> setCookie = response.headerFields.get("Set-Cookie");
		if (setCookie != null)
			cookie = setCookie;
		return response;
	public Response put(String url, String postBody, String... headers)
			throws IOException {
		HttpURLConnection connection = getConnection(url, headers);
		Response response;
		try {
			response = new Response(connection.getHeaderFields(),
		} catch (Throwable t) {
			response = new Response(connection.getHeaderFields(),

		List<String> setCookie = response.headerFields.get("Set-Cookie");
		if (setCookie != null)
			cookie = setCookie;
		return response;

	public class Response {
		public Map<String, List<String>> headerFields;
		private byte[] body;

		public Response(Map<String, List<String>> headerFields, InputStream body)
				throws IOException {
			this.headerFields = headerFields;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			if (body != null) {
				byte[] dump = new byte[65536];
				for (;;) {
					int length = body.read(dump);
					if (length < 0)
					baos.write(dump, 0, length);
			this.body = baos.toByteArray();


		public byte[] getBodyBytes() {
			return this.body;

		public String toString() {
			return new String(this.body);

		public String toBase64String() {
			return Base64.encodeBytes(this.body);
			// return new String(dms.os.Codec.base64.encode(this.body));

		public String getHeader(String header) {
			List<String> strings = headerFields.get(header);
			return (strings == null) ? null : strings.get(0);
Simple PHP POST API call (using file_get_contents)
1 files attached: apiCall.php
function apiCall($path,$params){
	$opts=array('http'=>array('method'=>'POST','header'=>'Content-type: application/x-www-form-urlencoded','content'=>http_build_query($params)));
	return $result;
Simple HTA widget to see online data on desktop
How to:
  1. paste the main code below in a file named my_file.hta;
  2. just run the file by double-clicking it;
  3. close it by ALT-F4'ing it after getting it in focus.
  1. Supports resizing with mouse drag from the bottom-right corner;
  2. Supports moving the HTA on display using the CTRL-drag from the same bottom-right corner
  3. .
Tips for power users:
  • Make it Always on top:
    1. install an utility to bring windows on top (like http://www.softpedia.com/get/System/OS-Enhancements/PowerMenu.shtml);
    2. set attribute head/HTA:APPLICATION CAPTION="yes" - if you are using Power Menu;
    3. press F5 to refresh the widget and show the window caption;
    4. set the window always-on-top using the utility;
    5. set attribute head/HTA:APPLICATION CAPTION="no" - if you are using Power Menu;
    6. TADA! You have now  a small always-on-top HTML page showing your custom HTML page on desktop;
  • Show/hide it from task bar by manipulating the SHOWINTASKBAR attribute.
Sample caption (details below are server-side HTML that checks the status of 3rd party systems):
1 files attached: application.hta
How to throw an exception in Java even if the compiler does not allow you to...
How to throw an exception that you are not allowed to...
Did you ever get frustrated when a previous developer declared an interface that simply won't allow you to throw a new type of exception?
Rethrow it wrapped in a runtime exception: throw new RuntimeException(myOldJunkyException)
Did you ever need to rethrow the very same exception as reported by a remote system?
Serialize it, receive it, and rewrap it in a synthetic new exception with new RuntimeException().setStackTrace(myNewSyntheticStackTraceIncludingRemoteJunkyLines)
Or, just throw it as it is, by breaking the "convention" of throwing only declared exceptions from the method signature (which anyway the JVM does not care much at run time)... Usage:
public static int main(String[] args) throws IOException {
	THROW(new RuntimeException());
	return "dummy statement that won't ever be executed, but it's requied to compile the function. The compiler cannot figure out that the THROW will throw an exception... :D".length();
PS: Don't try it on JVM clones, it might not work at all. Neither on Google's Dalvik...
2 files attached: HelperClass.java Usage.java
HelperClass.java Usage.java
Windows NTNET test on "Java code to check if LDAP (including AD over LDAP) with basic authentication works (check if user/password) is valid"
Thanks to Dmitriy, I put below additional notes and an example on real-life NTNET domain test (sterilized code). The code below was tested on my current (production) NTNET DC and it worked fine.
Notes: {domain_controller_machine} can be found by running Windows echo %logonserver%, then run tracert {logon_server} to identify it's full name.
{my_ntnet_user in short form} is my NTNET user without any realm or domain information.
1 files attached: Test.java
Shortest (generally working) full-screen toggle coode
1 files attached: sample.html
<div class='pull-right' onclick='$(this).find("a").toggle()'>
	<a onclick='for(var k in{request:1,webkit:1,moz:1,ms:1})try{document.documentElement[k+"RequestFullScreen"]();}catch(e){console.log(e)}'><%icon:maximize%></a>
	<a style='display:none' onclick='for(var k in{exitFulls:1,mozCancelFullS:1,webkitCancelFullS:1})try{document[k+"creen"]();}catch(e){console.log(e)}'><%icon:window%></a>
Java code to check if LDAP (including AD over LDAP) with basic authentication works (check if user/password) is valid
Straight-forward pinging an LDAP server (to check if also authentication works).
1 files attached: Test.java
package dms;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.ldap.LdapName;
public class Test {
	public static void main(String[] args) {
		try {
		} catch (NamingException e) {

	public static void test() throws NamingException {
		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put(Context.PROVIDER_URL, "ldap://ldap_server.www.company.com:389/o=Users");
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.SECURITY_CREDENTIALS, "********");
		DirContext ctx = new InitialDirContext(env);
		Name name=new LdapName("invalid_name");
		Object o=null;
		ctx.bind(name, o);
		//Should throw "invalid name exception"
jQuery.val("input[type=checkbox]"[,value]) custom setter and getter - to work similar to regular input fields
Sample script on how to overwrite the jQuery val() for checkbox fields so that jQuery.val("input[type=checkbox]"[,value]) is in line with the one for input text.
1 files attached: jQueryValOverwrite.js
$.valHooks.checkbox.get=function(a){return $(a).attr('checked')?'checked':''}
HTML5 Canvas - sample gauge for smart home monitoring systems
Wrapper over HTML5 canvas for polar drawing (coordinates origin are in the centre of the canvas, the angle coordinate goes anti-clockwise, and the unitary magniture is the minimum of width and height of canvas) is attached. Instantiation is:
		var canvas=document.getElementById(dialName+"_z");
		var drawing=new Drawing(canvas);
. Sample usage (partial code) is in Sample.js. Result is:

2 files attached: Canvas.js Sample.js
Canvas.js Sample.js
:for(var sensorIdx=0;sensorIdx<sensors.length;sensorIdx++){
	var dialName=sensors[sensorIdx];
	var canvas=document.getElementById(dialName+"_z");
	var drawing=new Drawing(canvas);
	for(var hour=1;hour<=12;hour++){
	var params={};
	var lastPoint=null;
	var tooltips=[];
	for(var dataIdx=0;dataIdx<data.length;dataIdx++){
		var x=data[dataIdx][0];
		var y=data[dataIdx][1+json.sensor2column[sensorProperties.name]];
		var min=x%100;
		var hour=((x-min)/100)%100;
		var params={};
		var chan=2.5+2.5*Math.sin(Math.PI*2*((12+6+hour-1)/24));
	var rezolutie=allSensors[sensorProperties.name].resolution;
	var actualValue=Math.round(params.y/rezolutie)*rezolutie;
	var yesterdaysValue=Math.round(data[minTSIdx][colIdx]/rezolutie)*rezolutie;
	var delta=actualValue-yesterdaysValue;
	delta=delta+' ';
	}else if(actualValue<yesterdaysValue){
JackRabbit JCR - initial setup and "Hello World" to check that R/W access was granted
How I made the first Jackrabbit JCR have R/W access on the local environment. The smoke test (ran from a different application) is mentioned in SmokeTest.java. The reason I published this trivial code snippet (most of it copied from somewhere from the internet) is that I got frustrated for hours searching for a working snippet to grant me writing access.
2 files attached: Test.java SmokeTest.java
Test.java SmokeTest.java
Node root=session.getRootNode();
root.setProperty("number",123); System.out.println(root.getPath());
How to batch-kill processes in Windows from command prompt - taskkill /im image.exe /t /f
Automating web pages in Chrome using Selenium leads to lots of Chrome windows open that even if closed, the driver remains open. I am using the command taskkill /im chromedriver.exe /t /f to:
  • close all the Chrome Driver server processes;
  • close the Chrome Driver server process tree of children (/t);
  • close the Chrome Driver server processes forcefully (/f);
How to parse in PHP the cPanel mime type configuration, and how to filter the files using the .htaccess
Hosting more sites on a single IP and with an economic entry-level support from ISP (but still, allowed to process requests from more domains through the same PHP engine) leads to a long series of challanges.
One of them is that even though each site has its own files structured in its own folder, in case that a file was not found or there were conflicting files, the server seemed to pick randomly a file from another domain's folder.
Problem looked solved with the following configuration:
#Resources to their folders
RewriteCond %{REQUEST_URI} \.(pdf|doc|xml|pem|crx|apk|svg)$
RewriteRule ^(.+)$ %{HTTP_HOST}%{REQUEST_URI}
But it does not do what it should obviously do (due to whatever small detail, mistake, or misunderstanding from my side), so I found myself in need to filter the files through PHP code (yes, I know, let the web server deliver the static file contents). But until this will happen, I had to urgently improvise the code below.
The problem got solved by .htaccess-routing all the txt|png|jpeg|... to .mimeDelivery.php code (mentioned below).
The principle is that the script picks all the htaccessed mime types (as saved by cPanel in Perl store (serialized form). Perl deserialization algorithm is mentioned below.
1 files attached: Algorithm.php
Android - how to find the physical size of a display - using the DPI/PPI scale
Most of solutions found on internet compute the diagonal of the display by dividing the number of pixels to the DPI resolution. The capital mistake is that the DPI returns the dots per inch, and not the pixels. For this, you may use the scaledDensity to convert from DPI to PPI.
		float x=outMetrics.widthPixels/outMetrics.xdpi;
		float y=outMetrics.heightPixels/outMetrics.ydpi;
		double diag=Math.hypot(x, y);
		double physicalDiagonal=diag/outMetrics.scaledDensity;
		s+="Diag. logică: "+diag+";\n";
		s+="Diag. fizică: "+diag/physicalDiagonal+"\"";
Simple universal HTML client filter
A simple JS script for HTML client-side filtering of nodes:
function filterNodes(jQuerySet,value){
	var values=value.split(" ");
	var signs=[];
	for(var i=0;i<values.length;i++){
	var nodes=jQuerySet;
	for(var i=0;i<nodes.length;i++){
		var nodeValue=nodes[i].innerHTML.toUpperCase();
			nodeValue=nodeValue.replace(/<[^>]+>/g, '');
			for(var j=0;j<values.length;j++)
How to request and generate authentication nonces via emails
Some clues on how to implement a fast ad-hoc authentication mechanism based on the email of the user.
  1. Publish a page where the user may request the ad-hoc token;
  2. On the ad-hoc page request the user to input the email address;
    • To avoid bot spamming you may generate the form field name based on a secret name stored on the server-side session;
    • As a consequence, the submitted form must always come as a response to a pre-exising server session, session that is not preserved using the classical curl libraries used by bots;
  3. An email with the nonce will be sent to the given address;
    • The nonce will be stored only on the server side, so the only way to know it is to open the email - which means that the user has access to the given mail;
  4. The user will put the nonce from mail in form; together with the nonce, the server will keep in session also the generation time;
  • nonce may be short, it does not have to be long and secure;
  • only the server side and the email address owner have access to nonce;
  • nonce cannot be reused if another one has been generated for that given session;
  • the mechanism guarantees that the owner of the mail address is the user of the page;
  • the user does not need any 3rd party credentials authority supplier.
Menu sample:
1 files attached: OpenIdAuthenticationProvider
Emgu.CV video surveillance - part 2: how to keep only relevant images
One big issue in video surveillance is disseminating between relevant images and irrelevant images. For such comparison we need to compute the distance between two images, and for this a first step would be to bring images to only one relevant chanel, as example being:
  • luminosity channel - for comparing high resolution noiseless images;
  • crominance channel - when we have goot luminosity, but it changes over time;
Once we decide on the relevant channel for comparison, the next step is to filter the image (remove the noise). For this task I used the simple erode/dilate method mixed with median smoothing.
Once images are softened, I just compute the norm of the binary difference.
As seen in this code, I do run differences between thumbnails of images (which is much faster than the full image comparison.
Very important is that the value of threshold which is in my case 24 was not chosen randomly, but it is the one that gives best results on images both on day and night time.
To reach this value of 24 I ran tests on samples as following:
  • night time similar images;
  • night time small-difference images;
  • day time similar images;
  • day time small-difference images.
Even though the algorithm seems quite simple, it took me around one week to reach to it, as before I used various much more complex adaptive algorithms depending on other properties of images (including median luminance and noise quantity in image). At the end I reached to this very simple solution that brings the same quality but with much less code and much less complexity.
1 files attached: Campture.cs
C#-Selenium bridge to automate browser application testing
Depending on the application under test and the technical restrictions you may need to test applications on different platforms. One solution is to use Selenium. However, a huge limitation of Selenium is that windows cannot be reused. In order to automate various browsers my recommended way is to plug Selenium in a host (C#, Java, Python, or whatever else).
Attached is a scripting engine I used to automate with Selenium over C#. As a precondition, you need to import in the project the browser connectors:
  • chromedriver.exe
  • IEDriverServer.exe
The Firefox connector comes out of the box with Selenium.
Another important component is the attached test set class.
This second class is the big thing in application, which will be able to parse files as in main.dms. Or, sample1.dms, and sample2.dms.
5 files attached: SeleniumWrapper.cs TestSet.cs test.dms sample1.dms sample2.dms
SeleniumWrapper.cs TestSet.cs test.dms
#browser ie
#on step.before step_before.js

#timeout 20
#include login.dms

#include client_sim_add-remove.dms
#include client_people.dms
UNTIL => (''+window.location).match('^http://hidden-url.com/')

##Login > input email, password
$('input#email') <= 'secret@example.com'
$('input#password') <= 'secret-password'
##Login > click Login
$CLICK => $('button:contains(\"Login\")')
##Console > Wait for "Logout" button to appear
UNTIL => $('button:contains(\"Logout\")').length==1
##Console > Log in as
$CLICK => $('button:contains("Log in as")')
##Console > Log in as > roles := client; userId:=SecretUser*
$CLICK => $('input#roles').siblings("img")
$CLICK => $('.x-combo-list-item:contains("Client")')
$CLICK => $('input[name="userID"]').siblings('input[value^="Akela"]')
##Console > Click "Log in"
$CLICK => $('#btnLogin button:contains("Log in")')
$CLICK => $('#nav-Endusers button:contains("People")')
##People > Add
$CLICK => $('table:contains("Export to CSV") button:contains("Add")')
##People > Add > first_name, last_name, email, owner language, pass1, pass2, Active:=true, Save
$(':contains("Person details") input[name="first_name"]') <= d2a('%EXECUTION_ID%FirstName')
$(':contains("Person details") input[name="last_name"]') <= d2a('%EXECUTION_ID%LastName')
$(':contains("Person details") input[name="email"]') <= d2a('e%EXECUTION_ID%@example.com')
$('#EditPersonWindow input#ownerLanguage') <= 'English'
$('#EditPersonWindow input#pass1') <= d2a('%EXECUTION_ID%')
$('#EditPersonWindow input#pass2') <= d2a('%EXECUTION_ID%')
$('#EditPersonWindow label:contains("Active:")').siblings().find("input") <= true
$CLICK => $('#EditPersonWindow button:contains("Save")')
UNTIL => $('#EditPersonWindow').length==0
C# Emgu.CV video surveillance - part 1: how to capture snapshots every few seconds
A sample application to capture every two seconds a photo with the video camera using Emgu.CV on C#.
1 files attached: EmguCapture.cs
using Emgu.CV;
using System.Collections;
using Emgu.CV.CvEnum;
using Emgu.CV.Util;
using Emgu.CV.Structure;
using Emgu.CV.Features2D;
using System;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;

namespace ConsoleApplication2
	class Program
		static void Main(string[] args)
			if (args.Length!=0){
				if (args[0] == "start")
				if (args[0] == "stop")
			Console.WriteLine("Capture start | stop");
		public static void CaptureStart()
			var signature = "" + new Random().Next();
			Config.set("capture-session", signature);
			Capture c = new Capture();
			c.SetCaptureProperty(CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, 1024);
			c.SetCaptureProperty(CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, 768);
			for (;;)
				if (Config.get("capture-session") != signature) return;
					var thumbnail = c.QueryGrayFrame();
				catch (Exception e)
		public static void CaptureStop()
			Config.set("capture-session", "");
How to put in Windows the timestamp (year, month, day, hour, and minute) in an environment variable
(for /f "tokens=2,3,4 delims=/ " %i in ('date /t') do set _YMDHM=%k-%j-%i)
(for /f "eol=P tokens=1,2 delims=: " %i in ('time /t') do set _YMDHM=%_YMDHM%-%i-%j)
The final result should be similar to:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.


C:\Users\dsorescu>(for /f "tokens=2,3,4 delims=/ " %i in ('date /t') do set _YMD

C:\Users\dsorescu>set _YMDHM=2013-15-03

C:\Users\dsorescu>(for /f "eol=P tokens=1,2 delims=: " %i in ('time /t') do set

C:\Users\dsorescu>set _YMDHM=2013-15-03-04-10

SSL installation on Apache, and why SSL compression is A SECURITY HOLE
Some examples of how to install on Apache the certificates:
SSLCertificateFile /home/dsorescu/private/html/ssl/sorescu.eu.crt
SSLCertificateChainFile /home/dsorescu/private/html/ssl/sorescu.eu.pem #the CA file
SSLCertificateKeyFile /home/dsorescu/private/html/ssl/sorescu.eu.key
Most of people will also be tempted to enable the SSL comprssion as following:
SSLCompression on
Using compressed SSL poses a security leak very easy to understand and to exploit; the explaination is as following (all entities mentioned below are fictional and meant to ease the understanding of the method):
  1. your internet operator (or the IT department from your work) can listen to your compressed SSL requests (obviously they cannot decrypt them);
  2. the operator will modify your HTTP (non-secure) pages to include a small invisible image as following: <img src='https://dragos-matei.sorescu.eu/scrambled-image-name-freaky-url.png'/>;
  3. the network operator will measure the length of the browser request (the request will contain the cookies and the image fake url in a compressed and encrypted version);
  4. the network operator knows that once the url will contain repeating keywords (including passwords), the compressed SSL request will be shorter.
For this task to be successful, the operator (or your employer) should know a bit about which cookies the target site is using (this is not protected), and they have to use your browser to make lots of requests based on various possible passwords.
A way to ameliorate the speed of detection is to give up the brute force, but use orthogonal and white-noise techniques, which allows the attacker to send few very long requests with random information and see which of the requests is "closer" to your cookie values.
This works on the principle that the size of the compressed text decreases with the similarity of its components.
More details on: Short explanation from TheRegister.co.uk and Security.StackExchange.com.
Easy tool to query for IP details http://whois.net/ip-address-lookup/[IP_VALUE]
Often I was in need to know who is accessing my site. Aside the IP, I needed further information (like country or company owning the IP), and I found the following site very useful: http://whois.net/ip-address-lookup/[IP_VALUE] link.
Sorescu.EU SSL enabled - and how to enable SSL using cPanel for all subdomains
Steps (yes - it works out-of-box with Windows, you Linux geeks!):
  1. First step would be to buy a wildcard certificate, in my case being wildcard.sorescu.eu.pfx; this file should contain both, the private and the public key;
  2. Extract the key from the PFX: openssl pkcs12 -in wildcard.sorescu.eu.pfx -nocerts -out sorescu.eu.key; attention - you must know from before the password to be able to open the PFX; you will also be promted to enter the PEM pass phrase - which you should put it of a different value;
  3. Ensure that sorescu.eu.key was generated;
  4. Decrypt the key by running openssl rsa -in sorescu.eu.key -out sorescu.eu.decrypted.key;
  5. Ensure that sorescu.eu.decrypted.key got created;
  6. IMPORTANT! Now you need to generate the actual certificate, by running openssl pkcs12 -in sorescu.eu.pfx -clcerts -nokeys -out sorescu.eu.crt;
  7. Check that sorescu.eu.crt file got created;
  8. Generate the PEM file using openssl pkcs12 -in wildcard.sorescu.eu.pfx -cacerts -nokeys -out cabundle.pem; sincerely I don't understand much from this extension, only that it seems to contain the certification chain of the certificate;
  9. Check that the PEM file is created;
  10. Inside the cPanel open the SSL section;
  11. Go to Certificates (CRT);
  12. Once you install the CRT, you get a message similar to Installed Certificates for the domain(s): *.sorescu.eu (auto-detected);
  13. From the SSL home page in cPanel go to Activate SSL on Your Web Site (HTTPS);
  14. In the Certificate (CRT), Key (KEY), Ca Bundle (CABUNDLE) paste the text contents of the following files: sorescu.eu.crt, sorescu.eu.key, cabundle.pem;
  15. Open the web page.
I want to thank to http://www.mickgenie.com/cpanel-how-to-install-ssl-with-pfx-file/ for figuring me out how manage it.
Please also see below:
Sorescu technical Knowledge Base now supports OSSD fast search in Google Chrome
Now, once you visited KB.Sorescu.EU for the first time, you may instantly search the site via the Chrome's search extensions just by typing K, B, and [TAB] followed by your search query.
An example is below:

The technology used is OSSD Open Search standard; implementation has been done in two steps:
  • The home file contains the link to the OSSD file;
  • The second step was to supply the browser with the OSSD file.
Have a nice browsing experience!
2 files attached: header.html OSSD.xml
<link title="Sorescu KB" type="application/opensearchdescription+xml" rel="search" href="http://kb.sorescu.eu/ossd"/>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
	<ShortName>Sorescu KB</ShortName>
	<Description>Sorescu technical knowledge base</Description>
	<Image height="16" width="16" type="image/x-icon">http://kb.sorescu.eu/favicon.ico</Image>
	<Url type="text/html" template="http://kb.sorescu.eu/search/{searchTerms}"/>
Google Maps zoom control and other events - list for dummies
Or, how to check if the Google Map zoom changed in your page.
An example of using it is attached.
1 files attached: googleMapsListener.js
				alert('Tada - '+map.getBounds());
Light easy to use open web fonts - and how to use them
A great collection of web fonts found on: http://www.google.com/webfonts.
The usage of such fonts is very easy, as in example.
1 files attached: GoogleWebFonts.css
@import url(http://fonts.googleapis.com/css?family=Crafty+Girls|La+Belle+Aurore|Rock+Salt);
	font-family:"Rock Salt";
	font-family:"Crafty girls";
Annoying issue with PHP $_GET replacing the dots in variable names
The PHP replaces certain characters (among which dots, spaces, and square brakets) in the $_GET field names.
Personally I am strongly against pre-processing such information without a strong ground. The ground, the same with the well-known magic quotes workaround is to ameliorate the developer's life in using the parameters in a safer and easier way.
However, the effect is that in order to use any kind of variable name the developer needs to patch the patch.
The idea is that before using the $_GET variables they have to be corrected:
  1. clear the old keys;
  2. replace them with the correct key.
But now, another issue appeared in the PHP LightOpenID implementation, where the constructor strongly relies on this workaround.
Also this had to be fixed now.
2 files attached: PhpArgumentsFix.php LightOpenIdFix.php
{// Fix because $_GET replaces var name ., underscore, space, etc. to "_" FIX:F1301041743
	foreach($_GET as $k=>$v)
	foreach($get as $kv){
		foreach($this->data as $k=>$v){
jQuery - adding custom selectors
A trick for jQuery on how to add custom made selectors (I needed case insensitive CONTAINS selector).

Credentials go to http://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/ from where I found it.
1 files attached: jQuerySelector.js
Google Chrome extension to dynamically manipulate pages
How to make a small ad-hoc extension that manipulates dynamically pages every time they get loaded.
Their utility might be (but not limited to) autologin, GUI augmentation, manipulation, reformatting.
  1. Create a folder on disk (as an example, "E:\ChromePlugin\");
  2. Create a manifest.json file;
  3. Copy one JS utility (like jquery-1.8.2.js to the folder);
  4. Add an icon file (let's call it icon.png) to the folder (check http://kb.sorescu.eu/article/121107093243/Great-PNG-transparent-icon-finder-site-http-www.iconfinder.com- to find nice icons);
  5. Create the script file (let's call it script.js);
  6. Add the extension: Google Chrome > Wrench > Extensions > tick the "Developer mode" > click "Load unpacked extension" and select the folder ("E:\ChromePlugin\");
  7. Make available via HTTP (preferably HTTPS if you want to avoid some minor issues) the dynamic file (let's call it ChromeExtension.js);
  8. Attention, the jquery-1.8.2.js script mentioned in the manifest.json file won't be available in the context of http://localhost:81/js/ChromeExtension.js.
The manifest.json file contents should be as in manifest.json
The script.js is file the script that is actually launched every time a page loads. The ChromeExtension.js file contents is as attached.
3 files attached: manifest.json script.js ChromeExtension.js
	"name": "Hello World!", 
	"description": "My first Chrome extension.",
		"default_icon": "icon.png",
jQuery.getScript("http://localhost:81/js/ChromeExtension.js", function(data, textStatus, jqxhr){
	//alert("http://localhost/js/ChromeExtension.js could not be loaded");
// the jquery.js dump: (function(a,b){fu...
	// my actions
	// my TOP-SECRET work-related tweaking and bypassing applications
Small utility that types unique values from keyboard just by a hot key stroke
A short utility that types the current time stamp from keyboard (anywhere on desktop). I developed it because I was bored on typing all the times unique values while testing applications.
Executing the program is simple:
start RunCS TypeTimeStamp.cs

This program does the following:
  • When pressing CTRL-INS, the application will type the date in YYMMDDHHmmss format;
  • When pressing CTRL-SHIFT-INS, the application will type the date in YYMMDDHHmmssqq format;
  • When pressing CTRL-SHIFT-ALT-INS, the application will quit;
1 files attached: TypeTimestamp.cscript
RunCS with two new features - identification of default .NET runtime and compilation check
A new version of RunCS with the following features.
2 files attached: Header.cs RunCS.cs
/// v1212050857-1: @assembly %RunCSLib% refers to the .NET main assembly's libraries folder
    /// v1212050857-2: Usage: RunCS [-no-run] <file.cs> [<params>]
Great PNG transparent icon finder site - http://www.iconfinder.com/
A great icon finder site: http://www.iconfinder.com/ - Icon Finder.Com
  1. Ability to filter by pixel size (16x16, 24x24, ranges, etc.);
  2. Ability to show the icon with transparent background;
  3. Easy to download, no registration, no forms, no procedures;
  4. Licence filtering - free, commercial.
Programatic HTML automatic selection
A very useful way to programatically select text in your HTML.
Usage as in usage.html.
2 files attached: selectElementContents.js usage.html
selectElementContents.js usage.html
<a class='dms-button' href='#' onclick='selectElementContents($(this).siblings()[0])'><%icon:copy%></a>
Easy way to install the Microsoft Expression Encoder - using the MS WebPI
An easy way to install the Microsoft Expression Encoder (in case you need to process multimedia streams (via C#, etc.) is to simply follow the link http://www.microsoft.com/web/downloads/platform.aspx from where you install the Web Platform Installer - were you select the Microsoft Expression Encoder and it will automatically install the dependencies - Azure, .NET Web Express, etc. And all of it is free and easy.
Simple Dynamic C# Execution
A simple way to execute C# code, without using the Visual Studio is shown in RunCS.cs. Steps:
  1. Compile the code as RunCS.exe;
  2. Create a CS file;
  3. Execute RunCS.exe "my_file.cs" param1 param2
The CS file must contain the following lines, as in Program.cscript.
2 files attached: RunCS.cs Program.cscript
RunCS.cs Program.cscript
//@main MyNameSpace.MyClassName
//@assembly %programfiles%\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.dll
using System;
//@title This is optional, and it will be the window title
//@include ..\\my_dependency_file.cs
using System;
namespace MyNameSpace{
 public class MyClassName{
  public static void Main(string[]args){
    Console.WriteLine(args[0]+" "+args[1]);
How to execute remote programs on Windows
Recently I needed to start a program on a remote machine, so I used the following C# code (after adding the System.Management assembly).
1 files attached: Remote.cs
Tray icon flash on new messages in Outlook
Using the utility class from the previous post I wrote a small utility that is running through all the Outlook accounts and counts all the unread messages from inbox. Once a change is detected, the icon starts blinking, that will stop once you click once with the mouse on it.
Right now it is working for me with two Exchange accounts configured on my Outlook.
Very important note: before importing, you must add the reference to Microsoft.Office.Interop in order to access the Outlook interoperability automation engine.
The code is attached.
1 files attached: OutlookNotification.cs
C# counter in a Tray Icon - utility
Below is a small class I wrote in order to put a small tray icon with a custom background color, foreground color, and a text.
The particularity of this application is that it does not use any form.
1 files attached: TrayCounter.cs
Visual Basic and other applications don't start anymore after MS Windows update
It seems that recently Microsoft rolled out some new updates, among which one of them is related to a vulnerability in MSCOMCTL.OCX related to the RTF file handling. It might seem minor, but as a consequence the OCX file got fixed and it is not registered anymore.

In order to fix it, you have to run one of the following commands: 
  • regsvr32 c:\windows\system32\mscomctl.ocx
  • regsvr32 c:\windows\syswow64\mscomctl.ocx
depending on the operating system's bitness (either 32 or 64 bits).

For further information please consult also http://www.net-security.org/secworld.php?id=13429.
How to safely migrate data between databases in MySQL with PHP
I saw many people using lots of complex methods in attempt to move data between databases and file systems.

One of the most frequent methods is storing sequential data records in CSV, TSV, XML, or other formats. Obviously, each syntax requires specific escaping algorithms, a fact that most of times is omitted or forgotten by developer.

The last time I had to move data between two different instances of MySQL from two different sites I followed the approach:
  1. Select the database records and put them in an object (array);
  2. serialize the array;
  3. encode the array in base64 to ensure the text needs no escaping algorithm;
  4. copy the text on a support (file, ftp, mail, etc.);
  5. decode the array from base64 to native format;
  6. deserialize the array;
  7. take each record and save it to the database.
Some of the advantages are:
  1. you don't transfer database records, but business objects;
  2. if you have complex relations or fields, they just get wrapped, irrelevant on the database representation.
A code example is in sample.php.

And the result will be similar to sample.txt.
2 files attached: sample.php sample.txt
sample.php sample.txt
Right click functionality on some buttons - how to, and demo
To use at best the screen estate it is indicated sometimes to implement right-click handlers that trigger menus or other activities.

Recently I thought implementing such functionality on http://my.sorescu.eu/. The functionality implemented was triggering a dialogue box; the complete functionality is still under development, but the right-click handler has been implemented.

First, I looked for a library, and I found one that looked nice and simple (implemented using jQuery): http://www.abeautifulsite.net/blog/2008/05/jquery-right-click-plugin/#demo.

I am using Google Chrome right now to test it, and I saw the following misbehaviour: if I right-click on the "MY Place" button after right-dragging, I get the event triggered multiple times.

I patched the code by inserting a line after line 53:
$(this).mousedown( function(e) {
					var evt = e;
					$(this).unbind('mouseup');//added by dragos-matei@sorescu.eu to avoid double right click events, or ghost right clicks for right dragging events starting from this button
					$(this).mouseup( function() {
						if( evt.button == 2 ) {
							handler.call( $(this), evt );
							return false;
						} else {
							return true;
The issue seems to be in the original code that every time the  rightMouseDown   occurs, a new  rightMouseUp handler is added. 
What I did was to remove the rightMouseUp event also when rightMouseDown event.

Thanks to http://www.abeautifulsite.net and I hope it was useful for you.

N.B.: No guarantee that the script in discussion and the modification I did is useful, safe, good, or whatever else - just take it without any warranty, of any kind, under any circumstances.
Java 6 BrainBench certification results for Dragos-Matei Sorescu
I am happy to anounce that I passed another certification test, this time in Java. The overall results are:
Name: Java 6
Score: 4.53Date: 2012-07-10

View detailed topic results

Scored higher than 99% of all previous test takers.

Demonstrates understanding of most advanced concepts within the subject area. Appears capable of mentoring others on the most complex projects.
 Core Libraries 
 Practical Software Engineering 
 Integration Libraries 
 Class Definition 
 Support Libraries 
Weak Areas
    None Noted
Results per section are as below:
Dragos-Matei Sorescu
Test:Java 6
Annotation Processing(1/1)
Practical Software Engineering(6/7)
Object Design(1/1)
Best Practices(4/4)
Integration Libraries(5/5)
Web Services(2/2)
Class Definition(4/6)
Methods and Fields(2/3)
Access Modifiers(1/1)
Support Libraries(4/6)
Core Libraries(6/6)
Language and Utilities(1/1)
Visual Libraries(2/2)
OS Integration(1/1)
Data Types(1/1)
Flow of Control(1/1)
Virtual Machine(2/2)
Thread Management(1/1)
VM Internals(1/1)
Comments option available on Sorescu Knowledge Base
Now, based on the OpenID authentication, the KB.Sorescu.EU site accepts reader's comments. Please feel free to add your contribution to the value of the site.
Using OpenID SSO mechanism to retrieve your visitor's details
Recently I got interested in allowing people to add feedback, but from previous experience I noticed that such feedback mechanisms will allow spammers to compromise the site contents.
And to mitigate the situation, I had until recently two solutions:
  • using Captcha mechanisms;
  • using external APIs  to validate if the comment is a spam or not.
Now I decided to implement an OpenID mechanism, allowing people to log in with their already-existing credentials from Google, Yahoo, and other providers.
For this I found on the internet the http://gitorious.org/lightopenid API which will help me authenticate the consumers with their OpenID account. So, inside the LightOpenID class I defined few blocks.
This statement is executed every time the page is loaded, and it simply will set in my session the contact name and email, according to the authentication protocol.
But getting the name and email are not trivial task, for which I defined a getContactDetails() method inside that class.
This function, getContactDetails will return an array containing the email and the name (friendly, full name, or email, whichever is available, preferably the first).
How can be seen in the fist statement, I used a function getAllProviders that will return me all the identity providers recognized by my site. The code for this function is getAllProviders.
Finally, all this functionality is used in the PHP page, as in Usage.php.
The code is functioning for the moment only on http://my.sorescu.eu.
Have fun coding!
4 files attached: LightOpenID.php getContactDetails.php getAllProviders.php Usage.php
LightOpenID.php getContactDetails.php getAllProviders.php Usage.php
	<a class='dms-button' href='#' onclick='$(this).siblings().toggle()'>
	<a style='display:none' class='dms-button' href='?OpenIDAuthenticationProvider='><%icon:logout%>Logout</a>
	<a class='dms-button' href='#' onclick='$(this).siblings().toggle()'><%icon:login%>Login</a>
	<?foreach(LightOpenID::getAllProviders() as $providerName => $provider){?>
		<a style='display:none' class='dms-button' href='?OpenIDAuthenticationProvider=<?=$providerName?>'><img src='<?=$provider['icon']?>'/><?=$provider['label']?></a>
How to write a simple Light SMTP Server in C#
Sample of a small C# SMTP server with the following features:
  • 17KB source code;
  • five files of code only;
  • able to receive mails;
  • relay (forward) mails to external servers;
  • able to resolve the MX machine IPs for external mails;
  • mails to external recipients (external elaying) requires authentication.
The components of the code are:
  1. "Listener" daemon that takes the incoming SMTP requests;
  2. "MXDiscovery" module able to identify the IP of the external recipient servers;
  3. "Sender" component that is responsible for forwarding the message to external recipients;
  4. "SMTP" library with useful functions;
  5. "SMTPServer" the main application that starts the listener.

I hope this information might be useful for others, too.
5 files attached: SMTPServer.cs Listener.cs MXDiscovery.cs Sender.cs SMTP.cs
SMTPServer.cs Listener.cs MXDiscovery.cs Sender.cs SMTP.cs
Email obfuscator
When I decided to publish my CV on a web page (http://dragos-matei.sorescu.eu) I wanted to publish also my email, but without letting the bots read it.
So, I came with the following solution:
  1. encode the email in some kind;
  2. let the browser decode it after the page gets loaded.
For this I used the following encoded text:
The JavaScript to decode it is attached.
A small demonstration of the algorithm is put also below:
1 files attached: Decode.js
Search functionality enabled on www.sorescu.eu
Now the site http://www.sorescu.eu/ offers a search functionality in the left bar.
The code is relatively simple, with two components, client-side and server-side.
  • the PSP is a wrapper syntax on top of PHP;
  • after loading data, the client is responsible with formatting with JQuery the result;
  • in case of fast typing it is possible that multiple distinct requests to come in a different order (I shall fix it by adding a counter logic in few minutes).
2 files attached: ClientSide.html ServerSide.php
ClientSide.html ServerSide.php
Small Java Image Resizing Utility
Another small challenge; one guy came to me with 550 photographs in around 110 folders (they represent a tree structure of content images to be delivered and browsed by a front-end web application).

The challenge was to compress and resize all the images to improve the browsing performance.

Below is the code I wrote to perform this task.
My inspiration was http://www.mkyong.com/java/how-to-resize-an-image-in-java/ with the following small and compact code:
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
1 files attached: ImageResize.java
Screen Capture Update
My wife, the user of the Screen Capture application as described in  http://www.sorescu.eu/article/120220221500/Free-Screen-Capture-application explained me that she needs to run it also while in Full Screen mode.

For this I had to hook to the Windows Hot Key events, after I registered with the desired shortcut.

The chosen shortcut is <CTRL>+<ALT>+<PRINT_SCREEN>, and the code update is as in file below. Main call as following:
Thread t=new Thread(new ThreadStart(ProcessHotKey));
Worthy mentioning are the following:
  • I used
    GetMessage(ref msg,IntPtr.Zero,0,0)
    for avoiding message queues to any form, but to the current thread;
  • It was required
    int hashCode=("hash-"+modifiers+"-"+key).GetHashCode();
    to ensure that the Hot Key is unique in Windows;
  • The Hot Key handler had to be ran in a separate thread, using
    new Thread(new ThreadStart(ProcessHotKey))
1 files attached: RegisterHotKey.cs
A small Java program to generate transparent images (for dynamic background colours)
Somebody requested me to generate a web page with a wall background that should change the wall colour based on the user's desire.
I thought a transparency-enabled background will suffice, with a dynamic background of the image.
  1. Take the background image from my customer;
  2. Generate a mask image as a copy of the background image, and remove the area (set it to black) where I want to have transparency;
  3. Run the Java program that is written below;
  4. Use the final result image and put it in a web page.
You can check the result (while the web page is still there) at: http://dev-alexandru-doors.sorescu.eu/products-en_GB where you may click any image from gallery and the background image will appear.
1 files attached: ImageTansparency.java
Sending dynamic client-side parameters in URL fragments and manipulating them
Seldom I was in need to perform client filtering on tables and other data, and eventually save the filter. One solution was sending the filter to the server and generate the filtered page.
The functions below (I am using them few years already in Internet Explorer) are used to store and get the properties from fragments.
Some useful clues:
  • When the page is loaded, check all the fragment parameters and update the controls and perform filtering, etc.;
  • Whenever you update a filter in a text field, etc., you can save it in the fragment;
  • You can send the link with fragment to anybody else, and if the first bullet (filter executed on page loading) is accomplished, the URL receiver will see the same page as you.
1 files attached: getFragmentValues.js
Scripted C# - or how to run dynamic C# code, without compilation
As I started to develop small applications in C#, I thought why shouldn't I use the same paradigms that I used in Java... dynamic code execution, execution without compile/build/deploy process, hot-swap, etc.

I am far away from acomplishing the same functionality, but I started with writing a small program (81 lines) mentioned below.

When executing, it is able to compile and execute C# code that is written in text files, on the spot.

The mechanism is quite simple: it expects in the command line the name of an XML file (mentioned below this script) that describes:
  • the list of CS files that should be compiled;
  • the list of external binaries, if required;
  • the title of the application;
  • the entry point (the class name that contains the Main function).
An example (SMTPServer.csscriptof the input XML looks like attached.
Useful information:
  • the class mentioned in the CSScript/EntryClass node must have a Main(string[]args) method;
  • the Main method must be public and static!
  • additional parameters to be sent to the Main method are added to the executed command line!
Example of using the script attached.
In my development (that I started yesterday evening) I used some information from the following links:
The application code is straight forward, and I don't think any comment is required. If you need any comment, then either you should learn programming, or study a bit some C-like languages.

If you wonder why I don't also give the EXE file, please feel free to open the Visual Studio, create an empty project, add a class and paste this code.
3 files attached: RunCS.cs SMTPServer.csscript start.cmd
RunCS.cs SMTPServer.csscript start.cmd