{"repo": "axios/axios", "path": "lib/axios.js", "func_name": "createInstance", "original_string": "function createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n return instance;\n}", "language": "javascript", "code": "function createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n return instance;\n}", "code_tokens": ["function", "createInstance", "(", "defaultConfig", ")", "{", "var", "context", "=", "new", "Axios", "(", "defaultConfig", ")", ";", "var", "instance", "=", "bind", "(", "Axios", ".", "prototype", ".", "request", ",", "context", ")", ";", "utils", ".", "extend", "(", "instance", ",", "Axios", ".", "prototype", ",", "context", ")", ";", "utils", ".", "extend", "(", "instance", ",", "context", ")", ";", "return", "instance", ";", "}"], "docstring": "Create an instance of Axios\n\n@param {Object} defaultConfig The default config for the instance\n@return {Axios} A new instance of Axios", "docstring_tokens": ["Create", "an", "instance", "of", "Axios"], "sha": "92d231387fe2092f8736bc1746d4caa766b675f5", "url": "https://github.com/axios/axios/blob/92d231387fe2092f8736bc1746d4caa766b675f5/lib/axios.js#L15-L26", "partition": "test"} {"repo": "axios/axios", "path": "lib/cancel/CancelToken.js", "func_name": "CancelToken", "original_string": "function CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new Cancel(message);\n resolvePromise(token.reason);\n });\n}", "language": "javascript", "code": "function CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new Cancel(message);\n resolvePromise(token.reason);\n });\n}", "code_tokens": ["function", "CancelToken", "(", "executor", ")", "{", "if", "(", "typeof", "executor", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'executor must be a function.'", ")", ";", "}", "var", "resolvePromise", ";", "this", ".", "promise", "=", "new", "Promise", "(", "function", "promiseExecutor", "(", "resolve", ")", "{", "resolvePromise", "=", "resolve", ";", "}", ")", ";", "var", "token", "=", "this", ";", "executor", "(", "function", "cancel", "(", "message", ")", "{", "if", "(", "token", ".", "reason", ")", "{", "return", ";", "}", "token", ".", "reason", "=", "new", "Cancel", "(", "message", ")", ";", "resolvePromise", "(", "token", ".", "reason", ")", ";", "}", ")", ";", "}"], "docstring": "A `CancelToken` is an object that can be used to request cancellation of an operation.\n\n@class\n@param {Function} executor The executor function.", "docstring_tokens": ["A", "CancelToken", "is", "an", "object", "that", "can", "be", "used", "to", "request", "cancellation", "of", "an", "operation", "."], "sha": "92d231387fe2092f8736bc1746d4caa766b675f5", "url": "https://github.com/axios/axios/blob/92d231387fe2092f8736bc1746d4caa766b675f5/lib/cancel/CancelToken.js#L11-L31", "partition": "test"} {"repo": "axios/axios", "path": "lib/utils.js", "func_name": "isArrayBufferView", "original_string": "function isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);\n }\n return result;\n}", "language": "javascript", "code": "function isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);\n }\n return result;\n}", "code_tokens": ["function", "isArrayBufferView", "(", "val", ")", "{", "var", "result", ";", "if", "(", "(", "typeof", "ArrayBuffer", "!==", "'undefined'", ")", "&&", "(", "ArrayBuffer", ".", "isView", ")", ")", "{", "result", "=", "ArrayBuffer", ".", "isView", "(", "val", ")", ";", "}", "else", "{", "result", "=", "(", "val", ")", "&&", "(", "val", ".", "buffer", ")", "&&", "(", "val", ".", "buffer", "instanceof", "ArrayBuffer", ")", ";", "}", "return", "result", ";", "}"], "docstring": "Determine if a value is a view on an ArrayBuffer\n\n@param {Object} val The value to test\n@returns {boolean} True if value is a view on an ArrayBuffer, otherwise false", "docstring_tokens": ["Determine", "if", "a", "value", "is", "a", "view", "on", "an", "ArrayBuffer"], "sha": "92d231387fe2092f8736bc1746d4caa766b675f5", "url": "https://github.com/axios/axios/blob/92d231387fe2092f8736bc1746d4caa766b675f5/lib/utils.js#L48-L56", "partition": "test"} {"repo": "axios/axios", "path": "lib/utils.js", "func_name": "isStandardBrowserEnv", "original_string": "function isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}", "language": "javascript", "code": "function isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}", "code_tokens": ["function", "isStandardBrowserEnv", "(", ")", "{", "if", "(", "typeof", "navigator", "!==", "'undefined'", "&&", "(", "navigator", ".", "product", "===", "'ReactNative'", "||", "navigator", ".", "product", "===", "'NativeScript'", "||", "navigator", ".", "product", "===", "'NS'", ")", ")", "{", "return", "false", ";", "}", "return", "(", "typeof", "window", "!==", "'undefined'", "&&", "typeof", "document", "!==", "'undefined'", ")", ";", "}"], "docstring": "Determine if we're running in a standard browser environment\n\nThis allows axios to run in a web worker, and react-native.\nBoth environments support XMLHttpRequest, but not fully standard globals.\n\nweb workers:\ntypeof window -> undefined\ntypeof document -> undefined\n\nreact-native:\nnavigator.product -> 'ReactNative'\nnativescript\nnavigator.product -> 'NativeScript' or 'NS'", "docstring_tokens": ["Determine", "if", "we", "re", "running", "in", "a", "standard", "browser", "environment"], "sha": "92d231387fe2092f8736bc1746d4caa766b675f5", "url": "https://github.com/axios/axios/blob/92d231387fe2092f8736bc1746d4caa766b675f5/lib/utils.js#L183-L193", "partition": "test"} {"repo": "axios/axios", "path": "lib/utils.js", "func_name": "forEach", "original_string": "function forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}", "language": "javascript", "code": "function forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}", "code_tokens": ["function", "forEach", "(", "obj", ",", "fn", ")", "{", "if", "(", "obj", "===", "null", "||", "typeof", "obj", "===", "'undefined'", ")", "{", "return", ";", "}", "if", "(", "typeof", "obj", "!==", "'object'", ")", "{", "obj", "=", "[", "obj", "]", ";", "}", "if", "(", "isArray", "(", "obj", ")", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "obj", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "fn", ".", "call", "(", "null", ",", "obj", "[", "i", "]", ",", "i", ",", "obj", ")", ";", "}", "}", "else", "{", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "obj", ",", "key", ")", ")", "{", "fn", ".", "call", "(", "null", ",", "obj", "[", "key", "]", ",", "key", ",", "obj", ")", ";", "}", "}", "}", "}"], "docstring": "Iterate over an Array or an Object invoking a function for each item.\n\nIf `obj` is an Array callback will be called passing\nthe value, index, and complete array for each item.\n\nIf 'obj' is an Object callback will be called passing\nthe value, key, and complete object for each property.\n\n@param {Object|Array} obj The object to iterate\n@param {Function} fn The callback to invoke for each item", "docstring_tokens": ["Iterate", "over", "an", "Array", "or", "an", "Object", "invoking", "a", "function", "for", "each", "item", "."], "sha": "92d231387fe2092f8736bc1746d4caa766b675f5", "url": "https://github.com/axios/axios/blob/92d231387fe2092f8736bc1746d4caa766b675f5/lib/utils.js#L207-L232", "partition": "test"} {"repo": "axios/axios", "path": "lib/utils.js", "func_name": "extend", "original_string": "function extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}", "language": "javascript", "code": "function extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}", "code_tokens": ["function", "extend", "(", "a", ",", "b", ",", "thisArg", ")", "{", "forEach", "(", "b", ",", "function", "assignValue", "(", "val", ",", "key", ")", "{", "if", "(", "thisArg", "&&", "typeof", "val", "===", "'function'", ")", "{", "a", "[", "key", "]", "=", "bind", "(", "val", ",", "thisArg", ")", ";", "}", "else", "{", "a", "[", "key", "]", "=", "val", ";", "}", "}", ")", ";", "return", "a", ";", "}"], "docstring": "Extends object a by mutably adding to it the properties of object b.\n\n@param {Object} a The object to be extended\n@param {Object} b The object to copy properties from\n@param {Object} thisArg The object to bind function to\n@return {Object} The resulting value of object a", "docstring_tokens": ["Extends", "object", "a", "by", "mutably", "adding", "to", "it", "the", "properties", "of", "object", "b", "."], "sha": "92d231387fe2092f8736bc1746d4caa766b675f5", "url": "https://github.com/axios/axios/blob/92d231387fe2092f8736bc1746d4caa766b675f5/lib/utils.js#L301-L310", "partition": "test"} {"repo": "zeit/next.js", "path": "packages/next/taskfile-ncc.js", "func_name": "writePackageManifest", "original_string": "function writePackageManifest (packageName) {\n const packagePath = require.resolve(packageName + '/package.json')\n let { name, main, author, license, types, typings } = require(packagePath)\n if (!main) {\n main = 'index.js'\n }\n\n let typesFile = types || typings\n if (typesFile) {\n typesFile = require.resolve(join(packageName, typesFile))\n }\n\n const compiledPackagePath = join(__dirname, `dist/compiled/${packageName}`)\n\n const potentialLicensePath = join(dirname(packagePath), './LICENSE')\n if (existsSync(potentialLicensePath)) {\n this._.files.push({\n dir: compiledPackagePath,\n base: 'LICENSE',\n data: readFileSync(potentialLicensePath, 'utf8')\n })\n }\n\n this._.files.push({\n dir: compiledPackagePath,\n base: 'package.json',\n data:\n JSON.stringify(\n Object.assign(\n {},\n { name, main: `${basename(main, '.' + extname(main))}` },\n author ? { author } : undefined,\n license ? { license } : undefined,\n typesFile\n ? {\n types: relative(compiledPackagePath, typesFile)\n }\n : undefined\n )\n ) + '\\n'\n })\n}", "language": "javascript", "code": "function writePackageManifest (packageName) {\n const packagePath = require.resolve(packageName + '/package.json')\n let { name, main, author, license, types, typings } = require(packagePath)\n if (!main) {\n main = 'index.js'\n }\n\n let typesFile = types || typings\n if (typesFile) {\n typesFile = require.resolve(join(packageName, typesFile))\n }\n\n const compiledPackagePath = join(__dirname, `dist/compiled/${packageName}`)\n\n const potentialLicensePath = join(dirname(packagePath), './LICENSE')\n if (existsSync(potentialLicensePath)) {\n this._.files.push({\n dir: compiledPackagePath,\n base: 'LICENSE',\n data: readFileSync(potentialLicensePath, 'utf8')\n })\n }\n\n this._.files.push({\n dir: compiledPackagePath,\n base: 'package.json',\n data:\n JSON.stringify(\n Object.assign(\n {},\n { name, main: `${basename(main, '.' + extname(main))}` },\n author ? { author } : undefined,\n license ? { license } : undefined,\n typesFile\n ? {\n types: relative(compiledPackagePath, typesFile)\n }\n : undefined\n )\n ) + '\\n'\n })\n}", "code_tokens": ["function", "writePackageManifest", "(", "packageName", ")", "{", "const", "packagePath", "=", "require", ".", "resolve", "(", "packageName", "+", "'/package.json'", ")", "let", "{", "name", ",", "main", ",", "author", ",", "license", ",", "types", ",", "typings", "}", "=", "require", "(", "packagePath", ")", "if", "(", "!", "main", ")", "{", "main", "=", "'index.js'", "}", "let", "typesFile", "=", "types", "||", "typings", "if", "(", "typesFile", ")", "{", "typesFile", "=", "require", ".", "resolve", "(", "join", "(", "packageName", ",", "typesFile", ")", ")", "}", "const", "compiledPackagePath", "=", "join", "(", "__dirname", ",", "`", "${", "packageName", "}", "`", ")", "const", "potentialLicensePath", "=", "join", "(", "dirname", "(", "packagePath", ")", ",", "'./LICENSE'", ")", "if", "(", "existsSync", "(", "potentialLicensePath", ")", ")", "{", "this", ".", "_", ".", "files", ".", "push", "(", "{", "dir", ":", "compiledPackagePath", ",", "base", ":", "'LICENSE'", ",", "data", ":", "readFileSync", "(", "potentialLicensePath", ",", "'utf8'", ")", "}", ")", "}", "this", ".", "_", ".", "files", ".", "push", "(", "{", "dir", ":", "compiledPackagePath", ",", "base", ":", "'package.json'", ",", "data", ":", "JSON", ".", "stringify", "(", "Object", ".", "assign", "(", "{", "}", ",", "{", "name", ",", "main", ":", "`", "${", "basename", "(", "main", ",", "'.'", "+", "extname", "(", "main", ")", ")", "}", "`", "}", ",", "author", "?", "{", "author", "}", ":", "undefined", ",", "license", "?", "{", "license", "}", ":", "undefined", ",", "typesFile", "?", "{", "types", ":", "relative", "(", "compiledPackagePath", ",", "typesFile", ")", "}", ":", "undefined", ")", ")", "+", "'\\n'", "}", ")", "}"], "docstring": "This function writes a minimal `package.json` file for a compiled package. It defines `name`, `main`, `author`, and `license`. It also defines `types`. n.b. types intended for development usage only.", "docstring_tokens": ["This", "function", "writes", "a", "minimal", "package", ".", "json", "file", "for", "a", "compiled", "package", ".", "It", "defines", "name", "main", "author", "and", "license", ".", "It", "also", "defines", "types", ".", "n", ".", "b", ".", "types", "intended", "for", "development", "usage", "only", "."], "sha": "3641f79a0f68d1093cc238b50b8d47eec1c25cfd", "url": "https://github.com/zeit/next.js/blob/3641f79a0f68d1093cc238b50b8d47eec1c25cfd/packages/next/taskfile-ncc.js#L34-L75", "partition": "test"} {"repo": "zeit/next.js", "path": "packages/next/client/dev-error-overlay/hot-dev-client.js", "func_name": "processMessage", "original_string": "function processMessage (e) {\n const obj = JSON.parse(e.data)\n switch (obj.action) {\n case 'building': {\n console.log(\n '[HMR] bundle ' + (obj.name ? \"'\" + obj.name + \"' \" : '') +\n 'rebuilding'\n )\n break\n }\n case 'built':\n case 'sync': {\n clearOutdatedErrors()\n\n if (obj.hash) {\n handleAvailableHash(obj.hash)\n }\n\n if (obj.warnings.length > 0) {\n handleWarnings(obj.warnings)\n }\n\n if (obj.errors.length > 0) {\n // When there is a compilation error coming from SSR we have to reload the page on next successful compile\n if (obj.action === 'sync') {\n hadRuntimeError = true\n }\n handleErrors(obj.errors)\n break\n }\n\n handleSuccess()\n break\n }\n default: {\n if (customHmrEventHandler) {\n customHmrEventHandler(obj)\n break\n }\n break\n }\n }\n}", "language": "javascript", "code": "function processMessage (e) {\n const obj = JSON.parse(e.data)\n switch (obj.action) {\n case 'building': {\n console.log(\n '[HMR] bundle ' + (obj.name ? \"'\" + obj.name + \"' \" : '') +\n 'rebuilding'\n )\n break\n }\n case 'built':\n case 'sync': {\n clearOutdatedErrors()\n\n if (obj.hash) {\n handleAvailableHash(obj.hash)\n }\n\n if (obj.warnings.length > 0) {\n handleWarnings(obj.warnings)\n }\n\n if (obj.errors.length > 0) {\n // When there is a compilation error coming from SSR we have to reload the page on next successful compile\n if (obj.action === 'sync') {\n hadRuntimeError = true\n }\n handleErrors(obj.errors)\n break\n }\n\n handleSuccess()\n break\n }\n default: {\n if (customHmrEventHandler) {\n customHmrEventHandler(obj)\n break\n }\n break\n }\n }\n}", "code_tokens": ["function", "processMessage", "(", "e", ")", "{", "const", "obj", "=", "JSON", ".", "parse", "(", "e", ".", "data", ")", "switch", "(", "obj", ".", "action", ")", "{", "case", "'building'", ":", "{", "console", ".", "log", "(", "'[HMR] bundle '", "+", "(", "obj", ".", "name", "?", "\"'\"", "+", "obj", ".", "name", "+", "\"' \"", ":", "''", ")", "+", "'rebuilding'", ")", "break", "}", "case", "'built'", ":", "case", "'sync'", ":", "{", "clearOutdatedErrors", "(", ")", "if", "(", "obj", ".", "hash", ")", "{", "handleAvailableHash", "(", "obj", ".", "hash", ")", "}", "if", "(", "obj", ".", "warnings", ".", "length", ">", "0", ")", "{", "handleWarnings", "(", "obj", ".", "warnings", ")", "}", "if", "(", "obj", ".", "errors", ".", "length", ">", "0", ")", "{", "if", "(", "obj", ".", "action", "===", "'sync'", ")", "{", "hadRuntimeError", "=", "true", "}", "handleErrors", "(", "obj", ".", "errors", ")", "break", "}", "handleSuccess", "(", ")", "break", "}", "default", ":", "{", "if", "(", "customHmrEventHandler", ")", "{", "customHmrEventHandler", "(", "obj", ")", "break", "}", "break", "}", "}", "}"], "docstring": "Handle messages from the server.", "docstring_tokens": ["Handle", "messages", "from", "the", "server", "."], "sha": "3641f79a0f68d1093cc238b50b8d47eec1c25cfd", "url": "https://github.com/zeit/next.js/blob/3641f79a0f68d1093cc238b50b8d47eec1c25cfd/packages/next/client/dev-error-overlay/hot-dev-client.js#L202-L244", "partition": "test"} {"repo": "zeit/next.js", "path": "packages/next/client/dev-error-overlay/hot-dev-client.js", "func_name": "tryApplyUpdates", "original_string": "async function tryApplyUpdates (onHotUpdateSuccess) {\n if (!module.hot) {\n // HotModuleReplacementPlugin is not in Webpack configuration.\n console.error('HotModuleReplacementPlugin is not in Webpack configuration.')\n // window.location.reload();\n return\n }\n\n if (!isUpdateAvailable() || !canApplyUpdates()) {\n return\n }\n\n function handleApplyUpdates (err, updatedModules) {\n if (err || hadRuntimeError) {\n if (err) {\n console.warn('Error while applying updates, reloading page', err)\n }\n if (hadRuntimeError) {\n console.warn('Had runtime error previously, reloading page')\n }\n window.location.reload()\n return\n }\n\n if (typeof onHotUpdateSuccess === 'function') {\n // Maybe we want to do something.\n onHotUpdateSuccess()\n }\n\n if (isUpdateAvailable()) {\n // While we were updating, there was a new update! Do it again.\n tryApplyUpdates()\n }\n }\n\n // https://webpack.github.io/docs/hot-module-replacement.html#check\n try {\n const updatedModules = await module.hot.check(/* autoApply */ {\n ignoreUnaccepted: true\n })\n if (updatedModules) {\n handleApplyUpdates(null, updatedModules)\n }\n } catch (err) {\n handleApplyUpdates(err, null)\n }\n}", "language": "javascript", "code": "async function tryApplyUpdates (onHotUpdateSuccess) {\n if (!module.hot) {\n // HotModuleReplacementPlugin is not in Webpack configuration.\n console.error('HotModuleReplacementPlugin is not in Webpack configuration.')\n // window.location.reload();\n return\n }\n\n if (!isUpdateAvailable() || !canApplyUpdates()) {\n return\n }\n\n function handleApplyUpdates (err, updatedModules) {\n if (err || hadRuntimeError) {\n if (err) {\n console.warn('Error while applying updates, reloading page', err)\n }\n if (hadRuntimeError) {\n console.warn('Had runtime error previously, reloading page')\n }\n window.location.reload()\n return\n }\n\n if (typeof onHotUpdateSuccess === 'function') {\n // Maybe we want to do something.\n onHotUpdateSuccess()\n }\n\n if (isUpdateAvailable()) {\n // While we were updating, there was a new update! Do it again.\n tryApplyUpdates()\n }\n }\n\n // https://webpack.github.io/docs/hot-module-replacement.html#check\n try {\n const updatedModules = await module.hot.check(/* autoApply */ {\n ignoreUnaccepted: true\n })\n if (updatedModules) {\n handleApplyUpdates(null, updatedModules)\n }\n } catch (err) {\n handleApplyUpdates(err, null)\n }\n}", "code_tokens": ["async", "function", "tryApplyUpdates", "(", "onHotUpdateSuccess", ")", "{", "if", "(", "!", "module", ".", "hot", ")", "{", "console", ".", "error", "(", "'HotModuleReplacementPlugin is not in Webpack configuration.'", ")", "return", "}", "if", "(", "!", "isUpdateAvailable", "(", ")", "||", "!", "canApplyUpdates", "(", ")", ")", "{", "return", "}", "function", "handleApplyUpdates", "(", "err", ",", "updatedModules", ")", "{", "if", "(", "err", "||", "hadRuntimeError", ")", "{", "if", "(", "err", ")", "{", "console", ".", "warn", "(", "'Error while applying updates, reloading page'", ",", "err", ")", "}", "if", "(", "hadRuntimeError", ")", "{", "console", ".", "warn", "(", "'Had runtime error previously, reloading page'", ")", "}", "window", ".", "location", ".", "reload", "(", ")", "return", "}", "if", "(", "typeof", "onHotUpdateSuccess", "===", "'function'", ")", "{", "onHotUpdateSuccess", "(", ")", "}", "if", "(", "isUpdateAvailable", "(", ")", ")", "{", "tryApplyUpdates", "(", ")", "}", "}", "try", "{", "const", "updatedModules", "=", "await", "module", ".", "hot", ".", "check", "(", "{", "ignoreUnaccepted", ":", "true", "}", ")", "if", "(", "updatedModules", ")", "{", "handleApplyUpdates", "(", "null", ",", "updatedModules", ")", "}", "}", "catch", "(", "err", ")", "{", "handleApplyUpdates", "(", "err", ",", "null", ")", "}", "}"], "docstring": "Attempt to update code on the fly, fall back to a hard reload.", "docstring_tokens": ["Attempt", "to", "update", "code", "on", "the", "fly", "fall", "back", "to", "a", "hard", "reload", "."], "sha": "3641f79a0f68d1093cc238b50b8d47eec1c25cfd", "url": "https://github.com/zeit/next.js/blob/3641f79a0f68d1093cc238b50b8d47eec1c25cfd/packages/next/client/dev-error-overlay/hot-dev-client.js#L260-L306", "partition": "test"} {"repo": "zeit/next.js", "path": "packages/next/client/amp-dev.js", "func_name": "tryApplyUpdates", "original_string": "async function tryApplyUpdates () {\n if (!isUpdateAvailable() || !canApplyUpdates()) {\n return\n }\n try {\n const res = await fetch(`${hotUpdatePath}${curHash}.hot-update.json`)\n const data = await res.json()\n const curPage = page === '/' ? 'index' : page\n const pageUpdated = Object.keys(data.c)\n .some(mod => {\n return (\n mod.indexOf(`pages${curPage.substr(0, 1) === '/' ? curPage : `/${curPage}`}`) !== -1 ||\n mod.indexOf(`pages${curPage.substr(0, 1) === '/' ? curPage : `/${curPage}`}`.replace(/\\//g, '\\\\')) !== -1\n )\n })\n\n if (pageUpdated) {\n document.location.reload(true)\n } else {\n curHash = mostRecentHash\n }\n } catch (err) {\n console.error('Error occurred checking for update', err)\n document.location.reload(true)\n }\n}", "language": "javascript", "code": "async function tryApplyUpdates () {\n if (!isUpdateAvailable() || !canApplyUpdates()) {\n return\n }\n try {\n const res = await fetch(`${hotUpdatePath}${curHash}.hot-update.json`)\n const data = await res.json()\n const curPage = page === '/' ? 'index' : page\n const pageUpdated = Object.keys(data.c)\n .some(mod => {\n return (\n mod.indexOf(`pages${curPage.substr(0, 1) === '/' ? curPage : `/${curPage}`}`) !== -1 ||\n mod.indexOf(`pages${curPage.substr(0, 1) === '/' ? curPage : `/${curPage}`}`.replace(/\\//g, '\\\\')) !== -1\n )\n })\n\n if (pageUpdated) {\n document.location.reload(true)\n } else {\n curHash = mostRecentHash\n }\n } catch (err) {\n console.error('Error occurred checking for update', err)\n document.location.reload(true)\n }\n}", "code_tokens": ["async", "function", "tryApplyUpdates", "(", ")", "{", "if", "(", "!", "isUpdateAvailable", "(", ")", "||", "!", "canApplyUpdates", "(", ")", ")", "{", "return", "}", "try", "{", "const", "res", "=", "await", "fetch", "(", "`", "${", "hotUpdatePath", "}", "${", "curHash", "}", "`", ")", "const", "data", "=", "await", "res", ".", "json", "(", ")", "const", "curPage", "=", "page", "===", "'/'", "?", "'index'", ":", "page", "const", "pageUpdated", "=", "Object", ".", "keys", "(", "data", ".", "c", ")", ".", "some", "(", "mod", "=>", "{", "return", "(", "mod", ".", "indexOf", "(", "`", "${", "curPage", ".", "substr", "(", "0", ",", "1", ")", "===", "'/'", "?", "curPage", ":", "`", "${", "curPage", "}", "`", "}", "`", ")", "!==", "-", "1", "||", "mod", ".", "indexOf", "(", "`", "${", "curPage", ".", "substr", "(", "0", ",", "1", ")", "===", "'/'", "?", "curPage", ":", "`", "${", "curPage", "}", "`", "}", "`", ".", "replace", "(", "/", "\\/", "/", "g", ",", "'\\\\'", ")", ")", "!==", "\\\\", ")", "}", ")", "-", "1", "}", "if", "(", "pageUpdated", ")", "{", "document", ".", "location", ".", "reload", "(", "true", ")", "}", "else", "{", "curHash", "=", "mostRecentHash", "}", "}"], "docstring": "This function reads code updates on the fly and hard reloads the page when it has changed.", "docstring_tokens": ["This", "function", "reads", "code", "updates", "on", "the", "fly", "and", "hard", "reloads", "the", "page", "when", "it", "has", "changed", "."], "sha": "3641f79a0f68d1093cc238b50b8d47eec1c25cfd", "url": "https://github.com/zeit/next.js/blob/3641f79a0f68d1093cc238b50b8d47eec1c25cfd/packages/next/client/amp-dev.js#L34-L59", "partition": "test"} {"repo": "zeit/next.js", "path": "packages/next/client/dev-error-overlay/format-webpack-messages.js", "func_name": "formatMessage", "original_string": "function formatMessage (message, isError) {\n let lines = message.split('\\n')\n\n // Strip Webpack-added headers off errors/warnings\n // https://github.com/webpack/webpack/blob/master/lib/ModuleError.js\n lines = lines.filter(line => !/Module [A-z ]+\\(from/.test(line))\n\n // Transform parsing error into syntax error\n // TODO: move this to our ESLint formatter?\n lines = lines.map(line => {\n const parsingError = /Line (\\d+):(?:(\\d+):)?\\s*Parsing error: (.+)$/.exec(\n line\n )\n if (!parsingError) {\n return line\n }\n const [, errorLine, errorColumn, errorMessage] = parsingError\n return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`\n })\n\n message = lines.join('\\n')\n // Smoosh syntax errors (commonly found in CSS)\n message = message.replace(\n /SyntaxError\\s+\\((\\d+):(\\d+)\\)\\s*(.+?)\\n/g,\n `${friendlySyntaxErrorLabel} $3 ($1:$2)\\n`\n )\n // Remove columns from ESLint formatter output (we added these for more\n // accurate syntax errors)\n message = message.replace(/Line (\\d+):\\d+:/g, 'Line $1:')\n // Clean up export errors\n message = message.replace(\n /^.*export '(.+?)' was not found in '(.+?)'.*$/gm,\n `Attempted import error: '$1' is not exported from '$2'.`\n )\n message = message.replace(\n /^.*export 'default' \\(imported as '(.+?)'\\) was not found in '(.+?)'.*$/gm,\n `Attempted import error: '$2' does not contain a default export (imported as '$1').`\n )\n message = message.replace(\n /^.*export '(.+?)' \\(imported as '(.+?)'\\) was not found in '(.+?)'.*$/gm,\n `Attempted import error: '$1' is not exported from '$3' (imported as '$2').`\n )\n lines = message.split('\\n')\n\n // Remove leading newline\n if (lines.length > 2 && lines[1].trim() === '') {\n lines.splice(1, 1)\n }\n // Clean up file name\n lines[0] = lines[0].replace(/^(.*) \\d+:\\d+-\\d+$/, '$1')\n\n // Cleans up verbose \"module not found\" messages for files and packages.\n if (lines[1] && lines[1].indexOf('Module not found: ') === 0) {\n lines = [\n lines[0],\n lines[1]\n .replace('Error: ', '')\n .replace('Module not found: Cannot find file:', 'Cannot find file:')\n ]\n }\n\n message = lines.join('\\n')\n // Internal stacks are generally useless so we strip them... with the\n // exception of stacks containing `webpack:` because they're normally\n // from user code generated by Webpack. For more information see\n // https://github.com/facebook/create-react-app/pull/1050\n message = message.replace(\n /^\\s*at\\s((?!webpack:).)*:\\d+:\\d+[\\s)]*(\\n|$)/gm,\n ''\n ) // at ... ...:x:y\n message = message.replace(/^\\s*at\\s(\\n|$)/gm, '') // at \n lines = message.split('\\n')\n\n // Remove duplicated newlines\n lines = lines.filter(\n (line, index, arr) =>\n index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim()\n )\n\n // Reassemble the message\n message = lines.join('\\n')\n return message.trim()\n}", "language": "javascript", "code": "function formatMessage (message, isError) {\n let lines = message.split('\\n')\n\n // Strip Webpack-added headers off errors/warnings\n // https://github.com/webpack/webpack/blob/master/lib/ModuleError.js\n lines = lines.filter(line => !/Module [A-z ]+\\(from/.test(line))\n\n // Transform parsing error into syntax error\n // TODO: move this to our ESLint formatter?\n lines = lines.map(line => {\n const parsingError = /Line (\\d+):(?:(\\d+):)?\\s*Parsing error: (.+)$/.exec(\n line\n )\n if (!parsingError) {\n return line\n }\n const [, errorLine, errorColumn, errorMessage] = parsingError\n return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`\n })\n\n message = lines.join('\\n')\n // Smoosh syntax errors (commonly found in CSS)\n message = message.replace(\n /SyntaxError\\s+\\((\\d+):(\\d+)\\)\\s*(.+?)\\n/g,\n `${friendlySyntaxErrorLabel} $3 ($1:$2)\\n`\n )\n // Remove columns from ESLint formatter output (we added these for more\n // accurate syntax errors)\n message = message.replace(/Line (\\d+):\\d+:/g, 'Line $1:')\n // Clean up export errors\n message = message.replace(\n /^.*export '(.+?)' was not found in '(.+?)'.*$/gm,\n `Attempted import error: '$1' is not exported from '$2'.`\n )\n message = message.replace(\n /^.*export 'default' \\(imported as '(.+?)'\\) was not found in '(.+?)'.*$/gm,\n `Attempted import error: '$2' does not contain a default export (imported as '$1').`\n )\n message = message.replace(\n /^.*export '(.+?)' \\(imported as '(.+?)'\\) was not found in '(.+?)'.*$/gm,\n `Attempted import error: '$1' is not exported from '$3' (imported as '$2').`\n )\n lines = message.split('\\n')\n\n // Remove leading newline\n if (lines.length > 2 && lines[1].trim() === '') {\n lines.splice(1, 1)\n }\n // Clean up file name\n lines[0] = lines[0].replace(/^(.*) \\d+:\\d+-\\d+$/, '$1')\n\n // Cleans up verbose \"module not found\" messages for files and packages.\n if (lines[1] && lines[1].indexOf('Module not found: ') === 0) {\n lines = [\n lines[0],\n lines[1]\n .replace('Error: ', '')\n .replace('Module not found: Cannot find file:', 'Cannot find file:')\n ]\n }\n\n message = lines.join('\\n')\n // Internal stacks are generally useless so we strip them... with the\n // exception of stacks containing `webpack:` because they're normally\n // from user code generated by Webpack. For more information see\n // https://github.com/facebook/create-react-app/pull/1050\n message = message.replace(\n /^\\s*at\\s((?!webpack:).)*:\\d+:\\d+[\\s)]*(\\n|$)/gm,\n ''\n ) // at ... ...:x:y\n message = message.replace(/^\\s*at\\s(\\n|$)/gm, '') // at \n lines = message.split('\\n')\n\n // Remove duplicated newlines\n lines = lines.filter(\n (line, index, arr) =>\n index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim()\n )\n\n // Reassemble the message\n message = lines.join('\\n')\n return message.trim()\n}", "code_tokens": ["function", "formatMessage", "(", "message", ",", "isError", ")", "{", "let", "lines", "=", "message", ".", "split", "(", "'\\n'", ")", "\\n", "lines", "=", "lines", ".", "filter", "(", "line", "=>", "!", "/", "Module [A-z ]+\\(from", "/", ".", "test", "(", "line", ")", ")", "lines", "=", "lines", ".", "map", "(", "line", "=>", "{", "const", "parsingError", "=", "/", "Line (\\d+):(?:(\\d+):)?\\s*Parsing error: (.+)$", "/", ".", "exec", "(", "line", ")", "if", "(", "!", "parsingError", ")", "{", "return", "line", "}", "const", "[", ",", "errorLine", ",", "errorColumn", ",", "errorMessage", "]", "=", "parsingError", "return", "`", "${", "friendlySyntaxErrorLabel", "}", "${", "errorMessage", "}", "${", "errorLine", "}", "${", "errorColumn", "}", "`", "}", ")", "message", "=", "lines", ".", "join", "(", "'\\n'", ")", "\\n", "message", "=", "message", ".", "replace", "(", "/", "SyntaxError\\s+\\((\\d+):(\\d+)\\)\\s*(.+?)\\n", "/", "g", ",", "`", "${", "friendlySyntaxErrorLabel", "}", "\\n", "`", ")", "message", "=", "message", ".", "replace", "(", "/", "Line (\\d+):\\d+:", "/", "g", ",", "'Line $1:'", ")", "message", "=", "message", ".", "replace", "(", "/", "^.*export '(.+?)' was not found in '(.+?)'.*$", "/", "gm", ",", "`", "`", ")", "message", "=", "message", ".", "replace", "(", "/", "^.*export 'default' \\(imported as '(.+?)'\\) was not found in '(.+?)'.*$", "/", "gm", ",", "`", "`", ")", "message", "=", "message", ".", "replace", "(", "/", "^.*export '(.+?)' \\(imported as '(.+?)'\\) was not found in '(.+?)'.*$", "/", "gm", ",", "`", "`", ")", "lines", "=", "message", ".", "split", "(", "'\\n'", ")", "\\n", "if", "(", "lines", ".", "length", ">", "2", "&&", "lines", "[", "1", "]", ".", "trim", "(", ")", "===", "''", ")", "{", "lines", ".", "splice", "(", "1", ",", "1", ")", "}", "lines", "[", "0", "]", "=", "lines", "[", "0", "]", ".", "replace", "(", "/", "^(.*) \\d+:\\d+-\\d+$", "/", ",", "'$1'", ")", "if", "(", "lines", "[", "1", "]", "&&", "lines", "[", "1", "]", ".", "indexOf", "(", "'Module not found: '", ")", "===", "0", ")", "{", "lines", "=", "[", "lines", "[", "0", "]", ",", "lines", "[", "1", "]", ".", "replace", "(", "'Error: '", ",", "''", ")", ".", "replace", "(", "'Module not found: Cannot find file:'", ",", "'Cannot find file:'", ")", "]", "}", "message", "=", "lines", ".", "join", "(", "'\\n'", ")", "\\n", "message", "=", "message", ".", "replace", "(", "/", "^\\s*at\\s((?!webpack:).)*:\\d+:\\d+[\\s)]*(\\n|$)", "/", "gm", ",", "''", ")", "message", "=", "message", ".", "replace", "(", "/", "^\\s*at\\s(\\n|$)", "/", "gm", ",", "''", ")", "}"], "docstring": "Cleans up webpack error messages. eslint-disable-next-line no-unused-vars", "docstring_tokens": ["Cleans", "up", "webpack", "error", "messages", ".", "eslint", "-", "disable", "-", "next", "-", "line", "no", "-", "unused", "-", "vars"], "sha": "3641f79a0f68d1093cc238b50b8d47eec1c25cfd", "url": "https://github.com/zeit/next.js/blob/3641f79a0f68d1093cc238b50b8d47eec1c25cfd/packages/next/client/dev-error-overlay/format-webpack-messages.js#L37-L119", "partition": "test"} {"repo": "everitoken/evtjs", "path": "lib/format.js", "func_name": "UDecimalPad", "original_string": "function UDecimalPad(num, precision) {\n var value = UDecimalString(num);\n assert.equal(\"number\", typeof precision === 'undefined' ? 'undefined' : (0, _typeof3.default)(precision), \"precision\");\n\n var part = value.split(\".\");\n\n if (precision === 0 && part.length === 1) {\n return part[0];\n }\n\n if (part.length === 1) {\n return part[0] + '.' + \"0\".repeat(precision);\n } else {\n var pad = precision - part[1].length;\n assert(pad >= 0, 'decimal \\'' + value + '\\' exceeds precision ' + precision);\n return part[0] + '.' + part[1] + \"0\".repeat(pad);\n }\n}", "language": "javascript", "code": "function UDecimalPad(num, precision) {\n var value = UDecimalString(num);\n assert.equal(\"number\", typeof precision === 'undefined' ? 'undefined' : (0, _typeof3.default)(precision), \"precision\");\n\n var part = value.split(\".\");\n\n if (precision === 0 && part.length === 1) {\n return part[0];\n }\n\n if (part.length === 1) {\n return part[0] + '.' + \"0\".repeat(precision);\n } else {\n var pad = precision - part[1].length;\n assert(pad >= 0, 'decimal \\'' + value + '\\' exceeds precision ' + precision);\n return part[0] + '.' + part[1] + \"0\".repeat(pad);\n }\n}", "code_tokens": ["function", "UDecimalPad", "(", "num", ",", "precision", ")", "{", "var", "value", "=", "UDecimalString", "(", "num", ")", ";", "assert", ".", "equal", "(", "\"number\"", ",", "typeof", "precision", "===", "'undefined'", "?", "'undefined'", ":", "(", "0", ",", "_typeof3", ".", "default", ")", "(", "precision", ")", ",", "\"precision\"", ")", ";", "var", "part", "=", "value", ".", "split", "(", "\".\"", ")", ";", "if", "(", "precision", "===", "0", "&&", "part", ".", "length", "===", "1", ")", "{", "return", "part", "[", "0", "]", ";", "}", "if", "(", "part", ".", "length", "===", "1", ")", "{", "return", "part", "[", "0", "]", "+", "'.'", "+", "\"0\"", ".", "repeat", "(", "precision", ")", ";", "}", "else", "{", "var", "pad", "=", "precision", "-", "part", "[", "1", "]", ".", "length", ";", "assert", "(", "pad", ">=", "0", ",", "'decimal \\''", "+", "\\'", "+", "value", "+", "'\\' exceeds precision '", ")", ";", "\\'", "}", "}"], "docstring": "Ensure a fixed number of decimal places. Safe for large numbers.\n\n@see ./format.test.js\n\n@example UDecimalPad(10.2, 3) === '10.200'\n\n@arg {number|string|object.toString} value\n@arg {number} precision - number of decimal places\n@return {string} decimal part is added and zero padded to match precision", "docstring_tokens": ["Ensure", "a", "fixed", "number", "of", "decimal", "places", ".", "Safe", "for", "large", "numbers", "."], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/lib/format.js#L373-L390", "partition": "test"} {"repo": "everitoken/evtjs", "path": "src/evtLink.js", "func_name": "parseSegment", "original_string": "function parseSegment(buffer, offset) {\n let typeKey = buffer[offset];\n\n if (typeKey <= 20) {\n if (buffer[offset + 1] == undefined) throw new Error(\"ParseError: No value for uint8\");\n return { typeKey: typeKey, value: buffer[offset + 1], bufferLength: 2 };\n }\n if (typeKey <= 40) {\n if (buffer[offset + 2] == undefined) throw new Error(\"ParseError: Incomplete value for uint16\");\n return { typeKey: typeKey, value: buffer.readUInt16BE(offset + 1), bufferLength: 3 };\n }\n else if (typeKey <= 90) {\n if (buffer[offset + 4] == undefined) throw new Error(\"ParseError: Incomplete value for uint32\");\n return { typeKey: typeKey, value: buffer.readUInt32BE(offset + 1), bufferLength: 5 };\n }\n else if (typeKey <= 155) {\n if (buffer[offset + 1] == undefined) throw new Error(\"ParseError: Incomplete length value for string\");\n let len = buffer.readUInt8(offset + 1);\n if (buffer[offset + 1 + len] == undefined) throw new Error(\"ParseError: Incomplete value for string\");\n let value = buffer.toString(\"utf8\", offset + 2, offset + 2 + len);\n\n return { typeKey: typeKey, value: value, bufferLength: 2 + len };\n }\n else if (typeKey <= 165) {\n if (buffer[offset + 16] == undefined) throw new Error(\"ParseError: Incomplete value for uuid\");\n let len = 16;\n let value = new Buffer(len);\n buffer.copy(value, 0, offset + 1, offset + 1 + len);\n\n return { typeKey: typeKey, value: value, bufferLength: 1 + len };\n }\n else if (typeKey <= 180) {\n if (buffer[offset + 1] == undefined) throw new Error(\"ParseError: Incomplete length value for byte string\");\n let len = buffer.readUInt8(offset + 1);\n if (buffer[offset + len + 1] == undefined) throw new Error(\"ParseError: Incomplete value for byte string\");\n let value = new Buffer(len);\n buffer.copy(value, 0, offset + 2, offset + 2 + len);\n\n return { typeKey: typeKey, value: value, bufferLength: 2 + len };\n }\n else {\n throw new Error(\"typeKey not supported\");\n }\n}", "language": "javascript", "code": "function parseSegment(buffer, offset) {\n let typeKey = buffer[offset];\n\n if (typeKey <= 20) {\n if (buffer[offset + 1] == undefined) throw new Error(\"ParseError: No value for uint8\");\n return { typeKey: typeKey, value: buffer[offset + 1], bufferLength: 2 };\n }\n if (typeKey <= 40) {\n if (buffer[offset + 2] == undefined) throw new Error(\"ParseError: Incomplete value for uint16\");\n return { typeKey: typeKey, value: buffer.readUInt16BE(offset + 1), bufferLength: 3 };\n }\n else if (typeKey <= 90) {\n if (buffer[offset + 4] == undefined) throw new Error(\"ParseError: Incomplete value for uint32\");\n return { typeKey: typeKey, value: buffer.readUInt32BE(offset + 1), bufferLength: 5 };\n }\n else if (typeKey <= 155) {\n if (buffer[offset + 1] == undefined) throw new Error(\"ParseError: Incomplete length value for string\");\n let len = buffer.readUInt8(offset + 1);\n if (buffer[offset + 1 + len] == undefined) throw new Error(\"ParseError: Incomplete value for string\");\n let value = buffer.toString(\"utf8\", offset + 2, offset + 2 + len);\n\n return { typeKey: typeKey, value: value, bufferLength: 2 + len };\n }\n else if (typeKey <= 165) {\n if (buffer[offset + 16] == undefined) throw new Error(\"ParseError: Incomplete value for uuid\");\n let len = 16;\n let value = new Buffer(len);\n buffer.copy(value, 0, offset + 1, offset + 1 + len);\n\n return { typeKey: typeKey, value: value, bufferLength: 1 + len };\n }\n else if (typeKey <= 180) {\n if (buffer[offset + 1] == undefined) throw new Error(\"ParseError: Incomplete length value for byte string\");\n let len = buffer.readUInt8(offset + 1);\n if (buffer[offset + len + 1] == undefined) throw new Error(\"ParseError: Incomplete value for byte string\");\n let value = new Buffer(len);\n buffer.copy(value, 0, offset + 2, offset + 2 + len);\n\n return { typeKey: typeKey, value: value, bufferLength: 2 + len };\n }\n else {\n throw new Error(\"typeKey not supported\");\n }\n}", "code_tokens": ["function", "parseSegment", "(", "buffer", ",", "offset", ")", "{", "let", "typeKey", "=", "buffer", "[", "offset", "]", ";", "if", "(", "typeKey", "<=", "20", ")", "{", "if", "(", "buffer", "[", "offset", "+", "1", "]", "==", "undefined", ")", "throw", "new", "Error", "(", "\"ParseError: No value for uint8\"", ")", ";", "return", "{", "typeKey", ":", "typeKey", ",", "value", ":", "buffer", "[", "offset", "+", "1", "]", ",", "bufferLength", ":", "2", "}", ";", "}", "if", "(", "typeKey", "<=", "40", ")", "{", "if", "(", "buffer", "[", "offset", "+", "2", "]", "==", "undefined", ")", "throw", "new", "Error", "(", "\"ParseError: Incomplete value for uint16\"", ")", ";", "return", "{", "typeKey", ":", "typeKey", ",", "value", ":", "buffer", ".", "readUInt16BE", "(", "offset", "+", "1", ")", ",", "bufferLength", ":", "3", "}", ";", "}", "else", "if", "(", "typeKey", "<=", "90", ")", "{", "if", "(", "buffer", "[", "offset", "+", "4", "]", "==", "undefined", ")", "throw", "new", "Error", "(", "\"ParseError: Incomplete value for uint32\"", ")", ";", "return", "{", "typeKey", ":", "typeKey", ",", "value", ":", "buffer", ".", "readUInt32BE", "(", "offset", "+", "1", ")", ",", "bufferLength", ":", "5", "}", ";", "}", "else", "if", "(", "typeKey", "<=", "155", ")", "{", "if", "(", "buffer", "[", "offset", "+", "1", "]", "==", "undefined", ")", "throw", "new", "Error", "(", "\"ParseError: Incomplete length value for string\"", ")", ";", "let", "len", "=", "buffer", ".", "readUInt8", "(", "offset", "+", "1", ")", ";", "if", "(", "buffer", "[", "offset", "+", "1", "+", "len", "]", "==", "undefined", ")", "throw", "new", "Error", "(", "\"ParseError: Incomplete value for string\"", ")", ";", "let", "value", "=", "buffer", ".", "toString", "(", "\"utf8\"", ",", "offset", "+", "2", ",", "offset", "+", "2", "+", "len", ")", ";", "return", "{", "typeKey", ":", "typeKey", ",", "value", ":", "value", ",", "bufferLength", ":", "2", "+", "len", "}", ";", "}", "else", "if", "(", "typeKey", "<=", "165", ")", "{", "if", "(", "buffer", "[", "offset", "+", "16", "]", "==", "undefined", ")", "throw", "new", "Error", "(", "\"ParseError: Incomplete value for uuid\"", ")", ";", "let", "len", "=", "16", ";", "let", "value", "=", "new", "Buffer", "(", "len", ")", ";", "buffer", ".", "copy", "(", "value", ",", "0", ",", "offset", "+", "1", ",", "offset", "+", "1", "+", "len", ")", ";", "return", "{", "typeKey", ":", "typeKey", ",", "value", ":", "value", ",", "bufferLength", ":", "1", "+", "len", "}", ";", "}", "else", "if", "(", "typeKey", "<=", "180", ")", "{", "if", "(", "buffer", "[", "offset", "+", "1", "]", "==", "undefined", ")", "throw", "new", "Error", "(", "\"ParseError: Incomplete length value for byte string\"", ")", ";", "let", "len", "=", "buffer", ".", "readUInt8", "(", "offset", "+", "1", ")", ";", "if", "(", "buffer", "[", "offset", "+", "len", "+", "1", "]", "==", "undefined", ")", "throw", "new", "Error", "(", "\"ParseError: Incomplete value for byte string\"", ")", ";", "let", "value", "=", "new", "Buffer", "(", "len", ")", ";", "buffer", ".", "copy", "(", "value", ",", "0", ",", "offset", "+", "2", ",", "offset", "+", "2", "+", "len", ")", ";", "return", "{", "typeKey", ":", "typeKey", ",", "value", ":", "value", ",", "bufferLength", ":", "2", "+", "len", "}", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"typeKey not supported\"", ")", ";", "}", "}"], "docstring": "Parse a segment and convert it into json.\n@param {Buffer} buffer\n@param {number} offset", "docstring_tokens": ["Parse", "a", "segment", "and", "convert", "it", "into", "json", "."], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/src/evtLink.js#L138-L181", "partition": "test"} {"repo": "everitoken/evtjs", "path": "src/evtLink.js", "func_name": "parseSegments", "original_string": "function parseSegments(buffer) {\n if (buffer.length == 0) throw new Error(\"bad segments stream\");\n\n let pointer = 0;\n let segments = [ ];\n\n while (pointer < buffer.length) {\n let seg = parseSegment(buffer, pointer);\n segments.push(seg);\n pointer += seg.bufferLength;\n delete seg.bufferLength;\n }\n\n if (pointer != buffer.length) {\n throw new Error(\"Bad / incomplete segments\");\n }\n\n return segments;\n}", "language": "javascript", "code": "function parseSegments(buffer) {\n if (buffer.length == 0) throw new Error(\"bad segments stream\");\n\n let pointer = 0;\n let segments = [ ];\n\n while (pointer < buffer.length) {\n let seg = parseSegment(buffer, pointer);\n segments.push(seg);\n pointer += seg.bufferLength;\n delete seg.bufferLength;\n }\n\n if (pointer != buffer.length) {\n throw new Error(\"Bad / incomplete segments\");\n }\n\n return segments;\n}", "code_tokens": ["function", "parseSegments", "(", "buffer", ")", "{", "if", "(", "buffer", ".", "length", "==", "0", ")", "throw", "new", "Error", "(", "\"bad segments stream\"", ")", ";", "let", "pointer", "=", "0", ";", "let", "segments", "=", "[", "]", ";", "while", "(", "pointer", "<", "buffer", ".", "length", ")", "{", "let", "seg", "=", "parseSegment", "(", "buffer", ",", "pointer", ")", ";", "segments", ".", "push", "(", "seg", ")", ";", "pointer", "+=", "seg", ".", "bufferLength", ";", "delete", "seg", ".", "bufferLength", ";", "}", "if", "(", "pointer", "!=", "buffer", ".", "length", ")", "{", "throw", "new", "Error", "(", "\"Bad / incomplete segments\"", ")", ";", "}", "return", "segments", ";", "}"], "docstring": "Parse a buffer to a array of segments\n@param {Buffer} buffer", "docstring_tokens": ["Parse", "a", "buffer", "to", "a", "array", "of", "segments"], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/src/evtLink.js#L187-L205", "partition": "test"} {"repo": "everitoken/evtjs", "path": "src/evtLink.js", "func_name": "parseQRCode", "original_string": "function parseQRCode(text, options) {\n if (text.length < 3 || text.length > 2000) throw new Error(\"Invalid length of EvtLink\");\n\n let textSplited = text.split(\"_\");\n if (textSplited.length > 2) return null;\n\n let rawText;\n\n if (textSplited[0].startsWith(qrPrefix)) {\n rawText = textSplited[0].substr(qrPrefix.length);\n }\n else {\n rawText = textSplited[0];\n }\n \n // decode segments base42\n let segmentsBytes = EvtLink.dec2b(rawText);\n if (segmentsBytes.length < 2) throw new Error(\"no flag in segment\");\n let flag = segmentsBytes.readInt16BE(0);\n \n if ((flag & 1) == 0) { // check version of EvtLink\n throw new Error(\"The EvtLink is invalid or its version is newer than version 1 and is not supported by evtjs yet\");\n }\n let segmentsBytesRaw = new Buffer(segmentsBytes.length - 2);\n segmentsBytes.copy(segmentsBytesRaw, 0, 2, segmentsBytes.length);\n\n let publicKeys = [ ];\n let signatures = [ ];\n\n if (textSplited[1]) {\n let buf = EvtLink.dec2b(textSplited[1]);\n let i = 0;\n\n if (buf.length % 65 !== 0) {\n throw new Error(\"length of signature is invalid\");\n }\n\n while (i * 65 < buf.length) {\n let current = new Buffer(65);\n buf.copy(current, 0, i * 65, i * 65 + 65);\n let signature = ecc.Signature.fromBuffer(current);\n signatures.push(signature.toString());\n\n if (!options || options.recoverPublicKeys) {\n publicKeys.push(signature.recover(segmentsBytes).toString());\n }\n\n ++i;\n }\n }\n\n return { flag, segments: parseSegments(segmentsBytesRaw), publicKeys, signatures };\n}", "language": "javascript", "code": "function parseQRCode(text, options) {\n if (text.length < 3 || text.length > 2000) throw new Error(\"Invalid length of EvtLink\");\n\n let textSplited = text.split(\"_\");\n if (textSplited.length > 2) return null;\n\n let rawText;\n\n if (textSplited[0].startsWith(qrPrefix)) {\n rawText = textSplited[0].substr(qrPrefix.length);\n }\n else {\n rawText = textSplited[0];\n }\n \n // decode segments base42\n let segmentsBytes = EvtLink.dec2b(rawText);\n if (segmentsBytes.length < 2) throw new Error(\"no flag in segment\");\n let flag = segmentsBytes.readInt16BE(0);\n \n if ((flag & 1) == 0) { // check version of EvtLink\n throw new Error(\"The EvtLink is invalid or its version is newer than version 1 and is not supported by evtjs yet\");\n }\n let segmentsBytesRaw = new Buffer(segmentsBytes.length - 2);\n segmentsBytes.copy(segmentsBytesRaw, 0, 2, segmentsBytes.length);\n\n let publicKeys = [ ];\n let signatures = [ ];\n\n if (textSplited[1]) {\n let buf = EvtLink.dec2b(textSplited[1]);\n let i = 0;\n\n if (buf.length % 65 !== 0) {\n throw new Error(\"length of signature is invalid\");\n }\n\n while (i * 65 < buf.length) {\n let current = new Buffer(65);\n buf.copy(current, 0, i * 65, i * 65 + 65);\n let signature = ecc.Signature.fromBuffer(current);\n signatures.push(signature.toString());\n\n if (!options || options.recoverPublicKeys) {\n publicKeys.push(signature.recover(segmentsBytes).toString());\n }\n\n ++i;\n }\n }\n\n return { flag, segments: parseSegments(segmentsBytesRaw), publicKeys, signatures };\n}", "code_tokens": ["function", "parseQRCode", "(", "text", ",", "options", ")", "{", "if", "(", "text", ".", "length", "<", "3", "||", "text", ".", "length", ">", "2000", ")", "throw", "new", "Error", "(", "\"Invalid length of EvtLink\"", ")", ";", "let", "textSplited", "=", "text", ".", "split", "(", "\"_\"", ")", ";", "if", "(", "textSplited", ".", "length", ">", "2", ")", "return", "null", ";", "let", "rawText", ";", "if", "(", "textSplited", "[", "0", "]", ".", "startsWith", "(", "qrPrefix", ")", ")", "{", "rawText", "=", "textSplited", "[", "0", "]", ".", "substr", "(", "qrPrefix", ".", "length", ")", ";", "}", "else", "{", "rawText", "=", "textSplited", "[", "0", "]", ";", "}", "let", "segmentsBytes", "=", "EvtLink", ".", "dec2b", "(", "rawText", ")", ";", "if", "(", "segmentsBytes", ".", "length", "<", "2", ")", "throw", "new", "Error", "(", "\"no flag in segment\"", ")", ";", "let", "flag", "=", "segmentsBytes", ".", "readInt16BE", "(", "0", ")", ";", "if", "(", "(", "flag", "&", "1", ")", "==", "0", ")", "{", "throw", "new", "Error", "(", "\"The EvtLink is invalid or its version is newer than version 1 and is not supported by evtjs yet\"", ")", ";", "}", "let", "segmentsBytesRaw", "=", "new", "Buffer", "(", "segmentsBytes", ".", "length", "-", "2", ")", ";", "segmentsBytes", ".", "copy", "(", "segmentsBytesRaw", ",", "0", ",", "2", ",", "segmentsBytes", ".", "length", ")", ";", "let", "publicKeys", "=", "[", "]", ";", "let", "signatures", "=", "[", "]", ";", "if", "(", "textSplited", "[", "1", "]", ")", "{", "let", "buf", "=", "EvtLink", ".", "dec2b", "(", "textSplited", "[", "1", "]", ")", ";", "let", "i", "=", "0", ";", "if", "(", "buf", ".", "length", "%", "65", "!==", "0", ")", "{", "throw", "new", "Error", "(", "\"length of signature is invalid\"", ")", ";", "}", "while", "(", "i", "*", "65", "<", "buf", ".", "length", ")", "{", "let", "current", "=", "new", "Buffer", "(", "65", ")", ";", "buf", ".", "copy", "(", "current", ",", "0", ",", "i", "*", "65", ",", "i", "*", "65", "+", "65", ")", ";", "let", "signature", "=", "ecc", ".", "Signature", ".", "fromBuffer", "(", "current", ")", ";", "signatures", ".", "push", "(", "signature", ".", "toString", "(", ")", ")", ";", "if", "(", "!", "options", "||", "options", ".", "recoverPublicKeys", ")", "{", "publicKeys", ".", "push", "(", "signature", ".", "recover", "(", "segmentsBytes", ")", ".", "toString", "(", ")", ")", ";", "}", "++", "i", ";", "}", "}", "return", "{", "flag", ",", "segments", ":", "parseSegments", "(", "segmentsBytesRaw", ")", ",", "publicKeys", ",", "signatures", "}", ";", "}"], "docstring": "Parse a everiToken's QRCode Text\n@param {string} text", "docstring_tokens": ["Parse", "a", "everiToken", "s", "QRCode", "Text"], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/src/evtLink.js#L211-L263", "partition": "test"} {"repo": "everitoken/evtjs", "path": "src/evtLink.js", "func_name": "__calcKeyProvider", "original_string": "async function __calcKeyProvider(keyProvider) {\n if (!keyProvider) { return []; }\n\n // if keyProvider is function\n if (keyProvider.apply && keyProvider.call) {\n keyProvider = keyProvider();\n }\n\n // resolve for Promise\n keyProvider = await Promise.resolve(keyProvider);\n\n if (!Array.isArray(keyProvider)) {\n keyProvider = [ keyProvider ];\n }\n\n for (let key of keyProvider) {\n if (!EvtKey.isValidPrivateKey(key)) {\n throw new Error(\"Invalid private key\");\n }\n }\n\n return keyProvider;\n}", "language": "javascript", "code": "async function __calcKeyProvider(keyProvider) {\n if (!keyProvider) { return []; }\n\n // if keyProvider is function\n if (keyProvider.apply && keyProvider.call) {\n keyProvider = keyProvider();\n }\n\n // resolve for Promise\n keyProvider = await Promise.resolve(keyProvider);\n\n if (!Array.isArray(keyProvider)) {\n keyProvider = [ keyProvider ];\n }\n\n for (let key of keyProvider) {\n if (!EvtKey.isValidPrivateKey(key)) {\n throw new Error(\"Invalid private key\");\n }\n }\n\n return keyProvider;\n}", "code_tokens": ["async", "function", "__calcKeyProvider", "(", "keyProvider", ")", "{", "if", "(", "!", "keyProvider", ")", "{", "return", "[", "]", ";", "}", "if", "(", "keyProvider", ".", "apply", "&&", "keyProvider", ".", "call", ")", "{", "keyProvider", "=", "keyProvider", "(", ")", ";", "}", "keyProvider", "=", "await", "Promise", ".", "resolve", "(", "keyProvider", ")", ";", "if", "(", "!", "Array", ".", "isArray", "(", "keyProvider", ")", ")", "{", "keyProvider", "=", "[", "keyProvider", "]", ";", "}", "for", "(", "let", "key", "of", "keyProvider", ")", "{", "if", "(", "!", "EvtKey", ".", "isValidPrivateKey", "(", "key", ")", ")", "{", "throw", "new", "Error", "(", "\"Invalid private key\"", ")", ";", "}", "}", "return", "keyProvider", ";", "}"], "docstring": "Calculate the value of keyProvider\n@param {string | string[] | function} keyProvider\n@returns {string[]}", "docstring_tokens": ["Calculate", "the", "value", "of", "keyProvider"], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/src/evtLink.js#L270-L292", "partition": "test"} {"repo": "everitoken/evtjs", "path": "src/ecc/key_utils.js", "func_name": "random32ByteBuffer", "original_string": "function random32ByteBuffer({cpuEntropyBits = 0, safe = true} = {}) {\n assert.equal(typeof cpuEntropyBits, \"number\", \"cpuEntropyBits\");\n assert.equal(typeof safe, \"boolean\", \"boolean\");\n\n if(safe) {\n assert(entropyCount >= 128, \"Call initialize() to add entropy (current: \" + entropyCount + \")\");\n }\n\n // if(entropyCount > 0) {\n // console.log(`Additional private key entropy: ${entropyCount} events`)\n // }\n\n const hash_array = [];\n hash_array.push(randomBytes(32));\n hash_array.push(Buffer.from(cpuEntropy(cpuEntropyBits)));\n hash_array.push(externalEntropyArray);\n hash_array.push(browserEntropy());\n return hash.sha256(Buffer.concat(hash_array));\n}", "language": "javascript", "code": "function random32ByteBuffer({cpuEntropyBits = 0, safe = true} = {}) {\n assert.equal(typeof cpuEntropyBits, \"number\", \"cpuEntropyBits\");\n assert.equal(typeof safe, \"boolean\", \"boolean\");\n\n if(safe) {\n assert(entropyCount >= 128, \"Call initialize() to add entropy (current: \" + entropyCount + \")\");\n }\n\n // if(entropyCount > 0) {\n // console.log(`Additional private key entropy: ${entropyCount} events`)\n // }\n\n const hash_array = [];\n hash_array.push(randomBytes(32));\n hash_array.push(Buffer.from(cpuEntropy(cpuEntropyBits)));\n hash_array.push(externalEntropyArray);\n hash_array.push(browserEntropy());\n return hash.sha256(Buffer.concat(hash_array));\n}", "code_tokens": ["function", "random32ByteBuffer", "(", "{", "cpuEntropyBits", "=", "0", ",", "safe", "=", "true", "}", "=", "{", "}", ")", "{", "assert", ".", "equal", "(", "typeof", "cpuEntropyBits", ",", "\"number\"", ",", "\"cpuEntropyBits\"", ")", ";", "assert", ".", "equal", "(", "typeof", "safe", ",", "\"boolean\"", ",", "\"boolean\"", ")", ";", "if", "(", "safe", ")", "{", "assert", "(", "entropyCount", ">=", "128", ",", "\"Call initialize() to add entropy (current: \"", "+", "entropyCount", "+", "\")\"", ")", ";", "}", "const", "hash_array", "=", "[", "]", ";", "hash_array", ".", "push", "(", "randomBytes", "(", "32", ")", ")", ";", "hash_array", ".", "push", "(", "Buffer", ".", "from", "(", "cpuEntropy", "(", "cpuEntropyBits", ")", ")", ")", ";", "hash_array", ".", "push", "(", "externalEntropyArray", ")", ";", "hash_array", ".", "push", "(", "browserEntropy", "(", ")", ")", ";", "return", "hash", ".", "sha256", "(", "Buffer", ".", "concat", "(", "hash_array", ")", ")", ";", "}"], "docstring": "Additional forms of entropy are used. A week random number generator can run out of entropy. This should ensure even the worst random number implementation will be reasonably safe.\n\n@arg {number} [cpuEntropyBits = 0] generate entropy on the fly. This is\nnot required, entropy can be added in advanced via addEntropy or initialize().\n\n@arg {boolean} [safe = true] false for testing, otherwise this will be\ntrue to ensure initialize() was called.\n\n@return a random buffer obtained from the secure random number generator. Additional entropy is used.", "docstring_tokens": ["Additional", "forms", "of", "entropy", "are", "used", ".", "A", "week", "random", "number", "generator", "can", "run", "out", "of", "entropy", ".", "This", "should", "ensure", "even", "the", "worst", "random", "number", "implementation", "will", "be", "reasonably", "safe", "."], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/src/ecc/key_utils.js#L32-L50", "partition": "test"} {"repo": "everitoken/evtjs", "path": "src/ecc/key_utils.js", "func_name": "addEntropy", "original_string": "function addEntropy(...ints) {\n assert.equal(externalEntropyArray.length, 101, \"externalEntropyArray\");\n\n entropyCount += ints.length;\n for(const i of ints) {\n const pos = entropyPos++ % 101;\n const i2 = externalEntropyArray[pos] += i;\n if(i2 > 9007199254740991)\n externalEntropyArray[pos] = 0;\n }\n}", "language": "javascript", "code": "function addEntropy(...ints) {\n assert.equal(externalEntropyArray.length, 101, \"externalEntropyArray\");\n\n entropyCount += ints.length;\n for(const i of ints) {\n const pos = entropyPos++ % 101;\n const i2 = externalEntropyArray[pos] += i;\n if(i2 > 9007199254740991)\n externalEntropyArray[pos] = 0;\n }\n}", "code_tokens": ["function", "addEntropy", "(", "...", "ints", ")", "{", "assert", ".", "equal", "(", "externalEntropyArray", ".", "length", ",", "101", ",", "\"externalEntropyArray\"", ")", ";", "entropyCount", "+=", "ints", ".", "length", ";", "for", "(", "const", "i", "of", "ints", ")", "{", "const", "pos", "=", "entropyPos", "++", "%", "101", ";", "const", "i2", "=", "externalEntropyArray", "[", "pos", "]", "+=", "i", ";", "if", "(", "i2", ">", "9007199254740991", ")", "externalEntropyArray", "[", "pos", "]", "=", "0", ";", "}", "}"], "docstring": "Adds entropy. This may be called many times while the amount of data saved\nis accumulatively reduced to 101 integers. Data is retained in RAM for the\nlife of this module.\n\n@example React \ncomponentDidMount() {\nthis.refs.MyComponent.addEventListener(\"mousemove\", this.onEntropyEvent, {capture: false, passive: true})\n}\ncomponentWillUnmount() {\nthis.refs.MyComponent.removeEventListener(\"mousemove\", this.onEntropyEvent);\n}\nonEntropyEvent = (e) => {\nif(e.type === 'mousemove')\nkey_utils.addEntropy(e.pageX, e.pageY, e.screenX, e.screenY)\nelse\nconsole.log('onEntropyEvent Unknown', e.type, e)\n}\n", "docstring_tokens": ["Adds", "entropy", ".", "This", "may", "be", "called", "many", "times", "while", "the", "amount", "of", "data", "saved", "is", "accumulatively", "reduced", "to", "101", "integers", ".", "Data", "is", "retained", "in", "RAM", "for", "the", "life", "of", "this", "module", "."], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/src/ecc/key_utils.js#L72-L82", "partition": "test"} {"repo": "everitoken/evtjs", "path": "src/ecc/key_utils.js", "func_name": "cpuEntropy", "original_string": "function cpuEntropy(cpuEntropyBits = 128) {\n let collected = [];\n let lastCount = null;\n let lowEntropySamples = 0;\n while(collected.length < cpuEntropyBits) {\n const count = floatingPointCount();\n if(lastCount != null) {\n const delta = count - lastCount;\n if(Math.abs(delta) < 1) {\n lowEntropySamples++;\n continue;\n }\n // how many bits of entropy were in this sample\n const bits = Math.floor(log2(Math.abs(delta)) + 1);\n if(bits < 4) {\n if(bits < 2) {\n lowEntropySamples++;\n }\n continue;\n }\n collected.push(delta);\n }\n lastCount = count;\n }\n if(lowEntropySamples > 10) {\n const pct = Number(lowEntropySamples / cpuEntropyBits * 100).toFixed(2);\n // Is this algorithm getting inefficient?\n console.warn(`WARN: ${pct}% low CPU entropy re-sampled`);\n }\n return collected;\n}", "language": "javascript", "code": "function cpuEntropy(cpuEntropyBits = 128) {\n let collected = [];\n let lastCount = null;\n let lowEntropySamples = 0;\n while(collected.length < cpuEntropyBits) {\n const count = floatingPointCount();\n if(lastCount != null) {\n const delta = count - lastCount;\n if(Math.abs(delta) < 1) {\n lowEntropySamples++;\n continue;\n }\n // how many bits of entropy were in this sample\n const bits = Math.floor(log2(Math.abs(delta)) + 1);\n if(bits < 4) {\n if(bits < 2) {\n lowEntropySamples++;\n }\n continue;\n }\n collected.push(delta);\n }\n lastCount = count;\n }\n if(lowEntropySamples > 10) {\n const pct = Number(lowEntropySamples / cpuEntropyBits * 100).toFixed(2);\n // Is this algorithm getting inefficient?\n console.warn(`WARN: ${pct}% low CPU entropy re-sampled`);\n }\n return collected;\n}", "code_tokens": ["function", "cpuEntropy", "(", "cpuEntropyBits", "=", "128", ")", "{", "let", "collected", "=", "[", "]", ";", "let", "lastCount", "=", "null", ";", "let", "lowEntropySamples", "=", "0", ";", "while", "(", "collected", ".", "length", "<", "cpuEntropyBits", ")", "{", "const", "count", "=", "floatingPointCount", "(", ")", ";", "if", "(", "lastCount", "!=", "null", ")", "{", "const", "delta", "=", "count", "-", "lastCount", ";", "if", "(", "Math", ".", "abs", "(", "delta", ")", "<", "1", ")", "{", "lowEntropySamples", "++", ";", "continue", ";", "}", "const", "bits", "=", "Math", ".", "floor", "(", "log2", "(", "Math", ".", "abs", "(", "delta", ")", ")", "+", "1", ")", ";", "if", "(", "bits", "<", "4", ")", "{", "if", "(", "bits", "<", "2", ")", "{", "lowEntropySamples", "++", ";", "}", "continue", ";", "}", "collected", ".", "push", "(", "delta", ")", ";", "}", "lastCount", "=", "count", ";", "}", "if", "(", "lowEntropySamples", ">", "10", ")", "{", "const", "pct", "=", "Number", "(", "lowEntropySamples", "/", "cpuEntropyBits", "*", "100", ")", ".", "toFixed", "(", "2", ")", ";", "console", ".", "warn", "(", "`", "${", "pct", "}", "`", ")", ";", "}", "return", "collected", ";", "}"], "docstring": "This runs in just under 1 second and ensures a minimum of cpuEntropyBits\nbits of entropy are gathered.\n\nBased on more-entropy. @see https://github.com/keybase/more-entropy/blob/master/src/generator.iced\n\n@arg {number} [cpuEntropyBits = 128]\n@return {array} counts gathered by measuring variations in the CPU speed during floating point operations.", "docstring_tokens": ["This", "runs", "in", "just", "under", "1", "second", "and", "ensures", "a", "minimum", "of", "cpuEntropyBits", "bits", "of", "entropy", "are", "gathered", "."], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/src/ecc/key_utils.js#L93-L123", "partition": "test"} {"repo": "everitoken/evtjs", "path": "src/ecc/aes.js", "func_name": "cryptoJsDecrypt", "original_string": "function cryptoJsDecrypt(message, key, iv) {\n assert(message, \"Missing cipher text\");\n message = toBinaryBuffer(message);\n const decipher = crypto.createDecipheriv(\"aes-256-cbc\", key, iv);\n // decipher.setAutoPadding(true)\n message = Buffer.concat([decipher.update(message), decipher.final()]);\n return message;\n}", "language": "javascript", "code": "function cryptoJsDecrypt(message, key, iv) {\n assert(message, \"Missing cipher text\");\n message = toBinaryBuffer(message);\n const decipher = crypto.createDecipheriv(\"aes-256-cbc\", key, iv);\n // decipher.setAutoPadding(true)\n message = Buffer.concat([decipher.update(message), decipher.final()]);\n return message;\n}", "code_tokens": ["function", "cryptoJsDecrypt", "(", "message", ",", "key", ",", "iv", ")", "{", "assert", "(", "message", ",", "\"Missing cipher text\"", ")", ";", "message", "=", "toBinaryBuffer", "(", "message", ")", ";", "const", "decipher", "=", "crypto", ".", "createDecipheriv", "(", "\"aes-256-cbc\"", ",", "key", ",", "iv", ")", ";", "message", "=", "Buffer", ".", "concat", "(", "[", "decipher", ".", "update", "(", "message", ")", ",", "decipher", ".", "final", "(", ")", "]", ")", ";", "return", "message", ";", "}"], "docstring": "This method does not use a checksum, the returned data must be validated some other way.\n\n@arg {string|Buffer} message - ciphertext binary format\n@arg {string|Buffer} key - 256bit\n@arg {string|Buffer} iv - 128bit\n\n@return {Buffer}", "docstring_tokens": ["This", "method", "does", "not", "use", "a", "checksum", "the", "returned", "data", "must", "be", "validated", "some", "other", "way", "."], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/src/ecc/aes.js#L122-L129", "partition": "test"} {"repo": "everitoken/evtjs", "path": "src/ecc/key_private.js", "func_name": "initialize", "original_string": "function initialize() {\n if(initialized) {\n return;\n }\n\n unitTest();\n keyUtils.addEntropy(...keyUtils.cpuEntropy());\n assert(keyUtils.entropyCount() >= 128, \"insufficient entropy\");\n\n initialized = true;\n}", "language": "javascript", "code": "function initialize() {\n if(initialized) {\n return;\n }\n\n unitTest();\n keyUtils.addEntropy(...keyUtils.cpuEntropy());\n assert(keyUtils.entropyCount() >= 128, \"insufficient entropy\");\n\n initialized = true;\n}", "code_tokens": ["function", "initialize", "(", ")", "{", "if", "(", "initialized", ")", "{", "return", ";", "}", "unitTest", "(", ")", ";", "keyUtils", ".", "addEntropy", "(", "...", "keyUtils", ".", "cpuEntropy", "(", ")", ")", ";", "assert", "(", "keyUtils", ".", "entropyCount", "(", ")", ">=", "128", ",", "\"insufficient entropy\"", ")", ";", "initialized", "=", "true", ";", "}"], "docstring": "Run self-checking code and gather CPU entropy.\n\nInitialization happens once even if called multiple times.\n\n@return {Promise}", "docstring_tokens": ["Run", "self", "-", "checking", "code", "and", "gather", "CPU", "entropy", "."], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/src/ecc/key_private.js#L266-L276", "partition": "test"} {"repo": "everitoken/evtjs", "path": "src/bigi/lib/bigi.js", "func_name": "montConvert", "original_string": "function montConvert(x) {\n var r = new BigInteger()\n x.abs()\n .dlShiftTo(this.m.t, r)\n r.divRemTo(this.m, null, r)\n if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r)\n return r\n}", "language": "javascript", "code": "function montConvert(x) {\n var r = new BigInteger()\n x.abs()\n .dlShiftTo(this.m.t, r)\n r.divRemTo(this.m, null, r)\n if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r)\n return r\n}", "code_tokens": ["function", "montConvert", "(", "x", ")", "{", "var", "r", "=", "new", "BigInteger", "(", ")", "x", ".", "abs", "(", ")", ".", "dlShiftTo", "(", "this", ".", "m", ".", "t", ",", "r", ")", "r", ".", "divRemTo", "(", "this", ".", "m", ",", "null", ",", "r", ")", "if", "(", "x", ".", "s", "<", "0", "&&", "r", ".", "compareTo", "(", "BigInteger", ".", "ZERO", ")", ">", "0", ")", "this", ".", "m", ".", "subTo", "(", "r", ",", "r", ")", "return", "r", "}"], "docstring": "xR mod m", "docstring_tokens": ["xR", "mod", "m"], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/src/bigi/lib/bigi.js#L545-L552", "partition": "test"} {"repo": "everitoken/evtjs", "path": "src/ecc/signature.js", "func_name": "verify", "original_string": "function verify(data, pubkey, encoding = \"utf8\") {\n if (typeof data === \"string\") {\n data = Buffer.from(data, encoding);\n }\n assert(Buffer.isBuffer(data), \"data is a required String or Buffer\");\n data = hash.sha256(data);\n return verifyHash(data, pubkey);\n }", "language": "javascript", "code": "function verify(data, pubkey, encoding = \"utf8\") {\n if (typeof data === \"string\") {\n data = Buffer.from(data, encoding);\n }\n assert(Buffer.isBuffer(data), \"data is a required String or Buffer\");\n data = hash.sha256(data);\n return verifyHash(data, pubkey);\n }", "code_tokens": ["function", "verify", "(", "data", ",", "pubkey", ",", "encoding", "=", "\"utf8\"", ")", "{", "if", "(", "typeof", "data", "===", "\"string\"", ")", "{", "data", "=", "Buffer", ".", "from", "(", "data", ",", "encoding", ")", ";", "}", "assert", "(", "Buffer", ".", "isBuffer", "(", "data", ")", ",", "\"data is a required String or Buffer\"", ")", ";", "data", "=", "hash", ".", "sha256", "(", "data", ")", ";", "return", "verifyHash", "(", "data", ",", "pubkey", ")", ";", "}"], "docstring": "Verify signed data.\n\n@arg {String|Buffer} data - full data\n@arg {pubkey|PublicKey} pubkey - EOSKey..\n@arg {String} [encoding = 'utf8'] - data encoding (if data is a string)\n\n@return {boolean}", "docstring_tokens": ["Verify", "signed", "data", "."], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/src/ecc/signature.js#L33-L40", "partition": "test"} {"repo": "everitoken/evtjs", "path": "src/ecc/signature.js", "func_name": "recover", "original_string": "function recover(data, encoding = \"utf8\") {\n if (typeof data === \"string\") {\n data = Buffer.from(data, encoding);\n }\n assert(Buffer.isBuffer(data), \"data is a required String or Buffer\");\n data = hash.sha256(data);\n\n return recoverHash(data);\n }", "language": "javascript", "code": "function recover(data, encoding = \"utf8\") {\n if (typeof data === \"string\") {\n data = Buffer.from(data, encoding);\n }\n assert(Buffer.isBuffer(data), \"data is a required String or Buffer\");\n data = hash.sha256(data);\n\n return recoverHash(data);\n }", "code_tokens": ["function", "recover", "(", "data", ",", "encoding", "=", "\"utf8\"", ")", "{", "if", "(", "typeof", "data", "===", "\"string\"", ")", "{", "data", "=", "Buffer", ".", "from", "(", "data", ",", "encoding", ")", ";", "}", "assert", "(", "Buffer", ".", "isBuffer", "(", "data", ")", ",", "\"data is a required String or Buffer\"", ")", ";", "data", "=", "hash", ".", "sha256", "(", "data", ")", ";", "return", "recoverHash", "(", "data", ")", ";", "}"], "docstring": "Recover the public key used to create this signature using full data.\n\n@arg {String|Buffer} data - full data\n@arg {String} [encoding = 'utf8'] - data encoding (if string)\n\n@return {PublicKey}", "docstring_tokens": ["Recover", "the", "public", "key", "used", "to", "create", "this", "signature", "using", "full", "data", "."], "sha": "87d5dac3ae3205e654821c03c010e4738fc4b8a1", "url": "https://github.com/everitoken/evtjs/blob/87d5dac3ae3205e654821c03c010e4738fc4b8a1/src/ecc/signature.js#L77-L85", "partition": "test"} {"repo": "zaproxy/zaproxy", "path": "src/scripts/templates/targeted/Find HTML comments.js", "func_name": "invokeWith", "original_string": "function invokeWith(msg) {\n\t// Debugging can be done using println like this\n\tprint('Finding comments in ' + msg.getRequestHeader().getURI().toString()); \n\n\tvar body = msg.getResponseBody().toString()\n\t// Look for html comments\n\tif (body.indexOf('', o);\n\t\t\tprint(\"\\t\" + body.substr(o,e-o+3)) \n\t\t\to = body.indexOf('', o);\n\t\t\tprint(\"\\t\" + body.substr(o,e-o+3)) \n\t\t\to = body.indexOf('\n`;\n\n let currentGroup = '';\n\n documentedItems.forEach(item => {\n const itemGroup = createGroupName(item.group);\n\n if (itemGroup !== currentGroup) {\n markdownFile += `\\n\\n## ${itemGroup}`;\n currentGroup = itemGroup;\n }\n\n markdownFile += createMarkdownItem(item);\n });\n\n return prettier.format(\n toc.insert(markdownFile, { slugify }),\n prettierOptions\n );\n },\n err => {\n console.error(err);\n }\n );\n}", "language": "javascript", "code": "async function createMarkdown(sourceDir, config) {\n config = config || {};\n\n return sassdoc.parse(sourceDir, config).then(\n data => {\n let markdownFile = '';\n\n const documentedItems = data.filter(\n (item, index) => item.access === 'public' || item.access === 'private'\n );\n\n markdownFile += `# Sass API\n\n| Mark | Description |\n| --- | --- |\n| \u2705 | Public functions, mixins, placeholders, and variables |\n| \u274c | Private items - not supported outside package's build |\n| \u26a0\ufe0f | Deprecated items - may not be available in future releases |\n\n\n`;\n\n let currentGroup = '';\n\n documentedItems.forEach(item => {\n const itemGroup = createGroupName(item.group);\n\n if (itemGroup !== currentGroup) {\n markdownFile += `\\n\\n## ${itemGroup}`;\n currentGroup = itemGroup;\n }\n\n markdownFile += createMarkdownItem(item);\n });\n\n return prettier.format(\n toc.insert(markdownFile, { slugify }),\n prettierOptions\n );\n },\n err => {\n console.error(err);\n }\n );\n}", "code_tokens": ["async", "function", "createMarkdown", "(", "sourceDir", ",", "config", ")", "{", "config", "=", "config", "||", "{", "}", ";", "return", "sassdoc", ".", "parse", "(", "sourceDir", ",", "config", ")", ".", "then", "(", "data", "=>", "{", "let", "markdownFile", "=", "''", ";", "const", "documentedItems", "=", "data", ".", "filter", "(", "(", "item", ",", "index", ")", "=>", "item", ".", "access", "===", "'public'", "||", "item", ".", "access", "===", "'private'", ")", ";", "markdownFile", "+=", "`", "`", ";", "let", "currentGroup", "=", "''", ";", "documentedItems", ".", "forEach", "(", "item", "=>", "{", "const", "itemGroup", "=", "createGroupName", "(", "item", ".", "group", ")", ";", "if", "(", "itemGroup", "!==", "currentGroup", ")", "{", "markdownFile", "+=", "`", "\\n", "\\n", "${", "itemGroup", "}", "`", ";", "currentGroup", "=", "itemGroup", ";", "}", "markdownFile", "+=", "createMarkdownItem", "(", "item", ")", ";", "}", ")", ";", "return", "prettier", ".", "format", "(", "toc", ".", "insert", "(", "markdownFile", ",", "{", "slugify", "}", ")", ",", "prettierOptions", ")", ";", "}", ",", "err", "=>", "{", "console", ".", "error", "(", "err", ")", ";", "}", ")", ";", "}"], "docstring": "Create a markdown file of documented Sass items\n@see {@link http://sassdoc.com/configuration/|Sassdoc configuration}\n@param {string} sourceDir - source directory\n@param {Object} config - configuration object\n@return {string} markdown", "docstring_tokens": ["Create", "a", "markdown", "file", "of", "documented", "Sass", "items"], "sha": "e5ae58647d32aaae687e811d3f61e988cab1c302", "url": "https://github.com/carbon-design-system/carbon-components/blob/e5ae58647d32aaae687e811d3f61e988cab1c302/packages/bundler/src/tools/sassdoc.js#L347-L391", "partition": "test"} {"repo": "carbon-design-system/carbon-components", "path": "packages/components/src/components/date-picker/date-picker.js", "func_name": "flattenOptions", "original_string": "function flattenOptions(options) {\n const o = {};\n // eslint-disable-next-line guard-for-in, no-restricted-syntax\n for (const key in options) {\n o[key] = options[key];\n }\n return o;\n}", "language": "javascript", "code": "function flattenOptions(options) {\n const o = {};\n // eslint-disable-next-line guard-for-in, no-restricted-syntax\n for (const key in options) {\n o[key] = options[key];\n }\n return o;\n}", "code_tokens": ["function", "flattenOptions", "(", "options", ")", "{", "const", "o", "=", "{", "}", ";", "for", "(", "const", "key", "in", "options", ")", "{", "o", "[", "key", "]", "=", "options", "[", "key", "]", ";", "}", "return", "o", ";", "}"], "docstring": "`this.options` create-component mix-in creates prototype chain so that `options` given in constructor argument wins over the one defined in static `options` property 'Flatpickr' wants flat structure of object instead", "docstring_tokens": ["this", ".", "options", "create", "-", "component", "mix", "-", "in", "creates", "prototype", "chain", "so", "that", "options", "given", "in", "constructor", "argument", "wins", "over", "the", "one", "defined", "in", "static", "options", "property", "Flatpickr", "wants", "flat", "structure", "of", "object", "instead"], "sha": "e5ae58647d32aaae687e811d3f61e988cab1c302", "url": "https://github.com/carbon-design-system/carbon-components/blob/e5ae58647d32aaae687e811d3f61e988cab1c302/packages/components/src/components/date-picker/date-picker.js#L22-L29", "partition": "test"} {"repo": "barbajs/barba", "path": "packages/core/__web__/scripts/transitions/hooks.js", "func_name": "append", "original_string": "function append(str, prefix = '') {\n const item = document.createElement('li');\n\n item.textContent = prefix + str;\n list.appendChild(item);\n}", "language": "javascript", "code": "function append(str, prefix = '') {\n const item = document.createElement('li');\n\n item.textContent = prefix + str;\n list.appendChild(item);\n}", "code_tokens": ["function", "append", "(", "str", ",", "prefix", "=", "''", ")", "{", "const", "item", "=", "document", ".", "createElement", "(", "'li'", ")", ";", "item", ".", "textContent", "=", "prefix", "+", "str", ";", "list", ".", "appendChild", "(", "item", ")", ";", "}"], "docstring": "Append list item\n\n@param {*} str List item content\n@param {string} prefix Prefix for global\n@returns {void}", "docstring_tokens": ["Append", "list", "item"], "sha": "f450491297648a684e0f50d8335384340d8b5254", "url": "https://github.com/barbajs/barba/blob/f450491297648a684e0f50d8335384340d8b5254/packages/core/__web__/scripts/transitions/hooks.js#L12-L17", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/libpannellum.js", "func_name": "multiresNodeSort", "original_string": "function multiresNodeSort(a, b) {\n // Base tiles are always first\n if (a.level == 1 && b.level != 1) {\n return -1;\n }\n if (b. level == 1 && a.level != 1) {\n return 1;\n }\n \n // Higher timestamp first\n return b.timestamp - a.timestamp;\n }", "language": "javascript", "code": "function multiresNodeSort(a, b) {\n // Base tiles are always first\n if (a.level == 1 && b.level != 1) {\n return -1;\n }\n if (b. level == 1 && a.level != 1) {\n return 1;\n }\n \n // Higher timestamp first\n return b.timestamp - a.timestamp;\n }", "code_tokens": ["function", "multiresNodeSort", "(", "a", ",", "b", ")", "{", "if", "(", "a", ".", "level", "==", "1", "&&", "b", ".", "level", "!=", "1", ")", "{", "return", "-", "1", ";", "}", "if", "(", "b", ".", "level", "==", "1", "&&", "a", ".", "level", "!=", "1", ")", "{", "return", "1", ";", "}", "return", "b", ".", "timestamp", "-", "a", ".", "timestamp", ";", "}"], "docstring": "Sorting method for multires nodes.\n@private\n@param {MultiresNode} a - First node.\n@param {MultiresNode} b - Second node.\n@returns {number} Base tiles first, then higher timestamp first.", "docstring_tokens": ["Sorting", "method", "for", "multires", "nodes", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/libpannellum.js#L779-L790", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/libpannellum.js", "func_name": "multiresNodeRenderSort", "original_string": "function multiresNodeRenderSort(a, b) {\n // Lower zoom levels first\n if (a.level != b.level) {\n return a.level - b.level;\n }\n \n // Lower distance from center first\n return a.diff - b.diff;\n }", "language": "javascript", "code": "function multiresNodeRenderSort(a, b) {\n // Lower zoom levels first\n if (a.level != b.level) {\n return a.level - b.level;\n }\n \n // Lower distance from center first\n return a.diff - b.diff;\n }", "code_tokens": ["function", "multiresNodeRenderSort", "(", "a", ",", "b", ")", "{", "if", "(", "a", ".", "level", "!=", "b", ".", "level", ")", "{", "return", "a", ".", "level", "-", "b", ".", "level", ";", "}", "return", "a", ".", "diff", "-", "b", ".", "diff", ";", "}"], "docstring": "Sorting method for multires node rendering.\n@private\n@param {MultiresNode} a - First node.\n@param {MultiresNode} b - Second node.\n@returns {number} Lower zoom levels first, then closest to center first.", "docstring_tokens": ["Sorting", "method", "for", "multires", "node", "rendering", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/libpannellum.js#L799-L807", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/libpannellum.js", "func_name": "multiresDraw", "original_string": "function multiresDraw() {\n if (!program.drawInProgress) {\n program.drawInProgress = true;\n gl.clear(gl.COLOR_BUFFER_BIT);\n for ( var i = 0; i < program.currentNodes.length; i++ ) {\n if (program.currentNodes[i].textureLoaded > 1) {\n //var color = program.currentNodes[i].color;\n //gl.uniform4f(program.colorUniform, color[0], color[1], color[2], 1.0);\n \n // Bind vertex buffer and pass vertices to WebGL\n gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertBuf);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(program.currentNodes[i].vertices), gl.STATIC_DRAW);\n gl.vertexAttribPointer(program.vertPosLocation, 3, gl.FLOAT, false, 0, 0);\n \n // Prep for texture\n gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertTexCoordBuf);\n gl.vertexAttribPointer(program.texCoordLocation, 2, gl.FLOAT, false, 0, 0);\n \n // Bind texture and draw tile\n gl.bindTexture(gl.TEXTURE_2D, program.currentNodes[i].texture); // Bind program.currentNodes[i].texture to TEXTURE0\n gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);\n }\n }\n program.drawInProgress = false;\n }\n }", "language": "javascript", "code": "function multiresDraw() {\n if (!program.drawInProgress) {\n program.drawInProgress = true;\n gl.clear(gl.COLOR_BUFFER_BIT);\n for ( var i = 0; i < program.currentNodes.length; i++ ) {\n if (program.currentNodes[i].textureLoaded > 1) {\n //var color = program.currentNodes[i].color;\n //gl.uniform4f(program.colorUniform, color[0], color[1], color[2], 1.0);\n \n // Bind vertex buffer and pass vertices to WebGL\n gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertBuf);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(program.currentNodes[i].vertices), gl.STATIC_DRAW);\n gl.vertexAttribPointer(program.vertPosLocation, 3, gl.FLOAT, false, 0, 0);\n \n // Prep for texture\n gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertTexCoordBuf);\n gl.vertexAttribPointer(program.texCoordLocation, 2, gl.FLOAT, false, 0, 0);\n \n // Bind texture and draw tile\n gl.bindTexture(gl.TEXTURE_2D, program.currentNodes[i].texture); // Bind program.currentNodes[i].texture to TEXTURE0\n gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);\n }\n }\n program.drawInProgress = false;\n }\n }", "code_tokens": ["function", "multiresDraw", "(", ")", "{", "if", "(", "!", "program", ".", "drawInProgress", ")", "{", "program", ".", "drawInProgress", "=", "true", ";", "gl", ".", "clear", "(", "gl", ".", "COLOR_BUFFER_BIT", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "program", ".", "currentNodes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "program", ".", "currentNodes", "[", "i", "]", ".", "textureLoaded", ">", "1", ")", "{", "gl", ".", "bindBuffer", "(", "gl", ".", "ARRAY_BUFFER", ",", "cubeVertBuf", ")", ";", "gl", ".", "bufferData", "(", "gl", ".", "ARRAY_BUFFER", ",", "new", "Float32Array", "(", "program", ".", "currentNodes", "[", "i", "]", ".", "vertices", ")", ",", "gl", ".", "STATIC_DRAW", ")", ";", "gl", ".", "vertexAttribPointer", "(", "program", ".", "vertPosLocation", ",", "3", ",", "gl", ".", "FLOAT", ",", "false", ",", "0", ",", "0", ")", ";", "gl", ".", "bindBuffer", "(", "gl", ".", "ARRAY_BUFFER", ",", "cubeVertTexCoordBuf", ")", ";", "gl", ".", "vertexAttribPointer", "(", "program", ".", "texCoordLocation", ",", "2", ",", "gl", ".", "FLOAT", ",", "false", ",", "0", ",", "0", ")", ";", "gl", ".", "bindTexture", "(", "gl", ".", "TEXTURE_2D", ",", "program", ".", "currentNodes", "[", "i", "]", ".", "texture", ")", ";", "gl", ".", "drawElements", "(", "gl", ".", "TRIANGLES", ",", "6", ",", "gl", ".", "UNSIGNED_SHORT", ",", "0", ")", ";", "}", "}", "program", ".", "drawInProgress", "=", "false", ";", "}", "}"], "docstring": "Draws multires nodes.\n@private", "docstring_tokens": ["Draws", "multires", "nodes", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/libpannellum.js#L813-L838", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/libpannellum.js", "func_name": "MultiresNode", "original_string": "function MultiresNode(vertices, side, level, x, y, path) {\n this.vertices = vertices;\n this.side = side;\n this.level = level;\n this.x = x;\n this.y = y;\n this.path = path.replace('%s',side).replace('%l',level).replace('%x',x).replace('%y',y);\n }", "language": "javascript", "code": "function MultiresNode(vertices, side, level, x, y, path) {\n this.vertices = vertices;\n this.side = side;\n this.level = level;\n this.x = x;\n this.y = y;\n this.path = path.replace('%s',side).replace('%l',level).replace('%x',x).replace('%y',y);\n }", "code_tokens": ["function", "MultiresNode", "(", "vertices", ",", "side", ",", "level", ",", "x", ",", "y", ",", "path", ")", "{", "this", ".", "vertices", "=", "vertices", ";", "this", ".", "side", "=", "side", ";", "this", ".", "level", "=", "level", ";", "this", ".", "x", "=", "x", ";", "this", ".", "y", "=", "y", ";", "this", ".", "path", "=", "path", ".", "replace", "(", "'%s'", ",", "side", ")", ".", "replace", "(", "'%l'", ",", "level", ")", ".", "replace", "(", "'%x'", ",", "x", ")", ".", "replace", "(", "'%y'", ",", "y", ")", ";", "}"], "docstring": "Creates new multires node.\n@constructor\n@private\n@param {number[]} vertices - Node's verticies.\n@param {string} side - Node's cube face.\n@param {number} level - Node's zoom level.\n@param {number} x - Node's x position.\n@param {number} y - Node's y position.\n@param {string} path - Node's path.", "docstring_tokens": ["Creates", "new", "multires", "node", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/libpannellum.js#L851-L858", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/libpannellum.js", "func_name": "rotateMatrix", "original_string": "function rotateMatrix(m, angle, axis) {\n var s = Math.sin(angle);\n var c = Math.cos(angle);\n if (axis == 'x') {\n return [\n m[0], c*m[1] + s*m[2], c*m[2] - s*m[1],\n m[3], c*m[4] + s*m[5], c*m[5] - s*m[4],\n m[6], c*m[7] + s*m[8], c*m[8] - s*m[7]\n ];\n }\n if (axis == 'y') {\n return [\n c*m[0] - s*m[2], m[1], c*m[2] + s*m[0],\n c*m[3] - s*m[5], m[4], c*m[5] + s*m[3],\n c*m[6] - s*m[8], m[7], c*m[8] + s*m[6]\n ];\n }\n if (axis == 'z') {\n return [\n c*m[0] + s*m[1], c*m[1] - s*m[0], m[2],\n c*m[3] + s*m[4], c*m[4] - s*m[3], m[5],\n c*m[6] + s*m[7], c*m[7] - s*m[6], m[8]\n ];\n }\n }", "language": "javascript", "code": "function rotateMatrix(m, angle, axis) {\n var s = Math.sin(angle);\n var c = Math.cos(angle);\n if (axis == 'x') {\n return [\n m[0], c*m[1] + s*m[2], c*m[2] - s*m[1],\n m[3], c*m[4] + s*m[5], c*m[5] - s*m[4],\n m[6], c*m[7] + s*m[8], c*m[8] - s*m[7]\n ];\n }\n if (axis == 'y') {\n return [\n c*m[0] - s*m[2], m[1], c*m[2] + s*m[0],\n c*m[3] - s*m[5], m[4], c*m[5] + s*m[3],\n c*m[6] - s*m[8], m[7], c*m[8] + s*m[6]\n ];\n }\n if (axis == 'z') {\n return [\n c*m[0] + s*m[1], c*m[1] - s*m[0], m[2],\n c*m[3] + s*m[4], c*m[4] - s*m[3], m[5],\n c*m[6] + s*m[7], c*m[7] - s*m[6], m[8]\n ];\n }\n }", "code_tokens": ["function", "rotateMatrix", "(", "m", ",", "angle", ",", "axis", ")", "{", "var", "s", "=", "Math", ".", "sin", "(", "angle", ")", ";", "var", "c", "=", "Math", ".", "cos", "(", "angle", ")", ";", "if", "(", "axis", "==", "'x'", ")", "{", "return", "[", "m", "[", "0", "]", ",", "c", "*", "m", "[", "1", "]", "+", "s", "*", "m", "[", "2", "]", ",", "c", "*", "m", "[", "2", "]", "-", "s", "*", "m", "[", "1", "]", ",", "m", "[", "3", "]", ",", "c", "*", "m", "[", "4", "]", "+", "s", "*", "m", "[", "5", "]", ",", "c", "*", "m", "[", "5", "]", "-", "s", "*", "m", "[", "4", "]", ",", "m", "[", "6", "]", ",", "c", "*", "m", "[", "7", "]", "+", "s", "*", "m", "[", "8", "]", ",", "c", "*", "m", "[", "8", "]", "-", "s", "*", "m", "[", "7", "]", "]", ";", "}", "if", "(", "axis", "==", "'y'", ")", "{", "return", "[", "c", "*", "m", "[", "0", "]", "-", "s", "*", "m", "[", "2", "]", ",", "m", "[", "1", "]", ",", "c", "*", "m", "[", "2", "]", "+", "s", "*", "m", "[", "0", "]", ",", "c", "*", "m", "[", "3", "]", "-", "s", "*", "m", "[", "5", "]", ",", "m", "[", "4", "]", ",", "c", "*", "m", "[", "5", "]", "+", "s", "*", "m", "[", "3", "]", ",", "c", "*", "m", "[", "6", "]", "-", "s", "*", "m", "[", "8", "]", ",", "m", "[", "7", "]", ",", "c", "*", "m", "[", "8", "]", "+", "s", "*", "m", "[", "6", "]", "]", ";", "}", "if", "(", "axis", "==", "'z'", ")", "{", "return", "[", "c", "*", "m", "[", "0", "]", "+", "s", "*", "m", "[", "1", "]", ",", "c", "*", "m", "[", "1", "]", "-", "s", "*", "m", "[", "0", "]", ",", "m", "[", "2", "]", ",", "c", "*", "m", "[", "3", "]", "+", "s", "*", "m", "[", "4", "]", ",", "c", "*", "m", "[", "4", "]", "-", "s", "*", "m", "[", "3", "]", ",", "m", "[", "5", "]", ",", "c", "*", "m", "[", "6", "]", "+", "s", "*", "m", "[", "7", "]", ",", "c", "*", "m", "[", "7", "]", "-", "s", "*", "m", "[", "6", "]", ",", "m", "[", "8", "]", "]", ";", "}", "}"], "docstring": "Rotates a 3x3 matrix.\n@private\n@param {number[]} m - Matrix to rotate.\n@param {number[]} angle - Angle to rotate by in radians.\n@param {string} axis - Axis to rotate about (`x`, `y`, or `z`).\n@returns {number[]} Rotated matrix.", "docstring_tokens": ["Rotates", "a", "3x3", "matrix", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/libpannellum.js#L1040-L1064", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/libpannellum.js", "func_name": "makeMatrix4", "original_string": "function makeMatrix4(m) {\n return [\n m[0], m[1], m[2], 0,\n m[3], m[4], m[5], 0,\n m[6], m[7], m[8], 0,\n 0, 0, 0, 1\n ];\n }", "language": "javascript", "code": "function makeMatrix4(m) {\n return [\n m[0], m[1], m[2], 0,\n m[3], m[4], m[5], 0,\n m[6], m[7], m[8], 0,\n 0, 0, 0, 1\n ];\n }", "code_tokens": ["function", "makeMatrix4", "(", "m", ")", "{", "return", "[", "m", "[", "0", "]", ",", "m", "[", "1", "]", ",", "m", "[", "2", "]", ",", "0", ",", "m", "[", "3", "]", ",", "m", "[", "4", "]", ",", "m", "[", "5", "]", ",", "0", ",", "m", "[", "6", "]", ",", "m", "[", "7", "]", ",", "m", "[", "8", "]", ",", "0", ",", "0", ",", "0", ",", "0", ",", "1", "]", ";", "}"], "docstring": "Turns a 3x3 matrix into a 4x4 matrix.\n@private\n@param {number[]} m - Input matrix.\n@returns {number[]} Expanded matrix.", "docstring_tokens": ["Turns", "a", "3x3", "matrix", "into", "a", "4x4", "matrix", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/libpannellum.js#L1072-L1079", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/libpannellum.js", "func_name": "makePersp", "original_string": "function makePersp(hfov, aspect, znear, zfar) {\n var fovy = 2 * Math.atan(Math.tan(hfov/2) * gl.drawingBufferHeight / gl.drawingBufferWidth);\n var f = 1 / Math.tan(fovy/2);\n return [\n f/aspect, 0, 0, 0,\n 0, f, 0, 0,\n 0, 0, (zfar+znear)/(znear-zfar), (2*zfar*znear)/(znear-zfar),\n 0, 0, -1, 0\n ];\n }", "language": "javascript", "code": "function makePersp(hfov, aspect, znear, zfar) {\n var fovy = 2 * Math.atan(Math.tan(hfov/2) * gl.drawingBufferHeight / gl.drawingBufferWidth);\n var f = 1 / Math.tan(fovy/2);\n return [\n f/aspect, 0, 0, 0,\n 0, f, 0, 0,\n 0, 0, (zfar+znear)/(znear-zfar), (2*zfar*znear)/(znear-zfar),\n 0, 0, -1, 0\n ];\n }", "code_tokens": ["function", "makePersp", "(", "hfov", ",", "aspect", ",", "znear", ",", "zfar", ")", "{", "var", "fovy", "=", "2", "*", "Math", ".", "atan", "(", "Math", ".", "tan", "(", "hfov", "/", "2", ")", "*", "gl", ".", "drawingBufferHeight", "/", "gl", ".", "drawingBufferWidth", ")", ";", "var", "f", "=", "1", "/", "Math", ".", "tan", "(", "fovy", "/", "2", ")", ";", "return", "[", "f", "/", "aspect", ",", "0", ",", "0", ",", "0", ",", "0", ",", "f", ",", "0", ",", "0", ",", "0", ",", "0", ",", "(", "zfar", "+", "znear", ")", "/", "(", "znear", "-", "zfar", ")", ",", "(", "2", "*", "zfar", "*", "znear", ")", "/", "(", "znear", "-", "zfar", ")", ",", "0", ",", "0", ",", "-", "1", ",", "0", "]", ";", "}"], "docstring": "Creates a perspective matrix.\n@private\n@param {number} hfov - Desired horizontal field of view.\n@param {number} aspect - Desired aspect ratio.\n@param {number} znear - Near distance.\n@param {number} zfar - Far distance.\n@returns {number[]} Generated perspective matrix.", "docstring_tokens": ["Creates", "a", "perspective", "matrix", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/libpannellum.js#L1105-L1114", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/libpannellum.js", "func_name": "processLoadedTexture", "original_string": "function processLoadedTexture(img, tex) {\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, img);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.bindTexture(gl.TEXTURE_2D, null);\n }", "language": "javascript", "code": "function processLoadedTexture(img, tex) {\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, img);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.bindTexture(gl.TEXTURE_2D, null);\n }", "code_tokens": ["function", "processLoadedTexture", "(", "img", ",", "tex", ")", "{", "gl", ".", "bindTexture", "(", "gl", ".", "TEXTURE_2D", ",", "tex", ")", ";", "gl", ".", "texImage2D", "(", "gl", ".", "TEXTURE_2D", ",", "0", ",", "gl", ".", "RGB", ",", "gl", ".", "RGB", ",", "gl", ".", "UNSIGNED_BYTE", ",", "img", ")", ";", "gl", ".", "texParameteri", "(", "gl", ".", "TEXTURE_2D", ",", "gl", ".", "TEXTURE_MAG_FILTER", ",", "gl", ".", "LINEAR", ")", ";", "gl", ".", "texParameteri", "(", "gl", ".", "TEXTURE_2D", ",", "gl", ".", "TEXTURE_MIN_FILTER", ",", "gl", ".", "LINEAR", ")", ";", "gl", ".", "texParameteri", "(", "gl", ".", "TEXTURE_2D", ",", "gl", ".", "TEXTURE_WRAP_S", ",", "gl", ".", "CLAMP_TO_EDGE", ")", ";", "gl", ".", "texParameteri", "(", "gl", ".", "TEXTURE_2D", ",", "gl", ".", "TEXTURE_WRAP_T", ",", "gl", ".", "CLAMP_TO_EDGE", ")", ";", "gl", ".", "bindTexture", "(", "gl", ".", "TEXTURE_2D", ",", "null", ")", ";", "}"], "docstring": "Processes a loaded texture image into a WebGL texture.\n@private\n@param {Image} img - Input image.\n@param {WebGLTexture} tex - Texture to bind image to.", "docstring_tokens": ["Processes", "a", "loaded", "texture", "image", "into", "a", "WebGL", "texture", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/libpannellum.js#L1122-L1130", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/libpannellum.js", "func_name": "checkZoom", "original_string": "function checkZoom(hfov) {\n // Find optimal level\n var newLevel = 1;\n while ( newLevel < image.maxLevel &&\n gl.drawingBufferWidth > image.tileResolution *\n Math.pow(2, newLevel - 1) * Math.tan(hfov / 2) * 0.707 ) {\n newLevel++;\n }\n \n // Apply change\n program.level = newLevel;\n }", "language": "javascript", "code": "function checkZoom(hfov) {\n // Find optimal level\n var newLevel = 1;\n while ( newLevel < image.maxLevel &&\n gl.drawingBufferWidth > image.tileResolution *\n Math.pow(2, newLevel - 1) * Math.tan(hfov / 2) * 0.707 ) {\n newLevel++;\n }\n \n // Apply change\n program.level = newLevel;\n }", "code_tokens": ["function", "checkZoom", "(", "hfov", ")", "{", "var", "newLevel", "=", "1", ";", "while", "(", "newLevel", "<", "image", ".", "maxLevel", "&&", "gl", ".", "drawingBufferWidth", ">", "image", ".", "tileResolution", "*", "Math", ".", "pow", "(", "2", ",", "newLevel", "-", "1", ")", "*", "Math", ".", "tan", "(", "hfov", "/", "2", ")", "*", "0.707", ")", "{", "newLevel", "++", ";", "}", "program", ".", "level", "=", "newLevel", ";", "}"], "docstring": "Finds and applies optimal multires zoom level.\n@private\n@param {number} hfov - Horizontal field of view to check at.", "docstring_tokens": ["Finds", "and", "applies", "optimal", "multires", "zoom", "level", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/libpannellum.js#L1210-L1221", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/libpannellum.js", "func_name": "rotatePersp", "original_string": "function rotatePersp(p, r) {\n return [\n p[ 0]*r[0], p[ 0]*r[1], p[ 0]*r[ 2], 0,\n p[ 5]*r[4], p[ 5]*r[5], p[ 5]*r[ 6], 0,\n p[10]*r[8], p[10]*r[9], p[10]*r[10], p[11],\n -r[8], -r[9], -r[10], 0\n ];\n }", "language": "javascript", "code": "function rotatePersp(p, r) {\n return [\n p[ 0]*r[0], p[ 0]*r[1], p[ 0]*r[ 2], 0,\n p[ 5]*r[4], p[ 5]*r[5], p[ 5]*r[ 6], 0,\n p[10]*r[8], p[10]*r[9], p[10]*r[10], p[11],\n -r[8], -r[9], -r[10], 0\n ];\n }", "code_tokens": ["function", "rotatePersp", "(", "p", ",", "r", ")", "{", "return", "[", "p", "[", "0", "]", "*", "r", "[", "0", "]", ",", "p", "[", "0", "]", "*", "r", "[", "1", "]", ",", "p", "[", "0", "]", "*", "r", "[", "2", "]", ",", "0", ",", "p", "[", "5", "]", "*", "r", "[", "4", "]", ",", "p", "[", "5", "]", "*", "r", "[", "5", "]", ",", "p", "[", "5", "]", "*", "r", "[", "6", "]", ",", "0", ",", "p", "[", "10", "]", "*", "r", "[", "8", "]", ",", "p", "[", "10", "]", "*", "r", "[", "9", "]", ",", "p", "[", "10", "]", "*", "r", "[", "10", "]", ",", "p", "[", "11", "]", ",", "-", "r", "[", "8", "]", ",", "-", "r", "[", "9", "]", ",", "-", "r", "[", "10", "]", ",", "0", "]", ";", "}"], "docstring": "Rotates perspective matrix.\n@private\n@param {number[]} p - Perspective matrix.\n@param {number[]} r - Rotation matrix.\n@returns {number[]} Rotated matrix.", "docstring_tokens": ["Rotates", "perspective", "matrix", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/libpannellum.js#L1230-L1237", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/libpannellum.js", "func_name": "checkInView", "original_string": "function checkInView(m, v) {\n var vpp = applyRotPerspToVec(m, v);\n var winX = vpp[0]*vpp[3];\n var winY = vpp[1]*vpp[3];\n var winZ = vpp[2]*vpp[3];\n var ret = [0, 0, 0];\n \n if ( winX < -1 )\n ret[0] = -1;\n if ( winX > 1 )\n ret[0] = 1;\n if ( winY < -1 )\n ret[1] = -1;\n if ( winY > 1 )\n ret[1] = 1;\n if ( winZ < -1 || winZ > 1 )\n ret[2] = 1;\n return ret;\n }", "language": "javascript", "code": "function checkInView(m, v) {\n var vpp = applyRotPerspToVec(m, v);\n var winX = vpp[0]*vpp[3];\n var winY = vpp[1]*vpp[3];\n var winZ = vpp[2]*vpp[3];\n var ret = [0, 0, 0];\n \n if ( winX < -1 )\n ret[0] = -1;\n if ( winX > 1 )\n ret[0] = 1;\n if ( winY < -1 )\n ret[1] = -1;\n if ( winY > 1 )\n ret[1] = 1;\n if ( winZ < -1 || winZ > 1 )\n ret[2] = 1;\n return ret;\n }", "code_tokens": ["function", "checkInView", "(", "m", ",", "v", ")", "{", "var", "vpp", "=", "applyRotPerspToVec", "(", "m", ",", "v", ")", ";", "var", "winX", "=", "vpp", "[", "0", "]", "*", "vpp", "[", "3", "]", ";", "var", "winY", "=", "vpp", "[", "1", "]", "*", "vpp", "[", "3", "]", ";", "var", "winZ", "=", "vpp", "[", "2", "]", "*", "vpp", "[", "3", "]", ";", "var", "ret", "=", "[", "0", ",", "0", ",", "0", "]", ";", "if", "(", "winX", "<", "-", "1", ")", "ret", "[", "0", "]", "=", "-", "1", ";", "if", "(", "winX", ">", "1", ")", "ret", "[", "0", "]", "=", "1", ";", "if", "(", "winY", "<", "-", "1", ")", "ret", "[", "1", "]", "=", "-", "1", ";", "if", "(", "winY", ">", "1", ")", "ret", "[", "1", "]", "=", "1", ";", "if", "(", "winZ", "<", "-", "1", "||", "winZ", ">", "1", ")", "ret", "[", "2", "]", "=", "1", ";", "return", "ret", ";", "}"], "docstring": "Checks if a vertex is visible.\n@private\n@param {number[]} m - Rotated perspective matrix.\n@param {number[]} v - Input vertex.\n@returns {number} 1 or -1 if the vertex is or is not visible,\nrespectively.", "docstring_tokens": ["Checks", "if", "a", "vertex", "is", "visible", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/libpannellum.js#L1264-L1282", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "onImageLoad", "original_string": "function onImageLoad() {\n if (!renderer)\n renderer = new libpannellum.renderer(renderContainer);\n\n // Only add event listeners once\n if (!listenersAdded) {\n listenersAdded = true;\n dragFix.addEventListener('mousedown', onDocumentMouseDown, false);\n document.addEventListener('mousemove', onDocumentMouseMove, false);\n document.addEventListener('mouseup', onDocumentMouseUp, false);\n if (config.mouseZoom) {\n uiContainer.addEventListener('mousewheel', onDocumentMouseWheel, false);\n uiContainer.addEventListener('DOMMouseScroll', onDocumentMouseWheel, false);\n }\n if (config.doubleClickZoom) {\n dragFix.addEventListener('dblclick', onDocumentDoubleClick, false);\n }\n container.addEventListener('mozfullscreenchange', onFullScreenChange, false);\n container.addEventListener('webkitfullscreenchange', onFullScreenChange, false);\n container.addEventListener('msfullscreenchange', onFullScreenChange, false);\n container.addEventListener('fullscreenchange', onFullScreenChange, false);\n window.addEventListener('resize', onDocumentResize, false);\n window.addEventListener('orientationchange', onDocumentResize, false);\n if (!config.disableKeyboardCtrl) {\n container.addEventListener('keydown', onDocumentKeyPress, false);\n container.addEventListener('keyup', onDocumentKeyUp, false);\n container.addEventListener('blur', clearKeys, false);\n }\n document.addEventListener('mouseleave', onDocumentMouseUp, false);\n if (document.documentElement.style.pointerAction === '' &&\n document.documentElement.style.touchAction === '') {\n dragFix.addEventListener('pointerdown', onDocumentPointerDown, false);\n dragFix.addEventListener('pointermove', onDocumentPointerMove, false);\n dragFix.addEventListener('pointerup', onDocumentPointerUp, false);\n dragFix.addEventListener('pointerleave', onDocumentPointerUp, false);\n } else {\n dragFix.addEventListener('touchstart', onDocumentTouchStart, false);\n dragFix.addEventListener('touchmove', onDocumentTouchMove, false);\n dragFix.addEventListener('touchend', onDocumentTouchEnd, false);\n }\n\n // Deal with MS pointer events\n if (window.navigator.pointerEnabled)\n container.style.touchAction = 'none';\n }\n\n renderInit();\n setHfov(config.hfov); // possibly adapt hfov after configuration and canvas is complete; prevents empty space on top or bottom by zomming out too much\n setTimeout(function(){isTimedOut = true;}, 500);\n}", "language": "javascript", "code": "function onImageLoad() {\n if (!renderer)\n renderer = new libpannellum.renderer(renderContainer);\n\n // Only add event listeners once\n if (!listenersAdded) {\n listenersAdded = true;\n dragFix.addEventListener('mousedown', onDocumentMouseDown, false);\n document.addEventListener('mousemove', onDocumentMouseMove, false);\n document.addEventListener('mouseup', onDocumentMouseUp, false);\n if (config.mouseZoom) {\n uiContainer.addEventListener('mousewheel', onDocumentMouseWheel, false);\n uiContainer.addEventListener('DOMMouseScroll', onDocumentMouseWheel, false);\n }\n if (config.doubleClickZoom) {\n dragFix.addEventListener('dblclick', onDocumentDoubleClick, false);\n }\n container.addEventListener('mozfullscreenchange', onFullScreenChange, false);\n container.addEventListener('webkitfullscreenchange', onFullScreenChange, false);\n container.addEventListener('msfullscreenchange', onFullScreenChange, false);\n container.addEventListener('fullscreenchange', onFullScreenChange, false);\n window.addEventListener('resize', onDocumentResize, false);\n window.addEventListener('orientationchange', onDocumentResize, false);\n if (!config.disableKeyboardCtrl) {\n container.addEventListener('keydown', onDocumentKeyPress, false);\n container.addEventListener('keyup', onDocumentKeyUp, false);\n container.addEventListener('blur', clearKeys, false);\n }\n document.addEventListener('mouseleave', onDocumentMouseUp, false);\n if (document.documentElement.style.pointerAction === '' &&\n document.documentElement.style.touchAction === '') {\n dragFix.addEventListener('pointerdown', onDocumentPointerDown, false);\n dragFix.addEventListener('pointermove', onDocumentPointerMove, false);\n dragFix.addEventListener('pointerup', onDocumentPointerUp, false);\n dragFix.addEventListener('pointerleave', onDocumentPointerUp, false);\n } else {\n dragFix.addEventListener('touchstart', onDocumentTouchStart, false);\n dragFix.addEventListener('touchmove', onDocumentTouchMove, false);\n dragFix.addEventListener('touchend', onDocumentTouchEnd, false);\n }\n\n // Deal with MS pointer events\n if (window.navigator.pointerEnabled)\n container.style.touchAction = 'none';\n }\n\n renderInit();\n setHfov(config.hfov); // possibly adapt hfov after configuration and canvas is complete; prevents empty space on top or bottom by zomming out too much\n setTimeout(function(){isTimedOut = true;}, 500);\n}", "code_tokens": ["function", "onImageLoad", "(", ")", "{", "if", "(", "!", "renderer", ")", "renderer", "=", "new", "libpannellum", ".", "renderer", "(", "renderContainer", ")", ";", "if", "(", "!", "listenersAdded", ")", "{", "listenersAdded", "=", "true", ";", "dragFix", ".", "addEventListener", "(", "'mousedown'", ",", "onDocumentMouseDown", ",", "false", ")", ";", "document", ".", "addEventListener", "(", "'mousemove'", ",", "onDocumentMouseMove", ",", "false", ")", ";", "document", ".", "addEventListener", "(", "'mouseup'", ",", "onDocumentMouseUp", ",", "false", ")", ";", "if", "(", "config", ".", "mouseZoom", ")", "{", "uiContainer", ".", "addEventListener", "(", "'mousewheel'", ",", "onDocumentMouseWheel", ",", "false", ")", ";", "uiContainer", ".", "addEventListener", "(", "'DOMMouseScroll'", ",", "onDocumentMouseWheel", ",", "false", ")", ";", "}", "if", "(", "config", ".", "doubleClickZoom", ")", "{", "dragFix", ".", "addEventListener", "(", "'dblclick'", ",", "onDocumentDoubleClick", ",", "false", ")", ";", "}", "container", ".", "addEventListener", "(", "'mozfullscreenchange'", ",", "onFullScreenChange", ",", "false", ")", ";", "container", ".", "addEventListener", "(", "'webkitfullscreenchange'", ",", "onFullScreenChange", ",", "false", ")", ";", "container", ".", "addEventListener", "(", "'msfullscreenchange'", ",", "onFullScreenChange", ",", "false", ")", ";", "container", ".", "addEventListener", "(", "'fullscreenchange'", ",", "onFullScreenChange", ",", "false", ")", ";", "window", ".", "addEventListener", "(", "'resize'", ",", "onDocumentResize", ",", "false", ")", ";", "window", ".", "addEventListener", "(", "'orientationchange'", ",", "onDocumentResize", ",", "false", ")", ";", "if", "(", "!", "config", ".", "disableKeyboardCtrl", ")", "{", "container", ".", "addEventListener", "(", "'keydown'", ",", "onDocumentKeyPress", ",", "false", ")", ";", "container", ".", "addEventListener", "(", "'keyup'", ",", "onDocumentKeyUp", ",", "false", ")", ";", "container", ".", "addEventListener", "(", "'blur'", ",", "clearKeys", ",", "false", ")", ";", "}", "document", ".", "addEventListener", "(", "'mouseleave'", ",", "onDocumentMouseUp", ",", "false", ")", ";", "if", "(", "document", ".", "documentElement", ".", "style", ".", "pointerAction", "===", "''", "&&", "document", ".", "documentElement", ".", "style", ".", "touchAction", "===", "''", ")", "{", "dragFix", ".", "addEventListener", "(", "'pointerdown'", ",", "onDocumentPointerDown", ",", "false", ")", ";", "dragFix", ".", "addEventListener", "(", "'pointermove'", ",", "onDocumentPointerMove", ",", "false", ")", ";", "dragFix", ".", "addEventListener", "(", "'pointerup'", ",", "onDocumentPointerUp", ",", "false", ")", ";", "dragFix", ".", "addEventListener", "(", "'pointerleave'", ",", "onDocumentPointerUp", ",", "false", ")", ";", "}", "else", "{", "dragFix", ".", "addEventListener", "(", "'touchstart'", ",", "onDocumentTouchStart", ",", "false", ")", ";", "dragFix", ".", "addEventListener", "(", "'touchmove'", ",", "onDocumentTouchMove", ",", "false", ")", ";", "dragFix", ".", "addEventListener", "(", "'touchend'", ",", "onDocumentTouchEnd", ",", "false", ")", ";", "}", "if", "(", "window", ".", "navigator", ".", "pointerEnabled", ")", "container", ".", "style", ".", "touchAction", "=", "'none'", ";", "}", "renderInit", "(", ")", ";", "setHfov", "(", "config", ".", "hfov", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "isTimedOut", "=", "true", ";", "}", ",", "500", ")", ";", "}"], "docstring": "Create renderer and initialize event listeners once image is loaded.\n@private", "docstring_tokens": ["Create", "renderer", "and", "initialize", "event", "listeners", "once", "image", "is", "loaded", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L466-L515", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "", "original_string": "function(tag) {\n var result;\n if (xmpData.indexOf(tag + '=\"') >= 0) {\n result = xmpData.substring(xmpData.indexOf(tag + '=\"') + tag.length + 2);\n result = result.substring(0, result.indexOf('\"'));\n } else if (xmpData.indexOf(tag + '>') >= 0) {\n result = xmpData.substring(xmpData.indexOf(tag + '>') + tag.length + 1);\n result = result.substring(0, result.indexOf('<'));\n }\n if (result !== undefined) {\n return Number(result);\n }\n return null;\n }", "language": "javascript", "code": "function(tag) {\n var result;\n if (xmpData.indexOf(tag + '=\"') >= 0) {\n result = xmpData.substring(xmpData.indexOf(tag + '=\"') + tag.length + 2);\n result = result.substring(0, result.indexOf('\"'));\n } else if (xmpData.indexOf(tag + '>') >= 0) {\n result = xmpData.substring(xmpData.indexOf(tag + '>') + tag.length + 1);\n result = result.substring(0, result.indexOf('<'));\n }\n if (result !== undefined) {\n return Number(result);\n }\n return null;\n }", "code_tokens": ["function", "(", "tag", ")", "{", "var", "result", ";", "if", "(", "xmpData", ".", "indexOf", "(", "tag", "+", "'=\"'", ")", ">=", "0", ")", "{", "result", "=", "xmpData", ".", "substring", "(", "xmpData", ".", "indexOf", "(", "tag", "+", "'=\"'", ")", "+", "tag", ".", "length", "+", "2", ")", ";", "result", "=", "result", ".", "substring", "(", "0", ",", "result", ".", "indexOf", "(", "'\"'", ")", ")", ";", "}", "else", "if", "(", "xmpData", ".", "indexOf", "(", "tag", "+", "'>'", ")", ">=", "0", ")", "{", "result", "=", "xmpData", ".", "substring", "(", "xmpData", ".", "indexOf", "(", "tag", "+", "'>'", ")", "+", "tag", ".", "length", "+", "1", ")", ";", "result", "=", "result", ".", "substring", "(", "0", ",", "result", ".", "indexOf", "(", "'<'", ")", ")", ";", "}", "if", "(", "result", "!==", "undefined", ")", "{", "return", "Number", "(", "result", ")", ";", "}", "return", "null", ";", "}"], "docstring": "Extract the requested tag from the XMP data", "docstring_tokens": ["Extract", "the", "requested", "tag", "from", "the", "XMP", "data"], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L541-L554", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "anError", "original_string": "function anError(errorMsg) {\n if (errorMsg === undefined)\n errorMsg = config.strings.genericWebGLError;\n infoDisplay.errorMsg.innerHTML = '

' + errorMsg + '

';\n controls.load.style.display = 'none';\n infoDisplay.load.box.style.display = 'none';\n infoDisplay.errorMsg.style.display = 'table';\n error = true;\n renderContainer.style.display = 'none';\n fireEvent('error', errorMsg);\n}", "language": "javascript", "code": "function anError(errorMsg) {\n if (errorMsg === undefined)\n errorMsg = config.strings.genericWebGLError;\n infoDisplay.errorMsg.innerHTML = '

' + errorMsg + '

';\n controls.load.style.display = 'none';\n infoDisplay.load.box.style.display = 'none';\n infoDisplay.errorMsg.style.display = 'table';\n error = true;\n renderContainer.style.display = 'none';\n fireEvent('error', errorMsg);\n}", "code_tokens": ["function", "anError", "(", "errorMsg", ")", "{", "if", "(", "errorMsg", "===", "undefined", ")", "errorMsg", "=", "config", ".", "strings", ".", "genericWebGLError", ";", "infoDisplay", ".", "errorMsg", ".", "innerHTML", "=", "'

'", "+", "errorMsg", "+", "'

'", ";", "controls", ".", "load", ".", "style", ".", "display", "=", "'none'", ";", "infoDisplay", ".", "load", ".", "box", ".", "style", ".", "display", "=", "'none'", ";", "infoDisplay", ".", "errorMsg", ".", "style", ".", "display", "=", "'table'", ";", "error", "=", "true", ";", "renderContainer", ".", "style", ".", "display", "=", "'none'", ";", "fireEvent", "(", "'error'", ",", "errorMsg", ")", ";", "}"], "docstring": "Displays an error message.\n@private\n@param {string} errorMsg - Error message to display. If not specified, a\ngeneric WebGL error is displayed.", "docstring_tokens": ["Displays", "an", "error", "message", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L612-L622", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "clearError", "original_string": "function clearError() {\n if (error) {\n infoDisplay.load.box.style.display = 'none';\n infoDisplay.errorMsg.style.display = 'none';\n error = false;\n fireEvent('errorcleared');\n }\n}", "language": "javascript", "code": "function clearError() {\n if (error) {\n infoDisplay.load.box.style.display = 'none';\n infoDisplay.errorMsg.style.display = 'none';\n error = false;\n fireEvent('errorcleared');\n }\n}", "code_tokens": ["function", "clearError", "(", ")", "{", "if", "(", "error", ")", "{", "infoDisplay", ".", "load", ".", "box", ".", "style", ".", "display", "=", "'none'", ";", "infoDisplay", ".", "errorMsg", ".", "style", ".", "display", "=", "'none'", ";", "error", "=", "false", ";", "fireEvent", "(", "'errorcleared'", ")", ";", "}", "}"], "docstring": "Hides error message display.\n@private", "docstring_tokens": ["Hides", "error", "message", "display", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L628-L635", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "aboutMessage", "original_string": "function aboutMessage(event) {\n var pos = mousePosition(event);\n aboutMsg.style.left = pos.x + 'px';\n aboutMsg.style.top = pos.y + 'px';\n clearTimeout(aboutMessage.t1);\n clearTimeout(aboutMessage.t2);\n aboutMsg.style.display = 'block';\n aboutMsg.style.opacity = 1;\n aboutMessage.t1 = setTimeout(function() {aboutMsg.style.opacity = 0;}, 2000);\n aboutMessage.t2 = setTimeout(function() {aboutMsg.style.display = 'none';}, 2500);\n event.preventDefault();\n}", "language": "javascript", "code": "function aboutMessage(event) {\n var pos = mousePosition(event);\n aboutMsg.style.left = pos.x + 'px';\n aboutMsg.style.top = pos.y + 'px';\n clearTimeout(aboutMessage.t1);\n clearTimeout(aboutMessage.t2);\n aboutMsg.style.display = 'block';\n aboutMsg.style.opacity = 1;\n aboutMessage.t1 = setTimeout(function() {aboutMsg.style.opacity = 0;}, 2000);\n aboutMessage.t2 = setTimeout(function() {aboutMsg.style.display = 'none';}, 2500);\n event.preventDefault();\n}", "code_tokens": ["function", "aboutMessage", "(", "event", ")", "{", "var", "pos", "=", "mousePosition", "(", "event", ")", ";", "aboutMsg", ".", "style", ".", "left", "=", "pos", ".", "x", "+", "'px'", ";", "aboutMsg", ".", "style", ".", "top", "=", "pos", ".", "y", "+", "'px'", ";", "clearTimeout", "(", "aboutMessage", ".", "t1", ")", ";", "clearTimeout", "(", "aboutMessage", ".", "t2", ")", ";", "aboutMsg", ".", "style", ".", "display", "=", "'block'", ";", "aboutMsg", ".", "style", ".", "opacity", "=", "1", ";", "aboutMessage", ".", "t1", "=", "setTimeout", "(", "function", "(", ")", "{", "aboutMsg", ".", "style", ".", "opacity", "=", "0", ";", "}", ",", "2000", ")", ";", "aboutMessage", ".", "t2", "=", "setTimeout", "(", "function", "(", ")", "{", "aboutMsg", ".", "style", ".", "display", "=", "'none'", ";", "}", ",", "2500", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "}"], "docstring": "Displays about message.\n@private\n@param {MouseEvent} event - Right click location", "docstring_tokens": ["Displays", "about", "message", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L642-L653", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "mousePosition", "original_string": "function mousePosition(event) {\n var bounds = container.getBoundingClientRect();\n var pos = {};\n // pageX / pageY needed for iOS\n pos.x = (event.clientX || event.pageX) - bounds.left;\n pos.y = (event.clientY || event.pageY) - bounds.top;\n return pos;\n}", "language": "javascript", "code": "function mousePosition(event) {\n var bounds = container.getBoundingClientRect();\n var pos = {};\n // pageX / pageY needed for iOS\n pos.x = (event.clientX || event.pageX) - bounds.left;\n pos.y = (event.clientY || event.pageY) - bounds.top;\n return pos;\n}", "code_tokens": ["function", "mousePosition", "(", "event", ")", "{", "var", "bounds", "=", "container", ".", "getBoundingClientRect", "(", ")", ";", "var", "pos", "=", "{", "}", ";", "pos", ".", "x", "=", "(", "event", ".", "clientX", "||", "event", ".", "pageX", ")", "-", "bounds", ".", "left", ";", "pos", ".", "y", "=", "(", "event", ".", "clientY", "||", "event", ".", "pageY", ")", "-", "bounds", ".", "top", ";", "return", "pos", ";", "}"], "docstring": "Calculate mouse position relative to top left of viewer container.\n@private\n@param {MouseEvent} event - Mouse event to use in calculation\n@returns {Object} Calculated X and Y coordinates", "docstring_tokens": ["Calculate", "mouse", "position", "relative", "to", "top", "left", "of", "viewer", "container", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L661-L668", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "onDocumentMouseDown", "original_string": "function onDocumentMouseDown(event) {\n // Override default action\n event.preventDefault();\n // But not all of it\n container.focus();\n \n // Only do something if the panorama is loaded\n if (!loaded || !config.draggable) {\n return;\n }\n \n // Calculate mouse position relative to top left of viewer container\n var pos = mousePosition(event);\n\n // Log pitch / yaw of mouse click when debugging / placing hot spots\n if (config.hotSpotDebug) {\n var coords = mouseEventToCoords(event);\n console.log('Pitch: ' + coords[0] + ', Yaw: ' + coords[1] + ', Center Pitch: ' +\n config.pitch + ', Center Yaw: ' + config.yaw + ', HFOV: ' + config.hfov);\n }\n \n // Turn off auto-rotation if enabled\n stopAnimation();\n\n stopOrientation();\n config.roll = 0;\n\n speed.hfov = 0;\n\n isUserInteracting = true;\n latestInteraction = Date.now();\n \n onPointerDownPointerX = pos.x;\n onPointerDownPointerY = pos.y;\n \n onPointerDownYaw = config.yaw;\n onPointerDownPitch = config.pitch;\n \n uiContainer.classList.add('pnlm-grabbing');\n uiContainer.classList.remove('pnlm-grab');\n \n fireEvent('mousedown', event);\n animateInit();\n}", "language": "javascript", "code": "function onDocumentMouseDown(event) {\n // Override default action\n event.preventDefault();\n // But not all of it\n container.focus();\n \n // Only do something if the panorama is loaded\n if (!loaded || !config.draggable) {\n return;\n }\n \n // Calculate mouse position relative to top left of viewer container\n var pos = mousePosition(event);\n\n // Log pitch / yaw of mouse click when debugging / placing hot spots\n if (config.hotSpotDebug) {\n var coords = mouseEventToCoords(event);\n console.log('Pitch: ' + coords[0] + ', Yaw: ' + coords[1] + ', Center Pitch: ' +\n config.pitch + ', Center Yaw: ' + config.yaw + ', HFOV: ' + config.hfov);\n }\n \n // Turn off auto-rotation if enabled\n stopAnimation();\n\n stopOrientation();\n config.roll = 0;\n\n speed.hfov = 0;\n\n isUserInteracting = true;\n latestInteraction = Date.now();\n \n onPointerDownPointerX = pos.x;\n onPointerDownPointerY = pos.y;\n \n onPointerDownYaw = config.yaw;\n onPointerDownPitch = config.pitch;\n \n uiContainer.classList.add('pnlm-grabbing');\n uiContainer.classList.remove('pnlm-grab');\n \n fireEvent('mousedown', event);\n animateInit();\n}", "code_tokens": ["function", "onDocumentMouseDown", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "container", ".", "focus", "(", ")", ";", "if", "(", "!", "loaded", "||", "!", "config", ".", "draggable", ")", "{", "return", ";", "}", "var", "pos", "=", "mousePosition", "(", "event", ")", ";", "if", "(", "config", ".", "hotSpotDebug", ")", "{", "var", "coords", "=", "mouseEventToCoords", "(", "event", ")", ";", "console", ".", "log", "(", "'Pitch: '", "+", "coords", "[", "0", "]", "+", "', Yaw: '", "+", "coords", "[", "1", "]", "+", "', Center Pitch: '", "+", "config", ".", "pitch", "+", "', Center Yaw: '", "+", "config", ".", "yaw", "+", "', HFOV: '", "+", "config", ".", "hfov", ")", ";", "}", "stopAnimation", "(", ")", ";", "stopOrientation", "(", ")", ";", "config", ".", "roll", "=", "0", ";", "speed", ".", "hfov", "=", "0", ";", "isUserInteracting", "=", "true", ";", "latestInteraction", "=", "Date", ".", "now", "(", ")", ";", "onPointerDownPointerX", "=", "pos", ".", "x", ";", "onPointerDownPointerY", "=", "pos", ".", "y", ";", "onPointerDownYaw", "=", "config", ".", "yaw", ";", "onPointerDownPitch", "=", "config", ".", "pitch", ";", "uiContainer", ".", "classList", ".", "add", "(", "'pnlm-grabbing'", ")", ";", "uiContainer", ".", "classList", ".", "remove", "(", "'pnlm-grab'", ")", ";", "fireEvent", "(", "'mousedown'", ",", "event", ")", ";", "animateInit", "(", ")", ";", "}"], "docstring": "Event handler for mouse clicks. Initializes panning. Prints center and click\nlocation coordinates when hot spot debugging is enabled.\n@private\n@param {MouseEvent} event - Document mouse down event.", "docstring_tokens": ["Event", "handler", "for", "mouse", "clicks", ".", "Initializes", "panning", ".", "Prints", "center", "and", "click", "location", "coordinates", "when", "hot", "spot", "debugging", "is", "enabled", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L676-L719", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "onDocumentDoubleClick", "original_string": "function onDocumentDoubleClick(event) {\n if (config.minHfov === config.hfov) {\n _this.setHfov(origHfov, 1000);\n } else {\n var coords = mouseEventToCoords(event);\n _this.lookAt(coords[0], coords[1], config.minHfov, 1000);\n }\n}", "language": "javascript", "code": "function onDocumentDoubleClick(event) {\n if (config.minHfov === config.hfov) {\n _this.setHfov(origHfov, 1000);\n } else {\n var coords = mouseEventToCoords(event);\n _this.lookAt(coords[0], coords[1], config.minHfov, 1000);\n }\n}", "code_tokens": ["function", "onDocumentDoubleClick", "(", "event", ")", "{", "if", "(", "config", ".", "minHfov", "===", "config", ".", "hfov", ")", "{", "_this", ".", "setHfov", "(", "origHfov", ",", "1000", ")", ";", "}", "else", "{", "var", "coords", "=", "mouseEventToCoords", "(", "event", ")", ";", "_this", ".", "lookAt", "(", "coords", "[", "0", "]", ",", "coords", "[", "1", "]", ",", "config", ".", "minHfov", ",", "1000", ")", ";", "}", "}"], "docstring": "Event handler for double clicks. Zooms in at clicked location\n@private\n@param {MouseEvent} event - Document mouse down event.", "docstring_tokens": ["Event", "handler", "for", "double", "clicks", ".", "Zooms", "in", "at", "clicked", "location"], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L726-L733", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "mouseEventToCoords", "original_string": "function mouseEventToCoords(event) {\n var pos = mousePosition(event);\n var canvas = renderer.getCanvas();\n var canvasWidth = canvas.clientWidth,\n canvasHeight = canvas.clientHeight;\n var x = pos.x / canvasWidth * 2 - 1;\n var y = (1 - pos.y / canvasHeight * 2) * canvasHeight / canvasWidth;\n var focal = 1 / Math.tan(config.hfov * Math.PI / 360);\n var s = Math.sin(config.pitch * Math.PI / 180);\n var c = Math.cos(config.pitch * Math.PI / 180);\n var a = focal * c - y * s;\n var root = Math.sqrt(x*x + a*a);\n var pitch = Math.atan((y * c + focal * s) / root) * 180 / Math.PI;\n var yaw = Math.atan2(x / root, a / root) * 180 / Math.PI + config.yaw;\n if (yaw < -180)\n yaw += 360;\n if (yaw > 180)\n yaw -= 360;\n return [pitch, yaw];\n}", "language": "javascript", "code": "function mouseEventToCoords(event) {\n var pos = mousePosition(event);\n var canvas = renderer.getCanvas();\n var canvasWidth = canvas.clientWidth,\n canvasHeight = canvas.clientHeight;\n var x = pos.x / canvasWidth * 2 - 1;\n var y = (1 - pos.y / canvasHeight * 2) * canvasHeight / canvasWidth;\n var focal = 1 / Math.tan(config.hfov * Math.PI / 360);\n var s = Math.sin(config.pitch * Math.PI / 180);\n var c = Math.cos(config.pitch * Math.PI / 180);\n var a = focal * c - y * s;\n var root = Math.sqrt(x*x + a*a);\n var pitch = Math.atan((y * c + focal * s) / root) * 180 / Math.PI;\n var yaw = Math.atan2(x / root, a / root) * 180 / Math.PI + config.yaw;\n if (yaw < -180)\n yaw += 360;\n if (yaw > 180)\n yaw -= 360;\n return [pitch, yaw];\n}", "code_tokens": ["function", "mouseEventToCoords", "(", "event", ")", "{", "var", "pos", "=", "mousePosition", "(", "event", ")", ";", "var", "canvas", "=", "renderer", ".", "getCanvas", "(", ")", ";", "var", "canvasWidth", "=", "canvas", ".", "clientWidth", ",", "canvasHeight", "=", "canvas", ".", "clientHeight", ";", "var", "x", "=", "pos", ".", "x", "/", "canvasWidth", "*", "2", "-", "1", ";", "var", "y", "=", "(", "1", "-", "pos", ".", "y", "/", "canvasHeight", "*", "2", ")", "*", "canvasHeight", "/", "canvasWidth", ";", "var", "focal", "=", "1", "/", "Math", ".", "tan", "(", "config", ".", "hfov", "*", "Math", ".", "PI", "/", "360", ")", ";", "var", "s", "=", "Math", ".", "sin", "(", "config", ".", "pitch", "*", "Math", ".", "PI", "/", "180", ")", ";", "var", "c", "=", "Math", ".", "cos", "(", "config", ".", "pitch", "*", "Math", ".", "PI", "/", "180", ")", ";", "var", "a", "=", "focal", "*", "c", "-", "y", "*", "s", ";", "var", "root", "=", "Math", ".", "sqrt", "(", "x", "*", "x", "+", "a", "*", "a", ")", ";", "var", "pitch", "=", "Math", ".", "atan", "(", "(", "y", "*", "c", "+", "focal", "*", "s", ")", "/", "root", ")", "*", "180", "/", "Math", ".", "PI", ";", "var", "yaw", "=", "Math", ".", "atan2", "(", "x", "/", "root", ",", "a", "/", "root", ")", "*", "180", "/", "Math", ".", "PI", "+", "config", ".", "yaw", ";", "if", "(", "yaw", "<", "-", "180", ")", "yaw", "+=", "360", ";", "if", "(", "yaw", ">", "180", ")", "yaw", "-=", "360", ";", "return", "[", "pitch", ",", "yaw", "]", ";", "}"], "docstring": "Calculate panorama pitch and yaw from location of mouse event.\n@private\n@param {MouseEvent} event - Document mouse down event.\n@returns {number[]} [pitch, yaw]", "docstring_tokens": ["Calculate", "panorama", "pitch", "and", "yaw", "from", "location", "of", "mouse", "event", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L741-L760", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "onDocumentMouseMove", "original_string": "function onDocumentMouseMove(event) {\n if (isUserInteracting && loaded) {\n latestInteraction = Date.now();\n var canvas = renderer.getCanvas();\n var canvasWidth = canvas.clientWidth,\n canvasHeight = canvas.clientHeight;\n var pos = mousePosition(event);\n //TODO: This still isn't quite right\n var yaw = ((Math.atan(onPointerDownPointerX / canvasWidth * 2 - 1) - Math.atan(pos.x / canvasWidth * 2 - 1)) * 180 / Math.PI * config.hfov / 90) + onPointerDownYaw;\n speed.yaw = (yaw - config.yaw) % 360 * 0.2;\n config.yaw = yaw;\n \n var vfov = 2 * Math.atan(Math.tan(config.hfov/360*Math.PI) * canvasHeight / canvasWidth) * 180 / Math.PI;\n \n var pitch = ((Math.atan(pos.y / canvasHeight * 2 - 1) - Math.atan(onPointerDownPointerY / canvasHeight * 2 - 1)) * 180 / Math.PI * vfov / 90) + onPointerDownPitch;\n speed.pitch = (pitch - config.pitch) * 0.2;\n config.pitch = pitch;\n }\n}", "language": "javascript", "code": "function onDocumentMouseMove(event) {\n if (isUserInteracting && loaded) {\n latestInteraction = Date.now();\n var canvas = renderer.getCanvas();\n var canvasWidth = canvas.clientWidth,\n canvasHeight = canvas.clientHeight;\n var pos = mousePosition(event);\n //TODO: This still isn't quite right\n var yaw = ((Math.atan(onPointerDownPointerX / canvasWidth * 2 - 1) - Math.atan(pos.x / canvasWidth * 2 - 1)) * 180 / Math.PI * config.hfov / 90) + onPointerDownYaw;\n speed.yaw = (yaw - config.yaw) % 360 * 0.2;\n config.yaw = yaw;\n \n var vfov = 2 * Math.atan(Math.tan(config.hfov/360*Math.PI) * canvasHeight / canvasWidth) * 180 / Math.PI;\n \n var pitch = ((Math.atan(pos.y / canvasHeight * 2 - 1) - Math.atan(onPointerDownPointerY / canvasHeight * 2 - 1)) * 180 / Math.PI * vfov / 90) + onPointerDownPitch;\n speed.pitch = (pitch - config.pitch) * 0.2;\n config.pitch = pitch;\n }\n}", "code_tokens": ["function", "onDocumentMouseMove", "(", "event", ")", "{", "if", "(", "isUserInteracting", "&&", "loaded", ")", "{", "latestInteraction", "=", "Date", ".", "now", "(", ")", ";", "var", "canvas", "=", "renderer", ".", "getCanvas", "(", ")", ";", "var", "canvasWidth", "=", "canvas", ".", "clientWidth", ",", "canvasHeight", "=", "canvas", ".", "clientHeight", ";", "var", "pos", "=", "mousePosition", "(", "event", ")", ";", "var", "yaw", "=", "(", "(", "Math", ".", "atan", "(", "onPointerDownPointerX", "/", "canvasWidth", "*", "2", "-", "1", ")", "-", "Math", ".", "atan", "(", "pos", ".", "x", "/", "canvasWidth", "*", "2", "-", "1", ")", ")", "*", "180", "/", "Math", ".", "PI", "*", "config", ".", "hfov", "/", "90", ")", "+", "onPointerDownYaw", ";", "speed", ".", "yaw", "=", "(", "yaw", "-", "config", ".", "yaw", ")", "%", "360", "*", "0.2", ";", "config", ".", "yaw", "=", "yaw", ";", "var", "vfov", "=", "2", "*", "Math", ".", "atan", "(", "Math", ".", "tan", "(", "config", ".", "hfov", "/", "360", "*", "Math", ".", "PI", ")", "*", "canvasHeight", "/", "canvasWidth", ")", "*", "180", "/", "Math", ".", "PI", ";", "var", "pitch", "=", "(", "(", "Math", ".", "atan", "(", "pos", ".", "y", "/", "canvasHeight", "*", "2", "-", "1", ")", "-", "Math", ".", "atan", "(", "onPointerDownPointerY", "/", "canvasHeight", "*", "2", "-", "1", ")", ")", "*", "180", "/", "Math", ".", "PI", "*", "vfov", "/", "90", ")", "+", "onPointerDownPitch", ";", "speed", ".", "pitch", "=", "(", "pitch", "-", "config", ".", "pitch", ")", "*", "0.2", ";", "config", ".", "pitch", "=", "pitch", ";", "}", "}"], "docstring": "Event handler for mouse moves. Pans center of view.\n@private\n@param {MouseEvent} event - Document mouse move event.", "docstring_tokens": ["Event", "handler", "for", "mouse", "moves", ".", "Pans", "center", "of", "view", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L767-L785", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "onDocumentMouseUp", "original_string": "function onDocumentMouseUp(event) {\n if (!isUserInteracting) {\n return;\n }\n isUserInteracting = false;\n if (Date.now() - latestInteraction > 15) {\n // Prevents jump when user rapidly moves mouse, stops, and then\n // releases the mouse button\n speed.pitch = speed.yaw = 0;\n }\n uiContainer.classList.add('pnlm-grab');\n uiContainer.classList.remove('pnlm-grabbing');\n latestInteraction = Date.now();\n\n fireEvent('mouseup', event);\n}", "language": "javascript", "code": "function onDocumentMouseUp(event) {\n if (!isUserInteracting) {\n return;\n }\n isUserInteracting = false;\n if (Date.now() - latestInteraction > 15) {\n // Prevents jump when user rapidly moves mouse, stops, and then\n // releases the mouse button\n speed.pitch = speed.yaw = 0;\n }\n uiContainer.classList.add('pnlm-grab');\n uiContainer.classList.remove('pnlm-grabbing');\n latestInteraction = Date.now();\n\n fireEvent('mouseup', event);\n}", "code_tokens": ["function", "onDocumentMouseUp", "(", "event", ")", "{", "if", "(", "!", "isUserInteracting", ")", "{", "return", ";", "}", "isUserInteracting", "=", "false", ";", "if", "(", "Date", ".", "now", "(", ")", "-", "latestInteraction", ">", "15", ")", "{", "speed", ".", "pitch", "=", "speed", ".", "yaw", "=", "0", ";", "}", "uiContainer", ".", "classList", ".", "add", "(", "'pnlm-grab'", ")", ";", "uiContainer", ".", "classList", ".", "remove", "(", "'pnlm-grabbing'", ")", ";", "latestInteraction", "=", "Date", ".", "now", "(", ")", ";", "fireEvent", "(", "'mouseup'", ",", "event", ")", ";", "}"], "docstring": "Event handler for mouse up events. Stops panning.\n@private", "docstring_tokens": ["Event", "handler", "for", "mouse", "up", "events", ".", "Stops", "panning", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L791-L806", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "onDocumentTouchStart", "original_string": "function onDocumentTouchStart(event) {\n // Only do something if the panorama is loaded\n if (!loaded || !config.draggable) {\n return;\n }\n\n // Turn off auto-rotation if enabled\n stopAnimation();\n\n stopOrientation();\n config.roll = 0;\n\n speed.hfov = 0;\n\n // Calculate touch position relative to top left of viewer container\n var pos0 = mousePosition(event.targetTouches[0]);\n\n onPointerDownPointerX = pos0.x;\n onPointerDownPointerY = pos0.y;\n \n if (event.targetTouches.length == 2) {\n // Down pointer is the center of the two fingers\n var pos1 = mousePosition(event.targetTouches[1]);\n onPointerDownPointerX += (pos1.x - pos0.x) * 0.5;\n onPointerDownPointerY += (pos1.y - pos0.y) * 0.5;\n onPointerDownPointerDist = Math.sqrt((pos0.x - pos1.x) * (pos0.x - pos1.x) +\n (pos0.y - pos1.y) * (pos0.y - pos1.y));\n }\n isUserInteracting = true;\n latestInteraction = Date.now();\n \n onPointerDownYaw = config.yaw;\n onPointerDownPitch = config.pitch;\n\n fireEvent('touchstart', event);\n animateInit();\n}", "language": "javascript", "code": "function onDocumentTouchStart(event) {\n // Only do something if the panorama is loaded\n if (!loaded || !config.draggable) {\n return;\n }\n\n // Turn off auto-rotation if enabled\n stopAnimation();\n\n stopOrientation();\n config.roll = 0;\n\n speed.hfov = 0;\n\n // Calculate touch position relative to top left of viewer container\n var pos0 = mousePosition(event.targetTouches[0]);\n\n onPointerDownPointerX = pos0.x;\n onPointerDownPointerY = pos0.y;\n \n if (event.targetTouches.length == 2) {\n // Down pointer is the center of the two fingers\n var pos1 = mousePosition(event.targetTouches[1]);\n onPointerDownPointerX += (pos1.x - pos0.x) * 0.5;\n onPointerDownPointerY += (pos1.y - pos0.y) * 0.5;\n onPointerDownPointerDist = Math.sqrt((pos0.x - pos1.x) * (pos0.x - pos1.x) +\n (pos0.y - pos1.y) * (pos0.y - pos1.y));\n }\n isUserInteracting = true;\n latestInteraction = Date.now();\n \n onPointerDownYaw = config.yaw;\n onPointerDownPitch = config.pitch;\n\n fireEvent('touchstart', event);\n animateInit();\n}", "code_tokens": ["function", "onDocumentTouchStart", "(", "event", ")", "{", "if", "(", "!", "loaded", "||", "!", "config", ".", "draggable", ")", "{", "return", ";", "}", "stopAnimation", "(", ")", ";", "stopOrientation", "(", ")", ";", "config", ".", "roll", "=", "0", ";", "speed", ".", "hfov", "=", "0", ";", "var", "pos0", "=", "mousePosition", "(", "event", ".", "targetTouches", "[", "0", "]", ")", ";", "onPointerDownPointerX", "=", "pos0", ".", "x", ";", "onPointerDownPointerY", "=", "pos0", ".", "y", ";", "if", "(", "event", ".", "targetTouches", ".", "length", "==", "2", ")", "{", "var", "pos1", "=", "mousePosition", "(", "event", ".", "targetTouches", "[", "1", "]", ")", ";", "onPointerDownPointerX", "+=", "(", "pos1", ".", "x", "-", "pos0", ".", "x", ")", "*", "0.5", ";", "onPointerDownPointerY", "+=", "(", "pos1", ".", "y", "-", "pos0", ".", "y", ")", "*", "0.5", ";", "onPointerDownPointerDist", "=", "Math", ".", "sqrt", "(", "(", "pos0", ".", "x", "-", "pos1", ".", "x", ")", "*", "(", "pos0", ".", "x", "-", "pos1", ".", "x", ")", "+", "(", "pos0", ".", "y", "-", "pos1", ".", "y", ")", "*", "(", "pos0", ".", "y", "-", "pos1", ".", "y", ")", ")", ";", "}", "isUserInteracting", "=", "true", ";", "latestInteraction", "=", "Date", ".", "now", "(", ")", ";", "onPointerDownYaw", "=", "config", ".", "yaw", ";", "onPointerDownPitch", "=", "config", ".", "pitch", ";", "fireEvent", "(", "'touchstart'", ",", "event", ")", ";", "animateInit", "(", ")", ";", "}"], "docstring": "Event handler for touches. Initializes panning if one touch or zooming if\ntwo touches.\n@private\n@param {TouchEvent} event - Document touch start event.", "docstring_tokens": ["Event", "handler", "for", "touches", ".", "Initializes", "panning", "if", "one", "touch", "or", "zooming", "if", "two", "touches", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L814-L850", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "onDocumentTouchMove", "original_string": "function onDocumentTouchMove(event) {\n if (!config.draggable) {\n return;\n }\n\n // Override default action\n event.preventDefault();\n if (loaded) {\n latestInteraction = Date.now();\n }\n if (isUserInteracting && loaded) {\n var pos0 = mousePosition(event.targetTouches[0]);\n var clientX = pos0.x;\n var clientY = pos0.y;\n \n if (event.targetTouches.length == 2 && onPointerDownPointerDist != -1) {\n var pos1 = mousePosition(event.targetTouches[1]);\n clientX += (pos1.x - pos0.x) * 0.5;\n clientY += (pos1.y - pos0.y) * 0.5;\n var clientDist = Math.sqrt((pos0.x - pos1.x) * (pos0.x - pos1.x) +\n (pos0.y - pos1.y) * (pos0.y - pos1.y));\n setHfov(config.hfov + (onPointerDownPointerDist - clientDist) * 0.1);\n onPointerDownPointerDist = clientDist;\n }\n\n // The smaller the config.hfov value (the more zoomed-in the user is), the faster\n // yaw/pitch are perceived to change on one-finger touchmove (panning) events and vice versa.\n // To improve usability at both small and large zoom levels (config.hfov values)\n // we introduce a dynamic pan speed coefficient.\n //\n // Currently this seems to *roughly* keep initial drag/pan start position close to\n // the user's finger while panning regardless of zoom level / config.hfov value.\n var touchmovePanSpeedCoeff = (config.hfov / 360) * config.touchPanSpeedCoeffFactor;\n\n var yaw = (onPointerDownPointerX - clientX) * touchmovePanSpeedCoeff + onPointerDownYaw;\n speed.yaw = (yaw - config.yaw) % 360 * 0.2;\n config.yaw = yaw;\n\n var pitch = (clientY - onPointerDownPointerY) * touchmovePanSpeedCoeff + onPointerDownPitch;\n speed.pitch = (pitch - config.pitch) * 0.2;\n config.pitch = pitch;\n }\n}", "language": "javascript", "code": "function onDocumentTouchMove(event) {\n if (!config.draggable) {\n return;\n }\n\n // Override default action\n event.preventDefault();\n if (loaded) {\n latestInteraction = Date.now();\n }\n if (isUserInteracting && loaded) {\n var pos0 = mousePosition(event.targetTouches[0]);\n var clientX = pos0.x;\n var clientY = pos0.y;\n \n if (event.targetTouches.length == 2 && onPointerDownPointerDist != -1) {\n var pos1 = mousePosition(event.targetTouches[1]);\n clientX += (pos1.x - pos0.x) * 0.5;\n clientY += (pos1.y - pos0.y) * 0.5;\n var clientDist = Math.sqrt((pos0.x - pos1.x) * (pos0.x - pos1.x) +\n (pos0.y - pos1.y) * (pos0.y - pos1.y));\n setHfov(config.hfov + (onPointerDownPointerDist - clientDist) * 0.1);\n onPointerDownPointerDist = clientDist;\n }\n\n // The smaller the config.hfov value (the more zoomed-in the user is), the faster\n // yaw/pitch are perceived to change on one-finger touchmove (panning) events and vice versa.\n // To improve usability at both small and large zoom levels (config.hfov values)\n // we introduce a dynamic pan speed coefficient.\n //\n // Currently this seems to *roughly* keep initial drag/pan start position close to\n // the user's finger while panning regardless of zoom level / config.hfov value.\n var touchmovePanSpeedCoeff = (config.hfov / 360) * config.touchPanSpeedCoeffFactor;\n\n var yaw = (onPointerDownPointerX - clientX) * touchmovePanSpeedCoeff + onPointerDownYaw;\n speed.yaw = (yaw - config.yaw) % 360 * 0.2;\n config.yaw = yaw;\n\n var pitch = (clientY - onPointerDownPointerY) * touchmovePanSpeedCoeff + onPointerDownPitch;\n speed.pitch = (pitch - config.pitch) * 0.2;\n config.pitch = pitch;\n }\n}", "code_tokens": ["function", "onDocumentTouchMove", "(", "event", ")", "{", "if", "(", "!", "config", ".", "draggable", ")", "{", "return", ";", "}", "event", ".", "preventDefault", "(", ")", ";", "if", "(", "loaded", ")", "{", "latestInteraction", "=", "Date", ".", "now", "(", ")", ";", "}", "if", "(", "isUserInteracting", "&&", "loaded", ")", "{", "var", "pos0", "=", "mousePosition", "(", "event", ".", "targetTouches", "[", "0", "]", ")", ";", "var", "clientX", "=", "pos0", ".", "x", ";", "var", "clientY", "=", "pos0", ".", "y", ";", "if", "(", "event", ".", "targetTouches", ".", "length", "==", "2", "&&", "onPointerDownPointerDist", "!=", "-", "1", ")", "{", "var", "pos1", "=", "mousePosition", "(", "event", ".", "targetTouches", "[", "1", "]", ")", ";", "clientX", "+=", "(", "pos1", ".", "x", "-", "pos0", ".", "x", ")", "*", "0.5", ";", "clientY", "+=", "(", "pos1", ".", "y", "-", "pos0", ".", "y", ")", "*", "0.5", ";", "var", "clientDist", "=", "Math", ".", "sqrt", "(", "(", "pos0", ".", "x", "-", "pos1", ".", "x", ")", "*", "(", "pos0", ".", "x", "-", "pos1", ".", "x", ")", "+", "(", "pos0", ".", "y", "-", "pos1", ".", "y", ")", "*", "(", "pos0", ".", "y", "-", "pos1", ".", "y", ")", ")", ";", "setHfov", "(", "config", ".", "hfov", "+", "(", "onPointerDownPointerDist", "-", "clientDist", ")", "*", "0.1", ")", ";", "onPointerDownPointerDist", "=", "clientDist", ";", "}", "var", "touchmovePanSpeedCoeff", "=", "(", "config", ".", "hfov", "/", "360", ")", "*", "config", ".", "touchPanSpeedCoeffFactor", ";", "var", "yaw", "=", "(", "onPointerDownPointerX", "-", "clientX", ")", "*", "touchmovePanSpeedCoeff", "+", "onPointerDownYaw", ";", "speed", ".", "yaw", "=", "(", "yaw", "-", "config", ".", "yaw", ")", "%", "360", "*", "0.2", ";", "config", ".", "yaw", "=", "yaw", ";", "var", "pitch", "=", "(", "clientY", "-", "onPointerDownPointerY", ")", "*", "touchmovePanSpeedCoeff", "+", "onPointerDownPitch", ";", "speed", ".", "pitch", "=", "(", "pitch", "-", "config", ".", "pitch", ")", "*", "0.2", ";", "config", ".", "pitch", "=", "pitch", ";", "}", "}"], "docstring": "Event handler for touch movements. Pans center of view if one touch or\nadjusts zoom if two touches.\n@private\n@param {TouchEvent} event - Document touch move event.", "docstring_tokens": ["Event", "handler", "for", "touch", "movements", ".", "Pans", "center", "of", "view", "if", "one", "touch", "or", "adjusts", "zoom", "if", "two", "touches", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L858-L900", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "onDocumentMouseWheel", "original_string": "function onDocumentMouseWheel(event) {\n // Only do something if the panorama is loaded and mouse wheel zoom is enabled\n if (!loaded || (config.mouseZoom == 'fullscreenonly' && !fullscreenActive)) {\n return;\n }\n\n event.preventDefault();\n\n // Turn off auto-rotation if enabled\n stopAnimation();\n latestInteraction = Date.now();\n\n if (event.wheelDeltaY) {\n // WebKit\n setHfov(config.hfov - event.wheelDeltaY * 0.05);\n speed.hfov = event.wheelDelta < 0 ? 1 : -1;\n } else if (event.wheelDelta) {\n // Opera / Explorer 9\n setHfov(config.hfov - event.wheelDelta * 0.05);\n speed.hfov = event.wheelDelta < 0 ? 1 : -1;\n } else if (event.detail) {\n // Firefox\n setHfov(config.hfov + event.detail * 1.5);\n speed.hfov = event.detail > 0 ? 1 : -1;\n }\n animateInit();\n}", "language": "javascript", "code": "function onDocumentMouseWheel(event) {\n // Only do something if the panorama is loaded and mouse wheel zoom is enabled\n if (!loaded || (config.mouseZoom == 'fullscreenonly' && !fullscreenActive)) {\n return;\n }\n\n event.preventDefault();\n\n // Turn off auto-rotation if enabled\n stopAnimation();\n latestInteraction = Date.now();\n\n if (event.wheelDeltaY) {\n // WebKit\n setHfov(config.hfov - event.wheelDeltaY * 0.05);\n speed.hfov = event.wheelDelta < 0 ? 1 : -1;\n } else if (event.wheelDelta) {\n // Opera / Explorer 9\n setHfov(config.hfov - event.wheelDelta * 0.05);\n speed.hfov = event.wheelDelta < 0 ? 1 : -1;\n } else if (event.detail) {\n // Firefox\n setHfov(config.hfov + event.detail * 1.5);\n speed.hfov = event.detail > 0 ? 1 : -1;\n }\n animateInit();\n}", "code_tokens": ["function", "onDocumentMouseWheel", "(", "event", ")", "{", "if", "(", "!", "loaded", "||", "(", "config", ".", "mouseZoom", "==", "'fullscreenonly'", "&&", "!", "fullscreenActive", ")", ")", "{", "return", ";", "}", "event", ".", "preventDefault", "(", ")", ";", "stopAnimation", "(", ")", ";", "latestInteraction", "=", "Date", ".", "now", "(", ")", ";", "if", "(", "event", ".", "wheelDeltaY", ")", "{", "setHfov", "(", "config", ".", "hfov", "-", "event", ".", "wheelDeltaY", "*", "0.05", ")", ";", "speed", ".", "hfov", "=", "event", ".", "wheelDelta", "<", "0", "?", "1", ":", "-", "1", ";", "}", "else", "if", "(", "event", ".", "wheelDelta", ")", "{", "setHfov", "(", "config", ".", "hfov", "-", "event", ".", "wheelDelta", "*", "0.05", ")", ";", "speed", ".", "hfov", "=", "event", ".", "wheelDelta", "<", "0", "?", "1", ":", "-", "1", ";", "}", "else", "if", "(", "event", ".", "detail", ")", "{", "setHfov", "(", "config", ".", "hfov", "+", "event", ".", "detail", "*", "1.5", ")", ";", "speed", ".", "hfov", "=", "event", ".", "detail", ">", "0", "?", "1", ":", "-", "1", ";", "}", "animateInit", "(", ")", ";", "}"], "docstring": "Event handler for mouse wheel. Changes zoom.\n@private\n@param {WheelEvent} event - Document mouse wheel event.", "docstring_tokens": ["Event", "handler", "for", "mouse", "wheel", ".", "Changes", "zoom", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L982-L1008", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "onDocumentKeyPress", "original_string": "function onDocumentKeyPress(event) {\n // Turn off auto-rotation if enabled\n stopAnimation();\n latestInteraction = Date.now();\n\n stopOrientation();\n config.roll = 0;\n\n // Record key pressed\n var keynumber = event.which || event.keycode;\n\n // Override default action for keys that are used\n if (config.capturedKeyNumbers.indexOf(keynumber) < 0)\n return;\n event.preventDefault();\n \n // If escape key is pressed\n if (keynumber == 27) {\n // If in fullscreen mode\n if (fullscreenActive) {\n toggleFullscreen();\n }\n } else {\n // Change key\n changeKey(keynumber, true);\n }\n}", "language": "javascript", "code": "function onDocumentKeyPress(event) {\n // Turn off auto-rotation if enabled\n stopAnimation();\n latestInteraction = Date.now();\n\n stopOrientation();\n config.roll = 0;\n\n // Record key pressed\n var keynumber = event.which || event.keycode;\n\n // Override default action for keys that are used\n if (config.capturedKeyNumbers.indexOf(keynumber) < 0)\n return;\n event.preventDefault();\n \n // If escape key is pressed\n if (keynumber == 27) {\n // If in fullscreen mode\n if (fullscreenActive) {\n toggleFullscreen();\n }\n } else {\n // Change key\n changeKey(keynumber, true);\n }\n}", "code_tokens": ["function", "onDocumentKeyPress", "(", "event", ")", "{", "stopAnimation", "(", ")", ";", "latestInteraction", "=", "Date", ".", "now", "(", ")", ";", "stopOrientation", "(", ")", ";", "config", ".", "roll", "=", "0", ";", "var", "keynumber", "=", "event", ".", "which", "||", "event", ".", "keycode", ";", "if", "(", "config", ".", "capturedKeyNumbers", ".", "indexOf", "(", "keynumber", ")", "<", "0", ")", "return", ";", "event", ".", "preventDefault", "(", ")", ";", "if", "(", "keynumber", "==", "27", ")", "{", "if", "(", "fullscreenActive", ")", "{", "toggleFullscreen", "(", ")", ";", "}", "}", "else", "{", "changeKey", "(", "keynumber", ",", "true", ")", ";", "}", "}"], "docstring": "Event handler for key presses. Updates list of currently pressed keys.\n@private\n@param {KeyboardEvent} event - Document key press event.", "docstring_tokens": ["Event", "handler", "for", "key", "presses", ".", "Updates", "list", "of", "currently", "pressed", "keys", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1015-L1041", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "onDocumentKeyUp", "original_string": "function onDocumentKeyUp(event) {\n // Record key pressed\n var keynumber = event.which || event.keycode;\n \n // Override default action for keys that are used\n if (config.capturedKeyNumbers.indexOf(keynumber) < 0)\n return;\n event.preventDefault();\n \n // Change key\n changeKey(keynumber, false);\n}", "language": "javascript", "code": "function onDocumentKeyUp(event) {\n // Record key pressed\n var keynumber = event.which || event.keycode;\n \n // Override default action for keys that are used\n if (config.capturedKeyNumbers.indexOf(keynumber) < 0)\n return;\n event.preventDefault();\n \n // Change key\n changeKey(keynumber, false);\n}", "code_tokens": ["function", "onDocumentKeyUp", "(", "event", ")", "{", "var", "keynumber", "=", "event", ".", "which", "||", "event", ".", "keycode", ";", "if", "(", "config", ".", "capturedKeyNumbers", ".", "indexOf", "(", "keynumber", ")", "<", "0", ")", "return", ";", "event", ".", "preventDefault", "(", ")", ";", "changeKey", "(", "keynumber", ",", "false", ")", ";", "}"], "docstring": "Event handler for key releases. Updates list of currently pressed keys.\n@private\n@param {KeyboardEvent} event - Document key up event.", "docstring_tokens": ["Event", "handler", "for", "key", "releases", ".", "Updates", "list", "of", "currently", "pressed", "keys", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1058-L1069", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "changeKey", "original_string": "function changeKey(keynumber, value) {\n var keyChanged = false;\n switch(keynumber) {\n // If minus key is released\n case 109: case 189: case 17: case 173:\n if (keysDown[0] != value) { keyChanged = true; }\n keysDown[0] = value; break;\n \n // If plus key is released\n case 107: case 187: case 16: case 61:\n if (keysDown[1] != value) { keyChanged = true; }\n keysDown[1] = value; break;\n \n // If up arrow is released\n case 38:\n if (keysDown[2] != value) { keyChanged = true; }\n keysDown[2] = value; break;\n \n // If \"w\" is released\n case 87:\n if (keysDown[6] != value) { keyChanged = true; }\n keysDown[6] = value; break;\n \n // If down arrow is released\n case 40:\n if (keysDown[3] != value) { keyChanged = true; }\n keysDown[3] = value; break;\n \n // If \"s\" is released\n case 83:\n if (keysDown[7] != value) { keyChanged = true; }\n keysDown[7] = value; break;\n \n // If left arrow is released\n case 37:\n if (keysDown[4] != value) { keyChanged = true; }\n keysDown[4] = value; break;\n \n // If \"a\" is released\n case 65:\n if (keysDown[8] != value) { keyChanged = true; }\n keysDown[8] = value; break;\n \n // If right arrow is released\n case 39:\n if (keysDown[5] != value) { keyChanged = true; }\n keysDown[5] = value; break;\n \n // If \"d\" is released\n case 68:\n if (keysDown[9] != value) { keyChanged = true; }\n keysDown[9] = value;\n }\n \n if (keyChanged && value) {\n if (typeof performance !== 'undefined' && performance.now()) {\n prevTime = performance.now();\n } else {\n prevTime = Date.now();\n }\n animateInit();\n }\n}", "language": "javascript", "code": "function changeKey(keynumber, value) {\n var keyChanged = false;\n switch(keynumber) {\n // If minus key is released\n case 109: case 189: case 17: case 173:\n if (keysDown[0] != value) { keyChanged = true; }\n keysDown[0] = value; break;\n \n // If plus key is released\n case 107: case 187: case 16: case 61:\n if (keysDown[1] != value) { keyChanged = true; }\n keysDown[1] = value; break;\n \n // If up arrow is released\n case 38:\n if (keysDown[2] != value) { keyChanged = true; }\n keysDown[2] = value; break;\n \n // If \"w\" is released\n case 87:\n if (keysDown[6] != value) { keyChanged = true; }\n keysDown[6] = value; break;\n \n // If down arrow is released\n case 40:\n if (keysDown[3] != value) { keyChanged = true; }\n keysDown[3] = value; break;\n \n // If \"s\" is released\n case 83:\n if (keysDown[7] != value) { keyChanged = true; }\n keysDown[7] = value; break;\n \n // If left arrow is released\n case 37:\n if (keysDown[4] != value) { keyChanged = true; }\n keysDown[4] = value; break;\n \n // If \"a\" is released\n case 65:\n if (keysDown[8] != value) { keyChanged = true; }\n keysDown[8] = value; break;\n \n // If right arrow is released\n case 39:\n if (keysDown[5] != value) { keyChanged = true; }\n keysDown[5] = value; break;\n \n // If \"d\" is released\n case 68:\n if (keysDown[9] != value) { keyChanged = true; }\n keysDown[9] = value;\n }\n \n if (keyChanged && value) {\n if (typeof performance !== 'undefined' && performance.now()) {\n prevTime = performance.now();\n } else {\n prevTime = Date.now();\n }\n animateInit();\n }\n}", "code_tokens": ["function", "changeKey", "(", "keynumber", ",", "value", ")", "{", "var", "keyChanged", "=", "false", ";", "switch", "(", "keynumber", ")", "{", "case", "109", ":", "case", "189", ":", "case", "17", ":", "case", "173", ":", "if", "(", "keysDown", "[", "0", "]", "!=", "value", ")", "{", "keyChanged", "=", "true", ";", "}", "keysDown", "[", "0", "]", "=", "value", ";", "break", ";", "case", "107", ":", "case", "187", ":", "case", "16", ":", "case", "61", ":", "if", "(", "keysDown", "[", "1", "]", "!=", "value", ")", "{", "keyChanged", "=", "true", ";", "}", "keysDown", "[", "1", "]", "=", "value", ";", "break", ";", "case", "38", ":", "if", "(", "keysDown", "[", "2", "]", "!=", "value", ")", "{", "keyChanged", "=", "true", ";", "}", "keysDown", "[", "2", "]", "=", "value", ";", "break", ";", "case", "87", ":", "if", "(", "keysDown", "[", "6", "]", "!=", "value", ")", "{", "keyChanged", "=", "true", ";", "}", "keysDown", "[", "6", "]", "=", "value", ";", "break", ";", "case", "40", ":", "if", "(", "keysDown", "[", "3", "]", "!=", "value", ")", "{", "keyChanged", "=", "true", ";", "}", "keysDown", "[", "3", "]", "=", "value", ";", "break", ";", "case", "83", ":", "if", "(", "keysDown", "[", "7", "]", "!=", "value", ")", "{", "keyChanged", "=", "true", ";", "}", "keysDown", "[", "7", "]", "=", "value", ";", "break", ";", "case", "37", ":", "if", "(", "keysDown", "[", "4", "]", "!=", "value", ")", "{", "keyChanged", "=", "true", ";", "}", "keysDown", "[", "4", "]", "=", "value", ";", "break", ";", "case", "65", ":", "if", "(", "keysDown", "[", "8", "]", "!=", "value", ")", "{", "keyChanged", "=", "true", ";", "}", "keysDown", "[", "8", "]", "=", "value", ";", "break", ";", "case", "39", ":", "if", "(", "keysDown", "[", "5", "]", "!=", "value", ")", "{", "keyChanged", "=", "true", ";", "}", "keysDown", "[", "5", "]", "=", "value", ";", "break", ";", "case", "68", ":", "if", "(", "keysDown", "[", "9", "]", "!=", "value", ")", "{", "keyChanged", "=", "true", ";", "}", "keysDown", "[", "9", "]", "=", "value", ";", "}", "if", "(", "keyChanged", "&&", "value", ")", "{", "if", "(", "typeof", "performance", "!==", "'undefined'", "&&", "performance", ".", "now", "(", ")", ")", "{", "prevTime", "=", "performance", ".", "now", "(", ")", ";", "}", "else", "{", "prevTime", "=", "Date", ".", "now", "(", ")", ";", "}", "animateInit", "(", ")", ";", "}", "}"], "docstring": "Updates list of currently pressed keys.\n@private\n@param {number} keynumber - Key number.\n@param {boolean} value - Whether or not key is pressed.", "docstring_tokens": ["Updates", "list", "of", "currently", "pressed", "keys", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1077-L1139", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "animateMove", "original_string": "function animateMove(axis) {\n var t = animatedMove[axis];\n var normTime = Math.min(1, Math.max((Date.now() - t.startTime) / 1000 / (t.duration / 1000), 0));\n var result = t.startPosition + config.animationTimingFunction(normTime) * (t.endPosition - t.startPosition);\n if ((t.endPosition > t.startPosition && result >= t.endPosition) ||\n (t.endPosition < t.startPosition && result <= t.endPosition) ||\n t.endPosition === t.startPosition) {\n result = t.endPosition;\n speed[axis] = 0;\n delete animatedMove[axis];\n }\n config[axis] = result;\n}", "language": "javascript", "code": "function animateMove(axis) {\n var t = animatedMove[axis];\n var normTime = Math.min(1, Math.max((Date.now() - t.startTime) / 1000 / (t.duration / 1000), 0));\n var result = t.startPosition + config.animationTimingFunction(normTime) * (t.endPosition - t.startPosition);\n if ((t.endPosition > t.startPosition && result >= t.endPosition) ||\n (t.endPosition < t.startPosition && result <= t.endPosition) ||\n t.endPosition === t.startPosition) {\n result = t.endPosition;\n speed[axis] = 0;\n delete animatedMove[axis];\n }\n config[axis] = result;\n}", "code_tokens": ["function", "animateMove", "(", "axis", ")", "{", "var", "t", "=", "animatedMove", "[", "axis", "]", ";", "var", "normTime", "=", "Math", ".", "min", "(", "1", ",", "Math", ".", "max", "(", "(", "Date", ".", "now", "(", ")", "-", "t", ".", "startTime", ")", "/", "1000", "/", "(", "t", ".", "duration", "/", "1000", ")", ",", "0", ")", ")", ";", "var", "result", "=", "t", ".", "startPosition", "+", "config", ".", "animationTimingFunction", "(", "normTime", ")", "*", "(", "t", ".", "endPosition", "-", "t", ".", "startPosition", ")", ";", "if", "(", "(", "t", ".", "endPosition", ">", "t", ".", "startPosition", "&&", "result", ">=", "t", ".", "endPosition", ")", "||", "(", "t", ".", "endPosition", "<", "t", ".", "startPosition", "&&", "result", "<=", "t", ".", "endPosition", ")", "||", "t", ".", "endPosition", "===", "t", ".", "startPosition", ")", "{", "result", "=", "t", ".", "endPosition", ";", "speed", "[", "axis", "]", "=", "0", ";", "delete", "animatedMove", "[", "axis", "]", ";", "}", "config", "[", "axis", "]", "=", "result", ";", "}"], "docstring": "Animates moves.\n@param {string} axis - Axis to animate\n@private", "docstring_tokens": ["Animates", "moves", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1298-L1310", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "animate", "original_string": "function animate() {\n render();\n if (autoRotateStart)\n clearTimeout(autoRotateStart);\n if (isUserInteracting || orientation === true) {\n requestAnimationFrame(animate);\n } else if (keysDown[0] || keysDown[1] || keysDown[2] || keysDown[3] ||\n keysDown[4] || keysDown[5] || keysDown[6] || keysDown[7] ||\n keysDown[8] || keysDown[9] || config.autoRotate ||\n animatedMove.pitch || animatedMove.yaw || animatedMove.hfov ||\n Math.abs(speed.yaw) > 0.01 || Math.abs(speed.pitch) > 0.01 ||\n Math.abs(speed.hfov) > 0.01) {\n\n keyRepeat();\n if (config.autoRotateInactivityDelay >= 0 && autoRotateSpeed &&\n Date.now() - latestInteraction > config.autoRotateInactivityDelay &&\n !config.autoRotate) {\n config.autoRotate = autoRotateSpeed;\n _this.lookAt(origPitch, undefined, origHfov, 3000);\n }\n requestAnimationFrame(animate);\n } else if (renderer && (renderer.isLoading() || (config.dynamic === true && update))) {\n requestAnimationFrame(animate);\n } else {\n fireEvent('animatefinished', {pitch: _this.getPitch(), yaw: _this.getYaw(), hfov: _this.getHfov()});\n animating = false;\n prevTime = undefined;\n var autoRotateStartTime = config.autoRotateInactivityDelay -\n (Date.now() - latestInteraction);\n if (autoRotateStartTime > 0) {\n autoRotateStart = setTimeout(function() {\n config.autoRotate = autoRotateSpeed;\n _this.lookAt(origPitch, undefined, origHfov, 3000);\n animateInit();\n }, autoRotateStartTime);\n } else if (config.autoRotateInactivityDelay >= 0 && autoRotateSpeed) {\n config.autoRotate = autoRotateSpeed;\n _this.lookAt(origPitch, undefined, origHfov, 3000);\n animateInit();\n }\n }\n}", "language": "javascript", "code": "function animate() {\n render();\n if (autoRotateStart)\n clearTimeout(autoRotateStart);\n if (isUserInteracting || orientation === true) {\n requestAnimationFrame(animate);\n } else if (keysDown[0] || keysDown[1] || keysDown[2] || keysDown[3] ||\n keysDown[4] || keysDown[5] || keysDown[6] || keysDown[7] ||\n keysDown[8] || keysDown[9] || config.autoRotate ||\n animatedMove.pitch || animatedMove.yaw || animatedMove.hfov ||\n Math.abs(speed.yaw) > 0.01 || Math.abs(speed.pitch) > 0.01 ||\n Math.abs(speed.hfov) > 0.01) {\n\n keyRepeat();\n if (config.autoRotateInactivityDelay >= 0 && autoRotateSpeed &&\n Date.now() - latestInteraction > config.autoRotateInactivityDelay &&\n !config.autoRotate) {\n config.autoRotate = autoRotateSpeed;\n _this.lookAt(origPitch, undefined, origHfov, 3000);\n }\n requestAnimationFrame(animate);\n } else if (renderer && (renderer.isLoading() || (config.dynamic === true && update))) {\n requestAnimationFrame(animate);\n } else {\n fireEvent('animatefinished', {pitch: _this.getPitch(), yaw: _this.getYaw(), hfov: _this.getHfov()});\n animating = false;\n prevTime = undefined;\n var autoRotateStartTime = config.autoRotateInactivityDelay -\n (Date.now() - latestInteraction);\n if (autoRotateStartTime > 0) {\n autoRotateStart = setTimeout(function() {\n config.autoRotate = autoRotateSpeed;\n _this.lookAt(origPitch, undefined, origHfov, 3000);\n animateInit();\n }, autoRotateStartTime);\n } else if (config.autoRotateInactivityDelay >= 0 && autoRotateSpeed) {\n config.autoRotate = autoRotateSpeed;\n _this.lookAt(origPitch, undefined, origHfov, 3000);\n animateInit();\n }\n }\n}", "code_tokens": ["function", "animate", "(", ")", "{", "render", "(", ")", ";", "if", "(", "autoRotateStart", ")", "clearTimeout", "(", "autoRotateStart", ")", ";", "if", "(", "isUserInteracting", "||", "orientation", "===", "true", ")", "{", "requestAnimationFrame", "(", "animate", ")", ";", "}", "else", "if", "(", "keysDown", "[", "0", "]", "||", "keysDown", "[", "1", "]", "||", "keysDown", "[", "2", "]", "||", "keysDown", "[", "3", "]", "||", "keysDown", "[", "4", "]", "||", "keysDown", "[", "5", "]", "||", "keysDown", "[", "6", "]", "||", "keysDown", "[", "7", "]", "||", "keysDown", "[", "8", "]", "||", "keysDown", "[", "9", "]", "||", "config", ".", "autoRotate", "||", "animatedMove", ".", "pitch", "||", "animatedMove", ".", "yaw", "||", "animatedMove", ".", "hfov", "||", "Math", ".", "abs", "(", "speed", ".", "yaw", ")", ">", "0.01", "||", "Math", ".", "abs", "(", "speed", ".", "pitch", ")", ">", "0.01", "||", "Math", ".", "abs", "(", "speed", ".", "hfov", ")", ">", "0.01", ")", "{", "keyRepeat", "(", ")", ";", "if", "(", "config", ".", "autoRotateInactivityDelay", ">=", "0", "&&", "autoRotateSpeed", "&&", "Date", ".", "now", "(", ")", "-", "latestInteraction", ">", "config", ".", "autoRotateInactivityDelay", "&&", "!", "config", ".", "autoRotate", ")", "{", "config", ".", "autoRotate", "=", "autoRotateSpeed", ";", "_this", ".", "lookAt", "(", "origPitch", ",", "undefined", ",", "origHfov", ",", "3000", ")", ";", "}", "requestAnimationFrame", "(", "animate", ")", ";", "}", "else", "if", "(", "renderer", "&&", "(", "renderer", ".", "isLoading", "(", ")", "||", "(", "config", ".", "dynamic", "===", "true", "&&", "update", ")", ")", ")", "{", "requestAnimationFrame", "(", "animate", ")", ";", "}", "else", "{", "fireEvent", "(", "'animatefinished'", ",", "{", "pitch", ":", "_this", ".", "getPitch", "(", ")", ",", "yaw", ":", "_this", ".", "getYaw", "(", ")", ",", "hfov", ":", "_this", ".", "getHfov", "(", ")", "}", ")", ";", "animating", "=", "false", ";", "prevTime", "=", "undefined", ";", "var", "autoRotateStartTime", "=", "config", ".", "autoRotateInactivityDelay", "-", "(", "Date", ".", "now", "(", ")", "-", "latestInteraction", ")", ";", "if", "(", "autoRotateStartTime", ">", "0", ")", "{", "autoRotateStart", "=", "setTimeout", "(", "function", "(", ")", "{", "config", ".", "autoRotate", "=", "autoRotateSpeed", ";", "_this", ".", "lookAt", "(", "origPitch", ",", "undefined", ",", "origHfov", ",", "3000", ")", ";", "animateInit", "(", ")", ";", "}", ",", "autoRotateStartTime", ")", ";", "}", "else", "if", "(", "config", ".", "autoRotateInactivityDelay", ">=", "0", "&&", "autoRotateSpeed", ")", "{", "config", ".", "autoRotate", "=", "autoRotateSpeed", ";", "_this", ".", "lookAt", "(", "origPitch", ",", "undefined", ",", "origHfov", ",", "3000", ")", ";", "animateInit", "(", ")", ";", "}", "}", "}"], "docstring": "Animates view, using requestAnimationFrame to trigger rendering.\n@private", "docstring_tokens": ["Animates", "view", "using", "requestAnimationFrame", "to", "trigger", "rendering", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1351-L1392", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "taitBryanToQuaternion", "original_string": "function taitBryanToQuaternion(alpha, beta, gamma) {\n var r = [beta ? beta * Math.PI / 180 / 2 : 0,\n gamma ? gamma * Math.PI / 180 / 2 : 0,\n alpha ? alpha * Math.PI / 180 / 2 : 0];\n var c = [Math.cos(r[0]), Math.cos(r[1]), Math.cos(r[2])],\n s = [Math.sin(r[0]), Math.sin(r[1]), Math.sin(r[2])];\n\n return new Quaternion(c[0]*c[1]*c[2] - s[0]*s[1]*s[2],\n s[0]*c[1]*c[2] - c[0]*s[1]*s[2],\n c[0]*s[1]*c[2] + s[0]*c[1]*s[2],\n c[0]*c[1]*s[2] + s[0]*s[1]*c[2]);\n}", "language": "javascript", "code": "function taitBryanToQuaternion(alpha, beta, gamma) {\n var r = [beta ? beta * Math.PI / 180 / 2 : 0,\n gamma ? gamma * Math.PI / 180 / 2 : 0,\n alpha ? alpha * Math.PI / 180 / 2 : 0];\n var c = [Math.cos(r[0]), Math.cos(r[1]), Math.cos(r[2])],\n s = [Math.sin(r[0]), Math.sin(r[1]), Math.sin(r[2])];\n\n return new Quaternion(c[0]*c[1]*c[2] - s[0]*s[1]*s[2],\n s[0]*c[1]*c[2] - c[0]*s[1]*s[2],\n c[0]*s[1]*c[2] + s[0]*c[1]*s[2],\n c[0]*c[1]*s[2] + s[0]*s[1]*c[2]);\n}", "code_tokens": ["function", "taitBryanToQuaternion", "(", "alpha", ",", "beta", ",", "gamma", ")", "{", "var", "r", "=", "[", "beta", "?", "beta", "*", "Math", ".", "PI", "/", "180", "/", "2", ":", "0", ",", "gamma", "?", "gamma", "*", "Math", ".", "PI", "/", "180", "/", "2", ":", "0", ",", "alpha", "?", "alpha", "*", "Math", ".", "PI", "/", "180", "/", "2", ":", "0", "]", ";", "var", "c", "=", "[", "Math", ".", "cos", "(", "r", "[", "0", "]", ")", ",", "Math", ".", "cos", "(", "r", "[", "1", "]", ")", ",", "Math", ".", "cos", "(", "r", "[", "2", "]", ")", "]", ",", "s", "=", "[", "Math", ".", "sin", "(", "r", "[", "0", "]", ")", ",", "Math", ".", "sin", "(", "r", "[", "1", "]", ")", ",", "Math", ".", "sin", "(", "r", "[", "2", "]", ")", "]", ";", "return", "new", "Quaternion", "(", "c", "[", "0", "]", "*", "c", "[", "1", "]", "*", "c", "[", "2", "]", "-", "s", "[", "0", "]", "*", "s", "[", "1", "]", "*", "s", "[", "2", "]", ",", "s", "[", "0", "]", "*", "c", "[", "1", "]", "*", "c", "[", "2", "]", "-", "c", "[", "0", "]", "*", "s", "[", "1", "]", "*", "s", "[", "2", "]", ",", "c", "[", "0", "]", "*", "s", "[", "1", "]", "*", "c", "[", "2", "]", "+", "s", "[", "0", "]", "*", "c", "[", "1", "]", "*", "s", "[", "2", "]", ",", "c", "[", "0", "]", "*", "c", "[", "1", "]", "*", "s", "[", "2", "]", "+", "s", "[", "0", "]", "*", "s", "[", "1", "]", "*", "c", "[", "2", "]", ")", ";", "}"], "docstring": "Converts device orientation API Tait-Bryan angles to a quaternion.\n@private\n@param {Number} alpha - Alpha angle (in degrees)\n@param {Number} beta - Beta angle (in degrees)\n@param {Number} gamma - Gamma angle (in degrees)\n@returns {Quaternion} Orientation quaternion", "docstring_tokens": ["Converts", "device", "orientation", "API", "Tait", "-", "Bryan", "angles", "to", "a", "quaternion", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1529-L1540", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "computeQuaternion", "original_string": "function computeQuaternion(alpha, beta, gamma) {\n // Convert Tait-Bryan angles to quaternion\n var quaternion = taitBryanToQuaternion(alpha, beta, gamma);\n // Apply world transform\n quaternion = quaternion.multiply(new Quaternion(Math.sqrt(0.5), -Math.sqrt(0.5), 0, 0));\n // Apply screen transform\n var angle = window.orientation ? -window.orientation * Math.PI / 180 / 2 : 0;\n return quaternion.multiply(new Quaternion(Math.cos(angle), 0, -Math.sin(angle), 0));\n}", "language": "javascript", "code": "function computeQuaternion(alpha, beta, gamma) {\n // Convert Tait-Bryan angles to quaternion\n var quaternion = taitBryanToQuaternion(alpha, beta, gamma);\n // Apply world transform\n quaternion = quaternion.multiply(new Quaternion(Math.sqrt(0.5), -Math.sqrt(0.5), 0, 0));\n // Apply screen transform\n var angle = window.orientation ? -window.orientation * Math.PI / 180 / 2 : 0;\n return quaternion.multiply(new Quaternion(Math.cos(angle), 0, -Math.sin(angle), 0));\n}", "code_tokens": ["function", "computeQuaternion", "(", "alpha", ",", "beta", ",", "gamma", ")", "{", "var", "quaternion", "=", "taitBryanToQuaternion", "(", "alpha", ",", "beta", ",", "gamma", ")", ";", "quaternion", "=", "quaternion", ".", "multiply", "(", "new", "Quaternion", "(", "Math", ".", "sqrt", "(", "0.5", ")", ",", "-", "Math", ".", "sqrt", "(", "0.5", ")", ",", "0", ",", "0", ")", ")", ";", "var", "angle", "=", "window", ".", "orientation", "?", "-", "window", ".", "orientation", "*", "Math", ".", "PI", "/", "180", "/", "2", ":", "0", ";", "return", "quaternion", ".", "multiply", "(", "new", "Quaternion", "(", "Math", ".", "cos", "(", "angle", ")", ",", "0", ",", "-", "Math", ".", "sin", "(", "angle", ")", ",", "0", ")", ")", ";", "}"], "docstring": "Computes current device orientation quaternion from device orientation API\nTait-Bryan angles.\n@private\n@param {Number} alpha - Alpha angle (in degrees)\n@param {Number} beta - Beta angle (in degrees)\n@param {Number} gamma - Gamma angle (in degrees)\n@returns {Quaternion} Orientation quaternion", "docstring_tokens": ["Computes", "current", "device", "orientation", "quaternion", "from", "device", "orientation", "API", "Tait", "-", "Bryan", "angles", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1551-L1559", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "orientationListener", "original_string": "function orientationListener(e) {\n var q = computeQuaternion(e.alpha, e.beta, e.gamma).toEulerAngles();\n if (typeof(orientation) == 'number' && orientation < 10) {\n // This kludge is necessary because iOS sometimes provides a few stale\n // device orientation events when the listener is removed and then\n // readded. Thus, we skip the first 10 events to prevent this from\n // causing problems.\n orientation += 1;\n } else if (orientation === 10) {\n // Record starting yaw to prevent jumping\n orientationYawOffset = q[2] / Math.PI * 180 + config.yaw;\n orientation = true;\n requestAnimationFrame(animate);\n } else {\n config.pitch = q[0] / Math.PI * 180;\n config.roll = -q[1] / Math.PI * 180;\n config.yaw = -q[2] / Math.PI * 180 + orientationYawOffset;\n }\n}", "language": "javascript", "code": "function orientationListener(e) {\n var q = computeQuaternion(e.alpha, e.beta, e.gamma).toEulerAngles();\n if (typeof(orientation) == 'number' && orientation < 10) {\n // This kludge is necessary because iOS sometimes provides a few stale\n // device orientation events when the listener is removed and then\n // readded. Thus, we skip the first 10 events to prevent this from\n // causing problems.\n orientation += 1;\n } else if (orientation === 10) {\n // Record starting yaw to prevent jumping\n orientationYawOffset = q[2] / Math.PI * 180 + config.yaw;\n orientation = true;\n requestAnimationFrame(animate);\n } else {\n config.pitch = q[0] / Math.PI * 180;\n config.roll = -q[1] / Math.PI * 180;\n config.yaw = -q[2] / Math.PI * 180 + orientationYawOffset;\n }\n}", "code_tokens": ["function", "orientationListener", "(", "e", ")", "{", "var", "q", "=", "computeQuaternion", "(", "e", ".", "alpha", ",", "e", ".", "beta", ",", "e", ".", "gamma", ")", ".", "toEulerAngles", "(", ")", ";", "if", "(", "typeof", "(", "orientation", ")", "==", "'number'", "&&", "orientation", "<", "10", ")", "{", "orientation", "+=", "1", ";", "}", "else", "if", "(", "orientation", "===", "10", ")", "{", "orientationYawOffset", "=", "q", "[", "2", "]", "/", "Math", ".", "PI", "*", "180", "+", "config", ".", "yaw", ";", "orientation", "=", "true", ";", "requestAnimationFrame", "(", "animate", ")", ";", "}", "else", "{", "config", ".", "pitch", "=", "q", "[", "0", "]", "/", "Math", ".", "PI", "*", "180", ";", "config", ".", "roll", "=", "-", "q", "[", "1", "]", "/", "Math", ".", "PI", "*", "180", ";", "config", ".", "yaw", "=", "-", "q", "[", "2", "]", "/", "Math", ".", "PI", "*", "180", "+", "orientationYawOffset", ";", "}", "}"], "docstring": "Event handler for device orientation API. Controls pointing.\n@private\n@param {DeviceOrientationEvent} event - Device orientation event.", "docstring_tokens": ["Event", "handler", "for", "device", "orientation", "API", ".", "Controls", "pointing", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1566-L1584", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "renderInit", "original_string": "function renderInit() {\n try {\n var params = {};\n if (config.horizonPitch !== undefined)\n params.horizonPitch = config.horizonPitch * Math.PI / 180;\n if (config.horizonRoll !== undefined)\n params.horizonRoll = config.horizonRoll * Math.PI / 180;\n if (config.backgroundColor !== undefined)\n params.backgroundColor = config.backgroundColor;\n renderer.init(panoImage, config.type, config.dynamic, config.haov * Math.PI / 180, config.vaov * Math.PI / 180, config.vOffset * Math.PI / 180, renderInitCallback, params);\n if (config.dynamic !== true) {\n // Allow image to be garbage collected\n panoImage = undefined;\n }\n } catch(event) {\n // Panorama not loaded\n \n // Display error if there is a bad texture\n if (event.type == 'webgl error' || event.type == 'no webgl') {\n anError();\n } else if (event.type == 'webgl size error') {\n anError(config.strings.textureSizeError.replace('%s', event.width).replace('%s', event.maxWidth));\n } else {\n anError(config.strings.unknownError);\n throw event;\n }\n }\n}", "language": "javascript", "code": "function renderInit() {\n try {\n var params = {};\n if (config.horizonPitch !== undefined)\n params.horizonPitch = config.horizonPitch * Math.PI / 180;\n if (config.horizonRoll !== undefined)\n params.horizonRoll = config.horizonRoll * Math.PI / 180;\n if (config.backgroundColor !== undefined)\n params.backgroundColor = config.backgroundColor;\n renderer.init(panoImage, config.type, config.dynamic, config.haov * Math.PI / 180, config.vaov * Math.PI / 180, config.vOffset * Math.PI / 180, renderInitCallback, params);\n if (config.dynamic !== true) {\n // Allow image to be garbage collected\n panoImage = undefined;\n }\n } catch(event) {\n // Panorama not loaded\n \n // Display error if there is a bad texture\n if (event.type == 'webgl error' || event.type == 'no webgl') {\n anError();\n } else if (event.type == 'webgl size error') {\n anError(config.strings.textureSizeError.replace('%s', event.width).replace('%s', event.maxWidth));\n } else {\n anError(config.strings.unknownError);\n throw event;\n }\n }\n}", "code_tokens": ["function", "renderInit", "(", ")", "{", "try", "{", "var", "params", "=", "{", "}", ";", "if", "(", "config", ".", "horizonPitch", "!==", "undefined", ")", "params", ".", "horizonPitch", "=", "config", ".", "horizonPitch", "*", "Math", ".", "PI", "/", "180", ";", "if", "(", "config", ".", "horizonRoll", "!==", "undefined", ")", "params", ".", "horizonRoll", "=", "config", ".", "horizonRoll", "*", "Math", ".", "PI", "/", "180", ";", "if", "(", "config", ".", "backgroundColor", "!==", "undefined", ")", "params", ".", "backgroundColor", "=", "config", ".", "backgroundColor", ";", "renderer", ".", "init", "(", "panoImage", ",", "config", ".", "type", ",", "config", ".", "dynamic", ",", "config", ".", "haov", "*", "Math", ".", "PI", "/", "180", ",", "config", ".", "vaov", "*", "Math", ".", "PI", "/", "180", ",", "config", ".", "vOffset", "*", "Math", ".", "PI", "/", "180", ",", "renderInitCallback", ",", "params", ")", ";", "if", "(", "config", ".", "dynamic", "!==", "true", ")", "{", "panoImage", "=", "undefined", ";", "}", "}", "catch", "(", "event", ")", "{", "if", "(", "event", ".", "type", "==", "'webgl error'", "||", "event", ".", "type", "==", "'no webgl'", ")", "{", "anError", "(", ")", ";", "}", "else", "if", "(", "event", ".", "type", "==", "'webgl size error'", ")", "{", "anError", "(", "config", ".", "strings", ".", "textureSizeError", ".", "replace", "(", "'%s'", ",", "event", ".", "width", ")", ".", "replace", "(", "'%s'", ",", "event", ".", "maxWidth", ")", ")", ";", "}", "else", "{", "anError", "(", "config", ".", "strings", ".", "unknownError", ")", ";", "throw", "event", ";", "}", "}", "}"], "docstring": "Initializes renderer.\n@private", "docstring_tokens": ["Initializes", "renderer", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1590-L1617", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "renderInitCallback", "original_string": "function renderInitCallback() {\n // Fade if specified\n if (config.sceneFadeDuration && renderer.fadeImg !== undefined) {\n renderer.fadeImg.style.opacity = 0;\n // Remove image\n var fadeImg = renderer.fadeImg;\n delete renderer.fadeImg;\n setTimeout(function() {\n renderContainer.removeChild(fadeImg);\n fireEvent('scenechangefadedone');\n }, config.sceneFadeDuration);\n }\n \n // Show compass if applicable\n if (config.compass) {\n compass.style.display = 'inline';\n } else {\n compass.style.display = 'none';\n }\n \n // Show hotspots\n createHotSpots();\n \n // Hide loading display\n infoDisplay.load.box.style.display = 'none';\n if (preview !== undefined) {\n renderContainer.removeChild(preview);\n preview = undefined;\n }\n loaded = true;\n\n fireEvent('load');\n \n animateInit();\n}", "language": "javascript", "code": "function renderInitCallback() {\n // Fade if specified\n if (config.sceneFadeDuration && renderer.fadeImg !== undefined) {\n renderer.fadeImg.style.opacity = 0;\n // Remove image\n var fadeImg = renderer.fadeImg;\n delete renderer.fadeImg;\n setTimeout(function() {\n renderContainer.removeChild(fadeImg);\n fireEvent('scenechangefadedone');\n }, config.sceneFadeDuration);\n }\n \n // Show compass if applicable\n if (config.compass) {\n compass.style.display = 'inline';\n } else {\n compass.style.display = 'none';\n }\n \n // Show hotspots\n createHotSpots();\n \n // Hide loading display\n infoDisplay.load.box.style.display = 'none';\n if (preview !== undefined) {\n renderContainer.removeChild(preview);\n preview = undefined;\n }\n loaded = true;\n\n fireEvent('load');\n \n animateInit();\n}", "code_tokens": ["function", "renderInitCallback", "(", ")", "{", "if", "(", "config", ".", "sceneFadeDuration", "&&", "renderer", ".", "fadeImg", "!==", "undefined", ")", "{", "renderer", ".", "fadeImg", ".", "style", ".", "opacity", "=", "0", ";", "var", "fadeImg", "=", "renderer", ".", "fadeImg", ";", "delete", "renderer", ".", "fadeImg", ";", "setTimeout", "(", "function", "(", ")", "{", "renderContainer", ".", "removeChild", "(", "fadeImg", ")", ";", "fireEvent", "(", "'scenechangefadedone'", ")", ";", "}", ",", "config", ".", "sceneFadeDuration", ")", ";", "}", "if", "(", "config", ".", "compass", ")", "{", "compass", ".", "style", ".", "display", "=", "'inline'", ";", "}", "else", "{", "compass", ".", "style", ".", "display", "=", "'none'", ";", "}", "createHotSpots", "(", ")", ";", "infoDisplay", ".", "load", ".", "box", ".", "style", ".", "display", "=", "'none'", ";", "if", "(", "preview", "!==", "undefined", ")", "{", "renderContainer", ".", "removeChild", "(", "preview", ")", ";", "preview", "=", "undefined", ";", "}", "loaded", "=", "true", ";", "fireEvent", "(", "'load'", ")", ";", "animateInit", "(", ")", ";", "}"], "docstring": "Triggered when render initialization finishes. Handles fading between\nscenes as well as showing the compass and hotspots and hiding the loading\ndisplay.\n@private", "docstring_tokens": ["Triggered", "when", "render", "initialization", "finishes", ".", "Handles", "fading", "between", "scenes", "as", "well", "as", "showing", "the", "compass", "and", "hotspots", "and", "hiding", "the", "loading", "display", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1625-L1659", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "createHotSpots", "original_string": "function createHotSpots() {\n if (hotspotsCreated) return;\n\n if (!config.hotSpots) {\n config.hotSpots = [];\n } else {\n // Sort by pitch so tooltip is never obscured by another hot spot\n config.hotSpots = config.hotSpots.sort(function(a, b) {\n return a.pitch < b.pitch;\n });\n config.hotSpots.forEach(createHotSpot);\n }\n hotspotsCreated = true;\n renderHotSpots();\n}", "language": "javascript", "code": "function createHotSpots() {\n if (hotspotsCreated) return;\n\n if (!config.hotSpots) {\n config.hotSpots = [];\n } else {\n // Sort by pitch so tooltip is never obscured by another hot spot\n config.hotSpots = config.hotSpots.sort(function(a, b) {\n return a.pitch < b.pitch;\n });\n config.hotSpots.forEach(createHotSpot);\n }\n hotspotsCreated = true;\n renderHotSpots();\n}", "code_tokens": ["function", "createHotSpots", "(", ")", "{", "if", "(", "hotspotsCreated", ")", "return", ";", "if", "(", "!", "config", ".", "hotSpots", ")", "{", "config", ".", "hotSpots", "=", "[", "]", ";", "}", "else", "{", "config", ".", "hotSpots", "=", "config", ".", "hotSpots", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", ".", "pitch", "<", "b", ".", "pitch", ";", "}", ")", ";", "config", ".", "hotSpots", ".", "forEach", "(", "createHotSpot", ")", ";", "}", "hotspotsCreated", "=", "true", ";", "renderHotSpots", "(", ")", ";", "}"], "docstring": "Creates hot spot elements for the current scene.\n@private", "docstring_tokens": ["Creates", "hot", "spot", "elements", "for", "the", "current", "scene", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1760-L1774", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "destroyHotSpots", "original_string": "function destroyHotSpots() {\n var hs = config.hotSpots;\n hotspotsCreated = false;\n delete config.hotSpots;\n if (hs) {\n for (var i = 0; i < hs.length; i++) {\n var current = hs[i].div;\n if (current) {\n while (current.parentNode && current.parentNode != renderContainer) {\n current = current.parentNode;\n }\n renderContainer.removeChild(current);\n }\n delete hs[i].div;\n }\n }\n}", "language": "javascript", "code": "function destroyHotSpots() {\n var hs = config.hotSpots;\n hotspotsCreated = false;\n delete config.hotSpots;\n if (hs) {\n for (var i = 0; i < hs.length; i++) {\n var current = hs[i].div;\n if (current) {\n while (current.parentNode && current.parentNode != renderContainer) {\n current = current.parentNode;\n }\n renderContainer.removeChild(current);\n }\n delete hs[i].div;\n }\n }\n}", "code_tokens": ["function", "destroyHotSpots", "(", ")", "{", "var", "hs", "=", "config", ".", "hotSpots", ";", "hotspotsCreated", "=", "false", ";", "delete", "config", ".", "hotSpots", ";", "if", "(", "hs", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "hs", ".", "length", ";", "i", "++", ")", "{", "var", "current", "=", "hs", "[", "i", "]", ".", "div", ";", "if", "(", "current", ")", "{", "while", "(", "current", ".", "parentNode", "&&", "current", ".", "parentNode", "!=", "renderContainer", ")", "{", "current", "=", "current", ".", "parentNode", ";", "}", "renderContainer", ".", "removeChild", "(", "current", ")", ";", "}", "delete", "hs", "[", "i", "]", ".", "div", ";", "}", "}", "}"], "docstring": "Destroys currently created hot spot elements.\n@private", "docstring_tokens": ["Destroys", "currently", "created", "hot", "spot", "elements", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1780-L1796", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "renderHotSpot", "original_string": "function renderHotSpot(hs) {\n var hsPitchSin = Math.sin(hs.pitch * Math.PI / 180),\n hsPitchCos = Math.cos(hs.pitch * Math.PI / 180),\n configPitchSin = Math.sin(config.pitch * Math.PI / 180),\n configPitchCos = Math.cos(config.pitch * Math.PI / 180),\n yawCos = Math.cos((-hs.yaw + config.yaw) * Math.PI / 180);\n var z = hsPitchSin * configPitchSin + hsPitchCos * yawCos * configPitchCos;\n if ((hs.yaw <= 90 && hs.yaw > -90 && z <= 0) ||\n ((hs.yaw > 90 || hs.yaw <= -90) && z <= 0)) {\n hs.div.style.visibility = 'hidden';\n } else {\n var yawSin = Math.sin((-hs.yaw + config.yaw) * Math.PI / 180),\n hfovTan = Math.tan(config.hfov * Math.PI / 360);\n hs.div.style.visibility = 'visible';\n // Subpixel rendering doesn't work in Firefox\n // https://bugzilla.mozilla.org/show_bug.cgi?id=739176\n var canvas = renderer.getCanvas(),\n canvasWidth = canvas.clientWidth,\n canvasHeight = canvas.clientHeight;\n var coord = [-canvasWidth / hfovTan * yawSin * hsPitchCos / z / 2,\n -canvasWidth / hfovTan * (hsPitchSin * configPitchCos -\n hsPitchCos * yawCos * configPitchSin) / z / 2];\n // Apply roll\n var rollSin = Math.sin(config.roll * Math.PI / 180),\n rollCos = Math.cos(config.roll * Math.PI / 180);\n coord = [coord[0] * rollCos - coord[1] * rollSin,\n coord[0] * rollSin + coord[1] * rollCos];\n // Apply transform\n coord[0] += (canvasWidth - hs.div.offsetWidth) / 2;\n coord[1] += (canvasHeight - hs.div.offsetHeight) / 2;\n var transform = 'translate(' + coord[0] + 'px, ' + coord[1] +\n 'px) translateZ(9999px) rotate(' + config.roll + 'deg)';\n hs.div.style.webkitTransform = transform;\n hs.div.style.MozTransform = transform;\n hs.div.style.transform = transform;\n }\n}", "language": "javascript", "code": "function renderHotSpot(hs) {\n var hsPitchSin = Math.sin(hs.pitch * Math.PI / 180),\n hsPitchCos = Math.cos(hs.pitch * Math.PI / 180),\n configPitchSin = Math.sin(config.pitch * Math.PI / 180),\n configPitchCos = Math.cos(config.pitch * Math.PI / 180),\n yawCos = Math.cos((-hs.yaw + config.yaw) * Math.PI / 180);\n var z = hsPitchSin * configPitchSin + hsPitchCos * yawCos * configPitchCos;\n if ((hs.yaw <= 90 && hs.yaw > -90 && z <= 0) ||\n ((hs.yaw > 90 || hs.yaw <= -90) && z <= 0)) {\n hs.div.style.visibility = 'hidden';\n } else {\n var yawSin = Math.sin((-hs.yaw + config.yaw) * Math.PI / 180),\n hfovTan = Math.tan(config.hfov * Math.PI / 360);\n hs.div.style.visibility = 'visible';\n // Subpixel rendering doesn't work in Firefox\n // https://bugzilla.mozilla.org/show_bug.cgi?id=739176\n var canvas = renderer.getCanvas(),\n canvasWidth = canvas.clientWidth,\n canvasHeight = canvas.clientHeight;\n var coord = [-canvasWidth / hfovTan * yawSin * hsPitchCos / z / 2,\n -canvasWidth / hfovTan * (hsPitchSin * configPitchCos -\n hsPitchCos * yawCos * configPitchSin) / z / 2];\n // Apply roll\n var rollSin = Math.sin(config.roll * Math.PI / 180),\n rollCos = Math.cos(config.roll * Math.PI / 180);\n coord = [coord[0] * rollCos - coord[1] * rollSin,\n coord[0] * rollSin + coord[1] * rollCos];\n // Apply transform\n coord[0] += (canvasWidth - hs.div.offsetWidth) / 2;\n coord[1] += (canvasHeight - hs.div.offsetHeight) / 2;\n var transform = 'translate(' + coord[0] + 'px, ' + coord[1] +\n 'px) translateZ(9999px) rotate(' + config.roll + 'deg)';\n hs.div.style.webkitTransform = transform;\n hs.div.style.MozTransform = transform;\n hs.div.style.transform = transform;\n }\n}", "code_tokens": ["function", "renderHotSpot", "(", "hs", ")", "{", "var", "hsPitchSin", "=", "Math", ".", "sin", "(", "hs", ".", "pitch", "*", "Math", ".", "PI", "/", "180", ")", ",", "hsPitchCos", "=", "Math", ".", "cos", "(", "hs", ".", "pitch", "*", "Math", ".", "PI", "/", "180", ")", ",", "configPitchSin", "=", "Math", ".", "sin", "(", "config", ".", "pitch", "*", "Math", ".", "PI", "/", "180", ")", ",", "configPitchCos", "=", "Math", ".", "cos", "(", "config", ".", "pitch", "*", "Math", ".", "PI", "/", "180", ")", ",", "yawCos", "=", "Math", ".", "cos", "(", "(", "-", "hs", ".", "yaw", "+", "config", ".", "yaw", ")", "*", "Math", ".", "PI", "/", "180", ")", ";", "var", "z", "=", "hsPitchSin", "*", "configPitchSin", "+", "hsPitchCos", "*", "yawCos", "*", "configPitchCos", ";", "if", "(", "(", "hs", ".", "yaw", "<=", "90", "&&", "hs", ".", "yaw", ">", "-", "90", "&&", "z", "<=", "0", ")", "||", "(", "(", "hs", ".", "yaw", ">", "90", "||", "hs", ".", "yaw", "<=", "-", "90", ")", "&&", "z", "<=", "0", ")", ")", "{", "hs", ".", "div", ".", "style", ".", "visibility", "=", "'hidden'", ";", "}", "else", "{", "var", "yawSin", "=", "Math", ".", "sin", "(", "(", "-", "hs", ".", "yaw", "+", "config", ".", "yaw", ")", "*", "Math", ".", "PI", "/", "180", ")", ",", "hfovTan", "=", "Math", ".", "tan", "(", "config", ".", "hfov", "*", "Math", ".", "PI", "/", "360", ")", ";", "hs", ".", "div", ".", "style", ".", "visibility", "=", "'visible'", ";", "var", "canvas", "=", "renderer", ".", "getCanvas", "(", ")", ",", "canvasWidth", "=", "canvas", ".", "clientWidth", ",", "canvasHeight", "=", "canvas", ".", "clientHeight", ";", "var", "coord", "=", "[", "-", "canvasWidth", "/", "hfovTan", "*", "yawSin", "*", "hsPitchCos", "/", "z", "/", "2", ",", "-", "canvasWidth", "/", "hfovTan", "*", "(", "hsPitchSin", "*", "configPitchCos", "-", "hsPitchCos", "*", "yawCos", "*", "configPitchSin", ")", "/", "z", "/", "2", "]", ";", "var", "rollSin", "=", "Math", ".", "sin", "(", "config", ".", "roll", "*", "Math", ".", "PI", "/", "180", ")", ",", "rollCos", "=", "Math", ".", "cos", "(", "config", ".", "roll", "*", "Math", ".", "PI", "/", "180", ")", ";", "coord", "=", "[", "coord", "[", "0", "]", "*", "rollCos", "-", "coord", "[", "1", "]", "*", "rollSin", ",", "coord", "[", "0", "]", "*", "rollSin", "+", "coord", "[", "1", "]", "*", "rollCos", "]", ";", "coord", "[", "0", "]", "+=", "(", "canvasWidth", "-", "hs", ".", "div", ".", "offsetWidth", ")", "/", "2", ";", "coord", "[", "1", "]", "+=", "(", "canvasHeight", "-", "hs", ".", "div", ".", "offsetHeight", ")", "/", "2", ";", "var", "transform", "=", "'translate('", "+", "coord", "[", "0", "]", "+", "'px, '", "+", "coord", "[", "1", "]", "+", "'px) translateZ(9999px) rotate('", "+", "config", ".", "roll", "+", "'deg)'", ";", "hs", ".", "div", ".", "style", ".", "webkitTransform", "=", "transform", ";", "hs", ".", "div", ".", "style", ".", "MozTransform", "=", "transform", ";", "hs", ".", "div", ".", "style", ".", "transform", "=", "transform", ";", "}", "}"], "docstring": "Renders hot spot, updating its position and visibility.\n@private", "docstring_tokens": ["Renders", "hot", "spot", "updating", "its", "position", "and", "visibility", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1802-L1838", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "mergeConfig", "original_string": "function mergeConfig(sceneId) {\n config = {};\n var k, s;\n var photoSphereExcludes = ['haov', 'vaov', 'vOffset', 'northOffset', 'horizonPitch', 'horizonRoll'];\n specifiedPhotoSphereExcludes = [];\n \n // Merge default config\n for (k in defaultConfig) {\n if (defaultConfig.hasOwnProperty(k)) {\n config[k] = defaultConfig[k];\n }\n }\n \n // Merge default scene config\n for (k in initialConfig.default) {\n if (initialConfig.default.hasOwnProperty(k)) {\n if (k == 'strings') {\n for (s in initialConfig.default.strings) {\n if (initialConfig.default.strings.hasOwnProperty(s)) {\n config.strings[s] = escapeHTML(initialConfig.default.strings[s]);\n }\n }\n } else {\n config[k] = initialConfig.default[k];\n if (photoSphereExcludes.indexOf(k) >= 0) {\n specifiedPhotoSphereExcludes.push(k);\n }\n }\n }\n }\n \n // Merge current scene config\n if ((sceneId !== null) && (sceneId !== '') && (initialConfig.scenes) && (initialConfig.scenes[sceneId])) {\n var scene = initialConfig.scenes[sceneId];\n for (k in scene) {\n if (scene.hasOwnProperty(k)) {\n if (k == 'strings') {\n for (s in scene.strings) {\n if (scene.strings.hasOwnProperty(s)) {\n config.strings[s] = escapeHTML(scene.strings[s]);\n }\n }\n } else {\n config[k] = scene[k];\n if (photoSphereExcludes.indexOf(k) >= 0) {\n specifiedPhotoSphereExcludes.push(k);\n }\n }\n }\n }\n config.scene = sceneId;\n }\n \n // Merge initial config\n for (k in initialConfig) {\n if (initialConfig.hasOwnProperty(k)) {\n if (k == 'strings') {\n for (s in initialConfig.strings) {\n if (initialConfig.strings.hasOwnProperty(s)) {\n config.strings[s] = escapeHTML(initialConfig.strings[s]);\n }\n }\n } else {\n config[k] = initialConfig[k];\n if (photoSphereExcludes.indexOf(k) >= 0) {\n specifiedPhotoSphereExcludes.push(k);\n }\n }\n }\n }\n}", "language": "javascript", "code": "function mergeConfig(sceneId) {\n config = {};\n var k, s;\n var photoSphereExcludes = ['haov', 'vaov', 'vOffset', 'northOffset', 'horizonPitch', 'horizonRoll'];\n specifiedPhotoSphereExcludes = [];\n \n // Merge default config\n for (k in defaultConfig) {\n if (defaultConfig.hasOwnProperty(k)) {\n config[k] = defaultConfig[k];\n }\n }\n \n // Merge default scene config\n for (k in initialConfig.default) {\n if (initialConfig.default.hasOwnProperty(k)) {\n if (k == 'strings') {\n for (s in initialConfig.default.strings) {\n if (initialConfig.default.strings.hasOwnProperty(s)) {\n config.strings[s] = escapeHTML(initialConfig.default.strings[s]);\n }\n }\n } else {\n config[k] = initialConfig.default[k];\n if (photoSphereExcludes.indexOf(k) >= 0) {\n specifiedPhotoSphereExcludes.push(k);\n }\n }\n }\n }\n \n // Merge current scene config\n if ((sceneId !== null) && (sceneId !== '') && (initialConfig.scenes) && (initialConfig.scenes[sceneId])) {\n var scene = initialConfig.scenes[sceneId];\n for (k in scene) {\n if (scene.hasOwnProperty(k)) {\n if (k == 'strings') {\n for (s in scene.strings) {\n if (scene.strings.hasOwnProperty(s)) {\n config.strings[s] = escapeHTML(scene.strings[s]);\n }\n }\n } else {\n config[k] = scene[k];\n if (photoSphereExcludes.indexOf(k) >= 0) {\n specifiedPhotoSphereExcludes.push(k);\n }\n }\n }\n }\n config.scene = sceneId;\n }\n \n // Merge initial config\n for (k in initialConfig) {\n if (initialConfig.hasOwnProperty(k)) {\n if (k == 'strings') {\n for (s in initialConfig.strings) {\n if (initialConfig.strings.hasOwnProperty(s)) {\n config.strings[s] = escapeHTML(initialConfig.strings[s]);\n }\n }\n } else {\n config[k] = initialConfig[k];\n if (photoSphereExcludes.indexOf(k) >= 0) {\n specifiedPhotoSphereExcludes.push(k);\n }\n }\n }\n }\n}", "code_tokens": ["function", "mergeConfig", "(", "sceneId", ")", "{", "config", "=", "{", "}", ";", "var", "k", ",", "s", ";", "var", "photoSphereExcludes", "=", "[", "'haov'", ",", "'vaov'", ",", "'vOffset'", ",", "'northOffset'", ",", "'horizonPitch'", ",", "'horizonRoll'", "]", ";", "specifiedPhotoSphereExcludes", "=", "[", "]", ";", "for", "(", "k", "in", "defaultConfig", ")", "{", "if", "(", "defaultConfig", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "config", "[", "k", "]", "=", "defaultConfig", "[", "k", "]", ";", "}", "}", "for", "(", "k", "in", "initialConfig", ".", "default", ")", "{", "if", "(", "initialConfig", ".", "default", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "if", "(", "k", "==", "'strings'", ")", "{", "for", "(", "s", "in", "initialConfig", ".", "default", ".", "strings", ")", "{", "if", "(", "initialConfig", ".", "default", ".", "strings", ".", "hasOwnProperty", "(", "s", ")", ")", "{", "config", ".", "strings", "[", "s", "]", "=", "escapeHTML", "(", "initialConfig", ".", "default", ".", "strings", "[", "s", "]", ")", ";", "}", "}", "}", "else", "{", "config", "[", "k", "]", "=", "initialConfig", ".", "default", "[", "k", "]", ";", "if", "(", "photoSphereExcludes", ".", "indexOf", "(", "k", ")", ">=", "0", ")", "{", "specifiedPhotoSphereExcludes", ".", "push", "(", "k", ")", ";", "}", "}", "}", "}", "if", "(", "(", "sceneId", "!==", "null", ")", "&&", "(", "sceneId", "!==", "''", ")", "&&", "(", "initialConfig", ".", "scenes", ")", "&&", "(", "initialConfig", ".", "scenes", "[", "sceneId", "]", ")", ")", "{", "var", "scene", "=", "initialConfig", ".", "scenes", "[", "sceneId", "]", ";", "for", "(", "k", "in", "scene", ")", "{", "if", "(", "scene", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "if", "(", "k", "==", "'strings'", ")", "{", "for", "(", "s", "in", "scene", ".", "strings", ")", "{", "if", "(", "scene", ".", "strings", ".", "hasOwnProperty", "(", "s", ")", ")", "{", "config", ".", "strings", "[", "s", "]", "=", "escapeHTML", "(", "scene", ".", "strings", "[", "s", "]", ")", ";", "}", "}", "}", "else", "{", "config", "[", "k", "]", "=", "scene", "[", "k", "]", ";", "if", "(", "photoSphereExcludes", ".", "indexOf", "(", "k", ")", ">=", "0", ")", "{", "specifiedPhotoSphereExcludes", ".", "push", "(", "k", ")", ";", "}", "}", "}", "}", "config", ".", "scene", "=", "sceneId", ";", "}", "for", "(", "k", "in", "initialConfig", ")", "{", "if", "(", "initialConfig", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "if", "(", "k", "==", "'strings'", ")", "{", "for", "(", "s", "in", "initialConfig", ".", "strings", ")", "{", "if", "(", "initialConfig", ".", "strings", ".", "hasOwnProperty", "(", "s", ")", ")", "{", "config", ".", "strings", "[", "s", "]", "=", "escapeHTML", "(", "initialConfig", ".", "strings", "[", "s", "]", ")", ";", "}", "}", "}", "else", "{", "config", "[", "k", "]", "=", "initialConfig", "[", "k", "]", ";", "if", "(", "photoSphereExcludes", ".", "indexOf", "(", "k", ")", ">=", "0", ")", "{", "specifiedPhotoSphereExcludes", ".", "push", "(", "k", ")", ";", "}", "}", "}", "}", "}"], "docstring": "Merges a scene configuration into the current configuration.\n@private\n@param {string} sceneId - Identifier of scene configuration to merge in.", "docstring_tokens": ["Merges", "a", "scene", "configuration", "into", "the", "current", "configuration", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L1853-L1923", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "toggleFullscreen", "original_string": "function toggleFullscreen() {\n if (loaded && !error) {\n if (!fullscreenActive) {\n try {\n if (container.requestFullscreen) {\n container.requestFullscreen();\n } else if (container.mozRequestFullScreen) {\n container.mozRequestFullScreen();\n } else if (container.msRequestFullscreen) {\n container.msRequestFullscreen();\n } else {\n container.webkitRequestFullScreen();\n }\n } catch(event) {\n // Fullscreen doesn't work\n }\n } else {\n if (document.exitFullscreen) {\n document.exitFullscreen();\n } else if (document.mozCancelFullScreen) {\n document.mozCancelFullScreen();\n } else if (document.webkitCancelFullScreen) {\n document.webkitCancelFullScreen();\n } else if (document.msExitFullscreen) {\n document.msExitFullscreen();\n }\n }\n }\n}", "language": "javascript", "code": "function toggleFullscreen() {\n if (loaded && !error) {\n if (!fullscreenActive) {\n try {\n if (container.requestFullscreen) {\n container.requestFullscreen();\n } else if (container.mozRequestFullScreen) {\n container.mozRequestFullScreen();\n } else if (container.msRequestFullscreen) {\n container.msRequestFullscreen();\n } else {\n container.webkitRequestFullScreen();\n }\n } catch(event) {\n // Fullscreen doesn't work\n }\n } else {\n if (document.exitFullscreen) {\n document.exitFullscreen();\n } else if (document.mozCancelFullScreen) {\n document.mozCancelFullScreen();\n } else if (document.webkitCancelFullScreen) {\n document.webkitCancelFullScreen();\n } else if (document.msExitFullscreen) {\n document.msExitFullscreen();\n }\n }\n }\n}", "code_tokens": ["function", "toggleFullscreen", "(", ")", "{", "if", "(", "loaded", "&&", "!", "error", ")", "{", "if", "(", "!", "fullscreenActive", ")", "{", "try", "{", "if", "(", "container", ".", "requestFullscreen", ")", "{", "container", ".", "requestFullscreen", "(", ")", ";", "}", "else", "if", "(", "container", ".", "mozRequestFullScreen", ")", "{", "container", ".", "mozRequestFullScreen", "(", ")", ";", "}", "else", "if", "(", "container", ".", "msRequestFullscreen", ")", "{", "container", ".", "msRequestFullscreen", "(", ")", ";", "}", "else", "{", "container", ".", "webkitRequestFullScreen", "(", ")", ";", "}", "}", "catch", "(", "event", ")", "{", "}", "}", "else", "{", "if", "(", "document", ".", "exitFullscreen", ")", "{", "document", ".", "exitFullscreen", "(", ")", ";", "}", "else", "if", "(", "document", ".", "mozCancelFullScreen", ")", "{", "document", ".", "mozCancelFullScreen", "(", ")", ";", "}", "else", "if", "(", "document", ".", "webkitCancelFullScreen", ")", "{", "document", ".", "webkitCancelFullScreen", "(", ")", ";", "}", "else", "if", "(", "document", ".", "msExitFullscreen", ")", "{", "document", ".", "msExitFullscreen", "(", ")", ";", "}", "}", "}", "}"], "docstring": "Toggles fullscreen mode.\n@private", "docstring_tokens": ["Toggles", "fullscreen", "mode", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L2076-L2104", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "onFullScreenChange", "original_string": "function onFullScreenChange(resize) {\n if (document.fullscreenElement || document.fullscreen || document.mozFullScreen || document.webkitIsFullScreen || document.msFullscreenElement) {\n controls.fullscreen.classList.add('pnlm-fullscreen-toggle-button-active');\n fullscreenActive = true;\n } else {\n controls.fullscreen.classList.remove('pnlm-fullscreen-toggle-button-active');\n fullscreenActive = false;\n }\n if (resize !== 'resize')\n fireEvent('fullscreenchange', fullscreenActive);\n // Resize renderer (deal with browser quirks and fixes #155)\n renderer.resize();\n setHfov(config.hfov);\n animateInit();\n}", "language": "javascript", "code": "function onFullScreenChange(resize) {\n if (document.fullscreenElement || document.fullscreen || document.mozFullScreen || document.webkitIsFullScreen || document.msFullscreenElement) {\n controls.fullscreen.classList.add('pnlm-fullscreen-toggle-button-active');\n fullscreenActive = true;\n } else {\n controls.fullscreen.classList.remove('pnlm-fullscreen-toggle-button-active');\n fullscreenActive = false;\n }\n if (resize !== 'resize')\n fireEvent('fullscreenchange', fullscreenActive);\n // Resize renderer (deal with browser quirks and fixes #155)\n renderer.resize();\n setHfov(config.hfov);\n animateInit();\n}", "code_tokens": ["function", "onFullScreenChange", "(", "resize", ")", "{", "if", "(", "document", ".", "fullscreenElement", "||", "document", ".", "fullscreen", "||", "document", ".", "mozFullScreen", "||", "document", ".", "webkitIsFullScreen", "||", "document", ".", "msFullscreenElement", ")", "{", "controls", ".", "fullscreen", ".", "classList", ".", "add", "(", "'pnlm-fullscreen-toggle-button-active'", ")", ";", "fullscreenActive", "=", "true", ";", "}", "else", "{", "controls", ".", "fullscreen", ".", "classList", ".", "remove", "(", "'pnlm-fullscreen-toggle-button-active'", ")", ";", "fullscreenActive", "=", "false", ";", "}", "if", "(", "resize", "!==", "'resize'", ")", "fireEvent", "(", "'fullscreenchange'", ",", "fullscreenActive", ")", ";", "renderer", ".", "resize", "(", ")", ";", "setHfov", "(", "config", ".", "hfov", ")", ";", "animateInit", "(", ")", ";", "}"], "docstring": "Event handler for fullscreen changes.\n@private", "docstring_tokens": ["Event", "handler", "for", "fullscreen", "changes", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L2110-L2124", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "constrainHfov", "original_string": "function constrainHfov(hfov) {\n // Keep field of view within bounds\n var minHfov = config.minHfov;\n if (config.type == 'multires' && renderer && config.multiResMinHfov) {\n minHfov = Math.min(minHfov, renderer.getCanvas().width / (config.multiRes.cubeResolution / 90 * 0.9));\n }\n if (minHfov > config.maxHfov) {\n // Don't change view if bounds don't make sense\n console.log('HFOV bounds do not make sense (minHfov > maxHfov).')\n return config.hfov;\n }\n var newHfov = config.hfov;\n if (hfov < minHfov) {\n newHfov = minHfov;\n } else if (hfov > config.maxHfov) {\n newHfov = config.maxHfov;\n } else {\n newHfov = hfov;\n }\n // Optionally avoid showing background (empty space) on top or bottom by adapting newHfov\n if (config.avoidShowingBackground && renderer) {\n var canvas = renderer.getCanvas();\n newHfov = Math.min(newHfov,\n Math.atan(Math.tan((config.maxPitch - config.minPitch) / 360 * Math.PI) /\n canvas.height * canvas.width)\n * 360 / Math.PI);\n }\n return newHfov;\n}", "language": "javascript", "code": "function constrainHfov(hfov) {\n // Keep field of view within bounds\n var minHfov = config.minHfov;\n if (config.type == 'multires' && renderer && config.multiResMinHfov) {\n minHfov = Math.min(minHfov, renderer.getCanvas().width / (config.multiRes.cubeResolution / 90 * 0.9));\n }\n if (minHfov > config.maxHfov) {\n // Don't change view if bounds don't make sense\n console.log('HFOV bounds do not make sense (minHfov > maxHfov).')\n return config.hfov;\n }\n var newHfov = config.hfov;\n if (hfov < minHfov) {\n newHfov = minHfov;\n } else if (hfov > config.maxHfov) {\n newHfov = config.maxHfov;\n } else {\n newHfov = hfov;\n }\n // Optionally avoid showing background (empty space) on top or bottom by adapting newHfov\n if (config.avoidShowingBackground && renderer) {\n var canvas = renderer.getCanvas();\n newHfov = Math.min(newHfov,\n Math.atan(Math.tan((config.maxPitch - config.minPitch) / 360 * Math.PI) /\n canvas.height * canvas.width)\n * 360 / Math.PI);\n }\n return newHfov;\n}", "code_tokens": ["function", "constrainHfov", "(", "hfov", ")", "{", "var", "minHfov", "=", "config", ".", "minHfov", ";", "if", "(", "config", ".", "type", "==", "'multires'", "&&", "renderer", "&&", "config", ".", "multiResMinHfov", ")", "{", "minHfov", "=", "Math", ".", "min", "(", "minHfov", ",", "renderer", ".", "getCanvas", "(", ")", ".", "width", "/", "(", "config", ".", "multiRes", ".", "cubeResolution", "/", "90", "*", "0.9", ")", ")", ";", "}", "if", "(", "minHfov", ">", "config", ".", "maxHfov", ")", "{", "console", ".", "log", "(", "'HFOV bounds do not make sense (minHfov > maxHfov).'", ")", "return", "config", ".", "hfov", ";", "}", "var", "newHfov", "=", "config", ".", "hfov", ";", "if", "(", "hfov", "<", "minHfov", ")", "{", "newHfov", "=", "minHfov", ";", "}", "else", "if", "(", "hfov", ">", "config", ".", "maxHfov", ")", "{", "newHfov", "=", "config", ".", "maxHfov", ";", "}", "else", "{", "newHfov", "=", "hfov", ";", "}", "if", "(", "config", ".", "avoidShowingBackground", "&&", "renderer", ")", "{", "var", "canvas", "=", "renderer", ".", "getCanvas", "(", ")", ";", "newHfov", "=", "Math", ".", "min", "(", "newHfov", ",", "Math", ".", "atan", "(", "Math", ".", "tan", "(", "(", "config", ".", "maxPitch", "-", "config", ".", "minPitch", ")", "/", "360", "*", "Math", ".", "PI", ")", "/", "canvas", ".", "height", "*", "canvas", ".", "width", ")", "*", "360", "/", "Math", ".", "PI", ")", ";", "}", "return", "newHfov", ";", "}"], "docstring": "Clamps horzontal field of view to viewer's limits.\n@private\n@param {number} hfov - Input horizontal field of view (in degrees)\n@return {number} - Clamped horizontal field of view (in degrees)", "docstring_tokens": ["Clamps", "horzontal", "field", "of", "view", "to", "viewer", "s", "limits", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L2154-L2182", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "stopAnimation", "original_string": "function stopAnimation() {\n animatedMove = {};\n autoRotateSpeed = config.autoRotate ? config.autoRotate : autoRotateSpeed;\n config.autoRotate = false;\n}", "language": "javascript", "code": "function stopAnimation() {\n animatedMove = {};\n autoRotateSpeed = config.autoRotate ? config.autoRotate : autoRotateSpeed;\n config.autoRotate = false;\n}", "code_tokens": ["function", "stopAnimation", "(", ")", "{", "animatedMove", "=", "{", "}", ";", "autoRotateSpeed", "=", "config", ".", "autoRotate", "?", "config", ".", "autoRotate", ":", "autoRotateSpeed", ";", "config", ".", "autoRotate", "=", "false", ";", "}"], "docstring": "Stops auto rotation and animated moves.\n@private", "docstring_tokens": ["Stops", "auto", "rotation", "and", "animated", "moves", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L2198-L2202", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "load", "original_string": "function load() {\n // Since WebGL error handling is very general, first we clear any error box\n // since it is a new scene and the error from previous maybe because of lacking\n // memory etc and not because of a lack of WebGL support etc\n clearError();\n loaded = false;\n\n controls.load.style.display = 'none';\n infoDisplay.load.box.style.display = 'inline';\n init();\n}", "language": "javascript", "code": "function load() {\n // Since WebGL error handling is very general, first we clear any error box\n // since it is a new scene and the error from previous maybe because of lacking\n // memory etc and not because of a lack of WebGL support etc\n clearError();\n loaded = false;\n\n controls.load.style.display = 'none';\n infoDisplay.load.box.style.display = 'inline';\n init();\n}", "code_tokens": ["function", "load", "(", ")", "{", "clearError", "(", ")", ";", "loaded", "=", "false", ";", "controls", ".", "load", ".", "style", ".", "display", "=", "'none'", ";", "infoDisplay", ".", "load", ".", "box", ".", "style", ".", "display", "=", "'inline'", ";", "init", "(", ")", ";", "}"], "docstring": "Loads panorama.\n@private", "docstring_tokens": ["Loads", "panorama", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L2208-L2218", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "loadScene", "original_string": "function loadScene(sceneId, targetPitch, targetYaw, targetHfov, fadeDone) {\n loaded = false;\n animatedMove = {};\n \n // Set up fade if specified\n var fadeImg, workingPitch, workingYaw, workingHfov;\n if (config.sceneFadeDuration && !fadeDone) {\n var data = renderer.render(config.pitch * Math.PI / 180, config.yaw * Math.PI / 180, config.hfov * Math.PI / 180, {returnImage: true});\n if (data !== undefined) {\n fadeImg = new Image();\n fadeImg.className = 'pnlm-fade-img';\n fadeImg.style.transition = 'opacity ' + (config.sceneFadeDuration / 1000) + 's';\n fadeImg.style.width = '100%';\n fadeImg.style.height = '100%';\n fadeImg.onload = function() {\n loadScene(sceneId, targetPitch, targetYaw, targetHfov, true);\n };\n fadeImg.src = data;\n renderContainer.appendChild(fadeImg);\n renderer.fadeImg = fadeImg;\n return;\n }\n }\n \n // Set new pointing\n if (targetPitch === 'same') {\n workingPitch = config.pitch;\n } else {\n workingPitch = targetPitch;\n }\n if (targetYaw === 'same') {\n workingYaw = config.yaw;\n } else if (targetYaw === 'sameAzimuth') {\n workingYaw = config.yaw + (config.northOffset || 0) - (initialConfig.scenes[sceneId].northOffset || 0);\n } else {\n workingYaw = targetYaw;\n }\n if (targetHfov === 'same') {\n workingHfov = config.hfov;\n } else {\n workingHfov = targetHfov;\n }\n \n // Destroy hot spots from previous scene\n destroyHotSpots();\n \n // Create the new config for the scene\n mergeConfig(sceneId);\n\n // Stop motion\n speed.yaw = speed.pitch = speed.hfov = 0;\n\n // Reload scene\n processOptions();\n if (workingPitch !== undefined) {\n config.pitch = workingPitch;\n }\n if (workingYaw !== undefined) {\n config.yaw = workingYaw;\n }\n if (workingHfov !== undefined) {\n config.hfov = workingHfov;\n }\n fireEvent('scenechange', sceneId);\n load();\n\n // Properly handle switching to dynamic scenes\n update = config.dynamicUpdate === true;\n if (config.dynamic) {\n panoImage = config.panorama;\n onImageLoad();\n }\n}", "language": "javascript", "code": "function loadScene(sceneId, targetPitch, targetYaw, targetHfov, fadeDone) {\n loaded = false;\n animatedMove = {};\n \n // Set up fade if specified\n var fadeImg, workingPitch, workingYaw, workingHfov;\n if (config.sceneFadeDuration && !fadeDone) {\n var data = renderer.render(config.pitch * Math.PI / 180, config.yaw * Math.PI / 180, config.hfov * Math.PI / 180, {returnImage: true});\n if (data !== undefined) {\n fadeImg = new Image();\n fadeImg.className = 'pnlm-fade-img';\n fadeImg.style.transition = 'opacity ' + (config.sceneFadeDuration / 1000) + 's';\n fadeImg.style.width = '100%';\n fadeImg.style.height = '100%';\n fadeImg.onload = function() {\n loadScene(sceneId, targetPitch, targetYaw, targetHfov, true);\n };\n fadeImg.src = data;\n renderContainer.appendChild(fadeImg);\n renderer.fadeImg = fadeImg;\n return;\n }\n }\n \n // Set new pointing\n if (targetPitch === 'same') {\n workingPitch = config.pitch;\n } else {\n workingPitch = targetPitch;\n }\n if (targetYaw === 'same') {\n workingYaw = config.yaw;\n } else if (targetYaw === 'sameAzimuth') {\n workingYaw = config.yaw + (config.northOffset || 0) - (initialConfig.scenes[sceneId].northOffset || 0);\n } else {\n workingYaw = targetYaw;\n }\n if (targetHfov === 'same') {\n workingHfov = config.hfov;\n } else {\n workingHfov = targetHfov;\n }\n \n // Destroy hot spots from previous scene\n destroyHotSpots();\n \n // Create the new config for the scene\n mergeConfig(sceneId);\n\n // Stop motion\n speed.yaw = speed.pitch = speed.hfov = 0;\n\n // Reload scene\n processOptions();\n if (workingPitch !== undefined) {\n config.pitch = workingPitch;\n }\n if (workingYaw !== undefined) {\n config.yaw = workingYaw;\n }\n if (workingHfov !== undefined) {\n config.hfov = workingHfov;\n }\n fireEvent('scenechange', sceneId);\n load();\n\n // Properly handle switching to dynamic scenes\n update = config.dynamicUpdate === true;\n if (config.dynamic) {\n panoImage = config.panorama;\n onImageLoad();\n }\n}", "code_tokens": ["function", "loadScene", "(", "sceneId", ",", "targetPitch", ",", "targetYaw", ",", "targetHfov", ",", "fadeDone", ")", "{", "loaded", "=", "false", ";", "animatedMove", "=", "{", "}", ";", "var", "fadeImg", ",", "workingPitch", ",", "workingYaw", ",", "workingHfov", ";", "if", "(", "config", ".", "sceneFadeDuration", "&&", "!", "fadeDone", ")", "{", "var", "data", "=", "renderer", ".", "render", "(", "config", ".", "pitch", "*", "Math", ".", "PI", "/", "180", ",", "config", ".", "yaw", "*", "Math", ".", "PI", "/", "180", ",", "config", ".", "hfov", "*", "Math", ".", "PI", "/", "180", ",", "{", "returnImage", ":", "true", "}", ")", ";", "if", "(", "data", "!==", "undefined", ")", "{", "fadeImg", "=", "new", "Image", "(", ")", ";", "fadeImg", ".", "className", "=", "'pnlm-fade-img'", ";", "fadeImg", ".", "style", ".", "transition", "=", "'opacity '", "+", "(", "config", ".", "sceneFadeDuration", "/", "1000", ")", "+", "'s'", ";", "fadeImg", ".", "style", ".", "width", "=", "'100%'", ";", "fadeImg", ".", "style", ".", "height", "=", "'100%'", ";", "fadeImg", ".", "onload", "=", "function", "(", ")", "{", "loadScene", "(", "sceneId", ",", "targetPitch", ",", "targetYaw", ",", "targetHfov", ",", "true", ")", ";", "}", ";", "fadeImg", ".", "src", "=", "data", ";", "renderContainer", ".", "appendChild", "(", "fadeImg", ")", ";", "renderer", ".", "fadeImg", "=", "fadeImg", ";", "return", ";", "}", "}", "if", "(", "targetPitch", "===", "'same'", ")", "{", "workingPitch", "=", "config", ".", "pitch", ";", "}", "else", "{", "workingPitch", "=", "targetPitch", ";", "}", "if", "(", "targetYaw", "===", "'same'", ")", "{", "workingYaw", "=", "config", ".", "yaw", ";", "}", "else", "if", "(", "targetYaw", "===", "'sameAzimuth'", ")", "{", "workingYaw", "=", "config", ".", "yaw", "+", "(", "config", ".", "northOffset", "||", "0", ")", "-", "(", "initialConfig", ".", "scenes", "[", "sceneId", "]", ".", "northOffset", "||", "0", ")", ";", "}", "else", "{", "workingYaw", "=", "targetYaw", ";", "}", "if", "(", "targetHfov", "===", "'same'", ")", "{", "workingHfov", "=", "config", ".", "hfov", ";", "}", "else", "{", "workingHfov", "=", "targetHfov", ";", "}", "destroyHotSpots", "(", ")", ";", "mergeConfig", "(", "sceneId", ")", ";", "speed", ".", "yaw", "=", "speed", ".", "pitch", "=", "speed", ".", "hfov", "=", "0", ";", "processOptions", "(", ")", ";", "if", "(", "workingPitch", "!==", "undefined", ")", "{", "config", ".", "pitch", "=", "workingPitch", ";", "}", "if", "(", "workingYaw", "!==", "undefined", ")", "{", "config", ".", "yaw", "=", "workingYaw", ";", "}", "if", "(", "workingHfov", "!==", "undefined", ")", "{", "config", ".", "hfov", "=", "workingHfov", ";", "}", "fireEvent", "(", "'scenechange'", ",", "sceneId", ")", ";", "load", "(", ")", ";", "update", "=", "config", ".", "dynamicUpdate", "===", "true", ";", "if", "(", "config", ".", "dynamic", ")", "{", "panoImage", "=", "config", ".", "panorama", ";", "onImageLoad", "(", ")", ";", "}", "}"], "docstring": "Loads scene.\n@private\n@param {string} sceneId - Identifier of scene configuration to merge in.\n@param {number} targetPitch - Pitch viewer should be centered on once scene loads.\n@param {number} targetYaw - Yaw viewer should be centered on once scene loads.\n@param {number} targetHfov - HFOV viewer should use once scene loads.\n@param {boolean} [fadeDone] - If `true`, fade setup is skipped.", "docstring_tokens": ["Loads", "scene", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L2229-L2301", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "stopOrientation", "original_string": "function stopOrientation() {\n window.removeEventListener('deviceorientation', orientationListener);\n controls.orientation.classList.remove('pnlm-orientation-button-active');\n orientation = false;\n}", "language": "javascript", "code": "function stopOrientation() {\n window.removeEventListener('deviceorientation', orientationListener);\n controls.orientation.classList.remove('pnlm-orientation-button-active');\n orientation = false;\n}", "code_tokens": ["function", "stopOrientation", "(", ")", "{", "window", ".", "removeEventListener", "(", "'deviceorientation'", ",", "orientationListener", ")", ";", "controls", ".", "orientation", ".", "classList", ".", "remove", "(", "'pnlm-orientation-button-active'", ")", ";", "orientation", "=", "false", ";", "}"], "docstring": "Stop using device orientation.\n@private", "docstring_tokens": ["Stop", "using", "device", "orientation", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L2307-L2311", "partition": "test"} {"repo": "mpetroff/pannellum", "path": "src/js/pannellum.js", "func_name": "fireEvent", "original_string": "function fireEvent(type) {\n if (type in externalEventListeners) {\n // Reverse iteration is useful, if event listener is removed inside its definition\n for (var i = externalEventListeners[type].length; i > 0; i--) {\n externalEventListeners[type][externalEventListeners[type].length - i].apply(null, [].slice.call(arguments, 1));\n }\n }\n}", "language": "javascript", "code": "function fireEvent(type) {\n if (type in externalEventListeners) {\n // Reverse iteration is useful, if event listener is removed inside its definition\n for (var i = externalEventListeners[type].length; i > 0; i--) {\n externalEventListeners[type][externalEventListeners[type].length - i].apply(null, [].slice.call(arguments, 1));\n }\n }\n}", "code_tokens": ["function", "fireEvent", "(", "type", ")", "{", "if", "(", "type", "in", "externalEventListeners", ")", "{", "for", "(", "var", "i", "=", "externalEventListeners", "[", "type", "]", ".", "length", ";", "i", ">", "0", ";", "i", "--", ")", "{", "externalEventListeners", "[", "type", "]", "[", "externalEventListeners", "[", "type", "]", ".", "length", "-", "i", "]", ".", "apply", "(", "null", ",", "[", "]", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "}", "}", "}"], "docstring": "Fire listeners attached to specified event.\n@private\n@param {string} [type] - Type of event to fire listeners for.", "docstring_tokens": ["Fire", "listeners", "attached", "to", "specified", "event", "."], "sha": "59893bcea4629be059ad3e59c3fa5bde438d292b", "url": "https://github.com/mpetroff/pannellum/blob/59893bcea4629be059ad3e59c3fa5bde438d292b/src/js/pannellum.js#L3037-L3044", "partition": "test"} {"repo": "typekit/webfontloader", "path": "tools/jasmine/jasmine.js", "func_name": "", "original_string": "function(latchFunction, optional_timeoutMessage, optional_timeout) {\n jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments);\n}", "language": "javascript", "code": "function(latchFunction, optional_timeoutMessage, optional_timeout) {\n jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments);\n}", "code_tokens": ["function", "(", "latchFunction", ",", "optional_timeoutMessage", ",", "optional_timeout", ")", "{", "jasmine", ".", "getEnv", "(", ")", ".", "currentSpec", ".", "waitsFor", ".", "apply", "(", "jasmine", ".", "getEnv", "(", ")", ".", "currentSpec", ",", "arguments", ")", ";", "}"], "docstring": "Waits for the latchFunction to return true before proceeding to the next block.\n\n@param {Function} latchFunction\n@param {String} optional_timeoutMessage\n@param {Number} optional_timeout", "docstring_tokens": ["Waits", "for", "the", "latchFunction", "to", "return", "true", "before", "proceeding", "to", "the", "next", "block", "."], "sha": "117e48d521d6408f78cbfe4d23923cc828fdf576", "url": "https://github.com/typekit/webfontloader/blob/117e48d521d6408f78cbfe4d23923cc828fdf576/tools/jasmine/jasmine.js#L558-L560", "partition": "test"} {"repo": "brython-dev/brython", "path": "www/src/py_dom.js", "func_name": "$getMouseOffset", "original_string": "function $getMouseOffset(target, ev){\n ev = ev || _window.event;\n var docPos = $getPosition(target);\n var mousePos = $mouseCoords(ev);\n return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};\n}", "language": "javascript", "code": "function $getMouseOffset(target, ev){\n ev = ev || _window.event;\n var docPos = $getPosition(target);\n var mousePos = $mouseCoords(ev);\n return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};\n}", "code_tokens": ["function", "$getMouseOffset", "(", "target", ",", "ev", ")", "{", "ev", "=", "ev", "||", "_window", ".", "event", ";", "var", "docPos", "=", "$getPosition", "(", "target", ")", ";", "var", "mousePos", "=", "$mouseCoords", "(", "ev", ")", ";", "return", "{", "x", ":", "mousePos", ".", "x", "-", "docPos", ".", "x", ",", "y", ":", "mousePos", ".", "y", "-", "docPos", ".", "y", "}", ";", "}"], "docstring": "cross-browser utility functions", "docstring_tokens": ["cross", "-", "browser", "utility", "functions"], "sha": "e437d320fce3c649c3028f2f7a8533eeae906440", "url": "https://github.com/brython-dev/brython/blob/e437d320fce3c649c3028f2f7a8533eeae906440/www/src/py_dom.js#L11-L16", "partition": "test"} {"repo": "brython-dev/brython", "path": "www/src/py_string.js", "func_name": "", "original_string": "function(val, flags){\n number_check(val)\n if(! flags.precision){\n if(! flags.decimal_point){\n flags.precision = 6\n }else{\n flags.precision = 0\n }\n }else{\n flags.precision = parseInt(flags.precision, 10)\n validate_precision(flags.precision)\n }\n return parseFloat(val)\n}", "language": "javascript", "code": "function(val, flags){\n number_check(val)\n if(! flags.precision){\n if(! flags.decimal_point){\n flags.precision = 6\n }else{\n flags.precision = 0\n }\n }else{\n flags.precision = parseInt(flags.precision, 10)\n validate_precision(flags.precision)\n }\n return parseFloat(val)\n}", "code_tokens": ["function", "(", "val", ",", "flags", ")", "{", "number_check", "(", "val", ")", "if", "(", "!", "flags", ".", "precision", ")", "{", "if", "(", "!", "flags", ".", "decimal_point", ")", "{", "flags", ".", "precision", "=", "6", "}", "else", "{", "flags", ".", "precision", "=", "0", "}", "}", "else", "{", "flags", ".", "precision", "=", "parseInt", "(", "flags", ".", "precision", ",", "10", ")", "validate_precision", "(", "flags", ".", "precision", ")", "}", "return", "parseFloat", "(", "val", ")", "}"], "docstring": "converts val to float and sets precision if missing", "docstring_tokens": ["converts", "val", "to", "float", "and", "sets", "precision", "if", "missing"], "sha": "e437d320fce3c649c3028f2f7a8533eeae906440", "url": "https://github.com/brython-dev/brython/blob/e437d320fce3c649c3028f2f7a8533eeae906440/www/src/py_string.js#L366-L379", "partition": "test"} {"repo": "brython-dev/brython", "path": "www/src/py_int.js", "func_name": "", "original_string": "function(self, other){\n if(_b_.isinstance(other, int)) {\n if(other.__class__ === $B.long_int){\n return $B.long_int.__sub__($B.long_int.$factory(self),\n $B.long_int.$factory(other))\n }\n other = int_value(other)\n if(self > $B.max_int32 || self < $B.min_int32 ||\n other > $B.max_int32 || other < $B.min_int32){\n return $B.long_int.__sub__($B.long_int.$factory(self),\n $B.long_int.$factory(other))\n }\n return self - other\n }\n if(_b_.isinstance(other, _b_.bool)){return self - other}\n var rsub = $B.$getattr(other, \"__rsub__\", _b_.None)\n if(rsub !== _b_.None){return rsub(self)}\n $err(\"-\", other)\n}", "language": "javascript", "code": "function(self, other){\n if(_b_.isinstance(other, int)) {\n if(other.__class__ === $B.long_int){\n return $B.long_int.__sub__($B.long_int.$factory(self),\n $B.long_int.$factory(other))\n }\n other = int_value(other)\n if(self > $B.max_int32 || self < $B.min_int32 ||\n other > $B.max_int32 || other < $B.min_int32){\n return $B.long_int.__sub__($B.long_int.$factory(self),\n $B.long_int.$factory(other))\n }\n return self - other\n }\n if(_b_.isinstance(other, _b_.bool)){return self - other}\n var rsub = $B.$getattr(other, \"__rsub__\", _b_.None)\n if(rsub !== _b_.None){return rsub(self)}\n $err(\"-\", other)\n}", "code_tokens": ["function", "(", "self", ",", "other", ")", "{", "if", "(", "_b_", ".", "isinstance", "(", "other", ",", "int", ")", ")", "{", "if", "(", "other", ".", "__class__", "===", "$B", ".", "long_int", ")", "{", "return", "$B", ".", "long_int", ".", "__sub__", "(", "$B", ".", "long_int", ".", "$factory", "(", "self", ")", ",", "$B", ".", "long_int", ".", "$factory", "(", "other", ")", ")", "}", "other", "=", "int_value", "(", "other", ")", "if", "(", "self", ">", "$B", ".", "max_int32", "||", "self", "<", "$B", ".", "min_int32", "||", "other", ">", "$B", ".", "max_int32", "||", "other", "<", "$B", ".", "min_int32", ")", "{", "return", "$B", ".", "long_int", ".", "__sub__", "(", "$B", ".", "long_int", ".", "$factory", "(", "self", ")", ",", "$B", ".", "long_int", ".", "$factory", "(", "other", ")", ")", "}", "return", "self", "-", "other", "}", "if", "(", "_b_", ".", "isinstance", "(", "other", ",", "_b_", ".", "bool", ")", ")", "{", "return", "self", "-", "other", "}", "var", "rsub", "=", "$B", ".", "$getattr", "(", "other", ",", "\"__rsub__\"", ",", "_b_", ".", "None", ")", "if", "(", "rsub", "!==", "_b_", ".", "None", ")", "{", "return", "rsub", "(", "self", ")", "}", "$err", "(", "\"-\"", ",", "other", ")", "}"], "docstring": "code for operands & | ^", "docstring_tokens": ["code", "for", "operands", "&", "|", "^"], "sha": "e437d320fce3c649c3028f2f7a8533eeae906440", "url": "https://github.com/brython-dev/brython/blob/e437d320fce3c649c3028f2f7a8533eeae906440/www/src/py_int.js#L507-L525", "partition": "test"} {"repo": "brython-dev/brython", "path": "www/src/py_int.js", "func_name": "", "original_string": "function(self, other){\n if(_b_.isinstance(other, int)){\n other = int_value(other)\n if(typeof other == \"number\"){\n var res = self.valueOf() - other.valueOf()\n if(res > $B.min_int && res < $B.max_int){return res}\n else{return $B.long_int.__sub__($B.long_int.$factory(self),\n $B.long_int.$factory(other))}\n }else if(typeof other == \"boolean\"){\n return other ? self - 1 : self\n }else{\n return $B.long_int.__sub__($B.long_int.$factory(self),\n $B.long_int.$factory(other))\n }\n }\n if(_b_.isinstance(other, _b_.float)){\n return new Number(self - other)\n }\n if(_b_.isinstance(other, _b_.complex)){\n return $B.make_complex(self - other.$real, -other.$imag)\n }\n if(_b_.isinstance(other, _b_.bool)){\n var bool_value = 0;\n if(other.valueOf()){bool_value = 1}\n return self - bool_value\n }\n if(_b_.isinstance(other, _b_.complex)){\n return $B.make_complex(self.valueOf() - other.$real, other.$imag)\n }\n var rsub = $B.$getattr(other, \"__rsub__\", _b_.None)\n if(rsub !== _b_.None){return rsub(self)}\n throw $err(\"-\", other)\n}", "language": "javascript", "code": "function(self, other){\n if(_b_.isinstance(other, int)){\n other = int_value(other)\n if(typeof other == \"number\"){\n var res = self.valueOf() - other.valueOf()\n if(res > $B.min_int && res < $B.max_int){return res}\n else{return $B.long_int.__sub__($B.long_int.$factory(self),\n $B.long_int.$factory(other))}\n }else if(typeof other == \"boolean\"){\n return other ? self - 1 : self\n }else{\n return $B.long_int.__sub__($B.long_int.$factory(self),\n $B.long_int.$factory(other))\n }\n }\n if(_b_.isinstance(other, _b_.float)){\n return new Number(self - other)\n }\n if(_b_.isinstance(other, _b_.complex)){\n return $B.make_complex(self - other.$real, -other.$imag)\n }\n if(_b_.isinstance(other, _b_.bool)){\n var bool_value = 0;\n if(other.valueOf()){bool_value = 1}\n return self - bool_value\n }\n if(_b_.isinstance(other, _b_.complex)){\n return $B.make_complex(self.valueOf() - other.$real, other.$imag)\n }\n var rsub = $B.$getattr(other, \"__rsub__\", _b_.None)\n if(rsub !== _b_.None){return rsub(self)}\n throw $err(\"-\", other)\n}", "code_tokens": ["function", "(", "self", ",", "other", ")", "{", "if", "(", "_b_", ".", "isinstance", "(", "other", ",", "int", ")", ")", "{", "other", "=", "int_value", "(", "other", ")", "if", "(", "typeof", "other", "==", "\"number\"", ")", "{", "var", "res", "=", "self", ".", "valueOf", "(", ")", "-", "other", ".", "valueOf", "(", ")", "if", "(", "res", ">", "$B", ".", "min_int", "&&", "res", "<", "$B", ".", "max_int", ")", "{", "return", "res", "}", "else", "{", "return", "$B", ".", "long_int", ".", "__sub__", "(", "$B", ".", "long_int", ".", "$factory", "(", "self", ")", ",", "$B", ".", "long_int", ".", "$factory", "(", "other", ")", ")", "}", "}", "else", "if", "(", "typeof", "other", "==", "\"boolean\"", ")", "{", "return", "other", "?", "self", "-", "1", ":", "self", "}", "else", "{", "return", "$B", ".", "long_int", ".", "__sub__", "(", "$B", ".", "long_int", ".", "$factory", "(", "self", ")", ",", "$B", ".", "long_int", ".", "$factory", "(", "other", ")", ")", "}", "}", "if", "(", "_b_", ".", "isinstance", "(", "other", ",", "_b_", ".", "float", ")", ")", "{", "return", "new", "Number", "(", "self", "-", "other", ")", "}", "if", "(", "_b_", ".", "isinstance", "(", "other", ",", "_b_", ".", "complex", ")", ")", "{", "return", "$B", ".", "make_complex", "(", "self", "-", "other", ".", "$real", ",", "-", "other", ".", "$imag", ")", "}", "if", "(", "_b_", ".", "isinstance", "(", "other", ",", "_b_", ".", "bool", ")", ")", "{", "var", "bool_value", "=", "0", ";", "if", "(", "other", ".", "valueOf", "(", ")", ")", "{", "bool_value", "=", "1", "}", "return", "self", "-", "bool_value", "}", "if", "(", "_b_", ".", "isinstance", "(", "other", ",", "_b_", ".", "complex", ")", ")", "{", "return", "$B", ".", "make_complex", "(", "self", ".", "valueOf", "(", ")", "-", "other", ".", "$real", ",", "other", ".", "$imag", ")", "}", "var", "rsub", "=", "$B", ".", "$getattr", "(", "other", ",", "\"__rsub__\"", ",", "_b_", ".", "None", ")", "if", "(", "rsub", "!==", "_b_", ".", "None", ")", "{", "return", "rsub", "(", "self", ")", "}", "throw", "$err", "(", "\"-\"", ",", "other", ")", "}"], "docstring": "code for + and -", "docstring_tokens": ["code", "for", "+", "and", "-"], "sha": "e437d320fce3c649c3028f2f7a8533eeae906440", "url": "https://github.com/brython-dev/brython/blob/e437d320fce3c649c3028f2f7a8533eeae906440/www/src/py_int.js#L536-L568", "partition": "test"} {"repo": "formio/angular-formio", "path": "tools/gulp/inline-resources.js", "func_name": "inlineResourcesFromString", "original_string": "function inlineResourcesFromString(content, urlResolver) {\n // Curry through the inlining functions.\n return [\n inlineTemplate,\n inlineStyle,\n removeModuleId\n ].reduce((content, fn) => fn(content, urlResolver), content);\n}", "language": "javascript", "code": "function inlineResourcesFromString(content, urlResolver) {\n // Curry through the inlining functions.\n return [\n inlineTemplate,\n inlineStyle,\n removeModuleId\n ].reduce((content, fn) => fn(content, urlResolver), content);\n}", "code_tokens": ["function", "inlineResourcesFromString", "(", "content", ",", "urlResolver", ")", "{", "return", "[", "inlineTemplate", ",", "inlineStyle", ",", "removeModuleId", "]", ".", "reduce", "(", "(", "content", ",", "fn", ")", "=>", "fn", "(", "content", ",", "urlResolver", ")", ",", "content", ")", ";", "}"], "docstring": "Inline resources from a string content.\n@param content {string} The source file's content.\n@param urlResolver {Function} A resolver that takes a URL and return a path.\n@returns {string} The content with resources inlined.", "docstring_tokens": ["Inline", "resources", "from", "a", "string", "content", "."], "sha": "127eb556cb8fa810cdf06b3d7b80901f9ac055f9", "url": "https://github.com/formio/angular-formio/blob/127eb556cb8fa810cdf06b3d7b80901f9ac055f9/tools/gulp/inline-resources.js#L64-L71", "partition": "test"} {"repo": "formio/angular-formio", "path": "tools/gulp/inline-resources.js", "func_name": "buildSass", "original_string": "function buildSass(content, sourceFile) {\n try {\n const result = sass.renderSync({\n data: content,\n file: sourceFile,\n importer: tildeImporter\n });\n return result.css.toString()\n } catch (e) {\n console.error('\\x1b[41m');\n console.error('at ' + sourceFile + ':' + e.line + \":\" + e.column);\n console.error(e.formatted);\n console.error('\\x1b[0m');\n return \"\";\n }\n}", "language": "javascript", "code": "function buildSass(content, sourceFile) {\n try {\n const result = sass.renderSync({\n data: content,\n file: sourceFile,\n importer: tildeImporter\n });\n return result.css.toString()\n } catch (e) {\n console.error('\\x1b[41m');\n console.error('at ' + sourceFile + ':' + e.line + \":\" + e.column);\n console.error(e.formatted);\n console.error('\\x1b[0m');\n return \"\";\n }\n}", "code_tokens": ["function", "buildSass", "(", "content", ",", "sourceFile", ")", "{", "try", "{", "const", "result", "=", "sass", ".", "renderSync", "(", "{", "data", ":", "content", ",", "file", ":", "sourceFile", ",", "importer", ":", "tildeImporter", "}", ")", ";", "return", "result", ".", "css", ".", "toString", "(", ")", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "'\\x1b[41m'", ")", ";", "\\x1b", "console", ".", "error", "(", "'at '", "+", "sourceFile", "+", "':'", "+", "e", ".", "line", "+", "\":\"", "+", "e", ".", "column", ")", ";", "console", ".", "error", "(", "e", ".", "formatted", ")", ";", "console", ".", "error", "(", "'\\x1b[0m'", ")", ";", "}", "}"], "docstring": "build sass content to css\n@param content {string} the css content\n@param sourceFile {string} the scss file sourceFile\n@return {string} the generated css, empty string if error occured", "docstring_tokens": ["build", "sass", "content", "to", "css"], "sha": "127eb556cb8fa810cdf06b3d7b80901f9ac055f9", "url": "https://github.com/formio/angular-formio/blob/127eb556cb8fa810cdf06b3d7b80901f9ac055f9/tools/gulp/inline-resources.js#L123-L138", "partition": "test"} {"repo": "formio/angular-formio", "path": "src/resource/resource.routes.js", "func_name": "FormioResourceRoutes", "original_string": "function FormioResourceRoutes(config) {\n config = config || {};\n return [\n {\n path: '',\n component: config.index || index_component_1.FormioResourceIndexComponent\n },\n {\n path: 'new',\n component: config.create || create_component_1.FormioResourceCreateComponent\n },\n {\n path: ':id',\n component: config.resource || resource_component_1.FormioResourceComponent,\n children: [\n {\n path: '',\n redirectTo: 'view',\n pathMatch: 'full'\n },\n {\n path: 'view',\n component: config.view || view_component_1.FormioResourceViewComponent\n },\n {\n path: 'edit',\n component: config.edit || edit_component_1.FormioResourceEditComponent\n },\n {\n path: 'delete',\n component: config.delete || delete_component_1.FormioResourceDeleteComponent\n }\n ]\n }\n ];\n}", "language": "javascript", "code": "function FormioResourceRoutes(config) {\n config = config || {};\n return [\n {\n path: '',\n component: config.index || index_component_1.FormioResourceIndexComponent\n },\n {\n path: 'new',\n component: config.create || create_component_1.FormioResourceCreateComponent\n },\n {\n path: ':id',\n component: config.resource || resource_component_1.FormioResourceComponent,\n children: [\n {\n path: '',\n redirectTo: 'view',\n pathMatch: 'full'\n },\n {\n path: 'view',\n component: config.view || view_component_1.FormioResourceViewComponent\n },\n {\n path: 'edit',\n component: config.edit || edit_component_1.FormioResourceEditComponent\n },\n {\n path: 'delete',\n component: config.delete || delete_component_1.FormioResourceDeleteComponent\n }\n ]\n }\n ];\n}", "code_tokens": ["function", "FormioResourceRoutes", "(", "config", ")", "{", "config", "=", "config", "||", "{", "}", ";", "return", "[", "{", "path", ":", "''", ",", "component", ":", "config", ".", "index", "||", "index_component_1", ".", "FormioResourceIndexComponent", "}", ",", "{", "path", ":", "'new'", ",", "component", ":", "config", ".", "create", "||", "create_component_1", ".", "FormioResourceCreateComponent", "}", ",", "{", "path", ":", "':id'", ",", "component", ":", "config", ".", "resource", "||", "resource_component_1", ".", "FormioResourceComponent", ",", "children", ":", "[", "{", "path", ":", "''", ",", "redirectTo", ":", "'view'", ",", "pathMatch", ":", "'full'", "}", ",", "{", "path", ":", "'view'", ",", "component", ":", "config", ".", "view", "||", "view_component_1", ".", "FormioResourceViewComponent", "}", ",", "{", "path", ":", "'edit'", ",", "component", ":", "config", ".", "edit", "||", "edit_component_1", ".", "FormioResourceEditComponent", "}", ",", "{", "path", ":", "'delete'", ",", "component", ":", "config", ".", "delete", "||", "delete_component_1", ".", "FormioResourceDeleteComponent", "}", "]", "}", "]", ";", "}"], "docstring": "The routes used to define a resource.", "docstring_tokens": ["The", "routes", "used", "to", "define", "a", "resource", "."], "sha": "127eb556cb8fa810cdf06b3d7b80901f9ac055f9", "url": "https://github.com/formio/angular-formio/blob/127eb556cb8fa810cdf06b3d7b80901f9ac055f9/src/resource/resource.routes.js#L12-L47", "partition": "test"} {"repo": "SOHU-Co/kafka-node", "path": "lib/baseProducer.js", "func_name": "BaseProducer", "original_string": "function BaseProducer (client, options, defaultPartitionerType, customPartitioner) {\n EventEmitter.call(this);\n options = options || {};\n\n this.ready = false;\n this.client = client;\n\n this.requireAcks = options.requireAcks === undefined ? DEFAULTS.requireAcks : options.requireAcks;\n this.ackTimeoutMs = options.ackTimeoutMs === undefined ? DEFAULTS.ackTimeoutMs : options.ackTimeoutMs;\n\n if (customPartitioner !== undefined && options.partitionerType !== PARTITIONER_TYPES.custom) {\n throw new Error('Partitioner Type must be custom if providing a customPartitioner.');\n } else if (customPartitioner === undefined && options.partitionerType === PARTITIONER_TYPES.custom) {\n throw new Error('No customer partitioner defined');\n }\n\n var partitionerType = PARTITIONER_MAP[options.partitionerType] || PARTITIONER_MAP[defaultPartitionerType];\n\n // eslint-disable-next-line\n this.partitioner = new partitionerType(customPartitioner);\n\n this.connect();\n}", "language": "javascript", "code": "function BaseProducer (client, options, defaultPartitionerType, customPartitioner) {\n EventEmitter.call(this);\n options = options || {};\n\n this.ready = false;\n this.client = client;\n\n this.requireAcks = options.requireAcks === undefined ? DEFAULTS.requireAcks : options.requireAcks;\n this.ackTimeoutMs = options.ackTimeoutMs === undefined ? DEFAULTS.ackTimeoutMs : options.ackTimeoutMs;\n\n if (customPartitioner !== undefined && options.partitionerType !== PARTITIONER_TYPES.custom) {\n throw new Error('Partitioner Type must be custom if providing a customPartitioner.');\n } else if (customPartitioner === undefined && options.partitionerType === PARTITIONER_TYPES.custom) {\n throw new Error('No customer partitioner defined');\n }\n\n var partitionerType = PARTITIONER_MAP[options.partitionerType] || PARTITIONER_MAP[defaultPartitionerType];\n\n // eslint-disable-next-line\n this.partitioner = new partitionerType(customPartitioner);\n\n this.connect();\n}", "code_tokens": ["function", "BaseProducer", "(", "client", ",", "options", ",", "defaultPartitionerType", ",", "customPartitioner", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "ready", "=", "false", ";", "this", ".", "client", "=", "client", ";", "this", ".", "requireAcks", "=", "options", ".", "requireAcks", "===", "undefined", "?", "DEFAULTS", ".", "requireAcks", ":", "options", ".", "requireAcks", ";", "this", ".", "ackTimeoutMs", "=", "options", ".", "ackTimeoutMs", "===", "undefined", "?", "DEFAULTS", ".", "ackTimeoutMs", ":", "options", ".", "ackTimeoutMs", ";", "if", "(", "customPartitioner", "!==", "undefined", "&&", "options", ".", "partitionerType", "!==", "PARTITIONER_TYPES", ".", "custom", ")", "{", "throw", "new", "Error", "(", "'Partitioner Type must be custom if providing a customPartitioner.'", ")", ";", "}", "else", "if", "(", "customPartitioner", "===", "undefined", "&&", "options", ".", "partitionerType", "===", "PARTITIONER_TYPES", ".", "custom", ")", "{", "throw", "new", "Error", "(", "'No customer partitioner defined'", ")", ";", "}", "var", "partitionerType", "=", "PARTITIONER_MAP", "[", "options", ".", "partitionerType", "]", "||", "PARTITIONER_MAP", "[", "defaultPartitionerType", "]", ";", "this", ".", "partitioner", "=", "new", "partitionerType", "(", "customPartitioner", ")", ";", "this", ".", "connect", "(", ")", ";", "}"], "docstring": "Provides common functionality for a kafka producer\n\n@param {Client} client A kafka client object to use for the producer\n@param {Object} [options] An object containing configuration options\n@param {Number} [options.requireAcks=1] Configuration for when to consider a message as acknowledged.\n
  • 0 = No ack required
  • \n
  • 1 = Leader ack required
  • \n
  • -1 = All in sync replicas ack required
  • \n\n@param {Number} [options.ackTimeoutMs=100] The amount of time in milliseconds to wait for all acks before considered\nthe message as errored\n@param {Number} [defaultPartitionType] The default partitioner type\n@param {Object} [customPartitioner] a custom partitinoer to use of the form: function (partitions, key)\n@constructor", "docstring_tokens": ["Provides", "common", "functionality", "for", "a", "kafka", "producer"], "sha": "707348d9a9881782f3a390fdcc6362d35cfe24c0", "url": "https://github.com/SOHU-Co/kafka-node/blob/707348d9a9881782f3a390fdcc6362d35cfe24c0/lib/baseProducer.js#L55-L77", "partition": "test"} {"repo": "codemanki/cloudscraper", "path": "lib/sandbox.js", "func_name": "Context", "original_string": "function Context (options) {\n if (!options) options = { body: '', hostname: '' };\n\n const body = options.body;\n const href = 'http://' + options.hostname + '/';\n const cache = Object.create(null);\n const keys = [];\n\n this.atob = function (str) {\n return Buffer.from(str, 'base64').toString('binary');\n };\n\n // Used for eval during onRedirectChallenge\n this.location = { reload: function () {} };\n\n this.document = {\n createElement: function () {\n return { firstChild: { href: href } };\n },\n getElementById: function (id) {\n if (keys.indexOf(id) === -1) {\n const re = new RegExp(' id=[\\'\"]?' + id + '[^>]*>([^<]*)');\n const match = body.match(re);\n\n keys.push(id);\n cache[id] = match === null ? match : { innerHTML: match[1] };\n }\n\n return cache[id];\n }\n };\n}", "language": "javascript", "code": "function Context (options) {\n if (!options) options = { body: '', hostname: '' };\n\n const body = options.body;\n const href = 'http://' + options.hostname + '/';\n const cache = Object.create(null);\n const keys = [];\n\n this.atob = function (str) {\n return Buffer.from(str, 'base64').toString('binary');\n };\n\n // Used for eval during onRedirectChallenge\n this.location = { reload: function () {} };\n\n this.document = {\n createElement: function () {\n return { firstChild: { href: href } };\n },\n getElementById: function (id) {\n if (keys.indexOf(id) === -1) {\n const re = new RegExp(' id=[\\'\"]?' + id + '[^>]*>([^<]*)');\n const match = body.match(re);\n\n keys.push(id);\n cache[id] = match === null ? match : { innerHTML: match[1] };\n }\n\n return cache[id];\n }\n };\n}", "code_tokens": ["function", "Context", "(", "options", ")", "{", "if", "(", "!", "options", ")", "options", "=", "{", "body", ":", "''", ",", "hostname", ":", "''", "}", ";", "const", "body", "=", "options", ".", "body", ";", "const", "href", "=", "'http://'", "+", "options", ".", "hostname", "+", "'/'", ";", "const", "cache", "=", "Object", ".", "create", "(", "null", ")", ";", "const", "keys", "=", "[", "]", ";", "this", ".", "atob", "=", "function", "(", "str", ")", "{", "return", "Buffer", ".", "from", "(", "str", ",", "'base64'", ")", ".", "toString", "(", "'binary'", ")", ";", "}", ";", "this", ".", "location", "=", "{", "reload", ":", "function", "(", ")", "{", "}", "}", ";", "this", ".", "document", "=", "{", "createElement", ":", "function", "(", ")", "{", "return", "{", "firstChild", ":", "{", "href", ":", "href", "}", "}", ";", "}", ",", "getElementById", ":", "function", "(", "id", ")", "{", "if", "(", "keys", ".", "indexOf", "(", "id", ")", "===", "-", "1", ")", "{", "const", "re", "=", "new", "RegExp", "(", "' id=[\\'\"]?'", "+", "\\'", "+", "id", ")", ";", "'[^>]*>([^<]*)'", "const", "match", "=", "body", ".", "match", "(", "re", ")", ";", "keys", ".", "push", "(", "id", ")", ";", "}", "cache", "[", "id", "]", "=", "match", "===", "null", "?", "match", ":", "{", "innerHTML", ":", "match", "[", "1", "]", "}", ";", "}", "}", ";", "}"], "docstring": "Global context used to evaluate standard IUAM JS challenge", "docstring_tokens": ["Global", "context", "used", "to", "evaluate", "standard", "IUAM", "JS", "challenge"], "sha": "c5b576af9f918d990d6ccedea07a7e4f837dc88f", "url": "https://github.com/codemanki/cloudscraper/blob/c5b576af9f918d990d6ccedea07a7e4f837dc88f/lib/sandbox.js#L19-L50", "partition": "test"} {"repo": "codemanki/cloudscraper", "path": "docs/examples/solve-recaptcha-v2.js", "func_name": "alternative", "original_string": "function alternative (options, { captcha: { url, siteKey } }) {\n // Here you do some magic with the siteKey provided by cloudscraper\n console.error('The url is \"' + url + '\"');\n console.error('The site key is \"' + siteKey + '\"');\n return Promise.reject(new Error('This is a dummy function'));\n}", "language": "javascript", "code": "function alternative (options, { captcha: { url, siteKey } }) {\n // Here you do some magic with the siteKey provided by cloudscraper\n console.error('The url is \"' + url + '\"');\n console.error('The site key is \"' + siteKey + '\"');\n return Promise.reject(new Error('This is a dummy function'));\n}", "code_tokens": ["function", "alternative", "(", "options", ",", "{", "captcha", ":", "{", "url", ",", "siteKey", "}", "}", ")", "{", "console", ".", "error", "(", "'The url is \"'", "+", "url", "+", "'\"'", ")", ";", "console", ".", "error", "(", "'The site key is \"'", "+", "siteKey", "+", "'\"'", ")", ";", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'This is a dummy function'", ")", ")", ";", "}"], "docstring": "An example handler with destructuring arguments", "docstring_tokens": ["An", "example", "handler", "with", "destructuring", "arguments"], "sha": "c5b576af9f918d990d6ccedea07a7e4f837dc88f", "url": "https://github.com/codemanki/cloudscraper/blob/c5b576af9f918d990d6ccedea07a7e4f837dc88f/docs/examples/solve-recaptcha-v2.js#L19-L24", "partition": "test"} {"repo": "codemanki/cloudscraper", "path": "index.js", "func_name": "performRequest", "original_string": "function performRequest (options, isFirstRequest) {\n // This should be the default export of either request or request-promise.\n const requester = options.requester;\n\n // Note that request is always an instanceof ReadableStream, EventEmitter\n // If the requester is request-promise, it is also thenable.\n const request = requester(options);\n\n // We must define the host header ourselves to preserve case and order.\n if (request.getHeader('host') === HOST) {\n request.setHeader('host', request.uri.host);\n }\n\n // If the requester is not request-promise, ensure we get a callback.\n if (typeof request.callback !== 'function') {\n throw new TypeError('Expected a callback function, got ' +\n typeof (request.callback) + ' instead.');\n }\n\n // We only need the callback from the first request.\n // The other callbacks can be safely ignored.\n if (isFirstRequest) {\n // This should be a user supplied callback or request-promise's callback.\n // The callback is always wrapped/bound to the request instance.\n options.callback = request.callback;\n }\n\n request.removeAllListeners('error')\n .once('error', function (error) {\n onRequestResponse(options, error);\n });\n\n request.removeAllListeners('complete')\n .once('complete', function (response, body) {\n onRequestResponse(options, null, response, body);\n });\n\n // Indicate that this is a cloudscraper request\n request.cloudscraper = true;\n return request;\n}", "language": "javascript", "code": "function performRequest (options, isFirstRequest) {\n // This should be the default export of either request or request-promise.\n const requester = options.requester;\n\n // Note that request is always an instanceof ReadableStream, EventEmitter\n // If the requester is request-promise, it is also thenable.\n const request = requester(options);\n\n // We must define the host header ourselves to preserve case and order.\n if (request.getHeader('host') === HOST) {\n request.setHeader('host', request.uri.host);\n }\n\n // If the requester is not request-promise, ensure we get a callback.\n if (typeof request.callback !== 'function') {\n throw new TypeError('Expected a callback function, got ' +\n typeof (request.callback) + ' instead.');\n }\n\n // We only need the callback from the first request.\n // The other callbacks can be safely ignored.\n if (isFirstRequest) {\n // This should be a user supplied callback or request-promise's callback.\n // The callback is always wrapped/bound to the request instance.\n options.callback = request.callback;\n }\n\n request.removeAllListeners('error')\n .once('error', function (error) {\n onRequestResponse(options, error);\n });\n\n request.removeAllListeners('complete')\n .once('complete', function (response, body) {\n onRequestResponse(options, null, response, body);\n });\n\n // Indicate that this is a cloudscraper request\n request.cloudscraper = true;\n return request;\n}", "code_tokens": ["function", "performRequest", "(", "options", ",", "isFirstRequest", ")", "{", "const", "requester", "=", "options", ".", "requester", ";", "const", "request", "=", "requester", "(", "options", ")", ";", "if", "(", "request", ".", "getHeader", "(", "'host'", ")", "===", "HOST", ")", "{", "request", ".", "setHeader", "(", "'host'", ",", "request", ".", "uri", ".", "host", ")", ";", "}", "if", "(", "typeof", "request", ".", "callback", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'Expected a callback function, got '", "+", "typeof", "(", "request", ".", "callback", ")", "+", "' instead.'", ")", ";", "}", "if", "(", "isFirstRequest", ")", "{", "options", ".", "callback", "=", "request", ".", "callback", ";", "}", "request", ".", "removeAllListeners", "(", "'error'", ")", ".", "once", "(", "'error'", ",", "function", "(", "error", ")", "{", "onRequestResponse", "(", "options", ",", "error", ")", ";", "}", ")", ";", "request", ".", "removeAllListeners", "(", "'complete'", ")", ".", "once", "(", "'complete'", ",", "function", "(", "response", ",", "body", ")", "{", "onRequestResponse", "(", "options", ",", "null", ",", "response", ",", "body", ")", ";", "}", ")", ";", "request", ".", "cloudscraper", "=", "true", ";", "return", "request", ";", "}"], "docstring": "This function is wrapped to ensure that we get new options on first call. The options object is reused in subsequent calls when calling it directly.", "docstring_tokens": ["This", "function", "is", "wrapped", "to", "ensure", "that", "we", "get", "new", "options", "on", "first", "call", ".", "The", "options", "object", "is", "reused", "in", "subsequent", "calls", "when", "calling", "it", "directly", "."], "sha": "c5b576af9f918d990d6ccedea07a7e4f837dc88f", "url": "https://github.com/codemanki/cloudscraper/blob/c5b576af9f918d990d6ccedea07a7e4f837dc88f/index.js#L101-L141", "partition": "test"} {"repo": "codemanki/cloudscraper", "path": "index.js", "func_name": "onRequestResponse", "original_string": "function onRequestResponse (options, error, response, body) {\n const callback = options.callback;\n\n // Encoding is null so body should be a buffer object\n if (error || !body || !body.toString) {\n // Pure request error (bad connection, wrong url, etc)\n return callback(new RequestError(error, options, response));\n }\n\n response.responseStartTime = Date.now();\n response.isCloudflare = /^cloudflare/i.test('' + response.caseless.get('server'));\n response.isHTML = /text\\/html/i.test('' + response.caseless.get('content-type'));\n\n // If body isn't a buffer, this is a custom response body.\n if (!Buffer.isBuffer(body)) {\n return callback(null, response, body);\n }\n\n // Decompress brotli compressed responses\n if (/\\bbr\\b/i.test('' + response.caseless.get('content-encoding'))) {\n if (!brotli.isAvailable) {\n const cause = 'Received a Brotli compressed response. Please install brotli';\n return callback(new RequestError(cause, options, response));\n }\n\n response.body = body = brotli.decompress(body);\n }\n\n if (response.isCloudflare && response.isHTML) {\n onCloudflareResponse(options, response, body);\n } else {\n onRequestComplete(options, response, body);\n }\n}", "language": "javascript", "code": "function onRequestResponse (options, error, response, body) {\n const callback = options.callback;\n\n // Encoding is null so body should be a buffer object\n if (error || !body || !body.toString) {\n // Pure request error (bad connection, wrong url, etc)\n return callback(new RequestError(error, options, response));\n }\n\n response.responseStartTime = Date.now();\n response.isCloudflare = /^cloudflare/i.test('' + response.caseless.get('server'));\n response.isHTML = /text\\/html/i.test('' + response.caseless.get('content-type'));\n\n // If body isn't a buffer, this is a custom response body.\n if (!Buffer.isBuffer(body)) {\n return callback(null, response, body);\n }\n\n // Decompress brotli compressed responses\n if (/\\bbr\\b/i.test('' + response.caseless.get('content-encoding'))) {\n if (!brotli.isAvailable) {\n const cause = 'Received a Brotli compressed response. Please install brotli';\n return callback(new RequestError(cause, options, response));\n }\n\n response.body = body = brotli.decompress(body);\n }\n\n if (response.isCloudflare && response.isHTML) {\n onCloudflareResponse(options, response, body);\n } else {\n onRequestComplete(options, response, body);\n }\n}", "code_tokens": ["function", "onRequestResponse", "(", "options", ",", "error", ",", "response", ",", "body", ")", "{", "const", "callback", "=", "options", ".", "callback", ";", "if", "(", "error", "||", "!", "body", "||", "!", "body", ".", "toString", ")", "{", "return", "callback", "(", "new", "RequestError", "(", "error", ",", "options", ",", "response", ")", ")", ";", "}", "response", ".", "responseStartTime", "=", "Date", ".", "now", "(", ")", ";", "response", ".", "isCloudflare", "=", "/", "^cloudflare", "/", "i", ".", "test", "(", "''", "+", "response", ".", "caseless", ".", "get", "(", "'server'", ")", ")", ";", "response", ".", "isHTML", "=", "/", "text\\/html", "/", "i", ".", "test", "(", "''", "+", "response", ".", "caseless", ".", "get", "(", "'content-type'", ")", ")", ";", "if", "(", "!", "Buffer", ".", "isBuffer", "(", "body", ")", ")", "{", "return", "callback", "(", "null", ",", "response", ",", "body", ")", ";", "}", "if", "(", "/", "\\bbr\\b", "/", "i", ".", "test", "(", "''", "+", "response", ".", "caseless", ".", "get", "(", "'content-encoding'", ")", ")", ")", "{", "if", "(", "!", "brotli", ".", "isAvailable", ")", "{", "const", "cause", "=", "'Received a Brotli compressed response. Please install brotli'", ";", "return", "callback", "(", "new", "RequestError", "(", "cause", ",", "options", ",", "response", ")", ")", ";", "}", "response", ".", "body", "=", "body", "=", "brotli", ".", "decompress", "(", "body", ")", ";", "}", "if", "(", "response", ".", "isCloudflare", "&&", "response", ".", "isHTML", ")", "{", "onCloudflareResponse", "(", "options", ",", "response", ",", "body", ")", ";", "}", "else", "{", "onRequestComplete", "(", "options", ",", "response", ",", "body", ")", ";", "}", "}"], "docstring": "The argument convention is options first where possible, options always before response, and body always after response.", "docstring_tokens": ["The", "argument", "convention", "is", "options", "first", "where", "possible", "options", "always", "before", "response", "and", "body", "always", "after", "response", "."], "sha": "c5b576af9f918d990d6ccedea07a7e4f837dc88f", "url": "https://github.com/codemanki/cloudscraper/blob/c5b576af9f918d990d6ccedea07a7e4f837dc88f/index.js#L145-L178", "partition": "test"} {"repo": "codemanki/cloudscraper", "path": "index.js", "func_name": "onCaptcha", "original_string": "function onCaptcha (options, response, body) {\n const callback = options.callback;\n // UDF that has the responsibility of returning control back to cloudscraper\n const handler = options.onCaptcha;\n // The form data to send back to Cloudflare\n const payload = { /* s, g-re-captcha-response */ };\n\n let cause;\n let match;\n\n match = body.match(/]*)? id=[\"']?challenge-form['\"]?(?: [^<>]*)?>([\\S\\s]*?)<\\/form>/);\n if (!match) {\n cause = 'Challenge form extraction failed';\n return callback(new ParserError(cause, options, response));\n }\n\n // Defining response.challengeForm for debugging purposes\n const form = response.challengeForm = match[1];\n\n match = form.match(/\\/recaptcha\\/api\\/fallback\\?k=([^\\s\"'<>]*)/);\n if (!match) {\n // The site key wasn't inside the form so search the entire document\n match = body.match(/data-sitekey=[\"']?([^\\s\"'<>]*)/);\n if (!match) {\n cause = 'Unable to find the reCAPTCHA site key';\n return callback(new ParserError(cause, options, response));\n }\n }\n\n // Everything that is needed to solve the reCAPTCHA\n response.captcha = {\n url: response.request.uri.href,\n siteKey: match[1],\n form: payload\n };\n\n // Adding formData\n match = form.match(/]*)? name=[^<>]+>/g);\n if (!match) {\n cause = 'Challenge form is missing inputs';\n return callback(new ParserError(cause, options, response));\n }\n\n const inputs = match;\n // Only adding inputs that have both a name and value defined\n for (let name, value, i = 0; i < inputs.length; i++) {\n name = inputs[i].match(/name=[\"']?([^\\s\"'<>]*)/);\n if (name) {\n value = inputs[i].match(/value=[\"']?([^\\s\"'<>]*)/);\n if (value) {\n payload[name[1]] = value[1];\n }\n }\n }\n\n // Sanity check\n if (!payload['s']) {\n cause = 'Challenge form is missing secret input';\n return callback(new ParserError(cause, options, response));\n }\n\n // The callback used to green light form submission\n const submit = function (error) {\n if (error) {\n // Pass an user defined error back to the original request call\n return callback(new CaptchaError(error, options, response));\n }\n\n onSubmitCaptcha(options, response, body);\n };\n\n // This seems like an okay-ish API (fewer arguments to the handler)\n response.captcha.submit = submit;\n\n // We're handing control over to the user now.\n const thenable = handler(options, response, body);\n // Handle the case where the user returns a promise\n if (thenable && typeof thenable.then === 'function') {\n // eslint-disable-next-line promise/catch-or-return\n thenable.then(submit, function (error) {\n if (!error) {\n // The user broke their promise with a falsy error\n submit(new Error('Falsy error'));\n } else {\n submit(error);\n }\n });\n }\n}", "language": "javascript", "code": "function onCaptcha (options, response, body) {\n const callback = options.callback;\n // UDF that has the responsibility of returning control back to cloudscraper\n const handler = options.onCaptcha;\n // The form data to send back to Cloudflare\n const payload = { /* s, g-re-captcha-response */ };\n\n let cause;\n let match;\n\n match = body.match(/]*)? id=[\"']?challenge-form['\"]?(?: [^<>]*)?>([\\S\\s]*?)<\\/form>/);\n if (!match) {\n cause = 'Challenge form extraction failed';\n return callback(new ParserError(cause, options, response));\n }\n\n // Defining response.challengeForm for debugging purposes\n const form = response.challengeForm = match[1];\n\n match = form.match(/\\/recaptcha\\/api\\/fallback\\?k=([^\\s\"'<>]*)/);\n if (!match) {\n // The site key wasn't inside the form so search the entire document\n match = body.match(/data-sitekey=[\"']?([^\\s\"'<>]*)/);\n if (!match) {\n cause = 'Unable to find the reCAPTCHA site key';\n return callback(new ParserError(cause, options, response));\n }\n }\n\n // Everything that is needed to solve the reCAPTCHA\n response.captcha = {\n url: response.request.uri.href,\n siteKey: match[1],\n form: payload\n };\n\n // Adding formData\n match = form.match(/]*)? name=[^<>]+>/g);\n if (!match) {\n cause = 'Challenge form is missing inputs';\n return callback(new ParserError(cause, options, response));\n }\n\n const inputs = match;\n // Only adding inputs that have both a name and value defined\n for (let name, value, i = 0; i < inputs.length; i++) {\n name = inputs[i].match(/name=[\"']?([^\\s\"'<>]*)/);\n if (name) {\n value = inputs[i].match(/value=[\"']?([^\\s\"'<>]*)/);\n if (value) {\n payload[name[1]] = value[1];\n }\n }\n }\n\n // Sanity check\n if (!payload['s']) {\n cause = 'Challenge form is missing secret input';\n return callback(new ParserError(cause, options, response));\n }\n\n // The callback used to green light form submission\n const submit = function (error) {\n if (error) {\n // Pass an user defined error back to the original request call\n return callback(new CaptchaError(error, options, response));\n }\n\n onSubmitCaptcha(options, response, body);\n };\n\n // This seems like an okay-ish API (fewer arguments to the handler)\n response.captcha.submit = submit;\n\n // We're handing control over to the user now.\n const thenable = handler(options, response, body);\n // Handle the case where the user returns a promise\n if (thenable && typeof thenable.then === 'function') {\n // eslint-disable-next-line promise/catch-or-return\n thenable.then(submit, function (error) {\n if (!error) {\n // The user broke their promise with a falsy error\n submit(new Error('Falsy error'));\n } else {\n submit(error);\n }\n });\n }\n}", "code_tokens": ["function", "onCaptcha", "(", "options", ",", "response", ",", "body", ")", "{", "const", "callback", "=", "options", ".", "callback", ";", "const", "handler", "=", "options", ".", "onCaptcha", ";", "const", "payload", "=", "{", "}", ";", "let", "cause", ";", "let", "match", ";", "match", "=", "body", ".", "match", "(", "/", "]*)? id=[\"']?challenge-form['\"]?(?: [^<>]*)?>([\\S\\s]*?)<\\/form>", "/", ")", ";", "if", "(", "!", "match", ")", "{", "cause", "=", "'Challenge form extraction failed'", ";", "return", "callback", "(", "new", "ParserError", "(", "cause", ",", "options", ",", "response", ")", ")", ";", "}", "const", "form", "=", "response", ".", "challengeForm", "=", "match", "[", "1", "]", ";", "match", "=", "form", ".", "match", "(", "/", "\\/recaptcha\\/api\\/fallback\\?k=([^\\s\"'<>]*)", "/", ")", ";", "if", "(", "!", "match", ")", "{", "match", "=", "body", ".", "match", "(", "/", "data-sitekey=[\"']?([^\\s\"'<>]*)", "/", ")", ";", "if", "(", "!", "match", ")", "{", "cause", "=", "'Unable to find the reCAPTCHA site key'", ";", "return", "callback", "(", "new", "ParserError", "(", "cause", ",", "options", ",", "response", ")", ")", ";", "}", "}", "response", ".", "captcha", "=", "{", "url", ":", "response", ".", "request", ".", "uri", ".", "href", ",", "siteKey", ":", "match", "[", "1", "]", ",", "form", ":", "payload", "}", ";", "match", "=", "form", ".", "match", "(", "/", "]*)? name=[^<>]+>", "/", "g", ")", ";", "if", "(", "!", "match", ")", "{", "cause", "=", "'Challenge form is missing inputs'", ";", "return", "callback", "(", "new", "ParserError", "(", "cause", ",", "options", ",", "response", ")", ")", ";", "}", "const", "inputs", "=", "match", ";", "for", "(", "let", "name", ",", "value", ",", "i", "=", "0", ";", "i", "<", "inputs", ".", "length", ";", "i", "++", ")", "{", "name", "=", "inputs", "[", "i", "]", ".", "match", "(", "/", "name=[\"']?([^\\s\"'<>]*)", "/", ")", ";", "if", "(", "name", ")", "{", "value", "=", "inputs", "[", "i", "]", ".", "match", "(", "/", "value=[\"']?([^\\s\"'<>]*)", "/", ")", ";", "if", "(", "value", ")", "{", "payload", "[", "name", "[", "1", "]", "]", "=", "value", "[", "1", "]", ";", "}", "}", "}", "if", "(", "!", "payload", "[", "'s'", "]", ")", "{", "cause", "=", "'Challenge form is missing secret input'", ";", "return", "callback", "(", "new", "ParserError", "(", "cause", ",", "options", ",", "response", ")", ")", ";", "}", "const", "submit", "=", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "new", "CaptchaError", "(", "error", ",", "options", ",", "response", ")", ")", ";", "}", "onSubmitCaptcha", "(", "options", ",", "response", ",", "body", ")", ";", "}", ";", "response", ".", "captcha", ".", "submit", "=", "submit", ";", "const", "thenable", "=", "handler", "(", "options", ",", "response", ",", "body", ")", ";", "if", "(", "thenable", "&&", "typeof", "thenable", ".", "then", "===", "'function'", ")", "{", "thenable", ".", "then", "(", "submit", ",", "function", "(", "error", ")", "{", "if", "(", "!", "error", ")", "{", "submit", "(", "new", "Error", "(", "'Falsy error'", ")", ")", ";", "}", "else", "{", "submit", "(", "error", ")", ";", "}", "}", ")", ";", "}", "}"], "docstring": "Parses the reCAPTCHA form and hands control over to the user", "docstring_tokens": ["Parses", "the", "reCAPTCHA", "form", "and", "hands", "control", "over", "to", "the", "user"], "sha": "c5b576af9f918d990d6ccedea07a7e4f837dc88f", "url": "https://github.com/codemanki/cloudscraper/blob/c5b576af9f918d990d6ccedea07a7e4f837dc88f/index.js#L347-L435", "partition": "test"} {"repo": "codemanki/cloudscraper", "path": "index.js", "func_name": "", "original_string": "function (error) {\n if (error) {\n // Pass an user defined error back to the original request call\n return callback(new CaptchaError(error, options, response));\n }\n\n onSubmitCaptcha(options, response, body);\n }", "language": "javascript", "code": "function (error) {\n if (error) {\n // Pass an user defined error back to the original request call\n return callback(new CaptchaError(error, options, response));\n }\n\n onSubmitCaptcha(options, response, body);\n }", "code_tokens": ["function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "new", "CaptchaError", "(", "error", ",", "options", ",", "response", ")", ")", ";", "}", "onSubmitCaptcha", "(", "options", ",", "response", ",", "body", ")", ";", "}"], "docstring": "The callback used to green light form submission", "docstring_tokens": ["The", "callback", "used", "to", "green", "light", "form", "submission"], "sha": "c5b576af9f918d990d6ccedea07a7e4f837dc88f", "url": "https://github.com/codemanki/cloudscraper/blob/c5b576af9f918d990d6ccedea07a7e4f837dc88f/index.js#L409-L416", "partition": "test"} {"repo": "algolia/vue-instantsearch", "path": "docs/plugins/assets.js", "func_name": "assets", "original_string": "function assets(userOptions = {}) {\n const options = {\n ...defaults,\n ...userOptions,\n };\n\n return (files, metalsmith, cb) => {\n const src = metalsmith.path(options.source);\n const dest = options.destination;\n\n // copied almost line for line from https://github.com/segmentio/metalsmith/blob/master/lib/index.js\n readdir(src, (readDirError, arr) => {\n if (readDirError) {\n cb(readDirError);\n return;\n }\n\n each(arr, read, err => cb(err, files));\n });\n\n function read(file, done) {\n const name = path.join(dest, path.relative(src, file));\n fs.stat(file, (statError, stats) => {\n if (statError) {\n done(statError);\n return;\n }\n\n fs.readFile(file, (err, buffer) => {\n if (err) {\n done(err);\n return;\n }\n\n const newFile = {};\n\n newFile.contents = buffer;\n newFile.stats = stats;\n\n newFile.mode = mode(stats).toOctal();\n files[name] = newFile;\n done();\n });\n });\n }\n };\n}", "language": "javascript", "code": "function assets(userOptions = {}) {\n const options = {\n ...defaults,\n ...userOptions,\n };\n\n return (files, metalsmith, cb) => {\n const src = metalsmith.path(options.source);\n const dest = options.destination;\n\n // copied almost line for line from https://github.com/segmentio/metalsmith/blob/master/lib/index.js\n readdir(src, (readDirError, arr) => {\n if (readDirError) {\n cb(readDirError);\n return;\n }\n\n each(arr, read, err => cb(err, files));\n });\n\n function read(file, done) {\n const name = path.join(dest, path.relative(src, file));\n fs.stat(file, (statError, stats) => {\n if (statError) {\n done(statError);\n return;\n }\n\n fs.readFile(file, (err, buffer) => {\n if (err) {\n done(err);\n return;\n }\n\n const newFile = {};\n\n newFile.contents = buffer;\n newFile.stats = stats;\n\n newFile.mode = mode(stats).toOctal();\n files[name] = newFile;\n done();\n });\n });\n }\n };\n}", "code_tokens": ["function", "assets", "(", "userOptions", "=", "{", "}", ")", "{", "const", "options", "=", "{", "...", "defaults", ",", "...", "userOptions", ",", "}", ";", "return", "(", "files", ",", "metalsmith", ",", "cb", ")", "=>", "{", "const", "src", "=", "metalsmith", ".", "path", "(", "options", ".", "source", ")", ";", "const", "dest", "=", "options", ".", "destination", ";", "readdir", "(", "src", ",", "(", "readDirError", ",", "arr", ")", "=>", "{", "if", "(", "readDirError", ")", "{", "cb", "(", "readDirError", ")", ";", "return", ";", "}", "each", "(", "arr", ",", "read", ",", "err", "=>", "cb", "(", "err", ",", "files", ")", ")", ";", "}", ")", ";", "function", "read", "(", "file", ",", "done", ")", "{", "const", "name", "=", "path", ".", "join", "(", "dest", ",", "path", ".", "relative", "(", "src", ",", "file", ")", ")", ";", "fs", ".", "stat", "(", "file", ",", "(", "statError", ",", "stats", ")", "=>", "{", "if", "(", "statError", ")", "{", "done", "(", "statError", ")", ";", "return", ";", "}", "fs", ".", "readFile", "(", "file", ",", "(", "err", ",", "buffer", ")", "=>", "{", "if", "(", "err", ")", "{", "done", "(", "err", ")", ";", "return", ";", "}", "const", "newFile", "=", "{", "}", ";", "newFile", ".", "contents", "=", "buffer", ";", "newFile", ".", "stats", "=", "stats", ";", "newFile", ".", "mode", "=", "mode", "(", "stats", ")", ".", "toOctal", "(", ")", ";", "files", "[", "name", "]", "=", "newFile", ";", "done", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}", ";", "}"], "docstring": "Metalsmith plugin to include static assets.\n\n@param {Object} userOptions (optional)\n@property {String} source Path to copy static assets from (relative to working directory). Defaults to './public'\n@property {String} destination Path to copy static assets to (relative to destination directory). Defaults to '.'\n@return {Function} a Metalsmith plugin", "docstring_tokens": ["Metalsmith", "plugin", "to", "include", "static", "assets", "."], "sha": "2a21b5226908f1f71c9ac28372de56d01eda813d", "url": "https://github.com/algolia/vue-instantsearch/blob/2a21b5226908f1f71c9ac28372de56d01eda813d/docs/plugins/assets.js#L33-L79", "partition": "test"} {"repo": "algolia/vue-instantsearch", "path": "docs/assets/js/fix-sidebar.js", "func_name": "getStartStopBoundaries", "original_string": "function getStartStopBoundaries(parent, sidebar, topOffset) {\n const bbox = parent.getBoundingClientRect();\n const sidebarBbox = sidebar.getBoundingClientRect();\n const bodyBbox = document.body.getBoundingClientRect();\n\n const containerAbsoluteTop = bbox.top - bodyBbox.top;\n const sidebarAbsoluteTop = sidebarBbox.top - bodyBbox.top;\n const marginTop = sidebarAbsoluteTop - containerAbsoluteTop;\n const start = containerAbsoluteTop - topOffset;\n const stop = bbox.height + containerAbsoluteTop - sidebarBbox.height - marginTop - topOffset;\n\n return {\n start,\n stop,\n };\n}", "language": "javascript", "code": "function getStartStopBoundaries(parent, sidebar, topOffset) {\n const bbox = parent.getBoundingClientRect();\n const sidebarBbox = sidebar.getBoundingClientRect();\n const bodyBbox = document.body.getBoundingClientRect();\n\n const containerAbsoluteTop = bbox.top - bodyBbox.top;\n const sidebarAbsoluteTop = sidebarBbox.top - bodyBbox.top;\n const marginTop = sidebarAbsoluteTop - containerAbsoluteTop;\n const start = containerAbsoluteTop - topOffset;\n const stop = bbox.height + containerAbsoluteTop - sidebarBbox.height - marginTop - topOffset;\n\n return {\n start,\n stop,\n };\n}", "code_tokens": ["function", "getStartStopBoundaries", "(", "parent", ",", "sidebar", ",", "topOffset", ")", "{", "const", "bbox", "=", "parent", ".", "getBoundingClientRect", "(", ")", ";", "const", "sidebarBbox", "=", "sidebar", ".", "getBoundingClientRect", "(", ")", ";", "const", "bodyBbox", "=", "document", ".", "body", ".", "getBoundingClientRect", "(", ")", ";", "const", "containerAbsoluteTop", "=", "bbox", ".", "top", "-", "bodyBbox", ".", "top", ";", "const", "sidebarAbsoluteTop", "=", "sidebarBbox", ".", "top", "-", "bodyBbox", ".", "top", ";", "const", "marginTop", "=", "sidebarAbsoluteTop", "-", "containerAbsoluteTop", ";", "const", "start", "=", "containerAbsoluteTop", "-", "topOffset", ";", "const", "stop", "=", "bbox", ".", "height", "+", "containerAbsoluteTop", "-", "sidebarBbox", ".", "height", "-", "marginTop", "-", "topOffset", ";", "return", "{", "start", ",", "stop", ",", "}", ";", "}"], "docstring": "Defines the limits where to start or stop the stickiness\n@param {HTMLElement} parent the outer container of the sidebar\n@param {HTMLElement} sidebar the sidebar\n@param {number} topOffset an optional top offset for sticky menu", "docstring_tokens": ["Defines", "the", "limits", "where", "to", "start", "or", "stop", "the", "stickiness"], "sha": "2a21b5226908f1f71c9ac28372de56d01eda813d", "url": "https://github.com/algolia/vue-instantsearch/blob/2a21b5226908f1f71c9ac28372de56d01eda813d/docs/assets/js/fix-sidebar.js#L42-L57", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "around", "original_string": "function around (obj, method, fn) {\n var old = obj[method]\n\n obj[method] = function () {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) args[i] = arguments[i]\n return fn.call(this, old, args)\n }\n}", "language": "javascript", "code": "function around (obj, method, fn) {\n var old = obj[method]\n\n obj[method] = function () {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) args[i] = arguments[i]\n return fn.call(this, old, args)\n }\n}", "code_tokens": ["function", "around", "(", "obj", ",", "method", ",", "fn", ")", "{", "var", "old", "=", "obj", "[", "method", "]", "obj", "[", "method", "]", "=", "function", "(", ")", "{", "var", "args", "=", "new", "Array", "(", "arguments", ".", "length", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "args", "[", "i", "]", "=", "arguments", "[", "i", "]", "return", "fn", ".", "call", "(", "this", ",", "old", ",", "args", ")", "}", "}"], "docstring": "Install an around function; AOP.", "docstring_tokens": ["Install", "an", "around", "function", ";", "AOP", "."], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L70-L78", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "before", "original_string": "function before (obj, method, fn) {\n var old = obj[method]\n\n obj[method] = function () {\n fn.call(this)\n old.apply(this, arguments)\n }\n}", "language": "javascript", "code": "function before (obj, method, fn) {\n var old = obj[method]\n\n obj[method] = function () {\n fn.call(this)\n old.apply(this, arguments)\n }\n}", "code_tokens": ["function", "before", "(", "obj", ",", "method", ",", "fn", ")", "{", "var", "old", "=", "obj", "[", "method", "]", "obj", "[", "method", "]", "=", "function", "(", ")", "{", "fn", ".", "call", "(", "this", ")", "old", ".", "apply", "(", "this", ",", "arguments", ")", "}", "}"], "docstring": "Install a before function; AOP.", "docstring_tokens": ["Install", "a", "before", "function", ";", "AOP", "."], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L84-L91", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "copyTemplate", "original_string": "function copyTemplate (from, to) {\n write(to, fs.readFileSync(path.join(TEMPLATE_DIR, from), 'utf-8'))\n}", "language": "javascript", "code": "function copyTemplate (from, to) {\n write(to, fs.readFileSync(path.join(TEMPLATE_DIR, from), 'utf-8'))\n}", "code_tokens": ["function", "copyTemplate", "(", "from", ",", "to", ")", "{", "write", "(", "to", ",", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "TEMPLATE_DIR", ",", "from", ")", ",", "'utf-8'", ")", ")", "}"], "docstring": "Copy file from template directory.", "docstring_tokens": ["Copy", "file", "from", "template", "directory", "."], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L113-L115", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "copyTemplateMulti", "original_string": "function copyTemplateMulti (fromDir, toDir, nameGlob) {\n fs.readdirSync(path.join(TEMPLATE_DIR, fromDir))\n .filter(minimatch.filter(nameGlob, { matchBase: true }))\n .forEach(function (name) {\n copyTemplate(path.join(fromDir, name), path.join(toDir, name))\n })\n}", "language": "javascript", "code": "function copyTemplateMulti (fromDir, toDir, nameGlob) {\n fs.readdirSync(path.join(TEMPLATE_DIR, fromDir))\n .filter(minimatch.filter(nameGlob, { matchBase: true }))\n .forEach(function (name) {\n copyTemplate(path.join(fromDir, name), path.join(toDir, name))\n })\n}", "code_tokens": ["function", "copyTemplateMulti", "(", "fromDir", ",", "toDir", ",", "nameGlob", ")", "{", "fs", ".", "readdirSync", "(", "path", ".", "join", "(", "TEMPLATE_DIR", ",", "fromDir", ")", ")", ".", "filter", "(", "minimatch", ".", "filter", "(", "nameGlob", ",", "{", "matchBase", ":", "true", "}", ")", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "copyTemplate", "(", "path", ".", "join", "(", "fromDir", ",", "name", ")", ",", "path", ".", "join", "(", "toDir", ",", "name", ")", ")", "}", ")", "}"], "docstring": "Copy multiple files from template directory.", "docstring_tokens": ["Copy", "multiple", "files", "from", "template", "directory", "."], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L121-L127", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "createAppName", "original_string": "function createAppName (pathName) {\n return path.basename(pathName)\n .replace(/[^A-Za-z0-9.-]+/g, '-')\n .replace(/^[-_.]+|-+$/g, '')\n .toLowerCase()\n}", "language": "javascript", "code": "function createAppName (pathName) {\n return path.basename(pathName)\n .replace(/[^A-Za-z0-9.-]+/g, '-')\n .replace(/^[-_.]+|-+$/g, '')\n .toLowerCase()\n}", "code_tokens": ["function", "createAppName", "(", "pathName", ")", "{", "return", "path", ".", "basename", "(", "pathName", ")", ".", "replace", "(", "/", "[^A-Za-z0-9.-]+", "/", "g", ",", "'-'", ")", ".", "replace", "(", "/", "^[-_.]+|-+$", "/", "g", ",", "''", ")", ".", "toLowerCase", "(", ")", "}"], "docstring": "Create an app name from a directory path, fitting npm naming requirements.\n\n@param {String} pathName", "docstring_tokens": ["Create", "an", "app", "name", "from", "a", "directory", "path", "fitting", "npm", "naming", "requirements", "."], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L367-L372", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "emptyDirectory", "original_string": "function emptyDirectory (dir, fn) {\n fs.readdir(dir, function (err, files) {\n if (err && err.code !== 'ENOENT') throw err\n fn(!files || !files.length)\n })\n}", "language": "javascript", "code": "function emptyDirectory (dir, fn) {\n fs.readdir(dir, function (err, files) {\n if (err && err.code !== 'ENOENT') throw err\n fn(!files || !files.length)\n })\n}", "code_tokens": ["function", "emptyDirectory", "(", "dir", ",", "fn", ")", "{", "fs", ".", "readdir", "(", "dir", ",", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", "&&", "err", ".", "code", "!==", "'ENOENT'", ")", "throw", "err", "fn", "(", "!", "files", "||", "!", "files", ".", "length", ")", "}", ")", "}"], "docstring": "Check if the given directory `dir` is empty.\n\n@param {String} dir\n@param {Function} fn", "docstring_tokens": ["Check", "if", "the", "given", "directory", "dir", "is", "empty", "."], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L381-L386", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "exit", "original_string": "function exit (code) {\n // flush output for Node.js Windows pipe bug\n // https://github.com/joyent/node/issues/6247 is just one bug example\n // https://github.com/visionmedia/mocha/issues/333 has a good discussion\n function done () {\n if (!(draining--)) _exit(code)\n }\n\n var draining = 0\n var streams = [process.stdout, process.stderr]\n\n exit.exited = true\n\n streams.forEach(function (stream) {\n // submit empty write request and wait for completion\n draining += 1\n stream.write('', done)\n })\n\n done()\n}", "language": "javascript", "code": "function exit (code) {\n // flush output for Node.js Windows pipe bug\n // https://github.com/joyent/node/issues/6247 is just one bug example\n // https://github.com/visionmedia/mocha/issues/333 has a good discussion\n function done () {\n if (!(draining--)) _exit(code)\n }\n\n var draining = 0\n var streams = [process.stdout, process.stderr]\n\n exit.exited = true\n\n streams.forEach(function (stream) {\n // submit empty write request and wait for completion\n draining += 1\n stream.write('', done)\n })\n\n done()\n}", "code_tokens": ["function", "exit", "(", "code", ")", "{", "function", "done", "(", ")", "{", "if", "(", "!", "(", "draining", "--", ")", ")", "_exit", "(", "code", ")", "}", "var", "draining", "=", "0", "var", "streams", "=", "[", "process", ".", "stdout", ",", "process", ".", "stderr", "]", "exit", ".", "exited", "=", "true", "streams", ".", "forEach", "(", "function", "(", "stream", ")", "{", "draining", "+=", "1", "stream", ".", "write", "(", "''", ",", "done", ")", "}", ")", "done", "(", ")", "}"], "docstring": "Graceful exit for async STDIO", "docstring_tokens": ["Graceful", "exit", "for", "async", "STDIO"], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L392-L412", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "loadTemplate", "original_string": "function loadTemplate (name) {\n var contents = fs.readFileSync(path.join(__dirname, '..', 'templates', (name + '.ejs')), 'utf-8')\n var locals = Object.create(null)\n\n function render () {\n return ejs.render(contents, locals, {\n escape: util.inspect\n })\n }\n\n return {\n locals: locals,\n render: render\n }\n}", "language": "javascript", "code": "function loadTemplate (name) {\n var contents = fs.readFileSync(path.join(__dirname, '..', 'templates', (name + '.ejs')), 'utf-8')\n var locals = Object.create(null)\n\n function render () {\n return ejs.render(contents, locals, {\n escape: util.inspect\n })\n }\n\n return {\n locals: locals,\n render: render\n }\n}", "code_tokens": ["function", "loadTemplate", "(", "name", ")", "{", "var", "contents", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "__dirname", ",", "'..'", ",", "'templates'", ",", "(", "name", "+", "'.ejs'", ")", ")", ",", "'utf-8'", ")", "var", "locals", "=", "Object", ".", "create", "(", "null", ")", "function", "render", "(", ")", "{", "return", "ejs", ".", "render", "(", "contents", ",", "locals", ",", "{", "escape", ":", "util", ".", "inspect", "}", ")", "}", "return", "{", "locals", ":", "locals", ",", "render", ":", "render", "}", "}"], "docstring": "Load template file.", "docstring_tokens": ["Load", "template", "file", "."], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L427-L441", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "main", "original_string": "function main () {\n // Path\n var destinationPath = program.args.shift() || '.'\n\n // App name\n var appName = createAppName(path.resolve(destinationPath)) || 'hello-world'\n\n // View engine\n if (program.view === true) {\n if (program.ejs) program.view = 'ejs'\n if (program.hbs) program.view = 'hbs'\n if (program.hogan) program.view = 'hjs'\n if (program.pug) program.view = 'pug'\n }\n\n // Default view engine\n if (program.view === true) {\n warning('the default view engine will not be jade in future releases\\n' +\n \"use `--view=jade' or `--help' for additional options\")\n program.view = 'jade'\n }\n\n // Generate application\n emptyDirectory(destinationPath, function (empty) {\n if (empty || program.force) {\n createApplication(appName, destinationPath)\n } else {\n confirm('destination is not empty, continue? [y/N] ', function (ok) {\n if (ok) {\n process.stdin.destroy()\n createApplication(appName, destinationPath)\n } else {\n console.error('aborting')\n exit(1)\n }\n })\n }\n })\n}", "language": "javascript", "code": "function main () {\n // Path\n var destinationPath = program.args.shift() || '.'\n\n // App name\n var appName = createAppName(path.resolve(destinationPath)) || 'hello-world'\n\n // View engine\n if (program.view === true) {\n if (program.ejs) program.view = 'ejs'\n if (program.hbs) program.view = 'hbs'\n if (program.hogan) program.view = 'hjs'\n if (program.pug) program.view = 'pug'\n }\n\n // Default view engine\n if (program.view === true) {\n warning('the default view engine will not be jade in future releases\\n' +\n \"use `--view=jade' or `--help' for additional options\")\n program.view = 'jade'\n }\n\n // Generate application\n emptyDirectory(destinationPath, function (empty) {\n if (empty || program.force) {\n createApplication(appName, destinationPath)\n } else {\n confirm('destination is not empty, continue? [y/N] ', function (ok) {\n if (ok) {\n process.stdin.destroy()\n createApplication(appName, destinationPath)\n } else {\n console.error('aborting')\n exit(1)\n }\n })\n }\n })\n}", "code_tokens": ["function", "main", "(", ")", "{", "var", "destinationPath", "=", "program", ".", "args", ".", "shift", "(", ")", "||", "'.'", "var", "appName", "=", "createAppName", "(", "path", ".", "resolve", "(", "destinationPath", ")", ")", "||", "'hello-world'", "if", "(", "program", ".", "view", "===", "true", ")", "{", "if", "(", "program", ".", "ejs", ")", "program", ".", "view", "=", "'ejs'", "if", "(", "program", ".", "hbs", ")", "program", ".", "view", "=", "'hbs'", "if", "(", "program", ".", "hogan", ")", "program", ".", "view", "=", "'hjs'", "if", "(", "program", ".", "pug", ")", "program", ".", "view", "=", "'pug'", "}", "if", "(", "program", ".", "view", "===", "true", ")", "{", "warning", "(", "'the default view engine will not be jade in future releases\\n'", "+", "\\n", ")", "\"use `--view=jade' or `--help' for additional options\"", "}", "program", ".", "view", "=", "'jade'", "}"], "docstring": "Main program.", "docstring_tokens": ["Main", "program", "."], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L447-L485", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "mkdir", "original_string": "function mkdir (base, dir) {\n var loc = path.join(base, dir)\n\n console.log(' \\x1b[36mcreate\\x1b[0m : ' + loc + path.sep)\n mkdirp.sync(loc, MODE_0755)\n}", "language": "javascript", "code": "function mkdir (base, dir) {\n var loc = path.join(base, dir)\n\n console.log(' \\x1b[36mcreate\\x1b[0m : ' + loc + path.sep)\n mkdirp.sync(loc, MODE_0755)\n}", "code_tokens": ["function", "mkdir", "(", "base", ",", "dir", ")", "{", "var", "loc", "=", "path", ".", "join", "(", "base", ",", "dir", ")", "console", ".", "log", "(", "' \\x1b[36mcreate\\x1b[0m : '", "+", "\\x1b", "+", "\\x1b", ")", "loc", "}"], "docstring": "Make the given dir relative to base.\n\n@param {string} base\n@param {string} dir", "docstring_tokens": ["Make", "the", "given", "dir", "relative", "to", "base", "."], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L494-L499", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "renamedOption", "original_string": "function renamedOption (originalName, newName) {\n return function (val) {\n warning(util.format(\"option `%s' has been renamed to `%s'\", originalName, newName))\n return val\n }\n}", "language": "javascript", "code": "function renamedOption (originalName, newName) {\n return function (val) {\n warning(util.format(\"option `%s' has been renamed to `%s'\", originalName, newName))\n return val\n }\n}", "code_tokens": ["function", "renamedOption", "(", "originalName", ",", "newName", ")", "{", "return", "function", "(", "val", ")", "{", "warning", "(", "util", ".", "format", "(", "\"option `%s' has been renamed to `%s'\"", ",", "originalName", ",", "newName", ")", ")", "return", "val", "}", "}"], "docstring": "Generate a callback function for commander to warn about renamed option.\n\n@param {String} originalName\n@param {String} newName", "docstring_tokens": ["Generate", "a", "callback", "function", "for", "commander", "to", "warn", "about", "renamed", "option", "."], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L508-L513", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "warning", "original_string": "function warning (message) {\n console.error()\n message.split('\\n').forEach(function (line) {\n console.error(' warning: %s', line)\n })\n console.error()\n}", "language": "javascript", "code": "function warning (message) {\n console.error()\n message.split('\\n').forEach(function (line) {\n console.error(' warning: %s', line)\n })\n console.error()\n}", "code_tokens": ["function", "warning", "(", "message", ")", "{", "console", ".", "error", "(", ")", "message", ".", "split", "(", "'\\n'", ")", ".", "\\n", "forEach", "(", "function", "(", "line", ")", "{", "console", ".", "error", "(", "' warning: %s'", ",", "line", ")", "}", ")", "}"], "docstring": "Display a warning similar to how errors are displayed by commander.\n\n@param {String} message", "docstring_tokens": ["Display", "a", "warning", "similar", "to", "how", "errors", "are", "displayed", "by", "commander", "."], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L521-L527", "partition": "test"} {"repo": "expressjs/generator", "path": "bin/express-cli.js", "func_name": "write", "original_string": "function write (file, str, mode) {\n fs.writeFileSync(file, str, { mode: mode || MODE_0666 })\n console.log(' \\x1b[36mcreate\\x1b[0m : ' + file)\n}", "language": "javascript", "code": "function write (file, str, mode) {\n fs.writeFileSync(file, str, { mode: mode || MODE_0666 })\n console.log(' \\x1b[36mcreate\\x1b[0m : ' + file)\n}", "code_tokens": ["function", "write", "(", "file", ",", "str", ",", "mode", ")", "{", "fs", ".", "writeFileSync", "(", "file", ",", "str", ",", "{", "mode", ":", "mode", "||", "MODE_0666", "}", ")", "console", ".", "log", "(", "' \\x1b[36mcreate\\x1b[0m : '", "+", "\\x1b", ")", "}"], "docstring": "echo str > file.\n\n@param {String} file\n@param {String} str", "docstring_tokens": ["echo", "str", ">", "file", "."], "sha": "d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d", "url": "https://github.com/expressjs/generator/blob/d1f3fcc6ccc7ab8986fb3438c82ab1a1f20dc50d/bin/express-cli.js#L536-L539", "partition": "test"} {"repo": "maartenbreddels/ipyvolume", "path": "js/src/figure.js", "func_name": "bind_d3", "original_string": "function bind_d3(f, context) {\n return function() {\n var args = [this].concat([].slice.call(arguments)) // convert argument to array\n f.apply(context, args)\n }\n}", "language": "javascript", "code": "function bind_d3(f, context) {\n return function() {\n var args = [this].concat([].slice.call(arguments)) // convert argument to array\n f.apply(context, args)\n }\n}", "code_tokens": ["function", "bind_d3", "(", "f", ",", "context", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "[", "this", "]", ".", "concat", "(", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ")", "f", ".", "apply", "(", "context", ",", "args", ")", "}", "}"], "docstring": "similar to _.bind, except it puts this as first argument to f, followed be other arguments, and make context f's this", "docstring_tokens": ["similar", "to", "_", ".", "bind", "except", "it", "puts", "this", "as", "first", "argument", "to", "f", "followed", "be", "other", "arguments", "and", "make", "context", "f", "s", "this"], "sha": "e68b72852b61276f8e6793bc8811f5b2432a155f", "url": "https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/js/src/figure.js#L39-L44", "partition": "test"} {"repo": "callstack/haul", "path": "src/commands/bundle.js", "func_name": "adjustOptions", "original_string": "function adjustOptions(options) {\n const directory = process.cwd();\n const configPath = getWebpackConfigPath(directory, options.config);\n const haulOptions = getHaulConfig(configPath, logger);\n\n if (haulOptions.platforms) {\n const platformOption =\n command.options && command.options.find(_ => _.name === 'platform');\n if (platformOption) {\n platformOption.choices = [];\n for (const platformName in haulOptions.platforms) {\n if (\n Object.prototype.hasOwnProperty.call(\n haulOptions.platforms,\n platformName\n )\n ) {\n if (platformOption.choices) {\n platformOption.choices.push({\n value: platformName,\n description: `Builds ${haulOptions.platforms[\n platformName\n ]} bundle`,\n });\n }\n }\n }\n }\n }\n}", "language": "javascript", "code": "function adjustOptions(options) {\n const directory = process.cwd();\n const configPath = getWebpackConfigPath(directory, options.config);\n const haulOptions = getHaulConfig(configPath, logger);\n\n if (haulOptions.platforms) {\n const platformOption =\n command.options && command.options.find(_ => _.name === 'platform');\n if (platformOption) {\n platformOption.choices = [];\n for (const platformName in haulOptions.platforms) {\n if (\n Object.prototype.hasOwnProperty.call(\n haulOptions.platforms,\n platformName\n )\n ) {\n if (platformOption.choices) {\n platformOption.choices.push({\n value: platformName,\n description: `Builds ${haulOptions.platforms[\n platformName\n ]} bundle`,\n });\n }\n }\n }\n }\n }\n}", "code_tokens": ["function", "adjustOptions", "(", "options", ")", "{", "const", "directory", "=", "process", ".", "cwd", "(", ")", ";", "const", "configPath", "=", "getWebpackConfigPath", "(", "directory", ",", "options", ".", "config", ")", ";", "const", "haulOptions", "=", "getHaulConfig", "(", "configPath", ",", "logger", ")", ";", "if", "(", "haulOptions", ".", "platforms", ")", "{", "const", "platformOption", "=", "command", ".", "options", "&&", "command", ".", "options", ".", "find", "(", "_", "=>", "_", ".", "name", "===", "'platform'", ")", ";", "if", "(", "platformOption", ")", "{", "platformOption", ".", "choices", "=", "[", "]", ";", "for", "(", "const", "platformName", "in", "haulOptions", ".", "platforms", ")", "{", "if", "(", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "haulOptions", ".", "platforms", ",", "platformName", ")", ")", "{", "if", "(", "platformOption", ".", "choices", ")", "{", "platformOption", ".", "choices", ".", "push", "(", "{", "value", ":", "platformName", ",", "description", ":", "`", "${", "haulOptions", ".", "platforms", "[", "platformName", "]", "}", "`", ",", "}", ")", ";", "}", "}", "}", "}", "}", "}"], "docstring": "Allow config file to override the list of availiable platforms", "docstring_tokens": ["Allow", "config", "file", "to", "override", "the", "list", "of", "availiable", "platforms"], "sha": "b0b001c979f77c4a1656bfae42de0bb138858198", "url": "https://github.com/callstack/haul/blob/b0b001c979f77c4a1656bfae42de0bb138858198/src/commands/bundle.js#L114-L143", "partition": "test"} {"repo": "callstack/haul", "path": "src/server/middleware/devToolsMiddleware.js", "func_name": "devToolsMiddleware", "original_string": "function devToolsMiddleware(debuggerProxy) {\n return (req, res, next) => {\n switch (req.cleanPath) {\n /**\n * Request for the debugger frontend\n */\n case '/debugger-ui/':\n case '/debugger-ui': {\n const readStream = fs.createReadStream(\n path.join(__dirname, '../assets/debugger.html')\n );\n res.writeHead(200, { 'Content-Type': 'text/html' });\n readStream.pipe(res);\n break;\n }\n\n /**\n * Request for the debugger worker\n */\n case '/debugger-ui/debuggerWorker.js':\n case '/debuggerWorker.js': {\n const readStream = fs.createReadStream(\n path.join(__dirname, '../assets/debuggerWorker.js')\n );\n res.writeHead(200, { 'Content-Type': 'application/javascript' });\n readStream.pipe(res);\n break;\n }\n\n /**\n * Request for (maybe) launching devtools\n */\n case '/launch-js-devtools': {\n if (!debuggerProxy.isDebuggerConnected()) {\n launchBrowser(`http://localhost:${req.socket.localPort}/debugger-ui`);\n }\n res.end('OK');\n break;\n }\n\n default:\n next();\n }\n };\n}", "language": "javascript", "code": "function devToolsMiddleware(debuggerProxy) {\n return (req, res, next) => {\n switch (req.cleanPath) {\n /**\n * Request for the debugger frontend\n */\n case '/debugger-ui/':\n case '/debugger-ui': {\n const readStream = fs.createReadStream(\n path.join(__dirname, '../assets/debugger.html')\n );\n res.writeHead(200, { 'Content-Type': 'text/html' });\n readStream.pipe(res);\n break;\n }\n\n /**\n * Request for the debugger worker\n */\n case '/debugger-ui/debuggerWorker.js':\n case '/debuggerWorker.js': {\n const readStream = fs.createReadStream(\n path.join(__dirname, '../assets/debuggerWorker.js')\n );\n res.writeHead(200, { 'Content-Type': 'application/javascript' });\n readStream.pipe(res);\n break;\n }\n\n /**\n * Request for (maybe) launching devtools\n */\n case '/launch-js-devtools': {\n if (!debuggerProxy.isDebuggerConnected()) {\n launchBrowser(`http://localhost:${req.socket.localPort}/debugger-ui`);\n }\n res.end('OK');\n break;\n }\n\n default:\n next();\n }\n };\n}", "code_tokens": ["function", "devToolsMiddleware", "(", "debuggerProxy", ")", "{", "return", "(", "req", ",", "res", ",", "next", ")", "=>", "{", "switch", "(", "req", ".", "cleanPath", ")", "{", "case", "'/debugger-ui/'", ":", "case", "'/debugger-ui'", ":", "{", "const", "readStream", "=", "fs", ".", "createReadStream", "(", "path", ".", "join", "(", "__dirname", ",", "'../assets/debugger.html'", ")", ")", ";", "res", ".", "writeHead", "(", "200", ",", "{", "'Content-Type'", ":", "'text/html'", "}", ")", ";", "readStream", ".", "pipe", "(", "res", ")", ";", "break", ";", "}", "case", "'/debugger-ui/debuggerWorker.js'", ":", "case", "'/debuggerWorker.js'", ":", "{", "const", "readStream", "=", "fs", ".", "createReadStream", "(", "path", ".", "join", "(", "__dirname", ",", "'../assets/debuggerWorker.js'", ")", ")", ";", "res", ".", "writeHead", "(", "200", ",", "{", "'Content-Type'", ":", "'application/javascript'", "}", ")", ";", "readStream", ".", "pipe", "(", "res", ")", ";", "break", ";", "}", "case", "'/launch-js-devtools'", ":", "{", "if", "(", "!", "debuggerProxy", ".", "isDebuggerConnected", "(", ")", ")", "{", "launchBrowser", "(", "`", "${", "req", ".", "socket", ".", "localPort", "}", "`", ")", ";", "}", "res", ".", "end", "(", "'OK'", ")", ";", "break", ";", "}", "default", ":", "next", "(", ")", ";", "}", "}", ";", "}"], "docstring": "Devtools middleware compatible with default React Native implementation", "docstring_tokens": ["Devtools", "middleware", "compatible", "with", "default", "React", "Native", "implementation"], "sha": "b0b001c979f77c4a1656bfae42de0bb138858198", "url": "https://github.com/callstack/haul/blob/b0b001c979f77c4a1656bfae42de0bb138858198/src/server/middleware/devToolsMiddleware.js#L49-L93", "partition": "test"} {"repo": "vanruesc/postprocessing", "path": "demo/src/index.js", "func_name": "onLoad", "original_string": "function onLoad(event) {\n\n\t// Prepare the render pass.\n\tevent.demo.renderPass.camera = event.demo.camera;\n\n\tdocument.getElementById(\"viewport\").children[0].style.display = \"none\";\n\n}", "language": "javascript", "code": "function onLoad(event) {\n\n\t// Prepare the render pass.\n\tevent.demo.renderPass.camera = event.demo.camera;\n\n\tdocument.getElementById(\"viewport\").children[0].style.display = \"none\";\n\n}", "code_tokens": ["function", "onLoad", "(", "event", ")", "{", "event", ".", "demo", ".", "renderPass", ".", "camera", "=", "event", ".", "demo", ".", "camera", ";", "document", ".", "getElementById", "(", "\"viewport\"", ")", ".", "children", "[", "0", "]", ".", "style", ".", "display", "=", "\"none\"", ";", "}"], "docstring": "Handles demo load events.\n\n@private\n@param {Event} event - An event.", "docstring_tokens": ["Handles", "demo", "load", "events", "."], "sha": "43a6776c2a391ddd3539262e078b0f35b5563004", "url": "https://github.com/vanruesc/postprocessing/blob/43a6776c2a391ddd3539262e078b0f35b5563004/demo/src/index.js#L94-L101", "partition": "test"} {"repo": "vanruesc/postprocessing", "path": "build/postprocessing.esm.js", "func_name": "prefixSubstrings", "original_string": "function prefixSubstrings(prefix, substrings, strings) {\n\n\tlet prefixed, regExp;\n\n\tfor(const substring of substrings) {\n\n\t\tprefixed = \"$1\" + prefix + substring.charAt(0).toUpperCase() + substring.slice(1);\n\t\tregExp = new RegExp(\"([^\\\\.])(\\\\b\" + substring + \"\\\\b)\", \"g\");\n\n\t\tfor(const entry of strings.entries()) {\n\n\t\t\tif(entry[1] !== null) {\n\n\t\t\t\tstrings.set(entry[0], entry[1].replace(regExp, prefixed));\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}", "language": "javascript", "code": "function prefixSubstrings(prefix, substrings, strings) {\n\n\tlet prefixed, regExp;\n\n\tfor(const substring of substrings) {\n\n\t\tprefixed = \"$1\" + prefix + substring.charAt(0).toUpperCase() + substring.slice(1);\n\t\tregExp = new RegExp(\"([^\\\\.])(\\\\b\" + substring + \"\\\\b)\", \"g\");\n\n\t\tfor(const entry of strings.entries()) {\n\n\t\t\tif(entry[1] !== null) {\n\n\t\t\t\tstrings.set(entry[0], entry[1].replace(regExp, prefixed));\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}", "code_tokens": ["function", "prefixSubstrings", "(", "prefix", ",", "substrings", ",", "strings", ")", "{", "let", "prefixed", ",", "regExp", ";", "for", "(", "const", "substring", "of", "substrings", ")", "{", "prefixed", "=", "\"$1\"", "+", "prefix", "+", "substring", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "substring", ".", "slice", "(", "1", ")", ";", "regExp", "=", "new", "RegExp", "(", "\"([^\\\\.])(\\\\b\"", "+", "\\\\", "+", "\\\\", ",", "substring", ")", ";", "\"\\\\b)\"", "}", "}"], "docstring": "Prefixes substrings within the given strings.\n\n@private\n@param {String} prefix - A prefix.\n@param {String[]} substrings - The substrings.\n@param {Map} strings - A collection of named strings.", "docstring_tokens": ["Prefixes", "substrings", "within", "the", "given", "strings", "."], "sha": "43a6776c2a391ddd3539262e078b0f35b5563004", "url": "https://github.com/vanruesc/postprocessing/blob/43a6776c2a391ddd3539262e078b0f35b5563004/build/postprocessing.esm.js#L2400-L2421", "partition": "test"} {"repo": "vanruesc/postprocessing", "path": "build/postprocessing.esm.js", "func_name": "createCanvas", "original_string": "function createCanvas(width, height, data, channels) {\n\n\tconst canvas = document.createElementNS(\"http://www.w3.org/1999/xhtml\", \"canvas\");\n\tconst context = canvas.getContext(\"2d\");\n\n\tconst imageData = context.createImageData(width, height);\n\tconst target = imageData.data;\n\n\tlet x, y;\n\tlet i, j;\n\n\tfor(y = 0; y < height; ++y) {\n\n\t\tfor(x = 0; x < width; ++x) {\n\n\t\t\ti = (y * width + x) * 4;\n\t\t\tj = (y * width + x) * channels;\n\n\t\t\ttarget[i] = (channels > 0) ? data[j] : 0;\n\t\t\ttarget[i + 1] = (channels > 1) ? data[j + 1] : 0;\n\t\t\ttarget[i + 2] = (channels > 2) ? data[j + 2] : 0;\n\t\t\ttarget[i + 3] = (channels > 3) ? data[j + 3] : 255;\n\n\t\t}\n\n\t}\n\n\tcanvas.width = width;\n\tcanvas.height = height;\n\n\tcontext.putImageData(imageData, 0, 0);\n\n\treturn canvas;\n\n}", "language": "javascript", "code": "function createCanvas(width, height, data, channels) {\n\n\tconst canvas = document.createElementNS(\"http://www.w3.org/1999/xhtml\", \"canvas\");\n\tconst context = canvas.getContext(\"2d\");\n\n\tconst imageData = context.createImageData(width, height);\n\tconst target = imageData.data;\n\n\tlet x, y;\n\tlet i, j;\n\n\tfor(y = 0; y < height; ++y) {\n\n\t\tfor(x = 0; x < width; ++x) {\n\n\t\t\ti = (y * width + x) * 4;\n\t\t\tj = (y * width + x) * channels;\n\n\t\t\ttarget[i] = (channels > 0) ? data[j] : 0;\n\t\t\ttarget[i + 1] = (channels > 1) ? data[j + 1] : 0;\n\t\t\ttarget[i + 2] = (channels > 2) ? data[j + 2] : 0;\n\t\t\ttarget[i + 3] = (channels > 3) ? data[j + 3] : 255;\n\n\t\t}\n\n\t}\n\n\tcanvas.width = width;\n\tcanvas.height = height;\n\n\tcontext.putImageData(imageData, 0, 0);\n\n\treturn canvas;\n\n}", "code_tokens": ["function", "createCanvas", "(", "width", ",", "height", ",", "data", ",", "channels", ")", "{", "const", "canvas", "=", "document", ".", "createElementNS", "(", "\"http://www.w3.org/1999/xhtml\"", ",", "\"canvas\"", ")", ";", "const", "context", "=", "canvas", ".", "getContext", "(", "\"2d\"", ")", ";", "const", "imageData", "=", "context", ".", "createImageData", "(", "width", ",", "height", ")", ";", "const", "target", "=", "imageData", ".", "data", ";", "let", "x", ",", "y", ";", "let", "i", ",", "j", ";", "for", "(", "y", "=", "0", ";", "y", "<", "height", ";", "++", "y", ")", "{", "for", "(", "x", "=", "0", ";", "x", "<", "width", ";", "++", "x", ")", "{", "i", "=", "(", "y", "*", "width", "+", "x", ")", "*", "4", ";", "j", "=", "(", "y", "*", "width", "+", "x", ")", "*", "channels", ";", "target", "[", "i", "]", "=", "(", "channels", ">", "0", ")", "?", "data", "[", "j", "]", ":", "0", ";", "target", "[", "i", "+", "1", "]", "=", "(", "channels", ">", "1", ")", "?", "data", "[", "j", "+", "1", "]", ":", "0", ";", "target", "[", "i", "+", "2", "]", "=", "(", "channels", ">", "2", ")", "?", "data", "[", "j", "+", "2", "]", ":", "0", ";", "target", "[", "i", "+", "3", "]", "=", "(", "channels", ">", "3", ")", "?", "data", "[", "j", "+", "3", "]", ":", "255", ";", "}", "}", "canvas", ".", "width", "=", "width", ";", "canvas", ".", "height", "=", "height", ";", "context", ".", "putImageData", "(", "imageData", ",", "0", ",", "0", ")", ";", "return", "canvas", ";", "}"], "docstring": "Creates a new canvas from raw image data.\n\n@private\n@param {Number} width - The image width.\n@param {Number} height - The image height.\n@param {Uint8ClampedArray} data - The image data.\n@param {Number} channels - The color channels used for a single pixel.\n@return {Canvas} The canvas.", "docstring_tokens": ["Creates", "a", "new", "canvas", "from", "raw", "image", "data", "."], "sha": "43a6776c2a391ddd3539262e078b0f35b5563004", "url": "https://github.com/vanruesc/postprocessing/blob/43a6776c2a391ddd3539262e078b0f35b5563004/build/postprocessing.esm.js#L7925-L7959", "partition": "test"} {"repo": "vanruesc/postprocessing", "path": "build/postprocessing.esm.js", "func_name": "smoothArea", "original_string": "function smoothArea(d, b) {\n\n\tconst a1 = b.min;\n\tconst a2 = b.max;\n\n\tconst b1X = Math.sqrt(a1.x * 2.0) * 0.5;\n\tconst b1Y = Math.sqrt(a1.y * 2.0) * 0.5;\n\tconst b2X = Math.sqrt(a2.x * 2.0) * 0.5;\n\tconst b2Y = Math.sqrt(a2.y * 2.0) * 0.5;\n\n\tconst p = saturate(d / SMOOTH_MAX_DISTANCE);\n\n\ta1.set(lerp(b1X, a1.x, p), lerp(b1Y, a1.y, p));\n\ta2.set(lerp(b2X, a2.x, p), lerp(b2Y, a2.y, p));\n\n\treturn b;\n\n}", "language": "javascript", "code": "function smoothArea(d, b) {\n\n\tconst a1 = b.min;\n\tconst a2 = b.max;\n\n\tconst b1X = Math.sqrt(a1.x * 2.0) * 0.5;\n\tconst b1Y = Math.sqrt(a1.y * 2.0) * 0.5;\n\tconst b2X = Math.sqrt(a2.x * 2.0) * 0.5;\n\tconst b2Y = Math.sqrt(a2.y * 2.0) * 0.5;\n\n\tconst p = saturate(d / SMOOTH_MAX_DISTANCE);\n\n\ta1.set(lerp(b1X, a1.x, p), lerp(b1Y, a1.y, p));\n\ta2.set(lerp(b2X, a2.x, p), lerp(b2Y, a2.y, p));\n\n\treturn b;\n\n}", "code_tokens": ["function", "smoothArea", "(", "d", ",", "b", ")", "{", "const", "a1", "=", "b", ".", "min", ";", "const", "a2", "=", "b", ".", "max", ";", "const", "b1X", "=", "Math", ".", "sqrt", "(", "a1", ".", "x", "*", "2.0", ")", "*", "0.5", ";", "const", "b1Y", "=", "Math", ".", "sqrt", "(", "a1", ".", "y", "*", "2.0", ")", "*", "0.5", ";", "const", "b2X", "=", "Math", ".", "sqrt", "(", "a2", ".", "x", "*", "2.0", ")", "*", "0.5", ";", "const", "b2Y", "=", "Math", ".", "sqrt", "(", "a2", ".", "y", "*", "2.0", ")", "*", "0.5", ";", "const", "p", "=", "saturate", "(", "d", "/", "SMOOTH_MAX_DISTANCE", ")", ";", "a1", ".", "set", "(", "lerp", "(", "b1X", ",", "a1", ".", "x", ",", "p", ")", ",", "lerp", "(", "b1Y", ",", "a1", ".", "y", ",", "p", ")", ")", ";", "a2", ".", "set", "(", "lerp", "(", "b2X", ",", "a2", ".", "x", ",", "p", ")", ",", "lerp", "(", "b2Y", ",", "a2", ".", "y", ",", "p", ")", ")", ";", "return", "b", ";", "}"], "docstring": "A smoothing function for small U-patterns.\n\n@private\n@param {Number} d - A smoothing factor.\n@param {Box2} b - The area that should be smoothed.\n@return {Box2} The smoothed area.", "docstring_tokens": ["A", "smoothing", "function", "for", "small", "U", "-", "patterns", "."], "sha": "43a6776c2a391ddd3539262e078b0f35b5563004", "url": "https://github.com/vanruesc/postprocessing/blob/43a6776c2a391ddd3539262e078b0f35b5563004/build/postprocessing.esm.js#L8225-L8242", "partition": "test"} {"repo": "vanruesc/postprocessing", "path": "build/postprocessing.esm.js", "func_name": "calculateDiagonalAreaForPixel", "original_string": "function calculateDiagonalAreaForPixel(p1, p2, pX, pY) {\n\n\tlet a;\n\tlet x, y;\n\tlet offsetX, offsetY;\n\n\tfor(a = 0, y = 0; y < DIAGONAL_SAMPLES; ++y) {\n\n\t\tfor(x = 0; x < DIAGONAL_SAMPLES; ++x) {\n\n\t\t\toffsetX = x / (DIAGONAL_SAMPLES - 1.0);\n\t\t\toffsetY = y / (DIAGONAL_SAMPLES - 1.0);\n\n\t\t\tif(isInsideArea(p1, p2, pX + offsetX, pY + offsetY)) {\n\n\t\t\t\t++a;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn a / (DIAGONAL_SAMPLES * DIAGONAL_SAMPLES);\n\n}", "language": "javascript", "code": "function calculateDiagonalAreaForPixel(p1, p2, pX, pY) {\n\n\tlet a;\n\tlet x, y;\n\tlet offsetX, offsetY;\n\n\tfor(a = 0, y = 0; y < DIAGONAL_SAMPLES; ++y) {\n\n\t\tfor(x = 0; x < DIAGONAL_SAMPLES; ++x) {\n\n\t\t\toffsetX = x / (DIAGONAL_SAMPLES - 1.0);\n\t\t\toffsetY = y / (DIAGONAL_SAMPLES - 1.0);\n\n\t\t\tif(isInsideArea(p1, p2, pX + offsetX, pY + offsetY)) {\n\n\t\t\t\t++a;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn a / (DIAGONAL_SAMPLES * DIAGONAL_SAMPLES);\n\n}", "code_tokens": ["function", "calculateDiagonalAreaForPixel", "(", "p1", ",", "p2", ",", "pX", ",", "pY", ")", "{", "let", "a", ";", "let", "x", ",", "y", ";", "let", "offsetX", ",", "offsetY", ";", "for", "(", "a", "=", "0", ",", "y", "=", "0", ";", "y", "<", "DIAGONAL_SAMPLES", ";", "++", "y", ")", "{", "for", "(", "x", "=", "0", ";", "x", "<", "DIAGONAL_SAMPLES", ";", "++", "x", ")", "{", "offsetX", "=", "x", "/", "(", "DIAGONAL_SAMPLES", "-", "1.0", ")", ";", "offsetY", "=", "y", "/", "(", "DIAGONAL_SAMPLES", "-", "1.0", ")", ";", "if", "(", "isInsideArea", "(", "p1", ",", "p2", ",", "pX", "+", "offsetX", ",", "pY", "+", "offsetY", ")", ")", "{", "++", "a", ";", "}", "}", "}", "return", "a", "/", "(", "DIAGONAL_SAMPLES", "*", "DIAGONAL_SAMPLES", ")", ";", "}"], "docstring": "Calculates the area under the line p1 -> p2 for the pixel p using brute force\nsampling.\n\n@private\n@param {Vector2} p1 - The lower bounds of the area.\n@param {Vector2} p2 - The upper bounds of the area.\n@param {Number} pX - The X-coordinates.\n@param {Number} pY - The Y-coordinates.\n@return {Number} The amount of pixels inside the area relative to the total amount of sampled pixels.", "docstring_tokens": ["Calculates", "the", "area", "under", "the", "line", "p1", "-", ">", "p2", "for", "the", "pixel", "p", "using", "brute", "force", "sampling", "."], "sha": "43a6776c2a391ddd3539262e078b0f35b5563004", "url": "https://github.com/vanruesc/postprocessing/blob/43a6776c2a391ddd3539262e078b0f35b5563004/build/postprocessing.esm.js#L8681-L8706", "partition": "test"} {"repo": "vanruesc/postprocessing", "path": "build/postprocessing.esm.js", "func_name": "calculateDiagonalArea", "original_string": "function calculateDiagonalArea(pattern, p1, p2, left, offset, result) {\n\n\tconst e = diagonalEdges[pattern];\n\tconst e1 = e[0];\n\tconst e2 = e[1];\n\n\tif(e1 > 0) {\n\n\t\tp1.x += offset[0];\n\t\tp1.y += offset[1];\n\n\t}\n\n\tif(e2 > 0) {\n\n\t\tp2.x += offset[0];\n\t\tp2.y += offset[1];\n\n\t}\n\n\treturn result.set(\n\t\t1.0 - calculateDiagonalAreaForPixel(p1, p2, 1.0 + left, 0.0 + left),\n\t\tcalculateDiagonalAreaForPixel(p1, p2, 1.0 + left, 1.0 + left)\n\t);\n\n}", "language": "javascript", "code": "function calculateDiagonalArea(pattern, p1, p2, left, offset, result) {\n\n\tconst e = diagonalEdges[pattern];\n\tconst e1 = e[0];\n\tconst e2 = e[1];\n\n\tif(e1 > 0) {\n\n\t\tp1.x += offset[0];\n\t\tp1.y += offset[1];\n\n\t}\n\n\tif(e2 > 0) {\n\n\t\tp2.x += offset[0];\n\t\tp2.y += offset[1];\n\n\t}\n\n\treturn result.set(\n\t\t1.0 - calculateDiagonalAreaForPixel(p1, p2, 1.0 + left, 0.0 + left),\n\t\tcalculateDiagonalAreaForPixel(p1, p2, 1.0 + left, 1.0 + left)\n\t);\n\n}", "code_tokens": ["function", "calculateDiagonalArea", "(", "pattern", ",", "p1", ",", "p2", ",", "left", ",", "offset", ",", "result", ")", "{", "const", "e", "=", "diagonalEdges", "[", "pattern", "]", ";", "const", "e1", "=", "e", "[", "0", "]", ";", "const", "e2", "=", "e", "[", "1", "]", ";", "if", "(", "e1", ">", "0", ")", "{", "p1", ".", "x", "+=", "offset", "[", "0", "]", ";", "p1", ".", "y", "+=", "offset", "[", "1", "]", ";", "}", "if", "(", "e2", ">", "0", ")", "{", "p2", ".", "x", "+=", "offset", "[", "0", "]", ";", "p2", ".", "y", "+=", "offset", "[", "1", "]", ";", "}", "return", "result", ".", "set", "(", "1.0", "-", "calculateDiagonalAreaForPixel", "(", "p1", ",", "p2", ",", "1.0", "+", "left", ",", "0.0", "+", "left", ")", ",", "calculateDiagonalAreaForPixel", "(", "p1", ",", "p2", ",", "1.0", "+", "left", ",", "1.0", "+", "left", ")", ")", ";", "}"], "docstring": "Calculates the area under the line p1 -> p2. This includes the pixel and its\nopposite.\n\n@private\n@param {Number} pattern - A pattern index.\n@param {Vector2} p1 - The lower bounds of the area.\n@param {Vector2} p2 - The upper bounds of the area.\n@param {Number} left - The left distance.\n@param {Float32Array} offset - An offset.\n@param {Vector2} result - A target vector to store the area in.\n@return {Vector2} The area.", "docstring_tokens": ["Calculates", "the", "area", "under", "the", "line", "p1", "-", ">", "p2", ".", "This", "includes", "the", "pixel", "and", "its", "opposite", "."], "sha": "43a6776c2a391ddd3539262e078b0f35b5563004", "url": "https://github.com/vanruesc/postprocessing/blob/43a6776c2a391ddd3539262e078b0f35b5563004/build/postprocessing.esm.js#L8722-L8747", "partition": "test"} {"repo": "vanruesc/postprocessing", "path": "build/postprocessing.esm.js", "func_name": "generatePatterns", "original_string": "function generatePatterns(patterns, offset, orthogonal) {\n\n\tconst result = new Vector2();\n\n\tlet i, l;\n\tlet x, y;\n\tlet c;\n\n\tlet pattern;\n\tlet data, size;\n\n\tfor(i = 0, l = patterns.length; i < l; ++i) {\n\n\t\tpattern = patterns[i];\n\n\t\tdata = pattern.data;\n\t\tsize = pattern.width;\n\n\t\tfor(y = 0; y < size; ++y) {\n\n\t\t\tfor(x = 0; x < size; ++x) {\n\n\t\t\t\tif(orthogonal) {\n\n\t\t\t\t\tcalculateOrthogonalAreaForPattern(i, x, y, offset, result);\n\n\t\t\t\t} else {\n\n\t\t\t\t\tcalculateDiagonalAreaForPattern(i, x, y, offset, result);\n\n\t\t\t\t}\n\n\t\t\t\tc = (y * size + x) * 2;\n\n\t\t\t\tdata[c] = result.x * 255;\n\t\t\t\tdata[c + 1] = result.y * 255;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}", "language": "javascript", "code": "function generatePatterns(patterns, offset, orthogonal) {\n\n\tconst result = new Vector2();\n\n\tlet i, l;\n\tlet x, y;\n\tlet c;\n\n\tlet pattern;\n\tlet data, size;\n\n\tfor(i = 0, l = patterns.length; i < l; ++i) {\n\n\t\tpattern = patterns[i];\n\n\t\tdata = pattern.data;\n\t\tsize = pattern.width;\n\n\t\tfor(y = 0; y < size; ++y) {\n\n\t\t\tfor(x = 0; x < size; ++x) {\n\n\t\t\t\tif(orthogonal) {\n\n\t\t\t\t\tcalculateOrthogonalAreaForPattern(i, x, y, offset, result);\n\n\t\t\t\t} else {\n\n\t\t\t\t\tcalculateDiagonalAreaForPattern(i, x, y, offset, result);\n\n\t\t\t\t}\n\n\t\t\t\tc = (y * size + x) * 2;\n\n\t\t\t\tdata[c] = result.x * 255;\n\t\t\t\tdata[c + 1] = result.y * 255;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}", "code_tokens": ["function", "generatePatterns", "(", "patterns", ",", "offset", ",", "orthogonal", ")", "{", "const", "result", "=", "new", "Vector2", "(", ")", ";", "let", "i", ",", "l", ";", "let", "x", ",", "y", ";", "let", "c", ";", "let", "pattern", ";", "let", "data", ",", "size", ";", "for", "(", "i", "=", "0", ",", "l", "=", "patterns", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "{", "pattern", "=", "patterns", "[", "i", "]", ";", "data", "=", "pattern", ".", "data", ";", "size", "=", "pattern", ".", "width", ";", "for", "(", "y", "=", "0", ";", "y", "<", "size", ";", "++", "y", ")", "{", "for", "(", "x", "=", "0", ";", "x", "<", "size", ";", "++", "x", ")", "{", "if", "(", "orthogonal", ")", "{", "calculateOrthogonalAreaForPattern", "(", "i", ",", "x", ",", "y", ",", "offset", ",", "result", ")", ";", "}", "else", "{", "calculateDiagonalAreaForPattern", "(", "i", ",", "x", ",", "y", ",", "offset", ",", "result", ")", ";", "}", "c", "=", "(", "y", "*", "size", "+", "x", ")", "*", "2", ";", "data", "[", "c", "]", "=", "result", ".", "x", "*", "255", ";", "data", "[", "c", "+", "1", "]", "=", "result", ".", "y", "*", "255", ";", "}", "}", "}", "}"], "docstring": "Calculates orthogonal or diagonal patterns for a given offset.\n\n@param {RawImageData[]} patterns - The patterns to assemble.\n@param {Number|Float32Array} offset - A pattern offset. Diagonal offsets are pairs.\n@param {Boolean} orthogonal - Whether the patterns are orthogonal or diagonal.", "docstring_tokens": ["Calculates", "orthogonal", "or", "diagonal", "patterns", "for", "a", "given", "offset", "."], "sha": "43a6776c2a391ddd3539262e078b0f35b5563004", "url": "https://github.com/vanruesc/postprocessing/blob/43a6776c2a391ddd3539262e078b0f35b5563004/build/postprocessing.esm.js#L9088-L9131", "partition": "test"} {"repo": "vanruesc/postprocessing", "path": "build/postprocessing.esm.js", "func_name": "assemble", "original_string": "function assemble(base, patterns, edges, size, orthogonal, target) {\n\n\tconst p = new Vector2();\n\n\tconst dstData = target.data;\n\tconst dstWidth = target.width;\n\n\tlet i, l;\n\tlet x, y;\n\tlet c, d;\n\n\tlet edge;\n\tlet pattern;\n\tlet srcData, srcWidth;\n\n\tfor(i = 0, l = patterns.length; i < l; ++i) {\n\n\t\tedge = edges[i];\n\t\tpattern = patterns[i];\n\n\t\tsrcData = pattern.data;\n\t\tsrcWidth = pattern.width;\n\n\t\tfor(y = 0; y < size; ++y) {\n\n\t\t\tfor(x = 0; x < size; ++x) {\n\n\t\t\t\tp.fromArray(edge).multiplyScalar(size);\n\t\t\t\tp.add(base);\n\t\t\t\tp.x += x;\n\t\t\t\tp.y += y;\n\n\t\t\t\tc = (p.y * dstWidth + p.x) * 2;\n\n\t\t\t\t/* The texture coordinates of orthogonal patterns are compressed\n\t\t\t\tquadratically to reach longer distances for a given texture size. */\n\t\t\t\td = orthogonal ? ((y * y * srcWidth + x * x) * 2) :\n\t\t\t\t\t((y * srcWidth + x) * 2);\n\n\t\t\t\tdstData[c] = srcData[d];\n\t\t\t\tdstData[c + 1] = srcData[d + 1];\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}", "language": "javascript", "code": "function assemble(base, patterns, edges, size, orthogonal, target) {\n\n\tconst p = new Vector2();\n\n\tconst dstData = target.data;\n\tconst dstWidth = target.width;\n\n\tlet i, l;\n\tlet x, y;\n\tlet c, d;\n\n\tlet edge;\n\tlet pattern;\n\tlet srcData, srcWidth;\n\n\tfor(i = 0, l = patterns.length; i < l; ++i) {\n\n\t\tedge = edges[i];\n\t\tpattern = patterns[i];\n\n\t\tsrcData = pattern.data;\n\t\tsrcWidth = pattern.width;\n\n\t\tfor(y = 0; y < size; ++y) {\n\n\t\t\tfor(x = 0; x < size; ++x) {\n\n\t\t\t\tp.fromArray(edge).multiplyScalar(size);\n\t\t\t\tp.add(base);\n\t\t\t\tp.x += x;\n\t\t\t\tp.y += y;\n\n\t\t\t\tc = (p.y * dstWidth + p.x) * 2;\n\n\t\t\t\t/* The texture coordinates of orthogonal patterns are compressed\n\t\t\t\tquadratically to reach longer distances for a given texture size. */\n\t\t\t\td = orthogonal ? ((y * y * srcWidth + x * x) * 2) :\n\t\t\t\t\t((y * srcWidth + x) * 2);\n\n\t\t\t\tdstData[c] = srcData[d];\n\t\t\t\tdstData[c + 1] = srcData[d + 1];\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}", "code_tokens": ["function", "assemble", "(", "base", ",", "patterns", ",", "edges", ",", "size", ",", "orthogonal", ",", "target", ")", "{", "const", "p", "=", "new", "Vector2", "(", ")", ";", "const", "dstData", "=", "target", ".", "data", ";", "const", "dstWidth", "=", "target", ".", "width", ";", "let", "i", ",", "l", ";", "let", "x", ",", "y", ";", "let", "c", ",", "d", ";", "let", "edge", ";", "let", "pattern", ";", "let", "srcData", ",", "srcWidth", ";", "for", "(", "i", "=", "0", ",", "l", "=", "patterns", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "{", "edge", "=", "edges", "[", "i", "]", ";", "pattern", "=", "patterns", "[", "i", "]", ";", "srcData", "=", "pattern", ".", "data", ";", "srcWidth", "=", "pattern", ".", "width", ";", "for", "(", "y", "=", "0", ";", "y", "<", "size", ";", "++", "y", ")", "{", "for", "(", "x", "=", "0", ";", "x", "<", "size", ";", "++", "x", ")", "{", "p", ".", "fromArray", "(", "edge", ")", ".", "multiplyScalar", "(", "size", ")", ";", "p", ".", "add", "(", "base", ")", ";", "p", ".", "x", "+=", "x", ";", "p", ".", "y", "+=", "y", ";", "c", "=", "(", "p", ".", "y", "*", "dstWidth", "+", "p", ".", "x", ")", "*", "2", ";", "d", "=", "orthogonal", "?", "(", "(", "y", "*", "y", "*", "srcWidth", "+", "x", "*", "x", ")", "*", "2", ")", ":", "(", "(", "y", "*", "srcWidth", "+", "x", ")", "*", "2", ")", ";", "dstData", "[", "c", "]", "=", "srcData", "[", "d", "]", ";", "dstData", "[", "c", "+", "1", "]", "=", "srcData", "[", "d", "+", "1", "]", ";", "}", "}", "}", "}"], "docstring": "Assembles orthogonal or diagonal patterns into the final area image.\n\n@param {Vector2} base - A base position.\n@param {RawImageData[]} patterns - The patterns to assemble.\n@param {Uint8Array[]} edges - Edge coordinate pairs, used for positioning.\n@param {Number} size - The pattern size.\n@param {Boolean} orthogonal - Whether the patterns are orthogonal or diagonal.\n@param {RawImageData} target - The target image data.", "docstring_tokens": ["Assembles", "orthogonal", "or", "diagonal", "patterns", "into", "the", "final", "area", "image", "."], "sha": "43a6776c2a391ddd3539262e078b0f35b5563004", "url": "https://github.com/vanruesc/postprocessing/blob/43a6776c2a391ddd3539262e078b0f35b5563004/build/postprocessing.esm.js#L9144-L9192", "partition": "test"} {"repo": "vanruesc/postprocessing", "path": "build/postprocessing.esm.js", "func_name": "deltaRight", "original_string": "function deltaRight(left, top) {\n\n\tlet d = 0;\n\n\t// If there is an edge, and no crossing edges, continue.\n\tif(top[3] === 1 && left[1] !== 1 && left[3] !== 1) {\n\n\t\td += 1;\n\n\t}\n\n\t/* If an edge was previously found, there is another edge and there are no\n\tcrossing edges, continue. */\n\tif(d === 1 && top[2] === 1 && left[0] !== 1 && left[2] !== 1) {\n\n\t\td += 1;\n\n\t}\n\n\treturn d;\n\n}", "language": "javascript", "code": "function deltaRight(left, top) {\n\n\tlet d = 0;\n\n\t// If there is an edge, and no crossing edges, continue.\n\tif(top[3] === 1 && left[1] !== 1 && left[3] !== 1) {\n\n\t\td += 1;\n\n\t}\n\n\t/* If an edge was previously found, there is another edge and there are no\n\tcrossing edges, continue. */\n\tif(d === 1 && top[2] === 1 && left[0] !== 1 && left[2] !== 1) {\n\n\t\td += 1;\n\n\t}\n\n\treturn d;\n\n}", "code_tokens": ["function", "deltaRight", "(", "left", ",", "top", ")", "{", "let", "d", "=", "0", ";", "if", "(", "top", "[", "3", "]", "===", "1", "&&", "left", "[", "1", "]", "!==", "1", "&&", "left", "[", "3", "]", "!==", "1", ")", "{", "d", "+=", "1", ";", "}", "if", "(", "d", "===", "1", "&&", "top", "[", "2", "]", "===", "1", "&&", "left", "[", "0", "]", "!==", "1", "&&", "left", "[", "2", "]", "!==", "1", ")", "{", "d", "+=", "1", ";", "}", "return", "d", ";", "}"], "docstring": "Computes the delta distance to add in the last step of searches to the right.\n\n@private\n@param {Number[]} left - The left edge combination.\n@param {Number[]} top - The top edge combination.\n@return {Number} The right delta distance.", "docstring_tokens": ["Computes", "the", "delta", "distance", "to", "add", "in", "the", "last", "step", "of", "searches", "to", "the", "right", "."], "sha": "43a6776c2a391ddd3539262e078b0f35b5563004", "url": "https://github.com/vanruesc/postprocessing/blob/43a6776c2a391ddd3539262e078b0f35b5563004/build/postprocessing.esm.js#L9380-L9401", "partition": "test"} {"repo": "vanruesc/postprocessing", "path": "src/images/smaa/utils/SMAASearchImageData.js", "func_name": "bilinear", "original_string": "function bilinear(e) {\n\n\tconst a = lerp(e[0], e[1], 1.0 - 0.25);\n\tconst b = lerp(e[2], e[3], 1.0 - 0.25);\n\n\treturn lerp(a, b, 1.0 - 0.125);\n\n}", "language": "javascript", "code": "function bilinear(e) {\n\n\tconst a = lerp(e[0], e[1], 1.0 - 0.25);\n\tconst b = lerp(e[2], e[3], 1.0 - 0.25);\n\n\treturn lerp(a, b, 1.0 - 0.125);\n\n}", "code_tokens": ["function", "bilinear", "(", "e", ")", "{", "const", "a", "=", "lerp", "(", "e", "[", "0", "]", ",", "e", "[", "1", "]", ",", "1.0", "-", "0.25", ")", ";", "const", "b", "=", "lerp", "(", "e", "[", "2", "]", ",", "e", "[", "3", "]", ",", "1.0", "-", "0.25", ")", ";", "return", "lerp", "(", "a", ",", "b", ",", "1.0", "-", "0.125", ")", ";", "}"], "docstring": "Calculates the bilinear fetch for a certain edge combination.\n\ne[0] e[1]\n\nx <-------- Sample Position: (-0.25, -0.125)\ne[2] e[3] <--- Current Pixel [3]: (0.0, 0.0)\n\n@private\n@param {Number[]} e - The edge combination.\n@return {Number} The interpolated value.", "docstring_tokens": ["Calculates", "the", "bilinear", "fetch", "for", "a", "certain", "edge", "combination", "."], "sha": "43a6776c2a391ddd3539262e078b0f35b5563004", "url": "https://github.com/vanruesc/postprocessing/blob/43a6776c2a391ddd3539262e078b0f35b5563004/src/images/smaa/utils/SMAASearchImageData.js#L64-L71", "partition": "test"} {"repo": "italia/bootstrap-italia", "path": "src/js/plugins/timepicker.js", "func_name": "checkForm", "original_string": "function checkForm(that) {\n var newValue = $(that).val()\n var matches = newValue != '' ? newValue.match(timeRegEx) : ''\n var error = $(that)\n .closest('.time-spinner')\n .find('.error_container')\n var $closerTimeSpinner = $(that)\n .closest('.time-spinner')\n .find('.spinner-control')\n\n if (matches) {\n $(error).html('')\n //$closerTimeSpinner.find('.spinner-hour input').val(timeRegEx.split(':')[0]);\n //$closerTimeSpinner.find('.spinner-min input').val(timeRegEx.split(':')[1]);\n return true\n } else {\n var errMsg = 'Formato data non valido'\n $(error).html(errMsg)\n //$(that).val('Formato data non valido')\n return false\n }\n }", "language": "javascript", "code": "function checkForm(that) {\n var newValue = $(that).val()\n var matches = newValue != '' ? newValue.match(timeRegEx) : ''\n var error = $(that)\n .closest('.time-spinner')\n .find('.error_container')\n var $closerTimeSpinner = $(that)\n .closest('.time-spinner')\n .find('.spinner-control')\n\n if (matches) {\n $(error).html('')\n //$closerTimeSpinner.find('.spinner-hour input').val(timeRegEx.split(':')[0]);\n //$closerTimeSpinner.find('.spinner-min input').val(timeRegEx.split(':')[1]);\n return true\n } else {\n var errMsg = 'Formato data non valido'\n $(error).html(errMsg)\n //$(that).val('Formato data non valido')\n return false\n }\n }", "code_tokens": ["function", "checkForm", "(", "that", ")", "{", "var", "newValue", "=", "$", "(", "that", ")", ".", "val", "(", ")", "var", "matches", "=", "newValue", "!=", "''", "?", "newValue", ".", "match", "(", "timeRegEx", ")", ":", "''", "var", "error", "=", "$", "(", "that", ")", ".", "closest", "(", "'.time-spinner'", ")", ".", "find", "(", "'.error_container'", ")", "var", "$closerTimeSpinner", "=", "$", "(", "that", ")", ".", "closest", "(", "'.time-spinner'", ")", ".", "find", "(", "'.spinner-control'", ")", "if", "(", "matches", ")", "{", "$", "(", "error", ")", ".", "html", "(", "''", ")", "return", "true", "}", "else", "{", "var", "errMsg", "=", "'Formato data non valido'", "$", "(", "error", ")", ".", "html", "(", "errMsg", ")", "return", "false", "}", "}"], "docstring": "TIME VALIDATION FOR DATA ENTRY", "docstring_tokens": ["TIME", "VALIDATION", "FOR", "DATA", "ENTRY"], "sha": "9d2177a1c0c731f83636d2164bd22702ef5767c2", "url": "https://github.com/italia/bootstrap-italia/blob/9d2177a1c0c731f83636d2164bd22702ef5767c2/src/js/plugins/timepicker.js#L221-L242", "partition": "test"} {"repo": "italia/bootstrap-italia", "path": "src/js/plugins/transfer-back.js", "func_name": "resetToMove", "original_string": "function resetToMove(contextControl) {\n var left = contextControl.find('.source .transfer-group')\n var right = contextControl.find('.target .transfer-group')\n var textLeft = contextControl.find('.source .transfer-header span.num')\n var textRight = contextControl.find('.target .transfer-header span.num')\n var header = contextControl.find('.transfer-header input')\n\n $(left).html(elemLeft)\n $(right).html(elemRight)\n\n $(textLeft).text(elemLeftNum)\n $(textRight).text(elemRightNum)\n\n $(header).prop('disabled', false)\n }", "language": "javascript", "code": "function resetToMove(contextControl) {\n var left = contextControl.find('.source .transfer-group')\n var right = contextControl.find('.target .transfer-group')\n var textLeft = contextControl.find('.source .transfer-header span.num')\n var textRight = contextControl.find('.target .transfer-header span.num')\n var header = contextControl.find('.transfer-header input')\n\n $(left).html(elemLeft)\n $(right).html(elemRight)\n\n $(textLeft).text(elemLeftNum)\n $(textRight).text(elemRightNum)\n\n $(header).prop('disabled', false)\n }", "code_tokens": ["function", "resetToMove", "(", "contextControl", ")", "{", "var", "left", "=", "contextControl", ".", "find", "(", "'.source .transfer-group'", ")", "var", "right", "=", "contextControl", ".", "find", "(", "'.target .transfer-group'", ")", "var", "textLeft", "=", "contextControl", ".", "find", "(", "'.source .transfer-header span.num'", ")", "var", "textRight", "=", "contextControl", ".", "find", "(", "'.target .transfer-header span.num'", ")", "var", "header", "=", "contextControl", ".", "find", "(", "'.transfer-header input'", ")", "$", "(", "left", ")", ".", "html", "(", "elemLeft", ")", "$", "(", "right", ")", ".", "html", "(", "elemRight", ")", "$", "(", "textLeft", ")", ".", "text", "(", "elemLeftNum", ")", "$", "(", "textRight", ")", ".", "text", "(", "elemRightNum", ")", "$", "(", "header", ")", ".", "prop", "(", "'disabled'", ",", "false", ")", "}"], "docstring": "ripristino stato iniziale", "docstring_tokens": ["ripristino", "stato", "iniziale"], "sha": "9d2177a1c0c731f83636d2164bd22702ef5767c2", "url": "https://github.com/italia/bootstrap-italia/blob/9d2177a1c0c731f83636d2164bd22702ef5767c2/src/js/plugins/transfer-back.js#L24-L38", "partition": "test"} {"repo": "italia/bootstrap-italia", "path": "src/js/plugins/transfer-back.js", "func_name": "checkIfActive", "original_string": "function checkIfActive(\n targetControl,\n targetHeaderControl,\n containerTypeControl,\n addButtonControl\n ) {\n $(targetControl).each(function(el) {\n if ($(this).prop('checked')) {\n if (!$(targetHeaderControl).hasClass('semi-checked')) {\n $(targetHeaderControl).addClass('semi-checked')\n $(targetHeaderControl).prop('checked', false)\n if (containerTypeControl.hasClass('source')) {\n $(addButtonControl).addClass('active')\n }\n if (containerTypeControl.hasClass('target')) {\n $(inverseButton).addClass('active')\n }\n }\n return false\n } else {\n $(targetHeaderControl).removeClass('semi-checked')\n if (containerTypeControl.hasClass('source')) {\n $(addButtonControl).removeClass('active')\n }\n if (containerTypeControl.hasClass('target')) {\n $(inverseButton).removeClass('active')\n }\n }\n })\n }", "language": "javascript", "code": "function checkIfActive(\n targetControl,\n targetHeaderControl,\n containerTypeControl,\n addButtonControl\n ) {\n $(targetControl).each(function(el) {\n if ($(this).prop('checked')) {\n if (!$(targetHeaderControl).hasClass('semi-checked')) {\n $(targetHeaderControl).addClass('semi-checked')\n $(targetHeaderControl).prop('checked', false)\n if (containerTypeControl.hasClass('source')) {\n $(addButtonControl).addClass('active')\n }\n if (containerTypeControl.hasClass('target')) {\n $(inverseButton).addClass('active')\n }\n }\n return false\n } else {\n $(targetHeaderControl).removeClass('semi-checked')\n if (containerTypeControl.hasClass('source')) {\n $(addButtonControl).removeClass('active')\n }\n if (containerTypeControl.hasClass('target')) {\n $(inverseButton).removeClass('active')\n }\n }\n })\n }", "code_tokens": ["function", "checkIfActive", "(", "targetControl", ",", "targetHeaderControl", ",", "containerTypeControl", ",", "addButtonControl", ")", "{", "$", "(", "targetControl", ")", ".", "each", "(", "function", "(", "el", ")", "{", "if", "(", "$", "(", "this", ")", ".", "prop", "(", "'checked'", ")", ")", "{", "if", "(", "!", "$", "(", "targetHeaderControl", ")", ".", "hasClass", "(", "'semi-checked'", ")", ")", "{", "$", "(", "targetHeaderControl", ")", ".", "addClass", "(", "'semi-checked'", ")", "$", "(", "targetHeaderControl", ")", ".", "prop", "(", "'checked'", ",", "false", ")", "if", "(", "containerTypeControl", ".", "hasClass", "(", "'source'", ")", ")", "{", "$", "(", "addButtonControl", ")", ".", "addClass", "(", "'active'", ")", "}", "if", "(", "containerTypeControl", ".", "hasClass", "(", "'target'", ")", ")", "{", "$", "(", "inverseButton", ")", ".", "addClass", "(", "'active'", ")", "}", "}", "return", "false", "}", "else", "{", "$", "(", "targetHeaderControl", ")", ".", "removeClass", "(", "'semi-checked'", ")", "if", "(", "containerTypeControl", ".", "hasClass", "(", "'source'", ")", ")", "{", "$", "(", "addButtonControl", ")", ".", "removeClass", "(", "'active'", ")", "}", "if", "(", "containerTypeControl", ".", "hasClass", "(", "'target'", ")", ")", "{", "$", "(", "inverseButton", ")", ".", "removeClass", "(", "'active'", ")", "}", "}", "}", ")", "}"], "docstring": "control active check & header check", "docstring_tokens": ["control", "active", "check", "&", "header", "check"], "sha": "9d2177a1c0c731f83636d2164bd22702ef5767c2", "url": "https://github.com/italia/bootstrap-italia/blob/9d2177a1c0c731f83636d2164bd22702ef5767c2/src/js/plugins/transfer-back.js#L41-L70", "partition": "test"} {"repo": "italia/bootstrap-italia", "path": "src/js/plugins/transfer-back.js", "func_name": "sourceControl", "original_string": "function sourceControl(contextControl) {\n var tocheck = contextControl.find('.transfer-scroll').find('input')\n var checknum = tocheck.length\n var targetText = contextControl\n .find('.transfer-header')\n .find('label span.num')\n var header = contextControl.find('.transfer-header input')\n\n $(header)\n .prop('checked', false)\n .removeClass('semi-checked')\n\n if (checknum < 1) {\n $(header).prop('disabled', true)\n } else {\n $(header).prop('disabled', false)\n }\n\n $(targetText).text(checknum)\n }", "language": "javascript", "code": "function sourceControl(contextControl) {\n var tocheck = contextControl.find('.transfer-scroll').find('input')\n var checknum = tocheck.length\n var targetText = contextControl\n .find('.transfer-header')\n .find('label span.num')\n var header = contextControl.find('.transfer-header input')\n\n $(header)\n .prop('checked', false)\n .removeClass('semi-checked')\n\n if (checknum < 1) {\n $(header).prop('disabled', true)\n } else {\n $(header).prop('disabled', false)\n }\n\n $(targetText).text(checknum)\n }", "code_tokens": ["function", "sourceControl", "(", "contextControl", ")", "{", "var", "tocheck", "=", "contextControl", ".", "find", "(", "'.transfer-scroll'", ")", ".", "find", "(", "'input'", ")", "var", "checknum", "=", "tocheck", ".", "length", "var", "targetText", "=", "contextControl", ".", "find", "(", "'.transfer-header'", ")", ".", "find", "(", "'label span.num'", ")", "var", "header", "=", "contextControl", ".", "find", "(", "'.transfer-header input'", ")", "$", "(", "header", ")", ".", "prop", "(", "'checked'", ",", "false", ")", ".", "removeClass", "(", "'semi-checked'", ")", "if", "(", "checknum", "<", "1", ")", "{", "$", "(", "header", ")", ".", "prop", "(", "'disabled'", ",", "true", ")", "}", "else", "{", "$", "(", "header", ")", ".", "prop", "(", "'disabled'", ",", "false", ")", "}", "$", "(", "targetText", ")", ".", "text", "(", "checknum", ")", "}"], "docstring": "controllo elementi source", "docstring_tokens": ["controllo", "elementi", "source"], "sha": "9d2177a1c0c731f83636d2164bd22702ef5767c2", "url": "https://github.com/italia/bootstrap-italia/blob/9d2177a1c0c731f83636d2164bd22702ef5767c2/src/js/plugins/transfer-back.js#L144-L163", "partition": "test"} {"repo": "italia/bootstrap-italia", "path": "src/js/plugins/transfer-back.js", "func_name": "targetControl", "original_string": "function targetControl(targetControl) {\n var tocheck = targetControl.find('input')\n var checknum = tocheck.length\n var targetText = tocheck\n .closest('.it-transfer-wrapper')\n .find('.transfer-header')\n .find('label span.num')\n var header = $(targetControl).find('.transfer-header input')\n\n if (checknum < 1) {\n $(header).prop('disabled', true)\n } else {\n $(header).prop('disabled', false)\n }\n\n $(targetText).text(checknum)\n }", "language": "javascript", "code": "function targetControl(targetControl) {\n var tocheck = targetControl.find('input')\n var checknum = tocheck.length\n var targetText = tocheck\n .closest('.it-transfer-wrapper')\n .find('.transfer-header')\n .find('label span.num')\n var header = $(targetControl).find('.transfer-header input')\n\n if (checknum < 1) {\n $(header).prop('disabled', true)\n } else {\n $(header).prop('disabled', false)\n }\n\n $(targetText).text(checknum)\n }", "code_tokens": ["function", "targetControl", "(", "targetControl", ")", "{", "var", "tocheck", "=", "targetControl", ".", "find", "(", "'input'", ")", "var", "checknum", "=", "tocheck", ".", "length", "var", "targetText", "=", "tocheck", ".", "closest", "(", "'.it-transfer-wrapper'", ")", ".", "find", "(", "'.transfer-header'", ")", ".", "find", "(", "'label span.num'", ")", "var", "header", "=", "$", "(", "targetControl", ")", ".", "find", "(", "'.transfer-header input'", ")", "if", "(", "checknum", "<", "1", ")", "{", "$", "(", "header", ")", ".", "prop", "(", "'disabled'", ",", "true", ")", "}", "else", "{", "$", "(", "header", ")", ".", "prop", "(", "'disabled'", ",", "false", ")", "}", "$", "(", "targetText", ")", ".", "text", "(", "checknum", ")", "}"], "docstring": "controllo elementi target", "docstring_tokens": ["controllo", "elementi", "target"], "sha": "9d2177a1c0c731f83636d2164bd22702ef5767c2", "url": "https://github.com/italia/bootstrap-italia/blob/9d2177a1c0c731f83636d2164bd22702ef5767c2/src/js/plugins/transfer-back.js#L166-L182", "partition": "test"} {"repo": "italia/bootstrap-italia", "path": "src/js/plugins/transfer-back.js", "func_name": "checkToMove", "original_string": "function checkToMove(contextControl, targetControl) {\n var elements = contextControl.find('.transfer-group').find('input:checked')\n var sourceTag = $(elements).closest('.form-check')\n\n $(elements).each(function() {\n $(this).prop('checked', false)\n $(sourceTag)\n .detach()\n .appendTo(targetControl)\n .addClass('added')\n })\n }", "language": "javascript", "code": "function checkToMove(contextControl, targetControl) {\n var elements = contextControl.find('.transfer-group').find('input:checked')\n var sourceTag = $(elements).closest('.form-check')\n\n $(elements).each(function() {\n $(this).prop('checked', false)\n $(sourceTag)\n .detach()\n .appendTo(targetControl)\n .addClass('added')\n })\n }", "code_tokens": ["function", "checkToMove", "(", "contextControl", ",", "targetControl", ")", "{", "var", "elements", "=", "contextControl", ".", "find", "(", "'.transfer-group'", ")", ".", "find", "(", "'input:checked'", ")", "var", "sourceTag", "=", "$", "(", "elements", ")", ".", "closest", "(", "'.form-check'", ")", "$", "(", "elements", ")", ".", "each", "(", "function", "(", ")", "{", "$", "(", "this", ")", ".", "prop", "(", "'checked'", ",", "false", ")", "$", "(", "sourceTag", ")", ".", "detach", "(", ")", ".", "appendTo", "(", "targetControl", ")", ".", "addClass", "(", "'added'", ")", "}", ")", "}"], "docstring": "elementi da aggiungere", "docstring_tokens": ["elementi", "da", "aggiungere"], "sha": "9d2177a1c0c731f83636d2164bd22702ef5767c2", "url": "https://github.com/italia/bootstrap-italia/blob/9d2177a1c0c731f83636d2164bd22702ef5767c2/src/js/plugins/transfer-back.js#L185-L196", "partition": "test"} {"repo": "italia/bootstrap-italia", "path": "src/js/plugins/i-sticky/i-sticky.js", "func_name": "updateScrollPos", "original_string": "function updateScrollPos() {\n if (!stickies.length) {\n return\n }\n\n lastKnownScrollTop =\n document.documentElement.scrollTop || document.body.scrollTop\n\n // Only trigger a layout change if we\u2019re not already waiting for one\n if (!isAnimationRequested) {\n isAnimationRequested = true\n\n // Don\u2019t update until next animation frame if we can, otherwise use a\n // timeout - either will help avoid too many repaints\n if (requestAnimationFrame) {\n requestAnimationFrame(setPositions)\n } else {\n if (timeout) {\n clearTimeout(timeout)\n }\n\n timeout = setTimeout(setPositions, 15)\n }\n }\n }", "language": "javascript", "code": "function updateScrollPos() {\n if (!stickies.length) {\n return\n }\n\n lastKnownScrollTop =\n document.documentElement.scrollTop || document.body.scrollTop\n\n // Only trigger a layout change if we\u2019re not already waiting for one\n if (!isAnimationRequested) {\n isAnimationRequested = true\n\n // Don\u2019t update until next animation frame if we can, otherwise use a\n // timeout - either will help avoid too many repaints\n if (requestAnimationFrame) {\n requestAnimationFrame(setPositions)\n } else {\n if (timeout) {\n clearTimeout(timeout)\n }\n\n timeout = setTimeout(setPositions, 15)\n }\n }\n }", "code_tokens": ["function", "updateScrollPos", "(", ")", "{", "if", "(", "!", "stickies", ".", "length", ")", "{", "return", "}", "lastKnownScrollTop", "=", "document", ".", "documentElement", ".", "scrollTop", "||", "document", ".", "body", ".", "scrollTop", "if", "(", "!", "isAnimationRequested", ")", "{", "isAnimationRequested", "=", "true", "if", "(", "requestAnimationFrame", ")", "{", "requestAnimationFrame", "(", "setPositions", ")", "}", "else", "{", "if", "(", "timeout", ")", "{", "clearTimeout", "(", "timeout", ")", "}", "timeout", "=", "setTimeout", "(", "setPositions", ",", "15", ")", "}", "}", "}"], "docstring": "Debounced scroll handling", "docstring_tokens": ["Debounced", "scroll", "handling"], "sha": "9d2177a1c0c731f83636d2164bd22702ef5767c2", "url": "https://github.com/italia/bootstrap-italia/blob/9d2177a1c0c731f83636d2164bd22702ef5767c2/src/js/plugins/i-sticky/i-sticky.js#L319-L343", "partition": "test"} {"repo": "italia/bootstrap-italia", "path": "src/js/plugins/password-strength-meter/password-strength-meter.js", "func_name": "scoreText", "original_string": "function scoreText(score) {\n if (score === -1) {\n return options.shortPass\n }\n\n score = score < 0 ? 0 : score\n\n if (score < 26) {\n return options.shortPass\n }\n if (score < 51) {\n return options.badPass\n }\n if (score < 76) {\n return options.goodPass\n }\n\n return options.strongPass\n }", "language": "javascript", "code": "function scoreText(score) {\n if (score === -1) {\n return options.shortPass\n }\n\n score = score < 0 ? 0 : score\n\n if (score < 26) {\n return options.shortPass\n }\n if (score < 51) {\n return options.badPass\n }\n if (score < 76) {\n return options.goodPass\n }\n\n return options.strongPass\n }", "code_tokens": ["function", "scoreText", "(", "score", ")", "{", "if", "(", "score", "===", "-", "1", ")", "{", "return", "options", ".", "shortPass", "}", "score", "=", "score", "<", "0", "?", "0", ":", "score", "if", "(", "score", "<", "26", ")", "{", "return", "options", ".", "shortPass", "}", "if", "(", "score", "<", "51", ")", "{", "return", "options", ".", "badPass", "}", "if", "(", "score", "<", "76", ")", "{", "return", "options", ".", "goodPass", "}", "return", "options", ".", "strongPass", "}"], "docstring": "Returns strings based on the score given.\n\n@param int score Score base.\n@return string", "docstring_tokens": ["Returns", "strings", "based", "on", "the", "score", "given", "."], "sha": "9d2177a1c0c731f83636d2164bd22702ef5767c2", "url": "https://github.com/italia/bootstrap-italia/blob/9d2177a1c0c731f83636d2164bd22702ef5767c2/src/js/plugins/password-strength-meter/password-strength-meter.js#L27-L45", "partition": "test"} {"repo": "italia/bootstrap-italia", "path": "src/js/plugins/password-strength-meter/password-strength-meter.js", "func_name": "calculateScore", "original_string": "function calculateScore(password) {\n var score = 0\n\n // password < options.minimumLength\n if (password.length < options.minimumLength) {\n return -1\n }\n\n // password length\n score += password.length * 4\n score += checkRepetition(1, password).length - password.length\n score += checkRepetition(2, password).length - password.length\n score += checkRepetition(3, password).length - password.length\n score += checkRepetition(4, password).length - password.length\n\n // password has 3 numbers\n if (password.match(/(.*[0-9].*[0-9].*[0-9])/)) {\n score += 5\n }\n\n // password has at least 2 sybols\n var symbols = '.*[!,@,#,$,%,^,&,*,?,_,~]'\n symbols = new RegExp('(' + symbols + symbols + ')')\n if (password.match(symbols)) {\n score += 5\n }\n\n // password has Upper and Lower chars\n if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {\n score += 10\n }\n\n // password has number and chars\n if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) {\n score += 15\n }\n\n // password has number and symbol\n if (\n password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) &&\n password.match(/([0-9])/)\n ) {\n score += 15\n }\n\n // password has char and symbol\n if (\n password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) &&\n password.match(/([a-zA-Z])/)\n ) {\n score += 15\n }\n\n // password is just numbers or chars\n if (password.match(/^\\w+$/) || password.match(/^\\d+$/)) {\n score -= 10\n }\n\n if (score > 100) {\n score = 100\n }\n\n if (score < 0) {\n score = 0\n }\n\n return score\n }", "language": "javascript", "code": "function calculateScore(password) {\n var score = 0\n\n // password < options.minimumLength\n if (password.length < options.minimumLength) {\n return -1\n }\n\n // password length\n score += password.length * 4\n score += checkRepetition(1, password).length - password.length\n score += checkRepetition(2, password).length - password.length\n score += checkRepetition(3, password).length - password.length\n score += checkRepetition(4, password).length - password.length\n\n // password has 3 numbers\n if (password.match(/(.*[0-9].*[0-9].*[0-9])/)) {\n score += 5\n }\n\n // password has at least 2 sybols\n var symbols = '.*[!,@,#,$,%,^,&,*,?,_,~]'\n symbols = new RegExp('(' + symbols + symbols + ')')\n if (password.match(symbols)) {\n score += 5\n }\n\n // password has Upper and Lower chars\n if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {\n score += 10\n }\n\n // password has number and chars\n if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) {\n score += 15\n }\n\n // password has number and symbol\n if (\n password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) &&\n password.match(/([0-9])/)\n ) {\n score += 15\n }\n\n // password has char and symbol\n if (\n password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) &&\n password.match(/([a-zA-Z])/)\n ) {\n score += 15\n }\n\n // password is just numbers or chars\n if (password.match(/^\\w+$/) || password.match(/^\\d+$/)) {\n score -= 10\n }\n\n if (score > 100) {\n score = 100\n }\n\n if (score < 0) {\n score = 0\n }\n\n return score\n }", "code_tokens": ["function", "calculateScore", "(", "password", ")", "{", "var", "score", "=", "0", "if", "(", "password", ".", "length", "<", "options", ".", "minimumLength", ")", "{", "return", "-", "1", "}", "score", "+=", "password", ".", "length", "*", "4", "score", "+=", "checkRepetition", "(", "1", ",", "password", ")", ".", "length", "-", "password", ".", "length", "score", "+=", "checkRepetition", "(", "2", ",", "password", ")", ".", "length", "-", "password", ".", "length", "score", "+=", "checkRepetition", "(", "3", ",", "password", ")", ".", "length", "-", "password", ".", "length", "score", "+=", "checkRepetition", "(", "4", ",", "password", ")", ".", "length", "-", "password", ".", "length", "if", "(", "password", ".", "match", "(", "/", "(.*[0-9].*[0-9].*[0-9])", "/", ")", ")", "{", "score", "+=", "5", "}", "var", "symbols", "=", "'.*[!,@,#,$,%,^,&,*,?,_,~]'", "symbols", "=", "new", "RegExp", "(", "'('", "+", "symbols", "+", "symbols", "+", "')'", ")", "if", "(", "password", ".", "match", "(", "symbols", ")", ")", "{", "score", "+=", "5", "}", "if", "(", "password", ".", "match", "(", "/", "([a-z].*[A-Z])|([A-Z].*[a-z])", "/", ")", ")", "{", "score", "+=", "10", "}", "if", "(", "password", ".", "match", "(", "/", "([a-zA-Z])", "/", ")", "&&", "password", ".", "match", "(", "/", "([0-9])", "/", ")", ")", "{", "score", "+=", "15", "}", "if", "(", "password", ".", "match", "(", "/", "([!,@,#,$,%,^,&,*,?,_,~])", "/", ")", "&&", "password", ".", "match", "(", "/", "([0-9])", "/", ")", ")", "{", "score", "+=", "15", "}", "if", "(", "password", ".", "match", "(", "/", "([!,@,#,$,%,^,&,*,?,_,~])", "/", ")", "&&", "password", ".", "match", "(", "/", "([a-zA-Z])", "/", ")", ")", "{", "score", "+=", "15", "}", "if", "(", "password", ".", "match", "(", "/", "^\\w+$", "/", ")", "||", "password", ".", "match", "(", "/", "^\\d+$", "/", ")", ")", "{", "score", "-=", "10", "}", "if", "(", "score", ">", "100", ")", "{", "score", "=", "100", "}", "if", "(", "score", "<", "0", ")", "{", "score", "=", "0", "}", "return", "score", "}"], "docstring": "Returns a value between -1 and 100 to score\nthe user's password.\n\n@param string password The password to be checked.\n@return int", "docstring_tokens": ["Returns", "a", "value", "between", "-", "1", "and", "100", "to", "score", "the", "user", "s", "password", "."], "sha": "9d2177a1c0c731f83636d2164bd22702ef5767c2", "url": "https://github.com/italia/bootstrap-italia/blob/9d2177a1c0c731f83636d2164bd22702ef5767c2/src/js/plugins/password-strength-meter/password-strength-meter.js#L77-L144", "partition": "test"} {"repo": "italia/bootstrap-italia", "path": "src/js/plugins/password-strength-meter/password-strength-meter.js", "func_name": "checkRepetition", "original_string": "function checkRepetition(rLen, str) {\n var res = '',\n repeated = false\n for (var i = 0; i < str.length; i++) {\n repeated = true\n for (var j = 0; j < rLen && j + i + rLen < str.length; j++) {\n repeated = repeated && str.charAt(j + i) === str.charAt(j + i + rLen)\n }\n if (j < rLen) {\n repeated = false\n }\n if (repeated) {\n i += rLen - 1\n repeated = false\n } else {\n res += str.charAt(i)\n }\n }\n return res\n }", "language": "javascript", "code": "function checkRepetition(rLen, str) {\n var res = '',\n repeated = false\n for (var i = 0; i < str.length; i++) {\n repeated = true\n for (var j = 0; j < rLen && j + i + rLen < str.length; j++) {\n repeated = repeated && str.charAt(j + i) === str.charAt(j + i + rLen)\n }\n if (j < rLen) {\n repeated = false\n }\n if (repeated) {\n i += rLen - 1\n repeated = false\n } else {\n res += str.charAt(i)\n }\n }\n return res\n }", "code_tokens": ["function", "checkRepetition", "(", "rLen", ",", "str", ")", "{", "var", "res", "=", "''", ",", "repeated", "=", "false", "for", "(", "var", "i", "=", "0", ";", "i", "<", "str", ".", "length", ";", "i", "++", ")", "{", "repeated", "=", "true", "for", "(", "var", "j", "=", "0", ";", "j", "<", "rLen", "&&", "j", "+", "i", "+", "rLen", "<", "str", ".", "length", ";", "j", "++", ")", "{", "repeated", "=", "repeated", "&&", "str", ".", "charAt", "(", "j", "+", "i", ")", "===", "str", ".", "charAt", "(", "j", "+", "i", "+", "rLen", ")", "}", "if", "(", "j", "<", "rLen", ")", "{", "repeated", "=", "false", "}", "if", "(", "repeated", ")", "{", "i", "+=", "rLen", "-", "1", "repeated", "=", "false", "}", "else", "{", "res", "+=", "str", ".", "charAt", "(", "i", ")", "}", "}", "return", "res", "}"], "docstring": "Checks for repetition of characters in\na string\n\n@param int rLen Repetition length.\n@param string str The string to be checked.\n@return string", "docstring_tokens": ["Checks", "for", "repetition", "of", "characters", "in", "a", "string"], "sha": "9d2177a1c0c731f83636d2164bd22702ef5767c2", "url": "https://github.com/italia/bootstrap-italia/blob/9d2177a1c0c731f83636d2164bd22702ef5767c2/src/js/plugins/password-strength-meter/password-strength-meter.js#L154-L173", "partition": "test"} {"repo": "italia/bootstrap-italia", "path": "src/js/plugins/password-strength-meter/password-strength-meter.js", "func_name": "init", "original_string": "function init() {\n var shown = true\n var $text = options.showText\n\n var $graybar = $('
    ').addClass(\n 'password-meter progress rounded-0 position-absolute'\n )\n $graybar.append(`
    \n
    \n
    \n
    \n
    \n
    `)\n var $colorbar = $('
    ').attr({\n class: 'progress-bar',\n role: 'progressbar',\n 'aria-valuenow': '0',\n 'aria-valuemin': '0',\n 'aria-valuemax': '100',\n })\n var $insert = $('
    ').append($graybar.append($colorbar))\n\n if (options.showText) {\n $text = $('')\n .addClass('form-text text-muted')\n .html(options.enterPass)\n $insert.prepend($text)\n }\n\n $object.after($insert)\n\n $object.keyup(function() {\n var score = calculateScore($object.val())\n $object.trigger('password.score', [score])\n var perc = score < 0 ? 0 : score\n $colorbar.removeClass(function(index, className) {\n return (className.match(/(^|\\s)bg-\\S+/g) || []).join(' ')\n })\n $colorbar.addClass('bg-' + scoreColor(score))\n $colorbar.css({\n width: perc + '%',\n })\n $colorbar.attr('aria-valuenow', perc)\n\n if (options.showText) {\n var text = scoreText(score)\n if (!$object.val().length && score <= 0) {\n text = options.enterPass\n }\n\n if (\n $text.html() !==\n $('
    ')\n .html(text)\n .html()\n ) {\n $text.html(text)\n $text.removeClass(function(index, className) {\n return (className.match(/(^|\\s)text-\\S+/g) || []).join(' ')\n })\n $text.addClass('text-' + scoreColor(score))\n $object.trigger('password.text', [text, score])\n }\n }\n })\n\n return this\n }", "language": "javascript", "code": "function init() {\n var shown = true\n var $text = options.showText\n\n var $graybar = $('
    ').addClass(\n 'password-meter progress rounded-0 position-absolute'\n )\n $graybar.append(`
    \n
    \n
    \n
    \n
    \n
    `)\n var $colorbar = $('
    ').attr({\n class: 'progress-bar',\n role: 'progressbar',\n 'aria-valuenow': '0',\n 'aria-valuemin': '0',\n 'aria-valuemax': '100',\n })\n var $insert = $('
    ').append($graybar.append($colorbar))\n\n if (options.showText) {\n $text = $('')\n .addClass('form-text text-muted')\n .html(options.enterPass)\n $insert.prepend($text)\n }\n\n $object.after($insert)\n\n $object.keyup(function() {\n var score = calculateScore($object.val())\n $object.trigger('password.score', [score])\n var perc = score < 0 ? 0 : score\n $colorbar.removeClass(function(index, className) {\n return (className.match(/(^|\\s)bg-\\S+/g) || []).join(' ')\n })\n $colorbar.addClass('bg-' + scoreColor(score))\n $colorbar.css({\n width: perc + '%',\n })\n $colorbar.attr('aria-valuenow', perc)\n\n if (options.showText) {\n var text = scoreText(score)\n if (!$object.val().length && score <= 0) {\n text = options.enterPass\n }\n\n if (\n $text.html() !==\n $('
    ')\n .html(text)\n .html()\n ) {\n $text.html(text)\n $text.removeClass(function(index, className) {\n return (className.match(/(^|\\s)text-\\S+/g) || []).join(' ')\n })\n $text.addClass('text-' + scoreColor(score))\n $object.trigger('password.text', [text, score])\n }\n }\n })\n\n return this\n }", "code_tokens": ["function", "init", "(", ")", "{", "var", "shown", "=", "true", "var", "$text", "=", "options", ".", "showText", "var", "$graybar", "=", "$", "(", "'
    '", ")", ".", "addClass", "(", "'password-meter progress rounded-0 position-absolute'", ")", "$graybar", ".", "append", "(", "`", "`", ")", "var", "$colorbar", "=", "$", "(", "'
    '", ")", ".", "attr", "(", "{", "class", ":", "'progress-bar'", ",", "role", ":", "'progressbar'", ",", "'aria-valuenow'", ":", "'0'", ",", "'aria-valuemin'", ":", "'0'", ",", "'aria-valuemax'", ":", "'100'", ",", "}", ")", "var", "$insert", "=", "$", "(", "'
    '", ")", ".", "append", "(", "$graybar", ".", "append", "(", "$colorbar", ")", ")", "if", "(", "options", ".", "showText", ")", "{", "$text", "=", "$", "(", "''", ")", ".", "addClass", "(", "'form-text text-muted'", ")", ".", "html", "(", "options", ".", "enterPass", ")", "$insert", ".", "prepend", "(", "$text", ")", "}", "$object", ".", "after", "(", "$insert", ")", "$object", ".", "keyup", "(", "function", "(", ")", "{", "var", "score", "=", "calculateScore", "(", "$object", ".", "val", "(", ")", ")", "$object", ".", "trigger", "(", "'password.score'", ",", "[", "score", "]", ")", "var", "perc", "=", "score", "<", "0", "?", "0", ":", "score", "$colorbar", ".", "removeClass", "(", "function", "(", "index", ",", "className", ")", "{", "return", "(", "className", ".", "match", "(", "/", "(^|\\s)bg-\\S+", "/", "g", ")", "||", "[", "]", ")", ".", "join", "(", "' '", ")", "}", ")", "$colorbar", ".", "addClass", "(", "'bg-'", "+", "scoreColor", "(", "score", ")", ")", "$colorbar", ".", "css", "(", "{", "width", ":", "perc", "+", "'%'", ",", "}", ")", "$colorbar", ".", "attr", "(", "'aria-valuenow'", ",", "perc", ")", "if", "(", "options", ".", "showText", ")", "{", "var", "text", "=", "scoreText", "(", "score", ")", "if", "(", "!", "$object", ".", "val", "(", ")", ".", "length", "&&", "score", "<=", "0", ")", "{", "text", "=", "options", ".", "enterPass", "}", "if", "(", "$text", ".", "html", "(", ")", "!==", "$", "(", "'
    '", ")", ".", "html", "(", "text", ")", ".", "html", "(", ")", ")", "{", "$text", ".", "html", "(", "text", ")", "$text", ".", "removeClass", "(", "function", "(", "index", ",", "className", ")", "{", "return", "(", "className", ".", "match", "(", "/", "(^|\\s)text-\\S+", "/", "g", ")", "||", "[", "]", ")", ".", "join", "(", "' '", ")", "}", ")", "$text", ".", "addClass", "(", "'text-'", "+", "scoreColor", "(", "score", ")", ")", "$object", ".", "trigger", "(", "'password.text'", ",", "[", "text", ",", "score", "]", ")", "}", "}", "}", ")", "return", "this", "}"], "docstring": "Initializes the plugin creating and binding the\nrequired layers and events.\n\n@return void", "docstring_tokens": ["Initializes", "the", "plugin", "creating", "and", "binding", "the", "required", "layers", "and", "events", "."], "sha": "9d2177a1c0c731f83636d2164bd22702ef5767c2", "url": "https://github.com/italia/bootstrap-italia/blob/9d2177a1c0c731f83636d2164bd22702ef5767c2/src/js/plugins/password-strength-meter/password-strength-meter.js#L181-L248", "partition": "test"} {"repo": "trufflesuite/ganache-core", "path": "lib/database/leveluparrayadapter.js", "func_name": "LevelUpArrayAdapter", "original_string": "function LevelUpArrayAdapter(name, db, serializer) {\n this.db = Sublevel(db);\n this.db = this.db.sublevel(name);\n this.name = name;\n this.serializer = serializer || {\n encode: function(val, callback) {\n callback(null, val);\n },\n decode: function(val, callback) {\n callback(null, val);\n }\n };\n}", "language": "javascript", "code": "function LevelUpArrayAdapter(name, db, serializer) {\n this.db = Sublevel(db);\n this.db = this.db.sublevel(name);\n this.name = name;\n this.serializer = serializer || {\n encode: function(val, callback) {\n callback(null, val);\n },\n decode: function(val, callback) {\n callback(null, val);\n }\n };\n}", "code_tokens": ["function", "LevelUpArrayAdapter", "(", "name", ",", "db", ",", "serializer", ")", "{", "this", ".", "db", "=", "Sublevel", "(", "db", ")", ";", "this", ".", "db", "=", "this", ".", "db", ".", "sublevel", "(", "name", ")", ";", "this", ".", "name", "=", "name", ";", "this", ".", "serializer", "=", "serializer", "||", "{", "encode", ":", "function", "(", "val", ",", "callback", ")", "{", "callback", "(", "null", ",", "val", ")", ";", "}", ",", "decode", ":", "function", "(", "val", ",", "callback", ")", "{", "callback", "(", "null", ",", "val", ")", ";", "}", "}", ";", "}"], "docstring": "Level up adapter that looks like an array. Doesn't support inserts.", "docstring_tokens": ["Level", "up", "adapter", "that", "looks", "like", "an", "array", ".", "Doesn", "t", "support", "inserts", "."], "sha": "cba166610008262266a60908d7ab4eb20fd856be", "url": "https://github.com/trufflesuite/ganache-core/blob/cba166610008262266a60908d7ab4eb20fd856be/lib/database/leveluparrayadapter.js#L6-L18", "partition": "test"} {"repo": "trufflesuite/ganache-core", "path": "lib/utils/transaction.js", "func_name": "fixProps", "original_string": "function fixProps(tx, data) {\n // ethereumjs-tx doesn't allow for a `0` value in fields, but we want it to\n // in order to differentiate between a value that isn't set and a value\n // that is set to 0 in a fake transaction.\n // Once https://github.com/ethereumjs/ethereumjs-tx/issues/112 is figured\n // out we can probably remove this fix/hack.\n // We keep track of the original value and return that value when\n // referenced by its property name. This lets us properly encode a `0` as\n // an empty buffer while still being able to differentiate between a `0`\n // and `null`/`undefined`.\n tx._originals = [];\n const fieldNames = [\"nonce\", \"gasPrice\", \"gasLimit\", \"value\"];\n fieldNames.forEach((fieldName) => configZeroableField(tx, fieldName, 32));\n\n // Ethereumjs-tx doesn't set the _chainId value whenever the v value is set,\n // which causes transaction signing to fail on transactions that include a\n // chain id in the v value (like ethers.js does).\n // Whenever the v value changes we need to make sure the chainId is also set.\n const vDescriptors = Object.getOwnPropertyDescriptor(tx, \"v\");\n // eslint-disable-next-line accessor-pairs\n Object.defineProperty(tx, \"v\", {\n set: (v) => {\n vDescriptors.set.call(tx, v);\n // calculate chainId from signature\n const sigV = ethUtil.bufferToInt(tx.v);\n let chainId = Math.floor((sigV - 35) / 2);\n if (chainId < 0) {\n chainId = 0;\n }\n tx._chainId = chainId || 0;\n }\n });\n\n if (tx.isFake()) {\n /**\n * @prop {Buffer} from (read/write) Set from address to bypass transaction\n * signing on fake transactions.\n */\n Object.defineProperty(tx, \"from\", {\n enumerable: true,\n configurable: true,\n get: tx.getSenderAddress.bind(tx),\n set: (val) => {\n if (val) {\n tx._from = ethUtil.toBuffer(val);\n } else {\n tx._from = null;\n }\n }\n });\n\n if (data && data.from) {\n tx.from = data.from;\n }\n\n tx.hash = fakeHash;\n }\n}", "language": "javascript", "code": "function fixProps(tx, data) {\n // ethereumjs-tx doesn't allow for a `0` value in fields, but we want it to\n // in order to differentiate between a value that isn't set and a value\n // that is set to 0 in a fake transaction.\n // Once https://github.com/ethereumjs/ethereumjs-tx/issues/112 is figured\n // out we can probably remove this fix/hack.\n // We keep track of the original value and return that value when\n // referenced by its property name. This lets us properly encode a `0` as\n // an empty buffer while still being able to differentiate between a `0`\n // and `null`/`undefined`.\n tx._originals = [];\n const fieldNames = [\"nonce\", \"gasPrice\", \"gasLimit\", \"value\"];\n fieldNames.forEach((fieldName) => configZeroableField(tx, fieldName, 32));\n\n // Ethereumjs-tx doesn't set the _chainId value whenever the v value is set,\n // which causes transaction signing to fail on transactions that include a\n // chain id in the v value (like ethers.js does).\n // Whenever the v value changes we need to make sure the chainId is also set.\n const vDescriptors = Object.getOwnPropertyDescriptor(tx, \"v\");\n // eslint-disable-next-line accessor-pairs\n Object.defineProperty(tx, \"v\", {\n set: (v) => {\n vDescriptors.set.call(tx, v);\n // calculate chainId from signature\n const sigV = ethUtil.bufferToInt(tx.v);\n let chainId = Math.floor((sigV - 35) / 2);\n if (chainId < 0) {\n chainId = 0;\n }\n tx._chainId = chainId || 0;\n }\n });\n\n if (tx.isFake()) {\n /**\n * @prop {Buffer} from (read/write) Set from address to bypass transaction\n * signing on fake transactions.\n */\n Object.defineProperty(tx, \"from\", {\n enumerable: true,\n configurable: true,\n get: tx.getSenderAddress.bind(tx),\n set: (val) => {\n if (val) {\n tx._from = ethUtil.toBuffer(val);\n } else {\n tx._from = null;\n }\n }\n });\n\n if (data && data.from) {\n tx.from = data.from;\n }\n\n tx.hash = fakeHash;\n }\n}", "code_tokens": ["function", "fixProps", "(", "tx", ",", "data", ")", "{", "tx", ".", "_originals", "=", "[", "]", ";", "const", "fieldNames", "=", "[", "\"nonce\"", ",", "\"gasPrice\"", ",", "\"gasLimit\"", ",", "\"value\"", "]", ";", "fieldNames", ".", "forEach", "(", "(", "fieldName", ")", "=>", "configZeroableField", "(", "tx", ",", "fieldName", ",", "32", ")", ")", ";", "const", "vDescriptors", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "tx", ",", "\"v\"", ")", ";", "Object", ".", "defineProperty", "(", "tx", ",", "\"v\"", ",", "{", "set", ":", "(", "v", ")", "=>", "{", "vDescriptors", ".", "set", ".", "call", "(", "tx", ",", "v", ")", ";", "const", "sigV", "=", "ethUtil", ".", "bufferToInt", "(", "tx", ".", "v", ")", ";", "let", "chainId", "=", "Math", ".", "floor", "(", "(", "sigV", "-", "35", ")", "/", "2", ")", ";", "if", "(", "chainId", "<", "0", ")", "{", "chainId", "=", "0", ";", "}", "tx", ".", "_chainId", "=", "chainId", "||", "0", ";", "}", "}", ")", ";", "if", "(", "tx", ".", "isFake", "(", ")", ")", "{", "Object", ".", "defineProperty", "(", "tx", ",", "\"from\"", ",", "{", "enumerable", ":", "true", ",", "configurable", ":", "true", ",", "get", ":", "tx", ".", "getSenderAddress", ".", "bind", "(", "tx", ")", ",", "set", ":", "(", "val", ")", "=>", "{", "if", "(", "val", ")", "{", "tx", ".", "_from", "=", "ethUtil", ".", "toBuffer", "(", "val", ")", ";", "}", "else", "{", "tx", ".", "_from", "=", "null", ";", "}", "}", "}", ")", ";", "if", "(", "data", "&&", "data", ".", "from", ")", "{", "tx", ".", "from", "=", "data", ".", "from", ";", "}", "tx", ".", "hash", "=", "fakeHash", ";", "}", "}"], "docstring": "etheruemjs-tx's Transactions don't behave quite like we need them to, so\nwe're monkey-patching them to do what we want here.\n@param {Transaction} tx The Transaction to fix\n@param {Object} [data] The data object", "docstring_tokens": ["etheruemjs", "-", "tx", "s", "Transactions", "don", "t", "behave", "quite", "like", "we", "need", "them", "to", "so", "we", "re", "monkey", "-", "patching", "them", "to", "do", "what", "we", "want", "here", "."], "sha": "cba166610008262266a60908d7ab4eb20fd856be", "url": "https://github.com/trufflesuite/ganache-core/blob/cba166610008262266a60908d7ab4eb20fd856be/lib/utils/transaction.js#L44-L101", "partition": "test"} {"repo": "trufflesuite/ganache-core", "path": "lib/utils/transaction.js", "func_name": "initData", "original_string": "function initData(tx, data) {\n if (data) {\n if (typeof data === \"string\") {\n data = to.buffer(data);\n }\n if (Buffer.isBuffer(data)) {\n data = rlp.decode(data);\n }\n const self = tx;\n if (Array.isArray(data)) {\n if (data.length > tx._fields.length) {\n throw new Error(\"wrong number of fields in data\");\n }\n\n // make sure all the items are buffers\n data.forEach((d, i) => {\n self[self._fields[i]] = ethUtil.toBuffer(d);\n });\n } else if ((typeof data === \"undefined\" ? \"undefined\" : typeof data) === \"object\") {\n const keys = Object.keys(data);\n tx._fields.forEach(function(field) {\n if (keys.indexOf(field) !== -1) {\n self[field] = data[field];\n }\n if (field === \"gasLimit\") {\n if (keys.indexOf(\"gas\") !== -1) {\n self[\"gas\"] = data[\"gas\"];\n }\n } else if (field === \"data\") {\n if (keys.indexOf(\"input\") !== -1) {\n self[\"input\"] = data[\"input\"];\n }\n }\n });\n\n // Set chainId value from the data, if it's there and the data didn't\n // contain a `v` value with chainId in it already. If we do have a\n // data.chainId value let's set the interval v value to it.\n if (!tx._chainId && data && data.chainId != null) {\n tx.raw[self._fields.indexOf(\"v\")] = tx._chainId = data.chainId || 0;\n }\n } else {\n throw new Error(\"invalid data\");\n }\n }\n}", "language": "javascript", "code": "function initData(tx, data) {\n if (data) {\n if (typeof data === \"string\") {\n data = to.buffer(data);\n }\n if (Buffer.isBuffer(data)) {\n data = rlp.decode(data);\n }\n const self = tx;\n if (Array.isArray(data)) {\n if (data.length > tx._fields.length) {\n throw new Error(\"wrong number of fields in data\");\n }\n\n // make sure all the items are buffers\n data.forEach((d, i) => {\n self[self._fields[i]] = ethUtil.toBuffer(d);\n });\n } else if ((typeof data === \"undefined\" ? \"undefined\" : typeof data) === \"object\") {\n const keys = Object.keys(data);\n tx._fields.forEach(function(field) {\n if (keys.indexOf(field) !== -1) {\n self[field] = data[field];\n }\n if (field === \"gasLimit\") {\n if (keys.indexOf(\"gas\") !== -1) {\n self[\"gas\"] = data[\"gas\"];\n }\n } else if (field === \"data\") {\n if (keys.indexOf(\"input\") !== -1) {\n self[\"input\"] = data[\"input\"];\n }\n }\n });\n\n // Set chainId value from the data, if it's there and the data didn't\n // contain a `v` value with chainId in it already. If we do have a\n // data.chainId value let's set the interval v value to it.\n if (!tx._chainId && data && data.chainId != null) {\n tx.raw[self._fields.indexOf(\"v\")] = tx._chainId = data.chainId || 0;\n }\n } else {\n throw new Error(\"invalid data\");\n }\n }\n}", "code_tokens": ["function", "initData", "(", "tx", ",", "data", ")", "{", "if", "(", "data", ")", "{", "if", "(", "typeof", "data", "===", "\"string\"", ")", "{", "data", "=", "to", ".", "buffer", "(", "data", ")", ";", "}", "if", "(", "Buffer", ".", "isBuffer", "(", "data", ")", ")", "{", "data", "=", "rlp", ".", "decode", "(", "data", ")", ";", "}", "const", "self", "=", "tx", ";", "if", "(", "Array", ".", "isArray", "(", "data", ")", ")", "{", "if", "(", "data", ".", "length", ">", "tx", ".", "_fields", ".", "length", ")", "{", "throw", "new", "Error", "(", "\"wrong number of fields in data\"", ")", ";", "}", "data", ".", "forEach", "(", "(", "d", ",", "i", ")", "=>", "{", "self", "[", "self", ".", "_fields", "[", "i", "]", "]", "=", "ethUtil", ".", "toBuffer", "(", "d", ")", ";", "}", ")", ";", "}", "else", "if", "(", "(", "typeof", "data", "===", "\"undefined\"", "?", "\"undefined\"", ":", "typeof", "data", ")", "===", "\"object\"", ")", "{", "const", "keys", "=", "Object", ".", "keys", "(", "data", ")", ";", "tx", ".", "_fields", ".", "forEach", "(", "function", "(", "field", ")", "{", "if", "(", "keys", ".", "indexOf", "(", "field", ")", "!==", "-", "1", ")", "{", "self", "[", "field", "]", "=", "data", "[", "field", "]", ";", "}", "if", "(", "field", "===", "\"gasLimit\"", ")", "{", "if", "(", "keys", ".", "indexOf", "(", "\"gas\"", ")", "!==", "-", "1", ")", "{", "self", "[", "\"gas\"", "]", "=", "data", "[", "\"gas\"", "]", ";", "}", "}", "else", "if", "(", "field", "===", "\"data\"", ")", "{", "if", "(", "keys", ".", "indexOf", "(", "\"input\"", ")", "!==", "-", "1", ")", "{", "self", "[", "\"input\"", "]", "=", "data", "[", "\"input\"", "]", ";", "}", "}", "}", ")", ";", "if", "(", "!", "tx", ".", "_chainId", "&&", "data", "&&", "data", ".", "chainId", "!=", "null", ")", "{", "tx", ".", "raw", "[", "self", ".", "_fields", ".", "indexOf", "(", "\"v\"", ")", "]", "=", "tx", ".", "_chainId", "=", "data", ".", "chainId", "||", "0", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "\"invalid data\"", ")", ";", "}", "}", "}"], "docstring": "Parses the given data object and adds its properties to the given tx.\n@param {Transaction} tx\n@param {Object} [data]", "docstring_tokens": ["Parses", "the", "given", "data", "object", "and", "adds", "its", "properties", "to", "the", "given", "tx", "."], "sha": "cba166610008262266a60908d7ab4eb20fd856be", "url": "https://github.com/trufflesuite/ganache-core/blob/cba166610008262266a60908d7ab4eb20fd856be/lib/utils/transaction.js#L108-L153", "partition": "test"} {"repo": "trufflesuite/ganache-core", "path": "lib/utils/txrejectederror.js", "func_name": "TXRejectedError", "original_string": "function TXRejectedError(message) {\n // Why not just Error.apply(this, [message])? See\n // https://gist.github.com/justmoon/15511f92e5216fa2624b#anti-patterns\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.message = message;\n}", "language": "javascript", "code": "function TXRejectedError(message) {\n // Why not just Error.apply(this, [message])? See\n // https://gist.github.com/justmoon/15511f92e5216fa2624b#anti-patterns\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.message = message;\n}", "code_tokens": ["function", "TXRejectedError", "(", "message", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "message", "=", "message", ";", "}"], "docstring": "raised when the transaction is rejected prior to running it in the EVM.", "docstring_tokens": ["raised", "when", "the", "transaction", "is", "rejected", "prior", "to", "running", "it", "in", "the", "EVM", "."], "sha": "cba166610008262266a60908d7ab4eb20fd856be", "url": "https://github.com/trufflesuite/ganache-core/blob/cba166610008262266a60908d7ab4eb20fd856be/lib/utils/txrejectederror.js#L4-L10", "partition": "test"} {"repo": "trufflesuite/ganache-core", "path": "lib/subproviders/requestfunnel.js", "func_name": "RequestFunnel", "original_string": "function RequestFunnel() {\n // We use an object here for O(1) lookups (speed).\n this.methods = {\n eth_call: true,\n eth_getStorageAt: true,\n eth_sendTransaction: true,\n eth_sendRawTransaction: true,\n\n // Ensure block filter and filter changes are process one at a time\n // as well so filter requests that come in after a transaction get\n // processed once that transaction has finished processing.\n eth_newBlockFilter: true,\n eth_getFilterChanges: true,\n eth_getFilterLogs: true\n };\n this.queue = [];\n this.isWorking = false;\n}", "language": "javascript", "code": "function RequestFunnel() {\n // We use an object here for O(1) lookups (speed).\n this.methods = {\n eth_call: true,\n eth_getStorageAt: true,\n eth_sendTransaction: true,\n eth_sendRawTransaction: true,\n\n // Ensure block filter and filter changes are process one at a time\n // as well so filter requests that come in after a transaction get\n // processed once that transaction has finished processing.\n eth_newBlockFilter: true,\n eth_getFilterChanges: true,\n eth_getFilterLogs: true\n };\n this.queue = [];\n this.isWorking = false;\n}", "code_tokens": ["function", "RequestFunnel", "(", ")", "{", "this", ".", "methods", "=", "{", "eth_call", ":", "true", ",", "eth_getStorageAt", ":", "true", ",", "eth_sendTransaction", ":", "true", ",", "eth_sendRawTransaction", ":", "true", ",", "eth_newBlockFilter", ":", "true", ",", "eth_getFilterChanges", ":", "true", ",", "eth_getFilterLogs", ":", "true", "}", ";", "this", ".", "queue", "=", "[", "]", ";", "this", ".", "isWorking", "=", "false", ";", "}"], "docstring": "See if any payloads for the specified methods are marked as external. If they are external, and match the method list, process them one at a time.", "docstring_tokens": ["See", "if", "any", "payloads", "for", "the", "specified", "methods", "are", "marked", "as", "external", ".", "If", "they", "are", "external", "and", "match", "the", "method", "list", "process", "them", "one", "at", "a", "time", "."], "sha": "cba166610008262266a60908d7ab4eb20fd856be", "url": "https://github.com/trufflesuite/ganache-core/blob/cba166610008262266a60908d7ab4eb20fd856be/lib/subproviders/requestfunnel.js#L11-L28", "partition": "test"} {"repo": "leovo2708/ngx-treeview", "path": "gulpfile.js", "func_name": "compileSass", "original_string": "function compileSass(_path, ext, data, callback) {\n const compiledCss = sass.renderSync({\n data: data,\n outputStyle: 'expanded',\n importer: function (url, prev, done) {\n if (url.startsWith('~')) {\n const newUrl = path.join(__dirname, 'node_modules', url.substr(1));\n return { file: newUrl };\n } else {\n return { file: url };\n }\n }\n });\n callback(null, compiledCss.css);\n}", "language": "javascript", "code": "function compileSass(_path, ext, data, callback) {\n const compiledCss = sass.renderSync({\n data: data,\n outputStyle: 'expanded',\n importer: function (url, prev, done) {\n if (url.startsWith('~')) {\n const newUrl = path.join(__dirname, 'node_modules', url.substr(1));\n return { file: newUrl };\n } else {\n return { file: url };\n }\n }\n });\n callback(null, compiledCss.css);\n}", "code_tokens": ["function", "compileSass", "(", "_path", ",", "ext", ",", "data", ",", "callback", ")", "{", "const", "compiledCss", "=", "sass", ".", "renderSync", "(", "{", "data", ":", "data", ",", "outputStyle", ":", "'expanded'", ",", "importer", ":", "function", "(", "url", ",", "prev", ",", "done", ")", "{", "if", "(", "url", ".", "startsWith", "(", "'~'", ")", ")", "{", "const", "newUrl", "=", "path", ".", "join", "(", "__dirname", ",", "'node_modules'", ",", "url", ".", "substr", "(", "1", ")", ")", ";", "return", "{", "file", ":", "newUrl", "}", ";", "}", "else", "{", "return", "{", "file", ":", "url", "}", ";", "}", "}", "}", ")", ";", "callback", "(", "null", ",", "compiledCss", ".", "css", ")", ";", "}"], "docstring": "Compile SASS to CSS.\n@see https://github.com/ludohenin/gulp-inline-ng2-template\n@see https://github.com/sass/node-sass", "docstring_tokens": ["Compile", "SASS", "to", "CSS", "."], "sha": "5afa879d2304344ec58c9d588209713fe28a31eb", "url": "https://github.com/leovo2708/ngx-treeview/blob/5afa879d2304344ec58c9d588209713fe28a31eb/gulpfile.js#L35-L49", "partition": "test"} {"repo": "broccolijs/broccoli", "path": "lib/load_brocfile.js", "func_name": "requireBrocfile", "original_string": "function requireBrocfile(brocfilePath) {\n let brocfile;\n\n if (brocfilePath.match(/\\.ts$/)) {\n try {\n require.resolve('ts-node');\n } catch (e) {\n throw new Error(`Cannot find module 'ts-node', please install`);\n }\n\n try {\n require.resolve('typescript');\n } catch (e) {\n throw new Error(`Cannot find module 'typescript', please install`);\n }\n\n // Register ts-node typescript compiler\n require('ts-node').register(); // eslint-disable-line node/no-unpublished-require\n\n // Load brocfile via ts-node\n brocfile = require(brocfilePath);\n } else {\n // Load brocfile via esm shim\n brocfile = esmRequire(brocfilePath);\n }\n\n // ESM `export default X` is represented as module.exports = { default: X }\n if (brocfile !== null && typeof brocfile === 'object' && brocfile.hasOwnProperty('default')) {\n brocfile = brocfile.default;\n }\n\n return brocfile;\n}", "language": "javascript", "code": "function requireBrocfile(brocfilePath) {\n let brocfile;\n\n if (brocfilePath.match(/\\.ts$/)) {\n try {\n require.resolve('ts-node');\n } catch (e) {\n throw new Error(`Cannot find module 'ts-node', please install`);\n }\n\n try {\n require.resolve('typescript');\n } catch (e) {\n throw new Error(`Cannot find module 'typescript', please install`);\n }\n\n // Register ts-node typescript compiler\n require('ts-node').register(); // eslint-disable-line node/no-unpublished-require\n\n // Load brocfile via ts-node\n brocfile = require(brocfilePath);\n } else {\n // Load brocfile via esm shim\n brocfile = esmRequire(brocfilePath);\n }\n\n // ESM `export default X` is represented as module.exports = { default: X }\n if (brocfile !== null && typeof brocfile === 'object' && brocfile.hasOwnProperty('default')) {\n brocfile = brocfile.default;\n }\n\n return brocfile;\n}", "code_tokens": ["function", "requireBrocfile", "(", "brocfilePath", ")", "{", "let", "brocfile", ";", "if", "(", "brocfilePath", ".", "match", "(", "/", "\\.ts$", "/", ")", ")", "{", "try", "{", "require", ".", "resolve", "(", "'ts-node'", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "`", "`", ")", ";", "}", "try", "{", "require", ".", "resolve", "(", "'typescript'", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "`", "`", ")", ";", "}", "require", "(", "'ts-node'", ")", ".", "register", "(", ")", ";", "brocfile", "=", "require", "(", "brocfilePath", ")", ";", "}", "else", "{", "brocfile", "=", "esmRequire", "(", "brocfilePath", ")", ";", "}", "if", "(", "brocfile", "!==", "null", "&&", "typeof", "brocfile", "===", "'object'", "&&", "brocfile", ".", "hasOwnProperty", "(", "'default'", ")", ")", "{", "brocfile", "=", "brocfile", ".", "default", ";", "}", "return", "brocfile", ";", "}"], "docstring": "Require a brocfile via either ESM or TypeScript\n\n@param {String} brocfilePath The path to the brocfile\n@returns {*}", "docstring_tokens": ["Require", "a", "brocfile", "via", "either", "ESM", "or", "TypeScript"], "sha": "55152adc4f7de802dea5758415c9c45653ecd4c5", "url": "https://github.com/broccolijs/broccoli/blob/55152adc4f7de802dea5758415c9c45653ecd4c5/lib/load_brocfile.js#L13-L45", "partition": "test"} {"repo": "kach/nearley", "path": "examples/calculator/calculator.js", "func_name": "runmath", "original_string": "function runmath(s) {\n var ans;\n try {// We want to catch parse errors and die appropriately\n\n // Make a parser and feed the input\n ans = new nearley.Parser(grammar.ParserRules, grammar.ParserStart)\n .feed(s);\n \n // Check if there are any results\n if (ans.results.length) {\n return ans.results[0].toString();\n } else {\n // This means the input is incomplete.\n var out = \"Error: incomplete input, parse failed. :(\";\n return out;\n }\n } catch(e) {\n // Panic in style, by graphically pointing out the error location.\n var out = new Array(PROMPT.length + e.offset + 1).join(\"-\") + \"^ Error.\";\n // --------\n // ^ This comes from nearley!\n return out;\n }\n}", "language": "javascript", "code": "function runmath(s) {\n var ans;\n try {// We want to catch parse errors and die appropriately\n\n // Make a parser and feed the input\n ans = new nearley.Parser(grammar.ParserRules, grammar.ParserStart)\n .feed(s);\n \n // Check if there are any results\n if (ans.results.length) {\n return ans.results[0].toString();\n } else {\n // This means the input is incomplete.\n var out = \"Error: incomplete input, parse failed. :(\";\n return out;\n }\n } catch(e) {\n // Panic in style, by graphically pointing out the error location.\n var out = new Array(PROMPT.length + e.offset + 1).join(\"-\") + \"^ Error.\";\n // --------\n // ^ This comes from nearley!\n return out;\n }\n}", "code_tokens": ["function", "runmath", "(", "s", ")", "{", "var", "ans", ";", "try", "{", "ans", "=", "new", "nearley", ".", "Parser", "(", "grammar", ".", "ParserRules", ",", "grammar", ".", "ParserStart", ")", ".", "feed", "(", "s", ")", ";", "if", "(", "ans", ".", "results", ".", "length", ")", "{", "return", "ans", ".", "results", "[", "0", "]", ".", "toString", "(", ")", ";", "}", "else", "{", "var", "out", "=", "\"Error: incomplete input, parse failed. :(\"", ";", "return", "out", ";", "}", "}", "catch", "(", "e", ")", "{", "var", "out", "=", "new", "Array", "(", "PROMPT", ".", "length", "+", "e", ".", "offset", "+", "1", ")", ".", "join", "(", "\"-\"", ")", "+", "\"^ Error.\"", ";", "return", "out", ";", "}", "}"], "docstring": "This is where the action is.", "docstring_tokens": ["This", "is", "where", "the", "action", "is", "."], "sha": "8635662b1ab690ee947a0613f0717dc85f45eb47", "url": "https://github.com/kach/nearley/blob/8635662b1ab690ee947a0613f0717dc85f45eb47/examples/calculator/calculator.js#L7-L30", "partition": "test"} {"repo": "mapbox/pbf", "path": "index.js", "func_name": "", "original_string": "function(arr, isSigned) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readVarint(isSigned));\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readVarint(isSigned));\n return arr;\n }", "language": "javascript", "code": "function(arr, isSigned) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readVarint(isSigned));\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readVarint(isSigned));\n return arr;\n }", "code_tokens": ["function", "(", "arr", ",", "isSigned", ")", "{", "if", "(", "this", ".", "type", "!==", "Pbf", ".", "Bytes", ")", "return", "arr", ".", "push", "(", "this", ".", "readVarint", "(", "isSigned", ")", ")", ";", "var", "end", "=", "readPackedEnd", "(", "this", ")", ";", "arr", "=", "arr", "||", "[", "]", ";", "while", "(", "this", ".", "pos", "<", "end", ")", "arr", ".", "push", "(", "this", ".", "readVarint", "(", "isSigned", ")", ")", ";", "return", "arr", ";", "}"], "docstring": "verbose for performance reasons; doesn't affect gzipped size", "docstring_tokens": ["verbose", "for", "performance", "reasons", ";", "doesn", "t", "affect", "gzipped", "size"], "sha": "e26454842595c3eae1f5f8281bba508fbd85b718", "url": "https://github.com/mapbox/pbf/blob/e26454842595c3eae1f5f8281bba508fbd85b718/index.js#L130-L136", "partition": "test"} {"repo": "acarl005/join-monster", "path": "src/query-ast-to-sql-ast/index.js", "func_name": "handleUnionSelections", "original_string": "function handleUnionSelections(\n sqlASTNode,\n children,\n selections,\n gqlType,\n namespace,\n depth,\n options,\n context,\n internalOptions = {}\n) {\n for (let selection of selections) {\n // we need to figure out what kind of selection this is\n switch (selection.kind) {\n case 'Field':\n // has this field been requested once already? GraphQL does not protect against duplicates so we have to check for it\n const existingNode = children.find(child => child.fieldName === selection.name.value && child.type === 'table')\n let newNode = new SQLASTNode(sqlASTNode)\n if (existingNode) {\n newNode = existingNode\n } else {\n children.push(newNode)\n }\n if (internalOptions.defferedFrom) {\n newNode.defferedFrom = internalOptions.defferedFrom\n }\n populateASTNode.call(this, selection, gqlType, newNode, namespace, depth + 1, options, context)\n break\n // if its an inline fragment, it has some fields and we gotta recurse thru all them\n case 'InlineFragment':\n {\n const selectionNameOfType = selection.typeCondition.name.value\n // normally, we would scan for the extra join-monster data on the current gqlType.\n // but the gqlType is the Union. The data isn't there, its on each of the types that make up the union\n // lets find that type and handle the selections based on THAT type instead\n const deferredType = this.schema._typeMap[selectionNameOfType]\n const deferToObjectType = deferredType.constructor.name === 'GraphQLObjectType'\n const handler = deferToObjectType ? handleSelections : handleUnionSelections\n if (deferToObjectType) {\n const typedChildren = sqlASTNode.typedChildren\n children = typedChildren[deferredType.name] = typedChildren[deferredType.name] || []\n internalOptions.defferedFrom = gqlType\n }\n handler.call(\n this, sqlASTNode, children,\n selection.selectionSet.selections, deferredType, namespace,\n depth, options, context,\n internalOptions\n )\n }\n break\n // if its a named fragment, we need to grab the fragment definition by its name and recurse over those fields\n case 'FragmentSpread':\n {\n const fragmentName = selection.name.value\n const fragment = this.fragments[fragmentName]\n const fragmentNameOfType = fragment.typeCondition.name.value\n const deferredType = this.schema._typeMap[fragmentNameOfType]\n const deferToObjectType = deferredType.constructor.name === 'GraphQLObjectType'\n const handler = deferToObjectType ? handleSelections : handleUnionSelections\n if (deferToObjectType) {\n const typedChildren = sqlASTNode.typedChildren\n children = typedChildren[deferredType.name] = typedChildren[deferredType.name] || []\n internalOptions.defferedFrom = gqlType\n }\n handler.call(\n this, sqlASTNode, children,\n fragment.selectionSet.selections, deferredType, namespace,\n depth, options, context,\n internalOptions\n )\n }\n break\n /* istanbul ignore next */\n default:\n throw new Error('Unknown selection kind: ' + selection.kind)\n }\n }\n}", "language": "javascript", "code": "function handleUnionSelections(\n sqlASTNode,\n children,\n selections,\n gqlType,\n namespace,\n depth,\n options,\n context,\n internalOptions = {}\n) {\n for (let selection of selections) {\n // we need to figure out what kind of selection this is\n switch (selection.kind) {\n case 'Field':\n // has this field been requested once already? GraphQL does not protect against duplicates so we have to check for it\n const existingNode = children.find(child => child.fieldName === selection.name.value && child.type === 'table')\n let newNode = new SQLASTNode(sqlASTNode)\n if (existingNode) {\n newNode = existingNode\n } else {\n children.push(newNode)\n }\n if (internalOptions.defferedFrom) {\n newNode.defferedFrom = internalOptions.defferedFrom\n }\n populateASTNode.call(this, selection, gqlType, newNode, namespace, depth + 1, options, context)\n break\n // if its an inline fragment, it has some fields and we gotta recurse thru all them\n case 'InlineFragment':\n {\n const selectionNameOfType = selection.typeCondition.name.value\n // normally, we would scan for the extra join-monster data on the current gqlType.\n // but the gqlType is the Union. The data isn't there, its on each of the types that make up the union\n // lets find that type and handle the selections based on THAT type instead\n const deferredType = this.schema._typeMap[selectionNameOfType]\n const deferToObjectType = deferredType.constructor.name === 'GraphQLObjectType'\n const handler = deferToObjectType ? handleSelections : handleUnionSelections\n if (deferToObjectType) {\n const typedChildren = sqlASTNode.typedChildren\n children = typedChildren[deferredType.name] = typedChildren[deferredType.name] || []\n internalOptions.defferedFrom = gqlType\n }\n handler.call(\n this, sqlASTNode, children,\n selection.selectionSet.selections, deferredType, namespace,\n depth, options, context,\n internalOptions\n )\n }\n break\n // if its a named fragment, we need to grab the fragment definition by its name and recurse over those fields\n case 'FragmentSpread':\n {\n const fragmentName = selection.name.value\n const fragment = this.fragments[fragmentName]\n const fragmentNameOfType = fragment.typeCondition.name.value\n const deferredType = this.schema._typeMap[fragmentNameOfType]\n const deferToObjectType = deferredType.constructor.name === 'GraphQLObjectType'\n const handler = deferToObjectType ? handleSelections : handleUnionSelections\n if (deferToObjectType) {\n const typedChildren = sqlASTNode.typedChildren\n children = typedChildren[deferredType.name] = typedChildren[deferredType.name] || []\n internalOptions.defferedFrom = gqlType\n }\n handler.call(\n this, sqlASTNode, children,\n fragment.selectionSet.selections, deferredType, namespace,\n depth, options, context,\n internalOptions\n )\n }\n break\n /* istanbul ignore next */\n default:\n throw new Error('Unknown selection kind: ' + selection.kind)\n }\n }\n}", "code_tokens": ["function", "handleUnionSelections", "(", "sqlASTNode", ",", "children", ",", "selections", ",", "gqlType", ",", "namespace", ",", "depth", ",", "options", ",", "context", ",", "internalOptions", "=", "{", "}", ")", "{", "for", "(", "let", "selection", "of", "selections", ")", "{", "switch", "(", "selection", ".", "kind", ")", "{", "case", "'Field'", ":", "const", "existingNode", "=", "children", ".", "find", "(", "child", "=>", "child", ".", "fieldName", "===", "selection", ".", "name", ".", "value", "&&", "child", ".", "type", "===", "'table'", ")", "let", "newNode", "=", "new", "SQLASTNode", "(", "sqlASTNode", ")", "if", "(", "existingNode", ")", "{", "newNode", "=", "existingNode", "}", "else", "{", "children", ".", "push", "(", "newNode", ")", "}", "if", "(", "internalOptions", ".", "defferedFrom", ")", "{", "newNode", ".", "defferedFrom", "=", "internalOptions", ".", "defferedFrom", "}", "populateASTNode", ".", "call", "(", "this", ",", "selection", ",", "gqlType", ",", "newNode", ",", "namespace", ",", "depth", "+", "1", ",", "options", ",", "context", ")", "break", "case", "'InlineFragment'", ":", "{", "const", "selectionNameOfType", "=", "selection", ".", "typeCondition", ".", "name", ".", "value", "const", "deferredType", "=", "this", ".", "schema", ".", "_typeMap", "[", "selectionNameOfType", "]", "const", "deferToObjectType", "=", "deferredType", ".", "constructor", ".", "name", "===", "'GraphQLObjectType'", "const", "handler", "=", "deferToObjectType", "?", "handleSelections", ":", "handleUnionSelections", "if", "(", "deferToObjectType", ")", "{", "const", "typedChildren", "=", "sqlASTNode", ".", "typedChildren", "children", "=", "typedChildren", "[", "deferredType", ".", "name", "]", "=", "typedChildren", "[", "deferredType", ".", "name", "]", "||", "[", "]", "internalOptions", ".", "defferedFrom", "=", "gqlType", "}", "handler", ".", "call", "(", "this", ",", "sqlASTNode", ",", "children", ",", "selection", ".", "selectionSet", ".", "selections", ",", "deferredType", ",", "namespace", ",", "depth", ",", "options", ",", "context", ",", "internalOptions", ")", "}", "break", "case", "'FragmentSpread'", ":", "{", "const", "fragmentName", "=", "selection", ".", "name", ".", "value", "const", "fragment", "=", "this", ".", "fragments", "[", "fragmentName", "]", "const", "fragmentNameOfType", "=", "fragment", ".", "typeCondition", ".", "name", ".", "value", "const", "deferredType", "=", "this", ".", "schema", ".", "_typeMap", "[", "fragmentNameOfType", "]", "const", "deferToObjectType", "=", "deferredType", ".", "constructor", ".", "name", "===", "'GraphQLObjectType'", "const", "handler", "=", "deferToObjectType", "?", "handleSelections", ":", "handleUnionSelections", "if", "(", "deferToObjectType", ")", "{", "const", "typedChildren", "=", "sqlASTNode", ".", "typedChildren", "children", "=", "typedChildren", "[", "deferredType", ".", "name", "]", "=", "typedChildren", "[", "deferredType", ".", "name", "]", "||", "[", "]", "internalOptions", ".", "defferedFrom", "=", "gqlType", "}", "handler", ".", "call", "(", "this", ",", "sqlASTNode", ",", "children", ",", "fragment", ".", "selectionSet", ".", "selections", ",", "deferredType", ",", "namespace", ",", "depth", ",", "options", ",", "context", ",", "internalOptions", ")", "}", "break", "default", ":", "throw", "new", "Error", "(", "'Unknown selection kind: '", "+", "selection", ".", "kind", ")", "}", "}", "}"], "docstring": "we need to collect all fields from all the fragments requested in the union type and ask for them in SQL", "docstring_tokens": ["we", "need", "to", "collect", "all", "fields", "from", "all", "the", "fragments", "requested", "in", "the", "union", "type", "and", "ask", "for", "them", "in", "SQL"], "sha": "8db8b54aaefd2fd975d63e2ab3ec05922e25118c", "url": "https://github.com/acarl005/join-monster/blob/8db8b54aaefd2fd975d63e2ab3ec05922e25118c/src/query-ast-to-sql-ast/index.js#L328-L406", "partition": "test"} {"repo": "acarl005/join-monster", "path": "src/query-ast-to-sql-ast/index.js", "func_name": "handleSelections", "original_string": "function handleSelections(\n sqlASTNode,\n children,\n selections,\n gqlType,\n namespace,\n depth,\n options,\n context,\n internalOptions = {},\n) {\n for (let selection of selections) {\n // we need to figure out what kind of selection this is\n switch (selection.kind) {\n // if its another field, recurse through that\n case 'Field':\n // has this field been requested once already? GraphQL does not protect against duplicates so we have to check for it\n const existingNode = children.find(child => child.fieldName === selection.name.value && child.type === 'table')\n let newNode = new SQLASTNode(sqlASTNode)\n if (existingNode) {\n newNode = existingNode\n } else {\n children.push(newNode)\n }\n if (internalOptions.defferedFrom) {\n newNode.defferedFrom = internalOptions.defferedFrom\n }\n populateASTNode.call(this, selection, gqlType, newNode, namespace, depth + 1, options, context)\n break\n // if its an inline fragment, it has some fields and we gotta recurse thru all them\n case 'InlineFragment':\n {\n // check to make sure the type of this fragment (or one of the interfaces it implements) matches the type being queried\n const selectionNameOfType = selection.typeCondition.name.value\n const sameType = selectionNameOfType === gqlType.name\n const interfaceType = (gqlType._interfaces || []).map(iface => iface.name).includes(selectionNameOfType)\n if (sameType || interfaceType) {\n handleSelections.call(\n this, sqlASTNode, children,\n selection.selectionSet.selections, gqlType, namespace,\n depth, options, context,\n internalOptions\n )\n }\n }\n break\n // if its a named fragment, we need to grab the fragment definition by its name and recurse over those fields\n case 'FragmentSpread':\n {\n const fragmentName = selection.name.value\n const fragment = this.fragments[fragmentName]\n // make sure fragment type (or one of the interfaces it implements) matches the type being queried\n const fragmentNameOfType = fragment.typeCondition.name.value\n const sameType = fragmentNameOfType === gqlType.name\n const interfaceType = gqlType._interfaces.map(iface => iface.name).indexOf(fragmentNameOfType) >= 0\n if (sameType || interfaceType) {\n handleSelections.call(\n this, sqlASTNode, children,\n fragment.selectionSet.selections, gqlType, namespace,\n depth, options, context,\n internalOptions\n )\n }\n }\n break\n /* istanbul ignore next */\n default:\n throw new Error('Unknown selection kind: ' + selection.kind)\n }\n }\n}", "language": "javascript", "code": "function handleSelections(\n sqlASTNode,\n children,\n selections,\n gqlType,\n namespace,\n depth,\n options,\n context,\n internalOptions = {},\n) {\n for (let selection of selections) {\n // we need to figure out what kind of selection this is\n switch (selection.kind) {\n // if its another field, recurse through that\n case 'Field':\n // has this field been requested once already? GraphQL does not protect against duplicates so we have to check for it\n const existingNode = children.find(child => child.fieldName === selection.name.value && child.type === 'table')\n let newNode = new SQLASTNode(sqlASTNode)\n if (existingNode) {\n newNode = existingNode\n } else {\n children.push(newNode)\n }\n if (internalOptions.defferedFrom) {\n newNode.defferedFrom = internalOptions.defferedFrom\n }\n populateASTNode.call(this, selection, gqlType, newNode, namespace, depth + 1, options, context)\n break\n // if its an inline fragment, it has some fields and we gotta recurse thru all them\n case 'InlineFragment':\n {\n // check to make sure the type of this fragment (or one of the interfaces it implements) matches the type being queried\n const selectionNameOfType = selection.typeCondition.name.value\n const sameType = selectionNameOfType === gqlType.name\n const interfaceType = (gqlType._interfaces || []).map(iface => iface.name).includes(selectionNameOfType)\n if (sameType || interfaceType) {\n handleSelections.call(\n this, sqlASTNode, children,\n selection.selectionSet.selections, gqlType, namespace,\n depth, options, context,\n internalOptions\n )\n }\n }\n break\n // if its a named fragment, we need to grab the fragment definition by its name and recurse over those fields\n case 'FragmentSpread':\n {\n const fragmentName = selection.name.value\n const fragment = this.fragments[fragmentName]\n // make sure fragment type (or one of the interfaces it implements) matches the type being queried\n const fragmentNameOfType = fragment.typeCondition.name.value\n const sameType = fragmentNameOfType === gqlType.name\n const interfaceType = gqlType._interfaces.map(iface => iface.name).indexOf(fragmentNameOfType) >= 0\n if (sameType || interfaceType) {\n handleSelections.call(\n this, sqlASTNode, children,\n fragment.selectionSet.selections, gqlType, namespace,\n depth, options, context,\n internalOptions\n )\n }\n }\n break\n /* istanbul ignore next */\n default:\n throw new Error('Unknown selection kind: ' + selection.kind)\n }\n }\n}", "code_tokens": ["function", "handleSelections", "(", "sqlASTNode", ",", "children", ",", "selections", ",", "gqlType", ",", "namespace", ",", "depth", ",", "options", ",", "context", ",", "internalOptions", "=", "{", "}", ",", ")", "{", "for", "(", "let", "selection", "of", "selections", ")", "{", "switch", "(", "selection", ".", "kind", ")", "{", "case", "'Field'", ":", "const", "existingNode", "=", "children", ".", "find", "(", "child", "=>", "child", ".", "fieldName", "===", "selection", ".", "name", ".", "value", "&&", "child", ".", "type", "===", "'table'", ")", "let", "newNode", "=", "new", "SQLASTNode", "(", "sqlASTNode", ")", "if", "(", "existingNode", ")", "{", "newNode", "=", "existingNode", "}", "else", "{", "children", ".", "push", "(", "newNode", ")", "}", "if", "(", "internalOptions", ".", "defferedFrom", ")", "{", "newNode", ".", "defferedFrom", "=", "internalOptions", ".", "defferedFrom", "}", "populateASTNode", ".", "call", "(", "this", ",", "selection", ",", "gqlType", ",", "newNode", ",", "namespace", ",", "depth", "+", "1", ",", "options", ",", "context", ")", "break", "case", "'InlineFragment'", ":", "{", "const", "selectionNameOfType", "=", "selection", ".", "typeCondition", ".", "name", ".", "value", "const", "sameType", "=", "selectionNameOfType", "===", "gqlType", ".", "name", "const", "interfaceType", "=", "(", "gqlType", ".", "_interfaces", "||", "[", "]", ")", ".", "map", "(", "iface", "=>", "iface", ".", "name", ")", ".", "includes", "(", "selectionNameOfType", ")", "if", "(", "sameType", "||", "interfaceType", ")", "{", "handleSelections", ".", "call", "(", "this", ",", "sqlASTNode", ",", "children", ",", "selection", ".", "selectionSet", ".", "selections", ",", "gqlType", ",", "namespace", ",", "depth", ",", "options", ",", "context", ",", "internalOptions", ")", "}", "}", "break", "case", "'FragmentSpread'", ":", "{", "const", "fragmentName", "=", "selection", ".", "name", ".", "value", "const", "fragment", "=", "this", ".", "fragments", "[", "fragmentName", "]", "const", "fragmentNameOfType", "=", "fragment", ".", "typeCondition", ".", "name", ".", "value", "const", "sameType", "=", "fragmentNameOfType", "===", "gqlType", ".", "name", "const", "interfaceType", "=", "gqlType", ".", "_interfaces", ".", "map", "(", "iface", "=>", "iface", ".", "name", ")", ".", "indexOf", "(", "fragmentNameOfType", ")", ">=", "0", "if", "(", "sameType", "||", "interfaceType", ")", "{", "handleSelections", ".", "call", "(", "this", ",", "sqlASTNode", ",", "children", ",", "fragment", ".", "selectionSet", ".", "selections", ",", "gqlType", ",", "namespace", ",", "depth", ",", "options", ",", "context", ",", "internalOptions", ")", "}", "}", "break", "default", ":", "throw", "new", "Error", "(", "'Unknown selection kind: '", "+", "selection", ".", "kind", ")", "}", "}", "}"], "docstring": "the selections could be several types, recursively handle each type here", "docstring_tokens": ["the", "selections", "could", "be", "several", "types", "recursively", "handle", "each", "type", "here"], "sha": "8db8b54aaefd2fd975d63e2ab3ec05922e25118c", "url": "https://github.com/acarl005/join-monster/blob/8db8b54aaefd2fd975d63e2ab3ec05922e25118c/src/query-ast-to-sql-ast/index.js#L409-L479", "partition": "test"} {"repo": "acarl005/join-monster", "path": "src/query-ast-to-sql-ast/index.js", "func_name": "columnToASTChild", "original_string": "function columnToASTChild(columnName, namespace) {\n return {\n type: 'column',\n name: columnName,\n fieldName: columnName,\n as: namespace.generate('column', columnName)\n }\n}", "language": "javascript", "code": "function columnToASTChild(columnName, namespace) {\n return {\n type: 'column',\n name: columnName,\n fieldName: columnName,\n as: namespace.generate('column', columnName)\n }\n}", "code_tokens": ["function", "columnToASTChild", "(", "columnName", ",", "namespace", ")", "{", "return", "{", "type", ":", "'column'", ",", "name", ":", "columnName", ",", "fieldName", ":", "columnName", ",", "as", ":", "namespace", ".", "generate", "(", "'column'", ",", "columnName", ")", "}", "}"], "docstring": "tell the AST we need a column that perhaps the user didnt ask for, but may be necessary for join monster to ID objects or associate ones across batches", "docstring_tokens": ["tell", "the", "AST", "we", "need", "a", "column", "that", "perhaps", "the", "user", "didnt", "ask", "for", "but", "may", "be", "necessary", "for", "join", "monster", "to", "ID", "objects", "or", "associate", "ones", "across", "batches"], "sha": "8db8b54aaefd2fd975d63e2ab3ec05922e25118c", "url": "https://github.com/acarl005/join-monster/blob/8db8b54aaefd2fd975d63e2ab3ec05922e25118c/src/query-ast-to-sql-ast/index.js#L484-L491", "partition": "test"} {"repo": "acarl005/join-monster", "path": "src/query-ast-to-sql-ast/index.js", "func_name": "keyToASTChild", "original_string": "function keyToASTChild(key, namespace) {\n if (typeof key === 'string') {\n return columnToASTChild(key, namespace)\n }\n if (Array.isArray(key)) {\n const clumsyName = toClumsyName(key)\n return {\n type: 'composite',\n name: key,\n fieldName: clumsyName,\n as: namespace.generate('column', clumsyName)\n }\n }\n}", "language": "javascript", "code": "function keyToASTChild(key, namespace) {\n if (typeof key === 'string') {\n return columnToASTChild(key, namespace)\n }\n if (Array.isArray(key)) {\n const clumsyName = toClumsyName(key)\n return {\n type: 'composite',\n name: key,\n fieldName: clumsyName,\n as: namespace.generate('column', clumsyName)\n }\n }\n}", "code_tokens": ["function", "keyToASTChild", "(", "key", ",", "namespace", ")", "{", "if", "(", "typeof", "key", "===", "'string'", ")", "{", "return", "columnToASTChild", "(", "key", ",", "namespace", ")", "}", "if", "(", "Array", ".", "isArray", "(", "key", ")", ")", "{", "const", "clumsyName", "=", "toClumsyName", "(", "key", ")", "return", "{", "type", ":", "'composite'", ",", "name", ":", "key", ",", "fieldName", ":", "clumsyName", ",", "as", ":", "namespace", ".", "generate", "(", "'column'", ",", "clumsyName", ")", "}", "}", "}"], "docstring": "keys are necessary for deduplication during the hydration process this will handle singular or composite keys", "docstring_tokens": ["keys", "are", "necessary", "for", "deduplication", "during", "the", "hydration", "process", "this", "will", "handle", "singular", "or", "composite", "keys"], "sha": "8db8b54aaefd2fd975d63e2ab3ec05922e25118c", "url": "https://github.com/acarl005/join-monster/blob/8db8b54aaefd2fd975d63e2ab3ec05922e25118c/src/query-ast-to-sql-ast/index.js#L501-L514", "partition": "test"} {"repo": "acarl005/join-monster", "path": "src/query-ast-to-sql-ast/index.js", "func_name": "stripRelayConnection", "original_string": "function stripRelayConnection(gqlType, queryASTNode, fragments) {\n // get the GraphQL Type inside the list of edges inside the Node from the schema definition\n const edgeType = stripNonNullType(gqlType._fields.edges.type)\n const strippedType = stripNonNullType(stripNonNullType(edgeType.ofType)._fields.node.type)\n // let's remember those arguments on the connection\n const args = queryASTNode.arguments\n // and then find the fields being selected on the underlying type, also buried within edges and Node\n const edges = spreadFragments(queryASTNode.selectionSet.selections, fragments, gqlType.name)\n .find(selection => selection.name.value === 'edges')\n if (edges) {\n queryASTNode = spreadFragments(edges.selectionSet.selections, fragments, gqlType.name)\n .find(selection => selection.name.value === 'node') || {}\n } else {\n queryASTNode = {}\n }\n // place the arguments on this inner field, so our SQL AST picks it up later\n queryASTNode.arguments = args\n return { gqlType: strippedType, queryASTNode }\n}", "language": "javascript", "code": "function stripRelayConnection(gqlType, queryASTNode, fragments) {\n // get the GraphQL Type inside the list of edges inside the Node from the schema definition\n const edgeType = stripNonNullType(gqlType._fields.edges.type)\n const strippedType = stripNonNullType(stripNonNullType(edgeType.ofType)._fields.node.type)\n // let's remember those arguments on the connection\n const args = queryASTNode.arguments\n // and then find the fields being selected on the underlying type, also buried within edges and Node\n const edges = spreadFragments(queryASTNode.selectionSet.selections, fragments, gqlType.name)\n .find(selection => selection.name.value === 'edges')\n if (edges) {\n queryASTNode = spreadFragments(edges.selectionSet.selections, fragments, gqlType.name)\n .find(selection => selection.name.value === 'node') || {}\n } else {\n queryASTNode = {}\n }\n // place the arguments on this inner field, so our SQL AST picks it up later\n queryASTNode.arguments = args\n return { gqlType: strippedType, queryASTNode }\n}", "code_tokens": ["function", "stripRelayConnection", "(", "gqlType", ",", "queryASTNode", ",", "fragments", ")", "{", "const", "edgeType", "=", "stripNonNullType", "(", "gqlType", ".", "_fields", ".", "edges", ".", "type", ")", "const", "strippedType", "=", "stripNonNullType", "(", "stripNonNullType", "(", "edgeType", ".", "ofType", ")", ".", "_fields", ".", "node", ".", "type", ")", "const", "args", "=", "queryASTNode", ".", "arguments", "const", "edges", "=", "spreadFragments", "(", "queryASTNode", ".", "selectionSet", ".", "selections", ",", "fragments", ",", "gqlType", ".", "name", ")", ".", "find", "(", "selection", "=>", "selection", ".", "name", ".", "value", "===", "'edges'", ")", "if", "(", "edges", ")", "{", "queryASTNode", "=", "spreadFragments", "(", "edges", ".", "selectionSet", ".", "selections", ",", "fragments", ",", "gqlType", ".", "name", ")", ".", "find", "(", "selection", "=>", "selection", ".", "name", ".", "value", "===", "'node'", ")", "||", "{", "}", "}", "else", "{", "queryASTNode", "=", "{", "}", "}", "queryASTNode", ".", "arguments", "=", "args", "return", "{", "gqlType", ":", "strippedType", ",", "queryASTNode", "}", "}"], "docstring": "if its a connection type, we need to look up the Node type inside their to find the relevant SQL info", "docstring_tokens": ["if", "its", "a", "connection", "type", "we", "need", "to", "look", "up", "the", "Node", "type", "inside", "their", "to", "find", "the", "relevant", "SQL", "info"], "sha": "8db8b54aaefd2fd975d63e2ab3ec05922e25118c", "url": "https://github.com/acarl005/join-monster/blob/8db8b54aaefd2fd975d63e2ab3ec05922e25118c/src/query-ast-to-sql-ast/index.js#L541-L559", "partition": "test"} {"repo": "acarl005/join-monster", "path": "src/query-ast-to-sql-ast/index.js", "func_name": "spreadFragments", "original_string": "function spreadFragments(selections, fragments, typeName) {\n return flatMap(selections, selection => {\n switch (selection.kind) {\n case 'FragmentSpread':\n const fragmentName = selection.name.value\n const fragment = fragments[fragmentName]\n return spreadFragments(fragment.selectionSet.selections, fragments, typeName)\n case 'InlineFragment':\n if (selection.typeCondition.name.value === typeName) {\n return spreadFragments(selection.selectionSet.selections, fragments, typeName)\n }\n return []\n\n default:\n return selection\n }\n })\n}", "language": "javascript", "code": "function spreadFragments(selections, fragments, typeName) {\n return flatMap(selections, selection => {\n switch (selection.kind) {\n case 'FragmentSpread':\n const fragmentName = selection.name.value\n const fragment = fragments[fragmentName]\n return spreadFragments(fragment.selectionSet.selections, fragments, typeName)\n case 'InlineFragment':\n if (selection.typeCondition.name.value === typeName) {\n return spreadFragments(selection.selectionSet.selections, fragments, typeName)\n }\n return []\n\n default:\n return selection\n }\n })\n}", "code_tokens": ["function", "spreadFragments", "(", "selections", ",", "fragments", ",", "typeName", ")", "{", "return", "flatMap", "(", "selections", ",", "selection", "=>", "{", "switch", "(", "selection", ".", "kind", ")", "{", "case", "'FragmentSpread'", ":", "const", "fragmentName", "=", "selection", ".", "name", ".", "value", "const", "fragment", "=", "fragments", "[", "fragmentName", "]", "return", "spreadFragments", "(", "fragment", ".", "selectionSet", ".", "selections", ",", "fragments", ",", "typeName", ")", "case", "'InlineFragment'", ":", "if", "(", "selection", ".", "typeCondition", ".", "name", ".", "value", "===", "typeName", ")", "{", "return", "spreadFragments", "(", "selection", ".", "selectionSet", ".", "selections", ",", "fragments", ",", "typeName", ")", "}", "return", "[", "]", "default", ":", "return", "selection", "}", "}", ")", "}"], "docstring": "instead of fields, selections can be fragments, which is another group of selections fragments can be arbitrarily nested this function recurses through and gets the relevant fields", "docstring_tokens": ["instead", "of", "fields", "selections", "can", "be", "fragments", "which", "is", "another", "group", "of", "selections", "fragments", "can", "be", "arbitrarily", "nested", "this", "function", "recurses", "through", "and", "gets", "the", "relevant", "fields"], "sha": "8db8b54aaefd2fd975d63e2ab3ec05922e25118c", "url": "https://github.com/acarl005/join-monster/blob/8db8b54aaefd2fd975d63e2ab3ec05922e25118c/src/query-ast-to-sql-ast/index.js#L653-L670", "partition": "test"} {"repo": "acarl005/join-monster", "path": "src/index.js", "func_name": "getNode", "original_string": "async function getNode(typeName, resolveInfo, context, condition, dbCall, options = {}) {\n // get the GraphQL type from the schema using the name\n const type = resolveInfo.schema._typeMap[typeName]\n assert(type, `Type \"${typeName}\" not found in your schema.`)\n assert(type._typeConfig.sqlTable, `joinMonster can't fetch a ${typeName} as a Node unless it has \"sqlTable\" tagged.`)\n\n // we need to determine what the WHERE function should be\n let where = buildWhereFunction(type, condition, options)\n\n // our getGraphQLType expects every requested field to be in the schema definition. \"node\" isn't a parent of whatever type we're getting, so we'll just wrap that type in an object that LOOKS that same as a hypothetical Node type\n const fakeParentNode = {\n _fields: {\n node: {\n type,\n name: type.name.toLowerCase(),\n where\n }\n }\n }\n const namespace = new AliasNamespace(options.minify)\n const sqlAST = {}\n const fieldNodes = resolveInfo.fieldNodes || resolveInfo.fieldASTs\n // uses the same underlying function as the main `joinMonster`\n queryAST.populateASTNode.call(resolveInfo, fieldNodes[0], fakeParentNode, sqlAST, namespace, 0, options, context)\n queryAST.pruneDuplicateSqlDeps(sqlAST, namespace)\n const { sql, shapeDefinition } = await compileSqlAST(sqlAST, context, options)\n const data = arrToConnection(await handleUserDbCall(dbCall, sql, sqlAST, shapeDefinition), sqlAST)\n await nextBatch(sqlAST, data, dbCall, context, options)\n if (!data) return data\n data.__type__ = type\n return data\n}", "language": "javascript", "code": "async function getNode(typeName, resolveInfo, context, condition, dbCall, options = {}) {\n // get the GraphQL type from the schema using the name\n const type = resolveInfo.schema._typeMap[typeName]\n assert(type, `Type \"${typeName}\" not found in your schema.`)\n assert(type._typeConfig.sqlTable, `joinMonster can't fetch a ${typeName} as a Node unless it has \"sqlTable\" tagged.`)\n\n // we need to determine what the WHERE function should be\n let where = buildWhereFunction(type, condition, options)\n\n // our getGraphQLType expects every requested field to be in the schema definition. \"node\" isn't a parent of whatever type we're getting, so we'll just wrap that type in an object that LOOKS that same as a hypothetical Node type\n const fakeParentNode = {\n _fields: {\n node: {\n type,\n name: type.name.toLowerCase(),\n where\n }\n }\n }\n const namespace = new AliasNamespace(options.minify)\n const sqlAST = {}\n const fieldNodes = resolveInfo.fieldNodes || resolveInfo.fieldASTs\n // uses the same underlying function as the main `joinMonster`\n queryAST.populateASTNode.call(resolveInfo, fieldNodes[0], fakeParentNode, sqlAST, namespace, 0, options, context)\n queryAST.pruneDuplicateSqlDeps(sqlAST, namespace)\n const { sql, shapeDefinition } = await compileSqlAST(sqlAST, context, options)\n const data = arrToConnection(await handleUserDbCall(dbCall, sql, sqlAST, shapeDefinition), sqlAST)\n await nextBatch(sqlAST, data, dbCall, context, options)\n if (!data) return data\n data.__type__ = type\n return data\n}", "code_tokens": ["async", "function", "getNode", "(", "typeName", ",", "resolveInfo", ",", "context", ",", "condition", ",", "dbCall", ",", "options", "=", "{", "}", ")", "{", "const", "type", "=", "resolveInfo", ".", "schema", ".", "_typeMap", "[", "typeName", "]", "assert", "(", "type", ",", "`", "${", "typeName", "}", "`", ")", "assert", "(", "type", ".", "_typeConfig", ".", "sqlTable", ",", "`", "${", "typeName", "}", "`", ")", "let", "where", "=", "buildWhereFunction", "(", "type", ",", "condition", ",", "options", ")", "const", "fakeParentNode", "=", "{", "_fields", ":", "{", "node", ":", "{", "type", ",", "name", ":", "type", ".", "name", ".", "toLowerCase", "(", ")", ",", "where", "}", "}", "}", "const", "namespace", "=", "new", "AliasNamespace", "(", "options", ".", "minify", ")", "const", "sqlAST", "=", "{", "}", "const", "fieldNodes", "=", "resolveInfo", ".", "fieldNodes", "||", "resolveInfo", ".", "fieldASTs", "queryAST", ".", "populateASTNode", ".", "call", "(", "resolveInfo", ",", "fieldNodes", "[", "0", "]", ",", "fakeParentNode", ",", "sqlAST", ",", "namespace", ",", "0", ",", "options", ",", "context", ")", "queryAST", ".", "pruneDuplicateSqlDeps", "(", "sqlAST", ",", "namespace", ")", "const", "{", "sql", ",", "shapeDefinition", "}", "=", "await", "compileSqlAST", "(", "sqlAST", ",", "context", ",", "options", ")", "const", "data", "=", "arrToConnection", "(", "await", "handleUserDbCall", "(", "dbCall", ",", "sql", ",", "sqlAST", ",", "shapeDefinition", ")", ",", "sqlAST", ")", "await", "nextBatch", "(", "sqlAST", ",", "data", ",", "dbCall", ",", "context", ",", "options", ")", "if", "(", "!", "data", ")", "return", "data", "data", ".", "__type__", "=", "type", "return", "data", "}"], "docstring": "A helper for resolving the Node type in Relay.\n@param {String} typeName - The Name of the GraphQLObjectType\n@param {Object} resolveInfo - Contains the parsed GraphQL query, schema definition, and more. Obtained from the fourth argument to the resolver.\n@param {Object} context - An arbitrary object that gets passed to the `where` function. Useful for contextual infomation that influeces the WHERE condition, e.g. session, logged in user, localization.\n@param {where|Number|String|Array} condition - A value to determine the `where` function for searching the node. If it's a function, that function will be used as the `where` function. Otherwise, it is assumed to be the value(s) of the `primaryKey`. An array of values is needed for composite primary keys.\n@param {Function} dbCall - A function that is passed the compiled SQL that calls the database and returns (a promise of) the data.\n@param {Object} [options] - Same as `joinMonster` function's options.\n@returns {Promise.} The correctly nested data from the database. The GraphQL Type is added to the \"\\_\\_type\\_\\_\" property, which is helpful for the `resolveType` function in the `nodeDefinitions` of **graphql-relay-js**.", "docstring_tokens": ["A", "helper", "for", "resolving", "the", "Node", "type", "in", "Relay", "."], "sha": "8db8b54aaefd2fd975d63e2ab3ec05922e25118c", "url": "https://github.com/acarl005/join-monster/blob/8db8b54aaefd2fd975d63e2ab3ec05922e25118c/src/index.js#L128-L159", "partition": "test"} {"repo": "acarl005/join-monster", "path": "src/array-to-connection.js", "func_name": "arrToConnection", "original_string": "function arrToConnection(data, sqlAST) {\n // use \"post-order\" tree traversal\n for (let astChild of sqlAST.children || []) {\n if (Array.isArray(data)) {\n for (let dataItem of data) {\n recurseOnObjInData(dataItem, astChild)\n }\n } else if (data) {\n recurseOnObjInData(data, astChild)\n }\n }\n const pageInfo = {\n hasNextPage: false,\n hasPreviousPage: false\n }\n if (!data) {\n if (sqlAST.paginate) {\n return {\n pageInfo,\n edges: []\n }\n }\n return null\n }\n // is cases where pagination was done, take the data and convert to the connection object\n // if any two fields happen to become a reference to the same object (when their `uniqueKey`s are the same),\n // we must prevent the recursive processing from visting the same object twice, because mutating the object the first\n // time changes it everywhere. we'll set the `_paginated` property to true to prevent this\n if (sqlAST.paginate && !data._paginated) {\n if (sqlAST.sortKey || idx(sqlAST, _ => _.junction.sortKey)) {\n if (idx(sqlAST, _ => _.args.first)) {\n // we fetched an extra one in order to determine if there is a next page, if there is one, pop off that extra\n if (data.length > sqlAST.args.first) {\n pageInfo.hasNextPage = true\n data.pop()\n }\n } else if (sqlAST.args && sqlAST.args.last) {\n // if backward paging, do the same, but also reverse it\n if (data.length > sqlAST.args.last) {\n pageInfo.hasPreviousPage = true\n data.pop()\n }\n data.reverse()\n }\n // convert nodes to edges and compute the cursor for each\n // TODO: only compute all the cursor if asked for them\n const sortKey = sqlAST.sortKey || sqlAST.junction.sortKey\n const edges = data.map(obj => {\n const cursor = {}\n const key = sortKey.key\n for (let column of wrap(key)) {\n cursor[column] = obj[column]\n }\n return { cursor: objToCursor(cursor), node: obj }\n })\n if (data.length) {\n pageInfo.startCursor = edges[0].cursor\n pageInfo.endCursor = last(edges).cursor\n }\n return { edges, pageInfo, _paginated: true }\n }\n if (sqlAST.orderBy || (sqlAST.junction && sqlAST.junction.orderBy)) {\n let offset = 0\n if (idx(sqlAST, _ => _.args.after)) {\n offset = cursorToOffset(sqlAST.args.after) + 1\n }\n // $total was a special column for determining the total number of items\n const arrayLength = data[0] && parseInt(data[0].$total, 10)\n const connection = connectionFromArraySlice(data, sqlAST.args || {}, { sliceStart: offset, arrayLength })\n connection.total = arrayLength || 0\n connection._paginated = true\n return connection\n }\n }\n return data\n}", "language": "javascript", "code": "function arrToConnection(data, sqlAST) {\n // use \"post-order\" tree traversal\n for (let astChild of sqlAST.children || []) {\n if (Array.isArray(data)) {\n for (let dataItem of data) {\n recurseOnObjInData(dataItem, astChild)\n }\n } else if (data) {\n recurseOnObjInData(data, astChild)\n }\n }\n const pageInfo = {\n hasNextPage: false,\n hasPreviousPage: false\n }\n if (!data) {\n if (sqlAST.paginate) {\n return {\n pageInfo,\n edges: []\n }\n }\n return null\n }\n // is cases where pagination was done, take the data and convert to the connection object\n // if any two fields happen to become a reference to the same object (when their `uniqueKey`s are the same),\n // we must prevent the recursive processing from visting the same object twice, because mutating the object the first\n // time changes it everywhere. we'll set the `_paginated` property to true to prevent this\n if (sqlAST.paginate && !data._paginated) {\n if (sqlAST.sortKey || idx(sqlAST, _ => _.junction.sortKey)) {\n if (idx(sqlAST, _ => _.args.first)) {\n // we fetched an extra one in order to determine if there is a next page, if there is one, pop off that extra\n if (data.length > sqlAST.args.first) {\n pageInfo.hasNextPage = true\n data.pop()\n }\n } else if (sqlAST.args && sqlAST.args.last) {\n // if backward paging, do the same, but also reverse it\n if (data.length > sqlAST.args.last) {\n pageInfo.hasPreviousPage = true\n data.pop()\n }\n data.reverse()\n }\n // convert nodes to edges and compute the cursor for each\n // TODO: only compute all the cursor if asked for them\n const sortKey = sqlAST.sortKey || sqlAST.junction.sortKey\n const edges = data.map(obj => {\n const cursor = {}\n const key = sortKey.key\n for (let column of wrap(key)) {\n cursor[column] = obj[column]\n }\n return { cursor: objToCursor(cursor), node: obj }\n })\n if (data.length) {\n pageInfo.startCursor = edges[0].cursor\n pageInfo.endCursor = last(edges).cursor\n }\n return { edges, pageInfo, _paginated: true }\n }\n if (sqlAST.orderBy || (sqlAST.junction && sqlAST.junction.orderBy)) {\n let offset = 0\n if (idx(sqlAST, _ => _.args.after)) {\n offset = cursorToOffset(sqlAST.args.after) + 1\n }\n // $total was a special column for determining the total number of items\n const arrayLength = data[0] && parseInt(data[0].$total, 10)\n const connection = connectionFromArraySlice(data, sqlAST.args || {}, { sliceStart: offset, arrayLength })\n connection.total = arrayLength || 0\n connection._paginated = true\n return connection\n }\n }\n return data\n}", "code_tokens": ["function", "arrToConnection", "(", "data", ",", "sqlAST", ")", "{", "for", "(", "let", "astChild", "of", "sqlAST", ".", "children", "||", "[", "]", ")", "{", "if", "(", "Array", ".", "isArray", "(", "data", ")", ")", "{", "for", "(", "let", "dataItem", "of", "data", ")", "{", "recurseOnObjInData", "(", "dataItem", ",", "astChild", ")", "}", "}", "else", "if", "(", "data", ")", "{", "recurseOnObjInData", "(", "data", ",", "astChild", ")", "}", "}", "const", "pageInfo", "=", "{", "hasNextPage", ":", "false", ",", "hasPreviousPage", ":", "false", "}", "if", "(", "!", "data", ")", "{", "if", "(", "sqlAST", ".", "paginate", ")", "{", "return", "{", "pageInfo", ",", "edges", ":", "[", "]", "}", "}", "return", "null", "}", "if", "(", "sqlAST", ".", "paginate", "&&", "!", "data", ".", "_paginated", ")", "{", "if", "(", "sqlAST", ".", "sortKey", "||", "idx", "(", "sqlAST", ",", "_", "=>", "_", ".", "junction", ".", "sortKey", ")", ")", "{", "if", "(", "idx", "(", "sqlAST", ",", "_", "=>", "_", ".", "args", ".", "first", ")", ")", "{", "if", "(", "data", ".", "length", ">", "sqlAST", ".", "args", ".", "first", ")", "{", "pageInfo", ".", "hasNextPage", "=", "true", "data", ".", "pop", "(", ")", "}", "}", "else", "if", "(", "sqlAST", ".", "args", "&&", "sqlAST", ".", "args", ".", "last", ")", "{", "if", "(", "data", ".", "length", ">", "sqlAST", ".", "args", ".", "last", ")", "{", "pageInfo", ".", "hasPreviousPage", "=", "true", "data", ".", "pop", "(", ")", "}", "data", ".", "reverse", "(", ")", "}", "const", "sortKey", "=", "sqlAST", ".", "sortKey", "||", "sqlAST", ".", "junction", ".", "sortKey", "const", "edges", "=", "data", ".", "map", "(", "obj", "=>", "{", "const", "cursor", "=", "{", "}", "const", "key", "=", "sortKey", ".", "key", "for", "(", "let", "column", "of", "wrap", "(", "key", ")", ")", "{", "cursor", "[", "column", "]", "=", "obj", "[", "column", "]", "}", "return", "{", "cursor", ":", "objToCursor", "(", "cursor", ")", ",", "node", ":", "obj", "}", "}", ")", "if", "(", "data", ".", "length", ")", "{", "pageInfo", ".", "startCursor", "=", "edges", "[", "0", "]", ".", "cursor", "pageInfo", ".", "endCursor", "=", "last", "(", "edges", ")", ".", "cursor", "}", "return", "{", "edges", ",", "pageInfo", ",", "_paginated", ":", "true", "}", "}", "if", "(", "sqlAST", ".", "orderBy", "||", "(", "sqlAST", ".", "junction", "&&", "sqlAST", ".", "junction", ".", "orderBy", ")", ")", "{", "let", "offset", "=", "0", "if", "(", "idx", "(", "sqlAST", ",", "_", "=>", "_", ".", "args", ".", "after", ")", ")", "{", "offset", "=", "cursorToOffset", "(", "sqlAST", ".", "args", ".", "after", ")", "+", "1", "}", "const", "arrayLength", "=", "data", "[", "0", "]", "&&", "parseInt", "(", "data", "[", "0", "]", ".", "$total", ",", "10", ")", "const", "connection", "=", "connectionFromArraySlice", "(", "data", ",", "sqlAST", ".", "args", "||", "{", "}", ",", "{", "sliceStart", ":", "offset", ",", "arrayLength", "}", ")", "connection", ".", "total", "=", "arrayLength", "||", "0", "connection", ".", "_paginated", "=", "true", "return", "connection", "}", "}", "return", "data", "}"], "docstring": "a function for data manipulation AFTER its nested. this is only necessary when using the SQL pagination we have to interpret the slice that comes back and generate the Connection Object type", "docstring_tokens": ["a", "function", "for", "data", "manipulation", "AFTER", "its", "nested", ".", "this", "is", "only", "necessary", "when", "using", "the", "SQL", "pagination", "we", "have", "to", "interpret", "the", "slice", "that", "comes", "back", "and", "generate", "the", "Connection", "Object", "type"], "sha": "8db8b54aaefd2fd975d63e2ab3ec05922e25118c", "url": "https://github.com/acarl005/join-monster/blob/8db8b54aaefd2fd975d63e2ab3ec05922e25118c/src/array-to-connection.js#L8-L83", "partition": "test"} {"repo": "acarl005/join-monster", "path": "src/util.js", "func_name": "validate", "original_string": "function validate(rows) {\n // its supposed to be an array of objects\n if (Array.isArray(rows)) return rows\n // a check for the most common error. a lot of ORMs return an object with the desired data on the `rows` property\n if (rows && rows.rows) return rows.rows\n\n throw new Error(\n `\"dbCall\" function must return/resolve an array of objects where each object is a row from the result set.\n Instead got ${util.inspect(rows, { depth: 3 })}`\n )\n}", "language": "javascript", "code": "function validate(rows) {\n // its supposed to be an array of objects\n if (Array.isArray(rows)) return rows\n // a check for the most common error. a lot of ORMs return an object with the desired data on the `rows` property\n if (rows && rows.rows) return rows.rows\n\n throw new Error(\n `\"dbCall\" function must return/resolve an array of objects where each object is a row from the result set.\n Instead got ${util.inspect(rows, { depth: 3 })}`\n )\n}", "code_tokens": ["function", "validate", "(", "rows", ")", "{", "if", "(", "Array", ".", "isArray", "(", "rows", ")", ")", "return", "rows", "if", "(", "rows", "&&", "rows", ".", "rows", ")", "return", "rows", ".", "rows", "throw", "new", "Error", "(", "`", "${", "util", ".", "inspect", "(", "rows", ",", "{", "depth", ":", "3", "}", ")", "}", "`", ")", "}"], "docstring": "validate the data they gave us", "docstring_tokens": ["validate", "the", "data", "they", "gave", "us"], "sha": "8db8b54aaefd2fd975d63e2ab3ec05922e25118c", "url": "https://github.com/acarl005/join-monster/blob/8db8b54aaefd2fd975d63e2ab3ec05922e25118c/src/util.js#L190-L200", "partition": "test"} {"repo": "acarl005/join-monster", "path": "src/stringifiers/shared.js", "func_name": "sortKeyToWhereCondition", "original_string": "function sortKeyToWhereCondition(keyObj, descending, sortTable, dialect) {\n const { name, quote: q } = dialect\n const sortColumns = []\n const sortValues = []\n for (let key in keyObj) {\n sortColumns.push(`${q(sortTable)}.${q(key)}`)\n sortValues.push(maybeQuote(keyObj[key], name))\n }\n const operator = descending ? '<' : '>'\n return name === 'oracle'\n ? recursiveWhereJoin(sortColumns, sortValues, operator)\n : `(${sortColumns.join(', ')}) ${operator} (${sortValues.join(', ')})`\n}", "language": "javascript", "code": "function sortKeyToWhereCondition(keyObj, descending, sortTable, dialect) {\n const { name, quote: q } = dialect\n const sortColumns = []\n const sortValues = []\n for (let key in keyObj) {\n sortColumns.push(`${q(sortTable)}.${q(key)}`)\n sortValues.push(maybeQuote(keyObj[key], name))\n }\n const operator = descending ? '<' : '>'\n return name === 'oracle'\n ? recursiveWhereJoin(sortColumns, sortValues, operator)\n : `(${sortColumns.join(', ')}) ${operator} (${sortValues.join(', ')})`\n}", "code_tokens": ["function", "sortKeyToWhereCondition", "(", "keyObj", ",", "descending", ",", "sortTable", ",", "dialect", ")", "{", "const", "{", "name", ",", "quote", ":", "q", "}", "=", "dialect", "const", "sortColumns", "=", "[", "]", "const", "sortValues", "=", "[", "]", "for", "(", "let", "key", "in", "keyObj", ")", "{", "sortColumns", ".", "push", "(", "`", "${", "q", "(", "sortTable", ")", "}", "${", "q", "(", "key", ")", "}", "`", ")", "sortValues", ".", "push", "(", "maybeQuote", "(", "keyObj", "[", "key", "]", ",", "name", ")", ")", "}", "const", "operator", "=", "descending", "?", "'<'", ":", "'>'", "return", "name", "===", "'oracle'", "?", "recursiveWhereJoin", "(", "sortColumns", ",", "sortValues", ",", "operator", ")", ":", "`", "${", "sortColumns", ".", "join", "(", "', '", ")", "}", "${", "operator", "}", "${", "sortValues", ".", "join", "(", "', '", ")", "}", "`", "}"], "docstring": "take the sort key and translate that for the where clause", "docstring_tokens": ["take", "the", "sort", "key", "and", "translate", "that", "for", "the", "where", "clause"], "sha": "8db8b54aaefd2fd975d63e2ab3ec05922e25118c", "url": "https://github.com/acarl005/join-monster/blob/8db8b54aaefd2fd975d63e2ab3ec05922e25118c/src/stringifiers/shared.js#L204-L216", "partition": "test"} {"repo": "reflux/refluxjs", "path": "src/defineReact.js", "func_name": "clone", "original_string": "function clone(frm, to) {\n\tif (frm === null || typeof frm !== \"object\") {\n\t\treturn frm;\n\t}\n\tif (frm.constructor !== Object && frm.constructor !== Array) {\n\t\treturn frm;\n\t}\n\tif (frm.constructor === Date || frm.constructor === RegExp || frm.constructor === Function ||\n\t\tfrm.constructor === String || frm.constructor === Number || frm.constructor === Boolean) {\n\t\treturn new frm.constructor(frm);\n\t}\n\tto = to || new frm.constructor();\n\tfor (var name in frm) {\n\t\tto[name] = typeof to[name] === \"undefined\" ? clone(frm[name], null) : to[name];\n\t}\n\treturn to;\n}", "language": "javascript", "code": "function clone(frm, to) {\n\tif (frm === null || typeof frm !== \"object\") {\n\t\treturn frm;\n\t}\n\tif (frm.constructor !== Object && frm.constructor !== Array) {\n\t\treturn frm;\n\t}\n\tif (frm.constructor === Date || frm.constructor === RegExp || frm.constructor === Function ||\n\t\tfrm.constructor === String || frm.constructor === Number || frm.constructor === Boolean) {\n\t\treturn new frm.constructor(frm);\n\t}\n\tto = to || new frm.constructor();\n\tfor (var name in frm) {\n\t\tto[name] = typeof to[name] === \"undefined\" ? clone(frm[name], null) : to[name];\n\t}\n\treturn to;\n}", "code_tokens": ["function", "clone", "(", "frm", ",", "to", ")", "{", "if", "(", "frm", "===", "null", "||", "typeof", "frm", "!==", "\"object\"", ")", "{", "return", "frm", ";", "}", "if", "(", "frm", ".", "constructor", "!==", "Object", "&&", "frm", ".", "constructor", "!==", "Array", ")", "{", "return", "frm", ";", "}", "if", "(", "frm", ".", "constructor", "===", "Date", "||", "frm", ".", "constructor", "===", "RegExp", "||", "frm", ".", "constructor", "===", "Function", "||", "frm", ".", "constructor", "===", "String", "||", "frm", ".", "constructor", "===", "Number", "||", "frm", ".", "constructor", "===", "Boolean", ")", "{", "return", "new", "frm", ".", "constructor", "(", "frm", ")", ";", "}", "to", "=", "to", "||", "new", "frm", ".", "constructor", "(", ")", ";", "for", "(", "var", "name", "in", "frm", ")", "{", "to", "[", "name", "]", "=", "typeof", "to", "[", "name", "]", "===", "\"undefined\"", "?", "clone", "(", "frm", "[", "name", "]", ",", "null", ")", ":", "to", "[", "name", "]", ";", "}", "return", "to", ";", "}"], "docstring": "this is utilized by some of the global state functionality in order to get a clone that will not continue to be modified as the GlobalState mutates", "docstring_tokens": ["this", "is", "utilized", "by", "some", "of", "the", "global", "state", "functionality", "in", "order", "to", "get", "a", "clone", "that", "will", "not", "continue", "to", "be", "modified", "as", "the", "GlobalState", "mutates"], "sha": "24a476defcf3f1dc79a3f1f29bb7b46e0a51d327", "url": "https://github.com/reflux/refluxjs/blob/24a476defcf3f1dc79a3f1f29bb7b46e0a51d327/src/defineReact.js#L453-L469", "partition": "test"} {"repo": "Kong/httpsnippet", "path": "src/targets/swift/helpers.js", "func_name": "buildString", "original_string": "function buildString (length, str) {\n return Array.apply(null, new Array(length)).map(String.prototype.valueOf, str).join('')\n}", "language": "javascript", "code": "function buildString (length, str) {\n return Array.apply(null, new Array(length)).map(String.prototype.valueOf, str).join('')\n}", "code_tokens": ["function", "buildString", "(", "length", ",", "str", ")", "{", "return", "Array", ".", "apply", "(", "null", ",", "new", "Array", "(", "length", ")", ")", ".", "map", "(", "String", ".", "prototype", ".", "valueOf", ",", "str", ")", ".", "join", "(", "''", ")", "}"], "docstring": "Create an string of given length filled with blank spaces\n\n@param {number} length Length of the array to return\n@return {string}", "docstring_tokens": ["Create", "an", "string", "of", "given", "length", "filled", "with", "blank", "spaces"], "sha": "c780dad09b014a1bb28e463b4b058b2d40ae2124", "url": "https://github.com/Kong/httpsnippet/blob/c780dad09b014a1bb28e463b4b058b2d40ae2124/src/targets/swift/helpers.js#L11-L13", "partition": "test"} {"repo": "Kong/httpsnippet", "path": "src/targets/swift/helpers.js", "func_name": "concatArray", "original_string": "function concatArray (arr, pretty, indentation, indentLevel) {\n var currentIndent = buildString(indentLevel, indentation)\n var closingBraceIndent = buildString(indentLevel - 1, indentation)\n var join = pretty ? ',\\n' + currentIndent : ', '\n\n if (pretty) {\n return '[\\n' + currentIndent + arr.join(join) + '\\n' + closingBraceIndent + ']'\n } else {\n return '[' + arr.join(join) + ']'\n }\n}", "language": "javascript", "code": "function concatArray (arr, pretty, indentation, indentLevel) {\n var currentIndent = buildString(indentLevel, indentation)\n var closingBraceIndent = buildString(indentLevel - 1, indentation)\n var join = pretty ? ',\\n' + currentIndent : ', '\n\n if (pretty) {\n return '[\\n' + currentIndent + arr.join(join) + '\\n' + closingBraceIndent + ']'\n } else {\n return '[' + arr.join(join) + ']'\n }\n}", "code_tokens": ["function", "concatArray", "(", "arr", ",", "pretty", ",", "indentation", ",", "indentLevel", ")", "{", "var", "currentIndent", "=", "buildString", "(", "indentLevel", ",", "indentation", ")", "var", "closingBraceIndent", "=", "buildString", "(", "indentLevel", "-", "1", ",", "indentation", ")", "var", "join", "=", "pretty", "?", "',\\n'", "+", "\\n", ":", "currentIndent", "', '", "}"], "docstring": "Create a string corresponding to a Dictionary or Array literal representation with pretty option\nand indentation.", "docstring_tokens": ["Create", "a", "string", "corresponding", "to", "a", "Dictionary", "or", "Array", "literal", "representation", "with", "pretty", "option", "and", "indentation", "."], "sha": "c780dad09b014a1bb28e463b4b058b2d40ae2124", "url": "https://github.com/Kong/httpsnippet/blob/c780dad09b014a1bb28e463b4b058b2d40ae2124/src/targets/swift/helpers.js#L19-L29", "partition": "test"} {"repo": "Kong/httpsnippet", "path": "src/targets/swift/helpers.js", "func_name": "", "original_string": "function (value, opts, indentLevel) {\n indentLevel = indentLevel === undefined ? 1 : indentLevel + 1\n\n switch (Object.prototype.toString.call(value)) {\n case '[object Number]':\n return value\n case '[object Array]':\n // Don't prettify arrays nto not take too much space\n var pretty = false\n var valuesRepresentation = value.map(function (v) {\n // Switch to prettify if the value is a dictionary with multiple keys\n if (Object.prototype.toString.call(v) === '[object Object]') {\n pretty = Object.keys(v).length > 1\n }\n return this.literalRepresentation(v, opts, indentLevel)\n }.bind(this))\n return concatArray(valuesRepresentation, pretty, opts.indent, indentLevel)\n case '[object Object]':\n var keyValuePairs = []\n for (var k in value) {\n keyValuePairs.push(util.format('\"%s\": %s', k, this.literalRepresentation(value[k], opts, indentLevel)))\n }\n return concatArray(keyValuePairs, opts.pretty && keyValuePairs.length > 1, opts.indent, indentLevel)\n case '[object Boolean]':\n return value.toString()\n default:\n if (value === null || value === undefined) {\n return ''\n }\n return '\"' + value.toString().replace(/\"/g, '\\\\\"') + '\"'\n }\n }", "language": "javascript", "code": "function (value, opts, indentLevel) {\n indentLevel = indentLevel === undefined ? 1 : indentLevel + 1\n\n switch (Object.prototype.toString.call(value)) {\n case '[object Number]':\n return value\n case '[object Array]':\n // Don't prettify arrays nto not take too much space\n var pretty = false\n var valuesRepresentation = value.map(function (v) {\n // Switch to prettify if the value is a dictionary with multiple keys\n if (Object.prototype.toString.call(v) === '[object Object]') {\n pretty = Object.keys(v).length > 1\n }\n return this.literalRepresentation(v, opts, indentLevel)\n }.bind(this))\n return concatArray(valuesRepresentation, pretty, opts.indent, indentLevel)\n case '[object Object]':\n var keyValuePairs = []\n for (var k in value) {\n keyValuePairs.push(util.format('\"%s\": %s', k, this.literalRepresentation(value[k], opts, indentLevel)))\n }\n return concatArray(keyValuePairs, opts.pretty && keyValuePairs.length > 1, opts.indent, indentLevel)\n case '[object Boolean]':\n return value.toString()\n default:\n if (value === null || value === undefined) {\n return ''\n }\n return '\"' + value.toString().replace(/\"/g, '\\\\\"') + '\"'\n }\n }", "code_tokens": ["function", "(", "value", ",", "opts", ",", "indentLevel", ")", "{", "indentLevel", "=", "indentLevel", "===", "undefined", "?", "1", ":", "indentLevel", "+", "1", "switch", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "value", ")", ")", "{", "case", "'[object Number]'", ":", "return", "value", "case", "'[object Array]'", ":", "var", "pretty", "=", "false", "var", "valuesRepresentation", "=", "value", ".", "map", "(", "function", "(", "v", ")", "{", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "v", ")", "===", "'[object Object]'", ")", "{", "pretty", "=", "Object", ".", "keys", "(", "v", ")", ".", "length", ">", "1", "}", "return", "this", ".", "literalRepresentation", "(", "v", ",", "opts", ",", "indentLevel", ")", "}", ".", "bind", "(", "this", ")", ")", "return", "concatArray", "(", "valuesRepresentation", ",", "pretty", ",", "opts", ".", "indent", ",", "indentLevel", ")", "case", "'[object Object]'", ":", "var", "keyValuePairs", "=", "[", "]", "for", "(", "var", "k", "in", "value", ")", "{", "keyValuePairs", ".", "push", "(", "util", ".", "format", "(", "'\"%s\": %s'", ",", "k", ",", "this", ".", "literalRepresentation", "(", "value", "[", "k", "]", ",", "opts", ",", "indentLevel", ")", ")", ")", "}", "return", "concatArray", "(", "keyValuePairs", ",", "opts", ".", "pretty", "&&", "keyValuePairs", ".", "length", ">", "1", ",", "opts", ".", "indent", ",", "indentLevel", ")", "case", "'[object Boolean]'", ":", "return", "value", ".", "toString", "(", ")", "default", ":", "if", "(", "value", "===", "null", "||", "value", "===", "undefined", ")", "{", "return", "''", "}", "return", "'\"'", "+", "value", ".", "toString", "(", ")", ".", "replace", "(", "/", "\"", "/", "g", ",", "'\\\\\"'", ")", "+", "\\\\", "}", "}"], "docstring": "Create a valid Swift string of a literal value according to its type.\n\n@param {*} value Any JavaScript literal\n@param {Object} opts Target options\n@return {string}", "docstring_tokens": ["Create", "a", "valid", "Swift", "string", "of", "a", "literal", "value", "according", "to", "its", "type", "."], "sha": "c780dad09b014a1bb28e463b4b058b2d40ae2124", "url": "https://github.com/Kong/httpsnippet/blob/c780dad09b014a1bb28e463b4b058b2d40ae2124/src/targets/swift/helpers.js#L51-L82", "partition": "test"} {"repo": "quip/quip-apps", "path": "packages/quip-apps-compat/index.js", "func_name": "", "original_string": "function(text, placeholders) {\n if (text[text.length - 1] == \"]\" && text.lastIndexOf(\" [\") != -1) {\n // Remove translation comments\n text = text.substr(0, text.lastIndexOf(\" [\"));\n }\n var replaceAll = function(str, substr, replacement) {\n return str.replace(\n new RegExp(\n substr.replace(/([.*+?^=!:${}()|\\[\\]\\/\\\\])/g, \"\\\\$1\"), \"g\"),\n replacement);\n }\n var localeReplace = function(text, placeholders) {\n for (var key in placeholders) {\n text = replaceAll(text, \"%(\" + key + \")s\", placeholders[key]);\n }\n return text;\n };\n var reactLocaleReplace = function(text, placeholders) {\n var start;\n var expanded = [text];\n for (var key in placeholders) {\n start = expanded;\n expanded = [];\n for (var i = 0; i < start.length; i++) {\n if (typeof start[i] == \"string\") {\n var keyStr = \"%(\" + key + \")s\";\n var parts = start[i].split(keyStr);\n var replaced = [];\n for (var j = 0; j < parts.length - 1; j++) {\n replaced.push(parts[j]);\n replaced.push(placeholders[key]);\n }\n replaced.push(parts[parts.length - 1]);\n replaced = replaced.filter(function (str) {\n return str != \"\";\n });\n expanded.push.apply(expanded, replaced)\n } else {\n expanded.push(start[i]);\n }\n }\n }\n return expanded;\n }\n if (placeholders) {\n var hasReactElements = false;\n for (var key in placeholders) {\n var val = placeholders[key];\n if (typeof val !== \"string\" && React.isValidElement(val)) {\n hasReactElements = true;\n break;\n }\n }\n return (hasReactElements ?\n reactLocaleReplace(text, placeholders) :\n localeReplace(text, placeholders));\n }\n return text;\n }", "language": "javascript", "code": "function(text, placeholders) {\n if (text[text.length - 1] == \"]\" && text.lastIndexOf(\" [\") != -1) {\n // Remove translation comments\n text = text.substr(0, text.lastIndexOf(\" [\"));\n }\n var replaceAll = function(str, substr, replacement) {\n return str.replace(\n new RegExp(\n substr.replace(/([.*+?^=!:${}()|\\[\\]\\/\\\\])/g, \"\\\\$1\"), \"g\"),\n replacement);\n }\n var localeReplace = function(text, placeholders) {\n for (var key in placeholders) {\n text = replaceAll(text, \"%(\" + key + \")s\", placeholders[key]);\n }\n return text;\n };\n var reactLocaleReplace = function(text, placeholders) {\n var start;\n var expanded = [text];\n for (var key in placeholders) {\n start = expanded;\n expanded = [];\n for (var i = 0; i < start.length; i++) {\n if (typeof start[i] == \"string\") {\n var keyStr = \"%(\" + key + \")s\";\n var parts = start[i].split(keyStr);\n var replaced = [];\n for (var j = 0; j < parts.length - 1; j++) {\n replaced.push(parts[j]);\n replaced.push(placeholders[key]);\n }\n replaced.push(parts[parts.length - 1]);\n replaced = replaced.filter(function (str) {\n return str != \"\";\n });\n expanded.push.apply(expanded, replaced)\n } else {\n expanded.push(start[i]);\n }\n }\n }\n return expanded;\n }\n if (placeholders) {\n var hasReactElements = false;\n for (var key in placeholders) {\n var val = placeholders[key];\n if (typeof val !== \"string\" && React.isValidElement(val)) {\n hasReactElements = true;\n break;\n }\n }\n return (hasReactElements ?\n reactLocaleReplace(text, placeholders) :\n localeReplace(text, placeholders));\n }\n return text;\n }", "code_tokens": ["function", "(", "text", ",", "placeholders", ")", "{", "if", "(", "text", "[", "text", ".", "length", "-", "1", "]", "==", "\"]\"", "&&", "text", ".", "lastIndexOf", "(", "\" [\"", ")", "!=", "-", "1", ")", "{", "text", "=", "text", ".", "substr", "(", "0", ",", "text", ".", "lastIndexOf", "(", "\" [\"", ")", ")", ";", "}", "var", "replaceAll", "=", "function", "(", "str", ",", "substr", ",", "replacement", ")", "{", "return", "str", ".", "replace", "(", "new", "RegExp", "(", "substr", ".", "replace", "(", "/", "([.*+?^=!:${}()|\\[\\]\\/\\\\])", "/", "g", ",", "\"\\\\$1\"", ")", ",", "\\\\", ")", ",", "\"g\"", ")", ";", "}", "replacement", "var", "localeReplace", "=", "function", "(", "text", ",", "placeholders", ")", "{", "for", "(", "var", "key", "in", "placeholders", ")", "{", "text", "=", "replaceAll", "(", "text", ",", "\"%(\"", "+", "key", "+", "\")s\"", ",", "placeholders", "[", "key", "]", ")", ";", "}", "return", "text", ";", "}", ";", "var", "reactLocaleReplace", "=", "function", "(", "text", ",", "placeholders", ")", "{", "var", "start", ";", "var", "expanded", "=", "[", "text", "]", ";", "for", "(", "var", "key", "in", "placeholders", ")", "{", "start", "=", "expanded", ";", "expanded", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "start", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeof", "start", "[", "i", "]", "==", "\"string\"", ")", "{", "var", "keyStr", "=", "\"%(\"", "+", "key", "+", "\")s\"", ";", "var", "parts", "=", "start", "[", "i", "]", ".", "split", "(", "keyStr", ")", ";", "var", "replaced", "=", "[", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "parts", ".", "length", "-", "1", ";", "j", "++", ")", "{", "replaced", ".", "push", "(", "parts", "[", "j", "]", ")", ";", "replaced", ".", "push", "(", "placeholders", "[", "key", "]", ")", ";", "}", "replaced", ".", "push", "(", "parts", "[", "parts", ".", "length", "-", "1", "]", ")", ";", "replaced", "=", "replaced", ".", "filter", "(", "function", "(", "str", ")", "{", "return", "str", "!=", "\"\"", ";", "}", ")", ";", "expanded", ".", "push", ".", "apply", "(", "expanded", ",", "replaced", ")", "}", "else", "{", "expanded", ".", "push", "(", "start", "[", "i", "]", ")", ";", "}", "}", "}", "return", "expanded", ";", "}", "if", "(", "placeholders", ")", "{", "var", "hasReactElements", "=", "false", ";", "for", "(", "var", "key", "in", "placeholders", ")", "{", "var", "val", "=", "placeholders", "[", "key", "]", ";", "if", "(", "typeof", "val", "!==", "\"string\"", "&&", "React", ".", "isValidElement", "(", "val", ")", ")", "{", "hasReactElements", "=", "true", ";", "break", ";", "}", "}", "return", "(", "hasReactElements", "?", "reactLocaleReplace", "(", "text", ",", "placeholders", ")", ":", "localeReplace", "(", "text", ",", "placeholders", ")", ")", ";", "}", "}"], "docstring": "For quiptext, introduced in 0.1.044", "docstring_tokens": ["For", "quiptext", "introduced", "in", "0", ".", "1", ".", "044"], "sha": "09ced6aabb3dbc28e91e9a713837b85de68422d9", "url": "https://github.com/quip/quip-apps/blob/09ced6aabb3dbc28e91e9a713837b85de68422d9/packages/quip-apps-compat/index.js#L11-L69", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "www/browser/Media.js", "func_name": "createNode", "original_string": "function createNode (media) {\n var node = new Audio();\n\n node.onplay = function () {\n Media.onStatus(media.id, Media.MEDIA_STATE, Media.MEDIA_STARTING);\n };\n\n node.onplaying = function () {\n Media.onStatus(media.id, Media.MEDIA_STATE, Media.MEDIA_RUNNING);\n };\n\n node.ondurationchange = function (e) {\n Media.onStatus(media.id, Media.MEDIA_DURATION, e.target.duration || -1);\n };\n\n node.onerror = function (e) {\n // Due to media.spec.15 It should return MediaError for bad filename\n var err = e.target.error.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED ?\n { code: MediaError.MEDIA_ERR_ABORTED } :\n e.target.error;\n\n Media.onStatus(media.id, Media.MEDIA_ERROR, err);\n };\n\n node.onended = function () {\n Media.onStatus(media.id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);\n };\n\n if (media.src) {\n node.src = media.src;\n }\n\n return node;\n}", "language": "javascript", "code": "function createNode (media) {\n var node = new Audio();\n\n node.onplay = function () {\n Media.onStatus(media.id, Media.MEDIA_STATE, Media.MEDIA_STARTING);\n };\n\n node.onplaying = function () {\n Media.onStatus(media.id, Media.MEDIA_STATE, Media.MEDIA_RUNNING);\n };\n\n node.ondurationchange = function (e) {\n Media.onStatus(media.id, Media.MEDIA_DURATION, e.target.duration || -1);\n };\n\n node.onerror = function (e) {\n // Due to media.spec.15 It should return MediaError for bad filename\n var err = e.target.error.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED ?\n { code: MediaError.MEDIA_ERR_ABORTED } :\n e.target.error;\n\n Media.onStatus(media.id, Media.MEDIA_ERROR, err);\n };\n\n node.onended = function () {\n Media.onStatus(media.id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);\n };\n\n if (media.src) {\n node.src = media.src;\n }\n\n return node;\n}", "code_tokens": ["function", "createNode", "(", "media", ")", "{", "var", "node", "=", "new", "Audio", "(", ")", ";", "node", ".", "onplay", "=", "function", "(", ")", "{", "Media", ".", "onStatus", "(", "media", ".", "id", ",", "Media", ".", "MEDIA_STATE", ",", "Media", ".", "MEDIA_STARTING", ")", ";", "}", ";", "node", ".", "onplaying", "=", "function", "(", ")", "{", "Media", ".", "onStatus", "(", "media", ".", "id", ",", "Media", ".", "MEDIA_STATE", ",", "Media", ".", "MEDIA_RUNNING", ")", ";", "}", ";", "node", ".", "ondurationchange", "=", "function", "(", "e", ")", "{", "Media", ".", "onStatus", "(", "media", ".", "id", ",", "Media", ".", "MEDIA_DURATION", ",", "e", ".", "target", ".", "duration", "||", "-", "1", ")", ";", "}", ";", "node", ".", "onerror", "=", "function", "(", "e", ")", "{", "var", "err", "=", "e", ".", "target", ".", "error", ".", "code", "===", "MediaError", ".", "MEDIA_ERR_SRC_NOT_SUPPORTED", "?", "{", "code", ":", "MediaError", ".", "MEDIA_ERR_ABORTED", "}", ":", "e", ".", "target", ".", "error", ";", "Media", ".", "onStatus", "(", "media", ".", "id", ",", "Media", ".", "MEDIA_ERROR", ",", "err", ")", ";", "}", ";", "node", ".", "onended", "=", "function", "(", ")", "{", "Media", ".", "onStatus", "(", "media", ".", "id", ",", "Media", ".", "MEDIA_STATE", ",", "Media", ".", "MEDIA_STOPPED", ")", ";", "}", ";", "if", "(", "media", ".", "src", ")", "{", "node", ".", "src", "=", "media", ".", "src", ";", "}", "return", "node", ";", "}"], "docstring": "Creates new Audio node and with necessary event listeners attached\n@param {Media} media Media object\n@return {Audio} Audio element", "docstring_tokens": ["Creates", "new", "Audio", "node", "and", "with", "necessary", "event", "listeners", "attached"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/www/browser/Media.js#L64-L97", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "src/windows/MediaProxy.js", "func_name": "", "original_string": "function(win, lose, args) {\n var id = args[0];\n\n var srcUri = processUri(args[1]);\n\n var createAudioNode = !!args[2];\n var thisM = Media.get(id);\n\n Media.prototype.node = null;\n\n var prefix = args[1].split(':').shift();\n var extension = srcUri.extension;\n if (thisM.node === null) {\n if (SUPPORTED_EXTENSIONS.indexOf(extension) === -1 && SUPPORTED_PREFIXES.indexOf(prefix) === -1) {\n if (lose) {\n lose({ code: MediaError.MEDIA_ERR_ABORTED });\n }\n return false; // unable to create\n }\n\n // Don't create Audio object in case of record mode\n if (createAudioNode === true) {\n thisM.node = new Audio();\n thisM.node.msAudioCategory = \"BackgroundCapableMedia\";\n thisM.node.src = srcUri.absoluteCanonicalUri;\n\n thisM.node.onloadstart = function () {\n Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STARTING);\n };\n\n thisM.node.ontimeupdate = function (e) {\n Media.onStatus(id, Media.MEDIA_POSITION, e.target.currentTime);\n };\n\n thisM.node.onplaying = function () {\n Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_RUNNING);\n };\n\n thisM.node.ondurationchange = function (e) {\n Media.onStatus(id, Media.MEDIA_DURATION, e.target.duration || -1);\n };\n\n thisM.node.onerror = function (e) {\n // Due to media.spec.15 It should return MediaError for bad filename\n var err = e.target.error.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED ?\n { code: MediaError.MEDIA_ERR_ABORTED } :\n e.target.error;\n\n Media.onStatus(id, Media.MEDIA_ERROR, err);\n };\n\n thisM.node.onended = function () {\n Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);\n };\n }\n }\n\n return true; // successfully created\n }", "language": "javascript", "code": "function(win, lose, args) {\n var id = args[0];\n\n var srcUri = processUri(args[1]);\n\n var createAudioNode = !!args[2];\n var thisM = Media.get(id);\n\n Media.prototype.node = null;\n\n var prefix = args[1].split(':').shift();\n var extension = srcUri.extension;\n if (thisM.node === null) {\n if (SUPPORTED_EXTENSIONS.indexOf(extension) === -1 && SUPPORTED_PREFIXES.indexOf(prefix) === -1) {\n if (lose) {\n lose({ code: MediaError.MEDIA_ERR_ABORTED });\n }\n return false; // unable to create\n }\n\n // Don't create Audio object in case of record mode\n if (createAudioNode === true) {\n thisM.node = new Audio();\n thisM.node.msAudioCategory = \"BackgroundCapableMedia\";\n thisM.node.src = srcUri.absoluteCanonicalUri;\n\n thisM.node.onloadstart = function () {\n Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STARTING);\n };\n\n thisM.node.ontimeupdate = function (e) {\n Media.onStatus(id, Media.MEDIA_POSITION, e.target.currentTime);\n };\n\n thisM.node.onplaying = function () {\n Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_RUNNING);\n };\n\n thisM.node.ondurationchange = function (e) {\n Media.onStatus(id, Media.MEDIA_DURATION, e.target.duration || -1);\n };\n\n thisM.node.onerror = function (e) {\n // Due to media.spec.15 It should return MediaError for bad filename\n var err = e.target.error.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED ?\n { code: MediaError.MEDIA_ERR_ABORTED } :\n e.target.error;\n\n Media.onStatus(id, Media.MEDIA_ERROR, err);\n };\n\n thisM.node.onended = function () {\n Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);\n };\n }\n }\n\n return true; // successfully created\n }", "code_tokens": ["function", "(", "win", ",", "lose", ",", "args", ")", "{", "var", "id", "=", "args", "[", "0", "]", ";", "var", "srcUri", "=", "processUri", "(", "args", "[", "1", "]", ")", ";", "var", "createAudioNode", "=", "!", "!", "args", "[", "2", "]", ";", "var", "thisM", "=", "Media", ".", "get", "(", "id", ")", ";", "Media", ".", "prototype", ".", "node", "=", "null", ";", "var", "prefix", "=", "args", "[", "1", "]", ".", "split", "(", "':'", ")", ".", "shift", "(", ")", ";", "var", "extension", "=", "srcUri", ".", "extension", ";", "if", "(", "thisM", ".", "node", "===", "null", ")", "{", "if", "(", "SUPPORTED_EXTENSIONS", ".", "indexOf", "(", "extension", ")", "===", "-", "1", "&&", "SUPPORTED_PREFIXES", ".", "indexOf", "(", "prefix", ")", "===", "-", "1", ")", "{", "if", "(", "lose", ")", "{", "lose", "(", "{", "code", ":", "MediaError", ".", "MEDIA_ERR_ABORTED", "}", ")", ";", "}", "return", "false", ";", "}", "if", "(", "createAudioNode", "===", "true", ")", "{", "thisM", ".", "node", "=", "new", "Audio", "(", ")", ";", "thisM", ".", "node", ".", "msAudioCategory", "=", "\"BackgroundCapableMedia\"", ";", "thisM", ".", "node", ".", "src", "=", "srcUri", ".", "absoluteCanonicalUri", ";", "thisM", ".", "node", ".", "onloadstart", "=", "function", "(", ")", "{", "Media", ".", "onStatus", "(", "id", ",", "Media", ".", "MEDIA_STATE", ",", "Media", ".", "MEDIA_STARTING", ")", ";", "}", ";", "thisM", ".", "node", ".", "ontimeupdate", "=", "function", "(", "e", ")", "{", "Media", ".", "onStatus", "(", "id", ",", "Media", ".", "MEDIA_POSITION", ",", "e", ".", "target", ".", "currentTime", ")", ";", "}", ";", "thisM", ".", "node", ".", "onplaying", "=", "function", "(", ")", "{", "Media", ".", "onStatus", "(", "id", ",", "Media", ".", "MEDIA_STATE", ",", "Media", ".", "MEDIA_RUNNING", ")", ";", "}", ";", "thisM", ".", "node", ".", "ondurationchange", "=", "function", "(", "e", ")", "{", "Media", ".", "onStatus", "(", "id", ",", "Media", ".", "MEDIA_DURATION", ",", "e", ".", "target", ".", "duration", "||", "-", "1", ")", ";", "}", ";", "thisM", ".", "node", ".", "onerror", "=", "function", "(", "e", ")", "{", "var", "err", "=", "e", ".", "target", ".", "error", ".", "code", "===", "MediaError", ".", "MEDIA_ERR_SRC_NOT_SUPPORTED", "?", "{", "code", ":", "MediaError", ".", "MEDIA_ERR_ABORTED", "}", ":", "e", ".", "target", ".", "error", ";", "Media", ".", "onStatus", "(", "id", ",", "Media", ".", "MEDIA_ERROR", ",", "err", ")", ";", "}", ";", "thisM", ".", "node", ".", "onended", "=", "function", "(", ")", "{", "Media", ".", "onStatus", "(", "id", ",", "Media", ".", "MEDIA_STATE", ",", "Media", ".", "MEDIA_STOPPED", ")", ";", "}", ";", "}", "}", "return", "true", ";", "}"], "docstring": "Initiates the audio file", "docstring_tokens": ["Initiates", "the", "audio", "file"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/src/windows/MediaProxy.js#L46-L104", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "src/windows/MediaProxy.js", "func_name": "", "original_string": "function(win, lose, args) {\n var id = args[0];\n //var src = args[1];\n //var options = args[2];\n\n var thisM = Media.get(id);\n // if Media was released, then node will be null and we need to create it again\n if (!thisM.node) {\n args[2] = true; // Setting createAudioNode to true\n if (!module.exports.create(win, lose, args)) {\n // there is no reason to continue if we can't create media\n // corresponding callback has been invoked in create so we don't need to call it here\n return;\n }\n }\n\n try {\n thisM.node.play();\n } catch (err) {\n if (lose) {\n lose({code:MediaError.MEDIA_ERR_ABORTED});\n }\n }\n }", "language": "javascript", "code": "function(win, lose, args) {\n var id = args[0];\n //var src = args[1];\n //var options = args[2];\n\n var thisM = Media.get(id);\n // if Media was released, then node will be null and we need to create it again\n if (!thisM.node) {\n args[2] = true; // Setting createAudioNode to true\n if (!module.exports.create(win, lose, args)) {\n // there is no reason to continue if we can't create media\n // corresponding callback has been invoked in create so we don't need to call it here\n return;\n }\n }\n\n try {\n thisM.node.play();\n } catch (err) {\n if (lose) {\n lose({code:MediaError.MEDIA_ERR_ABORTED});\n }\n }\n }", "code_tokens": ["function", "(", "win", ",", "lose", ",", "args", ")", "{", "var", "id", "=", "args", "[", "0", "]", ";", "var", "thisM", "=", "Media", ".", "get", "(", "id", ")", ";", "if", "(", "!", "thisM", ".", "node", ")", "{", "args", "[", "2", "]", "=", "true", ";", "if", "(", "!", "module", ".", "exports", ".", "create", "(", "win", ",", "lose", ",", "args", ")", ")", "{", "return", ";", "}", "}", "try", "{", "thisM", ".", "node", ".", "play", "(", ")", ";", "}", "catch", "(", "err", ")", "{", "if", "(", "lose", ")", "{", "lose", "(", "{", "code", ":", "MediaError", ".", "MEDIA_ERR_ABORTED", "}", ")", ";", "}", "}", "}"], "docstring": "Start playing the audio", "docstring_tokens": ["Start", "playing", "the", "audio"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/src/windows/MediaProxy.js#L107-L130", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "src/windows/MediaProxy.js", "func_name": "", "original_string": "function(win, lose, args) {\n var id = args[0];\n var milliseconds = args[1];\n var thisM = Media.get(id);\n try {\n thisM.node.currentTime = milliseconds / 1000;\n win(thisM.node.currentTime);\n } catch (err) {\n lose(\"Failed to seek: \"+err);\n }\n }", "language": "javascript", "code": "function(win, lose, args) {\n var id = args[0];\n var milliseconds = args[1];\n var thisM = Media.get(id);\n try {\n thisM.node.currentTime = milliseconds / 1000;\n win(thisM.node.currentTime);\n } catch (err) {\n lose(\"Failed to seek: \"+err);\n }\n }", "code_tokens": ["function", "(", "win", ",", "lose", ",", "args", ")", "{", "var", "id", "=", "args", "[", "0", "]", ";", "var", "milliseconds", "=", "args", "[", "1", "]", ";", "var", "thisM", "=", "Media", ".", "get", "(", "id", ")", ";", "try", "{", "thisM", ".", "node", ".", "currentTime", "=", "milliseconds", "/", "1000", ";", "win", "(", "thisM", ".", "node", ".", "currentTime", ")", ";", "}", "catch", "(", "err", ")", "{", "lose", "(", "\"Failed to seek: \"", "+", "err", ")", ";", "}", "}"], "docstring": "Seeks to the position in the audio", "docstring_tokens": ["Seeks", "to", "the", "position", "in", "the", "audio"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/src/windows/MediaProxy.js#L146-L156", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "src/windows/MediaProxy.js", "func_name": "", "original_string": "function(win, lose, args) {\n var id = args[0];\n var thisM = Media.get(id);\n try {\n thisM.node.pause();\n Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_PAUSED);\n } catch (err) {\n lose(\"Failed to pause: \"+err);\n }\n }", "language": "javascript", "code": "function(win, lose, args) {\n var id = args[0];\n var thisM = Media.get(id);\n try {\n thisM.node.pause();\n Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_PAUSED);\n } catch (err) {\n lose(\"Failed to pause: \"+err);\n }\n }", "code_tokens": ["function", "(", "win", ",", "lose", ",", "args", ")", "{", "var", "id", "=", "args", "[", "0", "]", ";", "var", "thisM", "=", "Media", ".", "get", "(", "id", ")", ";", "try", "{", "thisM", ".", "node", ".", "pause", "(", ")", ";", "Media", ".", "onStatus", "(", "id", ",", "Media", ".", "MEDIA_STATE", ",", "Media", ".", "MEDIA_PAUSED", ")", ";", "}", "catch", "(", "err", ")", "{", "lose", "(", "\"Failed to pause: \"", "+", "err", ")", ";", "}", "}"], "docstring": "Pauses the playing audio", "docstring_tokens": ["Pauses", "the", "playing", "audio"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/src/windows/MediaProxy.js#L159-L168", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "src/windows/MediaProxy.js", "func_name": "", "original_string": "function(win, lose, args) {\n var id = args[0];\n try {\n var p = (Media.get(id)).node.currentTime;\n win(p);\n } catch (err) {\n lose(err);\n }\n }", "language": "javascript", "code": "function(win, lose, args) {\n var id = args[0];\n try {\n var p = (Media.get(id)).node.currentTime;\n win(p);\n } catch (err) {\n lose(err);\n }\n }", "code_tokens": ["function", "(", "win", ",", "lose", ",", "args", ")", "{", "var", "id", "=", "args", "[", "0", "]", ";", "try", "{", "var", "p", "=", "(", "Media", ".", "get", "(", "id", ")", ")", ".", "node", ".", "currentTime", ";", "win", "(", "p", ")", ";", "}", "catch", "(", "err", ")", "{", "lose", "(", "err", ")", ";", "}", "}"], "docstring": "Gets current position in the audio", "docstring_tokens": ["Gets", "current", "position", "in", "the", "audio"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/src/windows/MediaProxy.js#L171-L179", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "src/windows/MediaProxy.js", "func_name": "", "original_string": "function(win, lose, args) {\n var id = args[0];\n var srcUri = processUri(args[1]);\n\n var dest = parseUriToPathAndFilename(srcUri);\n var destFileName = dest.fileName;\n\n var success = function () {\n Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_RUNNING);\n };\n\n var error = function (reason) {\n Media.onStatus(id, Media.MEDIA_ERROR, reason);\n };\n\n // Initialize device\n Media.prototype.mediaCaptureMgr = null;\n var thisM = (Media.get(id));\n var captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();\n captureInitSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.audio;\n thisM.mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();\n thisM.mediaCaptureMgr.addEventListener(\"failed\", error);\n\n thisM.mediaCaptureMgr.initializeAsync(captureInitSettings).done(function (result) {\n thisM.mediaCaptureMgr.addEventListener(\"recordlimitationexceeded\", error);\n thisM.mediaCaptureMgr.addEventListener(\"failed\", error);\n\n // Start recording\n Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync(destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(function (newFile) {\n recordedFile = newFile;\n var encodingProfile = null;\n switch (newFile.fileType) {\n case '.m4a':\n encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createM4a(Windows.Media.MediaProperties.AudioEncodingQuality.auto);\n break;\n case '.mp3':\n encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createMp3(Windows.Media.MediaProperties.AudioEncodingQuality.auto);\n break;\n case '.wma':\n encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createWma(Windows.Media.MediaProperties.AudioEncodingQuality.auto);\n break;\n default:\n error(\"Invalid file type for record\");\n break;\n }\n thisM.mediaCaptureMgr.startRecordToStorageFileAsync(encodingProfile, newFile).done(success, error);\n }, error);\n }, error);\n }", "language": "javascript", "code": "function(win, lose, args) {\n var id = args[0];\n var srcUri = processUri(args[1]);\n\n var dest = parseUriToPathAndFilename(srcUri);\n var destFileName = dest.fileName;\n\n var success = function () {\n Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_RUNNING);\n };\n\n var error = function (reason) {\n Media.onStatus(id, Media.MEDIA_ERROR, reason);\n };\n\n // Initialize device\n Media.prototype.mediaCaptureMgr = null;\n var thisM = (Media.get(id));\n var captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();\n captureInitSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.audio;\n thisM.mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();\n thisM.mediaCaptureMgr.addEventListener(\"failed\", error);\n\n thisM.mediaCaptureMgr.initializeAsync(captureInitSettings).done(function (result) {\n thisM.mediaCaptureMgr.addEventListener(\"recordlimitationexceeded\", error);\n thisM.mediaCaptureMgr.addEventListener(\"failed\", error);\n\n // Start recording\n Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync(destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(function (newFile) {\n recordedFile = newFile;\n var encodingProfile = null;\n switch (newFile.fileType) {\n case '.m4a':\n encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createM4a(Windows.Media.MediaProperties.AudioEncodingQuality.auto);\n break;\n case '.mp3':\n encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createMp3(Windows.Media.MediaProperties.AudioEncodingQuality.auto);\n break;\n case '.wma':\n encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createWma(Windows.Media.MediaProperties.AudioEncodingQuality.auto);\n break;\n default:\n error(\"Invalid file type for record\");\n break;\n }\n thisM.mediaCaptureMgr.startRecordToStorageFileAsync(encodingProfile, newFile).done(success, error);\n }, error);\n }, error);\n }", "code_tokens": ["function", "(", "win", ",", "lose", ",", "args", ")", "{", "var", "id", "=", "args", "[", "0", "]", ";", "var", "srcUri", "=", "processUri", "(", "args", "[", "1", "]", ")", ";", "var", "dest", "=", "parseUriToPathAndFilename", "(", "srcUri", ")", ";", "var", "destFileName", "=", "dest", ".", "fileName", ";", "var", "success", "=", "function", "(", ")", "{", "Media", ".", "onStatus", "(", "id", ",", "Media", ".", "MEDIA_STATE", ",", "Media", ".", "MEDIA_RUNNING", ")", ";", "}", ";", "var", "error", "=", "function", "(", "reason", ")", "{", "Media", ".", "onStatus", "(", "id", ",", "Media", ".", "MEDIA_ERROR", ",", "reason", ")", ";", "}", ";", "Media", ".", "prototype", ".", "mediaCaptureMgr", "=", "null", ";", "var", "thisM", "=", "(", "Media", ".", "get", "(", "id", ")", ")", ";", "var", "captureInitSettings", "=", "new", "Windows", ".", "Media", ".", "Capture", ".", "MediaCaptureInitializationSettings", "(", ")", ";", "captureInitSettings", ".", "streamingCaptureMode", "=", "Windows", ".", "Media", ".", "Capture", ".", "StreamingCaptureMode", ".", "audio", ";", "thisM", ".", "mediaCaptureMgr", "=", "new", "Windows", ".", "Media", ".", "Capture", ".", "MediaCapture", "(", ")", ";", "thisM", ".", "mediaCaptureMgr", ".", "addEventListener", "(", "\"failed\"", ",", "error", ")", ";", "thisM", ".", "mediaCaptureMgr", ".", "initializeAsync", "(", "captureInitSettings", ")", ".", "done", "(", "function", "(", "result", ")", "{", "thisM", ".", "mediaCaptureMgr", ".", "addEventListener", "(", "\"recordlimitationexceeded\"", ",", "error", ")", ";", "thisM", ".", "mediaCaptureMgr", ".", "addEventListener", "(", "\"failed\"", ",", "error", ")", ";", "Windows", ".", "Storage", ".", "ApplicationData", ".", "current", ".", "temporaryFolder", ".", "createFileAsync", "(", "destFileName", ",", "Windows", ".", "Storage", ".", "CreationCollisionOption", ".", "replaceExisting", ")", ".", "done", "(", "function", "(", "newFile", ")", "{", "recordedFile", "=", "newFile", ";", "var", "encodingProfile", "=", "null", ";", "switch", "(", "newFile", ".", "fileType", ")", "{", "case", "'.m4a'", ":", "encodingProfile", "=", "Windows", ".", "Media", ".", "MediaProperties", ".", "MediaEncodingProfile", ".", "createM4a", "(", "Windows", ".", "Media", ".", "MediaProperties", ".", "AudioEncodingQuality", ".", "auto", ")", ";", "break", ";", "case", "'.mp3'", ":", "encodingProfile", "=", "Windows", ".", "Media", ".", "MediaProperties", ".", "MediaEncodingProfile", ".", "createMp3", "(", "Windows", ".", "Media", ".", "MediaProperties", ".", "AudioEncodingQuality", ".", "auto", ")", ";", "break", ";", "case", "'.wma'", ":", "encodingProfile", "=", "Windows", ".", "Media", ".", "MediaProperties", ".", "MediaEncodingProfile", ".", "createWma", "(", "Windows", ".", "Media", ".", "MediaProperties", ".", "AudioEncodingQuality", ".", "auto", ")", ";", "break", ";", "default", ":", "error", "(", "\"Invalid file type for record\"", ")", ";", "break", ";", "}", "thisM", ".", "mediaCaptureMgr", ".", "startRecordToStorageFileAsync", "(", "encodingProfile", ",", "newFile", ")", ".", "done", "(", "success", ",", "error", ")", ";", "}", ",", "error", ")", ";", "}", ",", "error", ")", ";", "}"], "docstring": "Start recording audio", "docstring_tokens": ["Start", "recording", "audio"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/src/windows/MediaProxy.js#L182-L230", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "src/windows/MediaProxy.js", "func_name": "", "original_string": "function(win, lose, args) {\n var id = args[0];\n var thisM = Media.get(id);\n var srcUri = processUri(thisM.src);\n\n var dest = parseUriToPathAndFilename(srcUri);\n var destPath = dest.path;\n var destFileName = dest.fileName;\n var fsType = dest.fsType;\n\n var success = function () {\n Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);\n };\n\n var error = function (reason) {\n Media.onStatus(id, Media.MEDIA_ERROR, reason);\n };\n\n thisM.mediaCaptureMgr.stopRecordAsync().done(function () {\n if (fsType === fsTypes.TEMPORARY) {\n if (!destPath) {\n // if path is not defined, we leave recorded file in temporary folder (similar to iOS)\n success();\n } else {\n Windows.Storage.ApplicationData.current.temporaryFolder.getFolderAsync(destPath).done(function (destFolder) {\n recordedFile.copyAsync(destFolder, destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(success, error);\n }, error);\n }\n } else {\n // Copying file to persistent storage\n if (!destPath) {\n recordedFile.copyAsync(Windows.Storage.ApplicationData.current.localFolder, destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(success, error);\n } else {\n Windows.Storage.ApplicationData.current.localFolder.getFolderAsync(destPath).done(function (destFolder) {\n recordedFile.copyAsync(destFolder, destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(success, error);\n }, error);\n }\n }\n }, error);\n }", "language": "javascript", "code": "function(win, lose, args) {\n var id = args[0];\n var thisM = Media.get(id);\n var srcUri = processUri(thisM.src);\n\n var dest = parseUriToPathAndFilename(srcUri);\n var destPath = dest.path;\n var destFileName = dest.fileName;\n var fsType = dest.fsType;\n\n var success = function () {\n Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STOPPED);\n };\n\n var error = function (reason) {\n Media.onStatus(id, Media.MEDIA_ERROR, reason);\n };\n\n thisM.mediaCaptureMgr.stopRecordAsync().done(function () {\n if (fsType === fsTypes.TEMPORARY) {\n if (!destPath) {\n // if path is not defined, we leave recorded file in temporary folder (similar to iOS)\n success();\n } else {\n Windows.Storage.ApplicationData.current.temporaryFolder.getFolderAsync(destPath).done(function (destFolder) {\n recordedFile.copyAsync(destFolder, destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(success, error);\n }, error);\n }\n } else {\n // Copying file to persistent storage\n if (!destPath) {\n recordedFile.copyAsync(Windows.Storage.ApplicationData.current.localFolder, destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(success, error);\n } else {\n Windows.Storage.ApplicationData.current.localFolder.getFolderAsync(destPath).done(function (destFolder) {\n recordedFile.copyAsync(destFolder, destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(success, error);\n }, error);\n }\n }\n }, error);\n }", "code_tokens": ["function", "(", "win", ",", "lose", ",", "args", ")", "{", "var", "id", "=", "args", "[", "0", "]", ";", "var", "thisM", "=", "Media", ".", "get", "(", "id", ")", ";", "var", "srcUri", "=", "processUri", "(", "thisM", ".", "src", ")", ";", "var", "dest", "=", "parseUriToPathAndFilename", "(", "srcUri", ")", ";", "var", "destPath", "=", "dest", ".", "path", ";", "var", "destFileName", "=", "dest", ".", "fileName", ";", "var", "fsType", "=", "dest", ".", "fsType", ";", "var", "success", "=", "function", "(", ")", "{", "Media", ".", "onStatus", "(", "id", ",", "Media", ".", "MEDIA_STATE", ",", "Media", ".", "MEDIA_STOPPED", ")", ";", "}", ";", "var", "error", "=", "function", "(", "reason", ")", "{", "Media", ".", "onStatus", "(", "id", ",", "Media", ".", "MEDIA_ERROR", ",", "reason", ")", ";", "}", ";", "thisM", ".", "mediaCaptureMgr", ".", "stopRecordAsync", "(", ")", ".", "done", "(", "function", "(", ")", "{", "if", "(", "fsType", "===", "fsTypes", ".", "TEMPORARY", ")", "{", "if", "(", "!", "destPath", ")", "{", "success", "(", ")", ";", "}", "else", "{", "Windows", ".", "Storage", ".", "ApplicationData", ".", "current", ".", "temporaryFolder", ".", "getFolderAsync", "(", "destPath", ")", ".", "done", "(", "function", "(", "destFolder", ")", "{", "recordedFile", ".", "copyAsync", "(", "destFolder", ",", "destFileName", ",", "Windows", ".", "Storage", ".", "CreationCollisionOption", ".", "replaceExisting", ")", ".", "done", "(", "success", ",", "error", ")", ";", "}", ",", "error", ")", ";", "}", "}", "else", "{", "if", "(", "!", "destPath", ")", "{", "recordedFile", ".", "copyAsync", "(", "Windows", ".", "Storage", ".", "ApplicationData", ".", "current", ".", "localFolder", ",", "destFileName", ",", "Windows", ".", "Storage", ".", "CreationCollisionOption", ".", "replaceExisting", ")", ".", "done", "(", "success", ",", "error", ")", ";", "}", "else", "{", "Windows", ".", "Storage", ".", "ApplicationData", ".", "current", ".", "localFolder", ".", "getFolderAsync", "(", "destPath", ")", ".", "done", "(", "function", "(", "destFolder", ")", "{", "recordedFile", ".", "copyAsync", "(", "destFolder", ",", "destFileName", ",", "Windows", ".", "Storage", ".", "CreationCollisionOption", ".", "replaceExisting", ")", ".", "done", "(", "success", ",", "error", ")", ";", "}", ",", "error", ")", ";", "}", "}", "}", ",", "error", ")", ";", "}"], "docstring": "Stop recording audio", "docstring_tokens": ["Stop", "recording", "audio"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/src/windows/MediaProxy.js#L233-L272", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "src/windows/MediaProxy.js", "func_name": "", "original_string": "function(win, lose, args) {\n var id = args[0];\n var thisM = Media.get(id);\n try {\n if (thisM.node) {\n thisM.node.onloadedmetadata = null;\n // Unsubscribing as the media object is being released\n thisM.node.onerror = null;\n // Needed to avoid \"0x80070005 - JavaScript runtime error: Access is denied.\" on copyAsync\n thisM.node.src = null;\n delete thisM.node;\n }\n } catch (err) {\n lose(\"Failed to release: \"+err);\n }\n }", "language": "javascript", "code": "function(win, lose, args) {\n var id = args[0];\n var thisM = Media.get(id);\n try {\n if (thisM.node) {\n thisM.node.onloadedmetadata = null;\n // Unsubscribing as the media object is being released\n thisM.node.onerror = null;\n // Needed to avoid \"0x80070005 - JavaScript runtime error: Access is denied.\" on copyAsync\n thisM.node.src = null;\n delete thisM.node;\n }\n } catch (err) {\n lose(\"Failed to release: \"+err);\n }\n }", "code_tokens": ["function", "(", "win", ",", "lose", ",", "args", ")", "{", "var", "id", "=", "args", "[", "0", "]", ";", "var", "thisM", "=", "Media", ".", "get", "(", "id", ")", ";", "try", "{", "if", "(", "thisM", ".", "node", ")", "{", "thisM", ".", "node", ".", "onloadedmetadata", "=", "null", ";", "thisM", ".", "node", ".", "onerror", "=", "null", ";", "thisM", ".", "node", ".", "src", "=", "null", ";", "delete", "thisM", ".", "node", ";", "}", "}", "catch", "(", "err", ")", "{", "lose", "(", "\"Failed to release: \"", "+", "err", ")", ";", "}", "}"], "docstring": "Release the media object", "docstring_tokens": ["Release", "the", "media", "object"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/src/windows/MediaProxy.js#L275-L290", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "src/windows/MediaProxy.js", "func_name": "fullPathToAppData", "original_string": "function fullPathToAppData(uri) {\n if (uri.schemeName === 'file') {\n if (uri.rawUri.indexOf(Windows.Storage.ApplicationData.current.localFolder.path) !== -1) {\n // Also remove path' beginning slash to avoid losing folder name part\n uri = new Windows.Foundation.Uri(localFolderAppDataBasePath, uri.rawUri.replace(localFolderFullPath, '').replace(/^[\\\\\\/]{1,2}/, ''));\n } else if (uri.rawUri.indexOf(Windows.Storage.ApplicationData.current.temporaryFolder.path) !== -1) {\n uri = new Windows.Foundation.Uri(tempFolderAppDataBasePath, uri.rawUri.replace(tempFolderFullPath, '').replace(/^[\\\\\\/]{1,2}/, ''));\n } else {\n throw new Error('Not supported file uri: ' + uri.rawUri);\n }\n }\n\n return uri;\n}", "language": "javascript", "code": "function fullPathToAppData(uri) {\n if (uri.schemeName === 'file') {\n if (uri.rawUri.indexOf(Windows.Storage.ApplicationData.current.localFolder.path) !== -1) {\n // Also remove path' beginning slash to avoid losing folder name part\n uri = new Windows.Foundation.Uri(localFolderAppDataBasePath, uri.rawUri.replace(localFolderFullPath, '').replace(/^[\\\\\\/]{1,2}/, ''));\n } else if (uri.rawUri.indexOf(Windows.Storage.ApplicationData.current.temporaryFolder.path) !== -1) {\n uri = new Windows.Foundation.Uri(tempFolderAppDataBasePath, uri.rawUri.replace(tempFolderFullPath, '').replace(/^[\\\\\\/]{1,2}/, ''));\n } else {\n throw new Error('Not supported file uri: ' + uri.rawUri);\n }\n }\n\n return uri;\n}", "code_tokens": ["function", "fullPathToAppData", "(", "uri", ")", "{", "if", "(", "uri", ".", "schemeName", "===", "'file'", ")", "{", "if", "(", "uri", ".", "rawUri", ".", "indexOf", "(", "Windows", ".", "Storage", ".", "ApplicationData", ".", "current", ".", "localFolder", ".", "path", ")", "!==", "-", "1", ")", "{", "uri", "=", "new", "Windows", ".", "Foundation", ".", "Uri", "(", "localFolderAppDataBasePath", ",", "uri", ".", "rawUri", ".", "replace", "(", "localFolderFullPath", ",", "''", ")", ".", "replace", "(", "/", "^[\\\\\\/]{1,2}", "/", ",", "''", ")", ")", ";", "}", "else", "if", "(", "uri", ".", "rawUri", ".", "indexOf", "(", "Windows", ".", "Storage", ".", "ApplicationData", ".", "current", ".", "temporaryFolder", ".", "path", ")", "!==", "-", "1", ")", "{", "uri", "=", "new", "Windows", ".", "Foundation", ".", "Uri", "(", "tempFolderAppDataBasePath", ",", "uri", ".", "rawUri", ".", "replace", "(", "tempFolderFullPath", ",", "''", ")", ".", "replace", "(", "/", "^[\\\\\\/]{1,2}", "/", ",", "''", ")", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Not supported file uri: '", "+", "uri", ".", "rawUri", ")", ";", "}", "}", "return", "uri", ";", "}"], "docstring": "Convert native full path to ms-appdata path\n@param {Object} uri Windows.Foundation.Uri\n@return {Object} ms-appdata Windows.Foundation.Uri", "docstring_tokens": ["Convert", "native", "full", "path", "to", "ms", "-", "appdata", "path"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/src/windows/MediaProxy.js#L326-L339", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "src/windows/MediaProxy.js", "func_name": "cdvfileToAppData", "original_string": "function cdvfileToAppData(uri) {\n var cdvFsRoot;\n\n if (uri.schemeName === 'cdvfile') {\n cdvFsRoot = uri.path.split('/')[1];\n if (cdvFsRoot === 'temporary') {\n return new Windows.Foundation.Uri(tempFolderAppDataBasePath, uri.path.split('/').slice(2).join('/'));\n } else if (cdvFsRoot === 'persistent') {\n return new Windows.Foundation.Uri(localFolderAppDataBasePath, uri.path.split('/').slice(2).join('/'));\n } else {\n throw new Error(cdvFsRoot + ' cdvfile root is not supported on Windows');\n }\n }\n\n return uri;\n}", "language": "javascript", "code": "function cdvfileToAppData(uri) {\n var cdvFsRoot;\n\n if (uri.schemeName === 'cdvfile') {\n cdvFsRoot = uri.path.split('/')[1];\n if (cdvFsRoot === 'temporary') {\n return new Windows.Foundation.Uri(tempFolderAppDataBasePath, uri.path.split('/').slice(2).join('/'));\n } else if (cdvFsRoot === 'persistent') {\n return new Windows.Foundation.Uri(localFolderAppDataBasePath, uri.path.split('/').slice(2).join('/'));\n } else {\n throw new Error(cdvFsRoot + ' cdvfile root is not supported on Windows');\n }\n }\n\n return uri;\n}", "code_tokens": ["function", "cdvfileToAppData", "(", "uri", ")", "{", "var", "cdvFsRoot", ";", "if", "(", "uri", ".", "schemeName", "===", "'cdvfile'", ")", "{", "cdvFsRoot", "=", "uri", ".", "path", ".", "split", "(", "'/'", ")", "[", "1", "]", ";", "if", "(", "cdvFsRoot", "===", "'temporary'", ")", "{", "return", "new", "Windows", ".", "Foundation", ".", "Uri", "(", "tempFolderAppDataBasePath", ",", "uri", ".", "path", ".", "split", "(", "'/'", ")", ".", "slice", "(", "2", ")", ".", "join", "(", "'/'", ")", ")", ";", "}", "else", "if", "(", "cdvFsRoot", "===", "'persistent'", ")", "{", "return", "new", "Windows", ".", "Foundation", ".", "Uri", "(", "localFolderAppDataBasePath", ",", "uri", ".", "path", ".", "split", "(", "'/'", ")", ".", "slice", "(", "2", ")", ".", "join", "(", "'/'", ")", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "cdvFsRoot", "+", "' cdvfile root is not supported on Windows'", ")", ";", "}", "}", "return", "uri", ";", "}"], "docstring": "Converts cdvfile paths to ms-appdata path\n@param {Object} uri Input cdvfile scheme Windows.Foundation.Uri\n@return {Object} Windows.Foundation.Uri based on App data path", "docstring_tokens": ["Converts", "cdvfile", "paths", "to", "ms", "-", "appdata", "path"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/src/windows/MediaProxy.js#L346-L361", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "src/windows/MediaProxy.js", "func_name": "processUri", "original_string": "function processUri(src) {\n // Collapse double slashes (File plugin issue): ms-appdata:///temp//recs/memos/media.m4a => ms-appdata:///temp/recs/memos/media.m4a\n src = src.replace(/([^\\/:])(\\/\\/)([^\\/])/g, '$1/$3');\n\n // Remove beginning slashes\n src = src.replace(/^[\\\\\\/]{1,2}/, '');\n\n var uri = setTemporaryFsByDefault(src);\n\n uri = fullPathToAppData(uri);\n uri = cdvfileToAppData(uri);\n\n return uri;\n}", "language": "javascript", "code": "function processUri(src) {\n // Collapse double slashes (File plugin issue): ms-appdata:///temp//recs/memos/media.m4a => ms-appdata:///temp/recs/memos/media.m4a\n src = src.replace(/([^\\/:])(\\/\\/)([^\\/])/g, '$1/$3');\n\n // Remove beginning slashes\n src = src.replace(/^[\\\\\\/]{1,2}/, '');\n\n var uri = setTemporaryFsByDefault(src);\n\n uri = fullPathToAppData(uri);\n uri = cdvfileToAppData(uri);\n\n return uri;\n}", "code_tokens": ["function", "processUri", "(", "src", ")", "{", "src", "=", "src", ".", "replace", "(", "/", "([^\\/:])(\\/\\/)([^\\/])", "/", "g", ",", "'$1/$3'", ")", ";", "src", "=", "src", ".", "replace", "(", "/", "^[\\\\\\/]{1,2}", "/", ",", "''", ")", ";", "var", "uri", "=", "setTemporaryFsByDefault", "(", "src", ")", ";", "uri", "=", "fullPathToAppData", "(", "uri", ")", ";", "uri", "=", "cdvfileToAppData", "(", "uri", ")", ";", "return", "uri", ";", "}"], "docstring": "Prepares media src for internal usage\n@param {String} src Input media path\n@return {Object} Windows.Foundation.Uri", "docstring_tokens": ["Prepares", "media", "src", "for", "internal", "usage"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/src/windows/MediaProxy.js#L368-L381", "partition": "test"} {"repo": "apache/cordova-plugin-media", "path": "src/windows/MediaProxy.js", "func_name": "parseUriToPathAndFilename", "original_string": "function parseUriToPathAndFilename(uri) {\n // Removing scheme and location, using backslashes: ms-appdata:///local/path/to/file.m4a -> path\\\\to\\\\file.m4a\n var normalizedSrc = uri.path.split('/').slice(2).join('\\\\');\n\n var path = normalizedSrc.substr(0, normalizedSrc.lastIndexOf('\\\\'));\n var fileName = normalizedSrc.replace(path + '\\\\', '');\n\n var fsType;\n\n if (uri.path.split('/')[1] === 'local') {\n fsType = fsTypes.PERSISTENT;\n } else if (uri.path.split('/')[1] === 'temp') {\n fsType = fsTypes.TEMPORARY;\n }\n\n return {\n path: path,\n fileName: fileName,\n fsType: fsType\n };\n}", "language": "javascript", "code": "function parseUriToPathAndFilename(uri) {\n // Removing scheme and location, using backslashes: ms-appdata:///local/path/to/file.m4a -> path\\\\to\\\\file.m4a\n var normalizedSrc = uri.path.split('/').slice(2).join('\\\\');\n\n var path = normalizedSrc.substr(0, normalizedSrc.lastIndexOf('\\\\'));\n var fileName = normalizedSrc.replace(path + '\\\\', '');\n\n var fsType;\n\n if (uri.path.split('/')[1] === 'local') {\n fsType = fsTypes.PERSISTENT;\n } else if (uri.path.split('/')[1] === 'temp') {\n fsType = fsTypes.TEMPORARY;\n }\n\n return {\n path: path,\n fileName: fileName,\n fsType: fsType\n };\n}", "code_tokens": ["function", "parseUriToPathAndFilename", "(", "uri", ")", "{", "var", "normalizedSrc", "=", "uri", ".", "path", ".", "split", "(", "'/'", ")", ".", "slice", "(", "2", ")", ".", "join", "(", "'\\\\'", ")", ";", "\\\\", "var", "path", "=", "normalizedSrc", ".", "substr", "(", "0", ",", "normalizedSrc", ".", "lastIndexOf", "(", "'\\\\'", ")", ")", ";", "\\\\", "var", "fileName", "=", "normalizedSrc", ".", "replace", "(", "path", "+", "'\\\\'", ",", "\\\\", ")", ";", "''", "}"], "docstring": "Extracts path, filename and filesystem type from Uri\n@param {Object} uri Windows.Foundation.Uri\n@return {Object} Object containing path, filename and filesystem type", "docstring_tokens": ["Extracts", "path", "filename", "and", "filesystem", "type", "from", "Uri"], "sha": "b1c135342619f773fee3e8693a46992a133efd56", "url": "https://github.com/apache/cordova-plugin-media/blob/b1c135342619f773fee3e8693a46992a133efd56/src/windows/MediaProxy.js#L388-L408", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/hooks/Context.js", "func_name": "Context", "original_string": "function Context (hook, opts) {\n this.hook = hook;\n\n // create new object, to avoid affecting input opts in other places\n // For example context.opts.plugin = Object is done, then it affects by reference\n this.opts = Object.assign({}, opts);\n this.cmdLine = process.argv.join(' ');\n\n // Lazy-load cordova to avoid cyclical dependency\n Object.defineProperty(this, 'cordova', {\n get () { return this.requireCordovaModule('cordova-lib').cordova; }\n });\n}", "language": "javascript", "code": "function Context (hook, opts) {\n this.hook = hook;\n\n // create new object, to avoid affecting input opts in other places\n // For example context.opts.plugin = Object is done, then it affects by reference\n this.opts = Object.assign({}, opts);\n this.cmdLine = process.argv.join(' ');\n\n // Lazy-load cordova to avoid cyclical dependency\n Object.defineProperty(this, 'cordova', {\n get () { return this.requireCordovaModule('cordova-lib').cordova; }\n });\n}", "code_tokens": ["function", "Context", "(", "hook", ",", "opts", ")", "{", "this", ".", "hook", "=", "hook", ";", "this", ".", "opts", "=", "Object", ".", "assign", "(", "{", "}", ",", "opts", ")", ";", "this", ".", "cmdLine", "=", "process", ".", "argv", ".", "join", "(", "' '", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'cordova'", ",", "{", "get", "(", ")", "{", "return", "this", ".", "requireCordovaModule", "(", "'cordova-lib'", ")", ".", "cordova", ";", "}", "}", ")", ";", "}"], "docstring": "Creates hook script context\n@constructor\n@param {String} hook The hook type\n@param {Object} opts Hook options\n@returns {Object}", "docstring_tokens": ["Creates", "hook", "script", "context"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/hooks/Context.js#L29-L41", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/cordova/fixtures/projects/platformApi/platforms/windows/cordova/lib/ConfigChanges.js", "func_name": "getUniqueCapabilities", "original_string": "function getUniqueCapabilities(capabilities) {\n return capabilities.reduce(function(uniqueCaps, currCap) {\n\n var isRepeated = uniqueCaps.some(function(cap) {\n return getCapabilityName(cap) === getCapabilityName(currCap);\n });\n\n return isRepeated ? uniqueCaps : uniqueCaps.concat([currCap]);\n }, []);\n}", "language": "javascript", "code": "function getUniqueCapabilities(capabilities) {\n return capabilities.reduce(function(uniqueCaps, currCap) {\n\n var isRepeated = uniqueCaps.some(function(cap) {\n return getCapabilityName(cap) === getCapabilityName(currCap);\n });\n\n return isRepeated ? uniqueCaps : uniqueCaps.concat([currCap]);\n }, []);\n}", "code_tokens": ["function", "getUniqueCapabilities", "(", "capabilities", ")", "{", "return", "capabilities", ".", "reduce", "(", "function", "(", "uniqueCaps", ",", "currCap", ")", "{", "var", "isRepeated", "=", "uniqueCaps", ".", "some", "(", "function", "(", "cap", ")", "{", "return", "getCapabilityName", "(", "cap", ")", "===", "getCapabilityName", "(", "currCap", ")", ";", "}", ")", ";", "return", "isRepeated", "?", "uniqueCaps", ":", "uniqueCaps", ".", "concat", "(", "[", "currCap", "]", ")", ";", "}", ",", "[", "]", ")", ";", "}"], "docstring": "Remove capabilities with same names\n@param {Object} an array of capabilities\n@return {Object} an unique array of capabilities", "docstring_tokens": ["Remove", "capabilities", "with", "same", "names"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/cordova/fixtures/projects/platformApi/platforms/windows/cordova/lib/ConfigChanges.js#L94-L103", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/cordova/fixtures/projects/platformApi/platforms/windows/cordova/lib/ConfigChanges.js", "func_name": "compareCapabilities", "original_string": "function compareCapabilities(firstCap, secondCap) {\n var firstCapName = getCapabilityName(firstCap);\n var secondCapName = getCapabilityName(secondCap);\n\n if (firstCapName < secondCapName) {\n return -1;\n }\n\n if (firstCapName > secondCapName) {\n return 1;\n }\n\n return 0;\n}", "language": "javascript", "code": "function compareCapabilities(firstCap, secondCap) {\n var firstCapName = getCapabilityName(firstCap);\n var secondCapName = getCapabilityName(secondCap);\n\n if (firstCapName < secondCapName) {\n return -1;\n }\n\n if (firstCapName > secondCapName) {\n return 1;\n }\n\n return 0;\n}", "code_tokens": ["function", "compareCapabilities", "(", "firstCap", ",", "secondCap", ")", "{", "var", "firstCapName", "=", "getCapabilityName", "(", "firstCap", ")", ";", "var", "secondCapName", "=", "getCapabilityName", "(", "secondCap", ")", ";", "if", "(", "firstCapName", "<", "secondCapName", ")", "{", "return", "-", "1", ";", "}", "if", "(", "firstCapName", ">", "secondCapName", ")", "{", "return", "1", ";", "}", "return", "0", ";", "}"], "docstring": "Comparator function to pass to Array.sort\n@param {Object} firstCap first capability\n@param {Object} secondCap second capability\n@return {Number} either -1, 0 or 1", "docstring_tokens": ["Comparator", "function", "to", "pass", "to", "Array", ".", "sort"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/cordova/fixtures/projects/platformApi/platforms/windows/cordova/lib/ConfigChanges.js#L111-L124", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/util.js", "func_name": "isCordova", "original_string": "function isCordova (dir) {\n if (!dir) {\n // Prefer PWD over cwd so that symlinked dirs within your PWD work correctly (CB-5687).\n var pwd = process.env.PWD;\n var cwd = process.cwd();\n if (pwd && pwd !== cwd && pwd !== 'undefined') {\n return this.isCordova(pwd) || this.isCordova(cwd);\n }\n return this.isCordova(cwd);\n }\n var bestReturnValueSoFar = false;\n for (var i = 0; i < 1000; ++i) {\n var result = isRootDir(dir);\n if (result === 2) {\n return dir;\n }\n if (result === 1) {\n bestReturnValueSoFar = dir;\n }\n var parentDir = path.normalize(path.join(dir, '..'));\n // Detect fs root.\n if (parentDir === dir) {\n return bestReturnValueSoFar;\n }\n dir = parentDir;\n }\n console.error('Hit an unhandled case in util.isCordova');\n return false;\n}", "language": "javascript", "code": "function isCordova (dir) {\n if (!dir) {\n // Prefer PWD over cwd so that symlinked dirs within your PWD work correctly (CB-5687).\n var pwd = process.env.PWD;\n var cwd = process.cwd();\n if (pwd && pwd !== cwd && pwd !== 'undefined') {\n return this.isCordova(pwd) || this.isCordova(cwd);\n }\n return this.isCordova(cwd);\n }\n var bestReturnValueSoFar = false;\n for (var i = 0; i < 1000; ++i) {\n var result = isRootDir(dir);\n if (result === 2) {\n return dir;\n }\n if (result === 1) {\n bestReturnValueSoFar = dir;\n }\n var parentDir = path.normalize(path.join(dir, '..'));\n // Detect fs root.\n if (parentDir === dir) {\n return bestReturnValueSoFar;\n }\n dir = parentDir;\n }\n console.error('Hit an unhandled case in util.isCordova');\n return false;\n}", "code_tokens": ["function", "isCordova", "(", "dir", ")", "{", "if", "(", "!", "dir", ")", "{", "var", "pwd", "=", "process", ".", "env", ".", "PWD", ";", "var", "cwd", "=", "process", ".", "cwd", "(", ")", ";", "if", "(", "pwd", "&&", "pwd", "!==", "cwd", "&&", "pwd", "!==", "'undefined'", ")", "{", "return", "this", ".", "isCordova", "(", "pwd", ")", "||", "this", ".", "isCordova", "(", "cwd", ")", ";", "}", "return", "this", ".", "isCordova", "(", "cwd", ")", ";", "}", "var", "bestReturnValueSoFar", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "1000", ";", "++", "i", ")", "{", "var", "result", "=", "isRootDir", "(", "dir", ")", ";", "if", "(", "result", "===", "2", ")", "{", "return", "dir", ";", "}", "if", "(", "result", "===", "1", ")", "{", "bestReturnValueSoFar", "=", "dir", ";", "}", "var", "parentDir", "=", "path", ".", "normalize", "(", "path", ".", "join", "(", "dir", ",", "'..'", ")", ")", ";", "if", "(", "parentDir", "===", "dir", ")", "{", "return", "bestReturnValueSoFar", ";", "}", "dir", "=", "parentDir", ";", "}", "console", ".", "error", "(", "'Hit an unhandled case in util.isCordova'", ")", ";", "return", "false", ";", "}"], "docstring": "Runs up the directory chain looking for a .cordova directory. IF it is found we are in a Cordova project. Omit argument to use CWD.", "docstring_tokens": ["Runs", "up", "the", "directory", "chain", "looking", "for", "a", ".", "cordova", "directory", ".", "IF", "it", "is", "found", "we", "are", "in", "a", "Cordova", "project", ".", "Omit", "argument", "to", "use", "CWD", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/util.js#L125-L153", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/util.js", "func_name": "cdProjectRoot", "original_string": "function cdProjectRoot () {\n const projectRoot = this.getProjectRoot();\n if (!origCwd) {\n origCwd = process.env.PWD || process.cwd();\n }\n process.env.PWD = projectRoot;\n process.chdir(projectRoot);\n return projectRoot;\n}", "language": "javascript", "code": "function cdProjectRoot () {\n const projectRoot = this.getProjectRoot();\n if (!origCwd) {\n origCwd = process.env.PWD || process.cwd();\n }\n process.env.PWD = projectRoot;\n process.chdir(projectRoot);\n return projectRoot;\n}", "code_tokens": ["function", "cdProjectRoot", "(", ")", "{", "const", "projectRoot", "=", "this", ".", "getProjectRoot", "(", ")", ";", "if", "(", "!", "origCwd", ")", "{", "origCwd", "=", "process", ".", "env", ".", "PWD", "||", "process", ".", "cwd", "(", ")", ";", "}", "process", ".", "env", ".", "PWD", "=", "projectRoot", ";", "process", ".", "chdir", "(", "projectRoot", ")", ";", "return", "projectRoot", ";", "}"], "docstring": "Cd to project root dir and return its path. Throw CordovaError if not in a Corodva project.", "docstring_tokens": ["Cd", "to", "project", "root", "dir", "and", "return", "its", "path", ".", "Throw", "CordovaError", "if", "not", "in", "a", "Corodva", "project", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/util.js#L171-L179", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/util.js", "func_name": "deleteSvnFolders", "original_string": "function deleteSvnFolders (dir) {\n var contents = fs.readdirSync(dir);\n contents.forEach(function (entry) {\n var fullpath = path.join(dir, entry);\n if (isDirectory(fullpath)) {\n if (entry === '.svn') {\n fs.removeSync(fullpath);\n } else module.exports.deleteSvnFolders(fullpath);\n }\n });\n}", "language": "javascript", "code": "function deleteSvnFolders (dir) {\n var contents = fs.readdirSync(dir);\n contents.forEach(function (entry) {\n var fullpath = path.join(dir, entry);\n if (isDirectory(fullpath)) {\n if (entry === '.svn') {\n fs.removeSync(fullpath);\n } else module.exports.deleteSvnFolders(fullpath);\n }\n });\n}", "code_tokens": ["function", "deleteSvnFolders", "(", "dir", ")", "{", "var", "contents", "=", "fs", ".", "readdirSync", "(", "dir", ")", ";", "contents", ".", "forEach", "(", "function", "(", "entry", ")", "{", "var", "fullpath", "=", "path", ".", "join", "(", "dir", ",", "entry", ")", ";", "if", "(", "isDirectory", "(", "fullpath", ")", ")", "{", "if", "(", "entry", "===", "'.svn'", ")", "{", "fs", ".", "removeSync", "(", "fullpath", ")", ";", "}", "else", "module", ".", "exports", ".", "deleteSvnFolders", "(", "fullpath", ")", ";", "}", "}", ")", ";", "}"], "docstring": "Recursively deletes .svn folders from a target path", "docstring_tokens": ["Recursively", "deletes", ".", "svn", "folders", "from", "a", "target", "path"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/util.js#L212-L222", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/util.js", "func_name": "findPlugins", "original_string": "function findPlugins (pluginDir) {\n var plugins = [];\n\n if (fs.existsSync(pluginDir)) {\n plugins = fs.readdirSync(pluginDir).filter(function (fileName) {\n var pluginPath = path.join(pluginDir, fileName);\n var isPlugin = isDirectory(pluginPath) || isSymbolicLink(pluginPath);\n return fileName !== '.svn' && fileName !== 'CVS' && isPlugin;\n });\n }\n\n return plugins;\n}", "language": "javascript", "code": "function findPlugins (pluginDir) {\n var plugins = [];\n\n if (fs.existsSync(pluginDir)) {\n plugins = fs.readdirSync(pluginDir).filter(function (fileName) {\n var pluginPath = path.join(pluginDir, fileName);\n var isPlugin = isDirectory(pluginPath) || isSymbolicLink(pluginPath);\n return fileName !== '.svn' && fileName !== 'CVS' && isPlugin;\n });\n }\n\n return plugins;\n}", "code_tokens": ["function", "findPlugins", "(", "pluginDir", ")", "{", "var", "plugins", "=", "[", "]", ";", "if", "(", "fs", ".", "existsSync", "(", "pluginDir", ")", ")", "{", "plugins", "=", "fs", ".", "readdirSync", "(", "pluginDir", ")", ".", "filter", "(", "function", "(", "fileName", ")", "{", "var", "pluginPath", "=", "path", ".", "join", "(", "pluginDir", ",", "fileName", ")", ";", "var", "isPlugin", "=", "isDirectory", "(", "pluginPath", ")", "||", "isSymbolicLink", "(", "pluginPath", ")", ";", "return", "fileName", "!==", "'.svn'", "&&", "fileName", "!==", "'CVS'", "&&", "isPlugin", ";", "}", ")", ";", "}", "return", "plugins", ";", "}"], "docstring": "list the directories in the path, ignoring any files", "docstring_tokens": ["list", "the", "directories", "in", "the", "path", "ignoring", "any", "files"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/util.js#L255-L267", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/hooks/HooksRunner.js", "func_name": "HooksRunner", "original_string": "function HooksRunner (projectRoot) {\n var root = cordovaUtil.isCordova(projectRoot);\n if (!root) throw new CordovaError('Not a Cordova project (\"' + projectRoot + '\"), can\\'t use hooks.');\n else this.projectRoot = root;\n}", "language": "javascript", "code": "function HooksRunner (projectRoot) {\n var root = cordovaUtil.isCordova(projectRoot);\n if (!root) throw new CordovaError('Not a Cordova project (\"' + projectRoot + '\"), can\\'t use hooks.');\n else this.projectRoot = root;\n}", "code_tokens": ["function", "HooksRunner", "(", "projectRoot", ")", "{", "var", "root", "=", "cordovaUtil", ".", "isCordova", "(", "projectRoot", ")", ";", "if", "(", "!", "root", ")", "throw", "new", "CordovaError", "(", "'Not a Cordova project (\"'", "+", "projectRoot", "+", "'\"), can\\'t use hooks.'", ")", ";", "else", "\\'", "}"], "docstring": "Tries to create a HooksRunner for passed project root.\n@constructor", "docstring_tokens": ["Tries", "to", "create", "a", "HooksRunner", "for", "passed", "project", "root", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/hooks/HooksRunner.js#L35-L39", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/hooks/HooksRunner.js", "func_name": "extractSheBangInterpreter", "original_string": "function extractSheBangInterpreter (fullpath) {\n // this is a modern cluster size. no need to read less\n const chunkSize = 4096;\n const fileData = readChunk.sync(fullpath, 0, chunkSize);\n const fileChunk = fileData.toString();\n const hookCmd = shebangCommand(fileChunk);\n\n if (hookCmd && fileData.length === chunkSize && !fileChunk.match(/[\\r\\n]/)) {\n events.emit('warn', 'shebang is too long for \"' + fullpath + '\"');\n }\n return hookCmd;\n}", "language": "javascript", "code": "function extractSheBangInterpreter (fullpath) {\n // this is a modern cluster size. no need to read less\n const chunkSize = 4096;\n const fileData = readChunk.sync(fullpath, 0, chunkSize);\n const fileChunk = fileData.toString();\n const hookCmd = shebangCommand(fileChunk);\n\n if (hookCmd && fileData.length === chunkSize && !fileChunk.match(/[\\r\\n]/)) {\n events.emit('warn', 'shebang is too long for \"' + fullpath + '\"');\n }\n return hookCmd;\n}", "code_tokens": ["function", "extractSheBangInterpreter", "(", "fullpath", ")", "{", "const", "chunkSize", "=", "4096", ";", "const", "fileData", "=", "readChunk", ".", "sync", "(", "fullpath", ",", "0", ",", "chunkSize", ")", ";", "const", "fileChunk", "=", "fileData", ".", "toString", "(", ")", ";", "const", "hookCmd", "=", "shebangCommand", "(", "fileChunk", ")", ";", "if", "(", "hookCmd", "&&", "fileData", ".", "length", "===", "chunkSize", "&&", "!", "fileChunk", ".", "match", "(", "/", "[\\r\\n]", "/", ")", ")", "{", "events", ".", "emit", "(", "'warn'", ",", "'shebang is too long for \"'", "+", "fullpath", "+", "'\"'", ")", ";", "}", "return", "hookCmd", ";", "}"], "docstring": "Extracts shebang interpreter from script' source.", "docstring_tokens": ["Extracts", "shebang", "interpreter", "from", "script", "source", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/hooks/HooksRunner.js#L231-L242", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/hooks/HooksRunner.js", "func_name": "isHookDisabled", "original_string": "function isHookDisabled (opts, hook) {\n if (opts === undefined || opts.nohooks === undefined) {\n return false;\n }\n var disabledHooks = opts.nohooks;\n var length = disabledHooks.length;\n for (var i = 0; i < length; i++) {\n if (hook.match(disabledHooks[i]) !== null) {\n return true;\n }\n }\n return false;\n}", "language": "javascript", "code": "function isHookDisabled (opts, hook) {\n if (opts === undefined || opts.nohooks === undefined) {\n return false;\n }\n var disabledHooks = opts.nohooks;\n var length = disabledHooks.length;\n for (var i = 0; i < length; i++) {\n if (hook.match(disabledHooks[i]) !== null) {\n return true;\n }\n }\n return false;\n}", "code_tokens": ["function", "isHookDisabled", "(", "opts", ",", "hook", ")", "{", "if", "(", "opts", "===", "undefined", "||", "opts", ".", "nohooks", "===", "undefined", ")", "{", "return", "false", ";", "}", "var", "disabledHooks", "=", "opts", ".", "nohooks", ";", "var", "length", "=", "disabledHooks", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "hook", ".", "match", "(", "disabledHooks", "[", "i", "]", ")", "!==", "null", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}"], "docstring": "Checks if the given hook type is disabled at the command line option.\n@param {Object} opts - the option object that contains command line options\n@param {String} hook - the hook type\n@returns {Boolean} return true if the passed hook is disabled.", "docstring_tokens": ["Checks", "if", "the", "given", "hook", "type", "is", "disabled", "at", "the", "command", "line", "option", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/hooks/HooksRunner.js#L250-L262", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/cordova/fixtures/platforms/cordova-browser/cordova-js-src/platform.js", "func_name": "", "original_string": "function() {\n\n var modulemapper = require('cordova/modulemapper');\n var channel = require('cordova/channel');\n\n modulemapper.clobbers('cordova/exec/proxy', 'cordova.commandProxy');\n\n channel.onNativeReady.fire();\n\n document.addEventListener(\"visibilitychange\", function(){\n if(document.hidden) {\n channel.onPause.fire();\n }\n else {\n channel.onResume.fire();\n }\n });\n\n // End of bootstrap\n }", "language": "javascript", "code": "function() {\n\n var modulemapper = require('cordova/modulemapper');\n var channel = require('cordova/channel');\n\n modulemapper.clobbers('cordova/exec/proxy', 'cordova.commandProxy');\n\n channel.onNativeReady.fire();\n\n document.addEventListener(\"visibilitychange\", function(){\n if(document.hidden) {\n channel.onPause.fire();\n }\n else {\n channel.onResume.fire();\n }\n });\n\n // End of bootstrap\n }", "code_tokens": ["function", "(", ")", "{", "var", "modulemapper", "=", "require", "(", "'cordova/modulemapper'", ")", ";", "var", "channel", "=", "require", "(", "'cordova/channel'", ")", ";", "modulemapper", ".", "clobbers", "(", "'cordova/exec/proxy'", ",", "'cordova.commandProxy'", ")", ";", "channel", ".", "onNativeReady", ".", "fire", "(", ")", ";", "document", ".", "addEventListener", "(", "\"visibilitychange\"", ",", "function", "(", ")", "{", "if", "(", "document", ".", "hidden", ")", "{", "channel", ".", "onPause", ".", "fire", "(", ")", ";", "}", "else", "{", "channel", ".", "onResume", ".", "fire", "(", ")", ";", "}", "}", ")", ";", "}"], "docstring": "cordova-js", "docstring_tokens": ["cordova", "-", "js"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/cordova/fixtures/platforms/cordova-browser/cordova-js-src/platform.js#L26-L45", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/hooks/scriptsFinder.js", "func_name": "", "original_string": "function (hook, opts) {\n // args check\n if (!hook) {\n throw new Error('hook type is not specified');\n }\n return getApplicationHookScripts(hook, opts)\n .concat(getPluginsHookScripts(hook, opts));\n }", "language": "javascript", "code": "function (hook, opts) {\n // args check\n if (!hook) {\n throw new Error('hook type is not specified');\n }\n return getApplicationHookScripts(hook, opts)\n .concat(getPluginsHookScripts(hook, opts));\n }", "code_tokens": ["function", "(", "hook", ",", "opts", ")", "{", "if", "(", "!", "hook", ")", "{", "throw", "new", "Error", "(", "'hook type is not specified'", ")", ";", "}", "return", "getApplicationHookScripts", "(", "hook", ",", "opts", ")", ".", "concat", "(", "getPluginsHookScripts", "(", "hook", ",", "opts", ")", ")", ";", "}"], "docstring": "Returns all script files for the hook type specified.", "docstring_tokens": ["Returns", "all", "script", "files", "for", "the", "hook", "type", "specified", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/hooks/scriptsFinder.js#L35-L42", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/hooks/scriptsFinder.js", "func_name": "getPluginsHookScripts", "original_string": "function getPluginsHookScripts (hook, opts) {\n // args check\n if (!hook) {\n throw new Error('hook type is not specified');\n }\n\n // In case before_plugin_install, after_plugin_install, before_plugin_uninstall hooks we receive opts.plugin and\n // retrieve scripts exclusive for this plugin.\n if (opts.plugin) {\n events.emit('verbose', 'Finding scripts for \"' + hook + '\" hook from plugin ' + opts.plugin.id + ' on ' + opts.plugin.platform + ' platform only.');\n // if plugin hook is not run for specific platform then use all available platforms\n return getPluginScriptFiles(opts.plugin, hook, opts.plugin.platform ? [opts.plugin.platform] : opts.cordova.platforms);\n }\n\n return getAllPluginsHookScriptFiles(hook, opts);\n}", "language": "javascript", "code": "function getPluginsHookScripts (hook, opts) {\n // args check\n if (!hook) {\n throw new Error('hook type is not specified');\n }\n\n // In case before_plugin_install, after_plugin_install, before_plugin_uninstall hooks we receive opts.plugin and\n // retrieve scripts exclusive for this plugin.\n if (opts.plugin) {\n events.emit('verbose', 'Finding scripts for \"' + hook + '\" hook from plugin ' + opts.plugin.id + ' on ' + opts.plugin.platform + ' platform only.');\n // if plugin hook is not run for specific platform then use all available platforms\n return getPluginScriptFiles(opts.plugin, hook, opts.plugin.platform ? [opts.plugin.platform] : opts.cordova.platforms);\n }\n\n return getAllPluginsHookScriptFiles(hook, opts);\n}", "code_tokens": ["function", "getPluginsHookScripts", "(", "hook", ",", "opts", ")", "{", "if", "(", "!", "hook", ")", "{", "throw", "new", "Error", "(", "'hook type is not specified'", ")", ";", "}", "if", "(", "opts", ".", "plugin", ")", "{", "events", ".", "emit", "(", "'verbose'", ",", "'Finding scripts for \"'", "+", "hook", "+", "'\" hook from plugin '", "+", "opts", ".", "plugin", ".", "id", "+", "' on '", "+", "opts", ".", "plugin", ".", "platform", "+", "' platform only.'", ")", ";", "return", "getPluginScriptFiles", "(", "opts", ".", "plugin", ",", "hook", ",", "opts", ".", "plugin", ".", "platform", "?", "[", "opts", ".", "plugin", ".", "platform", "]", ":", "opts", ".", "cordova", ".", "platforms", ")", ";", "}", "return", "getAllPluginsHookScriptFiles", "(", "hook", ",", "opts", ")", ";", "}"], "docstring": "Returns script files defined by plugin developers as part of plugin.xml.", "docstring_tokens": ["Returns", "script", "files", "defined", "by", "plugin", "developers", "as", "part", "of", "plugin", ".", "xml", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/hooks/scriptsFinder.js#L62-L77", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/hooks/scriptsFinder.js", "func_name": "getApplicationHookScriptsFromDir", "original_string": "function getApplicationHookScriptsFromDir (dir) {\n if (!(fs.existsSync(dir))) {\n return [];\n }\n\n var compareNumbers = function (a, b) {\n // TODO SG looks very complex, do we really need this?\n return isNaN(parseInt(a, 10)) ? a.toLowerCase().localeCompare(b.toLowerCase ? b.toLowerCase() : b)\n : parseInt(a, 10) > parseInt(b, 10) ? 1 : parseInt(a, 10) < parseInt(b, 10) ? -1 : 0;\n };\n\n var scripts = fs.readdirSync(dir).sort(compareNumbers).filter(function (s) {\n return s[0] !== '.';\n });\n return scripts.map(function (scriptPath) {\n // for old style hook files we don't use module loader for backward compatibility\n return { path: scriptPath, fullPath: path.join(dir, scriptPath), useModuleLoader: false };\n });\n}", "language": "javascript", "code": "function getApplicationHookScriptsFromDir (dir) {\n if (!(fs.existsSync(dir))) {\n return [];\n }\n\n var compareNumbers = function (a, b) {\n // TODO SG looks very complex, do we really need this?\n return isNaN(parseInt(a, 10)) ? a.toLowerCase().localeCompare(b.toLowerCase ? b.toLowerCase() : b)\n : parseInt(a, 10) > parseInt(b, 10) ? 1 : parseInt(a, 10) < parseInt(b, 10) ? -1 : 0;\n };\n\n var scripts = fs.readdirSync(dir).sort(compareNumbers).filter(function (s) {\n return s[0] !== '.';\n });\n return scripts.map(function (scriptPath) {\n // for old style hook files we don't use module loader for backward compatibility\n return { path: scriptPath, fullPath: path.join(dir, scriptPath), useModuleLoader: false };\n });\n}", "code_tokens": ["function", "getApplicationHookScriptsFromDir", "(", "dir", ")", "{", "if", "(", "!", "(", "fs", ".", "existsSync", "(", "dir", ")", ")", ")", "{", "return", "[", "]", ";", "}", "var", "compareNumbers", "=", "function", "(", "a", ",", "b", ")", "{", "return", "isNaN", "(", "parseInt", "(", "a", ",", "10", ")", ")", "?", "a", ".", "toLowerCase", "(", ")", ".", "localeCompare", "(", "b", ".", "toLowerCase", "?", "b", ".", "toLowerCase", "(", ")", ":", "b", ")", ":", "parseInt", "(", "a", ",", "10", ")", ">", "parseInt", "(", "b", ",", "10", ")", "?", "1", ":", "parseInt", "(", "a", ",", "10", ")", "<", "parseInt", "(", "b", ",", "10", ")", "?", "-", "1", ":", "0", ";", "}", ";", "var", "scripts", "=", "fs", ".", "readdirSync", "(", "dir", ")", ".", "sort", "(", "compareNumbers", ")", ".", "filter", "(", "function", "(", "s", ")", "{", "return", "s", "[", "0", "]", "!==", "'.'", ";", "}", ")", ";", "return", "scripts", ".", "map", "(", "function", "(", "scriptPath", ")", "{", "return", "{", "path", ":", "scriptPath", ",", "fullPath", ":", "path", ".", "join", "(", "dir", ",", "scriptPath", ")", ",", "useModuleLoader", ":", "false", "}", ";", "}", ")", ";", "}"], "docstring": "Gets application level hooks from the directrory specified.", "docstring_tokens": ["Gets", "application", "level", "hooks", "from", "the", "directrory", "specified", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/hooks/scriptsFinder.js#L82-L100", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/hooks/scriptsFinder.js", "func_name": "getScriptsFromConfigXml", "original_string": "function getScriptsFromConfigXml (hook, opts) {\n var configPath = cordovaUtil.projectConfig(opts.projectRoot);\n var configXml = new ConfigParser(configPath);\n\n return configXml.getHookScripts(hook, opts.cordova.platforms).map(function (scriptElement) {\n return {\n path: scriptElement.attrib.src,\n fullPath: path.join(opts.projectRoot, scriptElement.attrib.src)\n };\n });\n}", "language": "javascript", "code": "function getScriptsFromConfigXml (hook, opts) {\n var configPath = cordovaUtil.projectConfig(opts.projectRoot);\n var configXml = new ConfigParser(configPath);\n\n return configXml.getHookScripts(hook, opts.cordova.platforms).map(function (scriptElement) {\n return {\n path: scriptElement.attrib.src,\n fullPath: path.join(opts.projectRoot, scriptElement.attrib.src)\n };\n });\n}", "code_tokens": ["function", "getScriptsFromConfigXml", "(", "hook", ",", "opts", ")", "{", "var", "configPath", "=", "cordovaUtil", ".", "projectConfig", "(", "opts", ".", "projectRoot", ")", ";", "var", "configXml", "=", "new", "ConfigParser", "(", "configPath", ")", ";", "return", "configXml", ".", "getHookScripts", "(", "hook", ",", "opts", ".", "cordova", ".", "platforms", ")", ".", "map", "(", "function", "(", "scriptElement", ")", "{", "return", "{", "path", ":", "scriptElement", ".", "attrib", ".", "src", ",", "fullPath", ":", "path", ".", "join", "(", "opts", ".", "projectRoot", ",", "scriptElement", ".", "attrib", ".", "src", ")", "}", ";", "}", ")", ";", "}"], "docstring": "Gets all scripts defined in config.xml with the specified type and platforms.", "docstring_tokens": ["Gets", "all", "scripts", "defined", "in", "config", ".", "xml", "with", "the", "specified", "type", "and", "platforms", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/hooks/scriptsFinder.js#L105-L115", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/hooks/scriptsFinder.js", "func_name": "getPluginScriptFiles", "original_string": "function getPluginScriptFiles (plugin, hook, platforms) {\n var scriptElements = plugin.pluginInfo.getHookScripts(hook, platforms);\n\n return scriptElements.map(function (scriptElement) {\n return {\n path: scriptElement.attrib.src,\n fullPath: path.join(plugin.dir, scriptElement.attrib.src),\n plugin: plugin\n };\n });\n}", "language": "javascript", "code": "function getPluginScriptFiles (plugin, hook, platforms) {\n var scriptElements = plugin.pluginInfo.getHookScripts(hook, platforms);\n\n return scriptElements.map(function (scriptElement) {\n return {\n path: scriptElement.attrib.src,\n fullPath: path.join(plugin.dir, scriptElement.attrib.src),\n plugin: plugin\n };\n });\n}", "code_tokens": ["function", "getPluginScriptFiles", "(", "plugin", ",", "hook", ",", "platforms", ")", "{", "var", "scriptElements", "=", "plugin", ".", "pluginInfo", ".", "getHookScripts", "(", "hook", ",", "platforms", ")", ";", "return", "scriptElements", ".", "map", "(", "function", "(", "scriptElement", ")", "{", "return", "{", "path", ":", "scriptElement", ".", "attrib", ".", "src", ",", "fullPath", ":", "path", ".", "join", "(", "plugin", ".", "dir", ",", "scriptElement", ".", "attrib", ".", "src", ")", ",", "plugin", ":", "plugin", "}", ";", "}", ")", ";", "}"], "docstring": "Gets hook scripts defined by the plugin.", "docstring_tokens": ["Gets", "hook", "scripts", "defined", "by", "the", "plugin", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/hooks/scriptsFinder.js#L120-L130", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/hooks/scriptsFinder.js", "func_name": "getAllPluginsHookScriptFiles", "original_string": "function getAllPluginsHookScriptFiles (hook, opts) {\n var scripts = [];\n var currentPluginOptions;\n\n var plugins = (new PluginInfoProvider()).getAllWithinSearchPath(path.join(opts.projectRoot, 'plugins'));\n\n plugins.forEach(function (pluginInfo) {\n currentPluginOptions = {\n id: pluginInfo.id,\n pluginInfo: pluginInfo,\n dir: pluginInfo.dir\n };\n\n scripts = scripts.concat(getPluginScriptFiles(currentPluginOptions, hook, opts.cordova.platforms));\n });\n return scripts;\n}", "language": "javascript", "code": "function getAllPluginsHookScriptFiles (hook, opts) {\n var scripts = [];\n var currentPluginOptions;\n\n var plugins = (new PluginInfoProvider()).getAllWithinSearchPath(path.join(opts.projectRoot, 'plugins'));\n\n plugins.forEach(function (pluginInfo) {\n currentPluginOptions = {\n id: pluginInfo.id,\n pluginInfo: pluginInfo,\n dir: pluginInfo.dir\n };\n\n scripts = scripts.concat(getPluginScriptFiles(currentPluginOptions, hook, opts.cordova.platforms));\n });\n return scripts;\n}", "code_tokens": ["function", "getAllPluginsHookScriptFiles", "(", "hook", ",", "opts", ")", "{", "var", "scripts", "=", "[", "]", ";", "var", "currentPluginOptions", ";", "var", "plugins", "=", "(", "new", "PluginInfoProvider", "(", ")", ")", ".", "getAllWithinSearchPath", "(", "path", ".", "join", "(", "opts", ".", "projectRoot", ",", "'plugins'", ")", ")", ";", "plugins", ".", "forEach", "(", "function", "(", "pluginInfo", ")", "{", "currentPluginOptions", "=", "{", "id", ":", "pluginInfo", ".", "id", ",", "pluginInfo", ":", "pluginInfo", ",", "dir", ":", "pluginInfo", ".", "dir", "}", ";", "scripts", "=", "scripts", ".", "concat", "(", "getPluginScriptFiles", "(", "currentPluginOptions", ",", "hook", ",", "opts", ".", "cordova", ".", "platforms", ")", ")", ";", "}", ")", ";", "return", "scripts", ";", "}"], "docstring": "Gets hook scripts defined by all plugins.", "docstring_tokens": ["Gets", "hook", "scripts", "defined", "by", "all", "plugins", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/hooks/scriptsFinder.js#L135-L151", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/cordova/fixtures/projects/platformApi/platforms/windows/cordova/lib/AppxManifest.js", "func_name": "ensureUniqueCapabilities", "original_string": "function ensureUniqueCapabilities(capabilities) {\n var uniqueCapabilities = [];\n capabilities.getchildren()\n .forEach(function(el) {\n var name = el.attrib.Name;\n if (uniqueCapabilities.indexOf(name) !== -1) {\n capabilities.remove(el);\n } else {\n uniqueCapabilities.push(name);\n }\n });\n}", "language": "javascript", "code": "function ensureUniqueCapabilities(capabilities) {\n var uniqueCapabilities = [];\n capabilities.getchildren()\n .forEach(function(el) {\n var name = el.attrib.Name;\n if (uniqueCapabilities.indexOf(name) !== -1) {\n capabilities.remove(el);\n } else {\n uniqueCapabilities.push(name);\n }\n });\n}", "code_tokens": ["function", "ensureUniqueCapabilities", "(", "capabilities", ")", "{", "var", "uniqueCapabilities", "=", "[", "]", ";", "capabilities", ".", "getchildren", "(", ")", ".", "forEach", "(", "function", "(", "el", ")", "{", "var", "name", "=", "el", ".", "attrib", ".", "Name", ";", "if", "(", "uniqueCapabilities", ".", "indexOf", "(", "name", ")", "!==", "-", "1", ")", "{", "capabilities", ".", "remove", "(", "el", ")", ";", "}", "else", "{", "uniqueCapabilities", ".", "push", "(", "name", ")", ";", "}", "}", ")", ";", "}"], "docstring": "Cleans up duplicate capability declarations that were generated during the prepare process\n@param capabilities {ElementTree.Element} The appx manifest element for ", "docstring_tokens": ["Cleans", "up", "duplicate", "capability", "declarations", "that", "were", "generated", "during", "the", "prepare", "process"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/cordova/fixtures/projects/platformApi/platforms/windows/cordova/lib/AppxManifest.js#L720-L731", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/plugman/projects/android/cordova/lib/pluginHandlers.js", "func_name": "copyNewFile", "original_string": "function copyNewFile (plugin_dir, src, project_dir, dest, link) {\n var target_path = path.resolve(project_dir, dest);\n if (fs.existsSync(target_path))\n throw new CordovaError('\"' + target_path + '\" already exists!');\n\n copyFile(plugin_dir, src, project_dir, dest, !!link);\n}", "language": "javascript", "code": "function copyNewFile (plugin_dir, src, project_dir, dest, link) {\n var target_path = path.resolve(project_dir, dest);\n if (fs.existsSync(target_path))\n throw new CordovaError('\"' + target_path + '\" already exists!');\n\n copyFile(plugin_dir, src, project_dir, dest, !!link);\n}", "code_tokens": ["function", "copyNewFile", "(", "plugin_dir", ",", "src", ",", "project_dir", ",", "dest", ",", "link", ")", "{", "var", "target_path", "=", "path", ".", "resolve", "(", "project_dir", ",", "dest", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "target_path", ")", ")", "throw", "new", "CordovaError", "(", "'\"'", "+", "target_path", "+", "'\" already exists!'", ")", ";", "copyFile", "(", "plugin_dir", ",", "src", ",", "project_dir", ",", "dest", ",", "!", "!", "link", ")", ";", "}"], "docstring": "Same as copy file but throws error if target exists", "docstring_tokens": ["Same", "as", "copy", "file", "but", "throws", "error", "if", "target", "exists"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/plugman/projects/android/cordova/lib/pluginHandlers.js#L245-L251", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/plugin/plugin_spec_parser.js", "func_name": "PluginSpec", "original_string": "function PluginSpec (raw, scope, id, version) {\n /** @member {String|null} The npm scope of the plugin spec or null if it does not have one */\n this.scope = scope || null;\n\n /** @member {String|null} The id of the plugin or the raw plugin spec if it is not an npm package */\n this.id = id || raw;\n\n /** @member {String|null} The specified version of the plugin or null if no version was specified */\n this.version = version || null;\n\n /** @member {String|null} The npm package of the plugin (with scope) or null if this is not a spec for an npm package */\n this.package = (scope ? scope + id : id) || null;\n}", "language": "javascript", "code": "function PluginSpec (raw, scope, id, version) {\n /** @member {String|null} The npm scope of the plugin spec or null if it does not have one */\n this.scope = scope || null;\n\n /** @member {String|null} The id of the plugin or the raw plugin spec if it is not an npm package */\n this.id = id || raw;\n\n /** @member {String|null} The specified version of the plugin or null if no version was specified */\n this.version = version || null;\n\n /** @member {String|null} The npm package of the plugin (with scope) or null if this is not a spec for an npm package */\n this.package = (scope ? scope + id : id) || null;\n}", "code_tokens": ["function", "PluginSpec", "(", "raw", ",", "scope", ",", "id", ",", "version", ")", "{", "this", ".", "scope", "=", "scope", "||", "null", ";", "this", ".", "id", "=", "id", "||", "raw", ";", "this", ".", "version", "=", "version", "||", "null", ";", "this", ".", "package", "=", "(", "scope", "?", "scope", "+", "id", ":", "id", ")", "||", "null", ";", "}"], "docstring": "Represents a parsed specification for a plugin\n@class\n@param {String} raw The raw specification (i.e. provided by the user)\n@param {String} scope The scope of the package if this is an npm package\n@param {String} id The id of the package if this is an npm package\n@param {String} version The version specified for the package if this is an npm package", "docstring_tokens": ["Represents", "a", "parsed", "specification", "for", "a", "plugin"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/plugin/plugin_spec_parser.js#L33-L45", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/cordova/fixtures/projects/platformApi/platforms/windows/cordova/lib/PluginHandler.js", "func_name": "getPluginFilePath", "original_string": "function getPluginFilePath(plugin, pluginFile, targetDir) {\n var src = path.resolve(plugin.dir, pluginFile);\n return '$(ProjectDir)' + path.relative(targetDir, src);\n}", "language": "javascript", "code": "function getPluginFilePath(plugin, pluginFile, targetDir) {\n var src = path.resolve(plugin.dir, pluginFile);\n return '$(ProjectDir)' + path.relative(targetDir, src);\n}", "code_tokens": ["function", "getPluginFilePath", "(", "plugin", ",", "pluginFile", ",", "targetDir", ")", "{", "var", "src", "=", "path", ".", "resolve", "(", "plugin", ".", "dir", ",", "pluginFile", ")", ";", "return", "'$(ProjectDir)'", "+", "path", ".", "relative", "(", "targetDir", ",", "src", ")", ";", "}"], "docstring": "returns relative file path for a file in the plugin's folder that can be referenced from a project file.", "docstring_tokens": ["returns", "relative", "file", "path", "for", "a", "file", "in", "the", "plugin", "s", "folder", "that", "can", "be", "referenced", "from", "a", "project", "file", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/cordova/fixtures/projects/platformApi/platforms/windows/cordova/lib/PluginHandler.js#L30-L33", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/platform/index.js", "func_name": "platform", "original_string": "function platform (command, targets, opts) {\n // CB-10519 wrap function code into promise so throwing error\n // would result in promise rejection instead of uncaught exception\n return Promise.resolve().then(function () {\n var msg;\n var projectRoot = cordova_util.cdProjectRoot();\n var hooksRunner = new HooksRunner(projectRoot);\n\n if (arguments.length === 0) command = 'ls';\n\n if (targets && !(targets instanceof Array)) targets = [targets];\n\n // TODO: wouldn't update need a platform, too? what about save?\n if ((command === 'add' || command === 'rm' || command === 'remove') && (!targets || (targets instanceof Array && targets.length === 0))) {\n msg = 'You need to qualify `' + command + '` with one or more platforms!';\n return Promise.reject(new CordovaError(msg));\n }\n\n opts = opts || {};\n opts.platforms = targets;\n switch (command) {\n case 'add':\n return module.exports.add(hooksRunner, projectRoot, targets, opts);\n case 'rm':\n case 'remove':\n return module.exports.remove(hooksRunner, projectRoot, targets, opts);\n case 'update':\n case 'up':\n return module.exports.update(hooksRunner, projectRoot, targets, opts);\n case 'check':\n return module.exports.check(hooksRunner, projectRoot);\n default:\n return module.exports.list(hooksRunner, projectRoot, opts);\n }\n });\n}", "language": "javascript", "code": "function platform (command, targets, opts) {\n // CB-10519 wrap function code into promise so throwing error\n // would result in promise rejection instead of uncaught exception\n return Promise.resolve().then(function () {\n var msg;\n var projectRoot = cordova_util.cdProjectRoot();\n var hooksRunner = new HooksRunner(projectRoot);\n\n if (arguments.length === 0) command = 'ls';\n\n if (targets && !(targets instanceof Array)) targets = [targets];\n\n // TODO: wouldn't update need a platform, too? what about save?\n if ((command === 'add' || command === 'rm' || command === 'remove') && (!targets || (targets instanceof Array && targets.length === 0))) {\n msg = 'You need to qualify `' + command + '` with one or more platforms!';\n return Promise.reject(new CordovaError(msg));\n }\n\n opts = opts || {};\n opts.platforms = targets;\n switch (command) {\n case 'add':\n return module.exports.add(hooksRunner, projectRoot, targets, opts);\n case 'rm':\n case 'remove':\n return module.exports.remove(hooksRunner, projectRoot, targets, opts);\n case 'update':\n case 'up':\n return module.exports.update(hooksRunner, projectRoot, targets, opts);\n case 'check':\n return module.exports.check(hooksRunner, projectRoot);\n default:\n return module.exports.list(hooksRunner, projectRoot, opts);\n }\n });\n}", "code_tokens": ["function", "platform", "(", "command", ",", "targets", ",", "opts", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "function", "(", ")", "{", "var", "msg", ";", "var", "projectRoot", "=", "cordova_util", ".", "cdProjectRoot", "(", ")", ";", "var", "hooksRunner", "=", "new", "HooksRunner", "(", "projectRoot", ")", ";", "if", "(", "arguments", ".", "length", "===", "0", ")", "command", "=", "'ls'", ";", "if", "(", "targets", "&&", "!", "(", "targets", "instanceof", "Array", ")", ")", "targets", "=", "[", "targets", "]", ";", "if", "(", "(", "command", "===", "'add'", "||", "command", "===", "'rm'", "||", "command", "===", "'remove'", ")", "&&", "(", "!", "targets", "||", "(", "targets", "instanceof", "Array", "&&", "targets", ".", "length", "===", "0", ")", ")", ")", "{", "msg", "=", "'You need to qualify `'", "+", "command", "+", "'` with one or more platforms!'", ";", "return", "Promise", ".", "reject", "(", "new", "CordovaError", "(", "msg", ")", ")", ";", "}", "opts", "=", "opts", "||", "{", "}", ";", "opts", ".", "platforms", "=", "targets", ";", "switch", "(", "command", ")", "{", "case", "'add'", ":", "return", "module", ".", "exports", ".", "add", "(", "hooksRunner", ",", "projectRoot", ",", "targets", ",", "opts", ")", ";", "case", "'rm'", ":", "case", "'remove'", ":", "return", "module", ".", "exports", ".", "remove", "(", "hooksRunner", ",", "projectRoot", ",", "targets", ",", "opts", ")", ";", "case", "'update'", ":", "case", "'up'", ":", "return", "module", ".", "exports", ".", "update", "(", "hooksRunner", ",", "projectRoot", ",", "targets", ",", "opts", ")", ";", "case", "'check'", ":", "return", "module", ".", "exports", ".", "check", "(", "hooksRunner", ",", "projectRoot", ")", ";", "default", ":", "return", "module", ".", "exports", ".", "list", "(", "hooksRunner", ",", "projectRoot", ",", "opts", ")", ";", "}", "}", ")", ";", "}"], "docstring": "Handles all cordova platform commands.\n@param {string} command - Command to execute (add, rm, ls, update, save)\n@param {Object[]} targets - Array containing platforms to execute commands on\n@param {Object} opts\n@returns {Promise}", "docstring_tokens": ["Handles", "all", "cordova", "platform", "commands", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/platform/index.js#L49-L84", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/project_metadata.js", "func_name": "getPlatforms", "original_string": "function getPlatforms (projectRoot) {\n var xml = cordova_util.projectConfig(projectRoot);\n var cfg = new ConfigParser(xml);\n\n // If an engine's 'version' property is really its source, map that to the appropriate field.\n var engines = cfg.getEngines().map(function (engine) {\n var result = {\n name: engine.name\n };\n\n if (semver.validRange(engine.spec, true)) {\n result.version = engine.spec;\n } else {\n result.src = engine.spec;\n }\n\n return result;\n });\n\n return Promise.resolve(engines);\n}", "language": "javascript", "code": "function getPlatforms (projectRoot) {\n var xml = cordova_util.projectConfig(projectRoot);\n var cfg = new ConfigParser(xml);\n\n // If an engine's 'version' property is really its source, map that to the appropriate field.\n var engines = cfg.getEngines().map(function (engine) {\n var result = {\n name: engine.name\n };\n\n if (semver.validRange(engine.spec, true)) {\n result.version = engine.spec;\n } else {\n result.src = engine.spec;\n }\n\n return result;\n });\n\n return Promise.resolve(engines);\n}", "code_tokens": ["function", "getPlatforms", "(", "projectRoot", ")", "{", "var", "xml", "=", "cordova_util", ".", "projectConfig", "(", "projectRoot", ")", ";", "var", "cfg", "=", "new", "ConfigParser", "(", "xml", ")", ";", "var", "engines", "=", "cfg", ".", "getEngines", "(", ")", ".", "map", "(", "function", "(", "engine", ")", "{", "var", "result", "=", "{", "name", ":", "engine", ".", "name", "}", ";", "if", "(", "semver", ".", "validRange", "(", "engine", ".", "spec", ",", "true", ")", ")", "{", "result", ".", "version", "=", "engine", ".", "spec", ";", "}", "else", "{", "result", ".", "src", "=", "engine", ".", "spec", ";", "}", "return", "result", ";", "}", ")", ";", "return", "Promise", ".", "resolve", "(", "engines", ")", ";", "}"], "docstring": "Returns all the platforms that are currently saved into config.xml\n@return {Promise<{name: string, version: string, src: string}[]>}\ne.g: [ {name: 'android', version: '3.5.0'}, {name: 'wp8', src: 'C:/path/to/platform'}, {name: 'ios', src: 'git://...'} ]", "docstring_tokens": ["Returns", "all", "the", "platforms", "that", "are", "currently", "saved", "into", "config", ".", "xml"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/project_metadata.js#L28-L48", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/project_metadata.js", "func_name": "getPlugins", "original_string": "function getPlugins (projectRoot) {\n var xml = cordova_util.projectConfig(projectRoot);\n var cfg = new ConfigParser(xml);\n\n // Map variables object to an array\n var plugins = cfg.getPlugins().map(function (plugin) {\n var result = {\n name: plugin.name\n };\n\n if (semver.validRange(plugin.spec, true)) {\n result.version = plugin.spec;\n } else {\n result.src = plugin.spec;\n }\n\n var variablesObject = plugin.variables;\n var variablesArray = [];\n if (variablesObject) {\n for (var variable in variablesObject) {\n variablesArray.push({\n name: variable,\n value: variablesObject[variable]\n });\n }\n }\n result.variables = variablesArray;\n return result;\n });\n\n return Promise.resolve(plugins);\n}", "language": "javascript", "code": "function getPlugins (projectRoot) {\n var xml = cordova_util.projectConfig(projectRoot);\n var cfg = new ConfigParser(xml);\n\n // Map variables object to an array\n var plugins = cfg.getPlugins().map(function (plugin) {\n var result = {\n name: plugin.name\n };\n\n if (semver.validRange(plugin.spec, true)) {\n result.version = plugin.spec;\n } else {\n result.src = plugin.spec;\n }\n\n var variablesObject = plugin.variables;\n var variablesArray = [];\n if (variablesObject) {\n for (var variable in variablesObject) {\n variablesArray.push({\n name: variable,\n value: variablesObject[variable]\n });\n }\n }\n result.variables = variablesArray;\n return result;\n });\n\n return Promise.resolve(plugins);\n}", "code_tokens": ["function", "getPlugins", "(", "projectRoot", ")", "{", "var", "xml", "=", "cordova_util", ".", "projectConfig", "(", "projectRoot", ")", ";", "var", "cfg", "=", "new", "ConfigParser", "(", "xml", ")", ";", "var", "plugins", "=", "cfg", ".", "getPlugins", "(", ")", ".", "map", "(", "function", "(", "plugin", ")", "{", "var", "result", "=", "{", "name", ":", "plugin", ".", "name", "}", ";", "if", "(", "semver", ".", "validRange", "(", "plugin", ".", "spec", ",", "true", ")", ")", "{", "result", ".", "version", "=", "plugin", ".", "spec", ";", "}", "else", "{", "result", ".", "src", "=", "plugin", ".", "spec", ";", "}", "var", "variablesObject", "=", "plugin", ".", "variables", ";", "var", "variablesArray", "=", "[", "]", ";", "if", "(", "variablesObject", ")", "{", "for", "(", "var", "variable", "in", "variablesObject", ")", "{", "variablesArray", ".", "push", "(", "{", "name", ":", "variable", ",", "value", ":", "variablesObject", "[", "variable", "]", "}", ")", ";", "}", "}", "result", ".", "variables", "=", "variablesArray", ";", "return", "result", ";", "}", ")", ";", "return", "Promise", ".", "resolve", "(", "plugins", ")", ";", "}"], "docstring": "Returns all the plugins that are currently saved into config.xml\n@return {Promise<{id: string, version: string, variables: {name: string, value: string}[]}[]>}\ne.g: [ {id: 'org.apache.cordova.device', variables: [{name: 'APP_ID', value: 'my-app-id'}, {name: 'APP_NAME', value: 'my-app-name'}]} ]", "docstring_tokens": ["Returns", "all", "the", "plugins", "that", "are", "currently", "saved", "into", "config", ".", "xml"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/project_metadata.js#L54-L85", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/plugman/util/dependencies.js", "func_name": "", "original_string": "function (plugin_id, plugins_dir, platformJson, pluginInfoProvider) {\n var depsInfo;\n if (typeof plugins_dir === 'object') { depsInfo = plugins_dir; } else { depsInfo = pkg.generateDependencyInfo(platformJson, plugins_dir, pluginInfoProvider); }\n\n var graph = depsInfo.graph;\n var dependencies = graph.getChain(plugin_id);\n\n var tlps = depsInfo.top_level_plugins;\n var diff_arr = [];\n tlps.forEach(function (tlp) {\n if (tlp !== plugin_id) {\n diff_arr.push(graph.getChain(tlp));\n }\n });\n\n // if this plugin has dependencies, do a set difference to determine which dependencies are not required by other existing plugins\n diff_arr.unshift(dependencies);\n var danglers = underscore.difference.apply(null, diff_arr);\n\n // Ensure no top-level plugins are tagged as danglers.\n danglers = danglers && danglers.filter(function (x) { return tlps.indexOf(x) < 0; });\n return danglers;\n }", "language": "javascript", "code": "function (plugin_id, plugins_dir, platformJson, pluginInfoProvider) {\n var depsInfo;\n if (typeof plugins_dir === 'object') { depsInfo = plugins_dir; } else { depsInfo = pkg.generateDependencyInfo(platformJson, plugins_dir, pluginInfoProvider); }\n\n var graph = depsInfo.graph;\n var dependencies = graph.getChain(plugin_id);\n\n var tlps = depsInfo.top_level_plugins;\n var diff_arr = [];\n tlps.forEach(function (tlp) {\n if (tlp !== plugin_id) {\n diff_arr.push(graph.getChain(tlp));\n }\n });\n\n // if this plugin has dependencies, do a set difference to determine which dependencies are not required by other existing plugins\n diff_arr.unshift(dependencies);\n var danglers = underscore.difference.apply(null, diff_arr);\n\n // Ensure no top-level plugins are tagged as danglers.\n danglers = danglers && danglers.filter(function (x) { return tlps.indexOf(x) < 0; });\n return danglers;\n }", "code_tokens": ["function", "(", "plugin_id", ",", "plugins_dir", ",", "platformJson", ",", "pluginInfoProvider", ")", "{", "var", "depsInfo", ";", "if", "(", "typeof", "plugins_dir", "===", "'object'", ")", "{", "depsInfo", "=", "plugins_dir", ";", "}", "else", "{", "depsInfo", "=", "pkg", ".", "generateDependencyInfo", "(", "platformJson", ",", "plugins_dir", ",", "pluginInfoProvider", ")", ";", "}", "var", "graph", "=", "depsInfo", ".", "graph", ";", "var", "dependencies", "=", "graph", ".", "getChain", "(", "plugin_id", ")", ";", "var", "tlps", "=", "depsInfo", ".", "top_level_plugins", ";", "var", "diff_arr", "=", "[", "]", ";", "tlps", ".", "forEach", "(", "function", "(", "tlp", ")", "{", "if", "(", "tlp", "!==", "plugin_id", ")", "{", "diff_arr", ".", "push", "(", "graph", ".", "getChain", "(", "tlp", ")", ")", ";", "}", "}", ")", ";", "diff_arr", ".", "unshift", "(", "dependencies", ")", ";", "var", "danglers", "=", "underscore", ".", "difference", ".", "apply", "(", "null", ",", "diff_arr", ")", ";", "danglers", "=", "danglers", "&&", "danglers", ".", "filter", "(", "function", "(", "x", ")", "{", "return", "tlps", ".", "indexOf", "(", "x", ")", "<", "0", ";", "}", ")", ";", "return", "danglers", ";", "}"], "docstring": "Returns a list of plugins which the given plugin depends on, for which it is the only dependent. In other words, if the given plugin were deleted, these dangling dependencies should be deleted too.", "docstring_tokens": ["Returns", "a", "list", "of", "plugins", "which", "the", "given", "plugin", "depends", "on", "for", "which", "it", "is", "the", "only", "dependent", ".", "In", "other", "words", "if", "the", "given", "plugin", "were", "deleted", "these", "dangling", "dependencies", "should", "be", "deleted", "too", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/plugman/util/dependencies.js#L83-L105", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/cordova/fixtures/projects/platformApi/platforms/windows/cordova/lib/PluginInfo.js", "func_name": "createReplacement", "original_string": "function createReplacement(manifestFile, originalChange) {\n var replacement = {\n target: manifestFile,\n parent: originalChange.parent,\n after: originalChange.after,\n xmls: originalChange.xmls,\n versions: originalChange.versions,\n deviceTarget: originalChange.deviceTarget\n };\n return replacement;\n}", "language": "javascript", "code": "function createReplacement(manifestFile, originalChange) {\n var replacement = {\n target: manifestFile,\n parent: originalChange.parent,\n after: originalChange.after,\n xmls: originalChange.xmls,\n versions: originalChange.versions,\n deviceTarget: originalChange.deviceTarget\n };\n return replacement;\n}", "code_tokens": ["function", "createReplacement", "(", "manifestFile", ",", "originalChange", ")", "{", "var", "replacement", "=", "{", "target", ":", "manifestFile", ",", "parent", ":", "originalChange", ".", "parent", ",", "after", ":", "originalChange", ".", "after", ",", "xmls", ":", "originalChange", ".", "xmls", ",", "versions", ":", "originalChange", ".", "versions", ",", "deviceTarget", ":", "originalChange", ".", "deviceTarget", "}", ";", "return", "replacement", ";", "}"], "docstring": "This is a local function that creates the new replacement representing the mutation. Used to save code further down.", "docstring_tokens": ["This", "is", "a", "local", "function", "that", "creates", "the", "new", "replacement", "representing", "the", "mutation", ".", "Used", "to", "save", "code", "further", "down", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/cordova/fixtures/projects/platformApi/platforms/windows/cordova/lib/PluginInfo.js#L103-L113", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/plugman/fetch.js", "func_name": "checkID", "original_string": "function checkID (expectedIdAndVersion, pinfo) {\n if (!expectedIdAndVersion) return;\n\n var parsedSpec = pluginSpec.parse(expectedIdAndVersion);\n\n if (parsedSpec.id !== pinfo.id) {\n throw new Error('Expected plugin to have ID \"' + parsedSpec.id + '\" but got \"' + pinfo.id + '\".');\n }\n\n if (parsedSpec.version && !semver.satisfies(pinfo.version, parsedSpec.version)) {\n throw new Error('Expected plugin ' + pinfo.id + ' to satisfy version \"' + parsedSpec.version + '\" but got \"' + pinfo.version + '\".');\n }\n}", "language": "javascript", "code": "function checkID (expectedIdAndVersion, pinfo) {\n if (!expectedIdAndVersion) return;\n\n var parsedSpec = pluginSpec.parse(expectedIdAndVersion);\n\n if (parsedSpec.id !== pinfo.id) {\n throw new Error('Expected plugin to have ID \"' + parsedSpec.id + '\" but got \"' + pinfo.id + '\".');\n }\n\n if (parsedSpec.version && !semver.satisfies(pinfo.version, parsedSpec.version)) {\n throw new Error('Expected plugin ' + pinfo.id + ' to satisfy version \"' + parsedSpec.version + '\" but got \"' + pinfo.version + '\".');\n }\n}", "code_tokens": ["function", "checkID", "(", "expectedIdAndVersion", ",", "pinfo", ")", "{", "if", "(", "!", "expectedIdAndVersion", ")", "return", ";", "var", "parsedSpec", "=", "pluginSpec", ".", "parse", "(", "expectedIdAndVersion", ")", ";", "if", "(", "parsedSpec", ".", "id", "!==", "pinfo", ".", "id", ")", "{", "throw", "new", "Error", "(", "'Expected plugin to have ID \"'", "+", "parsedSpec", ".", "id", "+", "'\" but got \"'", "+", "pinfo", ".", "id", "+", "'\".'", ")", ";", "}", "if", "(", "parsedSpec", ".", "version", "&&", "!", "semver", ".", "satisfies", "(", "pinfo", ".", "version", ",", "parsedSpec", ".", "version", ")", ")", "{", "throw", "new", "Error", "(", "'Expected plugin '", "+", "pinfo", ".", "id", "+", "' to satisfy version \"'", "+", "parsedSpec", ".", "version", "+", "'\" but got \"'", "+", "pinfo", ".", "version", "+", "'\".'", ")", ";", "}", "}"], "docstring": "Helper function for checking expected plugin IDs against reality.", "docstring_tokens": ["Helper", "function", "for", "checking", "expected", "plugin", "IDs", "against", "reality", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/plugman/fetch.js#L182-L194", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/platform/getPlatformDetailsFromDir.js", "func_name": "getPlatformDetailsFromDir", "original_string": "function getPlatformDetailsFromDir (dir, platformIfKnown) {\n var libDir = path.resolve(dir);\n var platform;\n var version;\n\n // console.log(\"getPlatformDetailsFromDir : \", dir, platformIfKnown, libDir);\n\n try {\n var pkgPath = path.join(libDir, 'package.json');\n var pkg = cordova_util.requireNoCache(pkgPath);\n platform = module.exports.platformFromName(pkg.name);\n version = pkg.version;\n } catch (e) {\n return Promise.reject(new CordovaError('The provided path does not seem to contain a valid package.json or a valid Cordova platform: ' + libDir));\n }\n\n // platform does NOT have to exist in 'platforms', but it should have a name, and a version\n if (!version || !platform) {\n return Promise.reject(new CordovaError('The provided path does not seem to contain a ' +\n 'Cordova platform: ' + libDir));\n }\n\n return Promise.resolve({\n libDir: libDir,\n platform: platform,\n version: version\n });\n}", "language": "javascript", "code": "function getPlatformDetailsFromDir (dir, platformIfKnown) {\n var libDir = path.resolve(dir);\n var platform;\n var version;\n\n // console.log(\"getPlatformDetailsFromDir : \", dir, platformIfKnown, libDir);\n\n try {\n var pkgPath = path.join(libDir, 'package.json');\n var pkg = cordova_util.requireNoCache(pkgPath);\n platform = module.exports.platformFromName(pkg.name);\n version = pkg.version;\n } catch (e) {\n return Promise.reject(new CordovaError('The provided path does not seem to contain a valid package.json or a valid Cordova platform: ' + libDir));\n }\n\n // platform does NOT have to exist in 'platforms', but it should have a name, and a version\n if (!version || !platform) {\n return Promise.reject(new CordovaError('The provided path does not seem to contain a ' +\n 'Cordova platform: ' + libDir));\n }\n\n return Promise.resolve({\n libDir: libDir,\n platform: platform,\n version: version\n });\n}", "code_tokens": ["function", "getPlatformDetailsFromDir", "(", "dir", ",", "platformIfKnown", ")", "{", "var", "libDir", "=", "path", ".", "resolve", "(", "dir", ")", ";", "var", "platform", ";", "var", "version", ";", "try", "{", "var", "pkgPath", "=", "path", ".", "join", "(", "libDir", ",", "'package.json'", ")", ";", "var", "pkg", "=", "cordova_util", ".", "requireNoCache", "(", "pkgPath", ")", ";", "platform", "=", "module", ".", "exports", ".", "platformFromName", "(", "pkg", ".", "name", ")", ";", "version", "=", "pkg", ".", "version", ";", "}", "catch", "(", "e", ")", "{", "return", "Promise", ".", "reject", "(", "new", "CordovaError", "(", "'The provided path does not seem to contain a valid package.json or a valid Cordova platform: '", "+", "libDir", ")", ")", ";", "}", "if", "(", "!", "version", "||", "!", "platform", ")", "{", "return", "Promise", ".", "reject", "(", "new", "CordovaError", "(", "'The provided path does not seem to contain a '", "+", "'Cordova platform: '", "+", "libDir", ")", ")", ";", "}", "return", "Promise", ".", "resolve", "(", "{", "libDir", ":", "libDir", ",", "platform", ":", "platform", ",", "version", ":", "version", "}", ")", ";", "}"], "docstring": "Gets platform details from a directory", "docstring_tokens": ["Gets", "platform", "details", "from", "a", "directory"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/platform/getPlatformDetailsFromDir.js#L28-L55", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/platform/getPlatformDetailsFromDir.js", "func_name": "platformFromName", "original_string": "function platformFromName (name) {\n var platName = name;\n var platMatch = /^cordova-([a-z0-9-]+)$/.exec(name);\n if (platMatch && (platMatch[1] in platforms)) {\n platName = platMatch[1];\n events.emit('verbose', 'Removing \"cordova-\" prefix from ' + name);\n }\n return platName;\n}", "language": "javascript", "code": "function platformFromName (name) {\n var platName = name;\n var platMatch = /^cordova-([a-z0-9-]+)$/.exec(name);\n if (platMatch && (platMatch[1] in platforms)) {\n platName = platMatch[1];\n events.emit('verbose', 'Removing \"cordova-\" prefix from ' + name);\n }\n return platName;\n}", "code_tokens": ["function", "platformFromName", "(", "name", ")", "{", "var", "platName", "=", "name", ";", "var", "platMatch", "=", "/", "^cordova-([a-z0-9-]+)$", "/", ".", "exec", "(", "name", ")", ";", "if", "(", "platMatch", "&&", "(", "platMatch", "[", "1", "]", "in", "platforms", ")", ")", "{", "platName", "=", "platMatch", "[", "1", "]", ";", "events", ".", "emit", "(", "'verbose'", ",", "'Removing \"cordova-\" prefix from '", "+", "name", ")", ";", "}", "return", "platName", ";", "}"], "docstring": "Removes the cordova- prefix from the platform's name for known platforms.\n@param {string} name - platform name\n@returns {string}", "docstring_tokens": ["Removes", "the", "cordova", "-", "prefix", "from", "the", "platform", "s", "name", "for", "known", "platforms", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/platform/getPlatformDetailsFromDir.js#L62-L70", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/plugman/projects/android/platform_www/cordova-js-src/exec.js", "func_name": "processMessage", "original_string": "function processMessage(message) {\n var firstChar = message.charAt(0);\n if (firstChar == 'J') {\n // This is deprecated on the .java side. It doesn't work with CSP enabled.\n eval(message.slice(1));\n } else if (firstChar == 'S' || firstChar == 'F') {\n var success = firstChar == 'S';\n var keepCallback = message.charAt(1) == '1';\n var spaceIdx = message.indexOf(' ', 2);\n var status = +message.slice(2, spaceIdx);\n var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1);\n var callbackId = message.slice(spaceIdx + 1, nextSpaceIdx);\n var payloadMessage = message.slice(nextSpaceIdx + 1);\n var payload = [];\n buildPayload(payload, payloadMessage);\n cordova.callbackFromNative(callbackId, success, status, payload, keepCallback);\n } else {\n console.log(\"processMessage failed: invalid message: \" + JSON.stringify(message));\n }\n}", "language": "javascript", "code": "function processMessage(message) {\n var firstChar = message.charAt(0);\n if (firstChar == 'J') {\n // This is deprecated on the .java side. It doesn't work with CSP enabled.\n eval(message.slice(1));\n } else if (firstChar == 'S' || firstChar == 'F') {\n var success = firstChar == 'S';\n var keepCallback = message.charAt(1) == '1';\n var spaceIdx = message.indexOf(' ', 2);\n var status = +message.slice(2, spaceIdx);\n var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1);\n var callbackId = message.slice(spaceIdx + 1, nextSpaceIdx);\n var payloadMessage = message.slice(nextSpaceIdx + 1);\n var payload = [];\n buildPayload(payload, payloadMessage);\n cordova.callbackFromNative(callbackId, success, status, payload, keepCallback);\n } else {\n console.log(\"processMessage failed: invalid message: \" + JSON.stringify(message));\n }\n}", "code_tokens": ["function", "processMessage", "(", "message", ")", "{", "var", "firstChar", "=", "message", ".", "charAt", "(", "0", ")", ";", "if", "(", "firstChar", "==", "'J'", ")", "{", "eval", "(", "message", ".", "slice", "(", "1", ")", ")", ";", "}", "else", "if", "(", "firstChar", "==", "'S'", "||", "firstChar", "==", "'F'", ")", "{", "var", "success", "=", "firstChar", "==", "'S'", ";", "var", "keepCallback", "=", "message", ".", "charAt", "(", "1", ")", "==", "'1'", ";", "var", "spaceIdx", "=", "message", ".", "indexOf", "(", "' '", ",", "2", ")", ";", "var", "status", "=", "+", "message", ".", "slice", "(", "2", ",", "spaceIdx", ")", ";", "var", "nextSpaceIdx", "=", "message", ".", "indexOf", "(", "' '", ",", "spaceIdx", "+", "1", ")", ";", "var", "callbackId", "=", "message", ".", "slice", "(", "spaceIdx", "+", "1", ",", "nextSpaceIdx", ")", ";", "var", "payloadMessage", "=", "message", ".", "slice", "(", "nextSpaceIdx", "+", "1", ")", ";", "var", "payload", "=", "[", "]", ";", "buildPayload", "(", "payload", ",", "payloadMessage", ")", ";", "cordova", ".", "callbackFromNative", "(", "callbackId", ",", "success", ",", "status", ",", "payload", ",", "keepCallback", ")", ";", "}", "else", "{", "console", ".", "log", "(", "\"processMessage failed: invalid message: \"", "+", "JSON", ".", "stringify", "(", "message", ")", ")", ";", "}", "}"], "docstring": "Processes a single message, as encoded by NativeToJsMessageQueue.java.", "docstring_tokens": ["Processes", "a", "single", "message", "as", "encoded", "by", "NativeToJsMessageQueue", ".", "java", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/plugman/projects/android/platform_www/cordova-js-src/exec.js#L234-L253", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/plugman/install.js", "func_name": "callEngineScripts", "original_string": "function callEngineScripts (engines, project_dir) {\n\n return Promise.all(\n engines.map(function (engine) {\n // CB-5192; on Windows scriptSrc doesn't have file extension so we shouldn't check whether the script exists\n var scriptPath = engine.scriptSrc || null;\n if (scriptPath && (isWindows || fs.existsSync(engine.scriptSrc))) {\n\n if (!isWindows) { // not required on Windows\n fs.chmodSync(engine.scriptSrc, '755');\n }\n return superspawn.spawn(scriptPath)\n .then(stdout => {\n engine.currentVersion = cleanVersionOutput(stdout, engine.name);\n if (engine.currentVersion === '') {\n events.emit('warn', engine.name + ' version check returned nothing (' + scriptPath + '), continuing anyways.');\n engine.currentVersion = null;\n }\n }, () => {\n events.emit('warn', engine.name + ' version check failed (' + scriptPath + '), continuing anyways.');\n engine.currentVersion = null;\n })\n .then(_ => engine);\n } else {\n\n if (engine.currentVersion) {\n engine.currentVersion = cleanVersionOutput(engine.currentVersion, engine.name);\n } else {\n events.emit('warn', engine.name + ' version not detected (lacks script ' + scriptPath + ' ), continuing.');\n }\n\n return Promise.resolve(engine);\n }\n })\n );\n}", "language": "javascript", "code": "function callEngineScripts (engines, project_dir) {\n\n return Promise.all(\n engines.map(function (engine) {\n // CB-5192; on Windows scriptSrc doesn't have file extension so we shouldn't check whether the script exists\n var scriptPath = engine.scriptSrc || null;\n if (scriptPath && (isWindows || fs.existsSync(engine.scriptSrc))) {\n\n if (!isWindows) { // not required on Windows\n fs.chmodSync(engine.scriptSrc, '755');\n }\n return superspawn.spawn(scriptPath)\n .then(stdout => {\n engine.currentVersion = cleanVersionOutput(stdout, engine.name);\n if (engine.currentVersion === '') {\n events.emit('warn', engine.name + ' version check returned nothing (' + scriptPath + '), continuing anyways.');\n engine.currentVersion = null;\n }\n }, () => {\n events.emit('warn', engine.name + ' version check failed (' + scriptPath + '), continuing anyways.');\n engine.currentVersion = null;\n })\n .then(_ => engine);\n } else {\n\n if (engine.currentVersion) {\n engine.currentVersion = cleanVersionOutput(engine.currentVersion, engine.name);\n } else {\n events.emit('warn', engine.name + ' version not detected (lacks script ' + scriptPath + ' ), continuing.');\n }\n\n return Promise.resolve(engine);\n }\n })\n );\n}", "code_tokens": ["function", "callEngineScripts", "(", "engines", ",", "project_dir", ")", "{", "return", "Promise", ".", "all", "(", "engines", ".", "map", "(", "function", "(", "engine", ")", "{", "var", "scriptPath", "=", "engine", ".", "scriptSrc", "||", "null", ";", "if", "(", "scriptPath", "&&", "(", "isWindows", "||", "fs", ".", "existsSync", "(", "engine", ".", "scriptSrc", ")", ")", ")", "{", "if", "(", "!", "isWindows", ")", "{", "fs", ".", "chmodSync", "(", "engine", ".", "scriptSrc", ",", "'755'", ")", ";", "}", "return", "superspawn", ".", "spawn", "(", "scriptPath", ")", ".", "then", "(", "stdout", "=>", "{", "engine", ".", "currentVersion", "=", "cleanVersionOutput", "(", "stdout", ",", "engine", ".", "name", ")", ";", "if", "(", "engine", ".", "currentVersion", "===", "''", ")", "{", "events", ".", "emit", "(", "'warn'", ",", "engine", ".", "name", "+", "' version check returned nothing ('", "+", "scriptPath", "+", "'), continuing anyways.'", ")", ";", "engine", ".", "currentVersion", "=", "null", ";", "}", "}", ",", "(", ")", "=>", "{", "events", ".", "emit", "(", "'warn'", ",", "engine", ".", "name", "+", "' version check failed ('", "+", "scriptPath", "+", "'), continuing anyways.'", ")", ";", "engine", ".", "currentVersion", "=", "null", ";", "}", ")", ".", "then", "(", "_", "=>", "engine", ")", ";", "}", "else", "{", "if", "(", "engine", ".", "currentVersion", ")", "{", "engine", ".", "currentVersion", "=", "cleanVersionOutput", "(", "engine", ".", "currentVersion", ",", "engine", ".", "name", ")", ";", "}", "else", "{", "events", ".", "emit", "(", "'warn'", ",", "engine", ".", "name", "+", "' version not detected (lacks script '", "+", "scriptPath", "+", "' ), continuing.'", ")", ";", "}", "return", "Promise", ".", "resolve", "(", "engine", ")", ";", "}", "}", ")", ")", ";", "}"], "docstring": "exec engine scripts in order to get the current engine version Returns a promise for the array of engines.", "docstring_tokens": ["exec", "engine", "scripts", "in", "order", "to", "get", "the", "current", "engine", "version", "Returns", "a", "promise", "for", "the", "array", "of", "engines", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/plugman/install.js#L163-L198", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/plugman/createpackagejson.js", "func_name": "createPackageJson", "original_string": "function createPackageJson (plugin_path) {\n var pluginInfo = new PluginInfo(plugin_path);\n\n var defaults = {\n id: pluginInfo.id,\n version: pluginInfo.version,\n description: pluginInfo.description,\n license: pluginInfo.license,\n keywords: pluginInfo.getKeywordsAndPlatforms(),\n repository: pluginInfo.repo,\n engines: pluginInfo.getEngines(),\n platforms: pluginInfo.getPlatformsArray()\n };\n\n var initFile = require.resolve('./init-defaults');\n return initPkgJson(plugin_path, initFile, defaults)\n .then(_ => {\n events.emit('verbose', 'Package.json successfully created');\n });\n}", "language": "javascript", "code": "function createPackageJson (plugin_path) {\n var pluginInfo = new PluginInfo(plugin_path);\n\n var defaults = {\n id: pluginInfo.id,\n version: pluginInfo.version,\n description: pluginInfo.description,\n license: pluginInfo.license,\n keywords: pluginInfo.getKeywordsAndPlatforms(),\n repository: pluginInfo.repo,\n engines: pluginInfo.getEngines(),\n platforms: pluginInfo.getPlatformsArray()\n };\n\n var initFile = require.resolve('./init-defaults');\n return initPkgJson(plugin_path, initFile, defaults)\n .then(_ => {\n events.emit('verbose', 'Package.json successfully created');\n });\n}", "code_tokens": ["function", "createPackageJson", "(", "plugin_path", ")", "{", "var", "pluginInfo", "=", "new", "PluginInfo", "(", "plugin_path", ")", ";", "var", "defaults", "=", "{", "id", ":", "pluginInfo", ".", "id", ",", "version", ":", "pluginInfo", ".", "version", ",", "description", ":", "pluginInfo", ".", "description", ",", "license", ":", "pluginInfo", ".", "license", ",", "keywords", ":", "pluginInfo", ".", "getKeywordsAndPlatforms", "(", ")", ",", "repository", ":", "pluginInfo", ".", "repo", ",", "engines", ":", "pluginInfo", ".", "getEngines", "(", ")", ",", "platforms", ":", "pluginInfo", ".", "getPlatformsArray", "(", ")", "}", ";", "var", "initFile", "=", "require", ".", "resolve", "(", "'./init-defaults'", ")", ";", "return", "initPkgJson", "(", "plugin_path", ",", "initFile", ",", "defaults", ")", ".", "then", "(", "_", "=>", "{", "events", ".", "emit", "(", "'verbose'", ",", "'Package.json successfully created'", ")", ";", "}", ")", ";", "}"], "docstring": "returns a promise", "docstring_tokens": ["returns", "a", "promise"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/plugman/createpackagejson.js#L26-L45", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/prepare.js", "func_name": "preparePlatforms", "original_string": "function preparePlatforms (platformList, projectRoot, options) {\n return Promise.all(platformList.map(function (platform) {\n // TODO: this need to be replaced by real projectInfo\n // instance for current project.\n var project = {\n root: projectRoot,\n projectConfig: new ConfigParser(cordova_util.projectConfig(projectRoot)),\n locations: {\n plugins: path.join(projectRoot, 'plugins'),\n www: cordova_util.projectWww(projectRoot),\n rootConfigXml: cordova_util.projectConfig(projectRoot)\n }\n };\n // CB-9987 We need to reinstall the plugins for the platform it they were added by cordova@<5.4.0\n return module.exports.restoreMissingPluginsForPlatform(platform, projectRoot, options)\n .then(function () {\n // platformApi prepare takes care of all functionality\n // which previously had been executed by cordova.prepare:\n // - reset config.xml and then merge changes from project's one,\n // - update www directory from project's one and merge assets from platform_www,\n // - reapply config changes, made by plugins,\n // - update platform's project\n // Please note that plugins' changes, such as installed js files, assets and\n // config changes is not being reinstalled on each prepare.\n var platformApi = platforms.getPlatformApi(platform);\n return platformApi.prepare(project, _.clone(options))\n .then(function () {\n // Handle edit-config in config.xml\n var platformRoot = path.join(projectRoot, 'platforms', platform);\n var platformJson = PlatformJson.load(platformRoot, platform);\n var munger = new PlatformMunger(platform, platformRoot, platformJson);\n // the boolean argument below is \"should_increment\"\n munger.add_config_changes(project.projectConfig, true).save_all();\n });\n });\n }));\n}", "language": "javascript", "code": "function preparePlatforms (platformList, projectRoot, options) {\n return Promise.all(platformList.map(function (platform) {\n // TODO: this need to be replaced by real projectInfo\n // instance for current project.\n var project = {\n root: projectRoot,\n projectConfig: new ConfigParser(cordova_util.projectConfig(projectRoot)),\n locations: {\n plugins: path.join(projectRoot, 'plugins'),\n www: cordova_util.projectWww(projectRoot),\n rootConfigXml: cordova_util.projectConfig(projectRoot)\n }\n };\n // CB-9987 We need to reinstall the plugins for the platform it they were added by cordova@<5.4.0\n return module.exports.restoreMissingPluginsForPlatform(platform, projectRoot, options)\n .then(function () {\n // platformApi prepare takes care of all functionality\n // which previously had been executed by cordova.prepare:\n // - reset config.xml and then merge changes from project's one,\n // - update www directory from project's one and merge assets from platform_www,\n // - reapply config changes, made by plugins,\n // - update platform's project\n // Please note that plugins' changes, such as installed js files, assets and\n // config changes is not being reinstalled on each prepare.\n var platformApi = platforms.getPlatformApi(platform);\n return platformApi.prepare(project, _.clone(options))\n .then(function () {\n // Handle edit-config in config.xml\n var platformRoot = path.join(projectRoot, 'platforms', platform);\n var platformJson = PlatformJson.load(platformRoot, platform);\n var munger = new PlatformMunger(platform, platformRoot, platformJson);\n // the boolean argument below is \"should_increment\"\n munger.add_config_changes(project.projectConfig, true).save_all();\n });\n });\n }));\n}", "code_tokens": ["function", "preparePlatforms", "(", "platformList", ",", "projectRoot", ",", "options", ")", "{", "return", "Promise", ".", "all", "(", "platformList", ".", "map", "(", "function", "(", "platform", ")", "{", "var", "project", "=", "{", "root", ":", "projectRoot", ",", "projectConfig", ":", "new", "ConfigParser", "(", "cordova_util", ".", "projectConfig", "(", "projectRoot", ")", ")", ",", "locations", ":", "{", "plugins", ":", "path", ".", "join", "(", "projectRoot", ",", "'plugins'", ")", ",", "www", ":", "cordova_util", ".", "projectWww", "(", "projectRoot", ")", ",", "rootConfigXml", ":", "cordova_util", ".", "projectConfig", "(", "projectRoot", ")", "}", "}", ";", "return", "module", ".", "exports", ".", "restoreMissingPluginsForPlatform", "(", "platform", ",", "projectRoot", ",", "options", ")", ".", "then", "(", "function", "(", ")", "{", "var", "platformApi", "=", "platforms", ".", "getPlatformApi", "(", "platform", ")", ";", "return", "platformApi", ".", "prepare", "(", "project", ",", "_", ".", "clone", "(", "options", ")", ")", ".", "then", "(", "function", "(", ")", "{", "var", "platformRoot", "=", "path", ".", "join", "(", "projectRoot", ",", "'platforms'", ",", "platform", ")", ";", "var", "platformJson", "=", "PlatformJson", ".", "load", "(", "platformRoot", ",", "platform", ")", ";", "var", "munger", "=", "new", "PlatformMunger", "(", "platform", ",", "platformRoot", ",", "platformJson", ")", ";", "munger", ".", "add_config_changes", "(", "project", ".", "projectConfig", ",", "true", ")", ".", "save_all", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ")", ";", "}"], "docstring": "Calls `platformApi.prepare` for each platform in project\n\n@param {string[]} platformList List of platforms, added to current project\n@param {string} projectRoot Project root directory\n\n@return {Promise}", "docstring_tokens": ["Calls", "platformApi", ".", "prepare", "for", "each", "platform", "in", "project"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/prepare.js#L80-L116", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/plugman/projects/android/cordova/lib/prepare.js", "func_name": "", "original_string": "function(icon, icon_size) {\n // do I have a platform icon for that density already\n var density = icon.density || sizeToDensityMap[icon_size];\n if (!density) {\n // invalid icon defition ( or unsupported size)\n return;\n }\n var previous = android_icons[density];\n if (previous && previous.platform) {\n return;\n }\n android_icons[density] = icon;\n }", "language": "javascript", "code": "function(icon, icon_size) {\n // do I have a platform icon for that density already\n var density = icon.density || sizeToDensityMap[icon_size];\n if (!density) {\n // invalid icon defition ( or unsupported size)\n return;\n }\n var previous = android_icons[density];\n if (previous && previous.platform) {\n return;\n }\n android_icons[density] = icon;\n }", "code_tokens": ["function", "(", "icon", ",", "icon_size", ")", "{", "var", "density", "=", "icon", ".", "density", "||", "sizeToDensityMap", "[", "icon_size", "]", ";", "if", "(", "!", "density", ")", "{", "return", ";", "}", "var", "previous", "=", "android_icons", "[", "density", "]", ";", "if", "(", "previous", "&&", "previous", ".", "platform", ")", "{", "return", ";", "}", "android_icons", "[", "density", "]", "=", "icon", ";", "}"], "docstring": "find the best matching icon for a given density or size @output android_icons", "docstring_tokens": ["find", "the", "best", "matching", "icon", "for", "a", "given", "density", "or", "size"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/plugman/projects/android/cordova/lib/prepare.js#L329-L341", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/plugman/projects/android/cordova/lib/prepare.js", "func_name": "mapImageResources", "original_string": "function mapImageResources(rootDir, subDir, type, resourceName) {\n var pathMap = {};\n shell.ls(path.join(rootDir, subDir, type + '-*'))\n .forEach(function (drawableFolder) {\n var imagePath = path.join(subDir, path.basename(drawableFolder), resourceName);\n pathMap[imagePath] = null;\n });\n return pathMap;\n}", "language": "javascript", "code": "function mapImageResources(rootDir, subDir, type, resourceName) {\n var pathMap = {};\n shell.ls(path.join(rootDir, subDir, type + '-*'))\n .forEach(function (drawableFolder) {\n var imagePath = path.join(subDir, path.basename(drawableFolder), resourceName);\n pathMap[imagePath] = null;\n });\n return pathMap;\n}", "code_tokens": ["function", "mapImageResources", "(", "rootDir", ",", "subDir", ",", "type", ",", "resourceName", ")", "{", "var", "pathMap", "=", "{", "}", ";", "shell", ".", "ls", "(", "path", ".", "join", "(", "rootDir", ",", "subDir", ",", "type", "+", "'-*'", ")", ")", ".", "forEach", "(", "function", "(", "drawableFolder", ")", "{", "var", "imagePath", "=", "path", ".", "join", "(", "subDir", ",", "path", ".", "basename", "(", "drawableFolder", ")", ",", "resourceName", ")", ";", "pathMap", "[", "imagePath", "]", "=", "null", ";", "}", ")", ";", "return", "pathMap", ";", "}"], "docstring": "Gets a map containing resources of a specified name from all drawable folders in a directory.", "docstring_tokens": ["Gets", "a", "map", "containing", "resources", "of", "a", "specified", "name", "from", "all", "drawable", "folders", "in", "a", "directory", "."], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/plugman/projects/android/cordova/lib/prepare.js#L396-L404", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/plugman/projects/android/cordova/lib/prepare.js", "func_name": "findAndroidLaunchModePreference", "original_string": "function findAndroidLaunchModePreference(platformConfig) {\n var launchMode = platformConfig.getPreference('AndroidLaunchMode');\n if (!launchMode) {\n // Return a default value\n return 'singleTop';\n }\n\n var expectedValues = ['standard', 'singleTop', 'singleTask', 'singleInstance'];\n var valid = expectedValues.indexOf(launchMode) >= 0;\n if (!valid) {\n // Note: warn, but leave the launch mode as developer wanted, in case the list of options changes in the future\n events.emit('warn', 'Unrecognized value for AndroidLaunchMode preference: ' +\n launchMode + '. Expected values are: ' + expectedValues.join(', '));\n }\n\n return launchMode;\n}", "language": "javascript", "code": "function findAndroidLaunchModePreference(platformConfig) {\n var launchMode = platformConfig.getPreference('AndroidLaunchMode');\n if (!launchMode) {\n // Return a default value\n return 'singleTop';\n }\n\n var expectedValues = ['standard', 'singleTop', 'singleTask', 'singleInstance'];\n var valid = expectedValues.indexOf(launchMode) >= 0;\n if (!valid) {\n // Note: warn, but leave the launch mode as developer wanted, in case the list of options changes in the future\n events.emit('warn', 'Unrecognized value for AndroidLaunchMode preference: ' +\n launchMode + '. Expected values are: ' + expectedValues.join(', '));\n }\n\n return launchMode;\n}", "code_tokens": ["function", "findAndroidLaunchModePreference", "(", "platformConfig", ")", "{", "var", "launchMode", "=", "platformConfig", ".", "getPreference", "(", "'AndroidLaunchMode'", ")", ";", "if", "(", "!", "launchMode", ")", "{", "return", "'singleTop'", ";", "}", "var", "expectedValues", "=", "[", "'standard'", ",", "'singleTop'", ",", "'singleTask'", ",", "'singleInstance'", "]", ";", "var", "valid", "=", "expectedValues", ".", "indexOf", "(", "launchMode", ")", ">=", "0", ";", "if", "(", "!", "valid", ")", "{", "events", ".", "emit", "(", "'warn'", ",", "'Unrecognized value for AndroidLaunchMode preference: '", "+", "launchMode", "+", "'. Expected values are: '", "+", "expectedValues", ".", "join", "(", "', '", ")", ")", ";", "}", "return", "launchMode", ";", "}"], "docstring": "Gets and validates 'AndroidLaunchMode' prepference from config.xml. Returns\npreference value and warns if it doesn't seems to be valid\n\n@param {ConfigParser} platformConfig A configParser instance for\nplatform.\n\n@return {String} Preference's value from config.xml or\ndefault value, if there is no such preference. The default value is\n'singleTop'", "docstring_tokens": ["Gets", "and", "validates", "AndroidLaunchMode", "prepference", "from", "config", ".", "xml", ".", "Returns", "preference", "value", "and", "warns", "if", "it", "doesn", "t", "seems", "to", "be", "valid"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/plugman/projects/android/cordova/lib/prepare.js#L455-L471", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/plugman/projects/android/cordova/lib/AndroidManifest.js", "func_name": "AndroidManifest", "original_string": "function AndroidManifest(path) {\n this.path = path;\n this.doc = xml.parseElementtreeSync(path);\n if (this.doc.getroot().tag !== 'manifest') {\n throw new Error('AndroidManifest at ' + path + ' has incorrect root node name (expected \"manifest\")');\n }\n}", "language": "javascript", "code": "function AndroidManifest(path) {\n this.path = path;\n this.doc = xml.parseElementtreeSync(path);\n if (this.doc.getroot().tag !== 'manifest') {\n throw new Error('AndroidManifest at ' + path + ' has incorrect root node name (expected \"manifest\")');\n }\n}", "code_tokens": ["function", "AndroidManifest", "(", "path", ")", "{", "this", ".", "path", "=", "path", ";", "this", ".", "doc", "=", "xml", ".", "parseElementtreeSync", "(", "path", ")", ";", "if", "(", "this", ".", "doc", ".", "getroot", "(", ")", ".", "tag", "!==", "'manifest'", ")", "{", "throw", "new", "Error", "(", "'AndroidManifest at '", "+", "path", "+", "' has incorrect root node name (expected \"manifest\")'", ")", ";", "}", "}"], "docstring": "Wraps an AndroidManifest file", "docstring_tokens": ["Wraps", "an", "AndroidManifest", "file"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/plugman/projects/android/cordova/lib/AndroidManifest.js#L27-L33", "partition": "test"} {"repo": "apache/cordova-lib", "path": "spec/cordova/plugin/add.getFetchVersion.spec.js", "func_name": "expectUnmetRequirements", "original_string": "function expectUnmetRequirements (expected) {\n const actual = unmetRequirementsCollector.store;\n expect(actual).toEqual(jasmine.arrayWithExactContents(expected));\n}", "language": "javascript", "code": "function expectUnmetRequirements (expected) {\n const actual = unmetRequirementsCollector.store;\n expect(actual).toEqual(jasmine.arrayWithExactContents(expected));\n}", "code_tokens": ["function", "expectUnmetRequirements", "(", "expected", ")", "{", "const", "actual", "=", "unmetRequirementsCollector", ".", "store", ";", "expect", "(", "actual", ")", ".", "toEqual", "(", "jasmine", ".", "arrayWithExactContents", "(", "expected", ")", ")", ";", "}"], "docstring": "Checks the warnings that were printed by the CLI to ensure that the code is listing the correct reasons for failure. Checks against the global warnings object which is reset before each test", "docstring_tokens": ["Checks", "the", "warnings", "that", "were", "printed", "by", "the", "CLI", "to", "ensure", "that", "the", "code", "is", "listing", "the", "correct", "reasons", "for", "failure", ".", "Checks", "against", "the", "global", "warnings", "object", "which", "is", "reset", "before", "each", "test"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/spec/cordova/plugin/add.getFetchVersion.spec.js#L45-L48", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/plugin/add.js", "func_name": "findVersion", "original_string": "function findVersion (versions, version) {\n var cleanedVersion = semver.clean(version);\n for (var i = 0; i < versions.length; i++) {\n if (semver.clean(versions[i]) === cleanedVersion) {\n return versions[i];\n }\n }\n return null;\n}", "language": "javascript", "code": "function findVersion (versions, version) {\n var cleanedVersion = semver.clean(version);\n for (var i = 0; i < versions.length; i++) {\n if (semver.clean(versions[i]) === cleanedVersion) {\n return versions[i];\n }\n }\n return null;\n}", "code_tokens": ["function", "findVersion", "(", "versions", ",", "version", ")", "{", "var", "cleanedVersion", "=", "semver", ".", "clean", "(", "version", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "versions", ".", "length", ";", "i", "++", ")", "{", "if", "(", "semver", ".", "clean", "(", "versions", "[", "i", "]", ")", "===", "cleanedVersion", ")", "{", "return", "versions", "[", "i", "]", ";", "}", "}", "return", "null", ";", "}"], "docstring": "return the version if it is in the versions array return null if the version doesn't exist in the array", "docstring_tokens": ["return", "the", "version", "if", "it", "is", "in", "the", "versions", "array", "return", "null", "if", "the", "version", "doesn", "t", "exist", "in", "the", "array"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/plugin/add.js#L545-L553", "partition": "test"} {"repo": "apache/cordova-lib", "path": "src/cordova/plugin/add.js", "func_name": "listUnmetRequirements", "original_string": "function listUnmetRequirements (name, failedRequirements) {\n events.emit('warn', 'Unmet project requirements for latest version of ' + name + ':');\n\n failedRequirements.forEach(function (req) {\n events.emit('warn', ' ' + req.dependency + ' (' + req.installed + ' in project, ' + req.required + ' required)');\n });\n}", "language": "javascript", "code": "function listUnmetRequirements (name, failedRequirements) {\n events.emit('warn', 'Unmet project requirements for latest version of ' + name + ':');\n\n failedRequirements.forEach(function (req) {\n events.emit('warn', ' ' + req.dependency + ' (' + req.installed + ' in project, ' + req.required + ' required)');\n });\n}", "code_tokens": ["function", "listUnmetRequirements", "(", "name", ",", "failedRequirements", ")", "{", "events", ".", "emit", "(", "'warn'", ",", "'Unmet project requirements for latest version of '", "+", "name", "+", "':'", ")", ";", "failedRequirements", ".", "forEach", "(", "function", "(", "req", ")", "{", "events", ".", "emit", "(", "'warn'", ",", "' '", "+", "req", ".", "dependency", "+", "' ('", "+", "req", ".", "installed", "+", "' in project, '", "+", "req", ".", "required", "+", "' required)'", ")", ";", "}", ")", ";", "}"], "docstring": "emits warnings to users of failed dependnecy requirements in their projects", "docstring_tokens": ["emits", "warnings", "to", "users", "of", "failed", "dependnecy", "requirements", "in", "their", "projects"], "sha": "dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5", "url": "https://github.com/apache/cordova-lib/blob/dbab1acbd3d5c2d3248c8aca91cbb7518e197ae5/src/cordova/plugin/add.js#L556-L562", "partition": "test"} {"repo": "Microsoft/azure-pipelines-extensions", "path": "package.js", "func_name": "", "original_string": "function(folderName, task) {\r\n var defer = Q.defer();\r\n\r\n var vn = (task.name || folderName);\r\n\r\n if (!task.id || !check.isUUID(task.id)) {\r\n defer.reject(createError(vn + ': id is a required guid'));\r\n };\r\n\r\n if (!task.name || !check.isAlphanumeric(task.name)) {\r\n defer.reject(createError(vn + ': name is a required alphanumeric string'));\r\n }\r\n\r\n if (!task.friendlyName || !check.isLength(task.friendlyName, 1, 40)) {\r\n defer.reject(createError(vn + ': friendlyName is a required string <= 40 chars'));\r\n }\r\n\r\n if (!task.instanceNameFormat) {\r\n defer.reject(createError(vn + ': instanceNameFormat is required')); \r\n }\r\n\r\n // resolve if not already rejected\r\n defer.resolve();\r\n return defer.promise;\r\n}", "language": "javascript", "code": "function(folderName, task) {\r\n var defer = Q.defer();\r\n\r\n var vn = (task.name || folderName);\r\n\r\n if (!task.id || !check.isUUID(task.id)) {\r\n defer.reject(createError(vn + ': id is a required guid'));\r\n };\r\n\r\n if (!task.name || !check.isAlphanumeric(task.name)) {\r\n defer.reject(createError(vn + ': name is a required alphanumeric string'));\r\n }\r\n\r\n if (!task.friendlyName || !check.isLength(task.friendlyName, 1, 40)) {\r\n defer.reject(createError(vn + ': friendlyName is a required string <= 40 chars'));\r\n }\r\n\r\n if (!task.instanceNameFormat) {\r\n defer.reject(createError(vn + ': instanceNameFormat is required')); \r\n }\r\n\r\n // resolve if not already rejected\r\n defer.resolve();\r\n return defer.promise;\r\n}", "code_tokens": ["function", "(", "folderName", ",", "task", ")", "{", "var", "defer", "=", "Q", ".", "defer", "(", ")", ";", "var", "vn", "=", "(", "task", ".", "name", "||", "folderName", ")", ";", "if", "(", "!", "task", ".", "id", "||", "!", "check", ".", "isUUID", "(", "task", ".", "id", ")", ")", "{", "defer", ".", "reject", "(", "createError", "(", "vn", "+", "': id is a required guid'", ")", ")", ";", "}", ";", "if", "(", "!", "task", ".", "name", "||", "!", "check", ".", "isAlphanumeric", "(", "task", ".", "name", ")", ")", "{", "defer", ".", "reject", "(", "createError", "(", "vn", "+", "': name is a required alphanumeric string'", ")", ")", ";", "}", "if", "(", "!", "task", ".", "friendlyName", "||", "!", "check", ".", "isLength", "(", "task", ".", "friendlyName", ",", "1", ",", "40", ")", ")", "{", "defer", ".", "reject", "(", "createError", "(", "vn", "+", "': friendlyName is a required string <= 40 chars'", ")", ")", ";", "}", "if", "(", "!", "task", ".", "instanceNameFormat", ")", "{", "defer", ".", "reject", "(", "createError", "(", "vn", "+", "': instanceNameFormat is required'", ")", ")", ";", "}", "defer", ".", "resolve", "(", ")", ";", "return", "defer", ".", "promise", ";", "}"], "docstring": "Validates the structure of a task.json file.", "docstring_tokens": ["Validates", "the", "structure", "of", "a", "task", ".", "json", "file", "."], "sha": "be2b1c4772ec5c67958915d0f3ecb8509ea93d43", "url": "https://github.com/Microsoft/azure-pipelines-extensions/blob/be2b1c4772ec5c67958915d0f3ecb8509ea93d43/package.js#L22-L46", "partition": "test"} {"repo": "greenkeeperio/greenkeeper", "path": "utils/utils.js", "func_name": "", "original_string": "function (travisYML, newVersion, newCodeName, existingVersions) {\n // Should only add the new version if it is not present in any form\n if (existingVersions.versions.length === 0) return travisYML\n const nodeVersionIndex = getNodeVersionIndex(existingVersions.versions, newVersion, newCodeName)\n const travisYMLLines = travisYML.split('\\n')\n // We only need to do something if the new version isn\u2019t present\n if (nodeVersionIndex === -1) {\n let delimiter = ''\n let leadingSpaces = ''\n if (existingVersions.versions && existingVersions.versions.length > 0) {\n if (existingVersions.versions[0].match(/\"/)) {\n delimiter = '\"'\n }\n if (existingVersions.versions[0].match(/'/)) {\n delimiter = \"'\"\n }\n leadingSpaces = existingVersions.versions[0].match(/^([ ]*)/)[1]\n }\n // splice the new version back onto the end of the node version list in the original travisYMLLines array,\n // unless it wasn\u2019t an array but an inline definition of a single version, eg: `node_js: 9`\n if (existingVersions.versions.length === 1 && existingVersions.startIndex === existingVersions.endIndex) {\n // A single node version was defined in inline format, now we want to define two versions in array format\n travisYMLLines.splice(existingVersions.startIndex, 1, 'node_js:')\n travisYMLLines.splice(existingVersions.startIndex + 1, 0, `${leadingSpaces}- ${existingVersions.versions[0]}`)\n travisYMLLines.splice(existingVersions.startIndex + 2, 0, `${leadingSpaces}- ${delimiter}${newVersion}${delimiter}`)\n } else {\n // Multiple node versions were defined in array format\n travisYMLLines.splice(existingVersions.endIndex + 1, 0, `${leadingSpaces}- ${delimiter}${newVersion}${delimiter}`)\n }\n }\n return travisYMLLines.join('\\n')\n}", "language": "javascript", "code": "function (travisYML, newVersion, newCodeName, existingVersions) {\n // Should only add the new version if it is not present in any form\n if (existingVersions.versions.length === 0) return travisYML\n const nodeVersionIndex = getNodeVersionIndex(existingVersions.versions, newVersion, newCodeName)\n const travisYMLLines = travisYML.split('\\n')\n // We only need to do something if the new version isn\u2019t present\n if (nodeVersionIndex === -1) {\n let delimiter = ''\n let leadingSpaces = ''\n if (existingVersions.versions && existingVersions.versions.length > 0) {\n if (existingVersions.versions[0].match(/\"/)) {\n delimiter = '\"'\n }\n if (existingVersions.versions[0].match(/'/)) {\n delimiter = \"'\"\n }\n leadingSpaces = existingVersions.versions[0].match(/^([ ]*)/)[1]\n }\n // splice the new version back onto the end of the node version list in the original travisYMLLines array,\n // unless it wasn\u2019t an array but an inline definition of a single version, eg: `node_js: 9`\n if (existingVersions.versions.length === 1 && existingVersions.startIndex === existingVersions.endIndex) {\n // A single node version was defined in inline format, now we want to define two versions in array format\n travisYMLLines.splice(existingVersions.startIndex, 1, 'node_js:')\n travisYMLLines.splice(existingVersions.startIndex + 1, 0, `${leadingSpaces}- ${existingVersions.versions[0]}`)\n travisYMLLines.splice(existingVersions.startIndex + 2, 0, `${leadingSpaces}- ${delimiter}${newVersion}${delimiter}`)\n } else {\n // Multiple node versions were defined in array format\n travisYMLLines.splice(existingVersions.endIndex + 1, 0, `${leadingSpaces}- ${delimiter}${newVersion}${delimiter}`)\n }\n }\n return travisYMLLines.join('\\n')\n}", "code_tokens": ["function", "(", "travisYML", ",", "newVersion", ",", "newCodeName", ",", "existingVersions", ")", "{", "if", "(", "existingVersions", ".", "versions", ".", "length", "===", "0", ")", "return", "travisYML", "const", "nodeVersionIndex", "=", "getNodeVersionIndex", "(", "existingVersions", ".", "versions", ",", "newVersion", ",", "newCodeName", ")", "const", "travisYMLLines", "=", "travisYML", ".", "split", "(", "'\\n'", ")", "\\n", "if", "(", "nodeVersionIndex", "===", "-", "1", ")", "{", "let", "delimiter", "=", "''", "let", "leadingSpaces", "=", "''", "if", "(", "existingVersions", ".", "versions", "&&", "existingVersions", ".", "versions", ".", "length", ">", "0", ")", "{", "if", "(", "existingVersions", ".", "versions", "[", "0", "]", ".", "match", "(", "/", "\"", "/", ")", ")", "{", "delimiter", "=", "'\"'", "}", "if", "(", "existingVersions", ".", "versions", "[", "0", "]", ".", "match", "(", "/", "'", "/", ")", ")", "{", "delimiter", "=", "\"'\"", "}", "leadingSpaces", "=", "existingVersions", ".", "versions", "[", "0", "]", ".", "match", "(", "/", "^([ ]*)", "/", ")", "[", "1", "]", "}", "if", "(", "existingVersions", ".", "versions", ".", "length", "===", "1", "&&", "existingVersions", ".", "startIndex", "===", "existingVersions", ".", "endIndex", ")", "{", "travisYMLLines", ".", "splice", "(", "existingVersions", ".", "startIndex", ",", "1", ",", "'node_js:'", ")", "travisYMLLines", ".", "splice", "(", "existingVersions", ".", "startIndex", "+", "1", ",", "0", ",", "`", "${", "leadingSpaces", "}", "${", "existingVersions", ".", "versions", "[", "0", "]", "}", "`", ")", "travisYMLLines", ".", "splice", "(", "existingVersions", ".", "startIndex", "+", "2", ",", "0", ",", "`", "${", "leadingSpaces", "}", "${", "delimiter", "}", "${", "newVersion", "}", "${", "delimiter", "}", "`", ")", "}", "else", "{", "travisYMLLines", ".", "splice", "(", "existingVersions", ".", "endIndex", "+", "1", ",", "0", ",", "`", "${", "leadingSpaces", "}", "${", "delimiter", "}", "${", "newVersion", "}", "${", "delimiter", "}", "`", ")", "}", "}", "}"], "docstring": "Stop! YAMLtime! existingVersions is the output of getNodeVersionsFromTravisYML", "docstring_tokens": ["Stop!", "YAMLtime!", "existingVersions", "is", "the", "output", "of", "getNodeVersionsFromTravisYML"], "sha": "7ff179ce7b3381f8be7d52003e2741a700964284", "url": "https://github.com/greenkeeperio/greenkeeper/blob/7ff179ce7b3381f8be7d52003e2741a700964284/utils/utils.js#L241-L272", "partition": "test"} {"repo": "greenkeeperio/greenkeeper", "path": "utils/utils.js", "func_name": "", "original_string": "function (travisYML, newVersion, newCodeName, existingVersions) {\n // Should only remove the old version if it is actually present in any form\n if (existingVersions.versions.length === 0) return travisYML\n const nodeVersionIndex = getNodeVersionIndex(existingVersions.versions, newVersion, newCodeName, true)\n let travisYMLLines = travisYML.split('\\n')\n // We only need to do something if the old version is present\n if (nodeVersionIndex !== -1) {\n // If it\u2019s the only version we don\u2019t want to remove it\n if (existingVersions.versions.length !== 1) {\n // Multiple node versions were defined in array format\n // set lines we want to remove to undefined in existingVersion.versions and filter them out afterwards\n const updatedVersionsArray = _.filter(existingVersions.versions.map((version) => {\n return hasNodeVersion(version, newVersion, newCodeName, true) ? undefined : version\n }), Boolean)\n // splice the updated existingversions into travisymllines\n travisYMLLines.splice(existingVersions.startIndex + 1, existingVersions.endIndex - existingVersions.startIndex, updatedVersionsArray)\n // has an array in an array, needs to be flattened\n travisYMLLines = _.flatten(travisYMLLines)\n }\n }\n return travisYMLLines.join('\\n')\n}", "language": "javascript", "code": "function (travisYML, newVersion, newCodeName, existingVersions) {\n // Should only remove the old version if it is actually present in any form\n if (existingVersions.versions.length === 0) return travisYML\n const nodeVersionIndex = getNodeVersionIndex(existingVersions.versions, newVersion, newCodeName, true)\n let travisYMLLines = travisYML.split('\\n')\n // We only need to do something if the old version is present\n if (nodeVersionIndex !== -1) {\n // If it\u2019s the only version we don\u2019t want to remove it\n if (existingVersions.versions.length !== 1) {\n // Multiple node versions were defined in array format\n // set lines we want to remove to undefined in existingVersion.versions and filter them out afterwards\n const updatedVersionsArray = _.filter(existingVersions.versions.map((version) => {\n return hasNodeVersion(version, newVersion, newCodeName, true) ? undefined : version\n }), Boolean)\n // splice the updated existingversions into travisymllines\n travisYMLLines.splice(existingVersions.startIndex + 1, existingVersions.endIndex - existingVersions.startIndex, updatedVersionsArray)\n // has an array in an array, needs to be flattened\n travisYMLLines = _.flatten(travisYMLLines)\n }\n }\n return travisYMLLines.join('\\n')\n}", "code_tokens": ["function", "(", "travisYML", ",", "newVersion", ",", "newCodeName", ",", "existingVersions", ")", "{", "if", "(", "existingVersions", ".", "versions", ".", "length", "===", "0", ")", "return", "travisYML", "const", "nodeVersionIndex", "=", "getNodeVersionIndex", "(", "existingVersions", ".", "versions", ",", "newVersion", ",", "newCodeName", ",", "true", ")", "let", "travisYMLLines", "=", "travisYML", ".", "split", "(", "'\\n'", ")", "\\n", "if", "(", "nodeVersionIndex", "!==", "-", "1", ")", "{", "if", "(", "existingVersions", ".", "versions", ".", "length", "!==", "1", ")", "{", "const", "updatedVersionsArray", "=", "_", ".", "filter", "(", "existingVersions", ".", "versions", ".", "map", "(", "(", "version", ")", "=>", "{", "return", "hasNodeVersion", "(", "version", ",", "newVersion", ",", "newCodeName", ",", "true", ")", "?", "undefined", ":", "version", "}", ")", ",", "Boolean", ")", "travisYMLLines", ".", "splice", "(", "existingVersions", ".", "startIndex", "+", "1", ",", "existingVersions", ".", "endIndex", "-", "existingVersions", ".", "startIndex", ",", "updatedVersionsArray", ")", "travisYMLLines", "=", "_", ".", "flatten", "(", "travisYMLLines", ")", "}", "}", "}"], "docstring": "existingVersions is the output of getNodeVersionsFromTravisYML", "docstring_tokens": ["existingVersions", "is", "the", "output", "of", "getNodeVersionsFromTravisYML"], "sha": "7ff179ce7b3381f8be7d52003e2741a700964284", "url": "https://github.com/greenkeeperio/greenkeeper/blob/7ff179ce7b3381f8be7d52003e2741a700964284/utils/utils.js#L278-L299", "partition": "test"} {"repo": "greenkeeperio/greenkeeper", "path": "jobs/update-nodejs-version.js", "func_name": "travisTransform", "original_string": "function travisTransform (travisYML) {\n try {\n var travisJSON = yaml.safeLoad(travisYML, {\n schema: yaml.FAILSAFE_SCHEMA\n })\n } catch (e) {\n // ignore .travis.yml if it can not be parsed\n return\n }\n // No node versions specified in root level of travis YML\n // There may be node versions defined in the matrix or jobs keys, but those can become\n // far too complex for us to handle, so we don\u2019t\n if (!_.get(travisJSON, 'node_js')) return\n\n const nodeVersionFromYaml = getNodeVersionsFromTravisYML(travisYML)\n const hasNodeVersion = getNodeVersionIndex(nodeVersionFromYaml.versions, nodeVersion, codeName) !== -1\n if (hasNodeVersion) return\n\n const updatedTravisYaml = addNodeVersionToTravisYML(travisYML, nodeVersion, codeName, nodeVersionFromYaml)\n return updatedTravisYaml\n }", "language": "javascript", "code": "function travisTransform (travisYML) {\n try {\n var travisJSON = yaml.safeLoad(travisYML, {\n schema: yaml.FAILSAFE_SCHEMA\n })\n } catch (e) {\n // ignore .travis.yml if it can not be parsed\n return\n }\n // No node versions specified in root level of travis YML\n // There may be node versions defined in the matrix or jobs keys, but those can become\n // far too complex for us to handle, so we don\u2019t\n if (!_.get(travisJSON, 'node_js')) return\n\n const nodeVersionFromYaml = getNodeVersionsFromTravisYML(travisYML)\n const hasNodeVersion = getNodeVersionIndex(nodeVersionFromYaml.versions, nodeVersion, codeName) !== -1\n if (hasNodeVersion) return\n\n const updatedTravisYaml = addNodeVersionToTravisYML(travisYML, nodeVersion, codeName, nodeVersionFromYaml)\n return updatedTravisYaml\n }", "code_tokens": ["function", "travisTransform", "(", "travisYML", ")", "{", "try", "{", "var", "travisJSON", "=", "yaml", ".", "safeLoad", "(", "travisYML", ",", "{", "schema", ":", "yaml", ".", "FAILSAFE_SCHEMA", "}", ")", "}", "catch", "(", "e", ")", "{", "return", "}", "if", "(", "!", "_", ".", "get", "(", "travisJSON", ",", "'node_js'", ")", ")", "return", "const", "nodeVersionFromYaml", "=", "getNodeVersionsFromTravisYML", "(", "travisYML", ")", "const", "hasNodeVersion", "=", "getNodeVersionIndex", "(", "nodeVersionFromYaml", ".", "versions", ",", "nodeVersion", ",", "codeName", ")", "!==", "-", "1", "if", "(", "hasNodeVersion", ")", "return", "const", "updatedTravisYaml", "=", "addNodeVersionToTravisYML", "(", "travisYML", ",", "nodeVersion", ",", "codeName", ",", "nodeVersionFromYaml", ")", "return", "updatedTravisYaml", "}"], "docstring": "1. fetch .travis.yml", "docstring_tokens": ["1", ".", "fetch", ".", "travis", ".", "yml"], "sha": "7ff179ce7b3381f8be7d52003e2741a700964284", "url": "https://github.com/greenkeeperio/greenkeeper/blob/7ff179ce7b3381f8be7d52003e2741a700964284/jobs/update-nodejs-version.js#L66-L86", "partition": "test"} {"repo": "greenkeeperio/greenkeeper", "path": "lib/monorepo.js", "func_name": "isDependencyIgnoredInGroups", "original_string": "function isDependencyIgnoredInGroups (groups, packageFilePath, dependencyName) {\n const groupName = getGroupForPackageFile(groups, packageFilePath)\n return groupName && _.includes(groups[groupName].ignore, dependencyName)\n}", "language": "javascript", "code": "function isDependencyIgnoredInGroups (groups, packageFilePath, dependencyName) {\n const groupName = getGroupForPackageFile(groups, packageFilePath)\n return groupName && _.includes(groups[groupName].ignore, dependencyName)\n}", "code_tokens": ["function", "isDependencyIgnoredInGroups", "(", "groups", ",", "packageFilePath", ",", "dependencyName", ")", "{", "const", "groupName", "=", "getGroupForPackageFile", "(", "groups", ",", "packageFilePath", ")", "return", "groupName", "&&", "_", ".", "includes", "(", "groups", "[", "groupName", "]", ".", "ignore", ",", "dependencyName", ")", "}"], "docstring": "Given a groups array, a package path, and a dependency name, returns whether that dep is ignored for that package in any group", "docstring_tokens": ["Given", "a", "groups", "array", "a", "package", "path", "and", "a", "dependency", "name", "returns", "whether", "that", "dep", "is", "ignored", "for", "that", "package", "in", "any", "group"], "sha": "7ff179ce7b3381f8be7d52003e2741a700964284", "url": "https://github.com/greenkeeperio/greenkeeper/blob/7ff179ce7b3381f8be7d52003e2741a700964284/lib/monorepo.js#L131-L134", "partition": "test"} {"repo": "greenkeeperio/greenkeeper", "path": "lib/get-infos.js", "func_name": "getDependencyURL", "original_string": "function getDependencyURL ({ repositoryURL, dependency }) {\n // githubURL is an object!\n const githubURL = url.parse(\n githubFromGit(repositoryURL) || ''\n )\n if (dependency && !githubURL.href) {\n return `https://www.npmjs.com/package/${dependency}`\n }\n return githubURL\n}", "language": "javascript", "code": "function getDependencyURL ({ repositoryURL, dependency }) {\n // githubURL is an object!\n const githubURL = url.parse(\n githubFromGit(repositoryURL) || ''\n )\n if (dependency && !githubURL.href) {\n return `https://www.npmjs.com/package/${dependency}`\n }\n return githubURL\n}", "code_tokens": ["function", "getDependencyURL", "(", "{", "repositoryURL", ",", "dependency", "}", ")", "{", "const", "githubURL", "=", "url", ".", "parse", "(", "githubFromGit", "(", "repositoryURL", ")", "||", "''", ")", "if", "(", "dependency", "&&", "!", "githubURL", ".", "href", ")", "{", "return", "`", "${", "dependency", "}", "`", "}", "return", "githubURL", "}"], "docstring": "returns a url object if you pass in a GitHub repositoryURL, returns a string with an npm URL if you just pass in a dependency name", "docstring_tokens": ["returns", "a", "url", "object", "if", "you", "pass", "in", "a", "GitHub", "repositoryURL", "returns", "a", "string", "with", "an", "npm", "URL", "if", "you", "just", "pass", "in", "a", "dependency", "name"], "sha": "7ff179ce7b3381f8be7d52003e2741a700964284", "url": "https://github.com/greenkeeperio/greenkeeper/blob/7ff179ce7b3381f8be7d52003e2741a700964284/lib/get-infos.js#L12-L21", "partition": "test"} {"repo": "nfl/react-gpt", "path": "scripts/updateAPIList.js", "func_name": "extractApis", "original_string": "function extractApis(services) {\n var filterTypes = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];\n\n services = Array.isArray(services) ? services : [services];\n var apis = services.reduce(function (total, service) {\n var obj = service.constructor === Object ? service : Object.getPrototypeOf(service);\n var keys = aggregateApisByType(obj, total, filterTypes);\n total.push.apply(total, keys);\n return total;\n }, []);\n\n return apis;\n }", "language": "javascript", "code": "function extractApis(services) {\n var filterTypes = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];\n\n services = Array.isArray(services) ? services : [services];\n var apis = services.reduce(function (total, service) {\n var obj = service.constructor === Object ? service : Object.getPrototypeOf(service);\n var keys = aggregateApisByType(obj, total, filterTypes);\n total.push.apply(total, keys);\n return total;\n }, []);\n\n return apis;\n }", "code_tokens": ["function", "extractApis", "(", "services", ")", "{", "var", "filterTypes", "=", "arguments", ".", "length", "<=", "1", "||", "arguments", "[", "1", "]", "===", "undefined", "?", "[", "]", ":", "arguments", "[", "1", "]", ";", "services", "=", "Array", ".", "isArray", "(", "services", ")", "?", "services", ":", "[", "services", "]", ";", "var", "apis", "=", "services", ".", "reduce", "(", "function", "(", "total", ",", "service", ")", "{", "var", "obj", "=", "service", ".", "constructor", "===", "Object", "?", "service", ":", "Object", ".", "getPrototypeOf", "(", "service", ")", ";", "var", "keys", "=", "aggregateApisByType", "(", "obj", ",", "total", ",", "filterTypes", ")", ";", "total", ".", "push", ".", "apply", "(", "total", ",", "keys", ")", ";", "return", "total", ";", "}", ",", "[", "]", ")", ";", "return", "apis", ";", "}"], "docstring": "extracts lists of methods from each service object.", "docstring_tokens": ["extracts", "lists", "of", "methods", "from", "each", "service", "object", "."], "sha": "67b147eb4740ed627359aaee593d140f623be0b6", "url": "https://github.com/nfl/react-gpt/blob/67b147eb4740ed627359aaee593d140f623be0b6/scripts/updateAPIList.js#L90-L102", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchResults/index.js", "func_name": "extractNormalizedFacetValues", "original_string": "function extractNormalizedFacetValues(results, attribute) {\n var predicate = {name: attribute};\n if (results._state.isConjunctiveFacet(attribute)) {\n var facet = find(results.facets, predicate);\n if (!facet) return [];\n\n return map(facet.data, function(v, k) {\n return {\n name: k,\n count: v,\n isRefined: results._state.isFacetRefined(attribute, k),\n isExcluded: results._state.isExcludeRefined(attribute, k)\n };\n });\n } else if (results._state.isDisjunctiveFacet(attribute)) {\n var disjunctiveFacet = find(results.disjunctiveFacets, predicate);\n if (!disjunctiveFacet) return [];\n\n return map(disjunctiveFacet.data, function(v, k) {\n return {\n name: k,\n count: v,\n isRefined: results._state.isDisjunctiveFacetRefined(attribute, k)\n };\n });\n } else if (results._state.isHierarchicalFacet(attribute)) {\n return find(results.hierarchicalFacets, predicate);\n }\n}", "language": "javascript", "code": "function extractNormalizedFacetValues(results, attribute) {\n var predicate = {name: attribute};\n if (results._state.isConjunctiveFacet(attribute)) {\n var facet = find(results.facets, predicate);\n if (!facet) return [];\n\n return map(facet.data, function(v, k) {\n return {\n name: k,\n count: v,\n isRefined: results._state.isFacetRefined(attribute, k),\n isExcluded: results._state.isExcludeRefined(attribute, k)\n };\n });\n } else if (results._state.isDisjunctiveFacet(attribute)) {\n var disjunctiveFacet = find(results.disjunctiveFacets, predicate);\n if (!disjunctiveFacet) return [];\n\n return map(disjunctiveFacet.data, function(v, k) {\n return {\n name: k,\n count: v,\n isRefined: results._state.isDisjunctiveFacetRefined(attribute, k)\n };\n });\n } else if (results._state.isHierarchicalFacet(attribute)) {\n return find(results.hierarchicalFacets, predicate);\n }\n}", "code_tokens": ["function", "extractNormalizedFacetValues", "(", "results", ",", "attribute", ")", "{", "var", "predicate", "=", "{", "name", ":", "attribute", "}", ";", "if", "(", "results", ".", "_state", ".", "isConjunctiveFacet", "(", "attribute", ")", ")", "{", "var", "facet", "=", "find", "(", "results", ".", "facets", ",", "predicate", ")", ";", "if", "(", "!", "facet", ")", "return", "[", "]", ";", "return", "map", "(", "facet", ".", "data", ",", "function", "(", "v", ",", "k", ")", "{", "return", "{", "name", ":", "k", ",", "count", ":", "v", ",", "isRefined", ":", "results", ".", "_state", ".", "isFacetRefined", "(", "attribute", ",", "k", ")", ",", "isExcluded", ":", "results", ".", "_state", ".", "isExcludeRefined", "(", "attribute", ",", "k", ")", "}", ";", "}", ")", ";", "}", "else", "if", "(", "results", ".", "_state", ".", "isDisjunctiveFacet", "(", "attribute", ")", ")", "{", "var", "disjunctiveFacet", "=", "find", "(", "results", ".", "disjunctiveFacets", ",", "predicate", ")", ";", "if", "(", "!", "disjunctiveFacet", ")", "return", "[", "]", ";", "return", "map", "(", "disjunctiveFacet", ".", "data", ",", "function", "(", "v", ",", "k", ")", "{", "return", "{", "name", ":", "k", ",", "count", ":", "v", ",", "isRefined", ":", "results", ".", "_state", ".", "isDisjunctiveFacetRefined", "(", "attribute", ",", "k", ")", "}", ";", "}", ")", ";", "}", "else", "if", "(", "results", ".", "_state", ".", "isHierarchicalFacet", "(", "attribute", ")", ")", "{", "return", "find", "(", "results", ".", "hierarchicalFacets", ",", "predicate", ")", ";", "}", "}"], "docstring": "Get the facet values of a specified attribute from a SearchResults object.\n@private\n@param {SearchResults} results the search results to search in\n@param {string} attribute name of the faceted attribute to search for\n@return {array|object} facet values. For the hierarchical facets it is an object.", "docstring_tokens": ["Get", "the", "facet", "values", "of", "a", "specified", "attribute", "from", "a", "SearchResults", "object", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchResults/index.js#L548-L576", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchResults/index.js", "func_name": "recSort", "original_string": "function recSort(sortFn, node) {\n if (!node.data || node.data.length === 0) {\n return node;\n }\n var children = map(node.data, partial(recSort, sortFn));\n var sortedChildren = sortFn(children);\n var newNode = merge({}, node, {data: sortedChildren});\n return newNode;\n}", "language": "javascript", "code": "function recSort(sortFn, node) {\n if (!node.data || node.data.length === 0) {\n return node;\n }\n var children = map(node.data, partial(recSort, sortFn));\n var sortedChildren = sortFn(children);\n var newNode = merge({}, node, {data: sortedChildren});\n return newNode;\n}", "code_tokens": ["function", "recSort", "(", "sortFn", ",", "node", ")", "{", "if", "(", "!", "node", ".", "data", "||", "node", ".", "data", ".", "length", "===", "0", ")", "{", "return", "node", ";", "}", "var", "children", "=", "map", "(", "node", ".", "data", ",", "partial", "(", "recSort", ",", "sortFn", ")", ")", ";", "var", "sortedChildren", "=", "sortFn", "(", "children", ")", ";", "var", "newNode", "=", "merge", "(", "{", "}", ",", "node", ",", "{", "data", ":", "sortedChildren", "}", ")", ";", "return", "newNode", ";", "}"], "docstring": "Sort nodes of a hierarchical facet results\n@private\n@param {HierarchicalFacet} node node to upon which we want to apply the sort", "docstring_tokens": ["Sort", "nodes", "of", "a", "hierarchical", "facet", "results"], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchResults/index.js#L583-L591", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "", "original_string": "function(attribute, operator, v) {\n var value = valToNumber(v);\n\n if (this.isNumericRefined(attribute, operator, value)) return this;\n\n var mod = merge({}, this.numericRefinements);\n\n mod[attribute] = merge({}, mod[attribute]);\n\n if (mod[attribute][operator]) {\n // Array copy\n mod[attribute][operator] = mod[attribute][operator].slice();\n // Add the element. Concat can't be used here because value can be an array.\n mod[attribute][operator].push(value);\n } else {\n mod[attribute][operator] = [value];\n }\n\n return this.setQueryParameters({\n numericRefinements: mod\n });\n }", "language": "javascript", "code": "function(attribute, operator, v) {\n var value = valToNumber(v);\n\n if (this.isNumericRefined(attribute, operator, value)) return this;\n\n var mod = merge({}, this.numericRefinements);\n\n mod[attribute] = merge({}, mod[attribute]);\n\n if (mod[attribute][operator]) {\n // Array copy\n mod[attribute][operator] = mod[attribute][operator].slice();\n // Add the element. Concat can't be used here because value can be an array.\n mod[attribute][operator].push(value);\n } else {\n mod[attribute][operator] = [value];\n }\n\n return this.setQueryParameters({\n numericRefinements: mod\n });\n }", "code_tokens": ["function", "(", "attribute", ",", "operator", ",", "v", ")", "{", "var", "value", "=", "valToNumber", "(", "v", ")", ";", "if", "(", "this", ".", "isNumericRefined", "(", "attribute", ",", "operator", ",", "value", ")", ")", "return", "this", ";", "var", "mod", "=", "merge", "(", "{", "}", ",", "this", ".", "numericRefinements", ")", ";", "mod", "[", "attribute", "]", "=", "merge", "(", "{", "}", ",", "mod", "[", "attribute", "]", ")", ";", "if", "(", "mod", "[", "attribute", "]", "[", "operator", "]", ")", "{", "mod", "[", "attribute", "]", "[", "operator", "]", "=", "mod", "[", "attribute", "]", "[", "operator", "]", ".", "slice", "(", ")", ";", "mod", "[", "attribute", "]", "[", "operator", "]", ".", "push", "(", "value", ")", ";", "}", "else", "{", "mod", "[", "attribute", "]", "[", "operator", "]", "=", "[", "value", "]", ";", "}", "return", "this", ".", "setQueryParameters", "(", "{", "numericRefinements", ":", "mod", "}", ")", ";", "}"], "docstring": "Add a numeric filter for a given attribute\nWhen value is an array, they are combined with OR\nWhen value is a single value, it will combined with AND\n@method\n@param {string} attribute attribute to set the filter on\n@param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=)\n@param {number | number[]} value value of the filter\n@return {SearchParameters}\n@example\n// for price = 50 or 40\nsearchparameter.addNumericRefinement('price', '=', [50, 40]);\n@example\n// for size = 38 and 40\nsearchparameter.addNumericRefinement('size', '=', 38);\nsearchparameter.addNumericRefinement('size', '=', 40);", "docstring_tokens": ["Add", "a", "numeric", "filter", "for", "a", "given", "attribute", "When", "value", "is", "an", "array", "they", "are", "combined", "with", "OR", "When", "value", "is", "a", "single", "value", "it", "will", "combined", "with", "AND"], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L769-L790", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "_clearNumericRefinements", "original_string": "function _clearNumericRefinements(attribute) {\n if (isUndefined(attribute)) {\n if (isEmpty(this.numericRefinements)) return this.numericRefinements;\n return {};\n } else if (isString(attribute)) {\n if (isEmpty(this.numericRefinements[attribute])) return this.numericRefinements;\n return omit(this.numericRefinements, attribute);\n } else if (isFunction(attribute)) {\n var hasChanged = false;\n var newNumericRefinements = reduce(this.numericRefinements, function(memo, operators, key) {\n var operatorList = {};\n\n forEach(operators, function(values, operator) {\n var outValues = [];\n forEach(values, function(value) {\n var predicateResult = attribute({val: value, op: operator}, key, 'numeric');\n if (!predicateResult) outValues.push(value);\n });\n if (!isEmpty(outValues)) {\n if (outValues.length !== values.length) hasChanged = true;\n operatorList[operator] = outValues;\n }\n else hasChanged = true;\n });\n\n if (!isEmpty(operatorList)) memo[key] = operatorList;\n\n return memo;\n }, {});\n\n if (hasChanged) return newNumericRefinements;\n return this.numericRefinements;\n }\n }", "language": "javascript", "code": "function _clearNumericRefinements(attribute) {\n if (isUndefined(attribute)) {\n if (isEmpty(this.numericRefinements)) return this.numericRefinements;\n return {};\n } else if (isString(attribute)) {\n if (isEmpty(this.numericRefinements[attribute])) return this.numericRefinements;\n return omit(this.numericRefinements, attribute);\n } else if (isFunction(attribute)) {\n var hasChanged = false;\n var newNumericRefinements = reduce(this.numericRefinements, function(memo, operators, key) {\n var operatorList = {};\n\n forEach(operators, function(values, operator) {\n var outValues = [];\n forEach(values, function(value) {\n var predicateResult = attribute({val: value, op: operator}, key, 'numeric');\n if (!predicateResult) outValues.push(value);\n });\n if (!isEmpty(outValues)) {\n if (outValues.length !== values.length) hasChanged = true;\n operatorList[operator] = outValues;\n }\n else hasChanged = true;\n });\n\n if (!isEmpty(operatorList)) memo[key] = operatorList;\n\n return memo;\n }, {});\n\n if (hasChanged) return newNumericRefinements;\n return this.numericRefinements;\n }\n }", "code_tokens": ["function", "_clearNumericRefinements", "(", "attribute", ")", "{", "if", "(", "isUndefined", "(", "attribute", ")", ")", "{", "if", "(", "isEmpty", "(", "this", ".", "numericRefinements", ")", ")", "return", "this", ".", "numericRefinements", ";", "return", "{", "}", ";", "}", "else", "if", "(", "isString", "(", "attribute", ")", ")", "{", "if", "(", "isEmpty", "(", "this", ".", "numericRefinements", "[", "attribute", "]", ")", ")", "return", "this", ".", "numericRefinements", ";", "return", "omit", "(", "this", ".", "numericRefinements", ",", "attribute", ")", ";", "}", "else", "if", "(", "isFunction", "(", "attribute", ")", ")", "{", "var", "hasChanged", "=", "false", ";", "var", "newNumericRefinements", "=", "reduce", "(", "this", ".", "numericRefinements", ",", "function", "(", "memo", ",", "operators", ",", "key", ")", "{", "var", "operatorList", "=", "{", "}", ";", "forEach", "(", "operators", ",", "function", "(", "values", ",", "operator", ")", "{", "var", "outValues", "=", "[", "]", ";", "forEach", "(", "values", ",", "function", "(", "value", ")", "{", "var", "predicateResult", "=", "attribute", "(", "{", "val", ":", "value", ",", "op", ":", "operator", "}", ",", "key", ",", "'numeric'", ")", ";", "if", "(", "!", "predicateResult", ")", "outValues", ".", "push", "(", "value", ")", ";", "}", ")", ";", "if", "(", "!", "isEmpty", "(", "outValues", ")", ")", "{", "if", "(", "outValues", ".", "length", "!==", "values", ".", "length", ")", "hasChanged", "=", "true", ";", "operatorList", "[", "operator", "]", "=", "outValues", ";", "}", "else", "hasChanged", "=", "true", ";", "}", ")", ";", "if", "(", "!", "isEmpty", "(", "operatorList", ")", ")", "memo", "[", "key", "]", "=", "operatorList", ";", "return", "memo", ";", "}", ",", "{", "}", ")", ";", "if", "(", "hasChanged", ")", "return", "newNumericRefinements", ";", "return", "this", ".", "numericRefinements", ";", "}", "}"], "docstring": "Clear numeric filters.\n@method\n@private\n@param {string|SearchParameters.clearCallback} [attribute] optional string or function\n- If not given, means to clear all the filters.\n- If `string`, means to clear all refinements for the `attribute` named filter.\n- If `function`, means to clear all the refinements that return truthy values.\n@return {Object.}", "docstring_tokens": ["Clear", "numeric", "filters", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L897-L930", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "addHierarchicalFacet", "original_string": "function addHierarchicalFacet(hierarchicalFacet) {\n if (this.isHierarchicalFacet(hierarchicalFacet.name)) {\n throw new Error(\n 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`');\n }\n\n return this.setQueryParameters({\n hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet])\n });\n }", "language": "javascript", "code": "function addHierarchicalFacet(hierarchicalFacet) {\n if (this.isHierarchicalFacet(hierarchicalFacet.name)) {\n throw new Error(\n 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`');\n }\n\n return this.setQueryParameters({\n hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet])\n });\n }", "code_tokens": ["function", "addHierarchicalFacet", "(", "hierarchicalFacet", ")", "{", "if", "(", "this", ".", "isHierarchicalFacet", "(", "hierarchicalFacet", ".", "name", ")", ")", "{", "throw", "new", "Error", "(", "'Cannot declare two hierarchical facets with the same name: `'", "+", "hierarchicalFacet", ".", "name", "+", "'`'", ")", ";", "}", "return", "this", ".", "setQueryParameters", "(", "{", "hierarchicalFacets", ":", "this", ".", "hierarchicalFacets", ".", "concat", "(", "[", "hierarchicalFacet", "]", ")", "}", ")", ";", "}"], "docstring": "Add a hierarchical facet to the hierarchicalFacets attribute of the helper\nconfiguration.\n@method\n@param {object} hierarchicalFacet hierarchical facet to add\n@return {SearchParameters}\n@throws will throw an error if a hierarchical facet with the same name was already declared", "docstring_tokens": ["Add", "a", "hierarchical", "facet", "to", "the", "hierarchicalFacets", "attribute", "of", "the", "helper", "configuration", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L971-L980", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "addFacetRefinement", "original_string": "function addFacetRefinement(facet, value) {\n if (!this.isConjunctiveFacet(facet)) {\n throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');\n }\n if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;\n\n return this.setQueryParameters({\n facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value)\n });\n }", "language": "javascript", "code": "function addFacetRefinement(facet, value) {\n if (!this.isConjunctiveFacet(facet)) {\n throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');\n }\n if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;\n\n return this.setQueryParameters({\n facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value)\n });\n }", "code_tokens": ["function", "addFacetRefinement", "(", "facet", ",", "value", ")", "{", "if", "(", "!", "this", ".", "isConjunctiveFacet", "(", "facet", ")", ")", "{", "throw", "new", "Error", "(", "facet", "+", "' is not defined in the facets attribute of the helper configuration'", ")", ";", "}", "if", "(", "RefinementList", ".", "isRefined", "(", "this", ".", "facetsRefinements", ",", "facet", ",", "value", ")", ")", "return", "this", ";", "return", "this", ".", "setQueryParameters", "(", "{", "facetsRefinements", ":", "RefinementList", ".", "addRefinement", "(", "this", ".", "facetsRefinements", ",", "facet", ",", "value", ")", "}", ")", ";", "}"], "docstring": "Add a refinement on a \"normal\" facet\n@method\n@param {string} facet attribute to apply the faceting on\n@param {string} value value of the attribute (will be converted to string)\n@return {SearchParameters}", "docstring_tokens": ["Add", "a", "refinement", "on", "a", "normal", "facet"], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L988-L997", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "addExcludeRefinement", "original_string": "function addExcludeRefinement(facet, value) {\n if (!this.isConjunctiveFacet(facet)) {\n throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');\n }\n if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;\n\n return this.setQueryParameters({\n facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value)\n });\n }", "language": "javascript", "code": "function addExcludeRefinement(facet, value) {\n if (!this.isConjunctiveFacet(facet)) {\n throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');\n }\n if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;\n\n return this.setQueryParameters({\n facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value)\n });\n }", "code_tokens": ["function", "addExcludeRefinement", "(", "facet", ",", "value", ")", "{", "if", "(", "!", "this", ".", "isConjunctiveFacet", "(", "facet", ")", ")", "{", "throw", "new", "Error", "(", "facet", "+", "' is not defined in the facets attribute of the helper configuration'", ")", ";", "}", "if", "(", "RefinementList", ".", "isRefined", "(", "this", ".", "facetsExcludes", ",", "facet", ",", "value", ")", ")", "return", "this", ";", "return", "this", ".", "setQueryParameters", "(", "{", "facetsExcludes", ":", "RefinementList", ".", "addRefinement", "(", "this", ".", "facetsExcludes", ",", "facet", ",", "value", ")", "}", ")", ";", "}"], "docstring": "Exclude a value from a \"normal\" facet\n@method\n@param {string} facet attribute to apply the exclusion on\n@param {string} value value of the attribute (will be converted to string)\n@return {SearchParameters}", "docstring_tokens": ["Exclude", "a", "value", "from", "a", "normal", "facet"], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1005-L1014", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "addDisjunctiveFacetRefinement", "original_string": "function addDisjunctiveFacetRefinement(facet, value) {\n if (!this.isDisjunctiveFacet(facet)) {\n throw new Error(\n facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');\n }\n\n if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;\n\n return this.setQueryParameters({\n disjunctiveFacetsRefinements: RefinementList.addRefinement(\n this.disjunctiveFacetsRefinements, facet, value)\n });\n }", "language": "javascript", "code": "function addDisjunctiveFacetRefinement(facet, value) {\n if (!this.isDisjunctiveFacet(facet)) {\n throw new Error(\n facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');\n }\n\n if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;\n\n return this.setQueryParameters({\n disjunctiveFacetsRefinements: RefinementList.addRefinement(\n this.disjunctiveFacetsRefinements, facet, value)\n });\n }", "code_tokens": ["function", "addDisjunctiveFacetRefinement", "(", "facet", ",", "value", ")", "{", "if", "(", "!", "this", ".", "isDisjunctiveFacet", "(", "facet", ")", ")", "{", "throw", "new", "Error", "(", "facet", "+", "' is not defined in the disjunctiveFacets attribute of the helper configuration'", ")", ";", "}", "if", "(", "RefinementList", ".", "isRefined", "(", "this", ".", "disjunctiveFacetsRefinements", ",", "facet", ",", "value", ")", ")", "return", "this", ";", "return", "this", ".", "setQueryParameters", "(", "{", "disjunctiveFacetsRefinements", ":", "RefinementList", ".", "addRefinement", "(", "this", ".", "disjunctiveFacetsRefinements", ",", "facet", ",", "value", ")", "}", ")", ";", "}"], "docstring": "Adds a refinement on a disjunctive facet.\n@method\n@param {string} facet attribute to apply the faceting on\n@param {string} value value of the attribute (will be converted to string)\n@return {SearchParameters}", "docstring_tokens": ["Adds", "a", "refinement", "on", "a", "disjunctive", "facet", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1022-L1034", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "addTagRefinement", "original_string": "function addTagRefinement(tag) {\n if (this.isTagRefined(tag)) return this;\n\n var modification = {\n tagRefinements: this.tagRefinements.concat(tag)\n };\n\n return this.setQueryParameters(modification);\n }", "language": "javascript", "code": "function addTagRefinement(tag) {\n if (this.isTagRefined(tag)) return this;\n\n var modification = {\n tagRefinements: this.tagRefinements.concat(tag)\n };\n\n return this.setQueryParameters(modification);\n }", "code_tokens": ["function", "addTagRefinement", "(", "tag", ")", "{", "if", "(", "this", ".", "isTagRefined", "(", "tag", ")", ")", "return", "this", ";", "var", "modification", "=", "{", "tagRefinements", ":", "this", ".", "tagRefinements", ".", "concat", "(", "tag", ")", "}", ";", "return", "this", ".", "setQueryParameters", "(", "modification", ")", ";", "}"], "docstring": "addTagRefinement adds a tag to the list used to filter the results\n@param {string} tag tag to be added\n@return {SearchParameters}", "docstring_tokens": ["addTagRefinement", "adds", "a", "tag", "to", "the", "list", "used", "to", "filter", "the", "results"], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1040-L1048", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "removeFacet", "original_string": "function removeFacet(facet) {\n if (!this.isConjunctiveFacet(facet)) {\n return this;\n }\n\n return this.clearRefinements(facet).setQueryParameters({\n facets: filter(this.facets, function(f) {\n return f !== facet;\n })\n });\n }", "language": "javascript", "code": "function removeFacet(facet) {\n if (!this.isConjunctiveFacet(facet)) {\n return this;\n }\n\n return this.clearRefinements(facet).setQueryParameters({\n facets: filter(this.facets, function(f) {\n return f !== facet;\n })\n });\n }", "code_tokens": ["function", "removeFacet", "(", "facet", ")", "{", "if", "(", "!", "this", ".", "isConjunctiveFacet", "(", "facet", ")", ")", "{", "return", "this", ";", "}", "return", "this", ".", "clearRefinements", "(", "facet", ")", ".", "setQueryParameters", "(", "{", "facets", ":", "filter", "(", "this", ".", "facets", ",", "function", "(", "f", ")", "{", "return", "f", "!==", "facet", ";", "}", ")", "}", ")", ";", "}"], "docstring": "Remove a facet from the facets attribute of the helper configuration, if it\nis present.\n@method\n@param {string} facet facet name to remove\n@return {SearchParameters}", "docstring_tokens": ["Remove", "a", "facet", "from", "the", "facets", "attribute", "of", "the", "helper", "configuration", "if", "it", "is", "present", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1056-L1066", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "removeDisjunctiveFacet", "original_string": "function removeDisjunctiveFacet(facet) {\n if (!this.isDisjunctiveFacet(facet)) {\n return this;\n }\n\n return this.clearRefinements(facet).setQueryParameters({\n disjunctiveFacets: filter(this.disjunctiveFacets, function(f) {\n return f !== facet;\n })\n });\n }", "language": "javascript", "code": "function removeDisjunctiveFacet(facet) {\n if (!this.isDisjunctiveFacet(facet)) {\n return this;\n }\n\n return this.clearRefinements(facet).setQueryParameters({\n disjunctiveFacets: filter(this.disjunctiveFacets, function(f) {\n return f !== facet;\n })\n });\n }", "code_tokens": ["function", "removeDisjunctiveFacet", "(", "facet", ")", "{", "if", "(", "!", "this", ".", "isDisjunctiveFacet", "(", "facet", ")", ")", "{", "return", "this", ";", "}", "return", "this", ".", "clearRefinements", "(", "facet", ")", ".", "setQueryParameters", "(", "{", "disjunctiveFacets", ":", "filter", "(", "this", ".", "disjunctiveFacets", ",", "function", "(", "f", ")", "{", "return", "f", "!==", "facet", ";", "}", ")", "}", ")", ";", "}"], "docstring": "Remove a disjunctive facet from the disjunctiveFacets attribute of the\nhelper configuration, if it is present.\n@method\n@param {string} facet disjunctive facet name to remove\n@return {SearchParameters}", "docstring_tokens": ["Remove", "a", "disjunctive", "facet", "from", "the", "disjunctiveFacets", "attribute", "of", "the", "helper", "configuration", "if", "it", "is", "present", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1074-L1084", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "removeHierarchicalFacet", "original_string": "function removeHierarchicalFacet(facet) {\n if (!this.isHierarchicalFacet(facet)) {\n return this;\n }\n\n return this.clearRefinements(facet).setQueryParameters({\n hierarchicalFacets: filter(this.hierarchicalFacets, function(f) {\n return f.name !== facet;\n })\n });\n }", "language": "javascript", "code": "function removeHierarchicalFacet(facet) {\n if (!this.isHierarchicalFacet(facet)) {\n return this;\n }\n\n return this.clearRefinements(facet).setQueryParameters({\n hierarchicalFacets: filter(this.hierarchicalFacets, function(f) {\n return f.name !== facet;\n })\n });\n }", "code_tokens": ["function", "removeHierarchicalFacet", "(", "facet", ")", "{", "if", "(", "!", "this", ".", "isHierarchicalFacet", "(", "facet", ")", ")", "{", "return", "this", ";", "}", "return", "this", ".", "clearRefinements", "(", "facet", ")", ".", "setQueryParameters", "(", "{", "hierarchicalFacets", ":", "filter", "(", "this", ".", "hierarchicalFacets", ",", "function", "(", "f", ")", "{", "return", "f", ".", "name", "!==", "facet", ";", "}", ")", "}", ")", ";", "}"], "docstring": "Remove a hierarchical facet from the hierarchicalFacets attribute of the\nhelper configuration, if it is present.\n@method\n@param {string} facet hierarchical facet name to remove\n@return {SearchParameters}", "docstring_tokens": ["Remove", "a", "hierarchical", "facet", "from", "the", "hierarchicalFacets", "attribute", "of", "the", "helper", "configuration", "if", "it", "is", "present", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1092-L1102", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "removeFacetRefinement", "original_string": "function removeFacetRefinement(facet, value) {\n if (!this.isConjunctiveFacet(facet)) {\n throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');\n }\n if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;\n\n return this.setQueryParameters({\n facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value)\n });\n }", "language": "javascript", "code": "function removeFacetRefinement(facet, value) {\n if (!this.isConjunctiveFacet(facet)) {\n throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');\n }\n if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;\n\n return this.setQueryParameters({\n facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value)\n });\n }", "code_tokens": ["function", "removeFacetRefinement", "(", "facet", ",", "value", ")", "{", "if", "(", "!", "this", ".", "isConjunctiveFacet", "(", "facet", ")", ")", "{", "throw", "new", "Error", "(", "facet", "+", "' is not defined in the facets attribute of the helper configuration'", ")", ";", "}", "if", "(", "!", "RefinementList", ".", "isRefined", "(", "this", ".", "facetsRefinements", ",", "facet", ",", "value", ")", ")", "return", "this", ";", "return", "this", ".", "setQueryParameters", "(", "{", "facetsRefinements", ":", "RefinementList", ".", "removeRefinement", "(", "this", ".", "facetsRefinements", ",", "facet", ",", "value", ")", "}", ")", ";", "}"], "docstring": "Remove a refinement set on facet. If a value is provided, it will clear the\nrefinement for the given value, otherwise it will clear all the refinement\nvalues for the faceted attribute.\n@method\n@param {string} facet name of the attribute used for faceting\n@param {string} [value] value used to filter\n@return {SearchParameters}", "docstring_tokens": ["Remove", "a", "refinement", "set", "on", "facet", ".", "If", "a", "value", "is", "provided", "it", "will", "clear", "the", "refinement", "for", "the", "given", "value", "otherwise", "it", "will", "clear", "all", "the", "refinement", "values", "for", "the", "faceted", "attribute", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1112-L1121", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "removeExcludeRefinement", "original_string": "function removeExcludeRefinement(facet, value) {\n if (!this.isConjunctiveFacet(facet)) {\n throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');\n }\n if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;\n\n return this.setQueryParameters({\n facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value)\n });\n }", "language": "javascript", "code": "function removeExcludeRefinement(facet, value) {\n if (!this.isConjunctiveFacet(facet)) {\n throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');\n }\n if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;\n\n return this.setQueryParameters({\n facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value)\n });\n }", "code_tokens": ["function", "removeExcludeRefinement", "(", "facet", ",", "value", ")", "{", "if", "(", "!", "this", ".", "isConjunctiveFacet", "(", "facet", ")", ")", "{", "throw", "new", "Error", "(", "facet", "+", "' is not defined in the facets attribute of the helper configuration'", ")", ";", "}", "if", "(", "!", "RefinementList", ".", "isRefined", "(", "this", ".", "facetsExcludes", ",", "facet", ",", "value", ")", ")", "return", "this", ";", "return", "this", ".", "setQueryParameters", "(", "{", "facetsExcludes", ":", "RefinementList", ".", "removeRefinement", "(", "this", ".", "facetsExcludes", ",", "facet", ",", "value", ")", "}", ")", ";", "}"], "docstring": "Remove a negative refinement on a facet\n@method\n@param {string} facet name of the attribute used for faceting\n@param {string} value value used to filter\n@return {SearchParameters}", "docstring_tokens": ["Remove", "a", "negative", "refinement", "on", "a", "facet"], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1129-L1138", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "removeDisjunctiveFacetRefinement", "original_string": "function removeDisjunctiveFacetRefinement(facet, value) {\n if (!this.isDisjunctiveFacet(facet)) {\n throw new Error(\n facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');\n }\n if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;\n\n return this.setQueryParameters({\n disjunctiveFacetsRefinements: RefinementList.removeRefinement(\n this.disjunctiveFacetsRefinements, facet, value)\n });\n }", "language": "javascript", "code": "function removeDisjunctiveFacetRefinement(facet, value) {\n if (!this.isDisjunctiveFacet(facet)) {\n throw new Error(\n facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');\n }\n if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;\n\n return this.setQueryParameters({\n disjunctiveFacetsRefinements: RefinementList.removeRefinement(\n this.disjunctiveFacetsRefinements, facet, value)\n });\n }", "code_tokens": ["function", "removeDisjunctiveFacetRefinement", "(", "facet", ",", "value", ")", "{", "if", "(", "!", "this", ".", "isDisjunctiveFacet", "(", "facet", ")", ")", "{", "throw", "new", "Error", "(", "facet", "+", "' is not defined in the disjunctiveFacets attribute of the helper configuration'", ")", ";", "}", "if", "(", "!", "RefinementList", ".", "isRefined", "(", "this", ".", "disjunctiveFacetsRefinements", ",", "facet", ",", "value", ")", ")", "return", "this", ";", "return", "this", ".", "setQueryParameters", "(", "{", "disjunctiveFacetsRefinements", ":", "RefinementList", ".", "removeRefinement", "(", "this", ".", "disjunctiveFacetsRefinements", ",", "facet", ",", "value", ")", "}", ")", ";", "}"], "docstring": "Remove a refinement on a disjunctive facet\n@method\n@param {string} facet name of the attribute used for faceting\n@param {string} value value used to filter\n@return {SearchParameters}", "docstring_tokens": ["Remove", "a", "refinement", "on", "a", "disjunctive", "facet"], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1146-L1157", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "removeTagRefinement", "original_string": "function removeTagRefinement(tag) {\n if (!this.isTagRefined(tag)) return this;\n\n var modification = {\n tagRefinements: filter(this.tagRefinements, function(t) { return t !== tag; })\n };\n\n return this.setQueryParameters(modification);\n }", "language": "javascript", "code": "function removeTagRefinement(tag) {\n if (!this.isTagRefined(tag)) return this;\n\n var modification = {\n tagRefinements: filter(this.tagRefinements, function(t) { return t !== tag; })\n };\n\n return this.setQueryParameters(modification);\n }", "code_tokens": ["function", "removeTagRefinement", "(", "tag", ")", "{", "if", "(", "!", "this", ".", "isTagRefined", "(", "tag", ")", ")", "return", "this", ";", "var", "modification", "=", "{", "tagRefinements", ":", "filter", "(", "this", ".", "tagRefinements", ",", "function", "(", "t", ")", "{", "return", "t", "!==", "tag", ";", "}", ")", "}", ";", "return", "this", ".", "setQueryParameters", "(", "modification", ")", ";", "}"], "docstring": "Remove a tag from the list of tag refinements\n@method\n@param {string} tag the tag to remove\n@return {SearchParameters}", "docstring_tokens": ["Remove", "a", "tag", "from", "the", "list", "of", "tag", "refinements"], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1164-L1172", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "toggleFacetRefinement", "original_string": "function toggleFacetRefinement(facet, value) {\n if (this.isHierarchicalFacet(facet)) {\n return this.toggleHierarchicalFacetRefinement(facet, value);\n } else if (this.isConjunctiveFacet(facet)) {\n return this.toggleConjunctiveFacetRefinement(facet, value);\n } else if (this.isDisjunctiveFacet(facet)) {\n return this.toggleDisjunctiveFacetRefinement(facet, value);\n }\n\n throw new Error('Cannot refine the undeclared facet ' + facet +\n '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets');\n }", "language": "javascript", "code": "function toggleFacetRefinement(facet, value) {\n if (this.isHierarchicalFacet(facet)) {\n return this.toggleHierarchicalFacetRefinement(facet, value);\n } else if (this.isConjunctiveFacet(facet)) {\n return this.toggleConjunctiveFacetRefinement(facet, value);\n } else if (this.isDisjunctiveFacet(facet)) {\n return this.toggleDisjunctiveFacetRefinement(facet, value);\n }\n\n throw new Error('Cannot refine the undeclared facet ' + facet +\n '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets');\n }", "code_tokens": ["function", "toggleFacetRefinement", "(", "facet", ",", "value", ")", "{", "if", "(", "this", ".", "isHierarchicalFacet", "(", "facet", ")", ")", "{", "return", "this", ".", "toggleHierarchicalFacetRefinement", "(", "facet", ",", "value", ")", ";", "}", "else", "if", "(", "this", ".", "isConjunctiveFacet", "(", "facet", ")", ")", "{", "return", "this", ".", "toggleConjunctiveFacetRefinement", "(", "facet", ",", "value", ")", ";", "}", "else", "if", "(", "this", ".", "isDisjunctiveFacet", "(", "facet", ")", ")", "{", "return", "this", ".", "toggleDisjunctiveFacetRefinement", "(", "facet", ",", "value", ")", ";", "}", "throw", "new", "Error", "(", "'Cannot refine the undeclared facet '", "+", "facet", "+", "'; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets'", ")", ";", "}"], "docstring": "Generic toggle refinement method to use with facet, disjunctive facets\nand hierarchical facets\n@param {string} facet the facet to refine\n@param {string} value the associated value\n@return {SearchParameters}\n@throws will throw an error if the facet is not declared in the settings of the helper", "docstring_tokens": ["Generic", "toggle", "refinement", "method", "to", "use", "with", "facet", "disjunctive", "facets", "and", "hierarchical", "facets"], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1193-L1204", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "", "original_string": "function(facet, path) {\n if (this.isHierarchicalFacetRefined(facet)) {\n throw new Error(facet + ' is already refined.');\n }\n var mod = {};\n mod[facet] = [path];\n return this.setQueryParameters({\n hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)\n });\n }", "language": "javascript", "code": "function(facet, path) {\n if (this.isHierarchicalFacetRefined(facet)) {\n throw new Error(facet + ' is already refined.');\n }\n var mod = {};\n mod[facet] = [path];\n return this.setQueryParameters({\n hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)\n });\n }", "code_tokens": ["function", "(", "facet", ",", "path", ")", "{", "if", "(", "this", ".", "isHierarchicalFacetRefined", "(", "facet", ")", ")", "{", "throw", "new", "Error", "(", "facet", "+", "' is already refined.'", ")", ";", "}", "var", "mod", "=", "{", "}", ";", "mod", "[", "facet", "]", "=", "[", "path", "]", ";", "return", "this", ".", "setQueryParameters", "(", "{", "hierarchicalFacetsRefinements", ":", "defaults", "(", "{", "}", ",", "mod", ",", "this", ".", "hierarchicalFacetsRefinements", ")", "}", ")", ";", "}"], "docstring": "Adds a refinement on a hierarchical facet.\n@param {string} facet the facet name\n@param {string} path the hierarchical facet path\n@return {SearchParameter} the new state\n@throws Error if the facet is not defined or if the facet is refined", "docstring_tokens": ["Adds", "a", "refinement", "on", "a", "hierarchical", "facet", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1307-L1316", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "isFacetRefined", "original_string": "function isFacetRefined(facet, value) {\n if (!this.isConjunctiveFacet(facet)) {\n throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');\n }\n return RefinementList.isRefined(this.facetsRefinements, facet, value);\n }", "language": "javascript", "code": "function isFacetRefined(facet, value) {\n if (!this.isConjunctiveFacet(facet)) {\n throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');\n }\n return RefinementList.isRefined(this.facetsRefinements, facet, value);\n }", "code_tokens": ["function", "isFacetRefined", "(", "facet", ",", "value", ")", "{", "if", "(", "!", "this", ".", "isConjunctiveFacet", "(", "facet", ")", ")", "{", "throw", "new", "Error", "(", "facet", "+", "' is not defined in the facets attribute of the helper configuration'", ")", ";", "}", "return", "RefinementList", ".", "isRefined", "(", "this", ".", "facetsRefinements", ",", "facet", ",", "value", ")", ";", "}"], "docstring": "Returns true if the facet is refined, either for a specific value or in\ngeneral.\n@method\n@param {string} facet name of the attribute for used for faceting\n@param {string} value, optional value. If passed will test that this value\nis filtering the given facet.\n@return {boolean} returns true if refined", "docstring_tokens": ["Returns", "true", "if", "the", "facet", "is", "refined", "either", "for", "a", "specific", "value", "or", "in", "general", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1383-L1388", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "isExcludeRefined", "original_string": "function isExcludeRefined(facet, value) {\n if (!this.isConjunctiveFacet(facet)) {\n throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');\n }\n return RefinementList.isRefined(this.facetsExcludes, facet, value);\n }", "language": "javascript", "code": "function isExcludeRefined(facet, value) {\n if (!this.isConjunctiveFacet(facet)) {\n throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');\n }\n return RefinementList.isRefined(this.facetsExcludes, facet, value);\n }", "code_tokens": ["function", "isExcludeRefined", "(", "facet", ",", "value", ")", "{", "if", "(", "!", "this", ".", "isConjunctiveFacet", "(", "facet", ")", ")", "{", "throw", "new", "Error", "(", "facet", "+", "' is not defined in the facets attribute of the helper configuration'", ")", ";", "}", "return", "RefinementList", ".", "isRefined", "(", "this", ".", "facetsExcludes", ",", "facet", ",", "value", ")", ";", "}"], "docstring": "Returns true if the facet contains exclusions or if a specific value is\nexcluded.\n\n@method\n@param {string} facet name of the attribute for used for faceting\n@param {string} [value] optional value. If passed will test that this value\nis filtering the given facet.\n@return {boolean} returns true if refined", "docstring_tokens": ["Returns", "true", "if", "the", "facet", "contains", "exclusions", "or", "if", "a", "specific", "value", "is", "excluded", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1399-L1404", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "getRefinedDisjunctiveFacets", "original_string": "function getRefinedDisjunctiveFacets() {\n // attributes used for numeric filter can also be disjunctive\n var disjunctiveNumericRefinedFacets = intersection(\n keys(this.numericRefinements),\n this.disjunctiveFacets\n );\n\n return keys(this.disjunctiveFacetsRefinements)\n .concat(disjunctiveNumericRefinedFacets)\n .concat(this.getRefinedHierarchicalFacets());\n }", "language": "javascript", "code": "function getRefinedDisjunctiveFacets() {\n // attributes used for numeric filter can also be disjunctive\n var disjunctiveNumericRefinedFacets = intersection(\n keys(this.numericRefinements),\n this.disjunctiveFacets\n );\n\n return keys(this.disjunctiveFacetsRefinements)\n .concat(disjunctiveNumericRefinedFacets)\n .concat(this.getRefinedHierarchicalFacets());\n }", "code_tokens": ["function", "getRefinedDisjunctiveFacets", "(", ")", "{", "var", "disjunctiveNumericRefinedFacets", "=", "intersection", "(", "keys", "(", "this", ".", "numericRefinements", ")", ",", "this", ".", "disjunctiveFacets", ")", ";", "return", "keys", "(", "this", ".", "disjunctiveFacetsRefinements", ")", ".", "concat", "(", "disjunctiveNumericRefinedFacets", ")", ".", "concat", "(", "this", ".", "getRefinedHierarchicalFacets", "(", ")", ")", ";", "}"], "docstring": "Returns the list of all disjunctive facets refined\n@method\n@param {string} facet name of the attribute used for faceting\n@param {value} value value used for filtering\n@return {string[]}", "docstring_tokens": ["Returns", "the", "list", "of", "all", "disjunctive", "facets", "refined"], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1489-L1499", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "setParameter", "original_string": "function setParameter(parameter, value) {\n if (this[parameter] === value) return this;\n\n var modification = {};\n\n modification[parameter] = value;\n\n return this.setQueryParameters(modification);\n }", "language": "javascript", "code": "function setParameter(parameter, value) {\n if (this[parameter] === value) return this;\n\n var modification = {};\n\n modification[parameter] = value;\n\n return this.setQueryParameters(modification);\n }", "code_tokens": ["function", "setParameter", "(", "parameter", ",", "value", ")", "{", "if", "(", "this", "[", "parameter", "]", "===", "value", ")", "return", "this", ";", "var", "modification", "=", "{", "}", ";", "modification", "[", "parameter", "]", "=", "value", ";", "return", "this", ".", "setQueryParameters", "(", "modification", ")", ";", "}"], "docstring": "Let the user set a specific value for a given parameter. Will return the\nsame instance if the parameter is invalid or if the value is the same as the\nprevious one.\n@method\n@param {string} parameter the parameter name\n@param {any} value the value to be set, must be compliant with the definition\nof the attribute on the object\n@return {SearchParameters} the updated state", "docstring_tokens": ["Let", "the", "user", "set", "a", "specific", "value", "for", "a", "given", "parameter", ".", "Will", "return", "the", "same", "instance", "if", "the", "parameter", "is", "invalid", "or", "if", "the", "value", "is", "the", "same", "as", "the", "previous", "one", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1571-L1579", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "setQueryParameters", "original_string": "function setQueryParameters(params) {\n if (!params) return this;\n\n var error = SearchParameters.validate(this, params);\n\n if (error) {\n throw error;\n }\n\n var parsedParams = SearchParameters._parseNumbers(params);\n\n return this.mutateMe(function mergeWith(newInstance) {\n var ks = keys(params);\n\n forEach(ks, function(k) {\n newInstance[k] = parsedParams[k];\n });\n\n return newInstance;\n });\n }", "language": "javascript", "code": "function setQueryParameters(params) {\n if (!params) return this;\n\n var error = SearchParameters.validate(this, params);\n\n if (error) {\n throw error;\n }\n\n var parsedParams = SearchParameters._parseNumbers(params);\n\n return this.mutateMe(function mergeWith(newInstance) {\n var ks = keys(params);\n\n forEach(ks, function(k) {\n newInstance[k] = parsedParams[k];\n });\n\n return newInstance;\n });\n }", "code_tokens": ["function", "setQueryParameters", "(", "params", ")", "{", "if", "(", "!", "params", ")", "return", "this", ";", "var", "error", "=", "SearchParameters", ".", "validate", "(", "this", ",", "params", ")", ";", "if", "(", "error", ")", "{", "throw", "error", ";", "}", "var", "parsedParams", "=", "SearchParameters", ".", "_parseNumbers", "(", "params", ")", ";", "return", "this", ".", "mutateMe", "(", "function", "mergeWith", "(", "newInstance", ")", "{", "var", "ks", "=", "keys", "(", "params", ")", ";", "forEach", "(", "ks", ",", "function", "(", "k", ")", "{", "newInstance", "[", "k", "]", "=", "parsedParams", "[", "k", "]", ";", "}", ")", ";", "return", "newInstance", ";", "}", ")", ";", "}"], "docstring": "Let the user set any of the parameters with a plain object.\n@method\n@param {object} params all the keys and the values to be updated\n@return {SearchParameters} a new updated instance", "docstring_tokens": ["Let", "the", "user", "set", "any", "of", "the", "parameters", "with", "a", "plain", "object", "."], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1586-L1606", "partition": "test"} {"repo": "algolia/algoliasearch-helper-js", "path": "src/SearchParameters/index.js", "func_name": "", "original_string": "function(facetName) {\n if (!this.isHierarchicalFacet(facetName)) {\n throw new Error(\n 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`');\n }\n\n var refinement = this.getHierarchicalRefinement(facetName)[0];\n if (!refinement) return [];\n\n var separator = this._getHierarchicalFacetSeparator(\n this.getHierarchicalFacetByName(facetName)\n );\n var path = refinement.split(separator);\n return map(path, trim);\n }", "language": "javascript", "code": "function(facetName) {\n if (!this.isHierarchicalFacet(facetName)) {\n throw new Error(\n 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`');\n }\n\n var refinement = this.getHierarchicalRefinement(facetName)[0];\n if (!refinement) return [];\n\n var separator = this._getHierarchicalFacetSeparator(\n this.getHierarchicalFacetByName(facetName)\n );\n var path = refinement.split(separator);\n return map(path, trim);\n }", "code_tokens": ["function", "(", "facetName", ")", "{", "if", "(", "!", "this", ".", "isHierarchicalFacet", "(", "facetName", ")", ")", "{", "throw", "new", "Error", "(", "'Cannot get the breadcrumb of an unknown hierarchical facet: `'", "+", "facetName", "+", "'`'", ")", ";", "}", "var", "refinement", "=", "this", ".", "getHierarchicalRefinement", "(", "facetName", ")", "[", "0", "]", ";", "if", "(", "!", "refinement", ")", "return", "[", "]", ";", "var", "separator", "=", "this", ".", "_getHierarchicalFacetSeparator", "(", "this", ".", "getHierarchicalFacetByName", "(", "facetName", ")", ")", ";", "var", "path", "=", "refinement", ".", "split", "(", "separator", ")", ";", "return", "map", "(", "path", ",", "trim", ")", ";", "}"], "docstring": "Get the current breadcrumb for a hierarchical facet, as an array\n@param {string} facetName Hierarchical facet name\n@return {array.} the path as an array of string", "docstring_tokens": ["Get", "the", "current", "breadcrumb", "for", "a", "hierarchical", "facet", "as", "an", "array"], "sha": "9ebdd34ab98a3298a7687f81dfef24b01e798c53", "url": "https://github.com/algolia/algoliasearch-helper-js/blob/9ebdd34ab98a3298a7687f81dfef24b01e798c53/src/SearchParameters/index.js#L1692-L1706", "partition": "test"} {"repo": "AssemblyScript/binaryen.js", "path": "scripts/build.js", "func_name": "runCommand", "original_string": "function runCommand(cmd, args) {\n var prev = null;\n console.log(chalk.cyanBright(cmd) + \" \" + args.map(arg => {\n if (arg.startsWith(\"-\"))\n return chalk.gray(\"\\\\\") + \"\\n \" + chalk.bold(arg);\n return arg;\n }).join(\" \") + \"\\n\");\n var proc = child_process.spawnSync(cmd, args, { stdio: \"inherit\" });\n if (proc.error)\n throw proc.error;\n if (proc.status !== 0)\n throw Error(\"exited with \" + proc.status);\n return proc;\n}", "language": "javascript", "code": "function runCommand(cmd, args) {\n var prev = null;\n console.log(chalk.cyanBright(cmd) + \" \" + args.map(arg => {\n if (arg.startsWith(\"-\"))\n return chalk.gray(\"\\\\\") + \"\\n \" + chalk.bold(arg);\n return arg;\n }).join(\" \") + \"\\n\");\n var proc = child_process.spawnSync(cmd, args, { stdio: \"inherit\" });\n if (proc.error)\n throw proc.error;\n if (proc.status !== 0)\n throw Error(\"exited with \" + proc.status);\n return proc;\n}", "code_tokens": ["function", "runCommand", "(", "cmd", ",", "args", ")", "{", "var", "prev", "=", "null", ";", "console", ".", "log", "(", "chalk", ".", "cyanBright", "(", "cmd", ")", "+", "\" \"", "+", "args", ".", "map", "(", "arg", "=>", "{", "if", "(", "arg", ".", "startsWith", "(", "\"-\"", ")", ")", "return", "chalk", ".", "gray", "(", "\"\\\\\"", ")", "+", "\\\\", "+", "\"\\n \"", ";", "\\n", "}", ")", ".", "chalk", ".", "bold", "(", "arg", ")", "return", "arg", ";", "+", "join", ")", ";", "(", "\" \"", ")", "\"\\n\"", "\\n", "var", "proc", "=", "child_process", ".", "spawnSync", "(", "cmd", ",", "args", ",", "{", "stdio", ":", "\"inherit\"", "}", ")", ";", "}"], "docstring": "Runs a command using the specified arguments.", "docstring_tokens": ["Runs", "a", "command", "using", "the", "specified", "arguments", "."], "sha": "43effe71e5bf6488752a468e295b94ba6ecbf571", "url": "https://github.com/AssemblyScript/binaryen.js/blob/43effe71e5bf6488752a468e295b94ba6ecbf571/scripts/build.js#L55-L68", "partition": "test"} {"repo": "AssemblyScript/binaryen.js", "path": "scripts/build.js", "func_name": "compileIntrinsics", "original_string": "function compileIntrinsics() {\n var target = path.join(sourceDirectory, \"passes\", \"WasmIntrinsics.cpp\");\n runCommand(\"python\", [\n path.join(binaryenDirectory, \"scripts\", \"embedwast.py\"),\n path.join(sourceDirectory, \"passes\", \"wasm-intrinsics.wast\"),\n target\n ]);\n sourceFiles.push(target);\n}", "language": "javascript", "code": "function compileIntrinsics() {\n var target = path.join(sourceDirectory, \"passes\", \"WasmIntrinsics.cpp\");\n runCommand(\"python\", [\n path.join(binaryenDirectory, \"scripts\", \"embedwast.py\"),\n path.join(sourceDirectory, \"passes\", \"wasm-intrinsics.wast\"),\n target\n ]);\n sourceFiles.push(target);\n}", "code_tokens": ["function", "compileIntrinsics", "(", ")", "{", "var", "target", "=", "path", ".", "join", "(", "sourceDirectory", ",", "\"passes\"", ",", "\"WasmIntrinsics.cpp\"", ")", ";", "runCommand", "(", "\"python\"", ",", "[", "path", ".", "join", "(", "binaryenDirectory", ",", "\"scripts\"", ",", "\"embedwast.py\"", ")", ",", "path", ".", "join", "(", "sourceDirectory", ",", "\"passes\"", ",", "\"wasm-intrinsics.wast\"", ")", ",", "target", "]", ")", ";", "sourceFiles", ".", "push", "(", "target", ")", ";", "}"], "docstring": "Compiles embedded intrinsics used by the targets below.", "docstring_tokens": ["Compiles", "embedded", "intrinsics", "used", "by", "the", "targets", "below", "."], "sha": "43effe71e5bf6488752a468e295b94ba6ecbf571", "url": "https://github.com/AssemblyScript/binaryen.js/blob/43effe71e5bf6488752a468e295b94ba6ecbf571/scripts/build.js#L71-L79", "partition": "test"} {"repo": "AssemblyScript/binaryen.js", "path": "scripts/build.js", "func_name": "compileShared", "original_string": "function compileShared() {\n runCommand(\"python\", [\n path.join(emscriptenDirectory, \"em++\")\n ].concat(sourceFiles).concat(commonOptions).concat([\n \"-o\", \"shared.bc\"\n ]));\n}", "language": "javascript", "code": "function compileShared() {\n runCommand(\"python\", [\n path.join(emscriptenDirectory, \"em++\")\n ].concat(sourceFiles).concat(commonOptions).concat([\n \"-o\", \"shared.bc\"\n ]));\n}", "code_tokens": ["function", "compileShared", "(", ")", "{", "runCommand", "(", "\"python\"", ",", "[", "path", ".", "join", "(", "emscriptenDirectory", ",", "\"em++\"", ")", "]", ".", "concat", "(", "sourceFiles", ")", ".", "concat", "(", "commonOptions", ")", ".", "concat", "(", "[", "\"-o\"", ",", "\"shared.bc\"", "]", ")", ")", ";", "}"], "docstring": "Compiles shared bitcode used to build the targets below.", "docstring_tokens": ["Compiles", "shared", "bitcode", "used", "to", "build", "the", "targets", "below", "."], "sha": "43effe71e5bf6488752a468e295b94ba6ecbf571", "url": "https://github.com/AssemblyScript/binaryen.js/blob/43effe71e5bf6488752a468e295b94ba6ecbf571/scripts/build.js#L82-L88", "partition": "test"} {"repo": "AssemblyScript/binaryen.js", "path": "scripts/build.js", "func_name": "compileJs", "original_string": "function compileJs(options) {\n runCommand(\"python\", [\n path.join(emscriptenDirectory, \"em++\"),\n \"shared.bc\"\n ].concat(commonOptions).concat([\n \"--post-js\", options.post,\n \"--closure\", \"1\",\n \"-s\", \"WASM=0\",\n \"-s\", \"EXPORTED_FUNCTIONS=[\" + exportedFunctionsArg + \"]\",\n \"-s\", \"ALLOW_MEMORY_GROWTH=1\",\n \"-s\", \"ELIMINATE_DUPLICATE_FUNCTIONS=1\",\n \"-s\", \"MODULARIZE_INSTANCE=1\",\n \"-s\", \"EXPORT_NAME=\\\"Binaryen\\\"\",\n \"-o\", options.out,\n \"-Oz\"\n ]));\n}", "language": "javascript", "code": "function compileJs(options) {\n runCommand(\"python\", [\n path.join(emscriptenDirectory, \"em++\"),\n \"shared.bc\"\n ].concat(commonOptions).concat([\n \"--post-js\", options.post,\n \"--closure\", \"1\",\n \"-s\", \"WASM=0\",\n \"-s\", \"EXPORTED_FUNCTIONS=[\" + exportedFunctionsArg + \"]\",\n \"-s\", \"ALLOW_MEMORY_GROWTH=1\",\n \"-s\", \"ELIMINATE_DUPLICATE_FUNCTIONS=1\",\n \"-s\", \"MODULARIZE_INSTANCE=1\",\n \"-s\", \"EXPORT_NAME=\\\"Binaryen\\\"\",\n \"-o\", options.out,\n \"-Oz\"\n ]));\n}", "code_tokens": ["function", "compileJs", "(", "options", ")", "{", "runCommand", "(", "\"python\"", ",", "[", "path", ".", "join", "(", "emscriptenDirectory", ",", "\"em++\"", ")", ",", "\"shared.bc\"", "]", ".", "concat", "(", "commonOptions", ")", ".", "concat", "(", "[", "\"--post-js\"", ",", "options", ".", "post", ",", "\"--closure\"", ",", "\"1\"", ",", "\"-s\"", ",", "\"WASM=0\"", ",", "\"-s\"", ",", "\"EXPORTED_FUNCTIONS=[\"", "+", "exportedFunctionsArg", "+", "\"]\"", ",", "\"-s\"", ",", "\"ALLOW_MEMORY_GROWTH=1\"", ",", "\"-s\"", ",", "\"ELIMINATE_DUPLICATE_FUNCTIONS=1\"", ",", "\"-s\"", ",", "\"MODULARIZE_INSTANCE=1\"", ",", "\"-s\"", ",", "\"EXPORT_NAME=\\\"Binaryen\\\"\"", ",", "\\\"", ",", "\\\"", ",", "\"-o\"", "]", ")", ")", ";", "}"], "docstring": "Compiles the JavaScript target.", "docstring_tokens": ["Compiles", "the", "JavaScript", "target", "."], "sha": "43effe71e5bf6488752a468e295b94ba6ecbf571", "url": "https://github.com/AssemblyScript/binaryen.js/blob/43effe71e5bf6488752a468e295b94ba6ecbf571/scripts/build.js#L91-L107", "partition": "test"} {"repo": "AssemblyScript/binaryen.js", "path": "scripts/build.js", "func_name": "compileWasm", "original_string": "function compileWasm(options) {\n run(\"python\", [\n path.join(emscriptenDirectory, \"em++\"),\n \"shared.bc\"\n ].concat(commonOptions).concat([\n \"--post-js\", options.post,\n \"--closure\", \"1\",\n \"-s\", \"EXPORTED_FUNCTIONS=[\" + exportedFunctionsArg + \"]\",\n \"-s\", \"ALLOW_MEMORY_GROWTH=1\",\n \"-s\", \"BINARYEN=1\",\n \"-s\", \"BINARYEN_METHOD=\\\"native-wasm\\\"\",\n \"-s\", \"MODULARIZE_INSTANCE=1\",\n \"-s\", \"EXPORT_NAME=\\\"Binaryen\\\"\",\n \"-o\", options.out,\n \"-Oz\"\n ]));\n}", "language": "javascript", "code": "function compileWasm(options) {\n run(\"python\", [\n path.join(emscriptenDirectory, \"em++\"),\n \"shared.bc\"\n ].concat(commonOptions).concat([\n \"--post-js\", options.post,\n \"--closure\", \"1\",\n \"-s\", \"EXPORTED_FUNCTIONS=[\" + exportedFunctionsArg + \"]\",\n \"-s\", \"ALLOW_MEMORY_GROWTH=1\",\n \"-s\", \"BINARYEN=1\",\n \"-s\", \"BINARYEN_METHOD=\\\"native-wasm\\\"\",\n \"-s\", \"MODULARIZE_INSTANCE=1\",\n \"-s\", \"EXPORT_NAME=\\\"Binaryen\\\"\",\n \"-o\", options.out,\n \"-Oz\"\n ]));\n}", "code_tokens": ["function", "compileWasm", "(", "options", ")", "{", "run", "(", "\"python\"", ",", "[", "path", ".", "join", "(", "emscriptenDirectory", ",", "\"em++\"", ")", ",", "\"shared.bc\"", "]", ".", "concat", "(", "commonOptions", ")", ".", "concat", "(", "[", "\"--post-js\"", ",", "options", ".", "post", ",", "\"--closure\"", ",", "\"1\"", ",", "\"-s\"", ",", "\"EXPORTED_FUNCTIONS=[\"", "+", "exportedFunctionsArg", "+", "\"]\"", ",", "\"-s\"", ",", "\"ALLOW_MEMORY_GROWTH=1\"", ",", "\"-s\"", ",", "\"BINARYEN=1\"", ",", "\"-s\"", ",", "\"BINARYEN_METHOD=\\\"native-wasm\\\"\"", ",", "\\\"", ",", "\\\"", ",", "\"-s\"", ",", "\"MODULARIZE_INSTANCE=1\"", ",", "\"-s\"", ",", "\"EXPORT_NAME=\\\"Binaryen\\\"\"", ",", "\\\"", "]", ")", ")", ";", "}"], "docstring": "Compiles the WebAssembly target.", "docstring_tokens": ["Compiles", "the", "WebAssembly", "target", "."], "sha": "43effe71e5bf6488752a468e295b94ba6ecbf571", "url": "https://github.com/AssemblyScript/binaryen.js/blob/43effe71e5bf6488752a468e295b94ba6ecbf571/scripts/build.js#L110-L126", "partition": "test"} {"repo": "mesqueeb/vuex-easy-firestore", "path": "dist/index.esm.js", "func_name": "pluginState", "original_string": "function pluginState () {\n return {\n _sync: {\n signedIn: false,\n userId: null,\n unsubscribe: {},\n pathVariables: {},\n patching: false,\n syncStack: {\n inserts: [],\n updates: {},\n propDeletions: {},\n deletions: [],\n debounceTimer: null,\n },\n fetched: {},\n stopPatchingTimeout: null\n }\n };\n}", "language": "javascript", "code": "function pluginState () {\n return {\n _sync: {\n signedIn: false,\n userId: null,\n unsubscribe: {},\n pathVariables: {},\n patching: false,\n syncStack: {\n inserts: [],\n updates: {},\n propDeletions: {},\n deletions: [],\n debounceTimer: null,\n },\n fetched: {},\n stopPatchingTimeout: null\n }\n };\n}", "code_tokens": ["function", "pluginState", "(", ")", "{", "return", "{", "_sync", ":", "{", "signedIn", ":", "false", ",", "userId", ":", "null", ",", "unsubscribe", ":", "{", "}", ",", "pathVariables", ":", "{", "}", ",", "patching", ":", "false", ",", "syncStack", ":", "{", "inserts", ":", "[", "]", ",", "updates", ":", "{", "}", ",", "propDeletions", ":", "{", "}", ",", "deletions", ":", "[", "]", ",", "debounceTimer", ":", "null", ",", "}", ",", "fetched", ":", "{", "}", ",", "stopPatchingTimeout", ":", "null", "}", "}", ";", "}"], "docstring": "a function returning the state object\n\n@export\n@returns {IState} the state object", "docstring_tokens": ["a", "function", "returning", "the", "state", "object"], "sha": "08695ae1abd5c5bbfb6c3cfb618f17e7249f5667", "url": "https://github.com/mesqueeb/vuex-easy-firestore/blob/08695ae1abd5c5bbfb6c3cfb618f17e7249f5667/dist/index.esm.js#L63-L82", "partition": "test"} {"repo": "mesqueeb/vuex-easy-firestore", "path": "dist/index.esm.js", "func_name": "helpers", "original_string": "function helpers(originVal, newVal) {\n if (isArray(originVal) && isArrayHelper(newVal)) {\n newVal = newVal.executeOn(originVal);\n }\n if (isNumber(originVal) && isIncrementHelper(newVal)) {\n newVal = newVal.executeOn(originVal);\n }\n return newVal; // always return newVal as fallback!!\n }", "language": "javascript", "code": "function helpers(originVal, newVal) {\n if (isArray(originVal) && isArrayHelper(newVal)) {\n newVal = newVal.executeOn(originVal);\n }\n if (isNumber(originVal) && isIncrementHelper(newVal)) {\n newVal = newVal.executeOn(originVal);\n }\n return newVal; // always return newVal as fallback!!\n }", "code_tokens": ["function", "helpers", "(", "originVal", ",", "newVal", ")", "{", "if", "(", "isArray", "(", "originVal", ")", "&&", "isArrayHelper", "(", "newVal", ")", ")", "{", "newVal", "=", "newVal", ".", "executeOn", "(", "originVal", ")", ";", "}", "if", "(", "isNumber", "(", "originVal", ")", "&&", "isIncrementHelper", "(", "newVal", ")", ")", "{", "newVal", "=", "newVal", ".", "executeOn", "(", "originVal", ")", ";", "}", "return", "newVal", ";", "}"], "docstring": "Merge if exists", "docstring_tokens": ["Merge", "if", "exists"], "sha": "08695ae1abd5c5bbfb6c3cfb618f17e7249f5667", "url": "https://github.com/mesqueeb/vuex-easy-firestore/blob/08695ae1abd5c5bbfb6c3cfb618f17e7249f5667/dist/index.esm.js#L310-L318", "partition": "test"} {"repo": "mesqueeb/vuex-easy-firestore", "path": "dist/index.esm.js", "func_name": "makeBatchFromSyncstack", "original_string": "function makeBatchFromSyncstack(state, getters, Firebase, batchMaxCount) {\n if (batchMaxCount === void 0) { batchMaxCount = 500; }\n // get state & getter variables\n var firestorePath = state._conf.firestorePath;\n var firestorePathComplete = getters.firestorePathComplete;\n var dbRef = getters.dbRef;\n var collectionMode = getters.collectionMode;\n // make batch\n var batch = Firebase.firestore().batch();\n var log = {};\n var count = 0;\n // Add 'updates' to batch\n var updates = grabUntilApiLimit('updates', count, batchMaxCount, state);\n log['updates: '] = updates;\n count = count + updates.length;\n // Add to batch\n updates.forEach(function (item) {\n var id = item.id;\n var docRef = (collectionMode) ? dbRef.doc(id) : dbRef;\n if (state._conf.sync.guard.includes('id'))\n delete item.id;\n // @ts-ignore\n batch.update(docRef, item);\n });\n // Add 'propDeletions' to batch\n var propDeletions = grabUntilApiLimit('propDeletions', count, batchMaxCount, state);\n log['prop deletions: '] = propDeletions;\n count = count + propDeletions.length;\n // Add to batch\n propDeletions.forEach(function (item) {\n var id = item.id;\n var docRef = (collectionMode) ? dbRef.doc(id) : dbRef;\n if (state._conf.sync.guard.includes('id'))\n delete item.id;\n // @ts-ignore\n batch.update(docRef, item);\n });\n // Add 'deletions' to batch\n var deletions = grabUntilApiLimit('deletions', count, batchMaxCount, state);\n log['deletions: '] = deletions;\n count = count + deletions.length;\n // Add to batch\n deletions.forEach(function (id) {\n var docRef = dbRef.doc(id);\n batch.delete(docRef);\n });\n // Add 'inserts' to batch\n var inserts = grabUntilApiLimit('inserts', count, batchMaxCount, state);\n log['inserts: '] = inserts;\n count = count + inserts.length;\n // Add to batch\n inserts.forEach(function (item) {\n var newRef = dbRef.doc(item.id);\n batch.set(newRef, item);\n });\n // log the batch contents\n if (state._conf.logging) {\n console.group('[vuex-easy-firestore] api call batch:');\n console.log(\"%cFirestore PATH: \" + firestorePathComplete + \" [\" + firestorePath + \"]\", 'color: grey');\n Object.keys(log).forEach(function (key) {\n console.log(key, log[key]);\n });\n console.groupEnd();\n }\n return batch;\n}", "language": "javascript", "code": "function makeBatchFromSyncstack(state, getters, Firebase, batchMaxCount) {\n if (batchMaxCount === void 0) { batchMaxCount = 500; }\n // get state & getter variables\n var firestorePath = state._conf.firestorePath;\n var firestorePathComplete = getters.firestorePathComplete;\n var dbRef = getters.dbRef;\n var collectionMode = getters.collectionMode;\n // make batch\n var batch = Firebase.firestore().batch();\n var log = {};\n var count = 0;\n // Add 'updates' to batch\n var updates = grabUntilApiLimit('updates', count, batchMaxCount, state);\n log['updates: '] = updates;\n count = count + updates.length;\n // Add to batch\n updates.forEach(function (item) {\n var id = item.id;\n var docRef = (collectionMode) ? dbRef.doc(id) : dbRef;\n if (state._conf.sync.guard.includes('id'))\n delete item.id;\n // @ts-ignore\n batch.update(docRef, item);\n });\n // Add 'propDeletions' to batch\n var propDeletions = grabUntilApiLimit('propDeletions', count, batchMaxCount, state);\n log['prop deletions: '] = propDeletions;\n count = count + propDeletions.length;\n // Add to batch\n propDeletions.forEach(function (item) {\n var id = item.id;\n var docRef = (collectionMode) ? dbRef.doc(id) : dbRef;\n if (state._conf.sync.guard.includes('id'))\n delete item.id;\n // @ts-ignore\n batch.update(docRef, item);\n });\n // Add 'deletions' to batch\n var deletions = grabUntilApiLimit('deletions', count, batchMaxCount, state);\n log['deletions: '] = deletions;\n count = count + deletions.length;\n // Add to batch\n deletions.forEach(function (id) {\n var docRef = dbRef.doc(id);\n batch.delete(docRef);\n });\n // Add 'inserts' to batch\n var inserts = grabUntilApiLimit('inserts', count, batchMaxCount, state);\n log['inserts: '] = inserts;\n count = count + inserts.length;\n // Add to batch\n inserts.forEach(function (item) {\n var newRef = dbRef.doc(item.id);\n batch.set(newRef, item);\n });\n // log the batch contents\n if (state._conf.logging) {\n console.group('[vuex-easy-firestore] api call batch:');\n console.log(\"%cFirestore PATH: \" + firestorePathComplete + \" [\" + firestorePath + \"]\", 'color: grey');\n Object.keys(log).forEach(function (key) {\n console.log(key, log[key]);\n });\n console.groupEnd();\n }\n return batch;\n}", "code_tokens": ["function", "makeBatchFromSyncstack", "(", "state", ",", "getters", ",", "Firebase", ",", "batchMaxCount", ")", "{", "if", "(", "batchMaxCount", "===", "void", "0", ")", "{", "batchMaxCount", "=", "500", ";", "}", "var", "firestorePath", "=", "state", ".", "_conf", ".", "firestorePath", ";", "var", "firestorePathComplete", "=", "getters", ".", "firestorePathComplete", ";", "var", "dbRef", "=", "getters", ".", "dbRef", ";", "var", "collectionMode", "=", "getters", ".", "collectionMode", ";", "var", "batch", "=", "Firebase", ".", "firestore", "(", ")", ".", "batch", "(", ")", ";", "var", "log", "=", "{", "}", ";", "var", "count", "=", "0", ";", "var", "updates", "=", "grabUntilApiLimit", "(", "'updates'", ",", "count", ",", "batchMaxCount", ",", "state", ")", ";", "log", "[", "'updates: '", "]", "=", "updates", ";", "count", "=", "count", "+", "updates", ".", "length", ";", "updates", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "id", "=", "item", ".", "id", ";", "var", "docRef", "=", "(", "collectionMode", ")", "?", "dbRef", ".", "doc", "(", "id", ")", ":", "dbRef", ";", "if", "(", "state", ".", "_conf", ".", "sync", ".", "guard", ".", "includes", "(", "'id'", ")", ")", "delete", "item", ".", "id", ";", "batch", ".", "update", "(", "docRef", ",", "item", ")", ";", "}", ")", ";", "var", "propDeletions", "=", "grabUntilApiLimit", "(", "'propDeletions'", ",", "count", ",", "batchMaxCount", ",", "state", ")", ";", "log", "[", "'prop deletions: '", "]", "=", "propDeletions", ";", "count", "=", "count", "+", "propDeletions", ".", "length", ";", "propDeletions", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "id", "=", "item", ".", "id", ";", "var", "docRef", "=", "(", "collectionMode", ")", "?", "dbRef", ".", "doc", "(", "id", ")", ":", "dbRef", ";", "if", "(", "state", ".", "_conf", ".", "sync", ".", "guard", ".", "includes", "(", "'id'", ")", ")", "delete", "item", ".", "id", ";", "batch", ".", "update", "(", "docRef", ",", "item", ")", ";", "}", ")", ";", "var", "deletions", "=", "grabUntilApiLimit", "(", "'deletions'", ",", "count", ",", "batchMaxCount", ",", "state", ")", ";", "log", "[", "'deletions: '", "]", "=", "deletions", ";", "count", "=", "count", "+", "deletions", ".", "length", ";", "deletions", ".", "forEach", "(", "function", "(", "id", ")", "{", "var", "docRef", "=", "dbRef", ".", "doc", "(", "id", ")", ";", "batch", ".", "delete", "(", "docRef", ")", ";", "}", ")", ";", "var", "inserts", "=", "grabUntilApiLimit", "(", "'inserts'", ",", "count", ",", "batchMaxCount", ",", "state", ")", ";", "log", "[", "'inserts: '", "]", "=", "inserts", ";", "count", "=", "count", "+", "inserts", ".", "length", ";", "inserts", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "newRef", "=", "dbRef", ".", "doc", "(", "item", ".", "id", ")", ";", "batch", ".", "set", "(", "newRef", ",", "item", ")", ";", "}", ")", ";", "if", "(", "state", ".", "_conf", ".", "logging", ")", "{", "console", ".", "group", "(", "'[vuex-easy-firestore] api call batch:'", ")", ";", "console", ".", "log", "(", "\"%cFirestore PATH: \"", "+", "firestorePathComplete", "+", "\" [\"", "+", "firestorePath", "+", "\"]\"", ",", "'color: grey'", ")", ";", "Object", ".", "keys", "(", "log", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "console", ".", "log", "(", "key", ",", "log", "[", "key", "]", ")", ";", "}", ")", ";", "console", ".", "groupEnd", "(", ")", ";", "}", "return", "batch", ";", "}"], "docstring": "Create a Firebase batch from a syncStack to be passed inside the state param.\n\n@export\n@param {IPluginState} state The state which should have `_sync.syncStack`, `_sync.userId`, `state._conf.firestorePath`\n@param {AnyObject} getters The getters which should have `dbRef`, `storeRef`, `collectionMode` and `firestorePathComplete`\n@param {any} Firebase dependency injection for Firebase & Firestore\n@param {number} [batchMaxCount=500] The max count of the batch. Defaults to 500 as per Firestore documentation.\n@returns {*} A Firebase firestore batch object.", "docstring_tokens": ["Create", "a", "Firebase", "batch", "from", "a", "syncStack", "to", "be", "passed", "inside", "the", "state", "param", "."], "sha": "08695ae1abd5c5bbfb6c3cfb618f17e7249f5667", "url": "https://github.com/mesqueeb/vuex-easy-firestore/blob/08695ae1abd5c5bbfb6c3cfb618f17e7249f5667/dist/index.esm.js#L530-L595", "partition": "test"} {"repo": "mesqueeb/vuex-easy-firestore", "path": "dist/index.esm.js", "func_name": "iniModule", "original_string": "function iniModule (userConfig, FirebaseDependency) {\n // prepare state._conf\n var conf = copy(merge({ state: {}, mutations: {}, actions: {}, getters: {} }, defaultConfig, userConfig));\n if (!errorCheck(conf))\n return;\n var userState = conf.state;\n var userMutations = conf.mutations;\n var userActions = conf.actions;\n var userGetters = conf.getters;\n delete conf.state;\n delete conf.mutations;\n delete conf.actions;\n delete conf.getters;\n // prepare rest of state\n var docContainer = {};\n if (conf.statePropName)\n docContainer[conf.statePropName] = {};\n var restOfState = merge(userState, docContainer);\n // if 'doc' mode, set merge initial state onto default values\n if (conf.firestoreRefType === 'doc') {\n var defaultValsInState = (conf.statePropName)\n ? restOfState[conf.statePropName]\n : restOfState;\n conf.sync.defaultValues = copy(merge(defaultValsInState, conf.sync.defaultValues));\n }\n return {\n namespaced: true,\n state: merge(pluginState(), restOfState, { _conf: conf }),\n mutations: merge(userMutations, pluginMutations(merge(userState, { _conf: conf }))),\n actions: merge(userActions, pluginActions(FirebaseDependency)),\n getters: merge(userGetters, pluginGetters(FirebaseDependency))\n };\n}", "language": "javascript", "code": "function iniModule (userConfig, FirebaseDependency) {\n // prepare state._conf\n var conf = copy(merge({ state: {}, mutations: {}, actions: {}, getters: {} }, defaultConfig, userConfig));\n if (!errorCheck(conf))\n return;\n var userState = conf.state;\n var userMutations = conf.mutations;\n var userActions = conf.actions;\n var userGetters = conf.getters;\n delete conf.state;\n delete conf.mutations;\n delete conf.actions;\n delete conf.getters;\n // prepare rest of state\n var docContainer = {};\n if (conf.statePropName)\n docContainer[conf.statePropName] = {};\n var restOfState = merge(userState, docContainer);\n // if 'doc' mode, set merge initial state onto default values\n if (conf.firestoreRefType === 'doc') {\n var defaultValsInState = (conf.statePropName)\n ? restOfState[conf.statePropName]\n : restOfState;\n conf.sync.defaultValues = copy(merge(defaultValsInState, conf.sync.defaultValues));\n }\n return {\n namespaced: true,\n state: merge(pluginState(), restOfState, { _conf: conf }),\n mutations: merge(userMutations, pluginMutations(merge(userState, { _conf: conf }))),\n actions: merge(userActions, pluginActions(FirebaseDependency)),\n getters: merge(userGetters, pluginGetters(FirebaseDependency))\n };\n}", "code_tokens": ["function", "iniModule", "(", "userConfig", ",", "FirebaseDependency", ")", "{", "var", "conf", "=", "copy", "(", "merge", "(", "{", "state", ":", "{", "}", ",", "mutations", ":", "{", "}", ",", "actions", ":", "{", "}", ",", "getters", ":", "{", "}", "}", ",", "defaultConfig", ",", "userConfig", ")", ")", ";", "if", "(", "!", "errorCheck", "(", "conf", ")", ")", "return", ";", "var", "userState", "=", "conf", ".", "state", ";", "var", "userMutations", "=", "conf", ".", "mutations", ";", "var", "userActions", "=", "conf", ".", "actions", ";", "var", "userGetters", "=", "conf", ".", "getters", ";", "delete", "conf", ".", "state", ";", "delete", "conf", ".", "mutations", ";", "delete", "conf", ".", "actions", ";", "delete", "conf", ".", "getters", ";", "var", "docContainer", "=", "{", "}", ";", "if", "(", "conf", ".", "statePropName", ")", "docContainer", "[", "conf", ".", "statePropName", "]", "=", "{", "}", ";", "var", "restOfState", "=", "merge", "(", "userState", ",", "docContainer", ")", ";", "if", "(", "conf", ".", "firestoreRefType", "===", "'doc'", ")", "{", "var", "defaultValsInState", "=", "(", "conf", ".", "statePropName", ")", "?", "restOfState", "[", "conf", ".", "statePropName", "]", ":", "restOfState", ";", "conf", ".", "sync", ".", "defaultValues", "=", "copy", "(", "merge", "(", "defaultValsInState", ",", "conf", ".", "sync", ".", "defaultValues", ")", ")", ";", "}", "return", "{", "namespaced", ":", "true", ",", "state", ":", "merge", "(", "pluginState", "(", ")", ",", "restOfState", ",", "{", "_conf", ":", "conf", "}", ")", ",", "mutations", ":", "merge", "(", "userMutations", ",", "pluginMutations", "(", "merge", "(", "userState", ",", "{", "_conf", ":", "conf", "}", ")", ")", ")", ",", "actions", ":", "merge", "(", "userActions", ",", "pluginActions", "(", "FirebaseDependency", ")", ")", ",", "getters", ":", "merge", "(", "userGetters", ",", "pluginGetters", "(", "FirebaseDependency", ")", ")", "}", ";", "}"], "docstring": "A function that returns a vuex module object with seamless 2-way sync for firestore.\n\n@param {IEasyFirestoreModule} userConfig Takes a config object per module\n@param {*} FirebaseDependency The Firebase dependency (non-instanciated), defaults to the Firebase peer dependency if left blank.\n@returns {IStore} the module ready to be included in your vuex store", "docstring_tokens": ["A", "function", "that", "returns", "a", "vuex", "module", "object", "with", "seamless", "2", "-", "way", "sync", "for", "firestore", "."], "sha": "08695ae1abd5c5bbfb6c3cfb618f17e7249f5667", "url": "https://github.com/mesqueeb/vuex-easy-firestore/blob/08695ae1abd5c5bbfb6c3cfb618f17e7249f5667/dist/index.esm.js#L1771-L1803", "partition": "test"} {"repo": "mesqueeb/vuex-easy-firestore", "path": "dist/index.cjs.js", "func_name": "setDefaultValues", "original_string": "function setDefaultValues (obj, defaultValues) {\n if (!isWhat.isPlainObject(defaultValues))\n console.error('[vuex-easy-firestore] Trying to merge target:', obj, 'onto a non-object (defaultValues):', defaultValues);\n if (!isWhat.isPlainObject(obj))\n console.error('[vuex-easy-firestore] Trying to merge a non-object:', obj, 'onto the defaultValues:', defaultValues);\n var result = merge({ extensions: [convertTimestamps] }, defaultValues, obj);\n return findAndReplaceAnything.findAndReplace(result, '%convertTimestamp%', null, { onlyPlainObjects: true });\n}", "language": "javascript", "code": "function setDefaultValues (obj, defaultValues) {\n if (!isWhat.isPlainObject(defaultValues))\n console.error('[vuex-easy-firestore] Trying to merge target:', obj, 'onto a non-object (defaultValues):', defaultValues);\n if (!isWhat.isPlainObject(obj))\n console.error('[vuex-easy-firestore] Trying to merge a non-object:', obj, 'onto the defaultValues:', defaultValues);\n var result = merge({ extensions: [convertTimestamps] }, defaultValues, obj);\n return findAndReplaceAnything.findAndReplace(result, '%convertTimestamp%', null, { onlyPlainObjects: true });\n}", "code_tokens": ["function", "setDefaultValues", "(", "obj", ",", "defaultValues", ")", "{", "if", "(", "!", "isWhat", ".", "isPlainObject", "(", "defaultValues", ")", ")", "console", ".", "error", "(", "'[vuex-easy-firestore] Trying to merge target:'", ",", "obj", ",", "'onto a non-object (defaultValues):'", ",", "defaultValues", ")", ";", "if", "(", "!", "isWhat", ".", "isPlainObject", "(", "obj", ")", ")", "console", ".", "error", "(", "'[vuex-easy-firestore] Trying to merge a non-object:'", ",", "obj", ",", "'onto the defaultValues:'", ",", "defaultValues", ")", ";", "var", "result", "=", "merge", "(", "{", "extensions", ":", "[", "convertTimestamps", "]", "}", ",", "defaultValues", ",", "obj", ")", ";", "return", "findAndReplaceAnything", ".", "findAndReplace", "(", "result", ",", "'%convertTimestamp%'", ",", "null", ",", "{", "onlyPlainObjects", ":", "true", "}", ")", ";", "}"], "docstring": "Merge an object onto defaultValues\n\n@export\n@param {object} obj\n@param {object} defaultValues\n@returns {AnyObject} the new object", "docstring_tokens": ["Merge", "an", "object", "onto", "defaultValues"], "sha": "08695ae1abd5c5bbfb6c3cfb618f17e7249f5667", "url": "https://github.com/mesqueeb/vuex-easy-firestore/blob/08695ae1abd5c5bbfb6c3cfb618f17e7249f5667/dist/index.cjs.js#L447-L454", "partition": "test"} {"repo": "mesqueeb/vuex-easy-firestore", "path": "dist/index.cjs.js", "func_name": "getId", "original_string": "function getId(payloadPiece, conf, path, fullPayload) {\n if (isWhat.isString(payloadPiece))\n return payloadPiece;\n if (isWhat.isPlainObject(payloadPiece)) {\n if ('id' in payloadPiece)\n return payloadPiece.id;\n var keys = Object.keys(payloadPiece);\n if (keys.length === 1)\n return keys[0];\n }\n return '';\n}", "language": "javascript", "code": "function getId(payloadPiece, conf, path, fullPayload) {\n if (isWhat.isString(payloadPiece))\n return payloadPiece;\n if (isWhat.isPlainObject(payloadPiece)) {\n if ('id' in payloadPiece)\n return payloadPiece.id;\n var keys = Object.keys(payloadPiece);\n if (keys.length === 1)\n return keys[0];\n }\n return '';\n}", "code_tokens": ["function", "getId", "(", "payloadPiece", ",", "conf", ",", "path", ",", "fullPayload", ")", "{", "if", "(", "isWhat", ".", "isString", "(", "payloadPiece", ")", ")", "return", "payloadPiece", ";", "if", "(", "isWhat", ".", "isPlainObject", "(", "payloadPiece", ")", ")", "{", "if", "(", "'id'", "in", "payloadPiece", ")", "return", "payloadPiece", ".", "id", ";", "var", "keys", "=", "Object", ".", "keys", "(", "payloadPiece", ")", ";", "if", "(", "keys", ".", "length", "===", "1", ")", "return", "keys", "[", "0", "]", ";", "}", "return", "''", ";", "}"], "docstring": "gets an ID from a single piece of payload.\n\n@export\n@param {(object | string)} payloadPiece\n@param {object} [conf] (optional - for error handling) the vuex-easy-access config\n@param {string} [path] (optional - for error handling) the path called\n@param {(object | any[] | string)} [fullPayload] (optional - for error handling) the full payload on which each was `getId()` called\n@returns {string} the id", "docstring_tokens": ["gets", "an", "ID", "from", "a", "single", "piece", "of", "payload", "."], "sha": "08695ae1abd5c5bbfb6c3cfb618f17e7249f5667", "url": "https://github.com/mesqueeb/vuex-easy-firestore/blob/08695ae1abd5c5bbfb6c3cfb618f17e7249f5667/dist/index.cjs.js#L668-L679", "partition": "test"} {"repo": "mesqueeb/vuex-easy-firestore", "path": "dist/index.cjs.js", "func_name": "vuexEasyFirestore", "original_string": "function vuexEasyFirestore(easyFirestoreModule, _a) {\n var _b = _a === void 0 ? {\n logging: false,\n preventInitialDocInsertion: false,\n FirebaseDependency: Firebase$2\n } : _a, _c = _b.logging, logging = _c === void 0 ? false : _c, _d = _b.preventInitialDocInsertion, preventInitialDocInsertion = _d === void 0 ? false : _d, _e = _b.FirebaseDependency, FirebaseDependency = _e === void 0 ? Firebase$2 : _e;\n if (FirebaseDependency) {\n setFirebaseDependency(FirebaseDependency);\n setFirebaseDependency$1(FirebaseDependency);\n }\n return function (store) {\n // Get an array of config files\n if (!isWhat.isArray(easyFirestoreModule))\n easyFirestoreModule = [easyFirestoreModule];\n // Create a module for each config file\n easyFirestoreModule.forEach(function (config) {\n config.logging = logging;\n if (config.sync && config.sync.preventInitialDocInsertion === undefined) {\n config.sync.preventInitialDocInsertion = preventInitialDocInsertion;\n }\n var moduleName = vuexEasyAccess.getKeysFromPath(config.moduleName);\n store.registerModule(moduleName, iniModule(config, FirebaseDependency));\n });\n };\n}", "language": "javascript", "code": "function vuexEasyFirestore(easyFirestoreModule, _a) {\n var _b = _a === void 0 ? {\n logging: false,\n preventInitialDocInsertion: false,\n FirebaseDependency: Firebase$2\n } : _a, _c = _b.logging, logging = _c === void 0 ? false : _c, _d = _b.preventInitialDocInsertion, preventInitialDocInsertion = _d === void 0 ? false : _d, _e = _b.FirebaseDependency, FirebaseDependency = _e === void 0 ? Firebase$2 : _e;\n if (FirebaseDependency) {\n setFirebaseDependency(FirebaseDependency);\n setFirebaseDependency$1(FirebaseDependency);\n }\n return function (store) {\n // Get an array of config files\n if (!isWhat.isArray(easyFirestoreModule))\n easyFirestoreModule = [easyFirestoreModule];\n // Create a module for each config file\n easyFirestoreModule.forEach(function (config) {\n config.logging = logging;\n if (config.sync && config.sync.preventInitialDocInsertion === undefined) {\n config.sync.preventInitialDocInsertion = preventInitialDocInsertion;\n }\n var moduleName = vuexEasyAccess.getKeysFromPath(config.moduleName);\n store.registerModule(moduleName, iniModule(config, FirebaseDependency));\n });\n };\n}", "code_tokens": ["function", "vuexEasyFirestore", "(", "easyFirestoreModule", ",", "_a", ")", "{", "var", "_b", "=", "_a", "===", "void", "0", "?", "{", "logging", ":", "false", ",", "preventInitialDocInsertion", ":", "false", ",", "FirebaseDependency", ":", "Firebase$2", "}", ":", "_a", ",", "_c", "=", "_b", ".", "logging", ",", "logging", "=", "_c", "===", "void", "0", "?", "false", ":", "_c", ",", "_d", "=", "_b", ".", "preventInitialDocInsertion", ",", "preventInitialDocInsertion", "=", "_d", "===", "void", "0", "?", "false", ":", "_d", ",", "_e", "=", "_b", ".", "FirebaseDependency", ",", "FirebaseDependency", "=", "_e", "===", "void", "0", "?", "Firebase$2", ":", "_e", ";", "if", "(", "FirebaseDependency", ")", "{", "setFirebaseDependency", "(", "FirebaseDependency", ")", ";", "setFirebaseDependency$1", "(", "FirebaseDependency", ")", ";", "}", "return", "function", "(", "store", ")", "{", "if", "(", "!", "isWhat", ".", "isArray", "(", "easyFirestoreModule", ")", ")", "easyFirestoreModule", "=", "[", "easyFirestoreModule", "]", ";", "easyFirestoreModule", ".", "forEach", "(", "function", "(", "config", ")", "{", "config", ".", "logging", "=", "logging", ";", "if", "(", "config", ".", "sync", "&&", "config", ".", "sync", ".", "preventInitialDocInsertion", "===", "undefined", ")", "{", "config", ".", "sync", ".", "preventInitialDocInsertion", "=", "preventInitialDocInsertion", ";", "}", "var", "moduleName", "=", "vuexEasyAccess", ".", "getKeysFromPath", "(", "config", ".", "moduleName", ")", ";", "store", ".", "registerModule", "(", "moduleName", ",", "iniModule", "(", "config", ",", "FirebaseDependency", ")", ")", ";", "}", ")", ";", "}", ";", "}"], "docstring": "Firebase \nCreate vuex-easy-firestore modules. Add as single plugin to Vuex Store.\n\n@export\n@param {(IEasyFirestoreModule | IEasyFirestoreModule[])} easyFirestoreModule A vuex-easy-firestore module (or array of modules) with proper configuration as per the documentation.\n@param {{logging?: boolean, FirebaseDependency?: any}} extraConfig An object with `logging` and `FirebaseDependency` props. `logging` enables console logs for debugging. `FirebaseDependency` is the non-instanciated Firebase class you can pass. (defaults to the Firebase peer dependency)\n@returns {*}", "docstring_tokens": ["Firebase", "Create", "vuex", "-", "easy", "-", "firestore", "modules", ".", "Add", "as", "single", "plugin", "to", "Vuex", "Store", "."], "sha": "08695ae1abd5c5bbfb6c3cfb618f17e7249f5667", "url": "https://github.com/mesqueeb/vuex-easy-firestore/blob/08695ae1abd5c5bbfb6c3cfb618f17e7249f5667/dist/index.cjs.js#L1820-L1844", "partition": "test"} {"repo": "bkrem/react-d3-tree", "path": "src/util/index.js", "func_name": "parseCSV", "original_string": "function parseCSV(csvFilePath, attributeFields) {\n return new Promise((resolve, reject) => {\n try {\n csv(csvFilePath, data => resolve(_transformToHierarchy(data, attributeFields))); // lol hello Lisp\n } catch (err) {\n reject(err);\n }\n });\n}", "language": "javascript", "code": "function parseCSV(csvFilePath, attributeFields) {\n return new Promise((resolve, reject) => {\n try {\n csv(csvFilePath, data => resolve(_transformToHierarchy(data, attributeFields))); // lol hello Lisp\n } catch (err) {\n reject(err);\n }\n });\n}", "code_tokens": ["function", "parseCSV", "(", "csvFilePath", ",", "attributeFields", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "csv", "(", "csvFilePath", ",", "data", "=>", "resolve", "(", "_transformToHierarchy", "(", "data", ",", "attributeFields", ")", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "}", ")", ";", "}"], "docstring": "parseCSV - Parses a CSV file into a hierarchy structure.\n\n@param {string} csvFilePath Path to CSV file to be parsed.\n@param {array|undefined} attributeFields Set of column names to be used as attributes (optional)\n\n@return {Promise} Returns hierarchy array if resolved, error object if rejected.", "docstring_tokens": ["parseCSV", "-", "Parses", "a", "CSV", "file", "into", "a", "hierarchy", "structure", "."], "sha": "9084afca0f35e73dd6b7e7433a09907decd9f308", "url": "https://github.com/bkrem/react-d3-tree/blob/9084afca0f35e73dd6b7e7433a09907decd9f308/src/util/index.js#L72-L80", "partition": "test"} {"repo": "bkrem/react-d3-tree", "path": "src/util/index.js", "func_name": "parseJSON", "original_string": "function parseJSON(jsonFilePath) {\n return new Promise((resolve, reject) => {\n try {\n json(jsonFilePath, data => resolve([data]));\n } catch (err) {\n reject(err);\n }\n });\n}", "language": "javascript", "code": "function parseJSON(jsonFilePath) {\n return new Promise((resolve, reject) => {\n try {\n json(jsonFilePath, data => resolve([data]));\n } catch (err) {\n reject(err);\n }\n });\n}", "code_tokens": ["function", "parseJSON", "(", "jsonFilePath", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "json", "(", "jsonFilePath", ",", "data", "=>", "resolve", "(", "[", "data", "]", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "}", ")", ";", "}"], "docstring": "parseJSON - Parses a hierarchical JSON file that requires no further transformation.\n\n@param {string} jsonFilePath Path to JSON file to be parsed.\n\n@return {Promise} Returns hierarchy array if resolved, error object if rejected.", "docstring_tokens": ["parseJSON", "-", "Parses", "a", "hierarchical", "JSON", "file", "that", "requires", "no", "further", "transformation", "."], "sha": "9084afca0f35e73dd6b7e7433a09907decd9f308", "url": "https://github.com/bkrem/react-d3-tree/blob/9084afca0f35e73dd6b7e7433a09907decd9f308/src/util/index.js#L89-L97", "partition": "test"} {"repo": "bkrem/react-d3-tree", "path": "src/util/index.js", "func_name": "parseFlatJSON", "original_string": "function parseFlatJSON(jsonFilePath, attributeFields) {\n return new Promise((resolve, reject) => {\n try {\n json(jsonFilePath, data => resolve(_transformToHierarchy(data, attributeFields)));\n } catch (err) {\n reject(err);\n }\n });\n}", "language": "javascript", "code": "function parseFlatJSON(jsonFilePath, attributeFields) {\n return new Promise((resolve, reject) => {\n try {\n json(jsonFilePath, data => resolve(_transformToHierarchy(data, attributeFields)));\n } catch (err) {\n reject(err);\n }\n });\n}", "code_tokens": ["function", "parseFlatJSON", "(", "jsonFilePath", ",", "attributeFields", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "json", "(", "jsonFilePath", ",", "data", "=>", "resolve", "(", "_transformToHierarchy", "(", "data", ",", "attributeFields", ")", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "}", ")", ";", "}"], "docstring": "parseFlatJSON - Parses a flat JSON file into a hierarchy structure.\n\n@param {string} jsonFilePath Path to flat JSON file to be parsed.\n@param {array|undefined} attributeFields Set of `link` fields to be used as attributes\n\n@return {Promise} Returns hierarchy array if resolved, error object if rejected.", "docstring_tokens": ["parseFlatJSON", "-", "Parses", "a", "flat", "JSON", "file", "into", "a", "hierarchy", "structure", "."], "sha": "9084afca0f35e73dd6b7e7433a09907decd9f308", "url": "https://github.com/bkrem/react-d3-tree/blob/9084afca0f35e73dd6b7e7433a09907decd9f308/src/util/index.js#L107-L115", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "checkPropTypes", "original_string": "function checkPropTypes(typeSpecs, values, location, componentName, getStack) {\n if (true) {\n for (var typeSpecName in typeSpecs) {\n if (typeSpecs.hasOwnProperty(typeSpecName)) {\n var error;\n // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n var err = Error(\n (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +\n 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'\n );\n err.name = 'Invariant Violation';\n throw err;\n }\n error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);\n } catch (ex) {\n error = ex;\n }\n if (error && !(error instanceof Error)) {\n printWarning(\n (componentName || 'React class') + ': type specification of ' +\n location + ' `' + typeSpecName + '` is invalid; the type checker ' +\n 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +\n 'You may have forgotten to pass an argument to the type checker ' +\n 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +\n 'shape all require an argument).'\n )\n\n }\n if (error instanceof Error && !(error.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error.message] = true;\n\n var stack = getStack ? getStack() : '';\n\n printWarning(\n 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')\n );\n }\n }\n }\n }\n}", "language": "javascript", "code": "function checkPropTypes(typeSpecs, values, location, componentName, getStack) {\n if (true) {\n for (var typeSpecName in typeSpecs) {\n if (typeSpecs.hasOwnProperty(typeSpecName)) {\n var error;\n // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n var err = Error(\n (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +\n 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'\n );\n err.name = 'Invariant Violation';\n throw err;\n }\n error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);\n } catch (ex) {\n error = ex;\n }\n if (error && !(error instanceof Error)) {\n printWarning(\n (componentName || 'React class') + ': type specification of ' +\n location + ' `' + typeSpecName + '` is invalid; the type checker ' +\n 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +\n 'You may have forgotten to pass an argument to the type checker ' +\n 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +\n 'shape all require an argument).'\n )\n\n }\n if (error instanceof Error && !(error.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error.message] = true;\n\n var stack = getStack ? getStack() : '';\n\n printWarning(\n 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')\n );\n }\n }\n }\n }\n}", "code_tokens": ["function", "checkPropTypes", "(", "typeSpecs", ",", "values", ",", "location", ",", "componentName", ",", "getStack", ")", "{", "if", "(", "true", ")", "{", "for", "(", "var", "typeSpecName", "in", "typeSpecs", ")", "{", "if", "(", "typeSpecs", ".", "hasOwnProperty", "(", "typeSpecName", ")", ")", "{", "var", "error", ";", "try", "{", "if", "(", "typeof", "typeSpecs", "[", "typeSpecName", "]", "!==", "'function'", ")", "{", "var", "err", "=", "Error", "(", "(", "componentName", "||", "'React class'", ")", "+", "': '", "+", "location", "+", "' type `'", "+", "typeSpecName", "+", "'` is invalid; '", "+", "'it must be a function, usually from the `prop-types` package, but received `'", "+", "typeof", "typeSpecs", "[", "typeSpecName", "]", "+", "'`.'", ")", ";", "err", ".", "name", "=", "'Invariant Violation'", ";", "throw", "err", ";", "}", "error", "=", "typeSpecs", "[", "typeSpecName", "]", "(", "values", ",", "typeSpecName", ",", "componentName", ",", "location", ",", "null", ",", "ReactPropTypesSecret", ")", ";", "}", "catch", "(", "ex", ")", "{", "error", "=", "ex", ";", "}", "if", "(", "error", "&&", "!", "(", "error", "instanceof", "Error", ")", ")", "{", "printWarning", "(", "(", "componentName", "||", "'React class'", ")", "+", "': type specification of '", "+", "location", "+", "' `'", "+", "typeSpecName", "+", "'` is invalid; the type checker '", "+", "'function must return `null` or an `Error` but returned a '", "+", "typeof", "error", "+", "'. '", "+", "'You may have forgotten to pass an argument to the type checker '", "+", "'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and '", "+", "'shape all require an argument).'", ")", "}", "if", "(", "error", "instanceof", "Error", "&&", "!", "(", "error", ".", "message", "in", "loggedTypeFailures", ")", ")", "{", "loggedTypeFailures", "[", "error", ".", "message", "]", "=", "true", ";", "var", "stack", "=", "getStack", "?", "getStack", "(", ")", ":", "''", ";", "printWarning", "(", "'Failed '", "+", "location", "+", "' type: '", "+", "error", ".", "message", "+", "(", "stack", "!=", "null", "?", "stack", ":", "''", ")", ")", ";", "}", "}", "}", "}", "}"], "docstring": "Assert that the values match with the type specs.\nError messages are memorized and will only be shown once.\n\n@param {object} typeSpecs Map of name to a ReactPropType\n@param {object} values Runtime values that need to be type-checked\n@param {string} location e.g. \"prop\", \"context\", \"child context\"\n@param {string} componentName Name of the component for error messages.\n@param {?Function} getStack Returns the component stack.\n@private", "docstring_tokens": ["Assert", "that", "the", "values", "match", "with", "the", "type", "specs", ".", "Error", "messages", "are", "memorized", "and", "will", "only", "be", "shown", "once", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L2282-L2330", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "invokeGuardedCallback", "original_string": "function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {\n hasError = false;\n caughtError = null;\n invokeGuardedCallbackImpl$1.apply(reporter, arguments);\n}", "language": "javascript", "code": "function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {\n hasError = false;\n caughtError = null;\n invokeGuardedCallbackImpl$1.apply(reporter, arguments);\n}", "code_tokens": ["function", "invokeGuardedCallback", "(", "name", ",", "func", ",", "context", ",", "a", ",", "b", ",", "c", ",", "d", ",", "e", ",", "f", ")", "{", "hasError", "=", "false", ";", "caughtError", "=", "null", ";", "invokeGuardedCallbackImpl$1", ".", "apply", "(", "reporter", ",", "arguments", ")", ";", "}"], "docstring": "Call a function while guarding against errors that happens within it.\nReturns an error if it throws, otherwise null.\n\nIn production, this is implemented using a try-catch. The reason we don't\nuse a try-catch directly is so that we can swap out a different\nimplementation in DEV mode.\n\n@param {String} name of the guard to use for logging or debugging\n@param {Function} func The function to invoke\n@param {*} context The context to use when calling the function\n@param {...*} args Arguments for function", "docstring_tokens": ["Call", "a", "function", "while", "guarding", "against", "errors", "that", "happens", "within", "it", ".", "Returns", "an", "error", "if", "it", "throws", "otherwise", "null", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L2613-L2617", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "getClosestInstanceFromNode", "original_string": "function getClosestInstanceFromNode(node) {\n if (node[internalInstanceKey]) {\n return node[internalInstanceKey];\n }\n\n while (!node[internalInstanceKey]) {\n if (node.parentNode) {\n node = node.parentNode;\n } else {\n // Top of the tree. This node must not be part of a React tree (or is\n // unmounted, potentially).\n return null;\n }\n }\n\n var inst = node[internalInstanceKey];\n if (inst.tag === HostComponent || inst.tag === HostText) {\n // In Fiber, this will always be the deepest root.\n return inst;\n }\n\n return null;\n}", "language": "javascript", "code": "function getClosestInstanceFromNode(node) {\n if (node[internalInstanceKey]) {\n return node[internalInstanceKey];\n }\n\n while (!node[internalInstanceKey]) {\n if (node.parentNode) {\n node = node.parentNode;\n } else {\n // Top of the tree. This node must not be part of a React tree (or is\n // unmounted, potentially).\n return null;\n }\n }\n\n var inst = node[internalInstanceKey];\n if (inst.tag === HostComponent || inst.tag === HostText) {\n // In Fiber, this will always be the deepest root.\n return inst;\n }\n\n return null;\n}", "code_tokens": ["function", "getClosestInstanceFromNode", "(", "node", ")", "{", "if", "(", "node", "[", "internalInstanceKey", "]", ")", "{", "return", "node", "[", "internalInstanceKey", "]", ";", "}", "while", "(", "!", "node", "[", "internalInstanceKey", "]", ")", "{", "if", "(", "node", ".", "parentNode", ")", "{", "node", "=", "node", ".", "parentNode", ";", "}", "else", "{", "return", "null", ";", "}", "}", "var", "inst", "=", "node", "[", "internalInstanceKey", "]", ";", "if", "(", "inst", ".", "tag", "===", "HostComponent", "||", "inst", ".", "tag", "===", "HostText", ")", "{", "return", "inst", ";", "}", "return", "null", ";", "}"], "docstring": "Given a DOM node, return the closest ReactDOMComponent or\nReactDOMTextComponent instance ancestor.", "docstring_tokens": ["Given", "a", "DOM", "node", "return", "the", "closest", "ReactDOMComponent", "or", "ReactDOMTextComponent", "instance", "ancestor", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L3265-L3287", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "getInstanceFromNode$1", "original_string": "function getInstanceFromNode$1(node) {\n var inst = node[internalInstanceKey];\n if (inst) {\n if (inst.tag === HostComponent || inst.tag === HostText) {\n return inst;\n } else {\n return null;\n }\n }\n return null;\n}", "language": "javascript", "code": "function getInstanceFromNode$1(node) {\n var inst = node[internalInstanceKey];\n if (inst) {\n if (inst.tag === HostComponent || inst.tag === HostText) {\n return inst;\n } else {\n return null;\n }\n }\n return null;\n}", "code_tokens": ["function", "getInstanceFromNode$1", "(", "node", ")", "{", "var", "inst", "=", "node", "[", "internalInstanceKey", "]", ";", "if", "(", "inst", ")", "{", "if", "(", "inst", ".", "tag", "===", "HostComponent", "||", "inst", ".", "tag", "===", "HostText", ")", "{", "return", "inst", ";", "}", "else", "{", "return", "null", ";", "}", "}", "return", "null", ";", "}"], "docstring": "Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent\ninstance, or null if the node was not rendered by this React.", "docstring_tokens": ["Given", "a", "DOM", "node", "return", "the", "ReactDOMComponent", "or", "ReactDOMTextComponent", "instance", "or", "null", "if", "the", "node", "was", "not", "rendered", "by", "this", "React", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L3293-L3303", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "getNodeFromInstance$1", "original_string": "function getNodeFromInstance$1(inst) {\n if (inst.tag === HostComponent || inst.tag === HostText) {\n // In Fiber this, is just the state node right now. We assume it will be\n // a host component or host text.\n return inst.stateNode;\n }\n\n // Without this first invariant, passing a non-DOM-component triggers the next\n // invariant for a missing parent, which is super confusing.\n invariant(false, 'getNodeFromInstance: Invalid argument.');\n}", "language": "javascript", "code": "function getNodeFromInstance$1(inst) {\n if (inst.tag === HostComponent || inst.tag === HostText) {\n // In Fiber this, is just the state node right now. We assume it will be\n // a host component or host text.\n return inst.stateNode;\n }\n\n // Without this first invariant, passing a non-DOM-component triggers the next\n // invariant for a missing parent, which is super confusing.\n invariant(false, 'getNodeFromInstance: Invalid argument.');\n}", "code_tokens": ["function", "getNodeFromInstance$1", "(", "inst", ")", "{", "if", "(", "inst", ".", "tag", "===", "HostComponent", "||", "inst", ".", "tag", "===", "HostText", ")", "{", "return", "inst", ".", "stateNode", ";", "}", "invariant", "(", "false", ",", "'getNodeFromInstance: Invalid argument.'", ")", ";", "}"], "docstring": "Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding\nDOM node.", "docstring_tokens": ["Given", "a", "ReactDOMComponent", "or", "ReactDOMTextComponent", "return", "the", "corresponding", "DOM", "node", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L3309-L3319", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "traverseEnterLeave", "original_string": "function traverseEnterLeave(from, to, fn, argFrom, argTo) {\n var common = from && to ? getLowestCommonAncestor(from, to) : null;\n var pathFrom = [];\n while (true) {\n if (!from) {\n break;\n }\n if (from === common) {\n break;\n }\n var alternate = from.alternate;\n if (alternate !== null && alternate === common) {\n break;\n }\n pathFrom.push(from);\n from = getParent(from);\n }\n var pathTo = [];\n while (true) {\n if (!to) {\n break;\n }\n if (to === common) {\n break;\n }\n var _alternate = to.alternate;\n if (_alternate !== null && _alternate === common) {\n break;\n }\n pathTo.push(to);\n to = getParent(to);\n }\n for (var i = 0; i < pathFrom.length; i++) {\n fn(pathFrom[i], 'bubbled', argFrom);\n }\n for (var _i = pathTo.length; _i-- > 0;) {\n fn(pathTo[_i], 'captured', argTo);\n }\n}", "language": "javascript", "code": "function traverseEnterLeave(from, to, fn, argFrom, argTo) {\n var common = from && to ? getLowestCommonAncestor(from, to) : null;\n var pathFrom = [];\n while (true) {\n if (!from) {\n break;\n }\n if (from === common) {\n break;\n }\n var alternate = from.alternate;\n if (alternate !== null && alternate === common) {\n break;\n }\n pathFrom.push(from);\n from = getParent(from);\n }\n var pathTo = [];\n while (true) {\n if (!to) {\n break;\n }\n if (to === common) {\n break;\n }\n var _alternate = to.alternate;\n if (_alternate !== null && _alternate === common) {\n break;\n }\n pathTo.push(to);\n to = getParent(to);\n }\n for (var i = 0; i < pathFrom.length; i++) {\n fn(pathFrom[i], 'bubbled', argFrom);\n }\n for (var _i = pathTo.length; _i-- > 0;) {\n fn(pathTo[_i], 'captured', argTo);\n }\n}", "code_tokens": ["function", "traverseEnterLeave", "(", "from", ",", "to", ",", "fn", ",", "argFrom", ",", "argTo", ")", "{", "var", "common", "=", "from", "&&", "to", "?", "getLowestCommonAncestor", "(", "from", ",", "to", ")", ":", "null", ";", "var", "pathFrom", "=", "[", "]", ";", "while", "(", "true", ")", "{", "if", "(", "!", "from", ")", "{", "break", ";", "}", "if", "(", "from", "===", "common", ")", "{", "break", ";", "}", "var", "alternate", "=", "from", ".", "alternate", ";", "if", "(", "alternate", "!==", "null", "&&", "alternate", "===", "common", ")", "{", "break", ";", "}", "pathFrom", ".", "push", "(", "from", ")", ";", "from", "=", "getParent", "(", "from", ")", ";", "}", "var", "pathTo", "=", "[", "]", ";", "while", "(", "true", ")", "{", "if", "(", "!", "to", ")", "{", "break", ";", "}", "if", "(", "to", "===", "common", ")", "{", "break", ";", "}", "var", "_alternate", "=", "to", ".", "alternate", ";", "if", "(", "_alternate", "!==", "null", "&&", "_alternate", "===", "common", ")", "{", "break", ";", "}", "pathTo", ".", "push", "(", "to", ")", ";", "to", "=", "getParent", "(", "to", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "pathFrom", ".", "length", ";", "i", "++", ")", "{", "fn", "(", "pathFrom", "[", "i", "]", ",", "'bubbled'", ",", "argFrom", ")", ";", "}", "for", "(", "var", "_i", "=", "pathTo", ".", "length", ";", "_i", "--", ">", "0", ";", ")", "{", "fn", "(", "pathTo", "[", "_i", "]", ",", "'captured'", ",", "argTo", ")", ";", "}", "}"], "docstring": "Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that\nshould would receive a `mouseEnter` or `mouseLeave` event.\n\nDoes not invoke the callback on the nearest common ancestor because nothing\n\"entered\" or \"left\" that element.", "docstring_tokens": ["Traverses", "the", "ID", "hierarchy", "and", "invokes", "the", "supplied", "cb", "on", "any", "IDs", "that", "should", "would", "receive", "a", "mouseEnter", "or", "mouseLeave", "event", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L3417-L3455", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "makePrefixMap", "original_string": "function makePrefixMap(styleProp, eventName) {\n var prefixes = {};\n\n prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();\n prefixes['Webkit' + styleProp] = 'webkit' + eventName;\n prefixes['Moz' + styleProp] = 'moz' + eventName;\n\n return prefixes;\n}", "language": "javascript", "code": "function makePrefixMap(styleProp, eventName) {\n var prefixes = {};\n\n prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();\n prefixes['Webkit' + styleProp] = 'webkit' + eventName;\n prefixes['Moz' + styleProp] = 'moz' + eventName;\n\n return prefixes;\n}", "code_tokens": ["function", "makePrefixMap", "(", "styleProp", ",", "eventName", ")", "{", "var", "prefixes", "=", "{", "}", ";", "prefixes", "[", "styleProp", ".", "toLowerCase", "(", ")", "]", "=", "eventName", ".", "toLowerCase", "(", ")", ";", "prefixes", "[", "'Webkit'", "+", "styleProp", "]", "=", "'webkit'", "+", "eventName", ";", "prefixes", "[", "'Moz'", "+", "styleProp", "]", "=", "'moz'", "+", "eventName", ";", "return", "prefixes", ";", "}"], "docstring": "Generate a mapping of standard vendor prefixes using the defined style property and event name.\n\n@param {string} styleProp\n@param {string} eventName\n@returns {object}", "docstring_tokens": ["Generate", "a", "mapping", "of", "standard", "vendor", "prefixes", "using", "the", "defined", "style", "property", "and", "event", "name", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L3568-L3576", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "", "original_string": "function () {\n var Interface = this.constructor.Interface;\n for (var propName in Interface) {\n {\n Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));\n }\n }\n this.dispatchConfig = null;\n this._targetInst = null;\n this.nativeEvent = null;\n this.isDefaultPrevented = functionThatReturnsFalse;\n this.isPropagationStopped = functionThatReturnsFalse;\n this._dispatchListeners = null;\n this._dispatchInstances = null;\n {\n Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));\n Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));\n Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));\n Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));\n Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));\n }\n }", "language": "javascript", "code": "function () {\n var Interface = this.constructor.Interface;\n for (var propName in Interface) {\n {\n Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));\n }\n }\n this.dispatchConfig = null;\n this._targetInst = null;\n this.nativeEvent = null;\n this.isDefaultPrevented = functionThatReturnsFalse;\n this.isPropagationStopped = functionThatReturnsFalse;\n this._dispatchListeners = null;\n this._dispatchInstances = null;\n {\n Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));\n Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));\n Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));\n Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));\n Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));\n }\n }", "code_tokens": ["function", "(", ")", "{", "var", "Interface", "=", "this", ".", "constructor", ".", "Interface", ";", "for", "(", "var", "propName", "in", "Interface", ")", "{", "{", "Object", ".", "defineProperty", "(", "this", ",", "propName", ",", "getPooledWarningPropertyDefinition", "(", "propName", ",", "Interface", "[", "propName", "]", ")", ")", ";", "}", "}", "this", ".", "dispatchConfig", "=", "null", ";", "this", ".", "_targetInst", "=", "null", ";", "this", ".", "nativeEvent", "=", "null", ";", "this", ".", "isDefaultPrevented", "=", "functionThatReturnsFalse", ";", "this", ".", "isPropagationStopped", "=", "functionThatReturnsFalse", ";", "this", ".", "_dispatchListeners", "=", "null", ";", "this", ".", "_dispatchInstances", "=", "null", ";", "{", "Object", ".", "defineProperty", "(", "this", ",", "'nativeEvent'", ",", "getPooledWarningPropertyDefinition", "(", "'nativeEvent'", ",", "null", ")", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'isDefaultPrevented'", ",", "getPooledWarningPropertyDefinition", "(", "'isDefaultPrevented'", ",", "functionThatReturnsFalse", ")", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'isPropagationStopped'", ",", "getPooledWarningPropertyDefinition", "(", "'isPropagationStopped'", ",", "functionThatReturnsFalse", ")", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'preventDefault'", ",", "getPooledWarningPropertyDefinition", "(", "'preventDefault'", ",", "function", "(", ")", "{", "}", ")", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'stopPropagation'", ",", "getPooledWarningPropertyDefinition", "(", "'stopPropagation'", ",", "function", "(", ")", "{", "}", ")", ")", ";", "}", "}"], "docstring": "`PooledClass` looks for `destructor` on each instance it releases.", "docstring_tokens": ["PooledClass", "looks", "for", "destructor", "on", "each", "instance", "it", "releases", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L3958-L3979", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "getCompositionEventType", "original_string": "function getCompositionEventType(topLevelType) {\n switch (topLevelType) {\n case TOP_COMPOSITION_START:\n return eventTypes.compositionStart;\n case TOP_COMPOSITION_END:\n return eventTypes.compositionEnd;\n case TOP_COMPOSITION_UPDATE:\n return eventTypes.compositionUpdate;\n }\n}", "language": "javascript", "code": "function getCompositionEventType(topLevelType) {\n switch (topLevelType) {\n case TOP_COMPOSITION_START:\n return eventTypes.compositionStart;\n case TOP_COMPOSITION_END:\n return eventTypes.compositionEnd;\n case TOP_COMPOSITION_UPDATE:\n return eventTypes.compositionUpdate;\n }\n}", "code_tokens": ["function", "getCompositionEventType", "(", "topLevelType", ")", "{", "switch", "(", "topLevelType", ")", "{", "case", "TOP_COMPOSITION_START", ":", "return", "eventTypes", ".", "compositionStart", ";", "case", "TOP_COMPOSITION_END", ":", "return", "eventTypes", ".", "compositionEnd", ";", "case", "TOP_COMPOSITION_UPDATE", ":", "return", "eventTypes", ".", "compositionUpdate", ";", "}", "}"], "docstring": "Translate native top level events into event types.\n\n@param {string} topLevelType\n@return {object}", "docstring_tokens": ["Translate", "native", "top", "level", "events", "into", "event", "types", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L4161-L4170", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "isFallbackCompositionEnd", "original_string": "function isFallbackCompositionEnd(topLevelType, nativeEvent) {\n switch (topLevelType) {\n case TOP_KEY_UP:\n // Command keys insert or clear IME input.\n return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;\n case TOP_KEY_DOWN:\n // Expect IME keyCode on each keydown. If we get any other\n // code we must have exited earlier.\n return nativeEvent.keyCode !== START_KEYCODE;\n case TOP_KEY_PRESS:\n case TOP_MOUSE_DOWN:\n case TOP_BLUR:\n // Events are not possible without cancelling IME.\n return true;\n default:\n return false;\n }\n}", "language": "javascript", "code": "function isFallbackCompositionEnd(topLevelType, nativeEvent) {\n switch (topLevelType) {\n case TOP_KEY_UP:\n // Command keys insert or clear IME input.\n return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;\n case TOP_KEY_DOWN:\n // Expect IME keyCode on each keydown. If we get any other\n // code we must have exited earlier.\n return nativeEvent.keyCode !== START_KEYCODE;\n case TOP_KEY_PRESS:\n case TOP_MOUSE_DOWN:\n case TOP_BLUR:\n // Events are not possible without cancelling IME.\n return true;\n default:\n return false;\n }\n}", "code_tokens": ["function", "isFallbackCompositionEnd", "(", "topLevelType", ",", "nativeEvent", ")", "{", "switch", "(", "topLevelType", ")", "{", "case", "TOP_KEY_UP", ":", "return", "END_KEYCODES", ".", "indexOf", "(", "nativeEvent", ".", "keyCode", ")", "!==", "-", "1", ";", "case", "TOP_KEY_DOWN", ":", "return", "nativeEvent", ".", "keyCode", "!==", "START_KEYCODE", ";", "case", "TOP_KEY_PRESS", ":", "case", "TOP_MOUSE_DOWN", ":", "case", "TOP_BLUR", ":", "return", "true", ";", "default", ":", "return", "false", ";", "}", "}"], "docstring": "Does our fallback mode think that this event is the end of composition?\n\n@param {string} topLevelType\n@param {object} nativeEvent\n@return {boolean}", "docstring_tokens": ["Does", "our", "fallback", "mode", "think", "that", "this", "event", "is", "the", "end", "of", "composition?"], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L4191-L4208", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "getValueForProperty", "original_string": "function getValueForProperty(node, name, expected, propertyInfo) {\n {\n if (propertyInfo.mustUseProperty) {\n var propertyName = propertyInfo.propertyName;\n\n return node[propertyName];\n } else {\n var attributeName = propertyInfo.attributeName;\n\n var stringValue = null;\n\n if (propertyInfo.type === OVERLOADED_BOOLEAN) {\n if (node.hasAttribute(attributeName)) {\n var value = node.getAttribute(attributeName);\n if (value === '') {\n return true;\n }\n if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {\n return value;\n }\n if (value === '' + expected) {\n return expected;\n }\n return value;\n }\n } else if (node.hasAttribute(attributeName)) {\n if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {\n // We had an attribute but shouldn't have had one, so read it\n // for the error message.\n return node.getAttribute(attributeName);\n }\n if (propertyInfo.type === BOOLEAN) {\n // If this was a boolean, it doesn't matter what the value is\n // the fact that we have it is the same as the expected.\n return expected;\n }\n // Even if this property uses a namespace we use getAttribute\n // because we assume its namespaced name is the same as our config.\n // To use getAttributeNS we need the local name which we don't have\n // in our config atm.\n stringValue = node.getAttribute(attributeName);\n }\n\n if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {\n return stringValue === null ? expected : stringValue;\n } else if (stringValue === '' + expected) {\n return expected;\n } else {\n return stringValue;\n }\n }\n }\n}", "language": "javascript", "code": "function getValueForProperty(node, name, expected, propertyInfo) {\n {\n if (propertyInfo.mustUseProperty) {\n var propertyName = propertyInfo.propertyName;\n\n return node[propertyName];\n } else {\n var attributeName = propertyInfo.attributeName;\n\n var stringValue = null;\n\n if (propertyInfo.type === OVERLOADED_BOOLEAN) {\n if (node.hasAttribute(attributeName)) {\n var value = node.getAttribute(attributeName);\n if (value === '') {\n return true;\n }\n if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {\n return value;\n }\n if (value === '' + expected) {\n return expected;\n }\n return value;\n }\n } else if (node.hasAttribute(attributeName)) {\n if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {\n // We had an attribute but shouldn't have had one, so read it\n // for the error message.\n return node.getAttribute(attributeName);\n }\n if (propertyInfo.type === BOOLEAN) {\n // If this was a boolean, it doesn't matter what the value is\n // the fact that we have it is the same as the expected.\n return expected;\n }\n // Even if this property uses a namespace we use getAttribute\n // because we assume its namespaced name is the same as our config.\n // To use getAttributeNS we need the local name which we don't have\n // in our config atm.\n stringValue = node.getAttribute(attributeName);\n }\n\n if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {\n return stringValue === null ? expected : stringValue;\n } else if (stringValue === '' + expected) {\n return expected;\n } else {\n return stringValue;\n }\n }\n }\n}", "code_tokens": ["function", "getValueForProperty", "(", "node", ",", "name", ",", "expected", ",", "propertyInfo", ")", "{", "{", "if", "(", "propertyInfo", ".", "mustUseProperty", ")", "{", "var", "propertyName", "=", "propertyInfo", ".", "propertyName", ";", "return", "node", "[", "propertyName", "]", ";", "}", "else", "{", "var", "attributeName", "=", "propertyInfo", ".", "attributeName", ";", "var", "stringValue", "=", "null", ";", "if", "(", "propertyInfo", ".", "type", "===", "OVERLOADED_BOOLEAN", ")", "{", "if", "(", "node", ".", "hasAttribute", "(", "attributeName", ")", ")", "{", "var", "value", "=", "node", ".", "getAttribute", "(", "attributeName", ")", ";", "if", "(", "value", "===", "''", ")", "{", "return", "true", ";", "}", "if", "(", "shouldRemoveAttribute", "(", "name", ",", "expected", ",", "propertyInfo", ",", "false", ")", ")", "{", "return", "value", ";", "}", "if", "(", "value", "===", "''", "+", "expected", ")", "{", "return", "expected", ";", "}", "return", "value", ";", "}", "}", "else", "if", "(", "node", ".", "hasAttribute", "(", "attributeName", ")", ")", "{", "if", "(", "shouldRemoveAttribute", "(", "name", ",", "expected", ",", "propertyInfo", ",", "false", ")", ")", "{", "return", "node", ".", "getAttribute", "(", "attributeName", ")", ";", "}", "if", "(", "propertyInfo", ".", "type", "===", "BOOLEAN", ")", "{", "return", "expected", ";", "}", "stringValue", "=", "node", ".", "getAttribute", "(", "attributeName", ")", ";", "}", "if", "(", "shouldRemoveAttribute", "(", "name", ",", "expected", ",", "propertyInfo", ",", "false", ")", ")", "{", "return", "stringValue", "===", "null", "?", "expected", ":", "stringValue", ";", "}", "else", "if", "(", "stringValue", "===", "''", "+", "expected", ")", "{", "return", "expected", ";", "}", "else", "{", "return", "stringValue", ";", "}", "}", "}", "}"], "docstring": "Get the value for a property on a node. Only used in DEV for SSR validation.\nThe \"expected\" argument is used as a hint of what the expected value is.\nSome properties have multiple equivalent values.", "docstring_tokens": ["Get", "the", "value", "for", "a", "property", "on", "a", "node", ".", "Only", "used", "in", "DEV", "for", "SSR", "validation", ".", "The", "expected", "argument", "is", "used", "as", "a", "hint", "of", "what", "the", "expected", "value", "is", ".", "Some", "properties", "have", "multiple", "equivalent", "values", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L5312-L5364", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "getTargetInstForInputEventPolyfill", "original_string": "function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {\n if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {\n // On the selectionchange event, the target is just document which isn't\n // helpful for us so just check activeElement instead.\n //\n // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire\n // propertychange on the first input event after setting `value` from a\n // script and fires only keydown, keypress, keyup. Catching keyup usually\n // gets it and catching keydown lets us fire an event for the first\n // keystroke if user does a key repeat (it'll be a little delayed: right\n // before the second keystroke). Other input methods (e.g., paste) seem to\n // fire selectionchange normally.\n return getInstIfValueChanged(activeElementInst);\n }\n}", "language": "javascript", "code": "function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {\n if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {\n // On the selectionchange event, the target is just document which isn't\n // helpful for us so just check activeElement instead.\n //\n // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire\n // propertychange on the first input event after setting `value` from a\n // script and fires only keydown, keypress, keyup. Catching keyup usually\n // gets it and catching keydown lets us fire an event for the first\n // keystroke if user does a key repeat (it'll be a little delayed: right\n // before the second keystroke). Other input methods (e.g., paste) seem to\n // fire selectionchange normally.\n return getInstIfValueChanged(activeElementInst);\n }\n}", "code_tokens": ["function", "getTargetInstForInputEventPolyfill", "(", "topLevelType", ",", "targetInst", ")", "{", "if", "(", "topLevelType", "===", "TOP_SELECTION_CHANGE", "||", "topLevelType", "===", "TOP_KEY_UP", "||", "topLevelType", "===", "TOP_KEY_DOWN", ")", "{", "return", "getInstIfValueChanged", "(", "activeElementInst", ")", ";", "}", "}"], "docstring": "For IE8 and IE9.", "docstring_tokens": ["For", "IE8", "and", "IE9", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L6021-L6035", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "", "original_string": "function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {\n var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;\n var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;\n\n if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {\n return null;\n }\n\n if (!isOutEvent && !isOverEvent) {\n // Must not be a mouse or pointer in or out - ignoring.\n return null;\n }\n\n var win = void 0;\n if (nativeEventTarget.window === nativeEventTarget) {\n // `nativeEventTarget` is probably a window object.\n win = nativeEventTarget;\n } else {\n // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.\n var doc = nativeEventTarget.ownerDocument;\n if (doc) {\n win = doc.defaultView || doc.parentWindow;\n } else {\n win = window;\n }\n }\n\n var from = void 0;\n var to = void 0;\n if (isOutEvent) {\n from = targetInst;\n var related = nativeEvent.relatedTarget || nativeEvent.toElement;\n to = related ? getClosestInstanceFromNode(related) : null;\n } else {\n // Moving to a node from outside the window.\n from = null;\n to = targetInst;\n }\n\n if (from === to) {\n // Nothing pertains to our managed components.\n return null;\n }\n\n var eventInterface = void 0,\n leaveEventType = void 0,\n enterEventType = void 0,\n eventTypePrefix = void 0;\n\n if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {\n eventInterface = SyntheticMouseEvent;\n leaveEventType = eventTypes$2.mouseLeave;\n enterEventType = eventTypes$2.mouseEnter;\n eventTypePrefix = 'mouse';\n } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {\n eventInterface = SyntheticPointerEvent;\n leaveEventType = eventTypes$2.pointerLeave;\n enterEventType = eventTypes$2.pointerEnter;\n eventTypePrefix = 'pointer';\n }\n\n var fromNode = from == null ? win : getNodeFromInstance$1(from);\n var toNode = to == null ? win : getNodeFromInstance$1(to);\n\n var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);\n leave.type = eventTypePrefix + 'leave';\n leave.target = fromNode;\n leave.relatedTarget = toNode;\n\n var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);\n enter.type = eventTypePrefix + 'enter';\n enter.target = toNode;\n enter.relatedTarget = fromNode;\n\n accumulateEnterLeaveDispatches(leave, enter, from, to);\n\n return [leave, enter];\n }", "language": "javascript", "code": "function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {\n var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;\n var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;\n\n if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {\n return null;\n }\n\n if (!isOutEvent && !isOverEvent) {\n // Must not be a mouse or pointer in or out - ignoring.\n return null;\n }\n\n var win = void 0;\n if (nativeEventTarget.window === nativeEventTarget) {\n // `nativeEventTarget` is probably a window object.\n win = nativeEventTarget;\n } else {\n // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.\n var doc = nativeEventTarget.ownerDocument;\n if (doc) {\n win = doc.defaultView || doc.parentWindow;\n } else {\n win = window;\n }\n }\n\n var from = void 0;\n var to = void 0;\n if (isOutEvent) {\n from = targetInst;\n var related = nativeEvent.relatedTarget || nativeEvent.toElement;\n to = related ? getClosestInstanceFromNode(related) : null;\n } else {\n // Moving to a node from outside the window.\n from = null;\n to = targetInst;\n }\n\n if (from === to) {\n // Nothing pertains to our managed components.\n return null;\n }\n\n var eventInterface = void 0,\n leaveEventType = void 0,\n enterEventType = void 0,\n eventTypePrefix = void 0;\n\n if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {\n eventInterface = SyntheticMouseEvent;\n leaveEventType = eventTypes$2.mouseLeave;\n enterEventType = eventTypes$2.mouseEnter;\n eventTypePrefix = 'mouse';\n } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {\n eventInterface = SyntheticPointerEvent;\n leaveEventType = eventTypes$2.pointerLeave;\n enterEventType = eventTypes$2.pointerEnter;\n eventTypePrefix = 'pointer';\n }\n\n var fromNode = from == null ? win : getNodeFromInstance$1(from);\n var toNode = to == null ? win : getNodeFromInstance$1(to);\n\n var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);\n leave.type = eventTypePrefix + 'leave';\n leave.target = fromNode;\n leave.relatedTarget = toNode;\n\n var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);\n enter.type = eventTypePrefix + 'enter';\n enter.target = toNode;\n enter.relatedTarget = fromNode;\n\n accumulateEnterLeaveDispatches(leave, enter, from, to);\n\n return [leave, enter];\n }", "code_tokens": ["function", "(", "topLevelType", ",", "targetInst", ",", "nativeEvent", ",", "nativeEventTarget", ")", "{", "var", "isOverEvent", "=", "topLevelType", "===", "TOP_MOUSE_OVER", "||", "topLevelType", "===", "TOP_POINTER_OVER", ";", "var", "isOutEvent", "=", "topLevelType", "===", "TOP_MOUSE_OUT", "||", "topLevelType", "===", "TOP_POINTER_OUT", ";", "if", "(", "isOverEvent", "&&", "(", "nativeEvent", ".", "relatedTarget", "||", "nativeEvent", ".", "fromElement", ")", ")", "{", "return", "null", ";", "}", "if", "(", "!", "isOutEvent", "&&", "!", "isOverEvent", ")", "{", "return", "null", ";", "}", "var", "win", "=", "void", "0", ";", "if", "(", "nativeEventTarget", ".", "window", "===", "nativeEventTarget", ")", "{", "win", "=", "nativeEventTarget", ";", "}", "else", "{", "var", "doc", "=", "nativeEventTarget", ".", "ownerDocument", ";", "if", "(", "doc", ")", "{", "win", "=", "doc", ".", "defaultView", "||", "doc", ".", "parentWindow", ";", "}", "else", "{", "win", "=", "window", ";", "}", "}", "var", "from", "=", "void", "0", ";", "var", "to", "=", "void", "0", ";", "if", "(", "isOutEvent", ")", "{", "from", "=", "targetInst", ";", "var", "related", "=", "nativeEvent", ".", "relatedTarget", "||", "nativeEvent", ".", "toElement", ";", "to", "=", "related", "?", "getClosestInstanceFromNode", "(", "related", ")", ":", "null", ";", "}", "else", "{", "from", "=", "null", ";", "to", "=", "targetInst", ";", "}", "if", "(", "from", "===", "to", ")", "{", "return", "null", ";", "}", "var", "eventInterface", "=", "void", "0", ",", "leaveEventType", "=", "void", "0", ",", "enterEventType", "=", "void", "0", ",", "eventTypePrefix", "=", "void", "0", ";", "if", "(", "topLevelType", "===", "TOP_MOUSE_OUT", "||", "topLevelType", "===", "TOP_MOUSE_OVER", ")", "{", "eventInterface", "=", "SyntheticMouseEvent", ";", "leaveEventType", "=", "eventTypes$2", ".", "mouseLeave", ";", "enterEventType", "=", "eventTypes$2", ".", "mouseEnter", ";", "eventTypePrefix", "=", "'mouse'", ";", "}", "else", "if", "(", "topLevelType", "===", "TOP_POINTER_OUT", "||", "topLevelType", "===", "TOP_POINTER_OVER", ")", "{", "eventInterface", "=", "SyntheticPointerEvent", ";", "leaveEventType", "=", "eventTypes$2", ".", "pointerLeave", ";", "enterEventType", "=", "eventTypes$2", ".", "pointerEnter", ";", "eventTypePrefix", "=", "'pointer'", ";", "}", "var", "fromNode", "=", "from", "==", "null", "?", "win", ":", "getNodeFromInstance$1", "(", "from", ")", ";", "var", "toNode", "=", "to", "==", "null", "?", "win", ":", "getNodeFromInstance$1", "(", "to", ")", ";", "var", "leave", "=", "eventInterface", ".", "getPooled", "(", "leaveEventType", ",", "from", ",", "nativeEvent", ",", "nativeEventTarget", ")", ";", "leave", ".", "type", "=", "eventTypePrefix", "+", "'leave'", ";", "leave", ".", "target", "=", "fromNode", ";", "leave", ".", "relatedTarget", "=", "toNode", ";", "var", "enter", "=", "eventInterface", ".", "getPooled", "(", "enterEventType", ",", "to", ",", "nativeEvent", ",", "nativeEventTarget", ")", ";", "enter", ".", "type", "=", "eventTypePrefix", "+", "'enter'", ";", "enter", ".", "target", "=", "toNode", ";", "enter", ".", "relatedTarget", "=", "fromNode", ";", "accumulateEnterLeaveDispatches", "(", "leave", ",", "enter", ",", "from", ",", "to", ")", ";", "return", "[", "leave", ",", "enter", "]", ";", "}"], "docstring": "For almost every interaction we care about, there will be both a top-level\n`mouseover` and `mouseout` event that occurs. Only use `mouseout` so that\nwe do not extract duplicate events. However, moving the mouse into the\nbrowser from outside will not fire a `mouseout` event. In this case, we use\nthe `mouseover` top-level event.", "docstring_tokens": ["For", "almost", "every", "interaction", "we", "care", "about", "there", "will", "be", "both", "a", "top", "-", "level", "mouseover", "and", "mouseout", "event", "that", "occurs", ".", "Only", "use", "mouseout", "so", "that", "we", "do", "not", "extract", "duplicate", "events", ".", "However", "moving", "the", "mouse", "into", "the", "browser", "from", "outside", "will", "not", "fire", "a", "mouseout", "event", ".", "In", "this", "case", "we", "use", "the", "mouseover", "top", "-", "level", "event", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L6275-L6352", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "listenTo", "original_string": "function listenTo(registrationName, mountAt) {\n var isListening = getListeningForDocument(mountAt);\n var dependencies = registrationNameDependencies[registrationName];\n\n for (var i = 0; i < dependencies.length; i++) {\n var dependency = dependencies[i];\n if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {\n switch (dependency) {\n case TOP_SCROLL:\n trapCapturedEvent(TOP_SCROLL, mountAt);\n break;\n case TOP_FOCUS:\n case TOP_BLUR:\n trapCapturedEvent(TOP_FOCUS, mountAt);\n trapCapturedEvent(TOP_BLUR, mountAt);\n // We set the flag for a single dependency later in this function,\n // but this ensures we mark both as attached rather than just one.\n isListening[TOP_BLUR] = true;\n isListening[TOP_FOCUS] = true;\n break;\n case TOP_CANCEL:\n case TOP_CLOSE:\n if (isEventSupported(getRawEventName(dependency))) {\n trapCapturedEvent(dependency, mountAt);\n }\n break;\n case TOP_INVALID:\n case TOP_SUBMIT:\n case TOP_RESET:\n // We listen to them on the target DOM elements.\n // Some of them bubble so we don't want them to fire twice.\n break;\n default:\n // By default, listen on the top level to all non-media events.\n // Media events don't bubble so adding the listener wouldn't do anything.\n var isMediaEvent = mediaEventTypes.indexOf(dependency) !== -1;\n if (!isMediaEvent) {\n trapBubbledEvent(dependency, mountAt);\n }\n break;\n }\n isListening[dependency] = true;\n }\n }\n}", "language": "javascript", "code": "function listenTo(registrationName, mountAt) {\n var isListening = getListeningForDocument(mountAt);\n var dependencies = registrationNameDependencies[registrationName];\n\n for (var i = 0; i < dependencies.length; i++) {\n var dependency = dependencies[i];\n if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {\n switch (dependency) {\n case TOP_SCROLL:\n trapCapturedEvent(TOP_SCROLL, mountAt);\n break;\n case TOP_FOCUS:\n case TOP_BLUR:\n trapCapturedEvent(TOP_FOCUS, mountAt);\n trapCapturedEvent(TOP_BLUR, mountAt);\n // We set the flag for a single dependency later in this function,\n // but this ensures we mark both as attached rather than just one.\n isListening[TOP_BLUR] = true;\n isListening[TOP_FOCUS] = true;\n break;\n case TOP_CANCEL:\n case TOP_CLOSE:\n if (isEventSupported(getRawEventName(dependency))) {\n trapCapturedEvent(dependency, mountAt);\n }\n break;\n case TOP_INVALID:\n case TOP_SUBMIT:\n case TOP_RESET:\n // We listen to them on the target DOM elements.\n // Some of them bubble so we don't want them to fire twice.\n break;\n default:\n // By default, listen on the top level to all non-media events.\n // Media events don't bubble so adding the listener wouldn't do anything.\n var isMediaEvent = mediaEventTypes.indexOf(dependency) !== -1;\n if (!isMediaEvent) {\n trapBubbledEvent(dependency, mountAt);\n }\n break;\n }\n isListening[dependency] = true;\n }\n }\n}", "code_tokens": ["function", "listenTo", "(", "registrationName", ",", "mountAt", ")", "{", "var", "isListening", "=", "getListeningForDocument", "(", "mountAt", ")", ";", "var", "dependencies", "=", "registrationNameDependencies", "[", "registrationName", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "dependencies", ".", "length", ";", "i", "++", ")", "{", "var", "dependency", "=", "dependencies", "[", "i", "]", ";", "if", "(", "!", "(", "isListening", ".", "hasOwnProperty", "(", "dependency", ")", "&&", "isListening", "[", "dependency", "]", ")", ")", "{", "switch", "(", "dependency", ")", "{", "case", "TOP_SCROLL", ":", "trapCapturedEvent", "(", "TOP_SCROLL", ",", "mountAt", ")", ";", "break", ";", "case", "TOP_FOCUS", ":", "case", "TOP_BLUR", ":", "trapCapturedEvent", "(", "TOP_FOCUS", ",", "mountAt", ")", ";", "trapCapturedEvent", "(", "TOP_BLUR", ",", "mountAt", ")", ";", "isListening", "[", "TOP_BLUR", "]", "=", "true", ";", "isListening", "[", "TOP_FOCUS", "]", "=", "true", ";", "break", ";", "case", "TOP_CANCEL", ":", "case", "TOP_CLOSE", ":", "if", "(", "isEventSupported", "(", "getRawEventName", "(", "dependency", ")", ")", ")", "{", "trapCapturedEvent", "(", "dependency", ",", "mountAt", ")", ";", "}", "break", ";", "case", "TOP_INVALID", ":", "case", "TOP_SUBMIT", ":", "case", "TOP_RESET", ":", "break", ";", "default", ":", "var", "isMediaEvent", "=", "mediaEventTypes", ".", "indexOf", "(", "dependency", ")", "!==", "-", "1", ";", "if", "(", "!", "isMediaEvent", ")", "{", "trapBubbledEvent", "(", "dependency", ",", "mountAt", ")", ";", "}", "break", ";", "}", "isListening", "[", "dependency", "]", "=", "true", ";", "}", "}", "}"], "docstring": "We listen for bubbled touch events on the document object.\n\nFirefox v8.01 (and possibly others) exhibited strange behavior when\nmounting `onmousemove` events at some node that was not the document\nelement. The symptoms were that if your mouse is not moving over something\ncontained within that mount point (for example on the background) the\ntop-level listeners for `onmousemove` won't be called. However, if you\nregister the `mousemove` on the document object, then it will of course\ncatch all `mousemove`s. This along with iOS quirks, justifies restricting\ntop-level listeners to the document object only, at least for these\nmovement types of events and possibly all events.\n\n@see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html\n\nAlso, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but\nthey bubble to document.\n\n@param {string} registrationName Name of listener (e.g. `onClick`).\n@param {object} mountAt Container where to mount the listener", "docstring_tokens": ["We", "listen", "for", "bubbled", "touch", "events", "on", "the", "document", "object", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L7405-L7449", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "getEventTargetDocument", "original_string": "function getEventTargetDocument(eventTarget) {\n return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;\n}", "language": "javascript", "code": "function getEventTargetDocument(eventTarget) {\n return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;\n}", "code_tokens": ["function", "getEventTargetDocument", "(", "eventTarget", ")", "{", "return", "eventTarget", ".", "window", "===", "eventTarget", "?", "eventTarget", ".", "document", ":", "eventTarget", ".", "nodeType", "===", "DOCUMENT_NODE", "?", "eventTarget", ":", "eventTarget", ".", "ownerDocument", ";", "}"], "docstring": "Get document associated with the event target.\n\n@param {object} nativeEventTarget\n@return {Document}", "docstring_tokens": ["Get", "document", "associated", "with", "the", "event", "target", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L7901-L7903", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "constructSelectEvent", "original_string": "function constructSelectEvent(nativeEvent, nativeEventTarget) {\n // Ensure we have the right element, and that the user is not dragging a\n // selection (this matches native `select` event behavior). In HTML5, select\n // fires only on input and textarea thus if there's no focused element we\n // won't dispatch.\n var doc = getEventTargetDocument(nativeEventTarget);\n\n if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {\n return null;\n }\n\n // Only fire when selection has actually changed.\n var currentSelection = getSelection(activeElement$1);\n if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {\n lastSelection = currentSelection;\n\n var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);\n\n syntheticEvent.type = 'select';\n syntheticEvent.target = activeElement$1;\n\n accumulateTwoPhaseDispatches(syntheticEvent);\n\n return syntheticEvent;\n }\n\n return null;\n}", "language": "javascript", "code": "function constructSelectEvent(nativeEvent, nativeEventTarget) {\n // Ensure we have the right element, and that the user is not dragging a\n // selection (this matches native `select` event behavior). In HTML5, select\n // fires only on input and textarea thus if there's no focused element we\n // won't dispatch.\n var doc = getEventTargetDocument(nativeEventTarget);\n\n if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {\n return null;\n }\n\n // Only fire when selection has actually changed.\n var currentSelection = getSelection(activeElement$1);\n if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {\n lastSelection = currentSelection;\n\n var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);\n\n syntheticEvent.type = 'select';\n syntheticEvent.target = activeElement$1;\n\n accumulateTwoPhaseDispatches(syntheticEvent);\n\n return syntheticEvent;\n }\n\n return null;\n}", "code_tokens": ["function", "constructSelectEvent", "(", "nativeEvent", ",", "nativeEventTarget", ")", "{", "var", "doc", "=", "getEventTargetDocument", "(", "nativeEventTarget", ")", ";", "if", "(", "mouseDown", "||", "activeElement$1", "==", "null", "||", "activeElement$1", "!==", "getActiveElement", "(", "doc", ")", ")", "{", "return", "null", ";", "}", "var", "currentSelection", "=", "getSelection", "(", "activeElement$1", ")", ";", "if", "(", "!", "lastSelection", "||", "!", "shallowEqual", "(", "lastSelection", ",", "currentSelection", ")", ")", "{", "lastSelection", "=", "currentSelection", ";", "var", "syntheticEvent", "=", "SyntheticEvent", ".", "getPooled", "(", "eventTypes$3", ".", "select", ",", "activeElementInst$1", ",", "nativeEvent", ",", "nativeEventTarget", ")", ";", "syntheticEvent", ".", "type", "=", "'select'", ";", "syntheticEvent", ".", "target", "=", "activeElement$1", ";", "accumulateTwoPhaseDispatches", "(", "syntheticEvent", ")", ";", "return", "syntheticEvent", ";", "}", "return", "null", ";", "}"], "docstring": "Poll selection to see whether it's changed.\n\n@param {object} nativeEvent\n@param {object} nativeEventTarget\n@return {?SyntheticEvent}", "docstring_tokens": ["Poll", "selection", "to", "see", "whether", "it", "s", "changed", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L7912-L7939", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "", "original_string": "function (node, text) {\n if (text) {\n var firstChild = node.firstChild;\n\n if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {\n firstChild.nodeValue = text;\n return;\n }\n }\n node.textContent = text;\n}", "language": "javascript", "code": "function (node, text) {\n if (text) {\n var firstChild = node.firstChild;\n\n if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {\n firstChild.nodeValue = text;\n return;\n }\n }\n node.textContent = text;\n}", "code_tokens": ["function", "(", "node", ",", "text", ")", "{", "if", "(", "text", ")", "{", "var", "firstChild", "=", "node", ".", "firstChild", ";", "if", "(", "firstChild", "&&", "firstChild", "===", "node", ".", "lastChild", "&&", "firstChild", ".", "nodeType", "===", "TEXT_NODE", ")", "{", "firstChild", ".", "nodeValue", "=", "text", ";", "return", ";", "}", "}", "node", ".", "textContent", "=", "text", ";", "}"], "docstring": "Set the textContent property of a node. For text updates, it's faster\nto set the `nodeValue` of the Text node directly instead of using\n`.textContent` which will remove the existing node and create a new one.\n\n@param {DOMElement} node\n@param {string} text\n@internal", "docstring_tokens": ["Set", "the", "textContent", "property", "of", "a", "node", ".", "For", "text", "updates", "it", "s", "faster", "to", "set", "the", "nodeValue", "of", "the", "Text", "node", "directly", "instead", "of", "using", ".", "textContent", "which", "will", "remove", "the", "existing", "node", "and", "create", "a", "new", "one", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L8478-L8488", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "createDangerousStringForStyles", "original_string": "function createDangerousStringForStyles(styles) {\n {\n var serialized = '';\n var delimiter = '';\n for (var styleName in styles) {\n if (!styles.hasOwnProperty(styleName)) {\n continue;\n }\n var styleValue = styles[styleName];\n if (styleValue != null) {\n var isCustomProperty = styleName.indexOf('--') === 0;\n serialized += delimiter + hyphenateStyleName(styleName) + ':';\n serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);\n\n delimiter = ';';\n }\n }\n return serialized || null;\n }\n}", "language": "javascript", "code": "function createDangerousStringForStyles(styles) {\n {\n var serialized = '';\n var delimiter = '';\n for (var styleName in styles) {\n if (!styles.hasOwnProperty(styleName)) {\n continue;\n }\n var styleValue = styles[styleName];\n if (styleValue != null) {\n var isCustomProperty = styleName.indexOf('--') === 0;\n serialized += delimiter + hyphenateStyleName(styleName) + ':';\n serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);\n\n delimiter = ';';\n }\n }\n return serialized || null;\n }\n}", "code_tokens": ["function", "createDangerousStringForStyles", "(", "styles", ")", "{", "{", "var", "serialized", "=", "''", ";", "var", "delimiter", "=", "''", ";", "for", "(", "var", "styleName", "in", "styles", ")", "{", "if", "(", "!", "styles", ".", "hasOwnProperty", "(", "styleName", ")", ")", "{", "continue", ";", "}", "var", "styleValue", "=", "styles", "[", "styleName", "]", ";", "if", "(", "styleValue", "!=", "null", ")", "{", "var", "isCustomProperty", "=", "styleName", ".", "indexOf", "(", "'--'", ")", "===", "0", ";", "serialized", "+=", "delimiter", "+", "hyphenateStyleName", "(", "styleName", ")", "+", "':'", ";", "serialized", "+=", "dangerousStyleValue", "(", "styleName", ",", "styleValue", ",", "isCustomProperty", ")", ";", "delimiter", "=", "';'", ";", "}", "}", "return", "serialized", "||", "null", ";", "}", "}"], "docstring": "Operations for dealing with CSS properties.\n \nThis creates a string that is expected to be equivalent to the style\nattribute generated by server-side rendering. It by-passes warnings and\nsecurity checks so it's not safe to use this value for anything other than\ncomparison. It is only used in DEV for SSR validation.", "docstring_tokens": ["Operations", "for", "dealing", "with", "CSS", "properties", ".", "This", "creates", "a", "string", "that", "is", "expected", "to", "be", "equivalent", "to", "the", "style", "attribute", "generated", "by", "server", "-", "side", "rendering", ".", "It", "by", "-", "passes", "warnings", "and", "security", "checks", "so", "it", "s", "not", "safe", "to", "use", "this", "value", "for", "anything", "other", "than", "comparison", ".", "It", "is", "only", "used", "in", "DEV", "for", "SSR", "validation", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L8718-L8737", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "", "original_string": "function (containerChildSet, workInProgress) {\n // We only have the top Fiber that was created but we need recurse down its\n // children to find all the terminal nodes.\n var node = workInProgress.child;\n while (node !== null) {\n if (node.tag === HostComponent || node.tag === HostText) {\n appendChildToContainerChildSet(containerChildSet, node.stateNode);\n } else if (node.tag === HostPortal) {\n // If we have a portal child, then we don't want to traverse\n // down its children. Instead, we'll get insertions from each child in\n // the portal directly.\n } else if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n if (node === workInProgress) {\n return;\n }\n while (node.sibling === null) {\n if (node.return === null || node.return === workInProgress) {\n return;\n }\n node = node.return;\n }\n node.sibling.return = node.return;\n node = node.sibling;\n }\n }", "language": "javascript", "code": "function (containerChildSet, workInProgress) {\n // We only have the top Fiber that was created but we need recurse down its\n // children to find all the terminal nodes.\n var node = workInProgress.child;\n while (node !== null) {\n if (node.tag === HostComponent || node.tag === HostText) {\n appendChildToContainerChildSet(containerChildSet, node.stateNode);\n } else if (node.tag === HostPortal) {\n // If we have a portal child, then we don't want to traverse\n // down its children. Instead, we'll get insertions from each child in\n // the portal directly.\n } else if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n if (node === workInProgress) {\n return;\n }\n while (node.sibling === null) {\n if (node.return === null || node.return === workInProgress) {\n return;\n }\n node = node.return;\n }\n node.sibling.return = node.return;\n node = node.sibling;\n }\n }", "code_tokens": ["function", "(", "containerChildSet", ",", "workInProgress", ")", "{", "var", "node", "=", "workInProgress", ".", "child", ";", "while", "(", "node", "!==", "null", ")", "{", "if", "(", "node", ".", "tag", "===", "HostComponent", "||", "node", ".", "tag", "===", "HostText", ")", "{", "appendChildToContainerChildSet", "(", "containerChildSet", ",", "node", ".", "stateNode", ")", ";", "}", "else", "if", "(", "node", ".", "tag", "===", "HostPortal", ")", "{", "}", "else", "if", "(", "node", ".", "child", "!==", "null", ")", "{", "node", ".", "child", ".", "return", "=", "node", ";", "node", "=", "node", ".", "child", ";", "continue", ";", "}", "if", "(", "node", "===", "workInProgress", ")", "{", "return", ";", "}", "while", "(", "node", ".", "sibling", "===", "null", ")", "{", "if", "(", "node", ".", "return", "===", "null", "||", "node", ".", "return", "===", "workInProgress", ")", "{", "return", ";", "}", "node", "=", "node", ".", "return", ";", "}", "node", ".", "sibling", ".", "return", "=", "node", ".", "return", ";", "node", "=", "node", ".", "sibling", ";", "}", "}"], "docstring": "Persistent host tree mode An unfortunate fork of appendAllChildren because we have two different parent types.", "docstring_tokens": ["Persistent", "host", "tree", "mode", "An", "unfortunate", "fork", "of", "appendAllChildren", "because", "we", "have", "two", "different", "parent", "types", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L16593-L16621", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "safelyCallComponentWillUnmount", "original_string": "function safelyCallComponentWillUnmount(current$$1, instance) {\n {\n invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);\n if (hasCaughtError()) {\n var unmountError = clearCaughtError();\n captureCommitPhaseError(current$$1, unmountError);\n }\n }\n}", "language": "javascript", "code": "function safelyCallComponentWillUnmount(current$$1, instance) {\n {\n invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);\n if (hasCaughtError()) {\n var unmountError = clearCaughtError();\n captureCommitPhaseError(current$$1, unmountError);\n }\n }\n}", "code_tokens": ["function", "safelyCallComponentWillUnmount", "(", "current$$1", ",", "instance", ")", "{", "{", "invokeGuardedCallback", "(", "null", ",", "callComponentWillUnmountWithTimer", ",", "null", ",", "current$$1", ",", "instance", ")", ";", "if", "(", "hasCaughtError", "(", ")", ")", "{", "var", "unmountError", "=", "clearCaughtError", "(", ")", ";", "captureCommitPhaseError", "(", "current$$1", ",", "unmountError", ")", ";", "}", "}", "}"], "docstring": "Capture errors so they don't interrupt unmounting.", "docstring_tokens": ["Capture", "errors", "so", "they", "don", "t", "interrupt", "unmounting", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L16975-L16983", "partition": "test"} {"repo": "alvarotrigo/react-fullpage", "path": "example/dist/bundle.js", "func_name": "computeUniqueAsyncExpiration", "original_string": "function computeUniqueAsyncExpiration() {\n var currentTime = requestCurrentTime();\n var result = computeAsyncExpiration(currentTime);\n if (result <= lastUniqueAsyncExpiration) {\n // Since we assume the current time monotonically increases, we only hit\n // this branch when computeUniqueAsyncExpiration is fired multiple times\n // within a 200ms window (or whatever the async bucket size is).\n result = lastUniqueAsyncExpiration + 1;\n }\n lastUniqueAsyncExpiration = result;\n return lastUniqueAsyncExpiration;\n}", "language": "javascript", "code": "function computeUniqueAsyncExpiration() {\n var currentTime = requestCurrentTime();\n var result = computeAsyncExpiration(currentTime);\n if (result <= lastUniqueAsyncExpiration) {\n // Since we assume the current time monotonically increases, we only hit\n // this branch when computeUniqueAsyncExpiration is fired multiple times\n // within a 200ms window (or whatever the async bucket size is).\n result = lastUniqueAsyncExpiration + 1;\n }\n lastUniqueAsyncExpiration = result;\n return lastUniqueAsyncExpiration;\n}", "code_tokens": ["function", "computeUniqueAsyncExpiration", "(", ")", "{", "var", "currentTime", "=", "requestCurrentTime", "(", ")", ";", "var", "result", "=", "computeAsyncExpiration", "(", "currentTime", ")", ";", "if", "(", "result", "<=", "lastUniqueAsyncExpiration", ")", "{", "result", "=", "lastUniqueAsyncExpiration", "+", "1", ";", "}", "lastUniqueAsyncExpiration", "=", "result", ";", "return", "lastUniqueAsyncExpiration", ";", "}"], "docstring": "Creates a unique async expiration time.", "docstring_tokens": ["Creates", "a", "unique", "async", "expiration", "time", "."], "sha": "5a11fb5211e5706da81f2874516f023dc6e5aa88", "url": "https://github.com/alvarotrigo/react-fullpage/blob/5a11fb5211e5706da81f2874516f023dc6e5aa88/example/dist/bundle.js#L19109-L19120", "partition": "test"} {"repo": "kisenka/svg-sprite-loader", "path": "lib/utils/stringify.js", "func_name": "stringify", "original_string": "function stringify(content) {\n if (typeof content === 'string' && stringifiedRegexp.test(content)) {\n return content;\n }\n return JSON.stringify(content, null, 2);\n}", "language": "javascript", "code": "function stringify(content) {\n if (typeof content === 'string' && stringifiedRegexp.test(content)) {\n return content;\n }\n return JSON.stringify(content, null, 2);\n}", "code_tokens": ["function", "stringify", "(", "content", ")", "{", "if", "(", "typeof", "content", "===", "'string'", "&&", "stringifiedRegexp", ".", "test", "(", "content", ")", ")", "{", "return", "content", ";", "}", "return", "JSON", ".", "stringify", "(", "content", ",", "null", ",", "2", ")", ";", "}"], "docstring": "If already stringified - return original content\n@param {Object|Array} content\n@return {string}", "docstring_tokens": ["If", "already", "stringified", "-", "return", "original", "content"], "sha": "85f07caed508403ab259b5b13eabc97704e0261b", "url": "https://github.com/kisenka/svg-sprite-loader/blob/85f07caed508403ab259b5b13eabc97704e0261b/lib/utils/stringify.js#L8-L13", "partition": "test"} {"repo": "kisenka/svg-sprite-loader", "path": "lib/utils/get-loader-options.js", "func_name": "getLoaderOptions", "original_string": "function getLoaderOptions(loaderPath, rule) {\n let multiRuleProp;\n\n if (isWebpack1) {\n multiRuleProp = 'loaders';\n } else if (rule.oneOf) {\n multiRuleProp = 'oneOf';\n } else {\n multiRuleProp = 'use';\n }\n\n const multiRule = typeof rule === 'object' && Array.isArray(rule[multiRuleProp]) ? rule[multiRuleProp] : null;\n let options;\n\n if (multiRule) {\n const rules = [].concat(...multiRule.map(r => (r.use || r)));\n options = rules.map(normalizeRule).find(r => loaderPath.includes(r.loader)).options;\n } else {\n options = normalizeRule(rule).options;\n }\n\n return options;\n}", "language": "javascript", "code": "function getLoaderOptions(loaderPath, rule) {\n let multiRuleProp;\n\n if (isWebpack1) {\n multiRuleProp = 'loaders';\n } else if (rule.oneOf) {\n multiRuleProp = 'oneOf';\n } else {\n multiRuleProp = 'use';\n }\n\n const multiRule = typeof rule === 'object' && Array.isArray(rule[multiRuleProp]) ? rule[multiRuleProp] : null;\n let options;\n\n if (multiRule) {\n const rules = [].concat(...multiRule.map(r => (r.use || r)));\n options = rules.map(normalizeRule).find(r => loaderPath.includes(r.loader)).options;\n } else {\n options = normalizeRule(rule).options;\n }\n\n return options;\n}", "code_tokens": ["function", "getLoaderOptions", "(", "loaderPath", ",", "rule", ")", "{", "let", "multiRuleProp", ";", "if", "(", "isWebpack1", ")", "{", "multiRuleProp", "=", "'loaders'", ";", "}", "else", "if", "(", "rule", ".", "oneOf", ")", "{", "multiRuleProp", "=", "'oneOf'", ";", "}", "else", "{", "multiRuleProp", "=", "'use'", ";", "}", "const", "multiRule", "=", "typeof", "rule", "===", "'object'", "&&", "Array", ".", "isArray", "(", "rule", "[", "multiRuleProp", "]", ")", "?", "rule", "[", "multiRuleProp", "]", ":", "null", ";", "let", "options", ";", "if", "(", "multiRule", ")", "{", "const", "rules", "=", "[", "]", ".", "concat", "(", "...", "multiRule", ".", "map", "(", "r", "=>", "(", "r", ".", "use", "||", "r", ")", ")", ")", ";", "options", "=", "rules", ".", "map", "(", "normalizeRule", ")", ".", "find", "(", "r", "=>", "loaderPath", ".", "includes", "(", "r", ".", "loader", ")", ")", ".", "options", ";", "}", "else", "{", "options", "=", "normalizeRule", "(", "rule", ")", ".", "options", ";", "}", "return", "options", ";", "}"], "docstring": "webpack 1 compat loader options finder. Returns normalized options.\n@param {string} loaderPath\n@param {Object|Rule} rule\n@return {Object|null}", "docstring_tokens": ["webpack", "1", "compat", "loader", "options", "finder", ".", "Returns", "normalized", "options", "."], "sha": "85f07caed508403ab259b5b13eabc97704e0261b", "url": "https://github.com/kisenka/svg-sprite-loader/blob/85f07caed508403ab259b5b13eabc97704e0261b/lib/utils/get-loader-options.js#L10-L32", "partition": "test"} {"repo": "kisenka/svg-sprite-loader", "path": "lib/utils/normalize-rule.js", "func_name": "normalizeRule", "original_string": "function normalizeRule(rule) {\n if (!rule) {\n throw new Error('Rule should be string or object');\n }\n\n let data;\n\n if (typeof rule === 'string') {\n const parts = rule.split('?');\n data = {\n loader: parts[0],\n options: parts[1] ? parseQuery(`?${parts[1]}`) : null\n };\n } else {\n const options = isWebpack1 ? rule.query : rule.options;\n data = {\n loader: rule.loader,\n options: options || null\n };\n }\n\n return data;\n}", "language": "javascript", "code": "function normalizeRule(rule) {\n if (!rule) {\n throw new Error('Rule should be string or object');\n }\n\n let data;\n\n if (typeof rule === 'string') {\n const parts = rule.split('?');\n data = {\n loader: parts[0],\n options: parts[1] ? parseQuery(`?${parts[1]}`) : null\n };\n } else {\n const options = isWebpack1 ? rule.query : rule.options;\n data = {\n loader: rule.loader,\n options: options || null\n };\n }\n\n return data;\n}", "code_tokens": ["function", "normalizeRule", "(", "rule", ")", "{", "if", "(", "!", "rule", ")", "{", "throw", "new", "Error", "(", "'Rule should be string or object'", ")", ";", "}", "let", "data", ";", "if", "(", "typeof", "rule", "===", "'string'", ")", "{", "const", "parts", "=", "rule", ".", "split", "(", "'?'", ")", ";", "data", "=", "{", "loader", ":", "parts", "[", "0", "]", ",", "options", ":", "parts", "[", "1", "]", "?", "parseQuery", "(", "`", "${", "parts", "[", "1", "]", "}", "`", ")", ":", "null", "}", ";", "}", "else", "{", "const", "options", "=", "isWebpack1", "?", "rule", ".", "query", ":", "rule", ".", "options", ";", "data", "=", "{", "loader", ":", "rule", ".", "loader", ",", "options", ":", "options", "||", "null", "}", ";", "}", "return", "data", ";", "}"], "docstring": "webpack 1 compat rule normalizer\n@param {string|Rule} rule (string - webpack 1, Object - webpack 2)\n@return {Object}", "docstring_tokens": ["webpack", "1", "compat", "rule", "normalizer"], "sha": "85f07caed508403ab259b5b13eabc97704e0261b", "url": "https://github.com/kisenka/svg-sprite-loader/blob/85f07caed508403ab259b5b13eabc97704e0261b/lib/utils/normalize-rule.js#L9-L31", "partition": "test"} {"repo": "phphe/vue-draggable-nested-tree", "path": "src/components/autoMoveDragPlaceHolder.js", "func_name": "findParent", "original_string": "function findParent(node, handle) {\n let current = node\n while (current) {\n if (handle(current)) {\n return current\n }\n current = current.parent\n }\n}", "language": "javascript", "code": "function findParent(node, handle) {\n let current = node\n while (current) {\n if (handle(current)) {\n return current\n }\n current = current.parent\n }\n}", "code_tokens": ["function", "findParent", "(", "node", ",", "handle", ")", "{", "let", "current", "=", "node", "while", "(", "current", ")", "{", "if", "(", "handle", "(", "current", ")", ")", "{", "return", "current", "}", "current", "=", "current", ".", "parent", "}", "}"], "docstring": "start from node self", "docstring_tokens": ["start", "from", "node", "self"], "sha": "094b12954d55d449cdebbcbc00c6456fed3c99ce", "url": "https://github.com/phphe/vue-draggable-nested-tree/blob/094b12954d55d449cdebbcbc00c6456fed3c99ce/src/components/autoMoveDragPlaceHolder.js#L129-L137", "partition": "test"} {"repo": "phphe/vue-draggable-nested-tree", "path": "dist/vue-draggable-nested-tree.es.js", "func_name": "pure", "original_string": "function pure(node, withChildren, after) {\n var _this2 = this;\n\n var t = assign$1({}, node);\n\n delete t._id;\n delete t.parent;\n delete t.children;\n delete t.open;\n delete t.active;\n delete t.style;\n delete t.class;\n delete t.innerStyle;\n delete t.innerClass;\n delete t.innerBackStyle;\n delete t.innerBackClass;\n\n var _arr = keys$1(t);\n\n for (var _i = 0; _i < _arr.length; _i++) {\n var key = _arr[_i];\n\n if (key[0] === '_') {\n delete t[key];\n }\n }\n\n if (withChildren && node.children) {\n t.children = node.children.slice();\n t.children.forEach(function (v, k) {\n t.children[k] = _this2.pure(v, withChildren);\n });\n }\n\n if (after) {\n return after(t, node) || t;\n }\n\n return t;\n }", "language": "javascript", "code": "function pure(node, withChildren, after) {\n var _this2 = this;\n\n var t = assign$1({}, node);\n\n delete t._id;\n delete t.parent;\n delete t.children;\n delete t.open;\n delete t.active;\n delete t.style;\n delete t.class;\n delete t.innerStyle;\n delete t.innerClass;\n delete t.innerBackStyle;\n delete t.innerBackClass;\n\n var _arr = keys$1(t);\n\n for (var _i = 0; _i < _arr.length; _i++) {\n var key = _arr[_i];\n\n if (key[0] === '_') {\n delete t[key];\n }\n }\n\n if (withChildren && node.children) {\n t.children = node.children.slice();\n t.children.forEach(function (v, k) {\n t.children[k] = _this2.pure(v, withChildren);\n });\n }\n\n if (after) {\n return after(t, node) || t;\n }\n\n return t;\n }", "code_tokens": ["function", "pure", "(", "node", ",", "withChildren", ",", "after", ")", "{", "var", "_this2", "=", "this", ";", "var", "t", "=", "assign$1", "(", "{", "}", ",", "node", ")", ";", "delete", "t", ".", "_id", ";", "delete", "t", ".", "parent", ";", "delete", "t", ".", "children", ";", "delete", "t", ".", "open", ";", "delete", "t", ".", "active", ";", "delete", "t", ".", "style", ";", "delete", "t", ".", "class", ";", "delete", "t", ".", "innerStyle", ";", "delete", "t", ".", "innerClass", ";", "delete", "t", ".", "innerBackStyle", ";", "delete", "t", ".", "innerBackClass", ";", "var", "_arr", "=", "keys$1", "(", "t", ")", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "_arr", ".", "length", ";", "_i", "++", ")", "{", "var", "key", "=", "_arr", "[", "_i", "]", ";", "if", "(", "key", "[", "0", "]", "===", "'_'", ")", "{", "delete", "t", "[", "key", "]", ";", "}", "}", "if", "(", "withChildren", "&&", "node", ".", "children", ")", "{", "t", ".", "children", "=", "node", ".", "children", ".", "slice", "(", ")", ";", "t", ".", "children", ".", "forEach", "(", "function", "(", "v", ",", "k", ")", "{", "t", ".", "children", "[", "k", "]", "=", "_this2", ".", "pure", "(", "v", ",", "withChildren", ")", ";", "}", ")", ";", "}", "if", "(", "after", ")", "{", "return", "after", "(", "t", ",", "node", ")", "||", "t", ";", "}", "return", "t", ";", "}"], "docstring": "pure node self", "docstring_tokens": ["pure", "node", "self"], "sha": "094b12954d55d449cdebbcbc00c6456fed3c99ce", "url": "https://github.com/phphe/vue-draggable-nested-tree/blob/094b12954d55d449cdebbcbc00c6456fed3c99ce/dist/vue-draggable-nested-tree.es.js#L225-L264", "partition": "test"} {"repo": "phphe/vue-draggable-nested-tree", "path": "dist/vue-draggable-nested-tree.es.js", "func_name": "offset2", "original_string": "function offset2() {\n return {\n x: this.offset.x + this.nodeInnerEl.offsetWidth,\n y: this.offset.y + this.nodeInnerEl.offsetHeight\n };\n }", "language": "javascript", "code": "function offset2() {\n return {\n x: this.offset.x + this.nodeInnerEl.offsetWidth,\n y: this.offset.y + this.nodeInnerEl.offsetHeight\n };\n }", "code_tokens": ["function", "offset2", "(", ")", "{", "return", "{", "x", ":", "this", ".", "offset", ".", "x", "+", "this", ".", "nodeInnerEl", ".", "offsetWidth", ",", "y", ":", "this", ".", "offset", ".", "y", "+", "this", ".", "nodeInnerEl", ".", "offsetHeight", "}", ";", "}"], "docstring": "left top point", "docstring_tokens": ["left", "top", "point"], "sha": "094b12954d55d449cdebbcbc00c6456fed3c99ce", "url": "https://github.com/phphe/vue-draggable-nested-tree/blob/094b12954d55d449cdebbcbc00c6456fed3c99ce/dist/vue-draggable-nested-tree.es.js#L874-L879", "partition": "test"} {"repo": "phphe/vue-draggable-nested-tree", "path": "dist/vue-draggable-nested-tree.es.js", "func_name": "offsetToViewPort", "original_string": "function offsetToViewPort() {\n var r = this.nodeInnerEl.getBoundingClientRect();\n r.x = r.left;\n r.y = r.top;\n return r;\n }", "language": "javascript", "code": "function offsetToViewPort() {\n var r = this.nodeInnerEl.getBoundingClientRect();\n r.x = r.left;\n r.y = r.top;\n return r;\n }", "code_tokens": ["function", "offsetToViewPort", "(", ")", "{", "var", "r", "=", "this", ".", "nodeInnerEl", ".", "getBoundingClientRect", "(", ")", ";", "r", ".", "x", "=", "r", ".", "left", ";", "r", ".", "y", "=", "r", ".", "top", ";", "return", "r", ";", "}"], "docstring": "right bottom point", "docstring_tokens": ["right", "bottom", "point"], "sha": "094b12954d55d449cdebbcbc00c6456fed3c99ce", "url": "https://github.com/phphe/vue-draggable-nested-tree/blob/094b12954d55d449cdebbcbc00c6456fed3c99ce/dist/vue-draggable-nested-tree.es.js#L881-L886", "partition": "test"} {"repo": "phphe/vue-draggable-nested-tree", "path": "dist/vue-draggable-nested-tree.es.js", "func_name": "currentTreeRootSecondChildExcludingDragging", "original_string": "function currentTreeRootSecondChildExcludingDragging() {\n var _this = this;\n\n return this.currentTree.rootData.children.slice(0, 3).filter(function (v) {\n return v !== _this.node;\n })[1];\n }", "language": "javascript", "code": "function currentTreeRootSecondChildExcludingDragging() {\n var _this = this;\n\n return this.currentTree.rootData.children.slice(0, 3).filter(function (v) {\n return v !== _this.node;\n })[1];\n }", "code_tokens": ["function", "currentTreeRootSecondChildExcludingDragging", "(", ")", "{", "var", "_this", "=", "this", ";", "return", "this", ".", "currentTree", ".", "rootData", ".", "children", ".", "slice", "(", "0", ",", "3", ")", ".", "filter", "(", "function", "(", "v", ")", "{", "return", "v", "!==", "_this", ".", "node", ";", "}", ")", "[", "1", "]", ";", "}"], "docstring": "the second child of currentTree root, excluding dragging node", "docstring_tokens": ["the", "second", "child", "of", "currentTree", "root", "excluding", "dragging", "node"], "sha": "094b12954d55d449cdebbcbc00c6456fed3c99ce", "url": "https://github.com/phphe/vue-draggable-nested-tree/blob/094b12954d55d449cdebbcbc00c6456fed3c99ce/dist/vue-draggable-nested-tree.es.js#L921-L927", "partition": "test"} {"repo": "phphe/vue-draggable-nested-tree", "path": "dist/vue-draggable-nested-tree.cjs.js", "func_name": "appendPrev", "original_string": "function appendPrev(info) {\n if (isNodeDroppable(info.targetPrev)) {\n th.appendTo(info.dplh, info.targetPrev);\n if (!info.targetPrev.open) info.store.toggleOpen(info.targetPrev);\n } else {\n insertDplhAfterTo(info.dplh, info.targetPrev, info);\n }\n }", "language": "javascript", "code": "function appendPrev(info) {\n if (isNodeDroppable(info.targetPrev)) {\n th.appendTo(info.dplh, info.targetPrev);\n if (!info.targetPrev.open) info.store.toggleOpen(info.targetPrev);\n } else {\n insertDplhAfterTo(info.dplh, info.targetPrev, info);\n }\n }", "code_tokens": ["function", "appendPrev", "(", "info", ")", "{", "if", "(", "isNodeDroppable", "(", "info", ".", "targetPrev", ")", ")", "{", "th", ".", "appendTo", "(", "info", ".", "dplh", ",", "info", ".", "targetPrev", ")", ";", "if", "(", "!", "info", ".", "targetPrev", ".", "open", ")", "info", ".", "store", ".", "toggleOpen", "(", "info", ".", "targetPrev", ")", ";", "}", "else", "{", "insertDplhAfterTo", "(", "info", ".", "dplh", ",", "info", ".", "targetPrev", ",", "info", ")", ";", "}", "}"], "docstring": "append to prev sibling", "docstring_tokens": ["append", "to", "prev", "sibling"], "sha": "094b12954d55d449cdebbcbc00c6456fed3c99ce", "url": "https://github.com/phphe/vue-draggable-nested-tree/blob/094b12954d55d449cdebbcbc00c6456fed3c99ce/dist/vue-draggable-nested-tree.cjs.js#L646-L653", "partition": "test"} {"repo": "phphe/vue-draggable-nested-tree", "path": "dist/vue-draggable-nested-tree.cjs.js", "func_name": "appendCurrentTree", "original_string": "function appendCurrentTree(info) {\n if (isNodeDroppable(info.currentTree.rootData)) {\n th.appendTo(info.dplh, info.currentTree.rootData);\n }\n }", "language": "javascript", "code": "function appendCurrentTree(info) {\n if (isNodeDroppable(info.currentTree.rootData)) {\n th.appendTo(info.dplh, info.currentTree.rootData);\n }\n }", "code_tokens": ["function", "appendCurrentTree", "(", "info", ")", "{", "if", "(", "isNodeDroppable", "(", "info", ".", "currentTree", ".", "rootData", ")", ")", "{", "th", ".", "appendTo", "(", "info", ".", "dplh", ",", "info", ".", "currentTree", ".", "rootData", ")", ";", "}", "}"], "docstring": "append to current tree", "docstring_tokens": ["append", "to", "current", "tree"], "sha": "094b12954d55d449cdebbcbc00c6456fed3c99ce", "url": "https://github.com/phphe/vue-draggable-nested-tree/blob/094b12954d55d449cdebbcbc00c6456fed3c99ce/dist/vue-draggable-nested-tree.cjs.js#L655-L659", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/commands/find.js", "func_name": "stripViewFromSelector", "original_string": "function stripViewFromSelector (selector) {\n // Don't strip it out if it's one of these 4 element types\n // (see https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Utilities/FBElementTypeTransformer.m for reference)\n const keepView = [\n 'XCUIElementTypeScrollView',\n 'XCUIElementTypeCollectionView',\n 'XCUIElementTypeTextView',\n 'XCUIElementTypeWebView',\n ].includes(selector);\n\n if (!keepView && selector.indexOf('View') === selector.length - 4) {\n return selector.substr(0, selector.length - 4);\n } else {\n return selector;\n }\n }", "language": "javascript", "code": "function stripViewFromSelector (selector) {\n // Don't strip it out if it's one of these 4 element types\n // (see https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Utilities/FBElementTypeTransformer.m for reference)\n const keepView = [\n 'XCUIElementTypeScrollView',\n 'XCUIElementTypeCollectionView',\n 'XCUIElementTypeTextView',\n 'XCUIElementTypeWebView',\n ].includes(selector);\n\n if (!keepView && selector.indexOf('View') === selector.length - 4) {\n return selector.substr(0, selector.length - 4);\n } else {\n return selector;\n }\n }", "code_tokens": ["function", "stripViewFromSelector", "(", "selector", ")", "{", "const", "keepView", "=", "[", "'XCUIElementTypeScrollView'", ",", "'XCUIElementTypeCollectionView'", ",", "'XCUIElementTypeTextView'", ",", "'XCUIElementTypeWebView'", ",", "]", ".", "includes", "(", "selector", ")", ";", "if", "(", "!", "keepView", "&&", "selector", ".", "indexOf", "(", "'View'", ")", "===", "selector", ".", "length", "-", "4", ")", "{", "return", "selector", ".", "substr", "(", "0", ",", "selector", ".", "length", "-", "4", ")", ";", "}", "else", "{", "return", "selector", ";", "}", "}"], "docstring": "Check if the word 'View' is appended to selector and if it is, strip it out", "docstring_tokens": ["Check", "if", "the", "word", "View", "is", "appended", "to", "selector", "and", "if", "it", "is", "strip", "it", "out"], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/commands/find.js#L38-L53", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/utils.js", "func_name": "getPidUsingPattern", "original_string": "async function getPidUsingPattern (pgrepPattern) {\n const args = ['-nif', pgrepPattern];\n try {\n const {stdout} = await exec('pgrep', args);\n const pid = parseInt(stdout, 10);\n if (isNaN(pid)) {\n log.debug(`Cannot parse process id from 'pgrep ${args.join(' ')}' output: ${stdout}`);\n return null;\n }\n return `${pid}`;\n } catch (err) {\n log.debug(`'pgrep ${args.join(' ')}' didn't detect any matching processes. Return code: ${err.code}`);\n return null;\n }\n}", "language": "javascript", "code": "async function getPidUsingPattern (pgrepPattern) {\n const args = ['-nif', pgrepPattern];\n try {\n const {stdout} = await exec('pgrep', args);\n const pid = parseInt(stdout, 10);\n if (isNaN(pid)) {\n log.debug(`Cannot parse process id from 'pgrep ${args.join(' ')}' output: ${stdout}`);\n return null;\n }\n return `${pid}`;\n } catch (err) {\n log.debug(`'pgrep ${args.join(' ')}' didn't detect any matching processes. Return code: ${err.code}`);\n return null;\n }\n}", "code_tokens": ["async", "function", "getPidUsingPattern", "(", "pgrepPattern", ")", "{", "const", "args", "=", "[", "'-nif'", ",", "pgrepPattern", "]", ";", "try", "{", "const", "{", "stdout", "}", "=", "await", "exec", "(", "'pgrep'", ",", "args", ")", ";", "const", "pid", "=", "parseInt", "(", "stdout", ",", "10", ")", ";", "if", "(", "isNaN", "(", "pid", ")", ")", "{", "log", ".", "debug", "(", "`", "${", "args", ".", "join", "(", "' '", ")", "}", "${", "stdout", "}", "`", ")", ";", "return", "null", ";", "}", "return", "`", "${", "pid", "}", "`", ";", "}", "catch", "(", "err", ")", "{", "log", ".", "debug", "(", "`", "${", "args", ".", "join", "(", "' '", ")", "}", "${", "err", ".", "code", "}", "`", ")", ";", "return", "null", ";", "}", "}"], "docstring": "Get the process id of the most recent running application\nhaving the particular command line pattern.\n\n@param {string} pgrepPattern - pgrep-compatible search pattern.\n@return {string} Either a process id or null if no matches were found.", "docstring_tokens": ["Get", "the", "process", "id", "of", "the", "most", "recent", "running", "application", "having", "the", "particular", "command", "line", "pattern", "."], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/utils.js#L210-L224", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/utils.js", "func_name": "killAppUsingPattern", "original_string": "async function killAppUsingPattern (pgrepPattern) {\n for (const signal of [2, 15, 9]) {\n if (!await getPidUsingPattern(pgrepPattern)) {\n return;\n }\n const args = [`-${signal}`, '-if', pgrepPattern];\n try {\n await exec('pkill', args);\n } catch (err) {\n log.debug(`pkill ${args.join(' ')} -> ${err.message}`);\n }\n await B.delay(100);\n }\n}", "language": "javascript", "code": "async function killAppUsingPattern (pgrepPattern) {\n for (const signal of [2, 15, 9]) {\n if (!await getPidUsingPattern(pgrepPattern)) {\n return;\n }\n const args = [`-${signal}`, '-if', pgrepPattern];\n try {\n await exec('pkill', args);\n } catch (err) {\n log.debug(`pkill ${args.join(' ')} -> ${err.message}`);\n }\n await B.delay(100);\n }\n}", "code_tokens": ["async", "function", "killAppUsingPattern", "(", "pgrepPattern", ")", "{", "for", "(", "const", "signal", "of", "[", "2", ",", "15", ",", "9", "]", ")", "{", "if", "(", "!", "await", "getPidUsingPattern", "(", "pgrepPattern", ")", ")", "{", "return", ";", "}", "const", "args", "=", "[", "`", "${", "signal", "}", "`", ",", "'-if'", ",", "pgrepPattern", "]", ";", "try", "{", "await", "exec", "(", "'pkill'", ",", "args", ")", ";", "}", "catch", "(", "err", ")", "{", "log", ".", "debug", "(", "`", "${", "args", ".", "join", "(", "' '", ")", "}", "${", "err", ".", "message", "}", "`", ")", ";", "}", "await", "B", ".", "delay", "(", "100", ")", ";", "}", "}"], "docstring": "Kill a process having the particular command line pattern.\nThis method tries to send SIGINT, SIGTERM and SIGKILL to the\nmatched processes in this order if the process is still running.\n\n@param {string} pgrepPattern - pgrep-compatible search pattern.", "docstring_tokens": ["Kill", "a", "process", "having", "the", "particular", "command", "line", "pattern", ".", "This", "method", "tries", "to", "send", "SIGINT", "SIGTERM", "and", "SIGKILL", "to", "the", "matched", "processes", "in", "this", "order", "if", "the", "process", "is", "still", "running", "."], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/utils.js#L233-L246", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/utils.js", "func_name": "getPIDsListeningOnPort", "original_string": "async function getPIDsListeningOnPort (port, filteringFunc = null) {\n const result = [];\n try {\n // This only works since Mac OS X El Capitan\n const {stdout} = await exec('lsof', ['-ti', `tcp:${port}`]);\n result.push(...(stdout.trim().split(/\\n+/)));\n } catch (e) {\n return result;\n }\n\n if (!_.isFunction(filteringFunc)) {\n return result;\n }\n return await B.filter(result, async (x) => {\n const {stdout} = await exec('ps', ['-p', x, '-o', 'command']);\n return await filteringFunc(stdout);\n });\n}", "language": "javascript", "code": "async function getPIDsListeningOnPort (port, filteringFunc = null) {\n const result = [];\n try {\n // This only works since Mac OS X El Capitan\n const {stdout} = await exec('lsof', ['-ti', `tcp:${port}`]);\n result.push(...(stdout.trim().split(/\\n+/)));\n } catch (e) {\n return result;\n }\n\n if (!_.isFunction(filteringFunc)) {\n return result;\n }\n return await B.filter(result, async (x) => {\n const {stdout} = await exec('ps', ['-p', x, '-o', 'command']);\n return await filteringFunc(stdout);\n });\n}", "code_tokens": ["async", "function", "getPIDsListeningOnPort", "(", "port", ",", "filteringFunc", "=", "null", ")", "{", "const", "result", "=", "[", "]", ";", "try", "{", "const", "{", "stdout", "}", "=", "await", "exec", "(", "'lsof'", ",", "[", "'-ti'", ",", "`", "${", "port", "}", "`", "]", ")", ";", "result", ".", "push", "(", "...", "(", "stdout", ".", "trim", "(", ")", ".", "split", "(", "/", "\\n+", "/", ")", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "result", ";", "}", "if", "(", "!", "_", ".", "isFunction", "(", "filteringFunc", ")", ")", "{", "return", "result", ";", "}", "return", "await", "B", ".", "filter", "(", "result", ",", "async", "(", "x", ")", "=>", "{", "const", "{", "stdout", "}", "=", "await", "exec", "(", "'ps'", ",", "[", "'-p'", ",", "x", ",", "'-o'", ",", "'command'", "]", ")", ";", "return", "await", "filteringFunc", "(", "stdout", ")", ";", "}", ")", ";", "}"], "docstring": "Get the IDs of processes listening on the particular system port.\nIt is also possible to apply additional filtering based on the\nprocess command line.\n\n@param {string|number} port - The port number.\n@param {?Function} filteringFunc - Optional lambda function, which\nreceives command line string of the particular process\nlistening on given port, and is expected to return\neither true or false to include/exclude the corresponding PID\nfrom the resulting array.\n@returns {Array} - the list of matched process ids.", "docstring_tokens": ["Get", "the", "IDs", "of", "processes", "listening", "on", "the", "particular", "system", "port", ".", "It", "is", "also", "possible", "to", "apply", "additional", "filtering", "based", "on", "the", "process", "command", "line", "."], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/utils.js#L306-L323", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/utils.js", "func_name": "removeAllSessionWebSocketHandlers", "original_string": "async function removeAllSessionWebSocketHandlers (server, sessionId) {\n if (!server || !_.isFunction(server.getWebSocketHandlers)) {\n return;\n }\n\n const activeHandlers = await server.getWebSocketHandlers(sessionId);\n for (const pathname of _.keys(activeHandlers)) {\n await server.removeWebSocketHandler(pathname);\n }\n}", "language": "javascript", "code": "async function removeAllSessionWebSocketHandlers (server, sessionId) {\n if (!server || !_.isFunction(server.getWebSocketHandlers)) {\n return;\n }\n\n const activeHandlers = await server.getWebSocketHandlers(sessionId);\n for (const pathname of _.keys(activeHandlers)) {\n await server.removeWebSocketHandler(pathname);\n }\n}", "code_tokens": ["async", "function", "removeAllSessionWebSocketHandlers", "(", "server", ",", "sessionId", ")", "{", "if", "(", "!", "server", "||", "!", "_", ".", "isFunction", "(", "server", ".", "getWebSocketHandlers", ")", ")", "{", "return", ";", "}", "const", "activeHandlers", "=", "await", "server", ".", "getWebSocketHandlers", "(", "sessionId", ")", ";", "for", "(", "const", "pathname", "of", "_", ".", "keys", "(", "activeHandlers", ")", ")", "{", "await", "server", ".", "removeWebSocketHandler", "(", "pathname", ")", ";", "}", "}"], "docstring": "Stops and removes all web socket handlers that are listening\nin scope of the currect session.\n\n@param {Object} server - The instance of NodeJs HTTP server,\nwhich hosts Appium\n@param {string} sessionId - The id of the current session", "docstring_tokens": ["Stops", "and", "removes", "all", "web", "socket", "handlers", "that", "are", "listening", "in", "scope", "of", "the", "currect", "session", "."], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/utils.js#L400-L409", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/utils.js", "func_name": "verifyApplicationPlatform", "original_string": "async function verifyApplicationPlatform (app, isSimulator) {\n log.debug('Verifying application platform');\n\n const infoPlist = path.resolve(app, 'Info.plist');\n if (!await fs.exists(infoPlist)) {\n log.debug(`'${infoPlist}' does not exist`);\n return null;\n }\n\n const {CFBundleSupportedPlatforms} = await plist.parsePlistFile(infoPlist);\n log.debug(`CFBundleSupportedPlatforms: ${JSON.stringify(CFBundleSupportedPlatforms)}`);\n if (!_.isArray(CFBundleSupportedPlatforms)) {\n log.debug(`CFBundleSupportedPlatforms key does not exist in '${infoPlist}'`);\n return null;\n }\n\n const isAppSupported = (isSimulator && CFBundleSupportedPlatforms.includes('iPhoneSimulator'))\n || (!isSimulator && CFBundleSupportedPlatforms.includes('iPhoneOS'));\n if (isAppSupported) {\n return true;\n }\n throw new Error(`${isSimulator ? 'Simulator' : 'Real device'} architecture is unsupported by the '${app}' application. ` +\n `Make sure the correct deployment target has been selected for its compilation in Xcode.`);\n}", "language": "javascript", "code": "async function verifyApplicationPlatform (app, isSimulator) {\n log.debug('Verifying application platform');\n\n const infoPlist = path.resolve(app, 'Info.plist');\n if (!await fs.exists(infoPlist)) {\n log.debug(`'${infoPlist}' does not exist`);\n return null;\n }\n\n const {CFBundleSupportedPlatforms} = await plist.parsePlistFile(infoPlist);\n log.debug(`CFBundleSupportedPlatforms: ${JSON.stringify(CFBundleSupportedPlatforms)}`);\n if (!_.isArray(CFBundleSupportedPlatforms)) {\n log.debug(`CFBundleSupportedPlatforms key does not exist in '${infoPlist}'`);\n return null;\n }\n\n const isAppSupported = (isSimulator && CFBundleSupportedPlatforms.includes('iPhoneSimulator'))\n || (!isSimulator && CFBundleSupportedPlatforms.includes('iPhoneOS'));\n if (isAppSupported) {\n return true;\n }\n throw new Error(`${isSimulator ? 'Simulator' : 'Real device'} architecture is unsupported by the '${app}' application. ` +\n `Make sure the correct deployment target has been selected for its compilation in Xcode.`);\n}", "code_tokens": ["async", "function", "verifyApplicationPlatform", "(", "app", ",", "isSimulator", ")", "{", "log", ".", "debug", "(", "'Verifying application platform'", ")", ";", "const", "infoPlist", "=", "path", ".", "resolve", "(", "app", ",", "'Info.plist'", ")", ";", "if", "(", "!", "await", "fs", ".", "exists", "(", "infoPlist", ")", ")", "{", "log", ".", "debug", "(", "`", "${", "infoPlist", "}", "`", ")", ";", "return", "null", ";", "}", "const", "{", "CFBundleSupportedPlatforms", "}", "=", "await", "plist", ".", "parsePlistFile", "(", "infoPlist", ")", ";", "log", ".", "debug", "(", "`", "${", "JSON", ".", "stringify", "(", "CFBundleSupportedPlatforms", ")", "}", "`", ")", ";", "if", "(", "!", "_", ".", "isArray", "(", "CFBundleSupportedPlatforms", ")", ")", "{", "log", ".", "debug", "(", "`", "${", "infoPlist", "}", "`", ")", ";", "return", "null", ";", "}", "const", "isAppSupported", "=", "(", "isSimulator", "&&", "CFBundleSupportedPlatforms", ".", "includes", "(", "'iPhoneSimulator'", ")", ")", "||", "(", "!", "isSimulator", "&&", "CFBundleSupportedPlatforms", ".", "includes", "(", "'iPhoneOS'", ")", ")", ";", "if", "(", "isAppSupported", ")", "{", "return", "true", ";", "}", "throw", "new", "Error", "(", "`", "${", "isSimulator", "?", "'Simulator'", ":", "'Real device'", "}", "${", "app", "}", "`", "+", "`", "`", ")", ";", "}"], "docstring": "Verify whether the given application is compatible to the\nplatform where it is going to be installed and tested.\n\n@param {string} app - The actual path to the application bundle\n@param {boolean} isSimulator - Should be set to `true` if the test will be executed on Simulator\n@returns {?boolean} The function returns `null` if the application does not exist or there is no\n`CFBundleSupportedPlatforms` key in its Info.plist manifest.\n`true` is returned if the bundle architecture matches the device architecture.\n@throws {Error} If bundle architecture does not match the device architecture.", "docstring_tokens": ["Verify", "whether", "the", "given", "application", "is", "compatible", "to", "the", "platform", "where", "it", "is", "going", "to", "be", "installed", "and", "tested", "."], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/utils.js#L422-L445", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/utils.js", "func_name": "isLocalHost", "original_string": "function isLocalHost (urlString) {\n try {\n const {hostname} = url.parse(urlString);\n return ['localhost', '127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(hostname);\n } catch {\n log.warn(`'${urlString}' cannot be parsed as a valid URL`);\n }\n return false;\n}", "language": "javascript", "code": "function isLocalHost (urlString) {\n try {\n const {hostname} = url.parse(urlString);\n return ['localhost', '127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(hostname);\n } catch {\n log.warn(`'${urlString}' cannot be parsed as a valid URL`);\n }\n return false;\n}", "code_tokens": ["function", "isLocalHost", "(", "urlString", ")", "{", "try", "{", "const", "{", "hostname", "}", "=", "url", ".", "parse", "(", "urlString", ")", ";", "return", "[", "'localhost'", ",", "'127.0.0.1'", ",", "'::1'", ",", "'::ffff:127.0.0.1'", "]", ".", "includes", "(", "hostname", ")", ";", "}", "catch", "{", "log", ".", "warn", "(", "`", "${", "urlString", "}", "`", ")", ";", "}", "return", "false", ";", "}"], "docstring": "Returns true if the urlString is localhost\n@param {?string} urlString\n@returns {boolean} Return true if the urlString is localhost", "docstring_tokens": ["Returns", "true", "if", "the", "urlString", "is", "localhost"], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/utils.js#L461-L469", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/utils.js", "func_name": "normalizePlatformVersion", "original_string": "function normalizePlatformVersion (originalVersion) {\n const normalizedVersion = util.coerceVersion(originalVersion, false);\n if (!normalizedVersion) {\n throw new Error(`The platform version '${originalVersion}' should be a valid version number`);\n }\n const {major, minor} = new semver.SemVer(normalizedVersion);\n return `${major}.${minor}`;\n}", "language": "javascript", "code": "function normalizePlatformVersion (originalVersion) {\n const normalizedVersion = util.coerceVersion(originalVersion, false);\n if (!normalizedVersion) {\n throw new Error(`The platform version '${originalVersion}' should be a valid version number`);\n }\n const {major, minor} = new semver.SemVer(normalizedVersion);\n return `${major}.${minor}`;\n}", "code_tokens": ["function", "normalizePlatformVersion", "(", "originalVersion", ")", "{", "const", "normalizedVersion", "=", "util", ".", "coerceVersion", "(", "originalVersion", ",", "false", ")", ";", "if", "(", "!", "normalizedVersion", ")", "{", "throw", "new", "Error", "(", "`", "${", "originalVersion", "}", "`", ")", ";", "}", "const", "{", "major", ",", "minor", "}", "=", "new", "semver", ".", "SemVer", "(", "normalizedVersion", ")", ";", "return", "`", "${", "major", "}", "${", "minor", "}", "`", ";", "}"], "docstring": "Normalizes platformVersion to a valid iOS version string\n\n@param {string} originalVersion - Loose version number, that can be parsed by semver\n@return {string} iOS version number in . format\n@throws {Error} if the version number cannot be parsed", "docstring_tokens": ["Normalizes", "platformVersion", "to", "a", "valid", "iOS", "version", "string"], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/utils.js#L478-L485", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/wda/utils.js", "func_name": "updateProjectFile", "original_string": "async function updateProjectFile (agentPath, newBundleId) {\n let projectFilePath = `${agentPath}/${PROJECT_FILE}`;\n try {\n // Assuming projectFilePath is in the correct state, create .old from projectFilePath\n await fs.copyFile(projectFilePath, `${projectFilePath}.old`);\n await replaceInFile(projectFilePath, new RegExp(WDA_RUNNER_BUNDLE_ID.replace('.', '\\.'), 'g'), newBundleId); // eslint-disable-line no-useless-escape\n log.debug(`Successfully updated '${projectFilePath}' with bundle id '${newBundleId}'`);\n } catch (err) {\n log.debug(`Error updating project file: ${err.message}`);\n log.warn(`Unable to update project file '${projectFilePath}' with ` +\n `bundle id '${newBundleId}'. WebDriverAgent may not start`);\n }\n}", "language": "javascript", "code": "async function updateProjectFile (agentPath, newBundleId) {\n let projectFilePath = `${agentPath}/${PROJECT_FILE}`;\n try {\n // Assuming projectFilePath is in the correct state, create .old from projectFilePath\n await fs.copyFile(projectFilePath, `${projectFilePath}.old`);\n await replaceInFile(projectFilePath, new RegExp(WDA_RUNNER_BUNDLE_ID.replace('.', '\\.'), 'g'), newBundleId); // eslint-disable-line no-useless-escape\n log.debug(`Successfully updated '${projectFilePath}' with bundle id '${newBundleId}'`);\n } catch (err) {\n log.debug(`Error updating project file: ${err.message}`);\n log.warn(`Unable to update project file '${projectFilePath}' with ` +\n `bundle id '${newBundleId}'. WebDriverAgent may not start`);\n }\n}", "code_tokens": ["async", "function", "updateProjectFile", "(", "agentPath", ",", "newBundleId", ")", "{", "let", "projectFilePath", "=", "`", "${", "agentPath", "}", "${", "PROJECT_FILE", "}", "`", ";", "try", "{", "await", "fs", ".", "copyFile", "(", "projectFilePath", ",", "`", "${", "projectFilePath", "}", "`", ")", ";", "await", "replaceInFile", "(", "projectFilePath", ",", "new", "RegExp", "(", "WDA_RUNNER_BUNDLE_ID", ".", "replace", "(", "'.'", ",", "'\\.'", ")", ",", "\\.", ")", ",", "'g'", ")", ";", "newBundleId", "}", "log", ".", "debug", "(", "`", "${", "projectFilePath", "}", "${", "newBundleId", "}", "`", ")", ";", "}"], "docstring": "Update WebDriverAgentRunner project bundle ID with newBundleId.\nThis method assumes project file is in the correct state.\n@param {string} agentPath - Path to the .xcodeproj directory.\n@param {string} newBundleId the new bundle ID used to update.", "docstring_tokens": ["Update", "WebDriverAgentRunner", "project", "bundle", "ID", "with", "newBundleId", ".", "This", "method", "assumes", "project", "file", "is", "in", "the", "correct", "state", "."], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/wda/utils.js#L31-L43", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/wda/utils.js", "func_name": "resetProjectFile", "original_string": "async function resetProjectFile (agentPath) {\n let projectFilePath = `${agentPath}/${PROJECT_FILE}`;\n try {\n // restore projectFilePath from .old file\n if (!await fs.exists(`${projectFilePath}.old`)) {\n return; // no need to reset\n }\n await fs.mv(`${projectFilePath}.old`, projectFilePath);\n log.debug(`Successfully reset '${projectFilePath}' with bundle id '${WDA_RUNNER_BUNDLE_ID}'`);\n } catch (err) {\n log.debug(`Error resetting project file: ${err.message}`);\n log.warn(`Unable to reset project file '${projectFilePath}' with ` +\n `bundle id '${WDA_RUNNER_BUNDLE_ID}'. WebDriverAgent has been ` +\n `modified and not returned to the original state.`);\n }\n}", "language": "javascript", "code": "async function resetProjectFile (agentPath) {\n let projectFilePath = `${agentPath}/${PROJECT_FILE}`;\n try {\n // restore projectFilePath from .old file\n if (!await fs.exists(`${projectFilePath}.old`)) {\n return; // no need to reset\n }\n await fs.mv(`${projectFilePath}.old`, projectFilePath);\n log.debug(`Successfully reset '${projectFilePath}' with bundle id '${WDA_RUNNER_BUNDLE_ID}'`);\n } catch (err) {\n log.debug(`Error resetting project file: ${err.message}`);\n log.warn(`Unable to reset project file '${projectFilePath}' with ` +\n `bundle id '${WDA_RUNNER_BUNDLE_ID}'. WebDriverAgent has been ` +\n `modified and not returned to the original state.`);\n }\n}", "code_tokens": ["async", "function", "resetProjectFile", "(", "agentPath", ")", "{", "let", "projectFilePath", "=", "`", "${", "agentPath", "}", "${", "PROJECT_FILE", "}", "`", ";", "try", "{", "if", "(", "!", "await", "fs", ".", "exists", "(", "`", "${", "projectFilePath", "}", "`", ")", ")", "{", "return", ";", "}", "await", "fs", ".", "mv", "(", "`", "${", "projectFilePath", "}", "`", ",", "projectFilePath", ")", ";", "log", ".", "debug", "(", "`", "${", "projectFilePath", "}", "${", "WDA_RUNNER_BUNDLE_ID", "}", "`", ")", ";", "}", "catch", "(", "err", ")", "{", "log", ".", "debug", "(", "`", "${", "err", ".", "message", "}", "`", ")", ";", "log", ".", "warn", "(", "`", "${", "projectFilePath", "}", "`", "+", "`", "${", "WDA_RUNNER_BUNDLE_ID", "}", "`", "+", "`", "`", ")", ";", "}", "}"], "docstring": "Reset WebDriverAgentRunner project bundle ID to correct state.\n@param {string} agentPath - Path to the .xcodeproj directory.", "docstring_tokens": ["Reset", "WebDriverAgentRunner", "project", "bundle", "ID", "to", "correct", "state", "."], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/wda/utils.js#L49-L64", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/wda/utils.js", "func_name": "getAdditionalRunContent", "original_string": "function getAdditionalRunContent (platformName, wdaRemotePort) {\n const runner = `WebDriverAgentRunner${isTvOS(platformName) ? '_tvOS' : ''}`;\n\n return {\n [runner]: {\n EnvironmentVariables: {\n USE_PORT: wdaRemotePort\n }\n }\n };\n}", "language": "javascript", "code": "function getAdditionalRunContent (platformName, wdaRemotePort) {\n const runner = `WebDriverAgentRunner${isTvOS(platformName) ? '_tvOS' : ''}`;\n\n return {\n [runner]: {\n EnvironmentVariables: {\n USE_PORT: wdaRemotePort\n }\n }\n };\n}", "code_tokens": ["function", "getAdditionalRunContent", "(", "platformName", ",", "wdaRemotePort", ")", "{", "const", "runner", "=", "`", "${", "isTvOS", "(", "platformName", ")", "?", "'_tvOS'", ":", "''", "}", "`", ";", "return", "{", "[", "runner", "]", ":", "{", "EnvironmentVariables", ":", "{", "USE_PORT", ":", "wdaRemotePort", "}", "}", "}", ";", "}"], "docstring": "Return the WDA object which appends existing xctest runner content\n@param {string} platformName - The name of the platform\n@param {string} version - The Xcode SDK version of OS.\n@return {object} returns a runner object which has USE_PORT", "docstring_tokens": ["Return", "the", "WDA", "object", "which", "appends", "existing", "xctest", "runner", "content"], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/wda/utils.js#L237-L247", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/wda/utils.js", "func_name": "getWDAUpgradeTimestamp", "original_string": "async function getWDAUpgradeTimestamp (bootstrapPath) {\n const carthageRootPath = path.resolve(bootstrapPath, CARTHAGE_ROOT);\n if (await fs.exists(carthageRootPath)) {\n const {mtime} = await fs.stat(carthageRootPath);\n return mtime.getTime();\n }\n return null;\n}", "language": "javascript", "code": "async function getWDAUpgradeTimestamp (bootstrapPath) {\n const carthageRootPath = path.resolve(bootstrapPath, CARTHAGE_ROOT);\n if (await fs.exists(carthageRootPath)) {\n const {mtime} = await fs.stat(carthageRootPath);\n return mtime.getTime();\n }\n return null;\n}", "code_tokens": ["async", "function", "getWDAUpgradeTimestamp", "(", "bootstrapPath", ")", "{", "const", "carthageRootPath", "=", "path", ".", "resolve", "(", "bootstrapPath", ",", "CARTHAGE_ROOT", ")", ";", "if", "(", "await", "fs", ".", "exists", "(", "carthageRootPath", ")", ")", "{", "const", "{", "mtime", "}", "=", "await", "fs", ".", "stat", "(", "carthageRootPath", ")", ";", "return", "mtime", ".", "getTime", "(", ")", ";", "}", "return", "null", ";", "}"], "docstring": "Retrieves WDA upgrade timestamp\n\n@param {string} bootstrapPath The full path to the folder where WDA source is located\n@return {?number} The UNIX timestamp of the carthage root folder, where dependencies are downloaded.\nThis folder is created only once on module upgrade/first install.", "docstring_tokens": ["Retrieves", "WDA", "upgrade", "timestamp"], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/wda/utils.js#L340-L347", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/commands/file-movement.js", "func_name": "parseContainerPath", "original_string": "async function parseContainerPath (remotePath, containerRootSupplier) {\n const match = CONTAINER_PATH_PATTERN.exec(remotePath);\n if (!match) {\n log.errorAndThrow(`It is expected that package identifier ` +\n `starts with '${CONTAINER_PATH_MARKER}' and is separated from the ` +\n `relative path with a single slash. '${remotePath}' is given instead`);\n }\n let [, bundleId, relativePath] = match;\n let containerType = null;\n const typeSeparatorPos = bundleId.indexOf(CONTAINER_TYPE_SEPARATOR);\n // We only consider container type exists if its length is greater than zero\n // not counting the colon\n if (typeSeparatorPos > 0 && typeSeparatorPos < bundleId.length - 1) {\n containerType = bundleId.substring(typeSeparatorPos + 1);\n log.debug(`Parsed container type: ${containerType}`);\n bundleId = bundleId.substring(0, typeSeparatorPos);\n }\n const containerRoot = _.isFunction(containerRootSupplier)\n ? await containerRootSupplier(bundleId, containerType)\n : containerRootSupplier;\n const resultPath = path.posix.resolve(containerRoot, relativePath);\n verifyIsSubPath(resultPath, containerRoot);\n return [bundleId, resultPath];\n}", "language": "javascript", "code": "async function parseContainerPath (remotePath, containerRootSupplier) {\n const match = CONTAINER_PATH_PATTERN.exec(remotePath);\n if (!match) {\n log.errorAndThrow(`It is expected that package identifier ` +\n `starts with '${CONTAINER_PATH_MARKER}' and is separated from the ` +\n `relative path with a single slash. '${remotePath}' is given instead`);\n }\n let [, bundleId, relativePath] = match;\n let containerType = null;\n const typeSeparatorPos = bundleId.indexOf(CONTAINER_TYPE_SEPARATOR);\n // We only consider container type exists if its length is greater than zero\n // not counting the colon\n if (typeSeparatorPos > 0 && typeSeparatorPos < bundleId.length - 1) {\n containerType = bundleId.substring(typeSeparatorPos + 1);\n log.debug(`Parsed container type: ${containerType}`);\n bundleId = bundleId.substring(0, typeSeparatorPos);\n }\n const containerRoot = _.isFunction(containerRootSupplier)\n ? await containerRootSupplier(bundleId, containerType)\n : containerRootSupplier;\n const resultPath = path.posix.resolve(containerRoot, relativePath);\n verifyIsSubPath(resultPath, containerRoot);\n return [bundleId, resultPath];\n}", "code_tokens": ["async", "function", "parseContainerPath", "(", "remotePath", ",", "containerRootSupplier", ")", "{", "const", "match", "=", "CONTAINER_PATH_PATTERN", ".", "exec", "(", "remotePath", ")", ";", "if", "(", "!", "match", ")", "{", "log", ".", "errorAndThrow", "(", "`", "`", "+", "`", "${", "CONTAINER_PATH_MARKER", "}", "`", "+", "`", "${", "remotePath", "}", "`", ")", ";", "}", "let", "[", ",", "bundleId", ",", "relativePath", "]", "=", "match", ";", "let", "containerType", "=", "null", ";", "const", "typeSeparatorPos", "=", "bundleId", ".", "indexOf", "(", "CONTAINER_TYPE_SEPARATOR", ")", ";", "if", "(", "typeSeparatorPos", ">", "0", "&&", "typeSeparatorPos", "<", "bundleId", ".", "length", "-", "1", ")", "{", "containerType", "=", "bundleId", ".", "substring", "(", "typeSeparatorPos", "+", "1", ")", ";", "log", ".", "debug", "(", "`", "${", "containerType", "}", "`", ")", ";", "bundleId", "=", "bundleId", ".", "substring", "(", "0", ",", "typeSeparatorPos", ")", ";", "}", "const", "containerRoot", "=", "_", ".", "isFunction", "(", "containerRootSupplier", ")", "?", "await", "containerRootSupplier", "(", "bundleId", ",", "containerType", ")", ":", "containerRootSupplier", ";", "const", "resultPath", "=", "path", ".", "posix", ".", "resolve", "(", "containerRoot", ",", "relativePath", ")", ";", "verifyIsSubPath", "(", "resultPath", ",", "containerRoot", ")", ";", "return", "[", "bundleId", ",", "resultPath", "]", ";", "}"], "docstring": "Parses the actual path and the bundle identifier from the given path string\n\n@param {string} remotePath - The given path string. The string should\nmatch `CONTAINER_PATH_PATTERN` regexp, otherwise an error is going\nto be thrown. A valid string example: `@bundle.identifier:container_type/relative_path_in_container`\n@param {Function|string} containerRootSupplier - Either a string, that contains\nfull path to the mount root for real devices or a function, which accepts two parameters\n(bundle identifier and optional container type) and returns full path to container\nroot folder on the local file system, for Simulator\n@returns {Array} - An array where the first item is the parsed bundle\nidentifier and the second one is the absolute full path of the item on the local\nfile system", "docstring_tokens": ["Parses", "the", "actual", "path", "and", "the", "bundle", "identifier", "from", "the", "given", "path", "string"], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/commands/file-movement.js#L59-L82", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/commands/file-movement.js", "func_name": "pushFileToSimulator", "original_string": "async function pushFileToSimulator (device, remotePath, base64Data) {\n const buffer = Buffer.from(base64Data, 'base64');\n if (CONTAINER_PATH_PATTERN.test(remotePath)) {\n const [bundleId, dstPath] = await parseContainerPath(remotePath,\n async (appBundle, containerType) => await getAppContainer(device.udid, appBundle, null, containerType));\n log.info(`Parsed bundle identifier '${bundleId}' from '${remotePath}'. ` +\n `Will put the data into '${dstPath}'`);\n if (!await fs.exists(path.dirname(dstPath))) {\n log.debug(`The destination folder '${path.dirname(dstPath)}' does not exist. Creating...`);\n await mkdirp(path.dirname(dstPath));\n }\n await fs.writeFile(dstPath, buffer);\n return;\n }\n const dstFolder = await tempDir.openDir();\n const dstPath = path.resolve(dstFolder, path.basename(remotePath));\n try {\n await fs.writeFile(dstPath, buffer);\n await addMedia(device.udid, dstPath);\n } finally {\n await fs.rimraf(dstFolder);\n }\n}", "language": "javascript", "code": "async function pushFileToSimulator (device, remotePath, base64Data) {\n const buffer = Buffer.from(base64Data, 'base64');\n if (CONTAINER_PATH_PATTERN.test(remotePath)) {\n const [bundleId, dstPath] = await parseContainerPath(remotePath,\n async (appBundle, containerType) => await getAppContainer(device.udid, appBundle, null, containerType));\n log.info(`Parsed bundle identifier '${bundleId}' from '${remotePath}'. ` +\n `Will put the data into '${dstPath}'`);\n if (!await fs.exists(path.dirname(dstPath))) {\n log.debug(`The destination folder '${path.dirname(dstPath)}' does not exist. Creating...`);\n await mkdirp(path.dirname(dstPath));\n }\n await fs.writeFile(dstPath, buffer);\n return;\n }\n const dstFolder = await tempDir.openDir();\n const dstPath = path.resolve(dstFolder, path.basename(remotePath));\n try {\n await fs.writeFile(dstPath, buffer);\n await addMedia(device.udid, dstPath);\n } finally {\n await fs.rimraf(dstFolder);\n }\n}", "code_tokens": ["async", "function", "pushFileToSimulator", "(", "device", ",", "remotePath", ",", "base64Data", ")", "{", "const", "buffer", "=", "Buffer", ".", "from", "(", "base64Data", ",", "'base64'", ")", ";", "if", "(", "CONTAINER_PATH_PATTERN", ".", "test", "(", "remotePath", ")", ")", "{", "const", "[", "bundleId", ",", "dstPath", "]", "=", "await", "parseContainerPath", "(", "remotePath", ",", "async", "(", "appBundle", ",", "containerType", ")", "=>", "await", "getAppContainer", "(", "device", ".", "udid", ",", "appBundle", ",", "null", ",", "containerType", ")", ")", ";", "log", ".", "info", "(", "`", "${", "bundleId", "}", "${", "remotePath", "}", "`", "+", "`", "${", "dstPath", "}", "`", ")", ";", "if", "(", "!", "await", "fs", ".", "exists", "(", "path", ".", "dirname", "(", "dstPath", ")", ")", ")", "{", "log", ".", "debug", "(", "`", "${", "path", ".", "dirname", "(", "dstPath", ")", "}", "`", ")", ";", "await", "mkdirp", "(", "path", ".", "dirname", "(", "dstPath", ")", ")", ";", "}", "await", "fs", ".", "writeFile", "(", "dstPath", ",", "buffer", ")", ";", "return", ";", "}", "const", "dstFolder", "=", "await", "tempDir", ".", "openDir", "(", ")", ";", "const", "dstPath", "=", "path", ".", "resolve", "(", "dstFolder", ",", "path", ".", "basename", "(", "remotePath", ")", ")", ";", "try", "{", "await", "fs", ".", "writeFile", "(", "dstPath", ",", "buffer", ")", ";", "await", "addMedia", "(", "device", ".", "udid", ",", "dstPath", ")", ";", "}", "finally", "{", "await", "fs", ".", "rimraf", "(", "dstFolder", ")", ";", "}", "}"], "docstring": "Save the given base64 data chunk as a binary file on the Simulator under test.\n\n@param {Object} device - The device object, which represents the device under test.\nThis object is expected to have the `udid` property containing the\nvalid device ID.\n@param {string} remotePath - The remote path on the device. This variable can be prefixed with\nbundle id, so then the file will be uploaded to the corresponding\napplication container instead of the default media folder, for example\n'@com.myapp.bla:data/RelativePathInContainer/111.png'. The '@' character at the\nbeginning of the argument is mandatory in such case. The colon at the end of bundle identifier\nis optional and is used to distinguish the container type.\nPossible values there are 'app', 'data', 'groups', ''.\nThe default value is 'app'.\nThe relative folder path is ignored if the file is going to be uploaded\nto the default media folder and only the file name is considered important.\n@param {string} base64Data - Base-64 encoded content of the file to be uploaded.", "docstring_tokens": ["Save", "the", "given", "base64", "data", "chunk", "as", "a", "binary", "file", "on", "the", "Simulator", "under", "test", "."], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/commands/file-movement.js#L102-L124", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/commands/file-movement.js", "func_name": "pullFromSimulator", "original_string": "async function pullFromSimulator (device, remotePath, isFile) {\n let pathOnServer;\n if (CONTAINER_PATH_PATTERN.test(remotePath)) {\n const [bundleId, dstPath] = await parseContainerPath(remotePath,\n async (appBundle, containerType) => await getAppContainer(device.udid, appBundle, null, containerType));\n log.info(`Parsed bundle identifier '${bundleId}' from '${remotePath}'. ` +\n `Will get the data from '${dstPath}'`);\n pathOnServer = dstPath;\n } else {\n const simRoot = device.getDir();\n pathOnServer = path.posix.join(simRoot, remotePath);\n verifyIsSubPath(pathOnServer, simRoot);\n log.info(`Got the full item path: ${pathOnServer}`);\n }\n if (!await fs.exists(pathOnServer)) {\n log.errorAndThrow(`The remote ${isFile ? 'file' : 'folder'} at '${pathOnServer}' does not exist`);\n }\n const buffer = isFile\n ? await fs.readFile(pathOnServer)\n : await zip.toInMemoryZip(pathOnServer);\n return Buffer.from(buffer).toString('base64');\n}", "language": "javascript", "code": "async function pullFromSimulator (device, remotePath, isFile) {\n let pathOnServer;\n if (CONTAINER_PATH_PATTERN.test(remotePath)) {\n const [bundleId, dstPath] = await parseContainerPath(remotePath,\n async (appBundle, containerType) => await getAppContainer(device.udid, appBundle, null, containerType));\n log.info(`Parsed bundle identifier '${bundleId}' from '${remotePath}'. ` +\n `Will get the data from '${dstPath}'`);\n pathOnServer = dstPath;\n } else {\n const simRoot = device.getDir();\n pathOnServer = path.posix.join(simRoot, remotePath);\n verifyIsSubPath(pathOnServer, simRoot);\n log.info(`Got the full item path: ${pathOnServer}`);\n }\n if (!await fs.exists(pathOnServer)) {\n log.errorAndThrow(`The remote ${isFile ? 'file' : 'folder'} at '${pathOnServer}' does not exist`);\n }\n const buffer = isFile\n ? await fs.readFile(pathOnServer)\n : await zip.toInMemoryZip(pathOnServer);\n return Buffer.from(buffer).toString('base64');\n}", "code_tokens": ["async", "function", "pullFromSimulator", "(", "device", ",", "remotePath", ",", "isFile", ")", "{", "let", "pathOnServer", ";", "if", "(", "CONTAINER_PATH_PATTERN", ".", "test", "(", "remotePath", ")", ")", "{", "const", "[", "bundleId", ",", "dstPath", "]", "=", "await", "parseContainerPath", "(", "remotePath", ",", "async", "(", "appBundle", ",", "containerType", ")", "=>", "await", "getAppContainer", "(", "device", ".", "udid", ",", "appBundle", ",", "null", ",", "containerType", ")", ")", ";", "log", ".", "info", "(", "`", "${", "bundleId", "}", "${", "remotePath", "}", "`", "+", "`", "${", "dstPath", "}", "`", ")", ";", "pathOnServer", "=", "dstPath", ";", "}", "else", "{", "const", "simRoot", "=", "device", ".", "getDir", "(", ")", ";", "pathOnServer", "=", "path", ".", "posix", ".", "join", "(", "simRoot", ",", "remotePath", ")", ";", "verifyIsSubPath", "(", "pathOnServer", ",", "simRoot", ")", ";", "log", ".", "info", "(", "`", "${", "pathOnServer", "}", "`", ")", ";", "}", "if", "(", "!", "await", "fs", ".", "exists", "(", "pathOnServer", ")", ")", "{", "log", ".", "errorAndThrow", "(", "`", "${", "isFile", "?", "'file'", ":", "'folder'", "}", "${", "pathOnServer", "}", "`", ")", ";", "}", "const", "buffer", "=", "isFile", "?", "await", "fs", ".", "readFile", "(", "pathOnServer", ")", ":", "await", "zip", ".", "toInMemoryZip", "(", "pathOnServer", ")", ";", "return", "Buffer", ".", "from", "(", "buffer", ")", ".", "toString", "(", "'base64'", ")", ";", "}"], "docstring": "Get the content of given file or folder from iOS Simulator and return it as base-64 encoded string.\nFolder content is recursively packed into a zip archive.\n\n@param {Object} device - The device object, which represents the device under test.\nThis object is expected to have the `udid` property containing the\nvalid device ID.\n@param {string} remotePath - The path to a file or a folder, which exists in the corresponding application\ncontainer on Simulator. Use\n@:/\nformat to pull a file or a folder from an application container of the given type.\nPossible container types are 'app', 'data', 'groups', ''.\nThe default type is 'app'.\n@param {boolean} isFile - Whether the destination item is a file or a folder\n@returns {string} Base-64 encoded content of the file.", "docstring_tokens": ["Get", "the", "content", "of", "given", "file", "or", "folder", "from", "iOS", "Simulator", "and", "return", "it", "as", "base", "-", "64", "encoded", "string", ".", "Folder", "content", "is", "recursively", "packed", "into", "a", "zip", "archive", "."], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/commands/file-movement.js#L195-L216", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/commands/file-movement.js", "func_name": "pullFromRealDevice", "original_string": "async function pullFromRealDevice (device, remotePath, isFile) {\n await verifyIFusePresence();\n const mntRoot = await tempDir.openDir();\n let isUnmountSuccessful = true;\n try {\n let dstPath = path.resolve(mntRoot, remotePath);\n let ifuseArgs = ['-u', device.udid, mntRoot];\n if (CONTAINER_PATH_PATTERN.test(remotePath)) {\n const [bundleId, pathInContainer] = await parseContainerPath(remotePath, mntRoot);\n dstPath = pathInContainer;\n log.info(`Parsed bundle identifier '${bundleId}' from '${remotePath}'. ` +\n `Will get the data from '${dstPath}'`);\n ifuseArgs = ['-u', device.udid, '--container', bundleId, mntRoot];\n } else {\n verifyIsSubPath(dstPath, mntRoot);\n }\n await mountDevice(device, ifuseArgs);\n isUnmountSuccessful = false;\n try {\n if (!await fs.exists(dstPath)) {\n log.errorAndThrow(`The remote ${isFile ? 'file' : 'folder'} at '${dstPath}' does not exist`);\n }\n const buffer = isFile\n ? await fs.readFile(dstPath)\n : await zip.toInMemoryZip(dstPath);\n return Buffer.from(buffer).toString('base64');\n } finally {\n await exec('umount', [mntRoot]);\n isUnmountSuccessful = true;\n }\n } finally {\n if (isUnmountSuccessful) {\n await fs.rimraf(mntRoot);\n } else {\n log.warn(`Umount has failed, so not removing '${mntRoot}'`);\n }\n }\n}", "language": "javascript", "code": "async function pullFromRealDevice (device, remotePath, isFile) {\n await verifyIFusePresence();\n const mntRoot = await tempDir.openDir();\n let isUnmountSuccessful = true;\n try {\n let dstPath = path.resolve(mntRoot, remotePath);\n let ifuseArgs = ['-u', device.udid, mntRoot];\n if (CONTAINER_PATH_PATTERN.test(remotePath)) {\n const [bundleId, pathInContainer] = await parseContainerPath(remotePath, mntRoot);\n dstPath = pathInContainer;\n log.info(`Parsed bundle identifier '${bundleId}' from '${remotePath}'. ` +\n `Will get the data from '${dstPath}'`);\n ifuseArgs = ['-u', device.udid, '--container', bundleId, mntRoot];\n } else {\n verifyIsSubPath(dstPath, mntRoot);\n }\n await mountDevice(device, ifuseArgs);\n isUnmountSuccessful = false;\n try {\n if (!await fs.exists(dstPath)) {\n log.errorAndThrow(`The remote ${isFile ? 'file' : 'folder'} at '${dstPath}' does not exist`);\n }\n const buffer = isFile\n ? await fs.readFile(dstPath)\n : await zip.toInMemoryZip(dstPath);\n return Buffer.from(buffer).toString('base64');\n } finally {\n await exec('umount', [mntRoot]);\n isUnmountSuccessful = true;\n }\n } finally {\n if (isUnmountSuccessful) {\n await fs.rimraf(mntRoot);\n } else {\n log.warn(`Umount has failed, so not removing '${mntRoot}'`);\n }\n }\n}", "code_tokens": ["async", "function", "pullFromRealDevice", "(", "device", ",", "remotePath", ",", "isFile", ")", "{", "await", "verifyIFusePresence", "(", ")", ";", "const", "mntRoot", "=", "await", "tempDir", ".", "openDir", "(", ")", ";", "let", "isUnmountSuccessful", "=", "true", ";", "try", "{", "let", "dstPath", "=", "path", ".", "resolve", "(", "mntRoot", ",", "remotePath", ")", ";", "let", "ifuseArgs", "=", "[", "'-u'", ",", "device", ".", "udid", ",", "mntRoot", "]", ";", "if", "(", "CONTAINER_PATH_PATTERN", ".", "test", "(", "remotePath", ")", ")", "{", "const", "[", "bundleId", ",", "pathInContainer", "]", "=", "await", "parseContainerPath", "(", "remotePath", ",", "mntRoot", ")", ";", "dstPath", "=", "pathInContainer", ";", "log", ".", "info", "(", "`", "${", "bundleId", "}", "${", "remotePath", "}", "`", "+", "`", "${", "dstPath", "}", "`", ")", ";", "ifuseArgs", "=", "[", "'-u'", ",", "device", ".", "udid", ",", "'--container'", ",", "bundleId", ",", "mntRoot", "]", ";", "}", "else", "{", "verifyIsSubPath", "(", "dstPath", ",", "mntRoot", ")", ";", "}", "await", "mountDevice", "(", "device", ",", "ifuseArgs", ")", ";", "isUnmountSuccessful", "=", "false", ";", "try", "{", "if", "(", "!", "await", "fs", ".", "exists", "(", "dstPath", ")", ")", "{", "log", ".", "errorAndThrow", "(", "`", "${", "isFile", "?", "'file'", ":", "'folder'", "}", "${", "dstPath", "}", "`", ")", ";", "}", "const", "buffer", "=", "isFile", "?", "await", "fs", ".", "readFile", "(", "dstPath", ")", ":", "await", "zip", ".", "toInMemoryZip", "(", "dstPath", ")", ";", "return", "Buffer", ".", "from", "(", "buffer", ")", ".", "toString", "(", "'base64'", ")", ";", "}", "finally", "{", "await", "exec", "(", "'umount'", ",", "[", "mntRoot", "]", ")", ";", "isUnmountSuccessful", "=", "true", ";", "}", "}", "finally", "{", "if", "(", "isUnmountSuccessful", ")", "{", "await", "fs", ".", "rimraf", "(", "mntRoot", ")", ";", "}", "else", "{", "log", ".", "warn", "(", "`", "${", "mntRoot", "}", "`", ")", ";", "}", "}", "}"], "docstring": "Get the content of given file or folder from the real device under test and return it as base-64 encoded string.\nFolder content is recursively packed into a zip archive.\n\n@param {Object} device - The device object, which represents the device under test.\nThis object is expected to have the `udid` property containing the\nvalid device ID.\n@param {string} remotePath - The path to an existing remote file on the device. This variable can be prefixed with\nbundle id, so then the file will be downloaded from the corresponding\napplication container instead of the default media folder, for example\n'@com.myapp.bla/RelativePathInContainer/111.png'. The '@' character at the\nbeginning of the argument is mandatory in such case.\n@param {boolean} isFile - Whether the destination item is a file or a folder\n@return {string} Base-64 encoded content of the remote file", "docstring_tokens": ["Get", "the", "content", "of", "given", "file", "or", "folder", "from", "the", "real", "device", "under", "test", "and", "return", "it", "as", "base", "-", "64", "encoded", "string", ".", "Folder", "content", "is", "recursively", "packed", "into", "a", "zip", "archive", "."], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/commands/file-movement.js#L233-L270", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/simulator-management.js", "func_name": "createSim", "original_string": "async function createSim (caps, platform = PLATFORM_NAME_IOS) {\n const appiumTestDeviceName = `appiumTest-${UUID.create().toString().toUpperCase()}-${caps.deviceName}`;\n const udid = await createDevice(\n appiumTestDeviceName,\n caps.deviceName,\n caps.platformVersion,\n { platform }\n );\n return await getSimulator(udid);\n}", "language": "javascript", "code": "async function createSim (caps, platform = PLATFORM_NAME_IOS) {\n const appiumTestDeviceName = `appiumTest-${UUID.create().toString().toUpperCase()}-${caps.deviceName}`;\n const udid = await createDevice(\n appiumTestDeviceName,\n caps.deviceName,\n caps.platformVersion,\n { platform }\n );\n return await getSimulator(udid);\n}", "code_tokens": ["async", "function", "createSim", "(", "caps", ",", "platform", "=", "PLATFORM_NAME_IOS", ")", "{", "const", "appiumTestDeviceName", "=", "`", "${", "UUID", ".", "create", "(", ")", ".", "toString", "(", ")", ".", "toUpperCase", "(", ")", "}", "${", "caps", ".", "deviceName", "}", "`", ";", "const", "udid", "=", "await", "createDevice", "(", "appiumTestDeviceName", ",", "caps", ".", "deviceName", ",", "caps", ".", "platformVersion", ",", "{", "platform", "}", ")", ";", "return", "await", "getSimulator", "(", "udid", ")", ";", "}"], "docstring": "Capability set by a user\n\n@property {string} deviceName - A name for the device\n@property {string} platformVersion - The version of iOS to use\n \nCreate a new simulator with `appiumTest-` prefix and return the object.\n\n@param {object} SimCreationCaps - Capability set by a user. The options available are:\n@property {string} platform [iOS] - Platform name in order to specify runtime such as 'iOS', 'tvOS', 'watchOS'\n@returns {object} Simulator object associated with the udid passed in.", "docstring_tokens": ["Capability", "set", "by", "a", "user"], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/simulator-management.js#L28-L37", "partition": "test"} {"repo": "appium/appium-xcuitest-driver", "path": "lib/simulator-management.js", "func_name": "getExistingSim", "original_string": "async function getExistingSim (opts) {\n const devices = await getDevices(opts.platformVersion);\n const appiumTestDeviceName = `appiumTest-${opts.deviceName}`;\n\n let appiumTestDevice;\n\n for (const device of _.values(devices)) {\n if (device.name === opts.deviceName) {\n return await getSimulator(device.udid);\n }\n\n if (device.name === appiumTestDeviceName) {\n appiumTestDevice = device;\n }\n }\n\n if (appiumTestDevice) {\n log.warn(`Unable to find device '${opts.deviceName}'. Found '${appiumTestDevice.name}' (udid: '${appiumTestDevice.udid}') instead`);\n return await getSimulator(appiumTestDevice.udid);\n }\n return null;\n}", "language": "javascript", "code": "async function getExistingSim (opts) {\n const devices = await getDevices(opts.platformVersion);\n const appiumTestDeviceName = `appiumTest-${opts.deviceName}`;\n\n let appiumTestDevice;\n\n for (const device of _.values(devices)) {\n if (device.name === opts.deviceName) {\n return await getSimulator(device.udid);\n }\n\n if (device.name === appiumTestDeviceName) {\n appiumTestDevice = device;\n }\n }\n\n if (appiumTestDevice) {\n log.warn(`Unable to find device '${opts.deviceName}'. Found '${appiumTestDevice.name}' (udid: '${appiumTestDevice.udid}') instead`);\n return await getSimulator(appiumTestDevice.udid);\n }\n return null;\n}", "code_tokens": ["async", "function", "getExistingSim", "(", "opts", ")", "{", "const", "devices", "=", "await", "getDevices", "(", "opts", ".", "platformVersion", ")", ";", "const", "appiumTestDeviceName", "=", "`", "${", "opts", ".", "deviceName", "}", "`", ";", "let", "appiumTestDevice", ";", "for", "(", "const", "device", "of", "_", ".", "values", "(", "devices", ")", ")", "{", "if", "(", "device", ".", "name", "===", "opts", ".", "deviceName", ")", "{", "return", "await", "getSimulator", "(", "device", ".", "udid", ")", ";", "}", "if", "(", "device", ".", "name", "===", "appiumTestDeviceName", ")", "{", "appiumTestDevice", "=", "device", ";", "}", "}", "if", "(", "appiumTestDevice", ")", "{", "log", ".", "warn", "(", "`", "${", "opts", ".", "deviceName", "}", "${", "appiumTestDevice", ".", "name", "}", "${", "appiumTestDevice", ".", "udid", "}", "`", ")", ";", "return", "await", "getSimulator", "(", "appiumTestDevice", ".", "udid", ")", ";", "}", "return", "null", ";", "}"], "docstring": "Get a simulator which is already running.\n\n@param {object} opts - Capability set by a user. The options available are:\n- `deviceName` - a name for the device\n- `platformVersion` - the version of iOS to use\n@returns {?object} Simulator object associated with the udid passed in. Or null if no device is running.", "docstring_tokens": ["Get", "a", "simulator", "which", "is", "already", "running", "."], "sha": "eb8c1348c390314c7ad12294f8eb5c2e52326f57", "url": "https://github.com/appium/appium-xcuitest-driver/blob/eb8c1348c390314c7ad12294f8eb5c2e52326f57/lib/simulator-management.js#L47-L68", "partition": "test"} {"repo": "donmccurdy/aframe-extras", "path": "src/misc/sphere-collider.js", "func_name": "", "original_string": "function () {\n const data = this.data;\n let objectEls;\n\n // Push entities into list of els to intersect.\n if (data.objects) {\n objectEls = this.el.sceneEl.querySelectorAll(data.objects);\n } else {\n // If objects not defined, intersect with everything.\n objectEls = this.el.sceneEl.children;\n }\n // Convert from NodeList to Array\n this.els = Array.prototype.slice.call(objectEls);\n }", "language": "javascript", "code": "function () {\n const data = this.data;\n let objectEls;\n\n // Push entities into list of els to intersect.\n if (data.objects) {\n objectEls = this.el.sceneEl.querySelectorAll(data.objects);\n } else {\n // If objects not defined, intersect with everything.\n objectEls = this.el.sceneEl.children;\n }\n // Convert from NodeList to Array\n this.els = Array.prototype.slice.call(objectEls);\n }", "code_tokens": ["function", "(", ")", "{", "const", "data", "=", "this", ".", "data", ";", "let", "objectEls", ";", "if", "(", "data", ".", "objects", ")", "{", "objectEls", "=", "this", ".", "el", ".", "sceneEl", ".", "querySelectorAll", "(", "data", ".", "objects", ")", ";", "}", "else", "{", "objectEls", "=", "this", ".", "el", ".", "sceneEl", ".", "children", ";", "}", "this", ".", "els", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "objectEls", ")", ";", "}"], "docstring": "Update list of entities to test for collision.", "docstring_tokens": ["Update", "list", "of", "entities", "to", "test", "for", "collision", "."], "sha": "dcb4084cc89596cebcd24195a8753d877bea2f92", "url": "https://github.com/donmccurdy/aframe-extras/blob/dcb4084cc89596cebcd24195a8753d877bea2f92/src/misc/sphere-collider.js#L54-L67", "partition": "test"} {"repo": "donmccurdy/aframe-extras", "path": "src/misc/sphere-collider.js", "func_name": "intersect", "original_string": "function intersect (el) {\n let radius, mesh, distance, extent;\n\n if (!el.isEntity) { return; }\n\n mesh = el.getObject3D('mesh');\n\n if (!mesh) { return; }\n\n box.setFromObject(mesh).getSize(size);\n extent = Math.max(size.x, size.y, size.z) / 2;\n radius = Math.sqrt(2 * extent * extent);\n box.getCenter(meshPosition);\n\n if (!radius) { return; }\n\n distance = position.distanceTo(meshPosition);\n if (distance < radius + colliderRadius) {\n collisions.push(el);\n distanceMap.set(el, distance);\n }\n }", "language": "javascript", "code": "function intersect (el) {\n let radius, mesh, distance, extent;\n\n if (!el.isEntity) { return; }\n\n mesh = el.getObject3D('mesh');\n\n if (!mesh) { return; }\n\n box.setFromObject(mesh).getSize(size);\n extent = Math.max(size.x, size.y, size.z) / 2;\n radius = Math.sqrt(2 * extent * extent);\n box.getCenter(meshPosition);\n\n if (!radius) { return; }\n\n distance = position.distanceTo(meshPosition);\n if (distance < radius + colliderRadius) {\n collisions.push(el);\n distanceMap.set(el, distance);\n }\n }", "code_tokens": ["function", "intersect", "(", "el", ")", "{", "let", "radius", ",", "mesh", ",", "distance", ",", "extent", ";", "if", "(", "!", "el", ".", "isEntity", ")", "{", "return", ";", "}", "mesh", "=", "el", ".", "getObject3D", "(", "'mesh'", ")", ";", "if", "(", "!", "mesh", ")", "{", "return", ";", "}", "box", ".", "setFromObject", "(", "mesh", ")", ".", "getSize", "(", "size", ")", ";", "extent", "=", "Math", ".", "max", "(", "size", ".", "x", ",", "size", ".", "y", ",", "size", ".", "z", ")", "/", "2", ";", "radius", "=", "Math", ".", "sqrt", "(", "2", "*", "extent", "*", "extent", ")", ";", "box", ".", "getCenter", "(", "meshPosition", ")", ";", "if", "(", "!", "radius", ")", "{", "return", ";", "}", "distance", "=", "position", ".", "distanceTo", "(", "meshPosition", ")", ";", "if", "(", "distance", "<", "radius", "+", "colliderRadius", ")", "{", "collisions", ".", "push", "(", "el", ")", ";", "distanceMap", ".", "set", "(", "el", ",", "distance", ")", ";", "}", "}"], "docstring": "Bounding sphere collision detection", "docstring_tokens": ["Bounding", "sphere", "collision", "detection"], "sha": "dcb4084cc89596cebcd24195a8753d877bea2f92", "url": "https://github.com/donmccurdy/aframe-extras/blob/dcb4084cc89596cebcd24195a8753d877bea2f92/src/misc/sphere-collider.js#L109-L130", "partition": "test"} {"repo": "donmccurdy/aframe-extras", "path": "src/controls/gamepad-controls.js", "func_name": "", "original_string": "function () {\n const gamepad = this.getGamepad();\n if (!gamepad.buttons[GamepadButton.DPAD_RIGHT]) {\n return new THREE.Vector2();\n }\n return new THREE.Vector2(\n (gamepad.buttons[GamepadButton.DPAD_RIGHT].pressed ? 1 : 0)\n + (gamepad.buttons[GamepadButton.DPAD_LEFT].pressed ? -1 : 0),\n (gamepad.buttons[GamepadButton.DPAD_UP].pressed ? -1 : 0)\n + (gamepad.buttons[GamepadButton.DPAD_DOWN].pressed ? 1 : 0)\n );\n }", "language": "javascript", "code": "function () {\n const gamepad = this.getGamepad();\n if (!gamepad.buttons[GamepadButton.DPAD_RIGHT]) {\n return new THREE.Vector2();\n }\n return new THREE.Vector2(\n (gamepad.buttons[GamepadButton.DPAD_RIGHT].pressed ? 1 : 0)\n + (gamepad.buttons[GamepadButton.DPAD_LEFT].pressed ? -1 : 0),\n (gamepad.buttons[GamepadButton.DPAD_UP].pressed ? -1 : 0)\n + (gamepad.buttons[GamepadButton.DPAD_DOWN].pressed ? 1 : 0)\n );\n }", "code_tokens": ["function", "(", ")", "{", "const", "gamepad", "=", "this", ".", "getGamepad", "(", ")", ";", "if", "(", "!", "gamepad", ".", "buttons", "[", "GamepadButton", ".", "DPAD_RIGHT", "]", ")", "{", "return", "new", "THREE", ".", "Vector2", "(", ")", ";", "}", "return", "new", "THREE", ".", "Vector2", "(", "(", "gamepad", ".", "buttons", "[", "GamepadButton", ".", "DPAD_RIGHT", "]", ".", "pressed", "?", "1", ":", "0", ")", "+", "(", "gamepad", ".", "buttons", "[", "GamepadButton", ".", "DPAD_LEFT", "]", ".", "pressed", "?", "-", "1", ":", "0", ")", ",", "(", "gamepad", ".", "buttons", "[", "GamepadButton", ".", "DPAD_UP", "]", ".", "pressed", "?", "-", "1", ":", "0", ")", "+", "(", "gamepad", ".", "buttons", "[", "GamepadButton", ".", "DPAD_DOWN", "]", ".", "pressed", "?", "1", ":", "0", ")", ")", ";", "}"], "docstring": "Returns the state of the dpad as a THREE.Vector2.\n@return {THREE.Vector2}", "docstring_tokens": ["Returns", "the", "state", "of", "the", "dpad", "as", "a", "THREE", ".", "Vector2", "."], "sha": "dcb4084cc89596cebcd24195a8753d877bea2f92", "url": "https://github.com/donmccurdy/aframe-extras/blob/dcb4084cc89596cebcd24195a8753d877bea2f92/src/controls/gamepad-controls.js#L259-L270", "partition": "test"} {"repo": "jerrybendy/url-search-params-polyfill", "path": "index.js", "func_name": "URLSearchParamsPolyfill", "original_string": "function URLSearchParamsPolyfill(search) {\n search = search || \"\";\n\n // support construct object with another URLSearchParams instance\n if (search instanceof URLSearchParams || search instanceof URLSearchParamsPolyfill) {\n search = search.toString();\n }\n this [__URLSearchParams__] = parseToDict(search);\n }", "language": "javascript", "code": "function URLSearchParamsPolyfill(search) {\n search = search || \"\";\n\n // support construct object with another URLSearchParams instance\n if (search instanceof URLSearchParams || search instanceof URLSearchParamsPolyfill) {\n search = search.toString();\n }\n this [__URLSearchParams__] = parseToDict(search);\n }", "code_tokens": ["function", "URLSearchParamsPolyfill", "(", "search", ")", "{", "search", "=", "search", "||", "\"\"", ";", "if", "(", "search", "instanceof", "URLSearchParams", "||", "search", "instanceof", "URLSearchParamsPolyfill", ")", "{", "search", "=", "search", ".", "toString", "(", ")", ";", "}", "this", "[", "__URLSearchParams__", "]", "=", "parseToDict", "(", "search", ")", ";", "}"], "docstring": "Make a URLSearchParams instance\n\n@param {object|string|URLSearchParams} search\n@constructor", "docstring_tokens": ["Make", "a", "URLSearchParams", "instance"], "sha": "cb66794b60f603dd35e71e3031f2479e678a78c8", "url": "https://github.com/jerrybendy/url-search-params-polyfill/blob/cb66794b60f603dd35e71e3031f2479e678a78c8/index.js#L37-L45", "partition": "test"} {"repo": "joyent/node-ldapjs", "path": "lib/client/client.js", "func_name": "RequestQueue", "original_string": "function RequestQueue(opts) {\n if (!opts || typeof (opts) !== 'object') {\n opts = {};\n }\n this.size = (opts.size > 0) ? opts.size : Infinity;\n this.timeout = (opts.timeout > 0) ? opts.timeout : 0;\n this._queue = [];\n this._timer = null;\n this._frozen = false;\n}", "language": "javascript", "code": "function RequestQueue(opts) {\n if (!opts || typeof (opts) !== 'object') {\n opts = {};\n }\n this.size = (opts.size > 0) ? opts.size : Infinity;\n this.timeout = (opts.timeout > 0) ? opts.timeout : 0;\n this._queue = [];\n this._timer = null;\n this._frozen = false;\n}", "code_tokens": ["function", "RequestQueue", "(", "opts", ")", "{", "if", "(", "!", "opts", "||", "typeof", "(", "opts", ")", "!==", "'object'", ")", "{", "opts", "=", "{", "}", ";", "}", "this", ".", "size", "=", "(", "opts", ".", "size", ">", "0", ")", "?", "opts", ".", "size", ":", "Infinity", ";", "this", ".", "timeout", "=", "(", "opts", ".", "timeout", ">", "0", ")", "?", "opts", ".", "timeout", ":", "0", ";", "this", ".", "_queue", "=", "[", "]", ";", "this", ".", "_timer", "=", "null", ";", "this", ".", "_frozen", "=", "false", ";", "}"], "docstring": "Queue to contain LDAP requests.\n\n@param {Object} opts queue options\n\nAccepted Options:\n- size: Maximum queue size\n- timeout: Set timeout between first queue insertion and queue flush.", "docstring_tokens": ["Queue", "to", "contain", "LDAP", "requests", "."], "sha": "ad451edc18d7768c3ddee1a1dd472d2bbafdae5e", "url": "https://github.com/joyent/node-ldapjs/blob/ad451edc18d7768c3ddee1a1dd472d2bbafdae5e/lib/client/client.js#L104-L113", "partition": "test"} {"repo": "joyent/node-ldapjs", "path": "lib/client/client.js", "func_name": "MessageTracker", "original_string": "function MessageTracker(opts) {\n assert.object(opts);\n assert.string(opts.id);\n assert.object(opts.parser);\n\n this.id = opts.id;\n this._msgid = 0;\n this._messages = {};\n this._abandoned = {};\n this.parser = opts.parser;\n\n var self = this;\n this.__defineGetter__('pending', function () {\n return Object.keys(self._messages);\n });\n}", "language": "javascript", "code": "function MessageTracker(opts) {\n assert.object(opts);\n assert.string(opts.id);\n assert.object(opts.parser);\n\n this.id = opts.id;\n this._msgid = 0;\n this._messages = {};\n this._abandoned = {};\n this.parser = opts.parser;\n\n var self = this;\n this.__defineGetter__('pending', function () {\n return Object.keys(self._messages);\n });\n}", "code_tokens": ["function", "MessageTracker", "(", "opts", ")", "{", "assert", ".", "object", "(", "opts", ")", ";", "assert", ".", "string", "(", "opts", ".", "id", ")", ";", "assert", ".", "object", "(", "opts", ".", "parser", ")", ";", "this", ".", "id", "=", "opts", ".", "id", ";", "this", ".", "_msgid", "=", "0", ";", "this", ".", "_messages", "=", "{", "}", ";", "this", ".", "_abandoned", "=", "{", "}", ";", "this", ".", "parser", "=", "opts", ".", "parser", ";", "var", "self", "=", "this", ";", "this", ".", "__defineGetter__", "(", "'pending'", ",", "function", "(", ")", "{", "return", "Object", ".", "keys", "(", "self", ".", "_messages", ")", ";", "}", ")", ";", "}"], "docstring": "Track message callback by messageID.", "docstring_tokens": ["Track", "message", "callback", "by", "messageID", "."], "sha": "ad451edc18d7768c3ddee1a1dd472d2bbafdae5e", "url": "https://github.com/joyent/node-ldapjs/blob/ad451edc18d7768c3ddee1a1dd472d2bbafdae5e/lib/client/client.js#L179-L194", "partition": "test"} {"repo": "joyent/node-ldapjs", "path": "lib/client/client.js", "func_name": "connectSocket", "original_string": "function connectSocket(cb) {\n cb = once(cb);\n\n function onResult(err, res) {\n if (err) {\n if (self.connectTimer) {\n clearTimeout(self.connectTimer);\n self.connectTimer = null;\n }\n self.emit('connectError', err);\n }\n cb(err, res);\n }\n function onConnect() {\n if (self.connectTimer) {\n clearTimeout(self.connectTimer);\n self.connectTimer = null;\n }\n socket.removeAllListeners('error')\n .removeAllListeners('connect')\n .removeAllListeners('secureConnect');\n\n tracker.id = nextClientId() + '__' + tracker.id;\n self.log = self.log.child({ldap_id: tracker.id}, true);\n\n // Move on to client setup\n setupClient(cb);\n }\n\n var port = (self.port || self.socketPath);\n if (self.secure) {\n socket = tls.connect(port, self.host, self.tlsOptions);\n socket.once('secureConnect', onConnect);\n } else {\n socket = net.connect(port, self.host);\n socket.once('connect', onConnect);\n }\n socket.once('error', onResult);\n initSocket();\n\n // Setup connection timeout handling, if desired\n if (self.connectTimeout) {\n self.connectTimer = setTimeout(function onConnectTimeout() {\n if (!socket || !socket.readable || !socket.writeable) {\n socket.destroy();\n self._socket = null;\n onResult(new ConnectionError('connection timeout'));\n }\n }, self.connectTimeout);\n }\n }", "language": "javascript", "code": "function connectSocket(cb) {\n cb = once(cb);\n\n function onResult(err, res) {\n if (err) {\n if (self.connectTimer) {\n clearTimeout(self.connectTimer);\n self.connectTimer = null;\n }\n self.emit('connectError', err);\n }\n cb(err, res);\n }\n function onConnect() {\n if (self.connectTimer) {\n clearTimeout(self.connectTimer);\n self.connectTimer = null;\n }\n socket.removeAllListeners('error')\n .removeAllListeners('connect')\n .removeAllListeners('secureConnect');\n\n tracker.id = nextClientId() + '__' + tracker.id;\n self.log = self.log.child({ldap_id: tracker.id}, true);\n\n // Move on to client setup\n setupClient(cb);\n }\n\n var port = (self.port || self.socketPath);\n if (self.secure) {\n socket = tls.connect(port, self.host, self.tlsOptions);\n socket.once('secureConnect', onConnect);\n } else {\n socket = net.connect(port, self.host);\n socket.once('connect', onConnect);\n }\n socket.once('error', onResult);\n initSocket();\n\n // Setup connection timeout handling, if desired\n if (self.connectTimeout) {\n self.connectTimer = setTimeout(function onConnectTimeout() {\n if (!socket || !socket.readable || !socket.writeable) {\n socket.destroy();\n self._socket = null;\n onResult(new ConnectionError('connection timeout'));\n }\n }, self.connectTimeout);\n }\n }", "code_tokens": ["function", "connectSocket", "(", "cb", ")", "{", "cb", "=", "once", "(", "cb", ")", ";", "function", "onResult", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "if", "(", "self", ".", "connectTimer", ")", "{", "clearTimeout", "(", "self", ".", "connectTimer", ")", ";", "self", ".", "connectTimer", "=", "null", ";", "}", "self", ".", "emit", "(", "'connectError'", ",", "err", ")", ";", "}", "cb", "(", "err", ",", "res", ")", ";", "}", "function", "onConnect", "(", ")", "{", "if", "(", "self", ".", "connectTimer", ")", "{", "clearTimeout", "(", "self", ".", "connectTimer", ")", ";", "self", ".", "connectTimer", "=", "null", ";", "}", "socket", ".", "removeAllListeners", "(", "'error'", ")", ".", "removeAllListeners", "(", "'connect'", ")", ".", "removeAllListeners", "(", "'secureConnect'", ")", ";", "tracker", ".", "id", "=", "nextClientId", "(", ")", "+", "'__'", "+", "tracker", ".", "id", ";", "self", ".", "log", "=", "self", ".", "log", ".", "child", "(", "{", "ldap_id", ":", "tracker", ".", "id", "}", ",", "true", ")", ";", "setupClient", "(", "cb", ")", ";", "}", "var", "port", "=", "(", "self", ".", "port", "||", "self", ".", "socketPath", ")", ";", "if", "(", "self", ".", "secure", ")", "{", "socket", "=", "tls", ".", "connect", "(", "port", ",", "self", ".", "host", ",", "self", ".", "tlsOptions", ")", ";", "socket", ".", "once", "(", "'secureConnect'", ",", "onConnect", ")", ";", "}", "else", "{", "socket", "=", "net", ".", "connect", "(", "port", ",", "self", ".", "host", ")", ";", "socket", ".", "once", "(", "'connect'", ",", "onConnect", ")", ";", "}", "socket", ".", "once", "(", "'error'", ",", "onResult", ")", ";", "initSocket", "(", ")", ";", "if", "(", "self", ".", "connectTimeout", ")", "{", "self", ".", "connectTimer", "=", "setTimeout", "(", "function", "onConnectTimeout", "(", ")", "{", "if", "(", "!", "socket", "||", "!", "socket", ".", "readable", "||", "!", "socket", ".", "writeable", ")", "{", "socket", ".", "destroy", "(", ")", ";", "self", ".", "_socket", "=", "null", ";", "onResult", "(", "new", "ConnectionError", "(", "'connection timeout'", ")", ")", ";", "}", "}", ",", "self", ".", "connectTimeout", ")", ";", "}", "}"], "docstring": "Establish basic socket connection", "docstring_tokens": ["Establish", "basic", "socket", "connection"], "sha": "ad451edc18d7768c3ddee1a1dd472d2bbafdae5e", "url": "https://github.com/joyent/node-ldapjs/blob/ad451edc18d7768c3ddee1a1dd472d2bbafdae5e/lib/client/client.js#L1005-L1055", "partition": "test"} {"repo": "joyent/node-ldapjs", "path": "lib/client/client.js", "func_name": "initSocket", "original_string": "function initSocket() {\n tracker = new MessageTracker({\n id: self.url ? self.url.href : self.socketPath,\n parser: new Parser({log: log})\n });\n\n // This won't be set on TLS. So. Very. Annoying.\n if (typeof (socket.setKeepAlive) !== 'function') {\n socket.setKeepAlive = function setKeepAlive(enable, delay) {\n return socket.socket ?\n socket.socket.setKeepAlive(enable, delay) : false;\n };\n }\n\n socket.on('data', function onData(data) {\n if (log.trace())\n log.trace('data event: %s', util.inspect(data));\n\n tracker.parser.write(data);\n });\n\n // The \"router\"\n tracker.parser.on('message', function onMessage(message) {\n message.connection = self._socket;\n var callback = tracker.fetch(message.messageID);\n\n if (!callback) {\n log.error({message: message.json}, 'unsolicited message');\n return false;\n }\n\n return callback(message);\n });\n\n tracker.parser.on('error', function onParseError(err) {\n self.emit('error', new VError(err, 'Parser error for %s',\n tracker.id));\n self.connected = false;\n socket.end();\n });\n }", "language": "javascript", "code": "function initSocket() {\n tracker = new MessageTracker({\n id: self.url ? self.url.href : self.socketPath,\n parser: new Parser({log: log})\n });\n\n // This won't be set on TLS. So. Very. Annoying.\n if (typeof (socket.setKeepAlive) !== 'function') {\n socket.setKeepAlive = function setKeepAlive(enable, delay) {\n return socket.socket ?\n socket.socket.setKeepAlive(enable, delay) : false;\n };\n }\n\n socket.on('data', function onData(data) {\n if (log.trace())\n log.trace('data event: %s', util.inspect(data));\n\n tracker.parser.write(data);\n });\n\n // The \"router\"\n tracker.parser.on('message', function onMessage(message) {\n message.connection = self._socket;\n var callback = tracker.fetch(message.messageID);\n\n if (!callback) {\n log.error({message: message.json}, 'unsolicited message');\n return false;\n }\n\n return callback(message);\n });\n\n tracker.parser.on('error', function onParseError(err) {\n self.emit('error', new VError(err, 'Parser error for %s',\n tracker.id));\n self.connected = false;\n socket.end();\n });\n }", "code_tokens": ["function", "initSocket", "(", ")", "{", "tracker", "=", "new", "MessageTracker", "(", "{", "id", ":", "self", ".", "url", "?", "self", ".", "url", ".", "href", ":", "self", ".", "socketPath", ",", "parser", ":", "new", "Parser", "(", "{", "log", ":", "log", "}", ")", "}", ")", ";", "if", "(", "typeof", "(", "socket", ".", "setKeepAlive", ")", "!==", "'function'", ")", "{", "socket", ".", "setKeepAlive", "=", "function", "setKeepAlive", "(", "enable", ",", "delay", ")", "{", "return", "socket", ".", "socket", "?", "socket", ".", "socket", ".", "setKeepAlive", "(", "enable", ",", "delay", ")", ":", "false", ";", "}", ";", "}", "socket", ".", "on", "(", "'data'", ",", "function", "onData", "(", "data", ")", "{", "if", "(", "log", ".", "trace", "(", ")", ")", "log", ".", "trace", "(", "'data event: %s'", ",", "util", ".", "inspect", "(", "data", ")", ")", ";", "tracker", ".", "parser", ".", "write", "(", "data", ")", ";", "}", ")", ";", "tracker", ".", "parser", ".", "on", "(", "'message'", ",", "function", "onMessage", "(", "message", ")", "{", "message", ".", "connection", "=", "self", ".", "_socket", ";", "var", "callback", "=", "tracker", ".", "fetch", "(", "message", ".", "messageID", ")", ";", "if", "(", "!", "callback", ")", "{", "log", ".", "error", "(", "{", "message", ":", "message", ".", "json", "}", ",", "'unsolicited message'", ")", ";", "return", "false", ";", "}", "return", "callback", "(", "message", ")", ";", "}", ")", ";", "tracker", ".", "parser", ".", "on", "(", "'error'", ",", "function", "onParseError", "(", "err", ")", "{", "self", ".", "emit", "(", "'error'", ",", "new", "VError", "(", "err", ",", "'Parser error for %s'", ",", "tracker", ".", "id", ")", ")", ";", "self", ".", "connected", "=", "false", ";", "socket", ".", "end", "(", ")", ";", "}", ")", ";", "}"], "docstring": "Initialize socket events and LDAP parser.", "docstring_tokens": ["Initialize", "socket", "events", "and", "LDAP", "parser", "."], "sha": "ad451edc18d7768c3ddee1a1dd472d2bbafdae5e", "url": "https://github.com/joyent/node-ldapjs/blob/ad451edc18d7768c3ddee1a1dd472d2bbafdae5e/lib/client/client.js#L1058-L1098", "partition": "test"} {"repo": "joyent/node-ldapjs", "path": "lib/client/client.js", "func_name": "setupClient", "original_string": "function setupClient(cb) {\n cb = once(cb);\n\n // Indicate failure if anything goes awry during setup\n function bail(err) {\n socket.destroy();\n cb(err || new Error('client error during setup'));\n }\n // Work around lack of close event on tls.socket in node < 0.11\n ((socket.socket) ? socket.socket : socket).once('close', bail);\n socket.once('error', bail);\n socket.once('end', bail);\n socket.once('timeout', bail);\n\n self._socket = socket;\n self._tracker = tracker;\n\n // Run any requested setup (such as automatically performing a bind) on\n // socket before signalling successful connection.\n // This setup needs to bypass the request queue since all other activity is\n // blocked until the connection is considered fully established post-setup.\n // Only allow bind/search/starttls for now.\n var basicClient = {\n bind: function bindBypass(name, credentials, controls, callback) {\n return self.bind(name, credentials, controls, callback, true);\n },\n search: function searchBypass(base, options, controls, callback) {\n return self.search(base, options, controls, callback, true);\n },\n starttls: function starttlsBypass(options, controls, callback) {\n return self.starttls(options, controls, callback, true);\n },\n unbind: self.unbind.bind(self)\n };\n vasync.forEachPipeline({\n func: function (f, callback) {\n f(basicClient, callback);\n },\n inputs: self.listeners('setup')\n }, function (err, res) {\n if (err) {\n self.emit('setupError', err);\n }\n cb(err);\n });\n }", "language": "javascript", "code": "function setupClient(cb) {\n cb = once(cb);\n\n // Indicate failure if anything goes awry during setup\n function bail(err) {\n socket.destroy();\n cb(err || new Error('client error during setup'));\n }\n // Work around lack of close event on tls.socket in node < 0.11\n ((socket.socket) ? socket.socket : socket).once('close', bail);\n socket.once('error', bail);\n socket.once('end', bail);\n socket.once('timeout', bail);\n\n self._socket = socket;\n self._tracker = tracker;\n\n // Run any requested setup (such as automatically performing a bind) on\n // socket before signalling successful connection.\n // This setup needs to bypass the request queue since all other activity is\n // blocked until the connection is considered fully established post-setup.\n // Only allow bind/search/starttls for now.\n var basicClient = {\n bind: function bindBypass(name, credentials, controls, callback) {\n return self.bind(name, credentials, controls, callback, true);\n },\n search: function searchBypass(base, options, controls, callback) {\n return self.search(base, options, controls, callback, true);\n },\n starttls: function starttlsBypass(options, controls, callback) {\n return self.starttls(options, controls, callback, true);\n },\n unbind: self.unbind.bind(self)\n };\n vasync.forEachPipeline({\n func: function (f, callback) {\n f(basicClient, callback);\n },\n inputs: self.listeners('setup')\n }, function (err, res) {\n if (err) {\n self.emit('setupError', err);\n }\n cb(err);\n });\n }", "code_tokens": ["function", "setupClient", "(", "cb", ")", "{", "cb", "=", "once", "(", "cb", ")", ";", "function", "bail", "(", "err", ")", "{", "socket", ".", "destroy", "(", ")", ";", "cb", "(", "err", "||", "new", "Error", "(", "'client error during setup'", ")", ")", ";", "}", "(", "(", "socket", ".", "socket", ")", "?", "socket", ".", "socket", ":", "socket", ")", ".", "once", "(", "'close'", ",", "bail", ")", ";", "socket", ".", "once", "(", "'error'", ",", "bail", ")", ";", "socket", ".", "once", "(", "'end'", ",", "bail", ")", ";", "socket", ".", "once", "(", "'timeout'", ",", "bail", ")", ";", "self", ".", "_socket", "=", "socket", ";", "self", ".", "_tracker", "=", "tracker", ";", "var", "basicClient", "=", "{", "bind", ":", "function", "bindBypass", "(", "name", ",", "credentials", ",", "controls", ",", "callback", ")", "{", "return", "self", ".", "bind", "(", "name", ",", "credentials", ",", "controls", ",", "callback", ",", "true", ")", ";", "}", ",", "search", ":", "function", "searchBypass", "(", "base", ",", "options", ",", "controls", ",", "callback", ")", "{", "return", "self", ".", "search", "(", "base", ",", "options", ",", "controls", ",", "callback", ",", "true", ")", ";", "}", ",", "starttls", ":", "function", "starttlsBypass", "(", "options", ",", "controls", ",", "callback", ")", "{", "return", "self", ".", "starttls", "(", "options", ",", "controls", ",", "callback", ",", "true", ")", ";", "}", ",", "unbind", ":", "self", ".", "unbind", ".", "bind", "(", "self", ")", "}", ";", "vasync", ".", "forEachPipeline", "(", "{", "func", ":", "function", "(", "f", ",", "callback", ")", "{", "f", "(", "basicClient", ",", "callback", ")", ";", "}", ",", "inputs", ":", "self", ".", "listeners", "(", "'setup'", ")", "}", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "self", ".", "emit", "(", "'setupError'", ",", "err", ")", ";", "}", "cb", "(", "err", ")", ";", "}", ")", ";", "}"], "docstring": "After connect, register socket event handlers and run any setup actions", "docstring_tokens": ["After", "connect", "register", "socket", "event", "handlers", "and", "run", "any", "setup", "actions"], "sha": "ad451edc18d7768c3ddee1a1dd472d2bbafdae5e", "url": "https://github.com/joyent/node-ldapjs/blob/ad451edc18d7768c3ddee1a1dd472d2bbafdae5e/lib/client/client.js#L1101-L1146", "partition": "test"} {"repo": "bgrins/javascript-astar", "path": "astar.js", "func_name": "Graph", "original_string": "function Graph(gridIn, options) {\n options = options || {};\n this.nodes = [];\n this.diagonal = !!options.diagonal;\n this.grid = [];\n for (var x = 0; x < gridIn.length; x++) {\n this.grid[x] = [];\n\n for (var y = 0, row = gridIn[x]; y < row.length; y++) {\n var node = new GridNode(x, y, row[y]);\n this.grid[x][y] = node;\n this.nodes.push(node);\n }\n }\n this.init();\n}", "language": "javascript", "code": "function Graph(gridIn, options) {\n options = options || {};\n this.nodes = [];\n this.diagonal = !!options.diagonal;\n this.grid = [];\n for (var x = 0; x < gridIn.length; x++) {\n this.grid[x] = [];\n\n for (var y = 0, row = gridIn[x]; y < row.length; y++) {\n var node = new GridNode(x, y, row[y]);\n this.grid[x][y] = node;\n this.nodes.push(node);\n }\n }\n this.init();\n}", "code_tokens": ["function", "Graph", "(", "gridIn", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "nodes", "=", "[", "]", ";", "this", ".", "diagonal", "=", "!", "!", "options", ".", "diagonal", ";", "this", ".", "grid", "=", "[", "]", ";", "for", "(", "var", "x", "=", "0", ";", "x", "<", "gridIn", ".", "length", ";", "x", "++", ")", "{", "this", ".", "grid", "[", "x", "]", "=", "[", "]", ";", "for", "(", "var", "y", "=", "0", ",", "row", "=", "gridIn", "[", "x", "]", ";", "y", "<", "row", ".", "length", ";", "y", "++", ")", "{", "var", "node", "=", "new", "GridNode", "(", "x", ",", "y", ",", "row", "[", "y", "]", ")", ";", "this", ".", "grid", "[", "x", "]", "[", "y", "]", "=", "node", ";", "this", ".", "nodes", ".", "push", "(", "node", ")", ";", "}", "}", "this", ".", "init", "(", ")", ";", "}"], "docstring": "A graph memory structure\n@param {Array} gridIn 2D array of input weights\n@param {Object} [options]\n@param {bool} [options.diagonal] Specifies whether diagonal moves are allowed", "docstring_tokens": ["A", "graph", "memory", "structure"], "sha": "ef5ec96002f87f8ae9854c9a411e6f482d20ff35", "url": "https://github.com/bgrins/javascript-astar/blob/ef5ec96002f87f8ae9854c9a411e6f482d20ff35/astar.js#L157-L172", "partition": "test"} {"repo": "bgrins/javascript-astar", "path": "demo/demo.js", "func_name": "", "original_string": "function(path, i) {\n if(i >= path.length) { // finished removing path, set start positions\n return setStartClass(path, i);\n }\n elementFromNode(path[i]).removeClass(css.active);\n setTimeout(function() {\n removeClass(path, i+1);\n }, timeout*path[i].getCost());\n }", "language": "javascript", "code": "function(path, i) {\n if(i >= path.length) { // finished removing path, set start positions\n return setStartClass(path, i);\n }\n elementFromNode(path[i]).removeClass(css.active);\n setTimeout(function() {\n removeClass(path, i+1);\n }, timeout*path[i].getCost());\n }", "code_tokens": ["function", "(", "path", ",", "i", ")", "{", "if", "(", "i", ">=", "path", ".", "length", ")", "{", "return", "setStartClass", "(", "path", ",", "i", ")", ";", "}", "elementFromNode", "(", "path", "[", "i", "]", ")", ".", "removeClass", "(", "css", ".", "active", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "removeClass", "(", "path", ",", "i", "+", "1", ")", ";", "}", ",", "timeout", "*", "path", "[", "i", "]", ".", "getCost", "(", ")", ")", ";", "}"], "docstring": "will add start class if final", "docstring_tokens": ["will", "add", "start", "class", "if", "final"], "sha": "ef5ec96002f87f8ae9854c9a411e6f482d20ff35", "url": "https://github.com/bgrins/javascript-astar/blob/ef5ec96002f87f8ae9854c9a411e6f482d20ff35/demo/demo.js#L210-L218", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "forEach", "original_string": "function forEach(array, callback) {\n if (array) {\n for (var i = 0, len = array.length; i < len; i++) {\n var result = callback(array[i], i);\n if (result) {\n return result;\n }\n }\n }\n return undefined;\n }", "language": "javascript", "code": "function forEach(array, callback) {\n if (array) {\n for (var i = 0, len = array.length; i < len; i++) {\n var result = callback(array[i], i);\n if (result) {\n return result;\n }\n }\n }\n return undefined;\n }", "code_tokens": ["function", "forEach", "(", "array", ",", "callback", ")", "{", "if", "(", "array", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "array", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "result", "=", "callback", "(", "array", "[", "i", "]", ",", "i", ")", ";", "if", "(", "result", ")", "{", "return", "result", ";", "}", "}", "}", "return", "undefined", ";", "}"], "docstring": "Iterates through 'array' by index and performs the callback on each element of array until the callback\nreturns a truthy value, then returns that value.\nIf no such value is found, the callback is applied to each element of array and undefined is returned.", "docstring_tokens": ["Iterates", "through", "array", "by", "index", "and", "performs", "the", "callback", "on", "each", "element", "of", "array", "until", "the", "callback", "returns", "a", "truthy", "value", "then", "returns", "that", "value", ".", "If", "no", "such", "value", "is", "found", "the", "callback", "is", "applied", "to", "each", "element", "of", "array", "and", "undefined", "is", "returned", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L886-L896", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "arrayToMap", "original_string": "function arrayToMap(array, makeKey) {\n var result = {};\n forEach(array, function (value) {\n result[makeKey(value)] = value;\n });\n return result;\n }", "language": "javascript", "code": "function arrayToMap(array, makeKey) {\n var result = {};\n forEach(array, function (value) {\n result[makeKey(value)] = value;\n });\n return result;\n }", "code_tokens": ["function", "arrayToMap", "(", "array", ",", "makeKey", ")", "{", "var", "result", "=", "{", "}", ";", "forEach", "(", "array", ",", "function", "(", "value", ")", "{", "result", "[", "makeKey", "(", "value", ")", "]", "=", "value", ";", "}", ")", ";", "return", "result", ";", "}"], "docstring": "Creates a map from the elements of an array.\n\n@param array the array of input elements.\n@param makeKey a function that produces a key for a given element.\n\nThis function makes no effort to avoid collisions; if any two elements produce\nthe same key with the given 'makeKey' function, then the element with the higher\nindex in the array will be the one associated with the produced key.", "docstring_tokens": ["Creates", "a", "map", "from", "the", "elements", "of", "an", "array", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L1152-L1158", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "createWatchedFileSet", "original_string": "function createWatchedFileSet(interval, chunkSize) {\n if (interval === void 0) { interval = 2500; }\n if (chunkSize === void 0) { chunkSize = 30; }\n var watchedFiles = [];\n var nextFileToCheck = 0;\n var watchTimer;\n function getModifiedTime(fileName) {\n return _fs.statSync(fileName).mtime;\n }\n function poll(checkedIndex) {\n var watchedFile = watchedFiles[checkedIndex];\n if (!watchedFile) {\n return;\n }\n _fs.stat(watchedFile.fileName, function (err, stats) {\n if (err) {\n watchedFile.callback(watchedFile.fileName);\n }\n else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) {\n watchedFile.mtime = getModifiedTime(watchedFile.fileName);\n watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0);\n }\n });\n }\n // this implementation uses polling and\n // stat due to inconsistencies of fs.watch\n // and efficiency of stat on modern filesystems\n function startWatchTimer() {\n watchTimer = setInterval(function () {\n var count = 0;\n var nextToCheck = nextFileToCheck;\n var firstCheck = -1;\n while ((count < chunkSize) && (nextToCheck !== firstCheck)) {\n poll(nextToCheck);\n if (firstCheck < 0) {\n firstCheck = nextToCheck;\n }\n nextToCheck++;\n if (nextToCheck === watchedFiles.length) {\n nextToCheck = 0;\n }\n count++;\n }\n nextFileToCheck = nextToCheck;\n }, interval);\n }\n function addFile(fileName, callback) {\n var file = {\n fileName: fileName,\n callback: callback,\n mtime: getModifiedTime(fileName)\n };\n watchedFiles.push(file);\n if (watchedFiles.length === 1) {\n startWatchTimer();\n }\n return file;\n }\n function removeFile(file) {\n watchedFiles = ts.copyListRemovingItem(file, watchedFiles);\n }\n return {\n getModifiedTime: getModifiedTime,\n poll: poll,\n startWatchTimer: startWatchTimer,\n addFile: addFile,\n removeFile: removeFile\n };\n }", "language": "javascript", "code": "function createWatchedFileSet(interval, chunkSize) {\n if (interval === void 0) { interval = 2500; }\n if (chunkSize === void 0) { chunkSize = 30; }\n var watchedFiles = [];\n var nextFileToCheck = 0;\n var watchTimer;\n function getModifiedTime(fileName) {\n return _fs.statSync(fileName).mtime;\n }\n function poll(checkedIndex) {\n var watchedFile = watchedFiles[checkedIndex];\n if (!watchedFile) {\n return;\n }\n _fs.stat(watchedFile.fileName, function (err, stats) {\n if (err) {\n watchedFile.callback(watchedFile.fileName);\n }\n else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) {\n watchedFile.mtime = getModifiedTime(watchedFile.fileName);\n watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0);\n }\n });\n }\n // this implementation uses polling and\n // stat due to inconsistencies of fs.watch\n // and efficiency of stat on modern filesystems\n function startWatchTimer() {\n watchTimer = setInterval(function () {\n var count = 0;\n var nextToCheck = nextFileToCheck;\n var firstCheck = -1;\n while ((count < chunkSize) && (nextToCheck !== firstCheck)) {\n poll(nextToCheck);\n if (firstCheck < 0) {\n firstCheck = nextToCheck;\n }\n nextToCheck++;\n if (nextToCheck === watchedFiles.length) {\n nextToCheck = 0;\n }\n count++;\n }\n nextFileToCheck = nextToCheck;\n }, interval);\n }\n function addFile(fileName, callback) {\n var file = {\n fileName: fileName,\n callback: callback,\n mtime: getModifiedTime(fileName)\n };\n watchedFiles.push(file);\n if (watchedFiles.length === 1) {\n startWatchTimer();\n }\n return file;\n }\n function removeFile(file) {\n watchedFiles = ts.copyListRemovingItem(file, watchedFiles);\n }\n return {\n getModifiedTime: getModifiedTime,\n poll: poll,\n startWatchTimer: startWatchTimer,\n addFile: addFile,\n removeFile: removeFile\n };\n }", "code_tokens": ["function", "createWatchedFileSet", "(", "interval", ",", "chunkSize", ")", "{", "if", "(", "interval", "===", "void", "0", ")", "{", "interval", "=", "2500", ";", "}", "if", "(", "chunkSize", "===", "void", "0", ")", "{", "chunkSize", "=", "30", ";", "}", "var", "watchedFiles", "=", "[", "]", ";", "var", "nextFileToCheck", "=", "0", ";", "var", "watchTimer", ";", "function", "getModifiedTime", "(", "fileName", ")", "{", "return", "_fs", ".", "statSync", "(", "fileName", ")", ".", "mtime", ";", "}", "function", "poll", "(", "checkedIndex", ")", "{", "var", "watchedFile", "=", "watchedFiles", "[", "checkedIndex", "]", ";", "if", "(", "!", "watchedFile", ")", "{", "return", ";", "}", "_fs", ".", "stat", "(", "watchedFile", ".", "fileName", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "{", "watchedFile", ".", "callback", "(", "watchedFile", ".", "fileName", ")", ";", "}", "else", "if", "(", "watchedFile", ".", "mtime", ".", "getTime", "(", ")", "!==", "stats", ".", "mtime", ".", "getTime", "(", ")", ")", "{", "watchedFile", ".", "mtime", "=", "getModifiedTime", "(", "watchedFile", ".", "fileName", ")", ";", "watchedFile", ".", "callback", "(", "watchedFile", ".", "fileName", ",", "watchedFile", ".", "mtime", ".", "getTime", "(", ")", "===", "0", ")", ";", "}", "}", ")", ";", "}", "function", "startWatchTimer", "(", ")", "{", "watchTimer", "=", "setInterval", "(", "function", "(", ")", "{", "var", "count", "=", "0", ";", "var", "nextToCheck", "=", "nextFileToCheck", ";", "var", "firstCheck", "=", "-", "1", ";", "while", "(", "(", "count", "<", "chunkSize", ")", "&&", "(", "nextToCheck", "!==", "firstCheck", ")", ")", "{", "poll", "(", "nextToCheck", ")", ";", "if", "(", "firstCheck", "<", "0", ")", "{", "firstCheck", "=", "nextToCheck", ";", "}", "nextToCheck", "++", ";", "if", "(", "nextToCheck", "===", "watchedFiles", ".", "length", ")", "{", "nextToCheck", "=", "0", ";", "}", "count", "++", ";", "}", "nextFileToCheck", "=", "nextToCheck", ";", "}", ",", "interval", ")", ";", "}", "function", "addFile", "(", "fileName", ",", "callback", ")", "{", "var", "file", "=", "{", "fileName", ":", "fileName", ",", "callback", ":", "callback", ",", "mtime", ":", "getModifiedTime", "(", "fileName", ")", "}", ";", "watchedFiles", ".", "push", "(", "file", ")", ";", "if", "(", "watchedFiles", ".", "length", "===", "1", ")", "{", "startWatchTimer", "(", ")", ";", "}", "return", "file", ";", "}", "function", "removeFile", "(", "file", ")", "{", "watchedFiles", "=", "ts", ".", "copyListRemovingItem", "(", "file", ",", "watchedFiles", ")", ";", "}", "return", "{", "getModifiedTime", ":", "getModifiedTime", ",", "poll", ":", "poll", ",", "startWatchTimer", ":", "startWatchTimer", ",", "addFile", ":", "addFile", ",", "removeFile", ":", "removeFile", "}", ";", "}"], "docstring": "average async stat takes about 30 microseconds set chunk size to do 30 files in < 1 millisecond", "docstring_tokens": ["average", "async", "stat", "takes", "about", "30", "microseconds", "set", "chunk", "size", "to", "do", "30", "files", "in", "<", "1", "millisecond"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L1774-L1842", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "startWatchTimer", "original_string": "function startWatchTimer() {\n watchTimer = setInterval(function () {\n var count = 0;\n var nextToCheck = nextFileToCheck;\n var firstCheck = -1;\n while ((count < chunkSize) && (nextToCheck !== firstCheck)) {\n poll(nextToCheck);\n if (firstCheck < 0) {\n firstCheck = nextToCheck;\n }\n nextToCheck++;\n if (nextToCheck === watchedFiles.length) {\n nextToCheck = 0;\n }\n count++;\n }\n nextFileToCheck = nextToCheck;\n }, interval);\n }", "language": "javascript", "code": "function startWatchTimer() {\n watchTimer = setInterval(function () {\n var count = 0;\n var nextToCheck = nextFileToCheck;\n var firstCheck = -1;\n while ((count < chunkSize) && (nextToCheck !== firstCheck)) {\n poll(nextToCheck);\n if (firstCheck < 0) {\n firstCheck = nextToCheck;\n }\n nextToCheck++;\n if (nextToCheck === watchedFiles.length) {\n nextToCheck = 0;\n }\n count++;\n }\n nextFileToCheck = nextToCheck;\n }, interval);\n }", "code_tokens": ["function", "startWatchTimer", "(", ")", "{", "watchTimer", "=", "setInterval", "(", "function", "(", ")", "{", "var", "count", "=", "0", ";", "var", "nextToCheck", "=", "nextFileToCheck", ";", "var", "firstCheck", "=", "-", "1", ";", "while", "(", "(", "count", "<", "chunkSize", ")", "&&", "(", "nextToCheck", "!==", "firstCheck", ")", ")", "{", "poll", "(", "nextToCheck", ")", ";", "if", "(", "firstCheck", "<", "0", ")", "{", "firstCheck", "=", "nextToCheck", ";", "}", "nextToCheck", "++", ";", "if", "(", "nextToCheck", "===", "watchedFiles", ".", "length", ")", "{", "nextToCheck", "=", "0", ";", "}", "count", "++", ";", "}", "nextFileToCheck", "=", "nextToCheck", ";", "}", ",", "interval", ")", ";", "}"], "docstring": "this implementation uses polling and stat due to inconsistencies of fs.watch and efficiency of stat on modern filesystems", "docstring_tokens": ["this", "implementation", "uses", "polling", "and", "stat", "due", "to", "inconsistencies", "of", "fs", ".", "watch", "and", "efficiency", "of", "stat", "on", "modern", "filesystems"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L1801-L1819", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "scanTemplateAndSetTokenValue", "original_string": "function scanTemplateAndSetTokenValue() {\n var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;\n pos++;\n var start = pos;\n var contents = \"\";\n var resultingToken;\n while (true) {\n if (pos >= end) {\n contents += text.substring(start, pos);\n tokenIsUnterminated = true;\n error(ts.Diagnostics.Unterminated_template_literal);\n resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */;\n break;\n }\n var currChar = text.charCodeAt(pos);\n // '`'\n if (currChar === 96 /* backtick */) {\n contents += text.substring(start, pos);\n pos++;\n resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */;\n break;\n }\n // '${'\n if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {\n contents += text.substring(start, pos);\n pos += 2;\n resultingToken = startedWithBacktick ? 12 /* TemplateHead */ : 13 /* TemplateMiddle */;\n break;\n }\n // Escape character\n if (currChar === 92 /* backslash */) {\n contents += text.substring(start, pos);\n contents += scanEscapeSequence();\n start = pos;\n continue;\n }\n // Speculated ECMAScript 6 Spec 11.8.6.1:\n // and LineTerminatorSequences are normalized to for Template Values\n if (currChar === 13 /* carriageReturn */) {\n contents += text.substring(start, pos);\n pos++;\n if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {\n pos++;\n }\n contents += \"\\n\";\n start = pos;\n continue;\n }\n pos++;\n }\n ts.Debug.assert(resultingToken !== undefined);\n tokenValue = contents;\n return resultingToken;\n }", "language": "javascript", "code": "function scanTemplateAndSetTokenValue() {\n var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;\n pos++;\n var start = pos;\n var contents = \"\";\n var resultingToken;\n while (true) {\n if (pos >= end) {\n contents += text.substring(start, pos);\n tokenIsUnterminated = true;\n error(ts.Diagnostics.Unterminated_template_literal);\n resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */;\n break;\n }\n var currChar = text.charCodeAt(pos);\n // '`'\n if (currChar === 96 /* backtick */) {\n contents += text.substring(start, pos);\n pos++;\n resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */;\n break;\n }\n // '${'\n if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {\n contents += text.substring(start, pos);\n pos += 2;\n resultingToken = startedWithBacktick ? 12 /* TemplateHead */ : 13 /* TemplateMiddle */;\n break;\n }\n // Escape character\n if (currChar === 92 /* backslash */) {\n contents += text.substring(start, pos);\n contents += scanEscapeSequence();\n start = pos;\n continue;\n }\n // Speculated ECMAScript 6 Spec 11.8.6.1:\n // and LineTerminatorSequences are normalized to for Template Values\n if (currChar === 13 /* carriageReturn */) {\n contents += text.substring(start, pos);\n pos++;\n if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {\n pos++;\n }\n contents += \"\\n\";\n start = pos;\n continue;\n }\n pos++;\n }\n ts.Debug.assert(resultingToken !== undefined);\n tokenValue = contents;\n return resultingToken;\n }", "code_tokens": ["function", "scanTemplateAndSetTokenValue", "(", ")", "{", "var", "startedWithBacktick", "=", "text", ".", "charCodeAt", "(", "pos", ")", "===", "96", ";", "pos", "++", ";", "var", "start", "=", "pos", ";", "var", "contents", "=", "\"\"", ";", "var", "resultingToken", ";", "while", "(", "true", ")", "{", "if", "(", "pos", ">=", "end", ")", "{", "contents", "+=", "text", ".", "substring", "(", "start", ",", "pos", ")", ";", "tokenIsUnterminated", "=", "true", ";", "error", "(", "ts", ".", "Diagnostics", ".", "Unterminated_template_literal", ")", ";", "resultingToken", "=", "startedWithBacktick", "?", "11", ":", "14", ";", "break", ";", "}", "var", "currChar", "=", "text", ".", "charCodeAt", "(", "pos", ")", ";", "if", "(", "currChar", "===", "96", ")", "{", "contents", "+=", "text", ".", "substring", "(", "start", ",", "pos", ")", ";", "pos", "++", ";", "resultingToken", "=", "startedWithBacktick", "?", "11", ":", "14", ";", "break", ";", "}", "if", "(", "currChar", "===", "36", "&&", "pos", "+", "1", "<", "end", "&&", "text", ".", "charCodeAt", "(", "pos", "+", "1", ")", "===", "123", ")", "{", "contents", "+=", "text", ".", "substring", "(", "start", ",", "pos", ")", ";", "pos", "+=", "2", ";", "resultingToken", "=", "startedWithBacktick", "?", "12", ":", "13", ";", "break", ";", "}", "if", "(", "currChar", "===", "92", ")", "{", "contents", "+=", "text", ".", "substring", "(", "start", ",", "pos", ")", ";", "contents", "+=", "scanEscapeSequence", "(", ")", ";", "start", "=", "pos", ";", "continue", ";", "}", "if", "(", "currChar", "===", "13", ")", "{", "contents", "+=", "text", ".", "substring", "(", "start", ",", "pos", ")", ";", "pos", "++", ";", "if", "(", "pos", "<", "end", "&&", "text", ".", "charCodeAt", "(", "pos", ")", "===", "10", ")", "{", "pos", "++", ";", "}", "contents", "+=", "\"\\n\"", ";", "\\n", "start", "=", "pos", ";", "}", "continue", ";", "}", "pos", "++", ";", "ts", ".", "Debug", ".", "assert", "(", "resultingToken", "!==", "undefined", ")", ";", "tokenValue", "=", "contents", ";", "}"], "docstring": "Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or\na literal component of a TemplateExpression.", "docstring_tokens": ["Sets", "the", "current", "tokenValue", "and", "returns", "a", "NoSubstitutionTemplateLiteral", "or", "a", "literal", "component", "of", "a", "TemplateExpression", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L3408-L3461", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "utf16EncodeAsString", "original_string": "function utf16EncodeAsString(codePoint) {\n ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);\n if (codePoint <= 65535) {\n return String.fromCharCode(codePoint);\n }\n var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;\n var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;\n return String.fromCharCode(codeUnit1, codeUnit2);\n }", "language": "javascript", "code": "function utf16EncodeAsString(codePoint) {\n ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);\n if (codePoint <= 65535) {\n return String.fromCharCode(codePoint);\n }\n var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;\n var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;\n return String.fromCharCode(codeUnit1, codeUnit2);\n }", "code_tokens": ["function", "utf16EncodeAsString", "(", "codePoint", ")", "{", "ts", ".", "Debug", ".", "assert", "(", "0x0", "<=", "codePoint", "&&", "codePoint", "<=", "0x10FFFF", ")", ";", "if", "(", "codePoint", "<=", "65535", ")", "{", "return", "String", ".", "fromCharCode", "(", "codePoint", ")", ";", "}", "var", "codeUnit1", "=", "Math", ".", "floor", "(", "(", "codePoint", "-", "65536", ")", "/", "1024", ")", "+", "0xD800", ";", "var", "codeUnit2", "=", "(", "(", "codePoint", "-", "65536", ")", "%", "1024", ")", "+", "0xDC00", ";", "return", "String", ".", "fromCharCode", "(", "codeUnit1", ",", "codeUnit2", ")", ";", "}"], "docstring": "Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.", "docstring_tokens": ["Derived", "from", "the", "10", ".", "1", ".", "1", "UTF16Encoding", "of", "the", "ES6", "Spec", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L3555-L3563", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "peekUnicodeEscape", "original_string": "function peekUnicodeEscape() {\n if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {\n var start_1 = pos;\n pos += 2;\n var value = scanExactNumberOfHexDigits(4);\n pos = start_1;\n return value;\n }\n return -1;\n }", "language": "javascript", "code": "function peekUnicodeEscape() {\n if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {\n var start_1 = pos;\n pos += 2;\n var value = scanExactNumberOfHexDigits(4);\n pos = start_1;\n return value;\n }\n return -1;\n }", "code_tokens": ["function", "peekUnicodeEscape", "(", ")", "{", "if", "(", "pos", "+", "5", "<", "end", "&&", "text", ".", "charCodeAt", "(", "pos", "+", "1", ")", "===", "117", ")", "{", "var", "start_1", "=", "pos", ";", "pos", "+=", "2", ";", "var", "value", "=", "scanExactNumberOfHexDigits", "(", "4", ")", ";", "pos", "=", "start_1", ";", "return", "value", ";", "}", "return", "-", "1", ";", "}"], "docstring": "Current character is known to be a backslash. Check for Unicode escape of the form '\\uXXXX' and return code point value if valid Unicode escape is found. Otherwise return -1.", "docstring_tokens": ["Current", "character", "is", "known", "to", "be", "a", "backslash", ".", "Check", "for", "Unicode", "escape", "of", "the", "form", "\\", "uXXXX", "and", "return", "code", "point", "value", "if", "valid", "Unicode", "escape", "is", "found", ".", "Otherwise", "return", "-", "1", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L3566-L3575", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "scanJsxIdentifier", "original_string": "function scanJsxIdentifier() {\n if (tokenIsIdentifierOrKeyword(token)) {\n var firstCharPosition = pos;\n while (pos < end) {\n var ch = text.charCodeAt(pos);\n if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) {\n pos++;\n }\n else {\n break;\n }\n }\n tokenValue += text.substr(firstCharPosition, pos - firstCharPosition);\n }\n return token;\n }", "language": "javascript", "code": "function scanJsxIdentifier() {\n if (tokenIsIdentifierOrKeyword(token)) {\n var firstCharPosition = pos;\n while (pos < end) {\n var ch = text.charCodeAt(pos);\n if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) {\n pos++;\n }\n else {\n break;\n }\n }\n tokenValue += text.substr(firstCharPosition, pos - firstCharPosition);\n }\n return token;\n }", "code_tokens": ["function", "scanJsxIdentifier", "(", ")", "{", "if", "(", "tokenIsIdentifierOrKeyword", "(", "token", ")", ")", "{", "var", "firstCharPosition", "=", "pos", ";", "while", "(", "pos", "<", "end", ")", "{", "var", "ch", "=", "text", ".", "charCodeAt", "(", "pos", ")", ";", "if", "(", "ch", "===", "45", "||", "(", "(", "firstCharPosition", "===", "pos", ")", "?", "isIdentifierStart", "(", "ch", ",", "languageVersion", ")", ":", "isIdentifierPart", "(", "ch", ",", "languageVersion", ")", ")", ")", "{", "pos", "++", ";", "}", "else", "{", "break", ";", "}", "}", "tokenValue", "+=", "text", ".", "substr", "(", "firstCharPosition", ",", "pos", "-", "firstCharPosition", ")", ";", "}", "return", "token", ";", "}"], "docstring": "Scans a JSX identifier; these differ from normal identifiers in that they allow dashes", "docstring_tokens": ["Scans", "a", "JSX", "identifier", ";", "these", "differ", "from", "normal", "identifiers", "in", "that", "they", "allow", "dashes"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L4087-L4102", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getDeclarationName", "original_string": "function getDeclarationName(node) {\n if (node.name) {\n if (node.kind === 218 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) {\n return \"\\\"\" + node.name.text + \"\\\"\";\n }\n if (node.name.kind === 136 /* ComputedPropertyName */) {\n var nameExpression = node.name.expression;\n ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));\n return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text);\n }\n return node.name.text;\n }\n switch (node.kind) {\n case 144 /* Constructor */:\n return \"__constructor\";\n case 152 /* FunctionType */:\n case 147 /* CallSignature */:\n return \"__call\";\n case 153 /* ConstructorType */:\n case 148 /* ConstructSignature */:\n return \"__new\";\n case 149 /* IndexSignature */:\n return \"__index\";\n case 228 /* ExportDeclaration */:\n return \"__export\";\n case 227 /* ExportAssignment */:\n return node.isExportEquals ? \"export=\" : \"default\";\n case 213 /* FunctionDeclaration */:\n case 214 /* ClassDeclaration */:\n return node.flags & 1024 /* Default */ ? \"default\" : undefined;\n }\n }", "language": "javascript", "code": "function getDeclarationName(node) {\n if (node.name) {\n if (node.kind === 218 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) {\n return \"\\\"\" + node.name.text + \"\\\"\";\n }\n if (node.name.kind === 136 /* ComputedPropertyName */) {\n var nameExpression = node.name.expression;\n ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));\n return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text);\n }\n return node.name.text;\n }\n switch (node.kind) {\n case 144 /* Constructor */:\n return \"__constructor\";\n case 152 /* FunctionType */:\n case 147 /* CallSignature */:\n return \"__call\";\n case 153 /* ConstructorType */:\n case 148 /* ConstructSignature */:\n return \"__new\";\n case 149 /* IndexSignature */:\n return \"__index\";\n case 228 /* ExportDeclaration */:\n return \"__export\";\n case 227 /* ExportAssignment */:\n return node.isExportEquals ? \"export=\" : \"default\";\n case 213 /* FunctionDeclaration */:\n case 214 /* ClassDeclaration */:\n return node.flags & 1024 /* Default */ ? \"default\" : undefined;\n }\n }", "code_tokens": ["function", "getDeclarationName", "(", "node", ")", "{", "if", "(", "node", ".", "name", ")", "{", "if", "(", "node", ".", "kind", "===", "218", "&&", "node", ".", "name", ".", "kind", "===", "9", ")", "{", "return", "\"\\\"\"", "+", "\\\"", "+", "node", ".", "name", ".", "text", ";", "}", "\"\\\"\"", "\\\"", "}", "if", "(", "node", ".", "name", ".", "kind", "===", "136", ")", "{", "var", "nameExpression", "=", "node", ".", "name", ".", "expression", ";", "ts", ".", "Debug", ".", "assert", "(", "ts", ".", "isWellKnownSymbolSyntactically", "(", "nameExpression", ")", ")", ";", "return", "ts", ".", "getPropertyNameForKnownSymbolName", "(", "nameExpression", ".", "name", ".", "text", ")", ";", "}", "}"], "docstring": "Should not be called on a declaration with a computed property name, unless it is a well known Symbol.", "docstring_tokens": ["Should", "not", "be", "called", "on", "a", "declaration", "with", "a", "computed", "property", "name", "unless", "it", "is", "a", "well", "known", "Symbol", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L4276-L4307", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "bindChildren", "original_string": "function bindChildren(node) {\n // Before we recurse into a node's chilren, we first save the existing parent, container\n // and block-container. Then after we pop out of processing the children, we restore\n // these saved values.\n var saveParent = parent;\n var saveContainer = container;\n var savedBlockScopeContainer = blockScopeContainer;\n // This node will now be set as the parent of all of its children as we recurse into them.\n parent = node;\n // Depending on what kind of node this is, we may have to adjust the current container\n // and block-container. If the current node is a container, then it is automatically\n // considered the current block-container as well. Also, for containers that we know\n // may contain locals, we proactively initialize the .locals field. We do this because\n // it's highly likely that the .locals will be needed to place some child in (for example,\n // a parameter, or variable declaration).\n //\n // However, we do not proactively create the .locals for block-containers because it's\n // totally normal and common for block-containers to never actually have a block-scoped\n // variable in them. We don't want to end up allocating an object for every 'block' we\n // run into when most of them won't be necessary.\n //\n // Finally, if this is a block-container, then we clear out any existing .locals object\n // it may contain within it. This happens in incremental scenarios. Because we can be\n // reusing a node from a previous compilation, that node may have had 'locals' created\n // for it. We must clear this so we don't accidently move any stale data forward from\n // a previous compilation.\n var containerFlags = getContainerFlags(node);\n if (containerFlags & 1 /* IsContainer */) {\n container = blockScopeContainer = node;\n if (containerFlags & 4 /* HasLocals */) {\n container.locals = {};\n }\n addToContainerChain(container);\n }\n else if (containerFlags & 2 /* IsBlockScopedContainer */) {\n blockScopeContainer = node;\n blockScopeContainer.locals = undefined;\n }\n if (node.kind === 215 /* InterfaceDeclaration */) {\n seenThisKeyword = false;\n ts.forEachChild(node, bind);\n node.flags = seenThisKeyword ? node.flags | 524288 /* ContainsThis */ : node.flags & ~524288 /* ContainsThis */;\n }\n else {\n ts.forEachChild(node, bind);\n }\n container = saveContainer;\n parent = saveParent;\n blockScopeContainer = savedBlockScopeContainer;\n }", "language": "javascript", "code": "function bindChildren(node) {\n // Before we recurse into a node's chilren, we first save the existing parent, container\n // and block-container. Then after we pop out of processing the children, we restore\n // these saved values.\n var saveParent = parent;\n var saveContainer = container;\n var savedBlockScopeContainer = blockScopeContainer;\n // This node will now be set as the parent of all of its children as we recurse into them.\n parent = node;\n // Depending on what kind of node this is, we may have to adjust the current container\n // and block-container. If the current node is a container, then it is automatically\n // considered the current block-container as well. Also, for containers that we know\n // may contain locals, we proactively initialize the .locals field. We do this because\n // it's highly likely that the .locals will be needed to place some child in (for example,\n // a parameter, or variable declaration).\n //\n // However, we do not proactively create the .locals for block-containers because it's\n // totally normal and common for block-containers to never actually have a block-scoped\n // variable in them. We don't want to end up allocating an object for every 'block' we\n // run into when most of them won't be necessary.\n //\n // Finally, if this is a block-container, then we clear out any existing .locals object\n // it may contain within it. This happens in incremental scenarios. Because we can be\n // reusing a node from a previous compilation, that node may have had 'locals' created\n // for it. We must clear this so we don't accidently move any stale data forward from\n // a previous compilation.\n var containerFlags = getContainerFlags(node);\n if (containerFlags & 1 /* IsContainer */) {\n container = blockScopeContainer = node;\n if (containerFlags & 4 /* HasLocals */) {\n container.locals = {};\n }\n addToContainerChain(container);\n }\n else if (containerFlags & 2 /* IsBlockScopedContainer */) {\n blockScopeContainer = node;\n blockScopeContainer.locals = undefined;\n }\n if (node.kind === 215 /* InterfaceDeclaration */) {\n seenThisKeyword = false;\n ts.forEachChild(node, bind);\n node.flags = seenThisKeyword ? node.flags | 524288 /* ContainsThis */ : node.flags & ~524288 /* ContainsThis */;\n }\n else {\n ts.forEachChild(node, bind);\n }\n container = saveContainer;\n parent = saveParent;\n blockScopeContainer = savedBlockScopeContainer;\n }", "code_tokens": ["function", "bindChildren", "(", "node", ")", "{", "var", "saveParent", "=", "parent", ";", "var", "saveContainer", "=", "container", ";", "var", "savedBlockScopeContainer", "=", "blockScopeContainer", ";", "parent", "=", "node", ";", "var", "containerFlags", "=", "getContainerFlags", "(", "node", ")", ";", "if", "(", "containerFlags", "&", "1", ")", "{", "container", "=", "blockScopeContainer", "=", "node", ";", "if", "(", "containerFlags", "&", "4", ")", "{", "container", ".", "locals", "=", "{", "}", ";", "}", "addToContainerChain", "(", "container", ")", ";", "}", "else", "if", "(", "containerFlags", "&", "2", ")", "{", "blockScopeContainer", "=", "node", ";", "blockScopeContainer", ".", "locals", "=", "undefined", ";", "}", "if", "(", "node", ".", "kind", "===", "215", ")", "{", "seenThisKeyword", "=", "false", ";", "ts", ".", "forEachChild", "(", "node", ",", "bind", ")", ";", "node", ".", "flags", "=", "seenThisKeyword", "?", "node", ".", "flags", "|", "524288", ":", "node", ".", "flags", "&", "~", "524288", ";", "}", "else", "{", "ts", ".", "forEachChild", "(", "node", ",", "bind", ")", ";", "}", "container", "=", "saveContainer", ";", "parent", "=", "saveParent", ";", "blockScopeContainer", "=", "savedBlockScopeContainer", ";", "}"], "docstring": "All container nodes are kept on a linked list in declaration order. This list is used by the getLocalNameOfContainer function in the type checker to validate that the local name used for a container is unique.", "docstring_tokens": ["All", "container", "nodes", "are", "kept", "on", "a", "linked", "list", "in", "declaration", "order", ".", "This", "list", "is", "used", "by", "the", "getLocalNameOfContainer", "function", "in", "the", "type", "checker", "to", "validate", "that", "the", "local", "name", "used", "for", "a", "container", "is", "unique", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L4417-L4466", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "nodePosToString", "original_string": "function nodePosToString(node) {\n var file = getSourceFileOfNode(node);\n var loc = ts.getLineAndCharacterOfPosition(file, node.pos);\n return file.fileName + \"(\" + (loc.line + 1) + \",\" + (loc.character + 1) + \")\";\n }", "language": "javascript", "code": "function nodePosToString(node) {\n var file = getSourceFileOfNode(node);\n var loc = ts.getLineAndCharacterOfPosition(file, node.pos);\n return file.fileName + \"(\" + (loc.line + 1) + \",\" + (loc.character + 1) + \")\";\n }", "code_tokens": ["function", "nodePosToString", "(", "node", ")", "{", "var", "file", "=", "getSourceFileOfNode", "(", "node", ")", ";", "var", "loc", "=", "ts", ".", "getLineAndCharacterOfPosition", "(", "file", ",", "node", ".", "pos", ")", ";", "return", "file", ".", "fileName", "+", "\"(\"", "+", "(", "loc", ".", "line", "+", "1", ")", "+", "\",\"", "+", "(", "loc", ".", "character", "+", "1", ")", "+", "\")\"", ";", "}"], "docstring": "This is a useful function for debugging purposes.", "docstring_tokens": ["This", "is", "a", "useful", "function", "for", "debugging", "purposes", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L5243-L5247", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "unescapeIdentifier", "original_string": "function unescapeIdentifier(identifier) {\n return identifier.length >= 3 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ && identifier.charCodeAt(2) === 95 /* _ */ ? identifier.substr(1) : identifier;\n }", "language": "javascript", "code": "function unescapeIdentifier(identifier) {\n return identifier.length >= 3 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ && identifier.charCodeAt(2) === 95 /* _ */ ? identifier.substr(1) : identifier;\n }", "code_tokens": ["function", "unescapeIdentifier", "(", "identifier", ")", "{", "return", "identifier", ".", "length", ">=", "3", "&&", "identifier", ".", "charCodeAt", "(", "0", ")", "===", "95", "&&", "identifier", ".", "charCodeAt", "(", "1", ")", "===", "95", "&&", "identifier", ".", "charCodeAt", "(", "2", ")", "===", "95", "?", "identifier", ".", "substr", "(", "1", ")", ":", "identifier", ";", "}"], "docstring": "Remove extra underscore from escaped identifier", "docstring_tokens": ["Remove", "extra", "underscore", "from", "escaped", "identifier"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L5319-L5321", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getEnclosingBlockScopeContainer", "original_string": "function getEnclosingBlockScopeContainer(node) {\n var current = node.parent;\n while (current) {\n if (isFunctionLike(current)) {\n return current;\n }\n switch (current.kind) {\n case 248 /* SourceFile */:\n case 220 /* CaseBlock */:\n case 244 /* CatchClause */:\n case 218 /* ModuleDeclaration */:\n case 199 /* ForStatement */:\n case 200 /* ForInStatement */:\n case 201 /* ForOfStatement */:\n return current;\n case 192 /* Block */:\n // function block is not considered block-scope container\n // see comment in binder.ts: bind(...), case for SyntaxKind.Block\n if (!isFunctionLike(current.parent)) {\n return current;\n }\n }\n current = current.parent;\n }\n }", "language": "javascript", "code": "function getEnclosingBlockScopeContainer(node) {\n var current = node.parent;\n while (current) {\n if (isFunctionLike(current)) {\n return current;\n }\n switch (current.kind) {\n case 248 /* SourceFile */:\n case 220 /* CaseBlock */:\n case 244 /* CatchClause */:\n case 218 /* ModuleDeclaration */:\n case 199 /* ForStatement */:\n case 200 /* ForInStatement */:\n case 201 /* ForOfStatement */:\n return current;\n case 192 /* Block */:\n // function block is not considered block-scope container\n // see comment in binder.ts: bind(...), case for SyntaxKind.Block\n if (!isFunctionLike(current.parent)) {\n return current;\n }\n }\n current = current.parent;\n }\n }", "code_tokens": ["function", "getEnclosingBlockScopeContainer", "(", "node", ")", "{", "var", "current", "=", "node", ".", "parent", ";", "while", "(", "current", ")", "{", "if", "(", "isFunctionLike", "(", "current", ")", ")", "{", "return", "current", ";", "}", "switch", "(", "current", ".", "kind", ")", "{", "case", "248", ":", "case", "220", ":", "case", "244", ":", "case", "218", ":", "case", "199", ":", "case", "200", ":", "case", "201", ":", "return", "current", ";", "case", "192", ":", "if", "(", "!", "isFunctionLike", "(", "current", ".", "parent", ")", ")", "{", "return", "current", ";", "}", "}", "current", "=", "current", ".", "parent", ";", "}", "}"], "docstring": "Gets the nearest enclosing block scope container that has the provided node as a descendant, that is not the provided node.", "docstring_tokens": ["Gets", "the", "nearest", "enclosing", "block", "scope", "container", "that", "has", "the", "provided", "node", "as", "a", "descendant", "that", "is", "not", "the", "provided", "node", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L5336-L5360", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "isDeclarationName", "original_string": "function isDeclarationName(name) {\n if (name.kind !== 69 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) {\n return false;\n }\n var parent = name.parent;\n if (parent.kind === 226 /* ImportSpecifier */ || parent.kind === 230 /* ExportSpecifier */) {\n if (parent.propertyName) {\n return true;\n }\n }\n if (isDeclaration(parent)) {\n return parent.name === name;\n }\n return false;\n }", "language": "javascript", "code": "function isDeclarationName(name) {\n if (name.kind !== 69 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) {\n return false;\n }\n var parent = name.parent;\n if (parent.kind === 226 /* ImportSpecifier */ || parent.kind === 230 /* ExportSpecifier */) {\n if (parent.propertyName) {\n return true;\n }\n }\n if (isDeclaration(parent)) {\n return parent.name === name;\n }\n return false;\n }", "code_tokens": ["function", "isDeclarationName", "(", "name", ")", "{", "if", "(", "name", ".", "kind", "!==", "69", "&&", "name", ".", "kind", "!==", "9", "&&", "name", ".", "kind", "!==", "8", ")", "{", "return", "false", ";", "}", "var", "parent", "=", "name", ".", "parent", ";", "if", "(", "parent", ".", "kind", "===", "226", "||", "parent", ".", "kind", "===", "230", ")", "{", "if", "(", "parent", ".", "propertyName", ")", "{", "return", "true", ";", "}", "}", "if", "(", "isDeclaration", "(", "parent", ")", ")", "{", "return", "parent", ".", "name", "===", "name", ";", "}", "return", "false", ";", "}"], "docstring": "True if the given identifier, string literal, or number literal is the name of a declaration node", "docstring_tokens": ["True", "if", "the", "given", "identifier", "string", "literal", "or", "number", "literal", "is", "the", "name", "of", "a", "declaration", "node"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L6291-L6305", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "isIdentifierName", "original_string": "function isIdentifierName(node) {\n var parent = node.parent;\n switch (parent.kind) {\n case 141 /* PropertyDeclaration */:\n case 140 /* PropertySignature */:\n case 143 /* MethodDeclaration */:\n case 142 /* MethodSignature */:\n case 145 /* GetAccessor */:\n case 146 /* SetAccessor */:\n case 247 /* EnumMember */:\n case 245 /* PropertyAssignment */:\n case 166 /* PropertyAccessExpression */:\n // Name in member declaration or property name in property access\n return parent.name === node;\n case 135 /* QualifiedName */:\n // Name on right hand side of dot in a type query\n if (parent.right === node) {\n while (parent.kind === 135 /* QualifiedName */) {\n parent = parent.parent;\n }\n return parent.kind === 154 /* TypeQuery */;\n }\n return false;\n case 163 /* BindingElement */:\n case 226 /* ImportSpecifier */:\n // Property name in binding element or import specifier\n return parent.propertyName === node;\n case 230 /* ExportSpecifier */:\n // Any name in an export specifier\n return true;\n }\n return false;\n }", "language": "javascript", "code": "function isIdentifierName(node) {\n var parent = node.parent;\n switch (parent.kind) {\n case 141 /* PropertyDeclaration */:\n case 140 /* PropertySignature */:\n case 143 /* MethodDeclaration */:\n case 142 /* MethodSignature */:\n case 145 /* GetAccessor */:\n case 146 /* SetAccessor */:\n case 247 /* EnumMember */:\n case 245 /* PropertyAssignment */:\n case 166 /* PropertyAccessExpression */:\n // Name in member declaration or property name in property access\n return parent.name === node;\n case 135 /* QualifiedName */:\n // Name on right hand side of dot in a type query\n if (parent.right === node) {\n while (parent.kind === 135 /* QualifiedName */) {\n parent = parent.parent;\n }\n return parent.kind === 154 /* TypeQuery */;\n }\n return false;\n case 163 /* BindingElement */:\n case 226 /* ImportSpecifier */:\n // Property name in binding element or import specifier\n return parent.propertyName === node;\n case 230 /* ExportSpecifier */:\n // Any name in an export specifier\n return true;\n }\n return false;\n }", "code_tokens": ["function", "isIdentifierName", "(", "node", ")", "{", "var", "parent", "=", "node", ".", "parent", ";", "switch", "(", "parent", ".", "kind", ")", "{", "case", "141", ":", "case", "140", ":", "case", "143", ":", "case", "142", ":", "case", "145", ":", "case", "146", ":", "case", "247", ":", "case", "245", ":", "case", "166", ":", "return", "parent", ".", "name", "===", "node", ";", "case", "135", ":", "if", "(", "parent", ".", "right", "===", "node", ")", "{", "while", "(", "parent", ".", "kind", "===", "135", ")", "{", "parent", "=", "parent", ".", "parent", ";", "}", "return", "parent", ".", "kind", "===", "154", ";", "}", "return", "false", ";", "case", "163", ":", "case", "226", ":", "return", "parent", ".", "propertyName", "===", "node", ";", "case", "230", ":", "return", "true", ";", "}", "return", "false", ";", "}"], "docstring": "Return true if the given identifier is classified as an IdentifierName", "docstring_tokens": ["Return", "true", "if", "the", "given", "identifier", "is", "classified", "as", "an", "IdentifierName"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L6308-L6340", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getExpandedCharCodes", "original_string": "function getExpandedCharCodes(input) {\n var output = [];\n var length = input.length;\n for (var i = 0; i < length; i++) {\n var charCode = input.charCodeAt(i);\n // handel utf8\n if (charCode < 0x80) {\n output.push(charCode);\n }\n else if (charCode < 0x800) {\n output.push((charCode >> 6) | 192);\n output.push((charCode & 63) | 128);\n }\n else if (charCode < 0x10000) {\n output.push((charCode >> 12) | 224);\n output.push(((charCode >> 6) & 63) | 128);\n output.push((charCode & 63) | 128);\n }\n else if (charCode < 0x20000) {\n output.push((charCode >> 18) | 240);\n output.push(((charCode >> 12) & 63) | 128);\n output.push(((charCode >> 6) & 63) | 128);\n output.push((charCode & 63) | 128);\n }\n else {\n ts.Debug.assert(false, \"Unexpected code point\");\n }\n }\n return output;\n }", "language": "javascript", "code": "function getExpandedCharCodes(input) {\n var output = [];\n var length = input.length;\n for (var i = 0; i < length; i++) {\n var charCode = input.charCodeAt(i);\n // handel utf8\n if (charCode < 0x80) {\n output.push(charCode);\n }\n else if (charCode < 0x800) {\n output.push((charCode >> 6) | 192);\n output.push((charCode & 63) | 128);\n }\n else if (charCode < 0x10000) {\n output.push((charCode >> 12) | 224);\n output.push(((charCode >> 6) & 63) | 128);\n output.push((charCode & 63) | 128);\n }\n else if (charCode < 0x20000) {\n output.push((charCode >> 18) | 240);\n output.push(((charCode >> 12) & 63) | 128);\n output.push(((charCode >> 6) & 63) | 128);\n output.push((charCode & 63) | 128);\n }\n else {\n ts.Debug.assert(false, \"Unexpected code point\");\n }\n }\n return output;\n }", "code_tokens": ["function", "getExpandedCharCodes", "(", "input", ")", "{", "var", "output", "=", "[", "]", ";", "var", "length", "=", "input", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "var", "charCode", "=", "input", ".", "charCodeAt", "(", "i", ")", ";", "if", "(", "charCode", "<", "0x80", ")", "{", "output", ".", "push", "(", "charCode", ")", ";", "}", "else", "if", "(", "charCode", "<", "0x800", ")", "{", "output", ".", "push", "(", "(", "charCode", ">>", "6", ")", "|", "192", ")", ";", "output", ".", "push", "(", "(", "charCode", "&", "63", ")", "|", "128", ")", ";", "}", "else", "if", "(", "charCode", "<", "0x10000", ")", "{", "output", ".", "push", "(", "(", "charCode", ">>", "12", ")", "|", "224", ")", ";", "output", ".", "push", "(", "(", "(", "charCode", ">>", "6", ")", "&", "63", ")", "|", "128", ")", ";", "output", ".", "push", "(", "(", "charCode", "&", "63", ")", "|", "128", ")", ";", "}", "else", "if", "(", "charCode", "<", "0x20000", ")", "{", "output", ".", "push", "(", "(", "charCode", ">>", "18", ")", "|", "240", ")", ";", "output", ".", "push", "(", "(", "(", "charCode", ">>", "12", ")", "&", "63", ")", "|", "128", ")", ";", "output", ".", "push", "(", "(", "(", "charCode", ">>", "6", ")", "&", "63", ")", "|", "128", ")", ";", "output", ".", "push", "(", "(", "charCode", "&", "63", ")", "|", "128", ")", ";", "}", "else", "{", "ts", ".", "Debug", ".", "assert", "(", "false", ",", "\"Unexpected code point\"", ")", ";", "}", "}", "return", "output", ";", "}"], "docstring": "Replace each instance of non-ascii characters by one, two, three, or four escape sequences\nrepresenting the UTF-8 encoding of the character, and return the expanded char code list.", "docstring_tokens": ["Replace", "each", "instance", "of", "non", "-", "ascii", "characters", "by", "one", "two", "three", "or", "four", "escape", "sequences", "representing", "the", "UTF", "-", "8", "encoding", "of", "the", "character", "and", "return", "the", "expanded", "char", "code", "list", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L7085-L7114", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "textSpanContainsTextSpan", "original_string": "function textSpanContainsTextSpan(span, other) {\n return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);\n }", "language": "javascript", "code": "function textSpanContainsTextSpan(span, other) {\n return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);\n }", "code_tokens": ["function", "textSpanContainsTextSpan", "(", "span", ",", "other", ")", "{", "return", "other", ".", "start", ">=", "span", ".", "start", "&&", "textSpanEnd", "(", "other", ")", "<=", "textSpanEnd", "(", "span", ")", ";", "}"], "docstring": "Returns true if 'span' contains 'other'.", "docstring_tokens": ["Returns", "true", "if", "span", "contains", "other", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L7182-L7184", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "isListTerminator", "original_string": "function isListTerminator(kind) {\n if (token === 1 /* EndOfFileToken */) {\n // Being at the end of the file ends all lists.\n return true;\n }\n switch (kind) {\n case 1 /* BlockStatements */:\n case 2 /* SwitchClauses */:\n case 4 /* TypeMembers */:\n case 5 /* ClassMembers */:\n case 6 /* EnumMembers */:\n case 12 /* ObjectLiteralMembers */:\n case 9 /* ObjectBindingElements */:\n case 21 /* ImportOrExportSpecifiers */:\n return token === 16 /* CloseBraceToken */;\n case 3 /* SwitchClauseStatements */:\n return token === 16 /* CloseBraceToken */ || token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */;\n case 7 /* HeritageClauseElement */:\n return token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */;\n case 8 /* VariableDeclarations */:\n return isVariableDeclaratorListTerminator();\n case 17 /* TypeParameters */:\n // Tokens other than '>' are here for better error recovery\n return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */ || token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */;\n case 11 /* ArgumentExpressions */:\n // Tokens other than ')' are here for better error recovery\n return token === 18 /* CloseParenToken */ || token === 23 /* SemicolonToken */;\n case 15 /* ArrayLiteralMembers */:\n case 19 /* TupleElementTypes */:\n case 10 /* ArrayBindingElements */:\n return token === 20 /* CloseBracketToken */;\n case 16 /* Parameters */:\n // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery\n return token === 18 /* CloseParenToken */ || token === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;\n case 18 /* TypeArguments */:\n // Tokens other than '>' are here for better error recovery\n return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */;\n case 20 /* HeritageClauses */:\n return token === 15 /* OpenBraceToken */ || token === 16 /* CloseBraceToken */;\n case 13 /* JsxAttributes */:\n return token === 27 /* GreaterThanToken */ || token === 39 /* SlashToken */;\n case 14 /* JsxChildren */:\n return token === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash);\n case 22 /* JSDocFunctionParameters */:\n return token === 18 /* CloseParenToken */ || token === 54 /* ColonToken */ || token === 16 /* CloseBraceToken */;\n case 23 /* JSDocTypeArguments */:\n return token === 27 /* GreaterThanToken */ || token === 16 /* CloseBraceToken */;\n case 25 /* JSDocTupleTypes */:\n return token === 20 /* CloseBracketToken */ || token === 16 /* CloseBraceToken */;\n case 24 /* JSDocRecordMembers */:\n return token === 16 /* CloseBraceToken */;\n }\n }", "language": "javascript", "code": "function isListTerminator(kind) {\n if (token === 1 /* EndOfFileToken */) {\n // Being at the end of the file ends all lists.\n return true;\n }\n switch (kind) {\n case 1 /* BlockStatements */:\n case 2 /* SwitchClauses */:\n case 4 /* TypeMembers */:\n case 5 /* ClassMembers */:\n case 6 /* EnumMembers */:\n case 12 /* ObjectLiteralMembers */:\n case 9 /* ObjectBindingElements */:\n case 21 /* ImportOrExportSpecifiers */:\n return token === 16 /* CloseBraceToken */;\n case 3 /* SwitchClauseStatements */:\n return token === 16 /* CloseBraceToken */ || token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */;\n case 7 /* HeritageClauseElement */:\n return token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */;\n case 8 /* VariableDeclarations */:\n return isVariableDeclaratorListTerminator();\n case 17 /* TypeParameters */:\n // Tokens other than '>' are here for better error recovery\n return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */ || token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */;\n case 11 /* ArgumentExpressions */:\n // Tokens other than ')' are here for better error recovery\n return token === 18 /* CloseParenToken */ || token === 23 /* SemicolonToken */;\n case 15 /* ArrayLiteralMembers */:\n case 19 /* TupleElementTypes */:\n case 10 /* ArrayBindingElements */:\n return token === 20 /* CloseBracketToken */;\n case 16 /* Parameters */:\n // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery\n return token === 18 /* CloseParenToken */ || token === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;\n case 18 /* TypeArguments */:\n // Tokens other than '>' are here for better error recovery\n return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */;\n case 20 /* HeritageClauses */:\n return token === 15 /* OpenBraceToken */ || token === 16 /* CloseBraceToken */;\n case 13 /* JsxAttributes */:\n return token === 27 /* GreaterThanToken */ || token === 39 /* SlashToken */;\n case 14 /* JsxChildren */:\n return token === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash);\n case 22 /* JSDocFunctionParameters */:\n return token === 18 /* CloseParenToken */ || token === 54 /* ColonToken */ || token === 16 /* CloseBraceToken */;\n case 23 /* JSDocTypeArguments */:\n return token === 27 /* GreaterThanToken */ || token === 16 /* CloseBraceToken */;\n case 25 /* JSDocTupleTypes */:\n return token === 20 /* CloseBracketToken */ || token === 16 /* CloseBraceToken */;\n case 24 /* JSDocRecordMembers */:\n return token === 16 /* CloseBraceToken */;\n }\n }", "code_tokens": ["function", "isListTerminator", "(", "kind", ")", "{", "if", "(", "token", "===", "1", ")", "{", "return", "true", ";", "}", "switch", "(", "kind", ")", "{", "case", "1", ":", "case", "2", ":", "case", "4", ":", "case", "5", ":", "case", "6", ":", "case", "12", ":", "case", "9", ":", "case", "21", ":", "return", "token", "===", "16", ";", "case", "3", ":", "return", "token", "===", "16", "||", "token", "===", "71", "||", "token", "===", "77", ";", "case", "7", ":", "return", "token", "===", "15", "||", "token", "===", "83", "||", "token", "===", "106", ";", "case", "8", ":", "return", "isVariableDeclaratorListTerminator", "(", ")", ";", "case", "17", ":", "return", "token", "===", "27", "||", "token", "===", "17", "||", "token", "===", "15", "||", "token", "===", "83", "||", "token", "===", "106", ";", "case", "11", ":", "return", "token", "===", "18", "||", "token", "===", "23", ";", "case", "15", ":", "case", "19", ":", "case", "10", ":", "return", "token", "===", "20", ";", "case", "16", ":", "return", "token", "===", "18", "||", "token", "===", "20", ";", "case", "18", ":", "return", "token", "===", "27", "||", "token", "===", "17", ";", "case", "20", ":", "return", "token", "===", "15", "||", "token", "===", "16", ";", "case", "13", ":", "return", "token", "===", "27", "||", "token", "===", "39", ";", "case", "14", ":", "return", "token", "===", "25", "&&", "lookAhead", "(", "nextTokenIsSlash", ")", ";", "case", "22", ":", "return", "token", "===", "18", "||", "token", "===", "54", "||", "token", "===", "16", ";", "case", "23", ":", "return", "token", "===", "27", "||", "token", "===", "16", ";", "case", "25", ":", "return", "token", "===", "20", "||", "token", "===", "16", ";", "case", "24", ":", "return", "token", "===", "16", ";", "}", "}"], "docstring": "True if positioned at a list terminator", "docstring_tokens": ["True", "if", "positioned", "at", "a", "list", "terminator"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L8549-L8601", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "parseEntityName", "original_string": "function parseEntityName(allowReservedWords, diagnosticMessage) {\n var entity = parseIdentifier(diagnosticMessage);\n while (parseOptional(21 /* DotToken */)) {\n var node = createNode(135 /* QualifiedName */, entity.pos);\n node.left = entity;\n node.right = parseRightSideOfDot(allowReservedWords);\n entity = finishNode(node);\n }\n return entity;\n }", "language": "javascript", "code": "function parseEntityName(allowReservedWords, diagnosticMessage) {\n var entity = parseIdentifier(diagnosticMessage);\n while (parseOptional(21 /* DotToken */)) {\n var node = createNode(135 /* QualifiedName */, entity.pos);\n node.left = entity;\n node.right = parseRightSideOfDot(allowReservedWords);\n entity = finishNode(node);\n }\n return entity;\n }", "code_tokens": ["function", "parseEntityName", "(", "allowReservedWords", ",", "diagnosticMessage", ")", "{", "var", "entity", "=", "parseIdentifier", "(", "diagnosticMessage", ")", ";", "while", "(", "parseOptional", "(", "21", ")", ")", "{", "var", "node", "=", "createNode", "(", "135", ",", "entity", ".", "pos", ")", ";", "node", ".", "left", "=", "entity", ";", "node", ".", "right", "=", "parseRightSideOfDot", "(", "allowReservedWords", ")", ";", "entity", "=", "finishNode", "(", "node", ")", ";", "}", "return", "entity", ";", "}"], "docstring": "The allowReservedWords parameter controls whether reserved words are permitted after the first dot", "docstring_tokens": ["The", "allowReservedWords", "parameter", "controls", "whether", "reserved", "words", "are", "permitted", "after", "the", "first", "dot"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L8999-L9008", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "findHighestListElementThatStartsAtPosition", "original_string": "function findHighestListElementThatStartsAtPosition(position) {\n // Clear out any cached state about the last node we found.\n currentArray = undefined;\n currentArrayIndex = -1 /* Value */;\n current = undefined;\n // Recurse into the source file to find the highest node at this position.\n forEachChild(sourceFile, visitNode, visitArray);\n return;\n function visitNode(node) {\n if (position >= node.pos && position < node.end) {\n // Position was within this node. Keep searching deeper to find the node.\n forEachChild(node, visitNode, visitArray);\n // don't procede any futher in the search.\n return true;\n }\n // position wasn't in this node, have to keep searching.\n return false;\n }\n function visitArray(array) {\n if (position >= array.pos && position < array.end) {\n // position was in this array. Search through this array to see if we find a\n // viable element.\n for (var i = 0, n = array.length; i < n; i++) {\n var child = array[i];\n if (child) {\n if (child.pos === position) {\n // Found the right node. We're done.\n currentArray = array;\n currentArrayIndex = i;\n current = child;\n return true;\n }\n else {\n if (child.pos < position && position < child.end) {\n // Position in somewhere within this child. Search in it and\n // stop searching in this array.\n forEachChild(child, visitNode, visitArray);\n return true;\n }\n }\n }\n }\n }\n // position wasn't in this array, have to keep searching.\n return false;\n }\n }", "language": "javascript", "code": "function findHighestListElementThatStartsAtPosition(position) {\n // Clear out any cached state about the last node we found.\n currentArray = undefined;\n currentArrayIndex = -1 /* Value */;\n current = undefined;\n // Recurse into the source file to find the highest node at this position.\n forEachChild(sourceFile, visitNode, visitArray);\n return;\n function visitNode(node) {\n if (position >= node.pos && position < node.end) {\n // Position was within this node. Keep searching deeper to find the node.\n forEachChild(node, visitNode, visitArray);\n // don't procede any futher in the search.\n return true;\n }\n // position wasn't in this node, have to keep searching.\n return false;\n }\n function visitArray(array) {\n if (position >= array.pos && position < array.end) {\n // position was in this array. Search through this array to see if we find a\n // viable element.\n for (var i = 0, n = array.length; i < n; i++) {\n var child = array[i];\n if (child) {\n if (child.pos === position) {\n // Found the right node. We're done.\n currentArray = array;\n currentArrayIndex = i;\n current = child;\n return true;\n }\n else {\n if (child.pos < position && position < child.end) {\n // Position in somewhere within this child. Search in it and\n // stop searching in this array.\n forEachChild(child, visitNode, visitArray);\n return true;\n }\n }\n }\n }\n }\n // position wasn't in this array, have to keep searching.\n return false;\n }\n }", "code_tokens": ["function", "findHighestListElementThatStartsAtPosition", "(", "position", ")", "{", "currentArray", "=", "undefined", ";", "currentArrayIndex", "=", "-", "1", ";", "current", "=", "undefined", ";", "forEachChild", "(", "sourceFile", ",", "visitNode", ",", "visitArray", ")", ";", "return", ";", "function", "visitNode", "(", "node", ")", "{", "if", "(", "position", ">=", "node", ".", "pos", "&&", "position", "<", "node", ".", "end", ")", "{", "forEachChild", "(", "node", ",", "visitNode", ",", "visitArray", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", "function", "visitArray", "(", "array", ")", "{", "if", "(", "position", ">=", "array", ".", "pos", "&&", "position", "<", "array", ".", "end", ")", "{", "for", "(", "var", "i", "=", "0", ",", "n", "=", "array", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "var", "child", "=", "array", "[", "i", "]", ";", "if", "(", "child", ")", "{", "if", "(", "child", ".", "pos", "===", "position", ")", "{", "currentArray", "=", "array", ";", "currentArrayIndex", "=", "i", ";", "current", "=", "child", ";", "return", "true", ";", "}", "else", "{", "if", "(", "child", ".", "pos", "<", "position", "&&", "position", "<", "child", ".", "end", ")", "{", "forEachChild", "(", "child", ",", "visitNode", ",", "visitArray", ")", ";", "return", "true", ";", "}", "}", "}", "}", "}", "return", "false", ";", "}", "}"], "docstring": "Finds the highest element in the tree we can find that starts at the provided position. The element must be a direct child of some node list in the tree. This way after we return it, we can easily return its next sibling in the list.", "docstring_tokens": ["Finds", "the", "highest", "element", "in", "the", "tree", "we", "can", "find", "that", "starts", "at", "the", "provided", "position", ".", "The", "element", "must", "be", "a", "direct", "child", "of", "some", "node", "list", "in", "the", "tree", ".", "This", "way", "after", "we", "return", "it", "we", "can", "easily", "return", "its", "next", "sibling", "in", "the", "list", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L13169-L13215", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getSymbolOfPartOfRightHandSideOfImportEquals", "original_string": "function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) {\n if (!importDeclaration) {\n importDeclaration = ts.getAncestor(entityName, 221 /* ImportEqualsDeclaration */);\n ts.Debug.assert(importDeclaration !== undefined);\n }\n // There are three things we might try to look for. In the following examples,\n // the search term is enclosed in |...|:\n //\n // import a = |b|; // Namespace\n // import a = |b.c|; // Value, type, namespace\n // import a = |b.c|.d; // Namespace\n if (entityName.kind === 69 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {\n entityName = entityName.parent;\n }\n // Check for case 1 and 3 in the above example\n if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 135 /* QualifiedName */) {\n return resolveEntityName(entityName, 1536 /* Namespace */);\n }\n else {\n // Case 2 in above example\n // entityName.kind could be a QualifiedName or a Missing identifier\n ts.Debug.assert(entityName.parent.kind === 221 /* ImportEqualsDeclaration */);\n return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */);\n }\n }", "language": "javascript", "code": "function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) {\n if (!importDeclaration) {\n importDeclaration = ts.getAncestor(entityName, 221 /* ImportEqualsDeclaration */);\n ts.Debug.assert(importDeclaration !== undefined);\n }\n // There are three things we might try to look for. In the following examples,\n // the search term is enclosed in |...|:\n //\n // import a = |b|; // Namespace\n // import a = |b.c|; // Value, type, namespace\n // import a = |b.c|.d; // Namespace\n if (entityName.kind === 69 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {\n entityName = entityName.parent;\n }\n // Check for case 1 and 3 in the above example\n if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 135 /* QualifiedName */) {\n return resolveEntityName(entityName, 1536 /* Namespace */);\n }\n else {\n // Case 2 in above example\n // entityName.kind could be a QualifiedName or a Missing identifier\n ts.Debug.assert(entityName.parent.kind === 221 /* ImportEqualsDeclaration */);\n return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */);\n }\n }", "code_tokens": ["function", "getSymbolOfPartOfRightHandSideOfImportEquals", "(", "entityName", ",", "importDeclaration", ")", "{", "if", "(", "!", "importDeclaration", ")", "{", "importDeclaration", "=", "ts", ".", "getAncestor", "(", "entityName", ",", "221", ")", ";", "ts", ".", "Debug", ".", "assert", "(", "importDeclaration", "!==", "undefined", ")", ";", "}", "if", "(", "entityName", ".", "kind", "===", "69", "&&", "ts", ".", "isRightSideOfQualifiedNameOrPropertyAccess", "(", "entityName", ")", ")", "{", "entityName", "=", "entityName", ".", "parent", ";", "}", "if", "(", "entityName", ".", "kind", "===", "69", "||", "entityName", ".", "parent", ".", "kind", "===", "135", ")", "{", "return", "resolveEntityName", "(", "entityName", ",", "1536", ")", ";", "}", "else", "{", "ts", ".", "Debug", ".", "assert", "(", "entityName", ".", "parent", ".", "kind", "===", "221", ")", ";", "return", "resolveEntityName", "(", "entityName", ",", "107455", "|", "793056", "|", "1536", ")", ";", "}", "}"], "docstring": "This function is only for imports with entity names", "docstring_tokens": ["This", "function", "is", "only", "for", "imports", "with", "entity", "names"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L14067-L14091", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "resolveEntityName", "original_string": "function resolveEntityName(name, meaning, ignoreErrors) {\n if (ts.nodeIsMissing(name)) {\n return undefined;\n }\n var symbol;\n if (name.kind === 69 /* Identifier */) {\n var message = meaning === 1536 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0;\n symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name);\n if (!symbol) {\n return undefined;\n }\n }\n else if (name.kind === 135 /* QualifiedName */ || name.kind === 166 /* PropertyAccessExpression */) {\n var left = name.kind === 135 /* QualifiedName */ ? name.left : name.expression;\n var right = name.kind === 135 /* QualifiedName */ ? name.right : name.name;\n var namespace = resolveEntityName(left, 1536 /* Namespace */, ignoreErrors);\n if (!namespace || namespace === unknownSymbol || ts.nodeIsMissing(right)) {\n return undefined;\n }\n symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning);\n if (!symbol) {\n if (!ignoreErrors) {\n error(right, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));\n }\n return undefined;\n }\n }\n else {\n ts.Debug.fail(\"Unknown entity name kind.\");\n }\n ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, \"Should never get an instantiated symbol here.\");\n return symbol.flags & meaning ? symbol : resolveAlias(symbol);\n }", "language": "javascript", "code": "function resolveEntityName(name, meaning, ignoreErrors) {\n if (ts.nodeIsMissing(name)) {\n return undefined;\n }\n var symbol;\n if (name.kind === 69 /* Identifier */) {\n var message = meaning === 1536 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0;\n symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name);\n if (!symbol) {\n return undefined;\n }\n }\n else if (name.kind === 135 /* QualifiedName */ || name.kind === 166 /* PropertyAccessExpression */) {\n var left = name.kind === 135 /* QualifiedName */ ? name.left : name.expression;\n var right = name.kind === 135 /* QualifiedName */ ? name.right : name.name;\n var namespace = resolveEntityName(left, 1536 /* Namespace */, ignoreErrors);\n if (!namespace || namespace === unknownSymbol || ts.nodeIsMissing(right)) {\n return undefined;\n }\n symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning);\n if (!symbol) {\n if (!ignoreErrors) {\n error(right, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));\n }\n return undefined;\n }\n }\n else {\n ts.Debug.fail(\"Unknown entity name kind.\");\n }\n ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, \"Should never get an instantiated symbol here.\");\n return symbol.flags & meaning ? symbol : resolveAlias(symbol);\n }", "code_tokens": ["function", "resolveEntityName", "(", "name", ",", "meaning", ",", "ignoreErrors", ")", "{", "if", "(", "ts", ".", "nodeIsMissing", "(", "name", ")", ")", "{", "return", "undefined", ";", "}", "var", "symbol", ";", "if", "(", "name", ".", "kind", "===", "69", ")", "{", "var", "message", "=", "meaning", "===", "1536", "?", "ts", ".", "Diagnostics", ".", "Cannot_find_namespace_0", ":", "ts", ".", "Diagnostics", ".", "Cannot_find_name_0", ";", "symbol", "=", "resolveName", "(", "name", ",", "name", ".", "text", ",", "meaning", ",", "ignoreErrors", "?", "undefined", ":", "message", ",", "name", ")", ";", "if", "(", "!", "symbol", ")", "{", "return", "undefined", ";", "}", "}", "else", "if", "(", "name", ".", "kind", "===", "135", "||", "name", ".", "kind", "===", "166", ")", "{", "var", "left", "=", "name", ".", "kind", "===", "135", "?", "name", ".", "left", ":", "name", ".", "expression", ";", "var", "right", "=", "name", ".", "kind", "===", "135", "?", "name", ".", "right", ":", "name", ".", "name", ";", "var", "namespace", "=", "resolveEntityName", "(", "left", ",", "1536", ",", "ignoreErrors", ")", ";", "if", "(", "!", "namespace", "||", "namespace", "===", "unknownSymbol", "||", "ts", ".", "nodeIsMissing", "(", "right", ")", ")", "{", "return", "undefined", ";", "}", "symbol", "=", "getSymbol", "(", "getExportsOfSymbol", "(", "namespace", ")", ",", "right", ".", "text", ",", "meaning", ")", ";", "if", "(", "!", "symbol", ")", "{", "if", "(", "!", "ignoreErrors", ")", "{", "error", "(", "right", ",", "ts", ".", "Diagnostics", ".", "Module_0_has_no_exported_member_1", ",", "getFullyQualifiedName", "(", "namespace", ")", ",", "ts", ".", "declarationNameToString", "(", "right", ")", ")", ";", "}", "return", "undefined", ";", "}", "}", "else", "{", "ts", ".", "Debug", ".", "fail", "(", "\"Unknown entity name kind.\"", ")", ";", "}", "ts", ".", "Debug", ".", "assert", "(", "(", "symbol", ".", "flags", "&", "16777216", ")", "===", "0", ",", "\"Should never get an instantiated symbol here.\"", ")", ";", "return", "symbol", ".", "flags", "&", "meaning", "?", "symbol", ":", "resolveAlias", "(", "symbol", ")", ";", "}"], "docstring": "Resolves a qualified name and any involved aliases", "docstring_tokens": ["Resolves", "a", "qualified", "name", "and", "any", "involved", "aliases"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L14096-L14128", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "isReservedMemberName", "original_string": "function isReservedMemberName(name) {\n return name.charCodeAt(0) === 95 /* _ */ &&\n name.charCodeAt(1) === 95 /* _ */ &&\n name.charCodeAt(2) !== 95 /* _ */ &&\n name.charCodeAt(2) !== 64 /* at */;\n }", "language": "javascript", "code": "function isReservedMemberName(name) {\n return name.charCodeAt(0) === 95 /* _ */ &&\n name.charCodeAt(1) === 95 /* _ */ &&\n name.charCodeAt(2) !== 95 /* _ */ &&\n name.charCodeAt(2) !== 64 /* at */;\n }", "code_tokens": ["function", "isReservedMemberName", "(", "name", ")", "{", "return", "name", ".", "charCodeAt", "(", "0", ")", "===", "95", "&&", "name", ".", "charCodeAt", "(", "1", ")", "===", "95", "&&", "name", ".", "charCodeAt", "(", "2", ")", "!==", "95", "&&", "name", ".", "charCodeAt", "(", "2", ")", "!==", "64", ";", "}"], "docstring": "A reserved member name starts with two underscores, but the third character cannot be an underscore or the @ symbol. A third underscore indicates an escaped form of an identifer that started with at least two underscores. The @ character indicates that the name is denoted by a well known ES Symbol instance.", "docstring_tokens": ["A", "reserved", "member", "name", "starts", "with", "two", "underscores", "but", "the", "third", "character", "cannot", "be", "an", "underscore", "or", "the"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L14281-L14286", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "isSymbolUsedInExportAssignment", "original_string": "function isSymbolUsedInExportAssignment(symbol) {\n if (exportAssignmentSymbol === symbol) {\n return true;\n }\n if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & 8388608 /* Alias */)) {\n // if export assigned symbol is alias declaration, resolve the alias\n resolvedExportSymbol = resolvedExportSymbol || resolveAlias(exportAssignmentSymbol);\n if (resolvedExportSymbol === symbol) {\n return true;\n }\n // Container of resolvedExportSymbol is visible\n return ts.forEach(resolvedExportSymbol.declarations, function (current) {\n while (current) {\n if (current === node) {\n return true;\n }\n current = current.parent;\n }\n });\n }\n }", "language": "javascript", "code": "function isSymbolUsedInExportAssignment(symbol) {\n if (exportAssignmentSymbol === symbol) {\n return true;\n }\n if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & 8388608 /* Alias */)) {\n // if export assigned symbol is alias declaration, resolve the alias\n resolvedExportSymbol = resolvedExportSymbol || resolveAlias(exportAssignmentSymbol);\n if (resolvedExportSymbol === symbol) {\n return true;\n }\n // Container of resolvedExportSymbol is visible\n return ts.forEach(resolvedExportSymbol.declarations, function (current) {\n while (current) {\n if (current === node) {\n return true;\n }\n current = current.parent;\n }\n });\n }\n }", "code_tokens": ["function", "isSymbolUsedInExportAssignment", "(", "symbol", ")", "{", "if", "(", "exportAssignmentSymbol", "===", "symbol", ")", "{", "return", "true", ";", "}", "if", "(", "exportAssignmentSymbol", "&&", "!", "!", "(", "exportAssignmentSymbol", ".", "flags", "&", "8388608", ")", ")", "{", "resolvedExportSymbol", "=", "resolvedExportSymbol", "||", "resolveAlias", "(", "exportAssignmentSymbol", ")", ";", "if", "(", "resolvedExportSymbol", "===", "symbol", ")", "{", "return", "true", ";", "}", "return", "ts", ".", "forEach", "(", "resolvedExportSymbol", ".", "declarations", ",", "function", "(", "current", ")", "{", "while", "(", "current", ")", "{", "if", "(", "current", "===", "node", ")", "{", "return", "true", ";", "}", "current", "=", "current", ".", "parent", ";", "}", "}", ")", ";", "}", "}"], "docstring": "Check if the symbol is used in export assignment", "docstring_tokens": ["Check", "if", "the", "symbol", "is", "used", "in", "export", "assignment"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L15132-L15152", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getTypeOfPropertyOfType", "original_string": "function getTypeOfPropertyOfType(type, name) {\n var prop = getPropertyOfType(type, name);\n return prop ? getTypeOfSymbol(prop) : undefined;\n }", "language": "javascript", "code": "function getTypeOfPropertyOfType(type, name) {\n var prop = getPropertyOfType(type, name);\n return prop ? getTypeOfSymbol(prop) : undefined;\n }", "code_tokens": ["function", "getTypeOfPropertyOfType", "(", "type", ",", "name", ")", "{", "var", "prop", "=", "getPropertyOfType", "(", "type", ",", "name", ")", ";", "return", "prop", "?", "getTypeOfSymbol", "(", "prop", ")", ":", "undefined", ";", "}"], "docstring": "Return the type of the given property in the given type, or undefined if no such property exists", "docstring_tokens": ["Return", "the", "type", "of", "the", "given", "property", "in", "the", "given", "type", "or", "undefined", "if", "no", "such", "property", "exists"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L15341-L15344", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getTypeForBindingElementParent", "original_string": "function getTypeForBindingElementParent(node) {\n var symbol = getSymbolOfNode(node);\n return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node);\n }", "language": "javascript", "code": "function getTypeForBindingElementParent(node) {\n var symbol = getSymbolOfNode(node);\n return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node);\n }", "code_tokens": ["function", "getTypeForBindingElementParent", "(", "node", ")", "{", "var", "symbol", "=", "getSymbolOfNode", "(", "node", ")", ";", "return", "symbol", "&&", "getSymbolLinks", "(", "symbol", ")", ".", "type", "||", "getTypeForVariableLikeDeclaration", "(", "node", ")", ";", "}"], "docstring": "Return the type of a binding element parent. We check SymbolLinks first to see if a type has been assigned by contextual typing.", "docstring_tokens": ["Return", "the", "type", "of", "a", "binding", "element", "parent", ".", "We", "check", "SymbolLinks", "first", "to", "see", "if", "a", "type", "has", "been", "assigned", "by", "contextual", "typing", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L15350-L15353", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getTypeForBindingElement", "original_string": "function getTypeForBindingElement(declaration) {\n var pattern = declaration.parent;\n var parentType = getTypeForBindingElementParent(pattern.parent);\n // If parent has the unknown (error) type, then so does this binding element\n if (parentType === unknownType) {\n return unknownType;\n }\n // If no type was specified or inferred for parent, or if the specified or inferred type is any,\n // infer from the initializer of the binding element if one is present. Otherwise, go with the\n // undefined or any type of the parent.\n if (!parentType || isTypeAny(parentType)) {\n if (declaration.initializer) {\n return checkExpressionCached(declaration.initializer);\n }\n return parentType;\n }\n var type;\n if (pattern.kind === 161 /* ObjectBindingPattern */) {\n // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)\n var name_10 = declaration.propertyName || declaration.name;\n // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature,\n // or otherwise the type of the string index signature.\n type = getTypeOfPropertyOfType(parentType, name_10.text) ||\n isNumericLiteralName(name_10.text) && getIndexTypeOfType(parentType, 1 /* Number */) ||\n getIndexTypeOfType(parentType, 0 /* String */);\n if (!type) {\n error(name_10, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_10));\n return unknownType;\n }\n }\n else {\n // This elementType will be used if the specific property corresponding to this index is not\n // present (aka the tuple element property). This call also checks that the parentType is in\n // fact an iterable or array (depending on target language).\n var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false);\n if (!declaration.dotDotDotToken) {\n // Use specific property type when parent is a tuple or numeric index type when parent is an array\n var propName = \"\" + ts.indexOf(pattern.elements, declaration);\n type = isTupleLikeType(parentType)\n ? getTypeOfPropertyOfType(parentType, propName)\n : elementType;\n if (!type) {\n if (isTupleType(parentType)) {\n error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length);\n }\n else {\n error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName);\n }\n return unknownType;\n }\n }\n else {\n // Rest element has an array type with the same element type as the parent type\n type = createArrayType(elementType);\n }\n }\n return type;\n }", "language": "javascript", "code": "function getTypeForBindingElement(declaration) {\n var pattern = declaration.parent;\n var parentType = getTypeForBindingElementParent(pattern.parent);\n // If parent has the unknown (error) type, then so does this binding element\n if (parentType === unknownType) {\n return unknownType;\n }\n // If no type was specified or inferred for parent, or if the specified or inferred type is any,\n // infer from the initializer of the binding element if one is present. Otherwise, go with the\n // undefined or any type of the parent.\n if (!parentType || isTypeAny(parentType)) {\n if (declaration.initializer) {\n return checkExpressionCached(declaration.initializer);\n }\n return parentType;\n }\n var type;\n if (pattern.kind === 161 /* ObjectBindingPattern */) {\n // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)\n var name_10 = declaration.propertyName || declaration.name;\n // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature,\n // or otherwise the type of the string index signature.\n type = getTypeOfPropertyOfType(parentType, name_10.text) ||\n isNumericLiteralName(name_10.text) && getIndexTypeOfType(parentType, 1 /* Number */) ||\n getIndexTypeOfType(parentType, 0 /* String */);\n if (!type) {\n error(name_10, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_10));\n return unknownType;\n }\n }\n else {\n // This elementType will be used if the specific property corresponding to this index is not\n // present (aka the tuple element property). This call also checks that the parentType is in\n // fact an iterable or array (depending on target language).\n var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false);\n if (!declaration.dotDotDotToken) {\n // Use specific property type when parent is a tuple or numeric index type when parent is an array\n var propName = \"\" + ts.indexOf(pattern.elements, declaration);\n type = isTupleLikeType(parentType)\n ? getTypeOfPropertyOfType(parentType, propName)\n : elementType;\n if (!type) {\n if (isTupleType(parentType)) {\n error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length);\n }\n else {\n error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName);\n }\n return unknownType;\n }\n }\n else {\n // Rest element has an array type with the same element type as the parent type\n type = createArrayType(elementType);\n }\n }\n return type;\n }", "code_tokens": ["function", "getTypeForBindingElement", "(", "declaration", ")", "{", "var", "pattern", "=", "declaration", ".", "parent", ";", "var", "parentType", "=", "getTypeForBindingElementParent", "(", "pattern", ".", "parent", ")", ";", "if", "(", "parentType", "===", "unknownType", ")", "{", "return", "unknownType", ";", "}", "if", "(", "!", "parentType", "||", "isTypeAny", "(", "parentType", ")", ")", "{", "if", "(", "declaration", ".", "initializer", ")", "{", "return", "checkExpressionCached", "(", "declaration", ".", "initializer", ")", ";", "}", "return", "parentType", ";", "}", "var", "type", ";", "if", "(", "pattern", ".", "kind", "===", "161", ")", "{", "var", "name_10", "=", "declaration", ".", "propertyName", "||", "declaration", ".", "name", ";", "type", "=", "getTypeOfPropertyOfType", "(", "parentType", ",", "name_10", ".", "text", ")", "||", "isNumericLiteralName", "(", "name_10", ".", "text", ")", "&&", "getIndexTypeOfType", "(", "parentType", ",", "1", ")", "||", "getIndexTypeOfType", "(", "parentType", ",", "0", ")", ";", "if", "(", "!", "type", ")", "{", "error", "(", "name_10", ",", "ts", ".", "Diagnostics", ".", "Type_0_has_no_property_1_and_no_string_index_signature", ",", "typeToString", "(", "parentType", ")", ",", "ts", ".", "declarationNameToString", "(", "name_10", ")", ")", ";", "return", "unknownType", ";", "}", "}", "else", "{", "var", "elementType", "=", "checkIteratedTypeOrElementType", "(", "parentType", ",", "pattern", ",", "false", ")", ";", "if", "(", "!", "declaration", ".", "dotDotDotToken", ")", "{", "var", "propName", "=", "\"\"", "+", "ts", ".", "indexOf", "(", "pattern", ".", "elements", ",", "declaration", ")", ";", "type", "=", "isTupleLikeType", "(", "parentType", ")", "?", "getTypeOfPropertyOfType", "(", "parentType", ",", "propName", ")", ":", "elementType", ";", "if", "(", "!", "type", ")", "{", "if", "(", "isTupleType", "(", "parentType", ")", ")", "{", "error", "(", "declaration", ",", "ts", ".", "Diagnostics", ".", "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2", ",", "typeToString", "(", "parentType", ")", ",", "parentType", ".", "elementTypes", ".", "length", ",", "pattern", ".", "elements", ".", "length", ")", ";", "}", "else", "{", "error", "(", "declaration", ",", "ts", ".", "Diagnostics", ".", "Type_0_has_no_property_1", ",", "typeToString", "(", "parentType", ")", ",", "propName", ")", ";", "}", "return", "unknownType", ";", "}", "}", "else", "{", "type", "=", "createArrayType", "(", "elementType", ")", ";", "}", "}", "return", "type", ";", "}"], "docstring": "Return the inferred type for a binding element", "docstring_tokens": ["Return", "the", "inferred", "type", "for", "a", "binding", "element"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L15355-L15412", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getTypeForVariableLikeDeclaration", "original_string": "function getTypeForVariableLikeDeclaration(declaration) {\n // A variable declared in a for..in statement is always of type any\n if (declaration.parent.parent.kind === 200 /* ForInStatement */) {\n return anyType;\n }\n if (declaration.parent.parent.kind === 201 /* ForOfStatement */) {\n // checkRightHandSideOfForOf will return undefined if the for-of expression type was\n // missing properties/signatures required to get its iteratedType (like\n // [Symbol.iterator] or next). This may be because we accessed properties from anyType,\n // or it may have led to an error inside getElementTypeOfIterable.\n return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType;\n }\n if (ts.isBindingPattern(declaration.parent)) {\n return getTypeForBindingElement(declaration);\n }\n // Use type from type annotation if one is present\n if (declaration.type) {\n return getTypeFromTypeNode(declaration.type);\n }\n if (declaration.kind === 138 /* Parameter */) {\n var func = declaration.parent;\n // For a parameter of a set accessor, use the type of the get accessor if one is present\n if (func.kind === 146 /* SetAccessor */ && !ts.hasDynamicName(func)) {\n var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 145 /* GetAccessor */);\n if (getter) {\n return getReturnTypeOfSignature(getSignatureFromDeclaration(getter));\n }\n }\n // Use contextual parameter type if one is available\n var type = getContextuallyTypedParameterType(declaration);\n if (type) {\n return type;\n }\n }\n // Use the type of the initializer expression if one is present\n if (declaration.initializer) {\n return checkExpressionCached(declaration.initializer);\n }\n // If it is a short-hand property assignment, use the type of the identifier\n if (declaration.kind === 246 /* ShorthandPropertyAssignment */) {\n return checkIdentifier(declaration.name);\n }\n // If the declaration specifies a binding pattern, use the type implied by the binding pattern\n if (ts.isBindingPattern(declaration.name)) {\n return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false);\n }\n // No type specified and nothing can be inferred\n return undefined;\n }", "language": "javascript", "code": "function getTypeForVariableLikeDeclaration(declaration) {\n // A variable declared in a for..in statement is always of type any\n if (declaration.parent.parent.kind === 200 /* ForInStatement */) {\n return anyType;\n }\n if (declaration.parent.parent.kind === 201 /* ForOfStatement */) {\n // checkRightHandSideOfForOf will return undefined if the for-of expression type was\n // missing properties/signatures required to get its iteratedType (like\n // [Symbol.iterator] or next). This may be because we accessed properties from anyType,\n // or it may have led to an error inside getElementTypeOfIterable.\n return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType;\n }\n if (ts.isBindingPattern(declaration.parent)) {\n return getTypeForBindingElement(declaration);\n }\n // Use type from type annotation if one is present\n if (declaration.type) {\n return getTypeFromTypeNode(declaration.type);\n }\n if (declaration.kind === 138 /* Parameter */) {\n var func = declaration.parent;\n // For a parameter of a set accessor, use the type of the get accessor if one is present\n if (func.kind === 146 /* SetAccessor */ && !ts.hasDynamicName(func)) {\n var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 145 /* GetAccessor */);\n if (getter) {\n return getReturnTypeOfSignature(getSignatureFromDeclaration(getter));\n }\n }\n // Use contextual parameter type if one is available\n var type = getContextuallyTypedParameterType(declaration);\n if (type) {\n return type;\n }\n }\n // Use the type of the initializer expression if one is present\n if (declaration.initializer) {\n return checkExpressionCached(declaration.initializer);\n }\n // If it is a short-hand property assignment, use the type of the identifier\n if (declaration.kind === 246 /* ShorthandPropertyAssignment */) {\n return checkIdentifier(declaration.name);\n }\n // If the declaration specifies a binding pattern, use the type implied by the binding pattern\n if (ts.isBindingPattern(declaration.name)) {\n return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false);\n }\n // No type specified and nothing can be inferred\n return undefined;\n }", "code_tokens": ["function", "getTypeForVariableLikeDeclaration", "(", "declaration", ")", "{", "if", "(", "declaration", ".", "parent", ".", "parent", ".", "kind", "===", "200", ")", "{", "return", "anyType", ";", "}", "if", "(", "declaration", ".", "parent", ".", "parent", ".", "kind", "===", "201", ")", "{", "return", "checkRightHandSideOfForOf", "(", "declaration", ".", "parent", ".", "parent", ".", "expression", ")", "||", "anyType", ";", "}", "if", "(", "ts", ".", "isBindingPattern", "(", "declaration", ".", "parent", ")", ")", "{", "return", "getTypeForBindingElement", "(", "declaration", ")", ";", "}", "if", "(", "declaration", ".", "type", ")", "{", "return", "getTypeFromTypeNode", "(", "declaration", ".", "type", ")", ";", "}", "if", "(", "declaration", ".", "kind", "===", "138", ")", "{", "var", "func", "=", "declaration", ".", "parent", ";", "if", "(", "func", ".", "kind", "===", "146", "&&", "!", "ts", ".", "hasDynamicName", "(", "func", ")", ")", "{", "var", "getter", "=", "ts", ".", "getDeclarationOfKind", "(", "declaration", ".", "parent", ".", "symbol", ",", "145", ")", ";", "if", "(", "getter", ")", "{", "return", "getReturnTypeOfSignature", "(", "getSignatureFromDeclaration", "(", "getter", ")", ")", ";", "}", "}", "var", "type", "=", "getContextuallyTypedParameterType", "(", "declaration", ")", ";", "if", "(", "type", ")", "{", "return", "type", ";", "}", "}", "if", "(", "declaration", ".", "initializer", ")", "{", "return", "checkExpressionCached", "(", "declaration", ".", "initializer", ")", ";", "}", "if", "(", "declaration", ".", "kind", "===", "246", ")", "{", "return", "checkIdentifier", "(", "declaration", ".", "name", ")", ";", "}", "if", "(", "ts", ".", "isBindingPattern", "(", "declaration", ".", "name", ")", ")", "{", "return", "getTypeFromBindingPattern", "(", "declaration", ".", "name", ",", "false", ")", ";", "}", "return", "undefined", ";", "}"], "docstring": "Return the inferred type for a variable, parameter, or property declaration", "docstring_tokens": ["Return", "the", "inferred", "type", "for", "a", "variable", "parameter", "or", "property", "declaration"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L15414-L15462", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getTypeFromBindingElement", "original_string": "function getTypeFromBindingElement(element, includePatternInType) {\n if (element.initializer) {\n return getWidenedType(checkExpressionCached(element.initializer));\n }\n if (ts.isBindingPattern(element.name)) {\n return getTypeFromBindingPattern(element.name, includePatternInType);\n }\n return anyType;\n }", "language": "javascript", "code": "function getTypeFromBindingElement(element, includePatternInType) {\n if (element.initializer) {\n return getWidenedType(checkExpressionCached(element.initializer));\n }\n if (ts.isBindingPattern(element.name)) {\n return getTypeFromBindingPattern(element.name, includePatternInType);\n }\n return anyType;\n }", "code_tokens": ["function", "getTypeFromBindingElement", "(", "element", ",", "includePatternInType", ")", "{", "if", "(", "element", ".", "initializer", ")", "{", "return", "getWidenedType", "(", "checkExpressionCached", "(", "element", ".", "initializer", ")", ")", ";", "}", "if", "(", "ts", ".", "isBindingPattern", "(", "element", ".", "name", ")", ")", "{", "return", "getTypeFromBindingPattern", "(", "element", ".", "name", ",", "includePatternInType", ")", ";", "}", "return", "anyType", ";", "}"], "docstring": "Return the type implied by a binding pattern element. This is the type of the initializer of the element if one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding pattern. Otherwise, it is the type any.", "docstring_tokens": ["Return", "the", "type", "implied", "by", "a", "binding", "pattern", "element", ".", "This", "is", "the", "type", "of", "the", "initializer", "of", "the", "element", "if", "one", "is", "present", ".", "Otherwise", "if", "the", "element", "is", "itself", "a", "binding", "pattern", "it", "is", "the", "type", "implied", "by", "the", "binding", "pattern", ".", "Otherwise", "it", "is", "the", "type", "any", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L15466-L15474", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getTypeFromObjectBindingPattern", "original_string": "function getTypeFromObjectBindingPattern(pattern, includePatternInType) {\n var members = {};\n ts.forEach(pattern.elements, function (e) {\n var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0);\n var name = e.propertyName || e.name;\n var symbol = createSymbol(flags, name.text);\n symbol.type = getTypeFromBindingElement(e, includePatternInType);\n symbol.bindingElement = e;\n members[symbol.name] = symbol;\n });\n var result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined);\n if (includePatternInType) {\n result.pattern = pattern;\n }\n return result;\n }", "language": "javascript", "code": "function getTypeFromObjectBindingPattern(pattern, includePatternInType) {\n var members = {};\n ts.forEach(pattern.elements, function (e) {\n var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0);\n var name = e.propertyName || e.name;\n var symbol = createSymbol(flags, name.text);\n symbol.type = getTypeFromBindingElement(e, includePatternInType);\n symbol.bindingElement = e;\n members[symbol.name] = symbol;\n });\n var result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined);\n if (includePatternInType) {\n result.pattern = pattern;\n }\n return result;\n }", "code_tokens": ["function", "getTypeFromObjectBindingPattern", "(", "pattern", ",", "includePatternInType", ")", "{", "var", "members", "=", "{", "}", ";", "ts", ".", "forEach", "(", "pattern", ".", "elements", ",", "function", "(", "e", ")", "{", "var", "flags", "=", "4", "|", "67108864", "|", "(", "e", ".", "initializer", "?", "536870912", ":", "0", ")", ";", "var", "name", "=", "e", ".", "propertyName", "||", "e", ".", "name", ";", "var", "symbol", "=", "createSymbol", "(", "flags", ",", "name", ".", "text", ")", ";", "symbol", ".", "type", "=", "getTypeFromBindingElement", "(", "e", ",", "includePatternInType", ")", ";", "symbol", ".", "bindingElement", "=", "e", ";", "members", "[", "symbol", ".", "name", "]", "=", "symbol", ";", "}", ")", ";", "var", "result", "=", "createAnonymousType", "(", "undefined", ",", "members", ",", "emptyArray", ",", "emptyArray", ",", "undefined", ",", "undefined", ")", ";", "if", "(", "includePatternInType", ")", "{", "result", ".", "pattern", "=", "pattern", ";", "}", "return", "result", ";", "}"], "docstring": "Return the type implied by an object binding pattern", "docstring_tokens": ["Return", "the", "type", "implied", "by", "an", "object", "binding", "pattern"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L15476-L15491", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getLocalTypeParametersOfClassOrInterfaceOrTypeAlias", "original_string": "function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {\n var result;\n for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {\n var node = _a[_i];\n if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 214 /* ClassDeclaration */ ||\n node.kind === 186 /* ClassExpression */ || node.kind === 216 /* TypeAliasDeclaration */) {\n var declaration = node;\n if (declaration.typeParameters) {\n result = appendTypeParameters(result, declaration.typeParameters);\n }\n }\n }\n return result;\n }", "language": "javascript", "code": "function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {\n var result;\n for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {\n var node = _a[_i];\n if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 214 /* ClassDeclaration */ ||\n node.kind === 186 /* ClassExpression */ || node.kind === 216 /* TypeAliasDeclaration */) {\n var declaration = node;\n if (declaration.typeParameters) {\n result = appendTypeParameters(result, declaration.typeParameters);\n }\n }\n }\n return result;\n }", "code_tokens": ["function", "getLocalTypeParametersOfClassOrInterfaceOrTypeAlias", "(", "symbol", ")", "{", "var", "result", ";", "for", "(", "var", "_i", "=", "0", ",", "_a", "=", "symbol", ".", "declarations", ";", "_i", "<", "_a", ".", "length", ";", "_i", "++", ")", "{", "var", "node", "=", "_a", "[", "_i", "]", ";", "if", "(", "node", ".", "kind", "===", "215", "||", "node", ".", "kind", "===", "214", "||", "node", ".", "kind", "===", "186", "||", "node", ".", "kind", "===", "216", ")", "{", "var", "declaration", "=", "node", ";", "if", "(", "declaration", ".", "typeParameters", ")", "{", "result", "=", "appendTypeParameters", "(", "result", ",", "declaration", ".", "typeParameters", ")", ";", "}", "}", "}", "return", "result", ";", "}"], "docstring": "The local type parameters are the combined set of type parameters from all declarations of the class, interface, or type alias.", "docstring_tokens": ["The", "local", "type", "parameters", "are", "the", "combined", "set", "of", "type", "parameters", "from", "all", "declarations", "of", "the", "class", "interface", "or", "type", "alias", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L15754-L15767", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getBaseConstructorTypeOfClass", "original_string": "function getBaseConstructorTypeOfClass(type) {\n if (!type.resolvedBaseConstructorType) {\n var baseTypeNode = getBaseTypeNodeOfClass(type);\n if (!baseTypeNode) {\n return type.resolvedBaseConstructorType = undefinedType;\n }\n if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {\n return unknownType;\n }\n var baseConstructorType = checkExpression(baseTypeNode.expression);\n if (baseConstructorType.flags & 80896 /* ObjectType */) {\n // Resolving the members of a class requires us to resolve the base class of that class.\n // We force resolution here such that we catch circularities now.\n resolveStructuredTypeMembers(baseConstructorType);\n }\n if (!popTypeResolution()) {\n error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));\n return type.resolvedBaseConstructorType = unknownType;\n }\n if (baseConstructorType !== unknownType && baseConstructorType !== nullType && !isConstructorType(baseConstructorType)) {\n error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));\n return type.resolvedBaseConstructorType = unknownType;\n }\n type.resolvedBaseConstructorType = baseConstructorType;\n }\n return type.resolvedBaseConstructorType;\n }", "language": "javascript", "code": "function getBaseConstructorTypeOfClass(type) {\n if (!type.resolvedBaseConstructorType) {\n var baseTypeNode = getBaseTypeNodeOfClass(type);\n if (!baseTypeNode) {\n return type.resolvedBaseConstructorType = undefinedType;\n }\n if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {\n return unknownType;\n }\n var baseConstructorType = checkExpression(baseTypeNode.expression);\n if (baseConstructorType.flags & 80896 /* ObjectType */) {\n // Resolving the members of a class requires us to resolve the base class of that class.\n // We force resolution here such that we catch circularities now.\n resolveStructuredTypeMembers(baseConstructorType);\n }\n if (!popTypeResolution()) {\n error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));\n return type.resolvedBaseConstructorType = unknownType;\n }\n if (baseConstructorType !== unknownType && baseConstructorType !== nullType && !isConstructorType(baseConstructorType)) {\n error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));\n return type.resolvedBaseConstructorType = unknownType;\n }\n type.resolvedBaseConstructorType = baseConstructorType;\n }\n return type.resolvedBaseConstructorType;\n }", "code_tokens": ["function", "getBaseConstructorTypeOfClass", "(", "type", ")", "{", "if", "(", "!", "type", ".", "resolvedBaseConstructorType", ")", "{", "var", "baseTypeNode", "=", "getBaseTypeNodeOfClass", "(", "type", ")", ";", "if", "(", "!", "baseTypeNode", ")", "{", "return", "type", ".", "resolvedBaseConstructorType", "=", "undefinedType", ";", "}", "if", "(", "!", "pushTypeResolution", "(", "type", ",", "1", ")", ")", "{", "return", "unknownType", ";", "}", "var", "baseConstructorType", "=", "checkExpression", "(", "baseTypeNode", ".", "expression", ")", ";", "if", "(", "baseConstructorType", ".", "flags", "&", "80896", ")", "{", "resolveStructuredTypeMembers", "(", "baseConstructorType", ")", ";", "}", "if", "(", "!", "popTypeResolution", "(", ")", ")", "{", "error", "(", "type", ".", "symbol", ".", "valueDeclaration", ",", "ts", ".", "Diagnostics", ".", "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression", ",", "symbolToString", "(", "type", ".", "symbol", ")", ")", ";", "return", "type", ".", "resolvedBaseConstructorType", "=", "unknownType", ";", "}", "if", "(", "baseConstructorType", "!==", "unknownType", "&&", "baseConstructorType", "!==", "nullType", "&&", "!", "isConstructorType", "(", "baseConstructorType", ")", ")", "{", "error", "(", "baseTypeNode", ".", "expression", ",", "ts", ".", "Diagnostics", ".", "Type_0_is_not_a_constructor_function_type", ",", "typeToString", "(", "baseConstructorType", ")", ")", ";", "return", "type", ".", "resolvedBaseConstructorType", "=", "unknownType", ";", "}", "type", ".", "resolvedBaseConstructorType", "=", "baseConstructorType", ";", "}", "return", "type", ".", "resolvedBaseConstructorType", ";", "}"], "docstring": "The base constructor of a class can resolve to undefinedType if the class has no extends clause, unknownType if an error occurred during resolution of the extends expression, nullType if the extends expression is the null value, or an object type with at least one construct signature.", "docstring_tokens": ["The", "base", "constructor", "of", "a", "class", "can", "resolve", "to", "undefinedType", "if", "the", "class", "has", "no", "extends", "clause", "unknownType", "if", "an", "error", "occurred", "during", "resolution", "of", "the", "extends", "expression", "nullType", "if", "the", "extends", "expression", "is", "the", "null", "value", "or", "an", "object", "type", "with", "at", "least", "one", "construct", "signature", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L15796-L15822", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "isIndependentTypeReference", "original_string": "function isIndependentTypeReference(node) {\n if (node.typeArguments) {\n for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) {\n var typeNode = _a[_i];\n if (!isIndependentType(typeNode)) {\n return false;\n }\n }\n }\n return true;\n }", "language": "javascript", "code": "function isIndependentTypeReference(node) {\n if (node.typeArguments) {\n for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) {\n var typeNode = _a[_i];\n if (!isIndependentType(typeNode)) {\n return false;\n }\n }\n }\n return true;\n }", "code_tokens": ["function", "isIndependentTypeReference", "(", "node", ")", "{", "if", "(", "node", ".", "typeArguments", ")", "{", "for", "(", "var", "_i", "=", "0", ",", "_a", "=", "node", ".", "typeArguments", ";", "_i", "<", "_a", ".", "length", ";", "_i", "++", ")", "{", "var", "typeNode", "=", "_a", "[", "_i", "]", ";", "if", "(", "!", "isIndependentType", "(", "typeNode", ")", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}"], "docstring": "A type reference is considered independent if each type argument is considered independent.", "docstring_tokens": ["A", "type", "reference", "is", "considered", "independent", "if", "each", "type", "argument", "is", "considered", "independent", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L16044-L16054", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "createInstantiatedSymbolTable", "original_string": "function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {\n var result = {};\n for (var _i = 0; _i < symbols.length; _i++) {\n var symbol = symbols[_i];\n result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper);\n }\n return result;\n }", "language": "javascript", "code": "function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {\n var result = {};\n for (var _i = 0; _i < symbols.length; _i++) {\n var symbol = symbols[_i];\n result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper);\n }\n return result;\n }", "code_tokens": ["function", "createInstantiatedSymbolTable", "(", "symbols", ",", "mapper", ",", "mappingThisOnly", ")", "{", "var", "result", "=", "{", "}", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "symbols", ".", "length", ";", "_i", "++", ")", "{", "var", "symbol", "=", "symbols", "[", "_i", "]", ";", "result", "[", "symbol", ".", "name", "]", "=", "mappingThisOnly", "&&", "isIndependentMember", "(", "symbol", ")", "?", "symbol", ":", "instantiateSymbol", "(", "symbol", ",", "mapper", ")", ";", "}", "return", "result", ";", "}"], "docstring": "The mappingThisOnly flag indicates that the only type parameter being mapped is \"this\". When the flag is true, we check symbols to see if we can quickly conclude they are free of \"this\" references, thus needing no instantiation.", "docstring_tokens": ["The", "mappingThisOnly", "flag", "indicates", "that", "the", "only", "type", "parameter", "being", "mapped", "is", "this", ".", "When", "the", "flag", "is", "true", "we", "check", "symbols", "to", "see", "if", "we", "can", "quickly", "conclude", "they", "are", "free", "of", "this", "references", "thus", "needing", "no", "instantiation", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L16126-L16133", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getUnionSignatures", "original_string": "function getUnionSignatures(types, kind) {\n var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); });\n var result = undefined;\n for (var i = 0; i < signatureLists.length; i++) {\n for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {\n var signature = _a[_i];\n // Only process signatures with parameter lists that aren't already in the result list\n if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true)) {\n var unionSignatures = findMatchingSignatures(signatureLists, signature, i);\n if (unionSignatures) {\n var s = signature;\n // Union the result types when more than one signature matches\n if (unionSignatures.length > 1) {\n s = cloneSignature(signature);\n // Clear resolved return type we possibly got from cloneSignature\n s.resolvedReturnType = undefined;\n s.unionSignatures = unionSignatures;\n }\n (result || (result = [])).push(s);\n }\n }\n }\n }\n return result || emptyArray;\n }", "language": "javascript", "code": "function getUnionSignatures(types, kind) {\n var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); });\n var result = undefined;\n for (var i = 0; i < signatureLists.length; i++) {\n for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {\n var signature = _a[_i];\n // Only process signatures with parameter lists that aren't already in the result list\n if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true)) {\n var unionSignatures = findMatchingSignatures(signatureLists, signature, i);\n if (unionSignatures) {\n var s = signature;\n // Union the result types when more than one signature matches\n if (unionSignatures.length > 1) {\n s = cloneSignature(signature);\n // Clear resolved return type we possibly got from cloneSignature\n s.resolvedReturnType = undefined;\n s.unionSignatures = unionSignatures;\n }\n (result || (result = [])).push(s);\n }\n }\n }\n }\n return result || emptyArray;\n }", "code_tokens": ["function", "getUnionSignatures", "(", "types", ",", "kind", ")", "{", "var", "signatureLists", "=", "ts", ".", "map", "(", "types", ",", "function", "(", "t", ")", "{", "return", "getSignaturesOfType", "(", "t", ",", "kind", ")", ";", "}", ")", ";", "var", "result", "=", "undefined", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "signatureLists", ".", "length", ";", "i", "++", ")", "{", "for", "(", "var", "_i", "=", "0", ",", "_a", "=", "signatureLists", "[", "i", "]", ";", "_i", "<", "_a", ".", "length", ";", "_i", "++", ")", "{", "var", "signature", "=", "_a", "[", "_i", "]", ";", "if", "(", "!", "result", "||", "!", "findMatchingSignature", "(", "result", ",", "signature", ",", "false", ",", "true", ")", ")", "{", "var", "unionSignatures", "=", "findMatchingSignatures", "(", "signatureLists", ",", "signature", ",", "i", ")", ";", "if", "(", "unionSignatures", ")", "{", "var", "s", "=", "signature", ";", "if", "(", "unionSignatures", ".", "length", ">", "1", ")", "{", "s", "=", "cloneSignature", "(", "signature", ")", ";", "s", ".", "resolvedReturnType", "=", "undefined", ";", "s", ".", "unionSignatures", "=", "unionSignatures", ";", "}", "(", "result", "||", "(", "result", "=", "[", "]", ")", ")", ".", "push", "(", "s", ")", ";", "}", "}", "}", "}", "return", "result", "||", "emptyArray", ";", "}"], "docstring": "The signatures of a union type are those signatures that are present in each of the constituent types. Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional parameters and may differ in return types. When signatures differ in return types, the resulting return type is the union of the constituent return types.", "docstring_tokens": ["The", "signatures", "of", "a", "union", "type", "are", "those", "signatures", "that", "are", "present", "in", "each", "of", "the", "constituent", "types", ".", "Generic", "signatures", "must", "match", "exactly", "but", "non", "-", "generic", "signatures", "are", "allowed", "to", "have", "extra", "optional", "parameters", "and", "may", "differ", "in", "return", "types", ".", "When", "signatures", "differ", "in", "return", "types", "the", "resulting", "return", "type", "is", "the", "union", "of", "the", "constituent", "return", "types", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L16303-L16327", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getPropertyOfObjectType", "original_string": "function getPropertyOfObjectType(type, name) {\n if (type.flags & 80896 /* ObjectType */) {\n var resolved = resolveStructuredTypeMembers(type);\n if (ts.hasProperty(resolved.members, name)) {\n var symbol = resolved.members[name];\n if (symbolIsValue(symbol)) {\n return symbol;\n }\n }\n }\n }", "language": "javascript", "code": "function getPropertyOfObjectType(type, name) {\n if (type.flags & 80896 /* ObjectType */) {\n var resolved = resolveStructuredTypeMembers(type);\n if (ts.hasProperty(resolved.members, name)) {\n var symbol = resolved.members[name];\n if (symbolIsValue(symbol)) {\n return symbol;\n }\n }\n }\n }", "code_tokens": ["function", "getPropertyOfObjectType", "(", "type", ",", "name", ")", "{", "if", "(", "type", ".", "flags", "&", "80896", ")", "{", "var", "resolved", "=", "resolveStructuredTypeMembers", "(", "type", ")", ";", "if", "(", "ts", ".", "hasProperty", "(", "resolved", ".", "members", ",", "name", ")", ")", "{", "var", "symbol", "=", "resolved", ".", "members", "[", "name", "]", ";", "if", "(", "symbolIsValue", "(", "symbol", ")", ")", "{", "return", "symbol", ";", "}", "}", "}", "}"], "docstring": "If the given type is an object type and that type has a property by the given name, return the symbol for that property.Otherwise return undefined.", "docstring_tokens": ["If", "the", "given", "type", "is", "an", "object", "type", "and", "that", "type", "has", "a", "property", "by", "the", "given", "name", "return", "the", "symbol", "for", "that", "property", ".", "Otherwise", "return", "undefined", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L16449-L16459", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getApparentType", "original_string": "function getApparentType(type) {\n if (type.flags & 512 /* TypeParameter */) {\n do {\n type = getConstraintOfTypeParameter(type);\n } while (type && type.flags & 512 /* TypeParameter */);\n if (!type) {\n type = emptyObjectType;\n }\n }\n if (type.flags & 258 /* StringLike */) {\n type = globalStringType;\n }\n else if (type.flags & 132 /* NumberLike */) {\n type = globalNumberType;\n }\n else if (type.flags & 8 /* Boolean */) {\n type = globalBooleanType;\n }\n else if (type.flags & 16777216 /* ESSymbol */) {\n type = globalESSymbolType;\n }\n return type;\n }", "language": "javascript", "code": "function getApparentType(type) {\n if (type.flags & 512 /* TypeParameter */) {\n do {\n type = getConstraintOfTypeParameter(type);\n } while (type && type.flags & 512 /* TypeParameter */);\n if (!type) {\n type = emptyObjectType;\n }\n }\n if (type.flags & 258 /* StringLike */) {\n type = globalStringType;\n }\n else if (type.flags & 132 /* NumberLike */) {\n type = globalNumberType;\n }\n else if (type.flags & 8 /* Boolean */) {\n type = globalBooleanType;\n }\n else if (type.flags & 16777216 /* ESSymbol */) {\n type = globalESSymbolType;\n }\n return type;\n }", "code_tokens": ["function", "getApparentType", "(", "type", ")", "{", "if", "(", "type", ".", "flags", "&", "512", ")", "{", "do", "{", "type", "=", "getConstraintOfTypeParameter", "(", "type", ")", ";", "}", "while", "(", "type", "&&", "type", ".", "flags", "&", "512", ")", ";", "if", "(", "!", "type", ")", "{", "type", "=", "emptyObjectType", ";", "}", "}", "if", "(", "type", ".", "flags", "&", "258", ")", "{", "type", "=", "globalStringType", ";", "}", "else", "if", "(", "type", ".", "flags", "&", "132", ")", "{", "type", "=", "globalNumberType", ";", "}", "else", "if", "(", "type", ".", "flags", "&", "8", ")", "{", "type", "=", "globalBooleanType", ";", "}", "else", "if", "(", "type", ".", "flags", "&", "16777216", ")", "{", "type", "=", "globalESSymbolType", ";", "}", "return", "type", ";", "}"], "docstring": "For a type parameter, return the base constraint of the type parameter. For the string, number,\nboolean, and symbol primitive types, return the corresponding object types. Otherwise return the\ntype itself. Note that the apparent type of a union type is the union type itself.", "docstring_tokens": ["For", "a", "type", "parameter", "return", "the", "base", "constraint", "of", "the", "type", "parameter", ".", "For", "the", "string", "number", "boolean", "and", "symbol", "primitive", "types", "return", "the", "corresponding", "object", "types", ".", "Otherwise", "return", "the", "type", "itself", ".", "Note", "that", "the", "apparent", "type", "of", "a", "union", "type", "is", "the", "union", "type", "itself", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L16484-L16506", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getPropertyOfType", "original_string": "function getPropertyOfType(type, name) {\n type = getApparentType(type);\n if (type.flags & 80896 /* ObjectType */) {\n var resolved = resolveStructuredTypeMembers(type);\n if (ts.hasProperty(resolved.members, name)) {\n var symbol = resolved.members[name];\n if (symbolIsValue(symbol)) {\n return symbol;\n }\n }\n if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) {\n var symbol = getPropertyOfObjectType(globalFunctionType, name);\n if (symbol) {\n return symbol;\n }\n }\n return getPropertyOfObjectType(globalObjectType, name);\n }\n if (type.flags & 49152 /* UnionOrIntersection */) {\n return getPropertyOfUnionOrIntersectionType(type, name);\n }\n return undefined;\n }", "language": "javascript", "code": "function getPropertyOfType(type, name) {\n type = getApparentType(type);\n if (type.flags & 80896 /* ObjectType */) {\n var resolved = resolveStructuredTypeMembers(type);\n if (ts.hasProperty(resolved.members, name)) {\n var symbol = resolved.members[name];\n if (symbolIsValue(symbol)) {\n return symbol;\n }\n }\n if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) {\n var symbol = getPropertyOfObjectType(globalFunctionType, name);\n if (symbol) {\n return symbol;\n }\n }\n return getPropertyOfObjectType(globalObjectType, name);\n }\n if (type.flags & 49152 /* UnionOrIntersection */) {\n return getPropertyOfUnionOrIntersectionType(type, name);\n }\n return undefined;\n }", "code_tokens": ["function", "getPropertyOfType", "(", "type", ",", "name", ")", "{", "type", "=", "getApparentType", "(", "type", ")", ";", "if", "(", "type", ".", "flags", "&", "80896", ")", "{", "var", "resolved", "=", "resolveStructuredTypeMembers", "(", "type", ")", ";", "if", "(", "ts", ".", "hasProperty", "(", "resolved", ".", "members", ",", "name", ")", ")", "{", "var", "symbol", "=", "resolved", ".", "members", "[", "name", "]", ";", "if", "(", "symbolIsValue", "(", "symbol", ")", ")", "{", "return", "symbol", ";", "}", "}", "if", "(", "resolved", "===", "anyFunctionType", "||", "resolved", ".", "callSignatures", ".", "length", "||", "resolved", ".", "constructSignatures", ".", "length", ")", "{", "var", "symbol", "=", "getPropertyOfObjectType", "(", "globalFunctionType", ",", "name", ")", ";", "if", "(", "symbol", ")", "{", "return", "symbol", ";", "}", "}", "return", "getPropertyOfObjectType", "(", "globalObjectType", ",", "name", ")", ";", "}", "if", "(", "type", ".", "flags", "&", "49152", ")", "{", "return", "getPropertyOfUnionOrIntersectionType", "(", "type", ",", "name", ")", ";", "}", "return", "undefined", ";", "}"], "docstring": "Return the symbol for the property with the given name in the given type. Creates synthetic union properties when necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from Object and Function as appropriate.", "docstring_tokens": ["Return", "the", "symbol", "for", "the", "property", "with", "the", "given", "name", "in", "the", "given", "type", ".", "Creates", "synthetic", "union", "properties", "when", "necessary", "maps", "primitive", "types", "and", "type", "parameters", "are", "to", "their", "apparent", "types", "and", "augments", "with", "properties", "from", "Object", "and", "Function", "as", "appropriate", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L16564-L16586", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getPropagatingFlagsOfTypes", "original_string": "function getPropagatingFlagsOfTypes(types) {\n var result = 0;\n for (var _i = 0; _i < types.length; _i++) {\n var type = types[_i];\n result |= type.flags;\n }\n return result & 14680064 /* PropagatingFlags */;\n }", "language": "javascript", "code": "function getPropagatingFlagsOfTypes(types) {\n var result = 0;\n for (var _i = 0; _i < types.length; _i++) {\n var type = types[_i];\n result |= type.flags;\n }\n return result & 14680064 /* PropagatingFlags */;\n }", "code_tokens": ["function", "getPropagatingFlagsOfTypes", "(", "types", ")", "{", "var", "result", "=", "0", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "types", ".", "length", ";", "_i", "++", ")", "{", "var", "type", "=", "types", "[", "_i", "]", ";", "result", "|=", "type", ".", "flags", ";", "}", "return", "result", "&", "14680064", ";", "}"], "docstring": "This function is used to propagate certain flags when creating new object type references and union types. It is only necessary to do so if a constituent type might be the undefined type, the null type, the type of an object literal or the anyFunctionType. This is because there are operations in the type checker that care about the presence of such types at arbitrary depth in a containing type.", "docstring_tokens": ["This", "function", "is", "used", "to", "propagate", "certain", "flags", "when", "creating", "new", "object", "type", "references", "and", "union", "types", ".", "It", "is", "only", "necessary", "to", "do", "so", "if", "a", "constituent", "type", "might", "be", "the", "undefined", "type", "the", "null", "type", "the", "type", "of", "an", "object", "literal", "or", "the", "anyFunctionType", ".", "This", "is", "because", "there", "are", "operations", "in", "the", "type", "checker", "that", "care", "about", "the", "presence", "of", "such", "types", "at", "arbitrary", "depth", "in", "a", "containing", "type", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L16894-L16901", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getTypeFromClassOrInterfaceReference", "original_string": "function getTypeFromClassOrInterfaceReference(node, symbol) {\n var type = getDeclaredTypeOfSymbol(symbol);\n var typeParameters = type.localTypeParameters;\n if (typeParameters) {\n if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) {\n error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), typeParameters.length);\n return unknownType;\n }\n // In a type reference, the outer type parameters of the referenced class or interface are automatically\n // supplied as type arguments and the type reference only specifies arguments for the local type parameters\n // of the class or interface.\n return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode)));\n }\n if (node.typeArguments) {\n error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type));\n return unknownType;\n }\n return type;\n }", "language": "javascript", "code": "function getTypeFromClassOrInterfaceReference(node, symbol) {\n var type = getDeclaredTypeOfSymbol(symbol);\n var typeParameters = type.localTypeParameters;\n if (typeParameters) {\n if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) {\n error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), typeParameters.length);\n return unknownType;\n }\n // In a type reference, the outer type parameters of the referenced class or interface are automatically\n // supplied as type arguments and the type reference only specifies arguments for the local type parameters\n // of the class or interface.\n return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode)));\n }\n if (node.typeArguments) {\n error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type));\n return unknownType;\n }\n return type;\n }", "code_tokens": ["function", "getTypeFromClassOrInterfaceReference", "(", "node", ",", "symbol", ")", "{", "var", "type", "=", "getDeclaredTypeOfSymbol", "(", "symbol", ")", ";", "var", "typeParameters", "=", "type", ".", "localTypeParameters", ";", "if", "(", "typeParameters", ")", "{", "if", "(", "!", "node", ".", "typeArguments", "||", "node", ".", "typeArguments", ".", "length", "!==", "typeParameters", ".", "length", ")", "{", "error", "(", "node", ",", "ts", ".", "Diagnostics", ".", "Generic_type_0_requires_1_type_argument_s", ",", "typeToString", "(", "type", ",", "undefined", ",", "1", ")", ",", "typeParameters", ".", "length", ")", ";", "return", "unknownType", ";", "}", "return", "createTypeReference", "(", "type", ",", "ts", ".", "concatenate", "(", "type", ".", "outerTypeParameters", ",", "ts", ".", "map", "(", "node", ".", "typeArguments", ",", "getTypeFromTypeNode", ")", ")", ")", ";", "}", "if", "(", "node", ".", "typeArguments", ")", "{", "error", "(", "node", ",", "ts", ".", "Diagnostics", ".", "Type_0_is_not_generic", ",", "typeToString", "(", "type", ")", ")", ";", "return", "unknownType", ";", "}", "return", "type", ";", "}"], "docstring": "Get type from reference to class or interface", "docstring_tokens": ["Get", "type", "from", "reference", "to", "class", "or", "interface"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L16958-L16976", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getTypeFromTypeAliasReference", "original_string": "function getTypeFromTypeAliasReference(node, symbol) {\n var type = getDeclaredTypeOfSymbol(symbol);\n var links = getSymbolLinks(symbol);\n var typeParameters = links.typeParameters;\n if (typeParameters) {\n if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) {\n error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length);\n return unknownType;\n }\n var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode);\n var id = getTypeListId(typeArguments);\n return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments)));\n }\n if (node.typeArguments) {\n error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol));\n return unknownType;\n }\n return type;\n }", "language": "javascript", "code": "function getTypeFromTypeAliasReference(node, symbol) {\n var type = getDeclaredTypeOfSymbol(symbol);\n var links = getSymbolLinks(symbol);\n var typeParameters = links.typeParameters;\n if (typeParameters) {\n if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) {\n error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length);\n return unknownType;\n }\n var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode);\n var id = getTypeListId(typeArguments);\n return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments)));\n }\n if (node.typeArguments) {\n error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol));\n return unknownType;\n }\n return type;\n }", "code_tokens": ["function", "getTypeFromTypeAliasReference", "(", "node", ",", "symbol", ")", "{", "var", "type", "=", "getDeclaredTypeOfSymbol", "(", "symbol", ")", ";", "var", "links", "=", "getSymbolLinks", "(", "symbol", ")", ";", "var", "typeParameters", "=", "links", ".", "typeParameters", ";", "if", "(", "typeParameters", ")", "{", "if", "(", "!", "node", ".", "typeArguments", "||", "node", ".", "typeArguments", ".", "length", "!==", "typeParameters", ".", "length", ")", "{", "error", "(", "node", ",", "ts", ".", "Diagnostics", ".", "Generic_type_0_requires_1_type_argument_s", ",", "symbolToString", "(", "symbol", ")", ",", "typeParameters", ".", "length", ")", ";", "return", "unknownType", ";", "}", "var", "typeArguments", "=", "ts", ".", "map", "(", "node", ".", "typeArguments", ",", "getTypeFromTypeNode", ")", ";", "var", "id", "=", "getTypeListId", "(", "typeArguments", ")", ";", "return", "links", ".", "instantiations", "[", "id", "]", "||", "(", "links", ".", "instantiations", "[", "id", "]", "=", "instantiateType", "(", "type", ",", "createTypeMapper", "(", "typeParameters", ",", "typeArguments", ")", ")", ")", ";", "}", "if", "(", "node", ".", "typeArguments", ")", "{", "error", "(", "node", ",", "ts", ".", "Diagnostics", ".", "Type_0_is_not_generic", ",", "symbolToString", "(", "symbol", ")", ")", ";", "return", "unknownType", ";", "}", "return", "type", ";", "}"], "docstring": "Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the declared type. Instantiations are cached using the type identities of the type arguments as the key.", "docstring_tokens": ["Get", "type", "from", "reference", "to", "type", "alias", ".", "When", "a", "type", "alias", "is", "generic", "the", "declared", "type", "of", "the", "type", "alias", "may", "include", "references", "to", "the", "type", "parameters", "of", "the", "alias", ".", "We", "replace", "those", "with", "the", "actual", "type", "arguments", "by", "instantiating", "the", "declared", "type", ".", "Instantiations", "are", "cached", "using", "the", "type", "identities", "of", "the", "type", "arguments", "as", "the", "key", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L16980-L16998", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "addTypesToSet", "original_string": "function addTypesToSet(typeSet, types, typeSetKind) {\n for (var _i = 0; _i < types.length; _i++) {\n var type = types[_i];\n addTypeToSet(typeSet, type, typeSetKind);\n }\n }", "language": "javascript", "code": "function addTypesToSet(typeSet, types, typeSetKind) {\n for (var _i = 0; _i < types.length; _i++) {\n var type = types[_i];\n addTypeToSet(typeSet, type, typeSetKind);\n }\n }", "code_tokens": ["function", "addTypesToSet", "(", "typeSet", ",", "types", ",", "typeSetKind", ")", "{", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "types", ".", "length", ";", "_i", "++", ")", "{", "var", "type", "=", "types", "[", "_i", "]", ";", "addTypeToSet", "(", "typeSet", ",", "type", ",", "typeSetKind", ")", ";", "}", "}"], "docstring": "Add the given types to the given type set. Order is preserved, duplicates are removed, and nested types of the given kind are flattened into the set.", "docstring_tokens": ["Add", "the", "given", "types", "to", "the", "given", "type", "set", ".", "Order", "is", "preserved", "duplicates", "are", "removed", "and", "nested", "types", "of", "the", "given", "kind", "are", "flattened", "into", "the", "set", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L17157-L17162", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "isKnownProperty", "original_string": "function isKnownProperty(type, name) {\n if (type.flags & 80896 /* ObjectType */) {\n var resolved = resolveStructuredTypeMembers(type);\n if (relation === assignableRelation && (type === globalObjectType || resolved.properties.length === 0) ||\n resolved.stringIndexType || resolved.numberIndexType || getPropertyOfType(type, name)) {\n return true;\n }\n return false;\n }\n if (type.flags & 49152 /* UnionOrIntersection */) {\n for (var _i = 0, _a = type.types; _i < _a.length; _i++) {\n var t = _a[_i];\n if (isKnownProperty(t, name)) {\n return true;\n }\n }\n return false;\n }\n return true;\n }", "language": "javascript", "code": "function isKnownProperty(type, name) {\n if (type.flags & 80896 /* ObjectType */) {\n var resolved = resolveStructuredTypeMembers(type);\n if (relation === assignableRelation && (type === globalObjectType || resolved.properties.length === 0) ||\n resolved.stringIndexType || resolved.numberIndexType || getPropertyOfType(type, name)) {\n return true;\n }\n return false;\n }\n if (type.flags & 49152 /* UnionOrIntersection */) {\n for (var _i = 0, _a = type.types; _i < _a.length; _i++) {\n var t = _a[_i];\n if (isKnownProperty(t, name)) {\n return true;\n }\n }\n return false;\n }\n return true;\n }", "code_tokens": ["function", "isKnownProperty", "(", "type", ",", "name", ")", "{", "if", "(", "type", ".", "flags", "&", "80896", ")", "{", "var", "resolved", "=", "resolveStructuredTypeMembers", "(", "type", ")", ";", "if", "(", "relation", "===", "assignableRelation", "&&", "(", "type", "===", "globalObjectType", "||", "resolved", ".", "properties", ".", "length", "===", "0", ")", "||", "resolved", ".", "stringIndexType", "||", "resolved", ".", "numberIndexType", "||", "getPropertyOfType", "(", "type", ",", "name", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "if", "(", "type", ".", "flags", "&", "49152", ")", "{", "for", "(", "var", "_i", "=", "0", ",", "_a", "=", "type", ".", "types", ";", "_i", "<", "_a", ".", "length", ";", "_i", "++", ")", "{", "var", "t", "=", "_a", "[", "_i", "]", ";", "if", "(", "isKnownProperty", "(", "t", ",", "name", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "return", "true", ";", "}"], "docstring": "Check if a property with the given name is known anywhere in the given type. In an object type, a property is considered known if the object type is empty and the check is for assignability, if the object type has index signatures, or if the property is actually declared in the object type. In a union or intersection type, a property is considered known if it is known in any constituent type.", "docstring_tokens": ["Check", "if", "a", "property", "with", "the", "given", "name", "is", "known", "anywhere", "in", "the", "given", "type", ".", "In", "an", "object", "type", "a", "property", "is", "considered", "known", "if", "the", "object", "type", "is", "empty", "and", "the", "check", "is", "for", "assignability", "if", "the", "object", "type", "has", "index", "signatures", "or", "if", "the", "property", "is", "actually", "declared", "in", "the", "object", "type", ".", "In", "a", "union", "or", "intersection", "type", "a", "property", "is", "considered", "known", "if", "it", "is", "known", "in", "any", "constituent", "type", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L17786-L17805", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "objectTypeRelatedTo", "original_string": "function objectTypeRelatedTo(source, target, reportErrors) {\n if (overflow) {\n return 0 /* False */;\n }\n var id = relation !== identityRelation || source.id < target.id ? source.id + \",\" + target.id : target.id + \",\" + source.id;\n var related = relation[id];\n if (related !== undefined) {\n // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate\n // errors, we can use the cached value. Otherwise, recompute the relation\n if (!elaborateErrors || (related === 3 /* FailedAndReported */)) {\n return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;\n }\n }\n if (depth > 0) {\n for (var i = 0; i < depth; i++) {\n // If source and target are already being compared, consider them related with assumptions\n if (maybeStack[i][id]) {\n return 1 /* Maybe */;\n }\n }\n if (depth === 100) {\n overflow = true;\n return 0 /* False */;\n }\n }\n else {\n sourceStack = [];\n targetStack = [];\n maybeStack = [];\n expandingFlags = 0;\n }\n sourceStack[depth] = source;\n targetStack[depth] = target;\n maybeStack[depth] = {};\n maybeStack[depth][id] = 1 /* Succeeded */;\n depth++;\n var saveExpandingFlags = expandingFlags;\n if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth))\n expandingFlags |= 1;\n if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth))\n expandingFlags |= 2;\n var result;\n if (expandingFlags === 3) {\n result = 1 /* Maybe */;\n }\n else {\n result = propertiesRelatedTo(source, target, reportErrors);\n if (result) {\n result &= signaturesRelatedTo(source, target, 0 /* Call */, reportErrors);\n if (result) {\n result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportErrors);\n if (result) {\n result &= stringIndexTypesRelatedTo(source, target, reportErrors);\n if (result) {\n result &= numberIndexTypesRelatedTo(source, target, reportErrors);\n }\n }\n }\n }\n }\n expandingFlags = saveExpandingFlags;\n depth--;\n if (result) {\n var maybeCache = maybeStack[depth];\n // If result is definitely true, copy assumptions to global cache, else copy to next level up\n var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1];\n ts.copyMap(maybeCache, destinationCache);\n }\n else {\n // A false result goes straight into global cache (when something is false under assumptions it\n // will also be false without assumptions)\n relation[id] = reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */;\n }\n return result;\n }", "language": "javascript", "code": "function objectTypeRelatedTo(source, target, reportErrors) {\n if (overflow) {\n return 0 /* False */;\n }\n var id = relation !== identityRelation || source.id < target.id ? source.id + \",\" + target.id : target.id + \",\" + source.id;\n var related = relation[id];\n if (related !== undefined) {\n // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate\n // errors, we can use the cached value. Otherwise, recompute the relation\n if (!elaborateErrors || (related === 3 /* FailedAndReported */)) {\n return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;\n }\n }\n if (depth > 0) {\n for (var i = 0; i < depth; i++) {\n // If source and target are already being compared, consider them related with assumptions\n if (maybeStack[i][id]) {\n return 1 /* Maybe */;\n }\n }\n if (depth === 100) {\n overflow = true;\n return 0 /* False */;\n }\n }\n else {\n sourceStack = [];\n targetStack = [];\n maybeStack = [];\n expandingFlags = 0;\n }\n sourceStack[depth] = source;\n targetStack[depth] = target;\n maybeStack[depth] = {};\n maybeStack[depth][id] = 1 /* Succeeded */;\n depth++;\n var saveExpandingFlags = expandingFlags;\n if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth))\n expandingFlags |= 1;\n if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth))\n expandingFlags |= 2;\n var result;\n if (expandingFlags === 3) {\n result = 1 /* Maybe */;\n }\n else {\n result = propertiesRelatedTo(source, target, reportErrors);\n if (result) {\n result &= signaturesRelatedTo(source, target, 0 /* Call */, reportErrors);\n if (result) {\n result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportErrors);\n if (result) {\n result &= stringIndexTypesRelatedTo(source, target, reportErrors);\n if (result) {\n result &= numberIndexTypesRelatedTo(source, target, reportErrors);\n }\n }\n }\n }\n }\n expandingFlags = saveExpandingFlags;\n depth--;\n if (result) {\n var maybeCache = maybeStack[depth];\n // If result is definitely true, copy assumptions to global cache, else copy to next level up\n var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1];\n ts.copyMap(maybeCache, destinationCache);\n }\n else {\n // A false result goes straight into global cache (when something is false under assumptions it\n // will also be false without assumptions)\n relation[id] = reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */;\n }\n return result;\n }", "code_tokens": ["function", "objectTypeRelatedTo", "(", "source", ",", "target", ",", "reportErrors", ")", "{", "if", "(", "overflow", ")", "{", "return", "0", ";", "}", "var", "id", "=", "relation", "!==", "identityRelation", "||", "source", ".", "id", "<", "target", ".", "id", "?", "source", ".", "id", "+", "\",\"", "+", "target", ".", "id", ":", "target", ".", "id", "+", "\",\"", "+", "source", ".", "id", ";", "var", "related", "=", "relation", "[", "id", "]", ";", "if", "(", "related", "!==", "undefined", ")", "{", "if", "(", "!", "elaborateErrors", "||", "(", "related", "===", "3", ")", ")", "{", "return", "related", "===", "1", "?", "-", "1", ":", "0", ";", "}", "}", "if", "(", "depth", ">", "0", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "depth", ";", "i", "++", ")", "{", "if", "(", "maybeStack", "[", "i", "]", "[", "id", "]", ")", "{", "return", "1", ";", "}", "}", "if", "(", "depth", "===", "100", ")", "{", "overflow", "=", "true", ";", "return", "0", ";", "}", "}", "else", "{", "sourceStack", "=", "[", "]", ";", "targetStack", "=", "[", "]", ";", "maybeStack", "=", "[", "]", ";", "expandingFlags", "=", "0", ";", "}", "sourceStack", "[", "depth", "]", "=", "source", ";", "targetStack", "[", "depth", "]", "=", "target", ";", "maybeStack", "[", "depth", "]", "=", "{", "}", ";", "maybeStack", "[", "depth", "]", "[", "id", "]", "=", "1", ";", "depth", "++", ";", "var", "saveExpandingFlags", "=", "expandingFlags", ";", "if", "(", "!", "(", "expandingFlags", "&", "1", ")", "&&", "isDeeplyNestedGeneric", "(", "source", ",", "sourceStack", ",", "depth", ")", ")", "expandingFlags", "|=", "1", ";", "if", "(", "!", "(", "expandingFlags", "&", "2", ")", "&&", "isDeeplyNestedGeneric", "(", "target", ",", "targetStack", ",", "depth", ")", ")", "expandingFlags", "|=", "2", ";", "var", "result", ";", "if", "(", "expandingFlags", "===", "3", ")", "{", "result", "=", "1", ";", "}", "else", "{", "result", "=", "propertiesRelatedTo", "(", "source", ",", "target", ",", "reportErrors", ")", ";", "if", "(", "result", ")", "{", "result", "&=", "signaturesRelatedTo", "(", "source", ",", "target", ",", "0", ",", "reportErrors", ")", ";", "if", "(", "result", ")", "{", "result", "&=", "signaturesRelatedTo", "(", "source", ",", "target", ",", "1", ",", "reportErrors", ")", ";", "if", "(", "result", ")", "{", "result", "&=", "stringIndexTypesRelatedTo", "(", "source", ",", "target", ",", "reportErrors", ")", ";", "if", "(", "result", ")", "{", "result", "&=", "numberIndexTypesRelatedTo", "(", "source", ",", "target", ",", "reportErrors", ")", ";", "}", "}", "}", "}", "}", "expandingFlags", "=", "saveExpandingFlags", ";", "depth", "--", ";", "if", "(", "result", ")", "{", "var", "maybeCache", "=", "maybeStack", "[", "depth", "]", ";", "var", "destinationCache", "=", "(", "result", "===", "-", "1", "||", "depth", "===", "0", ")", "?", "relation", ":", "maybeStack", "[", "depth", "-", "1", "]", ";", "ts", ".", "copyMap", "(", "maybeCache", ",", "destinationCache", ")", ";", "}", "else", "{", "relation", "[", "id", "]", "=", "reportErrors", "?", "3", ":", "2", ";", "}", "return", "result", ";", "}"], "docstring": "Determine if two object types are related by structure. First, check if the result is already available in the global cache. Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion and issue an error. Otherwise, actually compare the structure of the two types.", "docstring_tokens": ["Determine", "if", "two", "object", "types", "are", "related", "by", "structure", ".", "First", "check", "if", "the", "result", "is", "already", "available", "in", "the", "global", "cache", ".", "Second", "check", "if", "we", "have", "already", "started", "a", "comparison", "of", "the", "given", "two", "types", "in", "which", "case", "we", "assume", "the", "result", "to", "be", "true", ".", "Third", "check", "if", "both", "types", "are", "part", "of", "deeply", "nested", "chains", "of", "generic", "type", "instantiations", "and", "if", "so", "assume", "the", "types", "are", "equal", "and", "infinitely", "expanding", ".", "Fourth", "if", "we", "have", "reached", "a", "depth", "of", "100", "nested", "comparisons", "assume", "we", "have", "runaway", "recursion", "and", "issue", "an", "error", ".", "Otherwise", "actually", "compare", "the", "structure", "of", "the", "two", "types", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L17914-L17988", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "isDeeplyNestedGeneric", "original_string": "function isDeeplyNestedGeneric(type, stack, depth) {\n // We track type references (created by createTypeReference) and instantiated types (created by instantiateType)\n if (type.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && depth >= 5) {\n var symbol = type.symbol;\n var count = 0;\n for (var i = 0; i < depth; i++) {\n var t = stack[i];\n if (t.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && t.symbol === symbol) {\n count++;\n if (count >= 5)\n return true;\n }\n }\n }\n return false;\n }", "language": "javascript", "code": "function isDeeplyNestedGeneric(type, stack, depth) {\n // We track type references (created by createTypeReference) and instantiated types (created by instantiateType)\n if (type.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && depth >= 5) {\n var symbol = type.symbol;\n var count = 0;\n for (var i = 0; i < depth; i++) {\n var t = stack[i];\n if (t.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && t.symbol === symbol) {\n count++;\n if (count >= 5)\n return true;\n }\n }\n }\n return false;\n }", "code_tokens": ["function", "isDeeplyNestedGeneric", "(", "type", ",", "stack", ",", "depth", ")", "{", "if", "(", "type", ".", "flags", "&", "(", "4096", "|", "131072", ")", "&&", "depth", ">=", "5", ")", "{", "var", "symbol", "=", "type", ".", "symbol", ";", "var", "count", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "depth", ";", "i", "++", ")", "{", "var", "t", "=", "stack", "[", "i", "]", ";", "if", "(", "t", ".", "flags", "&", "(", "4096", "|", "131072", ")", "&&", "t", ".", "symbol", "===", "symbol", ")", "{", "count", "++", ";", "if", "(", "count", ">=", "5", ")", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}"], "docstring": "Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case when structural type comparisons have been started for 10 or more instantiations of the same generic type. It is possible, though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 10 levels, but unequal at some level beyond that.", "docstring_tokens": ["Return", "true", "if", "the", "given", "type", "is", "part", "of", "a", "deeply", "nested", "chain", "of", "generic", "instantiations", ".", "We", "consider", "this", "to", "be", "the", "case", "when", "structural", "type", "comparisons", "have", "been", "started", "for", "10", "or", "more", "instantiations", "of", "the", "same", "generic", "type", ".", "It", "is", "possible", "though", "highly", "unlikely", "for", "this", "test", "to", "be", "true", "in", "a", "situation", "where", "a", "chain", "of", "instantiations", "is", "not", "infinitely", "expanding", ".", "Effectively", "we", "will", "generate", "a", "false", "positive", "when", "two", "types", "are", "structurally", "equal", "to", "at", "least", "10", "levels", "but", "unequal", "at", "some", "level", "beyond", "that", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L18338-L18353", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "isVariableAssignedWithin", "original_string": "function isVariableAssignedWithin(symbol, node) {\n var links = getNodeLinks(node);\n if (links.assignmentChecks) {\n var cachedResult = links.assignmentChecks[symbol.id];\n if (cachedResult !== undefined) {\n return cachedResult;\n }\n }\n else {\n links.assignmentChecks = {};\n }\n return links.assignmentChecks[symbol.id] = isAssignedIn(node);\n function isAssignedInBinaryExpression(node) {\n if (node.operatorToken.kind >= 56 /* FirstAssignment */ && node.operatorToken.kind <= 68 /* LastAssignment */) {\n var n = node.left;\n while (n.kind === 172 /* ParenthesizedExpression */) {\n n = n.expression;\n }\n if (n.kind === 69 /* Identifier */ && getResolvedSymbol(n) === symbol) {\n return true;\n }\n }\n return ts.forEachChild(node, isAssignedIn);\n }\n function isAssignedInVariableDeclaration(node) {\n if (!ts.isBindingPattern(node.name) && getSymbolOfNode(node) === symbol && hasInitializer(node)) {\n return true;\n }\n return ts.forEachChild(node, isAssignedIn);\n }\n function isAssignedIn(node) {\n switch (node.kind) {\n case 181 /* BinaryExpression */:\n return isAssignedInBinaryExpression(node);\n case 211 /* VariableDeclaration */:\n case 163 /* BindingElement */:\n return isAssignedInVariableDeclaration(node);\n case 161 /* ObjectBindingPattern */:\n case 162 /* ArrayBindingPattern */:\n case 164 /* ArrayLiteralExpression */:\n case 165 /* ObjectLiteralExpression */:\n case 166 /* PropertyAccessExpression */:\n case 167 /* ElementAccessExpression */:\n case 168 /* CallExpression */:\n case 169 /* NewExpression */:\n case 171 /* TypeAssertionExpression */:\n case 189 /* AsExpression */:\n case 172 /* ParenthesizedExpression */:\n case 179 /* PrefixUnaryExpression */:\n case 175 /* DeleteExpression */:\n case 178 /* AwaitExpression */:\n case 176 /* TypeOfExpression */:\n case 177 /* VoidExpression */:\n case 180 /* PostfixUnaryExpression */:\n case 184 /* YieldExpression */:\n case 182 /* ConditionalExpression */:\n case 185 /* SpreadElementExpression */:\n case 192 /* Block */:\n case 193 /* VariableStatement */:\n case 195 /* ExpressionStatement */:\n case 196 /* IfStatement */:\n case 197 /* DoStatement */:\n case 198 /* WhileStatement */:\n case 199 /* ForStatement */:\n case 200 /* ForInStatement */:\n case 201 /* ForOfStatement */:\n case 204 /* ReturnStatement */:\n case 205 /* WithStatement */:\n case 206 /* SwitchStatement */:\n case 241 /* CaseClause */:\n case 242 /* DefaultClause */:\n case 207 /* LabeledStatement */:\n case 208 /* ThrowStatement */:\n case 209 /* TryStatement */:\n case 244 /* CatchClause */:\n case 233 /* JsxElement */:\n case 234 /* JsxSelfClosingElement */:\n case 238 /* JsxAttribute */:\n case 239 /* JsxSpreadAttribute */:\n case 235 /* JsxOpeningElement */:\n case 240 /* JsxExpression */:\n return ts.forEachChild(node, isAssignedIn);\n }\n return false;\n }\n }", "language": "javascript", "code": "function isVariableAssignedWithin(symbol, node) {\n var links = getNodeLinks(node);\n if (links.assignmentChecks) {\n var cachedResult = links.assignmentChecks[symbol.id];\n if (cachedResult !== undefined) {\n return cachedResult;\n }\n }\n else {\n links.assignmentChecks = {};\n }\n return links.assignmentChecks[symbol.id] = isAssignedIn(node);\n function isAssignedInBinaryExpression(node) {\n if (node.operatorToken.kind >= 56 /* FirstAssignment */ && node.operatorToken.kind <= 68 /* LastAssignment */) {\n var n = node.left;\n while (n.kind === 172 /* ParenthesizedExpression */) {\n n = n.expression;\n }\n if (n.kind === 69 /* Identifier */ && getResolvedSymbol(n) === symbol) {\n return true;\n }\n }\n return ts.forEachChild(node, isAssignedIn);\n }\n function isAssignedInVariableDeclaration(node) {\n if (!ts.isBindingPattern(node.name) && getSymbolOfNode(node) === symbol && hasInitializer(node)) {\n return true;\n }\n return ts.forEachChild(node, isAssignedIn);\n }\n function isAssignedIn(node) {\n switch (node.kind) {\n case 181 /* BinaryExpression */:\n return isAssignedInBinaryExpression(node);\n case 211 /* VariableDeclaration */:\n case 163 /* BindingElement */:\n return isAssignedInVariableDeclaration(node);\n case 161 /* ObjectBindingPattern */:\n case 162 /* ArrayBindingPattern */:\n case 164 /* ArrayLiteralExpression */:\n case 165 /* ObjectLiteralExpression */:\n case 166 /* PropertyAccessExpression */:\n case 167 /* ElementAccessExpression */:\n case 168 /* CallExpression */:\n case 169 /* NewExpression */:\n case 171 /* TypeAssertionExpression */:\n case 189 /* AsExpression */:\n case 172 /* ParenthesizedExpression */:\n case 179 /* PrefixUnaryExpression */:\n case 175 /* DeleteExpression */:\n case 178 /* AwaitExpression */:\n case 176 /* TypeOfExpression */:\n case 177 /* VoidExpression */:\n case 180 /* PostfixUnaryExpression */:\n case 184 /* YieldExpression */:\n case 182 /* ConditionalExpression */:\n case 185 /* SpreadElementExpression */:\n case 192 /* Block */:\n case 193 /* VariableStatement */:\n case 195 /* ExpressionStatement */:\n case 196 /* IfStatement */:\n case 197 /* DoStatement */:\n case 198 /* WhileStatement */:\n case 199 /* ForStatement */:\n case 200 /* ForInStatement */:\n case 201 /* ForOfStatement */:\n case 204 /* ReturnStatement */:\n case 205 /* WithStatement */:\n case 206 /* SwitchStatement */:\n case 241 /* CaseClause */:\n case 242 /* DefaultClause */:\n case 207 /* LabeledStatement */:\n case 208 /* ThrowStatement */:\n case 209 /* TryStatement */:\n case 244 /* CatchClause */:\n case 233 /* JsxElement */:\n case 234 /* JsxSelfClosingElement */:\n case 238 /* JsxAttribute */:\n case 239 /* JsxSpreadAttribute */:\n case 235 /* JsxOpeningElement */:\n case 240 /* JsxExpression */:\n return ts.forEachChild(node, isAssignedIn);\n }\n return false;\n }\n }", "code_tokens": ["function", "isVariableAssignedWithin", "(", "symbol", ",", "node", ")", "{", "var", "links", "=", "getNodeLinks", "(", "node", ")", ";", "if", "(", "links", ".", "assignmentChecks", ")", "{", "var", "cachedResult", "=", "links", ".", "assignmentChecks", "[", "symbol", ".", "id", "]", ";", "if", "(", "cachedResult", "!==", "undefined", ")", "{", "return", "cachedResult", ";", "}", "}", "else", "{", "links", ".", "assignmentChecks", "=", "{", "}", ";", "}", "return", "links", ".", "assignmentChecks", "[", "symbol", ".", "id", "]", "=", "isAssignedIn", "(", "node", ")", ";", "function", "isAssignedInBinaryExpression", "(", "node", ")", "{", "if", "(", "node", ".", "operatorToken", ".", "kind", ">=", "56", "&&", "node", ".", "operatorToken", ".", "kind", "<=", "68", ")", "{", "var", "n", "=", "node", ".", "left", ";", "while", "(", "n", ".", "kind", "===", "172", ")", "{", "n", "=", "n", ".", "expression", ";", "}", "if", "(", "n", ".", "kind", "===", "69", "&&", "getResolvedSymbol", "(", "n", ")", "===", "symbol", ")", "{", "return", "true", ";", "}", "}", "return", "ts", ".", "forEachChild", "(", "node", ",", "isAssignedIn", ")", ";", "}", "function", "isAssignedInVariableDeclaration", "(", "node", ")", "{", "if", "(", "!", "ts", ".", "isBindingPattern", "(", "node", ".", "name", ")", "&&", "getSymbolOfNode", "(", "node", ")", "===", "symbol", "&&", "hasInitializer", "(", "node", ")", ")", "{", "return", "true", ";", "}", "return", "ts", ".", "forEachChild", "(", "node", ",", "isAssignedIn", ")", ";", "}", "function", "isAssignedIn", "(", "node", ")", "{", "switch", "(", "node", ".", "kind", ")", "{", "case", "181", ":", "return", "isAssignedInBinaryExpression", "(", "node", ")", ";", "case", "211", ":", "case", "163", ":", "return", "isAssignedInVariableDeclaration", "(", "node", ")", ";", "case", "161", ":", "case", "162", ":", "case", "164", ":", "case", "165", ":", "case", "166", ":", "case", "167", ":", "case", "168", ":", "case", "169", ":", "case", "171", ":", "case", "189", ":", "case", "172", ":", "case", "179", ":", "case", "175", ":", "case", "178", ":", "case", "176", ":", "case", "177", ":", "case", "180", ":", "case", "184", ":", "case", "182", ":", "case", "185", ":", "case", "192", ":", "case", "193", ":", "case", "195", ":", "case", "196", ":", "case", "197", ":", "case", "198", ":", "case", "199", ":", "case", "200", ":", "case", "201", ":", "case", "204", ":", "case", "205", ":", "case", "206", ":", "case", "241", ":", "case", "242", ":", "case", "207", ":", "case", "208", ":", "case", "209", ":", "case", "244", ":", "case", "233", ":", "case", "234", ":", "case", "238", ":", "case", "239", ":", "case", "235", ":", "case", "240", ":", "return", "ts", ".", "forEachChild", "(", "node", ",", "isAssignedIn", ")", ";", "}", "return", "false", ";", "}", "}"], "docstring": "Check if a given variable is assigned within a given syntax node", "docstring_tokens": ["Check", "if", "a", "given", "variable", "is", "assigned", "within", "a", "given", "syntax", "node"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L18949-L19034", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "narrowType", "original_string": "function narrowType(type, expr, assumeTrue) {\n switch (expr.kind) {\n case 168 /* CallExpression */:\n return narrowTypeByTypePredicate(type, expr, assumeTrue);\n case 172 /* ParenthesizedExpression */:\n return narrowType(type, expr.expression, assumeTrue);\n case 181 /* BinaryExpression */:\n var operator = expr.operatorToken.kind;\n if (operator === 32 /* EqualsEqualsEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) {\n return narrowTypeByEquality(type, expr, assumeTrue);\n }\n else if (operator === 51 /* AmpersandAmpersandToken */) {\n return narrowTypeByAnd(type, expr, assumeTrue);\n }\n else if (operator === 52 /* BarBarToken */) {\n return narrowTypeByOr(type, expr, assumeTrue);\n }\n else if (operator === 91 /* InstanceOfKeyword */) {\n return narrowTypeByInstanceof(type, expr, assumeTrue);\n }\n break;\n case 179 /* PrefixUnaryExpression */:\n if (expr.operator === 49 /* ExclamationToken */) {\n return narrowType(type, expr.operand, !assumeTrue);\n }\n break;\n }\n return type;\n }", "language": "javascript", "code": "function narrowType(type, expr, assumeTrue) {\n switch (expr.kind) {\n case 168 /* CallExpression */:\n return narrowTypeByTypePredicate(type, expr, assumeTrue);\n case 172 /* ParenthesizedExpression */:\n return narrowType(type, expr.expression, assumeTrue);\n case 181 /* BinaryExpression */:\n var operator = expr.operatorToken.kind;\n if (operator === 32 /* EqualsEqualsEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) {\n return narrowTypeByEquality(type, expr, assumeTrue);\n }\n else if (operator === 51 /* AmpersandAmpersandToken */) {\n return narrowTypeByAnd(type, expr, assumeTrue);\n }\n else if (operator === 52 /* BarBarToken */) {\n return narrowTypeByOr(type, expr, assumeTrue);\n }\n else if (operator === 91 /* InstanceOfKeyword */) {\n return narrowTypeByInstanceof(type, expr, assumeTrue);\n }\n break;\n case 179 /* PrefixUnaryExpression */:\n if (expr.operator === 49 /* ExclamationToken */) {\n return narrowType(type, expr.operand, !assumeTrue);\n }\n break;\n }\n return type;\n }", "code_tokens": ["function", "narrowType", "(", "type", ",", "expr", ",", "assumeTrue", ")", "{", "switch", "(", "expr", ".", "kind", ")", "{", "case", "168", ":", "return", "narrowTypeByTypePredicate", "(", "type", ",", "expr", ",", "assumeTrue", ")", ";", "case", "172", ":", "return", "narrowType", "(", "type", ",", "expr", ".", "expression", ",", "assumeTrue", ")", ";", "case", "181", ":", "var", "operator", "=", "expr", ".", "operatorToken", ".", "kind", ";", "if", "(", "operator", "===", "32", "||", "operator", "===", "33", ")", "{", "return", "narrowTypeByEquality", "(", "type", ",", "expr", ",", "assumeTrue", ")", ";", "}", "else", "if", "(", "operator", "===", "51", ")", "{", "return", "narrowTypeByAnd", "(", "type", ",", "expr", ",", "assumeTrue", ")", ";", "}", "else", "if", "(", "operator", "===", "52", ")", "{", "return", "narrowTypeByOr", "(", "type", ",", "expr", ",", "assumeTrue", ")", ";", "}", "else", "if", "(", "operator", "===", "91", ")", "{", "return", "narrowTypeByInstanceof", "(", "type", ",", "expr", ",", "assumeTrue", ")", ";", "}", "break", ";", "case", "179", ":", "if", "(", "expr", ".", "operator", "===", "49", ")", "{", "return", "narrowType", "(", "type", ",", "expr", ".", "operand", ",", "!", "assumeTrue", ")", ";", "}", "break", ";", "}", "return", "type", ";", "}"], "docstring": "Narrow the given type based on the given expression having the assumed boolean value. The returned type will be a subtype or the same type as the argument.", "docstring_tokens": ["Narrow", "the", "given", "type", "based", "on", "the", "given", "expression", "having", "the", "assumed", "boolean", "value", ".", "The", "returned", "type", "will", "be", "a", "subtype", "or", "the", "same", "type", "as", "the", "argument", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L19228-L19256", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getContextuallyTypedParameterType", "original_string": "function getContextuallyTypedParameterType(parameter) {\n var func = parameter.parent;\n if (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) {\n if (isContextSensitive(func)) {\n var contextualSignature = getContextualSignature(func);\n if (contextualSignature) {\n var funcHasRestParameters = ts.hasRestParameter(func);\n var len = func.parameters.length - (funcHasRestParameters ? 1 : 0);\n var indexOfParameter = ts.indexOf(func.parameters, parameter);\n if (indexOfParameter < len) {\n return getTypeAtPosition(contextualSignature, indexOfParameter);\n }\n // If last parameter is contextually rest parameter get its type\n if (funcHasRestParameters &&\n indexOfParameter === (func.parameters.length - 1) &&\n isRestParameterIndex(contextualSignature, func.parameters.length - 1)) {\n return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters));\n }\n }\n }\n }\n return undefined;\n }", "language": "javascript", "code": "function getContextuallyTypedParameterType(parameter) {\n var func = parameter.parent;\n if (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) {\n if (isContextSensitive(func)) {\n var contextualSignature = getContextualSignature(func);\n if (contextualSignature) {\n var funcHasRestParameters = ts.hasRestParameter(func);\n var len = func.parameters.length - (funcHasRestParameters ? 1 : 0);\n var indexOfParameter = ts.indexOf(func.parameters, parameter);\n if (indexOfParameter < len) {\n return getTypeAtPosition(contextualSignature, indexOfParameter);\n }\n // If last parameter is contextually rest parameter get its type\n if (funcHasRestParameters &&\n indexOfParameter === (func.parameters.length - 1) &&\n isRestParameterIndex(contextualSignature, func.parameters.length - 1)) {\n return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters));\n }\n }\n }\n }\n return undefined;\n }", "code_tokens": ["function", "getContextuallyTypedParameterType", "(", "parameter", ")", "{", "var", "func", "=", "parameter", ".", "parent", ";", "if", "(", "isFunctionExpressionOrArrowFunction", "(", "func", ")", "||", "ts", ".", "isObjectLiteralMethod", "(", "func", ")", ")", "{", "if", "(", "isContextSensitive", "(", "func", ")", ")", "{", "var", "contextualSignature", "=", "getContextualSignature", "(", "func", ")", ";", "if", "(", "contextualSignature", ")", "{", "var", "funcHasRestParameters", "=", "ts", ".", "hasRestParameter", "(", "func", ")", ";", "var", "len", "=", "func", ".", "parameters", ".", "length", "-", "(", "funcHasRestParameters", "?", "1", ":", "0", ")", ";", "var", "indexOfParameter", "=", "ts", ".", "indexOf", "(", "func", ".", "parameters", ",", "parameter", ")", ";", "if", "(", "indexOfParameter", "<", "len", ")", "{", "return", "getTypeAtPosition", "(", "contextualSignature", ",", "indexOfParameter", ")", ";", "}", "if", "(", "funcHasRestParameters", "&&", "indexOfParameter", "===", "(", "func", ".", "parameters", ".", "length", "-", "1", ")", "&&", "isRestParameterIndex", "(", "contextualSignature", ",", "func", ".", "parameters", ".", "length", "-", "1", ")", ")", "{", "return", "getTypeOfSymbol", "(", "ts", ".", "lastOrUndefined", "(", "contextualSignature", ".", "parameters", ")", ")", ";", "}", "}", "}", "}", "return", "undefined", ";", "}"], "docstring": "Return contextual type of parameter or undefined if no contextual type is available", "docstring_tokens": ["Return", "contextual", "type", "of", "parameter", "or", "undefined", "if", "no", "contextual", "type", "is", "available"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L19488-L19510", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getContextualTypeForInitializerExpression", "original_string": "function getContextualTypeForInitializerExpression(node) {\n var declaration = node.parent;\n if (node === declaration.initializer) {\n if (declaration.type) {\n return getTypeFromTypeNode(declaration.type);\n }\n if (declaration.kind === 138 /* Parameter */) {\n var type = getContextuallyTypedParameterType(declaration);\n if (type) {\n return type;\n }\n }\n if (ts.isBindingPattern(declaration.name)) {\n return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true);\n }\n }\n return undefined;\n }", "language": "javascript", "code": "function getContextualTypeForInitializerExpression(node) {\n var declaration = node.parent;\n if (node === declaration.initializer) {\n if (declaration.type) {\n return getTypeFromTypeNode(declaration.type);\n }\n if (declaration.kind === 138 /* Parameter */) {\n var type = getContextuallyTypedParameterType(declaration);\n if (type) {\n return type;\n }\n }\n if (ts.isBindingPattern(declaration.name)) {\n return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true);\n }\n }\n return undefined;\n }", "code_tokens": ["function", "getContextualTypeForInitializerExpression", "(", "node", ")", "{", "var", "declaration", "=", "node", ".", "parent", ";", "if", "(", "node", "===", "declaration", ".", "initializer", ")", "{", "if", "(", "declaration", ".", "type", ")", "{", "return", "getTypeFromTypeNode", "(", "declaration", ".", "type", ")", ";", "}", "if", "(", "declaration", ".", "kind", "===", "138", ")", "{", "var", "type", "=", "getContextuallyTypedParameterType", "(", "declaration", ")", ";", "if", "(", "type", ")", "{", "return", "type", ";", "}", "}", "if", "(", "ts", ".", "isBindingPattern", "(", "declaration", ".", "name", ")", ")", "{", "return", "getTypeFromBindingPattern", "(", "declaration", ".", "name", ",", "true", ")", ";", "}", "}", "return", "undefined", ";", "}"], "docstring": "In a variable, parameter or property declaration with a type annotation, the contextual type of an initializer expression is the type of the variable, parameter or property. Otherwise, in a parameter declaration of a contextually typed function expression, the contextual type of an initializer expression is the contextual type of the parameter. Otherwise, in a variable or parameter declaration with a binding pattern name, the contextual type of an initializer expression is the type implied by the binding pattern.", "docstring_tokens": ["In", "a", "variable", "parameter", "or", "property", "declaration", "with", "a", "type", "annotation", "the", "contextual", "type", "of", "an", "initializer", "expression", "is", "the", "type", "of", "the", "variable", "parameter", "or", "property", ".", "Otherwise", "in", "a", "parameter", "declaration", "of", "a", "contextually", "typed", "function", "expression", "the", "contextual", "type", "of", "an", "initializer", "expression", "is", "the", "contextual", "type", "of", "the", "parameter", ".", "Otherwise", "in", "a", "variable", "or", "parameter", "declaration", "with", "a", "binding", "pattern", "name", "the", "contextual", "type", "of", "an", "initializer", "expression", "is", "the", "type", "implied", "by", "the", "binding", "pattern", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L19516-L19533", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "applyToContextualType", "original_string": "function applyToContextualType(type, mapper) {\n if (!(type.flags & 16384 /* Union */)) {\n return mapper(type);\n }\n var types = type.types;\n var mappedType;\n var mappedTypes;\n for (var _i = 0; _i < types.length; _i++) {\n var current = types[_i];\n var t = mapper(current);\n if (t) {\n if (!mappedType) {\n mappedType = t;\n }\n else if (!mappedTypes) {\n mappedTypes = [mappedType, t];\n }\n else {\n mappedTypes.push(t);\n }\n }\n }\n return mappedTypes ? getUnionType(mappedTypes) : mappedType;\n }", "language": "javascript", "code": "function applyToContextualType(type, mapper) {\n if (!(type.flags & 16384 /* Union */)) {\n return mapper(type);\n }\n var types = type.types;\n var mappedType;\n var mappedTypes;\n for (var _i = 0; _i < types.length; _i++) {\n var current = types[_i];\n var t = mapper(current);\n if (t) {\n if (!mappedType) {\n mappedType = t;\n }\n else if (!mappedTypes) {\n mappedTypes = [mappedType, t];\n }\n else {\n mappedTypes.push(t);\n }\n }\n }\n return mappedTypes ? getUnionType(mappedTypes) : mappedType;\n }", "code_tokens": ["function", "applyToContextualType", "(", "type", ",", "mapper", ")", "{", "if", "(", "!", "(", "type", ".", "flags", "&", "16384", ")", ")", "{", "return", "mapper", "(", "type", ")", ";", "}", "var", "types", "=", "type", ".", "types", ";", "var", "mappedType", ";", "var", "mappedTypes", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "types", ".", "length", ";", "_i", "++", ")", "{", "var", "current", "=", "types", "[", "_i", "]", ";", "var", "t", "=", "mapper", "(", "current", ")", ";", "if", "(", "t", ")", "{", "if", "(", "!", "mappedType", ")", "{", "mappedType", "=", "t", ";", "}", "else", "if", "(", "!", "mappedTypes", ")", "{", "mappedTypes", "=", "[", "mappedType", ",", "t", "]", ";", "}", "else", "{", "mappedTypes", ".", "push", "(", "t", ")", ";", "}", "}", "}", "return", "mappedTypes", "?", "getUnionType", "(", "mappedTypes", ")", ":", "mappedType", ";", "}"], "docstring": "Apply a mapping function to a contextual type and return the resulting type. If the contextual type is a union type, the mapping function is applied to each constituent type and a union of the resulting types is returned.", "docstring_tokens": ["Apply", "a", "mapping", "function", "to", "a", "contextual", "type", "and", "return", "the", "resulting", "type", ".", "If", "the", "contextual", "type", "is", "a", "union", "type", "the", "mapping", "function", "is", "applied", "to", "each", "constituent", "type", "and", "a", "union", "of", "the", "resulting", "types", "is", "returned", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L19617-L19640", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "contextualTypeHasIndexSignature", "original_string": "function contextualTypeHasIndexSignature(type, kind) {\n return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, function (t) { return getIndexTypeOfStructuredType(t, kind); }) : getIndexTypeOfStructuredType(type, kind));\n }", "language": "javascript", "code": "function contextualTypeHasIndexSignature(type, kind) {\n return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, function (t) { return getIndexTypeOfStructuredType(t, kind); }) : getIndexTypeOfStructuredType(type, kind));\n }", "code_tokens": ["function", "contextualTypeHasIndexSignature", "(", "type", ",", "kind", ")", "{", "return", "!", "!", "(", "type", ".", "flags", "&", "16384", "?", "ts", ".", "forEach", "(", "type", ".", "types", ",", "function", "(", "t", ")", "{", "return", "getIndexTypeOfStructuredType", "(", "t", ",", "kind", ")", ";", "}", ")", ":", "getIndexTypeOfStructuredType", "(", "type", ",", "kind", ")", ")", ";", "}"], "docstring": "Return true if the given contextual type provides an index signature of the given kind", "docstring_tokens": ["Return", "true", "if", "the", "given", "contextual", "type", "provides", "an", "index", "signature", "of", "the", "given", "kind"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L19655-L19657", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getContextualTypeForObjectLiteralMethod", "original_string": "function getContextualTypeForObjectLiteralMethod(node) {\n ts.Debug.assert(ts.isObjectLiteralMethod(node));\n if (isInsideWithStatementBody(node)) {\n // We cannot answer semantic questions within a with block, do not proceed any further\n return undefined;\n }\n return getContextualTypeForObjectLiteralElement(node);\n }", "language": "javascript", "code": "function getContextualTypeForObjectLiteralMethod(node) {\n ts.Debug.assert(ts.isObjectLiteralMethod(node));\n if (isInsideWithStatementBody(node)) {\n // We cannot answer semantic questions within a with block, do not proceed any further\n return undefined;\n }\n return getContextualTypeForObjectLiteralElement(node);\n }", "code_tokens": ["function", "getContextualTypeForObjectLiteralMethod", "(", "node", ")", "{", "ts", ".", "Debug", ".", "assert", "(", "ts", ".", "isObjectLiteralMethod", "(", "node", ")", ")", ";", "if", "(", "isInsideWithStatementBody", "(", "node", ")", ")", "{", "return", "undefined", ";", "}", "return", "getContextualTypeForObjectLiteralElement", "(", "node", ")", ";", "}"], "docstring": "In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one exists. Otherwise, it is the type of the string index signature in T, if one exists.", "docstring_tokens": ["In", "an", "object", "literal", "contextually", "typed", "by", "a", "type", "T", "the", "contextual", "type", "of", "a", "property", "assignment", "is", "the", "type", "of", "the", "matching", "property", "in", "T", "if", "one", "exists", ".", "Otherwise", "it", "is", "the", "type", "of", "the", "numeric", "index", "signature", "in", "T", "if", "one", "exists", ".", "Otherwise", "it", "is", "the", "type", "of", "the", "string", "index", "signature", "in", "T", "if", "one", "exists", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L19661-L19668", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getContextualTypeForElementExpression", "original_string": "function getContextualTypeForElementExpression(node) {\n var arrayLiteral = node.parent;\n var type = getContextualType(arrayLiteral);\n if (type) {\n var index = ts.indexOf(arrayLiteral.elements, node);\n return getTypeOfPropertyOfContextualType(type, \"\" + index)\n || getIndexTypeOfContextualType(type, 1 /* Number */)\n || (languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined);\n }\n return undefined;\n }", "language": "javascript", "code": "function getContextualTypeForElementExpression(node) {\n var arrayLiteral = node.parent;\n var type = getContextualType(arrayLiteral);\n if (type) {\n var index = ts.indexOf(arrayLiteral.elements, node);\n return getTypeOfPropertyOfContextualType(type, \"\" + index)\n || getIndexTypeOfContextualType(type, 1 /* Number */)\n || (languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined);\n }\n return undefined;\n }", "code_tokens": ["function", "getContextualTypeForElementExpression", "(", "node", ")", "{", "var", "arrayLiteral", "=", "node", ".", "parent", ";", "var", "type", "=", "getContextualType", "(", "arrayLiteral", ")", ";", "if", "(", "type", ")", "{", "var", "index", "=", "ts", ".", "indexOf", "(", "arrayLiteral", ".", "elements", ",", "node", ")", ";", "return", "getTypeOfPropertyOfContextualType", "(", "type", ",", "\"\"", "+", "index", ")", "||", "getIndexTypeOfContextualType", "(", "type", ",", "1", ")", "||", "(", "languageVersion", ">=", "2", "?", "getElementTypeOfIterable", "(", "type", ",", "undefined", ")", ":", "undefined", ")", ";", "}", "return", "undefined", ";", "}"], "docstring": "In an array literal contextually typed by a type T, the contextual type of an element expression at index N is the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated type of T.", "docstring_tokens": ["In", "an", "array", "literal", "contextually", "typed", "by", "a", "type", "T", "the", "contextual", "type", "of", "an", "element", "expression", "at", "index", "N", "is", "the", "type", "of", "the", "property", "with", "the", "numeric", "name", "N", "in", "T", "if", "one", "exists", ".", "Otherwise", "if", "T", "has", "a", "numeric", "index", "signature", "it", "is", "the", "type", "of", "the", "numeric", "index", "signature", "in", "T", ".", "Otherwise", "in", "ES6", "and", "higher", "the", "contextual", "type", "is", "the", "iterated", "type", "of", "T", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L19692-L19702", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getNonGenericSignature", "original_string": "function getNonGenericSignature(type) {\n var signatures = getSignaturesOfStructuredType(type, 0 /* Call */);\n if (signatures.length === 1) {\n var signature = signatures[0];\n if (!signature.typeParameters) {\n return signature;\n }\n }\n }", "language": "javascript", "code": "function getNonGenericSignature(type) {\n var signatures = getSignaturesOfStructuredType(type, 0 /* Call */);\n if (signatures.length === 1) {\n var signature = signatures[0];\n if (!signature.typeParameters) {\n return signature;\n }\n }\n }", "code_tokens": ["function", "getNonGenericSignature", "(", "type", ")", "{", "var", "signatures", "=", "getSignaturesOfStructuredType", "(", "type", ",", "0", ")", ";", "if", "(", "signatures", ".", "length", "===", "1", ")", "{", "var", "signature", "=", "signatures", "[", "0", "]", ";", "if", "(", "!", "signature", ".", "typeParameters", ")", "{", "return", "signature", ";", "}", "}", "}"], "docstring": "If the given type is an object or union type, if that type has a single signature, and if that signature is non-generic, return the signature. Otherwise return undefined.", "docstring_tokens": ["If", "the", "given", "type", "is", "an", "object", "or", "union", "type", "if", "that", "type", "has", "a", "single", "signature", "and", "if", "that", "signature", "is", "non", "-", "generic", "return", "the", "signature", ".", "Otherwise", "return", "undefined", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L19779-L19787", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getContextualSignature", "original_string": "function getContextualSignature(node) {\n ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));\n var type = ts.isObjectLiteralMethod(node)\n ? getContextualTypeForObjectLiteralMethod(node)\n : getContextualType(node);\n if (!type) {\n return undefined;\n }\n if (!(type.flags & 16384 /* Union */)) {\n return getNonGenericSignature(type);\n }\n var signatureList;\n var types = type.types;\n for (var _i = 0; _i < types.length; _i++) {\n var current = types[_i];\n var signature = getNonGenericSignature(current);\n if (signature) {\n if (!signatureList) {\n // This signature will contribute to contextual union signature\n signatureList = [signature];\n }\n else if (!compareSignatures(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypes)) {\n // Signatures aren't identical, do not use\n return undefined;\n }\n else {\n // Use this signature for contextual union signature\n signatureList.push(signature);\n }\n }\n }\n // Result is union of signatures collected (return type is union of return types of this signature set)\n var result;\n if (signatureList) {\n result = cloneSignature(signatureList[0]);\n // Clear resolved return type we possibly got from cloneSignature\n result.resolvedReturnType = undefined;\n result.unionSignatures = signatureList;\n }\n return result;\n }", "language": "javascript", "code": "function getContextualSignature(node) {\n ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));\n var type = ts.isObjectLiteralMethod(node)\n ? getContextualTypeForObjectLiteralMethod(node)\n : getContextualType(node);\n if (!type) {\n return undefined;\n }\n if (!(type.flags & 16384 /* Union */)) {\n return getNonGenericSignature(type);\n }\n var signatureList;\n var types = type.types;\n for (var _i = 0; _i < types.length; _i++) {\n var current = types[_i];\n var signature = getNonGenericSignature(current);\n if (signature) {\n if (!signatureList) {\n // This signature will contribute to contextual union signature\n signatureList = [signature];\n }\n else if (!compareSignatures(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypes)) {\n // Signatures aren't identical, do not use\n return undefined;\n }\n else {\n // Use this signature for contextual union signature\n signatureList.push(signature);\n }\n }\n }\n // Result is union of signatures collected (return type is union of return types of this signature set)\n var result;\n if (signatureList) {\n result = cloneSignature(signatureList[0]);\n // Clear resolved return type we possibly got from cloneSignature\n result.resolvedReturnType = undefined;\n result.unionSignatures = signatureList;\n }\n return result;\n }", "code_tokens": ["function", "getContextualSignature", "(", "node", ")", "{", "ts", ".", "Debug", ".", "assert", "(", "node", ".", "kind", "!==", "143", "||", "ts", ".", "isObjectLiteralMethod", "(", "node", ")", ")", ";", "var", "type", "=", "ts", ".", "isObjectLiteralMethod", "(", "node", ")", "?", "getContextualTypeForObjectLiteralMethod", "(", "node", ")", ":", "getContextualType", "(", "node", ")", ";", "if", "(", "!", "type", ")", "{", "return", "undefined", ";", "}", "if", "(", "!", "(", "type", ".", "flags", "&", "16384", ")", ")", "{", "return", "getNonGenericSignature", "(", "type", ")", ";", "}", "var", "signatureList", ";", "var", "types", "=", "type", ".", "types", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "types", ".", "length", ";", "_i", "++", ")", "{", "var", "current", "=", "types", "[", "_i", "]", ";", "var", "signature", "=", "getNonGenericSignature", "(", "current", ")", ";", "if", "(", "signature", ")", "{", "if", "(", "!", "signatureList", ")", "{", "signatureList", "=", "[", "signature", "]", ";", "}", "else", "if", "(", "!", "compareSignatures", "(", "signatureList", "[", "0", "]", ",", "signature", ",", "false", ",", "true", ",", "compareTypes", ")", ")", "{", "return", "undefined", ";", "}", "else", "{", "signatureList", ".", "push", "(", "signature", ")", ";", "}", "}", "}", "var", "result", ";", "if", "(", "signatureList", ")", "{", "result", "=", "cloneSignature", "(", "signatureList", "[", "0", "]", ")", ";", "result", ".", "resolvedReturnType", "=", "undefined", ";", "result", ".", "unionSignatures", "=", "signatureList", ";", "}", "return", "result", ";", "}"], "docstring": "Return the contextual signature for a given expression node. A contextual type provides a contextual signature if it has a single call signature and if that call signature is non-generic. If the contextual type is a union type, get the signature from each type possible and if they are all identical ignoring their return type, the result is same signature but with return type as union type of return types from these signatures", "docstring_tokens": ["Return", "the", "contextual", "signature", "for", "a", "given", "expression", "node", ".", "A", "contextual", "type", "provides", "a", "contextual", "signature", "if", "it", "has", "a", "single", "call", "signature", "and", "if", "that", "call", "signature", "is", "non", "-", "generic", ".", "If", "the", "contextual", "type", "is", "a", "union", "type", "get", "the", "signature", "from", "each", "type", "possible", "and", "if", "they", "are", "all", "identical", "ignoring", "their", "return", "type", "the", "result", "is", "same", "signature", "but", "with", "return", "type", "as", "union", "type", "of", "return", "types", "from", "these", "signatures"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L19802-L19842", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getJsxAttributePropertySymbol", "original_string": "function getJsxAttributePropertySymbol(attrib) {\n var attributesType = getJsxElementAttributesType(attrib.parent);\n var prop = getPropertyOfType(attributesType, attrib.name.text);\n return prop || unknownSymbol;\n }", "language": "javascript", "code": "function getJsxAttributePropertySymbol(attrib) {\n var attributesType = getJsxElementAttributesType(attrib.parent);\n var prop = getPropertyOfType(attributesType, attrib.name.text);\n return prop || unknownSymbol;\n }", "code_tokens": ["function", "getJsxAttributePropertySymbol", "(", "attrib", ")", "{", "var", "attributesType", "=", "getJsxElementAttributesType", "(", "attrib", ".", "parent", ")", ";", "var", "prop", "=", "getPropertyOfType", "(", "attributesType", ",", "attrib", ".", "name", ".", "text", ")", ";", "return", "prop", "||", "unknownSymbol", ";", "}"], "docstring": "Given a JSX attribute, returns the symbol for the corresponds property\nof the element attributes type. Will return unknownSymbol for attributes\nthat have no matching element attributes type property.", "docstring_tokens": ["Given", "a", "JSX", "attribute", "returns", "the", "symbol", "for", "the", "corresponds", "property", "of", "the", "element", "attributes", "type", ".", "Will", "return", "unknownSymbol", "for", "attributes", "that", "have", "no", "matching", "element", "attributes", "type", "property", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L20447-L20451", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkClassPropertyAccess", "original_string": "function checkClassPropertyAccess(node, left, type, prop) {\n var flags = getDeclarationFlagsFromSymbol(prop);\n var declaringClass = getDeclaredTypeOfSymbol(prop.parent);\n if (left.kind === 95 /* SuperKeyword */) {\n var errorNode = node.kind === 166 /* PropertyAccessExpression */ ?\n node.name :\n node.right;\n // TS 1.0 spec (April 2014): 4.8.2\n // - In a constructor, instance member function, instance member accessor, or\n // instance member variable initializer where this references a derived class instance,\n // a super property access is permitted and must specify a public instance member function of the base class.\n // - In a static member function or static member accessor\n // where this references the constructor function object of a derived class,\n // a super property access is permitted and must specify a public static member function of the base class.\n if (getDeclarationKindFromSymbol(prop) !== 143 /* MethodDeclaration */) {\n // `prop` refers to a *property* declared in the super class\n // rather than a *method*, so it does not satisfy the above criteria.\n error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);\n return false;\n }\n if (flags & 256 /* Abstract */) {\n // A method cannot be accessed in a super property access if the method is abstract.\n // This error could mask a private property access error. But, a member\n // cannot simultaneously be private and abstract, so this will trigger an\n // additional error elsewhere.\n error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass));\n return false;\n }\n }\n // Public properties are otherwise accessible.\n if (!(flags & (32 /* Private */ | 64 /* Protected */))) {\n return true;\n }\n // Property is known to be private or protected at this point\n // Get the declaring and enclosing class instance types\n var enclosingClassDeclaration = ts.getContainingClass(node);\n var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined;\n // Private property is accessible if declaring and enclosing class are the same\n if (flags & 32 /* Private */) {\n if (declaringClass !== enclosingClass) {\n error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass));\n return false;\n }\n return true;\n }\n // Property is known to be protected at this point\n // All protected properties of a supertype are accessible in a super access\n if (left.kind === 95 /* SuperKeyword */) {\n return true;\n }\n // A protected property is accessible in the declaring class and classes derived from it\n if (!enclosingClass || !hasBaseType(enclosingClass, declaringClass)) {\n error(node, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass));\n return false;\n }\n // No further restrictions for static properties\n if (flags & 128 /* Static */) {\n return true;\n }\n // An instance property must be accessed through an instance of the enclosing class\n if (type.flags & 33554432 /* ThisType */) {\n // get the original type -- represented as the type constraint of the 'this' type\n type = getConstraintOfTypeParameter(type);\n }\n // TODO: why is the first part of this check here?\n if (!(getTargetType(type).flags & (1024 /* Class */ | 2048 /* Interface */) && hasBaseType(type, enclosingClass))) {\n error(node, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));\n return false;\n }\n return true;\n }", "language": "javascript", "code": "function checkClassPropertyAccess(node, left, type, prop) {\n var flags = getDeclarationFlagsFromSymbol(prop);\n var declaringClass = getDeclaredTypeOfSymbol(prop.parent);\n if (left.kind === 95 /* SuperKeyword */) {\n var errorNode = node.kind === 166 /* PropertyAccessExpression */ ?\n node.name :\n node.right;\n // TS 1.0 spec (April 2014): 4.8.2\n // - In a constructor, instance member function, instance member accessor, or\n // instance member variable initializer where this references a derived class instance,\n // a super property access is permitted and must specify a public instance member function of the base class.\n // - In a static member function or static member accessor\n // where this references the constructor function object of a derived class,\n // a super property access is permitted and must specify a public static member function of the base class.\n if (getDeclarationKindFromSymbol(prop) !== 143 /* MethodDeclaration */) {\n // `prop` refers to a *property* declared in the super class\n // rather than a *method*, so it does not satisfy the above criteria.\n error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);\n return false;\n }\n if (flags & 256 /* Abstract */) {\n // A method cannot be accessed in a super property access if the method is abstract.\n // This error could mask a private property access error. But, a member\n // cannot simultaneously be private and abstract, so this will trigger an\n // additional error elsewhere.\n error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass));\n return false;\n }\n }\n // Public properties are otherwise accessible.\n if (!(flags & (32 /* Private */ | 64 /* Protected */))) {\n return true;\n }\n // Property is known to be private or protected at this point\n // Get the declaring and enclosing class instance types\n var enclosingClassDeclaration = ts.getContainingClass(node);\n var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined;\n // Private property is accessible if declaring and enclosing class are the same\n if (flags & 32 /* Private */) {\n if (declaringClass !== enclosingClass) {\n error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass));\n return false;\n }\n return true;\n }\n // Property is known to be protected at this point\n // All protected properties of a supertype are accessible in a super access\n if (left.kind === 95 /* SuperKeyword */) {\n return true;\n }\n // A protected property is accessible in the declaring class and classes derived from it\n if (!enclosingClass || !hasBaseType(enclosingClass, declaringClass)) {\n error(node, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass));\n return false;\n }\n // No further restrictions for static properties\n if (flags & 128 /* Static */) {\n return true;\n }\n // An instance property must be accessed through an instance of the enclosing class\n if (type.flags & 33554432 /* ThisType */) {\n // get the original type -- represented as the type constraint of the 'this' type\n type = getConstraintOfTypeParameter(type);\n }\n // TODO: why is the first part of this check here?\n if (!(getTargetType(type).flags & (1024 /* Class */ | 2048 /* Interface */) && hasBaseType(type, enclosingClass))) {\n error(node, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));\n return false;\n }\n return true;\n }", "code_tokens": ["function", "checkClassPropertyAccess", "(", "node", ",", "left", ",", "type", ",", "prop", ")", "{", "var", "flags", "=", "getDeclarationFlagsFromSymbol", "(", "prop", ")", ";", "var", "declaringClass", "=", "getDeclaredTypeOfSymbol", "(", "prop", ".", "parent", ")", ";", "if", "(", "left", ".", "kind", "===", "95", ")", "{", "var", "errorNode", "=", "node", ".", "kind", "===", "166", "?", "node", ".", "name", ":", "node", ".", "right", ";", "if", "(", "getDeclarationKindFromSymbol", "(", "prop", ")", "!==", "143", ")", "{", "error", "(", "errorNode", ",", "ts", ".", "Diagnostics", ".", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword", ")", ";", "return", "false", ";", "}", "if", "(", "flags", "&", "256", ")", "{", "error", "(", "errorNode", ",", "ts", ".", "Diagnostics", ".", "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression", ",", "symbolToString", "(", "prop", ")", ",", "typeToString", "(", "declaringClass", ")", ")", ";", "return", "false", ";", "}", "}", "if", "(", "!", "(", "flags", "&", "(", "32", "|", "64", ")", ")", ")", "{", "return", "true", ";", "}", "var", "enclosingClassDeclaration", "=", "ts", ".", "getContainingClass", "(", "node", ")", ";", "var", "enclosingClass", "=", "enclosingClassDeclaration", "?", "getDeclaredTypeOfSymbol", "(", "getSymbolOfNode", "(", "enclosingClassDeclaration", ")", ")", ":", "undefined", ";", "if", "(", "flags", "&", "32", ")", "{", "if", "(", "declaringClass", "!==", "enclosingClass", ")", "{", "error", "(", "node", ",", "ts", ".", "Diagnostics", ".", "Property_0_is_private_and_only_accessible_within_class_1", ",", "symbolToString", "(", "prop", ")", ",", "typeToString", "(", "declaringClass", ")", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}", "if", "(", "left", ".", "kind", "===", "95", ")", "{", "return", "true", ";", "}", "if", "(", "!", "enclosingClass", "||", "!", "hasBaseType", "(", "enclosingClass", ",", "declaringClass", ")", ")", "{", "error", "(", "node", ",", "ts", ".", "Diagnostics", ".", "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses", ",", "symbolToString", "(", "prop", ")", ",", "typeToString", "(", "declaringClass", ")", ")", ";", "return", "false", ";", "}", "if", "(", "flags", "&", "128", ")", "{", "return", "true", ";", "}", "if", "(", "type", ".", "flags", "&", "33554432", ")", "{", "type", "=", "getConstraintOfTypeParameter", "(", "type", ")", ";", "}", "if", "(", "!", "(", "getTargetType", "(", "type", ")", ".", "flags", "&", "(", "1024", "|", "2048", ")", "&&", "hasBaseType", "(", "type", ",", "enclosingClass", ")", ")", ")", "{", "error", "(", "node", ",", "ts", ".", "Diagnostics", ".", "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1", ",", "symbolToString", "(", "prop", ")", ",", "typeToString", "(", "enclosingClass", ")", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}"], "docstring": "Check whether the requested property access is valid.\nReturns true if node is a valid property access, and false otherwise.\n@param node The node to be checked.\n@param left The left hand side of the property access (e.g.: the super in `super.foo`).\n@param type The type of left.\n@param prop The symbol for the right hand side of the property access.", "docstring_tokens": ["Check", "whether", "the", "requested", "property", "access", "is", "valid", ".", "Returns", "true", "if", "node", "is", "a", "valid", "property", "access", "and", "false", "otherwise", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L20541-L20611", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getPropertyNameForIndexedAccess", "original_string": "function getPropertyNameForIndexedAccess(indexArgumentExpression, indexArgumentType) {\n if (indexArgumentExpression.kind === 9 /* StringLiteral */ || indexArgumentExpression.kind === 8 /* NumericLiteral */) {\n return indexArgumentExpression.text;\n }\n if (indexArgumentExpression.kind === 167 /* ElementAccessExpression */ || indexArgumentExpression.kind === 166 /* PropertyAccessExpression */) {\n var value = getConstantValue(indexArgumentExpression);\n if (value !== undefined) {\n return value.toString();\n }\n }\n if (checkThatExpressionIsProperSymbolReference(indexArgumentExpression, indexArgumentType, /*reportError*/ false)) {\n var rightHandSideName = indexArgumentExpression.name.text;\n return ts.getPropertyNameForKnownSymbolName(rightHandSideName);\n }\n return undefined;\n }", "language": "javascript", "code": "function getPropertyNameForIndexedAccess(indexArgumentExpression, indexArgumentType) {\n if (indexArgumentExpression.kind === 9 /* StringLiteral */ || indexArgumentExpression.kind === 8 /* NumericLiteral */) {\n return indexArgumentExpression.text;\n }\n if (indexArgumentExpression.kind === 167 /* ElementAccessExpression */ || indexArgumentExpression.kind === 166 /* PropertyAccessExpression */) {\n var value = getConstantValue(indexArgumentExpression);\n if (value !== undefined) {\n return value.toString();\n }\n }\n if (checkThatExpressionIsProperSymbolReference(indexArgumentExpression, indexArgumentType, /*reportError*/ false)) {\n var rightHandSideName = indexArgumentExpression.name.text;\n return ts.getPropertyNameForKnownSymbolName(rightHandSideName);\n }\n return undefined;\n }", "code_tokens": ["function", "getPropertyNameForIndexedAccess", "(", "indexArgumentExpression", ",", "indexArgumentType", ")", "{", "if", "(", "indexArgumentExpression", ".", "kind", "===", "9", "||", "indexArgumentExpression", ".", "kind", "===", "8", ")", "{", "return", "indexArgumentExpression", ".", "text", ";", "}", "if", "(", "indexArgumentExpression", ".", "kind", "===", "167", "||", "indexArgumentExpression", ".", "kind", "===", "166", ")", "{", "var", "value", "=", "getConstantValue", "(", "indexArgumentExpression", ")", ";", "if", "(", "value", "!==", "undefined", ")", "{", "return", "value", ".", "toString", "(", ")", ";", "}", "}", "if", "(", "checkThatExpressionIsProperSymbolReference", "(", "indexArgumentExpression", ",", "indexArgumentType", ",", "false", ")", ")", "{", "var", "rightHandSideName", "=", "indexArgumentExpression", ".", "name", ".", "text", ";", "return", "ts", ".", "getPropertyNameForKnownSymbolName", "(", "rightHandSideName", ")", ";", "}", "return", "undefined", ";", "}"], "docstring": "If indexArgumentExpression is a string literal or number literal, returns its text.\nIf indexArgumentExpression is a constant value, returns its string value.\nIf indexArgumentExpression is a well known symbol, returns the property name corresponding\nto this symbol, as long as it is a proper symbol reference.\nOtherwise, returns undefined.", "docstring_tokens": ["If", "indexArgumentExpression", "is", "a", "string", "literal", "or", "number", "literal", "returns", "its", "text", ".", "If", "indexArgumentExpression", "is", "a", "constant", "value", "returns", "its", "string", "value", ".", "If", "indexArgumentExpression", "is", "a", "well", "known", "symbol", "returns", "the", "property", "name", "corresponding", "to", "this", "symbol", "as", "long", "as", "it", "is", "a", "proper", "symbol", "reference", ".", "Otherwise", "returns", "undefined", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L20735-L20750", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getSingleCallSignature", "original_string": "function getSingleCallSignature(type) {\n if (type.flags & 80896 /* ObjectType */) {\n var resolved = resolveStructuredTypeMembers(type);\n if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 &&\n resolved.properties.length === 0 && !resolved.stringIndexType && !resolved.numberIndexType) {\n return resolved.callSignatures[0];\n }\n }\n return undefined;\n }", "language": "javascript", "code": "function getSingleCallSignature(type) {\n if (type.flags & 80896 /* ObjectType */) {\n var resolved = resolveStructuredTypeMembers(type);\n if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 &&\n resolved.properties.length === 0 && !resolved.stringIndexType && !resolved.numberIndexType) {\n return resolved.callSignatures[0];\n }\n }\n return undefined;\n }", "code_tokens": ["function", "getSingleCallSignature", "(", "type", ")", "{", "if", "(", "type", ".", "flags", "&", "80896", ")", "{", "var", "resolved", "=", "resolveStructuredTypeMembers", "(", "type", ")", ";", "if", "(", "resolved", ".", "callSignatures", ".", "length", "===", "1", "&&", "resolved", ".", "constructSignatures", ".", "length", "===", "0", "&&", "resolved", ".", "properties", ".", "length", "===", "0", "&&", "!", "resolved", ".", "stringIndexType", "&&", "!", "resolved", ".", "numberIndexType", ")", "{", "return", "resolved", ".", "callSignatures", "[", "0", "]", ";", "}", "}", "return", "undefined", ";", "}"], "docstring": "If type has a single call signature and no other members, return that signature. Otherwise, return undefined.", "docstring_tokens": ["If", "type", "has", "a", "single", "call", "signature", "and", "no", "other", "members", "return", "that", "signature", ".", "Otherwise", "return", "undefined", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L20938-L20947", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getEffectiveCallArguments", "original_string": "function getEffectiveCallArguments(node) {\n var args;\n if (node.kind === 170 /* TaggedTemplateExpression */) {\n var template = node.template;\n args = [undefined];\n if (template.kind === 183 /* TemplateExpression */) {\n ts.forEach(template.templateSpans, function (span) {\n args.push(span.expression);\n });\n }\n }\n else if (node.kind === 139 /* Decorator */) {\n // For a decorator, we return undefined as we will determine\n // the number and types of arguments for a decorator using\n // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below.\n return undefined;\n }\n else {\n args = node.arguments || emptyArray;\n }\n return args;\n }", "language": "javascript", "code": "function getEffectiveCallArguments(node) {\n var args;\n if (node.kind === 170 /* TaggedTemplateExpression */) {\n var template = node.template;\n args = [undefined];\n if (template.kind === 183 /* TemplateExpression */) {\n ts.forEach(template.templateSpans, function (span) {\n args.push(span.expression);\n });\n }\n }\n else if (node.kind === 139 /* Decorator */) {\n // For a decorator, we return undefined as we will determine\n // the number and types of arguments for a decorator using\n // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below.\n return undefined;\n }\n else {\n args = node.arguments || emptyArray;\n }\n return args;\n }", "code_tokens": ["function", "getEffectiveCallArguments", "(", "node", ")", "{", "var", "args", ";", "if", "(", "node", ".", "kind", "===", "170", ")", "{", "var", "template", "=", "node", ".", "template", ";", "args", "=", "[", "undefined", "]", ";", "if", "(", "template", ".", "kind", "===", "183", ")", "{", "ts", ".", "forEach", "(", "template", ".", "templateSpans", ",", "function", "(", "span", ")", "{", "args", ".", "push", "(", "span", ".", "expression", ")", ";", "}", ")", ";", "}", "}", "else", "if", "(", "node", ".", "kind", "===", "139", ")", "{", "return", "undefined", ";", "}", "else", "{", "args", "=", "node", ".", "arguments", "||", "emptyArray", ";", "}", "return", "args", ";", "}"], "docstring": "Returns the effective arguments for an expression that works like a function invocation.\n\nIf 'node' is a CallExpression or a NewExpression, then its argument list is returned.\nIf 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution\nexpressions, where the first element of the list is `undefined`.\nIf 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types\nwill be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`.", "docstring_tokens": ["Returns", "the", "effective", "arguments", "for", "an", "expression", "that", "works", "like", "a", "function", "invocation", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L21075-L21096", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getEffectiveDecoratorArgumentType", "original_string": "function getEffectiveDecoratorArgumentType(node, argIndex) {\n if (argIndex === 0) {\n return getEffectiveDecoratorFirstArgumentType(node.parent);\n }\n else if (argIndex === 1) {\n return getEffectiveDecoratorSecondArgumentType(node.parent);\n }\n else if (argIndex === 2) {\n return getEffectiveDecoratorThirdArgumentType(node.parent);\n }\n ts.Debug.fail(\"Decorators should not have a fourth synthetic argument.\");\n return unknownType;\n }", "language": "javascript", "code": "function getEffectiveDecoratorArgumentType(node, argIndex) {\n if (argIndex === 0) {\n return getEffectiveDecoratorFirstArgumentType(node.parent);\n }\n else if (argIndex === 1) {\n return getEffectiveDecoratorSecondArgumentType(node.parent);\n }\n else if (argIndex === 2) {\n return getEffectiveDecoratorThirdArgumentType(node.parent);\n }\n ts.Debug.fail(\"Decorators should not have a fourth synthetic argument.\");\n return unknownType;\n }", "code_tokens": ["function", "getEffectiveDecoratorArgumentType", "(", "node", ",", "argIndex", ")", "{", "if", "(", "argIndex", "===", "0", ")", "{", "return", "getEffectiveDecoratorFirstArgumentType", "(", "node", ".", "parent", ")", ";", "}", "else", "if", "(", "argIndex", "===", "1", ")", "{", "return", "getEffectiveDecoratorSecondArgumentType", "(", "node", ".", "parent", ")", ";", "}", "else", "if", "(", "argIndex", "===", "2", ")", "{", "return", "getEffectiveDecoratorThirdArgumentType", "(", "node", ".", "parent", ")", ";", "}", "ts", ".", "Debug", ".", "fail", "(", "\"Decorators should not have a fourth synthetic argument.\"", ")", ";", "return", "unknownType", ";", "}"], "docstring": "Returns the effective argument type for the provided argument to a decorator.", "docstring_tokens": ["Returns", "the", "effective", "argument", "type", "for", "the", "provided", "argument", "to", "a", "decorator", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L21279-L21291", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getEffectiveArgumentType", "original_string": "function getEffectiveArgumentType(node, argIndex, arg) {\n // Decorators provide special arguments, a tagged template expression provides\n // a special first argument, and string literals get string literal types\n // unless we're reporting errors\n if (node.kind === 139 /* Decorator */) {\n return getEffectiveDecoratorArgumentType(node, argIndex);\n }\n else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) {\n return globalTemplateStringsArrayType;\n }\n // This is not a synthetic argument, so we return 'undefined'\n // to signal that the caller needs to check the argument.\n return undefined;\n }", "language": "javascript", "code": "function getEffectiveArgumentType(node, argIndex, arg) {\n // Decorators provide special arguments, a tagged template expression provides\n // a special first argument, and string literals get string literal types\n // unless we're reporting errors\n if (node.kind === 139 /* Decorator */) {\n return getEffectiveDecoratorArgumentType(node, argIndex);\n }\n else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) {\n return globalTemplateStringsArrayType;\n }\n // This is not a synthetic argument, so we return 'undefined'\n // to signal that the caller needs to check the argument.\n return undefined;\n }", "code_tokens": ["function", "getEffectiveArgumentType", "(", "node", ",", "argIndex", ",", "arg", ")", "{", "if", "(", "node", ".", "kind", "===", "139", ")", "{", "return", "getEffectiveDecoratorArgumentType", "(", "node", ",", "argIndex", ")", ";", "}", "else", "if", "(", "argIndex", "===", "0", "&&", "node", ".", "kind", "===", "170", ")", "{", "return", "globalTemplateStringsArrayType", ";", "}", "return", "undefined", ";", "}"], "docstring": "Gets the effective argument type for an argument in a call expression.", "docstring_tokens": ["Gets", "the", "effective", "argument", "type", "for", "an", "argument", "in", "a", "call", "expression", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L21295-L21308", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getEffectiveArgument", "original_string": "function getEffectiveArgument(node, args, argIndex) {\n // For a decorator or the first argument of a tagged template expression we return undefined.\n if (node.kind === 139 /* Decorator */ ||\n (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */)) {\n return undefined;\n }\n return args[argIndex];\n }", "language": "javascript", "code": "function getEffectiveArgument(node, args, argIndex) {\n // For a decorator or the first argument of a tagged template expression we return undefined.\n if (node.kind === 139 /* Decorator */ ||\n (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */)) {\n return undefined;\n }\n return args[argIndex];\n }", "code_tokens": ["function", "getEffectiveArgument", "(", "node", ",", "args", ",", "argIndex", ")", "{", "if", "(", "node", ".", "kind", "===", "139", "||", "(", "argIndex", "===", "0", "&&", "node", ".", "kind", "===", "170", ")", ")", "{", "return", "undefined", ";", "}", "return", "args", "[", "argIndex", "]", ";", "}"], "docstring": "Gets the effective argument expression for an argument in a call expression.", "docstring_tokens": ["Gets", "the", "effective", "argument", "expression", "for", "an", "argument", "in", "a", "call", "expression", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L21312-L21319", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getEffectiveArgumentErrorNode", "original_string": "function getEffectiveArgumentErrorNode(node, argIndex, arg) {\n if (node.kind === 139 /* Decorator */) {\n // For a decorator, we use the expression of the decorator for error reporting.\n return node.expression;\n }\n else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) {\n // For a the first argument of a tagged template expression, we use the template of the tag for error reporting.\n return node.template;\n }\n else {\n return arg;\n }\n }", "language": "javascript", "code": "function getEffectiveArgumentErrorNode(node, argIndex, arg) {\n if (node.kind === 139 /* Decorator */) {\n // For a decorator, we use the expression of the decorator for error reporting.\n return node.expression;\n }\n else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) {\n // For a the first argument of a tagged template expression, we use the template of the tag for error reporting.\n return node.template;\n }\n else {\n return arg;\n }\n }", "code_tokens": ["function", "getEffectiveArgumentErrorNode", "(", "node", ",", "argIndex", ",", "arg", ")", "{", "if", "(", "node", ".", "kind", "===", "139", ")", "{", "return", "node", ".", "expression", ";", "}", "else", "if", "(", "argIndex", "===", "0", "&&", "node", ".", "kind", "===", "170", ")", "{", "return", "node", ".", "template", ";", "}", "else", "{", "return", "arg", ";", "}", "}"], "docstring": "Gets the error node to use when reporting errors for an effective argument.", "docstring_tokens": ["Gets", "the", "error", "node", "to", "use", "when", "reporting", "errors", "for", "an", "effective", "argument", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L21323-L21335", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getDiagnosticHeadMessageForDecoratorResolution", "original_string": "function getDiagnosticHeadMessageForDecoratorResolution(node) {\n switch (node.parent.kind) {\n case 214 /* ClassDeclaration */:\n case 186 /* ClassExpression */:\n return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;\n case 138 /* Parameter */:\n return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;\n case 141 /* PropertyDeclaration */:\n return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;\n case 143 /* MethodDeclaration */:\n case 145 /* GetAccessor */:\n case 146 /* SetAccessor */:\n return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;\n }\n }", "language": "javascript", "code": "function getDiagnosticHeadMessageForDecoratorResolution(node) {\n switch (node.parent.kind) {\n case 214 /* ClassDeclaration */:\n case 186 /* ClassExpression */:\n return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;\n case 138 /* Parameter */:\n return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;\n case 141 /* PropertyDeclaration */:\n return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;\n case 143 /* MethodDeclaration */:\n case 145 /* GetAccessor */:\n case 146 /* SetAccessor */:\n return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;\n }\n }", "code_tokens": ["function", "getDiagnosticHeadMessageForDecoratorResolution", "(", "node", ")", "{", "switch", "(", "node", ".", "parent", ".", "kind", ")", "{", "case", "214", ":", "case", "186", ":", "return", "ts", ".", "Diagnostics", ".", "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression", ";", "case", "138", ":", "return", "ts", ".", "Diagnostics", ".", "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression", ";", "case", "141", ":", "return", "ts", ".", "Diagnostics", ".", "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression", ";", "case", "143", ":", "case", "145", ":", "case", "146", ":", "return", "ts", ".", "Diagnostics", ".", "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression", ";", "}", "}"], "docstring": "Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.", "docstring_tokens": ["Gets", "the", "localized", "diagnostic", "head", "message", "to", "use", "for", "errors", "when", "resolving", "a", "decorator", "as", "a", "call", "expression", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L21681-L21695", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "resolveDecorator", "original_string": "function resolveDecorator(node, candidatesOutArray) {\n var funcType = checkExpression(node.expression);\n var apparentType = getApparentType(funcType);\n if (apparentType === unknownType) {\n return resolveErrorCall(node);\n }\n var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);\n if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) {\n return resolveUntypedCall(node);\n }\n var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);\n if (!callSignatures.length) {\n var errorInfo;\n errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature);\n errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage);\n diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo));\n return resolveErrorCall(node);\n }\n return resolveCall(node, callSignatures, candidatesOutArray, headMessage);\n }", "language": "javascript", "code": "function resolveDecorator(node, candidatesOutArray) {\n var funcType = checkExpression(node.expression);\n var apparentType = getApparentType(funcType);\n if (apparentType === unknownType) {\n return resolveErrorCall(node);\n }\n var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);\n if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) {\n return resolveUntypedCall(node);\n }\n var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);\n if (!callSignatures.length) {\n var errorInfo;\n errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature);\n errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage);\n diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo));\n return resolveErrorCall(node);\n }\n return resolveCall(node, callSignatures, candidatesOutArray, headMessage);\n }", "code_tokens": ["function", "resolveDecorator", "(", "node", ",", "candidatesOutArray", ")", "{", "var", "funcType", "=", "checkExpression", "(", "node", ".", "expression", ")", ";", "var", "apparentType", "=", "getApparentType", "(", "funcType", ")", ";", "if", "(", "apparentType", "===", "unknownType", ")", "{", "return", "resolveErrorCall", "(", "node", ")", ";", "}", "var", "callSignatures", "=", "getSignaturesOfType", "(", "apparentType", ",", "0", ")", ";", "if", "(", "funcType", "===", "anyType", "||", "(", "!", "callSignatures", ".", "length", "&&", "!", "(", "funcType", ".", "flags", "&", "16384", ")", "&&", "isTypeAssignableTo", "(", "funcType", ",", "globalFunctionType", ")", ")", ")", "{", "return", "resolveUntypedCall", "(", "node", ")", ";", "}", "var", "headMessage", "=", "getDiagnosticHeadMessageForDecoratorResolution", "(", "node", ")", ";", "if", "(", "!", "callSignatures", ".", "length", ")", "{", "var", "errorInfo", ";", "errorInfo", "=", "ts", ".", "chainDiagnosticMessages", "(", "errorInfo", ",", "ts", ".", "Diagnostics", ".", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature", ")", ";", "errorInfo", "=", "ts", ".", "chainDiagnosticMessages", "(", "errorInfo", ",", "headMessage", ")", ";", "diagnostics", ".", "add", "(", "ts", ".", "createDiagnosticForNodeFromMessageChain", "(", "node", ",", "errorInfo", ")", ")", ";", "return", "resolveErrorCall", "(", "node", ")", ";", "}", "return", "resolveCall", "(", "node", ",", "callSignatures", ",", "candidatesOutArray", ",", "headMessage", ")", ";", "}"], "docstring": "Resolves a decorator as if it were a call expression.", "docstring_tokens": ["Resolves", "a", "decorator", "as", "if", "it", "were", "a", "call", "expression", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L21699-L21718", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getResolvedSignature", "original_string": "function getResolvedSignature(node, candidatesOutArray) {\n var links = getNodeLinks(node);\n // If getResolvedSignature has already been called, we will have cached the resolvedSignature.\n // However, it is possible that either candidatesOutArray was not passed in the first time,\n // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work\n // to correctly fill the candidatesOutArray.\n if (!links.resolvedSignature || candidatesOutArray) {\n links.resolvedSignature = anySignature;\n if (node.kind === 168 /* CallExpression */) {\n links.resolvedSignature = resolveCallExpression(node, candidatesOutArray);\n }\n else if (node.kind === 169 /* NewExpression */) {\n links.resolvedSignature = resolveNewExpression(node, candidatesOutArray);\n }\n else if (node.kind === 170 /* TaggedTemplateExpression */) {\n links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray);\n }\n else if (node.kind === 139 /* Decorator */) {\n links.resolvedSignature = resolveDecorator(node, candidatesOutArray);\n }\n else {\n ts.Debug.fail(\"Branch in 'getResolvedSignature' should be unreachable.\");\n }\n }\n return links.resolvedSignature;\n }", "language": "javascript", "code": "function getResolvedSignature(node, candidatesOutArray) {\n var links = getNodeLinks(node);\n // If getResolvedSignature has already been called, we will have cached the resolvedSignature.\n // However, it is possible that either candidatesOutArray was not passed in the first time,\n // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work\n // to correctly fill the candidatesOutArray.\n if (!links.resolvedSignature || candidatesOutArray) {\n links.resolvedSignature = anySignature;\n if (node.kind === 168 /* CallExpression */) {\n links.resolvedSignature = resolveCallExpression(node, candidatesOutArray);\n }\n else if (node.kind === 169 /* NewExpression */) {\n links.resolvedSignature = resolveNewExpression(node, candidatesOutArray);\n }\n else if (node.kind === 170 /* TaggedTemplateExpression */) {\n links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray);\n }\n else if (node.kind === 139 /* Decorator */) {\n links.resolvedSignature = resolveDecorator(node, candidatesOutArray);\n }\n else {\n ts.Debug.fail(\"Branch in 'getResolvedSignature' should be unreachable.\");\n }\n }\n return links.resolvedSignature;\n }", "code_tokens": ["function", "getResolvedSignature", "(", "node", ",", "candidatesOutArray", ")", "{", "var", "links", "=", "getNodeLinks", "(", "node", ")", ";", "if", "(", "!", "links", ".", "resolvedSignature", "||", "candidatesOutArray", ")", "{", "links", ".", "resolvedSignature", "=", "anySignature", ";", "if", "(", "node", ".", "kind", "===", "168", ")", "{", "links", ".", "resolvedSignature", "=", "resolveCallExpression", "(", "node", ",", "candidatesOutArray", ")", ";", "}", "else", "if", "(", "node", ".", "kind", "===", "169", ")", "{", "links", ".", "resolvedSignature", "=", "resolveNewExpression", "(", "node", ",", "candidatesOutArray", ")", ";", "}", "else", "if", "(", "node", ".", "kind", "===", "170", ")", "{", "links", ".", "resolvedSignature", "=", "resolveTaggedTemplateExpression", "(", "node", ",", "candidatesOutArray", ")", ";", "}", "else", "if", "(", "node", ".", "kind", "===", "139", ")", "{", "links", ".", "resolvedSignature", "=", "resolveDecorator", "(", "node", ",", "candidatesOutArray", ")", ";", "}", "else", "{", "ts", ".", "Debug", ".", "fail", "(", "\"Branch in 'getResolvedSignature' should be unreachable.\"", ")", ";", "}", "}", "return", "links", ".", "resolvedSignature", ";", "}"], "docstring": "candidatesOutArray is passed by signature help in the language service, and collectCandidates must fill it up with the appropriate candidate signatures", "docstring_tokens": ["candidatesOutArray", "is", "passed", "by", "signature", "help", "in", "the", "language", "service", "and", "collectCandidates", "must", "fill", "it", "up", "with", "the", "appropriate", "candidate", "signatures"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L21721-L21746", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkCallExpression", "original_string": "function checkCallExpression(node) {\n // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true\n checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments);\n var signature = getResolvedSignature(node);\n if (node.expression.kind === 95 /* SuperKeyword */) {\n return voidType;\n }\n if (node.kind === 169 /* NewExpression */) {\n var declaration = signature.declaration;\n if (declaration &&\n declaration.kind !== 144 /* Constructor */ &&\n declaration.kind !== 148 /* ConstructSignature */ &&\n declaration.kind !== 153 /* ConstructorType */) {\n // When resolved signature is a call signature (and not a construct signature) the result type is any\n if (compilerOptions.noImplicitAny) {\n error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);\n }\n return anyType;\n }\n }\n return getReturnTypeOfSignature(signature);\n }", "language": "javascript", "code": "function checkCallExpression(node) {\n // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true\n checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments);\n var signature = getResolvedSignature(node);\n if (node.expression.kind === 95 /* SuperKeyword */) {\n return voidType;\n }\n if (node.kind === 169 /* NewExpression */) {\n var declaration = signature.declaration;\n if (declaration &&\n declaration.kind !== 144 /* Constructor */ &&\n declaration.kind !== 148 /* ConstructSignature */ &&\n declaration.kind !== 153 /* ConstructorType */) {\n // When resolved signature is a call signature (and not a construct signature) the result type is any\n if (compilerOptions.noImplicitAny) {\n error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);\n }\n return anyType;\n }\n }\n return getReturnTypeOfSignature(signature);\n }", "code_tokens": ["function", "checkCallExpression", "(", "node", ")", "{", "checkGrammarTypeArguments", "(", "node", ",", "node", ".", "typeArguments", ")", "||", "checkGrammarArguments", "(", "node", ",", "node", ".", "arguments", ")", ";", "var", "signature", "=", "getResolvedSignature", "(", "node", ")", ";", "if", "(", "node", ".", "expression", ".", "kind", "===", "95", ")", "{", "return", "voidType", ";", "}", "if", "(", "node", ".", "kind", "===", "169", ")", "{", "var", "declaration", "=", "signature", ".", "declaration", ";", "if", "(", "declaration", "&&", "declaration", ".", "kind", "!==", "144", "&&", "declaration", ".", "kind", "!==", "148", "&&", "declaration", ".", "kind", "!==", "153", ")", "{", "if", "(", "compilerOptions", ".", "noImplicitAny", ")", "{", "error", "(", "node", ",", "ts", ".", "Diagnostics", ".", "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type", ")", ";", "}", "return", "anyType", ";", "}", "}", "return", "getReturnTypeOfSignature", "(", "signature", ")", ";", "}"], "docstring": "Syntactically and semantically checks a call or new expression.\n@param node The call/new expression to be checked.\n@returns On success, the expression's signature's return type. On failure, anyType.", "docstring_tokens": ["Syntactically", "and", "semantically", "checks", "a", "call", "or", "new", "expression", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L21752-L21773", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "assignBindingElementTypes", "original_string": "function assignBindingElementTypes(node) {\n if (ts.isBindingPattern(node.name)) {\n for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {\n var element = _a[_i];\n if (element.kind !== 187 /* OmittedExpression */) {\n if (element.name.kind === 69 /* Identifier */) {\n getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);\n }\n assignBindingElementTypes(element);\n }\n }\n }\n }", "language": "javascript", "code": "function assignBindingElementTypes(node) {\n if (ts.isBindingPattern(node.name)) {\n for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {\n var element = _a[_i];\n if (element.kind !== 187 /* OmittedExpression */) {\n if (element.name.kind === 69 /* Identifier */) {\n getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);\n }\n assignBindingElementTypes(element);\n }\n }\n }\n }", "code_tokens": ["function", "assignBindingElementTypes", "(", "node", ")", "{", "if", "(", "ts", ".", "isBindingPattern", "(", "node", ".", "name", ")", ")", "{", "for", "(", "var", "_i", "=", "0", ",", "_a", "=", "node", ".", "name", ".", "elements", ";", "_i", "<", "_a", ".", "length", ";", "_i", "++", ")", "{", "var", "element", "=", "_a", "[", "_i", "]", ";", "if", "(", "element", ".", "kind", "!==", "187", ")", "{", "if", "(", "element", ".", "name", ".", "kind", "===", "69", ")", "{", "getSymbolLinks", "(", "getSymbolOfNode", "(", "element", ")", ")", ".", "type", "=", "getTypeForBindingElement", "(", "element", ")", ";", "}", "assignBindingElementTypes", "(", "element", ")", ";", "}", "}", "}", "}"], "docstring": "When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push the destructured type into the contained binding elements.", "docstring_tokens": ["When", "contextual", "typing", "assigns", "a", "type", "to", "a", "parameter", "that", "contains", "a", "binding", "pattern", "we", "also", "need", "to", "push", "the", "destructured", "type", "into", "the", "contained", "binding", "elements", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L21808-L21820", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkTypeParameter", "original_string": "function checkTypeParameter(node) {\n // Grammar Checking\n if (node.expression) {\n grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);\n }\n checkSourceElement(node.constraint);\n if (produceDiagnostics) {\n checkTypeParameterHasIllegalReferencesInConstraint(node);\n checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);\n }\n // TODO: Check multiple declarations are identical\n }", "language": "javascript", "code": "function checkTypeParameter(node) {\n // Grammar Checking\n if (node.expression) {\n grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);\n }\n checkSourceElement(node.constraint);\n if (produceDiagnostics) {\n checkTypeParameterHasIllegalReferencesInConstraint(node);\n checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);\n }\n // TODO: Check multiple declarations are identical\n }", "code_tokens": ["function", "checkTypeParameter", "(", "node", ")", "{", "if", "(", "node", ".", "expression", ")", "{", "grammarErrorOnFirstToken", "(", "node", ".", "expression", ",", "ts", ".", "Diagnostics", ".", "Type_expected", ")", ";", "}", "checkSourceElement", "(", "node", ".", "constraint", ")", ";", "if", "(", "produceDiagnostics", ")", "{", "checkTypeParameterHasIllegalReferencesInConstraint", "(", "node", ")", ";", "checkTypeNameIsReserved", "(", "node", ".", "name", ",", "ts", ".", "Diagnostics", ".", "Type_parameter_name_cannot_be_0", ")", ";", "}", "}"], "docstring": "DECLARATION AND STATEMENT TYPE CHECKING", "docstring_tokens": ["DECLARATION", "AND", "STATEMENT", "TYPE", "CHECKING"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L22848-L22859", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getPromisedType", "original_string": "function getPromisedType(promise) {\n //\n // { // promise\n // then( // thenFunction\n // onfulfilled: ( // onfulfilledParameterType\n // value: T // valueParameterType\n // ) => any\n // ): any;\n // }\n //\n if (promise.flags & 1 /* Any */) {\n return undefined;\n }\n if ((promise.flags & 4096 /* Reference */) && promise.target === tryGetGlobalPromiseType()) {\n return promise.typeArguments[0];\n }\n var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType();\n if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) {\n return undefined;\n }\n var thenFunction = getTypeOfPropertyOfType(promise, \"then\");\n if (thenFunction && (thenFunction.flags & 1 /* Any */)) {\n return undefined;\n }\n var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : emptyArray;\n if (thenSignatures.length === 0) {\n return undefined;\n }\n var onfulfilledParameterType = getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature));\n if (onfulfilledParameterType.flags & 1 /* Any */) {\n return undefined;\n }\n var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);\n if (onfulfilledParameterSignatures.length === 0) {\n return undefined;\n }\n var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature));\n return valueParameterType;\n }", "language": "javascript", "code": "function getPromisedType(promise) {\n //\n // { // promise\n // then( // thenFunction\n // onfulfilled: ( // onfulfilledParameterType\n // value: T // valueParameterType\n // ) => any\n // ): any;\n // }\n //\n if (promise.flags & 1 /* Any */) {\n return undefined;\n }\n if ((promise.flags & 4096 /* Reference */) && promise.target === tryGetGlobalPromiseType()) {\n return promise.typeArguments[0];\n }\n var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType();\n if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) {\n return undefined;\n }\n var thenFunction = getTypeOfPropertyOfType(promise, \"then\");\n if (thenFunction && (thenFunction.flags & 1 /* Any */)) {\n return undefined;\n }\n var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : emptyArray;\n if (thenSignatures.length === 0) {\n return undefined;\n }\n var onfulfilledParameterType = getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature));\n if (onfulfilledParameterType.flags & 1 /* Any */) {\n return undefined;\n }\n var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);\n if (onfulfilledParameterSignatures.length === 0) {\n return undefined;\n }\n var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature));\n return valueParameterType;\n }", "code_tokens": ["function", "getPromisedType", "(", "promise", ")", "{", "if", "(", "promise", ".", "flags", "&", "1", ")", "{", "return", "undefined", ";", "}", "if", "(", "(", "promise", ".", "flags", "&", "4096", ")", "&&", "promise", ".", "target", "===", "tryGetGlobalPromiseType", "(", ")", ")", "{", "return", "promise", ".", "typeArguments", "[", "0", "]", ";", "}", "var", "globalPromiseLikeType", "=", "getInstantiatedGlobalPromiseLikeType", "(", ")", ";", "if", "(", "globalPromiseLikeType", "===", "emptyObjectType", "||", "!", "isTypeAssignableTo", "(", "promise", ",", "globalPromiseLikeType", ")", ")", "{", "return", "undefined", ";", "}", "var", "thenFunction", "=", "getTypeOfPropertyOfType", "(", "promise", ",", "\"then\"", ")", ";", "if", "(", "thenFunction", "&&", "(", "thenFunction", ".", "flags", "&", "1", ")", ")", "{", "return", "undefined", ";", "}", "var", "thenSignatures", "=", "thenFunction", "?", "getSignaturesOfType", "(", "thenFunction", ",", "0", ")", ":", "emptyArray", ";", "if", "(", "thenSignatures", ".", "length", "===", "0", ")", "{", "return", "undefined", ";", "}", "var", "onfulfilledParameterType", "=", "getUnionType", "(", "ts", ".", "map", "(", "thenSignatures", ",", "getTypeOfFirstParameterOfSignature", ")", ")", ";", "if", "(", "onfulfilledParameterType", ".", "flags", "&", "1", ")", "{", "return", "undefined", ";", "}", "var", "onfulfilledParameterSignatures", "=", "getSignaturesOfType", "(", "onfulfilledParameterType", ",", "0", ")", ";", "if", "(", "onfulfilledParameterSignatures", ".", "length", "===", "0", ")", "{", "return", "undefined", ";", "}", "var", "valueParameterType", "=", "getUnionType", "(", "ts", ".", "map", "(", "onfulfilledParameterSignatures", ",", "getTypeOfFirstParameterOfSignature", ")", ")", ";", "return", "valueParameterType", ";", "}"], "docstring": "Gets the \"promised type\" of a promise.\n@param type The type of the promise.\n@remarks The \"promised type\" of a type is the type of the \"value\" parameter of the \"onfulfilled\" callback.", "docstring_tokens": ["Gets", "the", "promised", "type", "of", "a", "promise", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L23619-L23657", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkDecorator", "original_string": "function checkDecorator(node) {\n var signature = getResolvedSignature(node);\n var returnType = getReturnTypeOfSignature(signature);\n if (returnType.flags & 1 /* Any */) {\n return;\n }\n var expectedReturnType;\n var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);\n var errorInfo;\n switch (node.parent.kind) {\n case 214 /* ClassDeclaration */:\n var classSymbol = getSymbolOfNode(node.parent);\n var classConstructorType = getTypeOfSymbol(classSymbol);\n expectedReturnType = getUnionType([classConstructorType, voidType]);\n break;\n case 138 /* Parameter */:\n expectedReturnType = voidType;\n errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);\n break;\n case 141 /* PropertyDeclaration */:\n expectedReturnType = voidType;\n errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);\n break;\n case 143 /* MethodDeclaration */:\n case 145 /* GetAccessor */:\n case 146 /* SetAccessor */:\n var methodType = getTypeOfNode(node.parent);\n var descriptorType = createTypedPropertyDescriptorType(methodType);\n expectedReturnType = getUnionType([descriptorType, voidType]);\n break;\n }\n checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo);\n }", "language": "javascript", "code": "function checkDecorator(node) {\n var signature = getResolvedSignature(node);\n var returnType = getReturnTypeOfSignature(signature);\n if (returnType.flags & 1 /* Any */) {\n return;\n }\n var expectedReturnType;\n var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);\n var errorInfo;\n switch (node.parent.kind) {\n case 214 /* ClassDeclaration */:\n var classSymbol = getSymbolOfNode(node.parent);\n var classConstructorType = getTypeOfSymbol(classSymbol);\n expectedReturnType = getUnionType([classConstructorType, voidType]);\n break;\n case 138 /* Parameter */:\n expectedReturnType = voidType;\n errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);\n break;\n case 141 /* PropertyDeclaration */:\n expectedReturnType = voidType;\n errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);\n break;\n case 143 /* MethodDeclaration */:\n case 145 /* GetAccessor */:\n case 146 /* SetAccessor */:\n var methodType = getTypeOfNode(node.parent);\n var descriptorType = createTypedPropertyDescriptorType(methodType);\n expectedReturnType = getUnionType([descriptorType, voidType]);\n break;\n }\n checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo);\n }", "code_tokens": ["function", "checkDecorator", "(", "node", ")", "{", "var", "signature", "=", "getResolvedSignature", "(", "node", ")", ";", "var", "returnType", "=", "getReturnTypeOfSignature", "(", "signature", ")", ";", "if", "(", "returnType", ".", "flags", "&", "1", ")", "{", "return", ";", "}", "var", "expectedReturnType", ";", "var", "headMessage", "=", "getDiagnosticHeadMessageForDecoratorResolution", "(", "node", ")", ";", "var", "errorInfo", ";", "switch", "(", "node", ".", "parent", ".", "kind", ")", "{", "case", "214", ":", "var", "classSymbol", "=", "getSymbolOfNode", "(", "node", ".", "parent", ")", ";", "var", "classConstructorType", "=", "getTypeOfSymbol", "(", "classSymbol", ")", ";", "expectedReturnType", "=", "getUnionType", "(", "[", "classConstructorType", ",", "voidType", "]", ")", ";", "break", ";", "case", "138", ":", "expectedReturnType", "=", "voidType", ";", "errorInfo", "=", "ts", ".", "chainDiagnosticMessages", "(", "errorInfo", ",", "ts", ".", "Diagnostics", ".", "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any", ")", ";", "break", ";", "case", "141", ":", "expectedReturnType", "=", "voidType", ";", "errorInfo", "=", "ts", ".", "chainDiagnosticMessages", "(", "errorInfo", ",", "ts", ".", "Diagnostics", ".", "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any", ")", ";", "break", ";", "case", "143", ":", "case", "145", ":", "case", "146", ":", "var", "methodType", "=", "getTypeOfNode", "(", "node", ".", "parent", ")", ";", "var", "descriptorType", "=", "createTypedPropertyDescriptorType", "(", "methodType", ")", ";", "expectedReturnType", "=", "getUnionType", "(", "[", "descriptorType", ",", "voidType", "]", ")", ";", "break", ";", "}", "checkTypeAssignableTo", "(", "returnType", ",", "expectedReturnType", ",", "node", ",", "headMessage", ",", "errorInfo", ")", ";", "}"], "docstring": "Check a decorator", "docstring_tokens": ["Check", "a", "decorator"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L23829-L23861", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkTypeNodeAsExpression", "original_string": "function checkTypeNodeAsExpression(node) {\n // When we are emitting type metadata for decorators, we need to try to check the type\n // as if it were an expression so that we can emit the type in a value position when we\n // serialize the type metadata.\n if (node && node.kind === 151 /* TypeReference */) {\n var root = getFirstIdentifier(node.typeName);\n var meaning = root.parent.kind === 151 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */;\n // Resolve type so we know which symbol is referenced\n var rootSymbol = resolveName(root, root.text, meaning | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined);\n // Resolved symbol is alias\n if (rootSymbol && rootSymbol.flags & 8388608 /* Alias */) {\n var aliasTarget = resolveAlias(rootSymbol);\n // If alias has value symbol - mark alias as referenced\n if (aliasTarget.flags & 107455 /* Value */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) {\n markAliasSymbolAsReferenced(rootSymbol);\n }\n }\n }\n }", "language": "javascript", "code": "function checkTypeNodeAsExpression(node) {\n // When we are emitting type metadata for decorators, we need to try to check the type\n // as if it were an expression so that we can emit the type in a value position when we\n // serialize the type metadata.\n if (node && node.kind === 151 /* TypeReference */) {\n var root = getFirstIdentifier(node.typeName);\n var meaning = root.parent.kind === 151 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */;\n // Resolve type so we know which symbol is referenced\n var rootSymbol = resolveName(root, root.text, meaning | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined);\n // Resolved symbol is alias\n if (rootSymbol && rootSymbol.flags & 8388608 /* Alias */) {\n var aliasTarget = resolveAlias(rootSymbol);\n // If alias has value symbol - mark alias as referenced\n if (aliasTarget.flags & 107455 /* Value */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) {\n markAliasSymbolAsReferenced(rootSymbol);\n }\n }\n }\n }", "code_tokens": ["function", "checkTypeNodeAsExpression", "(", "node", ")", "{", "if", "(", "node", "&&", "node", ".", "kind", "===", "151", ")", "{", "var", "root", "=", "getFirstIdentifier", "(", "node", ".", "typeName", ")", ";", "var", "meaning", "=", "root", ".", "parent", ".", "kind", "===", "151", "?", "793056", ":", "1536", ";", "var", "rootSymbol", "=", "resolveName", "(", "root", ",", "root", ".", "text", ",", "meaning", "|", "8388608", ",", "undefined", ",", "undefined", ")", ";", "if", "(", "rootSymbol", "&&", "rootSymbol", ".", "flags", "&", "8388608", ")", "{", "var", "aliasTarget", "=", "resolveAlias", "(", "rootSymbol", ")", ";", "if", "(", "aliasTarget", ".", "flags", "&", "107455", "&&", "!", "isConstEnumOrConstEnumOnlyModule", "(", "resolveAlias", "(", "rootSymbol", ")", ")", ")", "{", "markAliasSymbolAsReferenced", "(", "rootSymbol", ")", ";", "}", "}", "}", "}"], "docstring": "Checks a type reference node as an expression.", "docstring_tokens": ["Checks", "a", "type", "reference", "node", "as", "an", "expression", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L23863-L23881", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkTypeAnnotationAsExpression", "original_string": "function checkTypeAnnotationAsExpression(node) {\n switch (node.kind) {\n case 141 /* PropertyDeclaration */:\n checkTypeNodeAsExpression(node.type);\n break;\n case 138 /* Parameter */:\n checkTypeNodeAsExpression(node.type);\n break;\n case 143 /* MethodDeclaration */:\n checkTypeNodeAsExpression(node.type);\n break;\n case 145 /* GetAccessor */:\n checkTypeNodeAsExpression(node.type);\n break;\n case 146 /* SetAccessor */:\n checkTypeNodeAsExpression(ts.getSetAccessorTypeAnnotationNode(node));\n break;\n }\n }", "language": "javascript", "code": "function checkTypeAnnotationAsExpression(node) {\n switch (node.kind) {\n case 141 /* PropertyDeclaration */:\n checkTypeNodeAsExpression(node.type);\n break;\n case 138 /* Parameter */:\n checkTypeNodeAsExpression(node.type);\n break;\n case 143 /* MethodDeclaration */:\n checkTypeNodeAsExpression(node.type);\n break;\n case 145 /* GetAccessor */:\n checkTypeNodeAsExpression(node.type);\n break;\n case 146 /* SetAccessor */:\n checkTypeNodeAsExpression(ts.getSetAccessorTypeAnnotationNode(node));\n break;\n }\n }", "code_tokens": ["function", "checkTypeAnnotationAsExpression", "(", "node", ")", "{", "switch", "(", "node", ".", "kind", ")", "{", "case", "141", ":", "checkTypeNodeAsExpression", "(", "node", ".", "type", ")", ";", "break", ";", "case", "138", ":", "checkTypeNodeAsExpression", "(", "node", ".", "type", ")", ";", "break", ";", "case", "143", ":", "checkTypeNodeAsExpression", "(", "node", ".", "type", ")", ";", "break", ";", "case", "145", ":", "checkTypeNodeAsExpression", "(", "node", ".", "type", ")", ";", "break", ";", "case", "146", ":", "checkTypeNodeAsExpression", "(", "ts", ".", "getSetAccessorTypeAnnotationNode", "(", "node", ")", ")", ";", "break", ";", "}", "}"], "docstring": "Checks the type annotation of an accessor declaration or property declaration as\nan expression if it is a type reference to a type with a value declaration.", "docstring_tokens": ["Checks", "the", "type", "annotation", "of", "an", "accessor", "declaration", "or", "property", "declaration", "as", "an", "expression", "if", "it", "is", "a", "type", "reference", "to", "a", "type", "with", "a", "value", "declaration", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L23886-L23904", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkDecorators", "original_string": "function checkDecorators(node) {\n if (!node.decorators) {\n return;\n }\n // skip this check for nodes that cannot have decorators. These should have already had an error reported by\n // checkGrammarDecorators.\n if (!ts.nodeCanBeDecorated(node)) {\n return;\n }\n if (!compilerOptions.experimentalDecorators) {\n error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_to_remove_this_warning);\n }\n if (compilerOptions.emitDecoratorMetadata) {\n // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.\n switch (node.kind) {\n case 214 /* ClassDeclaration */:\n var constructor = ts.getFirstConstructorWithBody(node);\n if (constructor) {\n checkParameterTypeAnnotationsAsExpressions(constructor);\n }\n break;\n case 143 /* MethodDeclaration */:\n checkParameterTypeAnnotationsAsExpressions(node);\n // fall-through\n case 146 /* SetAccessor */:\n case 145 /* GetAccessor */:\n case 141 /* PropertyDeclaration */:\n case 138 /* Parameter */:\n checkTypeAnnotationAsExpression(node);\n break;\n }\n }\n emitDecorate = true;\n if (node.kind === 138 /* Parameter */) {\n emitParam = true;\n }\n ts.forEach(node.decorators, checkDecorator);\n }", "language": "javascript", "code": "function checkDecorators(node) {\n if (!node.decorators) {\n return;\n }\n // skip this check for nodes that cannot have decorators. These should have already had an error reported by\n // checkGrammarDecorators.\n if (!ts.nodeCanBeDecorated(node)) {\n return;\n }\n if (!compilerOptions.experimentalDecorators) {\n error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_to_remove_this_warning);\n }\n if (compilerOptions.emitDecoratorMetadata) {\n // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.\n switch (node.kind) {\n case 214 /* ClassDeclaration */:\n var constructor = ts.getFirstConstructorWithBody(node);\n if (constructor) {\n checkParameterTypeAnnotationsAsExpressions(constructor);\n }\n break;\n case 143 /* MethodDeclaration */:\n checkParameterTypeAnnotationsAsExpressions(node);\n // fall-through\n case 146 /* SetAccessor */:\n case 145 /* GetAccessor */:\n case 141 /* PropertyDeclaration */:\n case 138 /* Parameter */:\n checkTypeAnnotationAsExpression(node);\n break;\n }\n }\n emitDecorate = true;\n if (node.kind === 138 /* Parameter */) {\n emitParam = true;\n }\n ts.forEach(node.decorators, checkDecorator);\n }", "code_tokens": ["function", "checkDecorators", "(", "node", ")", "{", "if", "(", "!", "node", ".", "decorators", ")", "{", "return", ";", "}", "if", "(", "!", "ts", ".", "nodeCanBeDecorated", "(", "node", ")", ")", "{", "return", ";", "}", "if", "(", "!", "compilerOptions", ".", "experimentalDecorators", ")", "{", "error", "(", "node", ",", "ts", ".", "Diagnostics", ".", "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_to_remove_this_warning", ")", ";", "}", "if", "(", "compilerOptions", ".", "emitDecoratorMetadata", ")", "{", "switch", "(", "node", ".", "kind", ")", "{", "case", "214", ":", "var", "constructor", "=", "ts", ".", "getFirstConstructorWithBody", "(", "node", ")", ";", "if", "(", "constructor", ")", "{", "checkParameterTypeAnnotationsAsExpressions", "(", "constructor", ")", ";", "}", "break", ";", "case", "143", ":", "checkParameterTypeAnnotationsAsExpressions", "(", "node", ")", ";", "case", "146", ":", "case", "145", ":", "case", "141", ":", "case", "138", ":", "checkTypeAnnotationAsExpression", "(", "node", ")", ";", "break", ";", "}", "}", "emitDecorate", "=", "true", ";", "if", "(", "node", ".", "kind", "===", "138", ")", "{", "emitParam", "=", "true", ";", "}", "ts", ".", "forEach", "(", "node", ".", "decorators", ",", "checkDecorator", ")", ";", "}"], "docstring": "Check the decorators of a node", "docstring_tokens": ["Check", "the", "decorators", "of", "a", "node"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L23914-L23951", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkIfThisIsCapturedInEnclosingScope", "original_string": "function checkIfThisIsCapturedInEnclosingScope(node) {\n var current = node;\n while (current) {\n if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {\n var isDeclaration_1 = node.kind !== 69 /* Identifier */;\n if (isDeclaration_1) {\n error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);\n }\n else {\n error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);\n }\n return;\n }\n current = current.parent;\n }\n }", "language": "javascript", "code": "function checkIfThisIsCapturedInEnclosingScope(node) {\n var current = node;\n while (current) {\n if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {\n var isDeclaration_1 = node.kind !== 69 /* Identifier */;\n if (isDeclaration_1) {\n error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);\n }\n else {\n error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);\n }\n return;\n }\n current = current.parent;\n }\n }", "code_tokens": ["function", "checkIfThisIsCapturedInEnclosingScope", "(", "node", ")", "{", "var", "current", "=", "node", ";", "while", "(", "current", ")", "{", "if", "(", "getNodeCheckFlags", "(", "current", ")", "&", "4", ")", "{", "var", "isDeclaration_1", "=", "node", ".", "kind", "!==", "69", ";", "if", "(", "isDeclaration_1", ")", "{", "error", "(", "node", ".", "name", ",", "ts", ".", "Diagnostics", ".", "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference", ")", ";", "}", "else", "{", "error", "(", "node", ",", "ts", ".", "Diagnostics", ".", "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference", ")", ";", "}", "return", ";", "}", "current", "=", "current", ".", "parent", ";", "}", "}"], "docstring": "this function will run after checking the source file so 'CaptureThis' is correct for all nodes", "docstring_tokens": ["this", "function", "will", "run", "after", "checking", "the", "source", "file", "so", "CaptureThis", "is", "correct", "for", "all", "nodes"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L24068-L24083", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkParameterInitializer", "original_string": "function checkParameterInitializer(node) {\n if (ts.getRootDeclaration(node).kind !== 138 /* Parameter */) {\n return;\n }\n var func = ts.getContainingFunction(node);\n visit(node.initializer);\n function visit(n) {\n if (n.kind === 69 /* Identifier */) {\n var referencedSymbol = getNodeLinks(n).resolvedSymbol;\n // check FunctionLikeDeclaration.locals (stores parameters\\function local variable)\n // if it contains entry with a specified name and if this entry matches the resolved symbol\n if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(func.locals, referencedSymbol.name, 107455 /* Value */) === referencedSymbol) {\n if (referencedSymbol.valueDeclaration.kind === 138 /* Parameter */) {\n if (referencedSymbol.valueDeclaration === node) {\n error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name));\n return;\n }\n if (referencedSymbol.valueDeclaration.pos < node.pos) {\n // legal case - parameter initializer references some parameter strictly on left of current parameter declaration\n return;\n }\n }\n error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n));\n }\n }\n else {\n ts.forEachChild(n, visit);\n }\n }\n }", "language": "javascript", "code": "function checkParameterInitializer(node) {\n if (ts.getRootDeclaration(node).kind !== 138 /* Parameter */) {\n return;\n }\n var func = ts.getContainingFunction(node);\n visit(node.initializer);\n function visit(n) {\n if (n.kind === 69 /* Identifier */) {\n var referencedSymbol = getNodeLinks(n).resolvedSymbol;\n // check FunctionLikeDeclaration.locals (stores parameters\\function local variable)\n // if it contains entry with a specified name and if this entry matches the resolved symbol\n if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(func.locals, referencedSymbol.name, 107455 /* Value */) === referencedSymbol) {\n if (referencedSymbol.valueDeclaration.kind === 138 /* Parameter */) {\n if (referencedSymbol.valueDeclaration === node) {\n error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name));\n return;\n }\n if (referencedSymbol.valueDeclaration.pos < node.pos) {\n // legal case - parameter initializer references some parameter strictly on left of current parameter declaration\n return;\n }\n }\n error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n));\n }\n }\n else {\n ts.forEachChild(n, visit);\n }\n }\n }", "code_tokens": ["function", "checkParameterInitializer", "(", "node", ")", "{", "if", "(", "ts", ".", "getRootDeclaration", "(", "node", ")", ".", "kind", "!==", "138", ")", "{", "return", ";", "}", "var", "func", "=", "ts", ".", "getContainingFunction", "(", "node", ")", ";", "visit", "(", "node", ".", "initializer", ")", ";", "function", "visit", "(", "n", ")", "{", "if", "(", "n", ".", "kind", "===", "69", ")", "{", "var", "referencedSymbol", "=", "getNodeLinks", "(", "n", ")", ".", "resolvedSymbol", ";", "if", "(", "referencedSymbol", "&&", "referencedSymbol", "!==", "unknownSymbol", "&&", "getSymbol", "(", "func", ".", "locals", ",", "referencedSymbol", ".", "name", ",", "107455", ")", "===", "referencedSymbol", ")", "{", "if", "(", "referencedSymbol", ".", "valueDeclaration", ".", "kind", "===", "138", ")", "{", "if", "(", "referencedSymbol", ".", "valueDeclaration", "===", "node", ")", "{", "error", "(", "n", ",", "ts", ".", "Diagnostics", ".", "Parameter_0_cannot_be_referenced_in_its_initializer", ",", "ts", ".", "declarationNameToString", "(", "node", ".", "name", ")", ")", ";", "return", ";", "}", "if", "(", "referencedSymbol", ".", "valueDeclaration", ".", "pos", "<", "node", ".", "pos", ")", "{", "return", ";", "}", "}", "error", "(", "n", ",", "ts", ".", "Diagnostics", ".", "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it", ",", "ts", ".", "declarationNameToString", "(", "node", ".", "name", ")", ",", "ts", ".", "declarationNameToString", "(", "n", ")", ")", ";", "}", "}", "else", "{", "ts", ".", "forEachChild", "(", "n", ",", "visit", ")", ";", "}", "}", "}"], "docstring": "Check that a parameter initializer contains no references to parameters declared to the right of itself", "docstring_tokens": ["Check", "that", "a", "parameter", "initializer", "contains", "no", "references", "to", "parameters", "declared", "to", "the", "right", "of", "itself"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L24183-L24212", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkVariableLikeDeclaration", "original_string": "function checkVariableLikeDeclaration(node) {\n checkDecorators(node);\n checkSourceElement(node.type);\n // For a computed property, just check the initializer and exit\n // Do not use hasDynamicName here, because that returns false for well known symbols.\n // We want to perform checkComputedPropertyName for all computed properties, including\n // well known symbols.\n if (node.name.kind === 136 /* ComputedPropertyName */) {\n checkComputedPropertyName(node.name);\n if (node.initializer) {\n checkExpressionCached(node.initializer);\n }\n }\n // For a binding pattern, check contained binding elements\n if (ts.isBindingPattern(node.name)) {\n ts.forEach(node.name.elements, checkSourceElement);\n }\n // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body\n if (node.initializer && ts.getRootDeclaration(node).kind === 138 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {\n error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);\n return;\n }\n // For a binding pattern, validate the initializer and exit\n if (ts.isBindingPattern(node.name)) {\n if (node.initializer) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined);\n checkParameterInitializer(node);\n }\n return;\n }\n var symbol = getSymbolOfNode(node);\n var type = getTypeOfVariableOrParameterOrProperty(symbol);\n if (node === symbol.valueDeclaration) {\n // Node is the primary declaration of the symbol, just validate the initializer\n if (node.initializer) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined);\n checkParameterInitializer(node);\n }\n }\n else {\n // Node is a secondary declaration, check that type is identical to primary declaration and check that\n // initializer is consistent with type associated with the node\n var declarationType = getWidenedTypeForVariableLikeDeclaration(node);\n if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) {\n error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType));\n }\n if (node.initializer) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined);\n }\n }\n if (node.kind !== 141 /* PropertyDeclaration */ && node.kind !== 140 /* PropertySignature */) {\n // We know we don't have a binding pattern or computed name here\n checkExportsOnMergedDeclarations(node);\n if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) {\n checkVarDeclaredNamesNotShadowed(node);\n }\n checkCollisionWithCapturedSuperVariable(node, node.name);\n checkCollisionWithCapturedThisVariable(node, node.name);\n checkCollisionWithRequireExportsInGeneratedCode(node, node.name);\n }\n }", "language": "javascript", "code": "function checkVariableLikeDeclaration(node) {\n checkDecorators(node);\n checkSourceElement(node.type);\n // For a computed property, just check the initializer and exit\n // Do not use hasDynamicName here, because that returns false for well known symbols.\n // We want to perform checkComputedPropertyName for all computed properties, including\n // well known symbols.\n if (node.name.kind === 136 /* ComputedPropertyName */) {\n checkComputedPropertyName(node.name);\n if (node.initializer) {\n checkExpressionCached(node.initializer);\n }\n }\n // For a binding pattern, check contained binding elements\n if (ts.isBindingPattern(node.name)) {\n ts.forEach(node.name.elements, checkSourceElement);\n }\n // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body\n if (node.initializer && ts.getRootDeclaration(node).kind === 138 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {\n error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);\n return;\n }\n // For a binding pattern, validate the initializer and exit\n if (ts.isBindingPattern(node.name)) {\n if (node.initializer) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined);\n checkParameterInitializer(node);\n }\n return;\n }\n var symbol = getSymbolOfNode(node);\n var type = getTypeOfVariableOrParameterOrProperty(symbol);\n if (node === symbol.valueDeclaration) {\n // Node is the primary declaration of the symbol, just validate the initializer\n if (node.initializer) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined);\n checkParameterInitializer(node);\n }\n }\n else {\n // Node is a secondary declaration, check that type is identical to primary declaration and check that\n // initializer is consistent with type associated with the node\n var declarationType = getWidenedTypeForVariableLikeDeclaration(node);\n if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) {\n error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType));\n }\n if (node.initializer) {\n checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined);\n }\n }\n if (node.kind !== 141 /* PropertyDeclaration */ && node.kind !== 140 /* PropertySignature */) {\n // We know we don't have a binding pattern or computed name here\n checkExportsOnMergedDeclarations(node);\n if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) {\n checkVarDeclaredNamesNotShadowed(node);\n }\n checkCollisionWithCapturedSuperVariable(node, node.name);\n checkCollisionWithCapturedThisVariable(node, node.name);\n checkCollisionWithRequireExportsInGeneratedCode(node, node.name);\n }\n }", "code_tokens": ["function", "checkVariableLikeDeclaration", "(", "node", ")", "{", "checkDecorators", "(", "node", ")", ";", "checkSourceElement", "(", "node", ".", "type", ")", ";", "if", "(", "node", ".", "name", ".", "kind", "===", "136", ")", "{", "checkComputedPropertyName", "(", "node", ".", "name", ")", ";", "if", "(", "node", ".", "initializer", ")", "{", "checkExpressionCached", "(", "node", ".", "initializer", ")", ";", "}", "}", "if", "(", "ts", ".", "isBindingPattern", "(", "node", ".", "name", ")", ")", "{", "ts", ".", "forEach", "(", "node", ".", "name", ".", "elements", ",", "checkSourceElement", ")", ";", "}", "if", "(", "node", ".", "initializer", "&&", "ts", ".", "getRootDeclaration", "(", "node", ")", ".", "kind", "===", "138", "&&", "ts", ".", "nodeIsMissing", "(", "ts", ".", "getContainingFunction", "(", "node", ")", ".", "body", ")", ")", "{", "error", "(", "node", ",", "ts", ".", "Diagnostics", ".", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation", ")", ";", "return", ";", "}", "if", "(", "ts", ".", "isBindingPattern", "(", "node", ".", "name", ")", ")", "{", "if", "(", "node", ".", "initializer", ")", "{", "checkTypeAssignableTo", "(", "checkExpressionCached", "(", "node", ".", "initializer", ")", ",", "getWidenedTypeForVariableLikeDeclaration", "(", "node", ")", ",", "node", ",", "undefined", ")", ";", "checkParameterInitializer", "(", "node", ")", ";", "}", "return", ";", "}", "var", "symbol", "=", "getSymbolOfNode", "(", "node", ")", ";", "var", "type", "=", "getTypeOfVariableOrParameterOrProperty", "(", "symbol", ")", ";", "if", "(", "node", "===", "symbol", ".", "valueDeclaration", ")", "{", "if", "(", "node", ".", "initializer", ")", "{", "checkTypeAssignableTo", "(", "checkExpressionCached", "(", "node", ".", "initializer", ")", ",", "type", ",", "node", ",", "undefined", ")", ";", "checkParameterInitializer", "(", "node", ")", ";", "}", "}", "else", "{", "var", "declarationType", "=", "getWidenedTypeForVariableLikeDeclaration", "(", "node", ")", ";", "if", "(", "type", "!==", "unknownType", "&&", "declarationType", "!==", "unknownType", "&&", "!", "isTypeIdenticalTo", "(", "type", ",", "declarationType", ")", ")", "{", "error", "(", "node", ".", "name", ",", "ts", ".", "Diagnostics", ".", "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2", ",", "ts", ".", "declarationNameToString", "(", "node", ".", "name", ")", ",", "typeToString", "(", "type", ")", ",", "typeToString", "(", "declarationType", ")", ")", ";", "}", "if", "(", "node", ".", "initializer", ")", "{", "checkTypeAssignableTo", "(", "checkExpressionCached", "(", "node", ".", "initializer", ")", ",", "declarationType", ",", "node", ",", "undefined", ")", ";", "}", "}", "if", "(", "node", ".", "kind", "!==", "141", "&&", "node", ".", "kind", "!==", "140", ")", "{", "checkExportsOnMergedDeclarations", "(", "node", ")", ";", "if", "(", "node", ".", "kind", "===", "211", "||", "node", ".", "kind", "===", "163", ")", "{", "checkVarDeclaredNamesNotShadowed", "(", "node", ")", ";", "}", "checkCollisionWithCapturedSuperVariable", "(", "node", ",", "node", ".", "name", ")", ";", "checkCollisionWithCapturedThisVariable", "(", "node", ",", "node", ".", "name", ")", ";", "checkCollisionWithRequireExportsInGeneratedCode", "(", "node", ",", "node", ".", "name", ")", ";", "}", "}"], "docstring": "Check variable, parameter, or property declaration", "docstring_tokens": ["Check", "variable", "parameter", "or", "property", "declaration"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L24214-L24274", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkElementTypeOfIterable", "original_string": "function checkElementTypeOfIterable(iterable, errorNode) {\n var elementType = getElementTypeOfIterable(iterable, errorNode);\n // Now even though we have extracted the iteratedType, we will have to validate that the type\n // passed in is actually an Iterable.\n if (errorNode && elementType) {\n checkTypeAssignableTo(iterable, createIterableType(elementType), errorNode);\n }\n return elementType || anyType;\n }", "language": "javascript", "code": "function checkElementTypeOfIterable(iterable, errorNode) {\n var elementType = getElementTypeOfIterable(iterable, errorNode);\n // Now even though we have extracted the iteratedType, we will have to validate that the type\n // passed in is actually an Iterable.\n if (errorNode && elementType) {\n checkTypeAssignableTo(iterable, createIterableType(elementType), errorNode);\n }\n return elementType || anyType;\n }", "code_tokens": ["function", "checkElementTypeOfIterable", "(", "iterable", ",", "errorNode", ")", "{", "var", "elementType", "=", "getElementTypeOfIterable", "(", "iterable", ",", "errorNode", ")", ";", "if", "(", "errorNode", "&&", "elementType", ")", "{", "checkTypeAssignableTo", "(", "iterable", ",", "createIterableType", "(", "elementType", ")", ",", "errorNode", ")", ";", "}", "return", "elementType", "||", "anyType", ";", "}"], "docstring": "When errorNode is undefined, it means we should not report any errors.", "docstring_tokens": ["When", "errorNode", "is", "undefined", "it", "means", "we", "should", "not", "report", "any", "errors", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L24456-L24464", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkTypeParameters", "original_string": "function checkTypeParameters(typeParameterDeclarations) {\n if (typeParameterDeclarations) {\n for (var i = 0, n = typeParameterDeclarations.length; i < n; i++) {\n var node = typeParameterDeclarations[i];\n checkTypeParameter(node);\n if (produceDiagnostics) {\n for (var j = 0; j < i; j++) {\n if (typeParameterDeclarations[j].symbol === node.symbol) {\n error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));\n }\n }\n }\n }\n }\n }", "language": "javascript", "code": "function checkTypeParameters(typeParameterDeclarations) {\n if (typeParameterDeclarations) {\n for (var i = 0, n = typeParameterDeclarations.length; i < n; i++) {\n var node = typeParameterDeclarations[i];\n checkTypeParameter(node);\n if (produceDiagnostics) {\n for (var j = 0; j < i; j++) {\n if (typeParameterDeclarations[j].symbol === node.symbol) {\n error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));\n }\n }\n }\n }\n }\n }", "code_tokens": ["function", "checkTypeParameters", "(", "typeParameterDeclarations", ")", "{", "if", "(", "typeParameterDeclarations", ")", "{", "for", "(", "var", "i", "=", "0", ",", "n", "=", "typeParameterDeclarations", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "var", "node", "=", "typeParameterDeclarations", "[", "i", "]", ";", "checkTypeParameter", "(", "node", ")", ";", "if", "(", "produceDiagnostics", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "i", ";", "j", "++", ")", "{", "if", "(", "typeParameterDeclarations", "[", "j", "]", ".", "symbol", "===", "node", ".", "symbol", ")", "{", "error", "(", "node", ".", "name", ",", "ts", ".", "Diagnostics", ".", "Duplicate_identifier_0", ",", "ts", ".", "declarationNameToString", "(", "node", ".", "name", ")", ")", ";", "}", "}", "}", "}", "}", "}"], "docstring": "Check each type parameter and check that list has no duplicate type parameter declarations", "docstring_tokens": ["Check", "each", "type", "parameter", "and", "check", "that", "list", "has", "no", "duplicate", "type", "parameter", "declarations"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L24882-L24896", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "checkSourceFileWorker", "original_string": "function checkSourceFileWorker(node) {\n var links = getNodeLinks(node);\n if (!(links.flags & 1 /* TypeChecked */)) {\n // Check whether the file has declared it is the default lib,\n // and whether the user has specifically chosen to avoid checking it.\n if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) {\n return;\n }\n // Grammar checking\n checkGrammarSourceFile(node);\n emitExtends = false;\n emitDecorate = false;\n emitParam = false;\n potentialThisCollisions.length = 0;\n ts.forEach(node.statements, checkSourceElement);\n checkFunctionAndClassExpressionBodies(node);\n if (ts.isExternalModule(node)) {\n checkExternalModuleExports(node);\n }\n if (potentialThisCollisions.length) {\n ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);\n potentialThisCollisions.length = 0;\n }\n if (emitExtends) {\n links.flags |= 8 /* EmitExtends */;\n }\n if (emitDecorate) {\n links.flags |= 16 /* EmitDecorate */;\n }\n if (emitParam) {\n links.flags |= 32 /* EmitParam */;\n }\n if (emitAwaiter) {\n links.flags |= 64 /* EmitAwaiter */;\n }\n if (emitGenerator || (emitAwaiter && languageVersion < 2 /* ES6 */)) {\n links.flags |= 128 /* EmitGenerator */;\n }\n links.flags |= 1 /* TypeChecked */;\n }\n }", "language": "javascript", "code": "function checkSourceFileWorker(node) {\n var links = getNodeLinks(node);\n if (!(links.flags & 1 /* TypeChecked */)) {\n // Check whether the file has declared it is the default lib,\n // and whether the user has specifically chosen to avoid checking it.\n if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) {\n return;\n }\n // Grammar checking\n checkGrammarSourceFile(node);\n emitExtends = false;\n emitDecorate = false;\n emitParam = false;\n potentialThisCollisions.length = 0;\n ts.forEach(node.statements, checkSourceElement);\n checkFunctionAndClassExpressionBodies(node);\n if (ts.isExternalModule(node)) {\n checkExternalModuleExports(node);\n }\n if (potentialThisCollisions.length) {\n ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);\n potentialThisCollisions.length = 0;\n }\n if (emitExtends) {\n links.flags |= 8 /* EmitExtends */;\n }\n if (emitDecorate) {\n links.flags |= 16 /* EmitDecorate */;\n }\n if (emitParam) {\n links.flags |= 32 /* EmitParam */;\n }\n if (emitAwaiter) {\n links.flags |= 64 /* EmitAwaiter */;\n }\n if (emitGenerator || (emitAwaiter && languageVersion < 2 /* ES6 */)) {\n links.flags |= 128 /* EmitGenerator */;\n }\n links.flags |= 1 /* TypeChecked */;\n }\n }", "code_tokens": ["function", "checkSourceFileWorker", "(", "node", ")", "{", "var", "links", "=", "getNodeLinks", "(", "node", ")", ";", "if", "(", "!", "(", "links", ".", "flags", "&", "1", ")", ")", "{", "if", "(", "node", ".", "isDefaultLib", "&&", "compilerOptions", ".", "skipDefaultLibCheck", ")", "{", "return", ";", "}", "checkGrammarSourceFile", "(", "node", ")", ";", "emitExtends", "=", "false", ";", "emitDecorate", "=", "false", ";", "emitParam", "=", "false", ";", "potentialThisCollisions", ".", "length", "=", "0", ";", "ts", ".", "forEach", "(", "node", ".", "statements", ",", "checkSourceElement", ")", ";", "checkFunctionAndClassExpressionBodies", "(", "node", ")", ";", "if", "(", "ts", ".", "isExternalModule", "(", "node", ")", ")", "{", "checkExternalModuleExports", "(", "node", ")", ";", "}", "if", "(", "potentialThisCollisions", ".", "length", ")", "{", "ts", ".", "forEach", "(", "potentialThisCollisions", ",", "checkIfThisIsCapturedInEnclosingScope", ")", ";", "potentialThisCollisions", ".", "length", "=", "0", ";", "}", "if", "(", "emitExtends", ")", "{", "links", ".", "flags", "|=", "8", ";", "}", "if", "(", "emitDecorate", ")", "{", "links", ".", "flags", "|=", "16", ";", "}", "if", "(", "emitParam", ")", "{", "links", ".", "flags", "|=", "32", ";", "}", "if", "(", "emitAwaiter", ")", "{", "links", ".", "flags", "|=", "64", ";", "}", "if", "(", "emitGenerator", "||", "(", "emitAwaiter", "&&", "languageVersion", "<", "2", ")", ")", "{", "links", ".", "flags", "|=", "128", ";", "}", "links", ".", "flags", "|=", "1", ";", "}", "}"], "docstring": "Fully type check a source file and collect the relevant diagnostics.", "docstring_tokens": ["Fully", "type", "check", "a", "source", "file", "and", "collect", "the", "relevant", "diagnostics", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L25947-L25987", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "copySymbol", "original_string": "function copySymbol(symbol, meaning) {\n if (symbol.flags & meaning) {\n var id = symbol.name;\n // We will copy all symbol regardless of its reserved name because\n // symbolsToArray will check whether the key is a reserved name and\n // it will not copy symbol with reserved name to the array\n if (!ts.hasProperty(symbols, id)) {\n symbols[id] = symbol;\n }\n }\n }", "language": "javascript", "code": "function copySymbol(symbol, meaning) {\n if (symbol.flags & meaning) {\n var id = symbol.name;\n // We will copy all symbol regardless of its reserved name because\n // symbolsToArray will check whether the key is a reserved name and\n // it will not copy symbol with reserved name to the array\n if (!ts.hasProperty(symbols, id)) {\n symbols[id] = symbol;\n }\n }\n }", "code_tokens": ["function", "copySymbol", "(", "symbol", ",", "meaning", ")", "{", "if", "(", "symbol", ".", "flags", "&", "meaning", ")", "{", "var", "id", "=", "symbol", ".", "name", ";", "if", "(", "!", "ts", ".", "hasProperty", "(", "symbols", ",", "id", ")", ")", "{", "symbols", "[", "id", "]", "=", "symbol", ";", "}", "}", "}"], "docstring": "Copy the given symbol into symbol tables if the symbol has the given meaning\nand it doesn't already existed in the symbol table\n@param key a key for storing in symbol table; if undefined, use symbol.name\n@param symbol the symbol to be added into symbol table\n@param meaning meaning of symbol to filter by before adding to symbol table", "docstring_tokens": ["Copy", "the", "given", "symbol", "into", "symbol", "tables", "if", "the", "symbol", "has", "the", "given", "meaning", "and", "it", "doesn", "t", "already", "existed", "in", "the", "symbol", "table"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L26094-L26104", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getParentTypeOfClassElement", "original_string": "function getParentTypeOfClassElement(node) {\n var classSymbol = getSymbolOfNode(node.parent);\n return node.flags & 128 /* Static */\n ? getTypeOfSymbol(classSymbol)\n : getDeclaredTypeOfSymbol(classSymbol);\n }", "language": "javascript", "code": "function getParentTypeOfClassElement(node) {\n var classSymbol = getSymbolOfNode(node.parent);\n return node.flags & 128 /* Static */\n ? getTypeOfSymbol(classSymbol)\n : getDeclaredTypeOfSymbol(classSymbol);\n }", "code_tokens": ["function", "getParentTypeOfClassElement", "(", "node", ")", "{", "var", "classSymbol", "=", "getSymbolOfNode", "(", "node", ".", "parent", ")", ";", "return", "node", ".", "flags", "&", "128", "?", "getTypeOfSymbol", "(", "classSymbol", ")", ":", "getDeclaredTypeOfSymbol", "(", "classSymbol", ")", ";", "}"], "docstring": "Gets either the static or instance type of a class element, based on\nwhether the element is declared as \"static\".", "docstring_tokens": ["Gets", "either", "the", "static", "or", "instance", "type", "of", "a", "class", "element", "based", "on", "whether", "the", "element", "is", "declared", "as", "static", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L26367-L26372", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getAugmentedPropertiesOfType", "original_string": "function getAugmentedPropertiesOfType(type) {\n type = getApparentType(type);\n var propsByName = createSymbolTable(getPropertiesOfType(type));\n if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) {\n ts.forEach(getPropertiesOfType(globalFunctionType), function (p) {\n if (!ts.hasProperty(propsByName, p.name)) {\n propsByName[p.name] = p;\n }\n });\n }\n return getNamedMembers(propsByName);\n }", "language": "javascript", "code": "function getAugmentedPropertiesOfType(type) {\n type = getApparentType(type);\n var propsByName = createSymbolTable(getPropertiesOfType(type));\n if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) {\n ts.forEach(getPropertiesOfType(globalFunctionType), function (p) {\n if (!ts.hasProperty(propsByName, p.name)) {\n propsByName[p.name] = p;\n }\n });\n }\n return getNamedMembers(propsByName);\n }", "code_tokens": ["function", "getAugmentedPropertiesOfType", "(", "type", ")", "{", "type", "=", "getApparentType", "(", "type", ")", ";", "var", "propsByName", "=", "createSymbolTable", "(", "getPropertiesOfType", "(", "type", ")", ")", ";", "if", "(", "getSignaturesOfType", "(", "type", ",", "0", ")", ".", "length", "||", "getSignaturesOfType", "(", "type", ",", "1", ")", ".", "length", ")", "{", "ts", ".", "forEach", "(", "getPropertiesOfType", "(", "globalFunctionType", ")", ",", "function", "(", "p", ")", "{", "if", "(", "!", "ts", ".", "hasProperty", "(", "propsByName", ",", "p", ".", "name", ")", ")", "{", "propsByName", "[", "p", ".", "name", "]", "=", "p", ";", "}", "}", ")", ";", "}", "return", "getNamedMembers", "(", "propsByName", ")", ";", "}"], "docstring": "Return the list of properties of the given type, augmented with properties from Function if the type has call or construct signatures", "docstring_tokens": ["Return", "the", "list", "of", "properties", "of", "the", "given", "type", "augmented", "with", "properties", "from", "Function", "if", "the", "type", "has", "call", "or", "construct", "signatures"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L26375-L26386", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getReferencedExportContainer", "original_string": "function getReferencedExportContainer(node) {\n var symbol = getReferencedValueSymbol(node);\n if (symbol) {\n if (symbol.flags & 1048576 /* ExportValue */) {\n // If we reference an exported entity within the same module declaration, then whether\n // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the\n // kinds that we do NOT prefix.\n var exportSymbol = getMergedSymbol(symbol.exportSymbol);\n if (exportSymbol.flags & 944 /* ExportHasLocal */) {\n return undefined;\n }\n symbol = exportSymbol;\n }\n var parentSymbol = getParentOfSymbol(symbol);\n if (parentSymbol) {\n if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 248 /* SourceFile */) {\n return parentSymbol.valueDeclaration;\n }\n for (var n = node.parent; n; n = n.parent) {\n if ((n.kind === 218 /* ModuleDeclaration */ || n.kind === 217 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) {\n return n;\n }\n }\n }\n }\n }", "language": "javascript", "code": "function getReferencedExportContainer(node) {\n var symbol = getReferencedValueSymbol(node);\n if (symbol) {\n if (symbol.flags & 1048576 /* ExportValue */) {\n // If we reference an exported entity within the same module declaration, then whether\n // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the\n // kinds that we do NOT prefix.\n var exportSymbol = getMergedSymbol(symbol.exportSymbol);\n if (exportSymbol.flags & 944 /* ExportHasLocal */) {\n return undefined;\n }\n symbol = exportSymbol;\n }\n var parentSymbol = getParentOfSymbol(symbol);\n if (parentSymbol) {\n if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 248 /* SourceFile */) {\n return parentSymbol.valueDeclaration;\n }\n for (var n = node.parent; n; n = n.parent) {\n if ((n.kind === 218 /* ModuleDeclaration */ || n.kind === 217 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) {\n return n;\n }\n }\n }\n }\n }", "code_tokens": ["function", "getReferencedExportContainer", "(", "node", ")", "{", "var", "symbol", "=", "getReferencedValueSymbol", "(", "node", ")", ";", "if", "(", "symbol", ")", "{", "if", "(", "symbol", ".", "flags", "&", "1048576", ")", "{", "var", "exportSymbol", "=", "getMergedSymbol", "(", "symbol", ".", "exportSymbol", ")", ";", "if", "(", "exportSymbol", ".", "flags", "&", "944", ")", "{", "return", "undefined", ";", "}", "symbol", "=", "exportSymbol", ";", "}", "var", "parentSymbol", "=", "getParentOfSymbol", "(", "symbol", ")", ";", "if", "(", "parentSymbol", ")", "{", "if", "(", "parentSymbol", ".", "flags", "&", "512", "&&", "parentSymbol", ".", "valueDeclaration", ".", "kind", "===", "248", ")", "{", "return", "parentSymbol", ".", "valueDeclaration", ";", "}", "for", "(", "var", "n", "=", "node", ".", "parent", ";", "n", ";", "n", "=", "n", ".", "parent", ")", "{", "if", "(", "(", "n", ".", "kind", "===", "218", "||", "n", ".", "kind", "===", "217", ")", "&&", "getSymbolOfNode", "(", "n", ")", "===", "parentSymbol", ")", "{", "return", "n", ";", "}", "}", "}", "}", "}"], "docstring": "Emitter support When resolved as an expression identifier, if the given node references an exported entity, return the declaration node of the exported entity's container. Otherwise, return undefined.", "docstring_tokens": ["Emitter", "support", "When", "resolved", "as", "an", "expression", "identifier", "if", "the", "given", "node", "references", "an", "exported", "entity", "return", "the", "declaration", "node", "of", "the", "exported", "entity", "s", "container", ".", "Otherwise", "return", "undefined", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L26410-L26435", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getReferencedImportDeclaration", "original_string": "function getReferencedImportDeclaration(node) {\n var symbol = getReferencedValueSymbol(node);\n return symbol && symbol.flags & 8388608 /* Alias */ ? getDeclarationOfAliasSymbol(symbol) : undefined;\n }", "language": "javascript", "code": "function getReferencedImportDeclaration(node) {\n var symbol = getReferencedValueSymbol(node);\n return symbol && symbol.flags & 8388608 /* Alias */ ? getDeclarationOfAliasSymbol(symbol) : undefined;\n }", "code_tokens": ["function", "getReferencedImportDeclaration", "(", "node", ")", "{", "var", "symbol", "=", "getReferencedValueSymbol", "(", "node", ")", ";", "return", "symbol", "&&", "symbol", ".", "flags", "&", "8388608", "?", "getDeclarationOfAliasSymbol", "(", "symbol", ")", ":", "undefined", ";", "}"], "docstring": "When resolved as an expression identifier, if the given node references an import, return the declaration of that import. Otherwise, return undefined.", "docstring_tokens": ["When", "resolved", "as", "an", "expression", "identifier", "if", "the", "given", "node", "references", "an", "import", "return", "the", "declaration", "of", "that", "import", ".", "Otherwise", "return", "undefined", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L26438-L26441", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getReferencedNestedRedeclaration", "original_string": "function getReferencedNestedRedeclaration(node) {\n var symbol = getReferencedValueSymbol(node);\n return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined;\n }", "language": "javascript", "code": "function getReferencedNestedRedeclaration(node) {\n var symbol = getReferencedValueSymbol(node);\n return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined;\n }", "code_tokens": ["function", "getReferencedNestedRedeclaration", "(", "node", ")", "{", "var", "symbol", "=", "getReferencedValueSymbol", "(", "node", ")", ";", "return", "symbol", "&&", "isNestedRedeclarationSymbol", "(", "symbol", ")", "?", "symbol", ".", "valueDeclaration", ":", "undefined", ";", "}"], "docstring": "When resolved as an expression identifier, if the given node references a nested block scoped entity with a name that hides an existing name, return the declaration of that entity. Otherwise, return undefined.", "docstring_tokens": ["When", "resolved", "as", "an", "expression", "identifier", "if", "the", "given", "node", "references", "a", "nested", "block", "scoped", "entity", "with", "a", "name", "that", "hides", "an", "existing", "name", "return", "the", "declaration", "of", "that", "entity", ".", "Otherwise", "return", "undefined", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L26467-L26470", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getExportDefaultTempVariableName", "original_string": "function getExportDefaultTempVariableName() {\n var baseName = \"_default\";\n if (!ts.hasProperty(currentSourceFile.identifiers, baseName)) {\n return baseName;\n }\n var count = 0;\n while (true) {\n var name_18 = baseName + \"_\" + (++count);\n if (!ts.hasProperty(currentSourceFile.identifiers, name_18)) {\n return name_18;\n }\n }\n }", "language": "javascript", "code": "function getExportDefaultTempVariableName() {\n var baseName = \"_default\";\n if (!ts.hasProperty(currentSourceFile.identifiers, baseName)) {\n return baseName;\n }\n var count = 0;\n while (true) {\n var name_18 = baseName + \"_\" + (++count);\n if (!ts.hasProperty(currentSourceFile.identifiers, name_18)) {\n return name_18;\n }\n }\n }", "code_tokens": ["function", "getExportDefaultTempVariableName", "(", ")", "{", "var", "baseName", "=", "\"_default\"", ";", "if", "(", "!", "ts", ".", "hasProperty", "(", "currentSourceFile", ".", "identifiers", ",", "baseName", ")", ")", "{", "return", "baseName", ";", "}", "var", "count", "=", "0", ";", "while", "(", "true", ")", "{", "var", "name_18", "=", "baseName", "+", "\"_\"", "+", "(", "++", "count", ")", ";", "if", "(", "!", "ts", ".", "hasProperty", "(", "currentSourceFile", ".", "identifiers", ",", "name_18", ")", ")", "{", "return", "name_18", ";", "}", "}", "}"], "docstring": "Return a temp variable name to be used in `export default` statements. The temp name will be of the form _default_counter. Note that export default is only allowed at most once in a module, so we do not need to keep track of created temp names.", "docstring_tokens": ["Return", "a", "temp", "variable", "name", "to", "be", "used", "in", "export", "default", "statements", ".", "The", "temp", "name", "will", "be", "of", "the", "form", "_default_counter", ".", "Note", "that", "export", "default", "is", "only", "allowed", "at", "most", "once", "in", "a", "module", "so", "we", "do", "not", "need", "to", "keep", "track", "of", "created", "temp", "names", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L28135-L28147", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "emitFiles", "original_string": "function emitFiles(resolver, host, targetSourceFile) {\n // emit output for the __extends helper function\n var extendsHelper = \"\\nvar __extends = (this && this.__extends) || function (d, b) {\\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\\n function __() { this.constructor = d; }\\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\\n};\";\n // emit output for the __decorate helper function\n var decorateHelper = \"\\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\\n if (typeof Reflect === \\\"object\\\" && typeof Reflect.decorate === \\\"function\\\") r = Reflect.decorate(decorators, target, key, desc);\\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\\n return c > 3 && r && Object.defineProperty(target, key, r), r;\\n};\";\n // emit output for the __metadata helper function\n var metadataHelper = \"\\nvar __metadata = (this && this.__metadata) || function (k, v) {\\n if (typeof Reflect === \\\"object\\\" && typeof Reflect.metadata === \\\"function\\\") return Reflect.metadata(k, v);\\n};\";\n // emit output for the __param helper function\n var paramHelper = \"\\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\\n return function (target, key) { decorator(target, key, paramIndex); }\\n};\";\n var awaiterHelper = \"\\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {\\n return new Promise(function (resolve, reject) {\\n generator = generator.call(thisArg, _arguments);\\n function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }\\n function onfulfill(value) { try { step(\\\"next\\\", value); } catch (e) { reject(e); } }\\n function onreject(value) { try { step(\\\"throw\\\", value); } catch (e) { reject(e); } }\\n function step(verb, value) {\\n var result = generator[verb](value);\\n result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);\\n }\\n step(\\\"next\\\", void 0);\\n });\\n};\";\n var compilerOptions = host.getCompilerOptions();\n var languageVersion = compilerOptions.target || 0 /* ES3 */;\n var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */;\n var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined;\n var diagnostics = [];\n var newLine = host.getNewLine();\n var jsxDesugaring = host.getCompilerOptions().jsx !== 1 /* Preserve */;\n var shouldEmitJsx = function (s) { return (s.languageVariant === 1 /* JSX */ && !jsxDesugaring); };\n if (targetSourceFile === undefined) {\n ts.forEach(host.getSourceFiles(), function (sourceFile) {\n if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) {\n var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? \".jsx\" : \".js\");\n emitFile(jsFilePath, sourceFile);\n }\n });\n if (compilerOptions.outFile || compilerOptions.out) {\n emitFile(compilerOptions.outFile || compilerOptions.out);\n }\n }\n else {\n // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service)\n if (ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions)) {\n var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? \".jsx\" : \".js\");\n emitFile(jsFilePath, targetSourceFile);\n }\n else if (!ts.isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) {\n emitFile(compilerOptions.outFile || compilerOptions.out);\n }\n }\n // Sort and make the unique list of diagnostics\n diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics);\n return {\n emitSkipped: false,\n diagnostics: diagnostics,\n sourceMaps: sourceMapDataList\n };\n function isUniqueLocalName(name, container) {\n for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) {\n if (node.locals && ts.hasProperty(node.locals, name)) {\n // We conservatively include alias symbols to cover cases where they're emitted as locals\n if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) {\n return false;\n }\n }\n }\n return true;\n }\n function emitJavaScript(jsFilePath, root) {\n var writer = ts.createTextWriter(newLine);\n var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent;\n var currentSourceFile;\n // name of an exporter function if file is a System external module\n // System.register([...], function () {...})\n // exporting in System modules looks like:\n // export var x; ... x = 1\n // =>\n // var x;... exporter(\"x\", x = 1)\n var exportFunctionForFile;\n var generatedNameSet = {};\n var nodeToGeneratedName = [];\n var computedPropertyNamesToGeneratedNames;\n var extendsEmitted = false;\n var decorateEmitted = false;\n var paramEmitted = false;\n var awaiterEmitted = false;\n var tempFlags = 0;\n var tempVariables;\n var tempParameters;\n var externalImports;\n var exportSpecifiers;\n var exportEquals;\n var hasExportStars;\n /** Write emitted output to disk */\n var writeEmittedFiles = writeJavaScriptFile;\n var detachedCommentsInfo;\n var writeComment = ts.writeCommentRange;\n /** Emit a node */\n var emit = emitNodeWithCommentsAndWithoutSourcemap;\n /** Called just before starting emit of a node */\n var emitStart = function (node) { };\n /** Called once the emit of the node is done */\n var emitEnd = function (node) { };\n /** Emit the text for the given token that comes after startPos\n * This by default writes the text provided with the given tokenKind\n * but if optional emitFn callback is provided the text is emitted using the callback instead of default text\n * @param tokenKind the kind of the token to search and emit\n * @param startPos the position in the source to start searching for the token\n * @param emitFn if given will be invoked to emit the text instead of actual token emit */\n var emitToken = emitTokenText;\n /** Called to before starting the lexical scopes as in function/class in the emitted code because of node\n * @param scopeDeclaration node that starts the lexical scope\n * @param scopeName Optional name of this scope instead of deducing one from the declaration node */\n var scopeEmitStart = function (scopeDeclaration, scopeName) { };\n /** Called after coming out of the scope */\n var scopeEmitEnd = function () { };\n /** Sourcemap data that will get encoded */\n var sourceMapData;\n /** If removeComments is true, no leading-comments needed to be emitted **/\n var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker;\n var moduleEmitDelegates = (_a = {},\n _a[5 /* ES6 */] = emitES6Module,\n _a[2 /* AMD */] = emitAMDModule,\n _a[4 /* System */] = emitSystemModule,\n _a[3 /* UMD */] = emitUMDModule,\n _a[1 /* CommonJS */] = emitCommonJSModule,\n _a\n );\n if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {\n initializeEmitterWithSourceMaps();\n }\n if (root) {\n // Do not call emit directly. It does not set the currentSourceFile.\n emitSourceFile(root);\n }\n else {\n ts.forEach(host.getSourceFiles(), function (sourceFile) {\n if (!isExternalModuleOrDeclarationFile(sourceFile)) {\n emitSourceFile(sourceFile);\n }\n });\n }\n writeLine();\n writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM);\n return;\n function emitSourceFile(sourceFile) {\n currentSourceFile = sourceFile;\n exportFunctionForFile = undefined;\n emit(sourceFile);\n }\n function isUniqueName(name) {\n return !resolver.hasGlobalName(name) &&\n !ts.hasProperty(currentSourceFile.identifiers, name) &&\n !ts.hasProperty(generatedNameSet, name);\n }\n // Return the next available name in the pattern _a ... _z, _0, _1, ...\n // TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.\n // Note that names generated by makeTempVariableName and makeUniqueName will never conflict.\n function makeTempVariableName(flags) {\n if (flags && !(tempFlags & flags)) {\n var name_19 = flags === 268435456 /* _i */ ? \"_i\" : \"_n\";\n if (isUniqueName(name_19)) {\n tempFlags |= flags;\n return name_19;\n }\n }\n while (true) {\n var count = tempFlags & 268435455 /* CountMask */;\n tempFlags++;\n // Skip over 'i' and 'n'\n if (count !== 8 && count !== 13) {\n var name_20 = count < 26 ? \"_\" + String.fromCharCode(97 /* a */ + count) : \"_\" + (count - 26);\n if (isUniqueName(name_20)) {\n return name_20;\n }\n }\n }\n }\n // Generate a name that is unique within the current file and doesn't conflict with any names\n // in global scope. The name is formed by adding an '_n' suffix to the specified base name,\n // where n is a positive integer. Note that names generated by makeTempVariableName and\n // makeUniqueName are guaranteed to never conflict.\n function makeUniqueName(baseName) {\n // Find the first unique 'name_n', where n is a positive number\n if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {\n baseName += \"_\";\n }\n var i = 1;\n while (true) {\n var generatedName = baseName + i;\n if (isUniqueName(generatedName)) {\n return generatedNameSet[generatedName] = generatedName;\n }\n i++;\n }\n }\n function generateNameForModuleOrEnum(node) {\n var name = node.name.text;\n // Use module/enum name itself if it is unique, otherwise make a unique variation\n return isUniqueLocalName(name, node) ? name : makeUniqueName(name);\n }\n function generateNameForImportOrExportDeclaration(node) {\n var expr = ts.getExternalModuleName(node);\n var baseName = expr.kind === 9 /* StringLiteral */ ?\n ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : \"module\";\n return makeUniqueName(baseName);\n }\n function generateNameForExportDefault() {\n return makeUniqueName(\"default\");\n }\n function generateNameForClassExpression() {\n return makeUniqueName(\"class\");\n }\n function generateNameForNode(node) {\n switch (node.kind) {\n case 69 /* Identifier */:\n return makeUniqueName(node.text);\n case 218 /* ModuleDeclaration */:\n case 217 /* EnumDeclaration */:\n return generateNameForModuleOrEnum(node);\n case 222 /* ImportDeclaration */:\n case 228 /* ExportDeclaration */:\n return generateNameForImportOrExportDeclaration(node);\n case 213 /* FunctionDeclaration */:\n case 214 /* ClassDeclaration */:\n case 227 /* ExportAssignment */:\n return generateNameForExportDefault();\n case 186 /* ClassExpression */:\n return generateNameForClassExpression();\n }\n }\n function getGeneratedNameForNode(node) {\n var id = ts.getNodeId(node);\n return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node)));\n }\n function initializeEmitterWithSourceMaps() {\n var sourceMapDir; // The directory in which sourcemap will be\n // Current source map file and its index in the sources list\n var sourceMapSourceIndex = -1;\n // Names and its index map\n var sourceMapNameIndexMap = {};\n var sourceMapNameIndices = [];\n function getSourceMapNameIndex() {\n return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1;\n }\n // Last recorded and encoded spans\n var lastRecordedSourceMapSpan;\n var lastEncodedSourceMapSpan = {\n emittedLine: 1,\n emittedColumn: 1,\n sourceLine: 1,\n sourceColumn: 1,\n sourceIndex: 0\n };\n var lastEncodedNameIndex = 0;\n // Encoding for sourcemap span\n function encodeLastRecordedSourceMapSpan() {\n if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) {\n return;\n }\n var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn;\n // Line/Comma delimiters\n if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) {\n // Emit comma to separate the entry\n if (sourceMapData.sourceMapMappings) {\n sourceMapData.sourceMapMappings += \",\";\n }\n }\n else {\n // Emit line delimiters\n for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) {\n sourceMapData.sourceMapMappings += \";\";\n }\n prevEncodedEmittedColumn = 1;\n }\n // 1. Relative Column 0 based\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn);\n // 2. Relative sourceIndex\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex);\n // 3. Relative sourceLine 0 based\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine);\n // 4. Relative sourceColumn 0 based\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn);\n // 5. Relative namePosition 0 based\n if (lastRecordedSourceMapSpan.nameIndex >= 0) {\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex);\n lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex;\n }\n lastEncodedSourceMapSpan = lastRecordedSourceMapSpan;\n sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan);\n function base64VLQFormatEncode(inValue) {\n function base64FormatEncode(inValue) {\n if (inValue < 64) {\n return \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt(inValue);\n }\n throw TypeError(inValue + \": not a 64 based value\");\n }\n // Add a new least significant bit that has the sign of the value.\n // if negative number the least significant bit that gets added to the number has value 1\n // else least significant bit value that gets added is 0\n // eg. -1 changes to binary : 01 [1] => 3\n // +1 changes to binary : 01 [0] => 2\n if (inValue < 0) {\n inValue = ((-inValue) << 1) + 1;\n }\n else {\n inValue = inValue << 1;\n }\n // Encode 5 bits at a time starting from least significant bits\n var encodedStr = \"\";\n do {\n var currentDigit = inValue & 31; // 11111\n inValue = inValue >> 5;\n if (inValue > 0) {\n // There are still more digits to decode, set the msb (6th bit)\n currentDigit = currentDigit | 32;\n }\n encodedStr = encodedStr + base64FormatEncode(currentDigit);\n } while (inValue > 0);\n return encodedStr;\n }\n }\n function recordSourceMapSpan(pos) {\n var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos);\n // Convert the location to be one-based.\n sourceLinePos.line++;\n sourceLinePos.character++;\n var emittedLine = writer.getLine();\n var emittedColumn = writer.getColumn();\n // If this location wasn't recorded or the location in source is going backwards, record the span\n if (!lastRecordedSourceMapSpan ||\n lastRecordedSourceMapSpan.emittedLine !== emittedLine ||\n lastRecordedSourceMapSpan.emittedColumn !== emittedColumn ||\n (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex &&\n (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line ||\n (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) {\n // Encode the last recordedSpan before assigning new\n encodeLastRecordedSourceMapSpan();\n // New span\n lastRecordedSourceMapSpan = {\n emittedLine: emittedLine,\n emittedColumn: emittedColumn,\n sourceLine: sourceLinePos.line,\n sourceColumn: sourceLinePos.character,\n nameIndex: getSourceMapNameIndex(),\n sourceIndex: sourceMapSourceIndex\n };\n }\n else {\n // Take the new pos instead since there is no change in emittedLine and column since last location\n lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line;\n lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character;\n lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex;\n }\n }\n function recordEmitNodeStartSpan(node) {\n // Get the token pos after skipping to the token (ignoring the leading trivia)\n recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos));\n }\n function recordEmitNodeEndSpan(node) {\n recordSourceMapSpan(node.end);\n }\n function writeTextWithSpanRecord(tokenKind, startPos, emitFn) {\n var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos);\n recordSourceMapSpan(tokenStartPos);\n var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn);\n recordSourceMapSpan(tokenEndPos);\n return tokenEndPos;\n }\n function recordNewSourceFileStart(node) {\n // Add the file to tsFilePaths\n // If sourceroot option: Use the relative path corresponding to the common directory path\n // otherwise source locations relative to map file location\n var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;\n sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, host.getCurrentDirectory(), host.getCanonicalFileName,\n /*isAbsolutePathAnUrl*/ true));\n sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1;\n // The one that can be used from program to get the actual source file\n sourceMapData.inputSourceFileNames.push(node.fileName);\n if (compilerOptions.inlineSources) {\n if (!sourceMapData.sourceMapSourcesContent) {\n sourceMapData.sourceMapSourcesContent = [];\n }\n sourceMapData.sourceMapSourcesContent.push(node.text);\n }\n }\n function recordScopeNameOfNode(node, scopeName) {\n function recordScopeNameIndex(scopeNameIndex) {\n sourceMapNameIndices.push(scopeNameIndex);\n }\n function recordScopeNameStart(scopeName) {\n var scopeNameIndex = -1;\n if (scopeName) {\n var parentIndex = getSourceMapNameIndex();\n if (parentIndex !== -1) {\n // Child scopes are always shown with a dot (even if they have no name),\n // unless it is a computed property. Then it is shown with brackets,\n // but the brackets are included in the name.\n var name_21 = node.name;\n if (!name_21 || name_21.kind !== 136 /* ComputedPropertyName */) {\n scopeName = \".\" + scopeName;\n }\n scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName;\n }\n scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName);\n if (scopeNameIndex === undefined) {\n scopeNameIndex = sourceMapData.sourceMapNames.length;\n sourceMapData.sourceMapNames.push(scopeName);\n sourceMapNameIndexMap[scopeName] = scopeNameIndex;\n }\n }\n recordScopeNameIndex(scopeNameIndex);\n }\n if (scopeName) {\n // The scope was already given a name use it\n recordScopeNameStart(scopeName);\n }\n else if (node.kind === 213 /* FunctionDeclaration */ ||\n node.kind === 173 /* FunctionExpression */ ||\n node.kind === 143 /* MethodDeclaration */ ||\n node.kind === 142 /* MethodSignature */ ||\n node.kind === 145 /* GetAccessor */ ||\n node.kind === 146 /* SetAccessor */ ||\n node.kind === 218 /* ModuleDeclaration */ ||\n node.kind === 214 /* ClassDeclaration */ ||\n node.kind === 217 /* EnumDeclaration */) {\n // Declaration and has associated name use it\n if (node.name) {\n var name_22 = node.name;\n // For computed property names, the text will include the brackets\n scopeName = name_22.kind === 136 /* ComputedPropertyName */\n ? ts.getTextOfNode(name_22)\n : node.name.text;\n }\n recordScopeNameStart(scopeName);\n }\n else {\n // Block just use the name from upper level scope\n recordScopeNameIndex(getSourceMapNameIndex());\n }\n }\n function recordScopeNameEnd() {\n sourceMapNameIndices.pop();\n }\n ;\n function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) {\n recordSourceMapSpan(comment.pos);\n ts.writeCommentRange(currentSourceFile, writer, comment, newLine);\n recordSourceMapSpan(comment.end);\n }\n function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) {\n if (typeof JSON !== \"undefined\") {\n var map_1 = {\n version: version,\n file: file,\n sourceRoot: sourceRoot,\n sources: sources,\n names: names,\n mappings: mappings\n };\n if (sourcesContent !== undefined) {\n map_1.sourcesContent = sourcesContent;\n }\n return JSON.stringify(map_1);\n }\n return \"{\\\"version\\\":\" + version + \",\\\"file\\\":\\\"\" + ts.escapeString(file) + \"\\\",\\\"sourceRoot\\\":\\\"\" + ts.escapeString(sourceRoot) + \"\\\",\\\"sources\\\":[\" + serializeStringArray(sources) + \"],\\\"names\\\":[\" + serializeStringArray(names) + \"],\\\"mappings\\\":\\\"\" + ts.escapeString(mappings) + \"\\\" \" + (sourcesContent !== undefined ? \",\\\"sourcesContent\\\":[\" + serializeStringArray(sourcesContent) + \"]\" : \"\") + \"}\";\n function serializeStringArray(list) {\n var output = \"\";\n for (var i = 0, n = list.length; i < n; i++) {\n if (i) {\n output += \",\";\n }\n output += \"\\\"\" + ts.escapeString(list[i]) + \"\\\"\";\n }\n return output;\n }\n }\n function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) {\n encodeLastRecordedSourceMapSpan();\n var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent);\n sourceMapDataList.push(sourceMapData);\n var sourceMapUrl;\n if (compilerOptions.inlineSourceMap) {\n // Encode the sourceMap into the sourceMap url\n var base64SourceMapText = ts.convertToBase64(sourceMapText);\n sourceMapUrl = \"//# sourceMappingURL=data:application/json;base64,\" + base64SourceMapText;\n }\n else {\n // Write source map file\n ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, /*writeByteOrderMark*/ false);\n sourceMapUrl = \"//# sourceMappingURL=\" + sourceMapData.jsSourceMappingURL;\n }\n // Write sourcemap url to the js file and write the js file\n writeJavaScriptFile(emitOutput + sourceMapUrl, writeByteOrderMark);\n }\n // Initialize source map data\n var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath));\n sourceMapData = {\n sourceMapFilePath: jsFilePath + \".map\",\n jsSourceMappingURL: sourceMapJsFile + \".map\",\n sourceMapFile: sourceMapJsFile,\n sourceMapSourceRoot: compilerOptions.sourceRoot || \"\",\n sourceMapSources: [],\n inputSourceFileNames: [],\n sourceMapNames: [],\n sourceMapMappings: \"\",\n sourceMapSourcesContent: undefined,\n sourceMapDecodedMappings: []\n };\n // Normalize source root and make sure it has trailing \"/\" so that it can be used to combine paths with the\n // relative paths of the sources list in the sourcemap\n sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot);\n if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) {\n sourceMapData.sourceMapSourceRoot += ts.directorySeparator;\n }\n if (compilerOptions.mapRoot) {\n sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot);\n if (root) {\n // For modules or multiple emit files the mapRoot will have directory structure like the sources\n // So if src\\a.ts and src\\lib\\b.ts are compiled together user would be moving the maps into mapRoot\\a.js.map and mapRoot\\lib\\b.js.map\n sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(root, host, sourceMapDir));\n }\n if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) {\n // The relative paths are relative to the common directory\n sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);\n sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), // get the relative sourceMapDir path based on jsFilePath\n ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap\n host.getCurrentDirectory(), host.getCanonicalFileName,\n /*isAbsolutePathAnUrl*/ true);\n }\n else {\n sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL);\n }\n }\n else {\n sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath));\n }\n function emitNodeWithSourceMap(node) {\n if (node) {\n if (ts.nodeIsSynthesized(node)) {\n return emitNodeWithoutSourceMap(node);\n }\n if (node.kind !== 248 /* SourceFile */) {\n recordEmitNodeStartSpan(node);\n emitNodeWithoutSourceMap(node);\n recordEmitNodeEndSpan(node);\n }\n else {\n recordNewSourceFileStart(node);\n emitNodeWithoutSourceMap(node);\n }\n }\n }\n function emitNodeWithCommentsAndWithSourcemap(node) {\n emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap);\n }\n writeEmittedFiles = writeJavaScriptAndSourceMapFile;\n emit = emitNodeWithCommentsAndWithSourcemap;\n emitStart = recordEmitNodeStartSpan;\n emitEnd = recordEmitNodeEndSpan;\n emitToken = writeTextWithSpanRecord;\n scopeEmitStart = recordScopeNameOfNode;\n scopeEmitEnd = recordScopeNameEnd;\n writeComment = writeCommentRangeWithMap;\n }\n function writeJavaScriptFile(emitOutput, writeByteOrderMark) {\n ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark);\n }\n // Create a temporary variable with a unique unused name.\n function createTempVariable(flags) {\n var result = ts.createSynthesizedNode(69 /* Identifier */);\n result.text = makeTempVariableName(flags);\n return result;\n }\n function recordTempDeclaration(name) {\n if (!tempVariables) {\n tempVariables = [];\n }\n tempVariables.push(name);\n }\n function createAndRecordTempVariable(flags) {\n var temp = createTempVariable(flags);\n recordTempDeclaration(temp);\n return temp;\n }\n function emitTempDeclarations(newLine) {\n if (tempVariables) {\n if (newLine) {\n writeLine();\n }\n else {\n write(\" \");\n }\n write(\"var \");\n emitCommaList(tempVariables);\n write(\";\");\n }\n }\n function emitTokenText(tokenKind, startPos, emitFn) {\n var tokenString = ts.tokenToString(tokenKind);\n if (emitFn) {\n emitFn();\n }\n else {\n write(tokenString);\n }\n return startPos + tokenString.length;\n }\n function emitOptional(prefix, node) {\n if (node) {\n write(prefix);\n emit(node);\n }\n }\n function emitParenthesizedIf(node, parenthesized) {\n if (parenthesized) {\n write(\"(\");\n }\n emit(node);\n if (parenthesized) {\n write(\")\");\n }\n }\n function emitTrailingCommaIfPresent(nodeList) {\n if (nodeList.hasTrailingComma) {\n write(\",\");\n }\n }\n function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) {\n ts.Debug.assert(nodes.length > 0);\n increaseIndent();\n if (nodeStartPositionsAreOnSameLine(parent, nodes[0])) {\n if (spacesBetweenBraces) {\n write(\" \");\n }\n }\n else {\n writeLine();\n }\n for (var i = 0, n = nodes.length; i < n; i++) {\n if (i) {\n if (nodeEndIsOnSameLineAsNodeStart(nodes[i - 1], nodes[i])) {\n write(\", \");\n }\n else {\n write(\",\");\n writeLine();\n }\n }\n emit(nodes[i]);\n }\n if (nodes.hasTrailingComma && allowTrailingComma) {\n write(\",\");\n }\n decreaseIndent();\n if (nodeEndPositionsAreOnSameLine(parent, ts.lastOrUndefined(nodes))) {\n if (spacesBetweenBraces) {\n write(\" \");\n }\n }\n else {\n writeLine();\n }\n }\n function emitList(nodes, start, count, multiLine, trailingComma, leadingComma, noTrailingNewLine, emitNode) {\n if (!emitNode) {\n emitNode = emit;\n }\n for (var i = 0; i < count; i++) {\n if (multiLine) {\n if (i || leadingComma) {\n write(\",\");\n }\n writeLine();\n }\n else {\n if (i || leadingComma) {\n write(\", \");\n }\n }\n var node = nodes[start + i];\n // This emitting is to make sure we emit following comment properly\n // ...(x, /*comment1*/ y)...\n // ^ => node.pos\n // \"comment1\" is not considered leading comment for \"y\" but rather\n // considered as trailing comment of the previous node.\n emitTrailingCommentsOfPosition(node.pos);\n emitNode(node);\n leadingComma = true;\n }\n if (trailingComma) {\n write(\",\");\n }\n if (multiLine && !noTrailingNewLine) {\n writeLine();\n }\n return count;\n }\n function emitCommaList(nodes) {\n if (nodes) {\n emitList(nodes, 0, nodes.length, /*multiline*/ false, /*trailingComma*/ false);\n }\n }\n function emitLines(nodes) {\n emitLinesStartingAt(nodes, /*startIndex*/ 0);\n }\n function emitLinesStartingAt(nodes, startIndex) {\n for (var i = startIndex; i < nodes.length; i++) {\n writeLine();\n emit(nodes[i]);\n }\n }\n function isBinaryOrOctalIntegerLiteral(node, text) {\n if (node.kind === 8 /* NumericLiteral */ && text.length > 1) {\n switch (text.charCodeAt(1)) {\n case 98 /* b */:\n case 66 /* B */:\n case 111 /* o */:\n case 79 /* O */:\n return true;\n }\n }\n return false;\n }\n function emitLiteral(node) {\n var text = getLiteralText(node);\n if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {\n writer.writeLiteral(text);\n }\n else if (languageVersion < 2 /* ES6 */ && isBinaryOrOctalIntegerLiteral(node, text)) {\n write(node.text);\n }\n else {\n write(text);\n }\n }\n function getLiteralText(node) {\n // Any template literal or string literal with an extended escape\n // (e.g. \"\\u{0067}\") will need to be downleveled as a escaped string literal.\n if (languageVersion < 2 /* ES6 */ && (ts.isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {\n return getQuotedEscapedLiteralText(\"\\\"\", node.text, \"\\\"\");\n }\n // If we don't need to downlevel and we can reach the original source text using\n // the node's parent reference, then simply get the text as it was originally written.\n if (node.parent) {\n return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);\n }\n // If we can't reach the original source text, use the canonical form if it's a number,\n // or an escaped quoted form of the original text if it's string-like.\n switch (node.kind) {\n case 9 /* StringLiteral */:\n return getQuotedEscapedLiteralText(\"\\\"\", node.text, \"\\\"\");\n case 11 /* NoSubstitutionTemplateLiteral */:\n return getQuotedEscapedLiteralText(\"`\", node.text, \"`\");\n case 12 /* TemplateHead */:\n return getQuotedEscapedLiteralText(\"`\", node.text, \"${\");\n case 13 /* TemplateMiddle */:\n return getQuotedEscapedLiteralText(\"}\", node.text, \"${\");\n case 14 /* TemplateTail */:\n return getQuotedEscapedLiteralText(\"}\", node.text, \"`\");\n case 8 /* NumericLiteral */:\n return node.text;\n }\n ts.Debug.fail(\"Literal kind '\" + node.kind + \"' not accounted for.\");\n }\n function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) {\n return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote;\n }\n function emitDownlevelRawTemplateLiteral(node) {\n // Find original source text, since we need to emit the raw strings of the tagged template.\n // The raw strings contain the (escaped) strings of what the user wrote.\n // Examples: `\\n` is converted to \"\\\\n\", a template string with a newline to \"\\n\".\n var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);\n // text contains the original source, it will also contain quotes (\"`\"), dolar signs and braces (\"${\" and \"}\"),\n // thus we need to remove those characters.\n // First template piece starts with \"`\", others with \"}\"\n // Last template piece ends with \"`\", others with \"${\"\n var isLast = node.kind === 11 /* NoSubstitutionTemplateLiteral */ || node.kind === 14 /* TemplateTail */;\n text = text.substring(1, text.length - (isLast ? 1 : 2));\n // Newline normalization:\n // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's\n // and LineTerminatorSequences are normalized to for both TV and TRV.\n text = text.replace(/\\r\\n?/g, \"\\n\");\n text = ts.escapeString(text);\n write(\"\\\"\" + text + \"\\\"\");\n }\n function emitDownlevelTaggedTemplateArray(node, literalEmitter) {\n write(\"[\");\n if (node.template.kind === 11 /* NoSubstitutionTemplateLiteral */) {\n literalEmitter(node.template);\n }\n else {\n literalEmitter(node.template.head);\n ts.forEach(node.template.templateSpans, function (child) {\n write(\", \");\n literalEmitter(child.literal);\n });\n }\n write(\"]\");\n }\n function emitDownlevelTaggedTemplate(node) {\n var tempVariable = createAndRecordTempVariable(0 /* Auto */);\n write(\"(\");\n emit(tempVariable);\n write(\" = \");\n emitDownlevelTaggedTemplateArray(node, emit);\n write(\", \");\n emit(tempVariable);\n write(\".raw = \");\n emitDownlevelTaggedTemplateArray(node, emitDownlevelRawTemplateLiteral);\n write(\", \");\n emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag));\n write(\"(\");\n emit(tempVariable);\n // Now we emit the expressions\n if (node.template.kind === 183 /* TemplateExpression */) {\n ts.forEach(node.template.templateSpans, function (templateSpan) {\n write(\", \");\n var needsParens = templateSpan.expression.kind === 181 /* BinaryExpression */\n && templateSpan.expression.operatorToken.kind === 24 /* CommaToken */;\n emitParenthesizedIf(templateSpan.expression, needsParens);\n });\n }\n write(\"))\");\n }\n function emitTemplateExpression(node) {\n // In ES6 mode and above, we can simply emit each portion of a template in order, but in\n // ES3 & ES5 we must convert the template expression into a series of string concatenations.\n if (languageVersion >= 2 /* ES6 */) {\n ts.forEachChild(node, emit);\n return;\n }\n var emitOuterParens = ts.isExpression(node.parent)\n && templateNeedsParens(node, node.parent);\n if (emitOuterParens) {\n write(\"(\");\n }\n var headEmitted = false;\n if (shouldEmitTemplateHead()) {\n emitLiteral(node.head);\n headEmitted = true;\n }\n for (var i = 0, n = node.templateSpans.length; i < n; i++) {\n var templateSpan = node.templateSpans[i];\n // Check if the expression has operands and binds its operands less closely than binary '+'.\n // If it does, we need to wrap the expression in parentheses. Otherwise, something like\n // `abc${ 1 << 2 }`\n // becomes\n // \"abc\" + 1 << 2 + \"\"\n // which is really\n // (\"abc\" + 1) << (2 + \"\")\n // rather than\n // \"abc\" + (1 << 2) + \"\"\n var needsParens = templateSpan.expression.kind !== 172 /* ParenthesizedExpression */\n && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */;\n if (i > 0 || headEmitted) {\n // If this is the first span and the head was not emitted, then this templateSpan's\n // expression will be the first to be emitted. Don't emit the preceding ' + ' in that\n // case.\n write(\" + \");\n }\n emitParenthesizedIf(templateSpan.expression, needsParens);\n // Only emit if the literal is non-empty.\n // The binary '+' operator is left-associative, so the first string concatenation\n // with the head will force the result up to this point to be a string.\n // Emitting a '+ \"\"' has no semantic effect for middles and tails.\n if (templateSpan.literal.text.length !== 0) {\n write(\" + \");\n emitLiteral(templateSpan.literal);\n }\n }\n if (emitOuterParens) {\n write(\")\");\n }\n function shouldEmitTemplateHead() {\n // If this expression has an empty head literal and the first template span has a non-empty\n // literal, then emitting the empty head literal is not necessary.\n // `${ foo } and ${ bar }`\n // can be emitted as\n // foo + \" and \" + bar\n // This is because it is only required that one of the first two operands in the emit\n // output must be a string literal, so that the other operand and all following operands\n // are forced into strings.\n //\n // If the first template span has an empty literal, then the head must still be emitted.\n // `${ foo }${ bar }`\n // must still be emitted as\n // \"\" + foo + bar\n // There is always atleast one templateSpan in this code path, since\n // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()\n ts.Debug.assert(node.templateSpans.length !== 0);\n return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;\n }\n function templateNeedsParens(template, parent) {\n switch (parent.kind) {\n case 168 /* CallExpression */:\n case 169 /* NewExpression */:\n return parent.expression === template;\n case 170 /* TaggedTemplateExpression */:\n case 172 /* ParenthesizedExpression */:\n return false;\n default:\n return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */;\n }\n }\n /**\n * Returns whether the expression has lesser, greater,\n * or equal precedence to the binary '+' operator\n */\n function comparePrecedenceToBinaryPlus(expression) {\n // All binary expressions have lower precedence than '+' apart from '*', '/', and '%'\n // which have greater precedence and '-' which has equal precedence.\n // All unary operators have a higher precedence apart from yield.\n // Arrow functions and conditionals have a lower precedence,\n // although we convert the former into regular function expressions in ES5 mode,\n // and in ES6 mode this function won't get called anyway.\n //\n // TODO (drosen): Note that we need to account for the upcoming 'yield' and\n // spread ('...') unary operators that are anticipated for ES6.\n switch (expression.kind) {\n case 181 /* BinaryExpression */:\n switch (expression.operatorToken.kind) {\n case 37 /* AsteriskToken */:\n case 39 /* SlashToken */:\n case 40 /* PercentToken */:\n return 1 /* GreaterThan */;\n case 35 /* PlusToken */:\n case 36 /* MinusToken */:\n return 0 /* EqualTo */;\n default:\n return -1 /* LessThan */;\n }\n case 184 /* YieldExpression */:\n case 182 /* ConditionalExpression */:\n return -1 /* LessThan */;\n default:\n return 1 /* GreaterThan */;\n }\n }\n }\n function emitTemplateSpan(span) {\n emit(span.expression);\n emit(span.literal);\n }\n function jsxEmitReact(node) {\n /// Emit a tag name, which is either '\"div\"' for lower-cased names, or\n /// 'Div' for upper-cased or dotted names\n function emitTagName(name) {\n if (name.kind === 69 /* Identifier */ && ts.isIntrinsicJsxName(name.text)) {\n write(\"\\\"\");\n emit(name);\n write(\"\\\"\");\n }\n else {\n emit(name);\n }\n }\n /// Emit an attribute name, which is quoted if it needs to be quoted. Because\n /// these emit into an object literal property name, we don't need to be worried\n /// about keywords, just non-identifier characters\n function emitAttributeName(name) {\n if (/[A-Za-z_]+[\\w*]/.test(name.text)) {\n write(\"\\\"\");\n emit(name);\n write(\"\\\"\");\n }\n else {\n emit(name);\n }\n }\n /// Emit an name/value pair for an attribute (e.g. \"x: 3\")\n function emitJsxAttribute(node) {\n emitAttributeName(node.name);\n write(\": \");\n if (node.initializer) {\n emit(node.initializer);\n }\n else {\n write(\"true\");\n }\n }\n function emitJsxElement(openingNode, children) {\n var syntheticReactRef = ts.createSynthesizedNode(69 /* Identifier */);\n syntheticReactRef.text = \"React\";\n syntheticReactRef.parent = openingNode;\n // Call React.createElement(tag, ...\n emitLeadingComments(openingNode);\n emitExpressionIdentifier(syntheticReactRef);\n write(\".createElement(\");\n emitTagName(openingNode.tagName);\n write(\", \");\n // Attribute list\n if (openingNode.attributes.length === 0) {\n // When there are no attributes, React wants \"null\"\n write(\"null\");\n }\n else {\n // Either emit one big object literal (no spread attribs), or\n // a call to React.__spread\n var attrs = openingNode.attributes;\n if (ts.forEach(attrs, function (attr) { return attr.kind === 239 /* JsxSpreadAttribute */; })) {\n emitExpressionIdentifier(syntheticReactRef);\n write(\".__spread(\");\n var haveOpenedObjectLiteral = false;\n for (var i_1 = 0; i_1 < attrs.length; i_1++) {\n if (attrs[i_1].kind === 239 /* JsxSpreadAttribute */) {\n // If this is the first argument, we need to emit a {} as the first argument\n if (i_1 === 0) {\n write(\"{}, \");\n }\n if (haveOpenedObjectLiteral) {\n write(\"}\");\n haveOpenedObjectLiteral = false;\n }\n if (i_1 > 0) {\n write(\", \");\n }\n emit(attrs[i_1].expression);\n }\n else {\n ts.Debug.assert(attrs[i_1].kind === 238 /* JsxAttribute */);\n if (haveOpenedObjectLiteral) {\n write(\", \");\n }\n else {\n haveOpenedObjectLiteral = true;\n if (i_1 > 0) {\n write(\", \");\n }\n write(\"{\");\n }\n emitJsxAttribute(attrs[i_1]);\n }\n }\n if (haveOpenedObjectLiteral)\n write(\"}\");\n write(\")\"); // closing paren to React.__spread(\n }\n else {\n // One object literal with all the attributes in them\n write(\"{\");\n for (var i = 0; i < attrs.length; i++) {\n if (i > 0) {\n write(\", \");\n }\n emitJsxAttribute(attrs[i]);\n }\n write(\"}\");\n }\n }\n // Children\n if (children) {\n for (var i = 0; i < children.length; i++) {\n // Don't emit empty expressions\n if (children[i].kind === 240 /* JsxExpression */ && !(children[i].expression)) {\n continue;\n }\n // Don't emit empty strings\n if (children[i].kind === 236 /* JsxText */) {\n var text = getTextToEmit(children[i]);\n if (text !== undefined) {\n write(\", \\\"\");\n write(text);\n write(\"\\\"\");\n }\n }\n else {\n write(\", \");\n emit(children[i]);\n }\n }\n }\n // Closing paren\n write(\")\"); // closes \"React.createElement(\"\n emitTrailingComments(openingNode);\n }\n if (node.kind === 233 /* JsxElement */) {\n emitJsxElement(node.openingElement, node.children);\n }\n else {\n ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */);\n emitJsxElement(node);\n }\n }\n function jsxEmitPreserve(node) {\n function emitJsxAttribute(node) {\n emit(node.name);\n if (node.initializer) {\n write(\"=\");\n emit(node.initializer);\n }\n }\n function emitJsxSpreadAttribute(node) {\n write(\"{...\");\n emit(node.expression);\n write(\"}\");\n }\n function emitAttributes(attribs) {\n for (var i = 0, n = attribs.length; i < n; i++) {\n if (i > 0) {\n write(\" \");\n }\n if (attribs[i].kind === 239 /* JsxSpreadAttribute */) {\n emitJsxSpreadAttribute(attribs[i]);\n }\n else {\n ts.Debug.assert(attribs[i].kind === 238 /* JsxAttribute */);\n emitJsxAttribute(attribs[i]);\n }\n }\n }\n function emitJsxOpeningOrSelfClosingElement(node) {\n write(\"<\");\n emit(node.tagName);\n if (node.attributes.length > 0 || (node.kind === 234 /* JsxSelfClosingElement */)) {\n write(\" \");\n }\n emitAttributes(node.attributes);\n if (node.kind === 234 /* JsxSelfClosingElement */) {\n write(\"/>\");\n }\n else {\n write(\">\");\n }\n }\n function emitJsxClosingElement(node) {\n write(\"\");\n }\n function emitJsxElement(node) {\n emitJsxOpeningOrSelfClosingElement(node.openingElement);\n for (var i = 0, n = node.children.length; i < n; i++) {\n emit(node.children[i]);\n }\n emitJsxClosingElement(node.closingElement);\n }\n if (node.kind === 233 /* JsxElement */) {\n emitJsxElement(node);\n }\n else {\n ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */);\n emitJsxOpeningOrSelfClosingElement(node);\n }\n }\n // This function specifically handles numeric/string literals for enum and accessor 'identifiers'.\n // In a sense, it does not actually emit identifiers as much as it declares a name for a specific property.\n // For example, this is utilized when feeding in a result to Object.defineProperty.\n function emitExpressionForPropertyName(node) {\n ts.Debug.assert(node.kind !== 163 /* BindingElement */);\n if (node.kind === 9 /* StringLiteral */) {\n emitLiteral(node);\n }\n else if (node.kind === 136 /* ComputedPropertyName */) {\n // if this is a decorated computed property, we will need to capture the result\n // of the property expression so that we can apply decorators later. This is to ensure\n // we don't introduce unintended side effects:\n //\n // class C {\n // [_a = x]() { }\n // }\n //\n // The emit for the decorated computed property decorator is:\n //\n // __decorate([dec], C.prototype, _a, Object.getOwnPropertyDescriptor(C.prototype, _a));\n //\n if (ts.nodeIsDecorated(node.parent)) {\n if (!computedPropertyNamesToGeneratedNames) {\n computedPropertyNamesToGeneratedNames = [];\n }\n var generatedName = computedPropertyNamesToGeneratedNames[ts.getNodeId(node)];\n if (generatedName) {\n // we have already generated a variable for this node, write that value instead.\n write(generatedName);\n return;\n }\n generatedName = createAndRecordTempVariable(0 /* Auto */).text;\n computedPropertyNamesToGeneratedNames[ts.getNodeId(node)] = generatedName;\n write(generatedName);\n write(\" = \");\n }\n emit(node.expression);\n }\n else {\n write(\"\\\"\");\n if (node.kind === 8 /* NumericLiteral */) {\n write(node.text);\n }\n else {\n writeTextOfNode(currentSourceFile, node);\n }\n write(\"\\\"\");\n }\n }\n function isExpressionIdentifier(node) {\n var parent = node.parent;\n switch (parent.kind) {\n case 164 /* ArrayLiteralExpression */:\n case 189 /* AsExpression */:\n case 181 /* BinaryExpression */:\n case 168 /* CallExpression */:\n case 241 /* CaseClause */:\n case 136 /* ComputedPropertyName */:\n case 182 /* ConditionalExpression */:\n case 139 /* Decorator */:\n case 175 /* DeleteExpression */:\n case 197 /* DoStatement */:\n case 167 /* ElementAccessExpression */:\n case 227 /* ExportAssignment */:\n case 195 /* ExpressionStatement */:\n case 188 /* ExpressionWithTypeArguments */:\n case 199 /* ForStatement */:\n case 200 /* ForInStatement */:\n case 201 /* ForOfStatement */:\n case 196 /* IfStatement */:\n case 234 /* JsxSelfClosingElement */:\n case 235 /* JsxOpeningElement */:\n case 239 /* JsxSpreadAttribute */:\n case 240 /* JsxExpression */:\n case 169 /* NewExpression */:\n case 172 /* ParenthesizedExpression */:\n case 180 /* PostfixUnaryExpression */:\n case 179 /* PrefixUnaryExpression */:\n case 204 /* ReturnStatement */:\n case 246 /* ShorthandPropertyAssignment */:\n case 185 /* SpreadElementExpression */:\n case 206 /* SwitchStatement */:\n case 170 /* TaggedTemplateExpression */:\n case 190 /* TemplateSpan */:\n case 208 /* ThrowStatement */:\n case 171 /* TypeAssertionExpression */:\n case 176 /* TypeOfExpression */:\n case 177 /* VoidExpression */:\n case 198 /* WhileStatement */:\n case 205 /* WithStatement */:\n case 184 /* YieldExpression */:\n return true;\n case 163 /* BindingElement */:\n case 247 /* EnumMember */:\n case 138 /* Parameter */:\n case 245 /* PropertyAssignment */:\n case 141 /* PropertyDeclaration */:\n case 211 /* VariableDeclaration */:\n return parent.initializer === node;\n case 166 /* PropertyAccessExpression */:\n return parent.expression === node;\n case 174 /* ArrowFunction */:\n case 173 /* FunctionExpression */:\n return parent.body === node;\n case 221 /* ImportEqualsDeclaration */:\n return parent.moduleReference === node;\n case 135 /* QualifiedName */:\n return parent.left === node;\n }\n return false;\n }\n function emitExpressionIdentifier(node) {\n if (resolver.getNodeCheckFlags(node) & 2048 /* LexicalArguments */) {\n write(\"_arguments\");\n return;\n }\n var container = resolver.getReferencedExportContainer(node);\n if (container) {\n if (container.kind === 248 /* SourceFile */) {\n // Identifier references module export\n if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) {\n write(\"exports.\");\n }\n }\n else {\n // Identifier references namespace export\n write(getGeneratedNameForNode(container));\n write(\".\");\n }\n }\n else {\n if (modulekind !== 5 /* ES6 */) {\n var declaration = resolver.getReferencedImportDeclaration(node);\n if (declaration) {\n if (declaration.kind === 223 /* ImportClause */) {\n // Identifier references default import\n write(getGeneratedNameForNode(declaration.parent));\n write(languageVersion === 0 /* ES3 */ ? \"[\\\"default\\\"]\" : \".default\");\n return;\n }\n else if (declaration.kind === 226 /* ImportSpecifier */) {\n // Identifier references named import\n write(getGeneratedNameForNode(declaration.parent.parent.parent));\n var name_23 = declaration.propertyName || declaration.name;\n var identifier = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, name_23);\n if (languageVersion === 0 /* ES3 */ && identifier === \"default\") {\n write(\"[\\\"default\\\"]\");\n }\n else {\n write(\".\");\n write(identifier);\n }\n return;\n }\n }\n }\n if (languageVersion !== 2 /* ES6 */) {\n var declaration = resolver.getReferencedNestedRedeclaration(node);\n if (declaration) {\n write(getGeneratedNameForNode(declaration.name));\n return;\n }\n }\n }\n if (ts.nodeIsSynthesized(node)) {\n write(node.text);\n }\n else {\n writeTextOfNode(currentSourceFile, node);\n }\n }\n function isNameOfNestedRedeclaration(node) {\n if (languageVersion < 2 /* ES6 */) {\n var parent_6 = node.parent;\n switch (parent_6.kind) {\n case 163 /* BindingElement */:\n case 214 /* ClassDeclaration */:\n case 217 /* EnumDeclaration */:\n case 211 /* VariableDeclaration */:\n return parent_6.name === node && resolver.isNestedRedeclaration(parent_6);\n }\n }\n return false;\n }\n function emitIdentifier(node) {\n if (!node.parent) {\n write(node.text);\n }\n else if (isExpressionIdentifier(node)) {\n emitExpressionIdentifier(node);\n }\n else if (isNameOfNestedRedeclaration(node)) {\n write(getGeneratedNameForNode(node));\n }\n else if (ts.nodeIsSynthesized(node)) {\n write(node.text);\n }\n else {\n writeTextOfNode(currentSourceFile, node);\n }\n }\n function emitThis(node) {\n if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) {\n write(\"_this\");\n }\n else {\n write(\"this\");\n }\n }\n function emitSuper(node) {\n if (languageVersion >= 2 /* ES6 */) {\n write(\"super\");\n }\n else {\n var flags = resolver.getNodeCheckFlags(node);\n if (flags & 256 /* SuperInstance */) {\n write(\"_super.prototype\");\n }\n else {\n write(\"_super\");\n }\n }\n }\n function emitObjectBindingPattern(node) {\n write(\"{ \");\n var elements = node.elements;\n emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma);\n write(\" }\");\n }\n function emitArrayBindingPattern(node) {\n write(\"[\");\n var elements = node.elements;\n emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma);\n write(\"]\");\n }\n function emitBindingElement(node) {\n if (node.propertyName) {\n emit(node.propertyName);\n write(\": \");\n }\n if (node.dotDotDotToken) {\n write(\"...\");\n }\n if (ts.isBindingPattern(node.name)) {\n emit(node.name);\n }\n else {\n emitModuleMemberName(node);\n }\n emitOptional(\" = \", node.initializer);\n }\n function emitSpreadElementExpression(node) {\n write(\"...\");\n emit(node.expression);\n }\n function emitYieldExpression(node) {\n write(ts.tokenToString(114 /* YieldKeyword */));\n if (node.asteriskToken) {\n write(\"*\");\n }\n if (node.expression) {\n write(\" \");\n emit(node.expression);\n }\n }\n function emitAwaitExpression(node) {\n var needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node);\n if (needsParenthesis) {\n write(\"(\");\n }\n write(ts.tokenToString(114 /* YieldKeyword */));\n write(\" \");\n emit(node.expression);\n if (needsParenthesis) {\n write(\")\");\n }\n }\n function needsParenthesisForAwaitExpressionAsYield(node) {\n if (node.parent.kind === 181 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) {\n return true;\n }\n else if (node.parent.kind === 182 /* ConditionalExpression */ && node.parent.condition === node) {\n return true;\n }\n return false;\n }\n function needsParenthesisForPropertyAccessOrInvocation(node) {\n switch (node.kind) {\n case 69 /* Identifier */:\n case 164 /* ArrayLiteralExpression */:\n case 166 /* PropertyAccessExpression */:\n case 167 /* ElementAccessExpression */:\n case 168 /* CallExpression */:\n case 172 /* ParenthesizedExpression */:\n // This list is not exhaustive and only includes those cases that are relevant\n // to the check in emitArrayLiteral. More cases can be added as needed.\n return false;\n }\n return true;\n }\n function emitListWithSpread(elements, needsUniqueCopy, multiLine, trailingComma, useConcat) {\n var pos = 0;\n var group = 0;\n var length = elements.length;\n while (pos < length) {\n // Emit using the pattern .concat(, , ...)\n if (group === 1 && useConcat) {\n write(\".concat(\");\n }\n else if (group > 0) {\n write(\", \");\n }\n var e = elements[pos];\n if (e.kind === 185 /* SpreadElementExpression */) {\n e = e.expression;\n emitParenthesizedIf(e, /*parenthesized*/ group === 0 && needsParenthesisForPropertyAccessOrInvocation(e));\n pos++;\n if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 164 /* ArrayLiteralExpression */) {\n write(\".slice()\");\n }\n }\n else {\n var i = pos;\n while (i < length && elements[i].kind !== 185 /* SpreadElementExpression */) {\n i++;\n }\n write(\"[\");\n if (multiLine) {\n increaseIndent();\n }\n emitList(elements, pos, i - pos, multiLine, trailingComma && i === length);\n if (multiLine) {\n decreaseIndent();\n }\n write(\"]\");\n pos = i;\n }\n group++;\n }\n if (group > 1) {\n if (useConcat) {\n write(\")\");\n }\n }\n }\n function isSpreadElementExpression(node) {\n return node.kind === 185 /* SpreadElementExpression */;\n }\n function emitArrayLiteral(node) {\n var elements = node.elements;\n if (elements.length === 0) {\n write(\"[]\");\n }\n else if (languageVersion >= 2 /* ES6 */ || !ts.forEach(elements, isSpreadElementExpression)) {\n write(\"[\");\n emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces:*/ false);\n write(\"]\");\n }\n else {\n emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ (node.flags & 2048 /* MultiLine */) !== 0,\n /*trailingComma*/ elements.hasTrailingComma, /*useConcat*/ true);\n }\n }\n function emitObjectLiteralBody(node, numElements) {\n if (numElements === 0) {\n write(\"{}\");\n return;\n }\n write(\"{\");\n if (numElements > 0) {\n var properties = node.properties;\n // If we are not doing a downlevel transformation for object literals,\n // then try to preserve the original shape of the object literal.\n // Otherwise just try to preserve the formatting.\n if (numElements === properties.length) {\n emitLinePreservingList(node, properties, /* allowTrailingComma */ languageVersion >= 1 /* ES5 */, /* spacesBetweenBraces */ true);\n }\n else {\n var multiLine = (node.flags & 2048 /* MultiLine */) !== 0;\n if (!multiLine) {\n write(\" \");\n }\n else {\n increaseIndent();\n }\n emitList(properties, 0, numElements, /*multiLine*/ multiLine, /*trailingComma*/ false);\n if (!multiLine) {\n write(\" \");\n }\n else {\n decreaseIndent();\n }\n }\n }\n write(\"}\");\n }\n function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) {\n var multiLine = (node.flags & 2048 /* MultiLine */) !== 0;\n var properties = node.properties;\n write(\"(\");\n if (multiLine) {\n increaseIndent();\n }\n // For computed properties, we need to create a unique handle to the object\n // literal so we can modify it without risking internal assignments tainting the object.\n var tempVar = createAndRecordTempVariable(0 /* Auto */);\n // Write out the first non-computed properties\n // (or all properties if none of them are computed),\n // then emit the rest through indexing on the temp variable.\n emit(tempVar);\n write(\" = \");\n emitObjectLiteralBody(node, firstComputedPropertyIndex);\n for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) {\n writeComma();\n var property = properties[i];\n emitStart(property);\n if (property.kind === 145 /* GetAccessor */ || property.kind === 146 /* SetAccessor */) {\n // TODO (drosen): Reconcile with 'emitMemberFunctions'.\n var accessors = ts.getAllAccessorDeclarations(node.properties, property);\n if (property !== accessors.firstAccessor) {\n continue;\n }\n write(\"Object.defineProperty(\");\n emit(tempVar);\n write(\", \");\n emitStart(node.name);\n emitExpressionForPropertyName(property.name);\n emitEnd(property.name);\n write(\", {\");\n increaseIndent();\n if (accessors.getAccessor) {\n writeLine();\n emitLeadingComments(accessors.getAccessor);\n write(\"get: \");\n emitStart(accessors.getAccessor);\n write(\"function \");\n emitSignatureAndBody(accessors.getAccessor);\n emitEnd(accessors.getAccessor);\n emitTrailingComments(accessors.getAccessor);\n write(\",\");\n }\n if (accessors.setAccessor) {\n writeLine();\n emitLeadingComments(accessors.setAccessor);\n write(\"set: \");\n emitStart(accessors.setAccessor);\n write(\"function \");\n emitSignatureAndBody(accessors.setAccessor);\n emitEnd(accessors.setAccessor);\n emitTrailingComments(accessors.setAccessor);\n write(\",\");\n }\n writeLine();\n write(\"enumerable: true,\");\n writeLine();\n write(\"configurable: true\");\n decreaseIndent();\n writeLine();\n write(\"})\");\n emitEnd(property);\n }\n else {\n emitLeadingComments(property);\n emitStart(property.name);\n emit(tempVar);\n emitMemberAccessForPropertyName(property.name);\n emitEnd(property.name);\n write(\" = \");\n if (property.kind === 245 /* PropertyAssignment */) {\n emit(property.initializer);\n }\n else if (property.kind === 246 /* ShorthandPropertyAssignment */) {\n emitExpressionIdentifier(property.name);\n }\n else if (property.kind === 143 /* MethodDeclaration */) {\n emitFunctionDeclaration(property);\n }\n else {\n ts.Debug.fail(\"ObjectLiteralElement type not accounted for: \" + property.kind);\n }\n }\n emitEnd(property);\n }\n writeComma();\n emit(tempVar);\n if (multiLine) {\n decreaseIndent();\n writeLine();\n }\n write(\")\");\n function writeComma() {\n if (multiLine) {\n write(\",\");\n writeLine();\n }\n else {\n write(\", \");\n }\n }\n }\n function emitObjectLiteral(node) {\n var properties = node.properties;\n if (languageVersion < 2 /* ES6 */) {\n var numProperties = properties.length;\n // Find the first computed property.\n // Everything until that point can be emitted as part of the initial object literal.\n var numInitialNonComputedProperties = numProperties;\n for (var i = 0, n = properties.length; i < n; i++) {\n if (properties[i].name.kind === 136 /* ComputedPropertyName */) {\n numInitialNonComputedProperties = i;\n break;\n }\n }\n var hasComputedProperty = numInitialNonComputedProperties !== properties.length;\n if (hasComputedProperty) {\n emitDownlevelObjectLiteralWithComputedProperties(node, numInitialNonComputedProperties);\n return;\n }\n }\n // Ordinary case: either the object has no computed properties\n // or we're compiling with an ES6+ target.\n emitObjectLiteralBody(node, properties.length);\n }\n function createBinaryExpression(left, operator, right, startsOnNewLine) {\n var result = ts.createSynthesizedNode(181 /* BinaryExpression */, startsOnNewLine);\n result.operatorToken = ts.createSynthesizedNode(operator);\n result.left = left;\n result.right = right;\n return result;\n }\n function createPropertyAccessExpression(expression, name) {\n var result = ts.createSynthesizedNode(166 /* PropertyAccessExpression */);\n result.expression = parenthesizeForAccess(expression);\n result.dotToken = ts.createSynthesizedNode(21 /* DotToken */);\n result.name = name;\n return result;\n }\n function createElementAccessExpression(expression, argumentExpression) {\n var result = ts.createSynthesizedNode(167 /* ElementAccessExpression */);\n result.expression = parenthesizeForAccess(expression);\n result.argumentExpression = argumentExpression;\n return result;\n }\n function parenthesizeForAccess(expr) {\n // When diagnosing whether the expression needs parentheses, the decision should be based\n // on the innermost expression in a chain of nested type assertions.\n while (expr.kind === 171 /* TypeAssertionExpression */ || expr.kind === 189 /* AsExpression */) {\n expr = expr.expression;\n }\n // isLeftHandSideExpression is almost the correct criterion for when it is not necessary\n // to parenthesize the expression before a dot. The known exceptions are:\n //\n // NewExpression:\n // new C.x -> not the same as (new C).x\n // NumberLiteral\n // 1.x -> not the same as (1).x\n //\n if (ts.isLeftHandSideExpression(expr) &&\n expr.kind !== 169 /* NewExpression */ &&\n expr.kind !== 8 /* NumericLiteral */) {\n return expr;\n }\n var node = ts.createSynthesizedNode(172 /* ParenthesizedExpression */);\n node.expression = expr;\n return node;\n }\n function emitComputedPropertyName(node) {\n write(\"[\");\n emitExpressionForPropertyName(node);\n write(\"]\");\n }\n function emitMethod(node) {\n if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) {\n write(\"*\");\n }\n emit(node.name);\n if (languageVersion < 2 /* ES6 */) {\n write(\": function \");\n }\n emitSignatureAndBody(node);\n }\n function emitPropertyAssignment(node) {\n emit(node.name);\n write(\": \");\n // This is to ensure that we emit comment in the following case:\n // For example:\n // obj = {\n // id: /*comment1*/ ()=>void\n // }\n // \"comment1\" is not considered to be leading comment for node.initializer\n // but rather a trailing comment on the previous node.\n emitTrailingCommentsOfPosition(node.initializer.pos);\n emit(node.initializer);\n }\n // Return true if identifier resolves to an exported member of a namespace\n function isNamespaceExportReference(node) {\n var container = resolver.getReferencedExportContainer(node);\n return container && container.kind !== 248 /* SourceFile */;\n }\n function emitShorthandPropertyAssignment(node) {\n // The name property of a short-hand property assignment is considered an expression position, so here\n // we manually emit the identifier to avoid rewriting.\n writeTextOfNode(currentSourceFile, node.name);\n // If emitting pre-ES6 code, or if the name requires rewriting when resolved as an expression identifier,\n // we emit a normal property assignment. For example:\n // module m {\n // export let y;\n // }\n // module m {\n // let obj = { y };\n // }\n // Here we need to emit obj = { y : m.y } regardless of the output target.\n if (languageVersion < 2 /* ES6 */ || isNamespaceExportReference(node.name)) {\n // Emit identifier as an identifier\n write(\": \");\n emit(node.name);\n }\n if (languageVersion >= 2 /* ES6 */ && node.objectAssignmentInitializer) {\n write(\" = \");\n emit(node.objectAssignmentInitializer);\n }\n }\n function tryEmitConstantValue(node) {\n var constantValue = tryGetConstEnumValue(node);\n if (constantValue !== undefined) {\n write(constantValue.toString());\n if (!compilerOptions.removeComments) {\n var propertyName = node.kind === 166 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression);\n write(\" /* \" + propertyName + \" */\");\n }\n return true;\n }\n return false;\n }\n function tryGetConstEnumValue(node) {\n if (compilerOptions.isolatedModules) {\n return undefined;\n }\n return node.kind === 166 /* PropertyAccessExpression */ || node.kind === 167 /* ElementAccessExpression */\n ? resolver.getConstantValue(node)\n : undefined;\n }\n // Returns 'true' if the code was actually indented, false otherwise.\n // If the code is not indented, an optional valueToWriteWhenNotIndenting will be\n // emitted instead.\n function indentIfOnDifferentLines(parent, node1, node2, valueToWriteWhenNotIndenting) {\n var realNodesAreOnDifferentLines = !ts.nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2);\n // Always use a newline for synthesized code if the synthesizer desires it.\n var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2);\n if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) {\n increaseIndent();\n writeLine();\n return true;\n }\n else {\n if (valueToWriteWhenNotIndenting) {\n write(valueToWriteWhenNotIndenting);\n }\n return false;\n }\n }\n function emitPropertyAccess(node) {\n if (tryEmitConstantValue(node)) {\n return;\n }\n emit(node.expression);\n var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken);\n // 1 .toString is a valid property access, emit a space after the literal\n // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal\n var shouldEmitSpace;\n if (!indentedBeforeDot) {\n if (node.expression.kind === 8 /* NumericLiteral */) {\n // check if numeric literal was originally written with a dot\n var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);\n shouldEmitSpace = text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0;\n }\n else {\n // check if constant enum value is integer\n var constantValue = tryGetConstEnumValue(node.expression);\n // isFinite handles cases when constantValue is undefined\n shouldEmitSpace = isFinite(constantValue) && Math.floor(constantValue) === constantValue;\n }\n }\n if (shouldEmitSpace) {\n write(\" .\");\n }\n else {\n write(\".\");\n }\n var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name);\n emit(node.name);\n decreaseIndentIf(indentedBeforeDot, indentedAfterDot);\n }\n function emitQualifiedName(node) {\n emit(node.left);\n write(\".\");\n emit(node.right);\n }\n function emitQualifiedNameAsExpression(node, useFallback) {\n if (node.left.kind === 69 /* Identifier */) {\n emitEntityNameAsExpression(node.left, useFallback);\n }\n else if (useFallback) {\n var temp = createAndRecordTempVariable(0 /* Auto */);\n write(\"(\");\n emitNodeWithoutSourceMap(temp);\n write(\" = \");\n emitEntityNameAsExpression(node.left, /*useFallback*/ true);\n write(\") && \");\n emitNodeWithoutSourceMap(temp);\n }\n else {\n emitEntityNameAsExpression(node.left, /*useFallback*/ false);\n }\n write(\".\");\n emit(node.right);\n }\n function emitEntityNameAsExpression(node, useFallback) {\n switch (node.kind) {\n case 69 /* Identifier */:\n if (useFallback) {\n write(\"typeof \");\n emitExpressionIdentifier(node);\n write(\" !== 'undefined' && \");\n }\n emitExpressionIdentifier(node);\n break;\n case 135 /* QualifiedName */:\n emitQualifiedNameAsExpression(node, useFallback);\n break;\n }\n }\n function emitIndexedAccess(node) {\n if (tryEmitConstantValue(node)) {\n return;\n }\n emit(node.expression);\n write(\"[\");\n emit(node.argumentExpression);\n write(\"]\");\n }\n function hasSpreadElement(elements) {\n return ts.forEach(elements, function (e) { return e.kind === 185 /* SpreadElementExpression */; });\n }\n function skipParentheses(node) {\n while (node.kind === 172 /* ParenthesizedExpression */ || node.kind === 171 /* TypeAssertionExpression */ || node.kind === 189 /* AsExpression */) {\n node = node.expression;\n }\n return node;\n }\n function emitCallTarget(node) {\n if (node.kind === 69 /* Identifier */ || node.kind === 97 /* ThisKeyword */ || node.kind === 95 /* SuperKeyword */) {\n emit(node);\n return node;\n }\n var temp = createAndRecordTempVariable(0 /* Auto */);\n write(\"(\");\n emit(temp);\n write(\" = \");\n emit(node);\n write(\")\");\n return temp;\n }\n function emitCallWithSpread(node) {\n var target;\n var expr = skipParentheses(node.expression);\n if (expr.kind === 166 /* PropertyAccessExpression */) {\n // Target will be emitted as \"this\" argument\n target = emitCallTarget(expr.expression);\n write(\".\");\n emit(expr.name);\n }\n else if (expr.kind === 167 /* ElementAccessExpression */) {\n // Target will be emitted as \"this\" argument\n target = emitCallTarget(expr.expression);\n write(\"[\");\n emit(expr.argumentExpression);\n write(\"]\");\n }\n else if (expr.kind === 95 /* SuperKeyword */) {\n target = expr;\n write(\"_super\");\n }\n else {\n emit(node.expression);\n }\n write(\".apply(\");\n if (target) {\n if (target.kind === 95 /* SuperKeyword */) {\n // Calls of form super(...) and super.foo(...)\n emitThis(target);\n }\n else {\n // Calls of form obj.foo(...)\n emit(target);\n }\n }\n else {\n // Calls of form foo(...)\n write(\"void 0\");\n }\n write(\", \");\n emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ true);\n write(\")\");\n }\n function emitCallExpression(node) {\n if (languageVersion < 2 /* ES6 */ && hasSpreadElement(node.arguments)) {\n emitCallWithSpread(node);\n return;\n }\n var superCall = false;\n if (node.expression.kind === 95 /* SuperKeyword */) {\n emitSuper(node.expression);\n superCall = true;\n }\n else {\n emit(node.expression);\n superCall = node.expression.kind === 166 /* PropertyAccessExpression */ && node.expression.expression.kind === 95 /* SuperKeyword */;\n }\n if (superCall && languageVersion < 2 /* ES6 */) {\n write(\".call(\");\n emitThis(node.expression);\n if (node.arguments.length) {\n write(\", \");\n emitCommaList(node.arguments);\n }\n write(\")\");\n }\n else {\n write(\"(\");\n emitCommaList(node.arguments);\n write(\")\");\n }\n }\n function emitNewExpression(node) {\n write(\"new \");\n // Spread operator logic is supported in new expressions in ES5 using a combination\n // of Function.prototype.bind() and Function.prototype.apply().\n //\n // Example:\n //\n // var args = [1, 2, 3, 4, 5];\n // new Array(...args);\n //\n // is compiled into the following ES5:\n //\n // var args = [1, 2, 3, 4, 5];\n // new (Array.bind.apply(Array, [void 0].concat(args)));\n //\n // The 'thisArg' to 'bind' is ignored when invoking the result of 'bind' with 'new',\n // Thus, we set it to undefined ('void 0').\n if (languageVersion === 1 /* ES5 */ &&\n node.arguments &&\n hasSpreadElement(node.arguments)) {\n write(\"(\");\n var target = emitCallTarget(node.expression);\n write(\".bind.apply(\");\n emit(target);\n write(\", [void 0].concat(\");\n emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiline*/ false, /*trailingComma*/ false, /*useConcat*/ false);\n write(\")))\");\n write(\"()\");\n }\n else {\n emit(node.expression);\n if (node.arguments) {\n write(\"(\");\n emitCommaList(node.arguments);\n write(\")\");\n }\n }\n }\n function emitTaggedTemplateExpression(node) {\n if (languageVersion >= 2 /* ES6 */) {\n emit(node.tag);\n write(\" \");\n emit(node.template);\n }\n else {\n emitDownlevelTaggedTemplate(node);\n }\n }\n function emitParenExpression(node) {\n // If the node is synthesized, it means the emitter put the parentheses there,\n // not the user. If we didn't want them, the emitter would not have put them\n // there.\n if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 174 /* ArrowFunction */) {\n if (node.expression.kind === 171 /* TypeAssertionExpression */ || node.expression.kind === 189 /* AsExpression */) {\n var operand = node.expression.expression;\n // Make sure we consider all nested cast expressions, e.g.:\n // (-A).x;\n while (operand.kind === 171 /* TypeAssertionExpression */ || operand.kind === 189 /* AsExpression */) {\n operand = operand.expression;\n }\n // We have an expression of the form: (SubExpr)\n // Emitting this as (SubExpr) is really not desirable. We would like to emit the subexpr as is.\n // Omitting the parentheses, however, could cause change in the semantics of the generated\n // code if the casted expression has a lower precedence than the rest of the expression, e.g.:\n // (new A).foo should be emitted as (new A).foo and not new A.foo\n // (typeof A).toString() should be emitted as (typeof A).toString() and not typeof A.toString()\n // new (A()) should be emitted as new (A()) and not new A()\n // (function foo() { })() should be emitted as an IIF (function foo(){})() and not declaration function foo(){} ()\n if (operand.kind !== 179 /* PrefixUnaryExpression */ &&\n operand.kind !== 177 /* VoidExpression */ &&\n operand.kind !== 176 /* TypeOfExpression */ &&\n operand.kind !== 175 /* DeleteExpression */ &&\n operand.kind !== 180 /* PostfixUnaryExpression */ &&\n operand.kind !== 169 /* NewExpression */ &&\n !(operand.kind === 168 /* CallExpression */ && node.parent.kind === 169 /* NewExpression */) &&\n !(operand.kind === 173 /* FunctionExpression */ && node.parent.kind === 168 /* CallExpression */) &&\n !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 166 /* PropertyAccessExpression */)) {\n emit(operand);\n return;\n }\n }\n }\n write(\"(\");\n emit(node.expression);\n write(\")\");\n }\n function emitDeleteExpression(node) {\n write(ts.tokenToString(78 /* DeleteKeyword */));\n write(\" \");\n emit(node.expression);\n }\n function emitVoidExpression(node) {\n write(ts.tokenToString(103 /* VoidKeyword */));\n write(\" \");\n emit(node.expression);\n }\n function emitTypeOfExpression(node) {\n write(ts.tokenToString(101 /* TypeOfKeyword */));\n write(\" \");\n emit(node.expression);\n }\n function isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node) {\n if (!isCurrentFileSystemExternalModule() || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) {\n return false;\n }\n var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 211 /* VariableDeclaration */ || node.parent.kind === 163 /* BindingElement */);\n var targetDeclaration = isVariableDeclarationOrBindingElement\n ? node.parent\n : resolver.getReferencedValueDeclaration(node);\n return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, /*isExported*/ true);\n }\n function emitPrefixUnaryExpression(node) {\n var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand);\n if (exportChanged) {\n // emit\n // ++x\n // as\n // exports('x', ++x)\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithoutSourceMap(node.operand);\n write(\"\\\", \");\n }\n write(ts.tokenToString(node.operator));\n // In some cases, we need to emit a space between the operator and the operand. One obvious case\n // is when the operator is an identifier, like delete or typeof. We also need to do this for plus\n // and minus expressions in certain cases. Specifically, consider the following two cases (parens\n // are just for clarity of exposition, and not part of the source code):\n //\n // (+(+1))\n // (+(++1))\n //\n // We need to emit a space in both cases. In the first case, the absence of a space will make\n // the resulting expression a prefix increment operation. And in the second, it will make the resulting\n // expression a prefix increment whose operand is a plus expression - (++(+x))\n // The same is true of minus of course.\n if (node.operand.kind === 179 /* PrefixUnaryExpression */) {\n var operand = node.operand;\n if (node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) {\n write(\" \");\n }\n else if (node.operator === 36 /* MinusToken */ && (operand.operator === 36 /* MinusToken */ || operand.operator === 42 /* MinusMinusToken */)) {\n write(\" \");\n }\n }\n emit(node.operand);\n if (exportChanged) {\n write(\")\");\n }\n }\n function emitPostfixUnaryExpression(node) {\n var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand);\n if (exportChanged) {\n // export function returns the value that was passes as the second argument\n // however for postfix unary expressions result value should be the value before modification.\n // emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)'\n write(\"(\" + exportFunctionForFile + \"(\\\"\");\n emitNodeWithoutSourceMap(node.operand);\n write(\"\\\", \");\n write(ts.tokenToString(node.operator));\n emit(node.operand);\n if (node.operator === 41 /* PlusPlusToken */) {\n write(\") - 1)\");\n }\n else {\n write(\") + 1)\");\n }\n }\n else {\n emit(node.operand);\n write(ts.tokenToString(node.operator));\n }\n }\n function shouldHoistDeclarationInSystemJsModule(node) {\n return isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ false);\n }\n /*\n * Checks if given node is a source file level declaration (not nested in module/function).\n * If 'isExported' is true - then declaration must also be exported.\n * This function is used in two cases:\n * - check if node is a exported source file level value to determine\n * if we should also export the value after its it changed\n * - check if node is a source level declaration to emit it differently,\n * i.e non-exported variable statement 'var x = 1' is hoisted so\n * we we emit variable statement 'var' should be dropped.\n */\n function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) {\n if (!node || languageVersion >= 2 /* ES6 */ || !isCurrentFileSystemExternalModule()) {\n return false;\n }\n var current = node;\n while (current) {\n if (current.kind === 248 /* SourceFile */) {\n return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0);\n }\n else if (ts.isFunctionLike(current) || current.kind === 219 /* ModuleBlock */) {\n return false;\n }\n else {\n current = current.parent;\n }\n }\n }\n /**\n * Emit ES7 exponentiation operator downlevel using Math.pow\n * @param node a binary expression node containing exponentiationOperator (**, **=)\n */\n function emitExponentiationOperator(node) {\n var leftHandSideExpression = node.left;\n if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) {\n var synthesizedLHS;\n var shouldEmitParentheses = false;\n if (ts.isElementAccessExpression(leftHandSideExpression)) {\n shouldEmitParentheses = true;\n write(\"(\");\n synthesizedLHS = ts.createSynthesizedNode(167 /* ElementAccessExpression */, /*startsOnNewLine*/ false);\n var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false);\n synthesizedLHS.expression = identifier;\n if (leftHandSideExpression.argumentExpression.kind !== 8 /* NumericLiteral */ &&\n leftHandSideExpression.argumentExpression.kind !== 9 /* StringLiteral */) {\n var tempArgumentExpression = createAndRecordTempVariable(268435456 /* _i */);\n synthesizedLHS.argumentExpression = tempArgumentExpression;\n emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true);\n }\n else {\n synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression;\n }\n write(\", \");\n }\n else if (ts.isPropertyAccessExpression(leftHandSideExpression)) {\n shouldEmitParentheses = true;\n write(\"(\");\n synthesizedLHS = ts.createSynthesizedNode(166 /* PropertyAccessExpression */, /*startsOnNewLine*/ false);\n var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false);\n synthesizedLHS.expression = identifier;\n synthesizedLHS.dotToken = leftHandSideExpression.dotToken;\n synthesizedLHS.name = leftHandSideExpression.name;\n write(\", \");\n }\n emit(synthesizedLHS || leftHandSideExpression);\n write(\" = \");\n write(\"Math.pow(\");\n emit(synthesizedLHS || leftHandSideExpression);\n write(\", \");\n emit(node.right);\n write(\")\");\n if (shouldEmitParentheses) {\n write(\")\");\n }\n }\n else {\n write(\"Math.pow(\");\n emit(leftHandSideExpression);\n write(\", \");\n emit(node.right);\n write(\")\");\n }\n }\n function emitBinaryExpression(node) {\n if (languageVersion < 2 /* ES6 */ && node.operatorToken.kind === 56 /* EqualsToken */ &&\n (node.left.kind === 165 /* ObjectLiteralExpression */ || node.left.kind === 164 /* ArrayLiteralExpression */)) {\n emitDestructuring(node, node.parent.kind === 195 /* ExpressionStatement */);\n }\n else {\n var exportChanged = node.operatorToken.kind >= 56 /* FirstAssignment */ &&\n node.operatorToken.kind <= 68 /* LastAssignment */ &&\n isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.left);\n if (exportChanged) {\n // emit assignment 'x y' as 'exports(\"x\", x y)'\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithoutSourceMap(node.left);\n write(\"\\\", \");\n }\n if (node.operatorToken.kind === 38 /* AsteriskAsteriskToken */ || node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) {\n // Downleveled emit exponentiation operator using Math.pow\n emitExponentiationOperator(node);\n }\n else {\n emit(node.left);\n // Add indentation before emit the operator if the operator is on different line\n // For example:\n // 3\n // + 2;\n // emitted as\n // 3\n // + 2;\n var indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== 24 /* CommaToken */ ? \" \" : undefined);\n write(ts.tokenToString(node.operatorToken.kind));\n var indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, \" \");\n emit(node.right);\n decreaseIndentIf(indentedBeforeOperator, indentedAfterOperator);\n }\n if (exportChanged) {\n write(\")\");\n }\n }\n }\n function synthesizedNodeStartsOnNewLine(node) {\n return ts.nodeIsSynthesized(node) && node.startsOnNewLine;\n }\n function emitConditionalExpression(node) {\n emit(node.condition);\n var indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, \" \");\n write(\"?\");\n var indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, \" \");\n emit(node.whenTrue);\n decreaseIndentIf(indentedBeforeQuestion, indentedAfterQuestion);\n var indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, \" \");\n write(\":\");\n var indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, \" \");\n emit(node.whenFalse);\n decreaseIndentIf(indentedBeforeColon, indentedAfterColon);\n }\n // Helper function to decrease the indent if we previously indented. Allows multiple\n // previous indent values to be considered at a time. This also allows caller to just\n // call this once, passing in all their appropriate indent values, instead of needing\n // to call this helper function multiple times.\n function decreaseIndentIf(value1, value2) {\n if (value1) {\n decreaseIndent();\n }\n if (value2) {\n decreaseIndent();\n }\n }\n function isSingleLineEmptyBlock(node) {\n if (node && node.kind === 192 /* Block */) {\n var block = node;\n return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block);\n }\n }\n function emitBlock(node) {\n if (isSingleLineEmptyBlock(node)) {\n emitToken(15 /* OpenBraceToken */, node.pos);\n write(\" \");\n emitToken(16 /* CloseBraceToken */, node.statements.end);\n return;\n }\n emitToken(15 /* OpenBraceToken */, node.pos);\n increaseIndent();\n scopeEmitStart(node.parent);\n if (node.kind === 219 /* ModuleBlock */) {\n ts.Debug.assert(node.parent.kind === 218 /* ModuleDeclaration */);\n emitCaptureThisForNodeIfNecessary(node.parent);\n }\n emitLines(node.statements);\n if (node.kind === 219 /* ModuleBlock */) {\n emitTempDeclarations(/*newLine*/ true);\n }\n decreaseIndent();\n writeLine();\n emitToken(16 /* CloseBraceToken */, node.statements.end);\n scopeEmitEnd();\n }\n function emitEmbeddedStatement(node) {\n if (node.kind === 192 /* Block */) {\n write(\" \");\n emit(node);\n }\n else {\n increaseIndent();\n writeLine();\n emit(node);\n decreaseIndent();\n }\n }\n function emitExpressionStatement(node) {\n emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 174 /* ArrowFunction */);\n write(\";\");\n }\n function emitIfStatement(node) {\n var endPos = emitToken(88 /* IfKeyword */, node.pos);\n write(\" \");\n endPos = emitToken(17 /* OpenParenToken */, endPos);\n emit(node.expression);\n emitToken(18 /* CloseParenToken */, node.expression.end);\n emitEmbeddedStatement(node.thenStatement);\n if (node.elseStatement) {\n writeLine();\n emitToken(80 /* ElseKeyword */, node.thenStatement.end);\n if (node.elseStatement.kind === 196 /* IfStatement */) {\n write(\" \");\n emit(node.elseStatement);\n }\n else {\n emitEmbeddedStatement(node.elseStatement);\n }\n }\n }\n function emitDoStatement(node) {\n write(\"do\");\n emitEmbeddedStatement(node.statement);\n if (node.statement.kind === 192 /* Block */) {\n write(\" \");\n }\n else {\n writeLine();\n }\n write(\"while (\");\n emit(node.expression);\n write(\");\");\n }\n function emitWhileStatement(node) {\n write(\"while (\");\n emit(node.expression);\n write(\")\");\n emitEmbeddedStatement(node.statement);\n }\n /**\n * Returns true if start of variable declaration list was emitted.\n * Returns false if nothing was written - this can happen for source file level variable declarations\n * in system modules where such variable declarations are hoisted.\n */\n function tryEmitStartOfVariableDeclarationList(decl, startPos) {\n if (shouldHoistVariable(decl, /*checkIfSourceFileLevelDecl*/ true)) {\n // variables in variable declaration list were already hoisted\n return false;\n }\n var tokenKind = 102 /* VarKeyword */;\n if (decl && languageVersion >= 2 /* ES6 */) {\n if (ts.isLet(decl)) {\n tokenKind = 108 /* LetKeyword */;\n }\n else if (ts.isConst(decl)) {\n tokenKind = 74 /* ConstKeyword */;\n }\n }\n if (startPos !== undefined) {\n emitToken(tokenKind, startPos);\n write(\" \");\n }\n else {\n switch (tokenKind) {\n case 102 /* VarKeyword */:\n write(\"var \");\n break;\n case 108 /* LetKeyword */:\n write(\"let \");\n break;\n case 74 /* ConstKeyword */:\n write(\"const \");\n break;\n }\n }\n return true;\n }\n function emitVariableDeclarationListSkippingUninitializedEntries(list) {\n var started = false;\n for (var _a = 0, _b = list.declarations; _a < _b.length; _a++) {\n var decl = _b[_a];\n if (!decl.initializer) {\n continue;\n }\n if (!started) {\n started = true;\n }\n else {\n write(\", \");\n }\n emit(decl);\n }\n return started;\n }\n function emitForStatement(node) {\n var endPos = emitToken(86 /* ForKeyword */, node.pos);\n write(\" \");\n endPos = emitToken(17 /* OpenParenToken */, endPos);\n if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) {\n var variableDeclarationList = node.initializer;\n var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos);\n if (startIsEmitted) {\n emitCommaList(variableDeclarationList.declarations);\n }\n else {\n emitVariableDeclarationListSkippingUninitializedEntries(variableDeclarationList);\n }\n }\n else if (node.initializer) {\n emit(node.initializer);\n }\n write(\";\");\n emitOptional(\" \", node.condition);\n write(\";\");\n emitOptional(\" \", node.incrementor);\n write(\")\");\n emitEmbeddedStatement(node.statement);\n }\n function emitForInOrForOfStatement(node) {\n if (languageVersion < 2 /* ES6 */ && node.kind === 201 /* ForOfStatement */) {\n return emitDownLevelForOfStatement(node);\n }\n var endPos = emitToken(86 /* ForKeyword */, node.pos);\n write(\" \");\n endPos = emitToken(17 /* OpenParenToken */, endPos);\n if (node.initializer.kind === 212 /* VariableDeclarationList */) {\n var variableDeclarationList = node.initializer;\n if (variableDeclarationList.declarations.length >= 1) {\n tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos);\n emit(variableDeclarationList.declarations[0]);\n }\n }\n else {\n emit(node.initializer);\n }\n if (node.kind === 200 /* ForInStatement */) {\n write(\" in \");\n }\n else {\n write(\" of \");\n }\n emit(node.expression);\n emitToken(18 /* CloseParenToken */, node.expression.end);\n emitEmbeddedStatement(node.statement);\n }\n function emitDownLevelForOfStatement(node) {\n // The following ES6 code:\n //\n // for (let v of expr) { }\n //\n // should be emitted as\n //\n // for (let _i = 0, _a = expr; _i < _a.length; _i++) {\n // let v = _a[_i];\n // }\n //\n // where _a and _i are temps emitted to capture the RHS and the counter,\n // respectively.\n // When the left hand side is an expression instead of a let declaration,\n // the \"let v\" is not emitted.\n // When the left hand side is a let/const, the v is renamed if there is\n // another v in scope.\n // Note that all assignments to the LHS are emitted in the body, including\n // all destructuring.\n // Note also that because an extra statement is needed to assign to the LHS,\n // for-of bodies are always emitted as blocks.\n var endPos = emitToken(86 /* ForKeyword */, node.pos);\n write(\" \");\n endPos = emitToken(17 /* OpenParenToken */, endPos);\n // Do not emit the LHS let declaration yet, because it might contain destructuring.\n // Do not call recordTempDeclaration because we are declaring the temps\n // right here. Recording means they will be declared later.\n // In the case where the user wrote an identifier as the RHS, like this:\n //\n // for (let v of arr) { }\n //\n // we don't want to emit a temporary variable for the RHS, just use it directly.\n var rhsIsIdentifier = node.expression.kind === 69 /* Identifier */;\n var counter = createTempVariable(268435456 /* _i */);\n var rhsReference = rhsIsIdentifier ? node.expression : createTempVariable(0 /* Auto */);\n // This is the let keyword for the counter and rhsReference. The let keyword for\n // the LHS will be emitted inside the body.\n emitStart(node.expression);\n write(\"var \");\n // _i = 0\n emitNodeWithoutSourceMap(counter);\n write(\" = 0\");\n emitEnd(node.expression);\n if (!rhsIsIdentifier) {\n // , _a = expr\n write(\", \");\n emitStart(node.expression);\n emitNodeWithoutSourceMap(rhsReference);\n write(\" = \");\n emitNodeWithoutSourceMap(node.expression);\n emitEnd(node.expression);\n }\n write(\"; \");\n // _i < _a.length;\n emitStart(node.initializer);\n emitNodeWithoutSourceMap(counter);\n write(\" < \");\n emitNodeWithCommentsAndWithoutSourcemap(rhsReference);\n write(\".length\");\n emitEnd(node.initializer);\n write(\"; \");\n // _i++)\n emitStart(node.initializer);\n emitNodeWithoutSourceMap(counter);\n write(\"++\");\n emitEnd(node.initializer);\n emitToken(18 /* CloseParenToken */, node.expression.end);\n // Body\n write(\" {\");\n writeLine();\n increaseIndent();\n // Initialize LHS\n // let v = _a[_i];\n var rhsIterationValue = createElementAccessExpression(rhsReference, counter);\n emitStart(node.initializer);\n if (node.initializer.kind === 212 /* VariableDeclarationList */) {\n write(\"var \");\n var variableDeclarationList = node.initializer;\n if (variableDeclarationList.declarations.length > 0) {\n var declaration = variableDeclarationList.declarations[0];\n if (ts.isBindingPattern(declaration.name)) {\n // This works whether the declaration is a var, let, or const.\n // It will use rhsIterationValue _a[_i] as the initializer.\n emitDestructuring(declaration, /*isAssignmentExpressionStatement*/ false, rhsIterationValue);\n }\n else {\n // The following call does not include the initializer, so we have\n // to emit it separately.\n emitNodeWithCommentsAndWithoutSourcemap(declaration);\n write(\" = \");\n emitNodeWithoutSourceMap(rhsIterationValue);\n }\n }\n else {\n // It's an empty declaration list. This can only happen in an error case, if the user wrote\n // for (let of []) {}\n emitNodeWithoutSourceMap(createTempVariable(0 /* Auto */));\n write(\" = \");\n emitNodeWithoutSourceMap(rhsIterationValue);\n }\n }\n else {\n // Initializer is an expression. Emit the expression in the body, so that it's\n // evaluated on every iteration.\n var assignmentExpression = createBinaryExpression(node.initializer, 56 /* EqualsToken */, rhsIterationValue, /*startsOnNewLine*/ false);\n if (node.initializer.kind === 164 /* ArrayLiteralExpression */ || node.initializer.kind === 165 /* ObjectLiteralExpression */) {\n // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause\n // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash.\n emitDestructuring(assignmentExpression, /*isAssignmentExpressionStatement*/ true, /*value*/ undefined);\n }\n else {\n emitNodeWithCommentsAndWithoutSourcemap(assignmentExpression);\n }\n }\n emitEnd(node.initializer);\n write(\";\");\n if (node.statement.kind === 192 /* Block */) {\n emitLines(node.statement.statements);\n }\n else {\n writeLine();\n emit(node.statement);\n }\n writeLine();\n decreaseIndent();\n write(\"}\");\n }\n function emitBreakOrContinueStatement(node) {\n emitToken(node.kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos);\n emitOptional(\" \", node.label);\n write(\";\");\n }\n function emitReturnStatement(node) {\n emitToken(94 /* ReturnKeyword */, node.pos);\n emitOptional(\" \", node.expression);\n write(\";\");\n }\n function emitWithStatement(node) {\n write(\"with (\");\n emit(node.expression);\n write(\")\");\n emitEmbeddedStatement(node.statement);\n }\n function emitSwitchStatement(node) {\n var endPos = emitToken(96 /* SwitchKeyword */, node.pos);\n write(\" \");\n emitToken(17 /* OpenParenToken */, endPos);\n emit(node.expression);\n endPos = emitToken(18 /* CloseParenToken */, node.expression.end);\n write(\" \");\n emitCaseBlock(node.caseBlock, endPos);\n }\n function emitCaseBlock(node, startPos) {\n emitToken(15 /* OpenBraceToken */, startPos);\n increaseIndent();\n emitLines(node.clauses);\n decreaseIndent();\n writeLine();\n emitToken(16 /* CloseBraceToken */, node.clauses.end);\n }\n function nodeStartPositionsAreOnSameLine(node1, node2) {\n return ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) ===\n ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos));\n }\n function nodeEndPositionsAreOnSameLine(node1, node2) {\n return ts.getLineOfLocalPosition(currentSourceFile, node1.end) ===\n ts.getLineOfLocalPosition(currentSourceFile, node2.end);\n }\n function nodeEndIsOnSameLineAsNodeStart(node1, node2) {\n return ts.getLineOfLocalPosition(currentSourceFile, node1.end) ===\n ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos));\n }\n function emitCaseOrDefaultClause(node) {\n if (node.kind === 241 /* CaseClause */) {\n write(\"case \");\n emit(node.expression);\n write(\":\");\n }\n else {\n write(\"default:\");\n }\n if (node.statements.length === 1 && nodeStartPositionsAreOnSameLine(node, node.statements[0])) {\n write(\" \");\n emit(node.statements[0]);\n }\n else {\n increaseIndent();\n emitLines(node.statements);\n decreaseIndent();\n }\n }\n function emitThrowStatement(node) {\n write(\"throw \");\n emit(node.expression);\n write(\";\");\n }\n function emitTryStatement(node) {\n write(\"try \");\n emit(node.tryBlock);\n emit(node.catchClause);\n if (node.finallyBlock) {\n writeLine();\n write(\"finally \");\n emit(node.finallyBlock);\n }\n }\n function emitCatchClause(node) {\n writeLine();\n var endPos = emitToken(72 /* CatchKeyword */, node.pos);\n write(\" \");\n emitToken(17 /* OpenParenToken */, endPos);\n emit(node.variableDeclaration);\n emitToken(18 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : endPos);\n write(\" \");\n emitBlock(node.block);\n }\n function emitDebuggerStatement(node) {\n emitToken(76 /* DebuggerKeyword */, node.pos);\n write(\";\");\n }\n function emitLabelledStatement(node) {\n emit(node.label);\n write(\": \");\n emit(node.statement);\n }\n function getContainingModule(node) {\n do {\n node = node.parent;\n } while (node && node.kind !== 218 /* ModuleDeclaration */);\n return node;\n }\n function emitContainingModuleName(node) {\n var container = getContainingModule(node);\n write(container ? getGeneratedNameForNode(container) : \"exports\");\n }\n function emitModuleMemberName(node) {\n emitStart(node.name);\n if (ts.getCombinedNodeFlags(node) & 1 /* Export */) {\n var container = getContainingModule(node);\n if (container) {\n write(getGeneratedNameForNode(container));\n write(\".\");\n }\n else if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) {\n write(\"exports.\");\n }\n }\n emitNodeWithCommentsAndWithoutSourcemap(node.name);\n emitEnd(node.name);\n }\n function createVoidZero() {\n var zero = ts.createSynthesizedNode(8 /* NumericLiteral */);\n zero.text = \"0\";\n var result = ts.createSynthesizedNode(177 /* VoidExpression */);\n result.expression = zero;\n return result;\n }\n function emitEs6ExportDefaultCompat(node) {\n if (node.parent.kind === 248 /* SourceFile */) {\n ts.Debug.assert(!!(node.flags & 1024 /* Default */) || node.kind === 227 /* ExportAssignment */);\n // only allow export default at a source file level\n if (modulekind === 1 /* CommonJS */ || modulekind === 2 /* AMD */ || modulekind === 3 /* UMD */) {\n if (!currentSourceFile.symbol.exports[\"___esModule\"]) {\n if (languageVersion === 1 /* ES5 */) {\n // default value of configurable, enumerable, writable are `false`.\n write(\"Object.defineProperty(exports, \\\"__esModule\\\", { value: true });\");\n writeLine();\n }\n else if (languageVersion === 0 /* ES3 */) {\n write(\"exports.__esModule = true;\");\n writeLine();\n }\n }\n }\n }\n }\n function emitExportMemberAssignment(node) {\n if (node.flags & 1 /* Export */) {\n writeLine();\n emitStart(node);\n // emit call to exporter only for top level nodes\n if (modulekind === 4 /* System */ && node.parent === currentSourceFile) {\n // emit export default as\n // export(\"default\", )\n write(exportFunctionForFile + \"(\\\"\");\n if (node.flags & 1024 /* Default */) {\n write(\"default\");\n }\n else {\n emitNodeWithCommentsAndWithoutSourcemap(node.name);\n }\n write(\"\\\", \");\n emitDeclarationName(node);\n write(\")\");\n }\n else {\n if (node.flags & 1024 /* Default */) {\n emitEs6ExportDefaultCompat(node);\n if (languageVersion === 0 /* ES3 */) {\n write(\"exports[\\\"default\\\"]\");\n }\n else {\n write(\"exports.default\");\n }\n }\n else {\n emitModuleMemberName(node);\n }\n write(\" = \");\n emitDeclarationName(node);\n }\n emitEnd(node);\n write(\";\");\n }\n }\n function emitExportMemberAssignments(name) {\n if (modulekind === 4 /* System */) {\n return;\n }\n if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) {\n for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) {\n var specifier = _b[_a];\n writeLine();\n emitStart(specifier.name);\n emitContainingModuleName(specifier);\n write(\".\");\n emitNodeWithCommentsAndWithoutSourcemap(specifier.name);\n emitEnd(specifier.name);\n write(\" = \");\n emitExpressionIdentifier(name);\n write(\";\");\n }\n }\n }\n function emitExportSpecifierInSystemModule(specifier) {\n ts.Debug.assert(modulekind === 4 /* System */);\n if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier)) {\n return;\n }\n writeLine();\n emitStart(specifier.name);\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithCommentsAndWithoutSourcemap(specifier.name);\n write(\"\\\", \");\n emitExpressionIdentifier(specifier.propertyName || specifier.name);\n write(\")\");\n emitEnd(specifier.name);\n write(\";\");\n }\n /**\n * Emit an assignment to a given identifier, 'name', with a given expression, 'value'.\n * @param name an identifier as a left-hand-side operand of the assignment\n * @param value an expression as a right-hand-side operand of the assignment\n * @param shouldEmitCommaBeforeAssignment a boolean indicating whether to prefix an assignment with comma\n */\n function emitAssignment(name, value, shouldEmitCommaBeforeAssignment) {\n if (shouldEmitCommaBeforeAssignment) {\n write(\", \");\n }\n var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name);\n if (exportChanged) {\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithCommentsAndWithoutSourcemap(name);\n write(\"\\\", \");\n }\n var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 /* VariableDeclaration */ || name.parent.kind === 163 /* BindingElement */);\n if (isVariableDeclarationOrBindingElement) {\n emitModuleMemberName(name.parent);\n }\n else {\n emit(name);\n }\n write(\" = \");\n emit(value);\n if (exportChanged) {\n write(\")\");\n }\n }\n /**\n * Create temporary variable, emit an assignment of the variable the given expression\n * @param expression an expression to assign to the newly created temporary variable\n * @param canDefineTempVariablesInPlace a boolean indicating whether you can define the temporary variable at an assignment location\n * @param shouldEmitCommaBeforeAssignment a boolean indicating whether an assignment should prefix with comma\n */\n function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment) {\n var identifier = createTempVariable(0 /* Auto */);\n if (!canDefineTempVariablesInPlace) {\n recordTempDeclaration(identifier);\n }\n emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment);\n return identifier;\n }\n function emitDestructuring(root, isAssignmentExpressionStatement, value) {\n var emitCount = 0;\n // An exported declaration is actually emitted as an assignment (to a property on the module object), so\n // temporary variables in an exported declaration need to have real declarations elsewhere\n // Also temporary variables should be explicitly allocated for source level declarations when module target is system\n // because actual variable declarations are hoisted\n var canDefineTempVariablesInPlace = false;\n if (root.kind === 211 /* VariableDeclaration */) {\n var isExported = ts.getCombinedNodeFlags(root) & 1 /* Export */;\n var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root);\n canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind;\n }\n else if (root.kind === 138 /* Parameter */) {\n canDefineTempVariablesInPlace = true;\n }\n if (root.kind === 181 /* BinaryExpression */) {\n emitAssignmentExpression(root);\n }\n else {\n ts.Debug.assert(!isAssignmentExpressionStatement);\n emitBindingElement(root, value);\n }\n /**\n * Ensures that there exists a declared identifier whose value holds the given expression.\n * This function is useful to ensure that the expression's value can be read from in subsequent expressions.\n * Unless 'reuseIdentifierExpressions' is false, 'expr' will be returned if it is just an identifier.\n *\n * @param expr the expression whose value needs to be bound.\n * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;\n * false if it is necessary to always emit an identifier.\n */\n function ensureIdentifier(expr, reuseIdentifierExpressions) {\n if (expr.kind === 69 /* Identifier */ && reuseIdentifierExpressions) {\n return expr;\n }\n var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0);\n emitCount++;\n return identifier;\n }\n function createDefaultValueCheck(value, defaultValue) {\n // The value expression will be evaluated twice, so for anything but a simple identifier\n // we need to generate a temporary variable\n value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true);\n // Return the expression 'value === void 0 ? defaultValue : value'\n var equals = ts.createSynthesizedNode(181 /* BinaryExpression */);\n equals.left = value;\n equals.operatorToken = ts.createSynthesizedNode(32 /* EqualsEqualsEqualsToken */);\n equals.right = createVoidZero();\n return createConditionalExpression(equals, defaultValue, value);\n }\n function createConditionalExpression(condition, whenTrue, whenFalse) {\n var cond = ts.createSynthesizedNode(182 /* ConditionalExpression */);\n cond.condition = condition;\n cond.questionToken = ts.createSynthesizedNode(53 /* QuestionToken */);\n cond.whenTrue = whenTrue;\n cond.colonToken = ts.createSynthesizedNode(54 /* ColonToken */);\n cond.whenFalse = whenFalse;\n return cond;\n }\n function createNumericLiteral(value) {\n var node = ts.createSynthesizedNode(8 /* NumericLiteral */);\n node.text = \"\" + value;\n return node;\n }\n function createPropertyAccessForDestructuringProperty(object, propName) {\n // We create a synthetic copy of the identifier in order to avoid the rewriting that might\n // otherwise occur when the identifier is emitted.\n var syntheticName = ts.createSynthesizedNode(propName.kind);\n syntheticName.text = propName.text;\n if (syntheticName.kind !== 69 /* Identifier */) {\n return createElementAccessExpression(object, syntheticName);\n }\n return createPropertyAccessExpression(object, syntheticName);\n }\n function createSliceCall(value, sliceIndex) {\n var call = ts.createSynthesizedNode(168 /* CallExpression */);\n var sliceIdentifier = ts.createSynthesizedNode(69 /* Identifier */);\n sliceIdentifier.text = \"slice\";\n call.expression = createPropertyAccessExpression(value, sliceIdentifier);\n call.arguments = ts.createSynthesizedNodeArray();\n call.arguments[0] = createNumericLiteral(sliceIndex);\n return call;\n }\n function emitObjectLiteralAssignment(target, value) {\n var properties = target.properties;\n if (properties.length !== 1) {\n // For anything but a single element destructuring we need to generate a temporary\n // to ensure value is evaluated exactly once.\n value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true);\n }\n for (var _a = 0; _a < properties.length; _a++) {\n var p = properties[_a];\n if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) {\n var propName = p.name;\n var target_1 = p.kind === 246 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName;\n emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName));\n }\n }\n }\n function emitArrayLiteralAssignment(target, value) {\n var elements = target.elements;\n if (elements.length !== 1) {\n // For anything but a single element destructuring we need to generate a temporary\n // to ensure value is evaluated exactly once.\n value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true);\n }\n for (var i = 0; i < elements.length; i++) {\n var e = elements[i];\n if (e.kind !== 187 /* OmittedExpression */) {\n if (e.kind !== 185 /* SpreadElementExpression */) {\n emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)));\n }\n else if (i === elements.length - 1) {\n emitDestructuringAssignment(e.expression, createSliceCall(value, i));\n }\n }\n }\n }\n function emitDestructuringAssignment(target, value) {\n if (target.kind === 246 /* ShorthandPropertyAssignment */) {\n if (target.objectAssignmentInitializer) {\n value = createDefaultValueCheck(value, target.objectAssignmentInitializer);\n }\n target = target.name;\n }\n else if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) {\n value = createDefaultValueCheck(value, target.right);\n target = target.left;\n }\n if (target.kind === 165 /* ObjectLiteralExpression */) {\n emitObjectLiteralAssignment(target, value);\n }\n else if (target.kind === 164 /* ArrayLiteralExpression */) {\n emitArrayLiteralAssignment(target, value);\n }\n else {\n emitAssignment(target, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0);\n emitCount++;\n }\n }\n function emitAssignmentExpression(root) {\n var target = root.left;\n var value = root.right;\n if (ts.isEmptyObjectLiteralOrArrayLiteral(target)) {\n emit(value);\n }\n else if (isAssignmentExpressionStatement) {\n emitDestructuringAssignment(target, value);\n }\n else {\n if (root.parent.kind !== 172 /* ParenthesizedExpression */) {\n write(\"(\");\n }\n value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true);\n emitDestructuringAssignment(target, value);\n write(\", \");\n emit(value);\n if (root.parent.kind !== 172 /* ParenthesizedExpression */) {\n write(\")\");\n }\n }\n }\n function emitBindingElement(target, value) {\n if (target.initializer) {\n // Combine value and initializer\n value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer;\n }\n else if (!value) {\n // Use 'void 0' in absence of value and initializer\n value = createVoidZero();\n }\n if (ts.isBindingPattern(target.name)) {\n var pattern = target.name;\n var elements = pattern.elements;\n var numElements = elements.length;\n if (numElements !== 1) {\n // For anything other than a single-element destructuring we need to generate a temporary\n // to ensure value is evaluated exactly once. Additionally, if we have zero elements\n // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,\n // so in that case, we'll intentionally create that temporary.\n value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0);\n }\n for (var i = 0; i < numElements; i++) {\n var element = elements[i];\n if (pattern.kind === 161 /* ObjectBindingPattern */) {\n // Rewrite element to a declaration with an initializer that fetches property\n var propName = element.propertyName || element.name;\n emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName));\n }\n else if (element.kind !== 187 /* OmittedExpression */) {\n if (!element.dotDotDotToken) {\n // Rewrite element to a declaration that accesses array element at index i\n emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i)));\n }\n else if (i === numElements - 1) {\n emitBindingElement(element, createSliceCall(value, i));\n }\n }\n }\n }\n else {\n emitAssignment(target.name, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0);\n emitCount++;\n }\n }\n }\n function emitVariableDeclaration(node) {\n if (ts.isBindingPattern(node.name)) {\n if (languageVersion < 2 /* ES6 */) {\n emitDestructuring(node, /*isAssignmentExpressionStatement*/ false);\n }\n else {\n emit(node.name);\n emitOptional(\" = \", node.initializer);\n }\n }\n else {\n var initializer = node.initializer;\n if (!initializer && languageVersion < 2 /* ES6 */) {\n // downlevel emit for non-initialized let bindings defined in loops\n // for (...) { let x; }\n // should be\n // for (...) { var = void 0; }\n // this is necessary to preserve ES6 semantic in scenarios like\n // for (...) { let x; console.log(x); x = 1 } // assignment on one iteration should not affect other iterations\n var isUninitializedLet = (resolver.getNodeCheckFlags(node) & 16384 /* BlockScopedBindingInLoop */) &&\n (getCombinedFlagsForIdentifier(node.name) & 16384 /* Let */);\n // NOTE: default initialization should not be added to let bindings in for-in\\for-of statements\n if (isUninitializedLet &&\n node.parent.parent.kind !== 200 /* ForInStatement */ &&\n node.parent.parent.kind !== 201 /* ForOfStatement */) {\n initializer = createVoidZero();\n }\n }\n var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name);\n if (exportChanged) {\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithCommentsAndWithoutSourcemap(node.name);\n write(\"\\\", \");\n }\n emitModuleMemberName(node);\n emitOptional(\" = \", initializer);\n if (exportChanged) {\n write(\")\");\n }\n }\n }\n function emitExportVariableAssignments(node) {\n if (node.kind === 187 /* OmittedExpression */) {\n return;\n }\n var name = node.name;\n if (name.kind === 69 /* Identifier */) {\n emitExportMemberAssignments(name);\n }\n else if (ts.isBindingPattern(name)) {\n ts.forEach(name.elements, emitExportVariableAssignments);\n }\n }\n function getCombinedFlagsForIdentifier(node) {\n if (!node.parent || (node.parent.kind !== 211 /* VariableDeclaration */ && node.parent.kind !== 163 /* BindingElement */)) {\n return 0;\n }\n return ts.getCombinedNodeFlags(node.parent);\n }\n function isES6ExportedDeclaration(node) {\n return !!(node.flags & 1 /* Export */) &&\n modulekind === 5 /* ES6 */ &&\n node.parent.kind === 248 /* SourceFile */;\n }\n function emitVariableStatement(node) {\n var startIsEmitted = false;\n if (node.flags & 1 /* Export */) {\n if (isES6ExportedDeclaration(node)) {\n // Exported ES6 module member\n write(\"export \");\n startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList);\n }\n }\n else {\n startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList);\n }\n if (startIsEmitted) {\n emitCommaList(node.declarationList.declarations);\n write(\";\");\n }\n else {\n var atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList);\n if (atLeastOneItem) {\n write(\";\");\n }\n }\n if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) {\n ts.forEach(node.declarationList.declarations, emitExportVariableAssignments);\n }\n }\n function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) {\n // If we're not exporting the variables, there's nothing special here.\n // Always emit comments for these nodes.\n if (!(node.flags & 1 /* Export */)) {\n return true;\n }\n // If we are exporting, but it's a top-level ES6 module exports,\n // we'll emit the declaration list verbatim, so emit comments too.\n if (isES6ExportedDeclaration(node)) {\n return true;\n }\n // Otherwise, only emit if we have at least one initializer present.\n for (var _a = 0, _b = node.declarationList.declarations; _a < _b.length; _a++) {\n var declaration = _b[_a];\n if (declaration.initializer) {\n return true;\n }\n }\n return false;\n }\n function emitParameter(node) {\n if (languageVersion < 2 /* ES6 */) {\n if (ts.isBindingPattern(node.name)) {\n var name_24 = createTempVariable(0 /* Auto */);\n if (!tempParameters) {\n tempParameters = [];\n }\n tempParameters.push(name_24);\n emit(name_24);\n }\n else {\n emit(node.name);\n }\n }\n else {\n if (node.dotDotDotToken) {\n write(\"...\");\n }\n emit(node.name);\n emitOptional(\" = \", node.initializer);\n }\n }\n function emitDefaultValueAssignments(node) {\n if (languageVersion < 2 /* ES6 */) {\n var tempIndex = 0;\n ts.forEach(node.parameters, function (parameter) {\n // A rest parameter cannot have a binding pattern or an initializer,\n // so let's just ignore it.\n if (parameter.dotDotDotToken) {\n return;\n }\n var paramName = parameter.name, initializer = parameter.initializer;\n if (ts.isBindingPattern(paramName)) {\n // In cases where a binding pattern is simply '[]' or '{}',\n // we usually don't want to emit a var declaration; however, in the presence\n // of an initializer, we must emit that expression to preserve side effects.\n var hasBindingElements = paramName.elements.length > 0;\n if (hasBindingElements || initializer) {\n writeLine();\n write(\"var \");\n if (hasBindingElements) {\n emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]);\n }\n else {\n emit(tempParameters[tempIndex]);\n write(\" = \");\n emit(initializer);\n }\n write(\";\");\n tempIndex++;\n }\n }\n else if (initializer) {\n writeLine();\n emitStart(parameter);\n write(\"if (\");\n emitNodeWithoutSourceMap(paramName);\n write(\" === void 0)\");\n emitEnd(parameter);\n write(\" { \");\n emitStart(parameter);\n emitNodeWithCommentsAndWithoutSourcemap(paramName);\n write(\" = \");\n emitNodeWithCommentsAndWithoutSourcemap(initializer);\n emitEnd(parameter);\n write(\"; }\");\n }\n });\n }\n }\n function emitRestParameter(node) {\n if (languageVersion < 2 /* ES6 */ && ts.hasRestParameter(node)) {\n var restIndex = node.parameters.length - 1;\n var restParam = node.parameters[restIndex];\n // A rest parameter cannot have a binding pattern, so let's just ignore it if it does.\n if (ts.isBindingPattern(restParam.name)) {\n return;\n }\n var tempName = createTempVariable(268435456 /* _i */).text;\n writeLine();\n emitLeadingComments(restParam);\n emitStart(restParam);\n write(\"var \");\n emitNodeWithCommentsAndWithoutSourcemap(restParam.name);\n write(\" = [];\");\n emitEnd(restParam);\n emitTrailingComments(restParam);\n writeLine();\n write(\"for (\");\n emitStart(restParam);\n write(\"var \" + tempName + \" = \" + restIndex + \";\");\n emitEnd(restParam);\n write(\" \");\n emitStart(restParam);\n write(tempName + \" < arguments.length;\");\n emitEnd(restParam);\n write(\" \");\n emitStart(restParam);\n write(tempName + \"++\");\n emitEnd(restParam);\n write(\") {\");\n increaseIndent();\n writeLine();\n emitStart(restParam);\n emitNodeWithCommentsAndWithoutSourcemap(restParam.name);\n write(\"[\" + tempName + \" - \" + restIndex + \"] = arguments[\" + tempName + \"];\");\n emitEnd(restParam);\n decreaseIndent();\n writeLine();\n write(\"}\");\n }\n }\n function emitAccessor(node) {\n write(node.kind === 145 /* GetAccessor */ ? \"get \" : \"set \");\n emit(node.name);\n emitSignatureAndBody(node);\n }\n function shouldEmitAsArrowFunction(node) {\n return node.kind === 174 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */;\n }\n function emitDeclarationName(node) {\n if (node.name) {\n emitNodeWithCommentsAndWithoutSourcemap(node.name);\n }\n else {\n write(getGeneratedNameForNode(node));\n }\n }\n function shouldEmitFunctionName(node) {\n if (node.kind === 173 /* FunctionExpression */) {\n // Emit name if one is present\n return !!node.name;\n }\n if (node.kind === 213 /* FunctionDeclaration */) {\n // Emit name if one is present, or emit generated name in down-level case (for export default case)\n return !!node.name || languageVersion < 2 /* ES6 */;\n }\n }\n function emitFunctionDeclaration(node) {\n if (ts.nodeIsMissing(node.body)) {\n return emitCommentsOnNotEmittedNode(node);\n }\n // TODO (yuisu) : we should not have special cases to condition emitting comments\n // but have one place to fix check for these conditions.\n if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */ &&\n node.parent && node.parent.kind !== 245 /* PropertyAssignment */ &&\n node.parent.kind !== 168 /* CallExpression */) {\n // 1. Methods will emit the comments as part of emitting method declaration\n // 2. If the function is a property of object literal, emitting leading-comments\n // is done by emitNodeWithoutSourceMap which then call this function.\n // In particular, we would like to avoid emit comments twice in following case:\n // For example:\n // var obj = {\n // id:\n // /*comment*/ () => void\n // }\n // 3. If the function is an argument in call expression, emitting of comments will be\n // taken care of in emit list of arguments inside of emitCallexpression\n emitLeadingComments(node);\n }\n emitStart(node);\n // For targeting below es6, emit functions-like declaration including arrow function using function keyword.\n // When targeting ES6, emit arrow function natively in ES6 by omitting function keyword and using fat arrow instead\n if (!shouldEmitAsArrowFunction(node)) {\n if (isES6ExportedDeclaration(node)) {\n write(\"export \");\n if (node.flags & 1024 /* Default */) {\n write(\"default \");\n }\n }\n write(\"function\");\n if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) {\n write(\"*\");\n }\n write(\" \");\n }\n if (shouldEmitFunctionName(node)) {\n emitDeclarationName(node);\n }\n emitSignatureAndBody(node);\n if (modulekind !== 5 /* ES6 */ && node.kind === 213 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) {\n emitExportMemberAssignments(node.name);\n }\n emitEnd(node);\n if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */) {\n emitTrailingComments(node);\n }\n }\n function emitCaptureThisForNodeIfNecessary(node) {\n if (resolver.getNodeCheckFlags(node) & 4 /* CaptureThis */) {\n writeLine();\n emitStart(node);\n write(\"var _this = this;\");\n emitEnd(node);\n }\n }\n function emitSignatureParameters(node) {\n increaseIndent();\n write(\"(\");\n if (node) {\n var parameters = node.parameters;\n var omitCount = languageVersion < 2 /* ES6 */ && ts.hasRestParameter(node) ? 1 : 0;\n emitList(parameters, 0, parameters.length - omitCount, /*multiLine*/ false, /*trailingComma*/ false);\n }\n write(\")\");\n decreaseIndent();\n }\n function emitSignatureParametersForArrow(node) {\n // Check whether the parameter list needs parentheses and preserve no-parenthesis\n if (node.parameters.length === 1 && node.pos === node.parameters[0].pos) {\n emit(node.parameters[0]);\n return;\n }\n emitSignatureParameters(node);\n }\n function emitAsyncFunctionBodyForES6(node) {\n var promiseConstructor = ts.getEntityNameFromTypeNode(node.type);\n var isArrowFunction = node.kind === 174 /* ArrowFunction */;\n var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096 /* CaptureArguments */) !== 0;\n var args;\n // An async function is emit as an outer function that calls an inner\n // generator function. To preserve lexical bindings, we pass the current\n // `this` and `arguments` objects to `__awaiter`. The generator function\n // passed to `__awaiter` is executed inside of the callback to the\n // promise constructor.\n //\n // The emit for an async arrow without a lexical `arguments` binding might be:\n //\n // // input\n // let a = async (b) => { await b; }\n //\n // // output\n // let a = (b) => __awaiter(this, void 0, void 0, function* () {\n // yield b;\n // });\n //\n // The emit for an async arrow with a lexical `arguments` binding might be:\n //\n // // input\n // let a = async (b) => { await arguments[0]; }\n //\n // // output\n // let a = (b) => __awaiter(this, arguments, void 0, function* (arguments) {\n // yield arguments[0];\n // });\n //\n // The emit for an async function expression without a lexical `arguments` binding\n // might be:\n //\n // // input\n // let a = async function (b) {\n // await b;\n // }\n //\n // // output\n // let a = function (b) {\n // return __awaiter(this, void 0, void 0, function* () {\n // yield b;\n // });\n // }\n //\n // The emit for an async function expression with a lexical `arguments` binding\n // might be:\n //\n // // input\n // let a = async function (b) {\n // await arguments[0];\n // }\n //\n // // output\n // let a = function (b) {\n // return __awaiter(this, arguments, void 0, function* (_arguments) {\n // yield _arguments[0];\n // });\n // }\n //\n // The emit for an async function expression with a lexical `arguments` binding\n // and a return type annotation might be:\n //\n // // input\n // let a = async function (b): MyPromise {\n // await arguments[0];\n // }\n //\n // // output\n // let a = function (b) {\n // return __awaiter(this, arguments, MyPromise, function* (_arguments) {\n // yield _arguments[0];\n // });\n // }\n //\n // If this is not an async arrow, emit the opening brace of the function body\n // and the start of the return statement.\n if (!isArrowFunction) {\n write(\" {\");\n increaseIndent();\n writeLine();\n write(\"return\");\n }\n write(\" __awaiter(this\");\n if (hasLexicalArguments) {\n write(\", arguments\");\n }\n else {\n write(\", void 0\");\n }\n if (promiseConstructor) {\n write(\", \");\n emitNodeWithoutSourceMap(promiseConstructor);\n }\n else {\n write(\", Promise\");\n }\n // Emit the call to __awaiter.\n if (hasLexicalArguments) {\n write(\", function* (_arguments)\");\n }\n else {\n write(\", function* ()\");\n }\n // Emit the signature and body for the inner generator function.\n emitFunctionBody(node);\n write(\")\");\n // If this is not an async arrow, emit the closing brace of the outer function body.\n if (!isArrowFunction) {\n write(\";\");\n decreaseIndent();\n writeLine();\n write(\"}\");\n }\n }\n function emitFunctionBody(node) {\n if (!node.body) {\n // There can be no body when there are parse errors. Just emit an empty block\n // in that case.\n write(\" { }\");\n }\n else {\n if (node.body.kind === 192 /* Block */) {\n emitBlockFunctionBody(node, node.body);\n }\n else {\n emitExpressionFunctionBody(node, node.body);\n }\n }\n }\n function emitSignatureAndBody(node) {\n var saveTempFlags = tempFlags;\n var saveTempVariables = tempVariables;\n var saveTempParameters = tempParameters;\n tempFlags = 0;\n tempVariables = undefined;\n tempParameters = undefined;\n // When targeting ES6, emit arrow function natively in ES6\n if (shouldEmitAsArrowFunction(node)) {\n emitSignatureParametersForArrow(node);\n write(\" =>\");\n }\n else {\n emitSignatureParameters(node);\n }\n var isAsync = ts.isAsyncFunctionLike(node);\n if (isAsync && languageVersion === 2 /* ES6 */) {\n emitAsyncFunctionBodyForES6(node);\n }\n else {\n emitFunctionBody(node);\n }\n if (!isES6ExportedDeclaration(node)) {\n emitExportMemberAssignment(node);\n }\n tempFlags = saveTempFlags;\n tempVariables = saveTempVariables;\n tempParameters = saveTempParameters;\n }\n // Returns true if any preamble code was emitted.\n function emitFunctionBodyPreamble(node) {\n emitCaptureThisForNodeIfNecessary(node);\n emitDefaultValueAssignments(node);\n emitRestParameter(node);\n }\n function emitExpressionFunctionBody(node, body) {\n if (languageVersion < 2 /* ES6 */ || node.flags & 512 /* Async */) {\n emitDownLevelExpressionFunctionBody(node, body);\n return;\n }\n // For es6 and higher we can emit the expression as is. However, in the case\n // where the expression might end up looking like a block when emitted, we'll\n // also wrap it in parentheses first. For example if you have: a => {}\n // then we need to generate: a => ({})\n write(\" \");\n // Unwrap all type assertions.\n var current = body;\n while (current.kind === 171 /* TypeAssertionExpression */) {\n current = current.expression;\n }\n emitParenthesizedIf(body, current.kind === 165 /* ObjectLiteralExpression */);\n }\n function emitDownLevelExpressionFunctionBody(node, body) {\n write(\" {\");\n scopeEmitStart(node);\n increaseIndent();\n var outPos = writer.getTextPos();\n emitDetachedComments(node.body);\n emitFunctionBodyPreamble(node);\n var preambleEmitted = writer.getTextPos() !== outPos;\n decreaseIndent();\n // If we didn't have to emit any preamble code, then attempt to keep the arrow\n // function on one line.\n if (!preambleEmitted && nodeStartPositionsAreOnSameLine(node, body)) {\n write(\" \");\n emitStart(body);\n write(\"return \");\n emit(body);\n emitEnd(body);\n write(\";\");\n emitTempDeclarations(/*newLine*/ false);\n write(\" \");\n }\n else {\n increaseIndent();\n writeLine();\n emitLeadingComments(node.body);\n write(\"return \");\n emit(body);\n write(\";\");\n emitTrailingComments(node.body);\n emitTempDeclarations(/*newLine*/ true);\n decreaseIndent();\n writeLine();\n }\n emitStart(node.body);\n write(\"}\");\n emitEnd(node.body);\n scopeEmitEnd();\n }\n function emitBlockFunctionBody(node, body) {\n write(\" {\");\n scopeEmitStart(node);\n var initialTextPos = writer.getTextPos();\n increaseIndent();\n emitDetachedComments(body.statements);\n // Emit all the directive prologues (like \"use strict\"). These have to come before\n // any other preamble code we write (like parameter initializers).\n var startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true);\n emitFunctionBodyPreamble(node);\n decreaseIndent();\n var preambleEmitted = writer.getTextPos() !== initialTextPos;\n if (!preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) {\n for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {\n var statement = _b[_a];\n write(\" \");\n emit(statement);\n }\n emitTempDeclarations(/*newLine*/ false);\n write(\" \");\n emitLeadingCommentsOfPosition(body.statements.end);\n }\n else {\n increaseIndent();\n emitLinesStartingAt(body.statements, startIndex);\n emitTempDeclarations(/*newLine*/ true);\n writeLine();\n emitLeadingCommentsOfPosition(body.statements.end);\n decreaseIndent();\n }\n emitToken(16 /* CloseBraceToken */, body.statements.end);\n scopeEmitEnd();\n }\n function findInitialSuperCall(ctor) {\n if (ctor.body) {\n var statement = ctor.body.statements[0];\n if (statement && statement.kind === 195 /* ExpressionStatement */) {\n var expr = statement.expression;\n if (expr && expr.kind === 168 /* CallExpression */) {\n var func = expr.expression;\n if (func && func.kind === 95 /* SuperKeyword */) {\n return statement;\n }\n }\n }\n }\n }\n function emitParameterPropertyAssignments(node) {\n ts.forEach(node.parameters, function (param) {\n if (param.flags & 112 /* AccessibilityModifier */) {\n writeLine();\n emitStart(param);\n emitStart(param.name);\n write(\"this.\");\n emitNodeWithoutSourceMap(param.name);\n emitEnd(param.name);\n write(\" = \");\n emit(param.name);\n write(\";\");\n emitEnd(param);\n }\n });\n }\n function emitMemberAccessForPropertyName(memberName) {\n // This does not emit source map because it is emitted by caller as caller\n // is aware how the property name changes to the property access\n // eg. public x = 10; becomes this.x and static x = 10 becomes className.x\n if (memberName.kind === 9 /* StringLiteral */ || memberName.kind === 8 /* NumericLiteral */) {\n write(\"[\");\n emitNodeWithCommentsAndWithoutSourcemap(memberName);\n write(\"]\");\n }\n else if (memberName.kind === 136 /* ComputedPropertyName */) {\n emitComputedPropertyName(memberName);\n }\n else {\n write(\".\");\n emitNodeWithCommentsAndWithoutSourcemap(memberName);\n }\n }\n function getInitializedProperties(node, isStatic) {\n var properties = [];\n for (var _a = 0, _b = node.members; _a < _b.length; _a++) {\n var member = _b[_a];\n if (member.kind === 141 /* PropertyDeclaration */ && isStatic === ((member.flags & 128 /* Static */) !== 0) && member.initializer) {\n properties.push(member);\n }\n }\n return properties;\n }\n function emitPropertyDeclarations(node, properties) {\n for (var _a = 0; _a < properties.length; _a++) {\n var property = properties[_a];\n emitPropertyDeclaration(node, property);\n }\n }\n function emitPropertyDeclaration(node, property, receiver, isExpression) {\n writeLine();\n emitLeadingComments(property);\n emitStart(property);\n emitStart(property.name);\n if (receiver) {\n emit(receiver);\n }\n else {\n if (property.flags & 128 /* Static */) {\n emitDeclarationName(node);\n }\n else {\n write(\"this\");\n }\n }\n emitMemberAccessForPropertyName(property.name);\n emitEnd(property.name);\n write(\" = \");\n emit(property.initializer);\n if (!isExpression) {\n write(\";\");\n }\n emitEnd(property);\n emitTrailingComments(property);\n }\n function emitMemberFunctionsForES5AndLower(node) {\n ts.forEach(node.members, function (member) {\n if (member.kind === 191 /* SemicolonClassElement */) {\n writeLine();\n write(\";\");\n }\n else if (member.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) {\n if (!member.body) {\n return emitCommentsOnNotEmittedNode(member);\n }\n writeLine();\n emitLeadingComments(member);\n emitStart(member);\n emitStart(member.name);\n emitClassMemberPrefix(node, member);\n emitMemberAccessForPropertyName(member.name);\n emitEnd(member.name);\n write(\" = \");\n emitFunctionDeclaration(member);\n emitEnd(member);\n write(\";\");\n emitTrailingComments(member);\n }\n else if (member.kind === 145 /* GetAccessor */ || member.kind === 146 /* SetAccessor */) {\n var accessors = ts.getAllAccessorDeclarations(node.members, member);\n if (member === accessors.firstAccessor) {\n writeLine();\n emitStart(member);\n write(\"Object.defineProperty(\");\n emitStart(member.name);\n emitClassMemberPrefix(node, member);\n write(\", \");\n emitExpressionForPropertyName(member.name);\n emitEnd(member.name);\n write(\", {\");\n increaseIndent();\n if (accessors.getAccessor) {\n writeLine();\n emitLeadingComments(accessors.getAccessor);\n write(\"get: \");\n emitStart(accessors.getAccessor);\n write(\"function \");\n emitSignatureAndBody(accessors.getAccessor);\n emitEnd(accessors.getAccessor);\n emitTrailingComments(accessors.getAccessor);\n write(\",\");\n }\n if (accessors.setAccessor) {\n writeLine();\n emitLeadingComments(accessors.setAccessor);\n write(\"set: \");\n emitStart(accessors.setAccessor);\n write(\"function \");\n emitSignatureAndBody(accessors.setAccessor);\n emitEnd(accessors.setAccessor);\n emitTrailingComments(accessors.setAccessor);\n write(\",\");\n }\n writeLine();\n write(\"enumerable: true,\");\n writeLine();\n write(\"configurable: true\");\n decreaseIndent();\n writeLine();\n write(\"});\");\n emitEnd(member);\n }\n }\n });\n }\n function emitMemberFunctionsForES6AndHigher(node) {\n for (var _a = 0, _b = node.members; _a < _b.length; _a++) {\n var member = _b[_a];\n if ((member.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) && !member.body) {\n emitCommentsOnNotEmittedNode(member);\n }\n else if (member.kind === 143 /* MethodDeclaration */ ||\n member.kind === 145 /* GetAccessor */ ||\n member.kind === 146 /* SetAccessor */) {\n writeLine();\n emitLeadingComments(member);\n emitStart(member);\n if (member.flags & 128 /* Static */) {\n write(\"static \");\n }\n if (member.kind === 145 /* GetAccessor */) {\n write(\"get \");\n }\n else if (member.kind === 146 /* SetAccessor */) {\n write(\"set \");\n }\n if (member.asteriskToken) {\n write(\"*\");\n }\n emit(member.name);\n emitSignatureAndBody(member);\n emitEnd(member);\n emitTrailingComments(member);\n }\n else if (member.kind === 191 /* SemicolonClassElement */) {\n writeLine();\n write(\";\");\n }\n }\n }\n function emitConstructor(node, baseTypeElement) {\n var saveTempFlags = tempFlags;\n var saveTempVariables = tempVariables;\n var saveTempParameters = tempParameters;\n tempFlags = 0;\n tempVariables = undefined;\n tempParameters = undefined;\n emitConstructorWorker(node, baseTypeElement);\n tempFlags = saveTempFlags;\n tempVariables = saveTempVariables;\n tempParameters = saveTempParameters;\n }\n function emitConstructorWorker(node, baseTypeElement) {\n // Check if we have property assignment inside class declaration.\n // If there is property assignment, we need to emit constructor whether users define it or not\n // If there is no property assignment, we can omit constructor if users do not define it\n var hasInstancePropertyWithInitializer = false;\n // Emit the constructor overload pinned comments\n ts.forEach(node.members, function (member) {\n if (member.kind === 144 /* Constructor */ && !member.body) {\n emitCommentsOnNotEmittedNode(member);\n }\n // Check if there is any non-static property assignment\n if (member.kind === 141 /* PropertyDeclaration */ && member.initializer && (member.flags & 128 /* Static */) === 0) {\n hasInstancePropertyWithInitializer = true;\n }\n });\n var ctor = ts.getFirstConstructorWithBody(node);\n // For target ES6 and above, if there is no user-defined constructor and there is no property assignment\n // do not emit constructor in class declaration.\n if (languageVersion >= 2 /* ES6 */ && !ctor && !hasInstancePropertyWithInitializer) {\n return;\n }\n if (ctor) {\n emitLeadingComments(ctor);\n }\n emitStart(ctor || node);\n if (languageVersion < 2 /* ES6 */) {\n write(\"function \");\n emitDeclarationName(node);\n emitSignatureParameters(ctor);\n }\n else {\n write(\"constructor\");\n if (ctor) {\n emitSignatureParameters(ctor);\n }\n else {\n // Based on EcmaScript6 section 14.5.14: Runtime Semantics: ClassDefinitionEvaluation.\n // If constructor is empty, then,\n // If ClassHeritageopt is present, then\n // Let constructor be the result of parsing the String \"constructor(... args){ super (...args);}\" using the syntactic grammar with the goal symbol MethodDefinition.\n // Else,\n // Let constructor be the result of parsing the String \"constructor( ){ }\" using the syntactic grammar with the goal symbol MethodDefinition\n if (baseTypeElement) {\n write(\"(...args)\");\n }\n else {\n write(\"()\");\n }\n }\n }\n var startIndex = 0;\n write(\" {\");\n scopeEmitStart(node, \"constructor\");\n increaseIndent();\n if (ctor) {\n // Emit all the directive prologues (like \"use strict\"). These have to come before\n // any other preamble code we write (like parameter initializers).\n startIndex = emitDirectivePrologues(ctor.body.statements, /*startWithNewLine*/ true);\n emitDetachedComments(ctor.body.statements);\n }\n emitCaptureThisForNodeIfNecessary(node);\n var superCall;\n if (ctor) {\n emitDefaultValueAssignments(ctor);\n emitRestParameter(ctor);\n if (baseTypeElement) {\n superCall = findInitialSuperCall(ctor);\n if (superCall) {\n writeLine();\n emit(superCall);\n }\n }\n emitParameterPropertyAssignments(ctor);\n }\n else {\n if (baseTypeElement) {\n writeLine();\n emitStart(baseTypeElement);\n if (languageVersion < 2 /* ES6 */) {\n write(\"_super.apply(this, arguments);\");\n }\n else {\n write(\"super(...args);\");\n }\n emitEnd(baseTypeElement);\n }\n }\n emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ false));\n if (ctor) {\n var statements = ctor.body.statements;\n if (superCall) {\n statements = statements.slice(1);\n }\n emitLinesStartingAt(statements, startIndex);\n }\n emitTempDeclarations(/*newLine*/ true);\n writeLine();\n if (ctor) {\n emitLeadingCommentsOfPosition(ctor.body.statements.end);\n }\n decreaseIndent();\n emitToken(16 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end);\n scopeEmitEnd();\n emitEnd(ctor || node);\n if (ctor) {\n emitTrailingComments(ctor);\n }\n }\n function emitClassExpression(node) {\n return emitClassLikeDeclaration(node);\n }\n function emitClassDeclaration(node) {\n return emitClassLikeDeclaration(node);\n }\n function emitClassLikeDeclaration(node) {\n if (languageVersion < 2 /* ES6 */) {\n emitClassLikeDeclarationBelowES6(node);\n }\n else {\n emitClassLikeDeclarationForES6AndHigher(node);\n }\n if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile && node.name) {\n emitExportMemberAssignments(node.name);\n }\n }\n function emitClassLikeDeclarationForES6AndHigher(node) {\n var thisNodeIsDecorated = ts.nodeIsDecorated(node);\n if (node.kind === 214 /* ClassDeclaration */) {\n if (thisNodeIsDecorated) {\n // To preserve the correct runtime semantics when decorators are applied to the class,\n // the emit needs to follow one of the following rules:\n //\n // * For a local class declaration:\n //\n // @dec class C {\n // }\n //\n // The emit should be:\n //\n // let C = class {\n // };\n // C = __decorate([dec], C);\n //\n // * For an exported class declaration:\n //\n // @dec export class C {\n // }\n //\n // The emit should be:\n //\n // export let C = class {\n // };\n // C = __decorate([dec], C);\n //\n // * For a default export of a class declaration with a name:\n //\n // @dec default export class C {\n // }\n //\n // The emit should be:\n //\n // let C = class {\n // }\n // C = __decorate([dec], C);\n // export default C;\n //\n // * For a default export of a class declaration without a name:\n //\n // @dec default export class {\n // }\n //\n // The emit should be:\n //\n // let _default = class {\n // }\n // _default = __decorate([dec], _default);\n // export default _default;\n //\n if (isES6ExportedDeclaration(node) && !(node.flags & 1024 /* Default */)) {\n write(\"export \");\n }\n write(\"let \");\n emitDeclarationName(node);\n write(\" = \");\n }\n else if (isES6ExportedDeclaration(node)) {\n write(\"export \");\n if (node.flags & 1024 /* Default */) {\n write(\"default \");\n }\n }\n }\n // If the class has static properties, and it's a class expression, then we'll need\n // to specialize the emit a bit. for a class expression of the form:\n //\n // class C { static a = 1; static b = 2; ... }\n //\n // We'll emit:\n //\n // (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp)\n //\n // This keeps the expression as an expression, while ensuring that the static parts\n // of it have been initialized by the time it is used.\n var staticProperties = getInitializedProperties(node, /*static:*/ true);\n var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 186 /* ClassExpression */;\n var tempVariable;\n if (isClassExpressionWithStaticProperties) {\n tempVariable = createAndRecordTempVariable(0 /* Auto */);\n write(\"(\");\n increaseIndent();\n emit(tempVariable);\n write(\" = \");\n }\n write(\"class\");\n // emit name if\n // - node has a name\n // - this is default export with static initializers\n if ((node.name || (node.flags & 1024 /* Default */ && staticProperties.length > 0)) && !thisNodeIsDecorated) {\n write(\" \");\n emitDeclarationName(node);\n }\n var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node);\n if (baseTypeNode) {\n write(\" extends \");\n emit(baseTypeNode.expression);\n }\n write(\" {\");\n increaseIndent();\n scopeEmitStart(node);\n writeLine();\n emitConstructor(node, baseTypeNode);\n emitMemberFunctionsForES6AndHigher(node);\n decreaseIndent();\n writeLine();\n emitToken(16 /* CloseBraceToken */, node.members.end);\n scopeEmitEnd();\n // TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now.\n // For a decorated class, we need to assign its name (if it has one). This is because we emit\n // the class as a class expression to avoid the double-binding of the identifier:\n //\n // let C = class {\n // }\n // Object.defineProperty(C, \"name\", { value: \"C\", configurable: true });\n //\n if (thisNodeIsDecorated) {\n write(\";\");\n }\n // Emit static property assignment. Because classDeclaration is lexically evaluated,\n // it is safe to emit static property assignment after classDeclaration\n // From ES6 specification:\n // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using\n // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.\n if (isClassExpressionWithStaticProperties) {\n for (var _a = 0; _a < staticProperties.length; _a++) {\n var property = staticProperties[_a];\n write(\",\");\n writeLine();\n emitPropertyDeclaration(node, property, /*receiver:*/ tempVariable, /*isExpression:*/ true);\n }\n write(\",\");\n writeLine();\n emit(tempVariable);\n decreaseIndent();\n write(\")\");\n }\n else {\n writeLine();\n emitPropertyDeclarations(node, staticProperties);\n emitDecoratorsOfClass(node);\n }\n // If this is an exported class, but not on the top level (i.e. on an internal\n // module), export it\n if (!isES6ExportedDeclaration(node) && (node.flags & 1 /* Export */)) {\n writeLine();\n emitStart(node);\n emitModuleMemberName(node);\n write(\" = \");\n emitDeclarationName(node);\n emitEnd(node);\n write(\";\");\n }\n else if (isES6ExportedDeclaration(node) && (node.flags & 1024 /* Default */) && thisNodeIsDecorated) {\n // if this is a top level default export of decorated class, write the export after the declaration.\n writeLine();\n write(\"export default \");\n emitDeclarationName(node);\n write(\";\");\n }\n }\n function emitClassLikeDeclarationBelowES6(node) {\n if (node.kind === 214 /* ClassDeclaration */) {\n // source file level classes in system modules are hoisted so 'var's for them are already defined\n if (!shouldHoistDeclarationInSystemJsModule(node)) {\n write(\"var \");\n }\n emitDeclarationName(node);\n write(\" = \");\n }\n write(\"(function (\");\n var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node);\n if (baseTypeNode) {\n write(\"_super\");\n }\n write(\") {\");\n var saveTempFlags = tempFlags;\n var saveTempVariables = tempVariables;\n var saveTempParameters = tempParameters;\n var saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames;\n tempFlags = 0;\n tempVariables = undefined;\n tempParameters = undefined;\n computedPropertyNamesToGeneratedNames = undefined;\n increaseIndent();\n scopeEmitStart(node);\n if (baseTypeNode) {\n writeLine();\n emitStart(baseTypeNode);\n write(\"__extends(\");\n emitDeclarationName(node);\n write(\", _super);\");\n emitEnd(baseTypeNode);\n }\n writeLine();\n emitConstructor(node, baseTypeNode);\n emitMemberFunctionsForES5AndLower(node);\n emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ true));\n writeLine();\n emitDecoratorsOfClass(node);\n writeLine();\n emitToken(16 /* CloseBraceToken */, node.members.end, function () {\n write(\"return \");\n emitDeclarationName(node);\n });\n write(\";\");\n emitTempDeclarations(/*newLine*/ true);\n tempFlags = saveTempFlags;\n tempVariables = saveTempVariables;\n tempParameters = saveTempParameters;\n computedPropertyNamesToGeneratedNames = saveComputedPropertyNamesToGeneratedNames;\n decreaseIndent();\n writeLine();\n emitToken(16 /* CloseBraceToken */, node.members.end);\n scopeEmitEnd();\n emitStart(node);\n write(\")(\");\n if (baseTypeNode) {\n emit(baseTypeNode.expression);\n }\n write(\")\");\n if (node.kind === 214 /* ClassDeclaration */) {\n write(\";\");\n }\n emitEnd(node);\n if (node.kind === 214 /* ClassDeclaration */) {\n emitExportMemberAssignment(node);\n }\n }\n function emitClassMemberPrefix(node, member) {\n emitDeclarationName(node);\n if (!(member.flags & 128 /* Static */)) {\n write(\".prototype\");\n }\n }\n function emitDecoratorsOfClass(node) {\n emitDecoratorsOfMembers(node, /*staticFlag*/ 0);\n emitDecoratorsOfMembers(node, 128 /* Static */);\n emitDecoratorsOfConstructor(node);\n }\n function emitDecoratorsOfConstructor(node) {\n var decorators = node.decorators;\n var constructor = ts.getFirstConstructorWithBody(node);\n var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated);\n // skip decoration of the constructor if neither it nor its parameters are decorated\n if (!decorators && !hasDecoratedParameters) {\n return;\n }\n // Emit the call to __decorate. Given the class:\n //\n // @dec\n // class C {\n // }\n //\n // The emit for the class is:\n //\n // C = __decorate([dec], C);\n //\n writeLine();\n emitStart(node);\n emitDeclarationName(node);\n write(\" = __decorate([\");\n increaseIndent();\n writeLine();\n var decoratorCount = decorators ? decorators.length : 0;\n var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) {\n emitStart(decorator);\n emit(decorator.expression);\n emitEnd(decorator);\n });\n argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0);\n emitSerializedTypeMetadata(node, /*leadingComma*/ argumentsWritten >= 0);\n decreaseIndent();\n writeLine();\n write(\"], \");\n emitDeclarationName(node);\n write(\");\");\n emitEnd(node);\n writeLine();\n }\n function emitDecoratorsOfMembers(node, staticFlag) {\n for (var _a = 0, _b = node.members; _a < _b.length; _a++) {\n var member = _b[_a];\n // only emit members in the correct group\n if ((member.flags & 128 /* Static */) !== staticFlag) {\n continue;\n }\n // skip members that cannot be decorated (such as the constructor)\n if (!ts.nodeCanBeDecorated(member)) {\n continue;\n }\n // skip a member if it or any of its parameters are not decorated\n if (!ts.nodeOrChildIsDecorated(member)) {\n continue;\n }\n // skip an accessor declaration if it is not the first accessor\n var decorators = void 0;\n var functionLikeMember = void 0;\n if (ts.isAccessor(member)) {\n var accessors = ts.getAllAccessorDeclarations(node.members, member);\n if (member !== accessors.firstAccessor) {\n continue;\n }\n // get the decorators from the first accessor with decorators\n decorators = accessors.firstAccessor.decorators;\n if (!decorators && accessors.secondAccessor) {\n decorators = accessors.secondAccessor.decorators;\n }\n // we only decorate parameters of the set accessor\n functionLikeMember = accessors.setAccessor;\n }\n else {\n decorators = member.decorators;\n // we only decorate the parameters here if this is a method\n if (member.kind === 143 /* MethodDeclaration */) {\n functionLikeMember = member;\n }\n }\n // Emit the call to __decorate. Given the following:\n //\n // class C {\n // @dec method(@dec2 x) {}\n // @dec get accessor() {}\n // @dec prop;\n // }\n //\n // The emit for a method is:\n //\n // __decorate([\n // dec,\n // __param(0, dec2),\n // __metadata(\"design:type\", Function),\n // __metadata(\"design:paramtypes\", [Object]),\n // __metadata(\"design:returntype\", void 0)\n // ], C.prototype, \"method\", undefined);\n //\n // The emit for an accessor is:\n //\n // __decorate([\n // dec\n // ], C.prototype, \"accessor\", undefined);\n //\n // The emit for a property is:\n //\n // __decorate([\n // dec\n // ], C.prototype, \"prop\");\n //\n writeLine();\n emitStart(member);\n write(\"__decorate([\");\n increaseIndent();\n writeLine();\n var decoratorCount = decorators ? decorators.length : 0;\n var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) {\n emitStart(decorator);\n emit(decorator.expression);\n emitEnd(decorator);\n });\n argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0);\n emitSerializedTypeMetadata(member, argumentsWritten > 0);\n decreaseIndent();\n writeLine();\n write(\"], \");\n emitStart(member.name);\n emitClassMemberPrefix(node, member);\n write(\", \");\n emitExpressionForPropertyName(member.name);\n emitEnd(member.name);\n if (languageVersion > 0 /* ES3 */) {\n if (member.kind !== 141 /* PropertyDeclaration */) {\n // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.\n // We have this extra argument here so that we can inject an explicit property descriptor at a later date.\n write(\", null\");\n }\n else {\n // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it\n // should not invoke `Object.getOwnPropertyDescriptor`.\n write(\", void 0\");\n }\n }\n write(\");\");\n emitEnd(member);\n writeLine();\n }\n }\n function emitDecoratorsOfParameters(node, leadingComma) {\n var argumentsWritten = 0;\n if (node) {\n var parameterIndex = 0;\n for (var _a = 0, _b = node.parameters; _a < _b.length; _a++) {\n var parameter = _b[_a];\n if (ts.nodeIsDecorated(parameter)) {\n var decorators = parameter.decorators;\n argumentsWritten += emitList(decorators, 0, decorators.length, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ leadingComma, /*noTrailingNewLine*/ true, function (decorator) {\n emitStart(decorator);\n write(\"__param(\" + parameterIndex + \", \");\n emit(decorator.expression);\n write(\")\");\n emitEnd(decorator);\n });\n leadingComma = true;\n }\n ++parameterIndex;\n }\n }\n return argumentsWritten;\n }\n function shouldEmitTypeMetadata(node) {\n // This method determines whether to emit the \"design:type\" metadata based on the node's kind.\n // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata\n // compiler option is set.\n switch (node.kind) {\n case 143 /* MethodDeclaration */:\n case 145 /* GetAccessor */:\n case 146 /* SetAccessor */:\n case 141 /* PropertyDeclaration */:\n return true;\n }\n return false;\n }\n function shouldEmitReturnTypeMetadata(node) {\n // This method determines whether to emit the \"design:returntype\" metadata based on the node's kind.\n // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata\n // compiler option is set.\n switch (node.kind) {\n case 143 /* MethodDeclaration */:\n return true;\n }\n return false;\n }\n function shouldEmitParamTypesMetadata(node) {\n // This method determines whether to emit the \"design:paramtypes\" metadata based on the node's kind.\n // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata\n // compiler option is set.\n switch (node.kind) {\n case 214 /* ClassDeclaration */:\n case 143 /* MethodDeclaration */:\n case 146 /* SetAccessor */:\n return true;\n }\n return false;\n }\n /** Serializes the type of a declaration to an appropriate JS constructor value. Used by the __metadata decorator for a class member. */\n function emitSerializedTypeOfNode(node) {\n // serialization of the type of a declaration uses the following rules:\n //\n // * The serialized type of a ClassDeclaration is \"Function\"\n // * The serialized type of a ParameterDeclaration is the serialized type of its type annotation.\n // * The serialized type of a PropertyDeclaration is the serialized type of its type annotation.\n // * The serialized type of an AccessorDeclaration is the serialized type of the return type annotation of its getter or parameter type annotation of its setter.\n // * The serialized type of any other FunctionLikeDeclaration is \"Function\".\n // * The serialized type of any other node is \"void 0\".\n //\n // For rules on serializing type annotations, see `serializeTypeNode`.\n switch (node.kind) {\n case 214 /* ClassDeclaration */:\n write(\"Function\");\n return;\n case 141 /* PropertyDeclaration */:\n emitSerializedTypeNode(node.type);\n return;\n case 138 /* Parameter */:\n emitSerializedTypeNode(node.type);\n return;\n case 145 /* GetAccessor */:\n emitSerializedTypeNode(node.type);\n return;\n case 146 /* SetAccessor */:\n emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node));\n return;\n }\n if (ts.isFunctionLike(node)) {\n write(\"Function\");\n return;\n }\n write(\"void 0\");\n }\n function emitSerializedTypeNode(node) {\n if (node) {\n switch (node.kind) {\n case 103 /* VoidKeyword */:\n write(\"void 0\");\n return;\n case 160 /* ParenthesizedType */:\n emitSerializedTypeNode(node.type);\n return;\n case 152 /* FunctionType */:\n case 153 /* ConstructorType */:\n write(\"Function\");\n return;\n case 156 /* ArrayType */:\n case 157 /* TupleType */:\n write(\"Array\");\n return;\n case 150 /* TypePredicate */:\n case 120 /* BooleanKeyword */:\n write(\"Boolean\");\n return;\n case 130 /* StringKeyword */:\n case 9 /* StringLiteral */:\n write(\"String\");\n return;\n case 128 /* NumberKeyword */:\n write(\"Number\");\n return;\n case 131 /* SymbolKeyword */:\n write(\"Symbol\");\n return;\n case 151 /* TypeReference */:\n emitSerializedTypeReferenceNode(node);\n return;\n case 154 /* TypeQuery */:\n case 155 /* TypeLiteral */:\n case 158 /* UnionType */:\n case 159 /* IntersectionType */:\n case 117 /* AnyKeyword */:\n break;\n default:\n ts.Debug.fail(\"Cannot serialize unexpected type node.\");\n break;\n }\n }\n write(\"Object\");\n }\n /** Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator. */\n function emitSerializedTypeReferenceNode(node) {\n var location = node.parent;\n while (ts.isDeclaration(location) || ts.isTypeNode(location)) {\n location = location.parent;\n }\n // Clone the type name and parent it to a location outside of the current declaration.\n var typeName = ts.cloneEntityName(node.typeName);\n typeName.parent = location;\n var result = resolver.getTypeReferenceSerializationKind(typeName);\n switch (result) {\n case ts.TypeReferenceSerializationKind.Unknown:\n var temp = createAndRecordTempVariable(0 /* Auto */);\n write(\"(typeof (\");\n emitNodeWithoutSourceMap(temp);\n write(\" = \");\n emitEntityNameAsExpression(typeName, /*useFallback*/ true);\n write(\") === 'function' && \");\n emitNodeWithoutSourceMap(temp);\n write(\") || Object\");\n break;\n case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:\n emitEntityNameAsExpression(typeName, /*useFallback*/ false);\n break;\n case ts.TypeReferenceSerializationKind.VoidType:\n write(\"void 0\");\n break;\n case ts.TypeReferenceSerializationKind.BooleanType:\n write(\"Boolean\");\n break;\n case ts.TypeReferenceSerializationKind.NumberLikeType:\n write(\"Number\");\n break;\n case ts.TypeReferenceSerializationKind.StringLikeType:\n write(\"String\");\n break;\n case ts.TypeReferenceSerializationKind.ArrayLikeType:\n write(\"Array\");\n break;\n case ts.TypeReferenceSerializationKind.ESSymbolType:\n if (languageVersion < 2 /* ES6 */) {\n write(\"typeof Symbol === 'function' ? Symbol : Object\");\n }\n else {\n write(\"Symbol\");\n }\n break;\n case ts.TypeReferenceSerializationKind.TypeWithCallSignature:\n write(\"Function\");\n break;\n case ts.TypeReferenceSerializationKind.ObjectType:\n write(\"Object\");\n break;\n }\n }\n /** Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor. */\n function emitSerializedParameterTypesOfNode(node) {\n // serialization of parameter types uses the following rules:\n //\n // * If the declaration is a class, the parameters of the first constructor with a body are used.\n // * If the declaration is function-like and has a body, the parameters of the function are used.\n //\n // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`.\n if (node) {\n var valueDeclaration;\n if (node.kind === 214 /* ClassDeclaration */) {\n valueDeclaration = ts.getFirstConstructorWithBody(node);\n }\n else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) {\n valueDeclaration = node;\n }\n if (valueDeclaration) {\n var parameters = valueDeclaration.parameters;\n var parameterCount = parameters.length;\n if (parameterCount > 0) {\n for (var i = 0; i < parameterCount; i++) {\n if (i > 0) {\n write(\", \");\n }\n if (parameters[i].dotDotDotToken) {\n var parameterType = parameters[i].type;\n if (parameterType.kind === 156 /* ArrayType */) {\n parameterType = parameterType.elementType;\n }\n else if (parameterType.kind === 151 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) {\n parameterType = parameterType.typeArguments[0];\n }\n else {\n parameterType = undefined;\n }\n emitSerializedTypeNode(parameterType);\n }\n else {\n emitSerializedTypeOfNode(parameters[i]);\n }\n }\n }\n }\n }\n }\n /** Serializes the return type of function. Used by the __metadata decorator for a method. */\n function emitSerializedReturnTypeOfNode(node) {\n if (node && ts.isFunctionLike(node) && node.type) {\n emitSerializedTypeNode(node.type);\n return;\n }\n write(\"void 0\");\n }\n function emitSerializedTypeMetadata(node, writeComma) {\n // This method emits the serialized type metadata for a decorator target.\n // The caller should have already tested whether the node has decorators.\n var argumentsWritten = 0;\n if (compilerOptions.emitDecoratorMetadata) {\n if (shouldEmitTypeMetadata(node)) {\n if (writeComma) {\n write(\", \");\n }\n writeLine();\n write(\"__metadata('design:type', \");\n emitSerializedTypeOfNode(node);\n write(\")\");\n argumentsWritten++;\n }\n if (shouldEmitParamTypesMetadata(node)) {\n if (writeComma || argumentsWritten) {\n write(\", \");\n }\n writeLine();\n write(\"__metadata('design:paramtypes', [\");\n emitSerializedParameterTypesOfNode(node);\n write(\"])\");\n argumentsWritten++;\n }\n if (shouldEmitReturnTypeMetadata(node)) {\n if (writeComma || argumentsWritten) {\n write(\", \");\n }\n writeLine();\n write(\"__metadata('design:returntype', \");\n emitSerializedReturnTypeOfNode(node);\n write(\")\");\n argumentsWritten++;\n }\n }\n return argumentsWritten;\n }\n function emitInterfaceDeclaration(node) {\n emitCommentsOnNotEmittedNode(node);\n }\n function shouldEmitEnumDeclaration(node) {\n var isConstEnum = ts.isConst(node);\n return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules;\n }\n function emitEnumDeclaration(node) {\n // const enums are completely erased during compilation.\n if (!shouldEmitEnumDeclaration(node)) {\n return;\n }\n if (!shouldHoistDeclarationInSystemJsModule(node)) {\n // do not emit var if variable was already hoisted\n if (!(node.flags & 1 /* Export */) || isES6ExportedDeclaration(node)) {\n emitStart(node);\n if (isES6ExportedDeclaration(node)) {\n write(\"export \");\n }\n write(\"var \");\n emit(node.name);\n emitEnd(node);\n write(\";\");\n }\n }\n writeLine();\n emitStart(node);\n write(\"(function (\");\n emitStart(node.name);\n write(getGeneratedNameForNode(node));\n emitEnd(node.name);\n write(\") {\");\n increaseIndent();\n scopeEmitStart(node);\n emitLines(node.members);\n decreaseIndent();\n writeLine();\n emitToken(16 /* CloseBraceToken */, node.members.end);\n scopeEmitEnd();\n write(\")(\");\n emitModuleMemberName(node);\n write(\" || (\");\n emitModuleMemberName(node);\n write(\" = {}));\");\n emitEnd(node);\n if (!isES6ExportedDeclaration(node) && node.flags & 1 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) {\n // do not emit var if variable was already hoisted\n writeLine();\n emitStart(node);\n write(\"var \");\n emit(node.name);\n write(\" = \");\n emitModuleMemberName(node);\n emitEnd(node);\n write(\";\");\n }\n if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) {\n if (modulekind === 4 /* System */ && (node.flags & 1 /* Export */)) {\n // write the call to exporter for enum\n writeLine();\n write(exportFunctionForFile + \"(\\\"\");\n emitDeclarationName(node);\n write(\"\\\", \");\n emitDeclarationName(node);\n write(\");\");\n }\n emitExportMemberAssignments(node.name);\n }\n }\n function emitEnumMember(node) {\n var enumParent = node.parent;\n emitStart(node);\n write(getGeneratedNameForNode(enumParent));\n write(\"[\");\n write(getGeneratedNameForNode(enumParent));\n write(\"[\");\n emitExpressionForPropertyName(node.name);\n write(\"] = \");\n writeEnumMemberDeclarationValue(node);\n write(\"] = \");\n emitExpressionForPropertyName(node.name);\n emitEnd(node);\n write(\";\");\n }\n function writeEnumMemberDeclarationValue(member) {\n var value = resolver.getConstantValue(member);\n if (value !== undefined) {\n write(value.toString());\n return;\n }\n else if (member.initializer) {\n emit(member.initializer);\n }\n else {\n write(\"undefined\");\n }\n }\n function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {\n if (moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) {\n var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);\n return recursiveInnerModule || moduleDeclaration.body;\n }\n }\n function shouldEmitModuleDeclaration(node) {\n return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules);\n }\n function isModuleMergedWithES6Class(node) {\n return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 32768 /* LexicalModuleMergesWithClass */);\n }\n function emitModuleDeclaration(node) {\n // Emit only if this module is non-ambient.\n var shouldEmit = shouldEmitModuleDeclaration(node);\n if (!shouldEmit) {\n return emitCommentsOnNotEmittedNode(node);\n }\n var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node);\n var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node);\n if (emitVarForModule) {\n emitStart(node);\n if (isES6ExportedDeclaration(node)) {\n write(\"export \");\n }\n write(\"var \");\n emit(node.name);\n write(\";\");\n emitEnd(node);\n writeLine();\n }\n emitStart(node);\n write(\"(function (\");\n emitStart(node.name);\n write(getGeneratedNameForNode(node));\n emitEnd(node.name);\n write(\") \");\n if (node.body.kind === 219 /* ModuleBlock */) {\n var saveTempFlags = tempFlags;\n var saveTempVariables = tempVariables;\n tempFlags = 0;\n tempVariables = undefined;\n emit(node.body);\n tempFlags = saveTempFlags;\n tempVariables = saveTempVariables;\n }\n else {\n write(\"{\");\n increaseIndent();\n scopeEmitStart(node);\n emitCaptureThisForNodeIfNecessary(node);\n writeLine();\n emit(node.body);\n decreaseIndent();\n writeLine();\n var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;\n emitToken(16 /* CloseBraceToken */, moduleBlock.statements.end);\n scopeEmitEnd();\n }\n write(\")(\");\n // write moduleDecl = containingModule.m only if it is not exported es6 module member\n if ((node.flags & 1 /* Export */) && !isES6ExportedDeclaration(node)) {\n emit(node.name);\n write(\" = \");\n }\n emitModuleMemberName(node);\n write(\" || (\");\n emitModuleMemberName(node);\n write(\" = {}));\");\n emitEnd(node);\n if (!isES6ExportedDeclaration(node) && node.name.kind === 69 /* Identifier */ && node.parent === currentSourceFile) {\n if (modulekind === 4 /* System */ && (node.flags & 1 /* Export */)) {\n writeLine();\n write(exportFunctionForFile + \"(\\\"\");\n emitDeclarationName(node);\n write(\"\\\", \");\n emitDeclarationName(node);\n write(\");\");\n }\n emitExportMemberAssignments(node.name);\n }\n }\n /*\n * Some bundlers (SystemJS builder) sometimes want to rename dependencies.\n * Here we check if alternative name was provided for a given moduleName and return it if possible.\n */\n function tryRenameExternalModule(moduleName) {\n if (currentSourceFile.renamedDependencies && ts.hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) {\n return \"\\\"\" + currentSourceFile.renamedDependencies[moduleName.text] + \"\\\"\";\n }\n return undefined;\n }\n function emitRequire(moduleName) {\n if (moduleName.kind === 9 /* StringLiteral */) {\n write(\"require(\");\n var text = tryRenameExternalModule(moduleName);\n if (text) {\n write(text);\n }\n else {\n emitStart(moduleName);\n emitLiteral(moduleName);\n emitEnd(moduleName);\n }\n emitToken(18 /* CloseParenToken */, moduleName.end);\n }\n else {\n write(\"require()\");\n }\n }\n function getNamespaceDeclarationNode(node) {\n if (node.kind === 221 /* ImportEqualsDeclaration */) {\n return node;\n }\n var importClause = node.importClause;\n if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 224 /* NamespaceImport */) {\n return importClause.namedBindings;\n }\n }\n function isDefaultImport(node) {\n return node.kind === 222 /* ImportDeclaration */ && node.importClause && !!node.importClause.name;\n }\n function emitExportImportAssignments(node) {\n if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) {\n emitExportMemberAssignments(node.name);\n }\n ts.forEachChild(node, emitExportImportAssignments);\n }\n function emitImportDeclaration(node) {\n if (modulekind !== 5 /* ES6 */) {\n return emitExternalImportDeclaration(node);\n }\n // ES6 import\n if (node.importClause) {\n var shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause);\n var shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, /* checkChildren */ true);\n if (shouldEmitDefaultBindings || shouldEmitNamedBindings) {\n write(\"import \");\n emitStart(node.importClause);\n if (shouldEmitDefaultBindings) {\n emit(node.importClause.name);\n if (shouldEmitNamedBindings) {\n write(\", \");\n }\n }\n if (shouldEmitNamedBindings) {\n emitLeadingComments(node.importClause.namedBindings);\n emitStart(node.importClause.namedBindings);\n if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) {\n write(\"* as \");\n emit(node.importClause.namedBindings.name);\n }\n else {\n write(\"{ \");\n emitExportOrImportSpecifierList(node.importClause.namedBindings.elements, resolver.isReferencedAliasDeclaration);\n write(\" }\");\n }\n emitEnd(node.importClause.namedBindings);\n emitTrailingComments(node.importClause.namedBindings);\n }\n emitEnd(node.importClause);\n write(\" from \");\n emit(node.moduleSpecifier);\n write(\";\");\n }\n }\n else {\n write(\"import \");\n emit(node.moduleSpecifier);\n write(\";\");\n }\n }\n function emitExternalImportDeclaration(node) {\n if (ts.contains(externalImports, node)) {\n var isExportedImport = node.kind === 221 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0;\n var namespaceDeclaration = getNamespaceDeclarationNode(node);\n if (modulekind !== 2 /* AMD */) {\n emitLeadingComments(node);\n emitStart(node);\n if (namespaceDeclaration && !isDefaultImport(node)) {\n // import x = require(\"foo\")\n // import * as x from \"foo\"\n if (!isExportedImport)\n write(\"var \");\n emitModuleMemberName(namespaceDeclaration);\n write(\" = \");\n }\n else {\n // import \"foo\"\n // import x from \"foo\"\n // import { x, y } from \"foo\"\n // import d, * as x from \"foo\"\n // import d, { x, y } from \"foo\"\n var isNakedImport = 222 /* ImportDeclaration */ && !node.importClause;\n if (!isNakedImport) {\n write(\"var \");\n write(getGeneratedNameForNode(node));\n write(\" = \");\n }\n }\n emitRequire(ts.getExternalModuleName(node));\n if (namespaceDeclaration && isDefaultImport(node)) {\n // import d, * as x from \"foo\"\n write(\", \");\n emitModuleMemberName(namespaceDeclaration);\n write(\" = \");\n write(getGeneratedNameForNode(node));\n }\n write(\";\");\n emitEnd(node);\n emitExportImportAssignments(node);\n emitTrailingComments(node);\n }\n else {\n if (isExportedImport) {\n emitModuleMemberName(namespaceDeclaration);\n write(\" = \");\n emit(namespaceDeclaration.name);\n write(\";\");\n }\n else if (namespaceDeclaration && isDefaultImport(node)) {\n // import d, * as x from \"foo\"\n write(\"var \");\n emitModuleMemberName(namespaceDeclaration);\n write(\" = \");\n write(getGeneratedNameForNode(node));\n write(\";\");\n }\n emitExportImportAssignments(node);\n }\n }\n }\n function emitImportEqualsDeclaration(node) {\n if (ts.isExternalModuleImportEqualsDeclaration(node)) {\n emitExternalImportDeclaration(node);\n return;\n }\n // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when\n // - current file is not external module\n // - import declaration is top level and target is value imported by entity name\n if (resolver.isReferencedAliasDeclaration(node) ||\n (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {\n emitLeadingComments(node);\n emitStart(node);\n // variable declaration for import-equals declaration can be hoisted in system modules\n // in this case 'var' should be omitted and emit should contain only initialization\n var variableDeclarationIsHoisted = shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true);\n // is it top level export import v = a.b.c in system module?\n // if yes - it needs to be rewritten as exporter('v', v = a.b.c)\n var isExported = isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ true);\n if (!variableDeclarationIsHoisted) {\n ts.Debug.assert(!isExported);\n if (isES6ExportedDeclaration(node)) {\n write(\"export \");\n write(\"var \");\n }\n else if (!(node.flags & 1 /* Export */)) {\n write(\"var \");\n }\n }\n if (isExported) {\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithoutSourceMap(node.name);\n write(\"\\\", \");\n }\n emitModuleMemberName(node);\n write(\" = \");\n emit(node.moduleReference);\n if (isExported) {\n write(\")\");\n }\n write(\";\");\n emitEnd(node);\n emitExportImportAssignments(node);\n emitTrailingComments(node);\n }\n }\n function emitExportDeclaration(node) {\n ts.Debug.assert(modulekind !== 4 /* System */);\n if (modulekind !== 5 /* ES6 */) {\n if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) {\n emitStart(node);\n var generatedName = getGeneratedNameForNode(node);\n if (node.exportClause) {\n // export { x, y, ... } from \"foo\"\n if (modulekind !== 2 /* AMD */) {\n write(\"var \");\n write(generatedName);\n write(\" = \");\n emitRequire(ts.getExternalModuleName(node));\n write(\";\");\n }\n for (var _a = 0, _b = node.exportClause.elements; _a < _b.length; _a++) {\n var specifier = _b[_a];\n if (resolver.isValueAliasDeclaration(specifier)) {\n writeLine();\n emitStart(specifier);\n emitContainingModuleName(specifier);\n write(\".\");\n emitNodeWithCommentsAndWithoutSourcemap(specifier.name);\n write(\" = \");\n write(generatedName);\n write(\".\");\n emitNodeWithCommentsAndWithoutSourcemap(specifier.propertyName || specifier.name);\n write(\";\");\n emitEnd(specifier);\n }\n }\n }\n else {\n // export * from \"foo\"\n writeLine();\n write(\"__export(\");\n if (modulekind !== 2 /* AMD */) {\n emitRequire(ts.getExternalModuleName(node));\n }\n else {\n write(generatedName);\n }\n write(\");\");\n }\n emitEnd(node);\n }\n }\n else {\n if (!node.exportClause || resolver.isValueAliasDeclaration(node)) {\n write(\"export \");\n if (node.exportClause) {\n // export { x, y, ... }\n write(\"{ \");\n emitExportOrImportSpecifierList(node.exportClause.elements, resolver.isValueAliasDeclaration);\n write(\" }\");\n }\n else {\n write(\"*\");\n }\n if (node.moduleSpecifier) {\n write(\" from \");\n emit(node.moduleSpecifier);\n }\n write(\";\");\n }\n }\n }\n function emitExportOrImportSpecifierList(specifiers, shouldEmit) {\n ts.Debug.assert(modulekind === 5 /* ES6 */);\n var needsComma = false;\n for (var _a = 0; _a < specifiers.length; _a++) {\n var specifier = specifiers[_a];\n if (shouldEmit(specifier)) {\n if (needsComma) {\n write(\", \");\n }\n if (specifier.propertyName) {\n emit(specifier.propertyName);\n write(\" as \");\n }\n emit(specifier.name);\n needsComma = true;\n }\n }\n }\n function emitExportAssignment(node) {\n if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) {\n if (modulekind === 5 /* ES6 */) {\n writeLine();\n emitStart(node);\n write(\"export default \");\n var expression = node.expression;\n emit(expression);\n if (expression.kind !== 213 /* FunctionDeclaration */ &&\n expression.kind !== 214 /* ClassDeclaration */) {\n write(\";\");\n }\n emitEnd(node);\n }\n else {\n writeLine();\n emitStart(node);\n if (modulekind === 4 /* System */) {\n write(exportFunctionForFile + \"(\\\"default\\\",\");\n emit(node.expression);\n write(\")\");\n }\n else {\n emitEs6ExportDefaultCompat(node);\n emitContainingModuleName(node);\n if (languageVersion === 0 /* ES3 */) {\n write(\"[\\\"default\\\"] = \");\n }\n else {\n write(\".default = \");\n }\n emit(node.expression);\n }\n write(\";\");\n emitEnd(node);\n }\n }\n }\n function collectExternalModuleInfo(sourceFile) {\n externalImports = [];\n exportSpecifiers = {};\n exportEquals = undefined;\n hasExportStars = false;\n for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {\n var node = _b[_a];\n switch (node.kind) {\n case 222 /* ImportDeclaration */:\n if (!node.importClause ||\n resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) {\n // import \"mod\"\n // import x from \"mod\" where x is referenced\n // import * as x from \"mod\" where x is referenced\n // import { x, y } from \"mod\" where at least one import is referenced\n externalImports.push(node);\n }\n break;\n case 221 /* ImportEqualsDeclaration */:\n if (node.moduleReference.kind === 232 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) {\n // import x = require(\"mod\") where x is referenced\n externalImports.push(node);\n }\n break;\n case 228 /* ExportDeclaration */:\n if (node.moduleSpecifier) {\n if (!node.exportClause) {\n // export * from \"mod\"\n externalImports.push(node);\n hasExportStars = true;\n }\n else if (resolver.isValueAliasDeclaration(node)) {\n // export { x, y } from \"mod\" where at least one export is a value symbol\n externalImports.push(node);\n }\n }\n else {\n // export { x, y }\n for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) {\n var specifier = _d[_c];\n var name_25 = (specifier.propertyName || specifier.name).text;\n (exportSpecifiers[name_25] || (exportSpecifiers[name_25] = [])).push(specifier);\n }\n }\n break;\n case 227 /* ExportAssignment */:\n if (node.isExportEquals && !exportEquals) {\n // export = x\n exportEquals = node;\n }\n break;\n }\n }\n }\n function emitExportStarHelper() {\n if (hasExportStars) {\n writeLine();\n write(\"function __export(m) {\");\n increaseIndent();\n writeLine();\n write(\"for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\");\n decreaseIndent();\n writeLine();\n write(\"}\");\n }\n }\n function getLocalNameForExternalImport(node) {\n var namespaceDeclaration = getNamespaceDeclarationNode(node);\n if (namespaceDeclaration && !isDefaultImport(node)) {\n return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name);\n }\n if (node.kind === 222 /* ImportDeclaration */ && node.importClause) {\n return getGeneratedNameForNode(node);\n }\n if (node.kind === 228 /* ExportDeclaration */ && node.moduleSpecifier) {\n return getGeneratedNameForNode(node);\n }\n }\n function getExternalModuleNameText(importNode) {\n var moduleName = ts.getExternalModuleName(importNode);\n if (moduleName.kind === 9 /* StringLiteral */) {\n return tryRenameExternalModule(moduleName) || getLiteralText(moduleName);\n }\n return undefined;\n }\n function emitVariableDeclarationsForImports() {\n if (externalImports.length === 0) {\n return;\n }\n writeLine();\n var started = false;\n for (var _a = 0; _a < externalImports.length; _a++) {\n var importNode = externalImports[_a];\n // do not create variable declaration for exports and imports that lack import clause\n var skipNode = importNode.kind === 228 /* ExportDeclaration */ ||\n (importNode.kind === 222 /* ImportDeclaration */ && !importNode.importClause);\n if (skipNode) {\n continue;\n }\n if (!started) {\n write(\"var \");\n started = true;\n }\n else {\n write(\", \");\n }\n write(getLocalNameForExternalImport(importNode));\n }\n if (started) {\n write(\";\");\n }\n }\n function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) {\n // when resolving exports local exported entries/indirect exported entries in the module\n // should always win over entries with similar names that were added via star exports\n // to support this we store names of local/indirect exported entries in a set.\n // this set is used to filter names brought by star expors.\n if (!hasExportStars) {\n // local names set is needed only in presence of star exports\n return undefined;\n }\n // local names set should only be added if we have anything exported\n if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) {\n // no exported declarations (export var ...) or export specifiers (export {x})\n // check if we have any non star export declarations.\n var hasExportDeclarationWithExportClause = false;\n for (var _a = 0; _a < externalImports.length; _a++) {\n var externalImport = externalImports[_a];\n if (externalImport.kind === 228 /* ExportDeclaration */ && externalImport.exportClause) {\n hasExportDeclarationWithExportClause = true;\n break;\n }\n }\n if (!hasExportDeclarationWithExportClause) {\n // we still need to emit exportStar helper\n return emitExportStarFunction(/*localNames*/ undefined);\n }\n }\n var exportedNamesStorageRef = makeUniqueName(\"exportedNames\");\n writeLine();\n write(\"var \" + exportedNamesStorageRef + \" = {\");\n increaseIndent();\n var started = false;\n if (exportedDeclarations) {\n for (var i = 0; i < exportedDeclarations.length; ++i) {\n // write name of exported declaration, i.e 'export var x...'\n writeExportedName(exportedDeclarations[i]);\n }\n }\n if (exportSpecifiers) {\n for (var n in exportSpecifiers) {\n for (var _b = 0, _c = exportSpecifiers[n]; _b < _c.length; _b++) {\n var specifier = _c[_b];\n // write name of export specified, i.e. 'export {x}'\n writeExportedName(specifier.name);\n }\n }\n }\n for (var _d = 0; _d < externalImports.length; _d++) {\n var externalImport = externalImports[_d];\n if (externalImport.kind !== 228 /* ExportDeclaration */) {\n continue;\n }\n var exportDecl = externalImport;\n if (!exportDecl.exportClause) {\n // export * from ...\n continue;\n }\n for (var _e = 0, _f = exportDecl.exportClause.elements; _e < _f.length; _e++) {\n var element = _f[_e];\n // write name of indirectly exported entry, i.e. 'export {x} from ...'\n writeExportedName(element.name || element.propertyName);\n }\n }\n decreaseIndent();\n writeLine();\n write(\"};\");\n return emitExportStarFunction(exportedNamesStorageRef);\n function emitExportStarFunction(localNames) {\n var exportStarFunction = makeUniqueName(\"exportStar\");\n writeLine();\n // define an export star helper function\n write(\"function \" + exportStarFunction + \"(m) {\");\n increaseIndent();\n writeLine();\n write(\"var exports = {};\");\n writeLine();\n write(\"for(var n in m) {\");\n increaseIndent();\n writeLine();\n write(\"if (n !== \\\"default\\\"\");\n if (localNames) {\n write(\"&& !\" + localNames + \".hasOwnProperty(n)\");\n }\n write(\") exports[n] = m[n];\");\n decreaseIndent();\n writeLine();\n write(\"}\");\n writeLine();\n write(exportFunctionForFile + \"(exports);\");\n decreaseIndent();\n writeLine();\n write(\"}\");\n return exportStarFunction;\n }\n function writeExportedName(node) {\n // do not record default exports\n // they are local to module and never overwritten (explicitly skipped) by star export\n if (node.kind !== 69 /* Identifier */ && node.flags & 1024 /* Default */) {\n return;\n }\n if (started) {\n write(\",\");\n }\n else {\n started = true;\n }\n writeLine();\n write(\"'\");\n if (node.kind === 69 /* Identifier */) {\n emitNodeWithCommentsAndWithoutSourcemap(node);\n }\n else {\n emitDeclarationName(node);\n }\n write(\"': true\");\n }\n }\n function processTopLevelVariableAndFunctionDeclarations(node) {\n // per ES6 spec:\n // 15.2.1.16.4 ModuleDeclarationInstantiation() Concrete Method\n // - var declarations are initialized to undefined - 14.a.ii\n // - function/generator declarations are instantiated - 16.a.iv\n // this means that after module is instantiated but before its evaluation\n // exported functions are already accessible at import sites\n // in theory we should hoist only exported functions and its dependencies\n // in practice to simplify things we'll hoist all source level functions and variable declaration\n // including variables declarations for module and class declarations\n var hoistedVars;\n var hoistedFunctionDeclarations;\n var exportedDeclarations;\n visit(node);\n if (hoistedVars) {\n writeLine();\n write(\"var \");\n var seen = {};\n for (var i = 0; i < hoistedVars.length; ++i) {\n var local = hoistedVars[i];\n var name_26 = local.kind === 69 /* Identifier */\n ? local\n : local.name;\n if (name_26) {\n // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables\n var text = ts.unescapeIdentifier(name_26.text);\n if (ts.hasProperty(seen, text)) {\n continue;\n }\n else {\n seen[text] = text;\n }\n }\n if (i !== 0) {\n write(\", \");\n }\n if (local.kind === 214 /* ClassDeclaration */ || local.kind === 218 /* ModuleDeclaration */ || local.kind === 217 /* EnumDeclaration */) {\n emitDeclarationName(local);\n }\n else {\n emit(local);\n }\n var flags = ts.getCombinedNodeFlags(local.kind === 69 /* Identifier */ ? local.parent : local);\n if (flags & 1 /* Export */) {\n if (!exportedDeclarations) {\n exportedDeclarations = [];\n }\n exportedDeclarations.push(local);\n }\n }\n write(\";\");\n }\n if (hoistedFunctionDeclarations) {\n for (var _a = 0; _a < hoistedFunctionDeclarations.length; _a++) {\n var f = hoistedFunctionDeclarations[_a];\n writeLine();\n emit(f);\n if (f.flags & 1 /* Export */) {\n if (!exportedDeclarations) {\n exportedDeclarations = [];\n }\n exportedDeclarations.push(f);\n }\n }\n }\n return exportedDeclarations;\n function visit(node) {\n if (node.flags & 2 /* Ambient */) {\n return;\n }\n if (node.kind === 213 /* FunctionDeclaration */) {\n if (!hoistedFunctionDeclarations) {\n hoistedFunctionDeclarations = [];\n }\n hoistedFunctionDeclarations.push(node);\n return;\n }\n if (node.kind === 214 /* ClassDeclaration */) {\n if (!hoistedVars) {\n hoistedVars = [];\n }\n hoistedVars.push(node);\n return;\n }\n if (node.kind === 217 /* EnumDeclaration */) {\n if (shouldEmitEnumDeclaration(node)) {\n if (!hoistedVars) {\n hoistedVars = [];\n }\n hoistedVars.push(node);\n }\n return;\n }\n if (node.kind === 218 /* ModuleDeclaration */) {\n if (shouldEmitModuleDeclaration(node)) {\n if (!hoistedVars) {\n hoistedVars = [];\n }\n hoistedVars.push(node);\n }\n return;\n }\n if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) {\n if (shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ false)) {\n var name_27 = node.name;\n if (name_27.kind === 69 /* Identifier */) {\n if (!hoistedVars) {\n hoistedVars = [];\n }\n hoistedVars.push(name_27);\n }\n else {\n ts.forEachChild(name_27, visit);\n }\n }\n return;\n }\n if (ts.isInternalModuleImportEqualsDeclaration(node) && resolver.isValueAliasDeclaration(node)) {\n if (!hoistedVars) {\n hoistedVars = [];\n }\n hoistedVars.push(node.name);\n return;\n }\n if (ts.isBindingPattern(node)) {\n ts.forEach(node.elements, visit);\n return;\n }\n if (!ts.isDeclaration(node)) {\n ts.forEachChild(node, visit);\n }\n }\n }\n function shouldHoistVariable(node, checkIfSourceFileLevelDecl) {\n if (checkIfSourceFileLevelDecl && !shouldHoistDeclarationInSystemJsModule(node)) {\n return false;\n }\n // hoist variable if\n // - it is not block scoped\n // - it is top level block scoped\n // if block scoped variables are nested in some another block then\n // no other functions can use them except ones that are defined at least in the same block\n return (ts.getCombinedNodeFlags(node) & 49152 /* BlockScoped */) === 0 ||\n ts.getEnclosingBlockScopeContainer(node).kind === 248 /* SourceFile */;\n }\n function isCurrentFileSystemExternalModule() {\n return modulekind === 4 /* System */ && ts.isExternalModule(currentSourceFile);\n }\n function emitSystemModuleBody(node, dependencyGroups, startIndex) {\n // shape of the body in system modules:\n // function (exports) {\n // \n // \n // \n // return {\n // setters: [\n // \n // ],\n // execute: function() {\n // \n // }\n // }\n // \n // }\n // I.e:\n // import {x} from 'file1'\n // var y = 1;\n // export function foo() { return y + x(); }\n // console.log(y);\n // will be transformed to\n // function(exports) {\n // var file1; // local alias\n // var y;\n // function foo() { return y + file1.x(); }\n // exports(\"foo\", foo);\n // return {\n // setters: [\n // function(v) { file1 = v }\n // ],\n // execute(): function() {\n // y = 1;\n // console.log(y);\n // }\n // };\n // }\n emitVariableDeclarationsForImports();\n writeLine();\n var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node);\n var exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations);\n writeLine();\n write(\"return {\");\n increaseIndent();\n writeLine();\n emitSetters(exportStarFunction, dependencyGroups);\n writeLine();\n emitExecute(node, startIndex);\n decreaseIndent();\n writeLine();\n write(\"}\"); // return\n emitTempDeclarations(/*newLine*/ true);\n }\n function emitSetters(exportStarFunction, dependencyGroups) {\n write(\"setters:[\");\n for (var i = 0; i < dependencyGroups.length; ++i) {\n if (i !== 0) {\n write(\",\");\n }\n writeLine();\n increaseIndent();\n var group = dependencyGroups[i];\n // derive a unique name for parameter from the first named entry in the group\n var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || \"\");\n write(\"function (\" + parameterName + \") {\");\n increaseIndent();\n for (var _a = 0; _a < group.length; _a++) {\n var entry = group[_a];\n var importVariableName = getLocalNameForExternalImport(entry) || \"\";\n switch (entry.kind) {\n case 222 /* ImportDeclaration */:\n if (!entry.importClause) {\n // 'import \"...\"' case\n // module is imported only for side-effects, no emit required\n break;\n }\n // fall-through\n case 221 /* ImportEqualsDeclaration */:\n ts.Debug.assert(importVariableName !== \"\");\n writeLine();\n // save import into the local\n write(importVariableName + \" = \" + parameterName + \";\");\n writeLine();\n break;\n case 228 /* ExportDeclaration */:\n ts.Debug.assert(importVariableName !== \"\");\n if (entry.exportClause) {\n // export {a, b as c} from 'foo'\n // emit as:\n // exports_({\n // \"a\": _[\"a\"],\n // \"c\": _[\"b\"]\n // });\n writeLine();\n write(exportFunctionForFile + \"({\");\n writeLine();\n increaseIndent();\n for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; ++i_2) {\n if (i_2 !== 0) {\n write(\",\");\n writeLine();\n }\n var e = entry.exportClause.elements[i_2];\n write(\"\\\"\");\n emitNodeWithCommentsAndWithoutSourcemap(e.name);\n write(\"\\\": \" + parameterName + \"[\\\"\");\n emitNodeWithCommentsAndWithoutSourcemap(e.propertyName || e.name);\n write(\"\\\"]\");\n }\n decreaseIndent();\n writeLine();\n write(\"});\");\n }\n else {\n writeLine();\n // export * from 'foo'\n // emit as:\n // exportStar(_foo);\n write(exportStarFunction + \"(\" + parameterName + \");\");\n }\n writeLine();\n break;\n }\n }\n decreaseIndent();\n write(\"}\");\n decreaseIndent();\n }\n write(\"],\");\n }\n function emitExecute(node, startIndex) {\n write(\"execute: function() {\");\n increaseIndent();\n writeLine();\n for (var i = startIndex; i < node.statements.length; ++i) {\n var statement = node.statements[i];\n switch (statement.kind) {\n // - function declarations are not emitted because they were already hoisted\n // - import declarations are not emitted since they are already handled in setters\n // - export declarations with module specifiers are not emitted since they were already written in setters\n // - export declarations without module specifiers are emitted preserving the order\n case 213 /* FunctionDeclaration */:\n case 222 /* ImportDeclaration */:\n continue;\n case 228 /* ExportDeclaration */:\n if (!statement.moduleSpecifier) {\n for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) {\n var element = _b[_a];\n // write call to exporter function for every export specifier in exports list\n emitExportSpecifierInSystemModule(element);\n }\n }\n continue;\n case 221 /* ImportEqualsDeclaration */:\n if (!ts.isInternalModuleImportEqualsDeclaration(statement)) {\n // - import equals declarations that import external modules are not emitted\n continue;\n }\n // fall-though for import declarations that import internal modules\n default:\n writeLine();\n emit(statement);\n }\n }\n decreaseIndent();\n writeLine();\n write(\"}\"); // execute\n }\n function emitSystemModule(node) {\n collectExternalModuleInfo(node);\n // System modules has the following shape\n // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})\n // 'exports' here is a function 'exports(name: string, value: T): T' that is used to publish exported values.\n // 'exports' returns its 'value' argument so in most cases expressions\n // that mutate exported values can be rewritten as:\n // expr -> exports('name', expr).\n // The only exception in this rule is postfix unary operators,\n // see comment to 'emitPostfixUnaryExpression' for more details\n ts.Debug.assert(!exportFunctionForFile);\n // make sure that name of 'exports' function does not conflict with existing identifiers\n exportFunctionForFile = makeUniqueName(\"exports\");\n writeLine();\n write(\"System.register(\");\n if (node.moduleName) {\n write(\"\\\"\" + node.moduleName + \"\\\", \");\n }\n write(\"[\");\n var groupIndices = {};\n var dependencyGroups = [];\n for (var i = 0; i < externalImports.length; ++i) {\n var text = getExternalModuleNameText(externalImports[i]);\n if (ts.hasProperty(groupIndices, text)) {\n // deduplicate/group entries in dependency list by the dependency name\n var groupIndex = groupIndices[text];\n dependencyGroups[groupIndex].push(externalImports[i]);\n continue;\n }\n else {\n groupIndices[text] = dependencyGroups.length;\n dependencyGroups.push([externalImports[i]]);\n }\n if (i !== 0) {\n write(\", \");\n }\n write(text);\n }\n write(\"], function(\" + exportFunctionForFile + \") {\");\n writeLine();\n increaseIndent();\n var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);\n emitEmitHelpers(node);\n emitCaptureThisForNodeIfNecessary(node);\n emitSystemModuleBody(node, dependencyGroups, startIndex);\n decreaseIndent();\n writeLine();\n write(\"});\");\n }\n function getAMDDependencyNames(node, includeNonAmdDependencies) {\n // names of modules with corresponding parameter in the factory function\n var aliasedModuleNames = [];\n // names of modules with no corresponding parameters in factory function\n var unaliasedModuleNames = [];\n var importAliasNames = []; // names of the parameters in the factory function; these\n // parameters need to match the indexes of the corresponding\n // module names in aliasedModuleNames.\n // Fill in amd-dependency tags\n for (var _a = 0, _b = node.amdDependencies; _a < _b.length; _a++) {\n var amdDependency = _b[_a];\n if (amdDependency.name) {\n aliasedModuleNames.push(\"\\\"\" + amdDependency.path + \"\\\"\");\n importAliasNames.push(amdDependency.name);\n }\n else {\n unaliasedModuleNames.push(\"\\\"\" + amdDependency.path + \"\\\"\");\n }\n }\n for (var _c = 0; _c < externalImports.length; _c++) {\n var importNode = externalImports[_c];\n // Find the name of the external module\n var externalModuleName = getExternalModuleNameText(importNode);\n // Find the name of the module alias, if there is one\n var importAliasName = getLocalNameForExternalImport(importNode);\n if (includeNonAmdDependencies && importAliasName) {\n aliasedModuleNames.push(externalModuleName);\n importAliasNames.push(importAliasName);\n }\n else {\n unaliasedModuleNames.push(externalModuleName);\n }\n }\n return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };\n }\n function emitAMDDependencies(node, includeNonAmdDependencies) {\n // An AMD define function has the following shape:\n // define(id?, dependencies?, factory);\n //\n // This has the shape of\n // define(name, [\"module1\", \"module2\"], function (module1Alias) {\n // The location of the alias in the parameter list in the factory function needs to\n // match the position of the module name in the dependency list.\n //\n // To ensure this is true in cases of modules with no aliases, e.g.:\n // `import \"module\"` or ``\n // we need to add modules without alias names to the end of the dependencies list\n var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies);\n emitAMDDependencyList(dependencyNames);\n write(\", \");\n emitAMDFactoryHeader(dependencyNames);\n }\n function emitAMDDependencyList(_a) {\n var aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames;\n write(\"[\\\"require\\\", \\\"exports\\\"\");\n if (aliasedModuleNames.length) {\n write(\", \");\n write(aliasedModuleNames.join(\", \"));\n }\n if (unaliasedModuleNames.length) {\n write(\", \");\n write(unaliasedModuleNames.join(\", \"));\n }\n write(\"]\");\n }\n function emitAMDFactoryHeader(_a) {\n var importAliasNames = _a.importAliasNames;\n write(\"function (require, exports\");\n if (importAliasNames.length) {\n write(\", \");\n write(importAliasNames.join(\", \"));\n }\n write(\") {\");\n }\n function emitAMDModule(node) {\n emitEmitHelpers(node);\n collectExternalModuleInfo(node);\n writeLine();\n write(\"define(\");\n if (node.moduleName) {\n write(\"\\\"\" + node.moduleName + \"\\\", \");\n }\n emitAMDDependencies(node, /*includeNonAmdDependencies*/ true);\n increaseIndent();\n var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);\n emitExportStarHelper();\n emitCaptureThisForNodeIfNecessary(node);\n emitLinesStartingAt(node.statements, startIndex);\n emitTempDeclarations(/*newLine*/ true);\n emitExportEquals(/*emitAsReturn*/ true);\n decreaseIndent();\n writeLine();\n write(\"});\");\n }\n function emitCommonJSModule(node) {\n var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);\n emitEmitHelpers(node);\n collectExternalModuleInfo(node);\n emitExportStarHelper();\n emitCaptureThisForNodeIfNecessary(node);\n emitLinesStartingAt(node.statements, startIndex);\n emitTempDeclarations(/*newLine*/ true);\n emitExportEquals(/*emitAsReturn*/ false);\n }\n function emitUMDModule(node) {\n emitEmitHelpers(node);\n collectExternalModuleInfo(node);\n var dependencyNames = getAMDDependencyNames(node, /*includeNonAmdDependencies*/ false);\n // Module is detected first to support Browserify users that load into a browser with an AMD loader\n writeLines(\"(function (factory) {\\n if (typeof module === 'object' && typeof module.exports === 'object') {\\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\\n }\\n else if (typeof define === 'function' && define.amd) {\\n define(\");\n emitAMDDependencyList(dependencyNames);\n write(\", factory);\");\n writeLines(\" }\\n})(\");\n emitAMDFactoryHeader(dependencyNames);\n increaseIndent();\n var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);\n emitExportStarHelper();\n emitCaptureThisForNodeIfNecessary(node);\n emitLinesStartingAt(node.statements, startIndex);\n emitTempDeclarations(/*newLine*/ true);\n emitExportEquals(/*emitAsReturn*/ true);\n decreaseIndent();\n writeLine();\n write(\"});\");\n }\n function emitES6Module(node) {\n externalImports = undefined;\n exportSpecifiers = undefined;\n exportEquals = undefined;\n hasExportStars = false;\n var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);\n emitEmitHelpers(node);\n emitCaptureThisForNodeIfNecessary(node);\n emitLinesStartingAt(node.statements, startIndex);\n emitTempDeclarations(/*newLine*/ true);\n // Emit exportDefault if it exists will happen as part\n // or normal statement emit.\n }\n function emitExportEquals(emitAsReturn) {\n if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) {\n writeLine();\n emitStart(exportEquals);\n write(emitAsReturn ? \"return \" : \"module.exports = \");\n emit(exportEquals.expression);\n write(\";\");\n emitEnd(exportEquals);\n }\n }\n function emitJsxElement(node) {\n switch (compilerOptions.jsx) {\n case 2 /* React */:\n jsxEmitReact(node);\n break;\n case 1 /* Preserve */:\n // Fall back to preserve if None was specified (we'll error earlier)\n default:\n jsxEmitPreserve(node);\n break;\n }\n }\n function trimReactWhitespaceAndApplyEntities(node) {\n var result = undefined;\n var text = ts.getTextOfNode(node, /*includeTrivia*/ true);\n var firstNonWhitespace = 0;\n var lastNonWhitespace = -1;\n // JSX trims whitespace at the end and beginning of lines, except that the\n // start/end of a tag is considered a start/end of a line only if that line is\n // on the same line as the closing tag. See examples in tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx\n for (var i = 0; i < text.length; i++) {\n var c = text.charCodeAt(i);\n if (ts.isLineBreak(c)) {\n if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) {\n var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1);\n result = (result ? result + \"\\\" + ' ' + \\\"\" : \"\") + ts.escapeString(part);\n }\n firstNonWhitespace = -1;\n }\n else if (!ts.isWhiteSpace(c)) {\n lastNonWhitespace = i;\n if (firstNonWhitespace === -1) {\n firstNonWhitespace = i;\n }\n }\n }\n if (firstNonWhitespace !== -1) {\n var part = text.substr(firstNonWhitespace);\n result = (result ? result + \"\\\" + ' ' + \\\"\" : \"\") + ts.escapeString(part);\n }\n if (result) {\n // Replace entities like  \n result = result.replace(/&(\\w+);/g, function (s, m) {\n if (entities[m] !== undefined) {\n return String.fromCharCode(entities[m]);\n }\n else {\n return s;\n }\n });\n }\n return result;\n }\n function getTextToEmit(node) {\n switch (compilerOptions.jsx) {\n case 2 /* React */:\n var text = trimReactWhitespaceAndApplyEntities(node);\n if (text === undefined || text.length === 0) {\n return undefined;\n }\n else {\n return text;\n }\n case 1 /* Preserve */:\n default:\n return ts.getTextOfNode(node, /*includeTrivia*/ true);\n }\n }\n function emitJsxText(node) {\n switch (compilerOptions.jsx) {\n case 2 /* React */:\n write(\"\\\"\");\n write(trimReactWhitespaceAndApplyEntities(node));\n write(\"\\\"\");\n break;\n case 1 /* Preserve */:\n default:\n writer.writeLiteral(ts.getTextOfNode(node, /*includeTrivia*/ true));\n break;\n }\n }\n function emitJsxExpression(node) {\n if (node.expression) {\n switch (compilerOptions.jsx) {\n case 1 /* Preserve */:\n default:\n write(\"{\");\n emit(node.expression);\n write(\"}\");\n break;\n case 2 /* React */:\n emit(node.expression);\n break;\n }\n }\n }\n function emitDirectivePrologues(statements, startWithNewLine) {\n for (var i = 0; i < statements.length; ++i) {\n if (ts.isPrologueDirective(statements[i])) {\n if (startWithNewLine || i > 0) {\n writeLine();\n }\n emit(statements[i]);\n }\n else {\n // return index of the first non prologue directive\n return i;\n }\n }\n return statements.length;\n }\n function writeLines(text) {\n var lines = text.split(/\\r\\n|\\r|\\n/g);\n for (var i = 0; i < lines.length; ++i) {\n var line = lines[i];\n if (line.length) {\n writeLine();\n write(line);\n }\n }\n }\n function emitEmitHelpers(node) {\n // Only emit helpers if the user did not say otherwise.\n if (!compilerOptions.noEmitHelpers) {\n // Only Emit __extends function when target ES5.\n // For target ES6 and above, we can emit classDeclaration as is.\n if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8 /* EmitExtends */)) {\n writeLines(extendsHelper);\n extendsEmitted = true;\n }\n if (!decorateEmitted && resolver.getNodeCheckFlags(node) & 16 /* EmitDecorate */) {\n writeLines(decorateHelper);\n if (compilerOptions.emitDecoratorMetadata) {\n writeLines(metadataHelper);\n }\n decorateEmitted = true;\n }\n if (!paramEmitted && resolver.getNodeCheckFlags(node) & 32 /* EmitParam */) {\n writeLines(paramHelper);\n paramEmitted = true;\n }\n if (!awaiterEmitted && resolver.getNodeCheckFlags(node) & 64 /* EmitAwaiter */) {\n writeLines(awaiterHelper);\n awaiterEmitted = true;\n }\n }\n }\n function emitSourceFileNode(node) {\n // Start new file on new line\n writeLine();\n emitShebang();\n emitDetachedComments(node);\n if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {\n var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */];\n emitModule(node);\n }\n else {\n // emit prologue directives prior to __extends\n var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);\n externalImports = undefined;\n exportSpecifiers = undefined;\n exportEquals = undefined;\n hasExportStars = false;\n emitEmitHelpers(node);\n emitCaptureThisForNodeIfNecessary(node);\n emitLinesStartingAt(node.statements, startIndex);\n emitTempDeclarations(/*newLine*/ true);\n }\n emitLeadingComments(node.endOfFileToken);\n }\n function emitNodeWithCommentsAndWithoutSourcemap(node) {\n emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap);\n }\n function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) {\n if (node) {\n if (node.flags & 2 /* Ambient */) {\n return emitCommentsOnNotEmittedNode(node);\n }\n if (isSpecializedCommentHandling(node)) {\n // This is the node that will handle its own comments and sourcemap\n return emitNodeWithoutSourceMap(node);\n }\n var emitComments_1 = shouldEmitLeadingAndTrailingComments(node);\n if (emitComments_1) {\n emitLeadingComments(node);\n }\n emitNodeConsideringSourcemap(node);\n if (emitComments_1) {\n emitTrailingComments(node);\n }\n }\n }\n function emitNodeWithoutSourceMap(node) {\n if (node) {\n emitJavaScriptWorker(node);\n }\n }\n function isSpecializedCommentHandling(node) {\n switch (node.kind) {\n // All of these entities are emitted in a specialized fashion. As such, we allow\n // the specialized methods for each to handle the comments on the nodes.\n case 215 /* InterfaceDeclaration */:\n case 213 /* FunctionDeclaration */:\n case 222 /* ImportDeclaration */:\n case 221 /* ImportEqualsDeclaration */:\n case 216 /* TypeAliasDeclaration */:\n case 227 /* ExportAssignment */:\n return true;\n }\n }\n function shouldEmitLeadingAndTrailingComments(node) {\n switch (node.kind) {\n case 193 /* VariableStatement */:\n return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node);\n case 218 /* ModuleDeclaration */:\n // Only emit the leading/trailing comments for a module if we're actually\n // emitting the module as well.\n return shouldEmitModuleDeclaration(node);\n case 217 /* EnumDeclaration */:\n // Only emit the leading/trailing comments for an enum if we're actually\n // emitting the module as well.\n return shouldEmitEnumDeclaration(node);\n }\n // If the node is emitted in specialized fashion, dont emit comments as this node will handle\n // emitting comments when emitting itself\n ts.Debug.assert(!isSpecializedCommentHandling(node));\n // If this is the expression body of an arrow function that we're down-leveling,\n // then we don't want to emit comments when we emit the body. It will have already\n // been taken care of when we emitted the 'return' statement for the function\n // expression body.\n if (node.kind !== 192 /* Block */ &&\n node.parent &&\n node.parent.kind === 174 /* ArrowFunction */ &&\n node.parent.body === node &&\n compilerOptions.target <= 1 /* ES5 */) {\n return false;\n }\n // Emit comments for everything else.\n return true;\n }\n function emitJavaScriptWorker(node) {\n // Check if the node can be emitted regardless of the ScriptTarget\n switch (node.kind) {\n case 69 /* Identifier */:\n return emitIdentifier(node);\n case 138 /* Parameter */:\n return emitParameter(node);\n case 143 /* MethodDeclaration */:\n case 142 /* MethodSignature */:\n return emitMethod(node);\n case 145 /* GetAccessor */:\n case 146 /* SetAccessor */:\n return emitAccessor(node);\n case 97 /* ThisKeyword */:\n return emitThis(node);\n case 95 /* SuperKeyword */:\n return emitSuper(node);\n case 93 /* NullKeyword */:\n return write(\"null\");\n case 99 /* TrueKeyword */:\n return write(\"true\");\n case 84 /* FalseKeyword */:\n return write(\"false\");\n case 8 /* NumericLiteral */:\n case 9 /* StringLiteral */:\n case 10 /* RegularExpressionLiteral */:\n case 11 /* NoSubstitutionTemplateLiteral */:\n case 12 /* TemplateHead */:\n case 13 /* TemplateMiddle */:\n case 14 /* TemplateTail */:\n return emitLiteral(node);\n case 183 /* TemplateExpression */:\n return emitTemplateExpression(node);\n case 190 /* TemplateSpan */:\n return emitTemplateSpan(node);\n case 233 /* JsxElement */:\n case 234 /* JsxSelfClosingElement */:\n return emitJsxElement(node);\n case 236 /* JsxText */:\n return emitJsxText(node);\n case 240 /* JsxExpression */:\n return emitJsxExpression(node);\n case 135 /* QualifiedName */:\n return emitQualifiedName(node);\n case 161 /* ObjectBindingPattern */:\n return emitObjectBindingPattern(node);\n case 162 /* ArrayBindingPattern */:\n return emitArrayBindingPattern(node);\n case 163 /* BindingElement */:\n return emitBindingElement(node);\n case 164 /* ArrayLiteralExpression */:\n return emitArrayLiteral(node);\n case 165 /* ObjectLiteralExpression */:\n return emitObjectLiteral(node);\n case 245 /* PropertyAssignment */:\n return emitPropertyAssignment(node);\n case 246 /* ShorthandPropertyAssignment */:\n return emitShorthandPropertyAssignment(node);\n case 136 /* ComputedPropertyName */:\n return emitComputedPropertyName(node);\n case 166 /* PropertyAccessExpression */:\n return emitPropertyAccess(node);\n case 167 /* ElementAccessExpression */:\n return emitIndexedAccess(node);\n case 168 /* CallExpression */:\n return emitCallExpression(node);\n case 169 /* NewExpression */:\n return emitNewExpression(node);\n case 170 /* TaggedTemplateExpression */:\n return emitTaggedTemplateExpression(node);\n case 171 /* TypeAssertionExpression */:\n return emit(node.expression);\n case 189 /* AsExpression */:\n return emit(node.expression);\n case 172 /* ParenthesizedExpression */:\n return emitParenExpression(node);\n case 213 /* FunctionDeclaration */:\n case 173 /* FunctionExpression */:\n case 174 /* ArrowFunction */:\n return emitFunctionDeclaration(node);\n case 175 /* DeleteExpression */:\n return emitDeleteExpression(node);\n case 176 /* TypeOfExpression */:\n return emitTypeOfExpression(node);\n case 177 /* VoidExpression */:\n return emitVoidExpression(node);\n case 178 /* AwaitExpression */:\n return emitAwaitExpression(node);\n case 179 /* PrefixUnaryExpression */:\n return emitPrefixUnaryExpression(node);\n case 180 /* PostfixUnaryExpression */:\n return emitPostfixUnaryExpression(node);\n case 181 /* BinaryExpression */:\n return emitBinaryExpression(node);\n case 182 /* ConditionalExpression */:\n return emitConditionalExpression(node);\n case 185 /* SpreadElementExpression */:\n return emitSpreadElementExpression(node);\n case 184 /* YieldExpression */:\n return emitYieldExpression(node);\n case 187 /* OmittedExpression */:\n return;\n case 192 /* Block */:\n case 219 /* ModuleBlock */:\n return emitBlock(node);\n case 193 /* VariableStatement */:\n return emitVariableStatement(node);\n case 194 /* EmptyStatement */:\n return write(\";\");\n case 195 /* ExpressionStatement */:\n return emitExpressionStatement(node);\n case 196 /* IfStatement */:\n return emitIfStatement(node);\n case 197 /* DoStatement */:\n return emitDoStatement(node);\n case 198 /* WhileStatement */:\n return emitWhileStatement(node);\n case 199 /* ForStatement */:\n return emitForStatement(node);\n case 201 /* ForOfStatement */:\n case 200 /* ForInStatement */:\n return emitForInOrForOfStatement(node);\n case 202 /* ContinueStatement */:\n case 203 /* BreakStatement */:\n return emitBreakOrContinueStatement(node);\n case 204 /* ReturnStatement */:\n return emitReturnStatement(node);\n case 205 /* WithStatement */:\n return emitWithStatement(node);\n case 206 /* SwitchStatement */:\n return emitSwitchStatement(node);\n case 241 /* CaseClause */:\n case 242 /* DefaultClause */:\n return emitCaseOrDefaultClause(node);\n case 207 /* LabeledStatement */:\n return emitLabelledStatement(node);\n case 208 /* ThrowStatement */:\n return emitThrowStatement(node);\n case 209 /* TryStatement */:\n return emitTryStatement(node);\n case 244 /* CatchClause */:\n return emitCatchClause(node);\n case 210 /* DebuggerStatement */:\n return emitDebuggerStatement(node);\n case 211 /* VariableDeclaration */:\n return emitVariableDeclaration(node);\n case 186 /* ClassExpression */:\n return emitClassExpression(node);\n case 214 /* ClassDeclaration */:\n return emitClassDeclaration(node);\n case 215 /* InterfaceDeclaration */:\n return emitInterfaceDeclaration(node);\n case 217 /* EnumDeclaration */:\n return emitEnumDeclaration(node);\n case 247 /* EnumMember */:\n return emitEnumMember(node);\n case 218 /* ModuleDeclaration */:\n return emitModuleDeclaration(node);\n case 222 /* ImportDeclaration */:\n return emitImportDeclaration(node);\n case 221 /* ImportEqualsDeclaration */:\n return emitImportEqualsDeclaration(node);\n case 228 /* ExportDeclaration */:\n return emitExportDeclaration(node);\n case 227 /* ExportAssignment */:\n return emitExportAssignment(node);\n case 248 /* SourceFile */:\n return emitSourceFileNode(node);\n }\n }\n function hasDetachedComments(pos) {\n return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos;\n }\n function getLeadingCommentsWithoutDetachedComments() {\n // get the leading comments from detachedPos\n var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);\n if (detachedCommentsInfo.length - 1) {\n detachedCommentsInfo.pop();\n }\n else {\n detachedCommentsInfo = undefined;\n }\n return leadingComments;\n }\n function isPinnedComments(comment) {\n return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&\n currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */;\n }\n /**\n * Determine if the given comment is a triple-slash\n *\n * @return true if the comment is a triple-slash comment else false\n **/\n function isTripleSlashComment(comment) {\n // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text\n // so that we don't end up computing comment string and doing match for all // comments\n if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 /* slash */ &&\n comment.pos + 2 < comment.end &&\n currentSourceFile.text.charCodeAt(comment.pos + 2) === 47 /* slash */) {\n var textSubStr = currentSourceFile.text.substring(comment.pos, comment.end);\n return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||\n textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ?\n true : false;\n }\n return false;\n }\n function getLeadingCommentsToEmit(node) {\n // Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments\n if (node.parent) {\n if (node.parent.kind === 248 /* SourceFile */ || node.pos !== node.parent.pos) {\n if (hasDetachedComments(node.pos)) {\n // get comments without detached comments\n return getLeadingCommentsWithoutDetachedComments();\n }\n else {\n // get the leading comments from the node\n return ts.getLeadingCommentRangesOfNode(node, currentSourceFile);\n }\n }\n }\n }\n function getTrailingCommentsToEmit(node) {\n // Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments\n if (node.parent) {\n if (node.parent.kind === 248 /* SourceFile */ || node.end !== node.parent.end) {\n return ts.getTrailingCommentRanges(currentSourceFile.text, node.end);\n }\n }\n }\n /**\n * Emit comments associated with node that will not be emitted into JS file\n */\n function emitCommentsOnNotEmittedNode(node) {\n emitLeadingCommentsWorker(node, /*isEmittedNode:*/ false);\n }\n function emitLeadingComments(node) {\n return emitLeadingCommentsWorker(node, /*isEmittedNode:*/ true);\n }\n function emitLeadingCommentsWorker(node, isEmittedNode) {\n if (compilerOptions.removeComments) {\n return;\n }\n var leadingComments;\n if (isEmittedNode) {\n leadingComments = getLeadingCommentsToEmit(node);\n }\n else {\n // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,\n // unless it is a triple slash comment at the top of the file.\n // For Example:\n // /// \n // declare var x;\n // /// \n // interface F {}\n // The first /// will NOT be removed while the second one will be removed eventhough both node will not be emitted\n if (node.pos === 0) {\n leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment);\n }\n }\n ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);\n // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space\n ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment);\n }\n function emitTrailingComments(node) {\n if (compilerOptions.removeComments) {\n return;\n }\n // Emit the trailing comments only if the parent's end doesn't match\n var trailingComments = getTrailingCommentsToEmit(node);\n // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/\n ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);\n }\n /**\n * Emit trailing comments at the position. The term trailing comment is used here to describe following comment:\n * x, /comment1/ y\n * ^ => pos; the function will emit \"comment1\" in the emitJS\n */\n function emitTrailingCommentsOfPosition(pos) {\n if (compilerOptions.removeComments) {\n return;\n }\n var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, pos);\n // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/\n ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment);\n }\n function emitLeadingCommentsOfPositionWorker(pos) {\n if (compilerOptions.removeComments) {\n return;\n }\n var leadingComments;\n if (hasDetachedComments(pos)) {\n // get comments without detached comments\n leadingComments = getLeadingCommentsWithoutDetachedComments();\n }\n else {\n // get the leading comments from the node\n leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos);\n }\n ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments);\n // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space\n ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment);\n }\n function emitDetachedComments(node) {\n var leadingComments;\n if (compilerOptions.removeComments) {\n // removeComments is true, only reserve pinned comment at the top of file\n // For example:\n // /*! Pinned Comment */\n //\n // var x = 10;\n if (node.pos === 0) {\n leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComments);\n }\n }\n else {\n // removeComments is false, just get detached as normal and bypass the process to filter comment\n leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos);\n }\n if (leadingComments) {\n var detachedComments = [];\n var lastComment;\n ts.forEach(leadingComments, function (comment) {\n if (lastComment) {\n var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, lastComment.end);\n var commentLine = ts.getLineOfLocalPosition(currentSourceFile, comment.pos);\n if (commentLine >= lastCommentLine + 2) {\n // There was a blank line between the last comment and this comment. This\n // comment is not part of the copyright comments. Return what we have so\n // far.\n return detachedComments;\n }\n }\n detachedComments.push(comment);\n lastComment = comment;\n });\n if (detachedComments.length) {\n // All comments look like they could have been part of the copyright header. Make\n // sure there is at least one blank line between it and the node. If not, it's not\n // a copyright header.\n var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end);\n var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos));\n if (nodeLine >= lastCommentLine + 2) {\n // Valid detachedComments\n ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);\n ts.emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment);\n var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end };\n if (detachedCommentsInfo) {\n detachedCommentsInfo.push(currentDetachedCommentInfo);\n }\n else {\n detachedCommentsInfo = [currentDetachedCommentInfo];\n }\n }\n }\n }\n }\n function emitShebang() {\n var shebang = ts.getShebang(currentSourceFile.text);\n if (shebang) {\n write(shebang);\n }\n }\n var _a;\n }\n function emitFile(jsFilePath, sourceFile) {\n emitJavaScript(jsFilePath, sourceFile);\n if (compilerOptions.declaration) {\n ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics);\n }\n }\n }", "language": "javascript", "code": "function emitFiles(resolver, host, targetSourceFile) {\n // emit output for the __extends helper function\n var extendsHelper = \"\\nvar __extends = (this && this.__extends) || function (d, b) {\\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\\n function __() { this.constructor = d; }\\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\\n};\";\n // emit output for the __decorate helper function\n var decorateHelper = \"\\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\\n if (typeof Reflect === \\\"object\\\" && typeof Reflect.decorate === \\\"function\\\") r = Reflect.decorate(decorators, target, key, desc);\\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\\n return c > 3 && r && Object.defineProperty(target, key, r), r;\\n};\";\n // emit output for the __metadata helper function\n var metadataHelper = \"\\nvar __metadata = (this && this.__metadata) || function (k, v) {\\n if (typeof Reflect === \\\"object\\\" && typeof Reflect.metadata === \\\"function\\\") return Reflect.metadata(k, v);\\n};\";\n // emit output for the __param helper function\n var paramHelper = \"\\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\\n return function (target, key) { decorator(target, key, paramIndex); }\\n};\";\n var awaiterHelper = \"\\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {\\n return new Promise(function (resolve, reject) {\\n generator = generator.call(thisArg, _arguments);\\n function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }\\n function onfulfill(value) { try { step(\\\"next\\\", value); } catch (e) { reject(e); } }\\n function onreject(value) { try { step(\\\"throw\\\", value); } catch (e) { reject(e); } }\\n function step(verb, value) {\\n var result = generator[verb](value);\\n result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);\\n }\\n step(\\\"next\\\", void 0);\\n });\\n};\";\n var compilerOptions = host.getCompilerOptions();\n var languageVersion = compilerOptions.target || 0 /* ES3 */;\n var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */;\n var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined;\n var diagnostics = [];\n var newLine = host.getNewLine();\n var jsxDesugaring = host.getCompilerOptions().jsx !== 1 /* Preserve */;\n var shouldEmitJsx = function (s) { return (s.languageVariant === 1 /* JSX */ && !jsxDesugaring); };\n if (targetSourceFile === undefined) {\n ts.forEach(host.getSourceFiles(), function (sourceFile) {\n if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) {\n var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? \".jsx\" : \".js\");\n emitFile(jsFilePath, sourceFile);\n }\n });\n if (compilerOptions.outFile || compilerOptions.out) {\n emitFile(compilerOptions.outFile || compilerOptions.out);\n }\n }\n else {\n // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service)\n if (ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions)) {\n var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? \".jsx\" : \".js\");\n emitFile(jsFilePath, targetSourceFile);\n }\n else if (!ts.isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) {\n emitFile(compilerOptions.outFile || compilerOptions.out);\n }\n }\n // Sort and make the unique list of diagnostics\n diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics);\n return {\n emitSkipped: false,\n diagnostics: diagnostics,\n sourceMaps: sourceMapDataList\n };\n function isUniqueLocalName(name, container) {\n for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) {\n if (node.locals && ts.hasProperty(node.locals, name)) {\n // We conservatively include alias symbols to cover cases where they're emitted as locals\n if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) {\n return false;\n }\n }\n }\n return true;\n }\n function emitJavaScript(jsFilePath, root) {\n var writer = ts.createTextWriter(newLine);\n var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent;\n var currentSourceFile;\n // name of an exporter function if file is a System external module\n // System.register([...], function () {...})\n // exporting in System modules looks like:\n // export var x; ... x = 1\n // =>\n // var x;... exporter(\"x\", x = 1)\n var exportFunctionForFile;\n var generatedNameSet = {};\n var nodeToGeneratedName = [];\n var computedPropertyNamesToGeneratedNames;\n var extendsEmitted = false;\n var decorateEmitted = false;\n var paramEmitted = false;\n var awaiterEmitted = false;\n var tempFlags = 0;\n var tempVariables;\n var tempParameters;\n var externalImports;\n var exportSpecifiers;\n var exportEquals;\n var hasExportStars;\n /** Write emitted output to disk */\n var writeEmittedFiles = writeJavaScriptFile;\n var detachedCommentsInfo;\n var writeComment = ts.writeCommentRange;\n /** Emit a node */\n var emit = emitNodeWithCommentsAndWithoutSourcemap;\n /** Called just before starting emit of a node */\n var emitStart = function (node) { };\n /** Called once the emit of the node is done */\n var emitEnd = function (node) { };\n /** Emit the text for the given token that comes after startPos\n * This by default writes the text provided with the given tokenKind\n * but if optional emitFn callback is provided the text is emitted using the callback instead of default text\n * @param tokenKind the kind of the token to search and emit\n * @param startPos the position in the source to start searching for the token\n * @param emitFn if given will be invoked to emit the text instead of actual token emit */\n var emitToken = emitTokenText;\n /** Called to before starting the lexical scopes as in function/class in the emitted code because of node\n * @param scopeDeclaration node that starts the lexical scope\n * @param scopeName Optional name of this scope instead of deducing one from the declaration node */\n var scopeEmitStart = function (scopeDeclaration, scopeName) { };\n /** Called after coming out of the scope */\n var scopeEmitEnd = function () { };\n /** Sourcemap data that will get encoded */\n var sourceMapData;\n /** If removeComments is true, no leading-comments needed to be emitted **/\n var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker;\n var moduleEmitDelegates = (_a = {},\n _a[5 /* ES6 */] = emitES6Module,\n _a[2 /* AMD */] = emitAMDModule,\n _a[4 /* System */] = emitSystemModule,\n _a[3 /* UMD */] = emitUMDModule,\n _a[1 /* CommonJS */] = emitCommonJSModule,\n _a\n );\n if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {\n initializeEmitterWithSourceMaps();\n }\n if (root) {\n // Do not call emit directly. It does not set the currentSourceFile.\n emitSourceFile(root);\n }\n else {\n ts.forEach(host.getSourceFiles(), function (sourceFile) {\n if (!isExternalModuleOrDeclarationFile(sourceFile)) {\n emitSourceFile(sourceFile);\n }\n });\n }\n writeLine();\n writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM);\n return;\n function emitSourceFile(sourceFile) {\n currentSourceFile = sourceFile;\n exportFunctionForFile = undefined;\n emit(sourceFile);\n }\n function isUniqueName(name) {\n return !resolver.hasGlobalName(name) &&\n !ts.hasProperty(currentSourceFile.identifiers, name) &&\n !ts.hasProperty(generatedNameSet, name);\n }\n // Return the next available name in the pattern _a ... _z, _0, _1, ...\n // TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.\n // Note that names generated by makeTempVariableName and makeUniqueName will never conflict.\n function makeTempVariableName(flags) {\n if (flags && !(tempFlags & flags)) {\n var name_19 = flags === 268435456 /* _i */ ? \"_i\" : \"_n\";\n if (isUniqueName(name_19)) {\n tempFlags |= flags;\n return name_19;\n }\n }\n while (true) {\n var count = tempFlags & 268435455 /* CountMask */;\n tempFlags++;\n // Skip over 'i' and 'n'\n if (count !== 8 && count !== 13) {\n var name_20 = count < 26 ? \"_\" + String.fromCharCode(97 /* a */ + count) : \"_\" + (count - 26);\n if (isUniqueName(name_20)) {\n return name_20;\n }\n }\n }\n }\n // Generate a name that is unique within the current file and doesn't conflict with any names\n // in global scope. The name is formed by adding an '_n' suffix to the specified base name,\n // where n is a positive integer. Note that names generated by makeTempVariableName and\n // makeUniqueName are guaranteed to never conflict.\n function makeUniqueName(baseName) {\n // Find the first unique 'name_n', where n is a positive number\n if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {\n baseName += \"_\";\n }\n var i = 1;\n while (true) {\n var generatedName = baseName + i;\n if (isUniqueName(generatedName)) {\n return generatedNameSet[generatedName] = generatedName;\n }\n i++;\n }\n }\n function generateNameForModuleOrEnum(node) {\n var name = node.name.text;\n // Use module/enum name itself if it is unique, otherwise make a unique variation\n return isUniqueLocalName(name, node) ? name : makeUniqueName(name);\n }\n function generateNameForImportOrExportDeclaration(node) {\n var expr = ts.getExternalModuleName(node);\n var baseName = expr.kind === 9 /* StringLiteral */ ?\n ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : \"module\";\n return makeUniqueName(baseName);\n }\n function generateNameForExportDefault() {\n return makeUniqueName(\"default\");\n }\n function generateNameForClassExpression() {\n return makeUniqueName(\"class\");\n }\n function generateNameForNode(node) {\n switch (node.kind) {\n case 69 /* Identifier */:\n return makeUniqueName(node.text);\n case 218 /* ModuleDeclaration */:\n case 217 /* EnumDeclaration */:\n return generateNameForModuleOrEnum(node);\n case 222 /* ImportDeclaration */:\n case 228 /* ExportDeclaration */:\n return generateNameForImportOrExportDeclaration(node);\n case 213 /* FunctionDeclaration */:\n case 214 /* ClassDeclaration */:\n case 227 /* ExportAssignment */:\n return generateNameForExportDefault();\n case 186 /* ClassExpression */:\n return generateNameForClassExpression();\n }\n }\n function getGeneratedNameForNode(node) {\n var id = ts.getNodeId(node);\n return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node)));\n }\n function initializeEmitterWithSourceMaps() {\n var sourceMapDir; // The directory in which sourcemap will be\n // Current source map file and its index in the sources list\n var sourceMapSourceIndex = -1;\n // Names and its index map\n var sourceMapNameIndexMap = {};\n var sourceMapNameIndices = [];\n function getSourceMapNameIndex() {\n return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1;\n }\n // Last recorded and encoded spans\n var lastRecordedSourceMapSpan;\n var lastEncodedSourceMapSpan = {\n emittedLine: 1,\n emittedColumn: 1,\n sourceLine: 1,\n sourceColumn: 1,\n sourceIndex: 0\n };\n var lastEncodedNameIndex = 0;\n // Encoding for sourcemap span\n function encodeLastRecordedSourceMapSpan() {\n if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) {\n return;\n }\n var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn;\n // Line/Comma delimiters\n if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) {\n // Emit comma to separate the entry\n if (sourceMapData.sourceMapMappings) {\n sourceMapData.sourceMapMappings += \",\";\n }\n }\n else {\n // Emit line delimiters\n for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) {\n sourceMapData.sourceMapMappings += \";\";\n }\n prevEncodedEmittedColumn = 1;\n }\n // 1. Relative Column 0 based\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn);\n // 2. Relative sourceIndex\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex);\n // 3. Relative sourceLine 0 based\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine);\n // 4. Relative sourceColumn 0 based\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn);\n // 5. Relative namePosition 0 based\n if (lastRecordedSourceMapSpan.nameIndex >= 0) {\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex);\n lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex;\n }\n lastEncodedSourceMapSpan = lastRecordedSourceMapSpan;\n sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan);\n function base64VLQFormatEncode(inValue) {\n function base64FormatEncode(inValue) {\n if (inValue < 64) {\n return \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt(inValue);\n }\n throw TypeError(inValue + \": not a 64 based value\");\n }\n // Add a new least significant bit that has the sign of the value.\n // if negative number the least significant bit that gets added to the number has value 1\n // else least significant bit value that gets added is 0\n // eg. -1 changes to binary : 01 [1] => 3\n // +1 changes to binary : 01 [0] => 2\n if (inValue < 0) {\n inValue = ((-inValue) << 1) + 1;\n }\n else {\n inValue = inValue << 1;\n }\n // Encode 5 bits at a time starting from least significant bits\n var encodedStr = \"\";\n do {\n var currentDigit = inValue & 31; // 11111\n inValue = inValue >> 5;\n if (inValue > 0) {\n // There are still more digits to decode, set the msb (6th bit)\n currentDigit = currentDigit | 32;\n }\n encodedStr = encodedStr + base64FormatEncode(currentDigit);\n } while (inValue > 0);\n return encodedStr;\n }\n }\n function recordSourceMapSpan(pos) {\n var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos);\n // Convert the location to be one-based.\n sourceLinePos.line++;\n sourceLinePos.character++;\n var emittedLine = writer.getLine();\n var emittedColumn = writer.getColumn();\n // If this location wasn't recorded or the location in source is going backwards, record the span\n if (!lastRecordedSourceMapSpan ||\n lastRecordedSourceMapSpan.emittedLine !== emittedLine ||\n lastRecordedSourceMapSpan.emittedColumn !== emittedColumn ||\n (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex &&\n (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line ||\n (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) {\n // Encode the last recordedSpan before assigning new\n encodeLastRecordedSourceMapSpan();\n // New span\n lastRecordedSourceMapSpan = {\n emittedLine: emittedLine,\n emittedColumn: emittedColumn,\n sourceLine: sourceLinePos.line,\n sourceColumn: sourceLinePos.character,\n nameIndex: getSourceMapNameIndex(),\n sourceIndex: sourceMapSourceIndex\n };\n }\n else {\n // Take the new pos instead since there is no change in emittedLine and column since last location\n lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line;\n lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character;\n lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex;\n }\n }\n function recordEmitNodeStartSpan(node) {\n // Get the token pos after skipping to the token (ignoring the leading trivia)\n recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos));\n }\n function recordEmitNodeEndSpan(node) {\n recordSourceMapSpan(node.end);\n }\n function writeTextWithSpanRecord(tokenKind, startPos, emitFn) {\n var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos);\n recordSourceMapSpan(tokenStartPos);\n var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn);\n recordSourceMapSpan(tokenEndPos);\n return tokenEndPos;\n }\n function recordNewSourceFileStart(node) {\n // Add the file to tsFilePaths\n // If sourceroot option: Use the relative path corresponding to the common directory path\n // otherwise source locations relative to map file location\n var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;\n sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, host.getCurrentDirectory(), host.getCanonicalFileName,\n /*isAbsolutePathAnUrl*/ true));\n sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1;\n // The one that can be used from program to get the actual source file\n sourceMapData.inputSourceFileNames.push(node.fileName);\n if (compilerOptions.inlineSources) {\n if (!sourceMapData.sourceMapSourcesContent) {\n sourceMapData.sourceMapSourcesContent = [];\n }\n sourceMapData.sourceMapSourcesContent.push(node.text);\n }\n }\n function recordScopeNameOfNode(node, scopeName) {\n function recordScopeNameIndex(scopeNameIndex) {\n sourceMapNameIndices.push(scopeNameIndex);\n }\n function recordScopeNameStart(scopeName) {\n var scopeNameIndex = -1;\n if (scopeName) {\n var parentIndex = getSourceMapNameIndex();\n if (parentIndex !== -1) {\n // Child scopes are always shown with a dot (even if they have no name),\n // unless it is a computed property. Then it is shown with brackets,\n // but the brackets are included in the name.\n var name_21 = node.name;\n if (!name_21 || name_21.kind !== 136 /* ComputedPropertyName */) {\n scopeName = \".\" + scopeName;\n }\n scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName;\n }\n scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName);\n if (scopeNameIndex === undefined) {\n scopeNameIndex = sourceMapData.sourceMapNames.length;\n sourceMapData.sourceMapNames.push(scopeName);\n sourceMapNameIndexMap[scopeName] = scopeNameIndex;\n }\n }\n recordScopeNameIndex(scopeNameIndex);\n }\n if (scopeName) {\n // The scope was already given a name use it\n recordScopeNameStart(scopeName);\n }\n else if (node.kind === 213 /* FunctionDeclaration */ ||\n node.kind === 173 /* FunctionExpression */ ||\n node.kind === 143 /* MethodDeclaration */ ||\n node.kind === 142 /* MethodSignature */ ||\n node.kind === 145 /* GetAccessor */ ||\n node.kind === 146 /* SetAccessor */ ||\n node.kind === 218 /* ModuleDeclaration */ ||\n node.kind === 214 /* ClassDeclaration */ ||\n node.kind === 217 /* EnumDeclaration */) {\n // Declaration and has associated name use it\n if (node.name) {\n var name_22 = node.name;\n // For computed property names, the text will include the brackets\n scopeName = name_22.kind === 136 /* ComputedPropertyName */\n ? ts.getTextOfNode(name_22)\n : node.name.text;\n }\n recordScopeNameStart(scopeName);\n }\n else {\n // Block just use the name from upper level scope\n recordScopeNameIndex(getSourceMapNameIndex());\n }\n }\n function recordScopeNameEnd() {\n sourceMapNameIndices.pop();\n }\n ;\n function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) {\n recordSourceMapSpan(comment.pos);\n ts.writeCommentRange(currentSourceFile, writer, comment, newLine);\n recordSourceMapSpan(comment.end);\n }\n function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) {\n if (typeof JSON !== \"undefined\") {\n var map_1 = {\n version: version,\n file: file,\n sourceRoot: sourceRoot,\n sources: sources,\n names: names,\n mappings: mappings\n };\n if (sourcesContent !== undefined) {\n map_1.sourcesContent = sourcesContent;\n }\n return JSON.stringify(map_1);\n }\n return \"{\\\"version\\\":\" + version + \",\\\"file\\\":\\\"\" + ts.escapeString(file) + \"\\\",\\\"sourceRoot\\\":\\\"\" + ts.escapeString(sourceRoot) + \"\\\",\\\"sources\\\":[\" + serializeStringArray(sources) + \"],\\\"names\\\":[\" + serializeStringArray(names) + \"],\\\"mappings\\\":\\\"\" + ts.escapeString(mappings) + \"\\\" \" + (sourcesContent !== undefined ? \",\\\"sourcesContent\\\":[\" + serializeStringArray(sourcesContent) + \"]\" : \"\") + \"}\";\n function serializeStringArray(list) {\n var output = \"\";\n for (var i = 0, n = list.length; i < n; i++) {\n if (i) {\n output += \",\";\n }\n output += \"\\\"\" + ts.escapeString(list[i]) + \"\\\"\";\n }\n return output;\n }\n }\n function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) {\n encodeLastRecordedSourceMapSpan();\n var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent);\n sourceMapDataList.push(sourceMapData);\n var sourceMapUrl;\n if (compilerOptions.inlineSourceMap) {\n // Encode the sourceMap into the sourceMap url\n var base64SourceMapText = ts.convertToBase64(sourceMapText);\n sourceMapUrl = \"//# sourceMappingURL=data:application/json;base64,\" + base64SourceMapText;\n }\n else {\n // Write source map file\n ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, /*writeByteOrderMark*/ false);\n sourceMapUrl = \"//# sourceMappingURL=\" + sourceMapData.jsSourceMappingURL;\n }\n // Write sourcemap url to the js file and write the js file\n writeJavaScriptFile(emitOutput + sourceMapUrl, writeByteOrderMark);\n }\n // Initialize source map data\n var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath));\n sourceMapData = {\n sourceMapFilePath: jsFilePath + \".map\",\n jsSourceMappingURL: sourceMapJsFile + \".map\",\n sourceMapFile: sourceMapJsFile,\n sourceMapSourceRoot: compilerOptions.sourceRoot || \"\",\n sourceMapSources: [],\n inputSourceFileNames: [],\n sourceMapNames: [],\n sourceMapMappings: \"\",\n sourceMapSourcesContent: undefined,\n sourceMapDecodedMappings: []\n };\n // Normalize source root and make sure it has trailing \"/\" so that it can be used to combine paths with the\n // relative paths of the sources list in the sourcemap\n sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot);\n if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) {\n sourceMapData.sourceMapSourceRoot += ts.directorySeparator;\n }\n if (compilerOptions.mapRoot) {\n sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot);\n if (root) {\n // For modules or multiple emit files the mapRoot will have directory structure like the sources\n // So if src\\a.ts and src\\lib\\b.ts are compiled together user would be moving the maps into mapRoot\\a.js.map and mapRoot\\lib\\b.js.map\n sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(root, host, sourceMapDir));\n }\n if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) {\n // The relative paths are relative to the common directory\n sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);\n sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), // get the relative sourceMapDir path based on jsFilePath\n ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap\n host.getCurrentDirectory(), host.getCanonicalFileName,\n /*isAbsolutePathAnUrl*/ true);\n }\n else {\n sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL);\n }\n }\n else {\n sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath));\n }\n function emitNodeWithSourceMap(node) {\n if (node) {\n if (ts.nodeIsSynthesized(node)) {\n return emitNodeWithoutSourceMap(node);\n }\n if (node.kind !== 248 /* SourceFile */) {\n recordEmitNodeStartSpan(node);\n emitNodeWithoutSourceMap(node);\n recordEmitNodeEndSpan(node);\n }\n else {\n recordNewSourceFileStart(node);\n emitNodeWithoutSourceMap(node);\n }\n }\n }\n function emitNodeWithCommentsAndWithSourcemap(node) {\n emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap);\n }\n writeEmittedFiles = writeJavaScriptAndSourceMapFile;\n emit = emitNodeWithCommentsAndWithSourcemap;\n emitStart = recordEmitNodeStartSpan;\n emitEnd = recordEmitNodeEndSpan;\n emitToken = writeTextWithSpanRecord;\n scopeEmitStart = recordScopeNameOfNode;\n scopeEmitEnd = recordScopeNameEnd;\n writeComment = writeCommentRangeWithMap;\n }\n function writeJavaScriptFile(emitOutput, writeByteOrderMark) {\n ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark);\n }\n // Create a temporary variable with a unique unused name.\n function createTempVariable(flags) {\n var result = ts.createSynthesizedNode(69 /* Identifier */);\n result.text = makeTempVariableName(flags);\n return result;\n }\n function recordTempDeclaration(name) {\n if (!tempVariables) {\n tempVariables = [];\n }\n tempVariables.push(name);\n }\n function createAndRecordTempVariable(flags) {\n var temp = createTempVariable(flags);\n recordTempDeclaration(temp);\n return temp;\n }\n function emitTempDeclarations(newLine) {\n if (tempVariables) {\n if (newLine) {\n writeLine();\n }\n else {\n write(\" \");\n }\n write(\"var \");\n emitCommaList(tempVariables);\n write(\";\");\n }\n }\n function emitTokenText(tokenKind, startPos, emitFn) {\n var tokenString = ts.tokenToString(tokenKind);\n if (emitFn) {\n emitFn();\n }\n else {\n write(tokenString);\n }\n return startPos + tokenString.length;\n }\n function emitOptional(prefix, node) {\n if (node) {\n write(prefix);\n emit(node);\n }\n }\n function emitParenthesizedIf(node, parenthesized) {\n if (parenthesized) {\n write(\"(\");\n }\n emit(node);\n if (parenthesized) {\n write(\")\");\n }\n }\n function emitTrailingCommaIfPresent(nodeList) {\n if (nodeList.hasTrailingComma) {\n write(\",\");\n }\n }\n function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) {\n ts.Debug.assert(nodes.length > 0);\n increaseIndent();\n if (nodeStartPositionsAreOnSameLine(parent, nodes[0])) {\n if (spacesBetweenBraces) {\n write(\" \");\n }\n }\n else {\n writeLine();\n }\n for (var i = 0, n = nodes.length; i < n; i++) {\n if (i) {\n if (nodeEndIsOnSameLineAsNodeStart(nodes[i - 1], nodes[i])) {\n write(\", \");\n }\n else {\n write(\",\");\n writeLine();\n }\n }\n emit(nodes[i]);\n }\n if (nodes.hasTrailingComma && allowTrailingComma) {\n write(\",\");\n }\n decreaseIndent();\n if (nodeEndPositionsAreOnSameLine(parent, ts.lastOrUndefined(nodes))) {\n if (spacesBetweenBraces) {\n write(\" \");\n }\n }\n else {\n writeLine();\n }\n }\n function emitList(nodes, start, count, multiLine, trailingComma, leadingComma, noTrailingNewLine, emitNode) {\n if (!emitNode) {\n emitNode = emit;\n }\n for (var i = 0; i < count; i++) {\n if (multiLine) {\n if (i || leadingComma) {\n write(\",\");\n }\n writeLine();\n }\n else {\n if (i || leadingComma) {\n write(\", \");\n }\n }\n var node = nodes[start + i];\n // This emitting is to make sure we emit following comment properly\n // ...(x, /*comment1*/ y)...\n // ^ => node.pos\n // \"comment1\" is not considered leading comment for \"y\" but rather\n // considered as trailing comment of the previous node.\n emitTrailingCommentsOfPosition(node.pos);\n emitNode(node);\n leadingComma = true;\n }\n if (trailingComma) {\n write(\",\");\n }\n if (multiLine && !noTrailingNewLine) {\n writeLine();\n }\n return count;\n }\n function emitCommaList(nodes) {\n if (nodes) {\n emitList(nodes, 0, nodes.length, /*multiline*/ false, /*trailingComma*/ false);\n }\n }\n function emitLines(nodes) {\n emitLinesStartingAt(nodes, /*startIndex*/ 0);\n }\n function emitLinesStartingAt(nodes, startIndex) {\n for (var i = startIndex; i < nodes.length; i++) {\n writeLine();\n emit(nodes[i]);\n }\n }\n function isBinaryOrOctalIntegerLiteral(node, text) {\n if (node.kind === 8 /* NumericLiteral */ && text.length > 1) {\n switch (text.charCodeAt(1)) {\n case 98 /* b */:\n case 66 /* B */:\n case 111 /* o */:\n case 79 /* O */:\n return true;\n }\n }\n return false;\n }\n function emitLiteral(node) {\n var text = getLiteralText(node);\n if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {\n writer.writeLiteral(text);\n }\n else if (languageVersion < 2 /* ES6 */ && isBinaryOrOctalIntegerLiteral(node, text)) {\n write(node.text);\n }\n else {\n write(text);\n }\n }\n function getLiteralText(node) {\n // Any template literal or string literal with an extended escape\n // (e.g. \"\\u{0067}\") will need to be downleveled as a escaped string literal.\n if (languageVersion < 2 /* ES6 */ && (ts.isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {\n return getQuotedEscapedLiteralText(\"\\\"\", node.text, \"\\\"\");\n }\n // If we don't need to downlevel and we can reach the original source text using\n // the node's parent reference, then simply get the text as it was originally written.\n if (node.parent) {\n return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);\n }\n // If we can't reach the original source text, use the canonical form if it's a number,\n // or an escaped quoted form of the original text if it's string-like.\n switch (node.kind) {\n case 9 /* StringLiteral */:\n return getQuotedEscapedLiteralText(\"\\\"\", node.text, \"\\\"\");\n case 11 /* NoSubstitutionTemplateLiteral */:\n return getQuotedEscapedLiteralText(\"`\", node.text, \"`\");\n case 12 /* TemplateHead */:\n return getQuotedEscapedLiteralText(\"`\", node.text, \"${\");\n case 13 /* TemplateMiddle */:\n return getQuotedEscapedLiteralText(\"}\", node.text, \"${\");\n case 14 /* TemplateTail */:\n return getQuotedEscapedLiteralText(\"}\", node.text, \"`\");\n case 8 /* NumericLiteral */:\n return node.text;\n }\n ts.Debug.fail(\"Literal kind '\" + node.kind + \"' not accounted for.\");\n }\n function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) {\n return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote;\n }\n function emitDownlevelRawTemplateLiteral(node) {\n // Find original source text, since we need to emit the raw strings of the tagged template.\n // The raw strings contain the (escaped) strings of what the user wrote.\n // Examples: `\\n` is converted to \"\\\\n\", a template string with a newline to \"\\n\".\n var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);\n // text contains the original source, it will also contain quotes (\"`\"), dolar signs and braces (\"${\" and \"}\"),\n // thus we need to remove those characters.\n // First template piece starts with \"`\", others with \"}\"\n // Last template piece ends with \"`\", others with \"${\"\n var isLast = node.kind === 11 /* NoSubstitutionTemplateLiteral */ || node.kind === 14 /* TemplateTail */;\n text = text.substring(1, text.length - (isLast ? 1 : 2));\n // Newline normalization:\n // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's\n // and LineTerminatorSequences are normalized to for both TV and TRV.\n text = text.replace(/\\r\\n?/g, \"\\n\");\n text = ts.escapeString(text);\n write(\"\\\"\" + text + \"\\\"\");\n }\n function emitDownlevelTaggedTemplateArray(node, literalEmitter) {\n write(\"[\");\n if (node.template.kind === 11 /* NoSubstitutionTemplateLiteral */) {\n literalEmitter(node.template);\n }\n else {\n literalEmitter(node.template.head);\n ts.forEach(node.template.templateSpans, function (child) {\n write(\", \");\n literalEmitter(child.literal);\n });\n }\n write(\"]\");\n }\n function emitDownlevelTaggedTemplate(node) {\n var tempVariable = createAndRecordTempVariable(0 /* Auto */);\n write(\"(\");\n emit(tempVariable);\n write(\" = \");\n emitDownlevelTaggedTemplateArray(node, emit);\n write(\", \");\n emit(tempVariable);\n write(\".raw = \");\n emitDownlevelTaggedTemplateArray(node, emitDownlevelRawTemplateLiteral);\n write(\", \");\n emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag));\n write(\"(\");\n emit(tempVariable);\n // Now we emit the expressions\n if (node.template.kind === 183 /* TemplateExpression */) {\n ts.forEach(node.template.templateSpans, function (templateSpan) {\n write(\", \");\n var needsParens = templateSpan.expression.kind === 181 /* BinaryExpression */\n && templateSpan.expression.operatorToken.kind === 24 /* CommaToken */;\n emitParenthesizedIf(templateSpan.expression, needsParens);\n });\n }\n write(\"))\");\n }\n function emitTemplateExpression(node) {\n // In ES6 mode and above, we can simply emit each portion of a template in order, but in\n // ES3 & ES5 we must convert the template expression into a series of string concatenations.\n if (languageVersion >= 2 /* ES6 */) {\n ts.forEachChild(node, emit);\n return;\n }\n var emitOuterParens = ts.isExpression(node.parent)\n && templateNeedsParens(node, node.parent);\n if (emitOuterParens) {\n write(\"(\");\n }\n var headEmitted = false;\n if (shouldEmitTemplateHead()) {\n emitLiteral(node.head);\n headEmitted = true;\n }\n for (var i = 0, n = node.templateSpans.length; i < n; i++) {\n var templateSpan = node.templateSpans[i];\n // Check if the expression has operands and binds its operands less closely than binary '+'.\n // If it does, we need to wrap the expression in parentheses. Otherwise, something like\n // `abc${ 1 << 2 }`\n // becomes\n // \"abc\" + 1 << 2 + \"\"\n // which is really\n // (\"abc\" + 1) << (2 + \"\")\n // rather than\n // \"abc\" + (1 << 2) + \"\"\n var needsParens = templateSpan.expression.kind !== 172 /* ParenthesizedExpression */\n && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */;\n if (i > 0 || headEmitted) {\n // If this is the first span and the head was not emitted, then this templateSpan's\n // expression will be the first to be emitted. Don't emit the preceding ' + ' in that\n // case.\n write(\" + \");\n }\n emitParenthesizedIf(templateSpan.expression, needsParens);\n // Only emit if the literal is non-empty.\n // The binary '+' operator is left-associative, so the first string concatenation\n // with the head will force the result up to this point to be a string.\n // Emitting a '+ \"\"' has no semantic effect for middles and tails.\n if (templateSpan.literal.text.length !== 0) {\n write(\" + \");\n emitLiteral(templateSpan.literal);\n }\n }\n if (emitOuterParens) {\n write(\")\");\n }\n function shouldEmitTemplateHead() {\n // If this expression has an empty head literal and the first template span has a non-empty\n // literal, then emitting the empty head literal is not necessary.\n // `${ foo } and ${ bar }`\n // can be emitted as\n // foo + \" and \" + bar\n // This is because it is only required that one of the first two operands in the emit\n // output must be a string literal, so that the other operand and all following operands\n // are forced into strings.\n //\n // If the first template span has an empty literal, then the head must still be emitted.\n // `${ foo }${ bar }`\n // must still be emitted as\n // \"\" + foo + bar\n // There is always atleast one templateSpan in this code path, since\n // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()\n ts.Debug.assert(node.templateSpans.length !== 0);\n return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;\n }\n function templateNeedsParens(template, parent) {\n switch (parent.kind) {\n case 168 /* CallExpression */:\n case 169 /* NewExpression */:\n return parent.expression === template;\n case 170 /* TaggedTemplateExpression */:\n case 172 /* ParenthesizedExpression */:\n return false;\n default:\n return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */;\n }\n }\n /**\n * Returns whether the expression has lesser, greater,\n * or equal precedence to the binary '+' operator\n */\n function comparePrecedenceToBinaryPlus(expression) {\n // All binary expressions have lower precedence than '+' apart from '*', '/', and '%'\n // which have greater precedence and '-' which has equal precedence.\n // All unary operators have a higher precedence apart from yield.\n // Arrow functions and conditionals have a lower precedence,\n // although we convert the former into regular function expressions in ES5 mode,\n // and in ES6 mode this function won't get called anyway.\n //\n // TODO (drosen): Note that we need to account for the upcoming 'yield' and\n // spread ('...') unary operators that are anticipated for ES6.\n switch (expression.kind) {\n case 181 /* BinaryExpression */:\n switch (expression.operatorToken.kind) {\n case 37 /* AsteriskToken */:\n case 39 /* SlashToken */:\n case 40 /* PercentToken */:\n return 1 /* GreaterThan */;\n case 35 /* PlusToken */:\n case 36 /* MinusToken */:\n return 0 /* EqualTo */;\n default:\n return -1 /* LessThan */;\n }\n case 184 /* YieldExpression */:\n case 182 /* ConditionalExpression */:\n return -1 /* LessThan */;\n default:\n return 1 /* GreaterThan */;\n }\n }\n }\n function emitTemplateSpan(span) {\n emit(span.expression);\n emit(span.literal);\n }\n function jsxEmitReact(node) {\n /// Emit a tag name, which is either '\"div\"' for lower-cased names, or\n /// 'Div' for upper-cased or dotted names\n function emitTagName(name) {\n if (name.kind === 69 /* Identifier */ && ts.isIntrinsicJsxName(name.text)) {\n write(\"\\\"\");\n emit(name);\n write(\"\\\"\");\n }\n else {\n emit(name);\n }\n }\n /// Emit an attribute name, which is quoted if it needs to be quoted. Because\n /// these emit into an object literal property name, we don't need to be worried\n /// about keywords, just non-identifier characters\n function emitAttributeName(name) {\n if (/[A-Za-z_]+[\\w*]/.test(name.text)) {\n write(\"\\\"\");\n emit(name);\n write(\"\\\"\");\n }\n else {\n emit(name);\n }\n }\n /// Emit an name/value pair for an attribute (e.g. \"x: 3\")\n function emitJsxAttribute(node) {\n emitAttributeName(node.name);\n write(\": \");\n if (node.initializer) {\n emit(node.initializer);\n }\n else {\n write(\"true\");\n }\n }\n function emitJsxElement(openingNode, children) {\n var syntheticReactRef = ts.createSynthesizedNode(69 /* Identifier */);\n syntheticReactRef.text = \"React\";\n syntheticReactRef.parent = openingNode;\n // Call React.createElement(tag, ...\n emitLeadingComments(openingNode);\n emitExpressionIdentifier(syntheticReactRef);\n write(\".createElement(\");\n emitTagName(openingNode.tagName);\n write(\", \");\n // Attribute list\n if (openingNode.attributes.length === 0) {\n // When there are no attributes, React wants \"null\"\n write(\"null\");\n }\n else {\n // Either emit one big object literal (no spread attribs), or\n // a call to React.__spread\n var attrs = openingNode.attributes;\n if (ts.forEach(attrs, function (attr) { return attr.kind === 239 /* JsxSpreadAttribute */; })) {\n emitExpressionIdentifier(syntheticReactRef);\n write(\".__spread(\");\n var haveOpenedObjectLiteral = false;\n for (var i_1 = 0; i_1 < attrs.length; i_1++) {\n if (attrs[i_1].kind === 239 /* JsxSpreadAttribute */) {\n // If this is the first argument, we need to emit a {} as the first argument\n if (i_1 === 0) {\n write(\"{}, \");\n }\n if (haveOpenedObjectLiteral) {\n write(\"}\");\n haveOpenedObjectLiteral = false;\n }\n if (i_1 > 0) {\n write(\", \");\n }\n emit(attrs[i_1].expression);\n }\n else {\n ts.Debug.assert(attrs[i_1].kind === 238 /* JsxAttribute */);\n if (haveOpenedObjectLiteral) {\n write(\", \");\n }\n else {\n haveOpenedObjectLiteral = true;\n if (i_1 > 0) {\n write(\", \");\n }\n write(\"{\");\n }\n emitJsxAttribute(attrs[i_1]);\n }\n }\n if (haveOpenedObjectLiteral)\n write(\"}\");\n write(\")\"); // closing paren to React.__spread(\n }\n else {\n // One object literal with all the attributes in them\n write(\"{\");\n for (var i = 0; i < attrs.length; i++) {\n if (i > 0) {\n write(\", \");\n }\n emitJsxAttribute(attrs[i]);\n }\n write(\"}\");\n }\n }\n // Children\n if (children) {\n for (var i = 0; i < children.length; i++) {\n // Don't emit empty expressions\n if (children[i].kind === 240 /* JsxExpression */ && !(children[i].expression)) {\n continue;\n }\n // Don't emit empty strings\n if (children[i].kind === 236 /* JsxText */) {\n var text = getTextToEmit(children[i]);\n if (text !== undefined) {\n write(\", \\\"\");\n write(text);\n write(\"\\\"\");\n }\n }\n else {\n write(\", \");\n emit(children[i]);\n }\n }\n }\n // Closing paren\n write(\")\"); // closes \"React.createElement(\"\n emitTrailingComments(openingNode);\n }\n if (node.kind === 233 /* JsxElement */) {\n emitJsxElement(node.openingElement, node.children);\n }\n else {\n ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */);\n emitJsxElement(node);\n }\n }\n function jsxEmitPreserve(node) {\n function emitJsxAttribute(node) {\n emit(node.name);\n if (node.initializer) {\n write(\"=\");\n emit(node.initializer);\n }\n }\n function emitJsxSpreadAttribute(node) {\n write(\"{...\");\n emit(node.expression);\n write(\"}\");\n }\n function emitAttributes(attribs) {\n for (var i = 0, n = attribs.length; i < n; i++) {\n if (i > 0) {\n write(\" \");\n }\n if (attribs[i].kind === 239 /* JsxSpreadAttribute */) {\n emitJsxSpreadAttribute(attribs[i]);\n }\n else {\n ts.Debug.assert(attribs[i].kind === 238 /* JsxAttribute */);\n emitJsxAttribute(attribs[i]);\n }\n }\n }\n function emitJsxOpeningOrSelfClosingElement(node) {\n write(\"<\");\n emit(node.tagName);\n if (node.attributes.length > 0 || (node.kind === 234 /* JsxSelfClosingElement */)) {\n write(\" \");\n }\n emitAttributes(node.attributes);\n if (node.kind === 234 /* JsxSelfClosingElement */) {\n write(\"/>\");\n }\n else {\n write(\">\");\n }\n }\n function emitJsxClosingElement(node) {\n write(\"\");\n }\n function emitJsxElement(node) {\n emitJsxOpeningOrSelfClosingElement(node.openingElement);\n for (var i = 0, n = node.children.length; i < n; i++) {\n emit(node.children[i]);\n }\n emitJsxClosingElement(node.closingElement);\n }\n if (node.kind === 233 /* JsxElement */) {\n emitJsxElement(node);\n }\n else {\n ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */);\n emitJsxOpeningOrSelfClosingElement(node);\n }\n }\n // This function specifically handles numeric/string literals for enum and accessor 'identifiers'.\n // In a sense, it does not actually emit identifiers as much as it declares a name for a specific property.\n // For example, this is utilized when feeding in a result to Object.defineProperty.\n function emitExpressionForPropertyName(node) {\n ts.Debug.assert(node.kind !== 163 /* BindingElement */);\n if (node.kind === 9 /* StringLiteral */) {\n emitLiteral(node);\n }\n else if (node.kind === 136 /* ComputedPropertyName */) {\n // if this is a decorated computed property, we will need to capture the result\n // of the property expression so that we can apply decorators later. This is to ensure\n // we don't introduce unintended side effects:\n //\n // class C {\n // [_a = x]() { }\n // }\n //\n // The emit for the decorated computed property decorator is:\n //\n // __decorate([dec], C.prototype, _a, Object.getOwnPropertyDescriptor(C.prototype, _a));\n //\n if (ts.nodeIsDecorated(node.parent)) {\n if (!computedPropertyNamesToGeneratedNames) {\n computedPropertyNamesToGeneratedNames = [];\n }\n var generatedName = computedPropertyNamesToGeneratedNames[ts.getNodeId(node)];\n if (generatedName) {\n // we have already generated a variable for this node, write that value instead.\n write(generatedName);\n return;\n }\n generatedName = createAndRecordTempVariable(0 /* Auto */).text;\n computedPropertyNamesToGeneratedNames[ts.getNodeId(node)] = generatedName;\n write(generatedName);\n write(\" = \");\n }\n emit(node.expression);\n }\n else {\n write(\"\\\"\");\n if (node.kind === 8 /* NumericLiteral */) {\n write(node.text);\n }\n else {\n writeTextOfNode(currentSourceFile, node);\n }\n write(\"\\\"\");\n }\n }\n function isExpressionIdentifier(node) {\n var parent = node.parent;\n switch (parent.kind) {\n case 164 /* ArrayLiteralExpression */:\n case 189 /* AsExpression */:\n case 181 /* BinaryExpression */:\n case 168 /* CallExpression */:\n case 241 /* CaseClause */:\n case 136 /* ComputedPropertyName */:\n case 182 /* ConditionalExpression */:\n case 139 /* Decorator */:\n case 175 /* DeleteExpression */:\n case 197 /* DoStatement */:\n case 167 /* ElementAccessExpression */:\n case 227 /* ExportAssignment */:\n case 195 /* ExpressionStatement */:\n case 188 /* ExpressionWithTypeArguments */:\n case 199 /* ForStatement */:\n case 200 /* ForInStatement */:\n case 201 /* ForOfStatement */:\n case 196 /* IfStatement */:\n case 234 /* JsxSelfClosingElement */:\n case 235 /* JsxOpeningElement */:\n case 239 /* JsxSpreadAttribute */:\n case 240 /* JsxExpression */:\n case 169 /* NewExpression */:\n case 172 /* ParenthesizedExpression */:\n case 180 /* PostfixUnaryExpression */:\n case 179 /* PrefixUnaryExpression */:\n case 204 /* ReturnStatement */:\n case 246 /* ShorthandPropertyAssignment */:\n case 185 /* SpreadElementExpression */:\n case 206 /* SwitchStatement */:\n case 170 /* TaggedTemplateExpression */:\n case 190 /* TemplateSpan */:\n case 208 /* ThrowStatement */:\n case 171 /* TypeAssertionExpression */:\n case 176 /* TypeOfExpression */:\n case 177 /* VoidExpression */:\n case 198 /* WhileStatement */:\n case 205 /* WithStatement */:\n case 184 /* YieldExpression */:\n return true;\n case 163 /* BindingElement */:\n case 247 /* EnumMember */:\n case 138 /* Parameter */:\n case 245 /* PropertyAssignment */:\n case 141 /* PropertyDeclaration */:\n case 211 /* VariableDeclaration */:\n return parent.initializer === node;\n case 166 /* PropertyAccessExpression */:\n return parent.expression === node;\n case 174 /* ArrowFunction */:\n case 173 /* FunctionExpression */:\n return parent.body === node;\n case 221 /* ImportEqualsDeclaration */:\n return parent.moduleReference === node;\n case 135 /* QualifiedName */:\n return parent.left === node;\n }\n return false;\n }\n function emitExpressionIdentifier(node) {\n if (resolver.getNodeCheckFlags(node) & 2048 /* LexicalArguments */) {\n write(\"_arguments\");\n return;\n }\n var container = resolver.getReferencedExportContainer(node);\n if (container) {\n if (container.kind === 248 /* SourceFile */) {\n // Identifier references module export\n if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) {\n write(\"exports.\");\n }\n }\n else {\n // Identifier references namespace export\n write(getGeneratedNameForNode(container));\n write(\".\");\n }\n }\n else {\n if (modulekind !== 5 /* ES6 */) {\n var declaration = resolver.getReferencedImportDeclaration(node);\n if (declaration) {\n if (declaration.kind === 223 /* ImportClause */) {\n // Identifier references default import\n write(getGeneratedNameForNode(declaration.parent));\n write(languageVersion === 0 /* ES3 */ ? \"[\\\"default\\\"]\" : \".default\");\n return;\n }\n else if (declaration.kind === 226 /* ImportSpecifier */) {\n // Identifier references named import\n write(getGeneratedNameForNode(declaration.parent.parent.parent));\n var name_23 = declaration.propertyName || declaration.name;\n var identifier = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, name_23);\n if (languageVersion === 0 /* ES3 */ && identifier === \"default\") {\n write(\"[\\\"default\\\"]\");\n }\n else {\n write(\".\");\n write(identifier);\n }\n return;\n }\n }\n }\n if (languageVersion !== 2 /* ES6 */) {\n var declaration = resolver.getReferencedNestedRedeclaration(node);\n if (declaration) {\n write(getGeneratedNameForNode(declaration.name));\n return;\n }\n }\n }\n if (ts.nodeIsSynthesized(node)) {\n write(node.text);\n }\n else {\n writeTextOfNode(currentSourceFile, node);\n }\n }\n function isNameOfNestedRedeclaration(node) {\n if (languageVersion < 2 /* ES6 */) {\n var parent_6 = node.parent;\n switch (parent_6.kind) {\n case 163 /* BindingElement */:\n case 214 /* ClassDeclaration */:\n case 217 /* EnumDeclaration */:\n case 211 /* VariableDeclaration */:\n return parent_6.name === node && resolver.isNestedRedeclaration(parent_6);\n }\n }\n return false;\n }\n function emitIdentifier(node) {\n if (!node.parent) {\n write(node.text);\n }\n else if (isExpressionIdentifier(node)) {\n emitExpressionIdentifier(node);\n }\n else if (isNameOfNestedRedeclaration(node)) {\n write(getGeneratedNameForNode(node));\n }\n else if (ts.nodeIsSynthesized(node)) {\n write(node.text);\n }\n else {\n writeTextOfNode(currentSourceFile, node);\n }\n }\n function emitThis(node) {\n if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) {\n write(\"_this\");\n }\n else {\n write(\"this\");\n }\n }\n function emitSuper(node) {\n if (languageVersion >= 2 /* ES6 */) {\n write(\"super\");\n }\n else {\n var flags = resolver.getNodeCheckFlags(node);\n if (flags & 256 /* SuperInstance */) {\n write(\"_super.prototype\");\n }\n else {\n write(\"_super\");\n }\n }\n }\n function emitObjectBindingPattern(node) {\n write(\"{ \");\n var elements = node.elements;\n emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma);\n write(\" }\");\n }\n function emitArrayBindingPattern(node) {\n write(\"[\");\n var elements = node.elements;\n emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma);\n write(\"]\");\n }\n function emitBindingElement(node) {\n if (node.propertyName) {\n emit(node.propertyName);\n write(\": \");\n }\n if (node.dotDotDotToken) {\n write(\"...\");\n }\n if (ts.isBindingPattern(node.name)) {\n emit(node.name);\n }\n else {\n emitModuleMemberName(node);\n }\n emitOptional(\" = \", node.initializer);\n }\n function emitSpreadElementExpression(node) {\n write(\"...\");\n emit(node.expression);\n }\n function emitYieldExpression(node) {\n write(ts.tokenToString(114 /* YieldKeyword */));\n if (node.asteriskToken) {\n write(\"*\");\n }\n if (node.expression) {\n write(\" \");\n emit(node.expression);\n }\n }\n function emitAwaitExpression(node) {\n var needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node);\n if (needsParenthesis) {\n write(\"(\");\n }\n write(ts.tokenToString(114 /* YieldKeyword */));\n write(\" \");\n emit(node.expression);\n if (needsParenthesis) {\n write(\")\");\n }\n }\n function needsParenthesisForAwaitExpressionAsYield(node) {\n if (node.parent.kind === 181 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) {\n return true;\n }\n else if (node.parent.kind === 182 /* ConditionalExpression */ && node.parent.condition === node) {\n return true;\n }\n return false;\n }\n function needsParenthesisForPropertyAccessOrInvocation(node) {\n switch (node.kind) {\n case 69 /* Identifier */:\n case 164 /* ArrayLiteralExpression */:\n case 166 /* PropertyAccessExpression */:\n case 167 /* ElementAccessExpression */:\n case 168 /* CallExpression */:\n case 172 /* ParenthesizedExpression */:\n // This list is not exhaustive and only includes those cases that are relevant\n // to the check in emitArrayLiteral. More cases can be added as needed.\n return false;\n }\n return true;\n }\n function emitListWithSpread(elements, needsUniqueCopy, multiLine, trailingComma, useConcat) {\n var pos = 0;\n var group = 0;\n var length = elements.length;\n while (pos < length) {\n // Emit using the pattern .concat(, , ...)\n if (group === 1 && useConcat) {\n write(\".concat(\");\n }\n else if (group > 0) {\n write(\", \");\n }\n var e = elements[pos];\n if (e.kind === 185 /* SpreadElementExpression */) {\n e = e.expression;\n emitParenthesizedIf(e, /*parenthesized*/ group === 0 && needsParenthesisForPropertyAccessOrInvocation(e));\n pos++;\n if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 164 /* ArrayLiteralExpression */) {\n write(\".slice()\");\n }\n }\n else {\n var i = pos;\n while (i < length && elements[i].kind !== 185 /* SpreadElementExpression */) {\n i++;\n }\n write(\"[\");\n if (multiLine) {\n increaseIndent();\n }\n emitList(elements, pos, i - pos, multiLine, trailingComma && i === length);\n if (multiLine) {\n decreaseIndent();\n }\n write(\"]\");\n pos = i;\n }\n group++;\n }\n if (group > 1) {\n if (useConcat) {\n write(\")\");\n }\n }\n }\n function isSpreadElementExpression(node) {\n return node.kind === 185 /* SpreadElementExpression */;\n }\n function emitArrayLiteral(node) {\n var elements = node.elements;\n if (elements.length === 0) {\n write(\"[]\");\n }\n else if (languageVersion >= 2 /* ES6 */ || !ts.forEach(elements, isSpreadElementExpression)) {\n write(\"[\");\n emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces:*/ false);\n write(\"]\");\n }\n else {\n emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ (node.flags & 2048 /* MultiLine */) !== 0,\n /*trailingComma*/ elements.hasTrailingComma, /*useConcat*/ true);\n }\n }\n function emitObjectLiteralBody(node, numElements) {\n if (numElements === 0) {\n write(\"{}\");\n return;\n }\n write(\"{\");\n if (numElements > 0) {\n var properties = node.properties;\n // If we are not doing a downlevel transformation for object literals,\n // then try to preserve the original shape of the object literal.\n // Otherwise just try to preserve the formatting.\n if (numElements === properties.length) {\n emitLinePreservingList(node, properties, /* allowTrailingComma */ languageVersion >= 1 /* ES5 */, /* spacesBetweenBraces */ true);\n }\n else {\n var multiLine = (node.flags & 2048 /* MultiLine */) !== 0;\n if (!multiLine) {\n write(\" \");\n }\n else {\n increaseIndent();\n }\n emitList(properties, 0, numElements, /*multiLine*/ multiLine, /*trailingComma*/ false);\n if (!multiLine) {\n write(\" \");\n }\n else {\n decreaseIndent();\n }\n }\n }\n write(\"}\");\n }\n function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) {\n var multiLine = (node.flags & 2048 /* MultiLine */) !== 0;\n var properties = node.properties;\n write(\"(\");\n if (multiLine) {\n increaseIndent();\n }\n // For computed properties, we need to create a unique handle to the object\n // literal so we can modify it without risking internal assignments tainting the object.\n var tempVar = createAndRecordTempVariable(0 /* Auto */);\n // Write out the first non-computed properties\n // (or all properties if none of them are computed),\n // then emit the rest through indexing on the temp variable.\n emit(tempVar);\n write(\" = \");\n emitObjectLiteralBody(node, firstComputedPropertyIndex);\n for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) {\n writeComma();\n var property = properties[i];\n emitStart(property);\n if (property.kind === 145 /* GetAccessor */ || property.kind === 146 /* SetAccessor */) {\n // TODO (drosen): Reconcile with 'emitMemberFunctions'.\n var accessors = ts.getAllAccessorDeclarations(node.properties, property);\n if (property !== accessors.firstAccessor) {\n continue;\n }\n write(\"Object.defineProperty(\");\n emit(tempVar);\n write(\", \");\n emitStart(node.name);\n emitExpressionForPropertyName(property.name);\n emitEnd(property.name);\n write(\", {\");\n increaseIndent();\n if (accessors.getAccessor) {\n writeLine();\n emitLeadingComments(accessors.getAccessor);\n write(\"get: \");\n emitStart(accessors.getAccessor);\n write(\"function \");\n emitSignatureAndBody(accessors.getAccessor);\n emitEnd(accessors.getAccessor);\n emitTrailingComments(accessors.getAccessor);\n write(\",\");\n }\n if (accessors.setAccessor) {\n writeLine();\n emitLeadingComments(accessors.setAccessor);\n write(\"set: \");\n emitStart(accessors.setAccessor);\n write(\"function \");\n emitSignatureAndBody(accessors.setAccessor);\n emitEnd(accessors.setAccessor);\n emitTrailingComments(accessors.setAccessor);\n write(\",\");\n }\n writeLine();\n write(\"enumerable: true,\");\n writeLine();\n write(\"configurable: true\");\n decreaseIndent();\n writeLine();\n write(\"})\");\n emitEnd(property);\n }\n else {\n emitLeadingComments(property);\n emitStart(property.name);\n emit(tempVar);\n emitMemberAccessForPropertyName(property.name);\n emitEnd(property.name);\n write(\" = \");\n if (property.kind === 245 /* PropertyAssignment */) {\n emit(property.initializer);\n }\n else if (property.kind === 246 /* ShorthandPropertyAssignment */) {\n emitExpressionIdentifier(property.name);\n }\n else if (property.kind === 143 /* MethodDeclaration */) {\n emitFunctionDeclaration(property);\n }\n else {\n ts.Debug.fail(\"ObjectLiteralElement type not accounted for: \" + property.kind);\n }\n }\n emitEnd(property);\n }\n writeComma();\n emit(tempVar);\n if (multiLine) {\n decreaseIndent();\n writeLine();\n }\n write(\")\");\n function writeComma() {\n if (multiLine) {\n write(\",\");\n writeLine();\n }\n else {\n write(\", \");\n }\n }\n }\n function emitObjectLiteral(node) {\n var properties = node.properties;\n if (languageVersion < 2 /* ES6 */) {\n var numProperties = properties.length;\n // Find the first computed property.\n // Everything until that point can be emitted as part of the initial object literal.\n var numInitialNonComputedProperties = numProperties;\n for (var i = 0, n = properties.length; i < n; i++) {\n if (properties[i].name.kind === 136 /* ComputedPropertyName */) {\n numInitialNonComputedProperties = i;\n break;\n }\n }\n var hasComputedProperty = numInitialNonComputedProperties !== properties.length;\n if (hasComputedProperty) {\n emitDownlevelObjectLiteralWithComputedProperties(node, numInitialNonComputedProperties);\n return;\n }\n }\n // Ordinary case: either the object has no computed properties\n // or we're compiling with an ES6+ target.\n emitObjectLiteralBody(node, properties.length);\n }\n function createBinaryExpression(left, operator, right, startsOnNewLine) {\n var result = ts.createSynthesizedNode(181 /* BinaryExpression */, startsOnNewLine);\n result.operatorToken = ts.createSynthesizedNode(operator);\n result.left = left;\n result.right = right;\n return result;\n }\n function createPropertyAccessExpression(expression, name) {\n var result = ts.createSynthesizedNode(166 /* PropertyAccessExpression */);\n result.expression = parenthesizeForAccess(expression);\n result.dotToken = ts.createSynthesizedNode(21 /* DotToken */);\n result.name = name;\n return result;\n }\n function createElementAccessExpression(expression, argumentExpression) {\n var result = ts.createSynthesizedNode(167 /* ElementAccessExpression */);\n result.expression = parenthesizeForAccess(expression);\n result.argumentExpression = argumentExpression;\n return result;\n }\n function parenthesizeForAccess(expr) {\n // When diagnosing whether the expression needs parentheses, the decision should be based\n // on the innermost expression in a chain of nested type assertions.\n while (expr.kind === 171 /* TypeAssertionExpression */ || expr.kind === 189 /* AsExpression */) {\n expr = expr.expression;\n }\n // isLeftHandSideExpression is almost the correct criterion for when it is not necessary\n // to parenthesize the expression before a dot. The known exceptions are:\n //\n // NewExpression:\n // new C.x -> not the same as (new C).x\n // NumberLiteral\n // 1.x -> not the same as (1).x\n //\n if (ts.isLeftHandSideExpression(expr) &&\n expr.kind !== 169 /* NewExpression */ &&\n expr.kind !== 8 /* NumericLiteral */) {\n return expr;\n }\n var node = ts.createSynthesizedNode(172 /* ParenthesizedExpression */);\n node.expression = expr;\n return node;\n }\n function emitComputedPropertyName(node) {\n write(\"[\");\n emitExpressionForPropertyName(node);\n write(\"]\");\n }\n function emitMethod(node) {\n if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) {\n write(\"*\");\n }\n emit(node.name);\n if (languageVersion < 2 /* ES6 */) {\n write(\": function \");\n }\n emitSignatureAndBody(node);\n }\n function emitPropertyAssignment(node) {\n emit(node.name);\n write(\": \");\n // This is to ensure that we emit comment in the following case:\n // For example:\n // obj = {\n // id: /*comment1*/ ()=>void\n // }\n // \"comment1\" is not considered to be leading comment for node.initializer\n // but rather a trailing comment on the previous node.\n emitTrailingCommentsOfPosition(node.initializer.pos);\n emit(node.initializer);\n }\n // Return true if identifier resolves to an exported member of a namespace\n function isNamespaceExportReference(node) {\n var container = resolver.getReferencedExportContainer(node);\n return container && container.kind !== 248 /* SourceFile */;\n }\n function emitShorthandPropertyAssignment(node) {\n // The name property of a short-hand property assignment is considered an expression position, so here\n // we manually emit the identifier to avoid rewriting.\n writeTextOfNode(currentSourceFile, node.name);\n // If emitting pre-ES6 code, or if the name requires rewriting when resolved as an expression identifier,\n // we emit a normal property assignment. For example:\n // module m {\n // export let y;\n // }\n // module m {\n // let obj = { y };\n // }\n // Here we need to emit obj = { y : m.y } regardless of the output target.\n if (languageVersion < 2 /* ES6 */ || isNamespaceExportReference(node.name)) {\n // Emit identifier as an identifier\n write(\": \");\n emit(node.name);\n }\n if (languageVersion >= 2 /* ES6 */ && node.objectAssignmentInitializer) {\n write(\" = \");\n emit(node.objectAssignmentInitializer);\n }\n }\n function tryEmitConstantValue(node) {\n var constantValue = tryGetConstEnumValue(node);\n if (constantValue !== undefined) {\n write(constantValue.toString());\n if (!compilerOptions.removeComments) {\n var propertyName = node.kind === 166 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression);\n write(\" /* \" + propertyName + \" */\");\n }\n return true;\n }\n return false;\n }\n function tryGetConstEnumValue(node) {\n if (compilerOptions.isolatedModules) {\n return undefined;\n }\n return node.kind === 166 /* PropertyAccessExpression */ || node.kind === 167 /* ElementAccessExpression */\n ? resolver.getConstantValue(node)\n : undefined;\n }\n // Returns 'true' if the code was actually indented, false otherwise.\n // If the code is not indented, an optional valueToWriteWhenNotIndenting will be\n // emitted instead.\n function indentIfOnDifferentLines(parent, node1, node2, valueToWriteWhenNotIndenting) {\n var realNodesAreOnDifferentLines = !ts.nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2);\n // Always use a newline for synthesized code if the synthesizer desires it.\n var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2);\n if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) {\n increaseIndent();\n writeLine();\n return true;\n }\n else {\n if (valueToWriteWhenNotIndenting) {\n write(valueToWriteWhenNotIndenting);\n }\n return false;\n }\n }\n function emitPropertyAccess(node) {\n if (tryEmitConstantValue(node)) {\n return;\n }\n emit(node.expression);\n var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken);\n // 1 .toString is a valid property access, emit a space after the literal\n // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal\n var shouldEmitSpace;\n if (!indentedBeforeDot) {\n if (node.expression.kind === 8 /* NumericLiteral */) {\n // check if numeric literal was originally written with a dot\n var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);\n shouldEmitSpace = text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0;\n }\n else {\n // check if constant enum value is integer\n var constantValue = tryGetConstEnumValue(node.expression);\n // isFinite handles cases when constantValue is undefined\n shouldEmitSpace = isFinite(constantValue) && Math.floor(constantValue) === constantValue;\n }\n }\n if (shouldEmitSpace) {\n write(\" .\");\n }\n else {\n write(\".\");\n }\n var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name);\n emit(node.name);\n decreaseIndentIf(indentedBeforeDot, indentedAfterDot);\n }\n function emitQualifiedName(node) {\n emit(node.left);\n write(\".\");\n emit(node.right);\n }\n function emitQualifiedNameAsExpression(node, useFallback) {\n if (node.left.kind === 69 /* Identifier */) {\n emitEntityNameAsExpression(node.left, useFallback);\n }\n else if (useFallback) {\n var temp = createAndRecordTempVariable(0 /* Auto */);\n write(\"(\");\n emitNodeWithoutSourceMap(temp);\n write(\" = \");\n emitEntityNameAsExpression(node.left, /*useFallback*/ true);\n write(\") && \");\n emitNodeWithoutSourceMap(temp);\n }\n else {\n emitEntityNameAsExpression(node.left, /*useFallback*/ false);\n }\n write(\".\");\n emit(node.right);\n }\n function emitEntityNameAsExpression(node, useFallback) {\n switch (node.kind) {\n case 69 /* Identifier */:\n if (useFallback) {\n write(\"typeof \");\n emitExpressionIdentifier(node);\n write(\" !== 'undefined' && \");\n }\n emitExpressionIdentifier(node);\n break;\n case 135 /* QualifiedName */:\n emitQualifiedNameAsExpression(node, useFallback);\n break;\n }\n }\n function emitIndexedAccess(node) {\n if (tryEmitConstantValue(node)) {\n return;\n }\n emit(node.expression);\n write(\"[\");\n emit(node.argumentExpression);\n write(\"]\");\n }\n function hasSpreadElement(elements) {\n return ts.forEach(elements, function (e) { return e.kind === 185 /* SpreadElementExpression */; });\n }\n function skipParentheses(node) {\n while (node.kind === 172 /* ParenthesizedExpression */ || node.kind === 171 /* TypeAssertionExpression */ || node.kind === 189 /* AsExpression */) {\n node = node.expression;\n }\n return node;\n }\n function emitCallTarget(node) {\n if (node.kind === 69 /* Identifier */ || node.kind === 97 /* ThisKeyword */ || node.kind === 95 /* SuperKeyword */) {\n emit(node);\n return node;\n }\n var temp = createAndRecordTempVariable(0 /* Auto */);\n write(\"(\");\n emit(temp);\n write(\" = \");\n emit(node);\n write(\")\");\n return temp;\n }\n function emitCallWithSpread(node) {\n var target;\n var expr = skipParentheses(node.expression);\n if (expr.kind === 166 /* PropertyAccessExpression */) {\n // Target will be emitted as \"this\" argument\n target = emitCallTarget(expr.expression);\n write(\".\");\n emit(expr.name);\n }\n else if (expr.kind === 167 /* ElementAccessExpression */) {\n // Target will be emitted as \"this\" argument\n target = emitCallTarget(expr.expression);\n write(\"[\");\n emit(expr.argumentExpression);\n write(\"]\");\n }\n else if (expr.kind === 95 /* SuperKeyword */) {\n target = expr;\n write(\"_super\");\n }\n else {\n emit(node.expression);\n }\n write(\".apply(\");\n if (target) {\n if (target.kind === 95 /* SuperKeyword */) {\n // Calls of form super(...) and super.foo(...)\n emitThis(target);\n }\n else {\n // Calls of form obj.foo(...)\n emit(target);\n }\n }\n else {\n // Calls of form foo(...)\n write(\"void 0\");\n }\n write(\", \");\n emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ true);\n write(\")\");\n }\n function emitCallExpression(node) {\n if (languageVersion < 2 /* ES6 */ && hasSpreadElement(node.arguments)) {\n emitCallWithSpread(node);\n return;\n }\n var superCall = false;\n if (node.expression.kind === 95 /* SuperKeyword */) {\n emitSuper(node.expression);\n superCall = true;\n }\n else {\n emit(node.expression);\n superCall = node.expression.kind === 166 /* PropertyAccessExpression */ && node.expression.expression.kind === 95 /* SuperKeyword */;\n }\n if (superCall && languageVersion < 2 /* ES6 */) {\n write(\".call(\");\n emitThis(node.expression);\n if (node.arguments.length) {\n write(\", \");\n emitCommaList(node.arguments);\n }\n write(\")\");\n }\n else {\n write(\"(\");\n emitCommaList(node.arguments);\n write(\")\");\n }\n }\n function emitNewExpression(node) {\n write(\"new \");\n // Spread operator logic is supported in new expressions in ES5 using a combination\n // of Function.prototype.bind() and Function.prototype.apply().\n //\n // Example:\n //\n // var args = [1, 2, 3, 4, 5];\n // new Array(...args);\n //\n // is compiled into the following ES5:\n //\n // var args = [1, 2, 3, 4, 5];\n // new (Array.bind.apply(Array, [void 0].concat(args)));\n //\n // The 'thisArg' to 'bind' is ignored when invoking the result of 'bind' with 'new',\n // Thus, we set it to undefined ('void 0').\n if (languageVersion === 1 /* ES5 */ &&\n node.arguments &&\n hasSpreadElement(node.arguments)) {\n write(\"(\");\n var target = emitCallTarget(node.expression);\n write(\".bind.apply(\");\n emit(target);\n write(\", [void 0].concat(\");\n emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiline*/ false, /*trailingComma*/ false, /*useConcat*/ false);\n write(\")))\");\n write(\"()\");\n }\n else {\n emit(node.expression);\n if (node.arguments) {\n write(\"(\");\n emitCommaList(node.arguments);\n write(\")\");\n }\n }\n }\n function emitTaggedTemplateExpression(node) {\n if (languageVersion >= 2 /* ES6 */) {\n emit(node.tag);\n write(\" \");\n emit(node.template);\n }\n else {\n emitDownlevelTaggedTemplate(node);\n }\n }\n function emitParenExpression(node) {\n // If the node is synthesized, it means the emitter put the parentheses there,\n // not the user. If we didn't want them, the emitter would not have put them\n // there.\n if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 174 /* ArrowFunction */) {\n if (node.expression.kind === 171 /* TypeAssertionExpression */ || node.expression.kind === 189 /* AsExpression */) {\n var operand = node.expression.expression;\n // Make sure we consider all nested cast expressions, e.g.:\n // (-A).x;\n while (operand.kind === 171 /* TypeAssertionExpression */ || operand.kind === 189 /* AsExpression */) {\n operand = operand.expression;\n }\n // We have an expression of the form: (SubExpr)\n // Emitting this as (SubExpr) is really not desirable. We would like to emit the subexpr as is.\n // Omitting the parentheses, however, could cause change in the semantics of the generated\n // code if the casted expression has a lower precedence than the rest of the expression, e.g.:\n // (new A).foo should be emitted as (new A).foo and not new A.foo\n // (typeof A).toString() should be emitted as (typeof A).toString() and not typeof A.toString()\n // new (A()) should be emitted as new (A()) and not new A()\n // (function foo() { })() should be emitted as an IIF (function foo(){})() and not declaration function foo(){} ()\n if (operand.kind !== 179 /* PrefixUnaryExpression */ &&\n operand.kind !== 177 /* VoidExpression */ &&\n operand.kind !== 176 /* TypeOfExpression */ &&\n operand.kind !== 175 /* DeleteExpression */ &&\n operand.kind !== 180 /* PostfixUnaryExpression */ &&\n operand.kind !== 169 /* NewExpression */ &&\n !(operand.kind === 168 /* CallExpression */ && node.parent.kind === 169 /* NewExpression */) &&\n !(operand.kind === 173 /* FunctionExpression */ && node.parent.kind === 168 /* CallExpression */) &&\n !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 166 /* PropertyAccessExpression */)) {\n emit(operand);\n return;\n }\n }\n }\n write(\"(\");\n emit(node.expression);\n write(\")\");\n }\n function emitDeleteExpression(node) {\n write(ts.tokenToString(78 /* DeleteKeyword */));\n write(\" \");\n emit(node.expression);\n }\n function emitVoidExpression(node) {\n write(ts.tokenToString(103 /* VoidKeyword */));\n write(\" \");\n emit(node.expression);\n }\n function emitTypeOfExpression(node) {\n write(ts.tokenToString(101 /* TypeOfKeyword */));\n write(\" \");\n emit(node.expression);\n }\n function isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node) {\n if (!isCurrentFileSystemExternalModule() || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) {\n return false;\n }\n var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 211 /* VariableDeclaration */ || node.parent.kind === 163 /* BindingElement */);\n var targetDeclaration = isVariableDeclarationOrBindingElement\n ? node.parent\n : resolver.getReferencedValueDeclaration(node);\n return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, /*isExported*/ true);\n }\n function emitPrefixUnaryExpression(node) {\n var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand);\n if (exportChanged) {\n // emit\n // ++x\n // as\n // exports('x', ++x)\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithoutSourceMap(node.operand);\n write(\"\\\", \");\n }\n write(ts.tokenToString(node.operator));\n // In some cases, we need to emit a space between the operator and the operand. One obvious case\n // is when the operator is an identifier, like delete or typeof. We also need to do this for plus\n // and minus expressions in certain cases. Specifically, consider the following two cases (parens\n // are just for clarity of exposition, and not part of the source code):\n //\n // (+(+1))\n // (+(++1))\n //\n // We need to emit a space in both cases. In the first case, the absence of a space will make\n // the resulting expression a prefix increment operation. And in the second, it will make the resulting\n // expression a prefix increment whose operand is a plus expression - (++(+x))\n // The same is true of minus of course.\n if (node.operand.kind === 179 /* PrefixUnaryExpression */) {\n var operand = node.operand;\n if (node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) {\n write(\" \");\n }\n else if (node.operator === 36 /* MinusToken */ && (operand.operator === 36 /* MinusToken */ || operand.operator === 42 /* MinusMinusToken */)) {\n write(\" \");\n }\n }\n emit(node.operand);\n if (exportChanged) {\n write(\")\");\n }\n }\n function emitPostfixUnaryExpression(node) {\n var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand);\n if (exportChanged) {\n // export function returns the value that was passes as the second argument\n // however for postfix unary expressions result value should be the value before modification.\n // emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)'\n write(\"(\" + exportFunctionForFile + \"(\\\"\");\n emitNodeWithoutSourceMap(node.operand);\n write(\"\\\", \");\n write(ts.tokenToString(node.operator));\n emit(node.operand);\n if (node.operator === 41 /* PlusPlusToken */) {\n write(\") - 1)\");\n }\n else {\n write(\") + 1)\");\n }\n }\n else {\n emit(node.operand);\n write(ts.tokenToString(node.operator));\n }\n }\n function shouldHoistDeclarationInSystemJsModule(node) {\n return isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ false);\n }\n /*\n * Checks if given node is a source file level declaration (not nested in module/function).\n * If 'isExported' is true - then declaration must also be exported.\n * This function is used in two cases:\n * - check if node is a exported source file level value to determine\n * if we should also export the value after its it changed\n * - check if node is a source level declaration to emit it differently,\n * i.e non-exported variable statement 'var x = 1' is hoisted so\n * we we emit variable statement 'var' should be dropped.\n */\n function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) {\n if (!node || languageVersion >= 2 /* ES6 */ || !isCurrentFileSystemExternalModule()) {\n return false;\n }\n var current = node;\n while (current) {\n if (current.kind === 248 /* SourceFile */) {\n return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0);\n }\n else if (ts.isFunctionLike(current) || current.kind === 219 /* ModuleBlock */) {\n return false;\n }\n else {\n current = current.parent;\n }\n }\n }\n /**\n * Emit ES7 exponentiation operator downlevel using Math.pow\n * @param node a binary expression node containing exponentiationOperator (**, **=)\n */\n function emitExponentiationOperator(node) {\n var leftHandSideExpression = node.left;\n if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) {\n var synthesizedLHS;\n var shouldEmitParentheses = false;\n if (ts.isElementAccessExpression(leftHandSideExpression)) {\n shouldEmitParentheses = true;\n write(\"(\");\n synthesizedLHS = ts.createSynthesizedNode(167 /* ElementAccessExpression */, /*startsOnNewLine*/ false);\n var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false);\n synthesizedLHS.expression = identifier;\n if (leftHandSideExpression.argumentExpression.kind !== 8 /* NumericLiteral */ &&\n leftHandSideExpression.argumentExpression.kind !== 9 /* StringLiteral */) {\n var tempArgumentExpression = createAndRecordTempVariable(268435456 /* _i */);\n synthesizedLHS.argumentExpression = tempArgumentExpression;\n emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true);\n }\n else {\n synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression;\n }\n write(\", \");\n }\n else if (ts.isPropertyAccessExpression(leftHandSideExpression)) {\n shouldEmitParentheses = true;\n write(\"(\");\n synthesizedLHS = ts.createSynthesizedNode(166 /* PropertyAccessExpression */, /*startsOnNewLine*/ false);\n var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false);\n synthesizedLHS.expression = identifier;\n synthesizedLHS.dotToken = leftHandSideExpression.dotToken;\n synthesizedLHS.name = leftHandSideExpression.name;\n write(\", \");\n }\n emit(synthesizedLHS || leftHandSideExpression);\n write(\" = \");\n write(\"Math.pow(\");\n emit(synthesizedLHS || leftHandSideExpression);\n write(\", \");\n emit(node.right);\n write(\")\");\n if (shouldEmitParentheses) {\n write(\")\");\n }\n }\n else {\n write(\"Math.pow(\");\n emit(leftHandSideExpression);\n write(\", \");\n emit(node.right);\n write(\")\");\n }\n }\n function emitBinaryExpression(node) {\n if (languageVersion < 2 /* ES6 */ && node.operatorToken.kind === 56 /* EqualsToken */ &&\n (node.left.kind === 165 /* ObjectLiteralExpression */ || node.left.kind === 164 /* ArrayLiteralExpression */)) {\n emitDestructuring(node, node.parent.kind === 195 /* ExpressionStatement */);\n }\n else {\n var exportChanged = node.operatorToken.kind >= 56 /* FirstAssignment */ &&\n node.operatorToken.kind <= 68 /* LastAssignment */ &&\n isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.left);\n if (exportChanged) {\n // emit assignment 'x y' as 'exports(\"x\", x y)'\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithoutSourceMap(node.left);\n write(\"\\\", \");\n }\n if (node.operatorToken.kind === 38 /* AsteriskAsteriskToken */ || node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) {\n // Downleveled emit exponentiation operator using Math.pow\n emitExponentiationOperator(node);\n }\n else {\n emit(node.left);\n // Add indentation before emit the operator if the operator is on different line\n // For example:\n // 3\n // + 2;\n // emitted as\n // 3\n // + 2;\n var indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== 24 /* CommaToken */ ? \" \" : undefined);\n write(ts.tokenToString(node.operatorToken.kind));\n var indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, \" \");\n emit(node.right);\n decreaseIndentIf(indentedBeforeOperator, indentedAfterOperator);\n }\n if (exportChanged) {\n write(\")\");\n }\n }\n }\n function synthesizedNodeStartsOnNewLine(node) {\n return ts.nodeIsSynthesized(node) && node.startsOnNewLine;\n }\n function emitConditionalExpression(node) {\n emit(node.condition);\n var indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, \" \");\n write(\"?\");\n var indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, \" \");\n emit(node.whenTrue);\n decreaseIndentIf(indentedBeforeQuestion, indentedAfterQuestion);\n var indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, \" \");\n write(\":\");\n var indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, \" \");\n emit(node.whenFalse);\n decreaseIndentIf(indentedBeforeColon, indentedAfterColon);\n }\n // Helper function to decrease the indent if we previously indented. Allows multiple\n // previous indent values to be considered at a time. This also allows caller to just\n // call this once, passing in all their appropriate indent values, instead of needing\n // to call this helper function multiple times.\n function decreaseIndentIf(value1, value2) {\n if (value1) {\n decreaseIndent();\n }\n if (value2) {\n decreaseIndent();\n }\n }\n function isSingleLineEmptyBlock(node) {\n if (node && node.kind === 192 /* Block */) {\n var block = node;\n return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block);\n }\n }\n function emitBlock(node) {\n if (isSingleLineEmptyBlock(node)) {\n emitToken(15 /* OpenBraceToken */, node.pos);\n write(\" \");\n emitToken(16 /* CloseBraceToken */, node.statements.end);\n return;\n }\n emitToken(15 /* OpenBraceToken */, node.pos);\n increaseIndent();\n scopeEmitStart(node.parent);\n if (node.kind === 219 /* ModuleBlock */) {\n ts.Debug.assert(node.parent.kind === 218 /* ModuleDeclaration */);\n emitCaptureThisForNodeIfNecessary(node.parent);\n }\n emitLines(node.statements);\n if (node.kind === 219 /* ModuleBlock */) {\n emitTempDeclarations(/*newLine*/ true);\n }\n decreaseIndent();\n writeLine();\n emitToken(16 /* CloseBraceToken */, node.statements.end);\n scopeEmitEnd();\n }\n function emitEmbeddedStatement(node) {\n if (node.kind === 192 /* Block */) {\n write(\" \");\n emit(node);\n }\n else {\n increaseIndent();\n writeLine();\n emit(node);\n decreaseIndent();\n }\n }\n function emitExpressionStatement(node) {\n emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 174 /* ArrowFunction */);\n write(\";\");\n }\n function emitIfStatement(node) {\n var endPos = emitToken(88 /* IfKeyword */, node.pos);\n write(\" \");\n endPos = emitToken(17 /* OpenParenToken */, endPos);\n emit(node.expression);\n emitToken(18 /* CloseParenToken */, node.expression.end);\n emitEmbeddedStatement(node.thenStatement);\n if (node.elseStatement) {\n writeLine();\n emitToken(80 /* ElseKeyword */, node.thenStatement.end);\n if (node.elseStatement.kind === 196 /* IfStatement */) {\n write(\" \");\n emit(node.elseStatement);\n }\n else {\n emitEmbeddedStatement(node.elseStatement);\n }\n }\n }\n function emitDoStatement(node) {\n write(\"do\");\n emitEmbeddedStatement(node.statement);\n if (node.statement.kind === 192 /* Block */) {\n write(\" \");\n }\n else {\n writeLine();\n }\n write(\"while (\");\n emit(node.expression);\n write(\");\");\n }\n function emitWhileStatement(node) {\n write(\"while (\");\n emit(node.expression);\n write(\")\");\n emitEmbeddedStatement(node.statement);\n }\n /**\n * Returns true if start of variable declaration list was emitted.\n * Returns false if nothing was written - this can happen for source file level variable declarations\n * in system modules where such variable declarations are hoisted.\n */\n function tryEmitStartOfVariableDeclarationList(decl, startPos) {\n if (shouldHoistVariable(decl, /*checkIfSourceFileLevelDecl*/ true)) {\n // variables in variable declaration list were already hoisted\n return false;\n }\n var tokenKind = 102 /* VarKeyword */;\n if (decl && languageVersion >= 2 /* ES6 */) {\n if (ts.isLet(decl)) {\n tokenKind = 108 /* LetKeyword */;\n }\n else if (ts.isConst(decl)) {\n tokenKind = 74 /* ConstKeyword */;\n }\n }\n if (startPos !== undefined) {\n emitToken(tokenKind, startPos);\n write(\" \");\n }\n else {\n switch (tokenKind) {\n case 102 /* VarKeyword */:\n write(\"var \");\n break;\n case 108 /* LetKeyword */:\n write(\"let \");\n break;\n case 74 /* ConstKeyword */:\n write(\"const \");\n break;\n }\n }\n return true;\n }\n function emitVariableDeclarationListSkippingUninitializedEntries(list) {\n var started = false;\n for (var _a = 0, _b = list.declarations; _a < _b.length; _a++) {\n var decl = _b[_a];\n if (!decl.initializer) {\n continue;\n }\n if (!started) {\n started = true;\n }\n else {\n write(\", \");\n }\n emit(decl);\n }\n return started;\n }\n function emitForStatement(node) {\n var endPos = emitToken(86 /* ForKeyword */, node.pos);\n write(\" \");\n endPos = emitToken(17 /* OpenParenToken */, endPos);\n if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) {\n var variableDeclarationList = node.initializer;\n var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos);\n if (startIsEmitted) {\n emitCommaList(variableDeclarationList.declarations);\n }\n else {\n emitVariableDeclarationListSkippingUninitializedEntries(variableDeclarationList);\n }\n }\n else if (node.initializer) {\n emit(node.initializer);\n }\n write(\";\");\n emitOptional(\" \", node.condition);\n write(\";\");\n emitOptional(\" \", node.incrementor);\n write(\")\");\n emitEmbeddedStatement(node.statement);\n }\n function emitForInOrForOfStatement(node) {\n if (languageVersion < 2 /* ES6 */ && node.kind === 201 /* ForOfStatement */) {\n return emitDownLevelForOfStatement(node);\n }\n var endPos = emitToken(86 /* ForKeyword */, node.pos);\n write(\" \");\n endPos = emitToken(17 /* OpenParenToken */, endPos);\n if (node.initializer.kind === 212 /* VariableDeclarationList */) {\n var variableDeclarationList = node.initializer;\n if (variableDeclarationList.declarations.length >= 1) {\n tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos);\n emit(variableDeclarationList.declarations[0]);\n }\n }\n else {\n emit(node.initializer);\n }\n if (node.kind === 200 /* ForInStatement */) {\n write(\" in \");\n }\n else {\n write(\" of \");\n }\n emit(node.expression);\n emitToken(18 /* CloseParenToken */, node.expression.end);\n emitEmbeddedStatement(node.statement);\n }\n function emitDownLevelForOfStatement(node) {\n // The following ES6 code:\n //\n // for (let v of expr) { }\n //\n // should be emitted as\n //\n // for (let _i = 0, _a = expr; _i < _a.length; _i++) {\n // let v = _a[_i];\n // }\n //\n // where _a and _i are temps emitted to capture the RHS and the counter,\n // respectively.\n // When the left hand side is an expression instead of a let declaration,\n // the \"let v\" is not emitted.\n // When the left hand side is a let/const, the v is renamed if there is\n // another v in scope.\n // Note that all assignments to the LHS are emitted in the body, including\n // all destructuring.\n // Note also that because an extra statement is needed to assign to the LHS,\n // for-of bodies are always emitted as blocks.\n var endPos = emitToken(86 /* ForKeyword */, node.pos);\n write(\" \");\n endPos = emitToken(17 /* OpenParenToken */, endPos);\n // Do not emit the LHS let declaration yet, because it might contain destructuring.\n // Do not call recordTempDeclaration because we are declaring the temps\n // right here. Recording means they will be declared later.\n // In the case where the user wrote an identifier as the RHS, like this:\n //\n // for (let v of arr) { }\n //\n // we don't want to emit a temporary variable for the RHS, just use it directly.\n var rhsIsIdentifier = node.expression.kind === 69 /* Identifier */;\n var counter = createTempVariable(268435456 /* _i */);\n var rhsReference = rhsIsIdentifier ? node.expression : createTempVariable(0 /* Auto */);\n // This is the let keyword for the counter and rhsReference. The let keyword for\n // the LHS will be emitted inside the body.\n emitStart(node.expression);\n write(\"var \");\n // _i = 0\n emitNodeWithoutSourceMap(counter);\n write(\" = 0\");\n emitEnd(node.expression);\n if (!rhsIsIdentifier) {\n // , _a = expr\n write(\", \");\n emitStart(node.expression);\n emitNodeWithoutSourceMap(rhsReference);\n write(\" = \");\n emitNodeWithoutSourceMap(node.expression);\n emitEnd(node.expression);\n }\n write(\"; \");\n // _i < _a.length;\n emitStart(node.initializer);\n emitNodeWithoutSourceMap(counter);\n write(\" < \");\n emitNodeWithCommentsAndWithoutSourcemap(rhsReference);\n write(\".length\");\n emitEnd(node.initializer);\n write(\"; \");\n // _i++)\n emitStart(node.initializer);\n emitNodeWithoutSourceMap(counter);\n write(\"++\");\n emitEnd(node.initializer);\n emitToken(18 /* CloseParenToken */, node.expression.end);\n // Body\n write(\" {\");\n writeLine();\n increaseIndent();\n // Initialize LHS\n // let v = _a[_i];\n var rhsIterationValue = createElementAccessExpression(rhsReference, counter);\n emitStart(node.initializer);\n if (node.initializer.kind === 212 /* VariableDeclarationList */) {\n write(\"var \");\n var variableDeclarationList = node.initializer;\n if (variableDeclarationList.declarations.length > 0) {\n var declaration = variableDeclarationList.declarations[0];\n if (ts.isBindingPattern(declaration.name)) {\n // This works whether the declaration is a var, let, or const.\n // It will use rhsIterationValue _a[_i] as the initializer.\n emitDestructuring(declaration, /*isAssignmentExpressionStatement*/ false, rhsIterationValue);\n }\n else {\n // The following call does not include the initializer, so we have\n // to emit it separately.\n emitNodeWithCommentsAndWithoutSourcemap(declaration);\n write(\" = \");\n emitNodeWithoutSourceMap(rhsIterationValue);\n }\n }\n else {\n // It's an empty declaration list. This can only happen in an error case, if the user wrote\n // for (let of []) {}\n emitNodeWithoutSourceMap(createTempVariable(0 /* Auto */));\n write(\" = \");\n emitNodeWithoutSourceMap(rhsIterationValue);\n }\n }\n else {\n // Initializer is an expression. Emit the expression in the body, so that it's\n // evaluated on every iteration.\n var assignmentExpression = createBinaryExpression(node.initializer, 56 /* EqualsToken */, rhsIterationValue, /*startsOnNewLine*/ false);\n if (node.initializer.kind === 164 /* ArrayLiteralExpression */ || node.initializer.kind === 165 /* ObjectLiteralExpression */) {\n // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause\n // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash.\n emitDestructuring(assignmentExpression, /*isAssignmentExpressionStatement*/ true, /*value*/ undefined);\n }\n else {\n emitNodeWithCommentsAndWithoutSourcemap(assignmentExpression);\n }\n }\n emitEnd(node.initializer);\n write(\";\");\n if (node.statement.kind === 192 /* Block */) {\n emitLines(node.statement.statements);\n }\n else {\n writeLine();\n emit(node.statement);\n }\n writeLine();\n decreaseIndent();\n write(\"}\");\n }\n function emitBreakOrContinueStatement(node) {\n emitToken(node.kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos);\n emitOptional(\" \", node.label);\n write(\";\");\n }\n function emitReturnStatement(node) {\n emitToken(94 /* ReturnKeyword */, node.pos);\n emitOptional(\" \", node.expression);\n write(\";\");\n }\n function emitWithStatement(node) {\n write(\"with (\");\n emit(node.expression);\n write(\")\");\n emitEmbeddedStatement(node.statement);\n }\n function emitSwitchStatement(node) {\n var endPos = emitToken(96 /* SwitchKeyword */, node.pos);\n write(\" \");\n emitToken(17 /* OpenParenToken */, endPos);\n emit(node.expression);\n endPos = emitToken(18 /* CloseParenToken */, node.expression.end);\n write(\" \");\n emitCaseBlock(node.caseBlock, endPos);\n }\n function emitCaseBlock(node, startPos) {\n emitToken(15 /* OpenBraceToken */, startPos);\n increaseIndent();\n emitLines(node.clauses);\n decreaseIndent();\n writeLine();\n emitToken(16 /* CloseBraceToken */, node.clauses.end);\n }\n function nodeStartPositionsAreOnSameLine(node1, node2) {\n return ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) ===\n ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos));\n }\n function nodeEndPositionsAreOnSameLine(node1, node2) {\n return ts.getLineOfLocalPosition(currentSourceFile, node1.end) ===\n ts.getLineOfLocalPosition(currentSourceFile, node2.end);\n }\n function nodeEndIsOnSameLineAsNodeStart(node1, node2) {\n return ts.getLineOfLocalPosition(currentSourceFile, node1.end) ===\n ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos));\n }\n function emitCaseOrDefaultClause(node) {\n if (node.kind === 241 /* CaseClause */) {\n write(\"case \");\n emit(node.expression);\n write(\":\");\n }\n else {\n write(\"default:\");\n }\n if (node.statements.length === 1 && nodeStartPositionsAreOnSameLine(node, node.statements[0])) {\n write(\" \");\n emit(node.statements[0]);\n }\n else {\n increaseIndent();\n emitLines(node.statements);\n decreaseIndent();\n }\n }\n function emitThrowStatement(node) {\n write(\"throw \");\n emit(node.expression);\n write(\";\");\n }\n function emitTryStatement(node) {\n write(\"try \");\n emit(node.tryBlock);\n emit(node.catchClause);\n if (node.finallyBlock) {\n writeLine();\n write(\"finally \");\n emit(node.finallyBlock);\n }\n }\n function emitCatchClause(node) {\n writeLine();\n var endPos = emitToken(72 /* CatchKeyword */, node.pos);\n write(\" \");\n emitToken(17 /* OpenParenToken */, endPos);\n emit(node.variableDeclaration);\n emitToken(18 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : endPos);\n write(\" \");\n emitBlock(node.block);\n }\n function emitDebuggerStatement(node) {\n emitToken(76 /* DebuggerKeyword */, node.pos);\n write(\";\");\n }\n function emitLabelledStatement(node) {\n emit(node.label);\n write(\": \");\n emit(node.statement);\n }\n function getContainingModule(node) {\n do {\n node = node.parent;\n } while (node && node.kind !== 218 /* ModuleDeclaration */);\n return node;\n }\n function emitContainingModuleName(node) {\n var container = getContainingModule(node);\n write(container ? getGeneratedNameForNode(container) : \"exports\");\n }\n function emitModuleMemberName(node) {\n emitStart(node.name);\n if (ts.getCombinedNodeFlags(node) & 1 /* Export */) {\n var container = getContainingModule(node);\n if (container) {\n write(getGeneratedNameForNode(container));\n write(\".\");\n }\n else if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) {\n write(\"exports.\");\n }\n }\n emitNodeWithCommentsAndWithoutSourcemap(node.name);\n emitEnd(node.name);\n }\n function createVoidZero() {\n var zero = ts.createSynthesizedNode(8 /* NumericLiteral */);\n zero.text = \"0\";\n var result = ts.createSynthesizedNode(177 /* VoidExpression */);\n result.expression = zero;\n return result;\n }\n function emitEs6ExportDefaultCompat(node) {\n if (node.parent.kind === 248 /* SourceFile */) {\n ts.Debug.assert(!!(node.flags & 1024 /* Default */) || node.kind === 227 /* ExportAssignment */);\n // only allow export default at a source file level\n if (modulekind === 1 /* CommonJS */ || modulekind === 2 /* AMD */ || modulekind === 3 /* UMD */) {\n if (!currentSourceFile.symbol.exports[\"___esModule\"]) {\n if (languageVersion === 1 /* ES5 */) {\n // default value of configurable, enumerable, writable are `false`.\n write(\"Object.defineProperty(exports, \\\"__esModule\\\", { value: true });\");\n writeLine();\n }\n else if (languageVersion === 0 /* ES3 */) {\n write(\"exports.__esModule = true;\");\n writeLine();\n }\n }\n }\n }\n }\n function emitExportMemberAssignment(node) {\n if (node.flags & 1 /* Export */) {\n writeLine();\n emitStart(node);\n // emit call to exporter only for top level nodes\n if (modulekind === 4 /* System */ && node.parent === currentSourceFile) {\n // emit export default as\n // export(\"default\", )\n write(exportFunctionForFile + \"(\\\"\");\n if (node.flags & 1024 /* Default */) {\n write(\"default\");\n }\n else {\n emitNodeWithCommentsAndWithoutSourcemap(node.name);\n }\n write(\"\\\", \");\n emitDeclarationName(node);\n write(\")\");\n }\n else {\n if (node.flags & 1024 /* Default */) {\n emitEs6ExportDefaultCompat(node);\n if (languageVersion === 0 /* ES3 */) {\n write(\"exports[\\\"default\\\"]\");\n }\n else {\n write(\"exports.default\");\n }\n }\n else {\n emitModuleMemberName(node);\n }\n write(\" = \");\n emitDeclarationName(node);\n }\n emitEnd(node);\n write(\";\");\n }\n }\n function emitExportMemberAssignments(name) {\n if (modulekind === 4 /* System */) {\n return;\n }\n if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) {\n for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) {\n var specifier = _b[_a];\n writeLine();\n emitStart(specifier.name);\n emitContainingModuleName(specifier);\n write(\".\");\n emitNodeWithCommentsAndWithoutSourcemap(specifier.name);\n emitEnd(specifier.name);\n write(\" = \");\n emitExpressionIdentifier(name);\n write(\";\");\n }\n }\n }\n function emitExportSpecifierInSystemModule(specifier) {\n ts.Debug.assert(modulekind === 4 /* System */);\n if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier)) {\n return;\n }\n writeLine();\n emitStart(specifier.name);\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithCommentsAndWithoutSourcemap(specifier.name);\n write(\"\\\", \");\n emitExpressionIdentifier(specifier.propertyName || specifier.name);\n write(\")\");\n emitEnd(specifier.name);\n write(\";\");\n }\n /**\n * Emit an assignment to a given identifier, 'name', with a given expression, 'value'.\n * @param name an identifier as a left-hand-side operand of the assignment\n * @param value an expression as a right-hand-side operand of the assignment\n * @param shouldEmitCommaBeforeAssignment a boolean indicating whether to prefix an assignment with comma\n */\n function emitAssignment(name, value, shouldEmitCommaBeforeAssignment) {\n if (shouldEmitCommaBeforeAssignment) {\n write(\", \");\n }\n var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name);\n if (exportChanged) {\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithCommentsAndWithoutSourcemap(name);\n write(\"\\\", \");\n }\n var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 /* VariableDeclaration */ || name.parent.kind === 163 /* BindingElement */);\n if (isVariableDeclarationOrBindingElement) {\n emitModuleMemberName(name.parent);\n }\n else {\n emit(name);\n }\n write(\" = \");\n emit(value);\n if (exportChanged) {\n write(\")\");\n }\n }\n /**\n * Create temporary variable, emit an assignment of the variable the given expression\n * @param expression an expression to assign to the newly created temporary variable\n * @param canDefineTempVariablesInPlace a boolean indicating whether you can define the temporary variable at an assignment location\n * @param shouldEmitCommaBeforeAssignment a boolean indicating whether an assignment should prefix with comma\n */\n function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment) {\n var identifier = createTempVariable(0 /* Auto */);\n if (!canDefineTempVariablesInPlace) {\n recordTempDeclaration(identifier);\n }\n emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment);\n return identifier;\n }\n function emitDestructuring(root, isAssignmentExpressionStatement, value) {\n var emitCount = 0;\n // An exported declaration is actually emitted as an assignment (to a property on the module object), so\n // temporary variables in an exported declaration need to have real declarations elsewhere\n // Also temporary variables should be explicitly allocated for source level declarations when module target is system\n // because actual variable declarations are hoisted\n var canDefineTempVariablesInPlace = false;\n if (root.kind === 211 /* VariableDeclaration */) {\n var isExported = ts.getCombinedNodeFlags(root) & 1 /* Export */;\n var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root);\n canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind;\n }\n else if (root.kind === 138 /* Parameter */) {\n canDefineTempVariablesInPlace = true;\n }\n if (root.kind === 181 /* BinaryExpression */) {\n emitAssignmentExpression(root);\n }\n else {\n ts.Debug.assert(!isAssignmentExpressionStatement);\n emitBindingElement(root, value);\n }\n /**\n * Ensures that there exists a declared identifier whose value holds the given expression.\n * This function is useful to ensure that the expression's value can be read from in subsequent expressions.\n * Unless 'reuseIdentifierExpressions' is false, 'expr' will be returned if it is just an identifier.\n *\n * @param expr the expression whose value needs to be bound.\n * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;\n * false if it is necessary to always emit an identifier.\n */\n function ensureIdentifier(expr, reuseIdentifierExpressions) {\n if (expr.kind === 69 /* Identifier */ && reuseIdentifierExpressions) {\n return expr;\n }\n var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0);\n emitCount++;\n return identifier;\n }\n function createDefaultValueCheck(value, defaultValue) {\n // The value expression will be evaluated twice, so for anything but a simple identifier\n // we need to generate a temporary variable\n value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true);\n // Return the expression 'value === void 0 ? defaultValue : value'\n var equals = ts.createSynthesizedNode(181 /* BinaryExpression */);\n equals.left = value;\n equals.operatorToken = ts.createSynthesizedNode(32 /* EqualsEqualsEqualsToken */);\n equals.right = createVoidZero();\n return createConditionalExpression(equals, defaultValue, value);\n }\n function createConditionalExpression(condition, whenTrue, whenFalse) {\n var cond = ts.createSynthesizedNode(182 /* ConditionalExpression */);\n cond.condition = condition;\n cond.questionToken = ts.createSynthesizedNode(53 /* QuestionToken */);\n cond.whenTrue = whenTrue;\n cond.colonToken = ts.createSynthesizedNode(54 /* ColonToken */);\n cond.whenFalse = whenFalse;\n return cond;\n }\n function createNumericLiteral(value) {\n var node = ts.createSynthesizedNode(8 /* NumericLiteral */);\n node.text = \"\" + value;\n return node;\n }\n function createPropertyAccessForDestructuringProperty(object, propName) {\n // We create a synthetic copy of the identifier in order to avoid the rewriting that might\n // otherwise occur when the identifier is emitted.\n var syntheticName = ts.createSynthesizedNode(propName.kind);\n syntheticName.text = propName.text;\n if (syntheticName.kind !== 69 /* Identifier */) {\n return createElementAccessExpression(object, syntheticName);\n }\n return createPropertyAccessExpression(object, syntheticName);\n }\n function createSliceCall(value, sliceIndex) {\n var call = ts.createSynthesizedNode(168 /* CallExpression */);\n var sliceIdentifier = ts.createSynthesizedNode(69 /* Identifier */);\n sliceIdentifier.text = \"slice\";\n call.expression = createPropertyAccessExpression(value, sliceIdentifier);\n call.arguments = ts.createSynthesizedNodeArray();\n call.arguments[0] = createNumericLiteral(sliceIndex);\n return call;\n }\n function emitObjectLiteralAssignment(target, value) {\n var properties = target.properties;\n if (properties.length !== 1) {\n // For anything but a single element destructuring we need to generate a temporary\n // to ensure value is evaluated exactly once.\n value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true);\n }\n for (var _a = 0; _a < properties.length; _a++) {\n var p = properties[_a];\n if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) {\n var propName = p.name;\n var target_1 = p.kind === 246 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName;\n emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName));\n }\n }\n }\n function emitArrayLiteralAssignment(target, value) {\n var elements = target.elements;\n if (elements.length !== 1) {\n // For anything but a single element destructuring we need to generate a temporary\n // to ensure value is evaluated exactly once.\n value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true);\n }\n for (var i = 0; i < elements.length; i++) {\n var e = elements[i];\n if (e.kind !== 187 /* OmittedExpression */) {\n if (e.kind !== 185 /* SpreadElementExpression */) {\n emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)));\n }\n else if (i === elements.length - 1) {\n emitDestructuringAssignment(e.expression, createSliceCall(value, i));\n }\n }\n }\n }\n function emitDestructuringAssignment(target, value) {\n if (target.kind === 246 /* ShorthandPropertyAssignment */) {\n if (target.objectAssignmentInitializer) {\n value = createDefaultValueCheck(value, target.objectAssignmentInitializer);\n }\n target = target.name;\n }\n else if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) {\n value = createDefaultValueCheck(value, target.right);\n target = target.left;\n }\n if (target.kind === 165 /* ObjectLiteralExpression */) {\n emitObjectLiteralAssignment(target, value);\n }\n else if (target.kind === 164 /* ArrayLiteralExpression */) {\n emitArrayLiteralAssignment(target, value);\n }\n else {\n emitAssignment(target, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0);\n emitCount++;\n }\n }\n function emitAssignmentExpression(root) {\n var target = root.left;\n var value = root.right;\n if (ts.isEmptyObjectLiteralOrArrayLiteral(target)) {\n emit(value);\n }\n else if (isAssignmentExpressionStatement) {\n emitDestructuringAssignment(target, value);\n }\n else {\n if (root.parent.kind !== 172 /* ParenthesizedExpression */) {\n write(\"(\");\n }\n value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true);\n emitDestructuringAssignment(target, value);\n write(\", \");\n emit(value);\n if (root.parent.kind !== 172 /* ParenthesizedExpression */) {\n write(\")\");\n }\n }\n }\n function emitBindingElement(target, value) {\n if (target.initializer) {\n // Combine value and initializer\n value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer;\n }\n else if (!value) {\n // Use 'void 0' in absence of value and initializer\n value = createVoidZero();\n }\n if (ts.isBindingPattern(target.name)) {\n var pattern = target.name;\n var elements = pattern.elements;\n var numElements = elements.length;\n if (numElements !== 1) {\n // For anything other than a single-element destructuring we need to generate a temporary\n // to ensure value is evaluated exactly once. Additionally, if we have zero elements\n // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,\n // so in that case, we'll intentionally create that temporary.\n value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0);\n }\n for (var i = 0; i < numElements; i++) {\n var element = elements[i];\n if (pattern.kind === 161 /* ObjectBindingPattern */) {\n // Rewrite element to a declaration with an initializer that fetches property\n var propName = element.propertyName || element.name;\n emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName));\n }\n else if (element.kind !== 187 /* OmittedExpression */) {\n if (!element.dotDotDotToken) {\n // Rewrite element to a declaration that accesses array element at index i\n emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i)));\n }\n else if (i === numElements - 1) {\n emitBindingElement(element, createSliceCall(value, i));\n }\n }\n }\n }\n else {\n emitAssignment(target.name, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0);\n emitCount++;\n }\n }\n }\n function emitVariableDeclaration(node) {\n if (ts.isBindingPattern(node.name)) {\n if (languageVersion < 2 /* ES6 */) {\n emitDestructuring(node, /*isAssignmentExpressionStatement*/ false);\n }\n else {\n emit(node.name);\n emitOptional(\" = \", node.initializer);\n }\n }\n else {\n var initializer = node.initializer;\n if (!initializer && languageVersion < 2 /* ES6 */) {\n // downlevel emit for non-initialized let bindings defined in loops\n // for (...) { let x; }\n // should be\n // for (...) { var = void 0; }\n // this is necessary to preserve ES6 semantic in scenarios like\n // for (...) { let x; console.log(x); x = 1 } // assignment on one iteration should not affect other iterations\n var isUninitializedLet = (resolver.getNodeCheckFlags(node) & 16384 /* BlockScopedBindingInLoop */) &&\n (getCombinedFlagsForIdentifier(node.name) & 16384 /* Let */);\n // NOTE: default initialization should not be added to let bindings in for-in\\for-of statements\n if (isUninitializedLet &&\n node.parent.parent.kind !== 200 /* ForInStatement */ &&\n node.parent.parent.kind !== 201 /* ForOfStatement */) {\n initializer = createVoidZero();\n }\n }\n var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name);\n if (exportChanged) {\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithCommentsAndWithoutSourcemap(node.name);\n write(\"\\\", \");\n }\n emitModuleMemberName(node);\n emitOptional(\" = \", initializer);\n if (exportChanged) {\n write(\")\");\n }\n }\n }\n function emitExportVariableAssignments(node) {\n if (node.kind === 187 /* OmittedExpression */) {\n return;\n }\n var name = node.name;\n if (name.kind === 69 /* Identifier */) {\n emitExportMemberAssignments(name);\n }\n else if (ts.isBindingPattern(name)) {\n ts.forEach(name.elements, emitExportVariableAssignments);\n }\n }\n function getCombinedFlagsForIdentifier(node) {\n if (!node.parent || (node.parent.kind !== 211 /* VariableDeclaration */ && node.parent.kind !== 163 /* BindingElement */)) {\n return 0;\n }\n return ts.getCombinedNodeFlags(node.parent);\n }\n function isES6ExportedDeclaration(node) {\n return !!(node.flags & 1 /* Export */) &&\n modulekind === 5 /* ES6 */ &&\n node.parent.kind === 248 /* SourceFile */;\n }\n function emitVariableStatement(node) {\n var startIsEmitted = false;\n if (node.flags & 1 /* Export */) {\n if (isES6ExportedDeclaration(node)) {\n // Exported ES6 module member\n write(\"export \");\n startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList);\n }\n }\n else {\n startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList);\n }\n if (startIsEmitted) {\n emitCommaList(node.declarationList.declarations);\n write(\";\");\n }\n else {\n var atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList);\n if (atLeastOneItem) {\n write(\";\");\n }\n }\n if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) {\n ts.forEach(node.declarationList.declarations, emitExportVariableAssignments);\n }\n }\n function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) {\n // If we're not exporting the variables, there's nothing special here.\n // Always emit comments for these nodes.\n if (!(node.flags & 1 /* Export */)) {\n return true;\n }\n // If we are exporting, but it's a top-level ES6 module exports,\n // we'll emit the declaration list verbatim, so emit comments too.\n if (isES6ExportedDeclaration(node)) {\n return true;\n }\n // Otherwise, only emit if we have at least one initializer present.\n for (var _a = 0, _b = node.declarationList.declarations; _a < _b.length; _a++) {\n var declaration = _b[_a];\n if (declaration.initializer) {\n return true;\n }\n }\n return false;\n }\n function emitParameter(node) {\n if (languageVersion < 2 /* ES6 */) {\n if (ts.isBindingPattern(node.name)) {\n var name_24 = createTempVariable(0 /* Auto */);\n if (!tempParameters) {\n tempParameters = [];\n }\n tempParameters.push(name_24);\n emit(name_24);\n }\n else {\n emit(node.name);\n }\n }\n else {\n if (node.dotDotDotToken) {\n write(\"...\");\n }\n emit(node.name);\n emitOptional(\" = \", node.initializer);\n }\n }\n function emitDefaultValueAssignments(node) {\n if (languageVersion < 2 /* ES6 */) {\n var tempIndex = 0;\n ts.forEach(node.parameters, function (parameter) {\n // A rest parameter cannot have a binding pattern or an initializer,\n // so let's just ignore it.\n if (parameter.dotDotDotToken) {\n return;\n }\n var paramName = parameter.name, initializer = parameter.initializer;\n if (ts.isBindingPattern(paramName)) {\n // In cases where a binding pattern is simply '[]' or '{}',\n // we usually don't want to emit a var declaration; however, in the presence\n // of an initializer, we must emit that expression to preserve side effects.\n var hasBindingElements = paramName.elements.length > 0;\n if (hasBindingElements || initializer) {\n writeLine();\n write(\"var \");\n if (hasBindingElements) {\n emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]);\n }\n else {\n emit(tempParameters[tempIndex]);\n write(\" = \");\n emit(initializer);\n }\n write(\";\");\n tempIndex++;\n }\n }\n else if (initializer) {\n writeLine();\n emitStart(parameter);\n write(\"if (\");\n emitNodeWithoutSourceMap(paramName);\n write(\" === void 0)\");\n emitEnd(parameter);\n write(\" { \");\n emitStart(parameter);\n emitNodeWithCommentsAndWithoutSourcemap(paramName);\n write(\" = \");\n emitNodeWithCommentsAndWithoutSourcemap(initializer);\n emitEnd(parameter);\n write(\"; }\");\n }\n });\n }\n }\n function emitRestParameter(node) {\n if (languageVersion < 2 /* ES6 */ && ts.hasRestParameter(node)) {\n var restIndex = node.parameters.length - 1;\n var restParam = node.parameters[restIndex];\n // A rest parameter cannot have a binding pattern, so let's just ignore it if it does.\n if (ts.isBindingPattern(restParam.name)) {\n return;\n }\n var tempName = createTempVariable(268435456 /* _i */).text;\n writeLine();\n emitLeadingComments(restParam);\n emitStart(restParam);\n write(\"var \");\n emitNodeWithCommentsAndWithoutSourcemap(restParam.name);\n write(\" = [];\");\n emitEnd(restParam);\n emitTrailingComments(restParam);\n writeLine();\n write(\"for (\");\n emitStart(restParam);\n write(\"var \" + tempName + \" = \" + restIndex + \";\");\n emitEnd(restParam);\n write(\" \");\n emitStart(restParam);\n write(tempName + \" < arguments.length;\");\n emitEnd(restParam);\n write(\" \");\n emitStart(restParam);\n write(tempName + \"++\");\n emitEnd(restParam);\n write(\") {\");\n increaseIndent();\n writeLine();\n emitStart(restParam);\n emitNodeWithCommentsAndWithoutSourcemap(restParam.name);\n write(\"[\" + tempName + \" - \" + restIndex + \"] = arguments[\" + tempName + \"];\");\n emitEnd(restParam);\n decreaseIndent();\n writeLine();\n write(\"}\");\n }\n }\n function emitAccessor(node) {\n write(node.kind === 145 /* GetAccessor */ ? \"get \" : \"set \");\n emit(node.name);\n emitSignatureAndBody(node);\n }\n function shouldEmitAsArrowFunction(node) {\n return node.kind === 174 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */;\n }\n function emitDeclarationName(node) {\n if (node.name) {\n emitNodeWithCommentsAndWithoutSourcemap(node.name);\n }\n else {\n write(getGeneratedNameForNode(node));\n }\n }\n function shouldEmitFunctionName(node) {\n if (node.kind === 173 /* FunctionExpression */) {\n // Emit name if one is present\n return !!node.name;\n }\n if (node.kind === 213 /* FunctionDeclaration */) {\n // Emit name if one is present, or emit generated name in down-level case (for export default case)\n return !!node.name || languageVersion < 2 /* ES6 */;\n }\n }\n function emitFunctionDeclaration(node) {\n if (ts.nodeIsMissing(node.body)) {\n return emitCommentsOnNotEmittedNode(node);\n }\n // TODO (yuisu) : we should not have special cases to condition emitting comments\n // but have one place to fix check for these conditions.\n if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */ &&\n node.parent && node.parent.kind !== 245 /* PropertyAssignment */ &&\n node.parent.kind !== 168 /* CallExpression */) {\n // 1. Methods will emit the comments as part of emitting method declaration\n // 2. If the function is a property of object literal, emitting leading-comments\n // is done by emitNodeWithoutSourceMap which then call this function.\n // In particular, we would like to avoid emit comments twice in following case:\n // For example:\n // var obj = {\n // id:\n // /*comment*/ () => void\n // }\n // 3. If the function is an argument in call expression, emitting of comments will be\n // taken care of in emit list of arguments inside of emitCallexpression\n emitLeadingComments(node);\n }\n emitStart(node);\n // For targeting below es6, emit functions-like declaration including arrow function using function keyword.\n // When targeting ES6, emit arrow function natively in ES6 by omitting function keyword and using fat arrow instead\n if (!shouldEmitAsArrowFunction(node)) {\n if (isES6ExportedDeclaration(node)) {\n write(\"export \");\n if (node.flags & 1024 /* Default */) {\n write(\"default \");\n }\n }\n write(\"function\");\n if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) {\n write(\"*\");\n }\n write(\" \");\n }\n if (shouldEmitFunctionName(node)) {\n emitDeclarationName(node);\n }\n emitSignatureAndBody(node);\n if (modulekind !== 5 /* ES6 */ && node.kind === 213 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) {\n emitExportMemberAssignments(node.name);\n }\n emitEnd(node);\n if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */) {\n emitTrailingComments(node);\n }\n }\n function emitCaptureThisForNodeIfNecessary(node) {\n if (resolver.getNodeCheckFlags(node) & 4 /* CaptureThis */) {\n writeLine();\n emitStart(node);\n write(\"var _this = this;\");\n emitEnd(node);\n }\n }\n function emitSignatureParameters(node) {\n increaseIndent();\n write(\"(\");\n if (node) {\n var parameters = node.parameters;\n var omitCount = languageVersion < 2 /* ES6 */ && ts.hasRestParameter(node) ? 1 : 0;\n emitList(parameters, 0, parameters.length - omitCount, /*multiLine*/ false, /*trailingComma*/ false);\n }\n write(\")\");\n decreaseIndent();\n }\n function emitSignatureParametersForArrow(node) {\n // Check whether the parameter list needs parentheses and preserve no-parenthesis\n if (node.parameters.length === 1 && node.pos === node.parameters[0].pos) {\n emit(node.parameters[0]);\n return;\n }\n emitSignatureParameters(node);\n }\n function emitAsyncFunctionBodyForES6(node) {\n var promiseConstructor = ts.getEntityNameFromTypeNode(node.type);\n var isArrowFunction = node.kind === 174 /* ArrowFunction */;\n var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096 /* CaptureArguments */) !== 0;\n var args;\n // An async function is emit as an outer function that calls an inner\n // generator function. To preserve lexical bindings, we pass the current\n // `this` and `arguments` objects to `__awaiter`. The generator function\n // passed to `__awaiter` is executed inside of the callback to the\n // promise constructor.\n //\n // The emit for an async arrow without a lexical `arguments` binding might be:\n //\n // // input\n // let a = async (b) => { await b; }\n //\n // // output\n // let a = (b) => __awaiter(this, void 0, void 0, function* () {\n // yield b;\n // });\n //\n // The emit for an async arrow with a lexical `arguments` binding might be:\n //\n // // input\n // let a = async (b) => { await arguments[0]; }\n //\n // // output\n // let a = (b) => __awaiter(this, arguments, void 0, function* (arguments) {\n // yield arguments[0];\n // });\n //\n // The emit for an async function expression without a lexical `arguments` binding\n // might be:\n //\n // // input\n // let a = async function (b) {\n // await b;\n // }\n //\n // // output\n // let a = function (b) {\n // return __awaiter(this, void 0, void 0, function* () {\n // yield b;\n // });\n // }\n //\n // The emit for an async function expression with a lexical `arguments` binding\n // might be:\n //\n // // input\n // let a = async function (b) {\n // await arguments[0];\n // }\n //\n // // output\n // let a = function (b) {\n // return __awaiter(this, arguments, void 0, function* (_arguments) {\n // yield _arguments[0];\n // });\n // }\n //\n // The emit for an async function expression with a lexical `arguments` binding\n // and a return type annotation might be:\n //\n // // input\n // let a = async function (b): MyPromise {\n // await arguments[0];\n // }\n //\n // // output\n // let a = function (b) {\n // return __awaiter(this, arguments, MyPromise, function* (_arguments) {\n // yield _arguments[0];\n // });\n // }\n //\n // If this is not an async arrow, emit the opening brace of the function body\n // and the start of the return statement.\n if (!isArrowFunction) {\n write(\" {\");\n increaseIndent();\n writeLine();\n write(\"return\");\n }\n write(\" __awaiter(this\");\n if (hasLexicalArguments) {\n write(\", arguments\");\n }\n else {\n write(\", void 0\");\n }\n if (promiseConstructor) {\n write(\", \");\n emitNodeWithoutSourceMap(promiseConstructor);\n }\n else {\n write(\", Promise\");\n }\n // Emit the call to __awaiter.\n if (hasLexicalArguments) {\n write(\", function* (_arguments)\");\n }\n else {\n write(\", function* ()\");\n }\n // Emit the signature and body for the inner generator function.\n emitFunctionBody(node);\n write(\")\");\n // If this is not an async arrow, emit the closing brace of the outer function body.\n if (!isArrowFunction) {\n write(\";\");\n decreaseIndent();\n writeLine();\n write(\"}\");\n }\n }\n function emitFunctionBody(node) {\n if (!node.body) {\n // There can be no body when there are parse errors. Just emit an empty block\n // in that case.\n write(\" { }\");\n }\n else {\n if (node.body.kind === 192 /* Block */) {\n emitBlockFunctionBody(node, node.body);\n }\n else {\n emitExpressionFunctionBody(node, node.body);\n }\n }\n }\n function emitSignatureAndBody(node) {\n var saveTempFlags = tempFlags;\n var saveTempVariables = tempVariables;\n var saveTempParameters = tempParameters;\n tempFlags = 0;\n tempVariables = undefined;\n tempParameters = undefined;\n // When targeting ES6, emit arrow function natively in ES6\n if (shouldEmitAsArrowFunction(node)) {\n emitSignatureParametersForArrow(node);\n write(\" =>\");\n }\n else {\n emitSignatureParameters(node);\n }\n var isAsync = ts.isAsyncFunctionLike(node);\n if (isAsync && languageVersion === 2 /* ES6 */) {\n emitAsyncFunctionBodyForES6(node);\n }\n else {\n emitFunctionBody(node);\n }\n if (!isES6ExportedDeclaration(node)) {\n emitExportMemberAssignment(node);\n }\n tempFlags = saveTempFlags;\n tempVariables = saveTempVariables;\n tempParameters = saveTempParameters;\n }\n // Returns true if any preamble code was emitted.\n function emitFunctionBodyPreamble(node) {\n emitCaptureThisForNodeIfNecessary(node);\n emitDefaultValueAssignments(node);\n emitRestParameter(node);\n }\n function emitExpressionFunctionBody(node, body) {\n if (languageVersion < 2 /* ES6 */ || node.flags & 512 /* Async */) {\n emitDownLevelExpressionFunctionBody(node, body);\n return;\n }\n // For es6 and higher we can emit the expression as is. However, in the case\n // where the expression might end up looking like a block when emitted, we'll\n // also wrap it in parentheses first. For example if you have: a => {}\n // then we need to generate: a => ({})\n write(\" \");\n // Unwrap all type assertions.\n var current = body;\n while (current.kind === 171 /* TypeAssertionExpression */) {\n current = current.expression;\n }\n emitParenthesizedIf(body, current.kind === 165 /* ObjectLiteralExpression */);\n }\n function emitDownLevelExpressionFunctionBody(node, body) {\n write(\" {\");\n scopeEmitStart(node);\n increaseIndent();\n var outPos = writer.getTextPos();\n emitDetachedComments(node.body);\n emitFunctionBodyPreamble(node);\n var preambleEmitted = writer.getTextPos() !== outPos;\n decreaseIndent();\n // If we didn't have to emit any preamble code, then attempt to keep the arrow\n // function on one line.\n if (!preambleEmitted && nodeStartPositionsAreOnSameLine(node, body)) {\n write(\" \");\n emitStart(body);\n write(\"return \");\n emit(body);\n emitEnd(body);\n write(\";\");\n emitTempDeclarations(/*newLine*/ false);\n write(\" \");\n }\n else {\n increaseIndent();\n writeLine();\n emitLeadingComments(node.body);\n write(\"return \");\n emit(body);\n write(\";\");\n emitTrailingComments(node.body);\n emitTempDeclarations(/*newLine*/ true);\n decreaseIndent();\n writeLine();\n }\n emitStart(node.body);\n write(\"}\");\n emitEnd(node.body);\n scopeEmitEnd();\n }\n function emitBlockFunctionBody(node, body) {\n write(\" {\");\n scopeEmitStart(node);\n var initialTextPos = writer.getTextPos();\n increaseIndent();\n emitDetachedComments(body.statements);\n // Emit all the directive prologues (like \"use strict\"). These have to come before\n // any other preamble code we write (like parameter initializers).\n var startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true);\n emitFunctionBodyPreamble(node);\n decreaseIndent();\n var preambleEmitted = writer.getTextPos() !== initialTextPos;\n if (!preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) {\n for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {\n var statement = _b[_a];\n write(\" \");\n emit(statement);\n }\n emitTempDeclarations(/*newLine*/ false);\n write(\" \");\n emitLeadingCommentsOfPosition(body.statements.end);\n }\n else {\n increaseIndent();\n emitLinesStartingAt(body.statements, startIndex);\n emitTempDeclarations(/*newLine*/ true);\n writeLine();\n emitLeadingCommentsOfPosition(body.statements.end);\n decreaseIndent();\n }\n emitToken(16 /* CloseBraceToken */, body.statements.end);\n scopeEmitEnd();\n }\n function findInitialSuperCall(ctor) {\n if (ctor.body) {\n var statement = ctor.body.statements[0];\n if (statement && statement.kind === 195 /* ExpressionStatement */) {\n var expr = statement.expression;\n if (expr && expr.kind === 168 /* CallExpression */) {\n var func = expr.expression;\n if (func && func.kind === 95 /* SuperKeyword */) {\n return statement;\n }\n }\n }\n }\n }\n function emitParameterPropertyAssignments(node) {\n ts.forEach(node.parameters, function (param) {\n if (param.flags & 112 /* AccessibilityModifier */) {\n writeLine();\n emitStart(param);\n emitStart(param.name);\n write(\"this.\");\n emitNodeWithoutSourceMap(param.name);\n emitEnd(param.name);\n write(\" = \");\n emit(param.name);\n write(\";\");\n emitEnd(param);\n }\n });\n }\n function emitMemberAccessForPropertyName(memberName) {\n // This does not emit source map because it is emitted by caller as caller\n // is aware how the property name changes to the property access\n // eg. public x = 10; becomes this.x and static x = 10 becomes className.x\n if (memberName.kind === 9 /* StringLiteral */ || memberName.kind === 8 /* NumericLiteral */) {\n write(\"[\");\n emitNodeWithCommentsAndWithoutSourcemap(memberName);\n write(\"]\");\n }\n else if (memberName.kind === 136 /* ComputedPropertyName */) {\n emitComputedPropertyName(memberName);\n }\n else {\n write(\".\");\n emitNodeWithCommentsAndWithoutSourcemap(memberName);\n }\n }\n function getInitializedProperties(node, isStatic) {\n var properties = [];\n for (var _a = 0, _b = node.members; _a < _b.length; _a++) {\n var member = _b[_a];\n if (member.kind === 141 /* PropertyDeclaration */ && isStatic === ((member.flags & 128 /* Static */) !== 0) && member.initializer) {\n properties.push(member);\n }\n }\n return properties;\n }\n function emitPropertyDeclarations(node, properties) {\n for (var _a = 0; _a < properties.length; _a++) {\n var property = properties[_a];\n emitPropertyDeclaration(node, property);\n }\n }\n function emitPropertyDeclaration(node, property, receiver, isExpression) {\n writeLine();\n emitLeadingComments(property);\n emitStart(property);\n emitStart(property.name);\n if (receiver) {\n emit(receiver);\n }\n else {\n if (property.flags & 128 /* Static */) {\n emitDeclarationName(node);\n }\n else {\n write(\"this\");\n }\n }\n emitMemberAccessForPropertyName(property.name);\n emitEnd(property.name);\n write(\" = \");\n emit(property.initializer);\n if (!isExpression) {\n write(\";\");\n }\n emitEnd(property);\n emitTrailingComments(property);\n }\n function emitMemberFunctionsForES5AndLower(node) {\n ts.forEach(node.members, function (member) {\n if (member.kind === 191 /* SemicolonClassElement */) {\n writeLine();\n write(\";\");\n }\n else if (member.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) {\n if (!member.body) {\n return emitCommentsOnNotEmittedNode(member);\n }\n writeLine();\n emitLeadingComments(member);\n emitStart(member);\n emitStart(member.name);\n emitClassMemberPrefix(node, member);\n emitMemberAccessForPropertyName(member.name);\n emitEnd(member.name);\n write(\" = \");\n emitFunctionDeclaration(member);\n emitEnd(member);\n write(\";\");\n emitTrailingComments(member);\n }\n else if (member.kind === 145 /* GetAccessor */ || member.kind === 146 /* SetAccessor */) {\n var accessors = ts.getAllAccessorDeclarations(node.members, member);\n if (member === accessors.firstAccessor) {\n writeLine();\n emitStart(member);\n write(\"Object.defineProperty(\");\n emitStart(member.name);\n emitClassMemberPrefix(node, member);\n write(\", \");\n emitExpressionForPropertyName(member.name);\n emitEnd(member.name);\n write(\", {\");\n increaseIndent();\n if (accessors.getAccessor) {\n writeLine();\n emitLeadingComments(accessors.getAccessor);\n write(\"get: \");\n emitStart(accessors.getAccessor);\n write(\"function \");\n emitSignatureAndBody(accessors.getAccessor);\n emitEnd(accessors.getAccessor);\n emitTrailingComments(accessors.getAccessor);\n write(\",\");\n }\n if (accessors.setAccessor) {\n writeLine();\n emitLeadingComments(accessors.setAccessor);\n write(\"set: \");\n emitStart(accessors.setAccessor);\n write(\"function \");\n emitSignatureAndBody(accessors.setAccessor);\n emitEnd(accessors.setAccessor);\n emitTrailingComments(accessors.setAccessor);\n write(\",\");\n }\n writeLine();\n write(\"enumerable: true,\");\n writeLine();\n write(\"configurable: true\");\n decreaseIndent();\n writeLine();\n write(\"});\");\n emitEnd(member);\n }\n }\n });\n }\n function emitMemberFunctionsForES6AndHigher(node) {\n for (var _a = 0, _b = node.members; _a < _b.length; _a++) {\n var member = _b[_a];\n if ((member.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) && !member.body) {\n emitCommentsOnNotEmittedNode(member);\n }\n else if (member.kind === 143 /* MethodDeclaration */ ||\n member.kind === 145 /* GetAccessor */ ||\n member.kind === 146 /* SetAccessor */) {\n writeLine();\n emitLeadingComments(member);\n emitStart(member);\n if (member.flags & 128 /* Static */) {\n write(\"static \");\n }\n if (member.kind === 145 /* GetAccessor */) {\n write(\"get \");\n }\n else if (member.kind === 146 /* SetAccessor */) {\n write(\"set \");\n }\n if (member.asteriskToken) {\n write(\"*\");\n }\n emit(member.name);\n emitSignatureAndBody(member);\n emitEnd(member);\n emitTrailingComments(member);\n }\n else if (member.kind === 191 /* SemicolonClassElement */) {\n writeLine();\n write(\";\");\n }\n }\n }\n function emitConstructor(node, baseTypeElement) {\n var saveTempFlags = tempFlags;\n var saveTempVariables = tempVariables;\n var saveTempParameters = tempParameters;\n tempFlags = 0;\n tempVariables = undefined;\n tempParameters = undefined;\n emitConstructorWorker(node, baseTypeElement);\n tempFlags = saveTempFlags;\n tempVariables = saveTempVariables;\n tempParameters = saveTempParameters;\n }\n function emitConstructorWorker(node, baseTypeElement) {\n // Check if we have property assignment inside class declaration.\n // If there is property assignment, we need to emit constructor whether users define it or not\n // If there is no property assignment, we can omit constructor if users do not define it\n var hasInstancePropertyWithInitializer = false;\n // Emit the constructor overload pinned comments\n ts.forEach(node.members, function (member) {\n if (member.kind === 144 /* Constructor */ && !member.body) {\n emitCommentsOnNotEmittedNode(member);\n }\n // Check if there is any non-static property assignment\n if (member.kind === 141 /* PropertyDeclaration */ && member.initializer && (member.flags & 128 /* Static */) === 0) {\n hasInstancePropertyWithInitializer = true;\n }\n });\n var ctor = ts.getFirstConstructorWithBody(node);\n // For target ES6 and above, if there is no user-defined constructor and there is no property assignment\n // do not emit constructor in class declaration.\n if (languageVersion >= 2 /* ES6 */ && !ctor && !hasInstancePropertyWithInitializer) {\n return;\n }\n if (ctor) {\n emitLeadingComments(ctor);\n }\n emitStart(ctor || node);\n if (languageVersion < 2 /* ES6 */) {\n write(\"function \");\n emitDeclarationName(node);\n emitSignatureParameters(ctor);\n }\n else {\n write(\"constructor\");\n if (ctor) {\n emitSignatureParameters(ctor);\n }\n else {\n // Based on EcmaScript6 section 14.5.14: Runtime Semantics: ClassDefinitionEvaluation.\n // If constructor is empty, then,\n // If ClassHeritageopt is present, then\n // Let constructor be the result of parsing the String \"constructor(... args){ super (...args);}\" using the syntactic grammar with the goal symbol MethodDefinition.\n // Else,\n // Let constructor be the result of parsing the String \"constructor( ){ }\" using the syntactic grammar with the goal symbol MethodDefinition\n if (baseTypeElement) {\n write(\"(...args)\");\n }\n else {\n write(\"()\");\n }\n }\n }\n var startIndex = 0;\n write(\" {\");\n scopeEmitStart(node, \"constructor\");\n increaseIndent();\n if (ctor) {\n // Emit all the directive prologues (like \"use strict\"). These have to come before\n // any other preamble code we write (like parameter initializers).\n startIndex = emitDirectivePrologues(ctor.body.statements, /*startWithNewLine*/ true);\n emitDetachedComments(ctor.body.statements);\n }\n emitCaptureThisForNodeIfNecessary(node);\n var superCall;\n if (ctor) {\n emitDefaultValueAssignments(ctor);\n emitRestParameter(ctor);\n if (baseTypeElement) {\n superCall = findInitialSuperCall(ctor);\n if (superCall) {\n writeLine();\n emit(superCall);\n }\n }\n emitParameterPropertyAssignments(ctor);\n }\n else {\n if (baseTypeElement) {\n writeLine();\n emitStart(baseTypeElement);\n if (languageVersion < 2 /* ES6 */) {\n write(\"_super.apply(this, arguments);\");\n }\n else {\n write(\"super(...args);\");\n }\n emitEnd(baseTypeElement);\n }\n }\n emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ false));\n if (ctor) {\n var statements = ctor.body.statements;\n if (superCall) {\n statements = statements.slice(1);\n }\n emitLinesStartingAt(statements, startIndex);\n }\n emitTempDeclarations(/*newLine*/ true);\n writeLine();\n if (ctor) {\n emitLeadingCommentsOfPosition(ctor.body.statements.end);\n }\n decreaseIndent();\n emitToken(16 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end);\n scopeEmitEnd();\n emitEnd(ctor || node);\n if (ctor) {\n emitTrailingComments(ctor);\n }\n }\n function emitClassExpression(node) {\n return emitClassLikeDeclaration(node);\n }\n function emitClassDeclaration(node) {\n return emitClassLikeDeclaration(node);\n }\n function emitClassLikeDeclaration(node) {\n if (languageVersion < 2 /* ES6 */) {\n emitClassLikeDeclarationBelowES6(node);\n }\n else {\n emitClassLikeDeclarationForES6AndHigher(node);\n }\n if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile && node.name) {\n emitExportMemberAssignments(node.name);\n }\n }\n function emitClassLikeDeclarationForES6AndHigher(node) {\n var thisNodeIsDecorated = ts.nodeIsDecorated(node);\n if (node.kind === 214 /* ClassDeclaration */) {\n if (thisNodeIsDecorated) {\n // To preserve the correct runtime semantics when decorators are applied to the class,\n // the emit needs to follow one of the following rules:\n //\n // * For a local class declaration:\n //\n // @dec class C {\n // }\n //\n // The emit should be:\n //\n // let C = class {\n // };\n // C = __decorate([dec], C);\n //\n // * For an exported class declaration:\n //\n // @dec export class C {\n // }\n //\n // The emit should be:\n //\n // export let C = class {\n // };\n // C = __decorate([dec], C);\n //\n // * For a default export of a class declaration with a name:\n //\n // @dec default export class C {\n // }\n //\n // The emit should be:\n //\n // let C = class {\n // }\n // C = __decorate([dec], C);\n // export default C;\n //\n // * For a default export of a class declaration without a name:\n //\n // @dec default export class {\n // }\n //\n // The emit should be:\n //\n // let _default = class {\n // }\n // _default = __decorate([dec], _default);\n // export default _default;\n //\n if (isES6ExportedDeclaration(node) && !(node.flags & 1024 /* Default */)) {\n write(\"export \");\n }\n write(\"let \");\n emitDeclarationName(node);\n write(\" = \");\n }\n else if (isES6ExportedDeclaration(node)) {\n write(\"export \");\n if (node.flags & 1024 /* Default */) {\n write(\"default \");\n }\n }\n }\n // If the class has static properties, and it's a class expression, then we'll need\n // to specialize the emit a bit. for a class expression of the form:\n //\n // class C { static a = 1; static b = 2; ... }\n //\n // We'll emit:\n //\n // (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp)\n //\n // This keeps the expression as an expression, while ensuring that the static parts\n // of it have been initialized by the time it is used.\n var staticProperties = getInitializedProperties(node, /*static:*/ true);\n var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 186 /* ClassExpression */;\n var tempVariable;\n if (isClassExpressionWithStaticProperties) {\n tempVariable = createAndRecordTempVariable(0 /* Auto */);\n write(\"(\");\n increaseIndent();\n emit(tempVariable);\n write(\" = \");\n }\n write(\"class\");\n // emit name if\n // - node has a name\n // - this is default export with static initializers\n if ((node.name || (node.flags & 1024 /* Default */ && staticProperties.length > 0)) && !thisNodeIsDecorated) {\n write(\" \");\n emitDeclarationName(node);\n }\n var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node);\n if (baseTypeNode) {\n write(\" extends \");\n emit(baseTypeNode.expression);\n }\n write(\" {\");\n increaseIndent();\n scopeEmitStart(node);\n writeLine();\n emitConstructor(node, baseTypeNode);\n emitMemberFunctionsForES6AndHigher(node);\n decreaseIndent();\n writeLine();\n emitToken(16 /* CloseBraceToken */, node.members.end);\n scopeEmitEnd();\n // TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now.\n // For a decorated class, we need to assign its name (if it has one). This is because we emit\n // the class as a class expression to avoid the double-binding of the identifier:\n //\n // let C = class {\n // }\n // Object.defineProperty(C, \"name\", { value: \"C\", configurable: true });\n //\n if (thisNodeIsDecorated) {\n write(\";\");\n }\n // Emit static property assignment. Because classDeclaration is lexically evaluated,\n // it is safe to emit static property assignment after classDeclaration\n // From ES6 specification:\n // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using\n // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.\n if (isClassExpressionWithStaticProperties) {\n for (var _a = 0; _a < staticProperties.length; _a++) {\n var property = staticProperties[_a];\n write(\",\");\n writeLine();\n emitPropertyDeclaration(node, property, /*receiver:*/ tempVariable, /*isExpression:*/ true);\n }\n write(\",\");\n writeLine();\n emit(tempVariable);\n decreaseIndent();\n write(\")\");\n }\n else {\n writeLine();\n emitPropertyDeclarations(node, staticProperties);\n emitDecoratorsOfClass(node);\n }\n // If this is an exported class, but not on the top level (i.e. on an internal\n // module), export it\n if (!isES6ExportedDeclaration(node) && (node.flags & 1 /* Export */)) {\n writeLine();\n emitStart(node);\n emitModuleMemberName(node);\n write(\" = \");\n emitDeclarationName(node);\n emitEnd(node);\n write(\";\");\n }\n else if (isES6ExportedDeclaration(node) && (node.flags & 1024 /* Default */) && thisNodeIsDecorated) {\n // if this is a top level default export of decorated class, write the export after the declaration.\n writeLine();\n write(\"export default \");\n emitDeclarationName(node);\n write(\";\");\n }\n }\n function emitClassLikeDeclarationBelowES6(node) {\n if (node.kind === 214 /* ClassDeclaration */) {\n // source file level classes in system modules are hoisted so 'var's for them are already defined\n if (!shouldHoistDeclarationInSystemJsModule(node)) {\n write(\"var \");\n }\n emitDeclarationName(node);\n write(\" = \");\n }\n write(\"(function (\");\n var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node);\n if (baseTypeNode) {\n write(\"_super\");\n }\n write(\") {\");\n var saveTempFlags = tempFlags;\n var saveTempVariables = tempVariables;\n var saveTempParameters = tempParameters;\n var saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames;\n tempFlags = 0;\n tempVariables = undefined;\n tempParameters = undefined;\n computedPropertyNamesToGeneratedNames = undefined;\n increaseIndent();\n scopeEmitStart(node);\n if (baseTypeNode) {\n writeLine();\n emitStart(baseTypeNode);\n write(\"__extends(\");\n emitDeclarationName(node);\n write(\", _super);\");\n emitEnd(baseTypeNode);\n }\n writeLine();\n emitConstructor(node, baseTypeNode);\n emitMemberFunctionsForES5AndLower(node);\n emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ true));\n writeLine();\n emitDecoratorsOfClass(node);\n writeLine();\n emitToken(16 /* CloseBraceToken */, node.members.end, function () {\n write(\"return \");\n emitDeclarationName(node);\n });\n write(\";\");\n emitTempDeclarations(/*newLine*/ true);\n tempFlags = saveTempFlags;\n tempVariables = saveTempVariables;\n tempParameters = saveTempParameters;\n computedPropertyNamesToGeneratedNames = saveComputedPropertyNamesToGeneratedNames;\n decreaseIndent();\n writeLine();\n emitToken(16 /* CloseBraceToken */, node.members.end);\n scopeEmitEnd();\n emitStart(node);\n write(\")(\");\n if (baseTypeNode) {\n emit(baseTypeNode.expression);\n }\n write(\")\");\n if (node.kind === 214 /* ClassDeclaration */) {\n write(\";\");\n }\n emitEnd(node);\n if (node.kind === 214 /* ClassDeclaration */) {\n emitExportMemberAssignment(node);\n }\n }\n function emitClassMemberPrefix(node, member) {\n emitDeclarationName(node);\n if (!(member.flags & 128 /* Static */)) {\n write(\".prototype\");\n }\n }\n function emitDecoratorsOfClass(node) {\n emitDecoratorsOfMembers(node, /*staticFlag*/ 0);\n emitDecoratorsOfMembers(node, 128 /* Static */);\n emitDecoratorsOfConstructor(node);\n }\n function emitDecoratorsOfConstructor(node) {\n var decorators = node.decorators;\n var constructor = ts.getFirstConstructorWithBody(node);\n var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated);\n // skip decoration of the constructor if neither it nor its parameters are decorated\n if (!decorators && !hasDecoratedParameters) {\n return;\n }\n // Emit the call to __decorate. Given the class:\n //\n // @dec\n // class C {\n // }\n //\n // The emit for the class is:\n //\n // C = __decorate([dec], C);\n //\n writeLine();\n emitStart(node);\n emitDeclarationName(node);\n write(\" = __decorate([\");\n increaseIndent();\n writeLine();\n var decoratorCount = decorators ? decorators.length : 0;\n var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) {\n emitStart(decorator);\n emit(decorator.expression);\n emitEnd(decorator);\n });\n argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0);\n emitSerializedTypeMetadata(node, /*leadingComma*/ argumentsWritten >= 0);\n decreaseIndent();\n writeLine();\n write(\"], \");\n emitDeclarationName(node);\n write(\");\");\n emitEnd(node);\n writeLine();\n }\n function emitDecoratorsOfMembers(node, staticFlag) {\n for (var _a = 0, _b = node.members; _a < _b.length; _a++) {\n var member = _b[_a];\n // only emit members in the correct group\n if ((member.flags & 128 /* Static */) !== staticFlag) {\n continue;\n }\n // skip members that cannot be decorated (such as the constructor)\n if (!ts.nodeCanBeDecorated(member)) {\n continue;\n }\n // skip a member if it or any of its parameters are not decorated\n if (!ts.nodeOrChildIsDecorated(member)) {\n continue;\n }\n // skip an accessor declaration if it is not the first accessor\n var decorators = void 0;\n var functionLikeMember = void 0;\n if (ts.isAccessor(member)) {\n var accessors = ts.getAllAccessorDeclarations(node.members, member);\n if (member !== accessors.firstAccessor) {\n continue;\n }\n // get the decorators from the first accessor with decorators\n decorators = accessors.firstAccessor.decorators;\n if (!decorators && accessors.secondAccessor) {\n decorators = accessors.secondAccessor.decorators;\n }\n // we only decorate parameters of the set accessor\n functionLikeMember = accessors.setAccessor;\n }\n else {\n decorators = member.decorators;\n // we only decorate the parameters here if this is a method\n if (member.kind === 143 /* MethodDeclaration */) {\n functionLikeMember = member;\n }\n }\n // Emit the call to __decorate. Given the following:\n //\n // class C {\n // @dec method(@dec2 x) {}\n // @dec get accessor() {}\n // @dec prop;\n // }\n //\n // The emit for a method is:\n //\n // __decorate([\n // dec,\n // __param(0, dec2),\n // __metadata(\"design:type\", Function),\n // __metadata(\"design:paramtypes\", [Object]),\n // __metadata(\"design:returntype\", void 0)\n // ], C.prototype, \"method\", undefined);\n //\n // The emit for an accessor is:\n //\n // __decorate([\n // dec\n // ], C.prototype, \"accessor\", undefined);\n //\n // The emit for a property is:\n //\n // __decorate([\n // dec\n // ], C.prototype, \"prop\");\n //\n writeLine();\n emitStart(member);\n write(\"__decorate([\");\n increaseIndent();\n writeLine();\n var decoratorCount = decorators ? decorators.length : 0;\n var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) {\n emitStart(decorator);\n emit(decorator.expression);\n emitEnd(decorator);\n });\n argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0);\n emitSerializedTypeMetadata(member, argumentsWritten > 0);\n decreaseIndent();\n writeLine();\n write(\"], \");\n emitStart(member.name);\n emitClassMemberPrefix(node, member);\n write(\", \");\n emitExpressionForPropertyName(member.name);\n emitEnd(member.name);\n if (languageVersion > 0 /* ES3 */) {\n if (member.kind !== 141 /* PropertyDeclaration */) {\n // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.\n // We have this extra argument here so that we can inject an explicit property descriptor at a later date.\n write(\", null\");\n }\n else {\n // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it\n // should not invoke `Object.getOwnPropertyDescriptor`.\n write(\", void 0\");\n }\n }\n write(\");\");\n emitEnd(member);\n writeLine();\n }\n }\n function emitDecoratorsOfParameters(node, leadingComma) {\n var argumentsWritten = 0;\n if (node) {\n var parameterIndex = 0;\n for (var _a = 0, _b = node.parameters; _a < _b.length; _a++) {\n var parameter = _b[_a];\n if (ts.nodeIsDecorated(parameter)) {\n var decorators = parameter.decorators;\n argumentsWritten += emitList(decorators, 0, decorators.length, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ leadingComma, /*noTrailingNewLine*/ true, function (decorator) {\n emitStart(decorator);\n write(\"__param(\" + parameterIndex + \", \");\n emit(decorator.expression);\n write(\")\");\n emitEnd(decorator);\n });\n leadingComma = true;\n }\n ++parameterIndex;\n }\n }\n return argumentsWritten;\n }\n function shouldEmitTypeMetadata(node) {\n // This method determines whether to emit the \"design:type\" metadata based on the node's kind.\n // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata\n // compiler option is set.\n switch (node.kind) {\n case 143 /* MethodDeclaration */:\n case 145 /* GetAccessor */:\n case 146 /* SetAccessor */:\n case 141 /* PropertyDeclaration */:\n return true;\n }\n return false;\n }\n function shouldEmitReturnTypeMetadata(node) {\n // This method determines whether to emit the \"design:returntype\" metadata based on the node's kind.\n // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata\n // compiler option is set.\n switch (node.kind) {\n case 143 /* MethodDeclaration */:\n return true;\n }\n return false;\n }\n function shouldEmitParamTypesMetadata(node) {\n // This method determines whether to emit the \"design:paramtypes\" metadata based on the node's kind.\n // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata\n // compiler option is set.\n switch (node.kind) {\n case 214 /* ClassDeclaration */:\n case 143 /* MethodDeclaration */:\n case 146 /* SetAccessor */:\n return true;\n }\n return false;\n }\n /** Serializes the type of a declaration to an appropriate JS constructor value. Used by the __metadata decorator for a class member. */\n function emitSerializedTypeOfNode(node) {\n // serialization of the type of a declaration uses the following rules:\n //\n // * The serialized type of a ClassDeclaration is \"Function\"\n // * The serialized type of a ParameterDeclaration is the serialized type of its type annotation.\n // * The serialized type of a PropertyDeclaration is the serialized type of its type annotation.\n // * The serialized type of an AccessorDeclaration is the serialized type of the return type annotation of its getter or parameter type annotation of its setter.\n // * The serialized type of any other FunctionLikeDeclaration is \"Function\".\n // * The serialized type of any other node is \"void 0\".\n //\n // For rules on serializing type annotations, see `serializeTypeNode`.\n switch (node.kind) {\n case 214 /* ClassDeclaration */:\n write(\"Function\");\n return;\n case 141 /* PropertyDeclaration */:\n emitSerializedTypeNode(node.type);\n return;\n case 138 /* Parameter */:\n emitSerializedTypeNode(node.type);\n return;\n case 145 /* GetAccessor */:\n emitSerializedTypeNode(node.type);\n return;\n case 146 /* SetAccessor */:\n emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node));\n return;\n }\n if (ts.isFunctionLike(node)) {\n write(\"Function\");\n return;\n }\n write(\"void 0\");\n }\n function emitSerializedTypeNode(node) {\n if (node) {\n switch (node.kind) {\n case 103 /* VoidKeyword */:\n write(\"void 0\");\n return;\n case 160 /* ParenthesizedType */:\n emitSerializedTypeNode(node.type);\n return;\n case 152 /* FunctionType */:\n case 153 /* ConstructorType */:\n write(\"Function\");\n return;\n case 156 /* ArrayType */:\n case 157 /* TupleType */:\n write(\"Array\");\n return;\n case 150 /* TypePredicate */:\n case 120 /* BooleanKeyword */:\n write(\"Boolean\");\n return;\n case 130 /* StringKeyword */:\n case 9 /* StringLiteral */:\n write(\"String\");\n return;\n case 128 /* NumberKeyword */:\n write(\"Number\");\n return;\n case 131 /* SymbolKeyword */:\n write(\"Symbol\");\n return;\n case 151 /* TypeReference */:\n emitSerializedTypeReferenceNode(node);\n return;\n case 154 /* TypeQuery */:\n case 155 /* TypeLiteral */:\n case 158 /* UnionType */:\n case 159 /* IntersectionType */:\n case 117 /* AnyKeyword */:\n break;\n default:\n ts.Debug.fail(\"Cannot serialize unexpected type node.\");\n break;\n }\n }\n write(\"Object\");\n }\n /** Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator. */\n function emitSerializedTypeReferenceNode(node) {\n var location = node.parent;\n while (ts.isDeclaration(location) || ts.isTypeNode(location)) {\n location = location.parent;\n }\n // Clone the type name and parent it to a location outside of the current declaration.\n var typeName = ts.cloneEntityName(node.typeName);\n typeName.parent = location;\n var result = resolver.getTypeReferenceSerializationKind(typeName);\n switch (result) {\n case ts.TypeReferenceSerializationKind.Unknown:\n var temp = createAndRecordTempVariable(0 /* Auto */);\n write(\"(typeof (\");\n emitNodeWithoutSourceMap(temp);\n write(\" = \");\n emitEntityNameAsExpression(typeName, /*useFallback*/ true);\n write(\") === 'function' && \");\n emitNodeWithoutSourceMap(temp);\n write(\") || Object\");\n break;\n case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:\n emitEntityNameAsExpression(typeName, /*useFallback*/ false);\n break;\n case ts.TypeReferenceSerializationKind.VoidType:\n write(\"void 0\");\n break;\n case ts.TypeReferenceSerializationKind.BooleanType:\n write(\"Boolean\");\n break;\n case ts.TypeReferenceSerializationKind.NumberLikeType:\n write(\"Number\");\n break;\n case ts.TypeReferenceSerializationKind.StringLikeType:\n write(\"String\");\n break;\n case ts.TypeReferenceSerializationKind.ArrayLikeType:\n write(\"Array\");\n break;\n case ts.TypeReferenceSerializationKind.ESSymbolType:\n if (languageVersion < 2 /* ES6 */) {\n write(\"typeof Symbol === 'function' ? Symbol : Object\");\n }\n else {\n write(\"Symbol\");\n }\n break;\n case ts.TypeReferenceSerializationKind.TypeWithCallSignature:\n write(\"Function\");\n break;\n case ts.TypeReferenceSerializationKind.ObjectType:\n write(\"Object\");\n break;\n }\n }\n /** Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor. */\n function emitSerializedParameterTypesOfNode(node) {\n // serialization of parameter types uses the following rules:\n //\n // * If the declaration is a class, the parameters of the first constructor with a body are used.\n // * If the declaration is function-like and has a body, the parameters of the function are used.\n //\n // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`.\n if (node) {\n var valueDeclaration;\n if (node.kind === 214 /* ClassDeclaration */) {\n valueDeclaration = ts.getFirstConstructorWithBody(node);\n }\n else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) {\n valueDeclaration = node;\n }\n if (valueDeclaration) {\n var parameters = valueDeclaration.parameters;\n var parameterCount = parameters.length;\n if (parameterCount > 0) {\n for (var i = 0; i < parameterCount; i++) {\n if (i > 0) {\n write(\", \");\n }\n if (parameters[i].dotDotDotToken) {\n var parameterType = parameters[i].type;\n if (parameterType.kind === 156 /* ArrayType */) {\n parameterType = parameterType.elementType;\n }\n else if (parameterType.kind === 151 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) {\n parameterType = parameterType.typeArguments[0];\n }\n else {\n parameterType = undefined;\n }\n emitSerializedTypeNode(parameterType);\n }\n else {\n emitSerializedTypeOfNode(parameters[i]);\n }\n }\n }\n }\n }\n }\n /** Serializes the return type of function. Used by the __metadata decorator for a method. */\n function emitSerializedReturnTypeOfNode(node) {\n if (node && ts.isFunctionLike(node) && node.type) {\n emitSerializedTypeNode(node.type);\n return;\n }\n write(\"void 0\");\n }\n function emitSerializedTypeMetadata(node, writeComma) {\n // This method emits the serialized type metadata for a decorator target.\n // The caller should have already tested whether the node has decorators.\n var argumentsWritten = 0;\n if (compilerOptions.emitDecoratorMetadata) {\n if (shouldEmitTypeMetadata(node)) {\n if (writeComma) {\n write(\", \");\n }\n writeLine();\n write(\"__metadata('design:type', \");\n emitSerializedTypeOfNode(node);\n write(\")\");\n argumentsWritten++;\n }\n if (shouldEmitParamTypesMetadata(node)) {\n if (writeComma || argumentsWritten) {\n write(\", \");\n }\n writeLine();\n write(\"__metadata('design:paramtypes', [\");\n emitSerializedParameterTypesOfNode(node);\n write(\"])\");\n argumentsWritten++;\n }\n if (shouldEmitReturnTypeMetadata(node)) {\n if (writeComma || argumentsWritten) {\n write(\", \");\n }\n writeLine();\n write(\"__metadata('design:returntype', \");\n emitSerializedReturnTypeOfNode(node);\n write(\")\");\n argumentsWritten++;\n }\n }\n return argumentsWritten;\n }\n function emitInterfaceDeclaration(node) {\n emitCommentsOnNotEmittedNode(node);\n }\n function shouldEmitEnumDeclaration(node) {\n var isConstEnum = ts.isConst(node);\n return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules;\n }\n function emitEnumDeclaration(node) {\n // const enums are completely erased during compilation.\n if (!shouldEmitEnumDeclaration(node)) {\n return;\n }\n if (!shouldHoistDeclarationInSystemJsModule(node)) {\n // do not emit var if variable was already hoisted\n if (!(node.flags & 1 /* Export */) || isES6ExportedDeclaration(node)) {\n emitStart(node);\n if (isES6ExportedDeclaration(node)) {\n write(\"export \");\n }\n write(\"var \");\n emit(node.name);\n emitEnd(node);\n write(\";\");\n }\n }\n writeLine();\n emitStart(node);\n write(\"(function (\");\n emitStart(node.name);\n write(getGeneratedNameForNode(node));\n emitEnd(node.name);\n write(\") {\");\n increaseIndent();\n scopeEmitStart(node);\n emitLines(node.members);\n decreaseIndent();\n writeLine();\n emitToken(16 /* CloseBraceToken */, node.members.end);\n scopeEmitEnd();\n write(\")(\");\n emitModuleMemberName(node);\n write(\" || (\");\n emitModuleMemberName(node);\n write(\" = {}));\");\n emitEnd(node);\n if (!isES6ExportedDeclaration(node) && node.flags & 1 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) {\n // do not emit var if variable was already hoisted\n writeLine();\n emitStart(node);\n write(\"var \");\n emit(node.name);\n write(\" = \");\n emitModuleMemberName(node);\n emitEnd(node);\n write(\";\");\n }\n if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) {\n if (modulekind === 4 /* System */ && (node.flags & 1 /* Export */)) {\n // write the call to exporter for enum\n writeLine();\n write(exportFunctionForFile + \"(\\\"\");\n emitDeclarationName(node);\n write(\"\\\", \");\n emitDeclarationName(node);\n write(\");\");\n }\n emitExportMemberAssignments(node.name);\n }\n }\n function emitEnumMember(node) {\n var enumParent = node.parent;\n emitStart(node);\n write(getGeneratedNameForNode(enumParent));\n write(\"[\");\n write(getGeneratedNameForNode(enumParent));\n write(\"[\");\n emitExpressionForPropertyName(node.name);\n write(\"] = \");\n writeEnumMemberDeclarationValue(node);\n write(\"] = \");\n emitExpressionForPropertyName(node.name);\n emitEnd(node);\n write(\";\");\n }\n function writeEnumMemberDeclarationValue(member) {\n var value = resolver.getConstantValue(member);\n if (value !== undefined) {\n write(value.toString());\n return;\n }\n else if (member.initializer) {\n emit(member.initializer);\n }\n else {\n write(\"undefined\");\n }\n }\n function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {\n if (moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) {\n var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);\n return recursiveInnerModule || moduleDeclaration.body;\n }\n }\n function shouldEmitModuleDeclaration(node) {\n return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules);\n }\n function isModuleMergedWithES6Class(node) {\n return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 32768 /* LexicalModuleMergesWithClass */);\n }\n function emitModuleDeclaration(node) {\n // Emit only if this module is non-ambient.\n var shouldEmit = shouldEmitModuleDeclaration(node);\n if (!shouldEmit) {\n return emitCommentsOnNotEmittedNode(node);\n }\n var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node);\n var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node);\n if (emitVarForModule) {\n emitStart(node);\n if (isES6ExportedDeclaration(node)) {\n write(\"export \");\n }\n write(\"var \");\n emit(node.name);\n write(\";\");\n emitEnd(node);\n writeLine();\n }\n emitStart(node);\n write(\"(function (\");\n emitStart(node.name);\n write(getGeneratedNameForNode(node));\n emitEnd(node.name);\n write(\") \");\n if (node.body.kind === 219 /* ModuleBlock */) {\n var saveTempFlags = tempFlags;\n var saveTempVariables = tempVariables;\n tempFlags = 0;\n tempVariables = undefined;\n emit(node.body);\n tempFlags = saveTempFlags;\n tempVariables = saveTempVariables;\n }\n else {\n write(\"{\");\n increaseIndent();\n scopeEmitStart(node);\n emitCaptureThisForNodeIfNecessary(node);\n writeLine();\n emit(node.body);\n decreaseIndent();\n writeLine();\n var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;\n emitToken(16 /* CloseBraceToken */, moduleBlock.statements.end);\n scopeEmitEnd();\n }\n write(\")(\");\n // write moduleDecl = containingModule.m only if it is not exported es6 module member\n if ((node.flags & 1 /* Export */) && !isES6ExportedDeclaration(node)) {\n emit(node.name);\n write(\" = \");\n }\n emitModuleMemberName(node);\n write(\" || (\");\n emitModuleMemberName(node);\n write(\" = {}));\");\n emitEnd(node);\n if (!isES6ExportedDeclaration(node) && node.name.kind === 69 /* Identifier */ && node.parent === currentSourceFile) {\n if (modulekind === 4 /* System */ && (node.flags & 1 /* Export */)) {\n writeLine();\n write(exportFunctionForFile + \"(\\\"\");\n emitDeclarationName(node);\n write(\"\\\", \");\n emitDeclarationName(node);\n write(\");\");\n }\n emitExportMemberAssignments(node.name);\n }\n }\n /*\n * Some bundlers (SystemJS builder) sometimes want to rename dependencies.\n * Here we check if alternative name was provided for a given moduleName and return it if possible.\n */\n function tryRenameExternalModule(moduleName) {\n if (currentSourceFile.renamedDependencies && ts.hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) {\n return \"\\\"\" + currentSourceFile.renamedDependencies[moduleName.text] + \"\\\"\";\n }\n return undefined;\n }\n function emitRequire(moduleName) {\n if (moduleName.kind === 9 /* StringLiteral */) {\n write(\"require(\");\n var text = tryRenameExternalModule(moduleName);\n if (text) {\n write(text);\n }\n else {\n emitStart(moduleName);\n emitLiteral(moduleName);\n emitEnd(moduleName);\n }\n emitToken(18 /* CloseParenToken */, moduleName.end);\n }\n else {\n write(\"require()\");\n }\n }\n function getNamespaceDeclarationNode(node) {\n if (node.kind === 221 /* ImportEqualsDeclaration */) {\n return node;\n }\n var importClause = node.importClause;\n if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 224 /* NamespaceImport */) {\n return importClause.namedBindings;\n }\n }\n function isDefaultImport(node) {\n return node.kind === 222 /* ImportDeclaration */ && node.importClause && !!node.importClause.name;\n }\n function emitExportImportAssignments(node) {\n if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) {\n emitExportMemberAssignments(node.name);\n }\n ts.forEachChild(node, emitExportImportAssignments);\n }\n function emitImportDeclaration(node) {\n if (modulekind !== 5 /* ES6 */) {\n return emitExternalImportDeclaration(node);\n }\n // ES6 import\n if (node.importClause) {\n var shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause);\n var shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, /* checkChildren */ true);\n if (shouldEmitDefaultBindings || shouldEmitNamedBindings) {\n write(\"import \");\n emitStart(node.importClause);\n if (shouldEmitDefaultBindings) {\n emit(node.importClause.name);\n if (shouldEmitNamedBindings) {\n write(\", \");\n }\n }\n if (shouldEmitNamedBindings) {\n emitLeadingComments(node.importClause.namedBindings);\n emitStart(node.importClause.namedBindings);\n if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) {\n write(\"* as \");\n emit(node.importClause.namedBindings.name);\n }\n else {\n write(\"{ \");\n emitExportOrImportSpecifierList(node.importClause.namedBindings.elements, resolver.isReferencedAliasDeclaration);\n write(\" }\");\n }\n emitEnd(node.importClause.namedBindings);\n emitTrailingComments(node.importClause.namedBindings);\n }\n emitEnd(node.importClause);\n write(\" from \");\n emit(node.moduleSpecifier);\n write(\";\");\n }\n }\n else {\n write(\"import \");\n emit(node.moduleSpecifier);\n write(\";\");\n }\n }\n function emitExternalImportDeclaration(node) {\n if (ts.contains(externalImports, node)) {\n var isExportedImport = node.kind === 221 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0;\n var namespaceDeclaration = getNamespaceDeclarationNode(node);\n if (modulekind !== 2 /* AMD */) {\n emitLeadingComments(node);\n emitStart(node);\n if (namespaceDeclaration && !isDefaultImport(node)) {\n // import x = require(\"foo\")\n // import * as x from \"foo\"\n if (!isExportedImport)\n write(\"var \");\n emitModuleMemberName(namespaceDeclaration);\n write(\" = \");\n }\n else {\n // import \"foo\"\n // import x from \"foo\"\n // import { x, y } from \"foo\"\n // import d, * as x from \"foo\"\n // import d, { x, y } from \"foo\"\n var isNakedImport = 222 /* ImportDeclaration */ && !node.importClause;\n if (!isNakedImport) {\n write(\"var \");\n write(getGeneratedNameForNode(node));\n write(\" = \");\n }\n }\n emitRequire(ts.getExternalModuleName(node));\n if (namespaceDeclaration && isDefaultImport(node)) {\n // import d, * as x from \"foo\"\n write(\", \");\n emitModuleMemberName(namespaceDeclaration);\n write(\" = \");\n write(getGeneratedNameForNode(node));\n }\n write(\";\");\n emitEnd(node);\n emitExportImportAssignments(node);\n emitTrailingComments(node);\n }\n else {\n if (isExportedImport) {\n emitModuleMemberName(namespaceDeclaration);\n write(\" = \");\n emit(namespaceDeclaration.name);\n write(\";\");\n }\n else if (namespaceDeclaration && isDefaultImport(node)) {\n // import d, * as x from \"foo\"\n write(\"var \");\n emitModuleMemberName(namespaceDeclaration);\n write(\" = \");\n write(getGeneratedNameForNode(node));\n write(\";\");\n }\n emitExportImportAssignments(node);\n }\n }\n }\n function emitImportEqualsDeclaration(node) {\n if (ts.isExternalModuleImportEqualsDeclaration(node)) {\n emitExternalImportDeclaration(node);\n return;\n }\n // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when\n // - current file is not external module\n // - import declaration is top level and target is value imported by entity name\n if (resolver.isReferencedAliasDeclaration(node) ||\n (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {\n emitLeadingComments(node);\n emitStart(node);\n // variable declaration for import-equals declaration can be hoisted in system modules\n // in this case 'var' should be omitted and emit should contain only initialization\n var variableDeclarationIsHoisted = shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true);\n // is it top level export import v = a.b.c in system module?\n // if yes - it needs to be rewritten as exporter('v', v = a.b.c)\n var isExported = isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ true);\n if (!variableDeclarationIsHoisted) {\n ts.Debug.assert(!isExported);\n if (isES6ExportedDeclaration(node)) {\n write(\"export \");\n write(\"var \");\n }\n else if (!(node.flags & 1 /* Export */)) {\n write(\"var \");\n }\n }\n if (isExported) {\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithoutSourceMap(node.name);\n write(\"\\\", \");\n }\n emitModuleMemberName(node);\n write(\" = \");\n emit(node.moduleReference);\n if (isExported) {\n write(\")\");\n }\n write(\";\");\n emitEnd(node);\n emitExportImportAssignments(node);\n emitTrailingComments(node);\n }\n }\n function emitExportDeclaration(node) {\n ts.Debug.assert(modulekind !== 4 /* System */);\n if (modulekind !== 5 /* ES6 */) {\n if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) {\n emitStart(node);\n var generatedName = getGeneratedNameForNode(node);\n if (node.exportClause) {\n // export { x, y, ... } from \"foo\"\n if (modulekind !== 2 /* AMD */) {\n write(\"var \");\n write(generatedName);\n write(\" = \");\n emitRequire(ts.getExternalModuleName(node));\n write(\";\");\n }\n for (var _a = 0, _b = node.exportClause.elements; _a < _b.length; _a++) {\n var specifier = _b[_a];\n if (resolver.isValueAliasDeclaration(specifier)) {\n writeLine();\n emitStart(specifier);\n emitContainingModuleName(specifier);\n write(\".\");\n emitNodeWithCommentsAndWithoutSourcemap(specifier.name);\n write(\" = \");\n write(generatedName);\n write(\".\");\n emitNodeWithCommentsAndWithoutSourcemap(specifier.propertyName || specifier.name);\n write(\";\");\n emitEnd(specifier);\n }\n }\n }\n else {\n // export * from \"foo\"\n writeLine();\n write(\"__export(\");\n if (modulekind !== 2 /* AMD */) {\n emitRequire(ts.getExternalModuleName(node));\n }\n else {\n write(generatedName);\n }\n write(\");\");\n }\n emitEnd(node);\n }\n }\n else {\n if (!node.exportClause || resolver.isValueAliasDeclaration(node)) {\n write(\"export \");\n if (node.exportClause) {\n // export { x, y, ... }\n write(\"{ \");\n emitExportOrImportSpecifierList(node.exportClause.elements, resolver.isValueAliasDeclaration);\n write(\" }\");\n }\n else {\n write(\"*\");\n }\n if (node.moduleSpecifier) {\n write(\" from \");\n emit(node.moduleSpecifier);\n }\n write(\";\");\n }\n }\n }\n function emitExportOrImportSpecifierList(specifiers, shouldEmit) {\n ts.Debug.assert(modulekind === 5 /* ES6 */);\n var needsComma = false;\n for (var _a = 0; _a < specifiers.length; _a++) {\n var specifier = specifiers[_a];\n if (shouldEmit(specifier)) {\n if (needsComma) {\n write(\", \");\n }\n if (specifier.propertyName) {\n emit(specifier.propertyName);\n write(\" as \");\n }\n emit(specifier.name);\n needsComma = true;\n }\n }\n }\n function emitExportAssignment(node) {\n if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) {\n if (modulekind === 5 /* ES6 */) {\n writeLine();\n emitStart(node);\n write(\"export default \");\n var expression = node.expression;\n emit(expression);\n if (expression.kind !== 213 /* FunctionDeclaration */ &&\n expression.kind !== 214 /* ClassDeclaration */) {\n write(\";\");\n }\n emitEnd(node);\n }\n else {\n writeLine();\n emitStart(node);\n if (modulekind === 4 /* System */) {\n write(exportFunctionForFile + \"(\\\"default\\\",\");\n emit(node.expression);\n write(\")\");\n }\n else {\n emitEs6ExportDefaultCompat(node);\n emitContainingModuleName(node);\n if (languageVersion === 0 /* ES3 */) {\n write(\"[\\\"default\\\"] = \");\n }\n else {\n write(\".default = \");\n }\n emit(node.expression);\n }\n write(\";\");\n emitEnd(node);\n }\n }\n }\n function collectExternalModuleInfo(sourceFile) {\n externalImports = [];\n exportSpecifiers = {};\n exportEquals = undefined;\n hasExportStars = false;\n for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {\n var node = _b[_a];\n switch (node.kind) {\n case 222 /* ImportDeclaration */:\n if (!node.importClause ||\n resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) {\n // import \"mod\"\n // import x from \"mod\" where x is referenced\n // import * as x from \"mod\" where x is referenced\n // import { x, y } from \"mod\" where at least one import is referenced\n externalImports.push(node);\n }\n break;\n case 221 /* ImportEqualsDeclaration */:\n if (node.moduleReference.kind === 232 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) {\n // import x = require(\"mod\") where x is referenced\n externalImports.push(node);\n }\n break;\n case 228 /* ExportDeclaration */:\n if (node.moduleSpecifier) {\n if (!node.exportClause) {\n // export * from \"mod\"\n externalImports.push(node);\n hasExportStars = true;\n }\n else if (resolver.isValueAliasDeclaration(node)) {\n // export { x, y } from \"mod\" where at least one export is a value symbol\n externalImports.push(node);\n }\n }\n else {\n // export { x, y }\n for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) {\n var specifier = _d[_c];\n var name_25 = (specifier.propertyName || specifier.name).text;\n (exportSpecifiers[name_25] || (exportSpecifiers[name_25] = [])).push(specifier);\n }\n }\n break;\n case 227 /* ExportAssignment */:\n if (node.isExportEquals && !exportEquals) {\n // export = x\n exportEquals = node;\n }\n break;\n }\n }\n }\n function emitExportStarHelper() {\n if (hasExportStars) {\n writeLine();\n write(\"function __export(m) {\");\n increaseIndent();\n writeLine();\n write(\"for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\");\n decreaseIndent();\n writeLine();\n write(\"}\");\n }\n }\n function getLocalNameForExternalImport(node) {\n var namespaceDeclaration = getNamespaceDeclarationNode(node);\n if (namespaceDeclaration && !isDefaultImport(node)) {\n return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name);\n }\n if (node.kind === 222 /* ImportDeclaration */ && node.importClause) {\n return getGeneratedNameForNode(node);\n }\n if (node.kind === 228 /* ExportDeclaration */ && node.moduleSpecifier) {\n return getGeneratedNameForNode(node);\n }\n }\n function getExternalModuleNameText(importNode) {\n var moduleName = ts.getExternalModuleName(importNode);\n if (moduleName.kind === 9 /* StringLiteral */) {\n return tryRenameExternalModule(moduleName) || getLiteralText(moduleName);\n }\n return undefined;\n }\n function emitVariableDeclarationsForImports() {\n if (externalImports.length === 0) {\n return;\n }\n writeLine();\n var started = false;\n for (var _a = 0; _a < externalImports.length; _a++) {\n var importNode = externalImports[_a];\n // do not create variable declaration for exports and imports that lack import clause\n var skipNode = importNode.kind === 228 /* ExportDeclaration */ ||\n (importNode.kind === 222 /* ImportDeclaration */ && !importNode.importClause);\n if (skipNode) {\n continue;\n }\n if (!started) {\n write(\"var \");\n started = true;\n }\n else {\n write(\", \");\n }\n write(getLocalNameForExternalImport(importNode));\n }\n if (started) {\n write(\";\");\n }\n }\n function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) {\n // when resolving exports local exported entries/indirect exported entries in the module\n // should always win over entries with similar names that were added via star exports\n // to support this we store names of local/indirect exported entries in a set.\n // this set is used to filter names brought by star expors.\n if (!hasExportStars) {\n // local names set is needed only in presence of star exports\n return undefined;\n }\n // local names set should only be added if we have anything exported\n if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) {\n // no exported declarations (export var ...) or export specifiers (export {x})\n // check if we have any non star export declarations.\n var hasExportDeclarationWithExportClause = false;\n for (var _a = 0; _a < externalImports.length; _a++) {\n var externalImport = externalImports[_a];\n if (externalImport.kind === 228 /* ExportDeclaration */ && externalImport.exportClause) {\n hasExportDeclarationWithExportClause = true;\n break;\n }\n }\n if (!hasExportDeclarationWithExportClause) {\n // we still need to emit exportStar helper\n return emitExportStarFunction(/*localNames*/ undefined);\n }\n }\n var exportedNamesStorageRef = makeUniqueName(\"exportedNames\");\n writeLine();\n write(\"var \" + exportedNamesStorageRef + \" = {\");\n increaseIndent();\n var started = false;\n if (exportedDeclarations) {\n for (var i = 0; i < exportedDeclarations.length; ++i) {\n // write name of exported declaration, i.e 'export var x...'\n writeExportedName(exportedDeclarations[i]);\n }\n }\n if (exportSpecifiers) {\n for (var n in exportSpecifiers) {\n for (var _b = 0, _c = exportSpecifiers[n]; _b < _c.length; _b++) {\n var specifier = _c[_b];\n // write name of export specified, i.e. 'export {x}'\n writeExportedName(specifier.name);\n }\n }\n }\n for (var _d = 0; _d < externalImports.length; _d++) {\n var externalImport = externalImports[_d];\n if (externalImport.kind !== 228 /* ExportDeclaration */) {\n continue;\n }\n var exportDecl = externalImport;\n if (!exportDecl.exportClause) {\n // export * from ...\n continue;\n }\n for (var _e = 0, _f = exportDecl.exportClause.elements; _e < _f.length; _e++) {\n var element = _f[_e];\n // write name of indirectly exported entry, i.e. 'export {x} from ...'\n writeExportedName(element.name || element.propertyName);\n }\n }\n decreaseIndent();\n writeLine();\n write(\"};\");\n return emitExportStarFunction(exportedNamesStorageRef);\n function emitExportStarFunction(localNames) {\n var exportStarFunction = makeUniqueName(\"exportStar\");\n writeLine();\n // define an export star helper function\n write(\"function \" + exportStarFunction + \"(m) {\");\n increaseIndent();\n writeLine();\n write(\"var exports = {};\");\n writeLine();\n write(\"for(var n in m) {\");\n increaseIndent();\n writeLine();\n write(\"if (n !== \\\"default\\\"\");\n if (localNames) {\n write(\"&& !\" + localNames + \".hasOwnProperty(n)\");\n }\n write(\") exports[n] = m[n];\");\n decreaseIndent();\n writeLine();\n write(\"}\");\n writeLine();\n write(exportFunctionForFile + \"(exports);\");\n decreaseIndent();\n writeLine();\n write(\"}\");\n return exportStarFunction;\n }\n function writeExportedName(node) {\n // do not record default exports\n // they are local to module and never overwritten (explicitly skipped) by star export\n if (node.kind !== 69 /* Identifier */ && node.flags & 1024 /* Default */) {\n return;\n }\n if (started) {\n write(\",\");\n }\n else {\n started = true;\n }\n writeLine();\n write(\"'\");\n if (node.kind === 69 /* Identifier */) {\n emitNodeWithCommentsAndWithoutSourcemap(node);\n }\n else {\n emitDeclarationName(node);\n }\n write(\"': true\");\n }\n }\n function processTopLevelVariableAndFunctionDeclarations(node) {\n // per ES6 spec:\n // 15.2.1.16.4 ModuleDeclarationInstantiation() Concrete Method\n // - var declarations are initialized to undefined - 14.a.ii\n // - function/generator declarations are instantiated - 16.a.iv\n // this means that after module is instantiated but before its evaluation\n // exported functions are already accessible at import sites\n // in theory we should hoist only exported functions and its dependencies\n // in practice to simplify things we'll hoist all source level functions and variable declaration\n // including variables declarations for module and class declarations\n var hoistedVars;\n var hoistedFunctionDeclarations;\n var exportedDeclarations;\n visit(node);\n if (hoistedVars) {\n writeLine();\n write(\"var \");\n var seen = {};\n for (var i = 0; i < hoistedVars.length; ++i) {\n var local = hoistedVars[i];\n var name_26 = local.kind === 69 /* Identifier */\n ? local\n : local.name;\n if (name_26) {\n // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables\n var text = ts.unescapeIdentifier(name_26.text);\n if (ts.hasProperty(seen, text)) {\n continue;\n }\n else {\n seen[text] = text;\n }\n }\n if (i !== 0) {\n write(\", \");\n }\n if (local.kind === 214 /* ClassDeclaration */ || local.kind === 218 /* ModuleDeclaration */ || local.kind === 217 /* EnumDeclaration */) {\n emitDeclarationName(local);\n }\n else {\n emit(local);\n }\n var flags = ts.getCombinedNodeFlags(local.kind === 69 /* Identifier */ ? local.parent : local);\n if (flags & 1 /* Export */) {\n if (!exportedDeclarations) {\n exportedDeclarations = [];\n }\n exportedDeclarations.push(local);\n }\n }\n write(\";\");\n }\n if (hoistedFunctionDeclarations) {\n for (var _a = 0; _a < hoistedFunctionDeclarations.length; _a++) {\n var f = hoistedFunctionDeclarations[_a];\n writeLine();\n emit(f);\n if (f.flags & 1 /* Export */) {\n if (!exportedDeclarations) {\n exportedDeclarations = [];\n }\n exportedDeclarations.push(f);\n }\n }\n }\n return exportedDeclarations;\n function visit(node) {\n if (node.flags & 2 /* Ambient */) {\n return;\n }\n if (node.kind === 213 /* FunctionDeclaration */) {\n if (!hoistedFunctionDeclarations) {\n hoistedFunctionDeclarations = [];\n }\n hoistedFunctionDeclarations.push(node);\n return;\n }\n if (node.kind === 214 /* ClassDeclaration */) {\n if (!hoistedVars) {\n hoistedVars = [];\n }\n hoistedVars.push(node);\n return;\n }\n if (node.kind === 217 /* EnumDeclaration */) {\n if (shouldEmitEnumDeclaration(node)) {\n if (!hoistedVars) {\n hoistedVars = [];\n }\n hoistedVars.push(node);\n }\n return;\n }\n if (node.kind === 218 /* ModuleDeclaration */) {\n if (shouldEmitModuleDeclaration(node)) {\n if (!hoistedVars) {\n hoistedVars = [];\n }\n hoistedVars.push(node);\n }\n return;\n }\n if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) {\n if (shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ false)) {\n var name_27 = node.name;\n if (name_27.kind === 69 /* Identifier */) {\n if (!hoistedVars) {\n hoistedVars = [];\n }\n hoistedVars.push(name_27);\n }\n else {\n ts.forEachChild(name_27, visit);\n }\n }\n return;\n }\n if (ts.isInternalModuleImportEqualsDeclaration(node) && resolver.isValueAliasDeclaration(node)) {\n if (!hoistedVars) {\n hoistedVars = [];\n }\n hoistedVars.push(node.name);\n return;\n }\n if (ts.isBindingPattern(node)) {\n ts.forEach(node.elements, visit);\n return;\n }\n if (!ts.isDeclaration(node)) {\n ts.forEachChild(node, visit);\n }\n }\n }\n function shouldHoistVariable(node, checkIfSourceFileLevelDecl) {\n if (checkIfSourceFileLevelDecl && !shouldHoistDeclarationInSystemJsModule(node)) {\n return false;\n }\n // hoist variable if\n // - it is not block scoped\n // - it is top level block scoped\n // if block scoped variables are nested in some another block then\n // no other functions can use them except ones that are defined at least in the same block\n return (ts.getCombinedNodeFlags(node) & 49152 /* BlockScoped */) === 0 ||\n ts.getEnclosingBlockScopeContainer(node).kind === 248 /* SourceFile */;\n }\n function isCurrentFileSystemExternalModule() {\n return modulekind === 4 /* System */ && ts.isExternalModule(currentSourceFile);\n }\n function emitSystemModuleBody(node, dependencyGroups, startIndex) {\n // shape of the body in system modules:\n // function (exports) {\n // \n // \n // \n // return {\n // setters: [\n // \n // ],\n // execute: function() {\n // \n // }\n // }\n // \n // }\n // I.e:\n // import {x} from 'file1'\n // var y = 1;\n // export function foo() { return y + x(); }\n // console.log(y);\n // will be transformed to\n // function(exports) {\n // var file1; // local alias\n // var y;\n // function foo() { return y + file1.x(); }\n // exports(\"foo\", foo);\n // return {\n // setters: [\n // function(v) { file1 = v }\n // ],\n // execute(): function() {\n // y = 1;\n // console.log(y);\n // }\n // };\n // }\n emitVariableDeclarationsForImports();\n writeLine();\n var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node);\n var exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations);\n writeLine();\n write(\"return {\");\n increaseIndent();\n writeLine();\n emitSetters(exportStarFunction, dependencyGroups);\n writeLine();\n emitExecute(node, startIndex);\n decreaseIndent();\n writeLine();\n write(\"}\"); // return\n emitTempDeclarations(/*newLine*/ true);\n }\n function emitSetters(exportStarFunction, dependencyGroups) {\n write(\"setters:[\");\n for (var i = 0; i < dependencyGroups.length; ++i) {\n if (i !== 0) {\n write(\",\");\n }\n writeLine();\n increaseIndent();\n var group = dependencyGroups[i];\n // derive a unique name for parameter from the first named entry in the group\n var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || \"\");\n write(\"function (\" + parameterName + \") {\");\n increaseIndent();\n for (var _a = 0; _a < group.length; _a++) {\n var entry = group[_a];\n var importVariableName = getLocalNameForExternalImport(entry) || \"\";\n switch (entry.kind) {\n case 222 /* ImportDeclaration */:\n if (!entry.importClause) {\n // 'import \"...\"' case\n // module is imported only for side-effects, no emit required\n break;\n }\n // fall-through\n case 221 /* ImportEqualsDeclaration */:\n ts.Debug.assert(importVariableName !== \"\");\n writeLine();\n // save import into the local\n write(importVariableName + \" = \" + parameterName + \";\");\n writeLine();\n break;\n case 228 /* ExportDeclaration */:\n ts.Debug.assert(importVariableName !== \"\");\n if (entry.exportClause) {\n // export {a, b as c} from 'foo'\n // emit as:\n // exports_({\n // \"a\": _[\"a\"],\n // \"c\": _[\"b\"]\n // });\n writeLine();\n write(exportFunctionForFile + \"({\");\n writeLine();\n increaseIndent();\n for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; ++i_2) {\n if (i_2 !== 0) {\n write(\",\");\n writeLine();\n }\n var e = entry.exportClause.elements[i_2];\n write(\"\\\"\");\n emitNodeWithCommentsAndWithoutSourcemap(e.name);\n write(\"\\\": \" + parameterName + \"[\\\"\");\n emitNodeWithCommentsAndWithoutSourcemap(e.propertyName || e.name);\n write(\"\\\"]\");\n }\n decreaseIndent();\n writeLine();\n write(\"});\");\n }\n else {\n writeLine();\n // export * from 'foo'\n // emit as:\n // exportStar(_foo);\n write(exportStarFunction + \"(\" + parameterName + \");\");\n }\n writeLine();\n break;\n }\n }\n decreaseIndent();\n write(\"}\");\n decreaseIndent();\n }\n write(\"],\");\n }\n function emitExecute(node, startIndex) {\n write(\"execute: function() {\");\n increaseIndent();\n writeLine();\n for (var i = startIndex; i < node.statements.length; ++i) {\n var statement = node.statements[i];\n switch (statement.kind) {\n // - function declarations are not emitted because they were already hoisted\n // - import declarations are not emitted since they are already handled in setters\n // - export declarations with module specifiers are not emitted since they were already written in setters\n // - export declarations without module specifiers are emitted preserving the order\n case 213 /* FunctionDeclaration */:\n case 222 /* ImportDeclaration */:\n continue;\n case 228 /* ExportDeclaration */:\n if (!statement.moduleSpecifier) {\n for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) {\n var element = _b[_a];\n // write call to exporter function for every export specifier in exports list\n emitExportSpecifierInSystemModule(element);\n }\n }\n continue;\n case 221 /* ImportEqualsDeclaration */:\n if (!ts.isInternalModuleImportEqualsDeclaration(statement)) {\n // - import equals declarations that import external modules are not emitted\n continue;\n }\n // fall-though for import declarations that import internal modules\n default:\n writeLine();\n emit(statement);\n }\n }\n decreaseIndent();\n writeLine();\n write(\"}\"); // execute\n }\n function emitSystemModule(node) {\n collectExternalModuleInfo(node);\n // System modules has the following shape\n // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})\n // 'exports' here is a function 'exports(name: string, value: T): T' that is used to publish exported values.\n // 'exports' returns its 'value' argument so in most cases expressions\n // that mutate exported values can be rewritten as:\n // expr -> exports('name', expr).\n // The only exception in this rule is postfix unary operators,\n // see comment to 'emitPostfixUnaryExpression' for more details\n ts.Debug.assert(!exportFunctionForFile);\n // make sure that name of 'exports' function does not conflict with existing identifiers\n exportFunctionForFile = makeUniqueName(\"exports\");\n writeLine();\n write(\"System.register(\");\n if (node.moduleName) {\n write(\"\\\"\" + node.moduleName + \"\\\", \");\n }\n write(\"[\");\n var groupIndices = {};\n var dependencyGroups = [];\n for (var i = 0; i < externalImports.length; ++i) {\n var text = getExternalModuleNameText(externalImports[i]);\n if (ts.hasProperty(groupIndices, text)) {\n // deduplicate/group entries in dependency list by the dependency name\n var groupIndex = groupIndices[text];\n dependencyGroups[groupIndex].push(externalImports[i]);\n continue;\n }\n else {\n groupIndices[text] = dependencyGroups.length;\n dependencyGroups.push([externalImports[i]]);\n }\n if (i !== 0) {\n write(\", \");\n }\n write(text);\n }\n write(\"], function(\" + exportFunctionForFile + \") {\");\n writeLine();\n increaseIndent();\n var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);\n emitEmitHelpers(node);\n emitCaptureThisForNodeIfNecessary(node);\n emitSystemModuleBody(node, dependencyGroups, startIndex);\n decreaseIndent();\n writeLine();\n write(\"});\");\n }\n function getAMDDependencyNames(node, includeNonAmdDependencies) {\n // names of modules with corresponding parameter in the factory function\n var aliasedModuleNames = [];\n // names of modules with no corresponding parameters in factory function\n var unaliasedModuleNames = [];\n var importAliasNames = []; // names of the parameters in the factory function; these\n // parameters need to match the indexes of the corresponding\n // module names in aliasedModuleNames.\n // Fill in amd-dependency tags\n for (var _a = 0, _b = node.amdDependencies; _a < _b.length; _a++) {\n var amdDependency = _b[_a];\n if (amdDependency.name) {\n aliasedModuleNames.push(\"\\\"\" + amdDependency.path + \"\\\"\");\n importAliasNames.push(amdDependency.name);\n }\n else {\n unaliasedModuleNames.push(\"\\\"\" + amdDependency.path + \"\\\"\");\n }\n }\n for (var _c = 0; _c < externalImports.length; _c++) {\n var importNode = externalImports[_c];\n // Find the name of the external module\n var externalModuleName = getExternalModuleNameText(importNode);\n // Find the name of the module alias, if there is one\n var importAliasName = getLocalNameForExternalImport(importNode);\n if (includeNonAmdDependencies && importAliasName) {\n aliasedModuleNames.push(externalModuleName);\n importAliasNames.push(importAliasName);\n }\n else {\n unaliasedModuleNames.push(externalModuleName);\n }\n }\n return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };\n }\n function emitAMDDependencies(node, includeNonAmdDependencies) {\n // An AMD define function has the following shape:\n // define(id?, dependencies?, factory);\n //\n // This has the shape of\n // define(name, [\"module1\", \"module2\"], function (module1Alias) {\n // The location of the alias in the parameter list in the factory function needs to\n // match the position of the module name in the dependency list.\n //\n // To ensure this is true in cases of modules with no aliases, e.g.:\n // `import \"module\"` or ``\n // we need to add modules without alias names to the end of the dependencies list\n var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies);\n emitAMDDependencyList(dependencyNames);\n write(\", \");\n emitAMDFactoryHeader(dependencyNames);\n }\n function emitAMDDependencyList(_a) {\n var aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames;\n write(\"[\\\"require\\\", \\\"exports\\\"\");\n if (aliasedModuleNames.length) {\n write(\", \");\n write(aliasedModuleNames.join(\", \"));\n }\n if (unaliasedModuleNames.length) {\n write(\", \");\n write(unaliasedModuleNames.join(\", \"));\n }\n write(\"]\");\n }\n function emitAMDFactoryHeader(_a) {\n var importAliasNames = _a.importAliasNames;\n write(\"function (require, exports\");\n if (importAliasNames.length) {\n write(\", \");\n write(importAliasNames.join(\", \"));\n }\n write(\") {\");\n }\n function emitAMDModule(node) {\n emitEmitHelpers(node);\n collectExternalModuleInfo(node);\n writeLine();\n write(\"define(\");\n if (node.moduleName) {\n write(\"\\\"\" + node.moduleName + \"\\\", \");\n }\n emitAMDDependencies(node, /*includeNonAmdDependencies*/ true);\n increaseIndent();\n var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);\n emitExportStarHelper();\n emitCaptureThisForNodeIfNecessary(node);\n emitLinesStartingAt(node.statements, startIndex);\n emitTempDeclarations(/*newLine*/ true);\n emitExportEquals(/*emitAsReturn*/ true);\n decreaseIndent();\n writeLine();\n write(\"});\");\n }\n function emitCommonJSModule(node) {\n var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);\n emitEmitHelpers(node);\n collectExternalModuleInfo(node);\n emitExportStarHelper();\n emitCaptureThisForNodeIfNecessary(node);\n emitLinesStartingAt(node.statements, startIndex);\n emitTempDeclarations(/*newLine*/ true);\n emitExportEquals(/*emitAsReturn*/ false);\n }\n function emitUMDModule(node) {\n emitEmitHelpers(node);\n collectExternalModuleInfo(node);\n var dependencyNames = getAMDDependencyNames(node, /*includeNonAmdDependencies*/ false);\n // Module is detected first to support Browserify users that load into a browser with an AMD loader\n writeLines(\"(function (factory) {\\n if (typeof module === 'object' && typeof module.exports === 'object') {\\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\\n }\\n else if (typeof define === 'function' && define.amd) {\\n define(\");\n emitAMDDependencyList(dependencyNames);\n write(\", factory);\");\n writeLines(\" }\\n})(\");\n emitAMDFactoryHeader(dependencyNames);\n increaseIndent();\n var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);\n emitExportStarHelper();\n emitCaptureThisForNodeIfNecessary(node);\n emitLinesStartingAt(node.statements, startIndex);\n emitTempDeclarations(/*newLine*/ true);\n emitExportEquals(/*emitAsReturn*/ true);\n decreaseIndent();\n writeLine();\n write(\"});\");\n }\n function emitES6Module(node) {\n externalImports = undefined;\n exportSpecifiers = undefined;\n exportEquals = undefined;\n hasExportStars = false;\n var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);\n emitEmitHelpers(node);\n emitCaptureThisForNodeIfNecessary(node);\n emitLinesStartingAt(node.statements, startIndex);\n emitTempDeclarations(/*newLine*/ true);\n // Emit exportDefault if it exists will happen as part\n // or normal statement emit.\n }\n function emitExportEquals(emitAsReturn) {\n if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) {\n writeLine();\n emitStart(exportEquals);\n write(emitAsReturn ? \"return \" : \"module.exports = \");\n emit(exportEquals.expression);\n write(\";\");\n emitEnd(exportEquals);\n }\n }\n function emitJsxElement(node) {\n switch (compilerOptions.jsx) {\n case 2 /* React */:\n jsxEmitReact(node);\n break;\n case 1 /* Preserve */:\n // Fall back to preserve if None was specified (we'll error earlier)\n default:\n jsxEmitPreserve(node);\n break;\n }\n }\n function trimReactWhitespaceAndApplyEntities(node) {\n var result = undefined;\n var text = ts.getTextOfNode(node, /*includeTrivia*/ true);\n var firstNonWhitespace = 0;\n var lastNonWhitespace = -1;\n // JSX trims whitespace at the end and beginning of lines, except that the\n // start/end of a tag is considered a start/end of a line only if that line is\n // on the same line as the closing tag. See examples in tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx\n for (var i = 0; i < text.length; i++) {\n var c = text.charCodeAt(i);\n if (ts.isLineBreak(c)) {\n if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) {\n var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1);\n result = (result ? result + \"\\\" + ' ' + \\\"\" : \"\") + ts.escapeString(part);\n }\n firstNonWhitespace = -1;\n }\n else if (!ts.isWhiteSpace(c)) {\n lastNonWhitespace = i;\n if (firstNonWhitespace === -1) {\n firstNonWhitespace = i;\n }\n }\n }\n if (firstNonWhitespace !== -1) {\n var part = text.substr(firstNonWhitespace);\n result = (result ? result + \"\\\" + ' ' + \\\"\" : \"\") + ts.escapeString(part);\n }\n if (result) {\n // Replace entities like  \n result = result.replace(/&(\\w+);/g, function (s, m) {\n if (entities[m] !== undefined) {\n return String.fromCharCode(entities[m]);\n }\n else {\n return s;\n }\n });\n }\n return result;\n }\n function getTextToEmit(node) {\n switch (compilerOptions.jsx) {\n case 2 /* React */:\n var text = trimReactWhitespaceAndApplyEntities(node);\n if (text === undefined || text.length === 0) {\n return undefined;\n }\n else {\n return text;\n }\n case 1 /* Preserve */:\n default:\n return ts.getTextOfNode(node, /*includeTrivia*/ true);\n }\n }\n function emitJsxText(node) {\n switch (compilerOptions.jsx) {\n case 2 /* React */:\n write(\"\\\"\");\n write(trimReactWhitespaceAndApplyEntities(node));\n write(\"\\\"\");\n break;\n case 1 /* Preserve */:\n default:\n writer.writeLiteral(ts.getTextOfNode(node, /*includeTrivia*/ true));\n break;\n }\n }\n function emitJsxExpression(node) {\n if (node.expression) {\n switch (compilerOptions.jsx) {\n case 1 /* Preserve */:\n default:\n write(\"{\");\n emit(node.expression);\n write(\"}\");\n break;\n case 2 /* React */:\n emit(node.expression);\n break;\n }\n }\n }\n function emitDirectivePrologues(statements, startWithNewLine) {\n for (var i = 0; i < statements.length; ++i) {\n if (ts.isPrologueDirective(statements[i])) {\n if (startWithNewLine || i > 0) {\n writeLine();\n }\n emit(statements[i]);\n }\n else {\n // return index of the first non prologue directive\n return i;\n }\n }\n return statements.length;\n }\n function writeLines(text) {\n var lines = text.split(/\\r\\n|\\r|\\n/g);\n for (var i = 0; i < lines.length; ++i) {\n var line = lines[i];\n if (line.length) {\n writeLine();\n write(line);\n }\n }\n }\n function emitEmitHelpers(node) {\n // Only emit helpers if the user did not say otherwise.\n if (!compilerOptions.noEmitHelpers) {\n // Only Emit __extends function when target ES5.\n // For target ES6 and above, we can emit classDeclaration as is.\n if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8 /* EmitExtends */)) {\n writeLines(extendsHelper);\n extendsEmitted = true;\n }\n if (!decorateEmitted && resolver.getNodeCheckFlags(node) & 16 /* EmitDecorate */) {\n writeLines(decorateHelper);\n if (compilerOptions.emitDecoratorMetadata) {\n writeLines(metadataHelper);\n }\n decorateEmitted = true;\n }\n if (!paramEmitted && resolver.getNodeCheckFlags(node) & 32 /* EmitParam */) {\n writeLines(paramHelper);\n paramEmitted = true;\n }\n if (!awaiterEmitted && resolver.getNodeCheckFlags(node) & 64 /* EmitAwaiter */) {\n writeLines(awaiterHelper);\n awaiterEmitted = true;\n }\n }\n }\n function emitSourceFileNode(node) {\n // Start new file on new line\n writeLine();\n emitShebang();\n emitDetachedComments(node);\n if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {\n var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */];\n emitModule(node);\n }\n else {\n // emit prologue directives prior to __extends\n var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);\n externalImports = undefined;\n exportSpecifiers = undefined;\n exportEquals = undefined;\n hasExportStars = false;\n emitEmitHelpers(node);\n emitCaptureThisForNodeIfNecessary(node);\n emitLinesStartingAt(node.statements, startIndex);\n emitTempDeclarations(/*newLine*/ true);\n }\n emitLeadingComments(node.endOfFileToken);\n }\n function emitNodeWithCommentsAndWithoutSourcemap(node) {\n emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap);\n }\n function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) {\n if (node) {\n if (node.flags & 2 /* Ambient */) {\n return emitCommentsOnNotEmittedNode(node);\n }\n if (isSpecializedCommentHandling(node)) {\n // This is the node that will handle its own comments and sourcemap\n return emitNodeWithoutSourceMap(node);\n }\n var emitComments_1 = shouldEmitLeadingAndTrailingComments(node);\n if (emitComments_1) {\n emitLeadingComments(node);\n }\n emitNodeConsideringSourcemap(node);\n if (emitComments_1) {\n emitTrailingComments(node);\n }\n }\n }\n function emitNodeWithoutSourceMap(node) {\n if (node) {\n emitJavaScriptWorker(node);\n }\n }\n function isSpecializedCommentHandling(node) {\n switch (node.kind) {\n // All of these entities are emitted in a specialized fashion. As such, we allow\n // the specialized methods for each to handle the comments on the nodes.\n case 215 /* InterfaceDeclaration */:\n case 213 /* FunctionDeclaration */:\n case 222 /* ImportDeclaration */:\n case 221 /* ImportEqualsDeclaration */:\n case 216 /* TypeAliasDeclaration */:\n case 227 /* ExportAssignment */:\n return true;\n }\n }\n function shouldEmitLeadingAndTrailingComments(node) {\n switch (node.kind) {\n case 193 /* VariableStatement */:\n return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node);\n case 218 /* ModuleDeclaration */:\n // Only emit the leading/trailing comments for a module if we're actually\n // emitting the module as well.\n return shouldEmitModuleDeclaration(node);\n case 217 /* EnumDeclaration */:\n // Only emit the leading/trailing comments for an enum if we're actually\n // emitting the module as well.\n return shouldEmitEnumDeclaration(node);\n }\n // If the node is emitted in specialized fashion, dont emit comments as this node will handle\n // emitting comments when emitting itself\n ts.Debug.assert(!isSpecializedCommentHandling(node));\n // If this is the expression body of an arrow function that we're down-leveling,\n // then we don't want to emit comments when we emit the body. It will have already\n // been taken care of when we emitted the 'return' statement for the function\n // expression body.\n if (node.kind !== 192 /* Block */ &&\n node.parent &&\n node.parent.kind === 174 /* ArrowFunction */ &&\n node.parent.body === node &&\n compilerOptions.target <= 1 /* ES5 */) {\n return false;\n }\n // Emit comments for everything else.\n return true;\n }\n function emitJavaScriptWorker(node) {\n // Check if the node can be emitted regardless of the ScriptTarget\n switch (node.kind) {\n case 69 /* Identifier */:\n return emitIdentifier(node);\n case 138 /* Parameter */:\n return emitParameter(node);\n case 143 /* MethodDeclaration */:\n case 142 /* MethodSignature */:\n return emitMethod(node);\n case 145 /* GetAccessor */:\n case 146 /* SetAccessor */:\n return emitAccessor(node);\n case 97 /* ThisKeyword */:\n return emitThis(node);\n case 95 /* SuperKeyword */:\n return emitSuper(node);\n case 93 /* NullKeyword */:\n return write(\"null\");\n case 99 /* TrueKeyword */:\n return write(\"true\");\n case 84 /* FalseKeyword */:\n return write(\"false\");\n case 8 /* NumericLiteral */:\n case 9 /* StringLiteral */:\n case 10 /* RegularExpressionLiteral */:\n case 11 /* NoSubstitutionTemplateLiteral */:\n case 12 /* TemplateHead */:\n case 13 /* TemplateMiddle */:\n case 14 /* TemplateTail */:\n return emitLiteral(node);\n case 183 /* TemplateExpression */:\n return emitTemplateExpression(node);\n case 190 /* TemplateSpan */:\n return emitTemplateSpan(node);\n case 233 /* JsxElement */:\n case 234 /* JsxSelfClosingElement */:\n return emitJsxElement(node);\n case 236 /* JsxText */:\n return emitJsxText(node);\n case 240 /* JsxExpression */:\n return emitJsxExpression(node);\n case 135 /* QualifiedName */:\n return emitQualifiedName(node);\n case 161 /* ObjectBindingPattern */:\n return emitObjectBindingPattern(node);\n case 162 /* ArrayBindingPattern */:\n return emitArrayBindingPattern(node);\n case 163 /* BindingElement */:\n return emitBindingElement(node);\n case 164 /* ArrayLiteralExpression */:\n return emitArrayLiteral(node);\n case 165 /* ObjectLiteralExpression */:\n return emitObjectLiteral(node);\n case 245 /* PropertyAssignment */:\n return emitPropertyAssignment(node);\n case 246 /* ShorthandPropertyAssignment */:\n return emitShorthandPropertyAssignment(node);\n case 136 /* ComputedPropertyName */:\n return emitComputedPropertyName(node);\n case 166 /* PropertyAccessExpression */:\n return emitPropertyAccess(node);\n case 167 /* ElementAccessExpression */:\n return emitIndexedAccess(node);\n case 168 /* CallExpression */:\n return emitCallExpression(node);\n case 169 /* NewExpression */:\n return emitNewExpression(node);\n case 170 /* TaggedTemplateExpression */:\n return emitTaggedTemplateExpression(node);\n case 171 /* TypeAssertionExpression */:\n return emit(node.expression);\n case 189 /* AsExpression */:\n return emit(node.expression);\n case 172 /* ParenthesizedExpression */:\n return emitParenExpression(node);\n case 213 /* FunctionDeclaration */:\n case 173 /* FunctionExpression */:\n case 174 /* ArrowFunction */:\n return emitFunctionDeclaration(node);\n case 175 /* DeleteExpression */:\n return emitDeleteExpression(node);\n case 176 /* TypeOfExpression */:\n return emitTypeOfExpression(node);\n case 177 /* VoidExpression */:\n return emitVoidExpression(node);\n case 178 /* AwaitExpression */:\n return emitAwaitExpression(node);\n case 179 /* PrefixUnaryExpression */:\n return emitPrefixUnaryExpression(node);\n case 180 /* PostfixUnaryExpression */:\n return emitPostfixUnaryExpression(node);\n case 181 /* BinaryExpression */:\n return emitBinaryExpression(node);\n case 182 /* ConditionalExpression */:\n return emitConditionalExpression(node);\n case 185 /* SpreadElementExpression */:\n return emitSpreadElementExpression(node);\n case 184 /* YieldExpression */:\n return emitYieldExpression(node);\n case 187 /* OmittedExpression */:\n return;\n case 192 /* Block */:\n case 219 /* ModuleBlock */:\n return emitBlock(node);\n case 193 /* VariableStatement */:\n return emitVariableStatement(node);\n case 194 /* EmptyStatement */:\n return write(\";\");\n case 195 /* ExpressionStatement */:\n return emitExpressionStatement(node);\n case 196 /* IfStatement */:\n return emitIfStatement(node);\n case 197 /* DoStatement */:\n return emitDoStatement(node);\n case 198 /* WhileStatement */:\n return emitWhileStatement(node);\n case 199 /* ForStatement */:\n return emitForStatement(node);\n case 201 /* ForOfStatement */:\n case 200 /* ForInStatement */:\n return emitForInOrForOfStatement(node);\n case 202 /* ContinueStatement */:\n case 203 /* BreakStatement */:\n return emitBreakOrContinueStatement(node);\n case 204 /* ReturnStatement */:\n return emitReturnStatement(node);\n case 205 /* WithStatement */:\n return emitWithStatement(node);\n case 206 /* SwitchStatement */:\n return emitSwitchStatement(node);\n case 241 /* CaseClause */:\n case 242 /* DefaultClause */:\n return emitCaseOrDefaultClause(node);\n case 207 /* LabeledStatement */:\n return emitLabelledStatement(node);\n case 208 /* ThrowStatement */:\n return emitThrowStatement(node);\n case 209 /* TryStatement */:\n return emitTryStatement(node);\n case 244 /* CatchClause */:\n return emitCatchClause(node);\n case 210 /* DebuggerStatement */:\n return emitDebuggerStatement(node);\n case 211 /* VariableDeclaration */:\n return emitVariableDeclaration(node);\n case 186 /* ClassExpression */:\n return emitClassExpression(node);\n case 214 /* ClassDeclaration */:\n return emitClassDeclaration(node);\n case 215 /* InterfaceDeclaration */:\n return emitInterfaceDeclaration(node);\n case 217 /* EnumDeclaration */:\n return emitEnumDeclaration(node);\n case 247 /* EnumMember */:\n return emitEnumMember(node);\n case 218 /* ModuleDeclaration */:\n return emitModuleDeclaration(node);\n case 222 /* ImportDeclaration */:\n return emitImportDeclaration(node);\n case 221 /* ImportEqualsDeclaration */:\n return emitImportEqualsDeclaration(node);\n case 228 /* ExportDeclaration */:\n return emitExportDeclaration(node);\n case 227 /* ExportAssignment */:\n return emitExportAssignment(node);\n case 248 /* SourceFile */:\n return emitSourceFileNode(node);\n }\n }\n function hasDetachedComments(pos) {\n return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos;\n }\n function getLeadingCommentsWithoutDetachedComments() {\n // get the leading comments from detachedPos\n var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);\n if (detachedCommentsInfo.length - 1) {\n detachedCommentsInfo.pop();\n }\n else {\n detachedCommentsInfo = undefined;\n }\n return leadingComments;\n }\n function isPinnedComments(comment) {\n return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&\n currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */;\n }\n /**\n * Determine if the given comment is a triple-slash\n *\n * @return true if the comment is a triple-slash comment else false\n **/\n function isTripleSlashComment(comment) {\n // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text\n // so that we don't end up computing comment string and doing match for all // comments\n if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 /* slash */ &&\n comment.pos + 2 < comment.end &&\n currentSourceFile.text.charCodeAt(comment.pos + 2) === 47 /* slash */) {\n var textSubStr = currentSourceFile.text.substring(comment.pos, comment.end);\n return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||\n textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ?\n true : false;\n }\n return false;\n }\n function getLeadingCommentsToEmit(node) {\n // Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments\n if (node.parent) {\n if (node.parent.kind === 248 /* SourceFile */ || node.pos !== node.parent.pos) {\n if (hasDetachedComments(node.pos)) {\n // get comments without detached comments\n return getLeadingCommentsWithoutDetachedComments();\n }\n else {\n // get the leading comments from the node\n return ts.getLeadingCommentRangesOfNode(node, currentSourceFile);\n }\n }\n }\n }\n function getTrailingCommentsToEmit(node) {\n // Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments\n if (node.parent) {\n if (node.parent.kind === 248 /* SourceFile */ || node.end !== node.parent.end) {\n return ts.getTrailingCommentRanges(currentSourceFile.text, node.end);\n }\n }\n }\n /**\n * Emit comments associated with node that will not be emitted into JS file\n */\n function emitCommentsOnNotEmittedNode(node) {\n emitLeadingCommentsWorker(node, /*isEmittedNode:*/ false);\n }\n function emitLeadingComments(node) {\n return emitLeadingCommentsWorker(node, /*isEmittedNode:*/ true);\n }\n function emitLeadingCommentsWorker(node, isEmittedNode) {\n if (compilerOptions.removeComments) {\n return;\n }\n var leadingComments;\n if (isEmittedNode) {\n leadingComments = getLeadingCommentsToEmit(node);\n }\n else {\n // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,\n // unless it is a triple slash comment at the top of the file.\n // For Example:\n // /// \n // declare var x;\n // /// \n // interface F {}\n // The first /// will NOT be removed while the second one will be removed eventhough both node will not be emitted\n if (node.pos === 0) {\n leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment);\n }\n }\n ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);\n // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space\n ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment);\n }\n function emitTrailingComments(node) {\n if (compilerOptions.removeComments) {\n return;\n }\n // Emit the trailing comments only if the parent's end doesn't match\n var trailingComments = getTrailingCommentsToEmit(node);\n // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/\n ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);\n }\n /**\n * Emit trailing comments at the position. The term trailing comment is used here to describe following comment:\n * x, /comment1/ y\n * ^ => pos; the function will emit \"comment1\" in the emitJS\n */\n function emitTrailingCommentsOfPosition(pos) {\n if (compilerOptions.removeComments) {\n return;\n }\n var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, pos);\n // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/\n ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment);\n }\n function emitLeadingCommentsOfPositionWorker(pos) {\n if (compilerOptions.removeComments) {\n return;\n }\n var leadingComments;\n if (hasDetachedComments(pos)) {\n // get comments without detached comments\n leadingComments = getLeadingCommentsWithoutDetachedComments();\n }\n else {\n // get the leading comments from the node\n leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos);\n }\n ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments);\n // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space\n ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment);\n }\n function emitDetachedComments(node) {\n var leadingComments;\n if (compilerOptions.removeComments) {\n // removeComments is true, only reserve pinned comment at the top of file\n // For example:\n // /*! Pinned Comment */\n //\n // var x = 10;\n if (node.pos === 0) {\n leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComments);\n }\n }\n else {\n // removeComments is false, just get detached as normal and bypass the process to filter comment\n leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos);\n }\n if (leadingComments) {\n var detachedComments = [];\n var lastComment;\n ts.forEach(leadingComments, function (comment) {\n if (lastComment) {\n var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, lastComment.end);\n var commentLine = ts.getLineOfLocalPosition(currentSourceFile, comment.pos);\n if (commentLine >= lastCommentLine + 2) {\n // There was a blank line between the last comment and this comment. This\n // comment is not part of the copyright comments. Return what we have so\n // far.\n return detachedComments;\n }\n }\n detachedComments.push(comment);\n lastComment = comment;\n });\n if (detachedComments.length) {\n // All comments look like they could have been part of the copyright header. Make\n // sure there is at least one blank line between it and the node. If not, it's not\n // a copyright header.\n var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end);\n var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos));\n if (nodeLine >= lastCommentLine + 2) {\n // Valid detachedComments\n ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);\n ts.emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment);\n var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end };\n if (detachedCommentsInfo) {\n detachedCommentsInfo.push(currentDetachedCommentInfo);\n }\n else {\n detachedCommentsInfo = [currentDetachedCommentInfo];\n }\n }\n }\n }\n }\n function emitShebang() {\n var shebang = ts.getShebang(currentSourceFile.text);\n if (shebang) {\n write(shebang);\n }\n }\n var _a;\n }\n function emitFile(jsFilePath, sourceFile) {\n emitJavaScript(jsFilePath, sourceFile);\n if (compilerOptions.declaration) {\n ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics);\n }\n }\n }", "code_tokens": ["function", "emitFiles", "(", "resolver", ",", "host", ",", "targetSourceFile", ")", "{", "var", "extendsHelper", "=", "\"\\nvar __extends = (this && this.__extends) || function (d, b) {\\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\\n function __() { this.constructor = d; }\\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\\n};\"", ";", "\\n", "\\n", "\\n", "\\n", "\\n", "var", "decorateHelper", "=", "\"\\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\\n if (typeof Reflect === \\\"object\\\" && typeof Reflect.decorate === \\\"function\\\") r = Reflect.decorate(decorators, target, key, desc);\\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\\n return c > 3 && r && Object.defineProperty(target, key, r), r;\\n};\"", ";", "\\n", "\\n", "\\n", "\\\"", "\\\"", "\\\"", "\\\"", "\\n", "\\n", "\\n", "var", "metadataHelper", "=", "\"\\nvar __metadata = (this && this.__metadata) || function (k, v) {\\n if (typeof Reflect === \\\"object\\\" && typeof Reflect.metadata === \\\"function\\\") return Reflect.metadata(k, v);\\n};\"", ";", "\\n", "}"], "docstring": "targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature", "docstring_tokens": ["targetSourceFile", "is", "when", "users", "only", "want", "one", "file", "in", "entire", "project", "to", "be", "emitted", ".", "This", "is", "used", "in", "compileOnSave", "feature"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L29466-L35977", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "makeTempVariableName", "original_string": "function makeTempVariableName(flags) {\n if (flags && !(tempFlags & flags)) {\n var name_19 = flags === 268435456 /* _i */ ? \"_i\" : \"_n\";\n if (isUniqueName(name_19)) {\n tempFlags |= flags;\n return name_19;\n }\n }\n while (true) {\n var count = tempFlags & 268435455 /* CountMask */;\n tempFlags++;\n // Skip over 'i' and 'n'\n if (count !== 8 && count !== 13) {\n var name_20 = count < 26 ? \"_\" + String.fromCharCode(97 /* a */ + count) : \"_\" + (count - 26);\n if (isUniqueName(name_20)) {\n return name_20;\n }\n }\n }\n }", "language": "javascript", "code": "function makeTempVariableName(flags) {\n if (flags && !(tempFlags & flags)) {\n var name_19 = flags === 268435456 /* _i */ ? \"_i\" : \"_n\";\n if (isUniqueName(name_19)) {\n tempFlags |= flags;\n return name_19;\n }\n }\n while (true) {\n var count = tempFlags & 268435455 /* CountMask */;\n tempFlags++;\n // Skip over 'i' and 'n'\n if (count !== 8 && count !== 13) {\n var name_20 = count < 26 ? \"_\" + String.fromCharCode(97 /* a */ + count) : \"_\" + (count - 26);\n if (isUniqueName(name_20)) {\n return name_20;\n }\n }\n }\n }", "code_tokens": ["function", "makeTempVariableName", "(", "flags", ")", "{", "if", "(", "flags", "&&", "!", "(", "tempFlags", "&", "flags", ")", ")", "{", "var", "name_19", "=", "flags", "===", "268435456", "?", "\"_i\"", ":", "\"_n\"", ";", "if", "(", "isUniqueName", "(", "name_19", ")", ")", "{", "tempFlags", "|=", "flags", ";", "return", "name_19", ";", "}", "}", "while", "(", "true", ")", "{", "var", "count", "=", "tempFlags", "&", "268435455", ";", "tempFlags", "++", ";", "if", "(", "count", "!==", "8", "&&", "count", "!==", "13", ")", "{", "var", "name_20", "=", "count", "<", "26", "?", "\"_\"", "+", "String", ".", "fromCharCode", "(", "97", "+", "count", ")", ":", "\"_\"", "+", "(", "count", "-", "26", ")", ";", "if", "(", "isUniqueName", "(", "name_20", ")", ")", "{", "return", "name_20", ";", "}", "}", "}", "}"], "docstring": "Return the next available name in the pattern _a ... _z, _0, _1, ... TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. Note that names generated by makeTempVariableName and makeUniqueName will never conflict.", "docstring_tokens": ["Return", "the", "next", "available", "name", "in", "the", "pattern", "_a", "...", "_z", "_0", "_1", "...", "TempFlags", ".", "_i", "or", "TempFlags", ".", "_n", "may", "be", "used", "to", "express", "a", "preference", "for", "that", "dedicated", "name", ".", "Note", "that", "names", "generated", "by", "makeTempVariableName", "and", "makeUniqueName", "will", "never", "conflict", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L29613-L29632", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "makeUniqueName", "original_string": "function makeUniqueName(baseName) {\n // Find the first unique 'name_n', where n is a positive number\n if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {\n baseName += \"_\";\n }\n var i = 1;\n while (true) {\n var generatedName = baseName + i;\n if (isUniqueName(generatedName)) {\n return generatedNameSet[generatedName] = generatedName;\n }\n i++;\n }\n }", "language": "javascript", "code": "function makeUniqueName(baseName) {\n // Find the first unique 'name_n', where n is a positive number\n if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {\n baseName += \"_\";\n }\n var i = 1;\n while (true) {\n var generatedName = baseName + i;\n if (isUniqueName(generatedName)) {\n return generatedNameSet[generatedName] = generatedName;\n }\n i++;\n }\n }", "code_tokens": ["function", "makeUniqueName", "(", "baseName", ")", "{", "if", "(", "baseName", ".", "charCodeAt", "(", "baseName", ".", "length", "-", "1", ")", "!==", "95", ")", "{", "baseName", "+=", "\"_\"", ";", "}", "var", "i", "=", "1", ";", "while", "(", "true", ")", "{", "var", "generatedName", "=", "baseName", "+", "i", ";", "if", "(", "isUniqueName", "(", "generatedName", ")", ")", "{", "return", "generatedNameSet", "[", "generatedName", "]", "=", "generatedName", ";", "}", "i", "++", ";", "}", "}"], "docstring": "Generate a name that is unique within the current file and doesn't conflict with any names in global scope. The name is formed by adding an '_n' suffix to the specified base name, where n is a positive integer. Note that names generated by makeTempVariableName and makeUniqueName are guaranteed to never conflict.", "docstring_tokens": ["Generate", "a", "name", "that", "is", "unique", "within", "the", "current", "file", "and", "doesn", "t", "conflict", "with", "any", "names", "in", "global", "scope", ".", "The", "name", "is", "formed", "by", "adding", "an", "_n", "suffix", "to", "the", "specified", "base", "name", "where", "n", "is", "a", "positive", "integer", ".", "Note", "that", "names", "generated", "by", "makeTempVariableName", "and", "makeUniqueName", "are", "guaranteed", "to", "never", "conflict", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L29637-L29650", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "encodeLastRecordedSourceMapSpan", "original_string": "function encodeLastRecordedSourceMapSpan() {\n if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) {\n return;\n }\n var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn;\n // Line/Comma delimiters\n if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) {\n // Emit comma to separate the entry\n if (sourceMapData.sourceMapMappings) {\n sourceMapData.sourceMapMappings += \",\";\n }\n }\n else {\n // Emit line delimiters\n for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) {\n sourceMapData.sourceMapMappings += \";\";\n }\n prevEncodedEmittedColumn = 1;\n }\n // 1. Relative Column 0 based\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn);\n // 2. Relative sourceIndex\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex);\n // 3. Relative sourceLine 0 based\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine);\n // 4. Relative sourceColumn 0 based\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn);\n // 5. Relative namePosition 0 based\n if (lastRecordedSourceMapSpan.nameIndex >= 0) {\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex);\n lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex;\n }\n lastEncodedSourceMapSpan = lastRecordedSourceMapSpan;\n sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan);\n function base64VLQFormatEncode(inValue) {\n function base64FormatEncode(inValue) {\n if (inValue < 64) {\n return \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt(inValue);\n }\n throw TypeError(inValue + \": not a 64 based value\");\n }\n // Add a new least significant bit that has the sign of the value.\n // if negative number the least significant bit that gets added to the number has value 1\n // else least significant bit value that gets added is 0\n // eg. -1 changes to binary : 01 [1] => 3\n // +1 changes to binary : 01 [0] => 2\n if (inValue < 0) {\n inValue = ((-inValue) << 1) + 1;\n }\n else {\n inValue = inValue << 1;\n }\n // Encode 5 bits at a time starting from least significant bits\n var encodedStr = \"\";\n do {\n var currentDigit = inValue & 31; // 11111\n inValue = inValue >> 5;\n if (inValue > 0) {\n // There are still more digits to decode, set the msb (6th bit)\n currentDigit = currentDigit | 32;\n }\n encodedStr = encodedStr + base64FormatEncode(currentDigit);\n } while (inValue > 0);\n return encodedStr;\n }\n }", "language": "javascript", "code": "function encodeLastRecordedSourceMapSpan() {\n if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) {\n return;\n }\n var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn;\n // Line/Comma delimiters\n if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) {\n // Emit comma to separate the entry\n if (sourceMapData.sourceMapMappings) {\n sourceMapData.sourceMapMappings += \",\";\n }\n }\n else {\n // Emit line delimiters\n for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) {\n sourceMapData.sourceMapMappings += \";\";\n }\n prevEncodedEmittedColumn = 1;\n }\n // 1. Relative Column 0 based\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn);\n // 2. Relative sourceIndex\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex);\n // 3. Relative sourceLine 0 based\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine);\n // 4. Relative sourceColumn 0 based\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn);\n // 5. Relative namePosition 0 based\n if (lastRecordedSourceMapSpan.nameIndex >= 0) {\n sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex);\n lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex;\n }\n lastEncodedSourceMapSpan = lastRecordedSourceMapSpan;\n sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan);\n function base64VLQFormatEncode(inValue) {\n function base64FormatEncode(inValue) {\n if (inValue < 64) {\n return \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt(inValue);\n }\n throw TypeError(inValue + \": not a 64 based value\");\n }\n // Add a new least significant bit that has the sign of the value.\n // if negative number the least significant bit that gets added to the number has value 1\n // else least significant bit value that gets added is 0\n // eg. -1 changes to binary : 01 [1] => 3\n // +1 changes to binary : 01 [0] => 2\n if (inValue < 0) {\n inValue = ((-inValue) << 1) + 1;\n }\n else {\n inValue = inValue << 1;\n }\n // Encode 5 bits at a time starting from least significant bits\n var encodedStr = \"\";\n do {\n var currentDigit = inValue & 31; // 11111\n inValue = inValue >> 5;\n if (inValue > 0) {\n // There are still more digits to decode, set the msb (6th bit)\n currentDigit = currentDigit | 32;\n }\n encodedStr = encodedStr + base64FormatEncode(currentDigit);\n } while (inValue > 0);\n return encodedStr;\n }\n }", "code_tokens": ["function", "encodeLastRecordedSourceMapSpan", "(", ")", "{", "if", "(", "!", "lastRecordedSourceMapSpan", "||", "lastRecordedSourceMapSpan", "===", "lastEncodedSourceMapSpan", ")", "{", "return", ";", "}", "var", "prevEncodedEmittedColumn", "=", "lastEncodedSourceMapSpan", ".", "emittedColumn", ";", "if", "(", "lastEncodedSourceMapSpan", ".", "emittedLine", "===", "lastRecordedSourceMapSpan", ".", "emittedLine", ")", "{", "if", "(", "sourceMapData", ".", "sourceMapMappings", ")", "{", "sourceMapData", ".", "sourceMapMappings", "+=", "\",\"", ";", "}", "}", "else", "{", "for", "(", "var", "encodedLine", "=", "lastEncodedSourceMapSpan", ".", "emittedLine", ";", "encodedLine", "<", "lastRecordedSourceMapSpan", ".", "emittedLine", ";", "encodedLine", "++", ")", "{", "sourceMapData", ".", "sourceMapMappings", "+=", "\";\"", ";", "}", "prevEncodedEmittedColumn", "=", "1", ";", "}", "sourceMapData", ".", "sourceMapMappings", "+=", "base64VLQFormatEncode", "(", "lastRecordedSourceMapSpan", ".", "emittedColumn", "-", "prevEncodedEmittedColumn", ")", ";", "sourceMapData", ".", "sourceMapMappings", "+=", "base64VLQFormatEncode", "(", "lastRecordedSourceMapSpan", ".", "sourceIndex", "-", "lastEncodedSourceMapSpan", ".", "sourceIndex", ")", ";", "sourceMapData", ".", "sourceMapMappings", "+=", "base64VLQFormatEncode", "(", "lastRecordedSourceMapSpan", ".", "sourceLine", "-", "lastEncodedSourceMapSpan", ".", "sourceLine", ")", ";", "sourceMapData", ".", "sourceMapMappings", "+=", "base64VLQFormatEncode", "(", "lastRecordedSourceMapSpan", ".", "sourceColumn", "-", "lastEncodedSourceMapSpan", ".", "sourceColumn", ")", ";", "if", "(", "lastRecordedSourceMapSpan", ".", "nameIndex", ">=", "0", ")", "{", "sourceMapData", ".", "sourceMapMappings", "+=", "base64VLQFormatEncode", "(", "lastRecordedSourceMapSpan", ".", "nameIndex", "-", "lastEncodedNameIndex", ")", ";", "lastEncodedNameIndex", "=", "lastRecordedSourceMapSpan", ".", "nameIndex", ";", "}", "lastEncodedSourceMapSpan", "=", "lastRecordedSourceMapSpan", ";", "sourceMapData", ".", "sourceMapDecodedMappings", ".", "push", "(", "lastEncodedSourceMapSpan", ")", ";", "function", "base64VLQFormatEncode", "(", "inValue", ")", "{", "function", "base64FormatEncode", "(", "inValue", ")", "{", "if", "(", "inValue", "<", "64", ")", "{", "return", "\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"", ".", "charAt", "(", "inValue", ")", ";", "}", "throw", "TypeError", "(", "inValue", "+", "\": not a 64 based value\"", ")", ";", "}", "if", "(", "inValue", "<", "0", ")", "{", "inValue", "=", "(", "(", "-", "inValue", ")", "<<", "1", ")", "+", "1", ";", "}", "else", "{", "inValue", "=", "inValue", "<<", "1", ";", "}", "var", "encodedStr", "=", "\"\"", ";", "do", "{", "var", "currentDigit", "=", "inValue", "&", "31", ";", "inValue", "=", "inValue", ">>", "5", ";", "if", "(", "inValue", ">", "0", ")", "{", "currentDigit", "=", "currentDigit", "|", "32", ";", "}", "encodedStr", "=", "encodedStr", "+", "base64FormatEncode", "(", "currentDigit", ")", ";", "}", "while", "(", "inValue", ">", "0", ")", ";", "return", "encodedStr", ";", "}", "}"], "docstring": "Encoding for sourcemap span", "docstring_tokens": ["Encoding", "for", "sourcemap", "span"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L29711-L29776", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "createTempVariable", "original_string": "function createTempVariable(flags) {\n var result = ts.createSynthesizedNode(69 /* Identifier */);\n result.text = makeTempVariableName(flags);\n return result;\n }", "language": "javascript", "code": "function createTempVariable(flags) {\n var result = ts.createSynthesizedNode(69 /* Identifier */);\n result.text = makeTempVariableName(flags);\n return result;\n }", "code_tokens": ["function", "createTempVariable", "(", "flags", ")", "{", "var", "result", "=", "ts", ".", "createSynthesizedNode", "(", "69", ")", ";", "result", ".", "text", "=", "makeTempVariableName", "(", "flags", ")", ";", "return", "result", ";", "}"], "docstring": "Create a temporary variable with a unique unused name.", "docstring_tokens": ["Create", "a", "temporary", "variable", "with", "a", "unique", "unused", "name", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L30024-L30028", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "indentIfOnDifferentLines", "original_string": "function indentIfOnDifferentLines(parent, node1, node2, valueToWriteWhenNotIndenting) {\n var realNodesAreOnDifferentLines = !ts.nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2);\n // Always use a newline for synthesized code if the synthesizer desires it.\n var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2);\n if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) {\n increaseIndent();\n writeLine();\n return true;\n }\n else {\n if (valueToWriteWhenNotIndenting) {\n write(valueToWriteWhenNotIndenting);\n }\n return false;\n }\n }", "language": "javascript", "code": "function indentIfOnDifferentLines(parent, node1, node2, valueToWriteWhenNotIndenting) {\n var realNodesAreOnDifferentLines = !ts.nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2);\n // Always use a newline for synthesized code if the synthesizer desires it.\n var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2);\n if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) {\n increaseIndent();\n writeLine();\n return true;\n }\n else {\n if (valueToWriteWhenNotIndenting) {\n write(valueToWriteWhenNotIndenting);\n }\n return false;\n }\n }", "code_tokens": ["function", "indentIfOnDifferentLines", "(", "parent", ",", "node1", ",", "node2", ",", "valueToWriteWhenNotIndenting", ")", "{", "var", "realNodesAreOnDifferentLines", "=", "!", "ts", ".", "nodeIsSynthesized", "(", "parent", ")", "&&", "!", "nodeEndIsOnSameLineAsNodeStart", "(", "node1", ",", "node2", ")", ";", "var", "synthesizedNodeIsOnDifferentLine", "=", "synthesizedNodeStartsOnNewLine", "(", "node2", ")", ";", "if", "(", "realNodesAreOnDifferentLines", "||", "synthesizedNodeIsOnDifferentLine", ")", "{", "increaseIndent", "(", ")", ";", "writeLine", "(", ")", ";", "return", "true", ";", "}", "else", "{", "if", "(", "valueToWriteWhenNotIndenting", ")", "{", "write", "(", "valueToWriteWhenNotIndenting", ")", ";", "}", "return", "false", ";", "}", "}"], "docstring": "Returns 'true' if the code was actually indented, false otherwise. If the code is not indented, an optional valueToWriteWhenNotIndenting will be emitted instead.", "docstring_tokens": ["Returns", "true", "if", "the", "code", "was", "actually", "indented", "false", "otherwise", ".", "If", "the", "code", "is", "not", "indented", "an", "optional", "valueToWriteWhenNotIndenting", "will", "be", "emitted", "instead", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L31245-L31260", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "emitExponentiationOperator", "original_string": "function emitExponentiationOperator(node) {\n var leftHandSideExpression = node.left;\n if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) {\n var synthesizedLHS;\n var shouldEmitParentheses = false;\n if (ts.isElementAccessExpression(leftHandSideExpression)) {\n shouldEmitParentheses = true;\n write(\"(\");\n synthesizedLHS = ts.createSynthesizedNode(167 /* ElementAccessExpression */, /*startsOnNewLine*/ false);\n var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false);\n synthesizedLHS.expression = identifier;\n if (leftHandSideExpression.argumentExpression.kind !== 8 /* NumericLiteral */ &&\n leftHandSideExpression.argumentExpression.kind !== 9 /* StringLiteral */) {\n var tempArgumentExpression = createAndRecordTempVariable(268435456 /* _i */);\n synthesizedLHS.argumentExpression = tempArgumentExpression;\n emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true);\n }\n else {\n synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression;\n }\n write(\", \");\n }\n else if (ts.isPropertyAccessExpression(leftHandSideExpression)) {\n shouldEmitParentheses = true;\n write(\"(\");\n synthesizedLHS = ts.createSynthesizedNode(166 /* PropertyAccessExpression */, /*startsOnNewLine*/ false);\n var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false);\n synthesizedLHS.expression = identifier;\n synthesizedLHS.dotToken = leftHandSideExpression.dotToken;\n synthesizedLHS.name = leftHandSideExpression.name;\n write(\", \");\n }\n emit(synthesizedLHS || leftHandSideExpression);\n write(\" = \");\n write(\"Math.pow(\");\n emit(synthesizedLHS || leftHandSideExpression);\n write(\", \");\n emit(node.right);\n write(\")\");\n if (shouldEmitParentheses) {\n write(\")\");\n }\n }\n else {\n write(\"Math.pow(\");\n emit(leftHandSideExpression);\n write(\", \");\n emit(node.right);\n write(\")\");\n }\n }", "language": "javascript", "code": "function emitExponentiationOperator(node) {\n var leftHandSideExpression = node.left;\n if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) {\n var synthesizedLHS;\n var shouldEmitParentheses = false;\n if (ts.isElementAccessExpression(leftHandSideExpression)) {\n shouldEmitParentheses = true;\n write(\"(\");\n synthesizedLHS = ts.createSynthesizedNode(167 /* ElementAccessExpression */, /*startsOnNewLine*/ false);\n var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false);\n synthesizedLHS.expression = identifier;\n if (leftHandSideExpression.argumentExpression.kind !== 8 /* NumericLiteral */ &&\n leftHandSideExpression.argumentExpression.kind !== 9 /* StringLiteral */) {\n var tempArgumentExpression = createAndRecordTempVariable(268435456 /* _i */);\n synthesizedLHS.argumentExpression = tempArgumentExpression;\n emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true);\n }\n else {\n synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression;\n }\n write(\", \");\n }\n else if (ts.isPropertyAccessExpression(leftHandSideExpression)) {\n shouldEmitParentheses = true;\n write(\"(\");\n synthesizedLHS = ts.createSynthesizedNode(166 /* PropertyAccessExpression */, /*startsOnNewLine*/ false);\n var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false);\n synthesizedLHS.expression = identifier;\n synthesizedLHS.dotToken = leftHandSideExpression.dotToken;\n synthesizedLHS.name = leftHandSideExpression.name;\n write(\", \");\n }\n emit(synthesizedLHS || leftHandSideExpression);\n write(\" = \");\n write(\"Math.pow(\");\n emit(synthesizedLHS || leftHandSideExpression);\n write(\", \");\n emit(node.right);\n write(\")\");\n if (shouldEmitParentheses) {\n write(\")\");\n }\n }\n else {\n write(\"Math.pow(\");\n emit(leftHandSideExpression);\n write(\", \");\n emit(node.right);\n write(\")\");\n }\n }", "code_tokens": ["function", "emitExponentiationOperator", "(", "node", ")", "{", "var", "leftHandSideExpression", "=", "node", ".", "left", ";", "if", "(", "node", ".", "operatorToken", ".", "kind", "===", "60", ")", "{", "var", "synthesizedLHS", ";", "var", "shouldEmitParentheses", "=", "false", ";", "if", "(", "ts", ".", "isElementAccessExpression", "(", "leftHandSideExpression", ")", ")", "{", "shouldEmitParentheses", "=", "true", ";", "write", "(", "\"(\"", ")", ";", "synthesizedLHS", "=", "ts", ".", "createSynthesizedNode", "(", "167", ",", "false", ")", ";", "var", "identifier", "=", "emitTempVariableAssignment", "(", "leftHandSideExpression", ".", "expression", ",", "false", ",", "false", ")", ";", "synthesizedLHS", ".", "expression", "=", "identifier", ";", "if", "(", "leftHandSideExpression", ".", "argumentExpression", ".", "kind", "!==", "8", "&&", "leftHandSideExpression", ".", "argumentExpression", ".", "kind", "!==", "9", ")", "{", "var", "tempArgumentExpression", "=", "createAndRecordTempVariable", "(", "268435456", ")", ";", "synthesizedLHS", ".", "argumentExpression", "=", "tempArgumentExpression", ";", "emitAssignment", "(", "tempArgumentExpression", ",", "leftHandSideExpression", ".", "argumentExpression", ",", "true", ")", ";", "}", "else", "{", "synthesizedLHS", ".", "argumentExpression", "=", "leftHandSideExpression", ".", "argumentExpression", ";", "}", "write", "(", "\", \"", ")", ";", "}", "else", "if", "(", "ts", ".", "isPropertyAccessExpression", "(", "leftHandSideExpression", ")", ")", "{", "shouldEmitParentheses", "=", "true", ";", "write", "(", "\"(\"", ")", ";", "synthesizedLHS", "=", "ts", ".", "createSynthesizedNode", "(", "166", ",", "false", ")", ";", "var", "identifier", "=", "emitTempVariableAssignment", "(", "leftHandSideExpression", ".", "expression", ",", "false", ",", "false", ")", ";", "synthesizedLHS", ".", "expression", "=", "identifier", ";", "synthesizedLHS", ".", "dotToken", "=", "leftHandSideExpression", ".", "dotToken", ";", "synthesizedLHS", ".", "name", "=", "leftHandSideExpression", ".", "name", ";", "write", "(", "\", \"", ")", ";", "}", "emit", "(", "synthesizedLHS", "||", "leftHandSideExpression", ")", ";", "write", "(", "\" = \"", ")", ";", "write", "(", "\"Math.pow(\"", ")", ";", "emit", "(", "synthesizedLHS", "||", "leftHandSideExpression", ")", ";", "write", "(", "\", \"", ")", ";", "emit", "(", "node", ".", "right", ")", ";", "write", "(", "\")\"", ")", ";", "if", "(", "shouldEmitParentheses", ")", "{", "write", "(", "\")\"", ")", ";", "}", "}", "else", "{", "write", "(", "\"Math.pow(\"", ")", ";", "emit", "(", "leftHandSideExpression", ")", ";", "write", "(", "\", \"", ")", ";", "emit", "(", "node", ".", "right", ")", ";", "write", "(", "\")\"", ")", ";", "}", "}"], "docstring": "Emit ES7 exponentiation operator downlevel using Math.pow\n@param node a binary expression node containing exponentiationOperator (**, **=)", "docstring_tokens": ["Emit", "ES7", "exponentiation", "operator", "downlevel", "using", "Math", ".", "pow"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L31640-L31690", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "tryEmitStartOfVariableDeclarationList", "original_string": "function tryEmitStartOfVariableDeclarationList(decl, startPos) {\n if (shouldHoistVariable(decl, /*checkIfSourceFileLevelDecl*/ true)) {\n // variables in variable declaration list were already hoisted\n return false;\n }\n var tokenKind = 102 /* VarKeyword */;\n if (decl && languageVersion >= 2 /* ES6 */) {\n if (ts.isLet(decl)) {\n tokenKind = 108 /* LetKeyword */;\n }\n else if (ts.isConst(decl)) {\n tokenKind = 74 /* ConstKeyword */;\n }\n }\n if (startPos !== undefined) {\n emitToken(tokenKind, startPos);\n write(\" \");\n }\n else {\n switch (tokenKind) {\n case 102 /* VarKeyword */:\n write(\"var \");\n break;\n case 108 /* LetKeyword */:\n write(\"let \");\n break;\n case 74 /* ConstKeyword */:\n write(\"const \");\n break;\n }\n }\n return true;\n }", "language": "javascript", "code": "function tryEmitStartOfVariableDeclarationList(decl, startPos) {\n if (shouldHoistVariable(decl, /*checkIfSourceFileLevelDecl*/ true)) {\n // variables in variable declaration list were already hoisted\n return false;\n }\n var tokenKind = 102 /* VarKeyword */;\n if (decl && languageVersion >= 2 /* ES6 */) {\n if (ts.isLet(decl)) {\n tokenKind = 108 /* LetKeyword */;\n }\n else if (ts.isConst(decl)) {\n tokenKind = 74 /* ConstKeyword */;\n }\n }\n if (startPos !== undefined) {\n emitToken(tokenKind, startPos);\n write(\" \");\n }\n else {\n switch (tokenKind) {\n case 102 /* VarKeyword */:\n write(\"var \");\n break;\n case 108 /* LetKeyword */:\n write(\"let \");\n break;\n case 74 /* ConstKeyword */:\n write(\"const \");\n break;\n }\n }\n return true;\n }", "code_tokens": ["function", "tryEmitStartOfVariableDeclarationList", "(", "decl", ",", "startPos", ")", "{", "if", "(", "shouldHoistVariable", "(", "decl", ",", "true", ")", ")", "{", "return", "false", ";", "}", "var", "tokenKind", "=", "102", ";", "if", "(", "decl", "&&", "languageVersion", ">=", "2", ")", "{", "if", "(", "ts", ".", "isLet", "(", "decl", ")", ")", "{", "tokenKind", "=", "108", ";", "}", "else", "if", "(", "ts", ".", "isConst", "(", "decl", ")", ")", "{", "tokenKind", "=", "74", ";", "}", "}", "if", "(", "startPos", "!==", "undefined", ")", "{", "emitToken", "(", "tokenKind", ",", "startPos", ")", ";", "write", "(", "\" \"", ")", ";", "}", "else", "{", "switch", "(", "tokenKind", ")", "{", "case", "102", ":", "write", "(", "\"var \"", ")", ";", "break", ";", "case", "108", ":", "write", "(", "\"let \"", ")", ";", "break", ";", "case", "74", ":", "write", "(", "\"const \"", ")", ";", "break", ";", "}", "}", "return", "true", ";", "}"], "docstring": "Returns true if start of variable declaration list was emitted.\nReturns false if nothing was written - this can happen for source file level variable declarations\nin system modules where such variable declarations are hoisted.", "docstring_tokens": ["Returns", "true", "if", "start", "of", "variable", "declaration", "list", "was", "emitted", ".", "Returns", "false", "if", "nothing", "was", "written", "-", "this", "can", "happen", "for", "source", "file", "level", "variable", "declarations", "in", "system", "modules", "where", "such", "variable", "declarations", "are", "hoisted", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L31846-L31878", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "emitAssignment", "original_string": "function emitAssignment(name, value, shouldEmitCommaBeforeAssignment) {\n if (shouldEmitCommaBeforeAssignment) {\n write(\", \");\n }\n var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name);\n if (exportChanged) {\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithCommentsAndWithoutSourcemap(name);\n write(\"\\\", \");\n }\n var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 /* VariableDeclaration */ || name.parent.kind === 163 /* BindingElement */);\n if (isVariableDeclarationOrBindingElement) {\n emitModuleMemberName(name.parent);\n }\n else {\n emit(name);\n }\n write(\" = \");\n emit(value);\n if (exportChanged) {\n write(\")\");\n }\n }", "language": "javascript", "code": "function emitAssignment(name, value, shouldEmitCommaBeforeAssignment) {\n if (shouldEmitCommaBeforeAssignment) {\n write(\", \");\n }\n var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name);\n if (exportChanged) {\n write(exportFunctionForFile + \"(\\\"\");\n emitNodeWithCommentsAndWithoutSourcemap(name);\n write(\"\\\", \");\n }\n var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 /* VariableDeclaration */ || name.parent.kind === 163 /* BindingElement */);\n if (isVariableDeclarationOrBindingElement) {\n emitModuleMemberName(name.parent);\n }\n else {\n emit(name);\n }\n write(\" = \");\n emit(value);\n if (exportChanged) {\n write(\")\");\n }\n }", "code_tokens": ["function", "emitAssignment", "(", "name", ",", "value", ",", "shouldEmitCommaBeforeAssignment", ")", "{", "if", "(", "shouldEmitCommaBeforeAssignment", ")", "{", "write", "(", "\", \"", ")", ";", "}", "var", "exportChanged", "=", "isNameOfExportedSourceLevelDeclarationInSystemExternalModule", "(", "name", ")", ";", "if", "(", "exportChanged", ")", "{", "write", "(", "exportFunctionForFile", "+", "\"(\\\"\"", ")", ";", "\\\"", "emitNodeWithCommentsAndWithoutSourcemap", "(", "name", ")", ";", "}", "write", "(", "\"\\\", \"", ")", ";", "\\\"", "var", "isVariableDeclarationOrBindingElement", "=", "name", ".", "parent", "&&", "(", "name", ".", "parent", ".", "kind", "===", "211", "||", "name", ".", "parent", ".", "kind", "===", "163", ")", ";", "if", "(", "isVariableDeclarationOrBindingElement", ")", "{", "emitModuleMemberName", "(", "name", ".", "parent", ")", ";", "}", "else", "{", "emit", "(", "name", ")", ";", "}", "write", "(", "\" = \"", ")", ";", "}"], "docstring": "Emit an assignment to a given identifier, 'name', with a given expression, 'value'.\n@param name an identifier as a left-hand-side operand of the assignment\n@param value an expression as a right-hand-side operand of the assignment\n@param shouldEmitCommaBeforeAssignment a boolean indicating whether to prefix an assignment with comma", "docstring_tokens": ["Emit", "an", "assignment", "to", "a", "given", "identifier", "name", "with", "a", "given", "expression", "value", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L32302-L32324", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "emitTempVariableAssignment", "original_string": "function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment) {\n var identifier = createTempVariable(0 /* Auto */);\n if (!canDefineTempVariablesInPlace) {\n recordTempDeclaration(identifier);\n }\n emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment);\n return identifier;\n }", "language": "javascript", "code": "function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment) {\n var identifier = createTempVariable(0 /* Auto */);\n if (!canDefineTempVariablesInPlace) {\n recordTempDeclaration(identifier);\n }\n emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment);\n return identifier;\n }", "code_tokens": ["function", "emitTempVariableAssignment", "(", "expression", ",", "canDefineTempVariablesInPlace", ",", "shouldEmitCommaBeforeAssignment", ")", "{", "var", "identifier", "=", "createTempVariable", "(", "0", ")", ";", "if", "(", "!", "canDefineTempVariablesInPlace", ")", "{", "recordTempDeclaration", "(", "identifier", ")", ";", "}", "emitAssignment", "(", "identifier", ",", "expression", ",", "shouldEmitCommaBeforeAssignment", ")", ";", "return", "identifier", ";", "}"], "docstring": "Create temporary variable, emit an assignment of the variable the given expression\n@param expression an expression to assign to the newly created temporary variable\n@param canDefineTempVariablesInPlace a boolean indicating whether you can define the temporary variable at an assignment location\n@param shouldEmitCommaBeforeAssignment a boolean indicating whether an assignment should prefix with comma", "docstring_tokens": ["Create", "temporary", "variable", "emit", "an", "assignment", "of", "the", "variable", "the", "given", "expression"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L32331-L32338", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "ensureIdentifier", "original_string": "function ensureIdentifier(expr, reuseIdentifierExpressions) {\n if (expr.kind === 69 /* Identifier */ && reuseIdentifierExpressions) {\n return expr;\n }\n var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0);\n emitCount++;\n return identifier;\n }", "language": "javascript", "code": "function ensureIdentifier(expr, reuseIdentifierExpressions) {\n if (expr.kind === 69 /* Identifier */ && reuseIdentifierExpressions) {\n return expr;\n }\n var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0);\n emitCount++;\n return identifier;\n }", "code_tokens": ["function", "ensureIdentifier", "(", "expr", ",", "reuseIdentifierExpressions", ")", "{", "if", "(", "expr", ".", "kind", "===", "69", "&&", "reuseIdentifierExpressions", ")", "{", "return", "expr", ";", "}", "var", "identifier", "=", "emitTempVariableAssignment", "(", "expr", ",", "canDefineTempVariablesInPlace", ",", "emitCount", ">", "0", ")", ";", "emitCount", "++", ";", "return", "identifier", ";", "}"], "docstring": "Ensures that there exists a declared identifier whose value holds the given expression.\nThis function is useful to ensure that the expression's value can be read from in subsequent expressions.\nUnless 'reuseIdentifierExpressions' is false, 'expr' will be returned if it is just an identifier.\n\n@param expr the expression whose value needs to be bound.\n@param reuseIdentifierExpressions true if identifier expressions can simply be returned;\nfalse if it is necessary to always emit an identifier.", "docstring_tokens": ["Ensures", "that", "there", "exists", "a", "declared", "identifier", "whose", "value", "holds", "the", "given", "expression", ".", "This", "function", "is", "useful", "to", "ensure", "that", "the", "expression", "s", "value", "can", "be", "read", "from", "in", "subsequent", "expressions", ".", "Unless", "reuseIdentifierExpressions", "is", "false", "expr", "will", "be", "returned", "if", "it", "is", "just", "an", "identifier", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L32370-L32377", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "findSourceFile", "original_string": "function findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) {\n if (filesByName.contains(fileName)) {\n // We've already looked for this file, use cached result\n return getSourceFileFromCache(fileName, /*useAbsolutePath*/ false);\n }\n var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());\n if (filesByName.contains(normalizedAbsolutePath)) {\n var file_1 = getSourceFileFromCache(normalizedAbsolutePath, /*useAbsolutePath*/ true);\n // we don't have resolution for this relative file name but the match was found by absolute file name\n // store resolution for relative name as well\n filesByName.set(fileName, file_1);\n return file_1;\n }\n // We haven't looked for this file, do so now and cache result\n var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) {\n if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {\n fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));\n }\n else {\n fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));\n }\n });\n filesByName.set(fileName, file);\n if (file) {\n skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib;\n // Set the source file for normalized absolute path\n filesByName.set(normalizedAbsolutePath, file);\n var basePath = ts.getDirectoryPath(fileName);\n if (!options.noResolve) {\n processReferencedFiles(file, basePath);\n }\n // always process imported modules to record module name resolutions\n processImportedModules(file, basePath);\n if (isDefaultLib) {\n file.isDefaultLib = true;\n files.unshift(file);\n }\n else {\n files.push(file);\n }\n }\n return file;\n function getSourceFileFromCache(fileName, useAbsolutePath) {\n var file = filesByName.get(fileName);\n if (file && host.useCaseSensitiveFileNames()) {\n var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName;\n if (ts.normalizeSlashes(fileName) !== ts.normalizeSlashes(sourceFileName)) {\n if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {\n fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));\n }\n else {\n fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));\n }\n }\n }\n return file;\n }\n }", "language": "javascript", "code": "function findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) {\n if (filesByName.contains(fileName)) {\n // We've already looked for this file, use cached result\n return getSourceFileFromCache(fileName, /*useAbsolutePath*/ false);\n }\n var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());\n if (filesByName.contains(normalizedAbsolutePath)) {\n var file_1 = getSourceFileFromCache(normalizedAbsolutePath, /*useAbsolutePath*/ true);\n // we don't have resolution for this relative file name but the match was found by absolute file name\n // store resolution for relative name as well\n filesByName.set(fileName, file_1);\n return file_1;\n }\n // We haven't looked for this file, do so now and cache result\n var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) {\n if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {\n fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));\n }\n else {\n fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));\n }\n });\n filesByName.set(fileName, file);\n if (file) {\n skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib;\n // Set the source file for normalized absolute path\n filesByName.set(normalizedAbsolutePath, file);\n var basePath = ts.getDirectoryPath(fileName);\n if (!options.noResolve) {\n processReferencedFiles(file, basePath);\n }\n // always process imported modules to record module name resolutions\n processImportedModules(file, basePath);\n if (isDefaultLib) {\n file.isDefaultLib = true;\n files.unshift(file);\n }\n else {\n files.push(file);\n }\n }\n return file;\n function getSourceFileFromCache(fileName, useAbsolutePath) {\n var file = filesByName.get(fileName);\n if (file && host.useCaseSensitiveFileNames()) {\n var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName;\n if (ts.normalizeSlashes(fileName) !== ts.normalizeSlashes(sourceFileName)) {\n if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {\n fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));\n }\n else {\n fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));\n }\n }\n }\n return file;\n }\n }", "code_tokens": ["function", "findSourceFile", "(", "fileName", ",", "isDefaultLib", ",", "refFile", ",", "refPos", ",", "refEnd", ")", "{", "if", "(", "filesByName", ".", "contains", "(", "fileName", ")", ")", "{", "return", "getSourceFileFromCache", "(", "fileName", ",", "false", ")", ";", "}", "var", "normalizedAbsolutePath", "=", "ts", ".", "getNormalizedAbsolutePath", "(", "fileName", ",", "host", ".", "getCurrentDirectory", "(", ")", ")", ";", "if", "(", "filesByName", ".", "contains", "(", "normalizedAbsolutePath", ")", ")", "{", "var", "file_1", "=", "getSourceFileFromCache", "(", "normalizedAbsolutePath", ",", "true", ")", ";", "filesByName", ".", "set", "(", "fileName", ",", "file_1", ")", ";", "return", "file_1", ";", "}", "var", "file", "=", "host", ".", "getSourceFile", "(", "fileName", ",", "options", ".", "target", ",", "function", "(", "hostErrorMessage", ")", "{", "if", "(", "refFile", "!==", "undefined", "&&", "refPos", "!==", "undefined", "&&", "refEnd", "!==", "undefined", ")", "{", "fileProcessingDiagnostics", ".", "add", "(", "ts", ".", "createFileDiagnostic", "(", "refFile", ",", "refPos", ",", "refEnd", "-", "refPos", ",", "ts", ".", "Diagnostics", ".", "Cannot_read_file_0_Colon_1", ",", "fileName", ",", "hostErrorMessage", ")", ")", ";", "}", "else", "{", "fileProcessingDiagnostics", ".", "add", "(", "ts", ".", "createCompilerDiagnostic", "(", "ts", ".", "Diagnostics", ".", "Cannot_read_file_0_Colon_1", ",", "fileName", ",", "hostErrorMessage", ")", ")", ";", "}", "}", ")", ";", "filesByName", ".", "set", "(", "fileName", ",", "file", ")", ";", "if", "(", "file", ")", "{", "skipDefaultLib", "=", "skipDefaultLib", "||", "file", ".", "hasNoDefaultLib", ";", "filesByName", ".", "set", "(", "normalizedAbsolutePath", ",", "file", ")", ";", "var", "basePath", "=", "ts", ".", "getDirectoryPath", "(", "fileName", ")", ";", "if", "(", "!", "options", ".", "noResolve", ")", "{", "processReferencedFiles", "(", "file", ",", "basePath", ")", ";", "}", "processImportedModules", "(", "file", ",", "basePath", ")", ";", "if", "(", "isDefaultLib", ")", "{", "file", ".", "isDefaultLib", "=", "true", ";", "files", ".", "unshift", "(", "file", ")", ";", "}", "else", "{", "files", ".", "push", "(", "file", ")", ";", "}", "}", "return", "file", ";", "function", "getSourceFileFromCache", "(", "fileName", ",", "useAbsolutePath", ")", "{", "var", "file", "=", "filesByName", ".", "get", "(", "fileName", ")", ";", "if", "(", "file", "&&", "host", ".", "useCaseSensitiveFileNames", "(", ")", ")", "{", "var", "sourceFileName", "=", "useAbsolutePath", "?", "ts", ".", "getNormalizedAbsolutePath", "(", "file", ".", "fileName", ",", "host", ".", "getCurrentDirectory", "(", ")", ")", ":", "file", ".", "fileName", ";", "if", "(", "ts", ".", "normalizeSlashes", "(", "fileName", ")", "!==", "ts", ".", "normalizeSlashes", "(", "sourceFileName", ")", ")", "{", "if", "(", "refFile", "!==", "undefined", "&&", "refPos", "!==", "undefined", "&&", "refEnd", "!==", "undefined", ")", "{", "fileProcessingDiagnostics", ".", "add", "(", "ts", ".", "createFileDiagnostic", "(", "refFile", ",", "refPos", ",", "refEnd", "-", "refPos", ",", "ts", ".", "Diagnostics", ".", "File_name_0_differs_from_already_included_file_name_1_only_in_casing", ",", "fileName", ",", "sourceFileName", ")", ")", ";", "}", "else", "{", "fileProcessingDiagnostics", ".", "add", "(", "ts", ".", "createCompilerDiagnostic", "(", "ts", ".", "Diagnostics", ".", "File_name_0_differs_from_already_included_file_name_1_only_in_casing", ",", "fileName", ",", "sourceFileName", ")", ")", ";", "}", "}", "}", "return", "file", ";", "}", "}"], "docstring": "Get source file from normalized fileName", "docstring_tokens": ["Get", "source", "file", "from", "normalized", "fileName"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L36638-L36695", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "readConfigFile", "original_string": "function readConfigFile(fileName, readFile) {\n var text = \"\";\n try {\n text = readFile(fileName);\n }\n catch (e) {\n return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) };\n }\n return parseConfigFileTextToJson(fileName, text);\n }", "language": "javascript", "code": "function readConfigFile(fileName, readFile) {\n var text = \"\";\n try {\n text = readFile(fileName);\n }\n catch (e) {\n return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) };\n }\n return parseConfigFileTextToJson(fileName, text);\n }", "code_tokens": ["function", "readConfigFile", "(", "fileName", ",", "readFile", ")", "{", "var", "text", "=", "\"\"", ";", "try", "{", "text", "=", "readFile", "(", "fileName", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "{", "error", ":", "ts", ".", "createCompilerDiagnostic", "(", "ts", ".", "Diagnostics", ".", "Cannot_read_file_0_Colon_1", ",", "fileName", ",", "e", ".", "message", ")", "}", ";", "}", "return", "parseConfigFileTextToJson", "(", "fileName", ",", "text", ")", ";", "}"], "docstring": "Read tsconfig.json file\n@param fileName The path to the config file", "docstring_tokens": ["Read", "tsconfig", ".", "json", "file"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L37265-L37274", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "parseConfigFileTextToJson", "original_string": "function parseConfigFileTextToJson(fileName, jsonText) {\n try {\n return { config: /\\S/.test(jsonText) ? JSON.parse(jsonText) : {} };\n }\n catch (e) {\n return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) };\n }\n }", "language": "javascript", "code": "function parseConfigFileTextToJson(fileName, jsonText) {\n try {\n return { config: /\\S/.test(jsonText) ? JSON.parse(jsonText) : {} };\n }\n catch (e) {\n return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) };\n }\n }", "code_tokens": ["function", "parseConfigFileTextToJson", "(", "fileName", ",", "jsonText", ")", "{", "try", "{", "return", "{", "config", ":", "/", "\\S", "/", ".", "test", "(", "jsonText", ")", "?", "JSON", ".", "parse", "(", "jsonText", ")", ":", "{", "}", "}", ";", "}", "catch", "(", "e", ")", "{", "return", "{", "error", ":", "ts", ".", "createCompilerDiagnostic", "(", "ts", ".", "Diagnostics", ".", "Failed_to_parse_file_0_Colon_1", ",", "fileName", ",", "e", ".", "message", ")", "}", ";", "}", "}"], "docstring": "Parse the text of the tsconfig.json file\n@param fileName The path to the config file\n@param jsonText The text of the config file", "docstring_tokens": ["Parse", "the", "text", "of", "the", "tsconfig", ".", "json", "file"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L37281-L37288", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "removeDynamicallyNamedProperties", "original_string": "function removeDynamicallyNamedProperties(node) {\n return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); });\n }", "language": "javascript", "code": "function removeDynamicallyNamedProperties(node) {\n return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); });\n }", "code_tokens": ["function", "removeDynamicallyNamedProperties", "(", "node", ")", "{", "return", "ts", ".", "filter", "(", "node", ".", "members", ",", "function", "(", "member", ")", "{", "return", "!", "ts", ".", "hasDynamicName", "(", "member", ")", ";", "}", ")", ";", "}"], "docstring": "Like removeComputedProperties, but retains the properties with well known symbol names", "docstring_tokens": ["Like", "removeComputedProperties", "but", "retains", "the", "properties", "with", "well", "known", "symbol", "names"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L38110-L38112", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getImmediatelyContainingArgumentInfo", "original_string": "function getImmediatelyContainingArgumentInfo(node) {\n if (node.parent.kind === 168 /* CallExpression */ || node.parent.kind === 169 /* NewExpression */) {\n var callExpression = node.parent;\n // There are 3 cases to handle:\n // 1. The token introduces a list, and should begin a sig help session\n // 2. The token is either not associated with a list, or ends a list, so the session should end\n // 3. The token is buried inside a list, and should give sig help\n //\n // The following are examples of each:\n //\n // Case 1:\n // foo<#T, U>(#a, b) -> The token introduces a list, and should begin a sig help session\n // Case 2:\n // fo#o#(a, b)# -> The token is either not associated with a list, or ends a list, so the session should end\n // Case 3:\n // foo(a#, #b#) -> The token is buried inside a list, and should give sig help\n // Find out if 'node' is an argument, a type argument, or neither\n if (node.kind === 25 /* LessThanToken */ ||\n node.kind === 17 /* OpenParenToken */) {\n // Find the list that starts right *after* the < or ( token.\n // If the user has just opened a list, consider this item 0.\n var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile);\n var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos;\n ts.Debug.assert(list !== undefined);\n return {\n kind: isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */,\n invocation: callExpression,\n argumentsSpan: getApplicableSpanForArguments(list),\n argumentIndex: 0,\n argumentCount: getArgumentCount(list)\n };\n }\n // findListItemInfo can return undefined if we are not in parent's argument list\n // or type argument list. This includes cases where the cursor is:\n // - To the right of the closing paren, non-substitution template, or template tail.\n // - Between the type arguments and the arguments (greater than token)\n // - On the target of the call (parent.func)\n // - On the 'new' keyword in a 'new' expression\n var listItemInfo = ts.findListItemInfo(node);\n if (listItemInfo) {\n var list = listItemInfo.list;\n var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos;\n var argumentIndex = getArgumentIndex(list, node);\n var argumentCount = getArgumentCount(list);\n ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, \"argumentCount < argumentIndex, \" + argumentCount + \" < \" + argumentIndex);\n return {\n kind: isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */,\n invocation: callExpression,\n argumentsSpan: getApplicableSpanForArguments(list),\n argumentIndex: argumentIndex,\n argumentCount: argumentCount\n };\n }\n }\n else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 170 /* TaggedTemplateExpression */) {\n // Check if we're actually inside the template;\n // otherwise we'll fall out and return undefined.\n if (ts.isInsideTemplateLiteral(node, position)) {\n return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0);\n }\n }\n else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 170 /* TaggedTemplateExpression */) {\n var templateExpression = node.parent;\n var tagExpression = templateExpression.parent;\n ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */);\n var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1;\n return getArgumentListInfoForTemplate(tagExpression, argumentIndex);\n }\n else if (node.parent.kind === 190 /* TemplateSpan */ && node.parent.parent.parent.kind === 170 /* TaggedTemplateExpression */) {\n var templateSpan = node.parent;\n var templateExpression = templateSpan.parent;\n var tagExpression = templateExpression.parent;\n ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */);\n // If we're just after a template tail, don't show signature help.\n if (node.kind === 14 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) {\n return undefined;\n }\n var spanIndex = templateExpression.templateSpans.indexOf(templateSpan);\n var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node);\n return getArgumentListInfoForTemplate(tagExpression, argumentIndex);\n }\n return undefined;\n }", "language": "javascript", "code": "function getImmediatelyContainingArgumentInfo(node) {\n if (node.parent.kind === 168 /* CallExpression */ || node.parent.kind === 169 /* NewExpression */) {\n var callExpression = node.parent;\n // There are 3 cases to handle:\n // 1. The token introduces a list, and should begin a sig help session\n // 2. The token is either not associated with a list, or ends a list, so the session should end\n // 3. The token is buried inside a list, and should give sig help\n //\n // The following are examples of each:\n //\n // Case 1:\n // foo<#T, U>(#a, b) -> The token introduces a list, and should begin a sig help session\n // Case 2:\n // fo#o#(a, b)# -> The token is either not associated with a list, or ends a list, so the session should end\n // Case 3:\n // foo(a#, #b#) -> The token is buried inside a list, and should give sig help\n // Find out if 'node' is an argument, a type argument, or neither\n if (node.kind === 25 /* LessThanToken */ ||\n node.kind === 17 /* OpenParenToken */) {\n // Find the list that starts right *after* the < or ( token.\n // If the user has just opened a list, consider this item 0.\n var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile);\n var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos;\n ts.Debug.assert(list !== undefined);\n return {\n kind: isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */,\n invocation: callExpression,\n argumentsSpan: getApplicableSpanForArguments(list),\n argumentIndex: 0,\n argumentCount: getArgumentCount(list)\n };\n }\n // findListItemInfo can return undefined if we are not in parent's argument list\n // or type argument list. This includes cases where the cursor is:\n // - To the right of the closing paren, non-substitution template, or template tail.\n // - Between the type arguments and the arguments (greater than token)\n // - On the target of the call (parent.func)\n // - On the 'new' keyword in a 'new' expression\n var listItemInfo = ts.findListItemInfo(node);\n if (listItemInfo) {\n var list = listItemInfo.list;\n var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos;\n var argumentIndex = getArgumentIndex(list, node);\n var argumentCount = getArgumentCount(list);\n ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, \"argumentCount < argumentIndex, \" + argumentCount + \" < \" + argumentIndex);\n return {\n kind: isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */,\n invocation: callExpression,\n argumentsSpan: getApplicableSpanForArguments(list),\n argumentIndex: argumentIndex,\n argumentCount: argumentCount\n };\n }\n }\n else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 170 /* TaggedTemplateExpression */) {\n // Check if we're actually inside the template;\n // otherwise we'll fall out and return undefined.\n if (ts.isInsideTemplateLiteral(node, position)) {\n return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0);\n }\n }\n else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 170 /* TaggedTemplateExpression */) {\n var templateExpression = node.parent;\n var tagExpression = templateExpression.parent;\n ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */);\n var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1;\n return getArgumentListInfoForTemplate(tagExpression, argumentIndex);\n }\n else if (node.parent.kind === 190 /* TemplateSpan */ && node.parent.parent.parent.kind === 170 /* TaggedTemplateExpression */) {\n var templateSpan = node.parent;\n var templateExpression = templateSpan.parent;\n var tagExpression = templateExpression.parent;\n ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */);\n // If we're just after a template tail, don't show signature help.\n if (node.kind === 14 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) {\n return undefined;\n }\n var spanIndex = templateExpression.templateSpans.indexOf(templateSpan);\n var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node);\n return getArgumentListInfoForTemplate(tagExpression, argumentIndex);\n }\n return undefined;\n }", "code_tokens": ["function", "getImmediatelyContainingArgumentInfo", "(", "node", ")", "{", "if", "(", "node", ".", "parent", ".", "kind", "===", "168", "||", "node", ".", "parent", ".", "kind", "===", "169", ")", "{", "var", "callExpression", "=", "node", ".", "parent", ";", "if", "(", "node", ".", "kind", "===", "25", "||", "node", ".", "kind", "===", "17", ")", "{", "var", "list", "=", "getChildListThatStartsWithOpenerToken", "(", "callExpression", ",", "node", ",", "sourceFile", ")", ";", "var", "isTypeArgList", "=", "callExpression", ".", "typeArguments", "&&", "callExpression", ".", "typeArguments", ".", "pos", "===", "list", ".", "pos", ";", "ts", ".", "Debug", ".", "assert", "(", "list", "!==", "undefined", ")", ";", "return", "{", "kind", ":", "isTypeArgList", "?", "0", ":", "1", ",", "invocation", ":", "callExpression", ",", "argumentsSpan", ":", "getApplicableSpanForArguments", "(", "list", ")", ",", "argumentIndex", ":", "0", ",", "argumentCount", ":", "getArgumentCount", "(", "list", ")", "}", ";", "}", "var", "listItemInfo", "=", "ts", ".", "findListItemInfo", "(", "node", ")", ";", "if", "(", "listItemInfo", ")", "{", "var", "list", "=", "listItemInfo", ".", "list", ";", "var", "isTypeArgList", "=", "callExpression", ".", "typeArguments", "&&", "callExpression", ".", "typeArguments", ".", "pos", "===", "list", ".", "pos", ";", "var", "argumentIndex", "=", "getArgumentIndex", "(", "list", ",", "node", ")", ";", "var", "argumentCount", "=", "getArgumentCount", "(", "list", ")", ";", "ts", ".", "Debug", ".", "assert", "(", "argumentIndex", "===", "0", "||", "argumentIndex", "<", "argumentCount", ",", "\"argumentCount < argumentIndex, \"", "+", "argumentCount", "+", "\" < \"", "+", "argumentIndex", ")", ";", "return", "{", "kind", ":", "isTypeArgList", "?", "0", ":", "1", ",", "invocation", ":", "callExpression", ",", "argumentsSpan", ":", "getApplicableSpanForArguments", "(", "list", ")", ",", "argumentIndex", ":", "argumentIndex", ",", "argumentCount", ":", "argumentCount", "}", ";", "}", "}", "else", "if", "(", "node", ".", "kind", "===", "11", "&&", "node", ".", "parent", ".", "kind", "===", "170", ")", "{", "if", "(", "ts", ".", "isInsideTemplateLiteral", "(", "node", ",", "position", ")", ")", "{", "return", "getArgumentListInfoForTemplate", "(", "node", ".", "parent", ",", "0", ")", ";", "}", "}", "else", "if", "(", "node", ".", "kind", "===", "12", "&&", "node", ".", "parent", ".", "parent", ".", "kind", "===", "170", ")", "{", "var", "templateExpression", "=", "node", ".", "parent", ";", "var", "tagExpression", "=", "templateExpression", ".", "parent", ";", "ts", ".", "Debug", ".", "assert", "(", "templateExpression", ".", "kind", "===", "183", ")", ";", "var", "argumentIndex", "=", "ts", ".", "isInsideTemplateLiteral", "(", "node", ",", "position", ")", "?", "0", ":", "1", ";", "return", "getArgumentListInfoForTemplate", "(", "tagExpression", ",", "argumentIndex", ")", ";", "}", "else", "if", "(", "node", ".", "parent", ".", "kind", "===", "190", "&&", "node", ".", "parent", ".", "parent", ".", "parent", ".", "kind", "===", "170", ")", "{", "var", "templateSpan", "=", "node", ".", "parent", ";", "var", "templateExpression", "=", "templateSpan", ".", "parent", ";", "var", "tagExpression", "=", "templateExpression", ".", "parent", ";", "ts", ".", "Debug", ".", "assert", "(", "templateExpression", ".", "kind", "===", "183", ")", ";", "if", "(", "node", ".", "kind", "===", "14", "&&", "!", "ts", ".", "isInsideTemplateLiteral", "(", "node", ",", "position", ")", ")", "{", "return", "undefined", ";", "}", "var", "spanIndex", "=", "templateExpression", ".", "templateSpans", ".", "indexOf", "(", "templateSpan", ")", ";", "var", "argumentIndex", "=", "getArgumentIndexForTemplatePiece", "(", "spanIndex", ",", "node", ")", ";", "return", "getArgumentListInfoForTemplate", "(", "tagExpression", ",", "argumentIndex", ")", ";", "}", "return", "undefined", ";", "}"], "docstring": "Returns relevant information for the argument list and the current argument if we are\nin the argument of an invocation; returns undefined otherwise.", "docstring_tokens": ["Returns", "relevant", "information", "for", "the", "argument", "list", "and", "the", "current", "argument", "if", "we", "are", "in", "the", "argument", "of", "an", "invocation", ";", "returns", "undefined", "otherwise", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L38955-L39037", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "selectBestInvalidOverloadIndex", "original_string": "function selectBestInvalidOverloadIndex(candidates, argumentCount) {\n var maxParamsSignatureIndex = -1;\n var maxParams = -1;\n for (var i = 0; i < candidates.length; i++) {\n var candidate = candidates[i];\n if (candidate.hasRestParameter || candidate.parameters.length >= argumentCount) {\n return i;\n }\n if (candidate.parameters.length > maxParams) {\n maxParams = candidate.parameters.length;\n maxParamsSignatureIndex = i;\n }\n }\n return maxParamsSignatureIndex;\n }", "language": "javascript", "code": "function selectBestInvalidOverloadIndex(candidates, argumentCount) {\n var maxParamsSignatureIndex = -1;\n var maxParams = -1;\n for (var i = 0; i < candidates.length; i++) {\n var candidate = candidates[i];\n if (candidate.hasRestParameter || candidate.parameters.length >= argumentCount) {\n return i;\n }\n if (candidate.parameters.length > maxParams) {\n maxParams = candidate.parameters.length;\n maxParamsSignatureIndex = i;\n }\n }\n return maxParamsSignatureIndex;\n }", "code_tokens": ["function", "selectBestInvalidOverloadIndex", "(", "candidates", ",", "argumentCount", ")", "{", "var", "maxParamsSignatureIndex", "=", "-", "1", ";", "var", "maxParams", "=", "-", "1", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "candidates", ".", "length", ";", "i", "++", ")", "{", "var", "candidate", "=", "candidates", "[", "i", "]", ";", "if", "(", "candidate", ".", "hasRestParameter", "||", "candidate", ".", "parameters", ".", "length", ">=", "argumentCount", ")", "{", "return", "i", ";", "}", "if", "(", "candidate", ".", "parameters", ".", "length", ">", "maxParams", ")", "{", "maxParams", "=", "candidate", ".", "parameters", ".", "length", ";", "maxParamsSignatureIndex", "=", "i", ";", "}", "}", "return", "maxParamsSignatureIndex", ";", "}"], "docstring": "The selectedItemIndex could be negative for several reasons.\n1. There are too many arguments for all of the overloads\n2. None of the overloads were type compatible\nThe solution here is to try to pick the best overload by picking\neither the first one that has an appropriate number of parameters,\nor the one with the most parameters.", "docstring_tokens": ["The", "selectedItemIndex", "could", "be", "negative", "for", "several", "reasons", ".", "1", ".", "There", "are", "too", "many", "arguments", "for", "all", "of", "the", "overloads", "2", ".", "None", "of", "the", "overloads", "were", "type", "compatible", "The", "solution", "here", "is", "to", "try", "to", "pick", "the", "best", "overload", "by", "picking", "either", "the", "first", "one", "that", "has", "an", "appropriate", "number", "of", "parameters", "or", "the", "one", "with", "the", "most", "parameters", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L39184-L39198", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getTokenAtPositionWorker", "original_string": "function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition) {\n var current = sourceFile;\n outer: while (true) {\n if (isToken(current)) {\n // exit early\n return current;\n }\n // find the child that contains 'position'\n for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) {\n var child = current.getChildAt(i);\n var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile);\n if (start <= position) {\n var end = child.getEnd();\n if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) {\n current = child;\n continue outer;\n }\n else if (includeItemAtEndPosition && end === position) {\n var previousToken = findPrecedingToken(position, sourceFile, child);\n if (previousToken && includeItemAtEndPosition(previousToken)) {\n return previousToken;\n }\n }\n }\n }\n return current;\n }\n }", "language": "javascript", "code": "function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition) {\n var current = sourceFile;\n outer: while (true) {\n if (isToken(current)) {\n // exit early\n return current;\n }\n // find the child that contains 'position'\n for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) {\n var child = current.getChildAt(i);\n var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile);\n if (start <= position) {\n var end = child.getEnd();\n if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) {\n current = child;\n continue outer;\n }\n else if (includeItemAtEndPosition && end === position) {\n var previousToken = findPrecedingToken(position, sourceFile, child);\n if (previousToken && includeItemAtEndPosition(previousToken)) {\n return previousToken;\n }\n }\n }\n }\n return current;\n }\n }", "code_tokens": ["function", "getTokenAtPositionWorker", "(", "sourceFile", ",", "position", ",", "allowPositionInLeadingTrivia", ",", "includeItemAtEndPosition", ")", "{", "var", "current", "=", "sourceFile", ";", "outer", ":", "while", "(", "true", ")", "{", "if", "(", "isToken", "(", "current", ")", ")", "{", "return", "current", ";", "}", "for", "(", "var", "i", "=", "0", ",", "n", "=", "current", ".", "getChildCount", "(", "sourceFile", ")", ";", "i", "<", "n", ";", "i", "++", ")", "{", "var", "child", "=", "current", ".", "getChildAt", "(", "i", ")", ";", "var", "start", "=", "allowPositionInLeadingTrivia", "?", "child", ".", "getFullStart", "(", ")", ":", "child", ".", "getStart", "(", "sourceFile", ")", ";", "if", "(", "start", "<=", "position", ")", "{", "var", "end", "=", "child", ".", "getEnd", "(", ")", ";", "if", "(", "position", "<", "end", "||", "(", "position", "===", "end", "&&", "child", ".", "kind", "===", "1", ")", ")", "{", "current", "=", "child", ";", "continue", "outer", ";", "}", "else", "if", "(", "includeItemAtEndPosition", "&&", "end", "===", "position", ")", "{", "var", "previousToken", "=", "findPrecedingToken", "(", "position", ",", "sourceFile", ",", "child", ")", ";", "if", "(", "previousToken", "&&", "includeItemAtEndPosition", "(", "previousToken", ")", ")", "{", "return", "previousToken", ";", "}", "}", "}", "}", "return", "current", ";", "}", "}"], "docstring": "Get the token whose text contains the position", "docstring_tokens": ["Get", "the", "token", "whose", "text", "contains", "the", "position"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L39544-L39571", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "findTokenOnLeftOfPosition", "original_string": "function findTokenOnLeftOfPosition(file, position) {\n // Ideally, getTokenAtPosition should return a token. However, it is currently\n // broken, so we do a check to make sure the result was indeed a token.\n var tokenAtPosition = getTokenAtPosition(file, position);\n if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {\n return tokenAtPosition;\n }\n return findPrecedingToken(position, file);\n }", "language": "javascript", "code": "function findTokenOnLeftOfPosition(file, position) {\n // Ideally, getTokenAtPosition should return a token. However, it is currently\n // broken, so we do a check to make sure the result was indeed a token.\n var tokenAtPosition = getTokenAtPosition(file, position);\n if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {\n return tokenAtPosition;\n }\n return findPrecedingToken(position, file);\n }", "code_tokens": ["function", "findTokenOnLeftOfPosition", "(", "file", ",", "position", ")", "{", "var", "tokenAtPosition", "=", "getTokenAtPosition", "(", "file", ",", "position", ")", ";", "if", "(", "isToken", "(", "tokenAtPosition", ")", "&&", "position", ">", "tokenAtPosition", ".", "getStart", "(", "file", ")", "&&", "position", "<", "tokenAtPosition", ".", "getEnd", "(", ")", ")", "{", "return", "tokenAtPosition", ";", "}", "return", "findPrecedingToken", "(", "position", ",", "file", ")", ";", "}"], "docstring": "The token on the left of the position is the token that strictly includes the position\nor sits to the left of the cursor if it is on a boundary. For example\n\nfo|o -> will return foo\nfoo |bar -> will return foo", "docstring_tokens": ["The", "token", "on", "the", "left", "of", "the", "position", "is", "the", "token", "that", "strictly", "includes", "the", "position", "or", "sits", "to", "the", "left", "of", "the", "cursor", "if", "it", "is", "on", "a", "boundary", ".", "For", "example"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L39580-L39588", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getJsDocTagAtPosition", "original_string": "function getJsDocTagAtPosition(sourceFile, position) {\n var node = ts.getTokenAtPosition(sourceFile, position);\n if (isToken(node)) {\n switch (node.kind) {\n case 102 /* VarKeyword */:\n case 108 /* LetKeyword */:\n case 74 /* ConstKeyword */:\n // if the current token is var, let or const, skip the VariableDeclarationList\n node = node.parent === undefined ? undefined : node.parent.parent;\n break;\n default:\n node = node.parent;\n break;\n }\n }\n if (node) {\n var jsDocComment = node.jsDocComment;\n if (jsDocComment) {\n for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) {\n var tag = _a[_i];\n if (tag.pos <= position && position <= tag.end) {\n return tag;\n }\n }\n }\n }\n return undefined;\n }", "language": "javascript", "code": "function getJsDocTagAtPosition(sourceFile, position) {\n var node = ts.getTokenAtPosition(sourceFile, position);\n if (isToken(node)) {\n switch (node.kind) {\n case 102 /* VarKeyword */:\n case 108 /* LetKeyword */:\n case 74 /* ConstKeyword */:\n // if the current token is var, let or const, skip the VariableDeclarationList\n node = node.parent === undefined ? undefined : node.parent.parent;\n break;\n default:\n node = node.parent;\n break;\n }\n }\n if (node) {\n var jsDocComment = node.jsDocComment;\n if (jsDocComment) {\n for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) {\n var tag = _a[_i];\n if (tag.pos <= position && position <= tag.end) {\n return tag;\n }\n }\n }\n }\n return undefined;\n }", "code_tokens": ["function", "getJsDocTagAtPosition", "(", "sourceFile", ",", "position", ")", "{", "var", "node", "=", "ts", ".", "getTokenAtPosition", "(", "sourceFile", ",", "position", ")", ";", "if", "(", "isToken", "(", "node", ")", ")", "{", "switch", "(", "node", ".", "kind", ")", "{", "case", "102", ":", "case", "108", ":", "case", "74", ":", "node", "=", "node", ".", "parent", "===", "undefined", "?", "undefined", ":", "node", ".", "parent", ".", "parent", ";", "break", ";", "default", ":", "node", "=", "node", ".", "parent", ";", "break", ";", "}", "}", "if", "(", "node", ")", "{", "var", "jsDocComment", "=", "node", ".", "jsDocComment", ";", "if", "(", "jsDocComment", ")", "{", "for", "(", "var", "_i", "=", "0", ",", "_a", "=", "jsDocComment", ".", "tags", ";", "_i", "<", "_a", ".", "length", ";", "_i", "++", ")", "{", "var", "tag", "=", "_a", "[", "_i", "]", ";", "if", "(", "tag", ".", "pos", "<=", "position", "&&", "position", "<=", "tag", ".", "end", ")", "{", "return", "tag", ";", "}", "}", "}", "}", "return", "undefined", ";", "}"], "docstring": "Get the corresponding JSDocTag node if the position is in a jsDoc comment", "docstring_tokens": ["Get", "the", "corresponding", "JSDocTag", "node", "if", "the", "position", "is", "in", "a", "jsDoc", "comment"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L39724-L39751", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "stripQuotes", "original_string": "function stripQuotes(name) {\n var length = name.length;\n if (length >= 2 &&\n name.charCodeAt(0) === name.charCodeAt(length - 1) &&\n (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) {\n return name.substring(1, length - 1);\n }\n ;\n return name;\n }", "language": "javascript", "code": "function stripQuotes(name) {\n var length = name.length;\n if (length >= 2 &&\n name.charCodeAt(0) === name.charCodeAt(length - 1) &&\n (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) {\n return name.substring(1, length - 1);\n }\n ;\n return name;\n }", "code_tokens": ["function", "stripQuotes", "(", "name", ")", "{", "var", "length", "=", "name", ".", "length", ";", "if", "(", "length", ">=", "2", "&&", "name", ".", "charCodeAt", "(", "0", ")", "===", "name", ".", "charCodeAt", "(", "length", "-", "1", ")", "&&", "(", "name", ".", "charCodeAt", "(", "0", ")", "===", "34", "||", "name", ".", "charCodeAt", "(", "0", ")", "===", "39", ")", ")", "{", "return", "name", ".", "substring", "(", "1", ",", "length", "-", "1", ")", ";", "}", ";", "return", "name", ";", "}"], "docstring": "Strip off existed single quotes or double quotes from a given string\n\n@return non-quoted string", "docstring_tokens": ["Strip", "off", "existed", "single", "quotes", "or", "double", "quotes", "from", "a", "given", "string"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L40050-L40059", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "fixTokenKind", "original_string": "function fixTokenKind(tokenInfo, container) {\n if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) {\n tokenInfo.token.kind = container.kind;\n }\n return tokenInfo;\n }", "language": "javascript", "code": "function fixTokenKind(tokenInfo, container) {\n if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) {\n tokenInfo.token.kind = container.kind;\n }\n return tokenInfo;\n }", "code_tokens": ["function", "fixTokenKind", "(", "tokenInfo", ",", "container", ")", "{", "if", "(", "ts", ".", "isToken", "(", "container", ")", "&&", "tokenInfo", ".", "token", ".", "kind", "!==", "container", ".", "kind", ")", "{", "tokenInfo", ".", "token", ".", "kind", "=", "container", ".", "kind", ";", "}", "return", "tokenInfo", ";", "}"], "docstring": "when containing node in the tree is token but its kind differs from the kind that was returned by the scanner, then kind needs to be fixed. This might happen in cases when parser interprets token differently, i.e keyword treated as identifier", "docstring_tokens": ["when", "containing", "node", "in", "the", "tree", "is", "token", "but", "its", "kind", "differs", "from", "the", "kind", "that", "was", "returned", "by", "the", "scanner", "then", "kind", "needs", "to", "be", "fixed", ".", "This", "might", "happen", "in", "cases", "when", "parser", "interprets", "token", "differently", "i", ".", "e", "keyword", "treated", "as", "identifier"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L40286-L40291", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "isListElement", "original_string": "function isListElement(parent, node) {\n switch (parent.kind) {\n case 214 /* ClassDeclaration */:\n case 215 /* InterfaceDeclaration */:\n return ts.rangeContainsRange(parent.members, node);\n case 218 /* ModuleDeclaration */:\n var body = parent.body;\n return body && body.kind === 192 /* Block */ && ts.rangeContainsRange(body.statements, node);\n case 248 /* SourceFile */:\n case 192 /* Block */:\n case 219 /* ModuleBlock */:\n return ts.rangeContainsRange(parent.statements, node);\n case 244 /* CatchClause */:\n return ts.rangeContainsRange(parent.block.statements, node);\n }\n return false;\n }", "language": "javascript", "code": "function isListElement(parent, node) {\n switch (parent.kind) {\n case 214 /* ClassDeclaration */:\n case 215 /* InterfaceDeclaration */:\n return ts.rangeContainsRange(parent.members, node);\n case 218 /* ModuleDeclaration */:\n var body = parent.body;\n return body && body.kind === 192 /* Block */ && ts.rangeContainsRange(body.statements, node);\n case 248 /* SourceFile */:\n case 192 /* Block */:\n case 219 /* ModuleBlock */:\n return ts.rangeContainsRange(parent.statements, node);\n case 244 /* CatchClause */:\n return ts.rangeContainsRange(parent.block.statements, node);\n }\n return false;\n }", "code_tokens": ["function", "isListElement", "(", "parent", ",", "node", ")", "{", "switch", "(", "parent", ".", "kind", ")", "{", "case", "214", ":", "case", "215", ":", "return", "ts", ".", "rangeContainsRange", "(", "parent", ".", "members", ",", "node", ")", ";", "case", "218", ":", "var", "body", "=", "parent", ".", "body", ";", "return", "body", "&&", "body", ".", "kind", "===", "192", "&&", "ts", ".", "rangeContainsRange", "(", "body", ".", "statements", ",", "node", ")", ";", "case", "248", ":", "case", "192", ":", "case", "219", ":", "return", "ts", ".", "rangeContainsRange", "(", "parent", ".", "statements", ",", "node", ")", ";", "case", "244", ":", "return", "ts", ".", "rangeContainsRange", "(", "parent", ".", "block", ".", "statements", ",", "node", ")", ";", "}", "return", "false", ";", "}"], "docstring": "Returns true if node is a element in some list in parent i.e. parent is class declaration with the list of members and node is one of members.", "docstring_tokens": ["Returns", "true", "if", "node", "is", "a", "element", "in", "some", "list", "in", "parent", "i", ".", "e", ".", "parent", "is", "class", "declaration", "with", "the", "list", "of", "members", "and", "node", "is", "one", "of", "members", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L41511-L41527", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "findEnclosingNode", "original_string": "function findEnclosingNode(range, sourceFile) {\n return find(sourceFile);\n function find(n) {\n var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; });\n if (candidate) {\n var result = find(candidate);\n if (result) {\n return result;\n }\n }\n return n;\n }\n }", "language": "javascript", "code": "function findEnclosingNode(range, sourceFile) {\n return find(sourceFile);\n function find(n) {\n var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; });\n if (candidate) {\n var result = find(candidate);\n if (result) {\n return result;\n }\n }\n return n;\n }\n }", "code_tokens": ["function", "findEnclosingNode", "(", "range", ",", "sourceFile", ")", "{", "return", "find", "(", "sourceFile", ")", ";", "function", "find", "(", "n", ")", "{", "var", "candidate", "=", "ts", ".", "forEachChild", "(", "n", ",", "function", "(", "c", ")", "{", "return", "ts", ".", "startEndContainsRange", "(", "c", ".", "getStart", "(", "sourceFile", ")", ",", "c", ".", "end", ",", "range", ")", "&&", "c", ";", "}", ")", ";", "if", "(", "candidate", ")", "{", "var", "result", "=", "find", "(", "candidate", ")", ";", "if", "(", "result", ")", "{", "return", "result", ";", "}", "}", "return", "n", ";", "}", "}"], "docstring": "find node that fully contains given text range", "docstring_tokens": ["find", "node", "that", "fully", "contains", "given", "text", "range"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L41529-L41541", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "prepareRangeContainsErrorFunction", "original_string": "function prepareRangeContainsErrorFunction(errors, originalRange) {\n if (!errors.length) {\n return rangeHasNoErrors;\n }\n // pick only errors that fall in range\n var sorted = errors\n .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); })\n .sort(function (e1, e2) { return e1.start - e2.start; });\n if (!sorted.length) {\n return rangeHasNoErrors;\n }\n var index = 0;\n return function (r) {\n // in current implementation sequence of arguments [r1, r2...] is monotonically increasing.\n // 'index' tracks the index of the most recent error that was checked.\n while (true) {\n if (index >= sorted.length) {\n // all errors in the range were already checked -> no error in specified range\n return false;\n }\n var error = sorted[index];\n if (r.end <= error.start) {\n // specified range ends before the error refered by 'index' - no error in range\n return false;\n }\n if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) {\n // specified range overlaps with error range\n return true;\n }\n index++;\n }\n };\n function rangeHasNoErrors(r) {\n return false;\n }\n }", "language": "javascript", "code": "function prepareRangeContainsErrorFunction(errors, originalRange) {\n if (!errors.length) {\n return rangeHasNoErrors;\n }\n // pick only errors that fall in range\n var sorted = errors\n .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); })\n .sort(function (e1, e2) { return e1.start - e2.start; });\n if (!sorted.length) {\n return rangeHasNoErrors;\n }\n var index = 0;\n return function (r) {\n // in current implementation sequence of arguments [r1, r2...] is monotonically increasing.\n // 'index' tracks the index of the most recent error that was checked.\n while (true) {\n if (index >= sorted.length) {\n // all errors in the range were already checked -> no error in specified range\n return false;\n }\n var error = sorted[index];\n if (r.end <= error.start) {\n // specified range ends before the error refered by 'index' - no error in range\n return false;\n }\n if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) {\n // specified range overlaps with error range\n return true;\n }\n index++;\n }\n };\n function rangeHasNoErrors(r) {\n return false;\n }\n }", "code_tokens": ["function", "prepareRangeContainsErrorFunction", "(", "errors", ",", "originalRange", ")", "{", "if", "(", "!", "errors", ".", "length", ")", "{", "return", "rangeHasNoErrors", ";", "}", "var", "sorted", "=", "errors", ".", "filter", "(", "function", "(", "d", ")", "{", "return", "ts", ".", "rangeOverlapsWithStartEnd", "(", "originalRange", ",", "d", ".", "start", ",", "d", ".", "start", "+", "d", ".", "length", ")", ";", "}", ")", ".", "sort", "(", "function", "(", "e1", ",", "e2", ")", "{", "return", "e1", ".", "start", "-", "e2", ".", "start", ";", "}", ")", ";", "if", "(", "!", "sorted", ".", "length", ")", "{", "return", "rangeHasNoErrors", ";", "}", "var", "index", "=", "0", ";", "return", "function", "(", "r", ")", "{", "while", "(", "true", ")", "{", "if", "(", "index", ">=", "sorted", ".", "length", ")", "{", "return", "false", ";", "}", "var", "error", "=", "sorted", "[", "index", "]", ";", "if", "(", "r", ".", "end", "<=", "error", ".", "start", ")", "{", "return", "false", ";", "}", "if", "(", "ts", ".", "startEndOverlapsWithStartEnd", "(", "r", ".", "pos", ",", "r", ".", "end", ",", "error", ".", "start", ",", "error", ".", "start", "+", "error", ".", "length", ")", ")", "{", "return", "true", ";", "}", "index", "++", ";", "}", "}", ";", "function", "rangeHasNoErrors", "(", "r", ")", "{", "return", "false", ";", "}", "}"], "docstring": "formatting is not applied to ranges that contain parse errors.\nThis function will return a predicate that for a given text range will tell\nif there are any parse errors that overlap with the range.", "docstring_tokens": ["formatting", "is", "not", "applied", "to", "ranges", "that", "contain", "parse", "errors", ".", "This", "function", "will", "return", "a", "predicate", "that", "for", "a", "given", "text", "range", "will", "tell", "if", "there", "are", "any", "parse", "errors", "that", "overlap", "with", "the", "range", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L41546-L41581", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "isInsideComment", "original_string": "function isInsideComment(sourceFile, token, position) {\n // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment\n return position <= token.getStart(sourceFile) &&\n (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) ||\n isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart())));\n function isInsideCommentRange(comments) {\n return ts.forEach(comments, function (comment) {\n // either we are 1. completely inside the comment, or 2. at the end of the comment\n if (comment.pos < position && position < comment.end) {\n return true;\n }\n else if (position === comment.end) {\n var text = sourceFile.text;\n var width = comment.end - comment.pos;\n // is single line comment or just /*\n if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) {\n return true;\n }\n else {\n // is unterminated multi-line comment\n return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ &&\n text.charCodeAt(comment.end - 2) === 42 /* asterisk */);\n }\n }\n return false;\n });\n }\n }", "language": "javascript", "code": "function isInsideComment(sourceFile, token, position) {\n // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment\n return position <= token.getStart(sourceFile) &&\n (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) ||\n isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart())));\n function isInsideCommentRange(comments) {\n return ts.forEach(comments, function (comment) {\n // either we are 1. completely inside the comment, or 2. at the end of the comment\n if (comment.pos < position && position < comment.end) {\n return true;\n }\n else if (position === comment.end) {\n var text = sourceFile.text;\n var width = comment.end - comment.pos;\n // is single line comment or just /*\n if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) {\n return true;\n }\n else {\n // is unterminated multi-line comment\n return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ &&\n text.charCodeAt(comment.end - 2) === 42 /* asterisk */);\n }\n }\n return false;\n });\n }\n }", "code_tokens": ["function", "isInsideComment", "(", "sourceFile", ",", "token", ",", "position", ")", "{", "return", "position", "<=", "token", ".", "getStart", "(", "sourceFile", ")", "&&", "(", "isInsideCommentRange", "(", "ts", ".", "getTrailingCommentRanges", "(", "sourceFile", ".", "text", ",", "token", ".", "getFullStart", "(", ")", ")", ")", "||", "isInsideCommentRange", "(", "ts", ".", "getLeadingCommentRanges", "(", "sourceFile", ".", "text", ",", "token", ".", "getFullStart", "(", ")", ")", ")", ")", ";", "function", "isInsideCommentRange", "(", "comments", ")", "{", "return", "ts", ".", "forEach", "(", "comments", ",", "function", "(", "comment", ")", "{", "if", "(", "comment", ".", "pos", "<", "position", "&&", "position", "<", "comment", ".", "end", ")", "{", "return", "true", ";", "}", "else", "if", "(", "position", "===", "comment", ".", "end", ")", "{", "var", "text", "=", "sourceFile", ".", "text", ";", "var", "width", "=", "comment", ".", "end", "-", "comment", ".", "pos", ";", "if", "(", "width", "<=", "2", "||", "text", ".", "charCodeAt", "(", "comment", ".", "pos", "+", "1", ")", "===", "47", ")", "{", "return", "true", ";", "}", "else", "{", "return", "!", "(", "text", ".", "charCodeAt", "(", "comment", ".", "end", "-", "1", ")", "===", "47", "&&", "text", ".", "charCodeAt", "(", "comment", ".", "end", "-", "2", ")", "===", "42", ")", ";", "}", "}", "return", "false", ";", "}", ")", ";", "}", "}"], "docstring": "Returns true if the position is within a comment", "docstring_tokens": ["Returns", "true", "if", "the", "position", "is", "within", "a", "comment"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L44316-L44343", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getSemanticDiagnostics", "original_string": "function getSemanticDiagnostics(fileName) {\n synchronizeHostData();\n var targetSourceFile = getValidSourceFile(fileName);\n // For JavaScript files, we don't want to report the normal typescript semantic errors.\n // Instead, we just report errors for using TypeScript-only constructs from within a\n // JavaScript file.\n if (ts.isJavaScript(fileName)) {\n return getJavaScriptSemanticDiagnostics(targetSourceFile);\n }\n // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file.\n // Therefore only get diagnostics for given file.\n var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken);\n if (!program.getCompilerOptions().declaration) {\n return semanticDiagnostics;\n }\n // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface\n var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);\n return ts.concatenate(semanticDiagnostics, declarationDiagnostics);\n }", "language": "javascript", "code": "function getSemanticDiagnostics(fileName) {\n synchronizeHostData();\n var targetSourceFile = getValidSourceFile(fileName);\n // For JavaScript files, we don't want to report the normal typescript semantic errors.\n // Instead, we just report errors for using TypeScript-only constructs from within a\n // JavaScript file.\n if (ts.isJavaScript(fileName)) {\n return getJavaScriptSemanticDiagnostics(targetSourceFile);\n }\n // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file.\n // Therefore only get diagnostics for given file.\n var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken);\n if (!program.getCompilerOptions().declaration) {\n return semanticDiagnostics;\n }\n // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface\n var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken);\n return ts.concatenate(semanticDiagnostics, declarationDiagnostics);\n }", "code_tokens": ["function", "getSemanticDiagnostics", "(", "fileName", ")", "{", "synchronizeHostData", "(", ")", ";", "var", "targetSourceFile", "=", "getValidSourceFile", "(", "fileName", ")", ";", "if", "(", "ts", ".", "isJavaScript", "(", "fileName", ")", ")", "{", "return", "getJavaScriptSemanticDiagnostics", "(", "targetSourceFile", ")", ";", "}", "var", "semanticDiagnostics", "=", "program", ".", "getSemanticDiagnostics", "(", "targetSourceFile", ",", "cancellationToken", ")", ";", "if", "(", "!", "program", ".", "getCompilerOptions", "(", ")", ".", "declaration", ")", "{", "return", "semanticDiagnostics", ";", "}", "var", "declarationDiagnostics", "=", "program", ".", "getDeclarationDiagnostics", "(", "targetSourceFile", ",", "cancellationToken", ")", ";", "return", "ts", ".", "concatenate", "(", "semanticDiagnostics", ",", "declarationDiagnostics", ")", ";", "}"], "docstring": "getSemanticDiagnostiscs return array of Diagnostics. If '-d' is not enabled, only report semantic errors\nIf '-d' enabled, report both semantic and emitter errors", "docstring_tokens": ["getSemanticDiagnostiscs", "return", "array", "of", "Diagnostics", ".", "If", "-", "d", "is", "not", "enabled", "only", "report", "semantic", "errors", "If", "-", "d", "enabled", "report", "both", "semantic", "and", "emitter", "errors"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L44643-L44661", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getCompletionEntryDisplayName", "original_string": "function getCompletionEntryDisplayName(name, target, performCharacterChecks) {\n if (!name) {\n return undefined;\n }\n name = ts.stripQuotes(name);\n if (!name) {\n return undefined;\n }\n // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an\n // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name.\n // e.g \"b a\" is valid quoted name but when we strip off the quotes, it is invalid.\n // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name.\n if (performCharacterChecks) {\n if (!ts.isIdentifierStart(name.charCodeAt(0), target)) {\n return undefined;\n }\n for (var i = 1, n = name.length; i < n; i++) {\n if (!ts.isIdentifierPart(name.charCodeAt(i), target)) {\n return undefined;\n }\n }\n }\n return name;\n }", "language": "javascript", "code": "function getCompletionEntryDisplayName(name, target, performCharacterChecks) {\n if (!name) {\n return undefined;\n }\n name = ts.stripQuotes(name);\n if (!name) {\n return undefined;\n }\n // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an\n // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name.\n // e.g \"b a\" is valid quoted name but when we strip off the quotes, it is invalid.\n // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name.\n if (performCharacterChecks) {\n if (!ts.isIdentifierStart(name.charCodeAt(0), target)) {\n return undefined;\n }\n for (var i = 1, n = name.length; i < n; i++) {\n if (!ts.isIdentifierPart(name.charCodeAt(i), target)) {\n return undefined;\n }\n }\n }\n return name;\n }", "code_tokens": ["function", "getCompletionEntryDisplayName", "(", "name", ",", "target", ",", "performCharacterChecks", ")", "{", "if", "(", "!", "name", ")", "{", "return", "undefined", ";", "}", "name", "=", "ts", ".", "stripQuotes", "(", "name", ")", ";", "if", "(", "!", "name", ")", "{", "return", "undefined", ";", "}", "if", "(", "performCharacterChecks", ")", "{", "if", "(", "!", "ts", ".", "isIdentifierStart", "(", "name", ".", "charCodeAt", "(", "0", ")", ",", "target", ")", ")", "{", "return", "undefined", ";", "}", "for", "(", "var", "i", "=", "1", ",", "n", "=", "name", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "if", "(", "!", "ts", ".", "isIdentifierPart", "(", "name", ".", "charCodeAt", "(", "i", ")", ",", "target", ")", ")", "{", "return", "undefined", ";", "}", "}", "}", "return", "name", ";", "}"], "docstring": "Get a displayName from a given for completion list, performing any necessary quotes stripping\nand checking whether the name is valid identifier name.", "docstring_tokens": ["Get", "a", "displayName", "from", "a", "given", "for", "completion", "list", "performing", "any", "necessary", "quotes", "stripping", "and", "checking", "whether", "the", "name", "is", "valid", "identifier", "name", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L44833-L44856", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getScopeNode", "original_string": "function getScopeNode(initialToken, position, sourceFile) {\n var scope = initialToken;\n while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) {\n scope = scope.parent;\n }\n return scope;\n }", "language": "javascript", "code": "function getScopeNode(initialToken, position, sourceFile) {\n var scope = initialToken;\n while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) {\n scope = scope.parent;\n }\n return scope;\n }", "code_tokens": ["function", "getScopeNode", "(", "initialToken", ",", "position", ",", "sourceFile", ")", "{", "var", "scope", "=", "initialToken", ";", "while", "(", "scope", "&&", "!", "ts", ".", "positionBelongsToNode", "(", "scope", ",", "position", ",", "sourceFile", ")", ")", "{", "scope", "=", "scope", ".", "parent", ";", "}", "return", "scope", ";", "}"], "docstring": "Finds the first node that \"embraces\" the position, so that one may\naccurately aggregate locals from the closest containing scope.", "docstring_tokens": ["Finds", "the", "first", "node", "that", "embraces", "the", "position", "so", "that", "one", "may", "accurately", "aggregate", "locals", "from", "the", "closest", "containing", "scope", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L45108-L45114", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "tryGetObjectLikeCompletionSymbols", "original_string": "function tryGetObjectLikeCompletionSymbols(objectLikeContainer) {\n // We're looking up possible property names from contextual/inferred/declared type.\n isMemberCompletion = true;\n var typeForObject;\n var existingMembers;\n if (objectLikeContainer.kind === 165 /* ObjectLiteralExpression */) {\n // We are completing on contextual types, but may also include properties\n // other than those within the declared type.\n isNewIdentifierLocation = true;\n typeForObject = typeChecker.getContextualType(objectLikeContainer);\n existingMembers = objectLikeContainer.properties;\n }\n else if (objectLikeContainer.kind === 161 /* ObjectBindingPattern */) {\n // We are *only* completing on properties from the type being destructured.\n isNewIdentifierLocation = false;\n var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);\n if (ts.isVariableLike(rootDeclaration)) {\n // We don't want to complete using the type acquired by the shape\n // of the binding pattern; we are only interested in types acquired\n // through type declaration or inference.\n if (rootDeclaration.initializer || rootDeclaration.type) {\n typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);\n existingMembers = objectLikeContainer.elements;\n }\n }\n else {\n ts.Debug.fail(\"Root declaration is not variable-like.\");\n }\n }\n else {\n ts.Debug.fail(\"Expected object literal or binding pattern, got \" + objectLikeContainer.kind);\n }\n if (!typeForObject) {\n return false;\n }\n var typeMembers = typeChecker.getPropertiesOfType(typeForObject);\n if (typeMembers && typeMembers.length > 0) {\n // Add filtered items to the completion list\n symbols = filterObjectMembersList(typeMembers, existingMembers);\n }\n return true;\n }", "language": "javascript", "code": "function tryGetObjectLikeCompletionSymbols(objectLikeContainer) {\n // We're looking up possible property names from contextual/inferred/declared type.\n isMemberCompletion = true;\n var typeForObject;\n var existingMembers;\n if (objectLikeContainer.kind === 165 /* ObjectLiteralExpression */) {\n // We are completing on contextual types, but may also include properties\n // other than those within the declared type.\n isNewIdentifierLocation = true;\n typeForObject = typeChecker.getContextualType(objectLikeContainer);\n existingMembers = objectLikeContainer.properties;\n }\n else if (objectLikeContainer.kind === 161 /* ObjectBindingPattern */) {\n // We are *only* completing on properties from the type being destructured.\n isNewIdentifierLocation = false;\n var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);\n if (ts.isVariableLike(rootDeclaration)) {\n // We don't want to complete using the type acquired by the shape\n // of the binding pattern; we are only interested in types acquired\n // through type declaration or inference.\n if (rootDeclaration.initializer || rootDeclaration.type) {\n typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);\n existingMembers = objectLikeContainer.elements;\n }\n }\n else {\n ts.Debug.fail(\"Root declaration is not variable-like.\");\n }\n }\n else {\n ts.Debug.fail(\"Expected object literal or binding pattern, got \" + objectLikeContainer.kind);\n }\n if (!typeForObject) {\n return false;\n }\n var typeMembers = typeChecker.getPropertiesOfType(typeForObject);\n if (typeMembers && typeMembers.length > 0) {\n // Add filtered items to the completion list\n symbols = filterObjectMembersList(typeMembers, existingMembers);\n }\n return true;\n }", "code_tokens": ["function", "tryGetObjectLikeCompletionSymbols", "(", "objectLikeContainer", ")", "{", "isMemberCompletion", "=", "true", ";", "var", "typeForObject", ";", "var", "existingMembers", ";", "if", "(", "objectLikeContainer", ".", "kind", "===", "165", ")", "{", "isNewIdentifierLocation", "=", "true", ";", "typeForObject", "=", "typeChecker", ".", "getContextualType", "(", "objectLikeContainer", ")", ";", "existingMembers", "=", "objectLikeContainer", ".", "properties", ";", "}", "else", "if", "(", "objectLikeContainer", ".", "kind", "===", "161", ")", "{", "isNewIdentifierLocation", "=", "false", ";", "var", "rootDeclaration", "=", "ts", ".", "getRootDeclaration", "(", "objectLikeContainer", ".", "parent", ")", ";", "if", "(", "ts", ".", "isVariableLike", "(", "rootDeclaration", ")", ")", "{", "if", "(", "rootDeclaration", ".", "initializer", "||", "rootDeclaration", ".", "type", ")", "{", "typeForObject", "=", "typeChecker", ".", "getTypeAtLocation", "(", "objectLikeContainer", ")", ";", "existingMembers", "=", "objectLikeContainer", ".", "elements", ";", "}", "}", "else", "{", "ts", ".", "Debug", ".", "fail", "(", "\"Root declaration is not variable-like.\"", ")", ";", "}", "}", "else", "{", "ts", ".", "Debug", ".", "fail", "(", "\"Expected object literal or binding pattern, got \"", "+", "objectLikeContainer", ".", "kind", ")", ";", "}", "if", "(", "!", "typeForObject", ")", "{", "return", "false", ";", "}", "var", "typeMembers", "=", "typeChecker", ".", "getPropertiesOfType", "(", "typeForObject", ")", ";", "if", "(", "typeMembers", "&&", "typeMembers", ".", "length", ">", "0", ")", "{", "symbols", "=", "filterObjectMembersList", "(", "typeMembers", ",", "existingMembers", ")", ";", "}", "return", "true", ";", "}"], "docstring": "Aggregates relevant symbols for completion in object literals and object binding patterns.\nRelevant symbols are stored in the captured 'symbols' variable.\n\n@returns true if 'symbols' was successfully populated; false otherwise.", "docstring_tokens": ["Aggregates", "relevant", "symbols", "for", "completion", "in", "object", "literals", "and", "object", "binding", "patterns", ".", "Relevant", "symbols", "are", "stored", "in", "the", "captured", "symbols", "variable", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L45214-L45255", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "tryGetImportOrExportClauseCompletionSymbols", "original_string": "function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) {\n var declarationKind = namedImportsOrExports.kind === 225 /* NamedImports */ ?\n 222 /* ImportDeclaration */ :\n 228 /* ExportDeclaration */;\n var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind);\n var moduleSpecifier = importOrExportDeclaration.moduleSpecifier;\n if (!moduleSpecifier) {\n return false;\n }\n isMemberCompletion = true;\n isNewIdentifierLocation = false;\n var exports;\n var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier);\n if (moduleSpecifierSymbol) {\n exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol);\n }\n symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray;\n return true;\n }", "language": "javascript", "code": "function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) {\n var declarationKind = namedImportsOrExports.kind === 225 /* NamedImports */ ?\n 222 /* ImportDeclaration */ :\n 228 /* ExportDeclaration */;\n var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind);\n var moduleSpecifier = importOrExportDeclaration.moduleSpecifier;\n if (!moduleSpecifier) {\n return false;\n }\n isMemberCompletion = true;\n isNewIdentifierLocation = false;\n var exports;\n var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier);\n if (moduleSpecifierSymbol) {\n exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol);\n }\n symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray;\n return true;\n }", "code_tokens": ["function", "tryGetImportOrExportClauseCompletionSymbols", "(", "namedImportsOrExports", ")", "{", "var", "declarationKind", "=", "namedImportsOrExports", ".", "kind", "===", "225", "?", "222", ":", "228", ";", "var", "importOrExportDeclaration", "=", "ts", ".", "getAncestor", "(", "namedImportsOrExports", ",", "declarationKind", ")", ";", "var", "moduleSpecifier", "=", "importOrExportDeclaration", ".", "moduleSpecifier", ";", "if", "(", "!", "moduleSpecifier", ")", "{", "return", "false", ";", "}", "isMemberCompletion", "=", "true", ";", "isNewIdentifierLocation", "=", "false", ";", "var", "exports", ";", "var", "moduleSpecifierSymbol", "=", "typeChecker", ".", "getSymbolAtLocation", "(", "importOrExportDeclaration", ".", "moduleSpecifier", ")", ";", "if", "(", "moduleSpecifierSymbol", ")", "{", "exports", "=", "typeChecker", ".", "getExportsOfModule", "(", "moduleSpecifierSymbol", ")", ";", "}", "symbols", "=", "exports", "?", "filterNamedImportOrExportCompletionItems", "(", "exports", ",", "namedImportsOrExports", ".", "elements", ")", ":", "emptyArray", ";", "return", "true", ";", "}"], "docstring": "Aggregates relevant symbols for completion in import clauses and export clauses\nwhose declarations have a module specifier; for instance, symbols will be aggregated for\n\nimport { | } from \"moduleName\";\nexport { a as foo, | } from \"moduleName\";\n\nbut not for\n\nexport { | };\n\nRelevant symbols are stored in the captured 'symbols' variable.\n\n@returns true if 'symbols' was successfully populated; false otherwise.", "docstring_tokens": ["Aggregates", "relevant", "symbols", "for", "completion", "in", "import", "clauses", "and", "export", "clauses", "whose", "declarations", "have", "a", "module", "specifier", ";", "for", "instance", "symbols", "will", "be", "aggregated", "for"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L45271-L45289", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "tryGetObjectLikeCompletionContainer", "original_string": "function tryGetObjectLikeCompletionContainer(contextToken) {\n if (contextToken) {\n switch (contextToken.kind) {\n case 15 /* OpenBraceToken */: // let x = { |\n case 24 /* CommaToken */:\n var parent_10 = contextToken.parent;\n if (parent_10 && (parent_10.kind === 165 /* ObjectLiteralExpression */ || parent_10.kind === 161 /* ObjectBindingPattern */)) {\n return parent_10;\n }\n break;\n }\n }\n return undefined;\n }", "language": "javascript", "code": "function tryGetObjectLikeCompletionContainer(contextToken) {\n if (contextToken) {\n switch (contextToken.kind) {\n case 15 /* OpenBraceToken */: // let x = { |\n case 24 /* CommaToken */:\n var parent_10 = contextToken.parent;\n if (parent_10 && (parent_10.kind === 165 /* ObjectLiteralExpression */ || parent_10.kind === 161 /* ObjectBindingPattern */)) {\n return parent_10;\n }\n break;\n }\n }\n return undefined;\n }", "code_tokens": ["function", "tryGetObjectLikeCompletionContainer", "(", "contextToken", ")", "{", "if", "(", "contextToken", ")", "{", "switch", "(", "contextToken", ".", "kind", ")", "{", "case", "15", ":", "case", "24", ":", "var", "parent_10", "=", "contextToken", ".", "parent", ";", "if", "(", "parent_10", "&&", "(", "parent_10", ".", "kind", "===", "165", "||", "parent_10", ".", "kind", "===", "161", ")", ")", "{", "return", "parent_10", ";", "}", "break", ";", "}", "}", "return", "undefined", ";", "}"], "docstring": "Returns the immediate owning object literal or binding pattern of a context token,\non the condition that one exists and that the context implies completion should be given.", "docstring_tokens": ["Returns", "the", "immediate", "owning", "object", "literal", "or", "binding", "pattern", "of", "a", "context", "token", "on", "the", "condition", "that", "one", "exists", "and", "that", "the", "context", "implies", "completion", "should", "be", "given", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L45294-L45307", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "filterJsxAttributes", "original_string": "function filterJsxAttributes(symbols, attributes) {\n var seenNames = {};\n for (var _i = 0; _i < attributes.length; _i++) {\n var attr = attributes[_i];\n // If this is the current item we are editing right now, do not filter it out\n if (attr.getStart() <= position && position <= attr.getEnd()) {\n continue;\n }\n if (attr.kind === 238 /* JsxAttribute */) {\n seenNames[attr.name.text] = true;\n }\n }\n return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); });\n }", "language": "javascript", "code": "function filterJsxAttributes(symbols, attributes) {\n var seenNames = {};\n for (var _i = 0; _i < attributes.length; _i++) {\n var attr = attributes[_i];\n // If this is the current item we are editing right now, do not filter it out\n if (attr.getStart() <= position && position <= attr.getEnd()) {\n continue;\n }\n if (attr.kind === 238 /* JsxAttribute */) {\n seenNames[attr.name.text] = true;\n }\n }\n return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); });\n }", "code_tokens": ["function", "filterJsxAttributes", "(", "symbols", ",", "attributes", ")", "{", "var", "seenNames", "=", "{", "}", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "attributes", ".", "length", ";", "_i", "++", ")", "{", "var", "attr", "=", "attributes", "[", "_i", "]", ";", "if", "(", "attr", ".", "getStart", "(", ")", "<=", "position", "&&", "position", "<=", "attr", ".", "getEnd", "(", ")", ")", "{", "continue", ";", "}", "if", "(", "attr", ".", "kind", "===", "238", ")", "{", "seenNames", "[", "attr", ".", "name", ".", "text", "]", "=", "true", ";", "}", "}", "return", "ts", ".", "filter", "(", "symbols", ",", "function", "(", "a", ")", "{", "return", "!", "ts", ".", "lookUp", "(", "seenNames", ",", "a", ".", "name", ")", ";", "}", ")", ";", "}"], "docstring": "Filters out completion suggestions from 'symbols' according to existing JSX attributes.\n\n@returns Symbols to be suggested in a JSX element, barring those whose attributes\ndo not occur at the current position and have not otherwise been typed.", "docstring_tokens": ["Filters", "out", "completion", "suggestions", "from", "symbols", "according", "to", "existing", "JSX", "attributes", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L45546-L45559", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "isWriteAccess", "original_string": "function isWriteAccess(node) {\n if (node.kind === 69 /* Identifier */ && ts.isDeclarationName(node)) {\n return true;\n }\n var parent = node.parent;\n if (parent) {\n if (parent.kind === 180 /* PostfixUnaryExpression */ || parent.kind === 179 /* PrefixUnaryExpression */) {\n return true;\n }\n else if (parent.kind === 181 /* BinaryExpression */ && parent.left === node) {\n var operator = parent.operatorToken.kind;\n return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */;\n }\n }\n return false;\n }", "language": "javascript", "code": "function isWriteAccess(node) {\n if (node.kind === 69 /* Identifier */ && ts.isDeclarationName(node)) {\n return true;\n }\n var parent = node.parent;\n if (parent) {\n if (parent.kind === 180 /* PostfixUnaryExpression */ || parent.kind === 179 /* PrefixUnaryExpression */) {\n return true;\n }\n else if (parent.kind === 181 /* BinaryExpression */ && parent.left === node) {\n var operator = parent.operatorToken.kind;\n return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */;\n }\n }\n return false;\n }", "code_tokens": ["function", "isWriteAccess", "(", "node", ")", "{", "if", "(", "node", ".", "kind", "===", "69", "&&", "ts", ".", "isDeclarationName", "(", "node", ")", ")", "{", "return", "true", ";", "}", "var", "parent", "=", "node", ".", "parent", ";", "if", "(", "parent", ")", "{", "if", "(", "parent", ".", "kind", "===", "180", "||", "parent", ".", "kind", "===", "179", ")", "{", "return", "true", ";", "}", "else", "if", "(", "parent", ".", "kind", "===", "181", "&&", "parent", ".", "left", "===", "node", ")", "{", "var", "operator", "=", "parent", ".", "operatorToken", ".", "kind", ";", "return", "56", "<=", "operator", "&&", "operator", "<=", "68", ";", "}", "}", "return", "false", ";", "}"], "docstring": "A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment", "docstring_tokens": ["A", "node", "is", "considered", "a", "writeAccess", "iff", "it", "is", "a", "name", "of", "a", "declaration", "or", "a", "target", "of", "an", "assignment"], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L47573-L47588", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getSignatureHelpItems", "original_string": "function getSignatureHelpItems(fileName, position) {\n synchronizeHostData();\n var sourceFile = getValidSourceFile(fileName);\n return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, cancellationToken);\n }", "language": "javascript", "code": "function getSignatureHelpItems(fileName, position) {\n synchronizeHostData();\n var sourceFile = getValidSourceFile(fileName);\n return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, cancellationToken);\n }", "code_tokens": ["function", "getSignatureHelpItems", "(", "fileName", ",", "position", ")", "{", "synchronizeHostData", "(", ")", ";", "var", "sourceFile", "=", "getValidSourceFile", "(", "fileName", ")", ";", "return", "ts", ".", "SignatureHelp", ".", "getSignatureHelpItems", "(", "program", ",", "sourceFile", ",", "position", ",", "cancellationToken", ")", ";", "}"], "docstring": "Signature help \nThis is a semantic operation.", "docstring_tokens": ["Signature", "help", "This", "is", "a", "semantic", "operation", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L47746-L47750", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "hasValueSideModule", "original_string": "function hasValueSideModule(symbol) {\n return ts.forEach(symbol.declarations, function (declaration) {\n return declaration.kind === 218 /* ModuleDeclaration */ &&\n ts.getModuleInstanceState(declaration) === 1 /* Instantiated */;\n });\n }", "language": "javascript", "code": "function hasValueSideModule(symbol) {\n return ts.forEach(symbol.declarations, function (declaration) {\n return declaration.kind === 218 /* ModuleDeclaration */ &&\n ts.getModuleInstanceState(declaration) === 1 /* Instantiated */;\n });\n }", "code_tokens": ["function", "hasValueSideModule", "(", "symbol", ")", "{", "return", "ts", ".", "forEach", "(", "symbol", ".", "declarations", ",", "function", "(", "declaration", ")", "{", "return", "declaration", ".", "kind", "===", "218", "&&", "ts", ".", "getModuleInstanceState", "(", "declaration", ")", "===", "1", ";", "}", ")", ";", "}"], "docstring": "Returns true if there exists a module that introduces entities on the value side.", "docstring_tokens": ["Returns", "true", "if", "there", "exists", "a", "module", "that", "introduces", "entities", "on", "the", "value", "side", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L47883-L47888", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "classifyTokenType", "original_string": "function classifyTokenType(tokenKind, token) {\n if (ts.isKeyword(tokenKind)) {\n return 3 /* keyword */;\n }\n // Special case < and > If they appear in a generic context they are punctuation,\n // not operators.\n if (tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */) {\n // If the node owning the token has a type argument list or type parameter list, then\n // we can effectively assume that a '<' and '>' belong to those lists.\n if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) {\n return 10 /* punctuation */;\n }\n }\n if (ts.isPunctuation(tokenKind)) {\n if (token) {\n if (tokenKind === 56 /* EqualsToken */) {\n // the '=' in a variable declaration is special cased here.\n if (token.parent.kind === 211 /* VariableDeclaration */ ||\n token.parent.kind === 141 /* PropertyDeclaration */ ||\n token.parent.kind === 138 /* Parameter */) {\n return 5 /* operator */;\n }\n }\n if (token.parent.kind === 181 /* BinaryExpression */ ||\n token.parent.kind === 179 /* PrefixUnaryExpression */ ||\n token.parent.kind === 180 /* PostfixUnaryExpression */ ||\n token.parent.kind === 182 /* ConditionalExpression */) {\n return 5 /* operator */;\n }\n }\n return 10 /* punctuation */;\n }\n else if (tokenKind === 8 /* NumericLiteral */) {\n return 4 /* numericLiteral */;\n }\n else if (tokenKind === 9 /* StringLiteral */) {\n return 6 /* stringLiteral */;\n }\n else if (tokenKind === 10 /* RegularExpressionLiteral */) {\n // TODO: we should get another classification type for these literals.\n return 6 /* stringLiteral */;\n }\n else if (ts.isTemplateLiteralKind(tokenKind)) {\n // TODO (drosen): we should *also* get another classification type for these literals.\n return 6 /* stringLiteral */;\n }\n else if (tokenKind === 69 /* Identifier */) {\n if (token) {\n switch (token.parent.kind) {\n case 214 /* ClassDeclaration */:\n if (token.parent.name === token) {\n return 11 /* className */;\n }\n return;\n case 137 /* TypeParameter */:\n if (token.parent.name === token) {\n return 15 /* typeParameterName */;\n }\n return;\n case 215 /* InterfaceDeclaration */:\n if (token.parent.name === token) {\n return 13 /* interfaceName */;\n }\n return;\n case 217 /* EnumDeclaration */:\n if (token.parent.name === token) {\n return 12 /* enumName */;\n }\n return;\n case 218 /* ModuleDeclaration */:\n if (token.parent.name === token) {\n return 14 /* moduleName */;\n }\n return;\n case 138 /* Parameter */:\n if (token.parent.name === token) {\n return 17 /* parameterName */;\n }\n return;\n }\n }\n return 2 /* identifier */;\n }\n }", "language": "javascript", "code": "function classifyTokenType(tokenKind, token) {\n if (ts.isKeyword(tokenKind)) {\n return 3 /* keyword */;\n }\n // Special case < and > If they appear in a generic context they are punctuation,\n // not operators.\n if (tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */) {\n // If the node owning the token has a type argument list or type parameter list, then\n // we can effectively assume that a '<' and '>' belong to those lists.\n if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) {\n return 10 /* punctuation */;\n }\n }\n if (ts.isPunctuation(tokenKind)) {\n if (token) {\n if (tokenKind === 56 /* EqualsToken */) {\n // the '=' in a variable declaration is special cased here.\n if (token.parent.kind === 211 /* VariableDeclaration */ ||\n token.parent.kind === 141 /* PropertyDeclaration */ ||\n token.parent.kind === 138 /* Parameter */) {\n return 5 /* operator */;\n }\n }\n if (token.parent.kind === 181 /* BinaryExpression */ ||\n token.parent.kind === 179 /* PrefixUnaryExpression */ ||\n token.parent.kind === 180 /* PostfixUnaryExpression */ ||\n token.parent.kind === 182 /* ConditionalExpression */) {\n return 5 /* operator */;\n }\n }\n return 10 /* punctuation */;\n }\n else if (tokenKind === 8 /* NumericLiteral */) {\n return 4 /* numericLiteral */;\n }\n else if (tokenKind === 9 /* StringLiteral */) {\n return 6 /* stringLiteral */;\n }\n else if (tokenKind === 10 /* RegularExpressionLiteral */) {\n // TODO: we should get another classification type for these literals.\n return 6 /* stringLiteral */;\n }\n else if (ts.isTemplateLiteralKind(tokenKind)) {\n // TODO (drosen): we should *also* get another classification type for these literals.\n return 6 /* stringLiteral */;\n }\n else if (tokenKind === 69 /* Identifier */) {\n if (token) {\n switch (token.parent.kind) {\n case 214 /* ClassDeclaration */:\n if (token.parent.name === token) {\n return 11 /* className */;\n }\n return;\n case 137 /* TypeParameter */:\n if (token.parent.name === token) {\n return 15 /* typeParameterName */;\n }\n return;\n case 215 /* InterfaceDeclaration */:\n if (token.parent.name === token) {\n return 13 /* interfaceName */;\n }\n return;\n case 217 /* EnumDeclaration */:\n if (token.parent.name === token) {\n return 12 /* enumName */;\n }\n return;\n case 218 /* ModuleDeclaration */:\n if (token.parent.name === token) {\n return 14 /* moduleName */;\n }\n return;\n case 138 /* Parameter */:\n if (token.parent.name === token) {\n return 17 /* parameterName */;\n }\n return;\n }\n }\n return 2 /* identifier */;\n }\n }", "code_tokens": ["function", "classifyTokenType", "(", "tokenKind", ",", "token", ")", "{", "if", "(", "ts", ".", "isKeyword", "(", "tokenKind", ")", ")", "{", "return", "3", ";", "}", "if", "(", "tokenKind", "===", "25", "||", "tokenKind", "===", "27", ")", "{", "if", "(", "token", "&&", "ts", ".", "getTypeArgumentOrTypeParameterList", "(", "token", ".", "parent", ")", ")", "{", "return", "10", ";", "}", "}", "if", "(", "ts", ".", "isPunctuation", "(", "tokenKind", ")", ")", "{", "if", "(", "token", ")", "{", "if", "(", "tokenKind", "===", "56", ")", "{", "if", "(", "token", ".", "parent", ".", "kind", "===", "211", "||", "token", ".", "parent", ".", "kind", "===", "141", "||", "token", ".", "parent", ".", "kind", "===", "138", ")", "{", "return", "5", ";", "}", "}", "if", "(", "token", ".", "parent", ".", "kind", "===", "181", "||", "token", ".", "parent", ".", "kind", "===", "179", "||", "token", ".", "parent", ".", "kind", "===", "180", "||", "token", ".", "parent", ".", "kind", "===", "182", ")", "{", "return", "5", ";", "}", "}", "return", "10", ";", "}", "else", "if", "(", "tokenKind", "===", "8", ")", "{", "return", "4", ";", "}", "else", "if", "(", "tokenKind", "===", "9", ")", "{", "return", "6", ";", "}", "else", "if", "(", "tokenKind", "===", "10", ")", "{", "return", "6", ";", "}", "else", "if", "(", "ts", ".", "isTemplateLiteralKind", "(", "tokenKind", ")", ")", "{", "return", "6", ";", "}", "else", "if", "(", "tokenKind", "===", "69", ")", "{", "if", "(", "token", ")", "{", "switch", "(", "token", ".", "parent", ".", "kind", ")", "{", "case", "214", ":", "if", "(", "token", ".", "parent", ".", "name", "===", "token", ")", "{", "return", "11", ";", "}", "return", ";", "case", "137", ":", "if", "(", "token", ".", "parent", ".", "name", "===", "token", ")", "{", "return", "15", ";", "}", "return", ";", "case", "215", ":", "if", "(", "token", ".", "parent", ".", "name", "===", "token", ")", "{", "return", "13", ";", "}", "return", ";", "case", "217", ":", "if", "(", "token", ".", "parent", ".", "name", "===", "token", ")", "{", "return", "12", ";", "}", "return", ";", "case", "218", ":", "if", "(", "token", ".", "parent", ".", "name", "===", "token", ")", "{", "return", "14", ";", "}", "return", ";", "case", "138", ":", "if", "(", "token", ".", "parent", ".", "name", "===", "token", ")", "{", "return", "17", ";", "}", "return", ";", "}", "}", "return", "2", ";", "}", "}"], "docstring": "for accurate classification, the actual token should be passed in. however, for cases like 'disabled merge code' classification, we just get the token kind and classify based on that instead.", "docstring_tokens": ["for", "accurate", "classification", "the", "actual", "token", "should", "be", "passed", "in", ".", "however", "for", "cases", "like", "disabled", "merge", "code", "classification", "we", "just", "get", "the", "token", "kind", "and", "classify", "based", "on", "that", "instead", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L48123-L48206", "partition": "test"} {"repo": "twinssbc/Ionic2-Calendar", "path": "demo/typescript.js", "func_name": "getParametersFromRightHandSideOfAssignment", "original_string": "function getParametersFromRightHandSideOfAssignment(rightHandSide) {\n while (rightHandSide.kind === 172 /* ParenthesizedExpression */) {\n rightHandSide = rightHandSide.expression;\n }\n switch (rightHandSide.kind) {\n case 173 /* FunctionExpression */:\n case 174 /* ArrowFunction */:\n return rightHandSide.parameters;\n case 186 /* ClassExpression */:\n for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) {\n var member = _a[_i];\n if (member.kind === 144 /* Constructor */) {\n return member.parameters;\n }\n }\n break;\n }\n return emptyArray;\n }", "language": "javascript", "code": "function getParametersFromRightHandSideOfAssignment(rightHandSide) {\n while (rightHandSide.kind === 172 /* ParenthesizedExpression */) {\n rightHandSide = rightHandSide.expression;\n }\n switch (rightHandSide.kind) {\n case 173 /* FunctionExpression */:\n case 174 /* ArrowFunction */:\n return rightHandSide.parameters;\n case 186 /* ClassExpression */:\n for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) {\n var member = _a[_i];\n if (member.kind === 144 /* Constructor */) {\n return member.parameters;\n }\n }\n break;\n }\n return emptyArray;\n }", "code_tokens": ["function", "getParametersFromRightHandSideOfAssignment", "(", "rightHandSide", ")", "{", "while", "(", "rightHandSide", ".", "kind", "===", "172", ")", "{", "rightHandSide", "=", "rightHandSide", ".", "expression", ";", "}", "switch", "(", "rightHandSide", ".", "kind", ")", "{", "case", "173", ":", "case", "174", ":", "return", "rightHandSide", ".", "parameters", ";", "case", "186", ":", "for", "(", "var", "_i", "=", "0", ",", "_a", "=", "rightHandSide", ".", "members", ";", "_i", "<", "_a", ".", "length", ";", "_i", "++", ")", "{", "var", "member", "=", "_a", "[", "_i", "]", ";", "if", "(", "member", ".", "kind", "===", "144", ")", "{", "return", "member", ".", "parameters", ";", "}", "}", "break", ";", "}", "return", "emptyArray", ";", "}"], "docstring": "Digs into an an initializer or RHS operand of an assignment operation\nto get the parameters of an apt signature corresponding to a\nfunction expression or a class expression.\n\n@param rightHandSide the expression which may contain an appropriate set of parameters\n@returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'.", "docstring_tokens": ["Digs", "into", "an", "an", "initializer", "or", "RHS", "operand", "of", "an", "assignment", "operation", "to", "get", "the", "parameters", "of", "an", "apt", "signature", "corresponding", "to", "a", "function", "expression", "or", "a", "class", "expression", "."], "sha": "29c5389189364d3ccb23989c57e111c7d4009f0d", "url": "https://github.com/twinssbc/Ionic2-Calendar/blob/29c5389189364d3ccb23989c57e111c7d4009f0d/demo/typescript.js#L48416-L48434", "partition": "test"} {"repo": "superfly/fly", "path": "examples/load-balancer/lib/balancer.js", "func_name": "score", "original_string": "function score(backend, errorBasis) {\n if (typeof errorBasis !== \"number\" && !errorBasis)\n errorBasis = Date.now();\n const timeSinceError = (errorBasis - backend.lastError);\n const statuses = backend.statuses;\n const timeWeight = (backend.lastError === 0 && 0) ||\n ((timeSinceError < 1000) && 1) ||\n ((timeSinceError < 3000) && 0.8) ||\n ((timeSinceError < 5000) && 0.3) ||\n ((timeSinceError < 10000) && 0.1) ||\n 0;\n if (statuses.length == 0)\n return 0;\n let requests = 0;\n let errors = 0;\n for (let i = 0; i < statuses.length; i++) {\n const status = statuses[i];\n if (status && !isNaN(status)) {\n requests += 1;\n if (status >= 500 && status < 600) {\n errors += 1;\n }\n }\n }\n const score = (1 - (timeWeight * (errors / requests)));\n backend.healthScore = score;\n backend.scoredRequestCount = backend.requestCount;\n return score;\n}", "language": "javascript", "code": "function score(backend, errorBasis) {\n if (typeof errorBasis !== \"number\" && !errorBasis)\n errorBasis = Date.now();\n const timeSinceError = (errorBasis - backend.lastError);\n const statuses = backend.statuses;\n const timeWeight = (backend.lastError === 0 && 0) ||\n ((timeSinceError < 1000) && 1) ||\n ((timeSinceError < 3000) && 0.8) ||\n ((timeSinceError < 5000) && 0.3) ||\n ((timeSinceError < 10000) && 0.1) ||\n 0;\n if (statuses.length == 0)\n return 0;\n let requests = 0;\n let errors = 0;\n for (let i = 0; i < statuses.length; i++) {\n const status = statuses[i];\n if (status && !isNaN(status)) {\n requests += 1;\n if (status >= 500 && status < 600) {\n errors += 1;\n }\n }\n }\n const score = (1 - (timeWeight * (errors / requests)));\n backend.healthScore = score;\n backend.scoredRequestCount = backend.requestCount;\n return score;\n}", "code_tokens": ["function", "score", "(", "backend", ",", "errorBasis", ")", "{", "if", "(", "typeof", "errorBasis", "!==", "\"number\"", "&&", "!", "errorBasis", ")", "errorBasis", "=", "Date", ".", "now", "(", ")", ";", "const", "timeSinceError", "=", "(", "errorBasis", "-", "backend", ".", "lastError", ")", ";", "const", "statuses", "=", "backend", ".", "statuses", ";", "const", "timeWeight", "=", "(", "backend", ".", "lastError", "===", "0", "&&", "0", ")", "||", "(", "(", "timeSinceError", "<", "1000", ")", "&&", "1", ")", "||", "(", "(", "timeSinceError", "<", "3000", ")", "&&", "0.8", ")", "||", "(", "(", "timeSinceError", "<", "5000", ")", "&&", "0.3", ")", "||", "(", "(", "timeSinceError", "<", "10000", ")", "&&", "0.1", ")", "||", "0", ";", "if", "(", "statuses", ".", "length", "==", "0", ")", "return", "0", ";", "let", "requests", "=", "0", ";", "let", "errors", "=", "0", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "statuses", ".", "length", ";", "i", "++", ")", "{", "const", "status", "=", "statuses", "[", "i", "]", ";", "if", "(", "status", "&&", "!", "isNaN", "(", "status", ")", ")", "{", "requests", "+=", "1", ";", "if", "(", "status", ">=", "500", "&&", "status", "<", "600", ")", "{", "errors", "+=", "1", ";", "}", "}", "}", "const", "score", "=", "(", "1", "-", "(", "timeWeight", "*", "(", "errors", "/", "requests", ")", ")", ")", ";", "backend", ".", "healthScore", "=", "score", ";", "backend", ".", "scoredRequestCount", "=", "backend", ".", "requestCount", ";", "return", "score", ";", "}"], "docstring": "compute a backend health score with time + status codes", "docstring_tokens": ["compute", "a", "backend", "health", "score", "with", "time", "+", "status", "codes"], "sha": "8189991b6b345169bde2b265e21029d857189364", "url": "https://github.com/superfly/fly/blob/8189991b6b345169bde2b265e21029d857189364/examples/load-balancer/lib/balancer.js#L89-L117", "partition": "test"} {"repo": "superfly/fly", "path": "examples/cache-for-errors/index.js", "func_name": "origin", "original_string": "async function origin(req, init) {\n const url = new URL(req.url)\n const status = parseInt(url.searchParams.get('status') || '200')\n\n if (status === 200) {\n return new Response(`hello from ${req.url} on ${new Date()}`)\n } else {\n return new Response(`an error! Number ${status}`, { status: status })\n }\n}", "language": "javascript", "code": "async function origin(req, init) {\n const url = new URL(req.url)\n const status = parseInt(url.searchParams.get('status') || '200')\n\n if (status === 200) {\n return new Response(`hello from ${req.url} on ${new Date()}`)\n } else {\n return new Response(`an error! Number ${status}`, { status: status })\n }\n}", "code_tokens": ["async", "function", "origin", "(", "req", ",", "init", ")", "{", "const", "url", "=", "new", "URL", "(", "req", ".", "url", ")", "const", "status", "=", "parseInt", "(", "url", ".", "searchParams", ".", "get", "(", "'status'", ")", "||", "'200'", ")", "if", "(", "status", "===", "200", ")", "{", "return", "new", "Response", "(", "`", "${", "req", ".", "url", "}", "${", "new", "Date", "(", ")", "}", "`", ")", "}", "else", "{", "return", "new", "Response", "(", "`", "${", "status", "}", "`", ",", "{", "status", ":", "status", "}", ")", "}", "}"], "docstring": "This is just a basic origin http server that\nlets us control status codes.\n\n`/` => successful response\n`/?status=404` => serves a 404\n`/?status=500` => serves a 500", "docstring_tokens": ["This", "is", "just", "a", "basic", "origin", "http", "server", "that", "lets", "us", "control", "status", "codes", "."], "sha": "8189991b6b345169bde2b265e21029d857189364", "url": "https://github.com/superfly/fly/blob/8189991b6b345169bde2b265e21029d857189364/examples/cache-for-errors/index.js#L38-L47", "partition": "test"} {"repo": "mcasimir/mobile-angular-ui", "path": "demo/demo.js", "func_name": "", "original_string": "function(element, transform, touch) {\n //\n // use translate both as basis for the new transform:\n //\n var t = $drag.TRANSLATE_BOTH(element, transform, touch);\n\n //\n // Add rotation:\n //\n var Dx = touch.distanceX;\n var t0 = touch.startTransform;\n var sign = Dx < 0 ? -1 : 1;\n var angle = sign * Math.min((Math.abs(Dx) / 700) * 30, 30);\n\n t.rotateZ = angle + (Math.round(t0.rotateZ));\n\n return t;\n }", "language": "javascript", "code": "function(element, transform, touch) {\n //\n // use translate both as basis for the new transform:\n //\n var t = $drag.TRANSLATE_BOTH(element, transform, touch);\n\n //\n // Add rotation:\n //\n var Dx = touch.distanceX;\n var t0 = touch.startTransform;\n var sign = Dx < 0 ? -1 : 1;\n var angle = sign * Math.min((Math.abs(Dx) / 700) * 30, 30);\n\n t.rotateZ = angle + (Math.round(t0.rotateZ));\n\n return t;\n }", "code_tokens": ["function", "(", "element", ",", "transform", ",", "touch", ")", "{", "var", "t", "=", "$drag", ".", "TRANSLATE_BOTH", "(", "element", ",", "transform", ",", "touch", ")", ";", "var", "Dx", "=", "touch", ".", "distanceX", ";", "var", "t0", "=", "touch", ".", "startTransform", ";", "var", "sign", "=", "Dx", "<", "0", "?", "-", "1", ":", "1", ";", "var", "angle", "=", "sign", "*", "Math", ".", "min", "(", "(", "Math", ".", "abs", "(", "Dx", ")", "/", "700", ")", "*", "30", ",", "30", ")", ";", "t", ".", "rotateZ", "=", "angle", "+", "(", "Math", ".", "round", "(", "t0", ".", "rotateZ", ")", ")", ";", "return", "t", ";", "}"], "docstring": "This is an example of custom transform function", "docstring_tokens": ["This", "is", "an", "example", "of", "custom", "transform", "function"], "sha": "5ec10ac8883e31beb91a940f133290a5146a126d", "url": "https://github.com/mcasimir/mobile-angular-ui/blob/5ec10ac8883e31beb91a940f133290a5146a126d/demo/demo.js#L189-L206", "partition": "test"} {"repo": "mcasimir/mobile-angular-ui", "path": "dist/js/mobile-angular-ui.gestures.js", "func_name": "", "original_string": "function(t) {\n var absAngle = abs(t.angle);\n absAngle = absAngle >= 90 ? absAngle - 90 : absAngle;\n\n var validDistance = t.total - t.distance <= TURNAROUND_MAX;\n var validAngle = absAngle <= ANGLE_THRESHOLD || absAngle >= 90 - ANGLE_THRESHOLD;\n var validVelocity = t.averageVelocity >= VELOCITY_THRESHOLD;\n\n return validDistance && validAngle && validVelocity;\n }", "language": "javascript", "code": "function(t) {\n var absAngle = abs(t.angle);\n absAngle = absAngle >= 90 ? absAngle - 90 : absAngle;\n\n var validDistance = t.total - t.distance <= TURNAROUND_MAX;\n var validAngle = absAngle <= ANGLE_THRESHOLD || absAngle >= 90 - ANGLE_THRESHOLD;\n var validVelocity = t.averageVelocity >= VELOCITY_THRESHOLD;\n\n return validDistance && validAngle && validVelocity;\n }", "code_tokens": ["function", "(", "t", ")", "{", "var", "absAngle", "=", "abs", "(", "t", ".", "angle", ")", ";", "absAngle", "=", "absAngle", ">=", "90", "?", "absAngle", "-", "90", ":", "absAngle", ";", "var", "validDistance", "=", "t", ".", "total", "-", "t", ".", "distance", "<=", "TURNAROUND_MAX", ";", "var", "validAngle", "=", "absAngle", "<=", "ANGLE_THRESHOLD", "||", "absAngle", ">=", "90", "-", "ANGLE_THRESHOLD", ";", "var", "validVelocity", "=", "t", ".", "averageVelocity", ">=", "VELOCITY_THRESHOLD", ";", "return", "validDistance", "&&", "validAngle", "&&", "validVelocity", ";", "}"], "docstring": "start to consider only if movement exceeded MOVEMENT_THRESHOLD", "docstring_tokens": ["start", "to", "consider", "only", "if", "movement", "exceeded", "MOVEMENT_THRESHOLD"], "sha": "5ec10ac8883e31beb91a940f133290a5146a126d", "url": "https://github.com/mcasimir/mobile-angular-ui/blob/5ec10ac8883e31beb91a940f133290a5146a126d/dist/js/mobile-angular-ui.gestures.js#L416-L425", "partition": "test"} {"repo": "mcasimir/mobile-angular-ui", "path": "dist/js/mobile-angular-ui.gestures.js", "func_name": "", "original_string": "function(element, eventHandlers, options) {\n options = angular.extend({}, defaultOptions, options || {});\n return $touch.bind(element, eventHandlers, options);\n }", "language": "javascript", "code": "function(element, eventHandlers, options) {\n options = angular.extend({}, defaultOptions, options || {});\n return $touch.bind(element, eventHandlers, options);\n }", "code_tokens": ["function", "(", "element", ",", "eventHandlers", ",", "options", ")", "{", "options", "=", "angular", ".", "extend", "(", "{", "}", ",", "defaultOptions", ",", "options", "||", "{", "}", ")", ";", "return", "$touch", ".", "bind", "(", "element", ",", "eventHandlers", ",", "options", ")", ";", "}"], "docstring": "Bind swipe gesture handlers for an element.\n\n``` js\nvar unbind = $swipe.bind(elem, {\nend: function(touch) {\nconsole.log('Swiped:', touch.direction);\nunbind();\n}\n});\n```\n\n**Swipes Detection**\n\nBefore consider a touch to be a swipe Mobile Angular UI verifies that:\n\n1. Movement is quick. Average touch velocity should exceed a `VELOCITY_THRESHOLD`.\n2. Movement is linear.\n3. Movement has a clear, non-ambiguous direction. So we can assume without error\nthat underlying `touch.direction` is exactly the swipe direction. For that\nmovement is checked against an `ANGLE_THRESHOLD`.\n\n@param {Element|$element} element The element to observe for swipe gestures.\n@param {object} eventHandlers An object with handlers for specific swipe events.\n@param {function} [eventHandlers.start] The callback for swipe start event.\n@param {function} [eventHandlers.end] The callback for swipe end event.\n@param {function} [eventHandlers.move] The callback for swipe move event.\n@param {function} [eventHandlers.cancel] The callback for swipe cancel event.\n@param {object} [options] Options to be passed to underlying [$touch.bind](../module:touch) function.\n\n@returns {function} The unbind function.\n\n@method bind\n@memberOf mobile-angular-ui.gestures.swipe~$swipe", "docstring_tokens": ["Bind", "swipe", "gesture", "handlers", "for", "an", "element", "."], "sha": "5ec10ac8883e31beb91a940f133290a5146a126d", "url": "https://github.com/mcasimir/mobile-angular-ui/blob/5ec10ac8883e31beb91a940f133290a5146a126d/dist/js/mobile-angular-ui.gestures.js#L464-L467", "partition": "test"} {"repo": "mcasimir/mobile-angular-ui", "path": "dist/js/mobile-angular-ui.gestures.js", "func_name": "", "original_string": "function(type, c, t0, tl) {\n // Compute values for new TouchInfo based on coordinates and previus touches.\n // - c is coords of new touch\n // - t0 is first touch: useful to compute duration and distance (how far pointer\n // got from first touch)\n // - tl is last touch: useful to compute velocity and length (total length of the movement)\n\n t0 = t0 || {};\n tl = tl || {};\n\n // timestamps\n var ts = now();\n var ts0 = t0.timestamp || ts;\n var tsl = tl.timestamp || ts0;\n\n // coords\n var x = c.x;\n var y = c.y;\n var x0 = t0.x || x;\n var y0 = t0.y || y;\n var xl = tl.x || x0;\n var yl = tl.y || y0;\n\n // total movement\n var totalXl = tl.totalX || 0;\n var totalYl = tl.totalY || 0;\n var totalX = totalXl + abs(x - xl);\n var totalY = totalYl + abs(y - yl);\n var total = len(totalX, totalY);\n\n // duration\n var duration = timediff(ts, ts0);\n var durationl = timediff(ts, tsl);\n\n // distance\n var dxl = x - xl;\n var dyl = y - yl;\n var dl = len(dxl, dyl);\n var dx = x - x0;\n var dy = y - y0;\n var d = len(dx, dy);\n\n // velocity (px per second)\n var v = durationl > 0 ? abs(dl / (durationl / 1000)) : 0;\n var tv = duration > 0 ? abs(total / (duration / 1000)) : 0;\n\n // main direction: 'LEFT', 'RIGHT', 'TOP', 'BOTTOM'\n var dir = abs(dx) > abs(dy) ?\n (dx < 0 ? 'LEFT' : 'RIGHT') :\n (dy < 0 ? 'TOP' : 'BOTTOM');\n\n // angle (angle between distance vector and x axis)\n // angle will be:\n // 0 for x > 0 and y = 0\n // 90 for y < 0 and x = 0\n // 180 for x < 0 and y = 0\n // -90 for y > 0 and x = 0\n //\n // -90\u00b0\n // |\n // |\n // |\n // 180\u00b0 --------|-------- 0\u00b0\n // |\n // |\n // |\n // 90\u00b0\n //\n var angle = dx !== 0 || dy !== 0 ? atan2(dy, dx) * (180 / Math.PI) : null;\n angle = angle === -180 ? 180 : angle;\n\n return {\n type: type,\n timestamp: ts,\n duration: duration,\n startX: x0,\n startY: y0,\n prevX: xl,\n prevY: yl,\n x: c.x,\n y: c.y,\n\n step: dl, // distance from prev\n stepX: dxl,\n stepY: dyl,\n\n velocity: v,\n averageVelocity: tv,\n\n distance: d, // distance from start\n distanceX: dx,\n distanceY: dy,\n\n total: total, // total length of momement,\n // considering turnaround\n totalX: totalX,\n totalY: totalY,\n direction: dir,\n angle: angle\n };\n }", "language": "javascript", "code": "function(type, c, t0, tl) {\n // Compute values for new TouchInfo based on coordinates and previus touches.\n // - c is coords of new touch\n // - t0 is first touch: useful to compute duration and distance (how far pointer\n // got from first touch)\n // - tl is last touch: useful to compute velocity and length (total length of the movement)\n\n t0 = t0 || {};\n tl = tl || {};\n\n // timestamps\n var ts = now();\n var ts0 = t0.timestamp || ts;\n var tsl = tl.timestamp || ts0;\n\n // coords\n var x = c.x;\n var y = c.y;\n var x0 = t0.x || x;\n var y0 = t0.y || y;\n var xl = tl.x || x0;\n var yl = tl.y || y0;\n\n // total movement\n var totalXl = tl.totalX || 0;\n var totalYl = tl.totalY || 0;\n var totalX = totalXl + abs(x - xl);\n var totalY = totalYl + abs(y - yl);\n var total = len(totalX, totalY);\n\n // duration\n var duration = timediff(ts, ts0);\n var durationl = timediff(ts, tsl);\n\n // distance\n var dxl = x - xl;\n var dyl = y - yl;\n var dl = len(dxl, dyl);\n var dx = x - x0;\n var dy = y - y0;\n var d = len(dx, dy);\n\n // velocity (px per second)\n var v = durationl > 0 ? abs(dl / (durationl / 1000)) : 0;\n var tv = duration > 0 ? abs(total / (duration / 1000)) : 0;\n\n // main direction: 'LEFT', 'RIGHT', 'TOP', 'BOTTOM'\n var dir = abs(dx) > abs(dy) ?\n (dx < 0 ? 'LEFT' : 'RIGHT') :\n (dy < 0 ? 'TOP' : 'BOTTOM');\n\n // angle (angle between distance vector and x axis)\n // angle will be:\n // 0 for x > 0 and y = 0\n // 90 for y < 0 and x = 0\n // 180 for x < 0 and y = 0\n // -90 for y > 0 and x = 0\n //\n // -90\u00b0\n // |\n // |\n // |\n // 180\u00b0 --------|-------- 0\u00b0\n // |\n // |\n // |\n // 90\u00b0\n //\n var angle = dx !== 0 || dy !== 0 ? atan2(dy, dx) * (180 / Math.PI) : null;\n angle = angle === -180 ? 180 : angle;\n\n return {\n type: type,\n timestamp: ts,\n duration: duration,\n startX: x0,\n startY: y0,\n prevX: xl,\n prevY: yl,\n x: c.x,\n y: c.y,\n\n step: dl, // distance from prev\n stepX: dxl,\n stepY: dyl,\n\n velocity: v,\n averageVelocity: tv,\n\n distance: d, // distance from start\n distanceX: dx,\n distanceY: dy,\n\n total: total, // total length of momement,\n // considering turnaround\n totalX: totalX,\n totalY: totalY,\n direction: dir,\n angle: angle\n };\n }", "code_tokens": ["function", "(", "type", ",", "c", ",", "t0", ",", "tl", ")", "{", "t0", "=", "t0", "||", "{", "}", ";", "tl", "=", "tl", "||", "{", "}", ";", "var", "ts", "=", "now", "(", ")", ";", "var", "ts0", "=", "t0", ".", "timestamp", "||", "ts", ";", "var", "tsl", "=", "tl", ".", "timestamp", "||", "ts0", ";", "var", "x", "=", "c", ".", "x", ";", "var", "y", "=", "c", ".", "y", ";", "var", "x0", "=", "t0", ".", "x", "||", "x", ";", "var", "y0", "=", "t0", ".", "y", "||", "y", ";", "var", "xl", "=", "tl", ".", "x", "||", "x0", ";", "var", "yl", "=", "tl", ".", "y", "||", "y0", ";", "var", "totalXl", "=", "tl", ".", "totalX", "||", "0", ";", "var", "totalYl", "=", "tl", ".", "totalY", "||", "0", ";", "var", "totalX", "=", "totalXl", "+", "abs", "(", "x", "-", "xl", ")", ";", "var", "totalY", "=", "totalYl", "+", "abs", "(", "y", "-", "yl", ")", ";", "var", "total", "=", "len", "(", "totalX", ",", "totalY", ")", ";", "var", "duration", "=", "timediff", "(", "ts", ",", "ts0", ")", ";", "var", "durationl", "=", "timediff", "(", "ts", ",", "tsl", ")", ";", "var", "dxl", "=", "x", "-", "xl", ";", "var", "dyl", "=", "y", "-", "yl", ";", "var", "dl", "=", "len", "(", "dxl", ",", "dyl", ")", ";", "var", "dx", "=", "x", "-", "x0", ";", "var", "dy", "=", "y", "-", "y0", ";", "var", "d", "=", "len", "(", "dx", ",", "dy", ")", ";", "var", "v", "=", "durationl", ">", "0", "?", "abs", "(", "dl", "/", "(", "durationl", "/", "1000", ")", ")", ":", "0", ";", "var", "tv", "=", "duration", ">", "0", "?", "abs", "(", "total", "/", "(", "duration", "/", "1000", ")", ")", ":", "0", ";", "var", "dir", "=", "abs", "(", "dx", ")", ">", "abs", "(", "dy", ")", "?", "(", "dx", "<", "0", "?", "'LEFT'", ":", "'RIGHT'", ")", ":", "(", "dy", "<", "0", "?", "'TOP'", ":", "'BOTTOM'", ")", ";", "var", "angle", "=", "dx", "!==", "0", "||", "dy", "!==", "0", "?", "atan2", "(", "dy", ",", "dx", ")", "*", "(", "180", "/", "Math", ".", "PI", ")", ":", "null", ";", "angle", "=", "angle", "===", "-", "180", "?", "180", ":", "angle", ";", "return", "{", "type", ":", "type", ",", "timestamp", ":", "ts", ",", "duration", ":", "duration", ",", "startX", ":", "x0", ",", "startY", ":", "y0", ",", "prevX", ":", "xl", ",", "prevY", ":", "yl", ",", "x", ":", "c", ".", "x", ",", "y", ":", "c", ".", "y", ",", "step", ":", "dl", ",", "stepX", ":", "dxl", ",", "stepY", ":", "dyl", ",", "velocity", ":", "v", ",", "averageVelocity", ":", "tv", ",", "distance", ":", "d", ",", "distanceX", ":", "dx", ",", "distanceY", ":", "dy", ",", "total", ":", "total", ",", "totalX", ":", "totalX", ",", "totalY", ":", "totalY", ",", "direction", ":", "dir", ",", "angle", ":", "angle", "}", ";", "}"], "docstring": "`TouchInfo` is an object containing the following extended informations about any touch\nevent.\n\n@property {string} type Normalized event type. Despite of pointer device is always one of `touchstart`, `touchend`, `touchmove`, `touchcancel`.\n@property {Date} timestamp The time object corresponding to the moment this touch event happened.\n@property {integer} duration The difference between this touch event and the corresponding `touchstart`.\n@property {float} startX X coord of related `touchstart`.\n@property {float} startY Y coord of related `touchstart`.\n@property {float} prevX X coord of previous `touchstart` or `touchmove`.\n@property {float} prevY Y coord of previous `touchstart` or `touchmove`.\n@property {float} x X coord of this touch event.\n@property {float} y Y coord of this touch event.\n@property {float} step Distance between `[prevX, prevY]` and `[x, y]` points.\n@property {float} stepX Distance between `prevX` and `x`.\n@property {float} stepY Distance between `prevY` and `y`.\n@property {float} velocity Instantaneous velocity of a touch event in pixels per second.\n@property {float} averageVelocity Average velocity of a touch event from its corresponding `touchstart` in pixels per second.\n@property {float} distance Distance between `[startX, startY]` and `[x, y]` points.\n@property {float} distanceX Distance between `startX` and `x`.\n@property {float} distanceY Distance between `startY` and `y`.\n@property {float} total Total number of pixels covered by movement, taking account of direction changes and turnarounds.\n@property {float} totalX Total number of pixels covered by horizontal movement, taking account of direction changes and turnarounds.\n@property {float} totalY Total number of pixels covered by vertical, taking account of direction changes and turnarounds.\n@property {string} direction The current prevalent direction for this touch, one of `LEFT`, `RIGHT`, `TOP`, `BOTTOM`.\n@property {float} angle Angle in degree between x axis and the vector `[x, y]`, is `null` when no movement happens.\n\n@class TouchInfo\n@ngdoc type\n@memberOf mobile-angular-ui.gestures.touch~$touch", "docstring_tokens": ["TouchInfo", "is", "an", "object", "containing", "the", "following", "extended", "informations", "about", "any", "touch", "event", "."], "sha": "5ec10ac8883e31beb91a940f133290a5146a126d", "url": "https://github.com/mcasimir/mobile-angular-ui/blob/5ec10ac8883e31beb91a940f133290a5146a126d/dist/js/mobile-angular-ui.gestures.js#L817-L917", "partition": "test"} {"repo": "mcasimir/mobile-angular-ui", "path": "dist/js/mobile-angular-ui.gestures.js", "func_name": "", "original_string": "function(event) {\n // don't handle multi-touch\n if (event.touches && event.touches.length > 1) {\n return;\n }\n tl = t0 = buildTouchInfo('touchstart', getCoordinates(event));\n $movementTarget.on(moveEvents, onTouchMove);\n $movementTarget.on(endEvents, onTouchEnd);\n if (cancelEvents) {\n $movementTarget.on(cancelEvents, onTouchCancel);\n }\n if (startEventHandler) {\n startEventHandler(t0, event);\n }\n }", "language": "javascript", "code": "function(event) {\n // don't handle multi-touch\n if (event.touches && event.touches.length > 1) {\n return;\n }\n tl = t0 = buildTouchInfo('touchstart', getCoordinates(event));\n $movementTarget.on(moveEvents, onTouchMove);\n $movementTarget.on(endEvents, onTouchEnd);\n if (cancelEvents) {\n $movementTarget.on(cancelEvents, onTouchCancel);\n }\n if (startEventHandler) {\n startEventHandler(t0, event);\n }\n }", "code_tokens": ["function", "(", "event", ")", "{", "if", "(", "event", ".", "touches", "&&", "event", ".", "touches", ".", "length", ">", "1", ")", "{", "return", ";", "}", "tl", "=", "t0", "=", "buildTouchInfo", "(", "'touchstart'", ",", "getCoordinates", "(", "event", ")", ")", ";", "$movementTarget", ".", "on", "(", "moveEvents", ",", "onTouchMove", ")", ";", "$movementTarget", ".", "on", "(", "endEvents", ",", "onTouchEnd", ")", ";", "if", "(", "cancelEvents", ")", "{", "$movementTarget", ".", "on", "(", "cancelEvents", ",", "onTouchCancel", ")", ";", "}", "if", "(", "startEventHandler", ")", "{", "startEventHandler", "(", "t0", ",", "event", ")", ";", "}", "}"], "docstring": "Callbacks on touchstart", "docstring_tokens": ["Callbacks", "on", "touchstart"], "sha": "5ec10ac8883e31beb91a940f133290a5146a126d", "url": "https://github.com/mcasimir/mobile-angular-ui/blob/5ec10ac8883e31beb91a940f133290a5146a126d/dist/js/mobile-angular-ui.gestures.js#L1009-L1023", "partition": "test"} {"repo": "mcasimir/mobile-angular-ui", "path": "dist/js/mobile-angular-ui.gestures.js", "func_name": "", "original_string": "function(e) {\n e = e.length ? e[0] : e;\n var tr = window\n .getComputedStyle(e, null)\n .getPropertyValue(transformProperty);\n return tr;\n }", "language": "javascript", "code": "function(e) {\n e = e.length ? e[0] : e;\n var tr = window\n .getComputedStyle(e, null)\n .getPropertyValue(transformProperty);\n return tr;\n }", "code_tokens": ["function", "(", "e", ")", "{", "e", "=", "e", ".", "length", "?", "e", "[", "0", "]", ":", "e", ";", "var", "tr", "=", "window", ".", "getComputedStyle", "(", "e", ",", "null", ")", ".", "getPropertyValue", "(", "transformProperty", ")", ";", "return", "tr", ";", "}"], "docstring": "return current element transform matrix in a cross-browser way", "docstring_tokens": ["return", "current", "element", "transform", "matrix", "in", "a", "cross", "-", "browser", "way"], "sha": "5ec10ac8883e31beb91a940f133290a5146a126d", "url": "https://github.com/mcasimir/mobile-angular-ui/blob/5ec10ac8883e31beb91a940f133290a5146a126d/dist/js/mobile-angular-ui.gestures.js#L1263-L1269", "partition": "test"} {"repo": "mcasimir/mobile-angular-ui", "path": "dist/js/mobile-angular-ui.gestures.js", "func_name": "", "original_string": "function(elem, value) {\n elem = elem.length ? elem[0] : elem;\n elem.style[styleProperty] = value;\n }", "language": "javascript", "code": "function(elem, value) {\n elem = elem.length ? elem[0] : elem;\n elem.style[styleProperty] = value;\n }", "code_tokens": ["function", "(", "elem", ",", "value", ")", "{", "elem", "=", "elem", ".", "length", "?", "elem", "[", "0", "]", ":", "elem", ";", "elem", ".", "style", "[", "styleProperty", "]", "=", "value", ";", "}"], "docstring": "set current element transform matrix in a cross-browser way", "docstring_tokens": ["set", "current", "element", "transform", "matrix", "in", "a", "cross", "-", "browser", "way"], "sha": "5ec10ac8883e31beb91a940f133290a5146a126d", "url": "https://github.com/mcasimir/mobile-angular-ui/blob/5ec10ac8883e31beb91a940f133290a5146a126d/dist/js/mobile-angular-ui.gestures.js#L1272-L1275", "partition": "test"} {"repo": "mcasimir/mobile-angular-ui", "path": "dist/js/mobile-angular-ui.gestures.js", "func_name": "", "original_string": "function(e, t) {\n var str = (typeof t === 'string') ? t : this.toCss(t);\n setElementTransformProperty(e, str);\n }", "language": "javascript", "code": "function(e, t) {\n var str = (typeof t === 'string') ? t : this.toCss(t);\n setElementTransformProperty(e, str);\n }", "code_tokens": ["function", "(", "e", ",", "t", ")", "{", "var", "str", "=", "(", "typeof", "t", "===", "'string'", ")", "?", "t", ":", "this", ".", "toCss", "(", "t", ")", ";", "setElementTransformProperty", "(", "e", ",", "str", ")", ";", "}"], "docstring": "Recompose a transform from decomposition `t` and apply it to element `e`", "docstring_tokens": ["Recompose", "a", "transform", "from", "decomposition", "t", "and", "apply", "it", "to", "element", "e"], "sha": "5ec10ac8883e31beb91a940f133290a5146a126d", "url": "https://github.com/mcasimir/mobile-angular-ui/blob/5ec10ac8883e31beb91a940f133290a5146a126d/dist/js/mobile-angular-ui.gestures.js#L1688-L1691", "partition": "test"} {"repo": "ElemeFE/cooking", "path": "packages/cooking/lib/cooking.js", "func_name": "", "original_string": "function (_path) {\n if (/^((pre|post)?loader)s?/ig.test(_path)) {\n return _path.replace(/^((pre|post)?loader)s?/ig, 'module.$1s')\n }\n\n if (/^(plugin)s?/g.test(_path)) {\n return _path.replace(/^(plugin)s?/g, '$1s')\n }\n\n return _path\n}", "language": "javascript", "code": "function (_path) {\n if (/^((pre|post)?loader)s?/ig.test(_path)) {\n return _path.replace(/^((pre|post)?loader)s?/ig, 'module.$1s')\n }\n\n if (/^(plugin)s?/g.test(_path)) {\n return _path.replace(/^(plugin)s?/g, '$1s')\n }\n\n return _path\n}", "code_tokens": ["function", "(", "_path", ")", "{", "if", "(", "/", "^((pre|post)?loader)s?", "/", "ig", ".", "test", "(", "_path", ")", ")", "{", "return", "_path", ".", "replace", "(", "/", "^((pre|post)?loader)s?", "/", "ig", ",", "'module.$1s'", ")", "}", "if", "(", "/", "^(plugin)s?", "/", "g", ".", "test", "(", "_path", ")", ")", "{", "return", "_path", ".", "replace", "(", "/", "^(plugin)s?", "/", "g", ",", "'$1s'", ")", "}", "return", "_path", "}"], "docstring": "loader.vue => module.loaders.vue", "docstring_tokens": ["loader", ".", "vue", "=", ">", "module", ".", "loaders", ".", "vue"], "sha": "bb9c2f6bf00894deebb26c0229385960f3645c89", "url": "https://github.com/ElemeFE/cooking/blob/bb9c2f6bf00894deebb26c0229385960f3645c89/packages/cooking/lib/cooking.js#L19-L29", "partition": "test"} {"repo": "directus/sdk-js", "path": "src/index.js", "func_name": "getPayload", "original_string": "function getPayload(token) {\n const payloadBase64 = token\n .split(\".\")[1]\n .replace(\"-\", \"+\")\n .replace(\"_\", \"/\");\n const payloadDecoded = base64.decode(payloadBase64);\n const payloadObject = JSON.parse(payloadDecoded);\n\n if (AV.isNumber(payloadObject.exp)) {\n payloadObject.exp = new Date(payloadObject.exp * 1000);\n }\n\n return payloadObject;\n}", "language": "javascript", "code": "function getPayload(token) {\n const payloadBase64 = token\n .split(\".\")[1]\n .replace(\"-\", \"+\")\n .replace(\"_\", \"/\");\n const payloadDecoded = base64.decode(payloadBase64);\n const payloadObject = JSON.parse(payloadDecoded);\n\n if (AV.isNumber(payloadObject.exp)) {\n payloadObject.exp = new Date(payloadObject.exp * 1000);\n }\n\n return payloadObject;\n}", "code_tokens": ["function", "getPayload", "(", "token", ")", "{", "const", "payloadBase64", "=", "token", ".", "split", "(", "\".\"", ")", "[", "1", "]", ".", "replace", "(", "\"-\"", ",", "\"+\"", ")", ".", "replace", "(", "\"_\"", ",", "\"/\"", ")", ";", "const", "payloadDecoded", "=", "base64", ".", "decode", "(", "payloadBase64", ")", ";", "const", "payloadObject", "=", "JSON", ".", "parse", "(", "payloadDecoded", ")", ";", "if", "(", "AV", ".", "isNumber", "(", "payloadObject", ".", "exp", ")", ")", "{", "payloadObject", ".", "exp", "=", "new", "Date", "(", "payloadObject", ".", "exp", "*", "1000", ")", ";", "}", "return", "payloadObject", ";", "}"], "docstring": "Retrieves the payload from a JWT\n@param {String} token The JWT to retrieve the payload from\n@return {Object} The JWT payload", "docstring_tokens": ["Retrieves", "the", "payload", "from", "a", "JWT"], "sha": "f1e76fe844820886b77450b216228f3af62ed7b5", "url": "https://github.com/directus/sdk-js/blob/f1e76fe844820886b77450b216228f3af62ed7b5/src/index.js#L11-L24", "partition": "test"} {"repo": "GitbookIO/theme-default", "path": "src/js/theme/navigation.js", "func_name": "setChapterActive", "original_string": "function setChapterActive($chapter, hash) {\n // No chapter and no hash means first chapter\n if (!$chapter && !hash) {\n $chapter = $chapters.first();\n }\n\n // If hash is provided, set as active chapter\n if (!!hash) {\n // Multiple chapters for this file\n if ($chapters.length > 1) {\n $chapter = $chapters.filter(function() {\n var titleId = getChapterHash($(this));\n return titleId == hash;\n }).first();\n }\n // Only one chapter, no need to search\n else {\n $chapter = $chapters.first();\n }\n }\n\n // Don't update current chapter\n if ($chapter.is($activeChapter)) {\n return;\n }\n\n // Update current active chapter\n $activeChapter = $chapter;\n\n // Add class to selected chapter\n $chapters.removeClass('active');\n $chapter.addClass('active');\n\n // Update history state if needed\n hash = getChapterHash($chapter);\n\n var oldUri = window.location.pathname + window.location.hash,\n uri = window.location.pathname + hash;\n\n if (uri != oldUri) {\n history.replaceState({ path: uri }, null, uri);\n }\n}", "language": "javascript", "code": "function setChapterActive($chapter, hash) {\n // No chapter and no hash means first chapter\n if (!$chapter && !hash) {\n $chapter = $chapters.first();\n }\n\n // If hash is provided, set as active chapter\n if (!!hash) {\n // Multiple chapters for this file\n if ($chapters.length > 1) {\n $chapter = $chapters.filter(function() {\n var titleId = getChapterHash($(this));\n return titleId == hash;\n }).first();\n }\n // Only one chapter, no need to search\n else {\n $chapter = $chapters.first();\n }\n }\n\n // Don't update current chapter\n if ($chapter.is($activeChapter)) {\n return;\n }\n\n // Update current active chapter\n $activeChapter = $chapter;\n\n // Add class to selected chapter\n $chapters.removeClass('active');\n $chapter.addClass('active');\n\n // Update history state if needed\n hash = getChapterHash($chapter);\n\n var oldUri = window.location.pathname + window.location.hash,\n uri = window.location.pathname + hash;\n\n if (uri != oldUri) {\n history.replaceState({ path: uri }, null, uri);\n }\n}", "code_tokens": ["function", "setChapterActive", "(", "$chapter", ",", "hash", ")", "{", "if", "(", "!", "$chapter", "&&", "!", "hash", ")", "{", "$chapter", "=", "$chapters", ".", "first", "(", ")", ";", "}", "if", "(", "!", "!", "hash", ")", "{", "if", "(", "$chapters", ".", "length", ">", "1", ")", "{", "$chapter", "=", "$chapters", ".", "filter", "(", "function", "(", ")", "{", "var", "titleId", "=", "getChapterHash", "(", "$", "(", "this", ")", ")", ";", "return", "titleId", "==", "hash", ";", "}", ")", ".", "first", "(", ")", ";", "}", "else", "{", "$chapter", "=", "$chapters", ".", "first", "(", ")", ";", "}", "}", "if", "(", "$chapter", ".", "is", "(", "$activeChapter", ")", ")", "{", "return", ";", "}", "$activeChapter", "=", "$chapter", ";", "$chapters", ".", "removeClass", "(", "'active'", ")", ";", "$chapter", ".", "addClass", "(", "'active'", ")", ";", "hash", "=", "getChapterHash", "(", "$chapter", ")", ";", "var", "oldUri", "=", "window", ".", "location", ".", "pathname", "+", "window", ".", "location", ".", "hash", ",", "uri", "=", "window", ".", "location", ".", "pathname", "+", "hash", ";", "if", "(", "uri", "!=", "oldUri", ")", "{", "history", ".", "replaceState", "(", "{", "path", ":", "uri", "}", ",", "null", ",", "uri", ")", ";", "}", "}"], "docstring": "Set a chapter as active in summary and update state", "docstring_tokens": ["Set", "a", "chapter", "as", "active", "in", "summary", "and", "update", "state"], "sha": "a8e920453dc8e4eb522840b61606486622848099", "url": "https://github.com/GitbookIO/theme-default/blob/a8e920453dc8e4eb522840b61606486622848099/src/js/theme/navigation.js#L123-L165", "partition": "test"} {"repo": "GitbookIO/theme-default", "path": "src/js/theme/navigation.js", "func_name": "getChapterHash", "original_string": "function getChapterHash($chapter) {\n var $link = $chapter.children('a'),\n hash = $link.attr('href').split('#')[1];\n\n if (hash) hash = '#'+hash;\n return (!!hash)? hash : '';\n}", "language": "javascript", "code": "function getChapterHash($chapter) {\n var $link = $chapter.children('a'),\n hash = $link.attr('href').split('#')[1];\n\n if (hash) hash = '#'+hash;\n return (!!hash)? hash : '';\n}", "code_tokens": ["function", "getChapterHash", "(", "$chapter", ")", "{", "var", "$link", "=", "$chapter", ".", "children", "(", "'a'", ")", ",", "hash", "=", "$link", ".", "attr", "(", "'href'", ")", ".", "split", "(", "'#'", ")", "[", "1", "]", ";", "if", "(", "hash", ")", "hash", "=", "'#'", "+", "hash", ";", "return", "(", "!", "!", "hash", ")", "?", "hash", ":", "''", ";", "}"], "docstring": "Return the hash of link for a chapter", "docstring_tokens": ["Return", "the", "hash", "of", "link", "for", "a", "chapter"], "sha": "a8e920453dc8e4eb522840b61606486622848099", "url": "https://github.com/GitbookIO/theme-default/blob/a8e920453dc8e4eb522840b61606486622848099/src/js/theme/navigation.js#L168-L174", "partition": "test"} {"repo": "GitbookIO/theme-default", "path": "src/js/theme/navigation.js", "func_name": "handleScrolling", "original_string": "function handleScrolling() {\n // Get current page scroll\n var $scroller = getScroller(),\n scrollTop = $scroller.scrollTop(),\n scrollHeight = $scroller.prop('scrollHeight'),\n clientHeight = $scroller.prop('clientHeight'),\n nbChapters = $chapters.length,\n $chapter = null;\n\n // Find each title position in reverse order\n $($chapters.get().reverse()).each(function(index) {\n var titleId = getChapterHash($(this)),\n titleTop;\n\n if (!!titleId && !$chapter) {\n titleTop = getElementTopPosition(titleId);\n\n // Set current chapter as active if scroller passed it\n if (scrollTop >= titleTop) {\n $chapter = $(this);\n }\n }\n // If no active chapter when reaching first chapter, set it as active\n if (index == (nbChapters - 1) && !$chapter) {\n $chapter = $(this);\n }\n });\n\n // ScrollTop is at 0, set first chapter anyway\n if (!$chapter && !scrollTop) {\n $chapter = $chapters.first();\n }\n\n // Set last chapter as active if scrolled to bottom of page\n if (!!scrollTop && (scrollHeight - scrollTop == clientHeight)) {\n $chapter = $chapters.last();\n }\n\n setChapterActive($chapter);\n}", "language": "javascript", "code": "function handleScrolling() {\n // Get current page scroll\n var $scroller = getScroller(),\n scrollTop = $scroller.scrollTop(),\n scrollHeight = $scroller.prop('scrollHeight'),\n clientHeight = $scroller.prop('clientHeight'),\n nbChapters = $chapters.length,\n $chapter = null;\n\n // Find each title position in reverse order\n $($chapters.get().reverse()).each(function(index) {\n var titleId = getChapterHash($(this)),\n titleTop;\n\n if (!!titleId && !$chapter) {\n titleTop = getElementTopPosition(titleId);\n\n // Set current chapter as active if scroller passed it\n if (scrollTop >= titleTop) {\n $chapter = $(this);\n }\n }\n // If no active chapter when reaching first chapter, set it as active\n if (index == (nbChapters - 1) && !$chapter) {\n $chapter = $(this);\n }\n });\n\n // ScrollTop is at 0, set first chapter anyway\n if (!$chapter && !scrollTop) {\n $chapter = $chapters.first();\n }\n\n // Set last chapter as active if scrolled to bottom of page\n if (!!scrollTop && (scrollHeight - scrollTop == clientHeight)) {\n $chapter = $chapters.last();\n }\n\n setChapterActive($chapter);\n}", "code_tokens": ["function", "handleScrolling", "(", ")", "{", "var", "$scroller", "=", "getScroller", "(", ")", ",", "scrollTop", "=", "$scroller", ".", "scrollTop", "(", ")", ",", "scrollHeight", "=", "$scroller", ".", "prop", "(", "'scrollHeight'", ")", ",", "clientHeight", "=", "$scroller", ".", "prop", "(", "'clientHeight'", ")", ",", "nbChapters", "=", "$chapters", ".", "length", ",", "$chapter", "=", "null", ";", "$", "(", "$chapters", ".", "get", "(", ")", ".", "reverse", "(", ")", ")", ".", "each", "(", "function", "(", "index", ")", "{", "var", "titleId", "=", "getChapterHash", "(", "$", "(", "this", ")", ")", ",", "titleTop", ";", "if", "(", "!", "!", "titleId", "&&", "!", "$chapter", ")", "{", "titleTop", "=", "getElementTopPosition", "(", "titleId", ")", ";", "if", "(", "scrollTop", ">=", "titleTop", ")", "{", "$chapter", "=", "$", "(", "this", ")", ";", "}", "}", "if", "(", "index", "==", "(", "nbChapters", "-", "1", ")", "&&", "!", "$chapter", ")", "{", "$chapter", "=", "$", "(", "this", ")", ";", "}", "}", ")", ";", "if", "(", "!", "$chapter", "&&", "!", "scrollTop", ")", "{", "$chapter", "=", "$chapters", ".", "first", "(", ")", ";", "}", "if", "(", "!", "!", "scrollTop", "&&", "(", "scrollHeight", "-", "scrollTop", "==", "clientHeight", ")", ")", "{", "$chapter", "=", "$chapters", ".", "last", "(", ")", ";", "}", "setChapterActive", "(", "$chapter", ")", ";", "}"], "docstring": "Handle user scrolling", "docstring_tokens": ["Handle", "user", "scrolling"], "sha": "a8e920453dc8e4eb522840b61606486622848099", "url": "https://github.com/GitbookIO/theme-default/blob/a8e920453dc8e4eb522840b61606486622848099/src/js/theme/navigation.js#L177-L216", "partition": "test"} {"repo": "GitbookIO/theme-default", "path": "src/js/theme/toolbar.js", "func_name": "insertAt", "original_string": "function insertAt(parent, selector, index, element) {\n var lastIndex = parent.children(selector).length;\n if (index < 0) {\n index = Math.max(0, lastIndex + 1 + index);\n }\n parent.append(element);\n\n if (index < lastIndex) {\n parent.children(selector).eq(index).before(parent.children(selector).last());\n }\n}", "language": "javascript", "code": "function insertAt(parent, selector, index, element) {\n var lastIndex = parent.children(selector).length;\n if (index < 0) {\n index = Math.max(0, lastIndex + 1 + index);\n }\n parent.append(element);\n\n if (index < lastIndex) {\n parent.children(selector).eq(index).before(parent.children(selector).last());\n }\n}", "code_tokens": ["function", "insertAt", "(", "parent", ",", "selector", ",", "index", ",", "element", ")", "{", "var", "lastIndex", "=", "parent", ".", "children", "(", "selector", ")", ".", "length", ";", "if", "(", "index", "<", "0", ")", "{", "index", "=", "Math", ".", "max", "(", "0", ",", "lastIndex", "+", "1", "+", "index", ")", ";", "}", "parent", ".", "append", "(", "element", ")", ";", "if", "(", "index", "<", "lastIndex", ")", "{", "parent", ".", "children", "(", "selector", ")", ".", "eq", "(", "index", ")", ".", "before", "(", "parent", ".", "children", "(", "selector", ")", ".", "last", "(", ")", ")", ";", "}", "}"], "docstring": "Insert a jquery element at a specific position", "docstring_tokens": ["Insert", "a", "jquery", "element", "at", "a", "specific", "position"], "sha": "a8e920453dc8e4eb522840b61606486622848099", "url": "https://github.com/GitbookIO/theme-default/blob/a8e920453dc8e4eb522840b61606486622848099/src/js/theme/toolbar.js#L15-L25", "partition": "test"} {"repo": "GitbookIO/theme-default", "path": "src/js/theme/toolbar.js", "func_name": "createDropdownMenu", "original_string": "function createDropdownMenu(dropdown) {\n var $menu = $('
    ', {\n 'class': 'dropdown-menu',\n 'html': '
    '\n });\n\n if (typeof dropdown == 'string') {\n $menu.append(dropdown);\n } else {\n var groups = dropdown.map(function(group) {\n if ($.isArray(group)) return group;\n else return [group];\n });\n\n // Create buttons groups\n groups.forEach(function(group) {\n var $group = $('
    ', {\n 'class': 'buttons'\n });\n var sizeClass = 'size-'+group.length;\n\n // Append buttons\n group.forEach(function(btn) {\n btn = $.extend({\n text: '',\n className: '',\n onClick: defaultOnClick\n }, btn || {});\n\n var $btn = $('