_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q41600
_sendRequest
train
function _sendRequest(requestObj, callback) { var Storage, ajaxConfig; Storage = this; ajaxConfig = { url : requestObj.config.url, type : requestObj.config.type || this.REQUEST_TYPE_GET, contentType : requestObj.config.contentType || 'application/json', global : false, async : true, cache : false, complete : function(xhr, message){ Storage._processResponse(xhr, message, callback); } }; if (ajaxConfig.type != Argon.Storage.JsonRest.REQUEST_TYPE_GET) { ajaxConfig.data = JSON.stringify(requestObj.data); } if (ajaxConfig.type == this.REQUEST_TYPE_PUT || ajaxConfig.type == this.REQUEST_TYPE_DELETE) { ajaxConfig.beforeSend = function(xhr) { xhr.setRequestHeader("X-Http-Method-Override", ajaxConfig.type); }; ajaxConfig.type = this.REQUEST_TYPE_POST; } $.ajax(ajaxConfig); return this; }
javascript
{ "resource": "" }
q41601
train
function (xhr, message, callback) { var response; switch (xhr.status) { case this.RESPONSE_OK: response = JSON.parse(xhr.responseText); break; case this.RESPONSE_UNPROCESSABLE_ENTITY: response = JSON.parse(xhr.responseText); break; case this.RESPONSE_NOT_FOUND: response = { error : xhr.status }; break; case this.RESPONSE_INTERNAL_SERVER_ERROR: response = {}; break; case this.RESPONSE_SERVER_UNAVALIABLE: console.log('Server is unavailable, probably shutdown.'); response = {}; break; default: console.log('Unsuported code returned from the server: ', xhr.status); response = { error : xhr.status }; } callback(response); return this; }
javascript
{ "resource": "" }
q41602
create
train
function create(requestObj, callback) { var i, requestConfig, storage; storage = this; callback = callback || function(){}; if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(null); return this; } requestObj.config = {}; requestObj.config.url = requestObj.config.url || this.url.post; requestObj.config.type = requestObj.config.type || this.constructor.REQUEST_TYPE_POST; for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } this.constructor._sendRequest(requestObj, function(data){ for (i = 0; i < storage.processors.length; i++) { data = storage.processors[i](data, requestObj); } callback(data); }); return this; }
javascript
{ "resource": "" }
q41603
update
train
function update(requestObj, callback) { var i, found, storedData, storage; storage = this; callback = callback || function(){}; if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(null); return this; } requestObj.config = {}; requestObj.config.url = requestObj.config.url || this.url.put; requestObj.config.type = requestObj.config.type || this.constructor.REQUEST_TYPE_POST; if (requestObj.data) { for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } } this.constructor._sendRequest(requestObj, function(data){ for (i = 0; i < storage.processors.length; i++) { data = storage.processors[i](data, requestObj); } callback(data); }); return this; }
javascript
{ "resource": "" }
q41604
remove
train
function remove(requestObj, callback) { var i, storage; storage = this; callback = callback || function(){}; if ((typeof requestObj) === 'undefined' || requestObj === null) { callback(null); return this; } requestObj.config = {}; requestObj.config.url = requestObj.config.url || this.url.remove; requestObj.config.type = requestObj.config.type || this.constructor.REQUEST_TYPE_GET; if (requestObj.data) { for (i = 0; i < storage.preprocessors.length; i++) { requestObj.data = storage.preprocessors[i](requestObj.data, requestObj); } } this.constructor._sendRequest(requestObj, function(data){ callback(null); }); return this; }
javascript
{ "resource": "" }
q41605
aleaRandom
train
function aleaRandom(min, max, floating) { var gen = new Alea(uuid.v4()); if (floating && typeof floating !== 'boolean' && isIterateeCall(min, max, floating)) { max = floating = undefined; } if (floating === undefined) { if (typeof max === 'boolean') { floating = max; max = undefined; } else if (typeof min === 'boolean') { floating = min; min = undefined; } } if (min === undefined && max === undefined) { min = 0; max = 1; } else { min = toNumber(min) || 0; if (max === undefined) { max = min; min = 0; } else { max = toNumber(max) || 0; } } if (min > max) { var temp = min; min = max; max = temp; } if (floating || min % 1 || max % 1) { var rand = gen(); return Math.min(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max); } return min + Math.floor(gen() * (max - min + 1)); }
javascript
{ "resource": "" }
q41606
_functionBelongsToObject
train
function _functionBelongsToObject(self, caller, target, protectedMode = false) { if (!caller) return false; // We are caching the results for better performance. let cacheOfResultsForSelf = resultCache.get(self); if (cacheOfResultsForSelf && cacheOfResultsForSelf.has(caller)) { return cacheOfResultsForSelf.get(caller); } let proto = Object.getPrototypeOf(self); // proto !== target - means that extend was made. let check; if ((caller.name === 'get' || caller.name === 'set')) { check = !getterOrSetterBelongsToObject(caller, target); } else { check = !(target[caller.name] || target.constructor === caller); } if (target && proto !== target && check) { if (protectedMode) { if (!checkIfTargetIsRelated(proto, target)) { return false; } } else { return false; } } let result = false; while (proto !== Object && result === false && proto.constructor !== Object) { result = functionBelongsToObjectInternal(proto, caller); proto = Object.getPrototypeOf(proto); } if (!cacheOfResultsForSelf) { cacheOfResultsForSelf = new WeakMap(); } cacheOfResultsForSelf.set(caller, result); resultCache.set(self, cacheOfResultsForSelf); return result; }
javascript
{ "resource": "" }
q41607
prepareProfileDir
train
function prepareProfileDir(profilesDir, nick) { var nick = nick || '.tmp'; // Just in case `nick` has any funny business... nick = nick.replace(/[^\w\d.]/g, '-').replace('..', '-'); var profileDir = path.join(profilesDir, util.format('vox-%s', nick)); debug('Ensuring directory at %s', profileDir); mkdirp.sync(profileDir, 0700); return profileDir; }
javascript
{ "resource": "" }
q41608
train
function(model) { var _d = this._d; // quicker lookup if (!_d.hasData) { // if we've never rendered data yet, queue up a reset collection // this probably means we just finished our very first fetch // reset needed to clear out loading / no data state.. return this.resetCollection(); } _d.modelChanges[model.cid] = {t: 'add', m: model}; this.updateViews(); }
javascript
{ "resource": "" }
q41609
train
function(id) { var self = this; this.collection.each(function(model) { if (model.id == id || _(id).contains(model.id)) { return; } // console.log("Unselecting model", model.id, id); self.getStateModel(model).set({ selected: false }); }); }
javascript
{ "resource": "" }
q41610
exportVis
train
function exportVis(url, dest, callback) { if (dest === undefined) dest = '.'; (0, _mkdirp2['default'])(dest, function (err) { if (err && callback) return callback(err); if (!isVisUrl(url)) { url = getVisUrl(url); } getVisJson(url, _path2['default'].join(dest, 'viz.json'), function (err, visJson) { downloadVisualizationData(visJson, dest, callback); }); }); }
javascript
{ "resource": "" }
q41611
getVisUrl
train
function getVisUrl(url) { var match = /https?:\/\/(\S+)\.cartodb\.com\/viz\/(\S+)\/(?:public_)?map/.exec(url); if (match) { var user = match[1], mapId = match[2]; return 'https://' + user + '.cartodb.com/api/v2/viz/' + mapId + '/viz.json'; } }
javascript
{ "resource": "" }
q41612
downloadVisualizationData
train
function downloadVisualizationData(_visJson, destDir, callback) { if (destDir === undefined) destDir = '.'; withVisJson(_visJson, function (err, visJson) { if (err && callback) return callback(err); _async2['default'].forEachOf(visJson.layers, function (layer, layerIndex, callback) { if (layer.type === 'namedmap') { console.error("Layer is not public, cannot download its data. If you own the map and datasets, please change the privacy settings to 'public' and try again."); return callback(); } if (layer.type !== 'layergroup') { if (callback) callback(); return; } _async2['default'].forEachOf(layer.options.layer_definition.layers, function (sublayer, sublayerIndex, callback) { var dest = _path2['default'].join(sublayerDir(destDir, layerIndex, sublayerIndex), 'layer.geojson'); downloadSublayerData(visJson, layerIndex, sublayerIndex, dest, callback); }, callback); }, callback); }); }
javascript
{ "resource": "" }
q41613
downloadSublayerData
train
function downloadSublayerData(visJson, layerIndex, sublayerIndex, dest, callback) { var layer = visJson.layers[layerIndex], sublayer = layer.options.layer_definition.layers[sublayerIndex]; (0, _mkdirp2['default'])(_path2['default'].dirname(dest), function () { var dataFile = _fs2['default'].createWriteStream(dest).on('close', function () { if (callback) { callback(); } }); var req = (0, _request2['default'])({ url: getLayerSqlUrl(layer), qs: { format: 'GeoJSON', q: getSublayerSql(sublayer) } }); req.pipe(dataFile); // Show progress as file downloads req.on('response', function (res) { var len = parseInt(res.headers['content-length'], 10); var bar = new _progress2['default'](' downloading [:bar] :percent :etas', { complete: '=', incomplete: ' ', width: 20, total: len }); res.on('data', function (chunk) { bar.tick(chunk.length); }); res.on('end', function (chunk) { console.log('\n'); }); }); }); }
javascript
{ "resource": "" }
q41614
train
function(folder) { var files, modelName; folder = folder || process.cwd() + '/test/fixtures'; files = fs.readdirSync(folder); for (var i = 0; i < files.length; i++) { if (getFileExtension(files[i]) === '.json') { modelName = fileToModelName(files[i]); this.objects[modelName] = require(path.join(folder, files[i])); } } return this; }
javascript
{ "resource": "" }
q41615
train
function () { var that = this, independent, dependencyNotRequired; promiseIndependent = this.saveFixturesFromArray(independentFixtures); promiseDelayedDependency = this.saveFixturesFromArray(delayedDependencyFixtures); promise = Q.all([ promiseIndependent, promiseDelayedDependency ]) .then(function(models) { return that.saveFixturesFromArray(requiredDependencyFixtures); }); return promise; }
javascript
{ "resource": "" }
q41616
crc32
train
function crc32( buffer, seed, table ) { var crc = seed ^ -1 var length = buffer.length - 15 var TABLE = table || crc32.TABLE.DEFAULT var i = 0 while( i < length ) { crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] crc = ( crc >>> 8 ) ^ TABLE[ 0xFF & ( crc ^ buffer[ i++ ] ) ] } length = length + 15 while( i < length ) crc = ( crc >>> 8 ) ^ TABLE[ ( crc ^ buffer[ i++ ] ) & 0xFF ] return crc ^ -1 }
javascript
{ "resource": "" }
q41617
normalizeTwitterData
train
function normalizeTwitterData(data,req,res){ var normalized = { error: false, error_message: '', media: [] } // console.dir(req.session.twitter) if( isTwitterOverCapacity() ){ normalized.error = true normalized.error_message = "It appears Twitter is over capacity. Try again." } else{ console.log("Twitter Response array length: %s\n", data.length) // If the media response is empty... if(!data.length){ normalized.error = true normalized.error_message = "We were unable to fetch any images from your media timeline." console.dir(data) return processNormalizedResponse(normalized, req, res) } // We use a for loop so we can break out if // the cache is met for(i=0, len = data.length; i<len; i++){ var el = data[i] // console.dir(el) // TODO: Session won't stash this much data so switch this logic to pull from redis. if( req.session.media_cache && isItemFirstCacheItem(el.id, req.session.media_cache.latest_id ) ){ console.log('\n\nCache is same so we are breaking...\n\n') // update latest_id in cache normalized.latest_id = el.id // Now process the the response with new updated normalized data processNormalizedResponse(normalized, req, res) break } // The first time we run this, we need to stash the latest_id if( i === len-1 ){ normalized.latest_id = data[0].id } // In the case of just pic.twitter.com.... if(el.entities && el.entities.media && el.entities.media.length){ var twitMediaObj = el.entities.media[0] var item = { full_url: twitMediaObj.media_url+":large", thumb_url: twitMediaObj.media_url+":thumb", } normalized.media.push(item) } // Otherwise, we have 3rd part attributed providers. else if(el.entities && el.entities.urls && el.entities.urls.length && el.entities.urls[0].display_url){ var url = el.entities.urls[el.entities.urls.length-1].display_url if(url.indexOf('instagr.am') > -1){ var item = { full_url: "https://" + url + "/media/?size=l", thumb_url: "https://" + url + "/media/?size=t", } normalized.media.push(item) } if(url.indexOf('twimg.com') > -1){ // https://p.twimg.com/A128d2CCIAAPt--.jpg:small // https://p.twimg.com/A128d2CCIAAPt--.jpg:large } if(url.indexOf('flickr.com') > -1){ /* <div class="thumbnail-wrapper" data-url="http://flickr.com/groups/dalekcakes"> <img class="scaled-image" src="//farm7.static.flickr.com/6140/5917491915_8e92c65aa8.jpg"></div> */ // WILL NEED TO FIGURE OUT FLICKR RESPONSE // Requires API call via photo ID, or just use twitter: /* https://widgets.platform.twitter.com/services/rest?jsoncallback=jQuery15205886323538143188_1346683837796&format=json&api_key=2a56884b56a00758525eaa2fee16a798&method=flickr.photos.getInfo&photo_id=7275880290&_=1346683837809 */ console.dir(el) } if(url.indexOf('twitpic.com') > -1){ // POP OFF ID OF END OF TWITPIC URL // http://twitpic.com/9k68zj var url_id = url.split('com')[1] // includes slash var item = { full_url: "https://twitpic.com/show/iphone" + url_id, thumb_url: "https://twitpic.com/show/iphone" + url_id, } normalized.media.push(item) } // if(url.indexOf('etsy.am') > -1){} if(url.indexOf('twitgoo.com') > -1){ // http://twitgoo.com/66akxy/img var item = { full_url: url + '/img', thumb_url: url + '/img', } normalized.media.push(item) } // Daily booth closed down.... // if(url.indexOf('dailybooth.com') > -1){ // console.log(url) // request({ // followRedirect: false, // uri: 'http://'+url, // callback: function(e,r,b){ // need to handle errors better... // if(e) console.error(e) // // console.dir(r) // // var id = r.headers.location.split('/').pop() // // request({ // uri: "https://api.dailybooth.com/v1/picture/" + id + ".json", // json: true, // callback: function(e,r,b){ // if(e) return console.error(e) // /* // urls: // { tiny: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/tiny/78e4b486c80b29435504d94fdf626b7c_29230840.jpg', // small: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/small/78e4b486c80b29435504d94fdf626b7c_29230840.jpg', // medium: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/medium/78e4b486c80b29435504d94fdf626b7c_29230840.jpg', // large: 'http://d1oi94rh653f1l.cloudfront.net/15/pictures/large/78e4b486c80b29435504d94fdf626b7c_29230840.jpg' // } // // { error: // { error: 'rate_limit', // error_description: 'Rate limit exceeded.', // error_code: 412 } } // var item = { // full_url: b.urls.large + '/img', // thumb_url: b.urls.small + '/img', // } // */ // // if( (r.statusCode >= 400) || b.error) { // console.log('Fail. '.red +'Status Code for Daily Booth request: %s', r.statusCode) // console.error(b.error) // } // else{ // // var item = { // full_url: b.urls.large, // thumb_url: b.urls.small, // } // // normalized.media.push(item) // } // // delay = false // // processNormalizedResponse(normalized, req, res) // // } // end inner request callback // }) // end request() // } // end outer request callback // }) // end request() // // // Because of the async nature of the above request() calls, // // we set the delay here and mark it false in the last callback // if(!delay) delay = true // // } if(url.indexOf('yfrog.com') > -1){ // console.dir(el) var item = { full_url: "https://" + url + ":tw1", thumb_url: "https://" + url + ":tw1", } normalized.media.push(item) } // if(url.indexOf('lockerz.am') > -1){} // if(url.indexOf('kiva.am') > -1){} // if(url.indexOf('kickstarter.com') > -1){} if(url.indexOf('dipdive.com') > -1){ isVideo = false || true; // could be photo } // if(url.indexOf('photobucket.com') > -1){} // if(url.indexOf('with.me') > -1){} // if(url.indexOf('facebook.com') > -1){} if(url.indexOf('deviantart.com') > -1 || url.indexOf('fav.me') > -1){ // TODO: IMAGES DON'T SHOW UP? } } // end if el.entities.url } // end forloop } // end else capacity return processNormalizedResponse(normalized, req, res) }
javascript
{ "resource": "" }
q41618
isPropTypesDeclaration
train
function isPropTypesDeclaration(context, node) { // Special case for class properties // (babel-eslint does not expose property name so we have to rely on tokens) if (node.type === 'ClassProperty') { const tokens = context.getFirstTokens(node, 2); if (isTypesDecl(tokens[0].value) || isTypesDecl(tokens[1].value)) { return true; } return false; } return Boolean(node && isTypesDecl(node.name)); }
javascript
{ "resource": "" }
q41619
reduce
train
function reduce(reducingFn, initFn, enumerable, resultFn) { if (isFunction(resultFn)) { resultFn = pipe(unreduced, resultFn); } else { resultFn = unreduced; } let result; const iter = iterator(enumerable); if (!initFn) { const [initValue] = iter; initFn = lazy(initValue); } result = initFn(); for (const value of iter) { if (isReduced(result)) { break; } result = reducingFn(result, value); } return resultFn(result); }
javascript
{ "resource": "" }
q41620
Throwable
train
function Throwable(wrapped) { if (!(this instanceof Throwable)) { return new Throwable(wrapped); } /* istanbul ignore if */ if (typeof wrapped !== 'object') { throw Error('Throwable should wrap an Error'); } // Wrap the Error so that the stack, lineNumber, fileName, etc is correct this.wrapped = wrapped; this.wrapped.name = 'Throwable'; }
javascript
{ "resource": "" }
q41621
_bundleEPUB
train
function _bundleEPUB(config, done) { var epubconfig = config.akashacmsEPUB; var archive = archiver('zip'); var output = fs.createWriteStream(config.akashacmsEPUB.bookmetadata.epub); output.on('close', function() { logger.info(archive.pointer() + ' total bytes'); logger.info('archiver has been finalized and the output file descriptor has closed.'); done(); }); archive.on('error', function(err) { logger.info('*********** BundleEPUB ERROR '+ err); done(err); }); archive.pipe(output); // The mimetype file must be the first entry, and must not be compressed archive.append( fs.createReadStream(path.join(config.root_out, "mimetype")), { name: "mimetype", store: true }); archive.append( fs.createReadStream(path.join(config.root_out, "META-INF", "container.xml")), { name: path.join("META-INF", "container.xml") }); archive.append( fs.createReadStream(path.join(config.root_out, config.akashacmsEPUB.bookmetadata.opf)), { name: config.akashacmsEPUB.bookmetadata.opf }); // archive.append( // fs.createReadStream(path.join(config.root_out, config.akashacmsEPUB.files.ncx)), // { name: config.akashacmsEPUB.files.ncx }); // logger.info(util.inspect(config.akashacmsEPUB.manifest)); async.eachSeries(config.akashacmsEPUB.manifest, function(item, next) { // logger.info(util.inspect(item)); // if (item.spinetoc !== true) { // this had been used to skip the NCX file archive.append( fs.createReadStream(path.join(config.root_out, item.href)), { name: item.href } ); // } next(); }, function(err) { if (err) logger.error(err); logger.info('before finalize'); archive.finalize(); }); }
javascript
{ "resource": "" }
q41622
train
function(next) { // Stylesheet and JavaScript files are listed in the config config.headerScripts.stylesheets.forEach(function(cssentry) { config.akashacmsEPUB.manifest.push({ id: cssentry.id, type: "text/css", href: rewriteURL(akasha, config, { rendered_url: config.akashacmsEPUB.bookmetadata.opf }, cssentry.href, false) // MAP this URL }); }); config.headerScripts.javaScriptTop.concat(config.headerScripts.javaScriptBottom).forEach(function(jsentry) { config.akashacmsEPUB.manifest.push({ id: jsentry.id, type: "application/javascript", href: rewriteURL(akasha, config, { rendered_url: config.akashacmsEPUB.bookmetadata.opf }, jsentry.href, false) // MAP this URL }); }); // There had formerly been a list of allowed file extensions in globfs.operate // // Turns out to have been too restrictive because those who wanted to // include other kinds of files weren't free to do so. // // The purpose here is to add manifest entries for files that aren't documents // and aren't already in the manifest for any other reason. var assetNum = 0; globfs.operate(config.root_assets.concat(config.root_docs), [ "**/*" ], function(basedir, fpath, fini) { // logger.trace('asset file '+ path.join(basedir, fpath)); fs.stat(path.join(basedir, fpath), function(err, stats) { if (err || !stats) { // Shouldn't get this, because globfs will only give us // files which exist logger.error('ERROR '+ basedir +' '+ fpath +' '+ err); fini(); } else if (stats.isDirectory()) { // Skip directories // logger.trace('isDirectory '+ basedir +' '+ fpath); fini(); } else { // logger.trace('regular file '+ basedir +' '+ fpath); akasha.readDocumentEntry(fpath, function(err, docEntry) { if (docEntry) { // If there's a docEntry, we need to override the fpath // with the filename it renders to. This is to properly // detect files that are already in the manifest. // logger.trace('docEntry '+ basedir +' '+ fpath); fpath = docEntry.renderedFileName; } // Detect any files that are already in manifest // Only add to manifest stuff which isn't already there var inManifest = false; config.akashacmsEPUB.manifest.forEach(function(item) { if (item.href === fpath) { inManifest = true; } }); if (!inManifest) { // We're not using the mime library for some // file extensions because it gives // incorrect values for the .otf and .ttf files // logger.trace('assetManifestEntries '+ basedir +' '+ fpath); var mimetype; if (fpath.match(/\.ttf$/i)) mimetype = "application/vnd.ms-opentype"; else if (fpath.match(/\.otf$/i)) mimetype = "application/vnd.ms-opentype"; else mimetype = mime.lookup(fpath); config.akashacmsEPUB.manifest.push({ id: "asset" + assetNum++, type: mimetype, href: rewriteURL(akasha, config, { rendered_url: config.akashacmsEPUB.bookmetadata.opf }, fpath, false) }); } fini(); }); } }); }, next); }
javascript
{ "resource": "" }
q41623
waitAndSet
train
function waitAndSet() { var i; var times = [0,200,400,700,1000,1500,2000]; var len = times.length; for ( i = 0; i < len; i++ ) { $timeout(setParentHeight,times[i]); } }
javascript
{ "resource": "" }
q41624
uploadIndexPages
train
function uploadIndexPages(pagePaths, config, options, callback) { var requestOptions = { method: 'POST', url: options.airport + '/dev/' + config.appId + '/simulator', form: {} }; // Attach the files as multi-part var request = api(config, requestOptions, callback); var form = request.form(); pagePaths.forEach(function(pagePath) { grunt.log.debug("Uploading " + pagePath); form.append(path.basename(pagePath, '.html'), fs.createReadStream(pagePath)); }); }
javascript
{ "resource": "" }
q41625
write
train
function write(token, enc, next) { var type = token[0], buf = token[1]; if(('rule_start' === type || 'atrule_start' === type)) depth++; if(depth > 0 && !current) current = {location: [line, column], buffers:[]}; if('rule_end' === type || 'atrule_end' === type) depth--; if(current) { current.buffers.push(buf); if(depth === 0) pushRule.call(this); } updatePosition(buf); next(); }
javascript
{ "resource": "" }
q41626
createPartial
train
function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = this && this !== root && this instanceof wrapper ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; }
javascript
{ "resource": "" }
q41627
deep_set
train
function deep_set(root, path, value) { var twig = root; path.split('/').forEach(function (branch, index, branches) { if (branch) { if (self.camelize) { branch = branch.replace(/(\-([a-z]))/g, function (m) { return m[1].toUpperCase(); }) } if (index < branches.length - 1) { twig = twig[branch] || (twig[branch] = {}); } else { // optimistically try treating the value as JSON try { twig[branch] = JSON.parse(value); } catch (e) { twig[branch] = value; } } } }); }
javascript
{ "resource": "" }
q41628
deep_get
train
function deep_get(root, path) { var twig = root, result = undefined; path.split('/').forEach(function (branch, index, branches) { if (branch) { if (self.camelize) { branch = branch.replace(/(\-([a-z]))/g, function (m) { return m[1].toUpperCase(); }) } if (index < branches.length - 1) { twig = twig[branch]; } else { result = twig && twig[branch]; } } }); return result; }
javascript
{ "resource": "" }
q41629
parse_date_strings
train
function parse_date_strings(root) { for (key in root) { if (!root.hasOwnProperty(key)) continue; var value = root[key]; if (typeof(value) === 'object') { parse_date_strings(value); } else if (typeof(value) === 'string' && /\d{4}-?\d{2}-?\d{2}(T?\d{2}:?\d{2}:?\d{2}(Z)?)?/.test(value)) { var timestamp = Date.parse(value); if (!isNaN(timestamp)) { root[key] = new Date(timestamp); } } } }
javascript
{ "resource": "" }
q41630
getChoices
train
function getChoices() { const name = choice => fp.padStart(MAX_DESC)(choice.value) const desc = choice => wrap(choice.description, MAX) return types.map(choice => { if (choice.value === 'separator') return SEPARATOR return { name: `${name(choice)} ${choice.emoji} ${desc(choice)}`, value: choice.value, short: name(choice) } }) }
javascript
{ "resource": "" }
q41631
createObj
train
function createObj( str ) { if (!str || str.length == 0) { return window; } var d = str.split("."), j, o = window; for (j = 0; j < d.length; j = j + 1) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } return o; }
javascript
{ "resource": "" }
q41632
addPrototypeBeforeCall
train
function addPrototypeBeforeCall( Class, isAbstract ) { var constStatic = {}, currentState = { Static: window.Static, Abstract: window.Abstract, Const: window.Const, Private: window.Private }; saveState.push(currentState); window.Static = Class.prototype.Static = {Const:constStatic}; window.Abstract = Class.prototype.Abstract = isAbstract ? {} : undefined; window.Const = Class.prototype.Const = {Static:constStatic}; window.Private = Class.prototype.Private = {}; }
javascript
{ "resource": "" }
q41633
deleteAddedProtoTypes
train
function deleteAddedProtoTypes( Class ) { delete Class.prototype.Static; delete Class.prototype.Const; delete Class.prototype.Private; delete Class.prototype.Abstract; var currentState = saveState.pop(); window.Private = currentState.Private; window.Const = currentState.Const; window.Abstract = currentState.Abstract; window.Static = currentState.Static; }
javascript
{ "resource": "" }
q41634
simpleExtend
train
function simpleExtend( from, to ) { for ( var k in from) { if (to[k] == undefined) { to[k] = from[k]; } } return to; }
javascript
{ "resource": "" }
q41635
addAddedFileInnScript
train
function addAddedFileInnScript(key, path, dot_path){ dot_path = dot_path || path; // checking if same file imported twice for same Class. if(!dot_path) return; var script = scriptArr[scriptArr.length - 1]; if( !script ){ return; } var arr = script[key] || (script[key] = []); if( arr.indexOf(dot_path) === -1 ) { arr.push(dot_path); } return true; }
javascript
{ "resource": "" }
q41636
include
train
function include( path, isFromInclude, dot_path ) { if(!path){ return; } all_paths.push(path) if(isNode){ require(path); listenFileChange(path); if(isFromInclude){ fileLoadeManager.iamready(dot_path); } return; } if (fm.isConcatinated) { fileLoadeManager.iamready(dot_path); return; } if (!docHead) { docHead = document.getElementsByTagName("head")[0]; } // isNonfm && fm.holdReady(true); var e = document.createElement("script"); // onerror is not supported by IE so this will throw exception only for // non IE browsers. if(me.version){ path += "?v=" + me.version; } e.onerror = onFileLoadError; if(isFromInclude){ e.onload = function(){ fileLoadeManager.iamready(dot_path); $(document).trigger('jsfm-iamready-'+ path.split("/").pop().replace(".js", ""), [path]); }; } e.src = path; e.type = "text/javascript"; docHead.appendChild(e); }
javascript
{ "resource": "" }
q41637
getReleventClassInfo
train
function getReleventClassInfo( Class, fn, pofn ) { /// this is script addPrototypeBeforeCall(Class, this.isAbstract); var tempObj, k, len; tempObj = invoke(Class, this.args, pofn.base, this.ics, this.Package, pofn); tempObj.setMe && tempObj.setMe(pofn); tempObj.base = pofn.base; delete tempObj.setMe; this.shortHand = tempObj.shortHand || this.shortHand; var info = separeteMethodsAndFields(tempObj); this.methods = info.methods = pofn.base ? info.methods.concat(pofn.base.prototype.$get('methods')) : info.methods; if (this.isInterface) { pofn.base && simpleExtend(pofn.base.prototype.$get('fields'), info.fields); this.fields = info.fields; checkMandSetF(pofn); deleteAddedProtoTypes(Class); return this; } if (tempObj.init){ tempObj.init(); } this.isAbstract && checkForAbstractFields(tempObj.Abstract, this.Class); this.Static = simpleExtend(tempObj.Static, {}); this.isAbstract && (this.Abstract = simpleExtend(tempObj.Abstract, {})); this.staticConst = this.Static.Const; delete this.Static.Const; this.Const = simpleExtend(tempObj.Const, {}); delete this.Const.Static; checkAvailability(tempObj, this.Static, this.staticConst, this.Abstract, this.Const); addTransient(this, tempObj); this.privateConstructor = !!tempObj["Private"] && tempObj["Private"][fn]; deleteAddedProtoTypes(Class); var plugins = this.plugins, pp; //add plugin as extensin for(var p in plugins) { if(plugins.hasOwnProperty(p)) { pp = fm.isExist(plugins[p]); simpleExtend(pp.prototype.$get("Static"), this.Static); simpleExtend(pp.prototype.$get("staticConst"), this.staticConst); } } var temp = this.interfaces; if (temp) { for (k = 0, len = temp.length; k < len; k++) { createObj(temp[k]).prototype.$checkMAndGetF(pofn, info.methods, this.isAbstract, tempObj, this); } } temp = k = tempObj = info = Class = fn = undefined; }
javascript
{ "resource": "" }
q41638
checkAvailability
train
function checkAvailability( obj ) { for ( var k = 1, len = arguments.length; k < len; k++) { for ( var m in arguments[k]) { if (obj.hasOwnProperty(m)) { throw obj.getClass() + ": has " + m + " at more than one places"; } } } }
javascript
{ "resource": "" }
q41639
addTransient
train
function addTransient( internalObj, tempObj ) { var temp = {}, k, tr = tempObj["transient"] || []; tr.push("shortHand"); for (k = 0; k < tr.length; k++) { (temp[tr[k]] = true); } eachPropertyOf(internalObj.Static, function( v, key ) { temp[key] = true; }); eachPropertyOf(internalObj.staticConst, function( v, key ) { temp[key] = true; }); internalObj["transient"] = temp; internalObj = tempObj = k = temp = undefined; }
javascript
{ "resource": "" }
q41640
separeteMethodsAndFields
train
function separeteMethodsAndFields( obj ) { var methods = [], fields = {}; eachPropertyOf(obj, function( v, k ) { if (typeof v == 'function') { methods.push(k + ""); } else { fields[k + ""] = v; } }); obj = undefined; return { methods : methods, fields : fields }; }
javascript
{ "resource": "" }
q41641
getAllImportClass
train
function getAllImportClass( imp ) { var newImports = {}, splited; for ( var k = 0; imp && k < imp.length; k++) { splited = imp[k].split("."); newImports[splited[splited.length - 1]] = fm.stringToObject(imp[k]); } return newImports; }
javascript
{ "resource": "" }
q41642
addExtras
train
function addExtras( currentObj, baseObj, fn ) { // Return function name. var clss = currentObj.getClass(); for ( var k in currentObj) { if (currentObj.hasOwnProperty(k) && typeof currentObj[k] == 'function' && k != fn) { currentObj[k] = currentObj[k].bind(currentObj); currentObj[k].$name = k; currentObj[k].$Class = clss; } } addInstance(currentObj); // eachPropertyOf(currentObj.Private, function(val, key){ if (currentObj.Private && typeof currentObj.Private[fn] == 'function') { currentObj[fn] = currentObj.Private[fn]; } if (currentObj[fn]) { currentObj[fn].$Class = currentObj.getClass(); currentObj[fn].$name = fn; } // Check if function have constant. if (currentObj.Const) { var cnt = currentObj.Const; delete cnt.Static; for (k in cnt) { cnt.hasOwnProperty(k) && currentObj.$add(currentObj, k, cnt[k], true); } } // migrate information about abstract method to base class. if (currentObj.isAbstract) { var absMethods = currentObj.prototype.$get("Abstract"); currentObj.setAbstractMethods = function( solidObj ) { for ( var k in absMethods) { if (absMethods.hasOwnProperty(k)) { if (typeof solidObj[k] != 'function') { throw "Abstract method " + k + " is not implemented by " + solidObj.getClass(); } this[k] = solidObj[k]; } } if (baseObj && baseObj.prototype.isAbstract) { baseObj.prototype.setAbstractMethods(solidObj); } }; } if (baseObj) { if (baseObj.prototype.isAbstract) { baseObj.prototype.getSub = function( ) { return currentObj.isAbstract ? currentObj.getSub() : currentObj; }; } currentObj.base = baseObj; baseObj.$ADD(currentObj); } }
javascript
{ "resource": "" }
q41643
train
function(opts) { opts = opts || {}; this.heartbeat = null; this.timeout = null; this.disconnectOnTimeout = opts.disconnectOnTimeout; if(opts.heartbeat) { this.heartbeat = opts.heartbeat * 1000; // heartbeat interval this.timeout = opts.timeout * 1000 || this.heartbeat * 2; // max heartbeat message timeout this.disconnectOnTimeout = true; } this.timeouts = {}; this.clients = {}; }
javascript
{ "resource": "" }
q41644
MemoryAdapter
train
function MemoryAdapter(initialFiles) { if (!(this instanceof MemoryAdapter)) { return new MemoryAdapter(initialFiles); } this.entries = new Map(); // load initial file buffers if (typeof initialFiles === "object" && initialFiles) { Object.keys(initialFiles).forEach((fileName) => { const buf = Buffer.from(initialFiles[fileName]); this.entries.set(fileName, buf); }); } }
javascript
{ "resource": "" }
q41645
train
function (cmd, cwd, callback) { var async = typeof callback === 'function'; var result = exec( cmd, {cwd: cwd}, async ? callback : undefined ); return result.code !== 0 && !async ? result.stdout : undefined; }
javascript
{ "resource": "" }
q41646
train
function () { return [CORDOVA_PATH] .concat(Array.prototype.map.call(arguments || [], function (arg) { return '\'' + arg.replace("'", "\\'") + '\''; })).join(' '); }
javascript
{ "resource": "" }
q41647
moveRender
train
function moveRender (type) { var method = type ? 'down' : 'up' ui .left(lastLen + 2) .up(count - cur) .write(' ') // Each time move to right-bottom. ui[method]() .left(2) .write(chalk.blue(pointer)) .left(2) .down(count - (type ? ++cur : --cur)) .right(lastLen + 2) }
javascript
{ "resource": "" }
q41648
cancel
train
function cancel(callback) { if (!deis._authenticated) { return callback(new Error('You need to login first')); } commons.del(format('/%s/auth/cancel/', deis.version), function() { deis.api.logout(callback); }); }
javascript
{ "resource": "" }
q41649
createProfile
train
function createProfile(done) { if (self.closed) return done(null); temp.mkdir('browser-controller', function(err, dirpath) { if (err) return done(err); self.userDir = dirpath; done(null); }); }
javascript
{ "resource": "" }
q41650
closeChromium
train
function closeChromium(done) { var child = self.process; // remove error handlers if (child) { child.removeListener('error', handlers.relayError); child.removeListener('exit', handlers.prematureExit); child.stderr.removeListener('error', handlers.relayError); child.stdout.removeListener('error', handlers.relayError); } // kill chromium if (isKilled(child) === false) { // make sure stdout & stderr isn't paused, since the child won't // emit 'close' until the file descriptors are destroyed child.stdout.resume(); child.stderr.resume(); child.once('close', done); child.kill(); } else { done(null); } }
javascript
{ "resource": "" }
q41651
removePofile
train
function removePofile(done) { if (!self.userDir) return done(null); rimraf(self.userDir, done); }
javascript
{ "resource": "" }
q41652
SvcAws
train
function SvcAws (requestedSvc, options) { if (this.constructor.name === 'Object') { throw new Error('Must be instantiated using new') } else if (this.constructor.name === 'SvcAws') { throw new Error('Abstract class ' + this.constructor.name + ' should not be instantiated') } EventEmitter.call(this) let self = this // initialize the property bag of AWS services which will be created this._services = {} let credOptions = Object.assign({}, options) internals.initLogger(options.isLogging) this.logger = internals.logger credOptions.logger = this.logger let credsManager = new Credentials(credOptions) credsManager.once(internals.EVENT_INITIALIZED, function (err, data) { if (err) { self.logger.warn(internals.EVENT_INITIALIZED, err) internals.emitAsync.call(self, internals.EVENT_INITIALIZED, err) return } else { self.logger.info(internals.EVENT_INITIALIZED, 'success') } if (self._services.hasOwnProperty(requestedSvc.serviceIdentifier)) { let serviceName = requestedSvc.serviceIdentifier self.logger.info('Refreshing service: ' + serviceName) } // Always instantiate the requested aws service, even if old one exists internals.newService.call(self, credsManager._awsConfig, requestedSvc) }) }
javascript
{ "resource": "" }
q41653
train
function(x,y,depth,maxDepth) { if( depth >= maxDepth ) { console.warn("MAXIMUM DEPTH REACHED: %d", maxDepth); return; } if(!this.isCell(x,y)) { return; } let dirs = this.getShuffledNeighborDirs( x, y ); for( var key in dirs ) { var sDir = dirs[key]; var n = this.getNeighbor(x, y, sDir); if(n===null) { continue; } if(this.isMasked(n.x,n.y)) { continue; } if( this.isCell(n.x, n.y) && !this.hasConnections(n.x, n.y) ) { // Connect cell to neighbor this.connectUndirected( x, y, sDir); this.carveMaze( n.x, n.y, depth + 1, maxDepth ); } } }
javascript
{ "resource": "" }
q41654
train
function(spec) { spec = spec || {}; let aMask = spec.mask || [], start = spec.start || {}, x = start.c || 0, y = start.r || 0; this.fill(0); for( var mKey in aMask ) { var mask = aMask[mKey]; this.mask(mask.c,mask.r); } let maxDepth = this.xSize * this.ySize; this.carveMaze(x,y,0,maxDepth); // derived class can parse extra spec parameters this.afterGenerate(spec); }
javascript
{ "resource": "" }
q41655
invokeOnComplete
train
function invokeOnComplete(slinkerOptions) { if (typeof slinkerOptions.onComplete === 'function' && slinkerOptions.modules.length === symlinksCreated.length) { slinkerOptions.onComplete(); } }
javascript
{ "resource": "" }
q41656
checkPreconditions
train
function checkPreconditions(options) { if (!options) { throw Error("'options' must be specified!"); } if (!(options.modules instanceof Array)) { throw Error("'options.modules' must be an array!"); } // If the modules array is empty, immediately call the onComplete() if it exists if (!options.modules.length) { if (options.onComplete) { invokeOnComplete(options); } return false; } return true; }
javascript
{ "resource": "" }
q41657
train
function() { if (!(this instanceof clazz)) { throw new Error("Use new keyword to create a new instance or call/apply class with right scope"); } Class.onBeforeInstantiation && Class.onBeforeInstantiation(this); // remember the current super property var temp = this.__super__; // set the right super class prototype this.__super__ = superClass; // call the right constructor if (constructor) { constructor.apply(this, arguments); } else if (superClass) { superClass.apply(this, arguments); } // reset the current super property this.__super__ = temp; Class.onAfterInstantiation && Class.onAfterInstantiation(this); }
javascript
{ "resource": "" }
q41658
eatCharacter
train
function eatCharacter(stream) { var first = stream.next(); // Read special literals: backspace, newline, space, return. // Just read all lowercase letters. if (first.match(/[a-z]/) && stream.match(/[a-z]+/, true)) { return; } // Read unicode character: \u1000 \uA0a1 if (first === "u") { stream.match(/[0-9a-z]{4}/i, true); } }
javascript
{ "resource": "" }
q41659
__typeCheck
train
function __typeCheck(type, valueToCheck, optional) { var correct = typeof(valueToCheck) == type; if(optional) { // Exception if the variable is optional, than it also may be undefined or null correct = correct || valueToCheck === undefined || valueToCheck === null; } if(!correct) { throw new Error("Invalid argument type received; expected "+type+ ", but received "+typeof(valueToCheck)); } }
javascript
{ "resource": "" }
q41660
Queue
train
function Queue(client, channel){ EE.call(this); this.client = client; this.channel = channel; this.id = channel.$getId(); return this; }
javascript
{ "resource": "" }
q41661
checkForAuths
train
function checkForAuths(){ $twitter.isAuthenticated = $body.attr('data-twitter-auth') === 'true' ? true : false $facebook.isAuthenticated = $body.attr('data-facebook-auth') === 'true' ? true : false $dropbox.isAuthenticated = $body.attr('data-dropbox-auth') === 'true' ? true : false }
javascript
{ "resource": "" }
q41662
wireDestinationClickHandlers
train
function wireDestinationClickHandlers(){ $twitter.isAuthenticated && $twitterDestination.bind('click', twitterDestinationClickHandler) $facebook.isAuthenticated && $facebookDestination.bind('click', facebookDestinationClickHandler) $dropbox.isAuthenticated && $dropboxDestination.bind('click', dropboxDestinationClickHandler) }
javascript
{ "resource": "" }
q41663
fetchImagesForFbGallery
train
function fetchImagesForFbGallery(id){ $ .get('/facebook/get_photos_from_album_id?id='+id) .success(function(d, resp, x){ console.dir(d) var thumbs = "" if(d.message) thumbs += "<p>"+d.message+"</p>" else{ d.data.forEach(function(el,i){ // console.dir(el) thumbs += "<img data-standard-resolution='"+el.images[2].source+"' src='"+el.picture+"' />" }) } $oneUpFacebookWrapper .before(thumbs) $photoPickerFacebook .show() $spin .hide() // wire up the images int the fb gallery wireFacebookGalleryPicker() progressToNextStep($stepTwo, function(){ $stepThree.slideDown(333) }) }) .error(function(e){ if(e.status === 404) alert(e.responseText || 'Images were not found.') if(e.status === 403) alert(e.responseText || 'That request was not allowed.') if(e.status === 500) alert(e.responseText || 'Something went really wrong.') }) }
javascript
{ "resource": "" }
q41664
twitterOneUpClickHandler
train
function twitterOneUpClickHandler(e){ closeOneUp() var standardResUrl = $(e.target).attr('data-standard-resolution') // e.target.dataset.standardResolution var img = new Image() $spin.show() img.src = standardResUrl img.onload = function(){ $spin.hide() $oneUpTwitter .prepend(img) var $oneUpContainer = $photoPickerTwitter.find('.one-up-wrapper') positionFromTop( $photoPickerTwitter, $oneUpContainer ) showOverlay() $oneUpTwitter .find('> .close-one-up:first') .show() .end() .show() } }
javascript
{ "resource": "" }
q41665
wireOneUpHandlers
train
function wireOneUpHandlers(){ // Bind ESC key $document.bind('keyup', function(e){ if (e.keyCode === 27) { return closeOneUp() } }) // end keyup // The "x" button on the one up, close it. $closeOneUp.bind('click', closeOneUp ) // The overlay $overlay.bind('click', closeOneUp ) }
javascript
{ "resource": "" }
q41666
wireUsePhotoHandlers
train
function wireUsePhotoHandlers(){ $usePhoto.bind('click submit', function(e){ if(e.target.id === 'facebook-use-photo'){ // We don't want to show the facebook option, because // it is the source of the image. $facebookDestination.hide() _photoToUse = localStorage.imageToPipe || $('.one-up:visible').find('img')[0].src closeOneUp() $stepFourDestinationWrapper.show() progressToNextStep($stepThree, function(){ $stepFour.slideDown(333) }) } if(e.target.id === 'twitter-use-photo'){ // We don't want to show the facebook option, because // it is the source of the image. $twitterDestination.hide() _photoToUse = localStorage.imageToPipe || $('.one-up:visible').find('img')[0].src closeOneUp() $stepThreeDestinationWrapper.show() progressToNextStep($stepTwo, function(){ $stepThree.slideDown(333) }) } if(e.target.id === 'url-use-photo'){ _photoToUse = $photoFromUrl.val() || localStorage.imageToPipe $stepThreeDestinationWrapper.show() progressToNextStep($stepTwo, function(){ $stepThree.slideDown(333) }) } localStorage.imageToPipe = _photoToUse console.log(_photoToUse) console.log(localStorage.imageToPipe) return false }) // end bind() }
javascript
{ "resource": "" }
q41667
_cleanseInput
train
function _cleanseInput(dirty){ var clean = '' clean = dirty.replace('@', '') clean = clean.replace('#', '') clean = clean.replace(/\s/g, '') return clean }
javascript
{ "resource": "" }
q41668
_failHandler
train
function _failHandler(e){ $spin.hide() if(e.status === 400) alert(e.responseText || 'Bad request.') if(e.status === 401) alert(e.responseText || 'Unauthorized request.') if(e.status === 402) alert(e.responseText || 'Forbidden request.') if(e.status === 403) alert(e.responseText || 'Forbidden request.') if(e.status === 404) alert(e.responseText || 'Images were not found.') if(e.status === 405) alert(e.responseText || 'That method is not allowed.') if(e.status === 408) alert(e.responseText || 'The request timed out. Try again.') if(e.status === 500) alert(e.responseText || 'Something went really wrong.') postData = postUrl = '' cb & cb() }
javascript
{ "resource": "" }
q41669
_selectPhotoForPipe
train
function _selectPhotoForPipe(e){ var img = $('.one-up:visible').find('img')[0].src localStorage.imageToPipe = img closeOneUp() window.location = "/instagram/pipe/to" }
javascript
{ "resource": "" }
q41670
positionFromTop
train
function positionFromTop(container, el){ var containerTop = container.position().top , windowTop = $window.scrollTop() if(containerTop > windowTop) return el.css('top', 0) var pos = windowTop - containerTop return el.css('top', pos) }
javascript
{ "resource": "" }
q41671
featureDetector
train
function featureDetector(){ // Check if client can access file sytem (from Modernizer) var elem = document.createElement('input') elem.type = 'file' window.Photopipe.hasFileSystem = !elem.disabled // Check if client has media capture access window.Photopipe.hasMediaCapture = !!navigator.getUserMedia || !!navigator.webkitGetUserMedia || !!navigator.mozGetUserMedia || !!navigator.msGetUserMedia // Check if client has the download attribute for anchor tags window.Photopipe.hasDownloadAttribute = ("download" in document.createElement("a")) // Check for localstorage var storage try{ if(localStorage.getItem) {storage = localStorage} }catch(e){} window.Photopipe.hasLocalStorage = storage }
javascript
{ "resource": "" }
q41672
train
function (listener,evtObj) { if (!_.isFunction(listener) || !_.isObject(evtObj)) return false; var args = evtObj.arguments; switch (args.length) { case 1: listener(args[0]); break; case 2: listener(args[0],args[1]); break; case 3: listener(args[0],args[1],args[2]); break; case 4: listener(args[0],args[1],args[2],args[3]); break; case 5: listener(args[0],args[1],args[2],args[3],args[4]); break; default: listener.apply(undefined,args); } }
javascript
{ "resource": "" }
q41673
train
function (listener,prepend) { if ('function' !== typeof listener) return false; if (!_listeners) _listeners=listener; else if (typeof _listeners == 'object') { if (!prepend) _listeners.push(listener); else _listeners.unshift(listener); } else { if (!prepend) _listeners = [_listeners,listener]; else _listeners = [listener,_listeners]; } return this; }
javascript
{ "resource": "" }
q41674
train
function (listener, prepend) { if ('function' === typeof listener) { var self = this, g = function (e) { e.lastListeners--; self.removeListener(g); listener.apply(listener, arguments); }; g.listener = listener; this.addListener(g,prepend) } return this; }
javascript
{ "resource": "" }
q41675
train
function (listener) { if ('function' !== typeof listener) return false; var list = _listeners; var position = -1; if (list === listener || (typeof list.listener === 'function' && list.listener === listener)) _listeners = undefined; else if (typeof list === 'object') { for (var i = 0, length = list.length; i < length; i++) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position > -1) list.splice(position, 1); if (list.length == 1) _listeners = list[0]; } return this; }
javascript
{ "resource": "" }
q41676
train
function(b) { if (b instanceof Model) { if (this.constructor !== b.constructor) return false; b = b.attributes; } return _.isEqual(this.attributes, b); }
javascript
{ "resource": "" }
q41677
setInitalStyle
train
function setInitalStyle() { document.body.style.margin = 0; document.body.style.borderTopWidth = '10px'; document.body.style.borderTopStyle = 'solid'; }
javascript
{ "resource": "" }
q41678
style
train
function style() { var testsAre = 'pending'; if (failed > 0) { testsAre = 'failing'; } else if (passed > 0) { testsAre = 'passing'; } document.body.style.borderTopColor = richColors[testsAre]; faviconEl.setAttribute('href', favicons[testsAre]); document.body.style.backgroundColor = colors[testsAre]; }
javascript
{ "resource": "" }
q41679
hijackLog
train
function hijackLog() { var oldLog = console.log; console.log = function (message) { count(message); style(); var match = (message + '').match(/^# #tapeworm-html(.*)/); var isHtml = !!match; if (match) { var html = match[1]; var div = testResults.appendChild(document.createElement('div')); div.innerHTML = html; } else { var pre = testResults.appendChild(document.createElement('pre')); pre.style.margin = 0; pre.innerHTML = message + '\n'; oldLog.apply(console, arguments); } }; }
javascript
{ "resource": "" }
q41680
infect
train
function infect(tape) { if (!document) { tape.Test.prototype.html = function () {}; return; } injectFavicon(); createTestResults(); setInitalStyle(); decorateTape(tape); hijackLog(); style(); }
javascript
{ "resource": "" }
q41681
train
function(angle) { // TODO this clears any scale, should we care? var a = Math.cos(angle); var b = Math.sin(angle); this.matrix[0] = this.matrix[3] = a; this.matrix[1] = (0-b); this.matrix[2] = b; }
javascript
{ "resource": "" }
q41682
nextTickFn
train
function nextTickFn() { // setImmediate allows to run task after already queued I/O callbacks if (typeof setImmediate === 'function') { return setImmediate; } else if (typeof process !== 'undefined' && process.nextTick) { return function(fn) { process.nextTick(fn); } } else { return function(fn) { setTimeout(fn, 0); } } }
javascript
{ "resource": "" }
q41683
resolve
train
function resolve(val, i, isPath) { val = val.replace('~', ''); return Promise.resolve(System.normalize(val)) .then(function(normalized) { return System.locate({name: normalized, metadata: {}}); }) .then(function(address) { if (isPath) { options.includePaths.push( path.resolve(address.replace('file:', '').replace('.js', '')) ); } else { var originalRelativePath = path.relative( path.dirname(file.path), path.resolve(address.replace('file:', '').replace('.js', '')) ); var originalRelativePathArray = originalRelativePath.split(path.sep); replacements[i] = path.posix? path.posix.join.apply(this, originalRelativePathArray): path.normalize(originalRelativePath).replace(/\\/g, '/').replace('//', '/'); } }); }
javascript
{ "resource": "" }
q41684
resolveAll
train
function resolveAll(fileContent) { var matches = [].concat(fileContent.match(regexFile)).filter(Boolean).map(extractFile); var pathsMatches = [].concat(fileContent.match(regexPath)).filter(Boolean).map(extractFile); if (matches.length === 0 && pathsMatches.length === 0) { return new RSVP.Promise(function(resolve) { resolve(fileContent) }); } var promises = [].concat(matches.map(resolveFile)).filter(Boolean); var promisesPaths = [].concat(pathsMatches.map(resolvePath)).filter(Boolean); return RSVP.all(promises.concat(promisesPaths)).then(function() { for (var i = 0, len = matches.length; i < len; i++) { fileContent = fileContent.replace(matches[i], replacements[i]); } return fileContent; }); }
javascript
{ "resource": "" }
q41685
Client
train
function Client(opts) { this.opts = new clientOptions(opts) this.streamData = {} this.currentIndex = 0 this.cachedItems = new lru({maxSize: this.opts.maxCacheSize}) }
javascript
{ "resource": "" }
q41686
create
train
function create(basedir, defaults) { LOG.info("Initializing application configuration"); var config = defaults || {}; _loadConfigurationFiles(basedir, config); _validateConfig(config); if (config.DubBotBase.isConfigImmutable) { _freezeConfig(config); LOG.info("Configuration set up successfully. The config object is now frozen and no changes can be made to it."); } else { LOG.info("Configuration set up successfully. Config has not been frozen due to override of the DubBotBase.isConfigImmutable property."); } return config; }
javascript
{ "resource": "" }
q41687
_copyConfigFromFile
train
function _copyConfigFromFile(filePath, config) { LOG.info("Attempting to load configuration file '{}'", filePath); var fileConfig = require(filePath); _mergeConfig(config, fileConfig); LOG.info("Successfully read configuration file '{}'", filePath); }
javascript
{ "resource": "" }
q41688
_freezeConfig
train
function _freezeConfig(config) { Object.freeze(config); for (var key in config) { if (typeof config[key] === "object") { _freezeConfig(config[key]); } } }
javascript
{ "resource": "" }
q41689
_mergeConfig
train
function _mergeConfig(base, override) { for (var key in override) { if (base[key] && typeof base[key] === "object" && typeof override[key] === "object") { _mergeConfig(base[key], override[key]); } else { base[key] = override[key]; } } }
javascript
{ "resource": "" }
q41690
_validateConfig
train
function _validateConfig(config) { for (var i = 0; i < REQUIRED_CONFIG_VARIABLES.length; i++) { var key = REQUIRED_CONFIG_VARIABLES[i]; var value = config.DubBotBase[key]; if (!value || value === "UNSET") { throw new Error("No value has been set in config for key: DubBotBase." + key); } } }
javascript
{ "resource": "" }
q41691
train
function () { var value, c = input.charCodeAt(i); if ((c > 57 || c < 45) || c === 47) return; if (value = $(/^(-?\d*\.?\d+)(px|%|em|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn|dpi|dpcm|dppx|rem|vw|vh|vmin|vm|ch)?/)) { return new(tree.Dimension)(value[1], value[2]); } }
javascript
{ "resource": "" }
q41692
train
function(srcUrl, dstW, dstH, callback){ // to compute the width/height while keeping aspect var cpuScaleAspect = function(maxW, maxH, curW, curH){ var ratio = curH / curW; if( curW >= maxW && ratio <= 1 ){ curW = maxW; curH = maxW * ratio; }else if(curH >= maxH){ curH = maxH; curW = maxH / ratio; } return { width: curW, height: curH }; } // callback once the image is loaded var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; var onLoad = __bind(function(){ // init the canvas var canvas = document.createElement('canvas'); canvas.width = dstW; canvas.height = dstH; var ctx = canvas.getContext('2d'); // TODO is this needed ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height); // scale the image while preserving the aspect var scaled = cpuScaleAspect(canvas.width, canvas.height, image.width, image.height); // actually draw the image on canvas var offsetX = (canvas.width - scaled.width )/2; var offsetY = (canvas.height - scaled.height)/2; ctx.drawImage(image, offsetX, offsetY, scaled.width, scaled.height); // dump the canvas to an URL var mimetype = "image/png"; var newDataUrl = canvas.toDataURL(mimetype); // notify the url to the caller callback && callback(newDataUrl) }, this); // Create new Image object var image = new Image(); image.onload = onLoad; image.src = srcUrl; }
javascript
{ "resource": "" }
q41693
objectCreateComputedProp
train
function objectCreateComputedProp(obj, prop, setter, enumerable = true) { let propValue; let newValue; let needsInitialization = true; let allowSet = false; let needsNewValue = true; let isGeneratingNewValue = false; const dependencyTracker = () => { if (needsNewValue) { return; } needsNewValue = true; // If we have watchers on this computed prop, then queue the // value generator function. // else, just notify dependents. if (alwaysForceExec || setter.forceExec || obj[OBSERVABLE_IDENTIFIER].props[prop].watchers.size) { nextTick.queue(setPropValue); } else if (obj[OBSERVABLE_IDENTIFIER].props[prop].dependents.size) { obj[OBSERVABLE_IDENTIFIER].props[prop].dependents.notify(); } }; const setPropValue = silentSet => { // if there is no longer a need to regenerate the value, exit. // this can happen when other logic accesses the computed getter // between scheduled updates. // Also, in order to avoid looping, if value is currently being // generated, then also exit. if (!needsNewValue || isGeneratingNewValue) { return; } isGeneratingNewValue = true; try { setDependencyTracker(dependencyTracker); newValue = setter.call(obj, obj); unsetDependencyTracker(dependencyTracker); // IMPORTANT: turn if off right after setter is run! if (silentSet) { propValue = newValue; if (obj[OBSERVABLE_IDENTIFIER].props[prop].deep) { makeObservable(propValue); } } else { // Update is done via the prop assignment, which means that // handing of `deep` and all dependent/watcher notifiers is handled // as part of the objectWatchProp() functionality. // Doing the update this way also supports the use of these // objects with other library that may also intercept getter/setters. allowSet = true; needsNewValue = false; obj[prop] = newValue; } } catch (e) { allowSet = needsNewValue = isGeneratingNewValue = false; newValue = undefined; unsetDependencyTracker(dependencyTracker); throw e; } allowSet = needsNewValue = isGeneratingNewValue = false; newValue = undefined; }; dependencyTracker.asDependent = true; dependencyTracker.forProp = setPropValue.forProp = prop; // Does property already exists? Delete it. if (prop in obj) { delete obj[prop]; // Was prop an observable? if so, signal that interceptors must be redefined. if (obj[OBSERVABLE_IDENTIFIER] && obj[OBSERVABLE_IDENTIFIER].props[prop]) { obj[OBSERVABLE_IDENTIFIER].props[prop].setupInterceptors = true; } } defineProperty( obj, prop, undefined, function(){ if (needsInitialization) { needsInitialization = false; setPropValue(true); } else if (needsNewValue) { setPropValue(); } return propValue; }, function () { if (allowSet) { propValue = newValue; } return propValue; }, true, !!enumerable ); objectWatchProp(obj, prop); }
javascript
{ "resource": "" }
q41694
train
function( input, charset ) { if( charset && !Buffer.isBuffer( input ) ) { return MIME.Iconv.encode( input, charset ) } else { return Buffer.isBuffer( input ) ? input.toString( 'base64' ) : Buffer.from( input ).toString( 'base64' ) } }
javascript
{ "resource": "" }
q41695
train
function( input, charset ) { if( /iso-?2022-?jp/i.test( charset ) ) { charset = 'shift_jis' } if( charset ) { return MIME.Iconv.decode( Buffer.from( input, 'base64' ), charset ) } else { return Buffer.from( input, 'base64' ).toString() } }
javascript
{ "resource": "" }
q41696
waitFor
train
function waitFor(checkFn, timeout, cb) { var start = Date.now(); function runWaitFor() { if (checkFn()) { cb(); } else if ((Date.now() - start) <= timeout) { setTimeout(runWaitFor, 100); } else { cb(new Error('Timeout of ' + timeout + 'ms reached. This usually means something went wrong. Please try your SVGs inside icomoon itself, https://icomoon.io/app-old')); } } runWaitFor(); }
javascript
{ "resource": "" }
q41697
train
function (set, receive) { var values = setValues.call(set); var next; do { next = values.next(); } while (!next.done && receive(next.value)); }
javascript
{ "resource": "" }
q41698
done
train
function done () { that.fetchQueue.stopFetching(key, arguments); that.store(key, arguments, callback); }
javascript
{ "resource": "" }
q41699
train
function(source, target) { var linkedTarget = $(target); clearLinkedData(target); $.each(source, function(key, sourceValue) { if (isInternal(key)) { return; } var targetValue = null; if ($.isPlainObject(sourceValue)) { targetValue = target[key]; setLinkedData(sourceValue, targetValue); } else if ($.isArray(sourceValue)) { targetValue = target[key]; $.each(sourceValue, function(index, arrayValue) { var targetArrayValue = targetValue[index]; setLinkedData(arrayValue, targetArrayValue); }); } else { linkedTarget.setField(key, sourceValue); } return; }); }
javascript
{ "resource": "" }