_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q37100
train
function(value) { if ([ ['%5B', '%5D'], ['%7B', '%7D'] ].some(function isencoded(tokens) { return value.startsWith(tokens[0]) && value.endsWith(tokens[1]); })) { try { value = JSON.parse(decodeURIComponent(value)); } catch (exception) { value = null; console.error(this + ': Bad JSON: ' + exception.message); } } return value; }
javascript
{ "resource": "" }
q37101
train
function(name, value) { var list, att, handler, trigger; var triggers = !gui.attributes.every(function(prefix) { if ((trigger = name.startsWith(prefix))) { this.spirit.config.configureone(name, value); } return !trigger; }, this); if (!triggers && (list = this._trackedtypes[name])) { att = new gui.Att(name, value); list.forEach(function(checks) { handler = checks[0]; handler.onatt(att); }, this); } }
javascript
{ "resource": "" }
q37102
train
function(elm) { var map = Object.create(null); this.all(elm).forEach(function(att) { map[att.name] = gui.Type.cast(att.value); }); return map; }
javascript
{ "resource": "" }
q37103
train
function(element, name) { if (this._supports) { return element.classList.contains(name); } else { var classnames = element.className.split(" "); return classnames.indexOf(name) > -1; } }
javascript
{ "resource": "" }
q37104
train
function(thing, prop) { var element = thing instanceof gui.Spirit ? thing.element : thing; var doc = element.ownerDocument, win = doc.defaultView; prop = this._standardcase(this.jsproperty(prop)); return win.getComputedStyle(element, null).getPropertyValue(prop); }
javascript
{ "resource": "" }
q37105
train
function(prop) { var vendors = this._vendors, fixt = prop; var element = document.documentElement; prop = String(prop); if (prop.startsWith("-beta-")) { vendors.every(function(vendor) { var test = this._camelcase(prop.replace("-beta-", vendor)); if (element.style[test] !== undefined) { fixt = test; return false; } return true; }, this); } else { fixt = this._camelcase(fixt); } return fixt; }
javascript
{ "resource": "" }
q37106
train
function(value) { var vendors = this._vendors; var element = document.documentElement; value = String(value); if (value && value.contains("-beta-")) { var parts = []; value.split(", ").forEach(function(part) { if ((part = part.trim()).startsWith("-beta-")) { vendors.every(function(vendor) { var test = this._camelcase(part.replace("-beta-", vendor)); if (element.style[test] !== undefined) { parts.push(part.replace("-beta-", vendor)); return false; } return true; }, this); } else { parts.push(part); } }, this); value = parts.join(","); } return value; }
javascript
{ "resource": "" }
q37107
train
function(string) { return string.replace(/[A-Z]/g, function(all, letter) { return "-" + string.charAt(letter).toLowerCase(); }); }
javascript
{ "resource": "" }
q37108
train
function(element) { var result = 0; var parent = element.parentNode; if (parent) { var node = parent.firstElementChild; while (node) { if (node === element) { break; } else { node = node.nextElementSibling; result++; } } } return result; }
javascript
{ "resource": "" }
q37109
train
function(node1, node2) { node1 = node1 instanceof gui.Spirit ? node1.element : node1; node2 = node2 instanceof gui.Spirit ? node2.element : node2; return node1.compareDocumentPosition(node2); }
javascript
{ "resource": "" }
q37110
train
function(node, othernode) { var check = Node.DOCUMENT_POSITION_CONTAINS + Node.DOCUMENT_POSITION_PRECEDING; return this.compare(othernode, node) === check; }
javascript
{ "resource": "" }
q37111
train
function(node) { node = node instanceof gui.Spirit ? node.element : node; return this.contains(node.ownerDocument, node); }
javascript
{ "resource": "" }
q37112
train
function(nodes) { var node, groups = []; function containedby(target, others) { return others.some(function(other) { return gui.DOMPlugin.contains(other, target); }); } while ((node = nodes.pop())) { if (!containedby(node, nodes)) { groups.push(node); } } return groups; }
javascript
{ "resource": "" }
q37113
train
function(node, selector, type) { var result = null; return this._qualify(node, selector)(function(node, selector) { if (type) { result = this.qall(node, selector, type)[0] || null; } else { try { result = node.querySelector(selector); } catch (exception) { console.error("Dysfunctional selector: " + selector); throw exception; } } return result; }); }
javascript
{ "resource": "" }
q37114
train
function(type) { var result = null, spirit = null, el = this.spirit.element; if (type) { while ((el = el.nextElementSibling) !== null) { spirit = el.spirit; if (spirit !== null && spirit instanceof type) { result = spirit; break; } } } else { result = el.nextElementSibling; } return result; }
javascript
{ "resource": "" }
q37115
train
function(type) { var result = null, spirit = null, el = this.spirit.element; if (type) { while ((el = el.previousElementSibling) !== null) { spirit = el.spirit; if (spirit !== null && spirit instanceof type) { result = spirit; break; } } } else { result = el.previousElementSibling; } return result; }
javascript
{ "resource": "" }
q37116
train
function(type) { var result = null, spirit = null, el = this.spirit.element.lastElementChild; if (type) { while (result === null && el !== null) { spirit = el.spirit; if (spirit !== null && spirit instanceof type) { result = spirit; } el = el.previoustElementSibling; } } else { result = el; } return result; }
javascript
{ "resource": "" }
q37117
train
function(type) { var result = this.spirit.element.parentNode; if (type) { var spirit = result.spirit; if (spirit && spirit instanceof type) { result = spirit; } else { result = null; } } return result; }
javascript
{ "resource": "" }
q37118
train
function(type) { var result = this.spirit.element.firstElementChild; if (type) { result = this.children(type)[0] || null; } return result; }
javascript
{ "resource": "" }
q37119
train
function(type) { var result = []; var crawler = new gui.Crawler(); if (type) { crawler.ascend(this.element, { handleSpirit: function(spirit) { if (spirit instanceof type) { result.push(spirit); } } }); } else { crawler.ascend(this.element, { handleElement: function(el) { result.push(el); } }); } return result; }
javascript
{ "resource": "" }
q37120
train
function(type) { var result = []; var me = this.spirit.element; new gui.Crawler().descend(me, { handleElement: function(element) { if (!type && element !== me) { result.push(element); } }, handleSpirit: function(spirit) { if (type && spirit instanceof type) { if (spirit.element !== me) { result.push(spirit); } } } }); return result; }
javascript
{ "resource": "" }
q37121
train
function(type) { var result = [], spirit, el = this.spirit.element; while ((el = el.nextElementSibling)) { if (type && (spirit = el.spirit)) { if (spirit instanceof type) { result.push(spirit); } } else { result.push(el); } } return result; }
javascript
{ "resource": "" }
q37122
train
function(type) { var result = [], spirit, el = this.spirit.element; while ((el = el.previousElementSibling)) { if (type && (spirit = el.spirit)) { if (spirit instanceof type) { result.push(spirit); } } else { result.push(el); } } return result; }
javascript
{ "resource": "" }
q37123
train
function(things) { var els = things, element = this.spirit.element; els.forEach(function(el) { element.appendChild(el); maybespiritualize(el); }); }
javascript
{ "resource": "" }
q37124
train
function(things) { var els = things, element = this.spirit.element, first = element.firstChild; els.reverse().forEach(function(el) { element.insertBefore(el, first); maybespiritualize(el); }); }
javascript
{ "resource": "" }
q37125
train
function(things) { var els = things, target = this.spirit.element, parent = target.parentNode; els.reverse().forEach(function(el) { parent.insertBefore(el, target); maybespiritualize(el); }); }
javascript
{ "resource": "" }
q37126
train
function(type, checks) { var target = checks[0]; var handler = checks[1]; var capture = checks[2]; this.remove(type, target, handler, capture); }
javascript
{ "resource": "" }
q37127
train
function(arg) { return gui.TrackerPlugin.prototype._breakdown.call(this, arg).map(function(type) { return type === 'transitionend' ? this._transitionend() : type; }, this); }
javascript
{ "resource": "" }
q37128
train
function() { if (true || gui.Client.has3D) { this.spirit.css.set("-beta-transform", ""); } else { this.spirit.css.left = ""; this.spirit.css.top = ""; } }
javascript
{ "resource": "" }
q37129
train
function() { var pos = this._pos; var set = [pos.x, pos.y, pos.z].map(Math.round); if (true || gui.Client.has3D) { this.spirit.css.set("-beta-transform", "translate3d(" + set.join("px,") + "px)" ); } else { this.spirit.css.left = set [0]; this.spirit.css.top = set [1]; } }
javascript
{ "resource": "" }
q37130
train
function(elm, doc, win, sig) { // TODO: get rid of all these! this.element = elm; this.document = doc; this.window = win; this.$contextid = sig; gui.Spirit.$construct(this); }
javascript
{ "resource": "" }
q37131
train
function() { var Plugin, plugins = this.constructor.$plugins; this.life = new gui.LifePlugin(this); this.config = new gui.ConfigPlugin(this); Object.keys(plugins).filter(function(prefix) { return prefix !== "life" && prefix !== "config"; }).sort().forEach(function(prefix) { Plugin = plugins[prefix]; if ((this.life.plugins[prefix] = !Plugin.lazy)) { gui.Plugin.$assign(this, prefix, new Plugin(this)); } else { gui.Plugin.$prepare(this, prefix, Plugin); } }, this); }
javascript
{ "resource": "" }
q37132
train
function(constructing) { if (gui.debug) { var val, elm = this.element; var fix = gui.attributes[0]; // by default using `gui` if (constructing) { if (gui.attributes.every(function(f) { return !elm.hasAttribute(f); })) { val = "[" + this.constructor.$classname + "]"; elm.setAttribute(fix, val); } } else { val = elm.getAttribute(fix); if (val && val.startsWith("[")) { elm.removeAttribute(fix); } } } }
javascript
{ "resource": "" }
q37133
train
function() { var C = gui.Class.extend.apply(this, arguments); C.$plugins = gui.Object.copy(this.$plugins); return C; /* * Mutating plugins deprecated! * var args = [], def, br = gui.Class.breakdown(arguments); ["name", "protos", "recurring", "statics"].forEach(function(key) { if ((def = br[key])) { args.push(def); } }, this); var C = gui.Class.extend.apply(this, args); C.$plugins = gui.Object.copy(this.$plugins); var b = gui.Class.breakdown(arguments); gui.Object.each(C.$plugins, function(prefix, plugin) { var def = b.protos[prefix]; switch (gui.Type.of(def)) { case "object": var mutant = plugin.extend(def); C.plugin(prefix, mutant, true); break; case "undefined": break; default: throw new TypeError( C + ": Bad definition for " + prefix + ': ' + def ); } }, this); return C; */ }
javascript
{ "resource": "" }
q37134
train
function(spirit) { spirit.config.configureall(); spirit.life.configured = true; spirit.onconfigure(); spirit.life.dispatch(gui.LIFE_CONFIGURE); }
javascript
{ "resource": "" }
q37135
train
function(spirit) { spirit.window.gui.inside(spirit); spirit.life.entered = true; spirit.onenter(); spirit.life.dispatch(gui.LIFE_ENTER); }
javascript
{ "resource": "" }
q37136
train
function(spirit) { spirit.window.gui.inside(spirit); spirit.life.attached = true; spirit.onattach(); spirit.life.dispatch(gui.LIFE_ATTACH); }
javascript
{ "resource": "" }
q37137
train
function(spirit) { spirit.life.ready = true; spirit.onready(); spirit.life.dispatch(gui.LIFE_READY); }
javascript
{ "resource": "" }
q37138
train
function(spirit) { spirit.window.gui.outside(spirit); spirit.life.detached = true; spirit.life.visible = false; spirit.life.dispatch(gui.LIFE_DETACH); spirit.life.dispatch(gui.LIFE_INVISIBLE); spirit.ondetach(); }
javascript
{ "resource": "" }
q37139
train
function(spirit) { spirit.life.exited = true; spirit.life.dispatch(gui.LIFE_EXIT); spirit.onexit(); }
javascript
{ "resource": "" }
q37140
train
function(spirit) { spirit.life.async = true; spirit.onasync(); // TODO: life cycle stuff goes here spirit.life.dispatch(gui.LIFE_ASYNC); }
javascript
{ "resource": "" }
q37141
train
function(spirit) { spirit.$debug(false); spirit.life.destructed = true; spirit.life.dispatch(gui.LIFE_DESTRUCT); spirit.ondestruct(); }
javascript
{ "resource": "" }
q37142
train
function(a) { gui.Spirit.prototype.onaction.call(this, a); this.action.$handleownaction = false; switch (a.type) { case gui.$ACTION_XFRAME_VISIBILITY: this._waiting = false; if (gui.hasModule("gui-layout@wunderbyte.com")) { // TODO: - fix if (a.data === true) { this.visibility.on(); } else { this.visibility.off(); } } a.consume(); break; } }
javascript
{ "resource": "" }
q37143
train
function() { gui.Spirit.prototype.onenter.call(this); this.event.add('load'); this.action.addGlobal([ // in order of appearance gui.ACTION_DOC_ONDOMCONTENT, gui.ACTION_DOC_ONLOAD, gui.ACTION_DOC_ONHASH, gui.ACTION_DOC_ONSPIRITUALIZED, gui.ACTION_DOC_UNLOAD ]); if (this.fit) { this.css.height = 0; } var src = this.element.src; if (src && src !== gui.IframeSpirit.SRC_DEFAULT) { if (!src.startsWith("blob:")) { // wrong... this._setupsrc(src); } } }
javascript
{ "resource": "" }
q37144
train
function(a) { gui.Spirit.prototype.onaction.call(this, a); this.action.$handleownaction = false; var base; switch (a.type) { case gui.ACTION_DOC_ONDOMCONTENT: this.contentLocation = new gui.URL(document, a.data); this.life.dispatch(gui.LIFE_IFRAME_DOMCONTENT); this.action.remove(a.type); a.consume(); break; case gui.ACTION_DOC_ONLOAD: this.contentLocation = new gui.URL(document, a.data); this.life.dispatch(gui.LIFE_IFRAME_ONLOAD); this.action.remove(a.type); a.consume(); break; case gui.ACTION_DOC_ONHASH: base = this.contentLocation.href.split("#")[0]; this.contentLocation = new gui.URL(document, base + a.data); this.life.dispatch(gui.LIFE_IFRAME_ONHASH); a.consume(); break; case gui.ACTION_DOC_ONSPIRITUALIZED: this._onspiritualized(); this.life.dispatch(gui.LIFE_IFRAME_SPIRITUALIZED); this.action.remove(a.type); a.consume(); break; case gui.ACTION_DOC_UNLOAD: this._onunload(); this.life.dispatch(gui.LIFE_IFRAME_UNLOAD); this.action.add([ gui.ACTION_DOC_ONCONSTRUCT, gui.ACTION_DOC_ONDOMCONTENT, gui.ACTION_DOC_ONLOAD, gui.ACTION_DOC_ONSPIRITUALIZED ]); a.consume(); break; } }
javascript
{ "resource": "" }
q37145
train
function(url, src) { if (src) { this._setupsrc(src); } if (url) { this.element.src = url; } return this.contentLocation.href; }
javascript
{ "resource": "" }
q37146
train
function() { var proto = Element.prototype; if (gui.Type.isDefined(proto.spirit)) { throw new Error("Spiritual loaded twice?"); } else { proto.spirit = null; // defineProperty fails in iOS5 } }
javascript
{ "resource": "" }
q37147
train
function() { var Elm = gui.Client.isExplorer ? HTMLElement : Element; this._change(Elm.prototype, gui.DOMCombos); }
javascript
{ "resource": "" }
q37148
train
function(proto, name, combo, root) { var getter = root.__lookupGetter__(name); var setter = root.__lookupSetter__(name); if (getter) { // firefox 20 needs a getter for this to work proto.__defineGetter__(name, function() { return getter.apply(this, arguments); }); proto.__defineSetter__(name, combo(function() { setter.apply(this, arguments); })); } }
javascript
{ "resource": "" }
q37149
train
function() { if (gui.Client.hasMutations) { if (!this._observer) { var Observer = this._mutationobserver(); this._observer = new Observer(function(mutations) { mutations.forEach(function(mutation) { gui.DOMObserver._handleMutation(mutation); }); }); } this._connect(true); this.observes = true; } else { throw new Error('MutationObserver no such thing'); } }
javascript
{ "resource": "" }
q37150
train
function(action, thisp) { var res; if (this.observes) { if (++this._suspend === 1) { this._connect(false); } } if (gui.Type.isFunction(action)) { res = action.call(thisp); } if (this.observes) { this.resume(); } return res; }
javascript
{ "resource": "" }
q37151
train
function(connect) { var obs = this._observer; if (obs) { if (connect) { obs.observe(document, { childList: true, subtree: true }); } else { obs.disconnect(); } } }
javascript
{ "resource": "" }
q37152
train
function(mutation) { Array.forEach(mutation.removedNodes, function(node) { if (node.nodeType === Node.ELEMENT_NODE) { gui.materialize(node); } }, this); Array.forEach(mutation.addedNodes, function(node) { if (node.nodeType === Node.ELEMENT_NODE) { gui.spiritualize(node); } }, this); }
javascript
{ "resource": "" }
q37153
train
function(elm, Spirit) { var doc = elm.ownerDocument; var win = doc.defaultView; var sig = win.gui.$contextid; if (elm.spirit) { throw new Error( "Cannot repossess element with spirit " + elm.spirit + " (exorcise first)" ); } else if (!gui.debug || gui.Type.isSpiritConstructor(Spirit)) { elm.spirit = new Spirit(elm, doc, win, sig); } else { throw new Error( "Not a spirit constructor (" + gui.Type.of(Spirit) + ")" ); } return elm.spirit; }
javascript
{ "resource": "" }
q37154
train
function(operation, thisp) { this._suspended = true; var res = operation.call(thisp); this._suspended = false; return res; }
javascript
{ "resource": "" }
q37155
train
function(node, skip, id) { var list = []; new gui.Crawler(id).descend(node, { handleSpirit: function(spirit) { if (skip && spirit.element === node) { // nothing } else if (!spirit.life.destructed) { list.push(spirit); } } }); return list; }
javascript
{ "resource": "" }
q37156
train
function(node, skip, one) { node = node instanceof gui.Spirit ? node.element : node; node = node.nodeType === Node.DOCUMENT_NODE ? node.documentElement : node; if (this._handles(node)) { this._spiritualize(node, skip, one); } }
javascript
{ "resource": "" }
q37157
train
function(element, skip, one) { skip = false; // until DOM setters can finally replace Mutation Observers... var att = 'gui-spiritualizing'; if (!element.hasAttribute(att)) { var spirit, spirits = []; // classname = gui.CLASS_NOSPIRITS element.setAttribute(att, 'true'); new gui.Crawler(gui.CRAWLER_SPIRITUALIZE).descend(element, { handleElement: function(elm) { if (elm !== element && elm.hasAttribute(att)) { return one ? gui.Crawler.STOP : gui.Crawler.SKIP_CHILDREN; } else { if (!skip || elm !== element) { spirit = elm.spirit; if (!spirit) { spirit = gui.Guide._evaluate(elm); } if (spirit) { if (!spirit.life.attached) { spirits.push(spirit); } } } if (one) { return gui.Crawler.STOP; } else if (!elm.childElementCount) { // || gui.CSSPlugin.contains(elm, classname) return gui.Crawler.SKIP_CHILDREN; } else { // TODO: interface for this kind of stuff! switch (elm.localName) { case "pre": case "code": return gui.Crawler.SKIP_CHILDREN; } } } return gui.Crawler.CONTINUE; } }); element.removeAttribute(att); this._sequence(spirits); } }
javascript
{ "resource": "" }
q37158
train
function(node, skip, one, force) { node = node instanceof gui.Spirit ? node.element : node; node = node.nodeType === Node.DOCUMENT_NODE ? node.documentElement : node; if (force || this._handles(node)) { node.setAttribute('gui-matarializing', 'true'); this._materialize(node, skip, one); node.removeAttribute('gui-matarializing'); } }
javascript
{ "resource": "" }
q37159
train
function(spirits) { if (gui.hasModule("gui-layout@wunderbyte.com")) { gui.DOMPlugin.group(spirits).forEach(function(spirit) { gui.VisibilityPlugin.$init(spirit); }, this); } }
javascript
{ "resource": "" }
q37160
train
function(e) { /* * TODO: Move this code into {gui.EventPlugin} */ if (e.type === 'webkitTransitionEnd') { e = { type: 'transitionend', target: e.target, propertyName: e.propertyName, elapsedTime: e.elapsedTime, pseudoElement: e.pseudoElement }; } this.onevent(e); }
javascript
{ "resource": "" }
q37161
train
function(key) { gui.Spirit.prototype.onkey.call(this, key); console.log(key.type); var map = this._map; map[key.type] = key.down; if (Object.keys(map).every(function(type) { //console.log ( type + ": " + map [ type ]); return map[type] === true; })) { console.log("fis!"); } }
javascript
{ "resource": "" }
q37162
train
function() { var key = this.att.get("key"); if (key) { key.split(" ").forEach(function(token) { token = token.trim(); this.key.addGlobal(token); this._map[token] = false; }, this); } }
javascript
{ "resource": "" }
q37163
train
function(context) { this._keymap = Object.create(null); ["keydown", "keypress", "keyup"].forEach(function(type) { context.document.addEventListener(type, this, false); }, this); }
javascript
{ "resource": "" }
q37164
train
function(e) { var n = e.keyCode, c = this._keymap[n], b = gui.BROADCAST_KEYEVENT; var id = e.currentTarget.defaultView.gui.$contextid; /* // TODO: THIS! if ( e.ctrlKey && gui.Key.$key [ e.keyCode ] !== "Control" ) { e.preventDefault (); } */ switch (e.type) { case "keydown": if (c === undefined) { this._keycode = n; this._keymap[n] = null; this._keymap[n] = String.fromCharCode(e.which).toLowerCase(); gui.Tick.next(function() { c = this._keymap[n]; this._broadcast(true, null, c, n, id); this._keycode = null; }, this); } break; case "keypress": if (this._keycode) { c = this._keychar(e.keyCode, e.charCode, e.which); this._keymap[this._keycode] = c; } break; case "keyup": if (c !== undefined) { this._broadcast(false, null, c, n, id); delete this._keymap[n]; } break; } }
javascript
{ "resource": "" }
q37165
train
function(e) { gui.Key.ctrlDown = e.ctrlKey; gui.Key.shiftDown = e.shiftKey; gui.Key.altDown = e.altKey; gui.Key.metaDown = e.metaKey; }
javascript
{ "resource": "" }
q37166
record
train
function record(f) { // TODO document why @refreshing exists // guards against recursively evaluating this recorded // function (@body or an async body) when calling `.get()` if (!_this10.refreshing) { var res = void 0; _this10.disconnect(); if (recorded) { throw new Error("this refresh has already recorded its dependencies"); } _this10.refreshing = true; recorded = true; try { res = recorder.record(_this10, function () { return f.call(env); }); } finally { _this10.refreshing = false; } if (isSynchronous) { realDone(syncResult); } return res; } }
javascript
{ "resource": "" }
q37167
createAgentRequest
train
function createAgentRequest ( config, vault, params ) { if (!vault || !config || !params) throw new Error('"config", "vault", "params" are required) ') if (!params.returnURL && !params.callbackURL) throw new Error('params must have either "returnURL" or "callbackURL"') config = _init( config, vault ) var credentials = vault[ config.ix ].latest var details = { header: { typ: 'JWS' , alg: ALG_REQUEST } , payload: { 'iss': config.appID , 'aud': config.ix , 'iat': jwt.iat() , 'request.a2p3.org': { 'resources': params.resources || [] , 'auth': config.auth , 'ix': 'a2p3.net' } } , credentials: credentials } if ( params.returnURL ) details.payload['request.a2p3.org'].returnURL = params.returnURL else if ( params.callbackURL ) details.payload['request.a2p3.org'].callbackURL = params.callbackURL this.agentRequest = jwt.jws( details ) return this.agentRequest }
javascript
{ "resource": "" }
q37168
train
function(func, resolves = false){ if(typeof resolves !== 'boolean' && typeof resolves !== 'number' && resolves != 'all'){ throw new Error('Invalid value submitted for \'resolves\' argument.') } return function(){ return new Promise((resolve, reject)=>{ var params = [...arguments, function(...args){ //check for error hooks var error = false; for(let arg of args){ if(arg instanceof Error){ error = arg; break; } } if(error){ reject(error) }else{ switch(resolves){ case false: resolve(arguments.length == 1 ? arguments[0] : arguments[1]) break; case true: resolve(true) break; case 'all': resolve(args) break; default: resolve(args[resolve]) } } }] func.apply(null, params) }) } }
javascript
{ "resource": "" }
q37169
train
function(opts) { opts = opts || {}; this._context = opts.context; this._routeContext = opts.routeContext; this.router = opts.router || router.df; this.routerType = opts.routerType; this.rpcDebugLog = opts.rpcDebugLog; if (this._context) { opts.clientId = this._context.serverId; } this.opts = opts; this.proxies = {}; this._station = createStation(opts); this.state = STATE_INITED; }
javascript
{ "resource": "" }
q37170
train
function(client, serverType, msg, routeParam, cb) { if (!!client.routerType) { let method; switch (client.routerType) { case constants.SCHEDULE.ROUNDROBIN: method = router.rr; break; case constants.SCHEDULE.WEIGHT_ROUNDROBIN: method = router.wrr; break; case constants.SCHEDULE.LEAST_ACTIVE: method = router.la; break; case constants.SCHEDULE.CONSISTENT_HASH: method = router.ch; break; default: method = router.rd; break; } method.call(null, client, serverType, msg, function(err, serverId) { cb(err, serverId); }); } else { let route, target; if (typeof client.router === 'function') { route = client.router; target = null; } else if (typeof client.router.route === 'function') { route = client.router.route; target = client.router; } else { logger.error('[omelo-rpc] invalid route function.'); return; } route.call(target, routeParam, msg, client._routeContext, function(err, serverId) { cb(err, serverId); }); } }
javascript
{ "resource": "" }
q37171
train
function(client, msg, serverType, serverId, cb) { if (typeof serverId !== 'string') { logger.error('[omelo-rpc] serverId is not a string : %s', serverId); return; } if (serverId === '*') { let servers = client._routeContext.getServersByType(serverType); if (!servers) { logger.error('[omelo-rpc] serverType %s servers not exist', serverType); return; } async.each(servers, function(server, next) { let serverId = server['id']; client.rpcInvoke(serverId, msg, function(err) { next(err); }); }, cb); } else { client.rpcInvoke(serverId, msg, cb); } }
javascript
{ "resource": "" }
q37172
getValuesMapsFromOutcomes
train
function getValuesMapsFromOutcomes(outcomes) { var dataMap = {}; var noteMap = {}; // add each outcome to a set outcomes.forEach(function outcomeIterator(outcome) { var lowerCaseLabel = updateLabels(outcome.outcome); dataMap[lowerCaseLabel] = outcome.value; noteMap[lowerCaseLabel] = outcome.notes; }); return { data: dataMap, notes: noteMap }; }
javascript
{ "resource": "" }
q37173
updateLabels
train
function updateLabels(potentialLabel) { var lowerCaseLabel = potentialLabel.toLowerCase(); if (!labelSet.hasOwnProperty(lowerCaseLabel)) { labels.push(potentialLabel); // now value is in our set labelSet[lowerCaseLabel] = true; } return lowerCaseLabel; }
javascript
{ "resource": "" }
q37174
getExtractedDataAndTooltipNotes
train
function getExtractedDataAndTooltipNotes(valuesMap) { // go over currently added labels var data = []; var notes = []; labels.forEach(function labelIterator(label) { data.push(getExtractedDataValue(valuesMap.data[label.toLowerCase()])); notes.push(getExtractedNoteValue(valuesMap.notes[label.toLowerCase()])); }); return { data: data, notes: notes }; }
javascript
{ "resource": "" }
q37175
Scanner
train
function Scanner(target, cursor, pattern, count, map, stringify) { this.target = target; this.cursor = cursor; this.pattern = pattern; this.count = count || 10; this.map = map; this.stringify = stringify; // clamp the count this.count = Math.max(this.count, 10); this.count = Math.min(this.count, 1000); }
javascript
{ "resource": "" }
q37176
scan
train
function scan(req, res) { var records = [] , position , i , key , inc , map = this.map , len = this.cursor + this.count; for(i = this.cursor; i < len;i++) { if(i === this.target.length) { position = 0; break; } key = '' + this.target[i]; inc = !this.pattern || (this.pattern && this.pattern.test(key)); if(inc) { records.push(key); if(map) records.push(this.stringify ? '' + map[key] : map[key]); } position = i + 1; } res.send(null, [position, records]); }
javascript
{ "resource": "" }
q37177
train
function(message) { if (this.sendData % 200 == 0){ console.log("Kinect data being sent from kinect"); console.log(message); } this.sendData = this.sendData +1; if (true) { //Set the kinect data to the raw values from the kinect for(var key in message){ KinectState[key] = message[key]; } if (this.currentState == 1){ //We don't have any person data yet. }else if (this.currentState == 2){ var h = KinectState.head; User.updateObj(User.head,h.x,h.y,h.z, h.xmm, h.ymm); } else if (this.currentState == 3) { var h = KinectState.head; var l = KinectState.leftHand; var r = KinectState.rightHand; var el = KinectState.leftElbow; var er = KinectState.rightElbow; User.updateObj(User.head,h.x,h.y,h.z, h.xmm, h.ymm); User.updateObj(User.hands.left, l.x,l.y,l.z, l.xmm, l.ymm); User.updateObj(User.hands.right, r.x,r.y,r.z, r.xmm, r.ymm); User.updateObj(User.elbows.left, el.x, el.y, el.z, el.xmm, el.ymm); User.updateObj(User.elbows.right, er.x, er.y, er.z, er.xmm, er.ymm); } //Tell the app the state has changed this.setState(KinectState.phase); } }
javascript
{ "resource": "" }
q37178
lex
train
function lex(phrase) { var words = phrase && typeof(phrase) === 'string' ? lexer.lex(phrase) : {status:"Invalid phrase parameter"}; logger.log('verbose', '%s|lex|phrase=%s|words=%j', meta.module, phrase, words, meta); return words; }
javascript
{ "resource": "" }
q37179
tag
train
function tag(words) { var taggedWords = (words && typeof(words) === 'string') ? tagger.tag(lexer.lex(words)) : (words && typeof(words) === 'object') ? tagger.tag(words) : {status:"Invalid words parameter"}; logger.log('verbose', '%s|tag|words=%j|tags=%j', meta.module, words, taggedWords, meta); return taggedWords; }
javascript
{ "resource": "" }
q37180
Sort_nat
train
function Sort_nat(source, // @arg StringArray - source. ["abc100", "abc1", "abc10"] ignoreCase) { // @arg Boolean = false - true is case-insensitive // @ret StringArray - sorted array. ["abc1", "abc10", "abc100"] // @desc nat sort //{@dev _if(!Array.isArray(source), "Sort.nat(source)"); _if(ignoreCase !== undefined && typeof ignoreCase !== "boolean", "Sort.nat(,ignoreCase)"); //}@dev function toNumberArray(str) { return str.split(/(\d+)/).reduce(function(prev, next) { if (next !== "") { if (isNaN(next)) { next.split("").forEach(function(v) { prev.push( v.charCodeAt(0) ); }); } else { prev.push(+next); } } return prev; }, []); } var cache = {}; // { keyword: [number, ...], ... } return source.sort(function(a, b) { var aa, bb; if (a in cache) { aa = cache[a]; } else { cache[a] = aa = toNumberArray( ignoreCase ? a.toLowerCase() : a ); } if (b in cache) { bb = cache[b]; } else { cache[b] = bb = toNumberArray( ignoreCase ? b.toLowerCase() : b ); } var x = 0, y = 0, i = 0, iz = aa.length; for (; i < iz; ++i) { x = aa[i] || 0; y = bb[i] || 0; if (x !== y) { return x - y; } } return a.length - b.length; }); }
javascript
{ "resource": "" }
q37181
lookForExternalDependenciesRES
train
function lookForExternalDependenciesRES( _def, resources, depFile ) { if ( !_def ) return; try { const def = convertExternalDependencyDefinition( _def ); for ( const dep of Object.keys( def ) ) { if ( def[ dep ] === "" ) { // `res: { "bob/foo.png": "" }` is equivalent to // `res: { "bob/foo.png": "bob/foo.png" }` def[ dep ] = dep; } const srcDep = Project.srcOrLibPath( `mod/${dep}` ) || Project.srcOrLibPath( dep ); if ( !srcDep ) { Fatal.fire( `Unable to find dependency file "${dep}" nor "mod/${dep}"!`, depFile.getAbsoluteFilePath() ); } resources[ srcDep ] = Project.wwwPath( def[ dep ] ); } } catch ( ex ) { Fatal.fire( `Unable to parse RES dependencies: ${JSON.stringify(_def)}!\n${ex}`, depFile ); } }
javascript
{ "resource": "" }
q37182
lookForExternalDependenciesJS
train
function lookForExternalDependenciesJS( _def, javascriptSources ) { if ( !_def ) return; try { const def = convertExternalDependencyDefinition( _def ); Object.keys( def ).forEach( function ( js ) { const filename = `mod/${js}`, src = new Source( Project, filename ), code = src.read(); pushUnique( javascriptSources, code ); } ); } catch ( ex ) { Fatal.fire( `Unable to parse JS dependencies: ${JSON.stringify(_def)}!\n${ex}`, javascriptSources ); } }
javascript
{ "resource": "" }
q37183
pushUnique
train
function pushUnique( arr, item ) { if ( arr.indexOf( item ) > -1 ) return false; arr.push( item ); return true; }
javascript
{ "resource": "" }
q37184
addFilePrefix
train
function addFilePrefix( path, prefix ) { if ( typeof prefix === 'undefined' ) prefix = '@'; var separatorPosition = path.lastIndexOf( '/' ); if ( separatorPosition < 0 ) { // Let's try with Windows separators. separatorPosition = path.lastIndexOf( '\\' ); } var filenameStart = separatorPosition > -1 ? separatorPosition + 1 : 0; var result = path.substr( 0, filenameStart ) + prefix + path.substr( filenameStart ); return result.replace( /\\/g, '/' ); }
javascript
{ "resource": "" }
q37185
addDescriptionToHead
train
function addDescriptionToHead( head, options ) { if ( !options || !options.config || typeof options.config.description !== 'string' ) { return false; } if ( !Array.isArray( head.children ) ) { head.children = []; } for ( let i = 0; i < head.children.length; i++ ) { const child = head.children[ i ]; if ( child.type !== Tree.ELEMENT ) continue; if ( child.name.toLowerCase() != 'meta' ) continue; if ( !child.attribs ) continue; if ( typeof child.attribs.name !== 'string' ) continue; if ( child.attribs.name.toLowerCase() === 'description' ) { // There is already a description. We don't add a new one. return false; } } head.children.push( { type: Tree.ELEMENT, name: 'meta', attribs: { name: 'description', content: options.config.description } } ); return true; }
javascript
{ "resource": "" }
q37186
getEntryImports
train
function getEntryImports(dir, content, arr = []) { $C(content.split(eol)).forEach((line) => { if (!hasImport.test(line)) { return; } const url = RegExp.$2, nodeModule = isNodeModule(url); if (nodeModule && entriesDir.test(url) || insideEntry.test(url)) { const d = nodeModule ? lib : dir; let f = path.join(d, `${url}.js`); if (!fs.existsSync(f)) { f = path.join(d, url, 'index.js'); } getEntryImports(path.dirname(f), fs.readFileSync(f, 'utf-8'), arr); } else { arr.push(nodeModule ? url : path.join(dir, url)); } }); return arr; }
javascript
{ "resource": "" }
q37187
getEntryParents
train
function getEntryParents(content) { const parents = new Set(), clrfx = /\.\//; $C(content.split(eol)).forEach((line) => { if (!hasImport.test(line)) { return; } const url = RegExp.$2; if (isNodeModule(url) && entriesDir.test(url) || insideEntry.test(url)) { parents.add(url.replace(clrfx, '')); } }); return parents; }
javascript
{ "resource": "" }
q37188
getEntryRuntimeDependencies
train
async function getEntryRuntimeDependencies(dir, content, {cache} = {}) { const deps = { runtime: new Map(), parents: new Map(), libs: new Set() }; const runtime = new Set(); await $C(getEntryImports(dir, content)).async.forEach(async (el) => { const name = path.basename(el, path.extname(el)), block = cache ? cache.get(name) : await Block.get(name); if (!blockName(name) || !block) { deps.runtime.set(el, el); return; } const blockDeps = await block.getRuntimeDependencies({cache}); $C(blockDeps.runtime).forEach((obj, block) => { if (!blockDeps.parents.has(block)) { runtime.add(block); } }); deps.runtime = new Map([...deps.runtime.entries(), ...blockDeps.runtime.entries()]); deps.parents = new Map( $C([...deps.parents.entries(), ...blockDeps.parents.entries()]) .filter(([block]) => !runtime.has(block)) .map() ); deps.libs = new Set([...deps.libs, ...blockDeps.libs]); }); return deps; }
javascript
{ "resource": "" }
q37189
getBuildConfig
train
async function getBuildConfig() { const entries = await $C(vinyl.src(path.join(entry(), '*.js'), {read: false})) .async .to({}) .reduce((res, el) => { const src = el.path, name = path.basename(src, '.js'); let source; function getSource() { source = source || fs.readFileSync(src, 'utf-8'); return source; } res[name] = { path: src, get source() { return getSource(); }, get parent() { return $C(getEntryParents(getSource())).one.get(); }, get parents() { return getEntryParents(getSource()); }, getRuntimeDependencies({cache} = {}) { return getEntryRuntimeDependencies(path.dirname(src), getSource(), {cache}); } }; return res; }); function factory(entries) { function filter(cb) { return factory($C(entries).filter(cb).map()); } return { entries, filter, getUnionEntryPoints({cache} = {}) { return getUnionEntryPoints(entries, {cache}); } }; } return factory(entries); }
javascript
{ "resource": "" }
q37190
train
function (name, hash) { this.actionQueue.push(this.webdriverClient.windowHandles.bind(this.webdriverClient)); this.actionQueue.push(function (result) { var deferred = Q.defer(); if (name === null) { deferred.resolve(JSON.parse(result).value[0]); } deferred.resolve(name); return deferred.promise; }); this.actionQueue.push(this.webdriverClient.changeWindow.bind(this.webdriverClient)); this.actionQueue.push(this._windowCb.bind(this, name, hash)); return this; }
javascript
{ "resource": "" }
q37191
train
function (dimensions, hash) { this.actionQueue.push(this.webdriverClient.setWindowSize.bind(this.webdriverClient, dimensions.width, dimensions.height)); this.actionQueue.push(this._resizeCb.bind(this, dimensions, hash)); return this; }
javascript
{ "resource": "" }
q37192
train
function (hash) { this.actionQueue.push(this.webdriverClient.maximize.bind(this.webdriverClient)); this.actionQueue.push(this._maximizeCb.bind(this, hash)); return this; }
javascript
{ "resource": "" }
q37193
_set_url_from_token
train
function _set_url_from_token(in_token){ var url = null; if( in_token ){ url = barista_location + '/api/' + namespace + '/m3BatchPrivileged'; }else{ url = barista_location + '/api/' + namespace + '/m3Batch'; } anchor._url = url; return url; }
javascript
{ "resource": "" }
q37194
_on_fail
train
function _on_fail(resp, man){ // See if we got any traction. if( ! resp || ! resp.message_type() || ! resp.message() ){ // Something dark has happened, try to put something // together. // console.log('bad resp!?: ', resp); var resp_seed = { 'message_type': 'error', 'message': 'deep manager error' }; resp = new bbopx.barista.response(resp_seed); } anchor.apply_callbacks('manager_error', [resp, anchor]); }
javascript
{ "resource": "" }
q37195
_on_nominal_success
train
function _on_nominal_success(resp, man){ // Switch on message type when there isn't a complete failure. var m = resp.message_type(); if( m == 'error' ){ // Errors trump everything. anchor.apply_callbacks('error', [resp, anchor]); }else if( m == 'warning' ){ // Don't really have anything for warning yet...remove? anchor.apply_callbacks('warning', [resp, anchor]); }else if( m == 'success' ){ var sig = resp.signal(); if( sig == 'merge' || sig == 'rebuild' || sig == 'meta' ){ //console.log('run on signal: ' + sig); anchor.apply_callbacks(sig, [resp, anchor]); }else{ alert('unknown signal: very bad'); } }else{ alert('unimplemented message_type'); } // Postrun goes no matter what. anchor.apply_callbacks('postrun', [resp, anchor]); }
javascript
{ "resource": "" }
q37196
_applys_to_us_p
train
function _applys_to_us_p(data){ var ret = false; var mid = data['model_id'] || null; if( ! mid || mid != anchor.model_id ){ ll('skip packet--not for us'); }else{ ret = true; } return ret; }
javascript
{ "resource": "" }
q37197
train
function(e){ // Check if we are talking about self or parent. if( this === e.target || container_id === jQuery(e.target).parent().attr('id') || container_id === jQuery(e.target).attr('id') ){ _update_start_pos(e); // Bind to moving. jQuery(container_div).bind('mousemove', _scroller); } }
javascript
{ "resource": "" }
q37198
_sorter
train
function _sorter(a, b){ // Use aid property priority. var bpri = aid.priority(b.property_id()); var apri = aid.priority(a.property_id()); return apri - bpri; }
javascript
{ "resource": "" }
q37199
_add_table_row
train
function _add_table_row(item, color, prefix, suffix){ //var rep_color = aid.color(item.category()); var out_rep = bbopx.noctua.type_to_span(item, color); if( prefix ){ out_rep = prefix + out_rep; } if( suffix ){ out_rep = out_rep + suffix; } var trstr = null; if( color ){ trstr = '<tr class="bbop-mme-stack-tr" ' + 'style="background-color: ' + color + ';"><td class="bbop-mme-stack-td">' + out_rep + '</td></tr>'; }else{ trstr = '<tr class="bbop-mme-stack-tr">' + '<td class="bbop-mme-stack-td">' + out_rep + '</td></tr>'; } enode_stack_table.add_to(trstr); }
javascript
{ "resource": "" }