자주 쓰는 엑셀 함수 정리.


엑셀, 문자열 다루기 - 문자열 함수 (텍스트 함수)

  • CHAR - 코드 번호에 해당하는 문자를 반환합니다.
  • CODE - 텍스트 문자열의 첫 문자를 나타내는 코드 값(숫자)을 반환합니다.
  • CONCATENATE - 여러 텍스트 항목을 한 텍스트 항목으로 조인합니다.
  • EXACT - 두 텍스트 값이 동일한지 검사합니다.
  • FIND - 텍스트 값에서 다른 텍스트 값을 찾습니다(대/소문자 구분).
  • LEFT - 텍스트 값에서 맨 왼쪽의 문자를 반환합니다.
  • LEN - 텍스트 문자열의 문자 수를 반환합니다.
  • LOWER - 텍스트를 소문자로 변환합니다.
  • MID - 텍스트 문자열의 지정한 위치로부터 지정한 개수의 문자를 표시합니다.
  • PROPER - 텍스트 값에 있는 각 단어의 첫 글자를 대문자로 바꿉니다.
  • REPLACE - 텍스트 내의 문자를 바꿉니다.
  • REPT - 텍스트를 지정한 횟수만큼 반복합니다.
  • RIGHT - 텍스트 값에서 맨 오른쪽의 문자를 반환합니다.
  • SEARCH - 텍스트 값에서 다른 텍스트 값을 찾습니다(대/소문자 구분 안 함)
  • SUBSTITUTE - 텍스트 문자열에서 기존 텍스트를 새 텍스트로 바꿉니다.
  • T - 인수를 텍스트로 변환합니다.
  • TEXT - 숫자 표시 형식을 지정하고 텍스트로 변환합니다.
  • TRIM - 텍스트에서 공백을 제거합니다.
  • UPPER - 텍스트를 대문자로 변환합니다.
  • VALUE - 텍스트 인수를 숫자로 변환합니다.
  • CONCATENATE (문자열1,문자열2,...)
  • REPLACE(문자열, 시작위치, 바꿀 문자수, 바꿀 문자열)
  • SUBSTITUTE(문자열, 찾을 문자열, 바꿀 문자열)
엑셀, 문자열 다루기 - 문자열 함수 (텍스트 함수) [강동의별님의 블로그]

엑셀, 문자열 다루기 - 문자열 함수 (텍스트 함수)

  • 상대참조(A1 형식) : 셀의 변위에 따라 상대적으로 참조셀의 위치도 변하는 형식.
  • 절대참조($A$1 형식) : 셀의 변위에 상관없이 참조셀이 고정적으로 정해진 형식.
엑셀 절대참조,상대참조 - 기본 중의 기본 [강동의별님의 블로그]

컬럼 합치기

=A1&" "&B1

텍스트 추출하여 날짜/시간 형식으로 변환

=DATE(LEFT(A1,4),MID(A1,5,2),MID(A1,7,2))+TIME(MID(A1,10,2),RIGHT(A1,2),0)

조건절에 만족하면 갯수 세기

=IF(COUNTIF(Sheet1!$A$2:$A$6,Sheet2!A2)=1,1,0)

원하는 범위에서 값 찾아 바꾸기

VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
=vlookup(B1,sheet1!$C$1:$E$13, 3,false),0)


원하는 범위에서 여러 컬럼 값 찾아 바꾸기

=index(Sheet1!$D$1:$D$44,match(A1&B1,Sheet1!$A$1:$A$44&Sheet1!$B$1:$B$44,0))
Sheet1!$A$1:$A$44&Sheet1!$B$1:$B$44 범위에서 A1&B1값을 찾으면 Sheet1!$D$1:$D$44값을 컬럼에 채운다.


함수를 적용시키려면 CTRL+ENTER
배열 수식{}을 적용시키려면 CTRL+SHIFT+ENTER

엑셀 함수 참조 사이트

Contextures - Excel Tips and Excel Tutorials



by


Tags : , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Web application development References


ISO-639-1


Official languages of the United Nations

  • Arabic
  • Chinese (Mandarin)
  • English
  • French
  • Russian
  • Spanish

CLDR

Unicode Common Locale Data Repository

터미널 한글 설정

windows cmd - chcp 65001
linux shell - export LC_ALL=ko_KR.UTF-8


구글 맵스 지도 검색

https://maps.google.com/?q=이름@위도,경도

구글 정의 검색

define:something

Protocol SPDY

http://www.chromium.org/spdy

MongoDB

사용자추가 스키마생성 DB삭제

mongod 를 기동할 때는 --auth 옵션을 추가해야 함
mongoDB는 system영역 내에서 admin이라는 DB관리를 위한 스키마를 가짐
>use admin // admin DB 사용
>db.addUser('name','pswd') // 사용자 추가
>use newDB => 해당 디비가 없으면, 새로운 디비를 생성함
   mysql의 스키마 생성과 같음
>db.collectionName.drop() => 해당 collection을 삭제함
   mysql의 DROP TABLE과 같음

Mongodb eclipse

log path configuration

"C:\data\mongodb-xxxxxxxxx\bin\mongod" --service  --logpath  c:\data\test.log

import

mongoimport --host localhost --db myapp_development --collection my_collection --type csv --file C:\dev\data\test.csv --headerline --upsert

regex

mongodb regex = '^[work|accus*|planet]'
MongoDB can only use indexes on Regular Expression searches that are front (^) anchored.
RegEx searches that front-anchor and then use a wildcard query like .* will use the index for as much of the un-wildcarded area as it can before scanning --- i.e., ^foo.* will run a partial scan.


Mysql

mysql backup and restore


mysqldump -uUSER -pPASSWORD -hHOST DB > ./filename.sql
mysql -uUSER -pPASSWORD -hHOST DB < ./filename.sql

MySQL index

What should be indexed?
–All attributes where you JOIN
–All attributes where you filter (WHERE)
–All attributes where you ORDER or GROUP BY
–All attributes where you want to do an Index Scaninstead of a Table scan.
–NOT on attributes with an evenly distributed lowcardinality.
•How should be indexed?
–Indexes can only be used from left to right.
–Keep them short.
–Compound indexes: INDEX(a, b).
–Prefixed indexes: INDEX(a, b(10)).
–Do not function-cover indexed attributes

http://www.scribd.com/doc/80792061/MySQL-Performance-Tuning

MySQL Date and Time Functions


Mysql 동일 테이블에서 여러 필드 값의 합 쿼리

//쿼리1 보다 쿼리2가 두 배 이상 빠르다. 단, 하나의 칼럼 갯수를 구할 땐 where절과 count(*)를 쓰는 것이 더 빠르다.
//쿼리1
select sum(cnt) from (
    select count(*) as cnt from `my_table` WHERE `field_x` =1
    union all
    select count(*) as cnt from `my_table` WHERE `field_y` =1
    union all
    select count(*) as cnt from `my_table` WHERE `field_z` =1
) as cnt_all
//쿼리2
SELECT
(SUM(IF(`field_x` = 1,1,0)) +   
    SUM(IF(`field_y` = 1,1,0)) +
    SUM(IF(`field_z` = 1,1,0))) as cnt_all
FROM `my_table`
WHERE 1


firefox - keyword.url

http://www.google.co.kr/search?num=50&hl=ko&lr=&newwindow=1&tbo=1&as_qdr=all&aq=f&aqi=&aql=&oq=&gs_rfai=&ie=UTF-8&oe=UTF-8&sourceid=navclient&gfns=1&q=

리눅스 crontab

crontab -l

CSS FONT BASE-64

/* Fonts as files */
@font-face {
    font-family: 'MyFontFamily';
    src: url('myfont-webfont.eot?') format('eot'),
         url('myfont-webfont.woff') format('woff'),
         url('myfont-webfont.ttf')  format('truetype'),
         url('myfont-webfont.svg#svgFontName') format('svg');
    }
/* Fonts as data uris */
@font-face {
    font-family: 'MyFontFamily';
    src: url('myfont-webfont.eot?') format('embedded-opentype');
    }
   
@font-face {
    font-family: 'MyFontFamily';
         url(data:font/truetype;charset=utf-8;base64,BASE64_ENCODED_DATA_HERE)  format('truetype'),
         url(data:font/woff;charset=utf-8;base64,BASE64_ENCODED_DATA_HERE)  format('woff'),
         url('myfont-webfont.svg#svgFontName') format('svg');
    }


CSS Sticky windows

    .outer {
        width:200px;
        height:600px;
        background-color:red;
        margin:0 auto;
    }
    .inner {
        width:50px;
        border:1px solid white;
        position:fixed;
    }
 


Insert the word (image) into the alt text of an image that hasn’t loaded In Firefox

img:after   { content:" (image)"; }
img::after  { content:" (image)"; } /* New CSS3 standard notation */


FYI

References and Articles

빠른 웹 개발

도구


출처

  • 직접 작성
  • google 검색



by


Tags : , , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Ruby Gems Cheat Sheet


GEM 설정

gem environment
set GEM_PATH = D:\dev\ruby192\lib\ruby\gems\1.9.1\gems
gem update --system
gem uninstall gemname
bundle update
(vendor 폴더에 bundle 설치하기)
bundle install --path vendor/bundle


devise

Controller filters and helpers

Devise will create some helpers to use inside your controllers and views. To set up a controller with user authentication, just add this before_filter:
before_filter :authenticate_user!
To verify if a user is signed in, use the following helper:
user_signed_in?
For the current signed-in user, this helper is available:
current_user
You can access the session for this scope:
user_session
Callbacks
    after_set_user
    after_authentication
    before_failure
    before_logout
    Warden::Manager.after_authentication do |user,auth,opts|
        user.last_login = Time.now
    end
   

