_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q12000
|
buildServer
|
train
|
function buildServer() {
console.log();
console.log(`${chalk.cyan('SERVER-SIDE')}`);
console.log('===========================================================');
fs.emptyDirSync(paths.appServerBuild);
console.log('Creating a server-side production build...');
let compiler = webpack(serverlize(paths, config));
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return reject(err);
}
const messages = formatWebpackMessages(stats.toJson({}, true));
if (messages.errors.length) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(messages.warnings.join('\n\n')));
}
return resolve({
stats,
warnings: messages.warnings,
});
});
}).then(
({ stats, warnings }) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log(`The ${chalk.cyan(path.relative(process.cwd(), paths.appServerBuild))} folder is ready.`);
console.log(`You may run it in ${chalk.cyan('node')} environment`);
console.log();
console.log(` ${chalk.cyan('node')} ${chalk.cyan(path.relative(process.cwd(), paths.appServerBuild))}`);
console.log();
},
err => {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q12001
|
rebuildAttribute
|
train
|
function rebuildAttribute (attrib, data, itemSize) {
if (attrib.itemSize !== itemSize) return true
if (!attrib.array) return true
var attribLength = attrib.array.length
if (Array.isArray(data) && Array.isArray(data[0])) {
// [ [ x, y, z ] ]
return attribLength !== data.length * itemSize
} else {
// [ x, y, z ]
return attribLength !== data.length
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q12002
|
bridge
|
train
|
function bridge(destination, options) {
return transformer
function transformer(node, file, next) {
destination.run(mdast2hast(node, options), file, done)
function done(err) {
next(err)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q12003
|
drawDonutHole
|
train
|
function drawDonutHole(layer) {
if (options.series.pie.innerRadius > 0) {
// subtract the center
layer.save();
var innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius;
layer.globalCompositeOperation = "destination-out"; // this does not work with excanvas, but it will fall back to using the stroke color
layer.beginPath();
layer.fillStyle = options.series.pie.stroke.color;
layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
layer.fill();
layer.closePath();
layer.restore();
// add inner stroke
layer.save();
layer.beginPath();
layer.strokeStyle = options.series.pie.stroke.color;
layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
layer.stroke();
layer.closePath();
layer.restore();
// TODO: add extra shadow inside hole (with a mask) if the pie is tilted.
}
}
|
javascript
|
{
"resource": ""
}
|
q12004
|
makeUtcWrapper
|
train
|
function makeUtcWrapper(d) {
function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
sourceObj[sourceMethod] = function() {
return targetObj[targetMethod].apply(targetObj, arguments);
};
};
var utc = {
date: d
};
// support strftime, if found
if (d.strftime != undefined) {
addProxyMethod(utc, "strftime", d, "strftime");
}
addProxyMethod(utc, "getTime", d, "getTime");
addProxyMethod(utc, "setTime", d, "setTime");
var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
for (var p = 0; p < props.length; p++) {
addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
}
return utc;
}
|
javascript
|
{
"resource": ""
}
|
q12005
|
dateGenerator
|
train
|
function dateGenerator(ts, opts) {
if (opts.timezone == "browser") {
return new Date(ts);
} else if (!opts.timezone || opts.timezone == "utc") {
return makeUtcWrapper(new Date(ts));
} else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
var d = new timezoneJS.Date();
// timezone-js is fickle, so be sure to set the time zone before
// setting the time.
d.setTimezone(opts.timezone);
d.setTime(ts);
return d;
} else {
return makeUtcWrapper(new Date(ts));
}
}
|
javascript
|
{
"resource": ""
}
|
q12006
|
processOptions
|
train
|
function processOptions(plot, options) {
if (options.series.curvedLines.active) {
plot.hooks.processDatapoints.unshift(processDatapoints);
}
}
|
javascript
|
{
"resource": ""
}
|
q12007
|
processDatapoints
|
train
|
function processDatapoints(plot, series, datapoints) {
var nrPoints = datapoints.points.length / datapoints.pointsize;
var EPSILON = 0.005;
//detects missplaced legacy parameters (prior v1.x.x) in the options object
//this can happen if somebody upgrades to v1.x.x without adjusting the parameters or uses old examples
var invalidLegacyOptions = hasInvalidParameters(series.curvedLines);
if (!invalidLegacyOptions && series.curvedLines.apply == true && series.originSeries === undefined && nrPoints > (1 + EPSILON)) {
if (series.lines.fill) {
var pointsTop = calculateCurvePoints(datapoints, series.curvedLines, 1);
var pointsBottom = calculateCurvePoints(datapoints, series.curvedLines, 2);
//flot makes sure for us that we've got a second y point if fill is true !
//Merge top and bottom curve
datapoints.pointsize = 3;
datapoints.points = [];
var j = 0;
var k = 0;
var i = 0;
var ps = 2;
while (i < pointsTop.length || j < pointsBottom.length) {
if (pointsTop[i] == pointsBottom[j]) {
datapoints.points[k] = pointsTop[i];
datapoints.points[k + 1] = pointsTop[i + 1];
datapoints.points[k + 2] = pointsBottom[j + 1];
j += ps;
i += ps;
} else if (pointsTop[i] < pointsBottom[j]) {
datapoints.points[k] = pointsTop[i];
datapoints.points[k + 1] = pointsTop[i + 1];
datapoints.points[k + 2] = k > 0 ? datapoints.points[k - 1] : null;
i += ps;
} else {
datapoints.points[k] = pointsBottom[j];
datapoints.points[k + 1] = k > 1 ? datapoints.points[k - 2] : null;
datapoints.points[k + 2] = pointsBottom[j + 1];
j += ps;
}
k += 3;
}
} else if (series.lines.lineWidth > 0) {
datapoints.points = calculateCurvePoints(datapoints, series.curvedLines, 1);
datapoints.pointsize = 2;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q12008
|
train
|
function(apiKey) {
return function(path, data, done) {
var url = apiBase + path + '?' + querystring.stringify(_.extend({ 'key': apiKey }, data));
request.get(url, globalResponseHandler({ url: url }, done));
};
}
|
javascript
|
{
"resource": ""
}
|
|
q12009
|
buffer
|
train
|
function buffer(arr) {
if (!Array.isArray(arr)) {
return;
}
var l = new List();
arr.forEach(function(el) {
l[syncMethodName("add")](el);
});
return convert[syncMethodName("asScalaBuffer")](l);
}
|
javascript
|
{
"resource": ""
}
|
q12010
|
map
|
train
|
function map(arr) {
var hm = new HashMap();
Object.keys(arr).forEach(function(k) {
hm.put(k, arr[k]);
});
return convert[syncMethodName("asScalaMap")](hm);
}
|
javascript
|
{
"resource": ""
}
|
q12011
|
svgUrl
|
train
|
function svgUrl(name, collection) {
for (var i = 0, result; i < COLLECTION_FILTERS.length; i++) {
if (COLLECTION_FILTERS[i][0].test(collection)) {
result = COLLECTION_FILTERS[i][1];
collection = _.isFunction(result)? result(collection) : result;
break;
}
}
return 'https://raw.github.com/fontello/' + collection +
'/master/src/svg/' + name + '.svg';
}
|
javascript
|
{
"resource": ""
}
|
q12012
|
createGlyph
|
train
|
function createGlyph(name, collection, id, colors, fileFormat) {
var glyph = Object.create(Glyph);
if (!colors) colors = { 'black': 'rgb(0,0,0)' };
if (!fileFormat) fileFormat = "{0}-{1}-{2}.svg";
if (!id) id = name;
glyph.id = id;
glyph.name = name;
glyph.collection = collection;
glyph.url = svgUrl(glyph.name, glyph.collection);
glyph.colors = colors;
glyph.exists = null;
glyph.fileFormat = fileFormat;
return glyph;
}
|
javascript
|
{
"resource": ""
}
|
q12013
|
glyphCreator
|
train
|
function glyphCreator() {
var unique = nodupes();
return function(name, collection, colors) {
return createGlyph(name, collection, unique(name), colors);
};
}
|
javascript
|
{
"resource": ""
}
|
q12014
|
allGlyphs
|
train
|
function allGlyphs(rawGlyphs, colors, fileFormat) {
var unique = nodupes();
rawGlyphs = fixNames(rawGlyphs);
return rawGlyphs.map(function(rawGlyph) {
var name = rawGlyph.css;
var collection = rawGlyph.src;
return createGlyph(name, collection, unique(name), colors, fileFormat);
});
}
|
javascript
|
{
"resource": ""
}
|
q12015
|
missingGlyphs
|
train
|
function missingGlyphs(glyphs, svgDir, cb) {
async.reject(glyphs, function(glyph, cb) {
var filenames = glyph.filenames().map(function(filename) {
return svgDir + '/' + filename;
});
async.every(filenames, fs.exists, cb);
}, cb);
}
|
javascript
|
{
"resource": ""
}
|
q12016
|
BigNumber
|
train
|
function BigNumber(initialNumber) {
var index;
if (!(this instanceof BigNumber)) {
return new BigNumber(initialNumber);
}
this.number = [];
this.sign = 1;
this.rest = 0;
// The initial number can be an array, string, number of another big number
// e.g. array : [3,2,1], ['+',3,2,1], ['-',3,2,1]
// number : 312
// string : '321', '+321', -321'
// BigNumber : BigNumber(321)
// Every character except the first must be a digit
if (!isValidType(initialNumber)) {
this.number = errors['invalid'];
return;
}
if (isArray(initialNumber)) {
if (initialNumber.length && initialNumber[0] === '-' || initialNumber[0] === '+') {
this.sign = initialNumber[0] === '+' ? 1 : -1;
initialNumber.shift(0);
}
for (index = initialNumber.length - 1; index >= 0; index--) {
if (!this.addDigit(initialNumber[index]))
return;
}
} else {
initialNumber = initialNumber.toString();
if (initialNumber.charAt(0) === '-' || initialNumber.charAt(0) === '+') {
this.sign = initialNumber.charAt(0) === '+' ? 1 : -1;
initialNumber = initialNumber.substring(1);
}
for (index = initialNumber.length - 1; index >= 0; index--) {
if (!this.addDigit(parseInt(initialNumber.charAt(index), 10))) {
return;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q12017
|
train
|
function(viewClass) {
var t = this,
newIdNum = 1,
components = t.get('components'),
classParts = viewClass.split('.'),
appName = classParts[0],
appView = classParts[1];
// Instantiate and add the component
var component = new Component({
id: Monitor.generateUniqueCollectionId(components, 'c'),
viewClass: viewClass,
viewOptions: UI.app[appName][appView].prototype.defaultOptions,
css: {
'.nm-cv': 'top:10px;'
}
});
components.add(component);
return component;
}
|
javascript
|
{
"resource": ""
}
|
|
q12018
|
train
|
function(options) {
var t = this,
opts = _.extend({trim:true, deep:true}, options),
raw = Backbone.Model.prototype.toJSON.call(t, opts);
return raw;
}
|
javascript
|
{
"resource": ""
}
|
|
q12019
|
train
|
function() {
var t = this;
t.$el.append(template.apply({}));
t.editor = t.$('.nm-cs-source-edit');
t.sourceButton = t.$('.nm-cs-view-source');
// Get bindings to 'name=' attributes before custom views are rendered
t.componentBindings = Backbone.ModelBinder.createDefaultBindings(t.$el, 'name');
}
|
javascript
|
{
"resource": ""
}
|
|
q12020
|
train
|
function(model, componentView, customView) {
var t = this,
componentPane = t.$('.nm-cs-component');
// Remember the model state on entry
t.model = model;
t.componentView = componentView;
t.monitor = model.get('monitor');
t.originalModel = t.model.toJSON({trim:false});
// Remove any inner views
if (t.sourceView) {
t.sourceView.remove();
}
if (t.customView) {
t.customView.remove();
}
// Clean up prior monitorParams
if (t.monitorParams) {
t.monitorParams.off('change');
}
// Create the custom settings view
if (customView) {
t.customView = new customView({
model: t.model.get('viewOptions'),
monitor: t.model.get('monitor'),
pageView: UI.pageView,
component: t.model,
componentView: componentView
});
t.$('.nm-cs-view-settings').append(t.customView.el);
t.customView.render();
// Attach tooltips to anything with a title
UI.tooltip(t.$('*[title]'));
}
// Normal data binding - name to model
t.modelBinder.bind(t.model, t.$el, t.componentBindings);
// Bind data-view-option elements to component.viewOptions
t.viewOptionBinder.bind(
t.model.get('viewOptions'),
componentPane,
Backbone.ModelBinder.createDefaultBindings(componentPane, 'data-view-option')
);
// Bind data-monitor-param elements to monitor.initParams.
// This is a bit more difficult because initParams isnt a Backbone model.
// Copy into a Backbone model, and bind to that.
t.monitorParams = new Backbone.Model(t.monitor.get('initParams'));
t.monitorParamBinder.bind(
t.monitorParams,
componentPane,
Backbone.ModelBinder.createDefaultBindings(componentPane, 'data-monitor-param')
);
t.monitorParams.on('change', function() {
t.monitor.set('initParams', t.monitorParams.toJSON());
});
// Instantiate the source view
t.sourceView = new UI.JsonView({
model: t.model.toJSON({trim:false})
});
t.sourceView.render();
t.$('.nm-cs-source-view').append(t.sourceView.$el);
}
|
javascript
|
{
"resource": ""
}
|
|
q12021
|
train
|
function(e) {
var t = this;
// Make view options changes immediately on keydown
// Note: Don't be so aggressive with monitor initParams, because that
// could result in backend round-trips for each keystroke.
setTimeout(function(){
t.viewOptionBinder._onElChanged(e);
},0);
// Call the parent keydown
t.onKeydown(e);
}
|
javascript
|
{
"resource": ""
}
|
|
q12022
|
train
|
function() {
var t = this;
// Add the component to the model, then to the page view
var copy = t.model.toJSON();
delete copy.id;
var component = t.pageView.model.addComponent(copy.viewClass);
component.set(copy);
// Position the component on top left
var cv = t.pageView.getComponentView(component.get('id'));
cv.raiseToTop(true);
cv.moveToLeft();
t.pageView.leftJustify();
t.pageView.centerPage();
// Close the dialog box
t.closeDialog();
}
|
javascript
|
{
"resource": ""
}
|
|
q12023
|
train
|
function(dirpath, file) {
var templateFile = Path.join(__dirname, '../template/app', dirpath, file),
outputFile = Path.join(appPath, dirpath, file);
try {
var template = new Template({text: FS.readFileSync(templateFile).toString(), watchFile:false});
FS.writeFileSync(outputFile, template.apply(templateParams));
} catch(e) {
logger.fatal('Template', 'Cannot process template file: ' + templateFile + '. reason: ', e.toString());
process.exit(1);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12024
|
train
|
function(dirpath) {
try {
// Make the directory under the app
if (dirpath !== '/') {
FS.mkdirSync(Path.join('.', appPath, dirpath));
}
// Read the template directory
var templateDir = Path.join(__dirname, '../template/app', dirpath);
var files = FS.readdirSync(templateDir);
files.forEach(function(file) {
var fullFile = Path.join(templateDir, file);
var stat = FS.statSync(fullFile);
if (stat.isDirectory()) {
// Go into it
outputDir(Path.join(dirpath, file));
}
else {
outputFile(dirpath, file);
}
});
} catch(e) {
logger.fatal('Template', 'Cannot process template directory: ' + dirpath + '. reason: ', e.toString());
process.exit(1);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12025
|
buildClasses
|
train
|
function buildClasses (db) {
const classes = data.findClasses(db).order('name')
return classes.map(function (klass) {
const fns = data
.findChildFunctions(db, [klass])
.order('name')
.map(copyFunction)
return copyClass(klass, fns)
})
}
|
javascript
|
{
"resource": ""
}
|
q12026
|
train
|
function() {
var t = this;
if (t.dirWatcher) {
t.dirWatcher.close();
t.dirWatcher = null;
}
for (var pageId in t.fileWatchers) {
t.fileWatchers[pageId].close();
}
t.fileWatchers = {};
}
|
javascript
|
{
"resource": ""
}
|
|
q12027
|
train
|
function(dirs, callback) {
var t = this,
numLeft = dirs.length,
fileRegexp = /.json$/,
trimmed = [];
// Already trimmed
if (numLeft === 0) {
return callback(null, dirs);
}
// Process each directory
dirs.forEach(function(dir) {
t.hasContents(dir.path, fileRegexp, function(error, hasContents) {
if (error) {
numLeft = 0;
return callback(error);
}
delete dir.path;
if (hasContents) {
trimmed.push(dir);
}
if (--numLeft === 0) {
return callback(null, trimmed);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12028
|
train
|
function(dirname, fileRegexp, callback) {
var t = this;
// Get the directory at this level
FS.readdir(dirname, function(error, fileNames) {
// Process errors
if (error) {
console.error('Read dir error', error);
return callback(error);
}
// Process sequentially until content is found.
// If parallel, a deep scan would occur every time.
var dirsToCheck = [];
function checkNext() {
// Done checking all filenames
if (fileNames.length === 0) {
// Check directories, and return true if any have content
t.trimDirs(dirsToCheck, function(error, trimmed) {
return callback(error, trimmed.length > 0);
});
return;
}
// Stat the next entry
var filename = fileNames[0];
fileNames.splice(0,1);
var pathName = Path.join(dirname, filename);
FS.stat(pathName, function(error, stat) {
if (error) {
return callback(error);
}
// Check for directory content or if a file should be included
if (stat.isDirectory()) {
dirsToCheck.push({path:pathName});
}
else {
// There is content if a file exists and it matches an optional regexp
if (!fileRegexp || fileRegexp.test(filename)) {
return callback(null, true);
}
}
// Check the next filename
checkNext();
});
}
// Kick off the first check
checkNext();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12029
|
train
|
function(fileNames, callback) {
var t = this,
stats = [],
didError = false,
numLeft = fileNames.length;
// No files to process
if (fileNames.length === 0) {
return callback(null, stats);
}
// Call stat on each file
fileNames.forEach(function(fileName, index) {
var fullPath = Path.join(t.dirPath, fileName);
FS.stat(fullPath, function(error, stat) {
// Process a stat error
if (error) {
didError = true;
return callback(error);
}
// Do nothing if a prior error callback happened
if (didError) {
return;
}
// Set this stat item
stats[index] = stat;
// Callback if all stats are complete
if (--numLeft === 0) {
callback(null, stats);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12030
|
train
|
function() {
var t = this,
branches = t.model.get('branches'),
leaves = t.model.get('leaves'),
hash = "";
// The hash is the text of the branches & leaves
branches && branches.forEach(function(node) {
var label = node.get('label') || node.id,
description = node.get('description');
hash += '|' + label;
if (description) {
hash += '|' + description;
}
});
// The hash is the text of the branches & leaves
leaves && leaves.forEach(function(node) {
var label = node.get('label') || node.id,
description = node.get('description');
hash += '|' + label;
if (description) {
hash += '|' + description;
}
});
// Return the hash
return hash;
}
|
javascript
|
{
"resource": ""
}
|
|
q12031
|
train
|
function() {
var t = this,
branches = t.model.get('branches'),
leaves = t.model.get('leaves');
// Determine if we should connect a monitor to this node
//
// Connect a monitor if:
// * There isn't one already connected, and
// * There's a monitor definition available, and
// * We're open, or
// * preFetch is selected, and
// * we have no parent or our parent is open
//
// ** Is there any way to make this logic simpler?
var shouldConnect = !t.model.hasMonitor()
&& t.options.monitorParams
&& (t.model.get('isOpen')
|| (t.options.preFetch
&& (!t.options.parentView
|| t.options.parentView.model.get('isOpen'))));
// Connect to the monitor if we've determined we should
if (shouldConnect) {
// If there isn't any model data to display, show Loading...
if (!branches || !leaves) {
t.loading = $('<li>Loading...</li>').appendTo(t.$el);
}
// Build and connect the Monitor
var initParams = _.extend(
{},
t.options.monitorParams.initParams || {},
{path:t.options.path}
);
var monitorParams = _.extend(
{},
t.options.monitorParams,
{initParams: initParams}
);
t.monitor = new Monitor(monitorParams);
t.model.attachMonitor(t.monitor);
// Call our handlers once connected
t.monitor.on('connect', function(){
setTimeout(function(){
for (var i in t.connectHandlers) {
var handler = t.connectHandlers[i];
handler(t.monitor);
}
},10);
});
// Connect the monitor and process errors. Successes will change
// the underlying data model (or not), causing a re-render.
t.monitor.connect(function(error) {
// Remove the Loading... message
if (t.loading) {
t.loading.remove();
t.loading = null;
}
// Handle errors
if (error) {
$('<li>(connection problem)</li>').appendTo(t.$el);
console.error('TreeView monitor connection problem:', error, t.monitor);
// Detach the problem monitor so it'll have another chance
// if the user opens/closes the branch.
t.model.detachMonitor();
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12032
|
train
|
function() {
var t = this,
json = t.model.toJSON({trim:false});
t.sourceView.model = json;
t.sourceView.setData();
t.editor.val(JSON.stringify(json, null, 2));
}
|
javascript
|
{
"resource": ""
}
|
|
q12033
|
train
|
function(params, options) {
var t = this,
port = t.get('port'),
server = t.get('server'),
templates = t.get('templates'),
siteDbPath = t.get('siteDbPath'),
parentPath = siteDbPath.indexOf('.') === 0 ? process.cwd() : '';
// Distribute the site path to probes that need it
t.set('siteDbPath', Path.join(parentPath, siteDbPath));
// Initialize probes
SyncProbe.Config.defaultProbe = 'FileSyncProbe';
SyncProbe.FileSyncProbe.setRootPath(siteDbPath);
// Expose the current instance so probes running
// in this process can communicate with the server
UI.Server.currentServer = t;
// Internal (non-model) attributes
t.apps = {}; // Hash appName -> app data
t.site = null; // Site model associated with the server
// Create a connect server if no custom server was specified
if (!server) {
server = new Connect();
t.set({server: server});
}
// Attach server components
server.use(t.siteRoute.bind(t));
server.use(Connect['static'](Path.join(__dirname, '/../..')));
// Create a static server to the monitor distribution
var monitorDistDir = require.resolve('monitor').replace(/lib[\\\/]index.js/, 'dist');
t.monitorDist = Connect['static'](monitorDistDir);
// Initialize the template library
var gruntModules = GruntConfig.MODULE_DEF;
gruntModules.templates.sort().forEach(function(template){
var path = Path.normalize(__dirname + '/../../' + template);
var id = Path.basename(path, '.html');
templates.add({id:id, path:path});
});
// Build the page parameters from the config file
var styles = "", scripts="";
gruntModules.client_css.forEach(function(cssFile) {
styles += CSS_TEMPLATE({cssFile: cssFile.replace('lib/','/static/')});
});
var clientScripts = gruntModules.client_ext.concat(gruntModules.shared_js.concat(gruntModules.client_js));
clientScripts.forEach(function(file) {
scripts += JS_TEMPLATE({scriptFile: file.replace('lib/','/static/')});
});
_.extend(PAGE_PARAMS, {
styles: styles, scripts: scripts, version: PACKAGE_JSON.version
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12034
|
train
|
function(request, response, next) {
var t = this;
// URL rewrites
var url = URL.resolve('', request.url);
if (url === '/favicon.ico') {
var faviconUrl = t.site.get('favicon');
url = request.url = faviconUrl || request.url;
}
// Remove the leading slash for page manipulation
url = url.substr(1);
// Rewrite the url and forward if it points to static content
var urlParts = url.split('/');
if (urlParts[0] === 'static') {
// Replace static with lib, and put the leading slash back in
request.url = url.replace('static/', '/lib/');
// Forward to the monitor distribution
if (request.url.indexOf('monitor-all.js') > 0) {
request.url = '/monitor-all.js';
return t.monitorDist(request, response, next);
}
// Next is the static server
return next();
}
// If it's an URL to an app, route to the app
if (urlParts[0] === 'app') {
var appName = urlParts[1],
app = t.apps[appName];
// Route to a monitor page if the app doesn't handle the request
var appNext = function() {
t._monitorPageRoute(request, response, next);
};
// Continue if the app isn't defined
if (!app) {
return appNext();
}
// Make the app request relative to the app
var appUrl = '/' + url.split('/').slice(2).join('/'),
appRequest = _.extend({}, request, {url: appUrl});
// Forward the request to the app server
var server = typeof app.server === 'function' ? app.server : app.staticServer;
return server(appRequest, response, appNext);
}
// Forward to a monitor page
t._monitorPageRoute(request, response, next);
}
|
javascript
|
{
"resource": ""
}
|
|
q12035
|
train
|
function(request, response, next) {
var t = this,
url = request.url,
searchStart = url.indexOf('?'),
templates = t.get('templates');
// Remove any URL params
if (searchStart > 0) {
url = url.substr(0, searchStart);
}
// Get the page model
t._getPage(url, function(error, pageModel) {
if (error) {
return response.end('page error: ' + JSON.stringify(error));
}
// Build the object to put into the page template
var page = _.extend({templates:''}, PAGE_PARAMS, t.site.toJSON(), pageModel.toJSON());
page.pageParams = Template.indent(JSON.stringify(pageModel.toJSON({deep:true,trim:true}), null, 2), 8);
// Add all watched templates except the main page
templates.each(function(template) {
if (template.id !== 'UI') {
page.templates += TMPL_TEMPLATE({
id:template.id,
text:Template.indent(template.get('text'),8)
});
}
});
// Output the page
response.writeHead(200, {'Content-Type': 'text/html'});
var pageTemplate = templates.get('UI');
return response.end(pageTemplate.apply(page));
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12036
|
train
|
function(url, callback) {
var t = this,
originalUrl = url,
page = null;
// Change urls that end in / to /index
if (url.substr(-1) === '/') {
url = url + 'index';
}
// Return if it's in cache
page = pageCache.get(url);
if (page) {
return callback(null, page);
}
// Read from storage
page = new Page({id: url});
page.fetch({liveSync: true, silenceErrors: true}, function(error) {
// Process a 404. This returns a transient page copied from
// the default 404 page, with the id replaced by the specified url.
if (error && error.code === 'NOTFOUND' && url !== '/app/core/404') {
// Default the home page if notfound
if (originalUrl === '/') {
return t._getPage('/app/core/index', callback);
}
// Default the 404 page if notfound
if (originalUrl === '/404') {
return t._getPage('/app/core/404', callback);
}
// Otherwise it's a new page. Create it.
t._getPage('/404', function(error, page404) {
if (error) {
console.error("Error loading the 404 page", error);
return callback('404 page load error');
}
// Copy the 404 page into a new page
var newPage = new Page(JSON.parse(JSON.stringify(page404)));
// Build a sane starting title. TitleCase the last url element, separate words, replace underscores
var title = $.titleCase(url.split('/').pop(), true).replace(/([A-Z])/g," $1").replace(/^ /,'').replace(/_/g,' ');
var title = url.split('/').pop().replace(/([A-Z])/g," $1").replace(/^ /,'').replace(/_/g,' ');
newPage.set({id:url, title:title, is404page:true});
callback(null, newPage);
});
return;
}
// Process other errors
if (error) {
return callback(error);
}
// Assure the page model ID is correct on disk
if (url !== page.get('id')) {
page.set('id', url);
}
// Put the page into cache and return it
pageCache.add(page);
return callback(null, page);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12037
|
train
|
function(callback) {
callback = callback || function(){};
var t = this,
server = t.get('server'),
port = t.get('port'),
allowExternalConnections = t.get('allowExternalConnections');
// Allow connections from INADDR_ANY or LOCALHOST only
var host = allowExternalConnections ? '0.0.0.0' : '127.0.0.1';
// Start listening
server.listen(port, host, function(){
// Allow the UI server to be a Monitor gateway server
t.monitorServer = new Monitor.Server({server:server, gateway: true});
t.monitorServer.start(function(){
// Called after the site object is loaded
var onSiteLoad = function(error) {
if (error) {
return callback(error);
}
// Discover and initialize application modules
t.loadApps();
// Bind server events
t._bindEvents(callback);
};
// Load and keep the web site object updated
t.site = new Site();
t.site.fetch({liveSync: true, silenceErrors:true}, function(error) {
// Initialize the site if it's not found
if (error && error.code === 'NOTFOUND') {
t.site = new Site();
t.site.id = null; // This causes a create vs. update on save
return t.site.save({}, {liveSync: true}, onSiteLoad);
} else if (error) {
return onSiteLoad(error);
}
// Bind server events once connected
onSiteLoad();
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12038
|
train
|
function() {
var t = this;
// Test an app directory to see if it's a monitor app
var testAppDir = function(dir) {
// Load the package.json if it exists (and remove relative refs)
var pkg;
dir = Path.resolve(dir);
try {
pkg = JSON.parse(FS.readFileSync(dir + '/package.json', 'utf-8'));
} catch (e) {
// Report an error if the package.json has a parse problem. This is
// good during app development to show why we didn't discover the app.
if (e.code !== "ENOENT") {
console.error("Problem parsing " + dir + "/package.json");
}
return false;
}
// Is this a monitor-dashboard app?
var isMonitorApp = pkg.dependencies && _.find(_.keys(pkg.dependencies), function(keyword){ return keyword === 'monitor-dashboard'; });
if (!isMonitorApp) {
return false;
}
// This is a monitor-dashboard app.
return t.loadApp(dir, pkg);
};
// Process all apps under a node_modules directory
var loadNodeModulesDir = function(dir) {
// Return if the node_modules directory doesn't exist.
try {
FS.statSync(dir);
} catch (e) {return;}
// Check each direcory for a monitor-dashboard app
FS.readdirSync(dir).forEach(function(moduleName) {
// See if this is a monitor app, and load if it is
// then load sub-modules
var moduleDir = dir + '/' + moduleName;
if (testAppDir(moduleDir) || moduleName === 'monitor') {
// If it is a monitor-app, process any sub node_modules
loadNodeModulesDir(moduleDir + '/node_modules');
}
});
};
// Test this app as a monitor app
t.thisAppName = testAppDir('.');
// Process all possible node_module directories in the require path.
process.mainModule.paths.forEach(loadNodeModulesDir);
}
|
javascript
|
{
"resource": ""
}
|
|
q12039
|
train
|
function(dir) {
// Load the package.json if it exists (and remove relative refs)
var pkg;
dir = Path.resolve(dir);
try {
pkg = JSON.parse(FS.readFileSync(dir + '/package.json', 'utf-8'));
} catch (e) {
// Report an error if the package.json has a parse problem. This is
// good during app development to show why we didn't discover the app.
if (e.code !== "ENOENT") {
console.error("Problem parsing " + dir + "/package.json");
}
return false;
}
// Is this a monitor-dashboard app?
var isMonitorApp = pkg.dependencies && _.find(_.keys(pkg.dependencies), function(keyword){ return keyword === 'monitor-dashboard'; });
if (!isMonitorApp) {
return false;
}
// This is a monitor-dashboard app.
return t.loadApp(dir, pkg);
}
|
javascript
|
{
"resource": ""
}
|
|
q12040
|
train
|
function(dir) {
// Return if the node_modules directory doesn't exist.
try {
FS.statSync(dir);
} catch (e) {return;}
// Check each direcory for a monitor-dashboard app
FS.readdirSync(dir).forEach(function(moduleName) {
// See if this is a monitor app, and load if it is
// then load sub-modules
var moduleDir = dir + '/' + moduleName;
if (testAppDir(moduleDir) || moduleName === 'monitor') {
// If it is a monitor-app, process any sub node_modules
loadNodeModulesDir(moduleDir + '/node_modules');
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12041
|
train
|
function(callback) {
var t = this, server = t.get('server');
callback = callback || function(){};
// Unwatch all template files
t.get('templates').forEach(function(template) {
template.unWatchFile();
});
// Don't stop more than once.
if (!t.isListening) {
return callback();
}
// Shut down the server
t.isListening = false;
t.monitorServer.stop(function(error) {
if (!error) {
// Disregard close exception
try {
server.close();
} catch (e) {}
t.trigger('stop');
}
return callback(error);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12042
|
train
|
function() {
var t = this;
t.$el.append(template.apply({}));
t.dialog = t.$('.modal');
// Build the tour tree view
t.tv = new UI.TreeView({
preFetch: true,
monitorParams: {probeClass: 'ToursProbe'}
});
t.tv.render().appendTo(t.$('.nm-tsv-tree'));
// Select the first tour once the tree is loaded
t.tv.whenConnected(function(tree) {
t.firstTour();
});
// Instantiate the new tour page view
t.newTourPage = new UI.NewTourPage({tourSettings:t});
t.newTourPage.render();
UI.pageView.$el.append(t.newTourPage.$el);
}
|
javascript
|
{
"resource": ""
}
|
|
q12043
|
train
|
function(e) {
var t = this,
item = $(e.currentTarget),
path = item.attr('data-path');
t.showTour(path);
}
|
javascript
|
{
"resource": ""
}
|
|
q12044
|
train
|
function() {
var t = this;
// Set the current tour pages
t.pages = t.tour.get('pages');
// Tour fields
t.$('.nm-tsv-id').val(t.tour.get('id'));
t.$('.nm-tsv-title').val(t.tour.get('title'));
t.$('.nm-tsv-description').val(t.tour.get('description'));
t.$('.nm-tsv-auto-next-sec').val(t.tour.get('autoNextSec'));
var pageList = t.$('.nm-tsv-page-list').html('');
// Tour pages
var table = $('<table></table>').appendTo(pageList);
for (var i = 0; i < t.pages.length; i++) {
var page = t.pages[i];
$('<tr><td>' + page['title'] + '</td><td class="nm-tsv-up" title="move up"><i class="icon-caret-up"></i></td><td class="nm-tsv-down" title="move down"><i class="icon-caret-down"></i></td><td class="nm-tsv-remove" title="remove page"><i class="icon-minus"></i></td></tr>').appendTo(table);
}
// Connect all tooltips
UI.tooltip(t.$('*[title]'),{placement:'bottom'});
}
|
javascript
|
{
"resource": ""
}
|
|
q12045
|
train
|
function() {
var t = this;
// Show the modal dialog
t.dialog.centerBox().css({top:40}).modal('show');
// Set the cursor when the dialog fades in
setTimeout(function(){
t.$('.nm-tsv-title').focus();
}, 500);
}
|
javascript
|
{
"resource": ""
}
|
|
q12046
|
train
|
function() {
var t = this;
for (var i in t.tv.orderedNodes) {
var node = t.tv.orderedNodes[i];
if (node.type === 'leaf') {
var tour = node.node;
t.showTour('/' + tour.get('id'));
break;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12047
|
train
|
function(e) {
var t = this;
// Scrape the form
var params = {
title: t.$('.nm-tsv-title').val(),
description: t.$('.nm-tsv-description').val(),
autoNextSec: t.$('.nm-tsv-auto-next-sec').val()
};
if (!parseInt(params.autoNextSec)) {
// Assure blank, NaN, undefined, 0, etc translates to 0 (no auto-next)
params.autoNextSec = 0;
}
t.tour.set(params);
t.tour.isDirty = true;
t.setDirty(true);
t.loadForm();
// Change the title/description in the tree view
var tvNode = t.tv.model.getByPath(t.tour.get('id'));
tvNode.set({
label: params.title ? params.title : ' ',
description: params.description
});
// If the tour is deleted, go to the first one
if (!params.title) {
t.firstTour();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12048
|
train
|
function() {
var t = this,
modal = t.newTourPage.$('.modal');
UI.hideToolTips();
modal.centerBox().css({top:20, left:modal.css('left').replace(/px/,'') - 40}).modal('show');
$('.modal-backdrop:last-child').css({zIndex:1140});
}
|
javascript
|
{
"resource": ""
}
|
|
q12049
|
train
|
function(page) {
var t = this,
newPages = t.pages.slice(0);
newPages.push(page);
t.tour.set('pages', newPages);
t.tour.isDirty = true;
t.setDirty(true);
t.loadForm();
}
|
javascript
|
{
"resource": ""
}
|
|
q12050
|
setAttr
|
train
|
function setAttr(setModel, newValue, setOptions) {
var oldValue = model._containedModels[attrName];
// Pass through if removing
if (newValue === undefined || newValue === null) {
model._containedModels[attrName] = newValue;
return;
}
// Is the new value the correct type?
if (newValue instanceof Ctor) {
// Directly set if no old value
if (!oldValue instanceof Ctor) {
model._containedModels[attrName] = newValue;
return;
}
// They're both models. Disregard if they're the same.
var oldJSON = oldValue.toJSON({deep:true});
var newJSON = newValue.toJSON({deep:true});
if (_.isEqual(oldJSON, newJSON)) {
return;
}
// Merge the raw JSON if they're both models
newValue = newJSON;
}
// Keep the previous model and merge new data into it
// For collections this relies on the Collection.set() method
if (oldValue instanceof Ctor) {
model.attributes[attrName] = oldValue;
model._currentAttributes[attrName] = oldValue;
model.changed[attrName] = oldValue;
oldValue.set(newValue, setOptions);
return;
}
// Create a new model or collection, passing the value
newValue =
model._containedModels[attrName] =
model.attributes[attrName] =
model._currentAttributes[attrName] =
new Ctor(newValue, setOptions);
// Watch for changes to the underlying model or collection
// (collection add/remove), forwarding changes to this model
newValue.on('change add remove reset', UI.onSubModelChange, {
parent:model,
attrName: attrName
});
}
|
javascript
|
{
"resource": ""
}
|
q12051
|
train
|
function(params, options) {
var t = this;
// If raw text was sent to the template, compile and return
if (t.get('text')) {
t.compile();
return;
}
// Watch for changes in the text element
t.on('change:text', t.compile, t);
// Process a file template
var path = t.get('path');
if (path) {
// Load the file
if (t.asyncLoad) {
FS.readFile(path, function(err, text) {
if (err) {
return console.error('Error reading file: ' + path, err);
}
t.set({text: text.toString()});
});
} else {
t.set({text: FS.readFileSync(path).toString()});
}
// Watch the file for changes
if (t.get('watchFile')) {
t._watchFile();
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12052
|
train
|
function() {
var t = this, path = t.get('path');
t.watcher = FileProbe.watchLoad(path, {persistent: true}, function(error, content) {
if (!error) {
t.set('text', content);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12053
|
train
|
function(params) {
var t = this, text = t.get('text'), compiled = t.get('compiled');
// Convert parameters to JS object if they're a backbone model
if (params instanceof Backbone.Model) {
params = params.toJSON();
}
// Compile the template if necessary
if (!compiled) {
compiled = t.compile();
}
// Apply the template
return compiled(params);
}
|
javascript
|
{
"resource": ""
}
|
|
q12054
|
train
|
function() {
var t = this, text = t.get('text');
var compiled = Mustache.compile(text);
t.set({compiled: compiled});
return compiled;
}
|
javascript
|
{
"resource": ""
}
|
|
q12055
|
train
|
function() {
var styles = {},
viewOptions = component.get('viewOptions'),
title = viewOptions.get('title') || '',
background = viewOptions.get('background'),
css = component.get('css');
for (var selector in css) {
styles['#' + component.id + ' ' + selector] = css[selector];
}
$.styleSheet(styles, 'nm-cv-css-' + component.id);
t.$('.nm-cv')
.toggleClass('background', background === true)
.toggleClass('title', title.length > 0);
t.$('.nm-cv-title span').text(title);
}
|
javascript
|
{
"resource": ""
}
|
|
q12056
|
train
|
function() {
// Don't continue if the probe portion was what changed.
var thisMonitor = JSON.stringify(monitor.toMonitorJSON());
if (thisMonitor === t.priorMonitor) {
return;
}
// Remove the component listeners
log.info('render.monitorChange', t.logCtxt);
component.off('change:css change:viewOptions', applyStyles);
component.off('change:monitor', onMonitorChange, t);
// Disconnect, then build a fresh component
t.connectMonitor(false, function(){
UI.pageView.removeComponent(t.model);
UI.pageView.addComponent(t.model);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12057
|
train
|
function() {
var t = this;
UI.hideToolTips();
UI.pageView.model.get('components').remove(t.model);
t.connectMonitor(false);
t.view.remove();
}
|
javascript
|
{
"resource": ""
}
|
|
q12058
|
train
|
function(connect, callback) {
callback = callback || function(){};
var t = this,
needsConnecting = false,
logMethod = (connect ? 'connectMonitor' : 'disconnectMonitor'),
originalParams = null,
monitor = t.model.get('monitor'),
isConnected = monitor.isConnected();
// Determine if we need to connect/disconnect
if (
(connect && !isConnected && monitor.get('probeClass')) ||
(!connect && isConnected)) {
needsConnecting = true;
}
// If no need to connect, callback on next tick. This makes the
// call stack consistent regardless of the presence of monitors.
if (!needsConnecting) {
log.info(logMethod + '.alreadyConnected', t.logCtxt);
setTimeout(function(){
callback(null);
},0);
return;
}
// If connecting, override the init params with url params
if (connect) {
originalParams = monitor.get('initParams');
monitor.set(
{initParams: _.extend({}, originalParams, initOverrides)},
{silent: true}
);
}
else {
// If disconnecting, remove all change listeners
monitor.off('change');
}
// Connect or disconnect, calling the callback when done
var connectFn = connect ? 'connect' : 'disconnect';
log.info(logMethod, t.logCtxt);
monitor[connectFn](function(error) {
// Replace original initParams (so the page isn't dirty)
// Acutal init params will become attributes of the monitor object
if (originalParams) {
monitor.set(
{initParams: originalParams},
{silent: true}
);
}
// If disconnecting, clear the probe data
if (!connect) {
var probeElems = monitor.toProbeJSON();
delete probeElems.id;
monitor.set(probeElems, {unset:true});
}
// Callback passing error if set
return callback(error);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12059
|
train
|
function(e) {
var t = this;
UI.pauseTour();
// Set the component model into the settings view
settingsView.setModel(t.model, t, t.viewClass['SettingsView']);
// Center and show the settings
$('#nm-cv-settings').centerBox().css({top:40}).modal('show');
e.stopPropagation();
// Place the cursor into the first field once the form fades in
setTimeout(function(){
settingsView.$('#nm-cv-settings input').first().focus();
}, 500);
}
|
javascript
|
{
"resource": ""
}
|
|
q12060
|
train
|
function() {
var t = this,
pageView = UI.pageView,
pageModel = pageView.model,
view = t.view,
getMonitor = function(id) {return pageView.getMonitor(id);},
monitor = t.model.get('monitor');
// Execute the onInit
try {
eval(t.model.get('onInit'));
}
catch (e) {
log.error('onInitException', t.logCtxt, e);
alert("Component onInit exception. See error log for more information.");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12061
|
train
|
function(persist) {
var t = this,
viewElem = t.$('.nm-cv'),
thisZIndex = (viewElem.css('zIndex') === 'auto' ? 0 : +viewElem.css('zIndex')),
components = UI.pageView.model.get('components'),
maxZIndex = 0;
// Get the maximum z-index (disregarding this)
components.forEach(function(component) {
var id = component.get('id'),
elem = $('#' + id + ' .nm-cv'),
zIndex = elem.css('zIndex') === 'auto' ? 0 : +elem.css('zIndex');
if (id === t.model.get('id')) {return;}
if (zIndex > maxZIndex) {
maxZIndex = zIndex;
}
});
// Set this z-index to the max + 1 (unless already there)
if (maxZIndex >= thisZIndex) {
thisZIndex = maxZIndex + 1;
if (persist) {
// Change the model CSS.
var css = _.clone(t.model.get('css')),
parsedCss = $.parseStyleString(css['.nm-cv'] || '');
parsedCss['z-index'] = thisZIndex;
css['.nm-cv'] = $.makeStyleString(parsedCss);
t.model.set({css: css});
} else {
t.$('.nm-cv').css({zIndex: thisZIndex});
}
}
// Return this zIndex
return thisZIndex;
}
|
javascript
|
{
"resource": ""
}
|
|
q12062
|
train
|
function() {
var t = this,
viewElem = t.$('.nm-cv'),
width = viewElem.outerWidth() + 10;
// Change the model CSS.
var css = _.clone(t.model.get('css')),
parsedCss = $.parseStyleString(css['.nm-cv'] || '');
parsedCss['left'] = '-' + width + 'px';
css['.nm-cv'] = $.makeStyleString(parsedCss);
t.model.set({css: css});
}
|
javascript
|
{
"resource": ""
}
|
|
q12063
|
train
|
function() {
var t = this;
t.saveChanges();
// Open the new component dialog if no components exist
if (t.model.get('components').length === 0) {
t.pageView.newComponent();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12064
|
train
|
function() {
var t = this;
if (window.confirm('Are you sure you want to permanently delete this page?')) {
t.pageView.exiting = true;
t.model.destroy(function(){
UI.pageView.navigateTo('/');
});
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q12065
|
train
|
function(e) {
var t = this,
item = $(e.currentTarget),
id = item.attr('data-id'),
path = item.attr('data-path');
// Process a tour selection
if ($(e.currentTarget).parents('.nm-sb-tours').length) {
UI.pageView.runTour(path);
return;
}
// Process a page selection
UI.pageView.navigateTo(path);
}
|
javascript
|
{
"resource": ""
}
|
|
q12066
|
train
|
function(e) {
var t = this;
UI.hideToolTips();
UI.pauseTour();
// Tell the settings it's about to be shown
UI.pageView.$('#nm-pv-new').centerBox().css({top:100}).modal('show');
setTimeout(function(){
$('.nm-np-address').focus();
}, 500);
// Don't propagate the click to the heading
e.stopPropagation();
}
|
javascript
|
{
"resource": ""
}
|
|
q12067
|
train
|
function(e) {
var t = this;
UI.hideToolTips();
UI.pauseTour();
// Tell the settings it's about to be shown
t.tourSettingsView.show();
// Don't propagate the click to the heading
e.stopPropagation();
}
|
javascript
|
{
"resource": ""
}
|
|
q12068
|
train
|
function(e) {
var t = this,
sidebar = $('.nm-sb'),
newWidth = startWidth = sidebar.width(),
startX = e.pageX;
function drag(e) {
newWidth = startWidth + (e.pageX - startX);
sidebar.css({width:newWidth});
t.tour.css({left: newWidth + t.handleWidth});
UI.pageView.centerPage();
}
function drop(e) {
t.handle.removeClass('drag');
$(document).unbind("mousemove", drag).unbind("mouseup", drop);
// Simulate click?
if (newWidth === startWidth) {
newWidth = startWidth === 0 ? Sidebar.prototype.defaults.width : 0;
}
// Auto-close?
else if (newWidth < 30) {
newWidth = 0;
}
// Set the width, center the page, and persist
t.sidebar.set('width', newWidth);
sidebar.css({width: newWidth});
t.tour.css({left: newWidth + t.handleWidth});
UI.pageView.centerPage();
}
$(document).bind("mousemove", drag).bind("mouseup", drop);
t.handle.addClass('drag');
drag(e);
e.preventDefault();
}
|
javascript
|
{
"resource": ""
}
|
|
q12069
|
train
|
function() {
var t = this,
sbJSON = t.sidebar.toJSON({deep:true, trim:true});
// Function to trim closed sub-branches from a tree
var trimSubBranch = function(tree) {
var branches = tree.branches;
for (var i in branches) {
var subTree = branches[i];
if (subTree.isOpen && !subTree.isLoading) {
branches[i] = trimSubBranch(subTree);
} else {
branches[i] = {
id: subTree.id,
};
if (subTree.label) {
branches[i].label = subTree.label;
}
}
}
return tree;
};
// Trim sub-tree elements in pages, and save
for (var i = 0; i < sbJSON.tree.branches.length; i++) {
sbJSON.tree.branches[i] = trimSubBranch(sbJSON.tree.branches[i]);
}
localStorage.sidebar = JSON.stringify(sbJSON);
}
|
javascript
|
{
"resource": ""
}
|
|
q12070
|
train
|
function(tree) {
var branches = tree.branches;
for (var i in branches) {
var subTree = branches[i];
if (subTree.isOpen && !subTree.isLoading) {
branches[i] = trimSubBranch(subTree);
} else {
branches[i] = {
id: subTree.id,
};
if (subTree.label) {
branches[i].label = subTree.label;
}
}
}
return tree;
}
|
javascript
|
{
"resource": ""
}
|
|
q12071
|
train
|
function(size) {
var t = this,
css = _.clone(t.get('css')),
parsedCss = $.parseStyleString(css['.nm-cv-viewport'] || '');
if (!parsedCss.height && !parsedCss.width) {
parsedCss.height = size.height + 'px';
parsedCss.width = size.width + 'px';
css['.nm-cv-viewport'] = $.makeStyleString(parsedCss);
t.set({css: css});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12072
|
train
|
function(options) {
var t = this,
opts = _.extend({trim:true, deep:true, monitorOnly:true}, options),
raw = Backbone.Model.prototype.toJSON.call(t, opts);
// Keep only the monitor portion (strip the probe portion)?
if (opts.monitorOnly) {
raw.monitor = t.get('monitor').toMonitorJSON(opts);
}
return raw;
}
|
javascript
|
{
"resource": ""
}
|
|
q12073
|
train
|
function(e) {
var code = e.keyCode;
// Hotkeys while a tour is present
if (UI.pageView.tourView) {
// 1-9 direct page navigation
var target;
if (code >= 49 && code <=57) {
target = $('.nm-tv-page[data-index="' + (code - 49) + '"]');
}
// Pause / Run
if (code == 32) {
UI.pageView.tourView[UI.pageView.tourView.timer ? 'pause' : 'play']();
}
// Left / Up
if (code == 37 || code == 38) {
UI.pageView.tourView.prev();
}
// Right / Down
if (code == 39 || code == 40) {
UI.pageView.tourView.prev();
}
// Programmatically click the target
if (target && target.length) {
target.click();
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12074
|
train
|
function(e) {
var t = this,
box = t.getComponentArea(),
sidebarWidth = t.sidebar.width(),
canvasWidth = t.$el.width() - sidebarWidth,
canvasCenter = canvasWidth / 2;
// No components
if (!box.width) {return;}
// Obtain the center point, and offset the canvas by the difference
// Keep the left margin at multiples of 10 to match components
var componentCenter = box.left + (box.width / 2);
var newLeft = sidebarWidth + Math.max(0, canvasCenter - componentCenter);
newLeft = newLeft - newLeft % 10;
t.canvas.css({marginLeft: newLeft});
}
|
javascript
|
{
"resource": ""
}
|
|
q12075
|
train
|
function() {
var t = this,
box = t.getComponentArea();
// Shift all components by the furthest left
if (box.left) {
t.$('.nm-pv-component').each(function() {
var elem = $(this).find('.nm-cv'),
left = (parseInt(elem.css('left'), 10)),
model = t.componentViews[($(this).attr('id'))].model,
css = _.clone(model.get('css')),
parsedCss = $.parseStyleString(css['.nm-cv'] || '');
// Set the left into the model & remove from the element style
parsedCss.left = (left - box.left) + 'px';
css['.nm-cv'] = $.makeStyleString(parsedCss);
model.set({css: css});
elem.css({left:''});
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12076
|
train
|
function(model) {
var t = this,
componentView = new ComponentView({model: model});
componentView.$el
.addClass('nm-pv-component')
.data('view', componentView);
componentView.render();
t.canvas.append(componentView.$el);
t.componentViews[model.get('id')] = componentView;
}
|
javascript
|
{
"resource": ""
}
|
|
q12077
|
train
|
function() {
var t = this,
components = t.model.get('components'),
canvas = t.$('.nm-pv-canvas');
// Remove components not in the data model
canvas.find('.nm-pv-component').each(function() {
var component = $(this);
if (!components.get(component.attr('id'))) {
component.remove();
}
});
// Add new components
components.forEach(function(component) {
var onScreen = t.$('#' + component.get('id'));
if (!onScreen.length) {
t.addComponent(component);
}
});
// Center components onto the screen
t.leftJustify();
t.centerPage();
}
|
javascript
|
{
"resource": ""
}
|
|
q12078
|
train
|
function() {
var t = this,
pageView = t,
getMonitor = function(id){return t.getMonitor(id);};
pageModel = t.model;
// Execute the onInit
try {
eval(t.model.get('onInit'));
}
catch (e) {
console.error('PageView onInit threw exception: ', e);
alert("Page onInit exception. See console log for more information.");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12079
|
train
|
function() {
var t = this,
raw = t.model.toJSON({trim:false});
return !(_.isEqual(t.originalPage, raw));
}
|
javascript
|
{
"resource": ""
}
|
|
q12080
|
train
|
function(isDirty) {
var t = this;
// Pause a tour if the page turns dirty
if (isDirty) {
UI.pauseTour();
}
// Change the view elements
t.$el.toggleClass('dirty', isDirty);
if (!isDirty) {
t.originalPage = t.model.toJSON({trim:false});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12081
|
train
|
function() {
// Remember the current page state
var t = this;
t.pageSettingsView.originalModel = t.model.toJSON({trim:false});
// Load & show the dialog
t.showDialog('#nm-pv-settings');
}
|
javascript
|
{
"resource": ""
}
|
|
q12082
|
train
|
function() {
var t = this,
components = t.model.get('components');
components.remove(components.models);
t.showSettings();
}
|
javascript
|
{
"resource": ""
}
|
|
q12083
|
train
|
function(id) {
var t = this,
components = t.model.get('components');
return components.get(id).get('monitor');
}
|
javascript
|
{
"resource": ""
}
|
|
q12084
|
train
|
function(id) {
var t = this;
// Is there a tour running already?
if (t.tourView) {
t.tourView.stop();
}
// Load the Tour and start it
var tour = new UI.Tour({id:id});
tour.fetch(function(err){
if (err) {
alert("Error: Cannot open tour id: " + id);
console.error(e);
return;
}
// Go to the first page
var pages = tour.get('pages');
if (!pages.length) {
alert('No pages in tour: ' + tour.get('title'));
return;
}
// Save the current tour, and navigate to it
localStorage.currentTour = JSON.stringify(tour);
t.navigateTo(pages[0].url);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12085
|
train
|
function() {
var t = this,
isEditMode = t.$el.hasClass('edit-mode'),
text = isEditMode ? 'Lock Components' : 'Edit Components',
icon = isEditMode ? 'lock' : 'edit';
t.$('.nm-pvm-lock').text(text);
t.$('.nm-pvm-edit i').attr('class', 'icon-' + icon);
}
|
javascript
|
{
"resource": ""
}
|
|
q12086
|
train
|
function() {
var t = this;
// Show if loaded
if (aboutTemplate) {
return t.showDialog('#nm-pv-about');
}
UI.loadTemplate('', 'About', function(error, template) {
if (error) {return;}
t.$el.append(template.apply(t));
t.$('.modal a').attr({target: '_blank'});
t.$('.colorPicker').miniColors({opacity: true});
t.showDialog('#nm-pv-about');
});
}
|
javascript
|
{
"resource": ""
}
|
|
q12087
|
train
|
function() {
var t = this;
UI.hideToolTips();
t.leftJustify();
t.centerPage();
t.model.save(function(error){
if (error) {
console.error("Page save error:", error);
}
});
t.unlockPage();
t.setDirty(false);
}
|
javascript
|
{
"resource": ""
}
|
|
q12088
|
train
|
function() {
var t = this;
t.$el.html('');
// Output the heading if specified
if (t.options.heading) {
$(t.template.heading({value:t.options.heading})).appendTo(t.$el);
}
// If a non-object, just print it
t.json = t.isBackbone ? t.model.toJSON() : t.model;
if (typeof t.json !== 'object') {
$(t.template.line({name:'value', value:t.json})).appendTo(t.$el);
return;
}
t.keys = _.keys(t.json);
// Info about each element, keyed by element name
// div - The jQuery selector of the element outer div
// span - The jQuery selector of the data value span
// value - The element raw value
// isBackbone - Is the element an instance of a Backbone model?
// strValue - The currently displayed value
// isArray - True of the element is an array (or collection)
// innerDiv - The container for the inner view for objects
// innerView - The inner view if the element is an object
t.elems = {};
// Layout the tree (without element data)
for (var elemName in t.json) {
var elem = t.elems[elemName] = {};
elem.value = t.getElemValue(elemName);
elem.isBackbone = elem.value instanceof Backbone.Model || elem.value instanceof Backbone.Collection;
elem.div = $(t.template.line({name:elemName, value: ' '})).appendTo(t.$el);
elem.span = $('.data', elem.div);
// Render a sub-element as another JsonView
if (elem.value !== null && typeof elem.value === 'object') {
elem.div.addClass('open-close').data({elemName:elemName});
$('i', elem.div).html('');
elem.innerDiv = $(t.template.inner()).appendTo(t.$el);
elem.innerView = new JsonView({
model: elem.value,
closedOnInit: t.closedOnInit
});
elem.innerView.render();
elem.innerView.$el.appendTo(elem.innerDiv);
elem.isArray = _.isArray(elem.value);
$(t.template.endInner({symbol:elem.isArray ? "]" : "}"})).appendTo(elem.innerDiv);
}
}
// Bind the change handler
if (t.isBackbone) {
t.model.bind('change', t.setData, t);
}
// Add element data to the tree
t.setData();
// Reset for future renders
t.closedOnInit = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q12089
|
train
|
function(elemName) {
var t = this;
if (t.isBackbone) {
return t.model instanceof Backbone.Collection ? t.model.at(elemName) : t.model.get(elemName);
}
return t.model[elemName];
}
|
javascript
|
{
"resource": ""
}
|
|
q12090
|
train
|
function(elem) {
var t = this,
strValue;
// Catch recursive stringify
try {strValue = JSON.stringify(elem.value);}
catch (e) {strValue = "{object}";}
// Set if the value changed
if (strValue !== elem.strValue) {
var priorStrValue = elem.strValue;
elem.strValue = strValue;
// Set the value of this element or the inner element
elem.span.text(strValue);
if (elem.innerView) {
elem.innerView.model = elem.value;
elem.innerView.setData();
// Set the inner element open or closed
var isClosed = false;
if (priorStrValue) {
isClosed = elem.innerView.isClosed;
} else {
isClosed = t.closedOnInit ? true : strValue.length < AUTO_CLOSE_CHARS;
}
t.toggleClosed(elem, isClosed);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12091
|
train
|
function() {
// Compute the amount of play left to go
t.playLeft = t.playEnd - Date.now();
// Done playing
if (t.playLeft <= 0) {
clearInterval(t.timer);
t.next();
}
// Set the progress bar width
t.setProgress();
}
|
javascript
|
{
"resource": ""
}
|
|
q12092
|
train
|
function(e) {
var t = this,
target = $(e.currentTarget),
index = target.attr('data-index');
// Save the index. If a tour has many instances of the
// same page, it needs to know which instance.
localStorage.tourPageIndex = index;
// Navigate to the page
UI.pageView.navigateTo(target.attr('href'));
}
|
javascript
|
{
"resource": ""
}
|
|
q12093
|
train
|
function(options) {
var t = this;
t.options = options;
t.monitor = options.monitor;
// Call this to set the initial height/width to something
// other than the size of the inner view elements.
options.component.setDefaultSize({
width: 400,
height: 300
});
// Set monitor defaults. If your view is for a specific probe,
// then set the probeClass and any default probe initialization
// parameters.
if (!t.monitor.get('probeClass')) {
t.monitor.set({
probeClass: '{{shortAppName}}SampleProbe'
});
}
// Update the view on monitor change. The monitor isn't in
// a connected state, so this will be called when connected.
if (t.monitor != null) {
t.monitor.on('change', t.onchange, t);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12094
|
train
|
function() {
var t = this;
// Append a monitor picker
t.monitorPicker = new UI.MonitorPicker({
el: t.$el,
hideProbe: true, // Set false for the user to select the probe class
model: t.options.monitor
});
t.monitorPicker.render();
}
|
javascript
|
{
"resource": ""
}
|
|
q12095
|
train
|
function() {
var t = this,
map = {},
router = Monitor.getRouter(),
hostName = Monitor.getRouter().getHostName(),
appName = Monitor.Config.Monitor.appName,
appInstance = process.env.NODE_APP_INSTANCE;
// Add this process to the map
map[hostName] = {};
map[hostName][appName] = {
instances: [appInstance],
probeClasses: _.keys(Probe.classes)
};
// Process all known connections
var connections = router.findConnections();
connections.forEach(function(connection) {
hostName = connection.get('hostName') || connection.get('remoteHostName');
appName = connection.get('remoteAppName') || '';
appInstance = connection.get('remoteAppInstance') || '';
// Don't add to the map not yet connected
if (connection.connecting || !connection.connected) {
return;
}
// Add the hostname to the map
var host = map[hostName];
if (!host) {
host = map[hostName] = {};
}
// Add the app to the map
var app = host[appName];
if (!app) {
app = host[appName] = {
instances: [appInstance],
probeClasses: connection.get('remoteProbeClasses')
};
} else {
app.instances.push(appInstance);
}
});
log.info('buildMap', map);
// Set the map if it's changed. This method is called whenever
// connections come and go - including firewalled connections which
// aren't visible in the map. Only update if the map has changed.
if (!_.isEqual(map, t.get('map'))) {
log.info('mapChanged');
t.set({
map: map,
updateSequence: t.updateSequence++
});
} else {
log.info('mapNotChanged');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12096
|
Flint
|
train
|
function Flint(options) {
EventEmitter.call(this);
this.id = options.id || u.genUUID64();
/**
* Options Object
*
* @memberof Flint
* @instance
* @namespace options
* @property {string} token - Spark Token.
* @property {string} webhookUrl - URL that is used for SPark API to send callbacks.
* @property {string} [webhookSecret] - If specified, inbound webhooks are authorized before being processed.
* @property {string} [messageFormat=text] - Default Spark message format to use with bot.say().
* @property {number} [maxPageItems=50] - Max results that the paginator uses.
* @property {number} [maxConcurrent=3] - Max concurrent sessions to the Spark API
* @property {number} [minTime=600] - Min time between consecutive request starts.
* @property {number} [requeueMinTime=minTime*10] - Min time between consecutive request starts of requests that have been re-queued.
* @property {number} [requeueMaxRetry=3] - Msx number of atteempts to make for failed request.
* @property {array} [requeueCodes=[429,500,503]] - Array of http result codes that should be retried.
* @property {number} [requestTimeout=20000] - Timeout for an individual request recieving a response.
* @property {number} [queueSize=10000] - Size of the buffer that holds outbound requests.
* @property {number} [requeueSize=10000] - Size of the buffer that holds outbound re-queue requests.
* @property {string} [id=random] - The id this instance of flint uses.
* @property {string} [webhookRequestJSONLocation=body] - The property under the Request to find the JSON contents.
* @property {Boolean} [removeWebhooksOnStart=true] - If you wish to have the bot remove all account webhooks when starting.
*/
this.options = options;
this.active = false;
this.initialized = false;
this.storageActive = false;
this.isBotAccount = false;
this.isUserAccount = false;
this.person = {};
this.email;
// define location in webhook request to find json values of incoming webhook.
// note: this is typically 'request.body' but depending on express/restify configuration, it may be 'request.params'
this.options.webhookRequestJSONLocation = this.options.webhookRequestJSONLocation || 'body';
// define if flint remove all webhooks attached to token on start (if not defined, defaults to true)
this.options.removeWebhooksOnStart = typeof this.options.removeWebhooksOnStart === 'boolean' ? this.options.removeWebhooksOnStart : true;
// define default messageFormat used with bot.say (if not defined, defaults to 'text')
if(typeof this.options.messageFormat === 'string' && _.includes(['text', 'markdown', 'html'], _.toLower(this.options.messageFormat))) {
this.messageFormat = _.toLower(this.options.messageFormat);
} else {
this.messageFormat = 'text';
}
this.batchDelay = options.minTime * 2;
this.auditInterval;
this.auditDelay = 300;
this.auditCounter = 0;
this.logs = [];
this.logMax = 1000;
this.lexicon = [];
this.bots = [];
this.spark = {};
this.webhook = {};
// register internal events
this.on('error', err => {
if(err) {
console.err(err.stack);
}
});
this.on('start', () => {
require('./logs')(this);
this.initialize();
});
}
|
javascript
|
{
"resource": ""
}
|
q12097
|
runActions
|
train
|
function runActions(matched, bot, trigger, id) {
// process preference logic
if(matched.length > 1) {
matched = _.sortBy(matched, match => match.preference);
var prefLow = matched[0].preference;
var prefHigh = matched[matched.length - 1].preference;
if(prefLow !== prefHigh) {
matched = _.filter(matched, match => (match.preference === prefLow));
}
}
_.forEach(matched, lex => {
// for regex
if(lex.phrase instanceof RegExp && typeof lex.action === 'function') {
// define trigger.args, trigger.phrase
trigger.args = trigger.text.split(' ');
trigger.phrase = lex.phrase;
// run action
lex.action(bot, trigger, id);
return true;
}
// for string
else if (typeof lex.phrase === 'string' && typeof lex.action === 'function') {
// find index of match
var args = _.toLower(trigger.text).split(' ');
var indexOfMatch = args.indexOf(lex.phrase) !== -1 ? args.indexOf(lex.phrase) : 0;
// define trigger.args, trigger.phrase
trigger.args = trigger.text.split(' ');
trigger.args = trigger.args.slice(indexOfMatch, trigger.args.length);
trigger.phrase = lex.phrase;
// run action
lex.action(bot, trigger, id);
return true;
}
// for nothing...
else {
return false;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q12098
|
markdownFormat
|
train
|
function markdownFormat(str) {
// if string...
if(str && typeof str === 'string') {
// process characters that do not render visibly in markdown
str = str.replace(/\<(?!@)/g, '<');
str = str.split('').reverse().join('').replace(/\>(?!.*@\<)/g, ';tg&').split('').reverse().join('');
return str;
}
// else return empty
else {
return '';
}
}
|
javascript
|
{
"resource": ""
}
|
q12099
|
Bot
|
train
|
function Bot(flint) {
EventEmitter.call(this);
this.id = u.genUUID64();
this.flint = flint;
this.options = flint.options;
this.debug = function(message) {
message = util.format.apply(null, Array.prototype.slice.call(arguments));
if(typeof flint.debugger === 'function') {
flint.debugger(message, this.id);
} else {
_debug(message);
}
};
//randomize distribution of when audit event should take place for this bot instance...
this.auditTrigger = Math.floor((Math.random() * this.flint.auditDelay)) + 1;
this.spark = this.flint.spark;
this.batchDelay = this.flint.batchDelay;
this.active = false;
this.room = {};
this.team = {};
this.person = this.flint.person;
this.membership = {};
this.memberships = [];
this.email = this.flint.email;
this.isLocked = false;
this.isModerator = false;
this.isGroup = false;
this.isDirect = false;
this.isTeam = false;
this.lastActivity = moment().utc().toDate();
this.on('error', err => {
if(err) {
this.debug(err.stack);
}
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.