_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q40000
getBehavioralDirectives
train
function getBehavioralDirectives(appName) { var directives = {}; var me = this; _.each(this.getAppFileNames(appName, 'jng.directives'), function (directiveName) { // if not a JavaScript file, ignore it if (!me.pancakes.utils.isJavaScript(directiveName)) { return; } // get the directive and load it into the directive map var directivePath = 'app/' + appName + '/jng.directives/' + directiveName; var directive = me.pancakes.cook(directivePath, null); directiveName = directiveName.substring(0, directiveName.length - 3).replace('.', '-'); directives[directiveName] = directive; }); return directives; }
javascript
{ "resource": "" }
q40001
getClientDirectives
train
function getClientDirectives(appName) { var directives = []; var me = this; _.each(this.getAppFileNames(appName, 'ng.directives'), function (directiveName) { // if not a JavaScript file, ignore it if (!me.pancakes.utils.isJavaScript(directiveName)) { return; } directiveName = directiveName.substring(0, directiveName.length - 3).replace('.', '-'); directives.push(directiveName); }); return directives; }
javascript
{ "resource": "" }
q40002
getGenericDirective
train
function getGenericDirective(prefix, attrName, filterType, isBind, isFilter) { var directiveName = prefix + attrName.substring(0, 1).toUpperCase() + attrName.substring(1); var config = this.pancakes.cook('config', null); var i18n = this.pancakes.cook('i18n', null); var eventBus = this.pancakes.cook('eventBus', null); var me = this; return function (scope, element, attrs) { var originalValue = attrs[directiveName]; var boundValue = isBind ? me.getNestedValue(scope, originalValue) : originalValue; var value = boundValue; var useSSL, staticFileRoot, status; // if we are using a file filter, add the static file root if (isFilter && filterType === 'file' && config && config.staticFiles) { useSSL = (config[scope.appName] && config[scope.appName].useSSL !== undefined) ? config[scope.appName].useSSL : config.useSSL; staticFileRoot = config.staticFiles.assets; staticFileRoot = (staticFileRoot.charAt(0) === '/') ? staticFileRoot : ((useSSL ? 'https://' : 'http://') + config.staticFiles.assets + '/'); value = staticFileRoot + value; } // else for i18n filter, try to translate else if (isFilter && filterType === 'i18n' && i18n && i18n.translate) { //var cls = require('continuation-local-storage'); //var session = cls.getNamespace('appSession'); //var appName = (session && session.active && session.get('app')) || 'contact'; //var lang = (session && session.active && session.get('lang')) || 'en'; status = {}; value = i18n.translate(value, scope, status); // this is only done when we are in i18nDebug mode which is used to figure out // where we have missing translations if (status.missing) { eventBus.emit('i18n.missing', { lang: status.lang, text: boundValue, appName: status.app, binding: originalValue, directive: directiveName, context: JSON.stringify(element) }); } } if (attrName === 'text') { element.text(value); } else if (attrName === 'class') { attrs.$addClass(value); } else { value = value ? value.replace(/"/g, '') : value; attrs.$set(attrName, value, scope); } // attrName === 'text' ? // element.text(value) : // attrName === 'class' ? // attrs.$addClass(value) : // attrs.$set(attrName, value, scope); }; }
javascript
{ "resource": "" }
q40003
getGenericDirectives
train
function getGenericDirectives() { var directives = {}; var genericDirectives = { 'src': 'file', 'title': 'i18n', 'placeholder': 'i18n', 'popover': 'i18n', 'value': 'i18n', 'alt': 'i18n', 'text': 'i18n', 'id': null, 'type': null, 'class': null }; var me = this; _.each(genericDirectives, function (type, attr) { // no b-class because it is just adding classes one time if (attr !== 'class') { directives['b-' + attr] = me.getGenericDirective('b', attr, null, true, false); } directives['bo-' + attr] = me.getGenericDirective('bo', attr, null, true, false); if (type) { directives['f-' + attr] = me.getGenericDirective('f', attr, type, false, true); directives['fo-' + attr] = me.getGenericDirective('fo', attr, type, false, true); directives['bf-' + attr] = me.getGenericDirective('bf', attr, type, true, true); directives['bfo-' + attr] = me.getGenericDirective('bfo', attr, type, true, true); } }); return directives; }
javascript
{ "resource": "" }
q40004
addDirectivesToJangular
train
function addDirectivesToJangular(directives) { _.each(directives, function (directive, directiveName) { jangular.addDirective(directiveName, directive); }); }
javascript
{ "resource": "" }
q40005
f_rol_tumu
train
function f_rol_tumu(_tahta_id) { return result.dbQ.smembers(result.kp.tahta.ssetOzelTahtaRolleri(_tahta_id, true)) .then(function (_rol_idler) { return f_rol_id(_rol_idler); }); }
javascript
{ "resource": "" }
q40006
getLitmusForModule
train
function getLitmusForModule (module) { if (isLitmus(module)) { return module; } if (module.test && isLitmus(module.test)) { return module.test; } throw new Error('litmus: expected module to export litmus.Test or litmus.Suite'); }
javascript
{ "resource": "" }
q40007
train
function (elbName, cb) { query(elbName, function (err, data) { if (err) return cb(err); var result = []; data.Instances.map(function (item) { result.push(item.InstanceId); }); cb(undefined, result); }); }
javascript
{ "resource": "" }
q40008
isEventValid
train
function isEventValid (comp, type) { // if a component has aleary triggered 'appear' event, then // the 'appear' even† can't be triggered again utill the // 'disappear' event triggered. if (appearEvts.indexOf(type) <= -1) { return true } if (comp._appear === undefined && type === 'disappear') { return false } let res if (comp._appear === undefined && type === 'appear') { res = true } else { res = type !== comp._appear } res && (comp._appear = type) return res }
javascript
{ "resource": "" }
q40009
splitIntoSlabs
train
function splitIntoSlabs(str) { var slabs = str.split('<!-- TEXTBLOCK -->'); return slabs.map(function(val, index, array) { if (index % 2 == 1) { var rawAttr = val.match(/<code>(.*)<\/code>/); var attrs = JSON.parse(decodeURI(rawAttr[1])); return attrs; } else { return val; } }); }
javascript
{ "resource": "" }
q40010
train
function(source, format, ctx) { if (inputFormats.hasOwnProperty(format)) { return inputFormats[format](source, ctx); } else { throw new Error('invalid format to make a text block from: ' + source.format); } }
javascript
{ "resource": "" }
q40011
train
function(source, ctx) { if (source.hasOwnProperty('format')) { if (validateFormats.hasOwnProperty(source.format)) { return validateFormats[source.format](source, ctx); } else { throw new Error('invalid format for textblock: ' + source.format); } } throw new Error('invalid format for textblock (did you pass an Object in?)'); }
javascript
{ "resource": "" }
q40012
train
function(source, type) { if (source.hasOwnProperty('format')) { if (source.format !== type) { if (source.format === 'section') { var blocks = []; source.blocks.forEach(function(val, index, array) { var block = deleteTextBlockFormat(val, type); if (block) { blocks.push(block); } }); if (blocks.length) { return {format: 'section', blocks: blocks}; } else { return null; } } else { return source; } } else { return null; } } throw new Error('invalid format for textblock (did you pass an Object in?)'); }
javascript
{ "resource": "" }
q40013
train
function(blocks) { var blockarr = blocks; if (!(blockarr instanceof Array)) { blockarr = [blockarr]; } return {format: 'section', blocks: blockarr}; }
javascript
{ "resource": "" }
q40014
train
function(block, pos, ctx, callback) { if (block.hasOwnProperty('htmlslabs')) { outputSlabs(block.htmlslabs, ctx, callback); } else { if (formats.hasOwnProperty(block.format)) { formats[block.format](block, pos, ctx, callback); } else { callback(new Error('unknown format: ' + block.format)); } } }
javascript
{ "resource": "" }
q40015
train
function(block) { if (block.hasOwnProperty('htmlslabs')) { return outputSlabsAsText(block.htmlslabs); } else { if (block.format === 'section') { return block.blocks.reduce(function(previousValue, currentValue, currentIndex, array) { return previousValue + extractTextBlockText(currentValue); }, ''); } else { return ''; } } }
javascript
{ "resource": "" }
q40016
execute
train
function execute(req, res) { var scanner = new Scanner( req.db.getKeys(), req.info.cursor, req.info.pattern, req.info.count); scanner.scan(req, res); }
javascript
{ "resource": "" }
q40017
validate
train
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); var offset = info.exec.offset , arg = args[offset]; if(args.length > offset + 4) { throw new CommandArgLength(info.exec.definition.name); } // cursor already parsed to integer by numeric validation info.cursor = args[offset - 1] //console.dir(args); if(arg !== undefined) { arg = (('' + arg).toLowerCase()); while(arg !== undefined) { //console.dir(arg); if(arg !== Constants.SCAN.MATCH && arg !== Constants.SCAN.COUNT) { throw CommandSyntax; }else if(arg === Constants.SCAN.MATCH) { /* istanbul ignore next: really tough to get a pattern compile error! */ try { info.pattern = Pattern.compile(args[offset + 1]); }catch(e) { throw PatternCompile; } // should be on count arg }else{ info.count = parseInt('' + args[offset + 1]); if(isNaN(info.count)) { throw IntegerRange; } } offset+=2; arg = args[offset] ? '' + args[offset] : undefined; } } }
javascript
{ "resource": "" }
q40018
singletco
train
function singletco(partition) { var select = function select(compare, a, i, j, k) { while (true) { if (j - i < 2) return; var p = partition(compare, a, i, j); if (k < p) j = p;else if (k > p) i = p + 1;else return; } }; return select; }
javascript
{ "resource": "" }
q40019
BlurXFilter
train
function BlurXFilter() { core.AbstractFilter.call(this, // vertex shader fs.readFileSync(__dirname + '/blurX.vert', 'utf8'), // fragment shader fs.readFileSync(__dirname + '/blur.frag', 'utf8'), // set the uniforms { strength: { type: '1f', value: 1 } } ); /** * Sets the number of passes for blur. More passes means higher quaility bluring. * * @member {number} * @memberof BlurXFilter# * @default 1 */ this.passes = 1; this.strength = 4; }
javascript
{ "resource": "" }
q40020
ActivityTask
train
function ActivityTask(task) { if (!(this instanceof ActivityTask)) { return new ActivityTask(task); } this.input = {}; if (task.config.input) { this.input = JSON.parse(task.config.input); } // Depending on the language of the Decider impl, this can be an Array or Object // This is a big assumption, maybe make this configurable if (Array.isArray(this.input)) { this.input = this.input[0]; } this.activityId = task.config.activityId; this.activityType = task.config.activityType; this.startedEventId = task.config.startedEventId; this.taskToken = task.config.taskToken; this.workflowExecution = task.config.workflowExecution; this._task = task; // Register a hearbeat callback every 10 seconds this.hearbeatCount = 0; this.heartbeatTimer = setInterval(function () { var self = this; self._task.recordHeartbeat( { activity: self.activityType.name, id: self.activityId, count: self.hearbeatCount++ }, function (err) { if (err) { winston.log('debug', 'Heartbead failed for task: %s (%s) due to:', self.activityType.name, self.activityId, err); } }); }.bind(this), 10000); }
javascript
{ "resource": "" }
q40021
backboneOptsAsProps
train
function backboneOptsAsProps(subject, opts) { if (!opts) { opts = subject.options } subject.mergeOptions(subject.options, _.keys(opts)); //removing form view.options the options that ve been merged above //so if we use view.getOption("opt") will return the merged opt and not the opt in view.options boject subject.options=_.omit(subject.options,_.keys(opts)) console.log("opts mergerged for ",subject); }
javascript
{ "resource": "" }
q40022
omitBackboneOptsAsProps
train
function omitBackboneOptsAsProps(subject, omit) { console.log("omitBackboneOptsAsProps:") console.log(subject, subject.options, omit, _.omit(subject.options, omit)) backboneOptsAsProps(subject, _.omit(subject.options, omit)) }
javascript
{ "resource": "" }
q40023
kappInit
train
function kappInit(subject, callback) { //if expose option is added we expose this view console.log("kappInit:", subject) if (subject.getOption("expose_as")) { console.log("kappInit: found exposeAs option " + subject.getOption("expose_as")) subject.exposeAs(subject.getOption("expose_as")) } //as backbone has its owne method to bind a model and collections to views we just //avoid to merge it to the object atributes by this way omitBackboneOptsAsProps(subject, ['model', 'collection']) //giving the replaceable regions to the view if (typeof subject._addReplaceableRegions === "function") { subject._addReplaceableRegions(); }; if (typeof callback === "function") { callback() } }
javascript
{ "resource": "" }
q40024
lang
train
function lang(key, source) { //first we retrive the lang value of the root of the DOM var LANG = document.documentElement.lang; //console.log(source) //console.log(LANG+' '+key+' - '+source[LANG][key]); if (_.isObject(source) && _.isObject(source[LANG]) && _.isString(source[LANG][key])) { return source[LANG][key] } else { return key } }
javascript
{ "resource": "" }
q40025
expose
train
function expose(subject, name) { //console.log(window[name]) if (subject.isRendered()) { exposer(subject, name); } else { subject.on("attach", function () { exposer(subject, name); }) } }
javascript
{ "resource": "" }
q40026
commutate
train
function commutate(key, list) { _.each(list, function (v, k, l) { if (k === key) { l[key] = true } if (v === true && k !== key) { l[k] = false } }) }
javascript
{ "resource": "" }
q40027
Preprocessor
train
function Preprocessor(config, logger) { const log = logger.create('preprocessor.gzip'); return (content, file, done) => { const originalSize = content.length; // const contentBuffer = Buffer.isBuffer(content) ? content : Buffer.from(content); zlib.gzip(content, (err, gzippedContent) => { if (err) { log.error(err); done(err); return; } // eslint-disable-next-line no-param-reassign file.encodings.gzip = gzippedContent; log.info(`compressed ${file.originalPath} [${util.bytesToSize(originalSize)} -> ${util.bytesToSize(gzippedContent.length)}]`); done(null, content); }); }; }
javascript
{ "resource": "" }
q40028
scrollPage
train
function scrollPage(to, offset, callback) { if ( offset === void 0 ) offset = 0; var startTime; var duration = 500; var startPos = window.pageYOffset; var endPos = ~~(to.getBoundingClientRect().top - offset); var scroll = function (timestamp) { var elapsed; startTime = startTime || timestamp; elapsed = timestamp - startTime; document.body.scrollTop = document.documentElement.scrollTop = easeInOutCubic(elapsed, startPos, endPos, duration); if (elapsed < duration) { requestAnimationFrame(scroll); } else if (callback) { callback.call(to); } }; requestAnimationFrame(scroll); }
javascript
{ "resource": "" }
q40029
$$
train
function $$(els) { return els instanceof NodeList ? Array.prototype.slice.call(els) : els instanceof HTMLElement ? [els] : typeof els === 'string' ? Array.prototype.slice.call(document.querySelectorAll(els)) : []; }
javascript
{ "resource": "" }
q40030
requestHandler
train
function requestHandler (method) { return function (req, res, next) { method.call(this, req, responseHandler(res, next)); }.bind(this); }
javascript
{ "resource": "" }
q40031
responseHandler
train
function responseHandler (res, next) { return function (err, message) { if (err || !message) { next(err); } else { res.send(message); } } }
javascript
{ "resource": "" }
q40032
getPasswordObj
train
function getPasswordObj (values, keys) { var passwordObj = {}; (keys || Object.keys(values)).forEach(function (key) { passwordObj[values[key].password] = key; }); return passwordObj; }
javascript
{ "resource": "" }
q40033
getResetterObj
train
function getResetterObj (values, keys) { var resetterObj = {}; (keys || Object.keys(values)).forEach(function (key) { if (values[key].resetter) { resetterObj[values[key].resetter] = key; } }); return resetterObj; }
javascript
{ "resource": "" }
q40034
_first_split
train
function _first_split(character, string){ var retlist = null; var eq_loc = string.indexOf(character); if( eq_loc == 0 ){ retlist = ['', string.substr(eq_loc +1, string.length)]; }else if( eq_loc > 0 ){ var before = string.substr(0, eq_loc); var after = string.substr(eq_loc +1, string.length); retlist = [before, after]; }else{ retlist = ['', '']; } return retlist; }
javascript
{ "resource": "" }
q40035
train
function(str, lim, suff){ var ret = str; var limit = 10; if( lim ){ limit = lim; } var suffix = ''; if( suff ){ suffix = suff; } if( str.length > limit ){ ret = str.substring(0, (limit - suffix.length)) + suffix; } return ret; }
javascript
{ "resource": "" }
q40036
train
function(older_hash, newer_hash){ if( ! older_hash ){ older_hash = {}; } if( ! newer_hash ){ newer_hash = {}; } var ret_hash = {}; function _add (val, key){ ret_hash[key] = val; } each(older_hash, _add); each(newer_hash, _add); return ret_hash; }
javascript
{ "resource": "" }
q40037
train
function(in_thing, filter_function, sort_function){ var ret = []; // Probably an not array then. if( typeof(in_thing) === 'undefined' ){ // this is a nothing, to nothing.... }else if( typeof(in_thing) != 'object' ){ throw new Error('Unsupported type in bbop.core.pare: ' + typeof(in_thing) ); }else if( us.isArray(in_thing) ){ // An array; filter it if filter_function is defined. if( filter_function ){ each(in_thing, function(item, index){ if( filter_function(item, index) ){ // filter out item if true }else{ ret.push(item); } }); }else{ each(in_thing, function(item, index){ ret.push(item); }); } }else if( us.isFunction(in_thing) ){ // Skip is function (which is also an object). }else if( us.isObject(in_thing) ){ // Probably a hash; filter it if filter_function is defined. if( filter_function ){ each(in_thing, function(val, key){ if( filter_function(key, val) ){ // Remove matches to the filter. }else{ ret.push(val); } }); }else{ each(in_thing, function(val, key){ ret.push(val); }); } }else{ // No idea what this is--skip. } // For both: sort if there is anything. if( ret.length > 0 && sort_function ){ ret.sort(sort_function); } return ret; }
javascript
{ "resource": "" }
q40038
train
function(iobj, interface_list){ var retval = true; each(interface_list, function(iface){ //print('|' + typeof(in_key) + ' || ' + typeof(in_val)); //print('|' + in_key + ' || ' + in_val); if( typeof(iobj[iface]) == 'undefined' && typeof(iobj.prototype[iface]) == 'undefined' ){ retval = false; throw new Error(_what_is(iobj) + ' breaks interface ' + iface); } }); return retval; }
javascript
{ "resource": "" }
q40039
train
function(qargs){ var mbuff = []; for( var qname in qargs ){ var qval = qargs[qname]; // null is technically an object, but we don't want to render // it. if( qval != null ){ if( typeof qval == 'string' || typeof qval == 'number' ){ // Is standard name/value pair. var nano_buffer = []; nano_buffer.push(qname); nano_buffer.push('='); nano_buffer.push(qval); mbuff.push(nano_buffer.join('')); }else if( typeof qval == 'object' ){ if( typeof qval.length != 'undefined' ){ // Is array (probably). // Iterate through and double on. for(var qval_i = 0; qval_i < qval.length ; qval_i++){ var nano_buff = []; nano_buff.push(qname); nano_buff.push('='); nano_buff.push(qval[qval_i]); mbuff.push(nano_buff.join('')); } }else{ // // TODO: The "and" case is pretty much like // // the array, the "or" case needs to be // // handled carefully. In both cases, care will // // be needed to show which filters are marked. // Is object (probably). // Special "Solr-esque" handling. for( var sub_name in qval ){ var sub_vals = qval[sub_name]; // Since there might be an array down there, // ensure that there is an iterate over it. if( _what_is(sub_vals) != 'array' ){ sub_vals = [sub_vals]; } each(sub_vals, function(sub_val){ var nano_buff = []; nano_buff.push(qname); nano_buff.push('='); nano_buff.push(sub_name); nano_buff.push(':'); if( typeof sub_val !== 'undefined' && sub_val ){ // Do not double quote strings. // Also, do not requote if we already // have parens in place--that // indicates a complicated // expression. See the unit tests. var val_is_a = _what_is(sub_val); if( val_is_a == 'string' && sub_val.charAt(0) == '"' && sub_val.charAt(sub_val.length -1) == '"' ){ nano_buff.push(sub_val); }else if( val_is_a == 'string' && sub_val.charAt(0) == '(' && sub_val.charAt(sub_val.length -1) == ')' ){ nano_buff.push(sub_val); }else{ nano_buff.push('"' + sub_val + '"'); } }else{ nano_buff.push('""'); } mbuff.push(nano_buff.join('')); }); } } }else if( typeof qval == 'undefined' ){ // This happens in some cases where a key is tried, but no // value is found--likely equivalent to q="", but we'll // let it drop. // var nano_buff = []; // nano_buff.push(qname); // nano_buff.push('='); // mbuff.push(nano_buff.join('')); }else{ throw new Error("bbop.core.get_assemble: unknown type: " + typeof(qval)); } } } return mbuff.join('&'); }
javascript
{ "resource": "" }
q40040
train
function(len){ var random_base = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ]; var length = len || 10; var cache = new Array(); for( var ii = 0; ii < length; ii++ ){ var rbase_index = Math.floor(Math.random() * random_base.length); cache.push(random_base[rbase_index]); } return cache.join(''); }
javascript
{ "resource": "" }
q40041
train
function(url){ var retlist = []; // Pull parameters. var tmp = url.split('?'); var path = ''; var parms = []; if( ! tmp[1] ){ // catch bad url--nothing before '?' parms = tmp[0].split('&'); }else{ // normal structure path = tmp[0]; parms = tmp[1].split('&'); } // Decompose parameters. each(parms, function(p){ var c = _first_split('=', p); if( ! c[0] && ! c[1] ){ retlist.push([p]); }else{ retlist.push(c); } }); return retlist; }
javascript
{ "resource": "" }
q40042
train
function(str){ var retstr = str; if( ! us.isUndefined(str) && str.length > 2 ){ var end = str.length -1; if( str.charAt(0) == '"' && str.charAt(end) == '"' ){ retstr = str.substr(1, end -1); } } return retstr; }
javascript
{ "resource": "" }
q40043
train
function(str, delimiter){ var retlist = null; if( ! us.isUndefined(str) ){ if( us.isUndefined(delimiter) ){ delimiter = /\s+/; } retlist = str.split(delimiter); } return retlist; }
javascript
{ "resource": "" }
q40044
insertRight
train
function insertRight(parent, node) { var index = parent.length - 1; parent[index] = node; parent.sizes[index] = (0, _util.length)(node) + (index > 0 ? parent.sizes[index - 1] : 0); }
javascript
{ "resource": "" }
q40045
splitTemplate
train
function splitTemplate (template) { if (!template) { return [] } return split(template).filter((seg) => seg !== '' && seg !== undefined) }
javascript
{ "resource": "" }
q40046
createHeader
train
function createHeader (type, size) { var header = new Buffer(8); header.writeUInt8(type, 0); header.writeUInt32BE(size, 4); return header; }
javascript
{ "resource": "" }
q40047
validateArgs
train
function validateArgs (type, payload) { if (!type) { return new Error('type is required'); } if (!payload) { return new Error('payload is required'); } if (!isNumber(type)) { return new Error('type must be a number'); } if (!isBuffer(payload) && !isString(payload)) { return new Error('payload must be buffer or string'); } if (type > 3) { return new Error('type must be a number less than 3'); } }
javascript
{ "resource": "" }
q40048
sync
train
function sync(fn) { return function(done) { var res = isGenerator(fn) ? co(fn) : fn(done); if (isPromise(res)) { res.then(function(){ done(); }, done); } else { fn.length || done(); } }; }
javascript
{ "resource": "" }
q40049
train
function(regex){ //if it isn't global, `exec()` will not start at `lastIndex` if(!regex.global) regex.compile(regex.source, flags(regex)); regex.lastIndex = this.position; var m = regex.exec(this.source); //all matches must start at the current position. if(m && m.index!=this.position){ return null; } if(m) this.position += m[0].length; return m; }
javascript
{ "resource": "" }
q40050
get
train
function get(tree, i) { if (i < 0 || i >= tree.size) { return undefined; } var offset = (0, _util.tailOffset)(tree); if (i >= offset) { return tree.tail[i - offset]; } return (0, _util.getRoot)(i, tree.root); }
javascript
{ "resource": "" }
q40051
formatjson
train
function formatjson(pis) { return pis.map(function(pi) { var newpi = {}; newpi[pi.tag] = pi.att; return newpi; }); }
javascript
{ "resource": "" }
q40052
enumerate
train
function enumerate(collection) { if (isObject(collection)) { if (collection instanceof Map) { return enumerateMap(collection) } else if (isIterable(collection)) { return enumerateIterable(collection) } else { return enumerateObject(collection) } } else { throw new TypeError("Object cannot be enumerated") } }
javascript
{ "resource": "" }
q40053
sightread
train
function sightread(element, childRegistry) { if (!element || element === document) element = window; if (!childRegistry && !getChildRegistry(element)) return; // Clear the child registry. if (!childRegistry) { element.__private__.childRegistry = {}; childRegistry = getChildRegistry(element); } element = (element === window) ? document.body : (element.shadowRoot ? element.shadowRoot : element); assert(element, 'Element is invalid. Too early to sightread?'); const n = element.childNodes.length; for (let i = 0; i < n; i++) { let e = element.childNodes[i]; if (!(e instanceof Node)) continue; if (addToChildRegistry(childRegistry, e)) { if (!isCustomElement(e)) { if (!e.__private__) e.__private__ = {}; if (!e.__private__.childRegistry) e.__private__.childRegistry = {}; sightread(e); } } else { sightread(e, childRegistry); } } }
javascript
{ "resource": "" }
q40054
lintStyles
train
function lintStyles(conf, undertaker) { const sassSrc = path.join(conf.themeConfig.root, conf.themeConfig.sass.src, '**', '*.scss'); let stylelintConf = { config: require('./stylelint.config'), reporters: [{ formatter: 'string', console: true }], failAfterError: conf.productionMode }; // If there are any stylelint overrides, then apply them now. if (conf.themeConfig.sass.hasOwnProperty('stylelint')) { stylelintConf = merge(stylelintConf, conf.themeConfig.sass.stylelint); } return undertaker.src(sassSrc) .pipe(stylelint(stylelintConf)); }
javascript
{ "resource": "" }
q40055
render
train
function render(history, routes, store) { const resolve = resolver(routes); return function(location) { resolve(location) .then(config => { renderPage(config.page(store, history), routes); const actionParams = config.matchRoute(location.pathname).params; config.driverInstance.dispatchAction(store.dispatch, actionParams); }) .catch(error => resolve({location, error}) .then(errorConfig => renderPage(errorConfig.page(store, history)))); } }
javascript
{ "resource": "" }
q40056
resolver
train
function resolver(routes) { return async function(context) { const uri = context.error ? '/error' : context.pathname; return routes.find(route => route.matchRoute(uri)); } }
javascript
{ "resource": "" }
q40057
Connection
train
function Connection(conn) { if(!(this instanceof Connection)) { return new Connection(conn); } var self = this; if(!conn) { throw new TypeError("no connection set"); } self._connection = conn; }
javascript
{ "resource": "" }
q40058
train
function(opts) { opts = opts || {}; this.root = opts.path; this.interval = opts.interval || DEFAULT_INTERVAL; }
javascript
{ "resource": "" }
q40059
MySQL
train
function MySQL(config) { var self = this; config = config || {}; config.host = config.host || 'localhost'; config.port = config.port || 3306; this.className = this.constructor.name; this.config = config; // Set client this.client = mysql.createConnection(config); // Assign storage if (typeof config.storage == 'string') { this.storage = app.getResource('storages/' + config.storage); } else if (config.storage instanceof protos.lib.storage) { this.storage = config.storage; } // Set db this.db = config.database; // Only set important properties enumerable protos.util.onlySetEnumerable(this, ['className', 'db']); }
javascript
{ "resource": "" }
q40060
ANSIState
train
function ANSIState(legacy) { var feed = '', last_match = '', stream_match = [], _this = this; PassThrough.call(this); this.attrs = {}; this.reset(); this.is_reset = false; this.setEncoding('utf8'); this.on('data', function(chunk) { feed += chunk; if (feed.indexOf('\033') === -1) { feed = ''; } else { stream_match = feed.match(color_regex); if (stream_match.length > 0) { last_match = stream_match[stream_match.length - 1]; feed = feed.slice(feed.lastIndexOf(last_match) + last_match.length); _this.updateWithArray(stream_match); } } }); if (legacy !== undefined) { this.update(legacy); } }
javascript
{ "resource": "" }
q40061
initClickEvent
train
function initClickEvent (tabheader) { const box = tabheader.box box.addEventListener('click', function (evt) { let target = evt.target if (target.nodeName === 'UL') { return } if (target.parentNode.nodeName === 'LI') { target = target.parentNode } const floor = target.getAttribute('data-floor') /* eslint-disable eqeqeq */ if (tabheader.data.attr.selectedIndex == floor) { // Duplicated clicking, not to trigger select event. return } /* eslint-enable eqeqeq */ fireEvent(target, 'select', { index: floor }) }) }
javascript
{ "resource": "" }
q40062
doScroll
train
function doScroll (node, val, finish) { if (!val) { return } if (finish === undefined) { finish = Math.abs(val) } if (finish <= 0) { return } setTimeout(function () { if (val > 0) { node.scrollLeft += 2 } else { node.scrollLeft -= 2 } finish -= 2 doScroll(node, val, finish) }) }
javascript
{ "resource": "" }
q40063
getScrollVal
train
function getScrollVal (rect, node) { const left = node.previousSibling const right = node.nextSibling let scrollVal // process left-side element first. if (left) { const leftRect = left.getBoundingClientRect() // only need to compare the value of left. if (leftRect.left < rect.left) { scrollVal = leftRect.left return scrollVal } } if (right) { const rightRect = right.getBoundingClientRect() // compare the value of right. if (rightRect.right > rect.right) { scrollVal = rightRect.right - rect.right return scrollVal } } // process current node, from left to right. const nodeRect = node.getBoundingClientRect() if (nodeRect.left < rect.left) { scrollVal = nodeRect.left } else if (nodeRect.right > rect.right) { scrollVal = nodeRect.right - rect.right } return scrollVal }
javascript
{ "resource": "" }
q40064
fireEvent
train
function fireEvent (element, type, data) { const evt = document.createEvent('Event') evt.data = data for (const k in data) { if (data.hasOwnProperty(k)) { evt[k] = data[k] } } // need bubble. evt.initEvent(type, true, true) element.dispatchEvent(evt) }
javascript
{ "resource": "" }
q40065
getResolveHandlers
train
function getResolveHandlers(appName, routes, options) { var resolveHandlers = {}; var me = this; _.each(routes, function (route) { // if no route name, don't do anything if (!route.name) { return; } // else generate the UI part based on the name var uipart = me.getUIPart(appName, route); // if there is no model return without doing anything if (!uipart.model) { return; } var transOpts = _.extend({ raw: true, defaults: uipart.defaults, isClient: true }, options); // else we want to generate the initial model module resolveHandlers[route.name] = _.isFunction(uipart.model) ? me.transformers.basic.transform(uipart.model, transOpts) : JSON.stringify(uipart.model); }); return resolveHandlers || {}; }
javascript
{ "resource": "" }
q40066
getUIPart
train
function getUIPart(appName, route) { var rootDir = this.pancakes.getRootDir(); var filePath = path.join(rootDir, 'app', appName, 'pages', route.name + '.page.js'); return this.loadUIPart(appName, filePath); }
javascript
{ "resource": "" }
q40067
execute
train
function execute(req, res) { // setup the transaction req.conn.transaction = new Transaction(); res.send(null, Constants.OK); }
javascript
{ "resource": "" }
q40068
train
function () { obj.set('exploded', currentExplode + (step * frame) ); RGraph.clear(obj.canvas); RGraph.redrawCanvas(obj.canvas); if (frame++ < frames) { RGraph.Effects.updateCanvas(iterator); } else { callback(obj); } }
javascript
{ "resource": "" }
q40069
Route
train
function Route(path, options) { options = options || {}; this.path = path; this.method = 'GET'; this.regexp = pathtoRegexp(path , this.keys = [] , options.sensitive , options.strict); }
javascript
{ "resource": "" }
q40070
insert
train
function insert (builder, node) { finishPending (builder); appendNode (builder, spec.insertNode (node [1])); }
javascript
{ "resource": "" }
q40071
list
train
function list (builder, node) { finishPending (builder); var key = node [1]; var sub = subBuilder (builder); dispatch.nodes (sub, builder.dispatch, node, 2, node.length); var template = getTemplate (sub); appendNode (builder, spec.listNode (key, template)); }
javascript
{ "resource": "" }
q40072
CFClient
train
function CFClient(config) { if (!(config instanceof CFConfig)) { throw CFClientException( new Error('Given tokens must be an instance of CFConfig'), 'tokens must be an instance of CFConfig that contains: "protocol", "host", "username", "password", "skipSslValidation'); } this.config = config; this.infoData = null; this.client = null; }
javascript
{ "resource": "" }
q40073
CFConfig
train
function CFConfig(config) { const cf = this; extend(extend(cf, { protocol: 'http', host: 'api.bosh-lite.com', //port : null, // omitted to let it be based on config or protocol username: 'admin', password: 'admin', skipSslValidation: false }), config); cf.port = calculatePort(cf.port, cf.protocol); if (cf.skipSslValidation instanceof String) { cf.skipSslValidation = ('true' === cf.skipSslValidation); } }
javascript
{ "resource": "" }
q40074
demo_plugin
train
function demo_plugin (opts) { // adds an emit plugin. Emit plugins are called on regular intervals and have // the opertunity to add to the payload being sent to collectors. Data sent // from emit plugins should not require tagging, and should be map ready. this.add({role: 'metrics', hook: 'emit'}, emit) // adds a tag plugin. When inbound data is missing a source:'name' pair the // data is sent to tag plugins for identification and sanitation. Tag plugins // allow data to be standardised enough for map plugins to match on the data. this.add({role: 'metrics', hook: 'tag'}, tag) // adds a map plugin. Maps recieve data once per payload via sources. A // map can additionally match on source:'' for granularity. Maps emit // arrarys of one or more metrics. this.add({role: 'metrics', hook: 'map'}, map) // adds a sink plugin. Metrics are sent to sinks one at a time. A sink // can additionally match on source:'' and name: '' for granularity. A // sink does not emit data but may persist or otherwise store metrics. this.add({role: 'metrics', hook: 'sink'}, sink) // Tagging just means returning a source and payload, it allows // plugins that understand the data to tag it for themselves. This // means inbound data does not need to be modified at source function tag (msg, done) { var clean_data = { source: 'demo-plugin', payload: msg.payload } done(null, clean_data) } // Map plugins return arrays of metrics. The only required fields are // source and name. All other fields depend on the sink you want to use. // Note that the fields below represent our 'plugin' standard. function map (msg, done) { var metric = { source: msg.source, name: 'my-metric', values: {val: msg.payload.val}, tags: {tag: msg.payload.tag} } done(null, [metric]) } // On interval, Vidi: Metrics will call all emitters and ask for data. // Multiple points of data can be sent in a single emit. function emit (msg, done) { var raw_data = [ {source: 'demo-plugin', payload: {val: 1, tag: 'foo'}}, {val: 2, tag: 'foo'} ] done(null, raw_data) } // A sink simply does something with each metric it gets. In our case // we are logging to the console but you can do anything you like with it. function sink (msg, done) { var metric = msg.metric var as_text = JSON.stringify(metric, null, 1) console.log(as_text) done() } // Seneca requires you return a plugin name return 'demo-plugin' }
javascript
{ "resource": "" }
q40075
tag
train
function tag (msg, done) { var clean_data = { source: 'demo-plugin', payload: msg.payload } done(null, clean_data) }
javascript
{ "resource": "" }
q40076
map
train
function map (msg, done) { var metric = { source: msg.source, name: 'my-metric', values: {val: msg.payload.val}, tags: {tag: msg.payload.tag} } done(null, [metric]) }
javascript
{ "resource": "" }
q40077
sink
train
function sink (msg, done) { var metric = msg.metric var as_text = JSON.stringify(metric, null, 1) console.log(as_text) done() }
javascript
{ "resource": "" }
q40078
ErrorLocked
train
function ErrorLocked (message) { Error.call(this); // Add Information this.name = 'ErrorLocked'; this.type = 'client'; this.status = 423; if (message) { this.message = message; } }
javascript
{ "resource": "" }
q40079
cache
train
function cache(options, compiled) { // cachable if (compiled && options.filename && options.cache) { delete templates[options.filename]; cacheStore[options.filename] = compiled; return compiled; } // check cache if (options.filename && options.cache) { return cacheStore[options.filename]; } return compiled; }
javascript
{ "resource": "" }
q40080
store
train
function store(path, options) { var str = templates[path]; var cached = options.cache && str && typeof str === 'string'; // cached (only if cached is a string and not a compiled template function) if (cached) return str; // store str = options.str; // remove extraneous utf8 BOM marker str = str.replace(/^\uFEFF/, ''); if (options.cache) { templates[path] = str; } return str; }
javascript
{ "resource": "" }
q40081
set
train
function set(name, value) { // if no value then remove if (!value) { remove(name); return; } if (localStorage) { try { localStorage.setItem(name, value); } catch (ex) {} } _.isFunction($cookies.put) ? $cookies.put(name, value, { domain: cookieDomain }) : $cookies[name] = value; }
javascript
{ "resource": "" }
q40082
get
train
function get(name) { var value = (_.isFunction($cookies.get) ? $cookies.get(name) : $cookies[name]); if (!value && localStorage) { try { value = localStorage.getItem(name); } catch (ex) {} if (value) { set(name, value); } } return value; }
javascript
{ "resource": "" }
q40083
camelcase
train
function camelcase(val) { if (!is_1.isValue(val)) return null; var result = val.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[A-Z]|\b\w|\s+/g, function (m, i) { if (+m === 0 || /(\.|-|_)/.test(m)) return ''; return i === 0 ? m.toLowerCase() : m.toUpperCase(); }); return result.charAt(0).toLowerCase() + result.slice(1); }
javascript
{ "resource": "" }
q40084
capitalize
train
function capitalize(val) { if (!is_1.isValue(val)) return null; val = val.toLowerCase(); return "" + val.charAt(0).toUpperCase() + val.slice(1); }
javascript
{ "resource": "" }
q40085
padLeft
train
function padLeft(val, len, offset, char) { /* istanbul ignore if */ if (!is_1.isValue(val) || !is_1.isString(val)) return null; // If offset is a string // count its length. if (is_1.isString(offset)) offset = offset.length; char = char || ' '; var pad = ''; while (len--) { pad += char; } if (offset) return padLeft('', offset, null, char) + pad + val; return pad + val; }
javascript
{ "resource": "" }
q40086
padRight
train
function padRight(val, len, offset, char) { /* istanbul ignore if */ if (!is_1.isValue(val) || !is_1.isString(val)) return null; // If offset is a string // count its length. if (is_1.isString(offset)) offset = offset.length; char = char || ' '; while (len--) { val += char; } if (offset) val += padRight('', offset, null, char); return val; }
javascript
{ "resource": "" }
q40087
titlecase
train
function titlecase(val, conjunctions) { if (!is_1.isValue(val)) return null; // conjunctions var conj = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i; return val.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function (m, i, t) { if (i > 0 && i + m.length !== t.length && m.search(conj) > -1 && t.charAt(i - 2) !== ';' && (t.charAt(i + m.length) !== '-' || t.charAt(i - 1) === '-') && t.charAt(i - 1).search(/[^\s-]/) < 0) { if (conjunctions === false) return capitalize(m); return m.toLowerCase(); } if (m.substr(1).search(/[A-Z]|\../) > -1) /* istanbul ignore next */ return m; return m.charAt(0).toUpperCase() + m.substr(1); }); }
javascript
{ "resource": "" }
q40088
uuid
train
function uuid() { var d = Date.now(); // Use high perf timer if avail. /* istanbul ignore next */ if (typeof performance !== 'undefined' && is_1.isFunction(performance.now)) d += performance.now(); return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); }
javascript
{ "resource": "" }
q40089
validateOptions
train
function validateOptions(options) { if (!options) { return; } utils.each(['varControls', 'tagControls', 'cmtControls'], function (key) { if (!options.hasOwnProperty(key)) { return; } if (!utils.isArray(options[key]) || options[key].length !== 2) { throw new Error('Option "' + key + '" must be an array containing 2 different control strings.'); } if (options[key][0] === options[key][1]) { throw new Error('Option "' + key + '" open and close controls must not be the same.'); } utils.each(options[key], function (a, i) { if (a.length < 2) { throw new Error('Option "' + key + '" ' + ((i) ? 'open ' : 'close ') + 'control must be at least 2 characters. Saw "' + a + '" instead.'); } }); }); if (options.hasOwnProperty('cache')) { if (options.cache && options.cache !== 'memory') { if (!options.cache.get || !options.cache.set) { throw new Error('Invalid cache option ' + JSON.stringify(options.cache) + ' found. Expected "memory" or { get: function (key) { ... }, set: function (key, value) { ... } }.'); } } } if (options.hasOwnProperty('loader')) { if (options.loader) { if (!options.loader.load || !options.loader.resolve) { throw new Error('Invalid loader option ' + JSON.stringify(options.loader) + ' found. Expected { load: function (pathname, cb) { ... }, resolve: function (to, from) { ... } }.'); } } } }
javascript
{ "resource": "" }
q40090
getLocals
train
function getLocals(options) { if (!options || !options.locals) { return self.options.locals; } return utils.extend({}, self.options.locals, options.locals); }
javascript
{ "resource": "" }
q40091
cacheGet
train
function cacheGet(key, options) { if (shouldCache(options)) { return; } if (self.options.cache === 'memory') { return self.cache[key]; } return self.options.cache.get(key); }
javascript
{ "resource": "" }
q40092
cacheSet
train
function cacheSet(key, options, val) { if (shouldCache(options)) { return; } if (self.options.cache === 'memory') { self.cache[key] = val; return; } self.options.cache.set(key, val); }
javascript
{ "resource": "" }
q40093
remapBlocks
train
function remapBlocks(blocks, tokens) { return utils.map(tokens, function (token) { var args = token.args ? token.args.join('') : ''; if (token.name === 'block' && blocks[args]) { token = blocks[args]; } if (token.content && token.content.length) { token.content = remapBlocks(blocks, token.content); } return token; }); }
javascript
{ "resource": "" }
q40094
importNonBlocks
train
function importNonBlocks(blocks, tokens) { var temp = []; utils.each(blocks, function (block) { temp.push(block); }); utils.each(temp.reverse(), function (block) { if (block.name !== 'block') { tokens.unshift(block); } }); }
javascript
{ "resource": "" }
q40095
getParents
train
function getParents(tokens, options) { var parentName = tokens.parent, parentFiles = [], parents = [], parentFile, parent, l; while (parentName) { if (!options || !options.filename) { throw new Error('Cannot extend "' + parentName + '" because current template has no filename.'); } parentFile = parentFile || options.filename; parentFile = self.options.loader.resolve(parentName, parentFile); parent = cacheGet(parentFile, options) || self.parseFile(parentFile, utils.extend({}, options, { filename: parentFile })); parentName = parent.parent; if (parentFiles.indexOf(parentFile) !== -1) { throw new Error('Illegal circular extends of "' + parentFile + '".'); } parentFiles.push(parentFile); parents.push(parent); } // Remap each parents'(1) blocks onto its own parent(2), receiving the full token list for rendering the original parent(1) on its own. l = parents.length; for (l = parents.length - 2; l >= 0; l -= 1) { parents[l].tokens = remapBlocks(parents[l].blocks, parents[l + 1].tokens); importNonBlocks(parents[l].blocks, parents[l].tokens); } return parents; }
javascript
{ "resource": "" }
q40096
FrontRouter
train
function FrontRouter() { var opts = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; _classCallCheck(this, FrontRouter); this.options = { pageRoot: opts.pageRoot || process.cwd(), overwrite: opts.overwrite || false }; this.routes = []; // Figure out what library to load switch (_typeof(opts.library)) { // String: pull a library out of the built-in ones case 'string': { var lib = Libraries[opts.library]; if (typeof lib === 'undefined') { throw new Error('Front Router: there\'s no built-in plugin for "' + opts.library + '"'); } else { this.options.library = lib; } break; } // Function: add as-is case 'function': { this.options.library = opts.library; break; } // Nothing: use the default library adapter case 'undefined': { this.options.library = Libraries.default; break; } // Other weird values? Nope default: { throw new Error('Front Router: library must be a string or function.'); } } }
javascript
{ "resource": "" }
q40097
compileToken
train
function compileToken (token, arg) { let fn = tokens[token] || noOp return function () { return arg ? fn.call(this, arg) : fn.call(this) } }
javascript
{ "resource": "" }
q40098
execute
train
function execute(req, res) { this.state.pubsub.punsubscribe(req.conn, req.args); }
javascript
{ "resource": "" }
q40099
createModel
train
function createModel(string) { const reVariable = /\$\{([a-z][\w\-]*)\}/ig; const escapeCharCode = 92; // `\` symbol const variables = []; // We have to replace unescaped (e.g. not preceded with `\`) tokens. // Instead of writing a stream parser, we’ll cut some edges here: // 1. Find all tokens // 2. Walk string char-by-char and resolve only tokens that are not escaped const tokens = new Map(); let m; while (m = reVariable.exec(string)) { tokens.set(m.index, m); } if (tokens.size) { let start = 0, pos = 0, len = string.length; let output = ''; while (pos < len) { if (string.charCodeAt(pos) === escapeCharCode && tokens.has(pos + 1)) { // Found escape symbol that escapes variable: we should // omit this symbol in output string and skip variable const token = tokens.get(pos + 1); output += string.slice(start, pos) + token[0]; start = pos = token.index + token[0].length; tokens.delete(pos + 1); continue; } pos++; } string = output + string.slice(start); // Not using `.map()` here to reduce memory allocations const validMatches = Array.from(tokens.values()); for (let i = 0, il = validMatches.length; i < il; i++) { const token = validMatches[i]; variables.push({ name: token[1], location: token.index, length: token[0].length }); } } return {string, variables}; }
javascript
{ "resource": "" }