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 list | docstring stringlengths 4 11.8k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 86 226 |
|---|---|---|---|---|---|---|---|---|---|---|---|
34,200 | fibo/dflow | src/engine/inject/numbers.js | inject | function inject (taskKey) {
var taskName = task[taskKey]
var num = parseFloat(taskName)
if (!isNaN(num)) {
funcs[taskName] = function () { return num }
}
} | javascript | function inject (taskKey) {
var taskName = task[taskKey]
var num = parseFloat(taskName)
if (!isNaN(num)) {
funcs[taskName] = function () { return num }
}
} | [
"function",
"inject",
"(",
"taskKey",
")",
"{",
"var",
"taskName",
"=",
"task",
"[",
"taskKey",
"]",
"var",
"num",
"=",
"parseFloat",
"(",
"taskName",
")",
"if",
"(",
"!",
"isNaN",
"(",
"num",
")",
")",
"{",
"funcs",
"[",
"taskName",
"]",
"=",
"fun... | Inject a function that returns a number. | [
"Inject",
"a",
"function",
"that",
"returns",
"a",
"number",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/numbers.js#L13-L21 |
34,201 | OADA/oada-formats | model.js | Model | function Model(schema, examples, options) {
options = options || {};
this._schema = schema || null;
this._examples = examples || {};
this._additionalValidators = options.additionalValidators || [];
this.debugConstructor = options.debug || debug;
this.debug = this.debugConstructor(this.debugTopic || 'oada:model');
this.errorConstructor = options.error || debug;
this.error = this.errorConstructor(this.errorTopic || 'oada:model:error');
} | javascript | function Model(schema, examples, options) {
options = options || {};
this._schema = schema || null;
this._examples = examples || {};
this._additionalValidators = options.additionalValidators || [];
this.debugConstructor = options.debug || debug;
this.debug = this.debugConstructor(this.debugTopic || 'oada:model');
this.errorConstructor = options.error || debug;
this.error = this.errorConstructor(this.errorTopic || 'oada:model:error');
} | [
"function",
"Model",
"(",
"schema",
",",
"examples",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"_schema",
"=",
"schema",
"||",
"null",
";",
"this",
".",
"_examples",
"=",
"examples",
"||",
"{",
"}",
";",
... | A format model. Contains _schema, _examples, and validation.
@constructor
@param {*} schema - A format _schema in what every form validate() needs
@param {Array<*>} examples - An array of _examples in native form
@param {function} options.addtionalValidators - An array of validating
functions.
@param {function} options.debug - A debug logger constructor
@param {function} options.error - A custom error logger constructor | [
"A",
"format",
"model",
".",
"Contains",
"_schema",
"_examples",
"and",
"validation",
"."
] | ac4b4ab496736c0803e00e1eaf98377d6b15058d | https://github.com/OADA/oada-formats/blob/ac4b4ab496736c0803e00e1eaf98377d6b15058d/model.js#L57-L68 |
34,202 | fibo/dflow | src/engine/inject/accessors.js | injectAccessors | function injectAccessors (funcs, graph) {
if (no(graph.data)) graph.data = {}
funcs['this.graph.data'] = function () { return graph.data }
/**
* Inject accessor.
*
* @param {String} taskKey
*/
function inject (taskKey) {
var accessorName = null
var taskName = graph.task[taskKey]
/**
* Accessor-like function.
*
* @param {*} data that JSON can serialize
*/
function accessor (data) {
// Behave like a setter if an argument is provided.
if (arguments.length === 1) {
var json = JSON.stringify(data)
if (no(json)) {
throw new Error('JSON do not serialize data:' + data)
}
graph.data[accessorName] = data
}
// Always behave also like a getter.
return graph.data[accessorName]
}
if (regexAccessor.test(taskName)) {
accessorName = taskName.substring(1)
funcs[taskName] = accessor
}
}
Object.keys(graph.task).forEach(inject)
} | javascript | function injectAccessors (funcs, graph) {
if (no(graph.data)) graph.data = {}
funcs['this.graph.data'] = function () { return graph.data }
/**
* Inject accessor.
*
* @param {String} taskKey
*/
function inject (taskKey) {
var accessorName = null
var taskName = graph.task[taskKey]
/**
* Accessor-like function.
*
* @param {*} data that JSON can serialize
*/
function accessor (data) {
// Behave like a setter if an argument is provided.
if (arguments.length === 1) {
var json = JSON.stringify(data)
if (no(json)) {
throw new Error('JSON do not serialize data:' + data)
}
graph.data[accessorName] = data
}
// Always behave also like a getter.
return graph.data[accessorName]
}
if (regexAccessor.test(taskName)) {
accessorName = taskName.substring(1)
funcs[taskName] = accessor
}
}
Object.keys(graph.task).forEach(inject)
} | [
"function",
"injectAccessors",
"(",
"funcs",
",",
"graph",
")",
"{",
"if",
"(",
"no",
"(",
"graph",
".",
"data",
")",
")",
"graph",
".",
"data",
"=",
"{",
"}",
"funcs",
"[",
"'this.graph.data'",
"]",
"=",
"function",
"(",
")",
"{",
"return",
"graph",... | Inject functions to set or get graph data.
@param {Object} funcs reference
@param {Object} graph | [
"Inject",
"functions",
"to",
"set",
"or",
"get",
"graph",
"data",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/accessors.js#L11-L56 |
34,203 | fibo/dflow | src/engine/inject/accessors.js | inject | function inject (taskKey) {
var accessorName = null
var taskName = graph.task[taskKey]
/**
* Accessor-like function.
*
* @param {*} data that JSON can serialize
*/
function accessor (data) {
// Behave like a setter if an argument is provided.
if (arguments.length === 1) {
var json = JSON.stringify(data)
if (no(json)) {
throw new Error('JSON do not serialize data:' + data)
}
graph.data[accessorName] = data
}
// Always behave also like a getter.
return graph.data[accessorName]
}
if (regexAccessor.test(taskName)) {
accessorName = taskName.substring(1)
funcs[taskName] = accessor
}
} | javascript | function inject (taskKey) {
var accessorName = null
var taskName = graph.task[taskKey]
/**
* Accessor-like function.
*
* @param {*} data that JSON can serialize
*/
function accessor (data) {
// Behave like a setter if an argument is provided.
if (arguments.length === 1) {
var json = JSON.stringify(data)
if (no(json)) {
throw new Error('JSON do not serialize data:' + data)
}
graph.data[accessorName] = data
}
// Always behave also like a getter.
return graph.data[accessorName]
}
if (regexAccessor.test(taskName)) {
accessorName = taskName.substring(1)
funcs[taskName] = accessor
}
} | [
"function",
"inject",
"(",
"taskKey",
")",
"{",
"var",
"accessorName",
"=",
"null",
"var",
"taskName",
"=",
"graph",
".",
"task",
"[",
"taskKey",
"]",
"/**\n * Accessor-like function.\n *\n * @param {*} data that JSON can serialize\n */",
"function",
"access... | Inject accessor.
@param {String} taskKey | [
"Inject",
"accessor",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/accessors.js#L22-L53 |
34,204 | fibo/dflow | src/engine/inject/accessors.js | accessor | function accessor (data) {
// Behave like a setter if an argument is provided.
if (arguments.length === 1) {
var json = JSON.stringify(data)
if (no(json)) {
throw new Error('JSON do not serialize data:' + data)
}
graph.data[accessorName] = data
}
// Always behave also like a getter.
return graph.data[accessorName]
} | javascript | function accessor (data) {
// Behave like a setter if an argument is provided.
if (arguments.length === 1) {
var json = JSON.stringify(data)
if (no(json)) {
throw new Error('JSON do not serialize data:' + data)
}
graph.data[accessorName] = data
}
// Always behave also like a getter.
return graph.data[accessorName]
} | [
"function",
"accessor",
"(",
"data",
")",
"{",
"// Behave like a setter if an argument is provided.",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"var",
"json",
"=",
"JSON",
".",
"stringify",
"(",
"data",
")",
"if",
"(",
"no",
"(",
"json",
... | Accessor-like function.
@param {*} data that JSON can serialize | [
"Accessor",
"-",
"like",
"function",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/accessors.js#L32-L46 |
34,205 | fibo/dflow | src/engine/inject/dotOperators.js | injectDotOperators | function injectDotOperators (funcs, task) {
/**
* Inject dot operator.
*/
function inject (taskKey) {
var taskName = task[taskKey]
/**
* Dot operator function.
*
* @param {String} attributeName
* @param {Object} obj
* @param {...} rest of arguments
*
* @returns {*} result
*/
function dotOperatorFunc (attributeName, obj) {
var func
if (obj) func = obj[attributeName]
if (typeof func === 'function') {
return func.apply(obj, Array.prototype.slice.call(arguments, 2))
}
}
if (regexDotOperator.func.test(taskName)) {
// .foo() -> foo
funcs[taskName] = dotOperatorFunc.bind(null, taskName.substring(1, taskName.length - 2))
}
/**
* Dot operator attribute write.
*
* @param {String} attributeName
* @param {Object} obj
* @param {*} attributeValue
*
* @returns {Object} obj modified
*/
function dotOperatorAttributeWrite (attributeName, obj, attributeValue) {
obj[attributeName] = attributeValue
return obj
}
if (regexDotOperator.attrWrite.test(taskName)) {
// .foo= -> foo
funcs[taskName] = dotOperatorAttributeWrite.bind(null, taskName.substring(1, taskName.length - 1))
}
/**
* Dot operator attribute read.
*
* @param {String} attributeName
* @param {Object} obj
*
* @returns {*} attribute
*/
function dotOperatorAttributeRead (attributeName, obj) {
var attr
if (obj) attr = obj[attributeName]
if (typeof attr === 'function') return attr.bind(obj)
return attr
}
if (regexDotOperator.attrRead.test(taskName)) {
// .foo -> foo
funcs[taskName] = dotOperatorAttributeRead.bind(null, taskName.substring(1))
}
}
Object.keys(task).forEach(inject)
} | javascript | function injectDotOperators (funcs, task) {
/**
* Inject dot operator.
*/
function inject (taskKey) {
var taskName = task[taskKey]
/**
* Dot operator function.
*
* @param {String} attributeName
* @param {Object} obj
* @param {...} rest of arguments
*
* @returns {*} result
*/
function dotOperatorFunc (attributeName, obj) {
var func
if (obj) func = obj[attributeName]
if (typeof func === 'function') {
return func.apply(obj, Array.prototype.slice.call(arguments, 2))
}
}
if (regexDotOperator.func.test(taskName)) {
// .foo() -> foo
funcs[taskName] = dotOperatorFunc.bind(null, taskName.substring(1, taskName.length - 2))
}
/**
* Dot operator attribute write.
*
* @param {String} attributeName
* @param {Object} obj
* @param {*} attributeValue
*
* @returns {Object} obj modified
*/
function dotOperatorAttributeWrite (attributeName, obj, attributeValue) {
obj[attributeName] = attributeValue
return obj
}
if (regexDotOperator.attrWrite.test(taskName)) {
// .foo= -> foo
funcs[taskName] = dotOperatorAttributeWrite.bind(null, taskName.substring(1, taskName.length - 1))
}
/**
* Dot operator attribute read.
*
* @param {String} attributeName
* @param {Object} obj
*
* @returns {*} attribute
*/
function dotOperatorAttributeRead (attributeName, obj) {
var attr
if (obj) attr = obj[attributeName]
if (typeof attr === 'function') return attr.bind(obj)
return attr
}
if (regexDotOperator.attrRead.test(taskName)) {
// .foo -> foo
funcs[taskName] = dotOperatorAttributeRead.bind(null, taskName.substring(1))
}
}
Object.keys(task).forEach(inject)
} | [
"function",
"injectDotOperators",
"(",
"funcs",
",",
"task",
")",
"{",
"/**\n * Inject dot operator.\n */",
"function",
"inject",
"(",
"taskKey",
")",
"{",
"var",
"taskName",
"=",
"task",
"[",
"taskKey",
"]",
"/**\n * Dot operator function.\n *\n * @param ... | Inject functions that emulate dot operator.
@param {Object} funcs reference
@param {Object} task | [
"Inject",
"functions",
"that",
"emulate",
"dot",
"operator",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/dotOperators.js#L10-L90 |
34,206 | fibo/dflow | src/engine/inject/dotOperators.js | dotOperatorFunc | function dotOperatorFunc (attributeName, obj) {
var func
if (obj) func = obj[attributeName]
if (typeof func === 'function') {
return func.apply(obj, Array.prototype.slice.call(arguments, 2))
}
} | javascript | function dotOperatorFunc (attributeName, obj) {
var func
if (obj) func = obj[attributeName]
if (typeof func === 'function') {
return func.apply(obj, Array.prototype.slice.call(arguments, 2))
}
} | [
"function",
"dotOperatorFunc",
"(",
"attributeName",
",",
"obj",
")",
"{",
"var",
"func",
"if",
"(",
"obj",
")",
"func",
"=",
"obj",
"[",
"attributeName",
"]",
"if",
"(",
"typeof",
"func",
"===",
"'function'",
")",
"{",
"return",
"func",
".",
"apply",
... | Dot operator function.
@param {String} attributeName
@param {Object} obj
@param {...} rest of arguments
@returns {*} result | [
"Dot",
"operator",
"function",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/dotOperators.js#L28-L36 |
34,207 | fibo/dflow | src/engine/inject/dotOperators.js | dotOperatorAttributeRead | function dotOperatorAttributeRead (attributeName, obj) {
var attr
if (obj) attr = obj[attributeName]
if (typeof attr === 'function') return attr.bind(obj)
return attr
} | javascript | function dotOperatorAttributeRead (attributeName, obj) {
var attr
if (obj) attr = obj[attributeName]
if (typeof attr === 'function') return attr.bind(obj)
return attr
} | [
"function",
"dotOperatorAttributeRead",
"(",
"attributeName",
",",
"obj",
")",
"{",
"var",
"attr",
"if",
"(",
"obj",
")",
"attr",
"=",
"obj",
"[",
"attributeName",
"]",
"if",
"(",
"typeof",
"attr",
"===",
"'function'",
")",
"return",
"attr",
".",
"bind",
... | Dot operator attribute read.
@param {String} attributeName
@param {Object} obj
@returns {*} attribute | [
"Dot",
"operator",
"attribute",
"read",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/dotOperators.js#L73-L81 |
34,208 | quantmind/d3-view | src/forms/responses.js | defaultResponse | function defaultResponse(response) {
var level =
response.status < 300
? "info"
: response.status < 500
? "warning"
: "error";
this.$emit("formMessage", {
level: level,
data: response.data,
response: response
});
} | javascript | function defaultResponse(response) {
var level =
response.status < 300
? "info"
: response.status < 500
? "warning"
: "error";
this.$emit("formMessage", {
level: level,
data: response.data,
response: response
});
} | [
"function",
"defaultResponse",
"(",
"response",
")",
"{",
"var",
"level",
"=",
"response",
".",
"status",
"<",
"300",
"?",
"\"info\"",
":",
"response",
".",
"status",
"<",
"500",
"?",
"\"warning\"",
":",
"\"error\"",
";",
"this",
".",
"$emit",
"(",
"\"fo... | The default response emit a formMessage to event to parent models | [
"The",
"default",
"response",
"emit",
"a",
"formMessage",
"to",
"event",
"to",
"parent",
"models"
] | 014e8233fd3beacc454f63c8c054405e2506ae8e | https://github.com/quantmind/d3-view/blob/014e8233fd3beacc454f63c8c054405e2506ae8e/src/forms/responses.js#L18-L30 |
34,209 | fehmer/adafruit-i2c-lcd | example/demo.js | displayButton | function displayButton(state, button) {
lcd.clear();
lcd.message('Button: ' + lcd.buttonName(button) + '\nState: ' + state);
console.log(state, lcd.buttonName(button));
} | javascript | function displayButton(state, button) {
lcd.clear();
lcd.message('Button: ' + lcd.buttonName(button) + '\nState: ' + state);
console.log(state, lcd.buttonName(button));
} | [
"function",
"displayButton",
"(",
"state",
",",
"button",
")",
"{",
"lcd",
".",
"clear",
"(",
")",
";",
"lcd",
".",
"message",
"(",
"'Button: '",
"+",
"lcd",
".",
"buttonName",
"(",
"button",
")",
"+",
"'\\nState: '",
"+",
"state",
")",
";",
"console",... | show button state on lcd and console | [
"show",
"button",
"state",
"on",
"lcd",
"and",
"console"
] | 9b39cf701ac7ac3b2feb3b7fea588e40c166542f | https://github.com/fehmer/adafruit-i2c-lcd/blob/9b39cf701ac7ac3b2feb3b7fea588e40c166542f/example/demo.js#L45-L49 |
34,210 | OADA/oada-formats | lib/vocab.js | function (values) {
// first assume ret is already object with 'known':
var ret = values;
// if it's an array, replace with object that has 'known':
if (_.isArray(values)) { ret = { known: values }; }
// Make sure it has a type:
if (!ret.type) { ret.type = 'string' };
// Add enum if running in strict mode:
if (config.get('strict')) {
ret.enum = ret.known;
}
return ret;
} | javascript | function (values) {
// first assume ret is already object with 'known':
var ret = values;
// if it's an array, replace with object that has 'known':
if (_.isArray(values)) { ret = { known: values }; }
// Make sure it has a type:
if (!ret.type) { ret.type = 'string' };
// Add enum if running in strict mode:
if (config.get('strict')) {
ret.enum = ret.known;
}
return ret;
} | [
"function",
"(",
"values",
")",
"{",
"// first assume ret is already object with 'known':",
"var",
"ret",
"=",
"values",
";",
"// if it's an array, replace with object that has 'known':",
"if",
"(",
"_",
".",
"isArray",
"(",
"values",
")",
")",
"{",
"ret",
"=",
"{",
... | enumSchema checks the global config for strictness. If not strict, returns a schema that matches a string. If strict, returns a schema that matches a string which can only be the known set of values. Also includes a custom key called 'known' which records the original set of known values regardless of the config setting. The parameter to enumSchema can be either an array, or an object which at least contains a 'known' key. | [
"enumSchema",
"checks",
"the",
"global",
"config",
"for",
"strictness",
".",
"If",
"not",
"strict",
"returns",
"a",
"schema",
"that",
"matches",
"a",
"string",
".",
"If",
"strict",
"returns",
"a",
"schema",
"that",
"matches",
"a",
"string",
"which",
"can",
... | ac4b4ab496736c0803e00e1eaf98377d6b15058d | https://github.com/OADA/oada-formats/blob/ac4b4ab496736c0803e00e1eaf98377d6b15058d/lib/vocab.js#L30-L42 | |
34,211 | fibo/dflow | src/engine/evalTasks.js | evalTasks | function evalTasks (funcs, task) {
/**
* Evaluate a single task and inject it.
*
* @param {String} taskKey
*/
function inject (taskKey) {
var taskName = task[taskKey]
try {
var e = eval(taskName) // eslint-disable-line
if (typeof e === 'function') {
funcs[taskName] = e
} else {
funcs[taskName] = function () { return e }
}
} catch (err) {
var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' + err
throw new Error(msg)
}
}
Object.keys(task)
.filter(reserved(task))
.filter(dflowDSL(task))
.filter(alreadyDefined(funcs, task))
.forEach(inject)
} | javascript | function evalTasks (funcs, task) {
/**
* Evaluate a single task and inject it.
*
* @param {String} taskKey
*/
function inject (taskKey) {
var taskName = task[taskKey]
try {
var e = eval(taskName) // eslint-disable-line
if (typeof e === 'function') {
funcs[taskName] = e
} else {
funcs[taskName] = function () { return e }
}
} catch (err) {
var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' + err
throw new Error(msg)
}
}
Object.keys(task)
.filter(reserved(task))
.filter(dflowDSL(task))
.filter(alreadyDefined(funcs, task))
.forEach(inject)
} | [
"function",
"evalTasks",
"(",
"funcs",
",",
"task",
")",
"{",
"/**\n * Evaluate a single task and inject it.\n *\n * @param {String} taskKey\n */",
"function",
"inject",
"(",
"taskKey",
")",
"{",
"var",
"taskName",
"=",
"task",
"[",
"taskKey",
"]",
"try",
"{",
"va... | Inject evaluated tasks to functions.
@param {Object} funcs reference
@param {Object} task | [
"Inject",
"evaluated",
"tasks",
"to",
"functions",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/evalTasks.js#L32-L61 |
34,212 | fibo/dflow | src/engine/evalTasks.js | inject | function inject (taskKey) {
var taskName = task[taskKey]
try {
var e = eval(taskName) // eslint-disable-line
if (typeof e === 'function') {
funcs[taskName] = e
} else {
funcs[taskName] = function () { return e }
}
} catch (err) {
var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' + err
throw new Error(msg)
}
} | javascript | function inject (taskKey) {
var taskName = task[taskKey]
try {
var e = eval(taskName) // eslint-disable-line
if (typeof e === 'function') {
funcs[taskName] = e
} else {
funcs[taskName] = function () { return e }
}
} catch (err) {
var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' + err
throw new Error(msg)
}
} | [
"function",
"inject",
"(",
"taskKey",
")",
"{",
"var",
"taskName",
"=",
"task",
"[",
"taskKey",
"]",
"try",
"{",
"var",
"e",
"=",
"eval",
"(",
"taskName",
")",
"// eslint-disable-line",
"if",
"(",
"typeof",
"e",
"===",
"'function'",
")",
"{",
"funcs",
... | Evaluate a single task and inject it.
@param {String} taskKey | [
"Evaluate",
"a",
"single",
"task",
"and",
"inject",
"it",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/evalTasks.js#L39-L54 |
34,213 | OADA/oada-formats | lib/schema-util.js | addVocabAsProperties | function addVocabAsProperties(schema, terms_array) {
if (!schema.properties) schema.properties = {};
var propertySchema = schema.propertySchema || {};
_.each(terms_array, function(term) {
schema.properties[term] = vocab(term)
if (propertySchema) {
if (propertySchema.known) {
propertySchema.known.push(term);
}
if (propertySchema.enum) {
propertySchema.enum.push(term);
}
}
});
} | javascript | function addVocabAsProperties(schema, terms_array) {
if (!schema.properties) schema.properties = {};
var propertySchema = schema.propertySchema || {};
_.each(terms_array, function(term) {
schema.properties[term] = vocab(term)
if (propertySchema) {
if (propertySchema.known) {
propertySchema.known.push(term);
}
if (propertySchema.enum) {
propertySchema.enum.push(term);
}
}
});
} | [
"function",
"addVocabAsProperties",
"(",
"schema",
",",
"terms_array",
")",
"{",
"if",
"(",
"!",
"schema",
".",
"properties",
")",
"schema",
".",
"properties",
"=",
"{",
"}",
";",
"var",
"propertySchema",
"=",
"schema",
".",
"propertySchema",
"||",
"{",
"}... | addVocab adds a set of vocab terms as valid properties on a schema. Updates propertySchema if it's a simple single enumSchema | [
"addVocab",
"adds",
"a",
"set",
"of",
"vocab",
"terms",
"as",
"valid",
"properties",
"on",
"a",
"schema",
".",
"Updates",
"propertySchema",
"if",
"it",
"s",
"a",
"simple",
"single",
"enumSchema"
] | ac4b4ab496736c0803e00e1eaf98377d6b15058d | https://github.com/OADA/oada-formats/blob/ac4b4ab496736c0803e00e1eaf98377d6b15058d/lib/schema-util.js#L89-L103 |
34,214 | OADA/oada-formats | lib/schema-util.js | recursivelyChangeAllAdditionalProperties | function recursivelyChangeAllAdditionalProperties(schema, newvalue) {
if (!schema) return;
// First set additionalProperties if it's here:
if (typeof schema.additionalProperties !== 'undefined') {
schema.additionalProperties = newvalue;
}
// Then check any child properties for the same:
_.each(_.keys(schema.properties), function(child_schema) {
recursivelyChangeAllAdditionalProperties(child_schema, newvalue);
});
// Then check any child patternProperties for the same:
_.each(_.keys(schema.patternProperties), function(child_schema) {
recursivelyChangeAllAdditionalProperties(child_schema, newvalue);
});
// Then check for anyOf, allOf, oneOf
_.each(schema.anyOf, function(child_schema) {
recursivelyChangeAllAdditionalProperties(child_schema, newvalue);
});
_.each(schema.allOf, function(child_schema) {
recursivelyChangeAllAdditionalProperties(child_schema, newvalue);
});
_.each(schema.oneOf, function(child_schema) {
recursivelyChangeAllAdditionalProperties(child_schema, newvalue);
});
// ignoring 'not' for now
} | javascript | function recursivelyChangeAllAdditionalProperties(schema, newvalue) {
if (!schema) return;
// First set additionalProperties if it's here:
if (typeof schema.additionalProperties !== 'undefined') {
schema.additionalProperties = newvalue;
}
// Then check any child properties for the same:
_.each(_.keys(schema.properties), function(child_schema) {
recursivelyChangeAllAdditionalProperties(child_schema, newvalue);
});
// Then check any child patternProperties for the same:
_.each(_.keys(schema.patternProperties), function(child_schema) {
recursivelyChangeAllAdditionalProperties(child_schema, newvalue);
});
// Then check for anyOf, allOf, oneOf
_.each(schema.anyOf, function(child_schema) {
recursivelyChangeAllAdditionalProperties(child_schema, newvalue);
});
_.each(schema.allOf, function(child_schema) {
recursivelyChangeAllAdditionalProperties(child_schema, newvalue);
});
_.each(schema.oneOf, function(child_schema) {
recursivelyChangeAllAdditionalProperties(child_schema, newvalue);
});
// ignoring 'not' for now
} | [
"function",
"recursivelyChangeAllAdditionalProperties",
"(",
"schema",
",",
"newvalue",
")",
"{",
"if",
"(",
"!",
"schema",
")",
"return",
";",
"// First set additionalProperties if it's here:",
"if",
"(",
"typeof",
"schema",
".",
"additionalProperties",
"!==",
"'undefi... | recursivelyChangeAllAdditionalProperties is used when "strict" mode is turned on to set all the additionalProperties variables to false. Use only for developer testing to ensure you didn't mispell things because that is not the true definition of these schemas. Note this mutates the schema passed. | [
"recursivelyChangeAllAdditionalProperties",
"is",
"used",
"when",
"strict",
"mode",
"is",
"turned",
"on",
"to",
"set",
"all",
"the",
"additionalProperties",
"variables",
"to",
"false",
".",
"Use",
"only",
"for",
"developer",
"testing",
"to",
"ensure",
"you",
"didn... | ac4b4ab496736c0803e00e1eaf98377d6b15058d | https://github.com/OADA/oada-formats/blob/ac4b4ab496736c0803e00e1eaf98377d6b15058d/lib/schema-util.js#L181-L206 |
34,215 | fibo/dflow | src/engine/inputPipes.js | inputPipes | function inputPipes (pipe, taskKey) {
var pipes = []
function pushPipe (key) {
pipes.push(pipe[key])
}
function ifIsInputPipe (key) {
return pipe[key][1] === taskKey
}
Object.keys(pipe).filter(ifIsInputPipe).forEach(pushPipe)
return pipes
} | javascript | function inputPipes (pipe, taskKey) {
var pipes = []
function pushPipe (key) {
pipes.push(pipe[key])
}
function ifIsInputPipe (key) {
return pipe[key][1] === taskKey
}
Object.keys(pipe).filter(ifIsInputPipe).forEach(pushPipe)
return pipes
} | [
"function",
"inputPipes",
"(",
"pipe",
",",
"taskKey",
")",
"{",
"var",
"pipes",
"=",
"[",
"]",
"function",
"pushPipe",
"(",
"key",
")",
"{",
"pipes",
".",
"push",
"(",
"pipe",
"[",
"key",
"]",
")",
"}",
"function",
"ifIsInputPipe",
"(",
"key",
")",
... | Compute pipes that feed a task.
@param {Object} pipe
@param {String} taskKey
@returns {Array} pipes | [
"Compute",
"pipes",
"that",
"feed",
"a",
"task",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inputPipes.js#L10-L24 |
34,216 | byCedric/semantic-release-git-branches | lib/git.js | getModifiedFiles | async function getModifiedFiles() {
return (await execa.stdout('git', ['ls-files', '-m', '-o', '--exclude-standard']))
.split('\n')
.map(tag => tag.trim())
.filter(tag => Boolean(tag));
} | javascript | async function getModifiedFiles() {
return (await execa.stdout('git', ['ls-files', '-m', '-o', '--exclude-standard']))
.split('\n')
.map(tag => tag.trim())
.filter(tag => Boolean(tag));
} | [
"async",
"function",
"getModifiedFiles",
"(",
")",
"{",
"return",
"(",
"await",
"execa",
".",
"stdout",
"(",
"'git'",
",",
"[",
"'ls-files'",
",",
"'-m'",
",",
"'-o'",
",",
"'--exclude-standard'",
"]",
")",
")",
".",
"split",
"(",
"'\\n'",
")",
".",
"m... | Retrieve the list of files modified on the local repository.
@return {Array<String>} Array of modified files path. | [
"Retrieve",
"the",
"list",
"of",
"files",
"modified",
"on",
"the",
"local",
"repository",
"."
] | 199337210d7dd21d9cd8442604ef9e063ef69dc2 | https://github.com/byCedric/semantic-release-git-branches/blob/199337210d7dd21d9cd8442604ef9e063ef69dc2/lib/git.js#L9-L14 |
34,217 | fibo/dflow | src/engine/level.js | level | function level (pipe, cachedLevelOf, taskKey) {
var taskLevel = 0
var parentsOf = parents.bind(null, pipe)
if (typeof cachedLevelOf[taskKey] === 'number') {
return cachedLevelOf[taskKey]
}
function computeLevel (parentTaskKey) {
// ↓ Recursion here: the level of a task is the max level of its parents + 1.
taskLevel = Math.max(taskLevel, level(pipe, cachedLevelOf, parentTaskKey) + 1)
}
parentsOf(taskKey).forEach(computeLevel)
cachedLevelOf[taskKey] = taskLevel
return taskLevel
} | javascript | function level (pipe, cachedLevelOf, taskKey) {
var taskLevel = 0
var parentsOf = parents.bind(null, pipe)
if (typeof cachedLevelOf[taskKey] === 'number') {
return cachedLevelOf[taskKey]
}
function computeLevel (parentTaskKey) {
// ↓ Recursion here: the level of a task is the max level of its parents + 1.
taskLevel = Math.max(taskLevel, level(pipe, cachedLevelOf, parentTaskKey) + 1)
}
parentsOf(taskKey).forEach(computeLevel)
cachedLevelOf[taskKey] = taskLevel
return taskLevel
} | [
"function",
"level",
"(",
"pipe",
",",
"cachedLevelOf",
",",
"taskKey",
")",
"{",
"var",
"taskLevel",
"=",
"0",
"var",
"parentsOf",
"=",
"parents",
".",
"bind",
"(",
"null",
",",
"pipe",
")",
"if",
"(",
"typeof",
"cachedLevelOf",
"[",
"taskKey",
"]",
"... | Compute level of task.
@param {Object} pipe
@param {Object} cachedLevelOf
@param {String} taskKey
@returns {Number} taskLevel | [
"Compute",
"level",
"of",
"task",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/level.js#L13-L31 |
34,218 | fedecia/gmail-api-sync | index.js | function (callback) {
fs.readFile(clientSecretPath, function processClientSecrets(err, content) {
if (err) {
debug('Error loading client secret file: ' + err);
return callback(err);
} else {
credentials = JSON.parse(content);
return callback();
}
});
} | javascript | function (callback) {
fs.readFile(clientSecretPath, function processClientSecrets(err, content) {
if (err) {
debug('Error loading client secret file: ' + err);
return callback(err);
} else {
credentials = JSON.parse(content);
return callback();
}
});
} | [
"function",
"(",
"callback",
")",
"{",
"fs",
".",
"readFile",
"(",
"clientSecretPath",
",",
"function",
"processClientSecrets",
"(",
"err",
",",
"content",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"'Error loading client secret file: '",
"+",
"err",
... | Load client secrets from a local file. | [
"Load",
"client",
"secrets",
"from",
"a",
"local",
"file",
"."
] | c29bfda8735eaa6590d05f59e45d6301385a321c | https://github.com/fedecia/gmail-api-sync/blob/c29bfda8735eaa6590d05f59e45d6301385a321c/index.js#L23-L33 | |
34,219 | fibo/dflow | src/engine/isDflowFun.js | isDflowFun | function isDflowFun (f) {
var isFunction = typeof f === 'function'
var hasFuncsObject = typeof f.funcs === 'object'
var hasGraphObject = typeof f.graph === 'object'
var hasValidGraph = true
if (!isFunction || !hasFuncsObject || !hasGraphObject) return false
if (isFunction && hasGraphObject && hasFuncsObject) {
try {
validate(f.graph, f.funcs)
} catch (ignore) {
hasValidGraph = false
}
}
return hasValidGraph
} | javascript | function isDflowFun (f) {
var isFunction = typeof f === 'function'
var hasFuncsObject = typeof f.funcs === 'object'
var hasGraphObject = typeof f.graph === 'object'
var hasValidGraph = true
if (!isFunction || !hasFuncsObject || !hasGraphObject) return false
if (isFunction && hasGraphObject && hasFuncsObject) {
try {
validate(f.graph, f.funcs)
} catch (ignore) {
hasValidGraph = false
}
}
return hasValidGraph
} | [
"function",
"isDflowFun",
"(",
"f",
")",
"{",
"var",
"isFunction",
"=",
"typeof",
"f",
"===",
"'function'",
"var",
"hasFuncsObject",
"=",
"typeof",
"f",
".",
"funcs",
"===",
"'object'",
"var",
"hasGraphObject",
"=",
"typeof",
"f",
".",
"graph",
"===",
"'ob... | Duct tape for dflow functions.
@param {Function} f
@returns {Boolean} ok, it looks like a dflowFun | [
"Duct",
"tape",
"for",
"dflow",
"functions",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/isDflowFun.js#L11-L28 |
34,220 | OADA/oada-formats | formats.js | Formats | function Formats(options) {
options = options || {};
this.debugConstructor = options.debug || debug;
this.debug = this.debugConstructor('oada:formats');
this.errorConstructor = options.error || debug;
this.error = this.errorConstructor('oada:formats:error');
this.Model = Model;
this.models = {};
this.mediatypes = {};
// Add the built in models
this.use(require('./JsonModel'));
// Add the built in media types
this.use(require('./formats/index.js'));
} | javascript | function Formats(options) {
options = options || {};
this.debugConstructor = options.debug || debug;
this.debug = this.debugConstructor('oada:formats');
this.errorConstructor = options.error || debug;
this.error = this.errorConstructor('oada:formats:error');
this.Model = Model;
this.models = {};
this.mediatypes = {};
// Add the built in models
this.use(require('./JsonModel'));
// Add the built in media types
this.use(require('./formats/index.js'));
} | [
"function",
"Formats",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"debugConstructor",
"=",
"options",
".",
"debug",
"||",
"debug",
";",
"this",
".",
"debug",
"=",
"this",
".",
"debugConstructor",
"(",
"'oada:fo... | Maintains and builds OADA format models
@constructor
@param {object} options - Various optional options
@param {function} options.debug - A custom debug logger, debug.js interface
@param {function} options.error - A custom error logger, debug.js interface | [
"Maintains",
"and",
"builds",
"OADA",
"format",
"models"
] | ac4b4ab496736c0803e00e1eaf98377d6b15058d | https://github.com/OADA/oada-formats/blob/ac4b4ab496736c0803e00e1eaf98377d6b15058d/formats.js#L43-L61 |
34,221 | fibo/dflow | src/engine/inputArgs.js | inputArgs | function inputArgs (outs, pipe, taskKey) {
var args = []
var inputPipesOf = inputPipes.bind(null, pipe)
function populateArg (inputPipe) {
var index = inputPipe[2] || 0
var value = outs[inputPipe[0]]
args[index] = value
}
inputPipesOf(taskKey).forEach(populateArg)
return args
} | javascript | function inputArgs (outs, pipe, taskKey) {
var args = []
var inputPipesOf = inputPipes.bind(null, pipe)
function populateArg (inputPipe) {
var index = inputPipe[2] || 0
var value = outs[inputPipe[0]]
args[index] = value
}
inputPipesOf(taskKey).forEach(populateArg)
return args
} | [
"function",
"inputArgs",
"(",
"outs",
",",
"pipe",
",",
"taskKey",
")",
"{",
"var",
"args",
"=",
"[",
"]",
"var",
"inputPipesOf",
"=",
"inputPipes",
".",
"bind",
"(",
"null",
",",
"pipe",
")",
"function",
"populateArg",
"(",
"inputPipe",
")",
"{",
"var... | Retrieve input arguments of a task.
@param {Object} outs
@param {Object} pipe
@param {String} taskKey
@returns {Array} args | [
"Retrieve",
"input",
"arguments",
"of",
"a",
"task",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inputArgs.js#L13-L27 |
34,222 | mojitoholic/pauldron | pauldron-policy/SimplePolicyDecisionCombinerEngine.js | evaluate | function evaluate(request, policies, engines) {
const decisions = policies.map((policy) => (
engines[policy.type].evaluate(request, policy)
));
return combineDecisionsDenyOverrides(decisions);
} | javascript | function evaluate(request, policies, engines) {
const decisions = policies.map((policy) => (
engines[policy.type].evaluate(request, policy)
));
return combineDecisionsDenyOverrides(decisions);
} | [
"function",
"evaluate",
"(",
"request",
",",
"policies",
",",
"engines",
")",
"{",
"const",
"decisions",
"=",
"policies",
".",
"map",
"(",
"(",
"policy",
")",
"=>",
"(",
"engines",
"[",
"policy",
".",
"type",
"]",
".",
"evaluate",
"(",
"request",
",",
... | deny-override | [
"deny",
"-",
"override"
] | ec5acc53be9ae75436ef46cef6dddd8f088732a3 | https://github.com/mojitoholic/pauldron/blob/ec5acc53be9ae75436ef46cef6dddd8f088732a3/pauldron-policy/SimplePolicyDecisionCombinerEngine.js#L31-L36 |
34,223 | retextjs/retext-emoji | index.js | toGemoji | function toGemoji(node) {
var value = toString(node)
var info = (unicodes[value] || emoticons[value] || {}).shortcode
if (info) {
node.value = info
}
} | javascript | function toGemoji(node) {
var value = toString(node)
var info = (unicodes[value] || emoticons[value] || {}).shortcode
if (info) {
node.value = info
}
} | [
"function",
"toGemoji",
"(",
"node",
")",
"{",
"var",
"value",
"=",
"toString",
"(",
"node",
")",
"var",
"info",
"=",
"(",
"unicodes",
"[",
"value",
"]",
"||",
"emoticons",
"[",
"value",
"]",
"||",
"{",
"}",
")",
".",
"shortcode",
"if",
"(",
"info"... | Replace a unicode emoji with a short-code. | [
"Replace",
"a",
"unicode",
"emoji",
"with",
"a",
"short",
"-",
"code",
"."
] | 2edeea12f59bed2b0cb29acbf93bfb29fd8b1b1e | https://github.com/retextjs/retext-emoji/blob/2edeea12f59bed2b0cb29acbf93bfb29fd8b1b1e/index.js#L80-L87 |
34,224 | retextjs/retext-emoji | index.js | toEmoji | function toEmoji(node) {
var value = toString(node)
var info = (shortcodes[value] || emoticons[value] || {}).emoji
if (info) {
node.value = info
}
} | javascript | function toEmoji(node) {
var value = toString(node)
var info = (shortcodes[value] || emoticons[value] || {}).emoji
if (info) {
node.value = info
}
} | [
"function",
"toEmoji",
"(",
"node",
")",
"{",
"var",
"value",
"=",
"toString",
"(",
"node",
")",
"var",
"info",
"=",
"(",
"shortcodes",
"[",
"value",
"]",
"||",
"emoticons",
"[",
"value",
"]",
"||",
"{",
"}",
")",
".",
"emoji",
"if",
"(",
"info",
... | Replace a short-code with a unicode emoji. | [
"Replace",
"a",
"short",
"-",
"code",
"with",
"a",
"unicode",
"emoji",
"."
] | 2edeea12f59bed2b0cb29acbf93bfb29fd8b1b1e | https://github.com/retextjs/retext-emoji/blob/2edeea12f59bed2b0cb29acbf93bfb29fd8b1b1e/index.js#L90-L97 |
34,225 | fabric8-ui/ngx-widgets | gulpfile.js | minifyTemplate | function minifyTemplate(file) {
try {
let minifiedFile = htmlMinifier.minify(file, {
collapseWhitespace: true,
caseSensitive: true,
removeComments: true
});
return minifiedFile;
} catch (err) {
console.log(err);
}
} | javascript | function minifyTemplate(file) {
try {
let minifiedFile = htmlMinifier.minify(file, {
collapseWhitespace: true,
caseSensitive: true,
removeComments: true
});
return minifiedFile;
} catch (err) {
console.log(err);
}
} | [
"function",
"minifyTemplate",
"(",
"file",
")",
"{",
"try",
"{",
"let",
"minifiedFile",
"=",
"htmlMinifier",
".",
"minify",
"(",
"file",
",",
"{",
"collapseWhitespace",
":",
"true",
",",
"caseSensitive",
":",
"true",
",",
"removeComments",
":",
"true",
"}",
... | Minify HTML templates | [
"Minify",
"HTML",
"templates"
] | b569e15fac75c5739d87b1c9a46216bb792c8d80 | https://github.com/fabric8-ui/ngx-widgets/blob/b569e15fac75c5739d87b1c9a46216bb792c8d80/gulpfile.js#L73-L84 |
34,226 | fabric8-ui/ngx-widgets | gulpfile.js | transpile | function transpile() {
return exec('node_modules/.bin/ngc -p tsconfig.json', function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
if (err !== null) {
process.exit(1);
}
});
} | javascript | function transpile() {
return exec('node_modules/.bin/ngc -p tsconfig.json', function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
if (err !== null) {
process.exit(1);
}
});
} | [
"function",
"transpile",
"(",
")",
"{",
"return",
"exec",
"(",
"'node_modules/.bin/ngc -p tsconfig.json'",
",",
"function",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"{",
"console",
".",
"log",
"(",
"stdout",
")",
";",
"console",
".",
"log",
"(",
"std... | Build the components
Since the gulpngc is no longer being supported we need to us ngc
@returns {ChildProcess} | [
"Build",
"the",
"components",
"Since",
"the",
"gulpngc",
"is",
"no",
"longer",
"being",
"supported",
"we",
"need",
"to",
"us",
"ngc"
] | b569e15fac75c5739d87b1c9a46216bb792c8d80 | https://github.com/fabric8-ui/ngx-widgets/blob/b569e15fac75c5739d87b1c9a46216bb792c8d80/gulpfile.js#L158-L166 |
34,227 | ShoppinPal/Materializecss-Autocomplete | dist/js/materializecss-autocomplete.js | clearValue | function clearValue() {
clearSelectedItem();
setInputClearButton();
if (self.parentForm && self.parentForm !== null) {
self.parentForm.$setDirty();
}
} | javascript | function clearValue() {
clearSelectedItem();
setInputClearButton();
if (self.parentForm && self.parentForm !== null) {
self.parentForm.$setDirty();
}
} | [
"function",
"clearValue",
"(",
")",
"{",
"clearSelectedItem",
"(",
")",
";",
"setInputClearButton",
"(",
")",
";",
"if",
"(",
"self",
".",
"parentForm",
"&&",
"self",
".",
"parentForm",
"!==",
"null",
")",
"{",
"self",
".",
"parentForm",
".",
"$setDirty",
... | clear the input text field using clear button Check clear button visble and hidden | [
"clear",
"the",
"input",
"text",
"field",
"using",
"clear",
"button",
"Check",
"clear",
"button",
"visble",
"and",
"hidden"
] | 07bef97b9b373949058716054ec84c5ec5a397b9 | https://github.com/ShoppinPal/Materializecss-Autocomplete/blob/07bef97b9b373949058716054ec84c5ec5a397b9/dist/js/materializecss-autocomplete.js#L263-L269 |
34,228 | ShoppinPal/Materializecss-Autocomplete | dist/js/materializecss-autocomplete.js | handleSearchText | function handleSearchText(searchText, previousSearchText) {
self.index = -1;
// do nothing on init
if (searchText === previousSearchText) return;
else if (self.selectedItem && self.displayProperty1) {
setLoading(false);
if (self.selectedItem[self.displayProperty1] !== searchText) {
self.selectedItem = null;
self.hidden = shouldHide();
if (self.itemList && self.itemListCopy) {
self.itemList = angular.copy(self.itemListCopy);
}
}
}
else if (self.remoteMethod) {
fetchResults(searchText);
}
else if (self.itemList) {
self.itemList = $filter('filter')(self.itemListCopy, searchText);
}
} | javascript | function handleSearchText(searchText, previousSearchText) {
self.index = -1;
// do nothing on init
if (searchText === previousSearchText) return;
else if (self.selectedItem && self.displayProperty1) {
setLoading(false);
if (self.selectedItem[self.displayProperty1] !== searchText) {
self.selectedItem = null;
self.hidden = shouldHide();
if (self.itemList && self.itemListCopy) {
self.itemList = angular.copy(self.itemListCopy);
}
}
}
else if (self.remoteMethod) {
fetchResults(searchText);
}
else if (self.itemList) {
self.itemList = $filter('filter')(self.itemListCopy, searchText);
}
} | [
"function",
"handleSearchText",
"(",
"searchText",
",",
"previousSearchText",
")",
"{",
"self",
".",
"index",
"=",
"-",
"1",
";",
"// do nothing on init",
"if",
"(",
"searchText",
"===",
"previousSearchText",
")",
"return",
";",
"else",
"if",
"(",
"self",
".",... | Handles changes to the searchText property.
@param searchText
@param previousSearchText | [
"Handles",
"changes",
"to",
"the",
"searchText",
"property",
"."
] | 07bef97b9b373949058716054ec84c5ec5a397b9 | https://github.com/ShoppinPal/Materializecss-Autocomplete/blob/07bef97b9b373949058716054ec84c5ec5a397b9/dist/js/materializecss-autocomplete.js#L458-L478 |
34,229 | ShoppinPal/Materializecss-Autocomplete | dist/js/materializecss-autocomplete.js | selectedItemChange | function selectedItemChange(selectedItem, previousSelectedItem) {
if (selectedItem) {
if (self.displayProperty1) {
self.searchText = selectedItem[self.displayProperty1];
}
if (self.parentForm && self.parentForm !== null) {
self.parentForm.$setDirty();
}
}
else if (previousSelectedItem && self.searchText) {
if (previousSelectedItem[self.displayProperty1] === self.searchText) {
self.searchText = '';
}
}
if (selectedItem !== previousSelectedItem) announceItemChange();
} | javascript | function selectedItemChange(selectedItem, previousSelectedItem) {
if (selectedItem) {
if (self.displayProperty1) {
self.searchText = selectedItem[self.displayProperty1];
}
if (self.parentForm && self.parentForm !== null) {
self.parentForm.$setDirty();
}
}
else if (previousSelectedItem && self.searchText) {
if (previousSelectedItem[self.displayProperty1] === self.searchText) {
self.searchText = '';
}
}
if (selectedItem !== previousSelectedItem) announceItemChange();
} | [
"function",
"selectedItemChange",
"(",
"selectedItem",
",",
"previousSelectedItem",
")",
"{",
"if",
"(",
"selectedItem",
")",
"{",
"if",
"(",
"self",
".",
"displayProperty1",
")",
"{",
"self",
".",
"searchText",
"=",
"selectedItem",
"[",
"self",
".",
"displayP... | Handles changes to the selected item.
@param selectedItem
@param previousSelectedItem | [
"Handles",
"changes",
"to",
"the",
"selected",
"item",
"."
] | 07bef97b9b373949058716054ec84c5ec5a397b9 | https://github.com/ShoppinPal/Materializecss-Autocomplete/blob/07bef97b9b373949058716054ec84c5ec5a397b9/dist/js/materializecss-autocomplete.js#L485-L501 |
34,230 | ShoppinPal/Materializecss-Autocomplete | dist/js/materializecss-autocomplete.js | updateScroll | function updateScroll() {
if (!self.element.li[0]) return;
var height = self.element.li[0].offsetHeight,
top = height * self.index,
bot = top + height,
hgt = self.element.scroller.clientHeight,
scrollTop = self.element.scroller.scrollTop;
if (top<scrollTop) {
scrollTo(top);
}else if (bot>scrollTop + hgt) {
scrollTo(bot - hgt);
}
} | javascript | function updateScroll() {
if (!self.element.li[0]) return;
var height = self.element.li[0].offsetHeight,
top = height * self.index,
bot = top + height,
hgt = self.element.scroller.clientHeight,
scrollTop = self.element.scroller.scrollTop;
if (top<scrollTop) {
scrollTo(top);
}else if (bot>scrollTop + hgt) {
scrollTo(bot - hgt);
}
} | [
"function",
"updateScroll",
"(",
")",
"{",
"if",
"(",
"!",
"self",
".",
"element",
".",
"li",
"[",
"0",
"]",
")",
"return",
";",
"var",
"height",
"=",
"self",
".",
"element",
".",
"li",
"[",
"0",
"]",
".",
"offsetHeight",
",",
"top",
"=",
"height... | Makes sure that the focused element is within view. | [
"Makes",
"sure",
"that",
"the",
"focused",
"element",
"is",
"within",
"view",
"."
] | 07bef97b9b373949058716054ec84c5ec5a397b9 | https://github.com/ShoppinPal/Materializecss-Autocomplete/blob/07bef97b9b373949058716054ec84c5ec5a397b9/dist/js/materializecss-autocomplete.js#L527-L539 |
34,231 | ShoppinPal/Materializecss-Autocomplete | dist/js/materializecss-autocomplete.js | handleUniqueResult | function handleUniqueResult(results) {
var res = [], flag = {};
for (var i = 0; i<results.length; i++) {
if (flag[results[i][self.displayProperty1]]) continue;
flag[results[i][self.displayProperty1]] = true;
res.push(results[i]);
}
return res;
} | javascript | function handleUniqueResult(results) {
var res = [], flag = {};
for (var i = 0; i<results.length; i++) {
if (flag[results[i][self.displayProperty1]]) continue;
flag[results[i][self.displayProperty1]] = true;
res.push(results[i]);
}
return res;
} | [
"function",
"handleUniqueResult",
"(",
"results",
")",
"{",
"var",
"res",
"=",
"[",
"]",
",",
"flag",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"results",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"flag",
... | This function check for result uniqueness on displayProperty1 params and return unique array
@param results
@returns {Array} | [
"This",
"function",
"check",
"for",
"result",
"uniqueness",
"on",
"displayProperty1",
"params",
"and",
"return",
"unique",
"array"
] | 07bef97b9b373949058716054ec84c5ec5a397b9 | https://github.com/ShoppinPal/Materializecss-Autocomplete/blob/07bef97b9b373949058716054ec84c5ec5a397b9/dist/js/materializecss-autocomplete.js#L604-L612 |
34,232 | ShoppinPal/Materializecss-Autocomplete | dist/js/materializecss-autocomplete.js | convertArrayToObject | function convertArrayToObject(array) {
var temp = [];
array.forEach(function (text) {
temp.push({
index: text
});
});
return temp;
} | javascript | function convertArrayToObject(array) {
var temp = [];
array.forEach(function (text) {
temp.push({
index: text
});
});
return temp;
} | [
"function",
"convertArrayToObject",
"(",
"array",
")",
"{",
"var",
"temp",
"=",
"[",
"]",
";",
"array",
".",
"forEach",
"(",
"function",
"(",
"text",
")",
"{",
"temp",
".",
"push",
"(",
"{",
"index",
":",
"text",
"}",
")",
";",
"}",
")",
";",
"re... | This function converts an array of strings to object of strings with key "index"
@param array
@returns {Array} | [
"This",
"function",
"converts",
"an",
"array",
"of",
"strings",
"to",
"object",
"of",
"strings",
"with",
"key",
"index"
] | 07bef97b9b373949058716054ec84c5ec5a397b9 | https://github.com/ShoppinPal/Materializecss-Autocomplete/blob/07bef97b9b373949058716054ec84c5ec5a397b9/dist/js/materializecss-autocomplete.js#L636-L644 |
34,233 | cgmartin/express-api-server | src/lib/graceful-shutdown.js | function(retCode) {
retCode = (typeof retCode !== 'undefined') ? retCode : 0;
if (server) {
if (shutdownInProgress) { return; }
shutdownInProgress = true;
console.info('Shutting down gracefully...');
server.close(function() {
console.info('Closed out remaining connections');
process.exit(retCode);
});
setTimeout(function() {
console.error('Could not close out connections in time, force shutdown');
process.exit(retCode);
}, 10 * 1000).unref();
} else {
console.debug('Http server is not running. Exiting');
process.exit(retCode);
}
} | javascript | function(retCode) {
retCode = (typeof retCode !== 'undefined') ? retCode : 0;
if (server) {
if (shutdownInProgress) { return; }
shutdownInProgress = true;
console.info('Shutting down gracefully...');
server.close(function() {
console.info('Closed out remaining connections');
process.exit(retCode);
});
setTimeout(function() {
console.error('Could not close out connections in time, force shutdown');
process.exit(retCode);
}, 10 * 1000).unref();
} else {
console.debug('Http server is not running. Exiting');
process.exit(retCode);
}
} | [
"function",
"(",
"retCode",
")",
"{",
"retCode",
"=",
"(",
"typeof",
"retCode",
"!==",
"'undefined'",
")",
"?",
"retCode",
":",
"0",
";",
"if",
"(",
"server",
")",
"{",
"if",
"(",
"shutdownInProgress",
")",
"{",
"return",
";",
"}",
"shutdownInProgress",
... | Shut down gracefully | [
"Shut",
"down",
"gracefully"
] | 9d6de16e7c84d21b83639a904f2eaed4a30a4088 | https://github.com/cgmartin/express-api-server/blob/9d6de16e7c84d21b83639a904f2eaed4a30a4088/src/lib/graceful-shutdown.js#L12-L34 | |
34,234 | fibo/dflow | src/engine/inject/arguments.js | injectArguments | function injectArguments (funcs, task, args) {
function getArgument (index) {
return args[index]
}
/**
* Inject arguments.
*/
function inject (taskKey) {
var funcName = task[taskKey]
if (funcName === 'arguments') {
funcs[funcName] = function getArguments () { return args }
} else {
var arg = regexArgument.exec(funcName)
if (arg) {
funcs[funcName] = getArgument.bind(null, arg[1])
}
}
}
Object.keys(task)
.forEach(inject)
} | javascript | function injectArguments (funcs, task, args) {
function getArgument (index) {
return args[index]
}
/**
* Inject arguments.
*/
function inject (taskKey) {
var funcName = task[taskKey]
if (funcName === 'arguments') {
funcs[funcName] = function getArguments () { return args }
} else {
var arg = regexArgument.exec(funcName)
if (arg) {
funcs[funcName] = getArgument.bind(null, arg[1])
}
}
}
Object.keys(task)
.forEach(inject)
} | [
"function",
"injectArguments",
"(",
"funcs",
",",
"task",
",",
"args",
")",
"{",
"function",
"getArgument",
"(",
"index",
")",
"{",
"return",
"args",
"[",
"index",
"]",
"}",
"/**\n * Inject arguments.\n */",
"function",
"inject",
"(",
"taskKey",
")",
"{",
... | Inject functions to retrieve arguments.
@param {Object} funcs reference
@param {Object} task
@param {Object} args | [
"Inject",
"functions",
"to",
"retrieve",
"arguments",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/arguments.js#L11-L36 |
34,235 | fibo/dflow | src/engine/inject/arguments.js | inject | function inject (taskKey) {
var funcName = task[taskKey]
if (funcName === 'arguments') {
funcs[funcName] = function getArguments () { return args }
} else {
var arg = regexArgument.exec(funcName)
if (arg) {
funcs[funcName] = getArgument.bind(null, arg[1])
}
}
} | javascript | function inject (taskKey) {
var funcName = task[taskKey]
if (funcName === 'arguments') {
funcs[funcName] = function getArguments () { return args }
} else {
var arg = regexArgument.exec(funcName)
if (arg) {
funcs[funcName] = getArgument.bind(null, arg[1])
}
}
} | [
"function",
"inject",
"(",
"taskKey",
")",
"{",
"var",
"funcName",
"=",
"task",
"[",
"taskKey",
"]",
"if",
"(",
"funcName",
"===",
"'arguments'",
")",
"{",
"funcs",
"[",
"funcName",
"]",
"=",
"function",
"getArguments",
"(",
")",
"{",
"return",
"args",
... | Inject arguments. | [
"Inject",
"arguments",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/arguments.js#L20-L32 |
34,236 | fibo/dflow | src/engine/inject/globals.js | injectGlobals | function injectGlobals (funcs, task) {
/**
* Inject task
*/
function inject (taskKey) {
var taskName = task[taskKey]
// Do not overwrite a function if already defined.
// For example, console.log cannot be used as is, it must binded to console.
if (typeof funcs[taskName] === 'function') return
// Skip also reserved keywords.
if (reservedKeys.indexOf(taskName) > -1) return
var globalValue = walkGlobal(taskName)
if (no(globalValue)) return
if (typeof globalValue === 'function') {
funcs[taskName] = globalValue
} else {
funcs[taskName] = function () {
return globalValue
}
}
}
Object.keys(task)
.forEach(inject)
} | javascript | function injectGlobals (funcs, task) {
/**
* Inject task
*/
function inject (taskKey) {
var taskName = task[taskKey]
// Do not overwrite a function if already defined.
// For example, console.log cannot be used as is, it must binded to console.
if (typeof funcs[taskName] === 'function') return
// Skip also reserved keywords.
if (reservedKeys.indexOf(taskName) > -1) return
var globalValue = walkGlobal(taskName)
if (no(globalValue)) return
if (typeof globalValue === 'function') {
funcs[taskName] = globalValue
} else {
funcs[taskName] = function () {
return globalValue
}
}
}
Object.keys(task)
.forEach(inject)
} | [
"function",
"injectGlobals",
"(",
"funcs",
",",
"task",
")",
"{",
"/**\n * Inject task\n */",
"function",
"inject",
"(",
"taskKey",
")",
"{",
"var",
"taskName",
"=",
"task",
"[",
"taskKey",
"]",
"// Do not overwrite a function if already defined.",
"// For example, ... | Inject globals.
@param {Object} funcs reference
@param {Object} task | [
"Inject",
"globals",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/globals.js#L12-L42 |
34,237 | fibo/dflow | src/examples/renderer/client-side.js | renderExample | function renderExample (divId, example) {
var graph = graphs[example]
var canvas = new Canvas(divId, {
node: {
DefaultNode: Node,
InvalidNode,
ToggleNode
},
util: { typeOfNode }
})
canvas.render(graph.view)
dflow.fun(graph)()
} | javascript | function renderExample (divId, example) {
var graph = graphs[example]
var canvas = new Canvas(divId, {
node: {
DefaultNode: Node,
InvalidNode,
ToggleNode
},
util: { typeOfNode }
})
canvas.render(graph.view)
dflow.fun(graph)()
} | [
"function",
"renderExample",
"(",
"divId",
",",
"example",
")",
"{",
"var",
"graph",
"=",
"graphs",
"[",
"example",
"]",
"var",
"canvas",
"=",
"new",
"Canvas",
"(",
"divId",
",",
"{",
"node",
":",
"{",
"DefaultNode",
":",
"Node",
",",
"InvalidNode",
",... | Render example into given div and execute dflow graph.
@param {String} divId
@param {String} example
@returns {undefined} | [
"Render",
"example",
"into",
"given",
"div",
"and",
"execute",
"dflow",
"graph",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/examples/renderer/client-side.js#L18-L33 |
34,238 | fibo/dflow | src/engine/inject/references.js | injectReferences | function injectReferences (funcs, task) {
/**
* Inject task.
*
* @param {String} taskKey
*/
function inject (taskKey) {
var referenceName = null
var referencedFunction = null
var taskName = task[taskKey]
/**
* Inject reference.
*/
function reference () {
return referencedFunction
}
if (regexReference.test(taskName)) {
referenceName = taskName.substring(1)
if (typeof funcs[referenceName] === 'function') {
referencedFunction = funcs[referenceName]
} else {
referencedFunction = walkGlobal(referenceName)
}
if (typeof referencedFunction === 'function') {
funcs[taskName] = reference
}
}
}
Object.keys(task).forEach(inject)
} | javascript | function injectReferences (funcs, task) {
/**
* Inject task.
*
* @param {String} taskKey
*/
function inject (taskKey) {
var referenceName = null
var referencedFunction = null
var taskName = task[taskKey]
/**
* Inject reference.
*/
function reference () {
return referencedFunction
}
if (regexReference.test(taskName)) {
referenceName = taskName.substring(1)
if (typeof funcs[referenceName] === 'function') {
referencedFunction = funcs[referenceName]
} else {
referencedFunction = walkGlobal(referenceName)
}
if (typeof referencedFunction === 'function') {
funcs[taskName] = reference
}
}
}
Object.keys(task).forEach(inject)
} | [
"function",
"injectReferences",
"(",
"funcs",
",",
"task",
")",
"{",
"/**\n * Inject task.\n *\n * @param {String} taskKey\n */",
"function",
"inject",
"(",
"taskKey",
")",
"{",
"var",
"referenceName",
"=",
"null",
"var",
"referencedFunction",
"=",
"null",
"var"... | Inject references to functions.
@param {Object} funcs reference
@param {Object} task | [
"Inject",
"references",
"to",
"functions",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/references.js#L11-L47 |
34,239 | fibo/dflow | src/engine/inject/references.js | inject | function inject (taskKey) {
var referenceName = null
var referencedFunction = null
var taskName = task[taskKey]
/**
* Inject reference.
*/
function reference () {
return referencedFunction
}
if (regexReference.test(taskName)) {
referenceName = taskName.substring(1)
if (typeof funcs[referenceName] === 'function') {
referencedFunction = funcs[referenceName]
} else {
referencedFunction = walkGlobal(referenceName)
}
if (typeof referencedFunction === 'function') {
funcs[taskName] = reference
}
}
} | javascript | function inject (taskKey) {
var referenceName = null
var referencedFunction = null
var taskName = task[taskKey]
/**
* Inject reference.
*/
function reference () {
return referencedFunction
}
if (regexReference.test(taskName)) {
referenceName = taskName.substring(1)
if (typeof funcs[referenceName] === 'function') {
referencedFunction = funcs[referenceName]
} else {
referencedFunction = walkGlobal(referenceName)
}
if (typeof referencedFunction === 'function') {
funcs[taskName] = reference
}
}
} | [
"function",
"inject",
"(",
"taskKey",
")",
"{",
"var",
"referenceName",
"=",
"null",
"var",
"referencedFunction",
"=",
"null",
"var",
"taskName",
"=",
"task",
"[",
"taskKey",
"]",
"/**\n * Inject reference.\n */",
"function",
"reference",
"(",
")",
"{",
... | Inject task.
@param {String} taskKey | [
"Inject",
"task",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/references.js#L18-L44 |
34,240 | fibo/dflow | src/engine/inject/strings.js | injectStrings | function injectStrings (funcs, task) {
/**
* Inject a function that returns a string.
*/
function inject (taskKey) {
var taskName = task[taskKey]
if (regexQuoted.test(taskName)) {
funcs[taskName] = function () {
return taskName.substr(1, taskName.length - 2)
}
}
}
Object.keys(task)
.forEach(inject)
} | javascript | function injectStrings (funcs, task) {
/**
* Inject a function that returns a string.
*/
function inject (taskKey) {
var taskName = task[taskKey]
if (regexQuoted.test(taskName)) {
funcs[taskName] = function () {
return taskName.substr(1, taskName.length - 2)
}
}
}
Object.keys(task)
.forEach(inject)
} | [
"function",
"injectStrings",
"(",
"funcs",
",",
"task",
")",
"{",
"/**\n * Inject a function that returns a string.\n */",
"function",
"inject",
"(",
"taskKey",
")",
"{",
"var",
"taskName",
"=",
"task",
"[",
"taskKey",
"]",
"if",
"(",
"regexQuoted",
".",
"test... | Inject functions that return strings.
@param {Object} funcs reference
@param {Object} task collection | [
"Inject",
"functions",
"that",
"return",
"strings",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/strings.js#L10-L27 |
34,241 | fibo/dflow | src/engine/inject/strings.js | inject | function inject (taskKey) {
var taskName = task[taskKey]
if (regexQuoted.test(taskName)) {
funcs[taskName] = function () {
return taskName.substr(1, taskName.length - 2)
}
}
} | javascript | function inject (taskKey) {
var taskName = task[taskKey]
if (regexQuoted.test(taskName)) {
funcs[taskName] = function () {
return taskName.substr(1, taskName.length - 2)
}
}
} | [
"function",
"inject",
"(",
"taskKey",
")",
"{",
"var",
"taskName",
"=",
"task",
"[",
"taskKey",
"]",
"if",
"(",
"regexQuoted",
".",
"test",
"(",
"taskName",
")",
")",
"{",
"funcs",
"[",
"taskName",
"]",
"=",
"function",
"(",
")",
"{",
"return",
"task... | Inject a function that returns a string. | [
"Inject",
"a",
"function",
"that",
"returns",
"a",
"string",
"."
] | 6530e4659952b9013e47b5fb28fbbd3a7a4af17d | https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/strings.js#L15-L23 |
34,242 | macbre/wayback-machine | lib/wayback.js | request | function request(url, options, callback) {
var debug = require('debug')('wayback:http');
debug('req', url);
callback = typeof callback === 'undefined' ? options : callback;
// @see https://www.npmjs.com/package/fetch
var stream = new fetch(url, typeof options === 'object' ? options : undefined);
stream.on('error', function(err) {
debug('error', err);
callback(err, null);
});
stream.on('meta', function(meta) {
debug('resp', 'HTTP ' + meta.status);
debug('resp', meta.responseHeaders);
callback(null, stream);
});
} | javascript | function request(url, options, callback) {
var debug = require('debug')('wayback:http');
debug('req', url);
callback = typeof callback === 'undefined' ? options : callback;
// @see https://www.npmjs.com/package/fetch
var stream = new fetch(url, typeof options === 'object' ? options : undefined);
stream.on('error', function(err) {
debug('error', err);
callback(err, null);
});
stream.on('meta', function(meta) {
debug('resp', 'HTTP ' + meta.status);
debug('resp', meta.responseHeaders);
callback(null, stream);
});
} | [
"function",
"request",
"(",
"url",
",",
"options",
",",
"callback",
")",
"{",
"var",
"debug",
"=",
"require",
"(",
"'debug'",
")",
"(",
"'wayback:http'",
")",
";",
"debug",
"(",
"'req'",
",",
"url",
")",
";",
"callback",
"=",
"typeof",
"callback",
"===... | a simple HTTP client wrapper returning a response stream | [
"a",
"simple",
"HTTP",
"client",
"wrapper",
"returning",
"a",
"response",
"stream"
] | b48fbf4735efad4fd6571cc292d28dc17cf6786c | https://github.com/macbre/wayback-machine/blob/b48fbf4735efad4fd6571cc292d28dc17cf6786c/lib/wayback.js#L9-L28 |
34,243 | Bandwidth/opkit | lib/Persisters/filepersister.js | filePersister | function filePersister(filepath) {
var self = this;
this.initialized = false;
this.filepath = filepath;
/**
* Check to see if the specified file path is available.
* @returns A promise appropriately resolving or rejecting.
*/
this.start = function() {
if (!this.initialized) {
return fsp.emptyDir(this.filepath)
.then(function() {
self.initialized = true;
return Promise.resolve('User has permissions to write to that file.');
})
.catch(function(err) {
return Promise.reject('User does not have permissions to write to that folder.');
});
}
return Promise.reject('Error: Persister already initialized.');
};
/**
* Save the passed state to the file.
* @param {Object} passedState - State to be saved in the file.
* @returns A promise resolving to an appropriate success message or an error message.
*/
this.save = function(brain, package) {
var filepath = this.filepath;
if (this.initialized) {
return fsp.remove(filepath + '/' + package + '.txt')
.then(function(){
return fsp.writeFile(filepath + '/' + package + '.txt', JSON.stringify(brain));
})
.then(function(){
return Promise.resolve('Saved.');
})
}
return Promise.reject('Error: Persister not initialized.');
};
/**
* Retrieve data from the file.
* @returns The most recent entry to the file, as a JavaScript object.
*/
this.recover = function(package) {
if (this.initialized) {
var filepath = this.filepath
return fsp.ensureFile(filepath +'/' + package + '.txt')
.then(function(){
return fsp.readFile(filepath + '/' + package + '.txt', 'utf8')
})
.then(function(data) {
if (data === ''){
return Promise.resolve({});
} else {
return Promise.resolve(JSON.parse(data));
}
});
}
return Promise.reject('Error: Persister not initialized.');
};
} | javascript | function filePersister(filepath) {
var self = this;
this.initialized = false;
this.filepath = filepath;
/**
* Check to see if the specified file path is available.
* @returns A promise appropriately resolving or rejecting.
*/
this.start = function() {
if (!this.initialized) {
return fsp.emptyDir(this.filepath)
.then(function() {
self.initialized = true;
return Promise.resolve('User has permissions to write to that file.');
})
.catch(function(err) {
return Promise.reject('User does not have permissions to write to that folder.');
});
}
return Promise.reject('Error: Persister already initialized.');
};
/**
* Save the passed state to the file.
* @param {Object} passedState - State to be saved in the file.
* @returns A promise resolving to an appropriate success message or an error message.
*/
this.save = function(brain, package) {
var filepath = this.filepath;
if (this.initialized) {
return fsp.remove(filepath + '/' + package + '.txt')
.then(function(){
return fsp.writeFile(filepath + '/' + package + '.txt', JSON.stringify(brain));
})
.then(function(){
return Promise.resolve('Saved.');
})
}
return Promise.reject('Error: Persister not initialized.');
};
/**
* Retrieve data from the file.
* @returns The most recent entry to the file, as a JavaScript object.
*/
this.recover = function(package) {
if (this.initialized) {
var filepath = this.filepath
return fsp.ensureFile(filepath +'/' + package + '.txt')
.then(function(){
return fsp.readFile(filepath + '/' + package + '.txt', 'utf8')
})
.then(function(data) {
if (data === ''){
return Promise.resolve({});
} else {
return Promise.resolve(JSON.parse(data));
}
});
}
return Promise.reject('Error: Persister not initialized.');
};
} | [
"function",
"filePersister",
"(",
"filepath",
")",
"{",
"var",
"self",
"=",
"this",
";",
"this",
".",
"initialized",
"=",
"false",
";",
"this",
".",
"filepath",
"=",
"filepath",
";",
"/**\n\t * Check to see if the specified file path is available.\n\t * @returns A promi... | File persister factory method. Returns a persister object.
@param {Schema} filepath - Directory to store the data
@param {Object} persisterPluginObject - For users who have written their own persister object. | [
"File",
"persister",
"factory",
"method",
".",
"Returns",
"a",
"persister",
"object",
"."
] | f83321ee93dd8362370fc4ce0790658bead64337 | https://github.com/Bandwidth/opkit/blob/f83321ee93dd8362370fc4ce0790658bead64337/lib/Persisters/filepersister.js#L10-L75 |
34,244 | alliance-pcsg/primo-explore-custom-actions | dist/module.js | addAction | function addAction(action, ctrl) {
this.addActionIcon(action, ctrl);
if (!this.actionExists(action, ctrl)) {
ctrl.actionListService.requiredActionsList.splice(action.index, 0, action.name);
ctrl.actionListService.actionsToIndex[action.name] = action.index;
ctrl.actionListService.onToggle[action.name] = action.onToggle;
ctrl.actionListService.actionsToDisplay.unshift(action.name);
}
} | javascript | function addAction(action, ctrl) {
this.addActionIcon(action, ctrl);
if (!this.actionExists(action, ctrl)) {
ctrl.actionListService.requiredActionsList.splice(action.index, 0, action.name);
ctrl.actionListService.actionsToIndex[action.name] = action.index;
ctrl.actionListService.onToggle[action.name] = action.onToggle;
ctrl.actionListService.actionsToDisplay.unshift(action.name);
}
} | [
"function",
"addAction",
"(",
"action",
",",
"ctrl",
")",
"{",
"this",
".",
"addActionIcon",
"(",
"action",
",",
"ctrl",
")",
";",
"if",
"(",
"!",
"this",
".",
"actionExists",
"(",
"action",
",",
"ctrl",
")",
")",
"{",
"ctrl",
".",
"actionListService",... | Adds an action to the actions menu, including its icon.
@param {object} action action object
@param {object} ctrl instance of prmActionCtrl
TODO coerce action.index to be <= requiredActionsList.length | [
"Adds",
"an",
"action",
"to",
"the",
"actions",
"menu",
"including",
"its",
"icon",
"."
] | f5457699d27c0b76e61aab584eb4065a7a985b9d | https://github.com/alliance-pcsg/primo-explore-custom-actions/blob/f5457699d27c0b76e61aab584eb4065a7a985b9d/dist/module.js#L50-L58 |
34,245 | alliance-pcsg/primo-explore-custom-actions | dist/module.js | removeAction | function removeAction(action, ctrl) {
if (this.actionExists(action, ctrl)) {
this.removeActionIcon(action, ctrl);
delete ctrl.actionListService.actionsToIndex[action.name];
delete ctrl.actionListService.onToggle[action.name];
var i = ctrl.actionListService.actionsToDisplay.indexOf(action.name);
ctrl.actionListService.actionsToDisplay.splice(i, 1);
i = ctrl.actionListService.requiredActionsList.indexOf(action.name);
ctrl.actionListService.requiredActionsList.splice(i, 1);
}
} | javascript | function removeAction(action, ctrl) {
if (this.actionExists(action, ctrl)) {
this.removeActionIcon(action, ctrl);
delete ctrl.actionListService.actionsToIndex[action.name];
delete ctrl.actionListService.onToggle[action.name];
var i = ctrl.actionListService.actionsToDisplay.indexOf(action.name);
ctrl.actionListService.actionsToDisplay.splice(i, 1);
i = ctrl.actionListService.requiredActionsList.indexOf(action.name);
ctrl.actionListService.requiredActionsList.splice(i, 1);
}
} | [
"function",
"removeAction",
"(",
"action",
",",
"ctrl",
")",
"{",
"if",
"(",
"this",
".",
"actionExists",
"(",
"action",
",",
"ctrl",
")",
")",
"{",
"this",
".",
"removeActionIcon",
"(",
"action",
",",
"ctrl",
")",
";",
"delete",
"ctrl",
".",
"actionLi... | Removes an action from the actions menu, including its icon.
@param {object} action action object
@param {object} ctrl instance of prmActionCtrl | [
"Removes",
"an",
"action",
"from",
"the",
"actions",
"menu",
"including",
"its",
"icon",
"."
] | f5457699d27c0b76e61aab584eb4065a7a985b9d | https://github.com/alliance-pcsg/primo-explore-custom-actions/blob/f5457699d27c0b76e61aab584eb4065a7a985b9d/dist/module.js#L64-L74 |
34,246 | Bandwidth/opkit | lib/ec2.js | dataFormatter | function dataFormatter(data) {
var instanceInfoArray = [];
var instanceInfoObject = {};
var reservations = data.Reservations;
for (var reservation in reservations) {
var instances = reservations[reservation].Instances;
for (var instance in instances) {
var tags = instances[instance].Tags;
for (var tag in tags) {
if (tags[tag].Key === 'Name') {
instanceInfoObject = _.assign(instanceInfoObject,
{Name: tags[tag].Value});
}
}
instanceInfoObject = _.assign(instanceInfoObject,
{State: instances[instance].State.Name},
{id: instances[instance].InstanceId});
instanceInfoArray.push(instanceInfoObject);
instanceInfoObject = {};
}
}
return Promise.resolve(instanceInfoArray);
} | javascript | function dataFormatter(data) {
var instanceInfoArray = [];
var instanceInfoObject = {};
var reservations = data.Reservations;
for (var reservation in reservations) {
var instances = reservations[reservation].Instances;
for (var instance in instances) {
var tags = instances[instance].Tags;
for (var tag in tags) {
if (tags[tag].Key === 'Name') {
instanceInfoObject = _.assign(instanceInfoObject,
{Name: tags[tag].Value});
}
}
instanceInfoObject = _.assign(instanceInfoObject,
{State: instances[instance].State.Name},
{id: instances[instance].InstanceId});
instanceInfoArray.push(instanceInfoObject);
instanceInfoObject = {};
}
}
return Promise.resolve(instanceInfoArray);
} | [
"function",
"dataFormatter",
"(",
"data",
")",
"{",
"var",
"instanceInfoArray",
"=",
"[",
"]",
";",
"var",
"instanceInfoObject",
"=",
"{",
"}",
";",
"var",
"reservations",
"=",
"data",
".",
"Reservations",
";",
"for",
"(",
"var",
"reservation",
"in",
"rese... | Helper function to format data returned by AWS EC2 queries. | [
"Helper",
"function",
"to",
"format",
"data",
"returned",
"by",
"AWS",
"EC2",
"queries",
"."
] | f83321ee93dd8362370fc4ce0790658bead64337 | https://github.com/Bandwidth/opkit/blob/f83321ee93dd8362370fc4ce0790658bead64337/lib/ec2.js#L264-L287 |
34,247 | jcreigno/nodejs-file-extractor | lib/main.js | Extractor | function Extractor(ac , options) {
EventEmitter.call(this);
var self = this;
self.matchers = [];
self.vars = ac || {};
self.options = options || {};
self.watchers = [];
self._listen = function (car, file) {
car.once('end', function () {
self.emit('end', self.vars);
});
car.on('line', function (line) {
var i;
var firstMatch = true;
for (i = 0; i < self.matchers.length; i++) {
var matcher = self.matchers[i];
var m;
while(matcher.handler && (m = matcher.re.exec(line)) !== null){
matcher.handler(m, self.vars, file , firstMatch);
firstMatch = false;
if(!self.options.successive){
i = self.matchers.length;
break;
}
}
}
});
return self;
};
} | javascript | function Extractor(ac , options) {
EventEmitter.call(this);
var self = this;
self.matchers = [];
self.vars = ac || {};
self.options = options || {};
self.watchers = [];
self._listen = function (car, file) {
car.once('end', function () {
self.emit('end', self.vars);
});
car.on('line', function (line) {
var i;
var firstMatch = true;
for (i = 0; i < self.matchers.length; i++) {
var matcher = self.matchers[i];
var m;
while(matcher.handler && (m = matcher.re.exec(line)) !== null){
matcher.handler(m, self.vars, file , firstMatch);
firstMatch = false;
if(!self.options.successive){
i = self.matchers.length;
break;
}
}
}
});
return self;
};
} | [
"function",
"Extractor",
"(",
"ac",
",",
"options",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"var",
"self",
"=",
"this",
";",
"self",
".",
"matchers",
"=",
"[",
"]",
";",
"self",
".",
"vars",
"=",
"ac",
"||",
"{",
"}",
";",
... | Extractor Object. | [
"Extractor",
"Object",
"."
] | ce071d1a50eed08e0e593d0609de8b61da320280 | https://github.com/jcreigno/nodejs-file-extractor/blob/ce071d1a50eed08e0e593d0609de8b61da320280/lib/main.js#L13-L42 |
34,248 | jcreigno/nodejs-file-extractor | lib/main.js | wildcards | function wildcards(f, cb, ctxt) {
var starmatch = f.match(/([^*]*)\*.*/);
if (!starmatch) { //keep async
process.nextTick(function () {
cb.apply(ctxt, [f]);
});
return;
}
var basedirPath = starmatch[1].split(/\//);
basedirPath.pop();
var wkdir = basedirPath.join('/');
//console.log('search base : %s', wkdir);
var r = f.substring(wkdir.length + 1);
//console.log('match pattern: %s', r);
glob(r, {
cwd: wkdir
}, function (err, matches) {
if (err) {
ctxt.emit('error', err);
} else {
console.log(matches);
matches.forEach(function (f) {
cb.apply(ctxt, [path.join(wkdir, f)]);
});
}
});
} | javascript | function wildcards(f, cb, ctxt) {
var starmatch = f.match(/([^*]*)\*.*/);
if (!starmatch) { //keep async
process.nextTick(function () {
cb.apply(ctxt, [f]);
});
return;
}
var basedirPath = starmatch[1].split(/\//);
basedirPath.pop();
var wkdir = basedirPath.join('/');
//console.log('search base : %s', wkdir);
var r = f.substring(wkdir.length + 1);
//console.log('match pattern: %s', r);
glob(r, {
cwd: wkdir
}, function (err, matches) {
if (err) {
ctxt.emit('error', err);
} else {
console.log(matches);
matches.forEach(function (f) {
cb.apply(ctxt, [path.join(wkdir, f)]);
});
}
});
} | [
"function",
"wildcards",
"(",
"f",
",",
"cb",
",",
"ctxt",
")",
"{",
"var",
"starmatch",
"=",
"f",
".",
"match",
"(",
"/",
"([^*]*)\\*.*",
"/",
")",
";",
"if",
"(",
"!",
"starmatch",
")",
"{",
"//keep async",
"process",
".",
"nextTick",
"(",
"functio... | handle wildcards in filenames
@param f: filename.
@param cb : callback when a matching file is found.
@param ctxt : callback invocation context. | [
"handle",
"wildcards",
"in",
"filenames"
] | ce071d1a50eed08e0e593d0609de8b61da320280 | https://github.com/jcreigno/nodejs-file-extractor/blob/ce071d1a50eed08e0e593d0609de8b61da320280/lib/main.js#L81-L108 |
34,249 | SpoonX/Censoring | index.js | Censoring | function Censoring() {
/**
* The string to replaces found matches with. Defaults to ***
*
* @type {String}
*/
this.replacementString = '***';
/**
* The color used for highlighting
*
* @type {string}
*/
this.highlightColor = 'F2B8B8';
/**
* Holds the currently matched text.
*
* @type {{replace: string, hasMatches: boolean}}
*/
this.currentMatch = {
replace: '',
hasMatches: false,
matches: []
};
/**
* The available patterns. These are as follows:
* [name] [description]
* - long_number ; Matches long, consecutive numbers
* - phone_number ; Matches phone numbers.
* - email_address ; Matches email addresses in many formats.
* - url ; Matches URL patterns/
* - words ; Finds words, even when in disguise.
*
* @type {{long_number: {pattern: RegExp, enabled: boolean}, phone_number: {pattern: RegExp, enabled: boolean}, email_address: {pattern: RegExp, enabled: boolean}, url: {pattern: RegExp, enabled: boolean}, words: {enabled: boolean, pattern: Array}}}
*/
this.patterns = {
long_number: {
pattern: /\d{8,}/,
enabled: false
},
phone_number: {
pattern: /([+-]?[\d]{1,}[\d\s-]+|\([\d]+\))[-\d.\s]{8,}/gi,
enabled: false
},
email_address: {
pattern: /[\w._%+-]+(@|\[at\]|\(at\))[\w.-]+(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])[a-zA-Z]{2,4}/gi,
enabled: false
},
url: {
pattern: /((https?:\/{1,2})?([-\w]\.{0,1}){2,}(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])([a-zA-Z]{2}\.[a-zA-Z]{2,3}|[a-zA-Z]{2,4}).*?(?=$|[^\w\/-]))/gi,
enabled: false
},
words: {
pattern: [],
enabled: false
}
};
/**
* A mapping that maps regular characters to 1337 characters.
*
* @type {{o: string, g: string, b: Array, t: string, s: string, a: string, e: string, z: string, i: string, l: string}}
*/
this.map1337 = {
o: '0',
g: '9',
b: ['8', '6'],
t: '7',
s: '5',
a: '4',
e: '3',
z: '2',
i: '1',
l: '1'
};
} | javascript | function Censoring() {
/**
* The string to replaces found matches with. Defaults to ***
*
* @type {String}
*/
this.replacementString = '***';
/**
* The color used for highlighting
*
* @type {string}
*/
this.highlightColor = 'F2B8B8';
/**
* Holds the currently matched text.
*
* @type {{replace: string, hasMatches: boolean}}
*/
this.currentMatch = {
replace: '',
hasMatches: false,
matches: []
};
/**
* The available patterns. These are as follows:
* [name] [description]
* - long_number ; Matches long, consecutive numbers
* - phone_number ; Matches phone numbers.
* - email_address ; Matches email addresses in many formats.
* - url ; Matches URL patterns/
* - words ; Finds words, even when in disguise.
*
* @type {{long_number: {pattern: RegExp, enabled: boolean}, phone_number: {pattern: RegExp, enabled: boolean}, email_address: {pattern: RegExp, enabled: boolean}, url: {pattern: RegExp, enabled: boolean}, words: {enabled: boolean, pattern: Array}}}
*/
this.patterns = {
long_number: {
pattern: /\d{8,}/,
enabled: false
},
phone_number: {
pattern: /([+-]?[\d]{1,}[\d\s-]+|\([\d]+\))[-\d.\s]{8,}/gi,
enabled: false
},
email_address: {
pattern: /[\w._%+-]+(@|\[at\]|\(at\))[\w.-]+(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])[a-zA-Z]{2,4}/gi,
enabled: false
},
url: {
pattern: /((https?:\/{1,2})?([-\w]\.{0,1}){2,}(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])([a-zA-Z]{2}\.[a-zA-Z]{2,3}|[a-zA-Z]{2,4}).*?(?=$|[^\w\/-]))/gi,
enabled: false
},
words: {
pattern: [],
enabled: false
}
};
/**
* A mapping that maps regular characters to 1337 characters.
*
* @type {{o: string, g: string, b: Array, t: string, s: string, a: string, e: string, z: string, i: string, l: string}}
*/
this.map1337 = {
o: '0',
g: '9',
b: ['8', '6'],
t: '7',
s: '5',
a: '4',
e: '3',
z: '2',
i: '1',
l: '1'
};
} | [
"function",
"Censoring",
"(",
")",
"{",
"/**\n * The string to replaces found matches with. Defaults to ***\n *\n * @type {String}\n */",
"this",
".",
"replacementString",
"=",
"'***'",
";",
"/**\n * The color used for highlighting\n *\n * @type {string}\n */"... | The Censoring object constructor.
@constructor | [
"The",
"Censoring",
"object",
"constructor",
"."
] | 9ffc8c42d67a5773f6a09821a3f84b7482b41f3c | https://github.com/SpoonX/Censoring/blob/9ffc8c42d67a5773f6a09821a3f84b7482b41f3c/index.js#L9-L87 |
34,250 | SpoonX/Censoring | index.js | function (filters) {
if (!this.isArray(filters)) {
throw 'Invalid filters type supplied. Expected Array.';
}
for (var i = 0; i < filters.length; i++) {
this.enableFilter(filters[i]);
}
return this;
} | javascript | function (filters) {
if (!this.isArray(filters)) {
throw 'Invalid filters type supplied. Expected Array.';
}
for (var i = 0; i < filters.length; i++) {
this.enableFilter(filters[i]);
}
return this;
} | [
"function",
"(",
"filters",
")",
"{",
"if",
"(",
"!",
"this",
".",
"isArray",
"(",
"filters",
")",
")",
"{",
"throw",
"'Invalid filters type supplied. Expected Array.'",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"filters",
".",
"length",... | Enable multiple filters at once.
@param {Array} filters
@returns {Censoring}
@see Censoring.enableFilter | [
"Enable",
"multiple",
"filters",
"at",
"once",
"."
] | 9ffc8c42d67a5773f6a09821a3f84b7482b41f3c | https://github.com/SpoonX/Censoring/blob/9ffc8c42d67a5773f6a09821a3f84b7482b41f3c/index.js#L142-L152 | |
34,251 | SpoonX/Censoring | index.js | function (words) {
if (!this.isArray(words)) {
throw 'Invalid type supplied for addFilterWords. Expected array.';
}
for (var i = 0; i < words.length; i++) {
this.addFilterWord(words[i]);
}
return this;
} | javascript | function (words) {
if (!this.isArray(words)) {
throw 'Invalid type supplied for addFilterWords. Expected array.';
}
for (var i = 0; i < words.length; i++) {
this.addFilterWord(words[i]);
}
return this;
} | [
"function",
"(",
"words",
")",
"{",
"if",
"(",
"!",
"this",
".",
"isArray",
"(",
"words",
")",
")",
"{",
"throw",
"'Invalid type supplied for addFilterWords. Expected array.'",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"words",
".",
"len... | Add multiple filterWords.
@param {[]} words
@returns {Censoring} | [
"Add",
"multiple",
"filterWords",
"."
] | 9ffc8c42d67a5773f6a09821a3f84b7482b41f3c | https://github.com/SpoonX/Censoring/blob/9ffc8c42d67a5773f6a09821a3f84b7482b41f3c/index.js#L176-L186 | |
34,252 | SpoonX/Censoring | index.js | function (word) {
var pattern = '',
any = '[^a-z0-9]?',
last = false,
character;
for (var i = 0; i < word.length; i++) {
last = i === (word.length - 1);
character = word.charAt(i);
if (typeof this.map1337[character] === 'undefined') {
pattern += (character + (!last ? any : ''));
continue;
}
if (typeof this.map1337[character] === 'string') {
pattern += ('((' + character + '|' + this.map1337[character] + ')' + (!last ? any : '') + ')');
continue;
}
pattern += '((' + character;
for (var m = 0; m < this.map1337[character].length; m++) {
pattern += '|' + this.map1337[character][m];
}
pattern += ')' + (!last ? any : '') + ')';
}
this.patterns.words.pattern.push(new RegExp(pattern, 'ig'));
return this;
} | javascript | function (word) {
var pattern = '',
any = '[^a-z0-9]?',
last = false,
character;
for (var i = 0; i < word.length; i++) {
last = i === (word.length - 1);
character = word.charAt(i);
if (typeof this.map1337[character] === 'undefined') {
pattern += (character + (!last ? any : ''));
continue;
}
if (typeof this.map1337[character] === 'string') {
pattern += ('((' + character + '|' + this.map1337[character] + ')' + (!last ? any : '') + ')');
continue;
}
pattern += '((' + character;
for (var m = 0; m < this.map1337[character].length; m++) {
pattern += '|' + this.map1337[character][m];
}
pattern += ')' + (!last ? any : '') + ')';
}
this.patterns.words.pattern.push(new RegExp(pattern, 'ig'));
return this;
} | [
"function",
"(",
"word",
")",
"{",
"var",
"pattern",
"=",
"''",
",",
"any",
"=",
"'[^a-z0-9]?'",
",",
"last",
"=",
"false",
",",
"character",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"word",
".",
"length",
";",
"i",
"++",
")",
"{",... | Add a word to filter out.
@param {String} word
@returns {Censoring} | [
"Add",
"a",
"word",
"to",
"filter",
"out",
"."
] | 9ffc8c42d67a5773f6a09821a3f84b7482b41f3c | https://github.com/SpoonX/Censoring/blob/9ffc8c42d67a5773f6a09821a3f84b7482b41f3c/index.js#L194-L228 | |
34,253 | SpoonX/Censoring | index.js | function (str, highlight) {
this.currentMatch.replace = this.filterString(str, highlight);
this.currentMatch.hasMatches = str !== this.currentMatch.replace;
return this;
} | javascript | function (str, highlight) {
this.currentMatch.replace = this.filterString(str, highlight);
this.currentMatch.hasMatches = str !== this.currentMatch.replace;
return this;
} | [
"function",
"(",
"str",
",",
"highlight",
")",
"{",
"this",
".",
"currentMatch",
".",
"replace",
"=",
"this",
".",
"filterString",
"(",
"str",
",",
"highlight",
")",
";",
"this",
".",
"currentMatch",
".",
"hasMatches",
"=",
"str",
"!==",
"this",
".",
"... | Prepare some text to be matched against.
@param {String} str
@param {Boolean} highlight
@returns {Censoring} | [
"Prepare",
"some",
"text",
"to",
"be",
"matched",
"against",
"."
] | 9ffc8c42d67a5773f6a09821a3f84b7482b41f3c | https://github.com/SpoonX/Censoring/blob/9ffc8c42d67a5773f6a09821a3f84b7482b41f3c/index.js#L269-L274 | |
34,254 | SpoonX/Censoring | index.js | function (str, highlight) {
highlight = highlight || false;
var self = this;
var highlightColor = this.highlightColor;
var replace = function (str, pattern) {
if (!highlight) {
return str.replace(pattern, function (match) {
self.currentMatch.matches.push(match);
return self.replacementString;
});
}
return str.replace(pattern, function (match) {
self.currentMatch.matches.push(match);
return '<span style="background: #' + highlightColor + ';">' + match + '</span>';
});
}.bind(this);
if (typeof str !== 'string') {
throw 'Invalid "str" type supplied in filterString. Expected string.';
}
for (var p in this.patterns) {
if (!this.patterns[p].enabled) {
continue;
}
if (this.patterns[p].pattern instanceof RegExp) {
str = replace(str, this.patterns[p].pattern);
continue;
}
if (!this.isArray(this.patterns[p].pattern)) {
throw 'Invalid pattern type supplied. Expected Array.';
}
for (var i = 0; i < this.patterns[p].pattern.length; i++) {
if (!this.patterns[p].pattern[i] instanceof RegExp) {
throw 'Expected valid RegExp.';
}
str = replace(str, this.patterns[p].pattern[i]);
}
}
return str;
} | javascript | function (str, highlight) {
highlight = highlight || false;
var self = this;
var highlightColor = this.highlightColor;
var replace = function (str, pattern) {
if (!highlight) {
return str.replace(pattern, function (match) {
self.currentMatch.matches.push(match);
return self.replacementString;
});
}
return str.replace(pattern, function (match) {
self.currentMatch.matches.push(match);
return '<span style="background: #' + highlightColor + ';">' + match + '</span>';
});
}.bind(this);
if (typeof str !== 'string') {
throw 'Invalid "str" type supplied in filterString. Expected string.';
}
for (var p in this.patterns) {
if (!this.patterns[p].enabled) {
continue;
}
if (this.patterns[p].pattern instanceof RegExp) {
str = replace(str, this.patterns[p].pattern);
continue;
}
if (!this.isArray(this.patterns[p].pattern)) {
throw 'Invalid pattern type supplied. Expected Array.';
}
for (var i = 0; i < this.patterns[p].pattern.length; i++) {
if (!this.patterns[p].pattern[i] instanceof RegExp) {
throw 'Expected valid RegExp.';
}
str = replace(str, this.patterns[p].pattern[i]);
}
}
return str;
} | [
"function",
"(",
"str",
",",
"highlight",
")",
"{",
"highlight",
"=",
"highlight",
"||",
"false",
";",
"var",
"self",
"=",
"this",
";",
"var",
"highlightColor",
"=",
"this",
".",
"highlightColor",
";",
"var",
"replace",
"=",
"function",
"(",
"str",
",",
... | Filter the string.
@param {String} str
@param {Boolean} highlight
@returns {String}} | [
"Filter",
"the",
"string",
"."
] | 9ffc8c42d67a5773f6a09821a3f84b7482b41f3c | https://github.com/SpoonX/Censoring/blob/9ffc8c42d67a5773f6a09821a3f84b7482b41f3c/index.js#L292-L340 | |
34,255 | ipetez/react-create | src/scripts/component.js | addCssExtension | function addCssExtension(args, styleExts, extensions) {
for (let x = 0, len = args.length; x < len; x++) {
if (styleExts.includes(args[x])) {
extensions.push('.' + args[x].slice(2));
}
}
} | javascript | function addCssExtension(args, styleExts, extensions) {
for (let x = 0, len = args.length; x < len; x++) {
if (styleExts.includes(args[x])) {
extensions.push('.' + args[x].slice(2));
}
}
} | [
"function",
"addCssExtension",
"(",
"args",
",",
"styleExts",
",",
"extensions",
")",
"{",
"for",
"(",
"let",
"x",
"=",
"0",
",",
"len",
"=",
"args",
".",
"length",
";",
"x",
"<",
"len",
";",
"x",
"++",
")",
"{",
"if",
"(",
"styleExts",
".",
"inc... | Grabbing style extension from arguments and adding to
full list of extensions | [
"Grabbing",
"style",
"extension",
"from",
"arguments",
"and",
"adding",
"to",
"full",
"list",
"of",
"extensions"
] | 1b77954244aab1aac2133fe4bc4fa943d3c2c6d7 | https://github.com/ipetez/react-create/blob/1b77954244aab1aac2133fe4bc4fa943d3c2c6d7/src/scripts/component.js#L23-L29 |
34,256 | strapi/strapi-generate-email | files/api/email/models/Email.js | function (values, next) {
const api = path.basename(__filename, '.js').toLowerCase();
if (strapi.api.hasOwnProperty(api) && _.size(strapi.api[api].templates)) {
const template = _.includes(strapi.api[api].templates, values.template) ? values.template : strapi.models[api].defaultTemplate;
// Set template with correct value
values.template = template;
// Merge model type with template validations
const templateAttributes = _.merge(_.pick(strapi.models[api].attributes, 'lang'), strapi.api[api].templates[template].attributes);
const err = [];
_.forEach(templateAttributes, function (rules, key) {
if (values.hasOwnProperty(key) || key === 'lang') {
if (key === 'lang') {
// Set lang with correct value
values[key] = _.includes(strapi.config.i18n.locales, values[key]) ? values[key] : strapi.config.i18n.defaultLocale;
} else {
// Check validations
const rulesTest = anchor(values[key]).to(rules);
if (rulesTest) {
err.push(rulesTest[0]);
}
}
} else {
rules.required && err.push({
rule: 'required',
message: 'Missing attributes ' + key
});
}
});
// Go next step or not
_.isEmpty(err) ? next() : next(err);
} else {
next(new Error('Unknow API or no template detected'));
}
} | javascript | function (values, next) {
const api = path.basename(__filename, '.js').toLowerCase();
if (strapi.api.hasOwnProperty(api) && _.size(strapi.api[api].templates)) {
const template = _.includes(strapi.api[api].templates, values.template) ? values.template : strapi.models[api].defaultTemplate;
// Set template with correct value
values.template = template;
// Merge model type with template validations
const templateAttributes = _.merge(_.pick(strapi.models[api].attributes, 'lang'), strapi.api[api].templates[template].attributes);
const err = [];
_.forEach(templateAttributes, function (rules, key) {
if (values.hasOwnProperty(key) || key === 'lang') {
if (key === 'lang') {
// Set lang with correct value
values[key] = _.includes(strapi.config.i18n.locales, values[key]) ? values[key] : strapi.config.i18n.defaultLocale;
} else {
// Check validations
const rulesTest = anchor(values[key]).to(rules);
if (rulesTest) {
err.push(rulesTest[0]);
}
}
} else {
rules.required && err.push({
rule: 'required',
message: 'Missing attributes ' + key
});
}
});
// Go next step or not
_.isEmpty(err) ? next() : next(err);
} else {
next(new Error('Unknow API or no template detected'));
}
} | [
"function",
"(",
"values",
",",
"next",
")",
"{",
"const",
"api",
"=",
"path",
".",
"basename",
"(",
"__filename",
",",
"'.js'",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"strapi",
".",
"api",
".",
"hasOwnProperty",
"(",
"api",
")",
"&&",
... | Lifecycle callbacks
Before validate | [
"Lifecycle",
"callbacks",
"Before",
"validate"
] | e29983b725d4089364ebe6e5f6449c709bbac51d | https://github.com/strapi/strapi-generate-email/blob/e29983b725d4089364ebe6e5f6449c709bbac51d/files/api/email/models/Email.js#L55-L94 | |
34,257 | jokesterfr/node-pcsc | lib/node-pcsc.js | getItem | function getItem(ATR) {
var item;
while( item === undefined ) {
item = slist[ATR];
if(!ATR) break;
ATR = ATR.substring(0, ATR.length-1);
}
return item;
} | javascript | function getItem(ATR) {
var item;
while( item === undefined ) {
item = slist[ATR];
if(!ATR) break;
ATR = ATR.substring(0, ATR.length-1);
}
return item;
} | [
"function",
"getItem",
"(",
"ATR",
")",
"{",
"var",
"item",
";",
"while",
"(",
"item",
"===",
"undefined",
")",
"{",
"item",
"=",
"slist",
"[",
"ATR",
"]",
";",
"if",
"(",
"!",
"ATR",
")",
"break",
";",
"ATR",
"=",
"ATR",
".",
"substring",
"(",
... | Retrieve some more infos about the inserted card
@param ATR {String} atr of the inserted card
@return {Object} if defined, the card name and info details | [
"Retrieve",
"some",
"more",
"infos",
"about",
"the",
"inserted",
"card"
] | 8593d1bf784afe1fc605b936de9af266dac02eb1 | https://github.com/jokesterfr/node-pcsc/blob/8593d1bf784afe1fc605b936de9af266dac02eb1/lib/node-pcsc.js#L72-L80 |
34,258 | creamidea/keyboard-js | samples/heatmap.js | Log | function Log(keyboardInfo) {
var log = keyboardInfo.querySelector('ul')
var st = keyboardInfo.querySelector('.statistic')
var totalAvgTime = 0
var totalCount = 0
return function (key, statistic) {
var count = statistic.count
var average = statistic.average
totalCount = totalCount + 1
totalAvgTime = totalAvgTime + statistic.average
totalAvg = +(totalAvgTime/totalCount).toFixed(2) || 0
var li = document.createElement('li')
li.className = "bounceIn animated"
li.innerHTML = '<kbd>'+key+'</kbd><div><p><span class="avg">avg: </span><span class="value">'+average.toFixed(2)+'</span>ms</p><p><span class="count">count: </span><span class="value">'+count+'</span></p></div>'
log.insertBefore(li, log.firstChild) // http://callmenick.com/post/prepend-child-javascript
if (log.children.length > 10) {
log.lastChild.remove()
}
st.innerHTML = '<div><span class="avg">Total Avg: </span><span class="value">'+totalAvg+' ms</span></div><div><span class="count">Total Count: </span><span class="value">'+totalCount+'</span></div>'
}
} | javascript | function Log(keyboardInfo) {
var log = keyboardInfo.querySelector('ul')
var st = keyboardInfo.querySelector('.statistic')
var totalAvgTime = 0
var totalCount = 0
return function (key, statistic) {
var count = statistic.count
var average = statistic.average
totalCount = totalCount + 1
totalAvgTime = totalAvgTime + statistic.average
totalAvg = +(totalAvgTime/totalCount).toFixed(2) || 0
var li = document.createElement('li')
li.className = "bounceIn animated"
li.innerHTML = '<kbd>'+key+'</kbd><div><p><span class="avg">avg: </span><span class="value">'+average.toFixed(2)+'</span>ms</p><p><span class="count">count: </span><span class="value">'+count+'</span></p></div>'
log.insertBefore(li, log.firstChild) // http://callmenick.com/post/prepend-child-javascript
if (log.children.length > 10) {
log.lastChild.remove()
}
st.innerHTML = '<div><span class="avg">Total Avg: </span><span class="value">'+totalAvg+' ms</span></div><div><span class="count">Total Count: </span><span class="value">'+totalCount+'</span></div>'
}
} | [
"function",
"Log",
"(",
"keyboardInfo",
")",
"{",
"var",
"log",
"=",
"keyboardInfo",
".",
"querySelector",
"(",
"'ul'",
")",
"var",
"st",
"=",
"keyboardInfo",
".",
"querySelector",
"(",
"'.statistic'",
")",
"var",
"totalAvgTime",
"=",
"0",
"var",
"totalCount... | canvas.style.zIndex = 10 | [
"canvas",
".",
"style",
".",
"zIndex",
"=",
"10"
] | 71b6f21899eca0154a3fd5494fe5dd5d4db2b887 | https://github.com/creamidea/keyboard-js/blob/71b6f21899eca0154a3fd5494fe5dd5d4db2b887/samples/heatmap.js#L40-L61 |
34,259 | jonschlinkert/read-data | index.js | extname | function extname(ext) {
var str = ext.charAt(0) === '.' ? ext.slice(1) : ext;
if (str === 'yml') str = 'yaml';
return str;
} | javascript | function extname(ext) {
var str = ext.charAt(0) === '.' ? ext.slice(1) : ext;
if (str === 'yml') str = 'yaml';
return str;
} | [
"function",
"extname",
"(",
"ext",
")",
"{",
"var",
"str",
"=",
"ext",
".",
"charAt",
"(",
"0",
")",
"===",
"'.'",
"?",
"ext",
".",
"slice",
"(",
"1",
")",
":",
"ext",
";",
"if",
"(",
"str",
"===",
"'yml'",
")",
"str",
"=",
"'yaml'",
";",
"re... | Get the extname without leading `.` | [
"Get",
"the",
"extname",
"without",
"leading",
"."
] | 0d9636f9d1d064d57fd0d0e2948bcbd77ba8acfd | https://github.com/jonschlinkert/read-data/blob/0d9636f9d1d064d57fd0d0e2948bcbd77ba8acfd/index.js#L179-L183 |
34,260 | SimpleRegex/SRL-JavaScript | lib/Language/Helpers/buildQuery.js | buildQuery | function buildQuery(query, builder = new Builder()) {
for (let i = 0; i < query.length; i++) {
const method = query[i]
if (Array.isArray(method)) {
builder.and(buildQuery(method, new NonCapture()))
continue
}
if (!method instanceof Method) {
// At this point, there should only be methods left, since all parameters are already taken care of.
// If that's not the case, something didn't work out.
throw new SyntaxException(`Unexpected statement: ${method}`)
}
const parameters = []
// If there are parameters, walk through them and apply them if they don't start a new method.
while (query[i + 1] && !(query[i + 1] instanceof Method)) {
parameters.push(query[i + 1])
// Since the parameters will be appended to the method object, they are already parsed and can be
// removed from further parsing. Don't use unset to keep keys incrementing.
query.splice(i + 1, 1)
}
try {
// Now, append that method to the builder object.
method.setParameters(parameters).callMethodOn(builder)
} catch (e) {
const lastIndex = parameters.length - 1
if (Array.isArray(parameters[lastIndex])) {
if (lastIndex !== 0) {
method.setParameters(parameters.slice(0, lastIndex))
}
method.callMethodOn(builder)
builder.and(buildQuery(parameters[lastIndex], new NonCapture()))
} else {
throw new SyntaxException(`Invalid parameter given for ${method.origin}`)
}
}
}
return builder
} | javascript | function buildQuery(query, builder = new Builder()) {
for (let i = 0; i < query.length; i++) {
const method = query[i]
if (Array.isArray(method)) {
builder.and(buildQuery(method, new NonCapture()))
continue
}
if (!method instanceof Method) {
// At this point, there should only be methods left, since all parameters are already taken care of.
// If that's not the case, something didn't work out.
throw new SyntaxException(`Unexpected statement: ${method}`)
}
const parameters = []
// If there are parameters, walk through them and apply them if they don't start a new method.
while (query[i + 1] && !(query[i + 1] instanceof Method)) {
parameters.push(query[i + 1])
// Since the parameters will be appended to the method object, they are already parsed and can be
// removed from further parsing. Don't use unset to keep keys incrementing.
query.splice(i + 1, 1)
}
try {
// Now, append that method to the builder object.
method.setParameters(parameters).callMethodOn(builder)
} catch (e) {
const lastIndex = parameters.length - 1
if (Array.isArray(parameters[lastIndex])) {
if (lastIndex !== 0) {
method.setParameters(parameters.slice(0, lastIndex))
}
method.callMethodOn(builder)
builder.and(buildQuery(parameters[lastIndex], new NonCapture()))
} else {
throw new SyntaxException(`Invalid parameter given for ${method.origin}`)
}
}
}
return builder
} | [
"function",
"buildQuery",
"(",
"query",
",",
"builder",
"=",
"new",
"Builder",
"(",
")",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"query",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"method",
"=",
"query",
"[",
"i",
"]"... | After the query was resolved, it can be built and thus executed.
@param array $query
@param Builder|null $builder If no Builder is given, the default Builder will be taken.
@return Builder
@throws SyntaxException | [
"After",
"the",
"query",
"was",
"resolved",
"it",
"can",
"be",
"built",
"and",
"thus",
"executed",
"."
] | eb2f0576ec49076e95fc2adec57e10d83c24d438 | https://github.com/SimpleRegex/SRL-JavaScript/blob/eb2f0576ec49076e95fc2adec57e10d83c24d438/lib/Language/Helpers/buildQuery.js#L16-L59 |
34,261 | nhn/tui.dom | src/js/domutil.js | setClassName | function setClassName(element, cssClass) {
cssClass = snippet.isArray(cssClass) ? cssClass.join(' ') : cssClass;
cssClass = trim(cssClass);
if (snippet.isUndefined(element.className.baseVal)) {
element.className = cssClass;
return;
}
element.className.baseVal = cssClass;
} | javascript | function setClassName(element, cssClass) {
cssClass = snippet.isArray(cssClass) ? cssClass.join(' ') : cssClass;
cssClass = trim(cssClass);
if (snippet.isUndefined(element.className.baseVal)) {
element.className = cssClass;
return;
}
element.className.baseVal = cssClass;
} | [
"function",
"setClassName",
"(",
"element",
",",
"cssClass",
")",
"{",
"cssClass",
"=",
"snippet",
".",
"isArray",
"(",
"cssClass",
")",
"?",
"cssClass",
".",
"join",
"(",
"' '",
")",
":",
"cssClass",
";",
"cssClass",
"=",
"trim",
"(",
"cssClass",
")",
... | Set className value
@param {(HTMLElement|SVGElement)} element - target element
@param {(string|string[])} cssClass - class names
@ignore | [
"Set",
"className",
"value"
] | beafe74afb8f647d770e202894ecc9c2dc0ca2b5 | https://github.com/nhn/tui.dom/blob/beafe74afb8f647d770e202894ecc9c2dc0ca2b5/src/js/domutil.js#L82-L94 |
34,262 | kozhevnikov/jsdoc-memberof-namespace | index.js | getNamespace | function getNamespace(file, path) {
const files = namespaces.filter(ns => ns.meta.filename === file && ns.meta.path === path);
if (files.length > 0) {
return files[files.length - 1];
}
const paths = namespaces.filter(ns => isIndex(ns.meta.filename) && isParent(ns.meta.path, path));
if (paths.length > 0) {
paths.sort((ns1, ns2) => ns1.meta.path.length - ns2.meta.path.length);
return paths[paths.length - 1];
}
return null;
} | javascript | function getNamespace(file, path) {
const files = namespaces.filter(ns => ns.meta.filename === file && ns.meta.path === path);
if (files.length > 0) {
return files[files.length - 1];
}
const paths = namespaces.filter(ns => isIndex(ns.meta.filename) && isParent(ns.meta.path, path));
if (paths.length > 0) {
paths.sort((ns1, ns2) => ns1.meta.path.length - ns2.meta.path.length);
return paths[paths.length - 1];
}
return null;
} | [
"function",
"getNamespace",
"(",
"file",
",",
"path",
")",
"{",
"const",
"files",
"=",
"namespaces",
".",
"filter",
"(",
"ns",
"=>",
"ns",
".",
"meta",
".",
"filename",
"===",
"file",
"&&",
"ns",
".",
"meta",
".",
"path",
"===",
"path",
")",
";",
"... | Get closest namespace doclet previously parsed either from the same file as the doclet
or from one of the index.js files present in the same directory or any of its parents
@param {string} file - File name of the doclet
@param {string} path - Directory path of the doclet
@return {?Doclet} - Namespace doclet or null | [
"Get",
"closest",
"namespace",
"doclet",
"previously",
"parsed",
"either",
"from",
"the",
"same",
"file",
"as",
"the",
"doclet",
"or",
"from",
"one",
"of",
"the",
"index",
".",
"js",
"files",
"present",
"in",
"the",
"same",
"directory",
"or",
"any",
"of",
... | 6035128bd605c427105c5fabed31114f806c9e7b | https://github.com/kozhevnikov/jsdoc-memberof-namespace/blob/6035128bd605c427105c5fabed31114f806c9e7b/index.js#L95-L108 |
34,263 | hubiinetwork/nahmii-sdk | lib/utils.js | expandPropertyNameGlobs | function expandPropertyNameGlobs(object, globPatterns) {
const result = [];
if (!globPatterns.length)
return result;
const arrayGroupPattern = globPatterns[0];
const indexOfArrayGroup = arrayGroupPattern.indexOf('[]');
if (indexOfArrayGroup !== -1) {
const {arrayProp, arrayPropName} = getArrayProperty(object, arrayGroupPattern, indexOfArrayGroup);
arrayProp.forEach((v, i) => {
const pp = `${arrayPropName}[${i}]`;
const propertyGroup = [];
for (let i = 1; i < globPatterns.length; i++) {
const pattern = `${pp}.${globPatterns[i]}`;
propertyGroup.push(pattern);
}
result.push(propertyGroup);
});
return result;
}
for (let pattern of globPatterns) {
let indexOfGlob = pattern.indexOf('*');
if (indexOfGlob === -1) {
result.push(pattern);
}
else {
const {arrayProp, arrayPropName} = getArrayProperty(object, pattern, indexOfGlob);
arrayProp.forEach((v, i) => {
const pp = `${arrayPropName}[${i}]`;
if (indexOfGlob < pattern.length - 1)
result.push(pp + pattern.substring(indexOfGlob + 1));
else if (typeof v === 'object')
Object.getOwnPropertyNames(v).forEach(n => result.push(`${pp}.${n}`));
else
result.push(pp);
});
}
}
return result;
} | javascript | function expandPropertyNameGlobs(object, globPatterns) {
const result = [];
if (!globPatterns.length)
return result;
const arrayGroupPattern = globPatterns[0];
const indexOfArrayGroup = arrayGroupPattern.indexOf('[]');
if (indexOfArrayGroup !== -1) {
const {arrayProp, arrayPropName} = getArrayProperty(object, arrayGroupPattern, indexOfArrayGroup);
arrayProp.forEach((v, i) => {
const pp = `${arrayPropName}[${i}]`;
const propertyGroup = [];
for (let i = 1; i < globPatterns.length; i++) {
const pattern = `${pp}.${globPatterns[i]}`;
propertyGroup.push(pattern);
}
result.push(propertyGroup);
});
return result;
}
for (let pattern of globPatterns) {
let indexOfGlob = pattern.indexOf('*');
if (indexOfGlob === -1) {
result.push(pattern);
}
else {
const {arrayProp, arrayPropName} = getArrayProperty(object, pattern, indexOfGlob);
arrayProp.forEach((v, i) => {
const pp = `${arrayPropName}[${i}]`;
if (indexOfGlob < pattern.length - 1)
result.push(pp + pattern.substring(indexOfGlob + 1));
else if (typeof v === 'object')
Object.getOwnPropertyNames(v).forEach(n => result.push(`${pp}.${n}`));
else
result.push(pp);
});
}
}
return result;
} | [
"function",
"expandPropertyNameGlobs",
"(",
"object",
",",
"globPatterns",
")",
"{",
"const",
"result",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"globPatterns",
".",
"length",
")",
"return",
"result",
";",
"const",
"arrayGroupPattern",
"=",
"globPatterns",
"[",
"... | Takes an array of property patterns and expands any glob pattern it finds
based on the provided object.
@private
@param object
@param globPatterns
@returns {Array} | [
"Takes",
"an",
"array",
"of",
"property",
"patterns",
"and",
"expands",
"any",
"glob",
"pattern",
"it",
"finds",
"based",
"on",
"the",
"provided",
"object",
"."
] | 7a372deebf7d7326e3639ddb01c9ce6224fc83d6 | https://github.com/hubiinetwork/nahmii-sdk/blob/7a372deebf7d7326e3639ddb01c9ce6224fc83d6/lib/utils.js#L80-L125 |
34,264 | hubiinetwork/nahmii-sdk | lib/utils.js | fromRpcSig | function fromRpcSig(flatSig) {
const expandedSig = ethutil.fromRpcSig(flatSig);
return {
s: ethutil.bufferToHex(expandedSig.s),
r: ethutil.bufferToHex(expandedSig.r),
v: expandedSig.v
};
} | javascript | function fromRpcSig(flatSig) {
const expandedSig = ethutil.fromRpcSig(flatSig);
return {
s: ethutil.bufferToHex(expandedSig.s),
r: ethutil.bufferToHex(expandedSig.r),
v: expandedSig.v
};
} | [
"function",
"fromRpcSig",
"(",
"flatSig",
")",
"{",
"const",
"expandedSig",
"=",
"ethutil",
".",
"fromRpcSig",
"(",
"flatSig",
")",
";",
"return",
"{",
"s",
":",
"ethutil",
".",
"bufferToHex",
"(",
"expandedSig",
".",
"s",
")",
",",
"r",
":",
"ethutil",
... | Takes a flat format RPC signature and returns it in expanded form, with
s, r in hex string form, and v a number
@param {String} flatSig Flat form signature
@returns {Object} Expanded form signature | [
"Takes",
"a",
"flat",
"format",
"RPC",
"signature",
"and",
"returns",
"it",
"in",
"expanded",
"form",
"with",
"s",
"r",
"in",
"hex",
"string",
"form",
"and",
"v",
"a",
"number"
] | 7a372deebf7d7326e3639ddb01c9ce6224fc83d6 | https://github.com/hubiinetwork/nahmii-sdk/blob/7a372deebf7d7326e3639ddb01c9ce6224fc83d6/lib/utils.js#L177-L185 |
34,265 | hubiinetwork/nahmii-sdk | lib/utils.js | isSignedBy | function isSignedBy(message, signature, address) {
try {
const ethMessage = ethHash(message);
return caseInsensitiveCompare(recoverAddress(ethMessage, signature), prefix0x(address));
}
catch (e) {
return false;
}
} | javascript | function isSignedBy(message, signature, address) {
try {
const ethMessage = ethHash(message);
return caseInsensitiveCompare(recoverAddress(ethMessage, signature), prefix0x(address));
}
catch (e) {
return false;
}
} | [
"function",
"isSignedBy",
"(",
"message",
",",
"signature",
",",
"address",
")",
"{",
"try",
"{",
"const",
"ethMessage",
"=",
"ethHash",
"(",
"message",
")",
";",
"return",
"caseInsensitiveCompare",
"(",
"recoverAddress",
"(",
"ethMessage",
",",
"signature",
"... | Checks whether or not the address is the address of the private key used to
sign the specified message and signature.
@param {String} message - A message hash as a hexadecimal string
@param {Object} signature - The signature of the message given as V, R and S properties
@param {String} address - A hexadecimal representation of the address to verify
@returns {Boolean} True if address belongs to the signed message | [
"Checks",
"whether",
"or",
"not",
"the",
"address",
"is",
"the",
"address",
"of",
"the",
"private",
"key",
"used",
"to",
"sign",
"the",
"specified",
"message",
"and",
"signature",
"."
] | 7a372deebf7d7326e3639ddb01c9ce6224fc83d6 | https://github.com/hubiinetwork/nahmii-sdk/blob/7a372deebf7d7326e3639ddb01c9ce6224fc83d6/lib/utils.js#L243-L251 |
34,266 | SimpleRegex/SRL-JavaScript | lib/Language/Helpers/methodMatch.js | methodMatch | function methodMatch(part) {
let maxMatch = null
let maxMatchCount = 0
// Go through each mapper and check if the name matches. Then, take the highest match to avoid matching
// 'any', if 'any character' was given, and so on.
Object.keys(mapper).forEach((key) => {
const regex = new RegExp(`^(${key.replace(' ', ') (')})`, 'i')
const matches = part.match(regex)
const count = matches ? matches.length : 0
if (count > maxMatchCount) {
maxMatchCount = count
maxMatch = key
}
})
if (maxMatch) {
// We've got a match. Create the desired object and populate it.
const item = mapper[maxMatch]
return new item['class'](maxMatch, item.method, buildQuery)
}
throw new SyntaxException(`Invalid method: ${part}`)
} | javascript | function methodMatch(part) {
let maxMatch = null
let maxMatchCount = 0
// Go through each mapper and check if the name matches. Then, take the highest match to avoid matching
// 'any', if 'any character' was given, and so on.
Object.keys(mapper).forEach((key) => {
const regex = new RegExp(`^(${key.replace(' ', ') (')})`, 'i')
const matches = part.match(regex)
const count = matches ? matches.length : 0
if (count > maxMatchCount) {
maxMatchCount = count
maxMatch = key
}
})
if (maxMatch) {
// We've got a match. Create the desired object and populate it.
const item = mapper[maxMatch]
return new item['class'](maxMatch, item.method, buildQuery)
}
throw new SyntaxException(`Invalid method: ${part}`)
} | [
"function",
"methodMatch",
"(",
"part",
")",
"{",
"let",
"maxMatch",
"=",
"null",
"let",
"maxMatchCount",
"=",
"0",
"// Go through each mapper and check if the name matches. Then, take the highest match to avoid matching",
"// 'any', if 'any character' was given, and so on.",
"Object... | Match a string part to a method. Please note that the string must start with a method.
@param {string} part
@throws {SyntaxException} If no method was found, a SyntaxException will be thrown.
@return {method} | [
"Match",
"a",
"string",
"part",
"to",
"a",
"method",
".",
"Please",
"note",
"that",
"the",
"string",
"must",
"start",
"with",
"a",
"method",
"."
] | eb2f0576ec49076e95fc2adec57e10d83c24d438 | https://github.com/SimpleRegex/SRL-JavaScript/blob/eb2f0576ec49076e95fc2adec57e10d83c24d438/lib/Language/Helpers/methodMatch.js#L75-L100 |
34,267 | jahting/pnltri.js | build/pnltri.js | function () { // <<<<<< public
var newMono, newMonoTo, toFirstOutSeg, fromRevSeg;
for ( var i = 0, j = this.segments.length; i < j; i++) {
newMono = this.segments[i];
if ( this.PolyLeftArr[newMono.chainId] ) {
// preserve winding order
newMonoTo = newMono.vTo; // target of segment
newMono.mprev = newMono.sprev; // doubly linked list for monotone chains (sub-polygons)
newMono.mnext = newMono.snext;
} else {
// reverse winding order
newMonoTo = newMono.vFrom;
newMono = newMono.snext;
newMono.mprev = newMono.snext;
newMono.mnext = newMono.sprev;
}
if ( fromRevSeg = newMono.vFrom.lastInDiag ) { // assignment !
fromRevSeg.mnext = newMono;
newMono.mprev = fromRevSeg;
newMono.vFrom.lastInDiag = null; // cleanup
}
if ( toFirstOutSeg = newMonoTo.firstOutDiag ) { // assignment !
toFirstOutSeg.mprev = newMono;
newMono.mnext = toFirstOutSeg;
newMonoTo.firstOutDiag = null; // cleanup
}
}
} | javascript | function () { // <<<<<< public
var newMono, newMonoTo, toFirstOutSeg, fromRevSeg;
for ( var i = 0, j = this.segments.length; i < j; i++) {
newMono = this.segments[i];
if ( this.PolyLeftArr[newMono.chainId] ) {
// preserve winding order
newMonoTo = newMono.vTo; // target of segment
newMono.mprev = newMono.sprev; // doubly linked list for monotone chains (sub-polygons)
newMono.mnext = newMono.snext;
} else {
// reverse winding order
newMonoTo = newMono.vFrom;
newMono = newMono.snext;
newMono.mprev = newMono.snext;
newMono.mnext = newMono.sprev;
}
if ( fromRevSeg = newMono.vFrom.lastInDiag ) { // assignment !
fromRevSeg.mnext = newMono;
newMono.mprev = fromRevSeg;
newMono.vFrom.lastInDiag = null; // cleanup
}
if ( toFirstOutSeg = newMonoTo.firstOutDiag ) { // assignment !
toFirstOutSeg.mprev = newMono;
newMono.mnext = toFirstOutSeg;
newMonoTo.firstOutDiag = null; // cleanup
}
}
} | [
"function",
"(",
")",
"{",
"// <<<<<< public",
"var",
"newMono",
",",
"newMonoTo",
",",
"toFirstOutSeg",
",",
"fromRevSeg",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"j",
"=",
"this",
".",
"segments",
".",
"length",
";",
"i",
"<",
"j",
";",
"i",
... | Generate the uni-y-monotone sub-polygons from the trapezoidation of the polygon. | [
"Generate",
"the",
"uni",
"-",
"y",
"-",
"monotone",
"sub",
"-",
"polygons",
"from",
"the",
"trapezoidation",
"of",
"the",
"polygon",
"."
] | 72f162d39da3a84c78ff16181940da79f3f50ba9 | https://github.com/jahting/pnltri.js/blob/72f162d39da3a84c78ff16181940da79f3f50ba9/build/pnltri.js#L350-L377 | |
34,268 | jahting/pnltri.js | build/pnltri.js | function () { // <<<<<<<<<< public
var normedMonoChains = this.polyData.getMonoSubPolys();
this.polyData.clearTriangles();
for ( var i=0; i<normedMonoChains.length; i++ ) {
// loop through uni-y-monotone chains
// => monoPosmin is next to monoPosmax (left or right)
var monoPosmax = normedMonoChains[i];
var prevMono = monoPosmax.mprev;
var nextMono = monoPosmax.mnext;
if ( nextMono.mnext == prevMono ) { // already a triangle
this.polyData.addTriangle( monoPosmax.vFrom, nextMono.vFrom, prevMono.vFrom );
} else { // triangulate the polygon
this.triangulate_monotone_polygon( monoPosmax );
}
}
} | javascript | function () { // <<<<<<<<<< public
var normedMonoChains = this.polyData.getMonoSubPolys();
this.polyData.clearTriangles();
for ( var i=0; i<normedMonoChains.length; i++ ) {
// loop through uni-y-monotone chains
// => monoPosmin is next to monoPosmax (left or right)
var monoPosmax = normedMonoChains[i];
var prevMono = monoPosmax.mprev;
var nextMono = monoPosmax.mnext;
if ( nextMono.mnext == prevMono ) { // already a triangle
this.polyData.addTriangle( monoPosmax.vFrom, nextMono.vFrom, prevMono.vFrom );
} else { // triangulate the polygon
this.triangulate_monotone_polygon( monoPosmax );
}
}
} | [
"function",
"(",
")",
"{",
"// <<<<<<<<<< public",
"var",
"normedMonoChains",
"=",
"this",
".",
"polyData",
".",
"getMonoSubPolys",
"(",
")",
";",
"this",
".",
"polyData",
".",
"clearTriangles",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
... | Pass each uni-y-monotone polygon with start at Y-max for greedy triangulation. | [
"Pass",
"each",
"uni",
"-",
"y",
"-",
"monotone",
"polygon",
"with",
"start",
"at",
"Y",
"-",
"max",
"for",
"greedy",
"triangulation",
"."
] | 72f162d39da3a84c78ff16181940da79f3f50ba9 | https://github.com/jahting/pnltri.js/blob/72f162d39da3a84c78ff16181940da79f3f50ba9/build/pnltri.js#L1897-L1913 | |
34,269 | 3rd-Eden/FlashPolicyFileServer | index.js | Server | function Server (options, origins) {
var me = this;
this.origins = origins || ['*:*'];
this.port = 843;
this.log = console.log;
// merge `this` with the options
Object.keys(options).forEach(function (key) {
me[key] && (me[key] = options[key])
});
// create the net server
this.socket = net.createServer(function createServer (socket) {
socket.on('error', function socketError () {
me.responder.call(me, socket);
});
me.responder.call(me, socket);
});
// Listen for errors as the port might be blocked because we do not have root priv.
this.socket.on('error', function serverError (err) {
// Special and common case error handling
if (err.errno == 13) {
me.log && me.log(
'Unable to listen to port `' + me.port + '` as your Node.js instance does not have root privileges. ' +
(
me.server
? 'The Flash Policy File requests will only be served inline over the supplied HTTP server. Inline serving is slower than a dedicated server instance.'
: 'No fallback server supplied, we will be unable to answer Flash Policy File requests.'
)
);
me.emit('connect_failed', err);
me.socket.removeAllListeners();
delete me.socket;
} else {
me.log && me.log('FlashPolicyFileServer received an error event:\n' + (err.message ? err.message : err));
}
});
this.socket.on('timeout', function serverTimeout () {});
this.socket.on('close', function serverClosed (err) {
err && me.log && me.log('Server closing due to an error: \n' + (err.message ? err.message : err));
if (me.server) {
// Remove the inline policy listener if we close down
// but only when the server was `online` (see listen prototype)
if (me.server['@'] && me.server.online) {
me.server.removeListener('connection', me.server['@']);
}
// not online anymore
delete me.server.online;
}
});
// Compile the initial `buffer`
this.compile();
} | javascript | function Server (options, origins) {
var me = this;
this.origins = origins || ['*:*'];
this.port = 843;
this.log = console.log;
// merge `this` with the options
Object.keys(options).forEach(function (key) {
me[key] && (me[key] = options[key])
});
// create the net server
this.socket = net.createServer(function createServer (socket) {
socket.on('error', function socketError () {
me.responder.call(me, socket);
});
me.responder.call(me, socket);
});
// Listen for errors as the port might be blocked because we do not have root priv.
this.socket.on('error', function serverError (err) {
// Special and common case error handling
if (err.errno == 13) {
me.log && me.log(
'Unable to listen to port `' + me.port + '` as your Node.js instance does not have root privileges. ' +
(
me.server
? 'The Flash Policy File requests will only be served inline over the supplied HTTP server. Inline serving is slower than a dedicated server instance.'
: 'No fallback server supplied, we will be unable to answer Flash Policy File requests.'
)
);
me.emit('connect_failed', err);
me.socket.removeAllListeners();
delete me.socket;
} else {
me.log && me.log('FlashPolicyFileServer received an error event:\n' + (err.message ? err.message : err));
}
});
this.socket.on('timeout', function serverTimeout () {});
this.socket.on('close', function serverClosed (err) {
err && me.log && me.log('Server closing due to an error: \n' + (err.message ? err.message : err));
if (me.server) {
// Remove the inline policy listener if we close down
// but only when the server was `online` (see listen prototype)
if (me.server['@'] && me.server.online) {
me.server.removeListener('connection', me.server['@']);
}
// not online anymore
delete me.server.online;
}
});
// Compile the initial `buffer`
this.compile();
} | [
"function",
"Server",
"(",
"options",
",",
"origins",
")",
"{",
"var",
"me",
"=",
"this",
";",
"this",
".",
"origins",
"=",
"origins",
"||",
"[",
"'*:*'",
"]",
";",
"this",
".",
"port",
"=",
"843",
";",
"this",
".",
"log",
"=",
"console",
".",
"l... | The server that does the Policy File severing
Options:
- `log` false or a function that can output log information, defaults to console.log?
@param {Object} options Options to customize the servers functionality.
@param {Array} origins The origins that are allowed on this server, defaults to `*:*`.
@api public | [
"The",
"server",
"that",
"does",
"the",
"Policy",
"File",
"severing"
] | a3ad25396a63db58afff8d1c1358e1f30458ec37 | https://github.com/3rd-Eden/FlashPolicyFileServer/blob/a3ad25396a63db58afff8d1c1358e1f30458ec37/index.js#L20-L80 |
34,270 | hubiinetwork/nahmii-sdk | lib/settlement/utils.js | determineNonceFromReceipt | function determineNonceFromReceipt(receipt, address) {
const {sender, recipient} = receipt;
return caseInsensitiveCompare(sender.wallet, address) ? sender.nonce : recipient.nonce;
} | javascript | function determineNonceFromReceipt(receipt, address) {
const {sender, recipient} = receipt;
return caseInsensitiveCompare(sender.wallet, address) ? sender.nonce : recipient.nonce;
} | [
"function",
"determineNonceFromReceipt",
"(",
"receipt",
",",
"address",
")",
"{",
"const",
"{",
"sender",
",",
"recipient",
"}",
"=",
"receipt",
";",
"return",
"caseInsensitiveCompare",
"(",
"sender",
".",
"wallet",
",",
"address",
")",
"?",
"sender",
".",
... | Determine the settlement nonce for a wallet.
@param {Receipt} receipt - The receipt object
@param {Address} address - The wallet address
@returns {number} The nonce | [
"Determine",
"the",
"settlement",
"nonce",
"for",
"a",
"wallet",
"."
] | 7a372deebf7d7326e3639ddb01c9ce6224fc83d6 | https://github.com/hubiinetwork/nahmii-sdk/blob/7a372deebf7d7326e3639ddb01c9ce6224fc83d6/lib/settlement/utils.js#L20-L23 |
34,271 | InsideInc/node-pinterest-api | index.js | function(seriesCallback) {
async.eachLimit(groupedPinIds, 50, function(groupOfPinIds, eachCallback) {
var pinIdsString = groupOfPinIds.join(',');
getCache(pinIdsString, true, function (cacheData) {
if (cacheData === null) {
get('http://api.pinterest.com/v3/pidgets/pins/info/?pin_ids=' + pinIdsString, true, function (response) {
putCache(pinIdsString, JSON.stringify(response));
allPinsData = allPinsData.concat(response.data ? response.data : []);
eachCallback();
return;
});
} else {
allPinsData = allPinsData.concat(cacheData.data ? cacheData.data : []);
eachCallback();
return;
}
});
}, function (err) {
if(err) {
throw err;
}
seriesCallback();
return;
});
} | javascript | function(seriesCallback) {
async.eachLimit(groupedPinIds, 50, function(groupOfPinIds, eachCallback) {
var pinIdsString = groupOfPinIds.join(',');
getCache(pinIdsString, true, function (cacheData) {
if (cacheData === null) {
get('http://api.pinterest.com/v3/pidgets/pins/info/?pin_ids=' + pinIdsString, true, function (response) {
putCache(pinIdsString, JSON.stringify(response));
allPinsData = allPinsData.concat(response.data ? response.data : []);
eachCallback();
return;
});
} else {
allPinsData = allPinsData.concat(cacheData.data ? cacheData.data : []);
eachCallback();
return;
}
});
}, function (err) {
if(err) {
throw err;
}
seriesCallback();
return;
});
} | [
"function",
"(",
"seriesCallback",
")",
"{",
"async",
".",
"eachLimit",
"(",
"groupedPinIds",
",",
"50",
",",
"function",
"(",
"groupOfPinIds",
",",
"eachCallback",
")",
"{",
"var",
"pinIdsString",
"=",
"groupOfPinIds",
".",
"join",
"(",
"','",
")",
";",
"... | get pin data from API | [
"get",
"pin",
"data",
"from",
"API"
] | 74b94fc5ecfc8a52752bcd99b5d25d1223b49692 | https://github.com/InsideInc/node-pinterest-api/blob/74b94fc5ecfc8a52752bcd99b5d25d1223b49692/index.js#L646-L670 | |
34,272 | InsideInc/node-pinterest-api | index.js | function(seriesCallback) {
var userBoardAlreadyAdded = {};
for(var i = 0; i < allPinsData.length; i++) {
var pin = allPinsData[i];
if(pin.board) {
var boardUrlParts = pin.board.url.split('/');
var user = boardUrlParts[1];
var board = boardUrlParts[2];
if(!userBoardAlreadyAdded[user + board]) {
userBoardAlreadyAdded[user + board] = true;
boards.push({user: user, board: board});
}
}
}
seriesCallback();
return;
} | javascript | function(seriesCallback) {
var userBoardAlreadyAdded = {};
for(var i = 0; i < allPinsData.length; i++) {
var pin = allPinsData[i];
if(pin.board) {
var boardUrlParts = pin.board.url.split('/');
var user = boardUrlParts[1];
var board = boardUrlParts[2];
if(!userBoardAlreadyAdded[user + board]) {
userBoardAlreadyAdded[user + board] = true;
boards.push({user: user, board: board});
}
}
}
seriesCallback();
return;
} | [
"function",
"(",
"seriesCallback",
")",
"{",
"var",
"userBoardAlreadyAdded",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"allPinsData",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"pin",
"=",
"allPinsData",
"[",
"i",
"]... | create list of boards that the pins belong to | [
"create",
"list",
"of",
"boards",
"that",
"the",
"pins",
"belong",
"to"
] | 74b94fc5ecfc8a52752bcd99b5d25d1223b49692 | https://github.com/InsideInc/node-pinterest-api/blob/74b94fc5ecfc8a52752bcd99b5d25d1223b49692/index.js#L672-L691 | |
34,273 | InsideInc/node-pinterest-api | index.js | function(seriesCallback) {
if(!obtainDates) {
seriesCallback();
return;
}
var pinDateMaps = [];
async.eachLimit(boards, 5, function(board, eachCallback) {
getDatesForBoardPinsFromRss(board.user, board.board, function(result) {
pinDateMaps.push(result);
eachCallback();
});
}, function (err) {
if(err) {
throw err;
}
var pinDateMap = mergeMaps(pinDateMaps);
for (var i = 0; i < allPinsData.length; i++) {
allPinsData[i].created_at = null;
allPinsData[i].created_at_source = null;
if (pinDateMap[allPinsData[i].id]) {
allPinsData[i].created_at = pinDateMap[allPinsData[i].id];
allPinsData[i].created_at_source = 'rss';
} else {
pinsThatNeedScrapedDates.push(allPinsData[i].id);
}
}
seriesCallback();
return;
});
} | javascript | function(seriesCallback) {
if(!obtainDates) {
seriesCallback();
return;
}
var pinDateMaps = [];
async.eachLimit(boards, 5, function(board, eachCallback) {
getDatesForBoardPinsFromRss(board.user, board.board, function(result) {
pinDateMaps.push(result);
eachCallback();
});
}, function (err) {
if(err) {
throw err;
}
var pinDateMap = mergeMaps(pinDateMaps);
for (var i = 0; i < allPinsData.length; i++) {
allPinsData[i].created_at = null;
allPinsData[i].created_at_source = null;
if (pinDateMap[allPinsData[i].id]) {
allPinsData[i].created_at = pinDateMap[allPinsData[i].id];
allPinsData[i].created_at_source = 'rss';
} else {
pinsThatNeedScrapedDates.push(allPinsData[i].id);
}
}
seriesCallback();
return;
});
} | [
"function",
"(",
"seriesCallback",
")",
"{",
"if",
"(",
"!",
"obtainDates",
")",
"{",
"seriesCallback",
"(",
")",
";",
"return",
";",
"}",
"var",
"pinDateMaps",
"=",
"[",
"]",
";",
"async",
".",
"eachLimit",
"(",
"boards",
",",
"5",
",",
"function",
... | get what dates we can for pins from the board RSS feeds | [
"get",
"what",
"dates",
"we",
"can",
"for",
"pins",
"from",
"the",
"board",
"RSS",
"feeds"
] | 74b94fc5ecfc8a52752bcd99b5d25d1223b49692 | https://github.com/InsideInc/node-pinterest-api/blob/74b94fc5ecfc8a52752bcd99b5d25d1223b49692/index.js#L693-L726 | |
34,274 | InsideInc/node-pinterest-api | index.js | function(seriesCallback) {
if(!obtainDates) {
seriesCallback();
return;
}
getDatesForPinsFromScraping(pinsThatNeedScrapedDates, null, function (pinDateMap) {
for (var i = 0; i < allPinsData.length; i++) {
if (allPinsData[i].created_at == null && pinDateMap[allPinsData[i].id] && pinDateMap[allPinsData[i].id].date) {
allPinsData[i].created_at = pinDateMap[allPinsData[i].id].date;
allPinsData[i].created_at_source = pinDateMap[allPinsData[i].id].source;
}
}
seriesCallback();
return;
});
} | javascript | function(seriesCallback) {
if(!obtainDates) {
seriesCallback();
return;
}
getDatesForPinsFromScraping(pinsThatNeedScrapedDates, null, function (pinDateMap) {
for (var i = 0; i < allPinsData.length; i++) {
if (allPinsData[i].created_at == null && pinDateMap[allPinsData[i].id] && pinDateMap[allPinsData[i].id].date) {
allPinsData[i].created_at = pinDateMap[allPinsData[i].id].date;
allPinsData[i].created_at_source = pinDateMap[allPinsData[i].id].source;
}
}
seriesCallback();
return;
});
} | [
"function",
"(",
"seriesCallback",
")",
"{",
"if",
"(",
"!",
"obtainDates",
")",
"{",
"seriesCallback",
"(",
")",
";",
"return",
";",
"}",
"getDatesForPinsFromScraping",
"(",
"pinsThatNeedScrapedDates",
",",
"null",
",",
"function",
"(",
"pinDateMap",
")",
"{"... | get remaining dates by scraping | [
"get",
"remaining",
"dates",
"by",
"scraping"
] | 74b94fc5ecfc8a52752bcd99b5d25d1223b49692 | https://github.com/InsideInc/node-pinterest-api/blob/74b94fc5ecfc8a52752bcd99b5d25d1223b49692/index.js#L728-L744 | |
34,275 | jpederson/Squirrel.js | jquery.squirrel.js | stash | function stash(storage, storageKey, key, value) {
// get the squirrel storage object.
var store = window.JSON.parse(storage.getItem(storageKey));
// if it doesn't exist, create an empty object.
if (store === null) {
store = {};
}
// if a value isn't specified.
if (isUndefined(value) || value === null) {
// return the store value if the store value exists; otherwise, null.
return !isUndefined(store[key]) ? store[key] : null;
}
// if a value is specified.
// create an append object literal.
var append = {};
// add the new value to the object that we'll append to the store object.
append[key] = value;
// extend the squirrel store object.
// in ES6 this can be shortened to just $.extend(store, {[key]: value}), as there would be no need
// to create a temporary storage object.
$.extend(store, append);
// re-session the squirrel store again.
storage.setItem(storageKey, window.JSON.stringify(store));
// return the value.
return value;
} | javascript | function stash(storage, storageKey, key, value) {
// get the squirrel storage object.
var store = window.JSON.parse(storage.getItem(storageKey));
// if it doesn't exist, create an empty object.
if (store === null) {
store = {};
}
// if a value isn't specified.
if (isUndefined(value) || value === null) {
// return the store value if the store value exists; otherwise, null.
return !isUndefined(store[key]) ? store[key] : null;
}
// if a value is specified.
// create an append object literal.
var append = {};
// add the new value to the object that we'll append to the store object.
append[key] = value;
// extend the squirrel store object.
// in ES6 this can be shortened to just $.extend(store, {[key]: value}), as there would be no need
// to create a temporary storage object.
$.extend(store, append);
// re-session the squirrel store again.
storage.setItem(storageKey, window.JSON.stringify(store));
// return the value.
return value;
} | [
"function",
"stash",
"(",
"storage",
",",
"storageKey",
",",
"key",
",",
"value",
")",
"{",
"// get the squirrel storage object.",
"var",
"store",
"=",
"window",
".",
"JSON",
".",
"parse",
"(",
"storage",
".",
"getItem",
"(",
"storageKey",
")",
")",
";",
"... | METHODS stash or grab a value from our session store object. | [
"METHODS",
"stash",
"or",
"grab",
"a",
"value",
"from",
"our",
"session",
"store",
"object",
"."
] | 9b8897f2ec03afcf7d4262706a6169c6c196c7ee | https://github.com/jpederson/Squirrel.js/blob/9b8897f2ec03afcf7d4262706a6169c6c196c7ee/jquery.squirrel.js#L295-L333 |
34,276 | SimpleRegex/SRL-JavaScript | lib/Language/Helpers/parseParentheses.js | createLiterallyObjects | function createLiterallyObjects(query, openPos, stringPositions) {
const firstRaw = query.substr(0, openPos)
const result = [firstRaw.trim()]
let pointer = 0
stringPositions.forEach((stringPosition) => {
if (!stringPosition.end) {
throw new SyntaxException('Invalid string ending found.')
}
if (stringPosition.end < firstRaw.length) {
// At least one string exists in first part, create a new object.
// Remove the last part, since this wasn't parsed.
result.pop()
// Add part between pointer and string occurrence.
result.push(firstRaw.substr(pointer, stringPosition.start - pointer).trim())
// Add the string as object.
result.push(new Literally(firstRaw.substr(
stringPosition.start + 1,
stringPosition.end - stringPosition.start
)))
result.push(firstRaw.substr(stringPosition.end + 2).trim())
pointer = stringPosition.end + 2
}
})
return result
} | javascript | function createLiterallyObjects(query, openPos, stringPositions) {
const firstRaw = query.substr(0, openPos)
const result = [firstRaw.trim()]
let pointer = 0
stringPositions.forEach((stringPosition) => {
if (!stringPosition.end) {
throw new SyntaxException('Invalid string ending found.')
}
if (stringPosition.end < firstRaw.length) {
// At least one string exists in first part, create a new object.
// Remove the last part, since this wasn't parsed.
result.pop()
// Add part between pointer and string occurrence.
result.push(firstRaw.substr(pointer, stringPosition.start - pointer).trim())
// Add the string as object.
result.push(new Literally(firstRaw.substr(
stringPosition.start + 1,
stringPosition.end - stringPosition.start
)))
result.push(firstRaw.substr(stringPosition.end + 2).trim())
pointer = stringPosition.end + 2
}
})
return result
} | [
"function",
"createLiterallyObjects",
"(",
"query",
",",
"openPos",
",",
"stringPositions",
")",
"{",
"const",
"firstRaw",
"=",
"query",
".",
"substr",
"(",
"0",
",",
"openPos",
")",
"const",
"result",
"=",
"[",
"firstRaw",
".",
"trim",
"(",
")",
"]",
"l... | Replace all "literal strings" with a Literally object to simplify parsing later on.
@param {string} string
@param {number} openPos
@param {array} stringPositions
@return {array}
@throws {SyntaxException} | [
"Replace",
"all",
"literal",
"strings",
"with",
"a",
"Literally",
"object",
"to",
"simplify",
"parsing",
"later",
"on",
"."
] | eb2f0576ec49076e95fc2adec57e10d83c24d438 | https://github.com/SimpleRegex/SRL-JavaScript/blob/eb2f0576ec49076e95fc2adec57e10d83c24d438/lib/Language/Helpers/parseParentheses.js#L118-L150 |
34,277 | nhn/tui.dom | src/js/domevent.js | memorizeHandler | function memorizeHandler(element, type, keyFn, valueFn) {
const map = safeEvent(element, type);
let items = map.get(keyFn);
if (items) {
items.push(valueFn);
} else {
items = [valueFn];
map.set(keyFn, items);
}
} | javascript | function memorizeHandler(element, type, keyFn, valueFn) {
const map = safeEvent(element, type);
let items = map.get(keyFn);
if (items) {
items.push(valueFn);
} else {
items = [valueFn];
map.set(keyFn, items);
}
} | [
"function",
"memorizeHandler",
"(",
"element",
",",
"type",
",",
"keyFn",
",",
"valueFn",
")",
"{",
"const",
"map",
"=",
"safeEvent",
"(",
"element",
",",
"type",
")",
";",
"let",
"items",
"=",
"map",
".",
"get",
"(",
"keyFn",
")",
";",
"if",
"(",
... | Memorize DOM event handler for unbinding
@param {HTMLElement} element - element to bind events
@param {string} type - events name
@param {function} keyFn - handler function that user passed at on() use
@param {function} valueFn - handler function that wrapped by domevent for
implementing some features | [
"Memorize",
"DOM",
"event",
"handler",
"for",
"unbinding"
] | beafe74afb8f647d770e202894ecc9c2dc0ca2b5 | https://github.com/nhn/tui.dom/blob/beafe74afb8f647d770e202894ecc9c2dc0ca2b5/src/js/domevent.js#L50-L60 |
34,278 | nhn/tui.dom | src/js/domevent.js | bindEvent | function bindEvent(element, type, handler, context) {
/**
* Event handler
* @param {Event} e - event object
*/
function eventHandler(e) {
handler.call(context || element, e || window.event);
}
/**
* Event handler for normalize mouseenter event
* @param {MouseEvent} e - event object
*/
function mouseEnterHandler(e) {
e = e || window.event;
if (checkMouse(element, e)) {
eventHandler(e);
}
}
if ('addEventListener' in element) {
if (type === 'mouseenter' || type === 'mouseleave') {
type = (type === 'mouseenter') ? 'mouseover' : 'mouseout';
element.addEventListener(type, mouseEnterHandler);
memorizeHandler(element, type, handler, mouseEnterHandler);
} else {
element.addEventListener(type, eventHandler);
memorizeHandler(element, type, handler, eventHandler);
}
} else if ('attachEvent' in element) {
element.attachEvent(`on${type}`, eventHandler);
memorizeHandler(element, type, handler, eventHandler);
}
} | javascript | function bindEvent(element, type, handler, context) {
/**
* Event handler
* @param {Event} e - event object
*/
function eventHandler(e) {
handler.call(context || element, e || window.event);
}
/**
* Event handler for normalize mouseenter event
* @param {MouseEvent} e - event object
*/
function mouseEnterHandler(e) {
e = e || window.event;
if (checkMouse(element, e)) {
eventHandler(e);
}
}
if ('addEventListener' in element) {
if (type === 'mouseenter' || type === 'mouseleave') {
type = (type === 'mouseenter') ? 'mouseover' : 'mouseout';
element.addEventListener(type, mouseEnterHandler);
memorizeHandler(element, type, handler, mouseEnterHandler);
} else {
element.addEventListener(type, eventHandler);
memorizeHandler(element, type, handler, eventHandler);
}
} else if ('attachEvent' in element) {
element.attachEvent(`on${type}`, eventHandler);
memorizeHandler(element, type, handler, eventHandler);
}
} | [
"function",
"bindEvent",
"(",
"element",
",",
"type",
",",
"handler",
",",
"context",
")",
"{",
"/**\n * Event handler\n * @param {Event} e - event object\n */",
"function",
"eventHandler",
"(",
"e",
")",
"{",
"handler",
".",
"call",
"(",
"context",
"||",
... | Bind DOM events
@param {HTMLElement} element - element to bind events
@param {string} type - events name
@param {function} handler - handler function or context for handler
method
@param {object} [context] context - context for handler method. | [
"Bind",
"DOM",
"events"
] | beafe74afb8f647d770e202894ecc9c2dc0ca2b5 | https://github.com/nhn/tui.dom/blob/beafe74afb8f647d770e202894ecc9c2dc0ca2b5/src/js/domevent.js#L80-L114 |
34,279 | nhn/tui.dom | src/js/domevent.js | mouseEnterHandler | function mouseEnterHandler(e) {
e = e || window.event;
if (checkMouse(element, e)) {
eventHandler(e);
}
} | javascript | function mouseEnterHandler(e) {
e = e || window.event;
if (checkMouse(element, e)) {
eventHandler(e);
}
} | [
"function",
"mouseEnterHandler",
"(",
"e",
")",
"{",
"e",
"=",
"e",
"||",
"window",
".",
"event",
";",
"if",
"(",
"checkMouse",
"(",
"element",
",",
"e",
")",
")",
"{",
"eventHandler",
"(",
"e",
")",
";",
"}",
"}"
] | Event handler for normalize mouseenter event
@param {MouseEvent} e - event object | [
"Event",
"handler",
"for",
"normalize",
"mouseenter",
"event"
] | beafe74afb8f647d770e202894ecc9c2dc0ca2b5 | https://github.com/nhn/tui.dom/blob/beafe74afb8f647d770e202894ecc9c2dc0ca2b5/src/js/domevent.js#L93-L99 |
34,280 | nhn/tui.dom | src/js/domevent.js | unbindEvent | function unbindEvent(element, type, handler) {
const events = safeEvent(element, type);
const items = events.get(handler);
if (!items) {
return;
}
forgetHandler(element, type, handler);
util.forEach(items, func => {
if ('removeEventListener' in element) {
element.removeEventListener(type, func);
} else if ('detachEvent' in element) {
element.detachEvent(`on${type}`, func);
}
});
} | javascript | function unbindEvent(element, type, handler) {
const events = safeEvent(element, type);
const items = events.get(handler);
if (!items) {
return;
}
forgetHandler(element, type, handler);
util.forEach(items, func => {
if ('removeEventListener' in element) {
element.removeEventListener(type, func);
} else if ('detachEvent' in element) {
element.detachEvent(`on${type}`, func);
}
});
} | [
"function",
"unbindEvent",
"(",
"element",
",",
"type",
",",
"handler",
")",
"{",
"const",
"events",
"=",
"safeEvent",
"(",
"element",
",",
"type",
")",
";",
"const",
"items",
"=",
"events",
".",
"get",
"(",
"handler",
")",
";",
"if",
"(",
"!",
"item... | Unbind DOM events
@param {HTMLElement} element - element to unbind events
@param {string} type - events name
@param {function} handler - handler function or context for handler
method | [
"Unbind",
"DOM",
"events"
] | beafe74afb8f647d770e202894ecc9c2dc0ca2b5 | https://github.com/nhn/tui.dom/blob/beafe74afb8f647d770e202894ecc9c2dc0ca2b5/src/js/domevent.js#L123-L140 |
34,281 | lukaaash/sftp-ws | examples/console-client/index.js | execute | function execute(context, action) {
if (!remote) return fail(context, "Not connected to a server");
// prepare source path
if (context.args.length < 1) return fail(context, "Remote path missing");
var path = remote.join(remotePath, context.args[0]);
action(path);
} | javascript | function execute(context, action) {
if (!remote) return fail(context, "Not connected to a server");
// prepare source path
if (context.args.length < 1) return fail(context, "Remote path missing");
var path = remote.join(remotePath, context.args[0]);
action(path);
} | [
"function",
"execute",
"(",
"context",
",",
"action",
")",
"{",
"if",
"(",
"!",
"remote",
")",
"return",
"fail",
"(",
"context",
",",
"\"Not connected to a server\"",
")",
";",
"// prepare source path\r",
"if",
"(",
"context",
".",
"args",
".",
"length",
"<"... | execute a simple action on a remote path | [
"execute",
"a",
"simple",
"action",
"on",
"a",
"remote",
"path"
] | ec48b5974f13233285483201c1808d7c3b3045c3 | https://github.com/lukaaash/sftp-ws/blob/ec48b5974f13233285483201c1808d7c3b3045c3/examples/console-client/index.js#L267-L274 |
34,282 | lukaaash/sftp-ws | examples/console-client/index.js | list | function list(context, err, items, paths) {
if (err) return fail(context, err);
var long = context.options["l"];
if (typeof long === "undefined") long = (context.command.slice(-3) === "dir");
items.forEach(function (item) {
if (item.filename == "." || item.filename == "..") return;
if (paths) {
shell.write(item.path);
} else if (long) {
shell.write(item.longname);
} else {
shell.write(item.filename);
}
});
context.end();
} | javascript | function list(context, err, items, paths) {
if (err) return fail(context, err);
var long = context.options["l"];
if (typeof long === "undefined") long = (context.command.slice(-3) === "dir");
items.forEach(function (item) {
if (item.filename == "." || item.filename == "..") return;
if (paths) {
shell.write(item.path);
} else if (long) {
shell.write(item.longname);
} else {
shell.write(item.filename);
}
});
context.end();
} | [
"function",
"list",
"(",
"context",
",",
"err",
",",
"items",
",",
"paths",
")",
"{",
"if",
"(",
"err",
")",
"return",
"fail",
"(",
"context",
",",
"err",
")",
";",
"var",
"long",
"=",
"context",
".",
"options",
"[",
"\"l\"",
"]",
";",
"if",
"(",... | display a list of items | [
"display",
"a",
"list",
"of",
"items"
] | ec48b5974f13233285483201c1808d7c3b3045c3 | https://github.com/lukaaash/sftp-ws/blob/ec48b5974f13233285483201c1808d7c3b3045c3/examples/console-client/index.js#L277-L297 |
34,283 | lukaaash/sftp-ws | examples/console-client/index.js | done | function done(context, err, message) {
if (err) return fail(context, err);
if (typeof message !== "undefined") shell.write(message);
context.end();
} | javascript | function done(context, err, message) {
if (err) return fail(context, err);
if (typeof message !== "undefined") shell.write(message);
context.end();
} | [
"function",
"done",
"(",
"context",
",",
"err",
",",
"message",
")",
"{",
"if",
"(",
"err",
")",
"return",
"fail",
"(",
"context",
",",
"err",
")",
";",
"if",
"(",
"typeof",
"message",
"!==",
"\"undefined\"",
")",
"shell",
".",
"write",
"(",
"message... | finish command successfully or with an error | [
"finish",
"command",
"successfully",
"or",
"with",
"an",
"error"
] | ec48b5974f13233285483201c1808d7c3b3045c3 | https://github.com/lukaaash/sftp-ws/blob/ec48b5974f13233285483201c1808d7c3b3045c3/examples/console-client/index.js#L327-L331 |
34,284 | lukaaash/sftp-ws | examples/console-client/index.js | fail | function fail(context, err) {
var message;
switch (err.code) {
case "ENOENT":
message = err.path + ": No such file or directory";
break;
case "ENOSYS":
message = "Command not supported";
break;
default:
message = err["description"] || err.message;
break;
}
return context.fail(message);
} | javascript | function fail(context, err) {
var message;
switch (err.code) {
case "ENOENT":
message = err.path + ": No such file or directory";
break;
case "ENOSYS":
message = "Command not supported";
break;
default:
message = err["description"] || err.message;
break;
}
return context.fail(message);
} | [
"function",
"fail",
"(",
"context",
",",
"err",
")",
"{",
"var",
"message",
";",
"switch",
"(",
"err",
".",
"code",
")",
"{",
"case",
"\"ENOENT\"",
":",
"message",
"=",
"err",
".",
"path",
"+",
"\": No such file or directory\"",
";",
"break",
";",
"case"... | fail command with an error message | [
"fail",
"command",
"with",
"an",
"error",
"message"
] | ec48b5974f13233285483201c1808d7c3b3045c3 | https://github.com/lukaaash/sftp-ws/blob/ec48b5974f13233285483201c1808d7c3b3045c3/examples/console-client/index.js#L334-L349 |
34,285 | leodido/luhn.js | gulpfile.babel.js | umd | function umd() {
let bundler = browserify(src, { debug: true, standalone: 'luhn' })
.transform(babelify) // .configure({ optional: ['runtime'] })
.bundle();
return bundler
.pipe(source(pack.main)) // gives streaming vinyl file object
.pipe(buffer()) // convert from streaming to buffered vinyl file object
.pipe(sourcemaps.init({ loadMaps: true })) // loads map from browserify file
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./'));
} | javascript | function umd() {
let bundler = browserify(src, { debug: true, standalone: 'luhn' })
.transform(babelify) // .configure({ optional: ['runtime'] })
.bundle();
return bundler
.pipe(source(pack.main)) // gives streaming vinyl file object
.pipe(buffer()) // convert from streaming to buffered vinyl file object
.pipe(sourcemaps.init({ loadMaps: true })) // loads map from browserify file
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./'));
} | [
"function",
"umd",
"(",
")",
"{",
"let",
"bundler",
"=",
"browserify",
"(",
"src",
",",
"{",
"debug",
":",
"true",
",",
"standalone",
":",
"'luhn'",
"}",
")",
".",
"transform",
"(",
"babelify",
")",
"// .configure({ optional: ['runtime'] })",
".",
"bundle",
... | umd standalone library with sourcemaps | [
"umd",
"standalone",
"library",
"with",
"sourcemaps"
] | ef24d03e0e7f56ba6bafde0f966813ecb8cf7419 | https://github.com/leodido/luhn.js/blob/ef24d03e0e7f56ba6bafde0f966813ecb8cf7419/gulpfile.babel.js#L33-L44 |
34,286 | leodido/luhn.js | gulpfile.babel.js | min | function min() {
return gulp.src(pack.main)
.pipe(uglify())
.on('error', gutil.log)
.pipe(rename({ extname: minext + '.js' }))
.pipe(gulp.dest('./'));
} | javascript | function min() {
return gulp.src(pack.main)
.pipe(uglify())
.on('error', gutil.log)
.pipe(rename({ extname: minext + '.js' }))
.pipe(gulp.dest('./'));
} | [
"function",
"min",
"(",
")",
"{",
"return",
"gulp",
".",
"src",
"(",
"pack",
".",
"main",
")",
".",
"pipe",
"(",
"uglify",
"(",
")",
")",
".",
"on",
"(",
"'error'",
",",
"gutil",
".",
"log",
")",
".",
"pipe",
"(",
"rename",
"(",
"{",
"extname",... | minified umd standalone library | [
"minified",
"umd",
"standalone",
"library"
] | ef24d03e0e7f56ba6bafde0f966813ecb8cf7419 | https://github.com/leodido/luhn.js/blob/ef24d03e0e7f56ba6bafde0f966813ecb8cf7419/gulpfile.babel.js#L47-L53 |
34,287 | hubiinetwork/nahmii-sdk | lib/event-provider/index.js | subscribeToEvents | function subscribeToEvents() {
const socket = _socket.get(this);
function onEventApiError(error) {
dbg('Event API connection error: ' + JSON.stringify(error));
}
socket.on('pong', (latency) => {
dbg(`Event API latency: ${latency} ms`);
});
socket.on('connect_error', onEventApiError);
socket.on('error', onEventApiError);
socket.on('disconnect', onEventApiError);
socket.on('reconnect_error', onEventApiError);
socket.on('reconnect_failed', () => {
onEventApiError('Reconnecting to the Event API failed');
});
socket.on('new_receipt', receiptJSON => {
const receipt = Receipt.from(receiptJSON, _provider.get(this));
_eventEmitter.get(this).emit(EventNames.newReceipt, receipt);
});
} | javascript | function subscribeToEvents() {
const socket = _socket.get(this);
function onEventApiError(error) {
dbg('Event API connection error: ' + JSON.stringify(error));
}
socket.on('pong', (latency) => {
dbg(`Event API latency: ${latency} ms`);
});
socket.on('connect_error', onEventApiError);
socket.on('error', onEventApiError);
socket.on('disconnect', onEventApiError);
socket.on('reconnect_error', onEventApiError);
socket.on('reconnect_failed', () => {
onEventApiError('Reconnecting to the Event API failed');
});
socket.on('new_receipt', receiptJSON => {
const receipt = Receipt.from(receiptJSON, _provider.get(this));
_eventEmitter.get(this).emit(EventNames.newReceipt, receipt);
});
} | [
"function",
"subscribeToEvents",
"(",
")",
"{",
"const",
"socket",
"=",
"_socket",
".",
"get",
"(",
"this",
")",
";",
"function",
"onEventApiError",
"(",
"error",
")",
"{",
"dbg",
"(",
"'Event API connection error: '",
"+",
"JSON",
".",
"stringify",
"(",
"er... | Subscribes to critical socket.io events and relays nahmii events to any
registered listeners.
Private method, invoke with 'this' bound to provider instance.
@private | [
"Subscribes",
"to",
"critical",
"socket",
".",
"io",
"events",
"and",
"relays",
"nahmii",
"events",
"to",
"any",
"registered",
"listeners",
".",
"Private",
"method",
"invoke",
"with",
"this",
"bound",
"to",
"provider",
"instance",
"."
] | 7a372deebf7d7326e3639ddb01c9ce6224fc83d6 | https://github.com/hubiinetwork/nahmii-sdk/blob/7a372deebf7d7326e3639ddb01c9ce6224fc83d6/lib/event-provider/index.js#L136-L158 |
34,288 | AdamBrodzinski/RedScript | lib/transform.js | function(line) {
// example: def bar(a, b) do
//
// (^\s*) begining of line
// (def|defp) $1 public or private def
// (.*?) $2 in betweend def ... do
// \s* optional space
// do opening keyword (bracket in JS)
// \s*$ end of line
var parts = line.match(/^(\s*)(defp\s|def\s)(.*?)\s*do\s*$/);
if (!parts) return line;
// ^( $1
// \s*[\w$]+ function name
// )
// ( $2 optional params including parens
// \( literal parens
// (.*?) $3 just params
// \) literal parens
// )?
// \s*$ trailing space
var middle = /^(\s*[\w$]+)(\((.*?)\))?\s*$/;
var leading = parts[1];
var funcName = parts[3].trim().match(middle)[1];
var params = parts[3].trim().match(middle)[3] || '';
var _export = (parts[2].trim() === 'def') ? 'export ' : '';
return leading + _export + 'function ' + funcName + '('+ params +') {';
} | javascript | function(line) {
// example: def bar(a, b) do
//
// (^\s*) begining of line
// (def|defp) $1 public or private def
// (.*?) $2 in betweend def ... do
// \s* optional space
// do opening keyword (bracket in JS)
// \s*$ end of line
var parts = line.match(/^(\s*)(defp\s|def\s)(.*?)\s*do\s*$/);
if (!parts) return line;
// ^( $1
// \s*[\w$]+ function name
// )
// ( $2 optional params including parens
// \( literal parens
// (.*?) $3 just params
// \) literal parens
// )?
// \s*$ trailing space
var middle = /^(\s*[\w$]+)(\((.*?)\))?\s*$/;
var leading = parts[1];
var funcName = parts[3].trim().match(middle)[1];
var params = parts[3].trim().match(middle)[3] || '';
var _export = (parts[2].trim() === 'def') ? 'export ' : '';
return leading + _export + 'function ' + funcName + '('+ params +') {';
} | [
"function",
"(",
"line",
")",
"{",
"// example: def bar(a, b) do",
"//",
"// (^\\s*) begining of line",
"// (def|defp) $1 public or private def",
"// (.*?) $2 in betweend def ... do",
"// \\s* optional space",
"// do opening keyword (bracket in JS)",
"// \... | defines public and private module functions returns String a -> String b | [
"defines",
"public",
"and",
"private",
"module",
"functions",
"returns",
"String",
"a",
"-",
">",
"String",
"b"
] | ec5b657770c268441bb9cf37cac2080a5707da95 | https://github.com/AdamBrodzinski/RedScript/blob/ec5b657770c268441bb9cf37cac2080a5707da95/lib/transform.js#L38-L67 | |
34,289 | AdamBrodzinski/RedScript | lib/transform.js | function(line) {
var newLine;
// ex: [foo <- 1,2,3]
// [ opening array
// (.*) $1 array to concat into
// (<-) $2
// (.*) $3 content to be merged
// ] closing array
var regexArr = /\[(.*)(\<\-)(.*)\]/;
// ex: {foo <- foo: true, bar: 2}
// { opening object
// (.*) $1 obj to merge into
// (<-) $2
// (.*) $3 content to be merged
// } closing object
var regexObj = /\{(.*)(\<\-)(.*)\}/;
newLine = line.replace(regexArr, function($0, $1, $2, $3) {
return $1.trim() + '.concat([' + $3 + ']);';
});
return newLine.replace(regexObj, function($0, $1, $2, $3) {
return $1.trim() + '.merge({' + $3 + '});';
});
} | javascript | function(line) {
var newLine;
// ex: [foo <- 1,2,3]
// [ opening array
// (.*) $1 array to concat into
// (<-) $2
// (.*) $3 content to be merged
// ] closing array
var regexArr = /\[(.*)(\<\-)(.*)\]/;
// ex: {foo <- foo: true, bar: 2}
// { opening object
// (.*) $1 obj to merge into
// (<-) $2
// (.*) $3 content to be merged
// } closing object
var regexObj = /\{(.*)(\<\-)(.*)\}/;
newLine = line.replace(regexArr, function($0, $1, $2, $3) {
return $1.trim() + '.concat([' + $3 + ']);';
});
return newLine.replace(regexObj, function($0, $1, $2, $3) {
return $1.trim() + '.merge({' + $3 + '});';
});
} | [
"function",
"(",
"line",
")",
"{",
"var",
"newLine",
";",
"// ex: [foo <- 1,2,3]",
"// [ opening array",
"// (.*) $1 array to concat into",
"// (<-) $2",
"// (.*) $3 content to be merged",
"// ] closing array",
"var",
"regexArr",
"=",
"/",
"\\[(.*)(\\<\\... | merges immutable objects or arrays together returns String a -> String b | [
"merges",
"immutable",
"objects",
"or",
"arrays",
"together",
"returns",
"String",
"a",
"-",
">",
"String",
"b"
] | ec5b657770c268441bb9cf37cac2080a5707da95 | https://github.com/AdamBrodzinski/RedScript/blob/ec5b657770c268441bb9cf37cac2080a5707da95/lib/transform.js#L72-L98 | |
34,290 | AdamBrodzinski/RedScript | lib/transform.js | function(line, index, lines) {
var newLine;
if (insideString('|>', line)) return line;
// line does not have a one liner pipeline
if (!line.match(/(\=|return)(.*?)(\|\>)/)) return line;
// if next line has a pipe operator
if (lines[index] && lines[index + 1].match(/^\s*\|\>/)) return line;
// http://rubular.com/r/wiBJtf12Vn
// (^.+?) $1 value to pipe
// \s* optional spaces
// (\|\>) $2 |> pipe operator
// (.*?)$ $3 tail minus first pipe ($2)
//
var parts = line.match(/(^.+?)\s*(\|\>)(.*?)$/);
var head = parts[1]
var tail = parts[2].concat(parts[3]);
// process head depending on if it's immuttable or not
if (head.match('Immutable')) {
head = head.replace('Immutable', '_.chain(Immutable');
}
else if (head.match(/^\s*return/)) {
head = head.replace('return ', 'return _.chain(');
}
else if (head.match(/\s=\s/)) {
head = head.replace('= ', '= _.chain(');
}
tail = tail.replace(/(\s*\|\>\s*)/g, function($0, $1) {
return ').pipesCall(';
})
return head + tail + ').value();'
} | javascript | function(line, index, lines) {
var newLine;
if (insideString('|>', line)) return line;
// line does not have a one liner pipeline
if (!line.match(/(\=|return)(.*?)(\|\>)/)) return line;
// if next line has a pipe operator
if (lines[index] && lines[index + 1].match(/^\s*\|\>/)) return line;
// http://rubular.com/r/wiBJtf12Vn
// (^.+?) $1 value to pipe
// \s* optional spaces
// (\|\>) $2 |> pipe operator
// (.*?)$ $3 tail minus first pipe ($2)
//
var parts = line.match(/(^.+?)\s*(\|\>)(.*?)$/);
var head = parts[1]
var tail = parts[2].concat(parts[3]);
// process head depending on if it's immuttable or not
if (head.match('Immutable')) {
head = head.replace('Immutable', '_.chain(Immutable');
}
else if (head.match(/^\s*return/)) {
head = head.replace('return ', 'return _.chain(');
}
else if (head.match(/\s=\s/)) {
head = head.replace('= ', '= _.chain(');
}
tail = tail.replace(/(\s*\|\>\s*)/g, function($0, $1) {
return ').pipesCall(';
})
return head + tail + ').value();'
} | [
"function",
"(",
"line",
",",
"index",
",",
"lines",
")",
"{",
"var",
"newLine",
";",
"if",
"(",
"insideString",
"(",
"'|>'",
",",
"line",
")",
")",
"return",
"line",
";",
"// line does not have a one liner pipeline",
"if",
"(",
"!",
"line",
".",
"match",
... | One liner piping returns String a -> String b | [
"One",
"liner",
"piping",
"returns",
"String",
"a",
"-",
">",
"String",
"b"
] | ec5b657770c268441bb9cf37cac2080a5707da95 | https://github.com/AdamBrodzinski/RedScript/blob/ec5b657770c268441bb9cf37cac2080a5707da95/lib/transform.js#L120-L154 | |
34,291 | AdamBrodzinski/RedScript | lib/transform.js | function(line) {
//^
// (\s*) $1 opts leading spaces
// ([\w$]+\s*) $2 variable name & trailing spaces
// (\=) $3 division equals OR
// \s* opt spaces
// (.*?) rest of expression to assign
// $
var parts = line.match(/^(\s*)([\w$]+)\s*(\=)\s*(.*?)$/);
if (!parts) return line;
var leadingSpace = parts[1];
var name = parts[2].trim();
var operator = parts[3].trim();
var rest = parts[4];
return leadingSpace + 'const ' + name + ' ' + operator + ' ' + rest;
} | javascript | function(line) {
//^
// (\s*) $1 opts leading spaces
// ([\w$]+\s*) $2 variable name & trailing spaces
// (\=) $3 division equals OR
// \s* opt spaces
// (.*?) rest of expression to assign
// $
var parts = line.match(/^(\s*)([\w$]+)\s*(\=)\s*(.*?)$/);
if (!parts) return line;
var leadingSpace = parts[1];
var name = parts[2].trim();
var operator = parts[3].trim();
var rest = parts[4];
return leadingSpace + 'const ' + name + ' ' + operator + ' ' + rest;
} | [
"function",
"(",
"line",
")",
"{",
"//^",
"// (\\s*) $1 opts leading spaces",
"// ([\\w$]+\\s*) $2 variable name & trailing spaces",
"// (\\=) $3 division equals OR",
"// \\s* opt spaces",
"// (.*?) rest of expression to assign",
"// $",
"var",
"parts",
"=... | adds `const` to any declaration, works with shorthand operators String a -> String b | [
"adds",
"const",
"to",
"any",
"declaration",
"works",
"with",
"shorthand",
"operators",
"String",
"a",
"-",
">",
"String",
"b"
] | ec5b657770c268441bb9cf37cac2080a5707da95 | https://github.com/AdamBrodzinski/RedScript/blob/ec5b657770c268441bb9cf37cac2080a5707da95/lib/transform.js#L229-L246 | |
34,292 | GrosSacASac/DOM99 | documentation/presentation/reveal.js-2.6.2/plugin/zoom-js/zoom.js | magnify | function magnify( pageOffsetX, pageOffsetY, elementOffsetX, elementOffsetY, scale ) {
if( supportsTransforms ) {
var origin = pageOffsetX +'px '+ pageOffsetY +'px',
transform = 'translate('+ -elementOffsetX +'px,'+ -elementOffsetY +'px) scale('+ scale +')';
document.body.style.transformOrigin = origin;
document.body.style.OTransformOrigin = origin;
document.body.style.msTransformOrigin = origin;
document.body.style.MozTransformOrigin = origin;
document.body.style.WebkitTransformOrigin = origin;
document.body.style.transform = transform;
document.body.style.OTransform = transform;
document.body.style.msTransform = transform;
document.body.style.MozTransform = transform;
document.body.style.WebkitTransform = transform;
}
else {
// Reset all values
if( scale === 1 ) {
document.body.style.position = '';
document.body.style.left = '';
document.body.style.top = '';
document.body.style.width = '';
document.body.style.height = '';
document.body.style.zoom = '';
}
// Apply scale
else {
document.body.style.position = 'relative';
document.body.style.left = ( - ( pageOffsetX + elementOffsetX ) / scale ) + 'px';
document.body.style.top = ( - ( pageOffsetY + elementOffsetY ) / scale ) + 'px';
document.body.style.width = ( scale * 100 ) + '%';
document.body.style.height = ( scale * 100 ) + '%';
document.body.style.zoom = scale;
}
}
level = scale;
if( level !== 1 && document.documentElement.classList ) {
document.documentElement.classList.add( 'zoomed' );
}
else {
document.documentElement.classList.remove( 'zoomed' );
}
} | javascript | function magnify( pageOffsetX, pageOffsetY, elementOffsetX, elementOffsetY, scale ) {
if( supportsTransforms ) {
var origin = pageOffsetX +'px '+ pageOffsetY +'px',
transform = 'translate('+ -elementOffsetX +'px,'+ -elementOffsetY +'px) scale('+ scale +')';
document.body.style.transformOrigin = origin;
document.body.style.OTransformOrigin = origin;
document.body.style.msTransformOrigin = origin;
document.body.style.MozTransformOrigin = origin;
document.body.style.WebkitTransformOrigin = origin;
document.body.style.transform = transform;
document.body.style.OTransform = transform;
document.body.style.msTransform = transform;
document.body.style.MozTransform = transform;
document.body.style.WebkitTransform = transform;
}
else {
// Reset all values
if( scale === 1 ) {
document.body.style.position = '';
document.body.style.left = '';
document.body.style.top = '';
document.body.style.width = '';
document.body.style.height = '';
document.body.style.zoom = '';
}
// Apply scale
else {
document.body.style.position = 'relative';
document.body.style.left = ( - ( pageOffsetX + elementOffsetX ) / scale ) + 'px';
document.body.style.top = ( - ( pageOffsetY + elementOffsetY ) / scale ) + 'px';
document.body.style.width = ( scale * 100 ) + '%';
document.body.style.height = ( scale * 100 ) + '%';
document.body.style.zoom = scale;
}
}
level = scale;
if( level !== 1 && document.documentElement.classList ) {
document.documentElement.classList.add( 'zoomed' );
}
else {
document.documentElement.classList.remove( 'zoomed' );
}
} | [
"function",
"magnify",
"(",
"pageOffsetX",
",",
"pageOffsetY",
",",
"elementOffsetX",
",",
"elementOffsetY",
",",
"scale",
")",
"{",
"if",
"(",
"supportsTransforms",
")",
"{",
"var",
"origin",
"=",
"pageOffsetX",
"+",
"'px '",
"+",
"pageOffsetY",
"+",
"'px'",
... | Applies the CSS required to zoom in, prioritizes use of CSS3
transforms but falls back on zoom for IE.
@param {Number} pageOffsetX
@param {Number} pageOffsetY
@param {Number} elementOffsetX
@param {Number} elementOffsetY
@param {Number} scale | [
"Applies",
"the",
"CSS",
"required",
"to",
"zoom",
"in",
"prioritizes",
"use",
"of",
"CSS3",
"transforms",
"but",
"falls",
"back",
"on",
"zoom",
"for",
"IE",
"."
] | 0563cb3d4865d968e829d39c68dc62af3fc95cc8 | https://github.com/GrosSacASac/DOM99/blob/0563cb3d4865d968e829d39c68dc62af3fc95cc8/documentation/presentation/reveal.js-2.6.2/plugin/zoom-js/zoom.js#L81-L128 |
34,293 | GrosSacASac/DOM99 | documentation/presentation/reveal.js-2.6.2/plugin/zoom-js/zoom.js | pan | function pan() {
var range = 0.12,
rangeX = window.innerWidth * range,
rangeY = window.innerHeight * range,
scrollOffset = getScrollOffset();
// Up
if( mouseY < rangeY ) {
window.scroll( scrollOffset.x, scrollOffset.y - ( 1 - ( mouseY / rangeY ) ) * ( 14 / level ) );
}
// Down
else if( mouseY > window.innerHeight - rangeY ) {
window.scroll( scrollOffset.x, scrollOffset.y + ( 1 - ( window.innerHeight - mouseY ) / rangeY ) * ( 14 / level ) );
}
// Left
if( mouseX < rangeX ) {
window.scroll( scrollOffset.x - ( 1 - ( mouseX / rangeX ) ) * ( 14 / level ), scrollOffset.y );
}
// Right
else if( mouseX > window.innerWidth - rangeX ) {
window.scroll( scrollOffset.x + ( 1 - ( window.innerWidth - mouseX ) / rangeX ) * ( 14 / level ), scrollOffset.y );
}
} | javascript | function pan() {
var range = 0.12,
rangeX = window.innerWidth * range,
rangeY = window.innerHeight * range,
scrollOffset = getScrollOffset();
// Up
if( mouseY < rangeY ) {
window.scroll( scrollOffset.x, scrollOffset.y - ( 1 - ( mouseY / rangeY ) ) * ( 14 / level ) );
}
// Down
else if( mouseY > window.innerHeight - rangeY ) {
window.scroll( scrollOffset.x, scrollOffset.y + ( 1 - ( window.innerHeight - mouseY ) / rangeY ) * ( 14 / level ) );
}
// Left
if( mouseX < rangeX ) {
window.scroll( scrollOffset.x - ( 1 - ( mouseX / rangeX ) ) * ( 14 / level ), scrollOffset.y );
}
// Right
else if( mouseX > window.innerWidth - rangeX ) {
window.scroll( scrollOffset.x + ( 1 - ( window.innerWidth - mouseX ) / rangeX ) * ( 14 / level ), scrollOffset.y );
}
} | [
"function",
"pan",
"(",
")",
"{",
"var",
"range",
"=",
"0.12",
",",
"rangeX",
"=",
"window",
".",
"innerWidth",
"*",
"range",
",",
"rangeY",
"=",
"window",
".",
"innerHeight",
"*",
"range",
",",
"scrollOffset",
"=",
"getScrollOffset",
"(",
")",
";",
"/... | Pan the document when the mosue cursor approaches the edges
of the window. | [
"Pan",
"the",
"document",
"when",
"the",
"mosue",
"cursor",
"approaches",
"the",
"edges",
"of",
"the",
"window",
"."
] | 0563cb3d4865d968e829d39c68dc62af3fc95cc8 | https://github.com/GrosSacASac/DOM99/blob/0563cb3d4865d968e829d39c68dc62af3fc95cc8/documentation/presentation/reveal.js-2.6.2/plugin/zoom-js/zoom.js#L134-L157 |
34,294 | GrosSacASac/DOM99 | documentation/presentation/reveal.js-2.6.2/plugin/zoom-js/zoom.js | function() {
clearTimeout( panEngageTimeout );
clearInterval( panUpdateInterval );
var scrollOffset = getScrollOffset();
if( currentOptions && currentOptions.element ) {
scrollOffset.x -= ( window.innerWidth - ( currentOptions.width * currentOptions.scale ) ) / 2;
}
magnify( scrollOffset.x, scrollOffset.y, 0, 0, 1 );
level = 1;
} | javascript | function() {
clearTimeout( panEngageTimeout );
clearInterval( panUpdateInterval );
var scrollOffset = getScrollOffset();
if( currentOptions && currentOptions.element ) {
scrollOffset.x -= ( window.innerWidth - ( currentOptions.width * currentOptions.scale ) ) / 2;
}
magnify( scrollOffset.x, scrollOffset.y, 0, 0, 1 );
level = 1;
} | [
"function",
"(",
")",
"{",
"clearTimeout",
"(",
"panEngageTimeout",
")",
";",
"clearInterval",
"(",
"panUpdateInterval",
")",
";",
"var",
"scrollOffset",
"=",
"getScrollOffset",
"(",
")",
";",
"if",
"(",
"currentOptions",
"&&",
"currentOptions",
".",
"element",
... | Resets the document zoom state to its default. | [
"Resets",
"the",
"document",
"zoom",
"state",
"to",
"its",
"default",
"."
] | 0563cb3d4865d968e829d39c68dc62af3fc95cc8 | https://github.com/GrosSacASac/DOM99/blob/0563cb3d4865d968e829d39c68dc62af3fc95cc8/documentation/presentation/reveal.js-2.6.2/plugin/zoom-js/zoom.js#L233-L246 | |
34,295 | Botanalyticsco/botanalytics | examples/amazon-lex-with-lambda.js | buildResponseCard | function buildResponseCard(title, subTitle, options) {
let buttons = null;
if (options != null) {
buttons = [];
for (let i = 0; i < Math.min(5, options.length); i++) {
buttons.push(options[i]);
}
}
return {
contentType: 'application/vnd.amazonaws.card.generic',
version: 1,
genericAttachments: [{
title,
subTitle,
buttons,
}],
};
} | javascript | function buildResponseCard(title, subTitle, options) {
let buttons = null;
if (options != null) {
buttons = [];
for (let i = 0; i < Math.min(5, options.length); i++) {
buttons.push(options[i]);
}
}
return {
contentType: 'application/vnd.amazonaws.card.generic',
version: 1,
genericAttachments: [{
title,
subTitle,
buttons,
}],
};
} | [
"function",
"buildResponseCard",
"(",
"title",
",",
"subTitle",
",",
"options",
")",
"{",
"let",
"buttons",
"=",
"null",
";",
"if",
"(",
"options",
"!=",
"null",
")",
"{",
"buttons",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
... | Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. | [
"Build",
"a",
"responseCard",
"with",
"a",
"title",
"subtitle",
"and",
"an",
"optional",
"set",
"of",
"options",
"which",
"should",
"be",
"displayed",
"as",
"buttons",
"."
] | a6ca41f226752ab765b939dbc11bb6402465603a | https://github.com/Botanalyticsco/botanalytics/blob/a6ca41f226752ab765b939dbc11bb6402465603a/examples/amazon-lex-with-lambda.js#L74-L91 |
34,296 | Botanalyticsco/botanalytics | examples/amazon-lex-with-lambda.js | getAvailabilities | function getAvailabilities(date) {
const dayOfWeek = parseLocalDate(date).getDay();
const availabilities = [];
const availableProbability = 0.3;
if (dayOfWeek === 1) {
let startHour = 10;
while (startHour <= 16) {
if (Math.random() < availableProbability) {
// Add an availability window for the given hour, with duration determined by another random number.
const appointmentType = getRandomInt(1, 4);
if (appointmentType === 1) {
availabilities.push(`${startHour}:00`);
} else if (appointmentType === 2) {
availabilities.push(`${startHour}:30`);
} else {
availabilities.push(`${startHour}:00`);
availabilities.push(`${startHour}:30`);
}
}
startHour++;
}
}
if (dayOfWeek === 3 || dayOfWeek === 5) {
availabilities.push('10:00');
availabilities.push('16:00');
availabilities.push('16:30');
}
return availabilities;
} | javascript | function getAvailabilities(date) {
const dayOfWeek = parseLocalDate(date).getDay();
const availabilities = [];
const availableProbability = 0.3;
if (dayOfWeek === 1) {
let startHour = 10;
while (startHour <= 16) {
if (Math.random() < availableProbability) {
// Add an availability window for the given hour, with duration determined by another random number.
const appointmentType = getRandomInt(1, 4);
if (appointmentType === 1) {
availabilities.push(`${startHour}:00`);
} else if (appointmentType === 2) {
availabilities.push(`${startHour}:30`);
} else {
availabilities.push(`${startHour}:00`);
availabilities.push(`${startHour}:30`);
}
}
startHour++;
}
}
if (dayOfWeek === 3 || dayOfWeek === 5) {
availabilities.push('10:00');
availabilities.push('16:00');
availabilities.push('16:30');
}
return availabilities;
} | [
"function",
"getAvailabilities",
"(",
"date",
")",
"{",
"const",
"dayOfWeek",
"=",
"parseLocalDate",
"(",
"date",
")",
".",
"getDay",
"(",
")",
";",
"const",
"availabilities",
"=",
"[",
"]",
";",
"const",
"availableProbability",
"=",
"0.3",
";",
"if",
"(",... | Helper function which in a full implementation would feed into a backend API to provide query schedule availability.
The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format.
In order to enable quick demonstration of all possible conversation paths supported in this example, the function
returns a mixture of fixed and randomized results.
On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at
10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday. | [
"Helper",
"function",
"which",
"in",
"a",
"full",
"implementation",
"would",
"feed",
"into",
"a",
"backend",
"API",
"to",
"provide",
"query",
"schedule",
"availability",
".",
"The",
"output",
"of",
"this",
"function",
"is",
"an",
"array",
"of",
"30",
"minute... | a6ca41f226752ab765b939dbc11bb6402465603a | https://github.com/Botanalyticsco/botanalytics/blob/a6ca41f226752ab765b939dbc11bb6402465603a/examples/amazon-lex-with-lambda.js#L138-L166 |
34,297 | Botanalyticsco/botanalytics | examples/amazon-lex-with-lambda.js | getAvailabilitiesForDuration | function getAvailabilitiesForDuration(duration, availabilities) {
const durationAvailabilities = [];
let startTime = '10:00';
while (startTime !== '17:00') {
if (availabilities.indexOf(startTime) !== -1) {
if (duration === 30) {
durationAvailabilities.push(startTime);
} else if (availabilities.indexOf(incrementTimeByThirtyMins(startTime)) !== -1) {
durationAvailabilities.push(startTime);
}
}
startTime = incrementTimeByThirtyMins(startTime);
}
return durationAvailabilities;
} | javascript | function getAvailabilitiesForDuration(duration, availabilities) {
const durationAvailabilities = [];
let startTime = '10:00';
while (startTime !== '17:00') {
if (availabilities.indexOf(startTime) !== -1) {
if (duration === 30) {
durationAvailabilities.push(startTime);
} else if (availabilities.indexOf(incrementTimeByThirtyMins(startTime)) !== -1) {
durationAvailabilities.push(startTime);
}
}
startTime = incrementTimeByThirtyMins(startTime);
}
return durationAvailabilities;
} | [
"function",
"getAvailabilitiesForDuration",
"(",
"duration",
",",
"availabilities",
")",
"{",
"const",
"durationAvailabilities",
"=",
"[",
"]",
";",
"let",
"startTime",
"=",
"'10:00'",
";",
"while",
"(",
"startTime",
"!==",
"'17:00'",
")",
"{",
"if",
"(",
"ava... | Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows. | [
"Helper",
"function",
"to",
"return",
"the",
"windows",
"of",
"availability",
"of",
"the",
"given",
"duration",
"when",
"provided",
"a",
"set",
"of",
"30",
"minute",
"windows",
"."
] | a6ca41f226752ab765b939dbc11bb6402465603a | https://github.com/Botanalyticsco/botanalytics/blob/a6ca41f226752ab765b939dbc11bb6402465603a/examples/amazon-lex-with-lambda.js#L187-L201 |
34,298 | Botanalyticsco/botanalytics | examples/amazon-lex-with-lambda.js | buildAvailableTimeString | function buildAvailableTimeString(availabilities) {
let prefix = 'We have availabilities at ';
if (availabilities.length > 3) {
prefix = 'We have plenty of availability, including ';
}
prefix += buildTimeOutputString(availabilities[0]);
if (availabilities.length === 2) {
return `${prefix} and ${buildTimeOutputString(availabilities[1])}`;
}
return `${prefix}, ${buildTimeOutputString(availabilities[1])} and ${buildTimeOutputString(availabilities[2])}`;
} | javascript | function buildAvailableTimeString(availabilities) {
let prefix = 'We have availabilities at ';
if (availabilities.length > 3) {
prefix = 'We have plenty of availability, including ';
}
prefix += buildTimeOutputString(availabilities[0]);
if (availabilities.length === 2) {
return `${prefix} and ${buildTimeOutputString(availabilities[1])}`;
}
return `${prefix}, ${buildTimeOutputString(availabilities[1])} and ${buildTimeOutputString(availabilities[2])}`;
} | [
"function",
"buildAvailableTimeString",
"(",
"availabilities",
")",
"{",
"let",
"prefix",
"=",
"'We have availabilities at '",
";",
"if",
"(",
"availabilities",
".",
"length",
">",
"3",
")",
"{",
"prefix",
"=",
"'We have plenty of availability, including '",
";",
"}",... | Build a string eliciting for a possible time slot among at least two availabilities. | [
"Build",
"a",
"string",
"eliciting",
"for",
"a",
"possible",
"time",
"slot",
"among",
"at",
"least",
"two",
"availabilities",
"."
] | a6ca41f226752ab765b939dbc11bb6402465603a | https://github.com/Botanalyticsco/botanalytics/blob/a6ca41f226752ab765b939dbc11bb6402465603a/examples/amazon-lex-with-lambda.js#L260-L270 |
34,299 | Botanalyticsco/botanalytics | examples/amazon-lex-with-lambda.js | buildOptions | function buildOptions(slot, appointmentType, date, bookingMap) {
const dayStrings = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
if (slot === 'AppointmentType') {
return [
{ text: 'cleaning (30 min)', value: 'cleaning' },
{ text: 'root canal (60 min)', value: 'root canal' },
{ text: 'whitening (30 min)', value: 'whitening' },
];
} else if (slot === 'Date') {
// Return the next five weekdays.
const options = [];
const potentialDate = new Date();
while (options.length < 5) {
potentialDate.setDate(potentialDate.getDate() + 1);
if (potentialDate.getDay() > 0 && potentialDate.getDay() < 6) {
options.push({ text: `${potentialDate.getMonth() + 1}-${potentialDate.getDate()} (${dayStrings[potentialDate.getDay()]})`,
value: potentialDate.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) });
}
}
return options;
} else if (slot === 'Time') {
// Return the availabilities on the given date.
if (!appointmentType || !date) {
return null;
}
let availabilities = bookingMap[`${date}`];
if (!availabilities) {
return null;
}
availabilities = getAvailabilitiesForDuration(getDuration(appointmentType), availabilities);
if (availabilities.length === 0) {
return null;
}
const options = [];
for (let i = 0; i < Math.min(availabilities.length, 5); i++) {
options.push({ text: buildTimeOutputString(availabilities[i]), value: buildTimeOutputString(availabilities[i]) });
}
return options;
}
} | javascript | function buildOptions(slot, appointmentType, date, bookingMap) {
const dayStrings = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
if (slot === 'AppointmentType') {
return [
{ text: 'cleaning (30 min)', value: 'cleaning' },
{ text: 'root canal (60 min)', value: 'root canal' },
{ text: 'whitening (30 min)', value: 'whitening' },
];
} else if (slot === 'Date') {
// Return the next five weekdays.
const options = [];
const potentialDate = new Date();
while (options.length < 5) {
potentialDate.setDate(potentialDate.getDate() + 1);
if (potentialDate.getDay() > 0 && potentialDate.getDay() < 6) {
options.push({ text: `${potentialDate.getMonth() + 1}-${potentialDate.getDate()} (${dayStrings[potentialDate.getDay()]})`,
value: potentialDate.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) });
}
}
return options;
} else if (slot === 'Time') {
// Return the availabilities on the given date.
if (!appointmentType || !date) {
return null;
}
let availabilities = bookingMap[`${date}`];
if (!availabilities) {
return null;
}
availabilities = getAvailabilitiesForDuration(getDuration(appointmentType), availabilities);
if (availabilities.length === 0) {
return null;
}
const options = [];
for (let i = 0; i < Math.min(availabilities.length, 5); i++) {
options.push({ text: buildTimeOutputString(availabilities[i]), value: buildTimeOutputString(availabilities[i]) });
}
return options;
}
} | [
"function",
"buildOptions",
"(",
"slot",
",",
"appointmentType",
",",
"date",
",",
"bookingMap",
")",
"{",
"const",
"dayStrings",
"=",
"[",
"'Sun'",
",",
"'Mon'",
",",
"'Tue'",
",",
"'Wed'",
",",
"'Thu'",
",",
"'Fri'",
",",
"'Sat'",
"]",
";",
"if",
"("... | Build a list of potential options for a given slot, to be used in responseCard generation. | [
"Build",
"a",
"list",
"of",
"potential",
"options",
"for",
"a",
"given",
"slot",
"to",
"be",
"used",
"in",
"responseCard",
"generation",
"."
] | a6ca41f226752ab765b939dbc11bb6402465603a | https://github.com/Botanalyticsco/botanalytics/blob/a6ca41f226752ab765b939dbc11bb6402465603a/examples/amazon-lex-with-lambda.js#L273-L312 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.