generator

devise g view with haml
rails g devise_views -t=haml

OmniAuth

Add :password => Devise.friendly_token[0,20] when creating a new user from facebook omniauth.

Passwords Encrypt manually


Assuming you have a mysql database with a "users" table and a "password" column And an ActiveRecord model class called "user" that is hooked up to devise
Create an ActiveRecord model class in your app app/models/old_user.rb
OldUser < ActiveRecord::Base
  set_table :users
  establish_connection :database => "old_database", :user => "old user", :adapter => "mysql"
end
then create a rake task: app/lib/tasks/migrate_users.rake
task :migrate_users => :environment do
  OldUser.find_each do |old_user|
    u = User.new(:email => old_user.email, :password => old_user.password, :password_confirmation => old_user.password);
    #if your using confirmation
    u.skip_confirmation!
    u.save!
  end
end
Modify as necessary (make sure you're saving any app-specific user attributes)
Then$ rake migrate_users
   
Good news and bad news.
Good news:
The following works to create your user's password manually.
 pepper = nil
 cost = 10
 encrypted_password = ::BCrypt::Password.create("#{password}#{pepper}", :cost => cost).to_s
You can find your pepper and cost in your devise initializer. This method was confirmed using Devise's "valid_password?" method.
Bad news:
The entire reason I was trying to avoid "User.new(password: password).encrypted_password" was because of speed. It's terribly slow. With all my other pieces of my import task, I've intentionally avoided this.
But as it turns out, the major cost here is not instantiating a User object -- but BCrypt itself. There is very little noticeable speed boost when using BCrypt directly because it's intentionally designed to be slow.
My final answer: suck it up, run the rake script, go find a beverage.

mailer locale configuration

-ActionMailer::Base.default_url_options[:locale] = I18n.locale


Simple_form

<%= simple_form_for(@user, :builder => CustomBuilder) do |f| %>
  <%= f.input :name %>
<% end %>


Client side validations

Client side validations Registering own form builder
https://github.com/bcardarella/client_side_validations/wiki/Registering-your-own-custom-form-builder


Client MVC

Spine

Important is only that the public directory of the application is specified
as domainroot in Confixx. If the domain is called Passenger will start automatically.."
rails g spine:model Card text is_private order user_id card_type
rails g spine:controller Cards
rails g spine:scaffold card text is_private order user_id card_type
rails g spine:model Organization title description url image admins members followers
rails g spine:controller Organizations
rails g spine:scaffold organization title description url image admins members followers
var card = App.Card.create({ 
  is_private: true,
  order: 0,
  card_type: 'Reason',
  text: 'Spine & Rails, sitting in a tree!'
});
straightforward way to do that without extending Spine Model's
to allow for instances to be added in memory without syncing
Ajax.disable -> saveStuff()
Model.refresh()
extends
Contact.extend(Spine.Model.Ajax);
Contact.extend({
url: '/users/'
});
'/': ->
    if AuthenticatedUser
         @controller = new OtherController
         @replace @controller.render()
    else
         @controller = new LoginController
         @replace @controller.render()
http://spinejs.com/docs/controller_patterns         
         


Compass

compass init rails D:/dev/workspace/baksisi
compass init rails -r html5-boilerplate -u html5-boilerplate --syntax sass --force
css와 javascript를 asset 폴더로 옮겨준다. rails.js는 제외 (jquery_ujs와 동일하다)


Geo_location

https://github.com/chrisyour/geo_location
http://www.maxmind.com/app/geolitecountry


Mongoid id 변경하기

http://blog.joshdzielak.com/blog/2011/12/24/tame-the-mongoid-id-field-in-your-rails-and-backbone-js-app/
http://lostechies.com/derickbailey/2011/06/17/making-mongoid-play-nice-with-backbone-js/


Mongoid Follow unfollow

class User
  include Mongoid::Document
  field :name, type: String
  has_and_belongs_to_many :following, class_name: 'User', inverse_of: :followers, autosave: true
  has_and_belongs_to_many :followers, class_name: 'User', inverse_of: :following
  def follow!(user)
    if self.id != user.id && !self.following.include?(user)
      self.following << user
    end
  end
  def unfollow!(user)
    !self.following.include?(user)
    self.following.delete(user)
  end    
end
relation_ids instead? that is self.member_count = self.member_ids.size
self.challenged.where(_id: event.id).destroy_all
def unchallenge!(announce)
  self.announcements.destroy_all( conditions: { _id: announce.id })
  self.save!
end
Finally I successfully deleted the relation using self.challenged_ids.delete(event.id)
validates_inclusion_of :foo, in: [['foo'], ['bar']]


Mongoid polymorphic behaviour

When a child embedded document can belong to more than one type of parent document, you can tell Mongoid to support this by adding the as option to the definition on the parents, and the polymorphic option on the child.
class Doctor
  include Mongoid::Document
  embeds_one :name, as: :namable
end
class Nurse
  include Mongoid::Document
  embeds_one :name, as: :namable
end
class Name
  include Mongoid::Document
  embedded_in :namable, polymorphic: true
end


TEST

Cucumber

rails g cucumber:install ?capybara ?rspec
  ruby script/rails generate cucumber:feature user email:string password:string confirm_password:string name:string nickname:string gender:integer location_name:string location:integer email_is_priavate:boolean name_is_private:boolean danted:boolean description:string
  ruby script/rails generate scaffold post title:string body:text published:boolean
  rake db:migrate
  rake cucumber


Cucumber Errors Handling

If SystemStackError: stack level too deep 
Then add gem "rspec", ">= 2.6.0.rc2", :group => [:development, :test] to Gemfile


Cucumber & Capybara Ajax

sleep second
page.driver.browser.execute_script %Q{ $('.ui-menu-item a:contains("#{link_text}")').trigger("mouseenter").click(); }
Clicking any element with Cucumber and Capybara
class Capybara::XPath
  class << self
    def element(locator)
      append("//*[normalize-space(text())=#{s(locator)}]")
    end
  end
end
When 'I click "$locator"' do |locator|
  msg = "No element found with the content of '#{locator}'"
  locate(:xpath, Capybara::XPath.element(locator), msg).click
end
The step looks for any element with the given text. Here it is in use:
Scenario: Creating an item
  Given I am signed in as "brandon@example.com"
   When I click "Add to your list"
    And I fill in "Description" with "blog about clicking any element"
    And I press enter
   Then I should see "The item was added to your list"
    And I should see "blog about clicking any element"
   


Cucumber Capybara

selenium chrome driver
https://github.com/jnicklas/capybara
http://code.google.com/p/chromium/downloads/list
http://code.google.com/p/selenium/wiki/ChromeDriver#Overriding_the_Chrome_binary_location
Capybara.register_driver :selenium_with_firebug do |app|
  Capybara::Driver::Selenium
  profile = Selenium::WebDriver::Firefox::Profile.new
  profile.add_extension(File.expand_path("features/support/firebug-1.6.0-fx.xpi"))
  Capybara::Driver::Selenium.new(app, { :browser => :firefox, :profile => profile })
end
Before("@selenium_with_firebug") do
  Capybara.current_driver = :selenium_with_firebug
end


I18n

I18n-js initialize

layout/application.html.haml
- html_tag :class => 'no-js', :lang => "#{I18n.locale}"
applcation.js
I18n.default_locale = "en"
I18n.locale = $($("html")[0]).prop("lang")
I18n.fallbacks = true


Media - Flickraw

    flickr.upload_photo(params[:photo].tempfile.path)


Gem Trouble shooting

Q. `require': no such file to load -- thin (LoadError)
A. => Add gem 'thin' to Gemfile


Rails Performance

  • Curb for Http (libcurl)
  • Yajl, the fastest JSON library.
  • excon #=> faster http
  • Nokogiri, the fastest XML library.
  • Snappy, super fast compression tool by google.
  • fast_xs
  • Memcache. (libmemcached)
  • use Ree Garbage Collector

Fastest Server

  • Unicorn
  • Thin

Profiling Tools

  • NewRelic - Monitoring Tool (Commercial)
  • Ganglia - Monitoring Tool (OpenSource)
  • Cloudflare - Performance & Security
  • rack-perftools

Rack-bug

1. Install rack-bug (branch rails3) as plugin
cd vendor/plugins
git clone -b rails3 https://github.com/brynary/rack-bug.git
If you want to you it as gem then add following line into Gemfile
gem 'rack-bug', :git => 'https://github.com/brynary/rack-bug.git', :branch => 'rails3'
2. Replace the code from file actionview_extension.rb
which is avilable in vendor/plugins/rack-bug/lib/rack/bug/panels/templates_panel/ as specified in bug of rack_bug repository
if defined?(ActionView) && defined?(ActionView::Template)
ActionView::Template.class_eval do
def render_with_rack_bug(*args, &block)
Rack::Bug::TemplatesPanel.record(virtual_path) do
render_without_rack_bug(*args, &block)
end
end
alias_method_chain :render, :rack_bug
end
end
If you are using gem override the specified file in some way
3. Add following lines into your config.ru
require 'rack/bug'
use Rack::Bug, :secret_key => "someverylongandveryhardtoguesspreferablyrandomstring"
run myapp
4. Start your server and access the URL http://your_app/__rack_bug__/bookmarklet.html
and enter the password.
http://blog.railsupgrade.com/2011/04/configure-rack-bug-for-rails-3.html


출처



by


Tags : , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Ruby on Rails Cheat Sheet


rails 데이터 타입

:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean

Rails Mimetype   

"./."                      => :all
"text/plain"               => :text
"text/html"                => :html
"application/xhtml+xml"    => :html
"text/javascript"          => :js
"application/javascript"   => :js
"application/x-javascript" => :js
"text/calendar"            => :ics  
"text/csv"                 => :csv  
"application/xml"          => :xml
"text/xml"                 => :xml
"application/x-xml"        => :xml
"text/yaml"                => :yaml
"application/x-yaml"       => :yaml
"application/rss+xml"      => :rss  
"application/atom+xml"     => :atom 
"application/json"         => :json
"text/x-json"              => :json

bundle asset precompile

bundle exec rake assets:precompile RAILS_ENV="production"
rake assets:clean< add below code if you want development environment with out precompile config.serve.static.assets = false application.rb use Bundler.require(:default, :assets, Rails.env) instead of Bundler.require(*Rails.groups(:assets => %w(development test)))

compile assets locally

Put below into development.rb
config.assets.prefix = "/temp-assets"
Also put below into application.rb
config.assets.initialize.on.precompile = false

rails logger

Rails.logger.info "My info message"
Rails.logger.debug "My debugging message"
Rails.logger.warn "My warning message"

Environment Log level

config.log_level = :debug, :info, :warn, :error, and :fatal

Validation text length CR filter

before.validation :replace.cr
  protected
  def replace.cr
    if self.description.changed?
      self.description.gsub!(/\r\n?/, "\n")
    end
  end

validation locale


// config/locales/en.yml
en:
  activerecord:
    attributes:
      user:
        email: "E-mail address"
    errors:
      models:
        user:
          attributes:
            email:
              blank: "is required"
If you are using mongoid, replace activerecord: with mongoid:

Validate associated

The answer to this turned out to be rather simple. On the parent model, you simply explicitly declare that you want the associated children validated.
parent.rb
validates_associated :children

Validate if persisted? or new_record?

validates.uniqueness.of :nickname, :message => I18n.t("user.already.taken"), :if => :new.record?
validates.uniqueness.of :nickname, :message => I18n.t("user.already_taken"), :unless => :persisted?

Session Store in rails 3

Use the database for sessions instead of the cookie-based default, which shouldn't be used to store highly confidential information
Create the session table with
rake db:sessions:create
Run the migration
rake db:migrate
Make sure you also tell rails to use ActiveRecord to manage your sessions too.
Rails 3
config/initializers/session.store.rb:
Rails.application.config.session.store :active.record.store

DB Migrate Production

rake db:migrate RAILS_ENV="production"

get rails environment

Rails.env
env["SERVER_NAME"]

rails template

rake print --silent RECIPES=jquery,haml,rspec,cucumber,guard,mongoid,action.mailer,devise,add.user,home.page,home.page.users,seed.database,users.page,css.setup,application.layout,html5,navigation,cleanup,ban.spiders,extras,git,compass,omniauth,omniauth.email,backbone > ~/Desktop/backbone.template.txt
Could you please run it again using the "-T -O -J" flags? As in
rails new template_test -m https://github.com/fortuity/rails3-application-templates/raw/master/rails3-mongoid-devise-template.rb -T -O -J
http://blog.dominicsayers.com/2011/08/16/howto-use-a-rails-template-from-github-on-windows/

thin start

D:\dev\ruby192\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) D:/dev/workspace/baksisi/script/rails server thin -b 127.0.0.1 -p 3002 -e development
ruby ./script/rails server thin -b smoke-free-online.de -p 3000 -e development -d
thin start

Middle Man

"server" was called incorrectly. Call as "middleman server [-p 4567] [-e development]".
"middleman server [-p 4567] [-e development]" instead of "middleman server -p 4567 -e development

DB migration

Rails g migration change.data.type.for.table_column

I18n

locale join

config/application.rb
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '.*', '..{rb,yml}')]

locale path

routes.rb
  match '/:locale' => "home#index"
  root :to => "home#index"
  scope "/:locale" do   
    controller :models do
      something
    end
    resources :models, :only => :show
ApplicationController
  def default.url.options(options = {})
    options.merge!({:locale => I18n.locale})
  end   

Localize

I18n.l Time.now, :format => :short,  :locale => :"ko"

Pluralization

ko:
  pears:
    zero: ko.zero
    one: ko.one
    few: ko.few
    other: ko.other

generate rake tasks

rails g task namespace task1 task2
rake -T | grep namespace

세션 저장

config.session.store :cookie.store, :key => '.baksisi.session', :domain => :all
environment.rb 메일러에 레이아웃을 지정하고 싶다면.
DeviseMailer.layout "OMG"

show routes

rake routes

SASS

config/application.rb:
config.generators.stylesheet_engine = :sass
sass-convert style.sass style.scss

Trouble Shootings

uninitialized constant

file name confirm (if file name capital, it can be occurred.)

guard-livereload error

gem install eventmachine --pre 

open-uri.rb file in C:/Ruby1.9.2/lib/ruby/1.9.1/ (of course your path might be different).

http.verify.mode = options[:ssl.verify.mode] || OpenSSL::SSL::VERIFY.NONE

[ERROR] V8 is no longer usable

ulimit -v unlimited  

CSV Data Handling

http://www.ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html

get action information at view

    params[:action]

HAML

rails helper using haml
 
def section(name)
haml.tag(:div, :class => 'section') do
  haml.tag(:h2, name)
  haml.tag(:p, :class => 'section.content') do
    yield
  end
end
end
      
def content.box
  haml.tag :div, :class => "holder" do
    haml.tag :div, :class => "top"
    haml.tag :div, :class => "content" do
      yield
    haml.tag :div, :class => "bottom"
  end
end
and in haml
%html
  %head
  %body
    Maybee some content here.
    - content.box do
      Content that goes in the content_box like news or stuff      
     
fields_for with index
<% @questions.each.with.index do |question,index| %>
    <% f.fields.for :questions, question do |fq| %> 
        # here you have both the 'question' object and the current 'index'
    <% end %>
<% end %>
It’s also possible to specify the instance to be used:
<%= form.for @person do |person.form| %>
...
<% @person.projects.each do |project| %>
  <% if project.active? %>
    <%= person.form.fields.for :projects, project do |project.fields| %>
      Name: <%= project.fields.text_field :name %>
    <% end %>
  <% end %>
<% end %>
<% end %>     

Rails Response

namespace "api" do
  resources :regions, :defaults => { :format => 'xml' }
end
Then you should be able to have the following work for your controller methods:
class Api::RegionsController < ApplicationController
  respond.to :xml, :json
  def index
    respond.with(@regions = Region.all)
  end
end
rescue.from  ActionController::MissingFile do |e|
  # User's browser probably wont display this
  # Content-Type is application/x-shockwave-flash
  render :file => File.join(Rails.public.path, '404.html'), :status => 404
end

show details or stream video

def show
  @media = Media.find params[:id]
  respond.to do |format|
    format.html
    format.flv { send.file @media.path, :disposition => 'inline' }
  end
end
render :file => File.join(Rails.public.path, '404.html'), :status => 404, :content.type => 'text/html'

render with variable

render :partial => "my/conejo", :locals => {:my.val => something}
render "my/liebre", :my.val => something

scope

default_scope order('id DESC')
Model.reorder('')
Model.unscoped

render an other action in the controller, in js.

  render 'result', :id => @item.id, :format => :js
 

layout xhr? 

  class ApplicationController < ActionController::Base
  layout proc{|c| c.request.xhr? ? false : "application" }
  end
  layout :layout.xhr?
  def layout.xhr?
    request.xhr? ? false : 'application'
  end
 

AJAX Performance stale? and touch


 def show
    @list_item = @list.list_items.find( params[ :id ] )
    if stale?( :etag => @list_item, :last_modified => @list_item.updated_at.utc, :public => true )
      respond_with( @list_item )
    end
  end
  Also instead of the update_list method being called from after_save/destroy you can pass :touch => true to the belongs_to association which will do the same

AJAX Handler - ?xhr

respond_with( @something, :layout => !request.xhr? )
or
respond_to do |wants|
  wants.html do
    if request.xhr?
      render :partial => "items"
    else
      render
    end
  end
end

Asset

exist

YourApp::Application.assets.find_asset("#{asset}.file").nil?

### pathname

<YourAppName>::Application.assets.find_asset('Rails.png').pathname

absolute asset_path in view using helper

"#{request.protocol}#{request.host.with.port}#{asset.path('person/gravatar.default.png')}"
"#{request.scheme}://#{request.host.with.port}#{request.script_name}"

Mailer

config

environment/production.rb
  config.action.mailer.default.url.options = {:host => 'localhost:3000',:locale =>I18n.locale}
  config.action.mailer.smtp.settings = {
    :address              => "server.addr",
    :port                 => 587,
    :domain               => "sever.domain",
    :user.name            => "user.name",
    :password             => "user.password",
    :authentication       => "plain",
    :enable.starttls.auto => true
  } 
  config.action.mailer.delivery.method = :smtp
  config.action.mailer.perform.deliveries = true
  config.action.mailer.raise.delivery.errors = false
  config.action.mailer.default :charset => "utf-8"

inline attachement

in mailer

attachments.inline['blank'] = {
    :data => File.read("#{Rails.root.to.s + '/app/assets/images/blank.png'}"),
    :mime.type => "image/png",
    :encoding => "base64"
}

in view

if @offer.image.nil?
  = image.tag( attachments['blank'].url, :id => 'attachement.image', :width => "400", :height => "400")
 

validates in I18n

%{attribute} - field name
%{model} - model name 
%{count} - count


rescue log

begin
  ...some code...
rescue Exception => e
  logger.error e.message
 

Ruby

Iterate

a.each.with.index do |item, index|
  puts item, b[index]
end
array.each.slice(3) do |elements|
  fire.the_event
end

Timezone

in client (js):
function set.time.zone.offset() {
    var current.time = new Date();
    $.cookie('time.zone', current.time.getTimezoneOffset());
}
in Application Controller:
before.filter :set.timezone
def set.timezone 
 min = request.cookies["time.zone"].to_i
 Time.zone = ActiveSupport::TimeZone[-min.minutes]
end

DateTime format

  %a - The abbreviated weekday name (Sun)
&nbsp; %A - The&nbsp; full&nbsp; weekday&nbsp; name (Sunday)
  %b - The abbreviated month name (Jan)
&nbsp; %B - The&nbsp; full&nbsp; month&nbsp; name (January)
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (AM&nbsp; or&nbsp;PM)
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character
   t = Time.now
   t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
   t.strftime("at %I:%M%p")            #=> "at 08:56AM"
  
   datetime seconds, hours, days, weeks, months, and years
  
    Add below lines to one of your initializer files, e.g., config/environment.rb:
    DateTime::DATE.FORMATS[:short]="short %Y-%m-%d %H:%M:%S"
    Time::DATE.FORMATS[:short] = "short %Y-%m-%d %H:%M:%S"
    Date::DATE.FORMATS[:short] = "short %Y-%m-%d"
    modify view:
    <%= item.create_date.to_s(:short) %>
distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {})
today = DateTime.now
=> #<DateTime: 441799066630193/180000000,-301/1440,2299161>
birthday = Date.new(2008, 4, 10)
=> #<Date: 4909133/2,0,2299161>
days_to_go = birthday - today
time_until = birthday - today
=> Rational(22903369807, 180000000)
time_until.to_i             # get the number of days until my birthday
=> 127
hours,minutes,seconds,frac = Date.day_fraction.to_time(time_until)
[3053, 46, 57, Rational(1057, 180000000)]
- mm  = (now-la    st_cigarette).divmod(Rational(1, 1440))[0]
- past.days = mm / 1440
- past.hours = (mm % 1440) / 60
- past_minutes = mm % 60

timezone

def set_api_time_zone
  utc_offset = current.user.session && current.user.session.user ? current.user.session.user.time.zone.offset.to.i.minutes : 0
  user.timezone = ActiveSupport::TimeZone[utc.offset]
  Time.zone = user.timezone if user.timezone
  Time.zone.today
  Time.now.to.date
    # => Thu, 19 May 2011
  Time.now.in.time.zone('Melbourne').to_date
    # => Fri, 20 May 2011
end

Range step

range.step(2) {|x| puts x}


benchmark

require 'benchmark'
n = 1000000
def answer1 current.subdomain
  case current.subdomain
  when 'www', 'blog', 'foo', 'bar'
  else nil
  end
end
def answer2 current.subdomain
  nil unless  ["www", "blog", "foo", "bar"].include?(current.subdomain)
end
Benchmark.bmbm do |b|
  b.report('answer1'){n.times{answer1('bar')}}
  b.report('answer2'){n.times{answer2('bar')}}
end
Rehearsal -------------------------------------------
answer1   0.290000   0.000000   0.290000 (  0.286367)
answer2   1.170000   0.000000   1.170000 (  1.175492)
---------------------------------- total: 1.460000sec
              user     system      total        real
answer1   0.290000   0.000000   0.290000 (  0.282610)
answer2   1.180000   0.000000   1.180000 (  1.186130)
Benchmark.bmbm do |b|
  b.report('answer1'){n.times{answer1('hello')}}
  b.report('answer2'){n.times{answer2('hello')}}
end
Rehearsal -------------------------------------------
answer1   0.250000   0.000000   0.250000 (  0.252618)
answer2   1.100000   0.000000   1.100000 (  1.091571)
---------------------------------- total: 1.350000sec
              user     system      total        real
answer1   0.250000   0.000000   0.250000 (  0.251833)
answer2   1.090000   0.000000   1.090000 (  1.090418)


출처




by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Git cheat sheet


ssh 키페어 만들기

ssh 키 페어 만들기

git 기본 명령어


git init  - 초기화
git add * - git에 파일 목록 넣기
git commit -am 'initial commit' - 커밋
git push repository_name master - 해당 브랜치에 커밋
git clone git@app.repo.com:app/app.git - 코드를 로컬로  복제
cd app
git pull - 변경사항 풀


git 환경 설정


git config --global --list
현재 설정정보 조회할 수 있습니다. --global옵션은 전역설정에 대한 옵션이며 현재 프로젝트에만 적용할때는 주지 않습니다.
git config --global user.name "사용자명"
사용자명을 등록합니다 (필수)
git config --global user.email "이메일주소"
이메일 주소를 등록합니다. (필수)
git config --global color.ui “auto”
터미널에 표시되는 메시지에 칼라를 표시해 줍니다.



gitignore 사용하기


.gitignore
git config --global core.excludesfile ~/.gitignore_global
git rm -r --cached .
git add .
git commit -m ".gitignore 완성!"
git stash branch branchname
git fetch
git merge
git pull (git fetch + git merge branchname)


로컬 변경 무시하고 저장소에서 받아오기

모든 로컬 변경을 스태쉬 한다.
git stash save --keep-index
저장한 stash를 지운다.
git stash drop

파일 하나만 저장소에서 불러오려면 이렇게 한다.
git checkout HEAD^ path/to/file/to/revert

그리고 저장소에서 풀 한다.
git pull


특정 커밋으로 돌아가기
http://stackoverflow.com/questions/4114095/revert-to-previous-git-commit
git reset --hard 0d1d7fc32

Send a pull request on GitHub for only latest commit
http://stackoverflow.com/questions/5256021/send-a-pull-request-on-github-for-only-latest-commit
git checkout -b upstream upstream/master
git cherry-pick <SHA hash of commit>
git push origin upstream



How can I rollback a github repository to a specific commit?
http://stackoverflow.com/questions/4372435/how-can-i-rollback-a-github-repository-to-a-specific-commit
git reset --hard <old-commit-id>
git push -f



참고 자료

http://git-scm.com/
http://github.com/
아웃사이더님의 git 명령어 정리
구글 검색



by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Jquery,Coffeescript Snippet 모음


스타일 변화 시키기


    $('HTML').addClass('JS');
    * In your css */
    .JS #myDiv{display:none;}

coffee script 에서 함수 호출


    contents+="<li class='city_candidate' onclick='h(\""+data[v]+"\")'>"+v+"</li>"
    @h = h = (set) ->
      $('span#cityoutput').replaceWith("<span id='cityoutput'>"+set+"</span>")

Ajax Callback


    url = "locations"
    request = $.get url,data
    request.success (data) -> $("#regionresults").html(data)
    request.error (jqXHR, textStatus, errorThrown) -> $("#region
results").append "AJAX Error: ${textStatus}."

Slide UP


jQuery ->
  $(".search input").focus ->
    if @value == "Search"
      @value = ""
      @className = "textinput"  $(".search input").blur ->
    if @value == ""
      @value = "Search"
      @className = "placeholder"
  $('#message').css { border: '1px solid red' }
  $("p").click(function () {
      $(this).slideUp();
    });
    $("p").hover(function () {
      $(this).addClass("hilite");
    }, function () {
      $(this).removeClass("hilite");
    });

Sticky layer


sticky = () ->
  y = $(window).scrollTop()
  if y > $('#topnavigation').height()
    $('#top
navigation').css({
      'position': 'fixed',
      'top': '0',
      'z-index': "4444"
        'width': $('#top_navigation').width(), 'box-shadow': '0px 20px 20px -15px #CCC'
    })
    $('#topnavigation').removeClass("sixteen columns alpha")
    $('#main').css({'padding-top': $('#top
navigation').height()})
  else
    $('#topnavigation').removeAttr('style')
    $('#main').removeAttr('style')
    $('#top
navigation').addClass("sixteen columns alpha")
$(window).scroll(sticky)
$(window).resize(sticky)
   
   

페이드인 메시지


msg = "world"
inv = "you"
show_message = (x,y) ->
  $('span#message').hide().text(x).fadeIn(1000,
  -> $('span#message').append('!')
  )
  $('#hint').hide().text(x).fadeIn(0)$ ->
  showmessage msg,inv
    [inv, msg] = [msg, inv]
 
  $('span#message').click ->
    show
message inv,msg
    [inv, msg] = [msg, inv]
message fadein and out
.fadeIn(30).fadeOut(1000);
   

다이나믹 add remove


$('input#addlanguageskill').on 'click', () ->
  num = ($('.languageskillinnerbox').length)-1
  newNum  = new Number(num+1)
  sourceElem = $('div#language
skill' +num)
  newElem = sourceElem.clone().prop('id','language
skill'+newNum)
  newElem.find("#user
languageskillsattributes"+num+"languageid").prop({id:'userlanguageskillsattributes'+newNum+'languageid',name:'user[languageskillsattributes]['+newNum+'][languageid]'})
  newElem.append('<input onclick="remove(\''+newElem.prop('id')+'\')" id="removelanguageskill"'+newNum+' type="button" value="Remove Language"/>')
  sourceElem.after(newElem)
@remove = remove = (elemid) ->
  alert "remove : "+elem
id
  $("#"+elem_id).remove()

Nested Model Form 예제


<% formfor @person do |personform| %>  <%= personform.label :name %>
  <%= person
form.text_field :name %>
  <% personform.fieldsfor :children do |child_form| %>
    <%= childform.label :name %>
    <%= child
form.text_field :name %>
    <% unless childform.object.newrecord? %>
      <% # Don't forget to name both of these 'destroy' in Rails 3 %>
      <%= child
form.checkbox 'delete' %>
      <%= childform.label 'delete', 'Remove' %>
    <% end %>
  <% end %>
  <%= submit_tag %>
<% end %>

그리즈 몽키 ajax 콜


var jqxhr = $.ajax({
  type: "POST",
  url: trackback,
  headers: {'User-Agent': 'Trackback',
                  'Content-Type':'application/x-www-form-urlencoded; charset=utf8'},
  data: inputdata,
  datatype:"text"
   });
  jqxhr.done(function() {
    GM
log("Trackback Success : "+jqxhr.responseText);           
  });
  jqxhr.fail(function(data,statusText,error) {                
        GM_log("Trackback faild : "+statusText+" [ "+error+", "+data.responseText+" ]");              
       
       
  });
 

셀렉트 박스 정렬


sortingSelectBox(selectTagId,sortBy,order)
selectTagId <select id="selectTagId"></select>
sortBy [0:Text, 1:Value] - default:0
order[0:Ascending, 1:Descending] - default:0
Examples
sortingSelectBox("mySelectTagId",1,1) sortBy Value in Descending order
sortingSelectBox("mySelectTagId",1) sortBy Value in Ascending order
sortingSelectBox("mySelectTagId") sortBy Text in Ascending order
sortingSelectBox = (selectBoxId,sortBy,order) ->
   sortBy ?= 0
   order ?= 0
   sortVal = 0
   if order is 1 then sortVal = 2
   orderValLeft = -1 + sortVal
   orderValRight = 1 - sortVal
   selectBox = $("select#"+selectBoxId)
   options = $("select#"+selectBoxId+" option")
   selectedVal = selectBox.val()
   sortedOption = options.clone()
   options.empty().remove()
   switch sortBy
     when 0
       sortedOption.sort((left,right)->
         leftText = left.text.toLowerCase()
         rightText = right.text.toLowerCase()
         if leftText < rightText then return orderValLeft
         if leftText is rightText then return 0
         orderValRight
       )
     else
       sortedOption.sort((left,right)->
         leftVal = left.value
         rightVal = right.value
         if leftVal < rightVal then return orderValLeft
         if leftVal is rightVal then return 0
         orderValRight
       )
   selectBox.append(sortedOption)
   selectBox.val(selectedVal)
  
sortingSelectBox("country")

리다이렉트


// simulates similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// simulates similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

JQuery 데이터 타입


dataTypeString
Default: Intelligent Guess (xml, json, script, or html)
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:    "xml": Returns a XML document that can be processed via jQuery.
    "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
    "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
    "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
    "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "
=[TIMESTAMP]", to the URL unless the cache option is set to true.
    "text": A plain text string.
    multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
/*
If you wish to use any of the meta-characters
( such as !"#$%&'()*+,./:;?@[]^`{|}~ ) as a literal part of a name,
you must escape the character with two backslashes: . For example,
if you have an an element with id="foo.bar", you can use the selector
$("#foo.bar").
*/

