Categories
不学无术

宜送小爬虫

最近在看关于爬虫的东西,所以写了点练练手
目前还没竣工,只是到了能返回JSON数据的阶段
参考文献是:http://cuiqingcai.com/1001.html  作者写了一系列的爬虫教程,很实用!
用宜送转运的登录练练手吧,反正最近入了深圳海关坑,哎,。说多了都是泪
主要注意:

  1. 宜送登陆:HTTP头信息,Content-Type: application/x-www-form-urlencoded,不然直接提示登录失败。可能因为登录的人不多,目前没有设置验证码
  2. 获取账户订单信息:页面加载后,是AJAX向服务器二次请求JSON格式的订单信息的,而且发送的请求也是JSON格式来POST的。返回值也是JSON,直接免去了正则匹配啊!
# -*- coding: UTF-8 -*-
__author__ = 'Bowei'
import urllib
import urllib2
import cookielib
import json
class YiCrawler:
    statusCode = {
        'AIRARRDEST': '已到达',
        'DONE': '已完成',
        'CLEAR': '清关中',
        'CONFIRM': '已确认'
    }
    def __init__(self):
        self.userinfo = {'j_username': '',
                         'j_password': ''}
        self.cookie = cookielib.CookieJar()
        self.headers = {'Content-Type': 'application/x-www-form-urlencoded',
                        'Cache-Control': 'no-cache'}
        self.cookie_handler = urllib2.HTTPCookieProcessor(self.cookie)
        self.opener = urllib2.build_opener(self.cookie_handler)
        self.results = []   # 存放查询结果,队列中的元素是字典
    def get_status_str(self, status):
        if self.statusCode.has_key(status):
            return self.statusCode[status]
        else:
            return status
    def set_user_info(self, username, password):
        self.userinfo['j_username'] = username
        self.userinfo['j_password'] = password
    def login(self):
        print 'Login start'
        login_data = urllib.urlencode(self.userinfo)
        url = 'https://www.yi-express.com/login/send'
        request = urllib2.Request(url, login_data, self.headers)
        try:
            response = self.opener.open(request)
            print 'Finished login'
            return response.getcode()
        except urllib2.HTTPError, e:
            print e.code
            return e.code
    def get_page(self, pageNo=1, orderType="", warehouse=""):
        url = 'https://www.yi-express.com/customer/orderSearch'
        order_params = {"pageNo": str(pageNo), "orderNoOrName": "",
                        "warehouse": warehouse, "orderType": orderType,
                        "orderCreateStart": "", "orderCreateEnd": ""}
        request = urllib2.Request(url)
        request.add_header('Content-Type', 'application/json')
        try:
            response = self.opener.open(request, json.dumps(order_params))
            response_decoded = json.loads(response.read())
            for key, value in response_decoded.iteritems():
                # print str(key) + ': ' + str(value)
                if str(key) == 'result':
                    self.results.extend(value)
            return response_decoded['hasNext']
        except urllib2.HTTPError, e:
            print e.code
            return False
    def fetch_all(self):
        # 获取所有页面的数据
        self.results = []
        hasNext = True
        pageCount = 1
        while hasNext:
            hasNext = self.get_page(pageCount)
            pageCount += 1
    def print_results(self):
        print '========= START ==========='
        for item in self.results:
            print 'ID:\t' + item['id']
            print 'TIME:\t' + item['inDateWithFormat']
            print 'PRICE:\t' + str(item['realCost'])
            print 'WEIGHT:\t' + str(item['realWeight'])
            print 'EXP_NAME:\t' + item['expressName']
            print 'STATUS:\t' + self.get_status_str(item['statusCode'])
            print '\n'
if __name__ == '__main__':
    crawler = YiCrawler()
    print crawler.login()
    #crawler.get_page(pageNo=1)
    crawler.fetch_all()
    crawler.print_results()

 

Categories
不学无术

The Elements of Style 阅读笔记 之一 Elementary Rules of Usage

转载请注明来自http://boweihe.me/?p=1586

