_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q43600 | train | function( selector ) {
var removeTmpId = createTmpId( this ),
list = new CKEDITOR.dom.nodeList(
this.$.querySelectorAll( getContextualizedSelector( this, selector ) )
);
removeTmpId();
return list;
} | javascript | {
"resource": ""
} | |
q43601 | train | function( selector ) {
var removeTmpId = createTmpId( this ),
found = this.$.querySelector( getContextualizedSelector( this, selector ) );
removeTmpId();
return found ? new CKEDITOR.dom.element( found ) : null;
} | javascript | {
"resource": ""
} | |
q43602 | pushTo | train | function pushTo(array) {
return map(function (file, cb) {
array.push(file);
cb(null, file);
});
} | javascript | {
"resource": ""
} |
q43603 | processBundleFile | train | function processBundleFile(file, bundleExt, variables, bundleHandler, errorCallback) {
// get bundle files
var lines = file.contents.toString().split('\n');
var resultFilePaths = [];
lines.forEach(function (line) {
var filePath = getFilePathFromLine(file, line, variables);
if (filePath)
resultFilePaths.push(filePath);
});
if (!errorCallback)
errorCallback = function () { };
// find files and send to buffer
var bundleSrc = fs.src(resultFilePaths)
.on('error', errorCallback) // handle file not found errors
.pipe(plumber(errorCallback)) // handle other errors inside pipeline
.pipe(recursiveBundle(bundleExt, variables, errorCallback));
if (bundleHandler && typeof bundleHandler === 'function')
bundleSrc = bundleHandler(bundleSrc);
return bundleSrc.pipe(plumber.stop());
} | javascript | {
"resource": ""
} |
q43604 | getFilePathFromLine | train | function getFilePathFromLine(bundleFile, line, variables) {
// handle variables
var varRegex = /@{([^}]+)}/;
var match;
while (match = line.match(varRegex)) {
var varName = match[1];
if (!variables || typeof (variables[varName]) === 'undefined')
throw new gutil.PluginError(pluginName, bundleFile.path + ': variable "' + varName + '" is not specified');
var varValue = variables[varName];
line = line.substr(0, match.index) + varValue + line.substr(match.index + match[0].length);
}
if (line === '')
return null;
// handle `!` negated file paths
var negative = line[0] === '!';
if (negative)
line = line.substr(1);
// get file path for line
var filePath;
if (line.indexOf('./') === 0)
filePath = path.resolve(bundleFile.cwd, line);
else
filePath = path.resolve(bundleFile.base, line);
// return path
if (negative)
return '!' + filePath;
return filePath;
} | javascript | {
"resource": ""
} |
q43605 | recursiveBundle | train | function recursiveBundle(bundleExt, variables, errorCallback) {
return through2.obj(function (file, enc, cb) {
if (!checkFile(file, cb))
return;
// standart file push to callback
if (path.extname(file.path).toLowerCase() != bundleExt)
return cb(null, file);
// bundle file should be parsed
processBundleFile(file, bundleExt, variables, null, errorCallback)
.pipe(pushTo(this))
.on('end', cb);
});
} | javascript | {
"resource": ""
} |
q43606 | train | function (variables, bundleHandler) {
// handle if bundleHandler specified in first argument
if (!bundleHandler && typeof (variables) === 'function') {
bundleHandler = variables;
variables = null;
}
return through2.obj(function (file, enc, cb) {
if (!checkFile(file, cb))
return;
var ext = path.extname(file.path).toLowerCase();
var resultFileName = path.basename(file.path, ext);
var bundleFiles = processBundleFile(file, ext, variables, bundleHandler, cb);
if (file.sourceMap)
bundleFiles = bundleFiles.pipe(sourcemaps.init());
bundleFiles
.pipe(concat(resultFileName))
.pipe(pushTo(this))
.on('end', cb);
});
} | javascript | {
"resource": ""
} | |
q43607 | DispatchError | train | function DispatchError(message) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'DispatchError';
this.message = message;
} | javascript | {
"resource": ""
} |
q43608 | delegateOptional | train | function delegateOptional (self) {
if (hasOwn(self, 'actual') && hasOwn(self, 'expected')) {
var kindOf = tryRequire('kind-of-extra', 'kind-error')
delegate(self, {
orig: {
actual: self.actual,
expected: self.expected
},
type: {
actual: kindOf(self.actual),
expected: kindOf(self.expected)
},
inspect: {
actual: util.inspect(self.actual),
expected: util.inspect(self.expected)
}
})
if (typeof self.message === 'function') {
self.message = self.message.call(self, self.type, self.inspect) // eslint-disable-line no-useless-call
}
}
return self
} | javascript | {
"resource": ""
} |
q43609 | messageFormat | train | function messageFormat (type, inspect) {
var msg = this.detailed
? 'expect %s `%s`, but %s `%s` given'
: 'expect `%s`, but `%s` given'
return this.detailed
? util.format(msg, type.expected, inspect.expected, type.actual, inspect.actual)
: util.format(msg, type.expected, type.actual)
} | javascript | {
"resource": ""
} |
q43610 | remap | train | function remap (map, str) {
str = string.call(str) === '[object String]' ? str : ''
for (var key in map) {
if (str.match(new RegExp(key, 'i'))) return map[key]
}
return ''
} | javascript | {
"resource": ""
} |
q43611 | add | train | function add (a, b) {
var fifths = a[0] + b[0]
var octaves = a[1] === null || b[1] === null ? null : a[1] + b[1]
return [fifths, octaves]
} | javascript | {
"resource": ""
} |
q43612 | subtract | train | function subtract (a, b) {
var fifths = b[0] - a[0]
var octaves = a[1] !== null && b[1] !== null ? b[1] - a[1] : null
return [fifths, octaves]
} | javascript | {
"resource": ""
} |
q43613 | nth | train | function nth (n, array) {
return n < 0 ? array[array.length + n] : array[n]
} | javascript | {
"resource": ""
} |
q43614 | scanErr | train | function scanErr(err, pathname) {
log.debug(err);
if ('ENOENT' === err.code) {
callback(pathname + ' does not exist.');
} else {
callback('Unexpected error.');
}
// cli does process.exit() in callback, but unit tests don't.
callback = function () {};
} | javascript | {
"resource": ""
} |
q43615 | getCurrentServerTimeAndBlock | train | async function getCurrentServerTimeAndBlock() {
await retrieveDynGlobProps();
if(props.time) {
lastCommitedBlock = props.last_irreversible_block_num;
trace("lastCommitedBlock = " + lastCommitedBlock + ", headBlock = " + props.head_block_number);
return {
time : Date.parse(props.time),
block : props.head_block_number,
commited_block : props.last_irreversible_block_num
};
}
throw "Current time could not be retrieved";
} | javascript | {
"resource": ""
} |
q43616 | filter | train | function filter(obj) {
var result = {}, fieldDefine, value;
for(var field in options) {
fieldDefine = options[field];
value = obj[field];
if(!fieldDefine.private && value !== undefined) {
result[field] = value;
}
}
return result;
} | javascript | {
"resource": ""
} |
q43617 | Container | train | function Container(name, token, url) {
this._name = name;
this._url = url;
this._token = token;
this.isNew = false;
} | javascript | {
"resource": ""
} |
q43618 | waitForJobToFinish | train | function waitForJobToFinish(driver, options) {
return new Promise(function (resolve, reject) {
var start = Date.now();
var timingOut = false;
function check() {
var checkedForExceptions;
if (options.allowExceptions) {
checkedForExceptions = Promise.resolve(null);
} else {
checkedForExceptions = driver.browser().activeWindow()
.execute('return window.ERROR_HAS_OCCURED;').then(function (errorHasOcucured) {
if (!errorHasOcucured) return;
return driver.browser().activeWindow()
.execute('return window.FIRST_ERROR;').then(function (err) {
var loc = location.getOriginalLocation(err.url, err.line);
var clientError = new Error(err.msg + ' (' + loc.source + ' line ' + loc.line + ')');
clientError.isClientError = true;
throw clientError;
}, function () {
throw new Error('Unknown error was thrown and not caught in the browser.');
});
}, function () {});
}
checkedForExceptions.then(function () {
return retry(function () {
if (typeof options.testComplete === 'string') {
return driver.browser().activeWindow().execute(options.testComplete);
} else {
return Promise.resolve(options.testComplete(driver));
}
}, 5, '500ms', {debug: options.debug});
}).done(function (complete) {
if (complete) resolve();
else {
if (timingOut) return reject(new Error('Test timed out'));
if (Date.now() - start > ms('' + (options.timeout || '20s'))) timingOut = true;
setTimeout(check, 500);
}
}, reject);
}
check();
});
} | javascript | {
"resource": ""
} |
q43619 | Range | train | function Range(){
if (!(this instanceof Range)) {
return new Range();
}
// maximize int.
var max = Math.pow(2, 32) - 1;
// default options.
this.options = {
min: -max,
max: max,
res: {
range : /^[\s\d\-~,]+$/,
blank : /\s+/g,
number : /^\-?\d+$/,
min2num: /^~\-?\d+$/,
num2max: /^\-?\d+~$/,
num2num: /^\-?\d+~\-?\d+$/
}
};
Object.freeze(this.options);
} | javascript | {
"resource": ""
} |
q43620 | train | function(s, opts){
var r = s.split('~').map(function(d){
return parseFloat(d);
});
// number at position 1 must greater than position 0.
if (r[0] > r[1]) {
return r.reverse();
}
return r;
} | javascript | {
"resource": ""
} | |
q43621 | rename | train | function rename(node, it, to){
switch (node.type) {
case 'VariableDeclaration':
return node.declarations.forEach(function(dec){
if (dec.id.name == it) dec.id.name = to
if (dec.init) rename(dec.init, it, to)
})
case 'FunctionDeclaration':
if (node.id.name == it) node.id.name = to // falls through
case 'FunctionExpression':
var isIt = function(id){ return id.name == it }
return isIt(node.id)
|| node.params.some(isIt)
|| freshVars(node.body).some(isIt)
|| rename(node.body, it, to)
case 'CatchClause':
if (node.param.name == it) return
return rename(node.body, it, to)
case 'Identifier':
return node.name == it && (node.name = to)
}
children(node).forEach(function(child){
rename(child, it, to)
})
return node
} | javascript | {
"resource": ""
} |
q43622 | freshVars | train | function freshVars(node){
switch (node.type) {
case 'VariableDeclaration':
return node.declarations.map(function(n){ return n.id })
case 'FunctionExpression': return [] // early exit
case 'FunctionDeclaration':
return [node.id]
}
return children(node)
.map(freshVars)
.reduce(concat, [])
} | javascript | {
"resource": ""
} |
q43623 | train | function (filename) {
var resume = filename === true; // should only ever be set by resume calls
var fd = this._fd = resume ? this._fd : fs.openSync(filename, 'r');
var buffer = new Buffer(4096);
var bytesRead;
var current = '';
var remainder = resume ? this._remainder : '';
while (!this._paused && (bytesRead = fs.readSync(fd, buffer, 0, buffer.length))) {
current = buffer.toString('utf-8');
if (current.length > bytesRead) {
current = current.slice(0, bytesRead);
}
remainder = this._remainder = this._parseLines(remainder + current);
}
// The loop will end either when EOF is reached, or pause was called.
// In the former case, close the file; in the latter case, leave it
// open with the expectation that we'll pick up where we left off.
if (!this._paused) {
fs.closeSync(fd);
}
} | javascript | {
"resource": ""
} | |
q43624 | init | train | function init(){
//modules load
terminal.colors.default= chalk.white.bold;
terminal.default="";
//set the colors of the terminal
checkUserColors(terminal.colors);
bool=true;
//to control the view properties and colors
properties= Object.getOwnPropertyNames(terminal);
colors=Object.getOwnPropertyNames(terminal.colors);
} | javascript | {
"resource": ""
} |
q43625 | fertilise | train | function fertilise(objectName, value, color, blockPos){
if(!blockPos) throw new Error("incorrect call to fertilise method");
var name= objectName.slice(2);
terminal[name]=value;
terminal.colors[name]=color;
setOnBlock(objectName, blockPos);
checkUserColors(terminal.colors);
init();
} | javascript | {
"resource": ""
} |
q43626 | checkUserColors | train | function checkUserColors(colorUser){
if(terminal.colors){
for(var name in colorUser){
colorUser[name]= setUserColor(colorUser[name]);
}
}
else{
throw new Error("There is no colors object defined");
}
} | javascript | {
"resource": ""
} |
q43627 | setOnBlock | train | function setOnBlock(objectName, blockPos){
switch(blockPos){//check where to add in the structure
case 'header':
terminal.header.push(objectName);
break;
case 'body':
terminal.body.push(objectName);
break;
case 'footer':
terminal.footer.push(objectName);
break;
}
} | javascript | {
"resource": ""
} |
q43628 | checkColors | train | function checkColors(name){
var colors=Object.getOwnPropertyNames(terminal.colors);
var bul=false; // boolean to control if its defined the property
for(var i=0; i<colors.length; i++){//iterate over prop names
if(colors[i] === name){//if it is
bul=true;
}
}
if(bul!==true){//if its finded the statement of the tag
terminal.colors[name]=terminal.colors.default;
}
} | javascript | {
"resource": ""
} |
q43629 | checkProperties | train | function checkProperties(name){
var bul=false; // boolean to control if its defined the property
for(var i=0; i<properties.length; i++){//iterate over prop names
if(properties[i] === name){//if it is
bul=true;
}
}
if(bul!==true){// it isn't finded the statement of the tag
throw new Error('Not defined '+name);
}
} | javascript | {
"resource": ""
} |
q43630 | aError | train | function aError(errorObject){
if(!terminal.symbolProgress) terminal.symbolProgress="? ";
if(errorObject.aux){
if(!terminal.colors.aux) terminal.colors.aux= chalk.white;
console.log(terminal.colors.error(terminal.symbolProgress+" Error: "+errorObject.message)+ " " +terminal.colors.aux(errorObject.aux));
console.log();
}
else{
console.log(terminal.colors.error(terminal.symbolProgress+" Error: "+errorObject.message));
console.log();
}
} | javascript | {
"resource": ""
} |
q43631 | aSuccess | train | function aSuccess(errorObject){
if(!terminal.symbolProgress) terminal.symbolProgress="? ";
if(errorObject.aux){
if(!terminal.colors.aux) terminal.colors.aux= chalk.white;
console.log(terminal.colors.success(terminal.symbolProgress+" Success: "+errorObject.message) +" " +terminal.colors.aux(errorObject.aux));
console.log();
}
else{
console.log(terminal.colors.success(terminal.symbolProgress+" Success: "+errorObject.message));
console.log();
}
} | javascript | {
"resource": ""
} |
q43632 | aWarning | train | function aWarning(errorObject){
if(!terminal.symbolProgress) terminal.symbolProgress="? ";
if(errorObject.aux){
if(!terminal.colors.aux) terminal.colors.aux= chalk.white;
console.log(terminal.colors.warning(terminal.symbolProgress+" Warning: "+errorObject.message)+" " +terminal.colors.aux(errorObject.aux));
console.log();
}
else{
console.log(terminal.colors.warning(terminal.symbolProgress+" Warning: "+errorObject.message));
console.log();
}
} | javascript | {
"resource": ""
} |
q43633 | addStaticAssetRoute | train | function addStaticAssetRoute(server, scaffold) {
assert(scaffold.path, `TransomScaffold staticRoute requires "path" to be specified.`);
const contentFolder = scaffold.folder || path.sep;
const serveStatic = scaffold.serveStatic || restify.plugins.serveStatic;
const defaultAsset = scaffold.defaultAsset || 'index.html';
const appendRequestPath = (scaffold.appendRequestPath === false ? false : true); // default true
// When we are running tests, the path to our assets will be different.
// We create the path using NODE_ENV which should be set to TESTING.
let directory = path.join(__dirname, '..', '..', '..', '..', contentFolder);
if ((process.env.NODE_ENV || '').toUpperCase() === 'TESTING') {
directory = path.join(__dirname, "..", contentFolder);
}
debug(`Path ${scaffold.path} is serving static assets from ${directory}`);
server.get(scaffold.path, serveStatic({
directory,
appendRequestPath,
default: defaultAsset
}));
} | javascript | {
"resource": ""
} |
q43634 | addRedirectRoute | train | function addRedirectRoute(server, scaffold) {
assert(scaffold.path && scaffold.target, `TransomScaffold redirectRoute requires 'path' and 'target' to be specified.`);
server.get(scaffold.path, function (req, res, next) {
res.redirect(scaffold.target, next);
});
} | javascript | {
"resource": ""
} |
q43635 | addTemplateRoute | train | function addTemplateRoute(server, scaffold) {
server.get(scaffold.path, function (req, res, next) {
const transomTemplate = server.registry.get(scaffold.templateHandler);
const contentType = scaffold.contentType || 'text/html';
const p = new Promise(function (resolve, reject) {
// Push request headers and params into the data going to the template.
const data = scaffold.data || {};
data.headers = req.headers;
data.params = req.params;
resolve(transomTemplate.renderHtmlTemplate(scaffold.templateName, data));
}).then(function (pageData) {
res.setHeader('content-type', contentType);
res.end(pageData);
next(false); // false stops the chain.
}).catch(function (err) {
next(err);
});
});
} | javascript | {
"resource": ""
} |
q43636 | resolveNodeSkel | train | function resolveNodeSkel(index, nodeName) {
var idx = +graph.nameToIndex[nodeName];
argh = [idx, +index]
if(Number.isNaN(idx)) {
throw "Unable to get index for node '" + nodeName + "'. (Is the node name misspelled?)";
}
if(index !== undefined && idx > +index) {
throw "Unable to get index for node '" + nodeName + "'. (Are the nodes out of order?)";
}
if(index !== undefined && idx == +index) {
throw "Unable to get index for node '" + nodeName + "'. (Is the node trying to reference itself?)";
}
return (dataContext) => dataContext.values[idx];
} | javascript | {
"resource": ""
} |
q43637 | resolveValueOrNodeSkel | train | function resolveValueOrNodeSkel(index, val, valDefault) {
switch (typeof(val)) {
case "string":
return resolveNodeSkel(index, val);
case "undefined":
if (valDefault === undefined) {
throw "Unable to get value'" + val + "'";
}
return () => valDefault;
default:
return () => val;
}
} | javascript | {
"resource": ""
} |
q43638 | initialize | train | function initialize() {
var scene = ds = exports.ds = {
"time": 0,
"song": null,
"graph": null,
"shaders": {},
"textures": {},
"texturesToLoad": 0,
"audio": { "loaded": false, "playing": false },
"isLoaded": function() {
return this.graph !== null && this.texturesToLoad === 0 && this.audio.loaded === true;
},
"next": null
};
scene.gl = initializeWebGL();
initAudio(scene.audio);
initUI(scene);
scene.shaders.sprite = createGlslProgram(scene.gl, "vertexShaderSprite", "fragmentShaderSprite");
scene.shaders.particle = createGlslProgram(scene.gl, "vertexShaderParticle", "fragmentShaderParticle");
window.requestAnimationFrame(animationFrame.bind(null, scene));
} | javascript | {
"resource": ""
} |
q43639 | sumObjectValues | train | function sumObjectValues(object, depth, level = 1) {
let sum = 0;
for (const i in object) {
const value = object[i];
if (isNumber(value)) {
sum += parseFloat(value);
} else if (isObject(value) && (depth < 1 || depth > level)) {
sum += sumObjectValues(value, depth, ++level);
--level;
}
}
return sum;
} | javascript | {
"resource": ""
} |
q43640 | sumov | train | function sumov(object, depth = 0) {
if (isNumber(object)) {
return parseFloat(object);
} else if (isObject(object) && Number.isInteger(depth)) {
return sumObjectValues(object, depth);
}
return 0;
} | javascript | {
"resource": ""
} |
q43641 | shuffleObjArrays | train | function shuffleObjArrays( map, options ) {
var newMap = !! options && true === options.copy ? {} : map;
var copyNonArrays = !! options && true === options.copy && true === ( options.copyNonArrays || options.copyNonArray );
var values = null;
for ( var key in map ) {
values = map[ key ];
if ( isArray( values ) ) {
newMap[ key ] = shuffle( values, options );
} else if ( copyNonArrays ) {
newMap[ key ] = map[ key ];
}
}
return newMap;
} | javascript | {
"resource": ""
} |
q43642 | crypto_stream_salsa20_xor | train | function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {
var z = new Uint8Array(16), x = new Uint8Array(64);
var u, i;
for (i = 0; i < 16; i++) z[i] = 0;
for (i = 0; i < 8; i++) z[i] = n[i];
while (b >= 64) {
crypto_core_salsa20(x,z,k,sigma);
for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];
u = 1;
for (i = 8; i < 16; i++) {
u = u + (z[i] & 0xff) | 0;
z[i] = u & 0xff;
u >>>= 8;
}
b -= 64;
cpos += 64;
mpos += 64;
}
if (b > 0) {
crypto_core_salsa20(x,z,k,sigma);
for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];
}
return 0;
} | javascript | {
"resource": ""
} |
q43643 | handler | train | function handler(instance, context, func, index, callback) {
return function() {
var old = instance.results[index];
instance.results[index] = tryExpr(func, context);
if (old === instance.results[index])
return;
if (instance.dependenciesCount === 1 || !Interpolable.allowDelayedUpdate)
callback(instance.output(context), 'set');
else if (!instance.willFire)
instance.willFire = context.delay(function() { // call on nextTick to manage other dependencies update without multiple rerender
if (instance.willFire) {
instance.willFire = null;
callback(instance.output(context), 'set');
}
}, 0);
};
} | javascript | {
"resource": ""
} |
q43644 | directOutput | train | function directOutput(context) {
var o = tryExpr(this.parts[1].func, context);
return (typeof o === 'undefined' && !this._strict) ? '' : o;
} | javascript | {
"resource": ""
} |
q43645 | train | function(context, callback, binds) {
var instance = new Instance(this);
var count = 0,
binded = false;
for (var i = 1, len = this.parts.length; i < len; i = i + 2) {
var block = this.parts[i];
if (block.binded) {
binded = true;
var h = handler(instance, context, block.func, count, callback),
dep = block.dep;
for (var j = 0, lenJ = dep.length; j < lenJ; j++)
context.subscribe(dep[j], h, false, instance.binds);
}
count++;
}
if (binded && binds)
binds.push(unsub(instance));
return instance;
} | javascript | {
"resource": ""
} | |
q43646 | train | function(context) {
if (this.directOutput)
return this.directOutput(context);
var out = "",
odd = true,
parts = this.parts;
for (var j = 0, len = parts.length; j < len; ++j) {
if (odd)
out += parts[j];
else {
var r = tryExpr(parts[j].func, context);
if (typeof r === 'undefined') {
if (this._strict)
return;
out += '';
}
out += r;
}
odd = !odd;
}
return out;
} | javascript | {
"resource": ""
} | |
q43647 | tree | train | function tree(app, options) {
var opts = extend({}, options);
var node = {
label: getLabel(app, opts),
metadata: getMetadata(app, opts)
};
// get the names of the children to lookup
var names = arrayify(opts.names || ['nodes']);
return names.reduce(function(acc, name) {
var children = app[name];
if (typeof children !== 'object') {
return node;
}
// build a tree for each child node
var nodes = [];
for (var key in children) {
var child = children[key];
if (typeof child[opts.method] === 'function') {
nodes.push(child[opts.method](opts));
} else {
var res = tree(child, opts);
nodes.push(res);
}
}
if (nodes.length) {
node.nodes = (node.nodes || []).concat(nodes);
}
return node;
}, node);
} | javascript | {
"resource": ""
} |
q43648 | getLabel | train | function getLabel(app, options) {
if (typeof options.getLabel === 'function') {
return options.getLabel(app, options);
}
return app.full_name || app.nickname || app.name;
} | javascript | {
"resource": ""
} |
q43649 | train | function(template, templateUrl) {
var deferred = $q.defer();
if (template) {
deferred.resolve(template);
} else if (templateUrl) {
// Check to see if the template has already been loaded.
var cachedTemplate = $templateCache.get(templateUrl);
if (cachedTemplate) {
deferred.resolve(cachedTemplate);
} else {
// If not, let's grab the template for the first time.
$http.get(templateUrl).then(function(result) {
// Save template into the cache and return the template.
$templateCache.put(templateUrl, result.data);
deferred.resolve(result.data);
}, function(error) {
deferred.reject(error);
});
}
} else {
deferred.reject('No template or templateUrl has been specified.');
}
return deferred.promise;
} | javascript | {
"resource": ""
} | |
q43650 | train | function(e) {
this.touch.cur = 'dragging';
var delta = 0;
if (this.touch.lastY && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) {
//tilt
delta = e.gesture.deltaY - this.touch.lastY;
this.angleX += delta;
} else if (this.touch.lastX && (e.gesture.direction == 'left' || e.gesture.direction == 'right')) {
//pan
delta = e.gesture.deltaX - this.touch.lastX;
this.angleZ += delta;
}
if (delta)
this.onDraw();
this.touch.lastX = e.gesture.deltaX;
this.touch.lastY = e.gesture.deltaY;
} | javascript | {
"resource": ""
} | |
q43651 | train | function(e) {
this.touch.cur = 'shifting';
var factor = 5e-3;
var delta = 0;
if (this.touch.lastY && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) {
this.touch.shiftControl
.removeClass('shift-horizontal')
.addClass('shift-vertical')
.css('top', e.gesture.center.pageY + 'px');
delta = e.gesture.deltaY - this.touch.lastY;
this.viewpointY -= factor * delta * this.viewpointZ;
this.angleX += delta;
}
if (this.touch.lastX && (e.gesture.direction == 'left' || e.gesture.direction == 'right')) {
this.touch.shiftControl
.removeClass('shift-vertical')
.addClass('shift-horizontal')
.css('left', e.gesture.center.pageX + 'px');
delta = e.gesture.deltaX - this.touch.lastX;
this.viewpointX += factor * delta * this.viewpointZ;
this.angleZ += delta;
}
if (delta)
this.onDraw();
this.touch.lastX = e.gesture.deltaX;
this.touch.lastY = e.gesture.deltaY;
} | javascript | {
"resource": ""
} | |
q43652 | train | function(initial_csg) {
var csg = initial_csg.canonicalized();
var mesh = new GL.Mesh({ normals: true, colors: true });
var meshes = [ mesh ];
var vertexTag2Index = {};
var vertices = [];
var colors = [];
var triangles = [];
// set to true if we want to use interpolated vertex normals
// this creates nice round spheres but does not represent the shape of
// the actual model
var smoothlighting = this.solid.smooth;
var polygons = csg.toPolygons();
var numpolygons = polygons.length;
for(var j = 0; j < numpolygons; j++) {
var polygon = polygons[j];
var color = this.solid.color; // default color
if(polygon.shared && polygon.shared.color) {
color = polygon.shared.color;
} else if(polygon.color) {
color = polygon.color;
}
if (color.length < 4)
color.push(1.); //opaque
var indices = polygon.vertices.map(function(vertex) {
var vertextag = vertex.getTag();
var vertexindex = vertexTag2Index[vertextag];
var prevcolor = colors[vertexindex];
if(smoothlighting && (vertextag in vertexTag2Index) &&
(prevcolor[0] == color[0]) &&
(prevcolor[1] == color[1]) &&
(prevcolor[2] == color[2])
) {
vertexindex = vertexTag2Index[vertextag];
} else {
vertexindex = vertices.length;
vertexTag2Index[vertextag] = vertexindex;
vertices.push([vertex.pos.x, vertex.pos.y, vertex.pos.z]);
colors.push(color);
}
return vertexindex;
});
for (var i = 2; i < indices.length; i++) {
triangles.push([indices[0], indices[i - 1], indices[i]]);
}
// if too many vertices, start a new mesh;
if (vertices.length > 65000) {
// finalize the old mesh
mesh.triangles = triangles;
mesh.vertices = vertices;
mesh.colors = colors;
mesh.computeWireframe();
mesh.computeNormals();
if ( mesh.vertices.length ) {
meshes.push(mesh);
}
// start a new mesh
mesh = new GL.Mesh({ normals: true, colors: true });
triangles = [];
colors = [];
vertices = [];
}
}
// finalize last mesh
mesh.triangles = triangles;
mesh.vertices = vertices;
mesh.colors = colors;
mesh.computeWireframe();
mesh.computeNormals();
if ( mesh.vertices.length ) {
meshes.push(mesh);
}
return meshes;
} | javascript | {
"resource": ""
} | |
q43653 | train | function(err, objs) {
that.worker = null;
if(err) {
that.setError(err);
that.setStatus("Error.");
that.state = 3; // incomplete
} else {
that.setCurrentObjects(objs);
that.setStatus("Ready.");
that.state = 2; // complete
}
that.enableItems();
} | javascript | {
"resource": ""
} | |
q43654 | runBranch | train | function runBranch (index, options) {
var { tree, signal, start, promise } = options;
var currentBranch = tree.branches[index];
if (!currentBranch && tree.branches === signal.branches) {
if (tree.branches[index - 1]) {
tree.branches[index - 1].duration = Date.now() - start;
}
signal.isExecuting = false;
if (promise) {
promise.resolve(signal);
}
return;
}
if (!currentBranch) {
return;
}
if (Array.isArray(currentBranch)) {
return runAsyncBranch(index, currentBranch, options);
} else {
return runSyncBranch(index, currentBranch, options);
}
} | javascript | {
"resource": ""
} |
q43655 | runAsyncBranch | train | function runAsyncBranch (index, currentBranch, options) {
var { tree, args, signal, state, promise, start, services } = options;
var promises = currentBranch
.map(action => {
var actionFunc = tree.actions[action.actionIndex];
var actionArgs = createActionArgs(args, action, state, true);
var outputs = action.outputs ? Object.keys(action.outputs) : [];
action.isExecuting = true;
action.args = merge({}, args);
var nextActionPromise;
var foundResult = signal.asyncActionResults.find((result) => isEqualArrays(result.outputPath, action.path));
// If actions results provided, you run it in replay mode
if (foundResult) {
nextActionPromise = Promise.resolve(foundResult);
} else {
var next = createNextAsyncAction(actionFunc, outputs);
actionFunc.apply(null, actionArgs.concat(next.fn, services));
nextActionPromise = next.promise;
}
return nextActionPromise
.then(result => {
action.hasExecuted = true;
action.isExecuting = false;
action.output = result.args;
// Save short results snippet for replay
signal.asyncActionResults.push({
outputPath: action.path,
path: result.path,
args: result.args
});
merge(args, result.args);
if (result.path) {
action.outputPath = result.path;
var output = action.outputs[result.path];
return runBranch(0, {
args, signal, state, start, promise, services,
tree: {
actions: tree.actions,
branches: output
}
});
}
})
.catch((e) => promise.reject(e));
});
return Promise.all(promises)
.then(() => runBranch(index + 1, options));
} | javascript | {
"resource": ""
} |
q43656 | runSyncBranch | train | function runSyncBranch (index, currentBranch, options) {
var { args, tree, signal, state, start, promise, services } = options;
try {
var action = currentBranch;
var actionFunc = tree.actions[action.actionIndex];
var actionArgs = createActionArgs(args, action, state, false);
var outputs = action.outputs ? Object.keys(action.outputs) : [];
action.mutations = [];
action.args = merge({}, args);
var next = createNextSyncAction(actionFunc, outputs);
actionFunc.apply(null, actionArgs.concat(next, services));
var result = next._result || {};
merge(args, result.args);
action.isExecuting = false;
action.hasExecuted = true;
action.output = result.args;
if (result.path) {
action.outputPath = result.path;
var output = action.outputs[result.path];
var runResult = runBranch(0, {
args, signal, state, start, promise, services,
tree: {
actions: tree.actions,
branches: output
}
});
if (runResult && runResult.then) {
return runResult.then(() => {
return runBranch(index + 1, options);
});
}
return runBranch(index + 1, options);
}
return runBranch(index + 1, options);
} catch (e) {
promise.reject(e);
}
} | javascript | {
"resource": ""
} |
q43657 | addOutputs | train | function addOutputs (next, outputs) {
if (Array.isArray(outputs)) {
outputs.forEach(key => {
next[key] = next.bind(null, key);
});
}
return next;
} | javascript | {
"resource": ""
} |
q43658 | createNextFunction | train | function createNextFunction (action, resolver) {
return function next (...args) {
var path = typeof args[0] === 'string' ? args[0] : null;
var arg = path ? args[1] : args[0];
var result = {
path: path ? path : action.defaultOutput,
args: arg
};
if (resolver) {
resolver(result);
} else {
next._result = result;
}
};
} | javascript | {
"resource": ""
} |
q43659 | getStateMutatorsAndAccessors | train | function getStateMutatorsAndAccessors (state, action, isAsync) {
var mutators = [
'apply',
'concat',
'deepMerge',
'push',
'merge',
'unset',
'set',
'splice',
'unshift'
];
var accessors = [
'get',
'exists'
];
var methods = [];
if (isAsync) {
methods = methods.concat(accessors);
} else {
methods = methods.concat(mutators);
methods = methods.concat(accessors);
}
return methods.reduce((stateMethods, methodName) => {
var method = state[methodName].bind(state);
stateMethods[methodName] = (...args) => {
var path = [];
var firstArg = args[0];
if (Array.isArray(firstArg)) {
path = args.shift();
} else if (typeof firstArg === 'string') {
path = [args.shift()];
}
if (args.length === 0) {
return method.apply(null, [path.slice()]);
}
action.mutations.push({
name: methodName,
path: path.slice(),
args: args
});
return method.apply(null, [path.slice()].concat(args));
};
return stateMethods;
}, Object.create(null));
} | javascript | {
"resource": ""
} |
q43660 | staticTree | train | function staticTree (signalActions) {
var actions = [];
var branches = transformBranch(signalActions, [], [], actions, false);
return { actions, branches };
} | javascript | {
"resource": ""
} |
q43661 | transformBranch | train | function transformBranch (action, ...args) {
return Array.isArray(action) ?
transformAsyncBranch.apply(null, [action, ...args]) :
transformSyncBranch.apply(null, [action, ...args]);
} | javascript | {
"resource": ""
} |
q43662 | transformAsyncBranch | train | function transformAsyncBranch (action, parentAction, path, actions, isSync) {
action = action.slice();
isSync = !isSync;
return action
.map((subAction, index) => {
path.push(index);
var result = transformBranch(subAction, action, path, actions, isSync);
path.pop();
return result;
})
.filter(branch => !!branch);
} | javascript | {
"resource": ""
} |
q43663 | transformSyncBranch | train | function transformSyncBranch (action, parentAction, path, actions, isSync) {
var branch = {
name: getFunctionName(action),
args: {},
output: null,
duration: 0,
mutations: [],
isAsync: !isSync,
outputPath: null,
isExecuting: false,
hasExecuted: false,
path: path.slice(),
outputs: null,
actionIndex: actions.indexOf(action) === -1 ? actions.push(action) - 1 : actions.indexOf(action)
};
var nextAction = parentAction[parentAction.indexOf(action) + 1];
if (!Array.isArray(nextAction) && typeof nextAction === 'object') {
parentAction.splice(parentAction.indexOf(nextAction), 1);
branch.outputs = Object.keys(nextAction)
.reduce((paths, key) => {
path = path.concat('outputs', key);
paths[key] = transformBranch(nextAction[key], parentAction, path, actions, false);
path.pop();
path.pop();
return paths;
}, {});
}
return branch;
} | javascript | {
"resource": ""
} |
q43664 | analyze | train | function analyze (actions) {
if (!Array.isArray(actions)) {
throw new Error('State: Signal actions should be array');
}
actions.forEach((action, index) => {
if (typeof action === 'undefined' || typeof action === 'string') {
throw new Error(
`
State: Action number "${index}" in signal does not exist.
Check that you have spelled it correctly!
`
);
}
if (Array.isArray(action)) {
analyze(action);
} else if (Object.prototype.toString.call(action) === "[object Object]") {
Object.keys(action).forEach(function (output) {
analyze(action[output]);
});
}
});
} | javascript | {
"resource": ""
} |
q43665 | getFunctionName | train | function getFunctionName (fn) {
var name = fn.toString();
name = name.substr('function '.length);
name = name.substr(0, name.indexOf('('));
return name;
} | javascript | {
"resource": ""
} |
q43666 | Player | train | function Player(params) {
this.platformID = this.key = params.key;
this.kills = params.kills;
this.deaths = params.deaths;
this.name = params.name;
this.rank = params.rank;
this.weapon = params.weapon;
} | javascript | {
"resource": ""
} |
q43667 | Cms | train | function Cms(module, with_app) {
if (!module)
throw new Error('Requires a module');
if (!module.config)
throw new Error('Module requires config');
if (!module.config.name)
logger.info('No name specified in config. Calling it null.')
if (!module.config.mongoConnectString)
throw new Error('Config requires mongoConnectString');
if (!module.models)
throw new Error('Module requires models');
// module info and shortcut to configuration
this.module = module;
this.config = module.config;
// connection to mongo
this.connection = null;
// the storage client
this.client = null;
// gridfs storage (untested)
this.gfs = null;
// the express app
this.app = null;
// login, logout
this.auth = null;
// meta info for models
this.meta = null;
// guard manages view permissions
this.guard = null;
// workflow provides state transition info to view
this.workflow = null;
logger.info('cms init');
//process.nextTick(this._init.bind(this));
this._init(with_app === undefined ? true : with_app);
} | javascript | {
"resource": ""
} |
q43668 | handlePromise | train | function handlePromise(query, q, model, resultsPerPage) {
return Promise.all([
query.exec(),
model.count(q).exec()
]).spread(function(results, count) {
return [
results,
Math.ceil(count / resultsPerPage) || 1,
count
]
});
} | javascript | {
"resource": ""
} |
q43669 | handleCallback | train | function handleCallback(query, q, model, resultsPerPage, callback) {
return async.parallel({
results: function(callback) {
query.exec(callback);
},
count: function(callback) {
model.count(q, function(err, count) {
callback(err, count);
});
}
}, function(error, data) {
if (error) {
return callback(error);
}
callback(null, data.results, Math.ceil(data.count / resultsPerPage) || 1, data.count);
});
} | javascript | {
"resource": ""
} |
q43670 | foreachInDir | train | function foreachInDir (dirpath, fnc, done) {
// Read the files
fs.readdir(dirpath, function (err, files) {
// Return error
if (err) {
return done(err);
}
// Process each file
parallel(files.map(function (f) {
return fnc.bind(null, f);
}), done);
});
} | javascript | {
"resource": ""
} |
q43671 | rdf | train | function rdf(argv, callback) {
var command = argv[2];
var exec;
if (!command) {
console.log('rdf help for command list');
process.exit(-1);
}
try {
exec = require('./bin/' + command + '.js');
} catch (err) {
console.error(command + ': command not found');
process.exit(-1);
}
argv.splice(2, 1);
exec(argv, callback);
} | javascript | {
"resource": ""
} |
q43672 | bin | train | function bin() {
rdf(process.argv, function(err, res) {
if (Array.isArray(res)) {
for (var i=0; i<res.length; i++) {
console.log(res[i]);
}
} else {
console.log(res);
}
});
} | javascript | {
"resource": ""
} |
q43673 | update | train | function update(options) {
var reqOpt = {
host: url.parse(options.updateVersionURL).host,
uri: url.parse(options.updateVersionURL),
path: url.parse(options.updateVersionURL).pathname,
port: options.port
};
options.error = options.error || function () {
};
options.success = options.success || function () {
};
doLog = options.log || false;
log(doLog);
_handleUpdateProcess(reqOpt, options);
} | javascript | {
"resource": ""
} |
q43674 | train | function(start, end, query) {
//console.log("deep.store.Collection.range : ", start, end, query);
var res = null;
var total = 0;
query = query || "";
return deep.when(this.get(query))
.done(function(res) {
total = res.length;
if (typeof start === 'string')
start = parseInt(start);
if (typeof end === 'string')
end = parseInt(end);
start = Math.min(start, total);
res = res.slice(start, end + 1);
end = start + res.length - 1;
query += "&limit(" + (res.length) + "," + start + ")";
return ranger.createRangeObject(start, end, total, res.length, deep.utils.copy(res), query);
});
} | javascript | {
"resource": ""
} | |
q43675 | train | function (lintFile) {
var deferred = new Deferred();
parseJslintXml(lintFile, function (err, lintErrors) {
if (lintErrors) {
deferred.resolve(lintErrors);
} else {
if (err && err.code === 'ENOENT') {
console.warn('No jslint xml file found at:', lintFile);
} else if (err) {
console.log(err);
}
deferred.reject();
}
});
return deferred.promise;
} | javascript | {
"resource": ""
} | |
q43676 | train | function (lintFile, callback) {
fs.readFile(lintFile, function (err, data) {
if (err) {
callback(err);
} else {
var parser = new xml2js.Parser({
mergeAttrs: true
});
parser.parseString(data, function (err, result) {
if (err) {
callback(err);
} else if (result && result.jslint) {
callback(null, result.jslint.file);
} else {
callback('Invalid jslint xml file');
}
});
}
});
} | javascript | {
"resource": ""
} | |
q43677 | train | function (req, res, lintErrors) {
var html = template({
lintErrors: lintErrors
});
res.end(html);
} | javascript | {
"resource": ""
} | |
q43678 | train | function(predicate, asyncFunction) {
if (predicate()) {
return asyncFunction().then(function() {
return Parse.Promise._continueWhile(predicate, asyncFunction);
});
}
return Parse.Promise.as();
} | javascript | {
"resource": ""
} | |
q43679 | train | function(resolvedCallback, rejectedCallback) {
var promise = new Parse.Promise();
var wrappedResolvedCallback = function() {
var result = arguments;
if (resolvedCallback) {
result = [resolvedCallback.apply(this, result)];
}
if (result.length === 1 && Parse.Promise.is(result[0])) {
result[0].then(function() {
promise.resolve.apply(promise, arguments);
}, function(error) {
promise.reject(error);
});
} else {
promise.resolve.apply(promise, result);
}
};
var wrappedRejectedCallback = function(error) {
var result = [];
if (rejectedCallback) {
result = [rejectedCallback(error)];
if (result.length === 1 && Parse.Promise.is(result[0])) {
result[0].then(function() {
promise.resolve.apply(promise, arguments);
}, function(error) {
promise.reject(error);
});
} else {
// A Promises/A+ compliant implementation would call:
// promise.resolve.apply(promise, result);
promise.reject(result[0]);
}
} else {
promise.reject(error);
}
};
if (this._resolved) {
wrappedResolvedCallback.apply(this, this._result);
} else if (this._rejected) {
wrappedRejectedCallback(this._error);
} else {
this._resolvedCallbacks.push(wrappedResolvedCallback);
this._rejectedCallbacks.push(wrappedRejectedCallback);
}
return promise;
} | javascript | {
"resource": ""
} | |
q43680 | train | function(optionsOrCallback, model) {
var options;
if (_.isFunction(optionsOrCallback)) {
var callback = optionsOrCallback;
options = {
success: function(result) {
callback(result, null);
},
error: function(error) {
callback(null, error);
}
};
} else {
options = _.clone(optionsOrCallback);
}
options = options || {};
return this.then(function(result) {
if (options.success) {
options.success.apply(this, arguments);
} else if (model) {
// When there's no callback, a sync event should be triggered.
model.trigger('sync', model, result, options);
}
return Parse.Promise.as.apply(Parse.Promise, arguments);
}, function(error) {
if (options.error) {
if (!_.isUndefined(model)) {
options.error(model, error);
} else {
options.error(error);
}
} else if (model) {
// When there's no error callback, an error event should be triggered.
model.trigger('error', model, error, options);
}
// By explicitly returning a rejected Promise, this will work with
// either jQuery or Promises/A semantics.
return Parse.Promise.error(error);
});
} | javascript | {
"resource": ""
} | |
q43681 | train | function( s ){
if( s.match(/\./ ) ){
var l = s.split( /\./ );
for( var i = 0; i < l.length-1; i++ ){
l[ i ] = '_children.' + l[ i ];
}
return l.join( '.' );
} else {
return s;
}
} | javascript | {
"resource": ""
} | |
q43682 | train | function( filters, fieldPrefix, selectorWithoutBells ){
return {
querySelector: this._makeMongoConditions( filters.conditions || {}, fieldPrefix, selectorWithoutBells ),
sortHash: this._makeMongoSortHash( filters.sort || {}, fieldPrefix )
};
} | javascript | {
"resource": ""
} | |
q43683 | train | function( cb ){
if( ! self.positionField ){
cb( null );
} else {
// If repositioning is required, do it
if( self.positionField ){
var where, beforeId;
if( ! options.position ){
where = 'end';
} else {
where = options.position.where;
beforeId = options.position.beforeId;
}
self.reposition( recordWithLookups, where, beforeId, cb );
}
}
} | javascript | {
"resource": ""
} | |
q43684 | train | function( state ) {
if ( this._.state == state )
return false;
this._.state = state;
var element = CKEDITOR.document.getById( this._.id );
if ( element ) {
element.setState( state, 'cke_button' );
state == CKEDITOR.TRISTATE_DISABLED ?
element.setAttribute( 'aria-disabled', true ) :
element.removeAttribute( 'aria-disabled' );
if ( !this.hasArrow ) {
// Note: aria-pressed attribute should not be added to menuButton instances. (#11331)
state == CKEDITOR.TRISTATE_ON ?
element.setAttribute( 'aria-pressed', true ) :
element.removeAttribute( 'aria-pressed' );
} else {
var newLabel = state == CKEDITOR.TRISTATE_ON ?
this._.editor.lang.button.selectedLabel.replace( /%1/g, this.label ) : this.label;
CKEDITOR.document.getById( this._.id + '_label' ).setText( newLabel );
}
return true;
} else
return false;
} | javascript | {
"resource": ""
} | |
q43685 | rPath | train | function rPath (htmlyFile, sourceFilepath) {
htmlyFile = pathResolve(__dirname, htmlyFile)
htmlyFile = pathRelative(dirname(sourceFilepath), htmlyFile)
htmlyFile = slash(htmlyFile)
if (!/^(\.|\/)/.test(htmlyFile)) {
return './' + htmlyFile
} else {
return htmlyFile
}
} | javascript | {
"resource": ""
} |
q43686 | warning | train | function warning() {
let sentence = "";
const avoidList = getWords("avoid_list");
const avoid = nu.chooseFrom(avoidList);
const rnum = Math.floor(Math.random() * 10);
if (rnum <= 3) {
sentence = `You would be well advised to avoid ${avoid}`;
} else if (rnum <= 6){
sentence = `Avoid ${avoid} at all costs`;
} else if (rnum <= 8) {
sentence = `Steer clear of ${avoid} for a stress-free week`;
} else {
sentence = `For a peaceful week, avoid ${avoid}`;
}
return nu.sentenceCase(sentence);
} | javascript | {
"resource": ""
} |
q43687 | getIterableObjectEntries | train | function getIterableObjectEntries(obj) {
let index = 0;
const propKeys = Reflect.ownKeys(obj);
return {
[Symbol.iterator]() {
return this;
},
next() {
if (index < propKeys.length) {
const key = propKeys[index];
index += 1;
return {"value": [key, obj[key]]};
}
return {"done": true};
}
};
} | javascript | {
"resource": ""
} |
q43688 | findWhere | train | function findWhere(arr, key, value) {
return arr.find(elem => {
for (const [k, v] of getIterableObjectEntries(elem)) {
if (k === key && v === value) {
return true;
}
}
});
} | javascript | {
"resource": ""
} |
q43689 | findWhereKey | train | function findWhereKey(arr, key) {
return arr.find(elem => {
for (const [k] of getIterableObjectEntries(elem)) {
if (k === key) {
return true;
}
}
});
} | javascript | {
"resource": ""
} |
q43690 | load | train | function load(module) {
var toTransform,
transformedModule = {};
if (typeof module === "string") {
toTransform = require(module);
} else {
toTransform = module;
}
for (var item in toTransform) {
// transform only sync/async methods to promiseable since having utility methods also promiseable
// could do more harm than good.
if (typeof toTransform[item] === "function" && isFunctionPromiseable( toTransform, item, toTransform[item] )) {
transformedModule[item] = rebuildAsPromise( toTransform, item, toTransform[item] );
} else {
transformedModule[item] = toTransform[item];
}
}
return transformedModule;
} | javascript | {
"resource": ""
} |
q43691 | rebuildAsPromise | train | function rebuildAsPromise(_thisObject, name, fn) {
// if is a regular function, that has an async correspondent also make it promiseable
if (!isFunctionAsync(_thisObject, name, fn)) {
return function() {
var that = this,
args = arguments;
return blinkts.lang.promiseCode(function() {
return fn.apply(that, args);
});
};
}
// if it's an async function, make it promiseable.
return function() {
var args = Array.prototype.slice.apply(arguments),
that = this;
return new blinkts.lang.Promise(function(fulfill, reject) {
args.push(function(err, r) {
if (err) {
reject(err);
}
if (arguments.length > 2) { // if the callback received multiple arguments, put them into an array.
fulfill(Array.prototype.slice.call(arguments, 1));
} else {
fulfill(r);
}
});
try {
var result = fn.apply(that, args);
} catch (e) { // if the function failed, so we don't get a chance to get our callback called.
reject(e);
}
});
};
} | javascript | {
"resource": ""
} |
q43692 | train | function(err, res) {
if (err) return callback(err);
self._rawResponse = res;
if (!res || !res['cps:reply']) return callback(new Error("Invalid reply"));
self.seconds = res['cps:reply']['cps:seconds'];
if (res['cps:reply']['cps:content']) {
var content = res['cps:reply']['cps:content'];
self = _.merge(self, content);
}
callback(res['cps:reply']['cps:error'], self);
} | javascript | {
"resource": ""
} | |
q43693 | TypedNumber | train | function TypedNumber (config) {
const number = this;
// validate min
if (config.hasOwnProperty('min') && !util.isNumber(config.min)) {
const message = util.propertyErrorMessage('min', config.min, 'Must be a number.');
throw Error(message);
}
// validate max
if (config.hasOwnProperty('max') && !util.isNumber(config.max)) {
const message = util.propertyErrorMessage('max', config.max, 'Must be a number.');
throw Error(message);
}
// validate max is greater than min
if (config.hasOwnProperty('max') && config.hasOwnProperty('min') && config.min > config.max) {
const message = util.propertyErrorMessage('max', config.max, 'Must be a number that is less than the minimum: ' + config.min + '.');
throw Error(message);
}
// define properties
Object.defineProperties(number, {
exclusiveMax: {
/**
* @property
* @name TypedNumber#exclusiveMax
* @type {boolean}
*/
value: !!config.exclusiveMax,
writable: false
},
exclusiveMin: {
/**
* @property
* @name TypedNumber#exclusiveMin
* @type {boolean}
*/
value: !!config.exclusiveMin,
writable: false
},
integer: {
/**
* @property
* @name TypedNumber#integer
* @type {boolean}
*/
value: !!config.integer,
writable: false
},
max: {
/**
* @property
* @name TypedNumber#max
* @type {number}
*/
value: Number(config.max),
writable: false
},
min: {
/**
* @property
* @name TypedNumber#min
* @type {number}
*/
value: Number(config.min),
writable: false
}
});
return number;
} | javascript | {
"resource": ""
} |
q43694 | recursiveMapping | train | function recursiveMapping(source) {
if (source.type === 'array') {
if (source.items['$ref'] || source.items.type === 'object') {
source.items = mapSimpleField(source.items);
}
else if (source.items.type === 'object') {
recursiveMapping(source.items);
}
else mapSimpleField(source);
}
else if (source.type === 'object') {
for (var property in source.properties) {
if (source.properties[property]['$ref']) {
source.properties[property] = mapSimpleField(source.properties[property]);
}
else if (source.properties[property].type === 'object' || source.properties[property].type === 'array') {
recursiveMapping(source.properties[property]);
}
}
}
else if (source.schema) {
if (source.schema.type === 'object') {
for (var property in source.schema.properties) {
if (source.schema.properties[property]['$ref']) {
source.schema.properties[property] = mapSimpleField(source.schema.properties[property]);
}
}
}
}
else {
//map simple inputs if any
source = mapSimpleField(source);
}
} | javascript | {
"resource": ""
} |
q43695 | train | function (yamlContent, context, callback) {
var jsonAPISchema;
try {
jsonAPISchema = yamljs.parse(yamlContent);
}
catch (e) {
return callback({"code": 851, "msg": e.message});
}
try {
swagger.validateYaml(jsonAPISchema);
}
catch (e) {
return callback({"code": 173, "msg": e.message});
}
context.yaml = jsonAPISchema;
swagger.mapAPis(jsonAPISchema, function (response) {
context.soajs.config.schema = response.schema;
context.soajs.config.errors = response.errors;
var myValidator = new Validator();
var check = myValidator.validate(context.soajs.config, schema);
if (check.valid) {
return callback(null, true);
}
else {
var errMsgs = [];
check.errors.forEach(function (oneError) {
errMsgs.push(oneError.stack);
});
return callback({"code": 172, "msg": new Error(errMsgs.join(" - ")).message});
}
});
} | javascript | {
"resource": ""
} | |
q43696 | train | function (yamlJson) {
if (typeof yamlJson !== 'object') {
throw new Error("Yaml file was converted to a string");
}
if (!yamlJson.paths || Object.keys(yamlJson.paths).length === 0) {
throw new Error("Yaml file is missing api schema");
}
//loop in path
for (var onePath in yamlJson.paths) {
//loop in methods
for (var oneMethod in yamlJson.paths[onePath]) {
if (!yamlJson.paths[onePath][oneMethod].summary || yamlJson.paths[onePath][oneMethod].summary === "") {
throw new Error("Please enter a summary for API " + oneMethod + ": " + onePath + " you want to build.");
}
}
}
} | javascript | {
"resource": ""
} | |
q43697 | train | function (obj) {
if (typeof obj !== "object" || obj === null) {
return obj;
}
if (obj instanceof Date) {
return new Date(obj.getTime());
}
if (obj instanceof RegExp) {
return new RegExp(obj);
}
if (obj instanceof Array && Object.keys(obj).every(function (k) {
return !isNaN(k);
})) {
return obj.slice(0);
}
var _obj = {};
for (var attr in obj) {
if (Object.hasOwnProperty.call(obj, attr)) {
_obj[attr] = swagger.cloneObj(obj[attr]);
}
}
return _obj;
} | javascript | {
"resource": ""
} | |
q43698 | train | function (serviceInfo) {
var config = {
"type": "service",
"prerequisites": {
"cpu": " ",
"memory": " "
},
"swagger": true,
"injection": true,
"serviceName": serviceInfo.serviceName,
"serviceGroup": serviceInfo.serviceGroup,
"serviceVersion": serviceInfo.serviceVersion,
"servicePort": serviceInfo.servicePort,
"requestTimeout": serviceInfo.requestTimeout,
"requestTimeoutRenewal": serviceInfo.requestTimeoutRenewal,
"extKeyRequired": serviceInfo.extKeyRequired,
"oauth": serviceInfo.oauth,
"session": serviceInfo.session,
"errors": {},
"schema": {}
};
if (serviceInfo.dbs && Array.isArray(serviceInfo.dbs) && serviceInfo.dbs.length > 0) {
config["dbs"] = serviceInfo.dbs;
config["models"] = {
"path": '%__dirname% + "/lib/models/"',
"name": ""
};
var modelProps = Object.keys(serviceInfo.dbs[0]);
if (modelProps.indexOf("mongo") !== -1) {
config.models.name = serviceInfo.dbs[0] = "mongo";
}
else {
config.models.name = serviceInfo.dbs[0] = "es";
}
}
return config;
} | javascript | {
"resource": ""
} | |
q43699 | train | function (yamlJson, cb) {
let all_apis = {};
let all_errors = {};
let paths = reformatPaths(yamlJson.paths);
let definitions = yamlJson.definitions;
let parameters = yamlJson.parameters;
let convertedDefinitions = {};
let convertedParameters = {};
// convert definitions first
if (definitions) {
let definitionsKeys = Object.keys(definitions);
definitionsKeys.forEach(function (eachDef) {
convertedDefinitions[eachDef] = convertItem(null, definitions[eachDef], 1); // 1 ??? definitions should never have schema -=-=-=-=-=
});
}
// convert parameters then
if (parameters) {
let parametersKeys = Object.keys(parameters);
parametersKeys.forEach(function (eachParam) {
convertedParameters[eachParam] = convertItem(convertedDefinitions, parameters[eachParam], 1);
});
all_apis.commonFields = convertedParameters;
}
let pathsKeys = Object.keys(paths);
pathsKeys.forEach(function (eachPath) {
let methods = paths[eachPath];
let methodsKeys = Object.keys(methods);
methodsKeys.forEach(function (eachMethod) {
let apiData = methods[eachMethod];
if (!all_apis[eachMethod]) {
all_apis[eachMethod] = {};
}
var mwFile = eachPath.replace(/\\/g, "_").replace(/:/g, "_").replace(/\//g, "_").replace(/[_]{2,}/g, "_").replace(/{/g, "").replace(/}/g, "");
mwFile = mwFile.toLowerCase();
if (mwFile[0] === "_") {
mwFile = mwFile.substring(1);
}
mwFile += "_" + eachMethod.toLowerCase() + ".js";
all_apis[eachMethod][eachPath] = {
_apiInfo: {},
"mw": '%dirname% + "/lib/mw/' + mwFile + '"'
};
let newSoajsApi = all_apis[eachMethod][eachPath];
let params = apiData.parameters;
let group = apiData.tags ? apiData.tags[0] : "";
newSoajsApi._apiInfo.group = group && group !== '' ? group : "general";
newSoajsApi._apiInfo.l = apiData.summary;
newSoajsApi.imfv = convertParams(convertedDefinitions, convertedParameters, params);
});
});
// todo: convert errors
return cb({"schema": all_apis, "errors": all_errors});
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.