Session based tokens


If you are using session based tokens, you probably generate a secure token when generating the session, and store that token in the session. When a request comes back to the server, you check that the token is included in the request and compare it to what's in the session. If it's the same token, you accept the request, if not you reject it.
To use this token with jQuery, you need to make it available to javascript. You typically do this by adding it as a javascript variable.
var csrftoken = '<%= tokenvalue %>';
Next, the trick is to bind to the global ajaxSend event, and add the token to any POST request
$("body").bind("ajaxSend", function(elm, xhr, s){
if (s.type == "POST") {
xhr.setRequestHeader('X-CSRF-Token', csrf_token);
}
});

rails-3-1-and-jquery-ui-assets 설정


# http://stackoverflow.com/questions/6133818/rails-3-1-and-jquery-ui-assets
 $ cat app/assets/javascripts/application.js
    //= require jquery
    //= require jquery-ui
    $ cat app/assets/stylesheets/application.css
    /*
     *= require vendor
     *
     */
    $ cat vendor/assets/stylesheets/vendor.css
    /*
     *= requiretree ./jqueryui
     *
     */
    vendor/assets/ $ tree
     stylesheets
         vendor.css
             jqueryui
                      jquery-ui-1.8.13.custom.css
                      ...
     images
        jquery
ui
            ui-bgflat0aaaaaa40x100.png
            ...