内容摘自《The Elements of Style (Fourth Edition)》,根据自己的理解写的,如有错误烦请指正。

Page 4 从句之前的逗号

     从句作非限定用法,用于补充主语时,需要加逗号。
     The audience, which had at first been indifferent, became more and more interested.
     这句话可以拆分成两个句子:
     The audience was at first indifferent. Later it became more and more interested.
     与之对应,用于限定时,从句前面不用加逗号
     People who live in glass houses shouldnt’t throw stones.

Page 5 不同连接词对应不同的逗号

     当两个子句对应同一个主语时,若使用but表示转折关系,前面要加逗号,但是and就不用.
     I have heard the arguments, but am still uncovinced.
     He has had several years’ expericnce and is thoroughly competent.

Page 6 分号和连接词

     如果没有连接两个子句的连接词,那么更应该使用分号将他们隔开
     It is nearly half past five; we cannot reach town before dark.
     上面的句子可以不经修改直接拆成两个独立的句子.
     或者使用连接词and,用逗号连接
     It is nearly half past five, and we cannot reach town before dark.
     但是仍要注意,如果使用副词(accordingly, besides, then, therefore, thus)而不是连接词的话,仍是需要使用分号分隔的
     I had never been in the place before; besides, it was dark as a tomb.
 

Page 6 冒号的使用

     不要用冒号将动词与补语分开来(如下句中的requires a knife)
     错误:Your dedicated whittler requires: a knife, a piece of wood, and a back proch.
     正确:Your dedicated whittler requires three props: a knife, a piece of wood, and a back porch.
     不要用冒号将介词和后面的宾语分开来(如下句中的 grows from theory)
     错误:Understanding is that penetrating quality of knowledge that grows from: theory, practice, conviction, assertion, error, and humiliation.
     正确:Understanding is that penetrating quality of knowledge that grows from theory, practice, conviction, assertion, error, and humiliation.
     如果后面的子句是对前面的补充或是解释,可以用冒号连接
     But even so, there was a directness and dispatch about animal burial: there was non stopover in the undertaker’s foul parlor, no wreath or spray.

Page 10 (谓语)动词单复数形式

     one of the …. 形势,是不用在意’one’的
     One of those people who are never ready on time.
     但是在使用each, either, everyone, everybody, neither, nobody, someone时谓语动词应当是单数形式
     Everybody thinks he has a unique sense of humor.
     使用none的时候应该注意表达的意思,如果意思是“没有,没有人..”的话用单数
     None of us is perfect.
     如果是“不止一个”的含义,那就是复数形式
     None are so fallible as those who are sure they are right.  最易犯錯者莫過於自信正確無誤之人
     使用with, as well as, in addition to, except, together with, no less than之类的连接词增加的额外部分,不作为考虑单复数的依据,即只考虑原本的主语就可以了
     His speech as well as his manner is objectionable.

Page 13 句子开头的分词短语要与后面主句的主语一致

    Walking slowly down the road, he saw a woman accompanied by two children.
     如果是要强调是那个woman慢慢走在路上,应该这么写
     He saw a waman, accompanied by two children, walking slowly down the road.
     错误:Young and inexperienced, the task seemed easy to me. 这里的主语是task,但是前面的短语确实形容me的
     正确:Young and inexperienced, I thought the task easy.
Categories
不学无术

Python numpy 按矩阵的某一列排序

可以参考我在StackOverflow上的回答
sorting arrays in numpy by column
利用numpy的argsort对需要排序的列标记序号(索引),然后直接改变原始矩阵的索引就行啦~

a = np.array([[1,2,3],[4,5,6],[0,0,1]])
a_arg = np.argsort(a[:,1]) #按第'1'列排序
a = a[a_arg]

 

Categories
不学无术

Glickman 的ELO算法

Glickman的ELO算法被搬到众包中实现,可以参考这篇

