Never been to DZone Snippets 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

« Newer Snippets
Older Snippets »
Showing 1-10 of 24 total  RSS 

You have a nil object when you didn't expect it!

As seen on my webpage: http://freezzo.com

<%= @object.association.variable rescue nil %>

Excel object

// Excel object
// 'create object
Set excelobj = CreateObject( "Excel.Application")
Set exp_data_workbook=excelobj.workbooks.open("c:\debug_expected.xls")


'get the sheet count
exp_sheetcnt=exp_data_workbook.Sheets.Count
	

'select a sheet
For i = 1 to exp_sheetcnt
	sheet_tblname=exp_data_workbook.Sheets(i).Name
	If  UCASE(Trim(sheet_tblname)) = "Sheet_name" Then
		exp_data_workbook.Sheets(i).select

		'once selected set the range object	
		set exp_rangeobj=exp_data_workbook.Sheets(i).UsedRange
	end if
next


'Get the column count for the 

columncnt=exp_rangeobj.columns.count

'find  the column index of  the column column_name
		For i=1 to columncnt
			colname=exp_rangeobj.cells(1,i).value
			If UCASE(Trim(colname)) = "column_name" Then
				pos_id_idx = i
				Exit For
			End If
		Next		

'proceess the value from that column

rowcnt=exp_rangeobj.rows.count

		'Strat reading the values from the 2nd row since the first row contains the column names.
		If rowcnt > 1 Then
			For i=2 to rowcnt				 
				'process the expected file row if it has a value
				If  Len(Trim(exp_rangeobj.cells(i,1).value))>0 Then 
					posIndex = (exp_rangeobj.cells(i,pos_id_idx).value) -1
				end if
			next 
		end if
		

Wrap all methods of an object

Given an existing object "obj", wraps all of its methods. In this case, the wrapper prints a log of the method invocation, and the call stack of the call, but you can modify it to do anything...

virtual_class = class <<obj; self; end

virtual_class.class_eval {
  obj.methods.each { |method|
    the_alias = method.gsub(/([^?]+)(\??)/, "\\1_orig\\2").to_sym
    alias_method the_alias, method

    define_method(method) { |*args|
        args_str = args.map { |a| a.inspect }.join(", ")
        unless method == "to_s"
          puts "#{self.inspect_orig}.#{method}(#{args_str}) called from #{caller.inspect}"
        end
        self.send_orig(the_alias, *args)
    }
  }
}

Object alternative to iframe for XHTML 1.0 strict

<object data="mypage.php" type="text/html"></object>

Javascript Ajax Object

// Just a stub function we'll tell ajaxObject to call when it's done
// callback functions get responseText, and responseStat respectively
// in their arguments.
function fin(responseTxt,responseStat) {
  alert(responseStat+' - '+responseTxt);
}

// create a new ajaxObject, give it a url it will be calling and
// tell it to call the function "fin" when its got data back from the server.
var test1 = new ajaxObject('http://someurl.com/server.cgi',fin);
    test1.update();
		
// create a new ajaxObject, give it a url and tell it to call fin when it
// gets data back from the server.  When we initiate the ajax call we'll
// be passing 'id=user4379' to the server.		
var test2 = new ajaxObject('http://someurl.com/program.php',fin);
    test2.update('id=user4379');
		
// create a new ajaxObject but we'll overwrite the callback function inside
// the object to more tightly bind the object with the response hanlder.
var test3 = new ajaxObject('http://someurl.com/prog.py', fin);
    test3.callback = function (responseTxt, responseStat) {
      // we'll do something to process the data here.
      document.getElementById('someDiv').innerHTML=responseTxt;
    }
    test3.update('coolData=47&userId=user49&log=true');	
		
// create a new ajaxObject and pass the data to the server (in update) as
// a POST method instead of a GET method.
var test4 = new ajaxObject('http://someurl.com/postit.cgi', fin);
    test4.update('coolData=47&userId=user49&log=true','POST');	


