Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50654 views
1
// Copyright (c) IPython Development Team.
2
// Distributed under the terms of the Modified BSD License.
3
4
define([
5
'base/js/namespace',
6
'jquery',
7
'codemirror/lib/codemirror',
8
'moment',
9
// silently upgrades CodeMirror
10
'codemirror/mode/meta',
11
], function(IPython, $, CodeMirror, moment){
12
"use strict";
13
14
var load_extensions = function () {
15
// load one or more IPython notebook extensions with requirejs
16
17
var extensions = [];
18
var extension_names = arguments;
19
for (var i = 0; i < extension_names.length; i++) {
20
extensions.push("nbextensions/" + arguments[i]);
21
}
22
23
require(extensions,
24
function () {
25
for (var i = 0; i < arguments.length; i++) {
26
var ext = arguments[i];
27
var ext_name = extension_names[i];
28
// success callback
29
console.log("Loaded extension: " + ext_name);
30
if (ext && ext.load_ipython_extension !== undefined) {
31
ext.load_ipython_extension();
32
}
33
}
34
},
35
function (err) {
36
// failure callback
37
console.log("Failed to load extension(s):", err.requireModules, err);
38
}
39
);
40
};
41
42
IPython.load_extensions = load_extensions;
43
44
/**
45
* Wait for a config section to load, and then load the extensions specified
46
* in a 'load_extensions' key inside it.
47
*/
48
function load_extensions_from_config(section) {
49
section.loaded.then(function() {
50
if (section.data.load_extensions) {
51
var nbextension_paths = Object.getOwnPropertyNames(
52
section.data.load_extensions);
53
load_extensions.apply(this, nbextension_paths);
54
}
55
});
56
}
57
58
//============================================================================
59
// Cross-browser RegEx Split
60
//============================================================================
61
62
// This code has been MODIFIED from the code licensed below to not replace the
63
// default browser split. The license is reproduced here.
64
65
// see http://blog.stevenlevithan.com/archives/cross-browser-split for more info:
66
/*!
67
* Cross-Browser Split 1.1.1
68
* Copyright 2007-2012 Steven Levithan <stevenlevithan.com>
69
* Available under the MIT License
70
* ECMAScript compliant, uniform cross-browser split method
71
*/
72
73
/**
74
* Splits a string into an array of strings using a regex or string
75
* separator. Matches of the separator are not included in the result array.
76
* However, if `separator` is a regex that contains capturing groups,
77
* backreferences are spliced into the result each time `separator` is
78
* matched. Fixes browser bugs compared to the native
79
* `String.prototype.split` and can be used reliably cross-browser.
80
* @param {String} str String to split.
81
* @param {RegExp} separator Regex to use for separating
82
* the string.
83
* @param {Number} [limit] Maximum number of items to include in the result
84
* array.
85
* @returns {Array} Array of substrings.
86
* @example
87
*
88
* // Basic use
89
* regex_split('a b c d', ' ');
90
* // -> ['a', 'b', 'c', 'd']
91
*
92
* // With limit
93
* regex_split('a b c d', ' ', 2);
94
* // -> ['a', 'b']
95
*
96
* // Backreferences in result array
97
* regex_split('..word1 word2..', /([a-z]+)(\d+)/i);
98
* // -> ['..', 'word', '1', ' ', 'word', '2', '..']
99
*/
100
var regex_split = function (str, separator, limit) {
101
var output = [],
102
flags = (separator.ignoreCase ? "i" : "") +
103
(separator.multiline ? "m" : "") +
104
(separator.extended ? "x" : "") + // Proposed for ES6
105
(separator.sticky ? "y" : ""), // Firefox 3+
106
lastLastIndex = 0,
107
separator2, match, lastIndex, lastLength;
108
// Make `global` and avoid `lastIndex` issues by working with a copy
109
separator = new RegExp(separator.source, flags + "g");
110
111
var compliantExecNpcg = typeof(/()??/.exec("")[1]) === "undefined";
112
if (!compliantExecNpcg) {
113
// Doesn't need flags gy, but they don't hurt
114
separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
115
}
116
/* Values for `limit`, per the spec:
117
* If undefined: 4294967295 // Math.pow(2, 32) - 1
118
* If 0, Infinity, or NaN: 0
119
* If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
120
* If negative number: 4294967296 - Math.floor(Math.abs(limit))
121
* If other: Type-convert, then use the above rules
122
*/
123
limit = typeof(limit) === "undefined" ?
124
-1 >>> 0 : // Math.pow(2, 32) - 1
125
limit >>> 0; // ToUint32(limit)
126
for (match = separator.exec(str); match; match = separator.exec(str)) {
127
// `separator.lastIndex` is not reliable cross-browser
128
lastIndex = match.index + match[0].length;
129
if (lastIndex > lastLastIndex) {
130
output.push(str.slice(lastLastIndex, match.index));
131
// Fix browsers whose `exec` methods don't consistently return `undefined` for
132
// nonparticipating capturing groups
133
if (!compliantExecNpcg && match.length > 1) {
134
match[0].replace(separator2, function () {
135
for (var i = 1; i < arguments.length - 2; i++) {
136
if (typeof(arguments[i]) === "undefined") {
137
match[i] = undefined;
138
}
139
}
140
});
141
}
142
if (match.length > 1 && match.index < str.length) {
143
Array.prototype.push.apply(output, match.slice(1));
144
}
145
lastLength = match[0].length;
146
lastLastIndex = lastIndex;
147
if (output.length >= limit) {
148
break;
149
}
150
}
151
if (separator.lastIndex === match.index) {
152
separator.lastIndex++; // Avoid an infinite loop
153
}
154
}
155
if (lastLastIndex === str.length) {
156
if (lastLength || !separator.test("")) {
157
output.push("");
158
}
159
} else {
160
output.push(str.slice(lastLastIndex));
161
}
162
return output.length > limit ? output.slice(0, limit) : output;
163
};
164
165
//============================================================================
166
// End contributed Cross-browser RegEx Split
167
//============================================================================
168
169
170
var uuid = function () {
171
/**
172
* http://www.ietf.org/rfc/rfc4122.txt
173
*/
174
var s = [];
175
var hexDigits = "0123456789ABCDEF";
176
for (var i = 0; i < 32; i++) {
177
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
178
}
179
s[12] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
180
s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
181
182
var uuid = s.join("");
183
return uuid;
184
};
185
186
187
//Fix raw text to parse correctly in crazy XML
188
function xmlencode(string) {
189
return string.replace(/\&/g,'&'+'amp;')
190
.replace(/</g,'&'+'lt;')
191
.replace(/>/g,'&'+'gt;')
192
.replace(/\'/g,'&'+'apos;')
193
.replace(/\"/g,'&'+'quot;')
194
.replace(/`/g,'&'+'#96;');
195
}
196
197
198
//Map from terminal commands to CSS classes
199
var ansi_colormap = {
200
"01":"ansibold",
201
202
"30":"ansiblack",
203
"31":"ansired",
204
"32":"ansigreen",
205
"33":"ansiyellow",
206
"34":"ansiblue",
207
"35":"ansipurple",
208
"36":"ansicyan",
209
"37":"ansigray",
210
211
"40":"ansibgblack",
212
"41":"ansibgred",
213
"42":"ansibggreen",
214
"43":"ansibgyellow",
215
"44":"ansibgblue",
216
"45":"ansibgpurple",
217
"46":"ansibgcyan",
218
"47":"ansibggray"
219
};
220
221
function _process_numbers(attrs, numbers) {
222
// process ansi escapes
223
var n = numbers.shift();
224
if (ansi_colormap[n]) {
225
if ( ! attrs["class"] ) {
226
attrs["class"] = ansi_colormap[n];
227
} else {
228
attrs["class"] += " " + ansi_colormap[n];
229
}
230
} else if (n == "38" || n == "48") {
231
// VT100 256 color or 24 bit RGB
232
if (numbers.length < 2) {
233
console.log("Not enough fields for VT100 color", numbers);
234
return;
235
}
236
237
var index_or_rgb = numbers.shift();
238
var r,g,b;
239
if (index_or_rgb == "5") {
240
// 256 color
241
var idx = parseInt(numbers.shift(), 10);
242
if (idx < 16) {
243
// indexed ANSI
244
// ignore bright / non-bright distinction
245
idx = idx % 8;
246
var ansiclass = ansi_colormap[n[0] + (idx % 8).toString()];
247
if ( ! attrs["class"] ) {
248
attrs["class"] = ansiclass;
249
} else {
250
attrs["class"] += " " + ansiclass;
251
}
252
return;
253
} else if (idx < 232) {
254
// 216 color 6x6x6 RGB
255
idx = idx - 16;
256
b = idx % 6;
257
g = Math.floor(idx / 6) % 6;
258
r = Math.floor(idx / 36) % 6;
259
// convert to rgb
260
r = (r * 51);
261
g = (g * 51);
262
b = (b * 51);
263
} else {
264
// grayscale
265
idx = idx - 231;
266
// it's 1-24 and should *not* include black or white,
267
// so a 26 point scale
268
r = g = b = Math.floor(idx * 256 / 26);
269
}
270
} else if (index_or_rgb == "2") {
271
// Simple 24 bit RGB
272
if (numbers.length > 3) {
273
console.log("Not enough fields for RGB", numbers);
274
return;
275
}
276
r = numbers.shift();
277
g = numbers.shift();
278
b = numbers.shift();
279
} else {
280
console.log("unrecognized control", numbers);
281
return;
282
}
283
if (r !== undefined) {
284
// apply the rgb color
285
var line;
286
if (n == "38") {
287
line = "color: ";
288
} else {
289
line = "background-color: ";
290
}
291
line = line + "rgb(" + r + "," + g + "," + b + ");";
292
if ( !attrs.style ) {
293
attrs.style = line;
294
} else {
295
attrs.style += " " + line;
296
}
297
}
298
}
299
}
300
301
function ansispan(str) {
302
// ansispan function adapted from github.com/mmalecki/ansispan (MIT License)
303
// regular ansi escapes (using the table above)
304
var is_open = false;
305
return str.replace(/\033\[(0?[01]|22|39)?([;\d]+)?m/g, function(match, prefix, pattern) {
306
if (!pattern) {
307
// [(01|22|39|)m close spans
308
if (is_open) {
309
is_open = false;
310
return "</span>";
311
} else {
312
return "";
313
}
314
} else {
315
is_open = true;
316
317
// consume sequence of color escapes
318
var numbers = pattern.match(/\d+/g);
319
var attrs = {};
320
while (numbers.length > 0) {
321
_process_numbers(attrs, numbers);
322
}
323
324
var span = "<span ";
325
Object.keys(attrs).map(function (attr) {
326
span = span + " " + attr + '="' + attrs[attr] + '"';
327
});
328
return span + ">";
329
}
330
});
331
}
332
333
// Transform ANSI color escape codes into HTML <span> tags with css
334
// classes listed in the above ansi_colormap object. The actual color used
335
// are set in the css file.
336
function fixConsole(txt) {
337
txt = xmlencode(txt);
338
339
// Strip all ANSI codes that are not color related. Matches
340
// all ANSI codes that do not end with "m".
341
var ignored_re = /(?=(\033\[[\d;=]*[a-ln-zA-Z]{1}))\1(?!m)/g;
342
txt = txt.replace(ignored_re, "");
343
344
// color ansi codes
345
txt = ansispan(txt);
346
return txt;
347
}
348
349
// Remove chunks that should be overridden by the effect of
350
// carriage return characters
351
function fixCarriageReturn(txt) {
352
var tmp = txt;
353
do {
354
txt = tmp;
355
tmp = txt.replace(/\r+\n/gm, '\n'); // \r followed by \n --> newline
356
tmp = tmp.replace(/^.*\r+/gm, ''); // Other \r --> clear line
357
} while (tmp.length < txt.length);
358
return txt;
359
}
360
361
// Locate any URLs and convert them to a anchor tag
362
function autoLinkUrls(txt) {
363
return txt.replace(/(^|\s)(https?|ftp)(:[^'">\s]+)/gi,
364
"$1<a target=\"_blank\" href=\"$2$3\">$2$3</a>");
365
}
366
367
var points_to_pixels = function (points) {
368
/**
369
* A reasonably good way of converting between points and pixels.
370
*/
371
var test = $('<div style="display: none; width: 10000pt; padding:0; border:0;"></div>');
372
$('body').append(test);
373
var pixel_per_point = test.width()/10000;
374
test.remove();
375
return Math.floor(points*pixel_per_point);
376
};
377
378
var always_new = function (constructor) {
379
/**
380
* wrapper around contructor to avoid requiring `var a = new constructor()`
381
* useful for passing constructors as callbacks,
382
* not for programmer laziness.
383
* from http://programmers.stackexchange.com/questions/118798
384
*/
385
return function () {
386
var obj = Object.create(constructor.prototype);
387
constructor.apply(obj, arguments);
388
return obj;
389
};
390
};
391
392
var url_path_join = function () {
393
/**
394
* join a sequence of url components with '/'
395
*/
396
var url = '';
397
for (var i = 0; i < arguments.length; i++) {
398
if (arguments[i] === '') {
399
continue;
400
}
401
if (url.length > 0 && url[url.length-1] != '/') {
402
url = url + '/' + arguments[i];
403
} else {
404
url = url + arguments[i];
405
}
406
}
407
url = url.replace(/\/\/+/, '/');
408
return url;
409
};
410
411
var url_path_split = function (path) {
412
/**
413
* Like os.path.split for URLs.
414
* Always returns two strings, the directory path and the base filename
415
*/
416
417
var idx = path.lastIndexOf('/');
418
if (idx === -1) {
419
return ['', path];
420
} else {
421
return [ path.slice(0, idx), path.slice(idx + 1) ];
422
}
423
};
424
425
var parse_url = function (url) {
426
/**
427
* an `a` element with an href allows attr-access to the parsed segments of a URL
428
* a = parse_url("http://localhost:8888/path/name#hash")
429
* a.protocol = "http:"
430
* a.host = "localhost:8888"
431
* a.hostname = "localhost"
432
* a.port = 8888
433
* a.pathname = "/path/name"
434
* a.hash = "#hash"
435
*/
436
var a = document.createElement("a");
437
a.href = url;
438
return a;
439
};
440
441
var encode_uri_components = function (uri) {
442
/**
443
* encode just the components of a multi-segment uri,
444
* leaving '/' separators
445
*/
446
return uri.split('/').map(encodeURIComponent).join('/');
447
};
448
449
var url_join_encode = function () {
450
/**
451
* join a sequence of url components with '/',
452
* encoding each component with encodeURIComponent
453
*/
454
return encode_uri_components(url_path_join.apply(null, arguments));
455
};
456
457
458
var splitext = function (filename) {
459
/**
460
* mimic Python os.path.splitext
461
* Returns ['base', '.ext']
462
*/
463
var idx = filename.lastIndexOf('.');
464
if (idx > 0) {
465
return [filename.slice(0, idx), filename.slice(idx)];
466
} else {
467
return [filename, ''];
468
}
469
};
470
471
472
var escape_html = function (text) {
473
/**
474
* escape text to HTML
475
*/
476
return $("<div/>").text(text).html();
477
};
478
479
480
var get_body_data = function(key) {
481
/**
482
* get a url-encoded item from body.data and decode it
483
* we should never have any encoded URLs anywhere else in code
484
* until we are building an actual request
485
*/
486
var val = $('body').data(key);
487
if (!val)
488
return val;
489
return decodeURIComponent(val);
490
};
491
492
var to_absolute_cursor_pos = function (cm, cursor) {
493
/**
494
* get the absolute cursor position from CodeMirror's col, ch
495
*/
496
if (!cursor) {
497
cursor = cm.getCursor();
498
}
499
var cursor_pos = cursor.ch;
500
for (var i = 0; i < cursor.line; i++) {
501
cursor_pos += cm.getLine(i).length + 1;
502
}
503
return cursor_pos;
504
};
505
506
var from_absolute_cursor_pos = function (cm, cursor_pos) {
507
/**
508
* turn absolute cursor postion into CodeMirror col, ch cursor
509
*/
510
var i, line, next_line;
511
var offset = 0;
512
for (i = 0, next_line=cm.getLine(i); next_line !== undefined; i++, next_line=cm.getLine(i)) {
513
line = next_line;
514
if (offset + next_line.length < cursor_pos) {
515
offset += next_line.length + 1;
516
} else {
517
return {
518
line : i,
519
ch : cursor_pos - offset,
520
};
521
}
522
}
523
// reached end, return endpoint
524
return {
525
line : i - 1,
526
ch : line.length - 1,
527
};
528
};
529
530
// http://stackoverflow.com/questions/2400935/browser-detection-in-javascript
531
var browser = (function() {
532
if (typeof navigator === 'undefined') {
533
// navigator undefined in node
534
return 'None';
535
}
536
var N= navigator.appName, ua= navigator.userAgent, tem;
537
var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
538
if (M && (tem= ua.match(/version\/([\.\d]+)/i)) !== null) M[2]= tem[1];
539
M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
540
return M;
541
})();
542
543
// http://stackoverflow.com/questions/11219582/how-to-detect-my-browser-version-and-operating-system-using-javascript
544
var platform = (function () {
545
if (typeof navigator === 'undefined') {
546
// navigator undefined in node
547
return 'None';
548
}
549
var OSName="None";
550
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
551
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
552
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
553
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
554
return OSName;
555
})();
556
557
var get_url_param = function (name) {
558
// get a URL parameter. I cannot believe we actually need this.
559
// Based on http://stackoverflow.com/a/25359264/938949
560
var match = new RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
561
if (match){
562
return decodeURIComponent(match[1] || '');
563
}
564
};
565
566
var is_or_has = function (a, b) {
567
/**
568
* Is b a child of a or a itself?
569
*/
570
return a.has(b).length !==0 || a.is(b);
571
};
572
573
var is_focused = function (e) {
574
/**
575
* Is element e, or one of its children focused?
576
*/
577
e = $(e);
578
var target = $(document.activeElement);
579
if (target.length > 0) {
580
if (is_or_has(e, target)) {
581
return true;
582
} else {
583
return false;
584
}
585
} else {
586
return false;
587
}
588
};
589
590
var mergeopt = function(_class, options, overwrite){
591
options = options || {};
592
overwrite = overwrite || {};
593
return $.extend(true, {}, _class.options_default, options, overwrite);
594
};
595
596
var ajax_error_msg = function (jqXHR) {
597
/**
598
* Return a JSON error message if there is one,
599
* otherwise the basic HTTP status text.
600
*/
601
if (jqXHR.responseJSON && jqXHR.responseJSON.traceback) {
602
return jqXHR.responseJSON.traceback;
603
} else if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
604
return jqXHR.responseJSON.message;
605
} else {
606
return jqXHR.statusText;
607
}
608
};
609
var log_ajax_error = function (jqXHR, status, error) {
610
/**
611
* log ajax failures with informative messages
612
*/
613
var msg = "API request failed (" + jqXHR.status + "): ";
614
console.log(jqXHR);
615
msg += ajax_error_msg(jqXHR);
616
console.log(msg);
617
};
618
619
var requireCodeMirrorMode = function (mode, callback, errback) {
620
/**
621
* find a predefined mode or detect from CM metadata then
622
* require and callback with the resolveable mode string: mime or
623
* custom name
624
*/
625
626
var modename = (typeof mode == "string") ? mode :
627
mode.mode || mode.name;
628
629
// simplest, cheapest check by mode name: mode may also have config
630
if (CodeMirror.modes.hasOwnProperty(modename)) {
631
// return the full mode object, if it has a name
632
callback(mode.name ? mode : modename);
633
return;
634
}
635
636
// *somehow* get back a CM.modeInfo-like object that has .mode and
637
// .mime
638
var info = (mode && mode.mode && mode.mime && mode) ||
639
CodeMirror.findModeByName(modename) ||
640
CodeMirror.findModeByExtension(modename.split(".").slice(-1)) ||
641
CodeMirror.findModeByMIME(modename) ||
642
{mode: modename, mime: modename};
643
644
require([
645
// might want to use CodeMirror.modeURL here
646
['codemirror/mode', info.mode, info.mode].join('/'),
647
], function() {
648
// return the original mode, as from a kernelspec on first load
649
// or the mimetype, as for most highlighting
650
callback(mode.name ? mode : info.mime);
651
}, errback
652
);
653
};
654
655
/** Error type for wrapped XHR errors. */
656
var XHR_ERROR = 'XhrError';
657
658
/**
659
* Wraps an AJAX error as an Error object.
660
*/
661
var wrap_ajax_error = function (jqXHR, status, error) {
662
var wrapped_error = new Error(ajax_error_msg(jqXHR));
663
wrapped_error.name = XHR_ERROR;
664
// provide xhr response
665
wrapped_error.xhr = jqXHR;
666
wrapped_error.xhr_status = status;
667
wrapped_error.xhr_error = error;
668
return wrapped_error;
669
};
670
671
var promising_ajax = function(url, settings) {
672
/**
673
* Like $.ajax, but returning an ES6 promise. success and error settings
674
* will be ignored.
675
*/
676
settings = settings || {};
677
return new Promise(function(resolve, reject) {
678
settings.success = function(data, status, jqXHR) {
679
resolve(data);
680
};
681
settings.error = function(jqXHR, status, error) {
682
log_ajax_error(jqXHR, status, error);
683
reject(wrap_ajax_error(jqXHR, status, error));
684
};
685
$.ajax(url, settings);
686
});
687
};
688
689
var WrappedError = function(message, error){
690
/**
691
* Wrappable Error class
692
*
693
* The Error class doesn't actually act on `this`. Instead it always
694
* returns a new instance of Error. Here we capture that instance so we
695
* can apply it's properties to `this`.
696
*/
697
var tmp = Error.apply(this, [message]);
698
699
// Copy the properties of the error over to this.
700
var properties = Object.getOwnPropertyNames(tmp);
701
for (var i = 0; i < properties.length; i++) {
702
this[properties[i]] = tmp[properties[i]];
703
}
704
705
// Keep a stack of the original error messages.
706
if (error instanceof WrappedError) {
707
this.error_stack = error.error_stack;
708
} else {
709
this.error_stack = [error];
710
}
711
this.error_stack.push(tmp);
712
713
return this;
714
};
715
716
WrappedError.prototype = Object.create(Error.prototype, {});
717
718
719
var load_class = function(class_name, module_name, registry) {
720
/**
721
* Tries to load a class
722
*
723
* Tries to load a class from a module using require.js, if a module
724
* is specified, otherwise tries to load a class from the global
725
* registry, if the global registry is provided.
726
*/
727
return new Promise(function(resolve, reject) {
728
729
// Try loading the view module using require.js
730
if (module_name) {
731
require([module_name], function(module) {
732
if (module[class_name] === undefined) {
733
reject(new Error('Class '+class_name+' not found in module '+module_name));
734
} else {
735
resolve(module[class_name]);
736
}
737
}, reject);
738
} else {
739
if (registry && registry[class_name]) {
740
resolve(registry[class_name]);
741
} else {
742
reject(new Error('Class '+class_name+' not found in registry '));
743
}
744
}
745
});
746
};
747
748
var resolve_promises_dict = function(d) {
749
/**
750
* Resolve a promiseful dictionary.
751
* Returns a single Promise.
752
*/
753
var keys = Object.keys(d);
754
var values = [];
755
keys.forEach(function(key) {
756
values.push(d[key]);
757
});
758
return Promise.all(values).then(function(v) {
759
d = {};
760
for(var i=0; i<keys.length; i++) {
761
d[keys[i]] = v[i];
762
}
763
return d;
764
});
765
};
766
767
var reject = function(message, log) {
768
/**
769
* Creates a wrappable Promise rejection function.
770
*
771
* Creates a function that returns a Promise.reject with a new WrappedError
772
* that has the provided message and wraps the original error that
773
* caused the promise to reject.
774
*/
775
return function(error) {
776
var wrapped_error = new WrappedError(message, error);
777
if (log) console.error(wrapped_error);
778
return Promise.reject(wrapped_error);
779
};
780
};
781
782
var typeset = function(element, text) {
783
/**
784
* Apply MathJax rendering to an element, and optionally set its text
785
*
786
* If MathJax is not available, make no changes.
787
*
788
* Returns the output any number of typeset elements, or undefined if
789
* MathJax was not available.
790
*
791
* Parameters
792
* ----------
793
* element: Node, NodeList, or jQuery selection
794
* text: option string
795
*/
796
var $el = element.jquery ? element : $(element);
797
if(arguments.length > 1){
798
$el.text(text);
799
}
800
if(!window.MathJax){
801
return;
802
}
803
return $el.map(function(){
804
// MathJax takes a DOM node: $.map makes `this` the context
805
return MathJax.Hub.Queue(["Typeset", MathJax.Hub, this]);
806
});
807
};
808
809
var time = {};
810
time.milliseconds = {};
811
time.milliseconds.s = 1000;
812
time.milliseconds.m = 60 * time.milliseconds.s;
813
time.milliseconds.h = 60 * time.milliseconds.m;
814
time.milliseconds.d = 24 * time.milliseconds.h;
815
816
time.thresholds = {
817
// moment.js thresholds in milliseconds
818
s: moment.relativeTimeThreshold('s') * time.milliseconds.s,
819
m: moment.relativeTimeThreshold('m') * time.milliseconds.m,
820
h: moment.relativeTimeThreshold('h') * time.milliseconds.h,
821
d: moment.relativeTimeThreshold('d') * time.milliseconds.d,
822
};
823
824
time.timeout_from_dt = function (dt) {
825
/** compute a timeout based on dt
826
827
input and output both in milliseconds
828
829
use moment's relative time thresholds:
830
831
- 10 seconds if in 'seconds ago' territory
832
- 1 minute if in 'minutes ago'
833
- 1 hour otherwise
834
*/
835
if (dt < time.thresholds.s) {
836
return 10 * time.milliseconds.s;
837
} else if (dt < time.thresholds.m) {
838
return time.milliseconds.m;
839
} else {
840
return time.milliseconds.h;
841
}
842
};
843
844
var utils = {
845
load_extensions: load_extensions,
846
load_extensions_from_config: load_extensions_from_config,
847
regex_split : regex_split,
848
uuid : uuid,
849
fixConsole : fixConsole,
850
fixCarriageReturn : fixCarriageReturn,
851
autoLinkUrls : autoLinkUrls,
852
points_to_pixels : points_to_pixels,
853
get_body_data : get_body_data,
854
parse_url : parse_url,
855
url_path_split : url_path_split,
856
url_path_join : url_path_join,
857
url_join_encode : url_join_encode,
858
encode_uri_components : encode_uri_components,
859
splitext : splitext,
860
escape_html : escape_html,
861
always_new : always_new,
862
to_absolute_cursor_pos : to_absolute_cursor_pos,
863
from_absolute_cursor_pos : from_absolute_cursor_pos,
864
browser : browser,
865
platform: platform,
866
get_url_param: get_url_param,
867
is_or_has : is_or_has,
868
is_focused : is_focused,
869
mergeopt: mergeopt,
870
ajax_error_msg : ajax_error_msg,
871
log_ajax_error : log_ajax_error,
872
requireCodeMirrorMode : requireCodeMirrorMode,
873
XHR_ERROR : XHR_ERROR,
874
wrap_ajax_error : wrap_ajax_error,
875
promising_ajax : promising_ajax,
876
WrappedError: WrappedError,
877
load_class: load_class,
878
resolve_promises_dict: resolve_promises_dict,
879
reject: reject,
880
typeset: typeset,
881
time: time,
882
};
883
884
// Backwards compatability.
885
IPython.utils = utils;
886
887
return utils;
888
});
889
890