_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q39100 | train | function(o) {
return gui.Type.isGuiClass(o) &&
gui.Class.ancestorsAndSelf(o).some(function(C) {
return C === edb.Object || C === edb.Array;
});
} | javascript | {
"resource": ""
} | |
q39101 | train | function() {
return Array.map(this, function(thing) {
if (edb.Type.is(thing)) {
return thing.toJSON();
}
return thing;
});
} | javascript | {
"resource": ""
} | |
q39102 | observes | train | function observes(array) {
var key = array.$instanceid;
return edb.Array._observers[key] ? true : false;
} | javascript | {
"resource": ""
} |
q39103 | train | function(tick) {
var snapshot, handlers, observers = this._observers;
if (tick.type === edb.TICK_PUBLISH_CHANGES) {
snapshot = gui.Object.copy(this._changes);
this._changes = Object.create(null);
gui.Object.each(snapshot, function(instanceid, changes) {
if ((handlers = observers[instanceid])) {
handlers.forEach(function(handler) {
handler.onchange(changes);
});
}
});
}
} | javascript | {
"resource": ""
} | |
q39104 | decorateAccess | train | function decorateAccess(proto, methods) {
methods.forEach(function(method) {
proto[method] = beforeaccess(proto[method]);
});
} | javascript | {
"resource": ""
} |
q39105 | lookupDescriptor | train | function lookupDescriptor(proto, key) {
if (proto.hasOwnProperty(key)) {
return Object.getOwnPropertyDescriptor(proto, key);
} else if ((proto = Object.getPrototypeOf(proto))) {
return lookupDescriptor(proto, key);
} else {
return null;
}
} | javascript | {
"resource": ""
} |
q39106 | guidedconvert | train | function guidedconvert(args, array) {
return args.map(function(o) {
if (o !== undefined) {
if (gui.Type.isConstructor(array.$of)) {
o = constructas(array.$of, o);
} else {
o = filterfrom(function(x) {
return array.$of(x);
}, o);
}
}
return o;
});
} | javascript | {
"resource": ""
} |
q39107 | train | function(array, args) {
args = gui.Array.from(args);
if (!gui.Type.isNull(array.$of)) {
if (gui.Type.isFunction(array.$of)) {
return guidedconvert(args, array);
} else {
var type = gui.Type.of(array.$of);
throw new Error(array + ' cannot be $of ' + type);
}
} else {
return autoconvert(args);
}
} | javascript | {
"resource": ""
} | |
q39108 | getter | train | function getter(key, base) {
return function() {
var result = base.apply(this);
if (edb.$accessaware && !suspend) {
edb.Object.$onaccess(this, key);
}
return result;
};
} | javascript | {
"resource": ""
} |
q39109 | train | function(type, target) {
var handler, input = this._configure(type.constructor, type);
if (target) {
console.error("Deprecated API is deprecated", target.spirit);
if ((handler = target.$oninput || target.oninput)) {
handler.call(target, input);
}
} else {
gui.Broadcast.dispatch(edb.BROADCAST_OUTPUT, input);
}
} | javascript | {
"resource": ""
} | |
q39110 | train | function(Type) {
if (Type) {
if (this._map) {
var classid = Type.$classid;
var typeobj = this._map[classid];
return typeobj ? true : false;
}
return false;
} else {
throw new Error("Something is undefined");
}
} | javascript | {
"resource": ""
} | |
q39111 | train | function(Type, type) {
var classid = Type.$classid;
this._map[classid] = type;
return new edb.Input(Type, type);
} | javascript | {
"resource": ""
} | |
q39112 | train | function(type, filter, tabs) {
if (isType(type)) {
return JSON.stringify(parse(type), filter, tabs);
} else {
throw new TypeError("Expected edb.Object|edb.Array");
}
} | javascript | {
"resource": ""
} | |
q39113 | asObject | train | function asObject(type) {
var map = gui.Object.map(type, mapObject, type);
return {
$object: gui.Object.extend({
$classname: type.$classname,
$instanceid: type.$instanceid,
$originalid: type.$originalid
}, map)
};
} | javascript | {
"resource": ""
} |
q39114 | mapObject | train | function mapObject(key, value) {
var c = key.charAt(0);
if (c === "_" || c === "$") {
return undefined;
} else if (isArray(this) && key.match(INTRINSIC)) {
return undefined;
} else if (isType(value)) {
return parse(value);
} else if (gui.Type.isComplex(value)) {
switch (value.constructor) {
case Object:
case Array:
return value;
}
return undefined;
} else {
if (isType(this)) {
var base = this.constructor.prototype;
var desc = Object.getOwnPropertyDescriptor(base, key);
if (desc && (desc.set || desc.get)) {
return undefined;
}
}
return value;
}
} | javascript | {
"resource": ""
} |
q39115 | mapArray | train | function mapArray(type) {
return Array.map(type, function(thing) {
return isType(thing) ? parse(thing) : thing;
});
} | javascript | {
"resource": ""
} |
q39116 | train | function(input) {
var needstesting = !this._matches.length;
if (needstesting || this._matches.every(function(match) {
return match.$instanceid !== input.$instanceid;
})) {
return this._maybeinput(input);
}
return false;
} | javascript | {
"resource": ""
} | |
q39117 | train | function(types, handler, required) {
types.forEach(function(Type) {
if (gui.Type.isDefined(Type)) {
this._addchecks(Type.$classid, [handler]);
this._watches.push(Type);
if (required) {
this._needing.push(Type);
}
} else {
throw new TypeError("Could not register input for undefined Type");
}
}, this);
types.forEach(function(Type) {
gui.Class.descendantsAndSelf(Type, function(T) {
if (T.out(this.context)) { // type has been output already?
this._maybeinput(edb.Output.$get(T));
}
}, this);
}, this);
} | javascript | {
"resource": ""
} | |
q39118 | train | function(types, handler) {
types.forEach(function(Type) {
gui.Array.remove(this._watches, Type);
gui.Array.remove(this._needing, Type);
this._removechecks(Type.$classid, [handler]);
if (!this._watches.length) {
this._subscribe(false);
}
}, this);
} | javascript | {
"resource": ""
} | |
q39119 | train | function(input) {
var best = edb.InputPlugin._bestmatch(input.type, this._watches, true);
if (best) {
this._updatematch(input, best);
this.done = this._done();
this._updatehandlers(input);
return true;
}
return false;
} | javascript | {
"resource": ""
} | |
q39120 | train | function(input) {
var matches = this._matches;
var watches = this._watches;
var best = edb.InputPlugin._bestmatch(input.type, watches, true);
if (best) {
var oldinput = matches.filter(function(input) {
return input.type === best;
})[0];
var index = matches.indexOf(oldinput);
matches.splice(index, 1);
this.done = this._done();
if (!this.done) {
input.revoked = true;
this._updatehandlers(input);
}
}
} | javascript | {
"resource": ""
} | |
q39121 | train | function(input) {
gui.Class.ancestorsAndSelf(input.type, function(Type) {
var list = this._trackedtypes[Type.$classid];
if (list) {
list.forEach(function(checks) {
var handler = checks[0];
handler.oninput(input);
});
}
}, this);
} | javascript | {
"resource": ""
} | |
q39122 | train | function() {
var needs = this._needing;
var haves = this._matches;
return needs.every(function(Type) {
return haves.some(function(input) {
return (input.data instanceof Type);
});
});
} | javascript | {
"resource": ""
} | |
q39123 | train | function(arg, context) {
switch (gui.Type.of(arg)) {
case "function":
return [arg];
case "string":
return this._breakarray(arg.split(" "), context);
case "object":
console.error("Expected function. Got object.");
}
} | javascript | {
"resource": ""
} | |
q39124 | train | function(target, types, up, action) {
types.forEach(function(type) {
action(type, this._rateone(
up ? target : type, up ? type : target
));
}, this);
} | javascript | {
"resource": ""
} | |
q39125 | train | function(id) {
var config, script;
return {
as: function($edbml) {
config = edbml.$runtimeconfigure($edbml);
script = gui.Object.assert(id, config);
script.$bind = function() {
console.error('Deprecated API is deprecated: $bind');
};
script.lock = function(out) {
return script({
$out: out
});
};
return this;
},
withInstructions: function(pis) {
script.$instructions = pis;
}
};
} | javascript | {
"resource": ""
} | |
q39126 | train | function($edbml) {
return function configured($in) {
$edbml.$out = ($in && $in.$out) ? $in.$out : new edbml.Out();
$edbml.$att = new edbml.Att();
$edbml.$input = function(Type) {
return this.script.$input.get(Type);
}.bind(this);
return $edbml.apply(this, arguments);
};
} | javascript | {
"resource": ""
} | |
q39127 | train | function(func, thisp) {
var key = gui.KeyMaster.generateKey();
this._invokables[key] = function(value, checked) {
return func.apply(thisp, [gui.Type.cast(value), checked]);
};
return key;
} | javascript | {
"resource": ""
} | |
q39128 | train | function(e) {
this._latestevent = e ? {
type: e.type,
value: e.target.value,
checked: e.target.checked
} : null;
} | javascript | {
"resource": ""
} | |
q39129 | train | function() {
var html = "";
gui.Object.nonmethods(this).forEach(function(att) {
html += this._out(att);
}, this);
return html;
} | javascript | {
"resource": ""
} | |
q39130 | train | function(html) {
this._newdom = this._parse(html);
this._crawl(this._newdom, this._olddom, this._newdom, this._keyid, {});
this._olddom = this._newdom;
} | javascript | {
"resource": ""
} | |
q39131 | train | function(newnode, oldnode, lastnode, id, ids) {
var result = true,
oldid = this._assistant.id(oldnode);
if ((result = this._check(newnode, oldnode, lastnode, id, ids))) {
if (oldid) {
ids = gui.Object.copy(ids);
lastnode = newnode;
ids[oldid] = true;
id = oldid;
}
result = this._crawl(newnode.firstChild, oldnode.firstChild, lastnode, id, ids);
}
return result;
} | javascript | {
"resource": ""
} | |
q39132 | train | function(newnode, oldnode, ids) {
var result = true;
var update = null;
if (this._attschanged(newnode.attributes, oldnode.attributes, ids)) {
var newid = this._assistant.id(newnode);
var oldid = this._assistant.id(oldnode);
if (newid && newid === oldid) {
update = new edbml.AttsUpdate(this._doc).setup(oldid, newnode, oldnode);
this._updates.collect(update, ids);
} else {
result = false;
}
}
return result;
} | javascript | {
"resource": ""
} | |
q39133 | train | function(newnode, oldnode) {
if (newnode && oldnode) {
return newnode.id && newnode.id === oldnode.id &&
this._maybesoft(newnode) &&
this._maybesoft(oldnode);
} else {
return Array.every(newnode.childNodes, function(node) {
var res = true;
switch (node.nodeType) {
case Node.TEXT_NODE:
res = node.data.trim() === "";
break;
case Node.ELEMENT_NODE:
res = this._assistant.id(node) !== null;
break;
}
return res;
}, this);
}
} | javascript | {
"resource": ""
} | |
q39134 | train | function(newnode, oldnode, ids) {
var updates = [];
var news = this._assistant.index(newnode.childNodes);
var olds = this._assistant.index(oldnode.childNodes);
/*
* Add elements?
*/
var child = newnode.lastElementChild,
topid = this._assistant.id(oldnode),
oldid = null,
newid = null;
while (child) {
newid = this._assistant.id(child);
if (!olds[newid]) {
if (oldid) {
updates.push(
new edbml.InsertUpdate(this._doc).setup(oldid, child)
);
} else {
updates.push(
new edbml.AppendUpdate(this._doc).setup(topid, child)
);
}
} else {
oldid = newid;
}
child = child.previousElementSibling;
}
/*
* Remove elements?
*/
Object.keys(olds).forEach(function(id) {
if (!news[id]) {
updates.push(
new edbml.RemoveUpdate(this._doc).setup(id)
);
updates.push(
new edbml.FunctionUpdate(this._doc).setup(id)
);
} else { // note that crawling continues here...
var n1 = news[id];
var n2 = olds[id];
this._scan(n1, n2, n1, id, ids);
}
}, this);
/*
* Register updates
*/
updates.reverse().forEach(function(update) {
this._updates.collect(update, ids);
}, this);
} | javascript | {
"resource": ""
} | |
q39135 | train | function(update, ids) {
this._updates.push(update);
if (update.type === edbml.Update.TYPE_HARD) {
this._hardupdates[update.id] = true;
} else {
update.ids = ids || {};
}
return this;
} | javascript | {
"resource": ""
} | |
q39136 | train | function(report) {
if (edbml.debug) {
if (gui.KeyMaster.isKey(this.id)) {
report = report.replace(this.id, "(anonymous)");
}
console.debug(report);
}
} | javascript | {
"resource": ""
} | |
q39137 | train | function() {
edbml.Update.prototype.update.call(this);
var element = this.element();
if (this._beforeUpdate(element)) {
this._update(element);
this._afterUpdate(element);
this._report();
}
} | javascript | {
"resource": ""
} | |
q39138 | train | function() {
var summary = this._summary.join(', ');
var message = 'edbml.AttsUpdate "#' + this.id + '" ' + summary;
edbml.Update.prototype._report.call(this, message);
// TODO: this would break super keyword algorithm!!!
// edbml.Update.prototype._report.call(this, edbml.AttsUpdate \# +
// this.id + \ + this._summary.join(this, ));
} | javascript | {
"resource": ""
} | |
q39139 | train | function() {
edbml.Update.prototype.update.call(this);
var element = this.element();
if (element && this._beforeUpdate(element)) {
//gui.DOMPlugin.html ( element, this.xelement.outerHTML );
gui.DOMPlugin.html(element, this.xelement.innerHTML);
this._afterUpdate(element);
this._report();
}
} | javascript | {
"resource": ""
} | |
q39140 | train | function() {
var count = 0,
elm = this.element();
if (this._map) {
if ((count = edbml.FunctionUpdate._remap(elm, this._map))) {
this._report("remapped " + count + " keys");
}
} else {
if ((count = edbml.FunctionUpdate._revoke(elm))) {
this._report("revoked " + count + " keys");
}
}
} | javascript | {
"resource": ""
} | |
q39141 | train | function(element) {
var atts = [];
new gui.Crawler('functionupdate').descend(element, {
handleElement: function(elm) {
if (elm !== element) {
Array.forEach(elm.attributes, function(att) {
if (att.value.contains("edbml.$run")) {
atts.push([elm, att]);
}
});
if (elm.spirit && elm.spirit.script.loaded) { // ... not our DOM tree
return gui.Crawler.SKIP_CHILDREN;
}
}
}
});
return atts;
} | javascript | {
"resource": ""
} | |
q39142 | train | function() {
gui.Plugin.prototype.ondestruct.call(this);
if (this.loaded) {
gui.Tick.cancelFrame(this._frameindex);
this.spirit.life.remove(gui.LIFE_ENTER, this);
gui.Broadcast.remove(edb.BROADCAST_ACCESS, this);
if (this.$input) { // TODO: interface for this (dispose)
this.$input.ondestruct();
this.$input.$ondestruct();
}
}
} | javascript | {
"resource": ""
} | |
q39143 | train | function(html) {
var changed = this._html !== html;
var focused = this._focusedfield();
if (changed) {
this._html = html;
this._updater.update(html);
if(focused) {
this._restorefocus(focused);
}
}
this._status(this.spirit);
this.ran = true; // TODO: deprecate and use 'spirit.life.rendered'
} | javascript | {
"resource": ""
} | |
q39144 | train | function(changes) {
if (changes.some(function(c) {
var id = c.object.$instanceid,
clas = c.object.$classname,
name = c.name;
if(edbml.$rendering && edbml.$rendering[id]) {
console.error(
'Don\'t update "' + name + '" of the ' + clas + ' while ' +
'rendering, it will cause the rendering to run in an endless loop. '
);
} else {
var props = this._oldfokkers[id].properties;
try {
if (!name || props[name]) {
return true;
}
} catch (todoexception) {
//console.error(this._oldfokkers[id].toString(), name);
// TODO: fix sceario with selectedIndex................
}
return false;
}
}, this)) {
this._schedule();
}
} | javascript | {
"resource": ""
} | |
q39145 | train | function(l) {
if (l.type === gui.LIFE_ENTER) {
if (!this.spirit.life.rendered) { // spirit did a manual run?
this.run.apply(this, this._arguments || []);
}
this.spirit.life.remove(l.type, this);
this._arguments = null;
}
} | javascript | {
"resource": ""
} | |
q39146 | train | function() {
edbml.$rendering = this._oldfokkers || {};
gui.Broadcast.add(edb.BROADCAST_ACCESS, this);
edb.$accessaware = true;
this._newfokkers = {};
} | javascript | {
"resource": ""
} | |
q39147 | train | function() {
var oldfokkers = this._oldfokkers,
newfokkers = this._newfokkers;
edbml.$rendering = null;
gui.Broadcast.remove(edb.BROADCAST_ACCESS, this);
edb.$accessaware = false;
Object.keys(oldfokkers).forEach(function(id) {
if (!newfokkers[id]) {
oldfokkers[id].object.removeObserver(this);
delete oldfokkers[id];
}
}, this);
Object.keys(newfokkers).forEach(function(id) {
var oldx = oldfokkers[id];
var newx = newfokkers[id];
if (oldx) {
if (newx.properties) {
oldx.properties = newx.properties;
}
} else {
oldfokkers[id] = newfokkers[id];
oldfokkers[id].object.addObserver(this);
delete newfokkers[id];
}
}, this);
this._newfokkers = null;
} | javascript | {
"resource": ""
} | |
q39148 | train | function() {
gui.Tick.cancelFrame(this._frameindex);
var spirit = this.spirit;
var input = this.$input;
var runnow = function() {
if (!spirit.life.destructed && (!input || input.done)) {
this.run();
}
}.bind(this);
if (spirit.life.entered) {
if (spirit.life.rendered) {
this._frameindex = gui.Tick.nextFrame(runnow);
} else {
runnow();
}
} else {
spirit.life.add(gui.LIFE_ENTER, this);
}
} | javascript | {
"resource": ""
} | |
q39149 | train | function(elm) {
var index = -1;
var parts = [];
function hasid(elm) {
if (elm.id) {
try {
gui.DOMPlugin.q(elm.parentNode, elm.id);
return true;
} catch (malformedexception) {}
}
return false;
}
while (elm && elm.nodeType === Node.ELEMENT_NODE) {
if (hasid(elm)) {
parts.push("#" + elm.id);
elm = null;
} else {
if (elm.localName === "body") {
parts.push("body");
elm = null;
} else {
index = gui.DOMPlugin.ordinal(elm) + 1;
parts.push(">" + elm.localName + ":nth-child(" + index + ")");
elm = elm.parentNode;
}
}
}
return parts.reverse().join("");
} | javascript | {
"resource": ""
} | |
q39150 | train | function(selector) {
var texts = 'textarea, input:not([type=checkbox]):not([type=radio])';
var field = gui.DOMPlugin.qdoc(selector);
if(field && field !== document.activeElement) {
field.focus();
if (gui.CSSPlugin.matches(field, texts)) {
field.setSelectionRange(
field.value.length,
field.value.length
);
}
}
} | javascript | {
"resource": ""
} | |
q39151 | train | function() {
gui.Spirit.prototype.onconfigure.call(this);
if (this.dom.embedded()) {
var id, parent = this.dom.parent(gui.Spirit);
if (parent && (id = this.scriptid)) {
parent.script.load(gui.Object.lookup(id));
}
}
} | javascript | {
"resource": ""
} | |
q39152 | train | function() {
/*
* Automatically load spirit scripts by naming convention?
* ns.MySpirit would automatically load ns.MySpirit.edbml
*/
var edbmlscript, basespirit = gui.Spirit.prototype;
gui.Function.decorateAfter(basespirit, 'onconfigure', function() {
if (edbml.bootload && !this.script.loaded) {
edbmlscript = gui.Object.lookup(this.$classname + '.edbml');
if (gui.Type.isFunction(edbmlscript)) {
this.script.load(edbmlscript);
}
}
});
/*
* Nasty hack to circumvent that we hardcode "event" into inline poke
* events, this creates an undesired global variable, but fixes an
* exception in the console, at least I think this was the problem.
*/
if (!window.event) {
try {
window.event = null;
} catch (ieexception) {}
}
} | javascript | {
"resource": ""
} | |
q39153 | train | function(node) {
var newNode = function(data, next) {
var that = {};
that.getData = function() {
return data;
};
that.getNext = function() {
return next;
};
return that;
};
var top = node || null;
var that = {};
that.__push_internal__ = function(data) {
return newStack(newNode(data, top));
};
that.__peek__ = function() {
return top && top.getData();
};
that.__pop_internal__ = function() {
return top && newStack(top.getNext());
};
that.__forEach__ = function(f) {
var i = top;
var s = 0;
while (i !== null) {
f(i.getData(), s);
s = s +1;
i = i.getNext();
}
};
that.__map__ = function(f) {
var i = top;
var result = [];
while (i !== null) {
result.push(f(i.getData()));
i = i.getNext();
}
return result;
};
that.__length__ = function() {
var count = 0;
that.__forEach__(function() { count = count + 1;});
return count;
};
return that;
} | javascript | {
"resource": ""
} | |
q39154 | execute | train | function execute(req, res) {
//console.dir(req.args);
var hmap = req.db.getKey(req.args[0], req);
if(hmap === undefined) {
return res.send(null, [0, []]);
}
//console.dir(hmap.getKeys())
var scanner = new Scanner(
hmap.getKeys(),
req.info.cursor,
req.info.pattern,
req.info.count,
hmap.data);
scanner.scan(req, res);
} | javascript | {
"resource": ""
} |
q39155 | lexPhrase | train | function lexPhrase(req, res) {
var now = elapse.start();
var body = req ? req.body : null;
var phrase = typeof(body) === 'object' ? body.phrase : null;
if (!phrase) {
return res.jsonp(412, {"code":412, "message": meta.module + '|lex|EXCEPTION|invalid request body: ' + (body === null ? 'body is null' : 'phrase is null')});
}
body.words = api.lex(phrase);
body.elapsedMs = elapse.stop(now).elapsed;
res.jsonp(body);
} | javascript | {
"resource": ""
} |
q39156 | walk | train | function walk (dir, mapper, exclude, include, stopfile) {
let files = fs.readdirSync(dir).map((file) => path.join(dir, file))
if (exclude)
files = files.filter((file) => !exclude.test(file))
let directories = files.filter(utils.is.dir)
files = files.filter(utils.is.file)
if (include)
files = files.filter((file) => include.test(file))
if (stopfile) {
for (let ii = 0; ii < files.length; ii++) {
if (stopfile.test(files[ii]))
return mapper ? mapper(files[ii]) : [files[ii]]
}
}
if (mapper)
files = files.map(mapper)
for (let jj = 0; jj < directories.length; jj++) {
let result = walk(directories[jj], mapper, exclude, include, stopfile)
files = files.concat(result)
}
return files
} | javascript | {
"resource": ""
} |
q39157 | getEmoticons | train | function getEmoticons(arr) {
var nested = arr.map(function (str) {
return str.match(between);
});
return flatten(nested)
.filter(function (el) {
return el;
})
.filter(emoticonsPredicate)
.map(function (str) {
return str.slice(1, str.length - 1);
});
} | javascript | {
"resource": ""
} |
q39158 | train | function (diffSeq, targetModel) {
var self = this;
this.targetModel = targetModel;
// know if a trace has already been added to cmdList for {path <-> AdaptationPrimitive}
var traceAlreadyProcessed = function (cmd) {
return self.alreadyProcessedTraces[cmd.modelElement.path()] && self.alreadyProcessedTraces[cmd.modelElement.path()][cmd.toString()];
};
// add a trace to the processed trace map
var addProcessedTrace = function (cmd) {
self.alreadyProcessedTraces[cmd.modelElement.path()] = self.alreadyProcessedTraces[cmd.modelElement.path()] || {};
self.alreadyProcessedTraces[cmd.modelElement.path()][cmd.toString()] = cmd;
};
// fill adaptation primitives list
var cmdList = [];
diffSeq.traces.array.forEach(function (trace) {
self.processTrace(trace).forEach(function (cmd) {
if (!traceAlreadyProcessed(cmd)) {
cmdList.push(cmd);
addProcessedTrace(cmd);
}
});
});
// clean primitives:
// - don't call UpdateInstance when (Start|Stop)Instance will be executed
for (var path in this.alreadyProcessedTraces) {
if (this.alreadyProcessedTraces[path][UpdateInstance.prototype.toString()]) {
for (var type in this.alreadyProcessedTraces[path]) {
if (type === StopInstance.prototype.toString() || type === StartInstance.prototype.toString()) {
var index = cmdList.indexOf(this.alreadyProcessedTraces[path][UpdateInstance.prototype.toString()]);
if (index > -1) {
cmdList.splice(index, 1);
}
}
}
}
}
// free-up some mem
this.targetModel = null;
this.alreadyProcessedTraces = {};
//return sorted command list (sort by COMMAND_RANK in order to process adaptations properly)
// this.sortCommands(cmdList).forEach(function (cmd) {
// var tag = cmd.toString();
// while (tag.length < 20) {
// tag += ' ';
// }
// console.log(tag, cmd.modelElement.path());
// });
return this.sortCommands(cmdList);
} | javascript | {
"resource": ""
} | |
q39159 | train | function (cmd) {
self.alreadyProcessedTraces[cmd.modelElement.path()] = self.alreadyProcessedTraces[cmd.modelElement.path()] || {};
self.alreadyProcessedTraces[cmd.modelElement.path()][cmd.toString()] = cmd;
} | javascript | {
"resource": ""
} | |
q39160 | train | function (element) {
if (element) {
if (element.metaClassName() === 'org.kevoree.ComponentInstance') {
// if parent is this node platform: it's ok
return (element.eContainer().name === this.node.getName());
} else if (element.metaClassName() === 'org.kevoree.Channel') {
// if this channel has bindings with components hosted in this node platform: it's ok
var bindings = element.bindings.iterator();
while (bindings.hasNext()) {
var binding = bindings.next();
if (binding.port && binding.port.eContainer()) {
if (this.isRelatedToPlatform(binding.port.eContainer())) {
return true;
}
}
}
} else if (element.metaClassName() === 'org.kevoree.Group') {
return element.subNodes.array.some(function (node) {
return this.isRelatedToPlatform(node);
}.bind(this));
} else if (element.metaClassName() === 'org.kevoree.ContainerNode') {
return ((element.name === this.node.getName()) || (element.host && element.host.name === this.node.getName()));
} else if (element.metaClassName() === 'org.kevoree.MBinding') {
if (element.port && element.port.eContainer()) {
if (this.isRelatedToPlatform(element.port.eContainer())) {
return true;
}
}
if (element.hub) {
return this.isRelatedToPlatform(element.hub);
}
} else if (element.metaClassName() === 'org.kevoree.Value') {
if (element.eContainer().metaClassName() === 'org.kevoree.FragmentDictionary') {
return (element.eContainer().name === this.node.getName());
} else {
return this.isRelatedToPlatform(element.eContainer().eContainer());
}
} else if (element.metaClassName() === 'org.kevoree.Port') {
return this.isRelatedToPlatform(element.eContainer());
}
}
return false;
} | javascript | {
"resource": ""
} | |
q39161 | train | function (list) {
list.sort(function (a, b) {
if (COMMAND_RANK[a.toString()] > COMMAND_RANK[b.toString()]) {
return 1;
} else if (COMMAND_RANK[a.toString()] < COMMAND_RANK[b.toString()]) {
return -1;
} else {
return 0;
}
});
return list;
} | javascript | {
"resource": ""
} | |
q39162 | del | train | function del(/* key-1, key-N, req */) {
var args = slice.call(arguments, 0)
, req = typeof args[args.length-1] === 'object' ? args.pop() : null;
var deleted = 0;
for(var i = 0;i < args.length;i++) {
if(this.keyExists(args[i])) {
this.delKey(args[i], req);
deleted++;
}
}
return deleted;
} | javascript | {
"resource": ""
} |
q39163 | rename | train | function rename(key, newkey, req) {
var val = this.getKey(key);
this.delKey(key);
this.setKey(newkey, val);
return OK;
} | javascript | {
"resource": ""
} |
q39164 | renamenx | train | function renamenx(key, newkey, req) {
var exists = this.keyExists(newkey);
if(!exists) {
this.rename(key, newkey, req);
}
return exists ? 0 : 1;
} | javascript | {
"resource": ""
} |
q39165 | move | train | function move(key, index, req) {
var val = this.getKey(key)
, db = this.store.getDatabase(index, this.options);
//console.dir(val);
if(!val || db.keyExists(key)) return 0;
db.setKey(key, val);
this.delKey(key);
return 1;
} | javascript | {
"resource": ""
} |
q39166 | transform | train | function transform(flapjack, options) {
var filePath = options.filePath;
var appName = this.getAppName(filePath, options.appName);
var appInfo = this.pancakes.cook(flapjack, null);
var validations = this.getSchemaValidations(appInfo, null);
var schema = this.stringify(validations);
var deps = (options.isMobile && appInfo.clientMobileDeps) ?
appInfo.clientMobileDeps :
appInfo.clientDependencies;
return this.template({
appName: this.getAppModuleName(options.prefix, appName),
deps: deps || [],
initLoad: appInfo.clientLoadOnInit,
isMobile: options.isMobile,
schema: schema,
isCommon: appName === 'common'
});
} | javascript | {
"resource": ""
} |
q39167 | getSchemaValidations | train | function getSchemaValidations(appInfo, resources) {
if (!appInfo.includeSchemas) { return null; }
// if resources not passed in, then get from pancakes
resources = resources || this.pancakes.cook('resources', null);
var validations = {};
_.each(resources, function (resource) {
_.each(resource.fields, function (fieldDef, fieldName) {
if (fieldDef.ui) {
validations[resource.name] = validations[resource.name] || {};
validations[resource.name][fieldName] = fieldDef;
}
});
});
return validations;
} | javascript | {
"resource": ""
} |
q39168 | stringify | train | function stringify(validations) {
if (!validations) { return ''; }
return JSON.stringify(validations, function (key, value) {
if (_.isRegExp(value)) { return value.toString(); }
switch (value) {
case String: return 'String';
case Boolean: return 'Boolean';
case Date: return 'Date';
case Number: return 'Number';
default: return value;
}
});
} | javascript | {
"resource": ""
} |
q39169 | Client | train | function Client(API_URL, token, opts) {
if (!(this instanceof Client)) return new Client(API_URL, token, opts);
if (typeof token == 'object') {
opts = token;
token = null;
}
Emitter.call(this);
var self = this;
opts = opts || {};
self.cache = new LRU(opts.maxSize || 500);
self.pending = {};
self.root = get.bind(self, API_URL);
self.get = get.bind(self);
var context = self.context = superagent();
if (token) self.header('authorization', 'Bearer ' + token);
// TODO only set the parser for the context
var parsers = context.request.parse;
parsers['application/json'] = parsers['application/hyper+json'] = parseHyperJson;
patchCrappySuperagent(context.request.Response, context.request.parse);
} | javascript | {
"resource": ""
} |
q39170 | HyperError | train | function HyperError(res) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'HyperError';
this.status = res.status;
if (res.body && res.body.error) this.message = res.body.error.message;
else this.message = res.text;
} | javascript | {
"resource": ""
} |
q39171 | train | function(spec, banner, strict) {
spec = spec || {};
banner = banner || "Usage:";
var self = this;
var incoming = process.argv.slice(2); // incoming params
/**
* Returns extra items frob b
* @param a
* @param b
* @returns {Array}
*/
var arrayDiff = function(a, b) {
return b.filter(function(i) {
return a.indexOf(i) == -1;
});
};
/**
* Check conditions. If help setted - always exit.
* @param parsed Parsed specs
*/
var check = function(parsed) {
var end = false, message = "", code = 0, outer = console.log;
var setted = Object.keys(self);
var specced = Object.keys(parsed);
var required = arrayDiff(setted, specced);
var unexpected = arrayDiff(specced, setted);
// If any required options is not provided - crash it!
if (required.length) {
end = true;
code = 1;
outer = console.error;
message += "Required but not provided:\n --"
+ required.join("\n --") + "\n";
}
// + unexpected
if (unexpected.length) {
message += "Unexpected options:\n --"
+ unexpected.join("\n --") + "\n";
}
message += (message.length ?
"\nRun with --help for more info" : "");
if (strict && message.length) {
end = true;
code = 1;
outer = console.error;
}
// If --help, exit without error
if (incoming.indexOf("--help") != -1) {
end = true;
code = 0;
outer = console.log;
message = Object.keys(parsed).reduce(function(msg, k) {
return msg + parsed[k].note + "\n --" + k
+ (parsed[k].req ? " *required\n" : "\n");
}, "") + "Help. This message.\n --help\n";
}
if (end) {
// exiting
outer(banner + "\n");
outer(message);
process.exit(code);
}
};
// Fill spec and default values
var parsed = {};
Object.keys(spec).forEach(function(name) {
var req = spec[name].value === undefined ? true : false;
var note = spec[name].note || "Note not provided";
parsed[name] = {
req : req,
note : note
};
// If value not required - set it
if (!req) {
self[name] = spec[name].value;
}
});
// Evaluate process.argv
var numRe = /^[0-9.]+$/;
incoming.filter(function(chunk) {
return chunk != "--help" && chunk != "--";
})
.forEach(function(chunk) {
if (chunk.substring(0,2) == "--") {
var tokens = chunk.substring(2).split("=");
var name = tokens[0];
// Expected option - evaluate value
if (tokens.length == 1) {
// Boolean
var value = true;
} else {
var value = tokens.length > 2 ?
tokens.slice(1).join('=') : tokens[1];
if (numRe.test(value)) {
value = parseFloat(value);
}
}
if (self[name] instanceof Array) {
self[name].push(value);
} else {
self[name] = value;
}
} else {
// Just argument
self.args.push(chunk);
}
});
check(parsed);
return this;
} | javascript | {
"resource": ""
} | |
q39172 | train | function(parsed) {
var end = false, message = "", code = 0, outer = console.log;
var setted = Object.keys(self);
var specced = Object.keys(parsed);
var required = arrayDiff(setted, specced);
var unexpected = arrayDiff(specced, setted);
// If any required options is not provided - crash it!
if (required.length) {
end = true;
code = 1;
outer = console.error;
message += "Required but not provided:\n --"
+ required.join("\n --") + "\n";
}
// + unexpected
if (unexpected.length) {
message += "Unexpected options:\n --"
+ unexpected.join("\n --") + "\n";
}
message += (message.length ?
"\nRun with --help for more info" : "");
if (strict && message.length) {
end = true;
code = 1;
outer = console.error;
}
// If --help, exit without error
if (incoming.indexOf("--help") != -1) {
end = true;
code = 0;
outer = console.log;
message = Object.keys(parsed).reduce(function(msg, k) {
return msg + parsed[k].note + "\n --" + k
+ (parsed[k].req ? " *required\n" : "\n");
}, "") + "Help. This message.\n --help\n";
}
if (end) {
// exiting
outer(banner + "\n");
outer(message);
process.exit(code);
}
} | javascript | {
"resource": ""
} | |
q39173 | validate | train | function validate(cmd, args, info) {
AbstractCommand.prototype.validate.apply(this, arguments);
var op = ('' + args[0]).toLowerCase();
if(op !== BITOP.AND && op !== BITOP.OR
&& op !== BITOP.XOR && op !== BITOP.NOT) {
throw CommandSyntax;
}
if(op === BITOP.NOT && args.length !== 3) {
throw BitopNot;
}
args[0] = op;
} | javascript | {
"resource": ""
} |
q39174 | ServerState | train | function ServerState() {
// server configuration
this._conf = new Configuration();
this._conf.once('load', this.onConfigLoad.bind(this));
// the server bind address information
// if listen() is never called this is null
this._addr = null;
// timestamp for the last save of the rdb file
this._lastsave = Date.now();
// server logger
this._logger = logger();
// periodic scheduler
this._scheduler = new Scheduler();
// collection of connections
this._conn = [];
// master pattern matcher
this._pattern = new Pattern();
// the store - this is where the data lives
this._store = new Store(this._conf);
// ensure we have a database at index 0
// the SELECT command will lazily create databases
// on demand
if(this._store.databases[0] === undefined) {
this._store.getDatabase(0, {pattern: this._pattern});
}
// server statistics
this._stats = new Stats(this);
// server information
this._info = new Info(this);
// global pubsub state
this._pubsub = new PubSub(this._stats);
// slow log storage
this._slowlog = new SlowLog(this._conf);
function onSave(time, diff, version, file) {
this._lastsave = Date.now();
this.log.notice('db saved to disk: %s seconds (%s)', time, file)
}
Persistence.on('save', onSave.bind(this));
process.on('debug', debug.bind(this));
process.on('tick', expire.bind(this));
} | javascript | {
"resource": ""
} |
q39175 | pause | train | function pause(timeout) {
var log = this._logger;
// keep list of matching clients
var clients = [];
this._conn.forEach(function(conn) {
if(!conn.client.isSlave()) {
clients.push(conn);
conn.pause();
}
})
function resume() {
log.notice('resume %s connections', clients.length);
clients.forEach(function(conn) {
conn.resume();
})
}
log.notice('pause %s connections for %sms', clients.length, timeout);
setTimeout(resume, timeout);
} | javascript | {
"resource": ""
} |
q39176 | expire | train | function expire() {
var dbs = this._store.databases, i;
for(i in dbs) {
dbs[i].delExpiredKeys();
}
} | javascript | {
"resource": ""
} |
q39177 | debug | train | function debug(rusage, memory) {
var dbs = this._store.databases
, i
, db
, size;
for(i in dbs) {
db = dbs[i];
size = db.dbsize();
if(size) {
this._logger.debug('DB %s: %s keys (%s volatile)', i, size, db.expiring);
}
}
this._logger.debug('%s clients connected, %s heap, %s rss bytes',
this.getLength(), memory.heapUsed, rusage.maxrss);
} | javascript | {
"resource": ""
} |
q39178 | onConfigLoad | train | function onConfigLoad() {
var file = this._conf.get(ConfigName.LOGFILE);
this._logger.level(this._conf.get(ConfigName.LOGLEVEL));
//console.dir('config loaded.');
if(file && !this._conf.get(ConfigName.DAEMONIZE)) {
this._logger.stream(file);
}
if(this._conf.isDefault()) {
this._logger.warning('no config file specified, using the default config');
}
// TODO: listen for log change events and toggle this
this._scheduler.startDebugLog();
this._scheduler.start(this._conf.get(ConfigName.HZ));
} | javascript | {
"resource": ""
} |
q39179 | Panopticon | train | function Panopticon(options) {
var isInstance = this instanceof Panopticon;
if (!isInstance) {
return new Panopticon(options);
}
EventEmitter.call(this);
this.id = instanceCount;
instanceCount += 1;
// First we sort out the methods and data which handle are local to this process.
genericSetup(this, options);
// If the process is a worker, we only need to send the master results then return. If the
// process is not a worker, it is either the master or stand alone. The master also handles
// the delivery of aggregated data.
if (cluster.isWorker) {
workerSetup(this);
} else {
masterSetup(this);
setupDelivery(this);
}
} | javascript | {
"resource": ""
} |
q39180 | train | function(index) {
var calls = this.all();
var call = calls[index];
return call ? call.object : null;
} | javascript | {
"resource": ""
} | |
q39181 | isBuildInType | train | function isBuildInType(type) {
return type === Function
|| type === String
|| type === Boolean
|| type === Number
|| type === RegExp
|| type === Object
|| type === Array
|| type === Date
} | javascript | {
"resource": ""
} |
q39182 | isCustomType | train | function isCustomType(type) {
return ria.__API.isClassConstructor(type)
|| ria.__API.isInterface(type)
|| ria.__API.isEnum(type)
|| ria.__API.isIdentifier(type)
|| ria.__API.isDelegate(type)
|| ria.__API.isSpecification(type);
//|| ArrayOfDescriptor.isArrayOfDescriptor(type)
;
} | javascript | {
"resource": ""
} |
q39183 | smartIndexOf | train | function smartIndexOf(array, test) {
var index = -1;
if (!array || !test) return index;
var length = array.length;
if (!length) return index;
while (++index < length) {
if (test(array[index], index, array)) return index;
}
return -1;
} | javascript | {
"resource": ""
} |
q39184 | indexById | train | function indexById(array, id) {
if (!array) return -1;
return smartIndexOf(array, function (obj) {
return obj.id === id;
});
} | javascript | {
"resource": ""
} |
q39185 | querySearch | train | function querySearch( query, single, embed, callback ) {
var embd = '';
if ( single ) {
for ( var key in embed ) {
if ( embed.hasOwnProperty(key) ) {
embd += '&embed[]=' + embed[key];
}
}
}
var url = apiBaseUrl + ( single ? endpoints['query']['single'] : endpoints['query']['multi'] ) + query + embd;
fetch(url, function(result) {
callback(result);
});
} | javascript | {
"resource": ""
} |
q39186 | idSearch | train | function idSearch( id, type, callback ) {
if ( ! endpoints['id'].hasOwnProperty(type) ) {
return callback(new Error('No valid type'));
}
var url = apiBaseUrl+endpoints['id'][type] + id;
fetch(url, function(result) {
callback(result);
});
} | javascript | {
"resource": ""
} |
q39187 | showSearch | train | function showSearch( id, embed, callback ) {
var embd = '';
for ( var key in embed ) {
if ( embed.hasOwnProperty(key) ) {
embd += ( 0 == key ? '?' : '&' ) + 'embed[]=' + embed[key];
}
}
var url = apiBaseUrl+endpoints['show'] + id + embd;
fetch(url, function(result) {
callback(result);
});
} | javascript | {
"resource": ""
} |
q39188 | showPeople | train | function showPeople( id, callback ) {
var url = apiBaseUrl+endpoints['people'] + id;
fetch(url, function(result) {
callback(result);
});
} | javascript | {
"resource": ""
} |
q39189 | scheduleSearch | train | function scheduleSearch( country, date, callback ) {
var url = apiBaseUrl+endpoints['schedule'].replace('$1', country).replace('$2', date);
fetch(url, function(result) {
callback(result);
});
} | javascript | {
"resource": ""
} |
q39190 | fetch | train | function fetch( url, callback ) {
request({ url: url, json: true }, function( err, resp, data ) {
if (err) {
return callback(err);
}
if ( 200 != resp.statusCode ) {
return callback(new Error(resp.statusMessage));
}
callback(data);
});
} | javascript | {
"resource": ""
} |
q39191 | train | function( packageFilename, options ) {
if( typeof options === 'undefined' ) options = {};
packageFilename = Path.resolve( packageFilename );
if( false == FS.existsSync() )
this.fatal( "Package file not found: \"" + packageFilename + "\"" );
var prjDir = Path.dirname( packageFilename );
this._prjDir = Path.resolve( prjDir );
this._libDir = Path.resolve( Path.join(__dirname, "../ker") );
this._tplDir = Path.resolve( Path.join(__dirname, "../tpl") );
this._srcDir = mkdir.call( this, prjDir, "src" );
this._docDir = mkdir.call( this, prjDir, "doc" );
this._tmpDir = mkdir.call( this, prjDir, "tmp" );
this._wwwDir = mkdir.call( this, prjDir, "www" );
} | javascript | {
"resource": ""
} | |
q39192 | addAnnotation | train | function addAnnotation(target, key, index, data) {
const classAnnotationsStore = container.get(AnnotationsServiceName.ClassAnnotationsStore);
if (index === undefined) {
// property
classAnnotationsStore.addPropertyAnnotation(target.constructor, key, Constraints, data);
}
else {
// method parameter
classAnnotationsStore.addMethodParameterAnnotation(target.constructor, key, index, Constraints, data);
}
} | javascript | {
"resource": ""
} |
q39193 | createStaticFileRegex | train | function createStaticFileRegex() {
var regex = '^\\/(',
staticViews = this.views.static;
// Get directories in public/
var files = getStaticDirs.call(this);
// Iterate over files and append to regex
for (var path, dir, re, i=0; i < files.length; i++) {
dir = files[i];
path = dir.replace(this.regex.startOrEndSlash, '').replace(this.regex.regExpChars, '\\$1');
if (i > 0) path = "|" + path;
regex += path;
}
// Finalize & create regex
regex += ')\\/?';
if (regex == '^\\/()\\/?') {
// No directories found in public/. Invalidate regex
this.staticFileRegex = /^$/;
} else {
// Directories found in public/
this.staticFileRegex = new RegExp(regex);
}
} | javascript | {
"resource": ""
} |
q39194 | getStaticDirs | train | function getStaticDirs() {
var files = fs.readdirSync(this.path + '/' + this.paths.public),
dirs = [];
for (var file, stat, i=0; i < files.length; i++) {
file = files[i];
stat = fs.lstatSync(this.path + '/' + this.paths.public + file);
if ( stat.isDirectory() ) dirs.push(file);
}
return dirs;
} | javascript | {
"resource": ""
} |
q39195 | sequenceMessages | train | function sequenceMessages(batch, context) {
const states = batch.states;
const messages = batch.messages;
if (messages.length < 2 || !context.streamProcessing.sequencingRequired) {
return messages;
}
// First prepare the messages for sequencing by normalizing all of the messages' sequence numbers
prepareMessagesForSequencing(messages, states, context);
const firstMessagesToProcess = [];
const sequencingPerKey = context.streamProcessing.sequencingPerKey;
const comparator = sequencingPerKey ?
(m1, m2) => compareSameKeyMessages(m1, m2, states, context):
(m1, m2) => compareAnyKeyMessages(m1, m2, states, context);
// Group all of the messages by the stringified versions of their keys (to avoid strict equal failures)
const messagesByKeyString = sequencingPerKey ?
groupBy(messages, msg => {
const msgState = states.get(msg);
const keys = msgState.keys;
return keys && keys.length > 0 ? msgState.key : '?';
}) : {'*': messages};
// Sort all of the messages that share the same keys by their sequence numbers and then link them to each other via
// their prevMessage and nextMessage state properties
const keyStrings = Object.getOwnPropertyNames(messagesByKeyString);
for (let i = 0; i < keyStrings.length; ++i) {
const keyString = keyStrings[i];
const msgs = messagesByKeyString[keyString];
if (context.traceEnabled && msgs.length > 1) context.trace(`BEFORE sorting (${keyString}): ${stringify(msgs.map(m => states.get(m).seqNo))}`);
msgs.sort(comparator);
if (context.traceEnabled) context.trace(` AFTER sorting (${keyString}): ${stringify(msgs.map(m => states.get(m).seqNo))}`);
let prevMessage = undefined;
let prevMessageState = undefined;
firstMessagesToProcess.push(msgs[0]);
for (let m = 0; m < msgs.length; ++m) {
const nextMessage = msgs[m];
const nextMessageState = states.get(nextMessage);
setPrevMessage(nextMessageState, prevMessage);
if (prevMessageState) {
setNextMessage(prevMessageState, nextMessage);
}
prevMessage = nextMessage;
prevMessageState = nextMessageState;
}
if (prevMessageState) {
setNextMessage(prevMessageState, undefined);
}
}
if (context.debugEnabled) {
const firstMessagesDetails = firstMessagesToProcess.map(m => `(${getMessageStateKeySeqNoId(states.get(m))})`).join(", ");
context.debug(`Finished sequencing messages - found ${firstMessagesToProcess.length} first message${firstMessagesToProcess.length !== 1 ? 's' : ''} to process out of ${messages.length} message${messages.length !== 1 ? 's' : ''} - first [${firstMessagesDetails}]`);
}
return firstMessagesToProcess;
} | javascript | {
"resource": ""
} |
q39196 | getAuthorization | train | function getAuthorization(user, auth) {
if (auth === AUTH_BASIC) {
return 'Basic ' + btoa(user.username + ':' + user.password);
} else if (auth === AUTH_TOKEN) {
return 'Token token=' + user.token;
}
} | javascript | {
"resource": ""
} |
q39197 | getParams | train | function getParams(user, auth, url, options, headers) {
return _.extend({
url: url,
headers: _.extend({
'User-Agent': user.userAgent,
'Authorization': getAuthorization(user, auth)
}, headers)
}, options);
} | javascript | {
"resource": ""
} |
q39198 | makeRequest | train | function makeRequest(user, auth, url, cb, options = {}, headers = {}) {
const params = getParams(user, auth, url, options, headers);
const promise = new Promise((resolve, reject) => {
request(params, (err, response, body) => {
if (!err && [200, 201, 204, 301].indexOf(response.statusCode) > -1) {
const result = _.isString(body) ? JSON.parse(body) : body;
return resolve([undefined, result]);
} else {
if (cb) {
return resolve([err || body]);
}
return reject([err || body]);
}
});
});
return handleCallback(promise, cb);
} | javascript | {
"resource": ""
} |
q39199 | extractHeaders | train | function extractHeaders(options) {
let headers = {};
if (options && options.headers) {
headers = options.headers;
delete options.headers;
}
return headers;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.