_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q32900
bintodecoutput
train
function bintodecoutput(bin){ var len = bin.length; var decoutput = String(); var work = new Array(len); var outputlen = 0; for(var i=0; i<len; i++){work[i] = bin[i];} while(len){ // as long as a remaining value exists var lead = false; var bit0; var bit1; var bit2; var bit3; var value; var i = 0; while(i < len-3){ // walk through the remaining value bit0 = work[i+3]; bit1 = work[i+2]; bit2 = work[i+1]; bit3 = work[i+0]; value = (bit3<<3) | (bit2<<2) | (bit1<<1) | (bit0<<0); if(value >= 10){ // For nibbles greaterequal than 10, adjust the bits accordingly. work[i+0] = true; work[i+1] = bit2 && bit1; work[i+2] = !bit1; }else{ work[i+0] = lead; if(lead){ // When the previous nibble was 8 or 9, adjust the bits accordingly work[i+1] = !bit1; work[i+2] = !bit1; lead = bit1; }else{ // otherwise, just leave the bits as they are. if(value >= 8){lead = true;} } } i++; } // extract the decimal value of the remaining bits if(len==1){ bit0 = work[0]; bit1 = false; bit2 = false; }else if(len==2){ bit0 = work[1]; bit1 = work[0]; bit2 = false; }else{ bit0 = work[i + 2]; bit1 = work[i + 1]; bit2 = work[i + 0]; } bit3 = lead; var value = (bit3<<3) | (bit2<<2) | (bit1<<1) | (bit0<<0); if(!(outputlen%3)){decoutput = ' ' + decoutput;} decoutput = value + decoutput; outputlen++; len = i; } // Remove zeros var i = 0; outputlen = decoutput.length; while((i < outputlen) && ((decoutput[i] == '0') || (decoutput[i] == ' '))){i++;} if(i == outputlen){ return "0"; }else{ return decoutput.slice(i); } }
javascript
{ "resource": "" }
q32901
bintohexoutput
train
function bintohexoutput(bin){ var len = bin.length; var hexoutput = String(); for(var i=0; i<len; i+=4){ if((i > 0) && !(i%8)){hexoutput = " " + hexoutput;} var value = 0; if(bin[len - 1 - i - 0]){value+=1;} if(bin[len - 1 - i - 1]){value+=2;} if(bin[len - 1 - i - 2]){value+=4;} if(bin[len - 1 - i - 3]){value+=8;} switch(value){ case 0: hexoutput = "0" + hexoutput; break; case 1: hexoutput = "1" + hexoutput; break; case 2: hexoutput = "2" + hexoutput; break; case 3: hexoutput = "3" + hexoutput; break; case 4: hexoutput = "4" + hexoutput; break; case 5: hexoutput = "5" + hexoutput; break; case 6: hexoutput = "6" + hexoutput; break; case 7: hexoutput = "7" + hexoutput; break; case 8: hexoutput = "8" + hexoutput; break; case 9: hexoutput = "9" + hexoutput; break; case 10: hexoutput = "a" + hexoutput; break; case 11: hexoutput = "b" + hexoutput; break; case 12: hexoutput = "c" + hexoutput; break; case 13: hexoutput = "d" + hexoutput; break; case 14: hexoutput = "e" + hexoutput; break; case 15: hexoutput = "f" + hexoutput; break; default: break; } } // todo: make faster return hexoutput; }
javascript
{ "resource": "" }
q32902
bintobinoutput
train
function bintobinoutput(bin){ var len = bin.length; var binoutput = String(); for(var i=0; i<len; i++){ if((i > 0) && !(i%8)){binoutput = " " + binoutput;} if(bin[len - 1 - i]){binoutput = "1" + binoutput;}else{binoutput = "0" + binoutput;} } // todo: make faster return binoutput; }
javascript
{ "resource": "" }
q32903
bintooctoutput
train
function bintooctoutput(bin){ var len = bin.length; var octoutput = String(); for(var i=0; i<len; i+=3){ if((i > 0) && !(i%24)){octoutput = " " + octoutput;} var value = 0; if(bin[len - 1 - i - 0]){value+=1;} if(bin[len - 1 - i - 1]){value+=2;} if(bin[len - 1 - i - 2]){value+=4;} switch(value){ case 0: octoutput = "0" + octoutput; break; case 1: octoutput = "1" + octoutput; break; case 2: octoutput = "2" + octoutput; break; case 3: octoutput = "3" + octoutput; break; case 4: octoutput = "4" + octoutput; break; case 5: octoutput = "5" + octoutput; break; case 6: octoutput = "6" + octoutput; break; case 7: octoutput = "7" + octoutput; break; default: break; } } // todo: make faster return octoutput; }
javascript
{ "resource": "" }
q32904
filledarray
train
function filledarray(value, size){ var a = new Array(size); for(var i=0; i<size; i++){a[i] = value;} return a; }
javascript
{ "resource": "" }
q32905
binadd
train
function binadd(bin1, bin2){ var i1 = bin1.length; var i2 = bin2.length; var i3 = (i1 > i2) ? (i1 + 1) : (i2 + 1); var result = new Array(i3); var c = 0; // Add the two arrays as long as there exist elements in the arrays while((i1 > 0) && (i2 > 0)){ i1--; i2--; i3--; if(bin1[i1]){c++;} if(bin2[i2]){c++;} result[i3] = (c%2) ? true : false; c >>= 1; } // copy the remaining elements if(i1){ for(var i=0; i<i1; i++){result[i+1] = bin1[i];} }else{ for(var i=0; i<i2; i++){result[i+1] = bin2[i];} } // add the remaining carry var carry = c ? true : false; while(c && (i3 > 1)){ i3--; result[i3] = !result[i3]; c = !result[i3]; } // Return result with carry if necessary if (c==1){ result[0] = true; return result; }else{ return result.slice(1); } }
javascript
{ "resource": "" }
q32906
binaddone
train
function binaddone(bin){ var len = bin.length; var result = new Array(len + 1); var c = true; // carry bit var i = len; // i points at the bit in bin one after the untouched bit while(c && (i > 0)){ i--; c = bin[i]; result[i+1] = !c; } if(i){ // Return remaining untouched bin concatenated with the touched bits return bin.slice(0, i).concat(result.slice(i+1)); }else{ if(c){ // Return full result with carry as prefix result[0] = true; return result; }else{ // Return result without carry return result.slice(1); } } }
javascript
{ "resource": "" }
q32907
bintruncate
train
function bintruncate(bin, size){ var len = bin.length; if(len < size){ return filledarray(false, size-len).concat(bin); }else{ return bin.slice(len - size); } }
javascript
{ "resource": "" }
q32908
onescomplement
train
function onescomplement(bin){ var len = bin.length; var onebin = new Array(len); for (var i=0; i<len; i++){onebin[i] = !bin[i];} return onebin; }
javascript
{ "resource": "" }
q32909
updatedec
train
function updatedec(){ var dec = decinputfield; if(decinputvalue != dec){ updateall(decinputtobin(dec)); clearallinputs(); decinputfield = dec; decinputvalue = dec; } }
javascript
{ "resource": "" }
q32910
updatehex
train
function updatehex(){ var hex = hexinputfield; if(hexinputvalue != hex){ updateall(hexinputtobin(hex)); clearallinputs(); hexinputfield = hex; hexinputvalue = hex; } }
javascript
{ "resource": "" }
q32911
updatebin
train
function updatebin(){ var bin = bininputfield; if(bininputvalue != bin){ updateall(bininputtobin(bin)); clearallinputs(); bininputfield = bin; bininputvalue = bin; } }
javascript
{ "resource": "" }
q32912
updateoct
train
function updateoct(){ var oct = octinputfield; if(octinputvalue != oct){ updateall(octinputtobin(oct)); clearallinputs(); octinputfield = oct; octinputvalue = oct; } }
javascript
{ "resource": "" }
q32913
AnimationThrottler
train
function AnimationThrottler(delay) { if(!delay) delay = DELAY; // Anim is considered active if it's running or queued var currentDelay = 0; // func: Function that takes no params and returns a promise function requestAnim(func) { var result = q.delay(currentDelay) .thenResolve(func) .then(start); currentDelay += delay; return result; } this.requestAnim = requestAnim; function start(func) { return func() .catch(animFailed) .tap(animFinished); } function animFailed(error) { animFinished(); throw error; } function animFinished() { currentDelay -= delay; } }
javascript
{ "resource": "" }
q32914
train
function(service, credentials) { Services.load(service); process.nextTick(function() { Services.boot(service, credentials); }.bind(this)); }
javascript
{ "resource": "" }
q32915
update
train
function update(req, res, next) { res.__apiMethod = 'update'; const self = this; const id = req.params.id; let filter = this.option('update', 'filter'); const fields = this.option('update', 'fields'); const populate = this.option('update', 'populate'); const readonly = this.option('update', 'readonly'); if (filter instanceof Function) filter = filter.call(this, req); const query = Object.assign({ }, filter, { _id: id }); const method = self.option('update', 'method'); let data = helpers.flat( (method !== 'get') ? req.body : req.query ); try { if (readonly) { data = helpers.validateReadonly(data, readonly); } data = helpers.validateReadonly(data, [{ name: '_id', path: /^_id$/ }]); } catch(e) { return next(e) } let dbQuery = this.model.findOneAndUpdate( query, { $set: data }, { new: true, fields: fields, runValidators: true } ); if (populate) { dbQuery = dbQuery.populate(populate); } dbQuery.exec(function(err, obj) { if (err) { if (err.name && err.name == "ValidationError") { return next(new ModelAPIError(422, err)); } return next(err); }; if (!obj) return next(new ModelAPIError( 404, `The ${self.nameSingle} was not found by ${id}` )); res.status(200); res.json(obj); }); }
javascript
{ "resource": "" }
q32916
getOverlapTrapezoid
train
function getOverlapTrapezoid(x1, y1, x2, y2) { var factor = 2 / (widthTop + widthBottom); // correction for surface=1 if (y1 === 0 || y2 === 0) return 0; if (x1 === x2) { // they have the same position return Math.min(y1, y2); } var diff = Math.abs(x1 - x2); if (diff >= widthBottom) return 0; if (y1 === y2) { // do they have the same height ??? // we need to find the common length if (diff <= widthTop) { return (((widthTop + widthBottom) / 2 - diff) * y1) * factor; } else if (diff <= widthBottom) { return (widthBottom - diff) * y1 / 2 * (diff - widthTop) / (widthBottom - widthTop) * factor; } return 0; } else { // the height are different and not the same position ... // we need to consider only one segment to find its intersection var small = Math.min(y1, y2); var big = Math.max(y1, y2); var targets = [ [[0, 0], [widthSlope, small]], [[widthSlope, small], [widthSlope + widthTop, small]], [[widthTop + widthSlope, small], [widthBottom, 0]] ]; var segment; if ((x1 > x2 && y1 > y2) || (x1 < x2 && y1 < y2)) { segment = [[diff, 0], [diff + widthSlope, big]]; } else { segment = [[diff + widthSlope, big], [diff, 0]]; } for (var i = 0; i < 3; i++) { var intersection = getIntersection(targets[i], segment); if (intersection) { switch (i) { case 0: return small - ((diff * intersection.y / 2)) * factor; case 1: // to simplify ... // console.log(" ",widthSlope,small,big,intersection.x) return ((widthSlope * small / (2 * big)) * small + (widthTop + widthSlope - intersection.x) * small + widthSlope * small / 2) * factor; case 2: return ((widthBottom - diff) * intersection.y / 2) * factor; default: throw new Error(`unexpected intersection value: ${i}`); } } } } return NaN; }
javascript
{ "resource": "" }
q32917
calculateDiff
train
function calculateDiff() { // we need to take 2 pointers // and travel progressively between them ... var newFirst = [ [].concat(array1Extract[0]), [].concat(array1Extract[1]) ]; var newSecond = [ [].concat(array2Extract[0]), [].concat(array2Extract[1]) ]; var array1Length = array1Extract[0] ? array1Extract[0].length : 0; var array2Length = array2Extract[0] ? array2Extract[0].length : 0; var pos1 = 0; var pos2 = 0; var previous2 = 0; while (pos1 < array1Length) { var diff = newFirst[0][pos1] - array2Extract[0][pos2]; if (Math.abs(diff) < widthBottom) { // there is some overlap var overlap; if (options.trapezoid) { overlap = getOverlapTrapezoid(newFirst[0][pos1], newFirst[1][pos1], newSecond[0][pos2], newSecond[1][pos2], widthTop, widthBottom); } else { overlap = getOverlap(newFirst[0][pos1], newFirst[1][pos1], newSecond[0][pos2], newSecond[1][pos2], widthTop, widthBottom); } newFirst[1][pos1] -= overlap; newSecond[1][pos2] -= overlap; if (pos2 < (array2Length - 1)) { pos2++; } else { pos1++; pos2 = previous2; } } else { if (diff > 0 && pos2 < (array2Length - 1)) { pos2++; previous2 = pos2; } else { pos1++; pos2 = previous2; } } } return newSecond; }
javascript
{ "resource": "" }
q32918
commonExtractAndNormalize
train
function commonExtractAndNormalize(array1, array2, width, from, to, common) { if (!(Array.isArray(array1)) || !(Array.isArray(array2))) { return { info: undefined, data: undefined }; } var extract1 = extract(array1, from, to); var extract2 = extract(array2, from, to); var common1, common2, info1, info2; if (common & COMMON_SECOND) { common1 = getCommonArray(extract1, extract2, width); info1 = normalize(common1); } else { common1 = extract1; info1 = normalize(common1); } if (common & COMMON_FIRST) { common2 = getCommonArray(extract2, extract1, width); info2 = normalize(common2); } else { common2 = extract2; info2 = normalize(common2); } return { info1: info1, info2: info2, data1: common1, data2: common2 }; }
javascript
{ "resource": "" }
q32919
train
function(nameParams) { if(nameParams && nameParams.match(/^[a-zA-Z0-9_\.]*\(.*\)$/)) { var npart = nameParams.substring(0, nameParams.indexOf('(')); var ppart = Parameters( nameParams.substring(nameParams.indexOf('(')+1, nameParams.lastIndexOf(')')) ); return { name: npart, params: ppart }; } else { return { name: nameParams, params: null }; } }
javascript
{ "resource": "" }
q32920
train
function(name) { name = name || ''; // TODO optimize with RegExp var nameChain = name.split('.'); for(var i=0; i<nameChain.length; i++) { if(!nameChain[i].match(/[a-zA-Z0-9_]+/)) { return false; } } return true; }
javascript
{ "resource": "" }
q32921
train
function(query) { query = query || ''; // TODO optimize with RegExp var nameChain = query.split('.'); for(var i=0; i<nameChain.length; i++) { if(!nameChain[i].match(/(\*(\*)?|[a-zA-Z0-9_]+)/)) { return false; } } return true; }
javascript
{ "resource": "" }
q32922
train
function(a, b) { a = a || {}; b = b || {}; return a.name === b.name && angular.equals(a.params, b.params); }
javascript
{ "resource": "" }
q32923
train
function(name) { var nameList = name.split('.'); return nameList .map(function(item, i, list) { return list.slice(0, i+1).join('.'); }) .filter(function(item) { return item !== null; }); }
javascript
{ "resource": "" }
q32924
train
function(name) { name = name || ''; var state = null; // Only use valid state queries if(!_validateStateName(name)) { return null; // Use cache if exists } else if(_stateCache[name]) { return _stateCache[name]; } var nameChain = _getNameChain(name); var stateChain = nameChain .map(function(name, i) { var item = angular.copy(_stateLibrary[name]); return item; }) .filter(function(parent) { return !!parent; }); // Walk up checking inheritance for(var i=stateChain.length-1; i>=0; i--) { if(stateChain[i]) { var nextState = stateChain[i]; state = angular.merge(nextState, state || {}); } if(state && state.inherit === false) break; } // Store in cache _stateCache[name] = state; return state; }
javascript
{ "resource": "" }
q32925
train
function(name, data) { if(name === null || typeof name === 'undefined') { throw new Error('Name cannot be null.'); // Only use valid state names } else if(!_validateStateName(name)) { throw new Error('Invalid state name.'); } // Create state var state = angular.copy(data); // Use defaults _setStateDefaults(state); // Named state state.name = name; // Set definition _stateLibrary[name] = state; // Reset cache _stateCache = {}; // URL mapping if(state.url) { _urlDictionary.add(state.url, state); } return data; }
javascript
{ "resource": "" }
q32926
train
function(data) { // Keep the last n states (e.g. - defaults 5) var historyLength = _options.historyLength || 5; if(data) { _history.push(data); } // Update length if(_history.length > historyLength) { _history.splice(0, _history.length - historyLength); } }
javascript
{ "resource": "" }
q32927
train
function(name, params) { return _changeState(name, params).then(function() { $rootScope.$broadcast('$stateChangeComplete', null, _current); }, function(err) { $rootScope.$broadcast('$stateChangeComplete', err, _current); }); }
javascript
{ "resource": "" }
q32928
train
function() { var deferred = $q.defer(); $rootScope.$evalAsync(function() { var n = _current.name; var p = angular.copy(_current.params); if(!_current.params) { _current.params = {}; } _current.params.deprecated = true; // Notify $rootScope.$broadcast('$stateReload', null, _current); _changeStateAndBroadcastComplete(n, p).then(function() { deferred.resolve(); }, function(err) { deferred.reject(err); }); }); return deferred.promise; }
javascript
{ "resource": "" }
q32929
train
function(handler, priority) { if(typeof handler !== 'function') { throw new Error('Middleware must be a function.'); } if(typeof priority !== 'undefined') handler.priority = priority; _layerList.push(handler); return _inst; }
javascript
{ "resource": "" }
q32930
train
function(query, params) { query = query || ''; // No state if(!_current) { return false; // Use RegExp matching } else if(query instanceof RegExp) { return !!_current.name.match(query); // String; state dot-notation } else if(typeof query === 'string') { // Cast string to RegExp if(query.match(/^\/.*\/$/)) { var casted = query.substr(1, query.length-2); return !!_current.name.match(new RegExp(casted)); // Transform to state notation } else { var transformed = query .split('.') .map(function(item) { if(item === '*') { return '[a-zA-Z0-9_]*'; } else if(item === '**') { return '[a-zA-Z0-9_\\.]*'; } else { return item; } }) .join('\\.'); return !!_current.name.match(new RegExp(transformed)); } } // Non-matching return false; }
javascript
{ "resource": "" }
q32931
support
train
function support (name) { try { return BIKE.require(BIKEname + '-' + name); } catch (e) { return BIKE.require(name); } }
javascript
{ "resource": "" }
q32932
define
train
function define() { var type = this.data.type || this.defaults.type , collection = this.collection; this.data.use = collection[type].class; this.data.text = this.data.text || collection[type].text; this.data.href = this.data.href || collection[type].href; return this; }
javascript
{ "resource": "" }
q32933
train
function(service, credentials, accounts, keywords) { Stream.call(this, service, credentials, accounts, keywords); // Initialize responder this.responder = new Responder(); }
javascript
{ "resource": "" }
q32934
getLangDefinition
train
function getLangDefinition(m) { var langKey = (typeof m === 'string') && m || m && m._lang || null; return langKey ? (languages[langKey] || loadLang(langKey)) : moment; }
javascript
{ "resource": "" }
q32935
_flatten
train
function _flatten(groups, groupName, alreadySeen) { alreadySeen = alreadySeen || []; var ret = {}; // Intialize each key to empty so we don't have to check if they exist later HANDLER_KEYS.forEach(function(key) { ret[key] = []; }); var thisGroup = groups[groupName]; if ( !thisGroup ) throw new Error('Unknown group: ' + groupName); // If this group includes other groups, add them first if ( thisGroup.include ) { thisGroup.include.forEach(function(subGroupName) { if ( alreadySeen.indexOf(subGroupName) >= 0 ) { // Circular dependency and this group has already been included elsewhere return; } else { alreadySeen.push(subGroupName); } var subGroup = _flatten(groups, subGroupName, alreadySeen); if ( !subGroup ) throw new Error('Unknown subgroup:' +subGroupName); HANDLER_KEYS.forEach(function(key) { if ( subGroup[key] ) { _mergeArrayInPlace(ret[key], subGroup[key]); } }); }); } // Then add the individual files for this group at the end HANDLER_KEYS.forEach(function(key) { if ( thisGroup[key] ) { _mergeArrayInPlace( ret[key], thisGroup[key] ); } }); return ret; }
javascript
{ "resource": "" }
q32936
resolveFile
train
function resolveFile(baseDirs, addType, fileName, type, cb) { // The label this file will have in the output // For hbs views, this is the name that it will be save as into the template array. var label = pathlib.basename(fileName); // Label can be overridden with entries of the form: "label:file-name-or-path" var idx = fileName.indexOf(':'); if ( idx > 0 ) { label = fileName.substr(0,idx); fileName = fileName.substr(idx+1); } // Construct a list of paths to check var paths = []; baseDirs.forEach(function(baseDir) { if ( addType ) baseDir += '/'+type; // Search for exact filename paths.push(pathlib.resolve(baseDir,fileName)); // And with the type as an extension paths.push(pathlib.resolve(baseDir,fileName+'.'+type)); // Special case 'view' because it used to mean hbs if ( type == 'view' ) { VIEW_TYPES.forEach(function(altType) { paths.push(pathlib.resolve(baseDir,fileName+'.'+altType)); }); } }); // Async if ( cb ) { async.detectSeries(paths, fs.exists, function(result) { if ( result ) return cb(undefined, label+':'+result); else return cb(new Error(errStr)); }); } else { // Sync for ( i=0 ; i < paths.length ; i++ ) { if ( fs.existsSync(paths[i]) ) { return label+':'+paths[i]; } } throw new Error('Unable to find source ' + type + ' file for ' + fileName + ' in ' + paths.join(', ')); } }
javascript
{ "resource": "" }
q32937
makeStrProtoFn
train
function makeStrProtoFn(method) { return function () { // Convert `arguments` into an array (usually empty or has 1 parameter) var args = slice.call(arguments, 0); // Add the current string as the first argument args.unshift(this); return ColorHelper[method].apply(ColorHelper, args); }; }
javascript
{ "resource": "" }
q32938
sCurve
train
function sCurve(length, rotation) { var curve = new Float32Array(length), i, phase = rotation > 0 ? Math.PI / 2 : -(Math.PI / 2); for (i = 0; i < length; ++i) { curve[i] = Math.sin(Math.PI * i / length - phase) / 2 + 0.5; } return curve; }
javascript
{ "resource": "" }
q32939
logarithmic
train
function logarithmic(length, base, rotation) { var curve = new Float32Array(length), index, x = 0, i; for (i = 0; i < length; i++) { //index for the curve array. index = rotation > 0 ? i : length - 1 - i; x = i / length; curve[index] = Math.log(1 + base * x) / Math.log(1 + base); } return curve; }
javascript
{ "resource": "" }
q32940
HackerEarthAPI
train
function HackerEarthAPI (clientSecretKey, options) { if (typeof clientSecretKey != 'string') { clientSecretKey = null; options = clientSecretKey; } if (!options) { options = {}; } if (!clientSecretKey) { throw new Error('You have to provide a client secret key for this to work. If you do not have one, please register your client at https://www.hackerearth.com/api/register.'); } if (!options.version || options.version == '3') { this.version = 'v3'; } else if (options.version == '2') { this.version = 'v2'; } else { throw new Error('Version ' + options.version + ' of the HackerEarth API is currently not supported.'); } this.clientSecretKey = clientSecretKey; this.httpHost = 'api.hackerearth.com:443' this.httpUri = 'https://' + this.httpHost; this.possibleLangs = ['C', 'CPP', 'CPP11', 'CLOJURE', 'CSHARP', 'JAVA', 'JAVASCRIPT', 'HASKELL', 'PERL', 'PHP', 'PYTHON', 'RUBY']; }
javascript
{ "resource": "" }
q32941
unindex
train
function unindex (options) { var self = this var unindexUri = helpers.makeDocumentUri(options, self) // console.log('unindex:', unindexUri) var reqOpts = { method: 'DELETE', url: unindexUri } if(options.auth) { reqOpts.auth = { user: options.auth.user, pass: options.auth.password, sendImmediately: false }; } helpers.backOffRequest(reqOpts, function (err, res, body) { if (err) { var error = new Error('Elasticsearch document index deletion error: '+util.inspect(err, true, 10, true)) error.details = err console.log('error', error); //self.emit('error', error) return } self.emit('elmongoose-unindexed', body) }) }
javascript
{ "resource": "" }
q32942
normalizeEngine
train
function normalizeEngine(fn, options) { if (utils.isEngine(options)) { return normalizeEngine(options, fn); //<= reverse args } if (!isObject(fn) && typeof fn !== 'function') { throw new TypeError('expected an object or function'); } var engine = {}; engine.render = fn.render || fn; engine.options = extend({}, options); if (typeof engine.render !== 'function') { throw new Error('expected engine to have a render method'); } var keys = Object.keys(fn); var len = keys.length; var idx = -1; while (++idx < len) { var key = keys[idx]; if (key === 'options') { engine.options = extend({}, engine.options, fn[key]); continue; } if (key === '__express' && !fn.hasOwnProperty('renderFile')) { engine.renderFile = fn[key]; } engine[key] = fn[key]; } return engine; }
javascript
{ "resource": "" }
q32943
inspect
train
function inspect(engine) { var inspect = ['"' + engine.name + '"']; var exts = utils.arrayify(engine.options.ext).join(', '); inspect.push('<ext "' + exts + '">'); engine.inspect = function() { return '<Engine ' + inspect.join(' ') + '>'; }; }
javascript
{ "resource": "" }
q32944
mergeHelpers
train
function mergeHelpers(engine, options) { if (!options || typeof options !== 'object') { throw new TypeError('expected an object'); } var opts = extend({}, options); var helpers = merge({}, engine.helpers.cache, opts.helpers); var keys = Object.keys(helpers); for (var i = 0; i < keys.length; i++) { var key = keys[i]; engine.asyncHelpers.set(key, helpers[key]); } opts.helpers = engine.asyncHelpers.get({wrap: opts.async}); return opts; }
javascript
{ "resource": "" }
q32945
init
train
function init(){ eventDataPairs = 0; currentSession = sessionManager.createSession(); lastRequestTime = utils.getUnixTimeInSeconds(); mediaPlaying = false; // checks if time since last request has exceeded the maximum request time if (timeSinceRequestChecker){ clearInterval(timeSinceRequestChecker); timeSinceRequestChecker = null; } timeSinceRequestChecker = setInterval( () => { const currentTime = utils.getUnixTimeInSeconds(); if (currentTime - lastRequestTime > config.getDataPostTimeInterval()){ _createDataRequest(); } }, 1000); }
javascript
{ "resource": "" }
q32946
addScene
train
function addScene(sceneId, sceneName){ if (!sceneId && !sceneName){ logger.warn('SceneId or SceneName is required to starting a new scene session. Aborting'); return; } // close any previous media if (mediaPlaying) closeMedia(); currentSession.addScene(sceneId, sceneName); }
javascript
{ "resource": "" }
q32947
addMedia
train
function addMedia(mediaId, name, type, url){ // close any previous media if (mediaPlaying) closeMedia(); if (type != enums.media360.video && type != enums.media360.image){ logger.warn('Media type not supported. Aborting addind media.'); return; } if (type == enums.media360.video){ timeManager.playVideo(); } mediaPlaying = true; currentSession.addMedia(mediaId, name, type, url); }
javascript
{ "resource": "" }
q32948
registerEvent
train
function registerEvent(eventName, position, extra){ currentSession.registerEvent(eventName, position, extra); // check size of events and handle making request _checkDataPairs(); }
javascript
{ "resource": "" }
q32949
_createDataRequest
train
function _createDataRequest(){ logger.info('Creating data request'); eventDataPairs = 0; const currentSessionData = currentSession.getDictionary(); serverRequestManager.addDataRequest(currentSessionData); currentSession = currentSession.getDuplicate(); lastRequestTime = utils.getUnixTimeInSeconds(); sessionManager.setSessionCookie(); }
javascript
{ "resource": "" }
q32950
train
function () { return crypto.createHash('sha1') .update(Date.now().toString() + Math.random().toString()) .digest('hex'); }
javascript
{ "resource": "" }
q32951
TorRelay
train
function TorRelay(opts) { var self = this; opts = opts || {}; if (!opts.hasOwnProperty('autoCredentials')) { opts.autoCredentials = true; } this.dataDirectory = opts.dataDirectory || null; if (!opts.hasOwnProperty('cleanUpOnExit')) { this.cleanUpOnExit = true; } else { this.cleanUpOnExit = opts.cleanUpOnExit; } if (opts.hasOwnProperty('retries')) { this.retries = opts.retries; } if (opts.hasOwnProperty('timeout')) { this.timeout = opts.timeout; } /** * Configuration of the services * @type {{control: {password: (string|*), port: (string|*|null)}, socks: {port: (string|*|null)}}} */ this.service = { control: { password: opts.controlPassword || (opts.autoCredentials ? createCredential() : null), port: opts.controlPort || null }, socks: { username: opts.socksUsername || null, password: opts.socksPassword || null, port: opts.socksPort || null } }; if (!opts.hasOwnProperty('socksUsername') && opts.autoCredentials) { this.service.socks.username = createCredential(); } if (!opts.hasOwnProperty('socksPassword') && opts.autoCredentials) { this.service.socks.password = createCredential(); } process.on('exit', function () { if (self.process && self.cleanUpOnExit) { console.error('Killing tor sub-process'); self.process.kill('SIGTERM'); self.process.kill('SIGKILL'); } }); }
javascript
{ "resource": "" }
q32952
restartRelay
train
function restartRelay(cb) { var self = this; this.stop(function (err) { if (err) { return cb(err); } self.start(cb); }); }
javascript
{ "resource": "" }
q32953
train
function(doc, fields) { return Object.keys(fields).reduce((prev, key) => { let val if (fields[key].hasOwnProperty('referenceCollection')) { const displayField = fields[key].referenceCollection.defaultField if (Array.isArray(doc[key])) { val = doc[key].map(data => { return data[displayField] }) } else { val = doc[key][displayField] } } else { val = doc[key] } return Object.assign({}, prev, { [key]: val }) }, { _id: doc._id }) }
javascript
{ "resource": "" }
q32954
train
function(doc, def, labelTemplate) { return Object.keys(doc) .map(key => { const field = doc[key] const fieldDef = def[key] if (!field || (!fieldDef && key != '_id')) { return null } const name = key == '_id' ? 'id' : fieldDef.label const template = labelTemplate || '%s' const label = util.format(template, name) if (typeof field == 'object' && !Array.isArray(field) && key != '_id') { return getDocumentOutput(field, fieldDef.schemaType, label + ' (%s)') } return `${chalk.yellow(label)}: ${field}` }) .filter(line => { return line !== null }) .join('\n') }
javascript
{ "resource": "" }
q32955
train
function (value) { value += ''; if (value.search(/^\-?\d+$/) > -1) { return 'integer'; } if (value.search(/^\-?\d+\.\d+[\d.]*$/) > -1) { return 'float'; } if ('false' === value || 'true' === value) { return 'boolean'; } if (value.search(/^\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z?$/) > -1) { return 'datetime'; } return 'string'; }
javascript
{ "resource": "" }
q32956
train
function (value, type) { type = type || 'smart'; switch (type) { case 'boolean': case 'bool': if (typeof value !== 'string') { value = !!value; } else { value = ['null', 'undefined', '0', 'false'].indexOf(value) === -1; } break; case 'string': case 'text': value = this.cast(value, 'boolean') ? value + '' : null break; case 'date': case 'datetime': value = new Date(value); break; case 'int': case 'integer': case 'number': value = ~~value; break; case 'float': value = parseFloat(value); break; case 'smart': value = this.cast(value, this.detect(value)); break; default: throw new Error('Expected valid casting type.'); } return value; }
javascript
{ "resource": "" }
q32957
next_line
train
function next_line() { // Put the next line of source in source_line. If the line contains tabs, // replace them with spaces and give a warning. Also warn if the line contains // unsafe characters or is too damn long. let at; column = 0; line += 1; source_line = lines[line]; if (source_line !== undefined) { at = source_line.search(rx_tab); if (at >= 0) { if (!option.white) { warn_at("use_spaces", line, at + 1); } source_line = source_line.replace(rx_tab, " "); } at = source_line.search(rx_unsafe); if (at >= 0) { warn_at( "unsafe", line, column + at, "U+" + source_line.charCodeAt(at).toString(16) ); } if (option.maxlen && option.maxlen < source_line.length) { warn_at("too_long", line, source_line.length); } else if (!option.white && source_line.slice(-1) === " ") { warn_at( "unexpected_trailing_space", line, source_line.length - 1 ); } } return source_line; }
javascript
{ "resource": "" }
q32958
enroll
train
function enroll(name, role, readonly) { // Enroll a name into the current function context. The role can be exception, // function, label, parameter, or variable. We look for variable redefinition // because it causes confusion. const id = name.id; // Reserved words may not be enrolled. if (syntax[id] !== undefined && id !== "ignore") { warn("reserved_a", name); } else { // Has the name been enrolled in this context? let earlier = functionage.context[id]; if (earlier) { warn( "redefinition_a_b", name, name.id, earlier.line + fudge ); // Has the name been enrolled in an outer context? } else { stack.forEach(function (value) { const item = value.context[id]; if (item !== undefined) { earlier = item; } }); if (earlier) { if (id === "ignore") { if (earlier.role === "variable") { warn("unexpected_a", name); } } else { if ( ( role !== "exception" || earlier.role !== "exception" ) && role !== "parameter" && role !== "function" ) { warn( "redefinition_a_b", name, name.id, earlier.line + fudge ); } } } // Enroll it. functionage.context[id] = name; name.dead = true; name.function = functionage; name.init = false; name.role = role; name.used = 0; name.writable = !readonly; } } }
javascript
{ "resource": "" }
q32959
setAnnotationSets
train
function setAnnotationSets(sets) { annotationSets = sets.map(function(s) { var r = '\\b(' + s.terms.join('|') + ')\\b'; s.re = new RegExp(r, 'mi'); return s; }); }
javascript
{ "resource": "" }
q32960
buildQuery
train
function buildQuery(opts, globalSearch) { var imboQuery = new ImboQuery(); imboQuery.page(opts.page); imboQuery.limit(opts.limit); if (opts.users && globalSearch) { imboQuery.users(opts.users); } if (opts.fields) { imboQuery.fields(opts.fields); } if (opts.sort) { imboQuery.addSorts(opts.sort); } if (opts.metadata) { imboQuery.metadata(opts.metadata); } return imboQuery; }
javascript
{ "resource": "" }
q32961
searchGlobalMetadata
train
function searchGlobalMetadata(query, opts, callback) { if (typeof opts === 'function' && !callback) { callback = opts; opts = {}; } var searchEndpointUrl = this.getResourceUrl({ path: '/images', user: null, query: buildQuery(opts, true).toString() }); request({ method: 'SEARCH', uri: searchEndpointUrl.toString(), json: query, header: { 'User-Agent': 'imboclient-js' }, onComplete: function(err, res, body) { callback( err, body ? body.images : [], body ? body.search : {}, res ); } }); return true; }
javascript
{ "resource": "" }
q32962
granted
train
function granted(data, socket) { return new Promise((resolve, reject) => { setTimeout(() => { logger.debug(`i grant access to ${util.format(data.id)}`); broadcast('available'); let socketNamespace = data.id; let newData = { script: ss.createStream(), inputs: {} }; for (let inputSymbol in data.inputs) { //let filePath = data.inputs[inputSymbol]; //logger.debug(`-->${filePath}`); newData.inputs[inputSymbol] = ss.createStream(); logger.debug(`ssStream emission for input symbol '${inputSymbol}'`); ss(socket).emit(socketNamespace + "/" + inputSymbol, newData.inputs[inputSymbol]); //logger.warn('IeDump from' + socketNamespace + "/" + inputSymbol); //newData.inputs[inputSymbol].pipe(process.stdout) } ss(socket).emit(socketNamespace + "/script", newData.script); //logger.error(`TOTOT2\n${util.format(newData)}`); for (let k in data) { if (k !== 'inputs' && k !== 'script') newData[k] = data[k]; } newData.socket = socket; socket.emit('granted', { jobID: data.id }); resolve(newData); }, 250); }); }
javascript
{ "resource": "" }
q32963
getDecimalDegree
train
function getDecimalDegree(deg, min, sec) { if (min == undefined) min = 0; if (sec == undefined) sec = 0; return deg < 0 ? (Math.abs(deg) + Math.abs(min) / 60 + Math.absabs(sec) / 3600) * -1 : Math.absabs(deg) + Math.absabs(min) / 60 + Math.absabs(sec) / 3600; }
javascript
{ "resource": "" }
q32964
getTrueAngle
train
function getTrueAngle(point) { return Math.atan((minorAxisSquare / majorAxisSquare) * Math.tan(Deg2Rad(point.lat))) * 180 / Math.PI; }
javascript
{ "resource": "" }
q32965
tryParse
train
function tryParse(data) { var json; try { json = JSON.parse(data); } catch (ex) { debug('tryParse exception %s for data %s', ex, data); } return json || data; }
javascript
{ "resource": "" }
q32966
formatFileName
train
function formatFileName(filepath) { var validFilename; validFilename = filepath.replace(/\s/g, options.separator); validFilename = validFilename.replace(/[^a-zA-Z_0-9.]/, ''); validFilename = validFilename.toLowerCase(); return validFilename; }
javascript
{ "resource": "" }
q32967
checkFile
train
function checkFile(fileName, contents) { forbiddenCode.forEach(function(forbiddenItem) { if (contents.indexOf(forbiddenItem) > -1) { /* eslint-disable */ console.log('FAILURE: '.red + 'You left a '.reset + forbiddenItem.yellow + ' in '.reset + fileName.cyan); /* eslint-enable */ errorFound = true; } }); }
javascript
{ "resource": "" }
q32968
fileExists
train
function fileExists(file) { var fileExists = true; try { fs.statSync(file, function(err, stat) { if (err == null) { fileExists = true; } else { fileExists = false; } }); } catch (e) { fileExists = false; } return fileExists; }
javascript
{ "resource": "" }
q32969
cloneNode
train
function cloneNode (n) { var c = { __association_score: n.__association_score, __evidence_count: n.__evidence_count, id: n.id, __id: n.__id, __name: n.__name, target: { id: n.target.id, name: n.target.gene_info.name, symbol: n.target.gene_info.symbol }, disease: cloneDisease(n.disease), association_score: cloneAssociationScore(n.association_score), evidence_count: cloneEvidenceCount(n.evidence_count) }; if (n.is_direct) { c.is_direct = n.is_direct; } return c; }
javascript
{ "resource": "" }
q32970
_tryModuleSync
train
function _tryModuleSync(modulePath, defaultReturnValue) { try { return syncRequire({squashErrors:true}, modulePath.shift()); } catch (err) { } if(!modulePath.length) return defaultReturnValue; return _tryModuleSync(modulePath, defaultReturnValue); }
javascript
{ "resource": "" }
q32971
json
train
function json (options) { var opts = options || {} var limit = typeof opts.limit !== 'number' ? bytes.parse(opts.limit || '100kb') : opts.limit var inflate = opts.inflate !== false var reviver = opts.reviver var strict = opts.strict !== false var type = opts.type || 'application/json' var verify = opts.verify || false if (verify !== false && typeof verify !== 'function') { throw new TypeError('option verify must be function') } // create the appropriate type checking function var shouldParse = typeof type !== 'function' ? typeChecker(type) : type function parse (body) { if (body.length === 0) { // special-case empty json body, as it's a common client-side mistake // TODO: maybe make this configurable or part of "strict" option return {} } if (strict) { var first = firstchar(body) if (first !== '{' && first !== '[') { debug('strict violation') throw new SyntaxError('Unexpected token ' + first) } } debug('parse json') return JSON.parse(body, reviver) } return function jsonParser (req, res, next) { if (req._body) { debug('body already parsed') next() return } req.body = req.body || {} // skip requests without bodies if (!typeis.hasBody(req)) { debug('skip empty body') next() return } debug('content-type %j', req.headers['content-type']) // determine if request should be parsed if (!shouldParse(req)) { debug('skip parsing') next() return } // assert charset per RFC 7159 sec 8.1 var charset = getCharset(req) || 'utf-8' if (charset.substr(0, 4) !== 'utf-') { debug('invalid charset') next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { charset: charset })) return } // read read(req, res, next, parse, debug, { encoding: charset, inflate: inflate, limit: limit, verify: verify }) } }
javascript
{ "resource": "" }
q32972
_hasIndex
train
function _hasIndex(_this, model, key) { // Primary key always hasIndex if(key === 'id') { return true; } var modelDef = _this._models[model]; var retval = (_.isObject(modelDef.properties[key]) && modelDef.properties[key].index) || (_.isObject(modelDef.settings[key]) && modelDef.settings[key].index); return retval; }
javascript
{ "resource": "" }
q32973
register
train
function register() { ko.extenders['searchArray'] = searchArrayExtension; ko.components.register('grid', { template: template, viewModel: viewModel }); }
javascript
{ "resource": "" }
q32974
addStats
train
function addStats(collection, pkg) { var coverageType, stat; for (coverageType in collection) { if (collection.hasOwnProperty(coverageType)) { for (stat in collection[coverageType]) { if (collection[coverageType].hasOwnProperty(stat)) { collection[coverageType][stat] = collection[coverageType][stat] + pkg[coverageType][stat]; } } } } }
javascript
{ "resource": "" }
q32975
deleteStats
train
function deleteStats(collection) { var coverageType; for (coverageType in collection) { if (collection.hasOwnProperty(coverageType)) { if (collection[coverageType].hasOwnProperty("total")) { delete collection[coverageType].total; } if (collection[coverageType].hasOwnProperty("covered")) { delete collection[coverageType].covered; } if (collection[coverageType].hasOwnProperty("skipped")) { delete collection[coverageType].skipped; } } } }
javascript
{ "resource": "" }
q32976
badgeColour
train
function badgeColour(collection, stat, watermarks) { var watermarkType = stat === "overall" ? "lines" : stat; var low = watermarks[watermarkType][0]; var high = watermarks[watermarkType][1]; var mid = (high - low) / 2; var value = collection[stat].pct; if (value < low) { collection[stat].colour = "red"; } else if (value < mid) { collection[stat].colour = "orange"; } else if (value < high) { collection[stat].colour = "yellow"; } else if (value < 100) { collection[stat].colour = "green"; } else { collection[stat].colour = "brightgreen"; } }
javascript
{ "resource": "" }
q32977
computeHash
train
function computeHash(data) { const ha1 = data.ha1 || _computeHash( data.algorithm, [data.username, data.realm, data.password].join(':'), ); const ha2 = _computeHash(data.algorithm, [data.method, data.uri].join(':')); return _computeHash( data.algorithm, [ha1, data.nonce, data.nc, data.cnonce, data.qop, ha2].join(':'), ); }
javascript
{ "resource": "" }
q32978
train
function(req, res) { var url = passport.config.loginRedirect || '/profile'; var statusCode = 302; //303 is more accurate but express redirect() defaults //to 302 so stick to that for consistency if (req.session && req.session.returnTo) { if (req.session.returnToMethod == req.method) { statusCode = 307; } if (req.query.h && req.session.returnTo.indexOf('#') == -1) { url = req.session.returnTo + '#' + req.query.h; } else { url = req.session.returnTo; } delete req.session.returnTo; } return res.redirect(statusCode, url); }
javascript
{ "resource": "" }
q32979
setLogLevel
train
function setLogLevel(level){ level = level > 0 ? level : 0; level = level < 4 ? level : 4; level = parseInt(level); logLevel = level; }
javascript
{ "resource": "" }
q32980
fromCache
train
function fromCache(options) { var filename = options.filename; if (options.cache) { if (filename) { if (cache[filename]) { return cache[filename]; } } else { throw new Error('filename is required when using the cache option'); } } return false; }
javascript
{ "resource": "" }
q32981
cacheTemplate
train
function cacheTemplate(fn, options) { if (options.cache && options.filename) { cache[options.filename] = fn; } }
javascript
{ "resource": "" }
q32982
train
function (cb, text) { var calais = this; if (!calais.validateOptions()) return cb({}, 'Bad options'); if (this._undefinedOrNull(text) || typeof text != 'string' || text.length == 0) text = this.options.content; if (this._undefinedOrNull(text) || typeof text != 'string' || text.length == 0) return cb({}, 'No text given in options or parameter'); var params = { 'Host' : calais.options.apiHost, 'x-ag-access-token' : calais.apiKey, 'x-calais-language' : calais.options.language, 'Content-Type' : calais.options.contentType, 'Accept' : 'application/json', 'Content-Length' : text.length, 'OutputFormat' : 'application/json' } var options = { uri : 'https://' + calais.options.apiHost + calais.options.apiPath, method : 'POST', body : text, headers: params }; //Send the response request(options, function (error, response, calaisData) { if (error) return cb({}, error); if (response === undefined) { return cb({}, 'Undefined Calais response'); } else if (response.statusCode === 200) { if (!calaisData) return cb({}, calais.errors); try { // parse to a Javascript object if requested var result = JSON.parse(calaisData); result = (typeof result === 'string') ? JSON.parse(result) : result; var parsedResult; if (calais.options.parseData) { parsedResult = calais._parseCalaisData(result, calais.options.minConfidence); } else { parsedResult = result; } return cb(parsedResult, calais.errors); } catch(e) { return cb({}, e); } } else return cb({}, 'Request error: ' + (typeof response === 'string' ? response : JSON.stringify(response))); }); }
javascript
{ "resource": "" }
q32983
train
function(url, cb) { var calais = this; if (!calais.validateOptions()) return cb({}, 'Bad options'); //Make sure we were given a URL. if (this._undefinedOrNull(url) || typeof url != 'string' || url.length == 0) return cb({}, 'No URL given.'); //Make sure it's a valid URL. if (!(/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url))) return cb({}, 'Bad URL'); request(url, function(error, response, html) { if (error) return cb({}, error); //Limts to just under 100kb.... html = html.substring(0, 95000); //We can upload the html directly to Calais if we set the contentType as text/html var params = { 'Host' : calais.options.apiHost, 'x-ag-access-token' : calais.apiKey, 'x-calais-language' : calais.options.language, 'Content-Type' : 'text/html', 'Accept' : 'application/json', 'Content-Length' : html.length, 'OutputFormat' : 'application/json' }; var options = { uri : 'https://' + calais.options.apiHost + calais.options.apiPath, method : 'POST', body : html, headers: params }; request(options, function(error, response, calaisData) { if (error) return cb({}, error); if (response === undefined) { return cb({}, 'Undefined Calais response'); } else if (response.statusCode === 200) { if (!calaisData) return cb({}, calais.errors); try { // parse to a Javascript object if requested var result = JSON.parse(calaisData); result = (typeof result === 'string') ? JSON.parse(result) : result; var parsedResult; if (calais.options.parseData) { parsedResult = calais._parseCalaisData(result, calais.options.minConfidence); } else { parsedResult = result; } return cb(parsedResult, calais.errors); } catch(e) { return cb({}, e); } } else return cb({}, 'Request error: ' + (typeof response === 'string' ? response : JSON.stringify(response))); }); }); }
javascript
{ "resource": "" }
q32984
convToNum
train
function convToNum(ipstr) { let ret = 0; let mul = 256*256*256; ipstr.split('.').forEach((numstr)=>{ ret += parseInt(numstr)*mul; mul >>= 8; }); return ret; }
javascript
{ "resource": "" }
q32985
startCheckingArpTable
train
function startCheckingArpTable() { setInterval(()=>{ chkArpTable(); for (const macinfo of Object.values(macs)) { pingNet(macinfo.net, macinfo.ip); } }, CHECK_ARP_TABLE_AND_PING_INTERVAL); // Initial check chkArpTable(); }
javascript
{ "resource": "" }
q32986
getNetworkInterfaces
train
function getNetworkInterfaces() { const ret = {}; for (const macinfo of Object.values(macs)) { if (!macinfo.self) { continue; } ret[macinfo.net] = objCpy(macinfo); } return ret; }
javascript
{ "resource": "" }
q32987
searchNetworkInterface
train
function searchNetworkInterface(ip, networks) { networks = networks || getNetworkInterfaces(); for (const [net, netinfo] of Object.entries(networks)) { const ipnet = netinfo.ip; const mask = netinfo.netmask; if (isNetworkSame(mask, ip, ipnet)) { return net; } } return null; }
javascript
{ "resource": "" }
q32988
getItunesTracks
train
function getItunesTracks(librarypath) { var libraryID; var trackObj = {}; var isTrack = false; var line; var trackCount = 0; var streamIn; var streamOut = new stream_1.Readable; streamOut._read = function () { }; streamIn = fs.createReadStream(librarypath); streamIn.on('error', function () { return streamOut.emit("error", 'The file you selected does not exist'); }); streamIn = byline.createStream(streamIn); /* if (!module.exports.validPath(librarypath)) { streamOut.emit("error", 'Not a valid XML file') } */ streamIn.on('readable', function () { while (null !== (line = streamIn.read())) { if (line.indexOf("<key>Library Persistent ID</key>") > -1) { /* ADD A KEY/VALUE PROPERTY */ var iDString = String(line).match("<key>Library Persistent ID</key><string>(.*)</string>"); libraryID = iDString[1]; } else if (line.indexOf("<dict>") > -1) { /* START A NEW TRACK */ trackObj = {}; isTrack = true; } else if (line.indexOf("<key>") > -1) { /* ADD A PROPERTY TO THE TRACK */ Object.assign(trackObj, module.exports.buildProperty(line)); } else if (line.indexOf("</dict>") > -1) { /* END OF CURRENT TRACK */ if (module.exports.objectIsMusicTrack(trackObj)) { trackObj['Library Persistent ID'] = libraryID; //add extra metadata trackCount++; streamOut.push(JSON.stringify(trackObj)); } isTrack = false; } } }); streamIn.on('end', function () { if (trackCount == 0) streamOut.emit("error", 'No tracks exist in the file'); trackCount = 0; //reset it streamOut.push(null); }); streamIn.on('error', function (err) { streamOut.emit("error", 'Error parsing iTunes XML'); }); return streamOut; }
javascript
{ "resource": "" }
q32989
objectIsMusicTrack
train
function objectIsMusicTrack(obj) { if ((obj.Name || obj.Artist) && !obj['Playlist ID'] && (obj.Kind == ('MPEG audio file' || 'AAC audio file' || 'Matched AAC audio file' || 'Protected AAC audio file' || 'Purchased AAC audio file'))) return true; else return false; }
javascript
{ "resource": "" }
q32990
format
train
function format(err, options) { const error = { message: 'Internal Server Error' }; options = options || {}; if (options.exposeErrors || (err.httpStatusCode && err.httpStatusCode < 500)) { error.message = err.message; if (err.code) error.code = err.code; if (err.validation) error.validation = err.validation; } if (options.exposeErrors) { if (err.stack) error.stack = err.stack.split(/\r?\n/); if (err.info) { Object.keys(err.info).forEach(key => { if (!has(error, key) && has(err.info, key)) error[key] = err.info[key]; }); } } return error; }
javascript
{ "resource": "" }
q32991
validateFileset
train
function validateFileset(fileset, setter) { if (Array.isArray(fileset)) { async.each(fileset, function(path, callback) { if (typeof path === 'string') { callback(); } else { callback(util.format('Invalid path: %s', path)); } }, function(err) { if (err) { console.log(chalk.red(err)); } else { setter(fileset); } }); } else { console.log(chalk.red('Fileset is not an array: %j'), fileset); } }
javascript
{ "resource": "" }
q32992
platoExcludes
train
function platoExcludes() { var excludes = ''; excludeFileset.forEach(function (file) { if (isDirectory(file)) { excludes += file.replace(/\//g, '\/'); } else { excludes += file; } excludes += '|'; }); if (excludes !== '') { return new RegExp(excludes.slice(0, -1)); } else { return null; } }
javascript
{ "resource": "" }
q32993
applyPolyfill
train
function applyPolyfill(ElementClass) { if (ElementClass.prototype.hasOwnProperty('classList')) { return; } Object.defineProperty(ElementClass.prototype, 'classList', { get: lazyDefinePropertyValue('classList', function() { if (!(this instanceof ElementClass)) { throw new Error( '\'get classList\' called on an object that does not implement interface Element.'); } return new DOMTokenList(this, 'className'); }), set: throwError('classList property is read-only'), enumerable: true, configurable: true, }); }
javascript
{ "resource": "" }
q32994
SpyConstructor
train
function SpyConstructor (opts) { Constructor.call(this, opts) // Spy on Constructor functions for (var key in this) { if (this[key] instanceof Function) { this[key] = sinon.spy(this[key]) } } SpyConstructor.instances.push(this) }
javascript
{ "resource": "" }
q32995
text
train
function text(txt) { if(!this.length) { return this; } if(txt === undefined) { return this.dom[0].textContent; } txt = txt || ''; this.each(function(el) { el.textContent = txt; }); return this; }
javascript
{ "resource": "" }
q32996
init
train
function init(path, name) { // {{{2 /** * Class constructor * * @param name {String} Name of HttpContent instance * @param path {String} Path to content * * @method init */ this.modules = {}; this.handlers = {}; this.scripts = []; this.styles = []; this.path = path || Path.dirname(this.O.module.filename); this.name = name || this.O.packageName || this.O.package.packageName; // O.log.debug('Content', this.toString()); Http.addContent(this); this.addFiles && this.addFiles(); }
javascript
{ "resource": "" }
q32997
links
train
function links(data, page, options) { if (!data || !data.length) return; var targets = ['self', 'blank', 'parent', 'top'] , navigation = this; return data.reduce(function reduce(menu, item) { var url = item.href.split('/').filter(String) , active = url.shift(); if (page) active = item.base || url.shift(); item.active = ~navigation[page ? 'page' : 'base'].indexOf(active) ? ' class="active"' : ''; item.target = item.target && ~targets.indexOf(item.target) ? ' target=_' + item.target : ''; return menu + options.fn(item); }, ''); }
javascript
{ "resource": "" }
q32998
train
function(sMatch, text) { for (var i = 0; i < sMatch.matches.length; i++) { var r = sMatch.matches[i]; var found = text.match(r); if (found) { var exact = found[0]; var value = found[1].trim(); var key = sMatch.fields[i]; annoRows.push(annotations.createAnnotation({type: 'valueQuote', annotatedBy: sMatch.name, hasTarget: uri, key: key, value: value, ranges: annotations.createRange({ exact: exact, offset: found.index, selector: ''}) })); } } return annoRows; }
javascript
{ "resource": "" }
q32999
train
function(model, options) { options || (options = {}); model = this._prepareModel(model, options); if (!model) return false; var already = this.getByCid(model) || this.get(model); if (already) throw new Error(["Can't add the same model to a set twice", already.id]); this._byId[model.id] = model; this._byCid[model.cid] = model; var index = options.at != null ? options.at : this.comparator ? this.sortedIndex(model, this.comparator) : this.length; this.models.splice(index, 0, model); model.bind('all', this._onModelEvent); this.length++; if (!options.silent) model.trigger('add', model, this, options); return model; }
javascript
{ "resource": "" }