• Posts tagged "web"

Blog Archives

Angular2新的体验

AngularJS体验式编程系列文章,将介绍如何用angularjs构建一个强大的web前端系统。angularjs是由Google团队开发的一款非常优秀web前端框架。在当前如此多的web框架下,angularjs能脱颖而出,从架构设计上就高人一等,双向数据绑定,依赖注入,指令,MVC,模板。Angular.js创新地把后台技术融入前端开发,扫去jQuery一度的光芒。用angularjs就像写后台代码,更规范,更结构化,更可控。

从 Angular 2.x 开始新的体验。

关于作者

  • 张丹(Conan), 程序员R,Java,Nodejs
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/angular2-init/

前言

随着Angular2的升级,从1.x升级2.x,但我却迟迟没有动手。原因了2.x对1.x完全不兼容,而且从原生Javascript变成了Typescript,增加很多的生成模块,依赖的类库一下子变得很多。变化实在太大了,确实让人难以接受。我特别对于Typescript的不解,喜欢javascript的灵活,而静态化意味代码量的增加。

前几天,看到Angular2的release,想来想去还是要试试。从官方文档中,看到对中文支持的非常好,开发团队真是用心了。开发团队用心的改变,作为使用者来说是切身可以感受的,带着敬意和信心,决定把Angular2学起来。

目录

  1. Angular2介绍
  2. Anguar2的快速启动
  3. 从命令行构建Anguar2

1. Angular2介绍

Angular是由Google开发的一套前端应用开发框架,可以快速帮你构建复杂的大型前端单页应用(Single Page Application)。我非常喜欢Angular 1.x 给我带来的前端开发体验,当前花了2周时间时间学习,几百行代码就实现了,超乎想象的应用效果。我放下了所有原来对于前端Javascript的认知,直接转向了Angular。

官方网站:https://angular.cn/

Angular2的新特性包括:

  • 渐进式Web应用:借助现代化Web平台的力量,交付app式体验。高性能、离线化、零安装。
  • 原生:借助来自Ionic、NativeScript和React Native中的技术与思想,构建原生移动应用。
  • 桌面:借助你已经在Web开发中学过的能力,结合访问原生操作系统API的能力,创造能在桌面环境下安装的应用,横跨Mac、Windows和Linux平台。
  • 代码生成:Angular会把你的模板转换成代码,针对现代JavaScript虚拟机进行高度优化,轻松获得框架提供的高生产率,同时又能保留所有手写代码的优点。
  • 统一:在服务端渲染应用的首屏,像只有HTML和CSS的页面那样几乎瞬间展现,支持node.js、.NET、PHP,以及其它服务器,为通过SEO来优化站点铺平了道路。
  • 代码拆分:Angular应用通过新的组件路由(Component Router)模块实现快速加载,提供了自动拆分代码的功能,为用户单独加载它们请求的视图中需要的那部分代码。
  • 模板:通过简单而强大的模板语法,快速创建UI视图。
  • Angular命令行工具:命令行工具:快速进入构建环节、添加组件和测试,然后立即部署。
  • 各种IDE:在常用IDE和编辑器中获得智能代码补全、实时错误反馈及其它反馈等特性。
  • 测试:使用Karma进行单元测试,让你在每次存盘时都能立即知道是否弄坏了什么。Protractor则让你的场景测试运行得又快又稳定。
  • 动画:通过Angular中直观简便的API创建高性能复杂编排和动画时间线 —— 只要非常少的代码。
  • 可访问性:通过支持ARIA的组件、开发者指南和内置的一体化测试基础设施,创建具有完备可访问性的应用。

接下来,就让我们来体验Angular2的新颖之处的。

2. Anguar2的快速启动

阅读官方文档,我们可以跟着文档进行项目的快速启动,快速启动项目quickstart,是基于github,node,npm的,我们按照文档执行就可以了。关于Node的介绍,可以参考系列文章从零开始nodejs系列文章

系统环境:

  • Win10 64bit
  • node v6.9.4
  • npm 3.10.10
  • git version 2.7.0.windows.1

2.1 构建项目

进入开发目录,下载quickstart项目。


~ cd D:\\workspace\js
~ git clone https://github.com/angular/quickstart.git quickstart
~ cd quickstart
~ npm install   # 执行npm安装和配置
~ npm start     # 启动项目

通过npm start命令,就直接启动了angular2的程序,默认会自动打开浏览器,就可以看到效果了。如果浏览没有自动打开,自己手动在浏览器打开localhost:3000,也可以打开。

2.2 目录结构

接下来,我们查看项目目录结构。

由于这个quickstart的模板项目,包含了太多的文件。一下子看到这么多东西,肯定要晕一会的。图中用红色部分标记的几个文件,是我们应该要知道的,其他的文件对于首次执行来说并不是太重要。

文件说明

  • app/app.components.ts, 一个自定义组件,Typescript代码。
  • app/app.module.ts, 模块文件,用于组合管理组件,Typescript代码。
  • app/main.ts, 项目启动的入口,加载ts文件,Typescript代码。
  • app/app.components.spec.ts, 单测试文件
  • .gitignore, git的配置文件
  • index.html, 单页应用的html入口文件
  • package.json, Node项目的工程配置文件
  • tsconfig.json, Typescript语言的配置文件

2.3 4个核心文件

把几个核心的文件中的代码,进行解释。

app/app.components.ts文件


import { Component } from '@angular/core';        //引用系统类库

@Component({                                      //定义组件
  selector: 'my-app',                             //对应该index.html的<my-app>标签
  template: `<h1>Hello {{name}}</h1>`,            //替换<my-app>标签的内容
})
export class AppComponent  { name = 'Angular'; }  //输出自定义组件 

app/app.module.ts文件


import { NgModule }      from '@angular/core';                  //引用系统类库
import { BrowserModule } from '@angular/platform-browser';      //引用系统类库
import { AppComponent }  from './app.component';                //引用app.components.ts文件,定义的AppComponent组件
 
@NgModule({                                                     //定义模块
  imports:      [ BrowserModule ],                              //引用浏览器模块
  declarations: [ AppComponent ],                               //声明组件
  bootstrap:    [ AppComponent ]                                //启动组件
})
export class AppModule { }                                      //输出自定义模块 

app/main.ts文件


import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  //引用系统类库

import { AppModule } from './app.module';                                    //引用app.module.ts文件的AppModule 

platformBrowserDynamic().bootstrapModule(AppModule);                         //启动程序,加载模块

index.html文件


<!DOCTYPE html>
<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>
    <my-app>Loading AppComponent content here ...</my-app>
  </body>
</html>

index.html中$lt;my-app&gtl的标签,是会被app.components.ts文件定义的selector发现并处理。

这4个文件,其实就是程序源代码的核心文件。那么项目中的其他文件,都是各种工具的配置文件。比如,我要编译Typescript文件到Javascript文件,就是需要在tsconfig.json进行配置;对类库做动态加载就要用到systemjs;执行单元测试需要用到karma;上传到github需要用到.gitignore;对node项目的管理用package.json配置。

2.4 扩展工具

当然,还有一些扩展工具。

单独编译Typescrip到Javascript。


~ D:\workspace\js\quickstart>npm run tsc

单独编译Typescrip,并监控文件状态,发现文件变化重新变异。


~ D:\workspace\js\quickstart>npm run tsc:w

启动Server,在浏览器中查看效果。


~ D:\workspace\js\quickstart>npm run lite 

单元测试


~ D:\workspace\js\quickstart>npm test

E2E测试End-to-end


~ D:\workspace\js\quickstart>npm run e2e 

除了从github上面下载quickstart模板,还是另外一种初始构建项目的方式,就是用Anguar2的命令行工具。

3. 从命令行构建Anguar2

从上文的Angular2的特性中,就有一项是命令工具,用这种方式构建一个新项目,更符合开发人员“脚手架”的思路。首先,我们需要安装这个命令工具anguar-cli。请大家务必升级Nodejs到v6.x以上,我之前用v4.4,花了大量时间调试都没有通过。

3.1 安装anguar-cli


~ D:\workspace\js>npm install -g angular-cli

安装好后,我们可以通过help命令查看命令行有哪个功能。


D:\workspace\js>ng help
ember build 
  Builds your app and places it into the output path (dist/ by default).
  aliases: b
  --target (String) (Default: development)
    aliases: -t , -dev (--target=development), -prod (--target=production)
  --environment (String) (Default: )
    aliases: -e 
  --output-path (Path) (Default: null)
    aliases: -o 
  --watch (Boolean) (Default: false)
    aliases: -w
  --watcher (String)
  --suppress-sizes (Boolean) (Default: false)
  --base-href (String) (Default: null)
    aliases: -bh 
  --aot (Boolean) (Default: false)
  --sourcemap (Boolean) (Default: true)
    aliases: -sm
  --vendor-chunk (Boolean) (Default: true)
  --verbose (Boolean) (Default: false)
  --progress (Boolean) (Default: true)
  --i18n-file (String) (Default: null)
  --i18n-format (String) (Default: null)
  --locale (String) (Default: null)

  // 省略....

