_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q14200
|
serveSassFiles
|
train
|
function serveSassFiles(magnet, outputDir) {
if (!isServingSassFiles) {
magnet.getServer()
.getEngine()
.use('/css', express.static(outputDir));
}
isServingSassFiles = true;
}
|
javascript
|
{
"resource": ""
}
|
q14201
|
getOutputFile
|
train
|
function getOutputFile(file, outputDir) {
const fileName = path.basename(file).replace('.scss', '.css');
return path.join(outputDir, fileName);
}
|
javascript
|
{
"resource": ""
}
|
q14202
|
writeFile
|
train
|
function writeFile(file, css) {
return new Promise((resolve, reject) => {
fs.writeFile(file, css, err => {
if (err) {
return reject(err);
}
resolve();
})
});
}
|
javascript
|
{
"resource": ""
}
|
q14203
|
renderFile
|
train
|
function renderFile(file, config) {
const options = Object.assign({file}, config);
return new Promise((resolve, reject) => {
sass.render(options, (err, result) => {
if (err) {
return reject(err);
}
resolve(result.css);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14204
|
buildSassFiles
|
train
|
async function buildSassFiles(files, outputDir, config) {
const renderedFiles = await Promise.all(files.map(async file => {
const css = await renderFile(file, config);
return {file, css};
}));
await fs.ensureDir(outputDir);
return Promise.all(renderedFiles.map(({file, css}) => {
const outputFile = getOutputFile(file, outputDir);
return writeFile(outputFile, css);
}));
}
|
javascript
|
{
"resource": ""
}
|
q14205
|
range
|
train
|
function range(n,type) {
n = (typeof n !== 'undefined') ? n : 0;
if (!(Number.isInteger(n))) throw Error("Error in range: Value must be an integer");
let array;
if(type=='Uint8') array = new Uint8Array(n);
if(type=='Uint16') array = new Uint16Array(n);
if(type=='Uint32') array = new Uint32Array(n);
if(type=='Int8') array = new Int8Array(n);
if(type=='Int16') array = new Int16Array(n);
if(type=='Int32') array = new Int32Array(n);
if(type=='Float32') array = new Float32Array(n);
if((typeof type === 'undefined') || !array)array = new Array(n);
for(let i=0;i<n;i++)array[i]=i;
return array;
}
|
javascript
|
{
"resource": ""
}
|
q14206
|
_execution
|
train
|
function _execution (spawn, data, options) {
const match = data.match(WATING_STDIN);
if (match) {
if (-1 < match[1].indexOf("Country Name")) {
if (!options.country) {
options.country = match[2] ? match[2] : ".";
}
spawn.stdin.write(options.country + "\n");
}
else if (-1 < match[1].indexOf("Locality Name")) {
if (!options.locality) {
options.locality = match[2] ? match[2] : ".";
}
spawn.stdin.write(options.locality + "\n");
}
else if (-1 < match[1].indexOf("State or Province Name")) {
if (!options.state) {
options.state = match[2] ? match[2] : ".";
}
spawn.stdin.write(options.state + "\n");
}
else if (-1 < match[1].indexOf("Organization Name")) {
if (!options.organization) {
options.organization = match[2] ? match[2] : ".";
}
spawn.stdin.write(options.organization + "\n");
}
else if (-1 < match[1].indexOf("Common Name")) {
if (!options.common) {
options.common = match[2] ? match[2] : ".";
}
spawn.stdin.write(options.common + "\n");
}
else if (-1 < match[1].indexOf("Email Address")) {
if (!options.email) {
options.email = match[2] ? match[2] : ".";
}
spawn.stdin.write(options.email + "\n");
}
else {
spawn.stdin.write(".\n");
}
return "";
}
else {
return data;
}
}
|
javascript
|
{
"resource": ""
}
|
q14207
|
CanvasSurface
|
train
|
function CanvasSurface(options) {
if (options)
options.useTarget = true;
else
options = { useTarget: true };
if (options.canvasSize) this._canvasSize = options.canvasSize;
Surface.apply(this, arguments);
if (!this._canvasSize) this._canvasSize = this.getSize();
this._backBuffer = document.createElement('canvas');
if (this._canvasSize) {
this._backBuffer.width = this._canvasSize[0];
this._backBuffer.height = this._canvasSize[1];
}
this._contextId = undefined;
}
|
javascript
|
{
"resource": ""
}
|
q14208
|
cat
|
train
|
function cat(uri, callback) {
if (!uri) {
callback(new Error('URI is required'))
}
util.get(uri, function(err, val, uri) {
callback(null, val, uri)
})
}
|
javascript
|
{
"resource": ""
}
|
q14209
|
getParamNames
|
train
|
function getParamNames(fn) {
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var fnString = fn.toString().replace(STRIP_COMMENTS, '');
var result = fnString.slice(fnString.indexOf('(') + 1, fnString.indexOf(')')).match(/([^\s,]+)/g);
return result || [];
}
|
javascript
|
{
"resource": ""
}
|
q14210
|
merge_objects
|
train
|
function merge_objects(obj1,obj2){
var obj3 = {};
for (var attrname1 in obj1) { obj3[attrname1] = obj1[attrname1]; }
for (var attrname2 in obj2) { obj3[attrname2] = obj2[attrname2]; }
return obj3;
}
|
javascript
|
{
"resource": ""
}
|
q14211
|
toFiles
|
train
|
function toFiles(app, options) {
let opts = Object.assign({ collection: null }, options);
let name = opts.collection;
let collection = app.collections ? name && app[name] : app;
let view;
if (!collection && name) {
collection = app.create(name, opts);
}
return utils.through.obj(async (file, enc, next) => {
if (!app.File.isFile(file)) {
file = app.file(file.path, file);
}
if (file.isNull()) {
next(null, file);
return;
}
if (collection && isCollection(collection)) {
try {
view = await collection.set(file.path, file);
} catch (err) {
next(err);
return;
}
next(null, view);
return;
}
view = !app.File.isFile(file) ? app.file(file.path, file) : file;
app.handle('onLoad', view)
.then(() => next(null, view))
.catch(next);
});
}
|
javascript
|
{
"resource": ""
}
|
q14212
|
inspect
|
train
|
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments[2] !== undefined) ctx.depth = arguments[2];
if (arguments[3] !== undefined) ctx.colors = arguments[3];
if (typeof opts === 'boolean') {
// legacy...
ctx.showHidden = opts;
}
// Set default and user-specified options
ctx = Object.assign({}, inspect.defaultOptions, ctx, opts);
if (ctx.colors) ctx.stylize = stylizeWithColor;
if (ctx.maxArrayLength === null) ctx.maxArrayLength = Infinity;
return formatValue(ctx, obj, ctx.depth);
}
|
javascript
|
{
"resource": ""
}
|
q14213
|
getJscsrc
|
train
|
function getJscsrc () {
var jscsrcPath = process.cwd() + '/.jscsrc';
try {
return JSON.parse(fs.readFileSync(jscsrcPath, 'utf8'));
}
catch (error) {
throw new Error(`Expected to find JSCS configuration ${jscsrcPath}; saw error "${error.message}". Cannot run JSCS analysis.`, error);
}
}
|
javascript
|
{
"resource": ""
}
|
q14214
|
filterMatch
|
train
|
function filterMatch(s, regExps) {
if (!regExps) {
return false;
}
var match = false;
for (var i = 0; i < regExps.length && !match; i++) {
match = s.match(regExps[i]) !== null;
}
return match;
}
|
javascript
|
{
"resource": ""
}
|
q14215
|
isError
|
train
|
function isError(error) {
return error && (Object.prototype.toString.call(error).slice(8, -1) === "Error" ||
(typeof error.stack !== "undefined" && typeof error.name !== "undefined"));
}
|
javascript
|
{
"resource": ""
}
|
q14216
|
diffToMessage
|
train
|
function diffToMessage(diffedAssertionError) {
var diff = diffedAssertionError.diff;
var actual = "";
var expected = "";
for (var i = 0; i < diff.length; i++) {
var diffType = diff[i][0];
if (diffType === 1) {
if (actual.length > 0) {
actual += ", ";
}
actual += "\"" + diff[i][1] + "\"";
} else if (diffType === -1) {
if (expected.length > 0) {
expected += ", ";
}
expected += "\"" + diff[i][1] + "\"";
}
}
var message = "Differences: ";
if (expected.length > 0) {
message += "'expected': " + expected;
}
if (actual.length > 0) {
if (expected.length > 0) {
message += ", ";
}
message += "'actual': " + actual;
}
message += "\n";
return getMessages(diffedAssertionError).join(" ") + "\n" + message;
}
|
javascript
|
{
"resource": ""
}
|
q14217
|
train
|
function() {
if (!fullScreen.isFullScreen()) {
touchStartElement.removeEventListener('touchstart', requestFullScreen, false);
touchStartElement.style.display = "none";
fullScreen.requestFullScreen(document.body);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14218
|
train
|
function (name) {
if (!this.instances[name]) {
this.instances[name] = DevFixturesAdapter.create({name: name});
}
return this.instances[name];
}
|
javascript
|
{
"resource": ""
}
|
|
q14219
|
format
|
train
|
function format(string, args) {
if (
string.length === 0 ||
!args ||
Object.keys(args).length === 0
) {
return string;
}
var matchVar = '[0-9a-zA-Z_$\\.]+',
matchBrackets = '\\[[^\\]]*\\]',
matchParsing = new RegExp(
//"^" +
"((" + matchVar + "|" + matchBrackets + ")*)" + //Match arg path
"(!([rsa]))?" + //Conversion
"(:([^\\?\\!]+))?" //spec
//"$"
),
matchCount = 0;
return string.replace(FORMAT_EXPRESSION, function (_, match) {
var parts = match.match(matchParsing),
argName = parts[1] || matchCount,
conversion = parts[4] || 's', //Default is string conversion
formatSpec = parts[6],
value = formatArgGet(args, argName);
matchCount += 1;
if (value === undefined) {
return FORMAT_EXPRESSION_START + match + FORMAT_EXPRESSION_STOP;//Replace unchanged
}
if (formatSpec && formatSpec.length > 0) {
value = formatValueSpec(value, formatSpec);
}
//Conversion s, r or a
switch (conversion) {
case 's':
return '' + value;
case 'r':
return inspect(value);
case 'a':
throw new Error('Not yet implemented conversion "' + conversion + '"');
default:
throw new Error('Invalid conversion "' + conversion + '"');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q14220
|
mixin
|
train
|
function mixin(obj, props) {
var argi = 1,
argc = arguments.length,
source, property, value;
if (!obj) {
obj = {};
}
while (argi < argc) {
source = arguments[argi];
for (property in source) {
if (source.hasOwnProperty(property)) {
value = source[property];
if (obj[property] !== value) {
obj[property] = value;
}
}
}
argi += 1;
}
return obj; // Object
}
|
javascript
|
{
"resource": ""
}
|
q14221
|
isObject
|
train
|
function isObject(obj) {
return obj !== undefined &&
(obj === null || typeof obj === "object" ||
typeof obj === "array" || obj instanceof Array ||
Object.prototype.toString.call(obj) === "[object Function]"
);
}
|
javascript
|
{
"resource": ""
}
|
q14222
|
isScalar
|
train
|
function isScalar(obj) {
var type = typeof obj;
return (type !== 'undefined' && (
obj === null ||
type === 'string' ||
type === 'number' ||
type === 'boolean'
));
}
|
javascript
|
{
"resource": ""
}
|
q14223
|
destroy
|
train
|
function destroy(object) {
if (isObject(object)) {
if (isFunction(object.finalize)) {
object.finalize();
}
for (var property in object) {
if (true) {//For lint
delete object[property];
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14224
|
clone
|
train
|
function clone(obj, deep) {
if (!obj || typeof obj !== "object" || isFunction(obj)) {
// null, undefined, any non-object, or function
return obj; // anything
}
if (obj instanceof Date) {
// Date
return new Date(obj.getTime()); // Date
}
var result, index, length, value;
if (isArray(obj)) {
// array
result = [];
if (deep) {
for (index = 0, length = obj.length; index < length; index += 1) {
if (index in obj) {
value = obj[index];
value = value.clone ? value.clone(true) : clone(value);
result.push(clone(value));
}
}
} else {
for (index = 0, length = obj.length; index < length; index += 1) {
if (index in obj) {
result.push(value);
}
}
}
return result;
}
//Default implementation
if (obj.clone) {
return obj.clone(obj, deep);
}
// generic objects
result = obj.constructor ? new obj.constructor() : {};
for (index in obj) {
if (true) {//jslint validation
value = obj[index];
if (
!(index in result) ||
(result[index] !== value && (!(index in EMPTY) || EMPTY[index] !== value))
) {
result[index] = clone(value);
}
}
}
return result; // Object
}
|
javascript
|
{
"resource": ""
}
|
q14225
|
forEach
|
train
|
function forEach(object, iterator, thisp) {
if (object) {
if (object.forEach) {
object.forEach(iterator, thisp);
return;
}
//Default implementation
if (! (iterator instanceof Function)) {
throw new TypeError('iterator should be a Function');
}
var key, length;
if (isString(object)) {
length = object.length;
for (key = 0; key < length; key += 1) {
iterator.call(thisp, object[key], key, object);
}
return;
}
for (key in object) {
if (object.hasOwnProperty(key)) {
iterator.call(thisp, object[key], key, object);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14226
|
hash
|
train
|
function hash(object) {
if (object === undefined || isScalar(object)) {
return '' + object;
}
if (object.hash) {
return object.hash();
}
//Default implementation
var hashes = [],
value, key, hashKey, hashValue;
for (key in object) {
if (object.hasOwnProperty(key)) {
value = object[key];
hashKey = String(key);
hashValue = hash(value);
hashValue = (hashKey > hashValue) ? hashValue + hashKey : hashKey + hashValue;
hashes.push(hashValue);
}
}
return hashes.sort().join('');
}
|
javascript
|
{
"resource": ""
}
|
q14227
|
train
|
function (options, onConnect) {
var self = this;
EventEmitter.call(this);
this.options = options;
// debugging
this.debug_enabled = options.debug;
this.handshook = false;
// received data which could not be parsed into messages yet
this.data = '';
// determine correct call of net.connect
var cb = function () {
connected.call(self);
onConnect.call(self);
};
if (options.path) {
this.debug("Trying to establish connection to unix socket %s", options.path);
this.client = net.connect(options.path, cb);
} else {
this.debug("Trying to establish connection to %s on port %s", options.host, options.port);
this.client = net.connect(options.port, options.host, cb);
}
// when data is received
this.client.on('data', function (data) {
var obj = dezeusify.call(self, data.toString('utf8'));
obj.forEach(function (item) {
received.call(self, item);
});
});
// when the connection is closed
this.client.on('end', function () {
disconnected.call(self);
});
this.client.on('error', function (err) {
self.debug("Whoops, an error occurred: %s", err.message);
throw new Error(util.format("A connection error occurred: %s", err.message));
});
// when a new listener is added to this object, we'll want to check if we should notify the server
this.on('newListener', function (evt) {
this.debug("A new event listener was added");
if (evt.toUpperCase() === evt && !this.subscribedEvents.indexOf(evt) !== -1) {
subscribeServerEvent.call(self, evt);
}
});
this.subscribedEvents = [];
this.waitingCallbacks = [];
}
|
javascript
|
{
"resource": ""
}
|
|
q14228
|
train
|
function (data, callback) {
this.debug("Sending: %s", JSON.stringify(data));
var message = dazeusify.call(this, data);
this.client.write(message, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q14229
|
train
|
function (data, callback) {
if (typeof callback !== 'function') {
this.debug("Registering dummy callback, because a response message is expected");
} else {
this.debug("Registering callback");
}
this.waitingCallbacks.push(callback);
send.call(this, data);
}
|
javascript
|
{
"resource": ""
}
|
|
q14230
|
train
|
function (event) {
this.debug("Requesting subscription for " + event);
sendReceive.call(this, {'do': 'subscribe', params: [event]}, function (result) {
if (result.success) {
this.debug("Succesfully subscribed to %s", event);
} else {
this.debug("Subscription request for %s failed", event);
}
});
this.subscribedEvents.push(event);
}
|
javascript
|
{
"resource": ""
}
|
|
q14231
|
train
|
function (obj) {
this.debug("Received: %s", JSON.stringify(obj));
if (typeof obj.event !== 'undefined') {
this.debug("Received an event-based message, sending off to listeners");
handleEvent.call(this, obj.event, obj.params);
} else {
if (this.waitingCallbacks.length > 0) {
var callback = this.waitingCallbacks.shift();
if (typeof callback === 'function') {
this.debug("Calling previously registered callback with message");
callback.call(this, obj);
} else {
this.debug("Callback was a dummy, not calling");
}
} else {
this.debug("No callbacks remaining, still received a response");
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14232
|
train
|
function (event, parameters) {
if (event === 'COMMAND') {
event = 'command_' + parameters[3];
}
parameters.unshift(event);
this.emit.apply(this, parameters);
}
|
javascript
|
{
"resource": ""
}
|
|
q14233
|
train
|
function (message) {
var objs = [], collector = '', chr, msglen, data;
this.data += message;
data = new Buffer(this.data, 'utf8');
for (var i = 0; i < data.length; i += 1) {
chr = data[i];
if (chr > 47 && chr < 58) {
collector += String.fromCharCode(chr);
} else if (chr !== 10 && chr !== 13) {
msglen = parseInt(collector, 10);
if (msglen + i <= data.length) {
objs.push(JSON.parse(data.toString('utf8', i, msglen + i)));
data = data.slice(i + msglen);
collector = '';
i = 0;
} else {
break;
}
}
}
this.data = data.toString('utf8');
return objs;
}
|
javascript
|
{
"resource": ""
}
|
|
q14234
|
train
|
function(err) {
var validationErrMsg = self.handleError(err)
if (!validationErrMsg) return false
else {
self._merge(validationErrors, validationErrMsg, prefix)
isValid = false
return true
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14235
|
genTemplateData
|
train
|
function genTemplateData() {
var templateData = {
data : {
process : process,
commit : commit,
env : commitTask.commitOpts,
options : options
}
};
var rtn = {};
var arr = Array.prototype.slice.call(arguments, 0);
arr.forEach(function genIntMsgs(s) {
rtn[s] = options[s] ? rbot.processTemplate(options[s], templateData) : '';
if (rtn[s]) {
rbot.log.verbose(s + ' = ' + rtn[s]);
}
});
return rtn;
}
|
javascript
|
{
"resource": ""
}
|
q14236
|
remoteSetup
|
train
|
function remoteSetup() {
var link = '${GH_TOKEN}@' + options.gitHostname + '/' + commit.slug + '.git';
cmd('git config --global user.email "' + options.repoEmail + '"');
cmd('git config --global user.name "' + options.repoUser + '"');
cmd('git remote rm ' + options.repoName);
cmd('git remote add ' + options.repoName + ' https://' + commit.username + ':' + link);
}
|
javascript
|
{
"resource": ""
}
|
q14237
|
gitRelease
|
train
|
function gitRelease() {
// Tag release
rbot.log.info('Tagging release ' + commit.versionTag + ' via ' + options.gitHostname);
cmd('git tag -f -a ' + commit.versionTag + ' -m "'
+ (chgLogRtn ? chgLogRtn.replace(coopt.regexLines, '$1 \\') : commit.message) + '"');
cmd('git push -f ' + options.repoName + ' ' + commit.versionTag);
commit.releaseId = commit.versionTag;
// TODO : upload asset?
rollCall.addRollback(rollbackTag);
rollCall.then(publish);
}
|
javascript
|
{
"resource": ""
}
|
q14238
|
gitHubRelease
|
train
|
function gitHubRelease() {
rbot.log.info('Releasing ' + commit.versionTag + ' via ' + options.gitHostname);
// GitHub Release API will not remove the tag when removing a
// release
github.releaseAndUploadAsset(distAssets, coopt.regexLines, commit, tmpltData.name, chgLogRtn
|| commit.message, options, rollCall, rollbackTag, function() {
rollCall.then(publish);
});
}
|
javascript
|
{
"resource": ""
}
|
q14239
|
rollbackPublish
|
train
|
function rollbackPublish() {
try {
chkoutRun(options.distBranch, function() {
var cph = cmd('git rev-parse HEAD');
if (pubHash && pubHash !== cph) {
cmd('git checkout -qf ' + pubHash);
cmd('git commit -q -m "Rollback: ' + tmpltData.distBranchPubMsg + '"');
cmd('git push -f ' + options.repoName + ' ' + options.distBranch);
} else if (!pubHash) {
cmd('git push ' + options.repoName + ' --delete ' + options.distBranch);
} else {
rbot.log.verbose('Skipping rollback for ' + options.distBranch + ' for hash "' + pubHash
+ '" (current hash: "' + cph + '")');
}
});
} catch (e) {
var msg = 'Failed to rollback publish branch changes!';
rollCall.error(msg, e);
}
}
|
javascript
|
{
"resource": ""
}
|
q14240
|
getObjectToStringValue
|
train
|
function getObjectToStringValue(value) {
var result = objectToString.call(value);
switch (result) {
case '[object Undefined]':
return '#Undefined';
case '[object Null]':
return '#Null';
case '[object Object]':
return 'Object';
case '[object Function]':
return 'Function';
case '[object String]':
return 'String';
case '[object Number]':
return (value != +value) ? '#NaN' : 'Number';
case '[object Array]':
return 'Array';
case '[object Boolean]':
return 'Boolean';
case '[object RegExp]':
return 'RegExp';
case '[object Symbol]':
return 'Symbol';
case '[object Map]':
return 'Map';
case '[object WeakMap]':
return 'WeakMap';
case '[object Set]':
return 'Set';
case '[object WeakSet]':
return 'WeakSet';
case '[object Int8Array]':
return 'Int8Array';
case '[object Uint8Array]':
return 'Uint8Array';
case '[object Uint8ClampedArray]':
return 'Uint8ClampedArray';
case '[object Int16Array]':
return 'Int16Array';
case '[object Uint16Array]':
return 'Uint16Array';
case '[object Int32Array]':
return 'Int32Array';
case '[object Uint32Array]':
return 'Uint32Array';
case '[object Float32Array]':
return 'Float32Array';
case '[object Float64Array]':
return 'Float64Array';
case '[object ArrayBuffer]':
return 'ArrayBuffer';
case '[object DataView]':
return 'DataView';
case '[object Error]':
return 'Error';
case '[object Arguments]':
return 'Arguments';
case '[object JSON]':
return 'JSON';
case '[object Math]':
return 'Math';
case '[object Date]':
return 'Date';
default: //handle the rest (HTML element, future global objects,...)
return result.slice(8, -1);
}
}
|
javascript
|
{
"resource": ""
}
|
q14241
|
typeOf
|
train
|
function typeOf(value, options) {
if (value === undefined) return '#Undefined';
if (value === null) return '#Null';
if (options !== 'forceObjectToString') {
var constructor = getConstructor(value);
if (constructor !== null) {
var type = getFunctionName(constructor);
if (type === 'Object') {
return getObjectToStringValue(value);
}
return (type === 'Number' && value != +value) ? '#NaN' : type;
}
}
return getObjectToStringValue(value);
}
|
javascript
|
{
"resource": ""
}
|
q14242
|
fetchComponents
|
train
|
function fetchComponents(filter, options) {
console.log('Fetching dependencies...');
var componentList = [];
if (_.isObject(filter) || _.isArray(filter)) {
var dependencies = fetchBowerComponents();
_.each(dependencies, function(dep) {
var bowerObj = getBower(dep);
if (bowerObj) {
var mainFiles = fetchMainFiles(bowerObj);
var componentFiles = [];
_.each(filter, function(destDir, expression) {
var expressionObj = {};
expressionObj[expression] = destDir;
var filteredValues = filterByExpression(mainFiles, expressionObj, options);
Array.prototype.push.apply(componentFiles,
filteredValues);
});
// create Component class and encapsulate Component
// related info in that.
componentList.push(new Component(bowerObj, componentFiles));
console.log(componentFiles.length + ' file(s) found for ' + dep);
}
});
console.log('##### Total dependencie(s) found ' + componentList.length);
}
return componentList;
}
|
javascript
|
{
"resource": ""
}
|
q14243
|
fetchComponent
|
train
|
function fetchComponent(compName, filter, options) {
var componentFiles = [];
_.each(filter, function(destDir, expression) {
var fileInfo = path.parse(path.resolve(BOWER_DIRECTORY, compName, expression));
var sourceDir = fileInfo.dir;
var dirContent = fs.readdirSync(sourceDir);
var expressionObj = {};
expressionObj[expression] = destDir;
dirContent = dirContent.map(function(file) {
return path.resolve(BOWER_DIRECTORY, compName, file);
});
Array.prototype.push.apply(componentFiles,
filterByExpression(dirContent, expressionObj, options));
});
console.log(componentFiles.length + ' file(s) found for ' + compName);
var bowerObj = getBower(compName);
return new Component(bowerObj, componentFiles);
}
|
javascript
|
{
"resource": ""
}
|
q14244
|
typeName
|
train
|
function typeName(item) {
if (isNull(item)) {
return "null";
}
else if (isUndefined(item)) {
return "undefined";
}
return /\[.+ ([^\]]+)/.exec(toString(item))[1].toLowerCase();
}
|
javascript
|
{
"resource": ""
}
|
q14245
|
train
|
function(wrapper, audio) {
if (!audio.settings.createPlayer) return;
var player = audio.settings.createPlayer,
playPause = getByClass(player.playPauseClass, wrapper),
scrubber = getByClass(player.scrubberClass, wrapper),
leftPos = function(elem) {
var curleft = 0;
if (elem.offsetParent) {
do { curleft += elem.offsetLeft; } while (elem = elem.offsetParent);
}
return curleft;
};
container[audiojs].events.addListener(playPause, 'click', function(e) {
audio.playPause.apply(audio);
});
container[audiojs].events.addListener(scrubber, 'click', function(e) {
var relativeLeft = e.clientX - leftPos(this);
audio.skipTo(relativeLeft / scrubber.offsetWidth);
});
// _If flash is being used, then the following handlers don't need to be registered._
if (audio.settings.useFlash) return;
// Start tracking the load progress of the track.
container[audiojs].events.trackLoadProgress(audio);
container[audiojs].events.addListener(audio.element, 'timeupdate', function(e) {
audio.updatePlayhead.apply(audio);
});
container[audiojs].events.addListener(audio.element, 'ended', function(e) {
audio.trackEnded.apply(audio);
});
container[audiojs].events.addListener(audio.source, 'error', function(e) {
// on error, cancel any load timers that are running.
clearInterval(audio.readyTimer);
clearInterval(audio.loadTimer);
audio.settings.loadError.apply(audio);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14246
|
exec
|
train
|
function exec(ptn, source, opts) {
opts = opts || {};
var list = []
, flat = opts.flat = opts.flat !== undefined ? opts.flat : false
, keys = opts.keys = opts.keys !== undefined ? opts.keys : true
, values = opts.values = opts.values !== undefined ? opts.values : false
if(flat) {
source = flatten(source);
}
//console.dir(source);
function match(k, v, p) {
var re = recopy(ptn)
, res = {key: k, value: v, parent: p, match: {key: false, value: false}};
res.match.key = keys && re.test(k);
res.match.value = values && re.test('' + v);
//console.log('matches %s %s %s', matches, re, k);
if(res.match.key || res.match.value) {
res.pattern = ptn;
list.push(res);
}
}
function lookup(source) {
var k, v;
for(k in source) {
v = source[k];
match(k, v, source);
if(!flat && v && typeof v === 'object' && Object.keys(v).length) {
lookup(v);
}
}
}
lookup(source);
return list;
}
|
javascript
|
{
"resource": ""
}
|
q14247
|
generateGruntfile
|
train
|
function generateGruntfile (generatedConfig) {
return function(grunt) {
var path = require('path'),
fs = require('fs');
require('load-grunt-tasks')(grunt);
grunt.initConfig(generatedConfig);
grunt.registerTask('default', ['watch']);
// Handle new files with that have a new, supported preprocessor
grunt.event.on('watch', function(action, filepath) {
var ext = path.extname(filepath);
// Ignore directories
if (fs.lstatSync(filepath).isDirectory()) return;
if (action === 'added') {
// This is a special message that's parsed by YA
// to determine if support for an additional preprocessor is necessary
// Note: this allows us to avoid controlling grunt manually within YA
console.log('EXTADDED:' + ext);
// Note: we don't do anything for newly added .js files
// A new js file can't be the root unless it's changed to require
// the current root and saved/changed
} else if (action === 'changed' || action === 'deleted') {
if (ext === '.js') {
// Ignore bundles
if (/.+bundle.js/g.test(filepath)) return;
// Notify YA to recompute the roots and
// generate a configuration
console.log('JSCHANGED:' + filepath);
}
}
});
// For watching entire directories but allowing
// the grunt.event binding to take care of it
grunt.registerTask('noop', function () {});
};
}
|
javascript
|
{
"resource": ""
}
|
q14248
|
getMatches
|
train
|
function getMatches(source, pattern) {
var matches = [],
match;
// Grab all added extensions
while (match = pattern.exec(source)) {
matches.push(match[2]);
}
return matches;
}
|
javascript
|
{
"resource": ""
}
|
q14249
|
link
|
train
|
function link (outlet, editor) {
if (getLocationForItem(editor) === 'center') {
outlet.element.setAttribute('outlet-linked-editor-id', editor.id)
} else {
outlet.element.removeAttribute('outlet-linked-editor-id')
}
}
|
javascript
|
{
"resource": ""
}
|
q14250
|
_isVoidFilterRoute
|
train
|
function _isVoidFilterRoute(req) {
var reqPathRegex = new RegExp(['^', req.path.replace(/\/$/, ''), '$'].join(''), 'i')
, voidRoute
, i;
for (i=0; i<voidFilterRoutes.length; i++) {
if (reqPathRegex.test(voidFilterRoutes[i])) { return true; }
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q14251
|
_renderAppShell
|
train
|
function _renderAppShell(res) {
res.render(appShell.view, {
layout : appShell.layout
, appTitle : appConfig.appTitle
, appConfig : JSON.stringify(appConfig)
, appData : JSON.stringify(appData)
});
}
|
javascript
|
{
"resource": ""
}
|
q14252
|
configure
|
train
|
function configure(options) {
options = options || {};
var assertErrTemplate = '[connect-spa-request-filter middleware :: configure()] Fatal error! Missing parameter:';
assert(options.appConfig, util.format(assertErrTemplate, 'options.appConfig'));
assert(options.appConfig.appTitle, util.format(assertErrTemplate, 'options.appConfig.appTitle'));
appConfig = options.appConfig;
appData = options.appData || {};
appShell = options.appShell || {};
voidFilterRoutes = options.voidFilterRoutes || [];
appShell.view = appShell.view || 'index';
appShell.layout = appShell.layout || false;
// Publicly expose the module interface after initialized
return requestFilter;
}
|
javascript
|
{
"resource": ""
}
|
q14253
|
expand
|
train
|
function expand(object, options) {
var expanded = {};
var options = options || {};
var separator = options.separator || '.';
var affix = options.affix ? separator + options.affix + separator : separator;
for (var path in object) {
var value = object[path];
var pointer = expanded;
if (path.indexOf('[') >= 0) {
path = path.replace(/\[/g, '[.').replace(/]/g, '');
}
var parts = path.split(separator).join(affix).split('.');
while (parts.length - 1) {
var key = parts.shift();
if (key.slice(-1) === '[') {
key = key.slice(0, - 1);
pointer[key] = Array.isArray(pointer[key]) ? pointer[key] : [];
} else {
pointer[key] = (pointer[key] !== null && typeof pointer[key] === 'object' && pointer[key].constructor === Object) ? pointer[key] : {};
}
pointer = pointer[key];
}
pointer[parts.shift()] = value;
}
return expanded;
}
|
javascript
|
{
"resource": ""
}
|
q14254
|
touch
|
train
|
function touch(argv, callback) {
util.patch(argv[2], 'DELETE {} .', function(err, val) {
if (!err) {
console.log('touch to : ' + argv[2]);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q14255
|
getDocumentFragmentFromString
|
train
|
function getDocumentFragmentFromString(html) {
// return document.createRange().createContextualFragment(html); // FU safari
var range = document.createRange();
range.selectNode(document.body);// safari
return range.createContextualFragment(html);
}
|
javascript
|
{
"resource": ""
}
|
q14256
|
checkPath
|
train
|
function checkPath(name, path) {
helpers.exists(path, function (exist) {
if (!exist) {
callback(new Error(name + ' was not found (' + path + ')')); return;
}
progress.set(name);
});
}
|
javascript
|
{
"resource": ""
}
|
q14257
|
execFile
|
train
|
function execFile() {
var child;
if (options.strategy === 'development') {
child = core.spawnPump(options, false, false);
if (options.relay) child.pump(process);
} else if (options.strategy === 'unattached') {
child = core.spawnPump(options, true, false);
} else if (options.strategy === 'daemon') {
child = core.spawnDaemon(options, true);
}
// start child
child.spawn();
child.on('start', function () {
callback(null);
});
}
|
javascript
|
{
"resource": ""
}
|
q14258
|
train
|
function (mx, my, q1x1, q1y1, q1x, q1y, q2x1, q2y1, q2x, q2y ) {
return `M ${mx} ${my} Q ${q1x1} ${q1y1} ${q1x} ${q1y} Q ${q2x1} ${q2y1} ${q2x} ${q2y}`;
}
|
javascript
|
{
"resource": ""
}
|
|
q14259
|
_addTaskBubble
|
train
|
function _addTaskBubble(node, d) {
var group = node.append('g');
group.attr('class', 'task-bubble');
group.append('use').attr('xlink:href', '#task-bubble');
translateIfIE(group.append('text')
.text(_trimText(d.get('data.totalTasks') || 0, 3)), 0, 4);
translateIfIE(group, 38, -15);
}
|
javascript
|
{
"resource": ""
}
|
q14260
|
_addVertexGroupBubble
|
train
|
function _addVertexGroupBubble(node, d) {
var group;
if(d.vertexGroup) {
group = node.append('g');
group.attr('class', 'group-bubble');
group.append('use').attr('xlink:href', '#group-bubble');
translateIfIE(group.append('text')
.text(_trimText(d.get('vertexGroup.groupMembers.length'), 2)), 0, 4);
translateIfIE(group, 38, 15);
}
}
|
javascript
|
{
"resource": ""
}
|
q14261
|
_addStatusBar
|
train
|
function _addStatusBar(node, d) {
var group = node.append('g');
group.attr('class', 'status-bar');
group.append('foreignObject')
.attr("class", "status")
.attr("width", 70)
.attr("height", 15)
.html('<span class="msg-container">' +
d.get('data.status') +
'</span>'
);
}
|
javascript
|
{
"resource": ""
}
|
q14262
|
_addBasicContents
|
train
|
function _addBasicContents(node, d, titleProperty, maxTitleLength) {
var className = d.type;
node.attr('class', `node ${className}`);
node.append('use').attr('xlink:href', `#${className}-bg`);
translateIfIE(node.append('text')
.attr('class', 'title')
.text(_trimText(d.get(titleProperty || 'name'), maxTitleLength || 12)), 0, 4);
}
|
javascript
|
{
"resource": ""
}
|
q14263
|
_addContent
|
train
|
function _addContent(d) {
var node = d3.select(this);
switch(d.type) {
case 'vertex':
_addBasicContents(node, d, 'vertexName');
_addStatusBar(node, d);
_addTaskBubble(node, d);
_addIOBubble(node, d);
_addVertexGroupBubble(node, d);
break;
case 'input':
case 'output':
_addBasicContents(node, d);
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q14264
|
_getLinks
|
train
|
function _getLinks(nodes) {
var links = [],
nodeHash;
nodeHash = nodes.reduce(function (obj, node) {
obj[node.id] = node;
return obj;
}, {});
_data.links.forEach(function (link) {
var source = nodeHash[link.sourceId],
target = nodeHash[link.targetId];
if(source && target) {
link.setProperties({
source: source,
target: target,
isBackwardLink: source.isSelfOrAncestor(target)
});
links.push(link);
}
});
return links;
}
|
javascript
|
{
"resource": ""
}
|
q14265
|
_normalize
|
train
|
function _normalize(nodes) {
// Set layout
var farthestY = 0;
nodes.forEach(function (d) {
d.y = d.depth * -_layout.depthSpacing;
if(d.y < farthestY) {
farthestY = d.y;
}
});
farthestY -= PADDING;
nodes.forEach(function (d) {
d.y -= farthestY;
});
//Remove space occupied by dummy
var rootChildren = _treeData.get('children'),
rootChildCount = rootChildren.length,
dummyIndex,
i;
if(rootChildCount % 2 === 0) {
dummyIndex = rootChildren.indexOf(_treeData.get('dummy'));
if(dummyIndex >= rootChildCount / 2) {
for(i = 0; i < dummyIndex; i++) {
rootChildren[i].x = rootChildren[i + 1].x;
rootChildren[i].y = rootChildren[i + 1].y;
}
}
else {
for(i = rootChildCount - 1; i > dummyIndex; i--) {
rootChildren[i].x = rootChildren[i - 1].x;
rootChildren[i].y = rootChildren[i - 1].y;
}
}
}
// Put all single vertex outputs in-line with the vertex node
// So that they are directly below the respective vertex in vertical layout
nodes.forEach(function (node) {
if(node.type === DataProcessor.types.OUTPUT &&
node.get('vertex.outputs.length') === 1 &&
!node.get('vertex.outEdgeIds.length') &&
node.get('treeParent.x') !== node.get('x')
) {
node.x = node.get('vertex.x');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q14266
|
_scheduledClick
|
train
|
function _scheduledClick(d, node) {
node = node.correspondingUseElement || node;
_component.sendAction('entityClicked', {
type: _getType(node),
d: d
});
_tip.hide();
_scheduledClickId = 0;
}
|
javascript
|
{
"resource": ""
}
|
q14267
|
_onClick
|
train
|
function _onClick(d) {
if(!_scheduledClickId) {
_scheduledClickId = setTimeout(_scheduledClick.bind(this, d, d3.event.target), 200);
}
}
|
javascript
|
{
"resource": ""
}
|
q14268
|
_onDblclick
|
train
|
function _onDblclick(d) {
var event = d3.event,
node = event.target;
node = node.correspondingUseElement || node;
if(_scheduledClickId) {
clearTimeout(_scheduledClickId);
_scheduledClickId = 0;
}
switch(_getType(node)) {
case "io":
d.toggleAdditionalInclusion();
_update();
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q14269
|
_createPathData
|
train
|
function _createPathData(d) {
var sX = d.source.y,
sY = d.source.x,
tX = d.target.y,
tY = d.target.x,
mX = (sX + tX)/2,
mY = (sY + tY)/2,
sH = Math.abs(sX - tX) * 0.35,
sV = 0; // strength
if(d.isBackwardLink) {
if(sY === tY) {
sV = 45;
mY -= 50;
if(sX === tX) {
sX += _layout.linkDelta;
tX -= _layout.linkDelta;
}
}
sH = Math.abs(sX - tX) * 1.1;
}
return _layout.pathFormatter(
sX, sY,
sX + sH, sY - sV,
mX, mY,
tX - sH, tY - sV,
tX, tY
);
}
|
javascript
|
{
"resource": ""
}
|
q14270
|
_updateNodes
|
train
|
function _updateNodes(nodes, source) {
// Enter any new nodes at the parent's previous position.
nodes.enter().append('g')
.attr('transform', function(d) {
var node = _getVertexNode(d, "x0") || source;
node = _layout.projector(node.x0, node.y0);
return 'translate(' + node.x + ',' + node.y + ')';
})
.on({
mouseover: _onMouseOver,
mouseout: _tip.hide,
mousedown: _onMouse,
mousemove: _onMouse,
dblclick: _onDblclick
})
.style('opacity', 1e-6)
.each(_addContent);
// Transition nodes to their new position.
nodes.transition()
.duration(DURATION)
.attr('transform', function(d) {
d = _layout.projector(d.x, d.y);
return 'translate(' + d.x + ',' + d.y + ')';
})
.style('opacity', 1);
// Transition exiting nodes to the parent's new position.
nodes.exit().transition()
.duration(DURATION)
.attr('transform', function(d) {
var node = _getVertexNode(d, "x") || source;
node = _layout.projector(node.x, node.y);
return 'translate(' + node.x + ',' + node.y + ')';
})
.style('opacity', 1e-6)
.remove();
}
|
javascript
|
{
"resource": ""
}
|
q14271
|
_updateLinks
|
train
|
function _updateLinks(links, source) {
// Enter any new links at the parent's previous position.
links.enter().insert('path', 'g')
.attr('class', function (d) {
var type = d.get('dataMovementType') || "";
return 'link ' + type.toLowerCase();
})
/**
* IE11 rendering does not work for svg path element with marker set.
* See https://connect.microsoft.com/IE/feedback/details/801938
* This can be removed once the bug is fixed in all supported IE versions
*/
.attr("style", isIE ? "" : Ember.String.htmlSafe("marker-mid: url(" + window.location.pathname + "#arrow-marker);"))
.attr('d', function(d) {
var node = _getTargetNode(d, "x0") || source;
var o = {x: node.x0, y: node.y0};
return _createPathData({source: o, target: o});
})
.on({
mouseover: _onMouseOver,
mouseout: _tip.hide
});
// Transition links to their new position.
links.transition()
.duration(DURATION)
.attr('d', _createPathData);
// Transition exiting nodes to the parent's new position.
links.exit().transition()
.duration(DURATION)
.attr('d', function(d) {
var node = _getTargetNode(d, "x") || source;
var o = {x: node.x, y: node.y};
return _createPathData({source: o, target: o});
})
.remove();
}
|
javascript
|
{
"resource": ""
}
|
q14272
|
_update
|
train
|
function _update() {
var nodesData = _treeLayout.nodes(_treeData),
linksData = _getLinks(nodesData);
_normalize(nodesData);
var nodes = _g.selectAll('g.node')
.data(nodesData, _getNodeId);
_updateNodes(nodes, _treeData);
var links = _g.selectAll('path.link')
.data(linksData, _getLinkId);
_updateLinks(links, _treeData);
nodesData.forEach(_stashOldPositions);
}
|
javascript
|
{
"resource": ""
}
|
q14273
|
transform
|
train
|
function transform(animate) {
var base = animate ? g.transition().duration(DURATION) : g;
base.attr('transform', `translate(${panX}, ${panY}) scale(${scale})`);
}
|
javascript
|
{
"resource": ""
}
|
q14274
|
visibilityCheck
|
train
|
function visibilityCheck() {
var graphBound = g.node().getBoundingClientRect(),
containerBound = container[0].getBoundingClientRect();
if(graphBound.right < containerBound.left ||
graphBound.bottom < containerBound.top ||
graphBound.left > containerBound.right ||
graphBound.top > containerBound.bottom) {
panX = PADDING;
panY = PADDING;
scale = 1;
transform(true);
}
}
|
javascript
|
{
"resource": ""
}
|
q14275
|
onMouseMove
|
train
|
function onMouseMove(event) {
panX += event.pageX - prevX;
panY += event.pageY - prevY;
transform();
prevX = event.pageX;
prevY = event.pageY;
}
|
javascript
|
{
"resource": ""
}
|
q14276
|
onWheel
|
train
|
function onWheel(event) {
var prevScale = scale,
offset = container.offset(),
mouseX = event.pageX - offset.left,
mouseY = event.pageY - offset.top,
factor = 0;
scale += event.deltaY * SCALE_TUNER;
if(scale < MIN_SCALE) {
scale = MIN_SCALE;
}
else if(scale > MAX_SCALE) {
scale = MAX_SCALE;
}
factor = 1 - scale / prevScale;
panX += (mouseX - panX) * factor;
panY += (mouseY - panY) * factor;
transform();
scheduleVisibilityCheck();
_tip.reposition();
event.preventDefault();
}
|
javascript
|
{
"resource": ""
}
|
q14277
|
_setLayout
|
train
|
function _setLayout(layout) {
var leafCount = _data.leafCount,
dimention;
// If count is even dummy will be replaced by output, so output would no more be leaf
if(_data.tree.get('children.length') % 2 === 0) {
leafCount--;
}
dimention = layout.projector(leafCount, _data.maxDepth - 1);
_layout = layout;
_width = dimention.x *= _layout.hSpacing;
_height = dimention.y *= _layout.vSpacing;
dimention = _layout.projector(dimention.x, dimention.y); // Because tree is always top to bottom
_treeLayout = d3.layout.tree().size([dimention.x, dimention.y]);
_update();
}
|
javascript
|
{
"resource": ""
}
|
q14278
|
train
|
function (component, element, data) {
var svg = d3.select(element).select('svg');
_component = component;
_data = data;
_g = svg.append('g').attr('transform', `translate(${PADDING},${PADDING})`);
_svg = Ember.$(svg.node());
_tip = Tip;
_tip.init(Ember.$(element).find('.tool-tip'), _svg);
_treeData = data.tree;
_treeData.x0 = 0;
_treeData.y0 = 0;
_panZoom = _attachPanZoom(_svg, _g, element);
_setLayout(LAYOUTS.topToBottom);
}
|
javascript
|
{
"resource": ""
}
|
|
q14279
|
train
|
function (){
var scale = Math.min(
(_svg.width() - PADDING * 2) / _width,
(_svg.height() - PADDING * 2) / _height
),
panZoomValues = _panZoom();
if(
panZoomValues.panX !== PADDING ||
panZoomValues.panY !== PADDING ||
panZoomValues.scale !== scale
) {
_panZoomValues = _panZoom(PADDING, PADDING, scale);
}
else {
_panZoomValues = _panZoom(
_panZoomValues.panX,
_panZoomValues.panY,
_panZoomValues.scale);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14280
|
train
|
function (hide) {
if(hide) {
_g.attr('class', 'hide-io');
_treeData.recursivelyCall('excludeAdditionals');
}
else {
_treeData.recursivelyCall('includeAdditionals');
_g.attr('class', null);
}
_update();
}
|
javascript
|
{
"resource": ""
}
|
|
q14281
|
train
|
function () {
_setLayout(_layout === LAYOUTS.topToBottom ?
LAYOUTS.leftToRight :
LAYOUTS.topToBottom);
return _layout === LAYOUTS.topToBottom;
}
|
javascript
|
{
"resource": ""
}
|
|
q14282
|
User
|
train
|
function User(coll, username, opts) {
if (typeof coll !== 'object') { throw new TypeError('coll must be an object'); }
if (typeof username !== 'string') { throw new TypeError('username must be a string'); }
// setup a resolver
var db = {
find: coll.findOne.bind(coll),
insert: coll.insert.bind(coll),
updateHash: function(lookup, hash, cb) {
coll.update(lookup, { $set: { password: hash } }, function(err, updated) {
if (err) { cb(err); return; }
if (updated !== 1) { cb(new Error('failed to update password')); return; }
cb(null);
});
}
};
BcryptUser.call(this, db, username, opts || {});
}
|
javascript
|
{
"resource": ""
}
|
q14283
|
train
|
function(options) {
return function(err, resp) {
if (err) {
options.error(err);
} else {
options.success(resp);
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q14284
|
train
|
function(attrs, attrsToRemove) {
_.forEach(attrs, function(val, key) {
// shouldRemove is either an object or a boolean
var shouldRemove = attrsToRemove[key];
if (_.isUndefined(shouldRemove)) {
return;
}
// Support nested object
if (_.isPlainObject(val) && !_.isArray(val) && _.isPlainObject(shouldRemove)) {
return this._removeExpandableAttributes(val, shouldRemove);
}
// Make sure attribute is an object
// Strip all nested properties except for `_id`
if (_.isPlainObject(attrs[key]) && shouldRemove) {
attrs[key] = _.pick(attrs[key], ['_id']);
}
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q14285
|
train
|
function(schemaType, schemaDefault) {
if (!_.isUndefined(schemaDefault)) {
return schemaDefault;
}
switch (schemaType) {
case 'integer':
case 'uinteger':
case 'float':
case 'ufloat':
return 0;
case 'boolean':
return false;
case 'timestamp':
return new Date().getTime(); // ms
case 'date':
return new Date(); // iso
default:
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14286
|
train
|
function(def, withArray) {
def = def ? def : _.result(this, 'definition');
return _.reduce(def, function(defaults, attr, key) {
if (attr.computed) {
return defaults;
}
if (attr.default !== undefined) {
defaults[key] = _.result(attr, 'default');
} else if (attr.type === 'object') {
defaults[key] = this.defaults(attr.fields || {});
} else if (attr.type === 'array') {
// withArray to populate nested array values for _validateAttributes
defaults[key] = withArray ? [this.defaults(attr.fields || {})] : [];
} else {
defaults[key] = this._defaultVal(attr.type);
}
return defaults;
}.bind(this), {});
}
|
javascript
|
{
"resource": ""
}
|
|
q14287
|
train
|
function(def) {
def = def ? def : _.result(this, 'definition');
return _.reduce(def, function(schema, attr, key) {
if (attr.type === 'object') {
schema[key] = this.schema(attr.fields || {});
} else if (attr.type === 'array') {
if (attr.value_type === 'object') {
schema[key] = [this.schema(attr.fields || {})];
} else if (attr.value_type) {
schema[key] = [attr.value_type];
} else {
schema[key] = [];
}
} else {
schema[key] = attr.type;
}
return schema;
}.bind(this), {});
}
|
javascript
|
{
"resource": ""
}
|
|
q14288
|
train
|
function(prop, def) {
def = def ? def : _.result(this, 'definition');
return _.reduce(def, function(attrs, attr, key) {
if (attr.type === 'object') {
var nested = this.findAttributes(prop, attr.fields || {});
if (!_.isEmpty(nested)) {
attrs[key] = nested;
}
} if (attr[prop]) {
attrs[key] = true;
}
return attrs;
}.bind(this), {});
}
|
javascript
|
{
"resource": ""
}
|
|
q14289
|
train
|
function(resp, options) {
// Mongodb sometimes returns an array of one document
if (_.isArray(resp)) {
resp = resp[0];
}
resp = _.defaultsDeep({}, resp, this.defaults());
return resp;
}
|
javascript
|
{
"resource": ""
}
|
|
q14290
|
train
|
function(key, val, options) {
var attrs;
if (key === null) return this;
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options || (options = {});
// Don't override unset
if (options.unset) {
return Backbone.Model.prototype.set.apply(this, arguments);
}
// Apply schema
this._validateAttributes(attrs, this._schema, this._defaults);
return Backbone.Model.prototype.set.call(this, attrs, options);
}
|
javascript
|
{
"resource": ""
}
|
|
q14291
|
train
|
function(attrs, attr) {
if (!_.isString(attr)) {
return undefined;
}
var keys = attr.split('.');
var key;
var val = attrs;
var context = this;
for (var i = 0, n = keys.length; i < n; i++) {
// get key
key = keys[i];
// Hold reference to the context when diving deep into nested keys
if (i > 0) {
context = val;
}
// get value for key
val = val[key];
// value for key does not exist
// break out of loop early
if (_.isUndefined(val) || _.isNull(val)) {
break;
}
}
// Eval computed properties that are functions
if (_.isFunction(val)) {
// Call it with the proper context (see above)
val = val.call(context);
}
return val;
}
|
javascript
|
{
"resource": ""
}
|
|
q14292
|
determineVersion
|
train
|
function determineVersion(json) {
var version = 'unknown';
if (json) {
if (json.WMS_Capabilities) {
if (json.WMS_Capabilities.$) {
if (json.WMS_Capabilities.$.version) {
version = json.WMS_Capabilities.$.version;
}
}
} else {
if (json.WMT_MS_Capabilities) {
if (json.WMT_MS_Capabilities.$) {
if (json.WMT_MS_Capabilities.$.version) {
version = json.WMT_MS_Capabilities.$.version;
}
}
}
}
}
return version;
}
|
javascript
|
{
"resource": ""
}
|
q14293
|
determineJSON
|
train
|
function determineJSON(xml) {
var json = null;
parseString(xml, function(err, result) {
if (err) {
// TODO
console.log(err);
} else {
json = result;
}
});
return json;
}
|
javascript
|
{
"resource": ""
}
|
q14294
|
determineLayers
|
train
|
function determineLayers(json, version) {
var layers = [];
if (version == '1.3.0') {
if (json.WMS_Capabilities.Capability) {
if (json.WMS_Capabilities.Capability[0]) {
if (json.WMS_Capabilities.Capability[0].Layer) {
layers = buildLayers(json.WMS_Capabilities.Capability[0].Layer);
}
}
}
} else {
if (version == '1.1.1' || version == '1.1.0' || version == '1.0.0') {
if (json.WMT_MS_Capabilities.Capability) {
if (json.WMT_MS_Capabilities.Capability[0]) {
if (json.WMT_MS_Capabilities.Capability[0].Layer) {
layers = buildLayers(json.WMT_MS_Capabilities.Capability[0].Layer);
}
}
}
}
}
return layers;
}
|
javascript
|
{
"resource": ""
}
|
q14295
|
determineLayerName
|
train
|
function determineLayerName(layer) {
var name = '';
// Layer name available
if (layer.Name) {
return layer.Name;
} else {
// Layer name not available
// Layer name will be building from sublayers
for (var int = 0; int < layer.Layer.length; int++) {
name += determineLayerName(layer.Layer[int]) + ',';
}
}
// Remove last comma
if (name.substring(name.length - 1, name.length) == ',') {
name = name.substring(0, name.length - 1);
}
return name;
}
|
javascript
|
{
"resource": ""
}
|
q14296
|
buildLayers
|
train
|
function buildLayers(layersObject) {
// Array of layers
var layers = [];
if (layersObject) {
// Iterate over all layers
for (var int = 0; int < layersObject.length; int++) {
// One layer
var singleLayer = layersObject[int];
// Build a new layer object
var layer = {};
// Determine name from GetCapabilities document
if (singleLayer.Name) {
if (singleLayer.Name[0]) {
layer.Name = singleLayer.Name[0];
}
}
// Determine title from GetCapabilities document
if (singleLayer.Title) {
if (singleLayer.Title[0]) {
layer.Title = singleLayer.Title[0];
}
}
// Determine abstract from GetCapabilities document
if (singleLayer.Abstract) {
if (singleLayer.Abstract[0]) {
layer.Abstract = singleLayer.Abstract[0];
}
}
layer.Layer = buildLayers(singleLayer.Layer);
// Determine layer name if not available
layer.Name = determineLayerName(layer);
// Determine layer title if not available
if (!(layer.Title)) {
layer.Title = layer.Name;
}
// Add layer to the array
layers.push(layer);
}
}
return layers;
}
|
javascript
|
{
"resource": ""
}
|
q14297
|
determineMaxWidth
|
train
|
function determineMaxWidth(json, version) {
var maxWidth = 0;
// Only available in WMS 1.3.0
if (version == '1.3.0') {
if (json.WMS_Capabilities.Service) {
if (json.WMS_Capabilities.Service[0]) {
if (json.WMS_Capabilities.Service[0].MaxWidth) {
if (json.WMS_Capabilities.Service[0].MaxWidth[0]) {
maxWidth = json.WMS_Capabilities.Service[0].MaxWidth[0];
}
}
}
}
}
return maxWidth;
}
|
javascript
|
{
"resource": ""
}
|
q14298
|
determineMaxHeight
|
train
|
function determineMaxHeight(json, version) {
var maxHeight = 0;
// Only available in WMS 1.3.0
if (version == '1.3.0') {
if (json.WMS_Capabilities.Service) {
if (json.WMS_Capabilities.Service[0]) {
if (json.WMS_Capabilities.Service[0].MaxHeight) {
if (json.WMS_Capabilities.Service[0].MaxHeight[0]) {
maxHeight = json.WMS_Capabilities.Service[0].MaxHeight[0];
}
}
}
}
}
return maxHeight;
}
|
javascript
|
{
"resource": ""
}
|
q14299
|
determineWMSTitle
|
train
|
function determineWMSTitle(json, version) {
var ret = '';
if (version == '1.3.0') {
if (json.WMS_Capabilities.Service) {
if (json.WMS_Capabilities.Service[0]) {
if (json.WMS_Capabilities.Service[0].Title) {
if (json.WMS_Capabilities.Service[0].Title[0]) {
ret = json.WMS_Capabilities.Service[0].Title[0];
}
}
}
}
} else {
if (version == '1.1.1' || version == '1.1.0' || version == '1.0.0') {
if (json.WMT_MS_Capabilities.Service) {
if (json.WMT_MS_Capabilities.Service[0]) {
if (json.WMT_MS_Capabilities.Service[0].Title) {
if (json.WMT_MS_Capabilities.Service[0].Title[0]) {
ret = json.WMT_MS_Capabilities.Service[0].Title[0];
}
}
}
}
}
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.