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
partition
stringclasses
1 value
tritech/node-icalendar
lib/rrule.js
byday
function byday(rules, dt, after) { if(!rules || !rules.length) return dt; // Generate a list of candiDATES. (HA!) var candidates = rules.map(function(rule) { // Align on the correct day of the week... var days = rule[1]-wkday(dt); if(days < 0) days += 7; var newdt = add_d(new Date(dt), days); if(rule[0] > 0) { var wk = 0 | ((d(newdt) - 1) / 7) + 1; if(wk > rule[0]) return null; add_d(newdt, (rule[0] - wk) * 7); } else if(rule[0] < 0) { // Find all the matching days in the month... var dt2 = new Date(newdt); var days = []; while(m(dt2) === m(newdt)) { days.push(d(dt2)); add_d(dt2, 7); } // Then grab the nth from the end... set_d(newdt, days.reverse()[(-rule[0])-1]); } // Ignore if it's a past date... if (newdt.valueOf() <= after.valueOf()) return null; return newdt; }); // Select the date occurring next... var newdt = sort_dates(candidates).shift(); return newdt || dt; }
javascript
function byday(rules, dt, after) { if(!rules || !rules.length) return dt; // Generate a list of candiDATES. (HA!) var candidates = rules.map(function(rule) { // Align on the correct day of the week... var days = rule[1]-wkday(dt); if(days < 0) days += 7; var newdt = add_d(new Date(dt), days); if(rule[0] > 0) { var wk = 0 | ((d(newdt) - 1) / 7) + 1; if(wk > rule[0]) return null; add_d(newdt, (rule[0] - wk) * 7); } else if(rule[0] < 0) { // Find all the matching days in the month... var dt2 = new Date(newdt); var days = []; while(m(dt2) === m(newdt)) { days.push(d(dt2)); add_d(dt2, 7); } // Then grab the nth from the end... set_d(newdt, days.reverse()[(-rule[0])-1]); } // Ignore if it's a past date... if (newdt.valueOf() <= after.valueOf()) return null; return newdt; }); // Select the date occurring next... var newdt = sort_dates(candidates).shift(); return newdt || dt; }
[ "function", "byday", "(", "rules", ",", "dt", ",", "after", ")", "{", "if", "(", "!", "rules", "||", "!", "rules", ".", "length", ")", "return", "dt", ";", "var", "candidates", "=", "rules", ".", "map", "(", "function", "(", "rule", ")", "{", "var", "days", "=", "rule", "[", "1", "]", "-", "wkday", "(", "dt", ")", ";", "if", "(", "days", "<", "0", ")", "days", "+=", "7", ";", "var", "newdt", "=", "add_d", "(", "new", "Date", "(", "dt", ")", ",", "days", ")", ";", "if", "(", "rule", "[", "0", "]", ">", "0", ")", "{", "var", "wk", "=", "0", "|", "(", "(", "d", "(", "newdt", ")", "-", "1", ")", "/", "7", ")", "+", "1", ";", "if", "(", "wk", ">", "rule", "[", "0", "]", ")", "return", "null", ";", "add_d", "(", "newdt", ",", "(", "rule", "[", "0", "]", "-", "wk", ")", "*", "7", ")", ";", "}", "else", "if", "(", "rule", "[", "0", "]", "<", "0", ")", "{", "var", "dt2", "=", "new", "Date", "(", "newdt", ")", ";", "var", "days", "=", "[", "]", ";", "while", "(", "m", "(", "dt2", ")", "===", "m", "(", "newdt", ")", ")", "{", "days", ".", "push", "(", "d", "(", "dt2", ")", ")", ";", "add_d", "(", "dt2", ",", "7", ")", ";", "}", "set_d", "(", "newdt", ",", "days", ".", "reverse", "(", ")", "[", "(", "-", "rule", "[", "0", "]", ")", "-", "1", "]", ")", ";", "}", "if", "(", "newdt", ".", "valueOf", "(", ")", "<=", "after", ".", "valueOf", "(", ")", ")", "return", "null", ";", "return", "newdt", ";", "}", ")", ";", "var", "newdt", "=", "sort_dates", "(", "candidates", ")", ".", "shift", "(", ")", ";", "return", "newdt", "||", "dt", ";", "}" ]
Advance to the next day that satisfies the byday rule...
[ "Advance", "to", "the", "next", "day", "that", "satisfies", "the", "byday", "rule", "..." ]
afe4df6ffcf3ab03f2a854c25c50b1420cf5b4f6
https://github.com/tritech/node-icalendar/blob/afe4df6ffcf3ab03f2a854c25c50b1420cf5b4f6/lib/rrule.js#L540-L578
train
tritech/node-icalendar
spec/icalendar-spec.js
toStr
function toStr(next) { var stream = new Writable(); var str = ""; stream.write = function(chunk) { str += (chunk); }; stream.end = function() { next(str); }; return stream; }
javascript
function toStr(next) { var stream = new Writable(); var str = ""; stream.write = function(chunk) { str += (chunk); }; stream.end = function() { next(str); }; return stream; }
[ "function", "toStr", "(", "next", ")", "{", "var", "stream", "=", "new", "Writable", "(", ")", ";", "var", "str", "=", "\"\"", ";", "stream", ".", "write", "=", "function", "(", "chunk", ")", "{", "str", "+=", "(", "chunk", ")", ";", "}", ";", "stream", ".", "end", "=", "function", "(", ")", "{", "next", "(", "str", ")", ";", "}", ";", "return", "stream", ";", "}" ]
fake Writable stream to collect the data into a string
[ "fake", "Writable", "stream", "to", "collect", "the", "data", "into", "a", "string" ]
afe4df6ffcf3ab03f2a854c25c50b1420cf5b4f6
https://github.com/tritech/node-icalendar/blob/afe4df6ffcf3ab03f2a854c25c50b1420cf5b4f6/spec/icalendar-spec.js#L24-L34
train
jonschlinkert/update-copyright
index.js
updateYear
function updateYear(context) { return context.dateRange ? utils.updateYear(context.dateRange, String(utils.year())) : utils.year(); }
javascript
function updateYear(context) { return context.dateRange ? utils.updateYear(context.dateRange, String(utils.year())) : utils.year(); }
[ "function", "updateYear", "(", "context", ")", "{", "return", "context", ".", "dateRange", "?", "utils", ".", "updateYear", "(", "context", ".", "dateRange", ",", "String", "(", "utils", ".", "year", "(", ")", ")", ")", ":", "utils", ".", "year", "(", ")", ";", "}" ]
Parse the copyright statement and update the year or year range. @param {Object} `context` @return {String}
[ "Parse", "the", "copyright", "statement", "and", "update", "the", "year", "or", "year", "range", "." ]
5e8197a906a13c4400d777dc982b55216a31aa88
https://github.com/jonschlinkert/update-copyright/blob/5e8197a906a13c4400d777dc982b55216a31aa88/index.js#L37-L41
train
jonschlinkert/update-copyright
index.js
updateCopyright
function updateCopyright(str, context, options) { if (typeof str !== 'string') { options = context; context = str; str = null; } var opts = utils.merge({template: template, copyright: ''}, options); var pkg = opts.pkg || utils.loadPkg.sync(process.cwd()); var engine = new utils.Engine(opts); // create the template context from defaults, package.json, // context from parsing the original statement, and options. var ctx = utils.merge({}, defaults, pkg, context, opts); ctx.authors = ctx.author = author(ctx, pkg, options); ctx.years = ctx.year = updateYear(ctx); var statement = ctx.statement; // if no original statement was found, create one with the template if (typeof statement === 'undefined') { return engine.render(opts.template, ctx); } // necessary since the copyright regex doesn't match // the trailing dot. If it does later this is future-proof if (statement[statement.length - 1] !== '.') { var ch = statement + '.'; if (str.indexOf(ch) !== -1) { statement = ch; } } // create the new copyright statement var newStatement = engine.render(opts.template, ctx); if (str == null) { return newStatement; } // if the original string is no more than a copyright statement // just return the new one if (statement.trim() === str.trim() || opts.statementOnly === true) { return newStatement; } return str.replace(statement, newStatement); }
javascript
function updateCopyright(str, context, options) { if (typeof str !== 'string') { options = context; context = str; str = null; } var opts = utils.merge({template: template, copyright: ''}, options); var pkg = opts.pkg || utils.loadPkg.sync(process.cwd()); var engine = new utils.Engine(opts); // create the template context from defaults, package.json, // context from parsing the original statement, and options. var ctx = utils.merge({}, defaults, pkg, context, opts); ctx.authors = ctx.author = author(ctx, pkg, options); ctx.years = ctx.year = updateYear(ctx); var statement = ctx.statement; // if no original statement was found, create one with the template if (typeof statement === 'undefined') { return engine.render(opts.template, ctx); } // necessary since the copyright regex doesn't match // the trailing dot. If it does later this is future-proof if (statement[statement.length - 1] !== '.') { var ch = statement + '.'; if (str.indexOf(ch) !== -1) { statement = ch; } } // create the new copyright statement var newStatement = engine.render(opts.template, ctx); if (str == null) { return newStatement; } // if the original string is no more than a copyright statement // just return the new one if (statement.trim() === str.trim() || opts.statementOnly === true) { return newStatement; } return str.replace(statement, newStatement); }
[ "function", "updateCopyright", "(", "str", ",", "context", ",", "options", ")", "{", "if", "(", "typeof", "str", "!==", "'string'", ")", "{", "options", "=", "context", ";", "context", "=", "str", ";", "str", "=", "null", ";", "}", "var", "opts", "=", "utils", ".", "merge", "(", "{", "template", ":", "template", ",", "copyright", ":", "''", "}", ",", "options", ")", ";", "var", "pkg", "=", "opts", ".", "pkg", "||", "utils", ".", "loadPkg", ".", "sync", "(", "process", ".", "cwd", "(", ")", ")", ";", "var", "engine", "=", "new", "utils", ".", "Engine", "(", "opts", ")", ";", "var", "ctx", "=", "utils", ".", "merge", "(", "{", "}", ",", "defaults", ",", "pkg", ",", "context", ",", "opts", ")", ";", "ctx", ".", "authors", "=", "ctx", ".", "author", "=", "author", "(", "ctx", ",", "pkg", ",", "options", ")", ";", "ctx", ".", "years", "=", "ctx", ".", "year", "=", "updateYear", "(", "ctx", ")", ";", "var", "statement", "=", "ctx", ".", "statement", ";", "if", "(", "typeof", "statement", "===", "'undefined'", ")", "{", "return", "engine", ".", "render", "(", "opts", ".", "template", ",", "ctx", ")", ";", "}", "if", "(", "statement", "[", "statement", ".", "length", "-", "1", "]", "!==", "'.'", ")", "{", "var", "ch", "=", "statement", "+", "'.'", ";", "if", "(", "str", ".", "indexOf", "(", "ch", ")", "!==", "-", "1", ")", "{", "statement", "=", "ch", ";", "}", "}", "var", "newStatement", "=", "engine", ".", "render", "(", "opts", ".", "template", ",", "ctx", ")", ";", "if", "(", "str", "==", "null", ")", "{", "return", "newStatement", ";", "}", "if", "(", "statement", ".", "trim", "(", ")", "===", "str", ".", "trim", "(", ")", "||", "opts", ".", "statementOnly", "===", "true", ")", "{", "return", "newStatement", ";", "}", "return", "str", ".", "replace", "(", "statement", ",", "newStatement", ")", ";", "}" ]
Update an existing copyright statement, or create a new one if one isn't passed. @param {String} `str` String with copyright statement @param {Object} `context` Context to use for rendering the copyright template @param {Object} `options` @return {String}
[ "Update", "an", "existing", "copyright", "statement", "or", "create", "a", "new", "one", "if", "one", "isn", "t", "passed", "." ]
5e8197a906a13c4400d777dc982b55216a31aa88
https://github.com/jonschlinkert/update-copyright/blob/5e8197a906a13c4400d777dc982b55216a31aa88/index.js#L53-L98
train
cedx/gulp-php-minify
gulpfile.esm.js
_exec
function _exec(command, args = [], options = {}) { return new Promise((fulfill, reject) => spawn(normalize(command), args, {shell: true, stdio: 'inherit', ...options}) .on('close', code => code ? reject(new Error(`${command}: ${code}`)) : fulfill()) ); }
javascript
function _exec(command, args = [], options = {}) { return new Promise((fulfill, reject) => spawn(normalize(command), args, {shell: true, stdio: 'inherit', ...options}) .on('close', code => code ? reject(new Error(`${command}: ${code}`)) : fulfill()) ); }
[ "function", "_exec", "(", "command", ",", "args", "=", "[", "]", ",", "options", "=", "{", "}", ")", "{", "return", "new", "Promise", "(", "(", "fulfill", ",", "reject", ")", "=>", "spawn", "(", "normalize", "(", "command", ")", ",", "args", ",", "{", "shell", ":", "true", ",", "stdio", ":", "'inherit'", ",", "...", "options", "}", ")", ".", "on", "(", "'close'", ",", "code", "=>", "code", "?", "reject", "(", "new", "Error", "(", "`", "${", "command", "}", "${", "code", "}", "`", ")", ")", ":", "fulfill", "(", ")", ")", ")", ";", "}" ]
Spawns a new process using the specified command. @param {string} command The command to run. @param {string[]} [args] The command arguments. @param {SpawnOptions} [options] The settings to customize how the process is spawned. @return {Promise<void>} Completes when the command is finally terminated.
[ "Spawns", "a", "new", "process", "using", "the", "specified", "command", "." ]
0ca6499271a056a0951a41377f0c9eb4fae0c5e1
https://github.com/cedx/gulp-php-minify/blob/0ca6499271a056a0951a41377f0c9eb4fae0c5e1/gulpfile.esm.js#L70-L74
train
infinum/mobx-jsonapi-store
dist/NetworkUtils.js
create
function create(store, url, data, headers, options) { return exports.config.storeFetch({ data: data, method: 'POST', options: __assign({}, options, { headers: headers }), store: store, url: url, }); }
javascript
function create(store, url, data, headers, options) { return exports.config.storeFetch({ data: data, method: 'POST', options: __assign({}, options, { headers: headers }), store: store, url: url, }); }
[ "function", "create", "(", "store", ",", "url", ",", "data", ",", "headers", ",", "options", ")", "{", "return", "exports", ".", "config", ".", "storeFetch", "(", "{", "data", ":", "data", ",", "method", ":", "'POST'", ",", "options", ":", "__assign", "(", "{", "}", ",", "options", ",", "{", "headers", ":", "headers", "}", ")", ",", "store", ":", "store", ",", "url", ":", "url", ",", "}", ")", ";", "}" ]
API call used to create data on the server @export @param {Store} store Related Store @param {string} url API call URL @param {object} [data] Request body @param {IHeaders} [headers] Headers to be sent @param {IRequestOptions} [options] Server options @returns {Promise<Response>} Resolves with a Response object
[ "API", "call", "used", "to", "create", "data", "on", "the", "server" ]
0e30aecf6079af4379b35260ad4b83b169da8adb
https://github.com/infinum/mobx-jsonapi-store/blob/0e30aecf6079af4379b35260ad4b83b169da8adb/dist/NetworkUtils.js#L139-L147
train
infinum/mobx-jsonapi-store
dist/NetworkUtils.js
remove
function remove(store, url, headers, options) { return exports.config.storeFetch({ data: null, method: 'DELETE', options: __assign({}, options, { headers: headers }), store: store, url: url, }); }
javascript
function remove(store, url, headers, options) { return exports.config.storeFetch({ data: null, method: 'DELETE', options: __assign({}, options, { headers: headers }), store: store, url: url, }); }
[ "function", "remove", "(", "store", ",", "url", ",", "headers", ",", "options", ")", "{", "return", "exports", ".", "config", ".", "storeFetch", "(", "{", "data", ":", "null", ",", "method", ":", "'DELETE'", ",", "options", ":", "__assign", "(", "{", "}", ",", "options", ",", "{", "headers", ":", "headers", "}", ")", ",", "store", ":", "store", ",", "url", ":", "url", ",", "}", ")", ";", "}" ]
API call used to remove data from the server @export @param {Store} store Related Store @param {string} url API call URL @param {IHeaders} [headers] Headers to be sent @param {IRequestOptions} [options] Server options @returns {Promise<Response>} Resolves with a Response object
[ "API", "call", "used", "to", "remove", "data", "from", "the", "server" ]
0e30aecf6079af4379b35260ad4b83b169da8adb
https://github.com/infinum/mobx-jsonapi-store/blob/0e30aecf6079af4379b35260ad4b83b169da8adb/dist/NetworkUtils.js#L180-L188
train
infinum/mobx-jsonapi-store
dist/NetworkUtils.js
fetchLink
function fetchLink(link, store, requestHeaders, options) { if (link) { var href = typeof link === 'object' ? link.href : link; /* istanbul ignore else */ if (href) { return read(store, href, requestHeaders, options); } } return Promise.resolve(new Response_1.Response({ data: null }, store)); }
javascript
function fetchLink(link, store, requestHeaders, options) { if (link) { var href = typeof link === 'object' ? link.href : link; /* istanbul ignore else */ if (href) { return read(store, href, requestHeaders, options); } } return Promise.resolve(new Response_1.Response({ data: null }, store)); }
[ "function", "fetchLink", "(", "link", ",", "store", ",", "requestHeaders", ",", "options", ")", "{", "if", "(", "link", ")", "{", "var", "href", "=", "typeof", "link", "===", "'object'", "?", "link", ".", "href", ":", "link", ";", "if", "(", "href", ")", "{", "return", "read", "(", "store", ",", "href", ",", "requestHeaders", ",", "options", ")", ";", "}", "}", "return", "Promise", ".", "resolve", "(", "new", "Response_1", ".", "Response", "(", "{", "data", ":", "null", "}", ",", "store", ")", ")", ";", "}" ]
Fetch a link from the server @export @param {JsonApi.ILink} link Link URL or a link object @param {Store} store Store that will be used to save the response @param {IDictionary<string>} [requestHeaders] Request headers @param {IRequestOptions} [options] Server options @returns {Promise<LibResponse>} Response promise
[ "Fetch", "a", "link", "from", "the", "server" ]
0e30aecf6079af4379b35260ad4b83b169da8adb
https://github.com/infinum/mobx-jsonapi-store/blob/0e30aecf6079af4379b35260ad4b83b169da8adb/dist/NetworkUtils.js#L200-L209
train
infinum/mobx-jsonapi-store
dist/utils.js
mapItems
function mapItems(data, fn) { return data instanceof Array ? data.map(function (item) { return fn(item); }) : fn(data); }
javascript
function mapItems(data, fn) { return data instanceof Array ? data.map(function (item) { return fn(item); }) : fn(data); }
[ "function", "mapItems", "(", "data", ",", "fn", ")", "{", "return", "data", "instanceof", "Array", "?", "data", ".", "map", "(", "function", "(", "item", ")", "{", "return", "fn", "(", "item", ")", ";", "}", ")", ":", "fn", "(", "data", ")", ";", "}" ]
Iterate trough one item or array of items and call the defined function @export @template T @param {(object|Array<object>)} data - Data which needs to be iterated @param {Function} fn - Function that needs to be callse @returns {(T|Array<T>)} - The result of iteration
[ "Iterate", "trough", "one", "item", "or", "array", "of", "items", "and", "call", "the", "defined", "function" ]
0e30aecf6079af4379b35260ad4b83b169da8adb
https://github.com/infinum/mobx-jsonapi-store/blob/0e30aecf6079af4379b35260ad4b83b169da8adb/dist/utils.js#L27-L29
train
infinum/mobx-jsonapi-store
dist/utils.js
flattenRecord
function flattenRecord(record) { var data = { __internal: { id: record.id, type: record.type, }, }; objectForEach(record.attributes, function (key) { data[key] = record.attributes[key]; }); objectForEach(record.relationships, function (key) { var rel = record.relationships[key]; if (rel.meta) { data[key + "Meta"] = rel.meta; } if (rel.links) { data.__internal.relationships = data.__internal.relationships || {}; data.__internal.relationships[key] = rel.links; } }); objectForEach(record.links, function (key) { /* istanbul ignore else */ if (record.links[key]) { data.__internal.links = data.__internal.links || {}; data.__internal.links[key] = record.links[key]; } }); objectForEach(record.meta, function (key) { /* istanbul ignore else */ if (record.meta[key] !== undefined) { data.__internal.meta = data.__internal.meta || {}; data.__internal.meta[key] = record.meta[key]; } }); return data; }
javascript
function flattenRecord(record) { var data = { __internal: { id: record.id, type: record.type, }, }; objectForEach(record.attributes, function (key) { data[key] = record.attributes[key]; }); objectForEach(record.relationships, function (key) { var rel = record.relationships[key]; if (rel.meta) { data[key + "Meta"] = rel.meta; } if (rel.links) { data.__internal.relationships = data.__internal.relationships || {}; data.__internal.relationships[key] = rel.links; } }); objectForEach(record.links, function (key) { /* istanbul ignore else */ if (record.links[key]) { data.__internal.links = data.__internal.links || {}; data.__internal.links[key] = record.links[key]; } }); objectForEach(record.meta, function (key) { /* istanbul ignore else */ if (record.meta[key] !== undefined) { data.__internal.meta = data.__internal.meta || {}; data.__internal.meta[key] = record.meta[key]; } }); return data; }
[ "function", "flattenRecord", "(", "record", ")", "{", "var", "data", "=", "{", "__internal", ":", "{", "id", ":", "record", ".", "id", ",", "type", ":", "record", ".", "type", ",", "}", ",", "}", ";", "objectForEach", "(", "record", ".", "attributes", ",", "function", "(", "key", ")", "{", "data", "[", "key", "]", "=", "record", ".", "attributes", "[", "key", "]", ";", "}", ")", ";", "objectForEach", "(", "record", ".", "relationships", ",", "function", "(", "key", ")", "{", "var", "rel", "=", "record", ".", "relationships", "[", "key", "]", ";", "if", "(", "rel", ".", "meta", ")", "{", "data", "[", "key", "+", "\"Meta\"", "]", "=", "rel", ".", "meta", ";", "}", "if", "(", "rel", ".", "links", ")", "{", "data", ".", "__internal", ".", "relationships", "=", "data", ".", "__internal", ".", "relationships", "||", "{", "}", ";", "data", ".", "__internal", ".", "relationships", "[", "key", "]", "=", "rel", ".", "links", ";", "}", "}", ")", ";", "objectForEach", "(", "record", ".", "links", ",", "function", "(", "key", ")", "{", "if", "(", "record", ".", "links", "[", "key", "]", ")", "{", "data", ".", "__internal", ".", "links", "=", "data", ".", "__internal", ".", "links", "||", "{", "}", ";", "data", ".", "__internal", ".", "links", "[", "key", "]", "=", "record", ".", "links", "[", "key", "]", ";", "}", "}", ")", ";", "objectForEach", "(", "record", ".", "meta", ",", "function", "(", "key", ")", "{", "if", "(", "record", ".", "meta", "[", "key", "]", "!==", "undefined", ")", "{", "data", ".", "__internal", ".", "meta", "=", "data", ".", "__internal", ".", "meta", "||", "{", "}", ";", "data", ".", "__internal", ".", "meta", "[", "key", "]", "=", "record", ".", "meta", "[", "key", "]", ";", "}", "}", ")", ";", "return", "data", ";", "}" ]
Flatten the JSON API record so it can be inserted into the model @export @param {IJsonApiRecord} record - original JSON API record @returns {IDictionary<any>} - Flattened object
[ "Flatten", "the", "JSON", "API", "record", "so", "it", "can", "be", "inserted", "into", "the", "model" ]
0e30aecf6079af4379b35260ad4b83b169da8adb
https://github.com/infinum/mobx-jsonapi-store/blob/0e30aecf6079af4379b35260ad4b83b169da8adb/dist/utils.js#L38-L73
train
infinum/mobx-jsonapi-store
dist/utils.js
keys
function keys(obj) { var keyList = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keyList.push(key); } } return keyList; }
javascript
function keys(obj) { var keyList = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keyList.push(key); } } return keyList; }
[ "function", "keys", "(", "obj", ")", "{", "var", "keyList", "=", "[", "]", ";", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "keyList", ".", "push", "(", "key", ")", ";", "}", "}", "return", "keyList", ";", "}" ]
Get all object keys @export @param {object} obj Object to process @returns {Array<string>} List of object keys
[ "Get", "all", "object", "keys" ]
0e30aecf6079af4379b35260ad4b83b169da8adb
https://github.com/infinum/mobx-jsonapi-store/blob/0e30aecf6079af4379b35260ad4b83b169da8adb/dist/utils.js#L128-L136
train
lightsofapollo/superagent-promise
index.js
wrap
function wrap(superagent, Promise) { /** * Request object similar to superagent.Request, but with end() returning * a promise. */ function PromiseRequest() { superagent.Request.apply(this, arguments); } // Inherit form superagent.Request PromiseRequest.prototype = Object.create(superagent.Request.prototype); /** Send request and get a promise that `end` was emitted */ PromiseRequest.prototype.end = function(cb) { var _end = superagent.Request.prototype.end; var self = this; return new Promise(function(accept, reject) { _end.call(self, function(err, response) { if (cb) { cb(err, response); } if (err) { err.response = response; reject(err); } else { accept(response); } }); }); }; /** Provide a more promise-y interface */ PromiseRequest.prototype.then = function(resolve, reject) { var _end = superagent.Request.prototype.end; var self = this; return new Promise(function(accept, reject) { _end.call(self, function(err, response) { if (err) { err.response = response; reject(err); } else { accept(response); } }); }).then(resolve, reject); }; /** * Request builder with same interface as superagent. * It is convenient to import this as `request` in place of superagent. */ var request = function(method, url) { return new PromiseRequest(method, url); }; /** Helper for making an options request */ request.options = function(url) { return request('OPTIONS', url); } /** Helper for making a head request */ request.head = function(url, data) { var req = request('HEAD', url); if (data) { req.send(data); } return req; }; /** Helper for making a get request */ request.get = function(url, data) { var req = request('GET', url); if (data) { req.query(data); } return req; }; /** Helper for making a post request */ request.post = function(url, data) { var req = request('POST', url); if (data) { req.send(data); } return req; }; /** Helper for making a put request */ request.put = function(url, data) { var req = request('PUT', url); if (data) { req.send(data); } return req; }; /** Helper for making a patch request */ request.patch = function(url, data) { var req = request('PATCH', url); if (data) { req.send(data); } return req; }; /** Helper for making a delete request */ request.del = function(url, data) { var req = request('DELETE', url); if (data) { req.send(data); } return req; }; // Export the request builder return request; }
javascript
function wrap(superagent, Promise) { /** * Request object similar to superagent.Request, but with end() returning * a promise. */ function PromiseRequest() { superagent.Request.apply(this, arguments); } // Inherit form superagent.Request PromiseRequest.prototype = Object.create(superagent.Request.prototype); /** Send request and get a promise that `end` was emitted */ PromiseRequest.prototype.end = function(cb) { var _end = superagent.Request.prototype.end; var self = this; return new Promise(function(accept, reject) { _end.call(self, function(err, response) { if (cb) { cb(err, response); } if (err) { err.response = response; reject(err); } else { accept(response); } }); }); }; /** Provide a more promise-y interface */ PromiseRequest.prototype.then = function(resolve, reject) { var _end = superagent.Request.prototype.end; var self = this; return new Promise(function(accept, reject) { _end.call(self, function(err, response) { if (err) { err.response = response; reject(err); } else { accept(response); } }); }).then(resolve, reject); }; /** * Request builder with same interface as superagent. * It is convenient to import this as `request` in place of superagent. */ var request = function(method, url) { return new PromiseRequest(method, url); }; /** Helper for making an options request */ request.options = function(url) { return request('OPTIONS', url); } /** Helper for making a head request */ request.head = function(url, data) { var req = request('HEAD', url); if (data) { req.send(data); } return req; }; /** Helper for making a get request */ request.get = function(url, data) { var req = request('GET', url); if (data) { req.query(data); } return req; }; /** Helper for making a post request */ request.post = function(url, data) { var req = request('POST', url); if (data) { req.send(data); } return req; }; /** Helper for making a put request */ request.put = function(url, data) { var req = request('PUT', url); if (data) { req.send(data); } return req; }; /** Helper for making a patch request */ request.patch = function(url, data) { var req = request('PATCH', url); if (data) { req.send(data); } return req; }; /** Helper for making a delete request */ request.del = function(url, data) { var req = request('DELETE', url); if (data) { req.send(data); } return req; }; // Export the request builder return request; }
[ "function", "wrap", "(", "superagent", ",", "Promise", ")", "{", "function", "PromiseRequest", "(", ")", "{", "superagent", ".", "Request", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "PromiseRequest", ".", "prototype", "=", "Object", ".", "create", "(", "superagent", ".", "Request", ".", "prototype", ")", ";", "PromiseRequest", ".", "prototype", ".", "end", "=", "function", "(", "cb", ")", "{", "var", "_end", "=", "superagent", ".", "Request", ".", "prototype", ".", "end", ";", "var", "self", "=", "this", ";", "return", "new", "Promise", "(", "function", "(", "accept", ",", "reject", ")", "{", "_end", ".", "call", "(", "self", ",", "function", "(", "err", ",", "response", ")", "{", "if", "(", "cb", ")", "{", "cb", "(", "err", ",", "response", ")", ";", "}", "if", "(", "err", ")", "{", "err", ".", "response", "=", "response", ";", "reject", "(", "err", ")", ";", "}", "else", "{", "accept", "(", "response", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ";", "PromiseRequest", ".", "prototype", ".", "then", "=", "function", "(", "resolve", ",", "reject", ")", "{", "var", "_end", "=", "superagent", ".", "Request", ".", "prototype", ".", "end", ";", "var", "self", "=", "this", ";", "return", "new", "Promise", "(", "function", "(", "accept", ",", "reject", ")", "{", "_end", ".", "call", "(", "self", ",", "function", "(", "err", ",", "response", ")", "{", "if", "(", "err", ")", "{", "err", ".", "response", "=", "response", ";", "reject", "(", "err", ")", ";", "}", "else", "{", "accept", "(", "response", ")", ";", "}", "}", ")", ";", "}", ")", ".", "then", "(", "resolve", ",", "reject", ")", ";", "}", ";", "var", "request", "=", "function", "(", "method", ",", "url", ")", "{", "return", "new", "PromiseRequest", "(", "method", ",", "url", ")", ";", "}", ";", "request", ".", "options", "=", "function", "(", "url", ")", "{", "return", "request", "(", "'OPTIONS'", ",", "url", ")", ";", "}", "request", ".", "head", "=", "function", "(", "url", ",", "data", ")", "{", "var", "req", "=", "request", "(", "'HEAD'", ",", "url", ")", ";", "if", "(", "data", ")", "{", "req", ".", "send", "(", "data", ")", ";", "}", "return", "req", ";", "}", ";", "request", ".", "get", "=", "function", "(", "url", ",", "data", ")", "{", "var", "req", "=", "request", "(", "'GET'", ",", "url", ")", ";", "if", "(", "data", ")", "{", "req", ".", "query", "(", "data", ")", ";", "}", "return", "req", ";", "}", ";", "request", ".", "post", "=", "function", "(", "url", ",", "data", ")", "{", "var", "req", "=", "request", "(", "'POST'", ",", "url", ")", ";", "if", "(", "data", ")", "{", "req", ".", "send", "(", "data", ")", ";", "}", "return", "req", ";", "}", ";", "request", ".", "put", "=", "function", "(", "url", ",", "data", ")", "{", "var", "req", "=", "request", "(", "'PUT'", ",", "url", ")", ";", "if", "(", "data", ")", "{", "req", ".", "send", "(", "data", ")", ";", "}", "return", "req", ";", "}", ";", "request", ".", "patch", "=", "function", "(", "url", ",", "data", ")", "{", "var", "req", "=", "request", "(", "'PATCH'", ",", "url", ")", ";", "if", "(", "data", ")", "{", "req", ".", "send", "(", "data", ")", ";", "}", "return", "req", ";", "}", ";", "request", ".", "del", "=", "function", "(", "url", ",", "data", ")", "{", "var", "req", "=", "request", "(", "'DELETE'", ",", "url", ")", ";", "if", "(", "data", ")", "{", "req", ".", "send", "(", "data", ")", ";", "}", "return", "req", ";", "}", ";", "return", "request", ";", "}" ]
Promise wrapper for superagent
[ "Promise", "wrapper", "for", "superagent" ]
2b83fec676e07af24fb9a62908cca060ae706511
https://github.com/lightsofapollo/superagent-promise/blob/2b83fec676e07af24fb9a62908cca060ae706511/index.js#L5-L124
train
opbeat/opbeat-node
lib/instrumentation/protocol.js
encode
function encode (samples, durations, cb) { var agent = samples.length > 0 ? samples[0]._agent : null var transactions = groupTransactions(samples, durations) var traces = [].concat.apply([], samples.map(function (trans) { return trans.traces })) var groups = groupTraces(traces) var raw = rawTransactions(samples) if (agent && agent.captureTraceStackTraces) { addStackTracesToTraceGroups(groups, traces, done) } else { process.nextTick(done) } function done () { cb({ // eslint-disable-line standard/no-callback-literal transactions: transactions, traces: { groups: groups, raw: raw } }) } }
javascript
function encode (samples, durations, cb) { var agent = samples.length > 0 ? samples[0]._agent : null var transactions = groupTransactions(samples, durations) var traces = [].concat.apply([], samples.map(function (trans) { return trans.traces })) var groups = groupTraces(traces) var raw = rawTransactions(samples) if (agent && agent.captureTraceStackTraces) { addStackTracesToTraceGroups(groups, traces, done) } else { process.nextTick(done) } function done () { cb({ // eslint-disable-line standard/no-callback-literal transactions: transactions, traces: { groups: groups, raw: raw } }) } }
[ "function", "encode", "(", "samples", ",", "durations", ",", "cb", ")", "{", "var", "agent", "=", "samples", ".", "length", ">", "0", "?", "samples", "[", "0", "]", ".", "_agent", ":", "null", "var", "transactions", "=", "groupTransactions", "(", "samples", ",", "durations", ")", "var", "traces", "=", "[", "]", ".", "concat", ".", "apply", "(", "[", "]", ",", "samples", ".", "map", "(", "function", "(", "trans", ")", "{", "return", "trans", ".", "traces", "}", ")", ")", "var", "groups", "=", "groupTraces", "(", "traces", ")", "var", "raw", "=", "rawTransactions", "(", "samples", ")", "if", "(", "agent", "&&", "agent", ".", "captureTraceStackTraces", ")", "{", "addStackTracesToTraceGroups", "(", "groups", ",", "traces", ",", "done", ")", "}", "else", "{", "process", ".", "nextTick", "(", "done", ")", "}", "function", "done", "(", ")", "{", "cb", "(", "{", "transactions", ":", "transactions", ",", "traces", ":", "{", "groups", ":", "groups", ",", "raw", ":", "raw", "}", "}", ")", "}", "}" ]
Encodes recorded transactions into a format expected by the Opbeat intake API. samples: An array containing objects of type Transaction. It's expected that each Transaction have a unique name within a 15ms window based on its duration. durations: An object whos keys are generated by `transactionGroupingKey`. Each value is an array of floats representing the duration in milliseconds of each recorded Transaction that belongs to that key. cb: A callback which will be called with the encoded data.
[ "Encodes", "recorded", "transactions", "into", "a", "format", "expected", "by", "the", "Opbeat", "intake", "API", "." ]
09c99083d067fe8084a311f69a9655c1e850dbe2
https://github.com/opbeat/opbeat-node/blob/09c99083d067fe8084a311f69a9655c1e850dbe2/lib/instrumentation/protocol.js#L29-L53
train
opbeat/opbeat-node
lib/instrumentation/modules/ioredis.js
wrapInitPromise
function wrapInitPromise (original) { return function wrappedInitPromise () { var command = this var cb = this.callback if (typeof cb === 'function') { this.callback = agent._instrumentation.bindFunction(function wrappedCallback () { var trace = command.__obTrace if (trace && !trace.ended) trace.end() return cb.apply(this, arguments) }) } return original.apply(this, arguments) } }
javascript
function wrapInitPromise (original) { return function wrappedInitPromise () { var command = this var cb = this.callback if (typeof cb === 'function') { this.callback = agent._instrumentation.bindFunction(function wrappedCallback () { var trace = command.__obTrace if (trace && !trace.ended) trace.end() return cb.apply(this, arguments) }) } return original.apply(this, arguments) } }
[ "function", "wrapInitPromise", "(", "original", ")", "{", "return", "function", "wrappedInitPromise", "(", ")", "{", "var", "command", "=", "this", "var", "cb", "=", "this", ".", "callback", "if", "(", "typeof", "cb", "===", "'function'", ")", "{", "this", ".", "callback", "=", "agent", ".", "_instrumentation", ".", "bindFunction", "(", "function", "wrappedCallback", "(", ")", "{", "var", "trace", "=", "command", ".", "__obTrace", "if", "(", "trace", "&&", "!", "trace", ".", "ended", ")", "trace", ".", "end", "(", ")", "return", "cb", ".", "apply", "(", "this", ",", "arguments", ")", "}", ")", "}", "return", "original", ".", "apply", "(", "this", ",", "arguments", ")", "}", "}" ]
wrap initPromise to allow us to get notified when the callback to a command is called. If we don't do this we will still get notified because we register a callback with command.promise.finally the wrappedSendCommand, but the finally call will not get fired until the tick after the command.callback have fired, so if the transaction is ended in the same tick as the call to command.callback, we'll lose the last trace as it hasn't yet ended.
[ "wrap", "initPromise", "to", "allow", "us", "to", "get", "notified", "when", "the", "callback", "to", "a", "command", "is", "called", ".", "If", "we", "don", "t", "do", "this", "we", "will", "still", "get", "notified", "because", "we", "register", "a", "callback", "with", "command", ".", "promise", ".", "finally", "the", "wrappedSendCommand", "but", "the", "finally", "call", "will", "not", "get", "fired", "until", "the", "tick", "after", "the", "command", ".", "callback", "have", "fired", "so", "if", "the", "transaction", "is", "ended", "in", "the", "same", "tick", "as", "the", "call", "to", "command", ".", "callback", "we", "ll", "lose", "the", "last", "trace", "as", "it", "hasn", "t", "yet", "ended", "." ]
09c99083d067fe8084a311f69a9655c1e850dbe2
https://github.com/opbeat/opbeat-node/blob/09c99083d067fe8084a311f69a9655c1e850dbe2/lib/instrumentation/modules/ioredis.js#L28-L43
train
stomita/node-salesforce
lib/repl.js
promisify
function promisify(repl) { var _eval = repl.eval; repl.eval = function(cmd, context, filename, callback) { _eval.call(repl, cmd, context, filename, function(err, res) { if (isPromiseLike(res)) { res.then(function(ret) { callback(null, ret); }, function(err) { callback(err); }); } else { callback(err, res); } }); }; return repl; }
javascript
function promisify(repl) { var _eval = repl.eval; repl.eval = function(cmd, context, filename, callback) { _eval.call(repl, cmd, context, filename, function(err, res) { if (isPromiseLike(res)) { res.then(function(ret) { callback(null, ret); }, function(err) { callback(err); }); } else { callback(err, res); } }); }; return repl; }
[ "function", "promisify", "(", "repl", ")", "{", "var", "_eval", "=", "repl", ".", "eval", ";", "repl", ".", "eval", "=", "function", "(", "cmd", ",", "context", ",", "filename", ",", "callback", ")", "{", "_eval", ".", "call", "(", "repl", ",", "cmd", ",", "context", ",", "filename", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "isPromiseLike", "(", "res", ")", ")", "{", "res", ".", "then", "(", "function", "(", "ret", ")", "{", "callback", "(", "null", ",", "ret", ")", ";", "}", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", ")", ";", "}", "else", "{", "callback", "(", "err", ",", "res", ")", ";", "}", "}", ")", ";", "}", ";", "return", "repl", ";", "}" ]
Intercept the evaled value when it is "promise", and resolve its value before sending back to REPL. @private
[ "Intercept", "the", "evaled", "value", "when", "it", "is", "promise", "and", "resolve", "its", "value", "before", "sending", "back", "to", "REPL", "." ]
3dec6f206e027f2331cc1ffb9037ac3b50996a3f
https://github.com/stomita/node-salesforce/blob/3dec6f206e027f2331cc1ffb9037ac3b50996a3f/lib/repl.js#L12-L28
train
stomita/node-salesforce
lib/repl.js
defineBuiltinVars
function defineBuiltinVars(context) { // define salesforce package root objects for (var key in sf) { if (sf.hasOwnProperty(key) && !global[key]) { context[key] = sf[key]; } } // expose salesforce package root as "$sf" in context. context.$sf = sf; // create default connection object var conn = new sf.Connection(); for (var prop in conn) { if (prop.indexOf('_') === 0) { // ignore private continue; } if (_.isFunction(conn[prop])) { context[prop] = _.bind(conn[prop], conn); } else if (_.isObject(conn[prop])) { defineProp(context, conn, prop); } } // expose default connection as "$conn" context.$conn = conn; }
javascript
function defineBuiltinVars(context) { // define salesforce package root objects for (var key in sf) { if (sf.hasOwnProperty(key) && !global[key]) { context[key] = sf[key]; } } // expose salesforce package root as "$sf" in context. context.$sf = sf; // create default connection object var conn = new sf.Connection(); for (var prop in conn) { if (prop.indexOf('_') === 0) { // ignore private continue; } if (_.isFunction(conn[prop])) { context[prop] = _.bind(conn[prop], conn); } else if (_.isObject(conn[prop])) { defineProp(context, conn, prop); } } // expose default connection as "$conn" context.$conn = conn; }
[ "function", "defineBuiltinVars", "(", "context", ")", "{", "for", "(", "var", "key", "in", "sf", ")", "{", "if", "(", "sf", ".", "hasOwnProperty", "(", "key", ")", "&&", "!", "global", "[", "key", "]", ")", "{", "context", "[", "key", "]", "=", "sf", "[", "key", "]", ";", "}", "}", "context", ".", "$sf", "=", "sf", ";", "var", "conn", "=", "new", "sf", ".", "Connection", "(", ")", ";", "for", "(", "var", "prop", "in", "conn", ")", "{", "if", "(", "prop", ".", "indexOf", "(", "'_'", ")", "===", "0", ")", "{", "continue", ";", "}", "if", "(", "_", ".", "isFunction", "(", "conn", "[", "prop", "]", ")", ")", "{", "context", "[", "prop", "]", "=", "_", ".", "bind", "(", "conn", "[", "prop", "]", ",", "conn", ")", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "conn", "[", "prop", "]", ")", ")", "{", "defineProp", "(", "context", ",", "conn", ",", "prop", ")", ";", "}", "}", "context", ".", "$conn", "=", "conn", ";", "}" ]
Map all node-salesforce object to REPL context @private
[ "Map", "all", "node", "-", "salesforce", "object", "to", "REPL", "context" ]
3dec6f206e027f2331cc1ffb9037ac3b50996a3f
https://github.com/stomita/node-salesforce/blob/3dec6f206e027f2331cc1ffb9037ac3b50996a3f/lib/repl.js#L54-L80
train
stomita/node-salesforce
lib/tooling.js
function(conn) { this._conn = conn; this._logger = conn._logger; var delegates = [ "query", "queryMore", "create", "insert", "retrieve", "update", "upsert", "del", "delete", "destroy", "describe", "describeGlobal", "sobject" ]; delegates.forEach(function(method) { this[method] = conn.constructor.prototype[method]; }, this); this.cache = new Cache(); var cacheOptions = { key: function(type) { return type ? "describe." + type : "describe"; } }; this.describe$ = this.cache.makeCacheable(this.describe, this, cacheOptions); this.describe = this.cache.makeResponseCacheable(this.describe, this, cacheOptions); this.describeSObject$ = this.describe$; this.describeSObject = this.describe; cacheOptions = { key: 'describeGlobal' }; this.describeGlobal$ = this.cache.makeCacheable(this.describeGlobal, this, cacheOptions); this.describeGlobal = this.cache.makeResponseCacheable(this.describeGlobal, this, cacheOptions); this.initialize(); }
javascript
function(conn) { this._conn = conn; this._logger = conn._logger; var delegates = [ "query", "queryMore", "create", "insert", "retrieve", "update", "upsert", "del", "delete", "destroy", "describe", "describeGlobal", "sobject" ]; delegates.forEach(function(method) { this[method] = conn.constructor.prototype[method]; }, this); this.cache = new Cache(); var cacheOptions = { key: function(type) { return type ? "describe." + type : "describe"; } }; this.describe$ = this.cache.makeCacheable(this.describe, this, cacheOptions); this.describe = this.cache.makeResponseCacheable(this.describe, this, cacheOptions); this.describeSObject$ = this.describe$; this.describeSObject = this.describe; cacheOptions = { key: 'describeGlobal' }; this.describeGlobal$ = this.cache.makeCacheable(this.describeGlobal, this, cacheOptions); this.describeGlobal = this.cache.makeResponseCacheable(this.describeGlobal, this, cacheOptions); this.initialize(); }
[ "function", "(", "conn", ")", "{", "this", ".", "_conn", "=", "conn", ";", "this", ".", "_logger", "=", "conn", ".", "_logger", ";", "var", "delegates", "=", "[", "\"query\"", ",", "\"queryMore\"", ",", "\"create\"", ",", "\"insert\"", ",", "\"retrieve\"", ",", "\"update\"", ",", "\"upsert\"", ",", "\"del\"", ",", "\"delete\"", ",", "\"destroy\"", ",", "\"describe\"", ",", "\"describeGlobal\"", ",", "\"sobject\"", "]", ";", "delegates", ".", "forEach", "(", "function", "(", "method", ")", "{", "this", "[", "method", "]", "=", "conn", ".", "constructor", ".", "prototype", "[", "method", "]", ";", "}", ",", "this", ")", ";", "this", ".", "cache", "=", "new", "Cache", "(", ")", ";", "var", "cacheOptions", "=", "{", "key", ":", "function", "(", "type", ")", "{", "return", "type", "?", "\"describe.\"", "+", "type", ":", "\"describe\"", ";", "}", "}", ";", "this", ".", "describe$", "=", "this", ".", "cache", ".", "makeCacheable", "(", "this", ".", "describe", ",", "this", ",", "cacheOptions", ")", ";", "this", ".", "describe", "=", "this", ".", "cache", ".", "makeResponseCacheable", "(", "this", ".", "describe", ",", "this", ",", "cacheOptions", ")", ";", "this", ".", "describeSObject$", "=", "this", ".", "describe$", ";", "this", ".", "describeSObject", "=", "this", ".", "describe", ";", "cacheOptions", "=", "{", "key", ":", "'describeGlobal'", "}", ";", "this", ".", "describeGlobal$", "=", "this", ".", "cache", ".", "makeCacheable", "(", "this", ".", "describeGlobal", ",", "this", ",", "cacheOptions", ")", ";", "this", ".", "describeGlobal", "=", "this", ".", "cache", ".", "makeResponseCacheable", "(", "this", ".", "describeGlobal", ",", "this", ",", "cacheOptions", ")", ";", "this", ".", "initialize", "(", ")", ";", "}" ]
API class for Tooling API call @class @param {Connection} conn - Connection
[ "API", "class", "for", "Tooling", "API", "call" ]
3dec6f206e027f2331cc1ffb9037ac3b50996a3f
https://github.com/stomita/node-salesforce/blob/3dec6f206e027f2331cc1ffb9037ac3b50996a3f/lib/tooling.js#L16-L53
train
stomita/node-salesforce
lib/record-stream.js
function() { source.removeListener('record', onRecord); dest.removeListener('drain', onDrain); source.removeListener('end', onEnd); source.removeListener('close', onClose); source.removeListener('error', onError); dest.removeListener('error', onError); source.removeListener('end', cleanup); source.removeListener('close', cleanup); dest.removeListener('end', cleanup); dest.removeListener('close', cleanup); }
javascript
function() { source.removeListener('record', onRecord); dest.removeListener('drain', onDrain); source.removeListener('end', onEnd); source.removeListener('close', onClose); source.removeListener('error', onError); dest.removeListener('error', onError); source.removeListener('end', cleanup); source.removeListener('close', cleanup); dest.removeListener('end', cleanup); dest.removeListener('close', cleanup); }
[ "function", "(", ")", "{", "source", ".", "removeListener", "(", "'record'", ",", "onRecord", ")", ";", "dest", ".", "removeListener", "(", "'drain'", ",", "onDrain", ")", ";", "source", ".", "removeListener", "(", "'end'", ",", "onEnd", ")", ";", "source", ".", "removeListener", "(", "'close'", ",", "onClose", ")", ";", "source", ".", "removeListener", "(", "'error'", ",", "onError", ")", ";", "dest", ".", "removeListener", "(", "'error'", ",", "onError", ")", ";", "source", ".", "removeListener", "(", "'end'", ",", "cleanup", ")", ";", "source", ".", "removeListener", "(", "'close'", ",", "cleanup", ")", ";", "dest", ".", "removeListener", "(", "'end'", ",", "cleanup", ")", ";", "dest", ".", "removeListener", "(", "'close'", ",", "cleanup", ")", ";", "}" ]
remove all the event listeners that were added.
[ "remove", "all", "the", "event", "listeners", "that", "were", "added", "." ]
3dec6f206e027f2331cc1ffb9037ac3b50996a3f
https://github.com/stomita/node-salesforce/blob/3dec6f206e027f2331cc1ffb9037ac3b50996a3f/lib/record-stream.js#L141-L156
train
stomita/node-salesforce
lib/request.js
promisedRequest
function promisedRequest(params, callback) { var deferred = Promise.defer(); var req; var createRequest = function() { if (!req) { req = request(params, function(err, response) { if (err) { deferred.reject(err); } else { deferred.resolve(response); } }); } return req; }; return streamify(deferred.promise, createRequest).thenCall(callback); }
javascript
function promisedRequest(params, callback) { var deferred = Promise.defer(); var req; var createRequest = function() { if (!req) { req = request(params, function(err, response) { if (err) { deferred.reject(err); } else { deferred.resolve(response); } }); } return req; }; return streamify(deferred.promise, createRequest).thenCall(callback); }
[ "function", "promisedRequest", "(", "params", ",", "callback", ")", "{", "var", "deferred", "=", "Promise", ".", "defer", "(", ")", ";", "var", "req", ";", "var", "createRequest", "=", "function", "(", ")", "{", "if", "(", "!", "req", ")", "{", "req", "=", "request", "(", "params", ",", "function", "(", "err", ",", "response", ")", "{", "if", "(", "err", ")", "{", "deferred", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "deferred", ".", "resolve", "(", "response", ")", ";", "}", "}", ")", ";", "}", "return", "req", ";", "}", ";", "return", "streamify", "(", "deferred", ".", "promise", ",", "createRequest", ")", ".", "thenCall", "(", "callback", ")", ";", "}" ]
HTTP request method, returns promise instead of stream @private
[ "HTTP", "request", "method", "returns", "promise", "instead", "of", "stream" ]
3dec6f206e027f2331cc1ffb9037ac3b50996a3f
https://github.com/stomita/node-salesforce/blob/3dec6f206e027f2331cc1ffb9037ac3b50996a3f/lib/request.js#L10-L26
train
opbeat/opbeat-node
lib/parsers.js
setCulprit
function setCulprit (payload) { if (payload.culprit) return // skip if user provided a custom culprit var frames = payload.stacktrace.frames var filename = frames[0].filename var fnName = frames[0].function for (var n = 0; n < frames.length; n++) { if (frames[n].in_app) { filename = frames[n].filename fnName = frames[n].function break } } payload.culprit = filename ? fnName + ' (' + filename + ')' : fnName }
javascript
function setCulprit (payload) { if (payload.culprit) return // skip if user provided a custom culprit var frames = payload.stacktrace.frames var filename = frames[0].filename var fnName = frames[0].function for (var n = 0; n < frames.length; n++) { if (frames[n].in_app) { filename = frames[n].filename fnName = frames[n].function break } } payload.culprit = filename ? fnName + ' (' + filename + ')' : fnName }
[ "function", "setCulprit", "(", "payload", ")", "{", "if", "(", "payload", ".", "culprit", ")", "return", "var", "frames", "=", "payload", ".", "stacktrace", ".", "frames", "var", "filename", "=", "frames", "[", "0", "]", ".", "filename", "var", "fnName", "=", "frames", "[", "0", "]", ".", "function", "for", "(", "var", "n", "=", "0", ";", "n", "<", "frames", ".", "length", ";", "n", "++", ")", "{", "if", "(", "frames", "[", "n", "]", ".", "in_app", ")", "{", "filename", "=", "frames", "[", "n", "]", ".", "filename", "fnName", "=", "frames", "[", "n", "]", ".", "function", "break", "}", "}", "payload", ".", "culprit", "=", "filename", "?", "fnName", "+", "' ('", "+", "filename", "+", "')'", ":", "fnName", "}" ]
Default `culprit` to the top of the stack or the highest `in_app` frame if such exists
[ "Default", "culprit", "to", "the", "top", "of", "the", "stack", "or", "the", "highest", "in_app", "frame", "if", "such", "exists" ]
09c99083d067fe8084a311f69a9655c1e850dbe2
https://github.com/opbeat/opbeat-node/blob/09c99083d067fe8084a311f69a9655c1e850dbe2/lib/parsers.js#L193-L206
train
opbeat/opbeat-node
lib/request.js
capturePayload
function capturePayload (endpoint, payload) { var dumpfile = path.join(os.tmpdir(), 'opbeat-' + endpoint + '-' + Date.now() + '.json') fs.writeFile(dumpfile, JSON.stringify(payload), function (err) { if (err) console.log('could not capture intake payload: %s', err.message) else console.log('intake payload captured: %s', dumpfile) }) }
javascript
function capturePayload (endpoint, payload) { var dumpfile = path.join(os.tmpdir(), 'opbeat-' + endpoint + '-' + Date.now() + '.json') fs.writeFile(dumpfile, JSON.stringify(payload), function (err) { if (err) console.log('could not capture intake payload: %s', err.message) else console.log('intake payload captured: %s', dumpfile) }) }
[ "function", "capturePayload", "(", "endpoint", ",", "payload", ")", "{", "var", "dumpfile", "=", "path", ".", "join", "(", "os", ".", "tmpdir", "(", ")", ",", "'opbeat-'", "+", "endpoint", "+", "'-'", "+", "Date", ".", "now", "(", ")", "+", "'.json'", ")", "fs", ".", "writeFile", "(", "dumpfile", ",", "JSON", ".", "stringify", "(", "payload", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "console", ".", "log", "(", "'could not capture intake payload: %s'", ",", "err", ".", "message", ")", "else", "console", ".", "log", "(", "'intake payload captured: %s'", ",", "dumpfile", ")", "}", ")", "}" ]
Used only for debugging data sent to the intake API
[ "Used", "only", "for", "debugging", "data", "sent", "to", "the", "intake", "API" ]
09c99083d067fe8084a311f69a9655c1e850dbe2
https://github.com/opbeat/opbeat-node/blob/09c99083d067fe8084a311f69a9655c1e850dbe2/lib/request.js#L138-L144
train
Esri/terraformer-arcgis-parser
examples/terraformer-arcgis-fileparser.js
tryRead
function tryRead(fd, buff, offset, length) { return new Promise((resolve, reject) => { fs.read(fd, buff, offset, length, null, (err, bytesRead, buffer) => { if (err) return reject(err); const buffLen = buffer.length; offset += bytesRead; if (offset >= buffLen) return resolve(buff); if ((offset + length) >= buffLen) length = buffLen - offset; return resolve(); }); }) .then( (fullBuffer) => { return fullBuffer ? { data: fullBuffer, fd: fd } : tryRead(fd, buff, offset, length); }, (err) => { throw err; } ); }
javascript
function tryRead(fd, buff, offset, length) { return new Promise((resolve, reject) => { fs.read(fd, buff, offset, length, null, (err, bytesRead, buffer) => { if (err) return reject(err); const buffLen = buffer.length; offset += bytesRead; if (offset >= buffLen) return resolve(buff); if ((offset + length) >= buffLen) length = buffLen - offset; return resolve(); }); }) .then( (fullBuffer) => { return fullBuffer ? { data: fullBuffer, fd: fd } : tryRead(fd, buff, offset, length); }, (err) => { throw err; } ); }
[ "function", "tryRead", "(", "fd", ",", "buff", ",", "offset", ",", "length", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "read", "(", "fd", ",", "buff", ",", "offset", ",", "length", ",", "null", ",", "(", "err", ",", "bytesRead", ",", "buffer", ")", "=>", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "const", "buffLen", "=", "buffer", ".", "length", ";", "offset", "+=", "bytesRead", ";", "if", "(", "offset", ">=", "buffLen", ")", "return", "resolve", "(", "buff", ")", ";", "if", "(", "(", "offset", "+", "length", ")", ">=", "buffLen", ")", "length", "=", "buffLen", "-", "offset", ";", "return", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", "(", "fullBuffer", ")", "=>", "{", "return", "fullBuffer", "?", "{", "data", ":", "fullBuffer", ",", "fd", ":", "fd", "}", ":", "tryRead", "(", "fd", ",", "buff", ",", "offset", ",", "length", ")", ";", "}", ",", "(", "err", ")", "=>", "{", "throw", "err", ";", "}", ")", ";", "}" ]
Reads file by chunkSize at a time. Will resolve with the buffer if it's full, otherwise will resolve with nothing, indicating another read should happen.
[ "Reads", "file", "by", "chunkSize", "at", "a", "time", ".", "Will", "resolve", "with", "the", "buffer", "if", "it", "s", "full", "otherwise", "will", "resolve", "with", "nothing", "indicating", "another", "read", "should", "happen", "." ]
c7af3110f8219db6605a111844f0febb46cf8e9e
https://github.com/Esri/terraformer-arcgis-parser/blob/c7af3110f8219db6605a111844f0febb46cf8e9e/examples/terraformer-arcgis-fileparser.js#L58-L76
train
grow/airkit
modal/index.js
Modal
function Modal(config) { this.config = config; this.timers_ = []; this.scrollY = 0; this.initDom_(); var closeAttribute = 'data-' + this.config.className + '-x'; var closeClass = this.config.className + '-x'; var data = 'data-' + this.config.className + '-id'; var func = function(targetEl, e) { var modalId = targetEl.getAttribute(data); if (modalId) { e.preventDefault(); this.setActive_(true, modalId); } if (targetEl.classList.contains(closeClass) || targetEl.hasAttribute(closeAttribute)) { this.setActive_(false); } }.bind(this); events.addDelegatedListener(document, 'click', func); this.initStateFromHash_(); }
javascript
function Modal(config) { this.config = config; this.timers_ = []; this.scrollY = 0; this.initDom_(); var closeAttribute = 'data-' + this.config.className + '-x'; var closeClass = this.config.className + '-x'; var data = 'data-' + this.config.className + '-id'; var func = function(targetEl, e) { var modalId = targetEl.getAttribute(data); if (modalId) { e.preventDefault(); this.setActive_(true, modalId); } if (targetEl.classList.contains(closeClass) || targetEl.hasAttribute(closeAttribute)) { this.setActive_(false); } }.bind(this); events.addDelegatedListener(document, 'click', func); this.initStateFromHash_(); }
[ "function", "Modal", "(", "config", ")", "{", "this", ".", "config", "=", "config", ";", "this", ".", "timers_", "=", "[", "]", ";", "this", ".", "scrollY", "=", "0", ";", "this", ".", "initDom_", "(", ")", ";", "var", "closeAttribute", "=", "'data-'", "+", "this", ".", "config", ".", "className", "+", "'-x'", ";", "var", "closeClass", "=", "this", ".", "config", ".", "className", "+", "'-x'", ";", "var", "data", "=", "'data-'", "+", "this", ".", "config", ".", "className", "+", "'-id'", ";", "var", "func", "=", "function", "(", "targetEl", ",", "e", ")", "{", "var", "modalId", "=", "targetEl", ".", "getAttribute", "(", "data", ")", ";", "if", "(", "modalId", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "this", ".", "setActive_", "(", "true", ",", "modalId", ")", ";", "}", "if", "(", "targetEl", ".", "classList", ".", "contains", "(", "closeClass", ")", "||", "targetEl", ".", "hasAttribute", "(", "closeAttribute", ")", ")", "{", "this", ".", "setActive_", "(", "false", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ";", "events", ".", "addDelegatedListener", "(", "document", ",", "'click'", ",", "func", ")", ";", "this", ".", "initStateFromHash_", "(", ")", ";", "}" ]
Modal dialog. @constructor
[ "Modal", "dialog", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/modal/index.js#L30-L54
train
grow/airkit
modal/index.js
init
function init(opt_config) { if (modalInstance) { return; } var config = objects.clone(defaultConfig); if (opt_config) { objects.merge(config, opt_config); } modalInstance = new Modal(config); }
javascript
function init(opt_config) { if (modalInstance) { return; } var config = objects.clone(defaultConfig); if (opt_config) { objects.merge(config, opt_config); } modalInstance = new Modal(config); }
[ "function", "init", "(", "opt_config", ")", "{", "if", "(", "modalInstance", ")", "{", "return", ";", "}", "var", "config", "=", "objects", ".", "clone", "(", "defaultConfig", ")", ";", "if", "(", "opt_config", ")", "{", "objects", ".", "merge", "(", "config", ",", "opt_config", ")", ";", "}", "modalInstance", "=", "new", "Modal", "(", "config", ")", ";", "}" ]
Initializes a modal dialog singleton. @param {Object=} opt_config Config options.
[ "Initializes", "a", "modal", "dialog", "singleton", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/modal/index.js#L290-L300
train
grow/airkit
scrolldelegator/index.js
start
function start() { if (isStarted()) { return; } // Debounce the scroll event by executing the onScroll callback using a timed // interval. window.addEventListener('scroll', onScroll_, {'passive': true}); interval = window.setInterval(function() { if (scrolled) { for (var i = 0, delegate; delegate = delegates[i]; i++) { delegate.onScroll(); } scrolled = false; } }, 250); }
javascript
function start() { if (isStarted()) { return; } // Debounce the scroll event by executing the onScroll callback using a timed // interval. window.addEventListener('scroll', onScroll_, {'passive': true}); interval = window.setInterval(function() { if (scrolled) { for (var i = 0, delegate; delegate = delegates[i]; i++) { delegate.onScroll(); } scrolled = false; } }, 250); }
[ "function", "start", "(", ")", "{", "if", "(", "isStarted", "(", ")", ")", "{", "return", ";", "}", "window", ".", "addEventListener", "(", "'scroll'", ",", "onScroll_", ",", "{", "'passive'", ":", "true", "}", ")", ";", "interval", "=", "window", ".", "setInterval", "(", "function", "(", ")", "{", "if", "(", "scrolled", ")", "{", "for", "(", "var", "i", "=", "0", ",", "delegate", ";", "delegate", "=", "delegates", "[", "i", "]", ";", "i", "++", ")", "{", "delegate", ".", "onScroll", "(", ")", ";", "}", "scrolled", "=", "false", ";", "}", "}", ",", "250", ")", ";", "}" ]
Starts the scroll listener.
[ "Starts", "the", "scroll", "listener", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/scrolldelegator/index.js#L41-L57
train
grow/airkit
utils/uri.js
getParameterValue
function getParameterValue(key, opt_uri) { var uri = opt_uri || window.location.href; key = key.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]'); var regex = new RegExp('[\\?&]' + key + '=([^&#]*)'); var results = regex.exec(uri); var result = results === null ? null : results[1]; return result ? urlDecode_(result) : null; }
javascript
function getParameterValue(key, opt_uri) { var uri = opt_uri || window.location.href; key = key.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]'); var regex = new RegExp('[\\?&]' + key + '=([^&#]*)'); var results = regex.exec(uri); var result = results === null ? null : results[1]; return result ? urlDecode_(result) : null; }
[ "function", "getParameterValue", "(", "key", ",", "opt_uri", ")", "{", "var", "uri", "=", "opt_uri", "||", "window", ".", "location", ".", "href", ";", "key", "=", "key", ".", "replace", "(", "/", "[\\[]", "/", ",", "'\\\\\\['", ")", ".", "\\\\", "\\[", ";", "replace", "(", "/", "[\\]]", "/", ",", "'\\\\\\]'", ")", "\\\\", "\\]", "}" ]
Returns the value of a key in a query string.
[ "Returns", "the", "value", "of", "a", "key", "in", "a", "query", "string", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/utils/uri.js#L11-L18
train
grow/airkit
utils/uri.js
updateParamsFromUrl
function updateParamsFromUrl(config) { // If there is no query string in the URL, then there's nothing to do in this // function, so break early. if (!location.search) { return; } var c = objects.clone(UpdateParamsFromUrlDefaultConfig); objects.merge(c, config); var selector = c.selector; var attr = c.attr; var params = c.params; if (!params) { throw '`params` is required'; } var vals = {}; parseQueryString(location.search, function(key, value) { for (var i = 0; i < params.length; i++) { var param = params[i]; if (param instanceof RegExp) { if (key.match(param)) { vals[key] = value; } } else { if (param === key) { vals[key] = value; } } } }); var els = document.querySelectorAll(selector); for (var i = 0, el; el = els[i]; i++) { var href = el.getAttribute(attr); if (href && !href.startsWith('#')) { var url = new URL(el.getAttribute(attr), location.href); var map = parseQueryMap(url.search); // Optionally serialize the keys and values into a single key and value, // and rewrite the element's attribute with the new serialized query // string. This was built specifically to do things like pass `utm_*` // parameters into a `referrer` query string, for Google Play links, e.g. // `&referrer=utm_source%3DSOURCE`. // See https://developers.google.com/analytics/devguides/collection/android/v4/campaigns#google-play-url-builder var serializeIntoKey = el.getAttribute(c.serializeAttr); if (serializeIntoKey) { var serializedQueryString = encodeQueryMap(vals); map[serializeIntoKey] = serializedQueryString; } else { for (var key in vals) { map[key] = vals[key]; } } url.search = encodeQueryMap(map); el.setAttribute(attr, url.toString()); } } }
javascript
function updateParamsFromUrl(config) { // If there is no query string in the URL, then there's nothing to do in this // function, so break early. if (!location.search) { return; } var c = objects.clone(UpdateParamsFromUrlDefaultConfig); objects.merge(c, config); var selector = c.selector; var attr = c.attr; var params = c.params; if (!params) { throw '`params` is required'; } var vals = {}; parseQueryString(location.search, function(key, value) { for (var i = 0; i < params.length; i++) { var param = params[i]; if (param instanceof RegExp) { if (key.match(param)) { vals[key] = value; } } else { if (param === key) { vals[key] = value; } } } }); var els = document.querySelectorAll(selector); for (var i = 0, el; el = els[i]; i++) { var href = el.getAttribute(attr); if (href && !href.startsWith('#')) { var url = new URL(el.getAttribute(attr), location.href); var map = parseQueryMap(url.search); // Optionally serialize the keys and values into a single key and value, // and rewrite the element's attribute with the new serialized query // string. This was built specifically to do things like pass `utm_*` // parameters into a `referrer` query string, for Google Play links, e.g. // `&referrer=utm_source%3DSOURCE`. // See https://developers.google.com/analytics/devguides/collection/android/v4/campaigns#google-play-url-builder var serializeIntoKey = el.getAttribute(c.serializeAttr); if (serializeIntoKey) { var serializedQueryString = encodeQueryMap(vals); map[serializeIntoKey] = serializedQueryString; } else { for (var key in vals) { map[key] = vals[key]; } } url.search = encodeQueryMap(map); el.setAttribute(attr, url.toString()); } } }
[ "function", "updateParamsFromUrl", "(", "config", ")", "{", "if", "(", "!", "location", ".", "search", ")", "{", "return", ";", "}", "var", "c", "=", "objects", ".", "clone", "(", "UpdateParamsFromUrlDefaultConfig", ")", ";", "objects", ".", "merge", "(", "c", ",", "config", ")", ";", "var", "selector", "=", "c", ".", "selector", ";", "var", "attr", "=", "c", ".", "attr", ";", "var", "params", "=", "c", ".", "params", ";", "if", "(", "!", "params", ")", "{", "throw", "'`params` is required'", ";", "}", "var", "vals", "=", "{", "}", ";", "parseQueryString", "(", "location", ".", "search", ",", "function", "(", "key", ",", "value", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "params", ".", "length", ";", "i", "++", ")", "{", "var", "param", "=", "params", "[", "i", "]", ";", "if", "(", "param", "instanceof", "RegExp", ")", "{", "if", "(", "key", ".", "match", "(", "param", ")", ")", "{", "vals", "[", "key", "]", "=", "value", ";", "}", "}", "else", "{", "if", "(", "param", "===", "key", ")", "{", "vals", "[", "key", "]", "=", "value", ";", "}", "}", "}", "}", ")", ";", "var", "els", "=", "document", ".", "querySelectorAll", "(", "selector", ")", ";", "for", "(", "var", "i", "=", "0", ",", "el", ";", "el", "=", "els", "[", "i", "]", ";", "i", "++", ")", "{", "var", "href", "=", "el", ".", "getAttribute", "(", "attr", ")", ";", "if", "(", "href", "&&", "!", "href", ".", "startsWith", "(", "'#'", ")", ")", "{", "var", "url", "=", "new", "URL", "(", "el", ".", "getAttribute", "(", "attr", ")", ",", "location", ".", "href", ")", ";", "var", "map", "=", "parseQueryMap", "(", "url", ".", "search", ")", ";", "var", "serializeIntoKey", "=", "el", ".", "getAttribute", "(", "c", ".", "serializeAttr", ")", ";", "if", "(", "serializeIntoKey", ")", "{", "var", "serializedQueryString", "=", "encodeQueryMap", "(", "vals", ")", ";", "map", "[", "serializeIntoKey", "]", "=", "serializedQueryString", ";", "}", "else", "{", "for", "(", "var", "key", "in", "vals", ")", "{", "map", "[", "key", "]", "=", "vals", "[", "key", "]", ";", "}", "}", "url", ".", "search", "=", "encodeQueryMap", "(", "map", ")", ";", "el", ".", "setAttribute", "(", "attr", ",", "url", ".", "toString", "(", ")", ")", ";", "}", "}", "}" ]
Updates the URL attribute of elements with query params from the current URL. @param {Object} config Config object. Properties are: selector: CSS query selector of elements to act upon. attr: The element attribute to update. params: A list of URL params (string or RegExp) to set on the element attr from the current URL.
[ "Updates", "the", "URL", "attribute", "of", "elements", "with", "query", "params", "from", "the", "current", "URL", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/utils/uri.js#L37-L94
train
grow/airkit
utils/uri.js
parseQueryString
function parseQueryString(query, callback) { // Break early for empty string. if (!query) { return; } // Remove leading `?` so that callers can pass `location.search` directly to // this function. if (query.startsWith('?')) { query = query.slice(1); } var pairs = query.split('&'); for (var i = 0; i < pairs.length; i++) { var separatorIndex = pairs[i].indexOf('='); if (separatorIndex >= 0) { var key = pairs[i].substring(0, separatorIndex); var value = pairs[i].substring(separatorIndex + 1); callback(key, urlDecode_(value)); } else { // Treat "?foo" without the "=" as having an empty value. var key = pairs[i]; callback(key, ''); } } }
javascript
function parseQueryString(query, callback) { // Break early for empty string. if (!query) { return; } // Remove leading `?` so that callers can pass `location.search` directly to // this function. if (query.startsWith('?')) { query = query.slice(1); } var pairs = query.split('&'); for (var i = 0; i < pairs.length; i++) { var separatorIndex = pairs[i].indexOf('='); if (separatorIndex >= 0) { var key = pairs[i].substring(0, separatorIndex); var value = pairs[i].substring(separatorIndex + 1); callback(key, urlDecode_(value)); } else { // Treat "?foo" without the "=" as having an empty value. var key = pairs[i]; callback(key, ''); } } }
[ "function", "parseQueryString", "(", "query", ",", "callback", ")", "{", "if", "(", "!", "query", ")", "{", "return", ";", "}", "if", "(", "query", ".", "startsWith", "(", "'?'", ")", ")", "{", "query", "=", "query", ".", "slice", "(", "1", ")", ";", "}", "var", "pairs", "=", "query", ".", "split", "(", "'&'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "pairs", ".", "length", ";", "i", "++", ")", "{", "var", "separatorIndex", "=", "pairs", "[", "i", "]", ".", "indexOf", "(", "'='", ")", ";", "if", "(", "separatorIndex", ">=", "0", ")", "{", "var", "key", "=", "pairs", "[", "i", "]", ".", "substring", "(", "0", ",", "separatorIndex", ")", ";", "var", "value", "=", "pairs", "[", "i", "]", ".", "substring", "(", "separatorIndex", "+", "1", ")", ";", "callback", "(", "key", ",", "urlDecode_", "(", "value", ")", ")", ";", "}", "else", "{", "var", "key", "=", "pairs", "[", "i", "]", ";", "callback", "(", "key", ",", "''", ")", ";", "}", "}", "}" ]
Parses a query string and calls a callback function for every key-value pair found in the string. @param {string} query Query string (without the leading question mark). @param {function(string, string)} callback Function called for every key-value pair found in the query string.
[ "Parses", "a", "query", "string", "and", "calls", "a", "callback", "function", "for", "every", "key", "-", "value", "pair", "found", "in", "the", "string", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/utils/uri.js#L104-L128
train
grow/airkit
utils/uri.js
parseQueryMap
function parseQueryMap(query) { var map = {}; parseQueryString(query, function(key, value) { map[key] = value; }); return map; }
javascript
function parseQueryMap(query) { var map = {}; parseQueryString(query, function(key, value) { map[key] = value; }); return map; }
[ "function", "parseQueryMap", "(", "query", ")", "{", "var", "map", "=", "{", "}", ";", "parseQueryString", "(", "query", ",", "function", "(", "key", ",", "value", ")", "{", "map", "[", "key", "]", "=", "value", ";", "}", ")", ";", "return", "map", ";", "}" ]
Parses a query string and returns a map of key-value pairs. @param {string} query Query string (without the leading question mark). @return {Object} Map of key-value pairs.
[ "Parses", "a", "query", "string", "and", "returns", "a", "map", "of", "key", "-", "value", "pairs", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/utils/uri.js#L136-L142
train
grow/airkit
utils/uri.js
encodeQueryMap
function encodeQueryMap(map) { var params = []; for (var key in map) { var value = map[key]; params.push(key + '=' + urlEncode_(value)); } return params.join('&'); }
javascript
function encodeQueryMap(map) { var params = []; for (var key in map) { var value = map[key]; params.push(key + '=' + urlEncode_(value)); } return params.join('&'); }
[ "function", "encodeQueryMap", "(", "map", ")", "{", "var", "params", "=", "[", "]", ";", "for", "(", "var", "key", "in", "map", ")", "{", "var", "value", "=", "map", "[", "key", "]", ";", "params", ".", "push", "(", "key", "+", "'='", "+", "urlEncode_", "(", "value", ")", ")", ";", "}", "return", "params", ".", "join", "(", "'&'", ")", ";", "}" ]
Returns a URL-encoded query string from a map of key-value pairs. @param {Object} map Map of key-value pairs. @return {string} URL-encoded query string.
[ "Returns", "a", "URL", "-", "encoded", "query", "string", "from", "a", "map", "of", "key", "-", "value", "pairs", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/utils/uri.js#L150-L157
train
grow/airkit
dates/datetoggle.js
initStyle
function initStyle(opt_config) { var config = objects.clone(defaultConfig); if (opt_config) { objects.merge(config, opt_config); } var attrName = config.attributeName; var selector = '[' + attrName + ']'; var rules = {}; rules[selector] = {'display': 'none !important'}; ui.createStyle(rules); }
javascript
function initStyle(opt_config) { var config = objects.clone(defaultConfig); if (opt_config) { objects.merge(config, opt_config); } var attrName = config.attributeName; var selector = '[' + attrName + ']'; var rules = {}; rules[selector] = {'display': 'none !important'}; ui.createStyle(rules); }
[ "function", "initStyle", "(", "opt_config", ")", "{", "var", "config", "=", "objects", ".", "clone", "(", "defaultConfig", ")", ";", "if", "(", "opt_config", ")", "{", "objects", ".", "merge", "(", "config", ",", "opt_config", ")", ";", "}", "var", "attrName", "=", "config", ".", "attributeName", ";", "var", "selector", "=", "'['", "+", "attrName", "+", "']'", ";", "var", "rules", "=", "{", "}", ";", "rules", "[", "selector", "]", "=", "{", "'display'", ":", "'none !important'", "}", ";", "ui", ".", "createStyle", "(", "rules", ")", ";", "}" ]
Creates the styles used for toggling dates. Permits usage of datetoggle without needing to manually add styles to the page. You can optionally call this at the top of the page to avoid FOUC.
[ "Creates", "the", "styles", "used", "for", "toggling", "dates", ".", "Permits", "usage", "of", "datetoggle", "without", "needing", "to", "manually", "add", "styles", "to", "the", "page", ".", "You", "can", "optionally", "call", "this", "at", "the", "top", "of", "the", "page", "to", "avoid", "FOUC", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/dates/datetoggle.js#L63-L73
train
grow/airkit
utils/events.js
getDelegateFunction_
function getDelegateFunction_(listener) { if (!delegateFunctionMap.has(listener)) { var delegateFunction = function(e) { e = e || window.event; var target = e.target || e.srcElement; target = target.nodeType === 3 ? target.parentNode : target; do { listener(target, e); if (target.parentNode) { target = target.parentNode; } } while (target.parentNode); }; delegateFunctionMap.set(listener, delegateFunction); } return delegateFunctionMap.get(listener); }
javascript
function getDelegateFunction_(listener) { if (!delegateFunctionMap.has(listener)) { var delegateFunction = function(e) { e = e || window.event; var target = e.target || e.srcElement; target = target.nodeType === 3 ? target.parentNode : target; do { listener(target, e); if (target.parentNode) { target = target.parentNode; } } while (target.parentNode); }; delegateFunctionMap.set(listener, delegateFunction); } return delegateFunctionMap.get(listener); }
[ "function", "getDelegateFunction_", "(", "listener", ")", "{", "if", "(", "!", "delegateFunctionMap", ".", "has", "(", "listener", ")", ")", "{", "var", "delegateFunction", "=", "function", "(", "e", ")", "{", "e", "=", "e", "||", "window", ".", "event", ";", "var", "target", "=", "e", ".", "target", "||", "e", ".", "srcElement", ";", "target", "=", "target", ".", "nodeType", "===", "3", "?", "target", ".", "parentNode", ":", "target", ";", "do", "{", "listener", "(", "target", ",", "e", ")", ";", "if", "(", "target", ".", "parentNode", ")", "{", "target", "=", "target", ".", "parentNode", ";", "}", "}", "while", "(", "target", ".", "parentNode", ")", ";", "}", ";", "delegateFunctionMap", ".", "set", "(", "listener", ",", "delegateFunction", ")", ";", "}", "return", "delegateFunctionMap", ".", "get", "(", "listener", ")", ";", "}" ]
Creates the delegate function that gets added during addDelegatedListener. @param {Function} listener Listener function. @private
[ "Creates", "the", "delegate", "function", "that", "gets", "added", "during", "addDelegatedListener", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/utils/events.js#L38-L55
train
grow/airkit
utils/events.js
addDelegatedListener
function addDelegatedListener(el, type, listener) { incrementListenerCount(listener); return el.addEventListener(type, getDelegateFunction_(listener)); }
javascript
function addDelegatedListener(el, type, listener) { incrementListenerCount(listener); return el.addEventListener(type, getDelegateFunction_(listener)); }
[ "function", "addDelegatedListener", "(", "el", ",", "type", ",", "listener", ")", "{", "incrementListenerCount", "(", "listener", ")", ";", "return", "el", ".", "addEventListener", "(", "type", ",", "getDelegateFunction_", "(", "listener", ")", ")", ";", "}" ]
Adds an event listener to an element where the event target is discovered by moving up the clicked element's descendants. @param {Element} el Element to host the listener. @param {string} type Listener type. @param {Function} listener Listener function.
[ "Adds", "an", "event", "listener", "to", "an", "element", "where", "the", "event", "target", "is", "discovered", "by", "moving", "up", "the", "clicked", "element", "s", "descendants", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/utils/events.js#L64-L67
train
grow/airkit
utils/events.js
removeDelegatedListener
function removeDelegatedListener(el, type, listener) { var delegate = getDelegateFunction_(listener); decrementListenerCount(listener); if (getListenerCount(listener) <= 0) { delegateFunctionMap.delete(listener); } return el.removeEventListener(type, delegate); }
javascript
function removeDelegatedListener(el, type, listener) { var delegate = getDelegateFunction_(listener); decrementListenerCount(listener); if (getListenerCount(listener) <= 0) { delegateFunctionMap.delete(listener); } return el.removeEventListener(type, delegate); }
[ "function", "removeDelegatedListener", "(", "el", ",", "type", ",", "listener", ")", "{", "var", "delegate", "=", "getDelegateFunction_", "(", "listener", ")", ";", "decrementListenerCount", "(", "listener", ")", ";", "if", "(", "getListenerCount", "(", "listener", ")", "<=", "0", ")", "{", "delegateFunctionMap", ".", "delete", "(", "listener", ")", ";", "}", "return", "el", ".", "removeEventListener", "(", "type", ",", "delegate", ")", ";", "}" ]
Removes an event listener to an element where the event target is discovered by moving up the clicked element's descendants. @param {Element} el Element to host the listener. @param {string} type Listener type. @param {Function} listener Listener function.
[ "Removes", "an", "event", "listener", "to", "an", "element", "where", "the", "event", "target", "is", "discovered", "by", "moving", "up", "the", "clicked", "element", "s", "descendants", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/utils/events.js#L76-L83
train
grow/airkit
ui/inview.js
function(selector, opt_offset, opt_delay) { this.selector = selector; this.offset = opt_offset || null; this.delay = opt_delay || 0; // Ensure all videos are loaded. var els = document.querySelectorAll(this.selector); [].forEach.call(els, function(el) { el.load(); }); }
javascript
function(selector, opt_offset, opt_delay) { this.selector = selector; this.offset = opt_offset || null; this.delay = opt_delay || 0; // Ensure all videos are loaded. var els = document.querySelectorAll(this.selector); [].forEach.call(els, function(el) { el.load(); }); }
[ "function", "(", "selector", ",", "opt_offset", ",", "opt_delay", ")", "{", "this", ".", "selector", "=", "selector", ";", "this", ".", "offset", "=", "opt_offset", "||", "null", ";", "this", ".", "delay", "=", "opt_delay", "||", "0", ";", "var", "els", "=", "document", ".", "querySelectorAll", "(", "this", ".", "selector", ")", ";", "[", "]", ".", "forEach", ".", "call", "(", "els", ",", "function", "(", "el", ")", "{", "el", ".", "load", "(", ")", ";", "}", ")", ";", "}" ]
Plays videos when they enter the viewport. @param {string} selector Query selector to find elements to act upon. @param {number=} opt_offset Offset (by percentage of the element) to apply when checking if the element is in view. @param {Array.<number>=} opt_delay An array of [min delay, max delay].
[ "Plays", "videos", "when", "they", "enter", "the", "viewport", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/ui/inview.js#L94-L104
train
lantiga/ki
editor/scripts/escope.js
Variable
function Variable(name, scope) { /** * The variable name, as given in the source code. * @member {String} Variable#name */ this.name = name; /** * List of defining occurrences of this variable (like in 'var ...' * statements or as parameter), as AST nodes. * @member {esprima.Identifier[]} Variable#identifiers */ this.identifiers = []; /** * List of {@link Reference|references} of this variable (excluding parameter entries) * in its defining scope and all nested scopes. For defining * occurrences only see {@link Variable#defs}. * @member {Reference[]} Variable#references */ this.references = []; /** * List of defining occurrences of this variable (like in 'var ...' * statements or as parameter), as custom objects. * @typedef {Object} DefEntry * @property {String} DefEntry.type - the type of the occurrence (e.g. * "Parameter", "Variable", ...) * @property {esprima.Identifier} DefEntry.name - the identifier AST node of the occurrence * @property {esprima.Node} DefEntry.node - the enclosing node of the * identifier * @property {esprima.Node} [DefEntry.parent] - the enclosing statement * node of the identifier * @member {DefEntry[]} Variable#defs */ this.defs = []; this.tainted = false; /** * Whether this is a stack variable. * @member {boolean} Variable#stack */ this.stack = true; /** * Reference to the enclosing Scope. * @member {Scope} Variable#scope */ this.scope = scope; }
javascript
function Variable(name, scope) { /** * The variable name, as given in the source code. * @member {String} Variable#name */ this.name = name; /** * List of defining occurrences of this variable (like in 'var ...' * statements or as parameter), as AST nodes. * @member {esprima.Identifier[]} Variable#identifiers */ this.identifiers = []; /** * List of {@link Reference|references} of this variable (excluding parameter entries) * in its defining scope and all nested scopes. For defining * occurrences only see {@link Variable#defs}. * @member {Reference[]} Variable#references */ this.references = []; /** * List of defining occurrences of this variable (like in 'var ...' * statements or as parameter), as custom objects. * @typedef {Object} DefEntry * @property {String} DefEntry.type - the type of the occurrence (e.g. * "Parameter", "Variable", ...) * @property {esprima.Identifier} DefEntry.name - the identifier AST node of the occurrence * @property {esprima.Node} DefEntry.node - the enclosing node of the * identifier * @property {esprima.Node} [DefEntry.parent] - the enclosing statement * node of the identifier * @member {DefEntry[]} Variable#defs */ this.defs = []; this.tainted = false; /** * Whether this is a stack variable. * @member {boolean} Variable#stack */ this.stack = true; /** * Reference to the enclosing Scope. * @member {Scope} Variable#scope */ this.scope = scope; }
[ "function", "Variable", "(", "name", ",", "scope", ")", "{", "this", ".", "name", "=", "name", ";", "this", ".", "identifiers", "=", "[", "]", ";", "this", ".", "references", "=", "[", "]", ";", "this", ".", "defs", "=", "[", "]", ";", "this", ".", "tainted", "=", "false", ";", "this", ".", "stack", "=", "true", ";", "this", ".", "scope", "=", "scope", ";", "}" ]
A Variable represents a locally scoped identifier. These include arguments to functions. @class Variable
[ "A", "Variable", "represents", "a", "locally", "scoped", "identifier", ".", "These", "include", "arguments", "to", "functions", "." ]
5c2fdfc5f0ad9d6ea88161962604550193f5d6db
https://github.com/lantiga/ki/blob/5c2fdfc5f0ad9d6ea88161962604550193f5d6db/editor/scripts/escope.js#L282-L328
train
grow/airkit
youtubemodal/index.js
YouTubeModal
function YouTubeModal(config) { this.config = config; this.parentElement = document.querySelector(this.config.parentSelector); this.closeEventListener_ = this.setActive_.bind(this, false); this.popstateListener_ = this.onHistoryChange_.bind(this); this.el_ = null; this.closeEl_ = null; this.attributionEl_ = null; this.initDom_(); this.lastActiveVideoId_ = null; this.scrollY = 0; this.delegatedListener_ = function(targetEl) { var data = 'data-' + this.config.className + '-video-id'; var videoId = targetEl.getAttribute(data); var startDataAttribute = 'data-' + this.config.className + '-video-start-seconds'; var startTime = +targetEl.getAttribute(startDataAttribute); var attributionAttribute = 'data-' + this.config.className + '-attribution'; var attribution = targetEl.getAttribute(attributionAttribute); if (videoId) { this.play(videoId, true /* opt_updateState */, startTime, attribution); } }.bind(this); // Loads YouTube iframe API. events.addDelegatedListener(document, 'click', this.delegatedListener_); // Only add the script tag if it doesn't exist var scriptTag = document.querySelector('script[src="https://www.youtube.com/iframe_api"]'); if (!scriptTag) { var tag = document.createElement('script'); tag.setAttribute('src', 'https://www.youtube.com/iframe_api'); this.parentElement.appendChild(tag); } }
javascript
function YouTubeModal(config) { this.config = config; this.parentElement = document.querySelector(this.config.parentSelector); this.closeEventListener_ = this.setActive_.bind(this, false); this.popstateListener_ = this.onHistoryChange_.bind(this); this.el_ = null; this.closeEl_ = null; this.attributionEl_ = null; this.initDom_(); this.lastActiveVideoId_ = null; this.scrollY = 0; this.delegatedListener_ = function(targetEl) { var data = 'data-' + this.config.className + '-video-id'; var videoId = targetEl.getAttribute(data); var startDataAttribute = 'data-' + this.config.className + '-video-start-seconds'; var startTime = +targetEl.getAttribute(startDataAttribute); var attributionAttribute = 'data-' + this.config.className + '-attribution'; var attribution = targetEl.getAttribute(attributionAttribute); if (videoId) { this.play(videoId, true /* opt_updateState */, startTime, attribution); } }.bind(this); // Loads YouTube iframe API. events.addDelegatedListener(document, 'click', this.delegatedListener_); // Only add the script tag if it doesn't exist var scriptTag = document.querySelector('script[src="https://www.youtube.com/iframe_api"]'); if (!scriptTag) { var tag = document.createElement('script'); tag.setAttribute('src', 'https://www.youtube.com/iframe_api'); this.parentElement.appendChild(tag); } }
[ "function", "YouTubeModal", "(", "config", ")", "{", "this", ".", "config", "=", "config", ";", "this", ".", "parentElement", "=", "document", ".", "querySelector", "(", "this", ".", "config", ".", "parentSelector", ")", ";", "this", ".", "closeEventListener_", "=", "this", ".", "setActive_", ".", "bind", "(", "this", ",", "false", ")", ";", "this", ".", "popstateListener_", "=", "this", ".", "onHistoryChange_", ".", "bind", "(", "this", ")", ";", "this", ".", "el_", "=", "null", ";", "this", ".", "closeEl_", "=", "null", ";", "this", ".", "attributionEl_", "=", "null", ";", "this", ".", "initDom_", "(", ")", ";", "this", ".", "lastActiveVideoId_", "=", "null", ";", "this", ".", "scrollY", "=", "0", ";", "this", ".", "delegatedListener_", "=", "function", "(", "targetEl", ")", "{", "var", "data", "=", "'data-'", "+", "this", ".", "config", ".", "className", "+", "'-video-id'", ";", "var", "videoId", "=", "targetEl", ".", "getAttribute", "(", "data", ")", ";", "var", "startDataAttribute", "=", "'data-'", "+", "this", ".", "config", ".", "className", "+", "'-video-start-seconds'", ";", "var", "startTime", "=", "+", "targetEl", ".", "getAttribute", "(", "startDataAttribute", ")", ";", "var", "attributionAttribute", "=", "'data-'", "+", "this", ".", "config", ".", "className", "+", "'-attribution'", ";", "var", "attribution", "=", "targetEl", ".", "getAttribute", "(", "attributionAttribute", ")", ";", "if", "(", "videoId", ")", "{", "this", ".", "play", "(", "videoId", ",", "true", ",", "startTime", ",", "attribution", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ";", "events", ".", "addDelegatedListener", "(", "document", ",", "'click'", ",", "this", ".", "delegatedListener_", ")", ";", "var", "scriptTag", "=", "document", ".", "querySelector", "(", "'script[src=\"https://www.youtube.com/iframe_api\"]'", ")", ";", "if", "(", "!", "scriptTag", ")", "{", "var", "tag", "=", "document", ".", "createElement", "(", "'script'", ")", ";", "tag", ".", "setAttribute", "(", "'src'", ",", "'https://www.youtube.com/iframe_api'", ")", ";", "this", ".", "parentElement", ".", "appendChild", "(", "tag", ")", ";", "}", "}" ]
Plays a YouTube video in a modal dialog. @constructor
[ "Plays", "a", "YouTube", "video", "in", "a", "modal", "dialog", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/youtubemodal/index.js#L39-L74
train
grow/airkit
youtubemodal/index.js
init
function init(opt_config) { if (singleton) { return; } var config = objects.clone(defaultConfig); if (opt_config) { objects.merge(config, opt_config); } singleton = new YouTubeModal(config); }
javascript
function init(opt_config) { if (singleton) { return; } var config = objects.clone(defaultConfig); if (opt_config) { objects.merge(config, opt_config); } singleton = new YouTubeModal(config); }
[ "function", "init", "(", "opt_config", ")", "{", "if", "(", "singleton", ")", "{", "return", ";", "}", "var", "config", "=", "objects", ".", "clone", "(", "defaultConfig", ")", ";", "if", "(", "opt_config", ")", "{", "objects", ".", "merge", "(", "config", ",", "opt_config", ")", ";", "}", "singleton", "=", "new", "YouTubeModal", "(", "config", ")", ";", "}" ]
Initializes a YouTube modal dialog singleton. @param {Object=} opt_config Config options.
[ "Initializes", "a", "YouTube", "modal", "dialog", "singleton", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/youtubemodal/index.js#L263-L273
train
grow/airkit
analytics/googlecontentexperiments.js
init
function init(opt_config) { var config = objects.clone(defaultConfig); if (opt_config) { objects.merge(config, opt_config); } initVariations(config); }
javascript
function init(opt_config) { var config = objects.clone(defaultConfig); if (opt_config) { objects.merge(config, opt_config); } initVariations(config); }
[ "function", "init", "(", "opt_config", ")", "{", "var", "config", "=", "objects", ".", "clone", "(", "defaultConfig", ")", ";", "if", "(", "opt_config", ")", "{", "objects", ".", "merge", "(", "config", ",", "opt_config", ")", ";", "}", "initVariations", "(", "config", ")", ";", "}" ]
Loads GCX library and then initializes variations.
[ "Loads", "GCX", "library", "and", "then", "initializes", "variations", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/analytics/googlecontentexperiments.js#L19-L25
train
grow/airkit
dynamicdata/index.js
processStagingResp
function processStagingResp(resp, now, evergreen) { var keysToData = {}; for (var key in resp) { [].forEach.call(resp[key], function(datedRow) { var start = datedRow['start_date'] ? new Date(datedRow['start_date']) : null; var end = datedRow['end_date'] ? new Date(datedRow['end_date']) : null; if (evergreen) { var isEnabled = datetoggle.isEnabledNow(start, null, now); } else { var isEnabled = datetoggle.isEnabledNow(start, end, now); } if (isEnabled) { keysToData[key] = datedRow; } }); } return keysToData; }
javascript
function processStagingResp(resp, now, evergreen) { var keysToData = {}; for (var key in resp) { [].forEach.call(resp[key], function(datedRow) { var start = datedRow['start_date'] ? new Date(datedRow['start_date']) : null; var end = datedRow['end_date'] ? new Date(datedRow['end_date']) : null; if (evergreen) { var isEnabled = datetoggle.isEnabledNow(start, null, now); } else { var isEnabled = datetoggle.isEnabledNow(start, end, now); } if (isEnabled) { keysToData[key] = datedRow; } }); } return keysToData; }
[ "function", "processStagingResp", "(", "resp", ",", "now", ",", "evergreen", ")", "{", "var", "keysToData", "=", "{", "}", ";", "for", "(", "var", "key", "in", "resp", ")", "{", "[", "]", ".", "forEach", ".", "call", "(", "resp", "[", "key", "]", ",", "function", "(", "datedRow", ")", "{", "var", "start", "=", "datedRow", "[", "'start_date'", "]", "?", "new", "Date", "(", "datedRow", "[", "'start_date'", "]", ")", ":", "null", ";", "var", "end", "=", "datedRow", "[", "'end_date'", "]", "?", "new", "Date", "(", "datedRow", "[", "'end_date'", "]", ")", ":", "null", ";", "if", "(", "evergreen", ")", "{", "var", "isEnabled", "=", "datetoggle", ".", "isEnabledNow", "(", "start", ",", "null", ",", "now", ")", ";", "}", "else", "{", "var", "isEnabled", "=", "datetoggle", ".", "isEnabledNow", "(", "start", ",", "end", ",", "now", ")", ";", "}", "if", "(", "isEnabled", ")", "{", "keysToData", "[", "key", "]", "=", "datedRow", ";", "}", "}", ")", ";", "}", "return", "keysToData", ";", "}" ]
Normalizes staging data to become the same format as prod data.
[ "Normalizes", "staging", "data", "to", "become", "the", "same", "format", "as", "prod", "data", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/dynamicdata/index.js#L37-L54
train
grow/airkit
gulp/compilejs.js
compilejs
function compilejs(sources, outdir, outfile, opt_options) { var bundler = browserify({ entries: sources, debug: false }); return rebundle_(bundler, outdir, outfile, opt_options); }
javascript
function compilejs(sources, outdir, outfile, opt_options) { var bundler = browserify({ entries: sources, debug: false }); return rebundle_(bundler, outdir, outfile, opt_options); }
[ "function", "compilejs", "(", "sources", ",", "outdir", ",", "outfile", ",", "opt_options", ")", "{", "var", "bundler", "=", "browserify", "(", "{", "entries", ":", "sources", ",", "debug", ":", "false", "}", ")", ";", "return", "rebundle_", "(", "bundler", ",", "outdir", ",", "outfile", ",", "opt_options", ")", ";", "}" ]
Compiles js code using browserify and uglify. @param {Array.<string>} sources List of JS source files. @param {string} outdir Output directory. @param {string} outfile Output file name. @param {Object=} opt_options Options.
[ "Compiles", "js", "code", "using", "browserify", "and", "uglify", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/gulp/compilejs.js#L17-L23
train
grow/airkit
gulp/compilejs.js
watchjs
function watchjs(sources, outdir, outfile, opt_options) { var bundler = watchify(browserify({ entries: sources, debug: false, // Watchify options: cache: {}, packageCache: {}, fullPaths: true })); bundler.on('update', function() { gutil.log('recompiling js...'); rebundle_(bundler, outdir, outfile, opt_options); gutil.log('finished recompiling js'); }); return rebundle_(bundler, outdir, outfile, opt_options); }
javascript
function watchjs(sources, outdir, outfile, opt_options) { var bundler = watchify(browserify({ entries: sources, debug: false, // Watchify options: cache: {}, packageCache: {}, fullPaths: true })); bundler.on('update', function() { gutil.log('recompiling js...'); rebundle_(bundler, outdir, outfile, opt_options); gutil.log('finished recompiling js'); }); return rebundle_(bundler, outdir, outfile, opt_options); }
[ "function", "watchjs", "(", "sources", ",", "outdir", ",", "outfile", ",", "opt_options", ")", "{", "var", "bundler", "=", "watchify", "(", "browserify", "(", "{", "entries", ":", "sources", ",", "debug", ":", "false", ",", "cache", ":", "{", "}", ",", "packageCache", ":", "{", "}", ",", "fullPaths", ":", "true", "}", ")", ")", ";", "bundler", ".", "on", "(", "'update'", ",", "function", "(", ")", "{", "gutil", ".", "log", "(", "'recompiling js...'", ")", ";", "rebundle_", "(", "bundler", ",", "outdir", ",", "outfile", ",", "opt_options", ")", ";", "gutil", ".", "log", "(", "'finished recompiling js'", ")", ";", "}", ")", ";", "return", "rebundle_", "(", "bundler", ",", "outdir", ",", "outfile", ",", "opt_options", ")", ";", "}" ]
Watches JS code for changes and triggers compilation. @param {Array.<string>} sources List of JS source files. @param {string} outdir Output directory. @param {string} outfile Output file name. @param {Object=} opt_options Options.
[ "Watches", "JS", "code", "for", "changes", "and", "triggers", "compilation", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/gulp/compilejs.js#L33-L49
train
grow/airkit
utils/dom.js
createDom
function createDom(tagName, opt_className) { var element = document.createElement(tagName); if (opt_className) { element.className = opt_className; } return element; }
javascript
function createDom(tagName, opt_className) { var element = document.createElement(tagName); if (opt_className) { element.className = opt_className; } return element; }
[ "function", "createDom", "(", "tagName", ",", "opt_className", ")", "{", "var", "element", "=", "document", ".", "createElement", "(", "tagName", ")", ";", "if", "(", "opt_className", ")", "{", "element", ".", "className", "=", "opt_className", ";", "}", "return", "element", ";", "}" ]
Creates a dom element and optionally adds a class name. @param {string} tagName Element's tag name. @param {string?} opt_className Class name to add. @return {Element} Created element.
[ "Creates", "a", "dom", "element", "and", "optionally", "adds", "a", "class", "name", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/utils/dom.js#L7-L13
train
grow/airkit
scrolltoggle/index.js
ScrollToggle
function ScrollToggle(el, config) { this.el_ = el; this.config_ = objects.clone(config); if (this.el_.hasAttribute('data-ak-scrolltoggle')) { var elConfig = JSON.parse(this.el_.getAttribute('data-ak-scrolltoggle')); if (elConfig && typeof elConfig === 'object') { objects.merge(this.config_, elConfig); } } // Initialize the current scroll position. this.lastScrollPos_ = 0; this.onScroll(); }
javascript
function ScrollToggle(el, config) { this.el_ = el; this.config_ = objects.clone(config); if (this.el_.hasAttribute('data-ak-scrolltoggle')) { var elConfig = JSON.parse(this.el_.getAttribute('data-ak-scrolltoggle')); if (elConfig && typeof elConfig === 'object') { objects.merge(this.config_, elConfig); } } // Initialize the current scroll position. this.lastScrollPos_ = 0; this.onScroll(); }
[ "function", "ScrollToggle", "(", "el", ",", "config", ")", "{", "this", ".", "el_", "=", "el", ";", "this", ".", "config_", "=", "objects", ".", "clone", "(", "config", ")", ";", "if", "(", "this", ".", "el_", ".", "hasAttribute", "(", "'data-ak-scrolltoggle'", ")", ")", "{", "var", "elConfig", "=", "JSON", ".", "parse", "(", "this", ".", "el_", ".", "getAttribute", "(", "'data-ak-scrolltoggle'", ")", ")", ";", "if", "(", "elConfig", "&&", "typeof", "elConfig", "===", "'object'", ")", "{", "objects", ".", "merge", "(", "this", ".", "config_", ",", "elConfig", ")", ";", "}", "}", "this", ".", "lastScrollPos_", "=", "0", ";", "this", ".", "onScroll", "(", ")", ";", "}" ]
Toggles a class on an element when a scroll direction has been detected. @param {Element} el The element. @param {Object} config Config options. @constructor
[ "Toggles", "a", "class", "on", "an", "element", "when", "a", "scroll", "direction", "has", "been", "detected", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/scrolltoggle/index.js#L29-L43
train
RiptideElements/passport-google-auth
lib/GoogleOAuth2Strategy.js
GoogleOAuth2Strategy
function GoogleOAuth2Strategy(options, verify) { var self = this; if (typeof options === 'function') { verify = options; options = {}; } if (!verify) { throw new Error('GoogleOAuth2Strategy requires a verify callback'); } requiredArgs.forEach(function (arg) { if (!options[arg.name]) { throw new Error(util.format('GoogleOAuth2Strategy requires a [%s]', arg.name)); } else if (typeof options[arg.name] !== arg.type) { throw new Error(util.format('GoogleOAuth2Strategy expects [%s] to be a [%s] but it was a [%s]', arg.name, arg.type, typeof options[arg.name])); } // If we've passed the checks, go ahead and set it in the current object. self[arg.name] = options[arg.name]; }); optionalArgs.forEach(function (arg) { if (options[arg.name] && typeof options[arg.name] !== arg.type) { throw new Error(util.format('GoogleOAuth2Strategy expects [%s] to be a [%s] but it was a [%s]', arg.name, arg.type, typeof options[arg.name])); } // If we've passed the checks, go ahead and set it in the current object. self[arg.name] = options[arg.name]; }); if (options.scope && (typeof options.scope !== 'string' && !Array.isArray(options.scope))) { throw new Error(util.format('GoogleOAuth2Strategy expects [%s] to be a [%s] but it was a [%s]', 'scope', 'array or string', typeof options.scope)); } self.scope = options.scope || 'https://www.googleapis.com/auth/userinfo.email'; passport.Strategy.call(self); self.name = 'google'; self.verify = verify; if (!self.skipUserProfile) { self.googlePlus = gapi.plus('v1'); } }
javascript
function GoogleOAuth2Strategy(options, verify) { var self = this; if (typeof options === 'function') { verify = options; options = {}; } if (!verify) { throw new Error('GoogleOAuth2Strategy requires a verify callback'); } requiredArgs.forEach(function (arg) { if (!options[arg.name]) { throw new Error(util.format('GoogleOAuth2Strategy requires a [%s]', arg.name)); } else if (typeof options[arg.name] !== arg.type) { throw new Error(util.format('GoogleOAuth2Strategy expects [%s] to be a [%s] but it was a [%s]', arg.name, arg.type, typeof options[arg.name])); } // If we've passed the checks, go ahead and set it in the current object. self[arg.name] = options[arg.name]; }); optionalArgs.forEach(function (arg) { if (options[arg.name] && typeof options[arg.name] !== arg.type) { throw new Error(util.format('GoogleOAuth2Strategy expects [%s] to be a [%s] but it was a [%s]', arg.name, arg.type, typeof options[arg.name])); } // If we've passed the checks, go ahead and set it in the current object. self[arg.name] = options[arg.name]; }); if (options.scope && (typeof options.scope !== 'string' && !Array.isArray(options.scope))) { throw new Error(util.format('GoogleOAuth2Strategy expects [%s] to be a [%s] but it was a [%s]', 'scope', 'array or string', typeof options.scope)); } self.scope = options.scope || 'https://www.googleapis.com/auth/userinfo.email'; passport.Strategy.call(self); self.name = 'google'; self.verify = verify; if (!self.skipUserProfile) { self.googlePlus = gapi.plus('v1'); } }
[ "function", "GoogleOAuth2Strategy", "(", "options", ",", "verify", ")", "{", "var", "self", "=", "this", ";", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "verify", "=", "options", ";", "options", "=", "{", "}", ";", "}", "if", "(", "!", "verify", ")", "{", "throw", "new", "Error", "(", "'GoogleOAuth2Strategy requires a verify callback'", ")", ";", "}", "requiredArgs", ".", "forEach", "(", "function", "(", "arg", ")", "{", "if", "(", "!", "options", "[", "arg", ".", "name", "]", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'GoogleOAuth2Strategy requires a [%s]'", ",", "arg", ".", "name", ")", ")", ";", "}", "else", "if", "(", "typeof", "options", "[", "arg", ".", "name", "]", "!==", "arg", ".", "type", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'GoogleOAuth2Strategy expects [%s] to be a [%s] but it was a [%s]'", ",", "arg", ".", "name", ",", "arg", ".", "type", ",", "typeof", "options", "[", "arg", ".", "name", "]", ")", ")", ";", "}", "self", "[", "arg", ".", "name", "]", "=", "options", "[", "arg", ".", "name", "]", ";", "}", ")", ";", "optionalArgs", ".", "forEach", "(", "function", "(", "arg", ")", "{", "if", "(", "options", "[", "arg", ".", "name", "]", "&&", "typeof", "options", "[", "arg", ".", "name", "]", "!==", "arg", ".", "type", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'GoogleOAuth2Strategy expects [%s] to be a [%s] but it was a [%s]'", ",", "arg", ".", "name", ",", "arg", ".", "type", ",", "typeof", "options", "[", "arg", ".", "name", "]", ")", ")", ";", "}", "self", "[", "arg", ".", "name", "]", "=", "options", "[", "arg", ".", "name", "]", ";", "}", ")", ";", "if", "(", "options", ".", "scope", "&&", "(", "typeof", "options", ".", "scope", "!==", "'string'", "&&", "!", "Array", ".", "isArray", "(", "options", ".", "scope", ")", ")", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'GoogleOAuth2Strategy expects [%s] to be a [%s] but it was a [%s]'", ",", "'scope'", ",", "'array or string'", ",", "typeof", "options", ".", "scope", ")", ")", ";", "}", "self", ".", "scope", "=", "options", ".", "scope", "||", "'https://www.googleapis.com/auth/userinfo.email'", ";", "passport", ".", "Strategy", ".", "call", "(", "self", ")", ";", "self", ".", "name", "=", "'google'", ";", "self", ".", "verify", "=", "verify", ";", "if", "(", "!", "self", ".", "skipUserProfile", ")", "{", "self", ".", "googlePlus", "=", "gapi", ".", "plus", "(", "'v1'", ")", ";", "}", "}" ]
Creates an instance of `GoogleOAuth2Strategy`. The Google OAuth 2.0 authentication strategy authenticates requests by delegating to Google's OAuth 2.0 authentication implementation in their Node.JS API. OAuth 2.0 provides a facility for delegated authentication, whereby users can authenticate using a third-party service such as Facebook. Delegating in this manner involves a sequence of events, including redirecting the user to the third-party service for authorization. Once authorization has been granted, the user is redirected back to the application and an authorization code can be used to obtain credentials. Applications must supply a `verify` callback, for which the function signature is: function(accessToken, refreshToken, profile, done) { ... } The verify callback is responsible for finding or creating the user, and invoking `done` with the following arguments: done(err, user, info); `user` should be set to `false` to indicate an authentication failure. Additional `info` can optionally be passed as a third argument, typically used to display informational messages. If an exception occured, `err` should be set. Options: - `clientId` `String` identifies the client to the service provider **Required** - `clientSecret` `String` secret used to establish ownershup of the client identifier **Required** - `callbackURL` `String` URL to which the service provider will redirect the user after obtaining authorization. **Required** - `accessType` `String` Type of access to be requested from the service provider. Can be `online` (default) or `offline` (gets refresh_token) _Optional_ - `scope` `String` or `Array` representing the permission scopes to request access to. (default: `https://www.googleapis.com/auth/userinfo.email`) _Optional_ - `skipUserProfile` `Boolean` If set to false, profile information will be retrieved from Google+. (default: `true`) _Optional_ - `passReqToCallback` `Boolean` When `true`, `req` is the first argument to the verify callback (default: `false`) Examples: passport.use(new GoogleOAuth2Strategy({ clientID: '123-456-789', clientSecret: 'shhh-its-a-secret', callbackURL: 'https://www.example.com/auth/example/callback' }, function(accessToken, refreshToken, profile, done) { User.findOrCreate(..., function (err, user) { done(err, user); }); } )); @constructor @param {Object} options @param {Function} verify @api public
[ "Creates", "an", "instance", "of", "GoogleOAuth2Strategy", "." ]
ff29996480c1a55e44411b84a12b0242c8bb6e8d
https://github.com/RiptideElements/passport-google-auth/blob/ff29996480c1a55e44411b84a12b0242c8bb6e8d/lib/GoogleOAuth2Strategy.js#L111-L153
train
grow/airkit
utils/video.js
initVideoFallback
function initVideoFallback(opt_config) { var videoSelector = (opt_config && opt_config.videoSelector) || defaultConfig.fallbackVideoSelector; var imageSelector = (opt_config && opt_config.imageSelector) || defaultConfig.fallbackImageSelector; var breakpoint = (opt_config && opt_config.breakpoint) || defaultConfig.breakpoint; var hidden = {'display': 'none !important'}; var rules = {}; if (canPlayVideo()) { rules[imageSelector] = hidden; } else { rules[videoSelector] = hidden; } if (!breakpoint) { ui.createStyle(rules); } else { var minScreenQuery = '(min-width: ' + breakpoint + 'px)'; ui.createStyle(rules, minScreenQuery); var smallerBreakpoint = breakpoint - 1; var maxScreenQuery = '(max-width: ' + smallerBreakpoint + 'px)'; rules = {}; rules[videoSelector] = hidden; ui.createStyle(rules, maxScreenQuery); } }
javascript
function initVideoFallback(opt_config) { var videoSelector = (opt_config && opt_config.videoSelector) || defaultConfig.fallbackVideoSelector; var imageSelector = (opt_config && opt_config.imageSelector) || defaultConfig.fallbackImageSelector; var breakpoint = (opt_config && opt_config.breakpoint) || defaultConfig.breakpoint; var hidden = {'display': 'none !important'}; var rules = {}; if (canPlayVideo()) { rules[imageSelector] = hidden; } else { rules[videoSelector] = hidden; } if (!breakpoint) { ui.createStyle(rules); } else { var minScreenQuery = '(min-width: ' + breakpoint + 'px)'; ui.createStyle(rules, minScreenQuery); var smallerBreakpoint = breakpoint - 1; var maxScreenQuery = '(max-width: ' + smallerBreakpoint + 'px)'; rules = {}; rules[videoSelector] = hidden; ui.createStyle(rules, maxScreenQuery); } }
[ "function", "initVideoFallback", "(", "opt_config", ")", "{", "var", "videoSelector", "=", "(", "opt_config", "&&", "opt_config", ".", "videoSelector", ")", "||", "defaultConfig", ".", "fallbackVideoSelector", ";", "var", "imageSelector", "=", "(", "opt_config", "&&", "opt_config", ".", "imageSelector", ")", "||", "defaultConfig", ".", "fallbackImageSelector", ";", "var", "breakpoint", "=", "(", "opt_config", "&&", "opt_config", ".", "breakpoint", ")", "||", "defaultConfig", ".", "breakpoint", ";", "var", "hidden", "=", "{", "'display'", ":", "'none !important'", "}", ";", "var", "rules", "=", "{", "}", ";", "if", "(", "canPlayVideo", "(", ")", ")", "{", "rules", "[", "imageSelector", "]", "=", "hidden", ";", "}", "else", "{", "rules", "[", "videoSelector", "]", "=", "hidden", ";", "}", "if", "(", "!", "breakpoint", ")", "{", "ui", ".", "createStyle", "(", "rules", ")", ";", "}", "else", "{", "var", "minScreenQuery", "=", "'(min-width: '", "+", "breakpoint", "+", "'px)'", ";", "ui", ".", "createStyle", "(", "rules", ",", "minScreenQuery", ")", ";", "var", "smallerBreakpoint", "=", "breakpoint", "-", "1", ";", "var", "maxScreenQuery", "=", "'(max-width: '", "+", "smallerBreakpoint", "+", "'px)'", ";", "rules", "=", "{", "}", ";", "rules", "[", "videoSelector", "]", "=", "hidden", ";", "ui", ".", "createStyle", "(", "rules", ",", "maxScreenQuery", ")", ";", "}", "}" ]
Shows or hides video elements and their corresponding image elements depending on whether the user agent can play video. Fallback is only implemented between video and images, not video formats. You should rely on the video element's default behavior with <source> tags to support fallback between video formats. As a result, you should probably always include at least a mp4 video, as mp4 is the most compatible. This is opinionated and will not enable video for mobile devices. (1) Set up a DOM structure: <div class="ak-video-fallback"> <video>...</video> <img> </div> (2) Run at the top of the page (to avoid FOUC): initVideoFallback(); @param {Object=} opt_config Configuration. The configuration contains two options: videoSelector and imageSelector, selectors used to query videos and images to hide.
[ "Shows", "or", "hides", "video", "elements", "and", "their", "corresponding", "image", "elements", "depending", "on", "whether", "the", "user", "agent", "can", "play", "video", "." ]
870204d7512237c6ac5712ccc5583b81d6cd2d17
https://github.com/grow/airkit/blob/870204d7512237c6ac5712ccc5583b81d6cd2d17/utils/video.js#L49-L76
train
nohros/nsPopover
src/nsPopover.js
adjustRect
function adjustRect(rect, adjustX, adjustY, ev) { // if pageX or pageY is defined we need to lock the popover to the given // x and y position. // clone the rect, so we can manipulate its properties. var localRect = { bottom: rect.bottom, height: rect.height, left: rect.left, right: rect.right, top: rect.top, width: rect.width }; if (adjustX) { localRect.left = ev.pageX; localRect.right = ev.pageX; localRect.width = 0; } if (adjustY) { localRect.top = ev.pageY; localRect.bottom = ev.pageY; localRect.height = 0; } return localRect; }
javascript
function adjustRect(rect, adjustX, adjustY, ev) { // if pageX or pageY is defined we need to lock the popover to the given // x and y position. // clone the rect, so we can manipulate its properties. var localRect = { bottom: rect.bottom, height: rect.height, left: rect.left, right: rect.right, top: rect.top, width: rect.width }; if (adjustX) { localRect.left = ev.pageX; localRect.right = ev.pageX; localRect.width = 0; } if (adjustY) { localRect.top = ev.pageY; localRect.bottom = ev.pageY; localRect.height = 0; } return localRect; }
[ "function", "adjustRect", "(", "rect", ",", "adjustX", ",", "adjustY", ",", "ev", ")", "{", "var", "localRect", "=", "{", "bottom", ":", "rect", ".", "bottom", ",", "height", ":", "rect", ".", "height", ",", "left", ":", "rect", ".", "left", ",", "right", ":", "rect", ".", "right", ",", "top", ":", "rect", ".", "top", ",", "width", ":", "rect", ".", "width", "}", ";", "if", "(", "adjustX", ")", "{", "localRect", ".", "left", "=", "ev", ".", "pageX", ";", "localRect", ".", "right", "=", "ev", ".", "pageX", ";", "localRect", ".", "width", "=", "0", ";", "}", "if", "(", "adjustY", ")", "{", "localRect", ".", "top", "=", "ev", ".", "pageY", ";", "localRect", ".", "bottom", "=", "ev", ".", "pageY", ";", "localRect", ".", "height", "=", "0", ";", "}", "return", "localRect", ";", "}" ]
Adjust a rect accordingly to the given x and y mouse positions. @param rect {ClientRect} The rect to be adjusted.
[ "Adjust", "a", "rect", "accordingly", "to", "the", "given", "x", "and", "y", "mouse", "positions", "." ]
0d768929a4590f9602c87851dca0df54d19d069a
https://github.com/nohros/nsPopover/blob/0d768929a4590f9602c87851dca0df54d19d069a/src/nsPopover.js#L144-L170
train
nohros/nsPopover
src/nsPopover.js
loadTemplate
function loadTemplate(template, plain) { if (!template) { return ''; } if (angular.isString(template) && plain) { return template; } return $templateCache.get(template) || $http.get(template, { cache : true }); }
javascript
function loadTemplate(template, plain) { if (!template) { return ''; } if (angular.isString(template) && plain) { return template; } return $templateCache.get(template) || $http.get(template, { cache : true }); }
[ "function", "loadTemplate", "(", "template", ",", "plain", ")", "{", "if", "(", "!", "template", ")", "{", "return", "''", ";", "}", "if", "(", "angular", ".", "isString", "(", "template", ")", "&&", "plain", ")", "{", "return", "template", ";", "}", "return", "$templateCache", ".", "get", "(", "template", ")", "||", "$http", ".", "get", "(", "template", ",", "{", "cache", ":", "true", "}", ")", ";", "}" ]
Load the given template in the cache if it is not already loaded. @param template The URI of the template to be loaded. @returns {String} A promise that the template will be loaded. @remarks If the template is null or undefined a empty string will be returned.
[ "Load", "the", "given", "template", "in", "the", "cache", "if", "it", "is", "not", "already", "loaded", "." ]
0d768929a4590f9602c87851dca0df54d19d069a
https://github.com/nohros/nsPopover/blob/0d768929a4590f9602c87851dca0df54d19d069a/src/nsPopover.js#L225-L235
train
nohros/nsPopover
src/nsPopover.js
move
function move(popover, placement, align, rect, triangle) { var containerRect; var popoverRect = getBoundingClientRect(popover[0]); var popoverRight; var top, left; var positionX = function() { if (align === 'center') { return Math.round(rect.left + rect.width/2 - popoverRect.width/2); } else if(align === 'right') { return rect.right - popoverRect.width; } return rect.left; }; var positionY = function() { if (align === 'center') { return Math.round(rect.top + rect.height/2 - popoverRect.height/2); } else if(align === 'bottom') { return rect.bottom - popoverRect.height; } return rect.top; }; if (placement === 'top') { top = rect.top - popoverRect.height; left = positionX(); } else if (placement === 'right') { top = positionY(); left = rect.right; } else if (placement === 'bottom') { top = rect.bottom; left = positionX(); } else if (placement === 'left') { top = positionY(); left = rect.left - popoverRect.width; } // Rescrict the popover to the bounds of the container if (true === options.restrictBounds) { containerRect = getBoundingClientRect($container[0]); // The left should be below the left of the container. left = Math.max(containerRect.left, left); // Prevent the left from causing the right to go outside // the conatiner. popoverRight = left + popoverRect.width; if (popoverRight > containerRect.width) { left = left - (popoverRight - containerRect.width); } } popover .css('top', top.toString() + 'px') .css('left', left.toString() + 'px'); if (triangle && triangle.length) { if (placement === 'top' || placement === 'bottom') { left = rect.left + rect.width / 2 - left; triangle.css('left', left.toString() + 'px'); } else { top = rect.top + rect.height / 2 - top; triangle.css('top', top.toString() + 'px'); } } }
javascript
function move(popover, placement, align, rect, triangle) { var containerRect; var popoverRect = getBoundingClientRect(popover[0]); var popoverRight; var top, left; var positionX = function() { if (align === 'center') { return Math.round(rect.left + rect.width/2 - popoverRect.width/2); } else if(align === 'right') { return rect.right - popoverRect.width; } return rect.left; }; var positionY = function() { if (align === 'center') { return Math.round(rect.top + rect.height/2 - popoverRect.height/2); } else if(align === 'bottom') { return rect.bottom - popoverRect.height; } return rect.top; }; if (placement === 'top') { top = rect.top - popoverRect.height; left = positionX(); } else if (placement === 'right') { top = positionY(); left = rect.right; } else if (placement === 'bottom') { top = rect.bottom; left = positionX(); } else if (placement === 'left') { top = positionY(); left = rect.left - popoverRect.width; } // Rescrict the popover to the bounds of the container if (true === options.restrictBounds) { containerRect = getBoundingClientRect($container[0]); // The left should be below the left of the container. left = Math.max(containerRect.left, left); // Prevent the left from causing the right to go outside // the conatiner. popoverRight = left + popoverRect.width; if (popoverRight > containerRect.width) { left = left - (popoverRight - containerRect.width); } } popover .css('top', top.toString() + 'px') .css('left', left.toString() + 'px'); if (triangle && triangle.length) { if (placement === 'top' || placement === 'bottom') { left = rect.left + rect.width / 2 - left; triangle.css('left', left.toString() + 'px'); } else { top = rect.top + rect.height / 2 - top; triangle.css('top', top.toString() + 'px'); } } }
[ "function", "move", "(", "popover", ",", "placement", ",", "align", ",", "rect", ",", "triangle", ")", "{", "var", "containerRect", ";", "var", "popoverRect", "=", "getBoundingClientRect", "(", "popover", "[", "0", "]", ")", ";", "var", "popoverRight", ";", "var", "top", ",", "left", ";", "var", "positionX", "=", "function", "(", ")", "{", "if", "(", "align", "===", "'center'", ")", "{", "return", "Math", ".", "round", "(", "rect", ".", "left", "+", "rect", ".", "width", "/", "2", "-", "popoverRect", ".", "width", "/", "2", ")", ";", "}", "else", "if", "(", "align", "===", "'right'", ")", "{", "return", "rect", ".", "right", "-", "popoverRect", ".", "width", ";", "}", "return", "rect", ".", "left", ";", "}", ";", "var", "positionY", "=", "function", "(", ")", "{", "if", "(", "align", "===", "'center'", ")", "{", "return", "Math", ".", "round", "(", "rect", ".", "top", "+", "rect", ".", "height", "/", "2", "-", "popoverRect", ".", "height", "/", "2", ")", ";", "}", "else", "if", "(", "align", "===", "'bottom'", ")", "{", "return", "rect", ".", "bottom", "-", "popoverRect", ".", "height", ";", "}", "return", "rect", ".", "top", ";", "}", ";", "if", "(", "placement", "===", "'top'", ")", "{", "top", "=", "rect", ".", "top", "-", "popoverRect", ".", "height", ";", "left", "=", "positionX", "(", ")", ";", "}", "else", "if", "(", "placement", "===", "'right'", ")", "{", "top", "=", "positionY", "(", ")", ";", "left", "=", "rect", ".", "right", ";", "}", "else", "if", "(", "placement", "===", "'bottom'", ")", "{", "top", "=", "rect", ".", "bottom", ";", "left", "=", "positionX", "(", ")", ";", "}", "else", "if", "(", "placement", "===", "'left'", ")", "{", "top", "=", "positionY", "(", ")", ";", "left", "=", "rect", ".", "left", "-", "popoverRect", ".", "width", ";", "}", "if", "(", "true", "===", "options", ".", "restrictBounds", ")", "{", "containerRect", "=", "getBoundingClientRect", "(", "$container", "[", "0", "]", ")", ";", "left", "=", "Math", ".", "max", "(", "containerRect", ".", "left", ",", "left", ")", ";", "popoverRight", "=", "left", "+", "popoverRect", ".", "width", ";", "if", "(", "popoverRight", ">", "containerRect", ".", "width", ")", "{", "left", "=", "left", "-", "(", "popoverRight", "-", "containerRect", ".", "width", ")", ";", "}", "}", "popover", ".", "css", "(", "'top'", ",", "top", ".", "toString", "(", ")", "+", "'px'", ")", ".", "css", "(", "'left'", ",", "left", ".", "toString", "(", ")", "+", "'px'", ")", ";", "if", "(", "triangle", "&&", "triangle", ".", "length", ")", "{", "if", "(", "placement", "===", "'top'", "||", "placement", "===", "'bottom'", ")", "{", "left", "=", "rect", ".", "left", "+", "rect", ".", "width", "/", "2", "-", "left", ";", "triangle", ".", "css", "(", "'left'", ",", "left", ".", "toString", "(", ")", "+", "'px'", ")", ";", "}", "else", "{", "top", "=", "rect", ".", "top", "+", "rect", ".", "height", "/", "2", "-", "top", ";", "triangle", ".", "css", "(", "'top'", ",", "top", ".", "toString", "(", ")", "+", "'px'", ")", ";", "}", "}", "}" ]
Move the popover to the |placement| position of the object located on the |rect|. @param popover {Object} The popover object to be moved. @param placement {String} The relative position to move the popover - top | bottom | left | right. @param align {String} The way the popover should be aligned - center | left | right. @param rect {ClientRect} The ClientRect of the object to move the popover around. @param triangle {Object} The element that contains the popover's triangle. This can be null.
[ "Move", "the", "popover", "to", "the", "|placement|", "position", "of", "the", "object", "located", "on", "the", "|rect|", "." ]
0d768929a4590f9602c87851dca0df54d19d069a
https://github.com/nohros/nsPopover/blob/0d768929a4590f9602c87851dca0df54d19d069a/src/nsPopover.js#L246-L312
train
nohros/nsPopover
src/nsPopover.js
function(delay, e) { // Disable popover if ns-popover value is false if ($parse(attrs.nsPopover)(scope) === false) { return; } $timeout.cancel(displayer_.id_); if (!isDef(delay)) { delay = 0; } // hide any popovers being displayed if (options.group) { $rootScope.$broadcast('ns:popover:hide', options.group); } displayer_.id_ = $timeout(function() { if (true === $popover.isOpen) { return; } $popover.isOpen = true; $popover.css('display', 'block'); // position the popover accordingly to the defined placement around the // |elm|. var elmRect = getBoundingClientRect(elm[0]); // If the mouse-relative options is specified we need to adjust the // element client rect to the current mouse coordinates. if (options.mouseRelative) { elmRect = adjustRect(elmRect, options.mouseRelativeX, options.mouseRelativeY, e); } move($popover, placement_, align_, elmRect, $triangle); addEventListeners(); // Hide the popover without delay on the popover click events. if (true === options.hideOnInsideClick) { $popover.on('click', insideClickHandler); } // Hide the popover without delay on outside click events. if (true === options.hideOnOutsideClick) { $document.on('click', outsideClickHandler); } // Hide the popover without delay on the button click events. if (true === options.hideOnButtonClick) { elm.on('click', buttonClickHandler); } // Call the open callback options.onOpen(scope); }, delay*1000); }
javascript
function(delay, e) { // Disable popover if ns-popover value is false if ($parse(attrs.nsPopover)(scope) === false) { return; } $timeout.cancel(displayer_.id_); if (!isDef(delay)) { delay = 0; } // hide any popovers being displayed if (options.group) { $rootScope.$broadcast('ns:popover:hide', options.group); } displayer_.id_ = $timeout(function() { if (true === $popover.isOpen) { return; } $popover.isOpen = true; $popover.css('display', 'block'); // position the popover accordingly to the defined placement around the // |elm|. var elmRect = getBoundingClientRect(elm[0]); // If the mouse-relative options is specified we need to adjust the // element client rect to the current mouse coordinates. if (options.mouseRelative) { elmRect = adjustRect(elmRect, options.mouseRelativeX, options.mouseRelativeY, e); } move($popover, placement_, align_, elmRect, $triangle); addEventListeners(); // Hide the popover without delay on the popover click events. if (true === options.hideOnInsideClick) { $popover.on('click', insideClickHandler); } // Hide the popover without delay on outside click events. if (true === options.hideOnOutsideClick) { $document.on('click', outsideClickHandler); } // Hide the popover without delay on the button click events. if (true === options.hideOnButtonClick) { elm.on('click', buttonClickHandler); } // Call the open callback options.onOpen(scope); }, delay*1000); }
[ "function", "(", "delay", ",", "e", ")", "{", "if", "(", "$parse", "(", "attrs", ".", "nsPopover", ")", "(", "scope", ")", "===", "false", ")", "{", "return", ";", "}", "$timeout", ".", "cancel", "(", "displayer_", ".", "id_", ")", ";", "if", "(", "!", "isDef", "(", "delay", ")", ")", "{", "delay", "=", "0", ";", "}", "if", "(", "options", ".", "group", ")", "{", "$rootScope", ".", "$broadcast", "(", "'ns:popover:hide'", ",", "options", ".", "group", ")", ";", "}", "displayer_", ".", "id_", "=", "$timeout", "(", "function", "(", ")", "{", "if", "(", "true", "===", "$popover", ".", "isOpen", ")", "{", "return", ";", "}", "$popover", ".", "isOpen", "=", "true", ";", "$popover", ".", "css", "(", "'display'", ",", "'block'", ")", ";", "var", "elmRect", "=", "getBoundingClientRect", "(", "elm", "[", "0", "]", ")", ";", "if", "(", "options", ".", "mouseRelative", ")", "{", "elmRect", "=", "adjustRect", "(", "elmRect", ",", "options", ".", "mouseRelativeX", ",", "options", ".", "mouseRelativeY", ",", "e", ")", ";", "}", "move", "(", "$popover", ",", "placement_", ",", "align_", ",", "elmRect", ",", "$triangle", ")", ";", "addEventListeners", "(", ")", ";", "if", "(", "true", "===", "options", ".", "hideOnInsideClick", ")", "{", "$popover", ".", "on", "(", "'click'", ",", "insideClickHandler", ")", ";", "}", "if", "(", "true", "===", "options", ".", "hideOnOutsideClick", ")", "{", "$document", ".", "on", "(", "'click'", ",", "outsideClickHandler", ")", ";", "}", "if", "(", "true", "===", "options", ".", "hideOnButtonClick", ")", "{", "elm", ".", "on", "(", "'click'", ",", "buttonClickHandler", ")", ";", "}", "options", ".", "onOpen", "(", "scope", ")", ";", "}", ",", "delay", "*", "1000", ")", ";", "}" ]
Set the display property of the popover to 'block' after |delay| milliseconds. @param delay {Number} The time (in seconds) to wait before set the display property. @param e {Event} The event which caused the popover to be shown.
[ "Set", "the", "display", "property", "of", "the", "popover", "to", "block", "after", "|delay|", "milliseconds", "." ]
0d768929a4590f9602c87851dca0df54d19d069a
https://github.com/nohros/nsPopover/blob/0d768929a4590f9602c87851dca0df54d19d069a/src/nsPopover.js#L370-L426
train
nohros/nsPopover
src/nsPopover.js
function(delay) { $timeout.cancel(hider_.id_); // do not hide if -1 is passed in. if(delay !== "-1") { // delay the hiding operation for 1.5s by default. if (!isDef(delay)) { delay = 1.5; } hider_.id_ = $timeout(function() { $popover.off('click', insideClickHandler); $document.off('click', outsideClickHandler); elm.off('click', buttonClickHandler); $popover.isOpen = false; displayer_.cancel(); $popover.css('display', 'none'); removeEventListeners(); // Call the close callback options.onClose(scope); }, delay*1000); } }
javascript
function(delay) { $timeout.cancel(hider_.id_); // do not hide if -1 is passed in. if(delay !== "-1") { // delay the hiding operation for 1.5s by default. if (!isDef(delay)) { delay = 1.5; } hider_.id_ = $timeout(function() { $popover.off('click', insideClickHandler); $document.off('click', outsideClickHandler); elm.off('click', buttonClickHandler); $popover.isOpen = false; displayer_.cancel(); $popover.css('display', 'none'); removeEventListeners(); // Call the close callback options.onClose(scope); }, delay*1000); } }
[ "function", "(", "delay", ")", "{", "$timeout", ".", "cancel", "(", "hider_", ".", "id_", ")", ";", "if", "(", "delay", "!==", "\"-1\"", ")", "{", "if", "(", "!", "isDef", "(", "delay", ")", ")", "{", "delay", "=", "1.5", ";", "}", "hider_", ".", "id_", "=", "$timeout", "(", "function", "(", ")", "{", "$popover", ".", "off", "(", "'click'", ",", "insideClickHandler", ")", ";", "$document", ".", "off", "(", "'click'", ",", "outsideClickHandler", ")", ";", "elm", ".", "off", "(", "'click'", ",", "buttonClickHandler", ")", ";", "$popover", ".", "isOpen", "=", "false", ";", "displayer_", ".", "cancel", "(", ")", ";", "$popover", ".", "css", "(", "'display'", ",", "'none'", ")", ";", "removeEventListeners", "(", ")", ";", "options", ".", "onClose", "(", "scope", ")", ";", "}", ",", "delay", "*", "1000", ")", ";", "}", "}" ]
Set the display property of the popover to 'none' after |delay| milliseconds. @param delay {Number} The time (in seconds) to wait before set the display property.
[ "Set", "the", "display", "property", "of", "the", "popover", "to", "none", "after", "|delay|", "milliseconds", "." ]
0d768929a4590f9602c87851dca0df54d19d069a
https://github.com/nohros/nsPopover/blob/0d768929a4590f9602c87851dca0df54d19d069a/src/nsPopover.js#L445-L468
train
evenchange4/react-intl-cra
src/index.js
extract
function extract( pattern /* : string */, babelPlugins /* : Array<string> */ = [] ) /* : string */ { const srcPaths = glob.sync(pattern, { absolute: true }); const relativeSrcPaths = glob.sync(pattern); const contents = srcPaths.map(p => fs.readFileSync(p, 'utf-8')); const reqBabelPlugins = babelPlugins.map(b => require.resolve(`babel-plugin-${b}`) ); const messages = contents .map(content => babel.transform(content, { presets: [require.resolve('babel-preset-react-app')], plugins: [ require.resolve('babel-plugin-react-intl'), ...reqBabelPlugins, ], babelrc: false, }) ) .map(R.path(['metadata', 'react-intl', 'messages'])); const result = R.zipWith( (m, r) => m.map(R.assoc('filepath', r)), messages, relativeSrcPaths ) .filter(R.complement(R.isEmpty)) .reduce(R.concat, []); return result; }
javascript
function extract( pattern /* : string */, babelPlugins /* : Array<string> */ = [] ) /* : string */ { const srcPaths = glob.sync(pattern, { absolute: true }); const relativeSrcPaths = glob.sync(pattern); const contents = srcPaths.map(p => fs.readFileSync(p, 'utf-8')); const reqBabelPlugins = babelPlugins.map(b => require.resolve(`babel-plugin-${b}`) ); const messages = contents .map(content => babel.transform(content, { presets: [require.resolve('babel-preset-react-app')], plugins: [ require.resolve('babel-plugin-react-intl'), ...reqBabelPlugins, ], babelrc: false, }) ) .map(R.path(['metadata', 'react-intl', 'messages'])); const result = R.zipWith( (m, r) => m.map(R.assoc('filepath', r)), messages, relativeSrcPaths ) .filter(R.complement(R.isEmpty)) .reduce(R.concat, []); return result; }
[ "function", "extract", "(", "pattern", ",", "babelPlugins", "=", "[", "]", ")", "{", "const", "srcPaths", "=", "glob", ".", "sync", "(", "pattern", ",", "{", "absolute", ":", "true", "}", ")", ";", "const", "relativeSrcPaths", "=", "glob", ".", "sync", "(", "pattern", ")", ";", "const", "contents", "=", "srcPaths", ".", "map", "(", "p", "=>", "fs", ".", "readFileSync", "(", "p", ",", "'utf-8'", ")", ")", ";", "const", "reqBabelPlugins", "=", "babelPlugins", ".", "map", "(", "b", "=>", "require", ".", "resolve", "(", "`", "${", "b", "}", "`", ")", ")", ";", "const", "messages", "=", "contents", ".", "map", "(", "content", "=>", "babel", ".", "transform", "(", "content", ",", "{", "presets", ":", "[", "require", ".", "resolve", "(", "'babel-preset-react-app'", ")", "]", ",", "plugins", ":", "[", "require", ".", "resolve", "(", "'babel-plugin-react-intl'", ")", ",", "...", "reqBabelPlugins", ",", "]", ",", "babelrc", ":", "false", ",", "}", ")", ")", ".", "map", "(", "R", ".", "path", "(", "[", "'metadata'", ",", "'react-intl'", ",", "'messages'", "]", ")", ")", ";", "const", "result", "=", "R", ".", "zipWith", "(", "(", "m", ",", "r", ")", "=>", "m", ".", "map", "(", "R", ".", "assoc", "(", "'filepath'", ",", "r", ")", ")", ",", "messages", ",", "relativeSrcPaths", ")", ".", "filter", "(", "R", ".", "complement", "(", "R", ".", "isEmpty", ")", ")", ".", "reduce", "(", "R", ".", "concat", ",", "[", "]", ")", ";", "return", "result", ";", "}" ]
For babel.transform
[ "For", "babel", ".", "transform" ]
f06afc5c7e462aec5c739c8f7448f81bf473c9e0
https://github.com/evenchange4/react-intl-cra/blob/f06afc5c7e462aec5c739c8f7448f81bf473c9e0/src/index.js#L9-L41
train
spalger/grunt-run
src/tasks/run.js
trackBackgroundProc
function trackBackgroundProc() { runningProcs.push(proc); proc.on('close', function () { remove(runningProcs, proc); clearPid(name); grunt.log.debug('Process ' + name + ' closed.'); }); }
javascript
function trackBackgroundProc() { runningProcs.push(proc); proc.on('close', function () { remove(runningProcs, proc); clearPid(name); grunt.log.debug('Process ' + name + ' closed.'); }); }
[ "function", "trackBackgroundProc", "(", ")", "{", "runningProcs", ".", "push", "(", "proc", ")", ";", "proc", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "remove", "(", "runningProcs", ",", "proc", ")", ";", "clearPid", "(", "name", ")", ";", "grunt", ".", "log", ".", "debug", "(", "'Process '", "+", "name", "+", "' closed.'", ")", ";", "}", ")", ";", "}" ]
we aren't waiting for this proc to close, so setup some tracking stuff
[ "we", "aren", "t", "waiting", "for", "this", "proc", "to", "close", "so", "setup", "some", "tracking", "stuff" ]
f10171d9b736e18538b41a08cab48fa31fec465f
https://github.com/spalger/grunt-run/blob/f10171d9b736e18538b41a08cab48fa31fec465f/src/tasks/run.js#L196-L203
train
spalger/grunt-run
src/tasks/run.js
waitForReadyOutput
function waitForReadyOutput() { function onCloseBeforeReady(exitCode) { done(exitCode && new Error('non-zero exit code ' + exitCode)); } let outputBuffer = ''; function checkChunkForReady(chunk) { outputBuffer += chunk.toString('utf8'); // ensure the buffer doesn't grow out of control if (outputBuffer.length >= opts.readyBufferLength) { outputBuffer = outputBuffer.slice(outputBuffer.length - opts.readyBufferLength); } // don't strip ansi until we check, incase an ansi marker is split across chuncks. if (!opts.ready.test(stripAnsi(outputBuffer))) return; outputBuffer = ''; proc.removeListener('close', onCloseBeforeReady); proc.stdout.removeListener('data', checkChunkForReady); proc.stderr.removeListener('data', checkChunkForReady); done(); } proc.on('close', onCloseBeforeReady); proc.stdout.on('data', checkChunkForReady); proc.stderr.on('data', checkChunkForReady); }
javascript
function waitForReadyOutput() { function onCloseBeforeReady(exitCode) { done(exitCode && new Error('non-zero exit code ' + exitCode)); } let outputBuffer = ''; function checkChunkForReady(chunk) { outputBuffer += chunk.toString('utf8'); // ensure the buffer doesn't grow out of control if (outputBuffer.length >= opts.readyBufferLength) { outputBuffer = outputBuffer.slice(outputBuffer.length - opts.readyBufferLength); } // don't strip ansi until we check, incase an ansi marker is split across chuncks. if (!opts.ready.test(stripAnsi(outputBuffer))) return; outputBuffer = ''; proc.removeListener('close', onCloseBeforeReady); proc.stdout.removeListener('data', checkChunkForReady); proc.stderr.removeListener('data', checkChunkForReady); done(); } proc.on('close', onCloseBeforeReady); proc.stdout.on('data', checkChunkForReady); proc.stderr.on('data', checkChunkForReady); }
[ "function", "waitForReadyOutput", "(", ")", "{", "function", "onCloseBeforeReady", "(", "exitCode", ")", "{", "done", "(", "exitCode", "&&", "new", "Error", "(", "'non-zero exit code '", "+", "exitCode", ")", ")", ";", "}", "let", "outputBuffer", "=", "''", ";", "function", "checkChunkForReady", "(", "chunk", ")", "{", "outputBuffer", "+=", "chunk", ".", "toString", "(", "'utf8'", ")", ";", "if", "(", "outputBuffer", ".", "length", ">=", "opts", ".", "readyBufferLength", ")", "{", "outputBuffer", "=", "outputBuffer", ".", "slice", "(", "outputBuffer", ".", "length", "-", "opts", ".", "readyBufferLength", ")", ";", "}", "if", "(", "!", "opts", ".", "ready", ".", "test", "(", "stripAnsi", "(", "outputBuffer", ")", ")", ")", "return", ";", "outputBuffer", "=", "''", ";", "proc", ".", "removeListener", "(", "'close'", ",", "onCloseBeforeReady", ")", ";", "proc", ".", "stdout", ".", "removeListener", "(", "'data'", ",", "checkChunkForReady", ")", ";", "proc", ".", "stderr", ".", "removeListener", "(", "'data'", ",", "checkChunkForReady", ")", ";", "done", "(", ")", ";", "}", "proc", ".", "on", "(", "'close'", ",", "onCloseBeforeReady", ")", ";", "proc", ".", "stdout", ".", "on", "(", "'data'", ",", "checkChunkForReady", ")", ";", "proc", ".", "stderr", ".", "on", "(", "'data'", ",", "checkChunkForReady", ")", ";", "}" ]
we are scanning the output for a specific regular expression
[ "we", "are", "scanning", "the", "output", "for", "a", "specific", "regular", "expression" ]
f10171d9b736e18538b41a08cab48fa31fec465f
https://github.com/spalger/grunt-run/blob/f10171d9b736e18538b41a08cab48fa31fec465f/src/tasks/run.js#L206-L234
train
pugjs/pug-lexer
index.js
Lexer
function Lexer(str, options) { options = options || {}; if (typeof str !== 'string') { throw new Error('Expected source code to be a string but got "' + (typeof str) + '"') } if (typeof options !== 'object') { throw new Error('Expected "options" to be an object but got "' + (typeof options) + '"') } //Strip any UTF-8 BOM off of the start of `str`, if it exists. str = str.replace(/^\uFEFF/, ''); this.input = str.replace(/\r\n|\r/g, '\n'); this.originalInput = this.input; this.filename = options.filename; this.interpolated = options.interpolated || false; this.lineno = options.startingLine || 1; this.colno = options.startingColumn || 1; this.plugins = options.plugins || []; this.indentStack = [0]; this.indentRe = null; // If #{} or !{} syntax is allowed when adding text this.interpolationAllowed = true; this.tokens = []; this.ended = false; }
javascript
function Lexer(str, options) { options = options || {}; if (typeof str !== 'string') { throw new Error('Expected source code to be a string but got "' + (typeof str) + '"') } if (typeof options !== 'object') { throw new Error('Expected "options" to be an object but got "' + (typeof options) + '"') } //Strip any UTF-8 BOM off of the start of `str`, if it exists. str = str.replace(/^\uFEFF/, ''); this.input = str.replace(/\r\n|\r/g, '\n'); this.originalInput = this.input; this.filename = options.filename; this.interpolated = options.interpolated || false; this.lineno = options.startingLine || 1; this.colno = options.startingColumn || 1; this.plugins = options.plugins || []; this.indentStack = [0]; this.indentRe = null; // If #{} or !{} syntax is allowed when adding text this.interpolationAllowed = true; this.tokens = []; this.ended = false; }
[ "function", "Lexer", "(", "str", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "typeof", "str", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Expected source code to be a string but got \"'", "+", "(", "typeof", "str", ")", "+", "'\"'", ")", "}", "if", "(", "typeof", "options", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "'Expected \"options\" to be an object but got \"'", "+", "(", "typeof", "options", ")", "+", "'\"'", ")", "}", "str", "=", "str", ".", "replace", "(", "/", "^\\uFEFF", "/", ",", "''", ")", ";", "this", ".", "input", "=", "str", ".", "replace", "(", "/", "\\r\\n|\\r", "/", "g", ",", "'\\n'", ")", ";", "\\n", "this", ".", "originalInput", "=", "this", ".", "input", ";", "this", ".", "filename", "=", "options", ".", "filename", ";", "this", ".", "interpolated", "=", "options", ".", "interpolated", "||", "false", ";", "this", ".", "lineno", "=", "options", ".", "startingLine", "||", "1", ";", "this", ".", "colno", "=", "options", ".", "startingColumn", "||", "1", ";", "this", ".", "plugins", "=", "options", ".", "plugins", "||", "[", "]", ";", "this", ".", "indentStack", "=", "[", "0", "]", ";", "this", ".", "indentRe", "=", "null", ";", "this", ".", "interpolationAllowed", "=", "true", ";", "this", ".", "tokens", "=", "[", "]", ";", "}" ]
Initialize `Lexer` with the given `str`. @param {String} str @param {String} filename @api private
[ "Initialize", "Lexer", "with", "the", "given", "str", "." ]
035c891823b2193121421dc3db660810deac6b3e
https://github.com/pugjs/pug-lexer/blob/035c891823b2193121421dc3db660810deac6b3e/index.js#L23-L47
train
pugjs/pug-lexer
index.js
function(type, val){ var res = {type: type, line: this.lineno, col: this.colno}; if (val !== undefined) res.val = val; return res; }
javascript
function(type, val){ var res = {type: type, line: this.lineno, col: this.colno}; if (val !== undefined) res.val = val; return res; }
[ "function", "(", "type", ",", "val", ")", "{", "var", "res", "=", "{", "type", ":", "type", ",", "line", ":", "this", ".", "lineno", ",", "col", ":", "this", ".", "colno", "}", ";", "if", "(", "val", "!==", "undefined", ")", "res", ".", "val", "=", "val", ";", "return", "res", ";", "}" ]
Construct a token with the given `type` and `val`. @param {String} type @param {String} val @return {Object} @api private
[ "Construct", "a", "token", "with", "the", "given", "type", "and", "val", "." ]
035c891823b2193121421dc3db660810deac6b3e
https://github.com/pugjs/pug-lexer/blob/035c891823b2193121421dc3db660810deac6b3e/index.js#L108-L114
train
pugjs/pug-lexer
index.js
function(regexp, type){ var captures; if (captures = regexp.exec(this.input)) { var len = captures[0].length; var val = captures[1]; var diff = len - (val ? val.length : 0); var tok = this.tok(type, val); this.consume(len); this.incrementColumn(diff); return tok; } }
javascript
function(regexp, type){ var captures; if (captures = regexp.exec(this.input)) { var len = captures[0].length; var val = captures[1]; var diff = len - (val ? val.length : 0); var tok = this.tok(type, val); this.consume(len); this.incrementColumn(diff); return tok; } }
[ "function", "(", "regexp", ",", "type", ")", "{", "var", "captures", ";", "if", "(", "captures", "=", "regexp", ".", "exec", "(", "this", ".", "input", ")", ")", "{", "var", "len", "=", "captures", "[", "0", "]", ".", "length", ";", "var", "val", "=", "captures", "[", "1", "]", ";", "var", "diff", "=", "len", "-", "(", "val", "?", "val", ".", "length", ":", "0", ")", ";", "var", "tok", "=", "this", ".", "tok", "(", "type", ",", "val", ")", ";", "this", ".", "consume", "(", "len", ")", ";", "this", ".", "incrementColumn", "(", "diff", ")", ";", "return", "tok", ";", "}", "}" ]
Scan for `type` with the given `regexp`. @param {String} type @param {RegExp} regexp @return {Object} @api private
[ "Scan", "for", "type", "with", "the", "given", "regexp", "." ]
035c891823b2193121421dc3db660810deac6b3e
https://github.com/pugjs/pug-lexer/blob/035c891823b2193121421dc3db660810deac6b3e/index.js#L159-L170
train
pugjs/pug-lexer
index.js
function() { if (this.input.length) return; if (this.interpolated) { this.error('NO_END_BRACKET', 'End of line was reached with no closing bracket for interpolation.'); } for (var i = 0; this.indentStack[i]; i++) { this.tokens.push(this.tok('outdent')); } this.tokens.push(this.tok('eos')); this.ended = true; return true; }
javascript
function() { if (this.input.length) return; if (this.interpolated) { this.error('NO_END_BRACKET', 'End of line was reached with no closing bracket for interpolation.'); } for (var i = 0; this.indentStack[i]; i++) { this.tokens.push(this.tok('outdent')); } this.tokens.push(this.tok('eos')); this.ended = true; return true; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "input", ".", "length", ")", "return", ";", "if", "(", "this", ".", "interpolated", ")", "{", "this", ".", "error", "(", "'NO_END_BRACKET'", ",", "'End of line was reached with no closing bracket for interpolation.'", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "this", ".", "indentStack", "[", "i", "]", ";", "i", "++", ")", "{", "this", ".", "tokens", ".", "push", "(", "this", ".", "tok", "(", "'outdent'", ")", ")", ";", "}", "this", ".", "tokens", ".", "push", "(", "this", ".", "tok", "(", "'eos'", ")", ")", ";", "this", ".", "ended", "=", "true", ";", "return", "true", ";", "}" ]
end-of-source.
[ "end", "-", "of", "-", "source", "." ]
035c891823b2193121421dc3db660810deac6b3e
https://github.com/pugjs/pug-lexer/blob/035c891823b2193121421dc3db660810deac6b3e/index.js#L272-L283
train
pugjs/pug-lexer
index.js
function() { if (/^#\{/.test(this.input)) { var match = this.bracketExpression(1); this.consume(match.end + 1); var tok = this.tok('interpolation', match.src); this.tokens.push(tok); this.incrementColumn(2); // '#{' this.assertExpression(match.src); var splitted = match.src.split('\n'); var lines = splitted.length - 1; this.incrementLine(lines); this.incrementColumn(splitted[lines].length + 1); // + 1 → '}' return true; } }
javascript
function() { if (/^#\{/.test(this.input)) { var match = this.bracketExpression(1); this.consume(match.end + 1); var tok = this.tok('interpolation', match.src); this.tokens.push(tok); this.incrementColumn(2); // '#{' this.assertExpression(match.src); var splitted = match.src.split('\n'); var lines = splitted.length - 1; this.incrementLine(lines); this.incrementColumn(splitted[lines].length + 1); // + 1 → '}' return true; } }
[ "function", "(", ")", "{", "if", "(", "/", "^#\\{", "/", ".", "test", "(", "this", ".", "input", ")", ")", "{", "var", "match", "=", "this", ".", "bracketExpression", "(", "1", ")", ";", "this", ".", "consume", "(", "match", ".", "end", "+", "1", ")", ";", "var", "tok", "=", "this", ".", "tok", "(", "'interpolation'", ",", "match", ".", "src", ")", ";", "this", ".", "tokens", ".", "push", "(", "tok", ")", ";", "this", ".", "incrementColumn", "(", "2", ")", ";", "this", ".", "assertExpression", "(", "match", ".", "src", ")", ";", "var", "splitted", "=", "match", ".", "src", ".", "split", "(", "'\\n'", ")", ";", "\\n", "var", "lines", "=", "splitted", ".", "length", "-", "1", ";", "this", ".", "incrementLine", "(", "lines", ")", ";", "this", ".", "incrementColumn", "(", "splitted", "[", "lines", "]", ".", "length", "+", "1", ")", ";", "}", "}" ]
Interpolated tag.
[ "Interpolated", "tag", "." ]
035c891823b2193121421dc3db660810deac6b3e
https://github.com/pugjs/pug-lexer/blob/035c891823b2193121421dc3db660810deac6b3e/index.js#L320-L335
train
pugjs/pug-lexer
index.js
function() { var captures; if (captures = /^(?:block +)?prepend +([^\n]+)/.exec(this.input)) { var name = captures[1].trim(); var comment = ''; if (name.indexOf('//') !== -1) { comment = '//' + name.split('//').slice(1).join('//'); name = name.split('//')[0].trim(); } if (!name) return; this.consume(captures[0].length - comment.length); var tok = this.tok('block', name); tok.mode = 'prepend'; this.tokens.push(tok); return true; } }
javascript
function() { var captures; if (captures = /^(?:block +)?prepend +([^\n]+)/.exec(this.input)) { var name = captures[1].trim(); var comment = ''; if (name.indexOf('//') !== -1) { comment = '//' + name.split('//').slice(1).join('//'); name = name.split('//')[0].trim(); } if (!name) return; this.consume(captures[0].length - comment.length); var tok = this.tok('block', name); tok.mode = 'prepend'; this.tokens.push(tok); return true; } }
[ "function", "(", ")", "{", "var", "captures", ";", "if", "(", "captures", "=", "/", "^(?:block +)?prepend +([^\\n]+)", "/", ".", "exec", "(", "this", ".", "input", ")", ")", "{", "var", "name", "=", "captures", "[", "1", "]", ".", "trim", "(", ")", ";", "var", "comment", "=", "''", ";", "if", "(", "name", ".", "indexOf", "(", "'//'", ")", "!==", "-", "1", ")", "{", "comment", "=", "'//'", "+", "name", ".", "split", "(", "'//'", ")", ".", "slice", "(", "1", ")", ".", "join", "(", "'//'", ")", ";", "name", "=", "name", ".", "split", "(", "'//'", ")", "[", "0", "]", ".", "trim", "(", ")", ";", "}", "if", "(", "!", "name", ")", "return", ";", "this", ".", "consume", "(", "captures", "[", "0", "]", ".", "length", "-", "comment", ".", "length", ")", ";", "var", "tok", "=", "this", ".", "tok", "(", "'block'", ",", "name", ")", ";", "tok", ".", "mode", "=", "'prepend'", ";", "this", ".", "tokens", ".", "push", "(", "tok", ")", ";", "return", "true", ";", "}", "}" ]
Block prepend.
[ "Block", "prepend", "." ]
035c891823b2193121421dc3db660810deac6b3e
https://github.com/pugjs/pug-lexer/blob/035c891823b2193121421dc3db660810deac6b3e/index.js#L590-L606
train
pugjs/pug-lexer
index.js
function(){ var tok, captures, increment; if (captures = /^\+(\s*)(([-\w]+)|(#\{))/.exec(this.input)) { // try to consume simple or interpolated call if (captures[3]) { // simple call increment = captures[0].length; this.consume(increment); tok = this.tok('call', captures[3]); } else { // interpolated call var match = this.bracketExpression(2 + captures[1].length); increment = match.end + 1; this.consume(increment); this.assertExpression(match.src); tok = this.tok('call', '#{'+match.src+'}'); } this.incrementColumn(increment); tok.args = null; // Check for args (not attributes) if (captures = /^ *\(/.exec(this.input)) { var range = this.bracketExpression(captures[0].length - 1); if (!/^\s*[-\w]+ *=/.test(range.src)) { // not attributes this.incrementColumn(1); this.consume(range.end + 1); tok.args = range.src; this.assertExpression('[' + tok.args + ']'); for (var i = 0; i <= tok.args.length; i++) { if (tok.args[i] === '\n') { this.incrementLine(1); } else { this.incrementColumn(1); } } } } this.tokens.push(tok); return true; } }
javascript
function(){ var tok, captures, increment; if (captures = /^\+(\s*)(([-\w]+)|(#\{))/.exec(this.input)) { // try to consume simple or interpolated call if (captures[3]) { // simple call increment = captures[0].length; this.consume(increment); tok = this.tok('call', captures[3]); } else { // interpolated call var match = this.bracketExpression(2 + captures[1].length); increment = match.end + 1; this.consume(increment); this.assertExpression(match.src); tok = this.tok('call', '#{'+match.src+'}'); } this.incrementColumn(increment); tok.args = null; // Check for args (not attributes) if (captures = /^ *\(/.exec(this.input)) { var range = this.bracketExpression(captures[0].length - 1); if (!/^\s*[-\w]+ *=/.test(range.src)) { // not attributes this.incrementColumn(1); this.consume(range.end + 1); tok.args = range.src; this.assertExpression('[' + tok.args + ']'); for (var i = 0; i <= tok.args.length; i++) { if (tok.args[i] === '\n') { this.incrementLine(1); } else { this.incrementColumn(1); } } } } this.tokens.push(tok); return true; } }
[ "function", "(", ")", "{", "var", "tok", ",", "captures", ",", "increment", ";", "if", "(", "captures", "=", "/", "^\\+(\\s*)(([-\\w]+)|(#\\{))", "/", ".", "exec", "(", "this", ".", "input", ")", ")", "{", "if", "(", "captures", "[", "3", "]", ")", "{", "increment", "=", "captures", "[", "0", "]", ".", "length", ";", "this", ".", "consume", "(", "increment", ")", ";", "tok", "=", "this", ".", "tok", "(", "'call'", ",", "captures", "[", "3", "]", ")", ";", "}", "else", "{", "var", "match", "=", "this", ".", "bracketExpression", "(", "2", "+", "captures", "[", "1", "]", ".", "length", ")", ";", "increment", "=", "match", ".", "end", "+", "1", ";", "this", ".", "consume", "(", "increment", ")", ";", "this", ".", "assertExpression", "(", "match", ".", "src", ")", ";", "tok", "=", "this", ".", "tok", "(", "'call'", ",", "'#{'", "+", "match", ".", "src", "+", "'}'", ")", ";", "}", "this", ".", "incrementColumn", "(", "increment", ")", ";", "tok", ".", "args", "=", "null", ";", "if", "(", "captures", "=", "/", "^ *\\(", "/", ".", "exec", "(", "this", ".", "input", ")", ")", "{", "var", "range", "=", "this", ".", "bracketExpression", "(", "captures", "[", "0", "]", ".", "length", "-", "1", ")", ";", "if", "(", "!", "/", "^\\s*[-\\w]+ *=", "/", ".", "test", "(", "range", ".", "src", ")", ")", "{", "this", ".", "incrementColumn", "(", "1", ")", ";", "this", ".", "consume", "(", "range", ".", "end", "+", "1", ")", ";", "tok", ".", "args", "=", "range", ".", "src", ";", "this", ".", "assertExpression", "(", "'['", "+", "tok", ".", "args", "+", "']'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<=", "tok", ".", "args", ".", "length", ";", "i", "++", ")", "{", "if", "(", "tok", ".", "args", "[", "i", "]", "===", "'\\n'", ")", "\\n", "else", "{", "this", ".", "incrementLine", "(", "1", ")", ";", "}", "}", "}", "}", "{", "this", ".", "incrementColumn", "(", "1", ")", ";", "}", "this", ".", "tokens", ".", "push", "(", "tok", ")", ";", "}", "}" ]
Call mixin.
[ "Call", "mixin", "." ]
035c891823b2193121421dc3db660810deac6b3e
https://github.com/pugjs/pug-lexer/blob/035c891823b2193121421dc3db660810deac6b3e/index.js#L779-L821
train
pugjs/pug-lexer
index.js
function() { var tok if (tok = this.scanEndOfLine(/^-/, 'blockcode')) { this.tokens.push(tok); this.interpolationAllowed = false; this.callLexerFunction('pipelessText'); return true; } }
javascript
function() { var tok if (tok = this.scanEndOfLine(/^-/, 'blockcode')) { this.tokens.push(tok); this.interpolationAllowed = false; this.callLexerFunction('pipelessText'); return true; } }
[ "function", "(", ")", "{", "var", "tok", "if", "(", "tok", "=", "this", ".", "scanEndOfLine", "(", "/", "^-", "/", ",", "'blockcode'", ")", ")", "{", "this", ".", "tokens", ".", "push", "(", "tok", ")", ";", "this", ".", "interpolationAllowed", "=", "false", ";", "this", ".", "callLexerFunction", "(", "'pipelessText'", ")", ";", "return", "true", ";", "}", "}" ]
Block code.
[ "Block", "code", "." ]
035c891823b2193121421dc3db660810deac6b3e
https://github.com/pugjs/pug-lexer/blob/035c891823b2193121421dc3db660810deac6b3e/index.js#L992-L1000
train
pugjs/pug-lexer
index.js
function() { var captures = this.scanIndentation(); if (captures) { var indents = captures[1].length; this.incrementLine(1); this.consume(indents + 1); if (' ' == this.input[0] || '\t' == this.input[0]) { this.error('INVALID_INDENTATION', 'Invalid indentation, you can use tabs or spaces but not both'); } // blank line if ('\n' == this.input[0]) { this.interpolationAllowed = true; return this.tok('newline'); } // outdent if (indents < this.indentStack[0]) { while (this.indentStack[0] > indents) { if (this.indentStack[1] < indents) { this.error('INCONSISTENT_INDENTATION', 'Inconsistent indentation. Expecting either ' + this.indentStack[1] + ' or ' + this.indentStack[0] + ' spaces/tabs.'); } this.colno = this.indentStack[1] + 1; this.tokens.push(this.tok('outdent')); this.indentStack.shift(); } // indent } else if (indents && indents != this.indentStack[0]) { this.tokens.push(this.tok('indent', indents)); this.colno = 1 + indents; this.indentStack.unshift(indents); // newline } else { this.tokens.push(this.tok('newline')); this.colno = 1 + (this.indentStack[0] || 0); } this.interpolationAllowed = true; return true; } }
javascript
function() { var captures = this.scanIndentation(); if (captures) { var indents = captures[1].length; this.incrementLine(1); this.consume(indents + 1); if (' ' == this.input[0] || '\t' == this.input[0]) { this.error('INVALID_INDENTATION', 'Invalid indentation, you can use tabs or spaces but not both'); } // blank line if ('\n' == this.input[0]) { this.interpolationAllowed = true; return this.tok('newline'); } // outdent if (indents < this.indentStack[0]) { while (this.indentStack[0] > indents) { if (this.indentStack[1] < indents) { this.error('INCONSISTENT_INDENTATION', 'Inconsistent indentation. Expecting either ' + this.indentStack[1] + ' or ' + this.indentStack[0] + ' spaces/tabs.'); } this.colno = this.indentStack[1] + 1; this.tokens.push(this.tok('outdent')); this.indentStack.shift(); } // indent } else if (indents && indents != this.indentStack[0]) { this.tokens.push(this.tok('indent', indents)); this.colno = 1 + indents; this.indentStack.unshift(indents); // newline } else { this.tokens.push(this.tok('newline')); this.colno = 1 + (this.indentStack[0] || 0); } this.interpolationAllowed = true; return true; } }
[ "function", "(", ")", "{", "var", "captures", "=", "this", ".", "scanIndentation", "(", ")", ";", "if", "(", "captures", ")", "{", "var", "indents", "=", "captures", "[", "1", "]", ".", "length", ";", "this", ".", "incrementLine", "(", "1", ")", ";", "this", ".", "consume", "(", "indents", "+", "1", ")", ";", "if", "(", "' '", "==", "this", ".", "input", "[", "0", "]", "||", "'\\t'", "==", "\\t", ")", "this", ".", "input", "[", "0", "]", "{", "this", ".", "error", "(", "'INVALID_INDENTATION'", ",", "'Invalid indentation, you can use tabs or spaces but not both'", ")", ";", "}", "if", "(", "'\\n'", "==", "\\n", ")", "this", ".", "input", "[", "0", "]", "{", "this", ".", "interpolationAllowed", "=", "true", ";", "return", "this", ".", "tok", "(", "'newline'", ")", ";", "}", "if", "(", "indents", "<", "this", ".", "indentStack", "[", "0", "]", ")", "{", "while", "(", "this", ".", "indentStack", "[", "0", "]", ">", "indents", ")", "{", "if", "(", "this", ".", "indentStack", "[", "1", "]", "<", "indents", ")", "{", "this", ".", "error", "(", "'INCONSISTENT_INDENTATION'", ",", "'Inconsistent indentation. Expecting either '", "+", "this", ".", "indentStack", "[", "1", "]", "+", "' or '", "+", "this", ".", "indentStack", "[", "0", "]", "+", "' spaces/tabs.'", ")", ";", "}", "this", ".", "colno", "=", "this", ".", "indentStack", "[", "1", "]", "+", "1", ";", "this", ".", "tokens", ".", "push", "(", "this", ".", "tok", "(", "'outdent'", ")", ")", ";", "this", ".", "indentStack", ".", "shift", "(", ")", ";", "}", "}", "else", "if", "(", "indents", "&&", "indents", "!=", "this", ".", "indentStack", "[", "0", "]", ")", "{", "this", ".", "tokens", ".", "push", "(", "this", ".", "tok", "(", "'indent'", ",", "indents", ")", ")", ";", "this", ".", "colno", "=", "1", "+", "indents", ";", "this", ".", "indentStack", ".", "unshift", "(", "indents", ")", ";", "}", "else", "{", "this", ".", "tokens", ".", "push", "(", "this", ".", "tok", "(", "'newline'", ")", ")", ";", "this", ".", "colno", "=", "1", "+", "(", "this", ".", "indentStack", "[", "0", "]", "||", "0", ")", ";", "}", "}", "}" ]
Indent | Outdent | Newline.
[ "Indent", "|", "Outdent", "|", "Newline", "." ]
035c891823b2193121421dc3db660810deac6b3e
https://github.com/pugjs/pug-lexer/blob/035c891823b2193121421dc3db660810deac6b3e/index.js#L1185-L1228
train
aerospike-unofficial/aerospike-session-store-expressjs
lib/aerospike_store.js
AerospikeStore
function AerospikeStore (options) { if (!(this instanceof AerospikeStore)) { throw new TypeError('Cannot call AerospikeStore constructor as a function') } options = options || {} Store.call(this, options) this.as_namespace = options.namespace || 'test' this.as_set = options.set || 'express-session' this.ttl = options.ttl this.mapper = options.mapper || new DataMapper() if (options.serializer) { throw new Error('The `serializer` option is no longer supported - supply a custom data mapper instead.') } if (options.client) { this.client = options.client } else { this.client = Aerospike.client(options) this.client.connect(error => { if (error) { debug('ERROR - %s', error.message) process.nextTick(() => this._onDisconnected()) } else { process.nextTick(() => this._onConnected()) } }) } this.connected = false this.client.on('nodeAdded', () => this._onConnected()) this.client.on('disconnected', () => this._onDisconnected()) }
javascript
function AerospikeStore (options) { if (!(this instanceof AerospikeStore)) { throw new TypeError('Cannot call AerospikeStore constructor as a function') } options = options || {} Store.call(this, options) this.as_namespace = options.namespace || 'test' this.as_set = options.set || 'express-session' this.ttl = options.ttl this.mapper = options.mapper || new DataMapper() if (options.serializer) { throw new Error('The `serializer` option is no longer supported - supply a custom data mapper instead.') } if (options.client) { this.client = options.client } else { this.client = Aerospike.client(options) this.client.connect(error => { if (error) { debug('ERROR - %s', error.message) process.nextTick(() => this._onDisconnected()) } else { process.nextTick(() => this._onConnected()) } }) } this.connected = false this.client.on('nodeAdded', () => this._onConnected()) this.client.on('disconnected', () => this._onDisconnected()) }
[ "function", "AerospikeStore", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AerospikeStore", ")", ")", "{", "throw", "new", "TypeError", "(", "'Cannot call AerospikeStore constructor as a function'", ")", "}", "options", "=", "options", "||", "{", "}", "Store", ".", "call", "(", "this", ",", "options", ")", "this", ".", "as_namespace", "=", "options", ".", "namespace", "||", "'test'", "this", ".", "as_set", "=", "options", ".", "set", "||", "'express-session'", "this", ".", "ttl", "=", "options", ".", "ttl", "this", ".", "mapper", "=", "options", ".", "mapper", "||", "new", "DataMapper", "(", ")", "if", "(", "options", ".", "serializer", ")", "{", "throw", "new", "Error", "(", "'The `serializer` option is no longer supported - supply a custom data mapper instead.'", ")", "}", "if", "(", "options", ".", "client", ")", "{", "this", ".", "client", "=", "options", ".", "client", "}", "else", "{", "this", ".", "client", "=", "Aerospike", ".", "client", "(", "options", ")", "this", ".", "client", ".", "connect", "(", "error", "=>", "{", "if", "(", "error", ")", "{", "debug", "(", "'ERROR - %s'", ",", "error", ".", "message", ")", "process", ".", "nextTick", "(", "(", ")", "=>", "this", ".", "_onDisconnected", "(", ")", ")", "}", "else", "{", "process", ".", "nextTick", "(", "(", ")", "=>", "this", ".", "_onConnected", "(", ")", ")", "}", "}", ")", "}", "this", ".", "connected", "=", "false", "this", ".", "client", ".", "on", "(", "'nodeAdded'", ",", "(", ")", "=>", "this", ".", "_onConnected", "(", ")", ")", "this", ".", "client", ".", "on", "(", "'disconnected'", ",", "(", ")", "=>", "this", ".", "_onDisconnected", "(", ")", ")", "}" ]
Return the `AerospikeStore` extending `express`'s session Store. @param {Object} express session @return {Function} @public
[ "Return", "the", "AerospikeStore", "extending", "express", "s", "session", "Store", "." ]
ffaaf48208cb178aa7dde07bf586033cdad5b348
https://github.com/aerospike-unofficial/aerospike-session-store-expressjs/blob/ffaaf48208cb178aa7dde07bf586033cdad5b348/lib/aerospike_store.js#L35-L69
train
isleofcode/ember-cordova
lib/utils/cordova-validator.js
function(json, name, type) { if (json && json.widget) { var nodes = json.widget[type]; if (!!nodes && isArray(nodes)) { for (var i = 0; i < nodes.length; i++) { if (nameIsMatch(nodes[i], name)) { return true; } } } } return false; }
javascript
function(json, name, type) { if (json && json.widget) { var nodes = json.widget[type]; if (!!nodes && isArray(nodes)) { for (var i = 0; i < nodes.length; i++) { if (nameIsMatch(nodes[i], name)) { return true; } } } } return false; }
[ "function", "(", "json", ",", "name", ",", "type", ")", "{", "if", "(", "json", "&&", "json", ".", "widget", ")", "{", "var", "nodes", "=", "json", ".", "widget", "[", "type", "]", ";", "if", "(", "!", "!", "nodes", "&&", "isArray", "(", "nodes", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "nodes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "nameIsMatch", "(", "nodes", "[", "i", "]", ",", "name", ")", ")", "{", "return", "true", ";", "}", "}", "}", "}", "return", "false", ";", "}" ]
type == platform || plugin name == 'ios', 'android', 'cordova-plugin-camera'
[ "type", "==", "platform", "||", "plugin", "name", "==", "ios", "android", "cordova", "-", "plugin", "-", "camera" ]
9c21376e416ffa21bbeffd3e1854d9b508a499de
https://github.com/isleofcode/ember-cordova/blob/9c21376e416ffa21bbeffd3e1854d9b508a499de/lib/utils/cordova-validator.js#L26-L40
train
mongodb-js/query-parser
lib/index.js
isCollationValid
function isCollationValid(collation) { let isValid = true; _.forIn(collation, function(value, key) { const itemIndex = _.findIndex(COLLATION_OPTIONS, key); if (itemIndex === -1) { debug('Collation "%s" is invalid bc of its keys', collation); isValid = false; } if (COLLATION_OPTIONS[itemIndex][key].includes(value) === false) { debug('Collation "%s" is invalid bc of its values', collation); isValid = false; } }); return isValid ? collation : false; }
javascript
function isCollationValid(collation) { let isValid = true; _.forIn(collation, function(value, key) { const itemIndex = _.findIndex(COLLATION_OPTIONS, key); if (itemIndex === -1) { debug('Collation "%s" is invalid bc of its keys', collation); isValid = false; } if (COLLATION_OPTIONS[itemIndex][key].includes(value) === false) { debug('Collation "%s" is invalid bc of its values', collation); isValid = false; } }); return isValid ? collation : false; }
[ "function", "isCollationValid", "(", "collation", ")", "{", "let", "isValid", "=", "true", ";", "_", ".", "forIn", "(", "collation", ",", "function", "(", "value", ",", "key", ")", "{", "const", "itemIndex", "=", "_", ".", "findIndex", "(", "COLLATION_OPTIONS", ",", "key", ")", ";", "if", "(", "itemIndex", "===", "-", "1", ")", "{", "debug", "(", "'Collation \"%s\" is invalid bc of its keys'", ",", "collation", ")", ";", "isValid", "=", "false", ";", "}", "if", "(", "COLLATION_OPTIONS", "[", "itemIndex", "]", "[", "key", "]", ".", "includes", "(", "value", ")", "===", "false", ")", "{", "debug", "(", "'Collation \"%s\" is invalid bc of its values'", ",", "collation", ")", ";", "isValid", "=", "false", ";", "}", "}", ")", ";", "return", "isValid", "?", "collation", ":", "false", ";", "}" ]
Validation of collation object keys and values. @param {Object} collation @return {Boolean|Object} false if not valid, otherwise the parsed project.
[ "Validation", "of", "collation", "object", "keys", "and", "values", "." ]
93d46bd5fc29363a7ce5c01768e28bb514bcb567
https://github.com/mongodb-js/query-parser/blob/93d46bd5fc29363a7ce5c01768e28bb514bcb567/lib/index.js#L218-L232
train
tbranyen/combyne
lib/compiler.js
normalizeIdentifier
function normalizeIdentifier(identifier) { if (identifier === ".") { // '.' might be referencing either the root or a locally scoped variable // called '.'. So try for the locally scoped variable first and then // default to the root return "(data['.'] || data)"; } return "data" + identifier.split(".").map(function(property) { return property ? "['" + property + "']" : ""; }).join(""); }
javascript
function normalizeIdentifier(identifier) { if (identifier === ".") { // '.' might be referencing either the root or a locally scoped variable // called '.'. So try for the locally scoped variable first and then // default to the root return "(data['.'] || data)"; } return "data" + identifier.split(".").map(function(property) { return property ? "['" + property + "']" : ""; }).join(""); }
[ "function", "normalizeIdentifier", "(", "identifier", ")", "{", "if", "(", "identifier", "===", "\".\"", ")", "{", "return", "\"(data['.'] || data)\"", ";", "}", "return", "\"data\"", "+", "identifier", ".", "split", "(", "\".\"", ")", ".", "map", "(", "function", "(", "property", ")", "{", "return", "property", "?", "\"['\"", "+", "property", "+", "\"']\"", ":", "\"\"", ";", "}", ")", ".", "join", "(", "\"\"", ")", ";", "}" ]
Normalizes properties in the identifier to be looked up via hash-style instead of dot-notation. @private @param {string} identifier - The identifier to normalize. @returns {string} The identifier normalized.
[ "Normalizes", "properties", "in", "the", "identifier", "to", "be", "looked", "up", "via", "hash", "-", "style", "instead", "of", "dot", "-", "notation", "." ]
0d921dd183be34c33abe89ad33fea89c2ba16620
https://github.com/tbranyen/combyne/blob/0d921dd183be34c33abe89ad33fea89c2ba16620/lib/compiler.js#L68-L79
train
tbranyen/combyne
lib/compiler.js
Compiler
function Compiler(tree) { this.tree = tree; this.string = ""; // Optimization pass will flatten large templates to result in faster // rendering. var nodes = this.optimize(this.tree.nodes); var compiledSource = this.process(nodes); // The compiled function body. var body = []; // If there is a function, concatenate it to the default empty value. if (compiledSource) { compiledSource = " + " + compiledSource; } // Include map and its dependencies. if (compiledSource.indexOf("map(") > -1) { body.push(createObject, type, map); } // Include encode and its dependencies. if (compiledSource.indexOf("encode(") > -1) { body.push(type, encode); } // The compiled function body. body = body.concat([ // Return the evaluated contents. "return ''" + compiledSource ]).join(";\n"); // Create the JavaScript function from the source code. this.func = new Function("data", "template", body); // toString the function to get its raw source and expose. this.source = [ "{", "_partials: {},", "_filters: {},", "getPartial: " + getPartial + ",", "getFilter: " + getFilter + ",", "registerPartial: " + registerPartial + ",", "registerFilter: " + registerFilter + ",", "render: function(data) {", "try {", "return " + this.func + "(data, this);", "} catch (ex) {", type, encode, "console.error(ex);", "return '<pre>' + encode(ex + ex.stack) + '</pre>';", "}", "}", "}" ].join("\n"); }
javascript
function Compiler(tree) { this.tree = tree; this.string = ""; // Optimization pass will flatten large templates to result in faster // rendering. var nodes = this.optimize(this.tree.nodes); var compiledSource = this.process(nodes); // The compiled function body. var body = []; // If there is a function, concatenate it to the default empty value. if (compiledSource) { compiledSource = " + " + compiledSource; } // Include map and its dependencies. if (compiledSource.indexOf("map(") > -1) { body.push(createObject, type, map); } // Include encode and its dependencies. if (compiledSource.indexOf("encode(") > -1) { body.push(type, encode); } // The compiled function body. body = body.concat([ // Return the evaluated contents. "return ''" + compiledSource ]).join(";\n"); // Create the JavaScript function from the source code. this.func = new Function("data", "template", body); // toString the function to get its raw source and expose. this.source = [ "{", "_partials: {},", "_filters: {},", "getPartial: " + getPartial + ",", "getFilter: " + getFilter + ",", "registerPartial: " + registerPartial + ",", "registerFilter: " + registerFilter + ",", "render: function(data) {", "try {", "return " + this.func + "(data, this);", "} catch (ex) {", type, encode, "console.error(ex);", "return '<pre>' + encode(ex + ex.stack) + '</pre>';", "}", "}", "}" ].join("\n"); }
[ "function", "Compiler", "(", "tree", ")", "{", "this", ".", "tree", "=", "tree", ";", "this", ".", "string", "=", "\"\"", ";", "var", "nodes", "=", "this", ".", "optimize", "(", "this", ".", "tree", ".", "nodes", ")", ";", "var", "compiledSource", "=", "this", ".", "process", "(", "nodes", ")", ";", "var", "body", "=", "[", "]", ";", "if", "(", "compiledSource", ")", "{", "compiledSource", "=", "\" + \"", "+", "compiledSource", ";", "}", "if", "(", "compiledSource", ".", "indexOf", "(", "\"map(\"", ")", ">", "-", "1", ")", "{", "body", ".", "push", "(", "createObject", ",", "type", ",", "map", ")", ";", "}", "if", "(", "compiledSource", ".", "indexOf", "(", "\"encode(\"", ")", ">", "-", "1", ")", "{", "body", ".", "push", "(", "type", ",", "encode", ")", ";", "}", "body", "=", "body", ".", "concat", "(", "[", "\"return ''\"", "+", "compiledSource", "]", ")", ".", "join", "(", "\";\\n\"", ")", ";", "\\n", "this", ".", "func", "=", "new", "Function", "(", "\"data\"", ",", "\"template\"", ",", "body", ")", ";", "}" ]
Represents a Compiler. @class @memberOf module:compiler @param {Tree} tree - A template [Tree]{@link module:tree.Tree} to compile.
[ "Represents", "a", "Compiler", "." ]
0d921dd183be34c33abe89ad33fea89c2ba16620
https://github.com/tbranyen/combyne/blob/0d921dd183be34c33abe89ad33fea89c2ba16620/lib/compiler.js#L88-L144
train
tbranyen/combyne
lib/utils/parse_property.js
parseProperty
function parseProperty(value) { var retVal = { type: "Property", value: value }; if (value === "false" || value === "true") { retVal.type = "Literal"; } // Easy way to determine if the value is NaN or not. else if (Number(value) === Number(value)) { retVal.type = "Literal"; } else if (isString.test(value)) { retVal.type = "Literal"; } return retVal; }
javascript
function parseProperty(value) { var retVal = { type: "Property", value: value }; if (value === "false" || value === "true") { retVal.type = "Literal"; } // Easy way to determine if the value is NaN or not. else if (Number(value) === Number(value)) { retVal.type = "Literal"; } else if (isString.test(value)) { retVal.type = "Literal"; } return retVal; }
[ "function", "parseProperty", "(", "value", ")", "{", "var", "retVal", "=", "{", "type", ":", "\"Property\"", ",", "value", ":", "value", "}", ";", "if", "(", "value", "===", "\"false\"", "||", "value", "===", "\"true\"", ")", "{", "retVal", ".", "type", "=", "\"Literal\"", ";", "}", "else", "if", "(", "Number", "(", "value", ")", "===", "Number", "(", "value", ")", ")", "{", "retVal", ".", "type", "=", "\"Literal\"", ";", "}", "else", "if", "(", "isString", ".", "test", "(", "value", ")", ")", "{", "retVal", ".", "type", "=", "\"Literal\"", ";", "}", "return", "retVal", ";", "}" ]
Used to produce the object representing the type. @memberOf module:utils/is_literal @param {String} value - The extracted property to inspect. @returns {Object} A property descriptor.
[ "Used", "to", "produce", "the", "object", "representing", "the", "type", "." ]
0d921dd183be34c33abe89ad33fea89c2ba16620
https://github.com/tbranyen/combyne/blob/0d921dd183be34c33abe89ad33fea89c2ba16620/lib/utils/parse_property.js#L18-L36
train
tbranyen/combyne
lib/index.js
Combyne
function Combyne(template, data) { // Allow this method to run standalone. if (!(this instanceof Combyne)) { return new Combyne(template, data); } // Expose the template for easier accessing and mutation. this.template = template; // Default the data to an empty object. this.data = data || {}; // Internal use only. Stores the partials and filters. this._partials = {}; this._filters = {}; // Ensure the template is a String. if (type(this.template) !== "string") { throw new Error("Template must be a String."); } // Normalize the delimiters with the defaults, to ensure a full object. var delimiters = defaults(Combyne.settings.delimiters, defaultDelimiters); // Create a new grammar with the delimiters. var grammar = new Grammar(delimiters).escape(); // Break down the template into a series of tokens. var stack = new Tokenizer(this.template, grammar).parse(); // Take the stack and create something resembling an AST. var tree = new Tree(stack).make(); // Expose the internal tree and stack. this.tree = tree; this.stack = stack; // Compile the template function from the tree. this.compiler = new Compiler(tree); // Update the source. this.source = this.compiler.source; }
javascript
function Combyne(template, data) { // Allow this method to run standalone. if (!(this instanceof Combyne)) { return new Combyne(template, data); } // Expose the template for easier accessing and mutation. this.template = template; // Default the data to an empty object. this.data = data || {}; // Internal use only. Stores the partials and filters. this._partials = {}; this._filters = {}; // Ensure the template is a String. if (type(this.template) !== "string") { throw new Error("Template must be a String."); } // Normalize the delimiters with the defaults, to ensure a full object. var delimiters = defaults(Combyne.settings.delimiters, defaultDelimiters); // Create a new grammar with the delimiters. var grammar = new Grammar(delimiters).escape(); // Break down the template into a series of tokens. var stack = new Tokenizer(this.template, grammar).parse(); // Take the stack and create something resembling an AST. var tree = new Tree(stack).make(); // Expose the internal tree and stack. this.tree = tree; this.stack = stack; // Compile the template function from the tree. this.compiler = new Compiler(tree); // Update the source. this.source = this.compiler.source; }
[ "function", "Combyne", "(", "template", ",", "data", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Combyne", ")", ")", "{", "return", "new", "Combyne", "(", "template", ",", "data", ")", ";", "}", "this", ".", "template", "=", "template", ";", "this", ".", "data", "=", "data", "||", "{", "}", ";", "this", ".", "_partials", "=", "{", "}", ";", "this", ".", "_filters", "=", "{", "}", ";", "if", "(", "type", "(", "this", ".", "template", ")", "!==", "\"string\"", ")", "{", "throw", "new", "Error", "(", "\"Template must be a String.\"", ")", ";", "}", "var", "delimiters", "=", "defaults", "(", "Combyne", ".", "settings", ".", "delimiters", ",", "defaultDelimiters", ")", ";", "var", "grammar", "=", "new", "Grammar", "(", "delimiters", ")", ".", "escape", "(", ")", ";", "var", "stack", "=", "new", "Tokenizer", "(", "this", ".", "template", ",", "grammar", ")", ".", "parse", "(", ")", ";", "var", "tree", "=", "new", "Tree", "(", "stack", ")", ".", "make", "(", ")", ";", "this", ".", "tree", "=", "tree", ";", "this", ".", "stack", "=", "stack", ";", "this", ".", "compiler", "=", "new", "Compiler", "(", "tree", ")", ";", "this", ".", "source", "=", "this", ".", "compiler", ".", "source", ";", "}" ]
Represents a Combyne template. @class Combyne @param {string} template - The template to compile. @param {object} data - Optional data to compile. @memberOf module:index
[ "Represents", "a", "Combyne", "template", "." ]
0d921dd183be34c33abe89ad33fea89c2ba16620
https://github.com/tbranyen/combyne/blob/0d921dd183be34c33abe89ad33fea89c2ba16620/lib/index.js#L54-L96
train
tbranyen/combyne
lib/shared/get_filter.js
getFilter
function getFilter(name) { if (name in this._filters) { return this._filters[name]; } else if (this._parent) { return this._parent.getFilter(name); } throw new Error("Missing filter " + name); }
javascript
function getFilter(name) { if (name in this._filters) { return this._filters[name]; } else if (this._parent) { return this._parent.getFilter(name); } throw new Error("Missing filter " + name); }
[ "function", "getFilter", "(", "name", ")", "{", "if", "(", "name", "in", "this", ".", "_filters", ")", "{", "return", "this", ".", "_filters", "[", "name", "]", ";", "}", "else", "if", "(", "this", ".", "_parent", ")", "{", "return", "this", ".", "_parent", ".", "getFilter", "(", "name", ")", ";", "}", "throw", "new", "Error", "(", "\"Missing filter \"", "+", "name", ")", ";", "}" ]
Retrieves a filter locally registered, or via the parent. @memberOf module:shared/get_filter @param {string} name - The name of the filter to retrieve.
[ "Retrieves", "a", "filter", "locally", "registered", "or", "via", "the", "parent", "." ]
0d921dd183be34c33abe89ad33fea89c2ba16620
https://github.com/tbranyen/combyne/blob/0d921dd183be34c33abe89ad33fea89c2ba16620/lib/shared/get_filter.js#L15-L24
train
tbranyen/combyne
lib/shared/encode.js
encode
function encode(raw) { if (type(raw) !== "string") { return raw; } // Identifies all characters in the unicode range: 00A0-9999, ampersands, // greater & less than) with their respective html entity. return raw.replace(/["&'<>`]/g, function(match) { return "&#" + match.charCodeAt(0) + ";"; }); }
javascript
function encode(raw) { if (type(raw) !== "string") { return raw; } // Identifies all characters in the unicode range: 00A0-9999, ampersands, // greater & less than) with their respective html entity. return raw.replace(/["&'<>`]/g, function(match) { return "&#" + match.charCodeAt(0) + ";"; }); }
[ "function", "encode", "(", "raw", ")", "{", "if", "(", "type", "(", "raw", ")", "!==", "\"string\"", ")", "{", "return", "raw", ";", "}", "return", "raw", ".", "replace", "(", "/", "[\"&'<>`]", "/", "g", ",", "function", "(", "match", ")", "{", "return", "\"&#\"", "+", "match", ".", "charCodeAt", "(", "0", ")", "+", "\";\"", ";", "}", ")", ";", "}" ]
Encodes a String with HTML entities. Solution adapted from: http://stackoverflow.com/questions/18749591 @memberOf module:shared/encode @param {*} raw - The raw value to encode, identity if not a String. @returns {string} An encoded string with HTML entities.
[ "Encodes", "a", "String", "with", "HTML", "entities", "." ]
0d921dd183be34c33abe89ad33fea89c2ba16620
https://github.com/tbranyen/combyne/blob/0d921dd183be34c33abe89ad33fea89c2ba16620/lib/shared/encode.js#L23-L33
train
tbranyen/combyne
lib/grammar.js
Grammar
function Grammar(delimiters) { this.delimiters = delimiters; this.internal = [ makeEntry("START_IF", "if"), makeEntry("ELSE", "else"), makeEntry("ELSIF", "elsif"), makeEntry("END_IF", "endif"), makeEntry("NOT", "not"), makeEntry("EQUALITY", "=="), makeEntry("NOT_EQUALITY", "!="), makeEntry("GREATER_THAN_EQUAL", ">="), makeEntry("GREATER_THAN", ">"), makeEntry("LESS_THAN_EQUAL", "<="), makeEntry("LESS_THAN", "<"), makeEntry("START_EACH", "each"), makeEntry("END_EACH", "endeach"), makeEntry("ASSIGN", "as"), makeEntry("PARTIAL", "partial"), makeEntry("START_EXTEND", "extend"), makeEntry("END_EXTEND", "endextend"), makeEntry("MAGIC", ".") ]; }
javascript
function Grammar(delimiters) { this.delimiters = delimiters; this.internal = [ makeEntry("START_IF", "if"), makeEntry("ELSE", "else"), makeEntry("ELSIF", "elsif"), makeEntry("END_IF", "endif"), makeEntry("NOT", "not"), makeEntry("EQUALITY", "=="), makeEntry("NOT_EQUALITY", "!="), makeEntry("GREATER_THAN_EQUAL", ">="), makeEntry("GREATER_THAN", ">"), makeEntry("LESS_THAN_EQUAL", "<="), makeEntry("LESS_THAN", "<"), makeEntry("START_EACH", "each"), makeEntry("END_EACH", "endeach"), makeEntry("ASSIGN", "as"), makeEntry("PARTIAL", "partial"), makeEntry("START_EXTEND", "extend"), makeEntry("END_EXTEND", "endextend"), makeEntry("MAGIC", ".") ]; }
[ "function", "Grammar", "(", "delimiters", ")", "{", "this", ".", "delimiters", "=", "delimiters", ";", "this", ".", "internal", "=", "[", "makeEntry", "(", "\"START_IF\"", ",", "\"if\"", ")", ",", "makeEntry", "(", "\"ELSE\"", ",", "\"else\"", ")", ",", "makeEntry", "(", "\"ELSIF\"", ",", "\"elsif\"", ")", ",", "makeEntry", "(", "\"END_IF\"", ",", "\"endif\"", ")", ",", "makeEntry", "(", "\"NOT\"", ",", "\"not\"", ")", ",", "makeEntry", "(", "\"EQUALITY\"", ",", "\"==\"", ")", ",", "makeEntry", "(", "\"NOT_EQUALITY\"", ",", "\"!=\"", ")", ",", "makeEntry", "(", "\"GREATER_THAN_EQUAL\"", ",", "\">=\"", ")", ",", "makeEntry", "(", "\"GREATER_THAN\"", ",", "\">\"", ")", ",", "makeEntry", "(", "\"LESS_THAN_EQUAL\"", ",", "\"<=\"", ")", ",", "makeEntry", "(", "\"LESS_THAN\"", ",", "\"<\"", ")", ",", "makeEntry", "(", "\"START_EACH\"", ",", "\"each\"", ")", ",", "makeEntry", "(", "\"END_EACH\"", ",", "\"endeach\"", ")", ",", "makeEntry", "(", "\"ASSIGN\"", ",", "\"as\"", ")", ",", "makeEntry", "(", "\"PARTIAL\"", ",", "\"partial\"", ")", ",", "makeEntry", "(", "\"START_EXTEND\"", ",", "\"extend\"", ")", ",", "makeEntry", "(", "\"END_EXTEND\"", ",", "\"endextend\"", ")", ",", "makeEntry", "(", "\"MAGIC\"", ",", "\".\"", ")", "]", ";", "}" ]
Represents a Grammar. @class @memberOf module:grammar @param {object} delimiters - Delimiters to use store and use internally.
[ "Represents", "a", "Grammar", "." ]
0d921dd183be34c33abe89ad33fea89c2ba16620
https://github.com/tbranyen/combyne/blob/0d921dd183be34c33abe89ad33fea89c2ba16620/lib/grammar.js#L24-L47
train
tbranyen/combyne
lib/grammar.js
makeEntry
function makeEntry(name, value) { var escaped = escapeDelimiter(value); return { name: name, escaped: escaped, test: new RegExp("^" + escaped) }; }
javascript
function makeEntry(name, value) { var escaped = escapeDelimiter(value); return { name: name, escaped: escaped, test: new RegExp("^" + escaped) }; }
[ "function", "makeEntry", "(", "name", ",", "value", ")", "{", "var", "escaped", "=", "escapeDelimiter", "(", "value", ")", ";", "return", "{", "name", ":", "name", ",", "escaped", ":", "escaped", ",", "test", ":", "new", "RegExp", "(", "\"^\"", "+", "escaped", ")", "}", ";", "}" ]
Abstract the logic for adding items to the grammar. @private @param {string} name - Required to identify the match. @param {string} value - To be escaped and used within a RegExp. @returns {object} The normalized metadata.
[ "Abstract", "the", "logic", "for", "adding", "items", "to", "the", "grammar", "." ]
0d921dd183be34c33abe89ad33fea89c2ba16620
https://github.com/tbranyen/combyne/blob/0d921dd183be34c33abe89ad33fea89c2ba16620/lib/grammar.js#L57-L65
train
tbranyen/combyne
lib/shared/get_partial.js
getPartial
function getPartial(name) { if (name in this._partials) { return this._partials[name]; } else if (this._parent) { return this._parent.getPartial(name); } throw new Error("Missing partial " + name); }
javascript
function getPartial(name) { if (name in this._partials) { return this._partials[name]; } else if (this._parent) { return this._parent.getPartial(name); } throw new Error("Missing partial " + name); }
[ "function", "getPartial", "(", "name", ")", "{", "if", "(", "name", "in", "this", ".", "_partials", ")", "{", "return", "this", ".", "_partials", "[", "name", "]", ";", "}", "else", "if", "(", "this", ".", "_parent", ")", "{", "return", "this", ".", "_parent", ".", "getPartial", "(", "name", ")", ";", "}", "throw", "new", "Error", "(", "\"Missing partial \"", "+", "name", ")", ";", "}" ]
Retrieves a partial locally registered, or via the parent. @memberOf module:shared/get_partial @param {string} name - The name of the partial to retrieve.
[ "Retrieves", "a", "partial", "locally", "registered", "or", "via", "the", "parent", "." ]
0d921dd183be34c33abe89ad33fea89c2ba16620
https://github.com/tbranyen/combyne/blob/0d921dd183be34c33abe89ad33fea89c2ba16620/lib/shared/get_partial.js#L15-L24
train
tbranyen/combyne
lib/tokenizer.js
parseNextToken
function parseNextToken(template, grammar, stack) { grammar.some(function(token) { var capture = token.test.exec(template); // Ignore empty captures. if (capture && capture[0]) { template = template.replace(token.test, ""); stack.push({ name: token.name, capture: capture }); return true; } }); return template; }
javascript
function parseNextToken(template, grammar, stack) { grammar.some(function(token) { var capture = token.test.exec(template); // Ignore empty captures. if (capture && capture[0]) { template = template.replace(token.test, ""); stack.push({ name: token.name, capture: capture }); return true; } }); return template; }
[ "function", "parseNextToken", "(", "template", ",", "grammar", ",", "stack", ")", "{", "grammar", ".", "some", "(", "function", "(", "token", ")", "{", "var", "capture", "=", "token", ".", "test", ".", "exec", "(", "template", ")", ";", "if", "(", "capture", "&&", "capture", "[", "0", "]", ")", "{", "template", "=", "template", ".", "replace", "(", "token", ".", "test", ",", "\"\"", ")", ";", "stack", ".", "push", "(", "{", "name", ":", "token", ".", "name", ",", "capture", ":", "capture", "}", ")", ";", "return", "true", ";", "}", "}", ")", ";", "return", "template", ";", "}" ]
Loop through the grammar and return on the first source match. Remove matches from the source, after pushing to the stack. @private @param {string} template that is searched on till its length is 0. @param {array} grammar array of test regexes. @param {array} stack to push found tokens to. @returns {string} template that has been truncated.
[ "Loop", "through", "the", "grammar", "and", "return", "on", "the", "first", "source", "match", ".", "Remove", "matches", "from", "the", "source", "after", "pushing", "to", "the", "stack", "." ]
0d921dd183be34c33abe89ad33fea89c2ba16620
https://github.com/tbranyen/combyne/blob/0d921dd183be34c33abe89ad33fea89c2ba16620/lib/tokenizer.js#L36-L49
train
crypto-utils/random-bytes
index.js
randomBytesSync
function randomBytesSync (size) { var err = null for (var i = 0; i < GENERATE_ATTEMPTS; i++) { try { return crypto.randomBytes(size) } catch (e) { err = e } } throw err }
javascript
function randomBytesSync (size) { var err = null for (var i = 0; i < GENERATE_ATTEMPTS; i++) { try { return crypto.randomBytes(size) } catch (e) { err = e } } throw err }
[ "function", "randomBytesSync", "(", "size", ")", "{", "var", "err", "=", "null", "for", "(", "var", "i", "=", "0", ";", "i", "<", "GENERATE_ATTEMPTS", ";", "i", "++", ")", "{", "try", "{", "return", "crypto", ".", "randomBytes", "(", "size", ")", "}", "catch", "(", "e", ")", "{", "err", "=", "e", "}", "}", "throw", "err", "}" ]
Generates strong pseudo-random bytes sync. @param {number} size @return {Buffer} @public
[ "Generates", "strong", "pseudo", "-", "random", "bytes", "sync", "." ]
732aa5f73edc287c9a4c2837657cc92f781cc372
https://github.com/crypto-utils/random-bytes/blob/732aa5f73edc287c9a4c2837657cc92f781cc372/index.js#L72-L84
train
ioBroker/ioBroker.vis-bars
widgets/bars/js/bars.js
function (div) { var visWidget = vis.views[vis.activeView].widgets[barsIntern.wid]; if (visWidget === undefined) { for (var view in vis.views) { if (view === '___settings') continue; if (vis.views[view].widgets[barsIntern.wid]) { visWidget = vis.views[view].widgets[barsIntern.wid]; break; } } } return visWidget; }
javascript
function (div) { var visWidget = vis.views[vis.activeView].widgets[barsIntern.wid]; if (visWidget === undefined) { for (var view in vis.views) { if (view === '___settings') continue; if (vis.views[view].widgets[barsIntern.wid]) { visWidget = vis.views[view].widgets[barsIntern.wid]; break; } } } return visWidget; }
[ "function", "(", "div", ")", "{", "var", "visWidget", "=", "vis", ".", "views", "[", "vis", ".", "activeView", "]", ".", "widgets", "[", "barsIntern", ".", "wid", "]", ";", "if", "(", "visWidget", "===", "undefined", ")", "{", "for", "(", "var", "view", "in", "vis", ".", "views", ")", "{", "if", "(", "view", "===", "'", "settings'", ")", "continue", ";", "if", "(", "vis", ".", "views", "[", "view", "]", ".", "widgets", "[", "barsIntern", ".", "wid", "]", ")", "{", "visWidget", "=", "vis", ".", "views", "[", "view", "]", ".", "widgets", "[", "barsIntern", ".", "wid", "]", ";", "break", ";", "}", "}", "}", "return", "visWidget", ";", "}" ]
Return widget for hqWidgets Button
[ "Return", "widget", "for", "hqWidgets", "Button" ]
ad7c4c760a8cd1a4c6236058b7d7fe6eeb79eed2
https://github.com/ioBroker/ioBroker.vis-bars/blob/ad7c4c760a8cd1a4c6236058b7d7fe6eeb79eed2/widgets/bars/js/bars.js#L71-L84
train
serby/save
lib/memory-engine.js
checkForIdAndData
function checkForIdAndData(object, callback) { var id = object[options.idProperty] , foundObject if (id === undefined || id === null) { return callback(new Error('Object has no \'' + options.idProperty + '\' property')) } foundObject = findById(id) if (foundObject === null) { return callback(new Error('No object found with \'' + options.idProperty + '\' = \'' + id + '\'')) } return callback(null, foundObject) }
javascript
function checkForIdAndData(object, callback) { var id = object[options.idProperty] , foundObject if (id === undefined || id === null) { return callback(new Error('Object has no \'' + options.idProperty + '\' property')) } foundObject = findById(id) if (foundObject === null) { return callback(new Error('No object found with \'' + options.idProperty + '\' = \'' + id + '\'')) } return callback(null, foundObject) }
[ "function", "checkForIdAndData", "(", "object", ",", "callback", ")", "{", "var", "id", "=", "object", "[", "options", ".", "idProperty", "]", ",", "foundObject", "if", "(", "id", "===", "undefined", "||", "id", "===", "null", ")", "{", "return", "callback", "(", "new", "Error", "(", "'Object has no \\''", "+", "\\'", "+", "options", ".", "idProperty", ")", ")", "}", "'\\' property'", "\\'", "foundObject", "=", "findById", "(", "id", ")", "}" ]
Checks that the object has the ID property present, then checks if the data object has that ID value present.e Returns an Error to the callback if either of the above checks fail @param {Object} object to check @param {Function} callback @api private
[ "Checks", "that", "the", "object", "has", "the", "ID", "property", "present", "then", "checks", "if", "the", "data", "object", "has", "that", "ID", "value", "present", ".", "e" ]
9b9232cd73ebe4e408561688ba4ecc5e35a5be30
https://github.com/serby/save/blob/9b9232cd73ebe4e408561688ba4ecc5e35a5be30/lib/memory-engine.js#L30-L46
train
serby/save
lib/memory-engine.js
create
function create(object, callback) { self.emit('create', object) callback = callback || emptyFn // clone the object var extendedObject = extend({}, object) if (!extendedObject[options.idProperty]) { idSeq += 1 extendedObject[options.idProperty] = '' + idSeq } else { if (findById(extendedObject[options.idProperty]) !== null) { return callback(new Error('Key ' + extendedObject[options.idProperty] + ' already exists')) } // if an id is provided, cast to string. extendedObject[options.idProperty] = '' + extendedObject[options.idProperty] } data.push(extend({}, extendedObject)) self.emit('afterCreate', extendedObject) callback(undefined, extendedObject) }
javascript
function create(object, callback) { self.emit('create', object) callback = callback || emptyFn // clone the object var extendedObject = extend({}, object) if (!extendedObject[options.idProperty]) { idSeq += 1 extendedObject[options.idProperty] = '' + idSeq } else { if (findById(extendedObject[options.idProperty]) !== null) { return callback(new Error('Key ' + extendedObject[options.idProperty] + ' already exists')) } // if an id is provided, cast to string. extendedObject[options.idProperty] = '' + extendedObject[options.idProperty] } data.push(extend({}, extendedObject)) self.emit('afterCreate', extendedObject) callback(undefined, extendedObject) }
[ "function", "create", "(", "object", ",", "callback", ")", "{", "self", ".", "emit", "(", "'create'", ",", "object", ")", "callback", "=", "callback", "||", "emptyFn", "var", "extendedObject", "=", "extend", "(", "{", "}", ",", "object", ")", "if", "(", "!", "extendedObject", "[", "options", ".", "idProperty", "]", ")", "{", "idSeq", "+=", "1", "extendedObject", "[", "options", ".", "idProperty", "]", "=", "''", "+", "idSeq", "}", "else", "{", "if", "(", "findById", "(", "extendedObject", "[", "options", ".", "idProperty", "]", ")", "!==", "null", ")", "{", "return", "callback", "(", "new", "Error", "(", "'Key '", "+", "extendedObject", "[", "options", ".", "idProperty", "]", "+", "' already exists'", ")", ")", "}", "extendedObject", "[", "options", ".", "idProperty", "]", "=", "''", "+", "extendedObject", "[", "options", ".", "idProperty", "]", "}", "data", ".", "push", "(", "extend", "(", "{", "}", ",", "extendedObject", ")", ")", "self", ".", "emit", "(", "'afterCreate'", ",", "extendedObject", ")", "callback", "(", "undefined", ",", "extendedObject", ")", "}" ]
Create a new entity. Emits a 'create' event. @param {Object} object to create @param {Function} callback (optional) @api public
[ "Create", "a", "new", "entity", ".", "Emits", "a", "create", "event", "." ]
9b9232cd73ebe4e408561688ba4ecc5e35a5be30
https://github.com/serby/save/blob/9b9232cd73ebe4e408561688ba4ecc5e35a5be30/lib/memory-engine.js#L55-L74
train
serby/save
lib/memory-engine.js
createOrUpdate
function createOrUpdate(object, callback) { if (typeof object[options.idProperty] === 'undefined') { // Create a new object self.create(object, callback) } else { // Try and find the object first to update var query = {} query[options.idProperty] = object[options.idProperty] self.findOne(query, function (err, foundObject) { if (foundObject) { // We found the object so update self.update(object, callback) } else { // We didn't find the object so create self.create(object, callback) } }) } }
javascript
function createOrUpdate(object, callback) { if (typeof object[options.idProperty] === 'undefined') { // Create a new object self.create(object, callback) } else { // Try and find the object first to update var query = {} query[options.idProperty] = object[options.idProperty] self.findOne(query, function (err, foundObject) { if (foundObject) { // We found the object so update self.update(object, callback) } else { // We didn't find the object so create self.create(object, callback) } }) } }
[ "function", "createOrUpdate", "(", "object", ",", "callback", ")", "{", "if", "(", "typeof", "object", "[", "options", ".", "idProperty", "]", "===", "'undefined'", ")", "{", "self", ".", "create", "(", "object", ",", "callback", ")", "}", "else", "{", "var", "query", "=", "{", "}", "query", "[", "options", ".", "idProperty", "]", "=", "object", "[", "options", ".", "idProperty", "]", "self", ".", "findOne", "(", "query", ",", "function", "(", "err", ",", "foundObject", ")", "{", "if", "(", "foundObject", ")", "{", "self", ".", "update", "(", "object", ",", "callback", ")", "}", "else", "{", "self", ".", "create", "(", "object", ",", "callback", ")", "}", "}", ")", "}", "}" ]
Create or update a entity. Emits a 'create' event or a 'update'. @param {Object} object to create or update @param {Function} callback (optional) @api public
[ "Create", "or", "update", "a", "entity", ".", "Emits", "a", "create", "event", "or", "a", "update", "." ]
9b9232cd73ebe4e408561688ba4ecc5e35a5be30
https://github.com/serby/save/blob/9b9232cd73ebe4e408561688ba4ecc5e35a5be30/lib/memory-engine.js#L83-L102
train
serby/save
lib/memory-engine.js
read
function read(id, callback) { var query = {} self.emit('read', id) callback = callback || emptyFn query[options.idProperty] = '' + id findByQuery(query, {}, function (error, objects) { if (objects[0] !== undefined) { var cloned = extend({}, objects[0]) self.emit('received', cloned) callback(undefined, cloned) } else { callback(undefined, undefined) } }) }
javascript
function read(id, callback) { var query = {} self.emit('read', id) callback = callback || emptyFn query[options.idProperty] = '' + id findByQuery(query, {}, function (error, objects) { if (objects[0] !== undefined) { var cloned = extend({}, objects[0]) self.emit('received', cloned) callback(undefined, cloned) } else { callback(undefined, undefined) } }) }
[ "function", "read", "(", "id", ",", "callback", ")", "{", "var", "query", "=", "{", "}", "self", ".", "emit", "(", "'read'", ",", "id", ")", "callback", "=", "callback", "||", "emptyFn", "query", "[", "options", ".", "idProperty", "]", "=", "''", "+", "id", "findByQuery", "(", "query", ",", "{", "}", ",", "function", "(", "error", ",", "objects", ")", "{", "if", "(", "objects", "[", "0", "]", "!==", "undefined", ")", "{", "var", "cloned", "=", "extend", "(", "{", "}", ",", "objects", "[", "0", "]", ")", "self", ".", "emit", "(", "'received'", ",", "cloned", ")", "callback", "(", "undefined", ",", "cloned", ")", "}", "else", "{", "callback", "(", "undefined", ",", "undefined", ")", "}", "}", ")", "}" ]
Reads a single entity. Emits a 'read' event. @param {Number} id to read @param {Function} callback (optional) @api public
[ "Reads", "a", "single", "entity", ".", "Emits", "a", "read", "event", "." ]
9b9232cd73ebe4e408561688ba4ecc5e35a5be30
https://github.com/serby/save/blob/9b9232cd73ebe4e408561688ba4ecc5e35a5be30/lib/memory-engine.js#L111-L126
train
serby/save
lib/memory-engine.js
update
function update(object, overwrite, callback) { if (typeof overwrite === 'function') { callback = overwrite overwrite = false } self.emit('update', object, overwrite) callback = callback || emptyFn var id = '' + object[options.idProperty] , updatedObject checkForIdAndData(object, function (error, foundObject) { if (error) { return callback(error) } if (overwrite) { updatedObject = extend({}, object) } else { updatedObject = extend({}, foundObject, object) } var query = {} , copy = extend({}, updatedObject) query[ options.idProperty ] = id data = Mingo.remove(data, query) data.push(updatedObject) self.emit('afterUpdate', copy, overwrite) callback(undefined, copy) }) }
javascript
function update(object, overwrite, callback) { if (typeof overwrite === 'function') { callback = overwrite overwrite = false } self.emit('update', object, overwrite) callback = callback || emptyFn var id = '' + object[options.idProperty] , updatedObject checkForIdAndData(object, function (error, foundObject) { if (error) { return callback(error) } if (overwrite) { updatedObject = extend({}, object) } else { updatedObject = extend({}, foundObject, object) } var query = {} , copy = extend({}, updatedObject) query[ options.idProperty ] = id data = Mingo.remove(data, query) data.push(updatedObject) self.emit('afterUpdate', copy, overwrite) callback(undefined, copy) }) }
[ "function", "update", "(", "object", ",", "overwrite", ",", "callback", ")", "{", "if", "(", "typeof", "overwrite", "===", "'function'", ")", "{", "callback", "=", "overwrite", "overwrite", "=", "false", "}", "self", ".", "emit", "(", "'update'", ",", "object", ",", "overwrite", ")", "callback", "=", "callback", "||", "emptyFn", "var", "id", "=", "''", "+", "object", "[", "options", ".", "idProperty", "]", ",", "updatedObject", "checkForIdAndData", "(", "object", ",", "function", "(", "error", ",", "foundObject", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "error", ")", "}", "if", "(", "overwrite", ")", "{", "updatedObject", "=", "extend", "(", "{", "}", ",", "object", ")", "}", "else", "{", "updatedObject", "=", "extend", "(", "{", "}", ",", "foundObject", ",", "object", ")", "}", "var", "query", "=", "{", "}", ",", "copy", "=", "extend", "(", "{", "}", ",", "updatedObject", ")", "query", "[", "options", ".", "idProperty", "]", "=", "id", "data", "=", "Mingo", ".", "remove", "(", "data", ",", "query", ")", "data", ".", "push", "(", "updatedObject", ")", "self", ".", "emit", "(", "'afterUpdate'", ",", "copy", ",", "overwrite", ")", "callback", "(", "undefined", ",", "copy", ")", "}", ")", "}" ]
Updates a single entity. Emits an 'update' event. Optionally overwrites the entire entity, by default just extends it with the new values. @param {Object} object to update @param {Boolean} whether to overwrite or extend the existing entity @param {Function} callback (optional) @api public
[ "Updates", "a", "single", "entity", ".", "Emits", "an", "update", "event", ".", "Optionally", "overwrites", "the", "entire", "entity", "by", "default", "just", "extends", "it", "with", "the", "new", "values", "." ]
9b9232cd73ebe4e408561688ba4ecc5e35a5be30
https://github.com/serby/save/blob/9b9232cd73ebe4e408561688ba4ecc5e35a5be30/lib/memory-engine.js#L137-L166
train
serby/save
lib/memory-engine.js
deleteMany
function deleteMany(query, callback) { callback = callback || emptyFn self.emit('deleteMany', query) data = Mingo.remove(data, query) self.emit('afterDeleteMany', query) callback() }
javascript
function deleteMany(query, callback) { callback = callback || emptyFn self.emit('deleteMany', query) data = Mingo.remove(data, query) self.emit('afterDeleteMany', query) callback() }
[ "function", "deleteMany", "(", "query", ",", "callback", ")", "{", "callback", "=", "callback", "||", "emptyFn", "self", ".", "emit", "(", "'deleteMany'", ",", "query", ")", "data", "=", "Mingo", ".", "remove", "(", "data", ",", "query", ")", "self", ".", "emit", "(", "'afterDeleteMany'", ",", "query", ")", "callback", "(", ")", "}" ]
Deletes entities based on a query. Emits a 'delete' event. Performs a find by query, then calls delete for each item returned. Returns an error if no items match the query. @param {Object} query to delete on @param {Function} callback (optional) @api public
[ "Deletes", "entities", "based", "on", "a", "query", ".", "Emits", "a", "delete", "event", ".", "Performs", "a", "find", "by", "query", "then", "calls", "delete", "for", "each", "item", "returned", ".", "Returns", "an", "error", "if", "no", "items", "match", "the", "query", "." ]
9b9232cd73ebe4e408561688ba4ecc5e35a5be30
https://github.com/serby/save/blob/9b9232cd73ebe4e408561688ba4ecc5e35a5be30/lib/memory-engine.js#L177-L183
train
serby/save
lib/memory-engine.js
del
function del(id, callback) { callback = callback || emptyFn if (typeof callback !== 'function') { throw new TypeError('callback must be a function or empty') } self.emit('delete', id) var query = {} query[ options.idProperty ] = id deleteMany(query, function() { self.emit('afterDelete', '' + id) callback(undefined) }) }
javascript
function del(id, callback) { callback = callback || emptyFn if (typeof callback !== 'function') { throw new TypeError('callback must be a function or empty') } self.emit('delete', id) var query = {} query[ options.idProperty ] = id deleteMany(query, function() { self.emit('afterDelete', '' + id) callback(undefined) }) }
[ "function", "del", "(", "id", ",", "callback", ")", "{", "callback", "=", "callback", "||", "emptyFn", "if", "(", "typeof", "callback", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'callback must be a function or empty'", ")", "}", "self", ".", "emit", "(", "'delete'", ",", "id", ")", "var", "query", "=", "{", "}", "query", "[", "options", ".", "idProperty", "]", "=", "id", "deleteMany", "(", "query", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'afterDelete'", ",", "''", "+", "id", ")", "callback", "(", "undefined", ")", "}", ")", "}" ]
Deletes one entity. Emits a 'delete' event. Returns an error if the object can not be found or if the ID property is not present. @param {Object} object to delete @param {Function} callback (optional) @api public
[ "Deletes", "one", "entity", ".", "Emits", "a", "delete", "event", ".", "Returns", "an", "error", "if", "the", "object", "can", "not", "be", "found", "or", "if", "the", "ID", "property", "is", "not", "present", "." ]
9b9232cd73ebe4e408561688ba4ecc5e35a5be30
https://github.com/serby/save/blob/9b9232cd73ebe4e408561688ba4ecc5e35a5be30/lib/memory-engine.js#L193-L208
train
serby/save
lib/memory-engine.js
findByQuery
function findByQuery(query, options, callback) { if (typeof options === 'function') { callback = options options = {} } var cursor = Mingo.find(data, query, options && options.fields) if (options && options.sort) cursor = cursor.sort(options.sort) if (options && options.limit) cursor = cursor.limit(options.limit) var allData = getObjectCopies(cursor.all()) if (callback === undefined) { return es.readArray(allData).pipe(es.map(function (data, cb) { self.emit('received', data) cb(null, data) })) } else { callback(null, allData) } }
javascript
function findByQuery(query, options, callback) { if (typeof options === 'function') { callback = options options = {} } var cursor = Mingo.find(data, query, options && options.fields) if (options && options.sort) cursor = cursor.sort(options.sort) if (options && options.limit) cursor = cursor.limit(options.limit) var allData = getObjectCopies(cursor.all()) if (callback === undefined) { return es.readArray(allData).pipe(es.map(function (data, cb) { self.emit('received', data) cb(null, data) })) } else { callback(null, allData) } }
[ "function", "findByQuery", "(", "query", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", "options", "=", "{", "}", "}", "var", "cursor", "=", "Mingo", ".", "find", "(", "data", ",", "query", ",", "options", "&&", "options", ".", "fields", ")", "if", "(", "options", "&&", "options", ".", "sort", ")", "cursor", "=", "cursor", ".", "sort", "(", "options", ".", "sort", ")", "if", "(", "options", "&&", "options", ".", "limit", ")", "cursor", "=", "cursor", ".", "limit", "(", "options", ".", "limit", ")", "var", "allData", "=", "getObjectCopies", "(", "cursor", ".", "all", "(", ")", ")", "if", "(", "callback", "===", "undefined", ")", "{", "return", "es", ".", "readArray", "(", "allData", ")", ".", "pipe", "(", "es", ".", "map", "(", "function", "(", "data", ",", "cb", ")", "{", "self", ".", "emit", "(", "'received'", ",", "data", ")", "cb", "(", "null", ",", "data", ")", "}", ")", ")", "}", "else", "{", "callback", "(", "null", ",", "allData", ")", "}", "}" ]
Performs a find on the data by search query. Sorting can be done similarly to mongo by providing a $sort option to the options object. The query can target fields in a subdocument similarly to mongo by passing a string reference to the subdocument in dot notation. @param {Object} query to search by @param {Object} search options @param {Function} callback @api private
[ "Performs", "a", "find", "on", "the", "data", "by", "search", "query", "." ]
9b9232cd73ebe4e408561688ba4ecc5e35a5be30
https://github.com/serby/save/blob/9b9232cd73ebe4e408561688ba4ecc5e35a5be30/lib/memory-engine.js#L224-L247
train
serby/save
lib/memory-engine.js
find
function find(query, options, callback) { if (typeof options === 'function') { callback = options options = {} } self.emit('find', query, options) if (callback !== undefined) { findByQuery(query, options, function(error, data) { if (error) return callback(error) self.emit('received', data) callback(null, data) }) } else { return findByQuery(query, options) } }
javascript
function find(query, options, callback) { if (typeof options === 'function') { callback = options options = {} } self.emit('find', query, options) if (callback !== undefined) { findByQuery(query, options, function(error, data) { if (error) return callback(error) self.emit('received', data) callback(null, data) }) } else { return findByQuery(query, options) } }
[ "function", "find", "(", "query", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", "options", "=", "{", "}", "}", "self", ".", "emit", "(", "'find'", ",", "query", ",", "options", ")", "if", "(", "callback", "!==", "undefined", ")", "{", "findByQuery", "(", "query", ",", "options", ",", "function", "(", "error", ",", "data", ")", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ")", "self", ".", "emit", "(", "'received'", ",", "data", ")", "callback", "(", "null", ",", "data", ")", "}", ")", "}", "else", "{", "return", "findByQuery", "(", "query", ",", "options", ")", "}", "}" ]
Performs a find on the data. Emits a 'find' event. @param {Object} query to search by @param {Object} options @param {Function} callback @api public
[ "Performs", "a", "find", "on", "the", "data", ".", "Emits", "a", "find", "event", "." ]
9b9232cd73ebe4e408561688ba4ecc5e35a5be30
https://github.com/serby/save/blob/9b9232cd73ebe4e408561688ba4ecc5e35a5be30/lib/memory-engine.js#L265-L281
train
serby/save
lib/memory-engine.js
findOne
function findOne(query, options, callback) { if (typeof options === 'function') { callback = options options = {} } self.emit('findOne', query, options) findByQuery(query, options, function (error, objects) { self.emit('received', objects[0]) callback(undefined, objects[0]) }) }
javascript
function findOne(query, options, callback) { if (typeof options === 'function') { callback = options options = {} } self.emit('findOne', query, options) findByQuery(query, options, function (error, objects) { self.emit('received', objects[0]) callback(undefined, objects[0]) }) }
[ "function", "findOne", "(", "query", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", "options", "=", "{", "}", "}", "self", ".", "emit", "(", "'findOne'", ",", "query", ",", "options", ")", "findByQuery", "(", "query", ",", "options", ",", "function", "(", "error", ",", "objects", ")", "{", "self", ".", "emit", "(", "'received'", ",", "objects", "[", "0", "]", ")", "callback", "(", "undefined", ",", "objects", "[", "0", "]", ")", "}", ")", "}" ]
Performs a find on the data and limits the result set to 1. Emits a 'findOne' event. @param {Object} query to search by @param {Object} options @param {Function} callback @api public
[ "Performs", "a", "find", "on", "the", "data", "and", "limits", "the", "result", "set", "to", "1", ".", "Emits", "a", "findOne", "event", "." ]
9b9232cd73ebe4e408561688ba4ecc5e35a5be30
https://github.com/serby/save/blob/9b9232cd73ebe4e408561688ba4ecc5e35a5be30/lib/memory-engine.js#L292-L302
train
serby/save
lib/memory-engine.js
count
function count(query, callback) { self.emit('count', query) findByQuery(query, options, function (error, objects) { self.emit('received', objects.length) callback(undefined, objects.length) }) }
javascript
function count(query, callback) { self.emit('count', query) findByQuery(query, options, function (error, objects) { self.emit('received', objects.length) callback(undefined, objects.length) }) }
[ "function", "count", "(", "query", ",", "callback", ")", "{", "self", ".", "emit", "(", "'count'", ",", "query", ")", "findByQuery", "(", "query", ",", "options", ",", "function", "(", "error", ",", "objects", ")", "{", "self", ".", "emit", "(", "'received'", ",", "objects", ".", "length", ")", "callback", "(", "undefined", ",", "objects", ".", "length", ")", "}", ")", "}" ]
Performs a count by query. Emits a 'count' event. @param {Object} query to search by @param {Function} callback @api public
[ "Performs", "a", "count", "by", "query", ".", "Emits", "a", "count", "event", "." ]
9b9232cd73ebe4e408561688ba4ecc5e35a5be30
https://github.com/serby/save/blob/9b9232cd73ebe4e408561688ba4ecc5e35a5be30/lib/memory-engine.js#L311-L317
train
andreogle/eslint-teamcity
src/formatter.js
getTeamCityOutput
function getTeamCityOutput(results, propNames) { const config = getUserConfig(propNames || {}); if (process.env.ESLINT_TEAMCITY_DISPLAY_CONFIG) { console.info(`Running ESLint Teamcity with config: ${JSON.stringify(config, null, 4)}`); } let outputMessages = []; switch (config.reporter.toLowerCase()) { case 'inspections': { outputMessages = formatInspections(results, config); break; } case 'errors': default: { outputMessages = formatErrors(results, config); break; } } return outputMessages.join('\n'); }
javascript
function getTeamCityOutput(results, propNames) { const config = getUserConfig(propNames || {}); if (process.env.ESLINT_TEAMCITY_DISPLAY_CONFIG) { console.info(`Running ESLint Teamcity with config: ${JSON.stringify(config, null, 4)}`); } let outputMessages = []; switch (config.reporter.toLowerCase()) { case 'inspections': { outputMessages = formatInspections(results, config); break; } case 'errors': default: { outputMessages = formatErrors(results, config); break; } } return outputMessages.join('\n'); }
[ "function", "getTeamCityOutput", "(", "results", ",", "propNames", ")", "{", "const", "config", "=", "getUserConfig", "(", "propNames", "||", "{", "}", ")", ";", "if", "(", "process", ".", "env", ".", "ESLINT_TEAMCITY_DISPLAY_CONFIG", ")", "{", "console", ".", "info", "(", "`", "${", "JSON", ".", "stringify", "(", "config", ",", "null", ",", "4", ")", "}", "`", ")", ";", "}", "let", "outputMessages", "=", "[", "]", ";", "switch", "(", "config", ".", "reporter", ".", "toLowerCase", "(", ")", ")", "{", "case", "'inspections'", ":", "{", "outputMessages", "=", "formatInspections", "(", "results", ",", "config", ")", ";", "break", ";", "}", "case", "'errors'", ":", "default", ":", "{", "outputMessages", "=", "formatErrors", "(", "results", ",", "config", ")", ";", "break", ";", "}", "}", "return", "outputMessages", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Determines the formatter to use and any config variables to use @param {array} results The output generated by running ESLint. @param {object} [propNames] Optional config variables that will override all other config settings @returns {string} The concatenated output of all messages to display in TeamCity
[ "Determines", "the", "formatter", "to", "use", "and", "any", "config", "variables", "to", "use" ]
015a7a56d47a77bb3d2544b8d50ff657d77390e7
https://github.com/andreogle/eslint-teamcity/blob/015a7a56d47a77bb3d2544b8d50ff657d77390e7/src/formatter.js#L55-L76
train
posthtml/posthtml-modules
index.js
processNodeContentWithPosthtml
function processNodeContentWithPosthtml(node, options) { return function (content) { return processWithPostHtml(options.plugins, path.join(path.dirname(options.from), node.attrs.href), content, [function (tree) { // remove <content> tags and replace them with node's content return tree.match(match('content'), function () { return node.content || ''; }); }]); }; }
javascript
function processNodeContentWithPosthtml(node, options) { return function (content) { return processWithPostHtml(options.plugins, path.join(path.dirname(options.from), node.attrs.href), content, [function (tree) { // remove <content> tags and replace them with node's content return tree.match(match('content'), function () { return node.content || ''; }); }]); }; }
[ "function", "processNodeContentWithPosthtml", "(", "node", ",", "options", ")", "{", "return", "function", "(", "content", ")", "{", "return", "processWithPostHtml", "(", "options", ".", "plugins", ",", "path", ".", "join", "(", "path", ".", "dirname", "(", "options", ".", "from", ")", ",", "node", ".", "attrs", ".", "href", ")", ",", "content", ",", "[", "function", "(", "tree", ")", "{", "return", "tree", ".", "match", "(", "match", "(", "'content'", ")", ",", "function", "(", ")", "{", "return", "node", ".", "content", "||", "''", ";", "}", ")", ";", "}", "]", ")", ";", "}", ";", "}" ]
process every node content with posthtml @param {Object} node [posthtml element object] @param {Object} options @return {Function}
[ "process", "every", "node", "content", "with", "posthtml" ]
b6b778123921d1a4a87d065994810ff410726d5a
https://github.com/posthtml/posthtml-modules/blob/b6b778123921d1a4a87d065994810ff410726d5a/index.js#L15-L24
train
jellekralt/angular-drag-scroll
src/ng-drag-scroll.js
handleMouseDown
function handleMouseDown (e) { if(enabled){ for (var i= 0; i<excludedClasses.length; i++) { if (angular.element(e.target).hasClass(excludedClasses[i])) { return false; } } $scope.$apply(function() { onDragStart($scope); }); // Set mouse drag listeners setDragListeners(); // Set 'pushed' state pushed = true; lastClientX = startClientX = e.clientX; lastClientY = startClientY = e.clientY; clearSelection(); e.preventDefault(); e.stopPropagation(); } }
javascript
function handleMouseDown (e) { if(enabled){ for (var i= 0; i<excludedClasses.length; i++) { if (angular.element(e.target).hasClass(excludedClasses[i])) { return false; } } $scope.$apply(function() { onDragStart($scope); }); // Set mouse drag listeners setDragListeners(); // Set 'pushed' state pushed = true; lastClientX = startClientX = e.clientX; lastClientY = startClientY = e.clientY; clearSelection(); e.preventDefault(); e.stopPropagation(); } }
[ "function", "handleMouseDown", "(", "e", ")", "{", "if", "(", "enabled", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "excludedClasses", ".", "length", ";", "i", "++", ")", "{", "if", "(", "angular", ".", "element", "(", "e", ".", "target", ")", ".", "hasClass", "(", "excludedClasses", "[", "i", "]", ")", ")", "{", "return", "false", ";", "}", "}", "$scope", ".", "$apply", "(", "function", "(", ")", "{", "onDragStart", "(", "$scope", ")", ";", "}", ")", ";", "setDragListeners", "(", ")", ";", "pushed", "=", "true", ";", "lastClientX", "=", "startClientX", "=", "e", ".", "clientX", ";", "lastClientY", "=", "startClientY", "=", "e", ".", "clientY", ";", "clearSelection", "(", ")", ";", "e", ".", "preventDefault", "(", ")", ";", "e", ".", "stopPropagation", "(", ")", ";", "}", "}" ]
Handles mousedown event @param {object} e MouseDown event
[ "Handles", "mousedown", "event" ]
29ea86b2e722e23b86842f7aa8169acf3ed20d52
https://github.com/jellekralt/angular-drag-scroll/blob/29ea86b2e722e23b86842f7aa8169acf3ed20d52/src/ng-drag-scroll.js#L59-L85
train
jellekralt/angular-drag-scroll
src/ng-drag-scroll.js
handleMouseUp
function handleMouseUp (e) { if(enabled){ var selectable = (e.target.attributes && 'drag-scroll-text' in e.target.attributes); var withinXConstraints = (e.clientX >= (startClientX - allowedClickOffset) && e.clientX <= (startClientX + allowedClickOffset)); var withinYConstraints = (e.clientY >= (startClientY - allowedClickOffset) && e.clientY <= (startClientY + allowedClickOffset)); // Set 'pushed' state pushed = false; // Check if cursor falls within X and Y axis constraints if(selectable && withinXConstraints && withinYConstraints) { // If so, select the text inside the target element selectText(e.target); } $scope.$apply(function() { onDragEnd($scope); }); removeDragListeners(); } }
javascript
function handleMouseUp (e) { if(enabled){ var selectable = (e.target.attributes && 'drag-scroll-text' in e.target.attributes); var withinXConstraints = (e.clientX >= (startClientX - allowedClickOffset) && e.clientX <= (startClientX + allowedClickOffset)); var withinYConstraints = (e.clientY >= (startClientY - allowedClickOffset) && e.clientY <= (startClientY + allowedClickOffset)); // Set 'pushed' state pushed = false; // Check if cursor falls within X and Y axis constraints if(selectable && withinXConstraints && withinYConstraints) { // If so, select the text inside the target element selectText(e.target); } $scope.$apply(function() { onDragEnd($scope); }); removeDragListeners(); } }
[ "function", "handleMouseUp", "(", "e", ")", "{", "if", "(", "enabled", ")", "{", "var", "selectable", "=", "(", "e", ".", "target", ".", "attributes", "&&", "'drag-scroll-text'", "in", "e", ".", "target", ".", "attributes", ")", ";", "var", "withinXConstraints", "=", "(", "e", ".", "clientX", ">=", "(", "startClientX", "-", "allowedClickOffset", ")", "&&", "e", ".", "clientX", "<=", "(", "startClientX", "+", "allowedClickOffset", ")", ")", ";", "var", "withinYConstraints", "=", "(", "e", ".", "clientY", ">=", "(", "startClientY", "-", "allowedClickOffset", ")", "&&", "e", ".", "clientY", "<=", "(", "startClientY", "+", "allowedClickOffset", ")", ")", ";", "pushed", "=", "false", ";", "if", "(", "selectable", "&&", "withinXConstraints", "&&", "withinYConstraints", ")", "{", "selectText", "(", "e", ".", "target", ")", ";", "}", "$scope", ".", "$apply", "(", "function", "(", ")", "{", "onDragEnd", "(", "$scope", ")", ";", "}", ")", ";", "removeDragListeners", "(", ")", ";", "}", "}" ]
Handles mouseup event @param {object} e MouseUp event
[ "Handles", "mouseup", "event" ]
29ea86b2e722e23b86842f7aa8169acf3ed20d52
https://github.com/jellekralt/angular-drag-scroll/blob/29ea86b2e722e23b86842f7aa8169acf3ed20d52/src/ng-drag-scroll.js#L91-L113
train
jellekralt/angular-drag-scroll
src/ng-drag-scroll.js
handleMouseMove
function handleMouseMove (e) { if(enabled){ if (pushed) { if(!axis || axis === 'x') { $element[0].scrollLeft -= (-lastClientX + (lastClientX = e.clientX)); } if(!axis || axis === 'y') { $element[0].scrollTop -= (-lastClientY + (lastClientY = e.clientY)); } } e.preventDefault(); } }
javascript
function handleMouseMove (e) { if(enabled){ if (pushed) { if(!axis || axis === 'x') { $element[0].scrollLeft -= (-lastClientX + (lastClientX = e.clientX)); } if(!axis || axis === 'y') { $element[0].scrollTop -= (-lastClientY + (lastClientY = e.clientY)); } } e.preventDefault(); } }
[ "function", "handleMouseMove", "(", "e", ")", "{", "if", "(", "enabled", ")", "{", "if", "(", "pushed", ")", "{", "if", "(", "!", "axis", "||", "axis", "===", "'x'", ")", "{", "$element", "[", "0", "]", ".", "scrollLeft", "-=", "(", "-", "lastClientX", "+", "(", "lastClientX", "=", "e", ".", "clientX", ")", ")", ";", "}", "if", "(", "!", "axis", "||", "axis", "===", "'y'", ")", "{", "$element", "[", "0", "]", ".", "scrollTop", "-=", "(", "-", "lastClientY", "+", "(", "lastClientY", "=", "e", ".", "clientY", ")", ")", ";", "}", "}", "e", ".", "preventDefault", "(", ")", ";", "}", "}" ]
Handles mousemove event @param {object} e MouseMove event
[ "Handles", "mousemove", "event" ]
29ea86b2e722e23b86842f7aa8169acf3ed20d52
https://github.com/jellekralt/angular-drag-scroll/blob/29ea86b2e722e23b86842f7aa8169acf3ed20d52/src/ng-drag-scroll.js#L119-L132
train
jellekralt/angular-drag-scroll
src/ng-drag-scroll.js
destroy
function destroy () { $element.off('mousedown', handleMouseDown); angular.element($window).off('mouseup', handleMouseUp); angular.element($window).off('mousemove', handleMouseMove); }
javascript
function destroy () { $element.off('mousedown', handleMouseDown); angular.element($window).off('mouseup', handleMouseUp); angular.element($window).off('mousemove', handleMouseMove); }
[ "function", "destroy", "(", ")", "{", "$element", ".", "off", "(", "'mousedown'", ",", "handleMouseDown", ")", ";", "angular", ".", "element", "(", "$window", ")", ".", "off", "(", "'mouseup'", ",", "handleMouseUp", ")", ";", "angular", ".", "element", "(", "$window", ")", ".", "off", "(", "'mousemove'", ",", "handleMouseMove", ")", ";", "}" ]
Destroys all the event listeners
[ "Destroys", "all", "the", "event", "listeners" ]
29ea86b2e722e23b86842f7aa8169acf3ed20d52
https://github.com/jellekralt/angular-drag-scroll/blob/29ea86b2e722e23b86842f7aa8169acf3ed20d52/src/ng-drag-scroll.js#L137-L141
train
jellekralt/angular-drag-scroll
src/ng-drag-scroll.js
selectText
function selectText (element) { var range; if ($window.document.selection) { range = $window.document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if ($window.getSelection) { range = $window.document.createRange(); range.selectNode(element); $window.getSelection().addRange(range); } }
javascript
function selectText (element) { var range; if ($window.document.selection) { range = $window.document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if ($window.getSelection) { range = $window.document.createRange(); range.selectNode(element); $window.getSelection().addRange(range); } }
[ "function", "selectText", "(", "element", ")", "{", "var", "range", ";", "if", "(", "$window", ".", "document", ".", "selection", ")", "{", "range", "=", "$window", ".", "document", ".", "body", ".", "createTextRange", "(", ")", ";", "range", ".", "moveToElementText", "(", "element", ")", ";", "range", ".", "select", "(", ")", ";", "}", "else", "if", "(", "$window", ".", "getSelection", ")", "{", "range", "=", "$window", ".", "document", ".", "createRange", "(", ")", ";", "range", ".", "selectNode", "(", "element", ")", ";", "$window", ".", "getSelection", "(", ")", ".", "addRange", "(", "range", ")", ";", "}", "}" ]
Selects text for a specific element @param {object} element Selected element
[ "Selects", "text", "for", "a", "specific", "element" ]
29ea86b2e722e23b86842f7aa8169acf3ed20d52
https://github.com/jellekralt/angular-drag-scroll/blob/29ea86b2e722e23b86842f7aa8169acf3ed20d52/src/ng-drag-scroll.js#L147-L158
train
jellekralt/angular-drag-scroll
src/ng-drag-scroll.js
clearSelection
function clearSelection () { if ($window.getSelection) { if ($window.getSelection().empty) { // Chrome $window.getSelection().empty(); } else if ($window.getSelection().removeAllRanges) { // Firefox $window.getSelection().removeAllRanges(); } } else if ($document.selection) { // IE? $document.selection.empty(); } }
javascript
function clearSelection () { if ($window.getSelection) { if ($window.getSelection().empty) { // Chrome $window.getSelection().empty(); } else if ($window.getSelection().removeAllRanges) { // Firefox $window.getSelection().removeAllRanges(); } } else if ($document.selection) { // IE? $document.selection.empty(); } }
[ "function", "clearSelection", "(", ")", "{", "if", "(", "$window", ".", "getSelection", ")", "{", "if", "(", "$window", ".", "getSelection", "(", ")", ".", "empty", ")", "{", "$window", ".", "getSelection", "(", ")", ".", "empty", "(", ")", ";", "}", "else", "if", "(", "$window", ".", "getSelection", "(", ")", ".", "removeAllRanges", ")", "{", "$window", ".", "getSelection", "(", ")", ".", "removeAllRanges", "(", ")", ";", "}", "}", "else", "if", "(", "$document", ".", "selection", ")", "{", "$document", ".", "selection", ".", "empty", "(", ")", ";", "}", "}" ]
Clears text selection
[ "Clears", "text", "selection" ]
29ea86b2e722e23b86842f7aa8169acf3ed20d52
https://github.com/jellekralt/angular-drag-scroll/blob/29ea86b2e722e23b86842f7aa8169acf3ed20d52/src/ng-drag-scroll.js#L163-L173
train
guylabs/angular-spring-data-rest
src/angular-spring-data-rest-utils.js
deepExtend
function deepExtend(destination) { angular.forEach(arguments, function (obj) { if (obj !== destination) { angular.forEach(obj, function (value, key) { if (destination[key] && destination[key].constructor && destination[key].constructor === Object) { deepExtend(destination[key], value); } else { destination[key] = value; } }); } }); return angular.copy(destination); }
javascript
function deepExtend(destination) { angular.forEach(arguments, function (obj) { if (obj !== destination) { angular.forEach(obj, function (value, key) { if (destination[key] && destination[key].constructor && destination[key].constructor === Object) { deepExtend(destination[key], value); } else { destination[key] = value; } }); } }); return angular.copy(destination); }
[ "function", "deepExtend", "(", "destination", ")", "{", "angular", ".", "forEach", "(", "arguments", ",", "function", "(", "obj", ")", "{", "if", "(", "obj", "!==", "destination", ")", "{", "angular", ".", "forEach", "(", "obj", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "destination", "[", "key", "]", "&&", "destination", "[", "key", "]", ".", "constructor", "&&", "destination", "[", "key", "]", ".", "constructor", "===", "Object", ")", "{", "deepExtend", "(", "destination", "[", "key", "]", ",", "value", ")", ";", "}", "else", "{", "destination", "[", "key", "]", "=", "value", ";", "}", "}", ")", ";", "}", "}", ")", ";", "return", "angular", ".", "copy", "(", "destination", ")", ";", "}" ]
Makes a deep extend of the given destination object and the source objects. @param {object} destination the destination object @returns {object} a copy of the extended destination object
[ "Makes", "a", "deep", "extend", "of", "the", "given", "destination", "object", "and", "the", "source", "objects", "." ]
70d15b5cf3cd37328037d3884c30a4715a12b616
https://github.com/guylabs/angular-spring-data-rest/blob/70d15b5cf3cd37328037d3884c30a4715a12b616/src/angular-spring-data-rest-utils.js#L7-L20
train
guylabs/angular-spring-data-rest
src/angular-spring-data-rest-utils.js
checkUrl
function checkUrl(url, resourceName, hrefKey) { if (url == undefined || !url) { throw new Error("The provided resource name '" + resourceName + "' has no valid URL in the '" + hrefKey + "' property."); } return url }
javascript
function checkUrl(url, resourceName, hrefKey) { if (url == undefined || !url) { throw new Error("The provided resource name '" + resourceName + "' has no valid URL in the '" + hrefKey + "' property."); } return url }
[ "function", "checkUrl", "(", "url", ",", "resourceName", ",", "hrefKey", ")", "{", "if", "(", "url", "==", "undefined", "||", "!", "url", ")", "{", "throw", "new", "Error", "(", "\"The provided resource name '\"", "+", "resourceName", "+", "\"' has no valid URL in the '\"", "+", "hrefKey", "+", "\"' property.\"", ")", ";", "}", "return", "url", "}" ]
Checks the given URL if it is valid and throws a parameterized exception containing the resource name and the URL property name. @param {string} url the URL to check @param {string} resourceName the name of the resource @param {string} hrefKey the URL property key @returns {string} the URL if it is valid @throws Error if the URL is not valid
[ "Checks", "the", "given", "URL", "if", "it", "is", "valid", "and", "throws", "a", "parameterized", "exception", "containing", "the", "resource", "name", "and", "the", "URL", "property", "name", "." ]
70d15b5cf3cd37328037d3884c30a4715a12b616
https://github.com/guylabs/angular-spring-data-rest/blob/70d15b5cf3cd37328037d3884c30a4715a12b616/src/angular-spring-data-rest-utils.js#L81-L87
train
postcss/postcss-font-variant
index.js
getFontFeatureSettingsPrevTo
function getFontFeatureSettingsPrevTo(decl) { var fontFeatureSettings = null; decl.parent.walkDecls(function(decl) { if (decl.prop === "font-feature-settings") { fontFeatureSettings = decl; } }) if (fontFeatureSettings === null) { fontFeatureSettings = decl.clone() fontFeatureSettings.prop = "font-feature-settings" fontFeatureSettings.value = "" decl.parent.insertBefore(decl, fontFeatureSettings) } return fontFeatureSettings }
javascript
function getFontFeatureSettingsPrevTo(decl) { var fontFeatureSettings = null; decl.parent.walkDecls(function(decl) { if (decl.prop === "font-feature-settings") { fontFeatureSettings = decl; } }) if (fontFeatureSettings === null) { fontFeatureSettings = decl.clone() fontFeatureSettings.prop = "font-feature-settings" fontFeatureSettings.value = "" decl.parent.insertBefore(decl, fontFeatureSettings) } return fontFeatureSettings }
[ "function", "getFontFeatureSettingsPrevTo", "(", "decl", ")", "{", "var", "fontFeatureSettings", "=", "null", ";", "decl", ".", "parent", ".", "walkDecls", "(", "function", "(", "decl", ")", "{", "if", "(", "decl", ".", "prop", "===", "\"font-feature-settings\"", ")", "{", "fontFeatureSettings", "=", "decl", ";", "}", "}", ")", "if", "(", "fontFeatureSettings", "===", "null", ")", "{", "fontFeatureSettings", "=", "decl", ".", "clone", "(", ")", "fontFeatureSettings", ".", "prop", "=", "\"font-feature-settings\"", "fontFeatureSettings", ".", "value", "=", "\"\"", "decl", ".", "parent", ".", "insertBefore", "(", "decl", ",", "fontFeatureSettings", ")", "}", "return", "fontFeatureSettings", "}" ]
Find font-feature-settings declaration before given declaration, create if does not exist
[ "Find", "font", "-", "feature", "-", "settings", "declaration", "before", "given", "declaration", "create", "if", "does", "not", "exist" ]
9084a34e2aea66005f3fa845b2466b6cbdb1b93c
https://github.com/postcss/postcss-font-variant/blob/9084a34e2aea66005f3fa845b2466b6cbdb1b93c/index.js#L69-L84
train