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 31-38 of 38 total

Let user add your search engine to their Firefox search bar

Built your own queryable search engine? Let FireFox users easily add it to their search box with this on an HTML page:

   1  <a href="javascript:window.sidebar.addSearchEngine('http://yoursrcfile.src','http://yourpngfile.png','Name','Type Of App');">Click here to add my search engine</a>


And you have to make those 'src' and PNG icon files too.. the 'src' file has a syntax like this:

   1  <search name="YourSite" description="" method="GET" 
   2  action="http://www.yoursite.whatever/search" 
   3  searchForm="url-to-your-actual-search-form" queryEncoding="UTF-8" 
   4  queryCharset="UTF-8">
   5  <input name="sourceid" value="FireFox-Search-Box">
   6  <input name="q (or whatever your preferred arg is)" user=""><inputprev>
   7  </search>
   8  
   9  <browser update="URL back to this SRC file" updateIcon="URL to your PNG" 
  10  updateCheckDays="30">


More info here.

Search and replace over file(s) with Perl

A quick bit of Perl can come in handy if you have an old site to update that has no CMS, or something similar.

To change 'source' to 'destination' in all HTML files in the current directory:

   1  perl -pi -e 's/source/destination/g' *.html


You could use this to update copyright notices, etc.. but bear in mind you need to stay with Perl/regex syntax, so escape those forward slashes, etc :)

Search box

// description of your code here

   1  
   2  <form action="/search" method="get"><input type="hidden" name="w" id="w" value="">
   3  <table border="0" bgcolor="#FFFFFF" style="position:absolute;top:50;left:50%;margin-left:-120px;" cellpadding="0" cellspacing="0"  style="border-collapse: collapse"><tr><td>
   4  <div id="bg" onmouseover="ov()" onmouseout="ot()">
   5  <div id="bx" onmouseover="ovfm()" onmouseout="otfm()"><table border="1" cellpadding="0" cellspacing="0" bordercolorlight="#000000" bordercolordark="#000000" style="border-collapse: collapse" bordercolor="#111111"><tr><td><table border="0" cellpadding="0" cellspacing="0"><tr><td valign="bottom">
   6    <img src="/img/search.jpg" onclick="sh();" width="23" height="18"></td><td><input type="text" id="q" size="20" name="q" class="q" autocomplete="off" onclick="fs()" onfocus="fs()" onkeydown="rst()" style="border: 0;color: #000000;" value=""></td></tr></table></td></tr></table></div>
   7  <div class="o" id="a1" style="visibility:hidden;" onmouseover="document.getElementById('a1').style.cursor='default'">
   8  
   9  <div nowrap="nowrap" class="i" id="c1" onclick="si();" onMouseOver="this.className='ih';" onMouseOut="this.className='i'">
  10  <span id="b1"><img width="10" height="13" src="/img/nodot.gif"></span>Artists similar to: </div>
  11  <div nowrap="nowrap" class="i" id="c2" onclick="na();" onMouseOver="this.className='ih'" onMouseOut="this.className='i'">
  12  <span id="b2"><img width="10" height="13"  src="/img/nodot.gif"></span>Artists named:</div>
  13  <div nowrap="nowrap" class="i" id="c3" onclick="zi();" onMouseOver="this.className='ih'" onMouseOut="this.className='i'">
  14  <span id="b3"><img width="10" height="13"  src="/img/nodot.gif"></span>Artists near zipcode: 
  15  </div>
  16  <div nowrap="nowrap" class="i" id="c4" onclick="ge();" onMouseOver="this.className='ih'" onMouseOut="this.className='i'">
  17  <span id="b4"><img width="10" height="13"  src="/img/nodot.gif"></span>Artists in genre: 
  18  </div>
  19  <div nowrap="nowrap" class="i" id="c6" onclick="ez();" onMouseOver="this.className='ih'" onMouseOut="this.className='i'">
  20  <span id="b6"><img width="10" height="13"  src="/img/nodot.gif"></span>Events near zipcode: 
  21  </div>
  22  <div nowrap="nowrap" class="i" id="c5" onclick="ws();" onMouseOver="this.className='ih'" onMouseOut="this.className='i'">
  23  <span id="b5"><img width="10" height="13"  src="/img/nodot.gif"></span>Search whole site: 
  24  
  25  </div>
  26  </div>
  27  </div>
  28  </td><td><input type="submit" style="background:#006486; padding:0px; margin:0px; color:#fff; font-weight:bold; border:1px solid #006486;" value="Search"></td></tr></table>
  29  </form>

