PostgreSQL setting

Quick notes for Postgresql

When you upgrade your PostgreSQL

FATAL:  database files are incompatible with server
DETAIL:  The data directory was initialized by PostgreSQL version 9.3, which is not compatible with this version 9.5.1.
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

salesforce-trigger

Triggers are similar to callbacks in Ruby on Rails

Types

  • before
  • after

idea: Context variables

Trigger.New is a Context variable.
Which contains all the records the were inserted in insert or update triggers.

Trigger.Old provides the old version of sObjects before they were updated.

Triggers can fire when insert/update via API or Apex in a bulk or not.

Create a trigger

  • Maven project setting

inline

inline

inline

nginx-angular-html5mode

This code is about how to turn on the HTML5 mode on Angular js and rewrite the request on Nginx side.

Angular side

Remeber to put <base href="/"> before including any js file.

Nginx

location / {
  auth_basic "Restricted";
  auth_basic_user_file /etc/nginx/.htpasswd;  #For Basic Auth
  • try_files $uri $uri/ /index.html ; # make HTML5 workable
    +
    }

ios-table-view-controller

Assign your cell identifier, it should corresponds to the identifier in the VC

let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)

inline

aws-ses

Setting of AWS SES

Do not contain smtp in the server address Ref

email-smtp.eu-west-1.amazonaws.com ->  email.eu-west-1.amazonaws.com

nginx-cheat-sheet

Commands

  • check syntax nginx -t

Sections

  • basic auth

basic auth (Set Up Password Authentication with Nginx on Ubuntu 14.04)

install apache2-utils first

sudo apt-get install apache2-utils

cd to /etc/nginx

htpasswd -c .htpasswd deploy

Nginx.conf

server {
      listen 3000;
      server_name www.sample.co sample.co;
      location / {
          auth_basic "Restricted";
          auth_basic_user_file /etc/nginx/.htpasswd;  #For Basic Auth
      }
}

Allow direcotry browse mode

Add autoindex on;

server {
    listen      80 ;
    server_name SERVER_NAME;
    root /var/www/MEAN-development;
    location / {
     autoindex on;
    }
}

angular-course-notes

2016-08-10

https://github.com/decentcamper/MeanStackDevelopment/tree/30377_002
Sample code put in NodeJs/Tutorial3/EvneEmitterPattern
參考 EvenEmitter module
require(‘evnets’).EvenEmitter

callback 裡面千萬不要 throw exception, 因為發生exception的時候,這段block已經不再原本的stack.

Don’t throw exception in ASYNC,

Never return in CB function

  • setTimeOut 才有能力把你的code 變成 ASYNC

    [1,2,3,4,5].forEach(function(url, index){

    setTimeout(function(){
        console.log( url + "completed");
    }, 100);
    

    })

release our own package

module.export 

exports

npm add

npm publish

理解 Javascript 裡面的 event loop 異步操作的原理

2016-07-20

ES6 + Webpack 開發 Angular

xnpm install -g gulp karma karma-cli webpack

2016-07-13

利用 ng-class 動態地元件上style

ng controller for

<script>
    angular.module("exampleApp", [])
            .controller("defaultCtrl", function ($scope) {
                $scope.settings = {
                    Rows: "Red",
                    Columns: "Green"
                };
            });
</script>
<style>
    tr.Red { background-color: lightcoral; }
    tr.Green { background-color: lightgreen;}
    tr.Blue { background-color: lightblue; }
</style>
<table class="table">
    <thead>
    <tr><th>#</th><th>Action</th><th>Done</th></tr>
    </thead>
    <tr ng-repeat="item in todos" ng-class="settings.Rows">
        <td>{{$index + 1}}</td>
        <td>{{item.action}}</td>
        <td ng-style="{'background-color': settings.Columns}">
            {{item.complete}}
        </td>
    </tr>
</table>

react-course-notes

Prop 是constant 的角色, state 的子集合

所以要改變子孫的 prop, 就從最上層的 container 開始改變。

向下傳遞的除了資料流以外也可以是

