id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
17,300
|
af/envalid
|
src/envalidWithoutDotenv.js
|
validateVar
|
function validateVar({ spec = {}, name, rawValue }) {
if (typeof spec._parse !== 'function') {
throw new EnvError(`Invalid spec for "${name}"`)
}
const value = spec._parse(rawValue)
if (spec.choices) {
if (!Array.isArray(spec.choices)) {
throw new TypeError(`"choices" must be an array (in spec for "${name}")`)
} else if (!spec.choices.includes(value)) {
throw new EnvError(`Value "${value}" not in choices [${spec.choices}]`)
}
}
if (value == null) throw new EnvError(`Invalid value for env var "${name}"`)
return value
}
|
javascript
|
function validateVar({ spec = {}, name, rawValue }) {
if (typeof spec._parse !== 'function') {
throw new EnvError(`Invalid spec for "${name}"`)
}
const value = spec._parse(rawValue)
if (spec.choices) {
if (!Array.isArray(spec.choices)) {
throw new TypeError(`"choices" must be an array (in spec for "${name}")`)
} else if (!spec.choices.includes(value)) {
throw new EnvError(`Value "${value}" not in choices [${spec.choices}]`)
}
}
if (value == null) throw new EnvError(`Invalid value for env var "${name}"`)
return value
}
|
[
"function",
"validateVar",
"(",
"{",
"spec",
"=",
"{",
"}",
",",
"name",
",",
"rawValue",
"}",
")",
"{",
"if",
"(",
"typeof",
"spec",
".",
"_parse",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"EnvError",
"(",
"`",
"${",
"name",
"}",
"`",
")",
"}",
"const",
"value",
"=",
"spec",
".",
"_parse",
"(",
"rawValue",
")",
"if",
"(",
"spec",
".",
"choices",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"spec",
".",
"choices",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"`",
"${",
"name",
"}",
"`",
")",
"}",
"else",
"if",
"(",
"!",
"spec",
".",
"choices",
".",
"includes",
"(",
"value",
")",
")",
"{",
"throw",
"new",
"EnvError",
"(",
"`",
"${",
"value",
"}",
"${",
"spec",
".",
"choices",
"}",
"`",
")",
"}",
"}",
"if",
"(",
"value",
"==",
"null",
")",
"throw",
"new",
"EnvError",
"(",
"`",
"${",
"name",
"}",
"`",
")",
"return",
"value",
"}"
] |
Validate a single env var, given a spec object
@throws EnvError - If validation is unsuccessful
@return - The cleaned value
|
[
"Validate",
"a",
"single",
"env",
"var",
"given",
"a",
"spec",
"object"
] |
1e34b5f5ee06634ee526d58431373157a38324c7
|
https://github.com/af/envalid/blob/1e34b5f5ee06634ee526d58431373157a38324c7/src/envalidWithoutDotenv.js#L24-L39
|
17,301
|
af/envalid
|
src/envalidWithoutDotenv.js
|
formatSpecDescription
|
function formatSpecDescription(spec) {
const egText = spec.example ? ` (eg. "${spec.example}")` : ''
const docsText = spec.docs ? `. See ${spec.docs}` : ''
return `${spec.desc}${egText}${docsText}` || ''
}
|
javascript
|
function formatSpecDescription(spec) {
const egText = spec.example ? ` (eg. "${spec.example}")` : ''
const docsText = spec.docs ? `. See ${spec.docs}` : ''
return `${spec.desc}${egText}${docsText}` || ''
}
|
[
"function",
"formatSpecDescription",
"(",
"spec",
")",
"{",
"const",
"egText",
"=",
"spec",
".",
"example",
"?",
"`",
"${",
"spec",
".",
"example",
"}",
"`",
":",
"''",
"const",
"docsText",
"=",
"spec",
".",
"docs",
"?",
"`",
"${",
"spec",
".",
"docs",
"}",
"`",
":",
"''",
"return",
"`",
"${",
"spec",
".",
"desc",
"}",
"${",
"egText",
"}",
"${",
"docsText",
"}",
"`",
"||",
"''",
"}"
] |
Format a string error message for when a required env var is missing
|
[
"Format",
"a",
"string",
"error",
"message",
"for",
"when",
"a",
"required",
"env",
"var",
"is",
"missing"
] |
1e34b5f5ee06634ee526d58431373157a38324c7
|
https://github.com/af/envalid/blob/1e34b5f5ee06634ee526d58431373157a38324c7/src/envalidWithoutDotenv.js#L42-L46
|
17,302
|
af/envalid
|
src/envalid.js
|
extendWithDotEnv
|
function extendWithDotEnv(inputEnv, dotEnvPath = '.env') {
let dotEnvBuffer = null
try {
dotEnvBuffer = fs.readFileSync(dotEnvPath)
} catch (err) {
if (err.code === 'ENOENT') return inputEnv
throw err
}
const parsed = dotenv.parse(dotEnvBuffer)
return extend(parsed, inputEnv)
}
|
javascript
|
function extendWithDotEnv(inputEnv, dotEnvPath = '.env') {
let dotEnvBuffer = null
try {
dotEnvBuffer = fs.readFileSync(dotEnvPath)
} catch (err) {
if (err.code === 'ENOENT') return inputEnv
throw err
}
const parsed = dotenv.parse(dotEnvBuffer)
return extend(parsed, inputEnv)
}
|
[
"function",
"extendWithDotEnv",
"(",
"inputEnv",
",",
"dotEnvPath",
"=",
"'.env'",
")",
"{",
"let",
"dotEnvBuffer",
"=",
"null",
"try",
"{",
"dotEnvBuffer",
"=",
"fs",
".",
"readFileSync",
"(",
"dotEnvPath",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"'ENOENT'",
")",
"return",
"inputEnv",
"throw",
"err",
"}",
"const",
"parsed",
"=",
"dotenv",
".",
"parse",
"(",
"dotEnvBuffer",
")",
"return",
"extend",
"(",
"parsed",
",",
"inputEnv",
")",
"}"
] |
Extend an env var object with the values parsed from a ".env" file, whose path is given by the second argument.
|
[
"Extend",
"an",
"env",
"var",
"object",
"with",
"the",
"values",
"parsed",
"from",
"a",
".",
"env",
"file",
"whose",
"path",
"is",
"given",
"by",
"the",
"second",
"argument",
"."
] |
1e34b5f5ee06634ee526d58431373157a38324c7
|
https://github.com/af/envalid/blob/1e34b5f5ee06634ee526d58431373157a38324c7/src/envalid.js#L8-L18
|
17,303
|
prettier/plugin-php
|
src/util.js
|
useSingleQuote
|
function useSingleQuote(node, options) {
return (
!node.isDoubleQuote ||
(options.singleQuote &&
!node.raw.match(/\\n|\\t|\\r|\\t|\\v|\\e|\\f/) &&
!node.value.match(
/["'$\n]|\\[0-7]{1,3}|\\x[0-9A-Fa-f]{1,2}|\\u{[0-9A-Fa-f]+}/
))
);
}
|
javascript
|
function useSingleQuote(node, options) {
return (
!node.isDoubleQuote ||
(options.singleQuote &&
!node.raw.match(/\\n|\\t|\\r|\\t|\\v|\\e|\\f/) &&
!node.value.match(
/["'$\n]|\\[0-7]{1,3}|\\x[0-9A-Fa-f]{1,2}|\\u{[0-9A-Fa-f]+}/
))
);
}
|
[
"function",
"useSingleQuote",
"(",
"node",
",",
"options",
")",
"{",
"return",
"(",
"!",
"node",
".",
"isDoubleQuote",
"||",
"(",
"options",
".",
"singleQuote",
"&&",
"!",
"node",
".",
"raw",
".",
"match",
"(",
"/",
"\\\\n|\\\\t|\\\\r|\\\\t|\\\\v|\\\\e|\\\\f",
"/",
")",
"&&",
"!",
"node",
".",
"value",
".",
"match",
"(",
"/",
"[\"'$\\n]|\\\\[0-7]{1,3}|\\\\x[0-9A-Fa-f]{1,2}|\\\\u{[0-9A-Fa-f]+}",
"/",
")",
")",
")",
";",
"}"
] |
Check if string can safely be converted from double to single quotes, i.e.
- no embedded variables ("foo $bar")
- no linebreaks
- no special characters like \n, \t, ...
- no octal/hex/unicode characters
See http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
|
[
"Check",
"if",
"string",
"can",
"safely",
"be",
"converted",
"from",
"double",
"to",
"single",
"quotes",
"i",
".",
"e",
"."
] |
249651b8bf3f66d0c1cf63823b1a173a7f31e86a
|
https://github.com/prettier/plugin-php/blob/249651b8bf3f66d0c1cf63823b1a173a7f31e86a/src/util.js#L592-L601
|
17,304
|
aaronshaf/dynamodb-admin
|
lib/util.js
|
doSearch
|
function doSearch(docClient, tableName, scanParams, limit, startKey, progress,
readOperation = 'scan') {
limit = limit !== undefined ? limit : null
startKey = startKey !== undefined ? startKey : null
let params = {
TableName: tableName,
}
if (scanParams !== undefined && scanParams) {
params = Object.assign(params, scanParams)
}
if (limit !== null) {
params.Limit = limit
}
if (startKey !== null) {
params.ExclusiveStartKey = startKey
}
const readMethod = {
scan: (...args) => docClient.scan(...args).promise(),
query: (...args) => docClient.query(...args).promise(),
}[readOperation]
let items = []
const getNextBite = (params, nextKey = null) => {
if (nextKey) {
params.ExclusiveStartKey = nextKey
}
return readMethod(params)
.then(data => {
if (data && data.Items && data.Items.length > 0) {
items = items.concat(data.Items)
}
let lastStartKey = null
if (data) {
lastStartKey = data.LastEvaluatedKey
}
if (progress) {
const stop = progress(data.Items, lastStartKey)
if (stop) {
return items
}
}
if (!lastStartKey) {
return items
}
return getNextBite(params, lastStartKey)
})
}
return getNextBite(params)
}
|
javascript
|
function doSearch(docClient, tableName, scanParams, limit, startKey, progress,
readOperation = 'scan') {
limit = limit !== undefined ? limit : null
startKey = startKey !== undefined ? startKey : null
let params = {
TableName: tableName,
}
if (scanParams !== undefined && scanParams) {
params = Object.assign(params, scanParams)
}
if (limit !== null) {
params.Limit = limit
}
if (startKey !== null) {
params.ExclusiveStartKey = startKey
}
const readMethod = {
scan: (...args) => docClient.scan(...args).promise(),
query: (...args) => docClient.query(...args).promise(),
}[readOperation]
let items = []
const getNextBite = (params, nextKey = null) => {
if (nextKey) {
params.ExclusiveStartKey = nextKey
}
return readMethod(params)
.then(data => {
if (data && data.Items && data.Items.length > 0) {
items = items.concat(data.Items)
}
let lastStartKey = null
if (data) {
lastStartKey = data.LastEvaluatedKey
}
if (progress) {
const stop = progress(data.Items, lastStartKey)
if (stop) {
return items
}
}
if (!lastStartKey) {
return items
}
return getNextBite(params, lastStartKey)
})
}
return getNextBite(params)
}
|
[
"function",
"doSearch",
"(",
"docClient",
",",
"tableName",
",",
"scanParams",
",",
"limit",
",",
"startKey",
",",
"progress",
",",
"readOperation",
"=",
"'scan'",
")",
"{",
"limit",
"=",
"limit",
"!==",
"undefined",
"?",
"limit",
":",
"null",
"startKey",
"=",
"startKey",
"!==",
"undefined",
"?",
"startKey",
":",
"null",
"let",
"params",
"=",
"{",
"TableName",
":",
"tableName",
",",
"}",
"if",
"(",
"scanParams",
"!==",
"undefined",
"&&",
"scanParams",
")",
"{",
"params",
"=",
"Object",
".",
"assign",
"(",
"params",
",",
"scanParams",
")",
"}",
"if",
"(",
"limit",
"!==",
"null",
")",
"{",
"params",
".",
"Limit",
"=",
"limit",
"}",
"if",
"(",
"startKey",
"!==",
"null",
")",
"{",
"params",
".",
"ExclusiveStartKey",
"=",
"startKey",
"}",
"const",
"readMethod",
"=",
"{",
"scan",
":",
"(",
"...",
"args",
")",
"=>",
"docClient",
".",
"scan",
"(",
"...",
"args",
")",
".",
"promise",
"(",
")",
",",
"query",
":",
"(",
"...",
"args",
")",
"=>",
"docClient",
".",
"query",
"(",
"...",
"args",
")",
".",
"promise",
"(",
")",
",",
"}",
"[",
"readOperation",
"]",
"let",
"items",
"=",
"[",
"]",
"const",
"getNextBite",
"=",
"(",
"params",
",",
"nextKey",
"=",
"null",
")",
"=>",
"{",
"if",
"(",
"nextKey",
")",
"{",
"params",
".",
"ExclusiveStartKey",
"=",
"nextKey",
"}",
"return",
"readMethod",
"(",
"params",
")",
".",
"then",
"(",
"data",
"=>",
"{",
"if",
"(",
"data",
"&&",
"data",
".",
"Items",
"&&",
"data",
".",
"Items",
".",
"length",
">",
"0",
")",
"{",
"items",
"=",
"items",
".",
"concat",
"(",
"data",
".",
"Items",
")",
"}",
"let",
"lastStartKey",
"=",
"null",
"if",
"(",
"data",
")",
"{",
"lastStartKey",
"=",
"data",
".",
"LastEvaluatedKey",
"}",
"if",
"(",
"progress",
")",
"{",
"const",
"stop",
"=",
"progress",
"(",
"data",
".",
"Items",
",",
"lastStartKey",
")",
"if",
"(",
"stop",
")",
"{",
"return",
"items",
"}",
"}",
"if",
"(",
"!",
"lastStartKey",
")",
"{",
"return",
"items",
"}",
"return",
"getNextBite",
"(",
"params",
",",
"lastStartKey",
")",
"}",
")",
"}",
"return",
"getNextBite",
"(",
"params",
")",
"}"
] |
Invokes a database scan
@param {Object} docClient The AWS DynamoDB client
@param {String} tableName The table name
@param {Object} scanParams Extra params for the query
@param {Number} limit The of items to request per chunked query. NOT a limit
of items that should be returned.
@param {Object?} startKey The key to start query from
@param {Function} progress Function to execute on each new items returned
from query. Returns true to stop the query.
@param {string} readOperation The read operation
@return {Promise} Promise with items or rejected promise with error.
|
[
"Invokes",
"a",
"database",
"scan"
] |
c7726afa1a80f55e78502b6de7209f3639e7ff4a
|
https://github.com/aaronshaf/dynamodb-admin/blob/c7726afa1a80f55e78502b6de7209f3639e7ff4a/lib/util.js#L51-L111
|
17,305
|
aaronshaf/dynamodb-admin
|
lib/backend.js
|
loadDynamoConfig
|
function loadDynamoConfig(env, AWS) {
const dynamoConfig = {
endpoint: 'http://localhost:8000',
sslEnabled: false,
region: 'us-east-1',
accessKeyId: 'key',
secretAccessKey: env.AWS_SECRET_ACCESS_KEY || 'secret'
}
loadDynamoEndpoint(env, dynamoConfig)
if (AWS.config) {
if (AWS.config.region !== undefined) {
dynamoConfig.region = AWS.config.region
}
if (AWS.config.credentials) {
if (AWS.config.credentials.accessKeyId !== undefined) {
dynamoConfig.accessKeyId = AWS.config.credentials.accessKeyId
}
}
}
if (env.AWS_REGION) {
dynamoConfig.region = env.AWS_REGION
}
if (env.AWS_ACCESS_KEY_ID) {
dynamoConfig.accessKeyId = env.AWS_ACCESS_KEY_ID
}
return dynamoConfig
}
|
javascript
|
function loadDynamoConfig(env, AWS) {
const dynamoConfig = {
endpoint: 'http://localhost:8000',
sslEnabled: false,
region: 'us-east-1',
accessKeyId: 'key',
secretAccessKey: env.AWS_SECRET_ACCESS_KEY || 'secret'
}
loadDynamoEndpoint(env, dynamoConfig)
if (AWS.config) {
if (AWS.config.region !== undefined) {
dynamoConfig.region = AWS.config.region
}
if (AWS.config.credentials) {
if (AWS.config.credentials.accessKeyId !== undefined) {
dynamoConfig.accessKeyId = AWS.config.credentials.accessKeyId
}
}
}
if (env.AWS_REGION) {
dynamoConfig.region = env.AWS_REGION
}
if (env.AWS_ACCESS_KEY_ID) {
dynamoConfig.accessKeyId = env.AWS_ACCESS_KEY_ID
}
return dynamoConfig
}
|
[
"function",
"loadDynamoConfig",
"(",
"env",
",",
"AWS",
")",
"{",
"const",
"dynamoConfig",
"=",
"{",
"endpoint",
":",
"'http://localhost:8000'",
",",
"sslEnabled",
":",
"false",
",",
"region",
":",
"'us-east-1'",
",",
"accessKeyId",
":",
"'key'",
",",
"secretAccessKey",
":",
"env",
".",
"AWS_SECRET_ACCESS_KEY",
"||",
"'secret'",
"}",
"loadDynamoEndpoint",
"(",
"env",
",",
"dynamoConfig",
")",
"if",
"(",
"AWS",
".",
"config",
")",
"{",
"if",
"(",
"AWS",
".",
"config",
".",
"region",
"!==",
"undefined",
")",
"{",
"dynamoConfig",
".",
"region",
"=",
"AWS",
".",
"config",
".",
"region",
"}",
"if",
"(",
"AWS",
".",
"config",
".",
"credentials",
")",
"{",
"if",
"(",
"AWS",
".",
"config",
".",
"credentials",
".",
"accessKeyId",
"!==",
"undefined",
")",
"{",
"dynamoConfig",
".",
"accessKeyId",
"=",
"AWS",
".",
"config",
".",
"credentials",
".",
"accessKeyId",
"}",
"}",
"}",
"if",
"(",
"env",
".",
"AWS_REGION",
")",
"{",
"dynamoConfig",
".",
"region",
"=",
"env",
".",
"AWS_REGION",
"}",
"if",
"(",
"env",
".",
"AWS_ACCESS_KEY_ID",
")",
"{",
"dynamoConfig",
".",
"accessKeyId",
"=",
"env",
".",
"AWS_ACCESS_KEY_ID",
"}",
"return",
"dynamoConfig",
"}"
] |
Create the configuration for the local dynamodb instance.
Region and AccessKeyId are determined as follows:
1) Look at local aws configuration in ~/.aws/credentials
2) Look at env variables env.AWS_REGION and env.AWS_ACCESS_KEY_ID
3) Use default values 'us-east-1' and 'key'
@param env - the process environment
@param AWS - the AWS SDK object
@returns {{endpoint: string, sslEnabled: boolean, region: string, accessKeyId: string}}
|
[
"Create",
"the",
"configuration",
"for",
"the",
"local",
"dynamodb",
"instance",
"."
] |
c7726afa1a80f55e78502b6de7209f3639e7ff4a
|
https://github.com/aaronshaf/dynamodb-admin/blob/c7726afa1a80f55e78502b6de7209f3639e7ff4a/lib/backend.js#L47-L79
|
17,306
|
Jam3/layout-bmfont-text
|
demo/index.js
|
metrics
|
function metrics(context) {
//x-height
context.fillStyle = 'blue'
context.fillRect(0, -layout.height + layout.baseline, 15, -layout.xHeight)
//ascender
context.fillStyle = 'pink'
context.fillRect(27, -layout.height, 36, layout.ascender)
//cap height
context.fillStyle = 'yellow'
context.fillRect(110, -layout.height + layout.baseline , 18, -layout.capHeight)
//baseline
context.fillStyle = 'orange'
context.fillRect(140, -layout.height, 36, layout.baseline)
//descender
context.fillStyle = 'green'
context.fillRect(0, 0, 30, layout.descender)
//line height
context.fillStyle = 'red'
context.fillRect(0, -layout.height + layout.baseline, 52, layout.lineHeight)
//bounds
context.strokeRect(0, 0, layout.width, -layout.height)
}
|
javascript
|
function metrics(context) {
//x-height
context.fillStyle = 'blue'
context.fillRect(0, -layout.height + layout.baseline, 15, -layout.xHeight)
//ascender
context.fillStyle = 'pink'
context.fillRect(27, -layout.height, 36, layout.ascender)
//cap height
context.fillStyle = 'yellow'
context.fillRect(110, -layout.height + layout.baseline , 18, -layout.capHeight)
//baseline
context.fillStyle = 'orange'
context.fillRect(140, -layout.height, 36, layout.baseline)
//descender
context.fillStyle = 'green'
context.fillRect(0, 0, 30, layout.descender)
//line height
context.fillStyle = 'red'
context.fillRect(0, -layout.height + layout.baseline, 52, layout.lineHeight)
//bounds
context.strokeRect(0, 0, layout.width, -layout.height)
}
|
[
"function",
"metrics",
"(",
"context",
")",
"{",
"//x-height",
"context",
".",
"fillStyle",
"=",
"'blue'",
"context",
".",
"fillRect",
"(",
"0",
",",
"-",
"layout",
".",
"height",
"+",
"layout",
".",
"baseline",
",",
"15",
",",
"-",
"layout",
".",
"xHeight",
")",
"//ascender",
"context",
".",
"fillStyle",
"=",
"'pink'",
"context",
".",
"fillRect",
"(",
"27",
",",
"-",
"layout",
".",
"height",
",",
"36",
",",
"layout",
".",
"ascender",
")",
"//cap height",
"context",
".",
"fillStyle",
"=",
"'yellow'",
"context",
".",
"fillRect",
"(",
"110",
",",
"-",
"layout",
".",
"height",
"+",
"layout",
".",
"baseline",
",",
"18",
",",
"-",
"layout",
".",
"capHeight",
")",
"//baseline",
"context",
".",
"fillStyle",
"=",
"'orange'",
"context",
".",
"fillRect",
"(",
"140",
",",
"-",
"layout",
".",
"height",
",",
"36",
",",
"layout",
".",
"baseline",
")",
"//descender",
"context",
".",
"fillStyle",
"=",
"'green'",
"context",
".",
"fillRect",
"(",
"0",
",",
"0",
",",
"30",
",",
"layout",
".",
"descender",
")",
"//line height",
"context",
".",
"fillStyle",
"=",
"'red'",
"context",
".",
"fillRect",
"(",
"0",
",",
"-",
"layout",
".",
"height",
"+",
"layout",
".",
"baseline",
",",
"52",
",",
"layout",
".",
"lineHeight",
")",
"//bounds",
"context",
".",
"strokeRect",
"(",
"0",
",",
"0",
",",
"layout",
".",
"width",
",",
"-",
"layout",
".",
"height",
")",
"}"
] |
draw our metrics squares
|
[
"draw",
"our",
"metrics",
"squares"
] |
5efcf3d8179e5ed95c268f76a87975979f845db6
|
https://github.com/Jam3/layout-bmfont-text/blob/5efcf3d8179e5ed95c268f76a87975979f845db6/demo/index.js#L66-L93
|
17,307
|
JetBrains/ring-ui
|
packages/docs/webpack-docs-plugin.setup.js
|
createNav
|
function createNav(sources) {
const defaultCategory = 'Uncategorized';
const sourcesByCategories = sources.
// get category names
reduce((categories, source) => categories.
concat(source.attrs.category || defaultCategory), []).
// remove duplicates
filter((value, i, self) => self.indexOf(value) === i).
// create category object and fill it with related sources
reduce((categories, categoryName) => {
categories.push({
name: categoryName,
items: createCategoryItemsFromSources(sources, categoryName)
});
return categories;
}, []);
sourcesByCategories.sort(categoriesSorter);
sourcesByCategories.
forEach(category => category.items.sort(categoryItemsSorter));
return sourcesByCategories;
}
|
javascript
|
function createNav(sources) {
const defaultCategory = 'Uncategorized';
const sourcesByCategories = sources.
// get category names
reduce((categories, source) => categories.
concat(source.attrs.category || defaultCategory), []).
// remove duplicates
filter((value, i, self) => self.indexOf(value) === i).
// create category object and fill it with related sources
reduce((categories, categoryName) => {
categories.push({
name: categoryName,
items: createCategoryItemsFromSources(sources, categoryName)
});
return categories;
}, []);
sourcesByCategories.sort(categoriesSorter);
sourcesByCategories.
forEach(category => category.items.sort(categoryItemsSorter));
return sourcesByCategories;
}
|
[
"function",
"createNav",
"(",
"sources",
")",
"{",
"const",
"defaultCategory",
"=",
"'Uncategorized'",
";",
"const",
"sourcesByCategories",
"=",
"sources",
".",
"// get category names",
"reduce",
"(",
"(",
"categories",
",",
"source",
")",
"=>",
"categories",
".",
"concat",
"(",
"source",
".",
"attrs",
".",
"category",
"||",
"defaultCategory",
")",
",",
"[",
"]",
")",
".",
"// remove duplicates",
"filter",
"(",
"(",
"value",
",",
"i",
",",
"self",
")",
"=>",
"self",
".",
"indexOf",
"(",
"value",
")",
"===",
"i",
")",
".",
"// create category object and fill it with related sources",
"reduce",
"(",
"(",
"categories",
",",
"categoryName",
")",
"=>",
"{",
"categories",
".",
"push",
"(",
"{",
"name",
":",
"categoryName",
",",
"items",
":",
"createCategoryItemsFromSources",
"(",
"sources",
",",
"categoryName",
")",
"}",
")",
";",
"return",
"categories",
";",
"}",
",",
"[",
"]",
")",
";",
"sourcesByCategories",
".",
"sort",
"(",
"categoriesSorter",
")",
";",
"sourcesByCategories",
".",
"forEach",
"(",
"category",
"=>",
"category",
".",
"items",
".",
"sort",
"(",
"categoryItemsSorter",
")",
")",
";",
"return",
"sourcesByCategories",
";",
"}"
] |
Creates navigation object.
@param {Array<Source>} sources
@returns {Array<Object>}
|
[
"Creates",
"navigation",
"object",
"."
] |
fa7c39f47a91bb4b75d642834cad5409715a8402
|
https://github.com/JetBrains/ring-ui/blob/fa7c39f47a91bb4b75d642834cad5409715a8402/packages/docs/webpack-docs-plugin.setup.js#L123-L148
|
17,308
|
JetBrains/ring-ui
|
components/dialog-ng/dialog-ng.js
|
focusFirst
|
function focusFirst() {
const controls = node.queryAll('input,select,button,textarea,*[contentEditable=true]').
filter(inputNode => getStyles(inputNode).display !== 'none');
if (controls.length) {
controls[0].focus();
}
}
|
javascript
|
function focusFirst() {
const controls = node.queryAll('input,select,button,textarea,*[contentEditable=true]').
filter(inputNode => getStyles(inputNode).display !== 'none');
if (controls.length) {
controls[0].focus();
}
}
|
[
"function",
"focusFirst",
"(",
")",
"{",
"const",
"controls",
"=",
"node",
".",
"queryAll",
"(",
"'input,select,button,textarea,*[contentEditable=true]'",
")",
".",
"filter",
"(",
"inputNode",
"=>",
"getStyles",
"(",
"inputNode",
")",
".",
"display",
"!==",
"'none'",
")",
";",
"if",
"(",
"controls",
".",
"length",
")",
"{",
"controls",
"[",
"0",
"]",
".",
"focus",
"(",
")",
";",
"}",
"}"
] |
Focus first input
|
[
"Focus",
"first",
"input"
] |
fa7c39f47a91bb4b75d642834cad5409715a8402
|
https://github.com/JetBrains/ring-ui/blob/fa7c39f47a91bb4b75d642834cad5409715a8402/components/dialog-ng/dialog-ng.js#L405-L411
|
17,309
|
JetBrains/ring-ui
|
components/docked-panel-ng/docked-panel-ng.js
|
dock
|
function dock() {
onBeforeDock();
panel.classList.add(DOCKED_CSS_CLASS_NAME);
if (dockedPanelClass) {
panel.classList.add(dockedPanelClass);
}
isDocked = true;
}
|
javascript
|
function dock() {
onBeforeDock();
panel.classList.add(DOCKED_CSS_CLASS_NAME);
if (dockedPanelClass) {
panel.classList.add(dockedPanelClass);
}
isDocked = true;
}
|
[
"function",
"dock",
"(",
")",
"{",
"onBeforeDock",
"(",
")",
";",
"panel",
".",
"classList",
".",
"add",
"(",
"DOCKED_CSS_CLASS_NAME",
")",
";",
"if",
"(",
"dockedPanelClass",
")",
"{",
"panel",
".",
"classList",
".",
"add",
"(",
"dockedPanelClass",
")",
";",
"}",
"isDocked",
"=",
"true",
";",
"}"
] |
Docks the panel to the bottom of the page
|
[
"Docks",
"the",
"panel",
"to",
"the",
"bottom",
"of",
"the",
"page"
] |
fa7c39f47a91bb4b75d642834cad5409715a8402
|
https://github.com/JetBrains/ring-ui/blob/fa7c39f47a91bb4b75d642834cad5409715a8402/components/docked-panel-ng/docked-panel-ng.js#L119-L127
|
17,310
|
JetBrains/ring-ui
|
components/docked-panel-ng/docked-panel-ng.js
|
checkPanelPosition
|
function checkPanelPosition() {
const currentPanelRect = panel.getBoundingClientRect();
if (currentPanelRect.top + currentPanelRect.height > getScrollContainerHeight() &&
!isDocked) {
dock();
} else if (
isDocked &&
currentPanelRect.top + currentPanelRect.height +
getScrollContainerScrollTop() >= getInitialUndockedPosition() + TOGGLE_GAP
) {
undock();
}
}
|
javascript
|
function checkPanelPosition() {
const currentPanelRect = panel.getBoundingClientRect();
if (currentPanelRect.top + currentPanelRect.height > getScrollContainerHeight() &&
!isDocked) {
dock();
} else if (
isDocked &&
currentPanelRect.top + currentPanelRect.height +
getScrollContainerScrollTop() >= getInitialUndockedPosition() + TOGGLE_GAP
) {
undock();
}
}
|
[
"function",
"checkPanelPosition",
"(",
")",
"{",
"const",
"currentPanelRect",
"=",
"panel",
".",
"getBoundingClientRect",
"(",
")",
";",
"if",
"(",
"currentPanelRect",
".",
"top",
"+",
"currentPanelRect",
".",
"height",
">",
"getScrollContainerHeight",
"(",
")",
"&&",
"!",
"isDocked",
")",
"{",
"dock",
"(",
")",
";",
"}",
"else",
"if",
"(",
"isDocked",
"&&",
"currentPanelRect",
".",
"top",
"+",
"currentPanelRect",
".",
"height",
"+",
"getScrollContainerScrollTop",
"(",
")",
">=",
"getInitialUndockedPosition",
"(",
")",
"+",
"TOGGLE_GAP",
")",
"{",
"undock",
"(",
")",
";",
"}",
"}"
] |
Check panel position
|
[
"Check",
"panel",
"position"
] |
fa7c39f47a91bb4b75d642834cad5409715a8402
|
https://github.com/JetBrains/ring-ui/blob/fa7c39f47a91bb4b75d642834cad5409715a8402/components/docked-panel-ng/docked-panel-ng.js#L150-L163
|
17,311
|
JetBrains/ring-ui
|
components/old-browsers-message/old-browsers-message.js
|
startOldBrowsersDetector
|
function startOldBrowsersDetector(onOldBrowserDetected) {
previousWindowErrorHandler = window.onerror;
window.onerror = function oldBrowsersMessageShower(errorMsg, url, lineNumber) {
if (onOldBrowserDetected) {
onOldBrowserDetected();
}
if (previousWindowErrorHandler) {
return previousWindowErrorHandler(errorMsg, url, lineNumber);
}
return false;
};
}
|
javascript
|
function startOldBrowsersDetector(onOldBrowserDetected) {
previousWindowErrorHandler = window.onerror;
window.onerror = function oldBrowsersMessageShower(errorMsg, url, lineNumber) {
if (onOldBrowserDetected) {
onOldBrowserDetected();
}
if (previousWindowErrorHandler) {
return previousWindowErrorHandler(errorMsg, url, lineNumber);
}
return false;
};
}
|
[
"function",
"startOldBrowsersDetector",
"(",
"onOldBrowserDetected",
")",
"{",
"previousWindowErrorHandler",
"=",
"window",
".",
"onerror",
";",
"window",
".",
"onerror",
"=",
"function",
"oldBrowsersMessageShower",
"(",
"errorMsg",
",",
"url",
",",
"lineNumber",
")",
"{",
"if",
"(",
"onOldBrowserDetected",
")",
"{",
"onOldBrowserDetected",
"(",
")",
";",
"}",
"if",
"(",
"previousWindowErrorHandler",
")",
"{",
"return",
"previousWindowErrorHandler",
"(",
"errorMsg",
",",
"url",
",",
"lineNumber",
")",
";",
"}",
"return",
"false",
";",
"}",
";",
"}"
] |
Listens to unhandled errors and displays passed node
|
[
"Listens",
"to",
"unhandled",
"errors",
"and",
"displays",
"passed",
"node"
] |
fa7c39f47a91bb4b75d642834cad5409715a8402
|
https://github.com/JetBrains/ring-ui/blob/fa7c39f47a91bb4b75d642834cad5409715a8402/components/old-browsers-message/old-browsers-message.js#L98-L112
|
17,312
|
JetBrains/ring-ui
|
components/autofocus-ng/autofocus-ng.js
|
focusOnElement
|
function focusOnElement(element) {
if (!element) {
return;
}
if (element.hasAttribute(RING_SELECT) || element.tagName.toLowerCase() === RING_SELECT) {
focusOnElement(element.querySelector(RING_SELECT_SELECTOR));
return;
}
if (element.matches(FOCUSABLE_ELEMENTS) && element.focus) {
element.focus();
return;
}
const focusableChild = element.querySelector(FOCUSABLE_ELEMENTS);
if (focusableChild && focusableChild.focus) {
focusableChild.focus();
}
}
|
javascript
|
function focusOnElement(element) {
if (!element) {
return;
}
if (element.hasAttribute(RING_SELECT) || element.tagName.toLowerCase() === RING_SELECT) {
focusOnElement(element.querySelector(RING_SELECT_SELECTOR));
return;
}
if (element.matches(FOCUSABLE_ELEMENTS) && element.focus) {
element.focus();
return;
}
const focusableChild = element.querySelector(FOCUSABLE_ELEMENTS);
if (focusableChild && focusableChild.focus) {
focusableChild.focus();
}
}
|
[
"function",
"focusOnElement",
"(",
"element",
")",
"{",
"if",
"(",
"!",
"element",
")",
"{",
"return",
";",
"}",
"if",
"(",
"element",
".",
"hasAttribute",
"(",
"RING_SELECT",
")",
"||",
"element",
".",
"tagName",
".",
"toLowerCase",
"(",
")",
"===",
"RING_SELECT",
")",
"{",
"focusOnElement",
"(",
"element",
".",
"querySelector",
"(",
"RING_SELECT_SELECTOR",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"element",
".",
"matches",
"(",
"FOCUSABLE_ELEMENTS",
")",
"&&",
"element",
".",
"focus",
")",
"{",
"element",
".",
"focus",
"(",
")",
";",
"return",
";",
"}",
"const",
"focusableChild",
"=",
"element",
".",
"querySelector",
"(",
"FOCUSABLE_ELEMENTS",
")",
";",
"if",
"(",
"focusableChild",
"&&",
"focusableChild",
".",
"focus",
")",
"{",
"focusableChild",
".",
"focus",
"(",
")",
";",
"}",
"}"
] |
Focuses on element itself if it has "focus" method.
Searches and focuses on select's button or input if element is rg-select
@param element
|
[
"Focuses",
"on",
"element",
"itself",
"if",
"it",
"has",
"focus",
"method",
".",
"Searches",
"and",
"focuses",
"on",
"select",
"s",
"button",
"or",
"input",
"if",
"element",
"is",
"rg",
"-",
"select"
] |
fa7c39f47a91bb4b75d642834cad5409715a8402
|
https://github.com/JetBrains/ring-ui/blob/fa7c39f47a91bb4b75d642834cad5409715a8402/components/autofocus-ng/autofocus-ng.js#L23-L43
|
17,313
|
JetBrains/ring-ui
|
components/date-picker/months.js
|
scrollSpeed
|
function scrollSpeed(date) {
const monthStart = moment(date).startOf('month');
const monthEnd = moment(date).endOf('month');
return (monthEnd - monthStart) / monthHeight(monthStart);
}
|
javascript
|
function scrollSpeed(date) {
const monthStart = moment(date).startOf('month');
const monthEnd = moment(date).endOf('month');
return (monthEnd - monthStart) / monthHeight(monthStart);
}
|
[
"function",
"scrollSpeed",
"(",
"date",
")",
"{",
"const",
"monthStart",
"=",
"moment",
"(",
"date",
")",
".",
"startOf",
"(",
"'month'",
")",
";",
"const",
"monthEnd",
"=",
"moment",
"(",
"date",
")",
".",
"endOf",
"(",
"'month'",
")",
";",
"return",
"(",
"monthEnd",
"-",
"monthStart",
")",
"/",
"monthHeight",
"(",
"monthStart",
")",
";",
"}"
] |
in milliseconds per pixel
|
[
"in",
"milliseconds",
"per",
"pixel"
] |
fa7c39f47a91bb4b75d642834cad5409715a8402
|
https://github.com/JetBrains/ring-ui/blob/fa7c39f47a91bb4b75d642834cad5409715a8402/components/date-picker/months.js#L32-L36
|
17,314
|
JetBrains/ring-ui
|
components/grid/row.js
|
getModifierClassNames
|
function getModifierClassNames(props) {
return modifierKeys.reduce((result, key) => {
if (props[key]) {
return result.concat(styles[`${key}-${props[key]}`]);
}
return result;
}, []);
}
|
javascript
|
function getModifierClassNames(props) {
return modifierKeys.reduce((result, key) => {
if (props[key]) {
return result.concat(styles[`${key}-${props[key]}`]);
}
return result;
}, []);
}
|
[
"function",
"getModifierClassNames",
"(",
"props",
")",
"{",
"return",
"modifierKeys",
".",
"reduce",
"(",
"(",
"result",
",",
"key",
")",
"=>",
"{",
"if",
"(",
"props",
"[",
"key",
"]",
")",
"{",
"return",
"result",
".",
"concat",
"(",
"styles",
"[",
"`",
"${",
"key",
"}",
"${",
"props",
"[",
"key",
"]",
"}",
"`",
"]",
")",
";",
"}",
"return",
"result",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] |
Converts xs="middle" to class "middle-xs"
@param {Object} props incoming props
@returns {Array} result modifier classes
|
[
"Converts",
"xs",
"=",
"middle",
"to",
"class",
"middle",
"-",
"xs"
] |
fa7c39f47a91bb4b75d642834cad5409715a8402
|
https://github.com/JetBrains/ring-ui/blob/fa7c39f47a91bb4b75d642834cad5409715a8402/components/grid/row.js#L20-L27
|
17,315
|
mattdesl/budo
|
lib/budo.js
|
watch
|
function watch (glob, watchOpt) {
if (!started) {
deferredWatch = emitter.watch.bind(null, glob, watchOpt)
} else {
// destroy previous
if (fileWatcher) fileWatcher.close()
glob = glob && glob.length > 0 ? glob : defaultWatchGlob
glob = Array.isArray(glob) ? glob : [ glob ]
watchOpt = xtend({ poll: opts.poll }, watchOpt)
fileWatcher = createFileWatch(glob, watchOpt)
fileWatcher.on('watch', emitter.emit.bind(emitter, 'watch'))
}
return emitter
}
|
javascript
|
function watch (glob, watchOpt) {
if (!started) {
deferredWatch = emitter.watch.bind(null, glob, watchOpt)
} else {
// destroy previous
if (fileWatcher) fileWatcher.close()
glob = glob && glob.length > 0 ? glob : defaultWatchGlob
glob = Array.isArray(glob) ? glob : [ glob ]
watchOpt = xtend({ poll: opts.poll }, watchOpt)
fileWatcher = createFileWatch(glob, watchOpt)
fileWatcher.on('watch', emitter.emit.bind(emitter, 'watch'))
}
return emitter
}
|
[
"function",
"watch",
"(",
"glob",
",",
"watchOpt",
")",
"{",
"if",
"(",
"!",
"started",
")",
"{",
"deferredWatch",
"=",
"emitter",
".",
"watch",
".",
"bind",
"(",
"null",
",",
"glob",
",",
"watchOpt",
")",
"}",
"else",
"{",
"// destroy previous",
"if",
"(",
"fileWatcher",
")",
"fileWatcher",
".",
"close",
"(",
")",
"glob",
"=",
"glob",
"&&",
"glob",
".",
"length",
">",
"0",
"?",
"glob",
":",
"defaultWatchGlob",
"glob",
"=",
"Array",
".",
"isArray",
"(",
"glob",
")",
"?",
"glob",
":",
"[",
"glob",
"]",
"watchOpt",
"=",
"xtend",
"(",
"{",
"poll",
":",
"opts",
".",
"poll",
"}",
",",
"watchOpt",
")",
"fileWatcher",
"=",
"createFileWatch",
"(",
"glob",
",",
"watchOpt",
")",
"fileWatcher",
".",
"on",
"(",
"'watch'",
",",
"emitter",
".",
"emit",
".",
"bind",
"(",
"emitter",
",",
"'watch'",
")",
")",
"}",
"return",
"emitter",
"}"
] |
enable file watch capabilities
|
[
"enable",
"file",
"watch",
"capabilities"
] |
6800de2b083ba390a0936fce3f72c448d4b1ae3a
|
https://github.com/mattdesl/budo/blob/6800de2b083ba390a0936fce3f72c448d4b1ae3a/lib/budo.js#L199-L213
|
17,316
|
mattdesl/budo
|
lib/budo.js
|
live
|
function live (liveOpts) {
if (!started) {
deferredLive = emitter.live.bind(null, liveOpts)
} else {
// destroy previous
if (reloader) reloader.close()
// pass some options for the server middleware
server.setLiveOptions(xtend(liveOpts))
// create a web socket server for live reload
reloader = createReloadServer(server, opts)
}
return emitter
}
|
javascript
|
function live (liveOpts) {
if (!started) {
deferredLive = emitter.live.bind(null, liveOpts)
} else {
// destroy previous
if (reloader) reloader.close()
// pass some options for the server middleware
server.setLiveOptions(xtend(liveOpts))
// create a web socket server for live reload
reloader = createReloadServer(server, opts)
}
return emitter
}
|
[
"function",
"live",
"(",
"liveOpts",
")",
"{",
"if",
"(",
"!",
"started",
")",
"{",
"deferredLive",
"=",
"emitter",
".",
"live",
".",
"bind",
"(",
"null",
",",
"liveOpts",
")",
"}",
"else",
"{",
"// destroy previous",
"if",
"(",
"reloader",
")",
"reloader",
".",
"close",
"(",
")",
"// pass some options for the server middleware",
"server",
".",
"setLiveOptions",
"(",
"xtend",
"(",
"liveOpts",
")",
")",
"// create a web socket server for live reload",
"reloader",
"=",
"createReloadServer",
"(",
"server",
",",
"opts",
")",
"}",
"return",
"emitter",
"}"
] |
enables LiveReload capabilities
|
[
"enables",
"LiveReload",
"capabilities"
] |
6800de2b083ba390a0936fce3f72c448d4b1ae3a
|
https://github.com/mattdesl/budo/blob/6800de2b083ba390a0936fce3f72c448d4b1ae3a/lib/budo.js#L216-L230
|
17,317
|
mattdesl/budo
|
lib/error-handler.js
|
parseError
|
function parseError (err) {
var filePath, lineNum, splitLines
var result = {}
// For root files that syntax-error doesn't pick up:
var parseFilePrefix = 'Parsing file '
if (err.indexOf(parseFilePrefix) === 0) {
var pathWithErr = err.substring(parseFilePrefix.length)
filePath = getFilePath(pathWithErr)
if (!filePath) return result
result.path = filePath
var messageAndLine = pathWithErr.substring(filePath.length)
lineNum = /\((\d+):(\d+)\)/.exec(messageAndLine)
if (!lineNum) return result
result.message = messageAndLine.substring(1, lineNum.index).trim()
result.line = parseInt(lineNum[1], 10)
result.column = parseInt(lineNum[2], 10)
result.format = true
return result
}
// if module not found
var cannotFindModule = /^Cannot find module '(.+)' from '(.+)'(?:$| while parsing file: (.*)$)/.exec(err.trim())
if (cannotFindModule) {
result.missingModule = cannotFindModule[1]
result.path = cannotFindModule[3] || cannotFindModule[2]
result.message = "Cannot find module '" + result.missingModule + "'"
result.format = true
return result
}
// syntax-error returns the path and line number, also a \n at start
err = err.trim()
filePath = getFilePath(err)
if (!filePath) return result
result.path = filePath
var restOfMessage = err.substring(filePath.length)
var parsedSyntaxError = /^:(\d+)/.exec(restOfMessage)
if (parsedSyntaxError) { // this is a syntax-error
lineNum = parseInt(parsedSyntaxError[1], 10)
if (isFinite(lineNum)) result.line = lineNum
splitLines = restOfMessage.split('\n')
var code = splitLines.slice(1, splitLines.length - 1).join('\n')
result.code = code
result.message = splitLines[splitLines.length - 1]
result.format = true
return result
}
// remove colon
restOfMessage = restOfMessage.substring(1).trim()
var whileParsing = 'while parsing file: '
var whileParsingIdx = restOfMessage.indexOf(whileParsing)
if (whileParsingIdx >= 0) {
var beforeWhile = restOfMessage.substring(0, whileParsingIdx)
lineNum = /\((\d+):(\d+)\)/.exec(beforeWhile.split('\n')[0])
var messageStr = beforeWhile
if (lineNum) {
var line = parseInt(lineNum[1], 10)
var col = parseInt(lineNum[2], 10)
if (isFinite(line)) result.line = line
if (isFinite(col)) result.column = col
messageStr = messageStr.substring(0, lineNum.index)
}
result.message = messageStr.trim()
splitLines = restOfMessage.split('\n')
result.code = splitLines.slice(2).join('\n')
result.format = true
}
return result
}
|
javascript
|
function parseError (err) {
var filePath, lineNum, splitLines
var result = {}
// For root files that syntax-error doesn't pick up:
var parseFilePrefix = 'Parsing file '
if (err.indexOf(parseFilePrefix) === 0) {
var pathWithErr = err.substring(parseFilePrefix.length)
filePath = getFilePath(pathWithErr)
if (!filePath) return result
result.path = filePath
var messageAndLine = pathWithErr.substring(filePath.length)
lineNum = /\((\d+):(\d+)\)/.exec(messageAndLine)
if (!lineNum) return result
result.message = messageAndLine.substring(1, lineNum.index).trim()
result.line = parseInt(lineNum[1], 10)
result.column = parseInt(lineNum[2], 10)
result.format = true
return result
}
// if module not found
var cannotFindModule = /^Cannot find module '(.+)' from '(.+)'(?:$| while parsing file: (.*)$)/.exec(err.trim())
if (cannotFindModule) {
result.missingModule = cannotFindModule[1]
result.path = cannotFindModule[3] || cannotFindModule[2]
result.message = "Cannot find module '" + result.missingModule + "'"
result.format = true
return result
}
// syntax-error returns the path and line number, also a \n at start
err = err.trim()
filePath = getFilePath(err)
if (!filePath) return result
result.path = filePath
var restOfMessage = err.substring(filePath.length)
var parsedSyntaxError = /^:(\d+)/.exec(restOfMessage)
if (parsedSyntaxError) { // this is a syntax-error
lineNum = parseInt(parsedSyntaxError[1], 10)
if (isFinite(lineNum)) result.line = lineNum
splitLines = restOfMessage.split('\n')
var code = splitLines.slice(1, splitLines.length - 1).join('\n')
result.code = code
result.message = splitLines[splitLines.length - 1]
result.format = true
return result
}
// remove colon
restOfMessage = restOfMessage.substring(1).trim()
var whileParsing = 'while parsing file: '
var whileParsingIdx = restOfMessage.indexOf(whileParsing)
if (whileParsingIdx >= 0) {
var beforeWhile = restOfMessage.substring(0, whileParsingIdx)
lineNum = /\((\d+):(\d+)\)/.exec(beforeWhile.split('\n')[0])
var messageStr = beforeWhile
if (lineNum) {
var line = parseInt(lineNum[1], 10)
var col = parseInt(lineNum[2], 10)
if (isFinite(line)) result.line = line
if (isFinite(col)) result.column = col
messageStr = messageStr.substring(0, lineNum.index)
}
result.message = messageStr.trim()
splitLines = restOfMessage.split('\n')
result.code = splitLines.slice(2).join('\n')
result.format = true
}
return result
}
|
[
"function",
"parseError",
"(",
"err",
")",
"{",
"var",
"filePath",
",",
"lineNum",
",",
"splitLines",
"var",
"result",
"=",
"{",
"}",
"// For root files that syntax-error doesn't pick up:",
"var",
"parseFilePrefix",
"=",
"'Parsing file '",
"if",
"(",
"err",
".",
"indexOf",
"(",
"parseFilePrefix",
")",
"===",
"0",
")",
"{",
"var",
"pathWithErr",
"=",
"err",
".",
"substring",
"(",
"parseFilePrefix",
".",
"length",
")",
"filePath",
"=",
"getFilePath",
"(",
"pathWithErr",
")",
"if",
"(",
"!",
"filePath",
")",
"return",
"result",
"result",
".",
"path",
"=",
"filePath",
"var",
"messageAndLine",
"=",
"pathWithErr",
".",
"substring",
"(",
"filePath",
".",
"length",
")",
"lineNum",
"=",
"/",
"\\((\\d+):(\\d+)\\)",
"/",
".",
"exec",
"(",
"messageAndLine",
")",
"if",
"(",
"!",
"lineNum",
")",
"return",
"result",
"result",
".",
"message",
"=",
"messageAndLine",
".",
"substring",
"(",
"1",
",",
"lineNum",
".",
"index",
")",
".",
"trim",
"(",
")",
"result",
".",
"line",
"=",
"parseInt",
"(",
"lineNum",
"[",
"1",
"]",
",",
"10",
")",
"result",
".",
"column",
"=",
"parseInt",
"(",
"lineNum",
"[",
"2",
"]",
",",
"10",
")",
"result",
".",
"format",
"=",
"true",
"return",
"result",
"}",
"// if module not found",
"var",
"cannotFindModule",
"=",
"/",
"^Cannot find module '(.+)' from '(.+)'(?:$| while parsing file: (.*)$)",
"/",
".",
"exec",
"(",
"err",
".",
"trim",
"(",
")",
")",
"if",
"(",
"cannotFindModule",
")",
"{",
"result",
".",
"missingModule",
"=",
"cannotFindModule",
"[",
"1",
"]",
"result",
".",
"path",
"=",
"cannotFindModule",
"[",
"3",
"]",
"||",
"cannotFindModule",
"[",
"2",
"]",
"result",
".",
"message",
"=",
"\"Cannot find module '\"",
"+",
"result",
".",
"missingModule",
"+",
"\"'\"",
"result",
".",
"format",
"=",
"true",
"return",
"result",
"}",
"// syntax-error returns the path and line number, also a \\n at start",
"err",
"=",
"err",
".",
"trim",
"(",
")",
"filePath",
"=",
"getFilePath",
"(",
"err",
")",
"if",
"(",
"!",
"filePath",
")",
"return",
"result",
"result",
".",
"path",
"=",
"filePath",
"var",
"restOfMessage",
"=",
"err",
".",
"substring",
"(",
"filePath",
".",
"length",
")",
"var",
"parsedSyntaxError",
"=",
"/",
"^:(\\d+)",
"/",
".",
"exec",
"(",
"restOfMessage",
")",
"if",
"(",
"parsedSyntaxError",
")",
"{",
"// this is a syntax-error",
"lineNum",
"=",
"parseInt",
"(",
"parsedSyntaxError",
"[",
"1",
"]",
",",
"10",
")",
"if",
"(",
"isFinite",
"(",
"lineNum",
")",
")",
"result",
".",
"line",
"=",
"lineNum",
"splitLines",
"=",
"restOfMessage",
".",
"split",
"(",
"'\\n'",
")",
"var",
"code",
"=",
"splitLines",
".",
"slice",
"(",
"1",
",",
"splitLines",
".",
"length",
"-",
"1",
")",
".",
"join",
"(",
"'\\n'",
")",
"result",
".",
"code",
"=",
"code",
"result",
".",
"message",
"=",
"splitLines",
"[",
"splitLines",
".",
"length",
"-",
"1",
"]",
"result",
".",
"format",
"=",
"true",
"return",
"result",
"}",
"// remove colon",
"restOfMessage",
"=",
"restOfMessage",
".",
"substring",
"(",
"1",
")",
".",
"trim",
"(",
")",
"var",
"whileParsing",
"=",
"'while parsing file: '",
"var",
"whileParsingIdx",
"=",
"restOfMessage",
".",
"indexOf",
"(",
"whileParsing",
")",
"if",
"(",
"whileParsingIdx",
">=",
"0",
")",
"{",
"var",
"beforeWhile",
"=",
"restOfMessage",
".",
"substring",
"(",
"0",
",",
"whileParsingIdx",
")",
"lineNum",
"=",
"/",
"\\((\\d+):(\\d+)\\)",
"/",
".",
"exec",
"(",
"beforeWhile",
".",
"split",
"(",
"'\\n'",
")",
"[",
"0",
"]",
")",
"var",
"messageStr",
"=",
"beforeWhile",
"if",
"(",
"lineNum",
")",
"{",
"var",
"line",
"=",
"parseInt",
"(",
"lineNum",
"[",
"1",
"]",
",",
"10",
")",
"var",
"col",
"=",
"parseInt",
"(",
"lineNum",
"[",
"2",
"]",
",",
"10",
")",
"if",
"(",
"isFinite",
"(",
"line",
")",
")",
"result",
".",
"line",
"=",
"line",
"if",
"(",
"isFinite",
"(",
"col",
")",
")",
"result",
".",
"column",
"=",
"col",
"messageStr",
"=",
"messageStr",
".",
"substring",
"(",
"0",
",",
"lineNum",
".",
"index",
")",
"}",
"result",
".",
"message",
"=",
"messageStr",
".",
"trim",
"(",
")",
"splitLines",
"=",
"restOfMessage",
".",
"split",
"(",
"'\\n'",
")",
"result",
".",
"code",
"=",
"splitLines",
".",
"slice",
"(",
"2",
")",
".",
"join",
"(",
"'\\n'",
")",
"result",
".",
"format",
"=",
"true",
"}",
"return",
"result",
"}"
] |
parse an error message into pieces
|
[
"parse",
"an",
"error",
"message",
"into",
"pieces"
] |
6800de2b083ba390a0936fce3f72c448d4b1ae3a
|
https://github.com/mattdesl/budo/blob/6800de2b083ba390a0936fce3f72c448d4b1ae3a/lib/error-handler.js#L149-L221
|
17,318
|
mattdesl/budo
|
lib/error-handler.js
|
getFilePath
|
function getFilePath (str) {
var hasRoot = /^[a-z]:/i.exec(str)
var colonLeftIndex = 0
if (hasRoot) {
colonLeftIndex = hasRoot[0].length
}
var pathEnd = str.split('\n')[0].indexOf(':', colonLeftIndex)
if (pathEnd === -1) {
// invalid string, return non-formattable result
return null
}
return str.substring(0, pathEnd)
}
|
javascript
|
function getFilePath (str) {
var hasRoot = /^[a-z]:/i.exec(str)
var colonLeftIndex = 0
if (hasRoot) {
colonLeftIndex = hasRoot[0].length
}
var pathEnd = str.split('\n')[0].indexOf(':', colonLeftIndex)
if (pathEnd === -1) {
// invalid string, return non-formattable result
return null
}
return str.substring(0, pathEnd)
}
|
[
"function",
"getFilePath",
"(",
"str",
")",
"{",
"var",
"hasRoot",
"=",
"/",
"^[a-z]:",
"/",
"i",
".",
"exec",
"(",
"str",
")",
"var",
"colonLeftIndex",
"=",
"0",
"if",
"(",
"hasRoot",
")",
"{",
"colonLeftIndex",
"=",
"hasRoot",
"[",
"0",
"]",
".",
"length",
"}",
"var",
"pathEnd",
"=",
"str",
".",
"split",
"(",
"'\\n'",
")",
"[",
"0",
"]",
".",
"indexOf",
"(",
"':'",
",",
"colonLeftIndex",
")",
"if",
"(",
"pathEnd",
"===",
"-",
"1",
")",
"{",
"// invalid string, return non-formattable result",
"return",
"null",
"}",
"return",
"str",
".",
"substring",
"(",
"0",
",",
"pathEnd",
")",
"}"
] |
get a file path from the error message
|
[
"get",
"a",
"file",
"path",
"from",
"the",
"error",
"message"
] |
6800de2b083ba390a0936fce3f72c448d4b1ae3a
|
https://github.com/mattdesl/budo/blob/6800de2b083ba390a0936fce3f72c448d4b1ae3a/lib/error-handler.js#L224-L236
|
17,319
|
thysultan/stylis.js
|
docs/assets/javascript/editor.js
|
update
|
function update (e) {
// tab indent
if (e.keyCode === 9) {
e.preventDefault();
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var text = document.createTextNode('\t');
range.deleteContents();
range.insertNode(text);
range.setStartAfter(text);
selection.removeAllRanges();
selection.addRange(range);
return;
}
var namespace = '.scope';
var raw = editor.textContent;
var pragma = /\/\* @scope (.*?) \*\//g.exec(raw);
if (pragma != null) {
namespace = pragma[1].trim();
}
var processed = stylis(namespace, raw);
// apply formatting
processed = processed.replace(/(;|\})/g, format.newlines);
processed = processed.replace(/(.*?)\{/g, format.selector);
processed = processed.replace(/:(.*);/g, format.value);
processed = processed.replace(/^.*;$/gm, format.tabs);
processed = processed.replace(/\}\n\n\}/g, '}\n}');
processed = processed.replace(/(.*@.*\{)([^\0]+\})(\n\})/g, format.block);
processed = processed.replace(/['"`].*?['"`]/g, format.string);
output.innerHTML = processed;
}
|
javascript
|
function update (e) {
// tab indent
if (e.keyCode === 9) {
e.preventDefault();
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var text = document.createTextNode('\t');
range.deleteContents();
range.insertNode(text);
range.setStartAfter(text);
selection.removeAllRanges();
selection.addRange(range);
return;
}
var namespace = '.scope';
var raw = editor.textContent;
var pragma = /\/\* @scope (.*?) \*\//g.exec(raw);
if (pragma != null) {
namespace = pragma[1].trim();
}
var processed = stylis(namespace, raw);
// apply formatting
processed = processed.replace(/(;|\})/g, format.newlines);
processed = processed.replace(/(.*?)\{/g, format.selector);
processed = processed.replace(/:(.*);/g, format.value);
processed = processed.replace(/^.*;$/gm, format.tabs);
processed = processed.replace(/\}\n\n\}/g, '}\n}');
processed = processed.replace(/(.*@.*\{)([^\0]+\})(\n\})/g, format.block);
processed = processed.replace(/['"`].*?['"`]/g, format.string);
output.innerHTML = processed;
}
|
[
"function",
"update",
"(",
"e",
")",
"{",
"// tab indent",
"if",
"(",
"e",
".",
"keyCode",
"===",
"9",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"var",
"selection",
"=",
"window",
".",
"getSelection",
"(",
")",
";",
"var",
"range",
"=",
"selection",
".",
"getRangeAt",
"(",
"0",
")",
";",
"var",
"text",
"=",
"document",
".",
"createTextNode",
"(",
"'\\t'",
")",
";",
"range",
".",
"deleteContents",
"(",
")",
";",
"range",
".",
"insertNode",
"(",
"text",
")",
";",
"range",
".",
"setStartAfter",
"(",
"text",
")",
";",
"selection",
".",
"removeAllRanges",
"(",
")",
";",
"selection",
".",
"addRange",
"(",
"range",
")",
";",
"return",
";",
"}",
"var",
"namespace",
"=",
"'.scope'",
";",
"var",
"raw",
"=",
"editor",
".",
"textContent",
";",
"var",
"pragma",
"=",
"/",
"\\/\\* @scope (.*?) \\*\\/",
"/",
"g",
".",
"exec",
"(",
"raw",
")",
";",
"if",
"(",
"pragma",
"!=",
"null",
")",
"{",
"namespace",
"=",
"pragma",
"[",
"1",
"]",
".",
"trim",
"(",
")",
";",
"}",
"var",
"processed",
"=",
"stylis",
"(",
"namespace",
",",
"raw",
")",
";",
"// apply formatting",
"processed",
"=",
"processed",
".",
"replace",
"(",
"/",
"(;|\\})",
"/",
"g",
",",
"format",
".",
"newlines",
")",
";",
"processed",
"=",
"processed",
".",
"replace",
"(",
"/",
"(.*?)\\{",
"/",
"g",
",",
"format",
".",
"selector",
")",
";",
"processed",
"=",
"processed",
".",
"replace",
"(",
"/",
":(.*);",
"/",
"g",
",",
"format",
".",
"value",
")",
";",
"processed",
"=",
"processed",
".",
"replace",
"(",
"/",
"^.*;$",
"/",
"gm",
",",
"format",
".",
"tabs",
")",
";",
"processed",
"=",
"processed",
".",
"replace",
"(",
"/",
"\\}\\n\\n\\}",
"/",
"g",
",",
"'}\\n}'",
")",
";",
"processed",
"=",
"processed",
".",
"replace",
"(",
"/",
"(.*@.*\\{)([^\\0]+\\})(\\n\\})",
"/",
"g",
",",
"format",
".",
"block",
")",
";",
"processed",
"=",
"processed",
".",
"replace",
"(",
"/",
"['\"`].*?['\"`]",
"/",
"g",
",",
"format",
".",
"string",
")",
";",
"output",
".",
"innerHTML",
"=",
"processed",
";",
"}"
] |
update output preview
|
[
"update",
"output",
"preview"
] |
4561e9bc830fccf1cb0e9e9838488b4d1d5cebf5
|
https://github.com/thysultan/stylis.js/blob/4561e9bc830fccf1cb0e9e9838488b4d1d5cebf5/docs/assets/javascript/editor.js#L28-L66
|
17,320
|
Automattic/cli-table
|
lib/utils.js
|
options
|
function options(defaults, opts) {
for (var p in opts) {
if (opts[p] && opts[p].constructor && opts[p].constructor === Object) {
defaults[p] = defaults[p] || {};
options(defaults[p], opts[p]);
} else {
defaults[p] = opts[p];
}
}
return defaults;
}
|
javascript
|
function options(defaults, opts) {
for (var p in opts) {
if (opts[p] && opts[p].constructor && opts[p].constructor === Object) {
defaults[p] = defaults[p] || {};
options(defaults[p], opts[p]);
} else {
defaults[p] = opts[p];
}
}
return defaults;
}
|
[
"function",
"options",
"(",
"defaults",
",",
"opts",
")",
"{",
"for",
"(",
"var",
"p",
"in",
"opts",
")",
"{",
"if",
"(",
"opts",
"[",
"p",
"]",
"&&",
"opts",
"[",
"p",
"]",
".",
"constructor",
"&&",
"opts",
"[",
"p",
"]",
".",
"constructor",
"===",
"Object",
")",
"{",
"defaults",
"[",
"p",
"]",
"=",
"defaults",
"[",
"p",
"]",
"||",
"{",
"}",
";",
"options",
"(",
"defaults",
"[",
"p",
"]",
",",
"opts",
"[",
"p",
"]",
")",
";",
"}",
"else",
"{",
"defaults",
"[",
"p",
"]",
"=",
"opts",
"[",
"p",
"]",
";",
"}",
"}",
"return",
"defaults",
";",
"}"
] |
Copies and merges options with defaults.
@param {Object} defaults
@param {Object} supplied options
@return {Object} new (merged) object
|
[
"Copies",
"and",
"merges",
"options",
"with",
"defaults",
"."
] |
7b14232ba779929e1859b267bf753c150d90a618
|
https://github.com/Automattic/cli-table/blob/7b14232ba779929e1859b267bf753c150d90a618/lib/utils.js#L60-L70
|
17,321
|
Automattic/cli-table
|
lib/index.js
|
line
|
function line (line, left, right, intersection){
var width = 0
, line =
left
+ repeat(line, totalWidth - 2)
+ right;
colWidths.forEach(function (w, i){
if (i == colWidths.length - 1) return;
width += w + 1;
line = line.substr(0, width) + intersection + line.substr(width + 1);
});
return applyStyles(options.style.border, line);
}
|
javascript
|
function line (line, left, right, intersection){
var width = 0
, line =
left
+ repeat(line, totalWidth - 2)
+ right;
colWidths.forEach(function (w, i){
if (i == colWidths.length - 1) return;
width += w + 1;
line = line.substr(0, width) + intersection + line.substr(width + 1);
});
return applyStyles(options.style.border, line);
}
|
[
"function",
"line",
"(",
"line",
",",
"left",
",",
"right",
",",
"intersection",
")",
"{",
"var",
"width",
"=",
"0",
",",
"line",
"=",
"left",
"+",
"repeat",
"(",
"line",
",",
"totalWidth",
"-",
"2",
")",
"+",
"right",
";",
"colWidths",
".",
"forEach",
"(",
"function",
"(",
"w",
",",
"i",
")",
"{",
"if",
"(",
"i",
"==",
"colWidths",
".",
"length",
"-",
"1",
")",
"return",
";",
"width",
"+=",
"w",
"+",
"1",
";",
"line",
"=",
"line",
".",
"substr",
"(",
"0",
",",
"width",
")",
"+",
"intersection",
"+",
"line",
".",
"substr",
"(",
"width",
"+",
"1",
")",
";",
"}",
")",
";",
"return",
"applyStyles",
"(",
"options",
".",
"style",
".",
"border",
",",
"line",
")",
";",
"}"
] |
draws a line
|
[
"draws",
"a",
"line"
] |
7b14232ba779929e1859b267bf753c150d90a618
|
https://github.com/Automattic/cli-table/blob/7b14232ba779929e1859b267bf753c150d90a618/lib/index.js#L137-L151
|
17,322
|
Automattic/cli-table
|
lib/index.js
|
lineTop
|
function lineTop (){
var l = line(chars.top
, chars['top-left'] || chars.top
, chars['top-right'] || chars.top
, chars['top-mid']);
if (l)
ret += l + "\n";
}
|
javascript
|
function lineTop (){
var l = line(chars.top
, chars['top-left'] || chars.top
, chars['top-right'] || chars.top
, chars['top-mid']);
if (l)
ret += l + "\n";
}
|
[
"function",
"lineTop",
"(",
")",
"{",
"var",
"l",
"=",
"line",
"(",
"chars",
".",
"top",
",",
"chars",
"[",
"'top-left'",
"]",
"||",
"chars",
".",
"top",
",",
"chars",
"[",
"'top-right'",
"]",
"||",
"chars",
".",
"top",
",",
"chars",
"[",
"'top-mid'",
"]",
")",
";",
"if",
"(",
"l",
")",
"ret",
"+=",
"l",
"+",
"\"\\n\"",
";",
"}"
] |
draws the top line
|
[
"draws",
"the",
"top",
"line"
] |
7b14232ba779929e1859b267bf753c150d90a618
|
https://github.com/Automattic/cli-table/blob/7b14232ba779929e1859b267bf753c150d90a618/lib/index.js#L154-L161
|
17,323
|
Automattic/cli-table
|
lib/index.js
|
string
|
function string (str, index){
var str = String(typeof str == 'object' && str.text ? str.text : str)
, length = utils.strlen(str)
, width = colWidths[index]
- (style['padding-left'] || 0)
- (style['padding-right'] || 0)
, align = options.colAligns[index] || 'left';
return repeat(' ', style['padding-left'] || 0)
+ (length == width ? str :
(length < width
? pad(str, ( width + (str.length - length) ), ' ', align == 'left' ? 'right' :
(align == 'middle' ? 'both' : 'left'))
: (truncater ? truncate(str, width, truncater) : str))
)
+ repeat(' ', style['padding-right'] || 0);
}
|
javascript
|
function string (str, index){
var str = String(typeof str == 'object' && str.text ? str.text : str)
, length = utils.strlen(str)
, width = colWidths[index]
- (style['padding-left'] || 0)
- (style['padding-right'] || 0)
, align = options.colAligns[index] || 'left';
return repeat(' ', style['padding-left'] || 0)
+ (length == width ? str :
(length < width
? pad(str, ( width + (str.length - length) ), ' ', align == 'left' ? 'right' :
(align == 'middle' ? 'both' : 'left'))
: (truncater ? truncate(str, width, truncater) : str))
)
+ repeat(' ', style['padding-right'] || 0);
}
|
[
"function",
"string",
"(",
"str",
",",
"index",
")",
"{",
"var",
"str",
"=",
"String",
"(",
"typeof",
"str",
"==",
"'object'",
"&&",
"str",
".",
"text",
"?",
"str",
".",
"text",
":",
"str",
")",
",",
"length",
"=",
"utils",
".",
"strlen",
"(",
"str",
")",
",",
"width",
"=",
"colWidths",
"[",
"index",
"]",
"-",
"(",
"style",
"[",
"'padding-left'",
"]",
"||",
"0",
")",
"-",
"(",
"style",
"[",
"'padding-right'",
"]",
"||",
"0",
")",
",",
"align",
"=",
"options",
".",
"colAligns",
"[",
"index",
"]",
"||",
"'left'",
";",
"return",
"repeat",
"(",
"' '",
",",
"style",
"[",
"'padding-left'",
"]",
"||",
"0",
")",
"+",
"(",
"length",
"==",
"width",
"?",
"str",
":",
"(",
"length",
"<",
"width",
"?",
"pad",
"(",
"str",
",",
"(",
"width",
"+",
"(",
"str",
".",
"length",
"-",
"length",
")",
")",
",",
"' '",
",",
"align",
"==",
"'left'",
"?",
"'right'",
":",
"(",
"align",
"==",
"'middle'",
"?",
"'both'",
":",
"'left'",
")",
")",
":",
"(",
"truncater",
"?",
"truncate",
"(",
"str",
",",
"width",
",",
"truncater",
")",
":",
"str",
")",
")",
")",
"+",
"repeat",
"(",
"' '",
",",
"style",
"[",
"'padding-right'",
"]",
"||",
"0",
")",
";",
"}"
] |
renders a string, by padding it or truncating it
|
[
"renders",
"a",
"string",
"by",
"padding",
"it",
"or",
"truncating",
"it"
] |
7b14232ba779929e1859b267bf753c150d90a618
|
https://github.com/Automattic/cli-table/blob/7b14232ba779929e1859b267bf753c150d90a618/lib/index.js#L236-L252
|
17,324
|
jshttp/mime-types
|
index.js
|
charset
|
function charset (type) {
if (!type || typeof type !== 'string') {
return false
}
// TODO: use media-typer
var match = EXTRACT_TYPE_REGEXP.exec(type)
var mime = match && db[match[1].toLowerCase()]
if (mime && mime.charset) {
return mime.charset
}
// default text/* to utf-8
if (match && TEXT_TYPE_REGEXP.test(match[1])) {
return 'UTF-8'
}
return false
}
|
javascript
|
function charset (type) {
if (!type || typeof type !== 'string') {
return false
}
// TODO: use media-typer
var match = EXTRACT_TYPE_REGEXP.exec(type)
var mime = match && db[match[1].toLowerCase()]
if (mime && mime.charset) {
return mime.charset
}
// default text/* to utf-8
if (match && TEXT_TYPE_REGEXP.test(match[1])) {
return 'UTF-8'
}
return false
}
|
[
"function",
"charset",
"(",
"type",
")",
"{",
"if",
"(",
"!",
"type",
"||",
"typeof",
"type",
"!==",
"'string'",
")",
"{",
"return",
"false",
"}",
"// TODO: use media-typer",
"var",
"match",
"=",
"EXTRACT_TYPE_REGEXP",
".",
"exec",
"(",
"type",
")",
"var",
"mime",
"=",
"match",
"&&",
"db",
"[",
"match",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
"]",
"if",
"(",
"mime",
"&&",
"mime",
".",
"charset",
")",
"{",
"return",
"mime",
".",
"charset",
"}",
"// default text/* to utf-8",
"if",
"(",
"match",
"&&",
"TEXT_TYPE_REGEXP",
".",
"test",
"(",
"match",
"[",
"1",
"]",
")",
")",
"{",
"return",
"'UTF-8'",
"}",
"return",
"false",
"}"
] |
Get the default charset for a MIME type.
@param {string} type
@return {boolean|string}
|
[
"Get",
"the",
"default",
"charset",
"for",
"a",
"MIME",
"type",
"."
] |
e5b5f41ef0d7e4e66eb9baeec7920c0cd9ec81f0
|
https://github.com/jshttp/mime-types/blob/e5b5f41ef0d7e4e66eb9baeec7920c0cd9ec81f0/index.js#L49-L68
|
17,325
|
jshttp/mime-types
|
index.js
|
contentType
|
function contentType (str) {
// TODO: should this even be in this module?
if (!str || typeof str !== 'string') {
return false
}
var mime = str.indexOf('/') === -1
? exports.lookup(str)
: str
if (!mime) {
return false
}
// TODO: use content-type or other module
if (mime.indexOf('charset') === -1) {
var charset = exports.charset(mime)
if (charset) mime += '; charset=' + charset.toLowerCase()
}
return mime
}
|
javascript
|
function contentType (str) {
// TODO: should this even be in this module?
if (!str || typeof str !== 'string') {
return false
}
var mime = str.indexOf('/') === -1
? exports.lookup(str)
: str
if (!mime) {
return false
}
// TODO: use content-type or other module
if (mime.indexOf('charset') === -1) {
var charset = exports.charset(mime)
if (charset) mime += '; charset=' + charset.toLowerCase()
}
return mime
}
|
[
"function",
"contentType",
"(",
"str",
")",
"{",
"// TODO: should this even be in this module?",
"if",
"(",
"!",
"str",
"||",
"typeof",
"str",
"!==",
"'string'",
")",
"{",
"return",
"false",
"}",
"var",
"mime",
"=",
"str",
".",
"indexOf",
"(",
"'/'",
")",
"===",
"-",
"1",
"?",
"exports",
".",
"lookup",
"(",
"str",
")",
":",
"str",
"if",
"(",
"!",
"mime",
")",
"{",
"return",
"false",
"}",
"// TODO: use content-type or other module",
"if",
"(",
"mime",
".",
"indexOf",
"(",
"'charset'",
")",
"===",
"-",
"1",
")",
"{",
"var",
"charset",
"=",
"exports",
".",
"charset",
"(",
"mime",
")",
"if",
"(",
"charset",
")",
"mime",
"+=",
"'; charset='",
"+",
"charset",
".",
"toLowerCase",
"(",
")",
"}",
"return",
"mime",
"}"
] |
Create a full Content-Type header given a MIME type or extension.
@param {string} str
@return {boolean|string}
|
[
"Create",
"a",
"full",
"Content",
"-",
"Type",
"header",
"given",
"a",
"MIME",
"type",
"or",
"extension",
"."
] |
e5b5f41ef0d7e4e66eb9baeec7920c0cd9ec81f0
|
https://github.com/jshttp/mime-types/blob/e5b5f41ef0d7e4e66eb9baeec7920c0cd9ec81f0/index.js#L77-L98
|
17,326
|
jshttp/mime-types
|
index.js
|
extension
|
function extension (type) {
if (!type || typeof type !== 'string') {
return false
}
// TODO: use media-typer
var match = EXTRACT_TYPE_REGEXP.exec(type)
// get extensions
var exts = match && exports.extensions[match[1].toLowerCase()]
if (!exts || !exts.length) {
return false
}
return exts[0]
}
|
javascript
|
function extension (type) {
if (!type || typeof type !== 'string') {
return false
}
// TODO: use media-typer
var match = EXTRACT_TYPE_REGEXP.exec(type)
// get extensions
var exts = match && exports.extensions[match[1].toLowerCase()]
if (!exts || !exts.length) {
return false
}
return exts[0]
}
|
[
"function",
"extension",
"(",
"type",
")",
"{",
"if",
"(",
"!",
"type",
"||",
"typeof",
"type",
"!==",
"'string'",
")",
"{",
"return",
"false",
"}",
"// TODO: use media-typer",
"var",
"match",
"=",
"EXTRACT_TYPE_REGEXP",
".",
"exec",
"(",
"type",
")",
"// get extensions",
"var",
"exts",
"=",
"match",
"&&",
"exports",
".",
"extensions",
"[",
"match",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
"]",
"if",
"(",
"!",
"exts",
"||",
"!",
"exts",
".",
"length",
")",
"{",
"return",
"false",
"}",
"return",
"exts",
"[",
"0",
"]",
"}"
] |
Get the default extension for a MIME type.
@param {string} type
@return {boolean|string}
|
[
"Get",
"the",
"default",
"extension",
"for",
"a",
"MIME",
"type",
"."
] |
e5b5f41ef0d7e4e66eb9baeec7920c0cd9ec81f0
|
https://github.com/jshttp/mime-types/blob/e5b5f41ef0d7e4e66eb9baeec7920c0cd9ec81f0/index.js#L107-L123
|
17,327
|
jshttp/mime-types
|
index.js
|
populateMaps
|
function populateMaps (extensions, types) {
// source preference (least -> most)
var preference = ['nginx', 'apache', undefined, 'iana']
Object.keys(db).forEach(function forEachMimeType (type) {
var mime = db[type]
var exts = mime.extensions
if (!exts || !exts.length) {
return
}
// mime -> extensions
extensions[type] = exts
// extension -> mime
for (var i = 0; i < exts.length; i++) {
var extension = exts[i]
if (types[extension]) {
var from = preference.indexOf(db[types[extension]].source)
var to = preference.indexOf(mime.source)
if (types[extension] !== 'application/octet-stream' &&
(from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
// skip the remapping
continue
}
}
// set the extension -> mime
types[extension] = type
}
})
}
|
javascript
|
function populateMaps (extensions, types) {
// source preference (least -> most)
var preference = ['nginx', 'apache', undefined, 'iana']
Object.keys(db).forEach(function forEachMimeType (type) {
var mime = db[type]
var exts = mime.extensions
if (!exts || !exts.length) {
return
}
// mime -> extensions
extensions[type] = exts
// extension -> mime
for (var i = 0; i < exts.length; i++) {
var extension = exts[i]
if (types[extension]) {
var from = preference.indexOf(db[types[extension]].source)
var to = preference.indexOf(mime.source)
if (types[extension] !== 'application/octet-stream' &&
(from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
// skip the remapping
continue
}
}
// set the extension -> mime
types[extension] = type
}
})
}
|
[
"function",
"populateMaps",
"(",
"extensions",
",",
"types",
")",
"{",
"// source preference (least -> most)",
"var",
"preference",
"=",
"[",
"'nginx'",
",",
"'apache'",
",",
"undefined",
",",
"'iana'",
"]",
"Object",
".",
"keys",
"(",
"db",
")",
".",
"forEach",
"(",
"function",
"forEachMimeType",
"(",
"type",
")",
"{",
"var",
"mime",
"=",
"db",
"[",
"type",
"]",
"var",
"exts",
"=",
"mime",
".",
"extensions",
"if",
"(",
"!",
"exts",
"||",
"!",
"exts",
".",
"length",
")",
"{",
"return",
"}",
"// mime -> extensions",
"extensions",
"[",
"type",
"]",
"=",
"exts",
"// extension -> mime",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"exts",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"extension",
"=",
"exts",
"[",
"i",
"]",
"if",
"(",
"types",
"[",
"extension",
"]",
")",
"{",
"var",
"from",
"=",
"preference",
".",
"indexOf",
"(",
"db",
"[",
"types",
"[",
"extension",
"]",
"]",
".",
"source",
")",
"var",
"to",
"=",
"preference",
".",
"indexOf",
"(",
"mime",
".",
"source",
")",
"if",
"(",
"types",
"[",
"extension",
"]",
"!==",
"'application/octet-stream'",
"&&",
"(",
"from",
">",
"to",
"||",
"(",
"from",
"===",
"to",
"&&",
"types",
"[",
"extension",
"]",
".",
"substr",
"(",
"0",
",",
"12",
")",
"===",
"'application/'",
")",
")",
")",
"{",
"// skip the remapping",
"continue",
"}",
"}",
"// set the extension -> mime",
"types",
"[",
"extension",
"]",
"=",
"type",
"}",
"}",
")",
"}"
] |
Populate the extensions and types maps.
@private
|
[
"Populate",
"the",
"extensions",
"and",
"types",
"maps",
"."
] |
e5b5f41ef0d7e4e66eb9baeec7920c0cd9ec81f0
|
https://github.com/jshttp/mime-types/blob/e5b5f41ef0d7e4e66eb9baeec7920c0cd9ec81f0/index.js#L154-L188
|
17,328
|
observing/pre-commit
|
install.js
|
getGitFolderPath
|
function getGitFolderPath(currentPath) {
var git = path.resolve(currentPath, '.git')
if (!exists(git) || !fs.lstatSync(git).isDirectory()) {
console.log('pre-commit:');
console.log('pre-commit: Not found .git folder in', git);
var newPath = path.resolve(currentPath, '..');
// Stop if we on top folder
if (currentPath === newPath) {
return null;
}
return getGitFolderPath(newPath);
}
console.log('pre-commit:');
console.log('pre-commit: Found .git folder in', git);
return git;
}
|
javascript
|
function getGitFolderPath(currentPath) {
var git = path.resolve(currentPath, '.git')
if (!exists(git) || !fs.lstatSync(git).isDirectory()) {
console.log('pre-commit:');
console.log('pre-commit: Not found .git folder in', git);
var newPath = path.resolve(currentPath, '..');
// Stop if we on top folder
if (currentPath === newPath) {
return null;
}
return getGitFolderPath(newPath);
}
console.log('pre-commit:');
console.log('pre-commit: Found .git folder in', git);
return git;
}
|
[
"function",
"getGitFolderPath",
"(",
"currentPath",
")",
"{",
"var",
"git",
"=",
"path",
".",
"resolve",
"(",
"currentPath",
",",
"'.git'",
")",
"if",
"(",
"!",
"exists",
"(",
"git",
")",
"||",
"!",
"fs",
".",
"lstatSync",
"(",
"git",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"console",
".",
"log",
"(",
"'pre-commit:'",
")",
";",
"console",
".",
"log",
"(",
"'pre-commit: Not found .git folder in'",
",",
"git",
")",
";",
"var",
"newPath",
"=",
"path",
".",
"resolve",
"(",
"currentPath",
",",
"'..'",
")",
";",
"// Stop if we on top folder",
"if",
"(",
"currentPath",
"===",
"newPath",
")",
"{",
"return",
"null",
";",
"}",
"return",
"getGitFolderPath",
"(",
"newPath",
")",
";",
"}",
"console",
".",
"log",
"(",
"'pre-commit:'",
")",
";",
"console",
".",
"log",
"(",
"'pre-commit: Found .git folder in'",
",",
"git",
")",
";",
"return",
"git",
";",
"}"
] |
Function to recursively finding .git folder
|
[
"Function",
"to",
"recursively",
"finding",
".",
"git",
"folder"
] |
84aa9eac11634d8fe6053fa7946dee5b77f09581
|
https://github.com/observing/pre-commit/blob/84aa9eac11634d8fe6053fa7946dee5b77f09581/install.js#L23-L43
|
17,329
|
observing/pre-commit
|
index.js
|
Hook
|
function Hook(fn, options) {
if (!this) return new Hook(fn, options);
options = options || {};
this.options = options; // Used for testing only. Ignore this. Don't touch.
this.config = {}; // pre-commit configuration from the `package.json`.
this.json = {}; // Actual content of the `package.json`.
this.npm = ''; // The location of the `npm` binary.
this.git = ''; // The location of the `git` binary.
this.root = ''; // The root location of the .git folder.
this.status = ''; // Contents of the `git status`.
this.exit = fn; // Exit function.
this.initialize();
}
|
javascript
|
function Hook(fn, options) {
if (!this) return new Hook(fn, options);
options = options || {};
this.options = options; // Used for testing only. Ignore this. Don't touch.
this.config = {}; // pre-commit configuration from the `package.json`.
this.json = {}; // Actual content of the `package.json`.
this.npm = ''; // The location of the `npm` binary.
this.git = ''; // The location of the `git` binary.
this.root = ''; // The root location of the .git folder.
this.status = ''; // Contents of the `git status`.
this.exit = fn; // Exit function.
this.initialize();
}
|
[
"function",
"Hook",
"(",
"fn",
",",
"options",
")",
"{",
"if",
"(",
"!",
"this",
")",
"return",
"new",
"Hook",
"(",
"fn",
",",
"options",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"options",
"=",
"options",
";",
"// Used for testing only. Ignore this. Don't touch.",
"this",
".",
"config",
"=",
"{",
"}",
";",
"// pre-commit configuration from the `package.json`.",
"this",
".",
"json",
"=",
"{",
"}",
";",
"// Actual content of the `package.json`.",
"this",
".",
"npm",
"=",
"''",
";",
"// The location of the `npm` binary.",
"this",
".",
"git",
"=",
"''",
";",
"// The location of the `git` binary.",
"this",
".",
"root",
"=",
"''",
";",
"// The root location of the .git folder.",
"this",
".",
"status",
"=",
"''",
";",
"// Contents of the `git status`.",
"this",
".",
"exit",
"=",
"fn",
";",
"// Exit function.",
"this",
".",
"initialize",
"(",
")",
";",
"}"
] |
Representation of a hook runner.
@constructor
@param {Function} fn Function to be called when we want to exit
@param {Object} options Optional configuration, primarily used for testing.
@api public
|
[
"Representation",
"of",
"a",
"hook",
"runner",
"."
] |
84aa9eac11634d8fe6053fa7946dee5b77f09581
|
https://github.com/observing/pre-commit/blob/84aa9eac11634d8fe6053fa7946dee5b77f09581/index.js#L17-L31
|
17,330
|
davidyack/Xrm.Tools.CRMWebAPI
|
JS/Examples/SinglePage/app/scripts/app.js
|
loadView
|
function loadView(view) {
$errorMessage.empty();
var ctrl = loadCtrl(view);
if (!ctrl)
return;
// Check if View Requires Authentication
if (ctrl.requireADLogin && !authContext.getCachedUser()) {
authContext.config.redirectUri = window.location.href;
authContext.login();
return;
}
// Load View HTML
$.ajax({
type: "GET",
url: "views/" + view + '.html',
dataType: "html",
}).done(function (html) {
// Show HTML Skeleton (Without Data)
var $html = $(html);
$html.find(".data-container").empty();
$panel.html($html.html());
ctrl.postProcess(html);
}).fail(function () {
$errorMessage.html('Error loading page.');
}).always(function () {
});
}
|
javascript
|
function loadView(view) {
$errorMessage.empty();
var ctrl = loadCtrl(view);
if (!ctrl)
return;
// Check if View Requires Authentication
if (ctrl.requireADLogin && !authContext.getCachedUser()) {
authContext.config.redirectUri = window.location.href;
authContext.login();
return;
}
// Load View HTML
$.ajax({
type: "GET",
url: "views/" + view + '.html',
dataType: "html",
}).done(function (html) {
// Show HTML Skeleton (Without Data)
var $html = $(html);
$html.find(".data-container").empty();
$panel.html($html.html());
ctrl.postProcess(html);
}).fail(function () {
$errorMessage.html('Error loading page.');
}).always(function () {
});
}
|
[
"function",
"loadView",
"(",
"view",
")",
"{",
"$errorMessage",
".",
"empty",
"(",
")",
";",
"var",
"ctrl",
"=",
"loadCtrl",
"(",
"view",
")",
";",
"if",
"(",
"!",
"ctrl",
")",
"return",
";",
"// Check if View Requires Authentication",
"if",
"(",
"ctrl",
".",
"requireADLogin",
"&&",
"!",
"authContext",
".",
"getCachedUser",
"(",
")",
")",
"{",
"authContext",
".",
"config",
".",
"redirectUri",
"=",
"window",
".",
"location",
".",
"href",
";",
"authContext",
".",
"login",
"(",
")",
";",
"return",
";",
"}",
"// Load View HTML",
"$",
".",
"ajax",
"(",
"{",
"type",
":",
"\"GET\"",
",",
"url",
":",
"\"views/\"",
"+",
"view",
"+",
"'.html'",
",",
"dataType",
":",
"\"html\"",
",",
"}",
")",
".",
"done",
"(",
"function",
"(",
"html",
")",
"{",
"// Show HTML Skeleton (Without Data)",
"var",
"$html",
"=",
"$",
"(",
"html",
")",
";",
"$html",
".",
"find",
"(",
"\".data-container\"",
")",
".",
"empty",
"(",
")",
";",
"$panel",
".",
"html",
"(",
"$html",
".",
"html",
"(",
")",
")",
";",
"ctrl",
".",
"postProcess",
"(",
"html",
")",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
")",
"{",
"$errorMessage",
".",
"html",
"(",
"'Error loading page.'",
")",
";",
"}",
")",
".",
"always",
"(",
"function",
"(",
")",
"{",
"}",
")",
";",
"}"
] |
Show a View
|
[
"Show",
"a",
"View"
] |
c5569bb668e34d87fe4cba0f4089973943ab0ca0
|
https://github.com/davidyack/Xrm.Tools.CRMWebAPI/blob/c5569bb668e34d87fe4cba0f4089973943ab0ca0/JS/Examples/SinglePage/app/scripts/app.js#L79-L112
|
17,331
|
benwiley4000/cassette
|
packages/core/src/utils/getSourceList.js
|
getSourceList
|
function getSourceList(playlist) {
return (playlist || []).map((_, i) => getTrackSources(playlist, i)[0].src);
}
|
javascript
|
function getSourceList(playlist) {
return (playlist || []).map((_, i) => getTrackSources(playlist, i)[0].src);
}
|
[
"function",
"getSourceList",
"(",
"playlist",
")",
"{",
"return",
"(",
"playlist",
"||",
"[",
"]",
")",
".",
"map",
"(",
"(",
"_",
",",
"i",
")",
"=>",
"getTrackSources",
"(",
"playlist",
",",
"i",
")",
"[",
"0",
"]",
".",
"src",
")",
";",
"}"
] |
collapses playlist into flat list containing the first source url for each track
|
[
"collapses",
"playlist",
"into",
"flat",
"list",
"containing",
"the",
"first",
"source",
"url",
"for",
"each",
"track"
] |
2f6e15a911addb27fdf0d876e92c29c94779c1ca
|
https://github.com/benwiley4000/cassette/blob/2f6e15a911addb27fdf0d876e92c29c94779c1ca/packages/core/src/utils/getSourceList.js#L5-L7
|
17,332
|
benwiley4000/cassette
|
packages/core/src/PlayerContextProvider.js
|
getGoToTrackState
|
function getGoToTrackState({
prevState,
index,
track,
shouldPlay = true,
shouldForceLoad = false
}) {
const isNewTrack = prevState.activeTrackIndex !== index;
const shouldLoadAsNew = Boolean(isNewTrack || shouldForceLoad);
const currentTime = track.startingTime || 0;
return {
duration: getInitialDuration(track),
activeTrackIndex: index,
trackLoading: shouldLoadAsNew,
mediaCannotPlay: prevState.mediaCannotPlay && !shouldLoadAsNew,
currentTime: convertToNumberWithinIntervalBounds(currentTime, 0),
loop: shouldLoadAsNew ? false : prevState.loop,
shouldRequestPlayOnNextUpdate: Boolean(shouldPlay),
awaitingPlayAfterTrackLoad: Boolean(shouldPlay),
awaitingForceLoad: Boolean(shouldForceLoad),
maxKnownTime: shouldLoadAsNew ? 0 : prevState.maxKnownTime
};
}
|
javascript
|
function getGoToTrackState({
prevState,
index,
track,
shouldPlay = true,
shouldForceLoad = false
}) {
const isNewTrack = prevState.activeTrackIndex !== index;
const shouldLoadAsNew = Boolean(isNewTrack || shouldForceLoad);
const currentTime = track.startingTime || 0;
return {
duration: getInitialDuration(track),
activeTrackIndex: index,
trackLoading: shouldLoadAsNew,
mediaCannotPlay: prevState.mediaCannotPlay && !shouldLoadAsNew,
currentTime: convertToNumberWithinIntervalBounds(currentTime, 0),
loop: shouldLoadAsNew ? false : prevState.loop,
shouldRequestPlayOnNextUpdate: Boolean(shouldPlay),
awaitingPlayAfterTrackLoad: Boolean(shouldPlay),
awaitingForceLoad: Boolean(shouldForceLoad),
maxKnownTime: shouldLoadAsNew ? 0 : prevState.maxKnownTime
};
}
|
[
"function",
"getGoToTrackState",
"(",
"{",
"prevState",
",",
"index",
",",
"track",
",",
"shouldPlay",
"=",
"true",
",",
"shouldForceLoad",
"=",
"false",
"}",
")",
"{",
"const",
"isNewTrack",
"=",
"prevState",
".",
"activeTrackIndex",
"!==",
"index",
";",
"const",
"shouldLoadAsNew",
"=",
"Boolean",
"(",
"isNewTrack",
"||",
"shouldForceLoad",
")",
";",
"const",
"currentTime",
"=",
"track",
".",
"startingTime",
"||",
"0",
";",
"return",
"{",
"duration",
":",
"getInitialDuration",
"(",
"track",
")",
",",
"activeTrackIndex",
":",
"index",
",",
"trackLoading",
":",
"shouldLoadAsNew",
",",
"mediaCannotPlay",
":",
"prevState",
".",
"mediaCannotPlay",
"&&",
"!",
"shouldLoadAsNew",
",",
"currentTime",
":",
"convertToNumberWithinIntervalBounds",
"(",
"currentTime",
",",
"0",
")",
",",
"loop",
":",
"shouldLoadAsNew",
"?",
"false",
":",
"prevState",
".",
"loop",
",",
"shouldRequestPlayOnNextUpdate",
":",
"Boolean",
"(",
"shouldPlay",
")",
",",
"awaitingPlayAfterTrackLoad",
":",
"Boolean",
"(",
"shouldPlay",
")",
",",
"awaitingForceLoad",
":",
"Boolean",
"(",
"shouldForceLoad",
")",
",",
"maxKnownTime",
":",
"shouldLoadAsNew",
"?",
"0",
":",
"prevState",
".",
"maxKnownTime",
"}",
";",
"}"
] |
assumes playlist is valid
|
[
"assumes",
"playlist",
"is",
"valid"
] |
2f6e15a911addb27fdf0d876e92c29c94779c1ca
|
https://github.com/benwiley4000/cassette/blob/2f6e15a911addb27fdf0d876e92c29c94779c1ca/packages/core/src/PlayerContextProvider.js#L83-L105
|
17,333
|
morajabi/styled-media-query
|
src/convertors.js
|
pxToEmOrRem
|
function pxToEmOrRem(breakpoints, ratio = 16, unit) {
const newBreakpoints = {};
for (let key in breakpoints) {
const point = breakpoints[key];
if (String(point).includes('px')) {
newBreakpoints[key] = +(parseInt(point) / ratio) + unit;
continue;
}
newBreakpoints[key] = point;
}
return newBreakpoints;
}
|
javascript
|
function pxToEmOrRem(breakpoints, ratio = 16, unit) {
const newBreakpoints = {};
for (let key in breakpoints) {
const point = breakpoints[key];
if (String(point).includes('px')) {
newBreakpoints[key] = +(parseInt(point) / ratio) + unit;
continue;
}
newBreakpoints[key] = point;
}
return newBreakpoints;
}
|
[
"function",
"pxToEmOrRem",
"(",
"breakpoints",
",",
"ratio",
"=",
"16",
",",
"unit",
")",
"{",
"const",
"newBreakpoints",
"=",
"{",
"}",
";",
"for",
"(",
"let",
"key",
"in",
"breakpoints",
")",
"{",
"const",
"point",
"=",
"breakpoints",
"[",
"key",
"]",
";",
"if",
"(",
"String",
"(",
"point",
")",
".",
"includes",
"(",
"'px'",
")",
")",
"{",
"newBreakpoints",
"[",
"key",
"]",
"=",
"+",
"(",
"parseInt",
"(",
"point",
")",
"/",
"ratio",
")",
"+",
"unit",
";",
"continue",
";",
"}",
"newBreakpoints",
"[",
"key",
"]",
"=",
"point",
";",
"}",
"return",
"newBreakpoints",
";",
"}"
] |
Converts breakpoint units in px to rem or em
@param {Object} breakpoints - an object containing breakpoint names as keys and the width as value
@param {number} ratio [16] - size of 1 rem in px. What is your main font-size in px?
@param {'rem' | 'em'} unit
|
[
"Converts",
"breakpoint",
"units",
"in",
"px",
"to",
"rem",
"or",
"em"
] |
687a2089dbf46924783a8b157f4d3ebcdead7b3b
|
https://github.com/morajabi/styled-media-query/blob/687a2089dbf46924783a8b157f4d3ebcdead7b3b/src/convertors.js#L7-L22
|
17,334
|
Automattic/monk
|
lib/manager.js
|
Manager
|
function Manager (uri, opts, fn) {
if (!uri) {
throw Error('No connection URI provided.')
}
if (!(this instanceof Manager)) {
return new Manager(uri, opts, fn)
}
if (typeof opts === 'function') {
fn = opts
opts = {}
}
opts = opts || {}
this._collectionOptions = objectAssign({}, DEFAULT_OPTIONS, opts.collectionOptions || {})
delete opts.collectionOptions
if (Array.isArray(uri)) {
if (!opts.database) {
for (var i = 0, l = uri.length; i < l; i++) {
if (!opts.database) {
opts.database = uri[i].replace(/([^\/])+\/?/, '') // eslint-disable-line
}
uri[i] = uri[i].replace(/\/.*/, '')
}
}
uri = uri.join(',') + '/' + opts.database
monkDebug('repl set connection "%j" to database "%s"', uri, opts.database)
}
if (typeof uri === 'string') {
if (!/^mongodb:\/\//.test(uri)) {
uri = 'mongodb://' + uri
}
}
this._state = STATE.OPENING
this._queue = []
this.on('open', function (db) {
monkDebug('connection opened')
monkDebug('emptying queries queue (%s to go)', this._queue.length)
this._queue.forEach(function (cb) {
cb(db)
})
}.bind(this))
this._connectionURI = uri
this._connectionOptions = opts
this.open(uri, opts, fn && function (err) {
fn(err, this)
}.bind(this))
this.helper = {
id: ObjectId
}
this.collections = {}
this.open = this.open.bind(this)
this.close = this.close.bind(this)
this.executeWhenOpened = this.executeWhenOpened.bind(this)
this.collection = this.col = this.get = this.get.bind(this)
this.oid = this.id
this.setDefaultCollectionOptions = this.setDefaultCollectionOptions.bind(this)
this.addMiddleware = this.addMiddleware.bind(this)
}
|
javascript
|
function Manager (uri, opts, fn) {
if (!uri) {
throw Error('No connection URI provided.')
}
if (!(this instanceof Manager)) {
return new Manager(uri, opts, fn)
}
if (typeof opts === 'function') {
fn = opts
opts = {}
}
opts = opts || {}
this._collectionOptions = objectAssign({}, DEFAULT_OPTIONS, opts.collectionOptions || {})
delete opts.collectionOptions
if (Array.isArray(uri)) {
if (!opts.database) {
for (var i = 0, l = uri.length; i < l; i++) {
if (!opts.database) {
opts.database = uri[i].replace(/([^\/])+\/?/, '') // eslint-disable-line
}
uri[i] = uri[i].replace(/\/.*/, '')
}
}
uri = uri.join(',') + '/' + opts.database
monkDebug('repl set connection "%j" to database "%s"', uri, opts.database)
}
if (typeof uri === 'string') {
if (!/^mongodb:\/\//.test(uri)) {
uri = 'mongodb://' + uri
}
}
this._state = STATE.OPENING
this._queue = []
this.on('open', function (db) {
monkDebug('connection opened')
monkDebug('emptying queries queue (%s to go)', this._queue.length)
this._queue.forEach(function (cb) {
cb(db)
})
}.bind(this))
this._connectionURI = uri
this._connectionOptions = opts
this.open(uri, opts, fn && function (err) {
fn(err, this)
}.bind(this))
this.helper = {
id: ObjectId
}
this.collections = {}
this.open = this.open.bind(this)
this.close = this.close.bind(this)
this.executeWhenOpened = this.executeWhenOpened.bind(this)
this.collection = this.col = this.get = this.get.bind(this)
this.oid = this.id
this.setDefaultCollectionOptions = this.setDefaultCollectionOptions.bind(this)
this.addMiddleware = this.addMiddleware.bind(this)
}
|
[
"function",
"Manager",
"(",
"uri",
",",
"opts",
",",
"fn",
")",
"{",
"if",
"(",
"!",
"uri",
")",
"{",
"throw",
"Error",
"(",
"'No connection URI provided.'",
")",
"}",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Manager",
")",
")",
"{",
"return",
"new",
"Manager",
"(",
"uri",
",",
"opts",
",",
"fn",
")",
"}",
"if",
"(",
"typeof",
"opts",
"===",
"'function'",
")",
"{",
"fn",
"=",
"opts",
"opts",
"=",
"{",
"}",
"}",
"opts",
"=",
"opts",
"||",
"{",
"}",
"this",
".",
"_collectionOptions",
"=",
"objectAssign",
"(",
"{",
"}",
",",
"DEFAULT_OPTIONS",
",",
"opts",
".",
"collectionOptions",
"||",
"{",
"}",
")",
"delete",
"opts",
".",
"collectionOptions",
"if",
"(",
"Array",
".",
"isArray",
"(",
"uri",
")",
")",
"{",
"if",
"(",
"!",
"opts",
".",
"database",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"uri",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"opts",
".",
"database",
")",
"{",
"opts",
".",
"database",
"=",
"uri",
"[",
"i",
"]",
".",
"replace",
"(",
"/",
"([^\\/])+\\/?",
"/",
",",
"''",
")",
"// eslint-disable-line",
"}",
"uri",
"[",
"i",
"]",
"=",
"uri",
"[",
"i",
"]",
".",
"replace",
"(",
"/",
"\\/.*",
"/",
",",
"''",
")",
"}",
"}",
"uri",
"=",
"uri",
".",
"join",
"(",
"','",
")",
"+",
"'/'",
"+",
"opts",
".",
"database",
"monkDebug",
"(",
"'repl set connection \"%j\" to database \"%s\"'",
",",
"uri",
",",
"opts",
".",
"database",
")",
"}",
"if",
"(",
"typeof",
"uri",
"===",
"'string'",
")",
"{",
"if",
"(",
"!",
"/",
"^mongodb:\\/\\/",
"/",
".",
"test",
"(",
"uri",
")",
")",
"{",
"uri",
"=",
"'mongodb://'",
"+",
"uri",
"}",
"}",
"this",
".",
"_state",
"=",
"STATE",
".",
"OPENING",
"this",
".",
"_queue",
"=",
"[",
"]",
"this",
".",
"on",
"(",
"'open'",
",",
"function",
"(",
"db",
")",
"{",
"monkDebug",
"(",
"'connection opened'",
")",
"monkDebug",
"(",
"'emptying queries queue (%s to go)'",
",",
"this",
".",
"_queue",
".",
"length",
")",
"this",
".",
"_queue",
".",
"forEach",
"(",
"function",
"(",
"cb",
")",
"{",
"cb",
"(",
"db",
")",
"}",
")",
"}",
".",
"bind",
"(",
"this",
")",
")",
"this",
".",
"_connectionURI",
"=",
"uri",
"this",
".",
"_connectionOptions",
"=",
"opts",
"this",
".",
"open",
"(",
"uri",
",",
"opts",
",",
"fn",
"&&",
"function",
"(",
"err",
")",
"{",
"fn",
"(",
"err",
",",
"this",
")",
"}",
".",
"bind",
"(",
"this",
")",
")",
"this",
".",
"helper",
"=",
"{",
"id",
":",
"ObjectId",
"}",
"this",
".",
"collections",
"=",
"{",
"}",
"this",
".",
"open",
"=",
"this",
".",
"open",
".",
"bind",
"(",
"this",
")",
"this",
".",
"close",
"=",
"this",
".",
"close",
".",
"bind",
"(",
"this",
")",
"this",
".",
"executeWhenOpened",
"=",
"this",
".",
"executeWhenOpened",
".",
"bind",
"(",
"this",
")",
"this",
".",
"collection",
"=",
"this",
".",
"col",
"=",
"this",
".",
"get",
"=",
"this",
".",
"get",
".",
"bind",
"(",
"this",
")",
"this",
".",
"oid",
"=",
"this",
".",
"id",
"this",
".",
"setDefaultCollectionOptions",
"=",
"this",
".",
"setDefaultCollectionOptions",
".",
"bind",
"(",
"this",
")",
"this",
".",
"addMiddleware",
"=",
"this",
".",
"addMiddleware",
".",
"bind",
"(",
"this",
")",
"}"
] |
Monk constructor.
@param {Array|String} uri replica sets can be an array or
comma-separated
@param {Object|Function} opts or connect callback
@param {Function} fn connect callback
@return {Promise} resolve when the connection is opened
|
[
"Monk",
"constructor",
"."
] |
39228eacd4d649de884b096624a55472cf20c40a
|
https://github.com/Automattic/monk/blob/39228eacd4d649de884b096624a55472cf20c40a/lib/manager.js#L47-L116
|
17,335
|
flickr/yakbak
|
index.js
|
tapename
|
function tapename(req, body) {
var hash = opts.hash || messageHash.sync;
return hash(req, Buffer.concat(body)) + '.js';
}
|
javascript
|
function tapename(req, body) {
var hash = opts.hash || messageHash.sync;
return hash(req, Buffer.concat(body)) + '.js';
}
|
[
"function",
"tapename",
"(",
"req",
",",
"body",
")",
"{",
"var",
"hash",
"=",
"opts",
".",
"hash",
"||",
"messageHash",
".",
"sync",
";",
"return",
"hash",
"(",
"req",
",",
"Buffer",
".",
"concat",
"(",
"body",
")",
")",
"+",
"'.js'",
";",
"}"
] |
Returns the tape name for `req`.
@param {http.IncomingMessage} req
@param {Array.<Buffer>} body
@returns {String}
|
[
"Returns",
"the",
"tape",
"name",
"for",
"req",
"."
] |
0047013893066a3b3b0a9d3143042c5430e4db75
|
https://github.com/flickr/yakbak/blob/0047013893066a3b3b0a9d3143042c5430e4db75/index.js#L70-L74
|
17,336
|
flickr/yakbak
|
lib/record.js
|
write
|
function write(filename, data) {
return Promise.fromCallback(function (done) {
debug('write', filename);
fs.writeFile(filename, data, done);
});
}
|
javascript
|
function write(filename, data) {
return Promise.fromCallback(function (done) {
debug('write', filename);
fs.writeFile(filename, data, done);
});
}
|
[
"function",
"write",
"(",
"filename",
",",
"data",
")",
"{",
"return",
"Promise",
".",
"fromCallback",
"(",
"function",
"(",
"done",
")",
"{",
"debug",
"(",
"'write'",
",",
"filename",
")",
";",
"fs",
".",
"writeFile",
"(",
"filename",
",",
"data",
",",
"done",
")",
";",
"}",
")",
";",
"}"
] |
Write `data` to `filename`. Seems overkill to "promisify" this.
@param {String} filename
@param {String} data
@returns {Promise}
|
[
"Write",
"data",
"to",
"filename",
".",
"Seems",
"overkill",
"to",
"promisify",
"this",
"."
] |
0047013893066a3b3b0a9d3143042c5430e4db75
|
https://github.com/flickr/yakbak/blob/0047013893066a3b3b0a9d3143042c5430e4db75/lib/record.js#L46-L51
|
17,337
|
fluencelabs/fluence
|
fluence-js/src/examples/todo-list/index.js
|
createNewTask
|
function createNewTask(task) {
console.log("Creating task...");
//set up the new list item
const listItem = document.createElement("li");
const checkBox = document.createElement("input");
const label = document.createElement("label");
//pull the inputed text into label
label.innerText = task;
//add properties
checkBox.type = "checkbox";
//add items to the li
listItem.appendChild(checkBox);
listItem.appendChild(label);
//everything put together
return listItem;
}
|
javascript
|
function createNewTask(task) {
console.log("Creating task...");
//set up the new list item
const listItem = document.createElement("li");
const checkBox = document.createElement("input");
const label = document.createElement("label");
//pull the inputed text into label
label.innerText = task;
//add properties
checkBox.type = "checkbox";
//add items to the li
listItem.appendChild(checkBox);
listItem.appendChild(label);
//everything put together
return listItem;
}
|
[
"function",
"createNewTask",
"(",
"task",
")",
"{",
"console",
".",
"log",
"(",
"\"Creating task...\"",
")",
";",
"//set up the new list item",
"const",
"listItem",
"=",
"document",
".",
"createElement",
"(",
"\"li\"",
")",
";",
"const",
"checkBox",
"=",
"document",
".",
"createElement",
"(",
"\"input\"",
")",
";",
"const",
"label",
"=",
"document",
".",
"createElement",
"(",
"\"label\"",
")",
";",
"//pull the inputed text into label",
"label",
".",
"innerText",
"=",
"task",
";",
"//add properties",
"checkBox",
".",
"type",
"=",
"\"checkbox\"",
";",
"//add items to the li",
"listItem",
".",
"appendChild",
"(",
"checkBox",
")",
";",
"listItem",
".",
"appendChild",
"(",
"label",
")",
";",
"//everything put together",
"return",
"listItem",
";",
"}"
] |
create functions creating the actual task list item
|
[
"create",
"functions",
"creating",
"the",
"actual",
"task",
"list",
"item"
] |
2877526629d7efd8aa61e0e250d3498b2837dfb8
|
https://github.com/fluencelabs/fluence/blob/2877526629d7efd8aa61e0e250d3498b2837dfb8/fluence-js/src/examples/todo-list/index.js#L130-L150
|
17,338
|
fluencelabs/fluence
|
fluence-js/src/examples/todo-list/index.js
|
addTask
|
function addTask() {
const task = newTask.value.trim();
console.log("Adding task: " + task);
// *****
// *** we need to add a task to the fluence cluster after we pressed the `Add task` button
// *****
addTaskToFluence(task);
updateTaskList(task)
}
|
javascript
|
function addTask() {
const task = newTask.value.trim();
console.log("Adding task: " + task);
// *****
// *** we need to add a task to the fluence cluster after we pressed the `Add task` button
// *****
addTaskToFluence(task);
updateTaskList(task)
}
|
[
"function",
"addTask",
"(",
")",
"{",
"const",
"task",
"=",
"newTask",
".",
"value",
".",
"trim",
"(",
")",
";",
"console",
".",
"log",
"(",
"\"Adding task: \"",
"+",
"task",
")",
";",
"// *****",
"// *** we need to add a task to the fluence cluster after we pressed the `Add task` button",
"// *****",
"addTaskToFluence",
"(",
"task",
")",
";",
"updateTaskList",
"(",
"task",
")",
"}"
] |
do the new task into actual incomplete list
|
[
"do",
"the",
"new",
"task",
"into",
"actual",
"incomplete",
"list"
] |
2877526629d7efd8aa61e0e250d3498b2837dfb8
|
https://github.com/fluencelabs/fluence/blob/2877526629d7efd8aa61e0e250d3498b2837dfb8/fluence-js/src/examples/todo-list/index.js#L187-L198
|
17,339
|
fluencelabs/fluence
|
fluence-js/src/examples/todo-list/index.js
|
deleteTask
|
function deleteTask() {
console.log("Deleting task...");
const listItem = this.parentNode;
const ul = listItem.parentNode;
const task = listItem.getElementsByTagName('label')[0].innerText;
// *****
// *** delete a task from the cluster when we press `Delete` button on the completed task
// *****
deleteFromFluence(task);
ul.removeChild(listItem);
}
|
javascript
|
function deleteTask() {
console.log("Deleting task...");
const listItem = this.parentNode;
const ul = listItem.parentNode;
const task = listItem.getElementsByTagName('label')[0].innerText;
// *****
// *** delete a task from the cluster when we press `Delete` button on the completed task
// *****
deleteFromFluence(task);
ul.removeChild(listItem);
}
|
[
"function",
"deleteTask",
"(",
")",
"{",
"console",
".",
"log",
"(",
"\"Deleting task...\"",
")",
";",
"const",
"listItem",
"=",
"this",
".",
"parentNode",
";",
"const",
"ul",
"=",
"listItem",
".",
"parentNode",
";",
"const",
"task",
"=",
"listItem",
".",
"getElementsByTagName",
"(",
"'label'",
")",
"[",
"0",
"]",
".",
"innerText",
";",
"// *****",
"// *** delete a task from the cluster when we press `Delete` button on the completed task",
"// *****",
"deleteFromFluence",
"(",
"task",
")",
";",
"ul",
".",
"removeChild",
"(",
"listItem",
")",
";",
"}"
] |
delete task functions
|
[
"delete",
"task",
"functions"
] |
2877526629d7efd8aa61e0e250d3498b2837dfb8
|
https://github.com/fluencelabs/fluence/blob/2877526629d7efd8aa61e0e250d3498b2837dfb8/fluence-js/src/examples/todo-list/index.js#L242-L257
|
17,340
|
xtuc/webassemblyjs
|
packages/dce/src/used-exports.js
|
onLocalModuleBinding
|
function onLocalModuleBinding(ident, ast, acc) {
traverse(ast, {
CallExpression({ node: callExpression }) {
// left must be a member expression
if (t.isMemberExpression(callExpression.callee) === false) {
return;
}
const memberExpression = callExpression.callee;
/**
* Search for `makeX().then(...)`
*/
if (
t.isCallExpression(memberExpression.object) &&
memberExpression.object.callee.name === ident.name &&
memberExpression.property.name === "then"
) {
const [thenFnBody] = callExpression.arguments;
if (typeof thenFnBody === "undefined") {
return;
}
onInstanceThenFn(thenFnBody, acc);
}
}
});
}
|
javascript
|
function onLocalModuleBinding(ident, ast, acc) {
traverse(ast, {
CallExpression({ node: callExpression }) {
// left must be a member expression
if (t.isMemberExpression(callExpression.callee) === false) {
return;
}
const memberExpression = callExpression.callee;
/**
* Search for `makeX().then(...)`
*/
if (
t.isCallExpression(memberExpression.object) &&
memberExpression.object.callee.name === ident.name &&
memberExpression.property.name === "then"
) {
const [thenFnBody] = callExpression.arguments;
if (typeof thenFnBody === "undefined") {
return;
}
onInstanceThenFn(thenFnBody, acc);
}
}
});
}
|
[
"function",
"onLocalModuleBinding",
"(",
"ident",
",",
"ast",
",",
"acc",
")",
"{",
"traverse",
"(",
"ast",
",",
"{",
"CallExpression",
"(",
"{",
"node",
":",
"callExpression",
"}",
")",
"{",
"// left must be a member expression",
"if",
"(",
"t",
".",
"isMemberExpression",
"(",
"callExpression",
".",
"callee",
")",
"===",
"false",
")",
"{",
"return",
";",
"}",
"const",
"memberExpression",
"=",
"callExpression",
".",
"callee",
";",
"/**\n * Search for `makeX().then(...)`\n */",
"if",
"(",
"t",
".",
"isCallExpression",
"(",
"memberExpression",
".",
"object",
")",
"&&",
"memberExpression",
".",
"object",
".",
"callee",
".",
"name",
"===",
"ident",
".",
"name",
"&&",
"memberExpression",
".",
"property",
".",
"name",
"===",
"\"then\"",
")",
"{",
"const",
"[",
"thenFnBody",
"]",
"=",
"callExpression",
".",
"arguments",
";",
"if",
"(",
"typeof",
"thenFnBody",
"===",
"\"undefined\"",
")",
"{",
"return",
";",
"}",
"onInstanceThenFn",
"(",
"thenFnBody",
",",
"acc",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] |
We found a local binding from the wasm binary.
`import x from 'module.wasm'`
^
|
[
"We",
"found",
"a",
"local",
"binding",
"from",
"the",
"wasm",
"binary",
"."
] |
32996b42072073f270adc178ce542da1ae9e9704
|
https://github.com/xtuc/webassemblyjs/blob/32996b42072073f270adc178ce542da1ae9e9704/packages/dce/src/used-exports.js#L23-L51
|
17,341
|
xtuc/webassemblyjs
|
packages/dce/src/used-exports.js
|
onInstanceThenFn
|
function onInstanceThenFn(fn, acc) {
if (t.isArrowFunctionExpression(fn) === false) {
throw new Error("Unsupported function type: " + fn.type);
}
let [localIdent] = fn.params;
/**
* `then(({exports}) => ...)`
*
* We need to resolve the identifier (binding) from the ObjectPattern.
*
* TODO(sven): handle renaming the binding here
*/
if (t.isObjectPattern(localIdent) === true) {
// ModuleInstance has the exports prop by spec
localIdent = t.identifier("exports");
}
traverse(fn.body, {
noScope: true,
MemberExpression(path) {
const { object, property } = path.node;
/**
* Search for `localIdent.exports`
*/
if (
identEq(object, localIdent) === true &&
t.isIdentifier(property, { name: "exports" })
) {
/**
* We are looking for the right branch of the parent MemberExpression:
* `(localIdent.exports).x`
* ^
*/
const { property } = path.parentPath.node;
// Found an usage of an export
acc.push(property.name);
path.stop();
} else if (identEq(object, localIdent) === true) {
/**
* `exports` might be a local binding (from destructuring)
*/
// Found an usage of an export
acc.push(property.name);
path.stop();
}
}
});
}
|
javascript
|
function onInstanceThenFn(fn, acc) {
if (t.isArrowFunctionExpression(fn) === false) {
throw new Error("Unsupported function type: " + fn.type);
}
let [localIdent] = fn.params;
/**
* `then(({exports}) => ...)`
*
* We need to resolve the identifier (binding) from the ObjectPattern.
*
* TODO(sven): handle renaming the binding here
*/
if (t.isObjectPattern(localIdent) === true) {
// ModuleInstance has the exports prop by spec
localIdent = t.identifier("exports");
}
traverse(fn.body, {
noScope: true,
MemberExpression(path) {
const { object, property } = path.node;
/**
* Search for `localIdent.exports`
*/
if (
identEq(object, localIdent) === true &&
t.isIdentifier(property, { name: "exports" })
) {
/**
* We are looking for the right branch of the parent MemberExpression:
* `(localIdent.exports).x`
* ^
*/
const { property } = path.parentPath.node;
// Found an usage of an export
acc.push(property.name);
path.stop();
} else if (identEq(object, localIdent) === true) {
/**
* `exports` might be a local binding (from destructuring)
*/
// Found an usage of an export
acc.push(property.name);
path.stop();
}
}
});
}
|
[
"function",
"onInstanceThenFn",
"(",
"fn",
",",
"acc",
")",
"{",
"if",
"(",
"t",
".",
"isArrowFunctionExpression",
"(",
"fn",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Unsupported function type: \"",
"+",
"fn",
".",
"type",
")",
";",
"}",
"let",
"[",
"localIdent",
"]",
"=",
"fn",
".",
"params",
";",
"/**\n * `then(({exports}) => ...)`\n *\n * We need to resolve the identifier (binding) from the ObjectPattern.\n *\n * TODO(sven): handle renaming the binding here\n */",
"if",
"(",
"t",
".",
"isObjectPattern",
"(",
"localIdent",
")",
"===",
"true",
")",
"{",
"// ModuleInstance has the exports prop by spec",
"localIdent",
"=",
"t",
".",
"identifier",
"(",
"\"exports\"",
")",
";",
"}",
"traverse",
"(",
"fn",
".",
"body",
",",
"{",
"noScope",
":",
"true",
",",
"MemberExpression",
"(",
"path",
")",
"{",
"const",
"{",
"object",
",",
"property",
"}",
"=",
"path",
".",
"node",
";",
"/**\n * Search for `localIdent.exports`\n */",
"if",
"(",
"identEq",
"(",
"object",
",",
"localIdent",
")",
"===",
"true",
"&&",
"t",
".",
"isIdentifier",
"(",
"property",
",",
"{",
"name",
":",
"\"exports\"",
"}",
")",
")",
"{",
"/**\n * We are looking for the right branch of the parent MemberExpression:\n * `(localIdent.exports).x`\n * ^\n */",
"const",
"{",
"property",
"}",
"=",
"path",
".",
"parentPath",
".",
"node",
";",
"// Found an usage of an export",
"acc",
".",
"push",
"(",
"property",
".",
"name",
")",
";",
"path",
".",
"stop",
"(",
")",
";",
"}",
"else",
"if",
"(",
"identEq",
"(",
"object",
",",
"localIdent",
")",
"===",
"true",
")",
"{",
"/**\n * `exports` might be a local binding (from destructuring)\n */",
"// Found an usage of an export",
"acc",
".",
"push",
"(",
"property",
".",
"name",
")",
";",
"path",
".",
"stop",
"(",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] |
We found the function handling the module instance
`makeX().then(...)`
|
[
"We",
"found",
"the",
"function",
"handling",
"the",
"module",
"instance"
] |
32996b42072073f270adc178ce542da1ae9e9704
|
https://github.com/xtuc/webassemblyjs/blob/32996b42072073f270adc178ce542da1ae9e9704/packages/dce/src/used-exports.js#L58-L112
|
17,342
|
xtuc/webassemblyjs
|
website/static/js/repl.js
|
configureMonaco
|
function configureMonaco() {
monaco.languages.register({ id: "wast" });
monaco.languages.setMonarchTokensProvider("wast", {
tokenizer: {
root: [
[REGEXP_KEYWORD, "keyword"],
[REGEXP_KEYWORD_ASSERTS, "keyword"],
[REGEXP_NUMBER, "number"],
[/\$([a-zA-Z0-9_`\+\-\*\/\\\^~=<>!\?@#$%&|:\.]+)/, "variable"],
[REGEXP_STRING, "string"],
[/;;.*$/, "comment"]
]
}
});
monaco.editor.defineTheme("wastTheme", {
base: "vs-dark",
inherit: true,
rules: [
{ token: "string", foreground: "4caf50" },
{ token: "number", foreground: "808080" }
]
});
}
|
javascript
|
function configureMonaco() {
monaco.languages.register({ id: "wast" });
monaco.languages.setMonarchTokensProvider("wast", {
tokenizer: {
root: [
[REGEXP_KEYWORD, "keyword"],
[REGEXP_KEYWORD_ASSERTS, "keyword"],
[REGEXP_NUMBER, "number"],
[/\$([a-zA-Z0-9_`\+\-\*\/\\\^~=<>!\?@#$%&|:\.]+)/, "variable"],
[REGEXP_STRING, "string"],
[/;;.*$/, "comment"]
]
}
});
monaco.editor.defineTheme("wastTheme", {
base: "vs-dark",
inherit: true,
rules: [
{ token: "string", foreground: "4caf50" },
{ token: "number", foreground: "808080" }
]
});
}
|
[
"function",
"configureMonaco",
"(",
")",
"{",
"monaco",
".",
"languages",
".",
"register",
"(",
"{",
"id",
":",
"\"wast\"",
"}",
")",
";",
"monaco",
".",
"languages",
".",
"setMonarchTokensProvider",
"(",
"\"wast\"",
",",
"{",
"tokenizer",
":",
"{",
"root",
":",
"[",
"[",
"REGEXP_KEYWORD",
",",
"\"keyword\"",
"]",
",",
"[",
"REGEXP_KEYWORD_ASSERTS",
",",
"\"keyword\"",
"]",
",",
"[",
"REGEXP_NUMBER",
",",
"\"number\"",
"]",
",",
"[",
"/",
"\\$([a-zA-Z0-9_`\\+\\-\\*\\/\\\\\\^~=<>!\\?@#$%&|:\\.]+)",
"/",
",",
"\"variable\"",
"]",
",",
"[",
"REGEXP_STRING",
",",
"\"string\"",
"]",
",",
"[",
"/",
";;.*$",
"/",
",",
"\"comment\"",
"]",
"]",
"}",
"}",
")",
";",
"monaco",
".",
"editor",
".",
"defineTheme",
"(",
"\"wastTheme\"",
",",
"{",
"base",
":",
"\"vs-dark\"",
",",
"inherit",
":",
"true",
",",
"rules",
":",
"[",
"{",
"token",
":",
"\"string\"",
",",
"foreground",
":",
"\"4caf50\"",
"}",
",",
"{",
"token",
":",
"\"number\"",
",",
"foreground",
":",
"\"808080\"",
"}",
"]",
"}",
")",
";",
"}"
] |
Monaco wast def
|
[
"Monaco",
"wast",
"def"
] |
32996b42072073f270adc178ce542da1ae9e9704
|
https://github.com/xtuc/webassemblyjs/blob/32996b42072073f270adc178ce542da1ae9e9704/website/static/js/repl.js#L16-L40
|
17,343
|
xtuc/webassemblyjs
|
packages/leb128/src/leb.js
|
encodeBufferCommon
|
function encodeBufferCommon(buffer, signed) {
let signBit;
let bitCount;
if (signed) {
signBit = bits.getSign(buffer);
bitCount = signedBitCount(buffer);
} else {
signBit = 0;
bitCount = unsignedBitCount(buffer);
}
const byteCount = Math.ceil(bitCount / 7);
const result = bufs.alloc(byteCount);
for (let i = 0; i < byteCount; i++) {
const payload = bits.extract(buffer, i * 7, 7, signBit);
result[i] = payload | 0x80;
}
// Mask off the top bit of the last byte, to indicate the end of the
// encoding.
result[byteCount - 1] &= 0x7f;
return result;
}
|
javascript
|
function encodeBufferCommon(buffer, signed) {
let signBit;
let bitCount;
if (signed) {
signBit = bits.getSign(buffer);
bitCount = signedBitCount(buffer);
} else {
signBit = 0;
bitCount = unsignedBitCount(buffer);
}
const byteCount = Math.ceil(bitCount / 7);
const result = bufs.alloc(byteCount);
for (let i = 0; i < byteCount; i++) {
const payload = bits.extract(buffer, i * 7, 7, signBit);
result[i] = payload | 0x80;
}
// Mask off the top bit of the last byte, to indicate the end of the
// encoding.
result[byteCount - 1] &= 0x7f;
return result;
}
|
[
"function",
"encodeBufferCommon",
"(",
"buffer",
",",
"signed",
")",
"{",
"let",
"signBit",
";",
"let",
"bitCount",
";",
"if",
"(",
"signed",
")",
"{",
"signBit",
"=",
"bits",
".",
"getSign",
"(",
"buffer",
")",
";",
"bitCount",
"=",
"signedBitCount",
"(",
"buffer",
")",
";",
"}",
"else",
"{",
"signBit",
"=",
"0",
";",
"bitCount",
"=",
"unsignedBitCount",
"(",
"buffer",
")",
";",
"}",
"const",
"byteCount",
"=",
"Math",
".",
"ceil",
"(",
"bitCount",
"/",
"7",
")",
";",
"const",
"result",
"=",
"bufs",
".",
"alloc",
"(",
"byteCount",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"byteCount",
";",
"i",
"++",
")",
"{",
"const",
"payload",
"=",
"bits",
".",
"extract",
"(",
"buffer",
",",
"i",
"*",
"7",
",",
"7",
",",
"signBit",
")",
";",
"result",
"[",
"i",
"]",
"=",
"payload",
"|",
"0x80",
";",
"}",
"// Mask off the top bit of the last byte, to indicate the end of the",
"// encoding.",
"result",
"[",
"byteCount",
"-",
"1",
"]",
"&=",
"0x7f",
";",
"return",
"result",
";",
"}"
] |
Common encoder for both signed and unsigned ints. This takes a
bigint-ish buffer, returning an LEB128-encoded buffer.
|
[
"Common",
"encoder",
"for",
"both",
"signed",
"and",
"unsigned",
"ints",
".",
"This",
"takes",
"a",
"bigint",
"-",
"ish",
"buffer",
"returning",
"an",
"LEB128",
"-",
"encoded",
"buffer",
"."
] |
32996b42072073f270adc178ce542da1ae9e9704
|
https://github.com/xtuc/webassemblyjs/blob/32996b42072073f270adc178ce542da1ae9e9704/packages/leb128/src/leb.js#L95-L119
|
17,344
|
xtuc/webassemblyjs
|
packages/leb128/src/leb.js
|
encodedLength
|
function encodedLength(encodedBuffer, index) {
let result = 0;
while (encodedBuffer[index + result] >= 0x80) {
result++;
}
result++; // to account for the last byte
if (index + result > encodedBuffer.length) {
// FIXME(sven): seems to cause false positives
// throw new Error("integer representation too long");
}
return result;
}
|
javascript
|
function encodedLength(encodedBuffer, index) {
let result = 0;
while (encodedBuffer[index + result] >= 0x80) {
result++;
}
result++; // to account for the last byte
if (index + result > encodedBuffer.length) {
// FIXME(sven): seems to cause false positives
// throw new Error("integer representation too long");
}
return result;
}
|
[
"function",
"encodedLength",
"(",
"encodedBuffer",
",",
"index",
")",
"{",
"let",
"result",
"=",
"0",
";",
"while",
"(",
"encodedBuffer",
"[",
"index",
"+",
"result",
"]",
">=",
"0x80",
")",
"{",
"result",
"++",
";",
"}",
"result",
"++",
";",
"// to account for the last byte",
"if",
"(",
"index",
"+",
"result",
">",
"encodedBuffer",
".",
"length",
")",
"{",
"// FIXME(sven): seems to cause false positives",
"// throw new Error(\"integer representation too long\");",
"}",
"return",
"result",
";",
"}"
] |
Gets the byte-length of the value encoded in the given buffer at
the given index.
|
[
"Gets",
"the",
"byte",
"-",
"length",
"of",
"the",
"value",
"encoded",
"in",
"the",
"given",
"buffer",
"at",
"the",
"given",
"index",
"."
] |
32996b42072073f270adc178ce542da1ae9e9704
|
https://github.com/xtuc/webassemblyjs/blob/32996b42072073f270adc178ce542da1ae9e9704/packages/leb128/src/leb.js#L125-L140
|
17,345
|
xtuc/webassemblyjs
|
packages/leb128/src/leb.js
|
decodeBufferCommon
|
function decodeBufferCommon(encodedBuffer, index, signed) {
index = index === undefined ? 0 : index;
let length = encodedLength(encodedBuffer, index);
const bitLength = length * 7;
let byteLength = Math.ceil(bitLength / 8);
let result = bufs.alloc(byteLength);
let outIndex = 0;
while (length > 0) {
bits.inject(result, outIndex, 7, encodedBuffer[index]);
outIndex += 7;
index++;
length--;
}
let signBit;
let signByte;
if (signed) {
// Sign-extend the last byte.
let lastByte = result[byteLength - 1];
const endBit = outIndex % 8;
if (endBit !== 0) {
const shift = 32 - endBit; // 32 because JS bit ops work on 32-bit ints.
lastByte = result[byteLength - 1] = ((lastByte << shift) >> shift) & 0xff;
}
signBit = lastByte >> 7;
signByte = signBit * 0xff;
} else {
signBit = 0;
signByte = 0;
}
// Slice off any superfluous bytes, that is, ones that add no meaningful
// bits (because the value would be the same if they were removed).
while (
byteLength > 1 &&
result[byteLength - 1] === signByte &&
(!signed || result[byteLength - 2] >> 7 === signBit)
) {
byteLength--;
}
result = bufs.resize(result, byteLength);
return { value: result, nextIndex: index };
}
|
javascript
|
function decodeBufferCommon(encodedBuffer, index, signed) {
index = index === undefined ? 0 : index;
let length = encodedLength(encodedBuffer, index);
const bitLength = length * 7;
let byteLength = Math.ceil(bitLength / 8);
let result = bufs.alloc(byteLength);
let outIndex = 0;
while (length > 0) {
bits.inject(result, outIndex, 7, encodedBuffer[index]);
outIndex += 7;
index++;
length--;
}
let signBit;
let signByte;
if (signed) {
// Sign-extend the last byte.
let lastByte = result[byteLength - 1];
const endBit = outIndex % 8;
if (endBit !== 0) {
const shift = 32 - endBit; // 32 because JS bit ops work on 32-bit ints.
lastByte = result[byteLength - 1] = ((lastByte << shift) >> shift) & 0xff;
}
signBit = lastByte >> 7;
signByte = signBit * 0xff;
} else {
signBit = 0;
signByte = 0;
}
// Slice off any superfluous bytes, that is, ones that add no meaningful
// bits (because the value would be the same if they were removed).
while (
byteLength > 1 &&
result[byteLength - 1] === signByte &&
(!signed || result[byteLength - 2] >> 7 === signBit)
) {
byteLength--;
}
result = bufs.resize(result, byteLength);
return { value: result, nextIndex: index };
}
|
[
"function",
"decodeBufferCommon",
"(",
"encodedBuffer",
",",
"index",
",",
"signed",
")",
"{",
"index",
"=",
"index",
"===",
"undefined",
"?",
"0",
":",
"index",
";",
"let",
"length",
"=",
"encodedLength",
"(",
"encodedBuffer",
",",
"index",
")",
";",
"const",
"bitLength",
"=",
"length",
"*",
"7",
";",
"let",
"byteLength",
"=",
"Math",
".",
"ceil",
"(",
"bitLength",
"/",
"8",
")",
";",
"let",
"result",
"=",
"bufs",
".",
"alloc",
"(",
"byteLength",
")",
";",
"let",
"outIndex",
"=",
"0",
";",
"while",
"(",
"length",
">",
"0",
")",
"{",
"bits",
".",
"inject",
"(",
"result",
",",
"outIndex",
",",
"7",
",",
"encodedBuffer",
"[",
"index",
"]",
")",
";",
"outIndex",
"+=",
"7",
";",
"index",
"++",
";",
"length",
"--",
";",
"}",
"let",
"signBit",
";",
"let",
"signByte",
";",
"if",
"(",
"signed",
")",
"{",
"// Sign-extend the last byte.",
"let",
"lastByte",
"=",
"result",
"[",
"byteLength",
"-",
"1",
"]",
";",
"const",
"endBit",
"=",
"outIndex",
"%",
"8",
";",
"if",
"(",
"endBit",
"!==",
"0",
")",
"{",
"const",
"shift",
"=",
"32",
"-",
"endBit",
";",
"// 32 because JS bit ops work on 32-bit ints.",
"lastByte",
"=",
"result",
"[",
"byteLength",
"-",
"1",
"]",
"=",
"(",
"(",
"lastByte",
"<<",
"shift",
")",
">>",
"shift",
")",
"&",
"0xff",
";",
"}",
"signBit",
"=",
"lastByte",
">>",
"7",
";",
"signByte",
"=",
"signBit",
"*",
"0xff",
";",
"}",
"else",
"{",
"signBit",
"=",
"0",
";",
"signByte",
"=",
"0",
";",
"}",
"// Slice off any superfluous bytes, that is, ones that add no meaningful",
"// bits (because the value would be the same if they were removed).",
"while",
"(",
"byteLength",
">",
"1",
"&&",
"result",
"[",
"byteLength",
"-",
"1",
"]",
"===",
"signByte",
"&&",
"(",
"!",
"signed",
"||",
"result",
"[",
"byteLength",
"-",
"2",
"]",
">>",
"7",
"===",
"signBit",
")",
")",
"{",
"byteLength",
"--",
";",
"}",
"result",
"=",
"bufs",
".",
"resize",
"(",
"result",
",",
"byteLength",
")",
";",
"return",
"{",
"value",
":",
"result",
",",
"nextIndex",
":",
"index",
"}",
";",
"}"
] |
Common decoder for both signed and unsigned ints. This takes an
LEB128-encoded buffer, returning a bigint-ish buffer.
|
[
"Common",
"decoder",
"for",
"both",
"signed",
"and",
"unsigned",
"ints",
".",
"This",
"takes",
"an",
"LEB128",
"-",
"encoded",
"buffer",
"returning",
"a",
"bigint",
"-",
"ish",
"buffer",
"."
] |
32996b42072073f270adc178ce542da1ae9e9704
|
https://github.com/xtuc/webassemblyjs/blob/32996b42072073f270adc178ce542da1ae9e9704/packages/leb128/src/leb.js#L146-L192
|
17,346
|
expressjs/vhost
|
index.js
|
vhost
|
function vhost (hostname, handle) {
if (!hostname) {
throw new TypeError('argument hostname is required')
}
if (!handle) {
throw new TypeError('argument handle is required')
}
if (typeof handle !== 'function') {
throw new TypeError('argument handle must be a function')
}
// create regular expression for hostname
var regexp = hostregexp(hostname)
return function vhost (req, res, next) {
var vhostdata = vhostof(req, regexp)
if (!vhostdata) {
return next()
}
// populate
req.vhost = vhostdata
// handle
handle(req, res, next)
}
}
|
javascript
|
function vhost (hostname, handle) {
if (!hostname) {
throw new TypeError('argument hostname is required')
}
if (!handle) {
throw new TypeError('argument handle is required')
}
if (typeof handle !== 'function') {
throw new TypeError('argument handle must be a function')
}
// create regular expression for hostname
var regexp = hostregexp(hostname)
return function vhost (req, res, next) {
var vhostdata = vhostof(req, regexp)
if (!vhostdata) {
return next()
}
// populate
req.vhost = vhostdata
// handle
handle(req, res, next)
}
}
|
[
"function",
"vhost",
"(",
"hostname",
",",
"handle",
")",
"{",
"if",
"(",
"!",
"hostname",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'argument hostname is required'",
")",
"}",
"if",
"(",
"!",
"handle",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'argument handle is required'",
")",
"}",
"if",
"(",
"typeof",
"handle",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'argument handle must be a function'",
")",
"}",
"// create regular expression for hostname",
"var",
"regexp",
"=",
"hostregexp",
"(",
"hostname",
")",
"return",
"function",
"vhost",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"vhostdata",
"=",
"vhostof",
"(",
"req",
",",
"regexp",
")",
"if",
"(",
"!",
"vhostdata",
")",
"{",
"return",
"next",
"(",
")",
"}",
"// populate",
"req",
".",
"vhost",
"=",
"vhostdata",
"// handle",
"handle",
"(",
"req",
",",
"res",
",",
"next",
")",
"}",
"}"
] |
Create a vhost middleware.
@param {string|RegExp} hostname
@param {function} handle
@return {Function}
@public
|
[
"Create",
"a",
"vhost",
"middleware",
"."
] |
1ba557c2e1772ba4b0afe2b7355ff0ec050eff80
|
https://github.com/expressjs/vhost/blob/1ba557c2e1772ba4b0afe2b7355ff0ec050eff80/index.js#L37-L66
|
17,347
|
expressjs/vhost
|
index.js
|
hostnameof
|
function hostnameof (req) {
var host = req.headers.host
if (!host) {
return
}
var offset = host[0] === '['
? host.indexOf(']') + 1
: 0
var index = host.indexOf(':', offset)
return index !== -1
? host.substring(0, index)
: host
}
|
javascript
|
function hostnameof (req) {
var host = req.headers.host
if (!host) {
return
}
var offset = host[0] === '['
? host.indexOf(']') + 1
: 0
var index = host.indexOf(':', offset)
return index !== -1
? host.substring(0, index)
: host
}
|
[
"function",
"hostnameof",
"(",
"req",
")",
"{",
"var",
"host",
"=",
"req",
".",
"headers",
".",
"host",
"if",
"(",
"!",
"host",
")",
"{",
"return",
"}",
"var",
"offset",
"=",
"host",
"[",
"0",
"]",
"===",
"'['",
"?",
"host",
".",
"indexOf",
"(",
"']'",
")",
"+",
"1",
":",
"0",
"var",
"index",
"=",
"host",
".",
"indexOf",
"(",
"':'",
",",
"offset",
")",
"return",
"index",
"!==",
"-",
"1",
"?",
"host",
".",
"substring",
"(",
"0",
",",
"index",
")",
":",
"host",
"}"
] |
Get hostname of request.
@param (object} req
@return {string}
@private
|
[
"Get",
"hostname",
"of",
"request",
"."
] |
1ba557c2e1772ba4b0afe2b7355ff0ec050eff80
|
https://github.com/expressjs/vhost/blob/1ba557c2e1772ba4b0afe2b7355ff0ec050eff80/index.js#L76-L91
|
17,348
|
expressjs/vhost
|
index.js
|
hostregexp
|
function hostregexp (val) {
var source = !isregexp(val)
? String(val).replace(ESCAPE_REGEXP, ESCAPE_REPLACE).replace(ASTERISK_REGEXP, ASTERISK_REPLACE)
: val.source
// force leading anchor matching
if (source[0] !== '^') {
source = '^' + source
}
// force trailing anchor matching
if (!END_ANCHORED_REGEXP.test(source)) {
source += '$'
}
return new RegExp(source, 'i')
}
|
javascript
|
function hostregexp (val) {
var source = !isregexp(val)
? String(val).replace(ESCAPE_REGEXP, ESCAPE_REPLACE).replace(ASTERISK_REGEXP, ASTERISK_REPLACE)
: val.source
// force leading anchor matching
if (source[0] !== '^') {
source = '^' + source
}
// force trailing anchor matching
if (!END_ANCHORED_REGEXP.test(source)) {
source += '$'
}
return new RegExp(source, 'i')
}
|
[
"function",
"hostregexp",
"(",
"val",
")",
"{",
"var",
"source",
"=",
"!",
"isregexp",
"(",
"val",
")",
"?",
"String",
"(",
"val",
")",
".",
"replace",
"(",
"ESCAPE_REGEXP",
",",
"ESCAPE_REPLACE",
")",
".",
"replace",
"(",
"ASTERISK_REGEXP",
",",
"ASTERISK_REPLACE",
")",
":",
"val",
".",
"source",
"// force leading anchor matching",
"if",
"(",
"source",
"[",
"0",
"]",
"!==",
"'^'",
")",
"{",
"source",
"=",
"'^'",
"+",
"source",
"}",
"// force trailing anchor matching",
"if",
"(",
"!",
"END_ANCHORED_REGEXP",
".",
"test",
"(",
"source",
")",
")",
"{",
"source",
"+=",
"'$'",
"}",
"return",
"new",
"RegExp",
"(",
"source",
",",
"'i'",
")",
"}"
] |
Generate RegExp for given hostname value.
@param (string|RegExp} val
@private
|
[
"Generate",
"RegExp",
"for",
"given",
"hostname",
"value",
"."
] |
1ba557c2e1772ba4b0afe2b7355ff0ec050eff80
|
https://github.com/expressjs/vhost/blob/1ba557c2e1772ba4b0afe2b7355ff0ec050eff80/index.js#L112-L128
|
17,349
|
expressjs/vhost
|
index.js
|
vhostof
|
function vhostof (req, regexp) {
var host = req.headers.host
var hostname = hostnameof(req)
if (!hostname) {
return
}
var match = regexp.exec(hostname)
if (!match) {
return
}
var obj = Object.create(null)
obj.host = host
obj.hostname = hostname
obj.length = match.length - 1
for (var i = 1; i < match.length; i++) {
obj[i - 1] = match[i]
}
return obj
}
|
javascript
|
function vhostof (req, regexp) {
var host = req.headers.host
var hostname = hostnameof(req)
if (!hostname) {
return
}
var match = regexp.exec(hostname)
if (!match) {
return
}
var obj = Object.create(null)
obj.host = host
obj.hostname = hostname
obj.length = match.length - 1
for (var i = 1; i < match.length; i++) {
obj[i - 1] = match[i]
}
return obj
}
|
[
"function",
"vhostof",
"(",
"req",
",",
"regexp",
")",
"{",
"var",
"host",
"=",
"req",
".",
"headers",
".",
"host",
"var",
"hostname",
"=",
"hostnameof",
"(",
"req",
")",
"if",
"(",
"!",
"hostname",
")",
"{",
"return",
"}",
"var",
"match",
"=",
"regexp",
".",
"exec",
"(",
"hostname",
")",
"if",
"(",
"!",
"match",
")",
"{",
"return",
"}",
"var",
"obj",
"=",
"Object",
".",
"create",
"(",
"null",
")",
"obj",
".",
"host",
"=",
"host",
"obj",
".",
"hostname",
"=",
"hostname",
"obj",
".",
"length",
"=",
"match",
".",
"length",
"-",
"1",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"match",
".",
"length",
";",
"i",
"++",
")",
"{",
"obj",
"[",
"i",
"-",
"1",
"]",
"=",
"match",
"[",
"i",
"]",
"}",
"return",
"obj",
"}"
] |
Get the vhost data of the request for RegExp
@param (object} req
@param (RegExp} regexp
@return {object}
@private
|
[
"Get",
"the",
"vhost",
"data",
"of",
"the",
"request",
"for",
"RegExp"
] |
1ba557c2e1772ba4b0afe2b7355ff0ec050eff80
|
https://github.com/expressjs/vhost/blob/1ba557c2e1772ba4b0afe2b7355ff0ec050eff80/index.js#L139-L164
|
17,350
|
sheerun/graphqlviz
|
index.js
|
analyzeField
|
function analyzeField (field) {
var obj = {}
var namedType = field.type
obj.name = field.name
obj.isDeprecated = field.isDeprecated
obj.deprecationReason = field.deprecationReason
obj.defaultValue = field.defaultValue
if (namedType.kind === 'NON_NULL') {
obj.isRequired = true
namedType = namedType.ofType
} else {
obj.isRequired = false
}
if (namedType.kind === 'LIST') {
obj.isList = true
namedType = namedType.ofType
} else {
obj.isList = field.type.kind === 'LIST'
}
if (namedType.kind === 'NON_NULL') {
obj.isNestedRequired = true
namedType = namedType.ofType
} else {
obj.isNestedRequired = false
}
obj.type = namedType.name
obj.isUnionType = namedType.kind === 'UNION'
obj.isObjectType = namedType.kind === 'OBJECT'
obj.isEnumType = namedType.kind === 'ENUM'
obj.isInterfaceType = namedType.kind === 'INTERFACE'
obj.isInputType = namedType.kind === 'INPUT_OBJECT'
return obj
}
|
javascript
|
function analyzeField (field) {
var obj = {}
var namedType = field.type
obj.name = field.name
obj.isDeprecated = field.isDeprecated
obj.deprecationReason = field.deprecationReason
obj.defaultValue = field.defaultValue
if (namedType.kind === 'NON_NULL') {
obj.isRequired = true
namedType = namedType.ofType
} else {
obj.isRequired = false
}
if (namedType.kind === 'LIST') {
obj.isList = true
namedType = namedType.ofType
} else {
obj.isList = field.type.kind === 'LIST'
}
if (namedType.kind === 'NON_NULL') {
obj.isNestedRequired = true
namedType = namedType.ofType
} else {
obj.isNestedRequired = false
}
obj.type = namedType.name
obj.isUnionType = namedType.kind === 'UNION'
obj.isObjectType = namedType.kind === 'OBJECT'
obj.isEnumType = namedType.kind === 'ENUM'
obj.isInterfaceType = namedType.kind === 'INTERFACE'
obj.isInputType = namedType.kind === 'INPUT_OBJECT'
return obj
}
|
[
"function",
"analyzeField",
"(",
"field",
")",
"{",
"var",
"obj",
"=",
"{",
"}",
"var",
"namedType",
"=",
"field",
".",
"type",
"obj",
".",
"name",
"=",
"field",
".",
"name",
"obj",
".",
"isDeprecated",
"=",
"field",
".",
"isDeprecated",
"obj",
".",
"deprecationReason",
"=",
"field",
".",
"deprecationReason",
"obj",
".",
"defaultValue",
"=",
"field",
".",
"defaultValue",
"if",
"(",
"namedType",
".",
"kind",
"===",
"'NON_NULL'",
")",
"{",
"obj",
".",
"isRequired",
"=",
"true",
"namedType",
"=",
"namedType",
".",
"ofType",
"}",
"else",
"{",
"obj",
".",
"isRequired",
"=",
"false",
"}",
"if",
"(",
"namedType",
".",
"kind",
"===",
"'LIST'",
")",
"{",
"obj",
".",
"isList",
"=",
"true",
"namedType",
"=",
"namedType",
".",
"ofType",
"}",
"else",
"{",
"obj",
".",
"isList",
"=",
"field",
".",
"type",
".",
"kind",
"===",
"'LIST'",
"}",
"if",
"(",
"namedType",
".",
"kind",
"===",
"'NON_NULL'",
")",
"{",
"obj",
".",
"isNestedRequired",
"=",
"true",
"namedType",
"=",
"namedType",
".",
"ofType",
"}",
"else",
"{",
"obj",
".",
"isNestedRequired",
"=",
"false",
"}",
"obj",
".",
"type",
"=",
"namedType",
".",
"name",
"obj",
".",
"isUnionType",
"=",
"namedType",
".",
"kind",
"===",
"'UNION'",
"obj",
".",
"isObjectType",
"=",
"namedType",
".",
"kind",
"===",
"'OBJECT'",
"obj",
".",
"isEnumType",
"=",
"namedType",
".",
"kind",
"===",
"'ENUM'",
"obj",
".",
"isInterfaceType",
"=",
"namedType",
".",
"kind",
"===",
"'INTERFACE'",
"obj",
".",
"isInputType",
"=",
"namedType",
".",
"kind",
"===",
"'INPUT_OBJECT'",
"return",
"obj",
"}"
] |
analyzes a field and returns a simplified object
|
[
"analyzes",
"a",
"field",
"and",
"returns",
"a",
"simplified",
"object"
] |
976d12bc3965e487a91892f278194599e51974d8
|
https://github.com/sheerun/graphqlviz/blob/976d12bc3965e487a91892f278194599e51974d8/index.js#L70-L102
|
17,351
|
sheerun/graphqlviz
|
index.js
|
processType
|
function processType (item, entities, types) {
var type = _.find(types, { name: item })
var additionalTypes = []
// get the type names of the union or interface's possible types, given its type name
var addPossibleTypes = typeName => {
var union = _.find(types, { name: typeName })
var possibleTypes = _.map(union.possibleTypes, 'name')
// we must also process the union/interface type, as well as its possible types
additionalTypes = _.union(additionalTypes, possibleTypes, [typeName])
}
var fields = _.map(type.fields, field => {
var obj = analyzeField.call(this, field)
if (
(obj.isUnionType && !this.theme.unions.hide) ||
(obj.isInterfaceType && !this.theme.interfaces.hide)
) {
addPossibleTypes(obj.type)
}
// process args
if (!this.theme.field.noargs) {
if (field.args && field.args.length) {
obj.args = _.map(field.args, analyzeField.bind(this))
}
}
return obj
})
entities[type.name] = {
name: type.name,
fields: fields,
isObjectType: true,
isInterfaceType: type.kind === 'INTERFACE',
isUnionType: type.kind === 'UNION',
possibleTypes: _.map(type.possibleTypes, 'name')
}
var linkeditems = _.chain(fields)
.filter('isObjectType')
.map('type')
.union(additionalTypes)
.uniq()
.value()
return linkeditems
}
|
javascript
|
function processType (item, entities, types) {
var type = _.find(types, { name: item })
var additionalTypes = []
// get the type names of the union or interface's possible types, given its type name
var addPossibleTypes = typeName => {
var union = _.find(types, { name: typeName })
var possibleTypes = _.map(union.possibleTypes, 'name')
// we must also process the union/interface type, as well as its possible types
additionalTypes = _.union(additionalTypes, possibleTypes, [typeName])
}
var fields = _.map(type.fields, field => {
var obj = analyzeField.call(this, field)
if (
(obj.isUnionType && !this.theme.unions.hide) ||
(obj.isInterfaceType && !this.theme.interfaces.hide)
) {
addPossibleTypes(obj.type)
}
// process args
if (!this.theme.field.noargs) {
if (field.args && field.args.length) {
obj.args = _.map(field.args, analyzeField.bind(this))
}
}
return obj
})
entities[type.name] = {
name: type.name,
fields: fields,
isObjectType: true,
isInterfaceType: type.kind === 'INTERFACE',
isUnionType: type.kind === 'UNION',
possibleTypes: _.map(type.possibleTypes, 'name')
}
var linkeditems = _.chain(fields)
.filter('isObjectType')
.map('type')
.union(additionalTypes)
.uniq()
.value()
return linkeditems
}
|
[
"function",
"processType",
"(",
"item",
",",
"entities",
",",
"types",
")",
"{",
"var",
"type",
"=",
"_",
".",
"find",
"(",
"types",
",",
"{",
"name",
":",
"item",
"}",
")",
"var",
"additionalTypes",
"=",
"[",
"]",
"// get the type names of the union or interface's possible types, given its type name",
"var",
"addPossibleTypes",
"=",
"typeName",
"=>",
"{",
"var",
"union",
"=",
"_",
".",
"find",
"(",
"types",
",",
"{",
"name",
":",
"typeName",
"}",
")",
"var",
"possibleTypes",
"=",
"_",
".",
"map",
"(",
"union",
".",
"possibleTypes",
",",
"'name'",
")",
"// we must also process the union/interface type, as well as its possible types",
"additionalTypes",
"=",
"_",
".",
"union",
"(",
"additionalTypes",
",",
"possibleTypes",
",",
"[",
"typeName",
"]",
")",
"}",
"var",
"fields",
"=",
"_",
".",
"map",
"(",
"type",
".",
"fields",
",",
"field",
"=>",
"{",
"var",
"obj",
"=",
"analyzeField",
".",
"call",
"(",
"this",
",",
"field",
")",
"if",
"(",
"(",
"obj",
".",
"isUnionType",
"&&",
"!",
"this",
".",
"theme",
".",
"unions",
".",
"hide",
")",
"||",
"(",
"obj",
".",
"isInterfaceType",
"&&",
"!",
"this",
".",
"theme",
".",
"interfaces",
".",
"hide",
")",
")",
"{",
"addPossibleTypes",
"(",
"obj",
".",
"type",
")",
"}",
"// process args",
"if",
"(",
"!",
"this",
".",
"theme",
".",
"field",
".",
"noargs",
")",
"{",
"if",
"(",
"field",
".",
"args",
"&&",
"field",
".",
"args",
".",
"length",
")",
"{",
"obj",
".",
"args",
"=",
"_",
".",
"map",
"(",
"field",
".",
"args",
",",
"analyzeField",
".",
"bind",
"(",
"this",
")",
")",
"}",
"}",
"return",
"obj",
"}",
")",
"entities",
"[",
"type",
".",
"name",
"]",
"=",
"{",
"name",
":",
"type",
".",
"name",
",",
"fields",
":",
"fields",
",",
"isObjectType",
":",
"true",
",",
"isInterfaceType",
":",
"type",
".",
"kind",
"===",
"'INTERFACE'",
",",
"isUnionType",
":",
"type",
".",
"kind",
"===",
"'UNION'",
",",
"possibleTypes",
":",
"_",
".",
"map",
"(",
"type",
".",
"possibleTypes",
",",
"'name'",
")",
"}",
"var",
"linkeditems",
"=",
"_",
".",
"chain",
"(",
"fields",
")",
".",
"filter",
"(",
"'isObjectType'",
")",
".",
"map",
"(",
"'type'",
")",
".",
"union",
"(",
"additionalTypes",
")",
".",
"uniq",
"(",
")",
".",
"value",
"(",
")",
"return",
"linkeditems",
"}"
] |
process a graphql type object returns simplified version of the type
|
[
"process",
"a",
"graphql",
"type",
"object",
"returns",
"simplified",
"version",
"of",
"the",
"type"
] |
976d12bc3965e487a91892f278194599e51974d8
|
https://github.com/sheerun/graphqlviz/blob/976d12bc3965e487a91892f278194599e51974d8/index.js#L106-L156
|
17,352
|
sheerun/graphqlviz
|
index.js
|
walkBFS
|
function walkBFS (obj, iter) {
var q = _.map(_.keys(obj), k => {
return { key: k, path: '["' + k + '"]' }
})
var current
var currentNode
var retval
var push = (v, k) => {
q.push({ key: k, path: current.path + '["' + k + '"]' })
}
while (q.length) {
current = q.shift()
currentNode = _.get(obj, current.path)
retval = iter(currentNode, current.key, current.path)
if (retval) {
return retval
}
if (_.isPlainObject(currentNode) || _.isArray(currentNode)) {
_.each(currentNode, push)
}
}
}
|
javascript
|
function walkBFS (obj, iter) {
var q = _.map(_.keys(obj), k => {
return { key: k, path: '["' + k + '"]' }
})
var current
var currentNode
var retval
var push = (v, k) => {
q.push({ key: k, path: current.path + '["' + k + '"]' })
}
while (q.length) {
current = q.shift()
currentNode = _.get(obj, current.path)
retval = iter(currentNode, current.key, current.path)
if (retval) {
return retval
}
if (_.isPlainObject(currentNode) || _.isArray(currentNode)) {
_.each(currentNode, push)
}
}
}
|
[
"function",
"walkBFS",
"(",
"obj",
",",
"iter",
")",
"{",
"var",
"q",
"=",
"_",
".",
"map",
"(",
"_",
".",
"keys",
"(",
"obj",
")",
",",
"k",
"=>",
"{",
"return",
"{",
"key",
":",
"k",
",",
"path",
":",
"'[\"'",
"+",
"k",
"+",
"'\"]'",
"}",
"}",
")",
"var",
"current",
"var",
"currentNode",
"var",
"retval",
"var",
"push",
"=",
"(",
"v",
",",
"k",
")",
"=>",
"{",
"q",
".",
"push",
"(",
"{",
"key",
":",
"k",
",",
"path",
":",
"current",
".",
"path",
"+",
"'[\"'",
"+",
"k",
"+",
"'\"]'",
"}",
")",
"}",
"while",
"(",
"q",
".",
"length",
")",
"{",
"current",
"=",
"q",
".",
"shift",
"(",
")",
"currentNode",
"=",
"_",
".",
"get",
"(",
"obj",
",",
"current",
".",
"path",
")",
"retval",
"=",
"iter",
"(",
"currentNode",
",",
"current",
".",
"key",
",",
"current",
".",
"path",
")",
"if",
"(",
"retval",
")",
"{",
"return",
"retval",
"}",
"if",
"(",
"_",
".",
"isPlainObject",
"(",
"currentNode",
")",
"||",
"_",
".",
"isArray",
"(",
"currentNode",
")",
")",
"{",
"_",
".",
"each",
"(",
"currentNode",
",",
"push",
")",
"}",
"}",
"}"
] |
walks the object in level-order invokes iter at each node if iter returns truthy, breaks & returns the value assumes no cycles
|
[
"walks",
"the",
"object",
"in",
"level",
"-",
"order",
"invokes",
"iter",
"at",
"each",
"node",
"if",
"iter",
"returns",
"truthy",
"breaks",
"&",
"returns",
"the",
"value",
"assumes",
"no",
"cycles"
] |
976d12bc3965e487a91892f278194599e51974d8
|
https://github.com/sheerun/graphqlviz/blob/976d12bc3965e487a91892f278194599e51974d8/index.js#L188-L211
|
17,353
|
sheerun/graphqlviz
|
index.js
|
isEnabled
|
function isEnabled (obj) {
var enabled = false
if (obj.isEnumType) {
enabled = !this.theme.enums.hide
} else if (obj.isInputType) {
enabled = !this.theme.inputs.hide
} else if (obj.isInterfaceType) {
enabled = !this.theme.interfaces.hide
} else if (obj.isUnionType) {
enabled = !this.theme.unions.hide
} else {
enabled = true
}
return enabled
}
|
javascript
|
function isEnabled (obj) {
var enabled = false
if (obj.isEnumType) {
enabled = !this.theme.enums.hide
} else if (obj.isInputType) {
enabled = !this.theme.inputs.hide
} else if (obj.isInterfaceType) {
enabled = !this.theme.interfaces.hide
} else if (obj.isUnionType) {
enabled = !this.theme.unions.hide
} else {
enabled = true
}
return enabled
}
|
[
"function",
"isEnabled",
"(",
"obj",
")",
"{",
"var",
"enabled",
"=",
"false",
"if",
"(",
"obj",
".",
"isEnumType",
")",
"{",
"enabled",
"=",
"!",
"this",
".",
"theme",
".",
"enums",
".",
"hide",
"}",
"else",
"if",
"(",
"obj",
".",
"isInputType",
")",
"{",
"enabled",
"=",
"!",
"this",
".",
"theme",
".",
"inputs",
".",
"hide",
"}",
"else",
"if",
"(",
"obj",
".",
"isInterfaceType",
")",
"{",
"enabled",
"=",
"!",
"this",
".",
"theme",
".",
"interfaces",
".",
"hide",
"}",
"else",
"if",
"(",
"obj",
".",
"isUnionType",
")",
"{",
"enabled",
"=",
"!",
"this",
".",
"theme",
".",
"unions",
".",
"hide",
"}",
"else",
"{",
"enabled",
"=",
"true",
"}",
"return",
"enabled",
"}"
] |
get if the object type is enabled
|
[
"get",
"if",
"the",
"object",
"type",
"is",
"enabled"
] |
976d12bc3965e487a91892f278194599e51974d8
|
https://github.com/sheerun/graphqlviz/blob/976d12bc3965e487a91892f278194599e51974d8/index.js#L263-L277
|
17,354
|
sheerun/graphqlviz
|
index.js
|
getColor
|
function getColor (obj) {
var color = this.theme.types.color
if (obj.isEnumType && !this.theme.enums.hide) {
color = this.theme.enums.color
} else if (obj.isInputType && !this.theme.inputs.hide) {
color = this.theme.inputs.color
} else if (obj.isInterfaceType && !this.theme.interfaces.hide) {
color = this.theme.interfaces.color
} else if (obj.isUnionType && !this.theme.unions.hide) {
color = this.theme.unions.color
}
return color
}
|
javascript
|
function getColor (obj) {
var color = this.theme.types.color
if (obj.isEnumType && !this.theme.enums.hide) {
color = this.theme.enums.color
} else if (obj.isInputType && !this.theme.inputs.hide) {
color = this.theme.inputs.color
} else if (obj.isInterfaceType && !this.theme.interfaces.hide) {
color = this.theme.interfaces.color
} else if (obj.isUnionType && !this.theme.unions.hide) {
color = this.theme.unions.color
}
return color
}
|
[
"function",
"getColor",
"(",
"obj",
")",
"{",
"var",
"color",
"=",
"this",
".",
"theme",
".",
"types",
".",
"color",
"if",
"(",
"obj",
".",
"isEnumType",
"&&",
"!",
"this",
".",
"theme",
".",
"enums",
".",
"hide",
")",
"{",
"color",
"=",
"this",
".",
"theme",
".",
"enums",
".",
"color",
"}",
"else",
"if",
"(",
"obj",
".",
"isInputType",
"&&",
"!",
"this",
".",
"theme",
".",
"inputs",
".",
"hide",
")",
"{",
"color",
"=",
"this",
".",
"theme",
".",
"inputs",
".",
"color",
"}",
"else",
"if",
"(",
"obj",
".",
"isInterfaceType",
"&&",
"!",
"this",
".",
"theme",
".",
"interfaces",
".",
"hide",
")",
"{",
"color",
"=",
"this",
".",
"theme",
".",
"interfaces",
".",
"color",
"}",
"else",
"if",
"(",
"obj",
".",
"isUnionType",
"&&",
"!",
"this",
".",
"theme",
".",
"unions",
".",
"hide",
")",
"{",
"color",
"=",
"this",
".",
"theme",
".",
"unions",
".",
"color",
"}",
"return",
"color",
"}"
] |
get the color for the given field
|
[
"get",
"the",
"color",
"for",
"the",
"given",
"field"
] |
976d12bc3965e487a91892f278194599e51974d8
|
https://github.com/sheerun/graphqlviz/blob/976d12bc3965e487a91892f278194599e51974d8/index.js#L280-L292
|
17,355
|
sheerun/graphqlviz
|
index.js
|
createTable
|
function createTable (context) {
var result = '"' + context.typeName + '" '
result +=
'[label=<<TABLE COLOR="' +
context.color +
'" BORDER="0" CELLBORDER="1" CELLSPACING="0">'
result +=
'<TR><TD PORT="__title"' +
(this.theme.header.invert ? ' BGCOLOR="' + context.color + '"' : '') +
'><FONT COLOR="' +
(this.theme.header.invert ? 'WHITE' : context.color) +
'">' +
(_.isEmpty(context.stereotype) || context.stereotype === 'null'
? ''
: '«' + context.stereotype + '»<BR/>') +
'<B>' +
context.typeName +
'</B></FONT></TD></TR>'
if (context.rows.length) {
if (this.theme.field.hideSeperators) {
result +=
'<TR><TD><TABLE COLOR="' +
context.color +
'" BORDER="0" CELLBORDER="0" CELLSPACING="0">'
}
result += context.rows.map(row => {
return (
'<TR><TD ALIGN="' +
this.theme.field.align +
'" PORT="' +
row.port +
'"><FONT COLOR="' +
context.color +
'">' +
row.text +
'</FONT></TD></TR>'
)
})
if (this.theme.field.hideSeperators) {
result += '</TABLE></TD></TR>'
}
}
result += '</TABLE>>];'
return result
}
|
javascript
|
function createTable (context) {
var result = '"' + context.typeName + '" '
result +=
'[label=<<TABLE COLOR="' +
context.color +
'" BORDER="0" CELLBORDER="1" CELLSPACING="0">'
result +=
'<TR><TD PORT="__title"' +
(this.theme.header.invert ? ' BGCOLOR="' + context.color + '"' : '') +
'><FONT COLOR="' +
(this.theme.header.invert ? 'WHITE' : context.color) +
'">' +
(_.isEmpty(context.stereotype) || context.stereotype === 'null'
? ''
: '«' + context.stereotype + '»<BR/>') +
'<B>' +
context.typeName +
'</B></FONT></TD></TR>'
if (context.rows.length) {
if (this.theme.field.hideSeperators) {
result +=
'<TR><TD><TABLE COLOR="' +
context.color +
'" BORDER="0" CELLBORDER="0" CELLSPACING="0">'
}
result += context.rows.map(row => {
return (
'<TR><TD ALIGN="' +
this.theme.field.align +
'" PORT="' +
row.port +
'"><FONT COLOR="' +
context.color +
'">' +
row.text +
'</FONT></TD></TR>'
)
})
if (this.theme.field.hideSeperators) {
result += '</TABLE></TD></TR>'
}
}
result += '</TABLE>>];'
return result
}
|
[
"function",
"createTable",
"(",
"context",
")",
"{",
"var",
"result",
"=",
"'\"'",
"+",
"context",
".",
"typeName",
"+",
"'\" '",
"result",
"+=",
"'[label=<<TABLE COLOR=\"'",
"+",
"context",
".",
"color",
"+",
"'\" BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\">'",
"result",
"+=",
"'<TR><TD PORT=\"__title\"'",
"+",
"(",
"this",
".",
"theme",
".",
"header",
".",
"invert",
"?",
"' BGCOLOR=\"'",
"+",
"context",
".",
"color",
"+",
"'\"'",
":",
"''",
")",
"+",
"'><FONT COLOR=\"'",
"+",
"(",
"this",
".",
"theme",
".",
"header",
".",
"invert",
"?",
"'WHITE'",
":",
"context",
".",
"color",
")",
"+",
"'\">'",
"+",
"(",
"_",
".",
"isEmpty",
"(",
"context",
".",
"stereotype",
")",
"||",
"context",
".",
"stereotype",
"===",
"'null'",
"?",
"''",
":",
"'«'",
"+",
"context",
".",
"stereotype",
"+",
"'»<BR/>'",
")",
"+",
"'<B>'",
"+",
"context",
".",
"typeName",
"+",
"'</B></FONT></TD></TR>'",
"if",
"(",
"context",
".",
"rows",
".",
"length",
")",
"{",
"if",
"(",
"this",
".",
"theme",
".",
"field",
".",
"hideSeperators",
")",
"{",
"result",
"+=",
"'<TR><TD><TABLE COLOR=\"'",
"+",
"context",
".",
"color",
"+",
"'\" BORDER=\"0\" CELLBORDER=\"0\" CELLSPACING=\"0\">'",
"}",
"result",
"+=",
"context",
".",
"rows",
".",
"map",
"(",
"row",
"=>",
"{",
"return",
"(",
"'<TR><TD ALIGN=\"'",
"+",
"this",
".",
"theme",
".",
"field",
".",
"align",
"+",
"'\" PORT=\"'",
"+",
"row",
".",
"port",
"+",
"'\"><FONT COLOR=\"'",
"+",
"context",
".",
"color",
"+",
"'\">'",
"+",
"row",
".",
"text",
"+",
"'</FONT></TD></TR>'",
")",
"}",
")",
"if",
"(",
"this",
".",
"theme",
".",
"field",
".",
"hideSeperators",
")",
"{",
"result",
"+=",
"'</TABLE></TD></TR>'",
"}",
"}",
"result",
"+=",
"'</TABLE>>];'",
"return",
"result",
"}"
] |
For the given context, creates a table for the class with the typeName as the header, and rows as the fields
|
[
"For",
"the",
"given",
"context",
"creates",
"a",
"table",
"for",
"the",
"class",
"with",
"the",
"typeName",
"as",
"the",
"header",
"and",
"rows",
"as",
"the",
"fields"
] |
976d12bc3965e487a91892f278194599e51974d8
|
https://github.com/sheerun/graphqlviz/blob/976d12bc3965e487a91892f278194599e51974d8/index.js#L381-L425
|
17,356
|
sheerun/graphqlviz
|
index.js
|
graph
|
function graph (processedTypes, typeTheme) {
var result = ''
if (typeTheme.group) {
result += 'subgraph cluster_' + groupId++ + ' {'
if (typeTheme.color) {
result += 'color=' + typeTheme.color + ';'
}
if (typeTheme.groupLabel) {
result += 'label="' + typeTheme.groupLabel + '";'
}
}
result += _.map(processedTypes, v => {
// sort if desired
if (this.theme.field.sort) {
v.fields = _.sortBy(v.fields, 'name')
}
var rows = _.map(v.fields, v => {
return {
text: createField.call(this, v),
port: v.name + 'port'
}
})
return createTable.call(this, {
typeName: getTypeDisplayName(v.name),
color: typeTheme.color,
stereotype: typeTheme.stereotype,
rows: rows
})
}).join('\n')
if (typeTheme.group) {
result += '}'
}
result += '\n\n'
return result
}
|
javascript
|
function graph (processedTypes, typeTheme) {
var result = ''
if (typeTheme.group) {
result += 'subgraph cluster_' + groupId++ + ' {'
if (typeTheme.color) {
result += 'color=' + typeTheme.color + ';'
}
if (typeTheme.groupLabel) {
result += 'label="' + typeTheme.groupLabel + '";'
}
}
result += _.map(processedTypes, v => {
// sort if desired
if (this.theme.field.sort) {
v.fields = _.sortBy(v.fields, 'name')
}
var rows = _.map(v.fields, v => {
return {
text: createField.call(this, v),
port: v.name + 'port'
}
})
return createTable.call(this, {
typeName: getTypeDisplayName(v.name),
color: typeTheme.color,
stereotype: typeTheme.stereotype,
rows: rows
})
}).join('\n')
if (typeTheme.group) {
result += '}'
}
result += '\n\n'
return result
}
|
[
"function",
"graph",
"(",
"processedTypes",
",",
"typeTheme",
")",
"{",
"var",
"result",
"=",
"''",
"if",
"(",
"typeTheme",
".",
"group",
")",
"{",
"result",
"+=",
"'subgraph cluster_'",
"+",
"groupId",
"++",
"+",
"' {'",
"if",
"(",
"typeTheme",
".",
"color",
")",
"{",
"result",
"+=",
"'color='",
"+",
"typeTheme",
".",
"color",
"+",
"';'",
"}",
"if",
"(",
"typeTheme",
".",
"groupLabel",
")",
"{",
"result",
"+=",
"'label=\"'",
"+",
"typeTheme",
".",
"groupLabel",
"+",
"'\";'",
"}",
"}",
"result",
"+=",
"_",
".",
"map",
"(",
"processedTypes",
",",
"v",
"=>",
"{",
"// sort if desired",
"if",
"(",
"this",
".",
"theme",
".",
"field",
".",
"sort",
")",
"{",
"v",
".",
"fields",
"=",
"_",
".",
"sortBy",
"(",
"v",
".",
"fields",
",",
"'name'",
")",
"}",
"var",
"rows",
"=",
"_",
".",
"map",
"(",
"v",
".",
"fields",
",",
"v",
"=>",
"{",
"return",
"{",
"text",
":",
"createField",
".",
"call",
"(",
"this",
",",
"v",
")",
",",
"port",
":",
"v",
".",
"name",
"+",
"'port'",
"}",
"}",
")",
"return",
"createTable",
".",
"call",
"(",
"this",
",",
"{",
"typeName",
":",
"getTypeDisplayName",
"(",
"v",
".",
"name",
")",
",",
"color",
":",
"typeTheme",
".",
"color",
",",
"stereotype",
":",
"typeTheme",
".",
"stereotype",
",",
"rows",
":",
"rows",
"}",
")",
"}",
")",
".",
"join",
"(",
"'\\n'",
")",
"if",
"(",
"typeTheme",
".",
"group",
")",
"{",
"result",
"+=",
"'}'",
"}",
"result",
"+=",
"'\\n\\n'",
"return",
"result",
"}"
] |
For the provided simplified types, creates all the tables to represent them. Optionally groups the supplied types in a subgraph.
|
[
"For",
"the",
"provided",
"simplified",
"types",
"creates",
"all",
"the",
"tables",
"to",
"represent",
"them",
".",
"Optionally",
"groups",
"the",
"supplied",
"types",
"in",
"a",
"subgraph",
"."
] |
976d12bc3965e487a91892f278194599e51974d8
|
https://github.com/sheerun/graphqlviz/blob/976d12bc3965e487a91892f278194599e51974d8/index.js#L431-L471
|
17,357
|
sheerun/graphqlviz
|
cli.js
|
fatal
|
function fatal (e, text) {
console.error('ERROR processing input. Use --verbose flag to see output.')
console.error(e.message)
if (cli.flags.verbose) {
console.error(text)
}
process.exit(1)
}
|
javascript
|
function fatal (e, text) {
console.error('ERROR processing input. Use --verbose flag to see output.')
console.error(e.message)
if (cli.flags.verbose) {
console.error(text)
}
process.exit(1)
}
|
[
"function",
"fatal",
"(",
"e",
",",
"text",
")",
"{",
"console",
".",
"error",
"(",
"'ERROR processing input. Use --verbose flag to see output.'",
")",
"console",
".",
"error",
"(",
"e",
".",
"message",
")",
"if",
"(",
"cli",
".",
"flags",
".",
"verbose",
")",
"{",
"console",
".",
"error",
"(",
"text",
")",
"}",
"process",
".",
"exit",
"(",
"1",
")",
"}"
] |
logs the error and exits
|
[
"logs",
"the",
"error",
"and",
"exits"
] |
976d12bc3965e487a91892f278194599e51974d8
|
https://github.com/sheerun/graphqlviz/blob/976d12bc3965e487a91892f278194599e51974d8/cli.js#L69-L78
|
17,358
|
sheerun/graphqlviz
|
cli.js
|
introspect
|
function introspect (text) {
return new Promise(function (resolve, reject) {
try {
var astDocument = parse(text)
var schema = buildASTSchema(astDocument)
graphql(schema, graphqlviz.query)
.then(function (data) {
resolve(data)
})
.catch(function (e) {
reject('Fatal error, exiting.')
fatal(e, text)
})
} catch (e) {
reject('Fatal error, exiting.')
fatal(e, text)
}
})
}
|
javascript
|
function introspect (text) {
return new Promise(function (resolve, reject) {
try {
var astDocument = parse(text)
var schema = buildASTSchema(astDocument)
graphql(schema, graphqlviz.query)
.then(function (data) {
resolve(data)
})
.catch(function (e) {
reject('Fatal error, exiting.')
fatal(e, text)
})
} catch (e) {
reject('Fatal error, exiting.')
fatal(e, text)
}
})
}
|
[
"function",
"introspect",
"(",
"text",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"try",
"{",
"var",
"astDocument",
"=",
"parse",
"(",
"text",
")",
"var",
"schema",
"=",
"buildASTSchema",
"(",
"astDocument",
")",
"graphql",
"(",
"schema",
",",
"graphqlviz",
".",
"query",
")",
".",
"then",
"(",
"function",
"(",
"data",
")",
"{",
"resolve",
"(",
"data",
")",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"e",
")",
"{",
"reject",
"(",
"'Fatal error, exiting.'",
")",
"fatal",
"(",
"e",
",",
"text",
")",
"}",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"reject",
"(",
"'Fatal error, exiting.'",
")",
"fatal",
"(",
"e",
",",
"text",
")",
"}",
"}",
")",
"}"
] |
given a "GraphQL schema language" text file, converts into introspection JSON
|
[
"given",
"a",
"GraphQL",
"schema",
"language",
"text",
"file",
"converts",
"into",
"introspection",
"JSON"
] |
976d12bc3965e487a91892f278194599e51974d8
|
https://github.com/sheerun/graphqlviz/blob/976d12bc3965e487a91892f278194599e51974d8/cli.js#L81-L99
|
17,359
|
pillarjs/multiparty
|
index.js
|
function (done) {
if (called) return;
called = true;
// wait for req events to fire
process.nextTick(function() {
if (waitend && req.readable) {
// dump rest of request
req.resume();
req.once('end', done);
return;
}
done();
});
}
|
javascript
|
function (done) {
if (called) return;
called = true;
// wait for req events to fire
process.nextTick(function() {
if (waitend && req.readable) {
// dump rest of request
req.resume();
req.once('end', done);
return;
}
done();
});
}
|
[
"function",
"(",
"done",
")",
"{",
"if",
"(",
"called",
")",
"return",
";",
"called",
"=",
"true",
";",
"// wait for req events to fire",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"waitend",
"&&",
"req",
".",
"readable",
")",
"{",
"// dump rest of request",
"req",
".",
"resume",
"(",
")",
";",
"req",
".",
"once",
"(",
"'end'",
",",
"done",
")",
";",
"return",
";",
"}",
"done",
"(",
")",
";",
"}",
")",
";",
"}"
] |
wait for request to end before calling cb
|
[
"wait",
"for",
"request",
"to",
"end",
"before",
"calling",
"cb"
] |
7034ca123d9db53827bc8c4a058d79db513d0d3d
|
https://github.com/pillarjs/multiparty/blob/7034ca123d9db53827bc8c4a058d79db513d0d3d/index.js#L101-L117
|
|
17,360
|
observing/thor
|
metrics.js
|
Metrics
|
function Metrics(requests) {
this.requests = requests; // The total amount of requests send
this.connections = 0; // Connections established
this.disconnects = 0; // Closed connections
this.failures = 0; // Connections that received an error
this.errors = Object.create(null); // Collection of different errors
this.timing = Object.create(null); // Different timings
this.latency = new Stats(); // Latencies of the echo'd messages
this.handshaking = new Stats(); // Handshake duration
this.read = 0; // Bytes read
this.send = 0; // Bytes send
// Start tracking
this.start();
}
|
javascript
|
function Metrics(requests) {
this.requests = requests; // The total amount of requests send
this.connections = 0; // Connections established
this.disconnects = 0; // Closed connections
this.failures = 0; // Connections that received an error
this.errors = Object.create(null); // Collection of different errors
this.timing = Object.create(null); // Different timings
this.latency = new Stats(); // Latencies of the echo'd messages
this.handshaking = new Stats(); // Handshake duration
this.read = 0; // Bytes read
this.send = 0; // Bytes send
// Start tracking
this.start();
}
|
[
"function",
"Metrics",
"(",
"requests",
")",
"{",
"this",
".",
"requests",
"=",
"requests",
";",
"// The total amount of requests send",
"this",
".",
"connections",
"=",
"0",
";",
"// Connections established",
"this",
".",
"disconnects",
"=",
"0",
";",
"// Closed connections",
"this",
".",
"failures",
"=",
"0",
";",
"// Connections that received an error",
"this",
".",
"errors",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"// Collection of different errors",
"this",
".",
"timing",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"// Different timings",
"this",
".",
"latency",
"=",
"new",
"Stats",
"(",
")",
";",
"// Latencies of the echo'd messages",
"this",
".",
"handshaking",
"=",
"new",
"Stats",
"(",
")",
";",
"// Handshake duration",
"this",
".",
"read",
"=",
"0",
";",
"// Bytes read",
"this",
".",
"send",
"=",
"0",
";",
"// Bytes send",
"// Start tracking",
"this",
".",
"start",
"(",
")",
";",
"}"
] |
Metrics collection and generation.
@constructor
@param {Number} requests The total amount of requests scheduled to be send
|
[
"Metrics",
"collection",
"and",
"generation",
"."
] |
20c51d6c5dcc57a1927ae0c6e77f21836d71f9de
|
https://github.com/observing/thor/blob/20c51d6c5dcc57a1927ae0c6e77f21836d71f9de/metrics.js#L14-L32
|
17,361
|
observing/thor
|
mjolnir.js
|
write
|
function write(socket, task, id, fn) {
session[binary ? 'binary' : 'utf8'](task.size, function message(err, data) {
var start = socket.last = Date.now();
socket.send(data, {
binary: binary,
mask: masked
}, function sending(err) {
if (err) {
process.send({ type: 'error', message: err.message, concurrent: --concurrent, id: id });
socket.close();
delete connections[id];
}
if (fn) fn(err);
});
});
}
|
javascript
|
function write(socket, task, id, fn) {
session[binary ? 'binary' : 'utf8'](task.size, function message(err, data) {
var start = socket.last = Date.now();
socket.send(data, {
binary: binary,
mask: masked
}, function sending(err) {
if (err) {
process.send({ type: 'error', message: err.message, concurrent: --concurrent, id: id });
socket.close();
delete connections[id];
}
if (fn) fn(err);
});
});
}
|
[
"function",
"write",
"(",
"socket",
",",
"task",
",",
"id",
",",
"fn",
")",
"{",
"session",
"[",
"binary",
"?",
"'binary'",
":",
"'utf8'",
"]",
"(",
"task",
".",
"size",
",",
"function",
"message",
"(",
"err",
",",
"data",
")",
"{",
"var",
"start",
"=",
"socket",
".",
"last",
"=",
"Date",
".",
"now",
"(",
")",
";",
"socket",
".",
"send",
"(",
"data",
",",
"{",
"binary",
":",
"binary",
",",
"mask",
":",
"masked",
"}",
",",
"function",
"sending",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"process",
".",
"send",
"(",
"{",
"type",
":",
"'error'",
",",
"message",
":",
"err",
".",
"message",
",",
"concurrent",
":",
"--",
"concurrent",
",",
"id",
":",
"id",
"}",
")",
";",
"socket",
".",
"close",
"(",
")",
";",
"delete",
"connections",
"[",
"id",
"]",
";",
"}",
"if",
"(",
"fn",
")",
"fn",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Helper function from writing messages to the socket.
@param {WebSocket} socket WebSocket connection we should write to
@param {Object} task The given task
@param {String} id
@param {Function} fn The callback
@api private
|
[
"Helper",
"function",
"from",
"writing",
"messages",
"to",
"the",
"socket",
"."
] |
20c51d6c5dcc57a1927ae0c6e77f21836d71f9de
|
https://github.com/observing/thor/blob/20c51d6c5dcc57a1927ae0c6e77f21836d71f9de/mjolnir.js#L102-L120
|
17,362
|
takuyaa/kuromoji.js
|
gulpfile.js
|
toBuffer
|
function toBuffer (typed) {
var ab = typed.buffer;
var buffer = new Buffer(ab.byteLength);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
return buffer;
}
|
javascript
|
function toBuffer (typed) {
var ab = typed.buffer;
var buffer = new Buffer(ab.byteLength);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
return buffer;
}
|
[
"function",
"toBuffer",
"(",
"typed",
")",
"{",
"var",
"ab",
"=",
"typed",
".",
"buffer",
";",
"var",
"buffer",
"=",
"new",
"Buffer",
"(",
"ab",
".",
"byteLength",
")",
";",
"var",
"view",
"=",
"new",
"Uint8Array",
"(",
"ab",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"buffer",
".",
"length",
";",
"++",
"i",
")",
"{",
"buffer",
"[",
"i",
"]",
"=",
"view",
"[",
"i",
"]",
";",
"}",
"return",
"buffer",
";",
"}"
] |
To node.js Buffer
|
[
"To",
"node",
".",
"js",
"Buffer"
] |
71ea8473bd119546977f22c61e4d52da28ac30a6
|
https://github.com/takuyaa/kuromoji.js/blob/71ea8473bd119546977f22c61e4d52da28ac30a6/gulpfile.js#L58-L66
|
17,363
|
takuyaa/kuromoji.js
|
src/util/ByteBuffer.js
|
ByteBuffer
|
function ByteBuffer(arg) {
var initial_size;
if (arg == null) {
initial_size = 1024 * 1024;
} else if (typeof arg === "number") {
initial_size = arg;
} else if (arg instanceof Uint8Array) {
this.buffer = arg;
this.position = 0; // Overwrite
return;
} else {
// typeof arg -> String
throw typeof arg + " is invalid parameter type for ByteBuffer constructor";
}
// arg is null or number
this.buffer = new Uint8Array(initial_size);
this.position = 0;
}
|
javascript
|
function ByteBuffer(arg) {
var initial_size;
if (arg == null) {
initial_size = 1024 * 1024;
} else if (typeof arg === "number") {
initial_size = arg;
} else if (arg instanceof Uint8Array) {
this.buffer = arg;
this.position = 0; // Overwrite
return;
} else {
// typeof arg -> String
throw typeof arg + " is invalid parameter type for ByteBuffer constructor";
}
// arg is null or number
this.buffer = new Uint8Array(initial_size);
this.position = 0;
}
|
[
"function",
"ByteBuffer",
"(",
"arg",
")",
"{",
"var",
"initial_size",
";",
"if",
"(",
"arg",
"==",
"null",
")",
"{",
"initial_size",
"=",
"1024",
"*",
"1024",
";",
"}",
"else",
"if",
"(",
"typeof",
"arg",
"===",
"\"number\"",
")",
"{",
"initial_size",
"=",
"arg",
";",
"}",
"else",
"if",
"(",
"arg",
"instanceof",
"Uint8Array",
")",
"{",
"this",
".",
"buffer",
"=",
"arg",
";",
"this",
".",
"position",
"=",
"0",
";",
"// Overwrite",
"return",
";",
"}",
"else",
"{",
"// typeof arg -> String",
"throw",
"typeof",
"arg",
"+",
"\" is invalid parameter type for ByteBuffer constructor\"",
";",
"}",
"// arg is null or number",
"this",
".",
"buffer",
"=",
"new",
"Uint8Array",
"(",
"initial_size",
")",
";",
"this",
".",
"position",
"=",
"0",
";",
"}"
] |
Utilities to manipulate byte sequence
@param {(number|Uint8Array)} arg Initial size of this buffer (number), or buffer to set (Uint8Array)
@constructor
|
[
"Utilities",
"to",
"manipulate",
"byte",
"sequence"
] |
71ea8473bd119546977f22c61e4d52da28ac30a6
|
https://github.com/takuyaa/kuromoji.js/blob/71ea8473bd119546977f22c61e4d52da28ac30a6/src/util/ByteBuffer.js#L140-L157
|
17,364
|
takuyaa/kuromoji.js
|
src/loader/DictionaryLoader.js
|
function (callback) {
async.map([ "tid.dat.gz", "tid_pos.dat.gz", "tid_map.dat.gz" ], function (filename, _callback) {
loadArrayBuffer(path.join(dic_path, filename), function (err, buffer) {
if(err) {
return _callback(err);
}
_callback(null, buffer);
});
}, function (err, buffers) {
if(err) {
return callback(err);
}
var token_info_buffer = new Uint8Array(buffers[0]);
var pos_buffer = new Uint8Array(buffers[1]);
var target_map_buffer = new Uint8Array(buffers[2]);
dic.loadTokenInfoDictionaries(token_info_buffer, pos_buffer, target_map_buffer);
callback(null);
});
}
|
javascript
|
function (callback) {
async.map([ "tid.dat.gz", "tid_pos.dat.gz", "tid_map.dat.gz" ], function (filename, _callback) {
loadArrayBuffer(path.join(dic_path, filename), function (err, buffer) {
if(err) {
return _callback(err);
}
_callback(null, buffer);
});
}, function (err, buffers) {
if(err) {
return callback(err);
}
var token_info_buffer = new Uint8Array(buffers[0]);
var pos_buffer = new Uint8Array(buffers[1]);
var target_map_buffer = new Uint8Array(buffers[2]);
dic.loadTokenInfoDictionaries(token_info_buffer, pos_buffer, target_map_buffer);
callback(null);
});
}
|
[
"function",
"(",
"callback",
")",
"{",
"async",
".",
"map",
"(",
"[",
"\"tid.dat.gz\"",
",",
"\"tid_pos.dat.gz\"",
",",
"\"tid_map.dat.gz\"",
"]",
",",
"function",
"(",
"filename",
",",
"_callback",
")",
"{",
"loadArrayBuffer",
"(",
"path",
".",
"join",
"(",
"dic_path",
",",
"filename",
")",
",",
"function",
"(",
"err",
",",
"buffer",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"_callback",
"(",
"err",
")",
";",
"}",
"_callback",
"(",
"null",
",",
"buffer",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
",",
"buffers",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"var",
"token_info_buffer",
"=",
"new",
"Uint8Array",
"(",
"buffers",
"[",
"0",
"]",
")",
";",
"var",
"pos_buffer",
"=",
"new",
"Uint8Array",
"(",
"buffers",
"[",
"1",
"]",
")",
";",
"var",
"target_map_buffer",
"=",
"new",
"Uint8Array",
"(",
"buffers",
"[",
"2",
"]",
")",
";",
"dic",
".",
"loadTokenInfoDictionaries",
"(",
"token_info_buffer",
",",
"pos_buffer",
",",
"target_map_buffer",
")",
";",
"callback",
"(",
"null",
")",
";",
"}",
")",
";",
"}"
] |
Token info dictionaries
|
[
"Token",
"info",
"dictionaries"
] |
71ea8473bd119546977f22c61e4d52da28ac30a6
|
https://github.com/takuyaa/kuromoji.js/blob/71ea8473bd119546977f22c61e4d52da28ac30a6/src/loader/DictionaryLoader.js#L69-L88
|
|
17,365
|
takuyaa/kuromoji.js
|
src/loader/DictionaryLoader.js
|
function (callback) {
loadArrayBuffer(path.join(dic_path, "cc.dat.gz"), function (err, buffer) {
if(err) {
return callback(err);
}
var cc_buffer = new Int16Array(buffer);
dic.loadConnectionCosts(cc_buffer);
callback(null);
});
}
|
javascript
|
function (callback) {
loadArrayBuffer(path.join(dic_path, "cc.dat.gz"), function (err, buffer) {
if(err) {
return callback(err);
}
var cc_buffer = new Int16Array(buffer);
dic.loadConnectionCosts(cc_buffer);
callback(null);
});
}
|
[
"function",
"(",
"callback",
")",
"{",
"loadArrayBuffer",
"(",
"path",
".",
"join",
"(",
"dic_path",
",",
"\"cc.dat.gz\"",
")",
",",
"function",
"(",
"err",
",",
"buffer",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"var",
"cc_buffer",
"=",
"new",
"Int16Array",
"(",
"buffer",
")",
";",
"dic",
".",
"loadConnectionCosts",
"(",
"cc_buffer",
")",
";",
"callback",
"(",
"null",
")",
";",
"}",
")",
";",
"}"
] |
Connection cost matrix
|
[
"Connection",
"cost",
"matrix"
] |
71ea8473bd119546977f22c61e4d52da28ac30a6
|
https://github.com/takuyaa/kuromoji.js/blob/71ea8473bd119546977f22c61e4d52da28ac30a6/src/loader/DictionaryLoader.js#L90-L99
|
|
17,366
|
takuyaa/kuromoji.js
|
src/dict/DynamicDictionaries.js
|
DynamicDictionaries
|
function DynamicDictionaries(trie, token_info_dictionary, connection_costs, unknown_dictionary) {
if (trie != null) {
this.trie = trie;
} else {
this.trie = doublearray.builder(0).build([
{k: "", v: 1}
]);
}
if (token_info_dictionary != null) {
this.token_info_dictionary = token_info_dictionary;
} else {
this.token_info_dictionary = new TokenInfoDictionary();
}
if (connection_costs != null) {
this.connection_costs = connection_costs;
} else {
// backward_size * backward_size
this.connection_costs = new ConnectionCosts(0, 0);
}
if (unknown_dictionary != null) {
this.unknown_dictionary = unknown_dictionary;
} else {
this.unknown_dictionary = new UnknownDictionary();
}
}
|
javascript
|
function DynamicDictionaries(trie, token_info_dictionary, connection_costs, unknown_dictionary) {
if (trie != null) {
this.trie = trie;
} else {
this.trie = doublearray.builder(0).build([
{k: "", v: 1}
]);
}
if (token_info_dictionary != null) {
this.token_info_dictionary = token_info_dictionary;
} else {
this.token_info_dictionary = new TokenInfoDictionary();
}
if (connection_costs != null) {
this.connection_costs = connection_costs;
} else {
// backward_size * backward_size
this.connection_costs = new ConnectionCosts(0, 0);
}
if (unknown_dictionary != null) {
this.unknown_dictionary = unknown_dictionary;
} else {
this.unknown_dictionary = new UnknownDictionary();
}
}
|
[
"function",
"DynamicDictionaries",
"(",
"trie",
",",
"token_info_dictionary",
",",
"connection_costs",
",",
"unknown_dictionary",
")",
"{",
"if",
"(",
"trie",
"!=",
"null",
")",
"{",
"this",
".",
"trie",
"=",
"trie",
";",
"}",
"else",
"{",
"this",
".",
"trie",
"=",
"doublearray",
".",
"builder",
"(",
"0",
")",
".",
"build",
"(",
"[",
"{",
"k",
":",
"\"\"",
",",
"v",
":",
"1",
"}",
"]",
")",
";",
"}",
"if",
"(",
"token_info_dictionary",
"!=",
"null",
")",
"{",
"this",
".",
"token_info_dictionary",
"=",
"token_info_dictionary",
";",
"}",
"else",
"{",
"this",
".",
"token_info_dictionary",
"=",
"new",
"TokenInfoDictionary",
"(",
")",
";",
"}",
"if",
"(",
"connection_costs",
"!=",
"null",
")",
"{",
"this",
".",
"connection_costs",
"=",
"connection_costs",
";",
"}",
"else",
"{",
"// backward_size * backward_size",
"this",
".",
"connection_costs",
"=",
"new",
"ConnectionCosts",
"(",
"0",
",",
"0",
")",
";",
"}",
"if",
"(",
"unknown_dictionary",
"!=",
"null",
")",
"{",
"this",
".",
"unknown_dictionary",
"=",
"unknown_dictionary",
";",
"}",
"else",
"{",
"this",
".",
"unknown_dictionary",
"=",
"new",
"UnknownDictionary",
"(",
")",
";",
"}",
"}"
] |
Dictionaries container for Tokenizer
@param {DoubleArray} trie
@param {TokenInfoDictionary} token_info_dictionary
@param {ConnectionCosts} connection_costs
@param {UnknownDictionary} unknown_dictionary
@constructor
|
[
"Dictionaries",
"container",
"for",
"Tokenizer"
] |
71ea8473bd119546977f22c61e4d52da28ac30a6
|
https://github.com/takuyaa/kuromoji.js/blob/71ea8473bd119546977f22c61e4d52da28ac30a6/src/dict/DynamicDictionaries.js#L33-L57
|
17,367
|
takuyaa/kuromoji.js
|
src/viterbi/ViterbiNode.js
|
ViterbiNode
|
function ViterbiNode(node_name, node_cost, start_pos, length, type, left_id, right_id, surface_form) {
this.name = node_name;
this.cost = node_cost;
this.start_pos = start_pos;
this.length = length;
this.left_id = left_id;
this.right_id = right_id;
this.prev = null;
this.surface_form = surface_form;
if (type === "BOS") {
this.shortest_cost = 0;
} else {
this.shortest_cost = Number.MAX_VALUE;
}
this.type = type;
}
|
javascript
|
function ViterbiNode(node_name, node_cost, start_pos, length, type, left_id, right_id, surface_form) {
this.name = node_name;
this.cost = node_cost;
this.start_pos = start_pos;
this.length = length;
this.left_id = left_id;
this.right_id = right_id;
this.prev = null;
this.surface_form = surface_form;
if (type === "BOS") {
this.shortest_cost = 0;
} else {
this.shortest_cost = Number.MAX_VALUE;
}
this.type = type;
}
|
[
"function",
"ViterbiNode",
"(",
"node_name",
",",
"node_cost",
",",
"start_pos",
",",
"length",
",",
"type",
",",
"left_id",
",",
"right_id",
",",
"surface_form",
")",
"{",
"this",
".",
"name",
"=",
"node_name",
";",
"this",
".",
"cost",
"=",
"node_cost",
";",
"this",
".",
"start_pos",
"=",
"start_pos",
";",
"this",
".",
"length",
"=",
"length",
";",
"this",
".",
"left_id",
"=",
"left_id",
";",
"this",
".",
"right_id",
"=",
"right_id",
";",
"this",
".",
"prev",
"=",
"null",
";",
"this",
".",
"surface_form",
"=",
"surface_form",
";",
"if",
"(",
"type",
"===",
"\"BOS\"",
")",
"{",
"this",
".",
"shortest_cost",
"=",
"0",
";",
"}",
"else",
"{",
"this",
".",
"shortest_cost",
"=",
"Number",
".",
"MAX_VALUE",
";",
"}",
"this",
".",
"type",
"=",
"type",
";",
"}"
] |
ViterbiNode is a node of ViterbiLattice
@param {number} node_name Word ID
@param {number} node_cost Word cost to generate
@param {number} start_pos Start position from 1
@param {number} length Word length
@param {string} type Node type (KNOWN, UNKNOWN, BOS, EOS, ...)
@param {number} left_id Left context ID
@param {number} right_id Right context ID
@param {string} surface_form Surface form of this word
@constructor
|
[
"ViterbiNode",
"is",
"a",
"node",
"of",
"ViterbiLattice"
] |
71ea8473bd119546977f22c61e4d52da28ac30a6
|
https://github.com/takuyaa/kuromoji.js/blob/71ea8473bd119546977f22c61e4d52da28ac30a6/src/viterbi/ViterbiNode.js#L32-L47
|
17,368
|
fgnass/domino
|
lib/Document.js
|
MultiId
|
function MultiId(node) {
this.nodes = Object.create(null);
this.nodes[node._nid] = node;
this.length = 1;
this.firstNode = undefined;
}
|
javascript
|
function MultiId(node) {
this.nodes = Object.create(null);
this.nodes[node._nid] = node;
this.length = 1;
this.firstNode = undefined;
}
|
[
"function",
"MultiId",
"(",
"node",
")",
"{",
"this",
".",
"nodes",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"this",
".",
"nodes",
"[",
"node",
".",
"_nid",
"]",
"=",
"node",
";",
"this",
".",
"length",
"=",
"1",
";",
"this",
".",
"firstNode",
"=",
"undefined",
";",
"}"
] |
A class for storing multiple nodes with the same ID
|
[
"A",
"class",
"for",
"storing",
"multiple",
"nodes",
"with",
"the",
"same",
"ID"
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/Document.js#L833-L838
|
17,369
|
fgnass/domino
|
lib/HTMLParser.js
|
isA
|
function isA(elt, set) {
if (typeof set === 'string') {
// convenience case for testing a particular HTML element
return elt.namespaceURI === NAMESPACE.HTML &&
elt.localName === set;
}
var tagnames = set[elt.namespaceURI];
return tagnames && tagnames[elt.localName];
}
|
javascript
|
function isA(elt, set) {
if (typeof set === 'string') {
// convenience case for testing a particular HTML element
return elt.namespaceURI === NAMESPACE.HTML &&
elt.localName === set;
}
var tagnames = set[elt.namespaceURI];
return tagnames && tagnames[elt.localName];
}
|
[
"function",
"isA",
"(",
"elt",
",",
"set",
")",
"{",
"if",
"(",
"typeof",
"set",
"===",
"'string'",
")",
"{",
"// convenience case for testing a particular HTML element",
"return",
"elt",
".",
"namespaceURI",
"===",
"NAMESPACE",
".",
"HTML",
"&&",
"elt",
".",
"localName",
"===",
"set",
";",
"}",
"var",
"tagnames",
"=",
"set",
"[",
"elt",
".",
"namespaceURI",
"]",
";",
"return",
"tagnames",
"&&",
"tagnames",
"[",
"elt",
".",
"localName",
"]",
";",
"}"
] |
Determine whether the element is a member of the set. The set is an object that maps namespaces to objects. The objects then map local tagnames to the value true if that tag is part of the set
|
[
"Determine",
"whether",
"the",
"element",
"is",
"a",
"member",
"of",
"the",
"set",
".",
"The",
"set",
"is",
"an",
"object",
"that",
"maps",
"namespaces",
"to",
"objects",
".",
"The",
"objects",
"then",
"map",
"local",
"tagnames",
"to",
"the",
"value",
"true",
"if",
"that",
"tag",
"is",
"part",
"of",
"the",
"set"
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/HTMLParser.js#L1568-L1576
|
17,370
|
fgnass/domino
|
lib/HTMLParser.js
|
equal
|
function equal(newelt, oldelt, oldattrs) {
if (newelt.localName !== oldelt.localName) return false;
if (newelt._numattrs !== oldattrs.length) return false;
for(var i = 0, n = oldattrs.length; i < n; i++) {
var oldname = oldattrs[i][0];
var oldval = oldattrs[i][1];
if (!newelt.hasAttribute(oldname)) return false;
if (newelt.getAttribute(oldname) !== oldval) return false;
}
return true;
}
|
javascript
|
function equal(newelt, oldelt, oldattrs) {
if (newelt.localName !== oldelt.localName) return false;
if (newelt._numattrs !== oldattrs.length) return false;
for(var i = 0, n = oldattrs.length; i < n; i++) {
var oldname = oldattrs[i][0];
var oldval = oldattrs[i][1];
if (!newelt.hasAttribute(oldname)) return false;
if (newelt.getAttribute(oldname) !== oldval) return false;
}
return true;
}
|
[
"function",
"equal",
"(",
"newelt",
",",
"oldelt",
",",
"oldattrs",
")",
"{",
"if",
"(",
"newelt",
".",
"localName",
"!==",
"oldelt",
".",
"localName",
")",
"return",
"false",
";",
"if",
"(",
"newelt",
".",
"_numattrs",
"!==",
"oldattrs",
".",
"length",
")",
"return",
"false",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"oldattrs",
".",
"length",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"var",
"oldname",
"=",
"oldattrs",
"[",
"i",
"]",
"[",
"0",
"]",
";",
"var",
"oldval",
"=",
"oldattrs",
"[",
"i",
"]",
"[",
"1",
"]",
";",
"if",
"(",
"!",
"newelt",
".",
"hasAttribute",
"(",
"oldname",
")",
")",
"return",
"false",
";",
"if",
"(",
"newelt",
".",
"getAttribute",
"(",
"oldname",
")",
"!==",
"oldval",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
This function defines equality of two elements for the purposes of the AFE list. Note that it compares the new elements attributes to the saved array of attributes associated with the old element because a script could have changed the old element's set of attributes
|
[
"This",
"function",
"defines",
"equality",
"of",
"two",
"elements",
"for",
"the",
"purposes",
"of",
"the",
"AFE",
"list",
".",
"Note",
"that",
"it",
"compares",
"the",
"new",
"elements",
"attributes",
"to",
"the",
"saved",
"array",
"of",
"attributes",
"associated",
"with",
"the",
"old",
"element",
"because",
"a",
"script",
"could",
"have",
"changed",
"the",
"old",
"element",
"s",
"set",
"of",
"attributes"
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/HTMLParser.js#L1858-L1868
|
17,371
|
fgnass/domino
|
lib/HTMLParser.js
|
function() {
var frag = doc.createDocumentFragment();
var root = doc.firstChild;
while(root.hasChildNodes()) {
frag.appendChild(root.firstChild);
}
return frag;
}
|
javascript
|
function() {
var frag = doc.createDocumentFragment();
var root = doc.firstChild;
while(root.hasChildNodes()) {
frag.appendChild(root.firstChild);
}
return frag;
}
|
[
"function",
"(",
")",
"{",
"var",
"frag",
"=",
"doc",
".",
"createDocumentFragment",
"(",
")",
";",
"var",
"root",
"=",
"doc",
".",
"firstChild",
";",
"while",
"(",
"root",
".",
"hasChildNodes",
"(",
")",
")",
"{",
"frag",
".",
"appendChild",
"(",
"root",
".",
"firstChild",
")",
";",
"}",
"return",
"frag",
";",
"}"
] |
Convenience function for internal use. Can only be called once, as it removes the nodes from `doc` to add them to fragment.
|
[
"Convenience",
"function",
"for",
"internal",
"use",
".",
"Can",
"only",
"be",
"called",
"once",
"as",
"it",
"removes",
"the",
"nodes",
"from",
"doc",
"to",
"add",
"them",
"to",
"fragment",
"."
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/HTMLParser.js#L2008-L2015
|
|
17,372
|
fgnass/domino
|
lib/HTMLParser.js
|
handleSimpleAttribute
|
function handleSimpleAttribute() {
SIMPLEATTR.lastIndex = nextchar-1;
var matched = SIMPLEATTR.exec(chars);
if (!matched) throw new Error("should never happen");
var name = matched[1];
if (!name) return false;
var value = matched[2];
var len = value.length;
switch(value[0]) {
case '"':
case "'":
value = value.substring(1, len-1);
nextchar += (matched[0].length-1);
tokenizer = after_attribute_value_quoted_state;
break;
default:
tokenizer = before_attribute_name_state;
nextchar += (matched[0].length-1);
value = value.substring(0, len-1);
break;
}
// Make sure there isn't already an attribute with this name
// If there is, ignore this one.
for(var i = 0; i < attributes.length; i++) {
if (attributes[i][0] === name) return true;
}
attributes.push([name, value]);
return true;
}
|
javascript
|
function handleSimpleAttribute() {
SIMPLEATTR.lastIndex = nextchar-1;
var matched = SIMPLEATTR.exec(chars);
if (!matched) throw new Error("should never happen");
var name = matched[1];
if (!name) return false;
var value = matched[2];
var len = value.length;
switch(value[0]) {
case '"':
case "'":
value = value.substring(1, len-1);
nextchar += (matched[0].length-1);
tokenizer = after_attribute_value_quoted_state;
break;
default:
tokenizer = before_attribute_name_state;
nextchar += (matched[0].length-1);
value = value.substring(0, len-1);
break;
}
// Make sure there isn't already an attribute with this name
// If there is, ignore this one.
for(var i = 0; i < attributes.length; i++) {
if (attributes[i][0] === name) return true;
}
attributes.push([name, value]);
return true;
}
|
[
"function",
"handleSimpleAttribute",
"(",
")",
"{",
"SIMPLEATTR",
".",
"lastIndex",
"=",
"nextchar",
"-",
"1",
";",
"var",
"matched",
"=",
"SIMPLEATTR",
".",
"exec",
"(",
"chars",
")",
";",
"if",
"(",
"!",
"matched",
")",
"throw",
"new",
"Error",
"(",
"\"should never happen\"",
")",
";",
"var",
"name",
"=",
"matched",
"[",
"1",
"]",
";",
"if",
"(",
"!",
"name",
")",
"return",
"false",
";",
"var",
"value",
"=",
"matched",
"[",
"2",
"]",
";",
"var",
"len",
"=",
"value",
".",
"length",
";",
"switch",
"(",
"value",
"[",
"0",
"]",
")",
"{",
"case",
"'\"'",
":",
"case",
"\"'\"",
":",
"value",
"=",
"value",
".",
"substring",
"(",
"1",
",",
"len",
"-",
"1",
")",
";",
"nextchar",
"+=",
"(",
"matched",
"[",
"0",
"]",
".",
"length",
"-",
"1",
")",
";",
"tokenizer",
"=",
"after_attribute_value_quoted_state",
";",
"break",
";",
"default",
":",
"tokenizer",
"=",
"before_attribute_name_state",
";",
"nextchar",
"+=",
"(",
"matched",
"[",
"0",
"]",
".",
"length",
"-",
"1",
")",
";",
"value",
"=",
"value",
".",
"substring",
"(",
"0",
",",
"len",
"-",
"1",
")",
";",
"break",
";",
"}",
"// Make sure there isn't already an attribute with this name",
"// If there is, ignore this one.",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"attributes",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"attributes",
"[",
"i",
"]",
"[",
"0",
"]",
"===",
"name",
")",
"return",
"true",
";",
"}",
"attributes",
".",
"push",
"(",
"[",
"name",
",",
"value",
"]",
")",
";",
"return",
"true",
";",
"}"
] |
Shortcut for simple attributes
|
[
"Shortcut",
"for",
"simple",
"attributes"
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/HTMLParser.js#L2337-L2367
|
17,373
|
fgnass/domino
|
lib/HTMLParser.js
|
getMatchingChars
|
function getMatchingChars(pattern) {
pattern.lastIndex = nextchar - 1;
var match = pattern.exec(chars);
if (match && match.index === nextchar - 1) {
match = match[0];
nextchar += match.length - 1;
/* Careful! Make sure we haven't matched the EOF character! */
if (input_complete && nextchar === numchars) {
// Oops, backup one.
match = match.slice(0, -1);
nextchar--;
}
return match;
} else {
throw new Error("should never happen");
}
}
|
javascript
|
function getMatchingChars(pattern) {
pattern.lastIndex = nextchar - 1;
var match = pattern.exec(chars);
if (match && match.index === nextchar - 1) {
match = match[0];
nextchar += match.length - 1;
/* Careful! Make sure we haven't matched the EOF character! */
if (input_complete && nextchar === numchars) {
// Oops, backup one.
match = match.slice(0, -1);
nextchar--;
}
return match;
} else {
throw new Error("should never happen");
}
}
|
[
"function",
"getMatchingChars",
"(",
"pattern",
")",
"{",
"pattern",
".",
"lastIndex",
"=",
"nextchar",
"-",
"1",
";",
"var",
"match",
"=",
"pattern",
".",
"exec",
"(",
"chars",
")",
";",
"if",
"(",
"match",
"&&",
"match",
".",
"index",
"===",
"nextchar",
"-",
"1",
")",
"{",
"match",
"=",
"match",
"[",
"0",
"]",
";",
"nextchar",
"+=",
"match",
".",
"length",
"-",
"1",
";",
"/* Careful! Make sure we haven't matched the EOF character! */",
"if",
"(",
"input_complete",
"&&",
"nextchar",
"===",
"numchars",
")",
"{",
"// Oops, backup one.",
"match",
"=",
"match",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
";",
"nextchar",
"--",
";",
"}",
"return",
"match",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"should never happen\"",
")",
";",
"}",
"}"
] |
Consume chars matched by the pattern and return them as a string. Starts matching at the current position, so users should drop the current char otherwise.
|
[
"Consume",
"chars",
"matched",
"by",
"the",
"pattern",
"and",
"return",
"them",
"as",
"a",
"string",
".",
"Starts",
"matching",
"at",
"the",
"current",
"position",
"so",
"users",
"should",
"drop",
"the",
"current",
"char",
"otherwise",
"."
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/HTMLParser.js#L2423-L2439
|
17,374
|
fgnass/domino
|
lib/HTMLParser.js
|
emitCharsWhile
|
function emitCharsWhile(pattern) {
pattern.lastIndex = nextchar-1;
var match = pattern.exec(chars)[0];
if (!match) return false;
emitCharString(match);
nextchar += match.length - 1;
return true;
}
|
javascript
|
function emitCharsWhile(pattern) {
pattern.lastIndex = nextchar-1;
var match = pattern.exec(chars)[0];
if (!match) return false;
emitCharString(match);
nextchar += match.length - 1;
return true;
}
|
[
"function",
"emitCharsWhile",
"(",
"pattern",
")",
"{",
"pattern",
".",
"lastIndex",
"=",
"nextchar",
"-",
"1",
";",
"var",
"match",
"=",
"pattern",
".",
"exec",
"(",
"chars",
")",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"match",
")",
"return",
"false",
";",
"emitCharString",
"(",
"match",
")",
";",
"nextchar",
"+=",
"match",
".",
"length",
"-",
"1",
";",
"return",
"true",
";",
"}"
] |
emit a string of chars that match a regexp Returns false if no chars matched.
|
[
"emit",
"a",
"string",
"of",
"chars",
"that",
"match",
"a",
"regexp",
"Returns",
"false",
"if",
"no",
"chars",
"matched",
"."
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/HTMLParser.js#L2443-L2450
|
17,375
|
fgnass/domino
|
lib/HTMLParser.js
|
emitCharString
|
function emitCharString(s) {
if (textrun.length > 0) flushText();
if (ignore_linefeed) {
ignore_linefeed = false;
if (s[0] === "\n") s = s.substring(1);
if (s.length === 0) return;
}
insertToken(TEXT, s);
}
|
javascript
|
function emitCharString(s) {
if (textrun.length > 0) flushText();
if (ignore_linefeed) {
ignore_linefeed = false;
if (s[0] === "\n") s = s.substring(1);
if (s.length === 0) return;
}
insertToken(TEXT, s);
}
|
[
"function",
"emitCharString",
"(",
"s",
")",
"{",
"if",
"(",
"textrun",
".",
"length",
">",
"0",
")",
"flushText",
"(",
")",
";",
"if",
"(",
"ignore_linefeed",
")",
"{",
"ignore_linefeed",
"=",
"false",
";",
"if",
"(",
"s",
"[",
"0",
"]",
"===",
"\"\\n\"",
")",
"s",
"=",
"s",
".",
"substring",
"(",
"1",
")",
";",
"if",
"(",
"s",
".",
"length",
"===",
"0",
")",
"return",
";",
"}",
"insertToken",
"(",
"TEXT",
",",
"s",
")",
";",
"}"
] |
This is used by CDATA sections
|
[
"This",
"is",
"used",
"by",
"CDATA",
"sections"
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/HTMLParser.js#L2453-L2463
|
17,376
|
fgnass/domino
|
lib/HTMLParser.js
|
insertElement
|
function insertElement(eltFunc) {
var elt;
if (foster_parent_mode && isA(stack.top, tablesectionrowSet)) {
elt = fosterParent(eltFunc);
}
else if (stack.top instanceof impl.HTMLTemplateElement) {
// "If the adjusted insertion location is inside a template element,
// let it instead be inside the template element's template contents"
elt = eltFunc(stack.top.content.ownerDocument);
stack.top.content._appendChild(elt);
} else {
elt = eltFunc(stack.top.ownerDocument);
stack.top._appendChild(elt);
}
stack.push(elt);
return elt;
}
|
javascript
|
function insertElement(eltFunc) {
var elt;
if (foster_parent_mode && isA(stack.top, tablesectionrowSet)) {
elt = fosterParent(eltFunc);
}
else if (stack.top instanceof impl.HTMLTemplateElement) {
// "If the adjusted insertion location is inside a template element,
// let it instead be inside the template element's template contents"
elt = eltFunc(stack.top.content.ownerDocument);
stack.top.content._appendChild(elt);
} else {
elt = eltFunc(stack.top.ownerDocument);
stack.top._appendChild(elt);
}
stack.push(elt);
return elt;
}
|
[
"function",
"insertElement",
"(",
"eltFunc",
")",
"{",
"var",
"elt",
";",
"if",
"(",
"foster_parent_mode",
"&&",
"isA",
"(",
"stack",
".",
"top",
",",
"tablesectionrowSet",
")",
")",
"{",
"elt",
"=",
"fosterParent",
"(",
"eltFunc",
")",
";",
"}",
"else",
"if",
"(",
"stack",
".",
"top",
"instanceof",
"impl",
".",
"HTMLTemplateElement",
")",
"{",
"// \"If the adjusted insertion location is inside a template element,",
"// let it instead be inside the template element's template contents\"",
"elt",
"=",
"eltFunc",
"(",
"stack",
".",
"top",
".",
"content",
".",
"ownerDocument",
")",
";",
"stack",
".",
"top",
".",
"content",
".",
"_appendChild",
"(",
"elt",
")",
";",
"}",
"else",
"{",
"elt",
"=",
"eltFunc",
"(",
"stack",
".",
"top",
".",
"ownerDocument",
")",
";",
"stack",
".",
"top",
".",
"_appendChild",
"(",
"elt",
")",
";",
"}",
"stack",
".",
"push",
"(",
"elt",
")",
";",
"return",
"elt",
";",
"}"
] |
Insert the element into the open element or foster parent it
|
[
"Insert",
"the",
"element",
"into",
"the",
"open",
"element",
"or",
"foster",
"parent",
"it"
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/HTMLParser.js#L2640-L2657
|
17,377
|
fgnass/domino
|
lib/HTMLParser.js
|
after_attribute_name_state
|
function after_attribute_name_state(c) {
switch(c) {
case 0x0009: // CHARACTER TABULATION (tab)
case 0x000A: // LINE FEED (LF)
case 0x000C: // FORM FEED (FF)
case 0x0020: // SPACE
/* Ignore the character. */
break;
case 0x002F: // SOLIDUS
// Keep in sync with before_attribute_name_state.
addAttribute(attrnamebuf);
tokenizer = self_closing_start_tag_state;
break;
case 0x003D: // EQUALS SIGN
tokenizer = before_attribute_value_state;
break;
case 0x003E: // GREATER-THAN SIGN
// Keep in sync with before_attribute_name_state.
tokenizer = data_state;
addAttribute(attrnamebuf);
emitTag();
break;
case -1: // EOF
// Keep in sync with before_attribute_name_state.
addAttribute(attrnamebuf);
emitEOF();
break;
default:
addAttribute(attrnamebuf);
beginAttrName();
reconsume(c, attribute_name_state);
break;
}
}
|
javascript
|
function after_attribute_name_state(c) {
switch(c) {
case 0x0009: // CHARACTER TABULATION (tab)
case 0x000A: // LINE FEED (LF)
case 0x000C: // FORM FEED (FF)
case 0x0020: // SPACE
/* Ignore the character. */
break;
case 0x002F: // SOLIDUS
// Keep in sync with before_attribute_name_state.
addAttribute(attrnamebuf);
tokenizer = self_closing_start_tag_state;
break;
case 0x003D: // EQUALS SIGN
tokenizer = before_attribute_value_state;
break;
case 0x003E: // GREATER-THAN SIGN
// Keep in sync with before_attribute_name_state.
tokenizer = data_state;
addAttribute(attrnamebuf);
emitTag();
break;
case -1: // EOF
// Keep in sync with before_attribute_name_state.
addAttribute(attrnamebuf);
emitEOF();
break;
default:
addAttribute(attrnamebuf);
beginAttrName();
reconsume(c, attribute_name_state);
break;
}
}
|
[
"function",
"after_attribute_name_state",
"(",
"c",
")",
"{",
"switch",
"(",
"c",
")",
"{",
"case",
"0x0009",
":",
"// CHARACTER TABULATION (tab)",
"case",
"0x000A",
":",
"// LINE FEED (LF)",
"case",
"0x000C",
":",
"// FORM FEED (FF)",
"case",
"0x0020",
":",
"// SPACE",
"/* Ignore the character. */",
"break",
";",
"case",
"0x002F",
":",
"// SOLIDUS",
"// Keep in sync with before_attribute_name_state.",
"addAttribute",
"(",
"attrnamebuf",
")",
";",
"tokenizer",
"=",
"self_closing_start_tag_state",
";",
"break",
";",
"case",
"0x003D",
":",
"// EQUALS SIGN",
"tokenizer",
"=",
"before_attribute_value_state",
";",
"break",
";",
"case",
"0x003E",
":",
"// GREATER-THAN SIGN",
"// Keep in sync with before_attribute_name_state.",
"tokenizer",
"=",
"data_state",
";",
"addAttribute",
"(",
"attrnamebuf",
")",
";",
"emitTag",
"(",
")",
";",
"break",
";",
"case",
"-",
"1",
":",
"// EOF",
"// Keep in sync with before_attribute_name_state.",
"addAttribute",
"(",
"attrnamebuf",
")",
";",
"emitEOF",
"(",
")",
";",
"break",
";",
"default",
":",
"addAttribute",
"(",
"attrnamebuf",
")",
";",
"beginAttrName",
"(",
")",
";",
"reconsume",
"(",
"c",
",",
"attribute_name_state",
")",
";",
"break",
";",
"}",
"}"
] |
There is an active attribute in attrnamebuf, but not yet in attrvaluebuf.
|
[
"There",
"is",
"an",
"active",
"attribute",
"in",
"attrnamebuf",
"but",
"not",
"yet",
"in",
"attrvaluebuf",
"."
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/HTMLParser.js#L4179-L4212
|
17,378
|
fgnass/domino
|
lib/HTMLParser.js
|
before_html_mode
|
function before_html_mode(t,value,arg3,arg4) {
var elt;
switch(t) {
case 1: // TEXT
value = value.replace(LEADINGWS, ""); // Ignore spaces
if (value.length === 0) return; // Are we done?
break; // Handle anything non-space text below
case 5: // DOCTYPE
/* ignore the token */
return;
case 4: // COMMENT
doc._appendChild(doc.createComment(value));
return;
case 2: // TAG
if (value === "html") {
elt = createHTMLElt(doc, value, arg3);
stack.push(elt);
doc.appendChild(elt);
// XXX: handle application cache here
parser = before_head_mode;
return;
}
break;
case 3: // ENDTAG
switch(value) {
case "html":
case "head":
case "body":
case "br":
break; // fall through on these
default:
return; // ignore most end tags
}
}
// Anything that didn't get handled above is handled like this:
elt = createHTMLElt(doc, "html", null);
stack.push(elt);
doc.appendChild(elt);
// XXX: handle application cache here
parser = before_head_mode;
parser(t,value,arg3,arg4);
}
|
javascript
|
function before_html_mode(t,value,arg3,arg4) {
var elt;
switch(t) {
case 1: // TEXT
value = value.replace(LEADINGWS, ""); // Ignore spaces
if (value.length === 0) return; // Are we done?
break; // Handle anything non-space text below
case 5: // DOCTYPE
/* ignore the token */
return;
case 4: // COMMENT
doc._appendChild(doc.createComment(value));
return;
case 2: // TAG
if (value === "html") {
elt = createHTMLElt(doc, value, arg3);
stack.push(elt);
doc.appendChild(elt);
// XXX: handle application cache here
parser = before_head_mode;
return;
}
break;
case 3: // ENDTAG
switch(value) {
case "html":
case "head":
case "body":
case "br":
break; // fall through on these
default:
return; // ignore most end tags
}
}
// Anything that didn't get handled above is handled like this:
elt = createHTMLElt(doc, "html", null);
stack.push(elt);
doc.appendChild(elt);
// XXX: handle application cache here
parser = before_head_mode;
parser(t,value,arg3,arg4);
}
|
[
"function",
"before_html_mode",
"(",
"t",
",",
"value",
",",
"arg3",
",",
"arg4",
")",
"{",
"var",
"elt",
";",
"switch",
"(",
"t",
")",
"{",
"case",
"1",
":",
"// TEXT",
"value",
"=",
"value",
".",
"replace",
"(",
"LEADINGWS",
",",
"\"\"",
")",
";",
"// Ignore spaces",
"if",
"(",
"value",
".",
"length",
"===",
"0",
")",
"return",
";",
"// Are we done?",
"break",
";",
"// Handle anything non-space text below",
"case",
"5",
":",
"// DOCTYPE",
"/* ignore the token */",
"return",
";",
"case",
"4",
":",
"// COMMENT",
"doc",
".",
"_appendChild",
"(",
"doc",
".",
"createComment",
"(",
"value",
")",
")",
";",
"return",
";",
"case",
"2",
":",
"// TAG",
"if",
"(",
"value",
"===",
"\"html\"",
")",
"{",
"elt",
"=",
"createHTMLElt",
"(",
"doc",
",",
"value",
",",
"arg3",
")",
";",
"stack",
".",
"push",
"(",
"elt",
")",
";",
"doc",
".",
"appendChild",
"(",
"elt",
")",
";",
"// XXX: handle application cache here",
"parser",
"=",
"before_head_mode",
";",
"return",
";",
"}",
"break",
";",
"case",
"3",
":",
"// ENDTAG",
"switch",
"(",
"value",
")",
"{",
"case",
"\"html\"",
":",
"case",
"\"head\"",
":",
"case",
"\"body\"",
":",
"case",
"\"br\"",
":",
"break",
";",
"// fall through on these",
"default",
":",
"return",
";",
"// ignore most end tags",
"}",
"}",
"// Anything that didn't get handled above is handled like this:",
"elt",
"=",
"createHTMLElt",
"(",
"doc",
",",
"\"html\"",
",",
"null",
")",
";",
"stack",
".",
"push",
"(",
"elt",
")",
";",
"doc",
".",
"appendChild",
"(",
"elt",
")",
";",
"// XXX: handle application cache here",
"parser",
"=",
"before_head_mode",
";",
"parser",
"(",
"t",
",",
"value",
",",
"arg3",
",",
"arg4",
")",
";",
"}"
] |
11.2.5.4.2 The "before html" insertion mode
|
[
"11",
".",
"2",
".",
"5",
".",
"4",
".",
"2",
"The",
"before",
"html",
"insertion",
"mode"
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/HTMLParser.js#L5332-L5374
|
17,379
|
fgnass/domino
|
lib/HTMLParser.js
|
before_head_mode
|
function before_head_mode(t,value,arg3,arg4) {
switch(t) {
case 1: // TEXT
value = value.replace(LEADINGWS, ""); // Ignore spaces
if (value.length === 0) return; // Are we done?
break; // Handle anything non-space text below
case 5: // DOCTYPE
/* ignore the token */
return;
case 4: // COMMENT
insertComment(value);
return;
case 2: // TAG
switch(value) {
case "html":
in_body_mode(t,value,arg3,arg4);
return;
case "head":
var elt = insertHTMLElement(value, arg3);
head_element_pointer = elt;
parser = in_head_mode;
return;
}
break;
case 3: // ENDTAG
switch(value) {
case "html":
case "head":
case "body":
case "br":
break;
default:
return; // ignore most end tags
}
}
// If not handled explicitly above
before_head_mode(TAG, "head", null); // create a head tag
parser(t, value, arg3, arg4); // then try again with this token
}
|
javascript
|
function before_head_mode(t,value,arg3,arg4) {
switch(t) {
case 1: // TEXT
value = value.replace(LEADINGWS, ""); // Ignore spaces
if (value.length === 0) return; // Are we done?
break; // Handle anything non-space text below
case 5: // DOCTYPE
/* ignore the token */
return;
case 4: // COMMENT
insertComment(value);
return;
case 2: // TAG
switch(value) {
case "html":
in_body_mode(t,value,arg3,arg4);
return;
case "head":
var elt = insertHTMLElement(value, arg3);
head_element_pointer = elt;
parser = in_head_mode;
return;
}
break;
case 3: // ENDTAG
switch(value) {
case "html":
case "head":
case "body":
case "br":
break;
default:
return; // ignore most end tags
}
}
// If not handled explicitly above
before_head_mode(TAG, "head", null); // create a head tag
parser(t, value, arg3, arg4); // then try again with this token
}
|
[
"function",
"before_head_mode",
"(",
"t",
",",
"value",
",",
"arg3",
",",
"arg4",
")",
"{",
"switch",
"(",
"t",
")",
"{",
"case",
"1",
":",
"// TEXT",
"value",
"=",
"value",
".",
"replace",
"(",
"LEADINGWS",
",",
"\"\"",
")",
";",
"// Ignore spaces",
"if",
"(",
"value",
".",
"length",
"===",
"0",
")",
"return",
";",
"// Are we done?",
"break",
";",
"// Handle anything non-space text below",
"case",
"5",
":",
"// DOCTYPE",
"/* ignore the token */",
"return",
";",
"case",
"4",
":",
"// COMMENT",
"insertComment",
"(",
"value",
")",
";",
"return",
";",
"case",
"2",
":",
"// TAG",
"switch",
"(",
"value",
")",
"{",
"case",
"\"html\"",
":",
"in_body_mode",
"(",
"t",
",",
"value",
",",
"arg3",
",",
"arg4",
")",
";",
"return",
";",
"case",
"\"head\"",
":",
"var",
"elt",
"=",
"insertHTMLElement",
"(",
"value",
",",
"arg3",
")",
";",
"head_element_pointer",
"=",
"elt",
";",
"parser",
"=",
"in_head_mode",
";",
"return",
";",
"}",
"break",
";",
"case",
"3",
":",
"// ENDTAG",
"switch",
"(",
"value",
")",
"{",
"case",
"\"html\"",
":",
"case",
"\"head\"",
":",
"case",
"\"body\"",
":",
"case",
"\"br\"",
":",
"break",
";",
"default",
":",
"return",
";",
"// ignore most end tags",
"}",
"}",
"// If not handled explicitly above",
"before_head_mode",
"(",
"TAG",
",",
"\"head\"",
",",
"null",
")",
";",
"// create a head tag",
"parser",
"(",
"t",
",",
"value",
",",
"arg3",
",",
"arg4",
")",
";",
"// then try again with this token",
"}"
] |
11.2.5.4.3 The "before head" insertion mode
|
[
"11",
".",
"2",
".",
"5",
".",
"4",
".",
"3",
"The",
"before",
"head",
"insertion",
"mode"
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/HTMLParser.js#L5377-L5416
|
17,380
|
fgnass/domino
|
lib/HTMLParser.js
|
in_head_noscript_mode
|
function in_head_noscript_mode(t, value, arg3, arg4) {
switch(t) {
case 5: // DOCTYPE
return;
case 4: // COMMENT
in_head_mode(t, value);
return;
case 1: // TEXT
var ws = value.match(LEADINGWS);
if (ws) {
in_head_mode(t, ws[0]);
value = value.substring(ws[0].length);
}
if (value.length === 0) return; // no more text
break; // Handle non-whitespace below
case 2: // TAG
switch(value) {
case "html":
in_body_mode(t, value, arg3, arg4);
return;
case "basefont":
case "bgsound":
case "link":
case "meta":
case "noframes":
case "style":
in_head_mode(t, value, arg3);
return;
case "head":
case "noscript":
return;
}
break;
case 3: // ENDTAG
switch(value) {
case "noscript":
stack.pop();
parser = in_head_mode;
return;
case "br":
break; // goes to the outer default
default:
return; // ignore other end tags
}
break;
}
// If not handled above
in_head_noscript_mode(ENDTAG, "noscript", null);
parser(t, value, arg3, arg4);
}
|
javascript
|
function in_head_noscript_mode(t, value, arg3, arg4) {
switch(t) {
case 5: // DOCTYPE
return;
case 4: // COMMENT
in_head_mode(t, value);
return;
case 1: // TEXT
var ws = value.match(LEADINGWS);
if (ws) {
in_head_mode(t, ws[0]);
value = value.substring(ws[0].length);
}
if (value.length === 0) return; // no more text
break; // Handle non-whitespace below
case 2: // TAG
switch(value) {
case "html":
in_body_mode(t, value, arg3, arg4);
return;
case "basefont":
case "bgsound":
case "link":
case "meta":
case "noframes":
case "style":
in_head_mode(t, value, arg3);
return;
case "head":
case "noscript":
return;
}
break;
case 3: // ENDTAG
switch(value) {
case "noscript":
stack.pop();
parser = in_head_mode;
return;
case "br":
break; // goes to the outer default
default:
return; // ignore other end tags
}
break;
}
// If not handled above
in_head_noscript_mode(ENDTAG, "noscript", null);
parser(t, value, arg3, arg4);
}
|
[
"function",
"in_head_noscript_mode",
"(",
"t",
",",
"value",
",",
"arg3",
",",
"arg4",
")",
"{",
"switch",
"(",
"t",
")",
"{",
"case",
"5",
":",
"// DOCTYPE",
"return",
";",
"case",
"4",
":",
"// COMMENT",
"in_head_mode",
"(",
"t",
",",
"value",
")",
";",
"return",
";",
"case",
"1",
":",
"// TEXT",
"var",
"ws",
"=",
"value",
".",
"match",
"(",
"LEADINGWS",
")",
";",
"if",
"(",
"ws",
")",
"{",
"in_head_mode",
"(",
"t",
",",
"ws",
"[",
"0",
"]",
")",
";",
"value",
"=",
"value",
".",
"substring",
"(",
"ws",
"[",
"0",
"]",
".",
"length",
")",
";",
"}",
"if",
"(",
"value",
".",
"length",
"===",
"0",
")",
"return",
";",
"// no more text",
"break",
";",
"// Handle non-whitespace below",
"case",
"2",
":",
"// TAG",
"switch",
"(",
"value",
")",
"{",
"case",
"\"html\"",
":",
"in_body_mode",
"(",
"t",
",",
"value",
",",
"arg3",
",",
"arg4",
")",
";",
"return",
";",
"case",
"\"basefont\"",
":",
"case",
"\"bgsound\"",
":",
"case",
"\"link\"",
":",
"case",
"\"meta\"",
":",
"case",
"\"noframes\"",
":",
"case",
"\"style\"",
":",
"in_head_mode",
"(",
"t",
",",
"value",
",",
"arg3",
")",
";",
"return",
";",
"case",
"\"head\"",
":",
"case",
"\"noscript\"",
":",
"return",
";",
"}",
"break",
";",
"case",
"3",
":",
"// ENDTAG",
"switch",
"(",
"value",
")",
"{",
"case",
"\"noscript\"",
":",
"stack",
".",
"pop",
"(",
")",
";",
"parser",
"=",
"in_head_mode",
";",
"return",
";",
"case",
"\"br\"",
":",
"break",
";",
"// goes to the outer default",
"default",
":",
"return",
";",
"// ignore other end tags",
"}",
"break",
";",
"}",
"// If not handled above",
"in_head_noscript_mode",
"(",
"ENDTAG",
",",
"\"noscript\"",
",",
"null",
")",
";",
"parser",
"(",
"t",
",",
"value",
",",
"arg3",
",",
"arg4",
")",
";",
"}"
] |
13.2.5.4.5 The "in head noscript" insertion mode
|
[
"13",
".",
"2",
".",
"5",
".",
"4",
".",
"5",
"The",
"in",
"head",
"noscript",
"insertion",
"mode"
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/HTMLParser.js#L5521-L5571
|
17,381
|
fgnass/domino
|
lib/EventTarget.js
|
function(event) {
return (this._armed !== null &&
event.type === 'mouseup' &&
event.isTrusted &&
event.button === 0 &&
event.timeStamp - this._armed.t < 1000 &&
Math.abs(event.clientX - this._armed.x) < 10 &&
Math.abs(event.clientY - this._armed.Y) < 10);
}
|
javascript
|
function(event) {
return (this._armed !== null &&
event.type === 'mouseup' &&
event.isTrusted &&
event.button === 0 &&
event.timeStamp - this._armed.t < 1000 &&
Math.abs(event.clientX - this._armed.x) < 10 &&
Math.abs(event.clientY - this._armed.Y) < 10);
}
|
[
"function",
"(",
"event",
")",
"{",
"return",
"(",
"this",
".",
"_armed",
"!==",
"null",
"&&",
"event",
".",
"type",
"===",
"'mouseup'",
"&&",
"event",
".",
"isTrusted",
"&&",
"event",
".",
"button",
"===",
"0",
"&&",
"event",
".",
"timeStamp",
"-",
"this",
".",
"_armed",
".",
"t",
"<",
"1000",
"&&",
"Math",
".",
"abs",
"(",
"event",
".",
"clientX",
"-",
"this",
".",
"_armed",
".",
"x",
")",
"<",
"10",
"&&",
"Math",
".",
"abs",
"(",
"event",
".",
"clientY",
"-",
"this",
".",
"_armed",
".",
"Y",
")",
"<",
"10",
")",
";",
"}"
] |
Determine whether a click occurred XXX We don't support double clicks for now
|
[
"Determine",
"whether",
"a",
"click",
"occurred",
"XXX",
"We",
"don",
"t",
"support",
"double",
"clicks",
"for",
"now"
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/EventTarget.js#L222-L230
|
|
17,382
|
fgnass/domino
|
lib/cssparser.js
|
function(filter){
var buffer = "",
c = this.read();
while(c !== null && filter(c)){
buffer += c;
c = this.read();
}
return buffer;
}
|
javascript
|
function(filter){
var buffer = "",
c = this.read();
while(c !== null && filter(c)){
buffer += c;
c = this.read();
}
return buffer;
}
|
[
"function",
"(",
"filter",
")",
"{",
"var",
"buffer",
"=",
"\"\"",
",",
"c",
"=",
"this",
".",
"read",
"(",
")",
";",
"while",
"(",
"c",
"!==",
"null",
"&&",
"filter",
"(",
"c",
")",
")",
"{",
"buffer",
"+=",
"c",
";",
"c",
"=",
"this",
".",
"read",
"(",
")",
";",
"}",
"return",
"buffer",
";",
"}"
] |
Reads characters while each character causes the given
filter function to return true. The function is passed
in each character and either returns true to continue
reading or false to stop.
@param {Function} filter The function to read on each character.
@return {String} The string made up of all characters that passed the
filter check.
@method readWhile
|
[
"Reads",
"characters",
"while",
"each",
"character",
"causes",
"the",
"given",
"filter",
"function",
"to",
"return",
"true",
".",
"The",
"function",
"is",
"passed",
"in",
"each",
"character",
"and",
"either",
"returns",
"true",
"to",
"continue",
"reading",
"or",
"false",
"to",
"stop",
"."
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/cssparser.js#L320-L332
|
|
17,383
|
fgnass/domino
|
lib/cssparser.js
|
function(matcher){
var source = this._input.substring(this._cursor),
value = null;
//if it's a string, just do a straight match
if (typeof matcher === "string"){
if (source.indexOf(matcher) === 0){
value = this.readCount(matcher.length);
}
} else if (matcher instanceof RegExp){
if (matcher.test(source)){
value = this.readCount(RegExp.lastMatch.length);
}
}
return value;
}
|
javascript
|
function(matcher){
var source = this._input.substring(this._cursor),
value = null;
//if it's a string, just do a straight match
if (typeof matcher === "string"){
if (source.indexOf(matcher) === 0){
value = this.readCount(matcher.length);
}
} else if (matcher instanceof RegExp){
if (matcher.test(source)){
value = this.readCount(RegExp.lastMatch.length);
}
}
return value;
}
|
[
"function",
"(",
"matcher",
")",
"{",
"var",
"source",
"=",
"this",
".",
"_input",
".",
"substring",
"(",
"this",
".",
"_cursor",
")",
",",
"value",
"=",
"null",
";",
"//if it's a string, just do a straight match",
"if",
"(",
"typeof",
"matcher",
"===",
"\"string\"",
")",
"{",
"if",
"(",
"source",
".",
"indexOf",
"(",
"matcher",
")",
"===",
"0",
")",
"{",
"value",
"=",
"this",
".",
"readCount",
"(",
"matcher",
".",
"length",
")",
";",
"}",
"}",
"else",
"if",
"(",
"matcher",
"instanceof",
"RegExp",
")",
"{",
"if",
"(",
"matcher",
".",
"test",
"(",
"source",
")",
")",
"{",
"value",
"=",
"this",
".",
"readCount",
"(",
"RegExp",
".",
"lastMatch",
".",
"length",
")",
";",
"}",
"}",
"return",
"value",
";",
"}"
] |
Reads characters that match either text or a regular expression and
returns those characters. If a match is found, the row and column
are adjusted; if no match is found, the reader's state is unchanged.
reading or false to stop.
@param {String|RegExp} matchter If a string, then the literal string
value is searched for. If a regular expression, then any string
matching the pattern is search for.
@return {String} The string made up of all characters that matched or
null if there was no match.
@method readMatch
|
[
"Reads",
"characters",
"that",
"match",
"either",
"text",
"or",
"a",
"regular",
"expression",
"and",
"returns",
"those",
"characters",
".",
"If",
"a",
"match",
"is",
"found",
"the",
"row",
"and",
"column",
"are",
"adjusted",
";",
"if",
"no",
"match",
"is",
"found",
"the",
"reader",
"s",
"state",
"is",
"unchanged",
".",
"reading",
"or",
"false",
"to",
"stop",
"."
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/cssparser.js#L346-L363
|
|
17,384
|
fgnass/domino
|
lib/cssparser.js
|
TokenStreamBase
|
function TokenStreamBase(input, tokenData){
/**
* The string reader for easy access to the text.
* @type StringReader
* @property _reader
* @private
*/
this._reader = input ? new StringReader(input.toString()) : null;
/**
* Token object for the last consumed token.
* @type Token
* @property _token
* @private
*/
this._token = null;
/**
* The array of token information.
* @type Array
* @property _tokenData
* @private
*/
this._tokenData = tokenData;
/**
* Lookahead token buffer.
* @type Array
* @property _lt
* @private
*/
this._lt = [];
/**
* Lookahead token buffer index.
* @type int
* @property _ltIndex
* @private
*/
this._ltIndex = 0;
this._ltIndexCache = [];
}
|
javascript
|
function TokenStreamBase(input, tokenData){
/**
* The string reader for easy access to the text.
* @type StringReader
* @property _reader
* @private
*/
this._reader = input ? new StringReader(input.toString()) : null;
/**
* Token object for the last consumed token.
* @type Token
* @property _token
* @private
*/
this._token = null;
/**
* The array of token information.
* @type Array
* @property _tokenData
* @private
*/
this._tokenData = tokenData;
/**
* Lookahead token buffer.
* @type Array
* @property _lt
* @private
*/
this._lt = [];
/**
* Lookahead token buffer index.
* @type int
* @property _ltIndex
* @private
*/
this._ltIndex = 0;
this._ltIndexCache = [];
}
|
[
"function",
"TokenStreamBase",
"(",
"input",
",",
"tokenData",
")",
"{",
"/**\n * The string reader for easy access to the text.\n * @type StringReader\n * @property _reader\n * @private\n */",
"this",
".",
"_reader",
"=",
"input",
"?",
"new",
"StringReader",
"(",
"input",
".",
"toString",
"(",
")",
")",
":",
"null",
";",
"/**\n * Token object for the last consumed token.\n * @type Token\n * @property _token\n * @private\n */",
"this",
".",
"_token",
"=",
"null",
";",
"/**\n * The array of token information.\n * @type Array\n * @property _tokenData\n * @private\n */",
"this",
".",
"_tokenData",
"=",
"tokenData",
";",
"/**\n * Lookahead token buffer.\n * @type Array\n * @property _lt\n * @private\n */",
"this",
".",
"_lt",
"=",
"[",
"]",
";",
"/**\n * Lookahead token buffer index.\n * @type int\n * @property _ltIndex\n * @private\n */",
"this",
".",
"_ltIndex",
"=",
"0",
";",
"this",
".",
"_ltIndexCache",
"=",
"[",
"]",
";",
"}"
] |
Generic TokenStream providing base functionality.
@class TokenStreamBase
@namespace parserlib.util
@constructor
@param {String|StringReader} input The text to tokenize or a reader from
which to read the input.
|
[
"Generic",
"TokenStream",
"providing",
"base",
"functionality",
"."
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/cssparser.js#L510-L553
|
17,385
|
fgnass/domino
|
lib/Element.js
|
Attr
|
function Attr(elt, lname, prefix, namespace, value) {
// localName and namespace are constant for any attr object.
// But value may change. And so can prefix, and so, therefore can name.
this.localName = lname;
this.prefix = (prefix===null || prefix==='') ? null : ('' + prefix);
this.namespaceURI = (namespace===null || namespace==='') ? null : ('' + namespace);
this.data = value;
// Set ownerElement last to ensure it is hooked up to onchange handler
this._setOwnerElement(elt);
}
|
javascript
|
function Attr(elt, lname, prefix, namespace, value) {
// localName and namespace are constant for any attr object.
// But value may change. And so can prefix, and so, therefore can name.
this.localName = lname;
this.prefix = (prefix===null || prefix==='') ? null : ('' + prefix);
this.namespaceURI = (namespace===null || namespace==='') ? null : ('' + namespace);
this.data = value;
// Set ownerElement last to ensure it is hooked up to onchange handler
this._setOwnerElement(elt);
}
|
[
"function",
"Attr",
"(",
"elt",
",",
"lname",
",",
"prefix",
",",
"namespace",
",",
"value",
")",
"{",
"// localName and namespace are constant for any attr object.",
"// But value may change. And so can prefix, and so, therefore can name.",
"this",
".",
"localName",
"=",
"lname",
";",
"this",
".",
"prefix",
"=",
"(",
"prefix",
"===",
"null",
"||",
"prefix",
"===",
"''",
")",
"?",
"null",
":",
"(",
"''",
"+",
"prefix",
")",
";",
"this",
".",
"namespaceURI",
"=",
"(",
"namespace",
"===",
"null",
"||",
"namespace",
"===",
"''",
")",
"?",
"null",
":",
"(",
"''",
"+",
"namespace",
")",
";",
"this",
".",
"data",
"=",
"value",
";",
"// Set ownerElement last to ensure it is hooked up to onchange handler",
"this",
".",
"_setOwnerElement",
"(",
"elt",
")",
";",
"}"
] |
The Attr class represents a single attribute. The values in _attrsByQName and _attrsByLName are instances of this class.
|
[
"The",
"Attr",
"class",
"represents",
"a",
"single",
"attribute",
".",
"The",
"values",
"in",
"_attrsByQName",
"and",
"_attrsByLName",
"are",
"instances",
"of",
"this",
"class",
"."
] |
2fc67e349e5a9ff978330d2247a546682e04753d
|
https://github.com/fgnass/domino/blob/2fc67e349e5a9ff978330d2247a546682e04753d/lib/Element.js#L964-L973
|
17,386
|
wbyoung/avn
|
lib/hooks.js
|
function(version) {
var result;
/** local */
var ensure = function(key) {
return function(r) {
if (r && !r[key]) { throw new Error('result missing ' + key); }
return r;
};
};
return plugins.first(function(plugin) {
return Promise.resolve()
.then(function() { return plugin.match(version); })
.then(ensure('command'))
.then(ensure('version'))
.then(function(r) { return (result = r); });
})
.then(function(plugin) {
return result && _.extend({ plugin: plugin }, result);
});
}
|
javascript
|
function(version) {
var result;
/** local */
var ensure = function(key) {
return function(r) {
if (r && !r[key]) { throw new Error('result missing ' + key); }
return r;
};
};
return plugins.first(function(plugin) {
return Promise.resolve()
.then(function() { return plugin.match(version); })
.then(ensure('command'))
.then(ensure('version'))
.then(function(r) { return (result = r); });
})
.then(function(plugin) {
return result && _.extend({ plugin: plugin }, result);
});
}
|
[
"function",
"(",
"version",
")",
"{",
"var",
"result",
";",
"/** local */",
"var",
"ensure",
"=",
"function",
"(",
"key",
")",
"{",
"return",
"function",
"(",
"r",
")",
"{",
"if",
"(",
"r",
"&&",
"!",
"r",
"[",
"key",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'result missing '",
"+",
"key",
")",
";",
"}",
"return",
"r",
";",
"}",
";",
"}",
";",
"return",
"plugins",
".",
"first",
"(",
"function",
"(",
"plugin",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"plugin",
".",
"match",
"(",
"version",
")",
";",
"}",
")",
".",
"then",
"(",
"ensure",
"(",
"'command'",
")",
")",
".",
"then",
"(",
"ensure",
"(",
"'version'",
")",
")",
".",
"then",
"(",
"function",
"(",
"r",
")",
"{",
"return",
"(",
"result",
"=",
"r",
")",
";",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"plugin",
")",
"{",
"return",
"result",
"&&",
"_",
".",
"extend",
"(",
"{",
"plugin",
":",
"plugin",
"}",
",",
"result",
")",
";",
"}",
")",
";",
"}"
] |
Find the first plugin that can activate the requested version.
@private
@function hooks.~match
@param {String} version The semver version to activate.
@return {Promise} A promise that resolves with both `version` and `command`
properties.
|
[
"Find",
"the",
"first",
"plugin",
"that",
"can",
"activate",
"the",
"requested",
"version",
"."
] |
30884a077977181a5851025c9a309e196943b591
|
https://github.com/wbyoung/avn/blob/30884a077977181a5851025c9a309e196943b591/lib/hooks.js#L20-L39
|
|
17,387
|
wbyoung/avn
|
lib/fmt.js
|
function(error) {
return util.format(' %s: %s',
chalk.magenta(error.plugin.name),
error.message);
}
|
javascript
|
function(error) {
return util.format(' %s: %s',
chalk.magenta(error.plugin.name),
error.message);
}
|
[
"function",
"(",
"error",
")",
"{",
"return",
"util",
".",
"format",
"(",
"' %s: %s'",
",",
"chalk",
".",
"magenta",
"(",
"error",
".",
"plugin",
".",
"name",
")",
",",
"error",
".",
"message",
")",
";",
"}"
] |
Build a detailed error string for displaying to the user.
@private
@function fmt.~errorDetail
@param {Error} error The error for which to build a string.
@return {String}
|
[
"Build",
"a",
"detailed",
"error",
"string",
"for",
"displaying",
"to",
"the",
"user",
"."
] |
30884a077977181a5851025c9a309e196943b591
|
https://github.com/wbyoung/avn/blob/30884a077977181a5851025c9a309e196943b591/lib/fmt.js#L34-L38
|
|
17,388
|
wbyoung/avn
|
lib/setup/plugins.js
|
function() {
return Promise.resolve()
.then(function() { return npm.loadAsync(); })
.then(function(npm) {
npm.config.set('spin', false);
npm.config.set('global', true);
npm.config.set('depth', 0);
return Promise.promisify(npm.commands.list)([], true);
})
.then(function(data) { return data; });
}
|
javascript
|
function() {
return Promise.resolve()
.then(function() { return npm.loadAsync(); })
.then(function(npm) {
npm.config.set('spin', false);
npm.config.set('global', true);
npm.config.set('depth', 0);
return Promise.promisify(npm.commands.list)([], true);
})
.then(function(data) { return data; });
}
|
[
"function",
"(",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"npm",
".",
"loadAsync",
"(",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"npm",
")",
"{",
"npm",
".",
"config",
".",
"set",
"(",
"'spin'",
",",
"false",
")",
";",
"npm",
".",
"config",
".",
"set",
"(",
"'global'",
",",
"true",
")",
";",
"npm",
".",
"config",
".",
"set",
"(",
"'depth'",
",",
"0",
")",
";",
"return",
"Promise",
".",
"promisify",
"(",
"npm",
".",
"commands",
".",
"list",
")",
"(",
"[",
"]",
",",
"true",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"data",
")",
"{",
"return",
"data",
";",
"}",
")",
";",
"}"
] |
Get a list of all global npm modules.
@private
@function setup.plugins.~modules
@return {Promise}
|
[
"Get",
"a",
"list",
"of",
"all",
"global",
"npm",
"modules",
"."
] |
30884a077977181a5851025c9a309e196943b591
|
https://github.com/wbyoung/avn/blob/30884a077977181a5851025c9a309e196943b591/lib/setup/plugins.js#L15-L25
|
|
17,389
|
pouchdb/pouchdb-server
|
examples/todos/public/scripts/app.js
|
addTodo
|
function addTodo(text) {
var todo = {
_id: new Date().toISOString(),
title: text,
completed: false
};
db.put(todo, function callback (err, result) {
if (!err) {
console.log('Successfully posted a todo!');
}
});
}
|
javascript
|
function addTodo(text) {
var todo = {
_id: new Date().toISOString(),
title: text,
completed: false
};
db.put(todo, function callback (err, result) {
if (!err) {
console.log('Successfully posted a todo!');
}
});
}
|
[
"function",
"addTodo",
"(",
"text",
")",
"{",
"var",
"todo",
"=",
"{",
"_id",
":",
"new",
"Date",
"(",
")",
".",
"toISOString",
"(",
")",
",",
"title",
":",
"text",
",",
"completed",
":",
"false",
"}",
";",
"db",
".",
"put",
"(",
"todo",
",",
"function",
"callback",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"console",
".",
"log",
"(",
"'Successfully posted a todo!'",
")",
";",
"}",
"}",
")",
";",
"}"
] |
We have to create a new todo document and enter it in the database
|
[
"We",
"have",
"to",
"create",
"a",
"new",
"todo",
"document",
"and",
"enter",
"it",
"in",
"the",
"database"
] |
89d59b0c3f8cec3be38d75d01cf0fa205c1f2ad5
|
https://github.com/pouchdb/pouchdb-server/blob/89d59b0c3f8cec3be38d75d01cf0fa205c1f2ad5/examples/todos/public/scripts/app.js#L23-L34
|
17,390
|
pouchdb/pouchdb-server
|
examples/todos/public/scripts/app.js
|
showTodos
|
function showTodos() {
db.allDocs({
include_docs: true,
descending: true
}, function(err, doc) {
redrawTodosUI(doc.rows);
});
}
|
javascript
|
function showTodos() {
db.allDocs({
include_docs: true,
descending: true
}, function(err, doc) {
redrawTodosUI(doc.rows);
});
}
|
[
"function",
"showTodos",
"(",
")",
"{",
"db",
".",
"allDocs",
"(",
"{",
"include_docs",
":",
"true",
",",
"descending",
":",
"true",
"}",
",",
"function",
"(",
"err",
",",
"doc",
")",
"{",
"redrawTodosUI",
"(",
"doc",
".",
"rows",
")",
";",
"}",
")",
";",
"}"
] |
Show the current list of todos by reading them from the database
|
[
"Show",
"the",
"current",
"list",
"of",
"todos",
"by",
"reading",
"them",
"from",
"the",
"database"
] |
89d59b0c3f8cec3be38d75d01cf0fa205c1f2ad5
|
https://github.com/pouchdb/pouchdb-server/blob/89d59b0c3f8cec3be38d75d01cf0fa205c1f2ad5/examples/todos/public/scripts/app.js#L37-L44
|
17,391
|
pouchdb/pouchdb-server
|
examples/todos/public/scripts/app.js
|
todoBlurred
|
function todoBlurred(todo, event) {
var trimmedText = event.target.value.trim();
if (!trimmedText) {
db.remove(todo);
} else {
todo.title = trimmedText;
db.put(todo);
}
}
|
javascript
|
function todoBlurred(todo, event) {
var trimmedText = event.target.value.trim();
if (!trimmedText) {
db.remove(todo);
} else {
todo.title = trimmedText;
db.put(todo);
}
}
|
[
"function",
"todoBlurred",
"(",
"todo",
",",
"event",
")",
"{",
"var",
"trimmedText",
"=",
"event",
".",
"target",
".",
"value",
".",
"trim",
"(",
")",
";",
"if",
"(",
"!",
"trimmedText",
")",
"{",
"db",
".",
"remove",
"(",
"todo",
")",
";",
"}",
"else",
"{",
"todo",
".",
"title",
"=",
"trimmedText",
";",
"db",
".",
"put",
"(",
"todo",
")",
";",
"}",
"}"
] |
The input box when editing a todo has blurred, we should save the new title or delete the todo if the title is empty
|
[
"The",
"input",
"box",
"when",
"editing",
"a",
"todo",
"has",
"blurred",
"we",
"should",
"save",
"the",
"new",
"title",
"or",
"delete",
"the",
"todo",
"if",
"the",
"title",
"is",
"empty"
] |
89d59b0c3f8cec3be38d75d01cf0fa205c1f2ad5
|
https://github.com/pouchdb/pouchdb-server/blob/89d59b0c3f8cec3be38d75d01cf0fa205c1f2ad5/examples/todos/public/scripts/app.js#L58-L66
|
17,392
|
pouchdb/pouchdb-server
|
examples/todos/public/scripts/app.js
|
sync
|
function sync() {
syncDom.setAttribute('data-sync-state', 'syncing');
var opts = {continuous: true, complete: syncError};
db.replicate.to(remoteCouch, opts);
db.replicate.from(remoteCouch, opts);
}
|
javascript
|
function sync() {
syncDom.setAttribute('data-sync-state', 'syncing');
var opts = {continuous: true, complete: syncError};
db.replicate.to(remoteCouch, opts);
db.replicate.from(remoteCouch, opts);
}
|
[
"function",
"sync",
"(",
")",
"{",
"syncDom",
".",
"setAttribute",
"(",
"'data-sync-state'",
",",
"'syncing'",
")",
";",
"var",
"opts",
"=",
"{",
"continuous",
":",
"true",
",",
"complete",
":",
"syncError",
"}",
";",
"db",
".",
"replicate",
".",
"to",
"(",
"remoteCouch",
",",
"opts",
")",
";",
"db",
".",
"replicate",
".",
"from",
"(",
"remoteCouch",
",",
"opts",
")",
";",
"}"
] |
Initialise a sync with the remote server
|
[
"Initialise",
"a",
"sync",
"with",
"the",
"remote",
"server"
] |
89d59b0c3f8cec3be38d75d01cf0fa205c1f2ad5
|
https://github.com/pouchdb/pouchdb-server/blob/89d59b0c3f8cec3be38d75d01cf0fa205c1f2ad5/examples/todos/public/scripts/app.js#L69-L74
|
17,393
|
pouchdb/pouchdb-server
|
examples/todos/public/scripts/app.js
|
todoDblClicked
|
function todoDblClicked(todo) {
var div = document.getElementById('li_' + todo._id);
var inputEditTodo = document.getElementById('input_' + todo._id);
div.className = 'editing';
inputEditTodo.focus();
}
|
javascript
|
function todoDblClicked(todo) {
var div = document.getElementById('li_' + todo._id);
var inputEditTodo = document.getElementById('input_' + todo._id);
div.className = 'editing';
inputEditTodo.focus();
}
|
[
"function",
"todoDblClicked",
"(",
"todo",
")",
"{",
"var",
"div",
"=",
"document",
".",
"getElementById",
"(",
"'li_'",
"+",
"todo",
".",
"_id",
")",
";",
"var",
"inputEditTodo",
"=",
"document",
".",
"getElementById",
"(",
"'input_'",
"+",
"todo",
".",
"_id",
")",
";",
"div",
".",
"className",
"=",
"'editing'",
";",
"inputEditTodo",
".",
"focus",
"(",
")",
";",
"}"
] |
User has double clicked a todo, display an input so they can edit the title
|
[
"User",
"has",
"double",
"clicked",
"a",
"todo",
"display",
"an",
"input",
"so",
"they",
"can",
"edit",
"the",
"title"
] |
89d59b0c3f8cec3be38d75d01cf0fa205c1f2ad5
|
https://github.com/pouchdb/pouchdb-server/blob/89d59b0c3f8cec3be38d75d01cf0fa205c1f2ad5/examples/todos/public/scripts/app.js#L84-L89
|
17,394
|
pouchdb/pouchdb-server
|
examples/todos/public/scripts/app.js
|
createTodoListItem
|
function createTodoListItem(todo) {
var checkbox = document.createElement('input');
checkbox.className = 'toggle';
checkbox.type = 'checkbox';
checkbox.addEventListener('change', checkboxChanged.bind(this, todo));
var label = document.createElement('label');
label.appendChild( document.createTextNode(todo.title));
label.addEventListener('dblclick', todoDblClicked.bind(this, todo));
var deleteLink = document.createElement('button');
deleteLink.className = 'destroy';
deleteLink.addEventListener( 'click', deleteButtonPressed.bind(this, todo));
var divDisplay = document.createElement('div');
divDisplay.className = 'view';
divDisplay.appendChild(checkbox);
divDisplay.appendChild(label);
divDisplay.appendChild(deleteLink);
var inputEditTodo = document.createElement('input');
inputEditTodo.id = 'input_' + todo._id;
inputEditTodo.className = 'edit';
inputEditTodo.value = todo.title;
inputEditTodo.addEventListener('keypress', todoKeyPressed.bind(this, todo));
inputEditTodo.addEventListener('blur', todoBlurred.bind(this, todo));
var li = document.createElement('li');
li.id = 'li_' + todo._id;
li.appendChild(divDisplay);
li.appendChild(inputEditTodo);
if (todo.completed) {
li.className += 'complete';
checkbox.checked = true;
}
return li;
}
|
javascript
|
function createTodoListItem(todo) {
var checkbox = document.createElement('input');
checkbox.className = 'toggle';
checkbox.type = 'checkbox';
checkbox.addEventListener('change', checkboxChanged.bind(this, todo));
var label = document.createElement('label');
label.appendChild( document.createTextNode(todo.title));
label.addEventListener('dblclick', todoDblClicked.bind(this, todo));
var deleteLink = document.createElement('button');
deleteLink.className = 'destroy';
deleteLink.addEventListener( 'click', deleteButtonPressed.bind(this, todo));
var divDisplay = document.createElement('div');
divDisplay.className = 'view';
divDisplay.appendChild(checkbox);
divDisplay.appendChild(label);
divDisplay.appendChild(deleteLink);
var inputEditTodo = document.createElement('input');
inputEditTodo.id = 'input_' + todo._id;
inputEditTodo.className = 'edit';
inputEditTodo.value = todo.title;
inputEditTodo.addEventListener('keypress', todoKeyPressed.bind(this, todo));
inputEditTodo.addEventListener('blur', todoBlurred.bind(this, todo));
var li = document.createElement('li');
li.id = 'li_' + todo._id;
li.appendChild(divDisplay);
li.appendChild(inputEditTodo);
if (todo.completed) {
li.className += 'complete';
checkbox.checked = true;
}
return li;
}
|
[
"function",
"createTodoListItem",
"(",
"todo",
")",
"{",
"var",
"checkbox",
"=",
"document",
".",
"createElement",
"(",
"'input'",
")",
";",
"checkbox",
".",
"className",
"=",
"'toggle'",
";",
"checkbox",
".",
"type",
"=",
"'checkbox'",
";",
"checkbox",
".",
"addEventListener",
"(",
"'change'",
",",
"checkboxChanged",
".",
"bind",
"(",
"this",
",",
"todo",
")",
")",
";",
"var",
"label",
"=",
"document",
".",
"createElement",
"(",
"'label'",
")",
";",
"label",
".",
"appendChild",
"(",
"document",
".",
"createTextNode",
"(",
"todo",
".",
"title",
")",
")",
";",
"label",
".",
"addEventListener",
"(",
"'dblclick'",
",",
"todoDblClicked",
".",
"bind",
"(",
"this",
",",
"todo",
")",
")",
";",
"var",
"deleteLink",
"=",
"document",
".",
"createElement",
"(",
"'button'",
")",
";",
"deleteLink",
".",
"className",
"=",
"'destroy'",
";",
"deleteLink",
".",
"addEventListener",
"(",
"'click'",
",",
"deleteButtonPressed",
".",
"bind",
"(",
"this",
",",
"todo",
")",
")",
";",
"var",
"divDisplay",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"divDisplay",
".",
"className",
"=",
"'view'",
";",
"divDisplay",
".",
"appendChild",
"(",
"checkbox",
")",
";",
"divDisplay",
".",
"appendChild",
"(",
"label",
")",
";",
"divDisplay",
".",
"appendChild",
"(",
"deleteLink",
")",
";",
"var",
"inputEditTodo",
"=",
"document",
".",
"createElement",
"(",
"'input'",
")",
";",
"inputEditTodo",
".",
"id",
"=",
"'input_'",
"+",
"todo",
".",
"_id",
";",
"inputEditTodo",
".",
"className",
"=",
"'edit'",
";",
"inputEditTodo",
".",
"value",
"=",
"todo",
".",
"title",
";",
"inputEditTodo",
".",
"addEventListener",
"(",
"'keypress'",
",",
"todoKeyPressed",
".",
"bind",
"(",
"this",
",",
"todo",
")",
")",
";",
"inputEditTodo",
".",
"addEventListener",
"(",
"'blur'",
",",
"todoBlurred",
".",
"bind",
"(",
"this",
",",
"todo",
")",
")",
";",
"var",
"li",
"=",
"document",
".",
"createElement",
"(",
"'li'",
")",
";",
"li",
".",
"id",
"=",
"'li_'",
"+",
"todo",
".",
"_id",
";",
"li",
".",
"appendChild",
"(",
"divDisplay",
")",
";",
"li",
".",
"appendChild",
"(",
"inputEditTodo",
")",
";",
"if",
"(",
"todo",
".",
"completed",
")",
"{",
"li",
".",
"className",
"+=",
"'complete'",
";",
"checkbox",
".",
"checked",
"=",
"true",
";",
"}",
"return",
"li",
";",
"}"
] |
Given an object representing a todo, this will create a list item to display it.
|
[
"Given",
"an",
"object",
"representing",
"a",
"todo",
"this",
"will",
"create",
"a",
"list",
"item",
"to",
"display",
"it",
"."
] |
89d59b0c3f8cec3be38d75d01cf0fa205c1f2ad5
|
https://github.com/pouchdb/pouchdb-server/blob/89d59b0c3f8cec3be38d75d01cf0fa205c1f2ad5/examples/todos/public/scripts/app.js#L102-L140
|
17,395
|
ReactiveX/IxJS
|
gulp/closure-task.js
|
getPublicExportedNames
|
function getPublicExportedNames(entryModule) {
const fn = function() {};
const isStaticOrProtoName = (x) => (
!(x in fn) &&
(x !== `default`) &&
(x !== `undefined`) &&
(x !== `__esModule`) &&
(x !== `constructor`)
);
return Object
.getOwnPropertyNames(entryModule)
.filter((name) => name !== 'default')
.filter((name) => (
typeof entryModule[name] === `object` ||
typeof entryModule[name] === `function`
))
.map((name) => [name, entryModule[name]])
.reduce((reserved, [name, value]) => {
const staticNames = value &&
typeof value === 'object' ? Object.getOwnPropertyNames(value).filter(isStaticOrProtoName) :
typeof value === 'function' ? Object.getOwnPropertyNames(value).filter(isStaticOrProtoName) : [];
const instanceNames = (typeof value === `function` && Object.getOwnPropertyNames(value.prototype || {}) || []).filter(isStaticOrProtoName);
return [...reserved, { exportName: name, staticNames, instanceNames }];
}, []);
}
|
javascript
|
function getPublicExportedNames(entryModule) {
const fn = function() {};
const isStaticOrProtoName = (x) => (
!(x in fn) &&
(x !== `default`) &&
(x !== `undefined`) &&
(x !== `__esModule`) &&
(x !== `constructor`)
);
return Object
.getOwnPropertyNames(entryModule)
.filter((name) => name !== 'default')
.filter((name) => (
typeof entryModule[name] === `object` ||
typeof entryModule[name] === `function`
))
.map((name) => [name, entryModule[name]])
.reduce((reserved, [name, value]) => {
const staticNames = value &&
typeof value === 'object' ? Object.getOwnPropertyNames(value).filter(isStaticOrProtoName) :
typeof value === 'function' ? Object.getOwnPropertyNames(value).filter(isStaticOrProtoName) : [];
const instanceNames = (typeof value === `function` && Object.getOwnPropertyNames(value.prototype || {}) || []).filter(isStaticOrProtoName);
return [...reserved, { exportName: name, staticNames, instanceNames }];
}, []);
}
|
[
"function",
"getPublicExportedNames",
"(",
"entryModule",
")",
"{",
"const",
"fn",
"=",
"function",
"(",
")",
"{",
"}",
";",
"const",
"isStaticOrProtoName",
"=",
"(",
"x",
")",
"=>",
"(",
"!",
"(",
"x",
"in",
"fn",
")",
"&&",
"(",
"x",
"!==",
"`",
"`",
")",
"&&",
"(",
"x",
"!==",
"`",
"`",
")",
"&&",
"(",
"x",
"!==",
"`",
"`",
")",
"&&",
"(",
"x",
"!==",
"`",
"`",
")",
")",
";",
"return",
"Object",
".",
"getOwnPropertyNames",
"(",
"entryModule",
")",
".",
"filter",
"(",
"(",
"name",
")",
"=>",
"name",
"!==",
"'default'",
")",
".",
"filter",
"(",
"(",
"name",
")",
"=>",
"(",
"typeof",
"entryModule",
"[",
"name",
"]",
"===",
"`",
"`",
"||",
"typeof",
"entryModule",
"[",
"name",
"]",
"===",
"`",
"`",
")",
")",
".",
"map",
"(",
"(",
"name",
")",
"=>",
"[",
"name",
",",
"entryModule",
"[",
"name",
"]",
"]",
")",
".",
"reduce",
"(",
"(",
"reserved",
",",
"[",
"name",
",",
"value",
"]",
")",
"=>",
"{",
"const",
"staticNames",
"=",
"value",
"&&",
"typeof",
"value",
"===",
"'object'",
"?",
"Object",
".",
"getOwnPropertyNames",
"(",
"value",
")",
".",
"filter",
"(",
"isStaticOrProtoName",
")",
":",
"typeof",
"value",
"===",
"'function'",
"?",
"Object",
".",
"getOwnPropertyNames",
"(",
"value",
")",
".",
"filter",
"(",
"isStaticOrProtoName",
")",
":",
"[",
"]",
";",
"const",
"instanceNames",
"=",
"(",
"typeof",
"value",
"===",
"`",
"`",
"&&",
"Object",
".",
"getOwnPropertyNames",
"(",
"value",
".",
"prototype",
"||",
"{",
"}",
")",
"||",
"[",
"]",
")",
".",
"filter",
"(",
"isStaticOrProtoName",
")",
";",
"return",
"[",
"...",
"reserved",
",",
"{",
"exportName",
":",
"name",
",",
"staticNames",
",",
"instanceNames",
"}",
"]",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] |
Reflect on the Ix entrypoint module to build the closure externs file. Assume all the non-inherited static and prototype members of the Ix entrypoint and its direct exports are public, and should be preserved through minification.
|
[
"Reflect",
"on",
"the",
"Ix",
"entrypoint",
"module",
"to",
"build",
"the",
"closure",
"externs",
"file",
".",
"Assume",
"all",
"the",
"non",
"-",
"inherited",
"static",
"and",
"prototype",
"members",
"of",
"the",
"Ix",
"entrypoint",
"and",
"its",
"direct",
"exports",
"are",
"public",
"and",
"should",
"be",
"preserved",
"through",
"minification",
"."
] |
230791d96fe9e76e959c21a23e485e081b6bc4bb
|
https://github.com/ReactiveX/IxJS/blob/230791d96fe9e76e959c21a23e485e081b6bc4bb/gulp/closure-task.js#L160-L187
|
17,396
|
substantial/updeep
|
lib/freeze.js
|
freeze
|
function freeze(object) {
if (process.env.NODE_ENV === 'production') {
return object
}
if (process.env.UPDEEP_MODE === 'dangerously_never_freeze') {
return object
}
if (needsFreezing(object)) {
recur(object)
}
return object
}
|
javascript
|
function freeze(object) {
if (process.env.NODE_ENV === 'production') {
return object
}
if (process.env.UPDEEP_MODE === 'dangerously_never_freeze') {
return object
}
if (needsFreezing(object)) {
recur(object)
}
return object
}
|
[
"function",
"freeze",
"(",
"object",
")",
"{",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"'production'",
")",
"{",
"return",
"object",
"}",
"if",
"(",
"process",
".",
"env",
".",
"UPDEEP_MODE",
"===",
"'dangerously_never_freeze'",
")",
"{",
"return",
"object",
"}",
"if",
"(",
"needsFreezing",
"(",
"object",
")",
")",
"{",
"recur",
"(",
"object",
")",
"}",
"return",
"object",
"}"
] |
Deeply freeze a plain javascript object.
If `process.env.NODE_ENV === 'production'`, this returns the original object
without freezing.
Or if `process.env.UPDEEP_MODE === 'dangerously_never_freeze'`, this returns the original object
without freezing.
@function
@sig a -> a
@param {object} object Object to freeze.
@return {object} Frozen object, unless in production, then the same object.
|
[
"Deeply",
"freeze",
"a",
"plain",
"javascript",
"object",
"."
] |
8236f815402861f4f2f500a57305c361405e1784
|
https://github.com/substantial/updeep/blob/8236f815402861f4f2f500a57305c361405e1784/lib/freeze.js#L40-L54
|
17,397
|
substantial/updeep
|
lib/update.js
|
update
|
function update(updates, object, ...args) {
if (typeof updates === 'function') {
return updates(object, ...args)
}
if (!isPlainObject(updates)) {
return updates
}
const defaultedObject =
typeof object === 'undefined' || object === null ? {} : object
const resolvedUpdates = resolveUpdates(updates, defaultedObject)
if (isEmpty(resolvedUpdates)) {
return defaultedObject
}
if (Array.isArray(defaultedObject)) {
return updateArray(resolvedUpdates, defaultedObject).filter(
value => value !== innerOmitted
)
}
return _omitBy(
{ ...defaultedObject, ...resolvedUpdates },
value => value === innerOmitted
)
}
|
javascript
|
function update(updates, object, ...args) {
if (typeof updates === 'function') {
return updates(object, ...args)
}
if (!isPlainObject(updates)) {
return updates
}
const defaultedObject =
typeof object === 'undefined' || object === null ? {} : object
const resolvedUpdates = resolveUpdates(updates, defaultedObject)
if (isEmpty(resolvedUpdates)) {
return defaultedObject
}
if (Array.isArray(defaultedObject)) {
return updateArray(resolvedUpdates, defaultedObject).filter(
value => value !== innerOmitted
)
}
return _omitBy(
{ ...defaultedObject, ...resolvedUpdates },
value => value === innerOmitted
)
}
|
[
"function",
"update",
"(",
"updates",
",",
"object",
",",
"...",
"args",
")",
"{",
"if",
"(",
"typeof",
"updates",
"===",
"'function'",
")",
"{",
"return",
"updates",
"(",
"object",
",",
"...",
"args",
")",
"}",
"if",
"(",
"!",
"isPlainObject",
"(",
"updates",
")",
")",
"{",
"return",
"updates",
"}",
"const",
"defaultedObject",
"=",
"typeof",
"object",
"===",
"'undefined'",
"||",
"object",
"===",
"null",
"?",
"{",
"}",
":",
"object",
"const",
"resolvedUpdates",
"=",
"resolveUpdates",
"(",
"updates",
",",
"defaultedObject",
")",
"if",
"(",
"isEmpty",
"(",
"resolvedUpdates",
")",
")",
"{",
"return",
"defaultedObject",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"defaultedObject",
")",
")",
"{",
"return",
"updateArray",
"(",
"resolvedUpdates",
",",
"defaultedObject",
")",
".",
"filter",
"(",
"value",
"=>",
"value",
"!==",
"innerOmitted",
")",
"}",
"return",
"_omitBy",
"(",
"{",
"...",
"defaultedObject",
",",
"...",
"resolvedUpdates",
"}",
",",
"value",
"=>",
"value",
"===",
"innerOmitted",
")",
"}"
] |
Recursively update an object or array.
Can update with values:
update({ foo: 3 }, { foo: 1, bar: 2 });
// => { foo: 3, bar: 2 }
Or with a function:
update({ foo: x => (x + 1) }, { foo: 2 });
// => { foo: 3 }
@function
@name update
@param {Object|Function} updates
@param {Object|Array} object to update
@return {Object|Array} new object with modifications
|
[
"Recursively",
"update",
"an",
"object",
"or",
"array",
"."
] |
8236f815402861f4f2f500a57305c361405e1784
|
https://github.com/substantial/updeep/blob/8236f815402861f4f2f500a57305c361405e1784/lib/update.js#L74-L102
|
17,398
|
nbubna/store
|
dist/app.js
|
function(k) {
if (typeof k !== "string"){ k = _.stringify(k); }
return this._ns ? this._ns + k : k;
}
|
javascript
|
function(k) {
if (typeof k !== "string"){ k = _.stringify(k); }
return this._ns ? this._ns + k : k;
}
|
[
"function",
"(",
"k",
")",
"{",
"if",
"(",
"typeof",
"k",
"!==",
"\"string\"",
")",
"{",
"k",
"=",
"_",
".",
"stringify",
"(",
"k",
")",
";",
"}",
"return",
"this",
".",
"_ns",
"?",
"this",
".",
"_ns",
"+",
"k",
":",
"k",
";",
"}"
] |
internal use functions
|
[
"internal",
"use",
"functions"
] |
0d4d1ce35de6bd79c6a040e2546c87a85825868a
|
https://github.com/nbubna/store/blob/0d4d1ce35de6bd79c6a040e2546c87a85825868a/dist/app.js#L392-L395
|
|
17,399
|
pillarjs/hbs
|
lib/hbs.js
|
render_with_layout
|
function render_with_layout(template, locals, cb) {
render_file(locals, function(err, str) {
if (err) {
return cb(err);
}
locals.body = str;
var res = template(locals, handlebarsOpts);
self.async.done(function(values) {
Object.keys(values).forEach(function(id) {
res = res.replace(id, values[id]);
});
cb(null, res);
});
});
}
|
javascript
|
function render_with_layout(template, locals, cb) {
render_file(locals, function(err, str) {
if (err) {
return cb(err);
}
locals.body = str;
var res = template(locals, handlebarsOpts);
self.async.done(function(values) {
Object.keys(values).forEach(function(id) {
res = res.replace(id, values[id]);
});
cb(null, res);
});
});
}
|
[
"function",
"render_with_layout",
"(",
"template",
",",
"locals",
",",
"cb",
")",
"{",
"render_file",
"(",
"locals",
",",
"function",
"(",
"err",
",",
"str",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"locals",
".",
"body",
"=",
"str",
";",
"var",
"res",
"=",
"template",
"(",
"locals",
",",
"handlebarsOpts",
")",
";",
"self",
".",
"async",
".",
"done",
"(",
"function",
"(",
"values",
")",
"{",
"Object",
".",
"keys",
"(",
"values",
")",
".",
"forEach",
"(",
"function",
"(",
"id",
")",
"{",
"res",
"=",
"res",
".",
"replace",
"(",
"id",
",",
"values",
"[",
"id",
"]",
")",
";",
"}",
")",
";",
"cb",
"(",
"null",
",",
"res",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
render with a layout
|
[
"render",
"with",
"a",
"layout"
] |
3a8a47ec53bddf87183fb6e903d0d0cf0876c062
|
https://github.com/pillarjs/hbs/blob/3a8a47ec53bddf87183fb6e903d0d0cf0876c062/lib/hbs.js#L79-L96
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.