my blog is abt wht i have learnt technically, mostly in Ruby on Rails, Javascript, node.js hope this share a little bit of info & adds a bit stuff., Thanks.
Wednesday, December 23, 2009
undefined method `relative_url_root' error
To clear the error ,make the followning change,
changed line no. 51 in asset_packager/lib/synthesis/asset_packager_helper.rb
err line: source = "#{ActionController::Base.asset_host}#{@controller.request.relative_url_root}#{source}"
changed_to :
source = "#{ActionController::Base.asset_host}#{ActionController::Base.relative_url_root}#{source}"
Github get Public Key, set user name
ssh-keygen -t rsa
Set Username:
git config --global user.name "srikanth"
git config --global user.email "sri.jjhero@gmail.com"
Friday, November 27, 2009
Multiple Language implementation Using Google Translate
Just surfed through how to implement a multiple language App, & got this from google Translate..
Just add this code in your HTML Layout.
<div id="google_translate_element"></div><script>
function googleTranslateElementInit() {
new google.translate.TranslateElement({
pageLanguage: 'en'
}, 'google_translate_element');
}
</script><script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
PTS:
This works only inside the app, & not in a HTML file.
Source : http://translate.google.com/translate_tools?hl=en
Thanks,
Srikanth
Thursday, November 26, 2009
Multiple Select boxes in Js
& what worked for me is i have given below,
http://www.box.net/shared/9lo1g8p3ei
Download the Js & Css from the above link.
Create a HTML file like this,
<script src="javascripts/moo.js" type="text/javascript"></script>
<script src="javascripts/multi_transfer.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="stylesheets/multiple.css" />
<table>
<tr>
<td align="center">
<div class="holder" > <p>Exam List</p>
<select multiple="multiple" id="select1" name="select1[]">
<option value="1">one1</option>
<option value="2">one2</option>
<option value="3">one3</option>
<option value="4">one4</option>
<option value="5">one5</option>
</select>
<a href="javascript:;" id="add">add >></a>
</div>
</td>
<td align="center">
<div class="holder"><p>Selected Exam </p>
<select multiple="multiple" id="select2" name="selected_exam_list[]">
</select>
<a href="javascript:;" id="remove"><< remove</a>
</div>
</td>
</tr>
</table>
Reference & Demo : http://davidwalsh.name/dw-content/multi-select.php
Thanks,
Srikanth
Add Favicon in a webpage
<link rel="SHORTCUT ICON" href="/images/favicon.ico" type="image/x-icon"></span>
Thanks,
Srikanth
Tuesday, November 17, 2009
Adding GEM sources
sudo gem sources -a http://gems.rubyonrails.org/
Action Web Service Gem
Version 2.3.2 for actionwebservice is " datanoise-actionwebservice"
For installing the gem when i used,
gem install datanoise-actionwebservice
got this error,
ERROR: could not find gem datanoise-actionwebservice locally or in a repository
& found this is the right way to install
gem install datanoise-actionwebservice --source http://gems.github.com
Add this line to your config/environment.rb
file in the initializer section:
config.gem 'datanoise-actionwebservice', :lib => 'actionwebservice'
Generating API controller
ActionWebService gem includes web_service
generator that you can use like this:
$ ./script/generate web_service post
Define your API
Open app/services/post_api.rb
file and add methods that your service exposes:
class PostApi < returns =""> [[:string]]
end
API implementation
We are going to use direct dispatching mode, so all methods that implement our API go directly to PostController
itself:
class PostController < ApplicationController
wsdl_service_name 'Post'
web_service_api PostApi
web_service_scaffold :invocation if Rails.env == 'development'
def get_posts
["Post 1", "Post 2"]
end
end
wsdl url:
http://localhost:3000/post/wsdl
Books : Restful Web Services | Web Services Essentials (O'Reilly XML) | Web Services: Principles and Technology | RESTful Web Services Cookbook
Tuesday, November 10, 2009
Getting Next Existing Record in a DB
Wondered how to do it,, & did it Using offset:
sql:
SELECT * FROM foo WHERE id = 4 OFFSET 1
Thursday, September 24, 2009
Table Sorting Jquery Plugin
I was wondering how to sort a table. I got this plugin & did it in 10 mins.
Here is an useful plugin in jquery,
Reference URL : http://tablesorter.com/docs/#Download
Table sorting is pretty much easier using this tablesorter plugin.
Thanks,
Srikanth
Monday, September 14, 2009
MySQL Change root Password
mysqladmin command to change root password
If you have never set a root password for MySQL, the server does not require a password at all for connecting as root. To setup root password for first time, use mysqladmin command at shell prompt as follows:
$ mysqladmin -u root password NEWPASSWORD
However, if you want to change (or update) a root password, then you need to use following command
$ mysqladmin -u root -p'oldpassword' password newpass
For example, If old password is abc, and set new password to 123456, enter:
$ mysqladmin -u root -p'abc' password '123456'
Change MySQL password for other user
To change a normal user password you need to type (let us assume you would like to change password for vivek):
$ mysqladmin -u vivek -p oldpassword password newpass
Changing MySQL root user password using MySQL sql command
This is another method. MySQL stores username and passwords in user table inside MySQL database. You can directly update password using the following method to update or change password for user vivek:
1) Login to mysql server, type following command at shell prompt:
$ mysql -u root -p
2) Use mysql database (type command at mysql> prompt):
mysql> use mysql;
3) Change password for user vivek:
mysql> update user set password=PASSWORD("NEWPASSWORD") where User='vivek';
4) Reload privileges:
mysql> flush privileges;Thanks,
mysql> quit
Recover Mysql Password
http://www.cyberciti.biz/tips/recover-mysql-root-password.html
Srikanth
Sunday, September 6, 2009
Polymorphic Association
Reference : http://charlesmaxwood.com/ruby-on-rails-restful-links-when-you-dont-know-the-class/
Example :
restful routes:
map.resources :users
map.resources :groups
Model Relation:
class Post < ActiveRecord::Base
belongs_to :owner, :polymorphic => true
end
class User < ActiveRecord::Base
has_many :posts, :as => :owner
end
class Group
has_many :posts, :as => :owner
end
Now, let’s say that when you show a post, you want to provide a link to the owner of the post when you display it on its show page. You know that because you’ve provided the restful routes in your config/routes.rb file as show above, you get the nice functionality of the user_path and the group_path methods. The problem is that because you don’t know if @post.owner is a user or a group.
<%= link_to @post.owner.name, polymorphic_path(@post.owner) %>
Documentation : http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M000261&name=polymorphic_path
Thanks,
Srikanth
Monday, August 17, 2009
string conversions
>>> print "Before %s After" % 7
Before 7 After
>>> print "Before %x After" % 15
Before f After
>>> print "Foo %04d Bar" % 3*3
Foo 0009 Bar
Sunday, August 16, 2009
jquery show, hide
current version of jquery can be downloaded here.
Friday, July 24, 2009
base 64 enocde/decode
puts Base64.decode64("aG1hYw==").chomp => hmac
puts Base64.encode64("hmac").chomp => aG1hYw==
Thursday, July 9, 2009
Check Whether a test Credit Card is working.,
require 'active_merchant'
# Use the TrustCommerce test servers
ActiveMerchant::Billing::Base.mode = :test
# ActiveMerchant accepts all amounts as Integer values in cents
# $10.00
amount = 1000
# The card verification value is also known as CVV2, CVC2, or CID
credit_card = ActiveMerchant::Billing::CreditCard.new(
:first_name => 'Bob',
:last_name => 'Bobsen',
:number => '349298720353895',
:month => '8',
:year => '2012',
:verification_value => '1234'
)
puts credit_card.valid?
Wednesday, July 1, 2009
Getting Local ip Address
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
p= local_ip
puts p
Friday, June 19, 2009
Get month names for the integer
=> "January"
some other date methods:
Date::ABBR_DAYNAMES
Date::ABBR_MONTHNAMES
Date::DAYNAMES
Thanks,
sri..
Thursday, June 18, 2009
Adding data in add column
Adding data in add column
class AddPeopleSalary < ActiveRecord::Migration
def self.up
add_column :people, :salary, :integer
Person.reset_column_information
Person.find(:all).each do |p|
p.update_attribute :salary, SalaryCalculator.compute(p)
end
end
end
Tuesday, June 9, 2009
Amazon simple Payment in ruby on rails
Amazon is Doing a great job in rails Payments.
here is the ruby code for generation of button.
require 'base64'
require 'openssl'
module PayNowWidgetUtils
def generate_signed_form(access_key, aws_secret_key, form_params)
form_params['accessKey'] = access_key
str_to_sign = ""
form_params.keys.sort.each { |k| str_to_sign += "#{k}#{form_params[k]}" }
digest = OpenSSL::Digest::Digest.new('sha1')
hmac = OpenSSL::HMAC.digest(digest, aws_secret_key, str_to_sign)
form_params['signature'] = Base64.encode64(hmac).chomp
signed_form =<<-STARTFORM
ENDFORM
return signed_form
end
end
include PayNowWidgetUtils
ACCESS_KEY = 'your amazon aws access key'
SECRET_KEY = 'your amazon aws secret key'
print generate_signed_form(ACCESS_KEY, SECRET_KEY,
'amount' => 'USD 100',
'description' => 'Test Button',
'referenceId' => 'txn1102',
'returnUrl' => 'http://localhost:3000/success',
'abandonUrl' => 'http://localhost:3000/fail')
amazon aws signup..
http://aws.amazon.com/
use a sandbox account for doing test case.
Tuesday, May 26, 2009
Get the list of sundays in a month
class Date
def self.last_day_of_the_month yyyy, mm
d = new yyyy, mm
d += 42 # warp into the next month
new(d.year, d.month) - 1 # back off one day from first of that month
end
def self.print_sundays(d1, d2)
d1 +=1 while (d1.wday != 0)
d1.step(d2, 7) do |date|
puts "#{Date::MONTHNAMES[date.mon]} #{date.day}"
end
end
end
date = Date.today
month = date.strftime("%m").to_i
year = date.strftime("%Y").to_i
last_date = Date.last_day_of_the_month(year, month)
l_date = last_date.strftime("%d").to_i
Date.print_sundays(Date::civil(year, month, 1), Date::civil(year, month, l_date))
Wednesday, May 20, 2009
Jump to the top of a page
http://www.dynamicdrive.com/dynamicindex5/jumptop.htm
this will help in making a top link in each page.
Monday, May 18, 2009
Connecting Db in ruby
@@dbh = Mysql.real_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB_NAME)
Sunday, May 17, 2009
check whether an url is working or not..
1. For domains: ping "domain name"
2. For urls, use the following..
def check_valid_link(link_url)
retrycount = 0
begin
res = Net::HTTP.get_response(URI.parse(link_url))
if res.code =~ /2|3\d{2}/
return true
else
return false
end
rescue Timeout::Error
if retrycount < 4
retrycount += 1
sleep 3
retry
else
return false
end
rescue
return false
end
end
Friday, April 3, 2009
image science requirement
.ruby_inline/Inline_ImageScience_aa58.c:2:23: error: FreeImage.h: No such file or directory
getting such an error??
just install freeimage,
http://www.urbanpuddle.com/articles/2008/01/22/install-freeimage-imagescience-on-ubuntu-gutsy#comments
the above link will guide u in installing..
thanks,
Tuesday, March 10, 2009
E- Books..
I have more than 200 E-Books, in all Programming languages.
If any one need it, mail me in sri.jjhero@gmail.com
Tuesday, March 3, 2009
calling JS from form in rails
Sunday, March 1, 2009
CSV
any work under csv??
here s something interesting which makes ur csv work easier.
http://fastercsv.rubyforge.org/
Thanks.
Tuesday, February 24, 2009
concat multiple arrays
joining multiple arrays is easy using "+"
we can do that using a single method as follows,
class Array
def concat_multi *lists
lists.each {|list| self.concat(list) }
end
end
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
d = [10, 11]
a.concat_multi(b, c, d)
p a
Thursday, February 19, 2009
Convert a String into Time
=> true
require'time'
=> true
a="Thu Feb 19 18:16:33 +0530 2009"
=> "Thu Feb 19 18:16:33 +0530 2009"
a=Time.parse(a)
=> Thu Feb 19 18:16:33 +0530 2009
a.day
=> 19
a.year
=> 2009
a.month
=> 2
a.hour
=> 18
a.min
=> 16
a.sec
=> 33
thanks..
Monday, February 16, 2009
Weekday or not
wanna find whether a day is week day or not??
i have tried tht here. ,
date=date.today
[0,6].include?(date.wday)
------------------------------------------------------------------------ require 'date'
class Date
def weekend?
self.wday == 0 || self.wday == 6
end
end
d1 = "9 December 2008"
d2 = "13 December 2008"
p Date.parse(d1).weekend? # false
p Date.parse(d2).weekend? # true
------------------------------------------------------------------------I have used the code for calculation of weekdays between 2 dates.,
require 'date'
d1 = Date.new( 2008, 11, 1 )
d2 = Date.new( 2008, 12, 31 )
WEEKDAY_NUMBERS = [1,2,3,4,5]
weekdays = (d1..d2).select{ |d| WEEKDAY_NUMBERS.include?( d.wday ) }
p weekdays.length
----------------------------------------------------
Friday, February 13, 2009
Displaying Rss in rails
i have displayed an array as rss feeds, using rails..
here s the code..
In the controller,
h={}
h[:summary] =summary
h[:description]=description
h[:dtstart]=dtstart.to_s
h[:url]=url
@arr << h
render :layout =>false
response.headers["Content-Type"]= "application/xml; charset=utf-8"
In the View file., Filename is , *.rxml
xml.instruct!
xml.rss "version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/" do
xml.channel do |feed|
feed.title("My great blog!")
feed.description("description")
feed.link("ur url link")
@arr.each { |p|
feed.item do |item|
item.title p[:summary]
item.description p[:description]
item.link p[:url]
item.pubdate p[:dtstart]
end
}
end
end
now it is displayed as xml feed in the view file..
Thanks .
Wednesday, February 11, 2009
ICAL - specifications
here is the ical specifications listed by wiki..
http://upload.wikimedia.org/wikipedia/en/c/c0/ICalendarSpecification.png
Thanks.
Tuesday, February 10, 2009
ICAL-RSS convertion using vpim gem
i have done the same rss to ical ,vise-versa using vpim gem..
here is the gem home..
http://vpim.rubyforge.org/
This is my code..
require 'rubygems'
require 'vpim/icalendar'
require'feed_tools'
require'digest/md5'
feed = FeedTools::Feed.open("http://rss.cnn.com/rss/edition_world.rss")
cal = Vpim::Icalendar.create2
feed.items.each do |item|
cal.add_event do |e|
e.dtstart item.time
e.dtend item.time
e.summary item.title.to_s
e.description item.description.to_s
e.url item.link
e.uid Digest::MD5.hexdigest("#{item.title} #{item.link}")
e.access_class "PUBLIC"
e.transparency 'OPAQUE'
now = Time.now
e.created now
e.lastmod now
e.organizer do |o|
o.cn = "Example Organizer, Mr."
o.uri = "mailto:organizer@example.com"
end
end
end
icsfile = cal.encode
f=File.open('2.ics','w')
f.write(icsfile)
puts '--- Encode:'
puts icsfile
puts '--- Decode:'
cal = Vpim::Icalendar.decode(icsfile).first
cal.components do |e|
puts e.summary
puts e.description
puts e.dtstart.to_s
puts e.dtend.to_s
puts e.url
end
Monday, February 9, 2009
Ical to Rss Converter
first execute the rss to ical converter, store it in a file, then use this script, to convert it into rss.
require 'rubygems'
require 'net/http'
require 'uri'
require 'time'
class Time
def self.gcalschema(tzid) # We may not be handling Time Zones in the best way...
tzid =~ /(\d\d\d\d)(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z/ ? # yyyymmddThhmmss
Time.xmlschema("#{$1}-#{$2}-#{$3}T#{$4}:#{$5}:#{$6}") :
nil
end
end
class ICal
attr_accessor :hash, :raw
def initialize(ical_data)
self.raw = ical_data
self.hash = self.parse_ical_data(self.raw)
end
def parse_ical_data(data)
data.gsub!(/\\\n/, "\\n")
data.gsub!(/[\n\r]+ /, "\\n")
lines = data.split(/[\n\r]+/)
structure = [{}]
keys_path = []
last_is_array = false
lines.each do |line|
line.gsub!(/\\n/, "\n")
pair = line.split(':')
name = pair.shift
value = pair.join(':')
case name
when 'BEGIN' #Begin Section
if structure[-1].has_key?(value)
if structure[-1][value].is_a?(Array)
structure[-1][value].push({})
last_is_array = true
else
structure[-1][value] = [structure[-1][value], {}]
last_is_array = true
end
else
structure[-1][value] = {}
end
keys_path.push(value)
structure.push({})
when 'END' #End Section
if last_is_array
structure[-2][keys_path.pop][-1] = structure.pop
last_is_array = false
else
structure[-2][keys_path.pop] = structure.pop
end
else #Within last Section
structure[-1][name] = value
end
end
structure[0]
end
end
class Parse
attr_accessor :url, :ical, :xml, :product_id, :version, :scale, :method, :time_zone_name, :time_zone_offset, :events
def parse_from_ical
rawdata = self.calendar_raw_data
return nil unless rawdata
self.ical = ICal.new(rawdata)
self.version = self.ical.hash['VCALENDAR']['VERSION']
self.scale = self.ical.hash['VCALENDAR']['CALSCALE']
self.method = self.ical.hash['VCALENDAR']['METHOD']
self.product_id = self.ical.hash['VCALENDAR']['PRODID']
self.ical.hash['VCALENDAR']['VEVENT'] = [self.ical.hash['VCALENDAR']['VEVENT']] unless self.ical.hash['VCALENDAR']['VEVENT'].is_a?(Array)
self.ical.hash['VCALENDAR']['VEVENT'].each do |e|
if !e.nil?
st = e['DTSTART']
et = e['DTEND']
#et = (Time.gcalschema("#{e["DTEND;TZID=#{self.time_zone_name}"] || "#{e['DTEND;VALUE=DATE']}T000000"}Z") || Time.gcalschema(e['DTEND'])) + tzadjust
# DTSTART;TZID=America/New_York:20070508T070000
@xtr=self.add_event(Event.new(
:start_time => st,
:end_time => et,
:location => e['LOCATION'],
:created_at => Time.gcalschema(e['CREATED']),
:updated_at => Time.gcalschema(e['LAST-MODIFIED']),
:summary => e['SUMMARY'],
:description => e['DESCRIPTION'],
:recurrance_rule => e['RRULE']
), false) # (disable sorting until done)
@events.reject! {|e| e.start_time.nil?}
@events.sort! {|a,b| a.start_time <=> b.start_time }
puts @xtr
end
end
end
def calendar_raw_data
f=File.open("rss2ical.ics","r")
a=f.readlines
return a.to_s
end
def add_event(event, sortit=true)
self.events = [] unless self.events.is_a?(Array)
self.events << event
@events.sort! {|a,b| a.start_time <=> b.start_time } if sortit
event
end
end
class Event
attr_accessor :start_time, :end_time, :location, :created_at, :updated_at, :summary, :description, :recurrance_rule
def initialize(attributes={})
attributes.each do |key, value|
self.send("#{key.to_s}=", value)
end
end
end
a=Parse.new
a.parse_from_ical
Saturday, February 7, 2009
RSS to Ical Converter
this program gets the rss feed using the feed_tools gem.
then converts into ical. then i ve written it in a file.
hope it will be useful.
require'rubygems'
require'feed_tools'
require'digest/md5'
require 'icalendar'
require 'date'
feed = FeedTools::Feed.open("http://timesofindia.indiatimes.com/rssfeeds/-2128932452.cms")
cal = Icalendar::Calendar.new
cal.custom_property("METHOD","PUBLISH")
feed.items.each do |item|
event = Icalendar::Event.new
event.url=item.link
event.uid=Digest::MD5.hexdigest("#{item.title} #{item.link}")
event.dtstart = item.time.strftime("%Y%m%dT%H%M%S")
event.dtend = item.time.strftime("%Y%m%dT%H%M%S")
event.summary = item.title.to_s
event.description = item.description.to_s
event.klass = "PUBLIC"
cal.add_event(event)
end
ical= cal.to_ical
f=File.open("rss2ical.ics","w")
f.write(ical)
puts ical.to_html
Thursday, January 22, 2009
google page rank gem
Ruby has this gem, to find google page rank of a site......,
just install the gem.
>>> sudo gem install googlepagerank
>>>
example program:require "rubygems"
require "googlepagerank"
puts GooglePageRank.get("www.yahoo.com")
=> 9
u can check the above in the site, for further info.
http://googlepagerank.rubyforge.org/
thanks..