_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q51200
train
function(element, block) { var selector = 'data-' + (block || this.keyName); if (element) { selector += '-' + element; } if (this.namespace) { selector += '="' + this.namespace + '"'; } return '[' + selector + ']'; }
javascript
{ "resource": "" }
q51201
train
function(content) { if (content.callback) { var namespaces = content.callback.split('.'), func = window, prev = func; for (var i = 0; i < namespaces.length; i++) { prev = func; func = func[namespaces[i]]; } func.call(prev, content); } this.fireEvent('process', [content]); this.hide(); }
javascript
{ "resource": "" }
q51202
train
function(element, key) { var value = element.data((this.keyName + '-' + key).toLowerCase()); if ($.type(value) === 'undefined') { value = this.options[key]; } return value; }
javascript
{ "resource": "" }
q51203
train
function(element, query) { if (!query) { return null; } element = $(element); if ($.type(query) === 'function') { return query.call(this, element); } return element.attr(query); }
javascript
{ "resource": "" }
q51204
train
function(options, params) { var ajax = {}; // Determine base options if ($.type(this.options.ajax) === 'object') { ajax = this.options.ajax; } // Set default options if ($.type(options) === 'string') { ajax.url = options; } else { $.extend(ajax, options); } // Prepare XHR object ajax.context = this; ajax.beforeSend = function(xhr) { xhr.url = ajax.url; xhr.cache = ((!ajax.type || ajax.type.toUpperCase() === 'GET') && this.options.cache); xhr.settings = ajax; xhr.params = params || {}; this.onRequestBefore.call(this, xhr); }; return $.ajax(ajax) .done(this.onRequestDone) .fail(this.onRequestFail); }
javascript
{ "resource": "" }
q51205
train
function(options, inheritFrom) { // Inherit options from a group if the data attribute exists // Do this first so responsive options can be triggered afterwards if (inheritFrom) { var group = this.readOption(inheritFrom, 'group'); if (group && options.groups[group]) { $.extend(options, options.groups[group]); } } var opts = Base.prototype.setOptions.call(this, options); // Inherit options from element data attributes if (inheritFrom) { opts = this.inheritOptions(opts, inheritFrom); } // Convert hover to mouseenter if (opts.mode && opts.mode === 'hover') { opts.mode = Toolkit.isTouch ? 'click' : 'mouseenter'; } this.options = opts; return opts; }
javascript
{ "resource": "" }
q51206
train
function(element, options) { var self = this; element = this.setElement(element).attr('role', 'tablist'); options = this.setOptions(options, element); // Find headers and cache the index of each header and set ARIA attributes this.headers = element.find(this.ns('header')).each(function(index) { $(this) .data('accordion-index', index) .attr({ role: 'tab', id: self.id('header', index) }) .aria({ controls: self.id('section', index), selected: false, expanded: false }); }); // Find sections and cache the height so we can use for sliding and set ARIA attributes this.sections = element.find(this.ns('section')).each(function(index) { $(this) .attr({ role: 'tabpanel', id: self.id('section', index) }) .aria('labelledby', self.id('header', index)) .conceal(); }); // Set events this.addEvents([ ['horizontalresize', 'window', $.debounce(this.calculate.bind(this))], ['{mode}', 'element', 'onShow', this.ns('header')] ]); // Initialize this.initialize(); // Jump to the index on page load this.calculate(); this.jump(options.defaultIndex); }
javascript
{ "resource": "" }
q51207
train
function(options) { options = this.setOptions(options); this.element = this.createElement(); // Generate loader elements this.loader = this.render(options.loaderTemplate).appendTo(this.element); this.message = this.loader.find(this.ns('message', 'loader')); if (options.showLoading) { this.message.html(Toolkit.messages.loading); } // Initialize this.initialize(); }
javascript
{ "resource": "" }
q51208
train
function() { this.fireEvent('hiding'); var count = this.count - 1; if (count <= 0) { this.count = 0; this.element.conceal(); } else { this.count = count; } this.hideLoader(); this.fireEvent('hidden', [(count <= 0)]); }
javascript
{ "resource": "" }
q51209
train
function() { this.fireEvent('showing'); var show = false; this.count++; if (this.count === 1) { this.element.reveal(); show = true; } this.showLoader(); this.fireEvent('shown', [show]); }
javascript
{ "resource": "" }
q51210
train
function() { var self = $(this), start, target; /** * There's a major bug in Android devices where `touchend` events do not fire * without calling `preventDefault()` in `touchstart` or `touchmove`. * Because of this, we have to hack-ily implement functionality into `touchmove`. * We also can't use `touchcancel` as that fires prematurely and unbinds our move event. * More information on these bugs can be found here: * * https://code.google.com/p/android/issues/detail?id=19827 * https://code.google.com/p/chromium/issues/detail?id=260732 * * Using `touchcancel` is also rather unpredictable, as described here: * * http://alxgbsn.co.uk/2011/12/23/different-ways-to-trigger-touchcancel-in-mobile-browsers/ */ function move(e) { var to = coords(e); // Trigger `preventDefault()` if `x` is larger than `y` (scrolling horizontally). // If we `preventDefault()` while scrolling vertically, the window will not scroll. if (abs(start.x - to.x) > abs(start.y - to.y)) { e.preventDefault(); } } /** * When `touchend` or `touchcancel` is triggered, clean up the swipe state. * Also unbind `touchmove` events until another swipe occurs. */ function cleanup() { start = target = null; swiping = false; self.off(moveEvent, move); } // Initialize the state when a touch occurs self.on(startEvent, function(e) { // Calling `preventDefault()` on start will disable clicking of elements (links, inputs, etc) // So only do it on an `img` element so it cannot be dragged if (!isTouch && e.target.tagName.toLowerCase() === 'img') { e.preventDefault(); } // Exit early if another swipe is occurring if (swiping) { return; } start = coords(e); target = e.target; swiping = true; // Non-touch devices don't make use of the move event if (isTouch) { self.on(moveEvent, move); } }); // Trigger the swipe event when the touch finishes self.on(stopEvent, function(e) { swipe(start, coords(e), self, target); cleanup(); }); // Reset the state when the touch is cancelled self.on('touchcancel', cleanup); }
javascript
{ "resource": "" }
q51211
cleanup
train
function cleanup() { start = target = null; swiping = false; self.off(moveEvent, move); }
javascript
{ "resource": "" }
q51212
train
function() { var options = this.options; return this.wrapper = this.render(options.wrapperTemplate) .addClass(Toolkit.buildTemplate(options.wrapperClass)) .attr('id', this.id('wrapper')) .appendTo('body'); }
javascript
{ "resource": "" }
q51213
train
function(node, callback) { var elements = this.elements, el, id = $(node).cache('toolkit.cid', function() { return Math.random().toString(32).substr(2); }); if (elements[id]) { el = elements[id]; } else { el = elements[id] = this.createElement(node); if ($.type(callback) === 'function') { callback.call(this, el); } } return this.element = el; }
javascript
{ "resource": "" }
q51214
train
function(e) { var node = $(e.currentTarget), element, isNode = (this.node && this.node.is(node)), cid = node.data('toolkit.cid'); // Set the current element based on the nodes composite ID if (cid && this.elements[cid]) { element = this.elements[cid]; } else { element = this.element; } if (element && element.is(':shown')) { // Touch devices should pass through on second click if (Toolkit.isTouch) { if (!isNode || this.node.prop('tagName').toLowerCase() !== 'a') { e.preventDefault(); } // Non-touch devices } else { e.preventDefault(); } if (isNode) { // Second click should close it if (this.options.mode === 'click') { this.hide(); } // Exit if the same node so it doesn't re-open return; } } else { e.preventDefault(); } this.show(node); }
javascript
{ "resource": "" }
q51215
train
function(node) { var target = this.readValue(node, this.options.getTarget); if (!target || target.substr(0, 1) !== '#') { throw new Error('Drop menu ' + target + ' does not exist'); } return $(target); }
javascript
{ "resource": "" }
q51216
train
function() { var element = this.element, node = this.node; // Clickout check if (!element && !node) { return; } this.fireEvent('hiding', [element, node]); element.conceal(); node .aria('toggled', false) .removeClass('is-active'); this.fireEvent('hidden', [element, node]); }
javascript
{ "resource": "" }
q51217
train
function(node) { this.node = node = $(node); var element = this.loadElement(node); this.fireEvent('showing', [element, node]); element.reveal(); node .aria('toggled', true) .addClass('is-active'); this.fireEvent('shown', [element, node]); }
javascript
{ "resource": "" }
q51218
train
function(e) { e.preventDefault(); // Hide previous drops this.hide(); // Toggle the menu var node = $(e.currentTarget), menu = this.loadElement(node); if (!menu.is(':shown')) { this.show(node); } else { this.hide(); } }
javascript
{ "resource": "" }
q51219
train
function(nodes, url, options) { if (Toolkit.isTouch) { return; // Flyouts shouldn't be usable on touch devices } this.nodes = $(nodes); options = this.setOptions(options); this.createWrapper(); if (options.mode === 'click') { this.addEvents([ ['click', 'document', 'onShowToggle', '{selector}'], ['resize', 'window', $.debounce(this.onHide.bind(this))] ]); } else { this.addEvents([ ['mouseenter', 'document', 'onShowToggle', '{selector}'], ['mouseenter', 'document', 'onEnter', '{selector}'], ['mouseleave', 'document', 'onLeave', '{selector}'] ]); } this.initialize(); // Load data from the URL if (url) { $.getJSON(url, function(response) { this.load(response); }.bind(this)); } }
javascript
{ "resource": "" }
q51220
train
function(data, depth) { depth = depth || 0; // If root, store the data if (!depth) { this.data = data; } // Store the data indexed by URL if (data.url) { this.dataMap[data.url] = data; } if (data.children) { for (var i = 0, l = data.children.length; i < l; i++) { this.load(data.children[i], depth + 1); } } }
javascript
{ "resource": "" }
q51221
train
function() { var options = this.options, node = this.node, element = this.loadElement(node); // Only position if the menu has children if (!element.children().length) { return; } this.fireEvent('showing'); var height = element.outerHeight(), coords = node.offset(), x = coords.left + options.xOffset, y = coords.top + options.yOffset + node.outerHeight(), windowScroll = $(window).height(), dir = 'left'; // If menu goes below half page, position it above if (y > (windowScroll / 2)) { y = coords.top - options.yOffset - height; } // Change position for RTL if (Toolkit.isRTL) { x = $(window).width() - coords.left - node.outerWidth(); dir = 'right'; } element .css('top', y) .css(dir, x) .reveal(); this.fireEvent('shown'); }
javascript
{ "resource": "" }
q51222
train
function(node) { node = $(node); var target = this.readValue(node, this.options.getUrl) || node.attr('href'); // When jumping from one node to another // Immediately hide the other menu and start the timer for the current one if (this.url && target !== this.url) { this.hide(); this.startTimer('show', this.options.showDelay); } // Set the state this.url = target; this.node = node.addClass('is-active'); // Load the menu this.loadElement(node, function(flyout) { flyout.addClass('is-root'); if (this.dataMap[target]) { this._buildMenu(flyout, this.dataMap[target]); } }); // Display immediately if click if (this.options.mode === 'click') { this.position(); } }
javascript
{ "resource": "" }
q51223
train
function(key, delay, args) { this.clearTimer(key); var func; if (key === 'show') { func = this.position; } else { func = this.hide; } if (func) { this.timers[key] = setTimeout(function() { func.apply(this, args || []); }.bind(this), delay); } }
javascript
{ "resource": "" }
q51224
train
function(parent) { parent = $(parent); parent.removeClass('is-open'); parent.children(this.ns('menu')) .removeAttr('style') .aria({ expanded: false, hidden: false }) .conceal(); this.fireEvent('hideChild', [parent]); }
javascript
{ "resource": "" }
q51225
train
function(parent) { var menu = parent.children(this.ns('menu')); if (!menu) { return; } menu.aria({ expanded: true, hidden: true }); // Alter width because of columns var children = menu.children(); menu.css('width', (children.outerWidth() * children.length) + 'px'); // Get sizes after menu positioning var win = $(window), winHeight = win.height() + win.scrollTop(), parentOffset = parent.offset(), parentHeight = parent.outerHeight(), oppositeClass = 'push-opposite'; // Display menu horizontally on opposite side if it spills out of viewport if (Toolkit.isRTL) { if ((parentOffset.left - menu.outerWidth()) < 0) { menu.addClass(oppositeClass); } else { menu.removeClass(oppositeClass); } } else { if ((parentOffset.left + parent.outerWidth() + menu.outerWidth()) >= win.width()) { menu.addClass(oppositeClass); } else { menu.removeClass(oppositeClass); } } // Reverse menu vertically if below half way fold if (parentOffset.top > (winHeight / 2)) { menu.css('top', '-' + (menu.outerHeight() - parentHeight) + 'px'); } else { menu.css('top', 0); } parent.addClass('is-open'); menu.reveal(); this.fireEvent('showChild', [parent]); }
javascript
{ "resource": "" }
q51226
train
function(element, options) { element = this.setElement(element); options = this.setOptions(options, element); if (options.checkbox) { element.find(options.checkbox).inputCheckbox(options); } if (options.radio) { element.find(options.radio).inputRadio(options); } if (options.select) { element.find(options.select).inputSelect(options); } this.initialize(); }
javascript
{ "resource": "" }
q51227
train
function() { var options = this.options, element = this.element; if (this.name === 'Input') { if (options.checkbox) { element.find(options.checkbox).each(function() { $(this).toolkit('inputCheckbox', 'destroy'); }); } if (options.radio) { element.find(options.radio).each(function() { $(this).toolkit('inputRadio', 'destroy'); }); } if (options.select) { element.find(options.select).each(function() { $(this).toolkit('inputSelect', 'destroy'); }); } // Check for the wrapper as some inputs may be initialized but not used. // Multi-selects using native controls for example. } else if (this.wrapper) { this.wrapper.replaceWith(element); element.removeAttr('style'); } }
javascript
{ "resource": "" }
q51228
train
function(from, to) { var classes = ($(from).attr('class') || '').replace(this.options.filterClasses, '').trim(); if (classes) { $(to).addClass(classes); } }
javascript
{ "resource": "" }
q51229
train
function() { var input = this.element, wrapper = this.render(this.options.template) .insertBefore(input) .append(input); if (this.options.copyClasses) { this.copyClasses(input, wrapper); } return wrapper; }
javascript
{ "resource": "" }
q51230
train
function(checkbox, options) { this.element = checkbox = $(checkbox); options = this.setOptions(options, checkbox); this.wrapper = this._buildWrapper(); // Create custom input this.input = this.render(options.checkboxTemplate) .attr('for', checkbox.attr('id')) .insertAfter(checkbox); // Initialize events this.initialize(); }
javascript
{ "resource": "" }
q51231
train
function(radio, options) { this.element = radio = $(radio); options = this.setOptions(options, radio); this.wrapper = this._buildWrapper(); // Create custom input this.input = this.render(options.radioTemplate) .attr('for', radio.attr('id')) .insertAfter(radio); // Initialize events this.initialize(); }
javascript
{ "resource": "" }
q51232
train
function(select, options) { this.element = select = $(select); options = this.setOptions(options, select); this.multiple = select.prop('multiple'); // Multiple selects must use native controls if (this.multiple && options.native) { return; } // Wrapping element this.wrapper = this._buildWrapper(); // Button element to open the drop menu this.input = this._buildButton(); // Initialize events this.addEvent('change', 'element', 'onChange'); if (!options.native) { this.addEvents([ ['blur', 'element', 'hide'], ['clickout', 'dropdown', 'hide'], ['click', 'input', 'onToggle'] ]); if (!this.multiple) { this.addEvent('keydown', 'window', 'onCycle'); } // Build custom dropdown when not in native this.dropdown = this._buildDropdown(); // Cant hide/invisible the real select or we lose focus/blur // So place it below .custom-input this.element.css('z-index', 1); } this.initialize(); // Trigger change immediately to update the label this.element.change(); }
javascript
{ "resource": "" }
q51233
train
function() { var options = this.options, button = this.render(options.selectTemplate) .find(this.ns('arrow', 'select')).html(this.render(options.arrowTemplate)).end() .find(this.ns('label', 'select')).html(Toolkit.messages.loading).end() .css('min-width', this.element.width()) .insertAfter(this.element); // Update the height of the native select input this.element.css('min-height', button.outerHeight()); return button; }
javascript
{ "resource": "" }
q51234
train
function() { var select = this.element, options = this.options, buildOption = this._buildOption.bind(this), renderTemplate = this.render.bind(this), dropdown = renderTemplate(options.optionsTemplate).attr('role', 'listbox').aria('multiselectable', this.multiple), list = $('<ul/>'), index = 0, self = this; // Must be set for `_buildOption()` this.dropdown = dropdown; select.children().each(function() { var optgroup = $(this); if (optgroup.prop('tagName').toLowerCase() === 'optgroup') { if (index === 0) { options.hideFirst = false; } list.append( renderTemplate(options.headingTemplate).text(optgroup.attr('label')) ); optgroup.children().each(function() { var option = $(this); if (optgroup.prop('disabled')) { option.prop('disabled', true); } if (option.prop('selected')) { self.index = index; } list.append( buildOption(option, index) ); index++; }); } else { if (optgroup.prop('selected')) { self.index = index; } list.append( buildOption(optgroup, index) ); index++; } }); if (options.hideSelected && !options.multiple) { dropdown.addClass('hide-selected'); } if (options.hideFirst) { dropdown.addClass('hide-first'); } if (this.multiple) { dropdown.addClass('is-multiple'); } this.wrapper.append(dropdown.append(list)); return dropdown; }
javascript
{ "resource": "" }
q51235
train
function(option, index) { var select = this.element, dropdown = this.dropdown, options = this.options, selected = option.prop('selected'), activeClass = 'is-active'; // Create elements var li = $('<li/>'), content = option.text(), description; if (selected) { li.addClass(activeClass); } if (description = this.readValue(option, options.getDescription)) { content += this.render(options.descTemplate).html(description).toString(); } var a = $('<a/>', { html: content, href: 'javascript:;', role: 'option' }).aria('selected', selected); if (this.options.copyClasses) { this.copyClasses(option, li); } li.append(a); // Attach no events for disabled options if (option.prop('disabled')) { li.addClass('is-disabled'); a.aria('disabled', true); return li; } // Set events if (this.multiple) { a.click(function() { var self = $(this), selected = false; if (option.prop('selected')) { self.parent().removeClass(activeClass); } else { selected = true; self.parent().addClass(activeClass); } option.prop('selected', selected); self.aria('selected', selected); select.change(); }); } else { var self = this; a.click(function() { dropdown .find('li').removeClass(activeClass).end() .find('a').aria('selected', false); $(this) .aria('selected', true) .parent() .addClass(activeClass); self.hide(); self.index = index; select.val(option.val()); select.change(); }); } return li; }
javascript
{ "resource": "" }
q51236
train
function(index, step, options) { var hideFirst = this.options.hideFirst; index += step; while (($.type(options[index]) === 'undefined') || options[index].disabled || (index === 0 && hideFirst)) { index += step; if (index >= options.length) { index = 0; } else if (index < 0) { index = options.length - 1; } } return index; }
javascript
{ "resource": "" }
q51237
train
function(e) { var select = $(e.target), options = select.find('option'), opts = this.options, selected = [], label = [], self = this; // Fetch label from selected option options.each(function() { if (this.selected) { selected.push( this ); label.push( self.readValue(this, opts.getOptionLabel) || this.textContent ); } }); // Reformat label if needed if (this.multiple) { var title = this.readValue(select, opts.getDefaultLabel), format = opts.multipleFormat, count = label.length; // Use default title if nothing selected if (!label.length && title) { label = title; // Display a counter for label } else if (format === 'count') { label = opts.countMessage .replace('{count}', count) .replace('{total}', options.length); // Display options as a list for label } else if (format === 'list') { var limit = opts.listLimit; label = label.splice(0, limit).join(', '); if (limit < count) { label += ' ...'; } } } else { label = label.join(', '); } // Set the label select.parent() .find(this.ns('label', 'select')) .text(label); this.fireEvent('change', [select.val(), selected]); }
javascript
{ "resource": "" }
q51238
train
function(e) { if (!this.dropdown.is(':shown')) { return; } if ($.inArray(e.keyCode, [38, 40, 13, 27]) >= 0) { e.preventDefault(); } else { return; } var options = this.element.find('option'), items = this.dropdown.find('a'), activeClass = 'is-active', index = this.index; switch (e.keyCode) { case 13: // enter case 27: // esc this.hide(); return; case 38: // up index = this._loop(index, -1, options); break; case 40: // down index = this._loop(index, 1, options); break; } options.prop('selected', false); options[index].selected = true; items.parent().removeClass(activeClass); items.eq(index).parent().addClass(activeClass); this.index = index; this.element.change(); }
javascript
{ "resource": "" }
q51239
train
function(container, options) { container = $(container); options = this.setOptions(options, container); this.items = container.find(this.options.lazyClass); if (container.css('overflow') === 'auto') { this.container = container; } var callback = $.throttle(this.load.bind(this), options.throttle); // Set events this.addEvents([ ['scroll', 'container', callback], ['resize', 'window', callback], ['ready', 'document', 'onReady'] ]); this.initialize(); }
javascript
{ "resource": "" }
q51240
train
function() { if (this.loaded >= this.items.length) { this.shutdown(); return; } this.fireEvent('loading'); this.items.each(function(index, item) { if (item && this.inViewport(item)) { this.show(item, index); } }.bind(this)); this.fireEvent('loaded'); }
javascript
{ "resource": "" }
q51241
train
function(node, index) { node = $(node); this.fireEvent('showing', [node]); // Set the item being loaded for so that events can be fired this.element = node.removeClass(this.options.lazyClass.substr(1)); // Replace src attributes on images node.find('img').each(function() { var image = $(this), src; if (Toolkit.isRetina) { src = image.data('src-retina'); } if (!src) { src = image.data('src'); } if (src) { image.attr('src', src); } }); // Replace item with null since removing from the array causes it to break this.items.splice(index, 1, null); this.loaded++; this.fireEvent('shown', [node]); }
javascript
{ "resource": "" }
q51242
train
function(element, options) { element = this.setElement(element); options = this.setOptions(options, element); // Add class and set relative positioning if (!element.is('body')) { element.addClass('is-maskable'); var position = element.css('position'); if (!position || position === 'static') { element.css('position', 'relative'); } } // Find a mask or create it var mask = element.find('> ' + this.ns()); if (!mask.length) { mask = this.render(options.template); } this.setMask(mask); if (options.selector) { this.addEvent('click', 'document', 'toggle', options.selector); } this.initialize(); }
javascript
{ "resource": "" }
q51243
train
function(mask) { var options = this.options, message; // Prepare mask mask.addClass('hide').appendTo(this.element); if (this.element.is('body')) { mask.css('position', 'fixed'); } if (options.revealOnClick) { mask.click(this.hide.bind(this)); } this.mask = mask; // Create message if it does not exist message = mask.find(this.ns('message')); if (!message.length && options.messageContent) { message = this.render(options.messageTemplate) .html(options.messageContent) .appendTo(mask); } this.message = message; }
javascript
{ "resource": "" }
q51244
train
function(nodes, options) { this.nodes = $(nodes); options = this.setOptions(options); this.element = this.createElement() .attr('role', 'dialog') .aria('labelledby', this.id('title')) .aria('describedby', this.id('content')); // Enable fullscreen if (options.fullScreen) { this.element.addClass('is-fullscreen'); } // Setup blackout if (options.blackout) { this.blackout = Blackout.instance(); } // Initialize events this.addEvents([ ['keydown', 'window', 'onKeydown'], ['click', 'document', 'onShow', '{selector}'], ['click', 'element', 'hide', this.ns('close')], ['click', 'element', 'onSubmit', this.ns('submit')] ]); if (options.clickout) { this.addEvent('click', 'element', 'onHide'); } this.initialize(); }
javascript
{ "resource": "" }
q51245
train
function(content) { // AJAX is currently loading if (content === true) { return; } // Hide blackout loading message if (this.blackout) { this.blackout.hideLoader(); } this.fireEvent('showing'); var body = this.element.find(this.ns('content')); body.html(content); this.fireEvent('load', [content]); // Reveal modal this.element.reveal(); // Resize modal if (this.options.fullScreen) { body.css('min-height', $(window).height()); } this.fireEvent('shown'); }
javascript
{ "resource": "" }
q51246
train
function(node, content) { if (node) { this.node = node = $(node); if (!content) { content = this.readValue(node, this.readOption(node, 'getContent')) || node.attr('href'); } } // Show blackout if the element is hidden // If it is visible, the blackout count will break if (this.blackout && !this.element.is(':shown')) { this.blackout.show(); } // Restrict scrolling if (this.options.stopScroll) { $('body').addClass('no-scroll'); } this.loadContent(content); }
javascript
{ "resource": "" }
q51247
train
function() { var form = this.element.find('form:first'); if (!form) { return; } this.fireEvent('submit', [form]); var options = { url: form.attr('action'), type: (form.attr('method') || 'post').toUpperCase() }; if (window.FormData) { options.processData = false; options.contentType = false; options.data = new FormData(form[0]); } else { options.data = form.serialize(); } this.requestData(options); }
javascript
{ "resource": "" }
q51248
train
function(element, options) { element = this.setElement(element).attr('role', 'complementary').conceal(); options = this.setOptions(options, element); var animation = options.animation; // Touch devices cannot use squish if (Toolkit.isTouch && animation === 'squish') { options.animation = animation = 'push'; } // Cannot have multiple non-overlayed or non-squished sidebars open if (animation !== 'on-top' && animation !== 'squish') { options.hideOthers = true; } // Setup container this.container = element.parent().addClass(animation); this.primary = element.siblings('[data-offcanvas-content]').attr('role', 'main'); this.secondary = element.siblings('[data-offcanvas-sidebar]'); // Determine the side this.side = element.data('offcanvas-sidebar') || 'left'; this.opposite = (this.side === 'left') ? 'right' : 'left'; // Initialize events this.addEvents([ ['ready', 'document', 'onReady'], ['resize', 'window', 'onResize'] ]); if (options.swipe) { if (this.side === 'left') { this.addEvents([ ['swipeleft', 'element', 'hide'], ['swiperight', 'container', 'onSwipe'] ]); } else { this.addEvents([ ['swipeleft', 'container', 'onSwipe'], ['swiperight', 'element', 'hide'] ]); } } if (options.selector) { this.addEvent('click', 'document', 'toggle', options.selector); } this.initialize(); }
javascript
{ "resource": "" }
q51249
train
function() { this.fireEvent('hiding'); this.container.removeClass('move-' + this.opposite); this.element .conceal() .removeClass('is-expanded') .aria('expanded', false); if (this.options.stopScroll) { $('body').removeClass('no-scroll'); } this.fireEvent('hidden'); }
javascript
{ "resource": "" }
q51250
train
function() { var options = this.options; if (options.hideOthers) { this.secondary.each(function() { var sidebar = $(this); if (sidebar.hasClass('is-expanded')) { sidebar.toolkit('offCanvas', 'hide'); } }); } this.fireEvent('showing'); this.container.addClass('move-' + this.opposite); this.element .reveal() .addClass('is-expanded') .aria('expanded', true); if (options.stopScroll) { $('body').addClass('no-scroll'); } this.fireEvent('shown'); }
javascript
{ "resource": "" }
q51251
train
function() { if (!this.options.openOnLoad || this._loaded) { return; } var sidebar = this.element, inner = this.primary, transClass = 'no-transition'; sidebar.addClass(transClass); inner.addClass(transClass); this.show(); // Transitions will still occur unless we place in a timeout setTimeout(function() { sidebar.removeClass(transClass); inner.removeClass(transClass); }, 15); // IE needs a minimum of 15 this._loaded = true; }
javascript
{ "resource": "" }
q51252
train
function(e) { e.preventDefault(); var target = $(e.target), selector = '[data-offcanvas-sidebar]'; if (target.is(selector) || target.parents(selector).length) { return; } this.show(); }
javascript
{ "resource": "" }
q51253
train
function(element, options) { element = this.setElement(element); options = this.setOptions(options, element); // Setup classes and ARIA element .attr('role', 'complementary') .addClass(options.animation); // Determine before calculations var initialTop = element[0].style.top; // jQuery sometimes returns auto this.initialTop = (initialTop === 'auto') ? 0 : parseInt(initialTop, 10); this.elementTop = element.offset().top; // Initialize events var throttle = options.throttle; this.addEvents([ ['scroll', 'window', $.throttle(this.onScroll.bind(this), throttle)], ['resize', 'window', $.throttle(this.onResize.bind(this), throttle)], ['ready', 'document', 'onResize'] ]); this.initialize(); }
javascript
{ "resource": "" }
q51254
train
function() { var win = $(window), options = this.options, element = this.element, parent = options.context ? element.parents(options.context) : element.parent(); this.viewport = { width: win.width(), height: win.height() }; this.elementHeight = element.outerHeight(true); // Include margin this.parentHeight = parent.height(); // Exclude padding this.parentTop = parent.offset().top; // Disable pin if element is larger than the viewport if (options.lock && this.elementHeight >= this.viewport.height) { this.active = false; // Enable pin if the parent is larger than the child } else { this.active = (element.is(':visible') && this.parentHeight > this.elementHeight); } }
javascript
{ "resource": "" }
q51255
train
function() { var options = this.options; if (options.calculate) { this.calculate(); } if (!this.active) { return; } var eHeight = this.elementHeight, eTop = this.elementTop, pHeight = this.parentHeight, pTop = this.parentTop, cssTop = this.initialTop, scrollTop = $(window).scrollTop(), pos = {}, x = options.xOffset, y = 0; // Scroll is above the parent, remove pin inline styles if (scrollTop < pTop || scrollTop === 0) { if (this.pinned) { this.unpin(); } return; } // Don't extend out the bottom var elementMaxPos = scrollTop + eHeight, parentMaxHeight = pHeight + pTop; // Swap positioning of the fixed menu once it reaches the parent borders if (options.fixed) { if (elementMaxPos >= parentMaxHeight) { y = 'auto'; pos.position = 'absolute'; pos.bottom = 0; } else if (scrollTop >= eTop) { y = options.yOffset; pos.position = 'fixed'; pos.bottom = 'auto'; } // Stop positioning absolute menu once it exits the parent } else { pos.position = 'absolute'; if (elementMaxPos >= parentMaxHeight) { y += (pHeight - eHeight); } else { y += (scrollTop - pTop) + options.yOffset; } // Don't go lower than default top if (cssTop && y < cssTop) { y = cssTop; } } pos[options.location] = x; pos.top = y; this.element .css(pos) .addClass('is-pinned'); this.pinned = true; this.fireEvent('pinned'); }
javascript
{ "resource": "" }
q51256
train
function(nodes, options) { this.nodes = $(nodes); options = this.setOptions(options); this.createWrapper(); // Remove title attributes if (options.getTitle === 'title') { options.getTitle = 'data-' + this.keyName + '-title'; this.nodes.each(function(i, node) { $(node).attr(options.getTitle, $(node).attr('title')).removeAttr('title'); }); } // Initialize events this.addEvents([ ['{mode}', 'document', 'onShowToggle', '{selector}'], ['resize', 'window', $.debounce(this.onHide.bind(this))] ]); if (options.mode === 'click') { this.addEvent('clickout', 'document', 'hide'); } else { this.addEvent('mouseleave', 'document', 'hide', '{selector}'); } this.initialize(); }
javascript
{ "resource": "" }
q51257
train
function(node, content) { this.node = node = $(node).addClass('is-active'); // Load the new element this.loadElement(node, function(tooltip) { tooltip .addClass(this.readOption(node, 'position')) .attr('role', 'tooltip'); }); // Load the content this.loadContent(content || this.readValue(node, this.readOption(node, 'getContent'))); }
javascript
{ "resource": "" }
q51258
train
function(e) { e.preventDefault(); var options = this.options; this.element.reveal().positionTo(options.position, e, { left: options.xOffset, top: options.yOffset }, true); }
javascript
{ "resource": "" }
q51259
train
function(nodes, options) { options = options || {}; options.mode = 'click'; // Click only options.follow = false; // Disable mouse follow Tooltip.prototype.constructor.call(this, nodes, options); }
javascript
{ "resource": "" }
q51260
train
function(element, options) { var sections, tabs, self = this; element = this.setElement(element); options = this.setOptions(options, element); // Determine cookie name if (!options.cookie) { options.cookie = element.attr('id'); } // Find all the sections and set ARIA attributes this.sections = sections = element.find(this.ns('section')).each(function(index, section) { section = $(section); section .attr('role', 'tabpanel') .attr('id', section.attr('id') || self.id('section', index)) .aria('labelledby', self.id('tab', index)) .conceal(); }); // Find the nav and set ARIA attributes this.nav = element.find(this.ns('nav')) .attr('role', 'tablist'); // Find the tabs within the nav and set ARIA attributes this.tabs = tabs = this.nav.find('a').each(function(index) { $(this) .data('tab-index', index) .attr({ role: 'tab', id: self.id('tab', index) }) .aria({ controls: sections.eq(index).attr('id'), selected: false, expanded: false }) .removeClass('is-active'); }); // Initialize events this.addEvent('{mode}', 'element', 'onShow', this.ns('nav') + ' a'); if (options.mode !== 'click' && options.preventDefault) { this.addEvent('click', 'element', function(e) { e.preventDefault(); }, this.ns('nav') + ' a'); } this.initialize(); // Trigger default tab to display var index = null; if (options.persistState) { if (options.cookie && $.cookie) { index = $.cookie('toolkit.tab.' + options.cookie); } if (index === null && options.loadFragment && location.hash) { index = tabs.filter(function() { return ($(this).attr('href') === location.hash); }).eq(0).data('tab-index'); } } if (!tabs[index]) { index = options.defaultIndex; } this.jump(index); }
javascript
{ "resource": "" }
q51261
train
function(tab) { tab = $(tab); var index = tab.data('tab-index'), section = this.sections.eq(index), options = this.options, url = this.readValue(tab, this.readOption(tab, 'getUrl')); this.fireEvent('showing', [this.index]); // Load content for AJAX requests if (url.substr(0, 10) !== 'javascript' && url.substr(0, 1) !== '#') { this.loadContent(url, { section: section }); } // Toggle tabs this.tabs .aria('toggled', false) .removeClass('is-active'); // Toggle sections if (index === this.index && options.collapsible) { if (section.is(':shown')) { section.conceal(); } else { tab.aria('toggled', true).addClass('is-active'); section.reveal(); } } else { this.hide(); tab.aria('toggled', true).addClass('is-active'); section.reveal(); } // Persist the state using a cookie if (options.persistState && $.cookie) { $.cookie('toolkit.tab.' + options.cookie, index, { expires: options.cookieDuration }); } this.index = index; this.node = tab; this.fireEvent('shown', [index]); }
javascript
{ "resource": "" }
q51262
train
function(e) { if (this.options.preventDefault || e.currentTarget.getAttribute('href').substr(0, 1) !== '#') { e.preventDefault(); } this.show(e.currentTarget); }
javascript
{ "resource": "" }
q51263
train
function(element, options) { this.nodes = element = $(element); // Set to nodes so instances are unset during destroy() options = this.setOptions(options, element); // Create the toasts wrapper this.createWrapper() .addClass(options.position) .attr('role', 'log') .aria({ relevant: 'additions', hidden: 'false' }); this.initialize(); }
javascript
{ "resource": "" }
q51264
train
function(content, options) { options = $.extend({}, this.options, options || {}); var self = this, toast = this.render(options.template) .addClass(options.animation) .attr('role', 'note') .html(content) .conceal() .prependTo(this.wrapper); this.fireEvent('create', [toast]); // Set a timeout to trigger show transition setTimeout(function() { self.show(toast); }, 15); // IE needs a minimum of 15 // Set a timeout to remove the toast if (options.duration) { setTimeout(function() { self.hide(toast); }, options.duration + 15); } }
javascript
{ "resource": "" }
q51265
train
function(element) { element = $(element); // Pass the element since it gets removed this.fireEvent('hiding', [element]); element.transitionend(function() { element.remove(); this.fireEvent('hidden'); }.bind(this)).conceal(); }
javascript
{ "resource": "" }
q51266
train
function(input, options) { input = $(input); if (input.prop('tagName').toLowerCase() !== 'input') { throw new Error('TypeAhead must be initialized on an input field'); } var self = this; options = this.setOptions(options, input); this.element = this.createElement() .attr('role', 'listbox') .aria('multiselectable', false); // The input field to listen against this.input = input; // Use default callbacks $.each({ sorter: 'sort', matcher: 'match', builder: 'build' }, function(key, fn) { if (options[key] === false) { return; } var callback; if (options[key] === null || $.type(options[key]) !== 'function') { callback = self[fn]; } else { callback = options[key]; } options[key] = callback.bind(self); }); // Prefetch source data from URL if (options.prefetch && $.type(options.source) === 'string') { var url = options.source; $.getJSON(url, options.query, function(items) { self.cache[url] = items; }); } // Enable shadow inputs if (options.shadow) { this.wrapper = this.render(this.options.shadowTemplate); this.shadow = this.input.clone() .addClass('is-shadow') .removeAttr('id') .prop('readonly', true) .aria('readonly', true); this.input .addClass('not-shadow') .replaceWith(this.wrapper); this.wrapper .append(this.shadow) .append(this.input); } // Set ARIA after shadow so that attributes are not inherited input .attr({ autocomplete: 'off', autocapitalize: 'off', autocorrect: 'off', spellcheck: 'false', role: 'combobox' }) .aria({ autocomplete: 'list', owns: this.element.attr('id'), expanded: false }); // Initialize events this.addEvents([ ['keyup', 'input', 'onLookup'], ['keydown', 'input', 'onCycle'], ['clickout', 'element', 'hide'], ['resize', 'window', $.debounce(this.onHide.bind(this))] ]); this.initialize(); }
javascript
{ "resource": "" }
q51267
train
function(item) { var a = $('<a/>', { href: 'javascript:;', role: 'option', 'aria-selected': 'false' }); a.append( this.render(this.options.titleTemplate).html(this.highlight(item.title)) ); if (item.description) { a.append( this.render(this.options.descTemplate).html(item.description) ); } return a; }
javascript
{ "resource": "" }
q51268
train
function() { this.fireEvent('hiding'); if (this.shadow) { this.shadow.val(''); } this.input.aria('expanded', false); this.element.conceal(); this.fireEvent('hidden'); }
javascript
{ "resource": "" }
q51269
train
function(item) { var terms = this.term.replace(/[\-\[\]\{\}()*+?.,\\^$|#]/g, '\\$&').split(' '), options = this.options, callback = function(match) { return this.render(options.highlightTemplate).html(match).toString(); }.bind(this); for (var i = 0, t; t = terms[i]; i++) { item = item.replace(new RegExp(t, 'ig'), callback); } return item; }
javascript
{ "resource": "" }
q51270
train
function() { if (!this.items.length) { this.hide(); return; } this.fireEvent('showing'); var iPos = this.input.offset(); this.element .css('top', iPos.top + this.input.outerHeight()) .css(Toolkit.isRTL ? 'right' : 'left', iPos.left) .reveal(); this.input.aria('expanded', true); this.fireEvent('shown'); }
javascript
{ "resource": "" }
q51271
train
function(index, event) { this.index = index; var rows = this.element.find('li'); rows .removeClass('is-active') .find('a') .aria('selected', false); // Select if (index >= 0) { if (this.items[index]) { var item = this.items[index]; rows.eq(index) .addClass('is-active') .find('a') .aria('selected', true); this.input.val(item.title); this.fireEvent(event || 'select', [item, index]); } // Reset } else { this.input.val(this.term); this.fireEvent('reset'); } }
javascript
{ "resource": "" }
q51272
train
function(items) { return items.sort(function(a, b) { return a.title.localeCompare(b.title); }); }
javascript
{ "resource": "" }
q51273
train
function(items) { if (!this.term.length || !items.length) { this.hide(); return; } var options = this.options, term = this.term, categories = { _empty_: [] }, item, list = $('<ul/>'); // Reset this.items = []; this.index = -1; // Sort and match the list of items if ($.type(options.sorter) === 'function') { items = options.sorter(items); } if ($.type(options.matcher) === 'function') { items = items.filter(function(item) { return options.matcher(item, term); }); } // Group the items into categories for (var i = 0; item = items[i]; i++) { if (item.category) { if (!categories[item.category]) { categories[item.category] = []; } categories[item.category].push(item); } else { categories._empty_.push(item); } } // Loop through the items and build the markup var results = [], count = 0; $.each(categories, function(category, items) { var elements = []; if (category !== '_empty_') { results.push(null); elements.push( this.render(options.headingTemplate).append( $('<span/>', { text: category }) ) ); } for (var i = 0, a; item = items[i]; i++) { if (count >= options.itemLimit) { break; } a = options.builder(item); a.on({ mouseover: this.rewind.bind(this), click: $.proxy(this.onSelect, this, results.length) }); elements.push( $('<li/>').append(a) ); results.push(item); count++; } list.append(elements); }.bind(this)); // Append list this.element.empty().append(list); // Set the current result set to the items list // This will be used for index cycling this.items = results; // Cache the result set to the term // Filter out null categories so that we can re-use the cache this.cache[term.toLowerCase()] = results.filter(function(item) { return (item !== null); }); this.fireEvent('load'); // Apply the shadow text this._shadow(); // Position the list this.position(); }
javascript
{ "resource": "" }
q51274
train
function() { if (!this.shadow) { return; } var term = this.input.val(), termLower = term.toLowerCase(), value = ''; if (this.cache[termLower] && this.cache[termLower][0]) { var title = this.cache[termLower][0].title; if (title.toLowerCase().indexOf(termLower) === 0) { value = term + title.substr(term.length, (title.length - term.length)); } } this.shadow.val(value); }
javascript
{ "resource": "" }
q51275
train
function(e) { var items = this.items, length = Math.min(this.options.itemLimit, Math.max(0, items.length)), event = 'cycle'; if (!length || !this.element.is(':shown')) { return; } switch (e.keyCode) { // Cycle upwards (up) case 38: this.index -= (items[this.index - 1] ? 1 : 2); // category check if (this.index < 0) { this.index = length; } break; // Cycle downwards (down) case 40: this.index += (items[this.index + 1] ? 1 : 2); // category check if (this.index >= length) { this.index = -1; } break; // Select first (tab) case 9: e.preventDefault(); var i = 0; while (!this.items[i]) { i++; } event = 'select'; this.index = i; this.hide(); break; // Select current index (enter) case 13: e.preventDefault(); event = 'select'; this.hide(); break; // Reset (esc) case 27: this.index = -1; this.hide(); break; // Cancel others default: return; } if (this.shadow) { this.shadow.val(''); } // Select the item this.select(this.index, event); }
javascript
{ "resource": "" }
q51276
train
function() { var term = this.term, options = this.options, sourceType = $.type(options.source); // Check the cache first if (this.cache[term.toLowerCase()]) { this.source(this.cache[term.toLowerCase()]); // Use the response of an AJAX request } else if (sourceType === 'string') { var url = options.source, cache = this.cache[url]; if (cache) { this.source(cache); } else { var query = options.query; query.term = term; $.getJSON(url, query, this.source.bind(this)); } // Use a literal array list } else if (sourceType === 'array') { this.source(options.source); // Use the return of a function } else if (sourceType === 'function') { var response = options.source.call(this); if (response) { this.source(response); } } else { throw new Error('Invalid TypeAhead source type'); } }
javascript
{ "resource": "" }
q51277
train
function(e) { if ($.inArray(e.keyCode, [38, 40, 27, 9, 13]) >= 0) { return; // Handle with onCycle() } clearTimeout(this.timer); var term = this.input.val().trim(); if (term.length < this.options.minLength) { this.fireEvent('reset'); this.hide(); } else { this._shadow(); this.lookup(term); } }
javascript
{ "resource": "" }
q51278
height
train
function height(node) { return node ? (1 + Math.max(height(node.left), height(node.right))) : 0; }
javascript
{ "resource": "" }
q51279
rotateLeft
train
function rotateLeft (node) { var rightNode = node.right; node.right = rightNode.left; if (rightNode.left) rightNode.left.parent = node; rightNode.parent = node.parent; if (rightNode.parent) { if (rightNode.parent.left === node) { rightNode.parent.left = rightNode; } else { rightNode.parent.right = rightNode; } } node.parent = rightNode; rightNode.left = node; node.balanceFactor += 1; if (rightNode.balanceFactor < 0) { node.balanceFactor -= rightNode.balanceFactor; } rightNode.balanceFactor += 1; if (node.balanceFactor > 0) { rightNode.balanceFactor += node.balanceFactor; } return rightNode; }
javascript
{ "resource": "" }
q51280
train
function(repo, version, hash, meta, outDir) { var url, tempRepoDir, packageJSONData, self = this; if (meta.vPrefix) { version = 'v' + version; } // Automatically track and cleanup files at exit temp.track(); url = createGitUrl(self.options.baseurl, repo, self.options.reposuffix, self.auth); return createTempDir().then(function(tempDir) { tempRepoDir = tempDir; return exportGitRepo(tempRepoDir, version, url, self.execOpt, self.options.shallowclone); }).then(function() { return readPackageJSON(tempRepoDir); }).then(function(data) { packageJSONData = data; return moveRepoToOutDir(tempRepoDir, outDir); }).then(function() { return packageJSONData; }); }
javascript
{ "resource": "" }
q51281
train
function(pjson, dir) { var main = pjson.main || ''; var libDir = pjson.directories && (pjson.directories.dist || pjson.directories.lib) || '.'; // convert to windows-style paths if necessary main = path.normalize(main); libDir = path.normalize(libDir); if (main.indexOf('!') !== -1) { return; } function checkMain(main, libDir) { if (!main) { return Promise.resolve(false); } if (main.substr(main.length - 3, 3) === '.js') { main = main.substr(0, main.length - 3); } return new Promise(function(resolve) { fs.exists(path.resolve(dir, libDir || '.', main) + '.js', function(exists) { resolve(exists); }); }); } return checkMain(main, libDir) .then(function(hasMain) { if (hasMain) { return; } return asp(fs.readFile)(path.resolve(dir, 'bower.json')) .then(function(bowerJson) { try { bowerJson = JSON.parse(bowerJson); } catch(e) { return; } main = bowerJson.main || ''; if (main instanceof Array) { main = main[0]; } return checkMain(main); }, function() {}) .then(function(hasBowerMain) { if (!hasBowerMain) { return; } pjson.main = main; }); }); }
javascript
{ "resource": "" }
q51282
train
function () { var createPublisher = function (publisherDiv) { var innerDeferred = $.Deferred(); var getContainer = function () { if (publisherDiv) { return publisherDiv; } if (typeof _this.screenSharingContainer === 'function') { return document.querySelector(_this.screenSharingContainer('publisher', 'screen')); } else { return _this.screenSharingContainer; } } var container = getContainer(); var properties = _this.localScreenProperties || _this.localScreenProperties || _defaultScreenProperties; _this.publisher = OT.initPublisher(container, properties, function (error) { if (error) { _triggerEvent('screenSharingError', error); innerDeferred.reject(_.extend(_.omit(error, 'messsage'), { message: 'Error starting the screen sharing', })); } else { _this.publisher.on('mediaStopped', function () { end(); }); innerDeferred.resolve(); } }); return innerDeferred.promise(); }; var outerDeferred = $.Deferred(); if (_this.annotation && _this.externalWindow) { _log(_logEventData.enableAnnotations, _logEventData.variationSuccess); _accPack.setupExternalAnnotation() .then(function (annotationWindow) { _this.annotationWindow = annotationWindow || null; var annotationElements = annotationWindow.createContainerElements(); createPublisher(annotationElements.publisher) .then(function () { outerDeferred.resolve(annotationElements.annotation); }); }); } else { createPublisher() .then(function () { outerDeferred.resolve(); }); } return outerDeferred.promise(); }
javascript
{ "resource": "" }
q51283
train
function (annotationContainer) { _session.publish(_this.publisher, function (error) { if (error) { // Let's write our own error message var customError = _.omit(error, 'message'); if (error.code === 1500 && navigator.userAgent.indexOf('Firefox') !== -1) { $('#dialog-form-ff').toggle(); } else { var errorMessage; if (error.code === 1010) { errorMessage = 'Check your network connection'; } else { errorMessage = 'Error sharing the screen'; } customError.message = errorMessage; _triggerEvent('screenSharingError', customError); _log(_logEventData.actionStart, _logEventData.variationError); } } else { if (_this.annotation && _this.externalWindow) { _accPack.linkAnnotation(_this.publisher, annotationContainer, _this.annotationWindow); _log(_logEventData.actionInitialize, _logEventData.variationSuccess); } _active = true; _triggerEvent('startScreenSharing', _this.publisher); _log(_logEventData.actionStart, _logEventData.variationSuccess); } }); }
javascript
{ "resource": "" }
q51284
train
function(){ if(Object.keys(app.getServers()).length === 0){ quick.logger.shutdown(shutdown); } else{ setTimeout(tryShutdown, 200); } }
javascript
{ "resource": "" }
q51285
Light
train
function Light(constr) { this.client = constr.client; this.id = constr.id; // Used to target the light this.address = constr.address; this.port = constr.port; this.label = null; this.status = 'on'; this.seenOnDiscovery = constr.seenOnDiscovery; }
javascript
{ "resource": "" }
q51286
Client
train
function Client() { EventEmitter.call(this); this.debug = false; this.socket = dgram.createSocket('udp4'); this.isSocketBound = false; this.devices = {}; this.port = null; this.messagesQueue = []; this.sendTimer = null; this.discoveryTimer = null; this.discoveryPacketSequence = 0; this.messageHandlers = [{ type: 'stateService', callback: this.processDiscoveryPacket.bind(this) }, { type: 'stateLabel', callback: this.processLabelPacket.bind(this) }, { type: 'stateLight', callback: this.processLabelPacket.bind(this) }]; this.sequenceNumber = 0; this.lightOfflineTolerance = 3; this.messageHandlerTimeout = 45000; // 45 sec this.resendPacketDelay = 150; this.resendMaxTimes = 5; this.source = utils.getRandomHexString(8); this.broadcastAddress = '255.255.255.255'; }
javascript
{ "resource": "" }
q51287
trimLine
train
function trimLine(line) { if (!line) { return null; } if (Array.isArray(line)) { return line.map(trimLine); } return String(line).trim(); }
javascript
{ "resource": "" }
q51288
removeComments
train
function removeComments(line) { var commentStartIndex = line.indexOf('#'); if (commentStartIndex > -1) { return line.substr(0, commentStartIndex); } return line; }
javascript
{ "resource": "" }
q51289
formatUserAgent
train
function formatUserAgent(userAgent) { var formattedUserAgent = userAgent.toLowerCase(); // Strip the version number from robot/1.0 user agents var idx = formattedUserAgent.indexOf('/'); if (idx > -1) { formattedUserAgent = formattedUserAgent.substr(0, idx); } return formattedUserAgent.trim(); }
javascript
{ "resource": "" }
q51290
parsePattern
train
function parsePattern(pattern) { var regexSpecialChars = /[\-\[\]\/\{\}\(\)\+\?\.\\\^\$\|]/g; // Treat consecutive wildcards as one (#12) var wildCardPattern = /\*+/g; var endOfLinePattern = /\\\$$/; pattern = normaliseEncoding(pattern) if (pattern.indexOf('*') < 0 && pattern.indexOf('$') < 0) { return pattern; } pattern = pattern .replace(regexSpecialChars, '\\$&') .replace(wildCardPattern, '(?:.*)') .replace(endOfLinePattern, '$'); return new RegExp(pattern); }
javascript
{ "resource": "" }
q51291
findRule
train
function findRule(path, rules) { var matchingRule = null; for (var i=0; i < rules.length; i++) { var rule = rules[i]; if (typeof rule.pattern === 'string') { if (path.indexOf(rule.pattern) !== 0) { continue; } // The longest matching rule takes precedence if (!matchingRule || rule.pattern.length > matchingRule.pattern.length) { matchingRule = rule; } // The first matching pattern takes precedence // over all other rules including other patterns } else if (rule.pattern.test(path)) { return rule; } } return matchingRule; }
javascript
{ "resource": "" }
q51292
asJson
train
function asJson(entity, shallow) { let json; try { json = JSON.stringify(asObject(entity, shallow)); } catch (error) { json = ''; } return json; }
javascript
{ "resource": "" }
q51293
getFlat
train
function getFlat(entity, json) { let flat = { entity : asObject(entity, true), collections: getCollectionsCompact(entity) }; if (json) { flat = JSON.stringify(flat); } return flat; }
javascript
{ "resource": "" }
q51294
getPropertyForAssociation
train
function getPropertyForAssociation(forEntity, entity) { let associations = forEntity.getMeta().fetch('associations'); return Object.keys(associations).filter(key => { return associations[key].entity === entity.getResource(); })[0]; }
javascript
{ "resource": "" }
q51295
trigger
train
function trigger (state, eventName) { var args = [].slice.call(arguments, 1) state.emitter.emit.apply(state.emitter, args) return this }
javascript
{ "resource": "" }
q51296
train
function( key ) { if( this.data[ key ] == null ) { return this.data[ key ] } if( Array.isArray( this.data[ key ] ) ) { return this.data[ key ].map( function( prop ) { return prop.clone() }) } else { return this.data[ key ].clone() } }
javascript
{ "resource": "" }
q51297
train
function( key, value, params ) { var prop = new vCard.Property( key, value, params ) this.addProperty( prop ) return this }
javascript
{ "resource": "" }
q51298
train
function( prop ) { var key = prop._field if( Array.isArray( this.data[ key ] ) ) { this.data[ key ].push( prop ) } else if( this.data[ key ] != null ) { this.data[ key ] = [ this.data[ key ], prop ] } else { this.data[ key ] = prop } return this }
javascript
{ "resource": "" }
q51299
train
function( value ) { // Normalize & split var lines = vCard.normalize( value ) .split( /\r?\n/g ) // Keep begin and end markers // for eventual error messages var begin = lines[0] var version = lines[1] var end = lines[ lines.length - 1 ] if( !/BEGIN:VCARD/i.test( begin ) ) throw new SyntaxError( 'Invalid vCard: Expected "BEGIN:VCARD" but found "'+ begin +'"' ) if( !/END:VCARD/i.test( end ) ) throw new SyntaxError( 'Invalid vCard: Expected "END:VCARD" but found "'+ end +'"' ) // TODO: For version 2.1, the VERSION can be anywhere between BEGIN & END if( !/VERSION:\d\.\d/i.test( version ) ) throw new SyntaxError( 'Invalid vCard: Expected "VERSION:\\d.\\d" but found "'+ version +'"' ) this.version = version.substring( 8, 11 ) if( !vCard.isSupported( this.version ) ) throw new Error( 'Unsupported version "' + this.version + '"' ) this.data = vCard.parseLines( lines ) return this }
javascript
{ "resource": "" }