查看ng工具的版本


~ D:\workspace\js>ng version
                             _                           _  _
  __ _  _ __    __ _  _   _ | |  __ _  _ __         ___ | |(_)
 / _` || '_ \  / _` || | | || | / _` || '__|_____  / __|| || |
| (_| || | | || (_| || |_| || || (_| || |  |_____|| (__ | || |
 \__,_||_| |_| \__, | \__,_||_| \__,_||_|          \___||_||_|
               |___/

angular-cli: 1.0.0-beta.26
node: 6.9.4
os: win32 x64

当然,我们最需要的就是构建项目,启动服务,生成组件,指令,服务等功能。

3.2 新建项目

新建一个项目


~ D:\workspace\js>ng new conan1      // 新建项目
installing ng2
  create .editorconfig
  create README.md
  create src\app\app.component.css
  create src\app\app.component.html
  create src\app\app.component.spec.ts
  create src\app\app.component.ts
  create src\app\app.module.ts
  create src\assets\.gitkeep
  create src\environments\environment.prod.ts
  create src\environments\environment.ts
  create src\favicon.ico
  create src\index.html
  create src\main.ts
  create src\polyfills.ts
  create src\styles.css
  create src\test.ts
  create src\tsconfig.json
  create angular-cli.json
  create e2e\app.e2e-spec.ts
  create e2e\app.po.ts
  create e2e\tsconfig.json
  create .gitignore
  create karma.conf.js
  create package.json
  create protractor.conf.js
  create tslint.json
Successfully initialized git.
Installing packages for tooling via npm.
Installed packages for tooling via npm.
Project 'conan1' successfully created.

等了大概有10分钟,下载了有200mb的文件,希望大家有耐心。进入安装目录。


~ D:\workspace\js\conan1>cd conan1      // 进入项目目录
~ D:\workspace\js\conan1>ng serve       // 启动项目

打开浏览器,查看Web网页。

如果你想修改启动端口为4201,可以用下面的命令。


ng serve --host 0.0.0.0 --port 4201 --live-reload-port 49153

用命令工具构建的项目目录。

目录结构有一个变化,就是嵌套了一层src目录,然后才是app目录。另外,多了angular-cli.json的配置文件。

3.3 模块生成器

接下来,我们可以用命令工具,进行项目模块和组件的开发了。

命令使用说明
组件Componentng generate component my-new-component
指令Directiveng generate directive my-new-directive
服务Serviceng generate pipe my-new-service
管道Pipeng generate pipe my-new-pipe
类Classng generate class my-new-class
接口Interfaceng generate interface my-new-interface
枚举对象Enumng generate enum my-new-enum
模块Moduleng generate module my-module

3.4 生成一个新组件

用命令生成一个hello的新组件,文件生成如下。


~ D:\workspace\js\conan1>ng generate component hello
installing component
  create src\app\hello\hello.component.css
  create src\app\hello\hello.component.html
  create src\app\hello\hello.component.spec.ts
  create src\app\hello\hello.component.ts
  update src\app\app.module.ts

在app目录下生成了一个hello的子目录,包括了4个组件的文件,同时在app.module.ts模块文件中,注册了这个新组件。

我们要修改2个地方,让这个新生成的hello组件可以运行。

1. 修改index.html文件,增加<app-hello>标签。


<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Conan1</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root>Loading...</app-root>
  
  <app-hello>Loading...</app-hello>
</body>
</html>

2. 修改app.module.ts文件,在@NgModule.bootstrap中,增加HelloComponent的启动项。


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello/hello.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent,HelloComponent]
})
export class AppModule { }

查看浏览器,我们可以看到hello works!显示到界面上。

3.5 生成一个新指令

属性型指令用于改变一个 DOM 元素的外观或行为。用命令生成一个link的新指令,操作如下。


~ D:\workspace\js\conan1>ng generate directive link
installing directive
  create src\app\link.directive.spec.ts
  create src\app\link.directive.ts
  update src\app\app.module.ts

主要生成了新文件link.directive.ts。


import { Directive } from '@angular/core';
@Directive({
  selector: '[appLink]'
})
export class LinkDirective {
  constructor() { }
}

接下来,用appLink指令来做一个样式的修饰,需要修改2个文件。

1. 修改hello.component.html文件,增加一段span的HTML标签,并配置appLink属性。


<p>hello works!</p>

<span appLink>Directive me!</span>

2. 修改link.directive.ts文件,在LinkDirective类的构造器constructor函数中,增加样式的修改属性。同时,通过@HostListener,监听鼠标动作。


import { Directive, ElementRef, HostListener, Renderer } from '@angular/core';
@Directive({
  selector: '[appLink]'
})
export class LinkDirective {
    constructor(el: ElementRef, renderer: Renderer) {
       renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow');
    }

    @HostListener('mouseenter') onMouseEnter() {
      this.highlight('blue');
    }
    @HostListener('mouseleave') onMouseLeave() {
      this.highlight('yellow');
    }
    
    private highlight(color: string) {
      this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color);
    }
}

修改后,我们在浏览器中查看运行的效果。

3.6 生成一个新服务

服务,可以封装代码,比如我们可以对数据访问代码单独隔离,封装到一个独立的服务中。用命令生成一个meta的新服务,操作如下。


~ D:\workspace\js\conan1>ng generate service meta
installing service
  create src\app\meta.service.spec.ts
  create src\app\meta.service.ts
  WARNING Service is generated but not provided, it must be provided to be used

生成了2个service的文件,同时提供了Service必须被provided,才可以被应用。我们如果想要启用meta的这个服务,需要在3个文件中进行修改。

1. 修改meta.service.ts文件,增加getNames()函数,用于提供数据访问。


import { Injectable } from '@angular/core';
@Injectable()
export class MetaService {
  constructor() { }
  getNames():any[]{
    return [
        {id: 1, name: 'AAA'},
        {id: 2, name: 'BBB'},
        {id: 3, name: 'CCC'},
        {id: 4, name: 'DDD'}
      ];
  }
}

2. 修改hello.component.ts文件,把MetaService注入到HelloComponent中,通过providers进行依赖注入的体现,同时调用MetaService 类的getNames()函数获取数据。


import { Component, OnInit } from '@angular/core';
import { MetaService } from '../meta.service';
@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css'],
  providers: [MetaService]
})
export class HelloComponent implements OnInit {
  meta = [];
  constructor(private metaService: MetaService) { }
  ngOnInit() {
    this.meta = this.metaService.getNames();
  }
}

3. 修改hello.component.html文件,用于数据的html输出,以列表形式输出。


<p>hello works!</p>

<span appLink>Directive me!</span>

<ul>
  <li *ngFor="let m of meta">
    {{m.id}}, {{m.name}}
  </li>
</ul>

修改后,我们在浏览器中查看运行的效果。

3.7 生成一个新管道

管道,可以用于数据的连续处理操作,比如可以把日期在界面端进行格式化,把20170101格式转型2017-01-01格式。用命令生成一个datef的新管道,操作如下。


~ D:\workspace\js\conan1>ng generate pipe datef
installing pipe
  create src\app\datef.pipe.spec.ts
  create src\app\datef.pipe.ts
  update src\app\app.module.ts

生成了2个pipe的文件。如果我们想使用这个功能,需要在2个文件中进行修改。

1. 修改datef.pipe.ts文件,对日期进行格式化,把20161222转化为2016-12-22。


import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'datef'
})
export class DatefPipe implements PipeTransform {
  transform(value: string) {
    var dat1 = value.toString();
    return dat1.substring(0,4)+ "-"+ parseInt(dat1.substring(4,6)) +  "-"+dat1.substring(6,8);
  }
}

2. 修改hello.component.html文件,进行HTML的输出。


<p>hello works!</p>

<span appLink>Directive me!</span>

<ul>
  <li *ngFor="let m of meta">
    {{m.id}}, {{m.name}}
  </li>
</ul>

<p>{{day}} ==> {{ day | datef}}</p>

修改后,我们在浏览器中查看运行的效果。

其他的命令,我们在后文再继续说明。本文只是一篇对Angular2的新体验介绍,由于Angular2整个框架还是变化挺大的,同时我对Typescript也不熟悉,对webapck也需要花时间学习。整个过程花了不少时间,也走了不少的弯路。

目前,网上Angular2框架介绍的文章本来就不多,虽然官网文档比较详细,但是上手来说,还是有一定的难度的,希望本文对于新手来说有一些帮助,也希望Angualr2尽快成熟,我准备正在项目中用起来!!

转载请注明出处:
http://blog.fens.me/angularjs-yeoman-project/

打赏作者

Hexo在github上构建免费的Web应用

从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发。Nodejs框架是基于V8的引擎,是目前速度最快的Javascript引擎。chrome浏览器就基于V8,同时打开20-30个网页都很流畅。Nodejs标准的web开发框架Express,可以帮助我们迅速建立web站点,比起PHP的开发效率更高,而且学习曲线更低。非常适合小型网站,个性化网站,我们自己的Geek网站!!

关于作者

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/hexo-blog-github/

hexo-github

前言

很多次想把博客从wordpress迁移到github,为此还特意学了一下Ruby和Jekyll。但由于迁移过程过于复杂,我又没有很多时间,这个计划就被搁置了。慢慢地文章积累越来越多了,更没有时间来整理了,所以就先用着wordpress吧。

不过,了迁移博客我也有一些新的发现。hexo,一个基于Node的博客框架,同样可以实现基于github的博客,而且更轻更快,更适合Node的开发程序员。

目录

  1. Hexo介绍
  2. Hexo安装
  3. Hexo的使用
  4. 发布到项目到github
  5. 替换皮肤
  6. 配置常用插件

1. Hexo介绍

Hexo 是一个简单地、轻量地、基于Node的一个静态博客框架。通过Hexo我们可以快速创建自己的博客,仅需要几条命令就可以完成。

发布时,Hexo可以部署在自己的Node服务器上面,也可以部署github上面。对于个人用户来说,部署在github上好处颇多,不仅可以省去服务器的成本,还可以减少各种系统运维的麻烦事(系统管理、备份、网络)。所以,基于github的个人站点,正在开始流行起来….

Hexo的官方网站:http://hexo.io/ ,也是基于Github构建的网站。

2. Hexo安装

系统环境:

  • win7 64bit
  • node v0.10.5
  • npm 1.2.19

Hexo安装,要用全局安装,加-g参数。


D:\> npm install -g hexo

查看hexo的版本


D:\> hexo version
hexo: 2.5.5
os: Windows_NT 6.1.7601 win32 x64
http_parser: 1.0
node: 0.10.5
v8: 3.14.5.8
ares: 1.9.0-DEV
uv: 0.10.5
zlib: 1.2.3
modules: 11
openssl: 1.0.1e

安装好后,我们就可以使用Hexo创建项目了。


D:\workspace\javascript> hexo init nodejs-hexo 
[info] Creating file: source/_posts/hello-world.md
[info] Creating file: package.json
[info] Creating file: .gitignore
[info] Copying file: _config.yml
[info] Copying file: scaffolds/draft.md
[info] Copying file: scaffolds/page.md
[info] Copying file: scaffolds/photo.md
[info] Copying file: scaffolds/post.md
[info] Creating folder: source/_drafts
[info] Creating folder: scripts
[info] Copying theme data...
[info] Initialization has been done. Start blogging with Hexo!

我们看到当前在目录下,出现了一个文件夹,包括初始化的文件。

进入目录,并启动Hexo服务器。


# 进入目录
D:\workspace\javascript>cd nodejs-hexo

# 启动hexo服务器
D:\workspace\nodejs-hexo>hexo server
[info] Hexo is running at http://localhost:4000/. Press Ctrl+C to stop.

这时端口4000被打开了,我们能过浏览器打开地址,http://localhost:4000/ 。

hexo-web

出现了默认的网页界面,是不是很容易呢!!

3. Hexo的使用

接下来,我们要对Hexo做更全面的了解,才能做出个性化一的博客。

3.1 目录和文件

先来看一下,默认生成了哪些东西。

hexo-folder

  • scaffolds 脚手架,也就是一个工具模板
  • scripts 写文件的js,扩展hexo的功能
  • source 存放博客正文内容
  • source/_drafts 草稿箱
  • source/_posts 文件箱
  • themes 存放皮肤的目录
  • themes/landscape 默认的皮肤
  • _config.yml 全局的配置文件
  • db.json 静态常量

在这里,我们每次用到的就是_posts目录里的文件,而_config.yml文件和themes目录是第一次配置好就行了。

_posts目录:Hexo是一个静态博客框架,因此没有数据库。文章内容都是以文本文件方式进行存储的,直接存储在_posts的目录。Hexo天生集成了markdown,我们可以直接使用markdown语法格式写博客,例如:hello-world.md。新增加一篇文章,就在_posts目录,新建一个xxx.md的文件。

themes目录:是存放皮肤的,包括一套Javascript+CSS样式和基于EJS的模板设置。通过在themes目录下,新建一个子目录,就可以创建一套新的皮肤,当然我们也可以直接在landscape上面修改。

3.2 全局配置

_config.yml是全局的配置文件:很多的网站配置都在这个文件中定义。

  • 站点信息: 定义标题,作者,语言
  • URL: URL访问路径
  • 文件目录: 正文的存储目录
  • 写博客配置:文章标题,文章类型,外部链接等
  • 目录和标签:默认分类,分类图,标签图
  • 归档设置:归档的类型
  • 服务器设置:IP,访问端口,日志输出
  • 时间和日期格式: 时间显示格式,日期显示格式
  • 分页设置:每页显示数量
  • 评论:外挂的Disqus评论系统
  • 插件和皮肤:换皮肤,安装插件
  • Markdown语言:markdown的标准
  • CSS的stylus格式:是否允许压缩
  • 部署配置:github发布

查看文件:_config.yml


# Hexo Configuration
## Docs: http://hexo.io/docs/configuration.html
## Source: https://github.com/tommy351/hexo/

# 站点信息
title: Hexo博客
subtitle: 新的开始
description: blog.fens.me
author: bsspirit
email: bsspirit@gmail.com
language: zh-CN

# URL
## If your site is put in a subdirectory, set url as 'http://yoursite.com/child' and root as '/child/'
url: http://blog.fens.me
root: /
permalink: :year/:month/:day/:title/
tag_dir: tags
archive_dir: archives
category_dir: categories
code_dir: downloads/code

# 文件目录
source_dir: source
public_dir: public

# 写博客配置
new_post_name: :title.md # File name of new posts
default_layout: post
auto_spacing: false # Add spaces between asian characters and western characters
titlecase: false # Transform title into titlecase
external_link: true # Open external links in new tab
max_open_file: 100
multi_thread: true
filename_case: 0
render_drafts: false
post_asset_folder: false
highlight:
  enable: true
  line_number: true
  tab_replace:

# 目录和标签
default_category: uncategorized
category_map:
tag_map:

# 归档设置
## 2: Enable pagination
## 1: Disable pagination
## 0: Fully Disable
archive: 2
category: 2
tag: 2

# 服务器设置
## Hexo uses Connect as a server
## You can customize the logger format as defined in
## http://www.senchalabs.org/connect/logger.html
port: 4000
server_ip: 0.0.0.0
logger: false
logger_format:

# 时间和日期格式
## Hexo uses Moment.js to parse and display date
## You can customize the date format as defined in
## http://momentjs.com/docs/#/displaying/format/
date_format: MMM D YYYY
time_format: H:mm:ss

# 分页设置
## Set per_page to 0 to disable pagination
per_page: 10
pagination_dir: page

# 评论
disqus_shortname:

# 插件和皮肤
## Plugins: https://github.com/tommy351/hexo/wiki/Plugins
## Themes: https://github.com/tommy351/hexo/wiki/Themes
theme: landscape
exclude_generator:

# Markdown语法
## https://github.com/chjj/marked
markdown:
  gfm: true
  pedantic: false
  sanitize: false
  tables: true
  breaks: true
  smartLists: true
  smartypants: true

# CSS的stylus格式
stylus:
  compress: false

# 部署配置
## Docs: http://hexo.io/docs/deployment.html
deploy:
  type:

3.3 命令行使用

查看命令行帮助


D:\> hexo help
Usage: hexo 

Commands:
  help      Get help on a command
  init      Create a new Hexo folder
  migrate   Migrate your site from other system to Hexo
  version   Display version information

Global Options:
  --config   Specify config file instead of using _config.yml
  --debug    Display all verbose messages in the terminal
  --safe     Disable all plugins and scripts
  --silent   Hide output on console

For more help, you can use `hexo help [command]` for the detailed information
or you can check the docs: http://hexo.io/docs/

命令行解释:

  • help 查看帮助信息
  • init 创建一个hexo项目
  • migrate 从其他系统向hexo迁移
  • version 查看hexo的版本
  • –config参数,指定配置文件,代替默认的_config.yml
  • –debug参数,调试模式,输出所有日志信息
  • –safe参数,安全模式,禁用所有的插件和脚本
  • –silent参数,无日志输出模式

3.4 创建新文章

接下来,我们开始新博客了,创建第一博客文章。Hexo建议通过命令行操作,当然你也可以直接在_posts目录下创建文件。

通过命令创建新文章


D:\workspace\javascript\nodejs-hexo>hexo new 新的开始
[info] File created at D:\workspace\javascript\nodejs-hexo\source\_posts\新的开始.md

在_posts目录下,就会生成文件:”新的开始.md”。

hexo-post

然后,我们编辑文件:”新的开始.md”,以markdown语法写文章,然后保存。


title: 新的开始
date: 2014-05-07 18:44:12
tags:
- 开始
- 我
- 日记
categories: 日志
---

这是**新的开始**,我用hexo创建了第一篇文章。

通过下面的命令,就可以创建新文章
```{bash}
D:\workspace\javascript\nodejs-hexo>hexo new 新的开始
[info] File created at D:\workspace\javascript\nodejs-hexo\source\_posts\新的开始.md
```

感觉非常好。

在命令行,启动服务器。


D:\workspace\javascript\nodejs-hexo>hexo server
[info] Hexo is running at http://localhost:4000/. Press Ctrl+C to stop.

通过浏览器打开, http://localhost:4000/ ,就出现了我们新写的文章。

hexo-index

同时,网页的右侧还会出现Categories(目录),Tags(标签),Tag Cloud(标签云)的显示。

3.5 文章的语法

我们在写文章时,有一些语法的要求。

语法包括3部分:

  • 基本信息:标题,发布日期,分类目录,标签,类型,固定发布链接
  • 正文:markdown语法和Swig语法(掌握一个就行)
  • 特殊标记:引用,链接,图片,代码块,iframe,youtube视频

3.5.1 基本信息

必须在文件的顶部,—的行之前的部分。如:


title: 新的开始
date: 2014-05-07 18:44:12
updated	: 2014-05-10 18:44:12
permalink: abc
tags:
- 开始
- 我
- 日记
categories:
- 日志
- 第一天

---

我们可以对刚才发的文章,做上面的修改,再看效果。

3.5.2 正文

hexo的正文要求使用markdown的语法,这里就不在多说,请自行查看markdwon的文档。

3.5.3 特殊标记

hexo对于一些有特殊标记 文字块,做了特殊的定义。

引用


# Swig语法
{% blockquote Seth Godin http://sethgodin.typepad.com/seths_blog/2009/07/welcome-to-island-marketing.html Welcome to Island Marketing %}
Every interaction is both precious and an opportunity to delight.
{% endblockquote %}

# Markdown语法
> Every interaction is both precious and an opportunity to delight.

代码块


# Swig语法
{% codeblock .compact http://underscorejs.org/#compact Underscore.js %}
.compact([0, 1, false, 2, ‘’, 3]);
=> [1, 2, 3]
{% endcodeblock %}

# Markdown语法
```{bash}
.compact([0, 1, false, 2, ‘’, 3]);
=> [1, 2, 3]
```

链接


{% link 粉丝日志 http://blog.fens.me true 粉丝日志 %}

# Markdown语法
[粉丝日志](http://blog.fens.me)

图片,对于本地图片,需要在source目录下面新建一个目录images,然后把图片放到目录中。


# Swig语法
{% img /images/fens.me.png 400 600 这是一张图片 %}

# Markdown语法
![这是一张图片](/images/fens.me.png)

在浏览器中看到效果。

hexo-content

我们发现Swig的语法比markdown语法有更多的配置项,可以让页面更丰富,下面显示完整的基于Swig代码。


title: 新的开始
date: 2014-05-07 18:44:12
permalink: abc
tags:
- 开始
- 我
- 日记
categories:
- 日志
- 第一天

---

这是**新的开始**,我用hexo创建了第一篇文章。

通过下面的命令,就可以创建新文章
```{bash}
D:\workspace\javascript\nodejs-hexo>hexo new 新的开始
[info] File created at D:\workspace\javascript\nodejs-hexo\source\_posts\新的开始.md
```

感觉非常好。


## 引用
{% blockquote Seth Godin http://sethgodin.typepad.com/seths_blog/2009/07/welcome-to-island-marketing.html Welcome to Island Marketing %}
Every interaction is both precious and an opportunity to delight.
{% endblockquote %}

## 代码块
{% codeblock .compact http://underscorejs.org/#compact Underscore.js %}
.compact([0, 1, false, 2, ‘’, 3]);
=> [1, 2, 3]
{% endcodeblock %}

## 链接
{% link 粉丝日志 http://blog.fens.me true 粉丝日志 %}

## 图片
{% img /images/fens.me.png 400 600 这是一张图片 %}

4. 发布到项目到github

4.1 静态化处理

写完了文章,我们就可以发布了。要说明的一点是hexo的静态博客框架,那什么是静态博客呢?静态博客,是只包含html, javascript, css文件的网站,没有动态的脚本。虽然我们是用Node进行的开发,但博客的发布后就与Node无关了。在发布之前,我们要通过一条命令,把所有的文章都做静态化处理,就是生成对应的html, javascript, css,使得所有的文章都是由静态文件组成的。

静态化命令


D:\workspace\javascript\nodejs-hexo>hexo generate
[info] Files loaded in 0.895s
[create] Public: js\script.js
[create] Public: css\fonts\fontawesome-webfont.svg
[create] Public: css\fonts\FontAwesome.otf
[create] Public: css\fonts\fontawesome-webfont.ttf
[create] Public: css\fonts\fontawesome-webfont.eot
[create] Public: css\fonts\fontawesome-webfont.woff
[create] Public: fancybox\blank.gif
[create] Public: fancybox\fancybox_loading@2x.gif
[create] Public: fancybox\fancybox_overlay.png
[create] Public: css\images\banner.jpg
[create] Public: fancybox\fancybox_sprite.png
[create] Public: fancybox\jquery.fancybox.css
[create] Public: fancybox\fancybox_loading.gif
[create] Public: fancybox\fancybox_sprite@2x.png
[create] Public: fancybox\jquery.fancybox.js
[create] Public: fancybox\jquery.fancybox.pack.js
[create] Public: fancybox\helpers\jquery.fancybox-buttons.js
[create] Public: fancybox\helpers\fancybox_buttons.png
[create] Public: fancybox\helpers\jquery.fancybox-buttons.css
[create] Public: fancybox\helpers\jquery.fancybox-media.js
[create] Public: fancybox\helpers\jquery.fancybox-thumbs.css
[create] Public: fancybox\helpers\jquery.fancybox-thumbs.js
[create] Public: archives\index.html
[create] Public: images\fens.me.png
[create] Public: archives\2014\index.html
[create] Public: archives\2014\05\index.html
[create] Public: css\style.css
[create] Public: index.html
[create] Public: categories\日志\index.html
[create] Public: categories\日志\第一天\index.html
[create] Public: 2014\05\07\abc\index.html
[create] Public: 2014\05\07\hello-world\index.html
[create] Public: tags\开始\index.html
[create] Public: tags\我\index.html
[create] Public: tags\日记\index.html
[info] 35 files generated in 0.711s

在本地目录下,会生成一个public的目录,里面包括了所有静态化的文件。

4.2 发布到github

接下来,我们把这个博客发布到github。

在github中创建一个项目nodejs-hexo,项目地址:https://github.com/bsspirit/nodejs-hexo

编辑全局配置文件:_config.yml,找到deploy的部分,设置github的项目地址。


deploy:
  type: github
  repo: git@github.com:bsspirit/nodejs-hexo.git

然后,通过命令进行部署。


D:\workspace\javascript\nodejs-hexo>hexo deploy
[info] Start deploying: github
[info] Setting up GitHub deployment...
Initialized empty Git repository in D:/workspace/javascript/nodejs-hexo/.deploy/.git/
[master (root-commit) 43873d3] First commit
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 placeholder
[info] Clearing .deploy folder...
[info] Copying files from public folder...

// 省略部分输出

Branch gh-pages set up to track remote branch gh-pages from github.
To git@github.com:bsspirit/nodejs-hexo.git
 * [new branch]      gh-pages -> gh-pages
[info] Deploy done: github

这个静态的web网站就被部署到了github,检查一下分支是gh-pages。gh-pages是github为了web项目特别设置的分支。

hexo-github

然后,点击”Settings”,找到GitHub Pages,提示“Your site is published at http://bsspirit.github.io/nodejs-hexo”,打开网页 http://bsspirit.github.io/nodejs-hexo,就是我们刚刚发布的站点。

hexo-github-page

4.3 设置域名

看起来css和js的加载路径不太对,不过没有关系。接下来,我们配置好域名,这个路径就会正确的。比如,我有一个域名是 52u.me,为了中国DNS解析,我先把域名绑定在Dnspod管理,再做跳转。

域名有两种配置方式:

  • 主域名绑定:直接绑定主域名52u.me
  • 子域名绑定:绑定子域名blog.52u.me
    • 4.3.1 主域名绑定

      在dnspod控制台,设置主机记录@,类型A,到IP 192.30.252.153。

      dnspod-1

      大概等几分钟会生效。判断生效,对域名执行ping或者dig命令。

      
      D:\workspace\javascript\nodejs-hexo>ping 52u.me
      
      正在 Ping 52u.me [192.30.252.153] 具有 32 字节的数据:
      来自 192.30.252.153 的回复: 字节=32 时间=321ms TTL=48
      来自 192.30.252.153 的回复: 字节=32 时间=325ms TTL=48
      来自 192.30.252.153 的回复: 字节=32 时间=329ms TTL=48
      来自 192.30.252.153 的回复: 字节=32 时间=326ms TTL=48
      
      192.30.252.153 的 Ping 统计信息:
          数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
      往返行程的估计时间(以毫秒为单位):
          最短 = 321ms,最长 = 329ms,平均 = 325ms
      

      在github项目中,新建一个文件CNAME,文件中写出你要绑定的域名52u.me。通过浏览器,访问http://52u.me,就打开了我们建好的博客站点。

      52u.me

      4.3.2 子域名绑定

      有时候,我们的主域名正在使用着,需要先新建一个博客绑定到子域名,比如: blog.52u.me。

      dnspod-2

      在dnspod控制台,我们要做3步设置。

      • 设置主机记录github,类型A,到IP 199.27.76.133
      • 设置主机记录bsspirit.github.io,类型CNAME,到github.52u.me.
      • 设置主机记录blog,类型CNAME,到 bsspirit.github.io

      记得我们还要修改文件CNAME,改为blog.52u.me。通过浏览器,访问http://blog.52u.me,就可以打开了我们的博客站点了,而这次用的是二级域名。

      由于每次执行deploy的时候,gh-pages分支所有的文件都会被覆盖,所以我们最好在source目录下创建这个CNAME文件,这样每次部署就不用动手创建了。

      5. 替换皮肤

      博客系统流行的原因,是因为他的个人性,而皮肤正式个性化的一种体现。

      利用hexo替换皮肤,还是比较简单的,3步完成。

      5.1 找到一个皮肤或者自己开发一个皮肤

      打开hexo的皮肤列表页面,你可以找到很多的皮肤,网页地址: https://github.com/tommy351/hexo/wiki/Themes。

      5.2. 放到themes目录下

      比如,我觉得pacman(https://github.com/A-limon/pacman)这个皮肤还不错,我就可以下载皮肤到themes目录下面。

      通过git命令下载皮肤

      
      git clone https://github.com/A-limon/pacman.git themes/pacman
      

      5.3. 在_config.yml指定皮肤

      编辑文件_config.yml,找到theme一行,改成 theme: pacman

      本地启动hexo服务器,打开浏览器 http://localhost:4000

      hexo-theme

      新皮肤的效果还不错吧,然后静态化处理,再发布到github,就完成了站点的改版。

      6. 配置常用插件

      6.1 Disqus评论系统

      首先登陆http://disqus.com/ 网站,申请一个新网站的shortname,配置到_config.yml文件里,disqus_shortname: blog52ume

      disqus

      然后,你会得到一段js代码,把他复制文件 themes/pacman/layout/_partial/comment.ejs 。继续修改themes/pacman/layout/layout.ejs文件,增加对comment.ejs的引用。具体修改请详见代码。

      disqus-comment

      这样,评论系统就增加好了!!

      6.2 RSS订阅

      这个功能非常简单,因为已经有人写好了插件,我们只要安装插件就行了。

      
      D:\workspace\javascript\nodejs-hexo>npm install hexo-generator-feed
      npm WARN package.json hexo-site@2.5.5 No readme data!
      npm http GET https://registry.npmjs.org/hexo-generator-feed
      npm http 304 https://registry.npmjs.org/hexo-generator-feed
      npm http GET https://registry.npmjs.org/ejs/0.8.5
      npm http GET https://registry.npmjs.org/lodash/2.4.1
      npm http 304 https://registry.npmjs.org/ejs/0.8.5
      npm http 200 https://registry.npmjs.org/lodash/2.4.1
      npm http GET https://registry.npmjs.org/lodash/-/lodash-2.4.1.tgz
      npm http 200 https://registry.npmjs.org/lodash/-/lodash-2.4.1.tgz
      hexo-generator-feed@0.1.0 node_modules\hexo-generator-feed
      ├── ejs@0.8.5
      └── lodash@2.4.1
      

      启动服务器,用浏览器打开 http://localhost:4000/atom.xml, 就可以看到RSS已经生效了。

      6.3 Sitemap站长地图

      同样是一条命令,就可以完成。

      
      D:\workspace\javascript\nodejs-hexo>npm install hexo-generator-sitemap
      npm WARN package.json hexo-site@2.5.5 No readme data!
      npm http GET https://registry.npmjs.org/hexo-generator-sitemap
      npm http 304 https://registry.npmjs.org/hexo-generator-sitemap
      npm http GET https://registry.npmjs.org/ejs/0.8.5
      npm http GET https://registry.npmjs.org/lodash/2.4.1
      npm http 304 https://registry.npmjs.org/lodash/2.4.1
      npm http 304 https://registry.npmjs.org/ejs/0.8.5
      hexo-generator-sitemap@0.1.1 node_modules\hexo-generator-sitemap
      ├── ejs@0.8.5
      └── lodash@2.4.1
      

      启动服务器,用浏览器打开 http://localhost:4000/sitemap.xml, 就可以看到sitemap已经生效了。

      6.4 mathjax数学公式

      有时候,我们还需要一些高级功能,比如在网页上显示数学公式。

      新建一个文件themes/pacman/layout/_partial/mathjax.ejs,找到mathjax的调用代码复制到文件。

      
      <!-- mathjax config similar to math.stackexchange -->
      
      <script type="text/x-mathjax-config">
        MathJax.Hub.Config({
          tex2jax: {
            inlineMath: [ ['$','$'], ["\\(","\\)"] ],
            processEscapes: true
          }
        });
      </script>
      
      <script type="text/x-mathjax-config">
          MathJax.Hub.Config({
            tex2jax: {
              skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
            }
          });
      </script>
      
      <script type="text/x-mathjax-config">
          MathJax.Hub.Queue(function() {
              var all = MathJax.Hub.getAllJax(), i;
              for(i=0; i < all.length; i += 1) {
                  all[i].SourceElement().parentNode.className += ' has-jax';
              }
          });
      </script>
      
      <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
      </script>
      

      在themes/pacman/layout/_partial/after_footer.ejs 的最后一行,增加对mathjax的引用,详细内容请查看源代码。

      我们修改文章:source/_posts/新的开始.md

      增加公式:

      
      ## 公式
      $$J\_\alpha(x)=\sum _{m=0}^\infty \frac{(-1)^ m}{m! \, \Gamma (m + \alpha + 1)}{\left({\frac{x}{2}}\right)}^{2 m + \alpha }$$
      

      启动服务器,查看效果:

      math

      当然,除了这些还有很多需要的功能,像Google分析,百度统计,微薄转发等,大家可以自己找找,也可以自己开发一些插件!

      最后,本文的中代码已经上传的github,https://github.com/bsspirit/nodejs-hexo。 其中master分支是项目源代码,gh-pages分支是发布的站点。

      Hexo框架确实如同它介绍中的话: “A fast, simple & powerful blog framework, powered by Node.js.”,Noder还等什么,赶紧搭建一个博客吧!!

      转载请注明出处:
      http://blog.fens.me/hexo-bootstarp-github/

      打赏作者

FastRWeb跑在Web上的R程序

R的极客理想系列文章,涵盖了R的思想,使用,工具,创新等的一系列要点,以我个人的学习和体验去诠释R的强大。

R语言作为统计学一门语言,一直在小众领域闪耀着光芒。直到大数据的爆发,R语言变成了一门炙手可热的数据分析的利器。随着越来越多的工程背景的人的加入,R语言的社区在迅速扩大成长。现在已不仅仅是统计领域,教育,银行,电商,互联网….都在使用R语言。

要成为有理想的极客,我们不能停留在语法上,要掌握牢固的数学,概率,统计知识,同时还要有创新精神,把R语言发挥到各个领域。让我们一起动起来吧,开始R的极客理想。

关于作者:

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/r-fastrweb-rserve/

FastRWeb
前言

一直以来R语言都被用在,基于个人电脑的客户端程序上。我们习惯性的下载R安装包,在自己的电脑上面装好,写算法,运行。然后,以贴图或者文档的形式,发表自己的作品。

R如果可以运行在Server端,把结果以Web的方式发布!这才是互联网的工作方式!FastRWeb提供一种方式,可以实现B/S结构的R应用。

目录

  1. FastRWeb介绍
  2. FastRWeb架构原理
  3. FastRWeb安装
  4. FastRWeb使用

1. FastRWeb介绍

FastRWeb 是一个基础架构环境, 可以让R脚本运行在任何WebServer上,展示数据和图形。用户通过URL地址与R脚本进行通信交互。 FastRWeb 可以快速地构建一个R的Web环境,FastRWeb 底层依赖于CGI程序,也就是说,只要能支持CGI程序的WebServer,就可以运行FastRWeb。

本文以R语言的WebServer库Rserve为例,部署FastRWeb,实现R的Web应用。

官方发布页:http://www.rforge.net/FastRWeb/

2. FastRWeb架构原理

fastRweb-architect

  • 1. 浏览器通过http请求访问Web服务器
  • 2. Web服务器通过socket,把请求发给Rserve服务器
  • 3. Rserve调用FastRWeb环境,运行R的脚本,返回数据和图片
  • 4. 浏览器,得到结果,并在web上展示

3. FastRWeb安装

服务器系统环境

  • Linux: Ubuntu 12.04.2 LTS 64bit
  • R: 3.0.1 x86_64-pc-linux-gnu

FastRWeb安装


~ R
> install.packages("FastRWeb")
installing to /home/conan/R/x86_64-pc-linux-gnu-library/3.0/FastRWeb/libs
** R
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded
* DONE (FastRWeb)

由于FastRWeb依赖于cairo库,Cairo安装会用到Linux本地库,请参考文章:R语言的高质量图形渲染库Cairo

安装Rserve


> install.packages("Rserve")

有关Rserve的介绍,请参考文章:Rserve与Java的跨平台通信

创建FastRWeb基于Rserve的运行环境


~ cd /home/conan/R/x86_64-pc-linux-gnu-library/3.0/FastRWeb

~ sudo ./install.sh
Done.
Please check files in /var/FastRWeb/code
If they match tour setup, you can start Rserve using
/var/FastRWeb/code/start

查看生成的目录:/var/FastRWeb/code/


~ cd /var/FastRWeb/code/

~ ls -l
-rw-r--r-- 1 conan conan 1210 Oct 29 16:07 README
-rw-r--r-- 1 conan conan   79 Oct 29 17:50 rserve.conf
-rw-r--r-- 1 conan conan 2169 Oct 29 17:51 rserve.R
-rwxr-xr-x 1 conan conan  457 Oct 29 17:35 start
  • README:帮助说明
  • rserve.conf:Rserve的启动参数
  • rserve.R:Rserve的启动脚本
  • start:启动命令

修改文件:rserve.conf


~ vi rserve.conf

http.port 8888
remote enable
source /var/FastRWeb/code/rserve.R
control enable

默认情况,rserve是提供socket通信接口,为了web测试方便,我们改成用http的通信接口。

修改文件:rserve.R, 在文件上的最上面增加2行代码。


~ vi rserve.R

library(FastRWeb)
.http.request <- FastRWeb:::.http.request

## 原文代码
## ...

这样我们就改好了,成http为通信接口。

4. FastRWeb使用

启动服务


~ sudo ./start

R CMD Rserve --RS-conf /var/FastRWeb/code/rserve.conf --vanilla --no-save --RS-enable-remote

R version 3.0.1 (2013-05-16) -- "Good Sport"
Copyright (C) 2013 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

Starting Rserve on conan
Loading packages...
XML: TRUE
Cairo: TRUE
Matrix: TRUE
FastRWeb: TRUE
Rserv started in daemon mode.

从启动日志,我们看出XML, Cairo, Matrix, FastRWeb, Rserv几个包都加载了,正常运行。

查看系统进程和端口:


~ ps -aux|grep Rserve
conan    23739  0.0  1.4 120140 28916 ?        Ss   16:47   0:00 /usr/lib/R/bin/Rserve --RS-conf /var/FastRWeb/code/rserve.conf --vanilla --no-save --RS-enable-remote

~ sudo netstat -nltp|grep Rserve
tcp        0      0 0.0.0.0:8888            0.0.0.0:*               LISTEN      25778/Rserve
tcp        0      0 0.0.0.0:6311            0.0.0.0:*               LISTEN      25778/Rserve

有2个端口被打开了,一个是Rseve的socket端口6311,一个是http端口8888。

通过web进行访问:http://192.168.1.201:8888/example1.png

fastRweb-example1

这个图的R代码,实际对应的是文件:/var/FastRWeb/web.R/example1.png.R


~ vi /var/FastRWeb/web.R/example1.png.R

run <- function(...) {
  p <- WebPlot(600, 600)
  plot(rnorm(100), rnorm(100), pch = 19, col = 2)
  p
}

修改:/var/FastRWeb/web.R/example1.png.R


~ vi /var/FastRWeb/web.R/example1.png.R

run <- function(...) {
  p <- WebPlot(600, 600)
  plot(rnorm(400), rnorm(400), pch = 20, col = 3)
  p
}

在浏览器刷新页面:

fastRweb-example2

这样就实现了,通过web来执行R脚本,在web上画图。

在目录:/var/FastRWeb/web.R/,下面有几个例子,大家可以参考写自己的R语言脚本。


ls -l /var/FastRWeb/web.R
total 32
-rw-r--r-- 1 conan conan 790 Oct 29 16:07 common.R
-rw-r--r-- 1 conan conan 316 Oct 29 20:01 example1.png.R
-rw-r--r-- 1 conan conan 520 Oct 29 16:07 example2.R
-rw-r--r-- 1 conan conan 174 Oct 29 16:07 index.R
-rw-r--r-- 1 conan conan 215 Oct 29 16:07 info.R
-rw-r--r-- 1 conan conan  64 Oct 29 16:07 main.R
-rw-r--r-- 1 conan conan 167 Oct 29 16:07 README
-rw-r--r-- 1 conan conan 214 Oct 29 16:07 tmp.R

example2.R,可以接受页面传参数。

根据FastRWeb的说明,FastRWeb可以通过CGI,与任何的WebServer通信,这样我们就可以把R脚本部署在PHP, Python, Ruby, Java等高级语言的服务器上面了。

R-bloggers上有一篇文章,讲FastRWeb部署在基于Apache的XAMPP环境中:
http://www.r-bloggers.com/setting-up-fastrweb-on-mac-os-x/

感兴趣的同学,自行尝试吧!!

转载请注明出处:
http://blog.fens.me/r-fastrweb-rserve/

打赏作者

AngularJS从构建项目开始

AngularJS体验式编程系列文章,将介绍如何用angularjs构建一个强大的web前端系统。angularjs是由Google团队开发的一款非常优秀web前端框架。在当前如此多的web框架下,angularjs能脱颖而出,从架构设计上就高人一等,双向数据绑定,依赖注入,指令,MVC,模板。Angular.js创新地把后台技术融入前端开发,扫去jQuery一度的光芒。用angularjs就像写后台代码,更规范,更结构化,更可控。

关于作者

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:

http://blog.fens.me/angularjs-yeoman-project/

angularjs-yeoman

前言

随着AngularJS被越来越多的开发人员所了解,AngularJS的应用受到市场的好评。AngularJS是一种新型的以Javascript为基础的框架,以后台的编程思路影响着web前端的开发。在扎根细节之前,让我们先了解AngularJS项目构架。自顶向下的开始,就是不一样的开发。Angular体验式编程从此开始。

目录

  1. AngularJS介绍
  2. 构建AngularJS项目(Yeoman,angular-seed)
  3. AngularJS项目结构(Yeoman)
  4. AngularJS必备基础
  5. 启动项目

1. AngularJS介绍

AngularJS是一个为动态WEB应用设计的结构框架。它能让你使用HTML作为模板语言,通过扩展HTML的语法,让你能更清楚、简洁地构建你的应用组件。它的创新点在于,利用 数据绑定 和 依赖注入,它使你不用再写大量的代码了。这些全都是通过浏览器端的Javascript实现,这也使得它能够完美地和任何服务器端技术结合。

AngularJS介绍,摘自:http://angularjs.cn/A00n

2. 构建AngularJS项目(Yeoman,angular-seed)

说到构建项目,目前我了解的有三种:

  • 手工项目: 自己建目录,下载类库,写html,js,css,自己实现引用关系
  • angular-seed项目: 下载github的angular-seed,在别人的基础之上开发
  • Yeoman项目:通过Yeoman下载一个标准Yeoman项目,已经内置了grunt及各种工具包

1). 手工项目

构建手工项目是我们平时用的最多的一种方式了,适用于小型或demo项目。我不在解释,参照angularjs一步一步操作就行了。

2). angular-seed项目

一般把这个项目称为angular的“种子项目”,构建方法是去github下载项目源代码,基于已有项目结构再做开发。这种项目都融入了前人的经验,会以一种比较合理的结构,帮我们构建出项目的原型。适合于有一定规模项目开发,同时更适合geek的扩展。

下载演示一下构建过程


~ D:\workspace\javascript>git clone https://github.com/bsspirit/angular-seed.git
Cloning into 'angular-seed'...
remote: Counting objects: 1007, done.
remote: Compressing objects: 100% (497/497), done.
emote: Total 1007 (delta 521), reused 847 (delta 412)
Receiving objects: 100% (1007/1007), 6.30 MiB | 164 KiB/s, done.
Resolving deltas: 100% (521/521), done.

~ D:\workspace\javascript>cd angular-seed
~ D:\workspace\javascript\angular-seed>node scripts\web-server.js
Http Server running at http://localhost:8000/

打开浏览器:http://localhost:8000/app/index.html

angular-seed1

通过阅读READMD.md,我们可以了解这个”种子项目”如何使用。

项目目录及介绍


## Directory Layout
    app/                --> all of the files to be used in production
      css/              --> css files
        app.css         --> default stylesheet
      img/              --> image files
      index.html        --> app layout file (the main html template file of the app)
      index-async.html  --> just like index.html, but loads js files asynchronously
      js/               --> javascript files
        app.js          --> application
        controllers.js  --> application controllers
        directives.js   --> application directives
        filters.js      --> custom angular filters
        services.js     --> custom angular services
      lib/              --> angular and 3rd party javascript libraries
        angular/
          angular.js        --> the latest angular js
          angular.min.js    --> the latest minified angular js
          angular-*.js      --> angular add-on modules
          version.txt       --> version number
      partials/             --> angular view partials (partial html templates)
        partial1.html
        partial2.html

    config/karma.conf.js        --> config file for running unit tests with Karma
    config/karma-e2e.conf.js    --> config file for running e2e tests with Karma

    scripts/            --> handy shell/js/ruby scripts
      e2e-test.sh       --> runs end-to-end tests with Karma (*nix)
      e2e-test.bat      --> runs end-to-end tests with Karma (windows)
      test.bat          --> autotests unit tests with Karma (windows)
      test.sh           --> autotests unit tests with Karma (*nix)
      web-server.js     --> simple development webserver based on node.js

    test/               --> test source files and libraries
      e2e/              -->
        runner.html     --> end-to-end test runner (open in your browser to run)
        scenarios.js    --> end-to-end specs
      lib/
        angular/                --> angular testing libraries
          angular-mocks.js      --> mocks that replace certain angular services in tests
          angular-scenario.js   --> angular's scenario (end-to-end) test runner library
          version.txt           --> version file
      unit/                     --> unit level specs/tests
        controllersSpec.js      --> specs for controllers
        directivessSpec.js      --> specs for directives
        filtersSpec.js          --> specs for filters
        servicesSpec.js         --> specs for services

启动server

node scripts/web-server.js

单元测试(Unit test):karma + jasmine
端到端测试(End to End test):karma + jasmine + webserver

我们大概了解了“种子工程”的全貌,这样子心理有数了,就可以开始我们的项目开发了。

对于更高要求的开发者来说,“种子工程”的基础是不够。

  • 1. karam,jasmine都需要手动安装
  • 2. 没有代码自动化(自动增加controller…)
  • 3. 没有实现构建自动化(自动打包,自动压缩js…)
  • ……

一个大型项目构成是方方面面的,接下来我们通过标准化的Yeoman来构建一个企业级应用的项目基础。

3). Yeoman项目
yeoman是一个标准化的项目开发工作流工具,详细使用介绍请参考:Yeoman自动构建js项目

通过yeoman也构建项目

~ D:\workspace\javascript>mkdir nodejs-angular
~ D:\workspace\javascript>cd nodejs-angular
~ D:\workspace\javascript>npm install -g generator-angular

# 创建项目
~ D:\workspace\javascript\nodejs-angular>yo angular
[?] Would you like to include Twitter Bootstrap? Yes
[?] Would you like to use the SCSS version of Twitter Bootstrap with the Compass CSS Authoring Framework? No
[?] Which modules would you like to include? angular-resource.js, angular-cookies.js, angular-sanitize.js
   create app/styles/bootstrap.css
   create app/styles/main.css
   create app\index.html
   create bower.json
   create package.json
   create Gruntfile.js
   invoke   angular:common:D:\toolkit\nodejs\node_modules\generator-angular\app\index.js
   create     .bowerrc
   create     .editorconfig
   create     .gitattributes
   create     .jshintrc
   create     app\.buildignore
   create     app\.htaccess
   create     app\404.html
   create     app\favicon.ico
   create     app\robots.txt
   create     app\views\main.html
   create     test\.jshintrc
   create     test\runner.html
   create     .gitignore
   invoke   angular:main:D:\toolkit\nodejs\node_modules\generator-angular\app\index.js
   create     app\scripts\app.js
   invoke   angular:controller:D:\toolkit\nodejs\node_modules\generator-angular\app\index.js
   create     app\scripts\controllers\main.js
   create     test\spec\controllers\main.js
   invoke   karma:app
   create     karma.conf.js
   create     karma-e2e.conf.js
   create     .travis.yml

I'm all done. Running bower install & npm install for you to install the required dependencies. If this fails, try runni
ng the command yourself.

输入yo angular后,会提示我们要不要使用bootstrap;要不要用SCSS生成CSS;要不要include试angular的资源文件。我们选择完以后,会列出生成的项目文件,这个命令执行要2分钟左右,会自动下载很多的依赖包。

3. AngularJS项目结构(Yeoman)

yo-angular1

更直观地看到目录结构

  • .tmp:临时目录
  • app:开发的源代码的目录
  • dist:生成用于发布的项目
  • node_modules:nodejs依赖包
  • test:测试文件的目录
  • .bowerrc:bower属性
  • .editooconfig:对开发工具的属性配置
  • .gitattributes:git属性的配置
  • .gitignore:git管理文件的配置
  • .jshintr:JSHint配置
  • .travis.yml:travis-ci持续集成的配置
  • bower.json:bower依赖管理
  • Gruntfile.js:grunt开发过程管理
  • karma.conf.js:karma自动化测试
  • karma-e2e.conf.js:karma端到端自动化测试
  • package.json:项目依赖文件

4. AngularJS必备基础

从上面的目录结构,我们可以看出AngularJS对哪些东西是需要的。

git, yeoman, bower, grunt, karma …

所以,不要着急上手,先把基础工具都掌握,请参考系列文章:从零开始nodejs系列文章:成为高手 – 进阶篇

基础知识掌握多少,注定我们能开发多大规模的项目。

5. 启动项目

我们下载这个工程后,发现没有任何的文档。启动项目应该如何操作呢?

从刚才分析目录及文件结构,我们知道了这个项目是基于grunt构建的,那么一切的操作都会源于Gruntfile.js。grunt的详细介绍,请参考:grunt让Nodejs规范起来

打开Gruntfile.js,直接定位到grunt.registerTask()


  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'open',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'copy:dist',
    'cdnify',
    'ngmin',
    'cssmin',
    'uglify',
    'rev',
    'usemin'
  ]);

  grunt.registerTask('default', [
    'jshint',
    'test',
    'build'
  ]);

这里定义了4个任务:server,test,build, default。

从名字看就能猜出对应该的功能。

启动server


~ D:\workspace\javascript\nodejs-angular>grunt server
Running "server" task

Running "clean:server" (clean) task
Cleaning .tmp...OK

Running "concurrent:server" (concurrent) task

Running "coffee:dist" (coffee) task

Running "copy:styles" (copy) task

Running "autoprefixer:dist" (autoprefixer) task
File ".tmp/styles/bootstrap.css" created.
File ".tmp/styles/main.css" created.

Running "connect:livereload" (connect) task
Started connect web server on localhost:9000.

Running "open:server" (open) task

Running "watch" task
Waiting...

浏览器被自动打开:http://localhost:9000/#/

yo-angular2

执行default任务,生成用于部署的目录dist


~ D:\workspace\javascript\nodejs-angular>grunt --force
Running "jshint:all" (jshint) task
>> 3 files lint free.
Warning: Task "karma" not found. Used --force, continuing.

Running "clean:dist" (clean) task
Cleaning .tmp...OK
Cleaning dist/.htaccess...OK
Cleaning dist/404.html...OK
Cleaning dist/bower_components...OK
Cleaning dist/favicon.ico...OK
Cleaning dist/index.html...OK
Cleaning dist/robots.txt...OK
Cleaning dist/scripts...OK
Cleaning dist/styles...OK
Cleaning dist/views...OK

Running "useminPrepare:html" (useminPrepare) task
Going through app/index.html to update the config
Looking for build script HTML comment blocks

Found a block:
<!-- build:css(.tmp) styles/main.css -->
<link rel="stylesheet" href="styles/bootstrap.css">
<link rel="stylesheet" href="styles/main.css">
<!-- endbuild -->
Updating config with the following assets:
- .tmp\styles\bootstrap.css
- .tmp\styles\main.css

Found a block:
<!-- build:js scripts/plugins.js -->
<script src="bower_components/bootstrap-sass/js/bootstrap-affix.js"></script>
<script src="bower_components/bootstrap-sass/js/bootstrap-alert.js"></script>
<script src="bower_components/bootstrap-sass/js/bootstrap-dropdown.js"></script>
<script src="bower_components/bootstrap-sass/js/bootstrap-tooltip.js"></script>
<script src="bower_components/bootstrap-sass/js/bootstrap-modal.js"></script>
<script src="bower_components/bootstrap-sass/js/bootstrap-transition.js"></script>
<script src="bower_components/bootstrap-sass/js/bootstrap-button.js"></script>
<script src="bower_components/bootstrap-sass/js/bootstrap-popover.js"></script>
<script src="bower_components/bootstrap-sass/js/bootstrap-typeahead.js"></script>
<script src="bower_components/bootstrap-sass/js/bootstrap-carousel.js"></script>
<script src="bower_components/bootstrap-sass/js/bootstrap-scrollspy.js"></script>
<script src="bower_components/bootstrap-sass/js/bootstrap-collapse.js"></script>
<script src="bower_components/bootstrap-sass/js/bootstrap-tab.js"></script>
<!-- endbuild -->
Updating config with the following assets:
- app\bower_components\bootstrap-sass\js\bootstrap-affix.js
- app\bower_components\bootstrap-sass\js\bootstrap-alert.js
- app\bower_components\bootstrap-sass\js\bootstrap-dropdown.js
- app\bower_components\bootstrap-sass\js\bootstrap-tooltip.js
- app\bower_components\bootstrap-sass\js\bootstrap-modal.js
- app\bower_components\bootstrap-sass\js\bootstrap-transition.js
- app\bower_components\bootstrap-sass\js\bootstrap-button.js
- app\bower_components\bootstrap-sass\js\bootstrap-popover.js
- app\bower_components\bootstrap-sass\js\bootstrap-typeahead.js
- app\bower_components\bootstrap-sass\js\bootstrap-carousel.js
- app\bower_components\bootstrap-sass\js\bootstrap-scrollspy.js
- app\bower_components\bootstrap-sass\js\bootstrap-collapse.js
- app\bower_components\bootstrap-sass\js\bootstrap-tab.js

Found a block:
<!-- build:js scripts/modules.js -->
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="bower_components/angular-cookies/angular-cookies.js"></script>
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
<!-- endbuild -->
Updating config with the following assets:
- app\bower_components\angular-resource\angular-resource.js
- app\bower_components\angular-cookies\angular-cookies.js
- app\bower_components\angular-sanitize\angular-sanitize.js

Found a block:
<!-- build:js({.tmp,app}) scripts/scripts.js -->
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
<!-- endbuild -->
Updating config with the following assets:
- {.tmp,app}\scripts\app.js
- {.tmp,app}\scripts\controllers\main.js

Configuration is now:

cssmin:
{ 'dist\\styles\\main.css': 'dist\\styles\\main.css' }

concat:
{ 'dist\\styles\\main.css':
[ '.tmp\\styles\\bootstrap.css',
'.tmp\\styles\\main.css' ],
'dist\\scripts\\plugins.js':
[ 'app\\bower_components\\bootstrap-sass\\js\\bootstrap-affix.js',
'app\\bower_components\\bootstrap-sass\\js\\bootstrap-alert.js',
'app\\bower_components\\bootstrap-sass\\js\\bootstrap-dropdown.js',
'app\\bower_components\\bootstrap-sass\\js\\bootstrap-tooltip.js',
'app\\bower_components\\bootstrap-sass\\js\\bootstrap-modal.js',
'app\\bower_components\\bootstrap-sass\\js\\bootstrap-transition.js',
'app\\bower_components\\bootstrap-sass\\js\\bootstrap-button.js',
'app\\bower_components\\bootstrap-sass\\js\\bootstrap-popover.js',
'app\\bower_components\\bootstrap-sass\\js\\bootstrap-typeahead.js',
'app\\bower_components\\bootstrap-sass\\js\\bootstrap-carousel.js',
'app\\bower_components\\bootstrap-sass\\js\\bootstrap-scrollspy.js',
'app\\bower_components\\bootstrap-sass\\js\\bootstrap-collapse.js',
'app\\bower_components\\bootstrap-sass\\js\\bootstrap-tab.js' ],
'dist\\scripts\\modules.js':
[ 'app\\bower_components\\angular-resource\\angular-resource.js',
'app\\bower_components\\angular-cookies\\angular-cookies.js',
'app\\bower_components\\angular-sanitize\\angular-sanitize.js' ],
'dist\\scripts\\scripts.js':
[ '{.tmp,app}\\scripts\\app.js',
'{.tmp,app}\\scripts\\controllers\\main.js' ] }

uglify:
{ dist: { files: { '<%= yeoman.dist %>/scripts/scripts.js': [ 'dist/scripts/scripts.js' ] } },
'dist\\scripts\\plugins.js': 'dist\\scripts\\plugins.js',
'dist\\scripts\\modules.js': 'dist\\scripts\\modules.js',
'dist\\scripts\\scripts.js': 'dist\\scripts\\scripts.js' }

requirejs:
{}

Running "concurrent:dist" (concurrent) task

Running "copy:styles" (copy) task

Running "imagemin:dist" (imagemin) task

Running "coffee:dist" (coffee) task

Running "htmlmin:dist" (htmlmin) task

Running "svgmin:dist" (svgmin) task

Running "autoprefixer:dist" (autoprefixer) task
File ".tmp/styles/bootstrap.css" created.
File ".tmp/styles/main.css" created.

Running "concat:dist\styles\main.css" (concat) task
File "dist\styles\main.css" created.

Running "concat:dist\scripts\plugins.js" (concat) task
File "dist\scripts\plugins.js" created.

Running "concat:dist\scripts\modules.js" (concat) task
File "dist\scripts\modules.js" created.

Running "concat:dist\scripts\scripts.js" (concat) task
File "dist\scripts\scripts.js" created.

Running "copy:dist" (copy) task
Created 63 directories, copied 367 files

Running "cdnify:dist" (cdnify) task
Going through dist/404.html, dist/index.html to update script refs

Running "ngmin:dist" (ngmin) task
ngminifying dist/scripts/modules.js, dist/scripts/plugins.js, dist/scripts/scripts.js

Running "cssmin:dist\styles\main.css" (cssmin) task
File dist\styles\main.css created.

Running "uglify:dist" (uglify) task
File "dist/scripts/scripts.js" created.

Running "uglify:dist\scripts\plugins.js" (uglify) task
File "dist\scripts\plugins.js" created.

Running "uglify:dist\scripts\modules.js" (uglify) task
File "dist\scripts\modules.js" created.

Running "uglify:dist\scripts\scripts.js" (uglify) task
File "dist\scripts\scripts.js" created.

Running "rev:dist" (rev) task
dist/scripts/modules.js >> 6b865daa.modules.js
dist/scripts/plugins.js >> 76c21dca.plugins.js
dist/scripts/scripts.js >> ff635307.scripts.js
dist/styles/main.css >> a5c01db0.main.css

Running "usemin:html" (usemin) task

Processing as HTML - dist/404.html
Update the HTML to reference our concat/min/revved script files
Update the HTML with the new css filenames
Update the HTML with the new img filenames
Update the HTML with data-main tags
Update the HTML with the data tags
Update the HTML with background imgs, case there is some inline style
Update the HTML with anchors images
Update the HTML with reference in input

Processing as HTML - dist/index.html
Update the HTML to reference our concat/min/revved script files
<script src="scripts/plugins.js" changed to <script src="scripts/76c21dca.plugins.js"
<script src="scripts/modules.js" changed to <script src="scripts/6b865daa.modules.js"
<script src="scripts/scripts.js" changed to <script src="scripts/ff635307.scripts.js"
Update the HTML with the new css filenames
<link rel="stylesheet" href="styles/main.css" changed to <link rel="stylesheet" href="styles/a5c01db0.main.css"
Update the HTML with the new img filenames
Update the HTML with data-main tags
Update the HTML with the data tags
Update the HTML with background imgs, case there is some inline style
Update the HTML with anchors images
Update the HTML with reference in input

Processing as HTML - dist/views/main.html
Update the HTML to reference our concat/min/revved script files
Update the HTML with the new css filenames
Update the HTML with the new img filenames
Update the HTML with data-main tags
Update the HTML with the data tags
Update the HTML with background imgs, case there is some inline style
Update the HTML with anchors images
Update the HTML with reference in input

Running "usemin:css" (usemin) task

Processing as CSS - dist/styles/a5c01db0.main.css
Update the CSS with new img filenames

Done, but with warnings.

Elapsed time
jshint:all 69ms
clean:dist 593ms
useminPrepare:html 49ms
concurrent:dist 2s
autoprefixer:dist 65ms
concat:dist\scripts\scripts.js 26ms
copy:dist 475ms
ngmin 21ms
ngmin:dist 210ms
uglify:dist 37ms
uglify:dist\scripts\plugins.js 252ms
uglify:dist\scripts\modules.js 76ms
usemin:html 313ms
usemin:css 82ms
Total 5s

有了工具的支持,开发效率就是事半功倍了,前提是你要知道如何善用这些工具!

转载请注明出处:
http://blog.fens.me/angularjs-yeoman-project/

打赏作者