_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q47100
repeatString
train
function repeatString(string, nb) { var s = string, l, i; if (nb <= 0) return ''; for (i = 1, l = nb | 0; i < l; i++) s += string; return s; }
javascript
{ "resource": "" }
q47101
processYAMLVariable
train
function processYAMLVariable(v, lvl, indent) { // Scalars if (typeof v === 'string') return yml.string(v); else if (typeof v === 'number') return yml.number(v); else if (typeof v === 'boolean') return yml.boolean(v); else if (typeof v === 'undefined' || v === null || isRealNaN(v)) return yml.nullValue(v); // Nonscalars else if (isPlainObject(v)) return yml.object(v, lvl, indent); else if (isArray(v)) return yml.array(v, lvl); else if (typeof v === 'function') return yml.fn(v); // Error else throw TypeError('artoo.writers.processYAMLVariable: wrong type.'); }
javascript
{ "resource": "" }
q47102
extend
train
function extend() { var i, k, res = {}, l = arguments.length; for (i = l - 1; i >= 0; i--) for (k in arguments[i]) if (res[k] && isPlainObject(arguments[i][k])) res[k] = extend(arguments[i][k], res[k]); else res[k] = arguments[i][k]; return res; }
javascript
{ "resource": "" }
q47103
first
train
function first(a, fn, scope) { for (var i = 0, l = a.length; i < l; i++) { if (fn.call(scope || null, a[i])) return a[i]; } return; }
javascript
{ "resource": "" }
q47104
getExtension
train
function getExtension(url) { var a = url.split('.'); if (a.length === 1 || (a[0] === '' && a.length === 2)) return ''; return a.pop(); }
javascript
{ "resource": "" }
q47105
createDocument
train
function createDocument(root, namespace) { if (!root) return document.implementation.createHTMLDocument(); else return document.implementation.createDocument( namespace || null, root, null ); }
javascript
{ "resource": "" }
q47106
getScript
train
function getScript(url, async, cb) { if (typeof async === 'function') { cb = async; async = false; } var el = document.createElement('script'); // Script attributes el.type = 'text/javascript'; el.src = url; // Should the script be loaded asynchronously? if (async) el.async = true; // Defining callbacks el.onload = el.onreadystatechange = function() { if ((!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { el.onload = el.onreadystatechange = null; // Removing element from head artoo.mountNode.removeChild(el); if (typeof cb === 'function') cb(); } }; // Appending the script to head artoo.mountNode.appendChild(el); }
javascript
{ "resource": "" }
q47107
getStylesheet
train
function getStylesheet(data, isUrl, cb) { var el = document.createElement(isUrl ? 'link' : 'style'), head = document.getElementsByTagName('head')[0]; el.type = 'text/css'; if (isUrl) { el.href = data; el.rel = 'stylesheet'; // Waiting for script to load el.onload = el.onreadystatechange = function() { if ((!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { el.onload = el.onreadystatechange = null; if (typeof cb === 'function') cb(); } }; } else { el.innerHTML = data; } // Appending the stylesheet to head head.appendChild(el); }
javascript
{ "resource": "" }
q47108
async
train
function async() { var args = Array.prototype.slice.call(arguments); return setTimeout.apply(null, [args[0], 0].concat(args.slice(1))); }
javascript
{ "resource": "" }
q47109
parallel
train
function parallel(tasks, params, last) { var onEnd = (typeof params === 'function') ? params : params.done || last, running = [], results = [], d = 0, t, l, i; if (typeof onEnd !== 'function') onEnd = noop; function cleanup() { running.forEach(function(r) { clearTimeout(r); }); } function onTaskEnd(err, result) { // Adding results to accumulator results.push(result); if (err) { cleanup(); return onEnd(err, results); } if (++d >= tasks.length) { // Parallel action is finished, returning return onEnd(null, results); } // Adding on stack t = tasks[i++]; running.push(async(t, onTaskEnd)); } for (i = 0, l = params.limit || tasks.length; i < l; i++) { t = tasks[i]; // Dispatching the function asynchronously running.push(async(t, onTaskEnd)); } }
javascript
{ "resource": "" }
q47110
isAllowed
train
function isAllowed(level) { var threshold = artoo.settings.log.level; if (artoo.helpers.isArray(threshold)) return !!~threshold.indexOf(level); else return priorities.indexOf(level) >= priorities.indexOf(threshold); }
javascript
{ "resource": "" }
q47111
scrape
train
function scrape(iterator, data, params, cb) { var $ = artoo.$, scraped = [], loneSelector = !!data.attr || !!data.method || data.scrape || typeof data === 'string' || typeof data === 'function'; params = params || {}; // Transforming to selector var $iterator; if (typeof iterator === 'function') $iterator = $(iterator($)); else $iterator = $(iterator); // Iteration $iterator.each(function(i) { var item = {}, p; // TODO: figure iteration scope elsewhere for scrape recursivity if (loneSelector) item = (typeof data === 'object' && 'scrape' in data) ? scrape( (data.sel ? $(this).find(data.sel) : $(this)) .find(data.scrape.iterator), data.scrape.data, data.scrape.params ) : step(data, this); else for (p in data) { item[p] = (typeof data[p] === 'object' && 'scrape' in data[p]) ? scrape( (data[p].sel ? $(this).find(data[p].sel) : $(this)) .find(data[p].scrape.iterator), data[p].scrape.data, data[p].scrape.params ) : step(data[p], this); } scraped.push(item); // Breaking if limit i attained return !params.limit || i < params.limit - 1; }); scraped = params.one ? scraped[0] : scraped; // Triggering callback if (typeof cb === 'function') cb(scraped); // Returning data return scraped; }
javascript
{ "resource": "" }
q47112
polymorphism
train
function polymorphism(iterator, data, params, cb) { var h = artoo.helpers, i, d, p, c; if (h.isPlainObject(iterator) && !h.isSelector(iterator) && !h.isDocument(iterator) && (iterator.iterator || iterator.data || iterator.params)) { d = iterator.data; p = h.isPlainObject(iterator.params) ? iterator.params : {}; i = iterator.iterator; } else { d = data; p = h.isPlainObject(params) ? params : {}; i = iterator; } // Default values d = d || 'text'; c = typeof cb === 'function' ? cb : typeof params === 'function' ? params : p.done; return [i, d, p, c]; }
javascript
{ "resource": "" }
q47113
createZip
train
function createZip (targetZipPath, currentFolder, filesToInclude, done) { const args = ['-FS', targetZipPath].concat(filesToInclude) const startTime = Date.now() trace(`Calling: zip ${args.join(' ')}`) const child = childProcess.spawn('zip', args, { cwd: currentFolder, stdio: [ 'ignore', 'ignore', 'ignore' ] }) child.on('error', (err) => { error(`Error: please verify that <zip> is installed on your system`) error(err.toString()) }) child.on('close', (code, signal) => { const elapsed = Math.floor(Date.now() - startTime) debug(`Zip exited with code ${code} in ${elapsed}ms`) done(code === 0 ? null : new Error(`Error creating ZIP file ${targetZipPath}`)) }) }
javascript
{ "resource": "" }
q47114
train
function( event, drag ) { var el, drops, selector, sels; this.last_active = []; for(var i=0; i < this._elements.length; i++){ //for each element el = this._elements[i] var drops = $.event.findBySelector(el, eventNames) for(selector in drops){ //find the selectors sels = selector ? jQuery(selector, el) : [el]; for(var e= 0; e < sels.length; e++){ //for each found element, create a drop point jQuery.removeData(sels[e],"offset"); this.add(sels[e], new this(drops[selector]), event, drag); } } } }
javascript
{ "resource": "" }
q47115
train
function( url, expand ) { var u = File(url); // if this.path is absolutely referenced if ( this.protocol() ) { //if we are absolutely referenced //try to shorten the path as much as possible: var firstDomain = this.domain(), secondDomain = u.domain(); // if domains are equal, shorten if ( firstDomain && firstDomain == secondDomain ) { return this.toReferenceFromSameDomain(url); } else { // if there is no domain or not equal, use our path return this.path; } // the path is the same as the folder the page is in } else if ( url === steal.pageUrl().dir() && !expand ) { return this.path; } else if ( this.isLocalAbsolute() ) { // we are a path like /page.js return (u.domain() ? u.protocol() + "//" + u.domain() : "" )+ this.path; } else { //we have 2 relative paths, remove folders with every ../ if ( url === '' ) { return this.path.replace(/\/$/, ''); } var urls = url.split('/'), paths = this.path.split('/'), path = paths[0]; //if we are joining from a folder like cookbook/, remove the last empty part if ( url.match(/\/$/) ) { urls.pop(); } // for each .. remove one folder while ( path == '..' && paths.length > 0 ) { // if we've emptied out, folders, just break // leaving any additional ../s if(! urls.pop() ){ break; } paths.shift(); path = paths[0]; } return urls.concat(paths).join('/'); } }
javascript
{ "resource": "" }
q47116
train
function( url ) { var parts = this.path.split('/'), other_parts = url.split('/'), result = ''; while ( parts.length > 0 && other_parts.length > 0 && parts[0] == other_parts[0] ) { parts.shift(); other_parts.shift(); } each(other_parts, function(){ result += '../'; }) return result + parts.join('/'); }
javascript
{ "resource": "" }
q47117
train
function() { var current = File.cur().dir(), //if you are cross domain from the page, and providing a path that doesn't have an domain path = this.path; if (/^\/\//.test(this.path)) { //if path is rooted from steal's root (DEPRECATED) path = this.path.substr(2); } else if (/^\.\//.test(this.path)) { // should be relative this.path = this.path.substr(2); path = this.joinFrom(current); this.path = "./" + this.path; } else if (/^[^\.|\/]/.test(this.path)) {} else { if (this.relative() || File.cur().isCrossDomain() && //if current file is on another domain and !this.protocol()) { //this file doesn't have a protocol path = this.joinFrom(current); } } return path; }
javascript
{ "resource": "" }
q47118
train
function(options){ var stel = new steal.p.init(options), rootSrc = stel.options.rootSrc; if(stel.unique && rootSrc){ // the .js is b/c we are not adding that automatically until // load because we defer 'type' determination until then if(!steals[rootSrc] && ! steals[rootSrc+".js"]){ //if we haven't loaded it before steals[rootSrc] = stel; } else{ // already have this steal stel = steals[rootSrc]; // extend the old stolen file with any new options extend(stel.options, typeof options === "string" ? {} : options) } } return stel; }
javascript
{ "resource": "" }
q47119
train
function(returnScript) { // if we are already loading / loaded if(this.loading || this.isLoaded){ return; } this.loading = true; var self = this; // get yourself steal.require(this.options, function load_calling_loaded(script){ self.loaded(script); }, function(error, src){ win.clearTimeout && win.clearTimeout(self.completeTimeout) throw "steal.js : "+self.options.src+" not completed" }); }
javascript
{ "resource": "" }
q47120
train
function(){ var args = typeof arguments[0] == 'function' ? arguments : [function(){}].concat(makeArray( arguments ) ) return steal.apply(win, args ); }
javascript
{ "resource": "" }
q47121
train
function(event, listener){ if(!events[event]){ events[event] = [] } var special = steal.events[event] if(special && special.add){ listener = special.add(listener); } listener && events[event].push(listener); return steal; }
javascript
{ "resource": "" }
q47122
train
function(event, listener){ var evs = events[event] || [], i = 0; while(i < evs.length){ if(listener === evs[i]){ evs.splice(i,1); }else{ i++; } } }
javascript
{ "resource": "" }
q47123
train
function(name){ // create the steal, mark it as loading, then as loaded var stel = steal.p.make( name ); stel.loading = true; convert(stel, "complete"); steal.preloaded(stel); stel.loaded() return steal; }
javascript
{ "resource": "" }
q47124
train
function(script) { script[ STR_ONREADYSTATECHANGE ] = script[ STR_ONLOAD ] = script[STR_ONERROR] = null; head().removeChild( script ); }
javascript
{ "resource": "" }
q47125
train
function(){ // if we don't have a current 'top' steal // we create one and set it up // to start loading its dependencies (the current pending steals) if(! currentCollection ){ currentCollection = new steal.p.init(); // keep a reference in case it disappears var cur = currentCollection, // runs when a steal is starting go = function(){ // indicates that a collection of steals has started steal.trigger("start", cur); when(cur,"complete", function(){ steal.trigger("end", cur); }); cur.loaded(); }; // if we are in rhino, start loading dependencies right away if(!win.setTimeout){ go() }else{ // otherwise wait a small timeout to make // sure we get all steals in the current file setTimeout(go,0) } } }
javascript
{ "resource": "" }
q47126
train
function(){ // indicates that a collection of steals has started steal.trigger("start", cur); when(cur,"complete", function(){ steal.trigger("end", cur); }); cur.loaded(); }
javascript
{ "resource": "" }
q47127
after
train
function after(f, after, changeRet){ return changeRet ? function after_CRet(){ return after.apply(this,[f.apply(this,arguments)].concat(makeArray(arguments))); }: function after_Ret(){ var ret = f.apply(this,arguments); after.apply(this,arguments); return ret; } }
javascript
{ "resource": "" }
q47128
convert
train
function convert(ob, func){ var oldFunc = ob[func]; // if we don't have callbacks if(!ob[func].callbacks){ //replace start with a function that will call ob2's method ob[func] = function(){ var me = arguments.callee, ret; // call the original function ret = oldFunc.apply(ob,arguments); var cbs = me.callbacks, len = cbs.length; //mark as called so any callees added to this caller will //automatically get called me.called = true; // call other callbacks for(var i =0; i < len; i++){ cbs[i].called() } return ret; } ob[func].callbacks = []; } return ob[func]; }
javascript
{ "resource": "" }
q47129
train
function(obj, meth){ // converts the function to be able to call // this join var f = convert(obj, meth); if(!f.called){ // adds us to the callback ... the callback will call // called f.callbacks.push(this); this.calls++; } }
javascript
{ "resource": "" }
q47130
train
function( event, element, type, autoPrevent ) { // dispatchEvent doesn't always work in IE (mostly in a popup) if ( element.dispatchEvent && event ) { var preventDefault = event.preventDefault, prevents = autoPrevent ? -1 : 0; //automatically prevents the default behavior for this event //this is to protect agianst nasty browser freezing bug in safari if ( autoPrevent ) { bind(element, type, function( ev ) { ev.preventDefault(); unbind(this, type, arguments.callee); }); } event.preventDefault = function() { prevents++; if (++prevents > 0 ) { preventDefault.apply(this, []); } }; element.dispatchEvent(event); return prevents <= 0; } else { try { window.event = event; } catch (e) {} //source element makes sure element is still in the document return element.sourceIndex <= 0 || (element.fireEvent && element.fireEvent('on' + type, event)); } }
javascript
{ "resource": "" }
q47131
train
function( timeout, callback ) { if ( typeof timeout === 'function' ) { callback = timeout; timeout = null; } timeout = timeout || 600; var self = this; this.queue.unshift(function() { setTimeout(function() { callback && callback.apply(self, []) self.done.apply(self, arguments); }, timeout); }); return this; }
javascript
{ "resource": "" }
q47132
train
function( keyCode ) { var specials = S.key.kinds.special; for ( var i = 0; i < specials.length; i++ ) { if ( Syn.keycodes[specials[i]] == keyCode ) { return specials[i]; } } }
javascript
{ "resource": "" }
q47133
train
function( key ) { //check if it is described directly if ( Syn.key.defaults[key] ) { return Syn.key.defaults[key]; } for ( var kind in Syn.key.kinds ) { if ( h.inArray(key, Syn.key.kinds[kind]) > -1 && Syn.key.defaults[kind] ) { return Syn.key.defaults[kind]; } } return Syn.key.defaults.character }
javascript
{ "resource": "" }
q47134
train
function( type, options, element ) { //Everyone Else var doc = h.getWindow(element).document || document; if ( doc.createEvent ) { var event; try { event = doc.createEvent("KeyEvents"); event.initKeyEvent(type, true, true, window, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.keyCode, options.charCode); } catch (e) { event = h.createBasicStandardEvent(type, options, doc); } event.synthetic = true; return event; } else { var event; try { event = h.createEventObject.apply(this, arguments); h.extend(event, options) } catch (e) {} return event; } }
javascript
{ "resource": "" }
q47135
train
function( runDefaults, el ) { var part = parts.shift(); if (!part ) { callback(runDefaults, el); return; } el = el || element; if ( part.length > 1 ) { part = part.substr(1, part.length - 2) } self._key(part, el, runNextPart) }
javascript
{ "resource": "" }
q47136
getAvailableBrowsers
train
function getAvailableBrowsers(config, browsers, cb) { browsers.forEach(function(b) { b.protocol = 'browser'; }); return Bluebird.filter(browsers, function(browser) { return isInstalled(browser, config).then(function(result) { if (!result) { return false; } browser.exe = result; return true; }); }).asCallback(cb); }
javascript
{ "resource": "" }
q47137
train
function( direction, amount, success ) { this._addExists(); var selector = this.selector, context = this.context, direction; if (direction == "left" || direction == "right") { direction = "Left"; } else if (direction == "top" || direction == "bottom") { direction = "Top"; } FuncUnit.add({ method: function(success, error){ steal.dev.log("setting " + selector + " scroll" + direction + " " + amount + " pixels") this.bind.each(function(i, el){ this["scroll" + direction] = amount; }) success(); }, success: success, error: "Could not scroll " + this.selector, bind: this, type: "action" }); return this; }
javascript
{ "resource": "" }
q47138
train
function( target ) { var selector = target.nodeName.toLowerCase(); if(target.id){ return "#"+target.id }else{ var parent = target.parentNode; while(parent){ if(parent.id){ selector = "#"+parent.id+" "+selector; break; }else{ parent = parent.parentNode } } } if(target.className){ selector += "."+target.className.split(" ")[0] } var others = jQuery(selector, Syn.helpers.getWindow(target).document) if(others.length > 1){ return selector+":eq("+others.index(target)+")"; }else{ return selector; } }
javascript
{ "resource": "" }
q47139
train
function( timeout, success, message ) { var logMessage = "Waiting for '"+this.selector+"' to exist"; if(timeout === false){ // pass false to suppress this wait (make it not print any logMessage) logMessage = false } return this.size({ condition: function(size){ return size > 0; }, timeout: timeout, success: success, message: message, errorMessage: "Exist failed: element with selector '"+this.selector+"' not found", logMessage: logMessage }) }
javascript
{ "resource": "" }
q47140
train
function( timeout, success, message ) { var self = this, sel = this.selector, ret; return this.size(function(size){ return this.is(":visible") === true; }, timeout, success, message) }
javascript
{ "resource": "" }
q47141
train
function(){ var loaded = FuncUnit.win.document.readyState === "complete" && FuncUnit.win.location.href != "about:blank" && FuncUnit.win.document.body; return loaded; }
javascript
{ "resource": "" }
q47142
train
function( out ) { if(steal.options.logLevel < 2){ Array.prototype.unshift.call(arguments, 'steal.js WARN:'); if ( window.console && console.warn ) { this._logger( "warn", Array.prototype.slice.call(arguments) ); } else if ( window.console && console.log ) { this._logger( "log", Array.prototype.slice.call(arguments) ); } else if ( window.opera && window.opera.postError ) { opera.postError("steal.js WARNING: " + out); } } }
javascript
{ "resource": "" }
q47143
kill
train
function kill(p, sig) { if (isWin) { let command = 'taskkill.exe'; let args = ['/t', '/pid', p.pid]; if (sig === 'SIGKILL') { args.push('/f'); } execa(command, args).then(result => { // Processes without windows can't be killed without /F, detect and force // kill them directly if (result.stderr.indexOf('can only be terminated forcefully') !== -1) { kill(p, 'SIGKILL'); } }).catch(err => { log.error(err); }); } else { p.kill(sig); } }
javascript
{ "resource": "" }
q47144
train
function( f ) { var i, vec, newArr = []; for ( i = 0; i < this.array.length; i++ ) { newArr.push(f(this.array[i])); } vec = new $.Vector(); return vec.update(newArr); }
javascript
{ "resource": "" }
q47145
train
function() { var i, args = arguments[0] instanceof $.Vector ? arguments[0].array : $.makeArray(arguments), arr = this.array.slice(0), vec = new $.Vector(); for ( i = 0; i < args.length; i++ ) { if ( arr[i] != args[i] ) { return null; } } return vec.update(arr); }
javascript
{ "resource": "" }
q47146
train
function( array ) { var i; if ( this.array ) { for ( i = 0; i < this.array.length; i++ ) { delete this.array[i]; } } this.array = array; for ( i = 0; i < array.length; i++ ) { this[i] = this.array[i]; } return this; }
javascript
{ "resource": "" }
q47147
train
function( ev, element ) { var isLeftButton = ev.button === 0 || ev.button == 1; if (!isLeftButton || this.current ) { return; } //only allows 1 drag at a time, but in future could allow more //ev.preventDefault(); //create Drag var drag = new $.Drag(), delegate = ev.liveFired || element, selector = ev.handleObj.selector, self = this; this.current = drag; drag.setup({ element: element, delegate: ev.liveFired || element, selector: ev.handleObj.selector, moved: false, callbacks: { dragdown: event.find(delegate, ["dragdown"], selector), draginit: event.find(delegate, ["draginit"], selector), dragover: event.find(delegate, ["dragover"], selector), dragmove: event.find(delegate, ["dragmove"], selector), dragout: event.find(delegate, ["dragout"], selector), dragend: event.find(delegate, ["dragend"], selector) }, destroyed: function() { self.current = null; } }, ev); }
javascript
{ "resource": "" }
q47148
train
function() { $(document).unbind('mousemove', this._mousemove); $(document).unbind('mouseup', this._mouseup); if (!this.moved ) { this.event = this.element = null; } //this.selection(); this.destroyed(); }
javascript
{ "resource": "" }
q47149
train
function( pointer, event ) { // only drag if we haven't been cancelled; if ( this._cancelled ) { return; } /** * @attribute location * The location of where the element should be in the page. This * takes into account the start position of the cursor on the element. */ this.location = pointer.minus(this.mouseElementPosition); // the offset between the mouse pointer and the representative that the user asked for // position = mouse - (dragOffset - dragTopLeft) - mousePosition this.move(event); if ( this._cancelled ) { return; } if (!event.isDefaultPrevented() ) { this.position(this.location); } //fill in if (!this._only && this.constructor.responder ) { this.constructor.responder.show(pointer, this, event); } }
javascript
{ "resource": "" }
q47150
train
function( newOffsetv ) { //should draw it on the page var style, dragged_element_css_offset = this.currentDelta(), // the drag element's current left + top css attributes dragged_element_position_vector = // the vector between the movingElement's page and css positions this.movingElement.offsetv().minus(dragged_element_css_offset); // this can be thought of as the original offset this.required_css_position = newOffsetv.minus(dragged_element_position_vector); this.offsetv = newOffsetv; //dragged_element vector can probably be cached. style = this.movingElement[0].style; if (!this._cancelled && !this._horizontal ) { style.top = this.required_css_position.top() + "px"; } if (!this._cancelled && !this._vertical ) { style.left = this.required_css_position.left() + "px"; } }
javascript
{ "resource": "" }
q47151
train
function( event ) { if ( this._cancelled ) { return; } if (!this._only && this.constructor.responder ) { this.constructor.responder.end(event, this); } this.callEvents('end', this.element, event); if ( this._revert ) { var self = this; this.movingElement.animate({ top: this.startPosition.top() + "px", left: this.startPosition.left() + "px" }, function() { self.cleanup.apply(self, arguments); }); } else { this.cleanup(); } this.event = null; }
javascript
{ "resource": "" }
q47152
train
function() { this.movingElement.css({ zIndex: this.oldZIndex }); if ( this.movingElement[0] !== this.element[0] ) { this.movingElement.css({ display: 'none' }); } if ( this._removeMovingElement ) { this.movingElement.remove(); } this.movingElement = this.element = this.event = null; }
javascript
{ "resource": "" }
q47153
train
function() { this._cancelled = true; //this.end(this.event); if (!this._only && this.constructor.responder ) { this.constructor.responder.clear(this.event.vector(), this, this.event); } this.destroy(); }
javascript
{ "resource": "" }
q47154
train
function( loc ) { // create a ghost by cloning the source element and attach the clone to the dom after the source element var ghost = this.movingElement.clone().css('position', 'absolute'); (loc ? $(loc) : this.movingElement).after(ghost); ghost.width(this.movingElement.width()).height(this.movingElement.height()); // store the original element and make the ghost the dragged element this.movingElement = ghost; this._removeMovingElement = true; return ghost; }
javascript
{ "resource": "" }
q47155
train
function( element, offsetX, offsetY ) { this._offsetX = offsetX || 0; this._offsetY = offsetY || 0; var p = this.mouseStartPosition; this.movingElement = $(element); this.movingElement.css({ top: (p.y() - this._offsetY) + "px", left: (p.x() - this._offsetX) + "px", display: 'block', position: 'absolute' }).show(); this.mouseElementPosition = new $.Vector(this._offsetX, this._offsetY); }
javascript
{ "resource": "" }
q47156
getUserProfile
train
function getUserProfile(key, steamID, callback) { var steam = new SteamWebAPI({ apiKey: key, format: 'json' }); steam.getPlayerSummaries({ steamids: [ steamID ], callback: function(err, result) { if(err) { return callback(err); } var profile = { provider: 'steam', _json: result.response.players[0], id: result.response.players[0].steamid, displayName: result.response.players[0].personaname, photos: [{ value: result.response.players[0].avatar }, { value: result.response.players[0].avatarmedium }, { value: result.response.players[0].avatarfull }] }; callback(null, profile); } }); }
javascript
{ "resource": "" }
q47157
verify
train
function verify(req, identifier, profile, done) { var validOpEndpoint = 'https://steamcommunity.com/openid/login'; var identifierRegex = /^https?:\/\/steamcommunity\.com\/openid\/id\/(\d+)$/; if(req.query['openid.op_endpoint'] !== validOpEndpoint || !identifierRegex.test(identifier)) { return done(null, false, { message: 'Claimed identity is invalid.' }); } var steamID = identifierRegex.exec(identifier)[0]; if(options.profile) { getUserProfile(options.apiKey, steamID, function(err, profile) { if(err) { done(err); } else { if(originalPassReqToCallback) { validate(req, identifier, profile, done); } else { validate(identifier, profile, done); } } }); } else { if(originalPassReqToCallback) { validate(req, identifier, profile, done); } else { validate(identifier, profile, done); } } }
javascript
{ "resource": "" }
q47158
addLatency
train
function addLatency(request, response, next) { if (request.path === '/') { return next(); } setTimeout(next, args.latency); }
javascript
{ "resource": "" }
q47159
serveRemoteJson
train
function serveRemoteJson(request, response, next) { if (request.path !== '/remote') { return next(); } var options = { url: request.query.url, headers: request.query.headers }; var error; if (!options.url || typeof options.url !== 'string') { error = new Error('Invalid query parameter: url'); error.status = 400; return next(error); } if (options.headers && typeof options.headers !== 'string') { error = new Error('Invalid query parameter: headers'); error.status = 400; return next(error); } options.headers = parseHeaders(options.headers); loadRemoteJson(options, function (error, json) { if (error) { return next(error); } response.writeHead(200, { 'Content-Type': 'application/x-shunter+json' }); response.end(JSON.stringify(json, null, 4)); }); }
javascript
{ "resource": "" }
q47160
loadRemoteJson
train
function loadRemoteJson(options, done) { var requestOptions = { url: options.url, headers: options.headers }; var error; request(requestOptions, function (err, response, body) { if (err) { return done(error); } if (response.statusCode < 200 || response.statusCode >= 300) { error = new Error('Remote JSON responded with ' + response.statusCode + ' status'); error.status = response.statusCode; return done(error); } try { body = JSON.parse(body); } catch (err) { return done(err); } done(null, body); }); }
javascript
{ "resource": "" }
q47161
parseHeaders
train
function parseHeaders(headerString) { var headers = {}; var headersArray = headerString.split(/[\r\n]+/); headersArray.forEach(function (headerString) { var headerChunks = headerString.split(':'); headers[headerChunks.shift().trim()] = headerChunks.join(':').trim(); }); return headers; }
javascript
{ "resource": "" }
q47162
train
function (p, cb) { var pth = p.replace(/\\\?/g, '\/'); // Glob must use / as path seperator even on windows glob(pth + '/**/*.*', function (er, files) { if (er) { return cb(er); } return cb(null, files.map(function (f) { return path.relative(p, f); })); }); }
javascript
{ "resource": "" }
q47163
train
function (name) { var isProduction = config.env.isProduction(); var asset = (isProduction) ? manifest.assets[name] : environment.findAsset(name); if (!asset) { return ''; } var mountPath = config.argv && (config.argv['mount-path'] || ''); return ( isProduction ? path.join(mountPath, config.web.publicResources, asset) : path.join(mountPath, config.web.resources, asset.digestPath) ); }
javascript
{ "resource": "" }
q47164
train
function (paths) { var self = this; if (typeof paths === 'string') { paths = [].slice.call(arguments, 0); } paths.forEach(function (name) { // DEPRECATED: checking both themes and templates folders for the right template file // when updated, should just look for 'self.compileFile(name));' // name will need to be full path, or contain the relevant subfolders e.g. laserwolf/views/subject/foo.dust if (fs.existsSync(path.join(config.path.themes, name))) { // Themes self.compileFile(path.join(config.path.themes, name)); } else if (fs.existsSync(path.join(config.path.templates, name))) { // Old shunter-proxy self.compileFile(path.join(config.path.templates, name)); } else if (fs.existsSync(name)) { // Full path self.compileFile(name); } else { config.log.info('Could not find template ' + name); } // End DEPRECATED }); }
javascript
{ "resource": "" }
q47165
findPackages
train
function findPackages(packagesPath) { return fs.readdirSync(packagesPath).reduce((acc, d) => { const fullpath = path.resolve(packagesPath, d); if (fs.statSync(fullpath).isDirectory()) { try { fs.statSync(path.resolve(fullpath, 'package.json')); acc.push(fullpath); } catch (err) { if (err.code === 'ENOENT') { return acc.concat(findPackages(fullpath)); } throw err; } } return acc; }, []); }
javascript
{ "resource": "" }
q47166
updateAllPackages
train
function updateAllPackages(rootPkgPath, packagesPath) { const paths = findPackages(packagesPath); return paths.reduce((promise, pkgPath) => promise.then(() => updateSinglePackage(rootPkgPath, pkgPath)), Promise.resolve()); }
javascript
{ "resource": "" }
q47167
checkLastCommit
train
async function checkLastCommit() { debug('checking if the last commit message has explicit release instructions'); const summary = await git.lastLog(); const re = /^#release v(\d+\.\d+\.\d+)/; const match = summary.match(re); if (match) { const version = match[1]; if (version) { return version; } } return undefined; }
javascript
{ "resource": "" }
q47168
getChangeType
train
async function getChangeType() { const subjects = await exec('git log upstream/master.. --format=%s'); for (const subject of subjects.split('\n')) { if (subject.startsWith('feat')) { return 'minor'; } if (subject.startsWith('fix') || subject.startsWith('perf') || subject.startsWith('refactor')) { return 'patch'; } } return undefined; }
javascript
{ "resource": "" }
q47169
fileToPackage
train
function fileToPackage(d) { debug(d); if (d.startsWith('packages/node_modules/')) { d = d.replace('packages/node_modules/', ''); d = d.split('/'); if (d[0].startsWith('@')) { return d.slice(0, 2).join('/'); } return d[0]; } if (d.startsWith('docs') || d.startsWith('documentation') || d.startsWith('.github') || d.endsWith('.md')) { return 'docs'; } return 'tooling'; }
javascript
{ "resource": "" }
q47170
read
train
async function read(packageName) { const packagePath = path.join(cwd, packageName, 'package.json'); return JSON.parse(await fs.readFile(packagePath)); }
javascript
{ "resource": "" }
q47171
write
train
async function write(packageName, pkg) { const packagePath = path.join(cwd, packageName, 'package.json'); await fs.writeFile(packagePath, `${JSON.stringify(pkg, null, 2)}\n`); }
javascript
{ "resource": "" }
q47172
encode
train
function encode(fp) { return new Promise((resolve, reject) => { fp.encode((err, encoded) => { if (err) { reject(err); return; } resolve(encoded); }); }); }
javascript
{ "resource": "" }
q47173
injectLocal
train
async function injectLocal(def) { debug(`checking ${def.base} for firefox`); if (def.base.toLowerCase().includes('firefox')) { debug('def is a firefox def'); const platform = platformToShortName(os.platform()); debug(`injecting ${platform} profile into ${def.base}`); const dest = await prepareLocalProfile(platform); def.profile = dest; debug(`injected ${dest} profile into ${def.base}`); } }
javascript
{ "resource": "" }
q47174
injectSauce
train
async function injectSauce(def) { debug(`checking ${def.base} for firefox`); if (def.browserName.toLowerCase().includes('firefox')) { debug('def is a firefox def'); const platform = platformToShortName(def.platform); if (platform !== 'mac') { throw new Error(`No tooling implemented for injecting h264 into ${platform} (${def.platform})`); } debug(`injecting ${platform} profile into ${def.base}`); const dir = path.resolve(process.cwd(), `${PROFILE_DIR}/${platform}`); debug(`profile is at ${dir}`); const profile = await copy(dir); const encoded = await encode(profile); // eslint-disable-next-line camelcase def.firefox_profile = encoded; debug(`injected ${platform} profile into def`); } }
javascript
{ "resource": "" }
q47175
watchSauce
train
async function watchSauce(server, cfg) { try { debug('reading sauce pid'); const pid = parseInt(await readFile(process.env.SC_PID_FILE), 10); debug(`sauce pid is ${pid}`); let done = false; server.once('run_complete', () => { debug('run complete'); done = true; }); const delay = 1000; // eslint-disable-next-line no-unmodified-loop-condition while (!done) { debug(`waiting ${delay}ms`); await new Promise((resolve) => setTimeout(resolve, delay)); debug(`waited ${delay}ms`); await new Promise((resolve, reject) => { debug(`checking if ${pid} is running`); ps.lookup({ psargs: '-A', pid }, (err, resultList) => { if (err) { debug('ps-node produced an error', err); reject(err); return; } if (resultList.length === 0) { debug(`pid ${pid} is not running`); reject(new Error(`pid ${pid} is not running`)); return; } debug(`pid ${pid} is running`); resolve(); }); }); } } catch (err) { console.error(err); console.error('Sauce Tunnel is not running, stopping server and exiting'); stopper.stop(cfg); // so, this is a bit harsh, but due to karma's api,there's no great way to // communicate back to test.js that karma failed because the tunnel // disappeared. By exiting here, cmd.sh should restart sauce and run the // suite again // eslint-disable-next-line no-process-exit process.exit(65); } }
javascript
{ "resource": "" }
q47176
start
train
async function start() { if (child) { await stop(); } return new Promise((resolve) => { const serverPath = path.resolve(process.cwd(), 'packages/node_modules/@webex/test-helper-server'); child = spawn(process.argv[0], [serverPath], { env: process.env, stdio: ['ignore', 'pipe', process.stderr] }); child.stdout.on('data', (data) => { const message = `${data}`; const pattern = /.+/gi; if (message.match(pattern)) { resolve(); } }); process.on('exit', stop); }); }
javascript
{ "resource": "" }
q47177
stop
train
function stop() { return new Promise((resolve) => { if (child && child.kill) { debug('stopping test server'); child.kill('SIGTERM'); process.removeListener('exit', stop); child = null; debug('stopped test server'); } resolve(); }); }
javascript
{ "resource": "" }
q47178
versionFromState
train
function versionFromState(state) { // eslint-disable-next-line global-require return require(pkgUp.sync(state.file.opts.filename)).version; }
javascript
{ "resource": "" }
q47179
buildLocalDepTree
train
async function buildLocalDepTree() { for (const packageName of await _list()) { tree.set(packageName, await exports.list(packageName, { includeTransitive: false, localOnly: true })); } }
javascript
{ "resource": "" }
q47180
buildDirectDependentTree
train
async function buildDirectDependentTree() { const dependents = new Map(); for (const packageName of await _list()) { dependents.set(packageName, new Set()); } for (const packageName of await _list()) { for (const dep of tree.get(packageName)) { dependents.get(dep).add(packageName); } } return dependents; }
javascript
{ "resource": "" }
q47181
findDeps
train
function findDeps(entrypoints) { let deps = new Set(); for (const entrypoint of entrypoints) { deps = new Set([...deps, ...walk(entrypoint)]); } return deps; }
javascript
{ "resource": "" }
q47182
requireToPackage
train
function requireToPackage(d) { d = d.split('/'); if (d[0].startsWith('@')) { return d.slice(0, 2).join('/'); } return d[0]; }
javascript
{ "resource": "" }
q47183
listEntryPoints
train
function listEntryPoints(pkg) { debug(`listing entrypoints for ${pkg.name}`); if (!pkg.name) { throw new Error('cannot read dependencies for unnamed package'); } let paths = []; if (pkg.main) { debug(`found main path for ${pkg.name}`); paths.push(pkg.main); } if (pkg.bin) { debug(`found bin entry(s) for ${pkg.name}`); paths = paths.concat(values(pkg.bin)); } if (pkg.browser) { debug(`found browser entry(s) for ${pkg.name}`); paths = paths.concat(values(pkg.browser).filter((p) => p && !p.startsWith('@'))); } debug(paths); return paths .map((p) => path.resolve('packages', 'node_modules', pkg.name, p)); }
javascript
{ "resource": "" }
q47184
walk
train
function walk(entrypoint) { try { if (!visited.has(entrypoint)) { debug(`finding requires for ${entrypoint}`); // This whole thing is *way* easier if we do it synchronously // eslint-disable-next-line no-sync const requires = detective(fs.readFileSync(entrypoint)); visited.set(entrypoint, requires.reduce((acc, dep) => { debug(`found ${dep}`); if (dep.startsWith('.')) { debug(`${dep} is relative, descending`); const next = walk(path.resolve(path.dirname(entrypoint), dep)); acc = new Set([...acc, ...next]); } else if (!builtins.includes(dep)) { debug(`found dependency ${dep}`); acc.add(requireToPackage(dep)); } return acc; }, new Set())); } return visited.get(entrypoint); } catch (err) { if (err.code === 'EISDIR') { return walk(path.resolve(entrypoint, 'index.js')); } if (err.code === 'ENOENT' && !entrypoint.endsWith('.js')) { return walk(`${entrypoint}.js`); } throw err; } }
javascript
{ "resource": "" }
q47185
startProxies
train
async function startProxies() { await Promise.all(services.map((service) => setEnv(service))); return Promise.all(services.map((service) => start(service))); }
javascript
{ "resource": "" }
q47186
stopProxies
train
async function stopProxies() { if (proxies && proxies.length) { return Promise.all(proxies.map((proxy) => stop(proxy))); } return Promise.resolve(); }
javascript
{ "resource": "" }
q47187
start
train
async function start(service) { return new Promise((resolve) => { const snapshotsDir = path.join(__dirname, '../../test/services/', service.name, 'snapshots'); const app = yakbak(service.defaultUrl, { dirname: snapshotsDir, hash: customHash }); const proxy = http.createServer(app).listen(service.port, () => { console.log(`Yakbak server listening on port ${service.port}. Proxy for ${service.defaultUrl}`); }); resolve(proxy); }); }
javascript
{ "resource": "" }
q47188
customHash
train
function customHash(req, body) { const hash = crypto.createHash('md5'); updateHash(hash, req); hash.write(body); return hash.digest('hex'); }
javascript
{ "resource": "" }
q47189
pruneHeaders
train
function pruneHeaders(requestHeaders) { const headers = Object.assign({}, requestHeaders); delete headers.trackingid; delete headers.authorization; return headers; }
javascript
{ "resource": "" }
q47190
attachEvt
train
function attachEvt( elems, evt ){ for( var i = 0, len = elems.length; i < len; i++ ){ mainButton = elems[i].querySelector('.' + mainButtonClass); mainButton.addEventListener( evt , toggleButton, false); } }
javascript
{ "resource": "" }
q47191
replaceAttrs
train
function replaceAttrs( elems ){ for( var i = 0, len = elems.length; i < len; i++ ){ elems[i].setAttribute( toggleMethod, clickOpt ); elems[i].setAttribute( menuState, isClosed ); } }
javascript
{ "resource": "" }
q47192
HOARenderer
train
function HOARenderer(context, config) { this._context = Utils.isAudioContext(context) ? context : Utils.throw('HOARenderer: Invalid BaseAudioContext.'); this._config = { ambisonicOrder: 3, renderingMode: RenderingMode.AMBISONIC, }; if (config && config.ambisonicOrder) { if (SupportedAmbisonicOrder.includes(config.ambisonicOrder)) { this._config.ambisonicOrder = config.ambisonicOrder; } else { Utils.log( 'HOARenderer: Invalid ambisonic order. (got ' + config.ambisonicOrder + ') Fallbacks to 3rd-order ambisonic.'); } } this._config.numberOfChannels = (this._config.ambisonicOrder + 1) * (this._config.ambisonicOrder + 1); this._config.numberOfStereoChannels = Math.ceil(this._config.numberOfChannels / 2); if (config && config.hrirPathList) { if (Array.isArray(config.hrirPathList) && config.hrirPathList.length === this._config.numberOfStereoChannels) { this._config.pathList = config.hrirPathList; } else { Utils.throw( 'HOARenderer: Invalid HRIR URLs. It must be an array with ' + this._config.numberOfStereoChannels + ' URLs to HRIR files.' + ' (got ' + config.hrirPathList + ')'); } } if (config && config.renderingMode) { if (Object.values(RenderingMode).includes(config.renderingMode)) { this._config.renderingMode = config.renderingMode; } else { Utils.log( 'HOARenderer: Invalid rendering mode. (got ' + config.renderingMode + ') Fallbacks to "ambisonic".'); } } this._buildAudioGraph(); this._isRendererReady = false; }
javascript
{ "resource": "" }
q47193
FOARouter
train
function FOARouter(context, channelMap) { this._context = context; this._splitter = this._context.createChannelSplitter(4); this._merger = this._context.createChannelMerger(4); // input/output proxy. this.input = this._splitter; this.output = this._merger; this.setChannelMap(channelMap || ChannelMap.DEFAULT); }
javascript
{ "resource": "" }
q47194
computeHOAMatrices
train
function computeHOAMatrices(matrix) { // We start by computing the 2nd-order matrix from the 1st-order matrix. for (let i = 2; i <= matrix.length; i++) { computeBandRotation(matrix, i); } }
javascript
{ "resource": "" }
q47195
buildPath
train
function buildPath (basePath, queryParams) { basePath = basePath.concat('?') var url = basePath.concat(queryString.stringify(queryParams)) return url }
javascript
{ "resource": "" }
q47196
restoreCase
train
function restoreCase (word, token) { // Tokens are an exact match. if (word === token) return token // Upper cased words. E.g. "HELLO". if (word === word.toUpperCase()) return token.toUpperCase() // Title cased words. E.g. "Title". if (word[0] === word[0].toUpperCase()) { return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase() } // Lower cased words. E.g. "test". return token.toLowerCase() }
javascript
{ "resource": "" }
q47197
extractGlamorStyles
train
function extractGlamorStyles(className) { const glamorlessClassName = [] const glamorStyles = [] className .toString() .split(' ') .forEach(name => { if (styleSheet.registered[name.substring(4)] === undefined) { glamorlessClassName.push(name) } else { const style = buildGlamorSrcFromClassName(name) glamorStyles.push(style) } }) return {glamorlessClassName, glamorStyles} }
javascript
{ "resource": "" }
q47198
handleStyles
train
function handleStyles(styles, props, context) { let current const mappedArgs = [] const nonGlamorClassNames = [] for (let i = 0; i < styles.length; i++) { current = styles[i] while (typeof current === 'function') { current = current(props, context) } if (typeof current === 'string') { const {glamorStyles, glamorlessClassName} = extractGlamorStyles(current) mappedArgs.push(...glamorStyles) nonGlamorClassNames.push(...glamorlessClassName) } else if (Array.isArray(current)) { const recursed = handleStyles(current, props, context) mappedArgs.push(...recursed.mappedArgs) nonGlamorClassNames.push(...recursed.nonGlamorClassNames) } else { mappedArgs.push(current) } } return {mappedArgs, nonGlamorClassNames} }
javascript
{ "resource": "" }
q47199
getPropsToApply
train
function getPropsToApply(propsToApply, accumulator, props, context) { // using forEach rather than reduce here because the reduce solution // effectively did the same thing because we manipulate the `accumulator` propsToApply.forEach(propsToApplyItem => { if (typeof propsToApplyItem === 'function') { return Object.assign( accumulator, propsToApplyItem(Object.assign({}, accumulator, props), context), ) } else if (Array.isArray(propsToApplyItem)) { return Object.assign( accumulator, getPropsToApply(propsToApplyItem, accumulator, props, context), ) } return Object.assign(accumulator, propsToApplyItem) }) // props wins return Object.assign(accumulator, props) }
javascript
{ "resource": "" }