function ajaxObject(url, callbackFunction) {
  var that=this;      
  this.updating = false;
  this.abort = function() {
    if (that.updating) {
      that.updating=false;
      that.AJAX.abort();
      that.AJAX=null;
    }
  }
  this.update = function(passData,postMethod) { 
    if (that.updating) { return false; }
    that.AJAX = null;                          
    if (window.XMLHttpRequest) {              
      that.AJAX=new XMLHttpRequest();              
    } else {                                  
      that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
    }                                             
    if (that.AJAX==null) {                             
      return false;                               
    } else {
      that.AJAX.onreadystatechange = function() {  
        if (that.AJAX.readyState==4) {             
          that.updating=false;                
          that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML);        
          that.AJAX=null;                                         
        }                                                      
      }                                                        
      that.updating = new Date();                              
      if (/post/i.test(postMethod)) {
        var uri=urlCall+'?'+that.updating.getTime();
        that.AJAX.open("POST", uri, true);
        that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        that.AJAX.send(passData);
      } else {
        var uri=urlCall+'?'+passData+'&timestamp='+(that.updating.getTime()); 
        that.AJAX.open("GET", uri, true);                             
        that.AJAX.send(null);                                         
      }              
      return true;                                             
    }                                                                           
  }
  var urlCall = url;        
  this.callback = callbackFunction || function () { };
}

Prototype-based Ruby


# From: http://programming.reddit.com/info/ob4m/comments/cobr4
# Author: Brian Mitchell
# cf. http://t-a-w.blogspot.com/2006/10/prototype-based-ruby.html

Proto = Class.new(Class)    # Beware: magic.
def Proto.clone
  Class.new(self)
end

# Demo
a = Proto.clone
def a.f
  puts 42
end
a.f                     #=> 42

b = a.clone
b.f                     #=> 42
def b.f
  puts 43
end
a.f                      #=> 42
b.f                      #=> 43

def a.g
  "Hello differential inheritance"
end

bool_val = (a.g == b.g)
p bool_val                #=> true



# From: http://www.ruby-forum.com/topic/94696
# cf. http://tech.rufy.com/2006/06/classes-are-just-prototype-pattern.html

AnimalSounds = Module.new

AnimalSounds.class_eval %q!
def createSound(attr_name)
class_eval <<-EOS
   #def self.#{attr_name};  puts "class method '#{attr_name}' called"; end 
   def self.#{attr_name}(arg = nil) 
      str = "class method '#{attr_name}' of class #{self.inspect} called"
      arg ? (puts str + " with " + arg.to_s) : (puts str)
   end
EOS
end!


puts
p AnimalSounds
p AnimalSounds.class
p AnimalSounds.class.superclass
p AnimalSounds.class.ancestors
p AnimalSounds.singleton_methods
puts


Pet = Object.clone.extend(AnimalSounds)    
Pet.createSound("meow")                    # create a class method
Pet.meow                                   
Pet.meow("argument")      

p Pet
p Pet.class
p Pet.class.superclass
p Pet.class.ancestors
p Pet.singleton_methods
puts


fido = Pet.clone           
fido.meow           
fido.meow("argument")
fido.createSound("woof")    
fido.woof
fido.woof("argument")
puts


fido2 = fido.clone                        
fido2.woof
fido2.woof("argument")
fido2.createSound("woof2")                 
fido2.woof2
fido2.woof2("argument")

puts
p Pet.singleton_methods
p fido.singleton_methods
p fido2.singleton_methods
puts


SINGLE-LINE-MOLD

	single-line-mold: func [
	    "Reformats a block or object-spec to a single line."
	    val [any-block! object!]
	] [
	    val: copy either any-block? val [val] [third val]
	    replace/all mold new-line/all val  off  "^/" "^^/"
	]

longest-field-name - Return the longest word in the object, as a string

longest-field-name: func [
    "Return the longest word in the object, as a string."
    obj [object!]
][
    last sort-by-length change-all remove first obj :form
]

words-like - Returns a block of words in the object that match the given pattern.

words-like: func [
    "Returns a block of words in the object that match the given pattern."
    object  [object!]
    pattern [word! any-string!]
    ;??? Add an /unbound refinement
][
    pattern: join form pattern "*"
    collect w [
        foreach word next first object [
            if find/match/any form word pattern [w: bind word in object 'self]
        ]
    ]
]

save Data with db4o

// save Data with db4o

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Query;
...

public class DbUtil {

  /**
  * save someObject to DB
  */
  public static void saveData(SomeClass someObject, String DbFilename) {
    ObjectContainer db=Db4o.openFile(DbFilename);
    try {
      db.set(idGenerator);
    }
    finally {
      db.close();
    }
  } //saveData(SomeClass ..)

  ..

} //DbUtil
« Newer Snippets
Older Snippets »
Showing 1-10 of 24 total  RSS