you are here: codestackercodes [RSS]

yahoo! search boss sample

# first, install bossman

gem sources -a http://gems.github.com
gem install jpignata-bossman

# the sample

require 'rubygems'
require 'bossman'
include BOSSMan

BOSSMan.application_id = "Your Application ID here"

news = BOSSMan::Search.news("Mac OS", 0, 3)
news.results.each do |result|
  puts "#{result.title} [from #{result.source}]"
end

another css reset

source: http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-weight: inherit;
	font-style: inherit;
	font-size: 100%;
	font-family: inherit;
	vertical-align: baseline;
}
/* remember to define focus styles! */
:focus {
	outline: 0;
}
body {
	line-height: 1;
	color: black;
	background: white;
}
ol, ul {
	list-style: none;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
	border-collapse: separate;
	border-spacing: 0;
}
caption, th, td {
	text-align: left;
	font-weight: normal;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: "";
}
blockquote, q {
	quotes: "" "";
}

disable shadow in screen window captures

defaults write com.apple.screencapture disable-shadow -bool true
killall SystemUIServer

yahoo finance sample

require 'yahoo_finance'
data = YahooFinance.quotes(['petr4.sa'], [:ask, :last_trade_price, :last_trade_date])
puts data[0].symbol + " => " + data[0].ask

Cache em VB.Net

Conjunto de classes para encapsular as operações de inserção, atualização, remoção e busca no cache do Asp.Net, podendo ser adicionados novos gerenciadores de cache, como o Memcache, por exemplo.

Imports System.Web

''' ---------------------------------------------------
''' Interface para as classes de cache.
''' ---------------------------------------------------
Public Interface ICache

    Function GetObject(Of T)(ByVal key As String) As T

    Sub Insert(Of T)(ByVal key As String, ByVal value As T)

    Sub Insert(ByVal key As String, ByVal value As Object)

    Sub Update(Of T)(ByVal key As String, ByVal value As T)

    Sub Update(ByVal key As String, ByVal value As Object)

    Sub Remove(ByVal key As String)

    Sub RemoveAll()

End Interface


''' ---------------------------------------------------
''' AspNetCache - Encapsula as rotinas de cache do ASP.Net
''' ---------------------------------------------------
Public Class AspNetCache
    Implements ICache

    'Objeto System.Web.Caching.Cache
    Private _cache As System.Web.Caching.Cache

    Private dias As Integer

    'Número de dias que o objeto ficará no cache
    Public Property Expire() As Integer
        Get
            Return dias
        End Get
        Set(ByVal value As Integer)
            dias = value
        End Set
    End Property

    Protected Property Cache() As System.Web.Caching.Cache
        Get
            Return _cache
        End Get
        Set(ByVal value As System.Web.Caching.Cache)
            _cache = value
        End Set
    End Property

    'Retorna o número de objetos no cache
    Public ReadOnly Property Count() As Integer
        Get
            Return Me.Cache.Count
        End Get
    End Property

    'Construtor, obtém o gerenciador de cache do contexto web atual.
    Public Sub New()
        Me.Cache = HttpContext.Current.Cache
    End Sub

    'Retorna do cache o objeto do tipo T
    Public Function GetObject(Of T)(ByVal key As String) As T Implements ICache.GetObject
        Dim obj As T
        Try
            obj = DirectCast(Me.Cache(key), T)
        Catch ex As Exception
            Throw
        End Try
        Return obj
    End Function

    'Inserção com generics (tipada)
    Public Sub Insert(Of T)(ByVal key As String, ByVal value As T) Implements ICache.Insert
        Try
            Me.Cache.Insert(key, value, Nothing, Now.AddDays(Me.dias), Caching.Cache.NoSlidingExpiration)
        Catch ex As Exception
            Throw
        End Try
    End Sub

    'Inserção não tipada
    Public Sub Insert(ByVal key As String, ByVal value As Object) Implements ICache.Insert
        Try
            Me.Cache.Insert(key, value, Nothing, Now.AddDays(Me.dias), Caching.Cache.NoSlidingExpiration)
        Catch ex As Exception
            Throw
        End Try
    End Sub

    'Atualização - Remove o antigo e insere o objeto novo (tipada - generics)
    Public Sub Update(Of T)(ByVal key As String, ByVal value As T) Implements ICache.Update
        Try
            'Remove o objeto existente...
            Me.Remove(key)
            '... e insere a nova versão
            Me.Cache.Insert(key, value, Nothing, Now.AddDays(Me.dias), Caching.Cache.NoSlidingExpiration)
        Catch ex As Exception
            Throw
        End Try
    End Sub

    'Atualização - Remove o antigo e insere o objeto novo (não tipada)
    Public Sub Update(ByVal key As String, ByVal value As Object) Implements ICache.Update
        Try
            'Remove o objeto existente...
            Me.Remove(key)
            '... e insere a nova versão
            Me.Cache.Insert(key, value, Nothing, Now.AddDays(Me.dias), Caching.Cache.NoSlidingExpiration)
        Catch ex As Exception
            Throw
        End Try
    End Sub

    'Remove um objeto do cache
    Public Sub Remove(ByVal key As String) Implements ICache.Remove
        Try
            Me.Cache.Remove(key)
        Catch ex As Exception
            Throw
        End Try
    End Sub

    'Remove todos os objetos do cache
    Public Sub RemoveAll() Implements ICache.RemoveAll
        Try
            Dim iterator As IDictionaryEnumerator = Me.Cache.GetEnumerator
            While iterator.MoveNext
                Me.Remove(iterator.Key.ToString)
            End While
        Catch ex As Exception
            Throw
        End Try
    End Sub
