Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

« Newer Snippets
Older Snippets »
7 total  XML / RSS feed 

UTF8 encode/decode helper library

var $utf8 = {  
      
    encode : function (string) {  
        string = string.replace(/\r\n/g,"\n");  
        var utftext = "";  
  
        for (var n=0, k=string.length; n < k; n++) {  
            var c = string.charCodeAt(n);  
  
            if (c < 128) {  
                utftext += String.fromCharCode(c);  
            }  
            else if((c > 127) && (c < 2048)) {  
                utftext += String.fromCharCode((c >> 6) | 192);  
                utftext += String.fromCharCode((c & 63) | 128);  
            }  
            else {  
                utftext += String.fromCharCode((c >> 12) | 224);  
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);  
                utftext += String.fromCharCode((c & 63) | 128);  
            }  
        }  
        return utftext;  
    },  
  
    decode : function (utftext) {  
        var string = "";  
        var i = 0;  
        var c = c1 = c2 = 0;  
  
        while ( i < utftext.length ) {  
            c = utftext.charCodeAt(i);  
            if (c < 128) {  
                string += String.fromCharCode(c);  
                i++;  
            }  
            else if((c > 191) && (c < 224)) {  
                c2 = utftext.charCodeAt(i+1);  
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));  
                i += 2;  
            }  
            else {  
                c2 = utftext.charCodeAt(i+1);  
                c3 = utftext.charCodeAt(i+2);  
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));  
                i += 3;  
            }  
  
        }  
        return string;  
    }  
}

Facebook Status Updater using cURL

<?PHP
/*******************************
*       Facebook Status Updater
*       Christian Flickinger
*       http://nexdot.net/blog
*    April 20, 2007
*******************************/

$status = 'YOUR_STATUS';
$first_name = 'YOUR_FIRST_NAME';
$login_email = 'YOUR_LOGIN_EMAIL';
$login_pass = 'YOUR_PASSWORD';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://login.facebook.com/login.php?m&amp;next=http%3A%2F%2Fm.facebook.com%2Fhome.php');
curl_setopt($ch, CURLOPT_POSTFIELDS,'email='.urlencode($login_email).'&pass='.urlencode($login_pass).'&login=Login');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_exec($ch);

curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php');
$page = curl_exec($ch);

curl_setopt($ch, CURLOPT_POST, 1);
preg_match('/name="post_form_id" value="(.*)" \/>'.ucfirst($first_name).'/', $page, $form_id);
curl_setopt($ch, CURLOPT_POSTFIELDS,'post_form_id='.$form_id[1].'&status='.urlencode($status).'&update=Update');
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php');
curl_exec($ch);
?>

Opening window/tab helper library for Mozilla

var $window = {
        open_in_new_tab: function(url){
                getBrowser().selectedTab = getBrowser().addTab(url);
        },

        open_in_same_tab: function(url){
                top.content.document.location = url;
        },

        open_as_popup: function(url){
                var mypopup = window.open(url,'popuppage','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=700,height=400,left=30,top=30');
                mypopup.focus();
        },

        focus: function(obj){
                obj.focus();
        },

        click : function(aEvent,url){
                if (aEvent.button == 2){
                        this.open_as_popup(url);
                }
                else if ((aEvent.ctrlKey) || (aEvent.button == 1) || (aEvent.metaKey)){
                        this.open_in_new_tab(url);
                } 
                else {
                        this.open_in_same_tab(url);
                        this.focus(window._content);
                        
                }
        }
}

Usage:
<toolbarbutton id="myid" label="my button"  class="toolbarbutton-1" onclick="$window.click(event,'http://localhost/');" />

Dynamically adding XUL elements

var mylib = {
       appendXulEl : function(parentId,nodeName,attribs){
                var elem = document.getElementById(parentId);
                var node = document.createElement(nodeName);
                for (attrib in attribs) {
                        node.setAttribute(attrib, attribs[attrib]);
                }            
                elem.appendChild(node);
        }
}


Usage:
mylib.appendXulEl('BrowserToolbarPalette', 'toolbarbutton', {'id':'MY_BUTTON_ID', 'label':'label for my button', 'tooltiptext':'button tooltip', 'class':'toolbarbutton-1', 'onclick':'alert("test")', 'context':''})

Mozilla Preferences helper library


var $Prefs = {
        _getBranch : Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch),
        _getService : Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService),
                
        set : function(pref_name, pref_value) {
                var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
                str.data = pref_value.replace(/^\s*|\s*$/g,'');
                (this._getBranch).setComplexValue(pref_name, Components.interfaces.nsISupportsString, str);
        },
        
        get : function(pref_name){
                try{
                        return (this._getBranch).getComplexValue(pref_name,Components.interfaces.nsISupportsString).data;
                }
                catch(e){ return false;}
        },

        remove : function(pref_name){
                try{
                        (this._getBranch).clearUserPref(pref_name)
                }
                catch(e){}
        },
                
        remove_all : function(pref_name){
                try{
                        (this._getBranch).deleteBranch(pref_name,'')
                }
                catch(e){}
        },
                        
        branch : function(pref_name){
                var serialBranch = (this._getService).getBranch(pref_name+'.');
                return serialBranch.getChildList("",{});
        }
}

