2 * jQuery Data Science Toolkit Plugin
3 * version: 0.50 (2013-05-19)
7 * dstk.street2coordinates('2543 Graystone Place, Simi Valley, CA 93065', myCallback);
9 * See http://www.datasciencetoolkit.org/developerdocs#javascript for a full
10 * guide on how to use this interface.
12 * This jQuery plugin is a simple way to access the Data Science Toolkit
13 * from Javascript. It's designed to work well cross-domain, using JSONP
14 * calls. The only restriction is that the text-handling calls can't take
15 * inputs of more than about 8k characters if going across domains, since
16 * they're limited to the length of a URL. You can work around this either
17 * by running your own copy of the server (it's available as a free VM and
18 * Amazon EC2 image) or just using a proxy from your domain.
20 * All code (C) Pete Warden, 2011
22 * This program is free software: you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as published by
24 * the Free Software Foundation, either version 3 of the License, or
25 * (at your option) any later version.
27 * This program is distributed in the hope that it will be useful,
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 * GNU General Public License for more details.
32 * You should have received a copy of the GNU General Public License
33 * along with this program. If not, see <http://www.gnu.org/licenses/>.
39 // Call this to create a new Data Science Toolkit object, that you can then
40 // use to make API calls.
41 $.DSTK = function(options) {
43 if ((typeof options == 'undefined')||(options == null)) {
47 // These are the only dependencies on JQuery. If you want to run the code without
48 // the framework, you can replace them with matching functions and call the
49 // constructor directly, eg
50 // var dstk = new DSTK({ajaxFunction: myAjax, toJSONFunction: myToJSON});
51 options.ajaxFunction = $.ajax;
52 options.toJSONFunction = $.toJSON;
54 return new DSTK(options);
58 function DSTK(options) {
60 var defaultOptions = {
61 apiBase: 'http://www.datasciencetoolkit.org',
65 if ((typeof options == 'undefined')||(options == null)) {
66 options = defaultOptions;
68 for (var key in defaultOptions) {
69 if (typeof options[key]=='undefined') {
70 options[key] = defaultOptions[key];
75 this.apiBase = options.apiBase;
76 this.ajaxFunction = options.ajaxFunction;
77 this.toJSONFunction = options.toJSONFunction;
79 if (options.checkVersion) {
84 DSTK.prototype.checkVersion = function() {
86 var requiredVersion = 50;
88 var apiUrl = this.apiBase+'/info';
90 this.ajaxFunction(apiUrl, {
91 success: function(result) {
92 var actualVersion = result['version'];
93 if (actualVersion<requiredVersion) {
94 throw 'DSTK: Version '+actualVersion+' found at "'+apiUrl+'" but '+requiredVersion+' is required';
103 // See http://www.datasciencetoolkit.org/developerdocs for information on these calls
105 DSTK.prototype.ip2coordinates = function(ips, callback) {
107 if (typeof ips.length == 'undefined') {
111 var apiUrl = this.apiBase+'/ip2coordinates';
112 apiUrl += '/'+encodeURIComponent($.toJSON(ips));
114 this.ajaxFunction(apiUrl, {
121 DSTK.prototype.street2coordinates = function(addresses, callback) {
123 if (typeof addresses.length == 'undefined') {
124 addresses = [addresses];
127 var apiUrl = this.apiBase+'/street2coordinates';
128 apiUrl += '/'+encodeURIComponent($.toJSON(addresses));
137 DSTK.prototype.coordinates2politics = function(coordinates, callback) {
139 if (typeof coordinates.length == 'undefined') {
140 coordinates = [coordinates];
143 var apiUrl = this.apiBase+'/coordinates2politics';
144 apiUrl += '/'+encodeURIComponent($.toJSON(coordinates));
153 DSTK.prototype.text2places = function(text, callback) {
154 this.makeTextCall(text, callback, 'text2places');
157 DSTK.prototype.text2sentences = function(text, callback) {
158 this.makeTextCall(text, callback, 'text2sentences');
161 DSTK.prototype.html2text = function(html, callback) {
162 this.makeTextCall(html, callback, 'html2text');
165 DSTK.prototype.html2story = function(html, callback) {
166 this.makeTextCall(html, callback, 'html2story');
169 DSTK.prototype.text2people = function(text, callback) {
170 this.makeTextCall(text, callback, 'text2people');
173 DSTK.prototype.text2times = function(text, callback) {
174 this.makeTextCall(text, callback, 'text2times');
177 DSTK.prototype.googlestylegeocoder = function(address, callback) {
178 var apiUrl = this.apiBase+'/maps/api/geocode/json';
179 apiUrl += '?address='+encodeURIComponent(address);
187 DSTK.prototype.text2sentiment = function(text, callback) {
188 this.makeTextCall(text, callback, 'text2sentiment');
191 DSTK.prototype.coordinates2statistics = function(coordinates, callback) {
193 if (typeof coordinates.length == 'undefined') {
194 coordinates = [coordinates];
197 var apiUrl = this.apiBase+'/coordinates2statistics';
198 apiUrl += '/'+encodeURIComponent($.toJSON(coordinates));
207 DSTK.prototype.makeTextCall = function(text, callback, method) {
209 var apiUrl = this.apiBase+'/'+method;
210 var apiSuffix = encodeURIComponent($.toJSON([text]));
212 if (apiSuffix.length<7500) {
213 apiUrl += '/'+apiSuffix;
237 * version: 2.1 (2009-08-14)
239 * This document is licensed as free software under the terms of the
240 * MIT License: http://www.opensource.org/licenses/mit-license.php
242 * Brantley Harris wrote this plugin. It is based somewhat on the JSON.org
243 * website's http://www.json.org/json2.js, which proclaims:
244 * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
247 * It is also influenced heavily by MochiKit's serializeJSON, which is
248 * copyrighted 2005 by Bob Ippolito.
252 /** jQuery.toJSON( json-serializble )
253 Converts the given argument into a JSON respresentation.
255 If an object has a "toJSON" function, that will be used to get the representation.
256 Non-integer/string keys are skipped in the object, as are keys that point to a function.
259 The *thing* to be converted.
261 $.toJSON = function(o)
263 if (typeof(JSON) == 'object' && JSON.stringify)
264 return JSON.stringify(o);
266 var type = typeof(o);
271 if (type == "undefined")
274 if (type == "number" || type == "boolean")
277 if (type == "string")
278 return $.quoteString(o);
280 if (type == 'object')
282 if (typeof o.toJSON == "function")
283 return $.toJSON( o.toJSON() );
285 if (o.constructor === Date)
287 var month = o.getUTCMonth() + 1;
288 if (month < 10) month = '0' + month;
290 var day = o.getUTCDate();
291 if (day < 10) day = '0' + day;
293 var year = o.getUTCFullYear();
295 var hours = o.getUTCHours();
296 if (hours < 10) hours = '0' + hours;
298 var minutes = o.getUTCMinutes();
299 if (minutes < 10) minutes = '0' + minutes;
301 var seconds = o.getUTCSeconds();
302 if (seconds < 10) seconds = '0' + seconds;
304 var milli = o.getUTCMilliseconds();
305 if (milli < 100) milli = '0' + milli;
306 if (milli < 10) milli = '0' + milli;
308 return '"' + year + '-' + month + '-' + day + 'T' +
309 hours + ':' + minutes + ':' + seconds +
313 if (o.constructor === Array)
316 for (var i = 0; i < o.length; i++)
317 ret.push( $.toJSON(o[i]) || "null" );
319 return "[" + ret.join(",") + "]";
327 if (type == "number")
328 name = '"' + k + '"';
329 else if (type == "string")
330 name = $.quoteString(k);
332 continue; //skip non-string or number keys
334 if (typeof o[k] == "function")
335 continue; //skip pairs where the value is a function.
337 var val = $.toJSON(o[k]);
339 pairs.push(name + ":" + val);
342 return "{" + pairs.join(", ") + "}";
346 /** jQuery.evalJSON(src)
347 Evaluates a given piece of json source.
349 $.evalJSON = function(src)
351 if (typeof(JSON) == 'object' && JSON.parse)
352 return JSON.parse(src);
353 return eval("(" + src + ")");
356 /** jQuery.secureEvalJSON(src)
357 Evals JSON in a way that is *more* secure.
359 $.secureEvalJSON = function(src)
361 if (typeof(JSON) == 'object' && JSON.parse)
362 return JSON.parse(src);
365 filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
366 filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
367 filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
369 if (/^[\],:{}\s]*$/.test(filtered))
370 return eval("(" + src + ")");
372 throw new SyntaxError("Error parsing JSON, source is not valid.");
375 /** jQuery.quoteString(string)
376 Returns a string-repr of a string, escaping quotes intelligently.
377 Mostly a support function for toJSON.
380 >>> jQuery.quoteString("apple")
383 >>> jQuery.quoteString('"Where are we going?", she asked.')
384 "\"Where are we going?\", she asked."
386 $.quoteString = function(string)
388 if (string.match(_escapeable))
390 return '"' + string.replace(_escapeable, function (a)
393 if (typeof c === 'string') return c;
395 return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
398 return '"' + string + '"';
401 var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;