Finally run this command:
    vendor/assets/images $ ln -s jquery_ui/ images
   

Get center


$(document).ready(function(){
  jQuery.fn.center = function () {
      this.css("top",$(window).height()/2-this.height()/2 + "px");
      this.css("left",$(window).width()/2-this.width()/2  + "px");
      return this;
  }
  $("#container").center();
 });
 

Multiple selector

$("#txt1, #txt2, #txt3").keyup(fn);

Jquery check CKEditor


$(this).data('initialForm', $(this).serialize());
to
$(this).data('initialForm', $(this).serialize() + '&' + FieldNameOfEditor + '=' + escape(ContentsOfEditor));
And a similar change to line 4 from
if ($(this).data('initialForm') != $(this).serialize()) {
to
var formData = $(this).serialize() + '&' + FieldNameOfEditor + '=' + escape(ContentsOfEditor);
if ($(this).data('initialForm') != formData) {

Jquery Defer


(function() {
      function getScript(url,success){
        var script=document.createElement('script');
        script.src=url;
        var head=document.getElementsByTagName('head')[0],
            done=false;
        script.onload=script.onreadystatechange = function(){
          if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
            done=true;
            success();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
          }
        };
        head.appendChild(script);
      }
        getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',function(){
            // YOUR CODE GOES HERE AND IS EXECUTED AFTER JQUERY LOADS
        });
    })();

