_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q49900
ComponentContext
train
function ComponentContext(zuixInstance, options, eventCallback) { zuix = zuixInstance; this._options = null; this.contextId = (options == null || options.contextId == null) ? null : options.contextId; this.componentId = null; this.trigger = function(context, eventPath, eventValue) { if (typeof eventCallback === 'function') { eventCallback(context, eventPath, eventValue); } }; /** @protected */ this._container = null; /** @protected */ this._model = null; /** @protected */ this._view = null; /** @protected */ this._css = null; /** @protected */ this._style = null; /** * @protected * @type {ContextControllerHandler} */ this._controller = null; /** * Define the local behavior handler for this context instance only. * Any global behavior matching the same `componentId` will be overridden. * * @function behavior * @param handler_fn {function} */ this.behavior = null; /** @package */ this._eventMap = []; /** @package */ this._behaviorMap = []; /** * @package * @type {ContextController} */ this._c = null; this.options(options); return this; }
javascript
{ "resource": "" }
q49901
trigger
train
function trigger(context, path, data) { if (util.isFunction(_hooksCallbacks[path])) { _hooksCallbacks[path].call(context, data, context); } }
javascript
{ "resource": "" }
q49902
Logger
train
function Logger(ctx) { _console = window ? window.console : {}; _global = window ? window : {}; this._timers = {}; this.args = function(context, level, args) { let logHeader = '%c '+level+' %c'+(new Date().toISOString())+' %c'+context; const colors = [_bc+_c1, _bc+_c2, _bc+_c3]; for (let i = 0; i < args.length; i++) { if (typeof args[i] == 'string' && args[i].indexOf('timer:') === 0) { const t = args[i].split(':'); if (t.length === 3) { let elapsed; switch (t[2]) { case 'start': this._timers[t[1]] = new Date().getTime(); logHeader += ' %cSTART '+t[1]; colors.push(_bc+_c_start); break; case 'stop': elapsed = (new Date().getTime() - this._timers[t[1]]); logHeader += ' %cSTOP '+t[1]+' '+elapsed+' ms'; if (elapsed > 200) { colors.push(_bc+_c_end_very_slow); } else if (elapsed > 100) { colors.push(_bc+_c_end_slow); } else { colors.push(_bc+_c_end); } break; } } } } logHeader += ' \n%c '; colors.push(_bt+'color:inherit;'); // if (typeof args[0] == 'string') { // logHeader += ' %c' + args[0]; // Array.prototype.shift.call(args); // } for (let c = colors.length-1; c >= 0; c--) { Array.prototype.unshift.call(args, colors[c]); } Array.prototype.unshift.call(args, logHeader); Array.prototype.push.call(args, '\n\n'); }; this.log = function(level, args) { if (typeof _callback === 'function') { _callback.call(ctx, level, args); } // route event if (!_global.zuixNoConsoleOutput) { this.args(ctx, level, args); _console.log.apply(_console, args); } }; }
javascript
{ "resource": "" }
q49903
lazyLoad
train
function lazyLoad(enable, threshold) { if (enable != null) { _disableLazyLoading = !enable; } if (threshold != null) { _lazyLoadingThreshold = threshold; } return !_isCrawlerBotClient && !_disableLazyLoading; }
javascript
{ "resource": "" }
q49904
applyReplacementRules
train
function applyReplacementRules(rulesset, content) { return rulesset.reduce((a,b) => { return a.replace(b[0], b[1]); }, content); }
javascript
{ "resource": "" }
q49905
normalize
train
function normalize(content) { if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.normalize.'); return ''; } const result = content .replace(/\u200B/g, '') .replace(brakePointRegex, (m, g1, g2) => { let chunk = g1 || ''; // Re-ordering uniquify(g2) .sort((a,b) => rankingMap[a] - rankingMap[b]) .forEach((v) => chunk += v); return applyReplacementRules(extendedRules, chunk); }); return applyReplacementRules(postExtendedRules, result); }
javascript
{ "resource": "" }
q49906
spellingFix
train
function spellingFix(content, fontType){ if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.spellingFix.'); return ''; } if (content === '' || !mmCharacterRange.test(content)) return content; if (!fontType) fontType = fontDetect(content); content = content.trim().replace(/\u200B/g, ''); switch (fontType) { case 'zawgyi': for (var i = 0; i < library.spellingFix.zawgyi.length; i++) { var rule = library.spellingFix.zawgyi[i]; content = content.replace(rule[0], rule[1]); } return content; case 'unicode': default: for (var i = 0; i < library.spellingFix.unicode.length; i++) { var rule = library.spellingFix.unicode[i]; content = content.replace(rule[0], rule[1]); } return content; } }
javascript
{ "resource": "" }
q49907
fontDetect
train
function fontDetect(content, fallback_font_type, options = {}){ if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.fontDetect.'); return fallback_font_type || 'en'; } if (content === '') return content; if (!mmCharacterRange.test(content)) return fallback_font_type || 'en'; content = content.trim().replace(/\u200B/g, ''); fallback_font_type = fallback_font_type || 'zawgyi'; options = globalOptions.detector(options); if (options.use_myanmartools) { var myanmartools_zg_probability = myanmartoolZawgyiDetector.getZawgyiProbability(content); if (myanmartools_zg_probability < options.myanmartools_zg_threshold[0]) { return 'unicode'; } else if (myanmartools_zg_probability > options.myanmartools_zg_threshold[1]) { return 'zawgyi'; } else { return fallback_font_type; } } else { var match = {}; for (var type in library.detect) { match[type] = 0; for (var i = 0; i < library.detect[type].length; i++) { var rule = library.detect[type][i] var m = content.match(rule); match[type] += (m && m.length) || 0; } } if (match.unicode > match.zawgyi) { return 'unicode'; } else if (match.unicode < match.zawgyi) { return 'zawgyi'; } else { return fallback_font_type; } } }
javascript
{ "resource": "" }
q49908
syllBreak
train
function syllBreak(content, fontType, breakpoint){ if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.syllBreak.'); return ''; } if (content === '' || !mmCharacterRange.test(content)) return content; content = content.trim().replace(/\u200B/g, ''); if (!fontType) fontType = fontDetect(content); var lib = library.syllable[fontType]; for (var i = 0; i < lib.length; i++) { content = content.replace(lib[i][0], lib[i][1]); }; content = content.replace(/^\u200B/, ''); if (breakpoint && breakpoint !== '\u200B') return content.replace(/\u200B/g, breakpoint); return content }
javascript
{ "resource": "" }
q49909
fontConvert
train
function fontConvert(content, to, from) { if (!content) { if (!globalOptions.isSilentMode()) console.warn('Content must be specified on knayi.fontConvert.'); return ''; } if (content === '' || !mmCharacterRange.test(content)) return content; if (!to) { if (!globalOptions.isSilentMode()) console.error('Convert target font must be specified on knayi.fontConvert.'); return content; } content = content.trim().replace(/\u200B/g, ''); to = fontTypes[to]; from = fontTypes[from]; if (!to) { if (!globalOptions.isSilentMode()) console.error('Convert library dosen\'t have this fontType.') return content; } else if (!from) { from = fontDetect(content); } if (to === from) { return content; } var debug_logs = { to: to, from: from, matched_patterns: [], steps: [] } content = spellingFix(content, from); var refLib = library.convert[from][to]; for (var i = 0; i < refLib.oneTime.length; i++) { var rule1 = refLib.oneTime[i]; // debugging if (this.debug && rule1[0].test(content)) { debug_logs.matched_patterns.push(rule1); debug_logs.steps.push(content); } content = content.replace(rule1[0], rule1[1]); } for (var j = 0; j < refLib.asLongAsMatch.length; j++) { var rule2 = refLib.asLongAsMatch[j]; // debugging if (this.debug && rule2[0].test(content)) { debug_logs.matched_patterns.push(rule2); debug_logs.steps.push(content); } while (rule2[0].test(content)) { content = content.replace(rule2[0], rule2[1]); } } if (this.debug) { // final debug_logs.steps.push(content); return debug_logs; } return content; }
javascript
{ "resource": "" }
q49910
compileFile
train
function compileFile(file, src) { var compiled; compiled = compile(file, src, exports.traceurOverrides); if (compiled.error) throw new Error(compiled.error); return compiled.source; }
javascript
{ "resource": "" }
q49911
Tree
train
function Tree(left, label, right) { this.left = left; this.label = label; this.right = right; }
javascript
{ "resource": "" }
q49912
make
train
function make(array) { // Leaf node: if (array.length == 1) return new Tree(null, array[0], null); return new Tree(make(array[0]), array[1], make(array[2])); }
javascript
{ "resource": "" }
q49913
checkAvailable
train
function checkAvailable(host, port) { return new Promise(function(resolve, reject) { const socket = new net.Socket(); socket.on('connect', () => { cleanupSocket(socket); resolve(true); }); socket.on('error', err => { cleanupSocket(socket); if (err.code !== 'ECONNREFUSED') { return reject(err); } resolve(false); }); socket.connect({ port: port, host: host }); }); }
javascript
{ "resource": "" }
q49914
waitForAvailable
train
function waitForAvailable(host, port, options) { return co(function*() { options = Object.assign( {}, { initialMS: 300, retryMS: 100, retryCount: 25 }, options ); // Delay initial amount before attempting to connect yield delay(options.initialMS); // Try up to a certain number of times to connect for (var i = 0; i < options.retryCount; i++) { // Attempt to connect, returns true/false var available = yield checkAvailable(host, port); // If connected then return if (available) return; // Otherwise delay the retry amount and try again yield delay(options.retryMS); } // If this is reached then unable to connect throw new Error('Server is unavailable'); }); }
javascript
{ "resource": "" }
q49915
train
function(className, options) { if (!(this instanceof Logger)) return new Logger(className, options); options = options || {}; // Current reference this.className = className; // Current logger if (currentLogger == null && options.logger) { currentLogger = options.logger; } else if (currentLogger == null) { currentLogger = console.log; } // Set level of logging, default is error if (level == null) { level = options.loggerLevel || 'error'; } // Add all class names if (filteredClasses[this.className] == null) classFilters[this.className] = true; }
javascript
{ "resource": "" }
q49916
loadScript
train
function loadScript(options, cb) { if (!options) { throw new Error('Can\'t load nothing...'); } // Allow for the simplest case, just passing a `src` string. if (type(options) === 'string') { options = { src : options }; } var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:'; // If you use protocol relative URLs, third-party scripts like Google // Analytics break when testing with `file:` so this fixes that. if (options.src && options.src.indexOf('//') === 0) { options.src = (https ? 'https:' : 'http:') + options.src; } // Allow them to pass in different URLs depending on the protocol. if (https && options.https) { options.src = options.https; } else if (!https && options.http) { options.src = options.http; } // Make the `<script>` element and insert it before the first script on the // page, which is guaranteed to exist since this Javascript is running. var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = options.src; // If we have a cb, attach event handlers. Does not work on < IE9 because // older browser versions don't register element.onerror if (type(cb) === 'function') { onload(script, cb); } tick(function() { // Append after event listeners are attached for IE. var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); }); // Return the script element in case they want to do anything special, like // give it an ID or attributes. return script; }
javascript
{ "resource": "" }
q49917
transformer
train
function transformer(tree, file, next) { if (loadError) { next(loadError) } else if (config.checker) { all(tree, file, config) next() } else { queue.push([tree, file, config, next]) } }
javascript
{ "resource": "" }
q49918
all
train
function all(tree, file, config) { var ignore = config.ignore var ignoreLiteral = config.ignoreLiteral var ignoreDigits = config.ignoreDigits var apos = config.normalizeApostrophes var checker = config.checker var cache = config.cache visit(tree, 'WordNode', checkWord) // Check one word. function checkWord(node, position, parent) { var children = node.children var word = toString(node) var correct var length var index var child var reason var message var suggestions if (ignoreLiteral && isLiteral(parent, position)) { return } if (apos) { word = word.replace(smart, straight) } if (irrelevant(word)) { return } correct = checker.correct(word) if (!correct && children.length > 1) { correct = true length = children.length index = -1 while (++index < length) { child = children[index] if (child.type !== 'TextNode' || irrelevant(child.value)) { continue } if (!checker.correct(child.value)) { correct = false } } } if (!correct) { if (own.call(cache, word)) { reason = cache[word] } else { reason = quote(word, '`') + ' is misspelt' if (config.count === config.max) { message = file.message( 'Too many misspellings; no further spell suggestions are given', node, 'overflow' ) message.source = source } config.count++ if (config.count < config.max) { suggestions = checker.suggest(word) if (suggestions.length !== 0) { reason += '; did you mean ' + quote(suggestions, '`').join(', ') + '?' cache[word] = reason } } cache[word] = reason } message = file.message(reason, node, source) message.source = source message.actual = word message.expected = suggestions } } // Check if a word is irrelevant. function irrelevant(word) { return includes(ignore, word) || (ignoreDigits && digitsOnly.test(word)) } }
javascript
{ "resource": "" }
q49919
clone
train
function clone(a) { var out = new Float32Array(3) out[0] = a[0] out[1] = a[1] out[2] = a[2] return out }
javascript
{ "resource": "" }
q49920
rotateX
train
function rotateX(out, a, b, c){ var by = b[1] var bz = b[2] // Translate point to the origin var py = a[1] - by var pz = a[2] - bz var sc = Math.sin(c) var cc = Math.cos(c) // perform rotation and translate to correct position out[0] = a[0] out[1] = by + py * cc - pz * sc out[2] = bz + py * sc + pz * cc return out }
javascript
{ "resource": "" }
q49921
rotateZ
train
function rotateZ(out, a, b, c){ var bx = b[0] var by = b[1] //Translate point to the origin var px = a[0] - bx var py = a[1] - by var sc = Math.sin(c) var cc = Math.cos(c) // perform rotation and translate to correct position out[0] = bx + px * cc - py * sc out[1] = by + px * sc + py * cc out[2] = a[2] return out }
javascript
{ "resource": "" }
q49922
negate
train
function negate(out, a) { out[0] = -a[0] out[1] = -a[1] out[2] = -a[2] return out }
javascript
{ "resource": "" }
q49923
rotateY
train
function rotateY(out, a, b, c){ var bx = b[0] var bz = b[2] // translate point to the origin var px = a[0] - bx var pz = a[2] - bz var sc = Math.sin(c) var cc = Math.cos(c) // perform rotation and translate to correct position out[0] = bx + pz * sc + px * cc out[1] = a[1] out[2] = bz + pz * cc - px * sc return out }
javascript
{ "resource": "" }
q49924
inverse
train
function inverse(out, a) { out[0] = 1.0 / a[0] out[1] = 1.0 / a[1] out[2] = 1.0 / a[2] return out }
javascript
{ "resource": "" }
q49925
angle
train
function angle(a, b) { var tempA = fromValues(a[0], a[1], a[2]) var tempB = fromValues(b[0], b[1], b[2]) normalize(tempA, tempA) normalize(tempB, tempB) var cosine = dot(tempA, tempB) if(cosine > 1.0){ return 0 } else { return Math.acos(cosine) } }
javascript
{ "resource": "" }
q49926
se
train
function se(me){/* jshint maxstatements: 18 */if(!(this instanceof se))return new se(me);var ge={};if(fe.isBuffer(me))ge=se._fromBufferReader(le(me));else if(de.isObject(me)){var _e;_e=me.header instanceof ce?me.header:ce.fromObject(me.header),ge={/** * @name MerkleBlock#header * @type {BlockHeader} */header:_e,/** * @name MerkleBlock#numTransactions * @type {Number} */numTransactions:me.numTransactions,/** * @name MerkleBlock#hashes * @type {String[]} */hashes:me.hashes,/** * @name MerkleBlock#flags * @type {Number[]} */flags:me.flags}}else throw new TypeError("Unrecognized argument for MerkleBlock");return de.extend(this,ge),this._flagBitsUsed=0,this._hashesUsed=0,this}
javascript
{ "resource": "" }
q49927
he
train
function he(vr,xr,Sr){for(var kr=-1,Ir=vr.criteria,Ar=xr.criteria,wr=Ir.length,Er=Sr.length,Pr;++kr<wr;)if(Pr=se(Ir[kr],Ar[kr]),Pr){if(kr>=Er)return Pr;var Br=Sr[kr];return Pr*("asc"===Br||!0===Br?1:-1)}// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://code.google.com/p/v8/issues/detail?id=90 for more details. return vr.index-xr.index}
javascript
{ "resource": "" }
q49928
uo
train
function uo(Kd,qd,Vd,Gd,Yd,Wd,Xd,Jd,Zd,Qd){function $d(){for(// Avoid `arguments` object use disqualifying optimizations by // converting it to an array before providing it to other functions. var dc=arguments.length,fc=dc,lc=Zn(dc);fc--;)lc[fc]=arguments[fc];if(Gd&&(lc=Da(lc,Gd,Yd)),Wd&&(lc=Ma(lc,Wd,Xd)),oc||ic){var pc=$d.placeholder,uc=Ae(lc,pc);if(dc-=uc.length,dc<Qd){var bc=Jd?Br(Jd):Te,hc=Gi(Qd-dc,0),mc=oc?uc:Te,gc=oc?Te:uc,_c=oc?lc:Te,vc=oc?Te:lc;qd|=oc?ze:De,qd&=~(oc?De:ze),nc||(qd&=~(Oe|Ce));var Sc=[Kd,qd,Vd,_c,mc,vc,gc,bc,Zd,hc],kc=uo.apply(Te,Sc);return Lo(Kd)&&gs(kc,Sc),kc.placeholder=pc,kc}}var Ic=rc?Vd:this,Ac=ac?Ic[Kd]:Kd;return Jd&&(lc=Ko(lc,Jd)),tc&&Zd<lc.length&&(lc.length=Zd),this&&this!==gr&&this instanceof $d&&(Ac=sc||Ya(Kd)),Ac.apply(Ic,lc)}var tc=qd&Me,rc=qd&Oe,ac=qd&Ce,oc=qd&je,nc=qd&Ne,ic=qd&Le,sc=ac?Te:Ya(Kd);return $d}
javascript
{ "resource": "" }
q49929
ho
train
function ho(Kd,qd,Vd,Gd){function Yd(){for(// Avoid `arguments` object use disqualifying optimizations by // converting it to an array before providing it `func`. var Xd=-1,Jd=arguments.length,Zd=-1,Qd=Gd.length,$d=Zn(Qd+Jd);++Zd<Qd;)$d[Zd]=Gd[Zd];for(;Jd--;)$d[Zd++]=arguments[++Xd];var tc=this&&this!==gr&&this instanceof Yd?Wd:Kd;return tc.apply(qd&Oe?Vd:this,$d)}var Wd=Ya(Kd);return Yd}
javascript
{ "resource": "" }
q49930
be
train
function be(Ce,Ne,je){je.negative=Ne.negative^Ce.negative;var Le=0|Ce.length+Ne.length;je.length=Le,Le=0|Le-1;// Peel one iteration (compiler can't do it, because of code complexity) var ze=0|Ce.words[0],De=0|Ne.words[0],Me=ze*De,Ue=67108863&Me,Fe=0|Me/67108864;je.words[0]=Ue;for(var He=1;He<Le;He++){for(var Ke=Fe>>>26,qe=67108863&Fe,Ve=Math.min(He,Ne.length-1),Ge=Math.max(0,He-Ce.length+1),Ye;Ge<=Ve;Ge++)Ye=0|He-Ge,ze=0|Ce.words[Ye],De=0|Ne.words[Ge],Me=ze*De+qe,Ke+=0|Me/67108864,qe=67108863&Me;// Sum all words with the same `i + j = k` and accumulate `ncarry`, // note that ncarry could be >= 0x3ffffff je.words[He]=0|qe,Fe=0|Ke}return 0==Fe?je.length--:je.words[He]=0|Fe,je.strip()}
javascript
{ "resource": "" }
q49931
train
function(Se){// Spawn var ke=ce(this);// Augment return Se&&ke.mixIn(Se),ke.hasOwnProperty("init")&&this.init!==ke.init||(ke.init=function(){ke.$super.init.apply(this,arguments)}),ke.init.prototype=ke,ke.$super=this,ke}
javascript
{ "resource": "" }
q49932
train
function(Se){// Convert for(var ke=Se.length,Ie=[],Ae=0;Ae<ke;Ae++)Ie[Ae>>>2]|=(255&Se.charCodeAt(Ae))<<24-8*(Ae%4);// Shortcut return new ue.init(Ie,ke)}
javascript
{ "resource": "" }
q49933
train
function(pe){// Shortcuts var ue=pe.words,be=pe.sigBytes,he=this._map;pe.clamp();for(var me=[],ge=0;ge<be;ge+=3)for(var _e=255&ue[ge>>>2]>>>24-8*(ge%4),ve=255&ue[ge+1>>>2]>>>24-8*((ge+1)%4),Se=255&ue[ge+2>>>2]>>>24-8*((ge+2)%4),ke=0;4>ke&&ge+0.75*ke<be;ke++)me.push(he.charAt(63&(_e<<16|ve<<8|Se)>>>6*(3-ke)));// Add padding var Ie=he.charAt(64);if(Ie)for(;me.length%4;)me.push(Ie);return me.join("")}
javascript
{ "resource": "" }
q49934
train
function(pe){// Shortcuts var ue=pe.length,be=this._map,he=this._reverseMap;if(!he){he=this._reverseMap=[];for(var me=0;me<be.length;me++)he[be.charCodeAt(me)]=me}// Ignore padding var ge=be.charAt(64);if(ge){var _e=pe.indexOf(ge);-1!==_e&&(ue=_e)}// Convert return se(pe,ue,he)}
javascript
{ "resource": "" }
q49935
train
function(pe){// Convert for(var ue=pe.length,be=[],he=0;he<ue;he++)be[he>>>1]|=pe.charCodeAt(he)<<16-16*(he%2);// Shortcut return fe.create(be,2*ue)}
javascript
{ "resource": "" }
q49936
train
function(ue){// Shortcut var be=this._hasher,he=be.finalize(ue);// Compute HMAC be.reset();var me=be.finalize(this._oKey.clone().concat(he));return me}
javascript
{ "resource": "" }
q49937
me
train
function me(Me){// Don't use UCS-2 var Ue=[],Fe=Me.length,Ke=0,qe=Be,Ve=Pe,He,Ge,Ye,We,Xe,Je,Ze,Qe,$e,/** Cached calculation results */et;// Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. for(Ge=Me.lastIndexOf(Re),0>Ge&&(Ge=0),Ye=0;Ye<Ge;++Ye)128<=Me.charCodeAt(Ye)&&de("not-basic"),Ue.push(Me.charCodeAt(Ye));// Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for(We=0<Ge?Ge+1:0;We<Fe;)/* no final expression */{// `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for(Xe=Ke,Je=1,Ze=Ae;;/* no condition */Ze+=Ae){if(We>=Fe&&de("invalid-input"),Qe=ue(Me.charCodeAt(We++)),(Qe>=Ae||Qe>Le((Ie-Ke)/Je))&&de("overflow"),Ke+=Qe*Je,$e=Ze<=Ve?we:Ze>=Ve+Ee?Ee:Ze-Ve,Qe<$e)break;et=Ae-$e,Je>Le(Ie/et)&&de("overflow"),Je*=et}He=Ue.length+1,Ve=he(Ke-Xe,He,0==Xe),Le(Ke/He)>Ie-qe&&de("overflow"),qe+=Le(Ke/He),Ke%=He,Ue.splice(Ke++,0,qe)}return pe(Ue)}
javascript
{ "resource": "" }
q49938
de
train
function de(Me,Ue){// default options var Fe={seen:[],stylize:fe};// legacy... return 3<=arguments.length&&(Fe.depth=arguments[2]),4<=arguments.length&&(Fe.colors=arguments[3]),ve(Ue)?Fe.showHidden=Ue:Ue&&te._extend(Fe,Ue),Ae(Fe.showHidden)&&(Fe.showHidden=!1),Ae(Fe.depth)&&(Fe.depth=2),Ae(Fe.colors)&&(Fe.colors=!1),Ae(Fe.customInspect)&&(Fe.customInspect=!0),Fe.colors&&(Fe.stylize=ce),pe(Fe,Me,Fe.depth)}
javascript
{ "resource": "" }
q49939
train
function(proxy_address, signer, controller_address) { this.proxy_address = proxy_address; this.controller_address = controller_address || proxy_address; this.signer = signer; }
javascript
{ "resource": "" }
q49940
uint16BEtoNumber
train
function uint16BEtoNumber(bytes) { var n = 0; for (var i = 0; i < 1; i++) { n |= bytes[i]; n <<= 8; } n |= bytes[1]; return n; }
javascript
{ "resource": "" }
q49941
readNumber
train
function readNumber(bf, numfmt) { var value = new Uint8Array(bf); if (numfmt === NUMFMT_UINT32) { // uint32 return uint32BEtoNumber(value); } else if (numfmt === NUMFMT_UINT64) { // uint64 return uint64BEtoNumber(value); } else if (numfmt === NUMFMT_UINT16) { // uint16 return uint16BEtoNumber(value); } else if (numfmt === NUMFMT_UINT8) { // uint8 return uint8BEtoNumber(value); } return 0; // return struct.unpack(this._number_format, bf)[0]; }
javascript
{ "resource": "" }
q49942
appendBuffer
train
function appendBuffer(buffer1, buffer2) { var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength); tmp.set(new Uint8Array(buffer1), 0); tmp.set(new Uint8Array(buffer2), buffer1.byteLength); return tmp.buffer; }
javascript
{ "resource": "" }
q49943
concat
train
function concat(a, b) { if (!a && !b) throw new Error("Please specify valid arguments for parameters a and b."); if (!b || b.length === 0) return a; if (!a || a.length === 0) return b; const c = new a.constructor(a.length + b.length); c.set(a); c.set(b, a.length); return c; }
javascript
{ "resource": "" }
q49944
Name
train
function Name() { /** * The prefix value * @member */ this.prefix = null; /** * The first value * @member */ this.first = null; /** * The middle value * @member */ this.middle = null; /** * The last value * @member */ this.last = null; /** * The suffix value * @member */ this.suffix = null; }
javascript
{ "resource": "" }
q49945
Customer
train
function Customer() { /** * The contactId value * @member */ this.contactId = null; /** * The isGuest value * @member */ this.isGuest = null; /** * The name of value * @member * @type { Name } */ this.name = Object.create(Name.prototype); /** * The phone value * @member */ this.phone = null; /** * The email value * @member */ this.email = null; }
javascript
{ "resource": "" }
q49946
HotelPurchaseFailedSchema
train
function HotelPurchaseFailedSchema() { /** * The reservationId value * @member */ this.reservationId = null; /** * The guests of value * @member * @type { Guests } */ this.guests = Object.create(Guests.prototype); /** * The stay of value * @member * @type { Stay } */ this.stay = Object.create(Stay.prototype); /** * The payment of value * @member * @type { Payment } */ this.payment = Object.create(Payment.prototype); /** * The customer of value * @member * @type { Customer } */ this.customer = Object.create(Customer.prototype); }
javascript
{ "resource": "" }
q49947
train
function(instance, secret, validator) { // spilt the instance into signature and data if (instance === null || typeof secret !== 'string' || instance.split('.').length !== 2) { throw { name: "WixSignatureException", message: "Missing instance or secret key" } } var pair = instance.split('.'); var signature = new Buffer(pair[0], 'base64'); // sign the data using hmac-sha1-256 var data = pair[1]; var newSignature = signData(secret, data); if (toBase64Safe(signature) !== newSignature.toString()) { throw { name: "WixSignatureException", message: "Signatures do not match, requester is most likely not Wix" }; } var jsonData = JSON.parse(new Buffer(fromBase64Safe(data), 'base64').toString('utf8')); if (typeof validator !== 'function') { validator = function (date) { return (Date.now() - date.getTime()) <= (1000 * 60 * 60 * 24 * 2); // 2 days }; } if (validator(new Date(jsonData.signDate))) { return jsonData; } throw { name: "WixSignatureException", message: "Signatures date has expired" }; }
javascript
{ "resource": "" }
q49948
Recipient
train
function Recipient() { /** * The method value * @member */ this.method = null; /** * The destination of value * @member * @type { Destination } */ this.destination = Object.create(Destination.prototype); /** * The contactId value * @member */ this.contactId = null; }
javascript
{ "resource": "" }
q49949
SendSchema
train
function SendSchema() { /** * The recipient of value * @member * @type { Recipient } */ this.recipient = Object.create(Recipient.prototype); /** * The messageId value * @member */ this.messageId = null; /** * The conversionTarget of value * @member * @type { ConversionTarget } */ this.conversionTarget = Object.create(ConversionTarget.prototype); }
javascript
{ "resource": "" }
q49950
HotelConfirmationSchema
train
function HotelConfirmationSchema() { /** * The source value * @member */ this.source = null; /** * The reservationId value * @member */ this.reservationId = null; /** * The guests of value * @member * @type { Guests } */ this.guests = Object.create(Guests.prototype); /** * The stay of value * @member * @type { Stay } */ this.stay = Object.create(Stay.prototype); /** * The invoice of value * @member * @type { Invoice } */ this.invoice = Object.create(Invoice.prototype); /** * The customer of value * @member * @type { Customer } */ this.customer = Object.create(Customer.prototype); }
javascript
{ "resource": "" }
q49951
TrackPlaySchema
train
function TrackPlaySchema() { /** * The track of value * @member * @type { Track } */ this.track = Object.create(Track.prototype); /** * The album of value * @member * @type { Album } */ this.album = Object.create(Album.prototype); }
javascript
{ "resource": "" }
q49952
TrackShareSchema
train
function TrackShareSchema() { /** * The track of value * @member * @type { Track } */ this.track = Object.create(Track.prototype); /** * The album of value * @member * @type { Album } */ this.album = Object.create(Album.prototype); /** * The sharedTo value * @member */ this.sharedTo = null; }
javascript
{ "resource": "" }
q49953
ItemsItem
train
function ItemsItem() { /** * The id value * @member */ this.id = null; /** * The sku value * @member */ this.sku = null; /** * The title value * @member */ this.title = null; /** * The quantity value * @member */ this.quantity = null; /** * The price value * @member */ this.price = null; /** * The formattedPrice value * @member */ this.formattedPrice = null; /** * The currency value * @member */ this.currency = null; /** * The productLink value * @member */ this.productLink = null; /** * The weight value * @member */ this.weight = null; /** * The formattedWeight value * @member */ this.formattedWeight = null; /** * The media of value * @member * @type { Media } */ this.media = Object.create(Media.prototype); }
javascript
{ "resource": "" }
q49954
BillingAddress
train
function BillingAddress() { /** * The firstName value * @member */ this.firstName = null; /** * The lastName value * @member */ this.lastName = null; /** * The email value * @member */ this.email = null; /** * The phone value * @member */ this.phone = null; /** * The country value * @member */ this.country = null; /** * The countryCode value * @member */ this.countryCode = null; /** * The region value * @member */ this.region = null; /** * The regionCode value * @member */ this.regionCode = null; /** * The city value * @member */ this.city = null; /** * The address1 value * @member */ this.address1 = null; /** * The address2 value * @member */ this.address2 = null; /** * The zip value * @member */ this.zip = null; /** * The company value * @member */ this.company = null; }
javascript
{ "resource": "" }
q49955
PurchaseSchema
train
function PurchaseSchema() { /** * The cartId value * @member */ this.cartId = null; /** * The storeId value * @member */ this.storeId = null; /** * The orderId value * @member */ this.orderId = null; /** * The payment of value * @member * @type { Payment } */ this.payment = Object.create(Payment.prototype); /** * The shippingAddress of value * @member * @type { ShippingAddress } */ this.shippingAddress = Object.create(ShippingAddress.prototype); /** * The billingAddress of value * @member * @type { BillingAddress } */ this.billingAddress = Object.create(BillingAddress.prototype); /** * The paymentGateway value * @member */ this.paymentGateway = null; /** * The note value * @member */ this.note = null; /** * The buyerAcceptsMarketing value * @member */ this.buyerAcceptsMarketing = null; }
javascript
{ "resource": "" }
q49956
TrackSkippedSchema
train
function TrackSkippedSchema() { /** * The track of value * @member * @type { Track } */ this.track = Object.create(Track.prototype); /** * The album of value * @member * @type { Album } */ this.album = Object.create(Album.prototype); }
javascript
{ "resource": "" }
q49957
AddressesItem
train
function AddressesItem() { /** * The tag value * @member */ this.tag = null; /** * The address value * @member */ this.address = null; /** * The neighborhood value * @member */ this.neighborhood = null; /** * The city value * @member */ this.city = null; /** * The region value * @member */ this.region = null; /** * The postalCode value * @member */ this.postalCode = null; /** * The country value * @member */ this.country = null; }
javascript
{ "resource": "" }
q49958
ContactCreateSchema
train
function ContactCreateSchema() { /** * The name of value * @member * @type { Name } */ this.name = Object.create(Name.prototype); /** * The picture value * @member */ this.picture = null; /** * The company of value * @member * @type { Company } */ this.company = Object.create(Company.prototype); }
javascript
{ "resource": "" }
q49959
WixPagingData
train
function WixPagingData(initialResult, wixApiCallback, dataHandler) { this.currentData = initialResult; if(dataHandler !== undefined && dataHandler !== null) { this.resultData = _.map(initialResult.results, function(elem) { return dataHandler(elem); }); } else { this.resultData = initialResult.results; } this.wixApiCallback = wixApiCallback; function canYieldData(data, mode) { if(data !== null) { var field = data.nextCursor; if(mode === 'previous') { field = data.previousCursor; } return field !== null && field !== 0; } return false; } /** * Determines if this cursor can yield additional data * @returns {boolean} */ this.hasNext = function() { return canYieldData(this.currentData, 'next'); }; /** * Determines if this cursor can yield previous data * @returns {boolean} */ this.hasPrevious = function() { return canYieldData(this.currentData, 'previous'); }; /** * Returns the next page of data for this paging collection * @returns {Promise.<WixPagingData, error>} */ this.next = function() { return this.wixApiCallback(this.currentData.nextCursor); }; /** * Returns the previous page of data for this paging collection * @returns {Promise.<WixPagingData, error>} */ this.previous = function() { return this.wixApiCallback(this.currentData.previousCursor); }; /** * Returns an array of items represented in this page of data * @returns {array} */ this.results = function() { return this.resultData; }; }
javascript
{ "resource": "" }
q49960
WixActivityData
train
function WixActivityData() { /** * Information about the Activity * @typedef {Object} WixActivityData.ActivityDetails * @property {?String} additionalInfoUrl Url linking to more specific contextual information about the activity for use in the Dashboard * @property {?string} summary A short description about the activity for use in the Dashboard */ /** * The id of the Activity * @member WixActivityData#id * @type {string} */ /** * A timestamp to indicate when this Activity took place * @member * @type {Date} */ this.createdAt = new Date().toISOString(); /** * The URL where the activity was performed * @member * @type {String} */ this.activityLocationUrl = null; /** * Information about the Activity * @member * @type {WixActivityData.ActivityDetails} */ this.activityDetails = {summary : null, additionalInfoUrl : null}; /** * The type of Activity * @member * @type {string} */ this.activityType = null; /** * Schema information about the Activity * @member * @type {Object} */ this.activityInfo = null; /** * @private */ this.init = function(obj) { this.activityType = { name: obj.activityType }; this.activityDetails = obj.activityDetails; this.activityInfo = obj.activityInfo; this.id = obj.id; this.activityLocationUrl = obj.activityLocationUrl; this.createdAt = obj.createdAt; return this; }; }
javascript
{ "resource": "" }
q49961
WixActivity
train
function WixActivity() { /** * Updates to the existing contact that performed this activity. The structure of this object should match the schema for Contact, with the relevant fields updated. * @member * @type {Object} */ this.contactUpdate = schemaFactory(this.TYPES.CONTACT_CREATE.name); /** * Configures this Activity with a given type * @param {ActivityType} type the type of the Activity to create * @returns {WixActivity} */ this.withActivityType = function(type) { this.activityType = type.name; this.activityInfo = schemaFactory(type.name); return this; }; /** * Configures the activityLocationUrl of this Activity * @param {string} url The URL of the Activities location * @returns {WixActivity} */ this.withLocationUrl = function(url) { this.activityLocationUrl = url; return this; }; /** * Configures the details of this Activity * @param {string} summary A summary of this Activity * @param {string} additionalInfoUrl a link to additional information about this Activity * @returns {WixActivity} */ this.withActivityDetails = function(summary, additionalInfoUrl) { if(summary !== null && summary !== undefined) { this.activityDetails.summary = summary; } if(additionalInfoUrl !== null && additionalInfoUrl !== undefined) { this.activityDetails.additionalInfoUrl = additionalInfoUrl; } return this; }; var readOnlyTypes = [ this.TYPES.CONTACT_CREATE.name ]; this.isWritable = function() { return (readOnlyTypes.indexOf(this.activityType) == -1); }; this.isValid = function() { //TODO provide slightly better validation return this.activityLocationUrl !== null && this.activityType !== null && this.activityDetails.summary !== null && this.createdAt !== null && this.activityDetails.additionalInfoUrl !== null; }; /** * Posts the Activity to Wix. Returns a Promise for an id * @param {string} sessionToken The current session token for the active Wix site visitor * @param {Wix} wix A Wix API object * @returns {Promise.<string, error>} A new id, or an error */ this.post = function(sessionToken, wix) { return wix.Activities.postActivity(this, sessionToken); }; function removeNulls(obj){ var isArray = obj instanceof Array; for (var k in obj){ if (obj[k]===null) isArray ? obj.splice(k,1) : delete obj[k]; else if (typeof obj[k]=="object") removeNulls(obj[k]); } } this.toJSON = function() { var _this = this; removeNulls(_this.contactUpdate); removeNulls(_this.activityInfo); return { createdAt : _this.createdAt, activityType : _this.activityType, contactUpdate : _this.contactUpdate, activityLocationUrl : _this.activityLocationUrl, activityDetails : _this.activityDetails, activityInfo: _this.activityInfo }; }; }
javascript
{ "resource": "" }
q49962
Name
train
function Name(obj){ this._prefix = obj && obj.prefix; this._first = obj && obj.first; this._last = obj && obj.last; this._middle = obj && obj.middle; this._suffix = obj && obj.suffix; }
javascript
{ "resource": "" }
q49963
Company
train
function Company(obj){ this._role = obj && obj.role; this._name = obj && obj.name; }
javascript
{ "resource": "" }
q49964
Email
train
function Email(obj){ this._id = obj && obj.id; this._tag = obj && obj.tag; this._email = obj && obj.email; this._emailStatus = obj && obj.emailStatus; if (this._tag == undefined || this._tag == null){ throw 'Tag is a required field' } if (this._email == undefined || this._email == null){ throw 'Email is a required field' } }
javascript
{ "resource": "" }
q49965
Phone
train
function Phone(obj){ this._id = obj && obj.id; this._tag = obj && obj.tag; this._phone = obj && obj.phone; this._normalizedPhone = obj && obj.normalizedPhone; }
javascript
{ "resource": "" }
q49966
Address
train
function Address(obj){ this._id = obj && obj.id; this._tag = obj && obj.tag; this._address = obj && obj.address; this._city = obj && obj.city; this._neighborhood = obj && obj.neighborhood; this._region = obj && obj.region; this._country = obj && obj.country; this._postalCode = obj && obj.postalCode; }
javascript
{ "resource": "" }
q49967
Url
train
function Url(obj){ this._id = obj && obj.id; this._tag = obj && obj.tag; this._url = obj && obj.url; }
javascript
{ "resource": "" }
q49968
StateLink
train
function StateLink(obj){ this._id = obj && obj.id; this._href = obj && obj.href; this._rel = obj && obj.rel; }
javascript
{ "resource": "" }
q49969
ImportantDate
train
function ImportantDate(obj){ this._id = obj && obj.id; this._tag = obj && obj.tag; this._date = obj && obj.date; }
javascript
{ "resource": "" }
q49970
Note
train
function Note(obj){ this._id = obj && obj.id; this._modifiedAt = obj && obj.modifiedAt; this._content = obj && obj.content; }
javascript
{ "resource": "" }
q49971
WixLabelData
train
function WixLabelData() { /** * The id of the Label * @member WixLabelData#id * @type {string} */ /** * A timestamp to indicate when this Label was created * @member * @type {Date} */ this.createdAt = new Date().toISOString(); /** * Label name * @member * @type {String} */ this.name = null; /** * Label description * @member * @type {String} */ this.description = null; /** * Label totalMembers * @member * @type {Number} */ this.totalMembers = null; /** * Label labelType * @member * @type {String} */ this.labelType = null; /** * @private */ this.init = function(obj) { this.id = obj.id; this.name = obj.name; this.description = obj.description; this.totalMembers = obj.totalMembers; this.labelType = obj.labelType; this.createdAt = obj.createdAt; return this; }; }
javascript
{ "resource": "" }
q49972
WixLabel
train
function WixLabel() { this.isValid = function() { //TODO provide slightly better validation return this.name !== null && this.description !== null; }; this.toJSON = function() { var _this = this; return { name : _this.name, description : _this.description }; }; }
javascript
{ "resource": "" }
q49973
APIBuilder
train
function APIBuilder() { /** * Creates a {@link Wix} API object with the give credentials. * @method * @param {APIBuilder.APICredentials} data JSON data containing credentials for the API * @throws an exception if signatures don't match when using the API with the instance param * @throws an exception if API credentials are missing * @returns {Wix} a Wix API interface object */ this.withCredentials = function(data) { if(!data.hasOwnProperty('secretKey')) { throwMissingValue('secretKey'); } if(!data.hasOwnProperty('appId')) { throwMissingValue('appId') } if(!data.hasOwnProperty('instanceId') && !data.hasOwnProperty('instance')) { throwMissingValue('instanceId or instance') } var i = null; if(data.hasOwnProperty('instanceId')) { i = data.instanceId; } else { i = wixconnect.parseInstance(data.instance, data.secretKey).instanceId; } return new Wix(data.secretKey, data.appId, i); }; }
javascript
{ "resource": "" }
q49974
TrackPlayedSchema
train
function TrackPlayedSchema() { /** * The track of value * @member * @type { Track } */ this.track = Object.create(Track.prototype); /** * The album of value * @member * @type { Album } */ this.album = Object.create(Album.prototype); }
javascript
{ "resource": "" }
q49975
train
function(client, key, ttl) { client.ttl(key, function(err, currentTtl) { if (currentTtl === -1) { // There is no expiry set on this key, set it client.expire(key, ttl); } }); }
javascript
{ "resource": "" }
q49976
train
function(callback) { crypto.randomBytes(16, function(err, buffer) { if (err) { return callback(err); } return callback(null, buffer.toString('base64')); }); }
javascript
{ "resource": "" }
q49977
encode
train
function encode (data, buffer, offset) { var buffers = [] var result = null encode._encode(buffers, data) result = Buffer.concat(buffers) encode.bytes = result.length if (Buffer.isBuffer(buffer)) { result.copy(buffer, offset) return buffer } return result }
javascript
{ "resource": "" }
q49978
decode
train
function decode (data, start, end, encoding) { if (data == null || data.length === 0) { return null } if (typeof start !== 'number' && encoding == null) { encoding = start start = undefined } if (typeof end !== 'number' && encoding == null) { encoding = end end = undefined } decode.position = 0 decode.encoding = encoding || null decode.data = !(Buffer.isBuffer(data)) ? Buffer.from(data) : data.slice(start, end) decode.bytes = decode.data.length return decode.next() }
javascript
{ "resource": "" }
q49979
copyFile
train
function copyFile (src, dest, ncpOpts, callback) { var orchestrator = new Orchestrator(); var parts = dest.split(path.sep); var fileName = parts.pop(); var destDir = parts.join(path.sep); var destFile = path.resolve(destDir, fileName); orchestrator.add('ensureDir', function (done) { mkdirp(destDir, function (err) { done(err); }); }); orchestrator.add('copyFile', ['ensureDir'], function (done) { ncp(src, destFile, ncpOpts, function (err) { done(err); }); }); orchestrator.start('copyFile', function (err) { callback(err); }); }
javascript
{ "resource": "" }
q49980
train
function (filename) { var contents = fs.readFileSync(filename, 'utf-8'); if(contents) { //Windows is the BOM. Skip the Byte Order Mark. contents = contents.substring(contents.indexOf('<')); } return new et.ElementTree(et.XML(contents)); }
javascript
{ "resource": "" }
q49981
carbonReporter
train
async function carbonReporter (registry, tags) { const { CarbonMetricReporter } = require('inspector-carbon') const reporter = new CarbonMetricReporter({ host: 'http://localhost/', log: null, minReportingTimeout: 30, reportInterval: 5000 }) reporter.setTags(tags) reporter.addMetricRegistry(registry) await reporter.start() return reporter }
javascript
{ "resource": "" }
q49982
getEnrichedConfig
train
function getEnrichedConfig(rule, config) { if (!config) { return rule; } if (config.include) { rule.include = config.include; } if (config.exclude) { rule.exclude = config.exclude; } return rule; }
javascript
{ "resource": "" }
q49983
getViewCombinations
train
function getViewCombinations(action) { const pathes = [action]; const positions = []; let i; let j; for (i = 0; i < action.length; i++) { if (action[i] === '-') { positions.push(i); } } const len = positions.length; const combinations = []; for (i = 1; i < (1 << len); i++) { const c = []; for (j = 0; j < len; j++) { if (i & (1 << j)) { c.push(positions[j]); } } combinations.push(c); } combinations.forEach((combination) => { let combinationPath = action; combination.forEach((pos) => { combinationPath = replaceAt(combinationPath, pos, '/'); }); pathes.push(combinationPath); }); return pathes; }
javascript
{ "resource": "" }
q49984
pathname
train
function pathname (routename, isElectron) { if (isElectron) routename = routename.replace(stripElectron, '') else routename = routename.replace(prefix, '') return decodeURI(routename.replace(suffix, '').replace(normalize, '/')) }
javascript
{ "resource": "" }
q49985
prepare
train
function prepare (binary, include = {memory: true, table: true}, symbol = '_') { return inject(binary, include, symbol) }
javascript
{ "resource": "" }
q49986
hibernate
train
function hibernate (instance, symbol = '_') { const json = { globals: [], table: [], symbol } for (const key in instance.exports) { const val = instance.exports[key] if (key.startsWith(symbol)) { const keyElems = key.slice(symbol.length).split('_') // save the memory if (val instanceof WebAssembly.Memory) { json.memory = new Uint32Array(val.buffer) } else if (val instanceof WebAssembly.Table) { // mark the tables, (do something for external function?) // the external functions should have a callback for (let i = 0; i < val.length; i++) { const func = val.get(i) if (func === instance.exports[`${symbol}func_${func.name}`]) { json.table.push(func.name) } } } else if (keyElems[0] === 'global' && keyElems[1] === 'getter') { // save the globals const last = keyElems.pop() if (last === 'high') { json.globals.push([instance.exports[key]()]) } else if (last === 'low') { json.globals[json.globals.length - 1].push(instance.exports[key]()) } else { json.globals.push(instance.exports[key]()) } } } } instance.__hibernated = true return json }
javascript
{ "resource": "" }
q49987
resume
train
function resume (instance, state) { if (instance.__hibernated) { instance.__hibernated = false } else { // initialize memory const mem = instance.exports[`${state.symbol}memory`] if (mem) { (new Uint32Array(mem.buffer)).set(state.memory, 0) } // initialize table if (instance.exports._table) { for (const index in state.table) { const funcIndex = state.table[index] instance.exports._table.set(index, instance.exports[`${state.symbol}func_${funcIndex}`]) } } // initialize globals for (const index in state.globals) { const val = state.globals[index] if (val !== undefined) { if (Array.isArray(val)) { instance.exports[`${state.symbol}global_setter_i64_${index}`](val[1], val[0]) } else { instance.exports[`${state.symbol}global_setter_i32_${index}`](val) } } } } return instance }
javascript
{ "resource": "" }
q49988
encodeBuffer
train
function encodeBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var data = packet.data; var typeBuffer = new Buffer(1); typeBuffer[0] = packets[packet.type]; return callback(Buffer.concat([typeBuffer, data])); }
javascript
{ "resource": "" }
q49989
map
train
function map(ary, each, done) { var result = new Array(ary.length); var next = after(ary.length, done); for (var i = 0; i < ary.length; i++) { each(ary[i], function(error, msg) { result[i] = msg; next(error, result); }); } }
javascript
{ "resource": "" }
q49990
parseJSON
train
function parseJSON(data) { var oData; try { oData = JSON.parse(data); } catch (e) { return false; } return oData; }
javascript
{ "resource": "" }
q49991
WebViewInterface
train
function WebViewInterface(webView) { /** * WebView to setup interface for */ this.webView = webView; /** * Mapping of webView event/command and its native handler */ this.eventListenerMap = {}; /** * Mapping of js call request id and its success handler. * Based on this mapping, the registered success handler will be called * on successful response from the js call */ this.jsCallReqIdSuccessCallbackMap = {}; /** * Mapping of js call request id and its error handler. * Based on this mapping, the error handler will be called * on error from the js call */ this.jsCallReqIdErrorCallbackMap = {}; /** * Web-view instance unique id to handle scenarios of multiple webview on single page. */ this.id = ++WebViewInterface.cntWebViewId; /** * Maintaining mapping of webview instance and its id, to handle scenarios of multiple webview on single page. */ WebViewInterface.webViewInterfaceIdMap[this.id] = this; }
javascript
{ "resource": "" }
q49992
getAndroidJSInterface
train
function getAndroidJSInterface(oWebViewInterface){ var AndroidWebViewInterface = com.shripalsoni.natiescriptwebviewinterface.WebViewInterface.extend({ /** * On call from webView to android, this function is called from handleEventFromWebView method of WebViewInerface class */ onWebViewEvent: function(webViewId, eventName, jsonData){ // getting webviewInterface object by webViewId from static map. var oWebViewInterface = getWebViewIntefaceObjByWebViewId(webViewId); if (oWebViewInterface) { oWebViewInterface._onWebViewEvent(eventName, jsonData); } } }); // creating androidWebViewInterface with unique web-view id. return new AndroidWebViewInterface(new java.lang.String(''+oWebViewInterface.id)); }
javascript
{ "resource": "" }
q49993
train
function(webViewId, eventName, jsonData){ // getting webviewInterface object by webViewId from static map. var oWebViewInterface = getWebViewIntefaceObjByWebViewId(webViewId); if (oWebViewInterface) { oWebViewInterface._onWebViewEvent(eventName, jsonData); } }
javascript
{ "resource": "" }
q49994
train
function(object) { // if we're not an array or object, return the primative if (object !== Object(object)) { return object; } var decamelizeString = function(string) { var separator = '_'; var split = /(?=[A-Z])/; return string.split(split).join(separator).toLowerCase(); }; var output; if (object instanceof Array) { output = []; for(var i = 0, l = object.length; i < l; i++) { output.push(decamelizeKeys(object[i])); } } else { output = {}; for (var key in object) { if (object.hasOwnProperty(key)) { output[decamelizeString(key)] = decamelizeKeys(object[key]); } } } return output; }
javascript
{ "resource": "" }
q49995
train
function(client, initialData, totalLength, requestOptions, successStatuses, successRootKeys, promise) { this.currentPage = 1; // default to start at page 1 // this.perPage = queryParams && queryParams.per_page || 25; // default to 25 per page this.totalLength = totalLength; // bootstrap with initial data this.push.apply(this, initialData); this.client = client; this.requestOptions = requestOptions; this.successStatuses = successStatuses; this.successRootKeys = successRootKeys; this.promise = promise; }
javascript
{ "resource": "" }
q49996
pollUntilDone
train
function pollUntilDone(id, done) { client.droplets.get(id, function(err, droplet) { if (!err && droplet.locked === false) { // we're done! done.call(); } else if (!err && droplet.locked === true) { // back off 10s more setTimeout(function() { pollUntilDone(id, done); }, (10 * 1000)); } else { pollUntilDone(id, done); } }); }
javascript
{ "resource": "" }
q49997
generateModule
train
function generateModule (f) { // f.dest must be a string or write will fail var moduleNames = []; var filePaths = f.src.filter(existsFilter); if (options.watch) { watcher.add(filePaths); } var modules = filePaths.map(function (filepath) { var moduleName = normalizePath(path.relative(options.base, filepath)); if (grunt.util.kindOf(options.rename) === 'function') { moduleName = options.rename(moduleName); } moduleNames.push(options.quoteChar + moduleName + options.quoteChar); var compiled; if (options.watch && (compiled = fileCache[filepath])) { // return compiled file contents from cache return compiled; } if (options.target === 'js') { compiled = compileTemplate(moduleName, filepath, options); } else if (options.target === 'coffee') { compiled = compileCoffeeTemplate(moduleName, filepath, options); } else { grunt.fail.fatal('Unknown target "' + options.target + '" specified'); } if (options.watch) { // store compiled file contents in cache fileCache[filepath] = compiled; } return compiled; }); // don't generate empty modules if (!modules.length) { return; } counter += modules.length; modules = modules.join('\n'); var fileHeader = options.fileHeaderString !== '' ? options.fileHeaderString + '\n' : ''; var fileFooter = options.fileFooterString !== '' ? options.fileFooterString + '\n' : ''; var bundle = ''; var targetModule = f.module || options.module; var indentString = options.indentString; var quoteChar = options.quoteChar; var strict = (options.useStrict) ? indentString + quoteChar + 'use strict' + quoteChar + ';\n' : ''; var amdPrefix = ''; var amdSuffix = ''; // If options.module is a function, use that to get the targetModule if (grunt.util.kindOf(targetModule) === 'function') { targetModule = targetModule(f, target); } if (options.amd) { amdPrefix = options.amdPrefixString; amdSuffix = options.amdSuffixString; } if (!targetModule && options.singleModule) { throw new Error('When using singleModule: true be sure to specify a (target) module'); } if (options.existingModule && !options.singleModule) { throw new Error('When using existingModule: true be sure to set singleModule: true'); } if (options.singleModule) { var moduleSuffix = options.existingModule ? '' : ', []'; if (options.target === 'js') { bundle = 'angular.module(' + quoteChar + targetModule + quoteChar + moduleSuffix + ').run([' + quoteChar + '$templateCache' + quoteChar + ', function($templateCache) {\n' + strict; modules += '\n}]);\n'; } else if (options.target === 'coffee') { bundle = 'angular.module(' + quoteChar + targetModule + quoteChar + moduleSuffix + ').run([' + quoteChar + '$templateCache' + quoteChar + ', ($templateCache) ->\n'; modules += '\n])\n'; } } else if (targetModule) { //Allow a 'no targetModule if module is null' option bundle = 'angular.module(' + quoteChar + targetModule + quoteChar + ', [' + moduleNames.join(', ') + '])'; if (options.target === 'js') { bundle += ';'; } bundle += '\n\n'; } grunt.file.write(f.dest, grunt.util.normalizelf(fileHeader + amdPrefix + bundle + modules + amdSuffix + fileFooter)); }
javascript
{ "resource": "" }
q49998
train
function (scope, elm, attrs) { var id = 0, mergedConfig; mergedConfig = angular.extend({}, toasterConfig, scope.$eval(attrs.toasterOptions)); scope.config = { position: mergedConfig['position-class'], title: mergedConfig['title-class'], message: mergedConfig['message-class'], tap: mergedConfig['tap-to-dismiss'], closeButton: mergedConfig['close-button'] }; scope.configureTimer = function configureTimer(toast) { var timeout = typeof (toast.timeout) == "number" ? toast.timeout : mergedConfig['time-out']; if (timeout > 0) setTimeout(toast, timeout); }; function addToast(toast) { toast.type = mergedConfig['icon-classes'][toast.type]; if (!toast.type) toast.type = mergedConfig['icon-class']; id++; angular.extend(toast, { id: id }); // Set the toast.bodyOutputType to the default if it isn't set toast.bodyOutputType = toast.bodyOutputType || mergedConfig['body-output-type']; switch (toast.bodyOutputType) { case 'trustedHtml': toast.html = $sce.trustAsHtml(toast.body); break; case 'template': toast.bodyTemplate = toast.body || mergedConfig['body-template']; break; } scope.configureTimer(toast); if (mergedConfig['newest-on-top'] === true) { scope.toasters.unshift(toast); if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) { scope.toasters.pop(); } } else { scope.toasters.push(toast); if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) { scope.toasters.shift(); } } } function setTimeout(toast, time) { toast.timeout = $timeout(function () { scope.removeToast(toast.id); }, time); } scope.toasters = []; scope.$on('toaster-newToast', function () { addToast(toaster.toast); }); scope.$on('toaster-clearToasts', function () { scope.toasters.splice(0, scope.toasters.length); }); }
javascript
{ "resource": "" }
q49999
_setDefaultTranslations
train
function _setDefaultTranslations(){ $scope.mdtTranslations = $scope.mdtTranslations || {}; $scope.mdtTranslations.rowsPerPage = $scope.mdtTranslations.rowsPerPage || 'Rows per page:'; $scope.mdtTranslations.largeEditDialog = $scope.mdtTranslations.largeEditDialog || {}; $scope.mdtTranslations.largeEditDialog.saveButtonLabel = $scope.mdtTranslations.largeEditDialog.saveButtonLabel || 'Save'; $scope.mdtTranslations.largeEditDialog.cancelButtonLabel = $scope.mdtTranslations.largeEditDialog.cancelButtonLabel || 'Cancel'; }
javascript
{ "resource": "" }