阅读视图

发现新文章,点击刷新页面。
🔲 ☆

SQL 转换 elasticsearch

select * from visits where visitable_id=22362 or os is not null;
{
  "query": {
    "bool": {
      "must": [{
        "term": {
          "visitable_id": "22362"
        }
      }],
      "must": [{
        "exists": {
          "field": "os"
        }
      }],
      "should": []
    }
  },
  "from": 0,
  "size": 10,
  "sort": [],
  "aggs": {}
}
select * from visits where visitable_id=22362 AND os is not null;
{
  "query": {
    "bool": {
      "must": [{
        "term": {
          "visitable_id": "22362"
        }
      },{
        "exists": {
          "field": "os"
        }
      }],
      "should": []
    }
  },
  "from": 0,
  "size": 10,
  "sort": [],
  "aggs": {}
}
select os,count(os)  from visits where visitable_id = 22362 and os is not null group by os
select browser,count(browser) from visits where visitable_id = 22362 and os is not null group by browser
select device_type,count(device_type) from visits where visitable_id = 22362 and os is not null  group by device_type


{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "visitable_id": "22362"
          }
        },
        {
          "exists": {
            "field": "os"
          }
        }
      ],
      "should": []
    }
  },
  "aggs": {
    "os": {
      "terms": {
        "field": "os.keyword"
      }
    },
    "browsers": {
      "terms": {
        "field": "browser.keyword"
      }
    },
    "device_type": {
      "terms": {
        "field": "device_type.keyword"
      }
    }
  }
}

ref: https://stackoverflow.com/questions/39113842/elastic-search-count-with-group-by-and-where-condition

Ref: https://stackoverflow.com/questions/14745210/create-elasticsearch-curl-query-for-not-null-and-not-empty http://railscasts.com/episodes/307-elasticsearch-part-2

🔲 ⭐

mackup configuration_files备份文件的问题

在mackup上,估计很多人也碰到同样的问题 applications_to_sync 不工作 mackup的文件坑了

下面的方法可以支持备份指定的文件。

第一步

vi .mackup/custom-env-file.cfg

[application]
name = custom-env-file

[configuration_files]
.gitignore_global
.gitconfig

第二步

vi .mackup.cfg

[applications_to_sync]
custom-env-file

就可以功能发同步了。

mackup backup

ref: https://github.com/lra/mackup/issues/869#issuecomment-249528570

🔲 ⭐

Let’s Encrypt免费的https证书

申请Let's Encrypt 免费https证书脚本。他的证书有效期只有90天,但是可以用自动化脚本继约,所以还是不很错的选择。

1. letsencrypt.sh证书的生成

1.1 目录的生成

cd ~
git clone https://github.com/lukas2511/letsencrypt.sh

sudo mkdir -p /etc/letsencrypt.sh
sudo mkdir -p /var/www/letsencrypt.sh

sudo chown `whoami` -R /var/www/letsencrypt.sh
sudo chown `whoami` -R /etc/letsencrypt.sh

cp ~/letsencrypt.sh/docs/examples/config /etc/letsencrypt.sh/config
cp ~/letsencrypt.sh/docs/examples/domains.txt /etc/letsencrypt.sh/domains.txt

1.2 修改letsencrypt.sh配置

vi /etc/letsencrypt.sh/config

BASEDIR="/etc/letsencrypt.sh/"
WELLKNOWN="/var/www/letsencrypt.sh/"

vi /etc/letsencrypt.sh/domains.txt

91any.com www.91any.com

1.3 修改nginx的配置

server {
  listen 80;
  ....

  location /.well-known/acme-challenge {
    allow all;
    alias /var/www/letsencrypt.sh/;
  }
  ...
}

在生成的证书的时候,需要确认域名的有效性如: http://foo.com/.well-known/acme-challenge/xxxxxxx_xxxxx

修改完了nginx的配置需要重启.

sudo /etc/init.d/nginx configtest
* Testing nginx configuration              [OK ]

sudo /etc/init.d/nginx reload
 * Reloading nginx configuration nginx     [ OK ]

1.4 执行生成ssl证的脚本

~/letsencrypt.sh/letsencrypt.sh -c

## INFO: Using main config file /etc/letsencrypt.sh/config
+ Generating account key...
+ Registering account key with letsencrypt...
Processing 91any.com with alternative names: www.91any.com
 + Signing domains...
 + Creating new directory /etc/letsencrypt.sh/certs/91any.com ...
 + Generating private key...
 + Generating signing request...
 + Requesting challenge for 91any.com...
 + Requesting challenge for www.91any.com...
 + Responding to challenge for 91any.com...
 + Challenge is valid!
 + Responding to challenge for www.91any.com...
 + Challenge is valid!
 + Requesting certificate...
 + Checking certificate...
 + Done!
 + Creating fullchain.pem...
 + Done!

