A javascript converts JSON object to XML string








http://cworld.110mb.com/doku.php?id=devel:convert-json-object-to-xml-string




A Complete Javascript AJAX library








simple = {
    version : 0.1
}
simple.http = {
    lastModified : {},
    createRequest : function() {
        if (typeof XMLHttpRequest !== 'undefined') {
            try {
                return new XMLHttpRequest();
            } catch (e) {
            }
        }
        if (typeof ActiveXObject !== 'undefined') {
            var msxml = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0',
                    'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
            for (var i = 0, len = msxml.length; i < len; ++i) {
                try {
                    return new ActiveXObject(msxml[i]);
                } catch (e) {
                }
            }
        }
        throw new Error('This browser does not support XMLHttpRequest.');
    },
    sendRequest : function(o) {
        o = o || {};
        o = {
            method : typeof o.method == 'string'
                    ? o.method.toUpperCase()
                    : 'GET',
            url : o.url || location.href,
            async : o.async || true,
            data : o.data || null,
            user : o.user || null,
            cached : o.cached || true,
            password : o.password || null,
            contentType : o.contentType || 'application/x-www-form-urlencoded',
            ifModified : o.ifModified || null,
            timeout : o.timeout || null,
            onSuccess : o.onSuccess || function() {
            },
            onFailure : o.onFailure || function() {
            },
            onTimeout : o.onTimeout || function() {
            },
            onProgress : o.onProgress || function() {
            },
            scope : o.scope || null
        }
        var request = simple.http.createRequest();
        var progress = 0;
        var timeoutId;
        if (o.timeout) {
            timeoutId = setTimeout(function() {
                        request.abort();
                        onTimeout();
                    }, o.timeout);
        }
        request.onreadystatechange = function() {
            if (request.readyState === 4) {
                if (timeoutId) {
                    clearTimeout(timeoutId);
                }
                if ((request.status >= 200 && request.status < 300)
                        || request.status === 1223
                        || request.status === 304
                        || (!request.status && location.protocol == 'file:')
                        || (navigator.userAgent.indexOf('Safari') >= 0 && typeof request.status == 'undefined')) {
                    //
                    // Success
                    //
                    if (o.ifModified) {
                        simple.http.lastModified(o.url) = request
                                .getResponseHeader("Last-Modified");
                    }
                    var responseData;
                    if (o.method == 'HEAD') {
                        responseData = request.getAllResponseHeaders();
                    } else {
                        if (request.getResponseHeader('Content-Type')
                                .indexOf('xml') != -1) {
                            responseData = request.responseXML;
                        } else {
                            responseData = request.responseText;
                        }
                    }
                    if (o.scope) {
                        o.onSuccess.apply(o.scope, responseData);
                    } else {
                        o.onSuccess(responseData);
                    }
                } else {
                    o.onFailure(request.status, request.statusText);
                }
            } else {
                o.onProgress(progress);
            }
        }
        if (o.method == 'GET') {
            if (o.data) {
                o.url = o.url + ((o.url.indexOf('?') == -1) ? '?' : '&')
                        + o.data;
                o.data = null;
            }
            if (!o.cached) {
                o.url = appendTimeStamp(o.url);
            }
        }
        if (o.user && o.password) {
            request.open(o.method, o.url, o.async, o.user, o.password);
        } else {
            request.open(o.method, o.url, o.async);
        }
        request.setRequestHeader('Content-Type', o.contentType);
        request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        if (o.ifModified) {
            request.setRequestHeader("If-Modified-Since",
                    simple.http.lastModified[o.url] || new Date(0));
        }
        request.send(o.data);
        if (!o.async) {
            request.onreadystatechange();
        }
        //
        // inner functions
        //
        function appendTimeStamp(url) {
            var ts = +new Date();
            // try replacing _= if it is there
            var ret = url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
            // if nothing was replaced, add timestamp to the end
            return ret
                    + ((ret == url)
                            ? (url.match(/\?/) ? "&" : "?") + "_=" + ts
                            : "");
        }
    },
    get : function(o) {
        o.method = 'GET';
        simple.http.sendRequest(o);
    },
    getAsync : function(o) {
        o.async = true;
        simple.http.get(o);
    },
    getSync : function(o) {
        o.async = false;
        simple.http.get(o);
    },
    post : function(o) {
        o.method = 'POST';
        simple.http.sendRequest(o);
    },
    postAsync : function(o) {
        o.async = true;
        simple.http.post(o);
    },
    postSync : function(o) {
        o.async = false;
        simple.http.post(o);
    },
    head : function(o) {
        o.method = 'HEAD';
        simple.http.sendRequest(o);
    }
};
simple.xml = {
    createDocument : function(rootTagName, namespaceURI) {
        rootTagName = rootTagName || '';
        namespaceURI = namespaceURI || '';
        if (document.implementation && document.implementation.createDocument) {
            // W3C way
            document.implementation.createDocument(namespaceURI, rootTagName,
                    null);
        } else {
            // IE way
            var doc = new ActiveXObject('MSXML2.DOMDocument');
            if (rootTagName) {
                var prefix = '';
                var tagname = rootTagName;
                var p = rootTagName.indexOf(':');
                if (p != -1) {
                    prefix = rootTagName.substring(0, p);
                    tagname = rootTagName.substring(p + 1);
                }
                if (namespaceURI) {
                    if (!prefix) {
                        prefix = 'a0';
                    }
                } else {
                    prefix = '';
                }
                var text = '<'
                        + (prefix ? (prefix + ':') : '')
                        + tagname
                        + (namespaceURI ? (' xmlns:' + prefix + '="'
                                + namespaceURI + '"') : '') + '/>';
                doc.loadXML(text);
            }
            return doc;
        }
    },
    loadSync : function(url) {
        var xmldoc = simple.xml.createDocument();
        xmldoc.async = false;
        xmldoc.load(url);
        return xmldoc;
    },
    loadAsync : function(url, callback) {
        var xmldoc = simple.xml.createDocument();
        if (document.implementation && document.implementation.createDocument) {
            // FF
            xmldoc.onload = function() {
                callback(xmldoc);
            };
        } else {
            // IE
            xmldoc.onreadystatechange = function() {
                if (xmldco.readyState == 4) {
                    callback(xmldoc);
                }
            }
        }
        xmldoc.load(url);
    },
    parse : function(text) {
        if (typeof DOMParser != 'undefined') {
            // Mozilla, Firefox and related browsers
            return (new DOMParser()).parseFromString(text, 'application/xml');
        } else if (typeof ActiveXObject != 'undefined') {
            // Internet Explorer
            var doc = simple.xml.createDocument();
            doc.loadXML(text);
            return doc;
        } else {
            var url = 'data:text/xml;charset=utf-8,' + encodeURIComponent(text);
            var request = new XMLHttpRequest();
            request.open('GET', url, false);
            request.send(null);
            return request.responseXML;
        }
    },
    serialize : function(node) {
        if (typeof XMLSerializer != "undefined") {
            return (new XMLSerializer()).serializeToString(node);
        } else if (node.xml) {
            return node.xml;
        } else {
            throw new Error("XML.serialize is not supported or can't serialize "
                    + node);
        }
    },
    getNodes : function(context, xpathExpr, namespaces) {
        return (new simple.xml.XPathExpression(xpathExpr, namespaces))
                .getNodes(context);
    },
    getNode : function(context, xpathExpr, namespaces) {
        return (new simple.xml.XPathExpression(xpathExpr, namespaces))
                .getNode(context);
    }
};
simple.xml.XPathExpression = function(xpathText, namespaces) {
    this.xpathText = xpathText; // Save the text of the expression
    this.namespaces = namespaces; // And the namespace mapping
    if (document.createExpression) {
        // If we're in a W3C-compliant browser, use the W3C API
        // to compile the text of the XPath query
        this.xpathExpr = document.createExpression(xpathText,
                // This function is passed a
                // namespace prefix and returns the URL.
                function(prefix) {
            return namespaces[prefix];
        });
    } else {
        // Otherwise, we assume for now that we're in IE and convert the
        // namespaces object into the textual form that IE requires.
        this.namespaceString = "";
        if (namespaces != null) {
            for (var prefix in namespaces) {
                // Add a space if there is already something there
                if (this.namespaceString)
                    this.namespaceString += ' ';
                // And add the namespace
                this.namespaceString += 'xmlns:' + prefix + '="'
                        + namespaces[prefix] + '"';
            }
        }
    }
};
simple.xml.XPathExpression.prototype.getNodes = function(context) {
    if (this.xpathExpr) {
        // If we are in a W3C-compliant browser, we compiled the
        // expression in the constructor. We now evaluate that compiled
        // expression in the specified context.
        var result = this.xpathExpr.evaluate(context,
                // This is the result type we want
                XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
        // Copy the results we get into an array.
        var a = new Array(result.snapshotLength);
        for (var i = 0; i < result.snapshotLength; i++) {
            a[i] = result.snapshotItem(i);
        }
        return a;
    } else {
        // If we are not in a W3C-compliant browser, attempt to evaluate
        // the expression using the IE API.
        try {
            // We need the Document object to specify namespaces
            var doc = context.ownerDocument;
            // If the context doesn't have ownerDocument, it is the Document
            if (doc == null) {
                doc = context;
            }
            // This is IE-specific magic to specify prefix-to-URL mapping
            doc.setProperty("SelectionLanguage", "XPath");
            doc.setProperty("SelectionNamespaces", this.namespaceString);
            // In IE, the context must be an Element not a Document,
            // so if context is a document, use documentElement instead
            if (context == doc) {
                context = doc.documentElement;
            }
            // Now use the IE method selectNodes( ) to evaluate the expression
            return context.selectNodes(this.xpathText);
        } catch (e) {
            // If the IE API doesn't work, we just give up
            throw new Error("XPath not supported by this browser.");
        }
    }
};
simple.xml.XPathExpression.prototype.getNode = function(context) {
    if (this.xpathExpr) {
        var result = this.xpathExpr.evaluate(context,
                // We just want the first match
                XPathResult.FIRST_ORDERED_NODE_TYPE, null);
        return result.singleNodeValue;
    } else {
        try {
            var doc = context.ownerDocument;
            if (doc == null) {
                doc = context;
            }
            doc.setProperty("SelectionLanguage", "XPath");
            doc.setProperty("SelectionNamespaces", this.namespaceString);
            if (context == doc) {
                context = doc.documentElement;
            }
            // In IE call selectSingleNode instead of selectNodes
            return context.selectSingleNode(this.xpathText);
        } catch (e) {
            throw new Error("XPath not supported by this browser.");
        }
    }
};



意大利人说英语











一舟书库








http://www.guyizhou.cn/




TeXnicCenter: Free alternative to WinEdt








TeXnicCenter is a (LA)TEX editor for Windows. It is a free alternative of WinEdt.

More information about (La)TEX on Windows: Installing (La)TeX for Free




Find file/data duplicates on Linux and Windows








There could be many duplicated copies of files sitting in your hard drive, especially, on the huge capacity file servers.

There are some software / scripts can be used to find and delete the duplicates. For example:

  1. fdupes is a command line tool written in c. It uses MD5 to find the duplicated copies.
  2. FSlint is an GUI application available on Linux that can find and display the duplicates.
  3. Noclone is an windows application that does byte-to-byte comparison to find the duplicates on the file servers. (Windows only)



Javascript: Lazy Function Definition Pattern








See this article at Peter's blog.


各国国歌欣赏








朝鲜民主主义人民共和国国歌
苏维埃社会主义共和国联盟国歌
中华人民共和国国歌
中华民国国歌
美利坚合众国国歌
大不列颠及北爱尔兰联合王国
日本国



A python script to convert long integer to date/time format








#!/usr/bin/python
import sys,time

if len(sys.argv) > 1:
    print time.ctime(long(sys.argv[1]))



How to get the button by element id in extjs?








Inline:

        buttons: [{
text: 'Save',
type: 'submit',
id: "save",
handler: function(){ ... }
}],


By reference:



Ext.getCmp('save').on('click', function(){ ... });


 



Original: Cannot assign id to button?




fcitx 配置文件乱码的解决办法








  • fcitx配置文件乱码的解决办法(fcitx 配置文件是 .fcitx/config)
    1. 如果你使用 vim
      • su
      • echo “set fencs=utf-8,ucs-bom,gb18030,gbk,gb2312,cp936” » /etc/vim/vimrc
    2. 如果你使用 gedit
      • gedit
      • File → Open
      • Select Character Coding at the bottom part of the dialog
      • Select Add or Remove
      • Select Chinese Simplified GBK, click Add button to add it to right column, then click OK button
      • Select Chinese Simplified GBK,
      • Right Click, then tick Show hidden files
      • Select ~/.fcitx/config



Debian 5.0 Lenny 安装中文输入法 fcitx








1. 安装fcitx
  • sudo aptitude install fcitx
2. fcitx启动设置
  • sudo vi /etc/X11/Xsession.d/95fcitx
    • export LANG="en_AU.UTF-8"
    • export LC_TYPE="zh_CN.UTF-8"
    • export XMODIFIERS="@im=fcitx"
    • fcitx &

3. 重启XWindows
  • Ctrl + Alt + Backspace
4. 设置fcitx

  • fcitx 的配置文件在~/.fcitx目录。你可能需要编辑~/.fcitx/config文件设置字体才能使fcitx正常显示。
  • 当打开~/.fcitx/config文件可能会是乱码。这里是解决办法
  • vi ~/.fctix/config

  • [程序]
    显示字体(中)=SimSun
    显示字体(英)=Courier New
    显示字体大小=11
    主窗口字体大小=11
    字体区域=zh_CN.UTF-8
    是否使用AA字体=1
    是否使用粗体=1




Making Ajax Elegantly Fast








Found this article describes an way to create XMLHttpRequest object more efficiently:

var asyncRequest = function() {
function handleReadyState(o, callback) {
if (o && o.readyState == 4 && o.status == 200) {
if (callback) {
callback(o);
}
}
}
var getXHR = function() {
var http;
try {
http = new XMLHttpRequest;
getXHR = function() {
return new XMLHttpRequest;
};

}
catch(e) {
var msxml = [
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP'
];
for (var i=0, len = msxml.length; i < len; ++i) {
try {
http = new ActiveXObject(msxml[i]);
getXHR = function() {
return new ActiveXObject(msxml[i]);
};

break;
}
catch(e) {}
}
}
return http;
};
return function(method, uri, callback, postData) {
var http = getXHR();
http.open(method, uri, true);
handleReadyState(http, callback);
http.send(postData || null);
return http;
};
}();


More detail and discussions: http://www.dustindiaz.com/faster-ajax/




Add loadXML, selectNodes and selectSingleNode functions for Firefox








var infoNodes;
if(document.all)
infoNodes = document.getElementById("xmlInfo").XMLDocument.documentElement.selectNodes("Product");
else{
XMLDocument.prototype.loadXML = function(xmlString)
{
var childNodes = this.childNodes;
for (var i = childNodes.length - 1; i >= 0; i--)
this.removeChild(childNodes[i]);

var dp = new DOMParser();
var newDOM = dp.parseFromString(xmlString, "text/xml");
var newElt = this.importNode(newDOM.documentElement, true);
this.appendChild(newElt);
};

// check for XPath implementation
if( document.implementation.hasFeature("XPath", "3.0") )
{
// prototying the XMLDocument
XMLDocument.prototype.selectNodes = function(cXPathString, xNode)
{
if( !xNode ) { xNode = this; }
var oNSResolver = this.createNSResolver(this.documentElement)
var aItems = this.evaluate(cXPathString, xNode, oNSResolver,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
var aResult = [];
for( var i = 0; i < aItems.snapshotLength; i++)
{
aResult[i] =  aItems.snapshotItem(i);
}
return aResult;
}

// prototying the Element
Element.prototype.selectNodes = function(cXPathString)
{
if(this.ownerDocument.selectNodes)
{
return this.ownerDocument.selectNodes(cXPathString, this);
}
else{throw "For XML Elements Only";}
}
}

// check for XPath implementation
if( document.implementation.hasFeature("XPath", "3.0") )
{
// prototying the XMLDocument
XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode)
{
if( !xNode ) { xNode = this; }
var xItems = this.selectNodes(cXPathString, xNode);
if( xItems.length > 0 )
{
return xItems[0];
}
else
{
return null;
}
}

// prototying the Element
Element.prototype.selectSingleNode = function(cXPathString)
{   
if(this.ownerDocument.selectSingleNode)
{
return this.ownerDocument.selectSingleNode(cXPathString, this);
}
else{throw "For XML Elements Only";}
}
}

// 创建 XML 文档对象
var xmlRef = document.implementation.createDocument("text/xml", "", null);
// 使用 importNode 将HTML DOM 的一部分转换为XML 文档。
// 参数 true 表示克隆全部子元素。
var myNode = document.getElementById("xmlInfo");
xmlRef.loadXML(myNode.innerHTML);
infoNodes = xmlRef.documentElement.childNodes;
}


Source: http://www.cnblogs.com/skyover/archive/2005/12/03/290055.html

See Also: Firefox compatible xPath functions in JavaScript


Fix warning message when using XAMPP control








When start XAMPP-control.exe, it shows an warning message : xampp-control don't find the install directory.

 

Solution:

1. Run regedit.exe

2.  create:

HKEY_LOCAL_MACHINE\SOFTWARE\XAMPP
Registry Key : Install_Dir
Value : D:\xampp (your xampp directory)




XPATH support in browsers








Internet Explorer: http://www.codeguru.com/cpp/i-n/internet/xml/article.php/c12431__1/

Firefox: http://www.codeguru.com/cpp/i-n/internet/xml/article.php/c12431__2/




Re-inventing XMLHttpRequest: Cross-browser implementation with sniffing capabilities








Description: http://www.ilinsky.com/articles/XMLHttpRequest/

Download: http://code.google.com/p/xmlhttprequest/




Differences between IE and Firefox on Javascript and XML









IE Supported Code

Firefox Supported Code

Creating XML DOM object

Creating XML DOM object

xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

xmlDoc  = document.implementation.createDocument("","doc",null);

Make sure before loading the XML file you use the following lines of code

It is the same for Firefox

xmlDoc.async = false;xmlDoc.preserveWhiteSpace=true;

xmlDoc.async = false;xmlDoc.preserveWhiteSpace=true;

Loading an XML file

Loading an XML file

xmlDoc .load("XML Path");

xmlDoc.onload=function (){};xmlDoc .load("XML Path");




Here Firefox does not support loading of XML directly. So we should use a dummy function and then load XML.

Selecting Single Node in an XML with conditions

Selecting Single Node in an XML

xmlNode=xmlDoc.selectSingleNode("//Path[@Attribute='condition']/remaining path");

selectSingleNode is not supported in Firefox. We can use XML Path to do our job as given below.




function SelectSingleNode(xmlDoc, elementPath){   if (document.implementation && document.implementation.createDocument)      {         var nodes=document.evaluate(elementPath, xmlDoc, null, XPathResult.ANY_TYPE, null);var results=nodes.iterateNext();return results;       } }




To the above function we need to pass XML and the Element path like "//Path[@Attribute='condition']/remaining path" and access it as below




xmlNode=SelectSingleNode(xmlDoc ,"//Path[@Attribute='condition']/remaining path");

For getting value of particular Attribute

For getting value of particular Attribute

xmlNode.getAttribute("Attribute Name");   

Here we can use the code given below




xmlNode.attributes["Attribute Name"].value;    

To access the Text of the Single Node selected

To access the Text of the Single Node selected

xmlNode.text;

xmlNode.childNodes[0].nodeValue;

Selecting Nodes list based on condition

Selecting Nodes list based on condition

xmlNodes= xmlDoc.selectNodes(“Node name Path [@attribute=’condition’]”) For ex: var xmlNodes = xmlDoc.selectNodes("//xNode[@xid='test']");

xmlNodes=xmlDoc.getElementsByTagName[“Node name Path”];For ex: var xmlNodes = xmlDoc.getElementsByTagName[“xNode”];

Iterating through the Nodes List and selecting value of a particular Attribute

Iterating through the Nodes List and selecting value of a particular Attribute

for(var n=0;  n< xmlNodes.length; n++){var xid= xmlNodes (n).getAttribute("xid");} xmlNodes contains only the Nodes which has the Attribute xid and which has value ‘test’. If the Attribute value = ‘test’, then we are iterating through that Nodes only and retrieving the value of xid.

Here xmlNodes  contains all the list of Nodes which are having the Node Name “xNode”. for(var n=0;  n< xmlNodes.length; n++){  // For getting all the Attributes of the Node selected var getXmlAttributes = xmlDoc.getElementsByTagName("Node name ")[n].attributes; // For selecting Attribute value based on condition, we should first get the Attributes List which contains the Attribute we need as below. var selectXmlAttribute = getXmlAttributes.getNamedItem("xid").value; // For retrieving the value of the Attribute based on Condition. if (selectXmlAttribute =="test") {   var xid= getXmlAttributes.getNamedItem("xid").value;}  

IE supports both () and [] braces while using document object

Firefox supports only [] braces while using document object.

Ex: document.forms(0); or document.forms[0];

Ex: or document.forms[0];

Use document.getElementById[“”] instead of document.all – Both are supported in IE  document.all is IE specific




In script tag never forget to mention type=”text/javascript”, as now a days all browsers implicitly know and support Java Script

For ex: <script language =”javascript” type = ”text/javascript”></script> 

Don’t close the script tag like <script language =”javascript” type = ”text/javascript”/> as some browsers like IE loads the first script, and then continues to look for a closing </script> tag.

Use:<script language =”javascript” type = ”text/javascript”></script> 



XSLT for Google Web Toolkit








Google Web Toolkit’s XML functionalities are limited. For example, there are no XPATH and XSLT libraries in the distribution. However, GWT allows call write native Javascript method in the java class. So it is possible to wrap existing Javascipt libraries in GWT.

Sarissa is an XSLT implementation in Javascript.

Here is an blog post that describes how to wrap Sarissa in Google Web Toolkit.