Eliminating sites from searches

You can eliminate matches on queries based on the name of the site. For example, to search on all sites except 'experts-exchange.com', use the following hyphen-prefixed 'site' string:

   1  
   2  -site:experts-exchange.com "convert cstring to int "


Or you can only seach a specified site by removing the dash
   1  
   2  site:planetargon.com "rails hosting"


Tip by xinu

Quick search with Quicksilver and EasyFind

// A script to quickly search files and folders using Quicksilver and EasyFind.

   1  
   2  (*
   3  A script to quickly search files and folders using Quicksilver [1] and EasyFind [2].
   4  Written by Simon Dorfman, January 8, 2006. www.SimonDorfman.com
   5  
   6  Save this script to ~/Library/Application Support/Quicksilver/Actions/EasyFind.scpt
   7  You'll need to have "Enable access for assisstive devices" enabled under Universal Access in System Preferences.
   8  To use:
   9  	1. activate Quicksilver
  10  	2. type "." (i.e. hit the period key)
  11  	3. type the text you want to search for (i.e. httpd.conf)
  12  	4. press tab
  13  	5. start typing "EasyFind.scpt"
  14  	6. once Quicksilver finds "EasyFind.scpt", press return
  15  	
  16  [1] http://www.versiontracker.com/dyn/moreinfo/macosx/22549
  17  [2] http://www.versiontracker.com/dyn/moreinfo/macosx/11706
  18  *)
  19  
  20  using terms from application "Quicksilver"
  21  	on process text t
  22  		tell application "EasyFind" to activate
  23  		tell application "System Events"
  24  			tell process "EasyFind"
  25  				set value of text field 1 of window 1 to t --type text in search field
  26  				--uncomment your preferred search option, or save separate scripts with each option
  27  				click radio button 1 of radio group 1 of window 1 --"Files & Folders"
  28  				--click radio button 2 of radio group 1 of window 1 --"Only Files"
  29  				--click radio button 3 of radio group 1 of window 1 --"Only Folders"
  30  				--click radio button 4 of radio group 1 of window 1 --"File Contents"
  31  				click button 4 of window 1 --start search
  32  			end tell
  33  		end tell
  34  	end process text
  35  end using terms from

wsdl the google API (search google with ruby)

sign up to get a key first

   1  
   2  require 'soap/wsdlDriver'
   3  $KCODE = "UTF8"
   4  key = 'LVJnAm5QFHblahblahblah your key here'
   5  
   6  #create driver
   7  wsdl = "http://api.google.com/GoogleSearch.wsdl"
   8  driver = SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
   9  query = "your query string here"
  10  start = 0
  11  max = 10
  12    
  13  # see http://dev.ctor.org/soap4r/browser/trunk/sample/wsdl/googleSearch/wsdlDriver.rb
  14  @results = driver.doGoogleSearch( key, query, start, max, true, "", true, 'lang_en', '','')
  15  snippets = @results.resultElements.collect { |r| r.snippet } # you can get all kinds'a' info here
  16  self.update_attribute(:html, snippets.join("\n")) # or whatever

Gmail-Like Incremental Search //JavaScript Class


Implements a GMail-like auto-complete.

[UPDATED CODE AND HELP CAN BE FOUND HERE]


