Error
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.

end

Daemonize a Ruby process
Thursday, 15 December 2011 12:26
Neat separation of responsibilities between fork/process stuff and actual app


#!/usr/bin/ruby

daemonize do
worker = Resque::Worker.new(*queues)
worker.work
end

def daemonize &block
child = fork
if child.nil? # is child
$stdout.close
$stdout = open("/dev/null")
$stdin.close
trap('HUP', 'IGNORE')
block.call
else # is parent
Process.detach child
end
end

Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/8RoOygYj_Co/14203

 
Cloths recommender
Friday, 25 November 2011 02:28
Prerequisites

Basic Ruby/Rails knowledge, including an installed version of Ruby 1.9.2, Rubygems, Bundler, and Rails 3.
Basic Git knowledge, including an installed version of Git.
Create a Heroku account http://www.heroku.com/
All the commands work on linux

1# Install the Heroku client:


$ gem install heroku


2# Write Your App

You may be starting from an existing app from http://dl.dropbox.com/u/261809/clothes_recommender.tar.gz. If not you can create your own


$ rails new myapp
$ cd myapp


3# Edit your Gemfile and change the line:

group :production do
gem 'pg'
end

group :development, :test do
gem 'sqlite3'
end

gem 'httparty'



4# Install Gems


$ bundle install --without production


5# Store Your App in Git


$ git init
$ git add .
$ git commit -m "init"


6# Deploy to Heroku/Cedar

Create the app on the Cedar stack:

$ heroku create --stack cedar


7# Creating the recommender:

* Create the models

create file app/models/google_weather.rb


class GoogleWeather
include HTTParty
base_uri "www.google.com"

attr_reader :long , :lat

def initialize(options)
@long = options[:long].to_f*1000000
@lat = options[:lat].to_f*1000000
end

def weather
@weather ||= self.class.get("/ig/api", :query => {:weather => ",,,#{@lat.to_i},#{@long.to_i}"}, :format => :xml)
end

def current_condition
@current_condition ||=@weather['xml_api_reply']['weather']['current_conditions']["condition"]["data"]
end

def current_temp
@current_temp ||= @weather['xml_api_reply']['weather']['current_conditions']["temp_f"]["data"]
end

def current_icon
@current_icon ||= "http://www.google.com/#{@weather['xml_api_reply']['weather']['current_conditions']["icon"]["data"]}"
end

def tomorrow_condition
@tomorrow_condition||=@weather['xml_api_reply']['weather']['forecast_conditions'][1]["condition"]["data"]
end

def tomorrow_high
@tomorrow_high||=@weather['xml_api_reply']['weather']['forecast_conditions'][1]["high"]["data"]
end

def tomorrow_low
@tomorrow_low||=@weather['xml_api_reply']['weather']['forecast_conditions'][1]["low"]["data"]
end

def tomorrow_avgtemp
@tomorrow_avgtemp||=(tomorrow_low.to_i+tomorrow_high.to_i)/2
end
end



create file app/models/clothes_recommender.rb


class ClothesRecommender

def self.get_recommendation(lat,long)
response={}
options={:lat=>lat,:long=>long}
gw=GoogleWeather.new(options)
gw.weather
response[:display_text]="Today's weather is #{gw.current_condition} at #{gw.current_temp}F, we recommend #{lookup(gw.current_condition,gw.current_temp)}"
response[:icon]=gw.current_icon
response
end

def self.lookup(condition,temp)
case condition.downcase
when "overcast"
return "you to carry an umberellea or rain coat"
when "rain"
return "not to forget your umberellea/rain coat"
when "mostly sunny"
return "take your umberellea/rain coat"
when "partly sunny"
return "Place holder text"
when "mostly cloudy"
return "Place holder text"
when "partly cloudy"
return "Place holder text"
when "clear"
return "Place holder text"
when "chance of rain"
return "Place holder text"
when "cloudy"
return "Place holder text"
end
case temp.to_i
when 81..100
return "you to wear light cotton clothing and bottle of water"
when 51..80
return "you to wear pants with a top and a lighter jacket"
when 41..50
return "you to take lighter jacket with you"
when 20..40
return "Place holder text"
when 0..30
return "Place holder text"
end
end
end


