_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q12100
initRedis
train
function initRedis() { return when.promise((resolve, reject) => { redis.get(name, (err, res) => { if(err) { memStore = {}; } else if(res) { memStore = JSON.parse(res); } else { memStore = {}; } resolve(true); }); }); }
javascript
{ "resource": "" }
q12101
syncRedis
train
function syncRedis() { // if memStore has changed... if(JSON.stringify(memCache) !== JSON.stringify(memStore)) { return when.promise((resolve, reject) => { var serializedStore = JSON.stringify(memStore); redis.set(name, serializedStore, err => { if(err) { reject(err); } else { resolve(true); } }); }) .delay(syncInterval) .catch(err => { console.log(err.stack); return when(true); }) .finally(() => { memCache = _.cloneDeep(memStore); if(active) syncRedis(memStore); return when(true); }); } // else memStore has not changed... else { return when(true) .delay(syncInterval) .then(() => { if(active) syncRedis(memStore); return when(true); }); } }
javascript
{ "resource": "" }
q12102
getKoaLogger
train
function getKoaLogger (logger4js, options) { if (typeof options === 'object') { options = options || {} } else if (options) { options = { format: options } } else { options = {} } let thislogger = logger4js let level = levels.getLevel(options.level, levels.INFO) let fmt = options.format || DEFAULT_FORMAT let nolog = options.nolog ? createNoLogCondition(options.nolog) : null return async (ctx, next) => { // mount safety if (ctx.request._logging) { await next() return } // nologs if (nolog && nolog.test(ctx.originalUrl)) { await next() return } if (thislogger.isLevelEnabled(level) || options.level === 'auto') { let start = new Date() let writeHead = ctx.response.writeHead // flag as logging ctx.request._logging = true // proxy for statusCode. ctx.response.writeHead = function (code, headers) { ctx.response.writeHead = writeHead ctx.response.writeHead(code, headers) ctx.response.__statusCode = code ctx.response.__headers = headers || {} // status code response level handling if (options.level === 'auto') { level = levels.INFO if (code >= 300) level = levels.WARN if (code >= 400) level = levels.ERROR } else { level = levels.getLevel(options.level, levels.INFO) } } await next() // hook on end request to emit the log entry of the HTTP request. ctx.response.responseTime = new Date() - start // status code response level handling if (ctx.res.statusCode && options.level === 'auto') { level = levels.INFO if (ctx.res.statusCode >= 300) level = levels.WARN if (ctx.res.statusCode >= 400) level = levels.ERROR } if (thislogger.isLevelEnabled(level)) { let combinedTokens = assembleTokens(ctx, options.tokens || []) if (typeof fmt === 'function') { let line = fmt(ctx, function (str) { return format(str, combinedTokens) }) if (line) thislogger.log(level, line) } else { thislogger.log(level, format(fmt, combinedTokens)) } } } else { // ensure next gets always called await next() } } }
javascript
{ "resource": "" }
q12103
format
train
function format (str, tokens) { for (let i = 0; i < tokens.length; i++) { str = str.replace(tokens[i].token, tokens[i].replacement) } return str }
javascript
{ "resource": "" }
q12104
createNoLogCondition
train
function createNoLogCondition (nolog) { let regexp = null if (nolog) { if (nolog instanceof RegExp) { regexp = nolog } if (typeof nolog === 'string') { regexp = new RegExp(nolog) } if (Array.isArray(nolog)) { let regexpsAsStrings = nolog.map((o) => (o.source ? o.source : o)) regexp = new RegExp(regexpsAsStrings.join('|')) } } return regexp }
javascript
{ "resource": "" }
q12105
log
train
function log(msg, color) { if (typeof(msg) === 'object') { for (var item in msg) { if (msg.hasOwnProperty(item)) { if(color && color in $.util.colors) { $.util.log($.util.colors[color](msg[item])); } $.util.log($.util.colors.lightgreen(msg[item])); } } } else { $.util.log($.util.colors.green(msg)); } }
javascript
{ "resource": "" }
q12106
clean
train
function clean(path, done) { log('Cleaning: ' + $.util.colors.green(path)); return del(path, done); }
javascript
{ "resource": "" }
q12107
bytediffFormatter
train
function bytediffFormatter(data) { var difference = (data.savings > 0) ? ' smaller.' : ' larger.'; return data.fileName + ' went from ' + (data.startSize / 1000).toFixed(2) + ' kB to ' + (data.endSize / 1000).toFixed(2) + ' kB and is ' + formatPercent(1 - data.percent, 2) + '%' + difference; }
javascript
{ "resource": "" }
q12108
train
function() { let options = {}; tap(Mix.paths.root('.babelrc'), babelrc => { if (File.exists(babelrc)) { options = JSON.parse(File.find(babelrc).read()); } }); if (this.babelConfig) { options = webpackMerge.smart(options, this.babelConfig); } return webpackMerge.smart( { cacheDirectory: true, presets: [ [ 'env', { modules: false, targets: { browsers: ['> 2%'], uglify: true } } ] ], plugins: [ 'transform-object-rest-spread', [ 'transform-runtime', { polyfill: false, helpers: false } ] ] }, options ); }
javascript
{ "resource": "" }
q12109
MixDefinitionsPlugin
train
function MixDefinitionsPlugin(envPath) { expand( dotenv.config({ path: envPath || Mix.paths.root('.env') }) ); }
javascript
{ "resource": "" }
q12110
train
function (name) { // @option imagePath: String // `Icon.Default` will try to auto-detect the location of // the blue icon images. If you are placing these images in a // non-standard way, set this option to point to the right // path, before any marker is added to a map. // Caution: do not use this option with inline base64 image(s). var imagePath = this.options.imagePath || L.Icon.Default.imagePath || ''; // Deprecated (IconDefault.imagePath), backwards-compatibility only if (this._needsInit) { // Modifying imagePath option after _getIconUrl has been called // once in this instance of IconDefault will no longer have any // effect. this._initializeOptions(imagePath); } return imagePath + L.Icon.prototype._getIconUrl.call(this, name); }
javascript
{ "resource": "" }
q12111
train
function (imagePath) { this._setOptions('icon', _detectIconOptions, imagePath); this._setOptions('shadow', _detectIconOptions, imagePath); this._setOptions('popup', _detectDivOverlayOptions); this._setOptions('tooltip', _detectDivOverlayOptions); this._needsInit = false; }
javascript
{ "resource": "" }
q12112
train
function (name, detectorFn, imagePath) { var options = this.options, prefix = options.classNamePrefix, optionValues = detectorFn(prefix + name, imagePath); for (var optionName in optionValues) { options[name + optionName] = options[name + optionName] || optionValues[optionName]; } }
javascript
{ "resource": "" }
q12113
_getStyle
train
function _getStyle(el, style) { return L.DomUtil.getStyle(el, style) || L.DomUtil.getStyle(el, _kebabToCamelCase(style)); }
javascript
{ "resource": "" }
q12114
fadeIn
train
function fadeIn(el) { el.style.opacity = 0; el.style.display = "block"; (function fadeIn() { let val = parseFloat(el.style.opacity); if (! ((val += .1) > 1)) { el.style.opacity = val; setTimeout(fadeIn, 40); } })(); }
javascript
{ "resource": "" }
q12115
copy
train
function copy(from, to) { var name; for (name in from) { if (from.hasOwnProperty(name)) { to[name] = from[name]; } } }
javascript
{ "resource": "" }
q12116
matchesCustom
train
function matchesCustom(ctx, opts) { if (opts.custom) { return opts.custom.call(ctx); } return false; }
javascript
{ "resource": "" }
q12117
matchesPath
train
function matchesPath(requestedUrl, opts) { var paths = !opts.path || Array.isArray(opts.path) ? opts.path : [opts.path]; if (paths) { return paths.some(function(p) { return (typeof p === 'string' && p === requestedUrl.pathname) || (p instanceof RegExp && !! p.exec(requestedUrl.pathname)); }); } return false; }
javascript
{ "resource": "" }
q12118
matchesExtension
train
function matchesExtension(requestedUrl, opts) { var exts = !opts.ext || Array.isArray(opts.ext) ? opts.ext : [opts.ext]; if (exts) { return exts.some(function(ext) { return requestedUrl.pathname.substr(ext.length * -1) === ext; }); } }
javascript
{ "resource": "" }
q12119
matchesMethod
train
function matchesMethod(method, opts) { var methods = !opts.method || Array.isArray(opts.method) ? opts.method : [opts.method]; if (methods) { return !!~methods.indexOf(method); } }
javascript
{ "resource": "" }
q12120
startRtm
train
function startRtm (token) { api.rtm.start(token, (err, bot) => { if (err) { return console.log(err) } bot.on(/hello/, (bot, message) => { bot.reply(message, 'GO CUBS') }) bot.on(/howdy/, (bot, message) => { bot.reply(message, 'GO TRIBE') }) }) }
javascript
{ "resource": "" }
q12121
sendToClient
train
function sendToClient (message, client) { return new Promise((resolve, reject) => { try { client.send(JSON.stringify(message), (e) => { if (e) { logger.error(`could not send rtm message to client`, e) return reject(e) } }) } catch (e) { logger.error(`could not send rtm message to client`, e) return reject(e) } resolve() }) }
javascript
{ "resource": "" }
q12122
scrollableElement
train
function scrollableElement(els) { for (var i = 0, argLength = arguments.length; i <argLength; i++) { var el = arguments[i], $scrollElement = $(el); if ($scrollElement.scrollTop()> 0) { return el; } else { $scrollElement.scrollTop(1); var isScrollable = $scrollElement.scrollTop()> 0; $scrollElement.scrollTop(0); if (isScrollable) { return el; } } } return []; }
javascript
{ "resource": "" }
q12123
instantiationError
train
function instantiationError(injector, originalException, originalStack, key) { return injectionError(injector, key, function () { var /** @type {?} */ first = stringify(this.keys[0].token); return getOriginalError(this).message + ": Error during instantiation of " + first + "!" + constructResolvingPath(this.keys) + "."; }, originalException); }
javascript
{ "resource": "" }
q12124
templateVisitAll
train
function templateVisitAll(visitor, asts, context) { if (context === void 0) { context = null; } var /** @type {?} */ result = []; var /** @type {?} */ visit = visitor.visit ? function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } : function (ast) { return ast.visit(visitor, context); }; asts.forEach(function (ast) { var /** @type {?} */ astResult = visit(ast); if (astResult) { result.push(astResult); } }); return result; }
javascript
{ "resource": "" }
q12125
can
train
function can(rbac, action, resource, cb) { // check existance of permission rbac.getPermission(action, resource, (err, permission) => { if (err) { return cb(err); } if (!permission) { return cb(null, false); } // check user additional permissions if (indexOf(this.permissions, permission.name) !== -1) { return cb(null, true); } if (!this.role) { return cb(null, false); } // check permission inside user role return rbac.can(this.role, action, resource, cb); }); return this; }
javascript
{ "resource": "" }
q12126
addPermission
train
function addPermission(rbac, action, resource, cb) { rbac.getPermission(action, resource, (err, permission) => { if (err) { return cb(err); } if (!permission) { return cb(new Error('Permission not exists')); } if (indexOf(this.permissions, permission.name) !== -1) { return cb(new Error('Permission is already assigned')); } this.permissions.push(permission.name); return this.save((err2, user) => { if (err2) { return cb(err2); } if (!user) { return cb(new Error('User is undefined')); } return cb(null, true); }); }); return this; }
javascript
{ "resource": "" }
q12127
hasRole
train
function hasRole(rbac, role, cb) { if (!this.role) { cb(null, false); return this; } // check existance of permission rbac.hasRole(this.role, role, cb); return this; }
javascript
{ "resource": "" }
q12128
addcalendarExtenderToDateInputs
train
function addcalendarExtenderToDateInputs () { //get and loop all the input[type=date]s in the page that dont have "haveCal" class yet var dateInputs = document.querySelectorAll('input[type=date]:not(.haveCal)'); [].forEach.call(dateInputs, function (dateInput) { //call calendarExtender function on the input new calendarExtender(dateInput); //mark that it have calendar dateInput.classList.add('haveCal'); }); }
javascript
{ "resource": "" }
q12129
train
function(data, done) { try { // Retrieve all the dependencies _.forEach(data._dependencies || {}, function(value, key) { if(this.sandbox[key] !== undefined) { // Do nothing if the dependency is already defined return; } this.sandbox[key] = module.parent.require(value); }.bind(this)); // Remove the dependencies property delete data._dependencies; } catch(e) { // Stop execution and return the MODULE_NOT_FOUND error return done(e); } // Iterate over all the data objects async.eachSeries(Object.keys(data), function(key, next) { _this.result[key] = {}; var value = data[key]; try { if(!value._model) { // Throw an error if the model could not be found throw new Error('Please provide a _model property that describes which database model should be used.'); } var modelName = value._model; // Remove model and unique properties delete value._model; // retrieve the model depending on the name provided var Model = mongoose.model(modelName); async.series([ function(callback) { if(_this.options.dropCollections === true) { // Drop the collection mongoose.connection.db.dropCollection(Model.collection.name, function(err) { callback(); }); } else { callback(); } }, function(callback) { async.eachSeries(Object.keys(value), function(k, innerNext) { var modelData = value[k], data = _this._unwind(modelData); // Create the model Model.create(data, function(err, result) { if(err) { // Do not stop execution if an error occurs return innerNext(err); } _this.result[key][k] = result; innerNext(); }); }, callback); } ], next); } catch(err) { // If the model does not exist, stop the execution return next(err); } }, function(err) { if(err) { // Make sure to not return the result return done(err); } done(undefined, _this.result); }); }
javascript
{ "resource": "" }
q12130
train
function(ref) { var keys = ref.split('.'), key = keys.shift(), result = _this.result[key]; if(!result) { // If the result does not exist, return an empty throw new TypeError('Could not read property \'' + key + '\' from undefined'); } // Iterate over all the keys and find the property while((key = keys.shift())) { result = result[key]; } if(_.isObject(result) && !_.isArray(result)) { // Test if the result we have is an object. This means the user wants to reference // to the _id of the object. if(!result._id) { // If no _id property exists, throw a TypeError that the property could not be found throw new TypeError('Could not read property \'_id\' of ' + JSON.stringify(result)); } return result._id; } return result; }
javascript
{ "resource": "" }
q12131
train
function(data, options, callback) { if(_.isFunction(options)) { // Set the correct callback function callback = options; options = {}; } // Create a deferred object for the promise var def = Q.defer(); // If no callback is provided, use a noop function callback = callback || function() {}; // Clear earlier results and options _this.result = {}; _this.options = {}; _this.sandbox = vm.createContext(); // Defaulting the options _this.options = _.extend(_.clone(DEFAULT_OPTIONS), options); if(_this.options.dropCollections === true && _this.options.dropDatabase === true) { // Only one of the two flags can be turned on. If both are true, this means the // user set the dropCollections itself and this should have higher priority then // the default values. _this.options.dropDatabase = false; } if(_this.options.dropDatabase === true) { // Make sure to drop the database first mongoose.connection.db.dropDatabase(function(err) { if(err) { // Stop seeding if an error occurred return done(err); } // Start seeding when the database is dropped _this._seed(_.cloneDeep(data), done); }); } else { // Do not drop the entire database, start seeding _this._seed(_.cloneDeep(data), done); } /** * This method will be invoked when the seeding is completed or when something * went wrong. This method will then call the callback and rejects or resolves * the promise object. This way, users of the library can use both. * * @param {*} err [description] * @param {Object} result [description] */ function done(err, result) { if(err) { def.reject(err); callback(err); return; } def.resolve(result); callback(undefined, result); } // Return the promise return def.promise; }
javascript
{ "resource": "" }
q12132
done
train
function done(err, result) { if(err) { def.reject(err); callback(err); return; } def.resolve(result); callback(undefined, result); }
javascript
{ "resource": "" }
q12133
proxyConfig
train
function proxyConfig(path) { const config = {} const {endpointsExtension} = tryGetGraphQLProjectConfig() if (endpointsExtension) { const graphqlEndpoint = endpointsExtension.getEndpoint() const {url: target, headers} = graphqlEndpoint const changeOrigin = true const pathRewrite = {} pathRewrite[`^${path}`] = '' config[path] = {changeOrigin, headers, pathRewrite, target} } return config }
javascript
{ "resource": "" }
q12134
train
function(source, options) { try { return prettify(source, options); } catch (e) { console.error(e); console.warn('HTML beautification failed.'); } }
javascript
{ "resource": "" }
q12135
refresh
train
function refresh() { if( active ) { requestAnimFrame( refresh ); for( var i = 0, len = lists.length; i < len; i++ ) { lists[i].update(); } } }
javascript
{ "resource": "" }
q12136
add
train
function add( element, options ) { // Only allow ul/ol if( !element.nodeName || /^(ul|li)$/i.test( element.nodeName ) === false ) { return false; } // Delete duplicates (but continue and re-bind this list to get the // latest properties and list items) else if( contains( element ) ) { remove( element ); } var list = IS_TOUCH_DEVICE ? new TouchList( element ) : new List( element ); // Handle options if( options && options.live ) { list.syncInterval = setInterval( function() { list.sync.call( list ); }, LIVE_INTERVAL ); } // Synchronize the list with the DOM list.sync(); // Add this element to the collection lists.push( list ); // Start refreshing if this was the first list to be added if( lists.length === 1 ) { active = true; refresh(); } }
javascript
{ "resource": "" }
q12137
remove
train
function remove( element ) { for( var i = 0; i < lists.length; i++ ) { var list = lists[i]; if( list.element == element ) { list.destroy(); lists.splice( i, 1 ); i--; } } // Stopped refreshing if the last list was removed if( lists.length === 0 ) { active = false; } }
javascript
{ "resource": "" }
q12138
contains
train
function contains( element ) { for( var i = 0, len = lists.length; i < len; i++ ) { if( lists[i].element == element ) { return true; } } return false; }
javascript
{ "resource": "" }
q12139
batch
train
function batch( target, method, options ) { var i, len; // Selector if( typeof target === 'string' ) { var targets = document.querySelectorAll( target ); for( i = 0, len = targets.length; i < len; i++ ) { method.call( null, targets[i], options ); } } // Array (jQuery) else if( typeof target === 'object' && typeof target.length === 'number' ) { for( i = 0, len = target.length; i < len; i++ ) { method.call( null, target[i], options ); } } // Single element else if( target.nodeName ) { method.call( null, target, options ); } else { throw 'Stroll target was of unexpected type.'; } }
javascript
{ "resource": "" }
q12140
TouchList
train
function TouchList( element ) { this.element = element; this.element.style.overflow = 'hidden'; this.top = { value: 0, natural: 0 }; this.touch = { value: 0, offset: 0, start: 0, previous: 0, lastMove: Date.now(), accellerateTimeout: -1, isAccellerating: false, isActive: false }; this.velocity = 0; }
javascript
{ "resource": "" }
q12141
displayMetrics
train
function displayMetrics(file) { var prefix = ''; var code = fs.readFileSync(file, 'utf-8'); // We remove any shebang at the start of the file since that isn't valid // Javascript and will trip up the parser. code = code.replace(/^#!.*\n/, ''); var metrics = complexity(code); // Walk the metrics structure and add each member to the table rows. function walk(data, name) { // Fade out anonymous functions. if (name.indexOf('anon@') === 0) { name = name.grey; } rows.push([ prefix + name, data.ecc, data.arity, data.codeLines, data.commentLines, Math.round(100 * data.commentLines / data.codeLines) ]); // Add two spaces to the prefix before the next depth, to illustrate // the hierarchy in the table. prefix += ' '; _.each(data.children, walk); prefix = prefix.slice(0,prefix.length-2); } walk(metrics, path.basename(file).blue.bold); }
javascript
{ "resource": "" }
q12142
walk
train
function walk(data, name) { // Fade out anonymous functions. if (name.indexOf('anon@') === 0) { name = name.grey; } rows.push([ prefix + name, data.ecc, data.arity, data.codeLines, data.commentLines, Math.round(100 * data.commentLines / data.codeLines) ]); // Add two spaces to the prefix before the next depth, to illustrate // the hierarchy in the table. prefix += ' '; _.each(data.children, walk); prefix = prefix.slice(0,prefix.length-2); }
javascript
{ "resource": "" }
q12143
train
function(v) { var t = this.t, //refers to the element's style property filters = t.filter || _getStyle(this.data, "filter") || "", val = (this.s + this.c * v) | 0, skip; if (val === 100) { //for older versions of IE that need to use a filter to apply opacity, we should remove the filter if opacity hits 1 in order to improve performance, but make sure there isn't a transform (matrix) or gradient in the filters. if (filters.indexOf("atrix(") === -1 && filters.indexOf("radient(") === -1 && filters.indexOf("oader(") === -1) { t.removeAttribute("filter"); skip = (!_getStyle(this.data, "filter")); //if a class is applied that has an alpha filter, it will take effect (we don't want that), so re-apply our alpha filter in that case. We must first remove it and then check. } else { t.filter = filters.replace(_alphaFilterExp, ""); skip = true; } } if (!skip) { if (this.xn1) { t.filter = filters = filters || ("alpha(opacity=" + val + ")"); //works around bug in IE7/8 that prevents changes to "visibility" from being applied properly if the filter is changed to a different alpha on the same frame. } if (filters.indexOf("pacity") === -1) { //only used if browser doesn't support the standard opacity style property (IE 7 and 8). We omit the "O" to avoid case-sensitivity issues if (val !== 0 || !this.xn1) { //bugs in IE7/8 won't render the filter properly if opacity is ADDED on the same frame/render as "visibility" changes (this.xn1 is 1 if this tween is an "autoAlpha" tween) t.filter = filters + " alpha(opacity=" + val + ")"; //we round the value because otherwise, bugs in IE7/8 can prevent "visibility" changes from being applied properly. } } else { t.filter = filters.replace(_opacityExp, "opacity=" + val); } } }
javascript
{ "resource": "" }
q12144
isVisualViewport
train
function isVisualViewport ( name ) { var viewport = isString( name ) && name.toLowerCase(); if ( name && !viewport ) throw new Error( "Invalid viewport option: " + name ); if ( viewport && viewport !== "visual" && viewport !== "layout" ) throw new Error( "Invalid viewport name: " + name ); return viewport === "visual"; }
javascript
{ "resource": "" }
q12145
restoreGlobalDocument
train
function restoreGlobalDocument ( previousState ) { if ( previousState.documentElement.modified ) document.documentElement.style.overflowX = previousState.documentElement.styleOverflowX; if ( previousState.body.modified ) document.body.style.overflowX = previousState.body.styleOverflowX; }
javascript
{ "resource": "" }
q12146
guessDocumentSize
train
function guessDocumentSize( dimension, _document ) { var ddE = _document.documentElement; return Math.max( ddE.body[ "scroll" + dimension ], _document[ "scroll" + dimension ], ddE.body[ "offset" + dimension ], _document[ "offset" + dimension ], _document[ "client" + dimension ] ); }
javascript
{ "resource": "" }
q12147
getWindowInnerSize
train
function getWindowInnerSize ( dimension, _window ) { var size = ( _window || window ).visualViewport ? ( _window || window ).visualViewport[ dimension.toLowerCase() ] : ( _window || window )[ "inner" + dimension]; // Check for fractions. Exclude undefined return values in browsers which don't support window.innerWidth/Height. if ( size ) checkForFractions( size ); return size; }
javascript
{ "resource": "" }
q12148
getIEVersion
train
function getIEVersion () { var userAgent, userAgentTestRx; if ( ieVersion === undefined ) { ieVersion = false; userAgent = navigator && navigator.userAgent; if ( navigator && navigator.appName === "Microsoft Internet Explorer" && userAgent ) { userAgentTestRx = new RegExp( "MSIE ([0-9]{1,}[\.0-9]{0,})" ); // jshint ignore:line if ( userAgentTestRx.exec( userAgent ) != null ) ieVersion = parseFloat( RegExp.$1 ); } } return ieVersion; }
javascript
{ "resource": "" }
q12149
train
function() { this.$container = $(this.options.buttonContainer); this.$container.on('show.bs.dropdown', this.options.onDropdownShow); this.$container.on('hide.bs.dropdown', this.options.onDropdownHide); this.$container.on('shown.bs.dropdown', this.options.onDropdownShown); this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden); }
javascript
{ "resource": "" }
q12150
train
function() { if (typeof this.options.selectAllValue === 'number') { this.options.selectAllValue = this.options.selectAllValue.toString(); } var alreadyHasSelectAll = this.hasSelectAll(); if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) { // Check whether to add a divider after the select all. if (this.options.includeSelectAllDivider) { this.$ul.prepend($(this.options.templates.divider)); } var $li = $(this.options.templates.li); $('label', $li).addClass("checkbox"); if (this.options.enableHTML) { $('label', $li).html(" " + this.options.selectAllText); } else { $('label', $li).text(" " + this.options.selectAllText); } if (this.options.selectAllName) { $('label', $li).prepend('<input type="checkbox" name="' + this.options.selectAllName + '" />'); } else { $('label', $li).prepend('<input type="checkbox" />'); } var $checkbox = $('input', $li); $checkbox.val(this.options.selectAllValue); $li.addClass("multiselect-item multiselect-all"); $checkbox.parent().parent() .addClass('multiselect-all'); this.$ul.prepend($li); $checkbox.prop('checked', false); } }
javascript
{ "resource": "" }
q12151
train
function (justVisible) { var justVisible = typeof justVisible === 'undefined' ? true : justVisible; if(justVisible) { var visibleCheckboxes = $("li input[type='checkbox']:not(:disabled)", this.$ul).filter(":visible"); visibleCheckboxes.prop('checked', false); var values = visibleCheckboxes.map(function() { return $(this).val(); }).get(); $("option:enabled", this.$select).filter(function(index) { return $.inArray($(this).val(), values) !== -1; }).prop('selected', false); if (this.options.selectedClass) { $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").removeClass(this.options.selectedClass); } } else { $("li input[type='checkbox']:enabled", this.$ul).prop('checked', false); $("option:enabled", this.$select).prop('selected', false); if (this.options.selectedClass) { $("li:not(.divider):not(.disabled)", this.$ul).removeClass(this.options.selectedClass); } } }
javascript
{ "resource": "" }
q12152
train
function() { this.$ul.html(''); // Important to distinguish between radios and checkboxes. this.options.multiple = this.$select.attr('multiple') === "multiple"; this.buildSelectAll(); this.buildDropdownOptions(); this.buildFilter(); this.updateButtonText(); this.updateSelectAll(); if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) { this.disable(); } else { this.enable(); } if (this.options.dropRight) { this.$ul.addClass('pull-right'); } }
javascript
{ "resource": "" }
q12153
train
function() { if (this.hasSelectAll()) { var allBoxes = $("li:not(.multiselect-item):not(.filter-hidden) input:enabled", this.$ul); var allBoxesLength = allBoxes.length; var checkedBoxesLength = allBoxes.filter(":checked").length; var selectAllLi = $("li.multiselect-all", this.$ul); var selectAllInput = selectAllLi.find("input"); if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) { selectAllInput.prop("checked", true); selectAllLi.addClass(this.options.selectedClass); this.options.onSelectAll(); } else { selectAllInput.prop("checked", false); selectAllLi.removeClass(this.options.selectedClass); } } }
javascript
{ "resource": "" }
q12154
extend
train
function extend(obj, extObj) { var a, b, i; if (arguments.length > 2) { for (a = 1, b = arguments.length; a < b; a += 1) { extend(obj, arguments[a]); } } else { for (i in extObj) { if (extObj.hasOwnProperty(i)) { obj[i] = extObj[i]; } } } return obj; }
javascript
{ "resource": "" }
q12155
toCamel
train
function toCamel(string) { if (string === null || string === undefined) { return ""; } return String(string).replace(/((\s|\-|\.)+[a-z0-9])/g, function($1) { return $1.toUpperCase().replace(/(\s|\-|\.)/g, ""); }); }
javascript
{ "resource": "" }
q12156
removeClass
train
function removeClass(element, value) { var class2remove = value || "", cur = element.nodeType === 1 && (element.className ? (" " + element.className + " ").replace(rclass, " ") : ""); if (cur) { while (cur.indexOf(" " + class2remove + " ") >= 0) { cur = cur.replace(" " + class2remove + " ", " "); } element.className = value ? trim(cur) : ""; } }
javascript
{ "resource": "" }
q12157
setVersion
train
function setVersion(versionType, versionFull) { versionType.version = versionFull; var versionArray = versionFull.split("."); if (versionArray.length > 0) { versionArray = versionArray.reverse(); versionType.major = versionArray.pop(); if (versionArray.length > 0) { versionType.minor = versionArray.pop(); if (versionArray.length > 0) { versionArray = versionArray.reverse(); versionType.patch = versionArray.join("."); } else { versionType.patch = "0"; } } else { versionType.minor = "0"; } } else { versionType.major = "0"; } }
javascript
{ "resource": "" }
q12158
getBoundingClientRectCompat
train
function getBoundingClientRectCompat ( elem ) { var elemRect = elem.getBoundingClientRect(); if ( elemRect.width === undefined || elemRect.height === undefined ) { // Fix for IE8 elemRect = { top: elemRect.top, left: elemRect.left, bottom: elemRect.bottom, right: elemRect.right, width: elemRect.right - elemRect.left, height: elemRect.bottom - elemRect.top }; } return elemRect; }
javascript
{ "resource": "" }
q12159
getAppliedOverflows
train
function getAppliedOverflows ( props, createBooleans ) { var status = {}; // Establish the applied overflow (e.g. overflowX: "scroll") status.overflowX = props.overflowX || props.overflow || "visible"; status.overflowY = props.overflowY || props.overflow || "visible"; // Create the derived boolean status properties (e.g overflowScrollX: true) if ( createBooleans ) { $.each( [ "Visible", "Auto", "Scroll", "Hidden" ], function ( index, type ) { var lcType = type.toLowerCase(); status["overflow" + type + "X"] = status.overflowX === lcType; status["overflow" + type + "Y"] = status.overflowY === lcType; } ); } return status; }
javascript
{ "resource": "" }
q12160
getAppliedViewportOverflows
train
function getAppliedViewportOverflows ( documentElementProps, bodyProps ) { var _window = getAppliedOverflows( documentElementProps, false ), body = getAppliedOverflows( bodyProps, false ), consolidated = { window: {}, body: {} }; // Handle the interdependent relation between body and window (documentElement) overflow if ( _window.overflowX === "visible" ) { // If the window overflow is set to "visible", body props get transferred to the window, body changes to // "visible". (Nothing really changes if both are set to "visible".) consolidated.body.overflowX = "visible"; consolidated.window.overflowX = body.overflowX; } else { // No transfer of properties. // - If body overflow is "visible", it remains that way, and the window stays as it is. // - If body and window are set to properties other than "visible", they keep their divergent settings. consolidated.body.overflowX = body.overflowX; consolidated.window.overflowX = _window.overflowX; } // Repeat for overflowY if ( _window.overflowY === "visible" ) { consolidated.body.overflowY = "visible"; consolidated.window.overflowY = body.overflowY; } else { consolidated.body.overflowY = body.overflowY; consolidated.window.overflowY = _window.overflowY; } // window.overflow(X/Y): "visible" actually means "auto" because scroll bars appear as needed; transform if ( consolidated.window.overflowX === "visible" ) consolidated.window.overflowX = "auto"; if ( consolidated.window.overflowY === "visible" ) consolidated.window.overflowY = "auto"; // In iOS, window.overflow(X/Y): "hidden" actually means "auto"; transform if ( isIOS() ) { if ( consolidated.window.overflowX === "hidden" ) consolidated.window.overflowX = "auto"; if ( consolidated.window.overflowY === "hidden" ) consolidated.window.overflowY = "auto"; } // Add the boolean status properties to the result consolidated.window = getAppliedOverflows( consolidated.window, true ); consolidated.body = getAppliedOverflows( consolidated.body, true ); return consolidated; }
javascript
{ "resource": "" }
q12161
scaleLog
train
function scaleLog () { var zoomFactor = $.pinchZoomFactor(), logProps = { top: ( initialLogProps.top / zoomFactor ) + "px", left: ( initialLogProps.left / zoomFactor ) + "px", paddingTop: ( initialLogProps.paddingTop / zoomFactor ) + "px", paddingLeft: ( initialLogProps.paddingLeft / zoomFactor ) + "px", paddingBottom: ( initialLogProps.paddingBottom / zoomFactor ) + "px", paddingRight: ( initialLogProps.paddingRight / zoomFactor ) + "px", minWidth: ( initialLogProps.minWidth / zoomFactor ) + "px", maxWidth: ( initialLogProps.maxWidth / zoomFactor ) + "px" }, dtProps = { fontSize: ( initialLogProps.dtFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.dtLineHeight / zoomFactor ) + "px", minWidth: ( initialLogProps.dtMinWidth / zoomFactor ) + "px" }, ddProps = { fontSize: ( initialLogProps.ddFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.ddLineHeight / zoomFactor ) + "px" }, dlProps = { fontSize: ( initialLogProps.dlFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.dlLineHeight / zoomFactor ) + "px", marginBottom: ( initialLogProps.dlMarginBottom / zoomFactor ) + "px" }, hrProps = { marginTop: ( initialLogProps.hrMarginTop / zoomFactor ) + "px", marginBottom: ( initialLogProps.hrMarginBottom / zoomFactor ) + "px" }; $logPane.css( logProps ); $( "dt", $logPane ).css( dtProps ); $( "dd", $logPane ).css( ddProps ); $( "dl", $logPane ).css( dlProps ); $( "hr", $logPane ).css( hrProps ); }
javascript
{ "resource": "" }
q12162
injectElementWithStyles
train
function injectElementWithStyles(rule, callback, nodes, testnames) { var mod = 'modernizr'; var style; var ret; var node; var docOverflow; var div = createElement('div'); var body = getBody(); if (parseInt(nodes, 10)) { // In order not to give false positives we create a node for each test // This also allows the method to scale for unspecified uses while (nodes--) { node = createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node); } } style = createElement('style'); style.type = 'text/css'; style.id = 's' + mod; // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 (!body.fake ? div : body).appendChild(style); body.appendChild(div); if (style.styleSheet) { style.styleSheet.cssText = rule; } else { style.appendChild(document.createTextNode(rule)); } div.id = mod; if (body.fake) { //avoid crashing IE8, if background image is used body.style.background = ''; //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible body.style.overflow = 'hidden'; docOverflow = docElement.style.overflow; docElement.style.overflow = 'hidden'; docElement.appendChild(body); } ret = callback(div, rule); // If this is done after page load we don't want to remove the body so check if body exists if (body.fake) { body.parentNode.removeChild(body); docElement.style.overflow = docOverflow; // Trigger layout so kinetic scrolling isn't disabled in iOS6+ docElement.offsetHeight; } else { div.parentNode.removeChild(div); } return !!ret; }
javascript
{ "resource": "" }
q12163
htmlAsEntities
train
function htmlAsEntities(html){ html = html.replace(/&/g, '&amp;'); html = html.replace(/>/g, '&gt;'); html = html.replace(/</g, '&lt;'); html = html.replace(/"/g, '&quot;'); html = html.replace(/'/g, '&#039;'); return html; }
javascript
{ "resource": "" }
q12164
map
train
function map(obj, callback){ var result = {}; Object.keys(obj).forEach(function(key){ result[key] = callback.call(obj, obj[key], key, obj); }); return result; }
javascript
{ "resource": "" }
q12165
sanitizeHtml
train
function sanitizeHtml(html){ var separator = '/'; if(html.constructor === Object){ return map(html, function(value){ var sanitizedHtml = value.split(separator) .map(sanitizeHtml) .join(separator); return sanitizedHtml; }); } else if(html.constructor === Array){ return html.map(sanitizeHtml); } var div = document.createElement('div'); div.appendChild(document.createTextNode(html)); var sanitizedHtml = div.innerHTML.replace(/&amp;/g, '&'); if(html != sanitizedHtml){ return ''; // Blank it } return sanitizedHtml; }
javascript
{ "resource": "" }
q12166
_isInView
train
function _isInView ( elem, config ) { var containerWidth, containerHeight, hTolerance, vTolerance, rect, container = config.container, $container = config.$container, cache = config.cache, elemInView = true; if ( elem === container ) throw new Error( "Invalid container: is the same as the element" ); // When hidden elements are ignored, we check if an element consumes space in the document. And we bail out // immediately if it doesn't. // // The test employed for this works in the vast majority of cases, but there is a limitation. We use offsetWidth // and offsetHeight, which considers the content (incl. borders) but ignores margins. Zero-size content with a // margin might actually consume space sometimes, but it won't be detected (see http://jsbin.com/tiwabo/3). // // That said, the definition of visibility and the actual test are the same as in jQuery :visible. if ( config.excludeHidden && !( elem.offsetWidth > 0 && elem.offsetHeight > 0 ) ) return false; if ( config.useHorizontal ) containerWidth = getNetContainerWidth( $container, config.containerIsWindow, cache ); if ( config.useVertical ) containerHeight = getNetContainerHeight( $container, config.containerIsWindow, cache ); // Convert tolerance to a px value (if given as a percentage) hTolerance = cache.hTolerance !== undefined ? cache.hTolerance : ( cache.hTolerance = config.toleranceType === "add" ? config.tolerance : containerWidth * config.tolerance ); vTolerance = cache.vTolerance !== undefined ? cache.vTolerance : ( cache.vTolerance = config.toleranceType === "add" ? config.tolerance : containerHeight * config.tolerance ); // We can safely use getBoundingClientRect without a fallback. Its core properties (top, left, bottom, right) // are supported on the desktop for ages (IE5+). On mobile, too: supported from Blackberry 6+ (2010), iOS 4 // (2010, iPhone 3GS+), according to the jQuery source comment in $.fn.offset. // // In oldIE (up to IE8), the coordinates were 2px off in each dimension because the "viewport" began at (2,2) of // the window. Can be feature-tested by creating an absolutely positioned div at (0,0) and reading the rect // coordinates. Won't be fixed here because the quirk is too minor to justify the overhead, just for oldIE. // // (See http://stackoverflow.com/a/10231202/508355 and Zakas, Professional Javascript (2012), p. 406) rect = config.borderBox ? elem.getBoundingClientRect() : getContentRect( elem ); if ( ! config.containerIsWindow ) rect = getRelativeRect( rect, $container, cache ); if ( config.partially ) { if ( config.useVertical ) elemInView = rect.top < containerHeight + vTolerance && rect.bottom > -vTolerance; if ( config.useHorizontal ) elemInView = elemInView && rect.left < containerWidth + hTolerance && rect.right > -hTolerance; } else { if ( config.useVertical ) elemInView = rect.top >= -vTolerance && rect.top < containerHeight + vTolerance && rect.bottom > -vTolerance && rect.bottom <= containerHeight + vTolerance; if ( config.useHorizontal ) elemInView = elemInView && rect.left >= -hTolerance && rect.left < containerWidth + hTolerance && rect.right > -hTolerance && rect.right <= containerWidth + hTolerance; } return elemInView; }
javascript
{ "resource": "" }
q12167
getRelativeRect
train
function getRelativeRect ( rect, $container, cache ) { var containerPaddingRectRoot; if ( cache && cache.containerPaddingRectRoot ) { containerPaddingRectRoot = cache.containerPaddingRectRoot; } else { // gBCR coordinates enclose padding, and leave out margin. That is perfect for scrolling because // // - padding scrolls (ie,o it is part of the scrollable area, and gBCR puts it inside) // - margin doesn't scroll (ie, it pushes the scrollable area to another position, and gBCR records that) // // Borders, however, don't scroll, so they are not part of the scrollable area, but gBCR puts them inside. // // (See http://jsbin.com/pivata/10 for an extensive test of gBCR behaviour.) containerPaddingRectRoot = getPaddingRectRoot( $container[0] ); // Cache the calculations if ( cache ) cache.containerPaddingRectRoot = containerPaddingRectRoot; } return { top: rect.top - containerPaddingRectRoot.top, bottom: rect.bottom - containerPaddingRectRoot.top, left: rect.left - containerPaddingRectRoot.left, right: rect.right - containerPaddingRectRoot.left }; }
javascript
{ "resource": "" }
q12168
getContentRect
train
function getContentRect( elem ) { var rect = elem.getBoundingClientRect(), props = getCss( elem, [ "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft" ], { toFloat: true } ); return { top: rect.top + props.paddingTop + props.borderTopWidth, right: rect.right - ( props.paddingRight + props.borderRightWidth ), bottom: rect.bottom - ( props.paddingBottom + props.borderBottomWidth ), left: rect.left + props.paddingLeft + props.borderLeftWidth }; }
javascript
{ "resource": "" }
q12169
wrapContainer
train
function wrapContainer ( container ) { var $container, isJquery = container instanceof $; if ( ! isJquery && ! $.isWindow( container ) && ! container.nodeType && ! isString( container ) ) throw new Error( 'Invalid container: not a window, node, jQuery object or selector string' ); $container = isJquery ? container : container === root ? $root : $( container ); if ( !$container.length ) throw new Error( 'Invalid container: empty jQuery object' ); container = $container[0]; if ( container.nodeType === 9 ) { // Document is passed in, transform to window $container = wrapContainer( container.defaultView || container.parentWindow ); } else if ( container.nodeType === 1 && container.tagName.toLowerCase() === "iframe" ) { // IFrame element is passed in, transform to IFrame content window $container = wrapContainer( container.contentWindow ); } // Check if the container matches the requirements if ( !$.isWindow( $container[0] ) && $container.css( "overflow" ) === "visible" ) throw new Error( 'Invalid container: is set to overflow:visible. Containers must have the ability to obscure some of their content, otherwise the in-view test is pointless. Containers must be set to overflow:scroll/auto/hide, or be a window (or document, or iframe, as proxies for a window)' ); return $container; }
javascript
{ "resource": "" }
q12170
checkOptions
train
function checkOptions ( opts ) { var isNum, isNumWithUnit; if ( opts.direction && !( opts.direction === 'vertical' || opts.direction === 'horizontal' || opts.direction === 'both' ) ) { throw new Error( 'Invalid option value: direction = "' + opts.direction + '"' ); } if ( opts.box && !( opts.box === 'border-box' || opts.box === 'content-box' ) ) { throw new Error( 'Invalid option value: box = "' + opts.box + '"' ); } if ( opts.tolerance !== undefined ) { isNum = isNumber( opts.tolerance ); isNumWithUnit = isString( opts.tolerance ) && ( /^[+-]?\d*\.?\d+(px|%)?$/.test( opts.tolerance ) ); if ( ! ( isNum || isNumWithUnit ) ) throw new Error( 'Invalid option value: tolerance = "' + opts.tolerance + '"' ); } }
javascript
{ "resource": "" }
q12171
getContainerScrollbarWidths
train
function getContainerScrollbarWidths ( $container, cache ) { var containerScrollbarWidths; if ( cache && cache.containerScrollbarWidths ) { containerScrollbarWidths = cache.containerScrollbarWidths; } else { containerScrollbarWidths = effectiveScrollbarWith( $container ); if ( cache ) cache.containerScrollbarWidths = containerScrollbarWidths; } return containerScrollbarWidths; }
javascript
{ "resource": "" }
q12172
getCss
train
function getCss ( elem, properties, opts ) { var i, length, name, props = {}, _window = ( elem.ownerDocument.defaultView || elem.ownerDocument.parentWindow ), computedStyles = _useGetComputedStyle ? _window.getComputedStyle( elem, null ) : elem.currentStyle; opts || ( opts = {} ); if ( ! $.isArray( properties ) ) properties = [ properties ]; length = properties.length; for ( i = 0; i < length; i++ ) { name = properties[i]; props[name] = $.css( elem, name, false, computedStyles ); if ( opts.toLowerCase && props[name] && props[name].toLowerCase ) props[name] = props[name].toLowerCase(); if ( opts.toFloat ) props[name] = parseFloat( props[name] ); } return props; }
javascript
{ "resource": "" }
q12173
isIOS
train
function isIOS () { if ( _isIOS === undefined ) _isIOS = (/iPad|iPhone|iPod/g).test( navigator.userAgent ); return _isIOS; }
javascript
{ "resource": "" }
q12174
toFloat
train
function toFloat ( object ) { var transformed = {}; $.map( object, function ( value, key ) { transformed[key] = parseFloat( value ); } ); return transformed; }
javascript
{ "resource": "" }
q12175
createChildWindow
train
function createChildWindow ( readyDfd, size ) { var childWindow, width, height, sizedDefaultProps = ",top=0,left=0,location=no,menubar=no,status=no,toolbar=no,resizeable=yes,scrollbars=yes"; if ( size ) { width = size === "parent" ? window.document.documentElement.clientWidth : size.width; height = size === "parent" ? window.document.documentElement.clientHeight : size.height; childWindow = window.open( "", "", "width=" + width + ",height=" + height + sizedDefaultProps ); } else { childWindow = window.open(); } if ( childWindow ) { // Setting the document content (using plain JS - jQuery can't write an entire HTML document, including the // doctype and <head> tags). childWindow.document.open(); childWindow.document.write( '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<title></title>\n</head>\n<body>\n</body>\n</html>' ); childWindow.document.close(); } if ( readyDfd ) { if ( ! varExists( $ ) ) throw new Error( "`$` variable is not available. For using a readyDfd, jQuery (or a compatible library) must be loaded" ); if ( childWindow && childWindow.document ) { $( childWindow.document ).ready ( function () { windowSizeReady( childWindow, readyDfd ); } ); } else { readyDfd.reject(); } } return childWindow; }
javascript
{ "resource": "" }
q12176
createIframe
train
function createIframe ( opts ) { var parent = ( opts && opts.parent ) ? ( varExists( $ ) && opts.parent instanceof $ ) ? opts.parent[0] : opts.parent : document.body, _document = parent.ownerDocument, iframe = _document.createElement( "iframe" ); opts || ( opts = {} ); if ( opts.elementStyles ) iframe.style.cssText = ensureTrailingSemicolon( opts.elementStyles ); iframe.frameborder = "0"; if ( opts.prepend ) { parent.insertBefore( iframe, parent.firstChild ); } else { parent.appendChild( iframe ); } iframe.src = 'about:blank'; createIframeDocument( iframe, opts.documentStyles ); return iframe; }
javascript
{ "resource": "" }
q12177
createIframeDocument
train
function createIframeDocument ( iframe, documentStyles ) { if ( varExists( $ ) && iframe instanceof $ ) iframe = iframe[0]; if ( ! iframe.ownerDocument.body.contains( iframe ) ) throw new Error( "The iframe has not been appended to the DOM, or is not a descendant of the body element. Can't create an iframe content document." ); if ( ! iframe.contentDocument ) throw new Error( "Cannot access the iframe content document. Check for cross-domain policy restrictions." ); documentStyles = documentStyles ? '<style type="text/css">\n' + documentStyles + '\n</style>\n' : ""; iframe.contentDocument.write( '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<title></title>\n' + documentStyles + '</head>\n<body>\n</body>\n</html>' ); return iframe.contentDocument; }
javascript
{ "resource": "" }
q12178
windowSizeReady
train
function windowSizeReady ( queriedWindow, readyDfd, interval ) { if ( !varExists( $ ) ) throw new Error( "This method uses jQuery deferreds, but the $ variable is not available" ); if ( queriedWindow instanceof $ ) queriedWindow = queriedWindow[0]; readyDfd || ( readyDfd = $.Deferred() ); $( queriedWindow.document ).ready( function () { var documentElement = queriedWindow.document.documentElement, lastSize = { width: documentElement.clientWidth, height: documentElement.clientHeight }, repeater = setInterval( function () { var width = documentElement.clientWidth, height = documentElement.clientHeight, isStable = width > 0 && height > 0 && width === lastSize.width && height === lastSize.height; if ( isStable ) { clearInterval( repeater ); readyDfd.resolve(); } else { lastSize = { width: width, height: height }; } }, interval || 100 ); } ); return readyDfd; }
javascript
{ "resource": "" }
q12179
validateWindowSize
train
function validateWindowSize ( expected, opts ) { var msg = "", documentElement = ( opts && opts.window || window ).document.documentElement, width = documentElement.clientWidth, height = documentElement.clientHeight; if ( opts && opts.exactly ) { if ( width !== expected.width ) msg = " Window width is " + width + "px (expected: " + expected.width + "px)."; if ( height !== expected.height ) msg += " Window height is " + height + "px (expected: " + expected.height + "px)."; } else { if ( width < expected.width ) msg = " Window width is " + width + "px (expected minimum: " + expected.width + "px)."; if ( height < expected.height ) msg += " Window height is " + height + "px (expected minimum: " + expected.height + "px)."; } if ( msg !== "" ) throw new Error( "The browser window does not match the expected size." + msg ); }
javascript
{ "resource": "" }
q12180
forceReflow
train
function forceReflow ( element ) { if ( !varExists( $ ) ) throw new Error( "This method uses jQuery, but the $ variable is not available" ); var $element = element instanceof $ ? element : $( element ); $element.css( { display: "none" } ).height(); $element.css( { display: "block" } ); }
javascript
{ "resource": "" }
q12181
isIE
train
function isIE ( opts ) { var ver = getIEVersion(), isMatch = ver !== 0; opts || ( opts = {} ); if ( isMatch && opts.eq ) isMatch = ver === opts.eq; if ( isMatch && opts.lt ) isMatch = ver < opts.lt; if ( isMatch && opts.lte ) isMatch = ver <= opts.lte; if ( isMatch && opts.gt ) isMatch = ver > opts.gt; if ( isMatch && opts.gte ) isMatch = ver >= opts.gte; return isMatch; }
javascript
{ "resource": "" }
q12182
getIEVersion
train
function getIEVersion () { var ieMatch = /MSIE (\d+)/.exec( navigator.userAgent ) || /Trident\/.+? rv:(\d+)/.exec( navigator.userAgent ); return ( ieMatch && ieMatch.length ) ? parseFloat( ieMatch[1] ) : 0; }
javascript
{ "resource": "" }
q12183
removeEmptySources
train
function removeEmptySources (sources) { return _.reject(sources, function (obj) { return _.isEmpty(obj.transformed); }); }
javascript
{ "resource": "" }
q12184
train
function(){ var self = this; var camera = self.el.sceneEl.camera; if(camera) { var camera_rotation = camera.el.getAttribute("rotation"); var camera_yaw = camera_rotation.y; // Set position of menu based on camera yaw and data.pitch // Have to add 1.6m to camera.position.y (????) self.y_position = camera.position.y + 1.6; self.x_position = -self.data.distance * Math.sin(camera_yaw * Math.PI / 180.0); self.z_position = -self.data.distance * Math.cos(camera_yaw * Math.PI / 180.0); self.el.setAttribute("position", [self.x_position, self.y_position, self.z_position].join(" ")); // and now, make our controls rotate towards origin this.el.object3D.lookAt(new THREE.Vector3(camera.position.x, camera.position.y + 1.6, camera.position.z)); } }
javascript
{ "resource": "" }
q12185
validateObject
train
function validateObject (object = {}, label, schema, options) { // Skip validation if no schema is provided if (schema) { // Validate the object against the provided schema const { error, value } = joi.validate(object, schema, options) if (error) { // Throw error with custom message if validation failed throw new Error(`Invalid ${label} - ${error.message}`) } } }
javascript
{ "resource": "" }
q12186
validate
train
function validate (validationObj) { // Return a Koa middleware function return (ctx, next) => { try { // Validate each request data object in the Koa context object validateObject(ctx.headers, 'Headers', validationObj.headers, { allowUnknown: true }) validateObject(ctx.params, 'URL Parameters', validationObj.params) validateObject(ctx.query, 'URL Query', validationObj.query) if (ctx.request.body) { validateObject(ctx.request.body, 'Request Body', validationObj.body) } return next() } catch (err) { // If any of the objects fails validation, send an HTTP 400 response. ctx.throw(400, err.message) } } }
javascript
{ "resource": "" }
q12187
train
function (protocol, host, port, username, password, onConnected) { this.rocketChatClient = new RocketChatClient(protocol, host, port, username, password, onConnected); this.token = null; /** * login the rocket chat * @param callback after login the rocket chat , will invoke the callback function */ this.login = function (username, password, callback) { var self = this; this.rocketChatClient.authentication.login(username, password, function (err, body) { self.token = body.data; callback(null, body); }); }; }
javascript
{ "resource": "" }
q12188
resizeWordsCloud
train
function resizeWordsCloud() { $timeout(function() { var element = document.getElementById('wordsCloud'); var height = $window.innerHeight * 0.75; element.style.height = height + 'px'; var width = element.getBoundingClientRect().width; var maxCount = originWords[0].count; var minCount = originWords[originWords.length - 1].count; var maxWordSize = width * 0.15; var minWordSize = maxWordSize / 5; var spread = maxCount - minCount; if (spread <= 0) spread = 1; var step = (maxWordSize - minWordSize) / spread; self.words = originWords.map(function(word) { return { text: word.text, size: Math.round(maxWordSize - ((maxCount - word.count) * step)), color: self.customColor, tooltipText: word.text + ' tooltip' }; }); self.width = width; self.height = height; self.padding = self.editPadding; self.rotate = self.editRotate; }); }
javascript
{ "resource": "" }
q12189
train
function(records,config) { //the hell is this doing here this.id = new Date(); if ( records instanceof Array ) { this.records = records; } else { var dataField = records.data; var data = records.datasource; this.records = data[dataField]; } this.config = config; if ( this.config ) { this.propertyConfigMap = {}; this.config.cols.forEach( col => { this.propertyConfigMap[col.property] = col; }); } //indexRecords.call(this); }
javascript
{ "resource": "" }
q12190
train
function (req, res) { // check for a user id if (!req[this.paramName]._id) { return res.badRequest(); } req[this.paramName].password = req.body.password; delete req.body.password; req[this.paramName].save(function (err) { if (err) { return res.handleError(err); } return res.noContent(); }); }
javascript
{ "resource": "" }
q12191
train
function (req, res, next) { var userId = req[this.paramName]._id; var oldPass = String(req.body.oldPassword); var newPass = String(req.body.newPassword); this.model.findOne({'_id': userId}, function (err, user) { if (user.authenticate(oldPass)) { user.password = newPass; user.save(function (err) { if (err) { return res.handleError(err); } return res.noContent(); }); } else { res.forbidden(); } }); }
javascript
{ "resource": "" }
q12192
train
function (req, res, next) { if (!req.userInfo) { return res.unauthorized(); } return res.ok(req.userInfo.profile); }
javascript
{ "resource": "" }
q12193
handleError
train
function handleError(err, options) { // jshint validthis: true // Get access to response object var res = this.res; var statusCode; console.log('handleError', err, options); if (err.name && err.name === 'ValidationError') { return res.badRequest(err); } try { statusCode = err.status || 500; // set the status as a default res.status(statusCode); if (statusCode !== 500 && typeof res[statusCode] === 'function') { return res[statusCode](err); } } catch (e) { console.log('Exception while handling error: %s', e); } return res.serverError(err); }
javascript
{ "resource": "" }
q12194
validateUniqueName
train
function validateUniqueName(value, respond) { // jshint validthis: true var self = this; // check for uniqueness of user name this.constructor.findOne({name: value}, function (err, user) { if (err) { throw err; } if (user) { // the searched name is my name or a duplicate return respond(self.id === user.id); } respond(true); }); }
javascript
{ "resource": "" }
q12195
preSave
train
function preSave(next) { // jshint validthis: true var self = this; if (this.isNew && !validatePresenceOf(this.hashedPassword)) { return next(new MongooseError.ValidationError('Missing password')); } // check if the root user should be updated // return an error if some not root tries to touch the root document self.constructor.getRoot(function (err, rootUser) { if (err) { throw err; } // will we update the root user? if (rootUser && self.id === rootUser.id) { // delete the role to prevent loosing the root status delete self.role; // get the user role to check if a root user will perform the update var userRole = contextService.getContext('request:acl.user.role'); if (!userRole) { // no user role - no root user check return next(); } if (!auth.roles.isRoot(userRole)) { // return error, only root can update root return next(new MongooseError.ValidationError('Forbidden root update request')); } } // normal user update return next(); }); }
javascript
{ "resource": "" }
q12196
preRemove
train
function preRemove(next) { // jshint validthis: true if (auth.roles.isRoot(this.role)) { return next(new MongooseError.ValidationError(auth.roles.getMaxRole() + ' role cannot be deleted')); } return next(); }
javascript
{ "resource": "" }
q12197
getAuthentication
train
function getAuthentication(authModel, config) { /** * @name authenticate * @function * @memberOf getAuthentication * Authenticate the user. * @param {String} name - The name used to authenticate the user * @param {String} password - The hashed password * @param {function} done - The callback function called with an error or the valid user object */ function authenticate(name, password, done) { authModel.findOne({name: name, active: true}, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false, {message: 'Unknown user'}); } if (!user.authenticate(password)) { return done(null, false, {message: 'Wrong password'}); } return done(null, user); }); } return authenticate; }
javascript
{ "resource": "" }
q12198
authenticate
train
function authenticate(req, res, next) { var callback = _.bind(authCallback, {req: req, res: res}); passport.authenticate('local', callback)(req, res, next) }
javascript
{ "resource": "" }
q12199
CrudController
train
function CrudController(model, idName) { // call super constructor BaseController.call(this); // set the model instance to work on this.model = model; // set id name if defined, defaults to 'id' if (idName) { this.idName = String(idName); } }
javascript
{ "resource": "" }