说明生成功完必了。接下来让配置ssl证到nginx中

2. 配置ssl证到nginx

$ sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048

2.1 nginx的配置

sudo vi /etc/nginx/sites-enabled/qiangda_production

server {
  listen 80;
  listen       443 ssl;
  ## listen 443 ssl http2;
  listen       [::]:443 ssl;

  ssl on;
  ssl_certificate /etc/letsencrypt.sh/certs/91any.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt.sh/certs/91any.com/privkey.pem;

  ssl_dhparam /etc/ssl/certs/dhparam.pem;
  ssl_session_cache shared:SSL:10m;
  ssl_session_timeout 10m;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;## omit SSLv3 because of POODLE (CVE-2014-3566)
  ssl_stapling on;
  ssl_ciphers "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA";
  ssl_prefer_server_ciphers on;
  add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";

}

2.1 测试脚本并重启nginx

#可以测试具体哪一行出问题。
sudo nginx -c /etc/nginx/nginx.conf -t
sudo /etc/init.d/nginx restart

yeah!!! 打开成功了。

接下来配置每个月更新一次证书。

3. 添加自动更新的脚本。

mv ~/letsencrypt.sh /etc/letsencrypt.sh/

vi /etc/letsencrypt.sh/auto-renew.sh

/etc/letsencrypt.sh/letsencrypt.sh/letsencrypt.sh -c
sudo service nginx reload
  • 把脚本改为可执行
chmod 777 /etc/letsencrypt.sh/auto-renew.sh
  • 把默认的nano改成vim.如果你喜欢nano的话跳过这一步。

vim ~/.selected_editor

SELECTED_EDITOR="/usr/bin/vim.tiny"
  • 添加日志目录
mkdir -p /etc/letsencrypt.sh/log

crontab -e

1 0 1 * * /etc/letsencrypt.sh/auto-renew.sh >> /etc/letsencrypt.sh/log/lets-encrypt.log 2>&1

重下cron的服务

sudo service cron restart

搞定!

🔲 ⭐

根据IP选择ruby source

开发必备翻墙。但生产服务器是放在国内,那么问题就来啦!

Gemfile中的source写哪里的?

  source 'https://rubygems.org'
  source 'http://ruby.taobao.org'

切换国外的时候跑 https://rubygems.org

切换国内的时候跑 http://ruby.taobao.org

难道还要每次手工改不成?

在想能不能自动辨别!

  1. 不过也可vpn上做一个国内外分流 (不过当前不使用此方法)
  2. 自建源智能跳转 ruby.growcn.com

nginx中的配置 ruby_mirror.conf

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allow_visit {
  default other;
  CN cn;
}

server {
  server_name ruby.growcn.com;
  location ~ /\.git {
      deny  all;
  }

  if ($allow_visit = cn) {
    rewrite ^(.*) http://ruby.taobao.org$1 permanent;
  }

  if ($allow_visit = other) {
    rewrite ^(.*) https://rubygems.org$1 permanent;
  }
}

这时候: 国内IP打开 http://ruby.growcn.com 就到 http://ruby.taobao.org 国外IP打开 http://ruby.growcn.com 就到 https://rubygems.org

好!Gemfile可以写成

source 'http://ruby.growcn.com'

bundle

搞定!

参阅

🔲 ⭐

创建MacOSX Yosemite的USB安装盘

官方发mail过来的技术支持

陈先生 您好,

感谢您联系Apple。

重装步骤:

- 在现有系统制作OS 10.10的安装U盘。下面是制作的教程文档链接:

https://support.apple.com/zh-cn/HT201372

- 您只要现在App Store中下载好Yosemite安装包,然后注意文档中的示例部分即可,

1. 先进入终端。
2. 输入 sudo -i开启管理员模式
3. 输入管理员密码(直接输入,界面不会显示出来输入的内容)
4. 输入文档中得命令行
5. sudo /Applications/Install\ OS\ X\ Yosemite.app/Contents/Resources/createinstallmedia --volume /Volumes/你U盘的名字 --applicationpath /Applications/Install\ OS\ X\ Yosemite.app
6. 如果输入成功,会问你是否要继续,输入Y,然后按回车。之后等待就可以了

在实际中碰到的问题

如果遇到这个报错的话!

grayson:~ root#  sudo /Applications/Install\ OS\ X\ Yosemite.app/Contents/Resources/createinstallmedia --volume /Volumes/NO\ NAME --applicationpath /Applications/Install\ OS\ X\ Yosemite.app
Ready to start.
To continue we need to erase the disk at /Volumes/NO NAME.
If you wish to continue type (Y) then press return: y
Erasing Disk: 0%... 10%...
Error erasing disk error number (-69874, 0)
A error occurred erasing the disk.

如果报这个错。那么需要用Disk Utility重新格式化下U盘

