_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q30800
makeWhiteSpace
train
function makeWhiteSpace(n) { var buffer = [], nb = true; for (; n > 0; n--) { buffer.push((nb || n == 1) ? nbsp : " "); nb = !nb; } return buffer.join(""); }
javascript
{ "resource": "" }
q30801
fixSpaces
train
function fixSpaces(string) { if (string.charAt(0) == " ") string = nbsp + string.slice(1); return string.replace(/\t/g, function(){return makeWhiteSpace(indentUnit);}) .replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);}); }
javascript
{ "resource": "" }
q30802
makePartSpan
train
function makePartSpan(value, doc) { var text = value; if (value.nodeType == 3) text = value.nodeValue; else value = doc.createTextNode(text); var span = doc.createElement("SPAN"); span.isPart = true; span.appendChild(value); span.currentText = text; return span; }
javascript
{ "resource": "" }
q30803
pointAt
train
function pointAt(node){ var parent = node.parentNode; var next = node.nextSibling; return function(newnode) { parent.insertBefore(newnode, next); }; }
javascript
{ "resource": "" }
q30804
writeNode
train
function writeNode(node, c, end) { var toYield = []; forEach(simplifyDOM(node, end), function(part) { toYield.push(insertPart(part)); }); return yield(toYield.join(""), c); }
javascript
{ "resource": "" }
q30805
train
function() { var line = cleanText(self.history.textAfter(self.line).slice(self.offset)); var match = (self.caseFold ? line.toLowerCase() : line).indexOf(string); if (match > -1) return {from: {node: self.line, offset: self.offset + match}, to: {node: self.line, offset: self.offset + match + string.length}}; }
javascript
{ "resource": "" }
q30806
train
function() { var firstLine = cleanText(self.history.textAfter(self.line).slice(self.offset)); var match = (self.caseFold ? firstLine.toLowerCase() : firstLine).lastIndexOf(target[0]); if (match == -1 || match != firstLine.length - target[0].length) return false; var startOffset = self.offset + match; var line = self.history.nodeAfter(self.line); for (var i = 1; i < target.length - 1; i++) { var line = cleanText(self.history.textAfter(line)); if ((self.caseFold ? line.toLowerCase() : line) != target[i]) return false; line = self.history.nodeAfter(line); } var lastLine = cleanText(self.history.textAfter(line)); if ((self.caseFold ? lastLine.toLowerCase() : lastLine).indexOf(target[target.length - 1]) != 0) return false; return {from: {node: self.line, offset: startOffset}, to: {node: line, offset: target[target.length - 1].length}}; }
javascript
{ "resource": "" }
q30807
saveAfter
train
function saveAfter(pos) { if (self.history.textAfter(pos.node).length > pos.offset) { self.line = pos.node; self.offset = pos.offset + 1; } else { self.line = self.history.nodeAfter(pos.node); self.offset = 0; } }
javascript
{ "resource": "" }
q30808
train
function() { if (!this.container.firstChild) return ""; var accum = []; select.markSelection(this.win); forEach(traverseDOM(this.container.firstChild), method(accum, "push")); webkitLastLineHack(this.container); select.selectMarked(); return cleanText(accum.join("")); }
javascript
{ "resource": "" }
q30809
train
function() { var h = this.history; h.commit(); var start = select.cursorPos(this.container, true), end = select.cursorPos(this.container, false); if (!start || !end) return ""; if (start.node == end.node) return h.textAfter(start.node).slice(start.offset, end.offset); var text = [h.textAfter(start.node).slice(start.offset)]; for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos)) text.push(h.textAfter(pos)); text.push(h.textAfter(end.node).slice(0, end.offset)); return cleanText(text.join("\n")); }
javascript
{ "resource": "" }
q30810
train
function(text) { this.history.commit(); var start = select.cursorPos(this.container, true), end = select.cursorPos(this.container, false); if (!start || !end) return; end = this.replaceRange(start, end, text); select.setCursorPos(this.container, end); webkitLastLineHack(this.container); }
javascript
{ "resource": "" }
q30811
train
function(event) { var electric = Editor.Parser.electricChars, self = this; // Hack for Opera, and Firefox on OS X, in which stopping a // keydown event does not prevent the associated keypress event // from happening, so we have to cancel enter and tab again // here. if ((this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode))) || event.code == 13 || (event.code == 9 && this.options.tabMode != "default") || (event.keyCode == 32 && event.shiftKey && this.options.tabMode == "default")) event.stop(); else if (electric && electric.indexOf(event.character) != -1) this.parent.setTimeout(function(){self.indentAtCursor(null);}, 0); else if ((event.character == "v" || event.character == "V") && (event.ctrlKey || event.metaKey) && !event.altKey) // ctrl-V this.reroutePasteEvent(); }
javascript
{ "resource": "" }
q30812
train
function() { var pos = select.selectionTopNode(this.container, true); var to = select.selectionTopNode(this.container, false); if (pos === false || to === false) return; select.markSelection(this.win); if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false) return false; select.selectMarked(); return true; }
javascript
{ "resource": "" }
q30813
train
function() { var cur = select.selectionTopNode(this.container, true), start = cur; if (cur === false || !(!cur || cur.isPart || isBR(cur)) || !this.container.firstChild) return false; while (cur && !isBR(cur)) cur = cur.previousSibling; var next = cur ? cur.nextSibling : this.container.firstChild; if (next && next != start && next.isPart && hasClass(next, "whitespace")) select.focusAfterNode(next, this.container); else select.focusAfterNode(cur, this.container); select.scrollToCursor(this.container); return true; }
javascript
{ "resource": "" }
q30814
highlight
train
function highlight(node, ok) { if (!node) return; if (self.options.markParen) { self.options.markParen(node, ok); } else { node.style.fontWeight = "bold"; node.style.color = ok ? "#8F8" : "#F88"; } }
javascript
{ "resource": "" }
q30815
paren
train
function paren(node) { if (node.currentText) { var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/); return match && match[1]; } }
javascript
{ "resource": "" }
q30816
tryFindMatch
train
function tryFindMatch() { var stack = [], ch, ok = true;; for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) { if (runner.className == className && isSpan(runner) && (ch = paren(runner))) { if (forward(ch) == dir) stack.push(ch); else if (!stack.length) ok = false; else if (stack.pop() != matching[ch]) ok = false; if (!stack.length) break; } else if (runner.dirty || !isSpan(runner) && !isBR(runner)) { return {node: runner, status: "dirty"}; } } return {node: runner, status: runner && ok}; }
javascript
{ "resource": "" }
q30817
train
function(direction) { if (!this.container.firstChild) return; // The line has to have up-to-date lexical information, so we // highlight it first. if (!this.highlightAtCursor()) return; var cursor = select.selectionTopNode(this.container, false); // If we couldn't determine the place of the cursor, // there's nothing to indent. if (cursor === false) return; var lineStart = startOfLine(cursor); var whiteSpace = this.indentLineAfter(lineStart, direction); if (cursor == lineStart && whiteSpace) cursor = whiteSpace; // This means the indentation has probably messed up the cursor. if (cursor == whiteSpace) select.focusAfterNode(cursor, this.container); }
javascript
{ "resource": "" }
q30818
train
function(start, end, direction) { var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling); if (!isBR(end)) end = endOfLine(end, this.container); this.addDirtyNode(start); do { var next = endOfLine(current, this.container); if (current) this.highlight(before, next, true); this.indentLineAfter(current, direction); before = current; current = next; } while (current != end); select.setCursorPos(this.container, {node: start, offset: 0}, {node: end, offset: 0}); }
javascript
{ "resource": "" }
q30819
train
function(safe) { // pagehide event hack above if (this.unloaded) { this.win.document.designMode = "off"; this.win.document.designMode = "on"; this.unloaded = false; } if (internetExplorer) { this.container.createTextRange().execCommand("unlink"); this.selectionSnapshot = select.getBookmark(this.container); } var activity = this.options.cursorActivity; if (!safe || activity) { var cursor = select.selectionTopNode(this.container, false); if (cursor === false || !this.container.firstChild) return; cursor = cursor || this.container.firstChild; if (activity) activity(cursor); if (!safe) { this.scheduleHighlight(); this.addDirtyNode(cursor); } } }
javascript
{ "resource": "" }
q30820
train
function(node) { node = node || this.container.firstChild; if (!node) return; for (var i = 0; i < this.dirty.length; i++) if (this.dirty[i] == node) return; if (node.nodeType != 3) node.dirty = true; this.dirty.push(node); }
javascript
{ "resource": "" }
q30821
train
function() { // Timeouts are routed through the parent window, because on // some browsers designMode windows do not fire timeouts. var self = this; this.parent.clearTimeout(this.highlightTimeout); this.highlightTimeout = this.parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay); }
javascript
{ "resource": "" }
q30822
train
function() { while (this.dirty.length > 0) { var found = this.dirty.pop(); // IE8 sometimes throws an unexplainable 'invalid argument' // exception for found.parentNode try { // If the node has been coloured in the meantime, or is no // longer in the document, it should not be returned. while (found && found.parentNode != this.container) found = found.parentNode; if (found && (found.dirty || found.nodeType == 3)) return found; } catch (e) {} } return null; }
javascript
{ "resource": "" }
q30823
train
function(force) { // Prevent FF from raising an error when it is firing timeouts // on a page that's no longer loaded. if (!window.select) return; if (!this.options.readOnly) select.markSelection(this.win); var start, endTime = force ? null : time() + this.options.passTime; while ((time() < endTime || force) && (start = this.getDirtyNode())) { var result = this.highlight(start, endTime); if (result && result.node && result.dirty) this.addDirtyNode(result.node); } if (!this.options.readOnly) select.selectMarked(); if (start) this.scheduleHighlight(); return this.dirty.length == 0; }
javascript
{ "resource": "" }
q30824
train
function(passTime) { var self = this, pos = null; return function() { // FF timeout weirdness workaround. if (!window.select) return; // If the current node is no longer in the document... oh // well, we start over. if (pos && pos.parentNode != self.container) pos = null; select.markSelection(self.win); var result = self.highlight(pos, time() + passTime, true); select.selectMarked(); var newPos = result ? (result.node && result.node.nextSibling) : null; pos = (pos == newPos) ? null : newPos; self.delayScanning(); }; }
javascript
{ "resource": "" }
q30825
train
function() { if (this.scanner) { this.parent.clearTimeout(this.documentScan); this.documentScan = this.parent.setTimeout(this.scanner, this.options.continuousScanning); } }
javascript
{ "resource": "" }
q30826
tokenPart
train
function tokenPart(token){ var part = makePartSpan(token.value, self.doc); part.className = token.style; return part; }
javascript
{ "resource": "" }
q30827
train
function(){ var part = this.get(); // Allow empty nodes when they are alone on a line, needed // for the FF cursor bug workaround (see select.js, // insertNewlineAtCursor). while (part && isSpan(part) && part.currentText == "") { // Leave empty nodes that are alone on a line alone in // Opera, since that browsers doesn't deal well with // having 2 BRs in a row. if (window.opera && surroundedByBRs(part)) { this.next(); part = this.get(); } else { var old = part; this.remove(); part = this.get(); // Adjust selection information, if any. See select.js for details. select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0); } } return part; }
javascript
{ "resource": "" }
q30828
train
function() { this.nodes = []; this.edges = []; // Extract wires for(var i = 0 ; i < this.layer.wires.length ; i++) { var wire = this.layer.wires[i]; this.edges.push([this.layer.containers.indexOf(wire.terminal1.container), this.layer.containers.indexOf(wire.terminal2.container) ]); } }
javascript
{ "resource": "" }
q30829
train
function(options) { inputEx.IPv4Field.superclass.setOptions.call(this, options); this.options.messages.invalid = inputEx.messages.invalidIPv4; this.options.regexp = /^(?:1\d?\d?|2(?:[0-4]\d?|[6789]|5[0-5]?)?|[3-9]\d?|0)(?:\.(?:1\d?\d?|2(?:[0-4]\d?|[6789]|5[0-5]?)?|[3-9]\d?|0)){3}$/; }
javascript
{ "resource": "" }
q30830
train
function(id, container, config) { // Normalize 2.4.0, pre 2.4.0 args var nArgs = this._parseArgs(arguments); id = nArgs.id; container = nArgs.container; config = nArgs.config; this.oDomContainer = Dom.get(container); if (!this.oDomContainer) { this.logger.log("Container not found in document.", "error"); } if (!this.oDomContainer.id) { this.oDomContainer.id = Dom.generateId(); } if (!id) { id = this.oDomContainer.id + "_t"; } /** * The unique id associated with the CalendarGroup * @property id * @type String */ this.id = id; /** * The unique id associated with the CalendarGroup container * @property containerId * @type String */ this.containerId = this.oDomContainer.id; this.logger = new YAHOO.widget.LogWriter("CalendarGroup " + this.id); this.initEvents(); this.initStyles(); /** * The collection of Calendar pages contained within the CalendarGroup * @property pages * @type YAHOO.widget.Calendar[] */ this.pages = []; Dom.addClass(this.oDomContainer, CalendarGroup.CSS_CONTAINER); Dom.addClass(this.oDomContainer, CalendarGroup.CSS_MULTI_UP); /** * The Config object used to hold the configuration variables for the CalendarGroup * @property cfg * @type YAHOO.util.Config */ this.cfg = new YAHOO.util.Config(this); /** * The local object which contains the CalendarGroup's options * @property Options * @type Object */ this.Options = {}; /** * The local object which contains the CalendarGroup's locale settings * @property Locale * @type Object */ this.Locale = {}; this.setupConfig(); if (config) { this.cfg.applyConfig(config, true); } this.cfg.fireQueue(); // OPERA HACK FOR MISWRAPPED FLOATS if (YAHOO.env.ua.opera){ this.renderEvent.subscribe(this._fixWidth, this, true); this.showEvent.subscribe(this._fixWidth, this, true); } this.logger.log("Initialized " + this.pages.length + "-page CalendarGroup", "info"); }
javascript
{ "resource": "" }
q30831
train
function() { // Add element button this.addButton = inputEx.cn('img', {src: inputEx.spacerUrl, className: 'inputEx-ListField-addButton'}); Dom.setStyle(this.addButton, 'float', 'left'); this.fieldContainer.appendChild(this.addButton); // Instanciate the new subField this.subField = inputEx(this.options.elementType,this); var subFieldEl = this.subField.getEl(); Dom.setStyle(subFieldEl, 'margin-left', '4px'); Dom.setStyle(subFieldEl, 'float', 'left'); this.fieldContainer.appendChild( subFieldEl ); // Line breaker this.fieldContainer.appendChild( inputEx.cn('div', null, {clear: "both"}, this.options.listLabel) ); // Div element to contain the children this.childContainer = inputEx.cn('div', {className: 'inputEx-ListField-childContainer'}); this.fieldContainer.appendChild(this.childContainer); }
javascript
{ "resource": "" }
q30832
train
function() { jsBox.WiringEditor.superclass.renderButtons.call(this); // Add the run button to the toolbar var toolbar = YAHOO.util.Dom.get('toolbar'); var runButton = new YAHOO.widget.Button({ label:"Run", id:"WiringEditor-runButton", container: toolbar }); runButton.on("click", jsBox.run, jsBox, true); }
javascript
{ "resource": "" }
q30833
train
function (p_sType, p_aArgs, p_oItem) { var sText = p_aArgs[0], oConfig = this.cfg, oAnchor = this._oAnchor, sHelpText = oConfig.getProperty(_HELP_TEXT), sHelpTextHTML = _EMPTY_STRING, sEmphasisStartTag = _EMPTY_STRING, sEmphasisEndTag = _EMPTY_STRING; if (sText) { if (sHelpText) { sHelpTextHTML = _START_HELP_TEXT + sHelpText + _END_EM; } if (oConfig.getProperty(_EMPHASIS)) { sEmphasisStartTag = _START_EM; sEmphasisEndTag = _END_EM; } if (oConfig.getProperty(_STRONG_EMPHASIS)) { sEmphasisStartTag = _START_STRONG; sEmphasisEndTag = _END_STRONG; } oAnchor.innerHTML = (sEmphasisStartTag + sText + sEmphasisEndTag + sHelpTextHTML); } }
javascript
{ "resource": "" }
q30834
train
function() { // Remove from DOM if(Dom.inDocument(this.el)) { this.el.parentNode.removeChild(this.el); } // recursively purge element Event.purgeElement(this.el, true); }
javascript
{ "resource": "" }
q30835
train
function(obj,parentEl) { var ul = inputEx.cn('ul', {className: 'inputEx-JsonTreeInspector'}); for(var key in obj) { if(obj.hasOwnProperty(key)) { var value = obj[key]; var id = Dom.generateId(); var li = inputEx.cn('li', {id: id}, null, key+':'); this.hash[id] = {value: value, expanded: false}; if( lang.isObject(value) || lang.isArray(value) ) { if(lang.isArray(value)) { li.appendChild( inputEx.cn('span', null, null, "[ "+value.length+" element"+(value.length > 1 ? 's':'')+"]" ) ); } Dom.addClass(li,'collapsed'); Event.addListener(li, 'click', this.onItemClick, this, true); } else { var spanContent = ''; if( lang.isString(value) ) { spanContent = '"'+inputEx.htmlEntities(value)+'"'; } else { if(value === null) { spanContent = "null"; } else { spanContent = value.toString(); } } li.appendChild( inputEx.cn('span', {className: 'type-'+(value === null ? "null" : (typeof value))}, null, spanContent ) ); } ul.appendChild(li); } } parentEl.appendChild(ul); return ul; }
javascript
{ "resource": "" }
q30836
train
function(e, params) { Event.stopEvent(e); var tgt = Event.getTarget(e); if( Dom.hasClass(tgt, 'expanded') || Dom.hasClass(tgt, 'collapsed') ) { this.expandElement(tgt); } }
javascript
{ "resource": "" }
q30837
train
function(li) { var isExpanded = Dom.hasClass(li, 'expanded'); Dom.replaceClass(li, isExpanded ? 'expanded' : 'collapsed' , isExpanded ? 'collapsed':'expanded'); var h = this.hash[li.id]; if(isExpanded) { // hide the sub-branch h.expanded.style.display = 'none'; } else { if(h.expanded === false) { // generate the sub-branch h.expanded = this.buildBranch(h.value, li); } // show the sub-branch h.expanded.style.display = ''; } }
javascript
{ "resource": "" }
q30838
train
function(li,maxLevel) { this.expandElement(li); var sub = Dom.getChildrenBy(li, function(c) {return c.tagName == "UL";})[0].childNodes; for(var j = 0 ; j < sub.length ; j++) { var s = sub[j]; if(Dom.hasClass(s,"collapsed") && maxLevel != 0) { this.expandBranch(s,maxLevel-1); } } }
javascript
{ "resource": "" }
q30839
train
function(maxLevel) { var ul = this.el.childNodes[0]; var liEls = ul.childNodes; for(var i = 0 ; i < liEls.length ; i++) { var li = liEls[i]; this.expandBranch(li,maxLevel); } }
javascript
{ "resource": "" }
q30840
train
function(key) { Y.log("Fetching item at " + key); var item = this._getItem(key); return YL.isValue(item) ? this._getValue(item) : null; // required by HTML 5 spec }
javascript
{ "resource": "" }
q30841
train
function(index) { Y.log("Fetching key at " + index); if (YL.isNumber(index) && -1 < index && this.length > index) { var value = this._key(index); if (value) {return value;} } // this is thrown according to the HTML5 spec throw('INDEX_SIZE_ERR - Storage.setItem - The provided index (' + index + ') is not available'); }
javascript
{ "resource": "" }
q30842
train
function(key) { Y.log("removing " + key); if (this.hasKey(key)) { var oldValue = this._getItem(key); if (! oldValue) {oldValue = null;} this._removeItem(key); this.fireEvent(this.CE_CHANGE, new YU.StorageEvent(this, key, oldValue, null, YU.StorageEvent.TYPE_REMOVE_ITEM)); } else { // HTML 5 spec says to do nothing } }
javascript
{ "resource": "" }
q30843
train
function(key, data) { Y.log("SETTING " + data + " to " + key); if (YL.isString(key)) { var eventType = this.hasKey(key) ? YU.StorageEvent.TYPE_UPDATE_ITEM : YU.StorageEvent.TYPE_ADD_ITEM, oldValue = this._getItem(key); if (! oldValue) {oldValue = null;} if (this._setItem(key, this._createValue(data))) { this.fireEvent(this.CE_CHANGE, new YU.StorageEvent(this, key, oldValue, data, eventType)); } else { // this is thrown according to the HTML5 spec throw('QUOTA_EXCEEDED_ERROR - Storage.setItem - The choosen storage method (' + this.getName() + ') has exceeded capacity'); } } else { // HTML 5 spec says to do nothing } }
javascript
{ "resource": "" }
q30844
train
function(s) { var a = s ? s.split(this.DELIMITER) : []; if (1 == a.length) {return s;} switch (a[0]) { case 'boolean': return 'true' === a[1]; case 'number': return parseFloat(a[1]); case 'null': return null; default: return a[1]; } }
javascript
{ "resource": "" }
q30845
train
function(engineType, location, conf) { var _cfg = YL.isObject(conf) ? conf : {}, klass = _getClass(_registeredEngineMap[engineType]); if (! klass && ! _cfg.force) { var i, j; if (_cfg.order) { j = _cfg.order.length; for (i = 0; i < j && ! klass; i += 1) { klass = _getClass(_cfg.order[i]); } } if (! klass) { j = _registeredEngineSet.length; for (i = 0; i < j && ! klass; i += 1) { klass = _getClass(_registeredEngineSet[i]); } } } if (klass) { return _getStorageEngine(_getValidLocation(location), klass, _cfg.engine); } throw('YAHOO.util.StorageManager.get - No engine available, please include an engine before calling this function.'); }
javascript
{ "resource": "" }
q30846
train
function(engineConstructor) { if (YL.isFunction(engineConstructor) && YL.isFunction(engineConstructor.isAvailable) && YL.isString(engineConstructor.ENGINE_NAME)) { _registeredEngineMap[engineConstructor.ENGINE_NAME] = engineConstructor; _registeredEngineSet.push(engineConstructor); return true; } return false; }
javascript
{ "resource": "" }
q30847
train
function(key) { this._keyMap[key] = this.length; this._keys.push(key); this.length = this._keys.length; }
javascript
{ "resource": "" }
q30848
train
function(key) { var j = this._indexOfKey(key), rest = this._keys.slice(j + 1); delete this._keyMap[key]; for (var k in this._keyMap) { if (j < this._keyMap[k]) { this._keyMap[k] -= 1; } } this._keys.length = j; this._keys = this._keys.concat(rest); this.length = this._keys.length; }
javascript
{ "resource": "" }
q30849
train
function() { this.logger.log("focus"); this.valueChangeSource = Slider.SOURCE_UI_EVENT; // Focus the background element if possible var el = this.getEl(); if (el.focus) { try { el.focus(); } catch(e) { // Prevent permission denied unhandled exception in FF that can // happen when setting focus while another element is handling // the blur. @TODO this is still writing to the error log // (unhandled error) in FF1.5 with strict error checking on. } } this.verifyOffset(); return !this.isLocked(); }
javascript
{ "resource": "" }
q30850
train
function(source, newOffset, skipAnim, force, silent) { var t = this.thumb, newX, newY; if (!t.available) { this.logger.log("defer setValue until after onAvailble"); this.deferredSetValue = arguments; return false; } if (this.isLocked() && !force) { this.logger.log("Can't set the value, the control is locked"); return false; } if ( isNaN(newOffset) ) { this.logger.log("setValue, Illegal argument: " + newOffset); return false; } if (t._isRegion) { this.logger.log("Call to setValue for region Slider ignored. Use setRegionValue","warn"); return false; } this.logger.log("setValue " + newOffset); this._silent = silent; this.valueChangeSource = source || Slider.SOURCE_SET_VALUE; t.lastOffset = [newOffset, newOffset]; this.verifyOffset(); this._slideStart(); if (t._isHoriz) { newX = t.initPageX + newOffset + this.thumbCenterPoint.x; this.moveThumb(newX, t.initPageY, skipAnim); } else { newY = t.initPageY + newOffset + this.thumbCenterPoint.y; this.moveThumb(t.initPageX, newY, skipAnim); } return true; }
javascript
{ "resource": "" }
q30851
train
function() { var xy = getXY(this.getEl()), t = this.thumb; if (!this.thumbCenterPoint || !this.thumbCenterPoint.x) { this.setThumbCenterPoint(); } if (xy) { this.logger.log("newPos: " + xy); if (xy[0] != this.baselinePos[0] || xy[1] != this.baselinePos[1]) { this.logger.log("background moved, resetting constraints"); // Reset background this.setInitPosition(); this.baselinePos = xy; // Reset thumb t.initPageX = this.initPageX + t.startOffset[0]; t.initPageY = this.initPageY + t.startOffset[1]; t.deltaSetXY = null; this.resetThumbConstraints(); return false; } } return true; }
javascript
{ "resource": "" }
q30852
train
function(x, y, skipAnim, midMove) { var t = this.thumb, self = this, p,_p,anim; if (!t.available) { this.logger.log("thumb is not available yet, aborting move"); return; } this.logger.log("move thumb, x: " + x + ", y: " + y); t.setDelta(this.thumbCenterPoint.x, this.thumbCenterPoint.y); _p = t.getTargetCoord(x, y); p = [Math.round(_p.x), Math.round(_p.y)]; if (this.animate && t._graduated && !skipAnim) { this.logger.log("graduated"); this.lock(); // cache the current thumb pos this.curCoord = getXY(this.thumb.getEl()); this.curCoord = [Math.round(this.curCoord[0]), Math.round(this.curCoord[1])]; setTimeout( function() { self.moveOneTick(p); }, this.tickPause ); } else if (this.animate && Slider.ANIM_AVAIL && !skipAnim) { this.logger.log("animating to " + p); this.lock(); anim = new YAHOO.util.Motion( t.id, { points: { to: p } }, this.animationDuration, YAHOO.util.Easing.easeOut ); anim.onComplete.subscribe( function() { self.logger.log("Animation completed _mouseDown:" + self._mouseDown); self.unlock(); if (!self._mouseDown) { self.endMove(); } }); anim.animate(); } else { t.setDragElPos(x, y); if (!midMove && !this._mouseDown) { this.endMove(); } } }
javascript
{ "resource": "" }
q30853
train
function(curCoord, finalCoord) { this.logger.log("getNextX: " + curCoord + ", " + finalCoord); var t = this.thumb, thresh, tmp = [], nextCoord = null; if (curCoord[0] > finalCoord[0]) { thresh = t.tickSize - this.thumbCenterPoint.x; tmp = t.getTargetCoord( curCoord[0] - thresh, curCoord[1] ); nextCoord = [tmp.x, tmp.y]; } else if (curCoord[0] < finalCoord[0]) { thresh = t.tickSize + this.thumbCenterPoint.x; tmp = t.getTargetCoord( curCoord[0] + thresh, curCoord[1] ); nextCoord = [tmp.x, tmp.y]; } else { // equal, do nothing } return nextCoord; }
javascript
{ "resource": "" }
q30854
train
function(e) { this.logger.log("background drag"); if (this.backgroundEnabled && !this.isLocked()) { var x = Event.getPageX(e), y = Event.getPageY(e); this.moveThumb(x, y, true, true); this.fireEvents(); } }
javascript
{ "resource": "" }
q30855
train
function (thumbEvent) { var t = this.thumb, newX, newY, newVal; if (!thumbEvent) { t.cachePosition(); } if (! this.isLocked()) { if (t._isRegion) { newX = t.getXValue(); newY = t.getYValue(); if (newX != this.previousX || newY != this.previousY) { if (!this._silent) { this.onChange(newX, newY); this.fireEvent("change", { x: newX, y: newY }); } } this.previousX = newX; this.previousY = newY; } else { newVal = t.getValue(); if (newVal != this.previousVal) { this.logger.log("Firing onchange: " + newVal); if (!this._silent) { this.onChange( newVal ); this.fireEvent("change", newVal); } } this.previousVal = newVal; } } }
javascript
{ "resource": "" }
q30856
train
function(options) { inputEx.ColorPickerField.superclass.setOptions.call(this, options); // Overwrite options this.options.className = options.className ? options.className : 'inputEx-Field inputEx-ColorPickerField'; // Color Picker options object this.options.colorPickerOptions = YAHOO.lang.isUndefined(options.colorPickerOptions) ? {} : options.colorPickerOptions; // showcontrols this.options.colorPickerOptions.showcontrols = YAHOO.lang.isUndefined(this.options.colorPickerOptions.showcontrols) ? true : this.options.colorPickerOptions.showcontrols; // default images (color selection images) this.options.colorPickerOptions.images = YAHOO.lang.isUndefined(this.options.colorPickerOptions.images) ? { PICKER_THUMB: "../lib/yui/colorpicker/assets/picker_thumb.png", HUE_THUMB: "../lib/yui/colorpicker/assets/hue_thumb.png" } : this.options.colorPickerOptions.images; }
javascript
{ "resource": "" }
q30857
train
function (userId, doc, fieldNames, modifier) { // only admins can update user roles via the client return Users.isAdmin(userId) || (doc._id === userId && fieldNames.indexOf("roles") < 0); }
javascript
{ "resource": "" }
q30858
encode
train
function encode(events) { if(!Array.isArray(events)) { return '00'; } let bitmask = 0; for(event in events) { let index = events[event]; bitmask += (1 << index); } return ('00' + bitmask.toString(16)).substr(-2); }
javascript
{ "resource": "" }
q30859
decode
train
function decode(events) { let indexList = []; let eventsByte = parseInt(events, 16); if(eventsByte & APPEARANCE_MASK) { indexList.push(APPEARANCE); } if(eventsByte & DISPLACEMENT_MASK) { indexList.push(DISPLACEMENT); } if(eventsByte & PACKETS_MASK) { indexList.push(PACKETS); } if(eventsByte & KEEPALIVE_MASK) { indexList.push(KEEPALIVE); } if(eventsByte & DISAPPEARANCE_MASK) { indexList.push(DISAPPEARANCE); } return indexList; }
javascript
{ "resource": "" }
q30860
measures
train
function measures (meter, measures, builder) { var list var mLen = measureLength(meter) if (!mLen) throw Error('Not valid meter: ' + meter) var seq = [] builder = builder || score.note splitMeasures(measures).forEach(function (measure) { measure = measure.trim() if (measure.length > 0) { list = parenthesize(tokenize(measure), []) processList(seq, list, measureLength(meter), builder) } }) return score.seq(seq) }
javascript
{ "resource": "" }
q30861
chords
train
function chords (meter, data) { return measures(meter, data, function (dur, el) { return score.el({ duration: dur, chord: el }) }) }
javascript
{ "resource": "" }
q30862
measureLength
train
function measureLength (meter) { var m = meter.split('/').map(function (n) { return +n.trim() }) return m[0] * (4 / m[1]) }
javascript
{ "resource": "" }
q30863
internalResolve
train
function internalResolve ( resolve ) { resolve(window.google && window.google.maps ? window.google.maps : false); }
javascript
{ "resource": "" }
q30864
constructFromObject
train
function constructFromObject(instance, source) { instance.transmitterId = identifiers.format(source.transmitterId); instance.transmitterIdType = source.transmitterIdType; instance.rssiSignature = source.rssiSignature || []; instance.rssiSignature.forEach(function(entry) { entry.receiverIdType = entry.receiverIdType || identifiers.TYPE_UNKNOWN; entry.rssi = entry.rssi || -Number.MAX_SAFE_INTEGER; entry.numberOfDecodings = entry.numberOfDecodings || 1; entry.rssiSum = entry.rssiSum || entry.rssi; }); if(source.hasOwnProperty('packets')) { instance.packets = source.packets; } if(source.hasOwnProperty('timestamp')) { instance.timestamp = source.timestamp; } if(source.hasOwnProperty('events')) { instance.events = source.events; } if(source.hasOwnProperty('earliestDecodingTime')) { instance.earliestDecodingTime = source.earliestDecodingTime; } instance.creationTime = new Date().getTime(); }
javascript
{ "resource": "" }
q30865
mergeTimes
train
function mergeTimes(source, destination) { if(source.hasOwnProperty('earliestDecodingTime')) { if(destination.hasOwnProperty('earliestDecodingTime')) { let isSourceEarlier = (source.earliestDecodingTime < destination.earliestDecodingTime); if(isSourceEarlier) { destination.earliestDecodingTime = source.earliestDecodingTime; } } else { destination.earliestDecodingTime = source.earliestDecodingTime; } } }
javascript
{ "resource": "" }
q30866
toHexString
train
function toHexString(number, numberOfBytes) { numberOfBytes = numberOfBytes || 1; let hexString = '00'.repeat(numberOfBytes) + number.toString(16); return hexString.substr(-2 * numberOfBytes); }
javascript
{ "resource": "" }
q30867
Region
train
function Region(config) { this.config = config; this.appLimit = new RateLimit(this.config.rateLimitTypeApplication, 1, this.config); this.methodLimits = {}; this.liveRequests = 0; }
javascript
{ "resource": "" }
q30868
RateLimit
train
function RateLimit(type, distFactor, config) { this.config = config; this.type = type; this.buckets = this.config.defaultBuckets.map(b => new TokenBucket(b.timespan, b.limit, b)); this.retryAfter = 0; this.distFactor = distFactor; }
javascript
{ "resource": "" }
q30869
dependency
train
function dependency(deps, name) { if (name in deps && typeof deps[name] !== 'undefined') { return deps[name]; } throw new Error('grunt-rewrite.registerTask requires dependency "' + name + '"'); }
javascript
{ "resource": "" }
q30870
train
function(deps) { deps = deps || {}; var grunt = dependency(deps, 'grunt'); var task = dependency(deps, 'task'); var done = task.async(); task.files.forEach(function(subTask) { // make sure an editing function has been provided if (typeof subTask.editor !== 'function') { return grunt.fatal(task.current.nameArgs + ' needs a ".editor" method'); } // replace contents of each file with the return value // of the editor when given the file's contents and path. subTask.src.forEach(function(filePath) { if (!grunt.file.isFile(filePath)) { return grunt.log.write('skipped "' + filePath + '" as is not a file'); } var original = grunt.file.read(filePath); var rewritten = subTask.editor(original, filePath); if (typeof rewritten === 'undefined') { return grunt.fatal(task.current.nameArgs + ' ".editor" method did not return a value'); } grunt.file.write(filePath, rewritten); }); }); done(); }
javascript
{ "resource": "" }
q30871
create_node
train
function create_node(length) { const node = {}; Object.defineProperty(node, "_", { value: { length: length, //record array length watchers: {}, watcher_key: new Set(), watcher_props: new Set(), on_watch_callback: undefined }, writable: true, enumerable: false }); return node; }
javascript
{ "resource": "" }
q30872
create_node_by_path
train
function create_node_by_path(context, path, len, tracker) { let node = context.state.rootNode; for (let i = 0; i < len; i++) { const k = path[i]; if (k == "_") continue; if (k == "#") { node = context.state.rootNode; continue; } if (node_type(node[k]) != NodeTypes.NODE) { commit_node_prop(context, node, k, create_node(), tracker); } node = node[k]; } return node; }
javascript
{ "resource": "" }
q30873
apply_patch
train
function apply_patch(context, patch, tracker) { const path = patch[0]; if (path.length == 0) return; //ignore replace root node const value = patch[1]; const len = path.length - 1; const prop = path[len]; if (!Array.isArray(value)) { const node = create_node_by_path(context, path, len, tracker); commit_node_prop(context, node, prop, value, tracker); return; } else { const patchType = value[0]; if (patchType == PatchTypes.DEL) { return apply_delete_patch(context, path, tracker); } const node = create_node_by_path(context, path, len, tracker); if (patchType == PatchTypes.REFERENCE) { const refNode = create_node_by_path( context, value[1], value[1].length, tracker ); commit_node_prop(context, node, prop, refNode, tracker); return; } if (patchType == PatchTypes.NODE) { if ( value[1] == undefined && node_type(node[prop]) == NodeTypes.NODE //&& node[prop]._.length == undefined ) { return; } const childNode = create_node(value[1]); commit_node_prop(context, node, prop, childNode, tracker); return; } } }
javascript
{ "resource": "" }
q30874
calc_patches_any
train
function calc_patches_any(context, patches, path, value, tracker) { const valueType = value_type(value); if (valueType == ValueTypes.OBJECT) { if (value.propertyIsEnumerable("_")) { if (value["_"] == "$ref") { return patches.push([path, [PatchTypes.REFERENCE, value.path]]); } throw new Error("Underscore property is reserved"); } calc_patches_object(context, patches, path, value, tracker); } else if (valueType == ValueTypes.ARRAY) { calc_patches_array(context, patches, path, value, tracker); } else { patches.push([path, value]); } }
javascript
{ "resource": "" }
q30875
draw
train
function draw (ctx, score) { console.log(score) drawStripes(box, ctx) forEachTime(function (time, note) { var midi = toMidi(note.pitch) console.log(time, note, midi) ctx.fillRect(box.x(time), box.y(midi), box.nw(note.duration), box.nh()) }, null, score) }
javascript
{ "resource": "" }
q30876
exec
train
function exec (ctx, scope, data) { console.log('exec', ctx, scope, data) var fn = getFunction(ctx, scope, data[0]) var elements = data.slice(1) var params = elements.map(function (p) { return Array.isArray(p) ? exec(ctx, scope, p) : (p[0] === '$') ? ctx[p] : p }).filter(function (p) { return p !== VAR }) return fn.apply(null, params) }
javascript
{ "resource": "" }
q30877
format
train
function format(identifier) { if(typeof identifier === 'string') { var hexIdentifier = identifier.replace(/[^A-Fa-f0-9]/g, ''); return hexIdentifier.toLowerCase(); } return null; }
javascript
{ "resource": "" }
q30878
lengthInBytes
train
function lengthInBytes(type) { switch(type) { case TYPE_UNKNOWN: return LENGTH_UNKNOWN; case TYPE_EUI64: return LENGTH_EUI64; case TYPE_EUI48: return LENGTH_EUI48; case TYPE_RND48: return LENGTH_RND48; default: return null; } }
javascript
{ "resource": "" }
q30879
buildType
train
function buildType(t, typeClassification) { let typeDef; switch (typeClassification) { case 'primative': typeDef = { interface: t, builder: t }; break; case 'message': typeDef = { interface: '$Subtype<' + t + 'Interface>', builder: t + 'Builder' }; break; case 'enum': typeDef = { interface: t + 'Values', builder: t + 'Values' }; break; default: throw new Error('Unhandled classification case :: ' + typeClassification); } if (repeated) { for (const key in typeDef) { typeDef[key] = 'Array<' + typeDef[key] + '>'; } } return typeDef; }
javascript
{ "resource": "" }
q30880
strip
train
function strip(obj) { if (!obj || ! obj instanceof Object || typeof obj === 'string') { return undefined; } if (obj instanceof Array) { for (const value of obj) { strip(value); } } else { delete obj['loc']; delete obj['start']; delete obj['end']; Object.keys(obj).forEach(key => strip(obj[key])); } return obj; }
javascript
{ "resource": "" }
q30881
clean
train
function clean(code) { try { const ast = babylon.parse(code, { // parse in strict mode and allow module declarations sourceType: 'module', plugins: [ // enable jsx and flow syntax 'jsx', 'flow' ] }); const cleanAst = strip(ast).program; const resultCode = generate(cleanAst, {}).code; return resultCode.replace(/(\/\*\$ | \#\*\/)/g, ''); } catch (e) { console.log(code); throw e; } }
javascript
{ "resource": "" }
q30882
camelCase
train
function camelCase(str, next) { let output = ''; for (const c of str) { if (c === '_') { next = true; continue; } output += next ? c.toUpperCase() : c; next = false; } return output; }
javascript
{ "resource": "" }
q30883
processProto
train
function processProto(protoFile, root, imported = []) { const protPath = path.format({ dir: root, base: protoFile }); const parser = new ProtoBuf.DotProto.Parser(fs.readFileSync(protPath)); const protoAst = parser.parse(); imported.push(protoFile); protoAst.imports.forEach(file => { if (imported.indexOf(file) === -1) { processProto(file, root, imported); } }); return Namespace.getNamespace(protoAst.package).update(protoAst); }
javascript
{ "resource": "" }
q30884
generateFromProto
train
function generateFromProto(outputDir, inputProto, protoDir) { try { fs.accessSync(path.format({ dir: protoDir, base: inputProto })); if (!protoDir) { const absolutePath = fs.realpathSync(inputProto); protoDir = path.dirname(absolutePath); inputProto = path.basename(absolutePath); } } catch (e) { throw new Error('Can not locate proto file - ' + inputProto, e); } let jsonDescriptor; try { class ImportBuilder extends ProtoBuf.Builder { import(json, filename) { this._imported = this._imported || []; this._imported.push({ filename: filename, json: json }); super['import'](json, filename); } } const importBuilder = new ImportBuilder(); // This validates that proto is parsable const builder = ProtoBuf.loadProtoFile({ root: protoDir, file: inputProto }, importBuilder); jsonDescriptor = JSON.stringify(builder._imported, undefined, 2); } catch (e) { console.error('Proto Parsing Failed', e); throw new Error('Generation Failed'); } Namespace.reset(); const namespace = processProto(inputProto, protoDir); const code = namespace.generate( jsonDescriptor, { render: data => mustache.render(fs.readFileSync(path.format({ dir: templateDir, base: 'module.js.mt' }), 'utf8'), data) }, { render: data => mustache.render(fs.readFileSync(path.format({ dir: templateDir, base: 'root.js.mt' }), 'utf8'), data) } ); for (const key of Object.keys(code)) { const dir = path.format({ dir: outputDir, base: key }); fs.ensureDirSync(dir); const file = path.format({ dir: dir, base: 'index.js' }); fs.writeFileSync(file, code[key], {encoding: 'utf8'}); } }
javascript
{ "resource": "" }
q30885
note
train
function note (dur, pitch, data) { if (arguments.length === 1) return function (p, d) { return note(dur, p, d) } return assign({ pitch: pitch, duration: dur || 1 }, data) }
javascript
{ "resource": "" }
q30886
transform
train
function transform (nt, st, pt, ctx, obj) { switch (arguments.length) { case 0: return transform case 1: case 2: case 3: return transformer(nt, st, pt) case 4: return function (o) { return transformer(nt, st, pt)(ctx, o) } default: return transformer(nt, st, pt)(ctx, obj) } }
javascript
{ "resource": "" }
q30887
map
train
function map (fn, ctx, obj) { switch (arguments.length) { case 0: return map case 1: return transform(fn, buildSeq, buildSim) case 2: return function (obj) { return map(fn)(ctx, obj) } case 3: return map(fn)(ctx, obj) } }
javascript
{ "resource": "" }
q30888
extend
train
function extend( obj, var_args ) { for ( var i = 1; i < arguments.length ; i += 1 ) { var other = arguments[ i ]; for ( var p in other ) { var v = Object.getOwnPropertyDescriptor( other, p ); if ( typeof v == "undefined" || typeof v.value == "undefined" ) { delete obj[ p ]; } else { Object.defineProperty( obj, p, v ); } } } return obj; }
javascript
{ "resource": "" }
q30889
SSH
train
function SSH(options) { this.options = options || {}; console.assert(this.options.hostname, "Hostname required!"); this.debug = !!options.debug; this.listener = new Listener({ debug: options.debug }); }
javascript
{ "resource": "" }
q30890
forEachTime
train
function forEachTime (fn, ctx, obj) { if (arguments.length > 1) return forEachTime(fn)(ctx, obj) return function (ctx, obj) { return score.transform( function (note) { return function (time, ctx) { fn(time, note, ctx) return note.duration } }, function (seq) { return function (time, ctx) { return seq.reduce(function (dur, fn) { return dur + fn(time + dur, ctx) }, 0) } }, function (par) { return function (time, ctx) { return par.reduce(function (max, fn) { return Math.max(max, fn(time, ctx)) }, 0) } } )(null, obj)(0, ctx) } }
javascript
{ "resource": "" }
q30891
events
train
function events (obj, build, compare) { var e = [] forEachTime(function (time, obj) { e.push(build ? build(time, obj) : [time, obj]) }, null, obj) return e.sort(compare || function (a, b) { return a[0] - b[0] }) }
javascript
{ "resource": "" }
q30892
SCP
train
function SCP(options) { this.options = options || {}; console.assert(this.options.hostname, "Hostname required!"); this.debug = !!options.debug; this.listener = new Listener({ debug: options.debug }); }
javascript
{ "resource": "" }
q30893
merge
train
function merge(source, destination) { source.forEach(function(current) { let matchFound = false; destination.forEach(function(target) { let isSameReceiver = identifiers.areMatch(current.receiverId, current.receiverIdType, target.receiverId, target.receiverIdType); if(isSameReceiver) { target.rssiSum = target.rssiSum || (target.rssi * target.numberOfDecodings); target.numberOfDecodings += current.numberOfDecodings || 1; target.rssiSum += current.rssiSum || (current.rssi * current.numberOfDecodings); target.rssi = Math.round(target.rssiSum / target.numberOfDecodings); matchFound = true; } }); if(!matchFound) { destination.push(current); } }); destination.sort(compareRssi); }
javascript
{ "resource": "" }
q30894
compareRssi
train
function compareRssi(a,b) { if(a.rssi < b.rssi) return 1; if(a.rssi > b.rssi) return -1; return 0; }
javascript
{ "resource": "" }
q30895
encode
train
function encode(rssi) { if(rssi < MIN_RSSI_DBM) { rssi = MIN_RSSI_DBM; } else if(rssi > MAX_RSSI_DBM) { rssi = MAX_RSSI_DBM; } else { rssi = Math.round(rssi); } return ('00' + (rssi - MIN_RSSI_DBM).toString(16)).substr(-2); }
javascript
{ "resource": "" }
q30896
ttone1
train
function ttone1 (reps, row, key, beat, amp) { var tr = row.split(' ').map(function (n) { return +n + key }) var r = score.repeat(reps, score.phrase(tr, beat, amp)) return score.map(function (e) { return randDur(randOct(e), beat) }, null, r) }
javascript
{ "resource": "" }
q30897
structureAs
train
function structureAs (name) { return function () { return [name].concat(isCollection(arguments[0]) ? arguments[0] : slice.call(arguments)) } }
javascript
{ "resource": "" }
q30898
Client
train
function Client(arg, port) { if (this instanceof Client === false) { return new Client(arg, port); } if (arg === undefined) { throw new TypeError('arg should be a host address, name or universe'); } this.host = Number.isInteger(arg) ? e131.getMulticastGroup(arg) : arg; this.port = port || e131.DEFAULT_PORT; this._socket = dgram.createSocket('udp4'); }
javascript
{ "resource": "" }
q30899
add_sp_n
train
function add_sp_n (cpu, mmu) { const n = mmu.readByte(cpu.pc + 1).signed(); const r = cpu.sp + n; const op = cpu.sp ^ n ^ r; cpu.f = 0; if ((op & 0x10) != 0) cpu.f |= FLAG_H; if ((op & 0x100) != 0) cpu.f |= FLAG_C; return r; }
javascript
{ "resource": "" }