为什么我在运行下面显示的代码时会出错? (它用于 Coursera 上斯坦福“创业工程”类(class)的作业之一:https://class.coursera.org/startup-001/quiz/attempt?quiz_id=149)
该类(class)于 2013 年 6 月至 9 月开课,因此可能存在破坏脚本的 Node 或 csv 更新,对吧?作业不是关于修复脚本的,所以这个问题不是'作弊',而且类(class)目前没有运行..
所以,环境是: Ubuntu 14.04(内核 3-13-0-29-generic), Node v0.11.13, npm v1.4.9
我在主目录中有 npm install 的 csv、accounting util 和 reSTLer,脚本也在那里。
这让我完全难住了.... :-(
错误信息:
[ubuntu@ip-xxx-xxx-xxx-xxx:~]$node market-research.js
Invoked at command line.
Wrote market-research.csv
Symbol Name Market Cap Previous Close Price P/E Ratio Shares EPS Earnings
/home/ubuntu/market-research.js:47
csv()
^
TypeError: object is not a function
at csv2console (/home/ubuntu/market-research.js:47:5)
at Request.response2console (/home/ubuntu/market-research.js:65:13)
at Request.EventEmitter.emit (events.js:110:17)
at Request.mixin._fireSuccess (/home/ubuntu/node_modules/restler/lib/restler.js:226:10)
at /home/ubuntu/node_modules/restler/lib/restler.js:158:20
at IncomingMessage.parsers.auto (/home/ubuntu/node_modules/restler/lib/restler.js:394:7)
at Request.mixin._encode (/home/ubuntu/node_modules/restler/lib/restler.js:195:29)
at /home/ubuntu/node_modules/restler/lib/restler.js:154:16
at Request.mixin._decode (/home/ubuntu/node_modules/restler/lib/restler.js:170:7)
at IncomingMessage.<anonymous> (/home/ubuntu/node_modules/restler/lib/restler.js:147:14)
[ubuntu@ip-xxx-xxx-xxx-xxx:~]$
代码:
#!/usr/bin/env node
/*
Use the Yahoo Finance CSV API to do some basic market research calculations.
- Background: http://greenido.wordpress.com/2009/12/22/yahoo-finance-hidden-api/
- Example URL: http://finance.yahoo.com/d/quotes.csv?s=GOOG+FB+AAPL&f=snj1pr
s: Symbol
n: Name
j1: Market Capitalization (in billions)
p: Price-per-share (at previous close)
r: Price to Earnings Ratio
Further references.
- https://github.com/danwrong/restler
- https://github.com/wdavidw/node-csv
- http://josscrowcroft.github.io/accounting.js
- http://stackoverflow.com/questions/4981891/node-js-equivalent-of-pythons-if-name-main
- http://nodejs.org/docs/latest/api/util.html#util_util_format_format
*/
var util = require('util');
var fs = require('fs');
var rest = require('restler');
var csv = require('csv');
var accounting = require('accounting');
var CSVFILE_DEFAULT = "market-research.csv";
var SYMBOLS_DEFAULT = ["GOOG", "FB", "AAPL", "YHOO", "MSFT", "LNKD", "CRM"];
var COLUMNS_DEFAULT = 'snj1pr'; // http://greenido.wordpress.com/2009/12/22/yahoo-finance-hidden-api
var HEADERS_DEFAULT = ["Symbol", "Name", "Market Cap", "Previous Close Price",
"P/E Ratio", "Shares", "EPS", "Earnings"];
var financeurl = function(symbols, columns) {
return util.format(
'http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s',
symbols.join('+'),
columns);
};
var marketCapFloat = function(marketCapString) {
return parseFloat(marketCapString.split('B')[0]) * 1e9;
};
var csv2console = function(csvfile, headers) {
console.log(headers.join("\t"));
csv()
.from.path(csvfile)
.on('record', function(row, index) {
var shares = Math.round(marketCapFloat(row[2])/row[3], 0);
var eps = (row[3]/row[4]).toFixed(3);
var earnings = accounting.formatMoney(eps * shares);
outrow = row.concat([shares, eps, earnings]);
console.log(outrow.join("\t"));
});
};
var buildfn = function(csvfile, headers) {
var response2console = function(result, response) {
if (result instanceof Error) {
console.error('Error: ' + util.format(response.message));
} else {
console.error("Wrote %s", csvfile);
fs.writeFileSync(csvfile, result);
csv2console(csvfile, headers);
}
};
return response2console;
};
var marketResearch = function(symbols, columns, csvfile, headers) {
symbols = symbols || SYMBOLS_DEFAULT;
columns = columns || COLUMNS_DEFAULT;
csvfile = csvfile || CSVFILE_DEFAULT;
headers = headers || HEADERS_DEFAULT;
var apiurl = financeurl(symbols, columns);
var response2console = buildfn(csvfile, headers);
rest.get(apiurl).on('complete', response2console);
};
if(require.main == module) {
console.error('Invoked at command line.');
var symbols = process.argv;
if(symbols.length > 2) {
symbols = symbols.slice(2, symbols.length);
} else {
symbols = undefined;
};
marketResearch(symbols);
} else {
console.error('Invoked via library call');
}
exports.marketResearch = marketResearch;
脚本创建的market-research.csv内容:
"GOOG","Google Inc.",386.6B,569.20,29.49
"FB","Facebook, Inc.",194.5B,73.855,78.49
"AAPL","Apple Inc.",613.8B,102.25,16.49
"YHOO","Yahoo! Inc.",38.302B,38.31,33.11
"MSFT","Microsoft Corpora",374.3B,44.88,17.06
"LNKD","LinkedIn Corporat",27.747B,223.26,N/A
"CRM","Salesforce.com In",36.577B,58.29,N/A
最佳答案
Quantas 94 Heavy,感谢提示。
12 个月前,node-csv 的版本是 0.2,但现在是 0.4,API 也发生了变化。
我现在编写的 csv-console 函数如下:
// part of file market-script.js
// edited by Jeff Moye (Moyesoft)
// no attribution in the original file
var csv2console = function(csvfile, headers) {
console.log(headers.join("\t"));
var parser = csv.parse(); //create the parser
parser.on('readable', function(){ //the 'record' event no longer exists
// so instead we write a handler for the
// 'readable' event
while(record = parser.read()){ // and read() each record in a loop
var shares = Math.round(marketCapFloat(record[2])/record[3], 0);
var eps = (record[3]/record[4]).toFixed(3);
var earnings = accounting.formatMoney(eps * shares);
outrow = record.concat([shares, eps, earnings]);
console.log(outrow.join("\t"));
}
});
parser.on('error', function(err){ // we may as well have an error handler
console.log(err.message);
});
fs.createReadStream(csvfile).pipe(parser); //open file as a stream and pipe it to the parser
};
关于javascript - 为什么我在运行此示例 node.js 代码时得到 "TypeError: object is not a function"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25603947/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串