这一步搞定以后!就不会报错了!Error erasing disk error number (-69874, 0)

grayson:~ root#  sudo /Applications/Install\ OS\ X\ Yosemite.app/Contents/Resources/createinstallmedia --volume /Volumes/Untitled --applicationpath /Applications/Install\ OS\ X\ Yosemite.app
Ready to start.
To continue we need to erase the disk at /Volumes/Untitled.
If you wish to continue type (Y) then press return: Y
Erasing Disk: 0%... 10%... 20%... 30%...100%...
Copying installer files to disk...
# 这个时候会很长时间,要做的事,就是耐心等待

Copy complete.
Making disk bootable...
Copying boot files...
Copy complete.
Done.

参阅

🔲 ☆

rails capistrano3发布时assets的优化

发布代码(cap production deploy),如果app/assets/没有代码变化,就跳过assets:precompile !

namespace :deploy do
  # https://gist.github.com/5b3471d17b8ced329832
  Rake::Task["deploy:compile_assets"].clear_actions
  task :compile_assets => [:set_rails_env] do
    run_locally do
      if capture("git --no-pager diff #{fetch(:previous_revision)} #{fetch(:current_revision)} app/assets vendor/assets").empty?
         info "Skipping assets compilation"
      else
        invoke 'deploy:assets:precompile'
        invoke 'deploy:assets:backup_manifest'
      end
    end
  end
end
🔲 ☆

AngularJS on Rails 4.1.5 - Part 2 待译

第一部用Rails创建的API实例!

如何获取第一部的方式如下:

$ git clone https://github.com/growcn/angular_casts $ cd angular_casts/angular_casts_part_1 $ bundle install $ rake db:migrate; rake db:migrate RAILS_ENV=test $ rake test $ rake screencast_sync:railscasts

添加AngularJS类

There are a couple of different ways we can add Angular into our application. Ryan Bates suggests using the angular-rails gem. Even though this is an excellent gem which is well maintained, it's good to know how to do this without a gem.

In our app we are going to link our scripts using a CDN. We can find the CDN for Angular at https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js. We will also be adding Angular Resource via the CDN as well.

修改你的layout文件:

{% raw %} ``` html app/views/layouts/application.html.erb <!DOCTYPE html>

Angular Casts <%= stylesheet_link_tag "application", media: "all" %> <%= csrf_meta_tags %>

<%= yield %>

<%= javascript_include_tag "application" %>

{% endraw %}

### Setup the Javascript Folders

We want to keep our code organized by placing our Angular controllers, filters, services, directives, etc. in the app/assets/javascripts folder. Create the following directories:

* app/assets/javascripts/angular/controllers
* app/assets/javascripts/angular/directives
* app/assets/javascripts/angular/services

Here's a shortcut to do this:

    $ mkdir -p app/assets/javascripts/angular/controllers \
               app/assets/javascripts/angular/directives \
               app/assets/javascripts/angular/services

Now let's create the main javascript file which will drive our Angular application.

``` coffeescript app/assets/javascripts/app.js.coffee
window.App = angular.module('AngularCasts', ['ngResource'])

In this file we create a new module called AngularCasts and assign it to window.App. We also add the dependency of ngResource which provides simple REST client functionality.

Next, we need to update our JavaScript manifest to include our Angular scripts. The order of these is important due to the latter ones depending on the ones prior to them.

``` javascript app/assets/javascripts/application.js //= require app //= require_tree ./angular


This is quite a change from what exists in the manifest already. We will add jQuery later, but via CDN. You'll see why later in this post.

## Add the View

Next, we need to create a controller. This will allow us to set up a route to a view.

    $ rails g controller home index

This set up the *HomeController* and added the action *index*. Before we modify this view, let's update our layout to acts as an Angular app. This is done by adding the directive `ng-app` to our `<html>` tag:

{% raw %}
``` html app/views/layouts/application.html.erb
<!DOCTYPE html>
<html ng-app>
...

{% endraw %}

Now let's update our index view with some simple Angular code:

{% raw %} ``` html app/views/home/index.html.erb


Hello {{yourName}}!

{% endraw %}

Update your routes file to use this view as the root.

``` ruby config/routes.rb
AngularCasts::Application.routes.draw do
  scope :api do
    get "/screencasts(.:format)" => "screencasts#index"
    get "/screencasts/:id(.:format)" => "screencasts#show"
  end
  root to: "home#index"
end

Note that the line get 'home#index' was removed. This is not needed because the root path directs to it.

Start up your server and open up http://localhost:3000. Type in your name into the text field. If the content changes as you type, it worked! You now have a functional Angular application!

If you are using Rails 3, you will need to delete the file public/index.html

Now the fun begins!

In order for us to tell the page that it should use the App module, we need to add the module name to the ng-app directive. Set the value of the attribute to AngularCasts:

