{{error}}
{{(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.
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
javascript:Array(...document.getElementsByTagName("video")).forEach(it=>it.playbackRate=1)
increase.js
javascript:Array(...document.getElementsByTagName("video")).forEach(it=>it.playbackRate*=1.25)
Simple compression/decompression functions for byte arrays
1 files attached: Compression.java
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.setLevel(Deflater.BEST_COMPRESSION);
        zipOut.putNextEntry(new java.util.zip.ZipEntry("data"));
        zipOut.write(in);
        zipOut.closeEntry();
        zipOut.flush();
        zipOut.close();
        return baos.toByteArray();
    }

    public static byte[] decompress(byte[] in) throws IOException {
        ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(in));
        zis.getNextEntry();
        return zis.readAllBytes();
    }
}
simple XLSX parser in Java - returns a map with a list of rows for each sheet
1 files attached: XlsxReader.java
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"))
                    .findFirst().get());
            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()).add(null);
                    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(xlsx.zipFiles.keySet());
        System.out.println(new String(xlsx.zipFiles.get("xl/workbook.xml")));
        System.out.println(xlsx.getData());
    }
}
2017-08-03
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
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){
        try{
            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())
                       .filter(it->it.getName().endsWith(".cer"))
                       .map(it->Try(()->new FileInputStream(it)))
                       .map(file->Try(()->x509.generateCertificate(file)))
                       .toArray(X509Certificate[]::new);
    }

    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){
        if(savedCertificate.getSerialNumber().equals(newCertificate.getSerialNumber()))
            return true;
        try{
            newCertificate.verify(savedCertificate.getPublicKey());
            return true;
        }catch(Throwable t){
            return false;
        }
    }

    private static void validateCertificate(X509Certificate it){
        System.out.println("Checking certificate: "+it.getSubjectDN());
        for(X509Certificate saved : getSavedCertificates())
            if(matches(saved,it)){
                System.out.println("Matched by: "+saved.getSubjectDN()+" by "+saved.getIssuerDN());
                return;
            }
        System.out.println("Not matched!!!");
        if(promptFor(it))
            saveCertificate(it);
        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+=x.getSerialNumber()+"\r\n";
        message+=new BASE64Encoder().encode(x.getSignature());
        return JOptionPane.showConfirmDialog(null,message)==ConfirmationCallback.YES;
    }

    public static void main(String[] args) throws IOException{
        trustSavedCertificates();
        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)
                            validateCertificate(cert);
                    }
                }
        };
        try{
            SSLContext sslContext=SSLContext.getInstance("SSL");
            sslContext.init(null,trustAllCerts,new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        }catch(Exception e){
            e.printStackTrace();
        }

    }
}
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
validateUsingCertificates.java
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();
con.setHostnameVerifier(verifier(publicKeys));
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
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();
			readInt(8);
			if (!readAsciiString(0, 8).equals("NTLMSSP\0"))
				return;
			if (readInt(8) != 1)
				return;
			readInt(12);
			this.domain = readSecurityBuffer(16);
			this.workstation = readSecurityBuffer(24);
		} else if (this.version == 3) {
			challenge = null;
			readInt(8);
			if (!readAsciiString(0, 8).equals("NTLMSSP\0"))
				return;
			if (readInt(8) != 3)
				return;
			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
@Memoized
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
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'>
					<tr>
						<th ng-repeat='header in logData.summary.headers'>{{header}}</th>
					</tr>
				</thead>
				<tbody ng-show='toggleSummaryTable'>
					<tr ng-repeat='record in logData.summary.data'>
						<td ng-repeat='header in logData.summary.headers'>{{record[header]}}</td>
					</tr>
				</tbody>
			</table>
regular expression custom jQuery selector
1 files attached: jQuery.matches.js
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
sQuery.js