_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q26000 | parseInput | train | function parseInput(str, idx) {
var raw = String(str || '');
var sliced = raw.slice(0, idx);
var sections = sliced.split('|');
var prefix = sections.slice(0, sections.length - 1) || [];
prefix.push('');
prefix = prefix.join('|');
var suffix = getSuffix(raw.slice(idx));
var context = sections[sections.length - 1];
return {
raw: raw,
prefix: prefix,
suffix: suffix,
context: context
};
} | javascript | {
"resource": ""
} |
q26001 | parseMatchSection | train | function parseMatchSection(input) {
var parts = (input.context || '').split(' ');
var last = parts.pop();
var beforeLast = strip(parts[parts.length - 1] || '').trim();
if (beforeLast.slice(0, 1) === '-') {
input.option = beforeLast;
}
input.context = last;
input.prefix = (input.prefix || '') + parts.join(' ') + ' ';
return input;
} | javascript | {
"resource": ""
} |
q26002 | getCommandNames | train | function getCommandNames(cmds) {
var commands = _.map(cmds, '_name');
commands = commands.concat.apply(commands, _.map(cmds, '_aliases'));
commands.sort();
return commands;
} | javascript | {
"resource": ""
} |
q26003 | getMatchData | train | function getMatchData(input, cb) {
var string = input.context;
var cmd = input.match;
var midOption = String(string).trim().slice(0, 1) === '-';
var afterOption = input.option !== undefined;
if (midOption === true && !cmd._allowUnknownOptions) {
var results = [];
for (var i = 0; i < cmd.options.length; ++i) {
var long = cmd.options[i].long;
var short = cmd.options[i].short;
if (!long && short) {
results.push(short);
} else if (long) {
results.push(long);
}
}
cb(results);
return;
}
function handleDataFormat(str, config, callback) {
var data = [];
if (_.isArray(config)) {
data = config;
} else if (_.isFunction(config)) {
var cbk = config.length < 2 ? function () {} : function (res) {
callback(res || []);
};
var res = config(str, cbk);
if (res && _.isFunction(res.then)) {
res.then(function (resp) {
callback(resp);
}).catch(function (err) {
callback(err);
});
} else if (config.length < 2) {
callback(res);
}
return;
}
callback(data);
return;
}
if (afterOption === true) {
var opt = strip(input.option).trim();
var shortMatch = _.find(cmd.options, { short: opt });
var longMatch = _.find(cmd.options, { long: opt });
var match = longMatch || shortMatch;
if (match) {
var config = match.autocomplete;
handleDataFormat(string, config, cb);
return;
}
}
var conf = cmd._autocomplete;
conf = conf && conf.data ? conf.data : conf;
handleDataFormat(string, conf, cb);
return;
} | javascript | {
"resource": ""
} |
q26004 | train | function (str, cb) {
var self = this;
var input = parseInput(str, this.parent.ui._activePrompt.screen.rl.cursor);
var commands = getCommandNames(this.parent.commands);
var vorpalMatch = getMatch(input.context, commands, {ignoreSlashes: true});
var freezeTabs = false;
function end(str) {
var res = handleTabCounts.call(self, str, freezeTabs);
cb(undefined, res);
}
function evaluateTabs(input) {
if (input.context && input.context[input.context.length - 1] === '/') {
freezeTabs = true;
}
}
if (vorpalMatch) {
input.context = vorpalMatch;
evaluateTabs(input);
end(assembleInput(input));
return;
}
input = getMatchObject.call(this, input, commands);
if (input.match) {
input = parseMatchSection.call(this, input);
getMatchData.call(self, input, function (data) {
var dataMatch = getMatch(input.context, data);
if (dataMatch) {
input.context = dataMatch;
evaluateTabs(input);
end(assembleInput(input));
return;
}
end(filterData(input.context, data));
});
return;
}
end(filterData(input.context, commands));
} | javascript | {
"resource": ""
} | |
q26005 | filterData | train | function filterData(str, data) {
data = data || [];
var ctx = String(str || '').trim();
var slashParts = ctx.split('/');
ctx = slashParts.pop();
var wordParts = String(ctx).trim().split(' ');
var res = data.filter(function (item) {
return (strip(item).slice(0, ctx.length) === ctx);
});
res = res.map(function (item) {
var parts = String(item).trim().split(' ');
if (parts.length > 1) {
parts = parts.slice(wordParts.length);
return parts.join(' ');
}
return item;
});
return res;
} | javascript | {
"resource": ""
} |
q26006 | getSuffix | train | function getSuffix(suffix) {
suffix = (suffix.slice(0, 1) === ' ') ?
suffix :
suffix.replace(/.+?(?=\s)/, '');
suffix = suffix.slice(1, suffix.length);
return suffix;
} | javascript | {
"resource": ""
} |
q26007 | getMatchObject | train | function getMatchObject(input, commands) {
var len = input.context.length;
var trimmed = String(input.context).replace(/^\s+/g, '');
var prefix = new Array((len - trimmed.length) + 1).join(' ');
var match;
var suffix;
commands.forEach(function (cmd) {
var nextChar = trimmed.substr(cmd.length, 1);
if (trimmed.substr(0, cmd.length) === cmd && String(cmd).trim() !== '' && nextChar === ' ') {
match = cmd;
suffix = trimmed.substr(cmd.length);
prefix += trimmed.substr(0, cmd.length);
}
});
var matchObject = (match) ?
_.find(this.parent.commands, {_name: String(match).trim()}) :
undefined;
if (!matchObject) {
this.parent.commands.forEach(function (cmd) {
if ((cmd._aliases || []).indexOf(String(match).trim()) > -1) {
matchObject = cmd;
}
return;
});
}
if (!matchObject) {
matchObject = _.find(this.parent.commands, {_catch: true});
if (matchObject) {
suffix = input.context;
}
}
if (!matchObject) {
prefix = input.context;
suffix = '';
}
if (matchObject) {
input.match = matchObject;
input.prefix += prefix;
input.context = suffix;
}
return input;
} | javascript | {
"resource": ""
} |
q26008 | PixelWalker | train | function PixelWalker(firstPoint, pixel_path) {
// go clockwise starting first point
var points = [];
points.push(firstPoint);
var moveHorizontal = true; // alternate horizontal and vertical movements to form pixel heart
pixel_path.forEach(function (p) {
var previous_point = points[points.length - 1];
var point_to_add;
if (moveHorizontal) {
point_to_add = [p, 0];
} else {
point_to_add = [0, p];
}
var e = makerjs.point.add(previous_point, point_to_add);
points.push(e);
// flip direction each time
moveHorizontal = !moveHorizontal;
});
return points;
} | javascript | {
"resource": ""
} |
q26009 | Heart | train | function Heart(desired_width) {
var points = PixelWalker(STARTING_POINT, path);
var pathModel = new makerjs.models.ConnectTheDots(true, points);
if (typeof desired_width != 'undefined') {
var scale = desired_width / HEART_WIDTH;
makerjs.model.scale(pathModel, scale);
}
return pathModel;
} | javascript | {
"resource": ""
} |
q26010 | complete2 | train | function complete2() {
//reset any calls to document.write
resetLog();
//reinstate alert
window.alert = originalAlert;
var originalFn = parent.makerjs.exporter.toSVG;
var captureExportedModel;
parent.makerjs.exporter.toSVG = function (itemToExport, options) {
if (parent.makerjs.isModel(itemToExport)) {
captureExportedModel = itemToExport;
}
else if (Array.isArray(itemToExport)) {
captureExportedModel = {};
itemToExport.forEach(function (x, i) {
if (makerjs.isModel(x)) {
captureExportedModel.models = captureExportedModel.models || {};
captureExportedModel.models[i] = x;
}
if (makerjs.isPath(x)) {
captureExportedModel.paths = captureExportedModel.paths || {};
captureExportedModel.paths[i] = x;
}
});
}
else if (parent.makerjs.isPath(itemToExport)) {
captureExportedModel = { paths: { "0": itemToExport } };
}
return originalFn(itemToExport, options);
};
//when all requirements are collected, run the code again, using its requirements
runCodeGlobal(javaScript);
parent.makerjs.exporter.toSVG = originalFn;
if (errorReported)
return;
//yield thread for the script tag to execute
setTimeout(function () {
var model;
if (captureExportedModel) {
model = captureExportedModel;
}
else {
//restore properties from the "this" keyword
model = {};
var props = ['layer', 'models', 'notes', 'origin', 'paths', 'type', 'units', 'caption', 'exporterOptions'];
var hasProps = false;
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (prop in window) {
model[prop] = window[prop];
hasProps = true;
}
}
if (!hasProps) {
model = null;
}
}
var orderedDependencies = [];
var scripts = head.getElementsByTagName('script');
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].hasAttribute('id')) {
orderedDependencies.push(scripts[i].id);
}
}
//send results back to parent window
parent.MakerJsPlayground.processResult({ html: getHtml(), result: window.module.exports || model, orderedDependencies: orderedDependencies, paramValues: window.paramValues });
}, 0);
} | javascript | {
"resource": ""
} |
q26011 | plugin | train | function plugin (Vue, options = {}) {
if (plugin.installed) {
return
}
plugin.installed = true
// install components
Vue.use(ArcgisRestSource, options)
Vue.use(BingmapsSource, options)
Vue.use(CircleGeom, options)
Vue.use(CircleStyle, options)
Vue.use(ClusterSource, options)
Vue.use(DrawInteraction, options)
Vue.use(Feature, options)
Vue.use(FillStyle, options)
Vue.use(Geoloc, options)
Vue.use(Graticule, options)
Vue.use(GroupLayer, options)
Vue.use(IconStyle, options)
Vue.use(ImageLayer, options)
Vue.use(ImageStaticSource, options)
Vue.use(ImageWmsSource, options)
Vue.use(LineStringGeom, options)
Vue.use(Map, options)
Vue.use(MapboxSource, options)
Vue.use(ModifyInteraction, options)
Vue.use(MultiLineStringGeom, options)
Vue.use(MultiPointGeom, options)
Vue.use(MultiPolygonGeom, options)
Vue.use(OsmSource, options)
Vue.use(Overlay, options)
Vue.use(PointGeom, options)
Vue.use(PolygonGeom, options)
Vue.use(RegShapeStyle, options)
Vue.use(SelectInteraction, options)
Vue.use(SnapInteraction, options)
Vue.use(SputnikSource, options)
Vue.use(StamenSource, options)
Vue.use(StrokeStyle, options)
Vue.use(StyleBox, options)
Vue.use(StyleFunc, options)
Vue.use(TextStyle, options)
Vue.use(TileLayer, options)
Vue.use(VectorLayer, options)
Vue.use(VectorSource, options)
Vue.use(VectorTileLayer, options)
Vue.use(VectorTileSource, options)
Vue.use(WmsSource, options)
Vue.use(WmtsSource, options)
Vue.use(XyzSource, options)
} | javascript | {
"resource": ""
} |
q26012 | getBoundingBox | train | function getBoundingBox() {
if (!bounds) return // client does not want to restrict movement
if (typeof bounds === 'boolean') {
// for boolean type we use parent container bounds
var ownerRect = owner.getBoundingClientRect()
var sceneWidth = ownerRect.width
var sceneHeight = ownerRect.height
return {
left: sceneWidth * boundsPadding,
top: sceneHeight * boundsPadding,
right: sceneWidth * (1 - boundsPadding),
bottom: sceneHeight * (1 - boundsPadding),
}
}
return bounds
} | javascript | {
"resource": ""
} |
q26013 | train | function(source) {
var copy, i, len, prop;
if (typeof source !== "object" || source == null || typeof source.nodeType === "number") {
copy = source;
} else if (typeof source.length === "number") {
copy = [];
for (i = 0, len = source.length; i < len; i++) {
if (_hasOwn.call(source, i)) {
copy[i] = _deepCopy(source[i]);
}
}
} else {
copy = {};
for (prop in source) {
if (_hasOwn.call(source, prop)) {
copy[prop] = _deepCopy(source[prop]);
}
}
}
return copy;
} | javascript | {
"resource": ""
} | |
q26014 | train | function(obj) {
if (obj) {
for (var prop in obj) {
if (_hasOwn.call(obj, prop)) {
delete obj[prop];
}
}
}
return obj;
} | javascript | {
"resource": ""
} | |
q26015 | train | function(el, ancestorEl) {
if (el && el.nodeType === 1 && el.ownerDocument && ancestorEl && (ancestorEl.nodeType === 1 && ancestorEl.ownerDocument && ancestorEl.ownerDocument === el.ownerDocument || ancestorEl.nodeType === 9 && !ancestorEl.ownerDocument && ancestorEl === el.ownerDocument)) {
do {
if (el === ancestorEl) {
return true;
}
el = el.parentNode;
} while (el);
}
return false;
} | javascript | {
"resource": ""
} | |
q26016 | train | function(url) {
var dir;
if (typeof url === "string" && url) {
dir = url.split("#")[0].split("?")[0];
dir = url.slice(0, url.lastIndexOf("/") + 1);
}
return dir;
} | javascript | {
"resource": ""
} | |
q26017 | train | function() {
var jsPath, scripts, i;
if (_document.currentScript && (jsPath = _document.currentScript.src)) {
return jsPath;
}
scripts = _document.getElementsByTagName("script");
if (scripts.length === 1) {
return scripts[0].src || undefined;
}
if ("readyState" in (scripts[0] || document.createElement("script"))) {
for (i = scripts.length; i--; ) {
if (scripts[i].readyState === "interactive" && (jsPath = scripts[i].src)) {
return jsPath;
}
}
}
if (_document.readyState === "loading" && (jsPath = scripts[scripts.length - 1].src)) {
return jsPath;
}
if (jsPath = _getCurrentScriptUrlFromError()) {
return jsPath;
}
return undefined;
} | javascript | {
"resource": ""
} | |
q26018 | train | function() {
var isWindowsRegex = /win(dows|[\s]?(nt|me|ce|xp|vista|[\d]+))/i;
return !!_navigator && (isWindowsRegex.test(_navigator.appVersion || "") || isWindowsRegex.test(_navigator.platform || "") || (_navigator.userAgent || "").indexOf("Windows") !== -1);
} | javascript | {
"resource": ""
} | |
q26019 | train | function(options) {
if (typeof options === "object" && options && !("length" in options)) {
_keys(options).forEach(function(prop) {
if (/^(?:forceHandCursor|title|zIndex|bubbleEvents|fixLineEndings)$/.test(prop)) {
_globalConfig[prop] = options[prop];
} else if (_flashState.bridge == null) {
if (prop === "containerId" || prop === "swfObjectId") {
if (_isValidHtml4Id(options[prop])) {
_globalConfig[prop] = options[prop];
} else {
throw new Error("The specified `" + prop + "` value is not valid as an HTML4 Element ID");
}
} else {
_globalConfig[prop] = options[prop];
}
}
});
}
if (typeof options === "string" && options) {
if (_hasOwn.call(_globalConfig, options)) {
return _globalConfig[options];
}
return;
}
return _deepCopy(_globalConfig);
} | javascript | {
"resource": ""
} | |
q26020 | train | function() {
_detectSandbox();
return {
browser: _extend(_pick(_navigator, [ "userAgent", "platform", "appName", "appVersion" ]), {
isSupported: _isBrowserSupported()
}),
flash: _omit(_flashState, [ "bridge" ]),
zeroclipboard: {
version: ZeroClipboard.version,
config: ZeroClipboard.config()
}
};
} | javascript | {
"resource": ""
} | |
q26021 | train | function() {
return !!(_flashState.sandboxed || _flashState.disabled || _flashState.outdated || _flashState.unavailable || _flashState.degraded || _flashState.deactivated);
} | javascript | {
"resource": ""
} | |
q26022 | train | function(eventType, listener) {
var i, len, events, added = {};
if (typeof eventType === "string" && eventType) {
events = eventType.toLowerCase().split(/\s+/);
} else if (typeof eventType === "object" && eventType && !("length" in eventType) && typeof listener === "undefined") {
_keys(eventType).forEach(function(key) {
var listener = eventType[key];
if (typeof listener === "function") {
ZeroClipboard.on(key, listener);
}
});
}
if (events && events.length && listener) {
for (i = 0, len = events.length; i < len; i++) {
eventType = events[i].replace(/^on/, "");
added[eventType] = true;
if (!_handlers[eventType]) {
_handlers[eventType] = [];
}
_handlers[eventType].push(listener);
}
if (added.ready && _flashState.ready) {
ZeroClipboard.emit({
type: "ready"
});
}
if (added.error) {
if (!_isBrowserSupported()) {
ZeroClipboard.emit({
type: "error",
name: "browser-unsupported"
});
}
for (i = 0, len = _flashStateErrorNames.length; i < len; i++) {
if (_flashState[_flashStateErrorNames[i].replace(/^flash-/, "")] === true) {
ZeroClipboard.emit({
type: "error",
name: _flashStateErrorNames[i]
});
break;
}
}
if (_zcSwfVersion !== undefined && ZeroClipboard.version !== _zcSwfVersion) {
ZeroClipboard.emit({
type: "error",
name: "version-mismatch",
jsVersion: ZeroClipboard.version,
swfVersion: _zcSwfVersion
});
}
}
}
return ZeroClipboard;
} | javascript | {
"resource": ""
} | |
q26023 | train | function(eventType, listener) {
var i, len, foundIndex, events, perEventHandlers;
if (arguments.length === 0) {
events = _keys(_handlers);
} else if (typeof eventType === "string" && eventType) {
events = eventType.toLowerCase().split(/\s+/);
} else if (typeof eventType === "object" && eventType && !("length" in eventType) && typeof listener === "undefined") {
_keys(eventType).forEach(function(key) {
var listener = eventType[key];
if (typeof listener === "function") {
ZeroClipboard.off(key, listener);
}
});
}
if (events && events.length) {
for (i = 0, len = events.length; i < len; i++) {
eventType = events[i].replace(/^on/, "");
perEventHandlers = _handlers[eventType];
if (perEventHandlers && perEventHandlers.length) {
if (listener) {
foundIndex = perEventHandlers.indexOf(listener);
while (foundIndex !== -1) {
perEventHandlers.splice(foundIndex, 1);
foundIndex = perEventHandlers.indexOf(listener, foundIndex);
}
} else {
perEventHandlers.length = 0;
}
}
}
}
return ZeroClipboard;
} | javascript | {
"resource": ""
} | |
q26024 | train | function(eventType) {
var copy;
if (typeof eventType === "string" && eventType) {
copy = _deepCopy(_handlers[eventType]) || null;
} else {
copy = _deepCopy(_handlers);
}
return copy;
} | javascript | {
"resource": ""
} | |
q26025 | train | function(event) {
var eventCopy, returnVal, tmp;
event = _createEvent(event);
if (!event) {
return;
}
if (_preprocessEvent(event)) {
return;
}
if (event.type === "ready" && _flashState.overdue === true) {
return ZeroClipboard.emit({
type: "error",
name: "flash-overdue"
});
}
eventCopy = _extend({}, event);
_dispatchCallbacks.call(this, eventCopy);
if (event.type === "copy") {
tmp = _mapClipDataToFlash(_clipData);
returnVal = tmp.data;
_clipDataFormatMap = tmp.formatMap;
}
return returnVal;
} | javascript | {
"resource": ""
} | |
q26026 | train | function() {
var swfPath = _globalConfig.swfPath || "", swfPathFirstTwoChars = swfPath.slice(0, 2), swfProtocol = swfPath.slice(0, swfPath.indexOf("://") + 1);
return swfPathFirstTwoChars === "\\\\" ? "file:" : swfPathFirstTwoChars === "//" || swfProtocol === "" ? _window.location.protocol : swfProtocol;
} | javascript | {
"resource": ""
} | |
q26027 | train | function() {
var maxWait, swfProtocol, previousState = _flashState.sandboxed;
if (!_isBrowserSupported()) {
_flashState.ready = false;
ZeroClipboard.emit({
type: "error",
name: "browser-unsupported"
});
return;
}
_detectSandbox();
if (typeof _flashState.ready !== "boolean") {
_flashState.ready = false;
}
if (_flashState.sandboxed !== previousState && _flashState.sandboxed === true) {
_flashState.ready = false;
ZeroClipboard.emit({
type: "error",
name: "flash-sandboxed"
});
} else if (!ZeroClipboard.isFlashUnusable() && _flashState.bridge === null) {
swfProtocol = _getSwfPathProtocol();
if (swfProtocol && swfProtocol !== _window.location.protocol) {
ZeroClipboard.emit({
type: "error",
name: "flash-insecure"
});
} else {
maxWait = _globalConfig.flashLoadTimeout;
if (typeof maxWait === "number" && maxWait >= 0) {
_flashCheckTimeout = _setTimeout(function() {
if (typeof _flashState.deactivated !== "boolean") {
_flashState.deactivated = true;
}
if (_flashState.deactivated === true) {
ZeroClipboard.emit({
type: "error",
name: "flash-deactivated"
});
}
}, maxWait);
}
_flashState.overdue = false;
_embedSwf();
}
}
} | javascript | {
"resource": ""
} | |
q26028 | train | function(format, data) {
var dataObj;
if (typeof format === "object" && format && typeof data === "undefined") {
dataObj = format;
ZeroClipboard.clearData();
} else if (typeof format === "string" && format) {
dataObj = {};
dataObj[format] = data;
} else {
return;
}
for (var dataFormat in dataObj) {
if (typeof dataFormat === "string" && dataFormat && _hasOwn.call(dataObj, dataFormat) && typeof dataObj[dataFormat] === "string" && dataObj[dataFormat]) {
_clipData[dataFormat] = _fixLineEndings(dataObj[dataFormat]);
}
}
} | javascript | {
"resource": ""
} | |
q26029 | train | function(format) {
if (typeof format === "undefined") {
_deleteOwnProperties(_clipData);
_clipDataFormatMap = null;
} else if (typeof format === "string" && _hasOwn.call(_clipData, format)) {
delete _clipData[format];
}
} | javascript | {
"resource": ""
} | |
q26030 | train | function(format) {
if (typeof format === "undefined") {
return _deepCopy(_clipData);
} else if (typeof format === "string" && _hasOwn.call(_clipData, format)) {
return _clipData[format];
}
} | javascript | {
"resource": ""
} | |
q26031 | train | function(event) {
var eventType;
if (typeof event === "string" && event) {
eventType = event;
event = {};
} else if (typeof event === "object" && event && typeof event.type === "string" && event.type) {
eventType = event.type;
}
if (!eventType) {
return;
}
eventType = eventType.toLowerCase();
if (!event.target && (/^(copy|aftercopy|_click)$/.test(eventType) || eventType === "error" && event.name === "clipboard-error")) {
event.target = _copyTarget;
}
_extend(event, {
type: eventType,
target: event.target || _currentElement || null,
relatedTarget: event.relatedTarget || null,
currentTarget: _flashState && _flashState.bridge || null,
timeStamp: event.timeStamp || _now() || null
});
var msg = _eventMessages[event.type];
if (event.type === "error" && event.name && msg) {
msg = msg[event.name];
}
if (msg) {
event.message = msg;
}
if (event.type === "ready") {
_extend(event, {
target: null,
version: _flashState.version
});
}
if (event.type === "error") {
if (_flashStateErrorNameMatchingRegex.test(event.name)) {
_extend(event, {
target: null,
minimumVersion: _minimumFlashVersion
});
}
if (_flashStateEnabledErrorNameMatchingRegex.test(event.name)) {
_extend(event, {
version: _flashState.version
});
}
if (event.name === "flash-insecure") {
_extend(event, {
pageProtocol: _window.location.protocol,
swfProtocol: _getSwfPathProtocol()
});
}
}
if (event.type === "copy") {
event.clipboardData = {
setData: ZeroClipboard.setData,
clearData: ZeroClipboard.clearData
};
}
if (event.type === "aftercopy") {
event = _mapClipResultsFromFlash(event, _clipDataFormatMap);
}
if (event.target && !event.relatedTarget) {
event.relatedTarget = _getRelatedTarget(event.target);
}
return _addMouseData(event);
} | javascript | {
"resource": ""
} | |
q26032 | train | function(targetEl) {
var relatedTargetId = targetEl && targetEl.getAttribute && targetEl.getAttribute("data-clipboard-target");
return relatedTargetId ? _document.getElementById(relatedTargetId) : null;
} | javascript | {
"resource": ""
} | |
q26033 | train | function(event) {
if (event && /^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) {
var srcElement = event.target;
var fromElement = event.type === "_mouseover" && event.relatedTarget ? event.relatedTarget : undefined;
var toElement = event.type === "_mouseout" && event.relatedTarget ? event.relatedTarget : undefined;
var pos = _getElementPosition(srcElement);
var screenLeft = _window.screenLeft || _window.screenX || 0;
var screenTop = _window.screenTop || _window.screenY || 0;
var scrollLeft = _document.body.scrollLeft + _document.documentElement.scrollLeft;
var scrollTop = _document.body.scrollTop + _document.documentElement.scrollTop;
var pageX = pos.left + (typeof event._stageX === "number" ? event._stageX : 0);
var pageY = pos.top + (typeof event._stageY === "number" ? event._stageY : 0);
var clientX = pageX - scrollLeft;
var clientY = pageY - scrollTop;
var screenX = screenLeft + clientX;
var screenY = screenTop + clientY;
var moveX = typeof event.movementX === "number" ? event.movementX : 0;
var moveY = typeof event.movementY === "number" ? event.movementY : 0;
delete event._stageX;
delete event._stageY;
_extend(event, {
srcElement: srcElement,
fromElement: fromElement,
toElement: toElement,
screenX: screenX,
screenY: screenY,
pageX: pageX,
pageY: pageY,
clientX: clientX,
clientY: clientY,
x: clientX,
y: clientY,
movementX: moveX,
movementY: moveY,
offsetX: 0,
offsetY: 0,
layerX: 0,
layerY: 0
});
}
return event;
} | javascript | {
"resource": ""
} | |
q26034 | train | function(func, context, args, async) {
if (async) {
_setTimeout(function() {
func.apply(context, args);
}, 0);
} else {
func.apply(context, args);
}
} | javascript | {
"resource": ""
} | |
q26035 | train | function(event) {
var isSandboxed = null;
if (_pageIsFramed === false || event && event.type === "error" && event.name && _errorsThatOnlyOccurAfterFlashLoads.indexOf(event.name) !== -1) {
isSandboxed = false;
}
return isSandboxed;
} | javascript | {
"resource": ""
} | |
q26036 | train | function(aftercopyEvent) {
if (aftercopyEvent.errors && aftercopyEvent.errors.length > 0) {
var errorEvent = _deepCopy(aftercopyEvent);
_extend(errorEvent, {
type: "error",
name: "clipboard-error"
});
delete errorEvent.success;
_setTimeout(function() {
ZeroClipboard.emit(errorEvent);
}, 0);
}
} | javascript | {
"resource": ""
} | |
q26037 | train | function(event) {
if (!(event && typeof event.type === "string" && event)) {
return;
}
var e, target = event.target || null, doc = target && target.ownerDocument || _document, defaults = {
view: doc.defaultView || _window,
canBubble: true,
cancelable: true,
detail: event.type === "click" ? 1 : 0,
button: typeof event.which === "number" ? event.which - 1 : typeof event.button === "number" ? event.button : doc.createEvent ? 0 : 1
}, args = _extend(defaults, event);
if (!target) {
return;
}
if (doc.createEvent && target.dispatchEvent) {
args = [ args.type, args.canBubble, args.cancelable, args.view, args.detail, args.screenX, args.screenY, args.clientX, args.clientY, args.ctrlKey, args.altKey, args.shiftKey, args.metaKey, args.button, args.relatedTarget ];
e = doc.createEvent("MouseEvents");
if (e.initMouseEvent) {
e.initMouseEvent.apply(e, args);
e._source = "js";
target.dispatchEvent(e);
}
}
} | javascript | {
"resource": ""
} | |
q26038 | train | function() {
var container = _document.createElement("div");
container.id = _globalConfig.containerId;
container.className = _globalConfig.containerClass;
container.style.position = "absolute";
container.style.left = "0px";
container.style.top = "-9999px";
container.style.width = "1px";
container.style.height = "1px";
container.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex);
return container;
} | javascript | {
"resource": ""
} | |
q26039 | train | function() {
var len, flashBridge = _flashState.bridge, container = _getHtmlBridge(flashBridge);
if (!flashBridge) {
var allowScriptAccess = _determineScriptAccess(_window.location.host, _globalConfig);
var allowNetworking = allowScriptAccess === "never" ? "none" : "all";
var flashvars = _vars(_extend({
jsVersion: ZeroClipboard.version
}, _globalConfig));
var swfUrl = _globalConfig.swfPath + _cacheBust(_globalConfig.swfPath, _globalConfig);
if (_pageIsXhtml) {
swfUrl = _escapeXmlValue(swfUrl);
}
container = _createHtmlBridge();
var divToBeReplaced = _document.createElement("div");
container.appendChild(divToBeReplaced);
_document.body.appendChild(container);
var tmpDiv = _document.createElement("div");
var usingActiveX = _flashState.pluginType === "activex";
tmpDiv.innerHTML = '<object id="' + _globalConfig.swfObjectId + '" name="' + _globalConfig.swfObjectId + '" ' + 'width="100%" height="100%" ' + (usingActiveX ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : 'type="application/x-shockwave-flash" data="' + swfUrl + '"') + ">" + (usingActiveX ? '<param name="movie" value="' + swfUrl + '"/>' : "") + '<param name="allowScriptAccess" value="' + allowScriptAccess + '"/>' + '<param name="allowNetworking" value="' + allowNetworking + '"/>' + '<param name="menu" value="false"/>' + '<param name="wmode" value="transparent"/>' + '<param name="flashvars" value="' + flashvars + '"/>' + '<div id="' + _globalConfig.swfObjectId + '_fallbackContent"> </div>' + "</object>";
flashBridge = tmpDiv.firstChild;
tmpDiv = null;
_unwrap(flashBridge).ZeroClipboard = ZeroClipboard;
container.replaceChild(flashBridge, divToBeReplaced);
_watchForSwfFallbackContent();
}
if (!flashBridge) {
flashBridge = _document[_globalConfig.swfObjectId];
if (flashBridge && (len = flashBridge.length)) {
flashBridge = flashBridge[len - 1];
}
if (!flashBridge && container) {
flashBridge = container.firstChild;
}
}
_flashState.bridge = flashBridge || null;
return flashBridge;
} | javascript | {
"resource": ""
} | |
q26040 | train | function() {
var flashBridge = _flashState.bridge;
if (flashBridge) {
var htmlBridge = _getHtmlBridge(flashBridge);
if (htmlBridge) {
if (_flashState.pluginType === "activex" && "readyState" in flashBridge) {
flashBridge.style.display = "none";
(function removeSwfFromIE() {
if (flashBridge.readyState === 4) {
for (var prop in flashBridge) {
if (typeof flashBridge[prop] === "function") {
flashBridge[prop] = null;
}
}
if (flashBridge.parentNode) {
flashBridge.parentNode.removeChild(flashBridge);
}
if (htmlBridge.parentNode) {
htmlBridge.parentNode.removeChild(htmlBridge);
}
} else {
_setTimeout(removeSwfFromIE, 10);
}
})();
} else {
if (flashBridge.parentNode) {
flashBridge.parentNode.removeChild(flashBridge);
}
if (htmlBridge.parentNode) {
htmlBridge.parentNode.removeChild(htmlBridge);
}
}
}
_clearTimeoutsAndPolling();
_flashState.ready = null;
_flashState.bridge = null;
_flashState.deactivated = null;
_flashState.insecure = null;
_zcSwfVersion = undefined;
}
} | javascript | {
"resource": ""
} | |
q26041 | train | function(clipData) {
var newClipData = {}, formatMap = {};
if (!(typeof clipData === "object" && clipData)) {
return;
}
for (var dataFormat in clipData) {
if (dataFormat && _hasOwn.call(clipData, dataFormat) && typeof clipData[dataFormat] === "string" && clipData[dataFormat]) {
switch (dataFormat.toLowerCase()) {
case "text/plain":
case "text":
case "air:text":
case "flash:text":
newClipData.text = clipData[dataFormat];
formatMap.text = dataFormat;
break;
case "text/html":
case "html":
case "air:html":
case "flash:html":
newClipData.html = clipData[dataFormat];
formatMap.html = dataFormat;
break;
case "application/rtf":
case "text/rtf":
case "rtf":
case "richtext":
case "air:rtf":
case "flash:rtf":
newClipData.rtf = clipData[dataFormat];
formatMap.rtf = dataFormat;
break;
default:
break;
}
}
}
return {
data: newClipData,
formatMap: formatMap
};
} | javascript | {
"resource": ""
} | |
q26042 | train | function(options) {
var i, len, domain, domains, str = "", trustedOriginsExpanded = [];
if (options.trustedDomains) {
if (typeof options.trustedDomains === "string") {
domains = [ options.trustedDomains ];
} else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) {
domains = options.trustedDomains;
}
}
if (domains && domains.length) {
for (i = 0, len = domains.length; i < len; i++) {
if (_hasOwn.call(domains, i) && domains[i] && typeof domains[i] === "string") {
domain = _extractDomain(domains[i]);
if (!domain) {
continue;
}
if (domain === "*") {
trustedOriginsExpanded.length = 0;
trustedOriginsExpanded.push(domain);
break;
}
trustedOriginsExpanded.push.apply(trustedOriginsExpanded, [ domain, "//" + domain, _window.location.protocol + "//" + domain ]);
}
}
}
if (trustedOriginsExpanded.length) {
str += "trustedOrigins=" + _encodeURIComponent(trustedOriginsExpanded.join(","));
}
if (options.forceEnhancedClipboard === true) {
str += (str ? "&" : "") + "forceEnhancedClipboard=true";
}
if (typeof options.swfObjectId === "string" && options.swfObjectId) {
str += (str ? "&" : "") + "swfObjectId=" + _encodeURIComponent(options.swfObjectId);
}
if (typeof options.jsVersion === "string" && options.jsVersion) {
str += (str ? "&" : "") + "jsVersion=" + _encodeURIComponent(options.jsVersion);
}
return str;
} | javascript | {
"resource": ""
} | |
q26043 | train | function(element, value) {
var c, cl, className, classNames = [];
if (typeof value === "string" && value) {
classNames = value.split(/\s+/);
}
if (element && element.nodeType === 1 && classNames.length > 0) {
className = (" " + (element.className || "") + " ").replace(/[\t\r\n\f]/g, " ");
for (c = 0, cl = classNames.length; c < cl; c++) {
if (className.indexOf(" " + classNames[c] + " ") === -1) {
className += classNames[c] + " ";
}
}
className = className.replace(/^\s+|\s+$/g, "");
if (className !== element.className) {
element.className = className;
}
}
return element;
} | javascript | {
"resource": ""
} | |
q26044 | train | function(el) {
var pos = {
left: 0,
top: 0,
width: 0,
height: 0
};
if (el.getBoundingClientRect) {
var elRect = el.getBoundingClientRect();
var pageXOffset = _window.pageXOffset;
var pageYOffset = _window.pageYOffset;
var leftBorderWidth = _document.documentElement.clientLeft || 0;
var topBorderWidth = _document.documentElement.clientTop || 0;
var leftBodyOffset = 0;
var topBodyOffset = 0;
if (_getStyle(_document.body, "position") === "relative") {
var bodyRect = _document.body.getBoundingClientRect();
var htmlRect = _document.documentElement.getBoundingClientRect();
leftBodyOffset = bodyRect.left - htmlRect.left || 0;
topBodyOffset = bodyRect.top - htmlRect.top || 0;
}
pos.left = elRect.left + pageXOffset - leftBorderWidth - leftBodyOffset;
pos.top = elRect.top + pageYOffset - topBorderWidth - topBodyOffset;
pos.width = "width" in elRect ? elRect.width : elRect.right - elRect.left;
pos.height = "height" in elRect ? elRect.height : elRect.bottom - elRect.top;
}
return pos;
} | javascript | {
"resource": ""
} | |
q26045 | train | function() {
var htmlBridge;
if (_currentElement && (htmlBridge = _getHtmlBridge(_flashState.bridge))) {
var pos = _getElementPosition(_currentElement);
_extend(htmlBridge.style, {
width: pos.width + "px",
height: pos.height + "px",
top: pos.top + "px",
left: pos.left + "px",
zIndex: "" + _getSafeZIndex(_globalConfig.zIndex)
});
}
} | javascript | {
"resource": ""
} | |
q26046 | train | function(enabled) {
if (_flashState.ready === true) {
if (_flashState.bridge && typeof _flashState.bridge.setHandCursor === "function") {
_flashState.bridge.setHandCursor(enabled);
} else {
_flashState.ready = false;
}
}
} | javascript | {
"resource": ""
} | |
q26047 | train | function(val) {
if (/^(?:auto|inherit)$/.test(val)) {
return val;
}
var zIndex;
if (typeof val === "number" && !_isNaN(val)) {
zIndex = val;
} else if (typeof val === "string") {
zIndex = _getSafeZIndex(_parseInt(val, 10));
}
return typeof zIndex === "number" ? zIndex : "auto";
} | javascript | {
"resource": ""
} | |
q26048 | train | function(content) {
var replaceRegex = /(\r\n|\r|\n)/g;
if (typeof content === "string" && _globalConfig.fixLineEndings === true) {
if (_isWindows()) {
if (/((^|[^\r])\n|\r([^\n]|$))/.test(content)) {
content = content.replace(replaceRegex, "\r\n");
}
} else if (/\r/.test(content)) {
content = content.replace(replaceRegex, "\n");
}
}
return content;
} | javascript | {
"resource": ""
} | |
q26049 | train | function(doNotReassessFlashSupport) {
var effectiveScriptOrigin, frame, frameError, previousState = _flashState.sandboxed, isSandboxed = null;
doNotReassessFlashSupport = doNotReassessFlashSupport === true;
if (_pageIsFramed === false) {
isSandboxed = false;
} else {
try {
frame = window.frameElement || null;
} catch (e) {
frameError = {
name: e.name,
message: e.message
};
}
if (frame && frame.nodeType === 1 && frame.nodeName === "IFRAME") {
try {
isSandboxed = frame.hasAttribute("sandbox");
} catch (e) {
isSandboxed = null;
}
} else {
try {
effectiveScriptOrigin = document.domain || null;
} catch (e) {
effectiveScriptOrigin = null;
}
if (effectiveScriptOrigin === null || frameError && frameError.name === "SecurityError" && /(^|[\s\(\[@])sandbox(es|ed|ing|[\s\.,!\)\]@]|$)/.test(frameError.message.toLowerCase())) {
isSandboxed = true;
}
}
}
_flashState.sandboxed = isSandboxed;
if (previousState !== isSandboxed && !doNotReassessFlashSupport) {
_detectFlashSupport(_ActiveXObject);
}
return isSandboxed;
} | javascript | {
"resource": ""
} | |
q26050 | parseFlashVersion | train | function parseFlashVersion(desc) {
var matches = desc.match(/[\d]+/g);
matches.length = 3;
return matches.join(".");
} | javascript | {
"resource": ""
} |
q26051 | train | function(elements) {
var meta, client = this;
client.id = "" + _clientIdCounter++;
meta = {
instance: client,
elements: [],
handlers: {},
coreWildcardHandler: function(event) {
return client.emit(event);
}
};
_clientMeta[client.id] = meta;
if (elements) {
client.clip(elements);
}
ZeroClipboard.on("*", meta.coreWildcardHandler);
ZeroClipboard.on("destroy", function() {
client.destroy();
});
ZeroClipboard.create();
} | javascript | {
"resource": ""
} | |
q26052 | train | function(eventType, listener) {
var i, len, events, added = {}, client = this, meta = _clientMeta[client.id], handlers = meta && meta.handlers;
if (!meta) {
throw new Error("Attempted to add new listener(s) to a destroyed ZeroClipboard client instance");
}
if (typeof eventType === "string" && eventType) {
events = eventType.toLowerCase().split(/\s+/);
} else if (typeof eventType === "object" && eventType && !("length" in eventType) && typeof listener === "undefined") {
_keys(eventType).forEach(function(key) {
var listener = eventType[key];
if (typeof listener === "function") {
client.on(key, listener);
}
});
}
if (events && events.length && listener) {
for (i = 0, len = events.length; i < len; i++) {
eventType = events[i].replace(/^on/, "");
added[eventType] = true;
if (!handlers[eventType]) {
handlers[eventType] = [];
}
handlers[eventType].push(listener);
}
if (added.ready && _flashState.ready) {
this.emit({
type: "ready",
client: this
});
}
if (added.error) {
for (i = 0, len = _flashStateErrorNames.length; i < len; i++) {
if (_flashState[_flashStateErrorNames[i].replace(/^flash-/, "")]) {
this.emit({
type: "error",
name: _flashStateErrorNames[i],
client: this
});
break;
}
}
if (_zcSwfVersion !== undefined && ZeroClipboard.version !== _zcSwfVersion) {
this.emit({
type: "error",
name: "version-mismatch",
jsVersion: ZeroClipboard.version,
swfVersion: _zcSwfVersion
});
}
}
}
return client;
} | javascript | {
"resource": ""
} | |
q26053 | train | function(eventType, listener) {
var i, len, foundIndex, events, perEventHandlers, client = this, meta = _clientMeta[client.id], handlers = meta && meta.handlers;
if (!handlers) {
return client;
}
if (arguments.length === 0) {
events = _keys(handlers);
} else if (typeof eventType === "string" && eventType) {
events = eventType.split(/\s+/);
} else if (typeof eventType === "object" && eventType && !("length" in eventType) && typeof listener === "undefined") {
_keys(eventType).forEach(function(key) {
var listener = eventType[key];
if (typeof listener === "function") {
client.off(key, listener);
}
});
}
if (events && events.length) {
for (i = 0, len = events.length; i < len; i++) {
eventType = events[i].toLowerCase().replace(/^on/, "");
perEventHandlers = handlers[eventType];
if (perEventHandlers && perEventHandlers.length) {
if (listener) {
foundIndex = perEventHandlers.indexOf(listener);
while (foundIndex !== -1) {
perEventHandlers.splice(foundIndex, 1);
foundIndex = perEventHandlers.indexOf(listener, foundIndex);
}
} else {
perEventHandlers.length = 0;
}
}
}
}
return client;
} | javascript | {
"resource": ""
} | |
q26054 | train | function(eventType) {
var copy = null, handlers = _clientMeta[this.id] && _clientMeta[this.id].handlers;
if (handlers) {
if (typeof eventType === "string" && eventType) {
copy = handlers[eventType] ? handlers[eventType].slice(0) : [];
} else {
copy = _deepCopy(handlers);
}
}
return copy;
} | javascript | {
"resource": ""
} | |
q26055 | train | function(event) {
var eventCopy, client = this;
if (_clientShouldEmit.call(client, event)) {
if (typeof event === "object" && event && typeof event.type === "string" && event.type) {
event = _extend({}, event);
}
eventCopy = _extend({}, _createEvent(event), {
client: client
});
_clientDispatchCallbacks.call(client, eventCopy);
}
return client;
} | javascript | {
"resource": ""
} | |
q26056 | train | function(elements) {
if (!_clientMeta[this.id]) {
throw new Error("Attempted to clip element(s) to a destroyed ZeroClipboard client instance");
}
elements = _prepClip(elements);
for (var i = 0; i < elements.length; i++) {
if (_hasOwn.call(elements, i) && elements[i] && elements[i].nodeType === 1) {
if (!elements[i].zcClippingId) {
elements[i].zcClippingId = "zcClippingId_" + _elementIdCounter++;
_elementMeta[elements[i].zcClippingId] = [ this.id ];
if (_globalConfig.autoActivate === true) {
_addMouseHandlers(elements[i]);
}
} else if (_elementMeta[elements[i].zcClippingId].indexOf(this.id) === -1) {
_elementMeta[elements[i].zcClippingId].push(this.id);
}
var clippedElements = _clientMeta[this.id] && _clientMeta[this.id].elements;
if (clippedElements.indexOf(elements[i]) === -1) {
clippedElements.push(elements[i]);
}
}
}
return this;
} | javascript | {
"resource": ""
} | |
q26057 | train | function(elements) {
var meta = _clientMeta[this.id];
if (!meta) {
return this;
}
var clippedElements = meta.elements;
var arrayIndex;
if (typeof elements === "undefined") {
elements = clippedElements.slice(0);
} else {
elements = _prepClip(elements);
}
for (var i = elements.length; i--; ) {
if (_hasOwn.call(elements, i) && elements[i] && elements[i].nodeType === 1) {
arrayIndex = 0;
while ((arrayIndex = clippedElements.indexOf(elements[i], arrayIndex)) !== -1) {
clippedElements.splice(arrayIndex, 1);
}
var clientIds = _elementMeta[elements[i].zcClippingId];
if (clientIds) {
arrayIndex = 0;
while ((arrayIndex = clientIds.indexOf(this.id, arrayIndex)) !== -1) {
clientIds.splice(arrayIndex, 1);
}
if (clientIds.length === 0) {
if (_globalConfig.autoActivate === true) {
_removeMouseHandlers(elements[i]);
}
delete elements[i].zcClippingId;
}
}
}
}
return this;
} | javascript | {
"resource": ""
} | |
q26058 | train | function() {
var meta = _clientMeta[this.id];
if (!meta) {
return;
}
this.unclip();
this.off();
ZeroClipboard.off("*", meta.coreWildcardHandler);
delete _clientMeta[this.id];
} | javascript | {
"resource": ""
} | |
q26059 | train | function(event) {
var meta = _clientMeta[this.id];
if (!(typeof event === "object" && event && event.type && meta)) {
return;
}
var async = _shouldPerformAsync(event);
var wildcardTypeHandlers = meta && meta.handlers["*"] || [];
var specificTypeHandlers = meta && meta.handlers[event.type] || [];
var handlers = wildcardTypeHandlers.concat(specificTypeHandlers);
if (handlers && handlers.length) {
var i, len, func, context, eventCopy, originalContext = this;
for (i = 0, len = handlers.length; i < len; i++) {
func = handlers[i];
context = originalContext;
if (typeof func === "string" && typeof _window[func] === "function") {
func = _window[func];
}
if (typeof func === "object" && func && typeof func.handleEvent === "function") {
context = func;
func = func.handleEvent;
}
if (typeof func === "function") {
eventCopy = _extend({}, event);
_dispatchCallback(func, context, [ eventCopy ], async);
}
}
}
} | javascript | {
"resource": ""
} | |
q26060 | train | function(element) {
if (!(element && element.nodeType === 1)) {
return;
}
var _suppressMouseEvents = function(event) {
if (!(event || (event = _window.event))) {
return;
}
if (event._source !== "js") {
event.stopImmediatePropagation();
event.preventDefault();
}
delete event._source;
};
var _elementMouseOver = function(event) {
if (!(event || (event = _window.event))) {
return;
}
_suppressMouseEvents(event);
ZeroClipboard.focus(element);
};
element.addEventListener("mouseover", _elementMouseOver, false);
element.addEventListener("mouseout", _suppressMouseEvents, false);
element.addEventListener("mouseenter", _suppressMouseEvents, false);
element.addEventListener("mouseleave", _suppressMouseEvents, false);
element.addEventListener("mousemove", _suppressMouseEvents, false);
_mouseHandlers[element.zcClippingId] = {
mouseover: _elementMouseOver,
mouseout: _suppressMouseEvents,
mouseenter: _suppressMouseEvents,
mouseleave: _suppressMouseEvents,
mousemove: _suppressMouseEvents
};
} | javascript | {
"resource": ""
} | |
q26061 | train | function(element) {
if (!(element && element.nodeType === 1)) {
return;
}
var mouseHandlers = _mouseHandlers[element.zcClippingId];
if (!(typeof mouseHandlers === "object" && mouseHandlers)) {
return;
}
var key, val, mouseEvents = [ "move", "leave", "enter", "out", "over" ];
for (var i = 0, len = mouseEvents.length; i < len; i++) {
key = "mouse" + mouseEvents[i];
val = mouseHandlers[key];
if (typeof val === "function") {
element.removeEventListener(key, val, false);
}
}
delete _mouseHandlers[element.zcClippingId];
} | javascript | {
"resource": ""
} | |
q26062 | decode | train | function decode(data) {
var languageCodeLength = (data[0] & 0x3F), // 6 LSBs
languageCode = data.slice(1, 1 + languageCodeLength),
utf16 = (data[0] & 0x80) !== 0; // assuming UTF-16BE
// TODO need to deal with UTF in the future
// console.log("lang " + languageCode + (utf16 ? " utf16" : " utf8"));
return util.bytesToString(data.slice(languageCodeLength + 1));
} | javascript | {
"resource": ""
} |
q26063 | encode | train | function encode(text, lang, encoding) {
// ISO/IANA language code, but we're not enforcing
if (!lang) { lang = 'en'; }
var encoded = util.stringToBytes(lang + text);
encoded.unshift(lang.length);
return encoded;
} | javascript | {
"resource": ""
} |
q26064 | train | function (text, languageCode, id) {
var payload = textHelper.encodePayload(text, languageCode);
if (!id) { id = []; }
return ndef.record(ndef.TNF_WELL_KNOWN, ndef.RTD_TEXT, id, payload);
} | javascript | {
"resource": ""
} | |
q26065 | train | function (uri, id) {
var payload = uriHelper.encodePayload(uri);
if (!id) { id = []; }
return ndef.record(ndef.TNF_WELL_KNOWN, ndef.RTD_URI, id, payload);
} | javascript | {
"resource": ""
} | |
q26066 | train | function (uri, payload, id) {
if (!id) { id = []; }
if (!payload) { payload = []; }
return ndef.record(ndef.TNF_ABSOLUTE_URI, uri, id, payload);
} | javascript | {
"resource": ""
} | |
q26067 | train | function (mimeType, payload, id) {
if (!id) { id = []; }
return ndef.record(ndef.TNF_MIME_MEDIA, mimeType, id, payload);
} | javascript | {
"resource": ""
} | |
q26068 | train | function (ndefRecords, id) {
var payload = [];
if (!id) { id = []; }
if (ndefRecords)
{
// make sure we have an array of something like NDEF records before encoding
if (ndefRecords[0] instanceof Object && ndefRecords[0].hasOwnProperty('tnf')) {
payload = ndef.encodeMessage(ndefRecords);
} else {
// assume the caller has already encoded the NDEF records into a byte array
payload = ndefRecords;
}
} else {
console.log("WARNING: Expecting an array of NDEF records");
}
return ndef.record(ndef.TNF_WELL_KNOWN, ndef.RTD_SMART_POSTER, id, payload);
} | javascript | {
"resource": ""
} | |
q26069 | train | function (ndefRecords) {
var encoded = [],
tnf_byte,
record_type,
payload_length,
id_length,
i,
mb, me, // messageBegin, messageEnd
cf = false, // chunkFlag TODO implement
sr, // boolean shortRecord
il; // boolean idLengthFieldIsPresent
for(i = 0; i < ndefRecords.length; i++) {
mb = (i === 0);
me = (i === (ndefRecords.length - 1));
sr = (ndefRecords[i].payload.length < 0xFF);
il = (ndefRecords[i].id.length > 0);
tnf_byte = ndef.encodeTnf(mb, me, cf, sr, il, ndefRecords[i].tnf);
encoded.push(tnf_byte);
// type is stored as String, converting to bytes for storage
record_type = util.stringToBytes(ndefRecords[i].type);
encoded.push(record_type.length);
if (sr) {
payload_length = ndefRecords[i].payload.length;
encoded.push(payload_length);
} else {
payload_length = ndefRecords[i].payload.length;
// 4 bytes
encoded.push((payload_length >> 24));
encoded.push((payload_length >> 16));
encoded.push((payload_length >> 8));
encoded.push((payload_length & 0xFF));
}
if (il) {
id_length = ndefRecords[i].id.length;
encoded.push(id_length);
}
encoded = encoded.concat(record_type);
if (il) {
encoded = encoded.concat(ndefRecords[i].id);
}
encoded = encoded.concat(ndefRecords[i].payload);
}
return encoded;
} | javascript | {
"resource": ""
} | |
q26070 | train | function (ndefBytes) {
// ndefBytes can be an array of bytes e.g. [0x03, 0x31, 0xd1] or a Buffer
var bytes;
// if (ndefBytes instanceof Buffer) {
// // get an array of bytes
// bytes = Array.prototype.slice.call(ndefBytes, 0);
// } else if (ndefBytes instanceof Array) {
if (ndefBytes instanceof Array) {
bytes = ndefBytes.slice(0);
} else {
throw new Error('ndef.decodeMessage requires a Buffer or an Array of bytes');
}
var bytes = bytes.slice(0), // clone since parsing is destructive
ndef_message = [],
tnf_byte,
header,
type_length = 0,
payload_length = 0,
id_length = 0,
record_type = [],
id = [],
payload = [];
while(bytes.length) {
tnf_byte = bytes.shift();
header = ndef.decodeTnf(tnf_byte);
type_length = bytes.shift();
if (header.sr) {
payload_length = bytes.shift();
} else {
// next 4 bytes are length
payload_length = ((0xFF & bytes.shift()) << 24) |
((0xFF & bytes.shift()) << 16) |
((0xFF & bytes.shift()) << 8) |
(0xFF & bytes.shift());
}
id_length = header.il ? bytes.shift() : 0;
record_type = bytes.splice(0, type_length);
id = bytes.splice(0, id_length);
payload = bytes.splice(0, payload_length);
ndef_message.push(
ndef.record(header.tnf, record_type, id, payload)
);
if (header.me) break; // last message
}
return ndef_message;
} | javascript | {
"resource": ""
} | |
q26071 | train | function (tnf_byte) {
return {
mb: (tnf_byte & 0x80) !== 0,
me: (tnf_byte & 0x40) !== 0,
cf: (tnf_byte & 0x20) !== 0,
sr: (tnf_byte & 0x10) !== 0,
il: (tnf_byte & 0x8) !== 0,
tnf: (tnf_byte & 0x7)
};
} | javascript | {
"resource": ""
} | |
q26072 | train | function (mb, me, cf, sr, il, tnf) {
var value = tnf;
if (mb) {
value = value | 0x80;
}
if (me) {
value = value | 0x40;
}
// note if cf: me, mb, li must be false and tnf must be 0x6
if (cf) {
value = value | 0x20;
}
if (sr) {
value = value | 0x10;
}
if (il) {
value = value | 0x8;
}
return value;
} | javascript | {
"resource": ""
} | |
q26073 | s | train | function s(bytes) {
if (typeof(bytes) === 'string') {
return bytes;
}
return bytes.reduce(function (acc, byte) {
return acc + String.fromCharCode(byte);
}, '')
// return new Buffer(bytes).toString();
} | javascript | {
"resource": ""
} |
q26074 | decode | train | function decode(data) {
var prefix = protocols[data[0]];
if (!prefix) { // 36 to 255 should be ""
prefix = "";
}
return prefix + util.bytesToString(data.slice(1));
} | javascript | {
"resource": ""
} |
q26075 | encode | train | function encode(uri) {
var prefix,
protocolCode,
encoded;
// check each protocol, unless we've found a match
// "urn:" is the one exception where we need to keep checking
// slice so we don't check ""
protocols.slice(1).forEach(function(protocol) {
if ((!prefix || prefix === "urn:") && uri.indexOf(protocol) === 0) {
prefix = protocol;
}
});
if (!prefix) {
prefix = "";
}
encoded = util.stringToBytes(uri.slice(prefix.length));
protocolCode = protocols.indexOf(prefix);
// prepend protocol code
encoded.unshift(protocolCode);
return encoded;
} | javascript | {
"resource": ""
} |
q26076 | bytesToHexString | train | function bytesToHexString(bytes) {
var dec, hexstring, bytesAsHexString = "";
for (var i = 0; i < bytes.length; i++) {
if (bytes[i] >= 0) {
dec = bytes[i];
} else {
dec = 256 + bytes[i];
}
hexstring = dec.toString(16);
// zero padding
if (hexstring.length == 1) {
hexstring = "0" + hexstring;
}
bytesAsHexString += hexstring;
}
return bytesAsHexString;
} | javascript | {
"resource": ""
} |
q26077 | toHex | train | function toHex(i) {
var hex;
if (i < 0) {
i += 256;
}
hex = i.toString(16);
// zero padding
if (hex.length == 1) {
hex = "0" + hex;
}
return hex;
} | javascript | {
"resource": ""
} |
q26078 | Authentication | train | function Authentication(auth0, options) {
// If we have two arguments, the first one is a WebAuth instance, so we assign that
// if not, it's an options object and then we should use that as options instead
// this is here because we don't want to break people coming from v8
if (arguments.length === 2) {
this.auth0 = auth0;
} else {
options = auth0;
}
/* eslint-disable */
assert.check(
options,
{ type: 'object', message: 'options parameter is not valid' },
{
domain: { type: 'string', message: 'domain option is required' },
clientID: { type: 'string', message: 'clientID option is required' },
responseType: { optional: true, type: 'string', message: 'responseType is not valid' },
responseMode: { optional: true, type: 'string', message: 'responseMode is not valid' },
redirectUri: { optional: true, type: 'string', message: 'redirectUri is not valid' },
scope: { optional: true, type: 'string', message: 'scope is not valid' },
audience: { optional: true, type: 'string', message: 'audience is not valid' },
_disableDeprecationWarnings: {
optional: true,
type: 'boolean',
message: '_disableDeprecationWarnings option is not valid'
},
_sendTelemetry: {
optional: true,
type: 'boolean',
message: '_sendTelemetry option is not valid'
},
_telemetryInfo: {
optional: true,
type: 'object',
message: '_telemetryInfo option is not valid'
}
}
);
/* eslint-enable */
this.baseOptions = options;
this.baseOptions._sendTelemetry =
this.baseOptions._sendTelemetry === false ? this.baseOptions._sendTelemetry : true;
this.baseOptions.rootUrl = 'https://' + this.baseOptions.domain;
this.request = new RequestBuilder(this.baseOptions);
this.passwordless = new PasswordlessAuthentication(this.request, this.baseOptions);
this.dbConnection = new DBConnection(this.request, this.baseOptions);
this.warn = new Warn({
disableWarnings: !!options._disableDeprecationWarnings
});
this.ssodataStorage = new SSODataStorage(this.baseOptions);
} | javascript | {
"resource": ""
} |
q26079 | train | function() {
var applyTouchMove = function(difference_x, difference_y) {
$this.scrollTop($this.scrollTop() - difference_y);
$this.scrollLeft($this.scrollLeft() - difference_x);
// update bar position
updateBarSizeAndPosition();
};
var start_coords = {},
start_time = 0,
speed = {},
breaking_process = null;
$this.bind("touchstart.perfect-scroll", function(e) {
var touch = e.originalEvent.targetTouches[0];
start_coords.pageX = touch.pageX;
start_coords.pageY = touch.pageY;
start_time = (new Date()).getTime();
if (breaking_process !== null) {
clearInterval(breaking_process);
}
});
$this.bind("touchmove.perfect-scroll", function(e) {
var touch = e.originalEvent.targetTouches[0];
var current_coords = {};
current_coords.pageX = touch.pageX;
current_coords.pageY = touch.pageY;
var difference_x = current_coords.pageX - start_coords.pageX,
difference_y = current_coords.pageY - start_coords.pageY;
applyTouchMove(difference_x, difference_y);
start_coords = current_coords;
var current_time = (new Date()).getTime();
speed.x = difference_x / (current_time - start_time);
speed.y = difference_y / (current_time - start_time);
start_time = current_time;
e.preventDefault();
});
$this.bind("touchend.perfect-scroll", function(e) {
breaking_process = setInterval(function() {
if(Math.abs(speed.x) < 0.01 && Math.abs(speed.y) < 0.01) {
clearInterval(breaking_process);
return;
}
applyTouchMove(speed.x * 30, speed.y * 30);
speed.x *= 0.8;
speed.y *= 0.8;
}, 10);
});
} | javascript | {
"resource": ""
} | |
q26080 | train | function( obj1, obj2 ) {
var newObj = {};
if ( obj1 ) {
this.inheritAttrs( newObj, this.cloneObj( obj1 ) );
}
if ( obj2 ) {
this.inheritAttrs( newObj, obj2 );
}
return newObj;
} | javascript | {
"resource": ""
} | |
q26081 | train | function() {
if ( $ ) {
Array.prototype.unshift.apply( arguments, [true, {}] );
return $.extend.apply( $, arguments );
}
else {
return UTIL.createMerge.apply( this, arguments );
}
} | javascript | {
"resource": ""
} | |
q26082 | train | function (jsonConfig, treeId ) {
/**
* @param {object} jsonConfig
* @param {number} treeId
* @returns {Tree}
*/
this.reset = function( jsonConfig, treeId ) {
this.initJsonConfig = jsonConfig;
this.initTreeId = treeId;
this.id = treeId;
this.CONFIG = UTIL.extend( Tree.CONFIG, jsonConfig.chart );
this.drawArea = UTIL.findEl( this.CONFIG.container, true );
if ( !this.drawArea ) {
throw new Error( 'Failed to find element by selector "'+this.CONFIG.container+'"' );
}
UTIL.addClass( this.drawArea, 'Treant' );
// kill of any child elements that may be there
this.drawArea.innerHTML = '';
this.imageLoader = new ImageLoader();
this.nodeDB = new NodeDB( jsonConfig.nodeStructure, this );
// key store for storing reference to node connectors,
// key = nodeId where the connector ends
this.connectionStore = {};
this.loaded = false;
this._R = new Raphael( this.drawArea, 100, 100 );
return this;
};
/**
* @returns {Tree}
*/
this.reload = function() {
this.reset( this.initJsonConfig, this.initTreeId ).redraw();
return this;
};
this.reset( jsonConfig, treeId );
} | javascript | {
"resource": ""
} | |
q26083 | train | function( node, level ) {
node.leftNeighborId = this.lastNodeOnLevel[level];
if ( node.leftNeighborId ) {
node.leftNeighbor().rightNeighborId = node.id;
}
this.lastNodeOnLevel[level] = node.id;
return this;
} | javascript | {
"resource": ""
} | |
q26084 | train | function( nodeStructure, id, parentId, tree, stackParentId ) {
this.reset( nodeStructure, id, parentId, tree, stackParentId );
} | javascript | {
"resource": ""
} | |
q26085 | train | function() {
var orientation = this.getTreeConfig().rootOrientation;
if ( this.pseudo ) {
// prevents separating the subtrees
return ( -this.getTreeConfig().subTeeSeparation );
}
if ( orientation === 'NORTH' || orientation === 'SOUTH' ) {
return this.width;
}
else if ( orientation === 'WEST' || orientation === 'EAST' ) {
return this.height;
}
} | javascript | {
"resource": ""
} | |
q26086 | train | function(startPoint) {
var orient = this.Tree().CONFIG.rootOrientation, point = {};
if ( this.stackParentId ) { // return different end point if node is a stacked child
if ( orient === 'NORTH' || orient === 'SOUTH' ) {
orient = 'WEST';
}
else if ( orient === 'EAST' || orient === 'WEST' ) {
orient = 'NORTH';
}
}
// if pseudo, a virtual center is used
if ( orient === 'NORTH' ) {
point.x = (this.pseudo) ? this.X - this.Tree().CONFIG.subTeeSeparation/2 : this.X + this.width/2;
point.y = (startPoint) ? this.Y + this.height : this.Y;
}
else if (orient === 'SOUTH') {
point.x = (this.pseudo) ? this.X - this.Tree().CONFIG.subTeeSeparation/2 : this.X + this.width/2;
point.y = (startPoint) ? this.Y : this.Y + this.height;
}
else if (orient === 'EAST') {
point.x = (startPoint) ? this.X : this.X + this.width;
point.y = (this.pseudo) ? this.Y - this.Tree().CONFIG.subTeeSeparation/2 : this.Y + this.height/2;
}
else if (orient === 'WEST') {
point.x = (startPoint) ? this.X + this.width : this.X;
point.y = (this.pseudo) ? this.Y - this.Tree().CONFIG.subTeeSeparation/2 : this.Y + this.height/2;
}
return point;
} | javascript | {
"resource": ""
} | |
q26087 | train | function( jsonConfig, callback, jQuery ) {
if ( jsonConfig instanceof Array ) {
jsonConfig = JSONconfig.make( jsonConfig );
}
// optional
if ( jQuery ) {
$ = jQuery;
}
this.tree = TreeStore.createTree( jsonConfig );
this.tree.positionTree( callback );
} | javascript | {
"resource": ""
} | |
q26088 | uniq | train | function uniq(el, arr){
arr = arr && arr.join ? arr : [];
if (!el) return arr.join(' > ');
if (9 == el.nodeType) return arr.join(' > ');
if (1 != el.nodeType) return arr.join(' > ');
arr.unshift(selector(el));
if (el.id) return arr.join(' > ');
return uniq(el.parentNode, arr);
} | javascript | {
"resource": ""
} |
q26089 | selector | train | function selector(el){
var classname = trim(el.className.baseVal ? el.className.baseVal : el.className);
var i = el.parentNode && 9 == el.parentNode.nodeType ? -1 : index(el);
return el.tagName.toLowerCase()
+ (el.id ? '#' + el.id : '')
+ (classname ? classname.replace(/^| +/g, '.') : '')
+ (~i ? ':nth-child(' + (i + 1) + ')' : '');
} | javascript | {
"resource": ""
} |
q26090 | _clearGeneratorConfig | train | function _clearGeneratorConfig(app, generator) {
if (generator === '*') {
globalConfig.removeAll();
} else {
globalConfig.remove(generator);
}
console.log('Global config has been successfully cleared');
app.navigate('home');
} | javascript | {
"resource": ""
} |
q26091 | parserFor | train | function parserFor(rules) {
// Sorts rules in order of increasing order, then
// ascending rule name in case of ties.
let ruleList = Object.keys(rules);
/* istanbul ignore next */
if (process.env.NODE_ENV !== 'production') {
ruleList.forEach(function(type) {
let order = rules[type].order;
if (
process.env.NODE_ENV !== 'production' &&
(typeof order !== 'number' || !isFinite(order))
) {
console.warn(
'markdown-to-jsx: Invalid order for rule `' + type + '`: ' + order
);
}
});
}
ruleList.sort(function(typeA, typeB) {
let orderA = rules[typeA].order;
let orderB = rules[typeB].order;
// First sort based on increasing order
if (orderA !== orderB) {
return orderA - orderB;
// Then based on increasing unicode lexicographic ordering
} else if (typeA < typeB) {
return -1;
}
return 1;
});
function nestedParse(source, state) {
let result = [];
// We store the previous capture so that match functions can
// use some limited amount of lookbehind. Lists use this to
// ensure they don't match arbitrary '- ' or '* ' in inline
// text (see the list rule for more information).
let prevCapture = '';
while (source) {
let i = 0;
while (i < ruleList.length) {
const ruleType = ruleList[i];
const rule = rules[ruleType];
const capture = rule.match(source, state, prevCapture);
if (capture) {
const currCaptureString = capture[0];
source = source.substring(currCaptureString.length);
const parsed = rule.parse(capture, nestedParse, state);
// We also let rules override the default type of
// their parsed node if they would like to, so that
// there can be a single output function for all links,
// even if there are several rules to parse them.
if (parsed.type == null) {
parsed.type = ruleType;
}
result.push(parsed);
prevCapture = currCaptureString;
break;
}
i++;
}
}
return result;
}
return function outerParse(source, state) {
return nestedParse(normalizeWhitespace(source), state);
};
} | javascript | {
"resource": ""
} |
q26092 | inlineRegex | train | function inlineRegex(regex) {
return function match(source, state) {
if (state.inline) {
return regex.exec(source);
} else {
return null;
}
};
} | javascript | {
"resource": ""
} |
q26093 | parseSimpleInline | train | function parseSimpleInline(parse, content, state) {
const isCurrentlyInline = state.inline || false;
const isCurrentlySimple = state.simple || false;
state.inline = false;
state.simple = true;
const result = parse(content, state);
state.inline = isCurrentlyInline;
state.simple = isCurrentlySimple;
return result;
} | javascript | {
"resource": ""
} |
q26094 | train | function(){
res.type('.html');
res.send(_render(tpl, css, {
code: httpStatusCode,
title: pageData.title,
message: pageData.message,
footer: opt.footer
}))
} | javascript | {
"resource": ""
} | |
q26095 | renderTemplate | train | function renderTemplate(template, css, data={}){
// assign css
data.inlinecss = css;
// render template - use custom escape function to handle linebreaks!
return _ejs.render(template, data, {
escape: function(text){
if (!text){
return '';
}
// apply generic escape function
text = _ejs.escapeXML(text);
// linebreaks
text = text.replace(/\n/g, '<br />');
return text;
}
});
} | javascript | {
"resource": ""
} |
q26096 | readJSONFile | train | async function readJSONFile(filename){
// load file
let raw = await _fs.readFile(filename, 'utf8');
// strip single line js comments
raw = raw.replace(/^\s*\/\/.*$/gm, '');
// parse text
return JSON.parse(raw);
} | javascript | {
"resource": ""
} |
q26097 | log | train | function log(key, value, message, errorLevel = 1) {
const error = {};
// looks for the original item that caused the error
error.entries = colorsSrc.entires.filter((entry) => {
return entry[key] === value;
});
error.message = message;
error.errorLevel = errorLevel;
errors.push(error);
} | javascript | {
"resource": ""
} |
q26098 | commandConvert | train | function commandConvert(command, env, normalize = false) {
if (!isWindows()) {
return command
}
const envUnixRegex = /\$(\w+)|\${(\w+)}/g // $my_var or ${my_var}
const convertedCmd = command.replace(envUnixRegex, (match, $1, $2) => {
const varName = $1 || $2
// In Windows, non-existent variables are not replaced by the shell,
// so for example "echo %FOO%" will literally print the string "%FOO%", as
// opposed to printing an empty string in UNIX. See kentcdodds/cross-env#145
// If the env variable isn't defined at runtime, just strip it from the command entirely
return env[varName] ? `%${varName}%` : ''
})
// Normalization is required for commands with relative paths
// For example, `./cmd.bat`. See kentcdodds/cross-env#127
// However, it should not be done for command arguments.
// See https://github.com/kentcdodds/cross-env/pull/130#issuecomment-319887970
return normalize === true ? path.normalize(convertedCmd) : convertedCmd
} | javascript | {
"resource": ""
} |
q26099 | checkJasmineStatus | train | function checkJasmineStatus() {
// Only inject the source once.
if (jasmineFound) {
return;
}
var found = page.evaluate(function () {
return "jasmine" in window && jasmine.getEnv;
});
if (!found) {
return;
}
jasmineFound = true;
injectReporter();
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.