``` html app/views/layouts/application.html.erb <!DOCTYPE html>

Angular Casts <%= stylesheet_link_tag "application", media: "all" %> <%= csrf_meta_tags %>
Angular Casts

<%= yield %>

<%= javascript_include_tag "application" %>


Now our view knows to use the AngularCasts module.

###### On lines 9-11 we have added the `<header>` content. Make sure you have this in your layout as well.

## Create an Angular Controller

Let's create a controller that will be used to list out the episodes. Create a new coffeescript file at *app/assets/javascripts/angular/controllers/screencasts_ctrl.js.coffee*

```coffeescript app/assets/javascripts/angular/controllers/screencasts_ctrl.js.coffee
App.controller 'ScreencastsCtrl', ['$scope', ($scope) ->
  $scope.message = "Angular Rocks!"
]

On line 1, we create a new Angular controller belonging to App named ScreencastsCtrl. The controller will be referenced in our view as ScreencastsCtrl. For more information on Angular controllers, read http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller.

Let's update our view to display the message.

{% raw %} ```html app/views/home/index.html.erb

Message: {{message}}

{% endraw %}

Here we have bound the contents of the *div* to the controller *ScreencastsCtrl*. Refresh the browser and you should see 'Message: Angular Rocks!'.

## Make it Pretty!

Lets add the much needed CSS to our application. Copy the following into *app/assets/stylesheets/home.css.scss*.

``` scss app/assets/stylesheets/home.css.scss
body {
  font-size: 12px;
  font-family: Helvetica, sans-serif;
  background-color: #ddd;
  margin: 0px;
}

header {
  background-color: #4F4F4F;
  color: #fff;
  position: absolute;
  height: 36px;
  top: 0;
  left: 0;
  right: 0;
  font-size: 18px;
  line-height: 36px;
  font-weight: bold;
  padding-left: 15px;
}

#screencast-ctrl {
  background-color: #fff;
  position: absolute;
  top: 37px;
  width: 100%;
  bottom: 0;
  overflow: auto;
}

#screencast-list-container {
  background-color: #fff;
  position: absolute;
  min-height: 700px;
  width: 300px;
  top: 37px;
  left: 0;
  bottom: 0;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  ul {
    margin: 0px;
    list-style: none;
    padding: 0px;
    li {
      cursor: pointer;
      border-bottom: 1px solid #ddd;
      padding: 0 10px;
    }
  }
  h3 {
    font-size: 14px;
    small {
      font-size: 12px;
      color: #ccc;
      font-weight: normal;
    }
    &.active {
      color: red;
    }
  }
}

#screencast-view-container {
  position: absolute;
  border-left: 1px solid #d0d0d0;
  top: 37px;
  left: 300px;
  right: 0;
  bottom: 0;
  background-color: #fff;
  min-height: 700px;
  padding: 5px 25px;

  #player {
    border: 1px solid #000;
    max-width: 800px;
  }
}

Refresh the browser. Ooooh!

Start with the Service

Our Angular controller is going to access the data from our API using ngResource. ngResource enables interation with RESTful server-side data sources.

Angular services are singletons that carry out specific tasks common to web apps. Services are commonly used to perform the XHR interaction with the server. To learn about the differences between services and factories, read this. Let's start off by creating a service at screencast.js.coffee:

``` coffeescript app/assets/javascripts/angular/services/screencast.js.coffee App.factory 'Screencast', ['$resource', ($resource) -> $resource '/api/screencasts/:id', id: '@id' ]


Now tell the controller to use this service:

``` coffeescript app/assets/javascripts/controllers/screencasts_ctrl.js.coffee
App.controller 'ScreencastsCtrl', ['$scope', 'Screencast', ($scope, Screencast) ->
  $scope.screencasts = Screencast.query()
]

Update the index view with the following:

{% raw %} ```html app/views/home/index.html.erb

  • {{screencast.title}} ({{screencast.duration}})

{% endraw %}

Now refresh the page. If all worked well, you should see a list of screencasts on the left side. When we reloaded the page, a *GET* request was sent to */api/screencasts*, populating the *screencasts* attribute in our scope. This is the power of Angular ngResource.

## Now What?

We are doing great! Now we have a list of screencasts on the side which are clickable. However, we don't do anything when they are clicked. What we want to do is show the screencast in the main section along with some additional screencast information.

Start off by adding the HTML code which will be used to display the main content. This is done inside the *index.html.erb* file:

{% raw %}
```html app/views/home/index.html.erb
<div ng-controller="ScreencastsCtrl">
  <div id="screencast-list-container">
    <ul>
      <li ng-repeat="screencast in screencasts">
        <h3>{{screencast.title}} <small>({{screencast.duration}})</small></h3>
      </li>
    </ul>
  </div>

  <div id="screencast-view-container" ng-show="selectedScreencast">
    <h2>{{selectedScreencast.title}}</h2>
    <p>{{selectedScreencast.summary}}</p>
    <p>
      Published at {{selectedScreencast.published_at | date: 'mediumDate'}}
      - <a ng-href="{{selectedScreencast.link}}">{{selectedScreencast.link}}</a>
    </p>
  </div>