@REQUIRES Event-Listener

   1  
   2  //Requires http://www.jsfromhell.com/geral/event-listener
   3  
   4  //+ Jonas Raoni Soares Silva
   5  //@ http://jsfromhell.com/dhtml/incremental-search [v1.0]
   6  
   7  IncrementalSearch = function( input, callback, className ){
   8  	var i, o = ( o = this, o.l = [], o.i = input, o.c = null, o.s = { e: null, i: -1 }, o.f = callback || function(){}, o.n = className || "", o );
   9  	for( i in { keydown: 0, focus: 0, blur: 0, keyup: 0, keypress: 0 } )
  10  		addEventListener( o.i, i, function( e ){ o.handler.call( o, e ); } );
  11  };
  12  with( { p: IncrementalSearch.prototype } ){
  13  	(p.constructor.fadeAway = function( o ){
  14  		o instanceof Object ? ( this.trash = this.trash || [] ).push( o ) && setTimeout( this.fadeAway, 200 ) : arguments.callee.c.trash.pop().hide();
  15  	}).c = p.constructor;
  16  	p.callEvent = function( e ){ this[e] && this[e].apply( this, [].slice.call( arguments, 1 ) ); };
  17  	p.highlite = function( e ){ ( this.s.e && ( this.s.e.className = "normal" ), ( this.s = { e: e, i: e.listindex } ).e.className += " highlited", this.callEvent( "onhighlite", this.l[ this.s.i ], this.s.e.d ) ); };
  18  	p.select = function(){ this.s.i + 1 && ( this.i.value = this.l[ this.s.i ], this.callEvent( "onselect", this.i.value, this.s.e.d ), this.hide() ); };
  19  	p.hide = function(){ ( this.c && this.c.parentNode.removeChild( this.c ), this.c = null, this.l = [], this.s = { e: null, i: -1 }, this.callEvent( "onhide" ) ); };
  20  	p.next = function(){ var e = ( e = this.s.e ) ? e.nextSibling || e.parentNode.firstChild : null; e && this.highlite( e ); };
  21  	p.previous = function(){ var e = ( e = this.s.e ) ? e.previousSibling || e.parentNode.lastChild : null; e && this.highlite( e ); };
  22  	p.handler = function( evt ){
  23  		var o = this, t = evt.type, k = evt.key, e = /span/i.test( ( e = evt.target ).tagName ) ? e.parentNode : e;
  24  		t == "keyup" ? k != 40 && k != 38 && k != 13 && o.show()
  25  		: t == "keydown" ? ( k == 40 && o.next() ) || ( k == 38 && o.previous() )
  26  		: t == "keypress" ? k == 13 && !evt.preventDefault() && o.select()
  27  		: t == "blur" ? o.constructor.fadeAway( o )
  28  		: t == "click" ? o.select()
  29  		: t == "focus" ? o.show()
  30  		: o.highlite( e );
  31  	};
  32  	p.show = function(){
  33  		var cS, found = 0, o = this, i = o.i, iV = i.value, d = document, c = ( o.hide(), o.c = d.body.appendChild( d.createElement( "div" ) ) );
  34  		( c.className = o.n, cS = c.style, cS.display = "none", cS.position = "absolute", o.callEvent( "onshow" ) );
  35  		o.f.call( function( s, x, data ){
  36  			if( !( x.length == undefined ? ( x = [x] ) : x ).length )
  37  				return;
  38  			var j, l = 0, i = o.l.length, e = c.appendChild( d.createElement( "div" ) );
  39  			for( j in ( o.l[i] = s, e.className = "normal", e.d = data, e.listindex = i, !found && i == o.s.i && ++found && o.highlite( e ), x ) )
  40  				e.appendChild( d.createTextNode( s.substring( l, x[j] ) ) ).parentNode.appendChild( d.createElement( "span" ) ).appendChild( d.createTextNode( s.substring( x[j], l = x[j] + iV.length ) ) ).parentNode.className = "selectedText";
  41  			for( x in ( e.appendChild( d.createTextNode( s.substr( l ) ) ), { click: 0, mouseover: 0 } ) )
  42  				addEventListener( e, x, function( e ){ o.handler.call( o, e ); } );
  43  		}, iV );
  44  		if( !c.childNodes.length )
  45  			return o.hide();
  46  		for( var x = i.offsetLeft, y = i.offsetTop + i.offsetHeight; i = i.offsetParent; x += i.offsetLeft, y += i.offsetTop );
  47  		( cS.display = "block", cS.left = x + "px", cS.top = y + "px", !found && o.highlite( c.firstChild ) );
  48  	};
  49  }



