_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q14800
|
train
|
function(str, end) {
return (str.length >= end.length &&
str.substring(str.length - end.length) === end);
}
|
javascript
|
{
"resource": ""
}
|
|
q14801
|
set
|
train
|
function set(key, module, global) {
var m = null;
var isGlobal = global && typeof global !== 'undefined';
// check to make sure the module has been assigned only once
if (isGlobal) {
if (global.hasOwnProperty(key)) {
throw '[define-shim] Module ' + key + ' already exists';
}
}
else if (_map.hasOwnProperty(key)) {
throw '[define-shim] Module ' + key + ' already exists';
return;
}
// construct the module if needed
if (typeof module === 'function') m = module(get);
else m = module;
// assign the module to whichever object is preferred
if (isGlobal) global[key] = m;
else _map[key] = m;
}
|
javascript
|
{
"resource": ""
}
|
q14802
|
insert
|
train
|
function insert (i, val, array) {
array = copy(array)
array.splice(i, 0, val)
return array
}
|
javascript
|
{
"resource": ""
}
|
q14803
|
generateFakeDataForSchema
|
train
|
function generateFakeDataForSchema(schemaName) {
return new RSVP.Promise(function (resolve, reject) {
agolSchemas.getSchema(schemaName).then(function (schema) {
// Generate fake data
var fakeData = jsf(schema);
// return fake data
resolve(fakeData);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14804
|
FullyTyped
|
train
|
function FullyTyped (configuration) {
if (arguments.length === 0 || configuration === null) configuration = {};
// validate input parameter
if (!util.isPlainObject(configuration)) {
throw Error('If provided, the schema configuration must be a plain object. Received: ' + configuration);
}
// get a copy of the configuration
const config = util.copy(configuration);
// if type is not specified then use the default
if (!config.type) config.type = 'typed';
// get the controller data
const data = FullyTyped.controllers.get(config.type);
// type is invalid
if (!data) throw Error('Unknown type: ' + config.type);
// return a schema object
return new Schema(config, data);
}
|
javascript
|
{
"resource": ""
}
|
q14805
|
validate
|
train
|
function validate(task, options) {
if (!task) {
if (options.verbose) {
console.log(' -', chalk.bold.yellow('[WARNING]:'), 'Task does not exist');
}
return Promise.resolve(false);
}
return new Promise(function(resolve, reject) {
var hooks = task.hooks(options) || {};
if (hooks.validate) {
var result = hooks.validate();
if (isPromise(result)) {
result.then(function(result) {
resolve(result !== false); // undefined should represent truthy
});
} else {
resolve(result);
}
} else {
resolve(true);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q14806
|
log
|
train
|
function log (out, desc) {
logger.log(header())
if (desc) {
logger.log(desc)
}
logger.log(out)
logger.log()
}
|
javascript
|
{
"resource": ""
}
|
q14807
|
error
|
train
|
function error (out, desc) {
logger.error(header())
if (desc) {
logger.error(desc)
}
logger.error(out)
logger.error()
}
|
javascript
|
{
"resource": ""
}
|
q14808
|
watch
|
train
|
function watch(glob, taskName)
{
var watcher = chokidar.watch(glob, {persistent: true,});
watcher.on('ready', ()=>
{
watcher.on('all', (event, path)=>
{
invokeTask(taskName);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14809
|
invokeTask
|
train
|
function invokeTask(taskName)
{
const tc = TASKS.globals.globalTaskCollection;
const t = tc.getByName(taskName);
if (t === undefined)
{
YERROR.raiseError(`task ${taskName} not found`);
}
TASKS.invokeTask(tc, t);
}
|
javascript
|
{
"resource": ""
}
|
q14810
|
create
|
train
|
function create() {
var sha1sum = crypto.createHash('sha1');
return { update: update, digest: digest };
function update(data) {
sha1sum.update(data);
}
function digest() {
return sha1sum.digest('hex');
}
}
|
javascript
|
{
"resource": ""
}
|
q14811
|
train
|
function(obj, maxNumProperties) {
var result = "";
maxNumProperties = maxNumProperties === undefined ? Number.MAX_VALUE : maxNumProperties;
if (obj !== undefined && obj !== null) {
var separator = "";
var propCount = 0;
for (var propertyName in obj) {
var objValue;
if ((obj[propertyName]) === undefined) {
objValue = "*** undefined ***";
} else {
objValue = obj[propertyName];
}
result += separator + propertyName + " = " + objValue;
separator = ",\n";
propCount++;
if (propCount >= maxNumProperties) {
break;
}
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q14812
|
train
|
function(argumentName, defaultValue) {
var result = argMap[argumentName];
if (this.isEmpty(result) && this.isNotEmpty(defaultValue)) {
if (typeof defaultValue === 'object') {
result = defaultValue[argumentName];
} else {
result = defaultValue;
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q14813
|
bundle
|
train
|
function bundle() {
return bundler.bundle()
// log errors if they happen
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('nutella_lib.js'))
.pipe(gulp.dest('./dist'));
}
|
javascript
|
{
"resource": ""
}
|
q14814
|
JFP_Error
|
train
|
function JFP_Error(message) {
Error.call(this, message);
Object.defineProperty(this, "name", {
value: this.constructor.name
});
Object.defineProperty(this, "message", {
value: message
});
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Object.defineProperty(this, "stack", {
value: (new Error()).stack
});
}
}
|
javascript
|
{
"resource": ""
}
|
q14815
|
type
|
train
|
function type(input) {
//If the input value is null, undefined or NaN the toStringTypes object shouldn't be used
if (input === null || input === undefined || (input !== input && String(input) === "NaN")) {
return String(input);
}
// use the typeMap to detect the type and fallback to object if the type wasn't found
return typeMap[Object.prototype.toString.call(input)] || "object";
}
|
javascript
|
{
"resource": ""
}
|
q14816
|
inherits
|
train
|
function inherits(constructor, superConstructor) {
constructor.super_ = superConstructor;
constructor.prototype = Object.create(superConstructor.prototype, {
'constructor': {
'value': constructor,
'enumerable': false,
'writable': true,
'configurable': true
}
});
}
|
javascript
|
{
"resource": ""
}
|
q14817
|
Confectioner
|
train
|
function Confectioner() {
if (!(this instanceof Confectioner)) {
var instance = Object.create(clazz);
Confectioner.apply(instance, arguments);
return instance;
}
this.keys = [];
this.addKey.apply(this, Array.prototype.slice.call(arguments));
}
|
javascript
|
{
"resource": ""
}
|
q14818
|
floatFromBuffer
|
train
|
function floatFromBuffer (buf) {
if (buf.length < FLOAT_ENTROPY_BYTES) {
throw new Error(
'buffer must contain at least ' + FLOAT_ENTROPY_BYTES + ' bytes of entropy'
)
}
var position = 0
// http://stackoverflow.com/questions/15753019/floating-point-number-from-crypto-randombytes-in-javascript
return (((((((
buf[position++] % 32) / 32 +
buf[position++]) / 256 +
buf[position++]) / 256 +
buf[position++]) / 256 +
buf[position++]) / 256 +
buf[position++]) / 256 +
buf[position]) / 256
}
|
javascript
|
{
"resource": ""
}
|
q14819
|
applyNSync
|
train
|
function applyNSync () {
var args = Array.prototype.slice.call(arguments)
var fn = args.shift()
var num = args.shift()
var arr = []
for (var i = 0; i < num; ++i) {
arr.push(fn.apply(null, args))
}
return arr
}
|
javascript
|
{
"resource": ""
}
|
q14820
|
applyN
|
train
|
function applyN (fn, opts, ready) {
var num = opts.num || 0
var unique = opts.unique
var arr = []
fn(opts, onValue)
function onValue (err, value) {
if (err) {
return ready(err)
}
if (!unique || arr.indexOf(value) === -1) {
arr.push(value)
}
if (arr.length >= num) {
return ready(null, arr)
}
process.nextTick(function () {
fn(opts, onValue)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q14821
|
restifyCORSSimple
|
train
|
function restifyCORSSimple(req, res, next) {
var origin;
if (!(origin = matchOrigin(req, origins))) {
next();
return;
}
function corsOnHeader() {
origin = req.headers.origin;
if (opts.credentials) {
res.setHeader(AC_ALLOW_CREDS, 'true');
}
res.setHeader(AC_ALLOW_ORIGIN, origin);
res.setHeader(AC_EXPOSE_HEADERS, headers.join(', '));
res.setHeader(AC_ALLOW_METHODS, ALLOW_METHODS.join(', '));
res.setHeader(AC_ALLOW_HEADERS, ALLOW_HEADERS.join(', '));
res.setHeader(AC_REQUEST_HEADERS, REQUEST_HEADERS.join(', '));
}
res.once('header', corsOnHeader);
next();
}
|
javascript
|
{
"resource": ""
}
|
q14822
|
processErrorAndData
|
train
|
function processErrorAndData (error, data) {
if (_cb.beforeReturnErrorAndData) { _cb.beforeReturnErrorAndData(error, data); }
if (_cb.returnErrorAndData) { _cb.returnErrorAndData(error, data, response); }
if (_cb.afterReturnErrorAndData) { _cb.afterReturnErrorAndData(error, data); }
}
|
javascript
|
{
"resource": ""
}
|
q14823
|
processError
|
train
|
function processError (error) {
if (_cb.beforeReturnError) { _cb.beforeReturnError(error); }
if (_cb.returnError) { _cb.returnError(error, response); }
if (_cb.afterReturnError) { _cb.afterReturnError(error); }
}
|
javascript
|
{
"resource": ""
}
|
q14824
|
processData
|
train
|
function processData (data) {
if (_cb.beforeReturnData) { _cb.beforeReturnData(data); }
if (_cb.returnData) { _cb.returnData(data, response); }
if (_cb.afterReturnData) { _cb.afterReturnData(data); }
}
|
javascript
|
{
"resource": ""
}
|
q14825
|
processNotFound
|
train
|
function processNotFound () {
if (_cb.beforeReturnNotFound) { _cb.beforeReturnNotFound(); }
if (_cb.returnNotFound) { _cb.returnNotFound(response); }
if (_cb.afterReturnNotFound) { _cb.afterReturnNotFound(); }
}
|
javascript
|
{
"resource": ""
}
|
q14826
|
train
|
function(token) {
this.oauthClient.setCredentials(token);
this.brain.set(this.TOKEN_KEY, token.access_token);
if (token.refresh_token) {
this.brain.set(this.REFRESH_KEY, token.refresh_token);
}
this.brain.set(this.EXPIRY_KEY, +token.expiry_date);
this.brain.save();
this.brain.resetSaveInterval(60);
}
|
javascript
|
{
"resource": ""
}
|
|
q14827
|
train
|
function(code, cb) {
var self = this;
this.oauthClient.getToken(code, function(err, token) {
if (err) {
cb({
err: err,
msg: 'Error while trying to retrieve access token'
});
return;
}
self.storeToken(token);
cb(null, {
resp: token,
msg: "Google auth code successfully set"
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14828
|
train
|
function(cb) {
var at = this.brain.get(this.TOKEN_KEY),
rt = this.brain.get(this.REFRESH_KEY);
if (at == null || rt == null) {
cb({
err: null,
msg: 'Error: No tokens found. Please authorize this app and store a refresh token'
});
return;
}
var expirTime = this.brain.get(this.EXPIRY_KEY),
curTime = (new Date()) / 1;
var self = this;
if (expirTime < curTime) {
this.oauthClient.refreshAccessToken(function(err, token) {
if (err != null) {
cb({
err: err,
msg: 'Google Authentication Error: error refreshing token'
}, null);
return;
}
self.storeToken(token);
cb(null, {
resp: token,
msg: 'Token refreshed'
});
});
} else {
cb(null);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14829
|
train
|
function() {
return {
token: this.brain.get(this.TOKEN_KEY),
refresh_token: this.brain.get(this.REFRESH_KEY),
expire_date: this.brain.get(this.EXPIRY_KEY)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14830
|
findValueByPath
|
train
|
function findValueByPath(jsonData, path){
var errorParts = false;
path.split('.').forEach(function(part){
if(!errorParts){
jsonData = jsonData[part];
if(!jsonData) errorParts = true;
}
});
return errorParts ? 0 : parseFloat(jsonData);
}
|
javascript
|
{
"resource": ""
}
|
q14831
|
requestPrice
|
train
|
function requestPrice(urlAPI, callback){
request({
method: 'GET',
url: urlAPI,
timeout: TIMEOUT,
maxRedirects: 2
}, function(error, res, body){
if(!error){
try{
var current = JSON.parse(body);
callback(current);
}catch(e){}
}
if(!current) {
callback({});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q14832
|
train
|
function(buildPath, manifest) {
fs.stat(manifest, function(err, stat) {
if (! err) {
manifest = JSON.parse(fs.readFileSync(manifest));
for (var key in manifest) {
del.sync(buildPath + '/' + manifest[key], { force: true });
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14833
|
train
|
function() {
var children = this.parent.children,
index = CKEDITOR.tools.indexOf( children, this ),
previous = this.previous,
next = this.next;
previous && ( previous.next = next );
next && ( next.previous = previous );
children.splice( index, 1 );
this.parent = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q14834
|
train
|
function( condition ) {
var checkFn =
typeof condition == 'function' ?
condition :
typeof condition == 'string' ?
function( el ) {
return el.name == condition;
} :
function( el ) {
return el.name in condition;
};
var parent = this.parent;
// Parent has to be an element - don't check doc fragment.
while ( parent && parent.type == CKEDITOR.NODE_ELEMENT ) {
if ( checkFn( parent ) )
return parent;
parent = parent.parent;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q14835
|
train
|
function(d) {
var self = this;
$('#circle-info').html(d.name);
console.log(d);
var focus0 = self.focus;
self.focus = d;
var transition = d3.transition()
.duration(d3.event.altKey ? 7500 : 750)
.tween("zoom", function(d) {
var i = d3.interpolateZoom(self.view,
[self.focus.x, self.focus.y,
self.focus.r * 2 + self.options.margin]);
return function(t) {
self.zoomTo(i(t));
};
});
transition.selectAll("text")
.filter(function(d) {
return d.parent === self.focus ||
this.style.display === "inline" ||
d.parent === focus0;
})
.style("fill-opacity", function(d) {
return d.parent === self.focus ? 1 : 0.5;
})
.each("start", function(d) {
if (d.parent === self.focus)
this.style.display = "inline";
})
.each("end", function(d) {
if (d.parent !== self.focus)
this.style.display = "none";
});
// logos are opaque at root level only
transition.selectAll("use")
.style("opacity", function(d) {
return self.focus.depth === 0 ? 1 : 0.8;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14836
|
discoverServicesAndCharacteristics
|
train
|
function discoverServicesAndCharacteristics(error) {
if (error) { return reject(error); }
peripheral.discoverSomeServicesAndCharacteristics(
ALL_SERVICES,
ALL_CHARACTERISTICS,
setupEmitter
);
}
|
javascript
|
{
"resource": ""
}
|
q14837
|
setupEmitter
|
train
|
function setupEmitter(error) {
if (error) { return reject(error); }
const sensorService = getService(SERVICE_SENSOR_UUID, peripheral);
const notifiable = sensorService.characteristics;
const withNotified = Promise.all(notifiable.map(characteristic =>
new Promise((resolve, reject) =>
void characteristic.notify([], error =>
void (!!error ? reject(error) : resolve(characteristic))))));
withNotified.then(characteristics => {
const emitter = new EventEmitter();
const onData = uuid => buffer =>
void emitter.emit("data", { characteristic: uuid, buffer });
characteristics.forEach(characteristic =>
void characteristic.on('data', onData(characteristic.uuid)));
const matrixCharacteristic =
getCharacteristic(CHARACTERISTIC_MATRIX_UUID,
getService(SERVICE_MATRIX_UUID, peripheral));
resolve(new client.NuimoClient(emitter, matrixCharacteristic, peripheral));
}).catch(reject);
}
|
javascript
|
{
"resource": ""
}
|
q14838
|
train
|
function (config) {
this.globals = config.globals || {};
this.templates = {};
this.config = _.extend({}, defaults, config);
this.config.optionsRegex = new RegExp("^" + this.config.optionsDelimiter + "([\\S\\s]+)" + this.config.optionsDelimiter + "([\\S\\s]+)");
}
|
javascript
|
{
"resource": ""
}
|
|
q14839
|
train
|
function(z_real, w_copy, s_property) {
// property is a function (ie: instance method)
if('function' === typeof z_real[s_property]) {
// implement same method name in virtual object
w_copy[s_property] = function() {
// forward to real class
return z_real[s_property].apply(z_real, arguments);
};
}
// read/write property
else {
// try to override object property
try {
Object.defineProperty(w_copy, s_property, {
// grant user full capability to modify this property
configurable: true,
// give enumerability setting same value as original
enumerable: z_real.propertyIsEnumerable(s_property),
// fetch property from real object
get: () => {
return z_real[s_property];
},
// set property on real object
set: (z_value) => {
z_real[s_property] = z_value;
},
});
}
// cannot redefine property
catch(d_redef_err) {
// try again, this time only set the value and enumerability
try {
Object.defineProperty(w_copy, s_property, {
// give enumerability setting same value as original
enumerable: z_real.propertyIsEnumerable(s_property),
// mask w undef
value: undefined,
});
// was not exepecting this property to give us trouble
if(!A_TROUBLE_PROPERTIES.includes(s_property)) {
console.warn('was not expecting "'+s_property+'" to prohibit redefinition on '+arginfo(w_copy));
}
}
// cannot even do that?!
catch(d_enum_err) {
// last try, this time only set the value
try {
Object.defineProperty(w_copy, s_property, {
// mask w undef
value: undefined,
});
// was not exepecting this property to give us trouble
if(!A_TROUBLE_PROPERTIES.includes(s_property)) {
console.warn('was not expecting "'+s_property+'" to prohibit redefinition on '+arginfo(w_copy));
}
}
// fail
catch(d_value_err) {
throw 'cannot override property "'+s_property+'" on '+arginfo(w_copy);
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14840
|
logFn
|
train
|
function logFn(level){
return function(msg){
var args = Array.prototype.slice.call(arguments);
if (level === 'hr'){
args = ['------------------------------------------------------------'];
args.push({_hr: true});
level = 'debug';
}
var logFn = logger[level] || console[level].bind(console);
if (enabled.enabled) logFn.apply(logger, args);
};
}
|
javascript
|
{
"resource": ""
}
|
q14841
|
disable
|
train
|
function disable(namespaces) {
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
function removeNamespaceFromNames(namespaces){
_.remove(exports.names, function(name){
return name.toString() === '/^' + namespaces + '$/';
});
}
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
removeNamespaceFromNames(namespaces);
exports.skips.push(new RegExp('^' + namespaces + '$'));
loggerEventBus.emit('disable', split[i]);
}
}
exports.save(namespaces);
}
|
javascript
|
{
"resource": ""
}
|
q14842
|
XUnitZH
|
train
|
function XUnitZH(runner) {
var tests = [],
passes = 0,
failures = 0;
runner.on('pass', function(test){
test.state = 'passed';
passes++;
tests.push(test);
test.number = tests.length;
});
runner.on('fail', function(test){
test.state = 'failed';
failures++;
tests.push(test);
test.number = tests.length;
});
runner.on('end', function(){
console.log();
console.log('testsuite: Mocha Tests'
+ ', tests: ' + tests.length
+ ', failures: ' + failures
+ ', errors: ' + failures
+ ', skipped: ' + (tests.length - failures - passes)
+ ', time: ' + 0
);
appendLine(tag('testsuite', {
name: 'Mocha Tests'
, tests: tests.length
, failures: failures
, errors: failures
, skipped: tests.length - failures - passes
, timestamp: (new Date).toUTCString()
, time: 0
}, false));
tests.forEach(test);
appendLine('</testsuite>');
fs.closeSync(fd);
process.exit(failures);
});
}
|
javascript
|
{
"resource": ""
}
|
q14843
|
toConsole
|
train
|
function toConsole(number, name, state, content){
console.log(number + ') ' + state + ' ' + name);
if (content) {
console.log('\t' + content);
}
}
|
javascript
|
{
"resource": ""
}
|
q14844
|
checkIceComponentState
|
train
|
function checkIceComponentState(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('DISCONNECTED|GATHERING|CONNECTING|CONNECTED|READY|FAILED'))
throw SyntaxError(key+' param is not one of [DISCONNECTED|GATHERING|CONNECTING|CONNECTED|READY|FAILED] ('+value+')');
}
|
javascript
|
{
"resource": ""
}
|
q14845
|
applyStyles
|
train
|
function applyStyles (css) {
return flattenDeep(css)
.reduce(
(classNames, declarations) => {
if (!declarations) {
return classNames
}
classNames.push(glamor(declarations))
return classNames
},
[]
)
.join(' ')
}
|
javascript
|
{
"resource": ""
}
|
q14846
|
centericMap
|
train
|
function centericMap(array, callback) {
var retArray = [],
length,
left, right;
if(array) {
length = array.length - 1;
left = length >> 1;
while(left >= 0) {
retArray[left] = callback(array[left]);
right = length - left;
if(right !== left) {
retArray[right] = callback(array[right]);
}
left--;
}
}
return retArray;
}
|
javascript
|
{
"resource": ""
}
|
q14847
|
train
|
function (children) {
var allChildren = this.get('allChildren');
if(allChildren) {
this._setChildren(allChildren.filter(function (child) {
return children.indexOf(child) !== -1; // true if child is in children
}));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14848
|
train
|
function (childrenToRemove) {
var children = this.get('children');
if(children) {
children = children.filter(function (child) {
return childrenToRemove.indexOf(child) === -1; // false if child is in children
});
this._setChildren(children);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14849
|
train
|
function (property, callback, thisArg) {
if(this.get(property)) {
this.get(property).forEach(callback, thisArg);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14850
|
train
|
function (depth) {
this.set('depth', depth);
depth++;
this.get('inputs').forEach(function (input) {
input.set('depth', depth);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14851
|
train
|
function() {
this.setChildren(this.get('inputs').concat(this.get('children') || []));
var ancestor = this.get('parent.parent');
if(ancestor) {
ancestor.setChildren(this.get('outputs').concat(ancestor.get('children') || []));
}
this.set('_additionalsIncluded', true);
}
|
javascript
|
{
"resource": ""
}
|
|
q14852
|
train
|
function() {
this.removeChildren(this.get('inputs'));
var ancestor = this.get('parent.parent');
if(ancestor) {
ancestor.removeChildren(this.get('outputs'));
}
this.set('_additionalsIncluded', false);
}
|
javascript
|
{
"resource": ""
}
|
|
q14853
|
train
|
function () {
var vertex = this.get('vertex');
this._super();
// Initialize data members
this.setProperties({
id: vertex.get('vertexName') + this.get('name'),
depth: vertex.get('depth') + 1
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14854
|
train
|
function (vertex, data) {
return InputDataNode.create(Ember.$.extend(data, {
treeParent: vertex,
vertex: vertex
}));
}
|
javascript
|
{
"resource": ""
}
|
|
q14855
|
_normalizeVertexTree
|
train
|
function _normalizeVertexTree(vertex) {
var children = vertex.get('children');
if(children) {
children = children.filter(function (child) {
_normalizeVertexTree(child);
return child.get('type') !== 'vertex' || child.get('treeParent') === vertex;
});
vertex._setChildren(children);
}
return vertex;
}
|
javascript
|
{
"resource": ""
}
|
q14856
|
_normalizeRawData
|
train
|
function _normalizeRawData(data) {
var EmObj = Ember.Object,
vertices, // Hash of vertices
edges, // Hash of edges
rootVertices = []; // Vertices without out-edges are considered root vertices
vertices = data.vertices.reduce(function (obj, vertex) {
vertex = VertexDataNode.create(vertex);
if(!vertex.outEdgeIds) {
rootVertices.push(vertex);
}
obj[vertex.vertexName] = vertex;
return obj;
}, {});
edges = !data.edges ? [] : data.edges.reduce(function (obj, edge) {
obj[edge.edgeId] = EmObj.create(edge);
return obj;
}, {});
if(data.vertexGroups) {
data.vertexGroups.forEach(function (group) {
group.groupMembers.forEach(function (vertex) {
vertices[vertex].vertexGroup = EmObj.create(group);
});
});
}
return {
vertices: EmObj.create(vertices),
edges: EmObj.create(edges),
rootVertices: rootVertices
};
}
|
javascript
|
{
"resource": ""
}
|
q14857
|
train
|
function (data) {
var dummy = DataNode.create({
type: types.DUMMY,
vertexName: 'dummy',
depth: 1
}),
root = RootDataNode.create({
dummy: dummy
});
if(!data.vertices) {
return "Vertices not found!";
}
_data = _normalizeRawData(data);
if(!_data.rootVertices.length) {
return "Sink vertex not found!";
}
dummy._setChildren(centericMap(_data.rootVertices, function (vertex) {
return _normalizeVertexTree(_treefyData(vertex, 2));
}));
_addOutputs(root);
_cacheChildren(root);
return _getGraphDetails(root);
}
|
javascript
|
{
"resource": ""
}
|
|
q14858
|
gather
|
train
|
function gather (variable, node) {
if (node.parent) {
let values = []
for (let n of Object.values(node.parent.nodes)) {
if (n.type === 'decl' && n.prop === `$${variable}`) {
values.push(n.value)
}
}
values.reverse()
let parentValues = node.parent.parent ? gather(variable, node.parent) : null
if (parentValues) {
values = values.concat(parentValues)
}
return values
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q14859
|
train
|
function (selector, args, cb) {
selector = selector || document;
args = args || {};
var self = this;
$(selector).find('*[data-view]').each(function () {
var viewArgs = _.extend({}, args);
viewArgs.el = this;
self.getComponent('viewManager').createView($(this).data('view'), viewArgs)
.then(cb);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14860
|
promisifyAll
|
train
|
function promisifyAll(sourceObject, keys){
// promisified output
const promisifiedFunctions = {};
// process each object key
for (const name of keys){
// function exist in source object ?
if (name in sourceObject && typeof sourceObject[name] === 'function'){
// create promisified named version
promisifiedFunctions[name] = _promisify(sourceObject[name], name);
}
}
return promisifiedFunctions;
}
|
javascript
|
{
"resource": ""
}
|
q14861
|
train
|
function (name, paramd) {
var self = this;
paramd = (paramd !== undefined) ? paramd : {};
self.name = (name !== undefined) ? name : "unnamed-queue";
self.qitems = [];
self.qurrents = [];
self.qn = (paramd.qn !== undefined) ? paramd.qn : 1;
self.qid = 0;
self.paused = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q14862
|
startSearch
|
train
|
function startSearch() {
iface.question('Enter search: ', function (query) {
// Get the results of our query
var matches = fileFinder.query(query),
len = matches.length;
// If no results were found
if (len === 0) {
console.log('No results found for: ' + query);
startSearch();
} else if (len === 1) {
var item = matches[0];
// If there is one, skip to go
console.log('Opening: ' + item);
fileFinder.open(item);
// Begin the search again
startSearch();
} else {
// Otherwise, list options
console.log('');
console.log('----------------');
console.log('Search Results');
console.log('----------------');
for (i = 0; i < len; i++) {
console.log(i + ': ' + matches[i]);
}
// Ask for a number
iface.question('Which item would you like to open? ', function (numStr) {
var num = +numStr,
item;
// If the number is not NaN and we were not given an empty string
if (num === num && numStr !== '') {
// and if it is in our result set
if (num >= 0 && num < len) {
// Open it
item = matches[num];
console.log('Opening: ' + item);
fileFinder.open(item);
}
} else {
// Otherwise, if there was a word in there so we are assuming it was 'rescan'
// Rescan
console.log('Rescanning...');
fileFinder.scan();
}
// Begin the search again
startSearch();
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q14863
|
getAuth
|
train
|
function getAuth() {
if (!auth.key || auth.key.indexOf("goes-here") !== -1) {
var err = new Error("API key missing");
out.error(err.message);
throw err;
}
if (!auth.secret || auth.secret.indexOf("goes-here") !== -1) {
var err = new Error("API secret missing");
out.error(err.message);
throw err;
}
return auth;
}
|
javascript
|
{
"resource": ""
}
|
q14864
|
sortComments
|
train
|
function sortComments(comments) {
var moduleComments = [];
var typeComments = [];
var varComments = [];
var methodComments = [];
var typelessComments = [];
comments.forEach(function (comment) {
if(comment.type) {
switch(comment.type) {
case exports.COMMENT_TYPES.MODULE:
moduleComments.push(comment);
break;
case exports.COMMENT_TYPES.METHOD:
methodComments.push(comment);
break;
case exports.COMMENT_TYPES.TYPE:
typeComments.push(comment);
break;
case exports.COMMENT_TYPES.VARIABLE:
varComments.push(comment);
break;
}
} else {
typelessComments.push(comment);
}
});
return moduleComments.concat(typeComments.concat(varComments.concat(methodComments.concat(typelessComments))));
}
|
javascript
|
{
"resource": ""
}
|
q14865
|
identifyCommentType
|
train
|
function identifyCommentType(tag) {
var commentType = null;
for (var tagName in tag) {
if (tag.hasOwnProperty(tagName)) {
switch (tagName) {
case exports.TAG_NAMES.API:
case exports.TAG_NAMES.METHOD:
case exports.TAG_NAMES.METHOD_SIGNATURE:
case exports.TAG_NAMES.METHOD_NAME:
case exports.TAG_NAMES.PARAM:
case exports.TAG_NAMES.RETURN:
case exports.TAG_NAMES.THROWS:
commentType = exports.COMMENT_TYPES.METHOD;
break;
case exports.TAG_NAMES.MODULE:
case exports.TAG_NAMES.REQUIRES:
commentType = exports.COMMENT_TYPES.MODULE;
break;
case exports.TAG_NAMES.CLASS:
commentType = exports.COMMENT_TYPES.TYPE;
break;
case exports.TAG_NAMES.VARIABLE_NAME:
commentType = exports.COMMENT_TYPES.VARIABLE;
break;
}
}
}
return commentType;
}
|
javascript
|
{
"resource": ""
}
|
q14866
|
balance
|
train
|
function balance(a, b){
var diff = a.length - b.length
var short = diff >= 0 ? b : a
diff = Math.abs(diff)
while (diff--) short.push(['c',0,0,0,0,0,0])
return [a, b]
}
|
javascript
|
{
"resource": ""
}
|
q14867
|
activate
|
train
|
function activate(context) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "Tlid" is now active!');
// // The command has been defined in the package.json file
// // Now provide the implementation of the command with registerCommand
// // The commandId parameter must match the command field in package.json
// let disposable = vscode.commands.registerCommand('extension.sayHello', function () {
// // The code you place here will be executed every time your command is executed
// // Display a message box to the user
// vscode.window.showInformationMessage('Hello World!');
// });
let disposableTlidGet = vscode.commands.registerCommand('extension.TlidGet', function () {
// The code you place here will be executed every time your command is executed
vscode.window.showInformationMessage("Creating Tlid...");
var tlidValue = tlid.get();
clipboardy.writeSync(tlidValue);
// Display a message box to the user
vscode.window.showInformationMessage(tlidValue);
});
let disposableTlidLineToJSON = vscode.commands.registerCommand('extension.TlidLineToJSON', function () {
// The code you place here will be executed every time your command is executed
// vscode.window.showInformationMessage("Transforming Tlid line...");
var tlidLine = clipboardy.readSync();
var tlidValue = tlid.get();
var r =
gixdeco.geto(tlidLine);
try {
if (r['tlid'] == null)
r['tlid'] = tlidValue; //setting it up
} catch (error) {
}
// if (r.tlid == null || r.tlid == "-1")
var out = JSON.stringify(r);
clipboardy.writeSync(out);
// Display a message box to the user
vscode.window.showInformationMessage(out);
// vscode.window.showInformationMessage(tlidLine);
});
let disposableTlidGetJSON = vscode.commands.registerCommand('extension.TlidGetJSON', function () {
// The code you place here will be executed every time your command is executed
vscode.window.showInformationMessage("Creating JSON Tlid...");
var tlidValue = tlid.json();
clipboardy.writeSync(tlidValue);
// Display a message box to the user
vscode.window.showInformationMessage(tlidValue);
});
let disposableTlidugGet = vscode.commands.registerCommand('extension.TlidugGet', function () {
// The code you place here will be executed every time your command is executed
vscode.window.showInformationMessage("Creating Tlidug...");
var tlidugValue = tlidug.get();
clipboardy.writeSync(tlidugValue);
// Display a message box to the user
vscode.window.showInformationMessage(tlidugValue);
});
let disposableIdugGet = vscode.commands.registerCommand('extension.IdugGet', function () {
// The code you place here will be executed every time your command is executed
vscode.window.showInformationMessage("Creating Idug...");
var idugValue = idug.get();
clipboardy.writeSync(idugValue);
// Display a message box to the user
vscode.window.showInformationMessage(idugValue);
});
let disposableUnIdugGet = vscode.commands.registerCommand('extension.UnIdugGet', function () {
// The code you place here will be executed every time your command is executed
vscode.window.showInformationMessage("Creating UnDashed Idug...");
var idugValue = idug.un();
clipboardy.writeSync(idugValue);
// Display a message box to the user
vscode.window.showInformationMessage(idugValue);
});
context.subscriptions.push(disposableTlidLineToJSON);
context.subscriptions.push(disposableUnIdugGet);
context.subscriptions.push(disposableIdugGet);
context.subscriptions.push(disposableTlidGet);
context.subscriptions.push(disposableTlidGetJSON);
context.subscriptions.push(disposableTlidugGet);
}
|
javascript
|
{
"resource": ""
}
|
q14868
|
TypedString
|
train
|
function TypedString (config) {
const string = this;
// validate min length
if (config.hasOwnProperty('minLength') && (!util.isInteger(config.minLength) || config.minLength < 0)) {
const message = util.propertyErrorMessage('minLength', config.minLength, 'Must be an integer that is greater than or equal to zero.');
throw Error(message);
}
const minLength = config.hasOwnProperty('minLength') ? config.minLength : 0;
// validate max length
if (config.hasOwnProperty('maxLength') && (!util.isInteger(config.maxLength) || config.maxLength < minLength)) {
const message = util.propertyErrorMessage('maxLength', config.maxLength, 'Must be an integer that is greater than or equal to the minLength.');
throw Error(message);
}
// validate pattern
if (config.hasOwnProperty('pattern') && !(config.pattern instanceof RegExp)) {
const message = util.propertyErrorMessage('pattern', config.pattern, 'Must be a regular expression object.');
throw Error(message);
}
// define properties
Object.defineProperties(string, {
maxLength: {
/**
* @property
* @name TypedString#maxLength
* @type {number}
*/
value: Math.round(config.maxLength),
writable: false
},
minLength: {
/**
* @property
* @name TypedString#minLength
* @type {number}
*/
value: Math.round(config.minLength),
writable: false
},
pattern: {
/**
* @property
* @name TypedString#pattern
* @type {RegExp}
*/
value: config.pattern,
writable: false
}
});
return string;
}
|
javascript
|
{
"resource": ""
}
|
q14869
|
custom
|
train
|
function custom(options, onfile, done) {
if ((!options) || (typeof(options) == 'function'))
throw new Error("please provide some options");
if (!options.fields)
throw new Error("please provide some fields");
return resolveList(builder.files, options, [], onfile, done);
}
|
javascript
|
{
"resource": ""
}
|
q14870
|
Ankh
|
train
|
function Ankh(kernel) {
Object.defineProperty(this,'kernel',{
value: (kernel || new Kernel())
,configurable: false
,writable: false
,enumerable: true
})
}
|
javascript
|
{
"resource": ""
}
|
q14871
|
notFound
|
train
|
function notFound( req, res, next ) {
var err = new Error( 'Not Found' );
err.status = 404;
next( err );
}
|
javascript
|
{
"resource": ""
}
|
q14872
|
debug
|
train
|
function debug( err, req, res, next ) {
res.status( err.status || 500 );
err.guid = uuid.v4();
console.error( err );
res.json( {
error: err.message,
message: err.userMessage,
handled: err.handled || false,
guid: err.guid,
stack: err.stack
} );
}
|
javascript
|
{
"resource": ""
}
|
q14873
|
train
|
function( tmpl, data, options, parentItem ) {
var ret, topLevel = !parentItem;
if ( topLevel ) {
// This is a top-level tmpl call (not from a nested template using {{tmpl}})
parentItem = topTmplItem;
tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl );
wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level
} else if ( !tmpl ) {
// The template item is already associated with DOM - this is a refresh.
// Re-evaluate rendered template for the parentItem
tmpl = parentItem.tmpl;
newTmplItems[parentItem.key] = parentItem;
parentItem.nodes = [];
if ( parentItem.wrapped ) {
updateWrapped( parentItem, parentItem.wrapped );
}
// Rebuild, without creating a new template item
return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) ));
}
if ( !tmpl ) {
return []; // Could throw...
}
if ( typeof data === "function" ) {
data = data.call( parentItem || {} );
}
if ( options && options.wrapped ) {
updateWrapped( options, options.wrapped );
}
ret = jQuery.isArray( data ) ?
jQuery.map( data, function( dataItem ) {
return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
}) :
[ newTmplItem( options, parentItem, tmpl, data ) ];
return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q14874
|
train
|
function( elem ) {
var tmplItem;
if ( elem instanceof jQuery ) {
elem = elem[0];
}
while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {}
return tmplItem || topTmplItem;
}
|
javascript
|
{
"resource": ""
}
|
|
q14875
|
ConsoleLogger
|
train
|
function ConsoleLogger() {
this.error = function () {
if (loggingLevel(ERROR)) {
console.error.apply(this, arguments);
}
};
this.warn = function () {
if (loggingLevel(WARN)) {
console.warn.apply(this, arguments);
}
};
this.info = function () {
if (loggingLevel(INFO)) {
console.info.apply(this, arguments);
}
};
this.log = function () {
if (loggingLevel(INFO)) {
console.log.apply(this, arguments);
}
};
this.debug = function () {
if (loggingLevel(DEBUG)) {
console.log.apply(this, arguments);
}
};
this.setLevelToInfo = function () {
setLevel(INFO);
};
this.setLevelToDebug = function() {
setLevel(DEBUG);
};
this.setLevelToWarning = function() {
setLevel(WARN);
};
this.setLevelToError = function() {
setLevel(ERROR);
};
}
|
javascript
|
{
"resource": ""
}
|
q14876
|
getNestedEditableIn
|
train
|
function getNestedEditableIn( editablesContainer, remainingEditables ) {
if ( remainingEditables == null )
remainingEditables = findNestedEditables( editablesContainer );
var editable;
while ( ( editable = remainingEditables.shift() ) ) {
if ( isIterableEditable( editable ) )
return { element: editable, remaining: remainingEditables };
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q14877
|
rangeAtInnerBlockBoundary
|
train
|
function rangeAtInnerBlockBoundary( range, block, checkEnd ) {
if ( !block )
return false;
var testRange = range.clone();
testRange.collapse( !checkEnd );
return testRange.checkBoundaryOfElement( block, checkEnd ? CKEDITOR.START : CKEDITOR.END );
}
|
javascript
|
{
"resource": ""
}
|
q14878
|
orgs
|
train
|
async function orgs(users, options) {
const opts = Object.assign({}, options);
const acc = { orgs: [], names: [] };
if (isObject(users)) {
return github('paged', '/user/orgs', users).then(res => addOrgs(acc, res));
}
if (typeof users === 'string') users = [users];
if (!Array.isArray(users)) {
return Promise.reject(new TypeError('expected users to be a string or array'));
}
const pending = [];
for (const name of users) {
pending.push(getOrgs(acc, name, options));
}
await Promise.all(pending);
if (opts.sort !== false) {
return acc.orgs.sort(compare('login'));
}
return acc.orgs;
}
|
javascript
|
{
"resource": ""
}
|
q14879
|
init
|
train
|
function init(){
debug("Checking if there is a repository");
return co(function*(){
let repo;
try {
repo = yield nodegit.Repository.open(repositoryPath);
} catch(err) {
debug("Repository not found.");
repo = yield _createRepository();
}
debug("Repository is ready");
return repo;
});
}
|
javascript
|
{
"resource": ""
}
|
q14880
|
_getFiles
|
train
|
function _getFiles(path){
let files = [];
fs.readdirSync(path).forEach(function(file){
let subpath = path + '/' + file;
if(fs.lstatSync(subpath).isDirectory()){
let filesReturned = _getFiles(subpath);
files = files.concat(filesReturned);
} else {
files.push(path + '/' + file);
}
});
return files;
}
|
javascript
|
{
"resource": ""
}
|
q14881
|
_commit
|
train
|
function _commit(repo, pathsToStage, message, pathsToUnstage) {
return co(function*(){
repo = repo || (yield nodegit.Repository.open(repositoryPath));
debug("Adding files to the index");
let index = yield repo.refreshIndex(repositoryPath + "/.git/index");
if(pathsToUnstage && pathsToUnstage.length && pathsToUnstage.length > 0) {
for(let file of pathsToUnstage) {
yield index.removeByPath(file);
}
yield index.write();
yield index.writeTree();
}
debug("Creating main files");
let signature = nodegit.Signature.default(repo);
debug("Commiting");
yield repo.createCommitOnHead(pathsToStage, signature, signature, message || "Automatic initialization");
});
}
|
javascript
|
{
"resource": ""
}
|
q14882
|
_createRepository
|
train
|
function _createRepository() {
return co(function*(){
try {
debug("Creating a new one");
let repo = yield nodegit.Repository.init(repositoryPath, 0);
debug("Connection established");
debug("Creating main files");
yield _createManifest(repo);
yield _createConfig(repo);
fs.mkdirSync(machinesDirPath);
yield _commit(repo, ["manifest.json", "config.json"]);
debug("Repository was successfully created");
return repo;
} catch (err) {
debug(err);
debug("Nuking the repository");
yield new Promise(function(resolve, reject) {
rimraf(repositoryPath, function () {
resolve();
});
}).then();
throw new Error(err);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q14883
|
_createManifest
|
train
|
function _createManifest(){
let file = repositoryPath + '/manifest.json';
let manifest = {
machines: {}
};
return new Promise(function(resolve, reject) {
debug("Creating manifest file");
jsonfile.writeFile(file, manifest, function (err) {
if(err){
debug("Failed to create the manifest file");
reject(err);
return;
}
resolve();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14884
|
_createConfig
|
train
|
function _createConfig(){
let file = repositoryPath + '/config.json';
let config = {
simulation: false
};
return new Promise(function(resolve, reject) {
jsonfile.writeFile(file, config, function (err) {
if(err){
reject(err);
return;
}
resolve();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14885
|
setManifest
|
train
|
function setManifest(manifest, withCommit, message){
jsonfile.writeFileSync(manifestPath, manifest, {spaces: 2});
if(withCommit) {
return _commit(null, ["manifest.json"],
message || "Changed the manifest file");
}
}
|
javascript
|
{
"resource": ""
}
|
q14886
|
setConfig
|
train
|
function setConfig(config, withCommit, message){
jsonfile.writeFileSync(configPath, config, {spaces: 2});
if(withCommit) {
return _commit(null, ["config.json"],
message || "Changed the config file");
}
}
|
javascript
|
{
"resource": ""
}
|
q14887
|
addMachine
|
train
|
function addMachine(name) {
return co(function*(){
debug("Adding a new machine with the name '%s'", name);
let manifest = getManifest();
if(manifest.machines[name]) {
debug("Machine already exists");
throw new Error("Machine already exists");
}
manifest.machines[name] = {
route: "machines/" + name,
"versions": {
"version1": {
"route": "machines/" + name + "/versions/version1",
"instances": {}
}
}
};
let machineDirPath = "machines/" + name;
let machineVersionsDirPath = machineDirPath + "/versions";
let version1DirPath = machineVersionsDirPath + "/version1";
let version1InstancesDirPath = version1DirPath + "/instances";
let modelFile = version1DirPath + '/model.scxml';
let infoFile = version1DirPath + "/info.json";
debug("Creating the directories");
fs.mkdirSync(repositoryPath + "/" + machineDirPath);
fs.mkdirSync(repositoryPath + "/" + machineVersionsDirPath);
fs.mkdirSync(repositoryPath + "/" + version1DirPath);
fs.mkdirSync(repositoryPath + "/" + version1InstancesDirPath);
debug("Creating the base.scxml file");
fs.copySync(__dirname + '/base.scxml', repositoryPath + "/" + modelFile);
debug("Creating the version info.json file");
let infoVersion1 = { "isSealed": false };
jsonfile.writeFileSync(repositoryPath + "/" + infoFile, infoVersion1);
debug("Setting the manifest");
setManifest(manifest);
yield _commit(null, ["manifest.json", modelFile, infoFile], "Added '" + name + "' machine");
debug("A new machine with the name '%s' was successfully added", name);
});
}
|
javascript
|
{
"resource": ""
}
|
q14888
|
removeMachine
|
train
|
function removeMachine(name) {
return co(function*(){
debug("Removing the machine");
let manifest = getManifest();
if(!manifest.machines[name]) {
debug("Machine doesn't exists");
return;
}
let machinePath = machinesDirPath + "/" + name;
let removedFileNames = _getFiles(machinePath).map((f)=>f.substring(repositoryPath.length + 1));
delete manifest.machines[name];
yield new Promise(function(resolve, reject) {
rimraf(machinesDirPath + "/" + name, function () {
resolve();
});
}).then();
debug("Setting the manifest");
setManifest(manifest);
yield _commit(null, ["manifest.json"], "Removed '" + name + "' machine.", removedFileNames);
return Object.keys(manifest.machines);
});
}
|
javascript
|
{
"resource": ""
}
|
q14889
|
getVersionsKeys
|
train
|
function getVersionsKeys(machineName) {
let manifest = getManifest();
if (!manifest.machines[machineName]) {
throw new Error("Machine does not exists");
}
return Object.keys(manifest.machines[machineName].versions);
}
|
javascript
|
{
"resource": ""
}
|
q14890
|
getVersionRoute
|
train
|
function getVersionRoute(machineName, versionKey) {
let manifest = getManifest();
if (!manifest.machines[machineName]) {
throw new Error("Machine does not exists");
}
if (!manifest.machines[machineName].versions[versionKey]) {
throw new Error("Version does not exists");
}
return manifest.machines[machineName].versions[versionKey].route;
}
|
javascript
|
{
"resource": ""
}
|
q14891
|
getVersionInfo
|
train
|
function getVersionInfo(machineName, versionKey) {
let route = getVersionInfoRoute(machineName, versionKey);
return jsonfile.readFileSync(repositoryPath + "/" + route);
}
|
javascript
|
{
"resource": ""
}
|
q14892
|
setVersionInfo
|
train
|
function setVersionInfo(machineName, versionKey, info, withCommit, message) {
let route = getVersionInfoRoute(machineName, versionKey);
let previousInfo = jsonfile.readFileSync(repositoryPath + "/" + route);
if(previousInfo.isSealed) {
throw new Error("Cannot change the version SCXML because the version is sealed.")
}
jsonfile.writeFileSync(repositoryPath + "/" + route, info, {spaces: 2});
if(withCommit) {
return _commit(null, [route],
message || "Changed the info for the " + versionKey + " of the '" + machineName + "' machine" );
}
}
|
javascript
|
{
"resource": ""
}
|
q14893
|
addVersion
|
train
|
function addVersion(machineName) {
return co(function*() {
debug("Adding a new version to the '" + machineName + "' machine");
let manifest = getManifest();
if (!manifest.machines[machineName]) {
throw new Error("Machine does not exists");
}
let versions = manifest.machines[machineName].versions;
let versionKeys = Object.keys(versions);
let lastVersionKey = versionKeys[versionKeys.length - 1];
let lastVersion = versions[lastVersionKey];
let lastVersionInfoFile = lastVersion.route + "/info.json";
let lastVersionInfo = jsonfile.readFileSync(repositoryPath + "/" + lastVersionInfoFile);
let lastVersionModelFile = lastVersion.route + '/model.scxml';
if(!lastVersionInfo.isSealed) {
throw new Error("The last versions is not sealed yet");
}
let newVersionKey = "version" + (versionKeys.length + 1);
let versionDirPath = manifest.machines[machineName].route + "/versions/" + newVersionKey;
manifest.machines[machineName].versions[newVersionKey] = {
"route": versionDirPath,
"instances": {}
};
let versionInstancesDirPath = versionDirPath + "/instances";
let modelFile = versionDirPath + '/model.scxml';
let infoFile = versionDirPath + "/info.json";
debug("Creating the directories");
fs.mkdirSync(repositoryPath + "/" + versionDirPath);
fs.mkdirSync(repositoryPath + "/" + versionInstancesDirPath);
debug("Copying the previous version's model.scxml");
fs.copySync(repositoryPath + "/" + lastVersionModelFile, repositoryPath + "/" + modelFile);
debug("Creating the version info.json file");
let infoVersion = { "isSealed": false };
jsonfile.writeFileSync(repositoryPath + "/" + infoFile, infoVersion);
debug("Setting the manifest");
setManifest(manifest);
yield _commit(null, ["manifest.json", modelFile, infoFile],
"Created the "+newVersionKey+" for the '" + machineName + "' machine");
return newVersionKey;
});
}
|
javascript
|
{
"resource": ""
}
|
q14894
|
sealVersion
|
train
|
function sealVersion(machineName, versionKey) {
return co(function*(){
debug("Attempting to seal the version '%s' of the machine '%s'", versionKey, machineName);
let info = yield getVersionInfo(machineName, versionKey);
if(info.isSealed) {
throw new Error("Version it already sealed");
}
debug("Getting manifest");
let manifest = getManifest();
let model = getVersionSCXML(machineName, versionKey);
let isValid = isSCXMLValid(model);
if(!isValid) {
throw new Error("The model is not valid.");
}
info.isSealed = true;
setVersionInfo(machineName, versionKey, info);
debug("The version '%s' of the machine '%s' was sealed successfully", versionKey, machineName);
});
}
|
javascript
|
{
"resource": ""
}
|
q14895
|
getVersionSCXML
|
train
|
function getVersionSCXML(machineName, versionKey) {
let route = getVersionModelRoute(machineName, versionKey);
return fs.readFileSync(repositoryPath + "/" + route).toString('utf8');
}
|
javascript
|
{
"resource": ""
}
|
q14896
|
setVersionSCXML
|
train
|
function setVersionSCXML(machineName, versionKey, model, withCommit, message) {
let route = getVersionInfoRoute(machineName, versionKey);
let previousInfo = jsonfile.readFileSync(repositoryPath + "/" + route);
if(previousInfo.isSealed) {
throw new Error("Cannot change the version SCXML because the version is sealed.")
}
let modelRoute = getVersionModelRoute(machineName, versionKey);
fs.writeFileSync(repositoryPath + "/" + modelRoute, model);
if(withCommit) {
return _commit(null, [modelRoute],
"Changed the model.scxml for the " + versionKey + " of the '" + machineName + "' machine");
}
}
|
javascript
|
{
"resource": ""
}
|
q14897
|
isSCXMLValid
|
train
|
function isSCXMLValid(model){
return new Promise(function(resolve, reject) {
if(model === "") {
reject("Model is empty");
return;
}
validator.validateXML(model, __dirname + '/xmlSchemas/scxml.xsd', function(err, result) {
if (err) {
reject(err);
return;
}
resolve(result.valid);
})
});
}
|
javascript
|
{
"resource": ""
}
|
q14898
|
getInstancesKeys
|
train
|
function getInstancesKeys(machineName, versionKey){
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
return Object.keys(version.instances);
}
|
javascript
|
{
"resource": ""
}
|
q14899
|
getInstanceRoute
|
train
|
function getInstanceRoute(machineName, versionKey, instanceKey){
let manifest = getManifest();
let machine = manifest.machines[machineName];
if (!machine) {
throw new Error("Machine does not exists");
}
let version = machine.versions[versionKey];
if (!version) {
throw new Error("Version does not exists");
}
let instance = version.instances[instanceKey];
if (!instance) {
throw new Error("Instance does not exists");
}
return instance.route;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.