</div>

{% endraw %}

On lines 10-17, we have added a div which shows the screencast title and summary. On line 10, we use the ng-show directive which only displays the div if selectedScreencast exists.

Go ahead and refresh the page. You should not see any changes. Click on a screencast. Still no changes.

Click and Show

In order for us to show the main content with the screencast information, we need to do a few things. The first thing we need to do is add an ng-click directive to our screencast list:

{% raw %} ```html app/views/home/index.html.erb ...

  • {{screencast.title}} ({{screencast.duration}})

...
{% endraw %}

Now when the list item is clicked the function *showScreencast* will be triggered with the screencast being passed in to it. Now let's update our controller with this function:

```coffeescript app/assets/javascripts/angular/controllers/screencasts_ctrl.js.coffee
App.controller 'ScreencastsCtrl', ['$scope', 'Screencast', ($scope, Screencast) ->
  # Attributes accessible on the view
  $scope.screencasts        = Screencast.query()
  $scope.selectedScreencast = null

  # Set the selected screencast to the one which was clicked
  $scope.showScreencast = (screencast) ->
    $scope.selectedScreencast = screencast
]

Refresh your browser and click on a screencast. As my wife would incorrectly say: "Waalah!"

Show the Screencast

After doing a bit of looking around, I found that Flow Player offered the easiest and cleanest way to show videos. Let's add the dependent scripts and css links to our layout:

``` html app/views/layouts/application.html.erb <!DOCTYPE html>

Angular Casts <%= stylesheet_link_tag "application", media: "all" %> <%= csrf_meta_tags %>
Angular Casts

<%= yield %>

<%= javascript_include_tag "application" %>


Remember how we removed jQuery from our Gemfile and javascript manifest? The reason is because we didn't want it concatenated with the other scripts. FlowPlayer depends on jQuery and so jQuery needs to be available prior to Flow Player being loaded. We also can load it via CDN. Good times for all.

### Create the FlowPlayer Directive

FlowPlayer requires triggering a function *flowplayer()* to show the video. We could add this into our controller, but we love to learn. Let's create a directive which listens to the controller and triggers the *flowplayer* function when *showScreencast* is called.

Create the directive at *app/assets/javascripts/angular/directives/flow_player.js.coffee*

``` coffeescript app/assets/javascripts/angular/directives/flow_player.js.coffee
App.directive 'flowPlayer', ->
  (scope, element, attrs) ->

    # Trigger when the selectedScreencast function is called
    # with a screencast
    scope.$watch 'selectedScreencast', (screencast) ->
      if screencast

        # See http://flowplayer.org/docs/
        element.flowplayer
          playlist: [[mp4: screencast.video_url]]
          ratio: 9 / 14

Now add the directive into our view:

{% raw %} ```html app/views/home/index.html.erb ...

{{selectedScreencast.title}}

{{selectedScreencast.summary}}

Published at {{selectedScreencast.published_at | date: 'mediumDate'}} - {{selectedScreencast.link}}

...
{% endraw %}

Refresh your browser and go nuts!

## Extra Goodies

One final thing that I would like to see is some sort of indicator which lets us know which video is playing on the screencast list. This can be done via CSS and some simple code.

In our CSS file, we have already added some style for an active screencast. Any *H3* tag on the side with the class of *active* will show as red. Try it out by adding the class to our view:

{% raw %}
```html app/views/home/index.html.erb
...
  <div id="screencast-list-container" >
    <ul>
      <li ng-repeat="screencast in screencasts"
          ng-click="showScreencast(screencast)">
        <h3 class="active">{{screencast.title}} <small>({{screencast.duration}})</small></h3>
      </li>
    </ul>
  </div>
...

{% endraw %}

Refresh the page. You should now see that every screencast link on the left is red.

For us to make it show for the active screencast only we have to make a few changes to our view and controller. Update the view to use the ng-class directive:

{% raw %} ```html app/views/home/index.html.erb ...

  • {{screencast.title}} ({{screencast.duration}})

...
{% endraw %}

Note that on line 5 we added the 2nd attribute *&index*. This is available via the *ng-repeat* directive and is the index value of the array (integer). We also modified line 6 to use the *ng-class* directive which only shows "active" if the *$index* is equal to *$scope.selectedRow*.

Now update the controller to work with these changes:

``` coffeescript app/assets/javascripts/controllers/screencasts_ctrl.js.coffee
App.controller 'ScreencastsCtrl', ['$scope', 'Screencast', ($scope, Screencast) ->
  # Attributes accessible on the view
  $scope.selectedScreencast = null
  $scope.selectedRow        = null

  # Gather the screencasts and set the selected one to the first on success
  $scope.screencasts = Screencast.query ->
    $scope.selectedScreencast = $scope.screencasts[0]
    $scope.selectedRow = 0

  # Set the selected screencast to the one which was clicked
  $scope.showScreencast = (screencast, row) ->
    $scope.selectedScreencast = screencast
    $scope.selectedRow = row
]

