_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q3000
getClusterVersion
train
function getClusterVersion(request, mCb) { delete request.project; v1Container().projects.zones.getServerconfig(request, function (err, response) { if (err) { return mCb(err); } let version; if (response && response.validMasterVersions && Array.isArray(response.validMasterVersions) && response.validMasterVersions.length > 0) { response.validMasterVersions.forEach(function (oneVersion) { if (oneVersion.substring(0, 3) === "1.7") { version = oneVersion; options.soajs.log.debug("Initial Cluster version set to :", version); } }); } else if (response && response.defaultClusterVersion && !version) { version = response.defaultClusterVersion; options.soajs.log.debug("Initial Cluster version set to default version :", version); } else { return mCb({"code": 410, "msg": "Invalid or no kubernetes cluster version found!"}) } return mCb(null, version); }); }
javascript
{ "resource": "" }
q3001
deleteNetwork
train
function deleteNetwork() { setTimeout(function () { //cluster failed, delete network if it was not provided by the user let networksOptions = Object.assign({}, options); networksOptions.params = {name: oneDeployment.options.network}; networks.delete(networksOptions, (error) => { if (error) { options.soajs.log.error(error); } else { options.soajs.log.debug("VPC Network Deleted Successfully."); } }); }, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 5 * 60 * 1000); }
javascript
{ "resource": "" }
q3002
train
function (options, region, verbose, mCb) { infraExtras.getRegion(options, region, verbose, (err, resR) => { if (err) { infraExtras.getZone(options, region, verbose, (err, resZ) => { if (err) { return mCb(err); } else { return mCb(null, resZ); } }); } else { return mCb(null, resR); } }); }
javascript
{ "resource": "" }
q3003
train
function (options, cb) { //call google api and get the machines let cluster = options.infra.stack; //Ref: https://cloud.google.com/compute/docs/reference/latest/instances/list let request = getConnector(options.infra.api); request.clusterId = cluster.id; request.filter = "name eq gke-" + cluster.id.substring(0, 19) + "-" + cluster.options.nodePoolId + "-.*"; let response = { "env": options.soajs.registry.code, "stackId": cluster.id, "stackName": cluster.id, "templateProperties": { "region": cluster.options.zone //"keyPair": "keyPair" //todo: what is this for ???? }, "machines": [], }; driver.checkZoneRegion(options, cluster.options.zone, true, (err, zones) => { if (err) { return cb(err) } //loop over all the zone ang get the ip of each location found in the zone //if zonal we only have to loop once async.each(zones, function (oneZone, callback) { request.zone = oneZone; v1Compute().instances.list(request, (error, instances) => { if (error) { return callback(error); } if (instances && instances.items) { //extract name and ip from response instances.items.forEach((oneInstance) => { let machineIP; oneInstance.networkInterfaces.forEach((oneNetInterface) => { if (oneNetInterface.accessConfigs) { oneNetInterface.accessConfigs.forEach((oneAC) => { if (oneAC.name === 'external-nat') { machineIP = oneAC.natIP; } }); } }); if (machineIP) { response.machines.push({ "name": oneInstance.name, "ip": machineIP, "zone": oneZone }); } }); } callback(); }); }, function (err) { if (err) { return cb(err) } else { return cb(null, response); } }); }); }
javascript
{ "resource": "" }
q3004
train
function (options, cb) { options.soajs.log.debug("Checking if Cluster is healthy ..."); let stack = options.infra.stack; let containerOptions = Object.assign({}, options); containerOptions.technology = (containerOptions && containerOptions.params && containerOptions.params.technology) ? containerOptions.params.technology : defaultDriver; //get the environment record if (options.soajs.registry.deployer.container[stack.technology].remote.nodes && options.soajs.registry.deployer.container[stack.technology].remote.nodes !== '') { let machineIp = options.soajs.registry.deployer.container[stack.technology].remote.nodes; return cb(null, machineIp); } else { let out = false; async.series({ "pre": (mCb) => { runCorrespondingDriver('getDeployClusterStatusPre', containerOptions, mCb); }, "exec": (mCb) => { ClusterDriver.getDeployClusterStatus(options, (error, response) => { if (response) { out = response; containerOptions.out = out; } return mCb(error, response); }); }, "post": (mCb) => { if (out) { runCorrespondingDriver('getDeployClusterStatusPost', containerOptions, mCb); } else { return mCb(); } } }, (error) => { return cb(error, out); }); } }
javascript
{ "resource": "" }
q3005
_timestampBeforeNow
train
function _timestampBeforeNow(timestamp) { if(!(typeof timestamp === 'string' && dateRegEx.test(timestamp))) { throw new TypeError('`revoked` timestamp must be a string.'); } const now = new Date(); const tsDate = new Date(timestamp); return tsDate < now; }
javascript
{ "resource": "" }
q3006
Cassanova
train
function Cassanova(){ this.tables = {}; this.models = {}; this.schemas = {}; this.client = null; this.options = null; EventEmitter.call(this); }
javascript
{ "resource": "" }
q3007
train
function(callback){ var filePath; output("Processing arguments..."); if(program.cql){ batchQueries.push(program.cql.toString().trim()); } if((!program.keyspace || program.keyspace.length === 0)){ output("A keyspace has not been defined. CQL will fail if the keyspace is not defined in the statement."); } if((!program.files || program.files.length === 0) && (!program.cql || program.cql.length === 0)){ return callback("Need a file to load or cql to run. Use -f=filename or --files=filename,filename or -cql='someCQLStatement;' or --cql='someCQLStatement;'. Run node CQL --help for mode information.", false); }else if(process.env.NODE_ENV === 'production' && !program.production){ return callback("CQL cannot be run while the NODE_ENV is set to production.", false); }else if(program.production && process.env.NODE_ENV === 'production'){ output("***** Preparing to run scripts in production mode *****"); output("***** You have " + productionRunDelay + " seconds to think about what your doing before the scripts will execute. *****"); output("***** CTRL+C to Exit *****"); barTimer = setInterval(function () { bar.tick(); if (bar.complete) { output("***** OK! Here we go... *****"); output("***** Running scripts in production mode *****"); clearInterval(barTimer); return callback(null, true); } }, 1000); return; }else if(program.production && process.env.NODE_ENV !== 'production'){ return callback("NODE_ENV is set not set to production, but you attempted to run in production mode.", false); } callback(null, true); }
javascript
{ "resource": "" }
q3008
train
function(callback){ var opts = {}; output("Connecting to database..."); //We need to be able to do anything with any keyspace. We just need a db connection. Just send //in the hosts, username and password, stripping the keyspace. opts.username = process.env.CASS_USER || config.db.username; opts.password = process.env.CASS_PASS || config.db.password; opts.hosts = config.db.hosts; opts.port = config.db.port; Cassanova.connect(opts, function(err, result){ if(err){ err.hosts = opts.hosts; } callback(err, result); }); }
javascript
{ "resource": "" }
q3009
train
function(callback){ var result, i; if(!files || files.length === 0){ return callback(null, true); } output("Processing queries..."); for(i=0; i<files.length; i++){ while((result = cqlRegex.exec(files[i])) !== null) { batchQueries.push(result[1].replace(/\s+/g, ' ').trim()); } } callback(null, true); }
javascript
{ "resource": "" }
q3010
train
function(callback){ output("Initializing queries..."); if(program.keyspace){ batchQueries.unshift("USE " + program.keyspace + ";"); } if(batchQueries && batchQueries.length > 0){ output("Running queries..."); executeQuery(batchQueries.shift(), callback); }else{ callback("No queries to run.", null); } }
javascript
{ "resource": "" }
q3011
train
function(eQuery, callback){ output("Executing:\t\t" + eQuery); Cassanova.execute(eQuery, function(err) { if (err){ return callback(err, null); } else { if(batchQueries.length > 0){ executeQuery(batchQueries.shift(), callback); }else{ callback(null, true); process.nextTick(function(){ process.exit(1); }); } } }); }
javascript
{ "resource": "" }
q3012
Event
train
function Event(type, data){ this._sender = null; this._type = type; this._data = data; for(var prop in data) { this[prop] = data[prop]; } this._stopPropagation = false; }
javascript
{ "resource": "" }
q3013
train
function () { var cwd = process.cwd(); var rootPath = cwd; var newRootPath = null; while (!fs.existsSync(path.join(process.cwd(), "node_modules/grunt"))) { process.chdir(".."); newRootPath = process.cwd(); if (newRootPath === rootPath) { return; } rootPath = newRootPath; } process.chdir(cwd); return rootPath; }
javascript
{ "resource": "" }
q3014
train
function (grunt, rootPath, tasks) { tasks.forEach(function (name) { if (name === 'grunt-cli') return; var cwd = process.cwd(); process.chdir(rootPath); // load files from proper root, I don't want to install everything locally per module! grunt.loadNpmTasks(name); process.chdir(cwd); }); }
javascript
{ "resource": "" }
q3015
train
function (next) { minify( outputCommonsJsFile, _.extend({optimize: true},uglifyOptions), function(err){ if ( err ){ return next(err); } return next(); } ); }
javascript
{ "resource": "" }
q3016
train
function (next) { minify( outputJsFile, _.extend({optimize: true},uglifyOptions), function(err){ if ( err ){ return next(err); } if ( isForPublish ){ publisher( outputJsFile, function (err) { return next(err); }, options.forceminified ); }else { return next(); } } ); }
javascript
{ "resource": "" }
q3017
train
function (next) { for (var i = 0; i < mapFiles.length; i++) { fs.unlinkSync(mapFiles[i]); // console.log( path.resolve(mapFiles[i]) ); } return next(); }
javascript
{ "resource": "" }
q3018
minify
train
function minify( file, options, done ){ if (_.isFunction(options)){ done = options; options = {}; } if (!_.isObject(options)) options = {}; if (!_.isFunction(done)) done = function(){}; const canOptimize = options.optimize; delete options.optimize; console.log(" minify file %s...".grey, file); try { var code = fs.readFileSync( file, {encoding: 'utf8'} ); var minify = UglifyJS.minify( code, options ); } catch (e) { return done( new Error(`Error on parse file ${e.filename}`) ); } if ( !minify || minify.error ) { if ( minify && minify.error ) return done( new Error(minify.error.message) ); return done(new Error('Minify error bundle.js') ); } try{ if ( canOptimize ){ console.log(" optimize file %s...".grey, file ); code = optimizeJs(minify.code); }else{ code = minify.code; } }catch(e){ console.error("Error on parse file %s", e.filename); return next(e); } fs.writeFile( file, code, function (err) { if ( err ) return done(err); return done(); } ); }
javascript
{ "resource": "" }
q3019
publisher
train
function publisher(outputJsFile, done, forceMinified){ // Check if JSCrambler configs file exist const time = process.hrtime(); const jscramblerConfigs = path.resolve('jscrambler.json'); fs.stat( jscramblerConfigs, function (err) { if ( err ){ let newTime = console.log(' obfuscating code with jScrambler was not executed, because the configs file `jscrambler.json` is not present into project\'s directory.'.yellow); console.log('Publication finished!'.gray); // +beautifyTime( process.hrtime(time) ).green + '\u0007' return done(err); } console.log(' obfuscating code with jScrambler...'.gray); try { var configs = require(jscramblerConfigs); } catch (e) { return done(' Error on obfuscation! The file configs is not a valid JSON'.red); } if ( !_.isObject(configs.keys) || _.isEmpty(configs.keys.accessKey) || _.isEmpty(configs.keys.secretKey) || _.isEmpty(configs.applicationId) ){ return done( new Error(' Error on obfuscation! Jcrambler\'s configs missed. Ex.: accessKey, secretKey or applicationId.') ); } // Set the file for obfuscation if ( !_.isArray(configs.filesSrc) ) configs.filesSrc = []; if ( configs.filesSrc.indexOf(outputJsFile) == -1 ) configs.filesSrc.push(outputJsFile); configs.filesDest = path.dirname( packageJSONFile ); // The project's dirname /* { keys: { accessKey: 'YOUR_JSCRAMBLER_ACCESS_KEY', secretKey: 'YOUR_JSCRAMBLER_SECRET_KEY' }, host: 'api4.jscrambler.com', port: 443, applicationId: 'YOUR_APPLICATION_ID', filesSrc: [ '/path/to/src/*.html', '/path/to/src/*.js' ], filesDest: '/path/to/destDir/', params: { stringSplitting: { chunk: 1 } } } */ const symbolTable = path.join( configs.filesDest, "symbolTable.json"); jscrambler .protectAndDownload(configs) .then(function () { try{ const st = fs.statSync( symbolTable ); fs.unlinkSync(symbolTable); }catch(e){} if ( !forceMinified ){ console.log('Publication finished in '.gray+beautifyTime( process.hrtime(time) ).green + '\u0007'); return done(); } minify(outputJsFile,{},function(err){ if (err){ return done(err); } console.log('Publication finished in '.gray+beautifyTime( process.hrtime(time) ).green + '\u0007'); return done(); }); }) .catch(function (err) { let message = ' Error on obfuscation! Error while obfuscating the code with jScrambler'; if ( err && err.message ) message = ` Error on obfuscation! jScrambler: ${err.message}`; done( new Error(message) ); }); }); }
javascript
{ "resource": "" }
q3020
train
function(token,options){ options = options||{}; options.token = token; var obj = { type:"rest" ,args:{ url: '/v1/sync', data: options, method: 'get' } }; var s = through(); repipe(s,function(err,last,done){ o.log('repipe got error? ',err,' should i repipe?'); if(err && err.code != 'E_MDM') return done(err); getConnection(function(err,con){ if(err) return done(err); var dbstream = con.mdm.createReadStream(obj); var noendstream = dbstream.pipe(through(function(data){ this.queue(data); },function(){ if(options.tail || options.tail == undefined) { // repipe resumes the stream on error events! var error = new Error("never end bro!"); error.code = "E_MDM"; this.emit("error",error); } else { this.queue(null); } })); dbstream.on('error',function(err){ noendstream.emit("error",err) }); done(false,noendstream); }); }); s.on('data',function(d){ // on reconnect start sync from where i left off. obj.args.data.start = d.time; }) return s; }
javascript
{ "resource": "" }
q3021
train
function(token,o){ /* o.troop o.scout o.reports = [led,..] o.start = now o.end = then o.tail defaults true with no end */ o.token = token; var obj = { type:"rest" ,args:{ url: '/v1/stats', data: o, method: 'get' } }; var s = through(); repipe(s,function(err,last,done){ if(err && err.code != 'E_MDM') return done(err); if(last) o.start = last.key; getConnection(function(err,con){ if(err) return done(err); done(false,con.mdm.createReadStream(obj)); }); }); return s; // resume! }
javascript
{ "resource": "" }
q3022
_serveFile
train
function _serveFile(requestedFile, done) { requestedFile.path = transformPath(requestedFile.path); log.debug(`Fetching ${requestedFile.path} from buffer`); // We get a requestedFile with an sha when Karma is watching files on // disk, and the file requested changed. When this happens, we need to // recompile the whole lot. if (requestedFile.sha) { delete requestedFile.sha; // Hack used to prevent infinite loop. enqueueForServing(requestedFile, done); // eslint-disable-next-line no-use-before-define compile(); return; } const normalized = _normalize(requestedFile.path); const compiled = compilationResults[normalized]; if (compiled) { delete compilationResults[normalized]; done(null, compiled.contents.toString()); return; } // If the file was not found in the stream, then maybe it is not compiled // or it is a definition file. log.debug(`${requestedFile.originalPath} was not found. Maybe it was \ not compiled or it is a definition file.`); done(null, dummyFile("This file was not compiled")); }
javascript
{ "resource": "" }
q3023
processServeQueue
train
function processServeQueue() { while (serveQueue.length) { const item = serveQueue.shift(); _serveFile(item.file, item.done); // It is possible start compiling while in release. if (state.compilationCompleted !== _currentState) { break; } } }
javascript
{ "resource": "" }
q3024
traverse
train
function traverse(transform, node, parent) { const type = node && node.type; assert(type, `Expected node, got '${node}'`); const baseHandler = transform.handlers[type] || transform.handlers.default; const userHandler = transform.userHandlers[type] || transform.userHandlers.default; const starHandler = transform.userHandlers['*']; const userBaseHandler = userHandler ? userHandler.bind({ __base: baseHandler }) : baseHandler; const handler = starHandler ? starHandler.bind({ __base: userBaseHandler }) : userBaseHandler; return handler(transform, node, parent); }
javascript
{ "resource": "" }
q3025
Table
train
function Table(name, schema){ if(!name || typeof name !== "string"){ throw new Error("Attempting to instantiate a table without a valid name."); } if(!schema || !(schema instanceof Schema)){ throw new Error("Attempting to instantiate a table without a valid schema."); } this.name = name; this.schema = schema; }
javascript
{ "resource": "" }
q3026
connect
train
function connect (state) { return Promise.resolve(state.remote) .then(function (remote) { if (state.replication) { return } state.replication = state.db.sync(remote, { create_target: true, live: true, retry: true }) state.replication.on('error', function (error) { state.emitter.emit('error', error) }) state.replication.on('change', function (change) { for (var i = 0; i < change.change.docs.length; i++) { state.emitter.emit(change.direction, change.change.docs[i]) } }) state.emitter.emit('connect') }) }
javascript
{ "resource": "" }
q3027
train
function (options, cb) { options.soajs.log.debug("Generating docker token"); crypto.randomBytes(1024, function (err, buffer) { if (err) { return cb(err); } options.soajs.registry.deployer.container.docker.remote.apiProtocol = 'https'; options.soajs.registry.deployer.container.docker.remote.apiPort = 32376; options.soajs.registry.deployer.container.docker.remote.auth = { token: buffer.toString('hex') }; return cb(null, true); }); }
javascript
{ "resource": "" }
q3028
train
function (options, cb) { let outIP = options.out; let stack = options.infra.stack; if (outIP && stack.options.ElbName) { options.soajs.log.debug("Creating SOAJS network."); dockerUtils.getDeployer(options, (error, deployer) => { if(error){ return cb(error); } deployer.listNetworks({}, (err, networks) => { if (err) { return cb(err); } let found = false; networks.forEach((oneNetwork) => { if (oneNetwork.Name === 'soajsnet') { found = true; } }); if(found){ return cb(null, true); } else{ let networkParams = { Name: 'soajsnet', Driver: 'overlay', Internal: false, Attachable: true, CheckDuplicate: true, EnableIPv6: false, IPAM: { Driver: 'default' } }; deployer.createNetwork(networkParams, (err) => { return cb(err, true); }); } }); }); } else { return cb(null, false); } }
javascript
{ "resource": "" }
q3029
disconnect
train
function disconnect (state) { if (state.replication) { state.replication.cancel() delete state.replication state.emitter.emit('disconnect') } return Promise.resolve() }
javascript
{ "resource": "" }
q3030
addJwtHandling
train
function addJwtHandling(secrets, app) { if (!secrets.authTokenSecret) { log.error( 'Cannot setup token authentication because token secret is not configured.' ); return; } app.use(expressJwt({ secret: secrets.authTokenSecret })); app.use(function (req, res, next) { if (req.user && req.user.data) { req.user.isAuthenticated = true; req.user.meta = req.user.meta || {}; } next(); }); app.use(function (err, req, res, next) { if (err.name === 'UnauthorizedError') { if (err.code === 'credentials_required') { // If the caller did not provide credentials, we'll just consider this // an unauthenticated request. next(); } else { res.status(401).send('Invalid token: ' + err.message); } } }); }
javascript
{ "resource": "" }
q3031
addSessionHandling
train
function addSessionHandling(secrets, app) { var connection = dbUtils.getConnectionNow(); var sessionStore = new MongoStore({ db: connection.db }); app.use(cookieParser()); app.use(session({ secret: secrets.cookieSecret, maxAge: 3600000, // 1 hour store: sessionStore })); app.use(passport.initialize()); exports.usingSessions = true; app.use(passport.session()); passport.serializeUser(function (user, done) { var data = user.data || user; done(null, { data: data, isAuthenticated: true, meta: {} }); }); passport.deserializeUser(function (obj, done) { done(null, obj); }); }
javascript
{ "resource": "" }
q3032
mix
train
function mix(receiver, supplier, overwrite) { var key; if (!receiver || !supplier) { return receiver || {}; } for (key in supplier) { if (supplier.hasOwnProperty(key)) { if (overwrite || !receiver.hasOwnProperty(key)) { receiver[key] = supplier[key]; } } } return receiver; }
javascript
{ "resource": "" }
q3033
train
function(val) { let guid = guidFor(val); if(guid in map) { return map[guid]; } else if(sort) { let sibiling = calculateMissingPosition(val, domain, sort); return map[guidFor(sibiling)]; } else { return r0; } }
javascript
{ "resource": "" }
q3034
restoreBackup
train
function restoreBackup(backupRecord, mongoUri) { var receipts = backupRecord.receipts; var handler = getHandler(backupRecord.type); var restorePromises = receipts.map(function (receipt) { var tmpfile = util.getTempFileName() + '.bson'; return R.pPipe( handler.restore.bind(handler), R.curry(R.flip(mds.dump.fs.file))(tmpfile), R.curryN(4, mongoRestoreFromFile)(tmpfile, mongoUri, receipt.collection) )(receipt.data); }); return q.all(restorePromises).thenResolve('done'); }
javascript
{ "resource": "" }
q3035
autoBox
train
function autoBox(object, model, data) { if (!object) { return isArray(data) ? model.collection(data, true) : model.instance(data); } if (isArray(data) && isArray(object)) { return model.collection(data, true); } if (data && JSON.stringify(data).length > 3) { deepExtend(object, data); object.$original.sync(data); } return object; }
javascript
{ "resource": "" }
q3036
train
function(object) { if (object instanceof ModelClass) { return object.url(); } if (object instanceof ModelInstance || isFunc(object.$model)) { var model = object.$model(); return expr(object, model.$config().identity + '.href').get() || model.url(); } throw new Error('Could not get URL for ' + typeof object); }
javascript
{ "resource": "" }
q3037
config
train
function config(name, options) { if (isObject(name)) { extend(global, name); return; } var previous = (registry[name] && registry[name].$config) ? registry[name].$config() : null, base = extend({}, previous ? extend({}, previous) : extend({}, DEFAULTS, DEFAULT_METHODS)); options = deepExtend(copy(base), options); if (!options.url) { options.url = global.base.replace(/\/$/, '') + '/' + hyphenate(name); } registry[name] = new ModelClass(options); }
javascript
{ "resource": "" }
q3038
ModelClassFactory
train
function ModelClassFactory(name, options) { if (!isUndef(options)) { return config(name, options); } return registry[name] || undefined; }
javascript
{ "resource": "" }
q3039
train
function (options, mCb) { const aws = options.infra.api; getElbMethod(options.params.elbType || 'classic', 'list', (elbResponse) => { const elb = getConnector({ api: elbResponse.api, region: options.params.region, keyId: aws.keyId, secretAccessKey: aws.secretAccessKey }); const ec2 = getConnector({ api: 'ec2', region: options.params.region, keyId: aws.keyId, secretAccessKey: aws.secretAccessKey }); elb[elbResponse.method]({}, function (err, response) { if (err) { return mCb(err); } async.map(response.LoadBalancerDescriptions, function (lb, callback) { async.parallel({ subnets: function (callback) { if (lb && lb.Subnets && Array.isArray(lb.Subnets) && lb.Subnets.length > 0) { let sParams = {SubnetIds: lb.Subnets}; ec2.describeSubnets(sParams, callback); } else { return callback(null, null); } }, instances: function (callback) { let iParams = {LoadBalancerName: lb.LoadBalancerName}; elb.describeInstanceHealth(iParams, callback); } }, function (err, results) { return callback(err, helper[elbResponse.helper]({ lb, region: options.params.region, subnets: results.subnets ? results.subnets.Subnets : [], instances: results.instances ? results.instances.InstanceStates : [] })); }); }, mCb); }); }); }
javascript
{ "resource": "" }
q3040
train
function (options, mCb) { getElbMethod(options.params.elbType || 'classic', 'delete', (elbResponse) => { const aws = options.infra.api; const elb = getConnector({ api: elbResponse.api, region: options.params.region, keyId: aws.keyId, secretAccessKey: aws.secretAccessKey }); let params = { LoadBalancerName: options.params.name }; options.soajs.log.debug(params); elb[elbResponse.method](params, mCb); }); }
javascript
{ "resource": "" }
q3041
initcpurow
train
function initcpurow() { return { user: 0, nice: 0, system: 0, iowait: 0, idle: 0, irq: 0, softirq: 0, steal: 0, guest: 0, guest_nice: 0 }; }
javascript
{ "resource": "" }
q3042
findname
train
function findname(error, response, body) { if (error){ return error } if (body){ try{ var info = JSON.parse(body) } catch(err){ console.log(body) return } if (info.items){ var ilen=info.items.length while(ilen--){ var it=info.items[ilen] var thename=it['properties']['name'] if (thename.match(srchfor)){ console.log(it) // <---- print json for server(s) that match srchfor } } } } }
javascript
{ "resource": "" }
q3043
Temper
train
function Temper(options) { if (!this) return new Temper(options); options = options || {}; // // We only want to cache the templates in production as it's so we can easily // change templates when we're developing. // options.cache = 'cache' in options ? options.cache : process.env.NODE_ENV !== 'production'; this.installed = Object.create(null); // Installed module for extension cache. this.required = Object.create(null); // Template engine require cache. this.compiled = Object.create(null); // Compiled template cache. this.timers = new TickTock(this); // Keep track of timeouts. this.file = Object.create(null); // File lookup cache. this.cache = options.cache; // Cache compiled templates. }
javascript
{ "resource": "" }
q3044
plugin
train
function plugin(options) { options = defaultsDeep({}, options, defaults); this.Compiler = compiler; function compiler(node, file) { const root = node && node.type && node.type === 'root'; const bemjson = toBemjson(node, { augment: options.augment }); const bjsonString = options.export ? JSON.stringify(bemjson, null, 4) : ''; if (file.extname) { file.extname = '.js'; } if (file.stem) { file.stem = file.stem + '.bemjson'; } file.data = bemjson; return root ? createExport({ type: options.exportType, name: options.exportName }, bjsonString) : bjsonString; } }
javascript
{ "resource": "" }
q3045
handleLogin
train
function handleLogin(user, req, res, next) { var token; var profile; var tokenExpiresInMinutes; var envelope = { data: user, isAuthenticated: true, meta: {} }; // First handle the case where the user was not logged in. if (!user) { if (authConfig.maintenance === 'cookie') { req.logout(); } return res.status(401).send('Wrong password or no such user.'); } // user_id is how it is in the schema /* jshint ignore:start */ // Now handle the case where we did get a user record. if (authConfig.maintenance === 'token') { // For token authentication we want to add a token. profile = { username: user.username, email: user.email, userdata_id: user.userdata_id }; /* jshint ignore:end */ tokenExpiresInMinutes = authConfig.expiresInMinutes || 60; envelope.meta.token = generateToken(profile, tokenExpiresInMinutes, secrets.authTokenSecret); envelope.meta.expires = getExpirationTime(tokenExpiresInMinutes); return res.status(200).send(envelope); } else if (authConfig.maintenance === 'cookie') { // For cookie authentication we want to login the user. req.login(user, function (err) { if (err) { return next(err); } else { return res.status(200).send(envelope); } }); } }
javascript
{ "resource": "" }
q3046
Deffy
train
function Deffy(input, def, options) { // Default is a function if (typeof def === "function") { return def(input); } options = Typpy(options) === "boolean" ? { empty: options } : { empty: false }; // Handle empty if (options.empty) { return input || def; } // Return input if (Typpy(input) === Typpy(def)) { return input; } // Return the default return def; }
javascript
{ "resource": "" }
q3047
generateRandomId
train
function generateRandomId (length) { var str = '' length = length || 6 while (str.length < length) { str += (((1 + Math.random()) * 0x10000) | 0).toString(16) } return str.substring(str.length - length, str.length) }
javascript
{ "resource": "" }
q3048
guessObjectType
train
function guessObjectType(obj, shortname=false) { var type if (typeof obj === "string" && obj) { if (obj in objectTypeUris) { // given by URI type = objectTypeUris[obj] } else { // given by name obj = obj.toLowerCase().replace(/s$/,"") type = Object.keys(objectTypes).find(name => { const lowercase = name.toLowerCase() if (lowercase === obj || lowercase === "concept" + obj) { return true } }) } } else if (typeof obj === "object") { if (obj.type) { let types = Array.isArray(obj.type) ? obj.type : [obj.type] for (let uri of types) { if (uri in objectTypeUris) { type = objectTypeUris[uri] break } } } } return (shortname && type) ? type.toLowerCase().replace(/^concept(.+)/, "$1") : type }
javascript
{ "resource": "" }
q3049
MongoAdapter
train
function MongoAdapter(mongooseConnection) { if (!(this instanceof MongoAdapter)) { return new MongoAdapter(mongooseConnection); } storj.StorageAdapter.call(this); if (mongooseConnection instanceof Storage) { this._model = mongooseConnection.models.Shard; } else { this._model = Shard(mongooseConnection); } }
javascript
{ "resource": "" }
q3050
constructModel
train
function constructModel(Model, options) { return construct({ input: Model, expected: AmpersandModel, createConstructor: model, options: options }); }
javascript
{ "resource": "" }
q3051
constructCollection
train
function constructCollection(Collection, options) { return construct({ input: Collection, expected: AmpersandCollection, createConstructor: collection, options: options }); }
javascript
{ "resource": "" }
q3052
train
function(options, cb) { let template, render; if(!options.params || !options.params.template || !options.params.template.content) { return utils.checkError('Missing template content', 727, cb); } try { template = handlebars.compile(options.params.template.content); if(options.params.template._id){ if(!options.params.input.tags){ options.params.input.tags = {}; } options.params.input.tags['soajs.template.id'] = options.params.template._id.toString(); } render = template(options.params.input); } catch(e) { return utils.checkError(e, 727, cb); } return cb(null, { render }); }
javascript
{ "resource": "" }
q3053
SchemaType
train
function SchemaType(type, validation, wrapper, params){ this.type = type; this.validate = validation; this.wrapper = wrapper; this.parameters = params; this.isPrimary = false; chainPrimaryKey(); }
javascript
{ "resource": "" }
q3054
train
function(node, entity, props, content) { const hasContent = (!entity || entity.content !== null) && content !== null; const entityContent = hasContent ? ((entity && entity.content) || content || traverse.children(transform, node)) : null; const block = parseBemNode(entity); const bemNode = build(block, props, entityContent); // Extend blocks context with external plugins hContext if (node.data) { node.data.htmlAttributes && (bemNode.attrs = Object.assign({}, bemNode.attrs, node.data.htmlAttributes)); node.data.hProperties && (bemNode.hProps = node.data.hProperties); } return transform.augment(bemNode); }
javascript
{ "resource": "" }
q3055
augmentFactory
train
function augmentFactory(augmentFunction) { /** * Apply custom augmentation and insert back to subtree * * @function AugmentFunction * @param {Object} bemNode - representation of bem entity * @returns {Object} bemNode */ function augment(bemNode) { const hasChildren = _hasChildren(bemNode.content); const bemNodeClone = hasChildren ? omit(bemNode, ['content']) : cloneDeep(bemNode); const augmentedBemNode = augmentFunction(bemNodeClone); /* Check that if we has children augmentation doesn't modify content */ assert( !hasChildren || !augmentedBemNode.content, 'You are not allow to modify subtree of bemNode. To do that please use bem-xjst@' ); if (hasChildren) { augmentedBemNode.content = bemNode.content; } return augmentedBemNode; } return augment; }
javascript
{ "resource": "" }
q3056
_hasChildren
train
function _hasChildren(content) { if (!content) return false; if (typeof content === 'object') return true; if (Array.isArray(content) && content.every(item => typeof item === 'string')) return false; return false; }
javascript
{ "resource": "" }
q3057
reindexNodes
train
function reindexNodes () { var child = this.node.firstChild; this._length = 0; while (child) { this[this._length++] = child; child = child.nextSibling; } }
javascript
{ "resource": "" }
q3058
Qlobber
train
function Qlobber (options) { options = options || {}; this._separator = options.separator || '.'; this._wildcard_one = options.wildcard_one || '*'; this._wildcard_some = options.wildcard_some || '#'; this._trie = new Map(); if (options.cache_adds instanceof Map) { this._shortcuts = options.cache_adds; } else if (options.cache_adds) { this._shortcuts = new Map(); } }
javascript
{ "resource": "" }
q3059
train
function(value, i, reads, options) { return value && value[getValueSymbol] && value[isValueLikeSymbol] !== false && (options.foundAt || !isAt(i, reads) ); }
javascript
{ "resource": "" }
q3060
train
function(parent, key, value, options) { var keys = typeof key === "string" ? observeReader.reads(key) : key; var last; options = options || {}; if(keys.length > 1) { last = keys.pop(); parent = observeReader.read(parent, keys, options).value; keys.push(last); } else { last = keys[0]; } if(!parent) { return; } var keyValue = peek(parent, last.key); // here's where we need to figure out the best way to write // if property being set points at a compute, set the compute if( observeReader.valueReadersMap.isValueLike.test(keyValue, keys.length - 1, keys, options) ) { observeReader.valueReadersMap.isValueLike.write(keyValue, value, options); } else { if(observeReader.valueReadersMap.isValueLike.test(parent, keys.length - 1, keys, options) ) { parent = parent[getValueSymbol](); } if(observeReader.propertyReadersMap.map.test(parent)) { observeReader.propertyReadersMap.map.write(parent, last.key, value, options); } else if(observeReader.propertyReadersMap.object.test(parent)) { observeReader.propertyReadersMap.object.write(parent, last.key, value, options); if(options.observation) { options.observation.update(); } } } }
javascript
{ "resource": "" }
q3061
assetFile
train
function assetFile(filename, callback) { const data = { source: files[filename].source, destination: files[filename].destination || path.join(path.dirname(filename), '.') } delete files[filename] metalsmithAssets(data)(files, metalsmith, callback) }
javascript
{ "resource": "" }
q3062
doesObjectListHaveDuplicates
train
function doesObjectListHaveDuplicates(l) { const mergedList = l.reduce((merged, obj) => ( obj ? merged.concat(Object.keys(obj)) : merged ), []); // Taken from: http://stackoverflow.com/a/7376645/1263876 // By casting the array to a Set, and then checking if the size of the array // shrunk in the process of casting, we can check if there were any duplicates return new Set(mergedList).size !== mergedList.length; }
javascript
{ "resource": "" }
q3063
safeInvokeForConfig
train
function safeInvokeForConfig({ fn, context, params, onNotInvoked }) { if (typeof fn === 'function') { let fnParams = params; if (typeof params === 'function') { fnParams = params(); } // Warn if params or lazily evaluated params were given but not in an array if (fnParams != null && !Array.isArray(fnParams)) { if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line no-console console.warn("Params to pass into safeInvoke's fn is not an array. Ignoring...", fnParams); } fnParams = null; } return { invoked: true, result: fn.apply(context, fnParams) }; } else { if (typeof onNotInvoked === 'function') { onNotInvoked(); } return { invoked: false }; } }
javascript
{ "resource": "" }
q3064
populateDefault
train
function populateDefault(message, field) { const fieldName = field.getName(); if (message.has(fieldName)) { return true; } const defaultValue = field.getDefault(message); if (defaultValue === null) { return false; } const msg = msgs.get(message); if (field.isASingleValue()) { msg.data.set(fieldName, defaultValue); msg.clearedFields.delete(fieldName); return true; } if (isEmpty(defaultValue)) { return false; } if (field.isASet()) { message.addToSet(fieldName, Array.from(defaultValue)); return true; } msg.data.set(fieldName, defaultValue); msg.clearedFields.delete(fieldName); return true; }
javascript
{ "resource": "" }
q3065
resetClock
train
function resetClock() { for (const key in jasmine.Clock.real) { if (jasmine.Clock.real.hasOwnProperty(key)) { window[key] = jasmine.Clock.real[key] } } }
javascript
{ "resource": "" }
q3066
nodeExec
train
function nodeExec() { var exitCode = nodeCLI.exec.apply(nodeCLI, arguments).code; if (exitCode > 0) { exit(1); } }
javascript
{ "resource": "" }
q3067
train
function(url, fromFilename, toFilename) { if (!SKIP_URLS.test(url)) { var fromDirname = path.dirname(fromFilename), toDirname = path.dirname(toFilename), fromPath = path.resolve(fromDirname, url), toPath = path.resolve(toDirname); return path.relative(toPath, fromPath).replace(/\\/g, "/"); } else { return url; } }
javascript
{ "resource": "" }
q3068
train
function(code) { var tokens = new TokenStream(code), hasCRLF = code.indexOf("\r") > -1, lines = code.split(/\r?\n/), line, token, tt, replacement, colAdjust = 0, lastLine = 0; while ((tt = tokens.get()) !== 0) { token = tokens.token(); if (tt === Tokens.URI) { // URI if (lastLine !== token.startLine) { colAdjust = 0; lastLine = token.startLine; } replacement = this.replacer(token.value.replace(URL_PARENS, "")); // 5 is for url() characters line = lines[token.startLine - 1]; lines[token.startLine - 1] = line.substring(0, token.startCol + colAdjust - 1) + "url(" + replacement + ")" + line.substring(token.endCol + colAdjust - 1); colAdjust += ((replacement.length + 5) - token.value.length); } } return lines.join(hasCRLF ? "\r\n" : "\n"); }
javascript
{ "resource": "" }
q3069
open
train
function open(url, callback){ var cmd, exec = require('child_process').exec; switch(process.platform){ case 'darwin': cmd = 'open'; break; case 'win32': case 'win64': cmd = 'start ""';//加空的双引号可以打开带有 "&" 的地址 break; case 'cygwin': cmd = 'cygstart'; break; default: cmd = 'xdg-open'; break; } cmd = cmd + ' ' + url + ''; return exec(cmd, callback); }
javascript
{ "resource": "" }
q3070
aliasExpand
train
function aliasExpand(cmdmap){ var cmds = {} , twei = require('../') , alias, apiGroup ; for(var key in cmdmap){ alias = cmdmap[key]; if(alias.alias){ if(Array.isArray(alias.alias)){ for(var i = 0, l = alias.alias.length; i < l; i++){ cmds[alias.alias[i]] = cmdmap[key].cmd; } }else{ cmds[alias.alias] = cmdmap[key].cmd; } cmds[key] = cmdmap[key].cmd; delete alias.alias; }else{ cmds[key] = cmdmap[key].cmd || cmdmap[key]; } if(alias.apis && typeof (apiGroup = twei.getApiGroup(alias.apis)) == 'object'){ for(var apiName in apiGroup){ if(!cmds[key + '.' + apiName]){ cmds[key + '.' + apiName] = 'execute ' + alias.apis + '.' + apiName; } } } } //console.log(cmds); return cmds; }
javascript
{ "resource": "" }
q3071
needRecurseArray
train
function needRecurseArray(arr) { for (var i = 0; i < arr.length; i++) { var el = arr[i] if (typeof el !== 'number' && typeof el !== 'string' && el != null) return true } return false }
javascript
{ "resource": "" }
q3072
generateLetterIcon
train
function generateLetterIcon(letter, cb) { // Derive SVG from base letter SVG var letterSVG = baseSVG; // Get a random Material Design color var color = getRandomLetterColor(); // Substitude placeholders for color and letter letterSVG = letterSVG.replace('{c}', color); letterSVG = letterSVG.replace('{x}', letter); // Get filesystem-friendly file name for letter var fileName = getIconFilename(letter); // Define SVG/PNG output path var outputSVGPath = rootDir + config.dist.path + config.dist.svg.outputPath + fileName + '.svg'; var outputPNGPath = rootDir + config.dist.path + config.dist.png.outputPath + fileName + '.png'; // Export the letter as an SVG file fs.writeFileSync(outputSVGPath, letterSVG); // Convert the SVG file into a PNG file using svg2png svg2png(new Buffer(letterSVG), config.dist.png.dimensions) .then(function (buffer) { // Write to disk fs.writeFileSync(outputPNGPath, buffer); // Success cb(); }).catch(function (err) { // Report error return cb(err); }); }
javascript
{ "resource": "" }
q3073
getRandomLetterColor
train
function getRandomLetterColor() { // Reset index if we're at the end of the array if (currentColorIndex >= colorKeys.length) { currentColorIndex = 0; } // Get current color and increment index for next time var currentColorKey = colorKeys[currentColorIndex++]; // Return most satured color hex (a700 or 900) var color = colors[currentColorKey]['a700'] || colors[currentColorKey]['900']; // Invalid color saturation value? if (color == undefined) { // No saturation for black or white, // so return the next random color instead return getRandomLetterColor(); } // Return current color hex return color; }
javascript
{ "resource": "" }
q3074
compileSass
train
function compileSass(path, ext, file, callback) { let compiledCss = sass.renderSync({ file: path, outputStyle: 'compressed', }); callback(null, compiledCss.css); }
javascript
{ "resource": "" }
q3075
asyncFor
train
function asyncFor(array, visitCallback, doneCallback, options) { var start = 0; var elapsed = 0; options = options || {}; var step = options.step || 1; var maxTimeMS = options.maxTimeMS || 8; var pointsPerLoopCycle = options.probeElements || 5000; // we should never block main thread for too long... setTimeout(processSubset, 0); function processSubset() { var finish = Math.min(array.length, start + pointsPerLoopCycle); var i = start; var timeStart = new Date(); for (i = start; i < finish; i += step) { visitCallback(array[i], i, array); } if (i < array.length) { elapsed += (new Date() - timeStart); start = i; pointsPerLoopCycle = Math.round(start * maxTimeMS/elapsed); setTimeout(processSubset, 0); } else { doneCallback(array); } } }
javascript
{ "resource": "" }
q3076
train
function () { delete this.gl; L.DomUtil.remove(this._container); L.DomEvent.off(this._container); delete this._container; }
javascript
{ "resource": "" }
q3077
Container
train
function Container(parent) { this.parent = parent; this.children = []; this.resolver = parent && parent.resolver || function() {}; this.registry = dictionary(parent ? parent.registry : null); this.cache = dictionary(parent ? parent.cache : null); this.factoryCache = dictionary(parent ? parent.factoryCache : null); this.resolveCache = dictionary(parent ? parent.resolveCache : null); this.typeInjections = dictionary(parent ? parent.typeInjections : null); this.injections = dictionary(null); this.normalizeCache = dictionary(null); this.factoryTypeInjections = dictionary(parent ? parent.factoryTypeInjections : null); this.factoryInjections = dictionary(null); this._options = dictionary(parent ? parent._options : null); this._typeOptions = dictionary(parent ? parent._typeOptions : null); }
javascript
{ "resource": "" }
q3078
train
function(fullName, factory, options) { Ember.assert('fullName must be a proper full name', validateFullName(fullName)); if (factory === undefined) { throw new TypeError('Attempting to register an unknown factory: `' + fullName + '`'); } var normalizedName = this.normalize(fullName); if (normalizedName in this.cache) { throw new Error('Cannot re-register: `' + fullName +'`, as it has already been looked up.'); } this.registry[normalizedName] = factory; this._options[normalizedName] = (options || {}); }
javascript
{ "resource": "" }
q3079
train
function(fullName) { Ember.assert('fullName must be a proper full name', validateFullName(fullName)); var normalizedName = this.normalize(fullName); delete this.registry[normalizedName]; delete this.cache[normalizedName]; delete this.factoryCache[normalizedName]; delete this.resolveCache[normalizedName]; delete this._options[normalizedName]; }
javascript
{ "resource": "" }
q3080
train
function(fullName, options) { Ember.assert('fullName must be a proper full name', validateFullName(fullName)); return lookup(this, this.normalize(fullName), options); }
javascript
{ "resource": "" }
q3081
train
function(type, property, fullName) { Ember.assert('fullName must be a proper full name', validateFullName(fullName)); if (this.parent) { illegalChildOperation('typeInjection'); } var fullNameType = fullName.split(':')[0]; if (fullNameType === type) { throw new Error('Cannot inject a `' + fullName + '` on other ' + type + '(s). Register the `' + fullName + '` as a different type and perform the typeInjection.'); } addTypeInjection(this.typeInjections, type, property, fullName); }
javascript
{ "resource": "" }
q3082
train
function(fullName, property, injectionName) { if (this.parent) { illegalChildOperation('injection'); } var normalizedName = this.normalize(fullName); var normalizedInjectionName = this.normalize(injectionName); validateFullName(injectionName); if (fullName.indexOf(':') === -1) { return this.factoryTypeInjection(normalizedName, property, normalizedInjectionName); } Ember.assert('fullName must be a proper full name', validateFullName(fullName)); if (this.factoryCache[normalizedName]) { throw new Error('Attempted to register a factoryInjection for a type that has already ' + 'been looked up. (\'' + normalizedName + '\', \'' + property + '\', \'' + injectionName + '\')'); } addInjection(this.factoryInjections, normalizedName, property, normalizedInjectionName); }
javascript
{ "resource": "" }
q3083
train
function() { for (var i = 0, length = this.children.length; i < length; i++) { this.children[i].destroy(); } this.children = []; eachDestroyable(this, function(item) { item.destroy(); }); this.parent = undefined; this.isDestroyed = true; }
javascript
{ "resource": "" }
q3084
train
function() { if (this.isDestroyed) { return; } // At this point, the App.Router must already be assigned if (this.Router) { var container = this.__container__; container.unregister('router:main'); container.register('router:main', this.Router); } this.runInitializers(); runLoadHooks('application', this); // At this point, any initializers or load hooks that would have wanted // to defer readiness have fired. In general, advancing readiness here // will proceed to didBecomeReady. this.advanceReadiness(); return this; }
javascript
{ "resource": "" }
q3085
train
function(namespace) { var container = new Container(); container.set = set; container.resolver = resolverFor(namespace); container.normalizeFullName = container.resolver.normalize; container.describe = container.resolver.describe; container.makeToString = container.resolver.makeToString; container.optionsForType('component', { singleton: false }); container.optionsForType('view', { singleton: false }); container.optionsForType('template', { instantiate: false }); container.optionsForType('helper', { instantiate: false }); container.register('application:main', namespace, { instantiate: false }); container.register('controller:basic', Controller, { instantiate: false }); container.register('controller:object', ObjectController, { instantiate: false }); container.register('controller:array', ArrayController, { instantiate: false }); container.register('view:select', SelectView); container.register('route:basic', Route, { instantiate: false }); container.register('event_dispatcher:main', EventDispatcher); container.register('router:main', Router); container.injection('router:main', 'namespace', 'application:main'); container.register('location:auto', AutoLocation); container.register('location:hash', HashLocation); container.register('location:history', HistoryLocation); container.register('location:none', NoneLocation); container.injection('controller', 'target', 'router:main'); container.injection('controller', 'namespace', 'application:main'); container.register('-bucket-cache:main', BucketCache); container.injection('router', '_bucketCache', '-bucket-cache:main'); container.injection('route', '_bucketCache', '-bucket-cache:main'); container.injection('controller', '_bucketCache', '-bucket-cache:main'); container.injection('route', 'router', 'router:main'); container.injection('location', 'rootURL', '-location-setting:root-url'); // DEBUGGING container.register('resolver-for-debugging:main', container.resolver.__resolver__, { instantiate: false }); container.injection('container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main'); container.injection('data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main'); // Custom resolver authors may want to register their own ContainerDebugAdapter with this key // ES6TODO: resolve this via import once ember-application package is ES6'ed if (!ContainerDebugAdapter) { ContainerDebugAdapter = requireModule('ember-extension-support/container_debug_adapter')['default']; } container.register('container-debug-adapter:main', ContainerDebugAdapter); return container; }
javascript
{ "resource": "" }
q3086
train
function() { var namespaces = emberA(Namespace.NAMESPACES); var types = emberA(); var self = this; namespaces.forEach(function(namespace) { for (var key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } // Even though we will filter again in `getModelTypes`, // we should not call `lookupContainer` on non-models // (especially when `Ember.MODEL_FACTORY_INJECTIONS` is `true`) if (!self.detect(namespace[key])) { continue; } var name = dasherize(key); if (!(namespace instanceof Application) && namespace.toString()) { name = namespace + '/' + name; } types.push(name); } }); return types; }
javascript
{ "resource": "" }
q3087
handlebarsGet
train
function handlebarsGet(root, path, options) { var data = options && options.data; var normalizedPath = normalizePath(root, path, data); var value; // In cases where the path begins with a keyword, change the // root to the value represented by that keyword, and ensure // the path is relative to it. root = normalizedPath.root; path = normalizedPath.path; // Ember.get with a null root and GlobalPath will fall back to // Ember.lookup, which is no longer allowed in templates. // // But when outputting a primitive, root will be the primitive // and path a blank string. These primitives should pass through // to `get`. if (root || path === '') { value = get(root, path); } if (detectIsGlobal(path)) { if (value === undefined && root !== Ember.lookup) { root = Ember.lookup; value = get(root, path); } if (root === Ember.lookup || root === null) { Ember.deprecate("Global lookup of "+path+" from a Handlebars template is deprecated."); } } return value; }
javascript
{ "resource": "" }
q3088
registerBoundHelper
train
function registerBoundHelper(name, fn) { var boundHelperArgs = slice.call(arguments, 1); var boundFn = makeBoundHelper.apply(this, boundHelperArgs); EmberHandlebars.registerHelper(name, boundFn); }
javascript
{ "resource": "" }
q3089
_triageMustacheHelper
train
function _triageMustacheHelper(property, options) { Ember.assert("You cannot pass more than one argument to the _triageMustache helper", arguments.length <= 2); var helper = EmberHandlebars.resolveHelper(options.data.view.container, property); if (helper) { return helper.call(this, options); } return helpers.bind.call(this, property, options); }
javascript
{ "resource": "" }
q3090
bindClasses
train
function bindClasses(context, classBindings, view, bindAttrId, options) { var ret = []; var newClass, value, elem; // Helper method to retrieve the property from the context and // determine which class string to return, based on whether it is // a Boolean or not. var classStringForPath = function(root, parsedPath, options) { var val; var path = parsedPath.path; if (path === 'this') { val = root; } else if (path === '') { val = true; } else { val = handlebarsGet(root, path, options); } return View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName); }; // For each property passed, loop through and setup // an observer. forEach.call(classBindings.split(' '), function(binding) { // Variable in which the old class value is saved. The observer function // closes over this variable, so it knows which string to remove when // the property changes. var oldClass; var observer; var parsedPath = View._parsePropertyPath(binding); var path = parsedPath.path; var pathRoot = context; var normalized; if (path !== '' && path !== 'this') { normalized = normalizePath(context, path, options.data); pathRoot = normalized.root; path = normalized.path; } // Set up an observer on the context. If the property changes, toggle the // class name. observer = function() { // Get the current value of the property newClass = classStringForPath(context, parsedPath, options); elem = bindAttrId ? view.$("[data-bindattr-" + bindAttrId + "='" + bindAttrId + "']") : view.$(); // If we can't find the element anymore, a parent template has been // re-rendered and we've been nuked. Remove the observer. if (!elem || elem.length === 0) { removeObserver(pathRoot, path, observer); } else { // If we had previously added a class to the element, remove it. if (oldClass) { elem.removeClass(oldClass); } // If necessary, add a new class. Make sure we keep track of it so // it can be removed in the future. if (newClass) { elem.addClass(newClass); oldClass = newClass; } else { oldClass = null; } } }; if (path !== '' && path !== 'this') { view.registerObserver(pathRoot, path, observer); } // We've already setup the observer; now we just need to figure out the // correct behavior right now on the first pass through. value = classStringForPath(context, parsedPath, options); if (value) { ret.push(value); // Make sure we save the current value so that it can be removed if the // observer fires. oldClass = value; } }); return ret; }
javascript
{ "resource": "" }
q3091
train
function(buffer) { // If not invoked via a triple-mustache ({{{foo}}}), escape // the content of the template. var escape = get(this, 'isEscaped'); var shouldDisplay = get(this, 'shouldDisplayFunc'); var preserveContext = get(this, 'preserveContext'); var context = get(this, 'previousContext'); var inverseTemplate = get(this, 'inverseTemplate'); var displayTemplate = get(this, 'displayTemplate'); var result = this.normalizedValue(); this._lastNormalizedValue = result; // First, test the conditional to see if we should // render the template or not. if (shouldDisplay(result)) { set(this, 'template', displayTemplate); // If we are preserving the context (for example, if this // is an #if block, call the template with the same object. if (preserveContext) { set(this, '_context', context); } else { // Otherwise, determine if this is a block bind or not. // If so, pass the specified object to the template if (displayTemplate) { set(this, '_context', result); } else { // This is not a bind block, just push the result of the // expression to the render context and return. if (result === null || result === undefined) { result = ""; } else if (!(result instanceof SafeString)) { result = String(result); } if (escape) { result = Handlebars.Utils.escapeExpression(result); } buffer.push(result); return; } } } else if (inverseTemplate) { set(this, 'template', inverseTemplate); if (preserveContext) { set(this, '_context', context); } else { set(this, '_context', result); } } else { set(this, 'template', function() { return ''; }); } return this._super(buffer); }
javascript
{ "resource": "" }
q3092
flushPendingChains
train
function flushPendingChains() { if (pendingQueue.length === 0) { return; } // nothing to do var queue = pendingQueue; pendingQueue = []; forEach.call(queue, function(q) { q[0].add(q[1]); }); warn('Watching an undefined global, Ember expects watched globals to be setup by the time the run loop is flushed, check for typos', pendingQueue.length === 0); }
javascript
{ "resource": "" }
q3093
deprecateProperty
train
function deprecateProperty(object, deprecatedKey, newKey) { function deprecate() { Ember.deprecate('Usage of `' + deprecatedKey + '` is deprecated, use `' + newKey + '` instead.'); } if (hasPropertyAccessors) { defineProperty(object, deprecatedKey, { configurable: true, enumerable: false, set: function(value) { deprecate(); set(this, newKey, value); }, get: function() { deprecate(); return get(this, newKey); } }); } }
javascript
{ "resource": "" }
q3094
indexOf
train
function indexOf(obj, element, index) { return obj.indexOf ? obj.indexOf(element, index) : _indexOf.call(obj, element, index); }
javascript
{ "resource": "" }
q3095
indexesOf
train
function indexesOf(obj, elements) { return elements === undefined ? [] : map(elements, function(item) { return indexOf(obj, item); }); }
javascript
{ "resource": "" }
q3096
addObject
train
function addObject(array, item) { var index = indexOf(array, item); if (index === -1) { array.push(item); } }
javascript
{ "resource": "" }
q3097
intersection
train
function intersection(array1, array2) { var result = []; forEach(array1, function(element) { if (indexOf(array2, element) >= 0) { result.push(element); } }); return result; }
javascript
{ "resource": "" }
q3098
watchedEvents
train
function watchedEvents(obj) { var listeners = obj['__ember_meta__'].listeners, ret = []; if (listeners) { for(var eventName in listeners) { if (listeners[eventName]) { ret.push(eventName); } } } return ret; }
javascript
{ "resource": "" }
q3099
isEmpty
train
function isEmpty(obj) { var none = isNone(obj); if (none) { return none; } if (typeof obj.size === 'number') { return !obj.size; } var objectType = typeof obj; if (objectType === 'object') { var size = get(obj, 'size'); if (typeof size === 'number') { return !size; } } if (typeof obj.length === 'number' && objectType !== 'function') { return !obj.length; } if (objectType === 'object') { var length = get(obj, 'length'); if (typeof length === 'number') { return !length; } } return false; }
javascript
{ "resource": "" }