_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q39600
getNew
train
function getNew(body) { // If we haven't already cleared the callback (we got the body, then the // message on the subscriber) if (timer) { // If the new body is present (say, if it wasn't deleted) if (body) { // Calculate the new Etag ourEtag = '"' + sha1hex(body) + '"'; // If it's a new body (which it almost certainly should be) if (ourEtag != theirEtag) { sendNewEtagAndBody(body); } // If it's not a new body we do nothing and keep listening / waiting // If the new body is empty } else { // Respond that it is now Not Found respondNotFound(); } } }
javascript
{ "resource": "" }
q39601
setOverrideHeader
train
function setOverrideHeader(res, name, value) { if (res._headers && res._headers[name] !== undefined) { return true; } res.setHeader(name, value); return true; }
javascript
{ "resource": "" }
q39602
setWritableHeader
train
function setWritableHeader(res, name, value) { if (res._headerSent && res.finished) { return false; } res.setHeader(name, value); return true; }
javascript
{ "resource": "" }
q39603
train
function (options) { /** call event emitter */ events.EventEmitter.call(this); /** module default configuration */ var defaults = { idSelector: 'linotype', start: 0, currentSection: 0, delay: 300, easingdelay: 700, easing: false, isMoving: false, keyboardScrolling: true, touchevents: true, mousewheel: true, sections: null, numSections: 0, touchSensitivity: 5, sectionHeight: null, callback: false, normalscroll: false, continuous: false }; this.$el = null; /** extended default options */ this.options = extend(defaults, options); this.init(this.options); }
javascript
{ "resource": "" }
q39604
train
function (e) { var touchEvents = getEventsPage(e); touchStartY = touchEvents.y; touchStartX = touchEvents.x; if (e.touches) { touchMoveStartY = e.touches[0].screenY; touchMoveStartX = e.touches[0].screenX; } }
javascript
{ "resource": "" }
q39605
describeFailure
train
function describeFailure(ex) { return ex.stack? [' ---' ,' type: ' + ex.name ,' message: >' , pad(6, ex.message) ,' stack: | ' , pad(6, ex.stack) ,' ...' ].join('\n') : /* otherwise */ [' ---' ,' message: >' , pad(6, ex.toString()) ,' ...' ].join('\n') }
javascript
{ "resource": "" }
q39606
TwistFilter
train
function TwistFilter() { core.AbstractFilter.call(this, // vertex shader null, // fragment shader fs.readFileSync(__dirname + '/twist.frag', 'utf8'), // custom uniforms { radius: { type: '1f', value: 0.5 }, angle: { type: '1f', value: 5 }, offset: { type: 'v2', value: { x: 0.5, y: 0.5 } } } ); }
javascript
{ "resource": "" }
q39607
lintScripts
train
function lintScripts(conf, undertaker) { const jsSrc = path.join(conf.themeConfig.root, conf.themeConfig.js.src, '**', '*.js'); // Lint theme scripts with ESLint. This won't touch any TypeScript files. return undertaker.src(jsSrc) .pipe(eslint()) .pipe(eslint.format()) .pipe(gulpIf(conf.productionMode, eslint.failAfterError())); }
javascript
{ "resource": "" }
q39608
switchState
train
function switchState(started, pkg) { pkg.started = started; //add available port back into port range if (!started && pkg.env && pkg.env.PORT) ports.push(pkg.env.PORT); console.log((started ? 'Started' : 'Stopped') + ' application ' + pkg.user + '/' + pkg.name); logInfo('info', 'Application ' + (started ? 'started' : 'stopped'), {name: pkg.app, user: pkg.user}); droneModel.createOrUpdate(pkg, function(){}); }
javascript
{ "resource": "" }
q39609
switchAndClear
train
function switchAndClear(pkg) { switchState(false, pkg); //unload proxy routes proxy.deleteBy(app.config.get('public-port'), {user: pkg.user, appid: pkg.name}); }
javascript
{ "resource": "" }
q39610
findSwitchAndClear
train
function findSwitchAndClear(uid) { if (uid) { droneModel.getProcessed({uid: uid}, function(err, result) { if (!err && result && result.length == 1) { switchAndClear(result[0]); } }); } }
javascript
{ "resource": "" }
q39611
startDrone
train
function startDrone(pkg, userid, appid, callback) { var drone_port = getPort(); if (drone_port) { pkg.env = pkg.env || {}; pkg.env['PORT'] = drone_port; //ensure package user and name match internally pkg.user = userid; pkg.name = appid; drone.start(pkg, function(err, result) { if (err) callback(err); pkg.host = result.host; pkg.port = result.port; pkg.uid = result.uid; //async update package in db droneModel.createOrUpdate(pkg, function(){}); //load proxy routes proxy.load(app.config.get('public-port'), pkg); callback(null, {drone: result}); }); }else{ callback({message: 'No more ports available'}); } }
javascript
{ "resource": "" }
q39612
stopDrone
train
function stopDrone(userid, appid, callback) { droneModel.getProcessed({user: userid, name: appid}, function(err, result) { if (err) return callback(err); if (result.length == 1) { if (!result[0].started) { callback({message: 'Drone is already stopped'}); }else{ //need to namespace apps to allow for two users with same app name drone.stop(appid, function(err, response) { if (err) return callback(err); result[0].started = false; callback(null, result[0]); }); } }else{ callback({message: 'No drone matching ' + userid + '/' + appid}); } }); }
javascript
{ "resource": "" }
q39613
sendDrones
train
function sendDrones(filter, res) { droneModel.getProcessed(filter, function(err, result) { if (err) return haibu.sendResponse(res, 500, err); haibu.sendResponse(res, 200, {drones: result}); }); }
javascript
{ "resource": "" }
q39614
train
function(ethereumAddress, ethereumDataDir, ethereumAccountPassword, cb = null){ if(isFunction(cb)){ try { keythereum.importFromFile(ethereumAddress, ethereumDataDir, function(keyObject){ keythereum.recover(ethereumAccountPassword, keyObject, function(privateKey){ return cb(null, privateKey) }) }) } catch (err){ return cb(err) } } else { try { var keyObject = keythereum.importFromFile(ethereumAddress, ethereumDataDir) return keythereum.recover(ethereumAccountPassword, keyObject) } catch (err){ return err } } }
javascript
{ "resource": "" }
q39615
train
function(privateKey, cb = null){ if(isFunction(cb)){ try { return cb(null, ethUtils.privateToPublic(privateKey)) } catch(err){ return cb(err) } } else { try { return ethUtils.privateToPublic(privateKey) } catch(err){ return err } } }
javascript
{ "resource": "" }
q39616
train
function(message, signatureObject, cb = null){ var result = false var ethSig = toEthUtilsSignature(signatureObject) try { var isSigValid = ethUtils.isValidSignature(ethSig.v, ethSig.r, ethSig.s) var isPubKeyValid = ethUtils.isValidPublic(signatureObject.publicKey) //convert public key to secp256k1 format signatureObject.publicKey = getSecp256k1PublicKey(signatureObject.publicKey) var isSigVerified = secp256k1.verify(ethUtils.sha3(message), signatureObject.signature, signatureObject.publicKey) if(isSigVerified){ result = true } } catch(err){ result = err } if(isFunction(cb)){ if(result instanceof Error){ return cb(result) } else { return cb(null, result) } } else { return result } }
javascript
{ "resource": "" }
q39617
train
function(signatureObject, publicKey, bufferEncoding = DEFAULT_ENCODING, cb = null){ var clonedSignatureObj = { signature: signatureObject.signature, recovery: signatureObject.recovery, publicKey: publicKey } bufferEncoding = getEncodingOrDefault(bufferEncoding) if(isFunction(cb)){ convertBuffersToStrings(clonedSignatureObj, bufferEncoding, function(convertedObj){ var base64String = Buffer.from(JSON.stringify(convertedObj)).toString('base64') return cb(null, base64String) }) } else { var convertedObj = convertBuffersToStrings(clonedSignatureObj, bufferEncoding) var base64String = Buffer.from(JSON.stringify(convertedObj)).toString('base64') return base64String } }
javascript
{ "resource": "" }
q39618
train
function(base64String, bufferEncoding = DEFAULT_ENCODING, cb = null){ bufferEncoding = getEncodingOrDefault(bufferEncoding) var decodedObj = JSON.parse(Buffer.from(base64String, 'base64').toString()) var result = {} if('signature' in decodedObj && 'recovery' in decodedObj){ result = decodedObj result.signature = Buffer.from(result.signature, bufferEncoding) if('publicKey' in decodedObj){ result.publicKey = Buffer.from(result.publicKey, bufferEncoding) } } else { result = new Error("decoded object does not contain all required elements!") } if(isFunction(cb)){ if(result instanceof Error){ return cb(result) } else { return cb(null, result) } } else { return result } }
javascript
{ "resource": "" }
q39619
getConnection
train
function getConnection (config) { var sequelize var defaultStorage = 'store.db' var logging = config.logging || false if (config.dialect === 'sqlite') { if (!config.storage) { config.storage = defaultStorage } sequelize = new Sequelize(config.database, config.username, config.password, { host: config.host, dialect: config.dialect, storage: config.storage, logging: logging }) } else { sequelize = new Sequelize(config.database, config.username, config.password, { host: config.host, dialect: config.dialect, logging: logging }) } return sequelize }
javascript
{ "resource": "" }
q39620
runSQL
train
function runSQL (sql, config, conn, replacements) { return new Promise(function (resolve, reject) { if (!config && !conn) { reject('Must set config or connection') } if (!sql) { reject('Need some sql') } if (!conn) { conn = getConnection(config) } replacements = replacements || {} conn.query(sql, { replacements: replacements }).then(function (ret) { return resolve({'ret': ret, 'conn': conn}) }).catch(function (err) { return reject(err) }) }) }
javascript
{ "resource": "" }
q39621
_checkCircular
train
function _checkCircular (opts, obj) { var key if (util.isObject(obj)) { if (~opts._visited.indexOf(obj)) { return true } opts._visited.push(obj) for (key in obj) { if (obj.hasOwnProperty(key) && _checkCircular(opts, obj[key])) { return true } } } return false }
javascript
{ "resource": "" }
q39622
merge
train
function merge () { var args = [].slice.call(arguments) args.unshift({}) return mergeExt.apply(null, args) }
javascript
{ "resource": "" }
q39623
_segment
train
function _segment (char) { var tmp char = char || '.' return function (k) { if (tmp) { tmp += char + k if (CLOSE.test(k)) { k = tmp tmp = '' } else { return } } else if (OPEN.test(k)) { tmp = k if (CLOSE.test(k)) { tmp = '' } else { return } } return k.trim().replace(QUOTES, '$2') } }
javascript
{ "resource": "" }
q39624
_splitPath
train
function _splitPath (keys) { var out if (util.isString(keys)) { out = [] keys .split('.') .map(_segment('.')) .forEach(function (k) { k = (k || ' ').trim() .replace(/^([^[]+)\[(["']?)(.+)\2\]$/, function (m, m1, m2, m3) { if (m1 && m3) { out.push(m1, m3) } return '' }) if (k) { out.push(k) } }) keys = out } return keys }
javascript
{ "resource": "" }
q39625
_splitProps
train
function _splitProps (props) { var test = {} if (util.isString(props)) { props = props .split(',') .map(_segment(',')) .filter(function (k) { return k }) } if (util.isArray(props)) { props.forEach(function (key) { test[key] = 1 }) return test } return {} }
javascript
{ "resource": "" }
q39626
pick
train
function pick (obj, props) { var key var val var out var test = _splitProps(props) if (util.isObject(obj)) { out = {} for (key in test) { val = get(obj, key) if (val !== undefined && val !== null) { set(out, key, val) } } } return out }
javascript
{ "resource": "" }
q39627
omit
train
function omit (obj, props) { var key var out var test = _splitProps(props) if (util.isObject(obj)) { out = clone(obj) for (key in test) { if ((get(obj, key))) { set(out, key, null) } } } return out }
javascript
{ "resource": "" }
q39628
get
train
function get (obj, keys, _default) { var i var key var tmp = obj || {} keys = _splitPath(keys) if (!keys || keys.length === 0) { return _default } for (i = 0; i < keys.length; i++) { key = keys[i] if (tmp && tmp.hasOwnProperty(key)) { tmp = tmp[key] } else { return _default } } return tmp }
javascript
{ "resource": "" }
q39629
set
train
function set (obj, keys, value) { var i var key var last var tmp = obj || {} keys = _splitPath(keys) if (!keys || keys.length === 0) { return } last = keys.pop() for (i = 0; i < keys.length; i++) { key = keys[i] if (!tmp[key]) { tmp[key] = {} } if (tmp.hasOwnProperty(key)) { tmp = tmp[key] } } if (value === null) { delete (tmp[last]) } else { tmp[last] = value } return obj }
javascript
{ "resource": "" }
q39630
arrayIndexOf
train
function arrayIndexOf (array, val) { // Use native indexOf if (Array.prototype.indexOf) { return array.indexOf(val); } // Use loop/if for environments without native indexOf var i, len = array.length; for (i = 0; i < len; len += 1) { if (array[i] === val) { return i; } } return -1; }
javascript
{ "resource": "" }
q39631
train
function (type, handler) { // Validate arguments if (typeof type !== 'string') { throw new Error('Type must be a string'); } if (typeof handler !== 'function') { throw new Error('Handler must be a function'); } // Check for presence of event store if (!this._events) { this._events = {}; } if (!this._events[type]) { this._events[type] = []; } // Add handler this._events[type].push(handler); }
javascript
{ "resource": "" }
q39632
train
function (type, handler) { // Validate arguments if (typeof type !== 'undefined' && typeof type !== 'string') { throw new Error('Type must be a string or undefined'); } if (typeof handler !== 'undefined' && typeof handler !== 'function') { throw new Error('Handler must be a function or undefined'); } // If no type is given, remove all handlers if (!type) { return delete this._events; } // Check for presence of event store if (!this._events || !this._events[type]) { return; } // If no handler is given, remove all handlers for this type if (!handler) { return delete this._events[type]; } // Do we have a matching handler? var handlers = this._events[type]; var i = arrayIndexOf(handlers, handler); if (i === -1) { return; } // Remove handler handlers.splice(i, 1); }
javascript
{ "resource": "" }
q39633
train
function (type, event) { // Validate arguments if (typeof type !== 'string') { throw new Error('Type must be a string'); } // Check for presence of event store if (!this._events || !this._events[type]) { return; } // Get handlers var handlers = this._events[type]; // Build event if (!(event instanceof Event)) { var data = event; event = new Event(data); } event.type = type; event.target = this; // Loop and call handlers var i, len = handlers.length; for (i = 0; i < len; i += 1) { handlers[i].call(this, event); // Prevent further handlers from being called if event is stopped if (event.stopped()) { break; } } }
javascript
{ "resource": "" }
q39634
Store
train
function Store(options) { if (!(this instanceof Store)) { return new Store(options); } if (typeof options === 'string') { options = { name: options }; } options = options || {}; var name = options.name || 'macros'; this.store = options.store || new utils.Store(name); }
javascript
{ "resource": "" }
q39635
_createProxyMethod
train
function _createProxyMethod(proxyMethodName, mixinMethodName, hostObject) { hostObject = hostObject || this._hostObject; // Mixin class does not allow shadowing methods that exist on the host object if (hostObject[proxyMethodName]) throw new Error('method ' + proxyMethodName + ' already defined in host object'); var method = this[mixinMethodName]; check(method, Function); // Bind proxied Mixin's method to Mixin instance var boundMethod = method.bind(this); Object.defineProperty(hostObject, proxyMethodName, { value: boundMethod, enumerable: false, configurable: false, writable: true }); }
javascript
{ "resource": "" }
q39636
_createProxyMethods
train
function _createProxyMethods(proxyMethods, hostObject) { check(proxyMethods, Match.Optional(Match.OneOf([String], Match.ObjectHash(String)))); // creating and binding proxy methods on the host object if (Array.isArray(proxyMethods)) proxyMethods.forEach(function(methodName) { // method called this way to allow using _createProxyMethods with objects // that are not inheriting from Mixin _createProxyMethod.call(this, methodName, methodName, hostObject); }, this); else for (var proxyMethodName in proxyMethods) { // method called this way to allow using _createProxyMethods with objects // that are not inheriting from Mixin if (proxyMethods.hasOwnProperty(proxyMethodName)) { var mixinMethodName = proxyMethods[proxyMethodName]; _createProxyMethod.call(this, proxyMethodName, mixinMethodName, hostObject); } } }
javascript
{ "resource": "" }
q39637
Mixin_setInstanceKey
train
function Mixin_setInstanceKey(hostClass, method, instanceKey) { check(hostClass, Function); check(instanceKey, Match.IdentifierString); var prop = INSTANCE_PROPERTIES_MAP, instanceKeys = hostClass[prop] = hostClass[prop] || {}; if (instanceKeys[method.name]) throw new Error('Mixin: instance property for method with name ' + method.name + ' is already set'); instanceKeys[method.name] = instanceKey; }
javascript
{ "resource": "" }
q39638
Mixin_addMethod
train
function Mixin_addMethod(hostClass, instanceKey, mixinMethodName, hostMethodName) { var method = this.prototype[mixinMethodName]; check(method, Function); var wrappedMethod = _wrapMixinMethod.call(this, method); Object.defineProperty(hostClass.prototype, hostMethodName, { value: wrappedMethod, enumerable: false, configurable: false, writable: true }); Mixin_setInstanceKey(hostClass, method, instanceKey); }
javascript
{ "resource": "" }
q39639
_wrapMixinMethod
train
function _wrapMixinMethod(method) { return function() { // ,... arguments var mixinInstance = _getMixinInstance.call(this, method.name); return method.apply(mixinInstance || this, arguments); }; }
javascript
{ "resource": "" }
q39640
Mixin$$useWith
train
function Mixin$$useWith(hostClass, instanceKey, mixinMethods) { check(mixinMethods, Match.Optional(Match.OneOf([String], Match.ObjectHash(String)))); if (Array.isArray(mixinMethods)) { mixinMethods.forEach(function(methodName) { Mixin_addMethod.call(this, hostClass, instanceKey, methodName, methodName); }, this); } else { for (var hostMethodName in mixinMethods) { if (mixinMethods.hasOwnProperty(hostMethodName)) { var mixinMethodName = mixinMethods[hostMethodName]; Mixin_addMethod.call(this, hostClass, instanceKey, mixinMethodName, hostMethodName); } } } }
javascript
{ "resource": "" }
q39641
boundClass
train
function boundClass(target) { // (Using reflect to get all keys including symbols) let keys // Use Reflect if exists if (typeof Reflect !== 'undefined' && typeof Reflect.ownKeys === 'function') { keys = Reflect.ownKeys(target.prototype) } else { keys = Object.getOwnPropertyNames(target.prototype) // use symbols if support is provided if (typeof Object.getOwnPropertySymbols === 'function') { keys = keys.concat(Object.getOwnPropertySymbols(target.prototype)) } } keys.forEach(key => { // Ignore special case target method if (key === 'constructor') { return } let descriptor = Object.getOwnPropertyDescriptor(target.prototype, key) // Only methods need binding if (typeof descriptor.value === 'function') { Object.defineProperty(target.prototype, key, boundMethod(target, key, descriptor)) } }) return target }
javascript
{ "resource": "" }
q39642
boundMethod
train
function boundMethod(target, key, descriptor) { // console.log('target, key, descriptor', target, key, descriptor) let fn = descriptor.value if (typeof fn !== 'function') { throw new Error(`@autobind decorator can only be applied to methods not: ${typeof fn}`) } // In IE11 calling Object.defineProperty has a side-effect of evaluating the // getter for the property which is being replaced. This causes infinite // recursion and an "Out of stack space" error. let definingProperty = false return { configurable: true, get() { if (definingProperty || this === target.prototype || this.hasOwnProperty(key) || typeof fn !== 'function') { return fn } let boundFn = bind(fn, this)//fn.bind(this) definingProperty = true Object.defineProperty(this, key, { configurable: true, get() { return boundFn }, set(value) { fn = value delete this[key] } }) definingProperty = false return boundFn }, set(value) { fn = value } } }
javascript
{ "resource": "" }
q39643
configureStreamProcessingWithSettings
train
function configureStreamProcessingWithSettings(context, settings, standardSettings, standardOptions, event, awsContext, forceConfiguration, validateConfiguration) { // Configure all of the stream processing dependencies if not configured by configuring the given context as a // standard context with stage handling, logging, custom settings, an optional Kinesis instance and an optional // DynamoDB.DocumentClient instance using the given standard settings and standard options and ALSO optionally with // the current region, resolved stage and AWS context, if BOTH the optional given event and optional given AWS context // are defined contexts.configureStandardContext(context, standardSettings, standardOptions, event, awsContext, forceConfiguration); // If forceConfiguration is false check if the given context already has stream processing configured on it // and, if so, do nothing more and simply return the context as is (to prevent overriding an earlier configuration) if (!forceConfiguration && isStreamProcessingConfigured(context)) { // Configure the consumer id if possible configureConsumerId(context, awsContext); // Configure an AWS.Lambda instance for disabling of the Lambda's event source mapping if necessary lambdaCache.configureLambda(context); // Validate the stream processing configuration if (typeof validateConfiguration === 'function') validateConfiguration(context); else validateStreamProcessingConfiguration(context); return context; } // Configure stream processing with the given settings context.streamProcessing = settings; // Configure the consumer id if possible configureConsumerId(context, awsContext); // Configure an AWS.Lambda instance for disabling of the Lambda's event source mapping if necessary lambdaCache.configureLambda(context); // Validate the stream processing configuration if (typeof validateConfiguration === 'function') validateConfiguration(context); else validateStreamProcessingConfiguration(context); return context; }
javascript
{ "resource": "" }
q39644
useStreamEventRecordAsMessage
train
function useStreamEventRecordAsMessage(record, batch, extractMessageFromRecord, context) { if (!record || typeof record !== 'object') { context.warn(`Adding invalid record (${record}) as an unusable record`); return Promise.resolve([{unusableRec: batch.addUnusableRecord(record, undefined, `invalid record (${record})`, context)}]); } const messageOutcome = Try.try(() => copy(record, deep)); // Add the "message" or unusable record to the batch return messageOutcome.map( message => { return [batch.addMessage(message, record, undefined, context)]; }, err => { return [{unusableRec: batch.addUnusableRecord(record, undefined, err.message, context)}]; } ).toPromise(); }
javascript
{ "resource": "" }
q39645
disableSourceStreamEventSourceMapping
train
function disableSourceStreamEventSourceMapping(batch, context) { const functionName = tracking.getInvokedFunctionNameWithAliasOrVersion(context); const batchKey = batch.key; const sourceStreamName = (batchKey && batchKey.components && batchKey.components.streamName) || (tracking.getSourceStreamNames(batch.records, context).find(n => isNotBlank(n))); if (isBlank(functionName) || isBlank(sourceStreamName)) { const errMsg = `FATAL - Cannot disable source stream event source mapping WITHOUT both function (${functionName}) & stream (${sourceStreamName})`; context.error(errMsg); return Promise.reject(new FatalError(errMsg)); } const avoidEsmCache = context.streamProcessing && context.streamProcessing.avoidEsmCache; return esmCache.disableEventSourceMapping(functionName, sourceStreamName, avoidEsmCache, context); }
javascript
{ "resource": "" }
q39646
sendEvents
train
function sendEvents() { logger.logEnter('sendEvents with eventCount ' + eventCount); if (eventCount > 0) { // If there are fewer than 10 events, we wait for more to arrive // before sending them. Only delay sending them once so they // don't get too old. if (eventCount < 10 && canDelaySend) { // Wait for more events. canDelaySend = false; logger.logExit('sendEvents, wait for more events'); return; } // Post the events. canDelaySend = true; // Ensure they're valid. validate(); if (eventCount === 0) { // All events were invalid. We're done. logger.logExit('sendEvents, all events were invalid'); return; } try { // Use one of the three APIs: there's one for a single // event, one for multiple events of the same type, and // one for a mix of types. var path, request, eventData, failureCallback, retryEventCount, retryEventData, retryBuffer; if (buffer.length === 1) { // They're all the same type. eventData = buffer[0]; if(runningInPublicEnv) { path = '/imfmobileanalytics/proxy/v1/apps/' + settings.AZFilterAppId + '/' + eventData[0]; } else { path = '/' + eventData[0]; } if (eventCount > 1) { path += '/_bulk'; } if(runningInPublicEnv) { // Deal with expiration of access token by refreshing token and retry the request. retryEventCount = eventCount; retryEventData = eventData; failureCallback = function(failureResponse, failureMessage) { emitter.emit('error', failureMessage); if(failureResponse.statusCode === 401) { logger.log('Received 401 Unathorized response while posting event(s) of same type. Refresh access token and retry the post.'); environment.refreshProxyAccessToken(); var retryRequest = createLogRequest(logger, utils, path, environment, emitter, null); if (retryEventCount > 1) { for (var i = 1; i < retryEventData.length; i++) { retryRequest.write('{"create":{}}\n'); retryRequest.write(JSON.stringify(retryEventData[i]) + '\n'); } retryRequest.end(); } else { retryRequest.end(JSON.stringify(retryEventData[1])); } } }; } request = createLogRequest(logger, utils, path, environment, emitter, failureCallback); // If this request processing logic is changed, then retryRequest processing above should also be changed. if (eventCount > 1) { for (var i = 1; i < eventData.length; i++) { request.write('{"create":{}}\n'); request.write(JSON.stringify(eventData[i]) + '\n'); } request.end(); } else { request.end(JSON.stringify(eventData[1])); } } else { // There's more than one type of event. if(runningInPublicEnv) { path = '/imfmobileanalytics/proxy/v1/apps/' + settings.AZFilterAppId + '/_bulk'; } else { path = '/_bulk'; } if(runningInPublicEnv) { // Deal with expiration of access token by refreshing token and retry the request. retryBuffer = buffer.slice(0); failureCallback = function(failureResponse, failureMessage) { emitter.emit('error', failureMessage); if(failureResponse.statusCode === 401) { logger.log('Received 401 Unathorized response while posting event(s) of different types. Refresh access token and retry the post.'); environment.refreshProxyAccessToken(); var retryRequest = createLogRequest(logger, utils, path, environment, emitter, null); for (var x = 0; x < retryBuffer.length; x++) { retryEventData = retryBuffer[x]; var createObject = '{"create":{"_type":"' + retryEventData[0] + '"}}\n'; for (var j = 1; j < retryEventData.length; j++) { retryRequest.write(createObject); retryRequest.write(JSON.stringify(retryEventData[j]) + '\n'); } } retryRequest.end(); } }; } request = createLogRequest(logger, utils, path, environment, emitter, failureCallback); // If this request processing logic is changed, then retryRequest processing above should also be changed. for (var x = 0; x < buffer.length; x++) { eventData = buffer[x]; var createObject = '{"create":{"_type":"' + eventData[0] + '"}}\n'; for (var j = 1; j < eventData.length; j++) { request.write(createObject); request.write(JSON.stringify(eventData[j]) + '\n'); } } request.end(); } } catch (thrown) { emitter.emit('error', 'While reporting events, caught ' + thrown); } buffer.clear(); } logger.logExit('sendEvents'); }
javascript
{ "resource": "" }
q39647
validate
train
function validate() { logger.logEnter('validate'); for (var i = 0; i < buffer.length; i++) { var eventData = buffer[i], typeName = eventData[0], typeKeys = eventTypes[typeName]; if (!typeKeys) { emitter.emit('error', typeName + ' is not a known event type.'); // Remove these events. eventCount -= eventData.length - 1; buffer.splice(i, 1); i--; } else { for (var j = 1; j < eventData.length; j++) { if (!validEvent(Object.keys(eventData[j]), typeKeys, emitter, typeName)) { // Remove this event. eventCount--; if (eventData.length === 2) { buffer.splice(i, 1); i--; break; } else { eventData.splice(j, 1); j--; } } } } } logger.logExit('validate'); }
javascript
{ "resource": "" }
q39648
validEvent
train
function validEvent(eventKeys, typeKeys, emitter, typeName) { if (eventKeys.length > typeKeys.length) { emitter.emit('error', 'An event has more properties than its type, ' + typeName + '. Event properties: [' + eventKeys + ']. ' + typeName + ' properties: [' + typeKeys + '].'); return false; } else { for (var i = 0; i < eventKeys.length; i++) { if (typeKeys.indexOf(eventKeys[i]) === -1) { emitter.emit('error', 'An event has property "' + eventKeys[i] + '" which is not in its type, ' + typeName + '. Event properties: [' + eventKeys + ']. ' + typeName + ' properties: [' + typeKeys + '].'); return false; } } return true; } }
javascript
{ "resource": "" }
q39649
createLogRequest
train
function createLogRequest(logger, utils, path, environment, emitter, failureCallback) { 'use strict'; logger.logEnter('createLogRequest ' + path); var options = environment.elasticsearchOptions('POST', path); var respConsumer = utils.responseConsumer(logger, 'after posting events', 200, failureCallback ? failureCallback : emitter, null, 201, options, path); var request = environment.request(options, respConsumer); request.once('error', function (e) { emitter.emit('error', 'Error while reporting events: ' + e); }); request.setHeader('Content-Type', 'text/plain'); logger.logExit('createLogRequest'); return request; }
javascript
{ "resource": "" }
q39650
fetchPackage
train
function fetchPackage(packageName, packageVersion) { // Get the latest matching version from NPM if a version range is specified return JudMarket.info(packageName).then(function(data){ //todo Market-Injection return util.getLatestMatchingNpmVersion(data.fullname, packageVersion).then( function (latestVersion) { return cachePackage(packageName, latestVersion); } ); }) }
javascript
{ "resource": "" }
q39651
cachePackage
train
function cachePackage(packageName, packageVersion) { //todo Market-Injection // WEEK_HOOK if(packageName !== "judpack-android" && packageName !== "judpack-ios") { packageName = JudMarket.info(packageName) } else { packageName = { fullname: packageName} } return Q(packageName).then(function (data) { packageName=data.fullname; // npm.config.set('registry','http://registry.npm.alibaba-inc.com'); /*if(data.p){ npm.config.set('registry','http://registry.npm.alibaba-inc.com'); } else{ npm.config.delete('registry'); }*/ var registry=data.p?'http://registry.npm.alibaba-inc.com':'http://registry.npm.taobao.org/'; var cacheDir = path.join(util.libDirectory, 'npm_cache'); // If already cached, use that rather than calling 'npm cache add' again. var packageCacheDir = path.resolve(cacheDir, packageName, packageVersion); var packageTGZ = path.resolve(packageCacheDir, 'package.tgz'); if (util.existsSync(packageTGZ)) { return unpack.unpackTgz(packageTGZ, path.resolve(packageCacheDir, 'package')); } // Load with NPM configuration return loadWithSettingsThenRestore({'cache': cacheDir,"registry":registry}, function () { // Invoke NPM Cache Add return Q.ninvoke(npm.commands, 'cache', ['add', (packageName + '@' + packageVersion)]).then( function (info) { var packageDir = path.resolve(npm.cache, info.name, info.version, 'package'); var packageTGZ = path.resolve(npm.cache, info.name, info.version, 'package.tgz'); return unpack.unpackTgz(packageTGZ, packageDir); } ); } ); }); }
javascript
{ "resource": "" }
q39652
evalRequiredError
train
function evalRequiredError(condition, required, type, name) { if (condition) { return new Error('Required argument <' + required + '> missing for ' + type + ': \'' + name + '\''); } return null; }
javascript
{ "resource": "" }
q39653
SocketServices
train
function SocketServices( options ){ options = options || {}; var self = this; this.logger = Logger.createLogger( 'socket', {'socket-services': VERSION}, options.logger ); self.server = options.server || { }; this.messageValidator = options.messageValidator || isCommunication; this.channel = options.channel || 'api'; this.event = options.event || 'rester'; self.logger.info('Will accepting communication on channel \'' + self.channel + '\' emitting to event \'' + self.event + '\'' ); this.inflicter = new Inflicter( { logger: self.logger, idLength: options.idLength || 16 } ); self.logger.info( 'Event system activated.' ); }
javascript
{ "resource": "" }
q39654
createOnAuthStateChangedChannel
train
function createOnAuthStateChangedChannel() { const auth = this.app.auth(); const channel = eventChannel(emit => auth.onAuthStateChanged(user => emit({ user })), ); return channel; }
javascript
{ "resource": "" }
q39655
DropShadowFilter
train
function DropShadowFilter() { core.AbstractFilter.call(this); this.blurXFilter = new BlurXFilter(); this.blurYTintFilter = new BlurYTintFilter(); this.defaultFilter = new core.AbstractFilter(); this.padding = 30; this._dirtyPosition = true; this._angle = 45 * Math.PI / 180; this._distance = 10; this.alpha = 0.75; this.hideObject = false; this.blendMode = core.BLEND_MODES.MULTIPLY; }
javascript
{ "resource": "" }
q39656
validate
train
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); var offset = 2 , arg , expires; // need string args (except for key, value) args.forEach(function(a, i, arr) { if(i > 1) { arr[i] = '' + a; } }) if(args.length > 7) { throw new CommandArgLength(cmd); }else if(args.length > 2) { arg = args[offset]; while(arg !== undefined) { arg = arg.toLowerCase(); args[offset] = arg; if(arg !== Constants.EX && arg !== Constants.PX && arg !== Constants.NX && arg !== Constants.XX) { throw CommandSyntax; } if(arg === Constants.EX || arg === Constants.PX) { expires = parseInt('' + args[offset + 1]); if(isNaN(expires)) { throw IntegerRange; } args[++offset] = expires; } arg = args[++offset]; } } }
javascript
{ "resource": "" }
q39657
ServerFacet
train
function ServerFacet($logs, $options, container) { if (!(this instanceof ServerFacet)) { return new ServerFacet($logs, $options, container); } this.name = ServerFacet.facetname; this.container = container; this.log = $logs.get('sit:jsonrpc:server#' + this.name); this.options = _.assign({}, $options[ServerFacet.facetname]); this._init(); }
javascript
{ "resource": "" }
q39658
train
function () { var self = this; _.each(_.clone(self._subscriptions), function (sub, id) { // Avoid killing the autoupdate subscription so that developers // still get hot code pushes when writing tests. // // XXX it's a hack to encode knowledge about autoupdate here, // but it doesn't seem worth it yet to have a special API for // subscriptions to preserve after unit tests. if (sub.name !== 'meteor_autoupdate_clientVersions') { self._send({msg: 'unsub', id: id}); delete self._subscriptions[id]; } }); }
javascript
{ "resource": "" }
q39659
_polarRadian
train
function _polarRadian(xyCenter, xyPointsArray) { // simplify the math by moving the computed circle center to [0, 0] var xAdj = 0 - xyCenter[0], yAdj = 0 - xyCenter[1]; return _.map(xyPointsArray, function(xy){ // reposition x and y relative to adjusted [0, 0] center var x = xy[0] + xAdj; var y = xy[1] + yAdj; var adjArcTan = Math.atan2(y, x); // compensate for quad3 and quad4 results if(adjArcTan < 0){ adjArcTan = 2 * Math.PI + adjArcTan; } return adjArcTan; }); }
javascript
{ "resource": "" }
q39660
_rotateRadian
train
function _rotateRadian(radiansRaw, radialAdj) { radialAdj %= TWOPI; return _.map(radiansRaw, function(r){ r += radialAdj; // for radial positions that cross the baseline, recompute if(r > TWOPI) { return r -= TWOPI; } if(r < 0) { return r += TWOPI; } return r; }); }
javascript
{ "resource": "" }
q39661
Messenger
train
function Messenger(namespace, options) { if (!(this instanceof Messenger)) { return new Messenger(namespace, options); } if (!namespace) { throw new Error('Cannot create Messenger without a namespace'); } events.EventEmitter.call(this); this.namespace = namespace; this.options = merge(Object.create(Messenger.DEFAULTS), options || {}); this.socketPath = this._getFileDescriptorPath(this.options.uid); this._init(); }
javascript
{ "resource": "" }
q39662
train
function(object, propertyMeta, property) { var that = this; object['_' + property] = undefined; // Adjust property 'type' and 'default fields if (_.isArray(propertyMeta)) { propertyMeta = propertyMeta.length === 3 || !_.isSimpleObject(propertyMeta[1]) ? { type: [propertyMeta[0], propertyMeta[2] || {}], default: propertyMeta[1] } : { type: propertyMeta } } else if (!_.isSimpleObject(propertyMeta)) { propertyMeta = { default: propertyMeta } } // Sets default property methods if (!('methods' in propertyMeta)) { propertyMeta.methods = ['get', 'set', 'has', 'is', 'clear', 'remove'] } object.__setPropertyParam(property, {}); // Process property meta data by options processors _.each(propertyMeta, function(data, option) { if (!(option in that._options)) { return; } var processor = that._options[option]; if (_.isString(processor)) { processor = meta(processor); } processor.process(object, data, property); }); }
javascript
{ "resource": "" }
q39663
_writeJSONFile
train
function _writeJSONFile (file, data, callback, replacer, space) { if ("undefined" === typeof file) { throw new ReferenceError("missing \"file\" argument"); } else if ("string" !== typeof file) { throw new TypeError("\"file\" argument is not a string"); } else if ("" === file.trim()) { throw new Error("\"file\" argument is empty"); } else if ("undefined" === typeof data) { throw new ReferenceError("missing \"data\" argument"); } else if ("undefined" === typeof callback) { throw new ReferenceError("missing \"callback\" argument"); } else if ("function" !== typeof callback) { throw new TypeError("\"callback\" argument is not a function"); } else { isFileProm(file).then((exists) => { return !exists ? Promise.resolve() : new Promise((resolve, reject) => { unlink(file, (err) => { return err ? reject(err) : resolve(); }); }); }).then(() => { return new Promise((resolve, reject) => { writeFile(file, JSON.stringify(data, replacer, space), (err) => { return err ? reject(err) : resolve(); }); }); }).then(() => { callback(null); }).catch(callback); } }
javascript
{ "resource": "" }
q39664
createContext
train
function createContext(params, onNext) { var context = function defaultCall(err) { return context.next(err); }; //additional parameters that are in effect beyond the object itself context.params = params || {}; //keep us from calling next after a failure context.failed = false; /* Fail causes a hard stop of the process with the error */ context.fail = function fail(err) { if (context.failed) throw new Error("Something caused Context.fail() to execute after the context is already failed."); failed = true; if (typeof err === "string") err = new Error(err); onNext(err); } /* Warn is a non-fatal informational warning error */ context.warn = function warn(err) { if (typeof err === "string") err = new Error(err); console.log("Warning from mock context", err); } /* Call when you are finished with your step and are passing to the next handler */ context.next = function next(err) { if (this.failed) throw new Error("Something caused Context.next() to execute after Context.fail()."); if (err) return this.fail(err); onNext(); } return context; }
javascript
{ "resource": "" }
q39665
hasGit
train
function hasGit(){ var checkGit; try { which.sync('git'); checkGit = true; } catch (ex) { checkGit = false; } return checkGit; }
javascript
{ "resource": "" }
q39666
loadScopes
train
function loadScopes(scopes) { var scopeMapping = {}; if (typeof scopes === 'object') { for (var s in scopes) { var routes = []; var entries = scopes[s]; debug('Scope: %s routes: %j', s, entries); if (Array.isArray(entries)) { for (var j = 0, k = entries.length; j < k; j++) { var route = entries[j]; if (typeof route === 'string') { routes.push({methods: ['all'], path: route, regexp: pathToRegexp(route, [], {end: false})}); } else { var methods = helpers.normalizeList(methods); if (methods.length === 0) { methods.push('all'); } methods = methods.map(toLowerCase); routes.push({methods: methods, path: route.path, regexp: pathToRegexp(route.path, [], {end: false})}); } } } else { debug('Routes must be an array: %j', entries); } scopeMapping[s] = routes; } } else if (typeof scopes === 'string') { scopes = helpers.normalizeList(scopes); for (var i = 0, n = scopes.length; i < n; i++) { scopeMapping[scopes[i]] = [ {methods: 'all', path: '/.+', regexp: /\/.+/} ]; } } return scopeMapping; }
javascript
{ "resource": "" }
q39667
getChild
train
function getChild() { let element = undefined; let name = undefined; let recursive = undefined; let arg1 = arguments[0]; if ((arg1 === window) || (arg1 === document) || (arg1 instanceof Node) || (arg1 === null) || (arg1 === undefined)) element = arg1; else if (typeof arg1 === 'string') name = arg1; else if (typeof arg1 === 'boolean') recursive = arg1; let arg2 = arguments[1]; if ((name === undefined) && ((typeof arg2 === 'string') || (arg2 === null) || (arg2 === undefined))) name = arg2; else if ((recursive === undefined) && (typeof arg2 === 'boolean')) recursive = arg2; let arg3 = arguments[2]; if ((recursive === undefined) && (typeof arg3 === 'boolean')) recursive = arg3; if (!assertType(name, 'string', true, 'Child name must be string')) return null; if (!assertType(recursive, 'boolean', true, 'Parameter \'recursive\', if specified, must be a boolean')) return null; let childRegistry = getChildRegistry(element); if (!childRegistry) return (typeof (element || document).querySelector === 'function') ? (element || document).querySelector(name) : null if (!name) return childRegistry; recursive = (typeof recursive === 'boolean') ? recursive : true; let targets = name.split('.'); let currentTarget = targets.shift(); let child = childRegistry[currentTarget]; if (recursive && (targets.length > 0)) { if (child instanceof Array) { let children = []; let n = child.length; for (let i = 0; i < n; i++) children.push(getChild(child[i], targets.join('.'), recursive)); return (noval(children, true) ? null : children); } else { return getChild(child, targets.join('.'), recursive); } } else { if (noval(child, true)) return (typeof (element || document).querySelector === 'function') ? (element || document).querySelector(name) : null; return child; } }
javascript
{ "resource": "" }
q39668
refcount
train
function refcount(req, res) { var obj = req.db.getKey(req.args[0], req); if(obj === undefined) return res.send(null, null); res.send(null, -1); }
javascript
{ "resource": "" }
q39669
idletime
train
function idletime(req, res) { var obj = req.db.getRawKey(req.args[0], req) , diff; if(obj === undefined) return res.send(null, null); diff = Date.now() - obj.t; diff = Math.round(diff / 1000); res.send(null, diff); }
javascript
{ "resource": "" }
q39670
encoding
train
function encoding(req, res) { var obj = req.db.getRawKey(req.args[0], req); if(obj === undefined) return res.send(null, null); res.send(null, getEncoding( req.db.getType(req.args[0]), obj.v, this.state.conf)); }
javascript
{ "resource": "" }
q39671
train
function () { if (!this.enabled || this.enabling) { return; } var err, cjsModule, id = this.map.id, depExports = this.depExports, exports = this.exports, factory = this.factory; if (!this.inited) { this.fetch(); } else if (this.error) { this.emit('error', this.error); } else if (!this.defining) { //The factory could trigger another require call //that would result in checking this module to //define itself again. If already in the process //of doing that, skip this work. this.defining = true; if (this.depCount < 1 && !this.defined) { if (isFunction(factory)) { //If there is an error listener, favor passing //to that instead of throwing an error. However, //only do it for define()'d modules. require //errbacks should not be called for failures in //their callbacks (#699). However if a global //onError is set, use that. if ((this.events.error && this.map.isDefine) || req.onError !== defaultOnError) { try { exports = context.execCb(id, factory, depExports, exports); } catch (e) { err = e; } } else { exports = context.execCb(id, factory, depExports, exports); } // Favor return value over exports. If node/cjs in play, // then will not have a return value anyway. Favor // module.exports assignment over exports object. if (this.map.isDefine && exports === undefined) { cjsModule = this.module; if (cjsModule) { exports = cjsModule.exports; } else if (this.usingExports) { //exports already set the defined value. exports = this.exports; } } if (err) { err.requireMap = this.map; err.requireModules = this.map.isDefine ? [this.map.id] : null; err.requireType = this.map.isDefine ? 'define' : 'require'; return onError((this.error = err)); } } else { //Just a literal value exports = factory; } this.exports = exports; if (this.map.isDefine && !this.ignore) { defined[id] = exports; if (req.onResourceLoad) { req.onResourceLoad(context, this.map, this.depMaps); } } //Clean up cleanRegistry(id); this.defined = true; } //Finished the define stage. Allow calling check again //to allow define notifications below in the case of a //cycle. this.defining = false; if (this.defined && !this.defineEmitted) { this.defineEmitted = true; this.emit('defined', this.exports); this.defineEmitComplete = true; } } }
javascript
{ "resource": "" }
q39672
parseGroupExpression
train
function parseGroupExpression() { var expr, expressions, startToken, isValidArrowParameter = true; expect('('); if (match(')')) { lex(); if (!match('=>')) { expect('=>'); } return { type: PlaceHolders.ArrowParameterPlaceHolder, params: [] }; } startToken = lookahead; if (match('...')) { expr = parseRestElement(); expect(')'); if (!match('=>')) { expect('=>'); } return { type: PlaceHolders.ArrowParameterPlaceHolder, params: [expr] }; } if (match('(')) { isValidArrowParameter = false; } expr = parseAssignmentExpression(); if (match(',')) { expressions = [expr]; while (startIndex < length) { if (!match(',')) { break; } lex(); if (match('...')) { if (!isValidArrowParameter) { throwUnexpectedToken(lookahead); } expressions.push(parseRestElement()); expect(')'); if (!match('=>')) { expect('=>'); } return { type: PlaceHolders.ArrowParameterPlaceHolder, params: expressions }; } else if (match('(')) { isValidArrowParameter = false; } expressions.push(parseAssignmentExpression()); } expr = new WrappingNode(startToken).finishSequenceExpression(expressions); } expect(')'); if (match('=>') && !isValidArrowParameter) { throwUnexpectedToken(lookahead); } return expr; }
javascript
{ "resource": "" }
q39673
parseStatementListItem
train
function parseStatementListItem() { if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'const': case 'let': return parseLexicalDeclaration(); case 'function': return parseFunctionDeclaration(new Node()); case 'class': return parseClassDeclaration(); } } return parseStatement(); }
javascript
{ "resource": "" }
q39674
includeFinished
train
function includeFinished(value) { //If a sync build environment, check for errors here, instead of //in the then callback below, since some errors, like two IDs pointed //to same URL but only one anon ID will leave the loader in an //unresolved state since a setTimeout cannot be used to check for //timeout. var hasError = false; if (syncChecks[env.get()]) { try { build.checkForErrors(context); } catch (e) { hasError = true; deferred.reject(e); } } if (!hasError) { deferred.resolve(value); } }
javascript
{ "resource": "" }
q39675
registerDriver
train
function registerDriver(Driver, name, options) { if (this.drivers[name]) { log.error(new Error('Driver "' + name + '" is already registered.')); return; } if (!Driver || !Driver.prototype || typeof Driver.prototype.send !== 'function') { log.error(new Error('Driver "' + name + '" should implement "send" method.')); return; } this.drivers[name] = new Driver(options || {}); }
javascript
{ "resource": "" }
q39676
getDriver
train
function getDriver(name) { if (!this.drivers[name]) { log.error(new Error('Driver "' + name + '" is not registered.')); return null; } return this.drivers[name]; }
javascript
{ "resource": "" }
q39677
registerTask
train
function registerTask(Task, name, options) { if (this.tasks[name]) { log.error(new Error('Task "' + name + '" is already registered.')); return; } if (!Task || !Task.prototype || typeof Task.prototype.run !== 'function') { log.error(new Error('Task "' + name + '" should implement "run" method.')); return; } this.tasks[name] = new Task(options || []); }
javascript
{ "resource": "" }
q39678
getTask
train
function getTask(name) { if (!this.tasks[name]) { log.error(new Error('Task "' + name + '" is not registered.')); return null; } return this.tasks[name]; }
javascript
{ "resource": "" }
q39679
run
train
function run(task_name, options, driver_name) { var task = this.tasks[task_name]; if (!task) { log.error(new Error('Task "' + task_name + '" is not registered.')); return; } var driver = this.drivers[driver_name]; if (!driver) { log.error(new Error('Driver "' + driver_name + '" is not registered.')); return; } return task.run(driver, options); }
javascript
{ "resource": "" }
q39680
nest
train
function nest(t, x, node, func, end) { x.stmtStack.push(node); var n = func(t, x); x.stmtStack.pop(); end && t.mustMatch(end); return n; }
javascript
{ "resource": "" }
q39681
NjsCompiler
train
function NjsCompiler(options) { this.nodeSequence = 0; this.options = options || {}; if (!this.options.runtime) { this.options.runtime = 'njs'; } this.parseBooleanOptions("exceptions", true); }
javascript
{ "resource": "" }
q39682
reader
train
function reader(str) { var matched; utils.some(rules, function (rule) { return utils.some(rule.regex, function (regex) { var match = str.match(regex), normalized; if (!match) { return; } normalized = match[rule.idx || 0].replace(/\s*$/, ''); normalized = (rule.hasOwnProperty('replace') && rule.replace.hasOwnProperty(normalized)) ? rule.replace[normalized] : normalized; matched = { match: normalized, type: rule.type, length: match[0].length }; return true; }); }); if (!matched) { matched = { match: str, type: TYPES.UNKNOWN, length: str.length }; } return matched; }
javascript
{ "resource": "" }
q39683
build
train
function build(mode, system, cdef, out, cb) { logger.info('building'); out.stdout('--> building'); builder.build(mode, system, cdef, out, function(err, specific) { if (err) { logger.error(err); return cb(err); } cb(err); }); }
javascript
{ "resource": "" }
q39684
needBuild
train
function needBuild(mode, system, cdef, out, cb) { // TODO handle authentication and HTTPS registries // also handle other registries than docker-registry-container var cmds = commands(os.platform()); var tag = cmds.generateTag(config, system, cdef); var baseUrl = 'http://' + config.registry + '/v1/repositories'; var url = tag.replace(config.registry, baseUrl) + '/tags'; request({ url: url, json: true }, function(err, res, body) { if (err) { return cb(err); } // return the missing definition, or null cb(null, Object.keys(body).length === 0 ? cdef : null); }); }
javascript
{ "resource": "" }
q39685
prepareAndGetExecutor
train
function prepareAndGetExecutor(target, out, operation) { target.privateIpAddress = target.privateIpAddress || target.ipAddress || target.ipaddress; var executor = platform.executor(config, target.privateIpAddress, os.platform(), logger); logger.info(operation); out.stdout(operation); return executor; }
javascript
{ "resource": "" }
q39686
deploy
train
function deploy(mode, target, system, containerDef, container, out, cb) { var executor = prepareAndGetExecutor(target, out, 'deploying'); executor.deploy(mode, target, system, containerDef, container, out, function(err) { cb(err); }); }
javascript
{ "resource": "" }
q39687
hup
train
function hup(mode, target, system, containerDef, container, newConfig, out, cb) { var executor = prepareAndGetExecutor(target, out, 'hup'); executor.hup(mode, target, system, containerDef, container, out, newConfig, function(err) { cb(err); }); }
javascript
{ "resource": "" }
q39688
toFn
train
function toFn (value) { if (typeof value === 'function') return value var str = Array.isArray(value) ? value : String(value) var obj = Object.create(null) for (var i = 0; i < str.length; i++) { obj[str[i]] = true } return function (char) { return obj[char] } }
javascript
{ "resource": "" }
q39689
trim
train
function trim (str, chars) { var fn = toFn(chars || WHITESPACE_CHARS) return trim.right(trim.left(str, fn), fn) }
javascript
{ "resource": "" }
q39690
processCsv
train
function processCsv (csvContent) { UNSAFE_SYMBOLS.forEach(function (symbolParams) { csvContent = csvContent.replace(symbolParams.pattern, symbolParams.replace); }); return csvContent; }
javascript
{ "resource": "" }
q39691
createLocales
train
function createLocales (json, params, callback) { var locales = registerLocales(json.shift()); var indexes = locales.indexes; var messageName; delete locales.indexes; json.forEach(function (messageLine) { var messageProp, lineValue, propPath; for (var i = 0, len = messageLine.length; i < len; i++) { lineValue = messageLine[i]; if (i === 0) { // The first item is a message name // or an empty string for a "description" messageName = lineValue || messageName; } else if (i === 1) { // The second is "message" or "description" messageProp = lineValue; } else { // All others are locales if (lineValue === '' && messageProp !== 'description') { continue; } propPath = [ indexes[i], 'messages', messageName ].join('.'); getByPath(locales, propPath, true)[messageProp] = messageProp !== 'placeholders' ? lineValue || '' : parsePlaceholders(lineValue); } } }); if (params.debug) { log('Generated locales:', locales); } writeLocales(locales, params, callback); }
javascript
{ "resource": "" }
q39692
parsePlaceholders
train
function parsePlaceholders (source) { return source.match(/\([^\)]+\)/g).reduce(function (result, placeholder) { placeholder = placeholder.replace(/^\(([^\)]+)\)$/, '$1'); var keyValue = placeholder.split(':'); result[keyValue[0]] = { content: keyValue[1] }; return result; }, {}); }
javascript
{ "resource": "" }
q39693
writeLocales
train
function writeLocales (locales, params, callback) { try { var jsonPath, json; for (var key in locales) { if (locales.hasOwnProperty(key)) { json = locales[key]; jsonPath = path.join(params.dirPath, json.localeName, 'messages.json'); // remove empty messages for (var msg_key in json.messages) { if (json.messages.hasOwnProperty(msg_key)) { if (json.messages[msg_key]['message'] == undefined) { delete json.messages[msg_key]; } } } fs.outputJsonSync(jsonPath, json.messages); if (params.debug) { log('Created file', jsonPath, json.messages); } } } callback(null); } catch (err) { callback(err); } }
javascript
{ "resource": "" }
q39694
registerLocales
train
function registerLocales (headers) { var localesList = { indexes: {} }; var i = headers.length - 1; var localeName; while (i >= 2) { localeName = headers[i].trim().split(/[\s\(]/)[0]; localesList[localeName] = { localeName: localeName, messages: {} }; localesList.indexes[i] = localeName; i--; } return localesList; }
javascript
{ "resource": "" }
q39695
processPath
train
function processPath (sourcePath, errorMessage) { if (!sourcePath || typeof sourcePath !== 'string') { throw new Error(errorMessage); } if (!path.isAbsolute(sourcePath)) { sourcePath = path.join(process.cwd(), sourcePath); } return sourcePath; }
javascript
{ "resource": "" }
q39696
assertBoolean
train
function assertBoolean(value, name, description) { if (!underscore.isBoolean(value)) { throw new Error( '<' + value + '> is not a boolean, ' + name + ': ' + description); } }
javascript
{ "resource": "" }
q39697
assertValidBuildType
train
function assertValidBuildType(value, name, description) { if ((value != common.DEBUG) && (value != common.RELEASE)) { throw new Error('Invalid build type: <' + value + '>, must be ' + 'closureProBuild.DEBUG or closureProBuild.RELEASE'); } }
javascript
{ "resource": "" }
q39698
assertObjectMapOf
train
function assertObjectMapOf(valueValidatorFn, value, name, description) { if (!underscore.isObject(value)) { throw new Error( '<' + value + '> is not an Object map, ' + name + ': ' + description); } // Check all values. for (var key in value) { valueValidatorFn(value[key], name + '[\'' + key + '\']', description); } }
javascript
{ "resource": "" }
q39699
loadJspmConfig
train
function loadJspmConfig(opts) { sh.echo('Loading jspm config...'); return new Promise(resolve => { const loader = new jspm.Loader(); opts.config(loader); resolve(loader); }); }
javascript
{ "resource": "" }