one way 資料流: (dispatcher) -> (store) -> (view) -> (action) —-> (dispatcher)

ios-reading-cocoa-and-core-services

What the framework does

I think poeple are usually compare the difference between framework and libraries.

For my point of view,

A modern framework not only provides a set of useful libraries but also provides the callbacks for putting hooks on the necessary place and a MVC model for developers to develop it.

A framework is a must to separate of concerns which can ease the complexity of design.

Libraries are more like external API, we just use it, call it.

Take note for preparing Rspec test for devise

rails_helper.rb

require ‘support/request_helper’
require ‘devise’
Dir[Rails.root.join(“spec/support/*/.rb”)].each { |f| require f }

RSpec.configure do |config|

Remove this line if you’re not using ActiveRecord or ActiveRecord fixtures

config.fixture_path = “#{::Rails.root}/spec/fixtures”
config.include Devise::TestHelpers, :type => :controller
config.extend ControllerMacros, :type => :controller

Devise Token Auth

Only email confirmation feature tested for this tutorial,

In this tutorial we will validate the model Admin rather than the most common model User.

if gem devise not installel yet

rails g devise:install

Add auth for model Admin (make sure the model Admin has been created, otherwise the following generated migration table will make some troubles.)

rails g devise_token_auth:install Admin admin_auth

Gemfile

gem 'devise', '4.0.0'
gem 'devise_token_auth', '0.1.37'

Application controller (disable CSRF on JSON query)

class ApplicationController < ActionController::Base
  include DeviseTokenAuth::Concerns::SetUserByToken
  protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format.json? }  
end

model/admin.rb (in this case, I don’t need email cofirm after registering, So I take off it)

class Admin < ActiveRecord::Base
  # Include default devise modules.
  devise :database_authenticatable, :registerable,
          :recoverable, :rememberable, :trackable, :validatable,
          :omniauthable
  include DeviseTokenAuth::Concerns::User
end

Angular configuration (please refer to the route.rb)

app.config(function($authProvider) {
    $authProvider.configure({
        apiUrl: '/api/v1/',
        tokenValidationPath: '/admin_auth/validate_token',
        signOutUrl: '/admin_auth/sign_out',
        ...
        Please refer to the official documentation for the following setting
});

route.rb

namespace :api do
  namespace :v1, defaults: {format: 'json'} do
    mount_devise_token_auth_for 'Admin', at: 'admin_auth'
  end
end

Ref: https://github.com/lynndylanhurley/devise_token_auth#using-multiple-models

MySQL configuration

Forget the root password (OSX)

mysql.server stop
mysql.server start --skip-grant-tables 
mysql
mysql> use mysql;
mysql> UPDATE user SET password=PASSWORD('YOUR_NEW_PASSWORD_HERE') WHERE user = 'root';
mysql> exit;
mysql.server stop
mysql.server start

login on ubuntu

mysql -u root -p

find the pid file location

mysqladmin -uroot -p<ROOT_PASSWORD> variables | grep sock

change pid file location

edit /etc/mysql/my.cnf

socket = /tmp/mysqld.sock
pid-file = /tmp/mysqld.pid

Unable to lock ./ibdata1, error: 11

cheatsheet

- https://gist.github.com/poc7667/3850d140df135106fefcd44532f6837f

- http://blog.toright.com/posts/1145/mysql-%E6%94%B9-root-%E5%AF%86%E7%A2%BC%E5%BF%85%E5%8B%9D%E6%96%B9%E6%B3%95%EF%BC%88%E7%AD%86%E8%A8%98%EF%BC%89.html

SUBURI setting on Rails with Nginx

ENV

  • ENV[‘RAILS_RELATIVE_URL_ROOT’]=/browse/

routes.rb

scope ENV['RAILS_RELATIVE_URL_ROOT'] do
    get 'browse/category_detail'
    get '*path' => redirect('/')
end

application.rb

class Application < Rails::Application
  config.relative_url_root = ENV['RAILS_RELATIVE_URL_ROOT']
end

Error in production log

I, [2015-10-20T07:07:15.956058 #30522]  INFO -- : Started GET "/" for 127.0.0.1 at 2015-10-20 07:07:15 +0000
F, [2015-10-20T07:07:15.957575 #30522] FATAL -- :
ActionController::RoutingError (No route matches [GET] "/"):

nginx.conf

server {
        listen 443;
        server_name WEBSITE.COM;
    location /browse {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://unix:/tmp/puma.broswe.sock:/;
    }
}%

AWS

  • add another aws configure

eg: assign a new profile name

aws configure –profile ezfly

  • use direnv to load a different aws profile
  • ssh login without pem file

open /etc/ssh/sshd_config

Before

PasswordAuthentication no

After

PasswordAuthentication yes

change PasswordAuthentication no to PasswordAuthentication yes

JS debugger CheatSheet

Embed errorception into your website

You’ll never know where an exception happens on the client side.

JS除錯第三方的好工具,客戶端的環境千百種,靠開發窮舉測試幾乎是不可能的任務。

Simply illustrate how to install it on an Angular js project.

Put the snippet at the every page’s header section.
Make it be executed as soon as possible.

Avoid included jQuery pollutes global jQuery

先前遇到了一個問題,我用 require.js build 一個 js plugin

想不到在客戶的網站裡面,因為該客戶已經 include 一個非常舊版本的 jQuery
然後被我包出來的 plugin 裡面自帶(self-included) 蓋掉,

導致對方的其他 scripts 接連受影響。

This post tells how to avoid polluting the existing global jquery with your require.js project.

Create a file under project root require_no_conflict_jquery.js

define( ["jquery"], function(jq) {
    // Raw jQuery does not return anything, so return it explicitly here.
    return jQuery.noConflict( true );
} );

app.main.js

requirejs.config({
    paths: {
        jq_no_conflict: "require_no_conflict_jquery",
        jquery: "./vendor/js/jquery-2.1.1.min",
    },
    map: {
        '*': {
            'jquery': 'jq_no_conflict'
        },
        'jq_no_conflict': {
            'jquery': 'jquery'
        }
    },

app.build.js

{
    mainConfigFile: 'app.main.js',
    out: "../js/dadasay.noJQConflict.min.js",
    optimize: "none",
    preserveLicenseComments: false,
    wrap: true,
    paths: {
        requireLib: './require'
    },
    include: [ 'requireLib', 'app.main.js' ],
    // insertRequire: ["app.main"],
}

#Build it

r.js -o app.build.js

pry-console-cheetsheet

edit .pryrc

enable tabular format on query

add these to .pryrc

require 'hirb'
Hirb.enable
Pry.config.print = proc do |output, value|
  Hirb::View.view_or_page_output(value) || Pry::DEFAULT_PRINT.call(output, value)
end

paperclip with s3

Requirements

aws-sdk version should < 2.0

Gemfile

gem "paperclip"
gem 'aws-sdk', '< 2.0'
# http://stackoverflow.com/questions/28374401/nameerror-uninitialized-constant-paperclipstorages3aws

AWS S3 (Ruby) Cheat sheet

rails-cheat-sheet

If rb-readlin not working, you can not type double chars in your console , try this

CONFIGURE_OPTS=”–disable-install-doc –with-readline-dir=/usr/local/opt/readline” rbenv install 2.3.1

  • new Model

    rails g model Bank name:string description:text

Strong params

Params

{"product"=>
  {"id"=>9,
   "specs"=>
    [{"type"=>"text", "value"=>"price"},
     {"type"=>"float", "value"=>"description"},
     {"type"=>"text", "value"=>"我好帥"}],
     ...

Whielist SPECS params (JSON format)

def product_params
  params.require(:product).permit(
    :name,
    :specs => [:type, :value]
  )
end

Many to Many

Generate migration, remember the params should be real name of data table

rails generate migration CreateJoinTableLoanPlanCareer loan_plans careers

JSON API

json.extract! @loan_plan, :id,
json.careers @loan_plan.careers do |t|
    json.id t.id
    json.name t.name
    json.description t.description
end

Sanitize Nested params

Raw params

 "loan_plan" => {
                  "id" => 32,
             "careers" => [
        [0] {
                     "id" => 8,
                   "name" => "police officer123434",
            "description" => "Tattooed vinyl jean shorts irony. Iphone wolf kinfolk austin venmo semiotics authentic slow-carb. Farm-to-table poutine letterpress asymmetrical hammock microdosing. 3 wolf moon viral offal portland."
        },
        [1] {
                     "id" => 9,
                   "name" => "engineer",
            "description" => "Wes anderson polaroid jean shorts meggings etsy roof listicle 90's. Tote bag plaid green juice. Microdosing 8-bit austin migas."
        }
    ]
},

You want to preserve careers with IDs, the syntax is strange, somehow this is the Rails way :(

def loan_plan_params
  params.require(:loan_plan).permit(
    :id, 
    {:careers=>:id}
  )
end

Rspec

RSpec examples

https://github.com/eliotsykes/rspec-rails-examples
https://gist.github.com/kyletcarlson/6234923
https://www.anchor.com.au/wp-content/uploads/rspec_cheatsheet_attributed.pdf

Enable should syntax

config.expect_with :rspec do |c|
  c.syntax = [:should, :expect]
end

Migration

Add field

rails generate migration add_specs_to_products specs:json

Rollback

rake db:migrate:status
rake db:rollback STEP=1

Migration for belong_to and has_many

rails g model LoanPlan bank:references name:string description:text lowerbound_rate:float upperbound_rate:float payment_fee:float start_date:datetime end_date:datetime min_lease:integer max_lease:integer min_installments:integer max_installments:integer min_loan_amount:float max_loan_amount:float

Generator

With namespace

rails g controller Admin::Dashboard index create delete

Api generator

rails g model Post title:string body:string
rake db:migrate
rails generate scaffold_controller api/Post --model-name=Post

paperclip

add logo_image to model Bank

rails generate paperclip Bank logo_image

Factory girls

make mock data to accelerate test performance

利用

annotate

It will append the fields/asttribute to your model files.

  • rails g annotate:install
  • rake annotate_models

spec/models/bank_spec.rb

it "assign bank name" do
  bank = FactoryGirl.create(:bank)
  bank.update_attribute(:name, "ChinaTrust")
  bank.name.should eql("ChinaTrust")
end

##factories/bank_factory.rb

FactoryGirl.define do
  factory :bank do
  end
end

exception handling practice - extract exception block

Ruby better exception handling

We need to clean the raw string and fetch some crudential toks.

However, the similar operations will scatters in differenct children scripts.

Put begin-exception in each get_locations method is so annoying.

We could try to extract the begin-exception block into the common function parse_matches

Before

child_a.rb

def get_locations(line)
  begin
      get_modifier(line)[1].split("/").last.split
  rescue Exception => e
      []
  end
end

def get_modifier(line)
  parse_matches(line.scan(/(\[)(.*?)(\])/))
end

child_b.rb

def get_locations(line)
  begin
      get_modifier(line)[2].split("/").first.split
  rescue Exception => e
      []
  end
end

def get_modifier(line)
  parse_matches(line.scan(/(\[)(.*?)(\])/))
end

parent.rb

def parse_matches(matchers, &block)
  rtn = (matchers) ? matchers.first : []
end

After

child_a.rb

def get_locations(line)
    get_modifier(line)[1].split("/").last.split
end

def get_modifier(line)
  parse_matches(line.scan(/(\[.*?\])/)) do |rtn|
    rtn[0].split("/")[1].split
  end
end

child_b.rb

def get_locations(line)
  get_modifier(line)[2].split("/").first.split
end

def get_modifier(line)
  parse_matches(line.scan(/(\[.*?\])/)) do |rtn|
    rtn[0].split("/")[1].split
  end
end


def parse_matches(matchers, &block)
  rtn = (matchers) ? matchers.first : []
  begin
    block.call(rtn)
  rescue Exception => e
    []
  end
end

angular interacts with DOM and FB plugin

最近需要讓 Angular 與 FB share button 互動,

想要達成的目標是當我的 URL 一有更動, FB share button 的連結(href) 也要跟著動。

cheatsheet

FB.XFBML.parse(); // 重新render, compiple FB button plugin
$location.$$absUrl, $location.url() 拿到你當前的 url

// compile 新的 DOM 元件
$('#quick_search_btn').append($compile(share_btn_dom)($rootScope));

// 放到 $timeout 避免遇到跟正在進行 digest phase conflict 的issue
$timeout(function(){
   $rootScope.$apply();
 });

Invaliad Pattern

一開始我嘗試要在 app.run 裡面綁一個 $locationChangeSuccess callback,

然後 remove 原本的 fb btn dom, 再 insert 新的 fb btn dom,

遺憾的是,完全沒有反應 (這邊我推測我違反了 Angular data flow 的 life cycle 所以會一點作用都沒有)

Facebook

$scope.fbShareBtnTemplate = '<div class="fb-share-button" data-href="'+ targetUrl+ '" data-layout="icon_link" data-mobile-iframe="true""> </div> '

Leetcode notes (medium)

https://leetcode.com/problems/missing-number/

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
利用bit xor 求解

https://leetcode.com/problems/reverse-string/

Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".

class Solution(object):
    def reverseString(self, s):
       return s[::-1]

gulp

inline

“PATH_INFO”=>”/portal/run@http://10.0.0.44:3000/portal/index.html“,
“REMOTE_ADDR”=>”10.0.0.42”,
“puma.socket”=>#,
“rack.hijack?”=>true,
“rack.hijack”=>#,
“rack.input”=>#,
“rack.url_scheme”=>”http”,
“rack.after_reply”=>[],
“ORIGINAL_FULLPATH”=>”/portal/run@http://10.0.0.44:3000/portal/index.html“,

UNEXPECTED_PATH_PREFIX = “/portal/run@”
if UNEXPECTED_PATH_PREFIX in env[“PATH_INFO”]
env[“PATH_INFO”].gsub!(UNEXPECTED_PATH_PREFIX,””)
end
“PATH_INFO”

“ORIGINAL_FULLPATH”=>”/portal/run@http://10.0.0.44:3000/portal/index.html“,

def call(env)
host = env["HTTP_HOST"]
# ["PATH_INFO", "ORIGINAL_FULLPATH", "REQUEST_URI"].each do |item|
["REQUEST_PATH", "REQUEST_URI", "ORIGINAL_FULLPATH", "PATH_INFO"].each do |item|
  if env[item].include? host
    start_of_pos = env[item].rindex(host)+host.length
    env[item] = env[item][start_of_pos..-1]
    if env[item].end_with? "/portal/index.html"
      env[item]="/"
    end
  end
end

["REQUEST_PATH", "REQUEST_URI",
  "HTTP_REFERER","SERVER_NAME", "SERVER_PORT",
  "ORIGINAL_FULLPATH", "PATH_INFO"].each do |k|
    ap("#{k}:#{env[k]}")
end

ap(env)
# binding.pry if env["REQUEST_PATH"].include? "/portal/index.html"

@status, @headers, @response = @app.call(env)
[@status, @headers, @response]

end

angular-cheatsheet

Show un-safe string as HTML

Add a filter

angular
    .module('altairApp').filter('unsafe', function($sce) {
    return function(val) {
        return $sce.trustAsHtml(val);
    };
});

In the view

<p ng-bind-html="product.description | unsafe"></p>

Dropdown selection: single and multiple choice

single choice

pitfalls

<ui-select ng-model="user_profile.career" theme="bootstrap" required="true">
<ui-select-match > {{$select.selected.name}} </ui-select-match>
<ui-select-choices repeat="option in selectOptions.career | propsFilter: {name: $select.search} ">
<div ng-bind-html="option.name | highlight: $select.search"></div>
</ui-select-choices>
</ui-select>

multiple choice

pitfalls

multiple,

<ui-select multiple ng-model="loan_plan.careers" theme="bootstrap" ng-disabled="disabled">
<ui-select-match > {{$item.name}} </ui-select-match>
<ui-select-choices repeat="option in careersOptions | propsFilter: {name: $select.search} ">
<div ng-bind-html="option.name | highlight: $select.search"></div>
<small>
<span ng-bind-html="''+ option.description | highlight: $select.search"></span>
</small>
</ui-select-choices>
</ui-select>

DEBUG skill

Check the existence of service on the console

injector = angular.element(document.body).injector()
injector.get(‘ServiceName’)
angular.js:68 Uncaught Error: [$injector:unpr] Unknown provider: ServiceNameProvider <- ServiceName(…)(anonymous function) @ angular.js:68(anonymous function) @ angular.js:4289getService @ angular.js:4437(anonymous function) @ angular.js:4294getService @ angular.js:4437(anonymous function) @ VM168822:1InjectedScript._evaluateOn @ (program):878InjectedScript._evaluateAndWrap @ (program):811InjectedScript.evaluateOnCallFrame @ (program):936(anonymous function) @ banks.js:2

RESTful

success callback

error callback

angular resource RESTful

type 1: Controller

app.controller('ProductIndexCtrl',
    function($scope, $resource, $q, $stateParams, productService) {
        $q.all([
            productService.query({
                product_id: $stateParams.id
            }).$promise

Update

productService.update({product_id: product_id},{product: product})

Create

productService.create({},{product: product})

type 1: Service

angular.module('productModule', [])
    .service('productService', function($resource, $http) {
            var product = $resource('/api/v1/products/:product_id', {
                product_id: '@product_id',
            }, {
                 update: { method:'PUT' },
                 create: { method: 'POST' },
                 delete: { method: 'DELETE'}
            });
            return product;
        }
    );

type 2: controller

app.controller('BanksBaseCtrl', function($scope, $resource, $q, bankService, $auth, $http) {
    $scope.BankService = new bankService();
});

app.controller('BanksIndexCtrl', function($rootScope, $scope, $http, $resource, $q, bankService, $auth) {
      $q.all([$scope.BankService.all().$promise]).then(function(ret){
        $scope.banks = ret[0]
    }
});

type 2(Verbosed mode): Service side

angular.module('bankModule', [])
    .service('bankService', function($resource, $http) {
        var Bank;
        return Bank = (function() {
            function Bank(BankListId, errorHandler) {
                var defaults;
                this.service = $resource('/api/v1/banks/:id',
                {
                    id: '@id'
                },
                {
                    update: {method: 'PUT'},
                    delete: { method: 'DELETE', params: {id: '@id'} },
                    create: { method: 'POST', params: {bank: '@bank'} }
                });
                this.errorHandler = errorHandler;
                defaults = $http.defaults.headers;
                defaults.patch = defaults.patch || {};
                defaults.patch['Content-Type'] = 'application/json';
            }
            Bank.prototype.all = function() {
                return this.service.query((function() {
                    return null;
                }), this.errorHandler);
            };
            Bank.prototype.create = function(bank) {
                return new this.service({
                    Bank: bank
                }).$create((function() {
                    return null;
                }), this.errorHandler);
            };
            Bank.prototype.update = function(bank, bank_id) {
                return new this.service({
                    Bank: bank
                }).$update({
                    id: bank_id
                }, (function() {
                    return null;
                }), this.errorHandler);
            };
            Bank.prototype.get = function(id){
                return this.service.get({id: id}, (function() {
                    return null;
                }), this.errorHandler);
            }
            Bank.prototype.delete = function(id){
                return this.service.delete({id: id}, (function() {
                    return null;
                }), this.errorHandler);
            }
            return Bank;
        })();
    });

angular-pattern

  • Router ‘/app/dashboard-v1’ -> State ‘app.dashboard-v1’
  • Router ‘/app/ui’ -> State ‘app.ui’

snippet

$urlRouterProvider
    .otherwise('/app/dashboard-v1');
$stateProvider
    .state('app.ui', {
        url: '/ui',
        template: '<div ui-view class="fade-in-up"></div>'
    })
    .state('app.ui.buttons', {
        url: '/buttons',
        templateUrl: 'tpl/ui_buttons.html'
    })

ui-router的状态

參考 http://blog.csdn.net/mooner_guo/article/details/42459861

Parent state 以及 children state 依靠 “.” 區分 namespace

question : patent state
question.init.attention.text : 子狀態children state

$stateProvider.state('question',{     //母模块
          ....
    }).state('question.init.attention.test',{       //子状态1  显示view1
            url:"/test",
      views:{
          /*'first':{
              template:'<div>first</div>'
          },*/
          'second':{
              template:'<div>second</div>'
          }
   }).state('question.init.attention.test',(        //子状态2 显示view2
             url:"/test2",
      views:{
          'first':{
              template:'<div>first</div>'
          }
          /*'second':{
              template:'<div>second</div>'
          }*/
      }
   )}.state('question.init.attention.test',{       //子状态3    显示view1,view2
       url:"/test2",
      views:{
          'first':{
              template:'<div>first</div>'
          }
          'second':{
              template:'<div>second</div>'
          }
      }
  });