* Create controller

create file app/controller/recommender_controller.rb


class RecommenderController < ApplicationController

def index
@recommendations= ClothesRecommender.get_recommendation(params[:latitude].to_f,params[:longitude].to_f)
@recommendations[:details_url]="http://#{request.host_with_port}/recommender/details?latitude=#{params[:latitude]},longitude=#{params[:longitude]}"
end

def details
options={:lat=>params[:latitude],:long => params[:longitude]}
@gw=GoogleWeather.new(options)
@gw.weather
@today="Today's weather is #{@gw.current_condition} at #{@gw.current_temp}F, we recommend #{ClothesRecommender.lookup(@gw.current_condition,@gw.current_temp)}"
@tomorrow="Tomorrow's forecast #{@gw.tomorrow_condition} with High at #{@gw.tomorrow_high}F and Low at #{@gw.tomorrow_low}F, we recommend #{ClothesRecommender.lookup(@gw.tomorrow_condition,@gw.tomorrow_avgtemp)}"
end

end


* Create the views







end | tag






Today:
<%=@today%>



Tomorrow:
<%=@tomorrow%>







* Create xml builder

xml.instruct!
xml.dev_expert do
xml.display_text "#{@recommendations[:display_text]}"
xml.icon_hdpi_url "#{@recommendations[:icon]}"
xml.icon_mdpi_url "#{@recommendations[:icon]}"
xml.icon_ldpi_url "#{@recommendations[:icon]}"
xml.details_view_url "#{@recommendations[:details_url]}"
end



8# Deploy your code:

$ git push heroku master

When prompted for your heroku user name and password please enter

Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/JjF1ADUg3gg/13965

 
Normalize table
Saturday, 22 October 2011 01:46
// Normalize table by creating a child table with the unique field and each value of the comma separated column.


DROP TABLE IF EXISTS SplitValues;
DROP PROCEDURE IF EXISTS split_string;
DROP PROCEDURE IF EXISTS normalize_table;

CREATE TABLE `SplitValues` (
`cid` varchar(40),
`value` varchar(500)
) ENGINE=MyISAM;

DELIMITER //

CREATE PROCEDURE split_string (pcd TEXT, pinput TEXT, pdmtr VARCHAR(10))
DETERMINISTIC
BEGIN
DECLARE cur_position INT DEFAULT 1;
DECLARE remainder TEXT;
DECLARE cur_string VARCHAR(1000);
DECLARE delimiter_length TINYINT UNSIGNED;

SET remainder = pinput;
SET delimiter_length = CHAR_LENGTH(pdmtr);

WHILE CHAR_LENGTH(remainder) > 0 AND cur_position > 0 DO
SET cur_position = INSTR(remainder, pdmtr);
IF cur_position = 0 THEN
SET cur_string = remainder;
ELSE
SET cur_string = LEFT(remainder, cur_position - 1);
END IF;
IF TRIM(cur_string) != '' THEN
INSERT INTO SplitValues (cid, value) VALUES (pcd, cur_string);
END IF;
SET remainder = SUBSTRING(remainder, cur_position + delimiter_length);
END WHILE;
END
//

CREATE PROCEDURE normalize_table (ptable VARCHAR(64), pkey TEXT, pvalue TEXT, pdel VARCHAR(10))
DETERMINISTIC
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE vkey,vvalue TEXT;
SET @vquery = CONCAT("CREATE VIEW tmpnormview AS SELECT ", pkey,",",pvalue," FROM ",ptable);

DROP VIEW IF EXISTS tmpnormview;
PREPARE stmt FROM @vquery;
EXECUTE stmt;