We have added the new param row to the showScreencast function and set this to $scope.selectedRow. Refresh your browser and see how things have changed.

完成项目

View the working app at http://angular-casts.herokuapp.com/.

Final Thoughts

I know there are no front-end tests for this tutorial. This was intentional. They were too hard. I spent hours upon hours trying to get the tests working with $httpBackend and service testing, etc. I tried karma and testem. Too much time. Too little benefit. If you are better at this stuff than I am please send me an email or pull request or something with the changes you've made to include the tests. I can always add a Part 3 which is about nothing other than testing the frontend.

Thank you all who have patiently waited for me to finish this post. I learned never to release a post before it has been proofread and run through several times. Next time I'm going to do a screencast.. just like the old days.

🔲 ☆

linux信息查看

查看有几个插口用了几个插口

# dmidecode -t memory |grep Size
Size: 1024 MB
Size: 1024 MB
Size: 1024 MB
Size: 1024 MB
Size: No Module Installed
Size: No Module Installed
Size: No Module Installed
Size: No Module Installed

查看服务器多少位

# getconf LONG_BIT
32
# uname -a
Linux longyuan 2.6.18-8.10AX #1 SMP Tue Aug 14 04:52:14 EDT 2007 i686 i686 i386 GNU/Linux

查看Linux内核版本的命令

# uname -a
Linux xxcloud 2.6.32-71.el6.x86_64 #1 SMP Fri May 20 03:51:51 BST 2011 x86_64 x86_64 x86_64 GNU/Linux

# cat /proc/version
Linux version 2.6.32-71.el6.x86_64 (mockbuild@c6b6.centos.org) (gcc version 4.4.4 20100726 (Red Hat 4.4.4-13) (GCC) ) #1 SMP Fri May 20 03:51:51 BST 2011

*linux 下怎样启用PAE(让32位支持4G以上内存)

   # cat /boot/config-*|grep PAE
   # Linux kernel version: 2.6.18-8.10AXPAE
   CONFIG_X86_PAE=y

查看是什么linux

[root@wocloud .ssh]# cat /etc/redhat-release
CentOS release 6.3 (Final)

[root@wocloud ~]# cat /etc/issue 
CentOS release 6.3 (Final)
Kernel \r on an \m

[cgg@longyuan ~]$ cat /etc/issue 
Asianux Server 3 (Quartet)
Kernel \r on an \m

john@li388-108:~$ cat /etc/issue 
Ubuntu 10.10 \n \l

MyBookLive:~# cat /etc/issue 
Debian GNU/Linux 5.0 \n \l

看内存情况

john@localhost:~$ free -m
             total       used       free     shared    buffers     cached
Mem:           496        464         31          0        126        197
-/+ buffers/cache:        140        356
Swap:          255          0        255
🔲 ☆

Nginx配置autoindex浏览目录列表

Nginx默认是不允许列出整个目录的。如需此功能, 打开nginx.conf文件,在location server 或 http段中加入

autoindex on;

另外两个参数最好也加上去:

autoindex_exact_size off;

默认为on,显示出文件的确切大小,单位是bytes。 改为off后,显示出文件的大概大小,单位是kB或者MB或者GB

autoindex_localtime on;

默认为off,显示的文件时间为GMT时间。

改为on后,显示的文件时间为文件的服务器时间

location /{
root   /var/www/html;
autoindex on;
}

这段代码的意思就是把 /var/www/html目录作为根目录来直接列出来。

当然,我在做这个事情的时候也碰到了一个问题。一般一台NGINX服务器上会有多个网站。那么怎么样把其中的一个网站设置为列出目录呢?

其实很简单,把该网站的.conf文件全部修改才行。如修改成如下即可:

server {
    listen 80;
    charset utf-8;
    server_name localhost;
    root /www/web/default;

    location / {
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
    }
}

参考

http://wiki.nginx.org/HttpAutoindexModuleChs

🔲 ☆

will_Paginate参数说明

```bash ruby u=User.paginate(:page => 1);

u.total_entries  #共有多少条 => 1527 u.per_page  #每页显示几条 => 30 u.total_pages #共有几页 => 51 u.current_page  #当前在哪一页 => 1



参考:[https://github.com/mislav/will_paginate/wiki/API-documentation](https://github.com/mislav/will_paginate/wiki/API-documentation)
🔲 ☆

一个不能删除的密秘

``bash Terminal ~/projects$ sudo rm test_del -rf rm: cannot removetest_del': Operation not permitted

这样都删不了,只因世界上有chattr这么一个命令。


```bash Terminal
~/projects$ sudo chattr -i test_del
~/projects$ rm test_del -rf