Abstract

Abstract - {boolean=} - An abstract state will never be directly activated, but can provide inherited properties to its common children states.

$stateProvider
    .state('loan', {
        abstract: true,
        url: '/loan',
        templateUrl: 'tpl/app.html'
    })
    .state('loan.loan_manager', {
        // abstract: true,
        url: '/loan_manager',
        templateUrl: 'tpl/ui_buttons.html'
    })

gulp

// const build = require(“public/plugin/v1/src/build_cfg.js”);

// gulp.task(“build”, function (callback) {
// build({ some: “public/plugin/v1/src/“ },
// callback);
// });

// rjs({
//     name: 'main',
//     baseUrl: 'dist/js',
//     out: 'carecadets.min.js'
// })

gulp.task(‘build-plugin’, function(){
rjs({
name: “main”,
baseUrl: export_cfg.src_dir,
findNestedDependencies: true,
include: true,
wrap: true,
removeCombined: true,
allowSourceOverwrites: true,
preserveLicenseComments: false,
// paths: {
// requireLib: ‘./require’
// },
out : export_cfg.name
})
.pipe(gulp.dest(export_cfg.dir));

})
gulp.task(‘minify_plugin_js’,function(){
gulp.src(v1_assets.js)
.pipe(amdOptimize(“main”,{
configFile: v1_assets.require_manifest_file,
findNestedDependencies: true,
wrap: true,

    include: true
}))
// .pipe(uglifyJS())
.pipe(concatFile('dadasay.min.js'))
.pipe(gulp.dest('public/plugin/v1/js'));

})