Nice Date

 sub nice_date {   
                (my $date) = @_;   
                ($sec, $min, $hr, $day, $month, $year, $day_Of_Week, $julianDate, $dst) = localtime($date); 
                $month+=1; $year+=1900;   
                ($sec2, $min2, $hr2, $day2, $month2, $year2, $day_Of_Week2, $julianDate2, $dst2) = localtime();
                $month2+=1; $year2+=1900;
                if($julianDate2==$julianDate and $year==$year2) {   
                        if($hr==$hr2) {print "a few moments ago";}   
                        elsif(($hr2-$hr)==1) {print "an hour ago";}   
                        elsif(($hr2-$hr)==2) {print "two hours ago}";}   
                        elsif(($hr2-$hr)==3) {print "three hours ago";}   
                        else {print "today";}   
                }
                elsif($julianDate2==($julianDate+1) and $year==$year2) {print "yesterday";} 
                elsif(($julianDate2-$julianDate)<=2 and $year==$year2) {print "two days ago";}
                elsif(($julianDate2-$julianDate)<=5 and $year==$year2) {print "this week";}   
                else {print "$month/$day/$year";}  
        }

Sqlite helper library for Mozilla

var $sqlite = {
        storageService: [],
        mDBConn: [],
        
        _initService : function(file){
                var db = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile);
                db.append(file);
                this.storageService[file] = Components.classes["@mozilla.org/storage/service;1"].getService(Components.interfaces.mozIStorageService);
                this.mDBConn[file] = (this.storageService[file]).openDatabase(db);
                        
        },
        
        select : function(file,sql,param){
                if (this.storageService[file]== undefined){
                    this._initService(file);
                }
                var ourTransaction = false;
                if ((this.mDBConn[file]).transactionInProgress){
                        ourTransaction = true;
                        (this.mDBConn[file]).beginTransactionAs((this.mDBConn[file]).TRANSACTION_DEFERRED);
                }
                var statement = (this.mDBConn[file]).createStatement(sql);
                if (param){
                        for (var m=2, arg=null; arg=arguments[m]; m++) {
                                statement.bindUTF8StringParameter(m-2, arg);
                        }
                }
                try{
                        var dataset = [];
                        while (statement.executeStep()){
                                var row = [];
                                for(var i=0,k=statement.columnCount; i<k; i++){
                                        row[statement.getColumnName(i)] = statement.getUTF8String(i);
                                }
                                dataset.push(row);
                        }
                        // return dataset;  
                }
                finally {
                        statement.reset();
                }
                if (ourTransaction){
                        (this.mDBConn[file]).commitTransaction();
                }
        return dataset;      
        },
        
        
        cmd : function(file,sql,param){
                if (this.storageService[file] == undefined){
                            this._initService(file);
                }
                var ourTransaction = false;
                if ((this.mDBConn[file]).transactionInProgress){
                        ourTransaction = true;
                        (this.mDBConn[file]).beginTransactionAs((this.mDBConn[file]).TRANSACTION_DEFERRED);
                }
                var statement = (this.mDBConn[file]).createStatement(sql);
                if (param){
                        for (var m=2, arg=null; arg=arguments[m]; m++) {
                                statement.bindUTF8StringParameter(m-2, arg);
                        }
                }
                try{
                        statement.execute();
                }
                finally {
                        statement.reset();
                }
                if (ourTransaction){
                        (this.mDBConn[file]).commitTransaction();
                }
        }    

}

Usage:
<script language="javascript">
//some variables :
//assuming db file is in user's profile directory:
var myDBFile = 'mydb.sqlite';

// some example SQL queries:
var myCreateDBQuery = 'CREATE TABLE IF NOT EXISTS mybooks_tbl (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);';

var myInsertQuery = 'INSERT INTO mybooks_tbl(title) VALUES("book title1");';
var myInsertQueryParameterized = 'INSERT INTO mybooks_tbl(title) VALUES(?1);';

var mySelectQuery = 'SELECT id,title FROM mybooks_tbl';
var mySelectQueryParameterized = 'SELECT id,title FROM mybooks_tbl WHERE id = ?1 AND title = ?2';



// For anything other than SELECT statement, use $sqlite.cmd() :
 
// creating a DB:
function test_createDB(){
        $sqlite.cmd(myDBFile,myCreateDBQuery);
}

// simple add record:
function test_addRecord(){
        $sqlite.cmd(myDBFile,myInsertQuery);
}

// parameterized add record, add parameters as much as you want:        
function test_addRecordParameterized(){
        // for example, adding 3 records:
        for(var i = 1 ; i < 4; i++){
                $sqlite.cmd(myDBFile,myInsertQueryParameterized,'book title'+i+'');
        }
}

// for SELECT, use $sqlite.select() :

// simple select:
function test_Select(){
        var myArray1 = $sqlite.select(myDBFile,mySelectQuery);
        // Now you can loop through the array:
        for(var j=0;j'title']);
        }
}

// select with bound parameters, add parameters as much as you want:
function test_SelectParameterized(){
        var myArray1 = $sqlite.select(myDBFile,mySelectQueryParameterized,'1','book title1');
        // Now you can loop through the array:
        for(var j=0;j'title']);
        }
}

Create DB | 
Simple Add Record | 
Parameterized Add Record | 
Simple Select | 
Parameterized Select |
« Newer Snippets
Older Snippets »
7 total  XML / RSS feed