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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
35,200 | stackgl/gl-mat3 | create.js | create | function create() {
var out = new Float32Array(9)
out[0] = 1
out[1] = 0
out[2] = 0
out[3] = 0
out[4] = 1
out[5] = 0
out[6] = 0
out[7] = 0
out[8] = 1
return out
} | javascript | function create() {
var out = new Float32Array(9)
out[0] = 1
out[1] = 0
out[2] = 0
out[3] = 0
out[4] = 1
out[5] = 0
out[6] = 0
out[7] = 0
out[8] = 1
return out
} | [
"function",
"create",
"(",
")",
"{",
"var",
"out",
"=",
"new",
"Float32Array",
"(",
"9",
")",
"out",
"[",
"0",
"]",
"=",
"1",
"out",
"[",
"1",
"]",
"=",
"0",
"out",
"[",
"2",
"]",
"=",
"0",
"out",
"[",
"3",
"]",
"=",
"0",
"out",
"[",
"4",... | Creates a new identity mat3
@alias mat3.create
@returns {mat3} a new 3x3 matrix | [
"Creates",
"a",
"new",
"identity",
"mat3"
] | df6df371ab119fb0c9f2b428d3a4f8d05cd2119e | https://github.com/stackgl/gl-mat3/blob/df6df371ab119fb0c9f2b428d3a4f8d05cd2119e/create.js#L9-L21 |
35,201 | eggjs/egg-sls | lib/client/log.js | Log | function Log(properties) {
this.contents = [];
if (properties) {
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
if (properties[keys[i]] != null) { this[keys[i]] = properties[keys[i]]; }
}
}
} | javascript | function Log(properties) {
this.contents = [];
if (properties) {
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
if (properties[keys[i]] != null) { this[keys[i]] = properties[keys[i]]; }
}
}
} | [
"function",
"Log",
"(",
"properties",
")",
"{",
"this",
".",
"contents",
"=",
"[",
"]",
";",
"if",
"(",
"properties",
")",
"{",
"for",
"(",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"properties",
")",
",",
"i",
"=",
"0",
";",
"i",
"<",
"k... | Properties of a Log.
@exports ILog
@interface ILog
@property {number} time Log time
@property {Array.<Log.IContent>|null} [contents] Log contents
Constructs a new Log.
@exports Log
@classdesc Represents a Log.
@implements ILog
@constructor
@param {ILog=} [properties] Properties to set | [
"Properties",
"of",
"a",
"Log",
"."
] | 52076d2f0bd708e1cf69a6ea03c08394cfbf5212 | https://github.com/eggjs/egg-sls/blob/52076d2f0bd708e1cf69a6ea03c08394cfbf5212/lib/client/log.js#L32-L39 |
35,202 | eggjs/egg-sls | lib/client/log.js | LogGroup | function LogGroup(properties) {
this.logs = [];
if (properties) {
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
if (properties[keys[i]] != null) { this[keys[i]] = properties[keys[i]]; }
}
}
} | javascript | function LogGroup(properties) {
this.logs = [];
if (properties) {
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
if (properties[keys[i]] != null) { this[keys[i]] = properties[keys[i]]; }
}
}
} | [
"function",
"LogGroup",
"(",
"properties",
")",
"{",
"this",
".",
"logs",
"=",
"[",
"]",
";",
"if",
"(",
"properties",
")",
"{",
"for",
"(",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"properties",
")",
",",
"i",
"=",
"0",
";",
"i",
"<",
"... | Properties of a LogGroup.
@exports ILogGroup
@interface ILogGroup
@property {Array.<ILog>|null} [logs] LogGroup logs
@property {string|null} [reserved] LogGroup reserved
@property {string|null} [topic] LogGroup topic
@property {string|null} [source] LogGroup source
Constructs a new LogGroup.
@exports LogGroup
@classdesc Represents a LogGroup.
@implements ILogGroup
@constructor
@param {ILogGroup=} [properties] Properties to set | [
"Properties",
"of",
"a",
"LogGroup",
"."
] | 52076d2f0bd708e1cf69a6ea03c08394cfbf5212 | https://github.com/eggjs/egg-sls/blob/52076d2f0bd708e1cf69a6ea03c08394cfbf5212/lib/client/log.js#L447-L454 |
35,203 | eggjs/egg-sls | lib/client/log.js | LogGroupList | function LogGroupList(properties) {
this.logGroupList = [];
if (properties) {
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
if (properties[keys[i]] != null) { this[keys[i]] = properties[keys[i]]; }
}
}
} | javascript | function LogGroupList(properties) {
this.logGroupList = [];
if (properties) {
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
if (properties[keys[i]] != null) { this[keys[i]] = properties[keys[i]]; }
}
}
} | [
"function",
"LogGroupList",
"(",
"properties",
")",
"{",
"this",
".",
"logGroupList",
"=",
"[",
"]",
";",
"if",
"(",
"properties",
")",
"{",
"for",
"(",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"properties",
")",
",",
"i",
"=",
"0",
";",
"i"... | Properties of a LogGroupList.
@exports ILogGroupList
@interface ILogGroupList
@property {Array.<ILogGroup>|null} [logGroupList] LogGroupList logGroupList
Constructs a new LogGroupList.
@exports LogGroupList
@classdesc Represents a LogGroupList.
@implements ILogGroupList
@constructor
@param {ILogGroupList=} [properties] Properties to set | [
"Properties",
"of",
"a",
"LogGroupList",
"."
] | 52076d2f0bd708e1cf69a6ea03c08394cfbf5212 | https://github.com/eggjs/egg-sls/blob/52076d2f0bd708e1cf69a6ea03c08394cfbf5212/lib/client/log.js#L700-L707 |
35,204 | bunsn/boiler | transaction.js | Transaction | function Transaction (attributes) {
this.attributes = {}
for (var key in attributes) {
if (attributes.hasOwnProperty(key)) this.set(key, attributes[key])
}
if (!this.get('date')) this.setDate()
if (!this.get('amount')) this.setAmount()
} | javascript | function Transaction (attributes) {
this.attributes = {}
for (var key in attributes) {
if (attributes.hasOwnProperty(key)) this.set(key, attributes[key])
}
if (!this.get('date')) this.setDate()
if (!this.get('amount')) this.setAmount()
} | [
"function",
"Transaction",
"(",
"attributes",
")",
"{",
"this",
".",
"attributes",
"=",
"{",
"}",
"for",
"(",
"var",
"key",
"in",
"attributes",
")",
"{",
"if",
"(",
"attributes",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"this",
".",
"set",
"(",
"... | Represents a single transaction.
Getters and setters are used to transform and format values. Also responsible
for calculating amounts and dates when missing or invalid.
@constructor
@param {Object} attributes | [
"Represents",
"a",
"single",
"transaction",
".",
"Getters",
"and",
"setters",
"are",
"used",
"to",
"transform",
"and",
"format",
"values",
".",
"Also",
"responsible",
"for",
"calculating",
"amounts",
"and",
"dates",
"when",
"missing",
"or",
"invalid",
"."
] | 21413dcc1003d9526041e105734287cc83a596ff | https://github.com/bunsn/boiler/blob/21413dcc1003d9526041e105734287cc83a596ff/transaction.js#L13-L22 |
35,205 | 8lueberry/express-dot-engine | index.js | done | function done(err, template) {
// cache
if (options && options.cache && template) {
cache.set(filename, template);
}
if (isAsync) {
callback(err, template);
}
return template;
} | javascript | function done(err, template) {
// cache
if (options && options.cache && template) {
cache.set(filename, template);
}
if (isAsync) {
callback(err, template);
}
return template;
} | [
"function",
"done",
"(",
"err",
",",
"template",
")",
"{",
"// cache",
"if",
"(",
"options",
"&&",
"options",
".",
"cache",
"&&",
"template",
")",
"{",
"cache",
".",
"set",
"(",
"filename",
",",
"template",
")",
";",
"}",
"if",
"(",
"isAsync",
")",
... | function to call when retieved template | [
"function",
"to",
"call",
"when",
"retieved",
"template"
] | 2c6fc58fcecb8c76917550864be17e2d8753a60d | https://github.com/8lueberry/express-dot-engine/blob/2c6fc58fcecb8c76917550864be17e2d8753a60d/index.js#L277-L289 |
35,206 | 8lueberry/express-dot-engine | index.js | buildTemplate | function buildTemplate(filename, options, callback) {
var isAsync = callback && typeof callback === 'function',
getTemplateContentFn = options.getTemplate && typeof options.getTemplate === 'function' ? options.getTemplate : getTemplateContentFromFile;
// sync
if (!isAsync) {
return builtTemplateFromString(
getTemplateContentFn(filename, options),
filename,
options
);
}
// function to call when retrieved template content
function done(err, templateText) {
callback(err, builtTemplateFromString(templateText, filename, options));
}
getTemplateContentFn(filename, options, done);
} | javascript | function buildTemplate(filename, options, callback) {
var isAsync = callback && typeof callback === 'function',
getTemplateContentFn = options.getTemplate && typeof options.getTemplate === 'function' ? options.getTemplate : getTemplateContentFromFile;
// sync
if (!isAsync) {
return builtTemplateFromString(
getTemplateContentFn(filename, options),
filename,
options
);
}
// function to call when retrieved template content
function done(err, templateText) {
callback(err, builtTemplateFromString(templateText, filename, options));
}
getTemplateContentFn(filename, options, done);
} | [
"function",
"buildTemplate",
"(",
"filename",
",",
"options",
",",
"callback",
")",
"{",
"var",
"isAsync",
"=",
"callback",
"&&",
"typeof",
"callback",
"===",
"'function'",
",",
"getTemplateContentFn",
"=",
"options",
".",
"getTemplate",
"&&",
"typeof",
"options... | Builds a template
If callback is passed, it will be called asynchronously.
@param {String} filename The path or the name to the template
@param {Object} options The options sent by express
@param {Function} callback (Optional) The async node style callback | [
"Builds",
"a",
"template",
"If",
"callback",
"is",
"passed",
"it",
"will",
"be",
"called",
"asynchronously",
"."
] | 2c6fc58fcecb8c76917550864be17e2d8753a60d | https://github.com/8lueberry/express-dot-engine/blob/2c6fc58fcecb8c76917550864be17e2d8753a60d/index.js#L308-L327 |
35,207 | 8lueberry/express-dot-engine | index.js | getTemplateContentFromFile | function getTemplateContentFromFile(filename, options, callback) {
var isAsync = callback && typeof callback === 'function';
// sync
if (!isAsync) {
return fs.readFileSync(filename, 'utf8');
}
// async
fs.readFile(filename, 'utf8', function(err, str) {
if (err) {
callback(new Error('Failed to open view file (' + filename + ')'));
return;
}
try {
callback(null, str);
}
catch (err) {
callback(err);
}
});
} | javascript | function getTemplateContentFromFile(filename, options, callback) {
var isAsync = callback && typeof callback === 'function';
// sync
if (!isAsync) {
return fs.readFileSync(filename, 'utf8');
}
// async
fs.readFile(filename, 'utf8', function(err, str) {
if (err) {
callback(new Error('Failed to open view file (' + filename + ')'));
return;
}
try {
callback(null, str);
}
catch (err) {
callback(err);
}
});
} | [
"function",
"getTemplateContentFromFile",
"(",
"filename",
",",
"options",
",",
"callback",
")",
"{",
"var",
"isAsync",
"=",
"callback",
"&&",
"typeof",
"callback",
"===",
"'function'",
";",
"// sync",
"if",
"(",
"!",
"isAsync",
")",
"{",
"return",
"fs",
"."... | Gets the template content from a file
If callback is passed, it will be called asynchronously.
@param {String} filename The path to the template
@param {Object} options The options sent by express
@param {Function} callback (Optional) The async node style callback | [
"Gets",
"the",
"template",
"content",
"from",
"a",
"file",
"If",
"callback",
"is",
"passed",
"it",
"will",
"be",
"called",
"asynchronously",
"."
] | 2c6fc58fcecb8c76917550864be17e2d8753a60d | https://github.com/8lueberry/express-dot-engine/blob/2c6fc58fcecb8c76917550864be17e2d8753a60d/index.js#L336-L358 |
35,208 | 8lueberry/express-dot-engine | index.js | builtTemplateFromString | function builtTemplateFromString(str, filename, options) {
try {
var config = {};
// config at the beginning of the file
str.replace(settings.config, function(m, conf) {
config = yaml.safeLoad(conf);
});
// strip comments
if (settings.stripComment) {
str = str.replace(settings.comment, function(m, code, assign, value) {
return '';
});
}
// strip whitespace
if (settings.stripWhitespace) {
settings.dot.strip = settings.stripWhitespace;
}
// layout sections
var sections = {};
if (!config.layout) {
sections.body = str;
}
else {
str.replace(settings.dot.define, function(m, code, assign, value) {
sections[code] = value;
});
}
var templateSettings = _.pick(options, ['settings']);
options.getTemplate && (templateSettings.getTemplate = options.getTemplate);
return new Template({
express: templateSettings,
config: config,
sections: sections,
dirname: path.dirname(filename),
filename: filename
});
}
catch (err) {
throw new Error(
'Failed to build template' +
' (' + filename + ')' +
' - ' + err.toString()
);
}
} | javascript | function builtTemplateFromString(str, filename, options) {
try {
var config = {};
// config at the beginning of the file
str.replace(settings.config, function(m, conf) {
config = yaml.safeLoad(conf);
});
// strip comments
if (settings.stripComment) {
str = str.replace(settings.comment, function(m, code, assign, value) {
return '';
});
}
// strip whitespace
if (settings.stripWhitespace) {
settings.dot.strip = settings.stripWhitespace;
}
// layout sections
var sections = {};
if (!config.layout) {
sections.body = str;
}
else {
str.replace(settings.dot.define, function(m, code, assign, value) {
sections[code] = value;
});
}
var templateSettings = _.pick(options, ['settings']);
options.getTemplate && (templateSettings.getTemplate = options.getTemplate);
return new Template({
express: templateSettings,
config: config,
sections: sections,
dirname: path.dirname(filename),
filename: filename
});
}
catch (err) {
throw new Error(
'Failed to build template' +
' (' + filename + ')' +
' - ' + err.toString()
);
}
} | [
"function",
"builtTemplateFromString",
"(",
"str",
",",
"filename",
",",
"options",
")",
"{",
"try",
"{",
"var",
"config",
"=",
"{",
"}",
";",
"// config at the beginning of the file",
"str",
".",
"replace",
"(",
"settings",
".",
"config",
",",
"function",
"("... | Builds a template from a string
@param {String} str The template string
@param {String} filename The path to the template
@param {Object} options The options sent by express
@return {Template} The template object | [
"Builds",
"a",
"template",
"from",
"a",
"string"
] | 2c6fc58fcecb8c76917550864be17e2d8753a60d | https://github.com/8lueberry/express-dot-engine/blob/2c6fc58fcecb8c76917550864be17e2d8753a60d/index.js#L367-L418 |
35,209 | 8lueberry/express-dot-engine | index.js | renderSync | function renderSync(filename, options) {
var template = getTemplate(filename, options);
return template.render({ model: options, });
} | javascript | function renderSync(filename, options) {
var template = getTemplate(filename, options);
return template.render({ model: options, });
} | [
"function",
"renderSync",
"(",
"filename",
",",
"options",
")",
"{",
"var",
"template",
"=",
"getTemplate",
"(",
"filename",
",",
"options",
")",
";",
"return",
"template",
".",
"render",
"(",
"{",
"model",
":",
"options",
",",
"}",
")",
";",
"}"
] | Renders a template sync
@param {String} filename The path to the file
@param {Object} options The model to pass to the view | [
"Renders",
"a",
"template",
"sync"
] | 2c6fc58fcecb8c76917550864be17e2d8753a60d | https://github.com/8lueberry/express-dot-engine/blob/2c6fc58fcecb8c76917550864be17e2d8753a60d/index.js#L447-L450 |
35,210 | 8lueberry/express-dot-engine | index.js | renderString | function renderString(templateString, options, callback) {
var template = builtTemplateFromString(templateString, '', options);
return template.render({ model: options, }, callback);
} | javascript | function renderString(templateString, options, callback) {
var template = builtTemplateFromString(templateString, '', options);
return template.render({ model: options, }, callback);
} | [
"function",
"renderString",
"(",
"templateString",
",",
"options",
",",
"callback",
")",
"{",
"var",
"template",
"=",
"builtTemplateFromString",
"(",
"templateString",
",",
"''",
",",
"options",
")",
";",
"return",
"template",
".",
"render",
"(",
"{",
"model",... | Render directly from a string
@param {String} templateString The template string
@param {Object} options The model to pass to the view
@param {Function} callback (Optional) The async node style callback | [
"Render",
"directly",
"from",
"a",
"string"
] | 2c6fc58fcecb8c76917550864be17e2d8753a60d | https://github.com/8lueberry/express-dot-engine/blob/2c6fc58fcecb8c76917550864be17e2d8753a60d/index.js#L458-L461 |
35,211 | bbc/ShouldIT | lib/run.js | run | function run(config) {
var specCollector = require('./specCollector'),
resultCollector = require('./resultCollector'),
inspector = require('./inspector'),
spitterOuter = require('./spitterOuter'),
summariser = require('./summariser'),
XmlWriter = require('./junitXmlWriter'),
fs = require('fs'),
prepareNodeData = require('./visualiser/prepareNodeData'),
allSpecs;
function outputFileComparison(specs, results) {
/**
* Use the collector to get the content of each file
*/
var files = [specs, results];
try {
results = inspector(files, config);
var writer = new XmlWriter(config);
writer.writeResults(results);
var output = spitterOuter(results, config);
output.forEach(function(line) {
console.log(line);
});
if (config.outputSummary) {
var summary = summariser(results);
summary.forEach(function(summaryItem) {
console.log(summaryItem);
});
}
prepareNodeData(config, files);
} catch (e) {
if (config.watch) {
console.log("Still watching... carry on BDD'ing!");
}
}
}
function collectResults(specs) {
allSpecs = specs;
return resultCollector(config.results);
}
function compareOutputFiles(results) {
outputFileComparison(allSpecs, results);
}
/**
* Get the specs from the spec collector
*/
specCollector(config.specs, config.tags)
.then(collectResults)
.then(compareOutputFiles);
} | javascript | function run(config) {
var specCollector = require('./specCollector'),
resultCollector = require('./resultCollector'),
inspector = require('./inspector'),
spitterOuter = require('./spitterOuter'),
summariser = require('./summariser'),
XmlWriter = require('./junitXmlWriter'),
fs = require('fs'),
prepareNodeData = require('./visualiser/prepareNodeData'),
allSpecs;
function outputFileComparison(specs, results) {
/**
* Use the collector to get the content of each file
*/
var files = [specs, results];
try {
results = inspector(files, config);
var writer = new XmlWriter(config);
writer.writeResults(results);
var output = spitterOuter(results, config);
output.forEach(function(line) {
console.log(line);
});
if (config.outputSummary) {
var summary = summariser(results);
summary.forEach(function(summaryItem) {
console.log(summaryItem);
});
}
prepareNodeData(config, files);
} catch (e) {
if (config.watch) {
console.log("Still watching... carry on BDD'ing!");
}
}
}
function collectResults(specs) {
allSpecs = specs;
return resultCollector(config.results);
}
function compareOutputFiles(results) {
outputFileComparison(allSpecs, results);
}
/**
* Get the specs from the spec collector
*/
specCollector(config.specs, config.tags)
.then(collectResults)
.then(compareOutputFiles);
} | [
"function",
"run",
"(",
"config",
")",
"{",
"var",
"specCollector",
"=",
"require",
"(",
"'./specCollector'",
")",
",",
"resultCollector",
"=",
"require",
"(",
"'./resultCollector'",
")",
",",
"inspector",
"=",
"require",
"(",
"'./inspector'",
")",
",",
"spitt... | Run App. | [
"Run",
"App",
"."
] | e7a9286339970c896c61058009e1d6fe812ac0df | https://github.com/bbc/ShouldIT/blob/e7a9286339970c896c61058009e1d6fe812ac0df/lib/run.js#L7-L63 |
35,212 | hydux/hydux-mutator | lib/index.js | getIn | function getIn(record, accessor, ctx) {
var v = record;
var keys = getPathKeys(accessor, ctx);
if (utils_1.isFn(record.getIn)) {
return record.getIn(keys);
}
var len = keys.length;
for (var i = 0; i < len; i++) {
var key = keys[i];
v = utils_1.isObj(v)
? utils_1.isFn(v.get)
? v.get(key)
: v[key]
: undefined;
}
return v;
} | javascript | function getIn(record, accessor, ctx) {
var v = record;
var keys = getPathKeys(accessor, ctx);
if (utils_1.isFn(record.getIn)) {
return record.getIn(keys);
}
var len = keys.length;
for (var i = 0; i < len; i++) {
var key = keys[i];
v = utils_1.isObj(v)
? utils_1.isFn(v.get)
? v.get(key)
: v[key]
: undefined;
}
return v;
} | [
"function",
"getIn",
"(",
"record",
",",
"accessor",
",",
"ctx",
")",
"{",
"var",
"v",
"=",
"record",
";",
"var",
"keys",
"=",
"getPathKeys",
"(",
"accessor",
",",
"ctx",
")",
";",
"if",
"(",
"utils_1",
".",
"isFn",
"(",
"record",
".",
"getIn",
")"... | get a deep child
@param record The object to update, it can be a plain object or a class instance
@param accessor A lambda function to get the key path, support dot, [''], [""], [1], **do not** support dynamic variable, function call, e.g.
@param ctx Dynamic key map. | [
"get",
"a",
"deep",
"child"
] | 59596fcd885276e5db119a00953470066670f265 | https://github.com/hydux/hydux-mutator/blob/59596fcd885276e5db119a00953470066670f265/lib/index.js#L113-L129 |
35,213 | hydux/hydux-mutator | lib/index.js | setIn | function setIn(record, accessor, value, ctx) {
return mutate(record, accessor, MutateType.setIn, value, ctx);
} | javascript | function setIn(record, accessor, value, ctx) {
return mutate(record, accessor, MutateType.setIn, value, ctx);
} | [
"function",
"setIn",
"(",
"record",
",",
"accessor",
",",
"value",
",",
"ctx",
")",
"{",
"return",
"mutate",
"(",
"record",
",",
"accessor",
",",
"MutateType",
".",
"setIn",
",",
"value",
",",
"ctx",
")",
";",
"}"
] | Set a deep child
@param record The object to update, it can be a plain object or a class instance
@param accessor A lambda function to get the key path, support dot, [''], [""], [1], **do not** support dynamic variable, function call, e.g.
@param value The new value to set, if it is ignored it will be set to undefined.
@param ctx Dynamic key map. | [
"Set",
"a",
"deep",
"child"
] | 59596fcd885276e5db119a00953470066670f265 | https://github.com/hydux/hydux-mutator/blob/59596fcd885276e5db119a00953470066670f265/lib/index.js#L139-L141 |
35,214 | hydux/hydux-mutator | lib/index.js | unsetIn | function unsetIn(record, accessor, ctx) {
return mutate(record, accessor, MutateType.setIn, void 0, ctx);
} | javascript | function unsetIn(record, accessor, ctx) {
return mutate(record, accessor, MutateType.setIn, void 0, ctx);
} | [
"function",
"unsetIn",
"(",
"record",
",",
"accessor",
",",
"ctx",
")",
"{",
"return",
"mutate",
"(",
"record",
",",
"accessor",
",",
"MutateType",
".",
"setIn",
",",
"void",
"0",
",",
"ctx",
")",
";",
"}"
] | Unset a deep child
@param record The object to update, it can be a plain object or a class instance
@param accessor A lambda function to get the key path, support dot, [''], [""], [1], **do not** support dynamic variable, function call, e.g.
@param ctx Dynamic key map. | [
"Unset",
"a",
"deep",
"child"
] | 59596fcd885276e5db119a00953470066670f265 | https://github.com/hydux/hydux-mutator/blob/59596fcd885276e5db119a00953470066670f265/lib/index.js#L150-L152 |
35,215 | hydux/hydux-mutator | lib/index.js | updateIn | function updateIn(record, accessor, updator, ctx) {
if (!updator) {
return record;
}
return mutate(record, accessor, MutateType.updateIn, updator, ctx);
} | javascript | function updateIn(record, accessor, updator, ctx) {
if (!updator) {
return record;
}
return mutate(record, accessor, MutateType.updateIn, updator, ctx);
} | [
"function",
"updateIn",
"(",
"record",
",",
"accessor",
",",
"updator",
",",
"ctx",
")",
"{",
"if",
"(",
"!",
"updator",
")",
"{",
"return",
"record",
";",
"}",
"return",
"mutate",
"(",
"record",
",",
"accessor",
",",
"MutateType",
".",
"updateIn",
","... | Update a deep child by old value
@param record The object to update, it can be a plain object or a class instance
@param accessor A lambda function to get the key path, support dot, [''], [""], [1], **do not** support dynamic variable, function call, e.g.
@param updator A update function that take the old value and return the new value.
@param ctx Dynamic key map. | [
"Update",
"a",
"deep",
"child",
"by",
"old",
"value"
] | 59596fcd885276e5db119a00953470066670f265 | https://github.com/hydux/hydux-mutator/blob/59596fcd885276e5db119a00953470066670f265/lib/index.js#L161-L166 |
35,216 | glenjamin/react-hotkey | index.js | handle | function handle(nativeEvent) {
var event = SyntheticKeyboardEvent.getPooled({}, 'hotkey', nativeEvent);
try {
dispatchEvent(event, handlers);
} finally {
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
} | javascript | function handle(nativeEvent) {
var event = SyntheticKeyboardEvent.getPooled({}, 'hotkey', nativeEvent);
try {
dispatchEvent(event, handlers);
} finally {
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
} | [
"function",
"handle",
"(",
"nativeEvent",
")",
"{",
"var",
"event",
"=",
"SyntheticKeyboardEvent",
".",
"getPooled",
"(",
"{",
"}",
",",
"'hotkey'",
",",
"nativeEvent",
")",
";",
"try",
"{",
"dispatchEvent",
"(",
"event",
",",
"handlers",
")",
";",
"}",
... | Create and dispatch an event object using React's object pool Cribbed from SimpleEventPlugin and EventPluginHub | [
"Create",
"and",
"dispatch",
"an",
"event",
"object",
"using",
"React",
"s",
"object",
"pool",
"Cribbed",
"from",
"SimpleEventPlugin",
"and",
"EventPluginHub"
] | 7cd9eec4f7f5c9f5a726c953591bcbb1c1668786 | https://github.com/glenjamin/react-hotkey/blob/7cd9eec4f7f5c9f5a726c953591bcbb1c1668786/index.js#L73-L82 |
35,217 | glenjamin/react-hotkey | index.js | dispatchEvent | function dispatchEvent(event, handlers) {
for (var i = (handlers.length - 1); i >= 0; i--) {
if (event.isPropagationStopped()) {
break;
}
var returnValue = handlers[i](event);
if (returnValue === false) {
event.stopPropagation();
event.preventDefault();
}
}
} | javascript | function dispatchEvent(event, handlers) {
for (var i = (handlers.length - 1); i >= 0; i--) {
if (event.isPropagationStopped()) {
break;
}
var returnValue = handlers[i](event);
if (returnValue === false) {
event.stopPropagation();
event.preventDefault();
}
}
} | [
"function",
"dispatchEvent",
"(",
"event",
",",
"handlers",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"(",
"handlers",
".",
"length",
"-",
"1",
")",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"if",
"(",
"event",
".",
"isPropagationStopped",
"(",
... | Dispatch the event, in order, to all interested listeners The most recently mounted component is the first to receive the event Cribbed from a combination of SimpleEventPlugin and EventPluginUtils | [
"Dispatch",
"the",
"event",
"in",
"order",
"to",
"all",
"interested",
"listeners",
"The",
"most",
"recently",
"mounted",
"component",
"is",
"the",
"first",
"to",
"receive",
"the",
"event",
"Cribbed",
"from",
"a",
"combination",
"of",
"SimpleEventPlugin",
"and",
... | 7cd9eec4f7f5c9f5a726c953591bcbb1c1668786 | https://github.com/glenjamin/react-hotkey/blob/7cd9eec4f7f5c9f5a726c953591bcbb1c1668786/index.js#L86-L97 |
35,218 | cucumber-attic/gherkin-syntax-highlighters | shjs/shjs-0.6-src/scriptaculous-js-1.8.1/lib/prototype.js | function(nodes) {
if (nodes.length == 0) return nodes;
var results = [], n;
for (var i = 0, l = nodes.length; i < l; i++)
if (!(n = nodes[i])._counted) {
n._counted = true;
results.push(Element.extend(n));
}
return Selector.handlers.unmark(results);
} | javascript | function(nodes) {
if (nodes.length == 0) return nodes;
var results = [], n;
for (var i = 0, l = nodes.length; i < l; i++)
if (!(n = nodes[i])._counted) {
n._counted = true;
results.push(Element.extend(n));
}
return Selector.handlers.unmark(results);
} | [
"function",
"(",
"nodes",
")",
"{",
"if",
"(",
"nodes",
".",
"length",
"==",
"0",
")",
"return",
"nodes",
";",
"var",
"results",
"=",
"[",
"]",
",",
"n",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"nodes",
".",
"length",
";",
"i",
... | filters out duplicates and extends all nodes | [
"filters",
"out",
"duplicates",
"and",
"extends",
"all",
"nodes"
] | 0eb0eadc1bc274c86047d12f7267c6e905bd35be | https://github.com/cucumber-attic/gherkin-syntax-highlighters/blob/0eb0eadc1bc274c86047d12f7267c6e905bd35be/shjs/shjs-0.6-src/scriptaculous-js-1.8.1/lib/prototype.js#L3003-L3012 | |
35,219 | nwhetsell/csound-api | examples/log-json-syntax-tree.js | addNextNodesToASTObject | function addNextNodesToASTObject(ASTObject) {
const ASTObjectsForDepths = [ASTObject];
function addNextNodes(ASTObject, depth) {
const depthPlus1 = depth + 1;
ASTObjectsForDepths[depthPlus1] = ASTObject;
if (ASTObject.left)
addNextNodes(ASTObject.left, depthPlus1);
if (ASTObject.right)
addNextNodes(ASTObject.right, depthPlus1);
if (ASTObject.next) {
const ASTObjectForDepth = ASTObjectsForDepths[depth];
if (ASTObjectForDepth.nextNodes)
ASTObjectForDepth.nextNodes.push(ASTObject.next);
else
ASTObjectForDepth.nextNodes = [ASTObject.next];
addNextNodes(ASTObject.next, depth);
}
}
addNextNodes(ASTObject, 0);
} | javascript | function addNextNodesToASTObject(ASTObject) {
const ASTObjectsForDepths = [ASTObject];
function addNextNodes(ASTObject, depth) {
const depthPlus1 = depth + 1;
ASTObjectsForDepths[depthPlus1] = ASTObject;
if (ASTObject.left)
addNextNodes(ASTObject.left, depthPlus1);
if (ASTObject.right)
addNextNodes(ASTObject.right, depthPlus1);
if (ASTObject.next) {
const ASTObjectForDepth = ASTObjectsForDepths[depth];
if (ASTObjectForDepth.nextNodes)
ASTObjectForDepth.nextNodes.push(ASTObject.next);
else
ASTObjectForDepth.nextNodes = [ASTObject.next];
addNextNodes(ASTObject.next, depth);
}
}
addNextNodes(ASTObject, 0);
} | [
"function",
"addNextNodesToASTObject",
"(",
"ASTObject",
")",
"{",
"const",
"ASTObjectsForDepths",
"=",
"[",
"ASTObject",
"]",
";",
"function",
"addNextNodes",
"(",
"ASTObject",
",",
"depth",
")",
"{",
"const",
"depthPlus1",
"=",
"depth",
"+",
"1",
";",
"ASTOb... | The next property of an AST node seems to be for the second argument of an opcode, its next property for the third argument, and so on. Add nextNodes properties to AST objects to reflect this relationship. | [
"The",
"next",
"property",
"of",
"an",
"AST",
"node",
"seems",
"to",
"be",
"for",
"the",
"second",
"argument",
"of",
"an",
"opcode",
"its",
"next",
"property",
"for",
"the",
"third",
"argument",
"and",
"so",
"on",
".",
"Add",
"nextNodes",
"properties",
"... | 931d5b5ffe03f89f0269046e4306b444c6eb9393 | https://github.com/nwhetsell/csound-api/blob/931d5b5ffe03f89f0269046e4306b444c6eb9393/examples/log-json-syntax-tree.js#L21-L40 |
35,220 | bmancini55/node-trx | trx.js | Counter | function Counter() {
this.total = 0;
this.executed = 0;
this.passed = 0;
this.error = 0;
this.failed = 0;
this.timeout = 0;
this.aborted = 0;
this.inconclusive = 0;
this.passedButRunAborted = 0;
this.notRunnable = 0;
this.notExecuted = 0;
this.disconnected = 0;
this.warning = 0;
this.completed = 0;
this.inProgress = 0;
this.pending = 0;
} | javascript | function Counter() {
this.total = 0;
this.executed = 0;
this.passed = 0;
this.error = 0;
this.failed = 0;
this.timeout = 0;
this.aborted = 0;
this.inconclusive = 0;
this.passedButRunAborted = 0;
this.notRunnable = 0;
this.notExecuted = 0;
this.disconnected = 0;
this.warning = 0;
this.completed = 0;
this.inProgress = 0;
this.pending = 0;
} | [
"function",
"Counter",
"(",
")",
"{",
"this",
".",
"total",
"=",
"0",
";",
"this",
".",
"executed",
"=",
"0",
";",
"this",
".",
"passed",
"=",
"0",
";",
"this",
".",
"error",
"=",
"0",
";",
"this",
".",
"failed",
"=",
"0",
";",
"this",
".",
"... | Counter is defined by the XSD | [
"Counter",
"is",
"defined",
"by",
"the",
"XSD"
] | 139c01ecf4b1fb6ffac3f0c7bee73e8cba15a281 | https://github.com/bmancini55/node-trx/blob/139c01ecf4b1fb6ffac3f0c7bee73e8cba15a281/trx.js#L137-L154 |
35,221 | bmancini55/node-trx | trx.js | Times | function Times(params) {
this.creation = params.creation;
this.queuing = params.queuing;
this.start = params.start;
this.finish = params.finish;
} | javascript | function Times(params) {
this.creation = params.creation;
this.queuing = params.queuing;
this.start = params.start;
this.finish = params.finish;
} | [
"function",
"Times",
"(",
"params",
")",
"{",
"this",
".",
"creation",
"=",
"params",
".",
"creation",
";",
"this",
".",
"queuing",
"=",
"params",
".",
"queuing",
";",
"this",
".",
"start",
"=",
"params",
".",
"start",
";",
"this",
".",
"finish",
"="... | A Times as defined by the XSD type `Times`
@param {object} params
@config creation
@config queuing
@config start
@config finish | [
"A",
"Times",
"as",
"defined",
"by",
"the",
"XSD",
"type",
"Times"
] | 139c01ecf4b1fb6ffac3f0c7bee73e8cba15a281 | https://github.com/bmancini55/node-trx/blob/139c01ecf4b1fb6ffac3f0c7bee73e8cba15a281/trx.js#L199-L204 |
35,222 | bmancini55/node-trx | trx.js | Deployment | function Deployment(params) {
this.runDeploymentRoot = params.runDeploymentRoot
this.userDeploymentRoot = params.userDeploymentRoot
this.deploySatelliteAssemblies = params.deploySatelliteAssemblies
this.ignoredDependentAssemblies = params.ignoredDependentAssemblies
this.enabled = params.enabled
} | javascript | function Deployment(params) {
this.runDeploymentRoot = params.runDeploymentRoot
this.userDeploymentRoot = params.userDeploymentRoot
this.deploySatelliteAssemblies = params.deploySatelliteAssemblies
this.ignoredDependentAssemblies = params.ignoredDependentAssemblies
this.enabled = params.enabled
} | [
"function",
"Deployment",
"(",
"params",
")",
"{",
"this",
".",
"runDeploymentRoot",
"=",
"params",
".",
"runDeploymentRoot",
"this",
".",
"userDeploymentRoot",
"=",
"params",
".",
"userDeploymentRoot",
"this",
".",
"deploySatelliteAssemblies",
"=",
"params",
".",
... | A Deployment element as defined by the XSD type `Deployment`
@param {object} params
@config {string} [runDeploymentRoot] - name of the folder where any files generated by the tests will be located
@config {string} [userDeploymentRoot]
@config {string} [deploySatelliteAssemblies]
@config {string} [ignoredDependentAssemblies]
@config {string} [enabled] | [
"A",
"Deployment",
"element",
"as",
"defined",
"by",
"the",
"XSD",
"type",
"Deployment"
] | 139c01ecf4b1fb6ffac3f0c7bee73e8cba15a281 | https://github.com/bmancini55/node-trx/blob/139c01ecf4b1fb6ffac3f0c7bee73e8cba15a281/trx.js#L228-L234 |
35,223 | claudio-silva/grunt-angular-builder | tasks/angular-builder.js | assembleMiddleware | function assembleMiddleware (middlewareStackClasses, context)
{
var middlewares = [];
middlewareStackClasses.forEach (function (MiddlewareClass)
{
middlewares.push (new MiddlewareClass (context));
});
return middlewares;
} | javascript | function assembleMiddleware (middlewareStackClasses, context)
{
var middlewares = [];
middlewareStackClasses.forEach (function (MiddlewareClass)
{
middlewares.push (new MiddlewareClass (context));
});
return middlewares;
} | [
"function",
"assembleMiddleware",
"(",
"middlewareStackClasses",
",",
"context",
")",
"{",
"var",
"middlewares",
"=",
"[",
"]",
";",
"middlewareStackClasses",
".",
"forEach",
"(",
"function",
"(",
"MiddlewareClass",
")",
"{",
"middlewares",
".",
"push",
"(",
"ne... | Creates a new instance of each loaded middleware and assembles them into a sequential list.
@param {MiddlewareInterface[]} middlewareStackClasses An ordered list of classes to be instantiated.
@param {Context} context The build execution context.
@returns {MiddlewareInterface[]} | [
"Creates",
"a",
"new",
"instance",
"of",
"each",
"loaded",
"middleware",
"and",
"assembles",
"them",
"into",
"a",
"sequential",
"list",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/angular-builder.js#L172-L180 |
35,224 | claudio-silva/grunt-angular-builder | tasks/angular-builder.js | traceModule | function traceModule (moduleName, context, processHook)
{
var module = context.modules[moduleName];
if (!module)
fatal ('Module <cyan>%</cyan> was not found.', moduleName);
// Ignore the module if it's external.
if (module.external)
return;
// Include required submodules first.
context.trigger (ContextEvent.ON_BEFORE_DEPS, [module]);
module.requires.forEach (function (modName)
{
traceModule (modName, context, processHook);
});
// Ignore references to already loaded modules or to explicitly excluded modules.
if (!context.loaded[module.name] && !~context.options.excludedModules.indexOf (module.name)) {
info ('Including module <cyan>%</cyan>.', moduleName);
context.loaded[module.name] = true;
processHook (module);
}
} | javascript | function traceModule (moduleName, context, processHook)
{
var module = context.modules[moduleName];
if (!module)
fatal ('Module <cyan>%</cyan> was not found.', moduleName);
// Ignore the module if it's external.
if (module.external)
return;
// Include required submodules first.
context.trigger (ContextEvent.ON_BEFORE_DEPS, [module]);
module.requires.forEach (function (modName)
{
traceModule (modName, context, processHook);
});
// Ignore references to already loaded modules or to explicitly excluded modules.
if (!context.loaded[module.name] && !~context.options.excludedModules.indexOf (module.name)) {
info ('Including module <cyan>%</cyan>.', moduleName);
context.loaded[module.name] = true;
processHook (module);
}
} | [
"function",
"traceModule",
"(",
"moduleName",
",",
"context",
",",
"processHook",
")",
"{",
"var",
"module",
"=",
"context",
".",
"modules",
"[",
"moduleName",
"]",
";",
"if",
"(",
"!",
"module",
")",
"fatal",
"(",
"'Module <cyan>%</cyan> was not found.'",
","... | Traces a dependency graph for the specified module and calls the given callback
to process each required module in the correct loading order.
@param {string} moduleName
@param {Context} context The execution context for the middleware stack.
@param {function(ModuleDef)} processHook | [
"Traces",
"a",
"dependency",
"graph",
"for",
"the",
"specified",
"module",
"and",
"calls",
"the",
"given",
"callback",
"to",
"process",
"each",
"required",
"module",
"in",
"the",
"correct",
"loading",
"order",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/angular-builder.js#L189-L209 |
35,225 | JamesMessinger/json-schema-lib | lib/util/safeCall.js | safeCall | function safeCall (fn, args, callback) {
args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
var callbackCalled;
try {
args.push(safeCallback);
fn.apply(null, args);
}
catch (err) {
if (callbackCalled) {
throw err;
}
else {
safeCallback(err);
}
}
function safeCallback (err, result) {
if (callbackCalled) {
err = ono('Error in %s: callback was called multiple times', fn.name);
}
callbackCalled = true;
callback(err, result);
}
} | javascript | function safeCall (fn, args, callback) {
args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
var callbackCalled;
try {
args.push(safeCallback);
fn.apply(null, args);
}
catch (err) {
if (callbackCalled) {
throw err;
}
else {
safeCallback(err);
}
}
function safeCallback (err, result) {
if (callbackCalled) {
err = ono('Error in %s: callback was called multiple times', fn.name);
}
callbackCalled = true;
callback(err, result);
}
} | [
"function",
"safeCall",
"(",
"fn",
",",
"args",
",",
"callback",
")",
"{",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"callback",
"=",
"args",
".",
"pop",
"(",
")",
";",
"var",
"callback... | Calls the specified function with the given arguments, ensuring that the callback
is only called once, and that it's called even if an unhandled error occurs.
@param {function} fn - The function to call
@param {...*} [args] - The arguments to pass to the function
@param {function} callback - The callback function | [
"Calls",
"the",
"specified",
"function",
"with",
"the",
"given",
"arguments",
"ensuring",
"that",
"the",
"callback",
"is",
"only",
"called",
"once",
"and",
"that",
"it",
"s",
"called",
"even",
"if",
"an",
"unhandled",
"error",
"occurs",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/safeCall.js#L15-L41 |
35,226 | JamesMessinger/json-schema-lib | lib/api/JsonSchemaLib/read.js | readReferencedFiles | function readReferencedFiles (schema, callback) {
var filesBeingRead = [], filesToRead = [];
var file, i;
// Check the state of all files in the schema
for (i = 0; i < schema.files.length; i++) {
file = schema.files[i];
if (file[__internal].state < STATE_READING) {
filesToRead.push(file);
}
else if (file[__internal].state < STATE_READ) {
filesBeingRead.push(file);
}
}
// Have we finished reading everything?
if (filesToRead.length === 0 && filesBeingRead.length === 0) {
return safeCall(finished, schema, callback);
}
// In sync mode, just read the next file.
// In async mode, start reading all files in the queue
var numberOfFilesToRead = schema.config.sync ? 1 : filesToRead.length;
for (i = 0; i < numberOfFilesToRead; i++) {
file = filesToRead[i];
safeCall(readFile, file, callback);
}
} | javascript | function readReferencedFiles (schema, callback) {
var filesBeingRead = [], filesToRead = [];
var file, i;
// Check the state of all files in the schema
for (i = 0; i < schema.files.length; i++) {
file = schema.files[i];
if (file[__internal].state < STATE_READING) {
filesToRead.push(file);
}
else if (file[__internal].state < STATE_READ) {
filesBeingRead.push(file);
}
}
// Have we finished reading everything?
if (filesToRead.length === 0 && filesBeingRead.length === 0) {
return safeCall(finished, schema, callback);
}
// In sync mode, just read the next file.
// In async mode, start reading all files in the queue
var numberOfFilesToRead = schema.config.sync ? 1 : filesToRead.length;
for (i = 0; i < numberOfFilesToRead; i++) {
file = filesToRead[i];
safeCall(readFile, file, callback);
}
} | [
"function",
"readReferencedFiles",
"(",
"schema",
",",
"callback",
")",
"{",
"var",
"filesBeingRead",
"=",
"[",
"]",
",",
"filesToRead",
"=",
"[",
"]",
";",
"var",
"file",
",",
"i",
";",
"// Check the state of all files in the schema",
"for",
"(",
"i",
"=",
... | Reads any files in the schema that haven't been read yet.
@param {Schema} schema
@param {function} callback | [
"Reads",
"any",
"files",
"in",
"the",
"schema",
"that",
"haven",
"t",
"been",
"read",
"yet",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/JsonSchemaLib/read.js#L113-L142 |
35,227 | JamesMessinger/json-schema-lib | lib/api/JsonSchemaLib/read.js | finished | function finished (schema, callback) {
schema.plugins.finished();
delete schema.config.sync;
callback(null, schema);
} | javascript | function finished (schema, callback) {
schema.plugins.finished();
delete schema.config.sync;
callback(null, schema);
} | [
"function",
"finished",
"(",
"schema",
",",
"callback",
")",
"{",
"schema",
".",
"plugins",
".",
"finished",
"(",
")",
";",
"delete",
"schema",
".",
"config",
".",
"sync",
";",
"callback",
"(",
"null",
",",
"schema",
")",
";",
"}"
] | Performs final cleanup steps on the schema after all files have been read successfully.
@param {Schema} schema
@param {function} callback | [
"Performs",
"final",
"cleanup",
"steps",
"on",
"the",
"schema",
"after",
"all",
"files",
"have",
"been",
"read",
"successfully",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/JsonSchemaLib/read.js#L150-L154 |
35,228 | matteodelabre/midijs | lib/file/parser/event.js | parseMetaEvent | function parseMetaEvent(delay, cursor) {
var type, specs = {}, length, value, rates;
rates = [24, 25, 30, 30];
type = cursor.readUInt8();
length = parseVarInt(cursor);
switch (type) {
case MetaEvent.TYPE.SEQUENCE_NUMBER:
specs.number = cursor.readUInt16LE();
break;
case MetaEvent.TYPE.TEXT:
case MetaEvent.TYPE.COPYRIGHT_NOTICE:
case MetaEvent.TYPE.SEQUENCE_NAME:
case MetaEvent.TYPE.INSTRUMENT_NAME:
case MetaEvent.TYPE.LYRICS:
case MetaEvent.TYPE.MARKER:
case MetaEvent.TYPE.CUE_POINT:
case MetaEvent.TYPE.PROGRAM_NAME:
case MetaEvent.TYPE.DEVICE_NAME:
specs.text = cursor.toString('utf8', length);
break;
case MetaEvent.TYPE.MIDI_CHANNEL:
specs.channel = cursor.readUInt8();
break;
case MetaEvent.TYPE.MIDI_PORT:
specs.port = cursor.readUInt8();
break;
case MetaEvent.TYPE.END_OF_TRACK:
break;
case MetaEvent.TYPE.SET_TEMPO:
specs.tempo = 60000000 / ((cursor.readUInt8() << 16) +
(cursor.readUInt8() << 8) +
cursor.readUInt8());
break;
case MetaEvent.TYPE.SMPTE_OFFSET:
value = cursor.readUInt8();
specs.rate = rates[value >> 6];
specs.hours = value & 0x3F;
specs.minutes = cursor.readUInt8();
specs.seconds = cursor.readUInt8();
specs.frames = cursor.readUInt8();
specs.subframes = cursor.readUInt8();
break;
case MetaEvent.TYPE.TIME_SIGNATURE:
specs.numerator = cursor.readUInt8();
specs.denominator = Math.pow(2, cursor.readUInt8());
specs.metronome = cursor.readUInt8();
specs.clockSignalsPerBeat = (192 / cursor.readUInt8());
break;
case MetaEvent.TYPE.KEY_SIGNATURE:
specs.note = cursor.readInt8();
specs.major = !cursor.readUInt8();
break;
case MetaEvent.TYPE.SEQUENCER_SPECIFIC:
specs.data = cursor.slice(length).buffer;
break;
default:
throw new error.MIDIParserError(
type,
'known MetaEvent type',
cursor.tell()
);
}
return new MetaEvent(type, specs, delay);
} | javascript | function parseMetaEvent(delay, cursor) {
var type, specs = {}, length, value, rates;
rates = [24, 25, 30, 30];
type = cursor.readUInt8();
length = parseVarInt(cursor);
switch (type) {
case MetaEvent.TYPE.SEQUENCE_NUMBER:
specs.number = cursor.readUInt16LE();
break;
case MetaEvent.TYPE.TEXT:
case MetaEvent.TYPE.COPYRIGHT_NOTICE:
case MetaEvent.TYPE.SEQUENCE_NAME:
case MetaEvent.TYPE.INSTRUMENT_NAME:
case MetaEvent.TYPE.LYRICS:
case MetaEvent.TYPE.MARKER:
case MetaEvent.TYPE.CUE_POINT:
case MetaEvent.TYPE.PROGRAM_NAME:
case MetaEvent.TYPE.DEVICE_NAME:
specs.text = cursor.toString('utf8', length);
break;
case MetaEvent.TYPE.MIDI_CHANNEL:
specs.channel = cursor.readUInt8();
break;
case MetaEvent.TYPE.MIDI_PORT:
specs.port = cursor.readUInt8();
break;
case MetaEvent.TYPE.END_OF_TRACK:
break;
case MetaEvent.TYPE.SET_TEMPO:
specs.tempo = 60000000 / ((cursor.readUInt8() << 16) +
(cursor.readUInt8() << 8) +
cursor.readUInt8());
break;
case MetaEvent.TYPE.SMPTE_OFFSET:
value = cursor.readUInt8();
specs.rate = rates[value >> 6];
specs.hours = value & 0x3F;
specs.minutes = cursor.readUInt8();
specs.seconds = cursor.readUInt8();
specs.frames = cursor.readUInt8();
specs.subframes = cursor.readUInt8();
break;
case MetaEvent.TYPE.TIME_SIGNATURE:
specs.numerator = cursor.readUInt8();
specs.denominator = Math.pow(2, cursor.readUInt8());
specs.metronome = cursor.readUInt8();
specs.clockSignalsPerBeat = (192 / cursor.readUInt8());
break;
case MetaEvent.TYPE.KEY_SIGNATURE:
specs.note = cursor.readInt8();
specs.major = !cursor.readUInt8();
break;
case MetaEvent.TYPE.SEQUENCER_SPECIFIC:
specs.data = cursor.slice(length).buffer;
break;
default:
throw new error.MIDIParserError(
type,
'known MetaEvent type',
cursor.tell()
);
}
return new MetaEvent(type, specs, delay);
} | [
"function",
"parseMetaEvent",
"(",
"delay",
",",
"cursor",
")",
"{",
"var",
"type",
",",
"specs",
"=",
"{",
"}",
",",
"length",
",",
"value",
",",
"rates",
";",
"rates",
"=",
"[",
"24",
",",
"25",
",",
"30",
",",
"30",
"]",
";",
"type",
"=",
"c... | Parse a meta MIDI event
@private
@param {number} delay Event delay in ticks
@param {module:buffercursor} cursor Buffer to parse
@throws {module:midijs/lib/error~MIDIParserError}
Failed to parse the meta event
@return {module:midijs/lib/file/event~MetaEvent} Parsed meta event | [
"Parse",
"a",
"meta",
"MIDI",
"event"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/event.js#L40-L107 |
35,229 | matteodelabre/midijs | lib/file/parser/event.js | parseSysexEvent | function parseSysexEvent(delay, type, cursor) {
var data, length = parseVarInt(cursor);
data = cursor.slice(length).buffer;
return new SysexEvent(type, data, delay);
} | javascript | function parseSysexEvent(delay, type, cursor) {
var data, length = parseVarInt(cursor);
data = cursor.slice(length).buffer;
return new SysexEvent(type, data, delay);
} | [
"function",
"parseSysexEvent",
"(",
"delay",
",",
"type",
",",
"cursor",
")",
"{",
"var",
"data",
",",
"length",
"=",
"parseVarInt",
"(",
"cursor",
")",
";",
"data",
"=",
"cursor",
".",
"slice",
"(",
"length",
")",
".",
"buffer",
";",
"return",
"new",
... | Parse a system exclusive MIDI event
@private
@param {number} delay Event delay in ticks
@param {number} type Sysex type
@param {module:buffercursor} cursor Buffer to parse
@return {module:midijs/lib/file/event~SysexEvent} Parsed sysex event | [
"Parse",
"a",
"system",
"exclusive",
"MIDI",
"event"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/event.js#L118-L123 |
35,230 | matteodelabre/midijs | lib/file/parser/event.js | parseChannelEvent | function parseChannelEvent(delay, type, channel, cursor) {
var specs = {};
switch (type) {
case ChannelEvent.TYPE.NOTE_OFF:
specs.note = cursor.readUInt8();
specs.velocity = cursor.readUInt8();
break;
case ChannelEvent.TYPE.NOTE_ON:
specs.note = cursor.readUInt8();
specs.velocity = cursor.readUInt8();
break;
case ChannelEvent.TYPE.NOTE_AFTERTOUCH:
specs.note = cursor.readUInt8();
specs.pressure = cursor.readUInt8();
break;
case ChannelEvent.TYPE.CONTROLLER:
specs.controller = cursor.readUInt8();
specs.value = cursor.readUInt8();
break;
case ChannelEvent.TYPE.PROGRAM_CHANGE:
specs.program = cursor.readUInt8();
break;
case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH:
specs.pressure = cursor.readUInt8();
break;
case ChannelEvent.TYPE.PITCH_BEND:
specs.value = cursor.readUInt8() +
(cursor.readUInt8() << 7) - 8192;
break;
}
return new ChannelEvent(type, specs, channel, delay);
} | javascript | function parseChannelEvent(delay, type, channel, cursor) {
var specs = {};
switch (type) {
case ChannelEvent.TYPE.NOTE_OFF:
specs.note = cursor.readUInt8();
specs.velocity = cursor.readUInt8();
break;
case ChannelEvent.TYPE.NOTE_ON:
specs.note = cursor.readUInt8();
specs.velocity = cursor.readUInt8();
break;
case ChannelEvent.TYPE.NOTE_AFTERTOUCH:
specs.note = cursor.readUInt8();
specs.pressure = cursor.readUInt8();
break;
case ChannelEvent.TYPE.CONTROLLER:
specs.controller = cursor.readUInt8();
specs.value = cursor.readUInt8();
break;
case ChannelEvent.TYPE.PROGRAM_CHANGE:
specs.program = cursor.readUInt8();
break;
case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH:
specs.pressure = cursor.readUInt8();
break;
case ChannelEvent.TYPE.PITCH_BEND:
specs.value = cursor.readUInt8() +
(cursor.readUInt8() << 7) - 8192;
break;
}
return new ChannelEvent(type, specs, channel, delay);
} | [
"function",
"parseChannelEvent",
"(",
"delay",
",",
"type",
",",
"channel",
",",
"cursor",
")",
"{",
"var",
"specs",
"=",
"{",
"}",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"ChannelEvent",
".",
"TYPE",
".",
"NOTE_OFF",
":",
"specs",
".",
"note",
... | Parse a channel event
@private
@param {number} delay Event delay in ticks
@param {number} type Event subtype
@param {number} channel Channel number
@param {module:buffercursor} cursor Buffer to parse
@return {module:midijs/lib/file/event~ChannelEvent} Parsed channel event | [
"Parse",
"a",
"channel",
"event"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/event.js#L135-L168 |
35,231 | matteodelabre/midijs | lib/file/parser/event.js | parseEvent | function parseEvent(cursor, runningStatus) {
var delay, status, result;
delay = parseVarInt(cursor);
status = cursor.readUInt8();
// if the most significant bit is not set,
// we use the last status
if ((status & 0x80) === 0) {
if (!runningStatus) {
throw new error.MIDIParserError(
'undefined event status',
cursor.tell()
);
}
status = runningStatus;
cursor.seek(cursor.tell() - 1);
} else {
runningStatus = status;
}
if (status === 0xFF) {
result = parseMetaEvent(delay, cursor);
} else if (status === 0xF0 || status === 0xF7) {
result = parseSysexEvent(delay, status & 0xF, cursor);
} else if (status >= 0x80 && status < 0xF0) {
result = parseChannelEvent(delay, status >> 4, status & 0xF, cursor);
} else {
throw new error.MIDIParserError(
status,
'known status type',
cursor.tell()
);
}
return {
runningStatus: runningStatus,
event: result
};
} | javascript | function parseEvent(cursor, runningStatus) {
var delay, status, result;
delay = parseVarInt(cursor);
status = cursor.readUInt8();
// if the most significant bit is not set,
// we use the last status
if ((status & 0x80) === 0) {
if (!runningStatus) {
throw new error.MIDIParserError(
'undefined event status',
cursor.tell()
);
}
status = runningStatus;
cursor.seek(cursor.tell() - 1);
} else {
runningStatus = status;
}
if (status === 0xFF) {
result = parseMetaEvent(delay, cursor);
} else if (status === 0xF0 || status === 0xF7) {
result = parseSysexEvent(delay, status & 0xF, cursor);
} else if (status >= 0x80 && status < 0xF0) {
result = parseChannelEvent(delay, status >> 4, status & 0xF, cursor);
} else {
throw new error.MIDIParserError(
status,
'known status type',
cursor.tell()
);
}
return {
runningStatus: runningStatus,
event: result
};
} | [
"function",
"parseEvent",
"(",
"cursor",
",",
"runningStatus",
")",
"{",
"var",
"delay",
",",
"status",
",",
"result",
";",
"delay",
"=",
"parseVarInt",
"(",
"cursor",
")",
";",
"status",
"=",
"cursor",
".",
"readUInt8",
"(",
")",
";",
"// if the most sign... | Parse any type of MIDI event
@param {BufferCursor} cursor Buffer to parse
@param {number} [runningStatus] Previous status if applicable
@throws {module:midijs/lib/error~MIDIParserError}
Unknown event status encountered or running status undefined
while being requested by this event's data
@return {Object} Parsed event and new running status | [
"Parse",
"any",
"type",
"of",
"MIDI",
"event"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/event.js#L180-L220 |
35,232 | matteodelabre/midijs | lib/file/encoder/event.js | encodeSysexEvent | function encodeSysexEvent(event) {
var cursor, length;
length = encodeVarInt(event.data.length);
cursor = new BufferCursor(new buffer.Buffer(
1 + length.length + event.data.length
));
cursor.writeUInt8(0xF0 | event.type);
cursor.copy(length);
cursor.copy(event.data);
return cursor.buffer;
} | javascript | function encodeSysexEvent(event) {
var cursor, length;
length = encodeVarInt(event.data.length);
cursor = new BufferCursor(new buffer.Buffer(
1 + length.length + event.data.length
));
cursor.writeUInt8(0xF0 | event.type);
cursor.copy(length);
cursor.copy(event.data);
return cursor.buffer;
} | [
"function",
"encodeSysexEvent",
"(",
"event",
")",
"{",
"var",
"cursor",
",",
"length",
";",
"length",
"=",
"encodeVarInt",
"(",
"event",
".",
"data",
".",
"length",
")",
";",
"cursor",
"=",
"new",
"BufferCursor",
"(",
"new",
"buffer",
".",
"Buffer",
"("... | Encode a system exclusive MIDI event
@private
@param {module:midijs/lib/file/event~SysexEvent} event Sysex event to encode
@return {Buffer} Encoded sysex event | [
"Encode",
"a",
"system",
"exclusive",
"MIDI",
"event"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/encoder/event.js#L150-L163 |
35,233 | matteodelabre/midijs | lib/file/encoder/event.js | encodeChannelEvent | function encodeChannelEvent(event) {
var cursor, eventData, value;
switch (event.type) {
case ChannelEvent.TYPE.NOTE_OFF:
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(event.note);
eventData.writeUInt8(event.velocity);
break;
case ChannelEvent.TYPE.NOTE_ON:
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(event.note);
eventData.writeUInt8(event.velocity);
break;
case ChannelEvent.TYPE.NOTE_AFTERTOUCH:
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(event.note);
eventData.writeUInt8(event.pressure);
break;
case ChannelEvent.TYPE.CONTROLLER:
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(event.controller);
eventData.writeUInt8(event.value);
break;
case ChannelEvent.TYPE.PROGRAM_CHANGE:
eventData = new BufferCursor(new buffer.Buffer(1));
eventData.writeUInt8(event.program);
break;
case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH:
eventData = new BufferCursor(new buffer.Buffer(1));
eventData.writeUInt8(event.pressure);
break;
case ChannelEvent.TYPE.PITCH_BEND:
value = event.value + 8192;
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(value & 0x7F);
eventData.writeUInt8(value >> 7);
break;
default:
throw new error.MIDIEncoderError(
event.type,
'known ChannelEvent type'
);
}
cursor = new BufferCursor(new buffer.Buffer(
1 + eventData.length
));
cursor.writeUInt8((event.type << 4) + event.channel);
cursor.copy(eventData.buffer);
return cursor.buffer;
} | javascript | function encodeChannelEvent(event) {
var cursor, eventData, value;
switch (event.type) {
case ChannelEvent.TYPE.NOTE_OFF:
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(event.note);
eventData.writeUInt8(event.velocity);
break;
case ChannelEvent.TYPE.NOTE_ON:
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(event.note);
eventData.writeUInt8(event.velocity);
break;
case ChannelEvent.TYPE.NOTE_AFTERTOUCH:
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(event.note);
eventData.writeUInt8(event.pressure);
break;
case ChannelEvent.TYPE.CONTROLLER:
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(event.controller);
eventData.writeUInt8(event.value);
break;
case ChannelEvent.TYPE.PROGRAM_CHANGE:
eventData = new BufferCursor(new buffer.Buffer(1));
eventData.writeUInt8(event.program);
break;
case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH:
eventData = new BufferCursor(new buffer.Buffer(1));
eventData.writeUInt8(event.pressure);
break;
case ChannelEvent.TYPE.PITCH_BEND:
value = event.value + 8192;
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(value & 0x7F);
eventData.writeUInt8(value >> 7);
break;
default:
throw new error.MIDIEncoderError(
event.type,
'known ChannelEvent type'
);
}
cursor = new BufferCursor(new buffer.Buffer(
1 + eventData.length
));
cursor.writeUInt8((event.type << 4) + event.channel);
cursor.copy(eventData.buffer);
return cursor.buffer;
} | [
"function",
"encodeChannelEvent",
"(",
"event",
")",
"{",
"var",
"cursor",
",",
"eventData",
",",
"value",
";",
"switch",
"(",
"event",
".",
"type",
")",
"{",
"case",
"ChannelEvent",
".",
"TYPE",
".",
"NOTE_OFF",
":",
"eventData",
"=",
"new",
"BufferCursor... | Encode a channel event
@private
@param {module:midijs/lib/file/event~ChannelEvent} event Channel event
@throws {module:midijs/lib/error~MIDIEncoderError}
Failed to encode the channel event
@return {Buffer} Encoded channel event | [
"Encode",
"a",
"channel",
"event"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/encoder/event.js#L174-L232 |
35,234 | matteodelabre/midijs | lib/file/encoder/event.js | encodeEvent | function encodeEvent(event, runningStatus) {
var delay, eventData, cursor;
delay = encodeVarInt(event.delay);
if (event instanceof MetaEvent) {
eventData = encodeMetaEvent(event);
} else if (event instanceof SysexEvent) {
eventData = encodeSysexEvent(event);
} else if (event instanceof ChannelEvent) {
eventData = encodeChannelEvent(event);
} else {
throw new error.MIDIEncoderError(
event.constructor.name,
'known Event type'
);
}
// if current type is the same as the last one,
// we don't include it
// (sysex events cancel the running status and
// meta events ignore it)
if (event instanceof ChannelEvent) {
if (runningStatus === eventData[0]) {
eventData = eventData.slice(1);
} else {
runningStatus = eventData[0];
}
} else if (event instanceof SysexEvent) {
runningStatus = null;
}
cursor = new BufferCursor(new buffer.Buffer(
delay.length + eventData.length
));
cursor.copy(delay);
cursor.copy(eventData);
return {
runningStatus: runningStatus,
data: cursor.buffer
};
} | javascript | function encodeEvent(event, runningStatus) {
var delay, eventData, cursor;
delay = encodeVarInt(event.delay);
if (event instanceof MetaEvent) {
eventData = encodeMetaEvent(event);
} else if (event instanceof SysexEvent) {
eventData = encodeSysexEvent(event);
} else if (event instanceof ChannelEvent) {
eventData = encodeChannelEvent(event);
} else {
throw new error.MIDIEncoderError(
event.constructor.name,
'known Event type'
);
}
// if current type is the same as the last one,
// we don't include it
// (sysex events cancel the running status and
// meta events ignore it)
if (event instanceof ChannelEvent) {
if (runningStatus === eventData[0]) {
eventData = eventData.slice(1);
} else {
runningStatus = eventData[0];
}
} else if (event instanceof SysexEvent) {
runningStatus = null;
}
cursor = new BufferCursor(new buffer.Buffer(
delay.length + eventData.length
));
cursor.copy(delay);
cursor.copy(eventData);
return {
runningStatus: runningStatus,
data: cursor.buffer
};
} | [
"function",
"encodeEvent",
"(",
"event",
",",
"runningStatus",
")",
"{",
"var",
"delay",
",",
"eventData",
",",
"cursor",
";",
"delay",
"=",
"encodeVarInt",
"(",
"event",
".",
"delay",
")",
";",
"if",
"(",
"event",
"instanceof",
"MetaEvent",
")",
"{",
"e... | Encode a MIDI event
@param {module:midijs/lib/file/event~Event} event Event to encode
@param {number} [runningStatus] Previous status if applicable
@throws {module:midijs/lib/error~MIDIInvalidArgument}
Unknown event encountered
@return {Object} Encoded data and new running status | [
"Encode",
"a",
"MIDI",
"event"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/encoder/event.js#L243-L286 |
35,235 | claudio-silva/grunt-angular-builder | tasks/middleware/overrideDependencies.js | OverrideDependenciesMiddleware | function OverrideDependenciesMiddleware (context)
{
/* jshint unused: vars */
var options = context.options.overrideDependencies
, enabled = options.dependencies && options.dependencies.length;
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
if (!enabled) return;
var mainModuleName = context.options.mainModule;
var mainModule = context.modules[mainModuleName] = new ModuleDef (mainModuleName);
mainModule.requires = options.dependencies;
// Must set head to a non-empty string to mark the module as being initialized.
mainModule.head = ' ';
};
this.trace = function (module)
{
/* jshint unused: vars */
};
this.build = function (targetScript)
{
/* jshint unused: vars */
if (!enabled) return;
if (context.options.debugBuild && context.options.debugBuild.enabled) {
var declaration = sprintf ("angular.module('%',%);",
context.options.mainModule,
util.toQuotedList (options.dependencies)
);
context.appendOutput += sprintf ('<script>%</script>', declaration);
}
};
} | javascript | function OverrideDependenciesMiddleware (context)
{
/* jshint unused: vars */
var options = context.options.overrideDependencies
, enabled = options.dependencies && options.dependencies.length;
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
if (!enabled) return;
var mainModuleName = context.options.mainModule;
var mainModule = context.modules[mainModuleName] = new ModuleDef (mainModuleName);
mainModule.requires = options.dependencies;
// Must set head to a non-empty string to mark the module as being initialized.
mainModule.head = ' ';
};
this.trace = function (module)
{
/* jshint unused: vars */
};
this.build = function (targetScript)
{
/* jshint unused: vars */
if (!enabled) return;
if (context.options.debugBuild && context.options.debugBuild.enabled) {
var declaration = sprintf ("angular.module('%',%);",
context.options.mainModule,
util.toQuotedList (options.dependencies)
);
context.appendOutput += sprintf ('<script>%</script>', declaration);
}
};
} | [
"function",
"OverrideDependenciesMiddleware",
"(",
"context",
")",
"{",
"/* jshint unused: vars */",
"var",
"options",
"=",
"context",
".",
"options",
".",
"overrideDependencies",
",",
"enabled",
"=",
"options",
".",
"dependencies",
"&&",
"options",
".",
"dependencies... | Allows the setting of the main module's dependencies via Grunt configuration options and synthetizes that module's
declaration javascript code.
@constructor
@implements {MiddlewareInterface}
@param {Context} context The execution context for the middleware stack. | [
"Allows",
"the",
"setting",
"of",
"the",
"main",
"module",
"s",
"dependencies",
"via",
"Grunt",
"configuration",
"options",
"and",
"synthetizes",
"that",
"module",
"s",
"declaration",
"javascript",
"code",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/overrideDependencies.js#L79-L119 |
35,236 | matteodelabre/midijs | lib/file/header.js | Header | function Header(fileType, trackCount, ticksPerBeat) {
this._fileType = fileType || Header.FILE_TYPE.SYNC_TRACKS;
this._trackCount = trackCount || 0;
this._ticksPerBeat = ticksPerBeat || 120;
} | javascript | function Header(fileType, trackCount, ticksPerBeat) {
this._fileType = fileType || Header.FILE_TYPE.SYNC_TRACKS;
this._trackCount = trackCount || 0;
this._ticksPerBeat = ticksPerBeat || 120;
} | [
"function",
"Header",
"(",
"fileType",
",",
"trackCount",
",",
"ticksPerBeat",
")",
"{",
"this",
".",
"_fileType",
"=",
"fileType",
"||",
"Header",
".",
"FILE_TYPE",
".",
"SYNC_TRACKS",
";",
"this",
".",
"_trackCount",
"=",
"trackCount",
"||",
"0",
";",
"t... | Construct a new Header
@class Header
@classdesc A Standard MIDI File's header (contains various metadata)
@param {module:midijs/lib/file/header~Header.FILE_TYPE}
fileType File type
@param {number} trackCount Amount of tracks in the file
@param {number} ticksPerBeat Beats rate in ticks per beat | [
"Construct",
"a",
"new",
"Header"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/header.js#L16-L20 |
35,237 | claudio-silva/grunt-angular-builder | tasks/middleware/buildAssets.js | BuildAssetsMiddleware | function BuildAssetsMiddleware (context)
{
var grunt = context.grunt
, options = context.options.assets;
/**
* Records which files have been already exported.
* Prevents duplicate asset exports.
* It's a map of absolute file names to boolean `true`.
* @type {Object.<string,boolean>}
*/
var exportedAssets = {};
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (module)
{
/* jshint unused: vars */
// Do nothing.
};
this.build = function (targetScript)
{
if (!options.enabled) return;
// Import file paths.
var stylehseets = grunt.config (context.options.requiredStylesheets.exportToConfigProperty);
if (!stylehseets) return; // No stylesheet sources are configured.
var targetPath = path.dirname (targetScript);
stylehseets.forEach (function (filePath)
{
var src = grunt.file.read (filePath);
scan (path.dirname (filePath), targetPath, src);
});
};
//--------------------------------------------------------------------------------------------------------------------
// PRIVATE
//--------------------------------------------------------------------------------------------------------------------
/**
* Scans a stylesheet for asset URL references and copies the assets to the build folder.
* @private
* @param {string} basePath
* @param {string} targetPath
* @param {string} sourceCode
*/
function scan (basePath, targetPath, sourceCode)
{
var match;
while ((match = MATCH_URLS.exec (sourceCode))) {
var url = match[2];
if (!url.match (/^http/i) && url[0] !== '/') { // Skip absolute URLs
var absSrcPath = path.resolve (basePath, url)
, absDestPath = path.resolve (targetPath, options.targetDir, url)
, relDestPath = path.relative (targetPath, absDestPath);
if (relDestPath[0] === '.')
return util.warn ('Relative asset url falls outside the build folder: <cyan>%</cyan>%', url, util.NL);
if (exportedAssets[absDestPath]) // skip already exported asset
continue;
else exportedAssets[absDestPath] = true;
var absTargetFolder = path.dirname (absDestPath);
grunt.file.mkdir (absTargetFolder);
if (options.symlink)
fs.symlinkSync (absSrcPath, absDestPath);
else grunt.file.copy (absSrcPath, absDestPath);
}
}
}
} | javascript | function BuildAssetsMiddleware (context)
{
var grunt = context.grunt
, options = context.options.assets;
/**
* Records which files have been already exported.
* Prevents duplicate asset exports.
* It's a map of absolute file names to boolean `true`.
* @type {Object.<string,boolean>}
*/
var exportedAssets = {};
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (module)
{
/* jshint unused: vars */
// Do nothing.
};
this.build = function (targetScript)
{
if (!options.enabled) return;
// Import file paths.
var stylehseets = grunt.config (context.options.requiredStylesheets.exportToConfigProperty);
if (!stylehseets) return; // No stylesheet sources are configured.
var targetPath = path.dirname (targetScript);
stylehseets.forEach (function (filePath)
{
var src = grunt.file.read (filePath);
scan (path.dirname (filePath), targetPath, src);
});
};
//--------------------------------------------------------------------------------------------------------------------
// PRIVATE
//--------------------------------------------------------------------------------------------------------------------
/**
* Scans a stylesheet for asset URL references and copies the assets to the build folder.
* @private
* @param {string} basePath
* @param {string} targetPath
* @param {string} sourceCode
*/
function scan (basePath, targetPath, sourceCode)
{
var match;
while ((match = MATCH_URLS.exec (sourceCode))) {
var url = match[2];
if (!url.match (/^http/i) && url[0] !== '/') { // Skip absolute URLs
var absSrcPath = path.resolve (basePath, url)
, absDestPath = path.resolve (targetPath, options.targetDir, url)
, relDestPath = path.relative (targetPath, absDestPath);
if (relDestPath[0] === '.')
return util.warn ('Relative asset url falls outside the build folder: <cyan>%</cyan>%', url, util.NL);
if (exportedAssets[absDestPath]) // skip already exported asset
continue;
else exportedAssets[absDestPath] = true;
var absTargetFolder = path.dirname (absDestPath);
grunt.file.mkdir (absTargetFolder);
if (options.symlink)
fs.symlinkSync (absSrcPath, absDestPath);
else grunt.file.copy (absSrcPath, absDestPath);
}
}
}
} | [
"function",
"BuildAssetsMiddleware",
"(",
"context",
")",
"{",
"var",
"grunt",
"=",
"context",
".",
"grunt",
",",
"options",
"=",
"context",
".",
"options",
".",
"assets",
";",
"/**\n * Records which files have been already exported.\n * Prevents duplicate asset exports... | Exports the assets required by the application's modules.
@constructor
@implements {MiddlewareInterface}
@param {Context} context The execution context for the middleware stack. | [
"Exports",
"the",
"assets",
"required",
"by",
"the",
"application",
"s",
"modules",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/buildAssets.js#L79-L157 |
35,238 | claudio-silva/grunt-angular-builder | tasks/middleware/makeDebugBuild.js | MakeDebugBuildMiddleware | function MakeDebugBuildMiddleware (context)
{
var options = context.options.debugBuild;
/** @type {string[]} */
var traceOutput = [];
//--------------------------------------------------------------------------------------------------------------------
// EVENTS
//--------------------------------------------------------------------------------------------------------------------
context.listen (ContextEvent.ON_AFTER_ANALYZE, function ()
{
if (options.enabled) {
var space = context.verbose ? NL : '';
writeln ('%Generating the <cyan>debug</cyan> build...%', space, space);
}
});
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (/*ModuleDef*/ module)
{
if (!options.enabled) return;
var rep = options.rebaseDebugUrls;
module.filePaths ().forEach (function (path)
{
if (context.outputtedFiles[path] && context.outputtedFiles[path] !== module.name)
return;
context.outputtedFiles[path] = true;
if (rep)
for (var i = 0, m = rep.length; i < m; ++i)
path = path.replace (rep[i].match, rep[i].replaceWith);
if (path) // Ignore empty path; it means that this middleware should not output a script tag.
traceOutput.push (util.sprintf ('<script src=\"%\"></script>', path));
});
};
this.build = function (targetScript)
{
/* jshint unused: vars */
if (!options.enabled) return;
/** @type {string[]} */
var output = ['document.write (\''];
if (context.prependOutput)
output.push (context.prependOutput);
// Output the modules (if any).
util.arrayAppend (output, traceOutput);
if (context.appendOutput)
output.push (context.appendOutput);
output.push ('\');');
util.writeFile (targetScript, output.join ('\\\n'));
};
} | javascript | function MakeDebugBuildMiddleware (context)
{
var options = context.options.debugBuild;
/** @type {string[]} */
var traceOutput = [];
//--------------------------------------------------------------------------------------------------------------------
// EVENTS
//--------------------------------------------------------------------------------------------------------------------
context.listen (ContextEvent.ON_AFTER_ANALYZE, function ()
{
if (options.enabled) {
var space = context.verbose ? NL : '';
writeln ('%Generating the <cyan>debug</cyan> build...%', space, space);
}
});
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (/*ModuleDef*/ module)
{
if (!options.enabled) return;
var rep = options.rebaseDebugUrls;
module.filePaths ().forEach (function (path)
{
if (context.outputtedFiles[path] && context.outputtedFiles[path] !== module.name)
return;
context.outputtedFiles[path] = true;
if (rep)
for (var i = 0, m = rep.length; i < m; ++i)
path = path.replace (rep[i].match, rep[i].replaceWith);
if (path) // Ignore empty path; it means that this middleware should not output a script tag.
traceOutput.push (util.sprintf ('<script src=\"%\"></script>', path));
});
};
this.build = function (targetScript)
{
/* jshint unused: vars */
if (!options.enabled) return;
/** @type {string[]} */
var output = ['document.write (\''];
if (context.prependOutput)
output.push (context.prependOutput);
// Output the modules (if any).
util.arrayAppend (output, traceOutput);
if (context.appendOutput)
output.push (context.appendOutput);
output.push ('\');');
util.writeFile (targetScript, output.join ('\\\n'));
};
} | [
"function",
"MakeDebugBuildMiddleware",
"(",
"context",
")",
"{",
"var",
"options",
"=",
"context",
".",
"options",
".",
"debugBuild",
";",
"/** @type {string[]} */",
"var",
"traceOutput",
"=",
"[",
"]",
";",
"//------------------------------------------------------------... | Generates a script file that inserts SCRIPT tags to the head of the html document, which will load the original
source scripts in the correct order. This is used on debug builds.
@constructor
@implements {MiddlewareInterface}
@param {Context} context The execution context for the middleware stack. | [
"Generates",
"a",
"script",
"file",
"that",
"inserts",
"SCRIPT",
"tags",
"to",
"the",
"head",
"of",
"the",
"html",
"document",
"which",
"will",
"load",
"the",
"original",
"source",
"scripts",
"in",
"the",
"correct",
"order",
".",
"This",
"is",
"used",
"on"... | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeDebugBuild.js#L75-L142 |
35,239 | jhermsmeier/node-tle | lib/stream.js | Parser | function Parser( options ) {
if( !(this instanceof Parser) )
return new Parser( options )
Stream.Transform.call( this, options )
this._readableState.objectMode = true
this._buffer = ''
} | javascript | function Parser( options ) {
if( !(this instanceof Parser) )
return new Parser( options )
Stream.Transform.call( this, options )
this._readableState.objectMode = true
this._buffer = ''
} | [
"function",
"Parser",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Parser",
")",
")",
"return",
"new",
"Parser",
"(",
"options",
")",
"Stream",
".",
"Transform",
".",
"call",
"(",
"this",
",",
"options",
")",
"this",
".",
"_r... | TLE Parser Stream
@constructor
@param {Object} [options]
@return {Parser} | [
"TLE",
"Parser",
"Stream"
] | 0c0a57270cd6573b912f007a5b9da83f98eba775 | https://github.com/jhermsmeier/node-tle/blob/0c0a57270cd6573b912f007a5b9da83f98eba775/lib/stream.js#L11-L21 |
35,240 | JamesMessinger/json-schema-lib | lib/plugins/HttpPlugin.js | readFileAsync | function readFileAsync (args) {
var file = args.file;
var config = args.config;
var next = args.next;
var url = parseUrl(file.url);
var transport;
switch (url.protocol) {
case 'http:':
transport = followRedirects.http;
break;
case 'https:':
transport = followRedirects.https;
break;
default:
// It's not an HTTP or HTTPS URL, so let some other plugin handle it
return next();
}
var httpConfig = {
hostname: url.hostname,
port: url.port,
path: url.pathname + url.search,
headers: Object.assign({}, defaultHeaders, config.http.headers),
timeout: config.http.timeout,
followRedirects: !!config.http.maxRedirects,
maxRedirects: config.http.maxRedirects,
};
var req = transport.get(httpConfig);
req.on('error', next);
req.on('timeout', function handleTimeout () {
req.abort();
});
req.once('response', function handleResponse (res) {
var responseChunks = [];
var chunksAreStrings = false;
decompressResponse(res);
setHttpMetadata(file, res);
res.on('error', next);
res.on('data', function handleResponseData (chunk) {
// Keep track of whether ANY of the chunks are strings (as opposed to Buffers)
if (typeof chunk === 'string') {
chunksAreStrings = true;
}
responseChunks.push(chunk);
});
res.on('end', function handleResponseEnd () {
try {
var response;
if (chunksAreStrings) {
// Return the response as a string
response = responseChunks.join('');
}
else {
// Return the response as a Buffer (Uint8Array)
response = Buffer.concat(responseChunks);
}
next(null, response);
}
catch (err) {
next(err);
}
});
});
} | javascript | function readFileAsync (args) {
var file = args.file;
var config = args.config;
var next = args.next;
var url = parseUrl(file.url);
var transport;
switch (url.protocol) {
case 'http:':
transport = followRedirects.http;
break;
case 'https:':
transport = followRedirects.https;
break;
default:
// It's not an HTTP or HTTPS URL, so let some other plugin handle it
return next();
}
var httpConfig = {
hostname: url.hostname,
port: url.port,
path: url.pathname + url.search,
headers: Object.assign({}, defaultHeaders, config.http.headers),
timeout: config.http.timeout,
followRedirects: !!config.http.maxRedirects,
maxRedirects: config.http.maxRedirects,
};
var req = transport.get(httpConfig);
req.on('error', next);
req.on('timeout', function handleTimeout () {
req.abort();
});
req.once('response', function handleResponse (res) {
var responseChunks = [];
var chunksAreStrings = false;
decompressResponse(res);
setHttpMetadata(file, res);
res.on('error', next);
res.on('data', function handleResponseData (chunk) {
// Keep track of whether ANY of the chunks are strings (as opposed to Buffers)
if (typeof chunk === 'string') {
chunksAreStrings = true;
}
responseChunks.push(chunk);
});
res.on('end', function handleResponseEnd () {
try {
var response;
if (chunksAreStrings) {
// Return the response as a string
response = responseChunks.join('');
}
else {
// Return the response as a Buffer (Uint8Array)
response = Buffer.concat(responseChunks);
}
next(null, response);
}
catch (err) {
next(err);
}
});
});
} | [
"function",
"readFileAsync",
"(",
"args",
")",
"{",
"var",
"file",
"=",
"args",
".",
"file",
";",
"var",
"config",
"=",
"args",
".",
"config",
";",
"var",
"next",
"=",
"args",
".",
"next",
";",
"var",
"url",
"=",
"parseUrl",
"(",
"file",
".",
"url"... | Asynchronously downlaods a file from an HTTP or HTTPS URL.
@param {File} args.file - The {@link File} to read
@param {function} args.next - Calls the next plugin, if the file is not a local filesystem file | [
"Asynchronously",
"downlaods",
"a",
"file",
"from",
"an",
"HTTP",
"or",
"HTTPS",
"URL",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/HttpPlugin.js#L41-L116 |
35,241 | JamesMessinger/json-schema-lib | lib/plugins/HttpPlugin.js | parseUrl | function parseUrl (url) {
if (typeof URL === 'function') {
// Use the new WHATWG URL API
return new URL(url);
}
else {
// Use the legacy url API
var parsed = legacyURL.parse(url);
// Replace nulls with default values, for compatibility with the WHATWG URL API
parsed.pathname = parsed.pathname || '/';
parsed.search = parsed.search || '';
}
} | javascript | function parseUrl (url) {
if (typeof URL === 'function') {
// Use the new WHATWG URL API
return new URL(url);
}
else {
// Use the legacy url API
var parsed = legacyURL.parse(url);
// Replace nulls with default values, for compatibility with the WHATWG URL API
parsed.pathname = parsed.pathname || '/';
parsed.search = parsed.search || '';
}
} | [
"function",
"parseUrl",
"(",
"url",
")",
"{",
"if",
"(",
"typeof",
"URL",
"===",
"'function'",
")",
"{",
"// Use the new WHATWG URL API",
"return",
"new",
"URL",
"(",
"url",
")",
";",
"}",
"else",
"{",
"// Use the legacy url API",
"var",
"parsed",
"=",
"lega... | Parses the given URL, using either the legacy Node.js url API, or the WHATWG URL API.
@param {string} url
@returns {object} | [
"Parses",
"the",
"given",
"URL",
"using",
"either",
"the",
"legacy",
"Node",
".",
"js",
"url",
"API",
"or",
"the",
"WHATWG",
"URL",
"API",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/HttpPlugin.js#L125-L138 |
35,242 | JamesMessinger/json-schema-lib | lib/plugins/HttpPlugin.js | decompressResponse | function decompressResponse (res) {
var encoding = lowercase(res.headers['content-encoding']);
var isCompressed = ['gzip', 'compress', 'deflate'].indexOf(encoding) >= 0;
if (isCompressed) {
// The response is compressed, so add decompression middleware to the stream
res.pipe(zlib.createUnzip());
// Remove the content-encoding header, to prevent double-decoding
delete res.headers['content-encoding'];
}
} | javascript | function decompressResponse (res) {
var encoding = lowercase(res.headers['content-encoding']);
var isCompressed = ['gzip', 'compress', 'deflate'].indexOf(encoding) >= 0;
if (isCompressed) {
// The response is compressed, so add decompression middleware to the stream
res.pipe(zlib.createUnzip());
// Remove the content-encoding header, to prevent double-decoding
delete res.headers['content-encoding'];
}
} | [
"function",
"decompressResponse",
"(",
"res",
")",
"{",
"var",
"encoding",
"=",
"lowercase",
"(",
"res",
".",
"headers",
"[",
"'content-encoding'",
"]",
")",
";",
"var",
"isCompressed",
"=",
"[",
"'gzip'",
",",
"'compress'",
",",
"'deflate'",
"]",
".",
"in... | Adds decompression middleware to the response stream if necessary.
@param {IncomingMessage} res | [
"Adds",
"decompression",
"middleware",
"to",
"the",
"response",
"stream",
"if",
"necessary",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/HttpPlugin.js#L145-L156 |
35,243 | strues/boldr | project/server/services/authentication/authService.js | fromHeaderOrQuerystring | function fromHeaderOrQuerystring(req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
return false;
} | javascript | function fromHeaderOrQuerystring(req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
return false;
} | [
"function",
"fromHeaderOrQuerystring",
"(",
"req",
")",
"{",
"if",
"(",
"req",
".",
"headers",
".",
"authorization",
"&&",
"req",
".",
"headers",
".",
"authorization",
".",
"split",
"(",
"' '",
")",
"[",
"0",
"]",
"===",
"'Bearer'",
")",
"{",
"return",
... | Extracts a JWT from a request header or query string
@param {Object} req the request object
@return {string} the token | [
"Extracts",
"a",
"JWT",
"from",
"a",
"request",
"header",
"or",
"query",
"string"
] | 21f1ed9a5ed754e01c50827249e89087b788e660 | https://github.com/strues/boldr/blob/21f1ed9a5ed754e01c50827249e89087b788e660/project/server/services/authentication/authService.js#L14-L21 |
35,244 | glayzzle/doc-parser | src/parser.js | function (a, b) {
if (a) {
if (Array.isArray(b)) {
for (var i = 0; i < b.length; i++) {
if (b[i]) {
a[i] = extend(a[i], b[i]);
}
}
return a;
} else if (typeof b === 'object') {
Object.getOwnPropertyNames(b).forEach(function (key) {
a[key] = extend(a[key], b[key]);
});
return a;
}
}
return b;
} | javascript | function (a, b) {
if (a) {
if (Array.isArray(b)) {
for (var i = 0; i < b.length; i++) {
if (b[i]) {
a[i] = extend(a[i], b[i]);
}
}
return a;
} else if (typeof b === 'object') {
Object.getOwnPropertyNames(b).forEach(function (key) {
a[key] = extend(a[key], b[key]);
});
return a;
}
}
return b;
} | [
"function",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"b",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"b",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
... | Deep recursive merge | [
"Deep",
"recursive",
"merge"
] | 4ed4d1d47a8da5b9baba7ec371b5e81b85efba25 | https://github.com/glayzzle/doc-parser/blob/4ed4d1d47a8da5b9baba7ec371b5e81b85efba25/src/parser.js#L9-L26 | |
35,245 | GianlucaGuarini/allora | index.js | allora | function allora (parent, prop) {
return new Proxy(prop ? parent[prop] : parent, {
get: (target, property) => {
// no function no need for promises in return
if (isOnCallback(property)) {
// detect properties like
// window.onload.then(() => console.log('loaded'))
return new Promise((resolve) => {
target[property] = resolve
})
} else if (typeof target[property] !== 'function') {
return target[property]
} else {
// make proxy also the nested object properties
return allora(target, property)
}
},
// this is cool to make promiseable event emitters
// and many other native node methods
apply: (target, thisArg, argumentsList) => {
let returnValue
const promise = new Promise((resolve, reject) => {
// guessing the timer functions from the type of arguments passed to the method
const isTimer = !argumentsList.length || typeof argumentsList[0] === 'number'
// assuming the callback will be always the second argument
argumentsList.splice(isTimer ? 0 : 1, 0, resolve)
returnValue = Reflect.apply(target, parent, argumentsList)
})
// Return the returnValue through valueOf
promise.valueOf = () => returnValue
promise.toString = () => returnValue
return promise
}
})
} | javascript | function allora (parent, prop) {
return new Proxy(prop ? parent[prop] : parent, {
get: (target, property) => {
// no function no need for promises in return
if (isOnCallback(property)) {
// detect properties like
// window.onload.then(() => console.log('loaded'))
return new Promise((resolve) => {
target[property] = resolve
})
} else if (typeof target[property] !== 'function') {
return target[property]
} else {
// make proxy also the nested object properties
return allora(target, property)
}
},
// this is cool to make promiseable event emitters
// and many other native node methods
apply: (target, thisArg, argumentsList) => {
let returnValue
const promise = new Promise((resolve, reject) => {
// guessing the timer functions from the type of arguments passed to the method
const isTimer = !argumentsList.length || typeof argumentsList[0] === 'number'
// assuming the callback will be always the second argument
argumentsList.splice(isTimer ? 0 : 1, 0, resolve)
returnValue = Reflect.apply(target, parent, argumentsList)
})
// Return the returnValue through valueOf
promise.valueOf = () => returnValue
promise.toString = () => returnValue
return promise
}
})
} | [
"function",
"allora",
"(",
"parent",
",",
"prop",
")",
"{",
"return",
"new",
"Proxy",
"(",
"prop",
"?",
"parent",
"[",
"prop",
"]",
":",
"parent",
",",
"{",
"get",
":",
"(",
"target",
",",
"property",
")",
"=>",
"{",
"// no function no need for promises ... | Function called recursively on all the object properties
If a property is a function we make it promisable
@param { Object } parent - context where the apply method will be triggered
@param { String } prop - property we are trying to get from the parent object
@returns { Proxy } | [
"Function",
"called",
"recursively",
"on",
"all",
"the",
"object",
"properties",
"If",
"a",
"property",
"is",
"a",
"function",
"we",
"make",
"it",
"promisable"
] | 99b396214477d4f444470290b25bc91381b657be | https://github.com/GianlucaGuarini/allora/blob/99b396214477d4f444470290b25bc91381b657be/index.js#L12-L46 |
35,246 | EarthlingInteractive/aframe-geo-projection-component | src/system.js | renderToContext | function renderToContext (geoJson, projection) {
var shapePath = new THREE.ShapePath();
var mapRenderContext = new ThreeJSRenderContext(shapePath);
var mapPath = geoPath(projection, mapRenderContext);
mapPath(geoJson);
return mapRenderContext;
} | javascript | function renderToContext (geoJson, projection) {
var shapePath = new THREE.ShapePath();
var mapRenderContext = new ThreeJSRenderContext(shapePath);
var mapPath = geoPath(projection, mapRenderContext);
mapPath(geoJson);
return mapRenderContext;
} | [
"function",
"renderToContext",
"(",
"geoJson",
",",
"projection",
")",
"{",
"var",
"shapePath",
"=",
"new",
"THREE",
".",
"ShapePath",
"(",
")",
";",
"var",
"mapRenderContext",
"=",
"new",
"ThreeJSRenderContext",
"(",
"shapePath",
")",
";",
"var",
"mapPath",
... | Takes the input geoJson and uses the projection and D3 to draw it
into a ThreeJSRenderContext.
@param geoJson the geoJson object to render
@param projection the projection to use for rendering
@return ThreeJSRenderContext | [
"Takes",
"the",
"input",
"geoJson",
"and",
"uses",
"the",
"projection",
"and",
"D3",
"to",
"draw",
"it",
"into",
"a",
"ThreeJSRenderContext",
"."
] | 687f023acfdab9810811c88a55d0aab00777de0c | https://github.com/EarthlingInteractive/aframe-geo-projection-component/blob/687f023acfdab9810811c88a55d0aab00777de0c/src/system.js#L15-L21 |
35,247 | glennjones/elsewhere-profiles | lib/pages.js | function(callback){
var self = this;
// if we have no pages just fire callback
if(self.pageCollection.length === 0){
callback(self);
}
// this is called once a page is fully parsed
whenPageIsFetched = function(){
self.completed ++;
if(self.completed === self.pageCollection.length){
callback(self);
} else {
findUnfetchedPages();
}
}
findUnfetchedPages = function(){
_.each(self.pageCollection, function (page) {
if (page.status === "unfetched") {
page.fetch(whenPageIsFetched);
}
});
},
findUnfetchedPages();
} | javascript | function(callback){
var self = this;
// if we have no pages just fire callback
if(self.pageCollection.length === 0){
callback(self);
}
// this is called once a page is fully parsed
whenPageIsFetched = function(){
self.completed ++;
if(self.completed === self.pageCollection.length){
callback(self);
} else {
findUnfetchedPages();
}
}
findUnfetchedPages = function(){
_.each(self.pageCollection, function (page) {
if (page.status === "unfetched") {
page.fetch(whenPageIsFetched);
}
});
},
findUnfetchedPages();
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// if we have no pages just fire callback",
"if",
"(",
"self",
".",
"pageCollection",
".",
"length",
"===",
"0",
")",
"{",
"callback",
"(",
"self",
")",
";",
"}",
"// this is called once ... | fetch all the pages | [
"fetch",
"all",
"the",
"pages"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/pages.js#L129-L156 | |
35,248 | glennjones/elsewhere-profiles | lib/pages.js | function (){
var out = {}
if(this.profiles.length !== 0){
out.profiles = this.profiles
}
if(this.noProfilesFound.length !== 0){
out.noProfilesFound = this.noProfilesFound;
}
if(utils.hasProperties(this.combinedProfile)){
out.combinedProfile = this.combinedProfile
}
return out;
} | javascript | function (){
var out = {}
if(this.profiles.length !== 0){
out.profiles = this.profiles
}
if(this.noProfilesFound.length !== 0){
out.noProfilesFound = this.noProfilesFound;
}
if(utils.hasProperties(this.combinedProfile)){
out.combinedProfile = this.combinedProfile
}
return out;
} | [
"function",
"(",
")",
"{",
"var",
"out",
"=",
"{",
"}",
"if",
"(",
"this",
".",
"profiles",
".",
"length",
"!==",
"0",
")",
"{",
"out",
".",
"profiles",
"=",
"this",
".",
"profiles",
"}",
"if",
"(",
"this",
".",
"noProfilesFound",
".",
"length",
... | converts the data structure into a compact version for output | [
"converts",
"the",
"data",
"structure",
"into",
"a",
"compact",
"version",
"for",
"output"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/pages.js#L160-L176 | |
35,249 | glennjones/elsewhere-profiles | lib/pages.js | commonUserName | function commonUserName(objs, logger){
logger.info('finding common username');
var i = objs.length,
x = 0
usernames = [],
highest = 0,
out ='';
while (x < i) {
appendName(objs[x].userName);
x++;
}
var i = usernames.length;
while (i--) {
if(usernames[i].count > highest){
highest = usernames[i].count;
out = usernames[i].name;
}
}
function appendName(userName){
var i = usernames.length;
while (i--) {
if(usernames[i].name === userName){
usernames[i].count ++;
return;
}
}
usernames.push({
'name': userName,
'count': 1
})
}
return out;
} | javascript | function commonUserName(objs, logger){
logger.info('finding common username');
var i = objs.length,
x = 0
usernames = [],
highest = 0,
out ='';
while (x < i) {
appendName(objs[x].userName);
x++;
}
var i = usernames.length;
while (i--) {
if(usernames[i].count > highest){
highest = usernames[i].count;
out = usernames[i].name;
}
}
function appendName(userName){
var i = usernames.length;
while (i--) {
if(usernames[i].name === userName){
usernames[i].count ++;
return;
}
}
usernames.push({
'name': userName,
'count': 1
})
}
return out;
} | [
"function",
"commonUserName",
"(",
"objs",
",",
"logger",
")",
"{",
"logger",
".",
"info",
"(",
"'finding common username'",
")",
";",
"var",
"i",
"=",
"objs",
".",
"length",
",",
"x",
"=",
"0",
"usernames",
"=",
"[",
"]",
",",
"highest",
"=",
"0",
"... | find the most common username by freguency of use | [
"find",
"the",
"most",
"common",
"username",
"by",
"freguency",
"of",
"use"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/pages.js#L232-L268 |
35,250 | glennjones/elsewhere-profiles | lib/pages.js | appendUrl | function appendUrl(url, urls) {
var i = urls.length
found = false;
while (i--) {
if (utils.compareUrl(urls[i], url))
found = true;
}
if (found === false && utils.isUrl(url))
urls.push(url);
} | javascript | function appendUrl(url, urls) {
var i = urls.length
found = false;
while (i--) {
if (utils.compareUrl(urls[i], url))
found = true;
}
if (found === false && utils.isUrl(url))
urls.push(url);
} | [
"function",
"appendUrl",
"(",
"url",
",",
"urls",
")",
"{",
"var",
"i",
"=",
"urls",
".",
"length",
"found",
"=",
"false",
";",
"while",
"(",
"i",
"--",
")",
"{",
"if",
"(",
"utils",
".",
"compareUrl",
"(",
"urls",
"[",
"i",
"]",
",",
"url",
")... | append a url if it is not already in the urls array | [
"append",
"a",
"url",
"if",
"it",
"is",
"not",
"already",
"in",
"the",
"urls",
"array"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/pages.js#L434-L443 |
35,251 | glennjones/elsewhere-profiles | lib/pages.js | rateAddress | function rateAddress(addr){
var rating = 0;
if(addr != undefined){
if (addr['extended-address']) rating++;
if (addr['street-address']) rating++;
if (addr.locality) rating++;
if (addr.region) rating++;
if (addr['postal-code']) rating++;
if (addr['country-name']) rating++;
}
return rating;
} | javascript | function rateAddress(addr){
var rating = 0;
if(addr != undefined){
if (addr['extended-address']) rating++;
if (addr['street-address']) rating++;
if (addr.locality) rating++;
if (addr.region) rating++;
if (addr['postal-code']) rating++;
if (addr['country-name']) rating++;
}
return rating;
} | [
"function",
"rateAddress",
"(",
"addr",
")",
"{",
"var",
"rating",
"=",
"0",
";",
"if",
"(",
"addr",
"!=",
"undefined",
")",
"{",
"if",
"(",
"addr",
"[",
"'extended-address'",
"]",
")",
"rating",
"++",
";",
"if",
"(",
"addr",
"[",
"'street-address'",
... | rates the fullness of a given address | [
"rates",
"the",
"fullness",
"of",
"a",
"given",
"address"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/pages.js#L463-L474 |
35,252 | matteodelabre/midijs | lib/gm.js | checkFamily | function checkFamily(program, family) {
var familyIndex = gm.families.indexOf(family.toLowerCase());
if (familyIndex === -1 || program < (familyIndex * 8) ||
program >= ((familyIndex + 1) * 8)) {
return false;
}
return true;
} | javascript | function checkFamily(program, family) {
var familyIndex = gm.families.indexOf(family.toLowerCase());
if (familyIndex === -1 || program < (familyIndex * 8) ||
program >= ((familyIndex + 1) * 8)) {
return false;
}
return true;
} | [
"function",
"checkFamily",
"(",
"program",
",",
"family",
")",
"{",
"var",
"familyIndex",
"=",
"gm",
".",
"families",
".",
"indexOf",
"(",
"family",
".",
"toLowerCase",
"(",
")",
")",
";",
"if",
"(",
"familyIndex",
"===",
"-",
"1",
"||",
"program",
"<"... | Check if a program is in a family of instruments
@private
@param {number} program Program to test
@param {string} family Family name
@return {boolean} Whether the program belongs to the family | [
"Check",
"if",
"a",
"program",
"is",
"in",
"a",
"family",
"of",
"instruments"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/gm.js#L13-L22 |
35,253 | matteodelabre/midijs | lib/error.js | format | function format(arg) {
if (typeof arg === 'number') {
return '0x' + arg.toString(16).toUpperCase();
}
if (typeof arg === 'string') {
return '"' + arg + '"';
}
return arg.toString();
} | javascript | function format(arg) {
if (typeof arg === 'number') {
return '0x' + arg.toString(16).toUpperCase();
}
if (typeof arg === 'string') {
return '"' + arg + '"';
}
return arg.toString();
} | [
"function",
"format",
"(",
"arg",
")",
"{",
"if",
"(",
"typeof",
"arg",
"===",
"'number'",
")",
"{",
"return",
"'0x'",
"+",
"arg",
".",
"toString",
"(",
"16",
")",
".",
"toUpperCase",
"(",
")",
";",
"}",
"if",
"(",
"typeof",
"arg",
"===",
"'string'... | Format an argument to be displayed in the error message
@private
@param {*} arg Argument to format
@return {string} Formatted argument | [
"Format",
"an",
"argument",
"to",
"be",
"displayed",
"in",
"the",
"error",
"message"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L12-L22 |
35,254 | matteodelabre/midijs | lib/error.js | MIDIParserError | function MIDIParserError(actual, expected, byte) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.actual = actual;
this.expected = expected;
actual = format(actual);
expected = format(expected);
this.message = 'Invalid MIDI file: expected ' +
expected + ' but found ' + actual;
if (byte !== undefined) {
this.byte = byte;
this.message += ' (at byte ' + byte + ')';
}
} | javascript | function MIDIParserError(actual, expected, byte) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.actual = actual;
this.expected = expected;
actual = format(actual);
expected = format(expected);
this.message = 'Invalid MIDI file: expected ' +
expected + ' but found ' + actual;
if (byte !== undefined) {
this.byte = byte;
this.message += ' (at byte ' + byte + ')';
}
} | [
"function",
"MIDIParserError",
"(",
"actual",
",",
"expected",
",",
"byte",
")",
"{",
"Error",
".",
"call",
"(",
"this",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
";",
"this",
".",
"name",
"=",
"thi... | Consruct a new MIDIParserError
@class MIDIParserError
@extends Error
@classdesc An error that occured while parsing a MIDI file
@param {*} actual Actual value
@param {*} expected Expected value
@param {number} [byte] The byte at which the error occured | [
"Consruct",
"a",
"new",
"MIDIParserError"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L35-L53 |
35,255 | matteodelabre/midijs | lib/error.js | MIDIEncoderError | function MIDIEncoderError(actual, expected) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.actual = actual;
this.expected = expected;
actual = format(actual);
expected = format(expected);
this.message = 'MIDI encoding error: expected ' +
expected + ' but found ' + actual;
} | javascript | function MIDIEncoderError(actual, expected) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.actual = actual;
this.expected = expected;
actual = format(actual);
expected = format(expected);
this.message = 'MIDI encoding error: expected ' +
expected + ' but found ' + actual;
} | [
"function",
"MIDIEncoderError",
"(",
"actual",
",",
"expected",
")",
"{",
"Error",
".",
"call",
"(",
"this",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
";",
"this",
".",
"name",
"=",
"this",
".",
"co... | Construct a new MIDIEncoderError
@class MIDIEncoderError
@extends Error
@classdesc An error that occured while encoding a MIDI file
@param {*} actual Actual value
@param {*} expected Expected value | [
"Construct",
"a",
"new",
"MIDIEncoderError"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L68-L81 |
35,256 | matteodelabre/midijs | lib/error.js | MIDIInvalidEventError | function MIDIInvalidEventError(message) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
} | javascript | function MIDIInvalidEventError(message) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
} | [
"function",
"MIDIInvalidEventError",
"(",
"message",
")",
"{",
"Error",
".",
"call",
"(",
"this",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
";",
"this",
".",
"name",
"=",
"this",
".",
"constructor",
"... | Construct a new MIDIInvalidEventError
@class MIDIInvalidEventError
@extends Error
@classdesc An error that occured if an event was malformed
@param {string} message Error message | [
"Construct",
"a",
"new",
"MIDIInvalidEventError"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L95-L101 |
35,257 | matteodelabre/midijs | lib/error.js | MIDIInvalidArgument | function MIDIInvalidArgument(message) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
} | javascript | function MIDIInvalidArgument(message) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
} | [
"function",
"MIDIInvalidArgument",
"(",
"message",
")",
"{",
"Error",
".",
"call",
"(",
"this",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
";",
"this",
".",
"name",
"=",
"this",
".",
"constructor",
"."... | Construct a new MIDIInvalidArgument
@class MIDIInvalidArgument
@extends Error
@classdesc Generic invalid argument error
@param {string} message Error message | [
"Construct",
"a",
"new",
"MIDIInvalidArgument"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L115-L121 |
35,258 | matteodelabre/midijs | lib/error.js | MIDINotMIDIError | function MIDINotMIDIError() {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = 'Not a valid MIDI file';
} | javascript | function MIDINotMIDIError() {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = 'Not a valid MIDI file';
} | [
"function",
"MIDINotMIDIError",
"(",
")",
"{",
"Error",
".",
"call",
"(",
"this",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
";",
"this",
".",
"name",
"=",
"this",
".",
"constructor",
".",
"name",
";... | Construct a new MIDINotMIDIError
@class MIDINotMIDIError
@extends Error
@classdesc An error that indicates that the file is not a MIDI file | [
"Construct",
"a",
"new",
"MIDINotMIDIError"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L133-L139 |
35,259 | matteodelabre/midijs | lib/error.js | MIDINotSupportedError | function MIDINotSupportedError(message) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
} | javascript | function MIDINotSupportedError(message) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
} | [
"function",
"MIDINotSupportedError",
"(",
"message",
")",
"{",
"Error",
".",
"call",
"(",
"this",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
";",
"this",
".",
"name",
"=",
"this",
".",
"constructor",
"... | Construct a new MIDINotSupportedError
@class MIDINotSupportedError
@extends Error
@classdesc An error that indicates that you tried to use
a MIDI feature that is not supported by this library
@param {string} message Error message | [
"Construct",
"a",
"new",
"MIDINotSupportedError"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/error.js#L154-L160 |
35,260 | LivePersonInc/chronosjs | src/courier/PostMessageChannel.js | postMessage | function postMessage(message, target, force) {
var consumer;
var parsed;
if (!this.disposed) {
try {
if (message) {
if (this.ready || force) {
// Post the message
consumer = target || this.receiver;
parsed = _prepareMessage.call(this, message);
consumer.postMessage(parsed);
return true;
}
else if (this.maxConcurrency >= this.messageQueue.length) {
// Need to delay/queue messages till target is ready
this.messageQueue.push(message);
return true;
}
else {
return false;
}
}
}
catch(ex) {
/* istanbul ignore next */
PostMessageUtilities.log("Error while trying to post the message", "ERROR", "PostMessageChannel");
return false;
}
}
} | javascript | function postMessage(message, target, force) {
var consumer;
var parsed;
if (!this.disposed) {
try {
if (message) {
if (this.ready || force) {
// Post the message
consumer = target || this.receiver;
parsed = _prepareMessage.call(this, message);
consumer.postMessage(parsed);
return true;
}
else if (this.maxConcurrency >= this.messageQueue.length) {
// Need to delay/queue messages till target is ready
this.messageQueue.push(message);
return true;
}
else {
return false;
}
}
}
catch(ex) {
/* istanbul ignore next */
PostMessageUtilities.log("Error while trying to post the message", "ERROR", "PostMessageChannel");
return false;
}
}
} | [
"function",
"postMessage",
"(",
"message",
",",
"target",
",",
"force",
")",
"{",
"var",
"consumer",
";",
"var",
"parsed",
";",
"if",
"(",
"!",
"this",
".",
"disposed",
")",
"{",
"try",
"{",
"if",
"(",
"message",
")",
"{",
"if",
"(",
"this",
".",
... | Method to post the message to the target
@param {Object} message - the message to post
@param {Object} [target] - optional target for post
@param {Boolean} [force = false] - force post even if not ready | [
"Method",
"to",
"post",
"the",
"message",
"to",
"the",
"target"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L214-L244 |
35,261 | LivePersonInc/chronosjs | src/courier/PostMessageChannel.js | _hookupMessageChannel | function _hookupMessageChannel(onmessage) {
return function() {
this.channel = new MessageChannel();
this.receiver = this.channel.port1;
this.dispatcher = this.channel.port2;
this.receiver.onmessage = onmessage;
this.neutered = false;
}.bind(this);
} | javascript | function _hookupMessageChannel(onmessage) {
return function() {
this.channel = new MessageChannel();
this.receiver = this.channel.port1;
this.dispatcher = this.channel.port2;
this.receiver.onmessage = onmessage;
this.neutered = false;
}.bind(this);
} | [
"function",
"_hookupMessageChannel",
"(",
"onmessage",
")",
"{",
"return",
"function",
"(",
")",
"{",
"this",
".",
"channel",
"=",
"new",
"MessageChannel",
"(",
")",
";",
"this",
".",
"receiver",
"=",
"this",
".",
"channel",
".",
"port1",
";",
"this",
".... | Method to create and hookup message channel factory for further use
@param {Function} onmessage - the message handler to be used with the channel
@private | [
"Method",
"to",
"create",
"and",
"hookup",
"message",
"channel",
"factory",
"for",
"further",
"use"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L408-L416 |
35,262 | LivePersonInc/chronosjs | src/courier/PostMessageChannel.js | _isHandshake | function _isHandshake(event) {
return (event && event.data && "string" === typeof event.data && (0 === event.data.indexOf(TOKEN_PREFIX) || (HANSHAKE_PREFIX + this.token) === event.data));
} | javascript | function _isHandshake(event) {
return (event && event.data && "string" === typeof event.data && (0 === event.data.indexOf(TOKEN_PREFIX) || (HANSHAKE_PREFIX + this.token) === event.data));
} | [
"function",
"_isHandshake",
"(",
"event",
")",
"{",
"return",
"(",
"event",
"&&",
"event",
".",
"data",
"&&",
"\"string\"",
"===",
"typeof",
"event",
".",
"data",
"&&",
"(",
"0",
"===",
"event",
".",
"data",
".",
"indexOf",
"(",
"TOKEN_PREFIX",
")",
"|... | Method to validate whether an event is for handshake
@param {Object} event - the event object on message
@private | [
"Method",
"to",
"validate",
"whether",
"an",
"event",
"is",
"for",
"handshake"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L443-L445 |
35,263 | LivePersonInc/chronosjs | src/courier/PostMessageChannel.js | _wrapReadyCallback | function _wrapReadyCallback(onready, target) {
return function(err) {
if (target && "function" === typeof target.callback) {
target.callback.call(target.context, err, this.target);
}
if (onready) {
if ("function" === typeof onready) {
onready(err, this.target);
}
else if ("function" === typeof onready.callback) {
onready.callback.call(onready.context, err, this.target);
}
}
};
} | javascript | function _wrapReadyCallback(onready, target) {
return function(err) {
if (target && "function" === typeof target.callback) {
target.callback.call(target.context, err, this.target);
}
if (onready) {
if ("function" === typeof onready) {
onready(err, this.target);
}
else if ("function" === typeof onready.callback) {
onready.callback.call(onready.context, err, this.target);
}
}
};
} | [
"function",
"_wrapReadyCallback",
"(",
"onready",
",",
"target",
")",
"{",
"return",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"target",
"&&",
"\"function\"",
"===",
"typeof",
"target",
".",
"callback",
")",
"{",
"target",
".",
"callback",
".",
"call",
... | Method for wrapping the callback of iframe ready
@param {Function} [onready] - the handler for iframe ready
@param {Object} [target] - the target iframe configuration
@returns {Function} handler function for messages
@private | [
"Method",
"for",
"wrapping",
"the",
"callback",
"of",
"iframe",
"ready"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L454-L468 |
35,264 | LivePersonInc/chronosjs | src/courier/PostMessageChannel.js | _waitForBody | function _waitForBody(options) {
options = options || {};
var onready = options.onready;
var doc = options.doc || root.document;
var delay = options.delay;
function _ready() {
if (doc.body) {
onready();
}
else {
PostMessageUtilities.delay(_ready, delay || DEFAULT_BODY_LOAD_DELAY);
}
}
PostMessageUtilities.delay(_ready, delay || false);
} | javascript | function _waitForBody(options) {
options = options || {};
var onready = options.onready;
var doc = options.doc || root.document;
var delay = options.delay;
function _ready() {
if (doc.body) {
onready();
}
else {
PostMessageUtilities.delay(_ready, delay || DEFAULT_BODY_LOAD_DELAY);
}
}
PostMessageUtilities.delay(_ready, delay || false);
} | [
"function",
"_waitForBody",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"onready",
"=",
"options",
".",
"onready",
";",
"var",
"doc",
"=",
"options",
".",
"doc",
"||",
"root",
".",
"document",
";",
"var",
"delay",
... | Method to enable running a callback once the document body is ready
@param {Object} [options] Configuration options
@param {Function} options.onready - the callback to run when ready
@param {Object} [options.doc = root.document] - document to refer to
@param {Number} [options.delay = 0] - milliseconds to delay the execution
@private | [
"Method",
"to",
"enable",
"running",
"a",
"callback",
"once",
"the",
"document",
"body",
"is",
"ready"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L611-L627 |
35,265 | LivePersonInc/chronosjs | src/courier/PostMessageChannel.js | _createIFrame | function _createIFrame(options, container) {
var frame = document.createElement("IFRAME");
var name = PostMessageUtilities.createUniqueSequence(IFRAME_PREFIX + PostMessageUtilities.SEQUENCE_FORMAT);
var delay = options.delayLoad;
var defaultAttributes = {
"id": name,
"name" :name,
"tabindex": "-1", // To prevent it getting focus when tabbing through the page
"aria-hidden": "true", // To prevent it being picked up by screen-readers
"title": "", // Adding an empty title for accessibility
"role": "presentation", // Adding a presentation role http://yahoodevelopers.tumblr.com/post/59489724815/easy-fixes-to-common-accessibility-problems
"allowTransparency":"true"
};
var defaultStyle = {
width :"0px",
height : "0px",
position :"absolute",
top : "-1000px",
left : "-1000px"
};
options.attributes = options.attributes || defaultAttributes;
for (var key in options.attributes){
if (options.attributes.hasOwnProperty(key)) {
frame.setAttribute(key, options.attributes[key]);
}
}
options.style = options.style || defaultStyle;
if (options.style) {
for (var attr in options.style) {
if (options.style.hasOwnProperty(attr)) {
frame.style[attr] = options.style[attr];
}
}
}
// Append and hookup after body tag opens
_waitForBody({
delay: delay,
onready: function() {
(container || document.body).appendChild(frame);
this.rmload = _addLoadHandler.call(this, frame);
_setIFrameLocation.call(this, frame, options.url, (false !== options.bust));
}.bind(this)
});
return frame;
} | javascript | function _createIFrame(options, container) {
var frame = document.createElement("IFRAME");
var name = PostMessageUtilities.createUniqueSequence(IFRAME_PREFIX + PostMessageUtilities.SEQUENCE_FORMAT);
var delay = options.delayLoad;
var defaultAttributes = {
"id": name,
"name" :name,
"tabindex": "-1", // To prevent it getting focus when tabbing through the page
"aria-hidden": "true", // To prevent it being picked up by screen-readers
"title": "", // Adding an empty title for accessibility
"role": "presentation", // Adding a presentation role http://yahoodevelopers.tumblr.com/post/59489724815/easy-fixes-to-common-accessibility-problems
"allowTransparency":"true"
};
var defaultStyle = {
width :"0px",
height : "0px",
position :"absolute",
top : "-1000px",
left : "-1000px"
};
options.attributes = options.attributes || defaultAttributes;
for (var key in options.attributes){
if (options.attributes.hasOwnProperty(key)) {
frame.setAttribute(key, options.attributes[key]);
}
}
options.style = options.style || defaultStyle;
if (options.style) {
for (var attr in options.style) {
if (options.style.hasOwnProperty(attr)) {
frame.style[attr] = options.style[attr];
}
}
}
// Append and hookup after body tag opens
_waitForBody({
delay: delay,
onready: function() {
(container || document.body).appendChild(frame);
this.rmload = _addLoadHandler.call(this, frame);
_setIFrameLocation.call(this, frame, options.url, (false !== options.bust));
}.bind(this)
});
return frame;
} | [
"function",
"_createIFrame",
"(",
"options",
",",
"container",
")",
"{",
"var",
"frame",
"=",
"document",
".",
"createElement",
"(",
"\"IFRAME\"",
")",
";",
"var",
"name",
"=",
"PostMessageUtilities",
".",
"createUniqueSequence",
"(",
"IFRAME_PREFIX",
"+",
"Post... | Creates an iFrame in memory and sets the default attributes except the actual URL
Does not attach to DOM at this point
@param {Object} options a passed in configuration options
@param {String} options.url - the url to load,
@param {String} [options.style] - the CSS style to apply
@param {String} [options.style.width] width of iframe
@param {String} [options.style.height] height of iframe
.....
@param {Boolean} [options.bust = true] - optional flag to indicate usage of cache buster when loading the iframe (default to true),
@param {Function} [options.callback] - a callback to invoke after the iframe had been loaded,
@param {Object} [options.context] - optional context for the callback
@param {Object} [container] - the container in which the iframe should be created (if not supplied, document.body will be used)
@returns {Element} the attached iFrame element
@private | [
"Creates",
"an",
"iFrame",
"in",
"memory",
"and",
"sets",
"the",
"default",
"attributes",
"except",
"the",
"actual",
"URL",
"Does",
"not",
"attach",
"to",
"DOM",
"at",
"this",
"point"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L645-L693 |
35,266 | LivePersonInc/chronosjs | src/courier/PostMessageChannel.js | _addLoadHandler | function _addLoadHandler(frame) {
var load = function() {
this.loading = false;
if (this.handshakeAttempts === this.handshakeAttemptsOrig) {
// Probably a first try for handshake or a reload of the iframe,
// Either way, we'll need to perform handshake, so ready flag should be set to false (if not already)
this.ready = false;
}
_handshake.call(this, this.handshakeInterval);
}.bind(this);
PostMessageUtilities.addEventListener(frame, "load", load);
return function() {
_removeLoadHandler(frame, load);
};
} | javascript | function _addLoadHandler(frame) {
var load = function() {
this.loading = false;
if (this.handshakeAttempts === this.handshakeAttemptsOrig) {
// Probably a first try for handshake or a reload of the iframe,
// Either way, we'll need to perform handshake, so ready flag should be set to false (if not already)
this.ready = false;
}
_handshake.call(this, this.handshakeInterval);
}.bind(this);
PostMessageUtilities.addEventListener(frame, "load", load);
return function() {
_removeLoadHandler(frame, load);
};
} | [
"function",
"_addLoadHandler",
"(",
"frame",
")",
"{",
"var",
"load",
"=",
"function",
"(",
")",
"{",
"this",
".",
"loading",
"=",
"false",
";",
"if",
"(",
"this",
".",
"handshakeAttempts",
"===",
"this",
".",
"handshakeAttemptsOrig",
")",
"{",
"// Probabl... | Add load handler for the iframe to make sure it is loaded
@param {Object} frame - the actual DOM iframe
@returns {Function} the remove handler function
@private | [
"Add",
"load",
"handler",
"for",
"the",
"iframe",
"to",
"make",
"sure",
"it",
"is",
"loaded"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L701-L719 |
35,267 | LivePersonInc/chronosjs | src/courier/PostMessageChannel.js | _setIFrameLocation | function _setIFrameLocation(frame, src, bust){
src += (0 < src.indexOf("?") ? "&" : "?");
if (bust) {
src += "bust=";
src += (new Date()).getTime() + "&";
}
src += ((this.hostParam ? "hostParam=" + this.hostParam + "&" + this.hostParam + "=" : "lpHost=") + encodeURIComponent(PostMessageUtilities.getHost(void 0, frame, true)));
if (!_isNativeMessageChannelSupported.call(this)) {
src += "&lpPMCPolyfill=true";
}
if (false === this.useObjects) {
src += "&lpPMDeSerialize=true";
}
frame.setAttribute("src", src);
} | javascript | function _setIFrameLocation(frame, src, bust){
src += (0 < src.indexOf("?") ? "&" : "?");
if (bust) {
src += "bust=";
src += (new Date()).getTime() + "&";
}
src += ((this.hostParam ? "hostParam=" + this.hostParam + "&" + this.hostParam + "=" : "lpHost=") + encodeURIComponent(PostMessageUtilities.getHost(void 0, frame, true)));
if (!_isNativeMessageChannelSupported.call(this)) {
src += "&lpPMCPolyfill=true";
}
if (false === this.useObjects) {
src += "&lpPMDeSerialize=true";
}
frame.setAttribute("src", src);
} | [
"function",
"_setIFrameLocation",
"(",
"frame",
",",
"src",
",",
"bust",
")",
"{",
"src",
"+=",
"(",
"0",
"<",
"src",
".",
"indexOf",
"(",
"\"?\"",
")",
"?",
"\"&\"",
":",
"\"?\"",
")",
";",
"if",
"(",
"bust",
")",
"{",
"src",
"+=",
"\"bust=\"",
... | Sets the iFrame location using a cache bust mechanism,
making sure the iFrame is actually loaded and not from cache
@param {Object} frame - the iframe DOM object
@param {String} src - the source url for the iframe
@param {Boolean} bust - flag to indicate usage of cache buster when loading the iframe
@private | [
"Sets",
"the",
"iFrame",
"location",
"using",
"a",
"cache",
"bust",
"mechanism",
"making",
"sure",
"the",
"iFrame",
"is",
"actually",
"loaded",
"and",
"not",
"from",
"cache"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageChannel.js#L739-L758 |
35,268 | matteodelabre/midijs | lib/connect/input.js | Input | function Input(native) {
EventEmitter.call(this);
this.native = native;
this.id = native.id;
this.manufacturer = native.manufacturer;
this.name = native.name;
this.version = native.version;
native.onmidimessage = function (event) {
var data, type, object;
data = new BufferCursor(new buffer.Buffer(event.data));
type = data.readUInt8();
object = parseChannelEvent(
event.receivedTime,
type >> 4,
type & 0xF,
data
);
this.emit('event', object);
}.bind(this);
} | javascript | function Input(native) {
EventEmitter.call(this);
this.native = native;
this.id = native.id;
this.manufacturer = native.manufacturer;
this.name = native.name;
this.version = native.version;
native.onmidimessage = function (event) {
var data, type, object;
data = new BufferCursor(new buffer.Buffer(event.data));
type = data.readUInt8();
object = parseChannelEvent(
event.receivedTime,
type >> 4,
type & 0xF,
data
);
this.emit('event', object);
}.bind(this);
} | [
"function",
"Input",
"(",
"native",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"native",
"=",
"native",
";",
"this",
".",
"id",
"=",
"native",
".",
"id",
";",
"this",
".",
"manufacturer",
"=",
"native",
".",
"manufactu... | Construct a new Input
@class Input
@classdesc An input device from which we can receive MIDI events
@param {MIDIInput} native Native MIDI input | [
"Construct",
"a",
"new",
"Input"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/connect/input.js#L18-L42 |
35,269 | glennjones/elsewhere-profiles | plugins/lanyrd.js | fetch | function fetch(identity, options, callback){
var completed = 0
combinedProfile = {};
// this is called once a page is fully parsed
function whenFetched(err, data){
completed ++;
// combines the api and microformats data into one profile
if(data){
if(data.fn) {combinedProfile.fn = data.fn};
if(data.n) {combinedProfile.n = data.n};
if(data.nickname) {combinedProfile.nickname = data.nickname};
if(data.photo) {combinedProfile.photo = data.photo};
if(data.note) {combinedProfile.note = data.note};
// for the moment exclude microformat url structures
if(data.url && data.source === 'api') {
if(!combinedProfile.url) {combinedProfile.url = []};
var i = data.url.length;
while (i--) {
appendUrls(data.url[i], combinedProfile.url);
}
};
}
// once we have both bit of data fire callback
if(completed === 2){
callback(combinedProfile);
}
}
// get microformats data
getUFData(identity.userName, identity, options, function(err,data){
whenFetched(err, data);
});
// get api data
getAPIData(identity.userName, options, function(err,data){
whenFetched(err, data);
});
} | javascript | function fetch(identity, options, callback){
var completed = 0
combinedProfile = {};
// this is called once a page is fully parsed
function whenFetched(err, data){
completed ++;
// combines the api and microformats data into one profile
if(data){
if(data.fn) {combinedProfile.fn = data.fn};
if(data.n) {combinedProfile.n = data.n};
if(data.nickname) {combinedProfile.nickname = data.nickname};
if(data.photo) {combinedProfile.photo = data.photo};
if(data.note) {combinedProfile.note = data.note};
// for the moment exclude microformat url structures
if(data.url && data.source === 'api') {
if(!combinedProfile.url) {combinedProfile.url = []};
var i = data.url.length;
while (i--) {
appendUrls(data.url[i], combinedProfile.url);
}
};
}
// once we have both bit of data fire callback
if(completed === 2){
callback(combinedProfile);
}
}
// get microformats data
getUFData(identity.userName, identity, options, function(err,data){
whenFetched(err, data);
});
// get api data
getAPIData(identity.userName, options, function(err,data){
whenFetched(err, data);
});
} | [
"function",
"fetch",
"(",
"identity",
",",
"options",
",",
"callback",
")",
"{",
"var",
"completed",
"=",
"0",
"combinedProfile",
"=",
"{",
"}",
";",
"// this is called once a page is fully parsed",
"function",
"whenFetched",
"(",
"err",
",",
"data",
")",
"{",
... | fetch both api and microformats data and then mix together | [
"fetch",
"both",
"api",
"and",
"microformats",
"data",
"and",
"then",
"mix",
"together"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/plugins/lanyrd.js#L41-L81 |
35,270 | glennjones/elsewhere-profiles | plugins/lanyrd.js | whenFetched | function whenFetched(err, data){
completed ++;
// combines the api and microformats data into one profile
if(data){
if(data.fn) {combinedProfile.fn = data.fn};
if(data.n) {combinedProfile.n = data.n};
if(data.nickname) {combinedProfile.nickname = data.nickname};
if(data.photo) {combinedProfile.photo = data.photo};
if(data.note) {combinedProfile.note = data.note};
// for the moment exclude microformat url structures
if(data.url && data.source === 'api') {
if(!combinedProfile.url) {combinedProfile.url = []};
var i = data.url.length;
while (i--) {
appendUrls(data.url[i], combinedProfile.url);
}
};
}
// once we have both bit of data fire callback
if(completed === 2){
callback(combinedProfile);
}
} | javascript | function whenFetched(err, data){
completed ++;
// combines the api and microformats data into one profile
if(data){
if(data.fn) {combinedProfile.fn = data.fn};
if(data.n) {combinedProfile.n = data.n};
if(data.nickname) {combinedProfile.nickname = data.nickname};
if(data.photo) {combinedProfile.photo = data.photo};
if(data.note) {combinedProfile.note = data.note};
// for the moment exclude microformat url structures
if(data.url && data.source === 'api') {
if(!combinedProfile.url) {combinedProfile.url = []};
var i = data.url.length;
while (i--) {
appendUrls(data.url[i], combinedProfile.url);
}
};
}
// once we have both bit of data fire callback
if(completed === 2){
callback(combinedProfile);
}
} | [
"function",
"whenFetched",
"(",
"err",
",",
"data",
")",
"{",
"completed",
"++",
";",
"// combines the api and microformats data into one profile",
"if",
"(",
"data",
")",
"{",
"if",
"(",
"data",
".",
"fn",
")",
"{",
"combinedProfile",
".",
"fn",
"=",
"data",
... | this is called once a page is fully parsed | [
"this",
"is",
"called",
"once",
"a",
"page",
"is",
"fully",
"parsed"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/plugins/lanyrd.js#L46-L70 |
35,271 | glennjones/elsewhere-profiles | plugins/lanyrd.js | appendUrls | function appendUrls(url, arr){
var i = arr.length,
found = false;
while (i--) {
if(arr[i] === url){
found = true;
break;
}
}
if(!found) arr.push(url);
} | javascript | function appendUrls(url, arr){
var i = arr.length,
found = false;
while (i--) {
if(arr[i] === url){
found = true;
break;
}
}
if(!found) arr.push(url);
} | [
"function",
"appendUrls",
"(",
"url",
",",
"arr",
")",
"{",
"var",
"i",
"=",
"arr",
".",
"length",
",",
"found",
"=",
"false",
";",
"while",
"(",
"i",
"--",
")",
"{",
"if",
"(",
"arr",
"[",
"i",
"]",
"===",
"url",
")",
"{",
"found",
"=",
"tru... | appends url if its not already in the array | [
"appends",
"url",
"if",
"its",
"not",
"already",
"in",
"the",
"array"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/plugins/lanyrd.js#L86-L96 |
35,272 | glennjones/elsewhere-profiles | plugins/lanyrd.js | getUFData | function getUFData(userName, identity, options, callback) {
var url = 'http://lanyrd.com/people/' + userName,
cache = options.cache,
page = new Page(url, identity, null, options);
page.fetchUrl(function(){
if(page.profile.hCards.length > 0){
page.profile.hCards[0].source = 'microformat';
callback(null, page.profile.hCards[0]);
}else{
callback(null, {});
}
})
} | javascript | function getUFData(userName, identity, options, callback) {
var url = 'http://lanyrd.com/people/' + userName,
cache = options.cache,
page = new Page(url, identity, null, options);
page.fetchUrl(function(){
if(page.profile.hCards.length > 0){
page.profile.hCards[0].source = 'microformat';
callback(null, page.profile.hCards[0]);
}else{
callback(null, {});
}
})
} | [
"function",
"getUFData",
"(",
"userName",
",",
"identity",
",",
"options",
",",
"callback",
")",
"{",
"var",
"url",
"=",
"'http://lanyrd.com/people/'",
"+",
"userName",
",",
"cache",
"=",
"options",
".",
"cache",
",",
"page",
"=",
"new",
"Page",
"(",
"url"... | collect microfomats data from the lanyrd site | [
"collect",
"microfomats",
"data",
"from",
"the",
"lanyrd",
"site"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/plugins/lanyrd.js#L101-L114 |
35,273 | glennjones/elsewhere-profiles | plugins/lanyrd.js | getAPIData | function getAPIData(userName, options, callback){
if(process.env.LANYRD_API_URL)
{
var url = process.env.LANYRD_API_URL + 'people/' + userName,
cache = options.cache,
startedRequest = new Date(),
requestObj = {
uri: url,
headers: options.httpHeaders
};
// if url is in the cache use that
if(cache && cache.has(url)){
options.logger.info('using cache for lanyrd API data');
callback(null, parse(cache.get(url)));
}else{
// if not get the json from the api url
request(requestObj, function(requestErrors, response, body){
options.logger.info('getting lanyrd API data from url');
if(!requestErrors && response.statusCode === 200){
var data = JSON.parse(body)
var out = parse(data);
// add to cache store
if(cache){
cache.set(url, data);
}
var endedRequest = new Date();
var requestTime = endedRequest.getTime() - startedRequest.getTime();
options.logger.log('made API call to: ' + requestTime + 'ms - ' + url);
callback(null, out);
}else{
callback('error requesting Lanyrd API', {});
}
});
}
}else{
callback('LANYRD_API_URL not found', {});
}
} | javascript | function getAPIData(userName, options, callback){
if(process.env.LANYRD_API_URL)
{
var url = process.env.LANYRD_API_URL + 'people/' + userName,
cache = options.cache,
startedRequest = new Date(),
requestObj = {
uri: url,
headers: options.httpHeaders
};
// if url is in the cache use that
if(cache && cache.has(url)){
options.logger.info('using cache for lanyrd API data');
callback(null, parse(cache.get(url)));
}else{
// if not get the json from the api url
request(requestObj, function(requestErrors, response, body){
options.logger.info('getting lanyrd API data from url');
if(!requestErrors && response.statusCode === 200){
var data = JSON.parse(body)
var out = parse(data);
// add to cache store
if(cache){
cache.set(url, data);
}
var endedRequest = new Date();
var requestTime = endedRequest.getTime() - startedRequest.getTime();
options.logger.log('made API call to: ' + requestTime + 'ms - ' + url);
callback(null, out);
}else{
callback('error requesting Lanyrd API', {});
}
});
}
}else{
callback('LANYRD_API_URL not found', {});
}
} | [
"function",
"getAPIData",
"(",
"userName",
",",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"process",
".",
"env",
".",
"LANYRD_API_URL",
")",
"{",
"var",
"url",
"=",
"process",
".",
"env",
".",
"LANYRD_API_URL",
"+",
"'people/'",
"+",
"userName",
"... | use the lanyrd api to get data | [
"use",
"the",
"lanyrd",
"api",
"to",
"get",
"data"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/plugins/lanyrd.js#L119-L161 |
35,274 | mozilla/speaktome-node | index.js | record | function record(options) {
return new Promise((res, rej) => {
var micInstance = mic({
rate: "16000",
channels: "1",
debug: true,
exitOnSilence: 3,
});
var micInputStream = micInstance.getAudioStream();
// Encode the file as Opus in an Ogg container, to send to server.
var rate = 16000;
var channels = 1;
var opusEncodeStream = new opus.Encoder(rate, channels);
var oggEncoder = new ogg.Encoder();
micInputStream.pipe(opusEncodeStream).pipe(oggEncoder.stream());
var bufs = [];
oggEncoder.on("data", function(buffer) {
bufs.push(buffer);
});
oggEncoder.on("end", function() {
// Package up encoded recording into buffer to send
// over the network to the API endpoint.
var buffer = Buffer.concat(bufs);
sendRecordingToServer(buffer, options)
.then((results) => {
res(results);
})
.catch((err) => {
console.error("ERR", err);
rej(err);
});
});
micInputStream.on("silence", function() {
// Stop recording at first silence after speaking.
micInstance.stop();
});
micInputStream.on("error", function(err) {
console.error("Error in Input Stream: " + err);
});
micInstance.start();
});
} | javascript | function record(options) {
return new Promise((res, rej) => {
var micInstance = mic({
rate: "16000",
channels: "1",
debug: true,
exitOnSilence: 3,
});
var micInputStream = micInstance.getAudioStream();
// Encode the file as Opus in an Ogg container, to send to server.
var rate = 16000;
var channels = 1;
var opusEncodeStream = new opus.Encoder(rate, channels);
var oggEncoder = new ogg.Encoder();
micInputStream.pipe(opusEncodeStream).pipe(oggEncoder.stream());
var bufs = [];
oggEncoder.on("data", function(buffer) {
bufs.push(buffer);
});
oggEncoder.on("end", function() {
// Package up encoded recording into buffer to send
// over the network to the API endpoint.
var buffer = Buffer.concat(bufs);
sendRecordingToServer(buffer, options)
.then((results) => {
res(results);
})
.catch((err) => {
console.error("ERR", err);
rej(err);
});
});
micInputStream.on("silence", function() {
// Stop recording at first silence after speaking.
micInstance.stop();
});
micInputStream.on("error", function(err) {
console.error("Error in Input Stream: " + err);
});
micInstance.start();
});
} | [
"function",
"record",
"(",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"res",
",",
"rej",
")",
"=>",
"{",
"var",
"micInstance",
"=",
"mic",
"(",
"{",
"rate",
":",
"\"16000\"",
",",
"channels",
":",
"\"1\"",
",",
"debug",
":",
"true",
... | Listen, record, send to server. Promise that returns array of results from server. | [
"Listen",
"record",
"send",
"to",
"server",
".",
"Promise",
"that",
"returns",
"array",
"of",
"results",
"from",
"server",
"."
] | af95d9890aa39d01e60de1c66434c003e81a51a7 | https://github.com/mozilla/speaktome-node/blob/af95d9890aa39d01e60de1c66434c003e81a51a7/index.js#L66-L117 |
35,275 | JamesMessinger/json-schema-lib | lib/api/JsonSchemaLib/JsonSchemaLib.js | JsonSchemaLib | function JsonSchemaLib (config, plugins) {
if (plugins === undefined && Array.isArray(config)) {
plugins = config;
config = undefined;
}
/**
* The configuration for this instance of {@link JsonSchemaLib}.
*
* @type {Config}
*/
this.config = new Config(config);
/**
* The plugins that have been added to this instance of {@link JsonSchemaLib}
*
* @type {object[]}
*/
this.plugins = new PluginManager(plugins);
} | javascript | function JsonSchemaLib (config, plugins) {
if (plugins === undefined && Array.isArray(config)) {
plugins = config;
config = undefined;
}
/**
* The configuration for this instance of {@link JsonSchemaLib}.
*
* @type {Config}
*/
this.config = new Config(config);
/**
* The plugins that have been added to this instance of {@link JsonSchemaLib}
*
* @type {object[]}
*/
this.plugins = new PluginManager(plugins);
} | [
"function",
"JsonSchemaLib",
"(",
"config",
",",
"plugins",
")",
"{",
"if",
"(",
"plugins",
"===",
"undefined",
"&&",
"Array",
".",
"isArray",
"(",
"config",
")",
")",
"{",
"plugins",
"=",
"config",
";",
"config",
"=",
"undefined",
";",
"}",
"/**\n * T... | The public JsonSchemaLib API.
@param {Config} [config] - The configuration to use. Can be overridden by {@link JsonSchemaLib#read}
@param {object[]} [plugins] - The plugins to use. Additional plugins can be added via {@link JsonSchemaLib#use}
@class | [
"The",
"public",
"JsonSchemaLib",
"API",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/JsonSchemaLib/JsonSchemaLib.js#L18-L37 |
35,276 | basti1302/repoman | lib/cli.js | _config | function _config(args) {
var opts = {};
if(args.removeExtraneous){
opts.removeExtraneous = true;
}
if (args.bitbucketAuthUser || args.bitbucketAuthPass) {
opts.bitbucket = {
authUser: args.bitbucketAuthUser,
authPass: args.bitbucketAuthPass
};
} else if (args.githubUser || args.githubOrg || args.githubAuthUser || args.githubAuthPass) {
opts.github = {
user : args.githubUser,
org : args.githubOrg,
authUser: args.githubAuthUser,
authPass: args.githubAuthPass,
useSsh : args.githubUseSsh
};
} else if (args.gitoriousUrl || args.gitoriousProject) {
opts.gitorious = {
url : args.gitoriousUrl,
project: args.gitoriousProject
};
} else if (args.local) {
opts.local = {
dir: process.cwd()
};
}
new Repoman().config(opts, bag.exit);
} | javascript | function _config(args) {
var opts = {};
if(args.removeExtraneous){
opts.removeExtraneous = true;
}
if (args.bitbucketAuthUser || args.bitbucketAuthPass) {
opts.bitbucket = {
authUser: args.bitbucketAuthUser,
authPass: args.bitbucketAuthPass
};
} else if (args.githubUser || args.githubOrg || args.githubAuthUser || args.githubAuthPass) {
opts.github = {
user : args.githubUser,
org : args.githubOrg,
authUser: args.githubAuthUser,
authPass: args.githubAuthPass,
useSsh : args.githubUseSsh
};
} else if (args.gitoriousUrl || args.gitoriousProject) {
opts.gitorious = {
url : args.gitoriousUrl,
project: args.gitoriousProject
};
} else if (args.local) {
opts.local = {
dir: process.cwd()
};
}
new Repoman().config(opts, bag.exit);
} | [
"function",
"_config",
"(",
"args",
")",
"{",
"var",
"opts",
"=",
"{",
"}",
";",
"if",
"(",
"args",
".",
"removeExtraneous",
")",
"{",
"opts",
".",
"removeExtraneous",
"=",
"true",
";",
"}",
"if",
"(",
"args",
".",
"bitbucketAuthUser",
"||",
"args",
... | Repoman CLI module.
@module cli | [
"Repoman",
"CLI",
"module",
"."
] | a1037015636d5744bcf764bc44a79961a93488da | https://github.com/basti1302/repoman/blob/a1037015636d5744bcf764bc44a79961a93488da/lib/cli.js#L14-L49 |
35,277 | matteodelabre/midijs | lib/file/event.js | Event | function Event(props, defaults, delay) {
var name;
this.delay = delay || 0;
props = props || {};
for (name in defaults) {
if (defaults.hasOwnProperty(name)) {
if (props.hasOwnProperty(name)) {
this[name] = props[name];
} else {
this[name] = defaults[name];
}
}
}
} | javascript | function Event(props, defaults, delay) {
var name;
this.delay = delay || 0;
props = props || {};
for (name in defaults) {
if (defaults.hasOwnProperty(name)) {
if (props.hasOwnProperty(name)) {
this[name] = props[name];
} else {
this[name] = defaults[name];
}
}
}
} | [
"function",
"Event",
"(",
"props",
",",
"defaults",
",",
"delay",
")",
"{",
"var",
"name",
";",
"this",
".",
"delay",
"=",
"delay",
"||",
"0",
";",
"props",
"=",
"props",
"||",
"{",
"}",
";",
"for",
"(",
"name",
"in",
"defaults",
")",
"{",
"if",
... | Construct a new Event
@abstract
@class Event
@classdesc Any type of MIDI event
@param {Object} [props={}] Event properties
@param {number} [defaults={}] Default event properties
@param {number} [delay=0] Event delay in ticks | [
"Construct",
"a",
"new",
"Event"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/event.js#L18-L33 |
35,278 | matteodelabre/midijs | lib/file/event.js | MetaEvent | function MetaEvent(type, props, delay) {
var defaults = {};
switch (type) {
case MetaEvent.TYPE.SEQUENCE_NUMBER:
defaults.number = 0;
break;
case MetaEvent.TYPE.TEXT:
case MetaEvent.TYPE.COPYRIGHT_NOTICE:
case MetaEvent.TYPE.SEQUENCE_NAME:
case MetaEvent.TYPE.INSTRUMENT_NAME:
case MetaEvent.TYPE.LYRICS:
case MetaEvent.TYPE.MARKER:
case MetaEvent.TYPE.CUE_POINT:
case MetaEvent.TYPE.PROGRAM_NAME:
case MetaEvent.TYPE.DEVICE_NAME:
defaults.text = '';
break;
case MetaEvent.TYPE.MIDI_CHANNEL:
defaults.channel = 0;
break;
case MetaEvent.TYPE.MIDI_PORT:
defaults.port = 0;
break;
case MetaEvent.TYPE.END_OF_TRACK:
break;
case MetaEvent.TYPE.SET_TEMPO:
defaults.tempo = 120;
break;
case MetaEvent.TYPE.SMPTE_OFFSET:
defaults.rate = 24;
defaults.hours = 0;
defaults.minutes = 0;
defaults.seconds = 0;
defaults.frames = 0;
defaults.subframes = 0;
break;
case MetaEvent.TYPE.TIME_SIGNATURE:
defaults.numerator = 4;
defaults.denominator = 4;
defaults.metronome = 24;
defaults.clockSignalsPerBeat = 24;
break;
case MetaEvent.TYPE.KEY_SIGNATURE:
defaults.note = 0;
defaults.major = true;
break;
case MetaEvent.TYPE.SEQUENCER_SPECIFIC:
defaults.data = new buffer.Buffer(0);
break;
default:
throw new error.MIDIInvalidEventError(
'Invalid MetaEvent type "' + type + '"'
);
}
this.type = type;
Event.call(this, props, defaults, delay);
} | javascript | function MetaEvent(type, props, delay) {
var defaults = {};
switch (type) {
case MetaEvent.TYPE.SEQUENCE_NUMBER:
defaults.number = 0;
break;
case MetaEvent.TYPE.TEXT:
case MetaEvent.TYPE.COPYRIGHT_NOTICE:
case MetaEvent.TYPE.SEQUENCE_NAME:
case MetaEvent.TYPE.INSTRUMENT_NAME:
case MetaEvent.TYPE.LYRICS:
case MetaEvent.TYPE.MARKER:
case MetaEvent.TYPE.CUE_POINT:
case MetaEvent.TYPE.PROGRAM_NAME:
case MetaEvent.TYPE.DEVICE_NAME:
defaults.text = '';
break;
case MetaEvent.TYPE.MIDI_CHANNEL:
defaults.channel = 0;
break;
case MetaEvent.TYPE.MIDI_PORT:
defaults.port = 0;
break;
case MetaEvent.TYPE.END_OF_TRACK:
break;
case MetaEvent.TYPE.SET_TEMPO:
defaults.tempo = 120;
break;
case MetaEvent.TYPE.SMPTE_OFFSET:
defaults.rate = 24;
defaults.hours = 0;
defaults.minutes = 0;
defaults.seconds = 0;
defaults.frames = 0;
defaults.subframes = 0;
break;
case MetaEvent.TYPE.TIME_SIGNATURE:
defaults.numerator = 4;
defaults.denominator = 4;
defaults.metronome = 24;
defaults.clockSignalsPerBeat = 24;
break;
case MetaEvent.TYPE.KEY_SIGNATURE:
defaults.note = 0;
defaults.major = true;
break;
case MetaEvent.TYPE.SEQUENCER_SPECIFIC:
defaults.data = new buffer.Buffer(0);
break;
default:
throw new error.MIDIInvalidEventError(
'Invalid MetaEvent type "' + type + '"'
);
}
this.type = type;
Event.call(this, props, defaults, delay);
} | [
"function",
"MetaEvent",
"(",
"type",
",",
"props",
",",
"delay",
")",
"{",
"var",
"defaults",
"=",
"{",
"}",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"MetaEvent",
".",
"TYPE",
".",
"SEQUENCE_NUMBER",
":",
"defaults",
".",
"number",
"=",
"0",
";... | Construct a new MetaEvent
@class MetaEvent
@extends Event
@classdesc A meta MIDI event, only encountered in Standard MIDI files
as holds information about the file
@param {MetaEvent.TYPE} type Type of meta event
@param {Object} [props={}] Event properties (@see MetaEvent.TYPE)
@param {number} [delay=0] Meta info delay in ticks
@throws {module:midijs/lib/error~MIDIInvalidEventError}
Invalid meta event type | [
"Construct",
"a",
"new",
"MetaEvent"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/event.js#L51-L109 |
35,279 | matteodelabre/midijs | lib/file/event.js | SysexEvent | function SysexEvent(type, data, delay) {
this.type = type;
this.data = data;
Event.call(this, {}, {}, delay);
} | javascript | function SysexEvent(type, data, delay) {
this.type = type;
this.data = data;
Event.call(this, {}, {}, delay);
} | [
"function",
"SysexEvent",
"(",
"type",
",",
"data",
",",
"delay",
")",
"{",
"this",
".",
"type",
"=",
"type",
";",
"this",
".",
"data",
"=",
"data",
";",
"Event",
".",
"call",
"(",
"this",
",",
"{",
"}",
",",
"{",
"}",
",",
"delay",
")",
";",
... | Construct a SysexEvent
@class SysexEvent
@extends Event
@classdesc A system exclusive MIDI event. This kind of event is
not formally defined by the specification and can hold any kind
of data. Its contents depends on the manufacturer, thus, this API
does not try to interpret them but only passes the data along
@param {number} type Sysex type
@param {Buffer} data Sysex data
@param {number} delay Sysex message delay in ticks | [
"Construct",
"a",
"SysexEvent"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/event.js#L204-L208 |
35,280 | matteodelabre/midijs | lib/file/event.js | ChannelEvent | function ChannelEvent(type, props, channel, delay) {
var defaults = {};
switch (type) {
case ChannelEvent.TYPE.NOTE_OFF:
defaults.note = 0;
defaults.velocity = 127;
break;
case ChannelEvent.TYPE.NOTE_ON:
defaults.note = 0;
defaults.velocity = 127;
break;
case ChannelEvent.TYPE.NOTE_AFTERTOUCH:
defaults.note = 0;
defaults.pressure = 0;
break;
case ChannelEvent.TYPE.CONTROLLER:
defaults.controller = 0;
defaults.value = 127;
break;
case ChannelEvent.TYPE.PROGRAM_CHANGE:
defaults.program = 0;
break;
case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH:
defaults.pressure = 0;
break;
case ChannelEvent.TYPE.PITCH_BEND:
defaults.value = 0;
break;
default:
throw new error.MIDIInvalidEventError(
'Invalid ChannelEvent type "' + type + '"'
);
}
this.type = type;
this.channel = channel || 0;
Event.call(this, props, defaults, delay);
} | javascript | function ChannelEvent(type, props, channel, delay) {
var defaults = {};
switch (type) {
case ChannelEvent.TYPE.NOTE_OFF:
defaults.note = 0;
defaults.velocity = 127;
break;
case ChannelEvent.TYPE.NOTE_ON:
defaults.note = 0;
defaults.velocity = 127;
break;
case ChannelEvent.TYPE.NOTE_AFTERTOUCH:
defaults.note = 0;
defaults.pressure = 0;
break;
case ChannelEvent.TYPE.CONTROLLER:
defaults.controller = 0;
defaults.value = 127;
break;
case ChannelEvent.TYPE.PROGRAM_CHANGE:
defaults.program = 0;
break;
case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH:
defaults.pressure = 0;
break;
case ChannelEvent.TYPE.PITCH_BEND:
defaults.value = 0;
break;
default:
throw new error.MIDIInvalidEventError(
'Invalid ChannelEvent type "' + type + '"'
);
}
this.type = type;
this.channel = channel || 0;
Event.call(this, props, defaults, delay);
} | [
"function",
"ChannelEvent",
"(",
"type",
",",
"props",
",",
"channel",
",",
"delay",
")",
"{",
"var",
"defaults",
"=",
"{",
"}",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"ChannelEvent",
".",
"TYPE",
".",
"NOTE_OFF",
":",
"defaults",
".",
"note",
... | Construct a ChannelEvent
@class ChannelEvent
@extends Event
@classdesc A channel MIDI event. This kind of event is the most important
one, it describes the state of the instruments, relative to the previous
state. Channel events can be transmitted between devices and can
also be present in Standard MIDI files.
@param {ChannelEvent.TYPE} type Type of channel event
@param {Object} [props={}] Event properties
@param {number} [channel=0] Channel to which the event applies
@param {number} [delay=0] Channel event delay in ticks
@throws {module:midijs/lib/error~MIDIInvalidEventError}
Invalid channel event type | [
"Construct",
"a",
"ChannelEvent"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/event.js#L230-L268 |
35,281 | stagnationlab/jumio | build/index.js | Jumio | function Jumio(config) {
var _this = this;
// setup configuration with defaults
this.config = __assign({ version: "1.0.0", identityApiBaseUrl: exports.identityRegionApiUrlMap[config.region], documentApiBaseUrl: exports.documentRegionApiUrlMap[config.region], callbackWhitelist: exports.regionCallbackWhitelistMap[config.region], handleIdentityVerification: function (_result) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); }); }, handleDocumentVerification: function (_result) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); }); }, log: ts_log_1.dummyLogger }, config);
// keep a shorter reference to the logger
this.log = this.config.log;
// build company-specific user agent
var userAgent = this.config.company + "/" + this.config.version;
// configure axios for making API requests to the identity verification api
this.identityApi = axios_1.default.create({
baseURL: this.config.identityApiBaseUrl,
auth: {
username: this.config.apiToken,
password: this.config.apiSecret
},
headers: {
"User-Agent": userAgent
}
});
// configure axios for making API requests to the document verification api
this.documentApi = axios_1.default.create({
baseURL: this.config.documentApiBaseUrl,
auth: {
username: this.config.apiToken,
password: this.config.apiSecret
},
headers: {
"User-Agent": userAgent
}
});
// log initialized
this.log.info({
identityApiBaseUrl: this.config.identityApiBaseUrl,
documentApiBaseUrl: this.config.documentApiBaseUrl,
apiToken: this.config.apiToken,
apiSecret: new Array(this.config.apiSecret.length + 1).join("x"),
userAgent: userAgent
}, "initialized");
} | javascript | function Jumio(config) {
var _this = this;
// setup configuration with defaults
this.config = __assign({ version: "1.0.0", identityApiBaseUrl: exports.identityRegionApiUrlMap[config.region], documentApiBaseUrl: exports.documentRegionApiUrlMap[config.region], callbackWhitelist: exports.regionCallbackWhitelistMap[config.region], handleIdentityVerification: function (_result) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); }); }, handleDocumentVerification: function (_result) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); }); }, log: ts_log_1.dummyLogger }, config);
// keep a shorter reference to the logger
this.log = this.config.log;
// build company-specific user agent
var userAgent = this.config.company + "/" + this.config.version;
// configure axios for making API requests to the identity verification api
this.identityApi = axios_1.default.create({
baseURL: this.config.identityApiBaseUrl,
auth: {
username: this.config.apiToken,
password: this.config.apiSecret
},
headers: {
"User-Agent": userAgent
}
});
// configure axios for making API requests to the document verification api
this.documentApi = axios_1.default.create({
baseURL: this.config.documentApiBaseUrl,
auth: {
username: this.config.apiToken,
password: this.config.apiSecret
},
headers: {
"User-Agent": userAgent
}
});
// log initialized
this.log.info({
identityApiBaseUrl: this.config.identityApiBaseUrl,
documentApiBaseUrl: this.config.documentApiBaseUrl,
apiToken: this.config.apiToken,
apiSecret: new Array(this.config.apiSecret.length + 1).join("x"),
userAgent: userAgent
}, "initialized");
} | [
"function",
"Jumio",
"(",
"config",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"// setup configuration with defaults",
"this",
".",
"config",
"=",
"__assign",
"(",
"{",
"version",
":",
"\"1.0.0\"",
",",
"identityApiBaseUrl",
":",
"exports",
".",
"identityRegion... | Sets up the library.
@param config Configuration | [
"Sets",
"up",
"the",
"library",
"."
] | 2e9223bf057b5b2c889806958aeec4db41473922 | https://github.com/stagnationlab/jumio/blob/2e9223bf057b5b2c889806958aeec4db41473922/build/index.js#L2517-L2559 |
35,282 | JamesMessinger/json-schema-lib | lib/util/isTypedArray.js | isTypedArray | function isTypedArray (obj) {
if (typeof obj === 'object') {
for (var i = 0; i < supportedDataTypes.length; i++) {
if (obj instanceof supportedDataTypes[i]) {
return true;
}
}
}
} | javascript | function isTypedArray (obj) {
if (typeof obj === 'object') {
for (var i = 0; i < supportedDataTypes.length; i++) {
if (obj instanceof supportedDataTypes[i]) {
return true;
}
}
}
} | [
"function",
"isTypedArray",
"(",
"obj",
")",
"{",
"if",
"(",
"typeof",
"obj",
"===",
"'object'",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"supportedDataTypes",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"obj",
"instanceof... | Determines whether the given object is any of the TypedArray types.
@param {*} obj
@returns {boolean} | [
"Determines",
"whether",
"the",
"given",
"object",
"is",
"any",
"of",
"the",
"TypedArray",
"types",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/isTypedArray.js#L13-L21 |
35,283 | JamesMessinger/json-schema-lib | lib/util/isTypedArray.js | getSupportedDataTypes | function getSupportedDataTypes () {
var types = [];
// NOTE: More frequently-used types come first, to improve lookup speed
if (typeof Uint8Array === 'function') {
types.push(Uint8Array);
}
if (typeof Uint16Array === 'function') {
types.push(Uint16Array);
}
if (typeof ArrayBuffer === 'function') {
types.push(ArrayBuffer);
}
if (typeof Uint32Array === 'function') {
types.push(Uint32Array);
}
if (typeof Int8Array === 'function') {
types.push(Int8Array);
}
if (typeof Int16Array === 'function') {
types.push(Int16Array);
}
if (typeof Int32Array === 'function') {
types.push(Int32Array);
}
if (typeof Uint8ClampedArray === 'function') {
types.push(Uint8ClampedArray);
}
if (typeof Float32Array === 'function') {
types.push(Float32Array);
}
if (typeof Float64Array === 'function') {
types.push(Float64Array);
}
if (typeof DataView === 'function') {
types.push(DataView);
}
return types;
} | javascript | function getSupportedDataTypes () {
var types = [];
// NOTE: More frequently-used types come first, to improve lookup speed
if (typeof Uint8Array === 'function') {
types.push(Uint8Array);
}
if (typeof Uint16Array === 'function') {
types.push(Uint16Array);
}
if (typeof ArrayBuffer === 'function') {
types.push(ArrayBuffer);
}
if (typeof Uint32Array === 'function') {
types.push(Uint32Array);
}
if (typeof Int8Array === 'function') {
types.push(Int8Array);
}
if (typeof Int16Array === 'function') {
types.push(Int16Array);
}
if (typeof Int32Array === 'function') {
types.push(Int32Array);
}
if (typeof Uint8ClampedArray === 'function') {
types.push(Uint8ClampedArray);
}
if (typeof Float32Array === 'function') {
types.push(Float32Array);
}
if (typeof Float64Array === 'function') {
types.push(Float64Array);
}
if (typeof DataView === 'function') {
types.push(DataView);
}
return types;
} | [
"function",
"getSupportedDataTypes",
"(",
")",
"{",
"var",
"types",
"=",
"[",
"]",
";",
"// NOTE: More frequently-used types come first, to improve lookup speed",
"if",
"(",
"typeof",
"Uint8Array",
"===",
"'function'",
")",
"{",
"types",
".",
"push",
"(",
"Uint8Array"... | Returns the TypedArray data types that are supported by the current runtime environment.
@returns {function[]} | [
"Returns",
"the",
"TypedArray",
"data",
"types",
"that",
"are",
"supported",
"by",
"the",
"current",
"runtime",
"environment",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/isTypedArray.js#L28-L67 |
35,284 | basti1302/repoman | lib/generator/bitbucket.js | Bitbucket | function Bitbucket(user, pass) {
this.user = user;
this.client = bitbucket.createClient({ username: user, password: pass });
} | javascript | function Bitbucket(user, pass) {
this.user = user;
this.client = bitbucket.createClient({ username: user, password: pass });
} | [
"function",
"Bitbucket",
"(",
"user",
",",
"pass",
")",
"{",
"this",
".",
"user",
"=",
"user",
";",
"this",
".",
"client",
"=",
"bitbucket",
".",
"createClient",
"(",
"{",
"username",
":",
"user",
",",
"password",
":",
"pass",
"}",
")",
";",
"}"
] | Configuration generator for remote Bitbucket repositories.
@param {String} user Bitbucket username
@param {String} pass Bitbucket password
@class | [
"Configuration",
"generator",
"for",
"remote",
"Bitbucket",
"repositories",
"."
] | a1037015636d5744bcf764bc44a79961a93488da | https://github.com/basti1302/repoman/blob/a1037015636d5744bcf764bc44a79961a93488da/lib/generator/bitbucket.js#L12-L16 |
35,285 | matteodelabre/midijs | lib/file/parser/chunk.js | parseChunk | function parseChunk(expected, cursor) {
var type, length;
type = cursor.toString('ascii', 4);
length = cursor.readUInt32BE();
if (type !== expected) {
throw new error.MIDIParserError(
type,
expected,
cursor.tell()
);
}
return cursor.slice(length);
} | javascript | function parseChunk(expected, cursor) {
var type, length;
type = cursor.toString('ascii', 4);
length = cursor.readUInt32BE();
if (type !== expected) {
throw new error.MIDIParserError(
type,
expected,
cursor.tell()
);
}
return cursor.slice(length);
} | [
"function",
"parseChunk",
"(",
"expected",
",",
"cursor",
")",
"{",
"var",
"type",
",",
"length",
";",
"type",
"=",
"cursor",
".",
"toString",
"(",
"'ascii'",
",",
"4",
")",
";",
"length",
"=",
"cursor",
".",
"readUInt32BE",
"(",
")",
";",
"if",
"(",... | Parse a MIDI chunk
@param {string} expected Expected type
@param {module:buffercursor} cursor Buffer to parse
@throws {module:midijs/lib/error~MIDIParserError}
Type expectation failed
@return {Buffer} Chunk data | [
"Parse",
"a",
"MIDI",
"chunk"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/chunk.js#L14-L29 |
35,286 | LivePersonInc/chronosjs | src/Events.js | unbind | function unbind(unbindObj) {
if ("*" !== defaultAppName) {
unbindObj.appName = unbindObj.appName || defaultAppName;
}
return evUtil.unbind({
unbindObj: unbindObj,
attrName: attrName,
loggerName: appName,
lstnrs: lstnrs
});
} | javascript | function unbind(unbindObj) {
if ("*" !== defaultAppName) {
unbindObj.appName = unbindObj.appName || defaultAppName;
}
return evUtil.unbind({
unbindObj: unbindObj,
attrName: attrName,
loggerName: appName,
lstnrs: lstnrs
});
} | [
"function",
"unbind",
"(",
"unbindObj",
")",
"{",
"if",
"(",
"\"*\"",
"!==",
"defaultAppName",
")",
"{",
"unbindObj",
".",
"appName",
"=",
"unbindObj",
".",
"appName",
"||",
"defaultAppName",
";",
"}",
"return",
"evUtil",
".",
"unbind",
"(",
"{",
"unbindOb... | This function allows unbinding according to a permutation of the three parameters
@param unbindObj
eventName - the eventName you want to unbind
func - the pointer to the function you want to unbind
context - the context you want to unbind
appName - the specific appName we want to unbind
OR - eventId
@return {Boolean} | [
"This",
"function",
"allows",
"unbinding",
"according",
"to",
"a",
"permutation",
"of",
"the",
"three",
"parameters"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/Events.js#L135-L145 |
35,287 | LivePersonInc/chronosjs | src/Events.js | hasFired | function hasFired(app, evName) {
if ("undefined" === typeof evName) {
evName = app;
app = defaultAppName;
}
return evUtil.hasFired(fired, app, evName);
} | javascript | function hasFired(app, evName) {
if ("undefined" === typeof evName) {
evName = app;
app = defaultAppName;
}
return evUtil.hasFired(fired, app, evName);
} | [
"function",
"hasFired",
"(",
"app",
",",
"evName",
")",
"{",
"if",
"(",
"\"undefined\"",
"===",
"typeof",
"evName",
")",
"{",
"evName",
"=",
"app",
";",
"app",
"=",
"defaultAppName",
";",
"}",
"return",
"evUtil",
".",
"hasFired",
"(",
"fired",
",",
"ap... | firedEventData can pass two request parameters
@param app name
@param evName = event name
@return {Array} | [
"firedEventData",
"can",
"pass",
"two",
"request",
"parameters"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/Events.js#L153-L160 |
35,288 | LivePersonInc/chronosjs | src/Events.js | _storeEventData | function _storeEventData(triggerData) {
evUtil.storeEventData({
triggerData: triggerData,
eventBufferLimit: eventBufferLimit,
attrName: attrName,
fired: fired,
index: indexer
});
} | javascript | function _storeEventData(triggerData) {
evUtil.storeEventData({
triggerData: triggerData,
eventBufferLimit: eventBufferLimit,
attrName: attrName,
fired: fired,
index: indexer
});
} | [
"function",
"_storeEventData",
"(",
"triggerData",
")",
"{",
"evUtil",
".",
"storeEventData",
"(",
"{",
"triggerData",
":",
"triggerData",
",",
"eventBufferLimit",
":",
"eventBufferLimit",
",",
"attrName",
":",
"attrName",
",",
"fired",
":",
"fired",
",",
"index... | Stores events so we can later ask for them, can be set to a limited store by defaults on instantiation
@param triggerData | [
"Stores",
"events",
"so",
"we",
"can",
"later",
"ask",
"for",
"them",
"can",
"be",
"set",
"to",
"a",
"limited",
"store",
"by",
"defaults",
"on",
"instantiation"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/Events.js#L237-L245 |
35,289 | graphology/graphology-shortest-path | unweighted.js | singleSource | function singleSource(graph, source) {
if (!isGraph(graph))
throw new Error('graphology-shortest-path: invalid graphology instance.');
if (arguments.length < 2)
throw new Error('graphology-shortest-path: invalid number of arguments. Expecting at least 2.');
if (!graph.hasNode(source))
throw new Error('graphology-shortest-path: the "' + source + '" source node does not exist in the given graph.');
source = '' + source;
var nextLevel = {},
paths = {},
currentLevel,
neighbors,
v,
w,
i,
l;
nextLevel[source] = true;
paths[source] = [source];
while (Object.keys(nextLevel).length) {
currentLevel = nextLevel;
nextLevel = {};
for (v in currentLevel) {
neighbors = graph.outNeighbors(v);
neighbors.push.apply(neighbors, graph.undirectedNeighbors(v));
for (i = 0, l = neighbors.length; i < l; i++) {
w = neighbors[i];
if (!paths[w]) {
paths[w] = paths[v].concat(w);
nextLevel[w] = true;
}
}
}
}
return paths;
} | javascript | function singleSource(graph, source) {
if (!isGraph(graph))
throw new Error('graphology-shortest-path: invalid graphology instance.');
if (arguments.length < 2)
throw new Error('graphology-shortest-path: invalid number of arguments. Expecting at least 2.');
if (!graph.hasNode(source))
throw new Error('graphology-shortest-path: the "' + source + '" source node does not exist in the given graph.');
source = '' + source;
var nextLevel = {},
paths = {},
currentLevel,
neighbors,
v,
w,
i,
l;
nextLevel[source] = true;
paths[source] = [source];
while (Object.keys(nextLevel).length) {
currentLevel = nextLevel;
nextLevel = {};
for (v in currentLevel) {
neighbors = graph.outNeighbors(v);
neighbors.push.apply(neighbors, graph.undirectedNeighbors(v));
for (i = 0, l = neighbors.length; i < l; i++) {
w = neighbors[i];
if (!paths[w]) {
paths[w] = paths[v].concat(w);
nextLevel[w] = true;
}
}
}
}
return paths;
} | [
"function",
"singleSource",
"(",
"graph",
",",
"source",
")",
"{",
"if",
"(",
"!",
"isGraph",
"(",
"graph",
")",
")",
"throw",
"new",
"Error",
"(",
"'graphology-shortest-path: invalid graphology instance.'",
")",
";",
"if",
"(",
"arguments",
".",
"length",
"<"... | Function attempting to find the shortest path in the graph between the
given source node & all the other nodes.
@param {Graph} graph - Target graph.
@param {any} source - Source node.
@return {object} - The map of found paths.
TODO: cutoff option | [
"Function",
"attempting",
"to",
"find",
"the",
"shortest",
"path",
"in",
"the",
"graph",
"between",
"the",
"given",
"source",
"node",
"&",
"all",
"the",
"other",
"nodes",
"."
] | d0c820c5242fc48738102f40b9cdf345a078248c | https://github.com/graphology/graphology-shortest-path/blob/d0c820c5242fc48738102f40b9cdf345a078248c/unweighted.js#L174-L218 |
35,290 | JamesMessinger/json-schema-lib | lib/plugins/NodeUrlPlugin.js | resolveUrl | function resolveUrl (from, to) {
if (typeof URL === 'function') {
// Use the new WHATWG URL API
return new URL(to, from).href;
}
else {
// Use the legacy url API
return legacyURL.resolve(from, to);
}
} | javascript | function resolveUrl (from, to) {
if (typeof URL === 'function') {
// Use the new WHATWG URL API
return new URL(to, from).href;
}
else {
// Use the legacy url API
return legacyURL.resolve(from, to);
}
} | [
"function",
"resolveUrl",
"(",
"from",
",",
"to",
")",
"{",
"if",
"(",
"typeof",
"URL",
"===",
"'function'",
")",
"{",
"// Use the new WHATWG URL API",
"return",
"new",
"URL",
"(",
"to",
",",
"from",
")",
".",
"href",
";",
"}",
"else",
"{",
"// Use the l... | Resolve the given URL, using either the legacy Node.js url API, or the WHATWG URL API.
@param {string} from
@param {string} to
@returns {string} | [
"Resolve",
"the",
"given",
"URL",
"using",
"either",
"the",
"legacy",
"Node",
".",
"js",
"url",
"API",
"or",
"the",
"WHATWG",
"URL",
"API",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/NodeUrlPlugin.js#L76-L85 |
35,291 | graphology/graphology-shortest-path | dijkstra.js | abstractDijkstraMultisource | function abstractDijkstraMultisource(
graph,
sources,
weightAttribute,
cutoff,
target,
paths
) {
if (!isGraph(graph))
throw new Error('graphology-shortest-path/dijkstra: invalid graphology instance.');
if (target && !graph.hasNode(target))
throw new Error('graphology-shortest-path/dijkstra: the "' + target + '" target node does not exist in the given graph.');
weightAttribute = weightAttribute || DEFAULTS.weightAttribute;
// Building necessary functions
var getWeight = function(edge) {
return graph.getEdgeAttribute(edge, weightAttribute);
};
var distances = {},
seen = {},
fringe = new Heap(DIJKSTRA_HEAP_COMPARATOR);
var count = 0,
edges,
item,
cost,
v,
u,
e,
d,
i,
j,
l,
m;
for (i = 0, l = sources.length; i < l; i++) {
v = sources[i];
seen[v] = 0;
fringe.push([0, count++, v]);
if (paths)
paths[v] = [v];
}
while (fringe.size) {
item = fringe.pop();
d = item[0];
v = item[2];
if (v in distances)
continue;
distances[v] = d;
if (v === target)
break;
edges = graph
.undirectedEdges(v)
.concat(graph.outEdges(v));
for (j = 0, m = edges.length; j < m; j++) {
e = edges[j];
u = graph.opposite(v, e);
cost = getWeight(e) + distances[v];
if (cutoff && cost > cutoff)
continue;
if (u in distances && cost < distances[u]) {
throw Error('graphology-shortest-path/dijkstra: contradictory paths found. Do some of your edges have a negative weight?');
}
else if (!(u in seen) || cost < seen[u]) {
seen[u] = cost;
fringe.push([cost, count++, u]);
if (paths)
paths[u] = paths[v].concat(u);
}
}
}
return distances;
} | javascript | function abstractDijkstraMultisource(
graph,
sources,
weightAttribute,
cutoff,
target,
paths
) {
if (!isGraph(graph))
throw new Error('graphology-shortest-path/dijkstra: invalid graphology instance.');
if (target && !graph.hasNode(target))
throw new Error('graphology-shortest-path/dijkstra: the "' + target + '" target node does not exist in the given graph.');
weightAttribute = weightAttribute || DEFAULTS.weightAttribute;
// Building necessary functions
var getWeight = function(edge) {
return graph.getEdgeAttribute(edge, weightAttribute);
};
var distances = {},
seen = {},
fringe = new Heap(DIJKSTRA_HEAP_COMPARATOR);
var count = 0,
edges,
item,
cost,
v,
u,
e,
d,
i,
j,
l,
m;
for (i = 0, l = sources.length; i < l; i++) {
v = sources[i];
seen[v] = 0;
fringe.push([0, count++, v]);
if (paths)
paths[v] = [v];
}
while (fringe.size) {
item = fringe.pop();
d = item[0];
v = item[2];
if (v in distances)
continue;
distances[v] = d;
if (v === target)
break;
edges = graph
.undirectedEdges(v)
.concat(graph.outEdges(v));
for (j = 0, m = edges.length; j < m; j++) {
e = edges[j];
u = graph.opposite(v, e);
cost = getWeight(e) + distances[v];
if (cutoff && cost > cutoff)
continue;
if (u in distances && cost < distances[u]) {
throw Error('graphology-shortest-path/dijkstra: contradictory paths found. Do some of your edges have a negative weight?');
}
else if (!(u in seen) || cost < seen[u]) {
seen[u] = cost;
fringe.push([cost, count++, u]);
if (paths)
paths[u] = paths[v].concat(u);
}
}
}
return distances;
} | [
"function",
"abstractDijkstraMultisource",
"(",
"graph",
",",
"sources",
",",
"weightAttribute",
",",
"cutoff",
",",
"target",
",",
"paths",
")",
"{",
"if",
"(",
"!",
"isGraph",
"(",
"graph",
")",
")",
"throw",
"new",
"Error",
"(",
"'graphology-shortest-path/d... | Multisource Dijkstra shortest path abstract function. This function is the
basis of the algorithm that every other will use.
Note that this implementation was basically copied from networkx.
TODO: it might be more performant to use a dedicated objet for the heap's
items.
@param {Graph} graph - The graphology instance.
@param {array} sources - A list of sources.
@param {string} weightAttribute - Name of the weight attribute.
@param {number} cutoff - Maximum depth of the search.
@param {string} target - Optional target to reach.
@param {object} paths - Optional paths object to maintain.
@return {object} - Returns the paths. | [
"Multisource",
"Dijkstra",
"shortest",
"path",
"abstract",
"function",
".",
"This",
"function",
"is",
"the",
"basis",
"of",
"the",
"algorithm",
"that",
"every",
"other",
"will",
"use",
"."
] | d0c820c5242fc48738102f40b9cdf345a078248c | https://github.com/graphology/graphology-shortest-path/blob/d0c820c5242fc48738102f40b9cdf345a078248c/dijkstra.js#L190-L278 |
35,292 | graphology/graphology-shortest-path | dijkstra.js | singleSourceDijkstra | function singleSourceDijkstra(graph, source, weightAttribute) {
var paths = {};
abstractDijkstraMultisource(
graph,
[source],
weightAttribute,
0,
null,
paths
);
return paths;
} | javascript | function singleSourceDijkstra(graph, source, weightAttribute) {
var paths = {};
abstractDijkstraMultisource(
graph,
[source],
weightAttribute,
0,
null,
paths
);
return paths;
} | [
"function",
"singleSourceDijkstra",
"(",
"graph",
",",
"source",
",",
"weightAttribute",
")",
"{",
"var",
"paths",
"=",
"{",
"}",
";",
"abstractDijkstraMultisource",
"(",
"graph",
",",
"[",
"source",
"]",
",",
"weightAttribute",
",",
"0",
",",
"null",
",",
... | Single source Dijkstra shortest path between given node & other nodes in
the graph.
@param {Graph} graph - The graphology instance.
@param {string} source - Source node.
@param {string} weightAttribute - Name of the weight attribute.
@return {object} - An object of found paths. | [
"Single",
"source",
"Dijkstra",
"shortest",
"path",
"between",
"given",
"node",
"&",
"other",
"nodes",
"in",
"the",
"graph",
"."
] | d0c820c5242fc48738102f40b9cdf345a078248c | https://github.com/graphology/graphology-shortest-path/blob/d0c820c5242fc48738102f40b9cdf345a078248c/dijkstra.js#L289-L302 |
35,293 | JamesMessinger/json-schema-lib | lib/api/PluginHelper/PluginHelper.js | PluginHelper | function PluginHelper (plugins, schema) {
validatePlugins(plugins);
plugins = plugins || [];
// Clone the array of plugins, and sort by priority
var pluginHelper = plugins.slice().sort(sortByPriority);
/**
* Internal stuff. Use at your own risk!
*
* @private
*/
pluginHelper[__internal] = {
/**
* A reference to the {@link Schema} object
*/
schema: schema,
};
// Return an array that "inherits" from PluginHelper
return assign(pluginHelper, PluginHelper.prototype);
} | javascript | function PluginHelper (plugins, schema) {
validatePlugins(plugins);
plugins = plugins || [];
// Clone the array of plugins, and sort by priority
var pluginHelper = plugins.slice().sort(sortByPriority);
/**
* Internal stuff. Use at your own risk!
*
* @private
*/
pluginHelper[__internal] = {
/**
* A reference to the {@link Schema} object
*/
schema: schema,
};
// Return an array that "inherits" from PluginHelper
return assign(pluginHelper, PluginHelper.prototype);
} | [
"function",
"PluginHelper",
"(",
"plugins",
",",
"schema",
")",
"{",
"validatePlugins",
"(",
"plugins",
")",
";",
"plugins",
"=",
"plugins",
"||",
"[",
"]",
";",
"// Clone the array of plugins, and sort by priority",
"var",
"pluginHelper",
"=",
"plugins",
".",
"sl... | Helper methods for working with plugins.
@param {object[]|null} plugins - The plugins to use
@param {Schema} schema - The {@link Schema} to apply the plugins to
@class
@extends Array | [
"Helper",
"methods",
"for",
"working",
"with",
"plugins",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/PluginHelper/PluginHelper.js#L21-L42 |
35,294 | matteodelabre/midijs | lib/file/encoder/chunk.js | encodeChunk | function encodeChunk(type, data) {
var cursor = new BufferCursor(new buffer.Buffer(
buffer.Buffer.byteLength(type) + 4 + data.length
));
cursor.write(type);
cursor.writeUInt32BE(data.length);
cursor.copy(data);
return cursor.buffer;
} | javascript | function encodeChunk(type, data) {
var cursor = new BufferCursor(new buffer.Buffer(
buffer.Buffer.byteLength(type) + 4 + data.length
));
cursor.write(type);
cursor.writeUInt32BE(data.length);
cursor.copy(data);
return cursor.buffer;
} | [
"function",
"encodeChunk",
"(",
"type",
",",
"data",
")",
"{",
"var",
"cursor",
"=",
"new",
"BufferCursor",
"(",
"new",
"buffer",
".",
"Buffer",
"(",
"buffer",
".",
"Buffer",
".",
"byteLength",
"(",
"type",
")",
"+",
"4",
"+",
"data",
".",
"length",
... | Encode a MIDI chunk
@param {string} type Chunk type
@param {Buffer} data Chunk data
@return {Buffer} Encoded chunk | [
"Encode",
"a",
"MIDI",
"chunk"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/encoder/chunk.js#L13-L23 |
35,295 | jhermsmeier/node-tle | lib/tle.js | function( value ) {
var lines = TLE.trim( value + '' ).split( /\r?\n/g )
var line, checksum
// Line 0
if (lines.length === 3) {
this.name = TLE.trim( lines.shift() )
}
// Line 1
line = lines.shift()
checksum = TLE.check( line )
if( checksum != line.substring( 68, 69 ) ) {
throw new Error(
'Line 1 checksum mismatch: ' + checksum + ' != ' +
line.substring( 68, 69 ) + ': ' + line
)
}
this.number = TLE.parseFloat( line.substring( 2, 7 ) )
this.class = TLE.trim( line.substring( 7, 9 ) )
this.id = TLE.trim( line.substring( 9, 18 ) )
this.date = TLE.parseDate( line.substring( 18, 33 ) )
this.fdmm = TLE.parseFloat( line.substring( 33, 44 ) )
this.sdmm = TLE.parseFloat( line.substring( 44, 53 ) )
this.drag = TLE.parseDrag( line.substring( 53, 62 ) )
this.ephemeris = TLE.parseFloat( line.substring( 62, 64 ) )
this.esn = TLE.parseFloat( line.substring( 64, 68 ) )
// Line 2
line = lines.shift()
checksum = TLE.check( line )
if( checksum != line.substring( 68, 69 ) ) {
throw new Error(
'Line 2 checksum mismatch: ' + checksum + ' != ' +
line.substring( 68, 69 ) + ': ' + line
)
}
this.inclination = TLE.parseFloat( line.substring( 8, 17 ) )
this.ascension = TLE.parseFloat( line.substring( 17, 26 ) )
this.eccentricity = TLE.parseFloat( '0.' + line.substring( 26, 34 ) )
this.perigee = TLE.parseFloat( line.substring( 34, 43 ) )
this.anomaly = TLE.parseFloat( line.substring( 43, 52 ) )
this.motion = TLE.parseFloat( line.substring( 52, 64 ) )
this.revolution = TLE.parseFloat( line.substring( 64, 68 ) )
return this
} | javascript | function( value ) {
var lines = TLE.trim( value + '' ).split( /\r?\n/g )
var line, checksum
// Line 0
if (lines.length === 3) {
this.name = TLE.trim( lines.shift() )
}
// Line 1
line = lines.shift()
checksum = TLE.check( line )
if( checksum != line.substring( 68, 69 ) ) {
throw new Error(
'Line 1 checksum mismatch: ' + checksum + ' != ' +
line.substring( 68, 69 ) + ': ' + line
)
}
this.number = TLE.parseFloat( line.substring( 2, 7 ) )
this.class = TLE.trim( line.substring( 7, 9 ) )
this.id = TLE.trim( line.substring( 9, 18 ) )
this.date = TLE.parseDate( line.substring( 18, 33 ) )
this.fdmm = TLE.parseFloat( line.substring( 33, 44 ) )
this.sdmm = TLE.parseFloat( line.substring( 44, 53 ) )
this.drag = TLE.parseDrag( line.substring( 53, 62 ) )
this.ephemeris = TLE.parseFloat( line.substring( 62, 64 ) )
this.esn = TLE.parseFloat( line.substring( 64, 68 ) )
// Line 2
line = lines.shift()
checksum = TLE.check( line )
if( checksum != line.substring( 68, 69 ) ) {
throw new Error(
'Line 2 checksum mismatch: ' + checksum + ' != ' +
line.substring( 68, 69 ) + ': ' + line
)
}
this.inclination = TLE.parseFloat( line.substring( 8, 17 ) )
this.ascension = TLE.parseFloat( line.substring( 17, 26 ) )
this.eccentricity = TLE.parseFloat( '0.' + line.substring( 26, 34 ) )
this.perigee = TLE.parseFloat( line.substring( 34, 43 ) )
this.anomaly = TLE.parseFloat( line.substring( 43, 52 ) )
this.motion = TLE.parseFloat( line.substring( 52, 64 ) )
this.revolution = TLE.parseFloat( line.substring( 64, 68 ) )
return this
} | [
"function",
"(",
"value",
")",
"{",
"var",
"lines",
"=",
"TLE",
".",
"trim",
"(",
"value",
"+",
"''",
")",
".",
"split",
"(",
"/",
"\\r?\\n",
"/",
"g",
")",
"var",
"line",
",",
"checksum",
"// Line 0",
"if",
"(",
"lines",
".",
"length",
"===",
"3... | Parse a TLE's string representation
@param {String} value
@return {TLE} | [
"Parse",
"a",
"TLE",
"s",
"string",
"representation"
] | 0c0a57270cd6573b912f007a5b9da83f98eba775 | https://github.com/jhermsmeier/node-tle/blob/0c0a57270cd6573b912f007a5b9da83f98eba775/lib/tle.js#L199-L251 | |
35,296 | JamesMessinger/json-schema-lib | lib/api/PluginHelper/callSyncPlugin.js | callSyncPlugin | function callSyncPlugin (pluginHelper, methodName, args) {
var plugins = pluginHelper.filter(filterByMethod(methodName));
args.schema = pluginHelper[__internal].schema;
args.config = args.schema.config;
return callNextPlugin(plugins, methodName, args);
} | javascript | function callSyncPlugin (pluginHelper, methodName, args) {
var plugins = pluginHelper.filter(filterByMethod(methodName));
args.schema = pluginHelper[__internal].schema;
args.config = args.schema.config;
return callNextPlugin(plugins, methodName, args);
} | [
"function",
"callSyncPlugin",
"(",
"pluginHelper",
",",
"methodName",
",",
"args",
")",
"{",
"var",
"plugins",
"=",
"pluginHelper",
".",
"filter",
"(",
"filterByMethod",
"(",
"methodName",
")",
")",
";",
"args",
".",
"schema",
"=",
"pluginHelper",
"[",
"__in... | Calls a synchronous plugin method with the given arguments.
@param {PluginHelper} pluginHelper - The {@link PluginHelper} whose plugins are called
@param {string} methodName - The name of the plugin method to call
@param {object} args - The arguments to pass to the method
@returns {{ result: *, plugin: ?object }}
If the method was handled by a plugin (i.e. the plugin didn't call next()), then the returned
object will contain a reference to the plugin, and the result that was returned by the plugin. | [
"Calls",
"a",
"synchronous",
"plugin",
"method",
"with",
"the",
"given",
"arguments",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/PluginHelper/callSyncPlugin.js#L20-L26 |
35,297 | glennjones/elsewhere-profiles | lib/plugins.js | load | function load(dirPath) {
findFiles(dirPath, function(filePath){
collection.push( require(filePath) );
})
function findFiles(dirPath, callback){
fs.readdir(dirPath, function(err, files) {
files.forEach(function(file){
fs.stat(dirPath + '/' + file, function(err, stats) {
if(stats.isFile()) {
callback(dirPath + '/' + file);
}
if(stats.isDirectory()) {
getDirectoryFiles(dirPath + '/' + file, callback);
}
});
});
});
}
} | javascript | function load(dirPath) {
findFiles(dirPath, function(filePath){
collection.push( require(filePath) );
})
function findFiles(dirPath, callback){
fs.readdir(dirPath, function(err, files) {
files.forEach(function(file){
fs.stat(dirPath + '/' + file, function(err, stats) {
if(stats.isFile()) {
callback(dirPath + '/' + file);
}
if(stats.isDirectory()) {
getDirectoryFiles(dirPath + '/' + file, callback);
}
});
});
});
}
} | [
"function",
"load",
"(",
"dirPath",
")",
"{",
"findFiles",
"(",
"dirPath",
",",
"function",
"(",
"filePath",
")",
"{",
"collection",
".",
"push",
"(",
"require",
"(",
"filePath",
")",
")",
";",
"}",
")",
"function",
"findFiles",
"(",
"dirPath",
",",
"c... | load any file that is found in the plugins directory | [
"load",
"any",
"file",
"that",
"is",
"found",
"in",
"the",
"plugins",
"directory"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/plugins.js#L7-L27 |
35,298 | glennjones/elsewhere-profiles | lib/plugins.js | add | function add(interface){
var i = arr.collection,
found = false;
while (i--) {
if(interface.name === collection[i].name){
found = true;
}
}
if(!found){ collection.push( interface ) };
} | javascript | function add(interface){
var i = arr.collection,
found = false;
while (i--) {
if(interface.name === collection[i].name){
found = true;
}
}
if(!found){ collection.push( interface ) };
} | [
"function",
"add",
"(",
"interface",
")",
"{",
"var",
"i",
"=",
"arr",
".",
"collection",
",",
"found",
"=",
"false",
";",
"while",
"(",
"i",
"--",
")",
"{",
"if",
"(",
"interface",
".",
"name",
"===",
"collection",
"[",
"i",
"]",
".",
"name",
")... | add an plugin directly | [
"add",
"an",
"plugin",
"directly"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/plugins.js#L30-L39 |
35,299 | matteodelabre/midijs | lib/file/parser/track.js | parseTrack | function parseTrack(cursor) {
var chunk, events = [],
result, runningStatus = null;
chunk = parseChunk('MTrk', cursor);
while (!chunk.eof()) {
result = parseEvent(chunk, runningStatus);
runningStatus = result.runningStatus;
events.push(result.event);
}
return new Track(events);
} | javascript | function parseTrack(cursor) {
var chunk, events = [],
result, runningStatus = null;
chunk = parseChunk('MTrk', cursor);
while (!chunk.eof()) {
result = parseEvent(chunk, runningStatus);
runningStatus = result.runningStatus;
events.push(result.event);
}
return new Track(events);
} | [
"function",
"parseTrack",
"(",
"cursor",
")",
"{",
"var",
"chunk",
",",
"events",
"=",
"[",
"]",
",",
"result",
",",
"runningStatus",
"=",
"null",
";",
"chunk",
"=",
"parseChunk",
"(",
"'MTrk'",
",",
"cursor",
")",
";",
"while",
"(",
"!",
"chunk",
".... | Parse a MIDI track chunk
@param {module:buffercursor} cursor Buffer to parse
@return {module:midijs/lib/file/track~Track} Parsed track | [
"Parse",
"a",
"MIDI",
"track",
"chunk"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/track.js#L13-L27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.