BEGIN
DECLARE cur CURSOR FOR SELECT * FROM tmpnormview;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
REPEAT
FETCH cur INTO vkey,vvalue;
IF NOT done THEN
CALL split_string(vkey,vvalue,pdel);
END IF;
UNTIL done END REPEAT;
CLOSE cur;
END;
DROP VIEW tmpnormview;
DEALLOCATE PREPARE stmt;
END
//

DELIMITER ;

Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/6V6bJL8QWm0/13779

 
SQL Columns metainfo : &quot;vw_XL_TableColumns&quot;
Tuesday, 11 October 2011 10:51
CREATE VIEW dbo.vw_XL_TableColumns
AS
SELECT TOP (100) PERCENT tabs.name AS TableName, col.name AS ColumnName, coltype.name AS TypeName, col.max_length AS MaxLength, col.precision, col.scale,
CASE WHEN col.name = pkCol.COLUMN_NAME THEN 'Y' ELSE 'N' END AS IsPrimaryKey, CASE WHEN col.is_nullable = 1 THEN 'Y' ELSE 'N' END AS IsNullable,
CASE WHEN col.is_identity = 1 THEN 'Y' ELSE 'N' END AS IsIdentity, CASE WHEN col.is_computed = 1 THEN 'Y' ELSE 'N' END AS IsComputed,
col.column_id AS ColumnOrder
FROM sys.columns AS col INNER JOIN
sys.tables AS tabs ON col.object_id = tabs.object_id INNER JOIN
sys.systypes AS coltype ON coltype.xtype = col.system_type_id LEFT OUTER JOIN
(SELECT c.COLUMN_NAME, c.TABLE_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS pk INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS c ON pk.TABLE_NAME = c.TABLE_NAME AND
pk.CONSTRAINT_NAME = c.CONSTRAINT_NAME
WHERE (pk.CONSTRAINT_TYPE = 'PRIMARY KEY')) AS pkCol ON pkCol.TABLE_NAME = tabs.name AND pkCol.COLUMN_NAME = col.name
ORDER BY TableName, ColumnOrder

Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/0BU9cjaOM5A/13687

 
Code to determine if file system is case sensitive in Ruby (esp. OS X)
Sunday, 02 October 2011 19:24
// this code will add normcase to Pathname and File in ruby correctly (only the OS X part has been tested)



module NormCase
require 'rbconfig'
require 'pathname'
require 'tempfile'
require 'tmpdir'
def case_sensitive(path=nil) #if not given will use tempfile on OS X
case RbConfig::CONFIG["host_os"]
when /mswin|mingw|cygwin/i #windows is always insensitive
return false
when /darwin/i # the trouble maker as only the underlying file system knows and that requires using Cocoa
require 'osx/cocoa'
include OSX
#OSX.require_framework('Foundation') #this would be false as it loaded already
if ! path then
tf=Tempfile.new(["Temp","Test"],File(path).dirname)
path=tf.path
tf.close
tf.unlink
end
realpath=Pathname(path).parent.realpath().to_s # now we have a full path
# filesystem is an NSURL for realpath with isDirectory => true
filesystem = NSURL.FileURLWithPath_isDirectory_(realpath,true)
#result = [has res., res. value, error value] forKey=>NSURLVolumeSupportsCaseSensitiveNamesKey
result = filesystem.getResourceValue_forKey_error_(NSURLVolumeSupportsCaseSensitiveNamesKey)
return result[1].to_ruby # convert to_ruby because it is an NSCFBoolean (this likely is is false, thanks to Adobe)
when /sunos|solaris|linux/i #unix types are case sensitive
return true
when /vms|os/i #vms or os/2 # TODO: check this but I know that vms and OS/2 are case-insensitive
return false
else # freeBSD, OpenBSD, etc #assume they are posix types with case sensitive file systems
return true
end
end

def normcase(path)
if ! case_sensitive(path) then
self.to_s().upcase()
else
self.to_s()
end
end
end
# don't forget to include this to extend Pathname and File
class Pathname
include NormCase
end
class File
include NormCase
end

Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/7Lnq0q7yk7I/13655

 
Start
Prev
1


Page 1 of 4
Taxonomy by Zaragoza Online