####以下说明转载(只因转载太多次不知道作者是谁,故不写上url啦。) chattr 用于设置文件属性

lsattr 用于查看文件属性

chattr 命令的作用很大,其中一些功能是由Linux内核版本来支持的,如果Linux内核版本低于2.2,那么许多功能不能实现。同样-D检查压缩文件中的错误的功能,需要2.5.19以上内核才能支持。另外,通过chattr命令修改属性能够提高系统的安全性,但是它并不适合所有的目录。chattr命令不能保护/、/dev、/tmp、/var目录。

补充说明:用chattr执行改变文件或目录的属性,可执行lsattr指令查询其属性。

🔲 ⭐

[转载]ruby 正则笔记

Ruby的正则表达式以"//"作为构造方法。表达式返回一个RegExp的对象。

一、字符规则

1. /a/匹配字符a。     
2.  /[\d]/代表任意数字
3.  /[\w]/代表任意字母,数字或者_
4.  /[\s]/代表空白字符,包括空格,TAB和换行。    
5.  /\?/匹配特殊字符?。特殊字符包括^, $, ? , ., /, \, [, ], {, }, (, ), +, *.    
6.  /[ab]c/匹配ac和bc,[]之间代表范围。例如:/[a-z]/ , /[a-zA-Z0-9]/。    
7.  /[^a-zA-Z0-9]/匹配不在该范围内的字符串。     
8.  /[\D]/,/[\W]/,/[\S]/均为上述的否定情况。 
9.  reA|reB 匹配 reA或者reB
10.  .(点符号)匹配任意字符,例如/a./匹配ab和ac。   

二、数量规则

1.  /[A-Z](\d){4}/匹配首位是大写字母,后面4个是数字的字符串,例如:A1234。
/([A-Z]\d){4}/  匹配:4组为首位是大写字母,第二位为数字的组合,例如:A1B2C3D4
2.  ?(问号)代表0或1个字符。/Mrs?\.?/匹配"Mr","Mrs","Mr.","Mrs."。
解析:/ M r s? \.? / M后面是字符r, 后面是0或1个字符s, 在后面是0或1个字符"."  
3.  *(星号)代表0或多个字符。/Hello*/匹配"Hello","HelloJack"。 
4.  +(加号)代表1或多个字符。/a+c/匹配:"abc","abbdrec"等等。 
5.  re{n}  匹配正好n个re  /d{3}/匹配3个数字。 
6.  re{m,n}  匹配至少m个最多n个re    /d{1,10}/匹配1-10个数字。 
7.  re{m,}  匹配至少m个re   /d{3,}/匹配3个数字以上。 

三、正则表达式操作

String和RegExp均支持=~和match 2个查询匹配方法

1. =~  返回匹配的第一个字符串位置,不匹配返回空nil
puts "12345678901"=~/1/
输出:0
puts "123456789045"=~/45/
输出:3

2.match返回一个MatchData对象。如果不匹配返回nil。
a=/abc/.match("abc cba adbdc abc")
puts a[0]
输出:abc
b=/aaa/.match("abc cba adbdc abc")
puts b[0]
报错:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)

3.[0]返回匹配主表达式的字符串,用()包括可显示子类
b=/[A-Za-z]+,[A-Za-z]+,Mrs?\./.match("One,Fei,Mrs.,hello")
puts b[0]
输出:One,Fei,Mrs.

c=/([A-Za-z]+),([A-Za-z]+),Mrs?\./.match("Two,Fei,Mrs.,hello")
puts c[0]
puts c[1]
puts c[2]
输出:
Two,Fei,Mrs.
Two
Fei

d=/(([A-Za-z]+),([A-Za-z]+)),Mrs?\./.match("Three,Fei,Mrs.,hello")
puts d[0]
puts d[1]
puts d[2]
puts d[3]
输出:
Three,Fei,Mrs.
Three,Fei
Three
Fei

4.Ruby也自动的为我们填写了一些全局变量,它们以数字做名:

$1,$2,等等,$1包含的是正则表达式中从左侧开始的第一对小括号内的子模式所匹配的字符串
我们看出匹配时,是从外到内,从左到右的顺序
string="PhoneNum:(021) 888-1234;Tele:13913913696;"
phone=/\((\d{3})\)\s+(\d{3})-(\d{4})/
m=phone.match(string)
print "匹配前内容:"
puts m.pre_match
print "匹配后内容:"
puts m.post_match
print "第二个匹配开始的字符"
puts m.begin(2)
print "第三个匹配开始的字符"
puts m.begin(3)
输出:
匹配前内容:PhoneNum:
匹配后内容:;Tele:13913913696;
第二个匹配开始的字符15
第三个匹配开始的字符19

