repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
godmodelabs/flora | lib/config-parser.js | parseBoolean | function parseBoolean(value, context) {
if (value === true || value === 'true') return true;
if (value === false || value === 'false') return false;
throw new ImplementationError(`Invalid boolean value "${value}"${context.errorContext}`);
} | javascript | function parseBoolean(value, context) {
if (value === true || value === 'true') return true;
if (value === false || value === 'false') return false;
throw new ImplementationError(`Invalid boolean value "${value}"${context.errorContext}`);
} | [
"function",
"parseBoolean",
"(",
"value",
",",
"context",
")",
"{",
"if",
"(",
"value",
"===",
"true",
"||",
"value",
"===",
"'true'",
")",
"return",
"true",
";",
"if",
"(",
"value",
"===",
"false",
"||",
"value",
"===",
"'false'",
")",
"return",
"false",
";",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"value",
"}",
"${",
"context",
".",
"errorContext",
"}",
"`",
")",
";",
"}"
] | Parses "true", true, "false", false.
@private | [
"Parses",
"true",
"true",
"false",
"false",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-parser.js#L205-L209 | train |
godmodelabs/flora | lib/config-parser.js | handleResourceContext | function handleResourceContext(attrNode, context) {
let dataSource;
let lastDataSourceName;
const errorContext = context.errorContext;
if (attrNode.resource) {
if ('subFilters' in attrNode) {
throw new ImplementationError(
'Adding subFilters for included sub-resource is not allowed' + context.errorContext
);
}
if ('primaryKey' in attrNode) {
throw new ImplementationError(
'Overwriting primaryKey for included sub-resource is not allowed' + context.errorContext
);
}
} else if (!('primaryKey' in attrNode)) {
throw new ImplementationError('Missing primaryKey' + context.errorContext);
}
if (attrNode.dataSources) {
Object.keys(attrNode.dataSources).forEach(dataSourceName => {
lastDataSourceName = dataSourceName;
context.dataSourceAttributes[dataSourceName] = [];
dataSource = attrNode.dataSources[dataSourceName];
if (dataSource.inherit) {
if (!attrNode.resource) {
throw new ImplementationError(
`DataSource "${dataSourceName}" is defined as "inherit" but has no included resource`
);
}
context.errorContext = ' in inherit' + errorContext;
dataSource.inherit = checkWhitelist(dataSource.inherit, ['true', 'inherit', 'replace'], context);
if (dataSource.inherit === 'true') {
dataSource.inherit = 'inherit';
}
context.errorContext = errorContext;
}
if (!dataSource.type && !dataSource.inherit) {
throw new ImplementationError(
`DataSource "${dataSourceName}" misses "type" option${context.errorContext}`
);
}
if (dataSource.joinParentKey) {
context.errorContext = ' in joinParentKey' + errorContext;
dataSource.joinParentKey = parsePrimaryKey(dataSource.joinParentKey, context);
context.errorContext = errorContext;
}
if (dataSource.joinChildKey) {
context.errorContext = ' in joinChildKey' + errorContext;
dataSource.joinChildKey = parsePrimaryKey(dataSource.joinChildKey, context);
context.errorContext = errorContext;
}
});
}
if (attrNode.joinVia) {
if (!attrNode.dataSources[attrNode.joinVia]) {
throw new ImplementationError(`Unknown DataSource "${attrNode.joinVia}" in joinVia` + context.errorContext);
} else {
dataSource = attrNode.dataSources[attrNode.joinVia];
if (!dataSource.joinParentKey) {
throw new ImplementationError(
`DataSource "${lastDataSourceName}" misses "joinParentKey" option` + context.errorContext
);
}
if (!dataSource.joinChildKey) {
throw new ImplementationError(
`DataSource "${lastDataSourceName}" misses "joinChildKey" option` + context.errorContext
);
}
}
}
} | javascript | function handleResourceContext(attrNode, context) {
let dataSource;
let lastDataSourceName;
const errorContext = context.errorContext;
if (attrNode.resource) {
if ('subFilters' in attrNode) {
throw new ImplementationError(
'Adding subFilters for included sub-resource is not allowed' + context.errorContext
);
}
if ('primaryKey' in attrNode) {
throw new ImplementationError(
'Overwriting primaryKey for included sub-resource is not allowed' + context.errorContext
);
}
} else if (!('primaryKey' in attrNode)) {
throw new ImplementationError('Missing primaryKey' + context.errorContext);
}
if (attrNode.dataSources) {
Object.keys(attrNode.dataSources).forEach(dataSourceName => {
lastDataSourceName = dataSourceName;
context.dataSourceAttributes[dataSourceName] = [];
dataSource = attrNode.dataSources[dataSourceName];
if (dataSource.inherit) {
if (!attrNode.resource) {
throw new ImplementationError(
`DataSource "${dataSourceName}" is defined as "inherit" but has no included resource`
);
}
context.errorContext = ' in inherit' + errorContext;
dataSource.inherit = checkWhitelist(dataSource.inherit, ['true', 'inherit', 'replace'], context);
if (dataSource.inherit === 'true') {
dataSource.inherit = 'inherit';
}
context.errorContext = errorContext;
}
if (!dataSource.type && !dataSource.inherit) {
throw new ImplementationError(
`DataSource "${dataSourceName}" misses "type" option${context.errorContext}`
);
}
if (dataSource.joinParentKey) {
context.errorContext = ' in joinParentKey' + errorContext;
dataSource.joinParentKey = parsePrimaryKey(dataSource.joinParentKey, context);
context.errorContext = errorContext;
}
if (dataSource.joinChildKey) {
context.errorContext = ' in joinChildKey' + errorContext;
dataSource.joinChildKey = parsePrimaryKey(dataSource.joinChildKey, context);
context.errorContext = errorContext;
}
});
}
if (attrNode.joinVia) {
if (!attrNode.dataSources[attrNode.joinVia]) {
throw new ImplementationError(`Unknown DataSource "${attrNode.joinVia}" in joinVia` + context.errorContext);
} else {
dataSource = attrNode.dataSources[attrNode.joinVia];
if (!dataSource.joinParentKey) {
throw new ImplementationError(
`DataSource "${lastDataSourceName}" misses "joinParentKey" option` + context.errorContext
);
}
if (!dataSource.joinChildKey) {
throw new ImplementationError(
`DataSource "${lastDataSourceName}" misses "joinChildKey" option` + context.errorContext
);
}
}
}
} | [
"function",
"handleResourceContext",
"(",
"attrNode",
",",
"context",
")",
"{",
"let",
"dataSource",
";",
"let",
"lastDataSourceName",
";",
"const",
"errorContext",
"=",
"context",
".",
"errorContext",
";",
"if",
"(",
"attrNode",
".",
"resource",
")",
"{",
"if",
"(",
"'subFilters'",
"in",
"attrNode",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"'Adding subFilters for included sub-resource is not allowed'",
"+",
"context",
".",
"errorContext",
")",
";",
"}",
"if",
"(",
"'primaryKey'",
"in",
"attrNode",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"'Overwriting primaryKey for included sub-resource is not allowed'",
"+",
"context",
".",
"errorContext",
")",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"(",
"'primaryKey'",
"in",
"attrNode",
")",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"'Missing primaryKey'",
"+",
"context",
".",
"errorContext",
")",
";",
"}",
"if",
"(",
"attrNode",
".",
"dataSources",
")",
"{",
"Object",
".",
"keys",
"(",
"attrNode",
".",
"dataSources",
")",
".",
"forEach",
"(",
"dataSourceName",
"=>",
"{",
"lastDataSourceName",
"=",
"dataSourceName",
";",
"context",
".",
"dataSourceAttributes",
"[",
"dataSourceName",
"]",
"=",
"[",
"]",
";",
"dataSource",
"=",
"attrNode",
".",
"dataSources",
"[",
"dataSourceName",
"]",
";",
"if",
"(",
"dataSource",
".",
"inherit",
")",
"{",
"if",
"(",
"!",
"attrNode",
".",
"resource",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"dataSourceName",
"}",
"`",
")",
";",
"}",
"context",
".",
"errorContext",
"=",
"' in inherit'",
"+",
"errorContext",
";",
"dataSource",
".",
"inherit",
"=",
"checkWhitelist",
"(",
"dataSource",
".",
"inherit",
",",
"[",
"'true'",
",",
"'inherit'",
",",
"'replace'",
"]",
",",
"context",
")",
";",
"if",
"(",
"dataSource",
".",
"inherit",
"===",
"'true'",
")",
"{",
"dataSource",
".",
"inherit",
"=",
"'inherit'",
";",
"}",
"context",
".",
"errorContext",
"=",
"errorContext",
";",
"}",
"if",
"(",
"!",
"dataSource",
".",
"type",
"&&",
"!",
"dataSource",
".",
"inherit",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"dataSourceName",
"}",
"${",
"context",
".",
"errorContext",
"}",
"`",
")",
";",
"}",
"if",
"(",
"dataSource",
".",
"joinParentKey",
")",
"{",
"context",
".",
"errorContext",
"=",
"' in joinParentKey'",
"+",
"errorContext",
";",
"dataSource",
".",
"joinParentKey",
"=",
"parsePrimaryKey",
"(",
"dataSource",
".",
"joinParentKey",
",",
"context",
")",
";",
"context",
".",
"errorContext",
"=",
"errorContext",
";",
"}",
"if",
"(",
"dataSource",
".",
"joinChildKey",
")",
"{",
"context",
".",
"errorContext",
"=",
"' in joinChildKey'",
"+",
"errorContext",
";",
"dataSource",
".",
"joinChildKey",
"=",
"parsePrimaryKey",
"(",
"dataSource",
".",
"joinChildKey",
",",
"context",
")",
";",
"context",
".",
"errorContext",
"=",
"errorContext",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"attrNode",
".",
"joinVia",
")",
"{",
"if",
"(",
"!",
"attrNode",
".",
"dataSources",
"[",
"attrNode",
".",
"joinVia",
"]",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"attrNode",
".",
"joinVia",
"}",
"`",
"+",
"context",
".",
"errorContext",
")",
";",
"}",
"else",
"{",
"dataSource",
"=",
"attrNode",
".",
"dataSources",
"[",
"attrNode",
".",
"joinVia",
"]",
";",
"if",
"(",
"!",
"dataSource",
".",
"joinParentKey",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"lastDataSourceName",
"}",
"`",
"+",
"context",
".",
"errorContext",
")",
";",
"}",
"if",
"(",
"!",
"dataSource",
".",
"joinChildKey",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"lastDataSourceName",
"}",
"`",
"+",
"context",
".",
"errorContext",
")",
";",
"}",
"}",
"}",
"}"
] | Handle special cases and checks for options in resource context.
@private | [
"Handle",
"special",
"cases",
"and",
"checks",
"for",
"options",
"in",
"resource",
"context",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-parser.js#L295-L376 | train |
godmodelabs/flora | lib/config-parser.js | handleAttributeContext | function handleAttributeContext(attrNode, context) {
if (!attrNode.type && attrNode.inherit !== 'inherit') attrNode.type = 'string';
if (attrNode.map) {
Object.keys(attrNode.map).forEach(mappingName => {
const mapping = attrNode.map[mappingName];
Object.keys(mapping).forEach(dataSourceName => {
if (!context.dataSourceAttributes[dataSourceName]) {
throw new ImplementationError(
`Unknown DataSource "${dataSourceName}" in map${context.errorContext}`
);
}
context.dataSourceAttributes[dataSourceName].push(mapping[dataSourceName]);
});
});
if ('value' in attrNode) {
throw new ImplementationError(
'Static "value" in combination with "map" makes no sense' + context.errorContext
);
}
}
} | javascript | function handleAttributeContext(attrNode, context) {
if (!attrNode.type && attrNode.inherit !== 'inherit') attrNode.type = 'string';
if (attrNode.map) {
Object.keys(attrNode.map).forEach(mappingName => {
const mapping = attrNode.map[mappingName];
Object.keys(mapping).forEach(dataSourceName => {
if (!context.dataSourceAttributes[dataSourceName]) {
throw new ImplementationError(
`Unknown DataSource "${dataSourceName}" in map${context.errorContext}`
);
}
context.dataSourceAttributes[dataSourceName].push(mapping[dataSourceName]);
});
});
if ('value' in attrNode) {
throw new ImplementationError(
'Static "value" in combination with "map" makes no sense' + context.errorContext
);
}
}
} | [
"function",
"handleAttributeContext",
"(",
"attrNode",
",",
"context",
")",
"{",
"if",
"(",
"!",
"attrNode",
".",
"type",
"&&",
"attrNode",
".",
"inherit",
"!==",
"'inherit'",
")",
"attrNode",
".",
"type",
"=",
"'string'",
";",
"if",
"(",
"attrNode",
".",
"map",
")",
"{",
"Object",
".",
"keys",
"(",
"attrNode",
".",
"map",
")",
".",
"forEach",
"(",
"mappingName",
"=>",
"{",
"const",
"mapping",
"=",
"attrNode",
".",
"map",
"[",
"mappingName",
"]",
";",
"Object",
".",
"keys",
"(",
"mapping",
")",
".",
"forEach",
"(",
"dataSourceName",
"=>",
"{",
"if",
"(",
"!",
"context",
".",
"dataSourceAttributes",
"[",
"dataSourceName",
"]",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"dataSourceName",
"}",
"${",
"context",
".",
"errorContext",
"}",
"`",
")",
";",
"}",
"context",
".",
"dataSourceAttributes",
"[",
"dataSourceName",
"]",
".",
"push",
"(",
"mapping",
"[",
"dataSourceName",
"]",
")",
";",
"}",
")",
";",
"}",
")",
";",
"if",
"(",
"'value'",
"in",
"attrNode",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"'Static \"value\" in combination with \"map\" makes no sense'",
"+",
"context",
".",
"errorContext",
")",
";",
"}",
"}",
"}"
] | Handle special cases and checks for options in attribute context.
@private | [
"Handle",
"special",
"cases",
"and",
"checks",
"for",
"options",
"in",
"attribute",
"context",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-parser.js#L383-L407 | train |
godmodelabs/flora | lib/config-parser.js | resolveKey | function resolveKey(key, attrNode, options, context) {
const resolvedKey = {};
key.forEach(keyAttrPath => {
const keyAttrNode = getLocalAttribute(keyAttrPath, attrNode, context);
if (keyAttrNode.multiValued) {
if (!options.allowMultiValued) {
throw new ImplementationError(
`Key attribute "${keyAttrPath.join('.')}" ` + `must not be multiValued${context.errorContext}`
);
}
if (key.length > 1) {
throw new ImplementationError(
`Composite key attribute "${keyAttrPath.join('.')}" ` +
`must not be multiValued${context.errorContext}`
);
}
}
if (keyAttrNode.map) {
Object.keys(keyAttrNode.map.default).forEach(dataSourceName => {
if (!resolvedKey[dataSourceName]) resolvedKey[dataSourceName] = [];
resolvedKey[dataSourceName].push(keyAttrNode.map.default[dataSourceName]);
});
}
if (options.neededDataSources) {
options.neededDataSources.forEach(neededDataSource => {
if (!keyAttrNode.map || !keyAttrNode.map.default[neededDataSource]) {
throw new ImplementationError(
`Key attribute "${keyAttrPath.join('.')}" ` +
`is not mapped to "${neededDataSource}" DataSource${context.errorContext}`
);
}
});
}
});
// remove DataSources with incomplete keys:
Object.keys(resolvedKey).forEach(dataSourceName => {
if (resolvedKey[dataSourceName].length !== key.length) {
delete resolvedKey[dataSourceName];
}
});
if (Object.keys(resolvedKey).length < 1) {
throw new ImplementationError('Key is not mappable to a single DataSource' + context.errorContext);
}
return resolvedKey;
} | javascript | function resolveKey(key, attrNode, options, context) {
const resolvedKey = {};
key.forEach(keyAttrPath => {
const keyAttrNode = getLocalAttribute(keyAttrPath, attrNode, context);
if (keyAttrNode.multiValued) {
if (!options.allowMultiValued) {
throw new ImplementationError(
`Key attribute "${keyAttrPath.join('.')}" ` + `must not be multiValued${context.errorContext}`
);
}
if (key.length > 1) {
throw new ImplementationError(
`Composite key attribute "${keyAttrPath.join('.')}" ` +
`must not be multiValued${context.errorContext}`
);
}
}
if (keyAttrNode.map) {
Object.keys(keyAttrNode.map.default).forEach(dataSourceName => {
if (!resolvedKey[dataSourceName]) resolvedKey[dataSourceName] = [];
resolvedKey[dataSourceName].push(keyAttrNode.map.default[dataSourceName]);
});
}
if (options.neededDataSources) {
options.neededDataSources.forEach(neededDataSource => {
if (!keyAttrNode.map || !keyAttrNode.map.default[neededDataSource]) {
throw new ImplementationError(
`Key attribute "${keyAttrPath.join('.')}" ` +
`is not mapped to "${neededDataSource}" DataSource${context.errorContext}`
);
}
});
}
});
// remove DataSources with incomplete keys:
Object.keys(resolvedKey).forEach(dataSourceName => {
if (resolvedKey[dataSourceName].length !== key.length) {
delete resolvedKey[dataSourceName];
}
});
if (Object.keys(resolvedKey).length < 1) {
throw new ImplementationError('Key is not mappable to a single DataSource' + context.errorContext);
}
return resolvedKey;
} | [
"function",
"resolveKey",
"(",
"key",
",",
"attrNode",
",",
"options",
",",
"context",
")",
"{",
"const",
"resolvedKey",
"=",
"{",
"}",
";",
"key",
".",
"forEach",
"(",
"keyAttrPath",
"=>",
"{",
"const",
"keyAttrNode",
"=",
"getLocalAttribute",
"(",
"keyAttrPath",
",",
"attrNode",
",",
"context",
")",
";",
"if",
"(",
"keyAttrNode",
".",
"multiValued",
")",
"{",
"if",
"(",
"!",
"options",
".",
"allowMultiValued",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"keyAttrPath",
".",
"join",
"(",
"'.'",
")",
"}",
"`",
"+",
"`",
"${",
"context",
".",
"errorContext",
"}",
"`",
")",
";",
"}",
"if",
"(",
"key",
".",
"length",
">",
"1",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"keyAttrPath",
".",
"join",
"(",
"'.'",
")",
"}",
"`",
"+",
"`",
"${",
"context",
".",
"errorContext",
"}",
"`",
")",
";",
"}",
"}",
"if",
"(",
"keyAttrNode",
".",
"map",
")",
"{",
"Object",
".",
"keys",
"(",
"keyAttrNode",
".",
"map",
".",
"default",
")",
".",
"forEach",
"(",
"dataSourceName",
"=>",
"{",
"if",
"(",
"!",
"resolvedKey",
"[",
"dataSourceName",
"]",
")",
"resolvedKey",
"[",
"dataSourceName",
"]",
"=",
"[",
"]",
";",
"resolvedKey",
"[",
"dataSourceName",
"]",
".",
"push",
"(",
"keyAttrNode",
".",
"map",
".",
"default",
"[",
"dataSourceName",
"]",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"options",
".",
"neededDataSources",
")",
"{",
"options",
".",
"neededDataSources",
".",
"forEach",
"(",
"neededDataSource",
"=>",
"{",
"if",
"(",
"!",
"keyAttrNode",
".",
"map",
"||",
"!",
"keyAttrNode",
".",
"map",
".",
"default",
"[",
"neededDataSource",
"]",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"`",
"${",
"keyAttrPath",
".",
"join",
"(",
"'.'",
")",
"}",
"`",
"+",
"`",
"${",
"neededDataSource",
"}",
"${",
"context",
".",
"errorContext",
"}",
"`",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"Object",
".",
"keys",
"(",
"resolvedKey",
")",
".",
"forEach",
"(",
"dataSourceName",
"=>",
"{",
"if",
"(",
"resolvedKey",
"[",
"dataSourceName",
"]",
".",
"length",
"!==",
"key",
".",
"length",
")",
"{",
"delete",
"resolvedKey",
"[",
"dataSourceName",
"]",
";",
"}",
"}",
")",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"resolvedKey",
")",
".",
"length",
"<",
"1",
")",
"{",
"throw",
"new",
"ImplementationError",
"(",
"'Key is not mappable to a single DataSource'",
"+",
"context",
".",
"errorContext",
")",
";",
"}",
"return",
"resolvedKey",
";",
"}"
] | Resolve key attributes per DataSource.
@private | [
"Resolve",
"key",
"attributes",
"per",
"DataSource",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-parser.js#L436-L487 | train |
godmodelabs/flora | lib/config-parser.js | resolvePrimaryKey | function resolvePrimaryKey(attrNode, context) {
const errorContext = context.errorContext;
context.errorContext = ' in primaryKey' + errorContext;
const neededDataSources = [];
Object.keys(attrNode.dataSources).forEach(dataSourceName => {
if (attrNode.dataSources[dataSourceName].joinParentKey) return;
neededDataSources.push(dataSourceName);
});
attrNode.resolvedPrimaryKey = resolveKey(
attrNode.primaryKey,
attrNode,
{
neededDataSources,
allowMultiValued: false
},
context
);
// enable "equal" filter:
attrNode.primaryKey.forEach(primaryKeyAttrPath => {
const primaryKeyAttrNode = getLocalAttribute(primaryKeyAttrPath, attrNode, context);
if (!primaryKeyAttrNode.filter && attrNode.primaryKey.length === 1) {
if (!primaryKeyAttrNode.hidden) {
primaryKeyAttrNode.filter = ['equal'];
}
}
});
context.errorContext = errorContext;
} | javascript | function resolvePrimaryKey(attrNode, context) {
const errorContext = context.errorContext;
context.errorContext = ' in primaryKey' + errorContext;
const neededDataSources = [];
Object.keys(attrNode.dataSources).forEach(dataSourceName => {
if (attrNode.dataSources[dataSourceName].joinParentKey) return;
neededDataSources.push(dataSourceName);
});
attrNode.resolvedPrimaryKey = resolveKey(
attrNode.primaryKey,
attrNode,
{
neededDataSources,
allowMultiValued: false
},
context
);
// enable "equal" filter:
attrNode.primaryKey.forEach(primaryKeyAttrPath => {
const primaryKeyAttrNode = getLocalAttribute(primaryKeyAttrPath, attrNode, context);
if (!primaryKeyAttrNode.filter && attrNode.primaryKey.length === 1) {
if (!primaryKeyAttrNode.hidden) {
primaryKeyAttrNode.filter = ['equal'];
}
}
});
context.errorContext = errorContext;
} | [
"function",
"resolvePrimaryKey",
"(",
"attrNode",
",",
"context",
")",
"{",
"const",
"errorContext",
"=",
"context",
".",
"errorContext",
";",
"context",
".",
"errorContext",
"=",
"' in primaryKey'",
"+",
"errorContext",
";",
"const",
"neededDataSources",
"=",
"[",
"]",
";",
"Object",
".",
"keys",
"(",
"attrNode",
".",
"dataSources",
")",
".",
"forEach",
"(",
"dataSourceName",
"=>",
"{",
"if",
"(",
"attrNode",
".",
"dataSources",
"[",
"dataSourceName",
"]",
".",
"joinParentKey",
")",
"return",
";",
"neededDataSources",
".",
"push",
"(",
"dataSourceName",
")",
";",
"}",
")",
";",
"attrNode",
".",
"resolvedPrimaryKey",
"=",
"resolveKey",
"(",
"attrNode",
".",
"primaryKey",
",",
"attrNode",
",",
"{",
"neededDataSources",
",",
"allowMultiValued",
":",
"false",
"}",
",",
"context",
")",
";",
"attrNode",
".",
"primaryKey",
".",
"forEach",
"(",
"primaryKeyAttrPath",
"=>",
"{",
"const",
"primaryKeyAttrNode",
"=",
"getLocalAttribute",
"(",
"primaryKeyAttrPath",
",",
"attrNode",
",",
"context",
")",
";",
"if",
"(",
"!",
"primaryKeyAttrNode",
".",
"filter",
"&&",
"attrNode",
".",
"primaryKey",
".",
"length",
"===",
"1",
")",
"{",
"if",
"(",
"!",
"primaryKeyAttrNode",
".",
"hidden",
")",
"{",
"primaryKeyAttrNode",
".",
"filter",
"=",
"[",
"'equal'",
"]",
";",
"}",
"}",
"}",
")",
";",
"context",
".",
"errorContext",
"=",
"errorContext",
";",
"}"
] | Resolve primaryKey per DataSource and fail if not all DataSources have the complete primaryKey.
Enable "equal" filter for visible non-composite primary keys by default.
@private | [
"Resolve",
"primaryKey",
"per",
"DataSource",
"and",
"fail",
"if",
"not",
"all",
"DataSources",
"have",
"the",
"complete",
"primaryKey",
".",
"Enable",
"equal",
"filter",
"for",
"visible",
"non",
"-",
"composite",
"primary",
"keys",
"by",
"default",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-parser.js#L663-L696 | train |
godmodelabs/flora | lib/config-parser.js | processNode | function processNode(attrNode, context) {
const isMainResource = context.attrPath.length === 0;
// identify/handle options-contexts: resource/sub-resource, nested-attribute, attribute:
if (attrNode.dataSources || attrNode.resource || isMainResource) {
context.errorContext = getErrorContext(isMainResource ? 'resource' : 'sub-resource', context);
context.subAttrPath = [];
context.dataSourceAttributes = {};
if (isMainResource) {
parseNode(
attrNode,
{
dataSources: null,
subFilters: parseSubFilters,
resource: checkResourceName,
primaryKey: parsePrimaryKey,
depends: parseDepends,
deprecated: parseBoolean,
permission: null,
attributes: null,
defaultLimit: parseInteger,
maxLimit: parseInteger,
defaultOrder: requestParser.order
},
context
);
} else {
parseNode(
attrNode,
{
dataSources: null,
subFilters: parseSubFilters,
resource: checkResourceName,
primaryKey: parsePrimaryKey,
parentKey: parseRelationKey,
childKey: parseRelationKey,
many: parseBoolean,
depends: parseDepends,
hidden: parseBoolean,
deprecated: parseBoolean,
permission: null,
joinVia: checkIdentifier,
attributes: null,
defaultLimit: parseInteger,
maxLimit: parseInteger,
defaultOrder: requestParser.order
},
context
);
}
handleResourceContext(attrNode, context);
} else if (attrNode.attributes) {
context.errorContext = getErrorContext('nested-attribute', context);
parseNode(
attrNode,
{
depends: parseDepends,
hidden: parseBoolean,
deprecated: parseBoolean,
permission: null,
attributes: null
},
context
);
// no context-specific special-cases for nested-attributes
} else {
context.errorContext = getErrorContext('attribute', context);
// prepare standard-mapping - except for fixed values and inherited attributes:
if (!attrNode.map && !('value' in attrNode) && attrNode.inherit !== 'inherit') {
attrNode.map = null; // "null" means "set standard-mapping in parseMap()"
}
parseNode(
attrNode,
{
type: parseType,
multiValued: parseBoolean,
storedType: parseStoredType,
delimiter: null,
map: parseMap,
filter: parseFilter,
order: parseOrder,
value: parseStaticValue,
depends: parseDepends,
hidden: parseBoolean,
deprecated: parseBoolean,
permission: null,
inherit: parseInherit
},
context
);
handleAttributeContext(attrNode, context);
}
// recursion:
if (attrNode.attributes) {
Object.keys(attrNode.attributes).forEach(subAttrName => {
const subAttrNode = attrNode.attributes[subAttrName];
const subContext = Object.assign({}, context);
subContext.attrPath = context.attrPath.concat([subAttrName]);
subContext.subAttrPath = context.subAttrPath.concat([subAttrName]);
processNode(subAttrNode, subContext);
});
}
if (attrNode.dataSources) {
if (attrNode.primaryKey) resolvePrimaryKey(attrNode, context);
prepareDataSources(attrNode, context);
}
} | javascript | function processNode(attrNode, context) {
const isMainResource = context.attrPath.length === 0;
// identify/handle options-contexts: resource/sub-resource, nested-attribute, attribute:
if (attrNode.dataSources || attrNode.resource || isMainResource) {
context.errorContext = getErrorContext(isMainResource ? 'resource' : 'sub-resource', context);
context.subAttrPath = [];
context.dataSourceAttributes = {};
if (isMainResource) {
parseNode(
attrNode,
{
dataSources: null,
subFilters: parseSubFilters,
resource: checkResourceName,
primaryKey: parsePrimaryKey,
depends: parseDepends,
deprecated: parseBoolean,
permission: null,
attributes: null,
defaultLimit: parseInteger,
maxLimit: parseInteger,
defaultOrder: requestParser.order
},
context
);
} else {
parseNode(
attrNode,
{
dataSources: null,
subFilters: parseSubFilters,
resource: checkResourceName,
primaryKey: parsePrimaryKey,
parentKey: parseRelationKey,
childKey: parseRelationKey,
many: parseBoolean,
depends: parseDepends,
hidden: parseBoolean,
deprecated: parseBoolean,
permission: null,
joinVia: checkIdentifier,
attributes: null,
defaultLimit: parseInteger,
maxLimit: parseInteger,
defaultOrder: requestParser.order
},
context
);
}
handleResourceContext(attrNode, context);
} else if (attrNode.attributes) {
context.errorContext = getErrorContext('nested-attribute', context);
parseNode(
attrNode,
{
depends: parseDepends,
hidden: parseBoolean,
deprecated: parseBoolean,
permission: null,
attributes: null
},
context
);
// no context-specific special-cases for nested-attributes
} else {
context.errorContext = getErrorContext('attribute', context);
// prepare standard-mapping - except for fixed values and inherited attributes:
if (!attrNode.map && !('value' in attrNode) && attrNode.inherit !== 'inherit') {
attrNode.map = null; // "null" means "set standard-mapping in parseMap()"
}
parseNode(
attrNode,
{
type: parseType,
multiValued: parseBoolean,
storedType: parseStoredType,
delimiter: null,
map: parseMap,
filter: parseFilter,
order: parseOrder,
value: parseStaticValue,
depends: parseDepends,
hidden: parseBoolean,
deprecated: parseBoolean,
permission: null,
inherit: parseInherit
},
context
);
handleAttributeContext(attrNode, context);
}
// recursion:
if (attrNode.attributes) {
Object.keys(attrNode.attributes).forEach(subAttrName => {
const subAttrNode = attrNode.attributes[subAttrName];
const subContext = Object.assign({}, context);
subContext.attrPath = context.attrPath.concat([subAttrName]);
subContext.subAttrPath = context.subAttrPath.concat([subAttrName]);
processNode(subAttrNode, subContext);
});
}
if (attrNode.dataSources) {
if (attrNode.primaryKey) resolvePrimaryKey(attrNode, context);
prepareDataSources(attrNode, context);
}
} | [
"function",
"processNode",
"(",
"attrNode",
",",
"context",
")",
"{",
"const",
"isMainResource",
"=",
"context",
".",
"attrPath",
".",
"length",
"===",
"0",
";",
"if",
"(",
"attrNode",
".",
"dataSources",
"||",
"attrNode",
".",
"resource",
"||",
"isMainResource",
")",
"{",
"context",
".",
"errorContext",
"=",
"getErrorContext",
"(",
"isMainResource",
"?",
"'resource'",
":",
"'sub-resource'",
",",
"context",
")",
";",
"context",
".",
"subAttrPath",
"=",
"[",
"]",
";",
"context",
".",
"dataSourceAttributes",
"=",
"{",
"}",
";",
"if",
"(",
"isMainResource",
")",
"{",
"parseNode",
"(",
"attrNode",
",",
"{",
"dataSources",
":",
"null",
",",
"subFilters",
":",
"parseSubFilters",
",",
"resource",
":",
"checkResourceName",
",",
"primaryKey",
":",
"parsePrimaryKey",
",",
"depends",
":",
"parseDepends",
",",
"deprecated",
":",
"parseBoolean",
",",
"permission",
":",
"null",
",",
"attributes",
":",
"null",
",",
"defaultLimit",
":",
"parseInteger",
",",
"maxLimit",
":",
"parseInteger",
",",
"defaultOrder",
":",
"requestParser",
".",
"order",
"}",
",",
"context",
")",
";",
"}",
"else",
"{",
"parseNode",
"(",
"attrNode",
",",
"{",
"dataSources",
":",
"null",
",",
"subFilters",
":",
"parseSubFilters",
",",
"resource",
":",
"checkResourceName",
",",
"primaryKey",
":",
"parsePrimaryKey",
",",
"parentKey",
":",
"parseRelationKey",
",",
"childKey",
":",
"parseRelationKey",
",",
"many",
":",
"parseBoolean",
",",
"depends",
":",
"parseDepends",
",",
"hidden",
":",
"parseBoolean",
",",
"deprecated",
":",
"parseBoolean",
",",
"permission",
":",
"null",
",",
"joinVia",
":",
"checkIdentifier",
",",
"attributes",
":",
"null",
",",
"defaultLimit",
":",
"parseInteger",
",",
"maxLimit",
":",
"parseInteger",
",",
"defaultOrder",
":",
"requestParser",
".",
"order",
"}",
",",
"context",
")",
";",
"}",
"handleResourceContext",
"(",
"attrNode",
",",
"context",
")",
";",
"}",
"else",
"if",
"(",
"attrNode",
".",
"attributes",
")",
"{",
"context",
".",
"errorContext",
"=",
"getErrorContext",
"(",
"'nested-attribute'",
",",
"context",
")",
";",
"parseNode",
"(",
"attrNode",
",",
"{",
"depends",
":",
"parseDepends",
",",
"hidden",
":",
"parseBoolean",
",",
"deprecated",
":",
"parseBoolean",
",",
"permission",
":",
"null",
",",
"attributes",
":",
"null",
"}",
",",
"context",
")",
";",
"}",
"else",
"{",
"context",
".",
"errorContext",
"=",
"getErrorContext",
"(",
"'attribute'",
",",
"context",
")",
";",
"if",
"(",
"!",
"attrNode",
".",
"map",
"&&",
"!",
"(",
"'value'",
"in",
"attrNode",
")",
"&&",
"attrNode",
".",
"inherit",
"!==",
"'inherit'",
")",
"{",
"attrNode",
".",
"map",
"=",
"null",
";",
"}",
"parseNode",
"(",
"attrNode",
",",
"{",
"type",
":",
"parseType",
",",
"multiValued",
":",
"parseBoolean",
",",
"storedType",
":",
"parseStoredType",
",",
"delimiter",
":",
"null",
",",
"map",
":",
"parseMap",
",",
"filter",
":",
"parseFilter",
",",
"order",
":",
"parseOrder",
",",
"value",
":",
"parseStaticValue",
",",
"depends",
":",
"parseDepends",
",",
"hidden",
":",
"parseBoolean",
",",
"deprecated",
":",
"parseBoolean",
",",
"permission",
":",
"null",
",",
"inherit",
":",
"parseInherit",
"}",
",",
"context",
")",
";",
"handleAttributeContext",
"(",
"attrNode",
",",
"context",
")",
";",
"}",
"if",
"(",
"attrNode",
".",
"attributes",
")",
"{",
"Object",
".",
"keys",
"(",
"attrNode",
".",
"attributes",
")",
".",
"forEach",
"(",
"subAttrName",
"=>",
"{",
"const",
"subAttrNode",
"=",
"attrNode",
".",
"attributes",
"[",
"subAttrName",
"]",
";",
"const",
"subContext",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"context",
")",
";",
"subContext",
".",
"attrPath",
"=",
"context",
".",
"attrPath",
".",
"concat",
"(",
"[",
"subAttrName",
"]",
")",
";",
"subContext",
".",
"subAttrPath",
"=",
"context",
".",
"subAttrPath",
".",
"concat",
"(",
"[",
"subAttrName",
"]",
")",
";",
"processNode",
"(",
"subAttrNode",
",",
"subContext",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"attrNode",
".",
"dataSources",
")",
"{",
"if",
"(",
"attrNode",
".",
"primaryKey",
")",
"resolvePrimaryKey",
"(",
"attrNode",
",",
"context",
")",
";",
"prepareDataSources",
"(",
"attrNode",
",",
"context",
")",
";",
"}",
"}"
] | Recursive iteration over one resource.
@param {Object} attrNode
@param {Object} context
@private | [
"Recursive",
"iteration",
"over",
"one",
"resource",
"."
] | a723b860a75dc9e09e1a4e6115b8833e6c621a51 | https://github.com/godmodelabs/flora/blob/a723b860a75dc9e09e1a4e6115b8833e6c621a51/lib/config-parser.js#L705-L822 | train |
vseryakov/backendjs | web/js/knockout-mapping.js | getPropertyName | function getPropertyName(parentName, parent, indexer) {
var propertyName = parentName || "";
if (exports.getType(parent) === "array") {
if (parentName) {
propertyName += "[" + indexer + "]";
}
} else {
if (parentName) {
propertyName += ".";
}
propertyName += indexer;
}
return propertyName;
} | javascript | function getPropertyName(parentName, parent, indexer) {
var propertyName = parentName || "";
if (exports.getType(parent) === "array") {
if (parentName) {
propertyName += "[" + indexer + "]";
}
} else {
if (parentName) {
propertyName += ".";
}
propertyName += indexer;
}
return propertyName;
} | [
"function",
"getPropertyName",
"(",
"parentName",
",",
"parent",
",",
"indexer",
")",
"{",
"var",
"propertyName",
"=",
"parentName",
"||",
"\"\"",
";",
"if",
"(",
"exports",
".",
"getType",
"(",
"parent",
")",
"===",
"\"array\"",
")",
"{",
"if",
"(",
"parentName",
")",
"{",
"propertyName",
"+=",
"\"[\"",
"+",
"indexer",
"+",
"\"]\"",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"parentName",
")",
"{",
"propertyName",
"+=",
"\".\"",
";",
"}",
"propertyName",
"+=",
"indexer",
";",
"}",
"return",
"propertyName",
";",
"}"
] | Based on the parentName, this creates a fully classified name of a property | [
"Based",
"on",
"the",
"parentName",
"this",
"creates",
"a",
"fully",
"classified",
"name",
"of",
"a",
"property"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/web/js/knockout-mapping.js#L699-L712 | train |
vseryakov/backendjs | lib/aws_dynamodbstreams.js | deps | function deps(s, p) {
if (!shards.map[p] || !shards.map[p].ParentShardId) return;
shards.deps[s] = lib.toFlags("add", shards.deps[s], shards.map[p].ParentShardId);
deps(s, shards.map[p].ParentShardId);
} | javascript | function deps(s, p) {
if (!shards.map[p] || !shards.map[p].ParentShardId) return;
shards.deps[s] = lib.toFlags("add", shards.deps[s], shards.map[p].ParentShardId);
deps(s, shards.map[p].ParentShardId);
} | [
"function",
"deps",
"(",
"s",
",",
"p",
")",
"{",
"if",
"(",
"!",
"shards",
".",
"map",
"[",
"p",
"]",
"||",
"!",
"shards",
".",
"map",
"[",
"p",
"]",
".",
"ParentShardId",
")",
"return",
";",
"shards",
".",
"deps",
"[",
"s",
"]",
"=",
"lib",
".",
"toFlags",
"(",
"\"add\"",
",",
"shards",
".",
"deps",
"[",
"s",
"]",
",",
"shards",
".",
"map",
"[",
"p",
"]",
".",
"ParentShardId",
")",
";",
"deps",
"(",
"s",
",",
"shards",
".",
"map",
"[",
"p",
"]",
".",
"ParentShardId",
")",
";",
"}"
] | For each shard keep all dependencies including parent's dependencies in one list for fast checks | [
"For",
"each",
"shard",
"keep",
"all",
"dependencies",
"including",
"parent",
"s",
"dependencies",
"in",
"one",
"list",
"for",
"fast",
"checks"
] | 7c7570a5343608912a47971f49340e2b28ce3935 | https://github.com/vseryakov/backendjs/blob/7c7570a5343608912a47971f49340e2b28ce3935/lib/aws_dynamodbstreams.js#L217-L221 | train |
mattmcmanus/dox-foundation | lib/dox-foundation.js | buildStructureForFile | function buildStructureForFile(file) {
var names = [];
var targetLink;
if (file.dox.length === 0) { return false; }
file.dox.forEach(function(method){
if (method.ctx && !method.ignore) { names.push(method.ctx.name); }
});
// How deep is your love?
// If the splitted currentFile (the file we are currently rendering) path got one folder
// in the path or more, add ../ for each level found
if(file.currentFile && file.currentFile.split(path.sep).length > 1 ){
// Depth of current file
var depth = file.currentFile.split(path.sep).length,
// Create a prefix with n "../"
prefix = new Array(depth).join('../');
// Set up target link with prefix
targetLink = prefix + file.targetFile;
} else {
// Link does not have to be altered
targetLink = file.targetFile;
}
return {
source: {
full: file.sourceFile,
dir: path.dirname(file.sourceFile),
file: path.basename(file.sourceFile)
},
target: file.targetFile,
methods: names,
link : targetLink
};
} | javascript | function buildStructureForFile(file) {
var names = [];
var targetLink;
if (file.dox.length === 0) { return false; }
file.dox.forEach(function(method){
if (method.ctx && !method.ignore) { names.push(method.ctx.name); }
});
// How deep is your love?
// If the splitted currentFile (the file we are currently rendering) path got one folder
// in the path or more, add ../ for each level found
if(file.currentFile && file.currentFile.split(path.sep).length > 1 ){
// Depth of current file
var depth = file.currentFile.split(path.sep).length,
// Create a prefix with n "../"
prefix = new Array(depth).join('../');
// Set up target link with prefix
targetLink = prefix + file.targetFile;
} else {
// Link does not have to be altered
targetLink = file.targetFile;
}
return {
source: {
full: file.sourceFile,
dir: path.dirname(file.sourceFile),
file: path.basename(file.sourceFile)
},
target: file.targetFile,
methods: names,
link : targetLink
};
} | [
"function",
"buildStructureForFile",
"(",
"file",
")",
"{",
"var",
"names",
"=",
"[",
"]",
";",
"var",
"targetLink",
";",
"if",
"(",
"file",
".",
"dox",
".",
"length",
"===",
"0",
")",
"{",
"return",
"false",
";",
"}",
"file",
".",
"dox",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"if",
"(",
"method",
".",
"ctx",
"&&",
"!",
"method",
".",
"ignore",
")",
"{",
"names",
".",
"push",
"(",
"method",
".",
"ctx",
".",
"name",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"file",
".",
"currentFile",
"&&",
"file",
".",
"currentFile",
".",
"split",
"(",
"path",
".",
"sep",
")",
".",
"length",
">",
"1",
")",
"{",
"var",
"depth",
"=",
"file",
".",
"currentFile",
".",
"split",
"(",
"path",
".",
"sep",
")",
".",
"length",
",",
"prefix",
"=",
"new",
"Array",
"(",
"depth",
")",
".",
"join",
"(",
"'../'",
")",
";",
"targetLink",
"=",
"prefix",
"+",
"file",
".",
"targetFile",
";",
"}",
"else",
"{",
"targetLink",
"=",
"file",
".",
"targetFile",
";",
"}",
"return",
"{",
"source",
":",
"{",
"full",
":",
"file",
".",
"sourceFile",
",",
"dir",
":",
"path",
".",
"dirname",
"(",
"file",
".",
"sourceFile",
")",
",",
"file",
":",
"path",
".",
"basename",
"(",
"file",
".",
"sourceFile",
")",
"}",
",",
"target",
":",
"file",
".",
"targetFile",
",",
"methods",
":",
"names",
",",
"link",
":",
"targetLink",
"}",
";",
"}"
] | Return a list of methods for the side navigation
@param {Object} file
@return {Object} Object formatted for template nav helper
@api private | [
"Return",
"a",
"list",
"of",
"methods",
"for",
"the",
"side",
"navigation"
] | 1d3aee327c87cb6578781959c6f81d40cd6dbac1 | https://github.com/mattmcmanus/dox-foundation/blob/1d3aee327c87cb6578781959c6f81d40cd6dbac1/lib/dox-foundation.js#L34-L69 | train |
mattdesl/ghrepo | cmd.js | commit | function commit(result) {
var url = result.html_url
//user opted not to commit anything
if (argv.b || argv.bare) {
return Promise.resolve(url)
}
return getMessage().then(function(message) {
return gitCommit({
message: message,
url: url + '.git'
}).catch(function() {
console.warn(chalk.dim("git commands ignored"))
return Promise.resolve(url)
}).then(function() {
return url
})
})
} | javascript | function commit(result) {
var url = result.html_url
//user opted not to commit anything
if (argv.b || argv.bare) {
return Promise.resolve(url)
}
return getMessage().then(function(message) {
return gitCommit({
message: message,
url: url + '.git'
}).catch(function() {
console.warn(chalk.dim("git commands ignored"))
return Promise.resolve(url)
}).then(function() {
return url
})
})
} | [
"function",
"commit",
"(",
"result",
")",
"{",
"var",
"url",
"=",
"result",
".",
"html_url",
"if",
"(",
"argv",
".",
"b",
"||",
"argv",
".",
"bare",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"url",
")",
"}",
"return",
"getMessage",
"(",
")",
".",
"then",
"(",
"function",
"(",
"message",
")",
"{",
"return",
"gitCommit",
"(",
"{",
"message",
":",
"message",
",",
"url",
":",
"url",
"+",
"'.git'",
"}",
")",
".",
"catch",
"(",
"function",
"(",
")",
"{",
"console",
".",
"warn",
"(",
"chalk",
".",
"dim",
"(",
"\"git commands ignored\"",
")",
")",
"return",
"Promise",
".",
"resolve",
"(",
"url",
")",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"url",
"}",
")",
"}",
")",
"}"
] | commits current working dir, resolves to html_url | [
"commits",
"current",
"working",
"dir",
"resolves",
"to",
"html_url"
] | 1d993a9ed287f30e3e7f5edeaf6235785e4df739 | https://github.com/mattdesl/ghrepo/blob/1d993a9ed287f30e3e7f5edeaf6235785e4df739/cmd.js#L111-L128 | train |
pixelunion/jquery.trend | jquery.trend.js | function(s) {
s = s.replace(/\s/, "");
var v = window.parseFloat(s);
return s.match(/[^m]s$/i)
? v * 1000
: v;
} | javascript | function(s) {
s = s.replace(/\s/, "");
var v = window.parseFloat(s);
return s.match(/[^m]s$/i)
? v * 1000
: v;
} | [
"function",
"(",
"s",
")",
"{",
"s",
"=",
"s",
".",
"replace",
"(",
"/",
"\\s",
"/",
",",
"\"\"",
")",
";",
"var",
"v",
"=",
"window",
".",
"parseFloat",
"(",
"s",
")",
";",
"return",
"s",
".",
"match",
"(",
"/",
"[^m]s$",
"/",
"i",
")",
"?",
"v",
"*",
"1000",
":",
"v",
";",
"}"
] | Parses a CSS time value into milliseconds. | [
"Parses",
"a",
"CSS",
"time",
"value",
"into",
"milliseconds",
"."
] | 79b0d05692de78f6b5e2dbc0f90219d2e245687b | https://github.com/pixelunion/jquery.trend/blob/79b0d05692de78f6b5e2dbc0f90219d2e245687b/jquery.trend.js#L45-L52 | train |
|
pixelunion/jquery.trend | jquery.trend.js | function(el, properties) {
var duration = 0;
for (var i = 0; i < properties.length; i++) {
// Get raw CSS value
var value = el.css(properties[i]);
if (!value) continue;
// Multiple transitions--pick the longest
if (value.indexOf(",") !== -1) {
var values = value.split(",");
var durations = (function(){
var results = [];
for (var i = 0; i < values.length; i++) {
var duration = parseTime(values[i]);
results.push(duration);
}
return results;
})();
duration = Math.max.apply(Math, durations);
}
// Single transition
else {
duration = parseTime(value);
}
// Accept first vaue
break;
}
return duration;
} | javascript | function(el, properties) {
var duration = 0;
for (var i = 0; i < properties.length; i++) {
// Get raw CSS value
var value = el.css(properties[i]);
if (!value) continue;
// Multiple transitions--pick the longest
if (value.indexOf(",") !== -1) {
var values = value.split(",");
var durations = (function(){
var results = [];
for (var i = 0; i < values.length; i++) {
var duration = parseTime(values[i]);
results.push(duration);
}
return results;
})();
duration = Math.max.apply(Math, durations);
}
// Single transition
else {
duration = parseTime(value);
}
// Accept first vaue
break;
}
return duration;
} | [
"function",
"(",
"el",
",",
"properties",
")",
"{",
"var",
"duration",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"properties",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"value",
"=",
"el",
".",
"css",
"(",
"properties",
"[",
"i",
"]",
")",
";",
"if",
"(",
"!",
"value",
")",
"continue",
";",
"if",
"(",
"value",
".",
"indexOf",
"(",
"\",\"",
")",
"!==",
"-",
"1",
")",
"{",
"var",
"values",
"=",
"value",
".",
"split",
"(",
"\",\"",
")",
";",
"var",
"durations",
"=",
"(",
"function",
"(",
")",
"{",
"var",
"results",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"values",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"duration",
"=",
"parseTime",
"(",
"values",
"[",
"i",
"]",
")",
";",
"results",
".",
"push",
"(",
"duration",
")",
";",
"}",
"return",
"results",
";",
"}",
")",
"(",
")",
";",
"duration",
"=",
"Math",
".",
"max",
".",
"apply",
"(",
"Math",
",",
"durations",
")",
";",
"}",
"else",
"{",
"duration",
"=",
"parseTime",
"(",
"value",
")",
";",
"}",
"break",
";",
"}",
"return",
"duration",
";",
"}"
] | Parses the longest time unit found in a series of CSS properties. Returns a value in milliseconds. | [
"Parses",
"the",
"longest",
"time",
"unit",
"found",
"in",
"a",
"series",
"of",
"CSS",
"properties",
".",
"Returns",
"a",
"value",
"in",
"milliseconds",
"."
] | 79b0d05692de78f6b5e2dbc0f90219d2e245687b | https://github.com/pixelunion/jquery.trend/blob/79b0d05692de78f6b5e2dbc0f90219d2e245687b/jquery.trend.js#L56-L89 | train |
|
pixelunion/jquery.trend | jquery.trend.js | function(handleObj) {
var el = $(this);
var fired = false;
// Mark element as being in transition
el.data("trend", true);
// Calculate a fallback duration. + 20 because some browsers fire
// timeouts faster than transitionend.
var time =
parseProperties(el, transitionDurationProperties) +
parseProperties(el, transitionDelayProperties) +
20;
var cb = function(e) {
// transitionend events can be sent for each property. Let's just
// skip all but the first. Also handles the timeout callback.
if (fired) return;
// Child elements that also have transitions can be fired before we
// complete. This will catch and ignore those. Unfortunately, we'll
// have to rely on the timeout in these cases.
if (e && e.srcElement !== el[0]) return;
// Mark element has not being in transition
el.data("trend", false);
// Callback
fired = true;
if (handleObj.handler) handleObj.handler();
};
el.one(transitionEndEvents, cb);
el.data("trend-timeout", window.setTimeout(cb, time));
} | javascript | function(handleObj) {
var el = $(this);
var fired = false;
// Mark element as being in transition
el.data("trend", true);
// Calculate a fallback duration. + 20 because some browsers fire
// timeouts faster than transitionend.
var time =
parseProperties(el, transitionDurationProperties) +
parseProperties(el, transitionDelayProperties) +
20;
var cb = function(e) {
// transitionend events can be sent for each property. Let's just
// skip all but the first. Also handles the timeout callback.
if (fired) return;
// Child elements that also have transitions can be fired before we
// complete. This will catch and ignore those. Unfortunately, we'll
// have to rely on the timeout in these cases.
if (e && e.srcElement !== el[0]) return;
// Mark element has not being in transition
el.data("trend", false);
// Callback
fired = true;
if (handleObj.handler) handleObj.handler();
};
el.one(transitionEndEvents, cb);
el.data("trend-timeout", window.setTimeout(cb, time));
} | [
"function",
"(",
"handleObj",
")",
"{",
"var",
"el",
"=",
"$",
"(",
"this",
")",
";",
"var",
"fired",
"=",
"false",
";",
"el",
".",
"data",
"(",
"\"trend\"",
",",
"true",
")",
";",
"var",
"time",
"=",
"parseProperties",
"(",
"el",
",",
"transitionDurationProperties",
")",
"+",
"parseProperties",
"(",
"el",
",",
"transitionDelayProperties",
")",
"+",
"20",
";",
"var",
"cb",
"=",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"fired",
")",
"return",
";",
"if",
"(",
"e",
"&&",
"e",
".",
"srcElement",
"!==",
"el",
"[",
"0",
"]",
")",
"return",
";",
"el",
".",
"data",
"(",
"\"trend\"",
",",
"false",
")",
";",
"fired",
"=",
"true",
";",
"if",
"(",
"handleObj",
".",
"handler",
")",
"handleObj",
".",
"handler",
"(",
")",
";",
"}",
";",
"el",
".",
"one",
"(",
"transitionEndEvents",
",",
"cb",
")",
";",
"el",
".",
"data",
"(",
"\"trend-timeout\"",
",",
"window",
".",
"setTimeout",
"(",
"cb",
",",
"time",
")",
")",
";",
"}"
] | Triggers an event handler when an element is done transitioning. Handles browsers that don't support transitionend by adding a timeout with the transition duration. | [
"Triggers",
"an",
"event",
"handler",
"when",
"an",
"element",
"is",
"done",
"transitioning",
".",
"Handles",
"browsers",
"that",
"don",
"t",
"support",
"transitionend",
"by",
"adding",
"a",
"timeout",
"with",
"the",
"transition",
"duration",
"."
] | 79b0d05692de78f6b5e2dbc0f90219d2e245687b | https://github.com/pixelunion/jquery.trend/blob/79b0d05692de78f6b5e2dbc0f90219d2e245687b/jquery.trend.js#L96-L130 | train |
|
uptick/js-tinyapi | src/utils.js | ajax | function ajax( opts ) {
const method = (opts.method || 'get').toUpperCase()
const {
url,
body,
contentType,
extraHeaders,
useBearer = true,
bearer
} = opts || {}
let requestInit = {
method,
headers: fetchHeaders({
method,
contentType,
extraHeaders,
useBearer,
bearer
}),
credentials: 'same-origin'
}
if( method != 'GET' && method != 'HEAD' && method != 'OPTIONS') {
requestInit.body = body
}
let request = new Request( url, requestInit )
return fetch( request )
.then( response => {
if( !!response.ok ) {
if( response.status == 204 ) {
return {}
}
if( typeof TINYAPI_NODE !== 'undefined' && TINYAPI_NODE ) {
return response
}
if( !!response.json ) {
return response.json()
}
else {
return response
}
}
if( !!response.json ) {
return response.json()
.catch( e => Object({ status: response.status }) )
.then( e => Promise.reject( e ) )
}
else {
return response
}
})
} | javascript | function ajax( opts ) {
const method = (opts.method || 'get').toUpperCase()
const {
url,
body,
contentType,
extraHeaders,
useBearer = true,
bearer
} = opts || {}
let requestInit = {
method,
headers: fetchHeaders({
method,
contentType,
extraHeaders,
useBearer,
bearer
}),
credentials: 'same-origin'
}
if( method != 'GET' && method != 'HEAD' && method != 'OPTIONS') {
requestInit.body = body
}
let request = new Request( url, requestInit )
return fetch( request )
.then( response => {
if( !!response.ok ) {
if( response.status == 204 ) {
return {}
}
if( typeof TINYAPI_NODE !== 'undefined' && TINYAPI_NODE ) {
return response
}
if( !!response.json ) {
return response.json()
}
else {
return response
}
}
if( !!response.json ) {
return response.json()
.catch( e => Object({ status: response.status }) )
.then( e => Promise.reject( e ) )
}
else {
return response
}
})
} | [
"function",
"ajax",
"(",
"opts",
")",
"{",
"const",
"method",
"=",
"(",
"opts",
".",
"method",
"||",
"'get'",
")",
".",
"toUpperCase",
"(",
")",
"const",
"{",
"url",
",",
"body",
",",
"contentType",
",",
"extraHeaders",
",",
"useBearer",
"=",
"true",
",",
"bearer",
"}",
"=",
"opts",
"||",
"{",
"}",
"let",
"requestInit",
"=",
"{",
"method",
",",
"headers",
":",
"fetchHeaders",
"(",
"{",
"method",
",",
"contentType",
",",
"extraHeaders",
",",
"useBearer",
",",
"bearer",
"}",
")",
",",
"credentials",
":",
"'same-origin'",
"}",
"if",
"(",
"method",
"!=",
"'GET'",
"&&",
"method",
"!=",
"'HEAD'",
"&&",
"method",
"!=",
"'OPTIONS'",
")",
"{",
"requestInit",
".",
"body",
"=",
"body",
"}",
"let",
"request",
"=",
"new",
"Request",
"(",
"url",
",",
"requestInit",
")",
"return",
"fetch",
"(",
"request",
")",
".",
"then",
"(",
"response",
"=>",
"{",
"if",
"(",
"!",
"!",
"response",
".",
"ok",
")",
"{",
"if",
"(",
"response",
".",
"status",
"==",
"204",
")",
"{",
"return",
"{",
"}",
"}",
"if",
"(",
"typeof",
"TINYAPI_NODE",
"!==",
"'undefined'",
"&&",
"TINYAPI_NODE",
")",
"{",
"return",
"response",
"}",
"if",
"(",
"!",
"!",
"response",
".",
"json",
")",
"{",
"return",
"response",
".",
"json",
"(",
")",
"}",
"else",
"{",
"return",
"response",
"}",
"}",
"if",
"(",
"!",
"!",
"response",
".",
"json",
")",
"{",
"return",
"response",
".",
"json",
"(",
")",
".",
"catch",
"(",
"e",
"=>",
"Object",
"(",
"{",
"status",
":",
"response",
".",
"status",
"}",
")",
")",
".",
"then",
"(",
"e",
"=>",
"Promise",
".",
"reject",
"(",
"e",
")",
")",
"}",
"else",
"{",
"return",
"response",
"}",
"}",
")",
"}"
] | Perform an ajax request.
Uses HTML5 fetch to perform an ajax request according to parameters
supplied via the options object.
@param {string} url - The URL to make the request to.
@param {string} method - The request method. Defaults to "get".
@param {string} body - Data to be sent with the request.
@param {string} contentType - The content type of the request. Defaults to "application/json".
@param {object} extraHeaders - Custom headers to add.
@param {boolean} useBearer - Flag indicating whether to include bearer authorization. | [
"Perform",
"an",
"ajax",
"request",
"."
] | e70ce2f24b0c2dc7bb6c5441eecf284456b54697 | https://github.com/uptick/js-tinyapi/blob/e70ce2f24b0c2dc7bb6c5441eecf284456b54697/src/utils.js#L165-L217 | train |
uptick/js-tinyapi | src/utils.js | postJson | function postJson({ url, payload, contentType, useBearer }) {
return ajax({
url,
method: 'post',
body: JSON.stringify( payload || {} ),
contentType,
useBearer
})
} | javascript | function postJson({ url, payload, contentType, useBearer }) {
return ajax({
url,
method: 'post',
body: JSON.stringify( payload || {} ),
contentType,
useBearer
})
} | [
"function",
"postJson",
"(",
"{",
"url",
",",
"payload",
",",
"contentType",
",",
"useBearer",
"}",
")",
"{",
"return",
"ajax",
"(",
"{",
"url",
",",
"method",
":",
"'post'",
",",
"body",
":",
"JSON",
".",
"stringify",
"(",
"payload",
"||",
"{",
"}",
")",
",",
"contentType",
",",
"useBearer",
"}",
")",
"}"
] | Post JSON data.
@param {string} url - The URL to make the request to.
@param {object} payload - Data to be sent with the request.
@param {string} contentType - The content type of the request. Defaults to "application/json".
@param {boolean} useBearer - Flag indicating whether to include bearer authorization. | [
"Post",
"JSON",
"data",
"."
] | e70ce2f24b0c2dc7bb6c5441eecf284456b54697 | https://github.com/uptick/js-tinyapi/blob/e70ce2f24b0c2dc7bb6c5441eecf284456b54697/src/utils.js#L267-L275 | train |
uptick/js-tinyapi | src/utils.js | makeFormData | function makeFormData( payload ) {
let body = new FormData()
for( let k in (payload || {}) ) {
body.append( k, payload[k] )
}
return body
} | javascript | function makeFormData( payload ) {
let body = new FormData()
for( let k in (payload || {}) ) {
body.append( k, payload[k] )
}
return body
} | [
"function",
"makeFormData",
"(",
"payload",
")",
"{",
"let",
"body",
"=",
"new",
"FormData",
"(",
")",
"for",
"(",
"let",
"k",
"in",
"(",
"payload",
"||",
"{",
"}",
")",
")",
"{",
"body",
".",
"append",
"(",
"k",
",",
"payload",
"[",
"k",
"]",
")",
"}",
"return",
"body",
"}"
] | Convert an object into HTML5 FormData. | [
"Convert",
"an",
"object",
"into",
"HTML5",
"FormData",
"."
] | e70ce2f24b0c2dc7bb6c5441eecf284456b54697 | https://github.com/uptick/js-tinyapi/blob/e70ce2f24b0c2dc7bb6c5441eecf284456b54697/src/utils.js#L280-L286 | train |
uptick/js-tinyapi | src/utils.js | postForm | function postForm({ url, payload, useBearer }) {
return ajax({
url,
body: makeFormData( payload ),
method: 'post',
useBearer
})
} | javascript | function postForm({ url, payload, useBearer }) {
return ajax({
url,
body: makeFormData( payload ),
method: 'post',
useBearer
})
} | [
"function",
"postForm",
"(",
"{",
"url",
",",
"payload",
",",
"useBearer",
"}",
")",
"{",
"return",
"ajax",
"(",
"{",
"url",
",",
"body",
":",
"makeFormData",
"(",
"payload",
")",
",",
"method",
":",
"'post'",
",",
"useBearer",
"}",
")",
"}"
] | Post form data.
@param {string} url - The URL to make the request to.
@param {object} payload - Data to be sent with the request.
@param {boolean} useBearer - Flag indicating whether to include bearer authorization. | [
"Post",
"form",
"data",
"."
] | e70ce2f24b0c2dc7bb6c5441eecf284456b54697 | https://github.com/uptick/js-tinyapi/blob/e70ce2f24b0c2dc7bb6c5441eecf284456b54697/src/utils.js#L295-L302 | train |
graphology/graphology-metrics | extent.js | nodeExtent | function nodeExtent(graph, attribute) {
if (!isGraph(graph))
throw new Error('graphology-metrics/extent: the given graph is not a valid graphology instance.');
var attributes = [].concat(attribute);
var nodes = graph.nodes(),
node,
data,
value,
key,
a,
i,
l;
var results = {};
for (a = 0; a < attributes.length; a++) {
key = attributes[a];
results[key] = [Infinity, -Infinity];
}
for (i = 0, l = nodes.length; i < l; i++) {
node = nodes[i];
data = graph.getNodeAttributes(node);
for (a = 0; a < attributes.length; a++) {
key = attributes[a];
value = data[key];
if (value < results[key][0])
results[key][0] = value;
if (value > results[key][1])
results[key][1] = value;
}
}
return typeof attribute === 'string' ? results[attribute] : results;
} | javascript | function nodeExtent(graph, attribute) {
if (!isGraph(graph))
throw new Error('graphology-metrics/extent: the given graph is not a valid graphology instance.');
var attributes = [].concat(attribute);
var nodes = graph.nodes(),
node,
data,
value,
key,
a,
i,
l;
var results = {};
for (a = 0; a < attributes.length; a++) {
key = attributes[a];
results[key] = [Infinity, -Infinity];
}
for (i = 0, l = nodes.length; i < l; i++) {
node = nodes[i];
data = graph.getNodeAttributes(node);
for (a = 0; a < attributes.length; a++) {
key = attributes[a];
value = data[key];
if (value < results[key][0])
results[key][0] = value;
if (value > results[key][1])
results[key][1] = value;
}
}
return typeof attribute === 'string' ? results[attribute] : results;
} | [
"function",
"nodeExtent",
"(",
"graph",
",",
"attribute",
")",
"{",
"if",
"(",
"!",
"isGraph",
"(",
"graph",
")",
")",
"throw",
"new",
"Error",
"(",
"'graphology-metrics/extent: the given graph is not a valid graphology instance.'",
")",
";",
"var",
"attributes",
"=",
"[",
"]",
".",
"concat",
"(",
"attribute",
")",
";",
"var",
"nodes",
"=",
"graph",
".",
"nodes",
"(",
")",
",",
"node",
",",
"data",
",",
"value",
",",
"key",
",",
"a",
",",
"i",
",",
"l",
";",
"var",
"results",
"=",
"{",
"}",
";",
"for",
"(",
"a",
"=",
"0",
";",
"a",
"<",
"attributes",
".",
"length",
";",
"a",
"++",
")",
"{",
"key",
"=",
"attributes",
"[",
"a",
"]",
";",
"results",
"[",
"key",
"]",
"=",
"[",
"Infinity",
",",
"-",
"Infinity",
"]",
";",
"}",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"nodes",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"node",
"=",
"nodes",
"[",
"i",
"]",
";",
"data",
"=",
"graph",
".",
"getNodeAttributes",
"(",
"node",
")",
";",
"for",
"(",
"a",
"=",
"0",
";",
"a",
"<",
"attributes",
".",
"length",
";",
"a",
"++",
")",
"{",
"key",
"=",
"attributes",
"[",
"a",
"]",
";",
"value",
"=",
"data",
"[",
"key",
"]",
";",
"if",
"(",
"value",
"<",
"results",
"[",
"key",
"]",
"[",
"0",
"]",
")",
"results",
"[",
"key",
"]",
"[",
"0",
"]",
"=",
"value",
";",
"if",
"(",
"value",
">",
"results",
"[",
"key",
"]",
"[",
"1",
"]",
")",
"results",
"[",
"key",
"]",
"[",
"1",
"]",
"=",
"value",
";",
"}",
"}",
"return",
"typeof",
"attribute",
"===",
"'string'",
"?",
"results",
"[",
"attribute",
"]",
":",
"results",
";",
"}"
] | Function returning the extent of the selected node attributes.
@param {Graph} graph - Target graph.
@param {string|array} attribute - Single or multiple attributes.
@return {array|object} | [
"Function",
"returning",
"the",
"extent",
"of",
"the",
"selected",
"node",
"attributes",
"."
] | bf920856140994251fa799f87f58f42bc06f53e6 | https://github.com/graphology/graphology-metrics/blob/bf920856140994251fa799f87f58f42bc06f53e6/extent.js#L16-L56 | train |
graphology/graphology-metrics | extent.js | edgeExtent | function edgeExtent(graph, attribute) {
if (!isGraph(graph))
throw new Error('graphology-metrics/extent: the given graph is not a valid graphology instance.');
var attributes = [].concat(attribute);
var edges = graph.edges(),
edge,
data,
value,
key,
a,
i,
l;
var results = {};
for (a = 0; a < attributes.length; a++) {
key = attributes[a];
results[key] = [Infinity, -Infinity];
}
for (i = 0, l = edges.length; i < l; i++) {
edge = edges[i];
data = graph.getEdgeAttributes(edge);
for (a = 0; a < attributes.length; a++) {
key = attributes[a];
value = data[key];
if (value < results[key][0])
results[key][0] = value;
if (value > results[key][1])
results[key][1] = value;
}
}
return typeof attribute === 'string' ? results[attribute] : results;
} | javascript | function edgeExtent(graph, attribute) {
if (!isGraph(graph))
throw new Error('graphology-metrics/extent: the given graph is not a valid graphology instance.');
var attributes = [].concat(attribute);
var edges = graph.edges(),
edge,
data,
value,
key,
a,
i,
l;
var results = {};
for (a = 0; a < attributes.length; a++) {
key = attributes[a];
results[key] = [Infinity, -Infinity];
}
for (i = 0, l = edges.length; i < l; i++) {
edge = edges[i];
data = graph.getEdgeAttributes(edge);
for (a = 0; a < attributes.length; a++) {
key = attributes[a];
value = data[key];
if (value < results[key][0])
results[key][0] = value;
if (value > results[key][1])
results[key][1] = value;
}
}
return typeof attribute === 'string' ? results[attribute] : results;
} | [
"function",
"edgeExtent",
"(",
"graph",
",",
"attribute",
")",
"{",
"if",
"(",
"!",
"isGraph",
"(",
"graph",
")",
")",
"throw",
"new",
"Error",
"(",
"'graphology-metrics/extent: the given graph is not a valid graphology instance.'",
")",
";",
"var",
"attributes",
"=",
"[",
"]",
".",
"concat",
"(",
"attribute",
")",
";",
"var",
"edges",
"=",
"graph",
".",
"edges",
"(",
")",
",",
"edge",
",",
"data",
",",
"value",
",",
"key",
",",
"a",
",",
"i",
",",
"l",
";",
"var",
"results",
"=",
"{",
"}",
";",
"for",
"(",
"a",
"=",
"0",
";",
"a",
"<",
"attributes",
".",
"length",
";",
"a",
"++",
")",
"{",
"key",
"=",
"attributes",
"[",
"a",
"]",
";",
"results",
"[",
"key",
"]",
"=",
"[",
"Infinity",
",",
"-",
"Infinity",
"]",
";",
"}",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"edges",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"edge",
"=",
"edges",
"[",
"i",
"]",
";",
"data",
"=",
"graph",
".",
"getEdgeAttributes",
"(",
"edge",
")",
";",
"for",
"(",
"a",
"=",
"0",
";",
"a",
"<",
"attributes",
".",
"length",
";",
"a",
"++",
")",
"{",
"key",
"=",
"attributes",
"[",
"a",
"]",
";",
"value",
"=",
"data",
"[",
"key",
"]",
";",
"if",
"(",
"value",
"<",
"results",
"[",
"key",
"]",
"[",
"0",
"]",
")",
"results",
"[",
"key",
"]",
"[",
"0",
"]",
"=",
"value",
";",
"if",
"(",
"value",
">",
"results",
"[",
"key",
"]",
"[",
"1",
"]",
")",
"results",
"[",
"key",
"]",
"[",
"1",
"]",
"=",
"value",
";",
"}",
"}",
"return",
"typeof",
"attribute",
"===",
"'string'",
"?",
"results",
"[",
"attribute",
"]",
":",
"results",
";",
"}"
] | Function returning the extent of the selected edge attributes.
@param {Graph} graph - Target graph.
@param {string|array} attribute - Single or multiple attributes.
@return {array|object} | [
"Function",
"returning",
"the",
"extent",
"of",
"the",
"selected",
"edge",
"attributes",
"."
] | bf920856140994251fa799f87f58f42bc06f53e6 | https://github.com/graphology/graphology-metrics/blob/bf920856140994251fa799f87f58f42bc06f53e6/extent.js#L65-L105 | train |
JCCDex/jcc_jingtum_base_lib | src/secp256k1.js | ScalarMultiple | function ScalarMultiple(bytes, discrim) {
var order = ec.curve.n;
for (var i = 0; i <= 0xFFFFFFFF; i++) {
// We hash the bytes to find a 256 bit number, looping until we are sure it
// is less than the order of the curve.
var hasher = new Sha512().add(bytes);
// If the optional discriminator index was passed in, update the hash.
if (discrim !== undefined) {
hasher.addU32(discrim);
}
hasher.addU32(i);
var key = hasher.first256BN();
/* istanbul ignore next */
if (key.cmpn(0) > 0 && key.cmp(order) < 0) {
return key;
}
}
/* istanbul ignore next */
throw new Error('impossible space search)');
} | javascript | function ScalarMultiple(bytes, discrim) {
var order = ec.curve.n;
for (var i = 0; i <= 0xFFFFFFFF; i++) {
// We hash the bytes to find a 256 bit number, looping until we are sure it
// is less than the order of the curve.
var hasher = new Sha512().add(bytes);
// If the optional discriminator index was passed in, update the hash.
if (discrim !== undefined) {
hasher.addU32(discrim);
}
hasher.addU32(i);
var key = hasher.first256BN();
/* istanbul ignore next */
if (key.cmpn(0) > 0 && key.cmp(order) < 0) {
return key;
}
}
/* istanbul ignore next */
throw new Error('impossible space search)');
} | [
"function",
"ScalarMultiple",
"(",
"bytes",
",",
"discrim",
")",
"{",
"var",
"order",
"=",
"ec",
".",
"curve",
".",
"n",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<=",
"0xFFFFFFFF",
";",
"i",
"++",
")",
"{",
"var",
"hasher",
"=",
"new",
"Sha512",
"(",
")",
".",
"add",
"(",
"bytes",
")",
";",
"if",
"(",
"discrim",
"!==",
"undefined",
")",
"{",
"hasher",
".",
"addU32",
"(",
"discrim",
")",
";",
"}",
"hasher",
".",
"addU32",
"(",
"i",
")",
";",
"var",
"key",
"=",
"hasher",
".",
"first256BN",
"(",
")",
";",
"if",
"(",
"key",
".",
"cmpn",
"(",
"0",
")",
">",
"0",
"&&",
"key",
".",
"cmp",
"(",
"order",
")",
"<",
"0",
")",
"{",
"return",
"key",
";",
"}",
"}",
"throw",
"new",
"Error",
"(",
"'impossible space search)'",
")",
";",
"}"
] | Scalar multiplication to find one 256 bit number
where it is less than the order of the curve.
@param bytes
@param discrim
@returns {*}
@constructor | [
"Scalar",
"multiplication",
"to",
"find",
"one",
"256",
"bit",
"number",
"where",
"it",
"is",
"less",
"than",
"the",
"order",
"of",
"the",
"curve",
"."
] | ace3cb56fcfa33372238e5f1bb06b9a58f98f889 | https://github.com/JCCDex/jcc_jingtum_base_lib/blob/ace3cb56fcfa33372238e5f1bb06b9a58f98f889/src/secp256k1.js#L14-L34 | train |
midknight41/map-factory | src/lib/object-mapper/get-key-value.js | getValue | function getValue(fromObject, fromKey) {
var regDot = /\./g
, regFinishArray = /.+(\[\])/g
, keys
, key
, result
, lastValue
;
keys = fromKey.split(regDot);
key = keys.splice(0, 1);
result = _getValue(fromObject, key[0], keys);
return handleArrayOfUndefined_(result);
} | javascript | function getValue(fromObject, fromKey) {
var regDot = /\./g
, regFinishArray = /.+(\[\])/g
, keys
, key
, result
, lastValue
;
keys = fromKey.split(regDot);
key = keys.splice(0, 1);
result = _getValue(fromObject, key[0], keys);
return handleArrayOfUndefined_(result);
} | [
"function",
"getValue",
"(",
"fromObject",
",",
"fromKey",
")",
"{",
"var",
"regDot",
"=",
"/",
"\\.",
"/",
"g",
",",
"regFinishArray",
"=",
"/",
".+(\\[\\])",
"/",
"g",
",",
"keys",
",",
"key",
",",
"result",
",",
"lastValue",
";",
"keys",
"=",
"fromKey",
".",
"split",
"(",
"regDot",
")",
";",
"key",
"=",
"keys",
".",
"splice",
"(",
"0",
",",
"1",
")",
";",
"result",
"=",
"_getValue",
"(",
"fromObject",
",",
"key",
"[",
"0",
"]",
",",
"keys",
")",
";",
"return",
"handleArrayOfUndefined_",
"(",
"result",
")",
";",
"}"
] | Make the get of a value with the key in the passed object
@param fromObject
@param fromKey
@constructor
@returns {*} | [
"Make",
"the",
"get",
"of",
"a",
"value",
"with",
"the",
"key",
"in",
"the",
"passed",
"object"
] | a8e55ec2c4e9119ce33f29c469ae21867e1827cf | https://github.com/midknight41/map-factory/blob/a8e55ec2c4e9119ce33f29c469ae21867e1827cf/src/lib/object-mapper/get-key-value.js#L13-L28 | train |
LaxarJS/laxar | lib/utilities/object.js | fillArrayWithNull | function fillArrayWithNull( arr, toIndex ) {
for( let i = arr.length; i < toIndex; ++i ) {
arr[ i ] = null;
}
} | javascript | function fillArrayWithNull( arr, toIndex ) {
for( let i = arr.length; i < toIndex; ++i ) {
arr[ i ] = null;
}
} | [
"function",
"fillArrayWithNull",
"(",
"arr",
",",
"toIndex",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"arr",
".",
"length",
";",
"i",
"<",
"toIndex",
";",
"++",
"i",
")",
"{",
"arr",
"[",
"i",
"]",
"=",
"null",
";",
"}",
"}"
] | eslint-disable-next-line valid-jsdoc
Sets all entries of the given array to `null`.
@private | [
"eslint",
"-",
"disable",
"-",
"next",
"-",
"line",
"valid",
"-",
"jsdoc",
"Sets",
"all",
"entries",
"of",
"the",
"given",
"array",
"to",
"null",
"."
] | 2d6e03feb2b7e0a9916742de0edd92ac15c5d45f | https://github.com/LaxarJS/laxar/blob/2d6e03feb2b7e0a9916742de0edd92ac15c5d45f/lib/utilities/object.js#L272-L276 | train |
mrvisser/node-corporal | examples/whoami/commands/greet.js | function(session, args, callback) {
session.stdout().write('Hello, ' + session.env('me').bold + '\n');
return callback();
} | javascript | function(session, args, callback) {
session.stdout().write('Hello, ' + session.env('me').bold + '\n');
return callback();
} | [
"function",
"(",
"session",
",",
"args",
",",
"callback",
")",
"{",
"session",
".",
"stdout",
"(",
")",
".",
"write",
"(",
"'Hello, '",
"+",
"session",
".",
"env",
"(",
"'me'",
")",
".",
"bold",
"+",
"'\\n'",
")",
";",
"\\n",
"}"
] | The function that actually invokes the command. Simply pull the current state of the "me" environment variable and print it to the console. | [
"The",
"function",
"that",
"actually",
"invokes",
"the",
"command",
".",
"Simply",
"pull",
"the",
"current",
"state",
"of",
"the",
"me",
"environment",
"variable",
"and",
"print",
"it",
"to",
"the",
"console",
"."
] | 93ead59d870fe78d43135bb0a8b2d346422b970e | https://github.com/mrvisser/node-corporal/blob/93ead59d870fe78d43135bb0a8b2d346422b970e/examples/whoami/commands/greet.js#L9-L12 | train |
|
graphology/graphology-metrics | modularity.js | modularity | function modularity(graph, options) {
// Handling errors
if (!isGraph(graph))
throw new Error('graphology-metrics/modularity: the given graph is not a valid graphology instance.');
if (graph.multi)
throw new Error('graphology-metrics/modularity: multi graphs are not handled.');
if (!graph.size)
throw new Error('graphology-metrics/modularity: the given graph has no edges.');
// Solving options
options = defaults({}, options, DEFAULTS);
var communities,
nodes = graph.nodes(),
edges = graph.edges(),
i,
l;
// Do we have a community mapping?
if (typeof options.communities === 'object') {
communities = options.communities;
}
// Else we need to extract it from the graph
else {
communities = {};
for (i = 0, l = nodes.length; i < l; i++)
communities[nodes[i]] = graph.getNodeAttribute(nodes[i], options.attributes.community);
}
var M = 0,
Q = 0,
internalW = {},
totalW = {},
bounds,
node1, node2, edge,
community1, community2,
w, weight;
for (i = 0, l = edges.length; i < l; i++) {
edge = edges[i];
bounds = graph.extremities(edge);
node1 = bounds[0];
node2 = bounds[1];
if (node1 === node2)
continue;
community1 = communities[node1];
community2 = communities[node2];
if (community1 === undefined)
throw new Error('graphology-metrics/modularity: the "' + node1 + '" node is not in the partition.');
if (community2 === undefined)
throw new Error('graphology-metrics/modularity: the "' + node2 + '" node is not in the partition.');
w = graph.getEdgeAttribute(edge, options.attributes.weight);
weight = isNaN(w) ? 1 : w;
totalW[community1] = (totalW[community1] || 0) + weight;
if (graph.undirected(edge) || !graph.hasDirectedEdge(node2, node1)) {
totalW[community2] = (totalW[community2] || 0) + weight;
M += 2 * weight;
}
else {
M += weight;
}
if (!graph.hasDirectedEdge(node2, node1))
weight *= 2;
if (community1 === community2)
internalW[community1] = (internalW[community1] || 0) + weight;
}
for (community1 in totalW)
Q += ((internalW[community1] || 0) - (totalW[community1] * totalW[community1] / M));
return Q / M;
} | javascript | function modularity(graph, options) {
// Handling errors
if (!isGraph(graph))
throw new Error('graphology-metrics/modularity: the given graph is not a valid graphology instance.');
if (graph.multi)
throw new Error('graphology-metrics/modularity: multi graphs are not handled.');
if (!graph.size)
throw new Error('graphology-metrics/modularity: the given graph has no edges.');
// Solving options
options = defaults({}, options, DEFAULTS);
var communities,
nodes = graph.nodes(),
edges = graph.edges(),
i,
l;
// Do we have a community mapping?
if (typeof options.communities === 'object') {
communities = options.communities;
}
// Else we need to extract it from the graph
else {
communities = {};
for (i = 0, l = nodes.length; i < l; i++)
communities[nodes[i]] = graph.getNodeAttribute(nodes[i], options.attributes.community);
}
var M = 0,
Q = 0,
internalW = {},
totalW = {},
bounds,
node1, node2, edge,
community1, community2,
w, weight;
for (i = 0, l = edges.length; i < l; i++) {
edge = edges[i];
bounds = graph.extremities(edge);
node1 = bounds[0];
node2 = bounds[1];
if (node1 === node2)
continue;
community1 = communities[node1];
community2 = communities[node2];
if (community1 === undefined)
throw new Error('graphology-metrics/modularity: the "' + node1 + '" node is not in the partition.');
if (community2 === undefined)
throw new Error('graphology-metrics/modularity: the "' + node2 + '" node is not in the partition.');
w = graph.getEdgeAttribute(edge, options.attributes.weight);
weight = isNaN(w) ? 1 : w;
totalW[community1] = (totalW[community1] || 0) + weight;
if (graph.undirected(edge) || !graph.hasDirectedEdge(node2, node1)) {
totalW[community2] = (totalW[community2] || 0) + weight;
M += 2 * weight;
}
else {
M += weight;
}
if (!graph.hasDirectedEdge(node2, node1))
weight *= 2;
if (community1 === community2)
internalW[community1] = (internalW[community1] || 0) + weight;
}
for (community1 in totalW)
Q += ((internalW[community1] || 0) - (totalW[community1] * totalW[community1] / M));
return Q / M;
} | [
"function",
"modularity",
"(",
"graph",
",",
"options",
")",
"{",
"if",
"(",
"!",
"isGraph",
"(",
"graph",
")",
")",
"throw",
"new",
"Error",
"(",
"'graphology-metrics/modularity: the given graph is not a valid graphology instance.'",
")",
";",
"if",
"(",
"graph",
".",
"multi",
")",
"throw",
"new",
"Error",
"(",
"'graphology-metrics/modularity: multi graphs are not handled.'",
")",
";",
"if",
"(",
"!",
"graph",
".",
"size",
")",
"throw",
"new",
"Error",
"(",
"'graphology-metrics/modularity: the given graph has no edges.'",
")",
";",
"options",
"=",
"defaults",
"(",
"{",
"}",
",",
"options",
",",
"DEFAULTS",
")",
";",
"var",
"communities",
",",
"nodes",
"=",
"graph",
".",
"nodes",
"(",
")",
",",
"edges",
"=",
"graph",
".",
"edges",
"(",
")",
",",
"i",
",",
"l",
";",
"if",
"(",
"typeof",
"options",
".",
"communities",
"===",
"'object'",
")",
"{",
"communities",
"=",
"options",
".",
"communities",
";",
"}",
"else",
"{",
"communities",
"=",
"{",
"}",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"nodes",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"communities",
"[",
"nodes",
"[",
"i",
"]",
"]",
"=",
"graph",
".",
"getNodeAttribute",
"(",
"nodes",
"[",
"i",
"]",
",",
"options",
".",
"attributes",
".",
"community",
")",
";",
"}",
"var",
"M",
"=",
"0",
",",
"Q",
"=",
"0",
",",
"internalW",
"=",
"{",
"}",
",",
"totalW",
"=",
"{",
"}",
",",
"bounds",
",",
"node1",
",",
"node2",
",",
"edge",
",",
"community1",
",",
"community2",
",",
"w",
",",
"weight",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"edges",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"edge",
"=",
"edges",
"[",
"i",
"]",
";",
"bounds",
"=",
"graph",
".",
"extremities",
"(",
"edge",
")",
";",
"node1",
"=",
"bounds",
"[",
"0",
"]",
";",
"node2",
"=",
"bounds",
"[",
"1",
"]",
";",
"if",
"(",
"node1",
"===",
"node2",
")",
"continue",
";",
"community1",
"=",
"communities",
"[",
"node1",
"]",
";",
"community2",
"=",
"communities",
"[",
"node2",
"]",
";",
"if",
"(",
"community1",
"===",
"undefined",
")",
"throw",
"new",
"Error",
"(",
"'graphology-metrics/modularity: the \"'",
"+",
"node1",
"+",
"'\" node is not in the partition.'",
")",
";",
"if",
"(",
"community2",
"===",
"undefined",
")",
"throw",
"new",
"Error",
"(",
"'graphology-metrics/modularity: the \"'",
"+",
"node2",
"+",
"'\" node is not in the partition.'",
")",
";",
"w",
"=",
"graph",
".",
"getEdgeAttribute",
"(",
"edge",
",",
"options",
".",
"attributes",
".",
"weight",
")",
";",
"weight",
"=",
"isNaN",
"(",
"w",
")",
"?",
"1",
":",
"w",
";",
"totalW",
"[",
"community1",
"]",
"=",
"(",
"totalW",
"[",
"community1",
"]",
"||",
"0",
")",
"+",
"weight",
";",
"if",
"(",
"graph",
".",
"undirected",
"(",
"edge",
")",
"||",
"!",
"graph",
".",
"hasDirectedEdge",
"(",
"node2",
",",
"node1",
")",
")",
"{",
"totalW",
"[",
"community2",
"]",
"=",
"(",
"totalW",
"[",
"community2",
"]",
"||",
"0",
")",
"+",
"weight",
";",
"M",
"+=",
"2",
"*",
"weight",
";",
"}",
"else",
"{",
"M",
"+=",
"weight",
";",
"}",
"if",
"(",
"!",
"graph",
".",
"hasDirectedEdge",
"(",
"node2",
",",
"node1",
")",
")",
"weight",
"*=",
"2",
";",
"if",
"(",
"community1",
"===",
"community2",
")",
"internalW",
"[",
"community1",
"]",
"=",
"(",
"internalW",
"[",
"community1",
"]",
"||",
"0",
")",
"+",
"weight",
";",
"}",
"for",
"(",
"community1",
"in",
"totalW",
")",
"Q",
"+=",
"(",
"(",
"internalW",
"[",
"community1",
"]",
"||",
"0",
")",
"-",
"(",
"totalW",
"[",
"community1",
"]",
"*",
"totalW",
"[",
"community1",
"]",
"/",
"M",
")",
")",
";",
"return",
"Q",
"/",
"M",
";",
"}"
] | Function returning the modularity of the given graph.
@param {Graph} graph - Target graph.
@param {object} options - Options:
@param {object} communities - Communities mapping.
@param {object} attributes - Attribute names:
@param {string} community - Name of the community attribute.
@param {string} weight - Name of the weight attribute.
@return {number} | [
"Function",
"returning",
"the",
"modularity",
"of",
"the",
"given",
"graph",
"."
] | bf920856140994251fa799f87f58f42bc06f53e6 | https://github.com/graphology/graphology-metrics/blob/bf920856140994251fa799f87f58f42bc06f53e6/modularity.js#L41-L125 | train |
AthenaJS/athenajs | js/Scene/default/Hud.js | function (destCtx, debug) {
if (!this.visible) {
return;
}
// auto goto next frame
if (this.currentAnimName.length) {
this.advanceFrame(this.currentAnimName);
}
var w = this.getCurrentWidth(),
scaledW = w * this.scale,
h = this.getCurrentHeight(),
scaledH = h * this.scale,
subScaledW = (scaledW / 2) | 0,
subScaledH = (scaledH / 2) | 0,
x = this.getCurrentOffsetX(),
y = this.getCurrentOffsetY(),
drawX = this.x + this.getCurrentShiftX(),
drawY = this.y + this.getCurrentShiftY(),
mapOffsetX = this.currentMap && this.currentMap.viewportX || 0,
mapOffsetY = this.currentMap && this.currentMap.viewportY || 0;
// TODO: fix map position when rotate is used
if ($.isEmptyObject(this.fxQueue)) {
if (this.type === 'enemy1' && window.todo)
var date = new Date().getTime();
destCtx.drawImage(this.image, x, y, w, h, drawX + mapOffsetX, drawY + mapOffsetY, scaledW, scaledH);
if (this.type === 'enemy1' && window.todo) {
var date2 = new Date().getTime();
console.log('drawSprite call duration:', date2 - date);
}
if (this.isDebug === true || debug === true) {
this.showHitBox(destCtx);
}
} else {
this.executeFx(destCtx);
// translate to keep the object as its position
destCtx.save();
destCtx.translate(drawX + mapOffsetX + subScaledW, drawY + mapOffsetY + subScaledH);
destCtx.rotate(this.angle);
destCtx.drawImage(this.image, x, y, w, h, -subScaledW, -subScaledH, scaledW, scaledH);
if (this.isDebug === true || debug === true) {
this.showHitBox(destCtx);
}
destCtx.restore();
}
} | javascript | function (destCtx, debug) {
if (!this.visible) {
return;
}
// auto goto next frame
if (this.currentAnimName.length) {
this.advanceFrame(this.currentAnimName);
}
var w = this.getCurrentWidth(),
scaledW = w * this.scale,
h = this.getCurrentHeight(),
scaledH = h * this.scale,
subScaledW = (scaledW / 2) | 0,
subScaledH = (scaledH / 2) | 0,
x = this.getCurrentOffsetX(),
y = this.getCurrentOffsetY(),
drawX = this.x + this.getCurrentShiftX(),
drawY = this.y + this.getCurrentShiftY(),
mapOffsetX = this.currentMap && this.currentMap.viewportX || 0,
mapOffsetY = this.currentMap && this.currentMap.viewportY || 0;
// TODO: fix map position when rotate is used
if ($.isEmptyObject(this.fxQueue)) {
if (this.type === 'enemy1' && window.todo)
var date = new Date().getTime();
destCtx.drawImage(this.image, x, y, w, h, drawX + mapOffsetX, drawY + mapOffsetY, scaledW, scaledH);
if (this.type === 'enemy1' && window.todo) {
var date2 = new Date().getTime();
console.log('drawSprite call duration:', date2 - date);
}
if (this.isDebug === true || debug === true) {
this.showHitBox(destCtx);
}
} else {
this.executeFx(destCtx);
// translate to keep the object as its position
destCtx.save();
destCtx.translate(drawX + mapOffsetX + subScaledW, drawY + mapOffsetY + subScaledH);
destCtx.rotate(this.angle);
destCtx.drawImage(this.image, x, y, w, h, -subScaledW, -subScaledH, scaledW, scaledH);
if (this.isDebug === true || debug === true) {
this.showHitBox(destCtx);
}
destCtx.restore();
}
} | [
"function",
"(",
"destCtx",
",",
"debug",
")",
"{",
"if",
"(",
"!",
"this",
".",
"visible",
")",
"{",
"return",
";",
"}",
"if",
"(",
"this",
".",
"currentAnimName",
".",
"length",
")",
"{",
"this",
".",
"advanceFrame",
"(",
"this",
".",
"currentAnimName",
")",
";",
"}",
"var",
"w",
"=",
"this",
".",
"getCurrentWidth",
"(",
")",
",",
"scaledW",
"=",
"w",
"*",
"this",
".",
"scale",
",",
"h",
"=",
"this",
".",
"getCurrentHeight",
"(",
")",
",",
"scaledH",
"=",
"h",
"*",
"this",
".",
"scale",
",",
"subScaledW",
"=",
"(",
"scaledW",
"/",
"2",
")",
"|",
"0",
",",
"subScaledH",
"=",
"(",
"scaledH",
"/",
"2",
")",
"|",
"0",
",",
"x",
"=",
"this",
".",
"getCurrentOffsetX",
"(",
")",
",",
"y",
"=",
"this",
".",
"getCurrentOffsetY",
"(",
")",
",",
"drawX",
"=",
"this",
".",
"x",
"+",
"this",
".",
"getCurrentShiftX",
"(",
")",
",",
"drawY",
"=",
"this",
".",
"y",
"+",
"this",
".",
"getCurrentShiftY",
"(",
")",
",",
"mapOffsetX",
"=",
"this",
".",
"currentMap",
"&&",
"this",
".",
"currentMap",
".",
"viewportX",
"||",
"0",
",",
"mapOffsetY",
"=",
"this",
".",
"currentMap",
"&&",
"this",
".",
"currentMap",
".",
"viewportY",
"||",
"0",
";",
"if",
"(",
"$",
".",
"isEmptyObject",
"(",
"this",
".",
"fxQueue",
")",
")",
"{",
"if",
"(",
"this",
".",
"type",
"===",
"'enemy1'",
"&&",
"window",
".",
"todo",
")",
"var",
"date",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"destCtx",
".",
"drawImage",
"(",
"this",
".",
"image",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"drawX",
"+",
"mapOffsetX",
",",
"drawY",
"+",
"mapOffsetY",
",",
"scaledW",
",",
"scaledH",
")",
";",
"if",
"(",
"this",
".",
"type",
"===",
"'enemy1'",
"&&",
"window",
".",
"todo",
")",
"{",
"var",
"date2",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"console",
".",
"log",
"(",
"'drawSprite call duration:'",
",",
"date2",
"-",
"date",
")",
";",
"}",
"if",
"(",
"this",
".",
"isDebug",
"===",
"true",
"||",
"debug",
"===",
"true",
")",
"{",
"this",
".",
"showHitBox",
"(",
"destCtx",
")",
";",
"}",
"}",
"else",
"{",
"this",
".",
"executeFx",
"(",
"destCtx",
")",
";",
"destCtx",
".",
"save",
"(",
")",
";",
"destCtx",
".",
"translate",
"(",
"drawX",
"+",
"mapOffsetX",
"+",
"subScaledW",
",",
"drawY",
"+",
"mapOffsetY",
"+",
"subScaledH",
")",
";",
"destCtx",
".",
"rotate",
"(",
"this",
".",
"angle",
")",
";",
"destCtx",
".",
"drawImage",
"(",
"this",
".",
"image",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"-",
"subScaledW",
",",
"-",
"subScaledH",
",",
"scaledW",
",",
"scaledH",
")",
";",
"if",
"(",
"this",
".",
"isDebug",
"===",
"true",
"||",
"debug",
"===",
"true",
")",
"{",
"this",
".",
"showHitBox",
"(",
"destCtx",
")",
";",
"}",
"destCtx",
".",
"restore",
"(",
")",
";",
"}",
"}"
] | we simply override the draw method | [
"we",
"simply",
"override",
"the",
"draw",
"method"
] | 5efe8ca3058986efc4af91fa3dbb03b716899e81 | https://github.com/AthenaJS/athenajs/blob/5efe8ca3058986efc4af91fa3dbb03b716899e81/js/Scene/default/Hud.js#L16-L64 | train |
|
graphology/graphology-metrics | centrality/degree.js | abstractDegreeCentrality | function abstractDegreeCentrality(assign, method, graph, options) {
var name = method + 'Centrality';
if (!isGraph(graph))
throw new Error('graphology-centrality/' + name + ': the given graph is not a valid graphology instance.');
if (method !== 'degree' && graph.type === 'undirected')
throw new Error('graphology-centrality/' + name + ': cannot compute ' + method + ' centrality on an undirected graph.');
// Solving options
options = options || {};
var attributes = options.attributes || {};
var centralityAttribute = attributes.centrality || name;
// Variables
var order = graph.order,
nodes = graph.nodes(),
getDegree = graph[method].bind(graph),
centralities = {};
if (order === 0)
return assign ? undefined : centralities;
var s = 1 / (order - 1);
// Iteration variables
var node,
centrality,
i;
for (i = 0; i < order; i++) {
node = nodes[i];
centrality = getDegree(node) * s;
if (assign)
graph.setNodeAttribute(node, centralityAttribute, centrality);
else
centralities[node] = centrality;
}
return assign ? undefined : centralities;
} | javascript | function abstractDegreeCentrality(assign, method, graph, options) {
var name = method + 'Centrality';
if (!isGraph(graph))
throw new Error('graphology-centrality/' + name + ': the given graph is not a valid graphology instance.');
if (method !== 'degree' && graph.type === 'undirected')
throw new Error('graphology-centrality/' + name + ': cannot compute ' + method + ' centrality on an undirected graph.');
// Solving options
options = options || {};
var attributes = options.attributes || {};
var centralityAttribute = attributes.centrality || name;
// Variables
var order = graph.order,
nodes = graph.nodes(),
getDegree = graph[method].bind(graph),
centralities = {};
if (order === 0)
return assign ? undefined : centralities;
var s = 1 / (order - 1);
// Iteration variables
var node,
centrality,
i;
for (i = 0; i < order; i++) {
node = nodes[i];
centrality = getDegree(node) * s;
if (assign)
graph.setNodeAttribute(node, centralityAttribute, centrality);
else
centralities[node] = centrality;
}
return assign ? undefined : centralities;
} | [
"function",
"abstractDegreeCentrality",
"(",
"assign",
",",
"method",
",",
"graph",
",",
"options",
")",
"{",
"var",
"name",
"=",
"method",
"+",
"'Centrality'",
";",
"if",
"(",
"!",
"isGraph",
"(",
"graph",
")",
")",
"throw",
"new",
"Error",
"(",
"'graphology-centrality/'",
"+",
"name",
"+",
"': the given graph is not a valid graphology instance.'",
")",
";",
"if",
"(",
"method",
"!==",
"'degree'",
"&&",
"graph",
".",
"type",
"===",
"'undirected'",
")",
"throw",
"new",
"Error",
"(",
"'graphology-centrality/'",
"+",
"name",
"+",
"': cannot compute '",
"+",
"method",
"+",
"' centrality on an undirected graph.'",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"attributes",
"=",
"options",
".",
"attributes",
"||",
"{",
"}",
";",
"var",
"centralityAttribute",
"=",
"attributes",
".",
"centrality",
"||",
"name",
";",
"var",
"order",
"=",
"graph",
".",
"order",
",",
"nodes",
"=",
"graph",
".",
"nodes",
"(",
")",
",",
"getDegree",
"=",
"graph",
"[",
"method",
"]",
".",
"bind",
"(",
"graph",
")",
",",
"centralities",
"=",
"{",
"}",
";",
"if",
"(",
"order",
"===",
"0",
")",
"return",
"assign",
"?",
"undefined",
":",
"centralities",
";",
"var",
"s",
"=",
"1",
"/",
"(",
"order",
"-",
"1",
")",
";",
"var",
"node",
",",
"centrality",
",",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"order",
";",
"i",
"++",
")",
"{",
"node",
"=",
"nodes",
"[",
"i",
"]",
";",
"centrality",
"=",
"getDegree",
"(",
"node",
")",
"*",
"s",
";",
"if",
"(",
"assign",
")",
"graph",
".",
"setNodeAttribute",
"(",
"node",
",",
"centralityAttribute",
",",
"centrality",
")",
";",
"else",
"centralities",
"[",
"node",
"]",
"=",
"centrality",
";",
"}",
"return",
"assign",
"?",
"undefined",
":",
"centralities",
";",
"}"
] | Asbtract function to perform any kind of degree centrality.
Intuitively, the degree centrality of a node is the fraction of nodes it
is connected to.
@param {boolean} assign - Whether to assign the result to the nodes.
@param {string} method - Method of the graph to get the degree.
@param {Graph} graph - A graphology instance.
@param {object} [options] - Options:
@param {object} [attributes] - Custom attribute names:
@param {string} [centrality] - Name of the attribute to assign.
@return {object|void} | [
"Asbtract",
"function",
"to",
"perform",
"any",
"kind",
"of",
"degree",
"centrality",
"."
] | bf920856140994251fa799f87f58f42bc06f53e6 | https://github.com/graphology/graphology-metrics/blob/bf920856140994251fa799f87f58f42bc06f53e6/centrality/degree.js#L23-L66 | train |
graphology/graphology-metrics | density.js | simpleSizeForMultiGraphs | function simpleSizeForMultiGraphs(graph) {
var nodes = graph.nodes(),
size = 0,
i,
l;
for (i = 0, l = nodes.length; i < l; i++) {
size += graph.outNeighbors(nodes[i]).length;
size += graph.undirectedNeighbors(nodes[i]).length / 2;
}
return size;
} | javascript | function simpleSizeForMultiGraphs(graph) {
var nodes = graph.nodes(),
size = 0,
i,
l;
for (i = 0, l = nodes.length; i < l; i++) {
size += graph.outNeighbors(nodes[i]).length;
size += graph.undirectedNeighbors(nodes[i]).length / 2;
}
return size;
} | [
"function",
"simpleSizeForMultiGraphs",
"(",
"graph",
")",
"{",
"var",
"nodes",
"=",
"graph",
".",
"nodes",
"(",
")",
",",
"size",
"=",
"0",
",",
"i",
",",
"l",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"nodes",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"size",
"+=",
"graph",
".",
"outNeighbors",
"(",
"nodes",
"[",
"i",
"]",
")",
".",
"length",
";",
"size",
"+=",
"graph",
".",
"undirectedNeighbors",
"(",
"nodes",
"[",
"i",
"]",
")",
".",
"length",
"/",
"2",
";",
"}",
"return",
"size",
";",
"}"
] | Returns the size a multi graph would have if it were a simple one.
@param {Graph} graph - Target graph.
@return {number} | [
"Returns",
"the",
"size",
"a",
"multi",
"graph",
"would",
"have",
"if",
"it",
"were",
"a",
"simple",
"one",
"."
] | bf920856140994251fa799f87f58f42bc06f53e6 | https://github.com/graphology/graphology-metrics/blob/bf920856140994251fa799f87f58f42bc06f53e6/density.js#L53-L65 | train |
graphology/graphology-metrics | density.js | abstractDensity | function abstractDensity(type, multi, graph) {
var order,
size;
// Retrieving order & size
if (arguments.length > 3) {
order = graph;
size = arguments[3];
if (typeof order !== 'number')
throw new Error('graphology-metrics/density: given order is not a number.');
if (typeof size !== 'number')
throw new Error('graphology-metrics/density: given size is not a number.');
}
else {
if (!isGraph(graph))
throw new Error('graphology-metrics/density: given graph is not a valid graphology instance.');
order = graph.order;
size = graph.size;
if (graph.multi && multi === false)
size = simpleSizeForMultiGraphs(graph);
}
// When the graph has only one node, its density is 0
if (order < 2)
return 0;
// Guessing type & multi
if (type === null)
type = graph.type;
if (multi === null)
multi = graph.multi;
// Getting the correct function
var fn;
if (type === 'undirected')
fn = undirectedDensity;
else if (type === 'directed')
fn = directedDensity;
else
fn = mixedDensity;
// Applying the function
return fn(order, size);
} | javascript | function abstractDensity(type, multi, graph) {
var order,
size;
// Retrieving order & size
if (arguments.length > 3) {
order = graph;
size = arguments[3];
if (typeof order !== 'number')
throw new Error('graphology-metrics/density: given order is not a number.');
if (typeof size !== 'number')
throw new Error('graphology-metrics/density: given size is not a number.');
}
else {
if (!isGraph(graph))
throw new Error('graphology-metrics/density: given graph is not a valid graphology instance.');
order = graph.order;
size = graph.size;
if (graph.multi && multi === false)
size = simpleSizeForMultiGraphs(graph);
}
// When the graph has only one node, its density is 0
if (order < 2)
return 0;
// Guessing type & multi
if (type === null)
type = graph.type;
if (multi === null)
multi = graph.multi;
// Getting the correct function
var fn;
if (type === 'undirected')
fn = undirectedDensity;
else if (type === 'directed')
fn = directedDensity;
else
fn = mixedDensity;
// Applying the function
return fn(order, size);
} | [
"function",
"abstractDensity",
"(",
"type",
",",
"multi",
",",
"graph",
")",
"{",
"var",
"order",
",",
"size",
";",
"if",
"(",
"arguments",
".",
"length",
">",
"3",
")",
"{",
"order",
"=",
"graph",
";",
"size",
"=",
"arguments",
"[",
"3",
"]",
";",
"if",
"(",
"typeof",
"order",
"!==",
"'number'",
")",
"throw",
"new",
"Error",
"(",
"'graphology-metrics/density: given order is not a number.'",
")",
";",
"if",
"(",
"typeof",
"size",
"!==",
"'number'",
")",
"throw",
"new",
"Error",
"(",
"'graphology-metrics/density: given size is not a number.'",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"isGraph",
"(",
"graph",
")",
")",
"throw",
"new",
"Error",
"(",
"'graphology-metrics/density: given graph is not a valid graphology instance.'",
")",
";",
"order",
"=",
"graph",
".",
"order",
";",
"size",
"=",
"graph",
".",
"size",
";",
"if",
"(",
"graph",
".",
"multi",
"&&",
"multi",
"===",
"false",
")",
"size",
"=",
"simpleSizeForMultiGraphs",
"(",
"graph",
")",
";",
"}",
"if",
"(",
"order",
"<",
"2",
")",
"return",
"0",
";",
"if",
"(",
"type",
"===",
"null",
")",
"type",
"=",
"graph",
".",
"type",
";",
"if",
"(",
"multi",
"===",
"null",
")",
"multi",
"=",
"graph",
".",
"multi",
";",
"var",
"fn",
";",
"if",
"(",
"type",
"===",
"'undirected'",
")",
"fn",
"=",
"undirectedDensity",
";",
"else",
"if",
"(",
"type",
"===",
"'directed'",
")",
"fn",
"=",
"directedDensity",
";",
"else",
"fn",
"=",
"mixedDensity",
";",
"return",
"fn",
"(",
"order",
",",
"size",
")",
";",
"}"
] | Returns the density for the given parameters.
Arity 3:
@param {boolean} type - Type of density.
@param {boolean} multi - Compute multi density?
@param {Graph} graph - Target graph.
Arity 4:
@param {boolean} type - Type of density.
@param {boolean} multi - Compute multi density?
@param {number} order - Number of nodes in the graph.
@param {number} size - Number of edges in the graph.
@return {number} | [
"Returns",
"the",
"density",
"for",
"the",
"given",
"parameters",
"."
] | bf920856140994251fa799f87f58f42bc06f53e6 | https://github.com/graphology/graphology-metrics/blob/bf920856140994251fa799f87f58f42bc06f53e6/density.js#L83-L132 | train |
LaxarJS/laxar | lib/runtime/log.js | Logger | function Logger( configuration, channels = [] ) {
this.levels = { ...levels, ...configuration.get( 'logging.levels' ) };
this.queueSize_ = 100;
this.channels_ = channels;
this.counter_ = 0;
this.messageQueue_ = [];
this.threshold_ = 0;
this.tags_ = {};
this.levelToName_ = ( levels => {
const result = {};
forEach( levels, ( level, levelName ) => {
this[ levelName.toLowerCase() ] = ( ...args ) => {
this.log( level, ...args, BLACKBOX );
};
result[ level ] = levelName;
} );
return result;
} )( this.levels );
this.setLogThreshold( configuration.ensure( 'logging.threshold' ) );
} | javascript | function Logger( configuration, channels = [] ) {
this.levels = { ...levels, ...configuration.get( 'logging.levels' ) };
this.queueSize_ = 100;
this.channels_ = channels;
this.counter_ = 0;
this.messageQueue_ = [];
this.threshold_ = 0;
this.tags_ = {};
this.levelToName_ = ( levels => {
const result = {};
forEach( levels, ( level, levelName ) => {
this[ levelName.toLowerCase() ] = ( ...args ) => {
this.log( level, ...args, BLACKBOX );
};
result[ level ] = levelName;
} );
return result;
} )( this.levels );
this.setLogThreshold( configuration.ensure( 'logging.threshold' ) );
} | [
"function",
"Logger",
"(",
"configuration",
",",
"channels",
"=",
"[",
"]",
")",
"{",
"this",
".",
"levels",
"=",
"{",
"...",
"levels",
",",
"...",
"configuration",
".",
"get",
"(",
"'logging.levels'",
")",
"}",
";",
"this",
".",
"queueSize_",
"=",
"100",
";",
"this",
".",
"channels_",
"=",
"channels",
";",
"this",
".",
"counter_",
"=",
"0",
";",
"this",
".",
"messageQueue_",
"=",
"[",
"]",
";",
"this",
".",
"threshold_",
"=",
"0",
";",
"this",
".",
"tags_",
"=",
"{",
"}",
";",
"this",
".",
"levelToName_",
"=",
"(",
"levels",
"=>",
"{",
"const",
"result",
"=",
"{",
"}",
";",
"forEach",
"(",
"levels",
",",
"(",
"level",
",",
"levelName",
")",
"=>",
"{",
"this",
"[",
"levelName",
".",
"toLowerCase",
"(",
")",
"]",
"=",
"(",
"...",
"args",
")",
"=>",
"{",
"this",
".",
"log",
"(",
"level",
",",
"...",
"args",
",",
"BLACKBOX",
")",
";",
"}",
";",
"result",
"[",
"level",
"]",
"=",
"levelName",
";",
"}",
")",
";",
"return",
"result",
";",
"}",
")",
"(",
"this",
".",
"levels",
")",
";",
"this",
".",
"setLogThreshold",
"(",
"configuration",
".",
"ensure",
"(",
"'logging.threshold'",
")",
")",
";",
"}"
] | eslint-disable-next-line valid-jsdoc
A flexible logger.
It is recommended to prefer this logger over `console.log` and friends, at least for any log messages that
might make their way into production code. For once, this logger is safe to use across browsers and allows
to attach additional channels for routing messages to (i.e. to send them to a server process for
persistence). If a browser console is available, messages will be logged to that console using the builtin
console channel.
For testing, a silent mock for this logger is used, making it simple to test the logging behavior of
widgets and activities, while avoiding noisy log messages in the test runner output.
All messages produced
@constructor
@private | [
"eslint",
"-",
"disable",
"-",
"next",
"-",
"line",
"valid",
"-",
"jsdoc",
"A",
"flexible",
"logger",
"."
] | 2d6e03feb2b7e0a9916742de0edd92ac15c5d45f | https://github.com/LaxarJS/laxar/blob/2d6e03feb2b7e0a9916742de0edd92ac15c5d45f/lib/runtime/log.js#L75-L97 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | getDatabase | function getDatabase() {
var mongoAdapter = this;
expect(arguments).to.have.length(
0,
'Invalid arguments length when getting a database in a MongoAdapter ' +
'(it has to be passed no arguments)'
);
return new Promise(function (resolve, reject) {
if (_databaseIsLocked || !_database) {
mongoAdapter
.openConnection()
.then(function () {
resolve(_database);
})
.catch(reject);
} else {
resolve(_database);
}
});
} | javascript | function getDatabase() {
var mongoAdapter = this;
expect(arguments).to.have.length(
0,
'Invalid arguments length when getting a database in a MongoAdapter ' +
'(it has to be passed no arguments)'
);
return new Promise(function (resolve, reject) {
if (_databaseIsLocked || !_database) {
mongoAdapter
.openConnection()
.then(function () {
resolve(_database);
})
.catch(reject);
} else {
resolve(_database);
}
});
} | [
"function",
"getDatabase",
"(",
")",
"{",
"var",
"mongoAdapter",
"=",
"this",
";",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"0",
",",
"'Invalid arguments length when getting a database in a MongoAdapter '",
"+",
"'(it has to be passed no arguments)'",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"_databaseIsLocked",
"||",
"!",
"_database",
")",
"{",
"mongoAdapter",
".",
"openConnection",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"resolve",
"(",
"_database",
")",
";",
"}",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
"_database",
")",
";",
"}",
"}",
")",
";",
"}"
] | Gets the MongoClient Db object to be use to perform the operations.
@name module:back4app-entity-mongodb.MongoAdapter#getDatabase
@function
@returns {Promise.<Db|Error>} Promise that returns the MongoClient Db
object if succeed and the Error if failed.
@example
mongoAdapter.getDatabase()
.then(function (database) {
database.createCollection('myCollection');
})
.catch(function (error) {
console.log(error);
}); | [
"Gets",
"the",
"MongoClient",
"Db",
"object",
"to",
"be",
"use",
"to",
"perform",
"the",
"operations",
"."
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L89-L110 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | openConnection | function openConnection() {
expect(arguments).to.have.length(
0,
'Invalid arguments length when opening a connection in a MongoAdapter ' +
'(it has to be passed no arguments)'
);
return new Promise(function (resolve, reject) {
if (_databaseIsLocked) {
_databaseRequestQueue.push(function () {
openConnection().then(resolve).catch(reject);
});
} else if (_database) {
resolve();
} else {
_databaseIsLocked = true;
MongoClient
.connect(connectionUrl, connectionOptions)
.then(function (database) {
_database = database;
_databaseIsLocked = false;
resolve();
_processDatabaseRequestQueue();
})
.catch(function (error) {
_databaseIsLocked = false;
reject(error);
_processDatabaseRequestQueue();
});
}
});
} | javascript | function openConnection() {
expect(arguments).to.have.length(
0,
'Invalid arguments length when opening a connection in a MongoAdapter ' +
'(it has to be passed no arguments)'
);
return new Promise(function (resolve, reject) {
if (_databaseIsLocked) {
_databaseRequestQueue.push(function () {
openConnection().then(resolve).catch(reject);
});
} else if (_database) {
resolve();
} else {
_databaseIsLocked = true;
MongoClient
.connect(connectionUrl, connectionOptions)
.then(function (database) {
_database = database;
_databaseIsLocked = false;
resolve();
_processDatabaseRequestQueue();
})
.catch(function (error) {
_databaseIsLocked = false;
reject(error);
_processDatabaseRequestQueue();
});
}
});
} | [
"function",
"openConnection",
"(",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"0",
",",
"'Invalid arguments length when opening a connection in a MongoAdapter '",
"+",
"'(it has to be passed no arguments)'",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"_databaseIsLocked",
")",
"{",
"_databaseRequestQueue",
".",
"push",
"(",
"function",
"(",
")",
"{",
"openConnection",
"(",
")",
".",
"then",
"(",
"resolve",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"_database",
")",
"{",
"resolve",
"(",
")",
";",
"}",
"else",
"{",
"_databaseIsLocked",
"=",
"true",
";",
"MongoClient",
".",
"connect",
"(",
"connectionUrl",
",",
"connectionOptions",
")",
".",
"then",
"(",
"function",
"(",
"database",
")",
"{",
"_database",
"=",
"database",
";",
"_databaseIsLocked",
"=",
"false",
";",
"resolve",
"(",
")",
";",
"_processDatabaseRequestQueue",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"_databaseIsLocked",
"=",
"false",
";",
"reject",
"(",
"error",
")",
";",
"_processDatabaseRequestQueue",
"(",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Connects the adapter with the targeted Mongo database.
@name module:back4app-entity-mongodb.MongoAdapter#openConnection
@function
@returns {Promise.<undefined|Error>} Promise that returns nothing if
succeed and the Error if failed.
@example
mongoAdapter.openConnection()
.then(function () {
console.log('connection opened');
})
.catch(function (error) {
console.log(error);
}); | [
"Connects",
"the",
"adapter",
"with",
"the",
"targeted",
"Mongo",
"database",
"."
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L127-L159 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | closeConnection | function closeConnection() {
expect(arguments).to.have.length(
0,
'Invalid arguments length when closing a connection in a MongoAdapter ' +
'(it has to be passed no arguments)'
);
return new Promise(function (resolve, reject) {
if (_databaseIsLocked) {
_databaseRequestQueue.push(function () {
closeConnection()
.then(resolve)
.catch(reject);
});
} else if (!_database) {
resolve();
} else {
_databaseIsLocked = true;
_database
.close()
.then(function () {
_database = null;
_databaseIsLocked = false;
resolve();
_processDatabaseRequestQueue();
})
.catch(function (error) {
_databaseIsLocked = false;
reject(error);
_processDatabaseRequestQueue();
});
}
});
} | javascript | function closeConnection() {
expect(arguments).to.have.length(
0,
'Invalid arguments length when closing a connection in a MongoAdapter ' +
'(it has to be passed no arguments)'
);
return new Promise(function (resolve, reject) {
if (_databaseIsLocked) {
_databaseRequestQueue.push(function () {
closeConnection()
.then(resolve)
.catch(reject);
});
} else if (!_database) {
resolve();
} else {
_databaseIsLocked = true;
_database
.close()
.then(function () {
_database = null;
_databaseIsLocked = false;
resolve();
_processDatabaseRequestQueue();
})
.catch(function (error) {
_databaseIsLocked = false;
reject(error);
_processDatabaseRequestQueue();
});
}
});
} | [
"function",
"closeConnection",
"(",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"0",
",",
"'Invalid arguments length when closing a connection in a MongoAdapter '",
"+",
"'(it has to be passed no arguments)'",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"_databaseIsLocked",
")",
"{",
"_databaseRequestQueue",
".",
"push",
"(",
"function",
"(",
")",
"{",
"closeConnection",
"(",
")",
".",
"then",
"(",
"resolve",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"!",
"_database",
")",
"{",
"resolve",
"(",
")",
";",
"}",
"else",
"{",
"_databaseIsLocked",
"=",
"true",
";",
"_database",
".",
"close",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"_database",
"=",
"null",
";",
"_databaseIsLocked",
"=",
"false",
";",
"resolve",
"(",
")",
";",
"_processDatabaseRequestQueue",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"_databaseIsLocked",
"=",
"false",
";",
"reject",
"(",
"error",
")",
";",
"_processDatabaseRequestQueue",
"(",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Closes the current adapter' connection with MongoDB.
@name module:back4app-entity-mongodb.MongoAdapter#closeConnection
@function
@returns {Promise.<undefined|Error>} Promise that returns nothing if
succeed and the Error if failed.
@example
mongoAdapter.closeConnection()
.then(function () {
console.log('connection closed');
})
.catch(function (error) {
console.log(error);
}); | [
"Closes",
"the",
"current",
"adapter",
"connection",
"with",
"MongoDB",
"."
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L176-L209 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | loadEntity | function loadEntity(Entity) {
expect(arguments).to.have.length(
1,
'Invalid arguments length when loading an entity in a ' +
'MongoAdapter (it has to be passed 1 argument)'
);
expect(Entity).to.be.a(
'function',
'Invalid argument "Entity" when loading an entity in a ' +
'MongoAdapter (it has to be an Entity class)'
);
expect(classes.isGeneral(entity.models.Entity, Entity)).to.be.equal(
true,
'Invalid argument "Entity" when loading an entity in a ' +
'MongoAdapter (it has to be an Entity class)'
);
expect(Entity.dataName).to.not.equal(
'',
'The dataName of an Entity cannot be an empty string in a MongoAdapter'
);
expect(Entity.dataName).to.not.match(
/^system\./,
'The dataName of an Entity cannot start with "system." in a MongoAdapter'
);
expect(Entity.dataName).to.not.contain(
'$',
'The dataName of an Entity cannot contain "$" in a MongoAdapter'
);
expect(Entity.dataName).to.not.contain(
'\0',
'The dataName of an Entity cannot contain "\0" in a MongoAdapter'
);
expect(_collections).to.not.have.ownProperty(
Entity.dataName,
'Failed to load the Entity called "' + Entity.specification.name +
'" because it is not possible to have Entities with duplicated ' +
'dataName in a MongoAdapter'
);
_collections[Entity.dataName] = [];
} | javascript | function loadEntity(Entity) {
expect(arguments).to.have.length(
1,
'Invalid arguments length when loading an entity in a ' +
'MongoAdapter (it has to be passed 1 argument)'
);
expect(Entity).to.be.a(
'function',
'Invalid argument "Entity" when loading an entity in a ' +
'MongoAdapter (it has to be an Entity class)'
);
expect(classes.isGeneral(entity.models.Entity, Entity)).to.be.equal(
true,
'Invalid argument "Entity" when loading an entity in a ' +
'MongoAdapter (it has to be an Entity class)'
);
expect(Entity.dataName).to.not.equal(
'',
'The dataName of an Entity cannot be an empty string in a MongoAdapter'
);
expect(Entity.dataName).to.not.match(
/^system\./,
'The dataName of an Entity cannot start with "system." in a MongoAdapter'
);
expect(Entity.dataName).to.not.contain(
'$',
'The dataName of an Entity cannot contain "$" in a MongoAdapter'
);
expect(Entity.dataName).to.not.contain(
'\0',
'The dataName of an Entity cannot contain "\0" in a MongoAdapter'
);
expect(_collections).to.not.have.ownProperty(
Entity.dataName,
'Failed to load the Entity called "' + Entity.specification.name +
'" because it is not possible to have Entities with duplicated ' +
'dataName in a MongoAdapter'
);
_collections[Entity.dataName] = [];
} | [
"function",
"loadEntity",
"(",
"Entity",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"1",
",",
"'Invalid arguments length when loading an entity in a '",
"+",
"'MongoAdapter (it has to be passed 1 argument)'",
")",
";",
"expect",
"(",
"Entity",
")",
".",
"to",
".",
"be",
".",
"a",
"(",
"'function'",
",",
"'Invalid argument \"Entity\" when loading an entity in a '",
"+",
"'MongoAdapter (it has to be an Entity class)'",
")",
";",
"expect",
"(",
"classes",
".",
"isGeneral",
"(",
"entity",
".",
"models",
".",
"Entity",
",",
"Entity",
")",
")",
".",
"to",
".",
"be",
".",
"equal",
"(",
"true",
",",
"'Invalid argument \"Entity\" when loading an entity in a '",
"+",
"'MongoAdapter (it has to be an Entity class)'",
")",
";",
"expect",
"(",
"Entity",
".",
"dataName",
")",
".",
"to",
".",
"not",
".",
"equal",
"(",
"''",
",",
"'The dataName of an Entity cannot be an empty string in a MongoAdapter'",
")",
";",
"expect",
"(",
"Entity",
".",
"dataName",
")",
".",
"to",
".",
"not",
".",
"match",
"(",
"/",
"^system\\.",
"/",
",",
"'The dataName of an Entity cannot start with \"system.\" in a MongoAdapter'",
")",
";",
"expect",
"(",
"Entity",
".",
"dataName",
")",
".",
"to",
".",
"not",
".",
"contain",
"(",
"'$'",
",",
"'The dataName of an Entity cannot contain \"$\" in a MongoAdapter'",
")",
";",
"expect",
"(",
"Entity",
".",
"dataName",
")",
".",
"to",
".",
"not",
".",
"contain",
"(",
"'\\0'",
",",
"\\0",
")",
";",
"'The dataName of an Entity cannot contain \"\\0\" in a MongoAdapter'",
"\\0",
"}"
] | Registers the Entity on Adapter's Collection Dictionary, if valid.
@name module:back4app-entity-mongodb.MongoAdapter#loadEntity
@function
@param {!module:back4app-entity/models/Entity} Entity The Entity Class
to be validated and added to Adapter's Collection dictionary.
@example
Entity.adapter.loadEntity(Entity); | [
"Registers",
"the",
"Entity",
"on",
"Adapter",
"s",
"Collection",
"Dictionary",
"if",
"valid",
"."
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L235-L282 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | loadEntityAttribute | function loadEntityAttribute(Entity, attribute) {
expect(arguments).to.have.length(
2,
'Invalid arguments length when loading an entity attribute in a ' +
'MongoAdapter (it has to be passed 2 arguments)'
);
expect(Entity).to.be.a(
'function',
'Invalid argument "Entity" when loading an entity in a ' +
'MongoAdapter (it has to be an Entity class)'
);
expect(classes.isGeneral(entity.models.Entity, Entity)).to.be.equal(
true,
'Invalid argument "Entity" when loading an entity attribute in a ' +
'MongoAdapter (it has to be an Entity class)'
);
expect(attribute).to.be.an.instanceOf(
Attribute,
'Invalid argument "attribute" when loading an entity attribute in a ' +
'MongoAdapter (it has to be an Attribute instance)'
);
var dataName = attribute.getDataName(Entity.adapterName);
expect(dataName).to.not.match(
/^\$/,
'The dataName of an Attribute cannot start with "$" in a MongoAdapter'
);
expect(dataName).to.not.contain(
'.',
'The dataName of an Attribute cannot contain "." in a MongoAdapter'
);
expect(dataName).to.not.contain(
'\0',
'The dataName of an Attribute cannot contain "\0" in a MongoAdapter'
);
expect(dataName).to.not.equal(
'Entity',
'The dataName of an Attribute cannot be equal to "Entity" in a ' +
'MongoAdapter'
);
expect(dataName).to.not.equal(
'_id',
'The dataName of an Attribute cannot be equal to "_id" in a MongoAdapter'
);
expect(_collections).to.have.ownProperty(
Entity.dataName,
'Failed to load the attribute in an Entity called "' +
Entity.specification.name + '" because the Entity was not loaded yet'
);
expect(_collections[Entity.dataName]).to.not.contain(
dataName,
'Failed to load the attribute "' + attribute.name + '" in an Entity ' +
'called "' + Entity.specification.name + '" because it is not ' +
'possible to have attributes of the same Entity with duplicated ' +
'dataName in a MongoAdapter'
);
_collections[Entity.dataName].push(dataName);
} | javascript | function loadEntityAttribute(Entity, attribute) {
expect(arguments).to.have.length(
2,
'Invalid arguments length when loading an entity attribute in a ' +
'MongoAdapter (it has to be passed 2 arguments)'
);
expect(Entity).to.be.a(
'function',
'Invalid argument "Entity" when loading an entity in a ' +
'MongoAdapter (it has to be an Entity class)'
);
expect(classes.isGeneral(entity.models.Entity, Entity)).to.be.equal(
true,
'Invalid argument "Entity" when loading an entity attribute in a ' +
'MongoAdapter (it has to be an Entity class)'
);
expect(attribute).to.be.an.instanceOf(
Attribute,
'Invalid argument "attribute" when loading an entity attribute in a ' +
'MongoAdapter (it has to be an Attribute instance)'
);
var dataName = attribute.getDataName(Entity.adapterName);
expect(dataName).to.not.match(
/^\$/,
'The dataName of an Attribute cannot start with "$" in a MongoAdapter'
);
expect(dataName).to.not.contain(
'.',
'The dataName of an Attribute cannot contain "." in a MongoAdapter'
);
expect(dataName).to.not.contain(
'\0',
'The dataName of an Attribute cannot contain "\0" in a MongoAdapter'
);
expect(dataName).to.not.equal(
'Entity',
'The dataName of an Attribute cannot be equal to "Entity" in a ' +
'MongoAdapter'
);
expect(dataName).to.not.equal(
'_id',
'The dataName of an Attribute cannot be equal to "_id" in a MongoAdapter'
);
expect(_collections).to.have.ownProperty(
Entity.dataName,
'Failed to load the attribute in an Entity called "' +
Entity.specification.name + '" because the Entity was not loaded yet'
);
expect(_collections[Entity.dataName]).to.not.contain(
dataName,
'Failed to load the attribute "' + attribute.name + '" in an Entity ' +
'called "' + Entity.specification.name + '" because it is not ' +
'possible to have attributes of the same Entity with duplicated ' +
'dataName in a MongoAdapter'
);
_collections[Entity.dataName].push(dataName);
} | [
"function",
"loadEntityAttribute",
"(",
"Entity",
",",
"attribute",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"2",
",",
"'Invalid arguments length when loading an entity attribute in a '",
"+",
"'MongoAdapter (it has to be passed 2 arguments)'",
")",
";",
"expect",
"(",
"Entity",
")",
".",
"to",
".",
"be",
".",
"a",
"(",
"'function'",
",",
"'Invalid argument \"Entity\" when loading an entity in a '",
"+",
"'MongoAdapter (it has to be an Entity class)'",
")",
";",
"expect",
"(",
"classes",
".",
"isGeneral",
"(",
"entity",
".",
"models",
".",
"Entity",
",",
"Entity",
")",
")",
".",
"to",
".",
"be",
".",
"equal",
"(",
"true",
",",
"'Invalid argument \"Entity\" when loading an entity attribute in a '",
"+",
"'MongoAdapter (it has to be an Entity class)'",
")",
";",
"expect",
"(",
"attribute",
")",
".",
"to",
".",
"be",
".",
"an",
".",
"instanceOf",
"(",
"Attribute",
",",
"'Invalid argument \"attribute\" when loading an entity attribute in a '",
"+",
"'MongoAdapter (it has to be an Attribute instance)'",
")",
";",
"var",
"dataName",
"=",
"attribute",
".",
"getDataName",
"(",
"Entity",
".",
"adapterName",
")",
";",
"expect",
"(",
"dataName",
")",
".",
"to",
".",
"not",
".",
"match",
"(",
"/",
"^\\$",
"/",
",",
"'The dataName of an Attribute cannot start with \"$\" in a MongoAdapter'",
")",
";",
"expect",
"(",
"dataName",
")",
".",
"to",
".",
"not",
".",
"contain",
"(",
"'.'",
",",
"'The dataName of an Attribute cannot contain \".\" in a MongoAdapter'",
")",
";",
"expect",
"(",
"dataName",
")",
".",
"to",
".",
"not",
".",
"contain",
"(",
"'\\0'",
",",
"\\0",
")",
";",
"'The dataName of an Attribute cannot contain \"\\0\" in a MongoAdapter'",
"\\0",
"expect",
"(",
"dataName",
")",
".",
"to",
".",
"not",
".",
"equal",
"(",
"'Entity'",
",",
"'The dataName of an Attribute cannot be equal to \"Entity\" in a '",
"+",
"'MongoAdapter'",
")",
";",
"expect",
"(",
"dataName",
")",
".",
"to",
".",
"not",
".",
"equal",
"(",
"'_id'",
",",
"'The dataName of an Attribute cannot be equal to \"_id\" in a MongoAdapter'",
")",
";",
"expect",
"(",
"_collections",
")",
".",
"to",
".",
"have",
".",
"ownProperty",
"(",
"Entity",
".",
"dataName",
",",
"'Failed to load the attribute in an Entity called \"'",
"+",
"Entity",
".",
"specification",
".",
"name",
"+",
"'\" because the Entity was not loaded yet'",
")",
";",
"}"
] | Registers the Attribute on the Entity on Collection Dictionary, if valid.
@name module:back4app-entity-mongodb.MongoAdapter#loadEntityAttribute
@function
@param {!module:back4app-entity/models/Entity} Entity The Entity Class
to have attribute validated and added to Entity on Collection dictionary.
@param {!module:back4app-entity/models/attributes.Attribute} attribute
The Attribute to be validated and added to Entity.
@example
_Entity.adapter.loadEntityAttribute(_Entity, attribute); | [
"Registers",
"the",
"Attribute",
"on",
"the",
"Entity",
"on",
"Collection",
"Dictionary",
"if",
"valid",
"."
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L295-L363 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | insertObject | function insertObject(entityObject) {
var mongoAdapter = this;
expect(arguments).to.have.length(
1,
'Invalid arguments length when inserting an object in a MongoAdapter ' +
'(it has to be passed 1 argument)'
);
return new Promise(function (resolve, reject) {
expect(entityObject).to.be.an.instanceOf(
Entity,
'Invalid argument "entityObject" when inserting an object in a ' +
'MongoAdapter (it has to be an Entity instance)'
);
var EntityClass = entityObject.Entity;
mongoAdapter
.getDatabase()
.then(function (database) {
return database
.collection(getEntityCollectionName(EntityClass))
.insertOne(
objectToDocument(entityObject)
);
})
.then(function (result) {
expect(result.insertedCount).to.equal(
1,
'Invalid result.insertedCount return of collection.insertOne ' +
'in MongoDB driver when inserting an Object (it should be 1)'
);
resolve();
})
.catch(reject);
});
} | javascript | function insertObject(entityObject) {
var mongoAdapter = this;
expect(arguments).to.have.length(
1,
'Invalid arguments length when inserting an object in a MongoAdapter ' +
'(it has to be passed 1 argument)'
);
return new Promise(function (resolve, reject) {
expect(entityObject).to.be.an.instanceOf(
Entity,
'Invalid argument "entityObject" when inserting an object in a ' +
'MongoAdapter (it has to be an Entity instance)'
);
var EntityClass = entityObject.Entity;
mongoAdapter
.getDatabase()
.then(function (database) {
return database
.collection(getEntityCollectionName(EntityClass))
.insertOne(
objectToDocument(entityObject)
);
})
.then(function (result) {
expect(result.insertedCount).to.equal(
1,
'Invalid result.insertedCount return of collection.insertOne ' +
'in MongoDB driver when inserting an Object (it should be 1)'
);
resolve();
})
.catch(reject);
});
} | [
"function",
"insertObject",
"(",
"entityObject",
")",
"{",
"var",
"mongoAdapter",
"=",
"this",
";",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"1",
",",
"'Invalid arguments length when inserting an object in a MongoAdapter '",
"+",
"'(it has to be passed 1 argument)'",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"expect",
"(",
"entityObject",
")",
".",
"to",
".",
"be",
".",
"an",
".",
"instanceOf",
"(",
"Entity",
",",
"'Invalid argument \"entityObject\" when inserting an object in a '",
"+",
"'MongoAdapter (it has to be an Entity instance)'",
")",
";",
"var",
"EntityClass",
"=",
"entityObject",
".",
"Entity",
";",
"mongoAdapter",
".",
"getDatabase",
"(",
")",
".",
"then",
"(",
"function",
"(",
"database",
")",
"{",
"return",
"database",
".",
"collection",
"(",
"getEntityCollectionName",
"(",
"EntityClass",
")",
")",
".",
"insertOne",
"(",
"objectToDocument",
"(",
"entityObject",
")",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"expect",
"(",
"result",
".",
"insertedCount",
")",
".",
"to",
".",
"equal",
"(",
"1",
",",
"'Invalid result.insertedCount return of collection.insertOne '",
"+",
"'in MongoDB driver when inserting an Object (it should be 1)'",
")",
";",
"resolve",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"}"
] | Saves an Entity instance, inserting on DB.
@name module:back4app-entity-mongodb.MongoAdapter#insertObject
@function
@param {!module:module:back4app-entity/models/Entity} entityObject
Entity instance being saved, to insert on DB.
@returns {Promise.<undefined|Error>} Promise that returns nothing if succeed
and the Error if failed.
@example
entity.adapter.insertObject(entity)
.then(function () {
entity.isNew = false;
entity.clean();
}); | [
"Saves",
"an",
"Entity",
"instance",
"inserting",
"on",
"DB",
"."
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L393-L431 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | updateObject | function updateObject(entityObject) {
var mongoAdapter = this;
expect(arguments).to.have.length(
1,
'Invalid arguments length when updating an object in a MongoAdapter ' +
'(it has to be passed 1 argument)'
);
return new Promise(function (resolve, reject) {
expect(entityObject).to.be.an.instanceOf(
Entity,
'Invalid argument "entityObject" when updating an object in a ' +
'MongoAdapter (it has to be an Entity instance)'
);
var EntityClass = entityObject.Entity;
mongoAdapter
.getDatabase()
.then(function (database) {
return database
.collection(getEntityCollectionName(EntityClass))
.updateOne(
{_id: entityObject.id},
{$set: objectToDocument(entityObject, true)}
);
})
.then(function (result) {
expect(result.matchedCount).to.equal(
1,
'Invalid result.matchedCount return of collection.updateOne ' +
'in MongoDB driver when inserting an Object (it should be 1)'
);
resolve();
})
.catch(reject);
});
} | javascript | function updateObject(entityObject) {
var mongoAdapter = this;
expect(arguments).to.have.length(
1,
'Invalid arguments length when updating an object in a MongoAdapter ' +
'(it has to be passed 1 argument)'
);
return new Promise(function (resolve, reject) {
expect(entityObject).to.be.an.instanceOf(
Entity,
'Invalid argument "entityObject" when updating an object in a ' +
'MongoAdapter (it has to be an Entity instance)'
);
var EntityClass = entityObject.Entity;
mongoAdapter
.getDatabase()
.then(function (database) {
return database
.collection(getEntityCollectionName(EntityClass))
.updateOne(
{_id: entityObject.id},
{$set: objectToDocument(entityObject, true)}
);
})
.then(function (result) {
expect(result.matchedCount).to.equal(
1,
'Invalid result.matchedCount return of collection.updateOne ' +
'in MongoDB driver when inserting an Object (it should be 1)'
);
resolve();
})
.catch(reject);
});
} | [
"function",
"updateObject",
"(",
"entityObject",
")",
"{",
"var",
"mongoAdapter",
"=",
"this",
";",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"1",
",",
"'Invalid arguments length when updating an object in a MongoAdapter '",
"+",
"'(it has to be passed 1 argument)'",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"expect",
"(",
"entityObject",
")",
".",
"to",
".",
"be",
".",
"an",
".",
"instanceOf",
"(",
"Entity",
",",
"'Invalid argument \"entityObject\" when updating an object in a '",
"+",
"'MongoAdapter (it has to be an Entity instance)'",
")",
";",
"var",
"EntityClass",
"=",
"entityObject",
".",
"Entity",
";",
"mongoAdapter",
".",
"getDatabase",
"(",
")",
".",
"then",
"(",
"function",
"(",
"database",
")",
"{",
"return",
"database",
".",
"collection",
"(",
"getEntityCollectionName",
"(",
"EntityClass",
")",
")",
".",
"updateOne",
"(",
"{",
"_id",
":",
"entityObject",
".",
"id",
"}",
",",
"{",
"$set",
":",
"objectToDocument",
"(",
"entityObject",
",",
"true",
")",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"expect",
"(",
"result",
".",
"matchedCount",
")",
".",
"to",
".",
"equal",
"(",
"1",
",",
"'Invalid result.matchedCount return of collection.updateOne '",
"+",
"'in MongoDB driver when inserting an Object (it should be 1)'",
")",
";",
"resolve",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"}"
] | Updates an Entity instance, changing on DB.
@name module:back4app-entity-mongodb.MongoAdapter#updateObject
@function
@param {!module:module:back4app-entity/models/Entity} entityObject
Entity instance being updates, to modify on DB.
@returns {Promise.<undefined|Error>} Promise that returns nothing if succeed
and the Error if failed.
@example
entity.adapter.updateObject(entity)
.then(function () {
entity.isNew = false;
entity.clean();
}); | [
"Updates",
"an",
"Entity",
"instance",
"changing",
"on",
"DB",
"."
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L448-L487 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | objectToDocument | function objectToDocument(entityObject, onlyDirty) {
expect(arguments).to.have.length.below(
3,
'Invalid arguments length when converting an entity object in a ' +
'MongoDB document (it has to be passed less than 3 arguments)'
);
expect(entityObject).to.be.an.instanceOf(
Entity,
'Invalid argument "entityObject" when converting an entity object in a ' +
'MongoDB document (it has to be an Entity instances)'
);
if (onlyDirty) {
expect(onlyDirty).to.be.a(
'boolean',
'Invalid argument "onlyDirty" when converting an entity object in a ' +
'MongoDB document (it has to be a boolean)'
);
}
var document = {};
var entityAttributes = entityObject.Entity.attributes;
for (var attributeName in entityAttributes) {
if (!onlyDirty || entityObject.isDirty(attributeName)) {
var attribute = entityAttributes[attributeName];
var attributeDataName = attribute.getDataName(entityObject.adapterName);
var attributeDataValue = attribute.getDataValue(
entityObject[attributeName]
);
document[attributeDataName] = attributeDataValue;
}
}
document.Entity = entityObject.Entity.specification.name;
if (!onlyDirty) {
document._id = entityObject.id;
}
delete document.id;
return document;
} | javascript | function objectToDocument(entityObject, onlyDirty) {
expect(arguments).to.have.length.below(
3,
'Invalid arguments length when converting an entity object in a ' +
'MongoDB document (it has to be passed less than 3 arguments)'
);
expect(entityObject).to.be.an.instanceOf(
Entity,
'Invalid argument "entityObject" when converting an entity object in a ' +
'MongoDB document (it has to be an Entity instances)'
);
if (onlyDirty) {
expect(onlyDirty).to.be.a(
'boolean',
'Invalid argument "onlyDirty" when converting an entity object in a ' +
'MongoDB document (it has to be a boolean)'
);
}
var document = {};
var entityAttributes = entityObject.Entity.attributes;
for (var attributeName in entityAttributes) {
if (!onlyDirty || entityObject.isDirty(attributeName)) {
var attribute = entityAttributes[attributeName];
var attributeDataName = attribute.getDataName(entityObject.adapterName);
var attributeDataValue = attribute.getDataValue(
entityObject[attributeName]
);
document[attributeDataName] = attributeDataValue;
}
}
document.Entity = entityObject.Entity.specification.name;
if (!onlyDirty) {
document._id = entityObject.id;
}
delete document.id;
return document;
} | [
"function",
"objectToDocument",
"(",
"entityObject",
",",
"onlyDirty",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
".",
"below",
"(",
"3",
",",
"'Invalid arguments length when converting an entity object in a '",
"+",
"'MongoDB document (it has to be passed less than 3 arguments)'",
")",
";",
"expect",
"(",
"entityObject",
")",
".",
"to",
".",
"be",
".",
"an",
".",
"instanceOf",
"(",
"Entity",
",",
"'Invalid argument \"entityObject\" when converting an entity object in a '",
"+",
"'MongoDB document (it has to be an Entity instances)'",
")",
";",
"if",
"(",
"onlyDirty",
")",
"{",
"expect",
"(",
"onlyDirty",
")",
".",
"to",
".",
"be",
".",
"a",
"(",
"'boolean'",
",",
"'Invalid argument \"onlyDirty\" when converting an entity object in a '",
"+",
"'MongoDB document (it has to be a boolean)'",
")",
";",
"}",
"var",
"document",
"=",
"{",
"}",
";",
"var",
"entityAttributes",
"=",
"entityObject",
".",
"Entity",
".",
"attributes",
";",
"for",
"(",
"var",
"attributeName",
"in",
"entityAttributes",
")",
"{",
"if",
"(",
"!",
"onlyDirty",
"||",
"entityObject",
".",
"isDirty",
"(",
"attributeName",
")",
")",
"{",
"var",
"attribute",
"=",
"entityAttributes",
"[",
"attributeName",
"]",
";",
"var",
"attributeDataName",
"=",
"attribute",
".",
"getDataName",
"(",
"entityObject",
".",
"adapterName",
")",
";",
"var",
"attributeDataValue",
"=",
"attribute",
".",
"getDataValue",
"(",
"entityObject",
"[",
"attributeName",
"]",
")",
";",
"document",
"[",
"attributeDataName",
"]",
"=",
"attributeDataValue",
";",
"}",
"}",
"document",
".",
"Entity",
"=",
"entityObject",
".",
"Entity",
".",
"specification",
".",
"name",
";",
"if",
"(",
"!",
"onlyDirty",
")",
"{",
"document",
".",
"_id",
"=",
"entityObject",
".",
"id",
";",
"}",
"delete",
"document",
".",
"id",
";",
"return",
"document",
";",
"}"
] | Converts an Entity object in a MongoDB document.
@name module:back4app-entity-mongodb.MongoAdapter#objectToDocument
@function
@param {!module:back4app-entity/models.Entity} entityObject The Entity object
to be converted to a MongoDB document.
@param {?boolean} [onlyDirty=false] Sets if only dirty attributes will be
added to the document.
@returns {Object.<string, *>} The MongoDB document that is a dictionary.
@example
var myDocument = mongoAdapter.objectToDocument(myObject); | [
"Converts",
"an",
"Entity",
"object",
"in",
"a",
"MongoDB",
"document",
"."
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L501-L546 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | getObject | function getObject(EntityClass, query) {
expect(arguments).to.have.length(
2,
'Invalid arguments length when inserting an object in a MongoAdapter ' +
'(it has to be passed 2 arguments)'
);
var cursor;
var document;
function findDocument(db) {
cursor = _buildCursor(db, EntityClass, query);
return cursor.next();
}
function checkNotEmpty(doc) {
// save document
document = doc;
// check for no result
if (doc === null) {
throw new QueryError('Object does not exist');
}
}
function checkNotMultiple() {
// check for multiple results
return cursor.hasNext()
.then(function (hasNext) {
if (hasNext) {
throw new QueryError('Query matches multiple objects');
}
});
}
function populateEntity() {
// return populated entity
return documentToObject(document, EntityClass.adapterName);
}
return this.getDatabase()
.then(findDocument)
.then(checkNotEmpty)
.then(checkNotMultiple)
.then(populateEntity);
} | javascript | function getObject(EntityClass, query) {
expect(arguments).to.have.length(
2,
'Invalid arguments length when inserting an object in a MongoAdapter ' +
'(it has to be passed 2 arguments)'
);
var cursor;
var document;
function findDocument(db) {
cursor = _buildCursor(db, EntityClass, query);
return cursor.next();
}
function checkNotEmpty(doc) {
// save document
document = doc;
// check for no result
if (doc === null) {
throw new QueryError('Object does not exist');
}
}
function checkNotMultiple() {
// check for multiple results
return cursor.hasNext()
.then(function (hasNext) {
if (hasNext) {
throw new QueryError('Query matches multiple objects');
}
});
}
function populateEntity() {
// return populated entity
return documentToObject(document, EntityClass.adapterName);
}
return this.getDatabase()
.then(findDocument)
.then(checkNotEmpty)
.then(checkNotMultiple)
.then(populateEntity);
} | [
"function",
"getObject",
"(",
"EntityClass",
",",
"query",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"2",
",",
"'Invalid arguments length when inserting an object in a MongoAdapter '",
"+",
"'(it has to be passed 2 arguments)'",
")",
";",
"var",
"cursor",
";",
"var",
"document",
";",
"function",
"findDocument",
"(",
"db",
")",
"{",
"cursor",
"=",
"_buildCursor",
"(",
"db",
",",
"EntityClass",
",",
"query",
")",
";",
"return",
"cursor",
".",
"next",
"(",
")",
";",
"}",
"function",
"checkNotEmpty",
"(",
"doc",
")",
"{",
"document",
"=",
"doc",
";",
"if",
"(",
"doc",
"===",
"null",
")",
"{",
"throw",
"new",
"QueryError",
"(",
"'Object does not exist'",
")",
";",
"}",
"}",
"function",
"checkNotMultiple",
"(",
")",
"{",
"return",
"cursor",
".",
"hasNext",
"(",
")",
".",
"then",
"(",
"function",
"(",
"hasNext",
")",
"{",
"if",
"(",
"hasNext",
")",
"{",
"throw",
"new",
"QueryError",
"(",
"'Query matches multiple objects'",
")",
";",
"}",
"}",
")",
";",
"}",
"function",
"populateEntity",
"(",
")",
"{",
"return",
"documentToObject",
"(",
"document",
",",
"EntityClass",
".",
"adapterName",
")",
";",
"}",
"return",
"this",
".",
"getDatabase",
"(",
")",
".",
"then",
"(",
"findDocument",
")",
".",
"then",
"(",
"checkNotEmpty",
")",
".",
"then",
"(",
"checkNotMultiple",
")",
".",
"then",
"(",
"populateEntity",
")",
";",
"}"
] | Get object from the database matching given query.
@name module:back4app-entity-mongodb.MongoAdapter#getObject
@function
@param {!module:back4app-entity/models.Entity} entityObject The Entity Class
which instance will be searched within the collections.
@param {?Object} query Object for query search.
@returns {Promise.<object|Error>} Promise that returns found object if
succeed or Error if failed.
@example
mongoAdapter.getObject(Car, {color: 'red'})
.then(function(car) {
console.log(car);
}); | [
"Get",
"object",
"from",
"the",
"database",
"matching",
"given",
"query",
"."
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L563-L608 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | findObjects | function findObjects(EntityClass, query, params) {
expect(arguments).to.have.length.within(
2,
3,
'Invalid arguments length when inserting an object in a MongoAdapter ' +
'(it has to be passed 2 or 3 arguments)'
);
function findDocuments(db) {
// cleaning params
params = params || {};
params.sort = params.sort || {id: 1};
params.skip = params.skip || 0;
params.limit = params.limit || 0;
if (params.sort.hasOwnProperty('id')) {
params.sort._id = params.sort.id;
delete params.sort.id;
}
return _buildCursor(db, EntityClass, query, params)
.skip(params.skip)
.limit(params.limit)
.sort(params.sort)
.toArray();
}
function populateEntities(docs) {
var entities = [];
for (var i = 0; i < docs.length; i++) {
entities.push(documentToObject(docs[i], EntityClass.adapterName));
}
return entities;
}
return this.getDatabase()
.then(findDocuments)
.then(populateEntities);
} | javascript | function findObjects(EntityClass, query, params) {
expect(arguments).to.have.length.within(
2,
3,
'Invalid arguments length when inserting an object in a MongoAdapter ' +
'(it has to be passed 2 or 3 arguments)'
);
function findDocuments(db) {
// cleaning params
params = params || {};
params.sort = params.sort || {id: 1};
params.skip = params.skip || 0;
params.limit = params.limit || 0;
if (params.sort.hasOwnProperty('id')) {
params.sort._id = params.sort.id;
delete params.sort.id;
}
return _buildCursor(db, EntityClass, query, params)
.skip(params.skip)
.limit(params.limit)
.sort(params.sort)
.toArray();
}
function populateEntities(docs) {
var entities = [];
for (var i = 0; i < docs.length; i++) {
entities.push(documentToObject(docs[i], EntityClass.adapterName));
}
return entities;
}
return this.getDatabase()
.then(findDocuments)
.then(populateEntities);
} | [
"function",
"findObjects",
"(",
"EntityClass",
",",
"query",
",",
"params",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
".",
"within",
"(",
"2",
",",
"3",
",",
"'Invalid arguments length when inserting an object in a MongoAdapter '",
"+",
"'(it has to be passed 2 or 3 arguments)'",
")",
";",
"function",
"findDocuments",
"(",
"db",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"params",
".",
"sort",
"=",
"params",
".",
"sort",
"||",
"{",
"id",
":",
"1",
"}",
";",
"params",
".",
"skip",
"=",
"params",
".",
"skip",
"||",
"0",
";",
"params",
".",
"limit",
"=",
"params",
".",
"limit",
"||",
"0",
";",
"if",
"(",
"params",
".",
"sort",
".",
"hasOwnProperty",
"(",
"'id'",
")",
")",
"{",
"params",
".",
"sort",
".",
"_id",
"=",
"params",
".",
"sort",
".",
"id",
";",
"delete",
"params",
".",
"sort",
".",
"id",
";",
"}",
"return",
"_buildCursor",
"(",
"db",
",",
"EntityClass",
",",
"query",
",",
"params",
")",
".",
"skip",
"(",
"params",
".",
"skip",
")",
".",
"limit",
"(",
"params",
".",
"limit",
")",
".",
"sort",
"(",
"params",
".",
"sort",
")",
".",
"toArray",
"(",
")",
";",
"}",
"function",
"populateEntities",
"(",
"docs",
")",
"{",
"var",
"entities",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"docs",
".",
"length",
";",
"i",
"++",
")",
"{",
"entities",
".",
"push",
"(",
"documentToObject",
"(",
"docs",
"[",
"i",
"]",
",",
"EntityClass",
".",
"adapterName",
")",
")",
";",
"}",
"return",
"entities",
";",
"}",
"return",
"this",
".",
"getDatabase",
"(",
")",
".",
"then",
"(",
"findDocuments",
")",
".",
"then",
"(",
"populateEntities",
")",
";",
"}"
] | Find objects in the database matching given query.
@name module:back4app-entity-mongodb.MongoAdapter#findObjects
@function
@param {!module:back4app-entity/models.Entity} entityObject The Entity Class
which instance will be searched within the collections.
@param {?Object} query Object for query search.
@param {?Object} param Object for pagination parameters.
@returns {Promise.<object|Error>} Promise that returns found objects if
succeed or Error if failed.
@example
mongoAdapter.findObjects(Car, {year: 1990})
.then(function(cars) {
for (var i = 0; i < cars.length; i++) {
var car = cars[i];
console.log(car);
}
}); | [
"Find",
"objects",
"in",
"the",
"database",
"matching",
"given",
"query",
"."
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L629-L667 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | _buildCursor | function _buildCursor(db, EntityClass, query) {
// copy query to not mess with user's object
query = objects.copy(query);
// rename id field
if (query.hasOwnProperty('id')) {
query._id = query.id;
delete query.id;
}
// find collection name
var name = getEntityCollectionName(EntityClass);
// build cursor
return db.collection(name).find(query);
} | javascript | function _buildCursor(db, EntityClass, query) {
// copy query to not mess with user's object
query = objects.copy(query);
// rename id field
if (query.hasOwnProperty('id')) {
query._id = query.id;
delete query.id;
}
// find collection name
var name = getEntityCollectionName(EntityClass);
// build cursor
return db.collection(name).find(query);
} | [
"function",
"_buildCursor",
"(",
"db",
",",
"EntityClass",
",",
"query",
")",
"{",
"query",
"=",
"objects",
".",
"copy",
"(",
"query",
")",
";",
"if",
"(",
"query",
".",
"hasOwnProperty",
"(",
"'id'",
")",
")",
"{",
"query",
".",
"_id",
"=",
"query",
".",
"id",
";",
"delete",
"query",
".",
"id",
";",
"}",
"var",
"name",
"=",
"getEntityCollectionName",
"(",
"EntityClass",
")",
";",
"return",
"db",
".",
"collection",
"(",
"name",
")",
".",
"find",
"(",
"query",
")",
";",
"}"
] | Creates the DB Cursor, which iterates within the results from a query
@name module:back4app-entity-mongodb.MongoAdapter~_buildCursor
@function
@param {!module:mongodb/Db} db Db instance from MongoDB Driver.
@param {!module:back4app-entity/models.Entity} entityObject The Entity Class
which instance will be searched within the collections.
@param {?Object} query Object for query search.
@returns {module:mongodb/Cursor} MongoDB Cursor instance pointing to results
based on a query.
@private
@example
var cursor = _buildCursor(db, EntityClass, query); | [
"Creates",
"the",
"DB",
"Cursor",
"which",
"iterates",
"within",
"the",
"results",
"from",
"a",
"query"
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L683-L698 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | documentToObject | function documentToObject(document, adapterName) {
expect(arguments).to.have.length(
2,
'Invalid arguments length when converting a MongoDB document into ' +
'an entity object (it has to be passed 2 arguments)'
);
var obj = {};
// replace `_id` with `id`
if (document.hasOwnProperty('_id')) {
obj.id = document._id;
}
// get document class
var EntityClass = Entity.getSpecialization(document.Entity);
// loop through entity's attributes and replace with parsed values
var attributes = EntityClass.attributes;
for (var attrName in attributes) {
if (attributes.hasOwnProperty(attrName)) {
// get attribute name in database
var attr = attributes[attrName];
var dataName = attr.getDataName(adapterName);
// check if name is present on document and replace with parsed value
if (document.hasOwnProperty(dataName)) {
obj[attrName] = attr.parseDataValue(document[dataName]);
}
}
}
return new EntityClass(obj);
} | javascript | function documentToObject(document, adapterName) {
expect(arguments).to.have.length(
2,
'Invalid arguments length when converting a MongoDB document into ' +
'an entity object (it has to be passed 2 arguments)'
);
var obj = {};
// replace `_id` with `id`
if (document.hasOwnProperty('_id')) {
obj.id = document._id;
}
// get document class
var EntityClass = Entity.getSpecialization(document.Entity);
// loop through entity's attributes and replace with parsed values
var attributes = EntityClass.attributes;
for (var attrName in attributes) {
if (attributes.hasOwnProperty(attrName)) {
// get attribute name in database
var attr = attributes[attrName];
var dataName = attr.getDataName(adapterName);
// check if name is present on document and replace with parsed value
if (document.hasOwnProperty(dataName)) {
obj[attrName] = attr.parseDataValue(document[dataName]);
}
}
}
return new EntityClass(obj);
} | [
"function",
"documentToObject",
"(",
"document",
",",
"adapterName",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"2",
",",
"'Invalid arguments length when converting a MongoDB document into '",
"+",
"'an entity object (it has to be passed 2 arguments)'",
")",
";",
"var",
"obj",
"=",
"{",
"}",
";",
"if",
"(",
"document",
".",
"hasOwnProperty",
"(",
"'_id'",
")",
")",
"{",
"obj",
".",
"id",
"=",
"document",
".",
"_id",
";",
"}",
"var",
"EntityClass",
"=",
"Entity",
".",
"getSpecialization",
"(",
"document",
".",
"Entity",
")",
";",
"var",
"attributes",
"=",
"EntityClass",
".",
"attributes",
";",
"for",
"(",
"var",
"attrName",
"in",
"attributes",
")",
"{",
"if",
"(",
"attributes",
".",
"hasOwnProperty",
"(",
"attrName",
")",
")",
"{",
"var",
"attr",
"=",
"attributes",
"[",
"attrName",
"]",
";",
"var",
"dataName",
"=",
"attr",
".",
"getDataName",
"(",
"adapterName",
")",
";",
"if",
"(",
"document",
".",
"hasOwnProperty",
"(",
"dataName",
")",
")",
"{",
"obj",
"[",
"attrName",
"]",
"=",
"attr",
".",
"parseDataValue",
"(",
"document",
"[",
"dataName",
"]",
")",
";",
"}",
"}",
"}",
"return",
"new",
"EntityClass",
"(",
"obj",
")",
";",
"}"
] | Converts a MongoDB document to an Entity object.
@name module:back4app-entity-mongodb.MongoAdapter#documentToObject
@function
@param {Object.<string, *>} document The MongoDB document.
@param {String} adapterName The name of the entity adapter.
@returns {!module:back4app-entity/models.Entity} The converted Entity object.
@example
<pre>
var myEntity = mongoAdapter.documentToObject(myDocument, 'mongo');
</pre> | [
"Converts",
"a",
"MongoDB",
"document",
"to",
"an",
"Entity",
"object",
"."
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L712-L744 | train |
back4app/back4app-entity-mongodb | src/back/MongoAdapter.js | getEntityCollectionName | function getEntityCollectionName(Entity) {
expect(arguments).to.have.length(
1,
'Invalid arguments length when getting the collection name of an Entity ' +
'class (it has to be passed 1 argument)'
);
expect(Entity).to.be.a(
'function',
'Invalid argument "Entity" when getting the collection name of an ' +
'Entity (it has to be an Entity class)'
);
expect(classes.isGeneral(entity.models.Entity, Entity)).to.equal(
true,
'Invalid argument "Entity" when getting the collection name of an ' +
'Entity (it has to be an Entity class)'
);
while (
Entity.General !== null &&
!Entity.General.specification.isAbstract
) {
Entity = Entity.General;
}
return Entity.dataName;
} | javascript | function getEntityCollectionName(Entity) {
expect(arguments).to.have.length(
1,
'Invalid arguments length when getting the collection name of an Entity ' +
'class (it has to be passed 1 argument)'
);
expect(Entity).to.be.a(
'function',
'Invalid argument "Entity" when getting the collection name of an ' +
'Entity (it has to be an Entity class)'
);
expect(classes.isGeneral(entity.models.Entity, Entity)).to.equal(
true,
'Invalid argument "Entity" when getting the collection name of an ' +
'Entity (it has to be an Entity class)'
);
while (
Entity.General !== null &&
!Entity.General.specification.isAbstract
) {
Entity = Entity.General;
}
return Entity.dataName;
} | [
"function",
"getEntityCollectionName",
"(",
"Entity",
")",
"{",
"expect",
"(",
"arguments",
")",
".",
"to",
".",
"have",
".",
"length",
"(",
"1",
",",
"'Invalid arguments length when getting the collection name of an Entity '",
"+",
"'class (it has to be passed 1 argument)'",
")",
";",
"expect",
"(",
"Entity",
")",
".",
"to",
".",
"be",
".",
"a",
"(",
"'function'",
",",
"'Invalid argument \"Entity\" when getting the collection name of an '",
"+",
"'Entity (it has to be an Entity class)'",
")",
";",
"expect",
"(",
"classes",
".",
"isGeneral",
"(",
"entity",
".",
"models",
".",
"Entity",
",",
"Entity",
")",
")",
".",
"to",
".",
"equal",
"(",
"true",
",",
"'Invalid argument \"Entity\" when getting the collection name of an '",
"+",
"'Entity (it has to be an Entity class)'",
")",
";",
"while",
"(",
"Entity",
".",
"General",
"!==",
"null",
"&&",
"!",
"Entity",
".",
"General",
".",
"specification",
".",
"isAbstract",
")",
"{",
"Entity",
"=",
"Entity",
".",
"General",
";",
"}",
"return",
"Entity",
".",
"dataName",
";",
"}"
] | Gets the collection name in which the objects of a given Entity shall be
saved.
@name module:back4app-entity-mongodb.MongoAdapter#getEntityCollectionName
@function
@param {!Class} Entity The Entity class whose collection name will be get.
@returns {string} The collection name.
@example
var entityCollectionName = mongoAdapter.getEntityCollectionName(MyEntity); | [
"Gets",
"the",
"collection",
"name",
"in",
"which",
"the",
"objects",
"of",
"a",
"given",
"Entity",
"shall",
"be",
"saved",
"."
] | 5a43ab50aabdd259b0324aa7c7eed03e8de40a30 | https://github.com/back4app/back4app-entity-mongodb/blob/5a43ab50aabdd259b0324aa7c7eed03e8de40a30/src/back/MongoAdapter.js#L807-L834 | train |
graphology/graphology-metrics | weighted-degree.js | abstractWeightedDegree | function abstractWeightedDegree(name, assign, edgeGetter, graph, options) {
if (!isGraph(graph))
throw new Error('graphology-metrics/' + name + ': the given graph is not a valid graphology instance.');
if (edgeGetter !== 'edges' && graph.type === 'undirected')
throw new Error('graphology-metrics/' + name + ': cannot compute ' + name + ' on an undirected graph.');
var singleNode = null;
// Solving arguments
if (arguments.length === 5 && typeof arguments[4] !== 'object') {
singleNode = arguments[4];
}
else if (arguments.length === 6) {
singleNode = arguments[4];
options = arguments[5];
}
// Solving options
options = options || {};
var attributes = options.attributes || {};
var weightAttribute = attributes.weight || DEFAULT_WEIGHT_ATTRIBUTE,
weightedDegreeAttribute = attributes.weightedDegree || name;
var edges,
d,
w,
i,
l;
// Computing weighted degree for a single node
if (singleNode) {
edges = graph[edgeGetter](singleNode);
d = 0;
for (i = 0, l = edges.length; i < l; i++) {
w = graph.getEdgeAttribute(edges[i], weightAttribute);
if (typeof w === 'number')
d += w;
}
if (assign) {
graph.setNodeAttribute(singleNode, weightedDegreeAttribute, d);
return;
}
else {
return d;
}
}
// Computing weighted degree for every node
// TODO: it might be more performant to iterate on the edges here.
var nodes = graph.nodes(),
node,
weightedDegrees = {},
j,
m;
for (i = 0, l = nodes.length; i < l; i++) {
node = nodes[i];
edges = graph[edgeGetter](node);
d = 0;
for (j = 0, m = edges.length; j < m; j++) {
w = graph.getEdgeAttribute(edges[j], weightAttribute);
if (typeof w === 'number')
d += w;
}
if (assign)
graph.setNodeAttribute(node, weightedDegreeAttribute, d);
else
weightedDegrees[node] = d;
}
if (!assign)
return weightedDegrees;
} | javascript | function abstractWeightedDegree(name, assign, edgeGetter, graph, options) {
if (!isGraph(graph))
throw new Error('graphology-metrics/' + name + ': the given graph is not a valid graphology instance.');
if (edgeGetter !== 'edges' && graph.type === 'undirected')
throw new Error('graphology-metrics/' + name + ': cannot compute ' + name + ' on an undirected graph.');
var singleNode = null;
// Solving arguments
if (arguments.length === 5 && typeof arguments[4] !== 'object') {
singleNode = arguments[4];
}
else if (arguments.length === 6) {
singleNode = arguments[4];
options = arguments[5];
}
// Solving options
options = options || {};
var attributes = options.attributes || {};
var weightAttribute = attributes.weight || DEFAULT_WEIGHT_ATTRIBUTE,
weightedDegreeAttribute = attributes.weightedDegree || name;
var edges,
d,
w,
i,
l;
// Computing weighted degree for a single node
if (singleNode) {
edges = graph[edgeGetter](singleNode);
d = 0;
for (i = 0, l = edges.length; i < l; i++) {
w = graph.getEdgeAttribute(edges[i], weightAttribute);
if (typeof w === 'number')
d += w;
}
if (assign) {
graph.setNodeAttribute(singleNode, weightedDegreeAttribute, d);
return;
}
else {
return d;
}
}
// Computing weighted degree for every node
// TODO: it might be more performant to iterate on the edges here.
var nodes = graph.nodes(),
node,
weightedDegrees = {},
j,
m;
for (i = 0, l = nodes.length; i < l; i++) {
node = nodes[i];
edges = graph[edgeGetter](node);
d = 0;
for (j = 0, m = edges.length; j < m; j++) {
w = graph.getEdgeAttribute(edges[j], weightAttribute);
if (typeof w === 'number')
d += w;
}
if (assign)
graph.setNodeAttribute(node, weightedDegreeAttribute, d);
else
weightedDegrees[node] = d;
}
if (!assign)
return weightedDegrees;
} | [
"function",
"abstractWeightedDegree",
"(",
"name",
",",
"assign",
",",
"edgeGetter",
",",
"graph",
",",
"options",
")",
"{",
"if",
"(",
"!",
"isGraph",
"(",
"graph",
")",
")",
"throw",
"new",
"Error",
"(",
"'graphology-metrics/'",
"+",
"name",
"+",
"': the given graph is not a valid graphology instance.'",
")",
";",
"if",
"(",
"edgeGetter",
"!==",
"'edges'",
"&&",
"graph",
".",
"type",
"===",
"'undirected'",
")",
"throw",
"new",
"Error",
"(",
"'graphology-metrics/'",
"+",
"name",
"+",
"': cannot compute '",
"+",
"name",
"+",
"' on an undirected graph.'",
")",
";",
"var",
"singleNode",
"=",
"null",
";",
"if",
"(",
"arguments",
".",
"length",
"===",
"5",
"&&",
"typeof",
"arguments",
"[",
"4",
"]",
"!==",
"'object'",
")",
"{",
"singleNode",
"=",
"arguments",
"[",
"4",
"]",
";",
"}",
"else",
"if",
"(",
"arguments",
".",
"length",
"===",
"6",
")",
"{",
"singleNode",
"=",
"arguments",
"[",
"4",
"]",
";",
"options",
"=",
"arguments",
"[",
"5",
"]",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"attributes",
"=",
"options",
".",
"attributes",
"||",
"{",
"}",
";",
"var",
"weightAttribute",
"=",
"attributes",
".",
"weight",
"||",
"DEFAULT_WEIGHT_ATTRIBUTE",
",",
"weightedDegreeAttribute",
"=",
"attributes",
".",
"weightedDegree",
"||",
"name",
";",
"var",
"edges",
",",
"d",
",",
"w",
",",
"i",
",",
"l",
";",
"if",
"(",
"singleNode",
")",
"{",
"edges",
"=",
"graph",
"[",
"edgeGetter",
"]",
"(",
"singleNode",
")",
";",
"d",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"edges",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"w",
"=",
"graph",
".",
"getEdgeAttribute",
"(",
"edges",
"[",
"i",
"]",
",",
"weightAttribute",
")",
";",
"if",
"(",
"typeof",
"w",
"===",
"'number'",
")",
"d",
"+=",
"w",
";",
"}",
"if",
"(",
"assign",
")",
"{",
"graph",
".",
"setNodeAttribute",
"(",
"singleNode",
",",
"weightedDegreeAttribute",
",",
"d",
")",
";",
"return",
";",
"}",
"else",
"{",
"return",
"d",
";",
"}",
"}",
"var",
"nodes",
"=",
"graph",
".",
"nodes",
"(",
")",
",",
"node",
",",
"weightedDegrees",
"=",
"{",
"}",
",",
"j",
",",
"m",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"nodes",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"node",
"=",
"nodes",
"[",
"i",
"]",
";",
"edges",
"=",
"graph",
"[",
"edgeGetter",
"]",
"(",
"node",
")",
";",
"d",
"=",
"0",
";",
"for",
"(",
"j",
"=",
"0",
",",
"m",
"=",
"edges",
".",
"length",
";",
"j",
"<",
"m",
";",
"j",
"++",
")",
"{",
"w",
"=",
"graph",
".",
"getEdgeAttribute",
"(",
"edges",
"[",
"j",
"]",
",",
"weightAttribute",
")",
";",
"if",
"(",
"typeof",
"w",
"===",
"'number'",
")",
"d",
"+=",
"w",
";",
"}",
"if",
"(",
"assign",
")",
"graph",
".",
"setNodeAttribute",
"(",
"node",
",",
"weightedDegreeAttribute",
",",
"d",
")",
";",
"else",
"weightedDegrees",
"[",
"node",
"]",
"=",
"d",
";",
"}",
"if",
"(",
"!",
"assign",
")",
"return",
"weightedDegrees",
";",
"}"
] | Asbtract function to perform any kind of weighted degree.
Signature n°1 - computing weighted degree for every node:
@param {string} name - Name of the implemented function.
@param {boolean} assign - Whether to assign the result to the nodes.
@param {string} method - Method of the graph to get the edges.
@param {Graph} graph - A graphology instance.
@param {object} [options] - Options:
@param {object} [attributes] - Custom attribute names:
@param {string} [weight] - Name of the weight attribute.
@param {string} [weightedDegree] - Name of the attribute to set.
Signature n°2 - computing weighted degree for a single node:
@param {string} name - Name of the implemented function.
@param {boolean} assign - Whether to assign the result to the nodes.
@param {string} edgeGetter - Graph's method used to get edges.
@param {Graph} graph - A graphology instance.
@param {any} node - Key of node.
@param {object} [options] - Options:
@param {object} [attributes] - Custom attribute names:
@param {string} [weight] - Name of the weight attribute.
@param {string} [weightedDegree] - Name of the attribute to set.
@return {object|void} | [
"Asbtract",
"function",
"to",
"perform",
"any",
"kind",
"of",
"weighted",
"degree",
"."
] | bf920856140994251fa799f87f58f42bc06f53e6 | https://github.com/graphology/graphology-metrics/blob/bf920856140994251fa799f87f58f42bc06f53e6/weighted-degree.js#L43-L124 | train |
graphology/graphology-metrics | centrality/betweenness.js | abstractBetweennessCentrality | function abstractBetweennessCentrality(assign, graph, options) {
if (!isGraph(graph))
throw new Error('graphology-centrality/beetweenness-centrality: the given graph is not a valid graphology instance.');
var centralities = {};
// Solving options
options = defaults({}, options, DEFAULTS);
var weightAttribute = options.attributes.weight,
centralityAttribute = options.attributes.centrality,
normalized = options.normalized,
weighted = options.weighted;
var shortestPath = weighted ?
dijkstraShotestPath.brandes :
unweightedShortestPath.brandes;
var nodes = graph.nodes(),
node,
result,
S,
P,
sigma,
delta,
coefficient,
i,
j,
l,
m,
v,
w;
// Initializing centralities
for (i = 0, l = nodes.length; i < l; i++)
centralities[nodes[i]] = 0;
// Iterating over each node
for (i = 0, l = nodes.length; i < l; i++) {
node = nodes[i];
result = shortestPath(graph, node, weightAttribute);
S = result[0];
P = result[1];
sigma = result[2];
delta = {};
// Accumulating
for (j = 0, m = S.length; j < m; j++)
delta[S[j]] = 0;
while (S.length) {
w = S.pop();
coefficient = (1 + delta[w]) / sigma[w];
for (j = 0, m = P[w].length; j < m; j++) {
v = P[w][j];
delta[v] += sigma[v] * coefficient;
}
if (w !== node)
centralities[w] += delta[w];
}
}
// Rescaling
var n = graph.order,
scale = null;
if (normalized)
scale = n <= 2 ? null : (1 / ((n - 1) * (n - 2)));
else
scale = graph.type === 'undirected' ? 0.5 : null;
if (scale !== null) {
for (node in centralities)
centralities[node] *= scale;
}
if (assign) {
for (node in centralities)
graph.setNodeAttribute(node, centralityAttribute, centralities[node]);
}
return centralities;
} | javascript | function abstractBetweennessCentrality(assign, graph, options) {
if (!isGraph(graph))
throw new Error('graphology-centrality/beetweenness-centrality: the given graph is not a valid graphology instance.');
var centralities = {};
// Solving options
options = defaults({}, options, DEFAULTS);
var weightAttribute = options.attributes.weight,
centralityAttribute = options.attributes.centrality,
normalized = options.normalized,
weighted = options.weighted;
var shortestPath = weighted ?
dijkstraShotestPath.brandes :
unweightedShortestPath.brandes;
var nodes = graph.nodes(),
node,
result,
S,
P,
sigma,
delta,
coefficient,
i,
j,
l,
m,
v,
w;
// Initializing centralities
for (i = 0, l = nodes.length; i < l; i++)
centralities[nodes[i]] = 0;
// Iterating over each node
for (i = 0, l = nodes.length; i < l; i++) {
node = nodes[i];
result = shortestPath(graph, node, weightAttribute);
S = result[0];
P = result[1];
sigma = result[2];
delta = {};
// Accumulating
for (j = 0, m = S.length; j < m; j++)
delta[S[j]] = 0;
while (S.length) {
w = S.pop();
coefficient = (1 + delta[w]) / sigma[w];
for (j = 0, m = P[w].length; j < m; j++) {
v = P[w][j];
delta[v] += sigma[v] * coefficient;
}
if (w !== node)
centralities[w] += delta[w];
}
}
// Rescaling
var n = graph.order,
scale = null;
if (normalized)
scale = n <= 2 ? null : (1 / ((n - 1) * (n - 2)));
else
scale = graph.type === 'undirected' ? 0.5 : null;
if (scale !== null) {
for (node in centralities)
centralities[node] *= scale;
}
if (assign) {
for (node in centralities)
graph.setNodeAttribute(node, centralityAttribute, centralities[node]);
}
return centralities;
} | [
"function",
"abstractBetweennessCentrality",
"(",
"assign",
",",
"graph",
",",
"options",
")",
"{",
"if",
"(",
"!",
"isGraph",
"(",
"graph",
")",
")",
"throw",
"new",
"Error",
"(",
"'graphology-centrality/beetweenness-centrality: the given graph is not a valid graphology instance.'",
")",
";",
"var",
"centralities",
"=",
"{",
"}",
";",
"options",
"=",
"defaults",
"(",
"{",
"}",
",",
"options",
",",
"DEFAULTS",
")",
";",
"var",
"weightAttribute",
"=",
"options",
".",
"attributes",
".",
"weight",
",",
"centralityAttribute",
"=",
"options",
".",
"attributes",
".",
"centrality",
",",
"normalized",
"=",
"options",
".",
"normalized",
",",
"weighted",
"=",
"options",
".",
"weighted",
";",
"var",
"shortestPath",
"=",
"weighted",
"?",
"dijkstraShotestPath",
".",
"brandes",
":",
"unweightedShortestPath",
".",
"brandes",
";",
"var",
"nodes",
"=",
"graph",
".",
"nodes",
"(",
")",
",",
"node",
",",
"result",
",",
"S",
",",
"P",
",",
"sigma",
",",
"delta",
",",
"coefficient",
",",
"i",
",",
"j",
",",
"l",
",",
"m",
",",
"v",
",",
"w",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"nodes",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"centralities",
"[",
"nodes",
"[",
"i",
"]",
"]",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"nodes",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"node",
"=",
"nodes",
"[",
"i",
"]",
";",
"result",
"=",
"shortestPath",
"(",
"graph",
",",
"node",
",",
"weightAttribute",
")",
";",
"S",
"=",
"result",
"[",
"0",
"]",
";",
"P",
"=",
"result",
"[",
"1",
"]",
";",
"sigma",
"=",
"result",
"[",
"2",
"]",
";",
"delta",
"=",
"{",
"}",
";",
"for",
"(",
"j",
"=",
"0",
",",
"m",
"=",
"S",
".",
"length",
";",
"j",
"<",
"m",
";",
"j",
"++",
")",
"delta",
"[",
"S",
"[",
"j",
"]",
"]",
"=",
"0",
";",
"while",
"(",
"S",
".",
"length",
")",
"{",
"w",
"=",
"S",
".",
"pop",
"(",
")",
";",
"coefficient",
"=",
"(",
"1",
"+",
"delta",
"[",
"w",
"]",
")",
"/",
"sigma",
"[",
"w",
"]",
";",
"for",
"(",
"j",
"=",
"0",
",",
"m",
"=",
"P",
"[",
"w",
"]",
".",
"length",
";",
"j",
"<",
"m",
";",
"j",
"++",
")",
"{",
"v",
"=",
"P",
"[",
"w",
"]",
"[",
"j",
"]",
";",
"delta",
"[",
"v",
"]",
"+=",
"sigma",
"[",
"v",
"]",
"*",
"coefficient",
";",
"}",
"if",
"(",
"w",
"!==",
"node",
")",
"centralities",
"[",
"w",
"]",
"+=",
"delta",
"[",
"w",
"]",
";",
"}",
"}",
"var",
"n",
"=",
"graph",
".",
"order",
",",
"scale",
"=",
"null",
";",
"if",
"(",
"normalized",
")",
"scale",
"=",
"n",
"<=",
"2",
"?",
"null",
":",
"(",
"1",
"/",
"(",
"(",
"n",
"-",
"1",
")",
"*",
"(",
"n",
"-",
"2",
")",
")",
")",
";",
"else",
"scale",
"=",
"graph",
".",
"type",
"===",
"'undirected'",
"?",
"0.5",
":",
"null",
";",
"if",
"(",
"scale",
"!==",
"null",
")",
"{",
"for",
"(",
"node",
"in",
"centralities",
")",
"centralities",
"[",
"node",
"]",
"*=",
"scale",
";",
"}",
"if",
"(",
"assign",
")",
"{",
"for",
"(",
"node",
"in",
"centralities",
")",
"graph",
".",
"setNodeAttribute",
"(",
"node",
",",
"centralityAttribute",
",",
"centralities",
"[",
"node",
"]",
")",
";",
"}",
"return",
"centralities",
";",
"}"
] | Abstract function computing beetweenness centrality for the given graph.
@param {boolean} assign - Assign the results to node attributes?
@param {Graph} graph - Target graph.
@param {object} [options] - Options:
@param {object} [attributes] - Attribute names:
@param {string} [weight] - Name of the weight attribute.
@param {string} [centrality] - Name of the attribute to assign.
@param {boolean} [normalized] - Should the centrality be normalized?
@param {boolean} [weighted] - Weighted graph?
@param {object} | [
"Abstract",
"function",
"computing",
"beetweenness",
"centrality",
"for",
"the",
"given",
"graph",
"."
] | bf920856140994251fa799f87f58f42bc06f53e6 | https://github.com/graphology/graphology-metrics/blob/bf920856140994251fa799f87f58f42bc06f53e6/centrality/betweenness.js#L37-L124 | train |
mrvisser/node-corporal | examples/whoami/commands/iam.js | function(session, args, callback) {
// Parse the arguments using optimist
var argv = optimist.parse(args);
// Update the environment to indicate who the specified user now is
session.env('me', argv._[0] || 'unknown');
// The callback always needs to be invoked to finish the command
return callback();
} | javascript | function(session, args, callback) {
// Parse the arguments using optimist
var argv = optimist.parse(args);
// Update the environment to indicate who the specified user now is
session.env('me', argv._[0] || 'unknown');
// The callback always needs to be invoked to finish the command
return callback();
} | [
"function",
"(",
"session",
",",
"args",
",",
"callback",
")",
"{",
"var",
"argv",
"=",
"optimist",
".",
"parse",
"(",
"args",
")",
";",
"session",
".",
"env",
"(",
"'me'",
",",
"argv",
".",
"_",
"[",
"0",
"]",
"||",
"'unknown'",
")",
";",
"return",
"callback",
"(",
")",
";",
"}"
] | The function that actually invokes the command. Optimist is being used here to parse the array arguments that were provided to your command, however you can use whatever utility you want | [
"The",
"function",
"that",
"actually",
"invokes",
"the",
"command",
".",
"Optimist",
"is",
"being",
"used",
"here",
"to",
"parse",
"the",
"array",
"arguments",
"that",
"were",
"provided",
"to",
"your",
"command",
"however",
"you",
"can",
"use",
"whatever",
"utility",
"you",
"want"
] | 93ead59d870fe78d43135bb0a8b2d346422b970e | https://github.com/mrvisser/node-corporal/blob/93ead59d870fe78d43135bb0a8b2d346422b970e/examples/whoami/commands/iam.js#L15-L25 | train |
|
w3c/node-w3capi | lib/index.js | subSteps | function subSteps (obj, items) {
util.inherits(obj, Ctx);
var key = "teamcontacts versions successors predecessors".split(" ")
, propKey = "team-contacts version-history successor-version predecessor-version".split(" ");
items.forEach(function (it) {
obj.prototype[it] = function () {
this.steps.push(it);
this.type = "list";
var i = key.indexOf(it);
this.linkKey = (i >= 0) ? propKey[i] : it;
return this;
};
});
} | javascript | function subSteps (obj, items) {
util.inherits(obj, Ctx);
var key = "teamcontacts versions successors predecessors".split(" ")
, propKey = "team-contacts version-history successor-version predecessor-version".split(" ");
items.forEach(function (it) {
obj.prototype[it] = function () {
this.steps.push(it);
this.type = "list";
var i = key.indexOf(it);
this.linkKey = (i >= 0) ? propKey[i] : it;
return this;
};
});
} | [
"function",
"subSteps",
"(",
"obj",
",",
"items",
")",
"{",
"util",
".",
"inherits",
"(",
"obj",
",",
"Ctx",
")",
";",
"var",
"key",
"=",
"\"teamcontacts versions successors predecessors\"",
".",
"split",
"(",
"\" \"",
")",
",",
"propKey",
"=",
"\"team-contacts version-history successor-version predecessor-version\"",
".",
"split",
"(",
"\" \"",
")",
";",
"items",
".",
"forEach",
"(",
"function",
"(",
"it",
")",
"{",
"obj",
".",
"prototype",
"[",
"it",
"]",
"=",
"function",
"(",
")",
"{",
"this",
".",
"steps",
".",
"push",
"(",
"it",
")",
";",
"this",
".",
"type",
"=",
"\"list\"",
";",
"var",
"i",
"=",
"key",
".",
"indexOf",
"(",
"it",
")",
";",
"this",
".",
"linkKey",
"=",
"(",
"i",
">=",
"0",
")",
"?",
"propKey",
"[",
"i",
"]",
":",
"it",
";",
"return",
"this",
";",
"}",
";",
"}",
")",
";",
"}"
] | generates steps beneath an existing one that has an ID | [
"generates",
"steps",
"beneath",
"an",
"existing",
"one",
"that",
"has",
"an",
"ID"
] | 70573181c1decd057a02c13fdcabe8b120703359 | https://github.com/w3c/node-w3capi/blob/70573181c1decd057a02c13fdcabe8b120703359/lib/index.js#L103-L117 | train |
w3c/node-w3capi | lib/index.js | idStep | function idStep (obj, name, inherit) {
return function (id) {
var ctx = obj ? new obj(inherit ? this : undefined) : this;
ctx.steps.push(name);
ctx.steps.push(id);
return ctx;
};
} | javascript | function idStep (obj, name, inherit) {
return function (id) {
var ctx = obj ? new obj(inherit ? this : undefined) : this;
ctx.steps.push(name);
ctx.steps.push(id);
return ctx;
};
} | [
"function",
"idStep",
"(",
"obj",
",",
"name",
",",
"inherit",
")",
"{",
"return",
"function",
"(",
"id",
")",
"{",
"var",
"ctx",
"=",
"obj",
"?",
"new",
"obj",
"(",
"inherit",
"?",
"this",
":",
"undefined",
")",
":",
"this",
";",
"ctx",
".",
"steps",
".",
"push",
"(",
"name",
")",
";",
"ctx",
".",
"steps",
".",
"push",
"(",
"id",
")",
";",
"return",
"ctx",
";",
"}",
";",
"}"
] | generates a step that takes an ID | [
"generates",
"a",
"step",
"that",
"takes",
"an",
"ID"
] | 70573181c1decd057a02c13fdcabe8b120703359 | https://github.com/w3c/node-w3capi/blob/70573181c1decd057a02c13fdcabe8b120703359/lib/index.js#L120-L127 | train |
w3c/node-w3capi | lib/index.js | accountOrIdStep | function accountOrIdStep(obj, name) {
return function (accountOrId) {
if (typeof accountOrId === 'string') {
// W3C obfuscated id
return idStep(obj, name)(accountOrId);
} else {
// accountOrId expected to be {type: 'github', id: 123456}
var ctx = new obj();
ctx.steps.push(name);
ctx.steps.push("connected");
ctx.steps.push(accountOrId.type);
ctx.steps.push(accountOrId.id);
return ctx;
}
};
} | javascript | function accountOrIdStep(obj, name) {
return function (accountOrId) {
if (typeof accountOrId === 'string') {
// W3C obfuscated id
return idStep(obj, name)(accountOrId);
} else {
// accountOrId expected to be {type: 'github', id: 123456}
var ctx = new obj();
ctx.steps.push(name);
ctx.steps.push("connected");
ctx.steps.push(accountOrId.type);
ctx.steps.push(accountOrId.id);
return ctx;
}
};
} | [
"function",
"accountOrIdStep",
"(",
"obj",
",",
"name",
")",
"{",
"return",
"function",
"(",
"accountOrId",
")",
"{",
"if",
"(",
"typeof",
"accountOrId",
"===",
"'string'",
")",
"{",
"return",
"idStep",
"(",
"obj",
",",
"name",
")",
"(",
"accountOrId",
")",
";",
"}",
"else",
"{",
"var",
"ctx",
"=",
"new",
"obj",
"(",
")",
";",
"ctx",
".",
"steps",
".",
"push",
"(",
"name",
")",
";",
"ctx",
".",
"steps",
".",
"push",
"(",
"\"connected\"",
")",
";",
"ctx",
".",
"steps",
".",
"push",
"(",
"accountOrId",
".",
"type",
")",
";",
"ctx",
".",
"steps",
".",
"push",
"(",
"accountOrId",
".",
"id",
")",
";",
"return",
"ctx",
";",
"}",
"}",
";",
"}"
] | generates a step that takes either an account object or an ID | [
"generates",
"a",
"step",
"that",
"takes",
"either",
"an",
"account",
"object",
"or",
"an",
"ID"
] | 70573181c1decd057a02c13fdcabe8b120703359 | https://github.com/w3c/node-w3capi/blob/70573181c1decd057a02c13fdcabe8b120703359/lib/index.js#L194-L209 | train |
modulesio/window-fetch | src/body.js | consumeBody | function consumeBody(body) {
if (this[DISTURBED]) {
return Body.Promise.reject(new Error(`body used already for: ${this.url}`));
}
this[DISTURBED] = true;
// body is null
if (this.body === null) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is string
if (typeof this.body === 'string') {
return Body.Promise.resolve(Buffer.from(this.body));
}
// body is blob
if (this.body instanceof Blob) {
return Body.Promise.resolve(this.body.buffer);
}
// body is buffer
if (Buffer.isBuffer(this.body)) {
return Body.Promise.resolve(this.body);
}
// istanbul ignore if: should never happen
if (!(this.body instanceof Stream)) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is stream
// get ready to actually consume the body
let accum = [];
let accumBytes = 0;
let abort = false;
return new Body.Promise((resolve, reject) => {
let resTimeout;
// allow timeout on slow response body
if (this.timeout) {
resTimeout = setTimeout(() => {
abort = true;
reject(new FetchError(`Response timeout while trying to fetch ${this.url} (over ${this.timeout}ms)`, 'body-timeout'));
}, this.timeout);
}
// handle stream error, such as incorrect content-encoding
this.body.on('error', err => {
reject(new FetchError(`Invalid response body while trying to fetch ${this.url}: ${err.message}`, 'system', err));
});
this.body.on('data', chunk => {
if (abort || chunk === null) {
return;
}
if (this.size && accumBytes + chunk.length > this.size) {
abort = true;
reject(new FetchError(`content size at ${this.url} over limit: ${this.size}`, 'max-size'));
return;
}
accumBytes += chunk.length;
accum.push(chunk);
});
this.body.on('end', () => {
if (abort) {
return;
}
clearTimeout(resTimeout);
resolve(Buffer.concat(accum));
});
});
} | javascript | function consumeBody(body) {
if (this[DISTURBED]) {
return Body.Promise.reject(new Error(`body used already for: ${this.url}`));
}
this[DISTURBED] = true;
// body is null
if (this.body === null) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is string
if (typeof this.body === 'string') {
return Body.Promise.resolve(Buffer.from(this.body));
}
// body is blob
if (this.body instanceof Blob) {
return Body.Promise.resolve(this.body.buffer);
}
// body is buffer
if (Buffer.isBuffer(this.body)) {
return Body.Promise.resolve(this.body);
}
// istanbul ignore if: should never happen
if (!(this.body instanceof Stream)) {
return Body.Promise.resolve(Buffer.alloc(0));
}
// body is stream
// get ready to actually consume the body
let accum = [];
let accumBytes = 0;
let abort = false;
return new Body.Promise((resolve, reject) => {
let resTimeout;
// allow timeout on slow response body
if (this.timeout) {
resTimeout = setTimeout(() => {
abort = true;
reject(new FetchError(`Response timeout while trying to fetch ${this.url} (over ${this.timeout}ms)`, 'body-timeout'));
}, this.timeout);
}
// handle stream error, such as incorrect content-encoding
this.body.on('error', err => {
reject(new FetchError(`Invalid response body while trying to fetch ${this.url}: ${err.message}`, 'system', err));
});
this.body.on('data', chunk => {
if (abort || chunk === null) {
return;
}
if (this.size && accumBytes + chunk.length > this.size) {
abort = true;
reject(new FetchError(`content size at ${this.url} over limit: ${this.size}`, 'max-size'));
return;
}
accumBytes += chunk.length;
accum.push(chunk);
});
this.body.on('end', () => {
if (abort) {
return;
}
clearTimeout(resTimeout);
resolve(Buffer.concat(accum));
});
});
} | [
"function",
"consumeBody",
"(",
"body",
")",
"{",
"if",
"(",
"this",
"[",
"DISTURBED",
"]",
")",
"{",
"return",
"Body",
".",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"this",
".",
"url",
"}",
"`",
")",
")",
";",
"}",
"this",
"[",
"DISTURBED",
"]",
"=",
"true",
";",
"if",
"(",
"this",
".",
"body",
"===",
"null",
")",
"{",
"return",
"Body",
".",
"Promise",
".",
"resolve",
"(",
"Buffer",
".",
"alloc",
"(",
"0",
")",
")",
";",
"}",
"if",
"(",
"typeof",
"this",
".",
"body",
"===",
"'string'",
")",
"{",
"return",
"Body",
".",
"Promise",
".",
"resolve",
"(",
"Buffer",
".",
"from",
"(",
"this",
".",
"body",
")",
")",
";",
"}",
"if",
"(",
"this",
".",
"body",
"instanceof",
"Blob",
")",
"{",
"return",
"Body",
".",
"Promise",
".",
"resolve",
"(",
"this",
".",
"body",
".",
"buffer",
")",
";",
"}",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"this",
".",
"body",
")",
")",
"{",
"return",
"Body",
".",
"Promise",
".",
"resolve",
"(",
"this",
".",
"body",
")",
";",
"}",
"if",
"(",
"!",
"(",
"this",
".",
"body",
"instanceof",
"Stream",
")",
")",
"{",
"return",
"Body",
".",
"Promise",
".",
"resolve",
"(",
"Buffer",
".",
"alloc",
"(",
"0",
")",
")",
";",
"}",
"let",
"accum",
"=",
"[",
"]",
";",
"let",
"accumBytes",
"=",
"0",
";",
"let",
"abort",
"=",
"false",
";",
"return",
"new",
"Body",
".",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"let",
"resTimeout",
";",
"if",
"(",
"this",
".",
"timeout",
")",
"{",
"resTimeout",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"abort",
"=",
"true",
";",
"reject",
"(",
"new",
"FetchError",
"(",
"`",
"${",
"this",
".",
"url",
"}",
"${",
"this",
".",
"timeout",
"}",
"`",
",",
"'body-timeout'",
")",
")",
";",
"}",
",",
"this",
".",
"timeout",
")",
";",
"}",
"this",
".",
"body",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"{",
"reject",
"(",
"new",
"FetchError",
"(",
"`",
"${",
"this",
".",
"url",
"}",
"${",
"err",
".",
"message",
"}",
"`",
",",
"'system'",
",",
"err",
")",
")",
";",
"}",
")",
";",
"this",
".",
"body",
".",
"on",
"(",
"'data'",
",",
"chunk",
"=>",
"{",
"if",
"(",
"abort",
"||",
"chunk",
"===",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"this",
".",
"size",
"&&",
"accumBytes",
"+",
"chunk",
".",
"length",
">",
"this",
".",
"size",
")",
"{",
"abort",
"=",
"true",
";",
"reject",
"(",
"new",
"FetchError",
"(",
"`",
"${",
"this",
".",
"url",
"}",
"${",
"this",
".",
"size",
"}",
"`",
",",
"'max-size'",
")",
")",
";",
"return",
";",
"}",
"accumBytes",
"+=",
"chunk",
".",
"length",
";",
"accum",
".",
"push",
"(",
"chunk",
")",
";",
"}",
")",
";",
"this",
".",
"body",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"if",
"(",
"abort",
")",
"{",
"return",
";",
"}",
"clearTimeout",
"(",
"resTimeout",
")",
";",
"resolve",
"(",
"Buffer",
".",
"concat",
"(",
"accum",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Decode buffers into utf-8 string
@return Promise | [
"Decode",
"buffers",
"into",
"utf",
"-",
"8",
"string"
] | 0a024896a36c439335931e5d7830fca6373a4c63 | https://github.com/modulesio/window-fetch/blob/0a024896a36c439335931e5d7830fca6373a4c63/src/body.js#L149-L227 | train |
gkjohnson/ply-exporter-js | PLYExporter.js | traverseMeshes | function traverseMeshes( cb ) {
object.traverse( function ( child ) {
if ( child.isMesh === true ) {
var mesh = child;
var geometry = mesh.geometry;
if ( geometry.isGeometry === true ) {
geometry = geomToBufferGeom.get( geometry );
}
if ( geometry.isBufferGeometry === true ) {
if ( geometry.getAttribute( 'position' ) !== undefined ) {
cb( mesh, geometry );
}
}
}
} );
} | javascript | function traverseMeshes( cb ) {
object.traverse( function ( child ) {
if ( child.isMesh === true ) {
var mesh = child;
var geometry = mesh.geometry;
if ( geometry.isGeometry === true ) {
geometry = geomToBufferGeom.get( geometry );
}
if ( geometry.isBufferGeometry === true ) {
if ( geometry.getAttribute( 'position' ) !== undefined ) {
cb( mesh, geometry );
}
}
}
} );
} | [
"function",
"traverseMeshes",
"(",
"cb",
")",
"{",
"object",
".",
"traverse",
"(",
"function",
"(",
"child",
")",
"{",
"if",
"(",
"child",
".",
"isMesh",
"===",
"true",
")",
"{",
"var",
"mesh",
"=",
"child",
";",
"var",
"geometry",
"=",
"mesh",
".",
"geometry",
";",
"if",
"(",
"geometry",
".",
"isGeometry",
"===",
"true",
")",
"{",
"geometry",
"=",
"geomToBufferGeom",
".",
"get",
"(",
"geometry",
")",
";",
"}",
"if",
"(",
"geometry",
".",
"isBufferGeometry",
"===",
"true",
")",
"{",
"if",
"(",
"geometry",
".",
"getAttribute",
"(",
"'position'",
")",
"!==",
"undefined",
")",
"{",
"cb",
"(",
"mesh",
",",
"geometry",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"}"
] | Iterate over the valid meshes in the object | [
"Iterate",
"over",
"the",
"valid",
"meshes",
"in",
"the",
"object"
] | e949f79cb3b200335788c64f765613be91f7085c | https://github.com/gkjohnson/ply-exporter-js/blob/e949f79cb3b200335788c64f765613be91f7085c/PLYExporter.js#L32-L61 | train |
cedx/which.js | example/main.js | main | async function main() { // eslint-disable-line no-unused-vars
try {
// `path` is the absolute path to the executable.
const path = await which('foobar');
console.log(`The command "foobar" is located at: ${path}`);
}
catch (err) {
// `err` is an instance of `FinderError`.
console.log(`The command "${err.command}" was not found`);
}
} | javascript | async function main() { // eslint-disable-line no-unused-vars
try {
// `path` is the absolute path to the executable.
const path = await which('foobar');
console.log(`The command "foobar" is located at: ${path}`);
}
catch (err) {
// `err` is an instance of `FinderError`.
console.log(`The command "${err.command}" was not found`);
}
} | [
"async",
"function",
"main",
"(",
")",
"{",
"try",
"{",
"const",
"path",
"=",
"await",
"which",
"(",
"'foobar'",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"path",
"}",
"`",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"err",
".",
"command",
"}",
"`",
")",
";",
"}",
"}"
] | Finds the instances of an executable. | [
"Finds",
"the",
"instances",
"of",
"an",
"executable",
"."
] | 1f875d997e6a9dff3f768673ad024e73e56af207 | https://github.com/cedx/which.js/blob/1f875d997e6a9dff3f768673ad024e73e56af207/example/main.js#L4-L15 | train |
dynamiccast/sails-json-api-blueprints | lib/api/services/JsonApiService.js | function(data) {
var errors = [];
// data.Errors is populated by sails-hook-validations and data.invalidAttributes is the default
var targetAttributes = (data.Errors !== undefined) ? data.Errors : data.invalidAttributes;
for (var attributeName in targetAttributes) {
var attributes = targetAttributes[attributeName];
for (var index in attributes) {
var error = attributes[index];
errors.push({
detail: error.message,
source: {
pointer: "data/attributes/" + this._convertCase(attributeName, this.getAttributesSerializedCaseSetting())
}
});
}
}
return errors;
} | javascript | function(data) {
var errors = [];
// data.Errors is populated by sails-hook-validations and data.invalidAttributes is the default
var targetAttributes = (data.Errors !== undefined) ? data.Errors : data.invalidAttributes;
for (var attributeName in targetAttributes) {
var attributes = targetAttributes[attributeName];
for (var index in attributes) {
var error = attributes[index];
errors.push({
detail: error.message,
source: {
pointer: "data/attributes/" + this._convertCase(attributeName, this.getAttributesSerializedCaseSetting())
}
});
}
}
return errors;
} | [
"function",
"(",
"data",
")",
"{",
"var",
"errors",
"=",
"[",
"]",
";",
"var",
"targetAttributes",
"=",
"(",
"data",
".",
"Errors",
"!==",
"undefined",
")",
"?",
"data",
".",
"Errors",
":",
"data",
".",
"invalidAttributes",
";",
"for",
"(",
"var",
"attributeName",
"in",
"targetAttributes",
")",
"{",
"var",
"attributes",
"=",
"targetAttributes",
"[",
"attributeName",
"]",
";",
"for",
"(",
"var",
"index",
"in",
"attributes",
")",
"{",
"var",
"error",
"=",
"attributes",
"[",
"index",
"]",
";",
"errors",
".",
"push",
"(",
"{",
"detail",
":",
"error",
".",
"message",
",",
"source",
":",
"{",
"pointer",
":",
"\"data/attributes/\"",
"+",
"this",
".",
"_convertCase",
"(",
"attributeName",
",",
"this",
".",
"getAttributesSerializedCaseSetting",
"(",
")",
")",
"}",
"}",
")",
";",
"}",
"}",
"return",
"errors",
";",
"}"
] | Turn a waterline validation error object into a JSON API compliant error object | [
"Turn",
"a",
"waterline",
"validation",
"error",
"object",
"into",
"a",
"JSON",
"API",
"compliant",
"error",
"object"
] | 01db9affa142a4323882b373a21f6d84d6211e81 | https://github.com/dynamiccast/sails-json-api-blueprints/blob/01db9affa142a4323882b373a21f6d84d6211e81/lib/api/services/JsonApiService.js#L230-L255 | train |
|
borisdiakur/memoize-fs | index.js | initCache | function initCache (cachePath) {
return new Promise(function (resolve, reject) {
mkdirp(cachePath, function (err) {
if (err) {
reject(err)
} else {
resolve()
}
})
})
} | javascript | function initCache (cachePath) {
return new Promise(function (resolve, reject) {
mkdirp(cachePath, function (err) {
if (err) {
reject(err)
} else {
resolve()
}
})
})
} | [
"function",
"initCache",
"(",
"cachePath",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"mkdirp",
"(",
"cachePath",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
"}",
"else",
"{",
"resolve",
"(",
")",
"}",
"}",
")",
"}",
")",
"}"
] | check for existing cache folder, if not found, create folder, then resolve | [
"check",
"for",
"existing",
"cache",
"folder",
"if",
"not",
"found",
"create",
"folder",
"then",
"resolve"
] | edf3b9a6ab48274544f6b7fc5be3b011aea47aac | https://github.com/borisdiakur/memoize-fs/blob/edf3b9a6ab48274544f6b7fc5be3b011aea47aac/index.js#L52-L62 | train |
One-com/livestyle | lib/middleware/bufferDataEventsUntilFirstListener.js | createEventBufferer | function createEventBufferer(eventName, bufferedEvents) {
return function () { // ...
bufferedEvents.push([eventName].concat(Array.prototype.slice.call(arguments)));
};
} | javascript | function createEventBufferer(eventName, bufferedEvents) {
return function () { // ...
bufferedEvents.push([eventName].concat(Array.prototype.slice.call(arguments)));
};
} | [
"function",
"createEventBufferer",
"(",
"eventName",
",",
"bufferedEvents",
")",
"{",
"return",
"function",
"(",
")",
"{",
"bufferedEvents",
".",
"push",
"(",
"[",
"eventName",
"]",
".",
"concat",
"(",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
")",
")",
";",
"}",
";",
"}"
] | Middleware that buffers up the request's 'data' and 'end' events
until another 'data' listener is added, then replay the events in
order.
Intended for use with formidable in scenarios where the IncomingForm
is initialized in a route after something async has happened
(authentication via a socket, for instance). | [
"Middleware",
"that",
"buffers",
"up",
"the",
"request",
"s",
"data",
"and",
"end",
"events",
"until",
"another",
"data",
"listener",
"is",
"added",
"then",
"replay",
"the",
"events",
"in",
"order",
"."
] | a93729183fe070d285f58f6bb1256b216f51a1f5 | https://github.com/One-com/livestyle/blob/a93729183fe070d285f58f6bb1256b216f51a1f5/lib/middleware/bufferDataEventsUntilFirstListener.js#L11-L15 | train |
spmjs/grunt-cmd-transport | tasks/lib/handlebars.js | patchHandlebars | function patchHandlebars(Handlebars) {
Handlebars.JavaScriptCompiler.prototype.preamble = function() {
var out = [];
if (!this.isChild) {
var namespace = this.namespace;
// patch for handlebars
var copies = [
"helpers = helpers || {};",
"for (var key in " + namespace + ".helpers) {",
" helpers[key] = helpers[key] || " + namespace + ".helpers[key];",
"}"
].join('\n');
if (this.environment.usePartial) { copies = copies + " partials = partials || " + namespace + ".partials;"; }
if (this.options.data) { copies = copies + " data = data || {};"; }
out.push(copies);
} else {
out.push('');
}
if (!this.environment.isSimple) {
out.push(", buffer = " + this.initializeBuffer());
} else {
out.push("");
}
// track the last context pushed into place to allow skipping the
// getContext opcode when it would be a noop
this.lastContext = 0;
this.source = out;
};
} | javascript | function patchHandlebars(Handlebars) {
Handlebars.JavaScriptCompiler.prototype.preamble = function() {
var out = [];
if (!this.isChild) {
var namespace = this.namespace;
// patch for handlebars
var copies = [
"helpers = helpers || {};",
"for (var key in " + namespace + ".helpers) {",
" helpers[key] = helpers[key] || " + namespace + ".helpers[key];",
"}"
].join('\n');
if (this.environment.usePartial) { copies = copies + " partials = partials || " + namespace + ".partials;"; }
if (this.options.data) { copies = copies + " data = data || {};"; }
out.push(copies);
} else {
out.push('');
}
if (!this.environment.isSimple) {
out.push(", buffer = " + this.initializeBuffer());
} else {
out.push("");
}
// track the last context pushed into place to allow skipping the
// getContext opcode when it would be a noop
this.lastContext = 0;
this.source = out;
};
} | [
"function",
"patchHandlebars",
"(",
"Handlebars",
")",
"{",
"Handlebars",
".",
"JavaScriptCompiler",
".",
"prototype",
".",
"preamble",
"=",
"function",
"(",
")",
"{",
"var",
"out",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"this",
".",
"isChild",
")",
"{",
"var",
"namespace",
"=",
"this",
".",
"namespace",
";",
"var",
"copies",
"=",
"[",
"\"helpers = helpers || {};\"",
",",
"\"for (var key in \"",
"+",
"namespace",
"+",
"\".helpers) {\"",
",",
"\" helpers[key] = helpers[key] || \"",
"+",
"namespace",
"+",
"\".helpers[key];\"",
",",
"\"}\"",
"]",
".",
"join",
"(",
"'\\n'",
")",
";",
"\\n",
"if",
"(",
"this",
".",
"environment",
".",
"usePartial",
")",
"{",
"copies",
"=",
"copies",
"+",
"\" partials = partials || \"",
"+",
"namespace",
"+",
"\".partials;\"",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"data",
")",
"{",
"copies",
"=",
"copies",
"+",
"\" data = data || {};\"",
";",
"}",
"}",
"else",
"out",
".",
"push",
"(",
"copies",
")",
";",
"{",
"out",
".",
"push",
"(",
"''",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"environment",
".",
"isSimple",
")",
"{",
"out",
".",
"push",
"(",
"\", buffer = \"",
"+",
"this",
".",
"initializeBuffer",
"(",
")",
")",
";",
"}",
"else",
"{",
"out",
".",
"push",
"(",
"\"\"",
")",
";",
"}",
"this",
".",
"lastContext",
"=",
"0",
";",
"}",
";",
"}"
] | patch for handlebars | [
"patch",
"for",
"handlebars"
] | 8426714a4cec653db54395ee17a6e883fbc7ce41 | https://github.com/spmjs/grunt-cmd-transport/blob/8426714a4cec653db54395ee17a6e883fbc7ce41/tasks/lib/handlebars.js#L29-L60 | train |
BowlingX/marklib | src/main/modules/Site.js | presentRendering | function presentRendering(selector, classNames, speed) {
const text = document.getElementById(selector).childNodes[0];
const thisLength = text.length;
const render = (autoMarkText, cp, length) => {
let c = cp;
const r = new Rendering(document, {
className: classNames
});
const range = document.createRange();
range.setStart(autoMarkText, 0);
range.setEnd(autoMarkText, 1);
r.renderWithRange(range);
if (autoMarkText.parentNode.nextSibling) {
const nextText = autoMarkText.parentNode.nextSibling.childNodes[0];
setTimeout(() => {
render(nextText, ++c, length);
}, speed);
}
};
return render(text, 0, thisLength);
} | javascript | function presentRendering(selector, classNames, speed) {
const text = document.getElementById(selector).childNodes[0];
const thisLength = text.length;
const render = (autoMarkText, cp, length) => {
let c = cp;
const r = new Rendering(document, {
className: classNames
});
const range = document.createRange();
range.setStart(autoMarkText, 0);
range.setEnd(autoMarkText, 1);
r.renderWithRange(range);
if (autoMarkText.parentNode.nextSibling) {
const nextText = autoMarkText.parentNode.nextSibling.childNodes[0];
setTimeout(() => {
render(nextText, ++c, length);
}, speed);
}
};
return render(text, 0, thisLength);
} | [
"function",
"presentRendering",
"(",
"selector",
",",
"classNames",
",",
"speed",
")",
"{",
"const",
"text",
"=",
"document",
".",
"getElementById",
"(",
"selector",
")",
".",
"childNodes",
"[",
"0",
"]",
";",
"const",
"thisLength",
"=",
"text",
".",
"length",
";",
"const",
"render",
"=",
"(",
"autoMarkText",
",",
"cp",
",",
"length",
")",
"=>",
"{",
"let",
"c",
"=",
"cp",
";",
"const",
"r",
"=",
"new",
"Rendering",
"(",
"document",
",",
"{",
"className",
":",
"classNames",
"}",
")",
";",
"const",
"range",
"=",
"document",
".",
"createRange",
"(",
")",
";",
"range",
".",
"setStart",
"(",
"autoMarkText",
",",
"0",
")",
";",
"range",
".",
"setEnd",
"(",
"autoMarkText",
",",
"1",
")",
";",
"r",
".",
"renderWithRange",
"(",
"range",
")",
";",
"if",
"(",
"autoMarkText",
".",
"parentNode",
".",
"nextSibling",
")",
"{",
"const",
"nextText",
"=",
"autoMarkText",
".",
"parentNode",
".",
"nextSibling",
".",
"childNodes",
"[",
"0",
"]",
";",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"render",
"(",
"nextText",
",",
"++",
"c",
",",
"length",
")",
";",
"}",
",",
"speed",
")",
";",
"}",
"}",
";",
"return",
"render",
"(",
"text",
",",
"0",
",",
"thisLength",
")",
";",
"}"
] | Creates an animated rendering | [
"Creates",
"an",
"animated",
"rendering"
] | d3ea15907cd5021a86348695391e07d554363e70 | https://github.com/BowlingX/marklib/blob/d3ea15907cd5021a86348695391e07d554363e70/src/main/modules/Site.js#L22-L44 | train |
BowlingX/marklib | src/main/modules/Site.js | onClick | function onClick(instance) {
const self = instance;
self.wrapperNodes.forEach((n) => {
n.addEventListener(ANIMATIONEND, function thisFunction(e) {
e.target.classList.remove('bubble');
e.target.removeEventListener(ANIMATIONEND, thisFunction);
});
n.classList.add('bubble');
});
if (tooltip.getCurrentTarget() === self.wrapperNodes[0]) {
return;
}
tooltip.createTooltip(self.wrapperNodes[0], self.result.text, false);
setTimeout(() => {
if (tooltip.getCurrentTarget()) {
document.addEventListener('click', function thisFunction() {
if (tooltip.getCurrentTarget() && tooltip.getCurrentTarget() === self.wrapperNodes[0]) {
tooltip.removeTooltip();
}
document.removeEventListener('click', thisFunction);
});
}
}, 0);
} | javascript | function onClick(instance) {
const self = instance;
self.wrapperNodes.forEach((n) => {
n.addEventListener(ANIMATIONEND, function thisFunction(e) {
e.target.classList.remove('bubble');
e.target.removeEventListener(ANIMATIONEND, thisFunction);
});
n.classList.add('bubble');
});
if (tooltip.getCurrentTarget() === self.wrapperNodes[0]) {
return;
}
tooltip.createTooltip(self.wrapperNodes[0], self.result.text, false);
setTimeout(() => {
if (tooltip.getCurrentTarget()) {
document.addEventListener('click', function thisFunction() {
if (tooltip.getCurrentTarget() && tooltip.getCurrentTarget() === self.wrapperNodes[0]) {
tooltip.removeTooltip();
}
document.removeEventListener('click', thisFunction);
});
}
}, 0);
} | [
"function",
"onClick",
"(",
"instance",
")",
"{",
"const",
"self",
"=",
"instance",
";",
"self",
".",
"wrapperNodes",
".",
"forEach",
"(",
"(",
"n",
")",
"=>",
"{",
"n",
".",
"addEventListener",
"(",
"ANIMATIONEND",
",",
"function",
"thisFunction",
"(",
"e",
")",
"{",
"e",
".",
"target",
".",
"classList",
".",
"remove",
"(",
"'bubble'",
")",
";",
"e",
".",
"target",
".",
"removeEventListener",
"(",
"ANIMATIONEND",
",",
"thisFunction",
")",
";",
"}",
")",
";",
"n",
".",
"classList",
".",
"add",
"(",
"'bubble'",
")",
";",
"}",
")",
";",
"if",
"(",
"tooltip",
".",
"getCurrentTarget",
"(",
")",
"===",
"self",
".",
"wrapperNodes",
"[",
"0",
"]",
")",
"{",
"return",
";",
"}",
"tooltip",
".",
"createTooltip",
"(",
"self",
".",
"wrapperNodes",
"[",
"0",
"]",
",",
"self",
".",
"result",
".",
"text",
",",
"false",
")",
";",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"tooltip",
".",
"getCurrentTarget",
"(",
")",
")",
"{",
"document",
".",
"addEventListener",
"(",
"'click'",
",",
"function",
"thisFunction",
"(",
")",
"{",
"if",
"(",
"tooltip",
".",
"getCurrentTarget",
"(",
")",
"&&",
"tooltip",
".",
"getCurrentTarget",
"(",
")",
"===",
"self",
".",
"wrapperNodes",
"[",
"0",
"]",
")",
"{",
"tooltip",
".",
"removeTooltip",
"(",
")",
";",
"}",
"document",
".",
"removeEventListener",
"(",
"'click'",
",",
"thisFunction",
")",
";",
"}",
")",
";",
"}",
"}",
",",
"0",
")",
";",
"}"
] | OnClick event for renderings | [
"OnClick",
"event",
"for",
"renderings"
] | d3ea15907cd5021a86348695391e07d554363e70 | https://github.com/BowlingX/marklib/blob/d3ea15907cd5021a86348695391e07d554363e70/src/main/modules/Site.js#L54-L80 | train |
cedx/which.js | bin/which.js | main | async function main() {
// Initialize the application.
process.title = 'Which.js';
// Parse the command line arguments.
program.name('which')
.description('Find the instances of an executable in the system path.')
.version(packageVersion, '-v, --version')
.option('-a, --all', 'list all instances of executables found (instead of just the first one)')
.option('-s, --silent', 'silence the output, just return the exit code (0 if any executable is found, otherwise 1)')
.arguments('<command>').action(command => program.executable = command)
.parse(process.argv);
if (!program.executable) {
program.outputHelp();
process.exitCode = 64;
return;
}
// Run the program.
let executables = await which(program.executable, {all: program.all});
if (!program.silent) {
if (!Array.isArray(executables)) executables = [executables];
for (const path of executables) console.log(path);
}
} | javascript | async function main() {
// Initialize the application.
process.title = 'Which.js';
// Parse the command line arguments.
program.name('which')
.description('Find the instances of an executable in the system path.')
.version(packageVersion, '-v, --version')
.option('-a, --all', 'list all instances of executables found (instead of just the first one)')
.option('-s, --silent', 'silence the output, just return the exit code (0 if any executable is found, otherwise 1)')
.arguments('<command>').action(command => program.executable = command)
.parse(process.argv);
if (!program.executable) {
program.outputHelp();
process.exitCode = 64;
return;
}
// Run the program.
let executables = await which(program.executable, {all: program.all});
if (!program.silent) {
if (!Array.isArray(executables)) executables = [executables];
for (const path of executables) console.log(path);
}
} | [
"async",
"function",
"main",
"(",
")",
"{",
"process",
".",
"title",
"=",
"'Which.js'",
";",
"program",
".",
"name",
"(",
"'which'",
")",
".",
"description",
"(",
"'Find the instances of an executable in the system path.'",
")",
".",
"version",
"(",
"packageVersion",
",",
"'-v, --version'",
")",
".",
"option",
"(",
"'-a, --all'",
",",
"'list all instances of executables found (instead of just the first one)'",
")",
".",
"option",
"(",
"'-s, --silent'",
",",
"'silence the output, just return the exit code (0 if any executable is found, otherwise 1)'",
")",
".",
"arguments",
"(",
"'<command>'",
")",
".",
"action",
"(",
"command",
"=>",
"program",
".",
"executable",
"=",
"command",
")",
".",
"parse",
"(",
"process",
".",
"argv",
")",
";",
"if",
"(",
"!",
"program",
".",
"executable",
")",
"{",
"program",
".",
"outputHelp",
"(",
")",
";",
"process",
".",
"exitCode",
"=",
"64",
";",
"return",
";",
"}",
"let",
"executables",
"=",
"await",
"which",
"(",
"program",
".",
"executable",
",",
"{",
"all",
":",
"program",
".",
"all",
"}",
")",
";",
"if",
"(",
"!",
"program",
".",
"silent",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"executables",
")",
")",
"executables",
"=",
"[",
"executables",
"]",
";",
"for",
"(",
"const",
"path",
"of",
"executables",
")",
"console",
".",
"log",
"(",
"path",
")",
";",
"}",
"}"
] | Application entry point.
@return {Promise<void>} Completes when the program is terminated. | [
"Application",
"entry",
"point",
"."
] | 1f875d997e6a9dff3f768673ad024e73e56af207 | https://github.com/cedx/which.js/blob/1f875d997e6a9dff3f768673ad024e73e56af207/bin/which.js#L15-L40 | train |
dynamiccast/sails-json-api-blueprints | lib/api/blueprints/_util/actionUtil.js | function(req) {
var pk = module.exports.parsePk(req);
// Validate the required `id` parameter
if (!pk) {
var err = new Error(
'No `id` parameter provided.' +
'(Note: even if the model\'s primary key is not named `id`- ' +
'`id` should be used as the name of the parameter- it will be ' +
'mapped to the proper primary key name)'
);
err.status = 400;
throw err;
}
return pk;
} | javascript | function(req) {
var pk = module.exports.parsePk(req);
// Validate the required `id` parameter
if (!pk) {
var err = new Error(
'No `id` parameter provided.' +
'(Note: even if the model\'s primary key is not named `id`- ' +
'`id` should be used as the name of the parameter- it will be ' +
'mapped to the proper primary key name)'
);
err.status = 400;
throw err;
}
return pk;
} | [
"function",
"(",
"req",
")",
"{",
"var",
"pk",
"=",
"module",
".",
"exports",
".",
"parsePk",
"(",
"req",
")",
";",
"if",
"(",
"!",
"pk",
")",
"{",
"var",
"err",
"=",
"new",
"Error",
"(",
"'No `id` parameter provided.'",
"+",
"'(Note: even if the model\\'s primary key is not named `id`- '",
"+",
"\\'",
"+",
"'`id` should be used as the name of the parameter- it will be '",
")",
";",
"'mapped to the proper primary key name)'",
"err",
".",
"status",
"=",
"400",
";",
"}",
"throw",
"err",
";",
"}"
] | Parse primary key value from parameters.
Throw an error if it cannot be retrieved.
@param {Request} req
@return {Integer|String} | [
"Parse",
"primary",
"key",
"value",
"from",
"parameters",
".",
"Throw",
"an",
"error",
"if",
"it",
"cannot",
"be",
"retrieved",
"."
] | 01db9affa142a4323882b373a21f6d84d6211e81 | https://github.com/dynamiccast/sails-json-api-blueprints/blob/01db9affa142a4323882b373a21f6d84d6211e81/lib/api/blueprints/_util/actionUtil.js#L71-L89 | train |
|
dynamiccast/sails-json-api-blueprints | lib/hook.js | function (path, action, options) {
options = options || routeOpts;
options = _.extend({}, options, {action: action, controller: controllerId});
sails.router.bind ( path, _getAction(action), null, options);
} | javascript | function (path, action, options) {
options = options || routeOpts;
options = _.extend({}, options, {action: action, controller: controllerId});
sails.router.bind ( path, _getAction(action), null, options);
} | [
"function",
"(",
"path",
",",
"action",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"routeOpts",
";",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"options",
",",
"{",
"action",
":",
"action",
",",
"controller",
":",
"controllerId",
"}",
")",
";",
"sails",
".",
"router",
".",
"bind",
"(",
"path",
",",
"_getAction",
"(",
"action",
")",
",",
"null",
",",
"options",
")",
";",
"}"
] | Binds a route to the specifed action using _getAction, and sets the action and controller options for req.options | [
"Binds",
"a",
"route",
"to",
"the",
"specifed",
"action",
"using",
"_getAction",
"and",
"sets",
"the",
"action",
"and",
"controller",
"options",
"for",
"req",
".",
"options"
] | 01db9affa142a4323882b373a21f6d84d6211e81 | https://github.com/dynamiccast/sails-json-api-blueprints/blob/01db9affa142a4323882b373a21f6d84d6211e81/lib/hook.js#L318-L323 | train |
|
dynamiccast/sails-json-api-blueprints | lib/hook.js | _getMiddlewareForShadowRoute | function _getMiddlewareForShadowRoute (controllerId, blueprintId) {
// Allow custom actions defined in controller to override blueprint actions.
return sails.middleware.controllers[controllerId][blueprintId.toLowerCase()] || hook.middleware[blueprintId.toLowerCase()];
} | javascript | function _getMiddlewareForShadowRoute (controllerId, blueprintId) {
// Allow custom actions defined in controller to override blueprint actions.
return sails.middleware.controllers[controllerId][blueprintId.toLowerCase()] || hook.middleware[blueprintId.toLowerCase()];
} | [
"function",
"_getMiddlewareForShadowRoute",
"(",
"controllerId",
",",
"blueprintId",
")",
"{",
"return",
"sails",
".",
"middleware",
".",
"controllers",
"[",
"controllerId",
"]",
"[",
"blueprintId",
".",
"toLowerCase",
"(",
")",
"]",
"||",
"hook",
".",
"middleware",
"[",
"blueprintId",
".",
"toLowerCase",
"(",
")",
"]",
";",
"}"
] | Return the middleware function that should be bound for a shadow route
pointing to the specified blueprintId. Will use the explicit controller
action if it exists, otherwise the blueprint action.
@param {String} controllerId
@param {String} blueprintId [find, create, etc.]
@return {Function} [middleware] | [
"Return",
"the",
"middleware",
"function",
"that",
"should",
"be",
"bound",
"for",
"a",
"shadow",
"route",
"pointing",
"to",
"the",
"specified",
"blueprintId",
".",
"Will",
"use",
"the",
"explicit",
"controller",
"action",
"if",
"it",
"exists",
"otherwise",
"the",
"blueprint",
"action",
"."
] | 01db9affa142a4323882b373a21f6d84d6211e81 | https://github.com/dynamiccast/sails-json-api-blueprints/blob/01db9affa142a4323882b373a21f6d84d6211e81/lib/hook.js#L395-L399 | train |
dojot/dojot-module-nodejs | lib/auth.js | getManagementToken | function getManagementToken(tenant, config = defaultConfig) {
const payload = {
service: tenant,
username: config.dojot.management.user
};
return (
new Buffer("jwt schema").toString("base64") +
"." +
new Buffer(JSON.stringify(payload)).toString("base64") +
"." +
new Buffer("dummy signature").toString("base64")
);
} | javascript | function getManagementToken(tenant, config = defaultConfig) {
const payload = {
service: tenant,
username: config.dojot.management.user
};
return (
new Buffer("jwt schema").toString("base64") +
"." +
new Buffer(JSON.stringify(payload)).toString("base64") +
"." +
new Buffer("dummy signature").toString("base64")
);
} | [
"function",
"getManagementToken",
"(",
"tenant",
",",
"config",
"=",
"defaultConfig",
")",
"{",
"const",
"payload",
"=",
"{",
"service",
":",
"tenant",
",",
"username",
":",
"config",
".",
"dojot",
".",
"management",
".",
"user",
"}",
";",
"return",
"(",
"new",
"Buffer",
"(",
"\"jwt schema\"",
")",
".",
"toString",
"(",
"\"base64\"",
")",
"+",
"\".\"",
"+",
"new",
"Buffer",
"(",
"JSON",
".",
"stringify",
"(",
"payload",
")",
")",
".",
"toString",
"(",
"\"base64\"",
")",
"+",
"\".\"",
"+",
"new",
"Buffer",
"(",
"\"dummy signature\"",
")",
".",
"toString",
"(",
"\"base64\"",
")",
")",
";",
"}"
] | Generates a dummy token
@param {string} tenant Tenant to be used when creating the token | [
"Generates",
"a",
"dummy",
"token"
] | f4a877ab7e39f5d27c6b28651e922654815890c6 | https://github.com/dojot/dojot-module-nodejs/blob/f4a877ab7e39f5d27c6b28651e922654815890c6/lib/auth.js#L12-L24 | train |
hoodiehq/hoodie-store-server-api | utils/remove-role-privilege.js | removeRolePrivilege | function removeRolePrivilege (access, role, privilege) {
if (role === true) {
access[privilege] = {
role: []
}
return
}
if (access[privilege].role === true) {
access[privilege].role = true
}
_.pullAll(access[privilege].role, _.concat(role))
} | javascript | function removeRolePrivilege (access, role, privilege) {
if (role === true) {
access[privilege] = {
role: []
}
return
}
if (access[privilege].role === true) {
access[privilege].role = true
}
_.pullAll(access[privilege].role, _.concat(role))
} | [
"function",
"removeRolePrivilege",
"(",
"access",
",",
"role",
",",
"privilege",
")",
"{",
"if",
"(",
"role",
"===",
"true",
")",
"{",
"access",
"[",
"privilege",
"]",
"=",
"{",
"role",
":",
"[",
"]",
"}",
"return",
"}",
"if",
"(",
"access",
"[",
"privilege",
"]",
".",
"role",
"===",
"true",
")",
"{",
"access",
"[",
"privilege",
"]",
".",
"role",
"=",
"true",
"}",
"_",
".",
"pullAll",
"(",
"access",
"[",
"privilege",
"]",
".",
"role",
",",
"_",
".",
"concat",
"(",
"role",
")",
")",
"}"
] | An empty array means that nobody has access. If the current setting is true,
access cannot be revoked for a role, so it remains true. Otherwise all passed
roles are removed from the once that currently have access | [
"An",
"empty",
"array",
"means",
"that",
"nobody",
"has",
"access",
".",
"If",
"the",
"current",
"setting",
"is",
"true",
"access",
"cannot",
"be",
"revoked",
"for",
"a",
"role",
"so",
"it",
"remains",
"true",
".",
"Otherwise",
"all",
"passed",
"roles",
"are",
"removed",
"from",
"the",
"once",
"that",
"currently",
"have",
"access"
] | 75e781ad90bc34116603c331d51aae96cae6109b | https://github.com/hoodiehq/hoodie-store-server-api/blob/75e781ad90bc34116603c331d51aae96cae6109b/utils/remove-role-privilege.js#L10-L23 | train |
forest-fire/firemodel | dist/cjs/path.js | pathJoin | function pathJoin(...args) {
return args
.reduce((prev, val) => {
if (typeof prev === "undefined") {
return;
}
if (val === undefined) {
return prev;
}
return typeof val === "string" || typeof val === "number"
? joinStringsWithSlash(prev, "" + val) // if string or number just keep as is
: Array.isArray(val)
? joinStringsWithSlash(prev, pathJoin.apply(null, val)) // handle array with recursion
: console.error(errorStr(typeof val));
}, "")
.replace(moreThanThreePeriods, ".."); // join the resulting array together
} | javascript | function pathJoin(...args) {
return args
.reduce((prev, val) => {
if (typeof prev === "undefined") {
return;
}
if (val === undefined) {
return prev;
}
return typeof val === "string" || typeof val === "number"
? joinStringsWithSlash(prev, "" + val) // if string or number just keep as is
: Array.isArray(val)
? joinStringsWithSlash(prev, pathJoin.apply(null, val)) // handle array with recursion
: console.error(errorStr(typeof val));
}, "")
.replace(moreThanThreePeriods, ".."); // join the resulting array together
} | [
"function",
"pathJoin",
"(",
"...",
"args",
")",
"{",
"return",
"args",
".",
"reduce",
"(",
"(",
"prev",
",",
"val",
")",
"=>",
"{",
"if",
"(",
"typeof",
"prev",
"===",
"\"undefined\"",
")",
"{",
"return",
";",
"}",
"if",
"(",
"val",
"===",
"undefined",
")",
"{",
"return",
"prev",
";",
"}",
"return",
"typeof",
"val",
"===",
"\"string\"",
"||",
"typeof",
"val",
"===",
"\"number\"",
"?",
"joinStringsWithSlash",
"(",
"prev",
",",
"\"\"",
"+",
"val",
")",
":",
"Array",
".",
"isArray",
"(",
"val",
")",
"?",
"joinStringsWithSlash",
"(",
"prev",
",",
"pathJoin",
".",
"apply",
"(",
"null",
",",
"val",
")",
")",
":",
"console",
".",
"error",
"(",
"errorStr",
"(",
"typeof",
"val",
")",
")",
";",
"}",
",",
"\"\"",
")",
".",
"replace",
"(",
"moreThanThreePeriods",
",",
"\"..\"",
")",
";",
"}"
] | An ISO-morphic path join that works everywhere | [
"An",
"ISO",
"-",
"morphic",
"path",
"join",
"that",
"works",
"everywhere"
] | 381b4c9d6df5db47924ef406243f6e8669a1f03e | https://github.com/forest-fire/firemodel/blob/381b4c9d6df5db47924ef406243f6e8669a1f03e/dist/cjs/path.js#L14-L30 | train |
npm/readdir-scoped-modules | readdir.js | readScopes | function readScopes (root, kids, cb) {
var scopes = kids . filter (function (kid) {
return kid . charAt (0) === '@'
})
kids = kids . filter (function (kid) {
return kid . charAt (0) !== '@'
})
debug ('scopes=%j', scopes)
if (scopes . length === 0)
dz (cb) (null, kids) // prevent maybe-sync zalgo release
cb = once (cb)
var l = scopes . length
scopes . forEach (function (scope) {
var scopedir = path . resolve (root, scope)
debug ('root=%j scope=%j scopedir=%j', root, scope, scopedir)
fs . readdir (scopedir, then . bind (null, scope))
})
function then (scope, er, scopekids) {
if (er)
return cb (er)
// XXX: Not sure how old this node bug is. Maybe superstition?
scopekids = scopekids . filter (function (scopekid) {
return !(scopekid === '.' || scopekid === '..' || !scopekid)
})
kids . push . apply (kids, scopekids . map (function (scopekid) {
return scope + '/' + scopekid
}))
debug ('scope=%j scopekids=%j kids=%j', scope, scopekids, kids)
if (--l === 0)
cb (null, kids)
}
} | javascript | function readScopes (root, kids, cb) {
var scopes = kids . filter (function (kid) {
return kid . charAt (0) === '@'
})
kids = kids . filter (function (kid) {
return kid . charAt (0) !== '@'
})
debug ('scopes=%j', scopes)
if (scopes . length === 0)
dz (cb) (null, kids) // prevent maybe-sync zalgo release
cb = once (cb)
var l = scopes . length
scopes . forEach (function (scope) {
var scopedir = path . resolve (root, scope)
debug ('root=%j scope=%j scopedir=%j', root, scope, scopedir)
fs . readdir (scopedir, then . bind (null, scope))
})
function then (scope, er, scopekids) {
if (er)
return cb (er)
// XXX: Not sure how old this node bug is. Maybe superstition?
scopekids = scopekids . filter (function (scopekid) {
return !(scopekid === '.' || scopekid === '..' || !scopekid)
})
kids . push . apply (kids, scopekids . map (function (scopekid) {
return scope + '/' + scopekid
}))
debug ('scope=%j scopekids=%j kids=%j', scope, scopekids, kids)
if (--l === 0)
cb (null, kids)
}
} | [
"function",
"readScopes",
"(",
"root",
",",
"kids",
",",
"cb",
")",
"{",
"var",
"scopes",
"=",
"kids",
".",
"filter",
"(",
"function",
"(",
"kid",
")",
"{",
"return",
"kid",
".",
"charAt",
"(",
"0",
")",
"===",
"'@'",
"}",
")",
"kids",
"=",
"kids",
".",
"filter",
"(",
"function",
"(",
"kid",
")",
"{",
"return",
"kid",
".",
"charAt",
"(",
"0",
")",
"!==",
"'@'",
"}",
")",
"debug",
"(",
"'scopes=%j'",
",",
"scopes",
")",
"if",
"(",
"scopes",
".",
"length",
"===",
"0",
")",
"dz",
"(",
"cb",
")",
"(",
"null",
",",
"kids",
")",
"cb",
"=",
"once",
"(",
"cb",
")",
"var",
"l",
"=",
"scopes",
".",
"length",
"scopes",
".",
"forEach",
"(",
"function",
"(",
"scope",
")",
"{",
"var",
"scopedir",
"=",
"path",
".",
"resolve",
"(",
"root",
",",
"scope",
")",
"debug",
"(",
"'root=%j scope=%j scopedir=%j'",
",",
"root",
",",
"scope",
",",
"scopedir",
")",
"fs",
".",
"readdir",
"(",
"scopedir",
",",
"then",
".",
"bind",
"(",
"null",
",",
"scope",
")",
")",
"}",
")",
"function",
"then",
"(",
"scope",
",",
"er",
",",
"scopekids",
")",
"{",
"if",
"(",
"er",
")",
"return",
"cb",
"(",
"er",
")",
"scopekids",
"=",
"scopekids",
".",
"filter",
"(",
"function",
"(",
"scopekid",
")",
"{",
"return",
"!",
"(",
"scopekid",
"===",
"'.'",
"||",
"scopekid",
"===",
"'..'",
"||",
"!",
"scopekid",
")",
"}",
")",
"kids",
".",
"push",
".",
"apply",
"(",
"kids",
",",
"scopekids",
".",
"map",
"(",
"function",
"(",
"scopekid",
")",
"{",
"return",
"scope",
"+",
"'/'",
"+",
"scopekid",
"}",
")",
")",
"debug",
"(",
"'scope=%j scopekids=%j kids=%j'",
",",
"scope",
",",
"scopekids",
",",
"kids",
")",
"if",
"(",
"--",
"l",
"===",
"0",
")",
"cb",
"(",
"null",
",",
"kids",
")",
"}",
"}"
] | Turn [ 'a', '@scope' ] into ['a', '@scope/foo', '@scope/bar'] | [
"Turn",
"[",
"a"
] | d41d5de877cb4e9e3f14b92913132680af73d1b4 | https://github.com/npm/readdir-scoped-modules/blob/d41d5de877cb4e9e3f14b92913132680af73d1b4/readdir.js#L31-L71 | train |
canjs/can-view-live | lib/attrs.js | liveAttrsUpdate | function liveAttrsUpdate(newVal) {
var newAttrs = live.getAttributeParts(newVal),
name;
for (name in newAttrs) {
var newValue = newAttrs[name],
// `oldAttrs` was set on the last run of setAttrs in this context
// (for this element and compute)
oldValue = oldAttrs[name];
// Only fire a callback
// if the value of the attribute has changed
if (newValue !== oldValue) {
// set on DOM attributes (dispatches an "attributes" event as well)
domMutateNode.setAttribute.call(el, name, newValue);
// get registered callback for attribute name and fire
var callback = viewCallbacks.attr(name);
if (callback) {
callback(el, {
attributeName: name,
scope: scope,
options: options
});
}
}
// remove key found in new attrs from old attrs
delete oldAttrs[name];
}
// any attrs left at this point are not set on the element now,
// so remove them.
for (name in oldAttrs) {
domMutateNode.removeAttribute.call(el, name);
}
oldAttrs = newAttrs;
} | javascript | function liveAttrsUpdate(newVal) {
var newAttrs = live.getAttributeParts(newVal),
name;
for (name in newAttrs) {
var newValue = newAttrs[name],
// `oldAttrs` was set on the last run of setAttrs in this context
// (for this element and compute)
oldValue = oldAttrs[name];
// Only fire a callback
// if the value of the attribute has changed
if (newValue !== oldValue) {
// set on DOM attributes (dispatches an "attributes" event as well)
domMutateNode.setAttribute.call(el, name, newValue);
// get registered callback for attribute name and fire
var callback = viewCallbacks.attr(name);
if (callback) {
callback(el, {
attributeName: name,
scope: scope,
options: options
});
}
}
// remove key found in new attrs from old attrs
delete oldAttrs[name];
}
// any attrs left at this point are not set on the element now,
// so remove them.
for (name in oldAttrs) {
domMutateNode.removeAttribute.call(el, name);
}
oldAttrs = newAttrs;
} | [
"function",
"liveAttrsUpdate",
"(",
"newVal",
")",
"{",
"var",
"newAttrs",
"=",
"live",
".",
"getAttributeParts",
"(",
"newVal",
")",
",",
"name",
";",
"for",
"(",
"name",
"in",
"newAttrs",
")",
"{",
"var",
"newValue",
"=",
"newAttrs",
"[",
"name",
"]",
",",
"oldValue",
"=",
"oldAttrs",
"[",
"name",
"]",
";",
"if",
"(",
"newValue",
"!==",
"oldValue",
")",
"{",
"domMutateNode",
".",
"setAttribute",
".",
"call",
"(",
"el",
",",
"name",
",",
"newValue",
")",
";",
"var",
"callback",
"=",
"viewCallbacks",
".",
"attr",
"(",
"name",
")",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"el",
",",
"{",
"attributeName",
":",
"name",
",",
"scope",
":",
"scope",
",",
"options",
":",
"options",
"}",
")",
";",
"}",
"}",
"delete",
"oldAttrs",
"[",
"name",
"]",
";",
"}",
"for",
"(",
"name",
"in",
"oldAttrs",
")",
"{",
"domMutateNode",
".",
"removeAttribute",
".",
"call",
"(",
"el",
",",
"name",
")",
";",
"}",
"oldAttrs",
"=",
"newAttrs",
";",
"}"
] | set up a callback for handling changes when the compute changes | [
"set",
"up",
"a",
"callback",
"for",
"handling",
"changes",
"when",
"the",
"compute",
"changes"
] | 00f6bf4ae003afe746b3d88fcfa67c9bb2f97a60 | https://github.com/canjs/can-view-live/blob/00f6bf4ae003afe746b3d88fcfa67c9bb2f97a60/lib/attrs.js#L29-L61 | train |
forest-fire/firemodel | dist/cjs/src/decorators/indexing.js | getDbIndexes | function getDbIndexes(modelKlass) {
const modelName = modelKlass.constructor.name;
return modelName === "Model"
? typed_conversions_1.hashToArray(exports.indexesForModel[modelName])
: (typed_conversions_1.hashToArray(exports.indexesForModel[modelName]) || []).concat(typed_conversions_1.hashToArray(exports.indexesForModel.Model));
} | javascript | function getDbIndexes(modelKlass) {
const modelName = modelKlass.constructor.name;
return modelName === "Model"
? typed_conversions_1.hashToArray(exports.indexesForModel[modelName])
: (typed_conversions_1.hashToArray(exports.indexesForModel[modelName]) || []).concat(typed_conversions_1.hashToArray(exports.indexesForModel.Model));
} | [
"function",
"getDbIndexes",
"(",
"modelKlass",
")",
"{",
"const",
"modelName",
"=",
"modelKlass",
".",
"constructor",
".",
"name",
";",
"return",
"modelName",
"===",
"\"Model\"",
"?",
"typed_conversions_1",
".",
"hashToArray",
"(",
"exports",
".",
"indexesForModel",
"[",
"modelName",
"]",
")",
":",
"(",
"typed_conversions_1",
".",
"hashToArray",
"(",
"exports",
".",
"indexesForModel",
"[",
"modelName",
"]",
")",
"||",
"[",
"]",
")",
".",
"concat",
"(",
"typed_conversions_1",
".",
"hashToArray",
"(",
"exports",
".",
"indexesForModel",
".",
"Model",
")",
")",
";",
"}"
] | Gets all the db indexes for a given model | [
"Gets",
"all",
"the",
"db",
"indexes",
"for",
"a",
"given",
"model"
] | 381b4c9d6df5db47924ef406243f6e8669a1f03e | https://github.com/forest-fire/firemodel/blob/381b4c9d6df5db47924ef406243f6e8669a1f03e/dist/cjs/src/decorators/indexing.js#L11-L16 | train |
vajahath/lme | src/config.js | getChalkColors | function getChalkColors(defaultConfig, overrideConfig) {
var effectiveConfig = Object.assign({}, defaultConfig, overrideConfig);
// make the effectiveConfig understandable to chalk
// and return it
return buildChalkFunction(effectiveConfig);
} | javascript | function getChalkColors(defaultConfig, overrideConfig) {
var effectiveConfig = Object.assign({}, defaultConfig, overrideConfig);
// make the effectiveConfig understandable to chalk
// and return it
return buildChalkFunction(effectiveConfig);
} | [
"function",
"getChalkColors",
"(",
"defaultConfig",
",",
"overrideConfig",
")",
"{",
"var",
"effectiveConfig",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"defaultConfig",
",",
"overrideConfig",
")",
";",
"return",
"buildChalkFunction",
"(",
"effectiveConfig",
")",
";",
"}"
] | Produce overrided configuration | [
"Produce",
"overrided",
"configuration"
] | 2ffe974ecafc291ce4dc3dc34ebcee1f4898f7aa | https://github.com/vajahath/lme/blob/2ffe974ecafc291ce4dc3dc34ebcee1f4898f7aa/src/config.js#L4-L10 | train |
alojs/alo | lib/subscription/subscription.js | Subscription | function Subscription () {
this._id = null
this._storeRelations = null
this._memberRelations = null
this._dependencyRelations = null
this._events = {
'beforePublish': [],
'afterPublish': []
}
this._subscriptionStream = null
this._stream = null
this._lastData = null
this._muted = false
storeRelation.constructParent(this)
memberRelation.constructParent(this)
dependencyRelation.constructParent(this)
subscription.apply(this, arguments)
} | javascript | function Subscription () {
this._id = null
this._storeRelations = null
this._memberRelations = null
this._dependencyRelations = null
this._events = {
'beforePublish': [],
'afterPublish': []
}
this._subscriptionStream = null
this._stream = null
this._lastData = null
this._muted = false
storeRelation.constructParent(this)
memberRelation.constructParent(this)
dependencyRelation.constructParent(this)
subscription.apply(this, arguments)
} | [
"function",
"Subscription",
"(",
")",
"{",
"this",
".",
"_id",
"=",
"null",
"this",
".",
"_storeRelations",
"=",
"null",
"this",
".",
"_memberRelations",
"=",
"null",
"this",
".",
"_dependencyRelations",
"=",
"null",
"this",
".",
"_events",
"=",
"{",
"'beforePublish'",
":",
"[",
"]",
",",
"'afterPublish'",
":",
"[",
"]",
"}",
"this",
".",
"_subscriptionStream",
"=",
"null",
"this",
".",
"_stream",
"=",
"null",
"this",
".",
"_lastData",
"=",
"null",
"this",
".",
"_muted",
"=",
"false",
"storeRelation",
".",
"constructParent",
"(",
"this",
")",
"memberRelation",
".",
"constructParent",
"(",
"this",
")",
"dependencyRelation",
".",
"constructParent",
"(",
"this",
")",
"subscription",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
"}"
] | Subscription Constructor, is used in the Store Class to create Subscriptions to state
@class
@extends {Store}
@see Store
@param {number} id
@param {Object} storeProtected
@param {string | Array} namespace | [
"Subscription",
"Constructor",
"is",
"used",
"in",
"the",
"Store",
"Class",
"to",
"create",
"Subscriptions",
"to",
"state"
] | daaeff958c261565e2f8bd666ffdeb513086aac2 | https://github.com/alojs/alo/blob/daaeff958c261565e2f8bd666ffdeb513086aac2/lib/subscription/subscription.js#L26-L49 | train |
forest-fire/firemodel | dist/cjs/src/Watch/createWatchEvent.js | createWatchEvent | function createWatchEvent(type, record, event) {
const payload = Object.assign({ type, key: record.id, modelName: record.modelName, pluralName: record.pluralName, modelConstructor: record.modelConstructor, dynamicPathProperties: record.dynamicPathComponents, compositeKey: record.compositeKey, dbPath: record.dbPath, localPath: record.localPath || "", localPostfix: record.META.localPostfix }, event);
return payload;
} | javascript | function createWatchEvent(type, record, event) {
const payload = Object.assign({ type, key: record.id, modelName: record.modelName, pluralName: record.pluralName, modelConstructor: record.modelConstructor, dynamicPathProperties: record.dynamicPathComponents, compositeKey: record.compositeKey, dbPath: record.dbPath, localPath: record.localPath || "", localPostfix: record.META.localPostfix }, event);
return payload;
} | [
"function",
"createWatchEvent",
"(",
"type",
",",
"record",
",",
"event",
")",
"{",
"const",
"payload",
"=",
"Object",
".",
"assign",
"(",
"{",
"type",
",",
"key",
":",
"record",
".",
"id",
",",
"modelName",
":",
"record",
".",
"modelName",
",",
"pluralName",
":",
"record",
".",
"pluralName",
",",
"modelConstructor",
":",
"record",
".",
"modelConstructor",
",",
"dynamicPathProperties",
":",
"record",
".",
"dynamicPathComponents",
",",
"compositeKey",
":",
"record",
".",
"compositeKey",
",",
"dbPath",
":",
"record",
".",
"dbPath",
",",
"localPath",
":",
"record",
".",
"localPath",
"||",
"\"\"",
",",
"localPostfix",
":",
"record",
".",
"META",
".",
"localPostfix",
"}",
",",
"event",
")",
";",
"return",
"payload",
";",
"}"
] | expands a locally originated event into a full featured
dispatch event with desired META from the model | [
"expands",
"a",
"locally",
"originated",
"event",
"into",
"a",
"full",
"featured",
"dispatch",
"event",
"with",
"desired",
"META",
"from",
"the",
"model"
] | 381b4c9d6df5db47924ef406243f6e8669a1f03e | https://github.com/forest-fire/firemodel/blob/381b4c9d6df5db47924ef406243f6e8669a1f03e/dist/cjs/src/Watch/createWatchEvent.js#L7-L10 | train |
forest-fire/firemodel | dist/cjs/src/decorators/model-meta/property-store.js | addPropertyToModelMeta | function addPropertyToModelMeta(modelName, property, meta) {
if (!exports.propertiesByModel[modelName]) {
exports.propertiesByModel[modelName] = {};
}
// TODO: investigate why we need to genericize to model (from <T>)
exports.propertiesByModel[modelName][property] = meta;
} | javascript | function addPropertyToModelMeta(modelName, property, meta) {
if (!exports.propertiesByModel[modelName]) {
exports.propertiesByModel[modelName] = {};
}
// TODO: investigate why we need to genericize to model (from <T>)
exports.propertiesByModel[modelName][property] = meta;
} | [
"function",
"addPropertyToModelMeta",
"(",
"modelName",
",",
"property",
",",
"meta",
")",
"{",
"if",
"(",
"!",
"exports",
".",
"propertiesByModel",
"[",
"modelName",
"]",
")",
"{",
"exports",
".",
"propertiesByModel",
"[",
"modelName",
"]",
"=",
"{",
"}",
";",
"}",
"exports",
".",
"propertiesByModel",
"[",
"modelName",
"]",
"[",
"property",
"]",
"=",
"meta",
";",
"}"
] | allows the addition of meta information to be added to a model's properties | [
"allows",
"the",
"addition",
"of",
"meta",
"information",
"to",
"be",
"added",
"to",
"a",
"model",
"s",
"properties"
] | 381b4c9d6df5db47924ef406243f6e8669a1f03e | https://github.com/forest-fire/firemodel/blob/381b4c9d6df5db47924ef406243f6e8669a1f03e/dist/cjs/src/decorators/model-meta/property-store.js#L13-L19 | train |
forest-fire/firemodel | dist/cjs/src/decorators/model-meta/property-store.js | getModelProperty | function getModelProperty(model) {
const className = model.constructor.name;
const propsForModel = getProperties(model);
return (prop) => {
return propsForModel.find(value => {
return value.property === prop;
});
};
} | javascript | function getModelProperty(model) {
const className = model.constructor.name;
const propsForModel = getProperties(model);
return (prop) => {
return propsForModel.find(value => {
return value.property === prop;
});
};
} | [
"function",
"getModelProperty",
"(",
"model",
")",
"{",
"const",
"className",
"=",
"model",
".",
"constructor",
".",
"name",
";",
"const",
"propsForModel",
"=",
"getProperties",
"(",
"model",
")",
";",
"return",
"(",
"prop",
")",
"=>",
"{",
"return",
"propsForModel",
".",
"find",
"(",
"value",
"=>",
"{",
"return",
"value",
".",
"property",
"===",
"prop",
";",
"}",
")",
";",
"}",
";",
"}"
] | lookup meta data for schema properties | [
"lookup",
"meta",
"data",
"for",
"schema",
"properties"
] | 381b4c9d6df5db47924ef406243f6e8669a1f03e | https://github.com/forest-fire/firemodel/blob/381b4c9d6df5db47924ef406243f6e8669a1f03e/dist/cjs/src/decorators/model-meta/property-store.js#L22-L30 | train |
forest-fire/firemodel | dist/cjs/src/decorators/model-meta/property-store.js | getProperties | function getProperties(model) {
const modelName = model.constructor.name;
const properties = typed_conversions_1.hashToArray(exports.propertiesByModel[modelName], "property") || [];
let parent = Object.getPrototypeOf(model.constructor);
while (parent.name) {
const subClass = new parent();
const subClassName = subClass.constructor.name;
properties.push(...typed_conversions_1.hashToArray(exports.propertiesByModel[subClassName], "property"));
parent = Object.getPrototypeOf(subClass.constructor);
}
return properties;
} | javascript | function getProperties(model) {
const modelName = model.constructor.name;
const properties = typed_conversions_1.hashToArray(exports.propertiesByModel[modelName], "property") || [];
let parent = Object.getPrototypeOf(model.constructor);
while (parent.name) {
const subClass = new parent();
const subClassName = subClass.constructor.name;
properties.push(...typed_conversions_1.hashToArray(exports.propertiesByModel[subClassName], "property"));
parent = Object.getPrototypeOf(subClass.constructor);
}
return properties;
} | [
"function",
"getProperties",
"(",
"model",
")",
"{",
"const",
"modelName",
"=",
"model",
".",
"constructor",
".",
"name",
";",
"const",
"properties",
"=",
"typed_conversions_1",
".",
"hashToArray",
"(",
"exports",
".",
"propertiesByModel",
"[",
"modelName",
"]",
",",
"\"property\"",
")",
"||",
"[",
"]",
";",
"let",
"parent",
"=",
"Object",
".",
"getPrototypeOf",
"(",
"model",
".",
"constructor",
")",
";",
"while",
"(",
"parent",
".",
"name",
")",
"{",
"const",
"subClass",
"=",
"new",
"parent",
"(",
")",
";",
"const",
"subClassName",
"=",
"subClass",
".",
"constructor",
".",
"name",
";",
"properties",
".",
"push",
"(",
"...",
"typed_conversions_1",
".",
"hashToArray",
"(",
"exports",
".",
"propertiesByModel",
"[",
"subClassName",
"]",
",",
"\"property\"",
")",
")",
";",
"parent",
"=",
"Object",
".",
"getPrototypeOf",
"(",
"subClass",
".",
"constructor",
")",
";",
"}",
"return",
"properties",
";",
"}"
] | Gets all the properties for a given model
@param modelConstructor the schema object which is being looked up | [
"Gets",
"all",
"the",
"properties",
"for",
"a",
"given",
"model"
] | 381b4c9d6df5db47924ef406243f6e8669a1f03e | https://github.com/forest-fire/firemodel/blob/381b4c9d6df5db47924ef406243f6e8669a1f03e/dist/cjs/src/decorators/model-meta/property-store.js#L37-L48 | train |
forest-fire/firemodel | dist/cjs/CompositeKey.js | createCompositeKeyString | function createCompositeKeyString(rec) {
const cKey = createCompositeKey(rec);
return rec.hasDynamicPath
? cKey.id +
Object.keys(cKey)
.filter(k => k !== "id")
.map(k => `::${k}:${cKey[k]}`)
: rec.id;
} | javascript | function createCompositeKeyString(rec) {
const cKey = createCompositeKey(rec);
return rec.hasDynamicPath
? cKey.id +
Object.keys(cKey)
.filter(k => k !== "id")
.map(k => `::${k}:${cKey[k]}`)
: rec.id;
} | [
"function",
"createCompositeKeyString",
"(",
"rec",
")",
"{",
"const",
"cKey",
"=",
"createCompositeKey",
"(",
"rec",
")",
";",
"return",
"rec",
".",
"hasDynamicPath",
"?",
"cKey",
".",
"id",
"+",
"Object",
".",
"keys",
"(",
"cKey",
")",
".",
"filter",
"(",
"k",
"=>",
"k",
"!==",
"\"id\"",
")",
".",
"map",
"(",
"k",
"=>",
"`",
"${",
"k",
"}",
"${",
"cKey",
"[",
"k",
"]",
"}",
"`",
")",
":",
"rec",
".",
"id",
";",
"}"
] | Creates a string based composite key if the passed in record
has dynamic path segments; if not it will just return the "id" | [
"Creates",
"a",
"string",
"based",
"composite",
"key",
"if",
"the",
"passed",
"in",
"record",
"has",
"dynamic",
"path",
"segments",
";",
"if",
"not",
"it",
"will",
"just",
"return",
"the",
"id"
] | 381b4c9d6df5db47924ef406243f6e8669a1f03e | https://github.com/forest-fire/firemodel/blob/381b4c9d6df5db47924ef406243f6e8669a1f03e/dist/cjs/CompositeKey.js#L12-L20 | train |
forest-fire/firemodel | dist/cjs/Mock/mockProperties.js | mockProperties | function mockProperties(db, config = { relationshipBehavior: "ignore" }, exceptions) {
return async (record) => {
const meta = ModelMeta_1.getModelMeta(record);
const props = meta.properties;
const recProps = {};
// below is needed to import faker library
props.map(prop => {
const p = prop.property;
recProps[p] = mockValue_1.default(db, prop);
});
const finalized = Object.assign({}, recProps, exceptions);
// write to mock db and retain a reference to same model
record = await __1.Record.add(record.modelConstructor, finalized, {
silent: true
});
return record;
};
} | javascript | function mockProperties(db, config = { relationshipBehavior: "ignore" }, exceptions) {
return async (record) => {
const meta = ModelMeta_1.getModelMeta(record);
const props = meta.properties;
const recProps = {};
// below is needed to import faker library
props.map(prop => {
const p = prop.property;
recProps[p] = mockValue_1.default(db, prop);
});
const finalized = Object.assign({}, recProps, exceptions);
// write to mock db and retain a reference to same model
record = await __1.Record.add(record.modelConstructor, finalized, {
silent: true
});
return record;
};
} | [
"function",
"mockProperties",
"(",
"db",
",",
"config",
"=",
"{",
"relationshipBehavior",
":",
"\"ignore\"",
"}",
",",
"exceptions",
")",
"{",
"return",
"async",
"(",
"record",
")",
"=>",
"{",
"const",
"meta",
"=",
"ModelMeta_1",
".",
"getModelMeta",
"(",
"record",
")",
";",
"const",
"props",
"=",
"meta",
".",
"properties",
";",
"const",
"recProps",
"=",
"{",
"}",
";",
"props",
".",
"map",
"(",
"prop",
"=>",
"{",
"const",
"p",
"=",
"prop",
".",
"property",
";",
"recProps",
"[",
"p",
"]",
"=",
"mockValue_1",
".",
"default",
"(",
"db",
",",
"prop",
")",
";",
"}",
")",
";",
"const",
"finalized",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"recProps",
",",
"exceptions",
")",
";",
"record",
"=",
"await",
"__1",
".",
"Record",
".",
"add",
"(",
"record",
".",
"modelConstructor",
",",
"finalized",
",",
"{",
"silent",
":",
"true",
"}",
")",
";",
"return",
"record",
";",
"}",
";",
"}"
] | adds mock values for all the properties on a given model | [
"adds",
"mock",
"values",
"for",
"all",
"the",
"properties",
"on",
"a",
"given",
"model"
] | 381b4c9d6df5db47924ef406243f6e8669a1f03e | https://github.com/forest-fire/firemodel/blob/381b4c9d6df5db47924ef406243f6e8669a1f03e/dist/cjs/Mock/mockProperties.js#L10-L27 | train |
forest-fire/firemodel | dist/cjs/src/decorators/model-meta/relationship-store.js | addRelationshipToModelMeta | function addRelationshipToModelMeta(modelName, property, meta) {
if (!exports.relationshipsByModel[modelName]) {
exports.relationshipsByModel[modelName] = {};
}
// TODO: investigate why we need to genericize to model (from <T>)
exports.relationshipsByModel[modelName][property] = meta;
} | javascript | function addRelationshipToModelMeta(modelName, property, meta) {
if (!exports.relationshipsByModel[modelName]) {
exports.relationshipsByModel[modelName] = {};
}
// TODO: investigate why we need to genericize to model (from <T>)
exports.relationshipsByModel[modelName][property] = meta;
} | [
"function",
"addRelationshipToModelMeta",
"(",
"modelName",
",",
"property",
",",
"meta",
")",
"{",
"if",
"(",
"!",
"exports",
".",
"relationshipsByModel",
"[",
"modelName",
"]",
")",
"{",
"exports",
".",
"relationshipsByModel",
"[",
"modelName",
"]",
"=",
"{",
"}",
";",
"}",
"exports",
".",
"relationshipsByModel",
"[",
"modelName",
"]",
"[",
"property",
"]",
"=",
"meta",
";",
"}"
] | allows the addition of meta information to be added to a model's relationships | [
"allows",
"the",
"addition",
"of",
"meta",
"information",
"to",
"be",
"added",
"to",
"a",
"model",
"s",
"relationships"
] | 381b4c9d6df5db47924ef406243f6e8669a1f03e | https://github.com/forest-fire/firemodel/blob/381b4c9d6df5db47924ef406243f6e8669a1f03e/dist/cjs/src/decorators/model-meta/relationship-store.js#L6-L12 | train |
forest-fire/firemodel | dist/cjs/src/decorators/model-meta/relationship-store.js | getRelationships | function getRelationships(model) {
const modelName = model.constructor.name;
const properties = typed_conversions_1.hashToArray(exports.relationshipsByModel[modelName], "property") || [];
let parent = Object.getPrototypeOf(model.constructor);
while (parent.name) {
const subClass = new parent();
const subClassName = subClass.constructor.name;
properties.push(...typed_conversions_1.hashToArray(exports.relationshipsByModel[subClassName], "property"));
parent = Object.getPrototypeOf(subClass.constructor);
}
return properties;
} | javascript | function getRelationships(model) {
const modelName = model.constructor.name;
const properties = typed_conversions_1.hashToArray(exports.relationshipsByModel[modelName], "property") || [];
let parent = Object.getPrototypeOf(model.constructor);
while (parent.name) {
const subClass = new parent();
const subClassName = subClass.constructor.name;
properties.push(...typed_conversions_1.hashToArray(exports.relationshipsByModel[subClassName], "property"));
parent = Object.getPrototypeOf(subClass.constructor);
}
return properties;
} | [
"function",
"getRelationships",
"(",
"model",
")",
"{",
"const",
"modelName",
"=",
"model",
".",
"constructor",
".",
"name",
";",
"const",
"properties",
"=",
"typed_conversions_1",
".",
"hashToArray",
"(",
"exports",
".",
"relationshipsByModel",
"[",
"modelName",
"]",
",",
"\"property\"",
")",
"||",
"[",
"]",
";",
"let",
"parent",
"=",
"Object",
".",
"getPrototypeOf",
"(",
"model",
".",
"constructor",
")",
";",
"while",
"(",
"parent",
".",
"name",
")",
"{",
"const",
"subClass",
"=",
"new",
"parent",
"(",
")",
";",
"const",
"subClassName",
"=",
"subClass",
".",
"constructor",
".",
"name",
";",
"properties",
".",
"push",
"(",
"...",
"typed_conversions_1",
".",
"hashToArray",
"(",
"exports",
".",
"relationshipsByModel",
"[",
"subClassName",
"]",
",",
"\"property\"",
")",
")",
";",
"parent",
"=",
"Object",
".",
"getPrototypeOf",
"(",
"subClass",
".",
"constructor",
")",
";",
"}",
"return",
"properties",
";",
"}"
] | Gets all the relationships for a given model | [
"Gets",
"all",
"the",
"relationships",
"for",
"a",
"given",
"model"
] | 381b4c9d6df5db47924ef406243f6e8669a1f03e | https://github.com/forest-fire/firemodel/blob/381b4c9d6df5db47924ef406243f6e8669a1f03e/dist/cjs/src/decorators/model-meta/relationship-store.js#L33-L44 | train |
nodeGame/ultimatum-game | auth/auth.js | authPlayers | function authPlayers(channel, info) {
var code, player, token;
playerId = info.cookies.player;
token = info.cookies.token;
// Code not existing.
if (!code) {
console.log('not existing token: ', token);
return false;
}
if (code.checkedOut) {
console.log('token was already checked out: ', token);
return false;
}
// Code in use.
// usage is for LOCAL check, IsUsed for MTURK
if (code.valid === false) {
if (code.disconnected) {
return true;
}
else {
console.log('token already in use: ', token);
return false;
}
}
// Client Authorized
return true;
} | javascript | function authPlayers(channel, info) {
var code, player, token;
playerId = info.cookies.player;
token = info.cookies.token;
// Code not existing.
if (!code) {
console.log('not existing token: ', token);
return false;
}
if (code.checkedOut) {
console.log('token was already checked out: ', token);
return false;
}
// Code in use.
// usage is for LOCAL check, IsUsed for MTURK
if (code.valid === false) {
if (code.disconnected) {
return true;
}
else {
console.log('token already in use: ', token);
return false;
}
}
// Client Authorized
return true;
} | [
"function",
"authPlayers",
"(",
"channel",
",",
"info",
")",
"{",
"var",
"code",
",",
"player",
",",
"token",
";",
"playerId",
"=",
"info",
".",
"cookies",
".",
"player",
";",
"token",
"=",
"info",
".",
"cookies",
".",
"token",
";",
"if",
"(",
"!",
"code",
")",
"{",
"console",
".",
"log",
"(",
"'not existing token: '",
",",
"token",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"code",
".",
"checkedOut",
")",
"{",
"console",
".",
"log",
"(",
"'token was already checked out: '",
",",
"token",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"code",
".",
"valid",
"===",
"false",
")",
"{",
"if",
"(",
"code",
".",
"disconnected",
")",
"{",
"return",
"true",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'token already in use: '",
",",
"token",
")",
";",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Creating an authorization function for the players. This is executed before the client the PCONNECT listener. Here direct messages to the client can be sent only using his socketId property, since no clientId has been created yet. | [
"Creating",
"an",
"authorization",
"function",
"for",
"the",
"players",
".",
"This",
"is",
"executed",
"before",
"the",
"client",
"the",
"PCONNECT",
"listener",
".",
"Here",
"direct",
"messages",
"to",
"the",
"client",
"can",
"be",
"sent",
"only",
"using",
"his",
"socketId",
"property",
"since",
"no",
"clientId",
"has",
"been",
"created",
"yet",
"."
] | b07351612df6d6759bf3563db36855ea3cc4c800 | https://github.com/nodeGame/ultimatum-game/blob/b07351612df6d6759bf3563db36855ea3cc4c800/auth/auth.js#L17-L49 | train |
nodeGame/ultimatum-game | auth/auth.js | idGen | function idGen(channel, info) {
var cid = channel.registry.generateClientId();
var cookies;
var ids;
// Return the id only if token was validated.
// More checks could be done here to ensure that token is unique in ids.
ids = channel.registry.getIds();
cookies = info.cookies;
if (cookies.player) {
if (!ids[cookies.player] || ids[cookies.player].disconnected) {
return cookies.player;
}
else {
console.log("already in ids", cookies.player);
return false;
}
}
} | javascript | function idGen(channel, info) {
var cid = channel.registry.generateClientId();
var cookies;
var ids;
// Return the id only if token was validated.
// More checks could be done here to ensure that token is unique in ids.
ids = channel.registry.getIds();
cookies = info.cookies;
if (cookies.player) {
if (!ids[cookies.player] || ids[cookies.player].disconnected) {
return cookies.player;
}
else {
console.log("already in ids", cookies.player);
return false;
}
}
} | [
"function",
"idGen",
"(",
"channel",
",",
"info",
")",
"{",
"var",
"cid",
"=",
"channel",
".",
"registry",
".",
"generateClientId",
"(",
")",
";",
"var",
"cookies",
";",
"var",
"ids",
";",
"ids",
"=",
"channel",
".",
"registry",
".",
"getIds",
"(",
")",
";",
"cookies",
"=",
"info",
".",
"cookies",
";",
"if",
"(",
"cookies",
".",
"player",
")",
"{",
"if",
"(",
"!",
"ids",
"[",
"cookies",
".",
"player",
"]",
"||",
"ids",
"[",
"cookies",
".",
"player",
"]",
".",
"disconnected",
")",
"{",
"return",
"cookies",
".",
"player",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"\"already in ids\"",
",",
"cookies",
".",
"player",
")",
";",
"return",
"false",
";",
"}",
"}",
"}"
] | Assigns Player Ids based on cookie token. | [
"Assigns",
"Player",
"Ids",
"based",
"on",
"cookie",
"token",
"."
] | b07351612df6d6759bf3563db36855ea3cc4c800 | https://github.com/nodeGame/ultimatum-game/blob/b07351612df6d6759bf3563db36855ea3cc4c800/auth/auth.js#L52-L72 | train |
kartotherian/server | static/main.js | bracketDevicePixelRatio | function bracketDevicePixelRatio() {
var i, scale,
brackets = [ 1, 1.3, 1.5, 2, 2.6, 3 ],
baseRatio = window.devicePixelRatio || 1;
for ( i = 0; i < brackets.length; i++ ) {
scale = brackets[ i ];
if ( scale >= baseRatio || ( baseRatio - scale ) < 0.1 ) {
return scale;
}
}
return brackets[ brackets.length - 1 ];
} | javascript | function bracketDevicePixelRatio() {
var i, scale,
brackets = [ 1, 1.3, 1.5, 2, 2.6, 3 ],
baseRatio = window.devicePixelRatio || 1;
for ( i = 0; i < brackets.length; i++ ) {
scale = brackets[ i ];
if ( scale >= baseRatio || ( baseRatio - scale ) < 0.1 ) {
return scale;
}
}
return brackets[ brackets.length - 1 ];
} | [
"function",
"bracketDevicePixelRatio",
"(",
")",
"{",
"var",
"i",
",",
"scale",
",",
"brackets",
"=",
"[",
"1",
",",
"1.3",
",",
"1.5",
",",
"2",
",",
"2.6",
",",
"3",
"]",
",",
"baseRatio",
"=",
"window",
".",
"devicePixelRatio",
"||",
"1",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"brackets",
".",
"length",
";",
"i",
"++",
")",
"{",
"scale",
"=",
"brackets",
"[",
"i",
"]",
";",
"if",
"(",
"scale",
">=",
"baseRatio",
"||",
"(",
"baseRatio",
"-",
"scale",
")",
"<",
"0.1",
")",
"{",
"return",
"scale",
";",
"}",
"}",
"return",
"brackets",
"[",
"brackets",
".",
"length",
"-",
"1",
"]",
";",
"}"
] | eslint-disable-line func-names Allow user to change style via the ?s=xxx URL parameter Uses "osm-intl" as the default style | [
"eslint",
"-",
"disable",
"-",
"line",
"func",
"-",
"names",
"Allow",
"user",
"to",
"change",
"style",
"via",
"the",
"?s",
"=",
"xxx",
"URL",
"parameter",
"Uses",
"osm",
"-",
"intl",
"as",
"the",
"default",
"style"
] | 490b558979199c7bba11aaac269d9e2122f0c819 | https://github.com/kartotherian/server/blob/490b558979199c7bba11aaac269d9e2122f0c819/static/main.js#L7-L20 | train |
kartotherian/server | static/main.js | setupMap | function setupMap( config ) {
var layerSettings, defaultSettings,
query = '',
matchLang = location.search.match( /lang=([-_a-zA-Z]+)/ );
defaultSettings = {
maxzoom: 18,
// TODO: This is UI text, and needs to be translatable.
attribution: 'Map data © <a href="http://openstreetmap.org/copyright">OpenStreetMap contributors</a>'
};
if ( matchLang ) {
query = '?lang=' + matchLang[ 1 ];
}
config = config || {};
layerSettings = {
maxZoom: config.maxzoom !== undefined ? config.maxzoom : defaultSettings.maxzoom,
// TODO: This is UI text, and needs to be translatable.
attribution: config.attribution !== undefined ? config.attribution : defaultSettings.attribution,
id: 'map-01'
};
// Add a map layer
L.tileLayer( style + '/{z}/{x}/{y}' + scalex + '.png' + query, layerSettings ).addTo( map );
// Add a km/miles scale
L.control.scale().addTo( map );
// Update the zoom level label
map.on( 'zoomend', function () {
document.getElementById( 'zoom-level' ).innerHTML = 'Zoom Level: ' + map.getZoom();
} );
// Add current location to URL hash
new L.Hash( map ); // eslint-disable-line no-new
} | javascript | function setupMap( config ) {
var layerSettings, defaultSettings,
query = '',
matchLang = location.search.match( /lang=([-_a-zA-Z]+)/ );
defaultSettings = {
maxzoom: 18,
// TODO: This is UI text, and needs to be translatable.
attribution: 'Map data © <a href="http://openstreetmap.org/copyright">OpenStreetMap contributors</a>'
};
if ( matchLang ) {
query = '?lang=' + matchLang[ 1 ];
}
config = config || {};
layerSettings = {
maxZoom: config.maxzoom !== undefined ? config.maxzoom : defaultSettings.maxzoom,
// TODO: This is UI text, and needs to be translatable.
attribution: config.attribution !== undefined ? config.attribution : defaultSettings.attribution,
id: 'map-01'
};
// Add a map layer
L.tileLayer( style + '/{z}/{x}/{y}' + scalex + '.png' + query, layerSettings ).addTo( map );
// Add a km/miles scale
L.control.scale().addTo( map );
// Update the zoom level label
map.on( 'zoomend', function () {
document.getElementById( 'zoom-level' ).innerHTML = 'Zoom Level: ' + map.getZoom();
} );
// Add current location to URL hash
new L.Hash( map ); // eslint-disable-line no-new
} | [
"function",
"setupMap",
"(",
"config",
")",
"{",
"var",
"layerSettings",
",",
"defaultSettings",
",",
"query",
"=",
"''",
",",
"matchLang",
"=",
"location",
".",
"search",
".",
"match",
"(",
"/",
"lang=([-_a-zA-Z]+)",
"/",
")",
";",
"defaultSettings",
"=",
"{",
"maxzoom",
":",
"18",
",",
"attribution",
":",
"'Map data © <a href=\"http://openstreetmap.org/copyright\">OpenStreetMap contributors</a>'",
"}",
";",
"if",
"(",
"matchLang",
")",
"{",
"query",
"=",
"'?lang='",
"+",
"matchLang",
"[",
"1",
"]",
";",
"}",
"config",
"=",
"config",
"||",
"{",
"}",
";",
"layerSettings",
"=",
"{",
"maxZoom",
":",
"config",
".",
"maxzoom",
"!==",
"undefined",
"?",
"config",
".",
"maxzoom",
":",
"defaultSettings",
".",
"maxzoom",
",",
"attribution",
":",
"config",
".",
"attribution",
"!==",
"undefined",
"?",
"config",
".",
"attribution",
":",
"defaultSettings",
".",
"attribution",
",",
"id",
":",
"'map-01'",
"}",
";",
"L",
".",
"tileLayer",
"(",
"style",
"+",
"'/{z}/{x}/{y}'",
"+",
"scalex",
"+",
"'.png'",
"+",
"query",
",",
"layerSettings",
")",
".",
"addTo",
"(",
"map",
")",
";",
"L",
".",
"control",
".",
"scale",
"(",
")",
".",
"addTo",
"(",
"map",
")",
";",
"map",
".",
"on",
"(",
"'zoomend'",
",",
"function",
"(",
")",
"{",
"document",
".",
"getElementById",
"(",
"'zoom-level'",
")",
".",
"innerHTML",
"=",
"'Zoom Level: '",
"+",
"map",
".",
"getZoom",
"(",
")",
";",
"}",
")",
";",
"new",
"L",
".",
"Hash",
"(",
"map",
")",
";",
"}"
] | Finishes setting up the map
@param {Object|null} config Config object
@param {string} [config.attribution] Attribution text to show in footer; see below for default
@param {number} [config.maxzoom=18] Maximum zoom level | [
"Finishes",
"setting",
"up",
"the",
"map"
] | 490b558979199c7bba11aaac269d9e2122f0c819 | https://github.com/kartotherian/server/blob/490b558979199c7bba11aaac269d9e2122f0c819/static/main.js#L36-L75 | train |
primus/mirage | index.js | gen | function gen(spark, fn) {
crypto.randomBytes(8, function generated(err, buff) {
if (err) return fn(err);
fn(undefined, buff.toString('hex'));
});
} | javascript | function gen(spark, fn) {
crypto.randomBytes(8, function generated(err, buff) {
if (err) return fn(err);
fn(undefined, buff.toString('hex'));
});
} | [
"function",
"gen",
"(",
"spark",
",",
"fn",
")",
"{",
"crypto",
".",
"randomBytes",
"(",
"8",
",",
"function",
"generated",
"(",
"err",
",",
"buff",
")",
"{",
"if",
"(",
"err",
")",
"return",
"fn",
"(",
"err",
")",
";",
"fn",
"(",
"undefined",
",",
"buff",
".",
"toString",
"(",
"'hex'",
")",
")",
";",
"}",
")",
";",
"}"
] | Generator of session ids. It should call the callback with a string that
should be used as session id. If a generation failed you should set an
error as first argument in the callback.
This function will only be called if there is no id sent with the request.
@param {Spark} spark The incoming connection.
@param {Function} fn Completion callback.
@api public | [
"Generator",
"of",
"session",
"ids",
".",
"It",
"should",
"call",
"the",
"callback",
"with",
"a",
"string",
"that",
"should",
"be",
"used",
"as",
"session",
"id",
".",
"If",
"a",
"generation",
"failed",
"you",
"should",
"set",
"an",
"error",
"as",
"first",
"argument",
"in",
"the",
"callback",
"."
] | 231c1de1d94593baa0a8ed3e8147f725cbaef36b | https://github.com/primus/mirage/blob/231c1de1d94593baa0a8ed3e8147f725cbaef36b/index.js#L113-L119 | train |
hsnaydd/validetta | dist/validetta.js | function( tmp ) {
var _length = tmp.val.length;
return _length === 0 || _length >= tmp.arg || messages.minLength.replace( '{count}', tmp.arg );
} | javascript | function( tmp ) {
var _length = tmp.val.length;
return _length === 0 || _length >= tmp.arg || messages.minLength.replace( '{count}', tmp.arg );
} | [
"function",
"(",
"tmp",
")",
"{",
"var",
"_length",
"=",
"tmp",
".",
"val",
".",
"length",
";",
"return",
"_length",
"===",
"0",
"||",
"_length",
">=",
"tmp",
".",
"arg",
"||",
"messages",
".",
"minLength",
".",
"replace",
"(",
"'{count}'",
",",
"tmp",
".",
"arg",
")",
";",
"}"
] | Minimum length check | [
"Minimum",
"length",
"check"
] | f712b7375e1465bfc687a8c6fc93ea700cb590e3 | https://github.com/hsnaydd/validetta/blob/f712b7375e1465bfc687a8c6fc93ea700cb590e3/dist/validetta.js#L100-L103 | train |
|
hsnaydd/validetta | dist/validetta.js | function( tmp ) {
return tmp.val.length <= tmp.arg || messages.maxLength.replace( '{count}', tmp.arg );
} | javascript | function( tmp ) {
return tmp.val.length <= tmp.arg || messages.maxLength.replace( '{count}', tmp.arg );
} | [
"function",
"(",
"tmp",
")",
"{",
"return",
"tmp",
".",
"val",
".",
"length",
"<=",
"tmp",
".",
"arg",
"||",
"messages",
".",
"maxLength",
".",
"replace",
"(",
"'{count}'",
",",
"tmp",
".",
"arg",
")",
";",
"}"
] | Maximum lenght check | [
"Maximum",
"lenght",
"check"
] | f712b7375e1465bfc687a8c6fc93ea700cb590e3 | https://github.com/hsnaydd/validetta/blob/f712b7375e1465bfc687a8c6fc93ea700cb590e3/dist/validetta.js#L105-L107 | train |
|
hsnaydd/validetta | dist/validetta.js | function( tmp ) {
if ( tmp.val === '' ) return true; // allow empty because empty check does by required metheod
var reg, cardNumber, pos, digit, i, sub_total, sum = 0, strlen;
reg = new RegExp( /[^0-9]+/g );
cardNumber = tmp.val.replace( reg, '' );
strlen = cardNumber.length;
if( strlen < 13 ) return messages.creditCard;
for( i=0 ; i < strlen ; i++ ) {
pos = strlen - i;
digit = parseInt( cardNumber.substring( pos - 1, pos ), 10 );
if( i % 2 === 1 ) {
sub_total = digit * 2 ;
if( sub_total > 9 ) {
sub_total = 1 + ( sub_total - 10 );
}
} else {
sub_total = digit ;
}
sum += sub_total ;
}
if( sum > 0 && sum % 10 === 0 ) return true;
return messages.creditCard;
} | javascript | function( tmp ) {
if ( tmp.val === '' ) return true; // allow empty because empty check does by required metheod
var reg, cardNumber, pos, digit, i, sub_total, sum = 0, strlen;
reg = new RegExp( /[^0-9]+/g );
cardNumber = tmp.val.replace( reg, '' );
strlen = cardNumber.length;
if( strlen < 13 ) return messages.creditCard;
for( i=0 ; i < strlen ; i++ ) {
pos = strlen - i;
digit = parseInt( cardNumber.substring( pos - 1, pos ), 10 );
if( i % 2 === 1 ) {
sub_total = digit * 2 ;
if( sub_total > 9 ) {
sub_total = 1 + ( sub_total - 10 );
}
} else {
sub_total = digit ;
}
sum += sub_total ;
}
if( sum > 0 && sum % 10 === 0 ) return true;
return messages.creditCard;
} | [
"function",
"(",
"tmp",
")",
"{",
"if",
"(",
"tmp",
".",
"val",
"===",
"''",
")",
"return",
"true",
";",
"var",
"reg",
",",
"cardNumber",
",",
"pos",
",",
"digit",
",",
"i",
",",
"sub_total",
",",
"sum",
"=",
"0",
",",
"strlen",
";",
"reg",
"=",
"new",
"RegExp",
"(",
"/",
"[^0-9]+",
"/",
"g",
")",
";",
"cardNumber",
"=",
"tmp",
".",
"val",
".",
"replace",
"(",
"reg",
",",
"''",
")",
";",
"strlen",
"=",
"cardNumber",
".",
"length",
";",
"if",
"(",
"strlen",
"<",
"13",
")",
"return",
"messages",
".",
"creditCard",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"strlen",
";",
"i",
"++",
")",
"{",
"pos",
"=",
"strlen",
"-",
"i",
";",
"digit",
"=",
"parseInt",
"(",
"cardNumber",
".",
"substring",
"(",
"pos",
"-",
"1",
",",
"pos",
")",
",",
"10",
")",
";",
"if",
"(",
"i",
"%",
"2",
"===",
"1",
")",
"{",
"sub_total",
"=",
"digit",
"*",
"2",
";",
"if",
"(",
"sub_total",
">",
"9",
")",
"{",
"sub_total",
"=",
"1",
"+",
"(",
"sub_total",
"-",
"10",
")",
";",
"}",
"}",
"else",
"{",
"sub_total",
"=",
"digit",
";",
"}",
"sum",
"+=",
"sub_total",
";",
"}",
"if",
"(",
"sum",
">",
"0",
"&&",
"sum",
"%",
"10",
"===",
"0",
")",
"return",
"true",
";",
"return",
"messages",
".",
"creditCard",
";",
"}"
] | Credit Card Control
@from : http://af-design.com/blog/2010/08/18/validating-credit-card-numbers | [
"Credit",
"Card",
"Control"
] | f712b7375e1465bfc687a8c6fc93ea700cb590e3 | https://github.com/hsnaydd/validetta/blob/f712b7375e1465bfc687a8c6fc93ea700cb590e3/dist/validetta.js#L119-L141 | train |
|
hsnaydd/validetta | dist/validetta.js | function( tmp, self ) {
var _arg = self.options.validators.regExp[ tmp.arg ],
_reg = new RegExp( _arg.pattern );
return _reg.test( tmp.val ) || _arg.errorMessage;
} | javascript | function( tmp, self ) {
var _arg = self.options.validators.regExp[ tmp.arg ],
_reg = new RegExp( _arg.pattern );
return _reg.test( tmp.val ) || _arg.errorMessage;
} | [
"function",
"(",
"tmp",
",",
"self",
")",
"{",
"var",
"_arg",
"=",
"self",
".",
"options",
".",
"validators",
".",
"regExp",
"[",
"tmp",
".",
"arg",
"]",
",",
"_reg",
"=",
"new",
"RegExp",
"(",
"_arg",
".",
"pattern",
")",
";",
"return",
"_reg",
".",
"test",
"(",
"tmp",
".",
"val",
")",
"||",
"_arg",
".",
"errorMessage",
";",
"}"
] | Custom reg check | [
"Custom",
"reg",
"check"
] | f712b7375e1465bfc687a8c6fc93ea700cb590e3 | https://github.com/hsnaydd/validetta/blob/f712b7375e1465bfc687a8c6fc93ea700cb590e3/dist/validetta.js#L171-L175 | train |
|
hsnaydd/validetta | dist/validetta.js | function(){
var self = this; // stored this
// Handle submit event
$( this.form ).submit( function( e ) {
// fields to be controlled transferred to global variable
FIELDS = this.querySelectorAll('[data-validetta]');
return self.init( e );
});
// real-time option control
if( this.options.realTime === true ) {
// handle change event for form elements (without checkbox)
$( this.form ).find('[data-validetta]').not('[type=checkbox]').on( 'change', function( e ) {
// field to be controlled transferred to global variable
FIELDS = $( this );
return self.init( e );
});
// handle click event for checkboxes
$( this.form ).find('[data-validetta][type=checkbox]').on( 'click', function( e ) {
// fields to be controlled transferred to global variable
FIELDS = self.form.querySelectorAll('[data-validetta][type=checkbox][name="'+ this.name +'"]');
return self.init( e );
});
}
// handle <form> reset button to clear error messages
$( this.form ).on( 'reset', function() {
$( self.form.querySelectorAll( '.'+ self.options.errorClass +', .'+ self.options.validClass ) )
.removeClass( self.options.errorClass +' '+ self.options.validClass );
return self.reset();
});
} | javascript | function(){
var self = this; // stored this
// Handle submit event
$( this.form ).submit( function( e ) {
// fields to be controlled transferred to global variable
FIELDS = this.querySelectorAll('[data-validetta]');
return self.init( e );
});
// real-time option control
if( this.options.realTime === true ) {
// handle change event for form elements (without checkbox)
$( this.form ).find('[data-validetta]').not('[type=checkbox]').on( 'change', function( e ) {
// field to be controlled transferred to global variable
FIELDS = $( this );
return self.init( e );
});
// handle click event for checkboxes
$( this.form ).find('[data-validetta][type=checkbox]').on( 'click', function( e ) {
// fields to be controlled transferred to global variable
FIELDS = self.form.querySelectorAll('[data-validetta][type=checkbox][name="'+ this.name +'"]');
return self.init( e );
});
}
// handle <form> reset button to clear error messages
$( this.form ).on( 'reset', function() {
$( self.form.querySelectorAll( '.'+ self.options.errorClass +', .'+ self.options.validClass ) )
.removeClass( self.options.errorClass +' '+ self.options.validClass );
return self.reset();
});
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"$",
"(",
"this",
".",
"form",
")",
".",
"submit",
"(",
"function",
"(",
"e",
")",
"{",
"FIELDS",
"=",
"this",
".",
"querySelectorAll",
"(",
"'[data-validetta]'",
")",
";",
"return",
"self",
".",
"init",
"(",
"e",
")",
";",
"}",
")",
";",
"if",
"(",
"this",
".",
"options",
".",
"realTime",
"===",
"true",
")",
"{",
"$",
"(",
"this",
".",
"form",
")",
".",
"find",
"(",
"'[data-validetta]'",
")",
".",
"not",
"(",
"'[type=checkbox]'",
")",
".",
"on",
"(",
"'change'",
",",
"function",
"(",
"e",
")",
"{",
"FIELDS",
"=",
"$",
"(",
"this",
")",
";",
"return",
"self",
".",
"init",
"(",
"e",
")",
";",
"}",
")",
";",
"$",
"(",
"this",
".",
"form",
")",
".",
"find",
"(",
"'[data-validetta][type=checkbox]'",
")",
".",
"on",
"(",
"'click'",
",",
"function",
"(",
"e",
")",
"{",
"FIELDS",
"=",
"self",
".",
"form",
".",
"querySelectorAll",
"(",
"'[data-validetta][type=checkbox][name=\"'",
"+",
"this",
".",
"name",
"+",
"'\"]'",
")",
";",
"return",
"self",
".",
"init",
"(",
"e",
")",
";",
"}",
")",
";",
"}",
"$",
"(",
"this",
".",
"form",
")",
".",
"on",
"(",
"'reset'",
",",
"function",
"(",
")",
"{",
"$",
"(",
"self",
".",
"form",
".",
"querySelectorAll",
"(",
"'.'",
"+",
"self",
".",
"options",
".",
"errorClass",
"+",
"', .'",
"+",
"self",
".",
"options",
".",
"validClass",
")",
")",
".",
"removeClass",
"(",
"self",
".",
"options",
".",
"errorClass",
"+",
"' '",
"+",
"self",
".",
"options",
".",
"validClass",
")",
";",
"return",
"self",
".",
"reset",
"(",
")",
";",
"}",
")",
";",
"}"
] | This is the method of handling events
@return {mixed} | [
"This",
"is",
"the",
"method",
"of",
"handling",
"events"
] | f712b7375e1465bfc687a8c6fc93ea700cb590e3 | https://github.com/hsnaydd/validetta/blob/f712b7375e1465bfc687a8c6fc93ea700cb590e3/dist/validetta.js#L220-L249 | train |
|
hsnaydd/validetta | dist/validetta.js | function( e ) {
// Reset error windows from all elements
this.reset( FIELDS );
// Start control each elements
this.checkFields( e );
if( e.type !== 'submit' ) return; // if event type is not submit, break
// This is for when running remote request, return false and wait request response
else if ( this.handler === 'pending' ) return false;
// if event type is submit and handler is true, break submit and call onError() function
else if( this.handler === true ) { this.options.onError.call( this, e ); return false; }
else return this.options.onValid.call( this, e ); // if form is valid call onValid() function
} | javascript | function( e ) {
// Reset error windows from all elements
this.reset( FIELDS );
// Start control each elements
this.checkFields( e );
if( e.type !== 'submit' ) return; // if event type is not submit, break
// This is for when running remote request, return false and wait request response
else if ( this.handler === 'pending' ) return false;
// if event type is submit and handler is true, break submit and call onError() function
else if( this.handler === true ) { this.options.onError.call( this, e ); return false; }
else return this.options.onValid.call( this, e ); // if form is valid call onValid() function
} | [
"function",
"(",
"e",
")",
"{",
"this",
".",
"reset",
"(",
"FIELDS",
")",
";",
"this",
".",
"checkFields",
"(",
"e",
")",
";",
"if",
"(",
"e",
".",
"type",
"!==",
"'submit'",
")",
"return",
";",
"else",
"if",
"(",
"this",
".",
"handler",
"===",
"'pending'",
")",
"return",
"false",
";",
"else",
"if",
"(",
"this",
".",
"handler",
"===",
"true",
")",
"{",
"this",
".",
"options",
".",
"onError",
".",
"call",
"(",
"this",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"else",
"return",
"this",
".",
"options",
".",
"onValid",
".",
"call",
"(",
"this",
",",
"e",
")",
";",
"}"
] | In this method, fields are validated
@params {object} e : event object
@return {mixed} | [
"In",
"this",
"method",
"fields",
"are",
"validated"
] | f712b7375e1465bfc687a8c6fc93ea700cb590e3 | https://github.com/hsnaydd/validetta/blob/f712b7375e1465bfc687a8c6fc93ea700cb590e3/dist/validetta.js#L257-L268 | train |
|
hsnaydd/validetta | dist/validetta.js | function( el, e ) {
var ajaxOptions = {},
data = {},
fieldName = el.name || el.id;
if ( typeof this.remoteCache === 'undefined' ) this.remoteCache = {};
data[ fieldName ] = this.tmp.val; // Set data
// exends ajax options
ajaxOptions = $.extend( true, {}, {
data: data
}, this.options.validators.remote[ this.tmp.remote ] || {} );
// use $.param() function for generate specific cache key
var cacheKey = $.param( ajaxOptions );
// Check cache
var cache = this.remoteCache[ cacheKey ];
if ( typeof cache !== 'undefined' ) {
switch( cache.state ) {
case 'pending' : // pending means remote request not finished yet
this.handler = 'pending'; // update handler and cache event type
cache.event = e.type;
break;
case 'rejected' : // rejected means remote request could not be performed
e.preventDefault(); // we have to break submit because of throw error
throw new Error( cache.result.message );
case 'resolved' : // resolved means remote request has done
// Check to cache, if result is invalid, open an error window
if ( cache.result.valid === false ) {
this.addErrorClass( this.tmp.parent );
this.window.open.call( this, el, cache.result.message );
} else {
this.addValidClass( this.tmp.parent );
}
}
} else {
// Abort if previous ajax request still running
var _xhr = this.xhr[ fieldName ];
if ( typeof _xhr !== 'undefined' && _xhr.state() === 'pending' ) _xhr.abort();
// Start caching
cache = this.remoteCache[ cacheKey ] = { state : 'pending', event : e.type };
// make a remote request
this.remoteRequest( ajaxOptions, cache, el, fieldName );
}
} | javascript | function( el, e ) {
var ajaxOptions = {},
data = {},
fieldName = el.name || el.id;
if ( typeof this.remoteCache === 'undefined' ) this.remoteCache = {};
data[ fieldName ] = this.tmp.val; // Set data
// exends ajax options
ajaxOptions = $.extend( true, {}, {
data: data
}, this.options.validators.remote[ this.tmp.remote ] || {} );
// use $.param() function for generate specific cache key
var cacheKey = $.param( ajaxOptions );
// Check cache
var cache = this.remoteCache[ cacheKey ];
if ( typeof cache !== 'undefined' ) {
switch( cache.state ) {
case 'pending' : // pending means remote request not finished yet
this.handler = 'pending'; // update handler and cache event type
cache.event = e.type;
break;
case 'rejected' : // rejected means remote request could not be performed
e.preventDefault(); // we have to break submit because of throw error
throw new Error( cache.result.message );
case 'resolved' : // resolved means remote request has done
// Check to cache, if result is invalid, open an error window
if ( cache.result.valid === false ) {
this.addErrorClass( this.tmp.parent );
this.window.open.call( this, el, cache.result.message );
} else {
this.addValidClass( this.tmp.parent );
}
}
} else {
// Abort if previous ajax request still running
var _xhr = this.xhr[ fieldName ];
if ( typeof _xhr !== 'undefined' && _xhr.state() === 'pending' ) _xhr.abort();
// Start caching
cache = this.remoteCache[ cacheKey ] = { state : 'pending', event : e.type };
// make a remote request
this.remoteRequest( ajaxOptions, cache, el, fieldName );
}
} | [
"function",
"(",
"el",
",",
"e",
")",
"{",
"var",
"ajaxOptions",
"=",
"{",
"}",
",",
"data",
"=",
"{",
"}",
",",
"fieldName",
"=",
"el",
".",
"name",
"||",
"el",
".",
"id",
";",
"if",
"(",
"typeof",
"this",
".",
"remoteCache",
"===",
"'undefined'",
")",
"this",
".",
"remoteCache",
"=",
"{",
"}",
";",
"data",
"[",
"fieldName",
"]",
"=",
"this",
".",
"tmp",
".",
"val",
";",
"ajaxOptions",
"=",
"$",
".",
"extend",
"(",
"true",
",",
"{",
"}",
",",
"{",
"data",
":",
"data",
"}",
",",
"this",
".",
"options",
".",
"validators",
".",
"remote",
"[",
"this",
".",
"tmp",
".",
"remote",
"]",
"||",
"{",
"}",
")",
";",
"var",
"cacheKey",
"=",
"$",
".",
"param",
"(",
"ajaxOptions",
")",
";",
"var",
"cache",
"=",
"this",
".",
"remoteCache",
"[",
"cacheKey",
"]",
";",
"if",
"(",
"typeof",
"cache",
"!==",
"'undefined'",
")",
"{",
"switch",
"(",
"cache",
".",
"state",
")",
"{",
"case",
"'pending'",
":",
"this",
".",
"handler",
"=",
"'pending'",
";",
"cache",
".",
"event",
"=",
"e",
".",
"type",
";",
"break",
";",
"case",
"'rejected'",
":",
"e",
".",
"preventDefault",
"(",
")",
";",
"throw",
"new",
"Error",
"(",
"cache",
".",
"result",
".",
"message",
")",
";",
"case",
"'resolved'",
":",
"if",
"(",
"cache",
".",
"result",
".",
"valid",
"===",
"false",
")",
"{",
"this",
".",
"addErrorClass",
"(",
"this",
".",
"tmp",
".",
"parent",
")",
";",
"this",
".",
"window",
".",
"open",
".",
"call",
"(",
"this",
",",
"el",
",",
"cache",
".",
"result",
".",
"message",
")",
";",
"}",
"else",
"{",
"this",
".",
"addValidClass",
"(",
"this",
".",
"tmp",
".",
"parent",
")",
";",
"}",
"}",
"}",
"else",
"{",
"var",
"_xhr",
"=",
"this",
".",
"xhr",
"[",
"fieldName",
"]",
";",
"if",
"(",
"typeof",
"_xhr",
"!==",
"'undefined'",
"&&",
"_xhr",
".",
"state",
"(",
")",
"===",
"'pending'",
")",
"_xhr",
".",
"abort",
"(",
")",
";",
"cache",
"=",
"this",
".",
"remoteCache",
"[",
"cacheKey",
"]",
"=",
"{",
"state",
":",
"'pending'",
",",
"event",
":",
"e",
".",
"type",
"}",
";",
"this",
".",
"remoteRequest",
"(",
"ajaxOptions",
",",
"cache",
",",
"el",
",",
"fieldName",
")",
";",
"}",
"}"
] | Checks remote validations
@param {object} el current field
@param {object} e event object
@throws {error} If previous remote request for same value has rejected
@return {void} | [
"Checks",
"remote",
"validations"
] | f712b7375e1465bfc687a8c6fc93ea700cb590e3 | https://github.com/hsnaydd/validetta/blob/f712b7375e1465bfc687a8c6fc93ea700cb590e3/dist/validetta.js#L350-L396 | train |
|
hsnaydd/validetta | dist/validetta.js | function( ajaxOptions, cache, el, fieldName, e ) {
var self = this;
$( this.tmp.parent ).addClass('validetta-pending');
// cache xhr
this.xhr[ fieldName ] = $.ajax( ajaxOptions )
.done( function( result ) {
if( typeof result !== 'object' ) result = JSON.parse( result );
cache.state = 'resolved';
cache.result = result;
if ( cache.event === 'submit' ) {
self.handler = false;
$( self.form ).trigger('submit');
}
else if( result.valid === false ) {
self.addErrorClass( self.tmp.parent );
self.window.open.call( self, el, result.message );
} else {
self.addValidClass( self.tmp.parent );
}
} )
.fail( function( jqXHR, textStatus ) {
if ( textStatus !== 'abort' ) { // Dont throw error if request is aborted
var _msg = 'Ajax request failed for field ('+ fieldName +') : '+ jqXHR.status +' '+ jqXHR.statusText;
cache.state = 'rejected';
cache.result = { valid : false, message : _msg };
throw new Error( _msg );
}
} )
.always( function( result ) { $( self.tmp.parent ).removeClass('validetta-pending'); } );
this.handler = 'pending';
} | javascript | function( ajaxOptions, cache, el, fieldName, e ) {
var self = this;
$( this.tmp.parent ).addClass('validetta-pending');
// cache xhr
this.xhr[ fieldName ] = $.ajax( ajaxOptions )
.done( function( result ) {
if( typeof result !== 'object' ) result = JSON.parse( result );
cache.state = 'resolved';
cache.result = result;
if ( cache.event === 'submit' ) {
self.handler = false;
$( self.form ).trigger('submit');
}
else if( result.valid === false ) {
self.addErrorClass( self.tmp.parent );
self.window.open.call( self, el, result.message );
} else {
self.addValidClass( self.tmp.parent );
}
} )
.fail( function( jqXHR, textStatus ) {
if ( textStatus !== 'abort' ) { // Dont throw error if request is aborted
var _msg = 'Ajax request failed for field ('+ fieldName +') : '+ jqXHR.status +' '+ jqXHR.statusText;
cache.state = 'rejected';
cache.result = { valid : false, message : _msg };
throw new Error( _msg );
}
} )
.always( function( result ) { $( self.tmp.parent ).removeClass('validetta-pending'); } );
this.handler = 'pending';
} | [
"function",
"(",
"ajaxOptions",
",",
"cache",
",",
"el",
",",
"fieldName",
",",
"e",
")",
"{",
"var",
"self",
"=",
"this",
";",
"$",
"(",
"this",
".",
"tmp",
".",
"parent",
")",
".",
"addClass",
"(",
"'validetta-pending'",
")",
";",
"this",
".",
"xhr",
"[",
"fieldName",
"]",
"=",
"$",
".",
"ajax",
"(",
"ajaxOptions",
")",
".",
"done",
"(",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"typeof",
"result",
"!==",
"'object'",
")",
"result",
"=",
"JSON",
".",
"parse",
"(",
"result",
")",
";",
"cache",
".",
"state",
"=",
"'resolved'",
";",
"cache",
".",
"result",
"=",
"result",
";",
"if",
"(",
"cache",
".",
"event",
"===",
"'submit'",
")",
"{",
"self",
".",
"handler",
"=",
"false",
";",
"$",
"(",
"self",
".",
"form",
")",
".",
"trigger",
"(",
"'submit'",
")",
";",
"}",
"else",
"if",
"(",
"result",
".",
"valid",
"===",
"false",
")",
"{",
"self",
".",
"addErrorClass",
"(",
"self",
".",
"tmp",
".",
"parent",
")",
";",
"self",
".",
"window",
".",
"open",
".",
"call",
"(",
"self",
",",
"el",
",",
"result",
".",
"message",
")",
";",
"}",
"else",
"{",
"self",
".",
"addValidClass",
"(",
"self",
".",
"tmp",
".",
"parent",
")",
";",
"}",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"jqXHR",
",",
"textStatus",
")",
"{",
"if",
"(",
"textStatus",
"!==",
"'abort'",
")",
"{",
"var",
"_msg",
"=",
"'Ajax request failed for field ('",
"+",
"fieldName",
"+",
"') : '",
"+",
"jqXHR",
".",
"status",
"+",
"' '",
"+",
"jqXHR",
".",
"statusText",
";",
"cache",
".",
"state",
"=",
"'rejected'",
";",
"cache",
".",
"result",
"=",
"{",
"valid",
":",
"false",
",",
"message",
":",
"_msg",
"}",
";",
"throw",
"new",
"Error",
"(",
"_msg",
")",
";",
"}",
"}",
")",
".",
"always",
"(",
"function",
"(",
"result",
")",
"{",
"$",
"(",
"self",
".",
"tmp",
".",
"parent",
")",
".",
"removeClass",
"(",
"'validetta-pending'",
")",
";",
"}",
")",
";",
"this",
".",
"handler",
"=",
"'pending'",
";",
"}"
] | Calls ajax request for remote validations
@param {object} ajaxOptions Ajax options
@param {object} cache Cache object
@param {object} el processing element
@param {string} fieldName Field name for make specific caching
@param {object} e Event object | [
"Calls",
"ajax",
"request",
"for",
"remote",
"validations"
] | f712b7375e1465bfc687a8c6fc93ea700cb590e3 | https://github.com/hsnaydd/validetta/blob/f712b7375e1465bfc687a8c6fc93ea700cb590e3/dist/validetta.js#L407-L441 | train |
|
hsnaydd/validetta | dist/validetta.js | function( el, error ) {
// We want display errors ?
if ( !this.options.showErrorMessages ) {
// because of form not valid, set handler true for break submit
this.handler = true;
return;
}
var elParent = this.parents( el );
// If the parent element undefined, that means el is an object. So we need to transform to the element
if( typeof elParent === 'undefined' ) elParent = el[0].parentNode;
// if there is an error window which previously opened for el, return
if ( elParent.querySelectorAll( '.'+ this.options.errorTemplateClass ).length ) return;
// Create the error window object which will be appear
var errorObject = document.createElement('span');
errorObject.className = this.options.errorTemplateClass + ' '+this.options.errorTemplateClass + '--' + this.options.bubblePosition;
// if error display is bubble, calculate to positions
if( this.options.display === 'bubble' ) {
var pos, W = 0, H = 0;
// !! Here, JQuery functions are using to support the IE8
pos = $( el ).position();
if ( this.options.bubblePosition === 'bottom' ){
H = el.offsetHeight;
}
else {
W = el.offsetWidth;
}
errorObject.innerHTML = '';
errorObject.style.top = pos.top + H + this.options.bubbleGapTop +'px';
errorObject.style.left = pos.left + W + this.options.bubbleGapLeft +'px'
}
elParent.appendChild( errorObject );
errorObject.innerHTML = error ;
// we have an error so we need to break submit
// set to handler true
this.handler = true;
} | javascript | function( el, error ) {
// We want display errors ?
if ( !this.options.showErrorMessages ) {
// because of form not valid, set handler true for break submit
this.handler = true;
return;
}
var elParent = this.parents( el );
// If the parent element undefined, that means el is an object. So we need to transform to the element
if( typeof elParent === 'undefined' ) elParent = el[0].parentNode;
// if there is an error window which previously opened for el, return
if ( elParent.querySelectorAll( '.'+ this.options.errorTemplateClass ).length ) return;
// Create the error window object which will be appear
var errorObject = document.createElement('span');
errorObject.className = this.options.errorTemplateClass + ' '+this.options.errorTemplateClass + '--' + this.options.bubblePosition;
// if error display is bubble, calculate to positions
if( this.options.display === 'bubble' ) {
var pos, W = 0, H = 0;
// !! Here, JQuery functions are using to support the IE8
pos = $( el ).position();
if ( this.options.bubblePosition === 'bottom' ){
H = el.offsetHeight;
}
else {
W = el.offsetWidth;
}
errorObject.innerHTML = '';
errorObject.style.top = pos.top + H + this.options.bubbleGapTop +'px';
errorObject.style.left = pos.left + W + this.options.bubbleGapLeft +'px'
}
elParent.appendChild( errorObject );
errorObject.innerHTML = error ;
// we have an error so we need to break submit
// set to handler true
this.handler = true;
} | [
"function",
"(",
"el",
",",
"error",
")",
"{",
"if",
"(",
"!",
"this",
".",
"options",
".",
"showErrorMessages",
")",
"{",
"this",
".",
"handler",
"=",
"true",
";",
"return",
";",
"}",
"var",
"elParent",
"=",
"this",
".",
"parents",
"(",
"el",
")",
";",
"if",
"(",
"typeof",
"elParent",
"===",
"'undefined'",
")",
"elParent",
"=",
"el",
"[",
"0",
"]",
".",
"parentNode",
";",
"if",
"(",
"elParent",
".",
"querySelectorAll",
"(",
"'.'",
"+",
"this",
".",
"options",
".",
"errorTemplateClass",
")",
".",
"length",
")",
"return",
";",
"var",
"errorObject",
"=",
"document",
".",
"createElement",
"(",
"'span'",
")",
";",
"errorObject",
".",
"className",
"=",
"this",
".",
"options",
".",
"errorTemplateClass",
"+",
"' '",
"+",
"this",
".",
"options",
".",
"errorTemplateClass",
"+",
"'--'",
"+",
"this",
".",
"options",
".",
"bubblePosition",
";",
"if",
"(",
"this",
".",
"options",
".",
"display",
"===",
"'bubble'",
")",
"{",
"var",
"pos",
",",
"W",
"=",
"0",
",",
"H",
"=",
"0",
";",
"pos",
"=",
"$",
"(",
"el",
")",
".",
"position",
"(",
")",
";",
"if",
"(",
"this",
".",
"options",
".",
"bubblePosition",
"===",
"'bottom'",
")",
"{",
"H",
"=",
"el",
".",
"offsetHeight",
";",
"}",
"else",
"{",
"W",
"=",
"el",
".",
"offsetWidth",
";",
"}",
"errorObject",
".",
"innerHTML",
"=",
"''",
";",
"errorObject",
".",
"style",
".",
"top",
"=",
"pos",
".",
"top",
"+",
"H",
"+",
"this",
".",
"options",
".",
"bubbleGapTop",
"+",
"'px'",
";",
"errorObject",
".",
"style",
".",
"left",
"=",
"pos",
".",
"left",
"+",
"W",
"+",
"this",
".",
"options",
".",
"bubbleGapLeft",
"+",
"'px'",
"}",
"elParent",
".",
"appendChild",
"(",
"errorObject",
")",
";",
"errorObject",
".",
"innerHTML",
"=",
"error",
";",
"this",
".",
"handler",
"=",
"true",
";",
"}"
] | Error window opens
@params {object} el : element which has an error ( it can be native element or jQuery object )
@params {string} error : error messages | [
"Error",
"window",
"opens"
] | f712b7375e1465bfc687a8c6fc93ea700cb590e3 | https://github.com/hsnaydd/validetta/blob/f712b7375e1465bfc687a8c6fc93ea700cb590e3/dist/validetta.js#L455-L492 | train |
|
hsnaydd/validetta | dist/validetta.js | function( el ) {
var _errorMessages = {};
// if el is undefined ( This is the process of resetting all <form> )
// or el is an object that has element more than one
// and these elements are not checkbox
if( typeof el === 'undefined' || ( el.length > 1 && el[0].type !== 'checkbox' ) ) {
_errorMessages = this.form.querySelectorAll( '.'+ this.options.errorTemplateClass );
}
else {
_errorMessages = this.parents( el[0] ).querySelectorAll( '.'+ this.options.errorTemplateClass );
}
for ( var i = 0, _lengthErrorMessages = _errorMessages.length; i < _lengthErrorMessages; i++ ) {
this.window.close.call( this, _errorMessages[ i ] );
}
// set to handler false
// otherwise at the next validation attempt, submit will not continue even the validation is successful
this.handler = false;
} | javascript | function( el ) {
var _errorMessages = {};
// if el is undefined ( This is the process of resetting all <form> )
// or el is an object that has element more than one
// and these elements are not checkbox
if( typeof el === 'undefined' || ( el.length > 1 && el[0].type !== 'checkbox' ) ) {
_errorMessages = this.form.querySelectorAll( '.'+ this.options.errorTemplateClass );
}
else {
_errorMessages = this.parents( el[0] ).querySelectorAll( '.'+ this.options.errorTemplateClass );
}
for ( var i = 0, _lengthErrorMessages = _errorMessages.length; i < _lengthErrorMessages; i++ ) {
this.window.close.call( this, _errorMessages[ i ] );
}
// set to handler false
// otherwise at the next validation attempt, submit will not continue even the validation is successful
this.handler = false;
} | [
"function",
"(",
"el",
")",
"{",
"var",
"_errorMessages",
"=",
"{",
"}",
";",
"if",
"(",
"typeof",
"el",
"===",
"'undefined'",
"||",
"(",
"el",
".",
"length",
">",
"1",
"&&",
"el",
"[",
"0",
"]",
".",
"type",
"!==",
"'checkbox'",
")",
")",
"{",
"_errorMessages",
"=",
"this",
".",
"form",
".",
"querySelectorAll",
"(",
"'.'",
"+",
"this",
".",
"options",
".",
"errorTemplateClass",
")",
";",
"}",
"else",
"{",
"_errorMessages",
"=",
"this",
".",
"parents",
"(",
"el",
"[",
"0",
"]",
")",
".",
"querySelectorAll",
"(",
"'.'",
"+",
"this",
".",
"options",
".",
"errorTemplateClass",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"_lengthErrorMessages",
"=",
"_errorMessages",
".",
"length",
";",
"i",
"<",
"_lengthErrorMessages",
";",
"i",
"++",
")",
"{",
"this",
".",
"window",
".",
"close",
".",
"call",
"(",
"this",
",",
"_errorMessages",
"[",
"i",
"]",
")",
";",
"}",
"this",
".",
"handler",
"=",
"false",
";",
"}"
] | Removes all error messages windows
@param {object} or {void} el : form elements which have an error message window | [
"Removes",
"all",
"error",
"messages",
"windows"
] | f712b7375e1465bfc687a8c6fc93ea700cb590e3 | https://github.com/hsnaydd/validetta/blob/f712b7375e1465bfc687a8c6fc93ea700cb590e3/dist/validetta.js#L509-L526 | train |
|
hsnaydd/validetta | dist/validetta.js | function( el ) {
var upLength = parseInt( el.getAttribute( 'data-vd-parent-up' ), 10 ) || 0;
for ( var i = 0; i <= upLength ; i++ ) {
el = el.parentNode;
}
return el;
} | javascript | function( el ) {
var upLength = parseInt( el.getAttribute( 'data-vd-parent-up' ), 10 ) || 0;
for ( var i = 0; i <= upLength ; i++ ) {
el = el.parentNode;
}
return el;
} | [
"function",
"(",
"el",
")",
"{",
"var",
"upLength",
"=",
"parseInt",
"(",
"el",
".",
"getAttribute",
"(",
"'data-vd-parent-up'",
")",
",",
"10",
")",
"||",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<=",
"upLength",
";",
"i",
"++",
")",
"{",
"el",
"=",
"el",
".",
"parentNode",
";",
"}",
"return",
"el",
";",
"}"
] | Finds parent element
@param {object} el element
@return {object} el parent element | [
"Finds",
"parent",
"element"
] | f712b7375e1465bfc687a8c6fc93ea700cb590e3 | https://github.com/hsnaydd/validetta/blob/f712b7375e1465bfc687a8c6fc93ea700cb590e3/dist/validetta.js#L553-L559 | train |
|
aweary/alder | fixtures/baz/baz.js | shouldBeIncluded | function shouldBeIncluded(file) {
let isIncluded = false
let isIgnored = false
if (hasIgnorePattern) {
return !ignorePattern.test(file)
}
if (hasIncludePattern) {
return includePattern.test(file)
}
return true
} | javascript | function shouldBeIncluded(file) {
let isIncluded = false
let isIgnored = false
if (hasIgnorePattern) {
return !ignorePattern.test(file)
}
if (hasIncludePattern) {
return includePattern.test(file)
}
return true
} | [
"function",
"shouldBeIncluded",
"(",
"file",
")",
"{",
"let",
"isIncluded",
"=",
"false",
"let",
"isIgnored",
"=",
"false",
"if",
"(",
"hasIgnorePattern",
")",
"{",
"return",
"!",
"ignorePattern",
".",
"test",
"(",
"file",
")",
"}",
"if",
"(",
"hasIncludePattern",
")",
"{",
"return",
"includePattern",
".",
"test",
"(",
"file",
")",
"}",
"return",
"true",
"}"
] | Uses either the ignore or include pattern to determine
if a file should be shown.
@param {String} file filename | [
"Uses",
"either",
"the",
"ignore",
"or",
"include",
"pattern",
"to",
"determine",
"if",
"a",
"file",
"should",
"be",
"shown",
"."
] | edf7c40a7a95b61e82a0685bdb720eac47777d01 | https://github.com/aweary/alder/blob/edf7c40a7a95b61e82a0685bdb720eac47777d01/fixtures/baz/baz.js#L66-L76 | train |
aweary/alder | alder.js | buildPrefix | function buildPrefix(depth, bottom) {
if (!shouldIndent) {
return ''
}
let prefix = bottom ? BOX_BOTTOM_LEFT : BOX_INTERSECTION
let spacing = []
let spaceIndex = 0
while(spaceIndex < depth) {
spacing[spaceIndex] = depths[spaceIndex] && !printJSX ? BOX_VERTICAL : EMPTY
spaceIndex++
}
return printJSX ? spacing.join('') : spacing.join('') + prefix
} | javascript | function buildPrefix(depth, bottom) {
if (!shouldIndent) {
return ''
}
let prefix = bottom ? BOX_BOTTOM_LEFT : BOX_INTERSECTION
let spacing = []
let spaceIndex = 0
while(spaceIndex < depth) {
spacing[spaceIndex] = depths[spaceIndex] && !printJSX ? BOX_VERTICAL : EMPTY
spaceIndex++
}
return printJSX ? spacing.join('') : spacing.join('') + prefix
} | [
"function",
"buildPrefix",
"(",
"depth",
",",
"bottom",
")",
"{",
"if",
"(",
"!",
"shouldIndent",
")",
"{",
"return",
"''",
"}",
"let",
"prefix",
"=",
"bottom",
"?",
"BOX_BOTTOM_LEFT",
":",
"BOX_INTERSECTION",
"let",
"spacing",
"=",
"[",
"]",
"let",
"spaceIndex",
"=",
"0",
"while",
"(",
"spaceIndex",
"<",
"depth",
")",
"{",
"spacing",
"[",
"spaceIndex",
"]",
"=",
"depths",
"[",
"spaceIndex",
"]",
"&&",
"!",
"printJSX",
"?",
"BOX_VERTICAL",
":",
"EMPTY",
"spaceIndex",
"++",
"}",
"return",
"printJSX",
"?",
"spacing",
".",
"join",
"(",
"''",
")",
":",
"spacing",
".",
"join",
"(",
"''",
")",
"+",
"prefix",
"}"
] | Pads filenames with either whitespace or box characters.
The depths map is used to track whether a character should
be whitespace or a vertical character. Typically it will
be whitespace if there are no other files at that depth
that need to be rendered.
@param {Number} depth the level at which this file/filder is nested
@param {Boolean} bottom whether this is the last file in the folder | [
"Pads",
"filenames",
"with",
"either",
"whitespace",
"or",
"box",
"characters",
".",
"The",
"depths",
"map",
"is",
"used",
"to",
"track",
"whether",
"a",
"character",
"should",
"be",
"whitespace",
"or",
"a",
"vertical",
"character",
".",
"Typically",
"it",
"will",
"be",
"whitespace",
"if",
"there",
"are",
"no",
"other",
"files",
"at",
"that",
"depth",
"that",
"need",
"to",
"be",
"rendered",
"."
] | edf7c40a7a95b61e82a0685bdb720eac47777d01 | https://github.com/aweary/alder/blob/edf7c40a7a95b61e82a0685bdb720eac47777d01/alder.js#L104-L116 | train |
aweary/alder | alder.js | shouldBeIncluded | function shouldBeIncluded(file) {
if (!showAllFiles && file[0] === '.') {
return false
}
if (hasExcludePattern) {
return !excludePattern.test(file)
}
if (hasIncludePattern) {
return includePattern.test(file)
}
return true
} | javascript | function shouldBeIncluded(file) {
if (!showAllFiles && file[0] === '.') {
return false
}
if (hasExcludePattern) {
return !excludePattern.test(file)
}
if (hasIncludePattern) {
return includePattern.test(file)
}
return true
} | [
"function",
"shouldBeIncluded",
"(",
"file",
")",
"{",
"if",
"(",
"!",
"showAllFiles",
"&&",
"file",
"[",
"0",
"]",
"===",
"'.'",
")",
"{",
"return",
"false",
"}",
"if",
"(",
"hasExcludePattern",
")",
"{",
"return",
"!",
"excludePattern",
".",
"test",
"(",
"file",
")",
"}",
"if",
"(",
"hasIncludePattern",
")",
"{",
"return",
"includePattern",
".",
"test",
"(",
"file",
")",
"}",
"return",
"true",
"}"
] | Uses either the exclude or include pattern to determine
if a file should be shown.
@param {String} file filename | [
"Uses",
"either",
"the",
"exclude",
"or",
"include",
"pattern",
"to",
"determine",
"if",
"a",
"file",
"should",
"be",
"shown",
"."
] | edf7c40a7a95b61e82a0685bdb720eac47777d01 | https://github.com/aweary/alder/blob/edf7c40a7a95b61e82a0685bdb720eac47777d01/alder.js#L123-L135 | train |
JakubMrozek/eet | lib/eet.js | generatePKP | function generatePKP (privateKey, dicPopl, idProvoz, idPokl, poradCis, datTrzby, celkTrzba) {
const options = [dicPopl, idProvoz, idPokl, poradCis, datTrzby, celkTrzba]
const strToHash = options.join('|')
const sign = crypto.createSign('RSA-SHA256')
sign.write(strToHash)
sign.end()
return sign.sign(privateKey, 'base64')
} | javascript | function generatePKP (privateKey, dicPopl, idProvoz, idPokl, poradCis, datTrzby, celkTrzba) {
const options = [dicPopl, idProvoz, idPokl, poradCis, datTrzby, celkTrzba]
const strToHash = options.join('|')
const sign = crypto.createSign('RSA-SHA256')
sign.write(strToHash)
sign.end()
return sign.sign(privateKey, 'base64')
} | [
"function",
"generatePKP",
"(",
"privateKey",
",",
"dicPopl",
",",
"idProvoz",
",",
"idPokl",
",",
"poradCis",
",",
"datTrzby",
",",
"celkTrzba",
")",
"{",
"const",
"options",
"=",
"[",
"dicPopl",
",",
"idProvoz",
",",
"idPokl",
",",
"poradCis",
",",
"datTrzby",
",",
"celkTrzba",
"]",
"const",
"strToHash",
"=",
"options",
".",
"join",
"(",
"'|'",
")",
"const",
"sign",
"=",
"crypto",
".",
"createSign",
"(",
"'RSA-SHA256'",
")",
"sign",
".",
"write",
"(",
"strToHash",
")",
"sign",
".",
"end",
"(",
")",
"return",
"sign",
".",
"sign",
"(",
"privateKey",
",",
"'base64'",
")",
"}"
] | Vygeneruje podpisovy kod poplatnika.
@see http://www.etrzby.cz/assets/cs/prilohy/EET_popis_rozhrani_v3.1.1.pdf (sekce 4.1) | [
"Vygeneruje",
"podpisovy",
"kod",
"poplatnika",
"."
] | 28a8f0b6743308c705eb0c17e985e0ed065b692e | https://github.com/JakubMrozek/eet/blob/28a8f0b6743308c705eb0c17e985e0ed065b692e/lib/eet.js#L25-L32 | train |
JakubMrozek/eet | lib/eet.js | generateBKP | function generateBKP (pkp) {
const buffer = new Buffer(pkp, 'base64')
const hash = crypto.createHash('sha1')
hash.update(buffer)
const sha1str = hash.digest('hex').toUpperCase()
return sha1str.match(/(.{1,8})/g).join('-')
} | javascript | function generateBKP (pkp) {
const buffer = new Buffer(pkp, 'base64')
const hash = crypto.createHash('sha1')
hash.update(buffer)
const sha1str = hash.digest('hex').toUpperCase()
return sha1str.match(/(.{1,8})/g).join('-')
} | [
"function",
"generateBKP",
"(",
"pkp",
")",
"{",
"const",
"buffer",
"=",
"new",
"Buffer",
"(",
"pkp",
",",
"'base64'",
")",
"const",
"hash",
"=",
"crypto",
".",
"createHash",
"(",
"'sha1'",
")",
"hash",
".",
"update",
"(",
"buffer",
")",
"const",
"sha1str",
"=",
"hash",
".",
"digest",
"(",
"'hex'",
")",
".",
"toUpperCase",
"(",
")",
"return",
"sha1str",
".",
"match",
"(",
"/",
"(.{1,8})",
"/",
"g",
")",
".",
"join",
"(",
"'-'",
")",
"}"
] | Vygeneruje bezpecnostni kod poplatnika.
@see http://www.etrzby.cz/assets/cs/prilohy/EET_popis_rozhrani_v3.1.1.pdf (sekce 4.2) | [
"Vygeneruje",
"bezpecnostni",
"kod",
"poplatnika",
"."
] | 28a8f0b6743308c705eb0c17e985e0ed065b692e | https://github.com/JakubMrozek/eet/blob/28a8f0b6743308c705eb0c17e985e0ed065b692e/lib/eet.js#L40-L46 | train |
JakubMrozek/eet | lib/eet.js | doRequest | function doRequest (options, items) {
const uid = options.uid || uuid.v4()
const date = options.currentDate || new Date()
const soapOptions = {}
if (options.playground) {
soapOptions.endpoint = PG_WSDL_URL
}
if (options.httpClient) {
soapOptions.httpClient = options.httpClient
}
const timeout = options.timeout || 2000
const offline = options.offline || false
return new Promise((resolve, reject) => {
const body = getBodyItems(options.privateKey, date, uid, items)
soap.createClient(WSDL, soapOptions, (err, client) => {
if (err) return reject(err)
client.setSecurity(new WSSecurity(options.privateKey, options.certificate, uid))
client.OdeslaniTrzby(body, (err, response) => {
if (err) return reject(err)
try {
validate.httpResponse(response)
resolve(getResponseItems(response))
} catch (e) {
reject(e)
}
}, {timeout: timeout})
})
}).catch(err => {
if (!offline) return Promise.reject(err)
let code = getFooterItems(options.privateKey, items)
let bkp = code.bkp
let pkp = code.pkp
return Promise.resolve({pkp: pkp.$value, bkp: bkp.$value, err})
})
} | javascript | function doRequest (options, items) {
const uid = options.uid || uuid.v4()
const date = options.currentDate || new Date()
const soapOptions = {}
if (options.playground) {
soapOptions.endpoint = PG_WSDL_URL
}
if (options.httpClient) {
soapOptions.httpClient = options.httpClient
}
const timeout = options.timeout || 2000
const offline = options.offline || false
return new Promise((resolve, reject) => {
const body = getBodyItems(options.privateKey, date, uid, items)
soap.createClient(WSDL, soapOptions, (err, client) => {
if (err) return reject(err)
client.setSecurity(new WSSecurity(options.privateKey, options.certificate, uid))
client.OdeslaniTrzby(body, (err, response) => {
if (err) return reject(err)
try {
validate.httpResponse(response)
resolve(getResponseItems(response))
} catch (e) {
reject(e)
}
}, {timeout: timeout})
})
}).catch(err => {
if (!offline) return Promise.reject(err)
let code = getFooterItems(options.privateKey, items)
let bkp = code.bkp
let pkp = code.pkp
return Promise.resolve({pkp: pkp.$value, bkp: bkp.$value, err})
})
} | [
"function",
"doRequest",
"(",
"options",
",",
"items",
")",
"{",
"const",
"uid",
"=",
"options",
".",
"uid",
"||",
"uuid",
".",
"v4",
"(",
")",
"const",
"date",
"=",
"options",
".",
"currentDate",
"||",
"new",
"Date",
"(",
")",
"const",
"soapOptions",
"=",
"{",
"}",
"if",
"(",
"options",
".",
"playground",
")",
"{",
"soapOptions",
".",
"endpoint",
"=",
"PG_WSDL_URL",
"}",
"if",
"(",
"options",
".",
"httpClient",
")",
"{",
"soapOptions",
".",
"httpClient",
"=",
"options",
".",
"httpClient",
"}",
"const",
"timeout",
"=",
"options",
".",
"timeout",
"||",
"2000",
"const",
"offline",
"=",
"options",
".",
"offline",
"||",
"false",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"body",
"=",
"getBodyItems",
"(",
"options",
".",
"privateKey",
",",
"date",
",",
"uid",
",",
"items",
")",
"soap",
".",
"createClient",
"(",
"WSDL",
",",
"soapOptions",
",",
"(",
"err",
",",
"client",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"reject",
"(",
"err",
")",
"client",
".",
"setSecurity",
"(",
"new",
"WSSecurity",
"(",
"options",
".",
"privateKey",
",",
"options",
".",
"certificate",
",",
"uid",
")",
")",
"client",
".",
"OdeslaniTrzby",
"(",
"body",
",",
"(",
"err",
",",
"response",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"reject",
"(",
"err",
")",
"try",
"{",
"validate",
".",
"httpResponse",
"(",
"response",
")",
"resolve",
"(",
"getResponseItems",
"(",
"response",
")",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"reject",
"(",
"e",
")",
"}",
"}",
",",
"{",
"timeout",
":",
"timeout",
"}",
")",
"}",
")",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"if",
"(",
"!",
"offline",
")",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
"let",
"code",
"=",
"getFooterItems",
"(",
"options",
".",
"privateKey",
",",
"items",
")",
"let",
"bkp",
"=",
"code",
".",
"bkp",
"let",
"pkp",
"=",
"code",
".",
"pkp",
"return",
"Promise",
".",
"resolve",
"(",
"{",
"pkp",
":",
"pkp",
".",
"$value",
",",
"bkp",
":",
"bkp",
".",
"$value",
",",
"err",
"}",
")",
"}",
")",
"}"
] | Odeslani platby do EET.
Volby:
- options.playground (boolean): povolit testovaci prostredi, def. false
- options.offline (boolean): při chybě vygeneruje PKP a BKP, def. false
Polozky (items) jsou popsany u funkce getItemsForBody().
Vraci Promise. Pokud je vse v poradku, vrati FIK, v opacnem pripade vraci info o chybe. | [
"Odeslani",
"platby",
"do",
"EET",
"."
] | 28a8f0b6743308c705eb0c17e985e0ed065b692e | https://github.com/JakubMrozek/eet/blob/28a8f0b6743308c705eb0c17e985e0ed065b692e/lib/eet.js#L59-L94 | train |
JakubMrozek/eet | lib/eet.js | getBodyItems | function getBodyItems (privateKey, currentDate, uid, items) {
return {
Hlavicka: getHeaderItems(uid, currentDate, items.prvniZaslani, items.overeni),
Data: getDataItems(items),
KontrolniKody: getFooterItems(privateKey, items)
}
} | javascript | function getBodyItems (privateKey, currentDate, uid, items) {
return {
Hlavicka: getHeaderItems(uid, currentDate, items.prvniZaslani, items.overeni),
Data: getDataItems(items),
KontrolniKody: getFooterItems(privateKey, items)
}
} | [
"function",
"getBodyItems",
"(",
"privateKey",
",",
"currentDate",
",",
"uid",
",",
"items",
")",
"{",
"return",
"{",
"Hlavicka",
":",
"getHeaderItems",
"(",
"uid",
",",
"currentDate",
",",
"items",
".",
"prvniZaslani",
",",
"items",
".",
"overeni",
")",
",",
"Data",
":",
"getDataItems",
"(",
"items",
")",
",",
"KontrolniKody",
":",
"getFooterItems",
"(",
"privateKey",
",",
"items",
")",
"}",
"}"
] | Vrati vsechny polozky pro obsah SOAP body.
Polozky: | [
"Vrati",
"vsechny",
"polozky",
"pro",
"obsah",
"SOAP",
"body",
"."
] | 28a8f0b6743308c705eb0c17e985e0ed065b692e | https://github.com/JakubMrozek/eet/blob/28a8f0b6743308c705eb0c17e985e0ed065b692e/lib/eet.js#L102-L108 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.