Bashir, M., Anderton, J., Wu, J., Golbus, P. B., Pavlu, V., & Aslam, J. A. (2013). A Document Rating System for Preference Judgements. In Proceedings of the 36th International ACM SIGIR Conference on Research and Development in Information Retrieval (pp. 909–912). New York, NY, USA: ACM. http://doi.org/10.1145/2484028.2484170
但是文章里算法描述的部分似乎有写错的地方,可能是作者不小心,把公式(7)的分母部分写错了(原文中的字母j没有换成自己的B)~
Glickman的原文是:
Glickman, M. E. (1999). Parameter estimation in large dynamic paired comparison experiments. Journal of the Royal Statistical Society: Series C (Applied Statistics), 48(3), 377-394.
QQ截图20150622165240
其中m为对手个数, 为与对手B进行比赛的次数; 为本局比赛A的结果(1-胜,0-负)
F是一个常量,(Bashir et al. 2013)中F=200, (Glickman, 1998)中F=400.
 
The rating algorithm is implemented as follows.
(a) Collect game outcome data over a rating period.
(b) At the end of the period, update players’ rating distributions due to game outcomes from their preperiod (prior) rating distributions.
(c) Subsequently update players’ rating distributions due to the passage of time.
Categories
不学无术

Matlab 变更(设定)启动时的默认目录|Change default startup folder of MATLAB

简要介绍下如何更改matlab启动后的默认目录
对于2013b及更早的版本,在matlab命令行输入(将THE NEW FOLDER替换为你的目录):

userpath('THE NEW FOLDER')

对于2014a和以后的版本,可以直接用图形界面设置,如下图:
主界面的Preferences,点进去后左侧选MATLAB底下的General,然后右侧就是了。可以选择默认目录,最后一次的工作目录或者指定一个~方便多了!
matlab_default_folder
 
文章改变自 https://marcowuen.wordpress.com/2014/10/13/howto-changing-matlabs-default-startup-folder/

Categories
不学无术

Crowd-BT算法模型 Part III [在线学习]

转载请注明来自http://boweihe.me/?p=1524
本文内容源自

Chen, X., Bennett, P. N., Collins-Thompson, K., & Horvitz, E. (2013, February). Pairwise ranking aggregation in a crowdsourced setting. InProceedings of the sixth ACM international conference on Web search and data mining (pp. 193-202). ACM.

第二部分还在努力学习,先把第三部分贴上来…有部分理解不全我就假装没看到了(捂脸)
在线学习:这个方法似乎是借鉴了Crowd-BT模型,但是最后参数更新的方法用了另外一套东西,可以独立于Crowd-BT的最优化而计算。
QQ截图20150517212359 QQ截图20150517212419 QQ截图20150517212505

Categories
不学无术

Crowd-BT算法模型 Part I [Bradley-Terry的延伸-模型基础]

转载请注明来自http://boweihe.me/?p=1524
本文内容源自

Chen, X., Bennett, P. N., Collins-Thompson, K., & Horvitz, E. (2013, February). Pairwise ranking aggregation in a crowdsourced setting. InProceedings of the sixth ACM international conference on Web search and data mining (pp. 193-202). ACM.

第一部分是对Crowd-BT中采用的模型的中文翻译及理解,不涉及后面的主动学习算法(因为暂时没看懂,哈哈)。
因为没弄懂Wordpress的公式插件,所以暂时用Word文档的截图了..
QQ截图20150515100316
 
QQ截图20150515100340
QQ截图20150515100406

Categories
不学无术 木有技术

MYSQL获取自增ID

参考:
http://flandycheng.blog.51cto.com/855176/280224
http://www.cnblogs.com/badtree/articles/2143103.html
http://my.oschina.net/fz04003/blog/63327
比较简单的方法是:
insert/select…等操作
然后直接下一条语句:

SELECT LAST_INSERT_ID()

LAST_INSERT_ID 是与table无关的,如果向表a插入数据后,再向表b插入数据,LAST_INSERT_ID会改变。
看参考文献中说,多用户的情况下这个方法不能用。不过在php环境下,单用户用足够的。
 

Categories
不学无术 木有技术

MySQL 引擎选择 MyISAM 还是 InnoDB?