四、高级操作

1.贪婪量词和不贪婪量词

量词*(零个或多个)和+(一个或多个)是贪婪的,它们会匹配尽可能多的字符,我们可以在*和+后面加一个?,使它成为非贪婪量词
下面代码是: 1个或多个字符后接一个感叹号。

test="abcdefg!!!"
match=/.+!/.match(test)
puts match[0]
limitmatch=/.+?!/.match(test)
puts limitmatch[0]
输出:
abcdefg!!!
abcdefg!

2.锚是指必须满足一定的条件,才能继续匹配

^     行首
$     行尾
\A   字符串的开始
\z    字符串的结尾
\Z    字符串的结尾(不包括最后的换行符)
\b    单词边界
\B    非单词边界

test="  # Ruby comment line"
a=/^\s*#/.match(test)
puts a[0]
a=/^\s*#(.+)/.match(test)
puts a[1]
b=/\ABetter man/.match("Better man is fei")
puts b[0]
c=/\b\w+\b/.match("!!!fei**")
puts c[0]

输出:
  #
 Ruby comment line
Better man
fei

五、正则表达式实例 1.邮箱

/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
解析:^和+$ 为了判定字符串前后的空白字符

2.小数

^[0-9]+(.[0-9]{2})$  ---2位小数

3.正整数

/^\+?[1-9][0-9]*$/

4.验证长度为3的字符:

/^.{3}$/

5.验证是否含有

^%&',;=?$\" 等字符:/[^%&',;=?$\x22]+/

6.验证身份证号(15位或18位数字)

^\d{15}|\d{}18$

7..rb结尾的文件

/\w.*(?=\.rb+$)/

ref:

Ruby正则表达式编辑器 rubular.com

http://www.iteye.com/topic/60620

http://www.iteye.com/topic/60620

🔲 ☆

压力测试apache-ab-使用方法

ab的全称是ApacheBench,是 Apache 附带的一个小工具,专门用于 HTTP Server 的benchmark testing,可以同时模拟多个并发请求。

参数简明 -n 发送请求的数量 -c 表示一次发送多少个(实际上就是把-n分批发送), 如:ab -n 1000 -c 64 http://center.xxxxxx.cn/

tianyi:~ john$ 
tianyi:~ john$ ab -n 10 -c 10 http://center.xxxxxx.cn/

```bash 参数说明 This is ApacheBench, Version 2.3 <$Revision: 655654 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking center.xxxxxx.cn (be patient).....done

Server Software:
Server Hostname: center.xxxxxx.cn Server Port: 80

Document Path: / Document Length: 89 bytes #页面长度

Concurrency Level: 10 #并发数 Time taken for tests: 0.150 seconds #注:测试共使用了多少时间 Complete requests: 10 #注:请求完成的数量 Failed requests: 0 #注:请求失败的数量 Write errors: 0 Non-2xx responses: 10 Total transferred: 3202 bytes #注:请求产生的流量 HTML transferred: 890 bytes #注:html传输流量 Requests per second: 66.52 #/sec #注:每秒事务数 Time per request: 150.330 ms #注:平均响应时间

Time per request: 15.033 ms #注:每个请求响的平均时间,也就是服务器吞吐量的倒数

Transfer rate: 20.80 [Kbytes/sec] received #注:传输效率

Connection Times (ms) min mean[+/-sd] median max Connect: 42 51 6.0 53 59 Processing: 87 94 4.7 94 101 Waiting: 86 93 5.0 94 101 Total: 139 145 3.5 146 149

Percentage of the requests served within a certain time (ms) 50% 146 #注:50%的请求响应小于146 66% 147 #注:60%的请求响应小于147 75% 148 #注:60%的请求响应小于148 80% 149 90% 149 95% 149 98% 149 99% 149 100% 149 (longest request)

🔲 ⭐

没有找到libmysql.dll

"没有找到libmysql.dll,因此这个应用程序未能启动。重新安装应用程序可能会修复问题。"

主要是system32的环境中没有libmysql.dll文件,修复的办法。

安装的目录mysql\bin下的libmySQL.dll复制到c:\windows\system32 即可!

🔲 ☆

用socks代理使用apt-get命令

安装

apt-get install tsocks

配置 ```bash /etc/tsocks.conf vi /etc/tsocks.conf

local = 192.168.1.0/255.255.255.0 #local表示本地的网络,也就是不使用socks代理的网络 ... server = 127.0.0.1 #socks服务器的IP server_type = 5 #socks服务版本 server_port = 7070 #socks服务使用的端口



```bash
tsocks apt-get update
tsocks aptitude upgrade

在命令前面“tsocks”会用“exec”来执行。

转载 http://www.linuxdiyf.com/viewarticle.php?id=78483

❌