id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
7,500
xaksis/vue-good-table
dist/vue-good-table.cjs.js
getClasses
function getClasses(index$$1, element, row) { var _this$typedColumns$in = this.typedColumns[index$$1], typeDef = _this$typedColumns$in.typeDef, custom = _this$typedColumns$in["".concat(element, "Class")]; var isRight = typeDef.isRight; if (this.rtl) isRight = true; var classes = { 'vgt-right-align': isRight, 'vgt-left-align': !isRight }; // for td we need to check if value is // a function. if (typeof custom === 'function') { classes[custom(row)] = true; } else if (typeof custom === 'string') { classes[custom] = true; } return classes; }
javascript
function getClasses(index$$1, element, row) { var _this$typedColumns$in = this.typedColumns[index$$1], typeDef = _this$typedColumns$in.typeDef, custom = _this$typedColumns$in["".concat(element, "Class")]; var isRight = typeDef.isRight; if (this.rtl) isRight = true; var classes = { 'vgt-right-align': isRight, 'vgt-left-align': !isRight }; // for td we need to check if value is // a function. if (typeof custom === 'function') { classes[custom(row)] = true; } else if (typeof custom === 'string') { classes[custom] = true; } return classes; }
[ "function", "getClasses", "(", "index$$1", ",", "element", ",", "row", ")", "{", "var", "_this$typedColumns$in", "=", "this", ".", "typedColumns", "[", "index$$1", "]", ",", "typeDef", "=", "_this$typedColumns$in", ".", "typeDef", ",", "custom", "=", "_this$typedColumns$in", "[", "\"\"", ".", "concat", "(", "element", ",", "\"Class\"", ")", "]", ";", "var", "isRight", "=", "typeDef", ".", "isRight", ";", "if", "(", "this", ".", "rtl", ")", "isRight", "=", "true", ";", "var", "classes", "=", "{", "'vgt-right-align'", ":", "isRight", ",", "'vgt-left-align'", ":", "!", "isRight", "}", ";", "// for td we need to check if value is", "// a function.", "if", "(", "typeof", "custom", "===", "'function'", ")", "{", "classes", "[", "custom", "(", "row", ")", "]", "=", "true", ";", "}", "else", "if", "(", "typeof", "custom", "===", "'string'", ")", "{", "classes", "[", "custom", "]", "=", "true", ";", "}", "return", "classes", ";", "}" ]
Get classes for the given column index & element.
[ "Get", "classes", "for", "the", "given", "column", "index", "&", "element", "." ]
bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6
https://github.com/xaksis/vue-good-table/blob/bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6/dist/vue-good-table.cjs.js#L2015-L2035
7,501
xaksis/vue-good-table
dist/vue-good-table.cjs.js
filterRows
function filterRows(columnFilters) { var _this4 = this; var fromFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; // if (!this.rows.length) return; // this is invoked either as a result of changing filters // or as a result of modifying rows. this.columnFilters = columnFilters; var computedRows = cloneDeep(this.originalRows); // do we have a filter to care about? // if not we don't need to do anything if (this.columnFilters && Object.keys(this.columnFilters).length) { // every time we filter rows, we need to set current page // to 1 // if the mode is remote, we only need to reset, if this is // being called from filter, not when rows are changing if (this.mode !== 'remote' || fromFilter) { this.changePage(1); } // we need to emit an event and that's that. // but this only needs to be invoked if filter is changing // not when row object is modified. if (fromFilter) { this.$emit('on-column-filter', { columnFilters: this.columnFilters }); } // if mode is remote, we don't do any filtering here. if (this.mode === 'remote') { if (fromFilter) { this.$emit('update:isLoading', true); } else { // if remote filtering has already been taken care of. this.filteredRows = computedRows; } return; } var _loop = function _loop(i) { var col = _this4.typedColumns[i]; if (_this4.columnFilters[col.field]) { computedRows = each(computedRows, function (headerRow) { var newChildren = headerRow.children.filter(function (row) { // If column has a custom filter, use that. if (col.filterOptions && typeof col.filterOptions.filterFn === 'function') { return col.filterOptions.filterFn(_this4.collect(row, col.field), _this4.columnFilters[col.field]); } // Otherwise Use default filters var typeDef = col.typeDef; return typeDef.filterPredicate(_this4.collect(row, col.field), _this4.columnFilters[col.field]); }); // should we remove the header? headerRow.children = newChildren; }); } }; for (var i = 0; i < this.typedColumns.length; i++) { _loop(i); } } this.filteredRows = computedRows; }
javascript
function filterRows(columnFilters) { var _this4 = this; var fromFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; // if (!this.rows.length) return; // this is invoked either as a result of changing filters // or as a result of modifying rows. this.columnFilters = columnFilters; var computedRows = cloneDeep(this.originalRows); // do we have a filter to care about? // if not we don't need to do anything if (this.columnFilters && Object.keys(this.columnFilters).length) { // every time we filter rows, we need to set current page // to 1 // if the mode is remote, we only need to reset, if this is // being called from filter, not when rows are changing if (this.mode !== 'remote' || fromFilter) { this.changePage(1); } // we need to emit an event and that's that. // but this only needs to be invoked if filter is changing // not when row object is modified. if (fromFilter) { this.$emit('on-column-filter', { columnFilters: this.columnFilters }); } // if mode is remote, we don't do any filtering here. if (this.mode === 'remote') { if (fromFilter) { this.$emit('update:isLoading', true); } else { // if remote filtering has already been taken care of. this.filteredRows = computedRows; } return; } var _loop = function _loop(i) { var col = _this4.typedColumns[i]; if (_this4.columnFilters[col.field]) { computedRows = each(computedRows, function (headerRow) { var newChildren = headerRow.children.filter(function (row) { // If column has a custom filter, use that. if (col.filterOptions && typeof col.filterOptions.filterFn === 'function') { return col.filterOptions.filterFn(_this4.collect(row, col.field), _this4.columnFilters[col.field]); } // Otherwise Use default filters var typeDef = col.typeDef; return typeDef.filterPredicate(_this4.collect(row, col.field), _this4.columnFilters[col.field]); }); // should we remove the header? headerRow.children = newChildren; }); } }; for (var i = 0; i < this.typedColumns.length; i++) { _loop(i); } } this.filteredRows = computedRows; }
[ "function", "filterRows", "(", "columnFilters", ")", "{", "var", "_this4", "=", "this", ";", "var", "fromFilter", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "true", ";", "// if (!this.rows.length) return;", "// this is invoked either as a result of changing filters", "// or as a result of modifying rows.", "this", ".", "columnFilters", "=", "columnFilters", ";", "var", "computedRows", "=", "cloneDeep", "(", "this", ".", "originalRows", ")", ";", "// do we have a filter to care about?", "// if not we don't need to do anything", "if", "(", "this", ".", "columnFilters", "&&", "Object", ".", "keys", "(", "this", ".", "columnFilters", ")", ".", "length", ")", "{", "// every time we filter rows, we need to set current page", "// to 1", "// if the mode is remote, we only need to reset, if this is", "// being called from filter, not when rows are changing", "if", "(", "this", ".", "mode", "!==", "'remote'", "||", "fromFilter", ")", "{", "this", ".", "changePage", "(", "1", ")", ";", "}", "// we need to emit an event and that's that.", "// but this only needs to be invoked if filter is changing", "// not when row object is modified.", "if", "(", "fromFilter", ")", "{", "this", ".", "$emit", "(", "'on-column-filter'", ",", "{", "columnFilters", ":", "this", ".", "columnFilters", "}", ")", ";", "}", "// if mode is remote, we don't do any filtering here.", "if", "(", "this", ".", "mode", "===", "'remote'", ")", "{", "if", "(", "fromFilter", ")", "{", "this", ".", "$emit", "(", "'update:isLoading'", ",", "true", ")", ";", "}", "else", "{", "// if remote filtering has already been taken care of.", "this", ".", "filteredRows", "=", "computedRows", ";", "}", "return", ";", "}", "var", "_loop", "=", "function", "_loop", "(", "i", ")", "{", "var", "col", "=", "_this4", ".", "typedColumns", "[", "i", "]", ";", "if", "(", "_this4", ".", "columnFilters", "[", "col", ".", "field", "]", ")", "{", "computedRows", "=", "each", "(", "computedRows", ",", "function", "(", "headerRow", ")", "{", "var", "newChildren", "=", "headerRow", ".", "children", ".", "filter", "(", "function", "(", "row", ")", "{", "// If column has a custom filter, use that.", "if", "(", "col", ".", "filterOptions", "&&", "typeof", "col", ".", "filterOptions", ".", "filterFn", "===", "'function'", ")", "{", "return", "col", ".", "filterOptions", ".", "filterFn", "(", "_this4", ".", "collect", "(", "row", ",", "col", ".", "field", ")", ",", "_this4", ".", "columnFilters", "[", "col", ".", "field", "]", ")", ";", "}", "// Otherwise Use default filters", "var", "typeDef", "=", "col", ".", "typeDef", ";", "return", "typeDef", ".", "filterPredicate", "(", "_this4", ".", "collect", "(", "row", ",", "col", ".", "field", ")", ",", "_this4", ".", "columnFilters", "[", "col", ".", "field", "]", ")", ";", "}", ")", ";", "// should we remove the header?", "headerRow", ".", "children", "=", "newChildren", ";", "}", ")", ";", "}", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "typedColumns", ".", "length", ";", "i", "++", ")", "{", "_loop", "(", "i", ")", ";", "}", "}", "this", ".", "filteredRows", "=", "computedRows", ";", "}" ]
method to filter rows
[ "method", "to", "filter", "rows" ]
bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6
https://github.com/xaksis/vue-good-table/blob/bc13a5bb90ce1d14d07bb71e70a63bc8c8936ae6/dist/vue-good-table.cjs.js#L2037-L2105
7,502
Microsoft/tsdoc
common/scripts/install-run.js
findRushJsonFolder
function findRushJsonFolder() { if (!_rushJsonFolder) { let basePath = __dirname; let tempPath = __dirname; do { const testRushJsonPath = path.join(basePath, exports.RUSH_JSON_FILENAME); if (fs.existsSync(testRushJsonPath)) { _rushJsonFolder = basePath; break; } else { basePath = tempPath; } } while (basePath !== (tempPath = path.dirname(basePath))); // Exit the loop when we hit the disk root if (!_rushJsonFolder) { throw new Error('Unable to find rush.json.'); } } return _rushJsonFolder; }
javascript
function findRushJsonFolder() { if (!_rushJsonFolder) { let basePath = __dirname; let tempPath = __dirname; do { const testRushJsonPath = path.join(basePath, exports.RUSH_JSON_FILENAME); if (fs.existsSync(testRushJsonPath)) { _rushJsonFolder = basePath; break; } else { basePath = tempPath; } } while (basePath !== (tempPath = path.dirname(basePath))); // Exit the loop when we hit the disk root if (!_rushJsonFolder) { throw new Error('Unable to find rush.json.'); } } return _rushJsonFolder; }
[ "function", "findRushJsonFolder", "(", ")", "{", "if", "(", "!", "_rushJsonFolder", ")", "{", "let", "basePath", "=", "__dirname", ";", "let", "tempPath", "=", "__dirname", ";", "do", "{", "const", "testRushJsonPath", "=", "path", ".", "join", "(", "basePath", ",", "exports", ".", "RUSH_JSON_FILENAME", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "testRushJsonPath", ")", ")", "{", "_rushJsonFolder", "=", "basePath", ";", "break", ";", "}", "else", "{", "basePath", "=", "tempPath", ";", "}", "}", "while", "(", "basePath", "!==", "(", "tempPath", "=", "path", ".", "dirname", "(", "basePath", ")", ")", ")", ";", "// Exit the loop when we hit the disk root", "if", "(", "!", "_rushJsonFolder", ")", "{", "throw", "new", "Error", "(", "'Unable to find rush.json.'", ")", ";", "}", "}", "return", "_rushJsonFolder", ";", "}" ]
Find the absolute path to the folder containing rush.json
[ "Find", "the", "absolute", "path", "to", "the", "folder", "containing", "rush", ".", "json" ]
8f3440ae388c3a33af7781ba2faf59e4644464fb
https://github.com/Microsoft/tsdoc/blob/8f3440ae388c3a33af7781ba2faf59e4644464fb/common/scripts/install-run.js#L132-L151
7,503
Microsoft/tsdoc
common/scripts/install-run.js
ensureAndJoinPath
function ensureAndJoinPath(baseFolder, ...pathSegments) { let joinedPath = baseFolder; try { for (let pathSegment of pathSegments) { pathSegment = pathSegment.replace(/[\\\/]/g, '+'); joinedPath = path.join(joinedPath, pathSegment); if (!fs.existsSync(joinedPath)) { fs.mkdirSync(joinedPath); } } } catch (e) { throw new Error(`Error building local installation folder (${path.join(baseFolder, ...pathSegments)}): ${e}`); } return joinedPath; }
javascript
function ensureAndJoinPath(baseFolder, ...pathSegments) { let joinedPath = baseFolder; try { for (let pathSegment of pathSegments) { pathSegment = pathSegment.replace(/[\\\/]/g, '+'); joinedPath = path.join(joinedPath, pathSegment); if (!fs.existsSync(joinedPath)) { fs.mkdirSync(joinedPath); } } } catch (e) { throw new Error(`Error building local installation folder (${path.join(baseFolder, ...pathSegments)}): ${e}`); } return joinedPath; }
[ "function", "ensureAndJoinPath", "(", "baseFolder", ",", "...", "pathSegments", ")", "{", "let", "joinedPath", "=", "baseFolder", ";", "try", "{", "for", "(", "let", "pathSegment", "of", "pathSegments", ")", "{", "pathSegment", "=", "pathSegment", ".", "replace", "(", "/", "[\\\\\\/]", "/", "g", ",", "'+'", ")", ";", "joinedPath", "=", "path", ".", "join", "(", "joinedPath", ",", "pathSegment", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "joinedPath", ")", ")", "{", "fs", ".", "mkdirSync", "(", "joinedPath", ")", ";", "}", "}", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "`", "${", "path", ".", "join", "(", "baseFolder", ",", "...", "pathSegments", ")", "}", "${", "e", "}", "`", ")", ";", "}", "return", "joinedPath", ";", "}" ]
Create missing directories under the specified base directory, and return the resolved directory. Does not support "." or ".." path segments. Assumes the baseFolder exists.
[ "Create", "missing", "directories", "under", "the", "specified", "base", "directory", "and", "return", "the", "resolved", "directory", "." ]
8f3440ae388c3a33af7781ba2faf59e4644464fb
https://github.com/Microsoft/tsdoc/blob/8f3440ae388c3a33af7781ba2faf59e4644464fb/common/scripts/install-run.js#L159-L174
7,504
Microsoft/tsdoc
common/scripts/install-run.js
isPackageAlreadyInstalled
function isPackageAlreadyInstalled(packageInstallFolder) { try { const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME); if (!fs.existsSync(flagFilePath)) { return false; } const fileContents = fs.readFileSync(flagFilePath).toString(); return fileContents.trim() === process.version; } catch (e) { return false; } }
javascript
function isPackageAlreadyInstalled(packageInstallFolder) { try { const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME); if (!fs.existsSync(flagFilePath)) { return false; } const fileContents = fs.readFileSync(flagFilePath).toString(); return fileContents.trim() === process.version; } catch (e) { return false; } }
[ "function", "isPackageAlreadyInstalled", "(", "packageInstallFolder", ")", "{", "try", "{", "const", "flagFilePath", "=", "path", ".", "join", "(", "packageInstallFolder", ",", "INSTALLED_FLAG_FILENAME", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "flagFilePath", ")", ")", "{", "return", "false", ";", "}", "const", "fileContents", "=", "fs", ".", "readFileSync", "(", "flagFilePath", ")", ".", "toString", "(", ")", ";", "return", "fileContents", ".", "trim", "(", ")", "===", "process", ".", "version", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
Detects if the package in the specified directory is installed
[ "Detects", "if", "the", "package", "in", "the", "specified", "directory", "is", "installed" ]
8f3440ae388c3a33af7781ba2faf59e4644464fb
https://github.com/Microsoft/tsdoc/blob/8f3440ae388c3a33af7781ba2faf59e4644464fb/common/scripts/install-run.js#L236-L248
7,505
Microsoft/tsdoc
common/scripts/install-run.js
installPackage
function installPackage(packageInstallFolder, name, version) { try { console.log(`Installing ${name}...`); const npmPath = getNpmPath(); const result = childProcess.spawnSync(npmPath, ['install'], { stdio: 'inherit', cwd: packageInstallFolder, env: process.env }); if (result.status !== 0) { throw new Error('"npm install" encountered an error'); } console.log(`Successfully installed ${name}@${version}`); } catch (e) { throw new Error(`Unable to install package: ${e}`); } }
javascript
function installPackage(packageInstallFolder, name, version) { try { console.log(`Installing ${name}...`); const npmPath = getNpmPath(); const result = childProcess.spawnSync(npmPath, ['install'], { stdio: 'inherit', cwd: packageInstallFolder, env: process.env }); if (result.status !== 0) { throw new Error('"npm install" encountered an error'); } console.log(`Successfully installed ${name}@${version}`); } catch (e) { throw new Error(`Unable to install package: ${e}`); } }
[ "function", "installPackage", "(", "packageInstallFolder", ",", "name", ",", "version", ")", "{", "try", "{", "console", ".", "log", "(", "`", "${", "name", "}", "`", ")", ";", "const", "npmPath", "=", "getNpmPath", "(", ")", ";", "const", "result", "=", "childProcess", ".", "spawnSync", "(", "npmPath", ",", "[", "'install'", "]", ",", "{", "stdio", ":", "'inherit'", ",", "cwd", ":", "packageInstallFolder", ",", "env", ":", "process", ".", "env", "}", ")", ";", "if", "(", "result", ".", "status", "!==", "0", ")", "{", "throw", "new", "Error", "(", "'\"npm install\" encountered an error'", ")", ";", "}", "console", ".", "log", "(", "`", "${", "name", "}", "${", "version", "}", "`", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "`", "${", "e", "}", "`", ")", ";", "}", "}" ]
Run "npm install" in the package install folder.
[ "Run", "npm", "install", "in", "the", "package", "install", "folder", "." ]
8f3440ae388c3a33af7781ba2faf59e4644464fb
https://github.com/Microsoft/tsdoc/blob/8f3440ae388c3a33af7781ba2faf59e4644464fb/common/scripts/install-run.js#L297-L314
7,506
Microsoft/tsdoc
common/scripts/install-run.js
getBinPath
function getBinPath(packageInstallFolder, binName) { const binFolderPath = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME, '.bin'); const resolvedBinName = (os.platform() === 'win32') ? `${binName}.cmd` : binName; return path.resolve(binFolderPath, resolvedBinName); }
javascript
function getBinPath(packageInstallFolder, binName) { const binFolderPath = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME, '.bin'); const resolvedBinName = (os.platform() === 'win32') ? `${binName}.cmd` : binName; return path.resolve(binFolderPath, resolvedBinName); }
[ "function", "getBinPath", "(", "packageInstallFolder", ",", "binName", ")", "{", "const", "binFolderPath", "=", "path", ".", "resolve", "(", "packageInstallFolder", ",", "NODE_MODULES_FOLDER_NAME", ",", "'.bin'", ")", ";", "const", "resolvedBinName", "=", "(", "os", ".", "platform", "(", ")", "===", "'win32'", ")", "?", "`", "${", "binName", "}", "`", ":", "binName", ";", "return", "path", ".", "resolve", "(", "binFolderPath", ",", "resolvedBinName", ")", ";", "}" ]
Get the ".bin" path for the package.
[ "Get", "the", ".", "bin", "path", "for", "the", "package", "." ]
8f3440ae388c3a33af7781ba2faf59e4644464fb
https://github.com/Microsoft/tsdoc/blob/8f3440ae388c3a33af7781ba2faf59e4644464fb/common/scripts/install-run.js#L318-L322
7,507
Microsoft/tsdoc
common/scripts/install-run.js
writeFlagFile
function writeFlagFile(packageInstallFolder) { try { const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME); fs.writeFileSync(flagFilePath, process.version); } catch (e) { throw new Error(`Unable to create installed.flag file in ${packageInstallFolder}`); } }
javascript
function writeFlagFile(packageInstallFolder) { try { const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME); fs.writeFileSync(flagFilePath, process.version); } catch (e) { throw new Error(`Unable to create installed.flag file in ${packageInstallFolder}`); } }
[ "function", "writeFlagFile", "(", "packageInstallFolder", ")", "{", "try", "{", "const", "flagFilePath", "=", "path", ".", "join", "(", "packageInstallFolder", ",", "INSTALLED_FLAG_FILENAME", ")", ";", "fs", ".", "writeFileSync", "(", "flagFilePath", ",", "process", ".", "version", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "`", "${", "packageInstallFolder", "}", "`", ")", ";", "}", "}" ]
Write a flag file to the package's install directory, signifying that the install was successful.
[ "Write", "a", "flag", "file", "to", "the", "package", "s", "install", "directory", "signifying", "that", "the", "install", "was", "successful", "." ]
8f3440ae388c3a33af7781ba2faf59e4644464fb
https://github.com/Microsoft/tsdoc/blob/8f3440ae388c3a33af7781ba2faf59e4644464fb/common/scripts/install-run.js#L326-L334
7,508
node-pinus/pinus
examples/websocket-chat-ts-run/web-server/public/js/client.js
addMessage
function addMessage(from, target, text, time) { var name = (target == '*' ? 'all' : target); if(text === null) return; if(time == null) { // if the time is null or undefined, use the current time. time = new Date(); } else if((time instanceof Date) === false) { // if it's a timestamp, interpret it time = new Date(time); } //every message you see is actually a table with 3 cols: // the time, // the person who caused the event, // and the content var messageElement = $(document.createElement("table")); messageElement.addClass("message"); // sanitize text = util.toStaticHTML(text); var content = '<tr>' + ' <td class="date">' + util.timeString(time) + '</td>' + ' <td class="nick">' + util.toStaticHTML(from) + ' says to ' + name + ': ' + '</td>' + ' <td class="msg-text">' + text + '</td>' + '</tr>'; messageElement.html(content); //the log is the stream that we view $("#chatHistory").append(messageElement); base += increase; scrollDown(base); }
javascript
function addMessage(from, target, text, time) { var name = (target == '*' ? 'all' : target); if(text === null) return; if(time == null) { // if the time is null or undefined, use the current time. time = new Date(); } else if((time instanceof Date) === false) { // if it's a timestamp, interpret it time = new Date(time); } //every message you see is actually a table with 3 cols: // the time, // the person who caused the event, // and the content var messageElement = $(document.createElement("table")); messageElement.addClass("message"); // sanitize text = util.toStaticHTML(text); var content = '<tr>' + ' <td class="date">' + util.timeString(time) + '</td>' + ' <td class="nick">' + util.toStaticHTML(from) + ' says to ' + name + ': ' + '</td>' + ' <td class="msg-text">' + text + '</td>' + '</tr>'; messageElement.html(content); //the log is the stream that we view $("#chatHistory").append(messageElement); base += increase; scrollDown(base); }
[ "function", "addMessage", "(", "from", ",", "target", ",", "text", ",", "time", ")", "{", "var", "name", "=", "(", "target", "==", "'*'", "?", "'all'", ":", "target", ")", ";", "if", "(", "text", "===", "null", ")", "return", ";", "if", "(", "time", "==", "null", ")", "{", "// if the time is null or undefined, use the current time.", "time", "=", "new", "Date", "(", ")", ";", "}", "else", "if", "(", "(", "time", "instanceof", "Date", ")", "===", "false", ")", "{", "// if it's a timestamp, interpret it", "time", "=", "new", "Date", "(", "time", ")", ";", "}", "//every message you see is actually a table with 3 cols:", "// the time,", "// the person who caused the event,", "// and the content", "var", "messageElement", "=", "$", "(", "document", ".", "createElement", "(", "\"table\"", ")", ")", ";", "messageElement", ".", "addClass", "(", "\"message\"", ")", ";", "// sanitize", "text", "=", "util", ".", "toStaticHTML", "(", "text", ")", ";", "var", "content", "=", "'<tr>'", "+", "' <td class=\"date\">'", "+", "util", ".", "timeString", "(", "time", ")", "+", "'</td>'", "+", "' <td class=\"nick\">'", "+", "util", ".", "toStaticHTML", "(", "from", ")", "+", "' says to '", "+", "name", "+", "': '", "+", "'</td>'", "+", "' <td class=\"msg-text\">'", "+", "text", "+", "'</td>'", "+", "'</tr>'", ";", "messageElement", ".", "html", "(", "content", ")", ";", "//the log is the stream that we view", "$", "(", "\"#chatHistory\"", ")", ".", "append", "(", "messageElement", ")", ";", "base", "+=", "increase", ";", "scrollDown", "(", "base", ")", ";", "}" ]
add message on board
[ "add", "message", "on", "board" ]
985ba74bc4ef4bab12d4b0cc677c8c07c557d8de
https://github.com/node-pinus/pinus/blob/985ba74bc4ef4bab12d4b0cc677c8c07c557d8de/examples/websocket-chat-ts-run/web-server/public/js/client.js#L52-L76
7,509
node-pinus/pinus
examples/websocket-chat-ts-run/web-server/public/js/client.js
initUserList
function initUserList(data) { users = data.users; for(var i = 0; i < users.length; i++) { var slElement = $(document.createElement("option")); slElement.attr("value", users[i]); slElement.text(users[i]); $("#usersList").append(slElement); } }
javascript
function initUserList(data) { users = data.users; for(var i = 0; i < users.length; i++) { var slElement = $(document.createElement("option")); slElement.attr("value", users[i]); slElement.text(users[i]); $("#usersList").append(slElement); } }
[ "function", "initUserList", "(", "data", ")", "{", "users", "=", "data", ".", "users", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "users", ".", "length", ";", "i", "++", ")", "{", "var", "slElement", "=", "$", "(", "document", ".", "createElement", "(", "\"option\"", ")", ")", ";", "slElement", ".", "attr", "(", "\"value\"", ",", "users", "[", "i", "]", ")", ";", "slElement", ".", "text", "(", "users", "[", "i", "]", ")", ";", "$", "(", "\"#usersList\"", ")", ".", "append", "(", "slElement", ")", ";", "}", "}" ]
init user list
[ "init", "user", "list" ]
985ba74bc4ef4bab12d4b0cc677c8c07c557d8de
https://github.com/node-pinus/pinus/blob/985ba74bc4ef4bab12d4b0cc677c8c07c557d8de/examples/websocket-chat-ts-run/web-server/public/js/client.js#L99-L107
7,510
node-pinus/pinus
examples/websocket-chat-ts-run/web-server/public/js/client.js
addUser
function addUser(user) { var slElement = $(document.createElement("option")); slElement.attr("value", user); slElement.text(user); $("#usersList").append(slElement); }
javascript
function addUser(user) { var slElement = $(document.createElement("option")); slElement.attr("value", user); slElement.text(user); $("#usersList").append(slElement); }
[ "function", "addUser", "(", "user", ")", "{", "var", "slElement", "=", "$", "(", "document", ".", "createElement", "(", "\"option\"", ")", ")", ";", "slElement", ".", "attr", "(", "\"value\"", ",", "user", ")", ";", "slElement", ".", "text", "(", "user", ")", ";", "$", "(", "\"#usersList\"", ")", ".", "append", "(", "slElement", ")", ";", "}" ]
add user in user list
[ "add", "user", "in", "user", "list" ]
985ba74bc4ef4bab12d4b0cc677c8c07c557d8de
https://github.com/node-pinus/pinus/blob/985ba74bc4ef4bab12d4b0cc677c8c07c557d8de/examples/websocket-chat-ts-run/web-server/public/js/client.js#L110-L115
7,511
node-pinus/pinus
tools/pinus-admin-web/public/front/TimelineOverviewPane.js
markPercentagesForRecord
function markPercentagesForRecord(record) { if (!(this._showShortEvents || record.isLong())) return; var percentages = this._overviewCalculator.computeBarGraphPercentages(record); var end = Math.round(percentages.end); var categoryName = record.category.name; for (var j = Math.round(percentages.start); j <= end; ++j) timelines[categoryName][j] = true; }
javascript
function markPercentagesForRecord(record) { if (!(this._showShortEvents || record.isLong())) return; var percentages = this._overviewCalculator.computeBarGraphPercentages(record); var end = Math.round(percentages.end); var categoryName = record.category.name; for (var j = Math.round(percentages.start); j <= end; ++j) timelines[categoryName][j] = true; }
[ "function", "markPercentagesForRecord", "(", "record", ")", "{", "if", "(", "!", "(", "this", ".", "_showShortEvents", "||", "record", ".", "isLong", "(", ")", ")", ")", "return", ";", "var", "percentages", "=", "this", ".", "_overviewCalculator", ".", "computeBarGraphPercentages", "(", "record", ")", ";", "var", "end", "=", "Math", ".", "round", "(", "percentages", ".", "end", ")", ";", "var", "categoryName", "=", "record", ".", "category", ".", "name", ";", "for", "(", "var", "j", "=", "Math", ".", "round", "(", "percentages", ".", "start", ")", ";", "j", "<=", "end", ";", "++", "j", ")", "timelines", "[", "categoryName", "]", "[", "j", "]", "=", "true", ";", "}" ]
Create sparse arrays with 101 cells each to fill with chunks for a given category.
[ "Create", "sparse", "arrays", "with", "101", "cells", "each", "to", "fill", "with", "chunks", "for", "a", "given", "category", "." ]
985ba74bc4ef4bab12d4b0cc677c8c07c557d8de
https://github.com/node-pinus/pinus/blob/985ba74bc4ef4bab12d4b0cc677c8c07c557d8de/tools/pinus-admin-web/public/front/TimelineOverviewPane.js#L219-L229
7,512
node-pinus/pinus
examples/websocket-chat-ts-run/web-server/public/js/lib/build/build.js
function(data) { if(!data || !data.sys) { return; } dict = data.sys.dict; var protos = data.sys.protos; //Init compress dict if(dict) { dict = dict; abbrs = {}; for(var route in dict) { abbrs[dict[route]] = route; } } //Init protobuf protos if(protos) { protoVersion = protos.version || 0; serverProtos = protos.server || {}; clientProtos = protos.client || {}; //Save protobuf protos to localStorage window.localStorage.setItem('protos', JSON.stringify(protos)); if(!!protobuf) { protobuf.init({encoderProtos: protos.client, decoderProtos: protos.server}); } if(!!decodeIO_protobuf) { decodeIO_encoder = decodeIO_protobuf.loadJson(clientProtos); decodeIO_decoder = decodeIO_protobuf.loadJson(serverProtos); } } }
javascript
function(data) { if(!data || !data.sys) { return; } dict = data.sys.dict; var protos = data.sys.protos; //Init compress dict if(dict) { dict = dict; abbrs = {}; for(var route in dict) { abbrs[dict[route]] = route; } } //Init protobuf protos if(protos) { protoVersion = protos.version || 0; serverProtos = protos.server || {}; clientProtos = protos.client || {}; //Save protobuf protos to localStorage window.localStorage.setItem('protos', JSON.stringify(protos)); if(!!protobuf) { protobuf.init({encoderProtos: protos.client, decoderProtos: protos.server}); } if(!!decodeIO_protobuf) { decodeIO_encoder = decodeIO_protobuf.loadJson(clientProtos); decodeIO_decoder = decodeIO_protobuf.loadJson(serverProtos); } } }
[ "function", "(", "data", ")", "{", "if", "(", "!", "data", "||", "!", "data", ".", "sys", ")", "{", "return", ";", "}", "dict", "=", "data", ".", "sys", ".", "dict", ";", "var", "protos", "=", "data", ".", "sys", ".", "protos", ";", "//Init compress dict", "if", "(", "dict", ")", "{", "dict", "=", "dict", ";", "abbrs", "=", "{", "}", ";", "for", "(", "var", "route", "in", "dict", ")", "{", "abbrs", "[", "dict", "[", "route", "]", "]", "=", "route", ";", "}", "}", "//Init protobuf protos", "if", "(", "protos", ")", "{", "protoVersion", "=", "protos", ".", "version", "||", "0", ";", "serverProtos", "=", "protos", ".", "server", "||", "{", "}", ";", "clientProtos", "=", "protos", ".", "client", "||", "{", "}", ";", "//Save protobuf protos to localStorage", "window", ".", "localStorage", ".", "setItem", "(", "'protos'", ",", "JSON", ".", "stringify", "(", "protos", ")", ")", ";", "if", "(", "!", "!", "protobuf", ")", "{", "protobuf", ".", "init", "(", "{", "encoderProtos", ":", "protos", ".", "client", ",", "decoderProtos", ":", "protos", ".", "server", "}", ")", ";", "}", "if", "(", "!", "!", "decodeIO_protobuf", ")", "{", "decodeIO_encoder", "=", "decodeIO_protobuf", ".", "loadJson", "(", "clientProtos", ")", ";", "decodeIO_decoder", "=", "decodeIO_protobuf", ".", "loadJson", "(", "serverProtos", ")", ";", "}", "}", "}" ]
Initilize data used in pomelo client
[ "Initilize", "data", "used", "in", "pomelo", "client" ]
985ba74bc4ef4bab12d4b0cc677c8c07c557d8de
https://github.com/node-pinus/pinus/blob/985ba74bc4ef4bab12d4b0cc677c8c07c557d8de/examples/websocket-chat-ts-run/web-server/public/js/lib/build/build.js#L1776-L1810
7,513
node-pinus/pinus
tools/pinus-admin-web/public/front/TextViewer.js
forwardWheelEvent
function forwardWheelEvent(event) { var clone = document.createEvent("WheelEvent"); clone.initWebKitWheelEvent(event.wheelDeltaX, event.wheelDeltaY, event.view, event.screenX, event.screenY, event.clientX, event.clientY, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey); this._mainPanel.element.dispatchEvent(clone); }
javascript
function forwardWheelEvent(event) { var clone = document.createEvent("WheelEvent"); clone.initWebKitWheelEvent(event.wheelDeltaX, event.wheelDeltaY, event.view, event.screenX, event.screenY, event.clientX, event.clientY, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey); this._mainPanel.element.dispatchEvent(clone); }
[ "function", "forwardWheelEvent", "(", "event", ")", "{", "var", "clone", "=", "document", ".", "createEvent", "(", "\"WheelEvent\"", ")", ";", "clone", ".", "initWebKitWheelEvent", "(", "event", ".", "wheelDeltaX", ",", "event", ".", "wheelDeltaY", ",", "event", ".", "view", ",", "event", ".", "screenX", ",", "event", ".", "screenY", ",", "event", ".", "clientX", ",", "event", ".", "clientY", ",", "event", ".", "ctrlKey", ",", "event", ".", "altKey", ",", "event", ".", "shiftKey", ",", "event", ".", "metaKey", ")", ";", "this", ".", "_mainPanel", ".", "element", ".", "dispatchEvent", "(", "clone", ")", ";", "}" ]
Forward mouse wheel events from the unscrollable gutter to the main panel.
[ "Forward", "mouse", "wheel", "events", "from", "the", "unscrollable", "gutter", "to", "the", "main", "panel", "." ]
985ba74bc4ef4bab12d4b0cc677c8c07c557d8de
https://github.com/node-pinus/pinus/blob/985ba74bc4ef4bab12d4b0cc677c8c07c557d8de/tools/pinus-admin-web/public/front/TextViewer.js#L59-L68
7,514
node-pinus/pinus
tools/pinus-admin-web/public/front/TextViewer.js
function(oldRange, newRange, oldText, newText) { if (!this._internalTextChangeMode) this._textModel.resetUndoStack(); this._mainPanel.textChanged(oldRange, newRange); this._gutterPanel.textChanged(oldRange, newRange); this._updatePanelOffsets(); }
javascript
function(oldRange, newRange, oldText, newText) { if (!this._internalTextChangeMode) this._textModel.resetUndoStack(); this._mainPanel.textChanged(oldRange, newRange); this._gutterPanel.textChanged(oldRange, newRange); this._updatePanelOffsets(); }
[ "function", "(", "oldRange", ",", "newRange", ",", "oldText", ",", "newText", ")", "{", "if", "(", "!", "this", ".", "_internalTextChangeMode", ")", "this", ".", "_textModel", ".", "resetUndoStack", "(", ")", ";", "this", ".", "_mainPanel", ".", "textChanged", "(", "oldRange", ",", "newRange", ")", ";", "this", ".", "_gutterPanel", ".", "textChanged", "(", "oldRange", ",", "newRange", ")", ";", "this", ".", "_updatePanelOffsets", "(", ")", ";", "}" ]
WebInspector.TextModel listener
[ "WebInspector", ".", "TextModel", "listener" ]
985ba74bc4ef4bab12d4b0cc677c8c07c557d8de
https://github.com/node-pinus/pinus/blob/985ba74bc4ef4bab12d4b0cc677c8c07c557d8de/tools/pinus-admin-web/public/front/TextViewer.js#L180-L187
7,515
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
function(data){ if(!data || !data.sys) { return; } pinus.data = pinus.data || {}; var dict = data.sys.dict; var protos = data.sys.protos; //Init compress dict if(dict){ pinus.data.dict = dict; pinus.data.abbrs = {}; for(var route in dict){ pinus.data.abbrs[dict[route]] = route; } } //Init protobuf protos if(protos){ pinus.data.protos = { server : protos.server || {}, client : protos.client || {} }; if(!!protobuf){ protobuf.init({encoderProtos: protos.client, decoderProtos: protos.server}); } } }
javascript
function(data){ if(!data || !data.sys) { return; } pinus.data = pinus.data || {}; var dict = data.sys.dict; var protos = data.sys.protos; //Init compress dict if(dict){ pinus.data.dict = dict; pinus.data.abbrs = {}; for(var route in dict){ pinus.data.abbrs[dict[route]] = route; } } //Init protobuf protos if(protos){ pinus.data.protos = { server : protos.server || {}, client : protos.client || {} }; if(!!protobuf){ protobuf.init({encoderProtos: protos.client, decoderProtos: protos.server}); } } }
[ "function", "(", "data", ")", "{", "if", "(", "!", "data", "||", "!", "data", ".", "sys", ")", "{", "return", ";", "}", "pinus", ".", "data", "=", "pinus", ".", "data", "||", "{", "}", ";", "var", "dict", "=", "data", ".", "sys", ".", "dict", ";", "var", "protos", "=", "data", ".", "sys", ".", "protos", ";", "//Init compress dict", "if", "(", "dict", ")", "{", "pinus", ".", "data", ".", "dict", "=", "dict", ";", "pinus", ".", "data", ".", "abbrs", "=", "{", "}", ";", "for", "(", "var", "route", "in", "dict", ")", "{", "pinus", ".", "data", ".", "abbrs", "[", "dict", "[", "route", "]", "]", "=", "route", ";", "}", "}", "//Init protobuf protos", "if", "(", "protos", ")", "{", "pinus", ".", "data", ".", "protos", "=", "{", "server", ":", "protos", ".", "server", "||", "{", "}", ",", "client", ":", "protos", ".", "client", "||", "{", "}", "}", ";", "if", "(", "!", "!", "protobuf", ")", "{", "protobuf", ".", "init", "(", "{", "encoderProtos", ":", "protos", ".", "client", ",", "decoderProtos", ":", "protos", ".", "server", "}", ")", ";", "}", "}", "}" ]
Initilize data used in pinus client
[ "Initilize", "data", "used", "in", "pinus", "client" ]
985ba74bc4ef4bab12d4b0cc677c8c07c557d8de
https://github.com/node-pinus/pinus/blob/985ba74bc4ef4bab12d4b0cc677c8c07c557d8de/examples/simple-example/web-server/public/js/lib/build/build.js#L1667-L1695
7,516
node-pinus/pinus
tools/pinus-admin-web/public/front/TextPrompt.js
function(text) { if (this._uncommittedIsTop) { this._data.pop(); delete this._uncommittedIsTop; } this._historyOffset = 1; if (this._coalesceHistoryDupes && text === this._currentHistoryItem()) return; this._data.push(text); }
javascript
function(text) { if (this._uncommittedIsTop) { this._data.pop(); delete this._uncommittedIsTop; } this._historyOffset = 1; if (this._coalesceHistoryDupes && text === this._currentHistoryItem()) return; this._data.push(text); }
[ "function", "(", "text", ")", "{", "if", "(", "this", ".", "_uncommittedIsTop", ")", "{", "this", ".", "_data", ".", "pop", "(", ")", ";", "delete", "this", ".", "_uncommittedIsTop", ";", "}", "this", ".", "_historyOffset", "=", "1", ";", "if", "(", "this", ".", "_coalesceHistoryDupes", "&&", "text", "===", "this", ".", "_currentHistoryItem", "(", ")", ")", "return", ";", "this", ".", "_data", ".", "push", "(", "text", ")", ";", "}" ]
Pushes a committed text into the history. @param {string} text
[ "Pushes", "a", "committed", "text", "into", "the", "history", "." ]
985ba74bc4ef4bab12d4b0cc677c8c07c557d8de
https://github.com/node-pinus/pinus/blob/985ba74bc4ef4bab12d4b0cc677c8c07c557d8de/tools/pinus-admin-web/public/front/TextPrompt.js#L799-L810
7,517
node-pinus/pinus
tools/pinus-robot/dist/lib/console/js/ui/webclient.jquery.js
calc_screen_size
function calc_screen_size(scount) { if (!scount) { scount = $("#screens .screen").length; } var ssize = (($(window).height() - bottom_height - 20) / scount) - (bar_height + 53); return ssize; }
javascript
function calc_screen_size(scount) { if (!scount) { scount = $("#screens .screen").length; } var ssize = (($(window).height() - bottom_height - 20) / scount) - (bar_height + 53); return ssize; }
[ "function", "calc_screen_size", "(", "scount", ")", "{", "if", "(", "!", "scount", ")", "{", "scount", "=", "$", "(", "\"#screens .screen\"", ")", ".", "length", ";", "}", "var", "ssize", "=", "(", "(", "$", "(", "window", ")", ".", "height", "(", ")", "-", "bottom_height", "-", "20", ")", "/", "scount", ")", "-", "(", "bar_height", "+", "53", ")", ";", "return", "ssize", ";", "}" ]
Calculate individual screen size
[ "Calculate", "individual", "screen", "size" ]
985ba74bc4ef4bab12d4b0cc677c8c07c557d8de
https://github.com/node-pinus/pinus/blob/985ba74bc4ef4bab12d4b0cc677c8c07c557d8de/tools/pinus-robot/dist/lib/console/js/ui/webclient.jquery.js#L113-L118
7,518
node-pinus/pinus
tools/pinus-admin-web/public/js/socket.io.js
SocketNamespace
function SocketNamespace (socket, name) { this.socket = socket; this.name = name || ''; this.flags = {}; this.json = new Flag(this, 'json'); this.ackPackets = 0; this.acks = {}; }
javascript
function SocketNamespace (socket, name) { this.socket = socket; this.name = name || ''; this.flags = {}; this.json = new Flag(this, 'json'); this.ackPackets = 0; this.acks = {}; }
[ "function", "SocketNamespace", "(", "socket", ",", "name", ")", "{", "this", ".", "socket", "=", "socket", ";", "this", ".", "name", "=", "name", "||", "''", ";", "this", ".", "flags", "=", "{", "}", ";", "this", ".", "json", "=", "new", "Flag", "(", "this", ",", "'json'", ")", ";", "this", ".", "ackPackets", "=", "0", ";", "this", ".", "acks", "=", "{", "}", ";", "}" ]
Socket namespace constructor. @constructor @api public
[ "Socket", "namespace", "constructor", "." ]
985ba74bc4ef4bab12d4b0cc677c8c07c557d8de
https://github.com/node-pinus/pinus/blob/985ba74bc4ef4bab12d4b0cc677c8c07c557d8de/tools/pinus-admin-web/public/js/socket.io.js#L2011-L2018
7,519
node-pinus/pinus
tools/pinus-admin-web/public/js/socket.io.js
JSONPPolling
function JSONPPolling (socket) { io.Transport['xhr-polling'].apply(this, arguments); this.index = io.j.length; var self = this; io.j.push(function (msg) { self._(msg); }); }
javascript
function JSONPPolling (socket) { io.Transport['xhr-polling'].apply(this, arguments); this.index = io.j.length; var self = this; io.j.push(function (msg) { self._(msg); }); }
[ "function", "JSONPPolling", "(", "socket", ")", "{", "io", ".", "Transport", "[", "'xhr-polling'", "]", ".", "apply", "(", "this", ",", "arguments", ")", ";", "this", ".", "index", "=", "io", ".", "j", ".", "length", ";", "var", "self", "=", "this", ";", "io", ".", "j", ".", "push", "(", "function", "(", "msg", ")", "{", "self", ".", "_", "(", "msg", ")", ";", "}", ")", ";", "}" ]
The JSONP transport creates an persistent connection by dynamically inserting a script tag in the page. This script tag will receive the information of the Socket.IO server. When new information is received it creates a new script tag for the new data stream. @constructor @extends {io.Transport.xhr-polling} @api public
[ "The", "JSONP", "transport", "creates", "an", "persistent", "connection", "by", "dynamically", "inserting", "a", "script", "tag", "in", "the", "page", ".", "This", "script", "tag", "will", "receive", "the", "information", "of", "the", "Socket", ".", "IO", "server", ".", "When", "new", "information", "is", "received", "it", "creates", "a", "new", "script", "tag", "for", "the", "new", "data", "stream", "." ]
985ba74bc4ef4bab12d4b0cc677c8c07c557d8de
https://github.com/node-pinus/pinus/blob/985ba74bc4ef4bab12d4b0cc677c8c07c557d8de/tools/pinus-admin-web/public/js/socket.io.js#L3532-L3542
7,520
ethereum/remix
remix-debug/src/solidity-decoder/astHelper.js
extractStateDefinitions
function extractStateDefinitions (contractName, sourcesList, contracts) { if (!contracts) { contracts = extractContractDefinitions(sourcesList) } var node = contracts.contractsByName[contractName] if (node) { var stateItems = [] var stateVar = [] var baseContracts = getLinearizedBaseContracts(node.id, contracts.contractsById) baseContracts.reverse() for (var k in baseContracts) { var ctr = baseContracts[k] for (var i in ctr.children) { var item = ctr.children[i] stateItems.push(item) if (item.name === 'VariableDeclaration') { stateVar.push(item) } } } return { stateDefinitions: stateItems, stateVariables: stateVar } } return null }
javascript
function extractStateDefinitions (contractName, sourcesList, contracts) { if (!contracts) { contracts = extractContractDefinitions(sourcesList) } var node = contracts.contractsByName[contractName] if (node) { var stateItems = [] var stateVar = [] var baseContracts = getLinearizedBaseContracts(node.id, contracts.contractsById) baseContracts.reverse() for (var k in baseContracts) { var ctr = baseContracts[k] for (var i in ctr.children) { var item = ctr.children[i] stateItems.push(item) if (item.name === 'VariableDeclaration') { stateVar.push(item) } } } return { stateDefinitions: stateItems, stateVariables: stateVar } } return null }
[ "function", "extractStateDefinitions", "(", "contractName", ",", "sourcesList", ",", "contracts", ")", "{", "if", "(", "!", "contracts", ")", "{", "contracts", "=", "extractContractDefinitions", "(", "sourcesList", ")", "}", "var", "node", "=", "contracts", ".", "contractsByName", "[", "contractName", "]", "if", "(", "node", ")", "{", "var", "stateItems", "=", "[", "]", "var", "stateVar", "=", "[", "]", "var", "baseContracts", "=", "getLinearizedBaseContracts", "(", "node", ".", "id", ",", "contracts", ".", "contractsById", ")", "baseContracts", ".", "reverse", "(", ")", "for", "(", "var", "k", "in", "baseContracts", ")", "{", "var", "ctr", "=", "baseContracts", "[", "k", "]", "for", "(", "var", "i", "in", "ctr", ".", "children", ")", "{", "var", "item", "=", "ctr", ".", "children", "[", "i", "]", "stateItems", ".", "push", "(", "item", ")", "if", "(", "item", ".", "name", "===", "'VariableDeclaration'", ")", "{", "stateVar", ".", "push", "(", "item", ")", "}", "}", "}", "return", "{", "stateDefinitions", ":", "stateItems", ",", "stateVariables", ":", "stateVar", "}", "}", "return", "null", "}" ]
return state var and type definition of the given contract @param {String} contractName - contract for which state var should be resolved @param {Object} sourcesList - sources list (containing root AST node) @param {Object} [contracts] - map of contract definitions (contains contractsById, contractsByName) @return {Object} - return an object containing: stateItems - list of all the children node of the @arg contractName stateVariables - list of all the variable declaration of the @arg contractName
[ "return", "state", "var", "and", "type", "definition", "of", "the", "given", "contract" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-debug/src/solidity-decoder/astHelper.js#L49-L75
7,521
ethereum/remix
remix-lib/src/util.js
function (hexString) { if (hexString.slice(0, 2) === '0x') { hexString = hexString.slice(2) } var integers = [] for (var i = 0; i < hexString.length; i += 2) { integers.push(parseInt(hexString.slice(i, i + 2), 16)) } return integers }
javascript
function (hexString) { if (hexString.slice(0, 2) === '0x') { hexString = hexString.slice(2) } var integers = [] for (var i = 0; i < hexString.length; i += 2) { integers.push(parseInt(hexString.slice(i, i + 2), 16)) } return integers }
[ "function", "(", "hexString", ")", "{", "if", "(", "hexString", ".", "slice", "(", "0", ",", "2", ")", "===", "'0x'", ")", "{", "hexString", "=", "hexString", ".", "slice", "(", "2", ")", "}", "var", "integers", "=", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "hexString", ".", "length", ";", "i", "+=", "2", ")", "{", "integers", ".", "push", "(", "parseInt", "(", "hexString", ".", "slice", "(", "i", ",", "i", "+", "2", ")", ",", "16", ")", ")", "}", "return", "integers", "}" ]
Converts a hex string to an array of integers.
[ "Converts", "a", "hex", "string", "to", "an", "array", "of", "integers", "." ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-lib/src/util.js#L33-L42
7,522
ethereum/remix
remix-debug/src/storage/mappingPreimages.js
getPreimage
function getPreimage (web3, key) { return new Promise((resolve, reject) => { web3.debug.preimage(key.indexOf('0x') === 0 ? key : '0x' + key, function (error, preimage) { if (error) { resolve(null) } else { resolve(preimage) } }) }) }
javascript
function getPreimage (web3, key) { return new Promise((resolve, reject) => { web3.debug.preimage(key.indexOf('0x') === 0 ? key : '0x' + key, function (error, preimage) { if (error) { resolve(null) } else { resolve(preimage) } }) }) }
[ "function", "getPreimage", "(", "web3", ",", "key", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "web3", ".", "debug", ".", "preimage", "(", "key", ".", "indexOf", "(", "'0x'", ")", "===", "0", "?", "key", ":", "'0x'", "+", "key", ",", "function", "(", "error", ",", "preimage", ")", "{", "if", "(", "error", ")", "{", "resolve", "(", "null", ")", "}", "else", "{", "resolve", "(", "preimage", ")", "}", "}", ")", "}", ")", "}" ]
Uses web3 to return preimage of a key @param {String} key - key to retrieve the preimage of @return {String} - preimage of the given key
[ "Uses", "web3", "to", "return", "preimage", "of", "a", "key" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-debug/src/storage/mappingPreimages.js#L51-L61
7,523
ethereum/remix
remix-debug/src/solidity-decoder/stateDecoder.js
decodeState
async function decodeState (stateVars, storageResolver) { var ret = {} for (var k in stateVars) { var stateVar = stateVars[k] try { var decoded = await stateVar.type.decodeFromStorage(stateVar.storagelocation, storageResolver) decoded.constant = stateVar.constant if (decoded.constant) { decoded.value = '<constant>' } ret[stateVar.name] = decoded } catch (e) { console.log(e) ret[stateVar.name] = '<decoding failed - ' + e.message + '>' } } return ret }
javascript
async function decodeState (stateVars, storageResolver) { var ret = {} for (var k in stateVars) { var stateVar = stateVars[k] try { var decoded = await stateVar.type.decodeFromStorage(stateVar.storagelocation, storageResolver) decoded.constant = stateVar.constant if (decoded.constant) { decoded.value = '<constant>' } ret[stateVar.name] = decoded } catch (e) { console.log(e) ret[stateVar.name] = '<decoding failed - ' + e.message + '>' } } return ret }
[ "async", "function", "decodeState", "(", "stateVars", ",", "storageResolver", ")", "{", "var", "ret", "=", "{", "}", "for", "(", "var", "k", "in", "stateVars", ")", "{", "var", "stateVar", "=", "stateVars", "[", "k", "]", "try", "{", "var", "decoded", "=", "await", "stateVar", ".", "type", ".", "decodeFromStorage", "(", "stateVar", ".", "storagelocation", ",", "storageResolver", ")", "decoded", ".", "constant", "=", "stateVar", ".", "constant", "if", "(", "decoded", ".", "constant", ")", "{", "decoded", ".", "value", "=", "'<constant>'", "}", "ret", "[", "stateVar", ".", "name", "]", "=", "decoded", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "e", ")", "ret", "[", "stateVar", ".", "name", "]", "=", "'<decoding failed - '", "+", "e", ".", "message", "+", "'>'", "}", "}", "return", "ret", "}" ]
decode the contract state storage @param {Array} storage location - location of all state variables @param {Object} storageResolver - resolve storage queries @return {Map} - decoded state variable
[ "decode", "the", "contract", "state", "storage" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-debug/src/solidity-decoder/stateDecoder.js#L11-L28
7,524
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isDynamicArrayAccess
function isDynamicArrayAccess (node) { return node && nodeType(node, exactMatch(nodeTypes.IDENTIFIER)) && (node.attributes.type.endsWith('[] storage ref') || node.attributes.type === 'bytes storage ref' || node.attributes.type === 'string storage ref') }
javascript
function isDynamicArrayAccess (node) { return node && nodeType(node, exactMatch(nodeTypes.IDENTIFIER)) && (node.attributes.type.endsWith('[] storage ref') || node.attributes.type === 'bytes storage ref' || node.attributes.type === 'string storage ref') }
[ "function", "isDynamicArrayAccess", "(", "node", ")", "{", "return", "node", "&&", "nodeType", "(", "node", ",", "exactMatch", "(", "nodeTypes", ".", "IDENTIFIER", ")", ")", "&&", "(", "node", ".", "attributes", ".", "type", ".", "endsWith", "(", "'[] storage ref'", ")", "||", "node", ".", "attributes", ".", "type", "===", "'bytes storage ref'", "||", "node", ".", "attributes", ".", "type", "===", "'string storage ref'", ")", "}" ]
True if node is node is a ref to a dynamic array @node {ASTNode} node to check for @return {bool}
[ "True", "if", "node", "is", "node", "is", "a", "ref", "to", "a", "dynamic", "array" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L506-L508
7,525
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isConstantFunction
function isConstantFunction (node) { return isFunctionDefinition(node) && ( node.attributes.constant === true || node.attributes.stateMutability === 'view' || node.attributes.stateMutability === 'pure' ) }
javascript
function isConstantFunction (node) { return isFunctionDefinition(node) && ( node.attributes.constant === true || node.attributes.stateMutability === 'view' || node.attributes.stateMutability === 'pure' ) }
[ "function", "isConstantFunction", "(", "node", ")", "{", "return", "isFunctionDefinition", "(", "node", ")", "&&", "(", "node", ".", "attributes", ".", "constant", "===", "true", "||", "node", ".", "attributes", ".", "stateMutability", "===", "'view'", "||", "node", ".", "attributes", ".", "stateMutability", "===", "'pure'", ")", "}" ]
True if is function defintion that is flaged as constant @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "is", "function", "defintion", "that", "is", "flaged", "as", "constant" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L634-L640
7,526
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isPlusPlusUnaryOperation
function isPlusPlusUnaryOperation (node) { return nodeType(node, exactMatch(nodeTypes.UNARYOPERATION)) && operator(node, exactMatch(util.escapeRegExp('++'))) }
javascript
function isPlusPlusUnaryOperation (node) { return nodeType(node, exactMatch(nodeTypes.UNARYOPERATION)) && operator(node, exactMatch(util.escapeRegExp('++'))) }
[ "function", "isPlusPlusUnaryOperation", "(", "node", ")", "{", "return", "nodeType", "(", "node", ",", "exactMatch", "(", "nodeTypes", ".", "UNARYOPERATION", ")", ")", "&&", "operator", "(", "node", ",", "exactMatch", "(", "util", ".", "escapeRegExp", "(", "'++'", ")", ")", ")", "}" ]
True if unary increment operation @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "unary", "increment", "operation" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L705-L707
7,527
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isFullyImplementedContract
function isFullyImplementedContract (node) { return nodeType(node, exactMatch(nodeTypes.CONTRACTDEFINITION)) && node.attributes.fullyImplemented === true }
javascript
function isFullyImplementedContract (node) { return nodeType(node, exactMatch(nodeTypes.CONTRACTDEFINITION)) && node.attributes.fullyImplemented === true }
[ "function", "isFullyImplementedContract", "(", "node", ")", "{", "return", "nodeType", "(", "node", ",", "exactMatch", "(", "nodeTypes", ".", "CONTRACTDEFINITION", ")", ")", "&&", "node", ".", "attributes", ".", "fullyImplemented", "===", "true", "}" ]
True if all functions on a contract are implemented @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "all", "functions", "on", "a", "contract", "are", "implemented" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L732-L734
7,528
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isLibrary
function isLibrary (node) { return nodeType(node, exactMatch(nodeTypes.CONTRACTDEFINITION)) && node.attributes.isLibrary === true }
javascript
function isLibrary (node) { return nodeType(node, exactMatch(nodeTypes.CONTRACTDEFINITION)) && node.attributes.isLibrary === true }
[ "function", "isLibrary", "(", "node", ")", "{", "return", "nodeType", "(", "node", ",", "exactMatch", "(", "nodeTypes", ".", "CONTRACTDEFINITION", ")", ")", "&&", "node", ".", "attributes", ".", "isLibrary", "===", "true", "}" ]
True if it is a library contract defintion @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "it", "is", "a", "library", "contract", "defintion" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L741-L743
7,529
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isLibraryCall
function isLibraryCall (node) { return isMemberAccess(node, basicRegex.FUNCTIONTYPE, undefined, basicRegex.LIBRARYTYPE, undefined) }
javascript
function isLibraryCall (node) { return isMemberAccess(node, basicRegex.FUNCTIONTYPE, undefined, basicRegex.LIBRARYTYPE, undefined) }
[ "function", "isLibraryCall", "(", "node", ")", "{", "return", "isMemberAccess", "(", "node", ",", "basicRegex", ".", "FUNCTIONTYPE", ",", "undefined", ",", "basicRegex", ".", "LIBRARYTYPE", ",", "undefined", ")", "}" ]
True if it is a call to a library @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "it", "is", "a", "call", "to", "a", "library" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L759-L761
7,530
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isNowAccess
function isNowAccess (node) { return nodeType(node, exactMatch(nodeTypes.IDENTIFIER)) && expressionType(node, exactMatch(basicTypes.UINT)) && name(node, exactMatch('now')) }
javascript
function isNowAccess (node) { return nodeType(node, exactMatch(nodeTypes.IDENTIFIER)) && expressionType(node, exactMatch(basicTypes.UINT)) && name(node, exactMatch('now')) }
[ "function", "isNowAccess", "(", "node", ")", "{", "return", "nodeType", "(", "node", ",", "exactMatch", "(", "nodeTypes", ".", "IDENTIFIER", ")", ")", "&&", "expressionType", "(", "node", ",", "exactMatch", "(", "basicTypes", ".", "UINT", ")", ")", "&&", "name", "(", "node", ",", "exactMatch", "(", "'now'", ")", ")", "}" ]
True if access to block.timestamp via now alias @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "access", "to", "block", ".", "timestamp", "via", "now", "alias" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L777-L781
7,531
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isBlockBlockHashAccess
function isBlockBlockHashAccess (node) { return isSpecialVariableAccess(node, specialVariables.BLOCKHASH) || isBuiltinFunctionCall(node) && getLocalCallName(node) === 'blockhash' }
javascript
function isBlockBlockHashAccess (node) { return isSpecialVariableAccess(node, specialVariables.BLOCKHASH) || isBuiltinFunctionCall(node) && getLocalCallName(node) === 'blockhash' }
[ "function", "isBlockBlockHashAccess", "(", "node", ")", "{", "return", "isSpecialVariableAccess", "(", "node", ",", "specialVariables", ".", "BLOCKHASH", ")", "||", "isBuiltinFunctionCall", "(", "node", ")", "&&", "getLocalCallName", "(", "node", ")", "===", "'blockhash'", "}" ]
True if access to block.blockhash @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "access", "to", "block", ".", "blockhash" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L797-L799
7,532
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isThisLocalCall
function isThisLocalCall (node) { return isMemberAccess(node, basicRegex.FUNCTIONTYPE, exactMatch('this'), basicRegex.CONTRACTTYPE, undefined) }
javascript
function isThisLocalCall (node) { return isMemberAccess(node, basicRegex.FUNCTIONTYPE, exactMatch('this'), basicRegex.CONTRACTTYPE, undefined) }
[ "function", "isThisLocalCall", "(", "node", ")", "{", "return", "isMemberAccess", "(", "node", ",", "basicRegex", ".", "FUNCTIONTYPE", ",", "exactMatch", "(", "'this'", ")", ",", "basicRegex", ".", "CONTRACTTYPE", ",", "undefined", ")", "}" ]
True if call to local function via this keyword @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "call", "to", "local", "function", "via", "this", "keyword" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L806-L808
7,533
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isSuperLocalCall
function isSuperLocalCall (node) { return isMemberAccess(node, basicRegex.FUNCTIONTYPE, exactMatch('super'), basicRegex.CONTRACTTYPE, undefined) }
javascript
function isSuperLocalCall (node) { return isMemberAccess(node, basicRegex.FUNCTIONTYPE, exactMatch('super'), basicRegex.CONTRACTTYPE, undefined) }
[ "function", "isSuperLocalCall", "(", "node", ")", "{", "return", "isMemberAccess", "(", "node", ",", "basicRegex", ".", "FUNCTIONTYPE", ",", "exactMatch", "(", "'super'", ")", ",", "basicRegex", ".", "CONTRACTTYPE", ",", "undefined", ")", "}" ]
True if access to local function via super keyword @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "access", "to", "local", "function", "via", "super", "keyword" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L815-L817
7,534
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isLocalCall
function isLocalCall (node) { return nodeType(node, exactMatch(nodeTypes.FUNCTIONCALL)) && minNrOfChildren(node, 1) && nodeType(node.children[0], exactMatch(nodeTypes.IDENTIFIER)) && expressionType(node.children[0], basicRegex.FUNCTIONTYPE) && !expressionType(node.children[0], basicRegex.EXTERNALFUNCTIONTYPE) && nrOfChildren(node.children[0], 0) }
javascript
function isLocalCall (node) { return nodeType(node, exactMatch(nodeTypes.FUNCTIONCALL)) && minNrOfChildren(node, 1) && nodeType(node.children[0], exactMatch(nodeTypes.IDENTIFIER)) && expressionType(node.children[0], basicRegex.FUNCTIONTYPE) && !expressionType(node.children[0], basicRegex.EXTERNALFUNCTIONTYPE) && nrOfChildren(node.children[0], 0) }
[ "function", "isLocalCall", "(", "node", ")", "{", "return", "nodeType", "(", "node", ",", "exactMatch", "(", "nodeTypes", ".", "FUNCTIONCALL", ")", ")", "&&", "minNrOfChildren", "(", "node", ",", "1", ")", "&&", "nodeType", "(", "node", ".", "children", "[", "0", "]", ",", "exactMatch", "(", "nodeTypes", ".", "IDENTIFIER", ")", ")", "&&", "expressionType", "(", "node", ".", "children", "[", "0", "]", ",", "basicRegex", ".", "FUNCTIONTYPE", ")", "&&", "!", "expressionType", "(", "node", ".", "children", "[", "0", "]", ",", "basicRegex", ".", "EXTERNALFUNCTIONTYPE", ")", "&&", "nrOfChildren", "(", "node", ".", "children", "[", "0", "]", ",", "0", ")", "}" ]
True if call to local function @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "call", "to", "local", "function" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L824-L831
7,535
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isLLCall
function isLLCall (node) { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.CALL.type)), undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.CALL.ident)) }
javascript
function isLLCall (node) { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.CALL.type)), undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.CALL.ident)) }
[ "function", "isLLCall", "(", "node", ")", "{", "return", "isMemberAccess", "(", "node", ",", "exactMatch", "(", "util", ".", "escapeRegExp", "(", "lowLevelCallTypes", ".", "CALL", ".", "type", ")", ")", ",", "undefined", ",", "exactMatch", "(", "basicTypes", ".", "ADDRESS", ")", ",", "exactMatch", "(", "lowLevelCallTypes", ".", "CALL", ".", "ident", ")", ")", "}" ]
True if low level call @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "low", "level", "call" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L875-L879
7,536
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isLLCallcode
function isLLCallcode (node) { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.CALLCODE.type)), undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.CALLCODE.ident)) }
javascript
function isLLCallcode (node) { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.CALLCODE.type)), undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.CALLCODE.ident)) }
[ "function", "isLLCallcode", "(", "node", ")", "{", "return", "isMemberAccess", "(", "node", ",", "exactMatch", "(", "util", ".", "escapeRegExp", "(", "lowLevelCallTypes", ".", "CALLCODE", ".", "type", ")", ")", ",", "undefined", ",", "exactMatch", "(", "basicTypes", ".", "ADDRESS", ")", ",", "exactMatch", "(", "lowLevelCallTypes", ".", "CALLCODE", ".", "ident", ")", ")", "}" ]
True if low level callcode @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "low", "level", "callcode" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L897-L901
7,537
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
isLLDelegatecall
function isLLDelegatecall (node) { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.DELEGATECALL.type)), undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.DELEGATECALL.ident)) }
javascript
function isLLDelegatecall (node) { return isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.DELEGATECALL.type)), undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.DELEGATECALL.ident)) }
[ "function", "isLLDelegatecall", "(", "node", ")", "{", "return", "isMemberAccess", "(", "node", ",", "exactMatch", "(", "util", ".", "escapeRegExp", "(", "lowLevelCallTypes", ".", "DELEGATECALL", ".", "type", ")", ")", ",", "undefined", ",", "exactMatch", "(", "basicTypes", ".", "ADDRESS", ")", ",", "exactMatch", "(", "lowLevelCallTypes", ".", "DELEGATECALL", ".", "ident", ")", ")", "}" ]
True if low level delegatecall @node {ASTNode} some AstNode @return {bool}
[ "True", "if", "low", "level", "delegatecall" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L908-L912
7,538
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
buildFunctionSignature
function buildFunctionSignature (paramTypes, returnTypes, isPayable, additionalMods) { return 'function (' + util.concatWithSeperator(paramTypes, ',') + ')' + ((isPayable) ? ' payable' : '') + ((additionalMods) ? ' ' + additionalMods : '') + ((returnTypes.length) ? ' returns (' + util.concatWithSeperator(returnTypes, ',') + ')' : '') }
javascript
function buildFunctionSignature (paramTypes, returnTypes, isPayable, additionalMods) { return 'function (' + util.concatWithSeperator(paramTypes, ',') + ')' + ((isPayable) ? ' payable' : '') + ((additionalMods) ? ' ' + additionalMods : '') + ((returnTypes.length) ? ' returns (' + util.concatWithSeperator(returnTypes, ',') + ')' : '') }
[ "function", "buildFunctionSignature", "(", "paramTypes", ",", "returnTypes", ",", "isPayable", ",", "additionalMods", ")", "{", "return", "'function ('", "+", "util", ".", "concatWithSeperator", "(", "paramTypes", ",", "','", ")", "+", "')'", "+", "(", "(", "isPayable", ")", "?", "' payable'", ":", "''", ")", "+", "(", "(", "additionalMods", ")", "?", "' '", "+", "additionalMods", ":", "''", ")", "+", "(", "(", "returnTypes", ".", "length", ")", "?", "' returns ('", "+", "util", ".", "concatWithSeperator", "(", "returnTypes", ",", "','", ")", "+", "')'", ":", "''", ")", "}" ]
Builds an function signature as used in the AST of the solc-json AST @param {Array} paramTypes list of parameter type names @param {Array} returnTypes list of return type names @return {Boolean} isPayable
[ "Builds", "an", "function", "signature", "as", "used", "in", "the", "AST", "of", "the", "solc", "-", "json", "AST" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L1023-L1025
7,539
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
findFirstSubNodeLTR
function findFirstSubNodeLTR (node, type) { if (!node || !node.children) return null for (let i = 0; i < node.children.length; ++i) { var item = node.children[i] if (nodeType(item, type)) return item else { var res = findFirstSubNodeLTR(item, type) if (res) return res } } return null }
javascript
function findFirstSubNodeLTR (node, type) { if (!node || !node.children) return null for (let i = 0; i < node.children.length; ++i) { var item = node.children[i] if (nodeType(item, type)) return item else { var res = findFirstSubNodeLTR(item, type) if (res) return res } } return null }
[ "function", "findFirstSubNodeLTR", "(", "node", ",", "type", ")", "{", "if", "(", "!", "node", "||", "!", "node", ".", "children", ")", "return", "null", "for", "(", "let", "i", "=", "0", ";", "i", "<", "node", ".", "children", ".", "length", ";", "++", "i", ")", "{", "var", "item", "=", "node", ".", "children", "[", "i", "]", "if", "(", "nodeType", "(", "item", ",", "type", ")", ")", "return", "item", "else", "{", "var", "res", "=", "findFirstSubNodeLTR", "(", "item", ",", "type", ")", "if", "(", "res", ")", "return", "res", "}", "}", "return", "null", "}" ]
Finds first node of a certain type under a specific node. @node {AstNode} node to start form @type {String} Type the ast node should have @return {AstNode} null or node found
[ "Finds", "first", "node", "of", "a", "certain", "type", "under", "a", "specific", "node", "." ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js#L1037-L1048
7,540
ethereum/remix
remix-debug/src/Ethdebugger.js
Ethdebugger
function Ethdebugger (opts) { this.opts = opts || {} if (!this.opts.compilationResult) this.opts.compilationResult = () => { return null } this.web3 = opts.web3 this.event = new EventManager() this.tx this.traceManager = new TraceManager({web3: this.web3}) this.codeManager = new CodeManager(this.traceManager) this.solidityProxy = new SolidityProxy(this.traceManager, this.codeManager) this.storageResolver = null this.callTree = new InternalCallTree(this.event, this.traceManager, this.solidityProxy, this.codeManager, { includeLocalVariables: true }) }
javascript
function Ethdebugger (opts) { this.opts = opts || {} if (!this.opts.compilationResult) this.opts.compilationResult = () => { return null } this.web3 = opts.web3 this.event = new EventManager() this.tx this.traceManager = new TraceManager({web3: this.web3}) this.codeManager = new CodeManager(this.traceManager) this.solidityProxy = new SolidityProxy(this.traceManager, this.codeManager) this.storageResolver = null this.callTree = new InternalCallTree(this.event, this.traceManager, this.solidityProxy, this.codeManager, { includeLocalVariables: true }) }
[ "function", "Ethdebugger", "(", "opts", ")", "{", "this", ".", "opts", "=", "opts", "||", "{", "}", "if", "(", "!", "this", ".", "opts", ".", "compilationResult", ")", "this", ".", "opts", ".", "compilationResult", "=", "(", ")", "=>", "{", "return", "null", "}", "this", ".", "web3", "=", "opts", ".", "web3", "this", ".", "event", "=", "new", "EventManager", "(", ")", "this", ".", "tx", "this", ".", "traceManager", "=", "new", "TraceManager", "(", "{", "web3", ":", "this", ".", "web3", "}", ")", "this", ".", "codeManager", "=", "new", "CodeManager", "(", "this", ".", "traceManager", ")", "this", ".", "solidityProxy", "=", "new", "SolidityProxy", "(", "this", ".", "traceManager", ",", "this", ".", "codeManager", ")", "this", ".", "storageResolver", "=", "null", "this", ".", "callTree", "=", "new", "InternalCallTree", "(", "this", ".", "event", ",", "this", ".", "traceManager", ",", "this", ".", "solidityProxy", ",", "this", ".", "codeManager", ",", "{", "includeLocalVariables", ":", "true", "}", ")", "}" ]
Ethdebugger is a wrapper around a few classes that helps debugging a transaction - Web3Providers - define which environment (web3) the transaction will be retrieved from - TraceManager - Load / Analyze the trace and retrieve details of specific test - CodeManager - Retrieve loaded byte code and help to resolve AST item from vmtrace index - SolidityProxy - Basically used to extract state variable from AST - Breakpoint Manager - Used to add / remove / jumpto breakpoint - InternalCallTree - Used to retrieved local variables - StorageResolver - Help resolving the storage accross different steps @param {Map} opts - { function compilationResult } //
[ "Ethdebugger", "is", "a", "wrapper", "around", "a", "few", "classes", "that", "helps", "debugging", "a", "transaction" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-debug/src/Ethdebugger.js#L31-L47
7,541
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/gasCosts.js
visitContracts
function visitContracts (contracts, cb) { for (var file in contracts) { for (var name in contracts[file]) { if (cb({ name: name, object: contracts[file][name], file: file })) return } } }
javascript
function visitContracts (contracts, cb) { for (var file in contracts) { for (var name in contracts[file]) { if (cb({ name: name, object: contracts[file][name], file: file })) return } } }
[ "function", "visitContracts", "(", "contracts", ",", "cb", ")", "{", "for", "(", "var", "file", "in", "contracts", ")", "{", "for", "(", "var", "name", "in", "contracts", "[", "file", "]", ")", "{", "if", "(", "cb", "(", "{", "name", ":", "name", ",", "object", ":", "contracts", "[", "file", "]", "[", "name", "]", ",", "file", ":", "file", "}", ")", ")", "return", "}", "}", "}" ]
call the given @arg cb (function) for all the contracts. Uses last compilation result stop visiting when cb return true @param {Function} cb - callback @TODO has been copied from remix-ide repo ! should fix that soon !
[ "call", "the", "given" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/gasCosts.js#L15-L21
7,542
ethereum/remix
remix-lib/src/code/codeUtils.js
function (raw) { var code = [] for (var i = 0; i < raw.length; i++) { var opcode = opcodes(raw[i], true) if (opcode.name.slice(0, 4) === 'PUSH') { var length = raw[i] - 0x5f opcode.pushData = raw.slice(i + 1, i + length + 1) // in case pushdata extends beyond code if (i + 1 + length > raw.length) { for (var j = opcode.pushData.length; j < length; j++) { opcode.pushData.push(0) } } i += length } code.push(opcode) } return code }
javascript
function (raw) { var code = [] for (var i = 0; i < raw.length; i++) { var opcode = opcodes(raw[i], true) if (opcode.name.slice(0, 4) === 'PUSH') { var length = raw[i] - 0x5f opcode.pushData = raw.slice(i + 1, i + length + 1) // in case pushdata extends beyond code if (i + 1 + length > raw.length) { for (var j = opcode.pushData.length; j < length; j++) { opcode.pushData.push(0) } } i += length } code.push(opcode) } return code }
[ "function", "(", "raw", ")", "{", "var", "code", "=", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "raw", ".", "length", ";", "i", "++", ")", "{", "var", "opcode", "=", "opcodes", "(", "raw", "[", "i", "]", ",", "true", ")", "if", "(", "opcode", ".", "name", ".", "slice", "(", "0", ",", "4", ")", "===", "'PUSH'", ")", "{", "var", "length", "=", "raw", "[", "i", "]", "-", "0x5f", "opcode", ".", "pushData", "=", "raw", ".", "slice", "(", "i", "+", "1", ",", "i", "+", "length", "+", "1", ")", "// in case pushdata extends beyond code", "if", "(", "i", "+", "1", "+", "length", ">", "raw", ".", "length", ")", "{", "for", "(", "var", "j", "=", "opcode", ".", "pushData", ".", "length", ";", "j", "<", "length", ";", "j", "++", ")", "{", "opcode", ".", "pushData", ".", "push", "(", "0", ")", "}", "}", "i", "+=", "length", "}", "code", ".", "push", "(", "opcode", ")", "}", "return", "code", "}" ]
Parses code as a list of integers into a list of objects containing information about the opcode.
[ "Parses", "code", "as", "a", "list", "of", "integers", "into", "a", "list", "of", "objects", "containing", "information", "about", "the", "opcode", "." ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-lib/src/code/codeUtils.js#L33-L51
7,543
ethereum/remix
remix-lib/src/execution/txFormat.js
function (funABI, values, contractbyteCode) { var encoded var encodedHex try { encoded = helper.encodeParams(funABI, values) encodedHex = encoded.toString('hex') } catch (e) { return { error: 'cannot encode arguments' } } if (contractbyteCode) { return { data: '0x' + contractbyteCode + encodedHex.replace('0x', '') } } else { return { data: helper.encodeFunctionId(funABI) + encodedHex.replace('0x', '') } } }
javascript
function (funABI, values, contractbyteCode) { var encoded var encodedHex try { encoded = helper.encodeParams(funABI, values) encodedHex = encoded.toString('hex') } catch (e) { return { error: 'cannot encode arguments' } } if (contractbyteCode) { return { data: '0x' + contractbyteCode + encodedHex.replace('0x', '') } } else { return { data: helper.encodeFunctionId(funABI) + encodedHex.replace('0x', '') } } }
[ "function", "(", "funABI", ",", "values", ",", "contractbyteCode", ")", "{", "var", "encoded", "var", "encodedHex", "try", "{", "encoded", "=", "helper", ".", "encodeParams", "(", "funABI", ",", "values", ")", "encodedHex", "=", "encoded", ".", "toString", "(", "'hex'", ")", "}", "catch", "(", "e", ")", "{", "return", "{", "error", ":", "'cannot encode arguments'", "}", "}", "if", "(", "contractbyteCode", ")", "{", "return", "{", "data", ":", "'0x'", "+", "contractbyteCode", "+", "encodedHex", ".", "replace", "(", "'0x'", ",", "''", ")", "}", "}", "else", "{", "return", "{", "data", ":", "helper", ".", "encodeFunctionId", "(", "funABI", ")", "+", "encodedHex", ".", "replace", "(", "'0x'", ",", "''", ")", "}", "}", "}" ]
build the transaction data @param {Object} function abi @param {Object} values to encode @param {String} contractbyteCode
[ "build", "the", "transaction", "data" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-lib/src/execution/txFormat.js#L17-L31
7,544
ethereum/remix
remix-lib/src/execution/txFormat.js
function (contract, params, funAbi, linkLibraries, linkReferences, callback) { this.encodeParams(params, funAbi, (error, encodedParam) => { if (error) return callback(error) var bytecodeToDeploy = contract.evm.bytecode.object if (bytecodeToDeploy.indexOf('_') >= 0) { if (linkLibraries && linkReferences) { for (var libFile in linkLibraries) { for (var lib in linkLibraries[libFile]) { var address = linkLibraries[libFile][lib] if (!ethJSUtil.isValidAddress(address)) return callback(address + ' is not a valid address. Please check the provided address is valid.') bytecodeToDeploy = this.linkLibraryStandardFromlinkReferences(lib, address.replace('0x', ''), bytecodeToDeploy, linkReferences) } } } } if (bytecodeToDeploy.indexOf('_') >= 0) { return callback('Failed to link some libraries') } return callback(null, { dataHex: bytecodeToDeploy + encodedParam.dataHex, funAbi, funArgs: encodedParam.funArgs, contractBytecode: contract.evm.bytecode.object }) }) }
javascript
function (contract, params, funAbi, linkLibraries, linkReferences, callback) { this.encodeParams(params, funAbi, (error, encodedParam) => { if (error) return callback(error) var bytecodeToDeploy = contract.evm.bytecode.object if (bytecodeToDeploy.indexOf('_') >= 0) { if (linkLibraries && linkReferences) { for (var libFile in linkLibraries) { for (var lib in linkLibraries[libFile]) { var address = linkLibraries[libFile][lib] if (!ethJSUtil.isValidAddress(address)) return callback(address + ' is not a valid address. Please check the provided address is valid.') bytecodeToDeploy = this.linkLibraryStandardFromlinkReferences(lib, address.replace('0x', ''), bytecodeToDeploy, linkReferences) } } } } if (bytecodeToDeploy.indexOf('_') >= 0) { return callback('Failed to link some libraries') } return callback(null, { dataHex: bytecodeToDeploy + encodedParam.dataHex, funAbi, funArgs: encodedParam.funArgs, contractBytecode: contract.evm.bytecode.object }) }) }
[ "function", "(", "contract", ",", "params", ",", "funAbi", ",", "linkLibraries", ",", "linkReferences", ",", "callback", ")", "{", "this", ".", "encodeParams", "(", "params", ",", "funAbi", ",", "(", "error", ",", "encodedParam", ")", "=>", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ")", "var", "bytecodeToDeploy", "=", "contract", ".", "evm", ".", "bytecode", ".", "object", "if", "(", "bytecodeToDeploy", ".", "indexOf", "(", "'_'", ")", ">=", "0", ")", "{", "if", "(", "linkLibraries", "&&", "linkReferences", ")", "{", "for", "(", "var", "libFile", "in", "linkLibraries", ")", "{", "for", "(", "var", "lib", "in", "linkLibraries", "[", "libFile", "]", ")", "{", "var", "address", "=", "linkLibraries", "[", "libFile", "]", "[", "lib", "]", "if", "(", "!", "ethJSUtil", ".", "isValidAddress", "(", "address", ")", ")", "return", "callback", "(", "address", "+", "' is not a valid address. Please check the provided address is valid.'", ")", "bytecodeToDeploy", "=", "this", ".", "linkLibraryStandardFromlinkReferences", "(", "lib", ",", "address", ".", "replace", "(", "'0x'", ",", "''", ")", ",", "bytecodeToDeploy", ",", "linkReferences", ")", "}", "}", "}", "}", "if", "(", "bytecodeToDeploy", ".", "indexOf", "(", "'_'", ")", ">=", "0", ")", "{", "return", "callback", "(", "'Failed to link some libraries'", ")", "}", "return", "callback", "(", "null", ",", "{", "dataHex", ":", "bytecodeToDeploy", "+", "encodedParam", ".", "dataHex", ",", "funAbi", ",", "funArgs", ":", "encodedParam", ".", "funArgs", ",", "contractBytecode", ":", "contract", ".", "evm", ".", "bytecode", ".", "object", "}", ")", "}", ")", "}" ]
encode constructor creation and link with provided libraries if needed @param {Object} contract - input paramater of the function to call @param {Object} params - input paramater of the function to call @param {Object} funAbi - abi definition of the function to call. null if building data for the ctor. @param {Object} linkLibraries - contains {linkReferences} object which list all the addresses to be linked @param {Object} linkReferences - given by the compiler, contains the proper linkReferences @param {Function} callback - callback
[ "encode", "constructor", "creation", "and", "link", "with", "provided", "libraries", "if", "needed" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-lib/src/execution/txFormat.js#L100-L120
7,545
ethereum/remix
remix-lib/src/execution/txFormat.js
function (contractName, contract, contracts, params, funAbi, callback, callbackStep, callbackDeployLibrary) { this.encodeParams(params, funAbi, (error, encodedParam) => { if (error) return callback(error) var dataHex = '' var contractBytecode = contract.evm.bytecode.object var bytecodeToDeploy = contract.evm.bytecode.object if (bytecodeToDeploy.indexOf('_') >= 0) { this.linkBytecode(contract, contracts, (err, bytecode) => { if (err) { callback('Error deploying required libraries: ' + err) } else { bytecodeToDeploy = bytecode + dataHex return callback(null, {dataHex: bytecodeToDeploy, funAbi, funArgs: encodedParam.funArgs, contractBytecode, contractName: contractName}) } }, callbackStep, callbackDeployLibrary) return } else { dataHex = bytecodeToDeploy + encodedParam.dataHex } callback(null, {dataHex: bytecodeToDeploy, funAbi, funArgs: encodedParam.funArgs, contractBytecode, contractName: contractName}) }) }
javascript
function (contractName, contract, contracts, params, funAbi, callback, callbackStep, callbackDeployLibrary) { this.encodeParams(params, funAbi, (error, encodedParam) => { if (error) return callback(error) var dataHex = '' var contractBytecode = contract.evm.bytecode.object var bytecodeToDeploy = contract.evm.bytecode.object if (bytecodeToDeploy.indexOf('_') >= 0) { this.linkBytecode(contract, contracts, (err, bytecode) => { if (err) { callback('Error deploying required libraries: ' + err) } else { bytecodeToDeploy = bytecode + dataHex return callback(null, {dataHex: bytecodeToDeploy, funAbi, funArgs: encodedParam.funArgs, contractBytecode, contractName: contractName}) } }, callbackStep, callbackDeployLibrary) return } else { dataHex = bytecodeToDeploy + encodedParam.dataHex } callback(null, {dataHex: bytecodeToDeploy, funAbi, funArgs: encodedParam.funArgs, contractBytecode, contractName: contractName}) }) }
[ "function", "(", "contractName", ",", "contract", ",", "contracts", ",", "params", ",", "funAbi", ",", "callback", ",", "callbackStep", ",", "callbackDeployLibrary", ")", "{", "this", ".", "encodeParams", "(", "params", ",", "funAbi", ",", "(", "error", ",", "encodedParam", ")", "=>", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ")", "var", "dataHex", "=", "''", "var", "contractBytecode", "=", "contract", ".", "evm", ".", "bytecode", ".", "object", "var", "bytecodeToDeploy", "=", "contract", ".", "evm", ".", "bytecode", ".", "object", "if", "(", "bytecodeToDeploy", ".", "indexOf", "(", "'_'", ")", ">=", "0", ")", "{", "this", ".", "linkBytecode", "(", "contract", ",", "contracts", ",", "(", "err", ",", "bytecode", ")", "=>", "{", "if", "(", "err", ")", "{", "callback", "(", "'Error deploying required libraries: '", "+", "err", ")", "}", "else", "{", "bytecodeToDeploy", "=", "bytecode", "+", "dataHex", "return", "callback", "(", "null", ",", "{", "dataHex", ":", "bytecodeToDeploy", ",", "funAbi", ",", "funArgs", ":", "encodedParam", ".", "funArgs", ",", "contractBytecode", ",", "contractName", ":", "contractName", "}", ")", "}", "}", ",", "callbackStep", ",", "callbackDeployLibrary", ")", "return", "}", "else", "{", "dataHex", "=", "bytecodeToDeploy", "+", "encodedParam", ".", "dataHex", "}", "callback", "(", "null", ",", "{", "dataHex", ":", "bytecodeToDeploy", ",", "funAbi", ",", "funArgs", ":", "encodedParam", ".", "funArgs", ",", "contractBytecode", ",", "contractName", ":", "contractName", "}", ")", "}", ")", "}" ]
encode constructor creation and deploy librairies if needed @param {String} contractName - current contract name @param {Object} contract - input paramater of the function to call @param {Object} contracts - map of all compiled contracts. @param {Object} params - input paramater of the function to call @param {Object} funAbi - abi definition of the function to call. null if building data for the ctor. @param {Function} callback - callback @param {Function} callbackStep - callbackStep @param {Function} callbackDeployLibrary - callbackDeployLibrary @param {Function} callback - callback
[ "encode", "constructor", "creation", "and", "deploy", "librairies", "if", "needed" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-lib/src/execution/txFormat.js#L135-L156
7,546
ethereum/remix
remix-lib/src/helpers/traceHelper.js
function (vmTraceIndex, trace) { var step = trace[vmTraceIndex] if (this.isCreateInstruction(step)) { return this.contractCreationToken(vmTraceIndex) } else if (this.isCallInstruction(step)) { var stack = step.stack // callcode, delegatecall, ... return ui.normalizeHexAddress(stack[stack.length - 2]) } return undefined }
javascript
function (vmTraceIndex, trace) { var step = trace[vmTraceIndex] if (this.isCreateInstruction(step)) { return this.contractCreationToken(vmTraceIndex) } else if (this.isCallInstruction(step)) { var stack = step.stack // callcode, delegatecall, ... return ui.normalizeHexAddress(stack[stack.length - 2]) } return undefined }
[ "function", "(", "vmTraceIndex", ",", "trace", ")", "{", "var", "step", "=", "trace", "[", "vmTraceIndex", "]", "if", "(", "this", ".", "isCreateInstruction", "(", "step", ")", ")", "{", "return", "this", ".", "contractCreationToken", "(", "vmTraceIndex", ")", "}", "else", "if", "(", "this", ".", "isCallInstruction", "(", "step", ")", ")", "{", "var", "stack", "=", "step", ".", "stack", "// callcode, delegatecall, ...", "return", "ui", ".", "normalizeHexAddress", "(", "stack", "[", "stack", ".", "length", "-", "2", "]", ")", "}", "return", "undefined", "}" ]
vmTraceIndex has to point to a CALL, CODECALL, ...
[ "vmTraceIndex", "has", "to", "point", "to", "a", "CALL", "CODECALL", "..." ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-lib/src/helpers/traceHelper.js#L5-L14
7,547
ethereum/remix
remix-debug/src/solidity-decoder/decodeInfo.js
typeClass
function typeClass (fullType) { fullType = util.removeLocation(fullType) if (fullType.lastIndexOf(']') === fullType.length - 1) { return 'array' } if (fullType.indexOf('mapping') === 0) { return 'mapping' } if (fullType.indexOf(' ') !== -1) { fullType = fullType.split(' ')[0] } var char = fullType.indexOf('bytes') === 0 ? 'X' : '' return fullType.replace(/[0-9]+/g, char) }
javascript
function typeClass (fullType) { fullType = util.removeLocation(fullType) if (fullType.lastIndexOf(']') === fullType.length - 1) { return 'array' } if (fullType.indexOf('mapping') === 0) { return 'mapping' } if (fullType.indexOf(' ') !== -1) { fullType = fullType.split(' ')[0] } var char = fullType.indexOf('bytes') === 0 ? 'X' : '' return fullType.replace(/[0-9]+/g, char) }
[ "function", "typeClass", "(", "fullType", ")", "{", "fullType", "=", "util", ".", "removeLocation", "(", "fullType", ")", "if", "(", "fullType", ".", "lastIndexOf", "(", "']'", ")", "===", "fullType", ".", "length", "-", "1", ")", "{", "return", "'array'", "}", "if", "(", "fullType", ".", "indexOf", "(", "'mapping'", ")", "===", "0", ")", "{", "return", "'mapping'", "}", "if", "(", "fullType", ".", "indexOf", "(", "' '", ")", "!==", "-", "1", ")", "{", "fullType", "=", "fullType", ".", "split", "(", "' '", ")", "[", "0", "]", "}", "var", "char", "=", "fullType", ".", "indexOf", "(", "'bytes'", ")", "===", "0", "?", "'X'", ":", "''", "return", "fullType", ".", "replace", "(", "/", "[0-9]+", "/", "g", ",", "char", ")", "}" ]
parse the full type @param {String} fullType - type given by the AST (ex: uint[2] storage ref[2]) @return {String} returns the token type (used to instanciate the right decoder) (uint[2] storage ref[2] will return 'array', uint256 will return uintX)
[ "parse", "the", "full", "type" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-debug/src/solidity-decoder/decodeInfo.js#L267-L280
7,548
ethereum/remix
remix-debug/src/solidity-decoder/decodeInfo.js
parseType
function parseType (type, stateDefinitions, contractName, location) { var decodeInfos = { 'contract': address, 'address': address, 'array': array, 'bool': bool, 'bytes': dynamicByteArray, 'bytesX': fixedByteArray, 'enum': enumType, 'string': stringType, 'struct': struct, 'int': int, 'uint': uint, 'mapping': mapping } var currentType = typeClass(type) if (currentType === null) { console.log('unable to retrieve decode info of ' + type) return null } if (decodeInfos[currentType]) { return decodeInfos[currentType](type, stateDefinitions, contractName, location) } else { return null } }
javascript
function parseType (type, stateDefinitions, contractName, location) { var decodeInfos = { 'contract': address, 'address': address, 'array': array, 'bool': bool, 'bytes': dynamicByteArray, 'bytesX': fixedByteArray, 'enum': enumType, 'string': stringType, 'struct': struct, 'int': int, 'uint': uint, 'mapping': mapping } var currentType = typeClass(type) if (currentType === null) { console.log('unable to retrieve decode info of ' + type) return null } if (decodeInfos[currentType]) { return decodeInfos[currentType](type, stateDefinitions, contractName, location) } else { return null } }
[ "function", "parseType", "(", "type", ",", "stateDefinitions", ",", "contractName", ",", "location", ")", "{", "var", "decodeInfos", "=", "{", "'contract'", ":", "address", ",", "'address'", ":", "address", ",", "'array'", ":", "array", ",", "'bool'", ":", "bool", ",", "'bytes'", ":", "dynamicByteArray", ",", "'bytesX'", ":", "fixedByteArray", ",", "'enum'", ":", "enumType", ",", "'string'", ":", "stringType", ",", "'struct'", ":", "struct", ",", "'int'", ":", "int", ",", "'uint'", ":", "uint", ",", "'mapping'", ":", "mapping", "}", "var", "currentType", "=", "typeClass", "(", "type", ")", "if", "(", "currentType", "===", "null", ")", "{", "console", ".", "log", "(", "'unable to retrieve decode info of '", "+", "type", ")", "return", "null", "}", "if", "(", "decodeInfos", "[", "currentType", "]", ")", "{", "return", "decodeInfos", "[", "currentType", "]", "(", "type", ",", "stateDefinitions", ",", "contractName", ",", "location", ")", "}", "else", "{", "return", "null", "}", "}" ]
parse the type and return an object representing the type @param {Object} type - type name given by the ast node @param {Object} stateDefinitions - all state stateDefinitions given by the AST (including struct and enum type declaration) for all contracts @param {String} contractName - contract the @args typeName belongs to @param {String} location - location of the data (storage ref| storage pointer| memory| calldata) @return {Object} - return the corresponding decoder or null on error
[ "parse", "the", "type", "and", "return", "an", "object", "representing", "the", "type" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-debug/src/solidity-decoder/decodeInfo.js#L291-L316
7,549
ethereum/remix
remix-analyzer/src/solidity-analyzer/modules/functionCallGraph.js
analyseCallGraph
function analyseCallGraph (callGraph, funcName, context, nodeCheck) { return analyseCallGraphInternal(callGraph, funcName, context, (a, b) => a || b, nodeCheck, {}) }
javascript
function analyseCallGraph (callGraph, funcName, context, nodeCheck) { return analyseCallGraphInternal(callGraph, funcName, context, (a, b) => a || b, nodeCheck, {}) }
[ "function", "analyseCallGraph", "(", "callGraph", ",", "funcName", ",", "context", ",", "nodeCheck", ")", "{", "return", "analyseCallGraphInternal", "(", "callGraph", ",", "funcName", ",", "context", ",", "(", "a", ",", "b", ")", "=>", "a", "||", "b", ",", "nodeCheck", ",", "{", "}", ")", "}" ]
Walks through the call graph from a defined starting function, true if nodeCheck holds for every relevant node in the callgraph @callGraph {callGraph} As returned by buildGlobalFuncCallGraph @funcName {string} full qualified name of the starting function @context {Object} provides additional context information that can be used by the nodeCheck function @nodeCheck {(ASTNode, context) -> bool} applied on every relevant node in the call graph @return {bool} returns map from contract name to contract call graph
[ "Walks", "through", "the", "call", "graph", "from", "a", "defined", "starting", "function", "true", "if", "nodeCheck", "holds", "for", "every", "relevant", "node", "in", "the", "callgraph" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-analyzer/src/solidity-analyzer/modules/functionCallGraph.js#L64-L66
7,550
ethereum/remix
remix-lib/src/execution/txExecution.js
function (from, data, value, gasLimit, txRunner, callbacks, finalCallback) { if (!callbacks.confirmationCb || !callbacks.gasEstimationForceSend || !callbacks.promptCb) { return finalCallback('all the callbacks must have been defined') } var tx = { from: from, to: null, data: data, useCall: false, value: value, gasLimit: gasLimit } txRunner.rawRun(tx, callbacks.confirmationCb, callbacks.gasEstimationForceSend, callbacks.promptCb, (error, txResult) => { // see universaldapp.js line 660 => 700 to check possible values of txResult (error case) finalCallback(error, txResult) }) }
javascript
function (from, data, value, gasLimit, txRunner, callbacks, finalCallback) { if (!callbacks.confirmationCb || !callbacks.gasEstimationForceSend || !callbacks.promptCb) { return finalCallback('all the callbacks must have been defined') } var tx = { from: from, to: null, data: data, useCall: false, value: value, gasLimit: gasLimit } txRunner.rawRun(tx, callbacks.confirmationCb, callbacks.gasEstimationForceSend, callbacks.promptCb, (error, txResult) => { // see universaldapp.js line 660 => 700 to check possible values of txResult (error case) finalCallback(error, txResult) }) }
[ "function", "(", "from", ",", "data", ",", "value", ",", "gasLimit", ",", "txRunner", ",", "callbacks", ",", "finalCallback", ")", "{", "if", "(", "!", "callbacks", ".", "confirmationCb", "||", "!", "callbacks", ".", "gasEstimationForceSend", "||", "!", "callbacks", ".", "promptCb", ")", "{", "return", "finalCallback", "(", "'all the callbacks must have been defined'", ")", "}", "var", "tx", "=", "{", "from", ":", "from", ",", "to", ":", "null", ",", "data", ":", "data", ",", "useCall", ":", "false", ",", "value", ":", "value", ",", "gasLimit", ":", "gasLimit", "}", "txRunner", ".", "rawRun", "(", "tx", ",", "callbacks", ".", "confirmationCb", ",", "callbacks", ".", "gasEstimationForceSend", ",", "callbacks", ".", "promptCb", ",", "(", "error", ",", "txResult", ")", "=>", "{", "// see universaldapp.js line 660 => 700 to check possible values of txResult (error case)", "finalCallback", "(", "error", ",", "txResult", ")", "}", ")", "}" ]
deploy the given contract @param {String} from - sender address @param {String} data - data to send with the transaction ( return of txFormat.buildData(...) ). @param {String} value - decimal representation of value. @param {String} gasLimit - decimal representation of gas limit. @param {Object} txRunner - TxRunner.js instance @param {Object} callbacks - { confirmationCb, gasEstimationForceSend, promptCb } [validate transaction] confirmationCb (network, tx, gasEstimation, continueTxExecution, cancelCb) [transaction failed, force send] gasEstimationForceSend (error, continueTxExecution, cancelCb) [personal mode enabled, need password to continue] promptCb (okCb, cancelCb) @param {Function} finalCallback - last callback.
[ "deploy", "the", "given", "contract" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-lib/src/execution/txExecution.js#L19-L28
7,551
ethereum/remix
remix-lib/src/execution/txExecution.js
function (txResult) { var errorCode = { OUT_OF_GAS: 'out of gas', STACK_UNDERFLOW: 'stack underflow', STACK_OVERFLOW: 'stack overflow', INVALID_JUMP: 'invalid JUMP', INVALID_OPCODE: 'invalid opcode', REVERT: 'revert', STATIC_STATE_CHANGE: 'static state change' } var ret = { error: false, message: '' } if (!txResult.result.vm.exceptionError) { return ret } var exceptionError = txResult.result.vm.exceptionError.error || '' var error = `VM error: ${exceptionError}.\n` var msg if (exceptionError === errorCode.INVALID_OPCODE) { msg = `\t\n\tThe execution might have thrown.\n` ret.error = true } else if (exceptionError === errorCode.OUT_OF_GAS) { msg = `\tThe transaction ran out of gas. Please increase the Gas Limit.\n` ret.error = true } else if (exceptionError === errorCode.REVERT) { var returnData = txResult.result.vm.return // It is the hash of Error(string) if (returnData && (returnData.slice(0, 4).toString('hex') === '08c379a0')) { var abiCoder = new ethers.utils.AbiCoder() var reason = abiCoder.decode(['string'], returnData.slice(4))[0] msg = `\tThe transaction has been reverted to the initial state.\nReason provided by the contract: "${reason}".` } else { msg = `\tThe transaction has been reverted to the initial state.\nNote: The called function should be payable if you send value and the value you send should be less than your current balance.` } ret.error = true } else if (exceptionError === errorCode.STATIC_STATE_CHANGE) { msg = `\tState changes is not allowed in Static Call context\n` ret.error = true } ret.message = `${error}${exceptionError}${msg}\tDebug the transaction to get more information.` return ret }
javascript
function (txResult) { var errorCode = { OUT_OF_GAS: 'out of gas', STACK_UNDERFLOW: 'stack underflow', STACK_OVERFLOW: 'stack overflow', INVALID_JUMP: 'invalid JUMP', INVALID_OPCODE: 'invalid opcode', REVERT: 'revert', STATIC_STATE_CHANGE: 'static state change' } var ret = { error: false, message: '' } if (!txResult.result.vm.exceptionError) { return ret } var exceptionError = txResult.result.vm.exceptionError.error || '' var error = `VM error: ${exceptionError}.\n` var msg if (exceptionError === errorCode.INVALID_OPCODE) { msg = `\t\n\tThe execution might have thrown.\n` ret.error = true } else if (exceptionError === errorCode.OUT_OF_GAS) { msg = `\tThe transaction ran out of gas. Please increase the Gas Limit.\n` ret.error = true } else if (exceptionError === errorCode.REVERT) { var returnData = txResult.result.vm.return // It is the hash of Error(string) if (returnData && (returnData.slice(0, 4).toString('hex') === '08c379a0')) { var abiCoder = new ethers.utils.AbiCoder() var reason = abiCoder.decode(['string'], returnData.slice(4))[0] msg = `\tThe transaction has been reverted to the initial state.\nReason provided by the contract: "${reason}".` } else { msg = `\tThe transaction has been reverted to the initial state.\nNote: The called function should be payable if you send value and the value you send should be less than your current balance.` } ret.error = true } else if (exceptionError === errorCode.STATIC_STATE_CHANGE) { msg = `\tState changes is not allowed in Static Call context\n` ret.error = true } ret.message = `${error}${exceptionError}${msg}\tDebug the transaction to get more information.` return ret }
[ "function", "(", "txResult", ")", "{", "var", "errorCode", "=", "{", "OUT_OF_GAS", ":", "'out of gas'", ",", "STACK_UNDERFLOW", ":", "'stack underflow'", ",", "STACK_OVERFLOW", ":", "'stack overflow'", ",", "INVALID_JUMP", ":", "'invalid JUMP'", ",", "INVALID_OPCODE", ":", "'invalid opcode'", ",", "REVERT", ":", "'revert'", ",", "STATIC_STATE_CHANGE", ":", "'static state change'", "}", "var", "ret", "=", "{", "error", ":", "false", ",", "message", ":", "''", "}", "if", "(", "!", "txResult", ".", "result", ".", "vm", ".", "exceptionError", ")", "{", "return", "ret", "}", "var", "exceptionError", "=", "txResult", ".", "result", ".", "vm", ".", "exceptionError", ".", "error", "||", "''", "var", "error", "=", "`", "${", "exceptionError", "}", "\\n", "`", "var", "msg", "if", "(", "exceptionError", "===", "errorCode", ".", "INVALID_OPCODE", ")", "{", "msg", "=", "`", "\\t", "\\n", "\\t", "\\n", "`", "ret", ".", "error", "=", "true", "}", "else", "if", "(", "exceptionError", "===", "errorCode", ".", "OUT_OF_GAS", ")", "{", "msg", "=", "`", "\\t", "\\n", "`", "ret", ".", "error", "=", "true", "}", "else", "if", "(", "exceptionError", "===", "errorCode", ".", "REVERT", ")", "{", "var", "returnData", "=", "txResult", ".", "result", ".", "vm", ".", "return", "// It is the hash of Error(string)", "if", "(", "returnData", "&&", "(", "returnData", ".", "slice", "(", "0", ",", "4", ")", ".", "toString", "(", "'hex'", ")", "===", "'08c379a0'", ")", ")", "{", "var", "abiCoder", "=", "new", "ethers", ".", "utils", ".", "AbiCoder", "(", ")", "var", "reason", "=", "abiCoder", ".", "decode", "(", "[", "'string'", "]", ",", "returnData", ".", "slice", "(", "4", ")", ")", "[", "0", "]", "msg", "=", "`", "\\t", "\\n", "${", "reason", "}", "`", "}", "else", "{", "msg", "=", "`", "\\t", "\\n", "`", "}", "ret", ".", "error", "=", "true", "}", "else", "if", "(", "exceptionError", "===", "errorCode", ".", "STATIC_STATE_CHANGE", ")", "{", "msg", "=", "`", "\\t", "\\n", "`", "ret", ".", "error", "=", "true", "}", "ret", ".", "message", "=", "`", "${", "error", "}", "${", "exceptionError", "}", "${", "msg", "}", "\\t", "`", "return", "ret", "}" ]
check if the vm has errored @param {Object} txResult - the value returned by the vm @return {Object} - { error: true/false, message: DOMNode }
[ "check", "if", "the", "vm", "has", "errored" ]
09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e
https://github.com/ethereum/remix/blob/09acd177d52d3b6d1c4ef04f4d9bdbad6e526a6e/remix-lib/src/execution/txExecution.js#L59-L102
7,552
livoras/simple-virtual-dom
lib/element.js
Element
function Element (tagName, props, children) { if (!(this instanceof Element)) { if (!_.isArray(children) && children != null) { children = _.slice(arguments, 2).filter(_.truthy) } return new Element(tagName, props, children) } if (_.isArray(props)) { children = props props = {} } this.tagName = tagName this.props = props || {} this.children = children || [] this.key = props ? props.key : void 666 var count = 0 _.each(this.children, function (child, i) { if (child instanceof Element) { count += child.count } else { children[i] = '' + child } count++ }) this.count = count }
javascript
function Element (tagName, props, children) { if (!(this instanceof Element)) { if (!_.isArray(children) && children != null) { children = _.slice(arguments, 2).filter(_.truthy) } return new Element(tagName, props, children) } if (_.isArray(props)) { children = props props = {} } this.tagName = tagName this.props = props || {} this.children = children || [] this.key = props ? props.key : void 666 var count = 0 _.each(this.children, function (child, i) { if (child instanceof Element) { count += child.count } else { children[i] = '' + child } count++ }) this.count = count }
[ "function", "Element", "(", "tagName", ",", "props", ",", "children", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Element", ")", ")", "{", "if", "(", "!", "_", ".", "isArray", "(", "children", ")", "&&", "children", "!=", "null", ")", "{", "children", "=", "_", ".", "slice", "(", "arguments", ",", "2", ")", ".", "filter", "(", "_", ".", "truthy", ")", "}", "return", "new", "Element", "(", "tagName", ",", "props", ",", "children", ")", "}", "if", "(", "_", ".", "isArray", "(", "props", ")", ")", "{", "children", "=", "props", "props", "=", "{", "}", "}", "this", ".", "tagName", "=", "tagName", "this", ".", "props", "=", "props", "||", "{", "}", "this", ".", "children", "=", "children", "||", "[", "]", "this", ".", "key", "=", "props", "?", "props", ".", "key", ":", "void", "666", "var", "count", "=", "0", "_", ".", "each", "(", "this", ".", "children", ",", "function", "(", "child", ",", "i", ")", "{", "if", "(", "child", "instanceof", "Element", ")", "{", "count", "+=", "child", ".", "count", "}", "else", "{", "children", "[", "i", "]", "=", "''", "+", "child", "}", "count", "++", "}", ")", "this", ".", "count", "=", "count", "}" ]
Virtual-dom Element. @param {String} tagName @param {Object} props - Element's properties, - using object to store key-value pair @param {Array<Element|String>} - This element's children elements. - Can be Element instance or just a piece plain text.
[ "Virtual", "-", "dom", "Element", "." ]
92856ae49bdb35d6c3aea7b3367eec47abb70f22
https://github.com/livoras/simple-virtual-dom/blob/92856ae49bdb35d6c3aea7b3367eec47abb70f22/lib/element.js#L11-L43
7,553
segmentio/analytics.js
analytics.js
Facade
function Facade (obj) { obj = clone(obj); if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date(); else obj.timestamp = newDate(obj.timestamp); traverse(obj); this.obj = obj; }
javascript
function Facade (obj) { obj = clone(obj); if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date(); else obj.timestamp = newDate(obj.timestamp); traverse(obj); this.obj = obj; }
[ "function", "Facade", "(", "obj", ")", "{", "obj", "=", "clone", "(", "obj", ")", ";", "if", "(", "!", "obj", ".", "hasOwnProperty", "(", "'timestamp'", ")", ")", "obj", ".", "timestamp", "=", "new", "Date", "(", ")", ";", "else", "obj", ".", "timestamp", "=", "newDate", "(", "obj", ".", "timestamp", ")", ";", "traverse", "(", "obj", ")", ";", "this", ".", "obj", "=", "obj", ";", "}" ]
Initialize a new `Facade` with an `obj` of arguments. @param {Object} obj
[ "Initialize", "a", "new", "Facade", "with", "an", "obj", "of", "arguments", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L1053-L1059
7,554
segmentio/analytics.js
analytics.js
traverse
function traverse (input, strict) { if (strict === undefined) strict = true; if (is.object(input)) return object(input, strict); if (is.array(input)) return array(input, strict); return input; }
javascript
function traverse (input, strict) { if (strict === undefined) strict = true; if (is.object(input)) return object(input, strict); if (is.array(input)) return array(input, strict); return input; }
[ "function", "traverse", "(", "input", ",", "strict", ")", "{", "if", "(", "strict", "===", "undefined", ")", "strict", "=", "true", ";", "if", "(", "is", ".", "object", "(", "input", ")", ")", "return", "object", "(", "input", ",", "strict", ")", ";", "if", "(", "is", ".", "array", "(", "input", ")", ")", "return", "array", "(", "input", ",", "strict", ")", ";", "return", "input", ";", "}" ]
Traverse an object or array, and return a clone with all ISO strings parsed into Date objects. @param {Object} obj @return {Object}
[ "Traverse", "an", "object", "or", "array", "and", "return", "a", "clone", "with", "all", "ISO", "strings", "parsed", "into", "Date", "objects", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L1369-L1375
7,555
segmentio/analytics.js
analytics.js
object
function object (obj, strict) { each(obj, function (key, val) { if (isodate.is(val, strict)) { obj[key] = isodate.parse(val); } else if (is.object(val) || is.array(val)) { traverse(val, strict); } }); return obj; }
javascript
function object (obj, strict) { each(obj, function (key, val) { if (isodate.is(val, strict)) { obj[key] = isodate.parse(val); } else if (is.object(val) || is.array(val)) { traverse(val, strict); } }); return obj; }
[ "function", "object", "(", "obj", ",", "strict", ")", "{", "each", "(", "obj", ",", "function", "(", "key", ",", "val", ")", "{", "if", "(", "isodate", ".", "is", "(", "val", ",", "strict", ")", ")", "{", "obj", "[", "key", "]", "=", "isodate", ".", "parse", "(", "val", ")", ";", "}", "else", "if", "(", "is", ".", "object", "(", "val", ")", "||", "is", ".", "array", "(", "val", ")", ")", "{", "traverse", "(", "val", ",", "strict", ")", ";", "}", "}", ")", ";", "return", "obj", ";", "}" ]
Object traverser. @param {Object} obj @param {Boolean} strict @return {Object}
[ "Object", "traverser", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L1385-L1394
7,556
segmentio/analytics.js
analytics.js
array
function array (arr, strict) { each(arr, function (val, x) { if (is.object(val)) { traverse(val, strict); } else if (isodate.is(val, strict)) { arr[x] = isodate.parse(val); } }); return arr; }
javascript
function array (arr, strict) { each(arr, function (val, x) { if (is.object(val)) { traverse(val, strict); } else if (isodate.is(val, strict)) { arr[x] = isodate.parse(val); } }); return arr; }
[ "function", "array", "(", "arr", ",", "strict", ")", "{", "each", "(", "arr", ",", "function", "(", "val", ",", "x", ")", "{", "if", "(", "is", ".", "object", "(", "val", ")", ")", "{", "traverse", "(", "val", ",", "strict", ")", ";", "}", "else", "if", "(", "isodate", ".", "is", "(", "val", ",", "strict", ")", ")", "{", "arr", "[", "x", "]", "=", "isodate", ".", "parse", "(", "val", ")", ";", "}", "}", ")", ";", "return", "arr", ";", "}" ]
Array traverser. @param {Array} arr @param {Boolean} strict @return {Array}
[ "Array", "traverser", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L1404-L1413
7,557
segmentio/analytics.js
analytics.js
isEmpty
function isEmpty (val) { if (null == val) return true; if ('number' == typeof val) return 0 === val; if (undefined !== val.length) return 0 === val.length; for (var key in val) if (has.call(val, key)) return false; return true; }
javascript
function isEmpty (val) { if (null == val) return true; if ('number' == typeof val) return 0 === val; if (undefined !== val.length) return 0 === val.length; for (var key in val) if (has.call(val, key)) return false; return true; }
[ "function", "isEmpty", "(", "val", ")", "{", "if", "(", "null", "==", "val", ")", "return", "true", ";", "if", "(", "'number'", "==", "typeof", "val", ")", "return", "0", "===", "val", ";", "if", "(", "undefined", "!==", "val", ".", "length", ")", "return", "0", "===", "val", ".", "length", ";", "for", "(", "var", "key", "in", "val", ")", "if", "(", "has", ".", "call", "(", "val", ",", "key", ")", ")", "return", "false", ";", "return", "true", ";", "}" ]
Test whether a value is "empty". @param {Mixed} val @return {Boolean}
[ "Test", "whether", "a", "value", "is", "empty", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L1516-L1522
7,558
segmentio/analytics.js
analytics.js
object
function object(obj, fn) { for (var key in obj) { if (has.call(obj, key)) { fn(key, obj[key]); } } }
javascript
function object(obj, fn) { for (var key in obj) { if (has.call(obj, key)) { fn(key, obj[key]); } } }
[ "function", "object", "(", "obj", ",", "fn", ")", "{", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "has", ".", "call", "(", "obj", ",", "key", ")", ")", "{", "fn", "(", "key", ",", "obj", "[", "key", "]", ")", ";", "}", "}", "}" ]
Iterate object keys. @param {Object} obj @param {Function} fn @api private
[ "Iterate", "object", "keys", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L1689-L1695
7,559
segmentio/analytics.js
analytics.js
multiple
function multiple (fn) { return function (obj, path, val, options) { var normalize = options && isFunction(options.normalizer) ? options.normalizer : defaultNormalize; path = normalize(path); var key; var finished = false; while (!finished) loop(); function loop() { for (key in obj) { var normalizedKey = normalize(key); if (0 === path.indexOf(normalizedKey)) { var temp = path.substr(normalizedKey.length); if (temp.charAt(0) === '.' || temp.length === 0) { path = temp.substr(1); var child = obj[key]; // we're at the end and there is nothing. if (null == child) { finished = true; return; } // we're at the end and there is something. if (!path.length) { finished = true; return; } // step into child obj = child; // but we're done here return; } } } key = undefined; // if we found no matching properties // on the current object, there's no match. finished = true; } if (!key) return; if (null == obj) return obj; // the `obj` and `key` is one above the leaf object and key, so // start object: { a: { 'b.c': 10 } } // end object: { 'b.c': 10 } // end key: 'b.c' // this way, you can do `obj[key]` and get `10`. return fn(obj, key, val); }; }
javascript
function multiple (fn) { return function (obj, path, val, options) { var normalize = options && isFunction(options.normalizer) ? options.normalizer : defaultNormalize; path = normalize(path); var key; var finished = false; while (!finished) loop(); function loop() { for (key in obj) { var normalizedKey = normalize(key); if (0 === path.indexOf(normalizedKey)) { var temp = path.substr(normalizedKey.length); if (temp.charAt(0) === '.' || temp.length === 0) { path = temp.substr(1); var child = obj[key]; // we're at the end and there is nothing. if (null == child) { finished = true; return; } // we're at the end and there is something. if (!path.length) { finished = true; return; } // step into child obj = child; // but we're done here return; } } } key = undefined; // if we found no matching properties // on the current object, there's no match. finished = true; } if (!key) return; if (null == obj) return obj; // the `obj` and `key` is one above the leaf object and key, so // start object: { a: { 'b.c': 10 } } // end object: { 'b.c': 10 } // end key: 'b.c' // this way, you can do `obj[key]` and get `10`. return fn(obj, key, val); }; }
[ "function", "multiple", "(", "fn", ")", "{", "return", "function", "(", "obj", ",", "path", ",", "val", ",", "options", ")", "{", "var", "normalize", "=", "options", "&&", "isFunction", "(", "options", ".", "normalizer", ")", "?", "options", ".", "normalizer", ":", "defaultNormalize", ";", "path", "=", "normalize", "(", "path", ")", ";", "var", "key", ";", "var", "finished", "=", "false", ";", "while", "(", "!", "finished", ")", "loop", "(", ")", ";", "function", "loop", "(", ")", "{", "for", "(", "key", "in", "obj", ")", "{", "var", "normalizedKey", "=", "normalize", "(", "key", ")", ";", "if", "(", "0", "===", "path", ".", "indexOf", "(", "normalizedKey", ")", ")", "{", "var", "temp", "=", "path", ".", "substr", "(", "normalizedKey", ".", "length", ")", ";", "if", "(", "temp", ".", "charAt", "(", "0", ")", "===", "'.'", "||", "temp", ".", "length", "===", "0", ")", "{", "path", "=", "temp", ".", "substr", "(", "1", ")", ";", "var", "child", "=", "obj", "[", "key", "]", ";", "// we're at the end and there is nothing.", "if", "(", "null", "==", "child", ")", "{", "finished", "=", "true", ";", "return", ";", "}", "// we're at the end and there is something.", "if", "(", "!", "path", ".", "length", ")", "{", "finished", "=", "true", ";", "return", ";", "}", "// step into child", "obj", "=", "child", ";", "// but we're done here", "return", ";", "}", "}", "}", "key", "=", "undefined", ";", "// if we found no matching properties", "// on the current object, there's no match.", "finished", "=", "true", ";", "}", "if", "(", "!", "key", ")", "return", ";", "if", "(", "null", "==", "obj", ")", "return", "obj", ";", "// the `obj` and `key` is one above the leaf object and key, so", "// start object: { a: { 'b.c': 10 } }", "// end object: { 'b.c': 10 }", "// end key: 'b.c'", "// this way, you can do `obj[key]` and get `10`.", "return", "fn", "(", "obj", ",", "key", ",", "val", ")", ";", "}", ";", "}" ]
Compose applying the function to a nested key
[ "Compose", "applying", "the", "function", "to", "a", "nested", "key" ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L1895-L1951
7,560
segmentio/analytics.js
analytics.js
replace
function replace (obj, key, val) { if (obj.hasOwnProperty(key)) obj[key] = val; return obj; }
javascript
function replace (obj, key, val) { if (obj.hasOwnProperty(key)) obj[key] = val; return obj; }
[ "function", "replace", "(", "obj", ",", "key", ",", "val", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "obj", "[", "key", "]", "=", "val", ";", "return", "obj", ";", "}" ]
Replace an objects existing value with a new one replace({ a : 'b' }, 'a', 'c') -> { a : 'c' }
[ "Replace", "an", "objects", "existing", "value", "with", "a", "new", "one" ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L1983-L1986
7,561
segmentio/analytics.js
analytics.js
currency
function currency(val) { if (!val) return; if (typeof val === 'number') return val; if (typeof val !== 'string') return; val = val.replace(/\$/g, ''); val = parseFloat(val); if (!isNaN(val)) return val; }
javascript
function currency(val) { if (!val) return; if (typeof val === 'number') return val; if (typeof val !== 'string') return; val = val.replace(/\$/g, ''); val = parseFloat(val); if (!isNaN(val)) return val; }
[ "function", "currency", "(", "val", ")", "{", "if", "(", "!", "val", ")", "return", ";", "if", "(", "typeof", "val", "===", "'number'", ")", "return", "val", ";", "if", "(", "typeof", "val", "!==", "'string'", ")", "return", ";", "val", "=", "val", ".", "replace", "(", "/", "\\$", "/", "g", ",", "''", ")", ";", "val", "=", "parseFloat", "(", "val", ")", ";", "if", "(", "!", "isNaN", "(", "val", ")", ")", "return", "val", ";", "}" ]
Get float from currency value. @param {Mixed} val @return {Number}
[ "Get", "float", "from", "currency", "value", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L2971-L2980
7,562
segmentio/analytics.js
analytics.js
bindMethods
function bindMethods (obj, methods) { methods = [].slice.call(arguments, 1); for (var i = 0, method; method = methods[i]; i++) { obj[method] = bind(obj, obj[method]); } return obj; }
javascript
function bindMethods (obj, methods) { methods = [].slice.call(arguments, 1); for (var i = 0, method; method = methods[i]; i++) { obj[method] = bind(obj, obj[method]); } return obj; }
[ "function", "bindMethods", "(", "obj", ",", "methods", ")", "{", "methods", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "for", "(", "var", "i", "=", "0", ",", "method", ";", "method", "=", "methods", "[", "i", "]", ";", "i", "++", ")", "{", "obj", "[", "method", "]", "=", "bind", "(", "obj", ",", "obj", "[", "method", "]", ")", ";", "}", "return", "obj", ";", "}" ]
Bind `methods` on `obj` to always be called with the `obj` as context. @param {Object} obj @param {String} methods...
[ "Bind", "methods", "on", "obj", "to", "always", "be", "called", "with", "the", "obj", "as", "context", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L3239-L3245
7,563
segmentio/analytics.js
analytics.js
set
function set(name, value, options) { options = options || {}; var str = encode(name) + '=' + encode(value); if (null == value) options.maxage = -1; if (options.maxage) { options.expires = new Date(+new Date + options.maxage); } if (options.path) str += '; path=' + options.path; if (options.domain) str += '; domain=' + options.domain; if (options.expires) str += '; expires=' + options.expires.toUTCString(); if (options.secure) str += '; secure'; document.cookie = str; }
javascript
function set(name, value, options) { options = options || {}; var str = encode(name) + '=' + encode(value); if (null == value) options.maxage = -1; if (options.maxage) { options.expires = new Date(+new Date + options.maxage); } if (options.path) str += '; path=' + options.path; if (options.domain) str += '; domain=' + options.domain; if (options.expires) str += '; expires=' + options.expires.toUTCString(); if (options.secure) str += '; secure'; document.cookie = str; }
[ "function", "set", "(", "name", ",", "value", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "str", "=", "encode", "(", "name", ")", "+", "'='", "+", "encode", "(", "value", ")", ";", "if", "(", "null", "==", "value", ")", "options", ".", "maxage", "=", "-", "1", ";", "if", "(", "options", ".", "maxage", ")", "{", "options", ".", "expires", "=", "new", "Date", "(", "+", "new", "Date", "+", "options", ".", "maxage", ")", ";", "}", "if", "(", "options", ".", "path", ")", "str", "+=", "'; path='", "+", "options", ".", "path", ";", "if", "(", "options", ".", "domain", ")", "str", "+=", "'; domain='", "+", "options", ".", "domain", ";", "if", "(", "options", ".", "expires", ")", "str", "+=", "'; expires='", "+", "options", ".", "expires", ".", "toUTCString", "(", ")", ";", "if", "(", "options", ".", "secure", ")", "str", "+=", "'; secure'", ";", "document", ".", "cookie", "=", "str", ";", "}" ]
Set cookie `name` to `value`. @param {String} name @param {String} value @param {Object} options @api private
[ "Set", "cookie", "name", "to", "value", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L3607-L3623
7,564
segmentio/analytics.js
analytics.js
parse
function parse(str) { var obj = {}; var pairs = str.split(/ *; */); var pair; if ('' == pairs[0]) return obj; for (var i = 0; i < pairs.length; ++i) { pair = pairs[i].split('='); obj[decode(pair[0])] = decode(pair[1]); } return obj; }
javascript
function parse(str) { var obj = {}; var pairs = str.split(/ *; */); var pair; if ('' == pairs[0]) return obj; for (var i = 0; i < pairs.length; ++i) { pair = pairs[i].split('='); obj[decode(pair[0])] = decode(pair[1]); } return obj; }
[ "function", "parse", "(", "str", ")", "{", "var", "obj", "=", "{", "}", ";", "var", "pairs", "=", "str", ".", "split", "(", "/", " *; *", "/", ")", ";", "var", "pair", ";", "if", "(", "''", "==", "pairs", "[", "0", "]", ")", "return", "obj", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "pairs", ".", "length", ";", "++", "i", ")", "{", "pair", "=", "pairs", "[", "i", "]", ".", "split", "(", "'='", ")", ";", "obj", "[", "decode", "(", "pair", "[", "0", "]", ")", "]", "=", "decode", "(", "pair", "[", "1", "]", ")", ";", "}", "return", "obj", ";", "}" ]
Parse cookie `str`. @param {String} str @return {Object} @api private
[ "Parse", "cookie", "str", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L3656-L3666
7,565
segmentio/analytics.js
analytics.js
function (dest, src, recursive) { for (var prop in src) { if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) { dest[prop] = defaults(dest[prop], src[prop], true); } else if (! (prop in dest)) { dest[prop] = src[prop]; } } return dest; }
javascript
function (dest, src, recursive) { for (var prop in src) { if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) { dest[prop] = defaults(dest[prop], src[prop], true); } else if (! (prop in dest)) { dest[prop] = src[prop]; } } return dest; }
[ "function", "(", "dest", ",", "src", ",", "recursive", ")", "{", "for", "(", "var", "prop", "in", "src", ")", "{", "if", "(", "recursive", "&&", "dest", "[", "prop", "]", "instanceof", "Object", "&&", "src", "[", "prop", "]", "instanceof", "Object", ")", "{", "dest", "[", "prop", "]", "=", "defaults", "(", "dest", "[", "prop", "]", ",", "src", "[", "prop", "]", ",", "true", ")", ";", "}", "else", "if", "(", "!", "(", "prop", "in", "dest", ")", ")", "{", "dest", "[", "prop", "]", "=", "src", "[", "prop", "]", ";", "}", "}", "return", "dest", ";", "}" ]
Merge default values. @param {Object} dest @param {Object} defaults @return {Object} @api public
[ "Merge", "default", "values", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L4002-L4012
7,566
segmentio/analytics.js
analytics.js
all
function all() { var str; try { str = document.cookie; } catch (err) { if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(err.stack || err); } return {}; } return parse(str); }
javascript
function all() { var str; try { str = document.cookie; } catch (err) { if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(err.stack || err); } return {}; } return parse(str); }
[ "function", "all", "(", ")", "{", "var", "str", ";", "try", "{", "str", "=", "document", ".", "cookie", ";", "}", "catch", "(", "err", ")", "{", "if", "(", "typeof", "console", "!==", "'undefined'", "&&", "typeof", "console", ".", "error", "===", "'function'", ")", "{", "console", ".", "error", "(", "err", ".", "stack", "||", "err", ")", ";", "}", "return", "{", "}", ";", "}", "return", "parse", "(", "str", ")", ";", "}" ]
Return all cookies. @return {Object} @api private
[ "Return", "all", "cookies", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L4775-L4786
7,567
segmentio/analytics.js
analytics.js
Group
function Group(options) { this.defaults = Group.defaults; this.debug = debug; Entity.call(this, options); }
javascript
function Group(options) { this.defaults = Group.defaults; this.debug = debug; Entity.call(this, options); }
[ "function", "Group", "(", "options", ")", "{", "this", ".", "defaults", "=", "Group", ".", "defaults", ";", "this", ".", "debug", "=", "debug", ";", "Entity", ".", "call", "(", "this", ",", "options", ")", ";", "}" ]
Initialize a new `Group` with `options`. @param {Object} options
[ "Initialize", "a", "new", "Group", "with", "options", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L4877-L4881
7,568
segmentio/analytics.js
analytics.js
includes
function includes(searchElement, collection) { var found = false; // Delegate to String.prototype.indexOf when `collection` is a string if (typeof collection === 'string') { return strIndexOf.call(collection, searchElement) !== -1; } // Iterate through enumerable/own array elements and object properties. each(function(value) { if (sameValueZero(value, searchElement)) { found = true; // Exit iteration early when found return false; } }, collection); return found; }
javascript
function includes(searchElement, collection) { var found = false; // Delegate to String.prototype.indexOf when `collection` is a string if (typeof collection === 'string') { return strIndexOf.call(collection, searchElement) !== -1; } // Iterate through enumerable/own array elements and object properties. each(function(value) { if (sameValueZero(value, searchElement)) { found = true; // Exit iteration early when found return false; } }, collection); return found; }
[ "function", "includes", "(", "searchElement", ",", "collection", ")", "{", "var", "found", "=", "false", ";", "// Delegate to String.prototype.indexOf when `collection` is a string", "if", "(", "typeof", "collection", "===", "'string'", ")", "{", "return", "strIndexOf", ".", "call", "(", "collection", ",", "searchElement", ")", "!==", "-", "1", ";", "}", "// Iterate through enumerable/own array elements and object properties.", "each", "(", "function", "(", "value", ")", "{", "if", "(", "sameValueZero", "(", "value", ",", "searchElement", ")", ")", "{", "found", "=", "true", ";", "// Exit iteration early when found", "return", "false", ";", "}", "}", ",", "collection", ")", ";", "return", "found", ";", "}" ]
Searches a given `collection` for a value, returning true if the collection contains the value and false otherwise. Can search strings, arrays, and objects. @name includes @api public @param {*} searchElement The element to search for. @param {Object|Array|string} collection The collection to search. @return {boolean} @example includes(2, [1, 2, 3]); //=> true includes(4, [1, 2, 3]); //=> false includes(2, { a: 1, b: 2, c: 3 }); //=> true includes('a', { a: 1, b: 2, c: 3 }); //=> false includes('abc', 'xyzabc opq'); //=> true includes('nope', 'xyzabc opq'); //=> false
[ "Searches", "a", "given", "collection", "for", "a", "value", "returning", "true", "if", "the", "collection", "contains", "the", "value", "and", "false", "otherwise", ".", "Can", "search", "strings", "arrays", "and", "objects", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L5817-L5835
7,569
segmentio/analytics.js
analytics.js
isArrayLike
function isArrayLike(val) { return val != null && (isArray(val) || (val !== 'function' && isNumber(val.length))); }
javascript
function isArrayLike(val) { return val != null && (isArray(val) || (val !== 'function' && isNumber(val.length))); }
[ "function", "isArrayLike", "(", "val", ")", "{", "return", "val", "!=", "null", "&&", "(", "isArray", "(", "val", ")", "||", "(", "val", "!==", "'function'", "&&", "isNumber", "(", "val", ".", "length", ")", ")", ")", ";", "}" ]
Tests if a value is array-like. Array-like means the value is not a function and has a numeric `.length` property. @name isArrayLike @api private @param {*} val @return {boolean} TODO: Move to library
[ "Tests", "if", "a", "value", "is", "array", "-", "like", ".", "Array", "-", "like", "means", "the", "value", "is", "not", "a", "function", "and", "has", "a", "numeric", ".", "length", "property", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L5900-L5902
7,570
segmentio/analytics.js
analytics.js
arrayEach
function arrayEach(iterator, array) { for (var i = 0; i < array.length; i += 1) { // Break iteration early if `iterator` returns `false` if (iterator(array[i], i, array) === false) { break; } } }
javascript
function arrayEach(iterator, array) { for (var i = 0; i < array.length; i += 1) { // Break iteration early if `iterator` returns `false` if (iterator(array[i], i, array) === false) { break; } } }
[ "function", "arrayEach", "(", "iterator", ",", "array", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "+=", "1", ")", "{", "// Break iteration early if `iterator` returns `false`", "if", "(", "iterator", "(", "array", "[", "i", "]", ",", "i", ",", "array", ")", "===", "false", ")", "{", "break", ";", "}", "}", "}" ]
Internal implementation of `each`. Works on arrays and array-like data structures. @name arrayEach @api private @param {Function(value, key, collection)} iterator The function to invoke per iteration. @param {Array} array The array(-like) structure to iterate over. @return {undefined}
[ "Internal", "implementation", "of", "each", ".", "Works", "on", "arrays", "and", "array", "-", "like", "data", "structures", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L5914-L5921
7,571
segmentio/analytics.js
analytics.js
baseEach
function baseEach(iterator, object) { var ks = keys(object); for (var i = 0; i < ks.length; i += 1) { // Break iteration early if `iterator` returns `false` if (iterator(object[ks[i]], ks[i], object) === false) { break; } } }
javascript
function baseEach(iterator, object) { var ks = keys(object); for (var i = 0; i < ks.length; i += 1) { // Break iteration early if `iterator` returns `false` if (iterator(object[ks[i]], ks[i], object) === false) { break; } } }
[ "function", "baseEach", "(", "iterator", ",", "object", ")", "{", "var", "ks", "=", "keys", "(", "object", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ks", ".", "length", ";", "i", "+=", "1", ")", "{", "// Break iteration early if `iterator` returns `false`", "if", "(", "iterator", "(", "object", "[", "ks", "[", "i", "]", "]", ",", "ks", "[", "i", "]", ",", "object", ")", "===", "false", ")", "{", "break", ";", "}", "}", "}" ]
Internal implementation of `each`. Works on objects. @name baseEach @api private @param {Function(value, key, collection)} iterator The function to invoke per iteration. @param {Object} object The object to iterate over. @return {undefined}
[ "Internal", "implementation", "of", "each", ".", "Works", "on", "objects", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L5933-L5942
7,572
segmentio/analytics.js
analytics.js
objectKeys
function objectKeys(target, pred) { pred = pred || has; var results = []; for (var key in target) { if (pred(target, key)) { results.push(String(key)); } } return results; }
javascript
function objectKeys(target, pred) { pred = pred || has; var results = []; for (var key in target) { if (pred(target, key)) { results.push(String(key)); } } return results; }
[ "function", "objectKeys", "(", "target", ",", "pred", ")", "{", "pred", "=", "pred", "||", "has", ";", "var", "results", "=", "[", "]", ";", "for", "(", "var", "key", "in", "target", ")", "{", "if", "(", "pred", "(", "target", ",", "key", ")", ")", "{", "results", ".", "push", "(", "String", "(", "key", ")", ")", ";", "}", "}", "return", "results", ";", "}" ]
Returns an array of all the owned @name objectKeys @api private @param {*} target @param {Function} pred Predicate function used to include/exclude values from the resulting array. @return {Array}
[ "Returns", "an", "array", "of", "all", "the", "owned" ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L6101-L6113
7,573
segmentio/analytics.js
analytics.js
toFunction
function toFunction(obj) { switch ({}.toString.call(obj)) { case '[object Object]': return objectToFunction(obj); case '[object Function]': return obj; case '[object String]': return stringToFunction(obj); case '[object RegExp]': return regexpToFunction(obj); default: return defaultToFunction(obj); } }
javascript
function toFunction(obj) { switch ({}.toString.call(obj)) { case '[object Object]': return objectToFunction(obj); case '[object Function]': return obj; case '[object String]': return stringToFunction(obj); case '[object RegExp]': return regexpToFunction(obj); default: return defaultToFunction(obj); } }
[ "function", "toFunction", "(", "obj", ")", "{", "switch", "(", "{", "}", ".", "toString", ".", "call", "(", "obj", ")", ")", "{", "case", "'[object Object]'", ":", "return", "objectToFunction", "(", "obj", ")", ";", "case", "'[object Function]'", ":", "return", "obj", ";", "case", "'[object String]'", ":", "return", "stringToFunction", "(", "obj", ")", ";", "case", "'[object RegExp]'", ":", "return", "regexpToFunction", "(", "obj", ")", ";", "default", ":", "return", "defaultToFunction", "(", "obj", ")", ";", "}", "}" ]
Convert `obj` to a `Function`. @param {Mixed} obj @return {Function} @api private
[ "Convert", "obj", "to", "a", "Function", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L6220-L6233
7,574
segmentio/analytics.js
analytics.js
objectToFunction
function objectToFunction(obj) { var match = {}; for (var key in obj) { match[key] = typeof obj[key] === 'string' ? defaultToFunction(obj[key]) : toFunction(obj[key]); } return function(val){ if (typeof val !== 'object') return false; for (var key in match) { if (!(key in val)) return false; if (!match[key](val[key])) return false; } return true; }; }
javascript
function objectToFunction(obj) { var match = {}; for (var key in obj) { match[key] = typeof obj[key] === 'string' ? defaultToFunction(obj[key]) : toFunction(obj[key]); } return function(val){ if (typeof val !== 'object') return false; for (var key in match) { if (!(key in val)) return false; if (!match[key](val[key])) return false; } return true; }; }
[ "function", "objectToFunction", "(", "obj", ")", "{", "var", "match", "=", "{", "}", ";", "for", "(", "var", "key", "in", "obj", ")", "{", "match", "[", "key", "]", "=", "typeof", "obj", "[", "key", "]", "===", "'string'", "?", "defaultToFunction", "(", "obj", "[", "key", "]", ")", ":", "toFunction", "(", "obj", "[", "key", "]", ")", ";", "}", "return", "function", "(", "val", ")", "{", "if", "(", "typeof", "val", "!==", "'object'", ")", "return", "false", ";", "for", "(", "var", "key", "in", "match", ")", "{", "if", "(", "!", "(", "key", "in", "val", ")", ")", "return", "false", ";", "if", "(", "!", "match", "[", "key", "]", "(", "val", "[", "key", "]", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}", ";", "}" ]
Convert `object` to a function. @param {Object} object @return {Function} @api private
[ "Convert", "object", "to", "a", "function", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L6287-L6302
7,575
segmentio/analytics.js
analytics.js
get
function get(str) { var props = expr(str); if (!props.length) return '_.' + str; var val, i, prop; for (i = 0; i < props.length; i++) { prop = props[i]; val = '_.' + prop; val = "('function' == typeof " + val + " ? " + val + "() : " + val + ")"; // mimic negative lookbehind to avoid problems with nested properties str = stripNested(prop, str, val); } return str; }
javascript
function get(str) { var props = expr(str); if (!props.length) return '_.' + str; var val, i, prop; for (i = 0; i < props.length; i++) { prop = props[i]; val = '_.' + prop; val = "('function' == typeof " + val + " ? " + val + "() : " + val + ")"; // mimic negative lookbehind to avoid problems with nested properties str = stripNested(prop, str, val); } return str; }
[ "function", "get", "(", "str", ")", "{", "var", "props", "=", "expr", "(", "str", ")", ";", "if", "(", "!", "props", ".", "length", ")", "return", "'_.'", "+", "str", ";", "var", "val", ",", "i", ",", "prop", ";", "for", "(", "i", "=", "0", ";", "i", "<", "props", ".", "length", ";", "i", "++", ")", "{", "prop", "=", "props", "[", "i", "]", ";", "val", "=", "'_.'", "+", "prop", ";", "val", "=", "\"('function' == typeof \"", "+", "val", "+", "\" ? \"", "+", "val", "+", "\"() : \"", "+", "val", "+", "\")\"", ";", "// mimic negative lookbehind to avoid problems with nested properties", "str", "=", "stripNested", "(", "prop", ",", "str", ",", "val", ")", ";", "}", "return", "str", ";", "}" ]
Built the getter function. Supports getter style functions @param {String} str @return {String} @api private
[ "Built", "the", "getter", "function", ".", "Supports", "getter", "style", "functions" ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L6312-L6327
7,576
segmentio/analytics.js
analytics.js
map
function map(str, props, fn) { var re = /\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g; return str.replace(re, function(_){ if ('(' == _[_.length - 1]) return fn(_); if (!~props.indexOf(_)) return _; return fn(_); }); }
javascript
function map(str, props, fn) { var re = /\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g; return str.replace(re, function(_){ if ('(' == _[_.length - 1]) return fn(_); if (!~props.indexOf(_)) return _; return fn(_); }); }
[ "function", "map", "(", "str", ",", "props", ",", "fn", ")", "{", "var", "re", "=", "/", "\\.\\w+|\\w+ *\\(|\"[^\"]*\"|'[^']*'|\\/([^/]+)\\/|[a-zA-Z_]\\w*", "/", "g", ";", "return", "str", ".", "replace", "(", "re", ",", "function", "(", "_", ")", "{", "if", "(", "'('", "==", "_", "[", "_", ".", "length", "-", "1", "]", ")", "return", "fn", "(", "_", ")", ";", "if", "(", "!", "~", "props", ".", "indexOf", "(", "_", ")", ")", "return", "_", ";", "return", "fn", "(", "_", ")", ";", "}", ")", ";", "}" ]
Return `str` with `props` mapped with `fn`. @param {String} str @param {Array} props @param {Function} fn @return {String} @api private
[ "Return", "str", "with", "props", "mapped", "with", "fn", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L6397-L6404
7,577
segmentio/analytics.js
analytics.js
unique
function unique(arr) { var ret = []; for (var i = 0; i < arr.length; i++) { if (~ret.indexOf(arr[i])) continue; ret.push(arr[i]); } return ret; }
javascript
function unique(arr) { var ret = []; for (var i = 0; i < arr.length; i++) { if (~ret.indexOf(arr[i])) continue; ret.push(arr[i]); } return ret; }
[ "function", "unique", "(", "arr", ")", "{", "var", "ret", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "if", "(", "~", "ret", ".", "indexOf", "(", "arr", "[", "i", "]", ")", ")", "continue", ";", "ret", ".", "push", "(", "arr", "[", "i", "]", ")", ";", "}", "return", "ret", ";", "}" ]
Return unique array. @param {Array} arr @return {Array} @api private
[ "Return", "unique", "array", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L6414-L6423
7,578
segmentio/analytics.js
analytics.js
pageDefaults
function pageDefaults() { return { path: canonicalPath(), referrer: document.referrer, search: location.search, title: document.title, url: canonicalUrl(location.search) }; }
javascript
function pageDefaults() { return { path: canonicalPath(), referrer: document.referrer, search: location.search, title: document.title, url: canonicalUrl(location.search) }; }
[ "function", "pageDefaults", "(", ")", "{", "return", "{", "path", ":", "canonicalPath", "(", ")", ",", "referrer", ":", "document", ".", "referrer", ",", "search", ":", "location", ".", "search", ",", "title", ":", "document", ".", "title", ",", "url", ":", "canonicalUrl", "(", "location", ".", "search", ")", "}", ";", "}" ]
Return a default `options.context.page` object. https://segment.com/docs/spec/page/#properties @return {Object}
[ "Return", "a", "default", "options", ".", "context", ".", "page", "object", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L6497-L6505
7,579
segmentio/analytics.js
analytics.js
canonicalPath
function canonicalPath() { var canon = canonical(); if (!canon) return window.location.pathname; var parsed = url.parse(canon); return parsed.pathname; }
javascript
function canonicalPath() { var canon = canonical(); if (!canon) return window.location.pathname; var parsed = url.parse(canon); return parsed.pathname; }
[ "function", "canonicalPath", "(", ")", "{", "var", "canon", "=", "canonical", "(", ")", ";", "if", "(", "!", "canon", ")", "return", "window", ".", "location", ".", "pathname", ";", "var", "parsed", "=", "url", ".", "parse", "(", "canon", ")", ";", "return", "parsed", ".", "pathname", ";", "}" ]
Return the canonical path for the page. @return {string}
[ "Return", "the", "canonical", "path", "for", "the", "page", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L6513-L6518
7,580
segmentio/analytics.js
analytics.js
canonicalUrl
function canonicalUrl(search) { var canon = canonical(); if (canon) return includes('?', canon) ? canon : canon + search; var url = window.location.href; var i = url.indexOf('#'); return i === -1 ? url : url.slice(0, i); }
javascript
function canonicalUrl(search) { var canon = canonical(); if (canon) return includes('?', canon) ? canon : canon + search; var url = window.location.href; var i = url.indexOf('#'); return i === -1 ? url : url.slice(0, i); }
[ "function", "canonicalUrl", "(", "search", ")", "{", "var", "canon", "=", "canonical", "(", ")", ";", "if", "(", "canon", ")", "return", "includes", "(", "'?'", ",", "canon", ")", "?", "canon", ":", "canon", "+", "search", ";", "var", "url", "=", "window", ".", "location", ".", "href", ";", "var", "i", "=", "url", ".", "indexOf", "(", "'#'", ")", ";", "return", "i", "===", "-", "1", "?", "url", ":", "url", ".", "slice", "(", "0", ",", "i", ")", ";", "}" ]
Return the canonical URL for the page concat the given `search` and strip the hash. @param {string} search @return {string}
[ "Return", "the", "canonical", "URL", "for", "the", "page", "concat", "the", "given", "search", "and", "strip", "the", "hash", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L6528-L6534
7,581
segmentio/analytics.js
analytics.js
pick
function pick(props, object) { if (!existy(object) || !isObject(object)) { return {}; } if (isString(props)) { props = [props]; } if (!isArray(props)) { props = []; } var result = {}; for (var i = 0; i < props.length; i += 1) { if (isString(props[i]) && props[i] in object) { result[props[i]] = object[props[i]]; } } return result; }
javascript
function pick(props, object) { if (!existy(object) || !isObject(object)) { return {}; } if (isString(props)) { props = [props]; } if (!isArray(props)) { props = []; } var result = {}; for (var i = 0; i < props.length; i += 1) { if (isString(props[i]) && props[i] in object) { result[props[i]] = object[props[i]]; } } return result; }
[ "function", "pick", "(", "props", ",", "object", ")", "{", "if", "(", "!", "existy", "(", "object", ")", "||", "!", "isObject", "(", "object", ")", ")", "{", "return", "{", "}", ";", "}", "if", "(", "isString", "(", "props", ")", ")", "{", "props", "=", "[", "props", "]", ";", "}", "if", "(", "!", "isArray", "(", "props", ")", ")", "{", "props", "=", "[", "]", ";", "}", "var", "result", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "props", ".", "length", ";", "i", "+=", "1", ")", "{", "if", "(", "isString", "(", "props", "[", "i", "]", ")", "&&", "props", "[", "i", "]", "in", "object", ")", "{", "result", "[", "props", "[", "i", "]", "]", "=", "object", "[", "props", "[", "i", "]", "]", ";", "}", "}", "return", "result", ";", "}" ]
Returns a copy of the new `object` containing only the specified properties. @name pick @api public @category Object @see {@link omit} @param {Array.<string>|string} props The property or properties to keep. @param {Object} object The object to iterate over. @return {Object} A new object containing only the specified properties from `object`. @example var person = { name: 'Tim', occupation: 'enchanter', fears: 'rabbits' }; pick('name', person); //=> { name: 'Tim' } pick(['name', 'fears'], person); //=> { name: 'Tim', fears: 'rabbits' }
[ "Returns", "a", "copy", "of", "the", "new", "object", "containing", "only", "the", "specified", "properties", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L6681-L6703
7,582
segmentio/analytics.js
analytics.js
User
function User(options) { this.defaults = User.defaults; this.debug = debug; Entity.call(this, options); }
javascript
function User(options) { this.defaults = User.defaults; this.debug = debug; Entity.call(this, options); }
[ "function", "User", "(", "options", ")", "{", "this", ".", "defaults", "=", "User", ".", "defaults", ";", "this", ".", "debug", "=", "debug", ";", "Entity", ".", "call", "(", "this", ",", "options", ")", ";", "}" ]
Initialize a new `User` with `options`. @param {Object} options
[ "Initialize", "a", "new", "User", "with", "options", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L6880-L6884
7,583
segmentio/analytics.js
analytics.js
render
function render(template, locals){ return foldl(function(attrs, val, key) { attrs[key] = val.replace(/\{\{\ *(\w+)\ *\}\}/g, function(_, $1){ return locals[$1]; }); return attrs; }, {}, template.attrs); }
javascript
function render(template, locals){ return foldl(function(attrs, val, key) { attrs[key] = val.replace(/\{\{\ *(\w+)\ *\}\}/g, function(_, $1){ return locals[$1]; }); return attrs; }, {}, template.attrs); }
[ "function", "render", "(", "template", ",", "locals", ")", "{", "return", "foldl", "(", "function", "(", "attrs", ",", "val", ",", "key", ")", "{", "attrs", "[", "key", "]", "=", "val", ".", "replace", "(", "/", "\\{\\{\\ *(\\w+)\\ *\\}\\}", "/", "g", ",", "function", "(", "_", ",", "$1", ")", "{", "return", "locals", "[", "$1", "]", ";", "}", ")", ";", "return", "attrs", ";", "}", ",", "{", "}", ",", "template", ".", "attrs", ")", ";", "}" ]
Render template + locals into an `attrs` object. @api private @param {Object} template @param {Object} locals @return {Object}
[ "Render", "template", "+", "locals", "into", "an", "attrs", "object", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L8139-L8146
7,584
segmentio/analytics.js
analytics.js
fmt
function fmt(str){ var args = [].slice.call(arguments, 1); var j = 0; return str.replace(/%([a-z])/gi, function(_, f){ return fmt[f] ? fmt[f](args[j++]) : _ + f; }); }
javascript
function fmt(str){ var args = [].slice.call(arguments, 1); var j = 0; return str.replace(/%([a-z])/gi, function(_, f){ return fmt[f] ? fmt[f](args[j++]) : _ + f; }); }
[ "function", "fmt", "(", "str", ")", "{", "var", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "var", "j", "=", "0", ";", "return", "str", ".", "replace", "(", "/", "%([a-z])", "/", "gi", ",", "function", "(", "_", ",", "f", ")", "{", "return", "fmt", "[", "f", "]", "?", "fmt", "[", "f", "]", "(", "args", "[", "j", "++", "]", ")", ":", "_", "+", "f", ";", "}", ")", ";", "}" ]
Format the given `str`. @param {String} str @param {...} args @return {String} @api public
[ "Format", "the", "given", "str", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L8329-L8338
7,585
segmentio/analytics.js
analytics.js
attach
function attach(el, fn){ el.attachEvent('onreadystatechange', function(e){ if (!/complete|loaded/.test(el.readyState)) return; fn(null, e); }); el.attachEvent('onerror', function(e){ var err = new Error('failed to load the script "' + el.src + '"'); err.event = e || window.event; fn(err); }); }
javascript
function attach(el, fn){ el.attachEvent('onreadystatechange', function(e){ if (!/complete|loaded/.test(el.readyState)) return; fn(null, e); }); el.attachEvent('onerror', function(e){ var err = new Error('failed to load the script "' + el.src + '"'); err.event = e || window.event; fn(err); }); }
[ "function", "attach", "(", "el", ",", "fn", ")", "{", "el", ".", "attachEvent", "(", "'onreadystatechange'", ",", "function", "(", "e", ")", "{", "if", "(", "!", "/", "complete|loaded", "/", ".", "test", "(", "el", ".", "readyState", ")", ")", "return", ";", "fn", "(", "null", ",", "e", ")", ";", "}", ")", ";", "el", ".", "attachEvent", "(", "'onerror'", ",", "function", "(", "e", ")", "{", "var", "err", "=", "new", "Error", "(", "'failed to load the script \"'", "+", "el", ".", "src", "+", "'\"'", ")", ";", "err", ".", "event", "=", "e", "||", "window", ".", "event", ";", "fn", "(", "err", ")", ";", "}", ")", ";", "}" ]
Attach event. @param {Element} el @param {Function} fn @api private
[ "Attach", "event", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L8506-L8516
7,586
segmentio/analytics.js
analytics.js
uncamelize
function uncamelize (string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' '); }); }
javascript
function uncamelize (string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' '); }); }
[ "function", "uncamelize", "(", "string", ")", "{", "return", "string", ".", "replace", "(", "camelSplitter", ",", "function", "(", "m", ",", "previous", ",", "uppers", ")", "{", "return", "previous", "+", "' '", "+", "uppers", ".", "toLowerCase", "(", ")", ".", "split", "(", "''", ")", ".", "join", "(", "' '", ")", ";", "}", ")", ";", "}" ]
Un-camelcase a `string`. @param {String} string @return {String}
[ "Un", "-", "camelcase", "a", "string", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L8648-L8652
7,587
segmentio/analytics.js
analytics.js
objectify
function objectify(str) { // replace `src` with `data-src` to prevent image loading str = str.replace(' src="', ' data-src="'); var el = domify(str); var attrs = {}; each(el.attributes, function(attr){ // then replace it back var name = attr.name === 'data-src' ? 'src' : attr.name; if (!includes(attr.name + '=', str)) return; attrs[name] = attr.value; }); return { type: el.tagName.toLowerCase(), attrs: attrs }; }
javascript
function objectify(str) { // replace `src` with `data-src` to prevent image loading str = str.replace(' src="', ' data-src="'); var el = domify(str); var attrs = {}; each(el.attributes, function(attr){ // then replace it back var name = attr.name === 'data-src' ? 'src' : attr.name; if (!includes(attr.name + '=', str)) return; attrs[name] = attr.value; }); return { type: el.tagName.toLowerCase(), attrs: attrs }; }
[ "function", "objectify", "(", "str", ")", "{", "// replace `src` with `data-src` to prevent image loading", "str", "=", "str", ".", "replace", "(", "' src=\"'", ",", "' data-src=\"'", ")", ";", "var", "el", "=", "domify", "(", "str", ")", ";", "var", "attrs", "=", "{", "}", ";", "each", "(", "el", ".", "attributes", ",", "function", "(", "attr", ")", "{", "// then replace it back", "var", "name", "=", "attr", ".", "name", "===", "'data-src'", "?", "'src'", ":", "attr", ".", "name", ";", "if", "(", "!", "includes", "(", "attr", ".", "name", "+", "'='", ",", "str", ")", ")", "return", ";", "attrs", "[", "name", "]", "=", "attr", ".", "value", ";", "}", ")", ";", "return", "{", "type", ":", "el", ".", "tagName", ".", "toLowerCase", "(", ")", ",", "attrs", ":", "attrs", "}", ";", "}" ]
Given a string, give back DOM attributes. Do it in a way where the browser doesn't load images or iframes. It turns out domify will load images/iframes because whenever you construct those DOM elements, the browser immediately loads them. @api private @param {string} str @return {Object}
[ "Given", "a", "string", "give", "back", "DOM", "attributes", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L8798-L8816
7,588
segmentio/analytics.js
analytics.js
toSpaceCase
function toSpaceCase (string) { return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) { return match ? ' ' + match : ''; }); }
javascript
function toSpaceCase (string) { return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) { return match ? ' ' + match : ''; }); }
[ "function", "toSpaceCase", "(", "string", ")", "{", "return", "clean", "(", "string", ")", ".", "replace", "(", "/", "[\\W_]+(.|$)", "/", "g", ",", "function", "(", "matches", ",", "match", ")", "{", "return", "match", "?", "' '", "+", "match", ":", "''", ";", "}", ")", ";", "}" ]
Convert a `string` to space case. @param {String} string @return {String}
[ "Convert", "a", "string", "to", "space", "case", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L8974-L8978
7,589
segmentio/analytics.js
analytics.js
toIsoString
function toIsoString (date) { return date.getUTCFullYear() + '-' + pad(date.getUTCMonth() + 1) + '-' + pad(date.getUTCDate()) + 'T' + pad(date.getUTCHours()) + ':' + pad(date.getUTCMinutes()) + ':' + pad(date.getUTCSeconds()) + '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5) + 'Z'; }
javascript
function toIsoString (date) { return date.getUTCFullYear() + '-' + pad(date.getUTCMonth() + 1) + '-' + pad(date.getUTCDate()) + 'T' + pad(date.getUTCHours()) + ':' + pad(date.getUTCMinutes()) + ':' + pad(date.getUTCSeconds()) + '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5) + 'Z'; }
[ "function", "toIsoString", "(", "date", ")", "{", "return", "date", ".", "getUTCFullYear", "(", ")", "+", "'-'", "+", "pad", "(", "date", ".", "getUTCMonth", "(", ")", "+", "1", ")", "+", "'-'", "+", "pad", "(", "date", ".", "getUTCDate", "(", ")", ")", "+", "'T'", "+", "pad", "(", "date", ".", "getUTCHours", "(", ")", ")", "+", "':'", "+", "pad", "(", "date", ".", "getUTCMinutes", "(", ")", ")", "+", "':'", "+", "pad", "(", "date", ".", "getUTCSeconds", "(", ")", ")", "+", "'.'", "+", "String", "(", "(", "date", ".", "getUTCMilliseconds", "(", ")", "/", "1000", ")", ".", "toFixed", "(", "3", ")", ")", ".", "slice", "(", "2", ",", "5", ")", "+", "'Z'", ";", "}" ]
Turn a `date` into an ISO string. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString @param {Date} date @return {String}
[ "Turn", "a", "date", "into", "an", "ISO", "string", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L11107-L11116
7,590
segmentio/analytics.js
analytics.js
alias
function alias (obj, method) { switch (type(method)) { case 'object': return aliasByDictionary(clone(obj), method); case 'function': return aliasByFunction(clone(obj), method); } }
javascript
function alias (obj, method) { switch (type(method)) { case 'object': return aliasByDictionary(clone(obj), method); case 'function': return aliasByFunction(clone(obj), method); } }
[ "function", "alias", "(", "obj", ",", "method", ")", "{", "switch", "(", "type", "(", "method", ")", ")", "{", "case", "'object'", ":", "return", "aliasByDictionary", "(", "clone", "(", "obj", ")", ",", "method", ")", ";", "case", "'function'", ":", "return", "aliasByFunction", "(", "clone", "(", "obj", ")", ",", "method", ")", ";", "}", "}" ]
Alias an `object`. @param {Object} obj @param {Mixed} method
[ "Alias", "an", "object", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L11362-L11367
7,591
segmentio/analytics.js
analytics.js
aliasByDictionary
function aliasByDictionary (obj, aliases) { for (var key in aliases) { if (undefined === obj[key]) continue; obj[aliases[key]] = obj[key]; delete obj[key]; } return obj; }
javascript
function aliasByDictionary (obj, aliases) { for (var key in aliases) { if (undefined === obj[key]) continue; obj[aliases[key]] = obj[key]; delete obj[key]; } return obj; }
[ "function", "aliasByDictionary", "(", "obj", ",", "aliases", ")", "{", "for", "(", "var", "key", "in", "aliases", ")", "{", "if", "(", "undefined", "===", "obj", "[", "key", "]", ")", "continue", ";", "obj", "[", "aliases", "[", "key", "]", "]", "=", "obj", "[", "key", "]", ";", "delete", "obj", "[", "key", "]", ";", "}", "return", "obj", ";", "}" ]
Convert the keys in an `obj` using a dictionary of `aliases`. @param {Object} obj @param {Object} aliases
[ "Convert", "the", "keys", "in", "an", "obj", "using", "a", "dictionary", "of", "aliases", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L11377-L11384
7,592
segmentio/analytics.js
analytics.js
aliasByFunction
function aliasByFunction (obj, convert) { // have to create another object so that ie8 won't infinite loop on keys var output = {}; for (var key in obj) output[convert(key)] = obj[key]; return output; }
javascript
function aliasByFunction (obj, convert) { // have to create another object so that ie8 won't infinite loop on keys var output = {}; for (var key in obj) output[convert(key)] = obj[key]; return output; }
[ "function", "aliasByFunction", "(", "obj", ",", "convert", ")", "{", "// have to create another object so that ie8 won't infinite loop on keys", "var", "output", "=", "{", "}", ";", "for", "(", "var", "key", "in", "obj", ")", "output", "[", "convert", "(", "key", ")", "]", "=", "obj", "[", "key", "]", ";", "return", "output", ";", "}" ]
Convert the keys in an `obj` using a `convert` function. @param {Object} obj @param {Function} convert
[ "Convert", "the", "keys", "in", "an", "obj", "using", "a", "convert", "function", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L11394-L11399
7,593
segmentio/analytics.js
analytics.js
convertDates
function convertDates (obj, convert) { obj = clone(obj); for (var key in obj) { var val = obj[key]; if (is.date(val)) obj[key] = convert(val); if (is.object(val)) obj[key] = convertDates(val, convert); } return obj; }
javascript
function convertDates (obj, convert) { obj = clone(obj); for (var key in obj) { var val = obj[key]; if (is.date(val)) obj[key] = convert(val); if (is.object(val)) obj[key] = convertDates(val, convert); } return obj; }
[ "function", "convertDates", "(", "obj", ",", "convert", ")", "{", "obj", "=", "clone", "(", "obj", ")", ";", "for", "(", "var", "key", "in", "obj", ")", "{", "var", "val", "=", "obj", "[", "key", "]", ";", "if", "(", "is", ".", "date", "(", "val", ")", ")", "obj", "[", "key", "]", "=", "convert", "(", "val", ")", ";", "if", "(", "is", ".", "object", "(", "val", ")", ")", "obj", "[", "key", "]", "=", "convertDates", "(", "val", ",", "convert", ")", ";", "}", "return", "obj", ";", "}" ]
Recursively convert an `obj`'s dates to new values. @param {Object} obj @param {Function} convert @return {Object}
[ "Recursively", "convert", "an", "obj", "s", "dates", "to", "new", "values", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L11427-L11435
7,594
segmentio/analytics.js
analytics.js
handler
function handler () { for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments); }
javascript
function handler () { for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments); }
[ "function", "handler", "(", ")", "{", "for", "(", "var", "i", "=", "0", ",", "fn", ";", "fn", "=", "callbacks", "[", "i", "]", ";", "i", "++", ")", "fn", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}" ]
Error handler.
[ "Error", "handler", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L11669-L11671
7,595
segmentio/analytics.js
analytics.js
onError
function onError (fn) { callbacks.push(fn); if (window.onerror != handler) { callbacks.push(window.onerror); window.onerror = handler; } }
javascript
function onError (fn) { callbacks.push(fn); if (window.onerror != handler) { callbacks.push(window.onerror); window.onerror = handler; } }
[ "function", "onError", "(", "fn", ")", "{", "callbacks", ".", "push", "(", "fn", ")", ";", "if", "(", "window", ".", "onerror", "!=", "handler", ")", "{", "callbacks", ".", "push", "(", "window", ".", "onerror", ")", ";", "window", ".", "onerror", "=", "handler", ";", "}", "}" ]
Call a `fn` on `window.onerror`. @param {Function} fn
[ "Call", "a", "fn", "on", "window", ".", "onerror", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L11680-L11686
7,596
segmentio/analytics.js
analytics.js
ecommerce
function ecommerce(event, track, arr) { push.apply(null, [ '_fxm.ecommerce.' + event, track.id() || track.sku(), track.name(), track.category() ].concat(arr || [])); }
javascript
function ecommerce(event, track, arr) { push.apply(null, [ '_fxm.ecommerce.' + event, track.id() || track.sku(), track.name(), track.category() ].concat(arr || [])); }
[ "function", "ecommerce", "(", "event", ",", "track", ",", "arr", ")", "{", "push", ".", "apply", "(", "null", ",", "[", "'_fxm.ecommerce.'", "+", "event", ",", "track", ".", "id", "(", ")", "||", "track", ".", "sku", "(", ")", ",", "track", ".", "name", "(", ")", ",", "track", ".", "category", "(", ")", "]", ".", "concat", "(", "arr", "||", "[", "]", ")", ")", ";", "}" ]
Track ecommerce `event` with `track` with optional `arr` to append. @api private @param {string} event @param {Track} track @param {Array} arr
[ "Track", "ecommerce", "event", "with", "track", "with", "optional", "arr", "to", "append", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L12364-L12371
7,597
segmentio/analytics.js
analytics.js
clean
function clean(obj) { var ret = {}; // Remove traits/properties that are already represented // outside of the data container // TODO: Refactor into `omit` call var excludeKeys = ['id', 'name', 'firstName', 'lastName']; each(excludeKeys, function(omitKey) { clear(obj, omitKey); }); // Flatten nested hierarchy, preserving arrays obj = flatten(obj); // Discard nulls, represent arrays as comma-separated strings // FIXME: This also discards `undefined`s. Is that OK? for (var key in obj) { if (has.call(obj, key)) { var val = obj[key]; if (val == null) { continue; } if (is.array(val)) { ret[key] = val.toString(); continue; } ret[key] = val; } } return ret; }
javascript
function clean(obj) { var ret = {}; // Remove traits/properties that are already represented // outside of the data container // TODO: Refactor into `omit` call var excludeKeys = ['id', 'name', 'firstName', 'lastName']; each(excludeKeys, function(omitKey) { clear(obj, omitKey); }); // Flatten nested hierarchy, preserving arrays obj = flatten(obj); // Discard nulls, represent arrays as comma-separated strings // FIXME: This also discards `undefined`s. Is that OK? for (var key in obj) { if (has.call(obj, key)) { var val = obj[key]; if (val == null) { continue; } if (is.array(val)) { ret[key] = val.toString(); continue; } ret[key] = val; } } return ret; }
[ "function", "clean", "(", "obj", ")", "{", "var", "ret", "=", "{", "}", ";", "// Remove traits/properties that are already represented", "// outside of the data container", "// TODO: Refactor into `omit` call", "var", "excludeKeys", "=", "[", "'id'", ",", "'name'", ",", "'firstName'", ",", "'lastName'", "]", ";", "each", "(", "excludeKeys", ",", "function", "(", "omitKey", ")", "{", "clear", "(", "obj", ",", "omitKey", ")", ";", "}", ")", ";", "// Flatten nested hierarchy, preserving arrays", "obj", "=", "flatten", "(", "obj", ")", ";", "// Discard nulls, represent arrays as comma-separated strings", "// FIXME: This also discards `undefined`s. Is that OK?", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "has", ".", "call", "(", "obj", ",", "key", ")", ")", "{", "var", "val", "=", "obj", "[", "key", "]", ";", "if", "(", "val", "==", "null", ")", "{", "continue", ";", "}", "if", "(", "is", ".", "array", "(", "val", ")", ")", "{", "ret", "[", "key", "]", "=", "val", ".", "toString", "(", ")", ";", "continue", ";", "}", "ret", "[", "key", "]", "=", "val", ";", "}", "}", "return", "ret", ";", "}" ]
Clean all nested objects and arrays. @api private @param {Object} obj @return {Object}
[ "Clean", "all", "nested", "objects", "and", "arrays", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L12526-L12559
7,598
segmentio/analytics.js
analytics.js
flatten
function flatten(source) { var output = {}; function step(object, prev) { for (var key in object) { if (has.call(object, key)) { var value = object[key]; var newKey = prev ? prev + ' ' + key : key; if (!is.array(value) && is.object(value)) { return step(value, newKey); } output[newKey] = value; } } } step(source); return output; }
javascript
function flatten(source) { var output = {}; function step(object, prev) { for (var key in object) { if (has.call(object, key)) { var value = object[key]; var newKey = prev ? prev + ' ' + key : key; if (!is.array(value) && is.object(value)) { return step(value, newKey); } output[newKey] = value; } } } step(source); return output; }
[ "function", "flatten", "(", "source", ")", "{", "var", "output", "=", "{", "}", ";", "function", "step", "(", "object", ",", "prev", ")", "{", "for", "(", "var", "key", "in", "object", ")", "{", "if", "(", "has", ".", "call", "(", "object", ",", "key", ")", ")", "{", "var", "value", "=", "object", "[", "key", "]", ";", "var", "newKey", "=", "prev", "?", "prev", "+", "' '", "+", "key", ":", "key", ";", "if", "(", "!", "is", ".", "array", "(", "value", ")", "&&", "is", ".", "object", "(", "value", ")", ")", "{", "return", "step", "(", "value", ",", "newKey", ")", ";", "}", "output", "[", "newKey", "]", "=", "value", ";", "}", "}", "}", "step", "(", "source", ")", ";", "return", "output", ";", "}" ]
Flatten a nested object into a single level space-delimited hierarchy. Based on https://github.com/hughsk/flat @api private @param {Object} source @return {Object}
[ "Flatten", "a", "nested", "object", "into", "a", "single", "level", "space", "-", "delimited", "hierarchy", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L12586-L12607
7,599
segmentio/analytics.js
analytics.js
convert
function convert(key, value) { key = camel(key); if (is.string(value)) return key + '_str'; if (isInt(value)) return key + '_int'; if (isFloat(value)) return key + '_real'; if (is.date(value)) return key + '_date'; if (is.boolean(value)) return key + '_bool'; }
javascript
function convert(key, value) { key = camel(key); if (is.string(value)) return key + '_str'; if (isInt(value)) return key + '_int'; if (isFloat(value)) return key + '_real'; if (is.date(value)) return key + '_date'; if (is.boolean(value)) return key + '_bool'; }
[ "function", "convert", "(", "key", ",", "value", ")", "{", "key", "=", "camel", "(", "key", ")", ";", "if", "(", "is", ".", "string", "(", "value", ")", ")", "return", "key", "+", "'_str'", ";", "if", "(", "isInt", "(", "value", ")", ")", "return", "key", "+", "'_int'", ";", "if", "(", "isFloat", "(", "value", ")", ")", "return", "key", "+", "'_real'", ";", "if", "(", "is", ".", "date", "(", "value", ")", ")", "return", "key", "+", "'_date'", ";", "if", "(", "is", ".", "boolean", "(", "value", ")", ")", "return", "key", "+", "'_bool'", ";", "}" ]
Convert to FullStory format. @param {string} trait @param {*} value
[ "Convert", "to", "FullStory", "format", "." ]
077efafa234d0bb4374169adb4e1ff71da39af8f
https://github.com/segmentio/analytics.js/blob/077efafa234d0bb4374169adb4e1ff71da39af8f/analytics.js#L12688-L12695