建表的时候会选择数据库引擎,常用的有MyISAM和InnoDB,到底选哪个呢?
参考文献:

什么是MyISAM?
MyISAM是MySQL关系数据库管理系统的默认储存引擎。这种MySQL表存储结构从旧的ISAM代码扩展出许多有用的功能。在新版本的MySQL中,InnoDB引擎由于其对事务,参照完整性,以及更高的并发性等优点开始广泛的取代MyISAM。
每一个MyISAM表都对应于硬盘上的三个文件。这三个文件有一样的文件名,但是有不同的扩展名以指示其类型用途:.frm文件保存表的定义,但是这个文件并不是MyISAM引擎的一部,而是服务器的一部分;.MYD保存表的数据;.MYI是表的索引文件。
什么是InnoDB?
InnoDB是MySQL的另一个存储引擎,正成为目前MySQL AB所发行新版的标准,被包含在所有二进制安装包里。较之于其它的存储引擎它的优点是它支持兼容ACID的事务(类似于PostgreSQL),以及参数完整性(即对外键的支持)。
Oracle公司与2005年10月收购了Innobase。Innobase采用双认证授权。它使用GNU发行,也允许其它想将InnoDB结合到商业软件的团体获得授权。

MyISAM vs Innodb – Quick comparison Table | 快速比较表:

MyISAM Innodb
Not *ACID compliant and non-transactional *ACID compliant and hence fully transactional with ROLLBACK and COMMIT and support for Foreign Keys
MySQL 5.0 Default Engine Rackspace Cloud Default Engine
Offers Compression Offers Compression
Requires full repair/rebuild of indexes/tables Auto recovery from crash via replay of logs
Changed Db pages written to disk instantly Dirty pages converted from random to sequential before commit and flush to disk
No ordering in storage of data Row data stored in pages in PK order
Table level locking Row level locking

在StackOverflow上的小总结:

Frequent reading, almost no writing 常有读取操作,几乎没有写操作=> MyISAM
Full-text search in MySQL <= 5.5      => MyISAM

InnoDB的设计目标是处理大容量数据库系统,它的CPU利用率是其它基于磁盘的关系数据库引擎所不能比的。

Categories
不学无术

Amazon Mechanical Turk (MTurk) 基本概念及术语

发现这方面中文资料比较少,所以就自己翻译一段英文文章里面的吧。
英文水平烂,翻译得很蹩脚,但是有总比没有好~哈哈:)里面的一些术语都用了斜体英文了,不是没有中文意思,只是提起来比较方便。
参考文献:Leeper, T. (2013). Crowdsourcing with R and the MTurk API. The Political Methodologist, 20(2), 2-7.


Requesters: 向workers发布一个或一组任务并为此付款的那堆人;
HITs(Human Intelligence Tasks): MTurk平台的核心元素。一个HIT是requester发布给一个或多个worker执行的任务。在操作流程中,每个HIT都被赋予一个唯一的HITId。
Assignment: 一个worker完成的那个HIT称作assignment,每个worker只能对一个HIT完成一次assignment(像是一个实例),但是多个worker的话每个人都能完成一个assignment,除非达到requester设定的上限。多个HIT可以归并为一个HITType,允许一个worker完成多个相似的HIT。
MTurk执行与市场类似的供求原理。Workers任意选择想要执行的任务,取决于其耗时、赏金等情况。一个requester对HIT定价,但每个assignment的定价必须大于$0.005,提高定价不一定能对完成质量产生直接影响。MTurk平台对每笔支付抽取10%小费。
一旦一个worker完成了一个HIT,requester可以审查(review)这份assignment,决定该worker的答案是否满足要求。满足的话,表示这份答案被接受(approved),交易完成,付款(这部分的定价必须是固定的,不可以浮动)。如果requester认为这份任务可以给额外奖励,也可以另外付赏金(bonus)给这个worker。如果任务完成情况不佳,requester有权拒绝(reject)支付,同时这份assignment被释放给另一个worker重做。
MTurk_workflow