_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q56100
|
ErrorDisplay
|
train
|
function ErrorDisplay(player, options) {
_classCallCheck(this, ErrorDisplay);
var _this = _possibleConstructorReturn(this, _ModalDialog.call(this, player, options));
_this.on(player, 'error', _this.open);
return _this;
}
|
javascript
|
{
"resource": ""
}
|
q56101
|
ModalDialog
|
train
|
function ModalDialog(player, options) {
_classCallCheck(this, ModalDialog);
var _this = _possibleConstructorReturn(this, _Component.call(this, player, options));
_this.opened_ = _this.hasBeenOpened_ = _this.hasBeenFilled_ = false;
_this.closeable(!_this.options_.uncloseable);
_this.content(_this.options_.content);
// Make sure the contentEl is defined AFTER any children are initialized
// because we only want the contents of the modal in the contentEl
// (not the UI elements like the close button).
_this.contentEl_ = Dom.createEl('div', {
className: MODAL_CLASS_NAME + '-content'
}, {
role: 'document'
});
_this.descEl_ = Dom.createEl('p', {
className: MODAL_CLASS_NAME + '-description vjs-offscreen',
id: _this.el().getAttribute('aria-describedby')
});
Dom.textContent(_this.descEl_, _this.description());
_this.el_.appendChild(_this.descEl_);
_this.el_.appendChild(_this.contentEl_);
return _this;
}
|
javascript
|
{
"resource": ""
}
|
q56102
|
loadTrack
|
train
|
function loadTrack(src, track) {
var opts = {
uri: src
};
var crossOrigin = (0, _url.isCrossOrigin)(src);
if (crossOrigin) {
opts.cors = crossOrigin;
}
(0, _xhr2['default'])(opts, Fn.bind(this, function (err, response, responseBody) {
if (err) {
return _log2['default'].error(err, response);
}
track.loaded_ = true;
// Make sure that vttjs has loaded, otherwise, wait till it finished loading
// NOTE: this is only used for the alt/video.novtt.js build
if (typeof _window2['default'].WebVTT !== 'function') {
if (track.tech_) {
(function () {
var loadHandler = function loadHandler() {
return parseCues(responseBody, track);
};
track.tech_.on('vttjsloaded', loadHandler);
track.tech_.on('vttjserror', function () {
_log2['default'].error('vttjs failed to load, stopping trying to process ' + track.src);
track.tech_.off('vttjsloaded', loadHandler);
});
})();
}
} else {
parseCues(responseBody, track);
}
}));
}
|
javascript
|
{
"resource": ""
}
|
q56103
|
bufferedPercent
|
train
|
function bufferedPercent(buffered, duration) {
var bufferedDuration = 0;
var start = void 0;
var end = void 0;
if (!duration) {
return 0;
}
if (!buffered || !buffered.length) {
buffered = (0, _timeRanges.createTimeRange)(0, 0);
}
for (var i = 0; i < buffered.length; i++) {
start = buffered.start(i);
end = buffered.end(i);
// buffered end can be bigger than duration by a very small fraction
if (end > duration) {
end = duration;
}
bufferedDuration += end - start;
}
return bufferedDuration / duration;
}
|
javascript
|
{
"resource": ""
}
|
q56104
|
createEl
|
train
|
function createEl() {
var tagName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'div';
var properties = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var el = _document2['default'].createElement(tagName);
Object.getOwnPropertyNames(properties).forEach(function (propName) {
var val = properties[propName];
// See #2176
// We originally were accepting both properties and attributes in the
// same object, but that doesn't work so well.
if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') {
_log2['default'].warn((0, _tsml2['default'])(_templateObject, propName, val));
el.setAttribute(propName, val);
} else {
el[propName] = val;
}
});
Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
el.setAttribute(attrName, attributes[attrName]);
});
return el;
}
|
javascript
|
{
"resource": ""
}
|
q56105
|
textContent
|
train
|
function textContent(el, text) {
if (typeof el.textContent === 'undefined') {
el.innerText = text;
} else {
el.textContent = text;
}
}
|
javascript
|
{
"resource": ""
}
|
q56106
|
insertElFirst
|
train
|
function insertElFirst(child, parent) {
if (parent.firstChild) {
parent.insertBefore(child, parent.firstChild);
} else {
parent.appendChild(child);
}
}
|
javascript
|
{
"resource": ""
}
|
q56107
|
getElData
|
train
|
function getElData(el) {
var id = el[elIdAttr];
if (!id) {
id = el[elIdAttr] = Guid.newGUID();
}
if (!elData[id]) {
elData[id] = {};
}
return elData[id];
}
|
javascript
|
{
"resource": ""
}
|
q56108
|
removeElData
|
train
|
function removeElData(el) {
var id = el[elIdAttr];
if (!id) {
return;
}
// Remove all stored data
delete elData[id];
// Remove the elIdAttr property from the DOM node
try {
delete el[elIdAttr];
} catch (e) {
if (el.removeAttribute) {
el.removeAttribute(elIdAttr);
} else {
// IE doesn't appear to support removeAttribute on the document element
el[elIdAttr] = null;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q56109
|
hasElClass
|
train
|
function hasElClass(element, classToCheck) {
throwIfWhitespace(classToCheck);
if (element.classList) {
return element.classList.contains(classToCheck);
}
return classRegExp(classToCheck).test(element.className);
}
|
javascript
|
{
"resource": ""
}
|
q56110
|
addElClass
|
train
|
function addElClass(element, classToAdd) {
if (element.classList) {
element.classList.add(classToAdd);
// Don't need to `throwIfWhitespace` here because `hasElClass` will do it
// in the case of classList not being supported.
} else if (!hasElClass(element, classToAdd)) {
element.className = (element.className + ' ' + classToAdd).trim();
}
return element;
}
|
javascript
|
{
"resource": ""
}
|
q56111
|
removeElClass
|
train
|
function removeElClass(element, classToRemove) {
if (element.classList) {
element.classList.remove(classToRemove);
} else {
throwIfWhitespace(classToRemove);
element.className = element.className.split(/\s+/).filter(function (c) {
return c !== classToRemove;
}).join(' ');
}
return element;
}
|
javascript
|
{
"resource": ""
}
|
q56112
|
setElAttributes
|
train
|
function setElAttributes(el, attributes) {
Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
var attrValue = attributes[attrName];
if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
el.removeAttribute(attrName);
} else {
el.setAttribute(attrName, attrValue === true ? '' : attrValue);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q56113
|
normalizeContent
|
train
|
function normalizeContent(content) {
// First, invoke content if it is a function. If it produces an array,
// that needs to happen before normalization.
if (typeof content === 'function') {
content = content();
}
// Next up, normalize to an array, so one or many items can be normalized,
// filtered, and returned.
return (Array.isArray(content) ? content : [content]).map(function (value) {
// First, invoke value if it is a function to produce a new value,
// which will be subsequently normalized to a Node of some kind.
if (typeof value === 'function') {
value = value();
}
if (isEl(value) || isTextNode(value)) {
return value;
}
if (typeof value === 'string' && /\S/.test(value)) {
return _document2['default'].createTextNode(value);
}
}).filter(function (value) {
return value;
});
}
|
javascript
|
{
"resource": ""
}
|
q56114
|
_cleanUpEvents
|
train
|
function _cleanUpEvents(elem, type) {
var data = Dom.getElData(elem);
// Remove the events of a particular type if there are none left
if (data.handlers[type].length === 0) {
delete data.handlers[type];
// data.handlers[type] = null;
// Setting to null was causing an error with data.handlers
// Remove the meta-handler from the element
if (elem.removeEventListener) {
elem.removeEventListener(type, data.dispatcher, false);
} else if (elem.detachEvent) {
elem.detachEvent('on' + type, data.dispatcher);
}
}
// Remove the events object if there are no types left
if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
delete data.handlers;
delete data.dispatcher;
delete data.disabled;
}
// Finally remove the element data if there is no data left
if (Object.getOwnPropertyNames(data).length === 0) {
Dom.removeElData(elem);
}
}
|
javascript
|
{
"resource": ""
}
|
q56115
|
off
|
train
|
function off(elem, type, fn) {
// Don't want to add a cache object through getElData if not needed
if (!Dom.hasElData(elem)) {
return;
}
var data = Dom.getElData(elem);
// If no events exist, nothing to unbind
if (!data.handlers) {
return;
}
if (Array.isArray(type)) {
return _handleMultipleEvents(off, elem, type, fn);
}
// Utility function
var removeType = function removeType(t) {
data.handlers[t] = [];
_cleanUpEvents(elem, t);
};
// Are we removing all bound events?
if (!type) {
for (var t in data.handlers) {
removeType(t);
}
return;
}
var handlers = data.handlers[type];
// If no handlers exist, nothing to unbind
if (!handlers) {
return;
}
// If no listener was provided, remove all listeners for type
if (!fn) {
removeType(type);
return;
}
// We're only removing a single handler
if (fn.guid) {
for (var n = 0; n < handlers.length; n++) {
if (handlers[n].guid === fn.guid) {
handlers.splice(n--, 1);
}
}
}
_cleanUpEvents(elem, type);
}
|
javascript
|
{
"resource": ""
}
|
q56116
|
trigger
|
train
|
function trigger(elem, event, hash) {
// Fetches element data and a reference to the parent (for bubbling).
// Don't want to add a data object to cache for every parent,
// so checking hasElData first.
var elemData = Dom.hasElData(elem) ? Dom.getElData(elem) : {};
var parent = elem.parentNode || elem.ownerDocument;
// type = event.type || event,
// handler;
// If an event name was passed as a string, creates an event out of it
if (typeof event === 'string') {
event = { type: event, target: elem };
}
// Normalizes the event properties.
event = fixEvent(event);
// If the passed element has a dispatcher, executes the established handlers.
if (elemData.dispatcher) {
elemData.dispatcher.call(elem, event, hash);
}
// Unless explicitly stopped or the event does not bubble (e.g. media events)
// recursively calls this function to bubble the event up the DOM.
if (parent && !event.isPropagationStopped() && event.bubbles === true) {
trigger.call(null, parent, event, hash);
// If at the top of the DOM, triggers the default action unless disabled.
} else if (!parent && !event.defaultPrevented) {
var targetData = Dom.getElData(event.target);
// Checks if the target has a default action for this event.
if (event.target[event.type]) {
// Temporarily disables event dispatching on the target as we have already executed the handler.
targetData.disabled = true;
// Executes the default action.
if (typeof event.target[event.type] === 'function') {
event.target[event.type]();
}
// Re-enables event dispatching.
targetData.disabled = false;
}
}
// Inform the triggerer if the default was prevented by returning false
return !event.defaultPrevented;
}
|
javascript
|
{
"resource": ""
}
|
q56117
|
ParsingError
|
train
|
function ParsingError(errorData, message) {
this.name = "ParsingError";
this.code = errorData.code;
this.message = message || errorData.message;
}
|
javascript
|
{
"resource": ""
}
|
q56118
|
parseTimeStamp
|
train
|
function parseTimeStamp(input) {
function computeSeconds(h, m, s, f) {
return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
}
var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
if (!m) {
return null;
}
if (m[3]) {
// Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
} else if (m[1] > 59) {
// Timestamp takes the form of [hours]:[minutes].[milliseconds]
// First position is hours as it's over 59.
return computeSeconds(m[1], m[2], 0, m[4]);
} else {
// Timestamp takes the form of [minutes]:[seconds].[milliseconds]
return computeSeconds(0, m[1], m[2], m[4]);
}
}
|
javascript
|
{
"resource": ""
}
|
q56119
|
train
|
function(k, dflt, defaultKey) {
if (defaultKey) {
return this.has(k) ? this.values[k] : dflt[defaultKey];
}
return this.has(k) ? this.values[k] : dflt;
}
|
javascript
|
{
"resource": ""
}
|
|
q56120
|
train
|
function(k, v, a) {
for (var n = 0; n < a.length; ++n) {
if (v === a[n]) {
this.set(k, v);
break;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56121
|
train
|
function(k, v) {
var m;
if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) {
v = parseFloat(v);
if (v >= 0 && v <= 100) {
this.set(k, v);
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q56122
|
consumeTimeStamp
|
train
|
function consumeTimeStamp() {
var ts = parseTimeStamp(input);
if (ts === null) {
throw new ParsingError(ParsingError.Errors.BadTimeStamp,
"Malformed timestamp: " + oInput);
}
// Remove time stamp from input.
input = input.replace(/^[^\sa-zA-Z-]+/, "");
return ts;
}
|
javascript
|
{
"resource": ""
}
|
q56123
|
consumeCueSettings
|
train
|
function consumeCueSettings(input, cue) {
var settings = new Settings();
parseOptions(input, function (k, v) {
switch (k) {
case "region":
// Find the last region we parsed with the same region id.
for (var i = regionList.length - 1; i >= 0; i--) {
if (regionList[i].id === v) {
settings.set(k, regionList[i].region);
break;
}
}
break;
case "vertical":
settings.alt(k, v, ["rl", "lr"]);
break;
case "line":
var vals = v.split(","),
vals0 = vals[0];
settings.integer(k, vals0);
settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
settings.alt(k, vals0, ["auto"]);
if (vals.length === 2) {
settings.alt("lineAlign", vals[1], ["start", "middle", "end"]);
}
break;
case "position":
vals = v.split(",");
settings.percent(k, vals[0]);
if (vals.length === 2) {
settings.alt("positionAlign", vals[1], ["start", "middle", "end"]);
}
break;
case "size":
settings.percent(k, v);
break;
case "align":
settings.alt(k, v, ["start", "middle", "end", "left", "right"]);
break;
}
}, /:/, /\s/);
// Apply default values for any missing fields.
cue.region = settings.get("region", null);
cue.vertical = settings.get("vertical", "");
cue.line = settings.get("line", "auto");
cue.lineAlign = settings.get("lineAlign", "start");
cue.snapToLines = settings.get("snapToLines", true);
cue.size = settings.get("size", 100);
cue.align = settings.get("align", "middle");
cue.position = settings.get("position", {
start: 0,
left: 0,
middle: 50,
end: 100,
right: 100
}, cue.align);
cue.positionAlign = settings.get("positionAlign", {
start: "start",
left: "start",
middle: "middle",
end: "end",
right: "end"
}, cue.align);
}
|
javascript
|
{
"resource": ""
}
|
q56124
|
createElement
|
train
|
function createElement(type, annotation) {
var tagName = TAG_NAME[type];
if (!tagName) {
return null;
}
var element = window.document.createElement(tagName);
element.localName = tagName;
var name = TAG_ANNOTATION[type];
if (name && annotation) {
element[name] = annotation.trim();
}
return element;
}
|
javascript
|
{
"resource": ""
}
|
q56125
|
BoxPosition
|
train
|
function BoxPosition(obj) {
var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent);
// Either a BoxPosition was passed in and we need to copy it, or a StyleBox
// was passed in and we need to copy the results of 'getBoundingClientRect'
// as the object returned is readonly. All co-ordinate values are in reference
// to the viewport origin (top left).
var lh, height, width, top;
if (obj.div) {
height = obj.div.offsetHeight;
width = obj.div.offsetWidth;
top = obj.div.offsetTop;
var rects = (rects = obj.div.childNodes) && (rects = rects[0]) &&
rects.getClientRects && rects.getClientRects();
obj = obj.div.getBoundingClientRect();
// In certain cases the outter div will be slightly larger then the sum of
// the inner div's lines. This could be due to bold text, etc, on some platforms.
// In this case we should get the average line height and use that. This will
// result in the desired behaviour.
lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length)
: 0;
}
this.left = obj.left;
this.right = obj.right;
this.top = obj.top || top;
this.height = obj.height || height;
this.bottom = obj.bottom || (top + (obj.height || height));
this.width = obj.width || width;
this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
if (isIE8 && !this.lineHeight) {
this.lineHeight = 13;
}
}
|
javascript
|
{
"resource": ""
}
|
q56126
|
shouldCompute
|
train
|
function shouldCompute(cues) {
for (var i = 0; i < cues.length; i++) {
if (cues[i].hasBeenReset || !cues[i].displayState) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q56127
|
parseRegion
|
train
|
function parseRegion(input) {
var settings = new Settings();
parseOptions(input, function (k, v) {
switch (k) {
case "id":
settings.set(k, v);
break;
case "width":
settings.percent(k, v);
break;
case "lines":
settings.integer(k, v);
break;
case "regionanchor":
case "viewportanchor":
var xy = v.split(',');
if (xy.length !== 2) {
break;
}
// We have to make sure both x and y parse, so use a temporary
// settings object here.
var anchor = new Settings();
anchor.percent("x", xy[0]);
anchor.percent("y", xy[1]);
if (!anchor.has("x") || !anchor.has("y")) {
break;
}
settings.set(k + "X", anchor.get("x"));
settings.set(k + "Y", anchor.get("y"));
break;
case "scroll":
settings.alt(k, v, ["up"]);
break;
}
}, /=/, /\s/);
// Create the region, using default values for any values that were not
// specified.
if (settings.has("id")) {
var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();
region.width = settings.get("width", 100);
region.lines = settings.get("lines", 3);
region.regionAnchorX = settings.get("regionanchorX", 0);
region.regionAnchorY = settings.get("regionanchorY", 100);
region.viewportAnchorX = settings.get("viewportanchorX", 0);
region.viewportAnchorY = settings.get("viewportanchorY", 100);
region.scroll = settings.get("scroll", "");
// Register the region.
self.onregion && self.onregion(region);
// Remember the VTTRegion for later in case we parse any VTTCues that
// reference it.
self.regionList.push({
id: settings.get("id"),
region: region
});
}
}
|
javascript
|
{
"resource": ""
}
|
q56128
|
prettifyJson
|
train
|
function prettifyJson(str) {
var json = JSON.parse(str);
return JSON.stringify(json, null, 2);
}
|
javascript
|
{
"resource": ""
}
|
q56129
|
unwrapItems
|
train
|
function unwrapItems(schema) {
if (_.isEmpty(schema.items))
schema.items = {};
else {
assert(_.isPlainObject(schema.items[0]));
schema.items = schema.items[0];
}
return schema;
}
|
javascript
|
{
"resource": ""
}
|
q56130
|
init
|
train
|
function init(settings) {
var opts = settings || {},
i;
if (opts.onError !== false) {
Canadarm.setUpOnErrorHandler();
}
if (opts.wrapEvents !== false) {
Canadarm.setUpEventListening();
}
if (opts.appenders) {
for (i = 0; i < opts.appenders.length; i++) {
Canadarm.addAppender(opts.appenders[i]);
}
}
if (opts.handlers) {
for (i = 0; i < opts.handlers.length; i++) {
Canadarm.addHandler(opts.handlers[i]);
}
}
if (opts.logLevel) {
Canadarm.loggingLevel = opts.logLevel;
}
}
|
javascript
|
{
"resource": ""
}
|
q56131
|
gatherErrors
|
train
|
function gatherErrors(level, exception, message, data, appenders) {
var logAttributes = {},
localAppenders = appenders || errorAppenders,
errorAppender, attributeName, attributes, i, key;
// Go over every log appender and add it's attributes so we can log them.
for (i = 0; i < localAppenders.length; i++) {
errorAppender = localAppenders[i];
attributes = errorAppender(level, exception, message, data);
for (key in attributes) {
if (!attributes.hasOwnProperty(key)) {
continue;
}
logAttributes[key] = attributes[key];
}
}
return logAttributes;
}
|
javascript
|
{
"resource": ""
}
|
q56132
|
pushErrors
|
train
|
function pushErrors(logAttributes, handlers) {
var localHandlers = handlers || errorHandlers,
errorHandler, i;
// Go over every log handler so we can actually create logs.
for (i = 0; i < localHandlers.length; i++) {
errorHandler = localHandlers[i];
errorHandler(logAttributes);
}
}
|
javascript
|
{
"resource": ""
}
|
q56133
|
customLogEvent
|
train
|
function customLogEvent(level) {
// options should contain the appenders and handlers to override the
// global ones defined in errorAppenders, and errorHandlers.
// Used by Canadarm.localWatch to wrap local appender calls.
return function (message, exception, data, settings) {
// If we are are below the current Canadarm.loggingLevel we
// should not do anything with the passed information. Return
// as if nothing happened.
if (Canadarm.levelOrder.indexOf(level) < Canadarm.levelOrder.indexOf(Canadarm.loggingLevel)) {
return;
}
var options = settings || {},
attrs = gatherErrors(level, exception, message, data, options.appenders);
pushErrors(attrs, options.handlers);
};
}
|
javascript
|
{
"resource": ""
}
|
q56134
|
consoleLogHandler
|
train
|
function consoleLogHandler(logAttributes) {
var logValues = '', key;
if (console) {
// detect IE
if (window.attachEvent) {
// Put attributes into a format that are easy for IE 8 to read.
for (key in logAttributes) {
if (!logAttributes.hasOwnProperty(key)) {
continue;
}
logValues += key + '=' + logAttributes[key] + '\n';
}
console.error(logValues);
} else if (typeof logAttributes.msg !== 'undefined') {
console.error(logAttributes.msg, logAttributes);
} else {
console.error(logAttributes);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q56135
|
_onError
|
train
|
function _onError(errorMessage, url, lineNumber, columnNumber, exception) {
var onErrorReturn;
// Execute the original window.onerror handler, if any
if (_oldOnError && typeof _oldOnError === 'function') {
onErrorReturn = _oldOnError.apply(this, arguments);
}
Canadarm.fatal(errorMessage, exception, {
url: url,
lineNumber: lineNumber,
columnNumber: columnNumber
});
return onErrorReturn;
}
|
javascript
|
{
"resource": ""
}
|
q56136
|
findStackData
|
train
|
function findStackData(stack) {
// If the stack is not in the error we cannot get any information and
// should return immediately.
if (stack === undefined || stack === null) {
return {
'url': Canadarm.constant.UNKNOWN_LOG,
'lineNumber': Canadarm.constant.UNKNOWN_LOG,
'columnNumber': Canadarm.constant.UNKNOWN_LOG
};
}
// Remove the newlines from all browsers so we can regex this easier
var stackBits = stack.replace(/(\r\n|\n|\r)/gm,'').match(STACK_SCRIPT_COLUMN_LINE_FINDER),
newStack, stackData = [],
stackHasBits = (stackBits !== null && stackBits !== undefined);
while (stackHasBits) {
stackBits = stackBits[1].match(STACK_SCRIPT_COLUMN_LINE_FINDER);
newStack = stackBits !== null ? stackBits[1] : null;
stackData = stackBits !== null ? stackBits : stackData;
stackHasBits = (stackBits !== null && stackBits !== undefined);
}
return {
'url': stackData.length >= 1 ? stackData[1] : Canadarm.constant.UNKNOWN_LOG,
'lineNumber': stackData.length >= 1 ? stackData[2] : Canadarm.constant.UNKNOWN_LOG,
'columnNumber': stackData.length >= 1 ? stackData[3] : Canadarm.constant.UNKNOWN_LOG
};
}
|
javascript
|
{
"resource": ""
}
|
q56137
|
train
|
function() {
// NOTE: This fixed issue #7
// https://github.com/vowstar/gitbook-plugin-uml/issues/7
// HTML will load after this operation
// Copy images to output folder every time
var book = this;
var output = book.output;
var rootPath = output.root();
if (fs.existsSync(ASSET_PATH)) {
fs.mkdirs(path.join(rootPath, ASSET_PATH));
fs.copySync(ASSET_PATH, path.join(rootPath, ASSET_PATH));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56138
|
processFileByModifiedTime
|
train
|
function processFileByModifiedTime(stream, firstPass, basePath, file, cache) {
var newTime = file.stat && file.stat.mtime;
var filePath = basePath ? path.relative(basePath, file.path) : file.path;
var oldTime = cache[filePath];
cache[filePath] = newTime.getTime();
if ((!oldTime && firstPass) || (oldTime && oldTime !== newTime.getTime())) {
stream.push(file);
}
}
|
javascript
|
{
"resource": ""
}
|
q56139
|
processFileBySha1Hash
|
train
|
function processFileBySha1Hash(stream, firstPass, basePath, file, cache) {
// null cannot be hashed
if (file.contents === null) {
// if element is really a file, something weird happened, but it's safer
// to assume it was changed (because we cannot said that it wasn't)
// if it's not a file, we don't care, do we? does anybody transform directories?
if (file.stat.isFile()) {
stream.push(file);
}
} else {
var newHash = crypto.createHash('sha1').update(file.contents).digest('hex');
var filePath = basePath ? path.relative(basePath, file.path) : file.path;
var currentHash = cache[filePath];
cache[filePath] = newHash;
if ((!currentHash && firstPass) || (currentHash && currentHash !== newHash)) {
stream.push(file);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q56140
|
build
|
train
|
async function build( previousFileSizes ) {
console.log( 'Creating an optimized production build...' );
const filenames = await getFilenames( FILENAMES );
const webpackConfig = await createWebpackConfig( config( filenames ) );
const compiler = webpack( webpackConfig );
return new Promise( ( resolve, reject ) => {
compiler.run( ( err, stats ) => {
if ( err ) {
return reject( err );
}
const messages = formatWebpackMessages(
stats.toJson( { all: false, warnings: true, errors: true } )
);
if ( messages.errors.length ) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if ( messages.errors.length > 1 ) {
messages.errors.length = 1;
}
return reject( new Error( messages.errors.join( '\n\n' ) ) );
}
if ( process.env.CI && ( typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') && messages.warnings.length ) {
console.log(
chalk.yellow( '\nTreating warnings as errors because process.env.CI = true.\nMost CI servers set it automatically.\n' )
);
return reject( new Error( messages.warnings.join( '\n\n' ) ) );
}
resolve( {
previousFileSizes,
stats,
warnings: messages.warnings,
} );
} );
} );
}
|
javascript
|
{
"resource": ""
}
|
q56141
|
constructCode
|
train
|
function constructCode(code, system, display) {
const codeObj = new models.Concept(system, code, display);
return codeObj;
}
|
javascript
|
{
"resource": ""
}
|
q56142
|
shorthandFromCodesystem
|
train
|
function shorthandFromCodesystem(cs) {
if (!cs) {
return '';
}
if (shorthands[cs]) {
return shorthands[cs];
} else if (cs.match(/http:\/\/standardhealthrecord.org\/shr\/[A-Za-z]*\/cs\/(#[A-Za-z]*CS)/)) {
return '';
} else {
return cs;
}
}
|
javascript
|
{
"resource": ""
}
|
q56143
|
formattedCodeFromConcept
|
train
|
function formattedCodeFromConcept(concept) {
var formattedConceptCode = `${shorthandFromCodesystem(concept.system)}#${concept.code}`;
if (concept.display) {
formattedConceptCode = `${formattedConceptCode} "${concept.display}"`;
} else if (concept.description) {
formattedConceptCode = `${formattedConceptCode} "${concept.description}"`;
}
return formattedConceptCode;
}
|
javascript
|
{
"resource": ""
}
|
q56144
|
train
|
function( elem, name, isXML ) {
var ret;
return isXML ?
undefined :
(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
}
|
javascript
|
{
"resource": ""
}
|
|
q56145
|
train
|
function( flag, needsFlag ) {
// optIn defaults implicit behavior to weak exclusion
if ( optIn && !modules[ flag ] && !modules[ "+" + flag ] ) {
excluded[ flag ] = false;
}
// explicit or inherited strong exclusion
if ( excluded[ needsFlag ] || modules[ "-" + flag ] ) {
excluded[ flag ] = true;
// explicit inclusion overrides weak exclusion
} else if ( excluded[ needsFlag ] === false &&
( modules[ flag ] || modules[ "+" + flag ] ) ) {
delete excluded[ needsFlag ];
// ...all the way down
if ( deps[ needsFlag ] ) {
deps[ needsFlag ].forEach(function( subDep ) {
modules[ needsFlag ] = true;
excluder( needsFlag, subDep );
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56146
|
getEachForSource
|
train
|
function getEachForSource(source) {
if (source.length < 40) {
return UniqueArrayWrapper.prototype.eachNoCache;
} else if (source.length < 100) {
return UniqueArrayWrapper.prototype.eachArrayCache;
} else {
return UniqueArrayWrapper.prototype.eachSetCache;
}
}
|
javascript
|
{
"resource": ""
}
|
q56147
|
createCallback
|
train
|
function createCallback(callback, defaultValue) {
switch (typeof callback) {
case "function":
return callback;
case "string":
return function(e) {
return e[callback];
};
case "object":
return function(e) {
return Lazy(callback).all(function(value, key) {
return e[key] === value;
});
};
case "undefined":
return defaultValue ?
function() { return defaultValue; } :
Lazy.identity;
default:
throw "Don't know how to make a callback from a " + typeof callback + "!";
}
}
|
javascript
|
{
"resource": ""
}
|
q56148
|
createSet
|
train
|
function createSet(values) {
var set = new Set();
Lazy(values || []).flatten().each(function(e) {
set.add(e);
});
return set;
}
|
javascript
|
{
"resource": ""
}
|
q56149
|
compare
|
train
|
function compare(x, y, fn) {
if (typeof fn === "function") {
return compare(fn(x), fn(y));
}
if (x === y) {
return 0;
}
return x > y ? 1 : -1;
}
|
javascript
|
{
"resource": ""
}
|
q56150
|
forEach
|
train
|
function forEach(array, fn) {
var i = -1,
len = array.length;
while (++i < len) {
if (fn(array[i], i) === false) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q56151
|
arrayContains
|
train
|
function arrayContains(array, element) {
var i = -1,
length = array.length;
// Special handling for NaN
if (element !== element) {
while (++i < length) {
if (array[i] !== array[i]) {
return true;
}
}
return false;
}
while (++i < length) {
if (array[i] === element) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q56152
|
arrayContainsBefore
|
train
|
function arrayContainsBefore(array, element, index, keyFn) {
var i = -1;
if (keyFn) {
keyFn = createCallback(keyFn);
while (++i < index) {
if (keyFn(array[i]) === keyFn(element)) {
return true;
}
}
} else {
while (++i < index) {
if (array[i] === element) {
return true;
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q56153
|
swap
|
train
|
function swap(array, i, j) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
|
javascript
|
{
"resource": ""
}
|
q56154
|
defineSequenceType
|
train
|
function defineSequenceType(base, name, overrides) {
/** @constructor */
var ctor = function ctor() {};
// Make this type inherit from the specified base.
ctor.prototype = new base();
// Attach overrides to the new sequence type's prototype.
for (var override in overrides) {
ctor.prototype[override] = overrides[override];
}
// Define a factory method that sets the new sequence's parent to the caller
// and (optionally) applies any additional initialization logic.
// Expose this as a chainable method so that we can do:
// Lazy(...).map(...).filter(...).blah(...);
var factory = function factory() {
var sequence = new ctor();
// Every sequence needs a reference to its parent in order to work.
sequence.parent = this;
// If a custom init function was supplied, call it now.
if (sequence.init) {
sequence.init.apply(sequence, arguments);
}
return sequence;
};
var methodNames = typeof name === 'string' ? [name] : name;
for (var i = 0; i < methodNames.length; ++i) {
base.prototype[methodNames[i]] = factory;
}
return ctor;
}
|
javascript
|
{
"resource": ""
}
|
q56155
|
getDirectoriesInURL
|
train
|
function getDirectoriesInURL()
{
var trail = document.location.pathname.split( PATH_SEPARATOR );
// check whether last section is a file or a directory
var lastcrumb = trail[trail.length-1];
for( var i = 0; i < FILE_EXTENSIONS.length; i++ )
{
if( lastcrumb.indexOf( FILE_EXTENSIONS[i] ) )
{
// it is, remove it and send results
return trail.slice( 1, trail.length-1 );
}
}
// it's not; send the trail unmodified
return trail.slice( 1, trail.length );
}
|
javascript
|
{
"resource": ""
}
|
q56156
|
getCrumbTrail
|
train
|
function getCrumbTrail( crumbs )
{
var xhtml = DISPLAY_PREPREND;
for( var i = 0; i < crumbs.length; i++ )
{
xhtml += '<a href="' + crumbs[i][1] + '" >';
xhtml += unescape( crumbs[i][0] ) + '</a>';
if( i != (crumbs.length-1) )
{
xhtml += DISPLAY_SEPARATOR;
}
}
xhtml += DISPLAY_POSTPREND;
return xhtml;
}
|
javascript
|
{
"resource": ""
}
|
q56157
|
getCrumbTrailXHTML
|
train
|
function getCrumbTrailXHTML( crumbs )
{
var xhtml = '<span class="' + CSS_CLASS_TRAIL + '">';
xhtml += DISPLAY_PREPREND;
for( var i = 0; i < crumbs.length; i++ )
{
xhtml += '<a href="' + crumbs[i][1] + '" class="' + CSS_CLASS_CRUMB + '">';
xhtml += unescape( crumbs[i][0] ) + '</a>';
if( i != (crumbs.length-1) )
{
xhtml += '<span class="' + CSS_CLASS_SEPARATOR + '">' + DISPLAY_SEPARATOR + '</span>';
}
}
xhtml += DISPLAY_POSTPREND;
xhtml += '</span>';
return xhtml;
}
|
javascript
|
{
"resource": ""
}
|
q56158
|
train
|
function(categoryName) {
// Use default logger if categoryName is not specified or invalid
if (!(typeof categoryName == "string")) {
categoryName = "[default]";
}
if (!Log4js.loggers[categoryName]) {
// Create the logger for this name if it doesn't already exist
Log4js.loggers[categoryName] = new Log4js.Logger(categoryName);
}
return Log4js.loggers[categoryName];
}
|
javascript
|
{
"resource": ""
}
|
|
q56159
|
train
|
function (element, name, observer) {
if (element.addEventListener) { //DOM event model
element.addEventListener(name, observer, false);
} else if (element.attachEvent) { //M$ event model
element.attachEvent('on' + name, observer);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56160
|
train
|
function(sArg, defaultLevel) {
if(sArg === null) {
return defaultLevel;
}
if(typeof sArg == "string") {
var s = sArg.toUpperCase();
if(s == "ALL") {return Log4js.Level.ALL;}
if(s == "DEBUG") {return Log4js.Level.DEBUG;}
if(s == "INFO") {return Log4js.Level.INFO;}
if(s == "WARN") {return Log4js.Level.WARN;}
if(s == "ERROR") {return Log4js.Level.ERROR;}
if(s == "FATAL") {return Log4js.Level.FATAL;}
if(s == "OFF") {return Log4js.Level.OFF;}
if(s == "TRACE") {return Log4js.Level.TRACE;}
return defaultLevel;
} else if(typeof sArg == "number") {
switch(sArg) {
case ALL_INT: return Log4js.Level.ALL;
case DEBUG_INT: return Log4js.Level.DEBUG;
case INFO_INT: return Log4js.Level.INFO;
case WARN_INT: return Log4js.Level.WARN;
case ERROR_INT: return Log4js.Level.ERROR;
case FATAL_INT: return Log4js.Level.FATAL;
case OFF_INT: return Log4js.Level.OFF;
case TRACE_INT: return Log4js.Level.TRACE;
default: return defaultLevel;
}
} else {
return defaultLevel;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56161
|
train
|
function(appender) {
if (appender instanceof Log4js.Appender) {
appender.setLogger(this);
this.appenders.push(appender);
} else {
throw "Not instance of an Appender: " + appender;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56162
|
train
|
function(appenders) {
//clear first all existing appenders
for(var i = 0; i < this.appenders.length; i++) {
this.appenders[i].doClear();
}
this.appenders = appenders;
for(var j = 0; j < this.appenders.length; j++) {
this.appenders[j].setLogger(this);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56163
|
train
|
function(logLevel, message, exception) {
var loggingEvent = new Log4js.LoggingEvent(this.category, logLevel,
message, exception, this);
this.loggingEvents.push(loggingEvent);
this.onlog.dispatch(loggingEvent);
}
|
javascript
|
{
"resource": ""
}
|
|
q56164
|
train
|
function(msg, url, line){
var message = "Error in (" + (url || window.location) + ") on line "+ line +" with message (" + msg + ")";
this.log(Log4js.Level.FATAL, message, null);
}
|
javascript
|
{
"resource": ""
}
|
|
q56165
|
train
|
function(logger){
// add listener to the logger methods
logger.onlog.addListener(Log4js.bind(this.doAppend, this));
logger.onclear.addListener(Log4js.bind(this.doClear, this));
this.logger = logger;
}
|
javascript
|
{
"resource": ""
}
|
|
q56166
|
train
|
function(loggingEvent) {
log4jsLogger.trace("> AjaxAppender.append");
if (this.loggingEventMap.length() <= this.threshold || this.isInProgress === true) {
this.loggingEventMap.push(loggingEvent);
}
if(this.loggingEventMap.length() >= this.threshold && this.isInProgress === false) {
//if threshold is reached send the events and reset current threshold
this.send();
}
log4jsLogger.trace("< AjaxAppender.append");
}
|
javascript
|
{
"resource": ""
}
|
|
q56167
|
train
|
function() {
if(this.loggingEventMap.length() >0) {
log4jsLogger.trace("> AjaxAppender.send");
this.isInProgress = true;
var a = [];
for(var i = 0; i < this.loggingEventMap.length() && i < this.threshold; i++) {
a.push(this.layout.format(this.loggingEventMap.pull()));
}
var content = this.layout.getHeader();
content += a.join(this.layout.getSeparator());
content += this.layout.getFooter();
var appender = this;
if(this.httpRequest === null){
this.httpRequest = this.getXmlHttpRequest();
}
this.httpRequest.onreadystatechange = function() {
appender.onReadyStateChanged.call(appender);
};
this.httpRequest.open("POST", this.loggingUrl, true);
// set the request headers.
this.httpRequest.setRequestHeader("Content-type", this.layout.getContentType());
this.httpRequest.send( content );
appender = this;
try {
window.setTimeout(function(){
log4jsLogger.trace("> AjaxAppender.timeout");
appender.httpRequest.onreadystatechange = function(){return;};
appender.httpRequest.abort();
//this.httpRequest = null;
appender.isInProgress = false;
if(appender.loggingEventMap.length() > 0) {
appender.send();
}
log4jsLogger.trace("< AjaxAppender.timeout");
}, this.timeout);
} catch (e) {
log4jsLogger.fatal(e);
}
log4jsLogger.trace("> AjaxAppender.send");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q56168
|
train
|
function() {
log4jsLogger.trace("> AjaxAppender.getXmlHttpRequest");
var httpRequest = false;
try {
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType(this.layout.getContentType());
}
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
}
} catch (e) {
httpRequest = false;
}
if (!httpRequest) {
log4jsLogger.fatal("Unfortunatelly your browser does not support AjaxAppender for log4js!");
}
log4jsLogger.trace("< AjaxAppender.getXmlHttpRequest");
return httpRequest;
}
|
javascript
|
{
"resource": ""
}
|
|
q56169
|
train
|
function(ex) {
if (ex) {
var exStr = "\t<log4js:throwable>";
if (ex.message) {
exStr += "\t\t<log4js:message><![CDATA[" + this.escapeCdata(ex.message) + "]]></log4js:message>\n";
}
if (ex.description) {
exStr += "\t\t<log4js:description><![CDATA[" + this.escapeCdata(ex.description) + "]]></log4js:description>\n";
}
exStr += "\t\t<log4js:stacktrace>";
exStr += "\t\t\t<log4js:location fileName=\""+ex.fileName+"\" lineNumber=\""+ex.lineNumber+"\" />";
exStr += "\t\t</log4js:stacktrace>";
exStr = "\t</log4js:throwable>";
return exStr;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q56170
|
SlackBot
|
train
|
function SlackBot(config) {
this.config = config || {};
this.commands = {};
this.aliases = {};
if (!this.config.structureResponse) {
this.config.structureResponse = function (response) {
return response;
};
}
}
|
javascript
|
{
"resource": ""
}
|
q56171
|
translate
|
train
|
function translate(load){
var filename;
//!steal-remove-start
filename = getFilename(load.name);
//!steal-remove-end
var result = parse(load.source, this, zoneOpts);
// Add any import specifiers to the load.
addImportSpecifiers(load, result);
load.metadata.originalSource = load.source;
// Register dynamic imports for the slim loader config
var localLoader = loader.localLoader || loader;
if (localLoader.slimConfig) {
localLoader.slimConfig.needsDynamicLoader = true;
var toMap = localLoader.slimConfig.toMap;
Array.prototype.push.apply(toMap, result.rawImports);
Array.prototype.push.apply(toMap, result.dynamicImports);
}
// For live-reload, determine if we should reload the viewModel
hasDynamicImports = result.dynamicImports.length > 0;
return Promise.all([
addBundles(result.dynamicImports, load.name),
Promise.all(result.imports)
]).then(function(pResults){
var exportedValuesDef = Object.keys(result.ases)
.map(function(name){
return "\"" + name + "\": {\n" +
"\t\t\tenumerable: true,\n" +
"\t\t\tconfigurable: true,\n" +
"\t\t\twritable: true,\n" +
"\t\t\tvalue: " + name + "['default'] || " + name + "\n" +
"\t\t}";
}).join(",\n");
var output = template({
imports: JSON.stringify(pResults[1]),
isDevelopment: isDevelopment || false,
routeData: result.viewModel.routeData || "",
args: result.args.join(", "),
zoneOpts: JSON.stringify(zoneOpts),
intermediate: JSON.stringify(result.intermediate),
ases: exportedValuesDef ? exportedValuesDef + "," : "",
filename: filename
});
return output;
});
}
|
javascript
|
{
"resource": ""
}
|
q56172
|
ensure_element_id
|
train
|
function ensure_element_id(element) {
if (!element.id || element.id === '') {
element.id = config.generate_random_id('ac_element');
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q56173
|
_attach
|
train
|
function _attach(ngmodel, target_element, options) {
// Element is already attached.
if (current_element === target_element) {
return;
}
// Safe: clear previously attached elements.
if (current_element) {
that.detach();
}
// The element is still the active element.
if (target_element[0] !== $document[0].activeElement) {
return;
}
if (options.on_attach) {
options.on_attach();
}
current_element = target_element;
current_model = ngmodel;
current_options = options;
previous_value = ngmodel.$viewValue;
current_element_random_id_set = ensure_element_id(target_element);
$scope.container[0].setAttribute('aria-labelledby', current_element.id);
$scope.results = [];
$scope.selected_index = -1;
bind_element();
value_watch = $scope.$watch(
function() {
return ngmodel.$modelValue;
},
function(nv) {
// Prevent suggestion cycle when the value is the last value selected.
// When selecting from the menu the ng-model is updated and this watch
// is triggered. This causes another suggestion cycle that will provide as
// suggestion the value that is currently selected - this is unnecessary.
if (nv === last_selected_value) {
return;
}
_position_autocomplete();
suggest(nv, current_element);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q56174
|
set_selection
|
train
|
function set_selection(i) {
// We use value instead of setting the model's view value
// because we watch the model value and setting it will trigger
// a new suggestion cycle.
var selected = $scope.results[i];
current_element.val(selected.value);
$scope.selected_index = i;
$scope.container[0].setAttribute('aria-activedescendant', selected.id);
return selected;
}
|
javascript
|
{
"resource": ""
}
|
q56175
|
fetchChatList
|
train
|
async function fetchChatList() {
return _makeSimulatedNetworkRequest((resolve, reject) => {
resolve(backendStateForLoggedInPerson.chats.map(chat => chat.name));
});
}
|
javascript
|
{
"resource": ""
}
|
q56176
|
fetchChat
|
train
|
async function fetchChat(name) {
return _makeSimulatedNetworkRequest((resolve, reject) => {
resolve(
backendStateForLoggedInPerson.chats.find(
chat => chat.name === name
)
);
});
}
|
javascript
|
{
"resource": ""
}
|
q56177
|
sendMessage
|
train
|
async function sendMessage({name, message}) {
return _makeSimulatedNetworkRequest((resolve, reject) => {
const chatForName = backendStateForLoggedInPerson.chats.find(
chat => chat.name === name
);
if (chatForName) {
chatForName.messages.push({
name: 'Me',
text: message,
});
resolve();
} else {
reject(new Error('Uknown person: ' + name));
}
});
}
|
javascript
|
{
"resource": ""
}
|
q56178
|
getInverseDependencies
|
train
|
function getInverseDependencies(resolutionResponse) {
const cache = new Map();
resolutionResponse.dependencies.forEach(module => {
resolveModuleRequires(resolutionResponse, module).forEach(dependency => {
getModuleDependents(cache, dependency).add(module);
});
});
return cache;
}
|
javascript
|
{
"resource": ""
}
|
q56179
|
copyToClipBoard
|
train
|
function copyToClipBoard(content) {
switch (process.platform) {
case 'darwin':
var child = spawn('pbcopy', []);
child.stdin.end(new Buffer(content, 'utf8'));
return true;
case 'win32':
var child = spawn('clip', []);
child.stdin.end(new Buffer(content, 'utf8'));
return true;
default:
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q56180
|
recurse
|
train
|
function recurse (obj, manifest, path, remoteCall) {
for(var name in manifest) (function (name, type) {
var _path = path ? path.concat(name) : [name]
obj[name] =
isObject(type)
? recurse({}, type, _path, remoteCall)
: function () {
return remoteCall(type, _path, [].slice.call(arguments))
}
})(name, manifest[name])
return obj
}
|
javascript
|
{
"resource": ""
}
|
q56181
|
buildBabelConfig
|
train
|
function buildBabelConfig(filename, options) {
const babelRC = getBabelRC(options.projectRoots);
const extraConfig = {
code: false,
filename,
};
let config = Object.assign({}, babelRC, extraConfig);
// Add extra plugins
const extraPlugins = [externalHelpersPlugin];
var inlineRequires = options.inlineRequires;
var blacklist = inlineRequires && inlineRequires.blacklist;
if (inlineRequires && !(blacklist && filename in blacklist)) {
extraPlugins.push(inlineRequiresPlugin);
}
config.plugins = extraPlugins.concat(config.plugins);
if (options.hot) {
const hmrConfig = makeHMRConfig(options, filename);
config = Object.assign({}, config, hmrConfig);
}
return Object.assign({}, babelRC, config);
}
|
javascript
|
{
"resource": ""
}
|
q56182
|
once
|
train
|
function once (fn) {
var done = false
return function (err, val) {
if(done) return
done = true
fn(err, val)
}
}
|
javascript
|
{
"resource": ""
}
|
q56183
|
library
|
train
|
function library(argv, config, args) {
if (!isValidPackageName(args.name)) {
return Promise.reject(
args.name + ' is not a valid name for a project. Please use a valid ' +
'identifier name (alphanumeric).'
);
}
const root = process.cwd();
const libraries = path.resolve(root, 'Libraries');
const libraryDest = path.resolve(libraries, args.name);
const source = path.resolve('node_modules', 'react-native', 'Libraries', 'Sample');
if (!fs.existsSync(libraries)) {
fs.mkdir(libraries);
}
if (fs.existsSync(libraryDest)) {
return Promise.reject(`Library already exists in ${libraryDest}`);
}
walk(source).forEach(f => {
if (f.indexOf('project.xcworkspace') !== -1 ||
f.indexOf('.xcodeproj/xcuserdata') !== -1) {
return;
}
const dest = f.replace(/Sample/g, args.name).replace(/^_/, '.');
copyAndReplace(
path.resolve(source, f),
path.resolve(libraryDest, dest),
{'Sample': args.name}
);
});
console.log('Created library in', libraryDest);
console.log('Next Steps:');
console.log(' Link your library in Xcode:');
console.log(
' https://facebook.github.io/react-native/docs/' +
'linking-libraries-ios.html#content\n'
);
}
|
javascript
|
{
"resource": ""
}
|
q56184
|
eject
|
train
|
function eject() {
const doesIOSExist = fs.existsSync(path.resolve('ios'));
const doesAndroidExist = fs.existsSync(path.resolve('android'));
if (doesIOSExist && doesAndroidExist) {
console.error(
'Both the iOS and Android folders already exist! Please delete `ios` and/or `android` ' +
'before ejecting.'
);
process.exit(1);
}
let appConfig = null;
try {
appConfig = require(path.resolve('app.json'));
} catch(e) {
console.error(
`Eject requires an \`app.json\` config file to be located at ` +
`${path.resolve('app.json')}, and it must at least specify a \`name\` for the project ` +
`name, and a \`displayName\` for the app's home screen label.`
);
process.exit(1);
}
const appName = appConfig.name;
if (!appName) {
console.error(
`App \`name\` must be defined in the \`app.json\` config file to define the project name. `+
`It must not contain any spaces or dashes.`
);
process.exit(1);
}
const displayName = appConfig.displayName;
if (!displayName) {
console.error(
`App \`displayName\` must be defined in the \`app.json\` config file, to define the label ` +
`of the app on the home screen.`
);
process.exit(1);
}
const templateOptions = { displayName };
if (!doesIOSExist) {
console.log('Generating the iOS folder.');
copyProjectTemplateAndReplace(
path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld', 'ios'),
path.resolve('ios'),
appName,
templateOptions
);
}
if (!doesAndroidExist) {
console.log('Generating the Android folder.');
copyProjectTemplateAndReplace(
path.resolve('node_modules', 'react-native', 'local-cli', 'templates', 'HelloWorld', 'android'),
path.resolve('android'),
appName,
templateOptions
);
}
}
|
javascript
|
{
"resource": ""
}
|
q56185
|
copyAndReplace
|
train
|
function copyAndReplace(srcPath, destPath, replacements, contentChangedCallback) {
if (fs.lstatSync(srcPath).isDirectory()) {
if (!fs.existsSync(destPath)) {
fs.mkdirSync(destPath);
}
// Not recursive
return;
}
const extension = path.extname(srcPath);
if (binaryExtensions.indexOf(extension) !== -1) {
// Binary file
let shouldOverwrite = 'overwrite';
if (contentChangedCallback) {
const newContentBuffer = fs.readFileSync(srcPath);
let contentChanged = 'identical';
try {
const origContentBuffer = fs.readFileSync(destPath);
if (Buffer.compare(origContentBuffer, newContentBuffer) !== 0) {
contentChanged = 'changed';
}
} catch (err) {
if (err.code === 'ENOENT') {
contentChanged = 'new';
} else {
throw err;
}
}
shouldOverwrite = contentChangedCallback(destPath, contentChanged);
}
if (shouldOverwrite === 'overwrite') {
copyBinaryFile(srcPath, destPath, (err) => {
if (err) { throw err; }
});
}
} else {
// Text file
const srcPermissions = fs.statSync(srcPath).mode;
let content = fs.readFileSync(srcPath, 'utf8');
Object.keys(replacements).forEach(regex =>
content = content.replace(new RegExp(regex, 'g'), replacements[regex])
);
let shouldOverwrite = 'overwrite';
if (contentChangedCallback) {
// Check if contents changed and ask to overwrite
let contentChanged = 'identical';
try {
const origContent = fs.readFileSync(destPath, 'utf8');
if (content !== origContent) {
//console.log('Content changed: ' + destPath);
contentChanged = 'changed';
}
} catch (err) {
if (err.code === 'ENOENT') {
contentChanged = 'new';
} else {
throw err;
}
}
shouldOverwrite = contentChangedCallback(destPath, contentChanged);
}
if (shouldOverwrite === 'overwrite') {
fs.writeFileSync(destPath, content, {
encoding: 'utf8',
mode: srcPermissions,
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q56186
|
BigNumber
|
train
|
function BigNumber(number) {
this.numberStr = number.toString();
// not a number
if (isNaN(parseFloat(this.numberStr)) === true
|| isFinite(this.numberStr) === false) {
throw new Error(number + ' is not a number');
}
}
|
javascript
|
{
"resource": ""
}
|
q56187
|
callYarnOrNpm
|
train
|
function callYarnOrNpm(yarnCommand, npmCommand) {
let command;
if (isYarnAvailable) {
command = yarnCommand;
} else {
command = npmCommand;
}
const args = command.split(' ');
const cmd = args.shift();
const res = spawnSync(cmd, args, spawnOpts);
return res;
}
|
javascript
|
{
"resource": ""
}
|
q56188
|
link
|
train
|
function link(args, config) {
var project;
try {
project = config.getProjectConfig();
} catch (err) {
log.error(
'ERRPACKAGEJSON',
'No package found. Are you sure it\'s a React Native project?'
);
return Promise.reject(err);
}
let packageName = args[0];
// Check if install package by specific version (eg. package@latest)
if (packageName !== undefined) {
packageName = packageName.split('@')[0];
}
const dependencies = getDependencyConfig(
config,
packageName ? [packageName] : getProjectDependencies()
);
const assets = dedupeAssets(dependencies.reduce(
(assets, dependency) => assets.concat(dependency.config.assets),
project.assets
));
const tasks = flatten(dependencies.map(dependency => [
() => promisify(dependency.config.commands.prelink || commandStub),
() => linkDependencyAndroid(project.android, dependency),
() => linkDependencyIOS(project.ios, dependency),
() => linkDependencyWindows(project.windows, dependency),
() => promisify(dependency.config.commands.postlink || commandStub),
]));
tasks.push(() => linkAssets(project, assets));
return promiseWaterfall(tasks).catch(err => {
log.error(
`It seems something went wrong while linking. Error: ${err.message} \n`
+ 'Please file an issue here: https://github.com/facebook/react-native/issues'
);
throw err;
});
}
|
javascript
|
{
"resource": ""
}
|
q56189
|
addJestToPackageJson
|
train
|
function addJestToPackageJson(destinationRoot) {
var packageJSONPath = path.join(destinationRoot, 'package.json');
var packageJSON = JSON.parse(fs.readFileSync(packageJSONPath));
packageJSON.scripts.test = 'jest';
packageJSON.jest = {
preset: 'react-native'
};
fs.writeFileSync(packageJSONPath, JSON.stringify(packageJSON, null, '\t'));
}
|
javascript
|
{
"resource": ""
}
|
q56190
|
isValidBody
|
train
|
function isValidBody(body) {
return (
body === undefined ||
typeof body === 'string' ||
(typeof FormData !== 'undefined' && body instanceof FormData) ||
(typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams)
);
}
|
javascript
|
{
"resource": ""
}
|
q56191
|
string2utf8Bytes
|
train
|
function string2utf8Bytes(s) {
var utf8 = unescape(encodeURIComponent(s)),
len = utf8.length,
bytes = new Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = utf8.charCodeAt(i);
}
return bytes;
}
|
javascript
|
{
"resource": ""
}
|
q56192
|
findPrev
|
train
|
function findPrev(type/*: string*/, element/*: Cheerio*/) {
let tries = 5
let prev = element
do {
if (prev.is(type)) {
return prev
}
prev = prev.prev()
}
while (--tries)
return prev
}
|
javascript
|
{
"resource": ""
}
|
q56193
|
findNext
|
train
|
function findNext(type, element) {
let tries = 5
let next = element
do {
if (next.is(type)) {
return next
}
next = next.next()
}
while (--tries)
return next
}
|
javascript
|
{
"resource": ""
}
|
q56194
|
smartComment
|
train
|
function smartComment(description/*:string*/ = '', links/*: string[]*/ = []) {
const descriptionLines = description.replace(/(.{1,72}\s)\s*?/g, '\n * $1')
const linksLines = links.reduce((acc, link) => (
`${acc} * @see ${link}\n`
), '')
return commentBlock(`*${descriptionLines}\n${linksLines} `)
}
|
javascript
|
{
"resource": ""
}
|
q56195
|
fixImportedSourceMap
|
train
|
function fixImportedSourceMap(file, state, callback) {
if (!state.map) {
return callback();
}
state.map.sourcesContent = state.map.sourcesContent || [];
nal.map(state.map.sources, normalizeSourcesAndContent, callback);
function assignSourcesContent(sourceContent, idx) {
state.map.sourcesContent[idx] = sourceContent;
}
function normalizeSourcesAndContent(sourcePath, idx, cb) {
var sourceRoot = state.map.sourceRoot || '';
var sourceContent = state.map.sourcesContent[idx] || null;
if (isRemoteSource(sourcePath)) {
assignSourcesContent(sourceContent, idx);
return cb();
}
if (state.map.sourcesContent[idx]) {
return cb();
}
if (sourceRoot && isRemoteSource(sourceRoot)) {
assignSourcesContent(sourceContent, idx);
return cb();
}
var basePath = path.resolve(file.base, sourceRoot);
var absPath = path.resolve(state.path, sourceRoot, sourcePath);
var relPath = path.relative(basePath, absPath);
var unixRelPath = normalizePath(relPath);
state.map.sources[idx] = unixRelPath;
if (absPath !== file.path) {
// Load content from file async
return fs.readFile(absPath, onRead);
}
// If current file: use content
assignSourcesContent(state.content, idx);
cb();
function onRead(err, data) {
if (err) {
assignSourcesContent(null, idx);
return cb();
}
assignSourcesContent(removeBOM(data).toString('utf8'), idx);
cb();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q56196
|
FlashWS
|
train
|
function FlashWS (options) {
WS.call(this, options);
this.flashPath = options.flashPath;
this.policyPort = options.policyPort;
}
|
javascript
|
{
"resource": ""
}
|
q56197
|
log
|
train
|
function log (type) {
return function(){
var str = Array.prototype.join.call(arguments, ' ');
debug('[websocketjs %s] %s', type, str);
};
}
|
javascript
|
{
"resource": ""
}
|
q56198
|
load
|
train
|
function load (arr, fn) {
function process (i) {
if (!arr[i]) return fn();
create(arr[i], function () {
process(++i);
});
};
process(0);
}
|
javascript
|
{
"resource": ""
}
|
q56199
|
saveCategoryList
|
train
|
function saveCategoryList(categoryObject){
var destinationPath = config.dest + 'db_category_list.json';
grunt.file.write(destinationPath, JSON.stringify(categoryObject, null, 4));
grunt.log.writeln('Prefixed file "' + destinationPath + '" created.');
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.