python-crawler-notes

記錄 Python 爬蟲的零碎筆記

Create a requests object with session

有時候需要 session 去記錄每一步 request , Server回傳給我們的 response (header, cookie)

import requests

angular xeditable

In-Place editor

remember to load the xeditable module into your controller

$stateProvider
    .state('admin', {
        abstract: true,
        url: '/admin',
        templateUrl: "admin_tpl/app.html"
    })
    .state('admin.banks', {
        url: '/banks',
        template: '<div ui-view class="fade-in"></div>',
        controller: 'BankCtrl',
        resolve: load(['xeditable', 'js/controllers/banks.js'])
    })

Trace

js/controllers/xeditable.js

app.controller('XeditableCtrl', ['$scope', '$filter', '$http', 'editableOptions', 'editableThemes', 
  function($scope, $filter, $http, editableOptions, editableThemes){
    editableThemes.bs3.inputClass = 'input-sm';
    editableThemes.bs3.buttonsClass = 'btn-sm';
    editableOptions.theme = 'bs3';

    $scope.html5 = {
      email: 'email@example.com',
      tel: '123-45-67',
      number: 29,
      range: 10,
      url: 'http://example.com',
      search: 'blabla',
      color: '#6a4415',
      date: null,
      time: '12:30',
      datetime: null,
      month: null,
      week: null
    };

    $scope.user = {
        name: 'awesome',
        desc: 'Awesome user \ndescription!',
      status: 2,
      agenda: 1,
      remember: false
    }; 

    $scope.statuses = [
      {value: 1, text: 'status1'},
      {value: 2, text: 'status2'},
      {value: 3, text: 'status3'}
    ];

    $scope.agenda = [
      {value: 1, text: 'male'},
      {value: 2, text: 'female'}
    ];

    $scope.showStatus = function() {
      var selected = $filter('filter')($scope.statuses, {value: $scope.user.status});
      return ($scope.user.status && selected.length) ? selected[0].text : 'Not set';
    };

    $scope.showAgenda = function() {
      var selected = $filter('filter')($scope.agenda, {value: $scope.user.agenda});
      return ($scope.user.agenda && selected.length) ? selected[0].text : 'Not set';
    };

    // editable table
    $scope.users = [
      {id: 1, name: 'awesome user1', status: 2, group: 4, groupName: 'admin'},
      {id: 2, name: 'awesome user2', status: undefined, group: 3, groupName: 'vip'},
      {id: 3, name: 'awesome user3', status: 2, group: null}
    ];

    $scope.groups = [];
    $scope.loadGroups = function() {
      return $scope.groups.length ? null : $http.get('api/groups').success(function(data) {
        $scope.groups = data;
      });
    };

    $scope.showGroup = function(user) {
      if(user.group && $scope.groups.length) {
        var selected = $filter('filter')($scope.groups, {id: user.group});
        return selected.length ? selected[0].text : 'Not set';
      } else {
        return user.groupName || 'Not set';
      }
    };

    $scope.showStatus = function(user) {
      var selected = [];
      if(user && user.status) {
        selected = $filter('filter')($scope.statuses, {value: user.status});
      }
      return selected.length ? selected[0].text : 'Not set';
    };

    $scope.checkName = function(data, id) {
      if (id === 2 && data !== 'awesome') {
        return "Username 2 should be `awesome`";
      }
    };

    $scope.saveUser = function(data, id) {
      //$scope.user not updated yet
      angular.extend(data, {id: id});
      // return $http.post('api/saveUser', data);
    };

    // remove user
    $scope.removeUser = function(index) {
      $scope.users.splice(index, 1);
    };

    // add user
    $scope.addUser = function() {
      $scope.inserted = {
        id: $scope.users.length+1,
        name: '',
        status: null,
        group: null 
      };
      $scope.users.push($scope.inserted);
    };

}]);