Example

   1  
   2  <style type="text/css">
   3  /*container da lista*/
   4  .autocomplete{
   5  	cursor: pointer;
   6  	border: 1px solid #999;
   7  	border-top: none;
   8  	background: #eee;
   9  }
  10  /*caracteres que combinaram*/
  11  .autocomplete .selectedText{ font-weight: bold; color: #008; }
  12  /*items não selecionados*/
  13  .autocomplete .normal{ border-top: 1px solid #999; overflow: hidden; white-space: pre; }
  14  /*item selecionado*/
  15  .autocomplete .highlited{ background: #ddf; }
  16  </style>
  17  
  18  <form action="">
  19  	<fieldset>
  20  		<legend>Preenchimento dinâmico</legend>
  21  		<label for="list" >Emails</label>
  22  		<input autocomplete="0" type="text" name="list" id="list" />
  23  		<br />
  24  		<label for="ip" >Lista de IPs</label>
  25  		<textarea name="ip" rows="3" cols="20" id="ip"></textarea>
  26  		<br />
  27  	</fieldset>
  28  </form>
  29  
  30  <script type="text/javascript">
  31  //<![CDATA[
  32  
  33  var list = [ "192.168.0.1", "192.168.0.2", "192.168.0.3", "192.168.1.1", "192.168.1.2", "192.168.1.3", "200.168.0.1", "200.168.0.2", "200.168.0.3", "200.168.1.1", "200.168.1.2", "200.168.1.3" ];
  34  new IncrementalSearch( document.forms[0].ip, function( search ){
  35  	for( var i in list )
  36  		if( !list[i].indexOf( search ) )
  37  			this( list[i], 0 );
  38  }, "autocomplete" );
  39  
  40  
  41  var names = [ "João Alves <joao@123.com>", "Jonas Raoni Soares Silva <jonas@abc.com>", "Roberto <rob@net.net>", "Maria Fernanda <mariaf@i.tu>" ];
  42  
  43  function retrieveNames( search ){
  44  	search = search.toLowerCase();
  45  	for( var i in names ){
  46  		if( search ){
  47  			for( var j = 0, indices = []; j = names[i].toLowerCase().indexOf( search, j ) + 1; indices[indices.length] = j - 1 );
  48  			this( names[i], indices, i );
  49  		}
  50  		else
  51  			this( names[i], 0, i );
  52  
  53  	}
  54  }
  55  
  56  x = new IncrementalSearch( document.forms[0].list, retrieveNames, "autocomplete" );
  57  
  58  
  59  //]]>
  60  </script>


Adding text search to ActiveRecord classes

It's fairly easy, but I have no idea how (in)efficient it is.

Here's the important stuff.

In model:
   1  
   2  def self.search(terms)
   3    find_by_sql(["select t.* from table t where #{ (["(lower(t.text_field1) like ? or lower(t.text_field1) like ?)"] * tokens.size).join(" and ") } order by s.created_on desc", *(tokens * 2).sort])
   4  end


Basically it searches any of the fields you specify. If I wanted just one search, I'd drop out the second lower(t.text_field) and change the (tokens*2) to just tokens.

Like this:
   1  
   2  def self.search(terms)
   3    find_by_sql(["select t.* from table t where #{ (["(lower(t.text_field1) like ? )"] * tokens.size).join(" and ") } order by s.created_on desc", tokens])
   4  end


The terms array is just an array of single words, lowercase. They're prepared like this:

   1  
   2   terms = query.split.collect {|c| "%#{c.downcase}%"}


To use this in a controller, I just do this:
   1  
   2   @results = Model.search( @params['query'].split.collect{ |c| "%#{c.downcase}%" } )


Just like that.

From Rory on Rails

« Newer Snippets
Older Snippets »
Showing 31-38 of 38 total