End Class


''' ---------------------------------------------------
''' Factory que instancia o objeto de cache de acordo com o argumento passado.
''' ---------------------------------------------------
Public Class CacheFactory

    ''' Tipos de cache
    '''     AspNet: cache do Asp.Net (System.Web.Caching.Cache)
    '''        OBS: outros objetos encapsuladores de cache podem ser criados,
    '''        bastando para isso implementar a extensão ICache. Uma sugestão
    '''        seria criar uma classe para trabalhar com o Memcache usando a
    '''        biblioteca Enyim.Caching.MemcachedClient, disponível em 
    '''        http://www.codeplex.com/EnyimMemcached.
    Enum CacheType
        AspNet
    End Enum

    Public Shared Function GetCache(ByVal type As CacheType) As ICache
        Dim cache As ICache = Nothing
        Select Case type
            Case CacheType.AspNet
                cache = New AspNetCache()
            ' No caso de adicionar mais gerenciadores de cache, inserir 
            ' aqui o código de criação dos objetos.
        End Select
        Return cache
    End Function

End Class

passing extra parameters to prototype observer handlers

a simple listener: $('myForm').observe('submit', validateMyForm) dont support extra params in the function (in the case, validateMyForm. the solution:

$('myForm').observe('submit', function(event) {  
    validateMyForm(event, param1, param2);  
}); 

get/post puro Ruby

get e post em ruby puro

require 'net/http'
require 'net/https'

http = Net::HTTP.new('profil.wp.pl', 443)
http.use_ssl = true
path = '/login.html'

# GET request -> so the host can set his cookies

resp, data = http.get(path, nil)
cookie = resp.response['set-cookie']


# POST request -> logging in

data = 'serwis=wp.pl&url=profil.html&tryLogin=1&countTest=1&logowaniessl=1&login_username=blah&login_password=blah'
headers = {
  'Cookie' => cookie,
  'Referer' => 'http://profil.wp.pl/login.html',
  'Content-Type' => 'application/x-www-form-urlencoded'
}

resp, data = http.post(path, data, headers)


# Output on the screen -> we should get either a 302 redirect (after a successful login) or an error page

puts 'Code = ' + resp.code
puts 'Message = ' + resp.message
resp.each {|key, val| puts key + ' = ' + val}
puts data

Ruby daemon module

require 'fileutils'

module Daemon
  WorkingDirectory = File.expand_path(File.dirname(__FILE__))  

  class Base
    def self.pid_fn
      File.join(WorkingDirectory, "#{name}.pid")
    end
    
    def self.daemonize
      Controller.daemonize(self)
    end
  end
  
  module PidFile
    def self.store(daemon, pid)
      File.open(daemon.pid_fn, 'w') {|f| f << pid}
    end
    
    def self.recall(daemon)
      IO.read(daemon.pid_fn).to_i rescue nil
    end
  end
  
  module Controller
    def self.daemonize(daemon)
      case !ARGV.empty? && ARGV[0]
      when 'start'
        start(daemon)
      when 'stop'
        stop(daemon)
      when 'restart'
        stop(daemon)
        start(daemon)
      else
        puts "Invalid command. Please specify start, stop or restart."
        exit
      end
    end
    
    def self.start(daemon)
      fork do
        Process.setsid
        exit if fork
        PidFile.store(daemon, Process.pid)
        Dir.chdir WorkingDirectory
        File.umask 0000
        STDIN.reopen "/dev/null"
        STDOUT.reopen "/dev/null", "a"
        STDERR.reopen STDOUT
        trap("TERM") {daemon.stop; exit}
        daemon.start
      end
    end
  
    def self.stop(daemon)
      if !File.file?(daemon.pid_fn)
        puts "Pid file not found. Is the daemon started?"
        exit
      end
      pid = PidFile.recall(daemon)
      FileUtils.rm(daemon.pid_fn)
      pid && Process.kill("TERM", pid)
    end
  end
end

Drop all tables in a MySQL Database

run in shell:

echo DROP TABLE `echo 'SHOW TABLES;' | mysql -u USER -p DATABASE | tail -n +2 | sed -e 's/$/,/'` | sed -e 's/,$/;/'

Função para remover acentos em PostgreSQL

Funçãozinha em PostgreSQL para remover acentos. Útil para buscar resultados independente da acentuação.

CREATE OR REPLACE FUNCTION sem_acentos(character varying)
  RETURNS character varying AS
$BODY$
	SELECT TRANSLATE($1, 'áéíóúàèìòùãõâêîôôäëïöüçÁÉÍÓÚÀÈÌÒÙÃÕÂÊÎÔÛÄËÏÖÜÇ', 'aeiouaeiouaoaeiooaeioucAEIOUAEIOUAOAEIOOAEIOUC')
$BODY$
  LANGUAGE 'sql' VOLATILE;

another ie 6 hack

p {			
	background: green !important; /* Major browsers other than IE 6 and below respect the importance immediately */
	background: red; /* IE 6 and below use this value instead, even though the above was marked as important */
}

valid Flash example for XHTML 1.0 Strict (XHTML 1.1)

<object type="application/x-shockwave-flash" data="images/banner.swf" width="288" height="128">
<param name="movie" value="images/banner.swf" />
<img src="banner.gif" width="288" height="128" alt="banner" />
</object>

Add recent application menu to your dock

source: http://brunomiranda.com/past/2008/6/14/add_recent_application_menu_to/

defaults write com.apple.dock persistent-others -array-add '{ "tile-data"  = { "list-type" = 1; }; "tile-type" = "recents-tile"; }'
killall Dock

1kb ie 6 png fix hack

create a 1x1 'clear.gif' image

var clear="images/clear.gif" //path to clear.gif


pngfix=function(){var els=document.getElementsByTagName('*');var i_p=/\.png/i;var i=els.length;while (i-- >0){var el=els[i];var es=el.style;if(el.src&&el.src.match(i_p)&&es.filter==''){el.height = el.height;el.width = el.width;es.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.src+"',sizingMethod='crop')";el.src = clear;}else{var elb=el.currentStyle.backgroundImage;if(elb.match(i_p)){var path=elb.split('"');var rep=(el.currentStyle.backgroundRepeat=='no-repeat')?'crop':'scale';es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path[1]+"',sizingMethod='"+rep+"')";es.height=el.clientHeight+'px';es.backgroundImage="none";}}if (el.currentStyle.position!='absolute' && !es.filter && !el.tagName.match(/(body|html|script)/gi)) es.position="relative";if (es.filter&&el.currentStyle.position=="relative") es.position="static";}}
window.attachEvent('onload',pngfix);

another min-height hack

http://www.dustindiaz.com/min-height-fast-hack/

selector {
  min-height:500px;
  height:auto !important;
  height:500px;
}

safari single window mode

defaults write com.apple.Safari TargetedClicksCreateTabs -bool true

Password protecting your pages with htaccess

create a .htaccess file with this content.

the .htpasswd contains a user and encrypted password (e.g.: leo:4tHAiRmQ4OpjM). create a encrypted password in: http://www.kxs.net/support/htaccess_pw.html

AuthUserFile /home/leonardo/public_html/project/.htpasswd
AuthGroupFile /dev/null
AuthName "Restricted Access"
AuthType Basic
<limit GET>
require valid-user
</limit>

Array como objeto

Como criar um array usando ArrayObject e podendo acessar os valores como propriedade de um objeto

// acessando somente como array
$array = new ArrayObject(array('name' => 'Rafael Souza', 'username' => 'rafaelss'));
echo 'Nome: ', $array['name'], "\n";
echo 'Usuário: ', $array['username'], "\n";

// acessando como objeto
$array = new ArrayObject(array('name' => 'Rafael Souza', 'username' => 'rafaelss'), ArrayObject::ARRAY_AS_PROPS);
echo 'Nome: ', $array->name, "\n";
echo 'Usuário: ', $array->username, "\n";

// acessando de qualquer jeito
$array = new ArrayObject(array('name' => 'Rafael Souza', 'username' => 'rafaelss'), ArrayObject::ARRAY_AS_PROPS | ArrayObject::STD_PROP_LIST);
echo 'Nome: ', $array['name'], "\n";
echo 'Usuário: ', $array['username'], "\n";

echo 'Nome: ', $array->name, "\n";
echo 'Usuário: ', $array->username, "\n";

Exibe o número de arquivos em um diretório

ls -1 | wc -l

[funny] google pagerank code

function getPagerank(url) {
	// start off with a random low PR

	pagerank = randomNumber(0, 3);

	if ( pageHostedOn(url, 'google.com') ) {
		pagerank++;
	}
	else if ( pageHostedOn(url, 'microsoft.com') ) {
		pagerank–;
	}
	
	if ( pageValidates(url) ) {
		pagerank *= .5;
	}
	
	tag_value['b'] = 1;
	tag_value['h2'] = 2;
	tag_value['h1'] = 3;
	tag_value['strong'] = -1; // W3C sux!

	pagerank = calculateTagsPr(tag_value, pagerank);
	
	// Sergey said good news sites have

	// lots of nested tables

	tablesOnPage = getTagCount('table');
	if (tablesOnPage >= 50) {
		pagerank += 2;
	}
	if (pagerank >= 5) {
		pagerank = 4; // helps selling AdWords

	}
	if ( linksFrom('mattcutts.com', url) >= 4 ) {
		// I link to “clean” sites only

		// – Matt, Feb 2006

		pagerank += 2;
	}
	
	pagerank += countBacklinks(url) / 10000;
	blacklist1 = getList('government.cn/censored.txt');
	blacklist2 = getList('c:\larry-page-hatelist.txt');
	
	if ( inArray(blacklist1, url) || inArray(blacklist2, url) ) {
		pagerank = 0;
	}
	
	d = dashesInUrl(url);
	pagerank = (d >= 3) ? pagerank -1 : pagerank + 1;

	if ( inString(url, “how to build a bomb”) ) {
		// added on request. 2004-12-01.

		recipient = “peter@homelandsecurity.gov”;
		subject = “You might wanna check this…”;
		sendMailTo(recipient, subject, url);
		// page might still be relevant

		pagerank++;
	}

	if ( month() == "June" || month() == "October" ) {
		// makes people talk about

		// PR updates, good publicity

		pagerank -= randomNumber(1,3);
	} 

	if ( linkCol(url) == WHITE &&
		pageCol(url) == WHITE ) {
		// spammer!! Googleaxe it!!

		pagerank = 0;
	}

	if (url == “http://www.nytimes.com”) {

		// just testing, pls remove tomorrow

		// – Frank, June 2003

		pagerank = 10;
	}
	return pagerank;
}
Displaying Code 261 - 280 of 301 in total