_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q40200 | train | function (selector, expected, hash) {
this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, selector));
this.actionQueue.push(this.webdriverClient.getAttribute.bind(this.webdriverClient, 'value'));
this.actionQueue.push(this._valCb.bind(this, selector, hash, expected));
return this;
} | javascript | {
"resource": ""
} | |
q40201 | train | function (selector, expected, hash) {
this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, selector));
this.actionQueue.push(this.webdriverClient.selected.bind(this.webdriverClient));
this.actionQueue.push(this._selectedCb.bind(this, selector, hash, expected));
return this;
} | javascript | {
"resource": ""
} | |
q40202 | train | function (selector, expected, hash) {
this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, selector));
this.actionQueue.push(this.webdriverClient.enabled.bind(this.webdriverClient));
this.actionQueue.push(this._enabledCb.bind(this, selector, hash, expected));
return this;
} | javascript | {
"resource": ""
} | |
q40203 | train | function (selector, hash, uuid) {
this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, selector));
this.actionQueue.push(this.webdriverClient.submit.bind(this.webdriverClient));
this.actionQueue.push(this._submitCb.bind(this, selector, hash, uuid));
return this;
} | javascript | {
"resource": ""
} | |
q40204 | train | function (selector, hash, uuid) {
var deferred = Q.defer();
this.events.emit('driver:message', {key: 'submit', value: selector, uuid: uuid, hash: hash});
deferred.resolve();
return deferred.promise;
} | javascript | {
"resource": ""
} | |
q40205 | train | function (selector, options, hash, uuid) {
this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, selector, options));
this.actionQueue.push(this.webdriverClient.scroll.bind(this.webdriverClient));
this.actionQueue.push(this._clickCb.bind(this, selector, options, hash, uuid));
return this;
} | javascript | {
"resource": ""
} | |
q40206 | train | function (selector, timeout, hash, uuid) {
this.actionQueue.push(this.webdriverClient.implicitWait.bind(this.webdriverClient, timeout));
this.actionQueue.push(this._waitForElementCb.bind(this, selector, hash, uuid));
return this;
} | javascript | {
"resource": ""
} | |
q40207 | train | function (selector, expected, hash) {
this.actionQueue.push(this.webdriverClient.elements.bind(this.webdriverClient, selector));
this.actionQueue.push(this._getNumberOfElementsCb.bind(this, selector, hash, expected));
return this;
} | javascript | {
"resource": ""
} | |
q40208 | train | function (selector, expected, hash) {
this.actionQueue.push(this.webdriverClient.elements.bind(this.webdriverClient, selector));
this.actionQueue.push(function (result) {
var deferred = Q.defer();
var res = JSON.parse(result);
var resLength = res.value.length;
var curLength = 0;
var visibleElement = [];
res.value.forEach(function (element) {
var fakeResponse = JSON.stringify({sessionId: res.sessionId, status: 0, value: element.ELEMENT});
this.webdriverClient.options.id = element.ELEMENT;
this.webdriverClient.displayed.bind(this.webdriverClient, selector)(fakeResponse).then(function (visRes) {
curLength++;
if (JSON.parse(visRes).value === true) {
visibleElement.push(element);
}
if (curLength === resLength) {
deferred.resolve(JSON.stringify({sessionId: res.sessionId, status: 0, value: visibleElement}));
}
});
}.bind(this));
return deferred.promise;
}.bind(this));
this.actionQueue.push(this._getNumberOfVisibleElementsCb.bind(this, selector, hash, expected));
return this;
} | javascript | {
"resource": ""
} | |
q40209 | train | function (selector, hash, expected, res) {
var deferred = Q.defer();
var result = JSON.parse(res);
// check if the expression matched any element
if (result.value === -1) {
this.events.emit('driver:message', {key: 'numberOfVisibleElements', hash: hash, selector: selector, expected: expected, value: 0});
} else {
this.events.emit('driver:message', {key: 'numberOfVisibleElements', selector: selector, expected: expected, hash: hash, value: result.value.length});
}
deferred.resolve();
return deferred.promise;
} | javascript | {
"resource": ""
} | |
q40210 | replace_content | train | function replace_content(fullpath) {
var source = fs.readFileSync(fullpath, 'utf8');
var regex = /(require\s*\(\s*['"]alloy\/underscore['"]\s*\))._/g
var test = regex.test(source);
if(test) {
logger.trace("Fixing file: " + fullpath);
source = source.replace(regex, "$1");
fs.writeFileSync(fullpath, source);
}
} | javascript | {
"resource": ""
} |
q40211 | plugin | train | function plugin(params) {
logger = params.logger;
params.dirname = params.dirname ? _.template(params.dirname)(params) : params.event.dir.resourcesPlatform;
logger.trace("fixing underscore in directory: " + params.dirname);
replace_content(path.join(params.dirname, "alloy.js"))
replace_content(path.join(params.dirname, "alloy", "sync", "properties.js"))
replace_content(path.join(params.dirname, "alloy", "sync", "sql.js"))
} | javascript | {
"resource": ""
} |
q40212 | Enumerator | train | function Enumerator(getCurrent, moveNext, reset) {
var index = 0,
self = this;
/**
* Get the current index of the enumerator
*/
this.getIndex = function getIndexEnumeratorInternal() {
return index;
};
/**
* Function that retrieves the current value
* @function
* @returns {Object} The current item
*/
this.getCurrent = function getCurrentInternal() {
return getCurrent(self);
};
this.overrideGetCurrent = function overrideGetCurrentInternal(getCurrent) {
self.getCurrent = function () {
return getCurrent(self.getCurrent());
};
return self;
};
/**
* Function that moves to the next item and returns true if there was a next item, otherwise false
* @function
* @returns {Boolean} True if moved to the next item, otherwise false
*/
this.moveNext = function moveNextInternal() {
index = index + 1;
return moveNext(self);
};
/**
* Function that moves to the next item and returns true if there was a next item, otherwise false
* @function
* @returns {Boolean} True if moved to the next item, otherwise false
*/
this.reset = function resetInternal() {
index = 0;
return reset(self);
};
} | javascript | {
"resource": ""
} |
q40213 | train | function (t) {
var self = this;
this.node = t.node;
var userOpts = this.get('opts');
this.opts = extend(defaultOpts, userOpts);
setTimeout(function () {
self.s = new IScroll(t.node, self.opts);
t.complete();
}, 0);
} | javascript | {
"resource": ""
} | |
q40214 | train | function (message, hash) {
var deferred = Q.defer();
this.events.emit('driver:message', {key: 'noop', uuid: hash, hash: hash, value: message});
deferred.resolve();
return deferred.promise;
} | javascript | {
"resource": ""
} | |
q40215 | train | function (hash) {
this.actionQueue.push(this.webdriverClient.source.bind(this.webdriverClient));
this.actionQueue.push(this._sourceCb.bind(this, hash));
return this;
} | javascript | {
"resource": ""
} | |
q40216 | train | function (hash, source) {
var deferred = Q.defer();
this.events.emit('driver:message', {key: 'source', uuid: hash, hash: hash, value: JSON.parse(source).value});
deferred.resolve();
return deferred.promise;
} | javascript | {
"resource": ""
} | |
q40217 | train | function (expected, hash) {
this.actionQueue.push(this.webdriverClient.title.bind(this.webdriverClient));
this.actionQueue.push(this._titleCb.bind(this, expected, hash));
return this;
} | javascript | {
"resource": ""
} | |
q40218 | train | function (expected, hash, title) {
var deferred = Q.defer();
this.events.emit('driver:message', {key: 'title', expected: expected, hash: hash, value: JSON.parse(title).value});
deferred.resolve();
return deferred.promise;
} | javascript | {
"resource": ""
} | |
q40219 | train | function (expected, hash) {
this.actionQueue.push(this.webdriverClient.alertText.bind(this.webdriverClient));
this.actionQueue.push(this._alertTextCb.bind(this, expected, hash));
return this;
} | javascript | {
"resource": ""
} | |
q40220 | train | function (text, hash) {
this.actionQueue.push(this.webdriverClient.promptText.bind(this.webdriverClient, text));
this.actionQueue.push(this._promptTextCb.bind(this, text, hash));
return this;
} | javascript | {
"resource": ""
} | |
q40221 | train | function (timeout, hash, uuid) {
this.actionQueue.push(this.webdriverClient.implicitWait.bind(this.webdriverClient, timeout));
this.actionQueue.push(this._waitCb.bind(this, timeout, hash, uuid));
return this;
} | javascript | {
"resource": ""
} | |
q40222 | train | function (timeout, hash, uuid) {
var deferred = Q.defer();
this.events.emit('driver:message', {key: 'wait', timeout: timeout, uuid: uuid, hash: hash, value: timeout + ' ms'});
setTimeout(function () {
deferred.resolve();
}.bind(this), timeout);
return deferred.promise;
} | javascript | {
"resource": ""
} | |
q40223 | train | function(referencePoint, otherPoint) {
if (this.yDown) {
if (otherPoint.y > referencePoint.y) {
otherPoint = {
x: otherPoint.x,
y: referencePoint.y - (otherPoint.y - referencePoint.y)
}
} else if (otherPoint.y < referencePoint.y) {
otherPoint = {
x: otherPoint.x,
y: referencePoint.y + (referencePoint.y - otherPoint.y)
}
}
}
var delta = vec2d(otherPoint).minus(vec2d(referencePoint))
var weird = radiansToWeird(delta.angle())
var compass = weirdToCompass(weird)
for (var i = 0; i < this.slices.length; i++) {
if (this.slices[i].contains(compass)) {
return this.slices[i].number
}
}
} | javascript | {
"resource": ""
} | |
q40224 | validate | train | function validate(cmd, args, info) {
AbstractCommand.prototype.validate.apply(this, arguments);
var offset = parseInt('' + args[1]);
if(isNaN(offset) || offset < 0 || offset > Constants.MAX_BIT_LEN) {
throw IntegerRange;
}
args[1] = offset;
} | javascript | {
"resource": ""
} |
q40225 | handleClassesAndId | train | function handleClassesAndId(str) {
return str.replace(/(.*?)([\.|#].[^|]*)(.*)/, function (fullStr, tag, classAndIds, end) {
if (classAndIds[0] === '|') {
return fullStr;
}
const clsIdArr = classAndIds.split(/(\..[^\.|#]*)/).filter(Boolean);
const returnArr = [];
let i = clsIdArr.length;
while (i--) {
returnArr.push(`|${attrType[clsIdArr[i][0]]}=${clsIdArr[i].substr(1)}`);
}
return tag + returnArr.join('') + end;
});
} | javascript | {
"resource": ""
} |
q40226 | readConfigFromFile | train | function readConfigFromFile(filePath) {
var config = {};
if (isFilePath(filePath)) {
try {
config = yaml.safeLoad(stripComments(fs.readFileSync(filePath, 'utf8'))) || {};
} catch (e) {
e.message = 'Cannot read config file: ' + filePath + '\nError: ' + e.message;
throw e;
}
if (path.basename(filePath) === PACKAGE_CONFIG_FILENAME) {
config = config[PACKAGE_CONFIG_FIELD_NAME] || {};
}
} else {
// it's a package
if (filePath.charAt(0) === '@') {
// it's a scoped package
// package name is 'nplint-config', or just a username
var scopedPackageShortcutRegex = /^(@[^\/]+)(?:\/(?:eslint-config)?)?$/;
if (scopedPackageShortcutRegex.test(filePath)) {
filePath = filePath.replace(scopedPackageShortcutRegex, '$1/nplint-config');
} else if (filePath.split('/')[1].indexOf('eslint-config-') !== 0) {
// for scoped packages, insert the eslint-config after the first /
filePath = filePath.replace(/^@([^\/]+)\/(.*)$/, '@$1/nplint-config-$2');
}
} else if (filePath.indexOf('nplint-config-') !== 0) {
filePath = 'nplint-config-' + filePath;
}
config = util.mergeConfigs(config, require(filePath));
}
return config;
} | javascript | {
"resource": ""
} |
q40227 | loadConfig | train | function loadConfig(configToLoad) {
var config = {};
var filePath = '';
if (configToLoad) {
if (isObject(configToLoad)) {
config = configToLoad;
} else {
filePath = configToLoad;
config = readConfigFromFile(filePath);
}
if (!config.rules) {
config.rules = {};
}
config.rules = Object.keys(config.rules).reduce(function(obj, ruleId) {
if (!Array.isArray(config.rules[ruleId])) {
obj[ruleId] = [config.rules[ruleId]];
}
return obj;
}, {});
validator.validate(config, filePath);
// If an `extends` property is defined, it represents a configuration file to use as
// a 'parent'. Load the referenced file and merge the configuration recursively.
if (config.extends) {
var configExtends = config.extends;
if (!Array.isArray(config.extends)) {
configExtends = [config.extends];
}
// Make the last element in an array take the highest precedence
config = configExtends.reduceRight(function(previousValue, parentPath) {
if (parentPath === 'nplint:recommended') {
// Add an explicit substitution for eslint:recommended to conf/eslint.json
// this lets us use the eslint.json file as the recommended rules
parentPath = path.resolve(__dirname, '../conf/nplint.json');
} else if (isFilePath(parentPath)) {
// If the `extends` path is relative, use the directory of the current configuration
// file as the reference point. Otherwise, use as-is.
parentPath = (!isAbsolutePath(parentPath) ?
path.join(path.dirname(filePath), parentPath) :
parentPath
);
}
try {
return util.mergeConfigs(loadConfig(parentPath), previousValue);
} catch (e) {
// If the file referenced by `extends` failed to load, add the path to the
// configuration file that referenced it to the error message so the user is
// able to see where it was referenced from, then re-throw
e.message += '\nReferenced from: ' + filePath;
throw e;
}
}, config);
}
}
return config;
} | javascript | {
"resource": ""
} |
q40228 | getPluginsConfig | train | function getPluginsConfig(pluginNames) {
var pluginConfig = {};
pluginNames.forEach(function(pluginName) {
var pluginNamespace = util.getNamespace(pluginName),
pluginNameWithoutNamespace = util.removeNameSpace(pluginName),
pluginNameWithoutPrefix = util.removePluginPrefix(pluginNameWithoutNamespace),
plugin = {},
rules = {};
if (!loadedPlugins[pluginNameWithoutPrefix]) {
try {
plugin = require(pluginNamespace + util.PLUGIN_NAME_PREFIX + pluginNameWithoutPrefix);
loadedPlugins[pluginNameWithoutPrefix] = plugin;
} catch (err) {
plugin = { rulesConfig: {}};
}
} else {
plugin = loadedPlugins[pluginNameWithoutPrefix];
}
if (!plugin.rulesConfig) {
plugin.rulesConfig = {};
}
Object.keys(plugin.rulesConfig).forEach(function(item) {
rules[pluginNameWithoutPrefix + '/' + item] = plugin.rulesConfig[item];
});
pluginConfig = util.mergeConfigs(pluginConfig, rules);
});
return {rules: pluginConfig};
} | javascript | {
"resource": ""
} |
q40229 | getLocalConfig | train | function getLocalConfig(thisConfig, directory) {
var found,
i,
localConfig,
localConfigFile,
config = {},
localConfigFiles = thisConfig.findLocalConfigFiles(directory),
numFiles = localConfigFiles.length,
rootPath,
projectConfigPath = path.join(process.cwd(), LOCAL_CONFIG_FILENAME);
for (i = 0; i < numFiles; i++) {
localConfigFile = localConfigFiles[i];
// Don't consider the personal config file in the home directory,
// except if the home directory is the same as the current working directory
if (localConfigFile === PERSONAL_CONFIG_PATH && localConfigFile !== projectConfigPath) {
continue;
}
// If root flag is set, don't consider file if it is above root
if (rootPath && !pathIsInside(path.dirname(localConfigFile), rootPath)) {
continue;
}
localConfig = loadConfig(localConfigFile);
// Don't consider a local config file found if the config is empty.
if (!Object.keys(localConfig).length) {
continue;
}
// Check for root flag
if (localConfig.root === true) {
rootPath = path.dirname(localConfigFile);
}
found = true;
config = util.mergeConfigs(localConfig, config);
}
// Use the personal config file if there are no other local config files found.
return found ? config : util.mergeConfigs(config, getPersonalConfig());
} | javascript | {
"resource": ""
} |
q40230 | SliderNeighbor | train | function SliderNeighbor (data) {
this.autoPlay = false // default value is false.
this.interval = DEFAULT_INTERVAL
this.direction = 'row' // 'column' is not temporarily supported.
this.slides = []
this.isPageShow = true
this.isDomRendering = true
this.currentIndex = 0
this.neighborSpace = DEFAULT_NEIGHBOR_SPACE
this.neighborAlpha = DEFAULT_NEIGHBOR_ALPHA
this.neighborScale = DEFAULT_NEIGHBOR_SCALE
// bind event 'pageshow', 'pagehide' and 'visibilitychange' on window.
idleWhenPageDisappear(this)
// bind event 'renderBegin' and 'renderEnd' on window.
idleWhenDomRendering(this)
Component.call(this, data)
} | javascript | {
"resource": ""
} |
q40231 | train | function (key, array, index, fnEqual) {
var idx = Arrays.indexOf(key, array, index, fnEqual);
if (idx >= 0)
array.splice(idx, 1);
return idx;
} | javascript | {
"resource": ""
} | |
q40232 | train | function (key, array, index) {
var idx = Arrays.lastIndexOf(key, array, index);
if (idx >= 0)
array.splice(idx, 1);
return idx;
} | javascript | {
"resource": ""
} | |
q40233 | train | function (items, array, index) {
// There might be some optimization to be made here.
// Right now, I'm just going for a simple solution.
if ( !(items instanceof Array)
|| !(array instanceof Array) )
throw "IllegalArgumentException: items and array must both be Array objects.";
var numRemoved = 0;
for (var i = 0, len = items.length; i < len; i++) {
if (Arrays.remove(items[i], array, index) >= 0)
numRemoved++;
}
return numRemoved;
} | javascript | {
"resource": ""
} | |
q40234 | Interpreter | train | function Interpreter(options) {
options = options || {};
this.quote = typeof options.quote === 'boolean' ? options.quote : true;
} | javascript | {
"resource": ""
} |
q40235 | interpret | train | function interpret(input) {
var cli = []
, exp = null
, i
, s
, q
, e
, sre = /^("|').*/
, ere = /.*("|')$/;
assert(
typeof input === 'string' || input instanceof String,
'interpret invalid input: must be a string');
input = '' + input;
assert(
input && !/^\s+$/.test(input),
'interpret invalid input: empty string');
input = input.replace(/^\s+/, '').replace(/\s+$/, '');
cli = input.split(/\s+/);
cli = cli.map(function(str) {
var num = parseInt(str);
if(!isNaN(num)) {
return num;
}
return str;
})
// expand quoted values
if(this.quote) {
exp = [];
for(i = 0;i < cli.length;i++) {
s = cli[i];
if(sre.test(s)) {
// string is self-closed no whitespace: ie: "dbsize" || 'dbsize'
if(ere.test(s)) {
s = s.substr(1, s.length - 2);
exp.push(s);
// find terminating string
}else{
assert(i < cli.length -1, 'invalid argument(s)');
e = s.replace(sre, "$1");
q = s;
while(++i < cli.length) {
s = cli[i];
q += ' ' + s;
if(s.substr(-1) === e) {
exp.push(q.substr(1, q.length - 2));
break;
}
// no terminating match found
assert(false, 'invalid argument(s)');
}
}
}else{
exp.push(s);
}
}
cli = exp;
}
//console.error('interpret got input %s', input);
//console.error('interpret returning %j', cli);
return cli;
} | javascript | {
"resource": ""
} |
q40236 | train | function (options) {
if (!options.path) {
throw new Error('A path must be supplied to write to')
}
this.path = options.path
this.useColors = options.useColors || false
mkdirp.sync(path.dirname(this.path))
this.fd = fs.openSync(this.path, 'w', options.mode || 0644)
} | javascript | {
"resource": ""
} | |
q40237 | replaceCssModules | train | function replaceCssModules (bundles, cssBundles, originBundleCssBundleMap, moduleClassnameMaps) {
const cssBundlesStats = moduleClassnameMaps && cssBundles.map(bundle => {
const moduleClassnames = bundle.modules.map(module => moduleClassnameMaps[module.path]);
const combinedJson = assign(...[{}].concat(moduleClassnames));
return {
type: "css-stats",
dest: `${bundle.dest}.json`,
moduleHashes: [],
raw: JSON.stringify(combinedJson)
};
}) || [];
return bundles.map((bundle, bIdx) => {
if (!(bIdx in originBundleCssBundleMap)) { return bundle; }
const cssBundle = cssBundles[originBundleCssBundleMap[bIdx]];
return assign({}, bundle, { modules: bundle.modules.map(module => {
if (module.type !== "css") { return module; }
const exportValue = moduleClassnameMaps && moduleClassnameMaps[module.path] ?
fromObject(assign(
{},
moduleClassnameMaps[module.path],
{ _path: cssBundle.dest }
)) :
t.stringLiteral(cssBundle.dest);
return assign({}, module, {
type: "javascript",
ast: exportObjTmpl({ EXPORT_VALUE: exportValue })
});
})});
}).concat(cssBundles, cssBundlesStats);
} | javascript | {
"resource": ""
} |
q40238 | visitEntry | train | function visitEntry (pkey, context, callback) {
_(context).chain().keys().each(function (key) {
var entry = context[key], curkey = pkey?(pkey + '.' + key):key;
if(_.isFunction(entry) || _.isString(entry) || _.isBoolean(entry) ||
_.isArray(entry) || _.isNumber(entry) || _.isRegExp(entry)) {//entry is a leaf node
callback(curkey, entry);
} else {//entry is not a leaf node
visitEntry (curkey, entry, callback)
}
});
} | javascript | {
"resource": ""
} |
q40239 | accessEntry | train | function accessEntry (context, keys) {
_.each(keys, function (key) {
if (context) {
context = context[key];
}
});
return context;
} | javascript | {
"resource": ""
} |
q40240 | Get | train | function Get(url)
{
//Initialize the output
var out = {"path": "", "file": "", "ext": "", "query": {}, "hashtag": ""};
//Save the file path
out.path = url;
//Find if exists a ? or #
var p1 = out.path.indexOf('?');
var p2 = out.path.indexOf('#');
//Check for hashtag
if(p2 != -1)
{
//Get the hashtag value
out.hashtag = out.path.substring(p2 + 1);
//Reset the file path
out.path = out.path.substring(0, p2);
}
//Check for query
if(p1 != -1)
{
//Get the query value
var query = out.path.substring(p1 + 1);
//Split the query value
query = query.split('&');
//Insert into the output
for(var i = 0; i < query.length; i++)
{
//Get the item
var item = query[i].split('=');
//Save to the output
out.query[item[0]] = item[1];
}
//Reset the file path
out.path = out.path.substring(0, p1);
}
//Get the file name
out.file = out.path.substring(out.path.lastIndexOf('/') + 1);
//Get the extension
out.ext = path.extname(out.file).replace('.', '');
//Return
return out;
} | javascript | {
"resource": ""
} |
q40241 | _directoryToFile | train | function _directoryToFile (directory, target, separator, callback) {
if ("undefined" === typeof directory) {
throw new ReferenceError("missing \"directory\" argument");
}
else if ("string" !== typeof directory) {
throw new TypeError("\"directory\" argument is not a string");
}
else if ("" === directory.trim()) {
throw new Error("\"directory\" argument is empty");
}
else if ("undefined" === typeof target) {
throw new ReferenceError("missing \"target\" argument");
}
else if ("string" !== typeof target) {
throw new TypeError("\"target\" argument is not a string");
}
else if ("" === target.trim()) {
throw new Error("\"target\" argument is empty");
}
else if ("undefined" === typeof callback && "undefined" === typeof separator) {
throw new ReferenceError("missing \"callback\" argument");
}
else if ("function" !== typeof callback && "function" !== typeof separator) {
throw new TypeError("\"callback\" argument is not a function");
}
else {
let _callback = callback;
let _separator = separator;
if ("undefined" === typeof _callback) {
_callback = separator;
_separator = " ";
}
extractFiles(directory, (err, files) => {
return err ? _callback(err) : filesToFile(files, target, _separator, _callback);
});
}
} | javascript | {
"resource": ""
} |
q40242 | deepFreeze | train | function deepFreeze(obj) {
// if it's already frozen, don't bother going deep into it...
if (obj === null || typeof obj === 'undefined' || typeof obj.toJS === 'function' || typeof obj !== 'object') {
return obj;
}
// Retrieve the property names defined on obj
let propNames = Object.getOwnPropertyNames(obj);
let properties = {toJS: {value: mirror.bind(obj)}};
if (Array.isArray(obj)) {
// create a copy and deep freeze all entries
obj = obj.slice(0).map(deepFreeze);
// re-attach some important methods
['map', 'forEach', 'find', 'indexOf', 'filter', 'some', 'every', 'lastIndexOf', 'slice'].forEach(fn => {
properties[fn] = {value: function () { return deepFreeze(Array.prototype[fn].apply(obj, arguments));}};
});
}
// Freeze properties before freezing self
for (let index = 0, prop; prop = obj[propNames[index]], index < propNames.length; index += 1) {
// Freeze prop if it is an object
properties[propNames[index]] = {
enumerable: true,
get () {
return deepFreeze(prop);
},
set (newValue) {
throw new Error('Cannot change property "' + propNames[index] + '" to "' + newValue + '" of an immutable object');
}
}
}
// Freeze self (no-op if already frozen)
return Object.freeze(Object.create(Object.getPrototypeOf(obj), properties));
} | javascript | {
"resource": ""
} |
q40243 | getCombination | train | function getCombination (dateFilter, resolutionFilter, dataTypeFilter) {
var c = {
date: getFilter(date, dateFilter),
resolution: getFilter(resolution, resolutionFilter),
dataType: getFilter(dataType, dataTypeFilter),
searchParameters: getSearchParameters(dateFilter, resolutionFilter, dataTypeFilter)
};
c.key = [c.date.key, c.resolution.key, c.dataType.key].join('_');
return c;
} | javascript | {
"resource": ""
} |
q40244 | getAllCombinations | train | function getAllCombinations () {
var combinations = [];
date.forEach(function (tf) {
resolution.forEach(function (rf) {
dataType.forEach(function (sf) {
combinations.push(getCombination(tf, rf, sf));
});
});
});
return combinations;
} | javascript | {
"resource": ""
} |
q40245 | WhileLoop | train | function WhileLoop(name, deps, fragment, doneFn, options) {
if (!(this instanceof WhileLoop)) {
return new WhileLoop(name, deps, fragment, doneFn, options);
}
Task.apply(this, Array.prototype.slice.call(arguments));
this.fragment = fragment;
if (!_.isFunction(doneFn)) {
throw new Error('You must provide a function to indicate when the loop is complete');
}
this.doneFn = doneFn;
this.options = options || {};
} | javascript | {
"resource": ""
} |
q40246 | readStream | train | function readStream(stream) {
return new Promise(function(resolve) {
stream.pipe(concat(function(data) {
resolve(data.toString().trim());
}));
});
} | javascript | {
"resource": ""
} |
q40247 | createGitCmdPromise | train | function createGitCmdPromise(args) {
return new Promise(function(resolve, reject) {
//Remove null values from the final git arguments
args = args.filter(function(arg) {
/*jshint eqnull:true */
return arg != null;
});
/**
* @name git#command
* @event
* @param {String} String the command issued
*/
events.emit('command', [gitCmd].concat(args).join(' '));
var proc = spawn(gitCmd, args);
var output = Promise.join(readStream(proc.stdout), readStream(proc.stderr), function(stdout, stderr) {
//Some warnings (like code === 1) are in stdout
//fatal are in stderr. So try both
return stdout || stderr;
}).tap(function(output) {
/**
* @name git#result
* @event
* @param {String} String the captured output
*/
events.emit('result', output);
});
proc.on('close', function(code) {
//Some weird behaviours can arise with stdout and stderr values
//cause writting to then is sync in *nix and async in windows.
//Also, excessive treatment or long outputs that cause a drain
//in the stderr & stdout streams, could lead us to having this proc
//closed (and this callback called), and no complete values captured
//in an eventual closure variable set then we emit the 'result' event
//So using promises solves this syncronization
output.then(function(output) {
if (code !== 0) {
var error = new Error('git exited with an error');
error.code = code;
error.output = output;
reject(error);
} else {
resolve(output);
}
});
});
proc.on('error', function(error) {
reject(new Error(error));
});
});
} | javascript | {
"resource": ""
} |
q40248 | spawnGit | train | function spawnGit(args) {
//don't bother with throws, they are catched by promises
gitCmd = gitCmd || which('git');
assert.ok(args, 'arguments to git is mandatory');
executionCount++;
if (executionPromise) {
executionPromise = executionPromise.then(
createGitCmdPromise.bind(null, args),
createGitCmdPromise.bind(null, args)
);
} else {
executionPromise = createGitCmdPromise(args);
}
return executionPromise.finally(function() {
if (--executionCount === 0) {
executionPromise = null;
}
});
} | javascript | {
"resource": ""
} |
q40249 | decorator | train | function decorator(fn, options, cb) {
if (typeof options === 'function') {
cb = options;
options = null;
}
return resolvable(options)
.then(fn)
.nodeify(cb);
} | javascript | {
"resource": ""
} |
q40250 | train | function(projection, map) {
Dispatcher.dispatch({
type: Constants.MAP_PROJECTION,
projection: projection,
map: map
});
} | javascript | {
"resource": ""
} | |
q40251 | buildFonts | train | function buildFonts(conf, undertaker) {
const fontSrc = path.join(conf.themeConfig.root, conf.themeConfig.fonts.src, '**', '*.{eot,ttf,woff,woff2,otf,svg}');
const fontDest = path.join(conf.themeConfig.root, conf.themeConfig.fonts.dest);
return undertaker.src(fontSrc)
.pipe(undertaker.dest(fontDest));
} | javascript | {
"resource": ""
} |
q40252 | chain | train | function chain() {
let arg = Array.from(arguments),
pipe = arg.length > 0 ? arg.shift() : stream => stream;
return function() {
let writer = through.obj();
return duplexer(
{objectMode: true},
writer,
pipe.apply(null, [writer].concat(merge(arguments, arg)))
);
};
} | javascript | {
"resource": ""
} |
q40253 | coordinates | train | function coordinates(index, source) {
if (!index || !source)
return void 0;
var lines = source
.slice(0, index)
.split('\n');
return lines.length + ':' + lines.pop().length;
} | javascript | {
"resource": ""
} |
q40254 | iterator | train | function iterator ()
{
// Begin by clearing the canvas
RG.clear(obj.canvas, color);
obj.context.save();
// First draw the circle and clip to it
obj.context.beginPath();
obj.context.arc(centerx, centery, currentRadius, 0, RG.TWOPI, false);
obj.context.clip();
// Clear the canvas to a white color
if (opt.background) {
RG.clear(obj.canvas, opt.background);
}
// Now draw the chart
obj.Draw();
obj.context.restore();
// Increment the radius
if (currentRadius < targetRadius) {
currentRadius += step;
RG.Effects.updateCanvas(iterator);
} else {
callback(obj);
}
} | javascript | {
"resource": ""
} |
q40255 | Tufu | train | function Tufu(src){
if(!(this instanceof Tufu)){
return new Tufu(src);
}
this.src = src;
var bufferData = fs.readFileSync(this.src);
this.codec = Tufu.adaptCodec(bufferData);
this.imageData = this.codec.decode(bufferData);
//set image quality 100%
this.quality = 100;
} | javascript | {
"resource": ""
} |
q40256 | castArgument | train | function castArgument(arg) {
if (isNumber(arg)) {
return parseFloat(arg);
}
if (helpers.isFraction(arg)) {
arg = arg.split('/');
return arg[0] / arg[1];
}
if (arg === 'false' || arg === 'true') {
return arg === 'true';
}
return arg.length ? arg : undefined;
} | javascript | {
"resource": ""
} |
q40257 | getArguments | train | function getArguments(name, mixin, obj) {
let named = obj.named,
ordered = obj.ordered,
args = [],
parameters;
// Cache function parameter names
if (! mixinArguments[name]) {
mixinArguments[name] = mixin.toString()
// Strip out quoted strings (stripping possible commas from parameters)
.replace(/'((?:[^'\\])*)'|"((?:[^"\\])*)"/g, '')
// Pull out parameters from function
.match(/(?:function)?\s?.*?\s?\(([^)]*)\)/)[1]
.split(',')
.map(function(arg) {
return arg.split('=')[0].trim();
});
}
parameters = mixinArguments[name];
Object.keys(named).forEach(key => {
parameters.forEach((param, i) => {
if (key === param) {
args[i] = castArgument(named[key]);
}
});
});
ordered.forEach((arg, i) => {
args[i] = castArgument(arg);
});
return args;
} | javascript | {
"resource": ""
} |
q40258 | ApiclientAdapter | train | function ApiclientAdapter(resource) {
this.admin = admin;
this.resource = resource || {};
// loop through API interface for resource to get methods to expose
var me = this;
_.each(resource.api, function (methodInfo, httpMethod) {
_.each(methodInfo, function (operation, path) {
me[operation] = function (req) {
return me.send(httpMethod, path, req);
};
});
});
} | javascript | {
"resource": ""
} |
q40259 | init | train | function init(config) {
var tokenConfig = config.security.token || {};
var privateKey = tokenConfig.privateKey;
var decryptedToken = {
_id: tokenConfig.webserverId,
authToken: tokenConfig.webserverToken
};
var jwt = jsonwebtoken.sign(decryptedToken, privateKey);
headers = { 'Authorization': 'Bearer ' + jwt };
admin._id = mongo.newObjectId('000000000000000000000000');
admin.name = 'systemAdmin';
admin.type = 'user';
admin.role = 'admin';
var apiConfig = config.api || {};
var host = apiConfig.internalHost || apiConfig.host; // from web server to api use internalHost name
var useSSL = apiConfig.serverUseSSL !== undefined ?
apiConfig.serverUseSSL : config.useSSL;
baseUrl = (useSSL ? 'https://' : 'http://') + host;
var port = config.api.port;
if (port !== 80 && port !== 443) {
baseUrl += ':' + port;
}
baseUrl += '/' + config.api.version;
return config;
} | javascript | {
"resource": ""
} |
q40260 | send | train | function send(httpMethod, path, req) {
req = req || {};
httpMethod = httpMethod.toUpperCase();
var deferred = Q.defer();
var url = baseUrl + path;
var data = req.data || {}; // separate out data from request
delete req.data;
var isAdmin = req.caller && req.caller.role === 'admin';
delete req.caller;
var id = req._id || data._id; // get id from request or data
if (req._id) { delete req._id; } // delete id from request so no dupe
var session = cls.getNamespace('appSession');
var caller = session && session.active && session.get('caller');
if (caller && !isAdmin) {
_.extend(req, { // onBehalfOf used by API to know who is the caller
onBehalfOfType: caller.type,
onBehalfOfId: caller._id + '',
onBehalfOfRole: caller.role,
onBehalfOfName: caller.name
});
}
_.each(req, function (val, key) {
if (!_.isString(val)) { req[key] = JSON.stringify(val); }
});
// replace the ID portion of the URL
url = id ?
url.replace('{_id}', id + '') :
url.replace('/{_id}', '');
var reqConfig = {
headers: headers,
url: url,
method: httpMethod,
qs: _.isEmpty(req) ? undefined : req,
json: _.isEmpty(data) ? true : data
};
// if baseUrl not there yet, wait for 100 seconds until it is (i.e. during system startup)
if (!baseUrl) {
setTimeout(function () {
makeRequest(reqConfig, deferred);
}, 100);
}
else {
makeRequest(reqConfig, deferred);
}
return deferred.promise;
} | javascript | {
"resource": ""
} |
q40261 | train | function(object, getters, property) {
_.each(getters, function(getter, name) {
object.__addGetter(property, name, getter);
});
} | javascript | {
"resource": ""
} | |
q40262 | _flatten | train | function _flatten(_ref) {
var _ref2 = _toArray(_ref);
var first = _ref2[0];
var rest = _ref2.slice(1);
if (first === undefined) {
return [];
} else if (!Array.isArray(first)) {
return [first].concat(_toConsumableArray(_flatten(rest)));
} else {
return [].concat(_toConsumableArray(_flatten(first)), _toConsumableArray(_flatten(rest)));
}
} | javascript | {
"resource": ""
} |
q40263 | serialize | train | function serialize(val) {
if (val == null) {
return 'NULL'
} else if (typeof val == 'string') {
return "'" + val.replace(/(\\)/g, '\\$1').replace(/(')/g, '\\$1') + "'";
} else if (typeof val == 'number') {
if (isNaN(val)) {
return 'NULL';
} else {
return val.toString();
}
} else if ([true, false].indexOf(val) != -1) {
return val.toString().toUpperCase();
} else if (val instanceof Date) {
return "'" + makeDateStr(val) + "'";
} else {
throw "Unable to serialize variable of type `" + typeof val + "`!";
}
} | javascript | {
"resource": ""
} |
q40264 | parseSQLVal | train | function parseSQLVal(type, val) {
if (val == 'NULL') {
return null;
}
switch (type) {
case 'datetime':
case 'timestamp':
if (val == 'CURRENT_TIMESTAMP') {
return val;
} else if (val == '0000-00-00 00:00:00') {
// HACK(arlen): Not sure if this is correct, but constructing
// a Date out of this yields "Invalid Date".
return null;
} else {
return new Date(val);
}
case 'text':
case 'string':
return val;
case 'integer':
case 'primary_key':
return parseInt(val);
case 'float':
return parseFloat(val);
case 'boolean':
return (val == "TRUE");
default:
throw "Unknown friendly type `" + type + "`!";
}
} | javascript | {
"resource": ""
} |
q40265 | microStorage | train | function microStorage ( namespace ) {
list[namespace] = list[namespace] || {};
localStorage.setItem(packageName, JSON.stringify(list));
/**
* Get or set value from storage
* @param {String} name key
* @param {AnyType} value value
* @return {AnyType} value
*/
function storage ( name, value ) {
if (arguments.length == 0) {
return;
}
if (arguments.length == 1) {
let result = JSON.parse(localStorage.getItem(`${ namespace }.${ name }`));
return result ? result.$ : result;
}
localStorage.setItem(`${ namespace }.${ name }`, JSON.stringify({ $ : value }));
list[namespace][name] = '';
localStorage.setItem(packageName, JSON.stringify(list));
return value;
};
/**
* Remove value from storage
* @param {String} name key
*/
storage.remove = function ( name ) {
localStorage.removeItem(`${ namespace }.${ name }`);
delete list[namespace][name];
localStorage.setItem(packageName, JSON.stringify(list));
};
/**
* Return value list of storage
* @return {Array} list list of storage
*/
storage.list = function () {
return Object.keys(list[namespace]);
};
/**
* Clear all value from storage
*/
storage.clear = function () {
this.list().forEach(( name ) => {
this.remove(name);
});
};
return storage;
} | javascript | {
"resource": ""
} |
q40266 | storage | train | function storage ( name, value ) {
if (arguments.length == 0) {
return;
}
if (arguments.length == 1) {
let result = JSON.parse(localStorage.getItem(`${ namespace }.${ name }`));
return result ? result.$ : result;
}
localStorage.setItem(`${ namespace }.${ name }`, JSON.stringify({ $ : value }));
list[namespace][name] = '';
localStorage.setItem(packageName, JSON.stringify(list));
return value;
} | javascript | {
"resource": ""
} |
q40267 | isLoggingConfigured | train | function isLoggingConfigured(target) {
return target && isBoolean(target.warnEnabled) && isBoolean(target.infoEnabled) && isBoolean(target.debugEnabled)
&& isBoolean(target.traceEnabled) && typeof target.error === 'function' && typeof target.warn === 'function'
&& typeof target.info === 'function' && typeof target.debug === 'function' && typeof target.trace === 'function';
} | javascript | {
"resource": ""
} |
q40268 | isValidLogLevel | train | function isValidLogLevel(logLevel) {
const level = cleanLogLevel(logLevel);
switch (level) {
case LogLevel.ERROR:
case LogLevel.WARN:
case LogLevel.INFO:
case LogLevel.DEBUG:
case LogLevel.TRACE:
return true;
default:
return false;
}
} | javascript | {
"resource": ""
} |
q40269 | prepareResults | train | function prepareResults(contentTypes) {
var results = _.reduce(contentTypes, function (result, contentType, key) {
// If content type is string, treat is as content type id
if(_.isString(contentType)){
var id = contentType;
contentType = {
id: id
}
}
contentType.name = key;
result.push(contentType);
return result;
}, []);
return when.resolve(results);
} | javascript | {
"resource": ""
} |
q40270 | fetchEntries | train | function fetchEntries(contentTypes) {
return when.map(contentTypes, function (contentType) {
if (!contentType.id) {
return when.reject('Content type `' + contentType.name + '` is missing an `id` value');
}
var filters = _.merge({}, contentType.filters, {content_type: contentType.id});
return client.entries(filters).then(function (results) {
response[contentType.name] = results;
});
});
} | javascript | {
"resource": ""
} |
q40271 | train | function(properties, cls, superClass, options) {
var opts = _.defaults({}, options, { wrap: true });
if (opts.wrap) {
var prototype = cls.prototype;
if (superClass) {
// combine the cls prototype with the superClass prototype, but do so
// using a new prototype chain to avoid copying (and invoking accessor
// methods) either prototype. the combined prototype can be used to wrap
// properties.
prototype = Object.create(prototype);
prototype.prototype = superClass.prototype;
}
properties = wrap.super.properties(properties, prototype);
}
_.extend(cls.prototype, properties);
} | javascript | {
"resource": ""
} | |
q40272 | train | function(model, options) {
options = options ? _.clone(options) : {};
if (!(model = this._prepareModel(model, options))) return false;
if (!options.wait) this.add(model, options);
return this._callAdapter('addToIndex', options, model);
} | javascript | {
"resource": ""
} | |
q40273 | train | function(options) {
options = options ? _.clone(options) : {};
options.indexKeys = this.indexKeys || options.indexKeys;
options.unionKey = this.unionKey || options.unionKey;
if (this.indexKey) options.indexKeys.push(this.indexKey);
var args = [this, options];
return nodefn.apply(_.bind(this.indexDb.readFromIndexes, this.indexDb), args);
} | javascript | {
"resource": ""
} | |
q40274 | train | function(models, options) {
if(!models) return false;
this.remove(models, options);
var singular = !_.isArray(models);
models = singular ? [models] : _.clone(models);
return this._callAdapter('removeFromIndex', options, models);
} | javascript | {
"resource": ""
} | |
q40275 | _isDirectory | train | function _isDirectory (directory, callback) {
if ("undefined" === typeof directory) {
throw new ReferenceError("missing \"directory\" argument");
}
else if ("string" !== typeof directory) {
throw new TypeError("\"directory\" argument is not a string");
}
else if ("" === directory.trim()) {
throw new Error("\"directory\" argument is empty");
}
else if ("undefined" === typeof callback) {
throw new ReferenceError("missing \"callback\" argument");
}
else if ("function" !== typeof callback) {
throw new TypeError("\"callback\" argument is not a function");
}
else {
lstat(directory, (err, stats) => {
return callback(null, Boolean(!err && stats.isDirectory()));
});
}
} | javascript | {
"resource": ""
} |
q40276 | traverse | train | function traverse(node, {enter = () => {}, leave = () => {}}, path = []) {
switch (node.type) {
// regular non-leaf nodes
case 'Apply':
enter(node, path)
node.args.forEach((arg, index) =>
traverse(arg, {enter, leave}, [...path, 'args', index]))
leave(node, path)
break
// leaf nodes
case 'Identifier':
case 'Number':
case 'Ellipsis':
enter(node, path)
leave(node, path)
break
// irregular non-leaf nodes
case 'Parentheses':
enter(node, path)
traverse(node.body, {enter, leave}, [...path, 'body'])
leave(node, path)
break
case 'List':
case 'Sequence':
enter(node, path)
node.items.forEach((item, index) =>
traverse(item, {enter, leave}, [...path, 'items', index]))
leave(node, path)
break
case 'System':
enter(node, path)
node.relations.forEach((rel, index) =>
traverse(rel, {enter, leave}, [...path, 'relations', index]))
leave(node, path)
break
case 'Placeholder':
// TODO(kevinb) handle children of the placeholder
// e.g. we there might #a_0 could match x_0, y_0, z_0, etc.
enter(node, path)
leave(node, path)
break
default:
throw new Error(`unrecognized node: ${node.type}`)
}
} | javascript | {
"resource": ""
} |
q40277 | validate | train | function validate(values) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var s = this;
var _tv4$validateMultiple = tv4.validateMultiple(values, s),
valid = _tv4$validateMultiple.valid,
errors = _tv4$validateMultiple.errors;
if (valid) {
return null;
}
var assign = options.assign,
_options$name = options.name,
name = _options$name === void 0 ? 'SchemaError' : _options$name;
var _s$schema = s.schema,
schema = _s$schema === void 0 ? {} : _s$schema;
var error = new Error("Validation failed with schema: ".concat(schema.title || schema.id || schema.description));
return Object.assign(error, {
id: uuid.v4(),
name: name,
errors: errors,
schema: schema,
values: values,
engine: 'tv4'
}, assign);
} | javascript | {
"resource": ""
} |
q40278 | validateToThrow | train | function validateToThrow() {
var s = this;
var error = s.validate.apply(s, arguments);
if (error) {
throw error;
}
} | javascript | {
"resource": ""
} |
q40279 | set | train | function set(values) {
var s = this;
if (arguments.length === 2) {
values = {};
var key = arguments[0];
values[key] = arguments[1];
}
Object.assign(s, values);
return s;
} | javascript | {
"resource": ""
} |
q40280 | toJSON | train | function toJSON() {
var s = this;
var values = Object.assign({}, s.schema);
Object.keys(values).forEach(function (key) {
var isFunc = iftype.isFunction(values[key]);
if (isFunc) {
delete values[key];
}
});
return values;
} | javascript | {
"resource": ""
} |
q40281 | expandFileGlobs | train | function expandFileGlobs(filesAndPatterns, rootDir, callbackFn) {
fileMatcher.resolveAnyGlobPatternsAsync(filesAndPatterns, rootDir)
.then(function(result) { callbackFn(null, result); })
.fail(callbackFn);
} | javascript | {
"resource": ""
} |
q40282 | train | function(selector, context) {
var results = [];
if (typeof(selector) === 'string') {
var idSelector = detectIdSelectors.exec(selector);
context = context || document;
if (idSelector && idSelector[1]) {
var element = context.getElementById(idSelector[1]);
if (element) results.push(element);
}
else {
results = context.querySelectorAll(selector);
}
}
else if (selector &&
(selector.nodeType || window.XMLHttpRequest && selector instanceof XMLHttpRequest)) {
// allow OTHelpers(DOMNode) and OTHelpers(xmlHttpRequest)
results = [selector];
context = selector;
}
else if (OTHelpers.isArray(selector)) {
results = selector.slice();
context = null;
}
return new ElementCollection(results, context);
} | javascript | {
"resource": ""
} | |
q40283 | nodeListToArray | train | function nodeListToArray (nodes) {
if ($.env.name !== 'IE' || $.env.version > 9) {
return prototypeSlice.call(nodes);
}
// IE 9 and below call use Array.prototype.slice.call against
// a NodeList, hence the following
var array = [];
for (var i=0, num=nodes.length; i<num; ++i) {
array.push(nodes[i]);
}
return array;
} | javascript | {
"resource": ""
} |
q40284 | versionGEThan | train | function versionGEThan (otherVersion) {
if (otherVersion === version) return true;
if (typeof(otherVersion) === 'number' && typeof(version) === 'number') {
return otherVersion > version;
}
// The versions have multiple components (i.e. 0.10.30) and
// must be compared piecewise.
// Note: I'm ignoring the case where one version has multiple
// components and the other doesn't.
var v1 = otherVersion.split('.'),
v2 = version.split('.'),
versionLength = (v1.length > v2.length ? v2 : v1).length;
for (var i = 0; i < versionLength; ++i) {
if (parseInt(v1[i], 10) > parseInt(v2[i], 10)) {
return true;
}
}
// Special case, v1 has extra components but the initial components
// were identical, we assume this means newer but it might also mean
// that someone changed versioning systems.
if (i < v1.length) {
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q40285 | executeListenersAsyncronously | train | function executeListenersAsyncronously(name, args, defaultAction) {
var listeners = api.events[name];
if (!listeners || listeners.length === 0) return;
var listenerAcks = listeners.length;
$.forEach(listeners, function(listener) { // , index
function filterHandlers(_listener) {
return _listener.handler === listener.handler;
}
// We run this asynchronously so that it doesn't interfere with execution if an
// error happens
$.callAsync(function() {
try {
// have to check if the listener has not been removed
if (api.events[name] && $.some(api.events[name], filterHandlers)) {
(listener.closure || listener.handler).apply(listener.context || null, args);
}
}
finally {
listenerAcks--;
if (listenerAcks === 0) {
executeDefaultAction(defaultAction, args);
}
}
});
});
} | javascript | {
"resource": ""
} |
q40286 | executeListenersSyncronously | train | function executeListenersSyncronously(name, args) { // defaultAction is not used
var listeners = api.events[name];
if (!listeners || listeners.length === 0) return;
$.forEach(listeners, function(listener) { // index
(listener.closure || listener.handler).apply(listener.context || null, args);
});
} | javascript | {
"resource": ""
} |
q40287 | appendToLogs | train | function appendToLogs(level, args) {
if (!args) return;
var message = toDebugString(args);
if (message.length <= 2) return;
_logs.push(
[level, formatDateStamp(), message]
);
} | javascript | {
"resource": ""
} |
q40288 | train | function (name, callback) {
capabilities[name] = function() {
var result = callback();
capabilities[name] = function() {
return result;
};
return result;
};
} | javascript | {
"resource": ""
} | |
q40289 | shim | train | function shim () {
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
FNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof FNOP && oThis ?
this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
};
FNOP.prototype = this.prototype;
fBound.prototype = new FNOP();
return fBound;
};
}
if(!Array.isArray) {
Array.isArray = function (vArg) {
return Object.prototype.toString.call(vArg) === '[object Array]';
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement, fromIndex) {
var i,
pivot = (fromIndex) ? fromIndex : 0,
length;
if (!this) {
throw new TypeError();
}
length = this.length;
if (length === 0 || pivot >= length) {
return -1;
}
if (pivot < 0) {
pivot = length - Math.abs(pivot);
}
for (i = pivot; i < length; i++) {
if (this[i] === searchElement) {
return i;
}
}
return -1;
};
}
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisArg */)
{
'use strict';
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = new Array(len);
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++)
{
// NOTE: Absolute correctness would demand Object.defineProperty
// be used. But this method is fairly new, and failure is
// possible only if Object.prototype or Array.prototype
// has a property |i| (very unlikely), so use a less-correct
// but more portable alternative.
if (i in t)
res[i] = fun.call(thisArg, t[i], i, t);
}
return res;
};
}
} | javascript | {
"resource": ""
} |
q40290 | train | function (options, completion) {
var Proto = function PluginProxy() {},
api = new Proto(),
waitForReadySignal = pluginEventingBehaviour(api);
refCountBehaviour(api);
// Assign +plugin+ to this object and setup all the public
// accessors that relate to the DOM Object.
//
var setPlugin = function setPlugin (plugin) {
if (plugin) {
api._ = plugin;
api.parentElement = plugin.parentElement;
api.$ = $(plugin);
}
else {
api._ = null;
api.parentElement = null;
api.$ = $();
}
};
api.uuid = generateCallbackID();
api.isValid = function() {
return api._.valid;
};
api.destroy = function() {
api.removeAllRefs();
setPlugin(null);
// Let listeners know that they should do any final book keeping
// that relates to us.
api.emit('destroy');
};
/// Initialise
// The next statement creates the raw plugin object accessor on the Proxy.
// This is null until we actually have created the Object.
setPlugin(null);
waitOnGlobalCallback(api.uuid, function(err) {
if (err) {
completion('The plugin with the mimeType of ' +
options.mimeType + ' timed out while loading: ' + err);
api.destroy();
return;
}
api._.setAttribute('id', 'tb_plugin_' + api._.uuid);
api._.removeAttribute('tb_callback_id');
api.uuid = api._.uuid;
api.id = api._.id;
waitForReadySignal(function(err) {
if (err) {
completion('Error while starting up plugin ' + api.uuid + ': ' + err);
api.destroy();
return;
}
completion(void 0, api);
});
});
createObject(api.uuid, options, function(err, plugin) {
setPlugin(plugin);
});
return api;
} | javascript | {
"resource": ""
} | |
q40291 | setPlugin | train | function setPlugin (plugin) {
if (plugin) {
api._ = plugin;
api.parentElement = plugin.parentElement;
api.$ = $(plugin);
}
else {
api._ = null;
api.parentElement = null;
api.$ = $();
}
} | javascript | {
"resource": ""
} |
q40292 | makeMediaCapturerProxy | train | function makeMediaCapturerProxy (api) {
api.selectSources = function() {
return api._.selectSources.apply(api._, arguments);
};
return api;
} | javascript | {
"resource": ""
} |
q40293 | makeMediaPeerProxy | train | function makeMediaPeerProxy (api) {
api.setStream = function(stream, completion) {
api._.setStream(stream);
if (completion) {
if (stream.hasVideo()) {
// FIX ME renderingStarted currently doesn't first
// api.once('renderingStarted', completion);
var verifyStream = function() {
if (!api._) {
completion(new $.Error('The plugin went away before the stream could be bound.'));
return;
}
if (api._.videoWidth > 0) {
// This fires a little too soon.
setTimeout(completion, 200);
}
else {
setTimeout(verifyStream, 500);
}
};
setTimeout(verifyStream, 500);
}
else {
// TODO Investigate whether there is a good way to detect
// when the audio is ready. Does it even matter?
// This fires a little too soon.
setTimeout(completion, 200);
}
}
return api;
};
return api;
} | javascript | {
"resource": ""
} |
q40294 | versionGreaterThan | train | function versionGreaterThan (version1, version2) {
if (version1 === version2) return false;
if (version1 === -1) return version2;
if (version2 === -1) return version1;
if (version1.indexOf('.') === -1 && version2.indexOf('.') === -1) {
return version1 > version2;
}
// The versions have multiple components (i.e. 0.10.30) and
// must be compared piecewise.
// Note: I'm ignoring the case where one version has multiple
// components and the other doesn't.
var v1 = version1.split('.'),
v2 = version2.split('.'),
versionLength = (v1.length > v2.length ? v2 : v1).length;
for (var i = 0; i < versionLength; ++i) {
if (parseInt(v1[i], 10) > parseInt(v2[i], 10)) {
return true;
}
}
// Special case, v1 has extra components but the initial components
// were identical, we assume this means newer but it might also mean
// that someone changed versioning systems.
if (i < v1.length) {
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q40295 | _getUserMedia | train | function _getUserMedia(mediaConstraints, success, error) {
PluginProxies.createMediaPeer(function(err, plugin) {
if (err) {
error.call(OTPlugin, err);
return;
}
plugin._.getUserMedia(mediaConstraints.toHash(), function(streamJson) {
success.call(OTPlugin, MediaStream.fromJson(streamJson, plugin));
}, error);
});
} | javascript | {
"resource": ""
} |
q40296 | measureUploadBandwidth | train | function measureUploadBandwidth(url, payload) {
var xhr = new XMLHttpRequest(),
resultPromise = new OT.$.RSVP.Promise(function(resolve, reject) {
var startTs,
lastTs,
lastLoaded;
xhr.upload.addEventListener('progress', function(evt) {
if (!startTs) {
startTs = Date.now();
}
lastLoaded = evt.loaded;
});
xhr.addEventListener('load', function() {
lastTs = Date.now();
resolve(1000 * 8 * lastLoaded / (lastTs - startTs));
});
xhr.addEventListener('error', function(e) {
reject(e);
});
xhr.addEventListener('abort', function() {
reject();
});
xhr.open('POST', url);
xhr.send(payload);
});
return {
promise: resultPromise,
abort: function() {
xhr.abort();
}
};
} | javascript | {
"resource": ""
} |
q40297 | getMLineIndex | train | function getMLineIndex(sdpLines, mediaType) {
var targetMLine = 'm=' + mediaType;
// Find the index of the media line for +type+
return OT.$.findIndex(sdpLines, function(line) {
if (line.indexOf(targetMLine) !== -1) {
return true;
}
return false;
});
} | javascript | {
"resource": ""
} |
q40298 | getMLinePayloadTypes | train | function getMLinePayloadTypes (mediaLine, mediaType) {
var mLineSelector = new RegExp('^m=' + mediaType +
' \\d+(/\\d+)? [a-zA-Z0-9/]+(( [a-zA-Z0-9/]+)+)$', 'i');
// Get all payload types that the line supports
var payloadTypes = mediaLine.match(mLineSelector);
if (!payloadTypes || payloadTypes.length < 2) {
// Error, invalid M line?
return [];
}
return OT.$.trim(payloadTypes[2]).split(' ');
} | javascript | {
"resource": ""
} |
q40299 | removeMediaEncoding | train | function removeMediaEncoding (sdp, mediaType, encodingName) {
var sdpLines = sdp.split('\r\n'),
mLineIndex = SDPHelpers.getMLineIndex(sdpLines, mediaType),
mLine = mLineIndex > -1 ? sdpLines[mLineIndex] : void 0,
typesToRemove = [],
payloadTypes,
match;
if (mLineIndex === -1) {
// Error, missing M line
return sdpLines.join('\r\n');
}
// Get all payload types that the line supports
payloadTypes = SDPHelpers.getMLinePayloadTypes(mLine, mediaType);
if (payloadTypes.length === 0) {
// Error, invalid M line?
return sdpLines.join('\r\n');
}
// Find the location of all the rtpmap lines that relate to +encodingName+
// and any of the supported payload types
var matcher = new RegExp('a=rtpmap:(' + payloadTypes.join('|') + ') ' +
encodingName + '\\/\\d+', 'i');
sdpLines = OT.$.filter(sdpLines, function(line, index) {
match = line.match(matcher);
if (match === null) return true;
typesToRemove.push(match[1]);
if (index < mLineIndex) {
// This removal changed the index of the mline, track it
mLineIndex--;
}
// remove this one
return false;
});
if (typesToRemove.length > 0 && mLineIndex > -1) {
// Remove all the payload types and we've removed from the media line
sdpLines[mLineIndex] = SDPHelpers.removeTypesFromMLine(mLine, typesToRemove);
}
return sdpLines.join('\r\n');
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.