id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
52,000
milojs/ml-mixin
lib/mixin.js
Mixin$$useWith
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
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); } } } }
[ "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", ")", ";", "}", "}", "}", "}" ]
Adds methods of Mixin subclass to host class prototype. @param {Function} this Mixin subclass (not instance) @param {Object} hostClass host object class; must be specified. @param {String} instanceKey the name of the property the host class instance will store mixin instance on @param {Hash[String]|Array[String]} mixinMethods map of names of methods, key - host method name, value - mixin method name. Can be array.
[ "Adds", "methods", "of", "Mixin", "subclass", "to", "host", "class", "prototype", "." ]
7e6d220d8c8bdd598969edcbbc8886da644b7a24
https://github.com/milojs/ml-mixin/blob/7e6d220d8c8bdd598969edcbbc8886da644b7a24/lib/mixin.js#L212-L227
52,001
mistyjae/nd-utils
src/lib/autobind.js
boundClass
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
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 }
[ "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", "}" ]
Use boundMethod to bind all methods on the target.prototype
[ "Use", "boundMethod", "to", "bind", "all", "methods", "on", "the", "target", ".", "prototype" ]
43d7219ed3fe3b93cd6e01cb52afd28048fb8ea5
https://github.com/mistyjae/nd-utils/blob/43d7219ed3fe3b93cd6e01cb52afd28048fb8ea5/src/lib/autobind.js#L28-L56
52,002
mistyjae/nd-utils
src/lib/autobind.js
boundMethod
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
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 } } }
[ "function", "boundMethod", "(", "target", ",", "key", ",", "descriptor", ")", "{", "// console.log('target, key, descriptor', target, key, descriptor)", "let", "fn", "=", "descriptor", ".", "value", "if", "(", "typeof", "fn", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "`", "${", "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", "}", "}", "}" ]
Return a descriptor removing the value and returning a getter The getter will return a .bind version of the function and memoize the result against a symbol on the instance
[ "Return", "a", "descriptor", "removing", "the", "value", "and", "returning", "a", "getter", "The", "getter", "will", "return", "a", ".", "bind", "version", "of", "the", "function", "and", "memoize", "the", "result", "against", "a", "symbol", "on", "the", "instance" ]
43d7219ed3fe3b93cd6e01cb52afd28048fb8ea5
https://github.com/mistyjae/nd-utils/blob/43d7219ed3fe3b93cd6e01cb52afd28048fb8ea5/src/lib/autobind.js#L63-L103
52,003
byron-dupreez/aws-stream-consumer-core
stream-processing.js
configureStreamProcessingWithSettings
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
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; }
[ "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", ";", "}" ]
Configures the given context with the given stream processing settings, but only if stream processing is not already configured on the given context OR if forceConfiguration is true, and with the given standard settings and options. Note that if either the given event or AWS context are undefined, then everything other than the event, AWS context & stage will be configured. This missing configuration can be configured at a later point in your code by invoking {@linkcode module:aws-stream-consumer-core/stream-processing#configureEventAwsContextAndStage}. This separation of configuration is primarily useful for unit testing. @param {Object|StreamProcessing|StandardContext} context - the context onto which to configure the given stream processing settings and standard settings @param {StreamProcessingSettings} settings - the stream processing settings to use @param {StandardSettings|undefined} [standardSettings] - optional standard settings to use to configure dependencies @param {StandardOptions|undefined} [standardOptions] - optional standard options to use to configure dependencies @param {AWSEvent|undefined} [event] - the AWS event, which was passed to your lambda @param {AWSContext|undefined} [awsContext] - the AWS context, which was passed to your lambda @param {boolean|undefined} [forceConfiguration] - whether or not to force configuration of the given settings and options, which will override any previously configured stream processing and stage handling settings on the given context @param {function(context: StreamConsumerContext)|undefined} [validateConfiguration] - an optional function to use to further validate the configuration on the given context @return {StreamProcessing} the context object configured with stream processing (either existing or new) and standard settings
[ "Configures", "the", "given", "context", "with", "the", "given", "stream", "processing", "settings", "but", "only", "if", "stream", "processing", "is", "not", "already", "configured", "on", "the", "given", "context", "OR", "if", "forceConfiguration", "is", "true", "and", "with", "the", "given", "standard", "settings", "and", "options", "." ]
9b256084297f80d373bcf483aaf68a9da176b3d7
https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-processing.js#L118-L162
52,004
byron-dupreez/aws-stream-consumer-core
stream-processing.js
useStreamEventRecordAsMessage
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
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(); }
[ "function", "useStreamEventRecordAsMessage", "(", "record", ",", "batch", ",", "extractMessageFromRecord", ",", "context", ")", "{", "if", "(", "!", "record", "||", "typeof", "record", "!==", "'object'", ")", "{", "context", ".", "warn", "(", "`", "${", "record", "}", "`", ")", ";", "return", "Promise", ".", "resolve", "(", "[", "{", "unusableRec", ":", "batch", ".", "addUnusableRecord", "(", "record", ",", "undefined", ",", "`", "${", "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", "(", ")", ";", "}" ]
noinspection JSUnusedLocalSymbols A default `extractMessagesFromRecord` function that uses a copy of the given stream event record as the message object & adds the message, rejected message or unusable record to the given batch. @see ExtractMessagesFromRecord @param {StreamEventRecord} record - a stream event record @param {Batch} batch - the batch to which to add the extracted messages (or unusable records) @param {undefined} [extractMessageFromRecord] - not used @param {StreamProcessing} context - the context @return {Promise.<MsgOrUnusableRec[]>} a promise of an array containing a message (copy of the record), a rejected message or an unusable record
[ "noinspection", "JSUnusedLocalSymbols", "A", "default", "extractMessagesFromRecord", "function", "that", "uses", "a", "copy", "of", "the", "given", "stream", "event", "record", "as", "the", "message", "object", "&", "adds", "the", "message", "rejected", "message", "or", "unusable", "record", "to", "the", "given", "batch", "." ]
9b256084297f80d373bcf483aaf68a9da176b3d7
https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-processing.js#L275-L292
52,005
byron-dupreez/aws-stream-consumer-core
stream-processing.js
disableSourceStreamEventSourceMapping
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
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); }
[ "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", "=", "`", "${", "functionName", "}", "${", "sourceStreamName", "}", "`", ";", "context", ".", "error", "(", "errMsg", ")", ";", "return", "Promise", ".", "reject", "(", "new", "FatalError", "(", "errMsg", ")", ")", ";", "}", "const", "avoidEsmCache", "=", "context", ".", "streamProcessing", "&&", "context", ".", "streamProcessing", ".", "avoidEsmCache", ";", "return", "esmCache", ".", "disableEventSourceMapping", "(", "functionName", ",", "sourceStreamName", ",", "avoidEsmCache", ",", "context", ")", ";", "}" ]
Attempts to disable this Lambda's event source mapping to its source stream, which will disable this Lambda's trigger and prevent it from processing any more messages until the issue is resolved and the trigger is manually re-enabled. @param {Batch} batch @param {LambdaAware|StreamConsumerContext} context @returns {Promise.<*>|*}
[ "Attempts", "to", "disable", "this", "Lambda", "s", "event", "source", "mapping", "to", "its", "source", "stream", "which", "will", "disable", "this", "Lambda", "s", "trigger", "and", "prevent", "it", "from", "processing", "any", "more", "messages", "until", "the", "issue", "is", "resolved", "and", "the", "trigger", "is", "manually", "re", "-", "enabled", "." ]
9b256084297f80d373bcf483aaf68a9da176b3d7
https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/stream-processing.js#L416-L432
52,006
ibm-bluemix-mobile-services/bms-monitoring-sdk-node
event-buffer-factory.js
sendEvents
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
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'); }
[ "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'", ")", ";", "}" ]
This function will run every so often to send the buffered events to Elasticsearch.
[ "This", "function", "will", "run", "every", "so", "often", "to", "send", "the", "buffered", "events", "to", "Elasticsearch", "." ]
5b26fbd3b8adacb3fa9f4a0cbd60c8eae1a44df9
https://github.com/ibm-bluemix-mobile-services/bms-monitoring-sdk-node/blob/5b26fbd3b8adacb3fa9f4a0cbd60c8eae1a44df9/event-buffer-factory.js#L42-L195
52,007
ibm-bluemix-mobile-services/bms-monitoring-sdk-node
event-buffer-factory.js
validate
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
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'); }
[ "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'", ")", ";", "}" ]
Verifies that every event's type exists and it has the proper fields. Any invalid events are not sent to Elasticsearch, and an error is emitted for each.
[ "Verifies", "that", "every", "event", "s", "type", "exists", "and", "it", "has", "the", "proper", "fields", ".", "Any", "invalid", "events", "are", "not", "sent", "to", "Elasticsearch", "and", "an", "error", "is", "emitted", "for", "each", "." ]
5b26fbd3b8adacb3fa9f4a0cbd60c8eae1a44df9
https://github.com/ibm-bluemix-mobile-services/bms-monitoring-sdk-node/blob/5b26fbd3b8adacb3fa9f4a0cbd60c8eae1a44df9/event-buffer-factory.js#L265-L306
52,008
ibm-bluemix-mobile-services/bms-monitoring-sdk-node
event-buffer-factory.js
validEvent
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
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; } }
[ "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", ";", "}", "}" ]
Returns true if every element of eventKeys is in typeKeys.
[ "Returns", "true", "if", "every", "element", "of", "eventKeys", "is", "in", "typeKeys", "." ]
5b26fbd3b8adacb3fa9f4a0cbd60c8eae1a44df9
https://github.com/ibm-bluemix-mobile-services/bms-monitoring-sdk-node/blob/5b26fbd3b8adacb3fa9f4a0cbd60c8eae1a44df9/event-buffer-factory.js#L309-L326
52,009
ibm-bluemix-mobile-services/bms-monitoring-sdk-node
event-buffer-factory.js
createLogRequest
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
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; }
[ "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", ";", "}" ]
Creates and initializes a request object for POSTing to Elasticsearch.
[ "Creates", "and", "initializes", "a", "request", "object", "for", "POSTing", "to", "Elasticsearch", "." ]
5b26fbd3b8adacb3fa9f4a0cbd60c8eae1a44df9
https://github.com/ibm-bluemix-mobile-services/bms-monitoring-sdk-node/blob/5b26fbd3b8adacb3fa9f4a0cbd60c8eae1a44df9/event-buffer-factory.js#L334-L355
52,010
vkiding/judpack-lib
src/util/npm-helper.js
fetchPackage
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
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); } ); }) }
[ "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", ")", ";", "}", ")", ";", "}", ")", "}" ]
Fetches the latest version of a package from NPM that matches the specified version. Returns a promise that resolves to the directory the NPM package is located in. @param packageName - name of an npm package @param packageVersion - requested version or version range
[ "Fetches", "the", "latest", "version", "of", "a", "package", "from", "NPM", "that", "matches", "the", "specified", "version", ".", "Returns", "a", "promise", "that", "resolves", "to", "the", "directory", "the", "NPM", "package", "is", "located", "in", "." ]
8657cecfec68221109279106adca8dbc81f430f4
https://github.com/vkiding/judpack-lib/blob/8657cecfec68221109279106adca8dbc81f430f4/src/util/npm-helper.js#L84-L94
52,011
vkiding/judpack-lib
src/util/npm-helper.js
cachePackage
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
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); } ); } ); }); }
[ "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){\n npm.config.set('registry','http://registry.npm.alibaba-inc.com');\n }\n else{\n npm.config.delete('registry');\n }*/", "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", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Invokes "npm cache add," and then returns a promise that resolves to a directory containing the downloaded, or cached package. @param packageName - name of an npm package @param packageVersion - requested version (not a version range)
[ "Invokes", "npm", "cache", "add", "and", "then", "returns", "a", "promise", "that", "resolves", "to", "a", "directory", "containing", "the", "downloaded", "or", "cached", "package", "." ]
8657cecfec68221109279106adca8dbc81f430f4
https://github.com/vkiding/judpack-lib/blob/8657cecfec68221109279106adca8dbc81f430f4/src/util/npm-helper.js#L102-L146
52,012
arjunmehta/node-protogram
main.js
evalRequiredError
function evalRequiredError(condition, required, type, name) { if (condition) { return new Error('Required argument <' + required + '> missing for ' + type + ': \'' + name + '\''); } return null; }
javascript
function evalRequiredError(condition, required, type, name) { if (condition) { return new Error('Required argument <' + required + '> missing for ' + type + ': \'' + name + '\''); } return null; }
[ "function", "evalRequiredError", "(", "condition", ",", "required", ",", "type", ",", "name", ")", "{", "if", "(", "condition", ")", "{", "return", "new", "Error", "(", "'Required argument <'", "+", "required", "+", "'> missing for '", "+", "type", "+", "': \\''", "+", "name", "+", "'\\''", ")", ";", "}", "return", "null", ";", "}" ]
Core Helper Methods
[ "Core", "Helper", "Methods" ]
9769c735adb51b61dcb029bfdaf4b9bbe1c2d66a
https://github.com/arjunmehta/node-protogram/blob/9769c735adb51b61dcb029bfdaf4b9bbe1c2d66a/main.js#L230-L235
52,013
imrefazekas/socket-services
lib/SocketServices.js
SocketServices
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
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.' ); }
[ "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.'", ")", ";", "}" ]
Creates the SocketServices instance
[ "Creates", "the", "SocketServices", "instance" ]
cc81e87ed9fbc13836adac66009183390a90624c
https://github.com/imrefazekas/socket-services/blob/cc81e87ed9fbc13836adac66009183390a90624c/lib/SocketServices.js#L16-L35
52,014
hupe1980/firebase-sagas
src/sagas/authModule.js
createOnAuthStateChangedChannel
function createOnAuthStateChangedChannel() { const auth = this.app.auth(); const channel = eventChannel(emit => auth.onAuthStateChanged(user => emit({ user })), ); return channel; }
javascript
function createOnAuthStateChangedChannel() { const auth = this.app.auth(); const channel = eventChannel(emit => auth.onAuthStateChanged(user => emit({ user })), ); return channel; }
[ "function", "createOnAuthStateChangedChannel", "(", ")", "{", "const", "auth", "=", "this", ".", "app", ".", "auth", "(", ")", ";", "const", "channel", "=", "eventChannel", "(", "emit", "=>", "auth", ".", "onAuthStateChanged", "(", "user", "=>", "emit", "(", "{", "user", "}", ")", ")", ",", ")", ";", "return", "channel", ";", "}" ]
Creates channel that will subscribe to changes to the user's sign-in state. @returns {eventChannel} onAuthStateChangedChannel
[ "Creates", "channel", "that", "will", "subscribe", "to", "changes", "to", "the", "user", "s", "sign", "-", "in", "state", "." ]
030321ee9ceff80edaa3ac0cb2444cff9c90489f
https://github.com/hupe1980/firebase-sagas/blob/030321ee9ceff80edaa3ac0cb2444cff9c90489f/src/sagas/authModule.js#L139-L145
52,015
Nazariglez/perenquen
lib/pixi/src/filters/dropshadow/DropShadowFilter.js
DropShadowFilter
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
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; }
[ "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", ";", "}" ]
The DropShadowFilter applies a Gaussian blur to an object. The strength of the blur can be set for x- and y-axis separately. @class @extends AbstractFilter @memberof PIXI.filters
[ "The", "DropShadowFilter", "applies", "a", "Gaussian", "blur", "to", "an", "object", ".", "The", "strength", "of", "the", "blur", "can", "be", "set", "for", "x", "-", "and", "y", "-", "axis", "separately", "." ]
e023964d05afeefebdcac4e2044819fdfa3899ae
https://github.com/Nazariglez/perenquen/blob/e023964d05afeefebdcac4e2044819fdfa3899ae/lib/pixi/src/filters/dropshadow/DropShadowFilter.js#L13-L30
52,016
redisjs/jsr-server
lib/command/database/string/set.js
validate
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
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]; } } }
[ "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", "]", ";", "}", "}", "}" ]
Validate the SET command.
[ "Validate", "the", "SET", "command", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/database/string/set.js#L21-L57
52,017
taoyuan/sit
lib/facets/jsonrpc/server.js
ServerFacet
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
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(); }
[ "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", "(", ")", ";", "}" ]
owned app and server ?
[ "owned", "app", "and", "server", "?" ]
1ec54af9363d1a22264b3f25a3a1c9dd592aea66
https://github.com/taoyuan/sit/blob/1ec54af9363d1a22264b3f25a3a1c9dd592aea66/lib/facets/jsonrpc/server.js#L17-L29
52,018
xiamidaxia/xiami
meteor/livedata/common/livedata_connection.js
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
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]; } }); }
[ "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", "]", ";", "}", "}", ")", ";", "}" ]
This is very much a private function we use to make the tests take up fewer server resources after they complete.
[ "This", "is", "very", "much", "a", "private", "function", "we", "use", "to", "make", "the", "tests", "take", "up", "fewer", "server", "resources", "after", "they", "complete", "." ]
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/livedata/common/livedata_connection.js#L902-L916
52,019
kurttheviking/radial-index
index.js
_polarRadian
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
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; }); }
[ "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", ";", "}", ")", ";", "}" ]
_polarRadian compute radian component of polar coordinate relative to a center point @param {Array} xyCenter [x, y] center point to anchor radial sweep @param {Array} xyPointsArray Array of [x, y] arrays -- one for each point to index @return {Array} the radian position (between 0 and 2PI) of each coordinate
[ "_polarRadian", "compute", "radian", "component", "of", "polar", "coordinate", "relative", "to", "a", "center", "point" ]
60713ba03ca5f027d7ea5e5a3f82589b87e67f44
https://github.com/kurttheviking/radial-index/blob/60713ba03ca5f027d7ea5e5a3f82589b87e67f44/index.js#L92-L111
52,020
kurttheviking/radial-index
index.js
_rotateRadian
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
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; }); }
[ "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", ";", "}", ")", ";", "}" ]
_rotateRadian rotates a list of radial positions by the desired radian amount @param {Array} radiansRaw List of radial positions to rotate @param {Float} radialAdj The radial rotation to apply -- max rotation is 2PI @return {Array} rotates a list of radial positions by the desired radian amount
[ "_rotateRadian", "rotates", "a", "list", "of", "radial", "positions", "by", "the", "desired", "radian", "amount" ]
60713ba03ca5f027d7ea5e5a3f82589b87e67f44
https://github.com/kurttheviking/radial-index/blob/60713ba03ca5f027d7ea5e5a3f82589b87e67f44/index.js#L119-L131
52,021
emeryrose/ipsee
lib/messenger.js
Messenger
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
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(); }
[ "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", "(", ")", ";", "}" ]
Creates an IPC messenger @constructor @param {string} namespace - prefix for unix socket file descriptors @param {object} options - messenger configuration
[ "Creates", "an", "IPC", "messenger" ]
5d99bdf8bca6f03f7b112b23759d86acb6cd218b
https://github.com/emeryrose/ipsee/blob/5d99bdf8bca6f03f7b112b23759d86acb6cd218b/lib/messenger.js#L19-L35
52,022
alexpods/ClazzJS
src/components/meta/Property.js
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
Process single property for clazz @param {clazz|object} object Clazz or its prototype @param {object} propertyMeta Property meta data @param {string} property Property name @this {metaProcessor}
[ "Process", "single", "property", "for", "clazz" ]
2f94496019669813c8246d48fcceb12a3e68a870
https://github.com/alexpods/ClazzJS/blob/2f94496019669813c8246d48fcceb12a3e68a870/src/components/meta/Property.js#L32-L68
52,023
Psychopoulet/node-promfs
lib/extends/_writeJSONFile.js
_writeJSONFile
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
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); } }
[ "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", ")", ";", "}", "}" ]
methods Async writeJSONFile @param {string} file : file to check @param {function} data : data to write @param {function} callback : operation's result @param {function|null} replacer : JSON.stringify argument @param {string|number|null} space : JSON.stringify argument @returns {void}
[ "methods", "Async", "writeJSONFile" ]
016e272fc58c6ef6eae5ea551a0e8873f0ac20cc
https://github.com/Psychopoulet/node-promfs/blob/016e272fc58c6ef6eae5ea551a0e8873f0ac20cc/lib/extends/_writeJSONFile.js#L28-L78
52,024
postral/telegraphjs-context-mock
index.js
createContext
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
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; }
[ "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", ";", "/*\n Fail causes a hard stop of the process with the error\n */", "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", ")", ";", "}", "/*\n Warn is a non-fatal informational warning error\n */", "context", ".", "warn", "=", "function", "warn", "(", "err", ")", "{", "if", "(", "typeof", "err", "===", "\"string\"", ")", "err", "=", "new", "Error", "(", "err", ")", ";", "console", ".", "log", "(", "\"Warning from mock context\"", ",", "err", ")", ";", "}", "/*\n Call when you are finished with your step and are passing to the next handler\n */", "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", ";", "}" ]
A mock Context object @constructor @this {Context}
[ "A", "mock", "Context", "object" ]
f45c12849137a1c22c8d894f95f44e2a9d6549ce
https://github.com/postral/telegraphjs-context-mock/blob/f45c12849137a1c22c8d894f95f44e2a9d6549ce/index.js#L8-L52
52,025
rajasekarm/git-check
index.js
hasGit
function hasGit(){ var checkGit; try { which.sync('git'); checkGit = true; } catch (ex) { checkGit = false; } return checkGit; }
javascript
function hasGit(){ var checkGit; try { which.sync('git'); checkGit = true; } catch (ex) { checkGit = false; } return checkGit; }
[ "function", "hasGit", "(", ")", "{", "var", "checkGit", ";", "try", "{", "which", ".", "sync", "(", "'git'", ")", ";", "checkGit", "=", "true", ";", "}", "catch", "(", "ex", ")", "{", "checkGit", "=", "false", ";", "}", "return", "checkGit", ";", "}" ]
Check if git is installed
[ "Check", "if", "git", "is", "installed" ]
a3a762ea55f84b1a008a2640f55bc628b31fe735
https://github.com/rajasekarm/git-check/blob/a3a762ea55f84b1a008a2640f55bc628b31fe735/index.js#L4-L13
52,026
copress/copress-component-oauth2
lib/scope.js
loadScopes
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
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; }
[ "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", ";", "}" ]
Load the definition of scopes ```json { "scope1": [{"methods": "get", path: "/:user/profile"}, "/order"], "scope2": [{"methods": "post", path: "/:user/profile"}] } ``` @param {Object} scopes @returns {Object}
[ "Load", "the", "definition", "of", "scopes" ]
4819f379a0d42753bfd51e237c5c3aaddee37544
https://github.com/copress/copress-component-oauth2/blob/4819f379a0d42753bfd51e237c5c3aaddee37544/lib/scope.js#L22-L60
52,027
andrewscwei/requiem
src/dom/getChild.js
getChild
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
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; } }
[ "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", ";", "}", "}" ]
Gets the a child from the global display tree consisting of all sightread Element instances. @param {Node} [element] - Specifies the parent element instance to fetch the child from. @param {string} [name] - Name of the child, depth separated by '.' (i.e. 'foo.bar'). If unspecified, the entire child list of this Element will be returned. @param {boolean} [recursive=true] - Speciifies whether to search for the child recursively down the tree. @return {Node|Array|Object} @alias module:requiem~dom.getChild
[ "Gets", "the", "a", "child", "from", "the", "global", "display", "tree", "consisting", "of", "all", "sightread", "Element", "instances", "." ]
c4182bfffc9841c6de5718f689ad3c2060511777
https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/dom/getChild.js#L25-L79
52,028
redisjs/jsr-server
lib/command/database/key/object.js
refcount
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
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); }
[ "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", ")", ";", "}" ]
Respond to the REFCOUNT subcommand.
[ "Respond", "to", "the", "REFCOUNT", "subcommand", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/database/key/object.js#L18-L22
52,029
redisjs/jsr-server
lib/command/database/key/object.js
idletime
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
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); }
[ "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", ")", ";", "}" ]
Respond to the IDLETIME subcommand.
[ "Respond", "to", "the", "IDLETIME", "subcommand", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/database/key/object.js#L27-L34
52,030
redisjs/jsr-server
lib/command/database/key/object.js
encoding
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
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)); }
[ "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", ")", ")", ";", "}" ]
Respond to the ENCODING subcommand.
[ "Respond", "to", "the", "ENCODING", "subcommand", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/database/key/object.js#L39-L44
52,031
Gnucki/gnucki-r
bin/r.js
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
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; } } }
[ "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", ";", "}", "}", "}" ]
Checks if the module is ready to define itself, and if so, define it.
[ "Checks", "if", "the", "module", "is", "ready", "to", "define", "itself", "and", "if", "so", "define", "it", "." ]
7d916f7858fa30565d100e051e319b74bb250308
https://github.com/Gnucki/gnucki-r/blob/7d916f7858fa30565d100e051e319b74bb250308/bin/r.js#L1087-L1181
52,032
Gnucki/gnucki-r
bin/r.js
parseGroupExpression
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
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; }
[ "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", ";", "}" ]
11.1.6 The Grouping Operator
[ "11", ".", "1", ".", "6", "The", "Grouping", "Operator" ]
7d916f7858fa30565d100e051e319b74bb250308
https://github.com/Gnucki/gnucki-r/blob/7d916f7858fa30565d100e051e319b74bb250308/bin/r.js#L6993-L7068
52,033
Gnucki/gnucki-r
bin/r.js
parseStatementListItem
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
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(); }
[ "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", "(", ")", ";", "}" ]
12.1 Block
[ "12", ".", "1", "Block" ]
7d916f7858fa30565d100e051e319b74bb250308
https://github.com/Gnucki/gnucki-r/blob/7d916f7858fa30565d100e051e319b74bb250308/bin/r.js#L7622-L7636
52,034
Gnucki/gnucki-r
bin/r.js
includeFinished
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
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); } }
[ "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", ")", ";", "}", "}" ]
Use a wrapping function so can check for errors.
[ "Use", "a", "wrapping", "function", "so", "can", "check", "for", "errors", "." ]
7d916f7858fa30565d100e051e319b74bb250308
https://github.com/Gnucki/gnucki-r/blob/7d916f7858fa30565d100e051e319b74bb250308/bin/r.js#L28333-L28352
52,035
damsonjs/damson-core
index.js
registerDriver
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
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 || {}); }
[ "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", "||", "{", "}", ")", ";", "}" ]
Registers output driver @param {Function} Driver Damson driver constructor @param {string} name Damson driver name @param {object} options Damson driver options
[ "Registers", "output", "driver" ]
6caadc0e3c93f131d0f496b480ab69f758175e63
https://github.com/damsonjs/damson-core/blob/6caadc0e3c93f131d0f496b480ab69f758175e63/index.js#L11-L21
52,036
damsonjs/damson-core
index.js
getDriver
function getDriver(name) { if (!this.drivers[name]) { log.error(new Error('Driver "' + name + '" is not registered.')); return null; } return this.drivers[name]; }
javascript
function getDriver(name) { if (!this.drivers[name]) { log.error(new Error('Driver "' + name + '" is not registered.')); return null; } return this.drivers[name]; }
[ "function", "getDriver", "(", "name", ")", "{", "if", "(", "!", "this", ".", "drivers", "[", "name", "]", ")", "{", "log", ".", "error", "(", "new", "Error", "(", "'Driver \"'", "+", "name", "+", "'\" is not registered.'", ")", ")", ";", "return", "null", ";", "}", "return", "this", ".", "drivers", "[", "name", "]", ";", "}" ]
Returns registered driver @param {string} name Registered driver name @return {object|null} Damson driver object
[ "Returns", "registered", "driver" ]
6caadc0e3c93f131d0f496b480ab69f758175e63
https://github.com/damsonjs/damson-core/blob/6caadc0e3c93f131d0f496b480ab69f758175e63/index.js#L28-L34
52,037
damsonjs/damson-core
index.js
registerTask
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
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 || []); }
[ "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", "||", "[", "]", ")", ";", "}" ]
Registers damson Task @param {Function} Task Damson task constructor @param {string} name Damson task name @param {object} options Damson task options
[ "Registers", "damson", "Task" ]
6caadc0e3c93f131d0f496b480ab69f758175e63
https://github.com/damsonjs/damson-core/blob/6caadc0e3c93f131d0f496b480ab69f758175e63/index.js#L50-L60
52,038
damsonjs/damson-core
index.js
getTask
function getTask(name) { if (!this.tasks[name]) { log.error(new Error('Task "' + name + '" is not registered.')); return null; } return this.tasks[name]; }
javascript
function getTask(name) { if (!this.tasks[name]) { log.error(new Error('Task "' + name + '" is not registered.')); return null; } return this.tasks[name]; }
[ "function", "getTask", "(", "name", ")", "{", "if", "(", "!", "this", ".", "tasks", "[", "name", "]", ")", "{", "log", ".", "error", "(", "new", "Error", "(", "'Task \"'", "+", "name", "+", "'\" is not registered.'", ")", ")", ";", "return", "null", ";", "}", "return", "this", ".", "tasks", "[", "name", "]", ";", "}" ]
Returns registered task @param {string} name Registered task name @return {object|null} Damson task object
[ "Returns", "registered", "task" ]
6caadc0e3c93f131d0f496b480ab69f758175e63
https://github.com/damsonjs/damson-core/blob/6caadc0e3c93f131d0f496b480ab69f758175e63/index.js#L67-L73
52,039
damsonjs/damson-core
index.js
run
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
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); }
[ "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", ")", ";", "}" ]
Runs task through selected driver @param {string} task_name registered task name @param {object} options task options @param {string} driver_name registered driver name @return {Promise}
[ "Runs", "task", "through", "selected", "driver" ]
6caadc0e3c93f131d0f496b480ab69f758175e63
https://github.com/damsonjs/damson-core/blob/6caadc0e3c93f131d0f496b480ab69f758175e63/index.js#L90-L103
52,040
Pavel-vo/njs-compiler
index.js
nest
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
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; }
[ "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", ";", "}" ]
Statement stack and nested statement handler.
[ "Statement", "stack", "and", "nested", "statement", "handler", "." ]
96651ad892eb19dd4e0de6f376d36083a0a969e7
https://github.com/Pavel-vo/njs-compiler/blob/96651ad892eb19dd4e0de6f376d36083a0a969e7/index.js#L636-L642
52,041
Pavel-vo/njs-compiler
index.js
NjsCompiler
function NjsCompiler(options) { this.nodeSequence = 0; this.options = options || {}; if (!this.options.runtime) { this.options.runtime = 'njs'; } this.parseBooleanOptions("exceptions", true); }
javascript
function NjsCompiler(options) { this.nodeSequence = 0; this.options = options || {}; if (!this.options.runtime) { this.options.runtime = 'njs'; } this.parseBooleanOptions("exceptions", true); }
[ "function", "NjsCompiler", "(", "options", ")", "{", "this", ".", "nodeSequence", "=", "0", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "this", ".", "options", ".", "runtime", ")", "{", "this", ".", "options", ".", "runtime", "=", "'njs'", ";", "}", "this", ".", "parseBooleanOptions", "(", "\"exceptions\"", ",", "true", ")", ";", "}" ]
fake node type for njs code segment
[ "fake", "node", "type", "for", "njs", "code", "segment" ]
96651ad892eb19dd4e0de6f376d36083a0a969e7
https://github.com/Pavel-vo/njs-compiler/blob/96651ad892eb19dd4e0de6f376d36083a0a969e7/index.js#L1420-L1427
52,042
WebArtWork/derer
lib/lexer.js
reader
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
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; }
[ "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", ";", "}" ]
Return the token type object for a single chunk of a string. @param {string} str String chunk. @return {LexerToken} Defined type, potentially stripped or replaced with more suitable content. @private
[ "Return", "the", "token", "type", "object", "for", "a", "single", "chunk", "of", "a", "string", "." ]
edf9f82c8042b543e6f291f605430fac84702b2d
https://github.com/WebArtWork/derer/blob/edf9f82c8042b543e6f291f605430fac84702b2d/lib/lexer.js#L253-L286
52,043
nearform/docker-container
lib/container.js
build
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
build the container system - the system definition cdef - contianer definition block out - ouput stream cb - complete callback
[ "build", "the", "container", "system", "-", "the", "system", "definition", "cdef", "-", "contianer", "definition", "block", "out", "-", "ouput", "stream", "cb", "-", "complete", "callback" ]
724ff6a9d8d3c116f9a6b8239594c4b5cd5e8e17
https://github.com/nearform/docker-container/blob/724ff6a9d8d3c116f9a6b8239594c4b5cd5e8e17/lib/container.js#L44-L52
52,044
nearform/docker-container
lib/container.js
needBuild
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
Check if the container needs a build system - the system definition cdef - contianer definition block out - ouput stream cb - complete callback
[ "Check", "if", "the", "container", "needs", "a", "build" ]
724ff6a9d8d3c116f9a6b8239594c4b5cd5e8e17
https://github.com/nearform/docker-container/blob/724ff6a9d8d3c116f9a6b8239594c4b5cd5e8e17/lib/container.js#L62-L78
52,045
nearform/docker-container
lib/container.js
prepareAndGetExecutor
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
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; }
[ "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", ";", "}" ]
prepare the environment to execute the operation and return the executor target - target to deploy to out - output stream operation - the string to log to announce the beginning to the operation
[ "prepare", "the", "environment", "to", "execute", "the", "operation", "and", "return", "the", "executor" ]
724ff6a9d8d3c116f9a6b8239594c4b5cd5e8e17
https://github.com/nearform/docker-container/blob/724ff6a9d8d3c116f9a6b8239594c4b5cd5e8e17/lib/container.js#L88-L94
52,046
nearform/docker-container
lib/container.js
deploy
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
deploy the container target - target to deploy to system - the target system defintinion cdef - the contianer definition container - the container as defined in the system topology out - ouput stream cb - complete callback
[ "deploy", "the", "container", "target", "-", "target", "to", "deploy", "to", "system", "-", "the", "target", "system", "defintinion", "cdef", "-", "the", "contianer", "definition", "container", "-", "the", "container", "as", "defined", "in", "the", "system", "topology", "out", "-", "ouput", "stream", "cb", "-", "complete", "callback" ]
724ff6a9d8d3c116f9a6b8239594c4b5cd5e8e17
https://github.com/nearform/docker-container/blob/724ff6a9d8d3c116f9a6b8239594c4b5cd5e8e17/lib/container.js#L107-L112
52,047
nearform/docker-container
lib/container.js
hup
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
send updated configurtaion information to a container and hup the internal daemon process
[ "send", "updated", "configurtaion", "information", "to", "a", "container", "and", "hup", "the", "internal", "daemon", "process" ]
724ff6a9d8d3c116f9a6b8239594c4b5cd5e8e17
https://github.com/nearform/docker-container/blob/724ff6a9d8d3c116f9a6b8239594c4b5cd5e8e17/lib/container.js#L209-L214
52,048
blakeembrey/node-trimmer
index.js
toFn
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
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] } }
[ "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", "]", "}", "}" ]
Convert the input value to a function.
[ "Convert", "the", "input", "value", "to", "a", "function", "." ]
aa26b42b0e9e33dc0bb76d30b8f593d3bdcd8221
https://github.com/blakeembrey/node-trimmer/blob/aa26b42b0e9e33dc0bb76d30b8f593d3bdcd8221/index.js#L8-L21
52,049
blakeembrey/node-trimmer
index.js
trim
function trim (str, chars) { var fn = toFn(chars || WHITESPACE_CHARS) return trim.right(trim.left(str, fn), fn) }
javascript
function trim (str, chars) { var fn = toFn(chars || WHITESPACE_CHARS) return trim.right(trim.left(str, fn), fn) }
[ "function", "trim", "(", "str", ",", "chars", ")", "{", "var", "fn", "=", "toFn", "(", "chars", "||", "WHITESPACE_CHARS", ")", "return", "trim", ".", "right", "(", "trim", ".", "left", "(", "str", ",", "fn", ")", ",", "fn", ")", "}" ]
The default trim function executes both sides.
[ "The", "default", "trim", "function", "executes", "both", "sides", "." ]
aa26b42b0e9e33dc0bb76d30b8f593d3bdcd8221
https://github.com/blakeembrey/node-trimmer/blob/aa26b42b0e9e33dc0bb76d30b8f593d3bdcd8221/index.js#L26-L30
52,050
drfisher/csv-locales
lib/index.js
processCsv
function processCsv (csvContent) { UNSAFE_SYMBOLS.forEach(function (symbolParams) { csvContent = csvContent.replace(symbolParams.pattern, symbolParams.replace); }); return csvContent; }
javascript
function processCsv (csvContent) { UNSAFE_SYMBOLS.forEach(function (symbolParams) { csvContent = csvContent.replace(symbolParams.pattern, symbolParams.replace); }); return csvContent; }
[ "function", "processCsv", "(", "csvContent", ")", "{", "UNSAFE_SYMBOLS", ".", "forEach", "(", "function", "(", "symbolParams", ")", "{", "csvContent", "=", "csvContent", ".", "replace", "(", "symbolParams", ".", "pattern", ",", "symbolParams", ".", "replace", ")", ";", "}", ")", ";", "return", "csvContent", ";", "}" ]
Replaces some unsafe symbols to spaces @param {string} csvContent @returns {string}
[ "Replaces", "some", "unsafe", "symbols", "to", "spaces" ]
96f75f90ea3ecca2d206a91974ca5cc1b983c151
https://github.com/drfisher/csv-locales/blob/96f75f90ea3ecca2d206a91974ca5cc1b983c151/lib/index.js#L18-L23
52,051
drfisher/csv-locales
lib/index.js
createLocales
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
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); }
[ "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", ")", ";", "}" ]
Creates all directories and files from json @param {Array} json @param {object} params @param {function} callback
[ "Creates", "all", "directories", "and", "files", "from", "json" ]
96f75f90ea3ecca2d206a91974ca5cc1b983c151
https://github.com/drfisher/csv-locales/blob/96f75f90ea3ecca2d206a91974ca5cc1b983c151/lib/index.js#L31-L71
52,052
drfisher/csv-locales
lib/index.js
parsePlaceholders
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
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; }, {}); }
[ "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", ";", "}", ",", "{", "}", ")", ";", "}" ]
Generates a placeholders object from a source string @param {string} source @returns {object}
[ "Generates", "a", "placeholders", "object", "from", "a", "source", "string" ]
96f75f90ea3ecca2d206a91974ca5cc1b983c151
https://github.com/drfisher/csv-locales/blob/96f75f90ea3ecca2d206a91974ca5cc1b983c151/lib/index.js#L78-L87
52,053
drfisher/csv-locales
lib/index.js
writeLocales
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
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); } }
[ "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", ")", ";", "}", "}" ]
Writes locales to a file system @param {object} locales @param {object} params @param {function} callback
[ "Writes", "locales", "to", "a", "file", "system" ]
96f75f90ea3ecca2d206a91974ca5cc1b983c151
https://github.com/drfisher/csv-locales/blob/96f75f90ea3ecca2d206a91974ca5cc1b983c151/lib/index.js#L95-L122
52,054
drfisher/csv-locales
lib/index.js
registerLocales
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
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; }
[ "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", ";", "}" ]
Returns an object with existed locales @param {Array} headers @returns {object}
[ "Returns", "an", "object", "with", "existed", "locales" ]
96f75f90ea3ecca2d206a91974ca5cc1b983c151
https://github.com/drfisher/csv-locales/blob/96f75f90ea3ecca2d206a91974ca5cc1b983c151/lib/index.js#L129-L146
52,055
drfisher/csv-locales
lib/index.js
processPath
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
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; }
[ "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", ";", "}" ]
Checks if a path exists and transforms it to an absolute if it's relative @param {string} sourcePath @param {string} errorMessage @returns {string}
[ "Checks", "if", "a", "path", "exists", "and", "transforms", "it", "to", "an", "absolute", "if", "it", "s", "relative" ]
96f75f90ea3ecca2d206a91974ca5cc1b983c151
https://github.com/drfisher/csv-locales/blob/96f75f90ea3ecca2d206a91974ca5cc1b983c151/lib/index.js#L168-L176
52,056
Lindurion/closure-pro-build
lib/option-validator.js
assertBoolean
function assertBoolean(value, name, description) { if (!underscore.isBoolean(value)) { throw new Error( '<' + value + '> is not a boolean, ' + name + ': ' + description); } }
javascript
function assertBoolean(value, name, description) { if (!underscore.isBoolean(value)) { throw new Error( '<' + value + '> is not a boolean, ' + name + ': ' + description); } }
[ "function", "assertBoolean", "(", "value", ",", "name", ",", "description", ")", "{", "if", "(", "!", "underscore", ".", "isBoolean", "(", "value", ")", ")", "{", "throw", "new", "Error", "(", "'<'", "+", "value", "+", "'> is not a boolean, '", "+", "name", "+", "': '", "+", "description", ")", ";", "}", "}" ]
Throws an Error if value isn't a boolean. @param {*} value @param {string} name The option name. @param {string} description Description of the option.
[ "Throws", "an", "Error", "if", "value", "isn", "t", "a", "boolean", "." ]
c279d0fcc3a65969d2fe965f55e627b074792f1a
https://github.com/Lindurion/closure-pro-build/blob/c279d0fcc3a65969d2fe965f55e627b074792f1a/lib/option-validator.js#L43-L48
52,057
Lindurion/closure-pro-build
lib/option-validator.js
assertValidBuildType
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
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'); } }
[ "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'", ")", ";", "}", "}" ]
Throws an Error if value isn't a valid build type. @param {*} value @param {string} name The option name. @param {string} description Description of the option.
[ "Throws", "an", "Error", "if", "value", "isn", "t", "a", "valid", "build", "type", "." ]
c279d0fcc3a65969d2fe965f55e627b074792f1a
https://github.com/Lindurion/closure-pro-build/blob/c279d0fcc3a65969d2fe965f55e627b074792f1a/lib/option-validator.js#L57-L62
52,058
Lindurion/closure-pro-build
lib/option-validator.js
assertObjectMapOf
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
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); } }
[ "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", ")", ";", "}", "}" ]
Throws an Error if value isn't an Object, and invokes elementValidatorFn for each value within the map. @param {function(*, string, string)} valueValidatorFn @param {*} value @param {string} name The option name. @param {string} description Description of the option.
[ "Throws", "an", "Error", "if", "value", "isn", "t", "an", "Object", "and", "invokes", "elementValidatorFn", "for", "each", "value", "within", "the", "map", "." ]
c279d0fcc3a65969d2fe965f55e627b074792f1a
https://github.com/Lindurion/closure-pro-build/blob/c279d0fcc3a65969d2fe965f55e627b074792f1a/lib/option-validator.js#L102-L112
52,059
singpath/example-app
packages/tools/index.js
loadJspmConfig
function loadJspmConfig(opts) { sh.echo('Loading jspm config...'); return new Promise(resolve => { const loader = new jspm.Loader(); opts.config(loader); resolve(loader); }); }
javascript
function loadJspmConfig(opts) { sh.echo('Loading jspm config...'); return new Promise(resolve => { const loader = new jspm.Loader(); opts.config(loader); resolve(loader); }); }
[ "function", "loadJspmConfig", "(", "opts", ")", "{", "sh", ".", "echo", "(", "'Loading jspm config...'", ")", ";", "return", "new", "Promise", "(", "resolve", "=>", "{", "const", "loader", "=", "new", "jspm", ".", "Loader", "(", ")", ";", "opts", ".", "config", "(", "loader", ")", ";", "resolve", "(", "loader", ")", ";", "}", ")", ";", "}" ]
Resolve with a module loader. @param {{config: function}} opts options @return {Promise<jspm.Loader, Error>}
[ "Resolve", "with", "a", "module", "loader", "." ]
50b8d54bf5b647cf68094c18d99b3c8785e1dee6
https://github.com/singpath/example-app/blob/50b8d54bf5b647cf68094c18d99b3c8785e1dee6/packages/tools/index.js#L141-L150
52,060
singpath/example-app
packages/tools/index.js
hookInstanbul
function hookInstanbul(opts) { return loadJspmConfig(opts).then(loader => { sh.echo('Registering instrumentation hook to loader...'); systemIstanbul.hookSystemJS(loader, opts.exclude(loader.baseURL)); return loader; }); }
javascript
function hookInstanbul(opts) { return loadJspmConfig(opts).then(loader => { sh.echo('Registering instrumentation hook to loader...'); systemIstanbul.hookSystemJS(loader, opts.exclude(loader.baseURL)); return loader; }); }
[ "function", "hookInstanbul", "(", "opts", ")", "{", "return", "loadJspmConfig", "(", "opts", ")", ".", "then", "(", "loader", "=>", "{", "sh", ".", "echo", "(", "'Registering instrumentation hook to loader...'", ")", ";", "systemIstanbul", ".", "hookSystemJS", "(", "loader", ",", "opts", ".", "exclude", "(", "loader", ".", "baseURL", ")", ")", ";", "return", "loader", ";", "}", ")", ";", "}" ]
Resolve with a module loader which will add coverage instrumentation to src code. @param {{exclude: function, config: function}} opts coverage options @return {Promise<void, Error>} , config: {}
[ "Resolve", "with", "a", "module", "loader", "which", "will", "add", "coverage", "instrumentation", "to", "src", "code", "." ]
50b8d54bf5b647cf68094c18d99b3c8785e1dee6
https://github.com/singpath/example-app/blob/50b8d54bf5b647cf68094c18d99b3c8785e1dee6/packages/tools/index.js#L159-L166
52,061
singpath/example-app
packages/tools/index.js
createReport
function createReport(coverage, opts) { const collector = new istanbul.Collector(); const reporter = new istanbul.Reporter(null, opts.coverage); const sync = true; sh.echo('Creating reports...'); collector.add(coverage); reporter.addAll(opts.reports); reporter.write(collector, sync, () => sh.echo('Reports created.')); }
javascript
function createReport(coverage, opts) { const collector = new istanbul.Collector(); const reporter = new istanbul.Reporter(null, opts.coverage); const sync = true; sh.echo('Creating reports...'); collector.add(coverage); reporter.addAll(opts.reports); reporter.write(collector, sync, () => sh.echo('Reports created.')); }
[ "function", "createReport", "(", "coverage", ",", "opts", ")", "{", "const", "collector", "=", "new", "istanbul", ".", "Collector", "(", ")", ";", "const", "reporter", "=", "new", "istanbul", ".", "Reporter", "(", "null", ",", "opts", ".", "coverage", ")", ";", "const", "sync", "=", "true", ";", "sh", ".", "echo", "(", "'Creating reports...'", ")", ";", "collector", ".", "add", "(", "coverage", ")", ";", "reporter", ".", "addAll", "(", "opts", ".", "reports", ")", ";", "reporter", ".", "write", "(", "collector", ",", "sync", ",", "(", ")", "=>", "sh", ".", "echo", "(", "'Reports created.'", ")", ")", ";", "}" ]
Create lcov and text reports. @param {Object} coverage the coverage object. @param {{coverage: string}} opts coverage options
[ "Create", "lcov", "and", "text", "reports", "." ]
50b8d54bf5b647cf68094c18d99b3c8785e1dee6
https://github.com/singpath/example-app/blob/50b8d54bf5b647cf68094c18d99b3c8785e1dee6/packages/tools/index.js#L247-L257
52,062
singpath/example-app
packages/tools/index.js
rejectHandler
function rejectHandler(err) { process.stderr.write(`${err.stack || err}\n`); if (sh.config.fatal) { sh.exit(1); } return Promise.reject(err); }
javascript
function rejectHandler(err) { process.stderr.write(`${err.stack || err}\n`); if (sh.config.fatal) { sh.exit(1); } return Promise.reject(err); }
[ "function", "rejectHandler", "(", "err", ")", "{", "process", ".", "stderr", ".", "write", "(", "`", "${", "err", ".", "stack", "||", "err", "}", "\\n", "`", ")", ";", "if", "(", "sh", ".", "config", ".", "fatal", ")", "{", "sh", ".", "exit", "(", "1", ")", ";", "}", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}" ]
Print error to stderr and exit process when shelljs "-e" option is set. @param {Error} err error to print. @return {Promise<void, Error>}
[ "Print", "error", "to", "stderr", "and", "exit", "process", "when", "shelljs", "-", "e", "option", "is", "set", "." ]
50b8d54bf5b647cf68094c18d99b3c8785e1dee6
https://github.com/singpath/example-app/blob/50b8d54bf5b647cf68094c18d99b3c8785e1dee6/packages/tools/index.js#L265-L273
52,063
redisjs/jsr-server
lib/command/server/save.js
execute
function execute(req, res) { Persistence.save(this.state.store, this.state.conf); res.send(null, Constants.OK); }
javascript
function execute(req, res) { Persistence.save(this.state.store, this.state.conf); res.send(null, Constants.OK); }
[ "function", "execute", "(", "req", ",", "res", ")", "{", "Persistence", ".", "save", "(", "this", ".", "state", ".", "store", ",", "this", ".", "state", ".", "conf", ")", ";", "res", ".", "send", "(", "null", ",", "Constants", ".", "OK", ")", ";", "}" ]
Respond to the SAVE command.
[ "Respond", "to", "the", "SAVE", "command", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/server/save.js#L22-L25
52,064
LaxarJS/karma-laxar
lib/adapter_post.js
function( path ) { var normalized = []; var parts = path.split( '/' ); for( var i = 0; i < parts.length; i++ ) { if( parts[i] === '.' ) { continue; } if( parts[i] === '..' && normalized.length && normalized[normalized.length - 1] !== '..' ) { normalized.pop(); continue; } normalized.push( parts[i] ); } return normalized.join( '/' ); }
javascript
function( path ) { var normalized = []; var parts = path.split( '/' ); for( var i = 0; i < parts.length; i++ ) { if( parts[i] === '.' ) { continue; } if( parts[i] === '..' && normalized.length && normalized[normalized.length - 1] !== '..' ) { normalized.pop(); continue; } normalized.push( parts[i] ); } return normalized.join( '/' ); }
[ "function", "(", "path", ")", "{", "var", "normalized", "=", "[", "]", ";", "var", "parts", "=", "path", ".", "split", "(", "'/'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "if", "(", "parts", "[", "i", "]", "===", "'.'", ")", "{", "continue", ";", "}", "if", "(", "parts", "[", "i", "]", "===", "'..'", "&&", "normalized", ".", "length", "&&", "normalized", "[", "normalized", ".", "length", "-", "1", "]", "!==", "'..'", ")", "{", "normalized", ".", "pop", "(", ")", ";", "continue", ";", "}", "normalized", ".", "push", "(", "parts", "[", "i", "]", ")", ";", "}", "return", "normalized", ".", "join", "(", "'/'", ")", ";", "}" ]
monkey patch requirejs, to use append timestamps to sources to take advantage of karma's heavy caching it would work even without this hack, but with reloading all the files all the time
[ "monkey", "patch", "requirejs", "to", "use", "append", "timestamps", "to", "sources", "to", "take", "advantage", "of", "karma", "s", "heavy", "caching", "it", "would", "work", "even", "without", "this", "hack", "but", "with", "reloading", "all", "the", "files", "all", "the", "time" ]
959680d5ae6336bb0ca86ce77eab70fde087ae9b
https://github.com/LaxarJS/karma-laxar/blob/959680d5ae6336bb0ca86ce77eab70fde087ae9b/lib/adapter_post.js#L91-L109
52,065
panoptix-za/hotrod-dash-data
lib/query/es/esQuery.js
function(queryRunner, options) { options = options || {}; this.queryParser = new QueryParser(options.paramValueRegEx); var indexNameBuilder = options.indexNameBuilder || new DefaultIndexNameBuilder(); this.queryBuilder = new EsQueryBuilder(indexNameBuilder, { defaults: options.queryDefaults }); this.queryRunner = queryRunner; }
javascript
function(queryRunner, options) { options = options || {}; this.queryParser = new QueryParser(options.paramValueRegEx); var indexNameBuilder = options.indexNameBuilder || new DefaultIndexNameBuilder(); this.queryBuilder = new EsQueryBuilder(indexNameBuilder, { defaults: options.queryDefaults }); this.queryRunner = queryRunner; }
[ "function", "(", "queryRunner", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "queryParser", "=", "new", "QueryParser", "(", "options", ".", "paramValueRegEx", ")", ";", "var", "indexNameBuilder", "=", "options", ".", "indexNameBuilder", "||", "new", "DefaultIndexNameBuilder", "(", ")", ";", "this", ".", "queryBuilder", "=", "new", "EsQueryBuilder", "(", "indexNameBuilder", ",", "{", "defaults", ":", "options", ".", "queryDefaults", "}", ")", ";", "this", ".", "queryRunner", "=", "queryRunner", ";", "}" ]
Small facade over lower level types. Provides a smaller API for users
[ "Small", "facade", "over", "lower", "level", "types", ".", "Provides", "a", "smaller", "API", "for", "users" ]
6cd2c64b0fac2cb9aa484abcbd641fbe8c651fa2
https://github.com/panoptix-za/hotrod-dash-data/blob/6cd2c64b0fac2cb9aa484abcbd641fbe8c651fa2/lib/query/es/esQuery.js#L8-L16
52,066
jonschlinkert/get-first-commit
index.js
firstCommit
function firstCommit(dir, cb) { if (typeof dir === 'function') { return firstCommit(process.cwd(), dir); } if (typeof cb !== 'function') { throw new TypeError('expected callback to be a function'); } lazy.git(dir).log(function(err, history) { if (err) return cb(err); history.sort(function(a, b) { return b.date.localeCompare(a.date); }); cb(null, history[history.length - 1]); }); }
javascript
function firstCommit(dir, cb) { if (typeof dir === 'function') { return firstCommit(process.cwd(), dir); } if (typeof cb !== 'function') { throw new TypeError('expected callback to be a function'); } lazy.git(dir).log(function(err, history) { if (err) return cb(err); history.sort(function(a, b) { return b.date.localeCompare(a.date); }); cb(null, history[history.length - 1]); }); }
[ "function", "firstCommit", "(", "dir", ",", "cb", ")", "{", "if", "(", "typeof", "dir", "===", "'function'", ")", "{", "return", "firstCommit", "(", "process", ".", "cwd", "(", ")", ",", "dir", ")", ";", "}", "if", "(", "typeof", "cb", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'expected callback to be a function'", ")", ";", "}", "lazy", ".", "git", "(", "dir", ")", ".", "log", "(", "function", "(", "err", ",", "history", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "history", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "b", ".", "date", ".", "localeCompare", "(", "a", ".", "date", ")", ";", "}", ")", ";", "cb", "(", "null", ",", "history", "[", "history", ".", "length", "-", "1", "]", ")", ";", "}", ")", ";", "}" ]
Asynchronously get the first commit from a git repository. ```js firstCommit('foo/.git', function(err, commit) { if (err) return console.log(err); // do stuff with commit }); ``` @param {String} `cwd` current working directory @param {Function} `callback` @return {Object} @api public
[ "Asynchronously", "get", "the", "first", "commit", "from", "a", "git", "repository", "." ]
69668ba3be92a629d4291bf78d52219da312f07c
https://github.com/jonschlinkert/get-first-commit/blob/69668ba3be92a629d4291bf78d52219da312f07c/index.js#L28-L45
52,067
Psychopoulet/node-promfs
lib/extends/_readJSONFile.js
_readJSONFile
function _readJSONFile (file, callback) { 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 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.reject(new Error("The file does not exist")) : new Promise((resolve, reject) => { readFile(file, (err, content) => { return err ? reject(err) : resolve(content); }); }); }).then((content) => { callback(null, JSON.parse(content)); }).catch(callback); } }
javascript
function _readJSONFile (file, callback) { 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 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.reject(new Error("The file does not exist")) : new Promise((resolve, reject) => { readFile(file, (err, content) => { return err ? reject(err) : resolve(content); }); }); }).then((content) => { callback(null, JSON.parse(content)); }).catch(callback); } }
[ "function", "_readJSONFile", "(", "file", ",", "callback", ")", "{", "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", "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", ".", "reject", "(", "new", "Error", "(", "\"The file does not exist\"", ")", ")", ":", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "readFile", "(", "file", ",", "(", "err", ",", "content", ")", "=>", "{", "return", "err", "?", "reject", "(", "err", ")", ":", "resolve", "(", "content", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", "(", "content", ")", "=>", "{", "callback", "(", "null", ",", "JSON", ".", "parse", "(", "content", ")", ")", ";", "}", ")", ".", "catch", "(", "callback", ")", ";", "}", "}" ]
methods Async readJSONFile @param {string} file : file to check @param {function} callback : operation's result @returns {void}
[ "methods", "Async", "readJSONFile" ]
016e272fc58c6ef6eae5ea551a0e8873f0ac20cc
https://github.com/Psychopoulet/node-promfs/blob/016e272fc58c6ef6eae5ea551a0e8873f0ac20cc/lib/extends/_readJSONFile.js#L21-L58
52,068
jonschlinkert/question-store
index.js
QuestionsStore
function QuestionsStore(options) { debug('initializing from <%s>', __filename); Cache.call(this, options); this.createStores(this, this.options); this.listen(this); }
javascript
function QuestionsStore(options) { debug('initializing from <%s>', __filename); Cache.call(this, options); this.createStores(this, this.options); this.listen(this); }
[ "function", "QuestionsStore", "(", "options", ")", "{", "debug", "(", "'initializing from <%s>'", ",", "__filename", ")", ";", "Cache", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "createStores", "(", "this", ",", "this", ".", "options", ")", ";", "this", ".", "listen", "(", "this", ")", ";", "}" ]
Create an instance of `QuestionsStore` with the given `options`. ```js var QuestionsStore = new QuestionsStore(options); ``` @param {Object} `options` question store options @api public
[ "Create", "an", "instance", "of", "QuestionsStore", "with", "the", "given", "options", "." ]
0c459f6e8aff2078fc23f680887f10e8c92fde26
https://github.com/jonschlinkert/question-store/blob/0c459f6e8aff2078fc23f680887f10e8c92fde26/index.js#L28-L33
52,069
cli-kit/cli-mid-exec
index.js
error
function error(scope, err, parameters) { if(err.code == 'EACCES') { scope.raise(scope.errors.EPERM, parameters); } }
javascript
function error(scope, err, parameters) { if(err.code == 'EACCES') { scope.raise(scope.errors.EPERM, parameters); } }
[ "function", "error", "(", "scope", ",", "err", ",", "parameters", ")", "{", "if", "(", "err", ".", "code", "==", "'EACCES'", ")", "{", "scope", ".", "raise", "(", "scope", ".", "errors", ".", "EPERM", ",", "parameters", ")", ";", "}", "}" ]
Child process error handler. @param scope The program scope. @param err The Error instance. @param parameters Message replacement parameters.
[ "Child", "process", "error", "handler", "." ]
2105ba5ff135a7bce2b066e996a822a49322ccd3
https://github.com/cli-kit/cli-mid-exec/blob/2105ba5ff135a7bce2b066e996a822a49322ccd3/index.js#L15-L19
52,070
cli-kit/cli-mid-exec
index.js
execute
function execute(argv, bin, args, req) { var config = this.configure(); var errors = this.errors, scope = this, e; var dir = config.bin || dirname(argv[1]); var local = path.join(dir, bin); var exists = fs.existsSync(local); var data = {bin: bin, dir: dir, local: local, args: args}; if(!exists) { e = new ExecError(errors.EEXEC_NOENT.message, [bin], errors.EEXEC_NOENT.code); e.data = data; throw e; } var stat = fs.statSync(local); var ps = spawn(local, args, {stdio: [0, 1, 'pipe']}); req.process = ps; this.emit('exec', ps, local, args, req); ps.on('error', function(err){ error(scope, err, [bin]); }); // suppress the execvp() error so we can cleanly // present our own error message ps.stderr.on('data', function(data) { if(!/^execvp\(\)/.test(data.toString())) { process.stderr.write(data); } }) ps.on('close', function (code, signal) { // NOTE: workaround for https://github.com/joyent/node/issues/3222 // NOTE: assume child process exited gracefully on SIGINT if(signal == 'SIGINT') { return process.exit(0); } // TODO: remove this event? scope.emit('close', code, signal); if(config.exit) process.exit(code); }); return ps; }
javascript
function execute(argv, bin, args, req) { var config = this.configure(); var errors = this.errors, scope = this, e; var dir = config.bin || dirname(argv[1]); var local = path.join(dir, bin); var exists = fs.existsSync(local); var data = {bin: bin, dir: dir, local: local, args: args}; if(!exists) { e = new ExecError(errors.EEXEC_NOENT.message, [bin], errors.EEXEC_NOENT.code); e.data = data; throw e; } var stat = fs.statSync(local); var ps = spawn(local, args, {stdio: [0, 1, 'pipe']}); req.process = ps; this.emit('exec', ps, local, args, req); ps.on('error', function(err){ error(scope, err, [bin]); }); // suppress the execvp() error so we can cleanly // present our own error message ps.stderr.on('data', function(data) { if(!/^execvp\(\)/.test(data.toString())) { process.stderr.write(data); } }) ps.on('close', function (code, signal) { // NOTE: workaround for https://github.com/joyent/node/issues/3222 // NOTE: assume child process exited gracefully on SIGINT if(signal == 'SIGINT') { return process.exit(0); } // TODO: remove this event? scope.emit('close', code, signal); if(config.exit) process.exit(code); }); return ps; }
[ "function", "execute", "(", "argv", ",", "bin", ",", "args", ",", "req", ")", "{", "var", "config", "=", "this", ".", "configure", "(", ")", ";", "var", "errors", "=", "this", ".", "errors", ",", "scope", "=", "this", ",", "e", ";", "var", "dir", "=", "config", ".", "bin", "||", "dirname", "(", "argv", "[", "1", "]", ")", ";", "var", "local", "=", "path", ".", "join", "(", "dir", ",", "bin", ")", ";", "var", "exists", "=", "fs", ".", "existsSync", "(", "local", ")", ";", "var", "data", "=", "{", "bin", ":", "bin", ",", "dir", ":", "dir", ",", "local", ":", "local", ",", "args", ":", "args", "}", ";", "if", "(", "!", "exists", ")", "{", "e", "=", "new", "ExecError", "(", "errors", ".", "EEXEC_NOENT", ".", "message", ",", "[", "bin", "]", ",", "errors", ".", "EEXEC_NOENT", ".", "code", ")", ";", "e", ".", "data", "=", "data", ";", "throw", "e", ";", "}", "var", "stat", "=", "fs", ".", "statSync", "(", "local", ")", ";", "var", "ps", "=", "spawn", "(", "local", ",", "args", ",", "{", "stdio", ":", "[", "0", ",", "1", ",", "'pipe'", "]", "}", ")", ";", "req", ".", "process", "=", "ps", ";", "this", ".", "emit", "(", "'exec'", ",", "ps", ",", "local", ",", "args", ",", "req", ")", ";", "ps", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "error", "(", "scope", ",", "err", ",", "[", "bin", "]", ")", ";", "}", ")", ";", "// suppress the execvp() error so we can cleanly", "// present our own error message", "ps", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "if", "(", "!", "/", "^execvp\\(\\)", "/", ".", "test", "(", "data", ".", "toString", "(", ")", ")", ")", "{", "process", ".", "stderr", ".", "write", "(", "data", ")", ";", "}", "}", ")", "ps", ".", "on", "(", "'close'", ",", "function", "(", "code", ",", "signal", ")", "{", "// NOTE: workaround for https://github.com/joyent/node/issues/3222", "// NOTE: assume child process exited gracefully on SIGINT", "if", "(", "signal", "==", "'SIGINT'", ")", "{", "return", "process", ".", "exit", "(", "0", ")", ";", "}", "// TODO: remove this event?", "scope", ".", "emit", "(", "'close'", ",", "code", ",", "signal", ")", ";", "if", "(", "config", ".", "exit", ")", "process", ".", "exit", "(", "code", ")", ";", "}", ")", ";", "return", "ps", ";", "}" ]
Execute a command as an external program. @param argv The program arguments. @param cmd The command to execute. @param args Array of arguments to pass to the command. @param req The request object for the middleware execution.
[ "Execute", "a", "command", "as", "an", "external", "program", "." ]
2105ba5ff135a7bce2b066e996a822a49322ccd3
https://github.com/cli-kit/cli-mid-exec/blob/2105ba5ff135a7bce2b066e996a822a49322ccd3/index.js#L29-L66
52,071
pcnsuite/pcnlint
src/mocha.js
stringMatch
function stringMatch(stringValues) { return function(testValue) { for (var i = stringValues.length - 1; i >= 0; i--) { if (stringValues[i] === testValue) { return true; } } return false; }; }
javascript
function stringMatch(stringValues) { return function(testValue) { for (var i = stringValues.length - 1; i >= 0; i--) { if (stringValues[i] === testValue) { return true; } } return false; }; }
[ "function", "stringMatch", "(", "stringValues", ")", "{", "return", "function", "(", "testValue", ")", "{", "for", "(", "var", "i", "=", "stringValues", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "stringValues", "[", "i", "]", "===", "testValue", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", ";", "}" ]
Verify that a given property is one of a list of strings
[ "Verify", "that", "a", "given", "property", "is", "one", "of", "a", "list", "of", "strings" ]
7f5f82d25f62aecc1ccefb99096cc416e842f7cf
https://github.com/pcnsuite/pcnlint/blob/7f5f82d25f62aecc1ccefb99096cc416e842f7cf/src/mocha.js#L13-L22
52,072
MaPhil/sicro
index.js
function (data) { var q = _q.defer(); data = data.replace(/\'/g,"\\\'"); data = data.replace(/\"/g,'\\\"'); exec(`echo "${data}" | crontab -`, (err, stdout, stderr) => { if (err) q.reject(err); if(stdout)q.resolve(stdout); else q.resolve(stderr); }); return q.promise; }
javascript
function (data) { var q = _q.defer(); data = data.replace(/\'/g,"\\\'"); data = data.replace(/\"/g,'\\\"'); exec(`echo "${data}" | crontab -`, (err, stdout, stderr) => { if (err) q.reject(err); if(stdout)q.resolve(stdout); else q.resolve(stderr); }); return q.promise; }
[ "function", "(", "data", ")", "{", "var", "q", "=", "_q", ".", "defer", "(", ")", ";", "data", "=", "data", ".", "replace", "(", "/", "\\'", "/", "g", ",", "\"\\\\\\'\"", ")", ";", "data", "=", "data", ".", "replace", "(", "/", "\\\"", "/", "g", ",", "'\\\\\\\"'", ")", ";", "exec", "(", "`", "${", "data", "}", "`", ",", "(", "err", ",", "stdout", ",", "stderr", ")", "=>", "{", "if", "(", "err", ")", "q", ".", "reject", "(", "err", ")", ";", "if", "(", "stdout", ")", "q", ".", "resolve", "(", "stdout", ")", ";", "else", "q", ".", "resolve", "(", "stderr", ")", ";", "}", ")", ";", "return", "q", ".", "promise", ";", "}" ]
low level to replace functionality after testing
[ "low", "level", "to", "replace", "functionality", "after", "testing" ]
2bb8cf0419ed625170ff534911e605d56596a4e2
https://github.com/MaPhil/sicro/blob/2bb8cf0419ed625170ff534911e605d56596a4e2/index.js#L18-L28
52,073
ninjablocks/node-ninja-blocks
index.js
function(cb) { if (typeof cb === "function") { var opts = { url: uri + 'user', method: 'GET', qs: qs, json: true }; request(opts,function(e,r,b) { if (e) cb(e) else { if (r.statusCode==200) cb(null, b) else { cb({statusCode:r.statusCode,error:b.error}) } } }); return; } return { /** * Fetches the user's stream * * Example: * app.user().stream(function(err,data){ ... }) * * @param {Function} cb * @api public */ stream: function(cb) { var opts = { url: uri + 'user/stream', method: 'GET', qs: qs, json: true }; request(opts,function(e,r,b) { if (e) cb(e) else { if (r.statusCode==200) cb(null, b) else { cb({statusCode:r.statusCode,error:b.error}) } } }); }, /** * Fetches the user's pucher channel * * Example: * app.user().pusher_channel(function(err,data){ ... }) * * @param {Function} cb * @api public */ pusher_channel: function(cb) { var opts = { url: uri + 'user/pusherchannel', method: 'GET', qs: qs, json: true }; request(opts,function(e,r,b) { if (e) cb(e) else { if (r.statusCode==200) cb(null, b.data) else { cb({statusCode:b.id||200,error:b.error}) } } }); }, } }
javascript
function(cb) { if (typeof cb === "function") { var opts = { url: uri + 'user', method: 'GET', qs: qs, json: true }; request(opts,function(e,r,b) { if (e) cb(e) else { if (r.statusCode==200) cb(null, b) else { cb({statusCode:r.statusCode,error:b.error}) } } }); return; } return { /** * Fetches the user's stream * * Example: * app.user().stream(function(err,data){ ... }) * * @param {Function} cb * @api public */ stream: function(cb) { var opts = { url: uri + 'user/stream', method: 'GET', qs: qs, json: true }; request(opts,function(e,r,b) { if (e) cb(e) else { if (r.statusCode==200) cb(null, b) else { cb({statusCode:r.statusCode,error:b.error}) } } }); }, /** * Fetches the user's pucher channel * * Example: * app.user().pusher_channel(function(err,data){ ... }) * * @param {Function} cb * @api public */ pusher_channel: function(cb) { var opts = { url: uri + 'user/pusherchannel', method: 'GET', qs: qs, json: true }; request(opts,function(e,r,b) { if (e) cb(e) else { if (r.statusCode==200) cb(null, b.data) else { cb({statusCode:b.id||200,error:b.error}) } } }); }, } }
[ "function", "(", "cb", ")", "{", "if", "(", "typeof", "cb", "===", "\"function\"", ")", "{", "var", "opts", "=", "{", "url", ":", "uri", "+", "'user'", ",", "method", ":", "'GET'", ",", "qs", ":", "qs", ",", "json", ":", "true", "}", ";", "request", "(", "opts", ",", "function", "(", "e", ",", "r", ",", "b", ")", "{", "if", "(", "e", ")", "cb", "(", "e", ")", "else", "{", "if", "(", "r", ".", "statusCode", "==", "200", ")", "cb", "(", "null", ",", "b", ")", "else", "{", "cb", "(", "{", "statusCode", ":", "r", ".", "statusCode", ",", "error", ":", "b", ".", "error", "}", ")", "}", "}", "}", ")", ";", "return", ";", "}", "return", "{", "/**\n * Fetches the user's stream\n *\n * Example:\n * app.user().stream(function(err,data){ ... })\n *\n * @param {Function} cb\n * @api public\n */", "stream", ":", "function", "(", "cb", ")", "{", "var", "opts", "=", "{", "url", ":", "uri", "+", "'user/stream'", ",", "method", ":", "'GET'", ",", "qs", ":", "qs", ",", "json", ":", "true", "}", ";", "request", "(", "opts", ",", "function", "(", "e", ",", "r", ",", "b", ")", "{", "if", "(", "e", ")", "cb", "(", "e", ")", "else", "{", "if", "(", "r", ".", "statusCode", "==", "200", ")", "cb", "(", "null", ",", "b", ")", "else", "{", "cb", "(", "{", "statusCode", ":", "r", ".", "statusCode", ",", "error", ":", "b", ".", "error", "}", ")", "}", "}", "}", ")", ";", "}", ",", "/**\n * Fetches the user's pucher channel\n *\n * Example:\n * app.user().pusher_channel(function(err,data){ ... })\n *\n * @param {Function} cb\n * @api public\n */", "pusher_channel", ":", "function", "(", "cb", ")", "{", "var", "opts", "=", "{", "url", ":", "uri", "+", "'user/pusherchannel'", ",", "method", ":", "'GET'", ",", "qs", ":", "qs", ",", "json", ":", "true", "}", ";", "request", "(", "opts", ",", "function", "(", "e", ",", "r", ",", "b", ")", "{", "if", "(", "e", ")", "cb", "(", "e", ")", "else", "{", "if", "(", "r", ".", "statusCode", "==", "200", ")", "cb", "(", "null", ",", "b", ".", "data", ")", "else", "{", "cb", "(", "{", "statusCode", ":", "b", ".", "id", "||", "200", ",", "error", ":", "b", ".", "error", "}", ")", "}", "}", "}", ")", ";", "}", ",", "}", "}" ]
Fetches all the user's information. If no callback is provided then more specific information can be requested Example: app.user(function(err, data) { ... }) app.user().stream(function(err,data){ ... }) @param {Function} cb @api public
[ "Fetches", "all", "the", "user", "s", "information", ".", "If", "no", "callback", "is", "provided", "then", "more", "specific", "information", "can", "be", "requested" ]
283acb0f5348abf18a534666bcd2cc169e1d9974
https://github.com/ninjablocks/node-ninja-blocks/blob/283acb0f5348abf18a534666bcd2cc169e1d9974/index.js#L32-L107
52,074
ninjablocks/node-ninja-blocks
index.js
function(cb) { var opts = { url: uri + 'user/stream', method: 'GET', qs: qs, json: true }; request(opts,function(e,r,b) { if (e) cb(e) else { if (r.statusCode==200) cb(null, b) else { cb({statusCode:r.statusCode,error:b.error}) } } }); }
javascript
function(cb) { var opts = { url: uri + 'user/stream', method: 'GET', qs: qs, json: true }; request(opts,function(e,r,b) { if (e) cb(e) else { if (r.statusCode==200) cb(null, b) else { cb({statusCode:r.statusCode,error:b.error}) } } }); }
[ "function", "(", "cb", ")", "{", "var", "opts", "=", "{", "url", ":", "uri", "+", "'user/stream'", ",", "method", ":", "'GET'", ",", "qs", ":", "qs", ",", "json", ":", "true", "}", ";", "request", "(", "opts", ",", "function", "(", "e", ",", "r", ",", "b", ")", "{", "if", "(", "e", ")", "cb", "(", "e", ")", "else", "{", "if", "(", "r", ".", "statusCode", "==", "200", ")", "cb", "(", "null", ",", "b", ")", "else", "{", "cb", "(", "{", "statusCode", ":", "r", ".", "statusCode", ",", "error", ":", "b", ".", "error", "}", ")", "}", "}", "}", ")", ";", "}" ]
Fetches the user's stream Example: app.user().stream(function(err,data){ ... }) @param {Function} cb @api public
[ "Fetches", "the", "user", "s", "stream" ]
283acb0f5348abf18a534666bcd2cc169e1d9974
https://github.com/ninjablocks/node-ninja-blocks/blob/283acb0f5348abf18a534666bcd2cc169e1d9974/index.js#L63-L79
52,075
ninjablocks/node-ninja-blocks
index.js
function(url,overwrite,cb) { if (typeof overwrite === "function") { cb = overwrite; overwrite = false; } var opts = { url: uri + 'device/'+device+'/callback', method: 'POST', qs: qs, json: { url:url } }; request(opts,function(e,r,b) { if (!cb && !overwrite && b && b.id !== 409 ) return; if (e) cb(e) else if (b.result===1) cb(null) else if (b.id===409 && overwrite) { // A url already exists, let's update it var opts = { url: uri + 'device/'+device+'/callback', method: 'PUT', qs: qs, json: { url:url } }; request(opts,function(e,r,b) { if (!cb) return; if (e) cb(e) else if (b.result===1) cb(null) else cb({statusCode:b.id||200,error:b.error}) }); } else { cb({statusCode:b.id||200,error:b.error}) } }); }
javascript
function(url,overwrite,cb) { if (typeof overwrite === "function") { cb = overwrite; overwrite = false; } var opts = { url: uri + 'device/'+device+'/callback', method: 'POST', qs: qs, json: { url:url } }; request(opts,function(e,r,b) { if (!cb && !overwrite && b && b.id !== 409 ) return; if (e) cb(e) else if (b.result===1) cb(null) else if (b.id===409 && overwrite) { // A url already exists, let's update it var opts = { url: uri + 'device/'+device+'/callback', method: 'PUT', qs: qs, json: { url:url } }; request(opts,function(e,r,b) { if (!cb) return; if (e) cb(e) else if (b.result===1) cb(null) else cb({statusCode:b.id||200,error:b.error}) }); } else { cb({statusCode:b.id||200,error:b.error}) } }); }
[ "function", "(", "url", ",", "overwrite", ",", "cb", ")", "{", "if", "(", "typeof", "overwrite", "===", "\"function\"", ")", "{", "cb", "=", "overwrite", ";", "overwrite", "=", "false", ";", "}", "var", "opts", "=", "{", "url", ":", "uri", "+", "'device/'", "+", "device", "+", "'/callback'", ",", "method", ":", "'POST'", ",", "qs", ":", "qs", ",", "json", ":", "{", "url", ":", "url", "}", "}", ";", "request", "(", "opts", ",", "function", "(", "e", ",", "r", ",", "b", ")", "{", "if", "(", "!", "cb", "&&", "!", "overwrite", "&&", "b", "&&", "b", ".", "id", "!==", "409", ")", "return", ";", "if", "(", "e", ")", "cb", "(", "e", ")", "else", "if", "(", "b", ".", "result", "===", "1", ")", "cb", "(", "null", ")", "else", "if", "(", "b", ".", "id", "===", "409", "&&", "overwrite", ")", "{", "// A url already exists, let's update it", "var", "opts", "=", "{", "url", ":", "uri", "+", "'device/'", "+", "device", "+", "'/callback'", ",", "method", ":", "'PUT'", ",", "qs", ":", "qs", ",", "json", ":", "{", "url", ":", "url", "}", "}", ";", "request", "(", "opts", ",", "function", "(", "e", ",", "r", ",", "b", ")", "{", "if", "(", "!", "cb", ")", "return", ";", "if", "(", "e", ")", "cb", "(", "e", ")", "else", "if", "(", "b", ".", "result", "===", "1", ")", "cb", "(", "null", ")", "else", "cb", "(", "{", "statusCode", ":", "b", ".", "id", "||", "200", ",", "error", ":", "b", ".", "error", "}", ")", "}", ")", ";", "}", "else", "{", "cb", "(", "{", "statusCode", ":", "b", ".", "id", "||", "200", ",", "error", ":", "b", ".", "error", "}", ")", "}", "}", ")", ";", "}" ]
Subscribes to a device's data feed. Optionally `overwrite`s an existing callback `url` Default is false. Example: app.device(guid).subscribe('example.com',true,function(err) { ... }) @param {String} url The url that Ninja Blocks will POST data to @param {Boolean} overwrite If a callback url exists, this flag will force an overwrite @param {Function} cb @api public
[ "Subscribes", "to", "a", "device", "s", "data", "feed", "." ]
283acb0f5348abf18a534666bcd2cc169e1d9974
https://github.com/ninjablocks/node-ninja-blocks/blob/283acb0f5348abf18a534666bcd2cc169e1d9974/index.js#L174-L208
52,076
ninjablocks/node-ninja-blocks
index.js
function(start, end, cb) { if (typeof start === "function") { cb = start; start = false; } else if (typeof end === "function") { cb = end; end = false; } if (start instanceof Date) start = start.getTime(); if (start) qs.from = start; if (end instanceof Date) end = end.getTime(); if (end) qs.to = end; var opts = { url: uri + 'device/'+device+'/data', method: 'GET', qs: qs, json: true }; request(opts,function(e,r,b) { if (e) cb(e) else if (b.result===1) cb(null, b.data) else cb({statusCode:b.id||200,error:b.error}) }); }
javascript
function(start, end, cb) { if (typeof start === "function") { cb = start; start = false; } else if (typeof end === "function") { cb = end; end = false; } if (start instanceof Date) start = start.getTime(); if (start) qs.from = start; if (end instanceof Date) end = end.getTime(); if (end) qs.to = end; var opts = { url: uri + 'device/'+device+'/data', method: 'GET', qs: qs, json: true }; request(opts,function(e,r,b) { if (e) cb(e) else if (b.result===1) cb(null, b.data) else cb({statusCode:b.id||200,error:b.error}) }); }
[ "function", "(", "start", ",", "end", ",", "cb", ")", "{", "if", "(", "typeof", "start", "===", "\"function\"", ")", "{", "cb", "=", "start", ";", "start", "=", "false", ";", "}", "else", "if", "(", "typeof", "end", "===", "\"function\"", ")", "{", "cb", "=", "end", ";", "end", "=", "false", ";", "}", "if", "(", "start", "instanceof", "Date", ")", "start", "=", "start", ".", "getTime", "(", ")", ";", "if", "(", "start", ")", "qs", ".", "from", "=", "start", ";", "if", "(", "end", "instanceof", "Date", ")", "end", "=", "end", ".", "getTime", "(", ")", ";", "if", "(", "end", ")", "qs", ".", "to", "=", "end", ";", "var", "opts", "=", "{", "url", ":", "uri", "+", "'device/'", "+", "device", "+", "'/data'", ",", "method", ":", "'GET'", ",", "qs", ":", "qs", ",", "json", ":", "true", "}", ";", "request", "(", "opts", ",", "function", "(", "e", ",", "r", ",", "b", ")", "{", "if", "(", "e", ")", "cb", "(", "e", ")", "else", "if", "(", "b", ".", "result", "===", "1", ")", "cb", "(", "null", ",", "b", ".", "data", ")", "else", "cb", "(", "{", "statusCode", ":", "b", ".", "id", "||", "200", ",", "error", ":", "b", ".", "error", "}", ")", "}", ")", ";", "}" ]
Fetches any historical data about this device. Optionally specify the period's `start` and `end` timestamp. Example: app.device(guid).data(start, end, function(err, data) { ... }) @param {Integer|Date} start The timestamp/datetime of the beginning of the period @param {Integer|Date} end the timestamp/datetime of the end of the period @param {Function} cb @api public
[ "Fetches", "any", "historical", "data", "about", "this", "device", ".", "Optionally", "specify", "the", "period", "s", "start", "and", "end", "timestamp", "." ]
283acb0f5348abf18a534666bcd2cc169e1d9974
https://github.com/ninjablocks/node-ninja-blocks/blob/283acb0f5348abf18a534666bcd2cc169e1d9974/index.js#L249-L276
52,077
ninjablocks/node-ninja-blocks
index.js
function(filter,cb) { if (!filter) { filter = {}; } else if (typeof filter == "function") { cb = filter; filter = {}; } else if (typeof filter == "string") { filter = {device_type:filter}; // Backwards compatibility } var opts = { url: uri + 'devices', method: 'GET', qs: qs, json: true }; request(opts,function(e,r,b) { if (e) cb(e) else if (b.result===1) cb(null, utils.filter(filter,b.data)) else cb({statusCode:b.id||200,error:b.error}) }); }
javascript
function(filter,cb) { if (!filter) { filter = {}; } else if (typeof filter == "function") { cb = filter; filter = {}; } else if (typeof filter == "string") { filter = {device_type:filter}; // Backwards compatibility } var opts = { url: uri + 'devices', method: 'GET', qs: qs, json: true }; request(opts,function(e,r,b) { if (e) cb(e) else if (b.result===1) cb(null, utils.filter(filter,b.data)) else cb({statusCode:b.id||200,error:b.error}) }); }
[ "function", "(", "filter", ",", "cb", ")", "{", "if", "(", "!", "filter", ")", "{", "filter", "=", "{", "}", ";", "}", "else", "if", "(", "typeof", "filter", "==", "\"function\"", ")", "{", "cb", "=", "filter", ";", "filter", "=", "{", "}", ";", "}", "else", "if", "(", "typeof", "filter", "==", "\"string\"", ")", "{", "filter", "=", "{", "device_type", ":", "filter", "}", ";", "// Backwards compatibility", "}", "var", "opts", "=", "{", "url", ":", "uri", "+", "'devices'", ",", "method", ":", "'GET'", ",", "qs", ":", "qs", ",", "json", ":", "true", "}", ";", "request", "(", "opts", ",", "function", "(", "e", ",", "r", ",", "b", ")", "{", "if", "(", "e", ")", "cb", "(", "e", ")", "else", "if", "(", "b", ".", "result", "===", "1", ")", "cb", "(", "null", ",", "utils", ".", "filter", "(", "filter", ",", "b", ".", "data", ")", ")", "else", "cb", "(", "{", "statusCode", ":", "b", ".", "id", "||", "200", ",", "error", ":", "b", ".", "error", "}", ")", "}", ")", ";", "}" ]
Fetches all the user's device details. Optionally if an object is passed as the first argument, it will filter by the parameters. If a string is provided, it will assume it's the device type intended for filtering. Example: app.devices('rgbled',function(err, data) { ... }) app.devices({shortName:'On Board RGB LED'},function(err,data){ ... }) app.devices({vid:0, shortName:'On Board RGB LED'},function(err,data){ ... }) @param {String/Object} filter @param {Function} cb @api public
[ "Fetches", "all", "the", "user", "s", "device", "details", ".", "Optionally", "if", "an", "object", "is", "passed", "as", "the", "first", "argument", "it", "will", "filter", "by", "the", "parameters", ".", "If", "a", "string", "is", "provided", "it", "will", "assume", "it", "s", "the", "device", "type", "intended", "for", "filtering", "." ]
283acb0f5348abf18a534666bcd2cc169e1d9974
https://github.com/ninjablocks/node-ninja-blocks/blob/283acb0f5348abf18a534666bcd2cc169e1d9974/index.js#L317-L337
52,078
samplx/samplx-agentdb
utils/tune-hash.js
getPrimes
function getPrimes(limit) { var sieve = new Array(limit); var n, j, k; var last = Math.floor(Math.sqrt(limit)); for (n=2; n < limit; n++) { sieve[n] = true; } for (n=2; n <= last;) { for (j= n+n; j < limit; j += n) { sieve[j] = false; } for (j=1; j < last; j++) { k = n+j; if (sieve[k]) { n = k; break; } } } var primes = []; for (n=2; n < limit; n++) { if (sieve[n]) { primes.push(n); } } return primes; }
javascript
function getPrimes(limit) { var sieve = new Array(limit); var n, j, k; var last = Math.floor(Math.sqrt(limit)); for (n=2; n < limit; n++) { sieve[n] = true; } for (n=2; n <= last;) { for (j= n+n; j < limit; j += n) { sieve[j] = false; } for (j=1; j < last; j++) { k = n+j; if (sieve[k]) { n = k; break; } } } var primes = []; for (n=2; n < limit; n++) { if (sieve[n]) { primes.push(n); } } return primes; }
[ "function", "getPrimes", "(", "limit", ")", "{", "var", "sieve", "=", "new", "Array", "(", "limit", ")", ";", "var", "n", ",", "j", ",", "k", ";", "var", "last", "=", "Math", ".", "floor", "(", "Math", ".", "sqrt", "(", "limit", ")", ")", ";", "for", "(", "n", "=", "2", ";", "n", "<", "limit", ";", "n", "++", ")", "{", "sieve", "[", "n", "]", "=", "true", ";", "}", "for", "(", "n", "=", "2", ";", "n", "<=", "last", ";", ")", "{", "for", "(", "j", "=", "n", "+", "n", ";", "j", "<", "limit", ";", "j", "+=", "n", ")", "{", "sieve", "[", "j", "]", "=", "false", ";", "}", "for", "(", "j", "=", "1", ";", "j", "<", "last", ";", "j", "++", ")", "{", "k", "=", "n", "+", "j", ";", "if", "(", "sieve", "[", "k", "]", ")", "{", "n", "=", "k", ";", "break", ";", "}", "}", "}", "var", "primes", "=", "[", "]", ";", "for", "(", "n", "=", "2", ";", "n", "<", "limit", ";", "n", "++", ")", "{", "if", "(", "sieve", "[", "n", "]", ")", "{", "primes", ".", "push", "(", "n", ")", ";", "}", "}", "return", "primes", ";", "}" ]
sieve of Eratosthenes to get prime numbers. @param limit
[ "sieve", "of", "Eratosthenes", "to", "get", "prime", "numbers", "." ]
4ded3176c8a9dceb3f2017f66581929d3cfc1084
https://github.com/samplx/samplx-agentdb/blob/4ded3176c8a9dceb3f2017f66581929d3cfc1084/utils/tune-hash.js#L42-L68
52,079
samplx/samplx-agentdb
utils/tune-hash.js
fill
function fill(size, seed, multiplier) { var hash = new HashTable(size, seed, multiplier); var x = agentdb.getX(1, 1); // dummy data Unknown, Unknown agents.forEach(function (agent) { if (agent.status < 2) { var obj = { "a": agent.agent, "x": x }; hash.add('a', obj); } }); return hash.getHistory(); }
javascript
function fill(size, seed, multiplier) { var hash = new HashTable(size, seed, multiplier); var x = agentdb.getX(1, 1); // dummy data Unknown, Unknown agents.forEach(function (agent) { if (agent.status < 2) { var obj = { "a": agent.agent, "x": x }; hash.add('a', obj); } }); return hash.getHistory(); }
[ "function", "fill", "(", "size", ",", "seed", ",", "multiplier", ")", "{", "var", "hash", "=", "new", "HashTable", "(", "size", ",", "seed", ",", "multiplier", ")", ";", "var", "x", "=", "agentdb", ".", "getX", "(", "1", ",", "1", ")", ";", "// dummy data Unknown, Unknown", "agents", ".", "forEach", "(", "function", "(", "agent", ")", "{", "if", "(", "agent", ".", "status", "<", "2", ")", "{", "var", "obj", "=", "{", "\"a\"", ":", "agent", ".", "agent", ",", "\"x\"", ":", "x", "}", ";", "hash", ".", "add", "(", "'a'", ",", "obj", ")", ";", "}", "}", ")", ";", "return", "hash", ".", "getHistory", "(", ")", ";", "}" ]
Fill the hash table with the agents. @param size of hash table. @param seed for hash table. @param multiplier of hash table. @rtype Array hash table history.
[ "Fill", "the", "hash", "table", "with", "the", "agents", "." ]
4ded3176c8a9dceb3f2017f66581929d3cfc1084
https://github.com/samplx/samplx-agentdb/blob/4ded3176c8a9dceb3f2017f66581929d3cfc1084/utils/tune-hash.js#L78-L88
52,080
samplx/samplx-agentdb
utils/tune-hash.js
dumpHistory
function dumpHistory(history, size, depth) { console.log("Hash table history, size="+size+", average depth="+depth); for (var n=0; n < history.length; n++) { console.log(" Depth=" + n + ", count=" + history[n] + ", percent=" + (history[n] / size)); } console.log(""); }
javascript
function dumpHistory(history, size, depth) { console.log("Hash table history, size="+size+", average depth="+depth); for (var n=0; n < history.length; n++) { console.log(" Depth=" + n + ", count=" + history[n] + ", percent=" + (history[n] / size)); } console.log(""); }
[ "function", "dumpHistory", "(", "history", ",", "size", ",", "depth", ")", "{", "console", ".", "log", "(", "\"Hash table history, size=\"", "+", "size", "+", "\", average depth=\"", "+", "depth", ")", ";", "for", "(", "var", "n", "=", "0", ";", "n", "<", "history", ".", "length", ";", "n", "++", ")", "{", "console", ".", "log", "(", "\" Depth=\"", "+", "n", "+", "\", count=\"", "+", "history", "[", "n", "]", "+", "\", percent=\"", "+", "(", "history", "[", "n", "]", "/", "size", ")", ")", ";", "}", "console", ".", "log", "(", "\"\"", ")", ";", "}" ]
Write the hash table history to the console. @param history Array. @param size of the hash table. @param depth fit estimate.
[ "Write", "the", "hash", "table", "history", "to", "the", "console", "." ]
4ded3176c8a9dceb3f2017f66581929d3cfc1084
https://github.com/samplx/samplx-agentdb/blob/4ded3176c8a9dceb3f2017f66581929d3cfc1084/utils/tune-hash.js#L97-L103
52,081
samplx/samplx-agentdb
utils/tune-hash.js
getDepth
function getDepth(history) { var total= history[0]; for (var n=1; n < history.length; n++) { total = total + (n * n * history[n]); } var result = total / agents.length; // console.log("total=" + total+", result=" + result); return result; }
javascript
function getDepth(history) { var total= history[0]; for (var n=1; n < history.length; n++) { total = total + (n * n * history[n]); } var result = total / agents.length; // console.log("total=" + total+", result=" + result); return result; }
[ "function", "getDepth", "(", "history", ")", "{", "var", "total", "=", "history", "[", "0", "]", ";", "for", "(", "var", "n", "=", "1", ";", "n", "<", "history", ".", "length", ";", "n", "++", ")", "{", "total", "=", "total", "+", "(", "n", "*", "n", "*", "history", "[", "n", "]", ")", ";", "}", "var", "result", "=", "total", "/", "agents", ".", "length", ";", "// console.log(\"total=\" + total+\", result=\" + result);", "return", "result", ";", "}" ]
find the average search depth. Include the null entries for cost. @param history of hash table. @rtype Number.
[ "find", "the", "average", "search", "depth", ".", "Include", "the", "null", "entries", "for", "cost", "." ]
4ded3176c8a9dceb3f2017f66581929d3cfc1084
https://github.com/samplx/samplx-agentdb/blob/4ded3176c8a9dceb3f2017f66581929d3cfc1084/utils/tune-hash.js#L111-L119
52,082
samplx/samplx-agentdb
utils/tune-hash.js
main
function main() { if (verbose) { console.log("Finding primes to " + UPPER); } var primes = getPrimes(UPPER); if (verbose) { console.log("Done."); } var bestSize = varySize(LOWER, UPPER, 5381, 33, primes); var bestSeed = varySeed(0, 8192, bestSize, 33); var bestMult = varyMultiplier(2, 256, bestSize, bestSeed); bestSize = varySize(LOWER, UPPER, bestSeed, bestMult, primes); }
javascript
function main() { if (verbose) { console.log("Finding primes to " + UPPER); } var primes = getPrimes(UPPER); if (verbose) { console.log("Done."); } var bestSize = varySize(LOWER, UPPER, 5381, 33, primes); var bestSeed = varySeed(0, 8192, bestSize, 33); var bestMult = varyMultiplier(2, 256, bestSize, bestSeed); bestSize = varySize(LOWER, UPPER, bestSeed, bestMult, primes); }
[ "function", "main", "(", ")", "{", "if", "(", "verbose", ")", "{", "console", ".", "log", "(", "\"Finding primes to \"", "+", "UPPER", ")", ";", "}", "var", "primes", "=", "getPrimes", "(", "UPPER", ")", ";", "if", "(", "verbose", ")", "{", "console", ".", "log", "(", "\"Done.\"", ")", ";", "}", "var", "bestSize", "=", "varySize", "(", "LOWER", ",", "UPPER", ",", "5381", ",", "33", ",", "primes", ")", ";", "var", "bestSeed", "=", "varySeed", "(", "0", ",", "8192", ",", "bestSize", ",", "33", ")", ";", "var", "bestMult", "=", "varyMultiplier", "(", "2", ",", "256", ",", "bestSize", ",", "bestSeed", ")", ";", "bestSize", "=", "varySize", "(", "LOWER", ",", "UPPER", ",", "bestSeed", ",", "bestMult", ",", "primes", ")", ";", "}" ]
tune-hash table main function.
[ "tune", "-", "hash", "table", "main", "function", "." ]
4ded3176c8a9dceb3f2017f66581929d3cfc1084
https://github.com/samplx/samplx-agentdb/blob/4ded3176c8a9dceb3f2017f66581929d3cfc1084/utils/tune-hash.js#L185-L194
52,083
redisjs/jsr-loader
lib/index.js
include
function include(list) { var cmd, clazz, i, file, j, name, newname; for(i = 0;i < list.length;i++) { file = list[i]; try { clazz = require(file); // assume it is already instantiated if(typeof clazz === 'object') { cmd = clazz; }else{ cmd = new clazz(clazz.definition); } // rename and delete commands if(cmd && cmd.definition && cmd.definition.name) { for(j = 0;j < rename.length;j++) { name = rename[j][0]; newname = rename[j][1]; if(name && name.toLowerCase() === cmd.definition.name.toLowerCase()) { newname = (newname || '').toLowerCase(); // actually renaming if(newname) { log.warning( 'rename command %s -> %s', cmd.definition.name, newname); cmd.definition.name = newname; // deleting the command, mark as deleted with false }else{ log.warning( 'deleted command %s (%s)', cmd.definition.name, file); commands[cmd.definition.name] = false; // clear the module cache delete require.cache[file]; } break; } } } // deleted the command if(!require.cache[file]) continue; // sanity checks if(!(cmd instanceof CommandExec)) { throw new Error( util.format( 'module does not export a command exec instance (%s)', file)); }else if( !cmd.definition || !cmd.definition.constructor || cmd.definition.constructor.name !== Command.name) { throw new Error( util.format( 'command does not have a valid definition (%s)', file)); }else if(!cmd.definition.name) { throw new Error( util.format( 'command definition does not have a name (%s)', file)); } if(opts.override !== true && commands[cmd.definition.name]) { throw new Error(util.format( 'duplicate command %s (%s)', cmd.definition.name, file)); } log.debug('loaded %s (%s)', cmd.definition.name, file); // map of command names to command exec handlers commands[cmd.definition.name] = cmd; }catch(e) { return complete(e); } } complete(); }
javascript
function include(list) { var cmd, clazz, i, file, j, name, newname; for(i = 0;i < list.length;i++) { file = list[i]; try { clazz = require(file); // assume it is already instantiated if(typeof clazz === 'object') { cmd = clazz; }else{ cmd = new clazz(clazz.definition); } // rename and delete commands if(cmd && cmd.definition && cmd.definition.name) { for(j = 0;j < rename.length;j++) { name = rename[j][0]; newname = rename[j][1]; if(name && name.toLowerCase() === cmd.definition.name.toLowerCase()) { newname = (newname || '').toLowerCase(); // actually renaming if(newname) { log.warning( 'rename command %s -> %s', cmd.definition.name, newname); cmd.definition.name = newname; // deleting the command, mark as deleted with false }else{ log.warning( 'deleted command %s (%s)', cmd.definition.name, file); commands[cmd.definition.name] = false; // clear the module cache delete require.cache[file]; } break; } } } // deleted the command if(!require.cache[file]) continue; // sanity checks if(!(cmd instanceof CommandExec)) { throw new Error( util.format( 'module does not export a command exec instance (%s)', file)); }else if( !cmd.definition || !cmd.definition.constructor || cmd.definition.constructor.name !== Command.name) { throw new Error( util.format( 'command does not have a valid definition (%s)', file)); }else if(!cmd.definition.name) { throw new Error( util.format( 'command definition does not have a name (%s)', file)); } if(opts.override !== true && commands[cmd.definition.name]) { throw new Error(util.format( 'duplicate command %s (%s)', cmd.definition.name, file)); } log.debug('loaded %s (%s)', cmd.definition.name, file); // map of command names to command exec handlers commands[cmd.definition.name] = cmd; }catch(e) { return complete(e); } } complete(); }
[ "function", "include", "(", "list", ")", "{", "var", "cmd", ",", "clazz", ",", "i", ",", "file", ",", "j", ",", "name", ",", "newname", ";", "for", "(", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "file", "=", "list", "[", "i", "]", ";", "try", "{", "clazz", "=", "require", "(", "file", ")", ";", "// assume it is already instantiated", "if", "(", "typeof", "clazz", "===", "'object'", ")", "{", "cmd", "=", "clazz", ";", "}", "else", "{", "cmd", "=", "new", "clazz", "(", "clazz", ".", "definition", ")", ";", "}", "// rename and delete commands", "if", "(", "cmd", "&&", "cmd", ".", "definition", "&&", "cmd", ".", "definition", ".", "name", ")", "{", "for", "(", "j", "=", "0", ";", "j", "<", "rename", ".", "length", ";", "j", "++", ")", "{", "name", "=", "rename", "[", "j", "]", "[", "0", "]", ";", "newname", "=", "rename", "[", "j", "]", "[", "1", "]", ";", "if", "(", "name", "&&", "name", ".", "toLowerCase", "(", ")", "===", "cmd", ".", "definition", ".", "name", ".", "toLowerCase", "(", ")", ")", "{", "newname", "=", "(", "newname", "||", "''", ")", ".", "toLowerCase", "(", ")", ";", "// actually renaming", "if", "(", "newname", ")", "{", "log", ".", "warning", "(", "'rename command %s -> %s'", ",", "cmd", ".", "definition", ".", "name", ",", "newname", ")", ";", "cmd", ".", "definition", ".", "name", "=", "newname", ";", "// deleting the command, mark as deleted with false", "}", "else", "{", "log", ".", "warning", "(", "'deleted command %s (%s)'", ",", "cmd", ".", "definition", ".", "name", ",", "file", ")", ";", "commands", "[", "cmd", ".", "definition", ".", "name", "]", "=", "false", ";", "// clear the module cache", "delete", "require", ".", "cache", "[", "file", "]", ";", "}", "break", ";", "}", "}", "}", "// deleted the command", "if", "(", "!", "require", ".", "cache", "[", "file", "]", ")", "continue", ";", "// sanity checks", "if", "(", "!", "(", "cmd", "instanceof", "CommandExec", ")", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'module does not export a command exec instance (%s)'", ",", "file", ")", ")", ";", "}", "else", "if", "(", "!", "cmd", ".", "definition", "||", "!", "cmd", ".", "definition", ".", "constructor", "||", "cmd", ".", "definition", ".", "constructor", ".", "name", "!==", "Command", ".", "name", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'command does not have a valid definition (%s)'", ",", "file", ")", ")", ";", "}", "else", "if", "(", "!", "cmd", ".", "definition", ".", "name", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'command definition does not have a name (%s)'", ",", "file", ")", ")", ";", "}", "if", "(", "opts", ".", "override", "!==", "true", "&&", "commands", "[", "cmd", ".", "definition", ".", "name", "]", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'duplicate command %s (%s)'", ",", "cmd", ".", "definition", ".", "name", ",", "file", ")", ")", ";", "}", "log", ".", "debug", "(", "'loaded %s (%s)'", ",", "cmd", ".", "definition", ".", "name", ",", "file", ")", ";", "// map of command names to command exec handlers", "commands", "[", "cmd", ".", "definition", ".", "name", "]", "=", "cmd", ";", "}", "catch", "(", "e", ")", "{", "return", "complete", "(", "e", ")", ";", "}", "}", "complete", "(", ")", ";", "}" ]
Requires the array of files.
[ "Requires", "the", "array", "of", "files", "." ]
93384142f6cfe1e6827c2789df76af06fa9eaf3d
https://github.com/redisjs/jsr-loader/blob/93384142f6cfe1e6827c2789df76af06fa9eaf3d/lib/index.js#L40-L114
52,084
redisjs/jsr-loader
lib/index.js
walk
function walk(files, cb, list) { var i = 0; list = list || []; function check(file, cb) { fs.stat(file, function onStat(err, stats) { if(err) return cb(err); if(stats.isFile() && !/\.js$/.test(file)) { log.warning('ignoring %s', file); return cb(); } if(stats.isFile()) { list.push(file); return cb(null, list); }else{ return fs.readdir(file, function onRead(err, files) { if(err) return cb(err); if(!files.length) return cb(); files = files.map(function(nm) { return path.join(file, nm); }) //files.forEach() return walk(files, cb, list); }) } }); } check(files[i], function onCheck(err, list) { if(err) return cb(err); if(i === files.length - 1) { return cb(null, list); } i++; check(files[i], onCheck); }); }
javascript
function walk(files, cb, list) { var i = 0; list = list || []; function check(file, cb) { fs.stat(file, function onStat(err, stats) { if(err) return cb(err); if(stats.isFile() && !/\.js$/.test(file)) { log.warning('ignoring %s', file); return cb(); } if(stats.isFile()) { list.push(file); return cb(null, list); }else{ return fs.readdir(file, function onRead(err, files) { if(err) return cb(err); if(!files.length) return cb(); files = files.map(function(nm) { return path.join(file, nm); }) //files.forEach() return walk(files, cb, list); }) } }); } check(files[i], function onCheck(err, list) { if(err) return cb(err); if(i === files.length - 1) { return cb(null, list); } i++; check(files[i], onCheck); }); }
[ "function", "walk", "(", "files", ",", "cb", ",", "list", ")", "{", "var", "i", "=", "0", ";", "list", "=", "list", "||", "[", "]", ";", "function", "check", "(", "file", ",", "cb", ")", "{", "fs", ".", "stat", "(", "file", ",", "function", "onStat", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "stats", ".", "isFile", "(", ")", "&&", "!", "/", "\\.js$", "/", ".", "test", "(", "file", ")", ")", "{", "log", ".", "warning", "(", "'ignoring %s'", ",", "file", ")", ";", "return", "cb", "(", ")", ";", "}", "if", "(", "stats", ".", "isFile", "(", ")", ")", "{", "list", ".", "push", "(", "file", ")", ";", "return", "cb", "(", "null", ",", "list", ")", ";", "}", "else", "{", "return", "fs", ".", "readdir", "(", "file", ",", "function", "onRead", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "!", "files", ".", "length", ")", "return", "cb", "(", ")", ";", "files", "=", "files", ".", "map", "(", "function", "(", "nm", ")", "{", "return", "path", ".", "join", "(", "file", ",", "nm", ")", ";", "}", ")", "//files.forEach()", "return", "walk", "(", "files", ",", "cb", ",", "list", ")", ";", "}", ")", "}", "}", ")", ";", "}", "check", "(", "files", "[", "i", "]", ",", "function", "onCheck", "(", "err", ",", "list", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "i", "===", "files", ".", "length", "-", "1", ")", "{", "return", "cb", "(", "null", ",", "list", ")", ";", "}", "i", "++", ";", "check", "(", "files", "[", "i", "]", ",", "onCheck", ")", ";", "}", ")", ";", "}" ]
Walk the file list array.
[ "Walk", "the", "file", "list", "array", "." ]
93384142f6cfe1e6827c2789df76af06fa9eaf3d
https://github.com/redisjs/jsr-loader/blob/93384142f6cfe1e6827c2789df76af06fa9eaf3d/lib/index.js#L119-L155
52,085
tjmehta/validate-firepad-text-operation
index.js
validateTextOperationJSON
function validateTextOperationJSON (op) { debug('validateTextOperationJSON %o', op) assertErr(Array.isArray(op), Error, 'operation must be an array', { op: op }) assertErr(op.length, Error, 'operation cannot be empty', { op: op }) var type var lastType = '' op.forEach(function (item) { if (typeof item === 'string') { // valid type = 'string' assertErr(lastType !== type, Error, 'invalid operation: cannot have repeating ' + type + 's') lastType = type return } else if (typeof item === 'number') { var isIntegerOrZero = (item === (item | 0)) assertErr(isIntegerOrZero, Error, 'invalid operation: numbers must be integers') type = item === 0 ? 'zero' : item > 0 ? 'positive integer' : 'negative integer' assertErr(lastType !== type, Error, 'invalid operation: cannot have repeating ' + type + 's') lastType = type } else { throw new Error('invalid operation: must be an array of strings and numbers') } }) }
javascript
function validateTextOperationJSON (op) { debug('validateTextOperationJSON %o', op) assertErr(Array.isArray(op), Error, 'operation must be an array', { op: op }) assertErr(op.length, Error, 'operation cannot be empty', { op: op }) var type var lastType = '' op.forEach(function (item) { if (typeof item === 'string') { // valid type = 'string' assertErr(lastType !== type, Error, 'invalid operation: cannot have repeating ' + type + 's') lastType = type return } else if (typeof item === 'number') { var isIntegerOrZero = (item === (item | 0)) assertErr(isIntegerOrZero, Error, 'invalid operation: numbers must be integers') type = item === 0 ? 'zero' : item > 0 ? 'positive integer' : 'negative integer' assertErr(lastType !== type, Error, 'invalid operation: cannot have repeating ' + type + 's') lastType = type } else { throw new Error('invalid operation: must be an array of strings and numbers') } }) }
[ "function", "validateTextOperationJSON", "(", "op", ")", "{", "debug", "(", "'validateTextOperationJSON %o'", ",", "op", ")", "assertErr", "(", "Array", ".", "isArray", "(", "op", ")", ",", "Error", ",", "'operation must be an array'", ",", "{", "op", ":", "op", "}", ")", "assertErr", "(", "op", ".", "length", ",", "Error", ",", "'operation cannot be empty'", ",", "{", "op", ":", "op", "}", ")", "var", "type", "var", "lastType", "=", "''", "op", ".", "forEach", "(", "function", "(", "item", ")", "{", "if", "(", "typeof", "item", "===", "'string'", ")", "{", "// valid", "type", "=", "'string'", "assertErr", "(", "lastType", "!==", "type", ",", "Error", ",", "'invalid operation: cannot have repeating '", "+", "type", "+", "'s'", ")", "lastType", "=", "type", "return", "}", "else", "if", "(", "typeof", "item", "===", "'number'", ")", "{", "var", "isIntegerOrZero", "=", "(", "item", "===", "(", "item", "|", "0", ")", ")", "assertErr", "(", "isIntegerOrZero", ",", "Error", ",", "'invalid operation: numbers must be integers'", ")", "type", "=", "item", "===", "0", "?", "'zero'", ":", "item", ">", "0", "?", "'positive integer'", ":", "'negative integer'", "assertErr", "(", "lastType", "!==", "type", ",", "Error", ",", "'invalid operation: cannot have repeating '", "+", "type", "+", "'s'", ")", "lastType", "=", "type", "}", "else", "{", "throw", "new", "Error", "(", "'invalid operation: must be an array of strings and numbers'", ")", "}", "}", ")", "}" ]
validate firepad text-operation json @param {Array} op firepad text-operation json @return {[type]} [description]
[ "validate", "firepad", "text", "-", "operation", "json" ]
7ebb8a390966aba0991c677a94b6e6aa62fbe5a5
https://github.com/tjmehta/validate-firepad-text-operation/blob/7ebb8a390966aba0991c677a94b6e6aa62fbe5a5/index.js#L13-L40
52,086
ctrees/msfeature
lib/methods/findStep.js
trim
function trim(str) { var input = str.replace(/\s\s+/g, ' ').trim(); var words = input.split(' '); if (_.contains(LANG_WORDS, _.first(words))) { return words.slice(1).join(' '); } return input; }
javascript
function trim(str) { var input = str.replace(/\s\s+/g, ' ').trim(); var words = input.split(' '); if (_.contains(LANG_WORDS, _.first(words))) { return words.slice(1).join(' '); } return input; }
[ "function", "trim", "(", "str", ")", "{", "var", "input", "=", "str", ".", "replace", "(", "/", "\\s\\s+", "/", "g", ",", "' '", ")", ".", "trim", "(", ")", ";", "var", "words", "=", "input", ".", "split", "(", "' '", ")", ";", "if", "(", "_", ".", "contains", "(", "LANG_WORDS", ",", "_", ".", "first", "(", "words", ")", ")", ")", "{", "return", "words", ".", "slice", "(", "1", ")", ".", "join", "(", "' '", ")", ";", "}", "return", "input", ";", "}" ]
Sanitize input and trim first word if Gherkin lang
[ "Sanitize", "input", "and", "trim", "first", "word", "if", "Gherkin", "lang" ]
5ee14fe11ade502ab2b47467717094ea9ea7b6ec
https://github.com/ctrees/msfeature/blob/5ee14fe11ade502ab2b47467717094ea9ea7b6ec/lib/methods/findStep.js#L16-L24
52,087
Nazariglez/perenquen
lib/pixi/src/filters/invert/InvertFilter.js
InvertFilter
function InvertFilter() { core.AbstractFilter.call(this, // vertex shader null, // fragment shader fs.readFileSync(__dirname + '/invert.frag', 'utf8'), // custom uniforms { invert: { type: '1f', value: 1 } } ); }
javascript
function InvertFilter() { core.AbstractFilter.call(this, // vertex shader null, // fragment shader fs.readFileSync(__dirname + '/invert.frag', 'utf8'), // custom uniforms { invert: { type: '1f', value: 1 } } ); }
[ "function", "InvertFilter", "(", ")", "{", "core", ".", "AbstractFilter", ".", "call", "(", "this", ",", "// vertex shader", "null", ",", "// fragment shader", "fs", ".", "readFileSync", "(", "__dirname", "+", "'/invert.frag'", ",", "'utf8'", ")", ",", "// custom uniforms", "{", "invert", ":", "{", "type", ":", "'1f'", ",", "value", ":", "1", "}", "}", ")", ";", "}" ]
This inverts your Display Objects colors. @class @extends AbstractFilter @memberof PIXI.filters
[ "This", "inverts", "your", "Display", "Objects", "colors", "." ]
e023964d05afeefebdcac4e2044819fdfa3899ae
https://github.com/Nazariglez/perenquen/blob/e023964d05afeefebdcac4e2044819fdfa3899ae/lib/pixi/src/filters/invert/InvertFilter.js#L12-L24
52,088
schwarzkopfb/ellipse
lib/router.js
function (req, res, next) { req.mounted = true req.url = req.url.replace(remove, '') // clear cached req.path delete req._path delete req._pathLength next() }
javascript
function (req, res, next) { req.mounted = true req.url = req.url.replace(remove, '') // clear cached req.path delete req._path delete req._pathLength next() }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "req", ".", "mounted", "=", "true", "req", ".", "url", "=", "req", ".", "url", ".", "replace", "(", "remove", ",", "''", ")", "// clear cached req.path", "delete", "req", ".", "_path", "delete", "req", ".", "_pathLength", "next", "(", ")", "}" ]
add mount middleware to the beginning of this sub-chain
[ "add", "mount", "middleware", "to", "the", "beginning", "of", "this", "sub", "-", "chain" ]
4400d3bb09061893b1a76ff2983f28ad2ad0c5a7
https://github.com/schwarzkopfb/ellipse/blob/4400d3bb09061893b1a76ff2983f28ad2ad0c5a7/lib/router.js#L293-L302
52,089
FreeAllMedia/dovima
es5/lib/model/delete.js
deleteSelf
function deleteSelf(callback) { var _this = this; _flowsync2["default"].series([function (done) { _this.beforeDelete(done); }, function (done) { if (_this.constructor.useSoftDelete !== undefined) { _this.softDestroy(done); } else { _this.destroy(done); } }, function (done) { _this.afterDelete(done); }], function (errors) { callback(errors); }); }
javascript
function deleteSelf(callback) { var _this = this; _flowsync2["default"].series([function (done) { _this.beforeDelete(done); }, function (done) { if (_this.constructor.useSoftDelete !== undefined) { _this.softDestroy(done); } else { _this.destroy(done); } }, function (done) { _this.afterDelete(done); }], function (errors) { callback(errors); }); }
[ "function", "deleteSelf", "(", "callback", ")", "{", "var", "_this", "=", "this", ";", "_flowsync2", "[", "\"default\"", "]", ".", "series", "(", "[", "function", "(", "done", ")", "{", "_this", ".", "beforeDelete", "(", "done", ")", ";", "}", ",", "function", "(", "done", ")", "{", "if", "(", "_this", ".", "constructor", ".", "useSoftDelete", "!==", "undefined", ")", "{", "_this", ".", "softDestroy", "(", "done", ")", ";", "}", "else", "{", "_this", ".", "destroy", "(", "done", ")", ";", "}", "}", ",", "function", "(", "done", ")", "{", "_this", ".", "afterDelete", "(", "done", ")", ";", "}", "]", ",", "function", "(", "errors", ")", "{", "callback", "(", "errors", ")", ";", "}", ")", ";", "}" ]
Delete the model according to the prescribed strategy. Named "deleteSelf" because "delete" is a reserved keyword in JS. @method deleteSelf @param {Function} callback
[ "Delete", "the", "model", "according", "to", "the", "prescribed", "strategy", "." ]
364db634fe85c0132e32807d8cecb4959e242ccd
https://github.com/FreeAllMedia/dovima/blob/364db634fe85c0132e32807d8cecb4959e242ccd/es5/lib/model/delete.js#L39-L55
52,090
smelukov/PromiseDelay
src/main.js
inject
function inject(PromiseConstructor, extName) { if (typeof PromiseConstructor === 'string') { extName = PromiseConstructor; } extName = typeof extName === 'string' ? extName : 'delay'; PromiseConstructor = (typeof PromiseConstructor === 'function' && PromiseConstructor) || (typeof Promise === 'function' && Promise) || null; if (!PromiseConstructor) { throw new Error('Wrong constructor is passed or browser doesn\'t support promises'); } /** * Delay promise * Will be resolved after `ms` milliseconds. 1000 by default * * @param {number=} ms * * @return {Promise} */ PromiseConstructor[extName] = function(ms) { ms = ms || 1000; if (this instanceof PromiseConstructor) { return this.then(function(value) { return PromiseConstructor[extName](ms).then(function() { return value; }); }); } else { return new PromiseConstructor(function(resolve) { setTimeout(resolve, ms); }); } }; if (typeof PromiseConstructor === 'function' && PromiseConstructor.prototype && PromiseConstructor.prototype.constructor === PromiseConstructor) { PromiseConstructor.prototype[extName] = PromiseConstructor[extName]; } return PromiseConstructor; }
javascript
function inject(PromiseConstructor, extName) { if (typeof PromiseConstructor === 'string') { extName = PromiseConstructor; } extName = typeof extName === 'string' ? extName : 'delay'; PromiseConstructor = (typeof PromiseConstructor === 'function' && PromiseConstructor) || (typeof Promise === 'function' && Promise) || null; if (!PromiseConstructor) { throw new Error('Wrong constructor is passed or browser doesn\'t support promises'); } /** * Delay promise * Will be resolved after `ms` milliseconds. 1000 by default * * @param {number=} ms * * @return {Promise} */ PromiseConstructor[extName] = function(ms) { ms = ms || 1000; if (this instanceof PromiseConstructor) { return this.then(function(value) { return PromiseConstructor[extName](ms).then(function() { return value; }); }); } else { return new PromiseConstructor(function(resolve) { setTimeout(resolve, ms); }); } }; if (typeof PromiseConstructor === 'function' && PromiseConstructor.prototype && PromiseConstructor.prototype.constructor === PromiseConstructor) { PromiseConstructor.prototype[extName] = PromiseConstructor[extName]; } return PromiseConstructor; }
[ "function", "inject", "(", "PromiseConstructor", ",", "extName", ")", "{", "if", "(", "typeof", "PromiseConstructor", "===", "'string'", ")", "{", "extName", "=", "PromiseConstructor", ";", "}", "extName", "=", "typeof", "extName", "===", "'string'", "?", "extName", ":", "'delay'", ";", "PromiseConstructor", "=", "(", "typeof", "PromiseConstructor", "===", "'function'", "&&", "PromiseConstructor", ")", "||", "(", "typeof", "Promise", "===", "'function'", "&&", "Promise", ")", "||", "null", ";", "if", "(", "!", "PromiseConstructor", ")", "{", "throw", "new", "Error", "(", "'Wrong constructor is passed or browser doesn\\'t support promises'", ")", ";", "}", "/**\n\t\t * Delay promise\n\t\t * Will be resolved after `ms` milliseconds. 1000 by default\n\t\t *\n\t\t * @param {number=} ms\n\t\t *\n\t\t * @return {Promise}\n\t\t */", "PromiseConstructor", "[", "extName", "]", "=", "function", "(", "ms", ")", "{", "ms", "=", "ms", "||", "1000", ";", "if", "(", "this", "instanceof", "PromiseConstructor", ")", "{", "return", "this", ".", "then", "(", "function", "(", "value", ")", "{", "return", "PromiseConstructor", "[", "extName", "]", "(", "ms", ")", ".", "then", "(", "function", "(", ")", "{", "return", "value", ";", "}", ")", ";", "}", ")", ";", "}", "else", "{", "return", "new", "PromiseConstructor", "(", "function", "(", "resolve", ")", "{", "setTimeout", "(", "resolve", ",", "ms", ")", ";", "}", ")", ";", "}", "}", ";", "if", "(", "typeof", "PromiseConstructor", "===", "'function'", "&&", "PromiseConstructor", ".", "prototype", "&&", "PromiseConstructor", ".", "prototype", ".", "constructor", "===", "PromiseConstructor", ")", "{", "PromiseConstructor", ".", "prototype", "[", "extName", "]", "=", "PromiseConstructor", "[", "extName", "]", ";", "}", "return", "PromiseConstructor", ";", "}" ]
Inject method with name `extName` to `PromiseConstructor` @param {Function|String=} PromiseConstructor which constructor should be extended If not defined, then default promise-constructor will be used @param {String=} extName name of the method. If not defined, then 'delay' will be used @returns {Function} @throws {Error}
[ "Inject", "method", "with", "name", "extName", "to", "PromiseConstructor" ]
f304103854c4a92e94cffe21d706e4763040703f
https://github.com/smelukov/PromiseDelay/blob/f304103854c4a92e94cffe21d706e4763040703f/src/main.js#L18-L62
52,091
tolokoban/ToloFrameWork
lib/boilerplate.view.js
generate
function generate( arr, comment, _indent ) { try { const indent = typeof _indent !== "undefined" ? _indent : " "; if ( arr.length === 0 ) return ""; let out = ''; if ( comment && comment.length > 0 ) { let len = comment.length + 3, dashes = ''; while ( len-- > 0 ) dashes += "-"; out += `${indent}//${dashes}\n${indent}// ${comment}.\n`; } arr.forEach( function ( line ) { if ( Array.isArray( line ) ) { out += generate( line, null, ` ${indent}` ); } else { out += `${indent}${line}\n`; } } ); return out; } catch ( ex ) { throw ex + "\n...in generate: " + JSON.stringify( comment ); } }
javascript
function generate( arr, comment, _indent ) { try { const indent = typeof _indent !== "undefined" ? _indent : " "; if ( arr.length === 0 ) return ""; let out = ''; if ( comment && comment.length > 0 ) { let len = comment.length + 3, dashes = ''; while ( len-- > 0 ) dashes += "-"; out += `${indent}//${dashes}\n${indent}// ${comment}.\n`; } arr.forEach( function ( line ) { if ( Array.isArray( line ) ) { out += generate( line, null, ` ${indent}` ); } else { out += `${indent}${line}\n`; } } ); return out; } catch ( ex ) { throw ex + "\n...in generate: " + JSON.stringify( comment ); } }
[ "function", "generate", "(", "arr", ",", "comment", ",", "_indent", ")", "{", "try", "{", "const", "indent", "=", "typeof", "_indent", "!==", "\"undefined\"", "?", "_indent", ":", "\" \"", ";", "if", "(", "arr", ".", "length", "===", "0", ")", "return", "\"\"", ";", "let", "out", "=", "''", ";", "if", "(", "comment", "&&", "comment", ".", "length", ">", "0", ")", "{", "let", "len", "=", "comment", ".", "length", "+", "3", ",", "dashes", "=", "''", ";", "while", "(", "len", "--", ">", "0", ")", "dashes", "+=", "\"-\"", ";", "out", "+=", "`", "${", "indent", "}", "${", "dashes", "}", "\\n", "${", "indent", "}", "${", "comment", "}", "\\n", "`", ";", "}", "arr", ".", "forEach", "(", "function", "(", "line", ")", "{", "if", "(", "Array", ".", "isArray", "(", "line", ")", ")", "{", "out", "+=", "generate", "(", "line", ",", "null", ",", "`", "${", "indent", "}", "`", ")", ";", "}", "else", "{", "out", "+=", "`", "${", "indent", "}", "${", "line", "}", "\\n", "`", ";", "}", "}", ")", ";", "return", "out", ";", "}", "catch", "(", "ex", ")", "{", "throw", "ex", "+", "\"\\n...in generate: \"", "+", "JSON", ".", "stringify", "(", "comment", ")", ";", "}", "}" ]
Return the code from an array and an identation. The code is preceded by a comment. @param {array} arr - Array of strings and/or arrays. @param {string} comment - Heading comment. Optional. @param {string} _indent - Indetation before each line. @returns {string} Readable Javascript code.
[ "Return", "the", "code", "from", "an", "array", "and", "an", "identation", ".", "The", "code", "is", "preceded", "by", "a", "comment", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/boilerplate.view.js#L85-L108
52,092
tolokoban/ToloFrameWork
lib/boilerplate.view.js
buildViewStatics
function buildViewStatics( def, code ) { try { let statics = def[ "view.statics" ]; if ( typeof statics === 'undefined' ) return; if ( typeof statics === 'string' ) statics = [ statics ]; else if ( !Array.isArray( statics ) ) { throw Error( "view.statics must be a string or an array of strings!" ); } statics.forEach( function ( name ) { code.addNeededBehindFunction( name ); code.section.statics.push( "ViewClass" + keySyntax( name ) + " = CODE_BEHIND" + keySyntax( name ) + ".bind(ViewClass);" ); } ); } catch ( ex ) { throw ex + "\n...in view.statics: " + JSON.stringify( statics ); } }
javascript
function buildViewStatics( def, code ) { try { let statics = def[ "view.statics" ]; if ( typeof statics === 'undefined' ) return; if ( typeof statics === 'string' ) statics = [ statics ]; else if ( !Array.isArray( statics ) ) { throw Error( "view.statics must be a string or an array of strings!" ); } statics.forEach( function ( name ) { code.addNeededBehindFunction( name ); code.section.statics.push( "ViewClass" + keySyntax( name ) + " = CODE_BEHIND" + keySyntax( name ) + ".bind(ViewClass);" ); } ); } catch ( ex ) { throw ex + "\n...in view.statics: " + JSON.stringify( statics ); } }
[ "function", "buildViewStatics", "(", "def", ",", "code", ")", "{", "try", "{", "let", "statics", "=", "def", "[", "\"view.statics\"", "]", ";", "if", "(", "typeof", "statics", "===", "'undefined'", ")", "return", ";", "if", "(", "typeof", "statics", "===", "'string'", ")", "statics", "=", "[", "statics", "]", ";", "else", "if", "(", "!", "Array", ".", "isArray", "(", "statics", ")", ")", "{", "throw", "Error", "(", "\"view.statics must be a string or an array of strings!\"", ")", ";", "}", "statics", ".", "forEach", "(", "function", "(", "name", ")", "{", "code", ".", "addNeededBehindFunction", "(", "name", ")", ";", "code", ".", "section", ".", "statics", ".", "push", "(", "\"ViewClass\"", "+", "keySyntax", "(", "name", ")", "+", "\" = CODE_BEHIND\"", "+", "keySyntax", "(", "name", ")", "+", "\".bind(ViewClass);\"", ")", ";", "}", ")", ";", "}", "catch", "(", "ex", ")", "{", "throw", "ex", "+", "\"\\n...in view.statics: \"", "+", "JSON", ".", "stringify", "(", "statics", ")", ";", "}", "}" ]
Add static functions to the current class. @example view.statics: ["show", "check"] view.statics: "show"
[ "Add", "static", "functions", "to", "the", "current", "class", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/boilerplate.view.js#L135-L154
52,093
tolokoban/ToloFrameWork
lib/boilerplate.view.js
buildViewAttribsFire
function buildViewAttribsFire( def, code ) { code.pm = true; const attribs = def[ "view.attribs" ]; if ( typeof attribs !== 'object' ) return; try { for ( const attName of Object.keys( attribs ) ) { const camelCaseAttName = camelCase( attName ); if ( !code.isAction( attName ) ) { buildViewAttribsInitFire( camelCaseAttName, code ); } } } catch ( ex ) { bubble( ex, `...in buildViewAttribsFire - view.attribs: ${JSON.stringify(attribs, null, " ")}` ); } }
javascript
function buildViewAttribsFire( def, code ) { code.pm = true; const attribs = def[ "view.attribs" ]; if ( typeof attribs !== 'object' ) return; try { for ( const attName of Object.keys( attribs ) ) { const camelCaseAttName = camelCase( attName ); if ( !code.isAction( attName ) ) { buildViewAttribsInitFire( camelCaseAttName, code ); } } } catch ( ex ) { bubble( ex, `...in buildViewAttribsFire - view.attribs: ${JSON.stringify(attribs, null, " ")}` ); } }
[ "function", "buildViewAttribsFire", "(", "def", ",", "code", ")", "{", "code", ".", "pm", "=", "true", ";", "const", "attribs", "=", "def", "[", "\"view.attribs\"", "]", ";", "if", "(", "typeof", "attribs", "!==", "'object'", ")", "return", ";", "try", "{", "for", "(", "const", "attName", "of", "Object", ".", "keys", "(", "attribs", ")", ")", "{", "const", "camelCaseAttName", "=", "camelCase", "(", "attName", ")", ";", "if", "(", "!", "code", ".", "isAction", "(", "attName", ")", ")", "{", "buildViewAttribsInitFire", "(", "camelCaseAttName", ",", "code", ")", ";", "}", "}", "}", "catch", "(", "ex", ")", "{", "bubble", "(", "ex", ",", "`", "${", "JSON", ".", "stringify", "(", "attribs", ",", "null", ",", "\" \"", ")", "}", "`", ")", ";", "}", "}" ]
Trigger the fire event on each attribute. @param {[type]} def [description] @param {[type]} code [description] @returns {undefined}
[ "Trigger", "the", "fire", "event", "on", "each", "attribute", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/boilerplate.view.js#L221-L235
52,094
tolokoban/ToloFrameWork
lib/boilerplate.view.js
buildViewAttribsSpecial
function buildViewAttribsSpecial( attName, attValue, code ) { const type = attValue[ 0 ], init = attValue[ 1 ]; let requireConverter = false; try { if ( typeof attValue.behind !== 'undefined' ) { buildViewAttribsSpecialCodeBehind( attName, attValue.behind, code ); } if ( typeof attValue.debug !== 'undefined' ) { buildViewAttribsSpecialDebug( attName, attValue.debug, code ); } if ( Array.isArray( type ) ) { // Enumerate. code.addCast( "enum" ); code.section.attribs.define.push( "pm.create(" + JSON.stringify( attName ) + `, { cast: conv_enum(${JSON.stringify(type)}), init: ${JSON.stringify(init)} });` ); buildViewAttribsInit( attName, init, code ); } else { switch ( type ) { case 'action': code.actions.push( attName ); code.section.attribs.define.push( "pm.createAction(" + JSON.stringify( attName ) + ")" ); break; case 'any': code.section.attribs.define.push( "pm.create(" + JSON.stringify( attName ) + ");" ); buildViewAttribsInit( attName, init, code ); break; case 'boolean': case 'booleans': case 'date': case 'color': case 'string': case 'strings': case 'array': case 'list': case 'intl': case 'time': case 'unit': case 'units': case 'multilang': case 'validator': requireConverter = true; code.vars[ "conv_" + type ] = "Converters.get('" + type + "')"; code.section.attribs.define.push( "pm.create(" + JSON.stringify( attName ) + ", { cast: conv_" + type + " });" ); buildViewAttribsInit( attName, init, code ); break; case 'integer': case 'float': requireConverter = true; code.vars[ "conv_" + type ] = "Converters.get('" + type + "')"; // Is Not a number, take this default value. let nanValue = attValue.default; if ( typeof nanValue !== 'number' || isNaN( nanValue ) ) { nanValue = 0; } code.section.attribs.define.push( "pm.create(" + JSON.stringify( attName ) + ", { cast: conv_" + type + "(" + nanValue + ") });" ); buildViewAttribsInit( attName, init, code ); break; default: throw "Unknown type \"" + type + "\" for attribute \"" + attName + "\"!"; } } if ( requireConverter ) { code.requires.Converters = "require('tfw.binding.converters')"; } } catch ( ex ) { bubble( ex, `buildViewAttribsSpecial(${attName}: ${JSON.stringify(attValue)})` ); } }
javascript
function buildViewAttribsSpecial( attName, attValue, code ) { const type = attValue[ 0 ], init = attValue[ 1 ]; let requireConverter = false; try { if ( typeof attValue.behind !== 'undefined' ) { buildViewAttribsSpecialCodeBehind( attName, attValue.behind, code ); } if ( typeof attValue.debug !== 'undefined' ) { buildViewAttribsSpecialDebug( attName, attValue.debug, code ); } if ( Array.isArray( type ) ) { // Enumerate. code.addCast( "enum" ); code.section.attribs.define.push( "pm.create(" + JSON.stringify( attName ) + `, { cast: conv_enum(${JSON.stringify(type)}), init: ${JSON.stringify(init)} });` ); buildViewAttribsInit( attName, init, code ); } else { switch ( type ) { case 'action': code.actions.push( attName ); code.section.attribs.define.push( "pm.createAction(" + JSON.stringify( attName ) + ")" ); break; case 'any': code.section.attribs.define.push( "pm.create(" + JSON.stringify( attName ) + ");" ); buildViewAttribsInit( attName, init, code ); break; case 'boolean': case 'booleans': case 'date': case 'color': case 'string': case 'strings': case 'array': case 'list': case 'intl': case 'time': case 'unit': case 'units': case 'multilang': case 'validator': requireConverter = true; code.vars[ "conv_" + type ] = "Converters.get('" + type + "')"; code.section.attribs.define.push( "pm.create(" + JSON.stringify( attName ) + ", { cast: conv_" + type + " });" ); buildViewAttribsInit( attName, init, code ); break; case 'integer': case 'float': requireConverter = true; code.vars[ "conv_" + type ] = "Converters.get('" + type + "')"; // Is Not a number, take this default value. let nanValue = attValue.default; if ( typeof nanValue !== 'number' || isNaN( nanValue ) ) { nanValue = 0; } code.section.attribs.define.push( "pm.create(" + JSON.stringify( attName ) + ", { cast: conv_" + type + "(" + nanValue + ") });" ); buildViewAttribsInit( attName, init, code ); break; default: throw "Unknown type \"" + type + "\" for attribute \"" + attName + "\"!"; } } if ( requireConverter ) { code.requires.Converters = "require('tfw.binding.converters')"; } } catch ( ex ) { bubble( ex, `buildViewAttribsSpecial(${attName}: ${JSON.stringify(attValue)})` ); } }
[ "function", "buildViewAttribsSpecial", "(", "attName", ",", "attValue", ",", "code", ")", "{", "const", "type", "=", "attValue", "[", "0", "]", ",", "init", "=", "attValue", "[", "1", "]", ";", "let", "requireConverter", "=", "false", ";", "try", "{", "if", "(", "typeof", "attValue", ".", "behind", "!==", "'undefined'", ")", "{", "buildViewAttribsSpecialCodeBehind", "(", "attName", ",", "attValue", ".", "behind", ",", "code", ")", ";", "}", "if", "(", "typeof", "attValue", ".", "debug", "!==", "'undefined'", ")", "{", "buildViewAttribsSpecialDebug", "(", "attName", ",", "attValue", ".", "debug", ",", "code", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "type", ")", ")", "{", "// Enumerate.", "code", ".", "addCast", "(", "\"enum\"", ")", ";", "code", ".", "section", ".", "attribs", ".", "define", ".", "push", "(", "\"pm.create(\"", "+", "JSON", ".", "stringify", "(", "attName", ")", "+", "`", "${", "JSON", ".", "stringify", "(", "type", ")", "}", "${", "JSON", ".", "stringify", "(", "init", ")", "}", "`", ")", ";", "buildViewAttribsInit", "(", "attName", ",", "init", ",", "code", ")", ";", "}", "else", "{", "switch", "(", "type", ")", "{", "case", "'action'", ":", "code", ".", "actions", ".", "push", "(", "attName", ")", ";", "code", ".", "section", ".", "attribs", ".", "define", ".", "push", "(", "\"pm.createAction(\"", "+", "JSON", ".", "stringify", "(", "attName", ")", "+", "\")\"", ")", ";", "break", ";", "case", "'any'", ":", "code", ".", "section", ".", "attribs", ".", "define", ".", "push", "(", "\"pm.create(\"", "+", "JSON", ".", "stringify", "(", "attName", ")", "+", "\");\"", ")", ";", "buildViewAttribsInit", "(", "attName", ",", "init", ",", "code", ")", ";", "break", ";", "case", "'boolean'", ":", "case", "'booleans'", ":", "case", "'date'", ":", "case", "'color'", ":", "case", "'string'", ":", "case", "'strings'", ":", "case", "'array'", ":", "case", "'list'", ":", "case", "'intl'", ":", "case", "'time'", ":", "case", "'unit'", ":", "case", "'units'", ":", "case", "'multilang'", ":", "case", "'validator'", ":", "requireConverter", "=", "true", ";", "code", ".", "vars", "[", "\"conv_\"", "+", "type", "]", "=", "\"Converters.get('\"", "+", "type", "+", "\"')\"", ";", "code", ".", "section", ".", "attribs", ".", "define", ".", "push", "(", "\"pm.create(\"", "+", "JSON", ".", "stringify", "(", "attName", ")", "+", "\", { cast: conv_\"", "+", "type", "+", "\" });\"", ")", ";", "buildViewAttribsInit", "(", "attName", ",", "init", ",", "code", ")", ";", "break", ";", "case", "'integer'", ":", "case", "'float'", ":", "requireConverter", "=", "true", ";", "code", ".", "vars", "[", "\"conv_\"", "+", "type", "]", "=", "\"Converters.get('\"", "+", "type", "+", "\"')\"", ";", "// Is Not a number, take this default value.", "let", "nanValue", "=", "attValue", ".", "default", ";", "if", "(", "typeof", "nanValue", "!==", "'number'", "||", "isNaN", "(", "nanValue", ")", ")", "{", "nanValue", "=", "0", ";", "}", "code", ".", "section", ".", "attribs", ".", "define", ".", "push", "(", "\"pm.create(\"", "+", "JSON", ".", "stringify", "(", "attName", ")", "+", "\", { cast: conv_\"", "+", "type", "+", "\"(\"", "+", "nanValue", "+", "\") });\"", ")", ";", "buildViewAttribsInit", "(", "attName", ",", "init", ",", "code", ")", ";", "break", ";", "default", ":", "throw", "\"Unknown type \\\"\"", "+", "type", "+", "\"\\\" for attribute \\\"\"", "+", "attName", "+", "\"\\\"!\"", ";", "}", "}", "if", "(", "requireConverter", ")", "{", "code", ".", "requires", ".", "Converters", "=", "\"require('tfw.binding.converters')\"", ";", "}", "}", "catch", "(", "ex", ")", "{", "bubble", "(", "ex", ",", "`", "${", "attName", "}", "${", "JSON", ".", "stringify", "(", "attValue", ")", "}", "`", ")", ";", "}", "}" ]
Attribute with casting. @example type: {[default, primary, secondary]} count: {integer} content: {string ok behind: onContentChanged}
[ "Attribute", "with", "casting", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/boilerplate.view.js#L244-L325
52,095
tolokoban/ToloFrameWork
lib/boilerplate.view.js
buildViewAttribsInit
function buildViewAttribsInit( attName, attValue, code ) { try { if ( typeof attValue === "undefined" ) { // code.section.attribs.init.push(`this.${attName} = args[${JSON.stringify(attName)}];`); code.section.attribs.init .push( `pm.set("${attName}", args[${JSON.stringify(attName)}]);` ); } else { code.functions.defVal = "(args, attName, attValue) " + "{ return args[attName] === undefined ? attValue : args[attName]; }"; // code.section.attribs.init.push( "this." + attName + " = defVal(args, " + // JSON.stringify( attName ) + ", " + JSON.stringify( attValue ) + // ");" ); code.section.attribs.init .push( `pm.set("${attName}", defVal(args, "${attName}", ${JSON.stringify( attValue )}));` ); } } catch ( ex ) { bubble( ex, `buildViewAttribsInit(${attName}, ${JSON.stringify(attValue)})` ); } }
javascript
function buildViewAttribsInit( attName, attValue, code ) { try { if ( typeof attValue === "undefined" ) { // code.section.attribs.init.push(`this.${attName} = args[${JSON.stringify(attName)}];`); code.section.attribs.init .push( `pm.set("${attName}", args[${JSON.stringify(attName)}]);` ); } else { code.functions.defVal = "(args, attName, attValue) " + "{ return args[attName] === undefined ? attValue : args[attName]; }"; // code.section.attribs.init.push( "this." + attName + " = defVal(args, " + // JSON.stringify( attName ) + ", " + JSON.stringify( attValue ) + // ");" ); code.section.attribs.init .push( `pm.set("${attName}", defVal(args, "${attName}", ${JSON.stringify( attValue )}));` ); } } catch ( ex ) { bubble( ex, `buildViewAttribsInit(${attName}, ${JSON.stringify(attValue)})` ); } }
[ "function", "buildViewAttribsInit", "(", "attName", ",", "attValue", ",", "code", ")", "{", "try", "{", "if", "(", "typeof", "attValue", "===", "\"undefined\"", ")", "{", "// code.section.attribs.init.push(`this.${attName} = args[${JSON.stringify(attName)}];`);", "code", ".", "section", ".", "attribs", ".", "init", ".", "push", "(", "`", "${", "attName", "}", "${", "JSON", ".", "stringify", "(", "attName", ")", "}", "`", ")", ";", "}", "else", "{", "code", ".", "functions", ".", "defVal", "=", "\"(args, attName, attValue) \"", "+", "\"{ return args[attName] === undefined ? attValue : args[attName]; }\"", ";", "// code.section.attribs.init.push( \"this.\" + attName + \" = defVal(args, \" +", "// JSON.stringify( attName ) + \", \" + JSON.stringify( attValue ) +", "// \");\" );", "code", ".", "section", ".", "attribs", ".", "init", ".", "push", "(", "`", "${", "attName", "}", "${", "attName", "}", "${", "JSON", ".", "stringify", "(", "attValue", ")", "}", "`", ")", ";", "}", "}", "catch", "(", "ex", ")", "{", "bubble", "(", "ex", ",", "`", "${", "attName", "}", "${", "JSON", ".", "stringify", "(", "attValue", ")", "}", "`", ")", ";", "}", "}" ]
Initialize attribute with a value. Priority to the value set in the contructor args.
[ "Initialize", "attribute", "with", "a", "value", ".", "Priority", "to", "the", "value", "set", "in", "the", "contructor", "args", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/boilerplate.view.js#L394-L415
52,096
tolokoban/ToloFrameWork
lib/boilerplate.view.js
buildViewAttribsInitFire
function buildViewAttribsInitFire( attName, code ) { try { code.section.attribs.init .push( `pm.fire("${attName}");` ); } catch ( ex ) { bubble( ex, `buildViewAttribsInitFire(${attName})` ); } }
javascript
function buildViewAttribsInitFire( attName, code ) { try { code.section.attribs.init .push( `pm.fire("${attName}");` ); } catch ( ex ) { bubble( ex, `buildViewAttribsInitFire(${attName})` ); } }
[ "function", "buildViewAttribsInitFire", "(", "attName", ",", "code", ")", "{", "try", "{", "code", ".", "section", ".", "attribs", ".", "init", ".", "push", "(", "`", "${", "attName", "}", "`", ")", ";", "}", "catch", "(", "ex", ")", "{", "bubble", "(", "ex", ",", "`", "${", "attName", "}", "`", ")", ";", "}", "}" ]
Once every attribute has been set, we must fire them. @param {[type]} attName [description] @param {[type]} code [description] @returns {undefined}
[ "Once", "every", "attribute", "has", "been", "set", "we", "must", "fire", "them", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/boilerplate.view.js#L424-L434
52,097
tolokoban/ToloFrameWork
lib/boilerplate.view.js
buildFunction
function buildFunction( def, code, varName ) { if ( isSpecial( def, "behind" ) ) { const behindFunctionName = def[ 1 ]; code.addNeededBehindFunction( behindFunctionName ); code.that = true; return [ "value => {", " try {", ` CODE_BEHIND${keySyntax(behindFunctionName)}.call(that, value, ${varName});`, " }", " catch( ex ) {", " console.error(`Exception in code behind \"" + behindFunctionName + "\" of module \"" + code.moduleName + "\": ${ex}`);", " }", "}" ]; } if ( isSpecial( def, "toggle" ) ) { const nameOfTheBooleanToToggle = def[ 1 ]; const namesOfTheBooleanToToggle = Array.isArray( nameOfTheBooleanToToggle ) ? nameOfTheBooleanToToggle : [ nameOfTheBooleanToToggle ]; const body = namesOfTheBooleanToToggle .map( name => `${getElemVarFromPath(name)} = !${getElemVarFromPath(name)};` ); return [ "() => {", body, "}" ]; } throw Error( `Function definition expected, but found ${JSON.stringify(def)}!` ); }
javascript
function buildFunction( def, code, varName ) { if ( isSpecial( def, "behind" ) ) { const behindFunctionName = def[ 1 ]; code.addNeededBehindFunction( behindFunctionName ); code.that = true; return [ "value => {", " try {", ` CODE_BEHIND${keySyntax(behindFunctionName)}.call(that, value, ${varName});`, " }", " catch( ex ) {", " console.error(`Exception in code behind \"" + behindFunctionName + "\" of module \"" + code.moduleName + "\": ${ex}`);", " }", "}" ]; } if ( isSpecial( def, "toggle" ) ) { const nameOfTheBooleanToToggle = def[ 1 ]; const namesOfTheBooleanToToggle = Array.isArray( nameOfTheBooleanToToggle ) ? nameOfTheBooleanToToggle : [ nameOfTheBooleanToToggle ]; const body = namesOfTheBooleanToToggle .map( name => `${getElemVarFromPath(name)} = !${getElemVarFromPath(name)};` ); return [ "() => {", body, "}" ]; } throw Error( `Function definition expected, but found ${JSON.stringify(def)}!` ); }
[ "function", "buildFunction", "(", "def", ",", "code", ",", "varName", ")", "{", "if", "(", "isSpecial", "(", "def", ",", "\"behind\"", ")", ")", "{", "const", "behindFunctionName", "=", "def", "[", "1", "]", ";", "code", ".", "addNeededBehindFunction", "(", "behindFunctionName", ")", ";", "code", ".", "that", "=", "true", ";", "return", "[", "\"value => {\"", ",", "\" try {\"", ",", "`", "${", "keySyntax", "(", "behindFunctionName", ")", "}", "${", "varName", "}", "`", ",", "\" }\"", ",", "\" catch( ex ) {\"", ",", "\" console.error(`Exception in code behind \\\"\"", "+", "behindFunctionName", "+", "\"\\\" of module \\\"\"", "+", "code", ".", "moduleName", "+", "\"\\\": ${ex}`);\"", ",", "\" }\"", ",", "\"}\"", "]", ";", "}", "if", "(", "isSpecial", "(", "def", ",", "\"toggle\"", ")", ")", "{", "const", "nameOfTheBooleanToToggle", "=", "def", "[", "1", "]", ";", "const", "namesOfTheBooleanToToggle", "=", "Array", ".", "isArray", "(", "nameOfTheBooleanToToggle", ")", "?", "nameOfTheBooleanToToggle", ":", "[", "nameOfTheBooleanToToggle", "]", ";", "const", "body", "=", "namesOfTheBooleanToToggle", ".", "map", "(", "name", "=>", "`", "${", "getElemVarFromPath", "(", "name", ")", "}", "${", "getElemVarFromPath", "(", "name", ")", "}", "`", ")", ";", "return", "[", "\"() => {\"", ",", "body", ",", "\"}\"", "]", ";", "}", "throw", "Error", "(", "`", "${", "JSON", ".", "stringify", "(", "def", ")", "}", "`", ")", ";", "}" ]
Create the code for a function. @example {Behind onVarChanged} {Toggle show-menu} @param {object} def - Function definition. @param {object} code - Needed for `code.section.ons`. @param {string} varName - Name of the object owning the attribute we want to listen on. @return {array} Resulting code as an array.
[ "Create", "the", "code", "for", "a", "function", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/boilerplate.view.js#L820-L853
52,098
tolokoban/ToloFrameWork
lib/boilerplate.view.js
extractAttribs
function extractAttribs( def ) { var key, val, attribs = { standard: {}, special: {}, implicit: [] }; for ( key in def ) { val = def[ key ]; if ( RX_INTEGER.test( key ) ) { attribs.implicit.push( val ); } else if ( RX_STD_ATT.test( key ) ) { attribs.standard[ key ] = val; } else { attribs.special[ key ] = val; } } return attribs; }
javascript
function extractAttribs( def ) { var key, val, attribs = { standard: {}, special: {}, implicit: [] }; for ( key in def ) { val = def[ key ]; if ( RX_INTEGER.test( key ) ) { attribs.implicit.push( val ); } else if ( RX_STD_ATT.test( key ) ) { attribs.standard[ key ] = val; } else { attribs.special[ key ] = val; } } return attribs; }
[ "function", "extractAttribs", "(", "def", ")", "{", "var", "key", ",", "val", ",", "attribs", "=", "{", "standard", ":", "{", "}", ",", "special", ":", "{", "}", ",", "implicit", ":", "[", "]", "}", ";", "for", "(", "key", "in", "def", ")", "{", "val", "=", "def", "[", "key", "]", ";", "if", "(", "RX_INTEGER", ".", "test", "(", "key", ")", ")", "{", "attribs", ".", "implicit", ".", "push", "(", "val", ")", ";", "}", "else", "if", "(", "RX_STD_ATT", ".", "test", "(", "key", ")", ")", "{", "attribs", ".", "standard", "[", "key", "]", "=", "val", ";", "}", "else", "{", "attribs", ".", "special", "[", "key", "]", "=", "val", ";", "}", "}", "return", "attribs", ";", "}" ]
An attribute is marked as _special_ as soon as it has a dot in its name. `view.attribs` is special, but `attribs` is not. Attributes with a numeric key are marked as _implicit_. @return `{ standard: {...}, special: {...}, implicit: [...] }`.
[ "An", "attribute", "is", "marked", "as", "_special_", "as", "soon", "as", "it", "has", "a", "dot", "in", "its", "name", ".", "view", ".", "attribs", "is", "special", "but", "attribs", "is", "not", ".", "Attributes", "with", "a", "numeric", "key", "are", "marked", "as", "_implicit_", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/boilerplate.view.js#L1119-L1132
52,099
tolokoban/ToloFrameWork
lib/boilerplate.view.js
declareRootElement
function declareRootElement( def, code ) { const rootElementName = buildElement( def, code ); code.section.elements.define.push( "//-----------------------" ); code.section.elements.define.push( "// Declare root element." ); code.section.elements.define.push( "Object.defineProperty( this, '$', {", [ `value: ${rootElementName}.$,`, "writable: false, ", "enumerable: false, ", "configurable: false" ], "});" ); }
javascript
function declareRootElement( def, code ) { const rootElementName = buildElement( def, code ); code.section.elements.define.push( "//-----------------------" ); code.section.elements.define.push( "// Declare root element." ); code.section.elements.define.push( "Object.defineProperty( this, '$', {", [ `value: ${rootElementName}.$,`, "writable: false, ", "enumerable: false, ", "configurable: false" ], "});" ); }
[ "function", "declareRootElement", "(", "def", ",", "code", ")", "{", "const", "rootElementName", "=", "buildElement", "(", "def", ",", "code", ")", ";", "code", ".", "section", ".", "elements", ".", "define", ".", "push", "(", "\"//-----------------------\"", ")", ";", "code", ".", "section", ".", "elements", ".", "define", ".", "push", "(", "\"// Declare root element.\"", ")", ";", "code", ".", "section", ".", "elements", ".", "define", ".", "push", "(", "\"Object.defineProperty( this, '$', {\"", ",", "[", "`", "${", "rootElementName", "}", "`", ",", "\"writable: false, \"", ",", "\"enumerable: false, \"", ",", "\"configurable: false\"", "]", ",", "\"});\"", ")", ";", "}" ]
Javascript for for root variable declaration. @param {object} def - `{View ...}` @param {Template} code - Helper to write the Javascript code. @return {undefined}
[ "Javascript", "for", "for", "root", "variable", "declaration", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/boilerplate.view.js#L1435-L1450