Category: programming
-
Python – Hamming Distance
def hamming_distance(s1, s2): assert len(s1) == len(s2) return sum([ch1 != ch2 for ch1, ch2 in zip(s1, s2)]) def test_hamming_distance(): s1,s2=”0102304″, “9375304” res = hamming_distance(s1, s2) print(res) print((s1,list(zip(s1,s2))))
-
Java – Parse Integer and String Lists from Text
public static List getIdsList(String ids) { ids = StringUtils.stripStart(ids, “{“); ids = StringUtils.stripEnd(ids, “}”); List list = parseInts(ids, ‘,’); return list; } public static List parseInts(String source, char delimeter) { if (StringUtils.isEmpty(source)) { return Collections.emptyList(); } List result = new ArrayList(); for (String intStr : source.split(String.valueOf(delimeter))) { result.add(NumberUtils.toInt(intStr)); } return result; } public static List…
-
Java – Get Exception as String
public static String exceptionToString(Throwable throwable ) { try{ StringWriter stringWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); }catch(Exception e){ // shouldn’t happen but whatever return null; } }
-
Java – ByteToHex and CharToHex
public static String byteToHex(byte b) { // Returns hex String representation of byte b char hexDigit[] = {‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’ }; char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] }; return new String(array); } public static String charToHex(char…
-
JavaScript – Get Stack Trace as String
public static String getStackTrace(Throwable e){ StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String stacktrace = sw.toString(); return stacktrace; }
-
JavaScript – Simple Helper Functions
Get an HTML object element function el(elementId){ var elementObject = null; try{ elementObject = document.all ? document.all[elementId] : document.getElementById(elementId); }catch(e){ // nothing to do } return elementObject; } Trim a string function trim(str) { return str.replace(/^\s*|\s*$/g,””); } Set focus on an HTML object element function focusElement(elementId){ try{ el(elementId).focus(); }catch(e){} } Move an HTML object element…
-
JavaScript – Check if HTML Links is visited or not
UPDATE: Code no longer works accross all browser. The reason is pretty clear – History Theft ! function hasLinkBeenVisited(url) { var link = document.createElement(‘a’); link.href = url; document.body.appendChild(link); if (link.currentStyle) { //IE var color = link.currentStyle.color; //alert(“[IE] url:”+url+”, color:”+color) if (color == ‘#800080’){ return true; } } else { // Firefox link.setAttribute(“href”,url); var computed_style =…