Reference

http://jsfiddle.net/christianacca/gpgD4/

commands-snippets

Replace of a string recursively under a specific folder

if the string contains double quote " you should escape it by backslash

This example will replace version: "0.0.2" to version: "1.0.0"

find <SPECIFIC_FOLDER> -type f -print0 | xargs -0 sed -i '' 's/version: \"0.0.2/version: \"1.0.0/g'

Rails bootstrap

new project

rails new AlphaLoan -d mysql

add-spring-guard-to-rails-app

open up Gemfile, add these gems

group :development do
  gem 'guard-rspec'
  gem 'spring-commands-rspec'
  gem 'spring'
end

install guard for rspec guard init rspec

about sprint server

run guard service, rails g

Nginx uwsgi deployment notes

We’re going to show how to ind

Firstly, run setup requirements recipe for instaling required packages

I am used to using capistrano for auto deployment

Install the deployment config files under project folder
>
cap install

Because the deployment files could be large,

I won’t put them under root disk to avoid no space on the disk issue,

I usually mount a external disk and deploy onto it.

mount the external disk to /workspace
mkdir /workspace/deploy_workspace

I usually put all the deploy

Avoid to run out of the root disk volume space,

We should change the DB datastore location to external disk.

Please refer to this snippet for setting up MongoDB

最好把python 相關的 packages 以 system 的方式安裝
因為 Foreman 在執行的時候不會 跑 pyenv 的 python 而是 system python