Scroll to top   


var destination = $(‘#idToScrollTo’).offset().top;
$(‘html’).animate({scrollTop: destination},600);

CKEDITOR


config.toolbar = 'Modati'
config.toolbar_Modati = [['Bold', 'Italic', 'Underline','Strike', '-', 'RemoveFormat','-', 'Outdent','Indent','-','Blockquote','HorizontalRule', '-', 'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','FontSize','TextColor','BGColor']]CKEDITOR.editorConfig = function( config )
{
    config.toolbar = 'MyToolbar';
 
    config.toolbar_MyToolbar =
    [
        { name: 'document', items : [ 'NewPage','Preview' ] },
        { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
        { name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','Scayt' ] },
        { name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'
                 ,'Iframe' ] },
                '/',
        { name: 'styles', items : [ 'Styles','Format' ] },
        { name: 'basicstyles', items : [ 'Bold','Italic','Strike','-','RemoveFormat' ] },
        { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote' ] },
        { name: 'links', items : [ 'Link','Unlink','Anchor' ] },
        { name: 'tools', items : [ 'Maximize','-','About' ] }
    ];
};
config.toolbar = 'Full';
 
config.toolbarFull =
[
    { name: 'document', items : [ 'Source','-','Save','NewPage','DocProps','Preview','Print','-','Templates' ] },
    { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
    { name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] },
    { name: 'forms', items : [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
 
         'HiddenField' ] },
    '/',
    { name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] },
    { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv','-
 
        ','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ] },
    { name: 'links', items : [ 'Link','Unlink','Anchor' ] },
    { name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] },
    '/',
    { name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] },
    { name: 'colors', items : [ 'TextColor','BGColor' ] },
    { name: 'tools', items : [ 'Maximize', 'ShowBlocks','-','About' ] }
];
 
