_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q64500
journal
test
function journal() { 'use strict'; var fs = require('fs'); // private properties var eventList = { 'creationEvents' : {}, 'executionEvents' : {} }; var logMode; // sets the log method: 'q', 'v' or 'l' // exposed by the agency constructor function setLogMode(mode) { logMode = mode; } // records the agent's validation and creation events in a temporary structure if log method is 'l' or // outputs the same events to the console if method is 'v' function logCreationEvent(id, type, message, time) { if (logMode === 'l') { if (!eventList.creationEvents[id]) { eventList.creationEvents[id] = []; } eventList.creationEvents[id].push({'type': type, 'event': message, "timestamp": time}); } else if (logMode === 'v') { console.log(type + ': Agent ' + id + ' ' + message + ' on ' + time); } } // records the agent's execution events in a temporary structure if log method is 'l' or // outputs the same events to the console if method is 'v' function logExecutionEvent(id, type, message, time) { if (logMode === 'l') { if (!eventList.executionEvents[id]) { eventList.executionEvents[id] = []; } eventList.executionEvents[id].push({'type': type, 'event': message, "timestamp": time}); } else if (logMode === 'v') { console.log(type + ': Agent ' + id + ' ' + message + ' on ' + time); } } // outputs the contents of the temporary creation and execution structure to a specific file // defined by the user; if file is not defined outputs to a default file; otherwise outputs error to the console function report(logFile) { var defaultLogFile = (new Date()).toJSON() + '.log'; var data = JSON.stringify(eventList, null, 3); if (logFile) { fs.writeFile(logFile, data, function(err) { if(err) { console.log('\nCould not write log to file "' + logFile + '"\n' + err); fs.writeFile(defaultLogFile, data, function(err) { if(err) { console.log('Could not write log file: ' + err); } else { console.log('Log was written on default file "' + defaultLogFile + '"'); } }); } }); } else { fs.writeFile(defaultLogFile, data, function(err) { if(err) { console.log('Could not write log file: ' + err); } }); } } //public interface return { setLogMode: setLogMode, logCreationEvent: logCreationEvent, logExecutionEvent: logExecutionEvent, report: report }; }
javascript
{ "resource": "" }
q64501
logCreationEvent
test
function logCreationEvent(id, type, message, time) { if (logMode === 'l') { if (!eventList.creationEvents[id]) { eventList.creationEvents[id] = []; } eventList.creationEvents[id].push({'type': type, 'event': message, "timestamp": time}); } else if (logMode === 'v') { console.log(type + ': Agent ' + id + ' ' + message + ' on ' + time); } }
javascript
{ "resource": "" }
q64502
logExecutionEvent
test
function logExecutionEvent(id, type, message, time) { if (logMode === 'l') { if (!eventList.executionEvents[id]) { eventList.executionEvents[id] = []; } eventList.executionEvents[id].push({'type': type, 'event': message, "timestamp": time}); } else if (logMode === 'v') { console.log(type + ': Agent ' + id + ' ' + message + ' on ' + time); } }
javascript
{ "resource": "" }
q64503
report
test
function report(logFile) { var defaultLogFile = (new Date()).toJSON() + '.log'; var data = JSON.stringify(eventList, null, 3); if (logFile) { fs.writeFile(logFile, data, function(err) { if(err) { console.log('\nCould not write log to file "' + logFile + '"\n' + err); fs.writeFile(defaultLogFile, data, function(err) { if(err) { console.log('Could not write log file: ' + err); } else { console.log('Log was written on default file "' + defaultLogFile + '"'); } }); } }); } else { fs.writeFile(defaultLogFile, data, function(err) { if(err) { console.log('Could not write log file: ' + err); } }); } }
javascript
{ "resource": "" }
q64504
scopeUrl
test
function scopeUrl(options, inst) { options = _.extend({}, inst, options) if (!options.teamcenter_team_id) throw new Error('teamcenter_team_id required to make TeamCenterContact instance api calls') if (!options.teamcenter_member_id) throw new Error('teamcenter_member_id require to make TeamCenterContact instance api calls') return ngin.TeamCenterTeam.urlRoot() + '/' + options.teamcenter_team_id + ngin.TeamCenterMember.urlRoot() + '/' + options.teamcenter_member_id + TeamCenterContact.urlRoot() }
javascript
{ "resource": "" }
q64505
ArticleTranslation
test
function ArticleTranslation(parent, definition) { var key; for (key in updateMixin) { this[key] = updateMixin[key]; } ArticleTranslation.super_.apply(this, arguments); }
javascript
{ "resource": "" }
q64506
MacroAction
test
function MacroAction(parent, definition) { var key; for (key in updateMixin) { this[key] = updateMixin[key]; } MacroAction.super_.apply(this, arguments); }
javascript
{ "resource": "" }
q64507
map
test
function map(obj, source, target, isRecursive = true) { // Check if parameters have invalid types if ((typeof obj) != "object") throw new TypeError("The object should be JSON"); if ((typeof source) != "string" && (typeof source) != "array") throw new TypeError("Source should be aither string or array"); if ((typeof target) != "string" && (typeof target) != "array") throw new TypeError("Target should be aither string or array"); // result object init let res = {}; // get array of properties need to be converted let propS = (typeof source == "string") ? source.replace(/ /g, '').split(",") : source; let propT = (typeof target == "string") ? target.replace(/ /g, '').split(",") : target; // each property is checked ... for (let propertyName in obj) { // ... if need be converted or not let propIndexInSource = propS.indexOf(propertyName); let newName = (propIndexInSource != -1) ? propT[propIndexInSource] : propertyName; // take into account that property could be an array if (isRecursive && obj[propertyName] instanceof Array) { res[newName] = []; for (var i = 0; i < obj[propertyName].length; i++) { let mappedItem = map(obj[propertyName][i], source, target, isRecursive) res[newName].push(mappedItem); } continue; } // take into account that JSON object can have nested objects if (isRecursive && ((typeof obj[propertyName]) == "object")) res[newName] = map(obj[propertyName], source, target, isRecursive); else res[newName] = obj[propertyName]; } return res; }
javascript
{ "resource": "" }
q64508
test
function (visit, onFail, opts) { var fail = onFail ? onFail : utils.ret(false), config = opts || { compact: true }; return function (list) { var p = Promise.resolve(false), results = []; list.forEach(function (l, i) { p = p.then(visit.bind(null, l)) .catch(function (err) { return fail(err, l); }) .then(function (result) { results.push(result); if(config.onProgress) config.onProgress(list.length, i + 1, l); }); }); return p.then(function () { return config.compact ? results.filter(Boolean) : results; }); }; }
javascript
{ "resource": "" }
q64509
test
function() { console.warn('Code is using deprecated teams_advancing, switch to teamsAdvancing') var where = (new Error().stack || '').split('\n', 3)[2] if (where) console.warn(where) this.teamsAdvancing.apply(this, arguments) }
javascript
{ "resource": "" }
q64510
getIndexOfPrimitive
test
function getIndexOfPrimitive(primitive, array, startingPosition) { if (startingPosition === void 0) { startingPosition = 0; } errorIfNotPrimitive_1.errorIfNotPrimitive(primitive); error_if_not_populated_array_1.errorIfNotPopulatedArray(array); errorIfNotInteger_1.errorIfNotInteger(startingPosition); return array.indexOf(primitive, startingPosition); }
javascript
{ "resource": "" }
q64511
loads
test
function loads(xhr, ee) { var onreadystatechange , onprogress , ontimeout , onabort , onerror , onload , timer; /** * Error listener. * * @param {Event} evt Triggered error event. * @api private */ onerror = xhr.onerror = one(function onerror(evt) { var status = statuscode(xhr) , err = fail(new Error('Network request failed'), status); ee.emit('error', err); ee.emit('end', err, status); }); /** * Fix for FireFox's odd abort handling behaviour. When you press ESC on an * active request it triggers `error` instead of abort. The same is called * when an HTTP request is canceled onunload. * * @see https://bugzilla.mozilla.org/show_bug.cgi?id=768596 * @see https://bugzilla.mozilla.org/show_bug.cgi?id=880200 * @see https://code.google.com/p/chromium/issues/detail?id=153570 * @param {Event} evt Triggerd abort event * @api private */ onabort = xhr.onabort = function onabort(evt) { onerror(evt); }; /** * ReadyStateChange listener. * * @param {Event} evt Triggered readyState change event. * @api private */ onreadystatechange = xhr.onreadystatechange = function change(evt) { var target = evt.target; if (4 === target.readyState) return onload(evt); }; /** * The connection has timed out. * * @api private */ ontimeout = xhr.ontimeout = one(function timeout(evt) { ee.emit('timeout', evt); // // Make sure that the request is aborted when there is a timeout. If this // doesn't trigger an error, the next call will. // if (xhr.abort) xhr.abort(); onerror(evt); }); // // Fallback for implementations that did not ship with timer support yet. // Microsoft's XDomainRequest was one of the first to ship with `.timeout` // support so we all XHR implementations before that require a polyfill. // // @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816 // if (xhr.timeout) timer = setTimeout(ontimeout, +xhr.timeout); /** * IE needs have it's `onprogress` function assigned to a unique function. So, * no touchy touchy here! * * @param {Event} evt Triggered progress event. * @api private */ onprogress = xhr.onprogress = function progress(evt) { var status = statuscode(xhr) , data; ee.emit('progress', evt, status); if (xhr.readyState >= 3 && status.code === 200 && (data = response(xhr))) { ee.emit('stream', data, status); } }; /** * Handle load events an potential data events for when there was no streaming * data. * * @param {Event} evt Triggered load event. * @api private */ onload = xhr.onload = one(function load(evt) { var status = statuscode(xhr) , data = response(xhr); if (status.code < 100 || status.code > 599) return onerror(evt); // // There is a bug in FireFox's XHR2 implementation where status code 204 // triggers a "no element found" error and bad data. So to be save here, // we're just **never** going to emit a `stream` event as for 204's there // shouldn't be any content. // // @see https://bugzilla.mozilla.org/show_bug.cgi?id=521301 // if (data && status.code !== 204) { ee.emit('stream', data, status); } ee.emit('end', undefined, status); }); // // Properly clean up the previously assigned event listeners and timers to // prevent potential data leaks and unwanted `stream` events. // ee.once('end', function cleanup() { xhr.onreadystatechange = onreadystatechange = xhr.onprogress = onprogress = xhr.ontimeout = ontimeout = xhr.onerror = onerror = xhr.onabort = onabort = xhr.onload = onload = nope; if (timer) clearTimeout(timer); }); return xhr; }
javascript
{ "resource": "" }
q64512
addWithDependencies
test
function addWithDependencies (allFiles, newFile, dependencies, currentFiles, cycleCheck) { if (cycleCheck.indexOf(newFile) >= 0) { throw new Error('Dependency cycle found ' + JSON.stringify(cycleCheck)) } cycleCheck.push(newFile) try { // Add dependencies first if (dependencies[newFile]) { dependencies[newFile].forEach(function (dependency) { if (allFiles.indexOf(dependency) < 0) { throw new Error('Dependency "' + dependency + '" of file "' + newFile + '" is not part of ' + JSON.stringify(allFiles)) } addWithDependencies(allFiles, dependency, dependencies, currentFiles, cycleCheck) }) } if (currentFiles.indexOf(newFile) < 0) { currentFiles.push(newFile) } } finally { cycleCheck.pop() } return currentFiles }
javascript
{ "resource": "" }
q64513
batchForms
test
function batchForms(batch, form, merkle) { // Use commonform-stringify to produce the text to be stored. var stringified = stringify(form) var digest = merkle.digest batch.put(digest, stringified) // Recurse children. form.content .forEach(function(element, index) { if (isChild(element)) { var childForm = element.form var childMerkle = merkle.content[index] batchForms(batch, childForm, childMerkle) } }) }
javascript
{ "resource": "" }
q64514
parseJSON
test
function parseJSON(input, callback) { var error var result try { result = JSON.parse(input) } catch (e) { error = e } callback(error, result) }
javascript
{ "resource": "" }
q64515
scopeUrl
test
function scopeUrl(options, inst) { options = _.extend(_.clone(options || {}), inst) var route = [] if (options.season_id) route.push('seasons', options.season_id) if (options.flight_stage_id) route.push('flight_stages', options.flight_stage_id) else if (options.division_id) route.push('divisions', options.division_id) else if (options.pool_id) route.push('pools', options.pool_id) route.push('standings') var base = config.urls && config.urls.sports || config.url return Url.resolve(base, route.join('/')) }
javascript
{ "resource": "" }
q64516
ReconnectingWebSocket
test
function ReconnectingWebSocket(url, opts) { if (!(this instanceof ReconnectingWebSocket)) { throw new TypeError('Cannot call a constructor as a function'); } opts = opts || {}; var self = this; function getOpt(name, def) { return opts.hasOwnProperty(name)? opts[name] : def; } var timeout = getOpt('timeout', 100); var maxRetries = getOpt('maxRetries', 5); var curRetries = 0; // External event callbacks self.onmessage = noop; self.onopen = noop; self.onclose = noop; function unreliableOnOpen(e) { self.onopen(e); curRetries = 0; } function unreliableOnClose(e) { self.onclose(e); if (curRetries < maxRetries) { ++curRetries; setTimeout(connect, timeout); } } function unreliableOnMessage(e) { self.onmessage(e); } function connect() { // Constructing a WebSocket() with opts.protocols === undefined // does NOT behave the same as calling it with only one argument // (specifically, it throws security errors). if (opts.protocols) { self.ws = new WebSocket(url, opts.protocols); } else { self.ws = new WebSocket(url); } // onerror isn't necessary: it is always accompanied by onclose self.ws.onopen = unreliableOnOpen; self.ws.onclose = unreliableOnClose; self.ws.onmessage = unreliableOnMessage; } connect(); this.connect = connect; }
javascript
{ "resource": "" }
q64517
getFirstIndexOfArray
test
function getFirstIndexOfArray(arrayToSearchFor, arrayToSearchInside) { errorIfNotArray_1.errorIfNotArray(arrayToSearchFor); error_if_not_populated_array_1.errorIfNotPopulatedArray(arrayToSearchInside); return arrayToSearchInside.findIndex(function (value) { return (isArray_notArray_1.isArray(value) && arrays_match_1.arraysMatch(value, arrayToSearchFor)); }); }
javascript
{ "resource": "" }
q64518
writePath
test
function writePath(parentDir, path, data) { let files = path.split('/'); let file = files.shift(); // init file if(!parentDir[file]) parentDir[file] = { content: undefined, tree: {} }; if(files.length > 0) { writePath(parentDir[file].tree, files.join('/'), data); } else if(data) { parentDir[file].content = data.toString(); } }
javascript
{ "resource": "" }
q64519
test
function(mainFiles /*, component*/) { for (var i=0; i<mainFiles.length; i++ ){ //Use no-minified version if available var parts = mainFiles[i].split('.'), ext = parts.pop(), min = parts.pop(), fName; if (min == 'min'){ parts.push(ext); fName = parts.join('.'); if (grunt.file.exists(fName)) mainFiles[i] = fName; } } return mainFiles; }
javascript
{ "resource": "" }
q64520
test
function() { this.objects = {}; this.index = []; this._objTree = []; this._objList = []; this._properties = {}; this._propID = 0; this._decodeIndex = []; this._objFreq = []; this._objInfeq = []; this.shortNames = true; this.indent = "\t"; this.hasEmbed = false; }
javascript
{ "resource": "" }
q64521
test
function( po ) { this.objects[po.name] = po; if (po.extends) { this._objTree.push([ po.extends, po.name ]); } else if (po.depends) { this._objTree.push([ po.depends, po.name ]); } else { this._objList.push( po.name ); } }
javascript
{ "resource": "" }
q64522
test
function( index_offset, size, depth, prefix, testVar, callback ) { if (size == 0) return prefix + this.indent + "/* No items */\n"; var code = ""; genChunk = (function( s, e, d, pf ) { if (d === 0) { code += pf + "switch ("+testVar+") {\n"; for (var i=s; i<e; ++i) { code += pf + this.indent + "case "+(index_offset+i)+": return "+callback(i); } code += pf + "}\n"; } else { // No items if (e == s) { // Only 1 item } else if (e == s+1) { code += pf + "if (" + testVar + " === " + (index_offset+s) + ")\n"; code += pf + this.indent + "return "+callback(s); } else { var mid = Math.round((s+e) / 2); code += pf + "if (" + testVar + " < " + (index_offset+mid) + ") {\n"; genChunk(s, mid, d - 1, pf + this.indent); code += pf + "} else {\n"; genChunk(mid, e, d - 1, pf + this.indent); code += pf + "}\n"; } } }).bind(this); genChunk( 0, size, depth, prefix + this.indent ); return code; }
javascript
{ "resource": "" }
q64523
test
function( name ) { var id = this._properties[name]; if (id === undefined) { if (this.shortNames) { id = this._properties[name] = 'p' + (this._propID++).toString() } else { id = this._properties[name] = 'p' + name[0].toUpperCase() + name.substr(1).toLowerCase().replace(/[,\.\- \_]/g, '_') } } }
javascript
{ "resource": "" }
q64524
test
function() { // Reset index this.index = []; // Apply extends to the objects for (var i=0, l=this._objTree.length; i<l; ++i) { if (this.objects[this._objTree[i][0]] === undefined) { throw "Extending unknown object "+this._objTree[i][0]; } // Apply this.objects[this._objTree[i][1]].applyExtend( this.objects[this._objTree[i][0]] ); } // Resolve dependencies var deps = toposort( this._objTree ).reverse(), used = {}; for (var i=0, l=deps.length; i<l; ++i) { used[deps[i]] = 1; this.objects[deps[i]].id = this.index.length; this.index.push( this.objects[deps[i]] ); } // Then include objects not part of dependency tree for (var i=0, l=this._objList.length; i<l; ++i) { // Skip objects already used in the dependency resolution if (!used[this._objList[i]]) { this.index.push( this.objects[this._objList[i]] ); } } // Then pre-cache property IDs for all the propeties // and check if any of the objects has embeds for (var i=0, l=this.index.length; i<l; ++i) { var pp = this.index[i].properties; for (var j=0, jl=pp.length; j<jl; ++j) { this.propertyVar(pp[j]); } if (this.index[i].embed.length > 0) { this.hasEmbed = true; } } // Separate to frequent and infrequent objects for (var i=0, l=this.index.length; i<l; ++i) { var obj = this.index[i], isFreq = obj.frequent; // Make sure we only register 5-bit objects if (isFreq) { if (this._objFreq.length >= MAX_FREQ_ITEMS) { isFreq = false; } } // Put on frequent or infrequent table if (isFreq) { obj.id = this._objFreq.length; this._objFreq.push(obj); } else { obj.id = this._objInfeq.length+MAX_FREQ_ITEMS; this._objInfeq.push(obj); } } }
javascript
{ "resource": "" }
q64525
test
function() { var pn = Object.keys(this._properties); var code = "var "; for (var i=0, l=pn.length; i<l; ++i) { if (i!==0) code += ",\n"; code += this.indent + this._properties[pn[i]] + " = '"+ pn[i] + "'"; } code += ";\n"; return code; }
javascript
{ "resource": "" }
q64526
test
function() { var code = ""; // Collect object initializers for (var i=0, l=this.index.length; i<l; ++i) { var o = this.index[i]; code += "/**\n * Factory & Initializer of "+o.name+"\n */\n"; code += "var factory_"+o.safeName+" = {\n"; code += this.indent + "props: "+o.properties.length+",\n"; code += this.indent + "create: function() {\n"; code += this.indent + this.indent + "return " + o.generateFactory() + ";\n"; code += this.indent + "},\n"; code += this.indent + "init: function(inst, props, pagesize, offset) {\n"; code += o.generateInitializer('inst','props','pagesize','offset',this.indent+this.indent, this.indent); code += this.indent + "}\n"; code += "}\n\n"; } return code; }
javascript
{ "resource": "" }
q64527
test
function(prefix) { var code = "function( id ) {\n"; code += prefix + this.indent + "if (id < "+MAX_FREQ_ITEMS+") {\n"; code += this.generateDnCif( 0, this._objFreq.length, 3, prefix+this.indent, 'id', (function(i) { return "factory_"+this._objFreq[i].safeName+";\n" }).bind(this)); code += prefix + this.indent + "} else {\n"; code += this.generateDnCif( MAX_FREQ_ITEMS, this._objInfeq.length, 3, prefix+this.indent, 'id', (function(i) { return "factory_"+this._objInfeq[i].safeName+";\n" }).bind(this)); code += prefix + this.indent + "}\n"; code += prefix + "}\n"; return code; }
javascript
{ "resource": "" }
q64528
test
function( prefix ) { var code = "function( inst ) {\n"; for (var i=0, l=this.index.length; i<l; ++i) { var o = this.index[i]; if (i === 0) code += prefix + this.indent + "if"; else code += prefix + this.indent + "} else if"; code += " (inst instanceof "+o.name+") {\n"; code += prefix + this.indent + this.indent + "return [" + o.id + ", getter_"+o.safeName+"];\n"; } code += prefix + this.indent + "}\n"; code += prefix + "}\n" return code; }
javascript
{ "resource": "" }
q64529
test
function() { var code = ""; // Collect object initializers for (var i=0, l=this.index.length; i<l; ++i) { var o = this.index[i]; code += "/**\n * Property getter "+o.name+"\n */\n"; code += "function getter_"+o.safeName+"(inst) {\n"; code += this.indent + "return "+o.generatePropertyGetter('inst',this.indent+this.indent) + ";\n"; code += "}\n\n"; } code += "\n" return code; }
javascript
{ "resource": "" }
q64530
Client
test
function Client(options) { options = options || {}; this.isClient = true; this.subdomain = options.subdomain; this.endpoint = options.endpoint; if (!this.subdomain && !this.endpoint) throw new Error('No subdomain was specified.'); // Determine if we construct a URL from the subdomain or use a custom one if(this.endpoint && typeof this.endpoint !== 'undefined') { this.baseUrl = this.endpoint; } else { this.baseUrl = 'https://' + this.subdomain + '.desk.com'; } if (options.username && options.password) { this.auth = { username: options.username, password: options.password, sendImmediately: true }; } else if (options.consumerKey && options.consumerSecret && options.token && options.tokenSecret) { this.auth = { consumer_key: options.consumerKey, consumer_secret: options.consumerSecret, token: options.token, token_secret: options.tokenSecret }; } else { throw new Error('No authentication specified, use either Basic Authentication or OAuth.'); } this.retry = options.retry || false; this.maxRetry = options.maxRetry || 3; this.timeout = options.timeout; this.logger = options.logger || null; this.queue = async.queue(this.request.bind(this), 60); linkMixin.call(this, JSON.parse(fs.readFileSync(__dirname + '/resources.json', 'utf-8'))); }
javascript
{ "resource": "" }
q64531
Imagesloader
test
function Imagesloader(opts){ /** * @define {object} Collection of public methods. */ var self = {}; /** * @define {object} Options for the constructor */ var opts = opts || {}; /** * @define {object} A image loader object */ var imageloader = Imageloader(); /** * @define {array} A holder for when an image is loaded */ var imgs = []; /** * @define {array} A holder for the image src that should be loaded */ var srcs = []; /** * @define {object} A promise container for promises */ var def; /** * Load a collection of images * @example imageloader.load(['img1.jpg', 'img2.jpg', 'img3.jpg']).success(function(){ // Do something }); * @param {array} images A collection of img object or img.src (paths) * @config {object} def Create a promise object * @return {object} Return the promise object */ function load(images){ def = Deferred(); /** * Check if the images is img objects or image src * return string of src */ srcs = convertImagesToSrc(images); /** * Loop through src's and load image */ for (var i = 0; i < srcs.length; i++) { imageloader.load(srcs[i]) .success(function(img){ /** call imageloaded a pass the img that is loaded */ imageLoaded(img); }) .error(function(msg){ def.reject(msg + ' couldn\'t be loaded'); }); }; return def.promise; } /** * Image loaded checker * @param {img} img The loaded image */ function imageLoaded(img){ /** Notify the promise */ def.notify("notify"); /** Add the image to the imgs array */ imgs.push(img); /** If the imgs array size is the same as the src's */ if(imgs.length == srcs.length){ /** First sort images, to have the same order as src's */ sortImages(); /** Resolve the promise with the images */ def.resolve(imgs); } } /** * Convert img to src * @param {array} imgs A collection og img/img paths * @config {array} src A temporally array for storing img path/src * @return {array} Return an array of img src's */ function convertImagesToSrc(imgs){ var src = []; for (var i = 0; i < imgs.length; i++) { /** If the img is an object (img) get the src */ if(typeof imgs[i] == 'object'){ src.push(imgs[i].src); } }; /** If the src array is null return the original imgs array */ return src.length ? src : imgs; } /** * Sort images after the originally order * @config {array} arr A temporally array for sorting images */ function sortImages(){ var arr = []; /** * Create a double loop * And match the order of the srcs array */ for (var i = 0; i < srcs.length; i++) { for (var j = 0; j < imgs.length; j++) { var str = imgs[j].src.toString(); var reg = new RegExp(srcs[i]) /** If srcs matches the imgs add it the the new array */ if(str.match(reg)) arr.push(imgs[j]); }; }; /** Override imgs array with the new sorted arr */ imgs = arr; } /** * Public methods * @public {function} */ self.load = load; /** * @return {object} Public methods */ return self; }
javascript
{ "resource": "" }
q64532
load
test
function load(images){ def = Deferred(); /** * Check if the images is img objects or image src * return string of src */ srcs = convertImagesToSrc(images); /** * Loop through src's and load image */ for (var i = 0; i < srcs.length; i++) { imageloader.load(srcs[i]) .success(function(img){ /** call imageloaded a pass the img that is loaded */ imageLoaded(img); }) .error(function(msg){ def.reject(msg + ' couldn\'t be loaded'); }); }; return def.promise; }
javascript
{ "resource": "" }
q64533
imageLoaded
test
function imageLoaded(img){ /** Notify the promise */ def.notify("notify"); /** Add the image to the imgs array */ imgs.push(img); /** If the imgs array size is the same as the src's */ if(imgs.length == srcs.length){ /** First sort images, to have the same order as src's */ sortImages(); /** Resolve the promise with the images */ def.resolve(imgs); } }
javascript
{ "resource": "" }
q64534
convertImagesToSrc
test
function convertImagesToSrc(imgs){ var src = []; for (var i = 0; i < imgs.length; i++) { /** If the img is an object (img) get the src */ if(typeof imgs[i] == 'object'){ src.push(imgs[i].src); } }; /** If the src array is null return the original imgs array */ return src.length ? src : imgs; }
javascript
{ "resource": "" }
q64535
sortImages
test
function sortImages(){ var arr = []; /** * Create a double loop * And match the order of the srcs array */ for (var i = 0; i < srcs.length; i++) { for (var j = 0; j < imgs.length; j++) { var str = imgs[j].src.toString(); var reg = new RegExp(srcs[i]) /** If srcs matches the imgs add it the the new array */ if(str.match(reg)) arr.push(imgs[j]); }; }; /** Override imgs array with the new sorted arr */ imgs = arr; }
javascript
{ "resource": "" }
q64536
builder
test
function builder(envList, envName) { if (envList == null) { envList = DEFAULT_ENV_LIST; } if (envName == null) { envName = DEFAULT_ENV_NAME; } if (!Array.isArray(envList)) { throw new Error('envList must be an array'); } if (typeof envName !== 'string') { throw new Error('envName must be a string'); } // . const index = envList.indexOf(env.get(envName, DEFAULT_ENV).required().asString()); /** * . */ // return function defaults(obj) { // return 'object' !== typeof obj ? obj : obj[index]; // }; let body; if (index < 0) { body = 'return function defaults() {}'; } else { body = `return function defaults(obj) { return 'object' !== typeof obj ? obj : obj[${index}] }`; } return new Function(body)(); }
javascript
{ "resource": "" }
q64537
validateId
test
function validateId(id) { if (id && id.trim() && /^[a-zA-Z0-9_]+$/.test(id)) { if (agency.isIdInUse(id)) { err.name = 'DuplicateIdError'; err.message = 'duplication (use a different id)'; return err; } else { return id; } } else { err.name = 'ValidateIdError'; err.message = 'failed id validation (please use alphanumeric characters and underscore)'; return err; } }
javascript
{ "resource": "" }
q64538
arrayGetUniques
test
function arrayGetUniques(arr) { var a = []; for (var i=0, l=arr.length; i<l; i++) { if (a.indexOf(arr[i]) === -1 && arr[i] !== '') a.push(arr[i]); } return a; }
javascript
{ "resource": "" }
q64539
setFunction
test
function setFunction(f) { if (canExecute) { if (Object.getPrototypeOf(f) === Function.prototype) { func = f; jn.logCreationEvent(id, 'INFO', 'function definition completed', (new Date()).toJSON()); } else { setCanExecute(false); jn.logCreationEvent(id, 'ERROR', 'function definition failed', (new Date()).toJSON()); } } }
javascript
{ "resource": "" }
q64540
setCallback
test
function setCallback(cb) { if (canExecute) { if (Object.getPrototypeOf(cb) === Function.prototype) { callback = cb; jn.logCreationEvent(id, 'INFO', 'callback definition completed', (new Date()).toJSON()); } else { setCanExecute(false); jn.logCreationEvent(id, 'ERROR', 'callback definition failed', (new Date()).toJSON()); } } }
javascript
{ "resource": "" }
q64541
Case
test
function Case(parent, definition) { var key; for (key in updateMixin) { this[key] = updateMixin[key]; } Case.super_.apply(this, arguments); }
javascript
{ "resource": "" }
q64542
Resource
test
function Resource(parent, definition) { this.parent = parent; this.definition = definition; // add mixins this._link = linkMixin; this._setup(); }
javascript
{ "resource": "" }
q64543
containerSlug
test
function containerSlug(language_slug, project_slug, resource_slug) { if(!language_slug || !project_slug || !resource_slug) throw new Error('Invalid resource container slug parameters'); return language_slug + '_' + project_slug + '_' + resource_slug; }
javascript
{ "resource": "" }
q64544
test
function () { let dir = path.join(container_directory, content_dir); return fs.readdirSync(dir).filter(function(file) { try { return fs.statSync(file).isDirectory(); } catch (err) { console.log(err); return false; } }); }
javascript
{ "resource": "" }
q64545
test
function(chapterSlug, chunkSlug) { let file = path.join(container_directory, content_dir, chapterSlug, chunkSlug + '.' + this.chunkExt); return fs.readFileSync(file, {encoding: 'utf8'}); }
javascript
{ "resource": "" }
q64546
makeContainer
test
function makeContainer(container_directory, opts) { return new Promise(function(resolve, reject) { if(fileUtils.fileExists(container_directory)) { reject(new Error('Container already exists')); return; } let package_json = {}; // TODO: build the container reject(new Error('Not implemented yet.')); // resolve(new Container(container_directory, package_json)); }); }
javascript
{ "resource": "" }
q64547
openContainer
test
function openContainer(container_archive, container_directory, opts) { opts = opts || { compression_method : 'tar' }; if(fileUtils.fileExists(container_directory)) { return loadContainer(container_directory); } if(!fileUtils.fileExists(container_archive)) return Promise.reject(new Error('Missing resource container')); if(opts.compression_method === 'zip') { return compressionUtils.unzip(container_archive, container_directory) .then(function(dir) { return loadContainer(dir); }); } else { return compressionUtils.untar(container_archive, container_directory) .then(function(dir) { return loadContainer(dir); }); } }
javascript
{ "resource": "" }
q64548
inspectContainer
test
function inspectContainer(container_path, opts) { return new Promise(function(resolve, reject) { if(path.extname(container_path) !== '.' + spec.file_ext) { reject(new Error('Invalid resource container file extension')); return; } try { resolve(fs.statSync(container_path).isFile()); } catch(err) { reject(new Error('The resource container does not exist at', container_path)); } }) .then(function(isFile) { if(isFile) { // TODO: For now we are just opening the container then closing it. // Eventually it would be nice if we can inspect the archive without extracting everything. let containerDir = path.join(path.dirname(container_path), path.basename(container_path, '.' + spec.file_ext)); return openContainer(container_path, containerDir, opts) .then(function(container) { return closeContainer(containerDir, opts) .then(function() { return Promise.resolve(container.info); }); }); } else { loadContainer(container_path) .then(function(container) { return Promise.resolve(container.info); }); } }); }
javascript
{ "resource": "" }
q64549
UserPreference
test
function UserPreference(parent, definition) { var key; for (key in updateMixin) { this[key] = updateMixin[key]; } UserPreference.super_.apply(this, arguments); }
javascript
{ "resource": "" }
q64550
getUpdater
test
function getUpdater(errorFn) { errorFn = errorFn || new Function(); return updater; /** * The updater function for the esprima transform * @param {string} file The filename for the Browserify transform * @param {object} ast The esprima syntax tree * @returns {object} The transformed esprima syntax tree */ function updater(file, ast) { if (ast.comments) { ast.comments .filter(testDocTag) .map(getAnnotatedNode) .concat(inferAngular(ast)) // find the items that are not explicitly annotated .filter(testFirstOccurrence) // ensure unique values .forEach(processNode); } else { errorFn('Esprima AST is required to have top-level comments array'); } return ast; } /** * Get the node that is annotated by the comment or throw if not present. * @throws {Error} Where comment does not annotate a node * @param {object} comment The comment node */ function getAnnotatedNode(comment) { // find the first function declaration or expression following the annotation var result; if (comment.annotates) { var candidateTrees; // consider the context the block is in (i.e. what is its parent) var parent = comment.annotates.parent; // consider nodes from the annotated node forward // include the first non-generated node and all generated nodes preceding it if (testNode.isBlockOrProgram(parent)) { var body = parent.body; var index = body.indexOf(comment.annotates); var candidates = body.slice(index); var length = candidates.map(testNode.isGeneratedCode).indexOf(false) + 1; candidateTrees = candidates.slice(0, length || candidates.length); } // otherwise we can only consider the given node else { candidateTrees = [comment.annotates]; } // try the nodes while (!result && candidateTrees.length) { result = esprimaTools .orderNodes(candidateTrees.shift()) .filter(testNode.isFunctionNotIFFE) .shift(); } } // throw where not valid if (result) { return result; } else { errorFn('Doc-tag @ngInject does not annotate anything'); } } }
javascript
{ "resource": "" }
q64551
updater
test
function updater(file, ast) { if (ast.comments) { ast.comments .filter(testDocTag) .map(getAnnotatedNode) .concat(inferAngular(ast)) // find the items that are not explicitly annotated .filter(testFirstOccurrence) // ensure unique values .forEach(processNode); } else { errorFn('Esprima AST is required to have top-level comments array'); } return ast; }
javascript
{ "resource": "" }
q64552
getAnnotatedNode
test
function getAnnotatedNode(comment) { // find the first function declaration or expression following the annotation var result; if (comment.annotates) { var candidateTrees; // consider the context the block is in (i.e. what is its parent) var parent = comment.annotates.parent; // consider nodes from the annotated node forward // include the first non-generated node and all generated nodes preceding it if (testNode.isBlockOrProgram(parent)) { var body = parent.body; var index = body.indexOf(comment.annotates); var candidates = body.slice(index); var length = candidates.map(testNode.isGeneratedCode).indexOf(false) + 1; candidateTrees = candidates.slice(0, length || candidates.length); } // otherwise we can only consider the given node else { candidateTrees = [comment.annotates]; } // try the nodes while (!result && candidateTrees.length) { result = esprimaTools .orderNodes(candidateTrees.shift()) .filter(testNode.isFunctionNotIFFE) .shift(); } } // throw where not valid if (result) { return result; } else { errorFn('Doc-tag @ngInject does not annotate anything'); } }
javascript
{ "resource": "" }
q64553
locationStr
test
function locationStr( runtime , line ) { var loc ; loc = 'line: ' + ( line !== undefined ? line : runtime.lineNumber ) ; if ( runtime.file ) { loc += ' -- file: ' + runtime.file ; } return loc ; }
javascript
{ "resource": "" }
q64554
Macro
test
function Macro(parent, definition) { var key; for (key in updateMixin) { this[key] = updateMixin[key]; } this.destroy = destroyMixin; Macro.super_.apply(this, arguments); }
javascript
{ "resource": "" }
q64555
quickSort
test
function quickSort(a, l, h, k, c) { const s = []; let t = 0; s[t++] = l; s[t++] = h; while (t > 0) { h = s[--t]; l = s[--t]; if (h - l > k) { const p = partition(a, l, h, c); if (p > l) { s[t++] = l; s[t++] = p; } if (p + 1 < h) { s[t++] = p + 1; s[t++] = h; } } } }
javascript
{ "resource": "" }
q64556
pivot
test
function pivot(a, l, h, c) { const p = (l + ((h - l) / 2)) | 0; if (c(a[h], a[l]) < 0) { [a[l], a[h]] = [a[h], a[l]]; } if (c(a[p], a[l]) < 0) { [a[l], a[p]] = [a[p], a[l]]; } if (c(a[h], a[p]) < 0) { [a[h], a[p]] = [a[p], a[h]]; } return p; }
javascript
{ "resource": "" }
q64557
partition
test
function partition(a, l, h, c) { const p = a[pivot(a, l, h, c)]; let i = l - 1; let j = h + 1; for (;;) { do { i++; } while (c(a[i], p) < 0); do { j--; } while (c(a[j], p) > 0); if (i < j) { [a[i], a[j]] = [a[j], a[i]]; } else { return j; } } }
javascript
{ "resource": "" }
q64558
insertionSort
test
function insertionSort(a, l, h, c) { for (let i = l + 1; i <= h; i++) { const x = a[i]; let j = i - 1; while (j >= 0 && c(a[j], x) > 0) { a[j + 1] = a[j]; j--; } a[j + 1] = x; } }
javascript
{ "resource": "" }
q64559
search
test
function search(parent, baseUrl, callback) { var resource = new (getResource('page'))(parent, { _links: { self: { href: baseUrl, 'class': 'page' } } }); if (typeof callback == 'function') return resource.exec(callback); return resource; }
javascript
{ "resource": "" }
q64560
createPipeStream
test
function createPipeStream(cmd/*, args, opts*/){ var proc; var command; if(Array.isArray(cmd)){ // We have an array so create a pipe from all elements var firstCmd = cmd.shift(); var open = Array.isArray(firstCmd) ? createPipeStream.apply({}, firstCmd) : createPipeStream(firstCmd); cmd.forEach(function(p){ open = open.pipe(p); }); return open; } else if(cmd instanceof EventEmitter){ // Take the eventemitter as base proc = cmd; command = 'pre-defined'; } else if(typeof cmd === 'object'){ throw new TypeError('Invalid input, expected object type -> EventEmitter'); } else { // We have input for Spawn command, normalize the input and create spawn var input = utils.normalizeInput.apply(this, arguments); command = utils.getCommand(input); proc = spawn.apply({}, input); } // Create inner pointer for command proc._command = command; // Check if process is still alive if(proc.exitCode){ throw new Error('Process already dead'); } return PipeStream(proc); }
javascript
{ "resource": "" }
q64561
wrapMethods
test
function wrapMethods(self){ var methods = ['on']; var childObjects = ['stdin','stdout','stderr']; // Wrap on method methods.forEach(function(m){ var old = self[m]; self[m] = function(){ old.apply(self, arguments); return self; }; }); // If its a spawn object then wrap child EventEmitters if(utils.isSpawn(self)){ childObjects.forEach(function(child){ methods.forEach(function(m){ var old = self[child][m]; self[child][m] = function(){ old.apply(self[child], arguments); return self; }; }); }); } }
javascript
{ "resource": "" }
q64562
connectEvents
test
function connectEvents(self){ if(self.stdout){ self.stdout.on('data', function(d){ self.emit('data', d); }); self.stderr.on('data', function(d){ self.emit('error', d); }); } }
javascript
{ "resource": "" }
q64563
addEventHandlers
test
function addEventHandlers(self){ self.on('error',function(d){ var fn = self._error; self._cleanUp(); if(fn){ fn('pipeline[' + self._nr + ']:"' + self._command + '" failed with: ' + d.toString()); } }); }
javascript
{ "resource": "" }
q64564
_resolve
test
function _resolve(routes, path, req, res) { return Q.fcall(function() { path = path || []; var obj = routes; // Resolve promises first if(IS.obj(obj) && IS.fun(obj.then)) { var p = obj.then(function(ret) { return _resolve(ret, path, req, res); }); return p; } // Resolve functions first if(IS.fun(obj)) { var p2 = Q.when(obj(req, res)).then(function(ret) { return _resolve(ret, path, req, res); }); return p2; } // If the resource is undefined, return flags.notFound (resulting to a HTTP error 404). if(obj === undefined) { return flags.notFound; } // If path is at the end, then return the current resource. if(path.length === 0) { return obj; } // Handle arrays if(IS.array(obj)) { var k = path[0], n = parseInt(path.shift(), 10); if(k === "length") { return _resolve(obj.length, path.shift(), req, res); } if(k !== ""+n) { return Q.fcall(function() { throw new errors.HTTPError({'code':400, 'desc':'Bad Request'}); }); } return _resolve(obj[n], path.shift(), req, res); } // Handle objects if(IS.obj(obj)) { var k2 = path[0]; if(obj[k2] === undefined) { return flags.notFound; } if(!obj.hasOwnProperty(k2)) { return Q.fcall(function() { throw new errors.HTTPError({'code':403, 'desc':'Forbidden'}); }); } return _resolve(obj[path.shift()], path, req, res); } // Returns notFound because we still have keys in the path but nowhere to go. return flags.notFound; }); }
javascript
{ "resource": "" }
q64565
_buildFunction
test
function _buildFunction(resource) { return function(callback) { if (typeof callback == 'function') { if (resource !== null) return resource.exec.call(resource, callback); else return callback(null, null); } return resource; } }
javascript
{ "resource": "" }
q64566
getApiKey
test
function getApiKey () { if (isLocal() && pkg.apiKey) { log.trace('using apiKey in fhconfig'); return pkg.apiKey; } else { log.trace('using api key in FH_APP_API_KEY env var'); return env('FH_APP_API_KEY').asString(); } }
javascript
{ "resource": "" }
q64567
getResource
test
function getResource(name) { if (name in resources) return resources[name]; try { return resources[name] = require('../resource/' + name); } catch(err) { return resources[name] = require('../resource'); } }
javascript
{ "resource": "" }
q64568
signMsg
test
function signMsg(msg, key, alg) { var signer = crypto.createSign(alg); signer.update(msg); return signer.sign(key); }
javascript
{ "resource": "" }
q64569
hashMsg
test
function hashMsg(msg, alg) { var hash = crypto.createHash(alg); hash.update(msg); return hash.digest(); }
javascript
{ "resource": "" }
q64570
addSignatureHeaders
test
function addSignatureHeaders(body, headers, keyId, key) { if (!headers) { headers = {}; } if (!headers.date) { headers.date = (new Date()).toUTCString(); } if (!headers.digest) { headers.digest = 'SHA256=' + hashMsg(JSON.stringify(body), 'sha256') .toString('base64'); } var combine = function(names, headers) { var parts = []; names.forEach(function(e) { parts.push(e + ': ' + headers[e]); }); return parts.join('\n'); }; headers.authorization = 'Signature ' + 'keyId="' + keyId + '", ' + 'headers="date digest", ' + 'algorithm="rsa-sha256", ' + 'signature="' + signMsg(combine([ 'date', 'digest' ], headers), key, 'RSA-SHA256') .toString('base64') + '"'; return headers; }
javascript
{ "resource": "" }
q64571
waitVariableToBe
test
async function waitVariableToBe (variableExpression, value, timeout) { return await this.waitUntil(async () => { const result = await this.execute(`return ${variableExpression} === ${JSON.stringify(value)}`) return result.value }, timeout, `Timeout to wait expression \`${variableExpression}\` to be \`${JSON.stringify(value)}\``) }
javascript
{ "resource": "" }
q64572
waitAttributeToBe
test
async function waitAttributeToBe (selector, key, value, timeout) { return await this.waitUntil(async () => { const got = await this.element(selector).getAttribute(key) return [].concat(value).some((value) => got === value || String(got) === String(value)) }, timeout, `Timeout to wait attribute "${key}" on \`${selector}\` to be \`${JSON.stringify(value)}\``) }
javascript
{ "resource": "" }
q64573
test
function(view) { this.unmount(); this.currentView = view; var renderReturnsView = this.currentView.render(); if (renderReturnsView) { $(SpecialK.mainContainer).empty().append(renderReturnsView.el).fadeIn('slow'); } }
javascript
{ "resource": "" }
q64574
test
function() { if (!this.currentView) return false; $(SpecialK.container).hide(); this.currentView.unbind(); this.currentView.remove(); this.currentView = null; return true; }
javascript
{ "resource": "" }
q64575
mergeAll
test
function mergeAll(safe, obj) { let args = toArray(arguments).slice(2); for (let i = 0; i < args.length; i++) { obj = merge(obj, args[i], safe); } return obj; }
javascript
{ "resource": "" }
q64576
quality
test
function quality(str) { var parts = str.split(/ *; */), val = parts[0]; var q = parts[1] ? parseFloat(parts[1].split(/ *= */)[1]) : 1; return { value: val, quality: q }; }
javascript
{ "resource": "" }
q64577
getBrightness
test
function getBrightness( hex ) { var r = parseInt( hex.substr(2+0*2, 2), 16), g = parseInt( hex.substr(2+1*2, 2), 16), b = parseInt( hex.substr(2+2*2, 2), 16); function lin2log(n) { return n <= 0.0031308 ? n * 12.92 : 1.055 * Math.pow(n,1/2.4) - 0.055; } function log2lin(n) { return n <= 0.04045 ? n / 12.92 : Math.pow(((n + 0.055)/1.055),2.4); } r = log2lin( r/255 ); g = log2lin( g/255 ); b = log2lin( b/255 ); return lin2log(0.2126 * r + 0.7152 * g + 0.0722 * b) * 100; }
javascript
{ "resource": "" }
q64578
command_exists
test
function command_exists (paths, name) { if (is.string(paths)) { paths = paths.split(':'); } debug.assert(paths).is('array'); return paths.some(dir => fs.existsSync(PATH.join(dir, name))); }
javascript
{ "resource": "" }
q64579
qExec
test
function qExec(command, options) { var d = Q.defer(); exec(command, options, function(err, stdout, stderr) { if(err) { err.stdout = stdout; err.stderr = stderr; return d.reject(err); } return d.resolve(stdout, stderr); }); return d.promise; }
javascript
{ "resource": "" }
q64580
initDynamic
test
function initDynamic() { // bootstrap popover $('a[data-toggle=popover]') .popover() .click(function(e) { e.preventDefault(); }) ; var version = $('#version strong').html(); $('#sidenav li').removeClass('is-new'); if (apiProject.template.withCompare) { $('#sidenav li[data-version=\'' + version + '\']').each(function(){ var group = $(this).data('group'); var name = $(this).data('name'); var length = $('#sidenav li[data-group=\'' + group + '\'][data-name=\'' + name + '\']').length; var index = $('#sidenav li[data-group=\'' + group + '\'][data-name=\'' + name + '\']').index($(this)); if (length === 1 || index === (length - 1)) $(this).addClass('is-new'); }); } // tabs $('.nav-tabs-examples a').click(function (e) { e.preventDefault(); $(this).tab('show'); }); $('.nav-tabs-examples').find('a:first').tab('show'); // sample request switch $('.sample-request-switch').click(function (e) { var name = '.' + $(this).attr('name') + '-fields'; $(name).addClass('hide'); $(this).parent().next(name).removeClass('hide'); }); // init modules sampleRequest.initDynamic(); }
javascript
{ "resource": "" }
q64581
changeAllVersionCompareTo
test
function changeAllVersionCompareTo(e) { e.preventDefault(); $('article:visible .versions').each(function(){ var $root = $(this).parents('article'); var currentVersion = $root.data('version'); var $foundElement = null; $(this).find('li.version a').each(function() { var selectVersion = $(this).html(); if (selectVersion < currentVersion && ! $foundElement) $foundElement = $(this); }); if($foundElement) $foundElement.trigger('click'); }); initDynamic(); }
javascript
{ "resource": "" }
q64582
addArticleSettings
test
function addArticleSettings(fields, entry) { // add unique id // TODO: replace all group-name-version in template with id. fields.id = fields.article.group + '-' + fields.article.name + '-' + fields.article.version; fields.id = fields.id.replace(/\./g, '_'); if (entry.header && entry.header.fields) fields._hasTypeInHeaderFields = _hasTypeInFields(entry.header.fields); if (entry.parameter && entry.parameter.fields) fields._hasTypeInParameterFields = _hasTypeInFields(entry.parameter.fields); if (entry.error && entry.error.fields) fields._hasTypeInErrorFields = _hasTypeInFields(entry.error.fields); if (entry.success && entry.success.fields) fields._hasTypeInSuccessFields = _hasTypeInFields(entry.success.fields); if (entry.info && entry.info.fields) fields._hasTypeInInfoFields = _hasTypeInFields(entry.info.fields); // add template settings fields.template = apiProject.template; }
javascript
{ "resource": "" }
q64583
renderArticle
test
function renderArticle(group, name, version) { var entry = {}; $.each(apiByGroupAndName[group][name], function(index, currentEntry) { if (currentEntry.version === version) entry = currentEntry; }); var fields = { article: entry, versions: articleVersions[group][name] }; addArticleSettings(fields, entry); return templateArticle(fields); }
javascript
{ "resource": "" }
q64584
resetArticle
test
function resetArticle(group, name, version) { var $root = $('article[data-group=\'' + group + '\'][data-name=\'' + name + '\']:visible'); var content = renderArticle(group, name, version); $root.after(content); var $content = $root.next(); // Event on.click muss neu zugewiesen werden (sollte eigentlich mit on automatisch funktionieren... sollte) $content.find('.versions li.version a').on('click', changeVersionCompareTo); $('#sidenav li[data-group=\'' + group + '\'][data-name=\'' + name + '\'][data-version=\'' + version + '\']').removeClass('has-modifications'); $root.remove(); return; }
javascript
{ "resource": "" }
q64585
loadGoogleFontCss
test
function loadGoogleFontCss() { var host = document.location.hostname.toLowerCase(); var protocol = document.location.protocol.toLowerCase(); var googleCss = '//fonts.googleapis.com/css?family=Source+Code+Pro|Source+Sans+Pro:400,600,700'; if (host == 'localhost' || !host.length || protocol === 'file:') googleCss = 'http:' + googleCss; $('<link/>', { rel: 'stylesheet', type: 'text/css', href: googleCss }).appendTo('head'); }
javascript
{ "resource": "" }
q64586
sortByOrder
test
function sortByOrder(elements, order, splitBy) { var results = []; order.forEach (function(name) { if (splitBy) elements.forEach (function(element) { var parts = element.split(splitBy); var key = parts[1]; // reference keep for sorting if (key == name) results.push(element); }); else elements.forEach (function(key) { if (key == name) results.push(name); }); }); // Append all other entries that ar not defined in order elements.forEach(function(element) { if (results.indexOf(element) === -1) results.push(element); }); return results; }
javascript
{ "resource": "" }
q64587
browserifyNgInject
test
function browserifyNgInject(opt) { var options = defaults(opt, { filter: defaultFilter // remove files that cannot be parsed by esprima }), updater = getUpdater(throwError); return esprimaTools.createTransform(updater, options); }
javascript
{ "resource": "" }
q64588
test
function (scope) { if (scope.model) { var modelInData = false; for(var i = 0; i < scope.data.length; i++) { if (angular.equals(scope.data[i], scope.model)) { scope.model = scope.data[i]; modelInData = true; break; } } if (!modelInData) { scope.model = null; } } if (!scope.model && !scope.chooseText && scope.data.length) { scope.model = scope.data[0]; } }
javascript
{ "resource": "" }
q64589
scopeUrl
test
function scopeUrl(options, inst) { options = _.extend(options || {}, inst) if (!options.url && !options.user_id && !options.group_id && !(options.query || options.query.owner_type && options.query.owner_id)) { return callback(new Error('user_id or group_id or (owner_type and owner_id) are required')) } if (options.user_id) { return ngin.User.urlRoot() + '/' + options.user_id + '/personas' } if (options.group_id) { return ngin.Group.urlRoot() + '/' + options.group_id + '/personas' } if (options.url || options.query.owner_type && options.query.owner_id) { return Persona.urlRoot() } }
javascript
{ "resource": "" }
q64590
processNode
test
function processNode(node) { // check if the function is part of a variable assignment var isVarAssignment = (node.parent.type === 'VariableDeclarator'); // the parameters of the function, converted to literal strings var params = node.params .map(paramToLiteral); // [ 'arg', ..., function(arg) {} ] // place inline if ((node.type === 'FunctionExpression') && !isVarAssignment) { esprimaTools.nodeSplicer(node)({ parent : node.parent, type : 'ArrayExpression', elements: params.concat(node) }); } // fn.$inject = [ 'arg', ... ] // hoist before any intervening return statement else { var appendTo = isVarAssignment ? node.parent.parent : node; esprimaTools.nodeSplicer(appendTo, offset)({ type : 'ExpressionStatement', expression: { type : 'AssignmentExpression', operator: '=', left : { type : 'MemberExpression', computed: false, object : { type: 'Identifier', name: node.id.name }, property: { type: 'Identifier', name: '$inject' } }, right : { type : 'ArrayExpression', elements: params } } }); } }
javascript
{ "resource": "" }
q64591
createApplication
test
function createApplication() { function app(req, res) { app.handle(req, res); } utils.merge(app, application); utils.merge(app, EventEmitter.prototype); app.request = { __proto__ : req }; app.response = { __proto__ : res }; app.init(); return app; }
javascript
{ "resource": "" }
q64592
test
function(){ var chai = require('chai'); chai.should(); global.assert = chai.assert; global.expect = chai.expect; }
javascript
{ "resource": "" }
q64593
Company
test
function Company(parent, definition) { var key; for (key in updateMixin) { this[key] = updateMixin[key]; } Company.super_.apply(this, arguments); }
javascript
{ "resource": "" }
q64594
inferAngular
test
function inferAngular(ast) { return esprimaTools.breadthFirst(ast) .map(getAnnotationCandidates) .filter(Boolean) .map(followReference) .filter(Boolean); }
javascript
{ "resource": "" }
q64595
getAnnotationCandidates
test
function getAnnotationCandidates(node) { var callExpression = testNode.isModuleExpression(node) && node.parent; if (callExpression) { return callExpression['arguments'] .filter(testNode.anyOf(testNode.isFunction, testNode.isIdentifier)) .pop(); } else { return null; } }
javascript
{ "resource": "" }
q64596
followReference
test
function followReference(node) { var result; // immediate function if (testNode.isFunction(node)) { return node; } // follow identifier else { var name = node.name; // find the next highest scope and search for declaration while (node.parent && !result) { node = node.parent; var isBlock = testNode.isBlockOrProgram(node); if (isBlock) { // look at the nodes breadth first and take the first result esprimaTools.breadthFirst(node) .some(function eachNode(subNode) { switch (subNode.type) { case 'FunctionDeclaration': if (subNode.id.name === name) { result = subNode; } break; case 'VariableDeclarator': if (subNode.id.name === name) { result = subNode.init; } break; case 'AssignmentExpression': if ((subNode.left.type === 'Identifier') && (subNode.left.name === name)) { result = subNode.right; } break; } return !!result; }); } } // recurse the result until we find a function return result ? followReference(result) : null; } }
javascript
{ "resource": "" }
q64597
test
function(callback) { // perform all the cleanup and other operations needed prior to shutdown, // but do not actually shutdown. Call the callback function only when // these operations are actually complete. try { TacitServer.app_server.close(); console.log(TacitServer.configs.server_prefix + " - Shutdown app successful."); } catch(ex) { console.log(TacitServer.configs.server_prefix + " - Shutdown app failed."); console.log(ex); } try { TacitServer.api_server.close(); console.log(TacitServer.configs.server_prefix + " - Shutdown api successful."); } catch(ex) { console.log(TacitServer.configs.server_prefix + " - Shutdown api failed."); console.log(ex); } console.log(TacitServer.configs.server_prefix + " - All preparations for shutdown completed."); callback(); }
javascript
{ "resource": "" }
q64598
transformBody
test
function transformBody(req, input) { req.log.debug('attempting transformation', input); const body = input.data; const { attributes } = body; const { password, referral } = attributes; const { autoGeneratePassword } = config; if (autoGeneratePassword === true && password) { throw new Errors.ValidationError('password is auto-generated, do not pass it', 400); } if (autoGeneratePassword === false && !password) { throw new Errors.ValidationError('password must be provided', 400); } const { country } = body; if (country && !countryData.info(country, 'ISO3')) { const err = `country name must be specified as ISO3. Please refer to https://github.com/therebelrobot/countryjs#info for a complete list of codes`; throw new Errors.ValidationError(err, 400, 'data.country'); } const message = { username: body.id, metadata: ld.pick(attributes, WHITE_LIST), activate: config.usersRequireActivate !== true || !password, audience: getAudience(), ipaddress: proxyaddr(req, config.trustProxy), }; if (password) { message.password = password; } if (attributes.alias) { message.alias = attributes.alias.toLowerCase(); } if (referral) { message.referral = referral; } // BC, remap additionalInformation to longDescription if it is not provided if (attributes.additionalInformation && !message.metadata.longDescription) { message.metadata.longDescription = attributes.additionalInformation; } return message; }
javascript
{ "resource": "" }
q64599
test
function( val, num, max ) { if ( max ) { // make sure the text value is greater than the max numerical value (max) var indx, len = val ? val.length : 0, n = max + num; for ( indx = 0; indx < len; indx++ ) { n += val.charCodeAt( indx ); } return num * n; } return 0; }
javascript
{ "resource": "" }