config.toolbar
Basic =
[
    ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink','-','About']
];
CKEDITOR.editorConfig = function( config )
{
    config.extraPlugins = "customparagraph";
    config.toolbar = [ [ 'ThinyP' ] ]; // add other toolbars and keep in mid this can be overwritten in page which loads CKEditor
};
<script type="text/javascript">
//<![CDATA[
    // Replace the <textarea id="editor1"> with a CKEditor
    // instance, using default configuration.
    CKEDITOR.replace( 'editor1',
        {
            extraPlugins : 'customparagraph',
            toolbar :
            [
                [ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
                [ 'ThinyP' ]
            ]
        });
//]]>
</script>
in the main ckeditor config-file there is an option to disable automatic <p> inserts. try to change the value of CKConfig.EnterMode and CKConfig.ShiftEnterMode for example to 'br'.
config.enterMode = CKEDITOR.ENTER_BR
lostmorethanfive, lostbeetweenfourandfive, lostbeetweenthreeandfour, lostbeetweentwoandthree, lostbeetweenoneandtwo, lostbeetweenzeroandone, gainedbeetweenzeroandone, gainedbeetweenoneandtwo,gainedbeetweentwoandthree, gainedbeetweenthreeandfour, gainedbeetweenfourandfive,gainedbeetweenfiveandsix, gainedbeetweensixandseven,gainedmorethanseven


출처




by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

특정 조건으로 검색을 자주 한다면, 자신만의 파이어폭스 검색 에드온을 만들어 보세요.

자주 쓰는 검색 조건이 있으신가요?

만약 특별히 자주 쓰는 검색 조건이 있다면,

기본 검색 에드온으로 검색한 다음에, 일일히 조건을 지정하시기는 참 귀찮은 일입니다.

자신만의 파이어폭스 검색 애드온을 만들면, 이런 수고를 덜어줘요.

 

파이어폭스용 검색 에드온 만들기

아래의 양식으로 문서를 만든 후 search-engine-name.xml 포멧으로 저장하세요.

firefox/Data/profile/searchplugins 폴더 혹은 Firefox/searchplugins 폴더에 파일을 복사해 넣으세요.

 

파이어폭스용 검색 에드온 양식

 

<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/" xmlns:os="http://a9.com/-/spec/opensearch/1.1/"><<os:ShortName>검색 엔진 이름</os:ShortName>
<os:Description>검색엔진 설명</os:Description>
<os:InputEncoding>UTF-8</os:InputEncoding>
<os:Image width="16" height="16">이미지의 base64코드</SearchForm>
<os:Url type="text/html" method="GET" template="검색엔진주소[query={searchTerms}]">
</os:Url>
</SearchPlugin>

 

아마 사람마다 즐겨 검색 하는 조건이 다를 거에요.

예를 들자면 저는 구글에서 최근 1년사이의 정보를 찾는 횟수가 잦습니다.

그리고 페이지 넘기는게 귀찮으니 한번에 50개 정도 검색 결과가 나오면 좋겠군요.

그리고 검색된 링크를 새 창으로 띄우면 더 편하겠어요.

이 조건을 적용하면 아래와 같은 검색 주소가 나옵니다.

 


http://www.google.com/search?num=50&amp;hl=en&amp;newwindow=1&amp;tbo=1&amp;output=search&amp;source=lnt&amp;tbs=qdr:y&amp;sa=X&amp;sourceid=navclient&amp;gfns=1&amp;q={searchTerms}

이 주소를 Url template 란에 넣어주면 되는거에요.

Image의 경우는 16*16 크기의 그림파일을 열어 base64코드로 변환해 줍니다.

아래 사이트에서 base64코드로 변경 할 수 있어요.

base64 sample decoder and encoder

 

이미지는 건너 뛰어도 무리없이 작동합니다.:D

 

또 제가 꽤 자주 쓰는 검색엔진이 있는데, 바로 국립국어원 표준국어대사전입니다.

국어 사전을 볼 때마다 제가 한국에 태어난 걸 참 다행이라고 생각해요.

이걸 외국어로 배우려고 했으면 얼마나 머리가 아팠을지.. 어휴.

 

파이어폭스용 국립국어원 표준국어대사전 검색 애드온이 필요하시다면 아래 링크에서 내려받으세요.

https://addons.mozilla.org/en-US/firefox/addon/표준국어대사전

 

검색 에드온에 대해 더 자세히 알고 싶다면 아래 링크를 참조하세요.

Creating OpenSearch plugins for Firefox

 



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

코드의 가독성을 높여주는 소프트웨어 개발자용 폰트 사용기 입니다.

개발자용 폰트라고 할만한 번들 고정폭(monospace) 폰트로는 Courier 폰트가 있습니다.
번들렌즈를 써도 고수가 찍은 사진은 멋지기만 하듯,
진정한 고수는 Courier 폰트만으로도 개발하는데 충분합니다.
하지만 그 고수의 손에 착 감기는 장비가 주어진다면,
더 멋진 작품이 나오겠죠?
이 글은 지극히 제 취향의 개발자용 폰트 사용기 입니다.

  1. Envy Code R

    가장 선호하는 폰트입니다.
    한글 문제도 없고, 코드가 한 눈에 들어오는 느낌. 마음에 들어요.
    글씨 크기는 다른 폰트보다 1 포인트 크게 하는 게 보기 좋더군요.
    다만 RubyMine에서 TODO List이용시,
    글씨가 깨지는 현상 때문에 루비마인에선 사용하지 않습니다.

  2. Monaco

    꽉찬 느낌의 폰트.
    Envy Code R 폰트를 눌러 놓은 느낌입니다.
    제가 쓰는 편집기에선, 다 잘 작동하고 괜찮아요.

  3. DejaVu Sans Mono

    깔끔하고 괜찮습니다.
    아쉽게도 Notepad2에서는 폰트를 못 찾더군요.

  4. Bitstream Vera Sans Mono

    시원시원하고 가독성이 좋은 편이라 마음에 드는 폰트입니다.
    하지만 단점이 좀 있어요.
    우선 라틴 문자중 ĝ 같은 글씨의 아래가 짤리는 문제가 발생합니다.
    그리고 루비 마인에서 한글 타이핑이 영 원활하지 않아서 사용하지 않는 폰트에요.
    오로지 영문 알파벳만 사용한다면 가장 이상적인 폰트라고 생각합니다.

  5. Inconsolata

    무난한 폰트로, 그리 매력적인 폰트는 아닙니다.
    게다가 루비 마인에서는 폰트를 못 찾아요.
    그래도 코드 가독성은 괜찮은 편이고,
    구글 웹폰트 서비스에서 제공합니다.
    제 블로그의 코드 블럭엔 이 폰트를 적용했어요.

  6. 나눔고딕 코딩

    NHN에서 제공하는 무료 코딩용 글꼴입니다.
    한글처리야 좋지만, 라틴문자가 아예 깨져버립니다.
    코드에 한글, 영문만 사용한다면 괜찮은 폰트인 것 같아요.

저는 개발용으로 세 가지 정도의 도구를 이용합니다.
도구마다 쓰는 폰트가 달라요.
우선 RoR개발용 루비마인엔 DejaVu Sans Mono를 씁니다.
루비마인과는 궁합이 가장 좋은 폰트 같아요.
블로그 템플릿등을 편집할 때 쓰는 Notepad++에선 Envy Code R을 사용합니다.
이 폰트가 제 취향에 가장 맞는 폰트거든요.:D
그리고 마지막으로 그리즈몽키 스크립트등을 편집할 때 쓰는 Notepad2에선 Monaco 폰트를 이용해요.
취향에 맞는 폰트를 쓰면, 개발이 좀 더 즐겁습니다.:D

참고자료
Top 10 Programming Fonts



by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

괜찮은 루비온 레일즈 개발 도구, 루비마인을 소개 합니다.

저에겐 이클립스가 가장 익숙한 IDE입니다.
그런데 요즘은 자바보단 RoR개발에 흥미가 있어서,
루비온레일즈용 IDE를 찾아보았어요.
이클립스에서도 루비온 레일즈용 플러그인인 aptana를 제공하긴 하지만,
다른 계열의 도구를 한번 써보고 싶었어요.

루비 마인 (RubyMine)

루비마인은 IntelliJ IDEA 계열의 IDE입니다.
얼마간 쓰다 보니, 금방 이클립스보다 더 친숙해졌어요.:D
UI가 직관적이라 따로 메뉴얼을 보지 않아도 금방 익숙해집니다.
물론 이클립스 같은 다른 IDE에 익숙한 경우에 말이죠. ^^;
다른 IDE에서 넘어오는 사용자를 위해, 친절하게 키셋도 제공해요.
이클립스의 키셋을 설정했더니, 단축키도 익숙하고 편하네요!
RoR개발만 한다면 한번 고려해 볼만한 IDE입니다.
저의 루비마인 RoR 개발 환경을 소개할게요.

우선 전 랩탑과 넷북사이의 어중간한 사양에서 루비마인을 돌려요.
그래서 무엇보다 성능 최적화가 중요하죠.
검색을 통해 약간의 최적화 팁을 찾았어요.
루비 마인은 프로젝트 내의 모든 파일을 인덱싱 합니다.
로그파일 처럼 큰 파일을 프로젝트 내에 포함시킨다면, 인덱싱을 하는데 많은 시간을 잡아먹죠.
그러니 이런 로그파일은 프로젝트 파일에서 제외시키는 편이 성능에 도움이 되요.

64비트 자바를 사용하신다면,
RubyMine\bin\rubymine.exe.vmoptions 파일에서 힙 메모리 옵션을 변경해 주세요.

-Xms800m
-Xmx1200m
-XX:MaxPermSize=1000m
-ea

저는 위 설정에서 Xmx가 너무 크다고 오류메시지가 나와서 아래처럼 설정을 했습니다.


-Xms800m
-Xmx964m
-XX:MaxPermSize=512m
-ea

Jquery 코드 어시스트 적용하기

Settings » JavaScript Libraries 로가서 Jquery 라이브러리를 추가해줍니다.
그리고 Usage Scope에서 추가한 Jquery에 체크를 하면 Jquery 코드 어시스트를 사용할 수 있어요.

Blueforest 색상 세트 적용하기

루비 마인에서 기본 색상 세트를 제공하지만, 저는 Blueforest 색상 세트를 약간 수정하여 사용합니다.
아주 만족스럽네요.:D

TODO List 사용하기

Setting에서 Todo페이지를 엽니다.
TODO 패턴을 정의합니다.
Ctrl+Slash 키나 Ctrl+Divide로 주석을 만들고 todo를 입력합니다.

예제
#todo 해야할 일 목록 작성하기

루비 마인 (RubyMine)

저는 crisis, hold, todo를 정의하여 사용 하고 있습니다.
루비마인에서 자동으로 트랙킹을 해 주기 때문에,
추후에 기능을 추가할 부분에 써 놓으면 편리해요.

맥이 아니라 Textmate도 없고,
괜찮은 루비온레일즈용 개발 도구를 찾고 계시다면 루비마인 한번 고려해 보세요.:D

참고 자료

Ruby on Rails IDE :: JetBrains RubyMine

Using TODO Lists

Set/Increase Memory Available in Rubymine

A couple of tips for RubyMine performance optimization

BlueForest Color Scheme



by


Tags : , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

원하는 DIV 레이어를 간편하게 프린트 해주는 Div Print Jquery 스크립트 입니다.

이 스크립트는 두 개의 메소드를 포함하고 있습니다.
printdiv 메소드와 printdiviframe 메소드인데요.
두 출력 메소드 모두 Jquery 라이브러리가 필요하고,
print
diviframe 메소드는 JqueryUI 모듈도 필요로 합니다.
print
div는 새 창을 띄워서 바로 프린트 하고,
printdiviframe는 JqueryUI의 다이얼로그를 이용해 출력 미리보기를 제공합니다.

print_div_iframe-'Print Div Jquery Coffeescript, Javascript'

div 출력하는 커피스크립트나 자바스크립트가 필요하신 분은 가져다 쓰세요~

Div Print Jquery 스크립트 소스 다운로드



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

월풍도원이 새로워졌습니다.



레이아웃 및 색상 변경

예전 스킨-'새로워진 월풍 도원'
아마 블로그에 자주 들어오시던 분은 달라진 걸 한눈에 느끼실 겁니다.
푸른색 계통의 색상을 사용했었는데,
이번에 새 단장을 하며 주황색 계통의 색상으로 색상을 바꾸었습니다.
상단 여백도 줄였습니다.
상단 메뉴와 글꼬리에 사용한 아이콘은 Deviant art에서 활동하는 arrioch씨가 제작한 아이콘입니다.
 


광고 없는 블로그

한동안 블로그에 게시한 광고로 약간의 수입을 얻었어요.
그렇지만 광고는 저의 이념에 반대되는 요소기에 모두 지웠습니다.
강압적인 것에 심한 거부감을 느끼는 제가,
블로그에 광고를 단다는 것은 어색한 일이죠.
광고를 달면, 블로그에 오는 사람은 누구나 광고를 봐야 합니다.
꼭 필요한 정보가 광고란에 가끔 나타나기도 하지만,
대부분은 그저 가독성을 해치는 방해물일 따름입니다.
이 블로그에 들르시는 분들께 어떤 강요도 하고 싶지 않아요.
저는 자유로운 세상을 꿈꾸니까요.
 


성능 개선 / 버그 수정

즐겨찾기 버튼이 제대로 동작하지 않던 걸 수정 했습니다.
몇몇 HTML5 기술과 스키마를 적용했습니다.
메뉴 아이콘에 CSS Sprite를 적용했습니다.
관련글 보여주기 코드를 개선했습니다.
성능을 저하시키는 부분을 개선해서, 속도가 빨라졌습니다.
예전 스킨-'새로워진 월풍 도원'
위쪽이 수정 전이고, 아래가 성능 개선 후 입니다. 꽤 빨라졌죠?
 


코드 블럭 스타일 적용

코드를 올리는 경우는 많지 않지만,
가끔 코드를 올릴때 마다 보기가 안 좋았습니다.
코드 하이라이트까지 적용하면 더 보기 좋겠지만,
속도 저하를 가져오기에 코드 블럭에 간단한 스타일만 적용했습니다.


<html>
코드는 이런식으로 표현됩니다.

 


웹폰트 적용

웹폰트로 변경된 글꼴도 눈에 띄는 부분중에 하나죠?
한글에는 혜움담죽 글꼴을 적용했고,
코드 블럭에는 inconsolata 글꼴을 적용했습니다.


상단 메뉴 바 변경

예전 스킨-'새로워진 월풍 도원'
저의 창작 활동을 소개하는 월풍공방(月風工房) 메뉴가 새로이 생겼습니다.
RSS구독과 이메일 구독, 그리고 즐겨찾기 추가 메뉴에서 글씨를 삭제하고, 버튼만 달았습니다.
메뉴바 오른쪽의 검색 바에서 월풍도원의 글을 검색 할 수 있습니다.
새 창에선 글 제목을 검색하고,원래 창은 태그를 검색하여 글을 보여줍니다.


글 꼬리 변경

예전 스킨-'새로워진 월풍 도원'
예전 스킨-'새로워진 월풍 도원'
구글 버즈에 공유하기를 삭제했습니다.
본문만 깔끔하게 출력 해주는, 출력 버튼이 새롭게 생겼습니다.
출력해서 사용하고픈 글을 마음껏 출력해서 사용하세요.
무료 PDF변환기인 Bullzip PDF Printer를 이용하시면 글을 간편하게 PDF로 저장 가능합니다.:D
기부하기 버튼이 생겼습니다.
월풍도원에 기부하고픈 마음이 샘솟는다면, 혼쾌히 기부 해 주세요.
블로그 운영에 큰 도움이 됩니다.


2011년 한 해가 저물어 갑니다.
감기 조심하시고,
즐거운 연말 보내세요!



by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

지난달 구글 애드센스 광고 수익과 앞으로의 블로그 광고 정책에 대하여 말씀드립니다.

저의 블로그에 한동안 구글 애드센스를 달아 사용했습니다.
따로 맞춤 광고 설정을 하지 않아,
글과 관계가 없는 광고가 뿌려지기에 클릭 빈도가 높지 않아요.
CPC(Cost per Click) 방식으로 수익이 지급되기 때문에 수입 또한 미비합니다.
아마 맞춤 타겟 설정을 한다면 클릭 빈도가 더 높아지겠죠.

보고서-'블로그 구글 애드센스 광고 수익'

보고서를 보면 하루에 천이백 분가량의 방문자께서 광고를 보셨고,
대략 네 분이 광고를 클릭하셨습니다.
나머지 천백구십여섯 분의 방문객께는,
광고가 전혀 달갑지 않다는 말일 겁니다.
네 번의 클릭 중 실수로 누른 예도 있을 거에요.
저의 블로그에 방문하시는 분이 늘어날 수록,
광고 때문에 더 많은 분이 불편함을 감수하셔야겠죠?
독자를 불편하게 하는 블로그는 제가 지향하는 방향이 아닙니다.
광고 수익은 점진적으로 늘어나는 중이지만,
이번에 준비 중인 블로그 개편에서 광고를 삭제하기로 했습니다.
그동안 광고를 클릭해 주신 방문객 여러분, 고맙습니다.
월풍도원에서 애드센스 광고가 곧 사라질 것입니다.



by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

구글과 모빌리스에서 제공하는 웹 폰트 적용으로 블로그의 개성을 표현하세요.

블로그에서 가장 눈에 띄는 건 무얼까요?
네. 글씨입니다.
내용을 보려고 들어오니, 글씨가 가장 먼저 눈에 들어오죠.
가장 중요한 부분임에도, 개성을 표현하기가 쉽지 않습니다.
한글의 경우 굴림, 돋움, 궁서, 바탕에 맑음 고딕까지 다섯 가지 폰트가 기본으로 쓰여요.
단지 한글을 보여주는 목적에는 충분하지만, 뭔가 약간 아쉽습니다.
블로그에 변화를 주고 싶으신가요?
웹폰트를 이용해서 블로그의 개성을 표현해 보세요.

 

구글 웹 폰트

구글에서는 무려 342종의 다양한 폰트를 웹폰트로 제공합니다.

아쉽게도 아직 한글 글꼴은 제공하지 않네요.


구글 웹폰트 사용법

<head>
<link href='http://fonts.googleapis.com/css?family=웹폰트_이름' rel='stylesheet' type='text/css'>
</head>

모빌리스 웹폰트

모빌리스에서는 나눔글꼴, 혜움글꼴, 은글꼴, 백묵글꼴, 렉시글꼴, 은진글꼴을 웹폰트로 제공합니다.


모빌리스 웹폰트 사용법

<head>
<link href='http://api.mobilis.co.kr/webfonts/css/?fontface=웹폰트_이름' rel='stylesheet' type='text/css' />
</head>

스타일 시트에 웹폰트 적용 하기 (body태그에 적용하는 예제입니다.)

웹폰트 이름 뒤에는 웹 폰트를 찾지 못할 경우 사용할 폰트 이름을 넣어주세요.

예제에선 selif를 넣었습니다.

<style type="text/css">
body { font-family: '웹폰트_이름',selif; }
</style>



by


Tags : , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

구글 블로거에 관련 글 보여주기를 추가하는 방법입니다.

블로그 새단장을 준비하며, 예전에 짜 두었던 관련 글 보여주기 소스를 좀 개선했습니다.
내 블로그에서 같은 태그가 달린 글을 검색해서 관련 글로 보여줘요.
관련글 보여주기를 달기 위해선 템플릿(스킨)을 수정해야 합니다.
구글 블로거에 관련 글 보여주기를 달고 싶은 분은, 마음껏 가져다 쓰세요.:D

Head 태그 안에 다음 코드를 추가 해 줍니다.(구글 API키 필요)

<script src='http://www.google.com/jsapi?key=MYAPIKEY' type='text/javascript'/>

스타일 시트에 다음 코드를 추가 해 줍니다.

#related-side{display:none;visibility:hidden;} #related-posts{padding:15px;}

구글 블로거 템플릿에서 <data:post.body/>를 검색해서, <data:post.body/> 아래에 다음 코드를 추가해 줍니다.

<aside id="related-side">
<br/>
<h4><data:post.title/> 관련 글</h4>
<div id='related-posts'/>
</aside>
<script type='text/javascript'>
// 구글 블로거용 관련글 검색 모듈 by 月風(http://dorajistyle.pe.kr)
google.load(&quot;gdata&quot;, &quot;1.x&quot;, { packages : [&quot;blogger&quot;] });
    function getRelated() {
    function eliminateDuplicates(arr) {var i,j=0,len=arr.length,out="",obj={};for (i=0;i&lt;len;i++) {obj[arr[i]]=0;}for (i in obj) {if(j>=9)break; out+=i;j++;}return out;}   
    var relPostArray = new Array();
    var funcvar1=0;    var bloggerService = new google.gdata.blogger.BloggerService(&#39;dorajistylerelatedposts&#39;);
    var handleQueryResults = function(resultsFeedRoot) {   
    var blogFeed = resultsFeedRoot.feed;var html,postTitle,entryUri;var postEntries = blogFeed.getEntries();for (var i = 0; postEntry = postEntries[i]; i++) {var postTitle=postEntry.getTitle().getText(),entryUri=postEntry.getHtmlLink().getHref();if(title==postTitle) continue;var html= &#39;&lt;li&gt;&lt;a rel=\&#39;bookmark\&#39; title=\&#39;&#39;+ postTitle + &#39;\&#39; href=\&#39;&#39;+entryUri+&#39;\&#39;&gt;&#39;+ postTitle + &#39;&lt;/a&gt;&lt;/li&gt;&#39;;
    relPostArray.push(html);}   
    funcvar1++;    if (funcvar1 == filtArray.length) {var urlfinal=eliminateDuplicates(relPostArray);if(urlfinal.length>0){var aside=document.getElementById(&quot;related-side&quot;);aside.style.display=&#39;block&#39;;aside.style.visibility=&#39;visible&#39;;var elem=document.getElementById(&quot;related-posts&quot;);var content=&#39;&lt;ul&gt;&#39;;content+=urlfinal;content+=&#39;&lt;/ul&gt;&#39;;
    elem.innerHtml=&#39;&lt;ul&gt;&#39;;elem.innerHTML=urlfinal;elem.innerHtml+=&#39;&lt;/ul&gt;&#39;;elem.innerHtml+=content;}}
    };       
    var handleError = function(error) {};
    var tagString=&#39;&#39;;
    var labelArray = new Array();<b:loop values='data:post.labels' var='label'>
    tagString+=&quot;<data:label.name/>&quot;;
    tagString+=&#39;,&#39;
    </b:loop>       
    tagString=tagString.substring(0,tagString.length-1);
    var filtArray = tagString.split(&#39;,&#39;);var title =&#39;<data:post.title/>&#39;;
    var feedUri,query;    for (var i = 0; i &lt; filtArray.length; i++){feedUri = &#39;/feeds/posts/default/-/&#39; + filtArray[i]; query = new google.gdata.blogger.BlogPostQuery(feedUri);    bloggerService.getBlogPostFeed(query, handleQueryResults, handleError);}
    }   
    google.setOnLoadCallback(getRelated);
</script>

구글 블로거용 관련글 보여주기 모듈로, 블로그 방문자들에게 편의를 제공하세요.:D



by


Tags : , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

모질라 파이어폭스에서 Ajax 한글 키 이벤트를 처리하는 Jquery,커피스크립트 코드입니다.

모질라 파이어폭스 Ajax. 한글 키 이벤트 처리.(Jquery Mozilla Force Keyup CoffeeScript module)

저는 주 브라우저로 모질라 파이어폭스를 사용합니다.
Ajax 모듈을 만드는데, 한글을 입력하면 못 알아듣더군요.
http://javascript.info/tutorial/keyboard-events에서 키 이벤트 체크를 해 봤습니다.
한글 키가 눌리면 Keydown(Keycode=229) 이벤트가 한 번만 발생하고,
Keyup 이벤트는 발생하지 않습니다.
중국어,일본어를 테스트 해보니 이 역시 같은 현상이군요.
한글과 다름없이 229키 코드가 딱 한번 발생합니다.
아마도 다른 블록형 문자 또한 같은 이벤트를 발생 시킬 거라 예상됩니다.
모질라에서 한글 키 이벤트를 부드럽게 처리하는 커피 스크립트 모듈을 만들었어요.
모질라 파이어폭스 이용자도 한글을 편하게 쓸 권리가 있으니까요.
필요하신 분은 마음껏 가져다 쓰세요.

커피스크립트 버전(Jquery Mozilla Force Keyup module  - Coffeescript version)



  
# Mozilla Force Keyup CoffeeScript module
# by 月風(http:://dorajistyle.pe.kr)
# How to use
# mozillaForceKeyup(”inputid”)
# in HTML.
# <input id=”input
id”>
mozillaForceKeyup = (targetId) ->
  if jQuery.browser.mozilla
    isIntervalRunning = null
    target = '#'+targetId
    $(target).bind 'keydown',(e) ->
      if e.which == 229
        forceKeyup = () ->
          $(target).trigger('keyup')
        if not isIntervalRunning
          isIntervalRunning = setInterval forceKeyup, 100

    $(target).bind 'blur',(e) ->
      if isIntervalRunning
        clearInterval isIntervalRunning
        isIntervalRunning = null



자바스크립트 버전(Jquery Mozilla Force Keyup module - Javascript version)



// Mozilla Force Keyup Javascript module
// by 月風(http:://dorajistyle.pe.kr)
// How to use
// mozillaForceKeyup(”inputid”)
// in HTML.
// <input id=”input
id”>

mozillaForceKeyup = function(targetId) {
var isIntervalRunning, target;
if (jQuery.browser.mozilla) {
isIntervalRunning = null;
target = '#' + targetId;
$(target).bind('keydown', function(e) {
var forceKeyup;
if (e.which === 229) {
forceKeyup = function() {
return $(target).trigger('keyup');
};
if (!isIntervalRunning) {
return isIntervalRunning = setInterval(forceKeyup, 100);
}
}
});
return $(target).bind('blur', function(e) {
if (isIntervalRunning) {
clearInterval(isIntervalRunning);
return isIntervalRunning = null;
}
});
}
};







by


Tags : , , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

강력한 단축키 메크로를 제공하는 무료 소프트웨어 오토핫키!

단축키 종결자 오토핫키(AutoHotKey)

 

단축키용 소프트웨어로 HotKeyz를 오랫동안 이용했습니다.
윈도우에서 자주 쓰는 프로그램을 단축키로 등록해 놓고 쓰면 참 편했죠.

문장을 자동 완성하는 핫스트링 기능이 있으면, 더 편하겠다 싶어,

Phrase Express도 설치해 사용했습니다.

‘이 두 기능을 모두 지원하는 가벼운 소프트웨어가 없을까?’

검색해보니 단축키 소프트웨어가 상당히 많았어요.

그중에 강력한 기능을 제공하는 오토잇과 오토핫키를 발견했습니다.

오토핫키는 새로운 세계입니다.

윈도우 메모장에서 코딩을 하다가,

코드 하이라이팅 기능을 제공하는 에디터로 갈아탄 기분이에요.

 

단축키와 핫스트링 기능을 추가하는 방법은 아래와 같습니다.

 

단축키::Run “실행할 파일 경로”

 

모디파이어 키(Modifiers)

  • ! - Alt
  • ^ - Ctrl
  • + - SHift
  • # - Window Key

;예제 - 윈도우 키+c  (계산기가 실행됩니다)

#c::Run Calc

 

제가 쓰는 유용한 오토핫키 단축키 예제를 몇 개 더 올려볼게요.

 

;윈도우 키+h (오토핫키 재시동 단축키로, 스크립트 테스팅시 유용합니다.)

#h::

Msgbox,4,, Do you really want to reload this script?

ifMsgBox, Yes, Reload

return

 

;쉬프트+컨트롤+알트+s 키 (윈도우를 종료합니다. 컴퓨터 하루에 한번 쯤은 끄시죠?)

+^!s::Shutdown,9

 

;윈도우키+오른쪽 화살표. (즐겨 찾는 페이지를 어디서나 한방에 볼 수 있습니다.)

#Right::Run www.dorajistyle.pe.kr

 

;윈도우 왼쪽 클릭으로 복사할 문장을 드래그 해서 우클릭 하면 복사합니다.

~LButton & RButton::

Send {CTRLDOWN}c{CTRLUP}

ClipWait

return

 

;윈도우키+우클릭 (마우스 왼쪽 버튼과 오른쪽 버튼을 교환 해 줍니다.)

#RButton::

Swapped := DllCall("SwapMouseButton", Int, 0)

if Swapped = 0j

DllCall("SwapMouseButton", Int, 1)

return

 

;핫스트링

 

;d. 을 입력하면 블로그 주소가 입력됩니다.

:*:d.::http://www.dorajistyle.pe.kr

 

;dv를 입력하고 스페이스를 누르면 월풍이 입력됩니다. ㅇㅍ에서도 작동하죠.

:*:dv ::월풍

 

;영문 요일을 소문자로 입력할 경우 대문자로 바꿔 줍니다.

::monday::Monday

::tuesday::Tuesday

::wednesday::Wednesday

::thursday::Thursday

::friday::Friday

::saturday::Saturday

::sunday::Sunday

 

오토핫키로 윈도우를 좀 더 편리하게 사용하세요.:D

 

단축키 종결자 오토핫키 다운로드

 

오토핫키 명령어 목록

 

 

by 月風



by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!