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
opendigitaleducation/sijil.js
docs/libs/typescript.js
trimTrailingWhitespacesForRemainingRange
function trimTrailingWhitespacesForRemainingRange() { var startPosition = previousRange ? previousRange.end : originalRange.pos; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); }
javascript
function trimTrailingWhitespacesForRemainingRange() { var startPosition = previousRange ? previousRange.end : originalRange.pos; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); }
[ "function", "trimTrailingWhitespacesForRemainingRange", "(", ")", "{", "var", "startPosition", "=", "previousRange", "?", "previousRange", ".", "end", ":", "originalRange", ".", "pos", ";", "var", "startLine", "=", "sourceFile", ".", "getLineAndCharacterOfPosition", "(", "startPosition", ")", ".", "line", ";", "var", "endLine", "=", "sourceFile", ".", "getLineAndCharacterOfPosition", "(", "originalRange", ".", "end", ")", ".", "line", ";", "trimTrailingWhitespacesForLines", "(", "startLine", ",", "endLine", "+", "1", ",", "previousRange", ")", ";", "}" ]
Trimming will be done for lines after the previous range
[ "Trimming", "will", "be", "done", "for", "lines", "after", "the", "previous", "range" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L52743-L52748
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
getCompletionEntryDisplayNameForSymbol
function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, location) { var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location); if (displayName) { var firstCharCode = displayName.charCodeAt(0); // First check of the displayName is not external module; if it is an external module, it is not valid entry if ((symbol.flags & 1920 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); }
javascript
function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, location) { var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location); if (displayName) { var firstCharCode = displayName.charCodeAt(0); // First check of the displayName is not external module; if it is an external module, it is not valid entry if ((symbol.flags & 1920 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); }
[ "function", "getCompletionEntryDisplayNameForSymbol", "(", "symbol", ",", "target", ",", "performCharacterChecks", ",", "location", ")", "{", "var", "displayName", "=", "ts", ".", "getDeclaredName", "(", "program", ".", "getTypeChecker", "(", ")", ",", "symbol", ",", "location", ")", ";", "if", "(", "displayName", ")", "{", "var", "firstCharCode", "=", "displayName", ".", "charCodeAt", "(", "0", ")", ";", "if", "(", "(", "symbol", ".", "flags", "&", "1920", ")", "&&", "(", "firstCharCode", "===", "39", "||", "firstCharCode", "===", "34", ")", ")", "{", "return", "undefined", ";", "}", "}", "return", "getCompletionEntryDisplayName", "(", "displayName", ",", "target", ",", "performCharacterChecks", ")", ";", "}" ]
Get the name to be display in completion from a given symbol. @return undefined if the name is of external module otherwise a name with striped of any quote
[ "Get", "the", "name", "to", "be", "display", "in", "completion", "from", "a", "given", "symbol", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L55741-L55753
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
getCompletionEntryDisplayName
function getCompletionEntryDisplayName(name, target, performCharacterChecks) { if (!name) { return undefined; } name = ts.stripQuotes(name); if (!name) { return undefined; } // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks) { if (!ts.isIdentifier(name, target)) { return undefined; } } return name; }
javascript
function getCompletionEntryDisplayName(name, target, performCharacterChecks) { if (!name) { return undefined; } name = ts.stripQuotes(name); if (!name) { return undefined; } // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks) { if (!ts.isIdentifier(name, target)) { return undefined; } } return name; }
[ "function", "getCompletionEntryDisplayName", "(", "name", ",", "target", ",", "performCharacterChecks", ")", "{", "if", "(", "!", "name", ")", "{", "return", "undefined", ";", "}", "name", "=", "ts", ".", "stripQuotes", "(", "name", ")", ";", "if", "(", "!", "name", ")", "{", "return", "undefined", ";", "}", "if", "(", "performCharacterChecks", ")", "{", "if", "(", "!", "ts", ".", "isIdentifier", "(", "name", ",", "target", ")", ")", "{", "return", "undefined", ";", "}", "}", "return", "name", ";", "}" ]
Get a displayName from a given for completion list, performing any necessary quotes stripping and checking whether the name is valid identifier name.
[ "Get", "a", "displayName", "from", "a", "given", "for", "completion", "list", "performing", "any", "necessary", "quotes", "stripping", "and", "checking", "whether", "the", "name", "is", "valid", "identifier", "name", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L55758-L55776
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
tryGetObjectLikeCompletionSymbols
function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; var typeForObject; var existingMembers; if (objectLikeContainer.kind === 171 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; // If the object literal is being assigned to something of type 'null | { hello: string }', // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. typeForObject = typeChecker.getContextualType(objectLikeContainer); typeForObject = typeForObject && typeForObject.getNonNullableType(); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 167 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (ts.isVariableLike(rootDeclaration)) { // We don't want to complete using the type acquired by the shape // of the binding pattern; we are only interested in types acquired // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); if (!canGetType && rootDeclaration.kind === 142 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } else if (rootDeclaration.parent.kind === 147 /* MethodDeclaration */ || rootDeclaration.parent.kind === 150 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } if (canGetType) { typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); existingMembers = objectLikeContainer.elements; } } else { ts.Debug.fail("Root declaration is not variable-like."); } } else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } if (!typeForObject) { return false; } var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); } return true; }
javascript
function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; var typeForObject; var existingMembers; if (objectLikeContainer.kind === 171 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; // If the object literal is being assigned to something of type 'null | { hello: string }', // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. typeForObject = typeChecker.getContextualType(objectLikeContainer); typeForObject = typeForObject && typeForObject.getNonNullableType(); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 167 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (ts.isVariableLike(rootDeclaration)) { // We don't want to complete using the type acquired by the shape // of the binding pattern; we are only interested in types acquired // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); if (!canGetType && rootDeclaration.kind === 142 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } else if (rootDeclaration.parent.kind === 147 /* MethodDeclaration */ || rootDeclaration.parent.kind === 150 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } if (canGetType) { typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); existingMembers = objectLikeContainer.elements; } } else { ts.Debug.fail("Root declaration is not variable-like."); } } else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } if (!typeForObject) { return false; } var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); } return true; }
[ "function", "tryGetObjectLikeCompletionSymbols", "(", "objectLikeContainer", ")", "{", "isMemberCompletion", "=", "true", ";", "var", "typeForObject", ";", "var", "existingMembers", ";", "if", "(", "objectLikeContainer", ".", "kind", "===", "171", ")", "{", "isNewIdentifierLocation", "=", "true", ";", "typeForObject", "=", "typeChecker", ".", "getContextualType", "(", "objectLikeContainer", ")", ";", "typeForObject", "=", "typeForObject", "&&", "typeForObject", ".", "getNonNullableType", "(", ")", ";", "existingMembers", "=", "objectLikeContainer", ".", "properties", ";", "}", "else", "if", "(", "objectLikeContainer", ".", "kind", "===", "167", ")", "{", "isNewIdentifierLocation", "=", "false", ";", "var", "rootDeclaration", "=", "ts", ".", "getRootDeclaration", "(", "objectLikeContainer", ".", "parent", ")", ";", "if", "(", "ts", ".", "isVariableLike", "(", "rootDeclaration", ")", ")", "{", "var", "canGetType", "=", "!", "!", "(", "rootDeclaration", ".", "initializer", "||", "rootDeclaration", ".", "type", ")", ";", "if", "(", "!", "canGetType", "&&", "rootDeclaration", ".", "kind", "===", "142", ")", "{", "if", "(", "ts", ".", "isExpression", "(", "rootDeclaration", ".", "parent", ")", ")", "{", "canGetType", "=", "!", "!", "typeChecker", ".", "getContextualType", "(", "rootDeclaration", ".", "parent", ")", ";", "}", "else", "if", "(", "rootDeclaration", ".", "parent", ".", "kind", "===", "147", "||", "rootDeclaration", ".", "parent", ".", "kind", "===", "150", ")", "{", "canGetType", "=", "ts", ".", "isExpression", "(", "rootDeclaration", ".", "parent", ".", "parent", ")", "&&", "!", "!", "typeChecker", ".", "getContextualType", "(", "rootDeclaration", ".", "parent", ".", "parent", ")", ";", "}", "}", "if", "(", "canGetType", ")", "{", "typeForObject", "=", "typeChecker", ".", "getTypeAtLocation", "(", "objectLikeContainer", ")", ";", "existingMembers", "=", "objectLikeContainer", ".", "elements", ";", "}", "}", "else", "{", "ts", ".", "Debug", ".", "fail", "(", "\"Root declaration is not variable-like.\"", ")", ";", "}", "}", "else", "{", "ts", ".", "Debug", ".", "fail", "(", "\"Expected object literal or binding pattern, got \"", "+", "objectLikeContainer", ".", "kind", ")", ";", "}", "if", "(", "!", "typeForObject", ")", "{", "return", "false", ";", "}", "var", "typeMembers", "=", "typeChecker", ".", "getPropertiesOfType", "(", "typeForObject", ")", ";", "if", "(", "typeMembers", "&&", "typeMembers", ".", "length", ">", "0", ")", "{", "symbols", "=", "filterObjectMembersList", "(", "typeMembers", ",", "existingMembers", ")", ";", "}", "return", "true", ";", "}" ]
Aggregates relevant symbols for completion in object literals and object binding patterns. Relevant symbols are stored in the captured 'symbols' variable. @returns true if 'symbols' was successfully populated; false otherwise.
[ "Aggregates", "relevant", "symbols", "for", "completion", "in", "object", "literals", "and", "object", "binding", "patterns", ".", "Relevant", "symbols", "are", "stored", "in", "the", "captured", "symbols", "variable", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L56137-L56192
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
tryGetObjectLikeCompletionContainer
function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { case 15 /* OpenBraceToken */: // const x = { | case 24 /* CommaToken */: var parent_19 = contextToken.parent; if (parent_19 && (parent_19.kind === 171 /* ObjectLiteralExpression */ || parent_19.kind === 167 /* ObjectBindingPattern */)) { return parent_19; } break; } } return undefined; }
javascript
function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { case 15 /* OpenBraceToken */: // const x = { | case 24 /* CommaToken */: var parent_19 = contextToken.parent; if (parent_19 && (parent_19.kind === 171 /* ObjectLiteralExpression */ || parent_19.kind === 167 /* ObjectBindingPattern */)) { return parent_19; } break; } } return undefined; }
[ "function", "tryGetObjectLikeCompletionContainer", "(", "contextToken", ")", "{", "if", "(", "contextToken", ")", "{", "switch", "(", "contextToken", ".", "kind", ")", "{", "case", "15", ":", "case", "24", ":", "var", "parent_19", "=", "contextToken", ".", "parent", ";", "if", "(", "parent_19", "&&", "(", "parent_19", ".", "kind", "===", "171", "||", "parent_19", ".", "kind", "===", "167", ")", ")", "{", "return", "parent_19", ";", "}", "break", ";", "}", "}", "return", "undefined", ";", "}" ]
Returns the immediate owning object literal or binding pattern of a context token, on the condition that one exists and that the context implies completion should be given.
[ "Returns", "the", "immediate", "owning", "object", "literal", "or", "binding", "pattern", "of", "a", "context", "token", "on", "the", "condition", "that", "one", "exists", "and", "that", "the", "context", "implies", "completion", "should", "be", "given", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L56231-L56244
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
tryGetNamedImportsOrExportsForCompletion
function tryGetNamedImportsOrExportsForCompletion(contextToken) { if (contextToken) { switch (contextToken.kind) { case 15 /* OpenBraceToken */: // import { | case 24 /* CommaToken */: switch (contextToken.parent.kind) { case 233 /* NamedImports */: case 237 /* NamedExports */: return contextToken.parent; } } } return undefined; }
javascript
function tryGetNamedImportsOrExportsForCompletion(contextToken) { if (contextToken) { switch (contextToken.kind) { case 15 /* OpenBraceToken */: // import { | case 24 /* CommaToken */: switch (contextToken.parent.kind) { case 233 /* NamedImports */: case 237 /* NamedExports */: return contextToken.parent; } } } return undefined; }
[ "function", "tryGetNamedImportsOrExportsForCompletion", "(", "contextToken", ")", "{", "if", "(", "contextToken", ")", "{", "switch", "(", "contextToken", ".", "kind", ")", "{", "case", "15", ":", "case", "24", ":", "switch", "(", "contextToken", ".", "parent", ".", "kind", ")", "{", "case", "233", ":", "case", "237", ":", "return", "contextToken", ".", "parent", ";", "}", "}", "}", "return", "undefined", ";", "}" ]
Returns the containing list of named imports or exports of a context token, on the condition that one exists and that the context implies completion should be given.
[ "Returns", "the", "containing", "list", "of", "named", "imports", "or", "exports", "of", "a", "context", "token", "on", "the", "condition", "that", "one", "exists", "and", "that", "the", "context", "implies", "completion", "should", "be", "given", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L56249-L56262
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
filterNamedImportOrExportCompletionItems
function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { var existingImportsOrExports = ts.createMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out if (element.getStart() <= position && position <= element.getEnd()) { continue; } var name_41 = element.propertyName || element.name; existingImportsOrExports[name_41.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); } return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports[e.name]; }); }
javascript
function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { var existingImportsOrExports = ts.createMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out if (element.getStart() <= position && position <= element.getEnd()) { continue; } var name_41 = element.propertyName || element.name; existingImportsOrExports[name_41.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); } return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports[e.name]; }); }
[ "function", "filterNamedImportOrExportCompletionItems", "(", "exportsOfModule", ",", "namedImportsOrExports", ")", "{", "var", "existingImportsOrExports", "=", "ts", ".", "createMap", "(", ")", ";", "for", "(", "var", "_i", "=", "0", ",", "namedImportsOrExports_1", "=", "namedImportsOrExports", ";", "_i", "<", "namedImportsOrExports_1", ".", "length", ";", "_i", "++", ")", "{", "var", "element", "=", "namedImportsOrExports_1", "[", "_i", "]", ";", "if", "(", "element", ".", "getStart", "(", ")", "<=", "position", "&&", "position", "<=", "element", ".", "getEnd", "(", ")", ")", "{", "continue", ";", "}", "var", "name_41", "=", "element", ".", "propertyName", "||", "element", ".", "name", ";", "existingImportsOrExports", "[", "name_41", ".", "text", "]", "=", "true", ";", "}", "if", "(", "!", "ts", ".", "someProperties", "(", "existingImportsOrExports", ")", ")", "{", "return", "ts", ".", "filter", "(", "exportsOfModule", ",", "function", "(", "e", ")", "{", "return", "e", ".", "name", "!==", "\"default\"", ";", "}", ")", ";", "}", "return", "ts", ".", "filter", "(", "exportsOfModule", ",", "function", "(", "e", ")", "{", "return", "e", ".", "name", "!==", "\"default\"", "&&", "!", "existingImportsOrExports", "[", "e", ".", "name", "]", ";", "}", ")", ";", "}" ]
Filters out completion suggestions for named imports or exports. @param exportsOfModule The list of symbols which a module exposes. @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause. @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports do not occur at the current position and have not otherwise been typed.
[ "Filters", "out", "completion", "suggestions", "for", "named", "imports", "or", "exports", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L56424-L56439
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
getBaseDirectoriesFromRootDirs
function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { // Make all paths absolute/normalized if they are not already rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory; for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { var rootDirectory = rootDirs_1[_i]; if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { relativeDirectory = scriptPath.substr(rootDirectory.length); break; } } // Now find a path for each potential directory that is to be merged with the one containing the script return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); }
javascript
function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { // Make all paths absolute/normalized if they are not already rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory; for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { var rootDirectory = rootDirs_1[_i]; if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { relativeDirectory = scriptPath.substr(rootDirectory.length); break; } } // Now find a path for each potential directory that is to be merged with the one containing the script return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); }
[ "function", "getBaseDirectoriesFromRootDirs", "(", "rootDirs", ",", "basePath", ",", "scriptPath", ",", "ignoreCase", ")", "{", "rootDirs", "=", "ts", ".", "map", "(", "rootDirs", ",", "function", "(", "rootDirectory", ")", "{", "return", "ts", ".", "normalizePath", "(", "ts", ".", "isRootedDiskPath", "(", "rootDirectory", ")", "?", "rootDirectory", ":", "ts", ".", "combinePaths", "(", "basePath", ",", "rootDirectory", ")", ")", ";", "}", ")", ";", "var", "relativeDirectory", ";", "for", "(", "var", "_i", "=", "0", ",", "rootDirs_1", "=", "rootDirs", ";", "_i", "<", "rootDirs_1", ".", "length", ";", "_i", "++", ")", "{", "var", "rootDirectory", "=", "rootDirs_1", "[", "_i", "]", ";", "if", "(", "ts", ".", "containsPath", "(", "rootDirectory", ",", "scriptPath", ",", "basePath", ",", "ignoreCase", ")", ")", "{", "relativeDirectory", "=", "scriptPath", ".", "substr", "(", "rootDirectory", ".", "length", ")", ";", "break", ";", "}", "}", "return", "ts", ".", "deduplicate", "(", "ts", ".", "map", "(", "rootDirs", ",", "function", "(", "rootDirectory", ")", "{", "return", "ts", ".", "combinePaths", "(", "rootDirectory", ",", "relativeDirectory", ")", ";", "}", ")", ")", ";", "}" ]
Takes a script path and returns paths for all potential folders that could be merged with its containing folder via the "rootDirs" compiler option
[ "Takes", "a", "script", "path", "and", "returns", "paths", "for", "all", "potential", "folders", "that", "could", "be", "merged", "with", "its", "containing", "folder", "via", "the", "rootDirs", "compiler", "option" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L56778-L56792
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
getDirectoryFragmentTextSpan
function getDirectoryFragmentTextSpan(text, textStart) { var index = text.lastIndexOf(ts.directorySeparator); var offset = index !== -1 ? index + 1 : 0; return { start: textStart + offset, length: text.length - offset }; }
javascript
function getDirectoryFragmentTextSpan(text, textStart) { var index = text.lastIndexOf(ts.directorySeparator); var offset = index !== -1 ? index + 1 : 0; return { start: textStart + offset, length: text.length - offset }; }
[ "function", "getDirectoryFragmentTextSpan", "(", "text", ",", "textStart", ")", "{", "var", "index", "=", "text", ".", "lastIndexOf", "(", "ts", ".", "directorySeparator", ")", ";", "var", "offset", "=", "index", "!==", "-", "1", "?", "index", "+", "1", ":", "0", ";", "return", "{", "start", ":", "textStart", "+", "offset", ",", "length", ":", "text", ".", "length", "-", "offset", "}", ";", "}" ]
Replace everything after the last directory seperator that appears
[ "Replace", "everything", "after", "the", "last", "directory", "seperator", "that", "appears" ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L57124-L57128
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
getSymbolScope
function getSymbolScope(symbol) { // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; if (valueDeclaration && (valueDeclaration.kind === 179 /* FunctionExpression */ || valueDeclaration.kind === 192 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 8 /* Private */) ? d : undefined; }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 221 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. // So consider it visible outside its declaration scope. if (symbol.flags & 8388608 /* Alias */) { return undefined; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { return undefined; } // if this symbol is visible from its parent container, e.g. exported, then bail out // if symbol correspond to the union property - bail out if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { return undefined; } var scope; var declarations = symbol.getDeclarations(); if (declarations) { for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { var declaration = declarations_9[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; } if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; } // The search scope is the container node scope = container; } } return scope; }
javascript
function getSymbolScope(symbol) { // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; if (valueDeclaration && (valueDeclaration.kind === 179 /* FunctionExpression */ || valueDeclaration.kind === 192 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 8 /* Private */) ? d : undefined; }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 221 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. // So consider it visible outside its declaration scope. if (symbol.flags & 8388608 /* Alias */) { return undefined; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { return undefined; } // if this symbol is visible from its parent container, e.g. exported, then bail out // if symbol correspond to the union property - bail out if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { return undefined; } var scope; var declarations = symbol.getDeclarations(); if (declarations) { for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { var declaration = declarations_9[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; } if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; } // The search scope is the container node scope = container; } } return scope; }
[ "function", "getSymbolScope", "(", "symbol", ")", "{", "var", "valueDeclaration", "=", "symbol", ".", "valueDeclaration", ";", "if", "(", "valueDeclaration", "&&", "(", "valueDeclaration", ".", "kind", "===", "179", "||", "valueDeclaration", ".", "kind", "===", "192", ")", ")", "{", "return", "valueDeclaration", ";", "}", "if", "(", "symbol", ".", "flags", "&", "(", "4", "|", "8192", ")", ")", "{", "var", "privateDeclaration", "=", "ts", ".", "forEach", "(", "symbol", ".", "getDeclarations", "(", ")", ",", "function", "(", "d", ")", "{", "return", "(", "d", ".", "flags", "&", "8", ")", "?", "d", ":", "undefined", ";", "}", ")", ";", "if", "(", "privateDeclaration", ")", "{", "return", "ts", ".", "getAncestor", "(", "privateDeclaration", ",", "221", ")", ";", "}", "}", "if", "(", "symbol", ".", "flags", "&", "8388608", ")", "{", "return", "undefined", ";", "}", "if", "(", "isObjectBindingPatternElementWithoutPropertyName", "(", "symbol", ")", ")", "{", "return", "undefined", ";", "}", "if", "(", "symbol", ".", "parent", "||", "(", "symbol", ".", "flags", "&", "268435456", ")", ")", "{", "return", "undefined", ";", "}", "var", "scope", ";", "var", "declarations", "=", "symbol", ".", "getDeclarations", "(", ")", ";", "if", "(", "declarations", ")", "{", "for", "(", "var", "_i", "=", "0", ",", "declarations_9", "=", "declarations", ";", "_i", "<", "declarations_9", ".", "length", ";", "_i", "++", ")", "{", "var", "declaration", "=", "declarations_9", "[", "_i", "]", ";", "var", "container", "=", "getContainerNode", "(", "declaration", ")", ";", "if", "(", "!", "container", ")", "{", "return", "undefined", ";", "}", "if", "(", "scope", "&&", "scope", "!==", "container", ")", "{", "return", "undefined", ";", "}", "if", "(", "container", ".", "kind", "===", "256", "&&", "!", "ts", ".", "isExternalModule", "(", "container", ")", ")", "{", "return", "undefined", ";", "}", "scope", "=", "container", ";", "}", "}", "return", "scope", ";", "}" ]
Determines the smallest scope in which a symbol may have named references. Note that not every construct has been accounted for. This function can probably be improved. @returns undefined if the scope cannot be determined, implying that a reference to a symbol can occur anywhere.
[ "Determines", "the", "smallest", "scope", "in", "which", "a", "symbol", "may", "have", "named", "references", ".", "Note", "that", "not", "every", "construct", "has", "been", "accounted", "for", ".", "This", "function", "can", "probably", "be", "improved", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L58682-L58734
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
tryClassifyNode
function tryClassifyNode(node) { if (ts.isJSDocTag(node)) { return true; } if (ts.nodeIsMissing(node)) { return true; } var classifiedElementName = tryClassifyJsxElementName(node); if (!ts.isToken(node) && node.kind !== 244 /* JsxText */ && classifiedElementName === undefined) { return false; } var tokenStart = node.kind === 244 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { var type = classifiedElementName || classifyTokenType(node.kind, node); if (type) { pushClassification(tokenStart, tokenWidth, type); } } return true; }
javascript
function tryClassifyNode(node) { if (ts.isJSDocTag(node)) { return true; } if (ts.nodeIsMissing(node)) { return true; } var classifiedElementName = tryClassifyJsxElementName(node); if (!ts.isToken(node) && node.kind !== 244 /* JsxText */ && classifiedElementName === undefined) { return false; } var tokenStart = node.kind === 244 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { var type = classifiedElementName || classifyTokenType(node.kind, node); if (type) { pushClassification(tokenStart, tokenWidth, type); } } return true; }
[ "function", "tryClassifyNode", "(", "node", ")", "{", "if", "(", "ts", ".", "isJSDocTag", "(", "node", ")", ")", "{", "return", "true", ";", "}", "if", "(", "ts", ".", "nodeIsMissing", "(", "node", ")", ")", "{", "return", "true", ";", "}", "var", "classifiedElementName", "=", "tryClassifyJsxElementName", "(", "node", ")", ";", "if", "(", "!", "ts", ".", "isToken", "(", "node", ")", "&&", "node", ".", "kind", "!==", "244", "&&", "classifiedElementName", "===", "undefined", ")", "{", "return", "false", ";", "}", "var", "tokenStart", "=", "node", ".", "kind", "===", "244", "?", "node", ".", "pos", ":", "classifyLeadingTriviaAndGetTokenStart", "(", "node", ")", ";", "var", "tokenWidth", "=", "node", ".", "end", "-", "tokenStart", ";", "ts", ".", "Debug", ".", "assert", "(", "tokenWidth", ">=", "0", ")", ";", "if", "(", "tokenWidth", ">", "0", ")", "{", "var", "type", "=", "classifiedElementName", "||", "classifyTokenType", "(", "node", ".", "kind", ",", "node", ")", ";", "if", "(", "type", ")", "{", "pushClassification", "(", "tokenStart", ",", "tokenWidth", ",", "type", ")", ";", "}", "}", "return", "true", ";", "}" ]
Returns true if node should be treated as classified and no further processing is required. False will mean that node is not classified and traverse routine should recurse into node contents.
[ "Returns", "true", "if", "node", "should", "be", "treated", "as", "classified", "and", "no", "further", "processing", "is", "required", ".", "False", "will", "mean", "that", "node", "is", "not", "classified", "and", "traverse", "routine", "should", "recurse", "into", "node", "contents", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L59869-L59890
train
opendigitaleducation/sijil.js
docs/libs/typescript.js
canFollow
function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { if (keyword2 === 123 /* GetKeyword */ || keyword2 === 131 /* SetKeyword */ || keyword2 === 121 /* ConstructorKeyword */ || keyword2 === 113 /* StaticKeyword */) { // Allow things like "public get", "public constructor" and "public static". // These are all legal. return true; } // Any other keyword following "public" is actually an identifier an not a real // keyword. return false; } // Assume any other keyword combination is legal. This can be refined in the future // if there are more cases we want the classifier to be better at. return true; }
javascript
function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { if (keyword2 === 123 /* GetKeyword */ || keyword2 === 131 /* SetKeyword */ || keyword2 === 121 /* ConstructorKeyword */ || keyword2 === 113 /* StaticKeyword */) { // Allow things like "public get", "public constructor" and "public static". // These are all legal. return true; } // Any other keyword following "public" is actually an identifier an not a real // keyword. return false; } // Assume any other keyword combination is legal. This can be refined in the future // if there are more cases we want the classifier to be better at. return true; }
[ "function", "canFollow", "(", "keyword1", ",", "keyword2", ")", "{", "if", "(", "ts", ".", "isAccessibilityModifier", "(", "keyword1", ")", ")", "{", "if", "(", "keyword2", "===", "123", "||", "keyword2", "===", "131", "||", "keyword2", "===", "121", "||", "keyword2", "===", "113", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "return", "true", ";", "}" ]
Returns true if 'keyword2' can legally follow 'keyword1' in any language construct.
[ "Returns", "true", "if", "keyword2", "can", "legally", "follow", "keyword1", "in", "any", "language", "construct", "." ]
c0cd5250a573689a8bcd9733b958d4215b0ecfa4
https://github.com/opendigitaleducation/sijil.js/blob/c0cd5250a573689a8bcd9733b958d4215b0ecfa4/docs/libs/typescript.js#L60612-L60629
train
2do2go/node-twostep
lib/twoStep.js
chainStepsNoError
function chainStepsNoError() { var steps = slice.call(arguments).map(function(step) { return notHandlingError(step); }); return chainSteps.apply(null, steps); }
javascript
function chainStepsNoError() { var steps = slice.call(arguments).map(function(step) { return notHandlingError(step); }); return chainSteps.apply(null, steps); }
[ "function", "chainStepsNoError", "(", ")", "{", "var", "steps", "=", "slice", ".", "call", "(", "arguments", ")", ".", "map", "(", "function", "(", "step", ")", "{", "return", "notHandlingError", "(", "step", ")", ";", "}", ")", ";", "return", "chainSteps", ".", "apply", "(", "null", ",", "steps", ")", ";", "}" ]
Similar to `makeSteps` but the chaining continues only on successful execution of the previous step and breaks after the first error occured.
[ "Similar", "to", "makeSteps", "but", "the", "chaining", "continues", "only", "on", "successful", "execution", "of", "the", "previous", "step", "and", "breaks", "after", "the", "first", "error", "occured", "." ]
4a491b6982e26f6349c82072f04bed0ff2cc779c
https://github.com/2do2go/node-twostep/blob/4a491b6982e26f6349c82072f04bed0ff2cc779c/lib/twoStep.js#L138-L143
train
2do2go/node-twostep
lib/twoStep.js
chainAndCall
function chainAndCall(chainer) { return function(/*step1, step2, ...*/) { var steps = slice.call(arguments); var callback = steps.pop(); chainer.apply(null, steps)(callback); }; }
javascript
function chainAndCall(chainer) { return function(/*step1, step2, ...*/) { var steps = slice.call(arguments); var callback = steps.pop(); chainer.apply(null, steps)(callback); }; }
[ "function", "chainAndCall", "(", "chainer", ")", "{", "return", "function", "(", ")", "{", "var", "steps", "=", "slice", ".", "call", "(", "arguments", ")", ";", "var", "callback", "=", "steps", ".", "pop", "(", ")", ";", "chainer", ".", "apply", "(", "null", ",", "steps", ")", "(", "callback", ")", ";", "}", ";", "}" ]
Chain and execute given steps immediately. The last step in chain will be the error- and result-handling callback.
[ "Chain", "and", "execute", "given", "steps", "immediately", ".", "The", "last", "step", "in", "chain", "will", "be", "the", "error", "-", "and", "result", "-", "handling", "callback", "." ]
4a491b6982e26f6349c82072f04bed0ff2cc779c
https://github.com/2do2go/node-twostep/blob/4a491b6982e26f6349c82072f04bed0ff2cc779c/lib/twoStep.js#L183-L189
train
apparatus/mu
packages/mu-router/index.js
route
function route (message, cb) { assert(message, 'route requries a valid message') assert(cb && (typeof cb === 'function'), 'route requires a valid callback handler') if (message.pattern) { return pattern(message, cb) } if (message.response) { return response(message, cb) } malformed(message, cb) }
javascript
function route (message, cb) { assert(message, 'route requries a valid message') assert(cb && (typeof cb === 'function'), 'route requires a valid callback handler') if (message.pattern) { return pattern(message, cb) } if (message.response) { return response(message, cb) } malformed(message, cb) }
[ "function", "route", "(", "message", ",", "cb", ")", "{", "assert", "(", "message", ",", "'route requries a valid message'", ")", "assert", "(", "cb", "&&", "(", "typeof", "cb", "===", "'function'", ")", ",", "'route requires a valid callback handler'", ")", "if", "(", "message", ".", "pattern", ")", "{", "return", "pattern", "(", "message", ",", "cb", ")", "}", "if", "(", "message", ".", "response", ")", "{", "return", "response", "(", "message", ",", "cb", ")", "}", "malformed", "(", "message", ",", "cb", ")", "}" ]
main routing function
[ "main", "routing", "function" ]
c084ec60b5e3a7c163bead9aedbb59eefa1ea787
https://github.com/apparatus/mu/blob/c084ec60b5e3a7c163bead9aedbb59eefa1ea787/packages/mu-router/index.js#L66-L79
train
ericelliott/qconf
lib/make-config.js
get
function get(attr) { var val = dotty.get(attrs, attr); if (val === undefined) { this.emit('undefined', 'WARNING: Undefined environment variable: ' + attr, attr); } return val; }
javascript
function get(attr) { var val = dotty.get(attrs, attr); if (val === undefined) { this.emit('undefined', 'WARNING: Undefined environment variable: ' + attr, attr); } return val; }
[ "function", "get", "(", "attr", ")", "{", "var", "val", "=", "dotty", ".", "get", "(", "attrs", ",", "attr", ")", ";", "if", "(", "val", "===", "undefined", ")", "{", "this", ".", "emit", "(", "'undefined'", ",", "'WARNING: Undefined environment variable: '", "+", "attr", ",", "attr", ")", ";", "}", "return", "val", ";", "}" ]
Return the value of the attribute requested. @param {String} attr The name of the attribute to return. @return {Any} The value of the requested attribute.
[ "Return", "the", "value", "of", "the", "attribute", "requested", "." ]
6969136ddfd3c4b688a26aba1bb7d0567158b7fb
https://github.com/ericelliott/qconf/blob/6969136ddfd3c4b688a26aba1bb7d0567158b7fb/lib/make-config.js#L22-L29
train
wokim/node-perforce
index.js
processZtagOutput
function processZtagOutput(output) { return output.split('\n').reduce(function(memo, line) { var match, key, value; match = ztagRegex.exec(line); if(match) { key = match[1]; value = match[2]; memo[key] = value; } return memo; }, {}); }
javascript
function processZtagOutput(output) { return output.split('\n').reduce(function(memo, line) { var match, key, value; match = ztagRegex.exec(line); if(match) { key = match[1]; value = match[2]; memo[key] = value; } return memo; }, {}); }
[ "function", "processZtagOutput", "(", "output", ")", "{", "return", "output", ".", "split", "(", "'\\n'", ")", ".", "\\n", "reduce", ";", "}" ]
process group of lines of output from a p4 command executed with -ztag
[ "process", "group", "of", "lines", "of", "output", "from", "a", "p4", "command", "executed", "with", "-", "ztag" ]
687e39b0177da0061f2980ed6b3c7e967259e263
https://github.com/wokim/node-perforce/blob/687e39b0177da0061f2980ed6b3c7e967259e263/index.js#L83-L94
train
af/JSnoX
jsnox.js
jsnox
function jsnox(React) { var client = function jsnoxClient(componentType, props, children) { // Special $renderIf prop allows you to conditionally render an element: //if (props && typeof props.$renderIf !== 'undefined') { if (props && typeof props === 'object' && props.hasOwnProperty('$renderIf')) { if (props.$renderIf) delete props.$renderIf // Don't pass down to components else return null } // Handle case where an array of children is given as the second argument: if (Array.isArray(props) || typeof props !== 'object') { children = props props = null } // Handle case where props object (second arg) is omitted var arg2IsReactElement = props && React.isValidElement(props) var finalProps = props if (typeof componentType === 'string' || !componentType) { // Parse the provided string into a hash of props // If componentType is invalid (undefined, empty string, etc), // parseTagSpec should throw. var spec = parseTagSpec(componentType) componentType = spec.tagName finalProps = arg2IsReactElement ? spec.props : extend(spec.props, props) } // If more than three args are given, assume args 3..n are ReactElement // children. You can also pass an array of children as the 3rd argument, // but in that case each child should have a unique key to avoid warnings. var args = protoSlice.call(arguments) if (args.length > 3 || arg2IsReactElement) { args[0] = componentType if (arg2IsReactElement) { args.splice(1, 0, finalProps || null) } else { args[1] = finalProps } return React.createElement.apply(React, args) } else { return React.createElement(componentType, finalProps, children) } } client.ParseError = ParseError return client }
javascript
function jsnox(React) { var client = function jsnoxClient(componentType, props, children) { // Special $renderIf prop allows you to conditionally render an element: //if (props && typeof props.$renderIf !== 'undefined') { if (props && typeof props === 'object' && props.hasOwnProperty('$renderIf')) { if (props.$renderIf) delete props.$renderIf // Don't pass down to components else return null } // Handle case where an array of children is given as the second argument: if (Array.isArray(props) || typeof props !== 'object') { children = props props = null } // Handle case where props object (second arg) is omitted var arg2IsReactElement = props && React.isValidElement(props) var finalProps = props if (typeof componentType === 'string' || !componentType) { // Parse the provided string into a hash of props // If componentType is invalid (undefined, empty string, etc), // parseTagSpec should throw. var spec = parseTagSpec(componentType) componentType = spec.tagName finalProps = arg2IsReactElement ? spec.props : extend(spec.props, props) } // If more than three args are given, assume args 3..n are ReactElement // children. You can also pass an array of children as the 3rd argument, // but in that case each child should have a unique key to avoid warnings. var args = protoSlice.call(arguments) if (args.length > 3 || arg2IsReactElement) { args[0] = componentType if (arg2IsReactElement) { args.splice(1, 0, finalProps || null) } else { args[1] = finalProps } return React.createElement.apply(React, args) } else { return React.createElement(componentType, finalProps, children) } } client.ParseError = ParseError return client }
[ "function", "jsnox", "(", "React", ")", "{", "var", "client", "=", "function", "jsnoxClient", "(", "componentType", ",", "props", ",", "children", ")", "{", "if", "(", "props", "&&", "typeof", "props", "===", "'object'", "&&", "props", ".", "hasOwnProperty", "(", "'$renderIf'", ")", ")", "{", "if", "(", "props", ".", "$renderIf", ")", "delete", "props", ".", "$renderIf", "else", "return", "null", "}", "if", "(", "Array", ".", "isArray", "(", "props", ")", "||", "typeof", "props", "!==", "'object'", ")", "{", "children", "=", "props", "props", "=", "null", "}", "var", "arg2IsReactElement", "=", "props", "&&", "React", ".", "isValidElement", "(", "props", ")", "var", "finalProps", "=", "props", "if", "(", "typeof", "componentType", "===", "'string'", "||", "!", "componentType", ")", "{", "var", "spec", "=", "parseTagSpec", "(", "componentType", ")", "componentType", "=", "spec", ".", "tagName", "finalProps", "=", "arg2IsReactElement", "?", "spec", ".", "props", ":", "extend", "(", "spec", ".", "props", ",", "props", ")", "}", "var", "args", "=", "protoSlice", ".", "call", "(", "arguments", ")", "if", "(", "args", ".", "length", ">", "3", "||", "arg2IsReactElement", ")", "{", "args", "[", "0", "]", "=", "componentType", "if", "(", "arg2IsReactElement", ")", "{", "args", ".", "splice", "(", "1", ",", "0", ",", "finalProps", "||", "null", ")", "}", "else", "{", "args", "[", "1", "]", "=", "finalProps", "}", "return", "React", ".", "createElement", ".", "apply", "(", "React", ",", "args", ")", "}", "else", "{", "return", "React", ".", "createElement", "(", "componentType", ",", "finalProps", ",", "children", ")", "}", "}", "client", ".", "ParseError", "=", "ParseError", "return", "client", "}" ]
Main exported function. Returns a "client", which is a function that can be used to compose ReactElement trees directly.
[ "Main", "exported", "function", ".", "Returns", "a", "client", "which", "is", "a", "function", "that", "can", "be", "used", "to", "compose", "ReactElement", "trees", "directly", "." ]
95f26f9f5dc90fea3c55aa67a7d3f090b5cc430d
https://github.com/af/JSnoX/blob/95f26f9f5dc90fea3c55aa67a7d3f090b5cc430d/jsnox.js#L102-L148
train
tschortsch/gulp-bootlint
index.js
function(file, lint, isError, isWarning, errorLocation) { var lintId = (isError) ? colors.bgRed(colors.white(lint.id)) : colors.bgYellow(colors.white(lint.id)); var message = ''; if (errorLocation) { message = file.path + ':' + (errorLocation.line + 1) + ':' + (errorLocation.column + 1) + ' ' + lintId + ' ' + lint.message; } else { message = file.path + ': ' + lintId + ' ' + lint.message; } if (isError) { log.error(message); } else { log.warning(message); } }
javascript
function(file, lint, isError, isWarning, errorLocation) { var lintId = (isError) ? colors.bgRed(colors.white(lint.id)) : colors.bgYellow(colors.white(lint.id)); var message = ''; if (errorLocation) { message = file.path + ':' + (errorLocation.line + 1) + ':' + (errorLocation.column + 1) + ' ' + lintId + ' ' + lint.message; } else { message = file.path + ': ' + lintId + ' ' + lint.message; } if (isError) { log.error(message); } else { log.warning(message); } }
[ "function", "(", "file", ",", "lint", ",", "isError", ",", "isWarning", ",", "errorLocation", ")", "{", "var", "lintId", "=", "(", "isError", ")", "?", "colors", ".", "bgRed", "(", "colors", ".", "white", "(", "lint", ".", "id", ")", ")", ":", "colors", ".", "bgYellow", "(", "colors", ".", "white", "(", "lint", ".", "id", ")", ")", ";", "var", "message", "=", "''", ";", "if", "(", "errorLocation", ")", "{", "message", "=", "file", ".", "path", "+", "':'", "+", "(", "errorLocation", ".", "line", "+", "1", ")", "+", "':'", "+", "(", "errorLocation", ".", "column", "+", "1", ")", "+", "' '", "+", "lintId", "+", "' '", "+", "lint", ".", "message", ";", "}", "else", "{", "message", "=", "file", ".", "path", "+", "': '", "+", "lintId", "+", "' '", "+", "lint", ".", "message", ";", "}", "if", "(", "isError", ")", "{", "log", ".", "error", "(", "message", ")", ";", "}", "else", "{", "log", ".", "warning", "(", "message", ")", ";", "}", "}" ]
Reporter function for linting errors and warnings. @param file Current file object. @param lint Current linting error. @param isError True if this is an error. @param isWarning True if this is a warning. @param errorLocation Error location object.
[ "Reporter", "function", "for", "linting", "errors", "and", "warnings", "." ]
6469fd16a4624d6ef4218f1323283d238fea61e2
https://github.com/tschortsch/gulp-bootlint/blob/6469fd16a4624d6ef4218f1323283d238fea61e2/index.js#L34-L48
train
tschortsch/gulp-bootlint
index.js
function(file, errorCount, warningCount) { if (errorCount > 0 || warningCount > 0) { var message = ''; if (errorCount > 0) { message += colors.red(errorCount + ' lint ' + (errorCount === 1 ? 'error' : 'errors')); } if (warningCount > 0) { if (errorCount > 0) { message += ' and '; } message += colors.yellow(warningCount + ' lint ' + (warningCount === 1 ? 'warning' : 'warnings')); } message += ' found in file ' + file.path; log.notice(message); } else { log.info(colors.green(file.path + ' is lint free!')); } }
javascript
function(file, errorCount, warningCount) { if (errorCount > 0 || warningCount > 0) { var message = ''; if (errorCount > 0) { message += colors.red(errorCount + ' lint ' + (errorCount === 1 ? 'error' : 'errors')); } if (warningCount > 0) { if (errorCount > 0) { message += ' and '; } message += colors.yellow(warningCount + ' lint ' + (warningCount === 1 ? 'warning' : 'warnings')); } message += ' found in file ' + file.path; log.notice(message); } else { log.info(colors.green(file.path + ' is lint free!')); } }
[ "function", "(", "file", ",", "errorCount", ",", "warningCount", ")", "{", "if", "(", "errorCount", ">", "0", "||", "warningCount", ">", "0", ")", "{", "var", "message", "=", "''", ";", "if", "(", "errorCount", ">", "0", ")", "{", "message", "+=", "colors", ".", "red", "(", "errorCount", "+", "' lint '", "+", "(", "errorCount", "===", "1", "?", "'error'", ":", "'errors'", ")", ")", ";", "}", "if", "(", "warningCount", ">", "0", ")", "{", "if", "(", "errorCount", ">", "0", ")", "{", "message", "+=", "' and '", ";", "}", "message", "+=", "colors", ".", "yellow", "(", "warningCount", "+", "' lint '", "+", "(", "warningCount", "===", "1", "?", "'warning'", ":", "'warnings'", ")", ")", ";", "}", "message", "+=", "' found in file '", "+", "file", ".", "path", ";", "log", ".", "notice", "(", "message", ")", ";", "}", "else", "{", "log", ".", "info", "(", "colors", ".", "green", "(", "file", ".", "path", "+", "' is lint free!'", ")", ")", ";", "}", "}" ]
Reporter function for linting summary. @param file File which was linted. @param errorCount Total count of errors in file. @param warningCount Total count of warnings in file.
[ "Reporter", "function", "for", "linting", "summary", "." ]
6469fd16a4624d6ef4218f1323283d238fea61e2
https://github.com/tschortsch/gulp-bootlint/blob/6469fd16a4624d6ef4218f1323283d238fea61e2/index.js#L57-L75
train
cazala/mnist
src/mnist.js
shuffle
function shuffle(v) { for (var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x); return v; }
javascript
function shuffle(v) { for (var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x); return v; }
[ "function", "shuffle", "(", "v", ")", "{", "for", "(", "var", "j", ",", "x", ",", "i", "=", "v", ".", "length", ";", "i", ";", "j", "=", "parseInt", "(", "Math", ".", "random", "(", ")", "*", "i", ")", ",", "x", "=", "v", "[", "--", "i", "]", ",", "v", "[", "i", "]", "=", "v", "[", "j", "]", ",", "v", "[", "j", "]", "=", "x", ")", ";", "return", "v", ";", "}" ]
+ Jonas Raoni Soares Silva @ http://jsfromhell.com/array/shuffle [rev. #1]
[ "+", "Jonas", "Raoni", "Soares", "Silva" ]
76157793a26e2eed9313a6cde6ee60d8167a04fd
https://github.com/cazala/mnist/blob/76157793a26e2eed9313a6cde6ee60d8167a04fd/src/mnist.js#L190-L193
train
cssobj/cssobj
dist/cssobj.amd.js
_assign
function _assign (target, source) { var s, from, key; var to = Object(target); for (s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (key in from) { if (own(from, key)) { to[key] = from[key]; } } } return to }
javascript
function _assign (target, source) { var s, from, key; var to = Object(target); for (s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (key in from) { if (own(from, key)) { to[key] = from[key]; } } } return to }
[ "function", "_assign", "(", "target", ",", "source", ")", "{", "var", "s", ",", "from", ",", "key", ";", "var", "to", "=", "Object", "(", "target", ")", ";", "for", "(", "s", "=", "1", ";", "s", "<", "arguments", ".", "length", ";", "s", "++", ")", "{", "from", "=", "Object", "(", "arguments", "[", "s", "]", ")", ";", "for", "(", "key", "in", "from", ")", "{", "if", "(", "own", "(", "from", ",", "key", ")", ")", "{", "to", "[", "key", "]", "=", "from", "[", "key", "]", ";", "}", "}", "}", "return", "to", "}" ]
Object.assgin polyfill
[ "Object", ".", "assgin", "polyfill" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L45-L57
train
cssobj/cssobj
dist/cssobj.amd.js
splitSelector
function splitSelector (sel, splitter, inBracket) { if (sel.indexOf(splitter) < 0) return [sel] for (var c, i = 0, n = 0, instr = '', prev = 0, d = []; c = sel.charAt(i); i++) { if (instr) { if (c == instr && sel.charAt(i-1)!='\\') instr = ''; continue } if (c == '"' || c == '\'') instr = c; /* istanbul ignore if */ if(!inBracket){ if (c == '(' || c == '[') n++; if (c == ')' || c == ']') n--; } if (!n && c == splitter) d.push(sel.substring(prev, i)), prev = i + 1; } return d.concat(sel.substring(prev)) }
javascript
function splitSelector (sel, splitter, inBracket) { if (sel.indexOf(splitter) < 0) return [sel] for (var c, i = 0, n = 0, instr = '', prev = 0, d = []; c = sel.charAt(i); i++) { if (instr) { if (c == instr && sel.charAt(i-1)!='\\') instr = ''; continue } if (c == '"' || c == '\'') instr = c; /* istanbul ignore if */ if(!inBracket){ if (c == '(' || c == '[') n++; if (c == ')' || c == ']') n--; } if (!n && c == splitter) d.push(sel.substring(prev, i)), prev = i + 1; } return d.concat(sel.substring(prev)) }
[ "function", "splitSelector", "(", "sel", ",", "splitter", ",", "inBracket", ")", "{", "if", "(", "sel", ".", "indexOf", "(", "splitter", ")", "<", "0", ")", "return", "[", "sel", "]", "for", "(", "var", "c", ",", "i", "=", "0", ",", "n", "=", "0", ",", "instr", "=", "''", ",", "prev", "=", "0", ",", "d", "=", "[", "]", ";", "c", "=", "sel", ".", "charAt", "(", "i", ")", ";", "i", "++", ")", "{", "if", "(", "instr", ")", "{", "if", "(", "c", "==", "instr", "&&", "sel", ".", "charAt", "(", "i", "-", "1", ")", "!=", "'\\\\'", ")", "\\\\", "instr", "=", "''", ";", "}", "continue", "if", "(", "c", "==", "'\"'", "||", "c", "==", "'\\''", ")", "\\'", "instr", "=", "c", ";", "}", "if", "(", "!", "inBracket", ")", "{", "if", "(", "c", "==", "'('", "||", "c", "==", "'['", ")", "n", "++", ";", "if", "(", "c", "==", "')'", "||", "c", "==", "']'", ")", "n", "--", ";", "}", "}" ]
split selector with splitter, aware of css attributes
[ "split", "selector", "with", "splitter", "aware", "of", "css", "attributes" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L162-L178
train
cssobj/cssobj
dist/cssobj.amd.js
isIterable
function isIterable (v) { return type.call(v) == OBJECT || type.call(v) == ARRAY }
javascript
function isIterable (v) { return type.call(v) == OBJECT || type.call(v) == ARRAY }
[ "function", "isIterable", "(", "v", ")", "{", "return", "type", ".", "call", "(", "v", ")", "==", "OBJECT", "||", "type", ".", "call", "(", "v", ")", "==", "ARRAY", "}" ]
only array, object now treated as iterable
[ "only", "array", "object", "now", "treated", "as", "iterable" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L202-L204
train
cssobj/cssobj
dist/cssobj.amd.js
createDOM
function createDOM (rootDoc, id, option) { var el = rootDoc.getElementById(id); var head = rootDoc.getElementsByTagName('head')[0]; if(el) { if(option.append) return el el.parentNode && el.parentNode.removeChild(el); } el = rootDoc.createElement('style'); head.appendChild(el); el.setAttribute('id', id); if (option.attrs) for (var i in option.attrs) { el.setAttribute(i, option.attrs[i]); } return el }
javascript
function createDOM (rootDoc, id, option) { var el = rootDoc.getElementById(id); var head = rootDoc.getElementsByTagName('head')[0]; if(el) { if(option.append) return el el.parentNode && el.parentNode.removeChild(el); } el = rootDoc.createElement('style'); head.appendChild(el); el.setAttribute('id', id); if (option.attrs) for (var i in option.attrs) { el.setAttribute(i, option.attrs[i]); } return el }
[ "function", "createDOM", "(", "rootDoc", ",", "id", ",", "option", ")", "{", "var", "el", "=", "rootDoc", ".", "getElementById", "(", "id", ")", ";", "var", "head", "=", "rootDoc", ".", "getElementsByTagName", "(", "'head'", ")", "[", "0", "]", ";", "if", "(", "el", ")", "{", "if", "(", "option", ".", "append", ")", "return", "el", "el", ".", "parentNode", "&&", "el", ".", "parentNode", ".", "removeChild", "(", "el", ")", ";", "}", "el", "=", "rootDoc", ".", "createElement", "(", "'style'", ")", ";", "head", ".", "appendChild", "(", "el", ")", ";", "el", ".", "setAttribute", "(", "'id'", ",", "id", ")", ";", "if", "(", "option", ".", "attrs", ")", "for", "(", "var", "i", "in", "option", ".", "attrs", ")", "{", "el", ".", "setAttribute", "(", "i", ",", "option", ".", "attrs", "[", "i", "]", ")", ";", "}", "return", "el", "}" ]
plugin for cssobj
[ "plugin", "for", "cssobj" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L567-L582
train
cssobj/cssobj
dist/cssobj.amd.js
prefixProp
function prefixProp (name, inCSS) { // $prop will skip if(name[0]=='$') return '' // find name and cache the name for next time use var retName = cssProps[ name ] || ( cssProps[ name ] = vendorPropName( name ) || name); return inCSS // if hasPrefix in prop ? dashify(cssPrefixesReg.test(retName) ? capitalize(retName) : name=='float' && name || retName) // fix float in CSS, avoid return cssFloat : retName }
javascript
function prefixProp (name, inCSS) { // $prop will skip if(name[0]=='$') return '' // find name and cache the name for next time use var retName = cssProps[ name ] || ( cssProps[ name ] = vendorPropName( name ) || name); return inCSS // if hasPrefix in prop ? dashify(cssPrefixesReg.test(retName) ? capitalize(retName) : name=='float' && name || retName) // fix float in CSS, avoid return cssFloat : retName }
[ "function", "prefixProp", "(", "name", ",", "inCSS", ")", "{", "if", "(", "name", "[", "0", "]", "==", "'$'", ")", "return", "''", "var", "retName", "=", "cssProps", "[", "name", "]", "||", "(", "cssProps", "[", "name", "]", "=", "vendorPropName", "(", "name", ")", "||", "name", ")", ";", "return", "inCSS", "?", "dashify", "(", "cssPrefixesReg", ".", "test", "(", "retName", ")", "?", "capitalize", "(", "retName", ")", ":", "name", "==", "'float'", "&&", "name", "||", "retName", ")", ":", "retName", "}" ]
apply prop to get right vendor prefix inCSS false=camelcase; true=dashed
[ "apply", "prop", "to", "get", "right", "vendor", "prefix", "inCSS", "false", "=", "camelcase", ";", "true", "=", "dashed" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L703-L712
train
cssobj/cssobj
dist/cssobj.amd.js
setCSSProperty
function setCSSProperty (styleObj, prop, val) { var value; var important = /^(.*)!(important)\s*$/i.exec(val); var propCamel = prefixProp(prop); var propDash = prefixProp(prop, true); if(important) { value = important[1]; important = important[2]; if(styleObj.setProperty) styleObj.setProperty(propDash, value, important); else { // for old IE, cssText is writable, and below is valid for contain !important // don't use styleObj.setAttribute since it's not set important // should do: delete styleObj[propCamel], but not affect result // only work on <= IE8: s.style['FONT-SIZE'] = '12px!important' styleObj[propDash.toUpperCase()] = val; // refresh cssText, the whole rule! styleObj.cssText = styleObj.cssText; } } else { styleObj[propCamel] = val; } }
javascript
function setCSSProperty (styleObj, prop, val) { var value; var important = /^(.*)!(important)\s*$/i.exec(val); var propCamel = prefixProp(prop); var propDash = prefixProp(prop, true); if(important) { value = important[1]; important = important[2]; if(styleObj.setProperty) styleObj.setProperty(propDash, value, important); else { // for old IE, cssText is writable, and below is valid for contain !important // don't use styleObj.setAttribute since it's not set important // should do: delete styleObj[propCamel], but not affect result // only work on <= IE8: s.style['FONT-SIZE'] = '12px!important' styleObj[propDash.toUpperCase()] = val; // refresh cssText, the whole rule! styleObj.cssText = styleObj.cssText; } } else { styleObj[propCamel] = val; } }
[ "function", "setCSSProperty", "(", "styleObj", ",", "prop", ",", "val", ")", "{", "var", "value", ";", "var", "important", "=", "/", "^(.*)!(important)\\s*$", "/", "i", ".", "exec", "(", "val", ")", ";", "var", "propCamel", "=", "prefixProp", "(", "prop", ")", ";", "var", "propDash", "=", "prefixProp", "(", "prop", ",", "true", ")", ";", "if", "(", "important", ")", "{", "value", "=", "important", "[", "1", "]", ";", "important", "=", "important", "[", "2", "]", ";", "if", "(", "styleObj", ".", "setProperty", ")", "styleObj", ".", "setProperty", "(", "propDash", ",", "value", ",", "important", ")", ";", "else", "{", "styleObj", "[", "propDash", ".", "toUpperCase", "(", ")", "]", "=", "val", ";", "styleObj", ".", "cssText", "=", "styleObj", ".", "cssText", ";", "}", "}", "else", "{", "styleObj", "[", "propCamel", "]", "=", "val", ";", "}", "}" ]
Get value and important flag from value str @param {CSSStyleRule} rule css style rule object @param {string} prop prop to set @param {string} val value string
[ "Get", "value", "and", "important", "flag", "from", "value", "str" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L720-L742
train
cssobj/cssobj
dist/cssobj.amd.js
function (node, selText, cssText) { if(!cssText) return // get parent to add var parent = getParent(node); var parentRule = node.parentRule; if (validParent(node)) return node.omRule = addCSSRule(parent, selText, cssText, node) else if (parentRule) { // for old IE not support @media, check mediaEnabled, add child nodes if (parentRule.mediaEnabled) { [].concat(node.omRule).forEach(removeOneRule); return node.omRule = addCSSRule(parent, selText, cssText, node) } else if (node.omRule) { node.omRule.forEach(removeOneRule); delete node.omRule; } } }
javascript
function (node, selText, cssText) { if(!cssText) return // get parent to add var parent = getParent(node); var parentRule = node.parentRule; if (validParent(node)) return node.omRule = addCSSRule(parent, selText, cssText, node) else if (parentRule) { // for old IE not support @media, check mediaEnabled, add child nodes if (parentRule.mediaEnabled) { [].concat(node.omRule).forEach(removeOneRule); return node.omRule = addCSSRule(parent, selText, cssText, node) } else if (node.omRule) { node.omRule.forEach(removeOneRule); delete node.omRule; } } }
[ "function", "(", "node", ",", "selText", ",", "cssText", ")", "{", "if", "(", "!", "cssText", ")", "return", "var", "parent", "=", "getParent", "(", "node", ")", ";", "var", "parentRule", "=", "node", ".", "parentRule", ";", "if", "(", "validParent", "(", "node", ")", ")", "return", "node", ".", "omRule", "=", "addCSSRule", "(", "parent", ",", "selText", ",", "cssText", ",", "node", ")", "else", "if", "(", "parentRule", ")", "{", "if", "(", "parentRule", ".", "mediaEnabled", ")", "{", "[", "]", ".", "concat", "(", "node", ".", "omRule", ")", ".", "forEach", "(", "removeOneRule", ")", ";", "return", "node", ".", "omRule", "=", "addCSSRule", "(", "parent", ",", "selText", ",", "cssText", ",", "node", ")", "}", "else", "if", "(", "node", ".", "omRule", ")", "{", "node", ".", "omRule", ".", "forEach", "(", "removeOneRule", ")", ";", "delete", "node", ".", "omRule", ";", "}", "}", "}" ]
helper function for addNormalrule
[ "helper", "function", "for", "addNormalrule" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L825-L842
train
cssobj/cssobj
dist/cssobj.amd.js
cssobj$1
function cssobj$1 (obj, config, state) { config = config || {}; var local = config.local; config.local = !local ? {space: ''} : local && typeof local === 'object' ? local : {}; config.plugins = [].concat( config.plugins || [], cssobj_plugin_selector_localize(config.local), cssobj_plugin_post_cssom(config.cssom) ); return cssobj(config)(obj, state) }
javascript
function cssobj$1 (obj, config, state) { config = config || {}; var local = config.local; config.local = !local ? {space: ''} : local && typeof local === 'object' ? local : {}; config.plugins = [].concat( config.plugins || [], cssobj_plugin_selector_localize(config.local), cssobj_plugin_post_cssom(config.cssom) ); return cssobj(config)(obj, state) }
[ "function", "cssobj$1", "(", "obj", ",", "config", ",", "state", ")", "{", "config", "=", "config", "||", "{", "}", ";", "var", "local", "=", "config", ".", "local", ";", "config", ".", "local", "=", "!", "local", "?", "{", "space", ":", "''", "}", ":", "local", "&&", "typeof", "local", "===", "'object'", "?", "local", ":", "{", "}", ";", "config", ".", "plugins", "=", "[", "]", ".", "concat", "(", "config", ".", "plugins", "||", "[", "]", ",", "cssobj_plugin_selector_localize", "(", "config", ".", "local", ")", ",", "cssobj_plugin_post_cssom", "(", "config", ".", "cssom", ")", ")", ";", "return", "cssobj", "(", "config", ")", "(", "obj", ",", "state", ")", "}" ]
cssobj is simply an intergration for cssobj-core, cssom
[ "cssobj", "is", "simply", "an", "intergration", "for", "cssobj", "-", "core", "cssom" ]
80f58c6fac72a0bbd9c1ba7c230d77be96909e1a
https://github.com/cssobj/cssobj/blob/80f58c6fac72a0bbd9c1ba7c230d77be96909e1a/dist/cssobj.amd.js#L1102-L1117
train
tnhu/jsface
jsface.pointcut.js
wrap
function wrap(fn, before, after, advisor) { var ignoredKeys = { prototype: 1 }; function wrapper() { var _before = wrapper[BEFORE], bLen = _before.length, _after = wrapper[AFTER], aLen = _after.length, _fn = wrapper[ORIGIN], ret, r; // Invoke before, if it returns { $skip: true } then skip fn() and after() and returns $data while (bLen--) { r = _before[bLen].apply(this, arguments); if (mapOrNil(r) && r.$skip === true) { return r.$data; } } // Invoke fn, save return value ret = _fn.apply(this, arguments); while (aLen--) { r = _after[aLen].apply(this, arguments); if (mapOrNil(r) && r.$skip === true) { return ret; } } return ret; } // wrapper exists? reuse it if (fn[WRAPPER] === fn) { fn[BEFORE].push(before); fn[AFTER].push(after); fn[ADVISOR].push(advisor); return fn; } // create a reusable wrapper structure extend(wrapper, fn, 0, true); if (classOrNil(fn)) { wrapper.prototype = fn.prototype; // this destroys the origin of wrapper[ORIGIN], in theory, prototype.constructor should point // to the class constructor itself, but it's no harm to not let that happen // wrapper.prototype.constructor = wrapper; } wrapper[BEFORE] = [ before ]; wrapper[AFTER] = [ after ]; wrapper[ORIGIN] = fn; wrapper[ADVISOR] = [ advisor ]; wrapper[WRAPPER] = wrapper; wrapper.$super = fn.$super; wrapper.$superp = fn.$superp; return wrapper; }
javascript
function wrap(fn, before, after, advisor) { var ignoredKeys = { prototype: 1 }; function wrapper() { var _before = wrapper[BEFORE], bLen = _before.length, _after = wrapper[AFTER], aLen = _after.length, _fn = wrapper[ORIGIN], ret, r; // Invoke before, if it returns { $skip: true } then skip fn() and after() and returns $data while (bLen--) { r = _before[bLen].apply(this, arguments); if (mapOrNil(r) && r.$skip === true) { return r.$data; } } // Invoke fn, save return value ret = _fn.apply(this, arguments); while (aLen--) { r = _after[aLen].apply(this, arguments); if (mapOrNil(r) && r.$skip === true) { return ret; } } return ret; } // wrapper exists? reuse it if (fn[WRAPPER] === fn) { fn[BEFORE].push(before); fn[AFTER].push(after); fn[ADVISOR].push(advisor); return fn; } // create a reusable wrapper structure extend(wrapper, fn, 0, true); if (classOrNil(fn)) { wrapper.prototype = fn.prototype; // this destroys the origin of wrapper[ORIGIN], in theory, prototype.constructor should point // to the class constructor itself, but it's no harm to not let that happen // wrapper.prototype.constructor = wrapper; } wrapper[BEFORE] = [ before ]; wrapper[AFTER] = [ after ]; wrapper[ORIGIN] = fn; wrapper[ADVISOR] = [ advisor ]; wrapper[WRAPPER] = wrapper; wrapper.$super = fn.$super; wrapper.$superp = fn.$superp; return wrapper; }
[ "function", "wrap", "(", "fn", ",", "before", ",", "after", ",", "advisor", ")", "{", "var", "ignoredKeys", "=", "{", "prototype", ":", "1", "}", ";", "function", "wrapper", "(", ")", "{", "var", "_before", "=", "wrapper", "[", "BEFORE", "]", ",", "bLen", "=", "_before", ".", "length", ",", "_after", "=", "wrapper", "[", "AFTER", "]", ",", "aLen", "=", "_after", ".", "length", ",", "_fn", "=", "wrapper", "[", "ORIGIN", "]", ",", "ret", ",", "r", ";", "while", "(", "bLen", "--", ")", "{", "r", "=", "_before", "[", "bLen", "]", ".", "apply", "(", "this", ",", "arguments", ")", ";", "if", "(", "mapOrNil", "(", "r", ")", "&&", "r", ".", "$skip", "===", "true", ")", "{", "return", "r", ".", "$data", ";", "}", "}", "ret", "=", "_fn", ".", "apply", "(", "this", ",", "arguments", ")", ";", "while", "(", "aLen", "--", ")", "{", "r", "=", "_after", "[", "aLen", "]", ".", "apply", "(", "this", ",", "arguments", ")", ";", "if", "(", "mapOrNil", "(", "r", ")", "&&", "r", ".", "$skip", "===", "true", ")", "{", "return", "ret", ";", "}", "}", "return", "ret", ";", "}", "if", "(", "fn", "[", "WRAPPER", "]", "===", "fn", ")", "{", "fn", "[", "BEFORE", "]", ".", "push", "(", "before", ")", ";", "fn", "[", "AFTER", "]", ".", "push", "(", "after", ")", ";", "fn", "[", "ADVISOR", "]", ".", "push", "(", "advisor", ")", ";", "return", "fn", ";", "}", "extend", "(", "wrapper", ",", "fn", ",", "0", ",", "true", ")", ";", "if", "(", "classOrNil", "(", "fn", ")", ")", "{", "wrapper", ".", "prototype", "=", "fn", ".", "prototype", ";", "}", "wrapper", "[", "BEFORE", "]", "=", "[", "before", "]", ";", "wrapper", "[", "AFTER", "]", "=", "[", "after", "]", ";", "wrapper", "[", "ORIGIN", "]", "=", "fn", ";", "wrapper", "[", "ADVISOR", "]", "=", "[", "advisor", "]", ";", "wrapper", "[", "WRAPPER", "]", "=", "wrapper", ";", "wrapper", ".", "$super", "=", "fn", ".", "$super", ";", "wrapper", ".", "$superp", "=", "fn", ".", "$superp", ";", "return", "wrapper", ";", "}" ]
Wrap a function with before & after.
[ "Wrap", "a", "function", "with", "before", "&", "after", "." ]
2949e282f01f5bcbe08dffb38044aef64413c24a
https://github.com/tnhu/jsface/blob/2949e282f01f5bcbe08dffb38044aef64413c24a/jsface.pointcut.js#L25-L82
train
tnhu/jsface
jsface.pointcut.js
restore
function restore(fn, advisor) { var origin, index, len; if (fn && fn === fn[WRAPPER]) { if ( !advisor) { origin = fn[ORIGIN]; delete fn[ORIGIN]; delete fn[ADVISOR]; delete fn[BEFORE]; delete fn[AFTER]; delete fn[WRAPPER]; } else { index = len = fn[ADVISOR].length; while (index--) { if (fn[ADVISOR][index] === advisor) { break; } } if (index >= 0) { if (len === 1) { return restore(fn); } fn[ADVISOR].splice(index, 1); fn[BEFORE].splice(index, 1); fn[AFTER].splice(index, 1); } } } return origin; }
javascript
function restore(fn, advisor) { var origin, index, len; if (fn && fn === fn[WRAPPER]) { if ( !advisor) { origin = fn[ORIGIN]; delete fn[ORIGIN]; delete fn[ADVISOR]; delete fn[BEFORE]; delete fn[AFTER]; delete fn[WRAPPER]; } else { index = len = fn[ADVISOR].length; while (index--) { if (fn[ADVISOR][index] === advisor) { break; } } if (index >= 0) { if (len === 1) { return restore(fn); } fn[ADVISOR].splice(index, 1); fn[BEFORE].splice(index, 1); fn[AFTER].splice(index, 1); } } } return origin; }
[ "function", "restore", "(", "fn", ",", "advisor", ")", "{", "var", "origin", ",", "index", ",", "len", ";", "if", "(", "fn", "&&", "fn", "===", "fn", "[", "WRAPPER", "]", ")", "{", "if", "(", "!", "advisor", ")", "{", "origin", "=", "fn", "[", "ORIGIN", "]", ";", "delete", "fn", "[", "ORIGIN", "]", ";", "delete", "fn", "[", "ADVISOR", "]", ";", "delete", "fn", "[", "BEFORE", "]", ";", "delete", "fn", "[", "AFTER", "]", ";", "delete", "fn", "[", "WRAPPER", "]", ";", "}", "else", "{", "index", "=", "len", "=", "fn", "[", "ADVISOR", "]", ".", "length", ";", "while", "(", "index", "--", ")", "{", "if", "(", "fn", "[", "ADVISOR", "]", "[", "index", "]", "===", "advisor", ")", "{", "break", ";", "}", "}", "if", "(", "index", ">=", "0", ")", "{", "if", "(", "len", "===", "1", ")", "{", "return", "restore", "(", "fn", ")", ";", "}", "fn", "[", "ADVISOR", "]", ".", "splice", "(", "index", ",", "1", ")", ";", "fn", "[", "BEFORE", "]", ".", "splice", "(", "index", ",", "1", ")", ";", "fn", "[", "AFTER", "]", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "}", "}", "return", "origin", ";", "}" ]
Restore a function to its origin state. @return function's origin state
[ "Restore", "a", "function", "to", "its", "origin", "state", "." ]
2949e282f01f5bcbe08dffb38044aef64413c24a
https://github.com/tnhu/jsface/blob/2949e282f01f5bcbe08dffb38044aef64413c24a/jsface.pointcut.js#L88-L113
train
tnhu/jsface
jsface.js
deepFreeze
function deepFreeze(object) { var prop, propKey; Object.freeze(object); // first freeze the object for (propKey in object) { prop = object[propKey]; if (!object.hasOwnProperty(propKey) || (typeof prop !== 'object') || Object.isFrozen(prop)) { // If the object is on the prototype, not an object, or is already frozen, // skip it. Note that this might leave an unfrozen reference somewhere in the // object if there is an already frozen object containing an unfrozen object. continue; } deepFreeze(prop); // recursively call deepFreeze } }
javascript
function deepFreeze(object) { var prop, propKey; Object.freeze(object); // first freeze the object for (propKey in object) { prop = object[propKey]; if (!object.hasOwnProperty(propKey) || (typeof prop !== 'object') || Object.isFrozen(prop)) { // If the object is on the prototype, not an object, or is already frozen, // skip it. Note that this might leave an unfrozen reference somewhere in the // object if there is an already frozen object containing an unfrozen object. continue; } deepFreeze(prop); // recursively call deepFreeze } }
[ "function", "deepFreeze", "(", "object", ")", "{", "var", "prop", ",", "propKey", ";", "Object", ".", "freeze", "(", "object", ")", ";", "for", "(", "propKey", "in", "object", ")", "{", "prop", "=", "object", "[", "propKey", "]", ";", "if", "(", "!", "object", ".", "hasOwnProperty", "(", "propKey", ")", "||", "(", "typeof", "prop", "!==", "'object'", ")", "||", "Object", ".", "isFrozen", "(", "prop", ")", ")", "{", "continue", ";", "}", "deepFreeze", "(", "prop", ")", ";", "}", "}" ]
To make object fully immutable, freeze each object inside it. @param object to deep freeze
[ "To", "make", "object", "fully", "immutable", "freeze", "each", "object", "inside", "it", "." ]
2949e282f01f5bcbe08dffb38044aef64413c24a
https://github.com/tnhu/jsface/blob/2949e282f01f5bcbe08dffb38044aef64413c24a/jsface.js#L89-L103
train
victorherraiz/cloud-config-client
index.js
getAuth
function getAuth (auth, url) { if (auth && auth.user && auth.pass) { return auth.user + ':' + auth.pass } return url.auth }
javascript
function getAuth (auth, url) { if (auth && auth.user && auth.pass) { return auth.user + ':' + auth.pass } return url.auth }
[ "function", "getAuth", "(", "auth", ",", "url", ")", "{", "if", "(", "auth", "&&", "auth", ".", "user", "&&", "auth", ".", "pass", ")", "{", "return", "auth", ".", "user", "+", "':'", "+", "auth", ".", "pass", "}", "return", "url", ".", "auth", "}" ]
Handle load response @callback loadCallback @param {?Error} error - whether there was an error retrieving configurations @param {module:Config~Config} config - configuration object instance Retrieve basic auth from options Priority: 1. Defined in options 2. Coded as basic auth in url @param {module:CloudConfigClient~Auth} auth - auth configuration. @param {URL} url - endpoint. @returns {string} basic auth.
[ "Handle", "load", "response" ]
33d98bc419f014c94a49bd50abddc33aca858fc5
https://github.com/victorherraiz/cloud-config-client/blob/33d98bc419f014c94a49bd50abddc33aca858fc5/index.js#L55-L60
train
victorherraiz/cloud-config-client
index.js
getPath
function getPath (path, name, profiles, label) { const profilesStr = buildProfilesString(profiles) return (path.endsWith('/') ? path : path + '/') + encodeURIComponent(name) + '/' + encodeURIComponent(profilesStr) + (label ? '/' + encodeURIComponent(label) : '') }
javascript
function getPath (path, name, profiles, label) { const profilesStr = buildProfilesString(profiles) return (path.endsWith('/') ? path : path + '/') + encodeURIComponent(name) + '/' + encodeURIComponent(profilesStr) + (label ? '/' + encodeURIComponent(label) : '') }
[ "function", "getPath", "(", "path", ",", "name", ",", "profiles", ",", "label", ")", "{", "const", "profilesStr", "=", "buildProfilesString", "(", "profiles", ")", "return", "(", "path", ".", "endsWith", "(", "'/'", ")", "?", "path", ":", "path", "+", "'/'", ")", "+", "encodeURIComponent", "(", "name", ")", "+", "'/'", "+", "encodeURIComponent", "(", "profilesStr", ")", "+", "(", "label", "?", "'/'", "+", "encodeURIComponent", "(", "label", ")", ":", "''", ")", "}" ]
Build spring config endpoint path @param {string} path - host base path @param {string} name - application name @param {(string|string[])} [profiles] - list of profiles, if none specified will use 'default' @param {string} [label] - environment id @returns {string} spring config endpoint
[ "Build", "spring", "config", "endpoint", "path" ]
33d98bc419f014c94a49bd50abddc33aca858fc5
https://github.com/victorherraiz/cloud-config-client/blob/33d98bc419f014c94a49bd50abddc33aca858fc5/index.js#L86-L93
train
victorherraiz/cloud-config-client
index.js
loadWithCallback
function loadWithCallback (options, callback) { const endpoint = options.endpoint ? URL.parse(options.endpoint) : DEFAULT_URL const name = options.name || options.application const context = options.context const client = endpoint.protocol === 'https:' ? https : http client.request({ protocol: endpoint.protocol, hostname: endpoint.hostname, port: endpoint.port, path: getPath(endpoint.path, name, options.profiles, options.label), auth: getAuth(options.auth, endpoint), rejectUnauthorized: options.rejectUnauthorized !== false, agent: options.agent }, (res) => { if (res.statusCode !== 200) { // OK res.resume() // it consumes response return callback(new Error('Invalid response: ' + res.statusCode)) } let response = '' res.setEncoding('utf8') res.on('data', (data) => { response += data }) res.on('end', () => { try { const body = JSON.parse(response) callback(null, new Config(body, context)) } catch (e) { callback(e) } }) }).on('error', callback).end() }
javascript
function loadWithCallback (options, callback) { const endpoint = options.endpoint ? URL.parse(options.endpoint) : DEFAULT_URL const name = options.name || options.application const context = options.context const client = endpoint.protocol === 'https:' ? https : http client.request({ protocol: endpoint.protocol, hostname: endpoint.hostname, port: endpoint.port, path: getPath(endpoint.path, name, options.profiles, options.label), auth: getAuth(options.auth, endpoint), rejectUnauthorized: options.rejectUnauthorized !== false, agent: options.agent }, (res) => { if (res.statusCode !== 200) { // OK res.resume() // it consumes response return callback(new Error('Invalid response: ' + res.statusCode)) } let response = '' res.setEncoding('utf8') res.on('data', (data) => { response += data }) res.on('end', () => { try { const body = JSON.parse(response) callback(null, new Config(body, context)) } catch (e) { callback(e) } }) }).on('error', callback).end() }
[ "function", "loadWithCallback", "(", "options", ",", "callback", ")", "{", "const", "endpoint", "=", "options", ".", "endpoint", "?", "URL", ".", "parse", "(", "options", ".", "endpoint", ")", ":", "DEFAULT_URL", "const", "name", "=", "options", ".", "name", "||", "options", ".", "application", "const", "context", "=", "options", ".", "context", "const", "client", "=", "endpoint", ".", "protocol", "===", "'https:'", "?", "https", ":", "http", "client", ".", "request", "(", "{", "protocol", ":", "endpoint", ".", "protocol", ",", "hostname", ":", "endpoint", ".", "hostname", ",", "port", ":", "endpoint", ".", "port", ",", "path", ":", "getPath", "(", "endpoint", ".", "path", ",", "name", ",", "options", ".", "profiles", ",", "options", ".", "label", ")", ",", "auth", ":", "getAuth", "(", "options", ".", "auth", ",", "endpoint", ")", ",", "rejectUnauthorized", ":", "options", ".", "rejectUnauthorized", "!==", "false", ",", "agent", ":", "options", ".", "agent", "}", ",", "(", "res", ")", "=>", "{", "if", "(", "res", ".", "statusCode", "!==", "200", ")", "{", "res", ".", "resume", "(", ")", "return", "callback", "(", "new", "Error", "(", "'Invalid response: '", "+", "res", ".", "statusCode", ")", ")", "}", "let", "response", "=", "''", "res", ".", "setEncoding", "(", "'utf8'", ")", "res", ".", "on", "(", "'data'", ",", "(", "data", ")", "=>", "{", "response", "+=", "data", "}", ")", "res", ".", "on", "(", "'end'", ",", "(", ")", "=>", "{", "try", "{", "const", "body", "=", "JSON", ".", "parse", "(", "response", ")", "callback", "(", "null", ",", "new", "Config", "(", "body", ",", "context", ")", ")", "}", "catch", "(", "e", ")", "{", "callback", "(", "e", ")", "}", "}", ")", "}", ")", ".", "on", "(", "'error'", ",", "callback", ")", ".", "end", "(", ")", "}" ]
Load configuration with callback @param {module:CloudConfigClient~Options} options - spring client configuration options @param {module:CloudConfigClient~loadCallback} [callback] - load callback
[ "Load", "configuration", "with", "callback" ]
33d98bc419f014c94a49bd50abddc33aca858fc5
https://github.com/victorherraiz/cloud-config-client/blob/33d98bc419f014c94a49bd50abddc33aca858fc5/index.js#L101-L134
train
victorherraiz/cloud-config-client
index.js
loadWithPromise
function loadWithPromise (options) { return new Promise((resolve, reject) => { loadWithCallback(options, (error, config) => { if (error) { reject(error) } else { resolve(config) } }) }) }
javascript
function loadWithPromise (options) { return new Promise((resolve, reject) => { loadWithCallback(options, (error, config) => { if (error) { reject(error) } else { resolve(config) } }) }) }
[ "function", "loadWithPromise", "(", "options", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "loadWithCallback", "(", "options", ",", "(", "error", ",", "config", ")", "=>", "{", "if", "(", "error", ")", "{", "reject", "(", "error", ")", "}", "else", "{", "resolve", "(", "config", ")", "}", "}", ")", "}", ")", "}" ]
Wrap loadWithCallback with Promise @param {module:CloudConfigClient~Options} options - spring client configuration options @returns {Promise<module:Config~Config, Error>} promise handler
[ "Wrap", "loadWithCallback", "with", "Promise" ]
33d98bc419f014c94a49bd50abddc33aca858fc5
https://github.com/victorherraiz/cloud-config-client/blob/33d98bc419f014c94a49bd50abddc33aca858fc5/index.js#L142-L152
train
SvSchmidt/linqjs
dist/linq.system.es5.js
_MinHeap
function _MinHeap(elements) { var comparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultComparator; _classCallCheck(this, _MinHeap); __assertArray(elements); __assertFunction(comparator); // we do not wrap elements here since the heapify function does that the moment it encounters elements this.__elements = elements; // create comparator that works on heap elements (it also ensures equal elements remain in original order) this.__comparator = function (a, b) { var res = comparator(a.__value, b.__value); if (res !== 0) { return res; } return defaultComparator(a.__index, b.__index); }; // create heap ordering this.__createHeap(this.__elements, this.__comparator); }
javascript
function _MinHeap(elements) { var comparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultComparator; _classCallCheck(this, _MinHeap); __assertArray(elements); __assertFunction(comparator); // we do not wrap elements here since the heapify function does that the moment it encounters elements this.__elements = elements; // create comparator that works on heap elements (it also ensures equal elements remain in original order) this.__comparator = function (a, b) { var res = comparator(a.__value, b.__value); if (res !== 0) { return res; } return defaultComparator(a.__index, b.__index); }; // create heap ordering this.__createHeap(this.__elements, this.__comparator); }
[ "function", "_MinHeap", "(", "elements", ")", "{", "var", "comparator", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "defaultComparator", ";", "_classCallCheck", "(", "this", ",", "_MinHeap", ")", ";", "__assertArray", "(", "elements", ")", ";", "__assertFunction", "(", "comparator", ")", ";", "this", ".", "__elements", "=", "elements", ";", "this", ".", "__comparator", "=", "function", "(", "a", ",", "b", ")", "{", "var", "res", "=", "comparator", "(", "a", ".", "__value", ",", "b", ".", "__value", ")", ";", "if", "(", "res", "!==", "0", ")", "{", "return", "res", ";", "}", "return", "defaultComparator", "(", "a", ".", "__index", ",", "b", ".", "__index", ")", ";", "}", ";", "this", ".", "__createHeap", "(", "this", ".", "__elements", ",", "this", ".", "__comparator", ")", ";", "}" ]
Creates the heap from the array of elements with the given comparator function. @param elements Array with elements to create the heap from. Will be modified in place for heap logic. @param comparator Comparator function (same as the one for Array.sort()).
[ "Creates", "the", "heap", "from", "the", "array", "of", "elements", "with", "the", "given", "comparator", "function", "." ]
e89561cd9c5d3f9f0b689711872d499b2b1a1e5a
https://github.com/SvSchmidt/linqjs/blob/e89561cd9c5d3f9f0b689711872d499b2b1a1e5a/dist/linq.system.es5.js#L2911-L2930
train
Bartvds/joi-assert
lib/index.js
assert
function assert(value, schema, message, vars) { return assertion(value, schema, message, vars, (internals.debug ? null : assert)); }
javascript
function assert(value, schema, message, vars) { return assertion(value, schema, message, vars, (internals.debug ? null : assert)); }
[ "function", "assert", "(", "value", ",", "schema", ",", "message", ",", "vars", ")", "{", "return", "assertion", "(", "value", ",", "schema", ",", "message", ",", "vars", ",", "(", "internals", ".", "debug", "?", "null", ":", "assert", ")", ")", ";", "}" ]
export API core assertion method
[ "export", "API", "core", "assertion", "method" ]
a4a920ad79a9b40ae38437244a5915e6cb76f3b3
https://github.com/Bartvds/joi-assert/blob/a4a920ad79a9b40ae38437244a5915e6cb76f3b3/lib/index.js#L8-L10
train
flohil/wdio-workflo
dist/lib/helpers.js
tolerancesToString
function tolerancesToString(values, tolerances) { let str = '{'; const props = []; if (typeof values !== 'object' && typeof values !== 'undefined') { if (typeof tolerances === 'undefined') { return values; } else if (typeof tolerances !== 'object') { const tolerance = Math.abs(tolerances); return `[${Math.max(values - tolerance, 0)}, ${Math.max(values + tolerance, 0)}]`; } } else { for (const p in values) { if (values.hasOwnProperty(p)) { const value = values[p]; let valueStr = ''; if (tolerances && typeof tolerances[p] !== 'undefined' && tolerances[p] !== 0) { const tolerance = Math.abs(tolerances[p]); valueStr = `[${Math.max(value - tolerance, 0)}, ${Math.max(value + tolerance, 0)}]`; } else { valueStr = `${value}`; } props.push(`${p}: ${valueStr}`); } } } str += props.join(', '); return `${str}}`; }
javascript
function tolerancesToString(values, tolerances) { let str = '{'; const props = []; if (typeof values !== 'object' && typeof values !== 'undefined') { if (typeof tolerances === 'undefined') { return values; } else if (typeof tolerances !== 'object') { const tolerance = Math.abs(tolerances); return `[${Math.max(values - tolerance, 0)}, ${Math.max(values + tolerance, 0)}]`; } } else { for (const p in values) { if (values.hasOwnProperty(p)) { const value = values[p]; let valueStr = ''; if (tolerances && typeof tolerances[p] !== 'undefined' && tolerances[p] !== 0) { const tolerance = Math.abs(tolerances[p]); valueStr = `[${Math.max(value - tolerance, 0)}, ${Math.max(value + tolerance, 0)}]`; } else { valueStr = `${value}`; } props.push(`${p}: ${valueStr}`); } } } str += props.join(', '); return `${str}}`; }
[ "function", "tolerancesToString", "(", "values", ",", "tolerances", ")", "{", "let", "str", "=", "'{'", ";", "const", "props", "=", "[", "]", ";", "if", "(", "typeof", "values", "!==", "'object'", "&&", "typeof", "values", "!==", "'undefined'", ")", "{", "if", "(", "typeof", "tolerances", "===", "'undefined'", ")", "{", "return", "values", ";", "}", "else", "if", "(", "typeof", "tolerances", "!==", "'object'", ")", "{", "const", "tolerance", "=", "Math", ".", "abs", "(", "tolerances", ")", ";", "return", "`", "${", "Math", ".", "max", "(", "values", "-", "tolerance", ",", "0", ")", "}", "${", "Math", ".", "max", "(", "values", "+", "tolerance", ",", "0", ")", "}", "`", ";", "}", "}", "else", "{", "for", "(", "const", "p", "in", "values", ")", "{", "if", "(", "values", ".", "hasOwnProperty", "(", "p", ")", ")", "{", "const", "value", "=", "values", "[", "p", "]", ";", "let", "valueStr", "=", "''", ";", "if", "(", "tolerances", "&&", "typeof", "tolerances", "[", "p", "]", "!==", "'undefined'", "&&", "tolerances", "[", "p", "]", "!==", "0", ")", "{", "const", "tolerance", "=", "Math", ".", "abs", "(", "tolerances", "[", "p", "]", ")", ";", "valueStr", "=", "`", "${", "Math", ".", "max", "(", "value", "-", "tolerance", ",", "0", ")", "}", "${", "Math", ".", "max", "(", "value", "+", "tolerance", ",", "0", ")", "}", "`", ";", "}", "else", "{", "valueStr", "=", "`", "${", "value", "}", "`", ";", "}", "props", ".", "push", "(", "`", "${", "p", "}", "${", "valueStr", "}", "`", ")", ";", "}", "}", "}", "str", "+=", "props", ".", "join", "(", "', '", ")", ";", "return", "`", "${", "str", "}", "`", ";", "}" ]
Prints values with tolerances as a string. @param values a number or an object with values of type number @param tolerances a number or an object with values of type number
[ "Prints", "values", "with", "tolerances", "as", "a", "string", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/helpers.js#L9-L39
train
SvSchmidt/linqjs
dist/linq.es6.js
isKeyComparator
function isKeyComparator(arg) { let result = __getParameterCount(arg) === 2; const first = self.first(); try { const key = keySelector(first); // if this is a key comparator, it must return truthy values for equal values and falsy ones if they're different result = result && arg(key, key) && !arg(key, {}); } catch (err) { // if the function throws an error for values, it can't be a keyComparator result = false; } return result; }
javascript
function isKeyComparator(arg) { let result = __getParameterCount(arg) === 2; const first = self.first(); try { const key = keySelector(first); // if this is a key comparator, it must return truthy values for equal values and falsy ones if they're different result = result && arg(key, key) && !arg(key, {}); } catch (err) { // if the function throws an error for values, it can't be a keyComparator result = false; } return result; }
[ "function", "isKeyComparator", "(", "arg", ")", "{", "let", "result", "=", "__getParameterCount", "(", "arg", ")", "===", "2", ";", "const", "first", "=", "self", ".", "first", "(", ")", ";", "try", "{", "const", "key", "=", "keySelector", "(", "first", ")", ";", "result", "=", "result", "&&", "arg", "(", "key", ",", "key", ")", "&&", "!", "arg", "(", "key", ",", "{", "}", ")", ";", "}", "catch", "(", "err", ")", "{", "result", "=", "false", ";", "}", "return", "result", ";", "}" ]
Checks whether or not a function is a key comparator. We need to differentiate between the key comparator and the result selector since both take two arguments. @param arg Function to be tested. @return If the given function is a key comparator.
[ "Checks", "whether", "or", "not", "a", "function", "is", "a", "key", "comparator", ".", "We", "need", "to", "differentiate", "between", "the", "key", "comparator", "and", "the", "result", "selector", "since", "both", "take", "two", "arguments", "." ]
e89561cd9c5d3f9f0b689711872d499b2b1a1e5a
https://github.com/SvSchmidt/linqjs/blob/e89561cd9c5d3f9f0b689711872d499b2b1a1e5a/dist/linq.es6.js#L559-L572
train
novacrazy/bluebird-co
src/yield_handler.js
processThunkArgs
function processThunkArgs( args ) { let length = args.length | 0; if( length >= 3 ) { let res = new Array( --length ); for( let i = 0; i < length; ) { res[i] = args[++i]; //It's a good thing this isn't undefined behavior in JavaScript } return res; } return args[1]; }
javascript
function processThunkArgs( args ) { let length = args.length | 0; if( length >= 3 ) { let res = new Array( --length ); for( let i = 0; i < length; ) { res[i] = args[++i]; //It's a good thing this isn't undefined behavior in JavaScript } return res; } return args[1]; }
[ "function", "processThunkArgs", "(", "args", ")", "{", "let", "length", "=", "args", ".", "length", "|", "0", ";", "if", "(", "length", ">=", "3", ")", "{", "let", "res", "=", "new", "Array", "(", "--", "length", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", ")", "{", "res", "[", "i", "]", "=", "args", "[", "++", "i", "]", ";", "}", "return", "res", ";", "}", "return", "args", "[", "1", "]", ";", "}" ]
This is separated out so it can be optimized independently to the calling function.
[ "This", "is", "separated", "out", "so", "it", "can", "be", "optimized", "independently", "to", "the", "calling", "function", "." ]
0f98755d326b99f8e3968308e4be43041ec5fde7
https://github.com/novacrazy/bluebird-co/blob/0f98755d326b99f8e3968308e4be43041ec5fde7/src/yield_handler.js#L174-L188
train
mikolalysenko/planar-graph-to-polyline
pg2pl.js
ccw
function ccw(c) { var n = c.length var area = [0] for(var j=0; j<n; ++j) { var a = positions[c[j]] var b = positions[c[(j+1)%n]] var t00 = twoProduct(-a[0], a[1]) var t01 = twoProduct(-a[0], b[1]) var t10 = twoProduct( b[0], a[1]) var t11 = twoProduct( b[0], b[1]) area = robustSum(area, robustSum(robustSum(t00, t01), robustSum(t10, t11))) } return area[area.length-1] > 0 }
javascript
function ccw(c) { var n = c.length var area = [0] for(var j=0; j<n; ++j) { var a = positions[c[j]] var b = positions[c[(j+1)%n]] var t00 = twoProduct(-a[0], a[1]) var t01 = twoProduct(-a[0], b[1]) var t10 = twoProduct( b[0], a[1]) var t11 = twoProduct( b[0], b[1]) area = robustSum(area, robustSum(robustSum(t00, t01), robustSum(t10, t11))) } return area[area.length-1] > 0 }
[ "function", "ccw", "(", "c", ")", "{", "var", "n", "=", "c", ".", "length", "var", "area", "=", "[", "0", "]", "for", "(", "var", "j", "=", "0", ";", "j", "<", "n", ";", "++", "j", ")", "{", "var", "a", "=", "positions", "[", "c", "[", "j", "]", "]", "var", "b", "=", "positions", "[", "c", "[", "(", "j", "+", "1", ")", "%", "n", "]", "]", "var", "t00", "=", "twoProduct", "(", "-", "a", "[", "0", "]", ",", "a", "[", "1", "]", ")", "var", "t01", "=", "twoProduct", "(", "-", "a", "[", "0", "]", ",", "b", "[", "1", "]", ")", "var", "t10", "=", "twoProduct", "(", "b", "[", "0", "]", ",", "a", "[", "1", "]", ")", "var", "t11", "=", "twoProduct", "(", "b", "[", "0", "]", ",", "b", "[", "1", "]", ")", "area", "=", "robustSum", "(", "area", ",", "robustSum", "(", "robustSum", "(", "t00", ",", "t01", ")", ",", "robustSum", "(", "t10", ",", "t11", ")", ")", ")", "}", "return", "area", "[", "area", ".", "length", "-", "1", "]", ">", "0", "}" ]
Check orientation of a polygon using exact arithmetic
[ "Check", "orientation", "of", "a", "polygon", "using", "exact", "arithmetic" ]
078192fd8c09bff5151a1db2c06a77c12cdc5554
https://github.com/mikolalysenko/planar-graph-to-polyline/blob/078192fd8c09bff5151a1db2c06a77c12cdc5554/pg2pl.js#L52-L65
train
ditesh/node-mbox
main.js
syncToTmp
function syncToTmp(tmpfd, msgnumber, cb) { // Pass the last msg if (msgnumber > messages.offsets.length) cb(); // Skip deleted messages else if (messages.offsets[msgnumber] === undefined) syncToTmp(tmpfd, msgnumber + 1, cb); else { var buffer = new Buffer(omessages.sizes[msgnumber]); fs.read(fd, buffer, 0, omessages.sizes[msgnumber], messages.offsets[msgnumber], function(err, bytesRead, buffer) { fs.write(tmpfd, buffer, 0, bytesRead, null, function(err, written, buffer) { syncToTmp(tmpfd, msgnumber + 1, cb); }); }); } }
javascript
function syncToTmp(tmpfd, msgnumber, cb) { // Pass the last msg if (msgnumber > messages.offsets.length) cb(); // Skip deleted messages else if (messages.offsets[msgnumber] === undefined) syncToTmp(tmpfd, msgnumber + 1, cb); else { var buffer = new Buffer(omessages.sizes[msgnumber]); fs.read(fd, buffer, 0, omessages.sizes[msgnumber], messages.offsets[msgnumber], function(err, bytesRead, buffer) { fs.write(tmpfd, buffer, 0, bytesRead, null, function(err, written, buffer) { syncToTmp(tmpfd, msgnumber + 1, cb); }); }); } }
[ "function", "syncToTmp", "(", "tmpfd", ",", "msgnumber", ",", "cb", ")", "{", "if", "(", "msgnumber", ">", "messages", ".", "offsets", ".", "length", ")", "cb", "(", ")", ";", "else", "if", "(", "messages", ".", "offsets", "[", "msgnumber", "]", "===", "undefined", ")", "syncToTmp", "(", "tmpfd", ",", "msgnumber", "+", "1", ",", "cb", ")", ";", "else", "{", "var", "buffer", "=", "new", "Buffer", "(", "omessages", ".", "sizes", "[", "msgnumber", "]", ")", ";", "fs", ".", "read", "(", "fd", ",", "buffer", ",", "0", ",", "omessages", ".", "sizes", "[", "msgnumber", "]", ",", "messages", ".", "offsets", "[", "msgnumber", "]", ",", "function", "(", "err", ",", "bytesRead", ",", "buffer", ")", "{", "fs", ".", "write", "(", "tmpfd", ",", "buffer", ",", "0", ",", "bytesRead", ",", "null", ",", "function", "(", "err", ",", "written", ",", "buffer", ")", "{", "syncToTmp", "(", "tmpfd", ",", "msgnumber", "+", "1", ",", "cb", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}" ]
Private methods follow Write modifications to temp file
[ "Private", "methods", "follow", "Write", "modifications", "to", "temp", "file" ]
85f6ad33e2f88fa55ffca6b47cc97e149d827a1e
https://github.com/ditesh/node-mbox/blob/85f6ad33e2f88fa55ffca6b47cc97e149d827a1e/main.js#L158-L178
train
flohil/wdio-workflo
dist/lib/page_objects/page_elements/PageElementGroup.js
isIElementNode
function isIElementNode(node) { return typeof node['getText'] === 'function' && typeof node.currently['hasText'] === 'function' && typeof node.currently['hasAnyText'] === 'function' && typeof node.currently['containsText'] === 'function' && typeof node.wait['hasText'] === 'function' && typeof node.wait['hasAnyText'] === 'function' && typeof node.wait['containsText'] === 'function' && typeof node.eventually['hasText'] === 'function' && typeof node.eventually['hasAnyText'] === 'function' && typeof node.eventually['containsText'] === 'function' && typeof node['getDirectText'] === 'function' && typeof node.currently['hasDirectText'] === 'function' && typeof node.currently['hasAnyDirectText'] === 'function' && typeof node.currently['containsDirectText'] === 'function' && typeof node.wait['hasDirectText'] === 'function' && typeof node.wait['hasAnyDirectText'] === 'function' && typeof node.wait['containsDirectText'] === 'function' && typeof node.eventually['hasDirectText'] === 'function' && typeof node.eventually['hasAnyDirectText'] === 'function' && typeof node.eventually['containsDirectText'] === 'function'; }
javascript
function isIElementNode(node) { return typeof node['getText'] === 'function' && typeof node.currently['hasText'] === 'function' && typeof node.currently['hasAnyText'] === 'function' && typeof node.currently['containsText'] === 'function' && typeof node.wait['hasText'] === 'function' && typeof node.wait['hasAnyText'] === 'function' && typeof node.wait['containsText'] === 'function' && typeof node.eventually['hasText'] === 'function' && typeof node.eventually['hasAnyText'] === 'function' && typeof node.eventually['containsText'] === 'function' && typeof node['getDirectText'] === 'function' && typeof node.currently['hasDirectText'] === 'function' && typeof node.currently['hasAnyDirectText'] === 'function' && typeof node.currently['containsDirectText'] === 'function' && typeof node.wait['hasDirectText'] === 'function' && typeof node.wait['hasAnyDirectText'] === 'function' && typeof node.wait['containsDirectText'] === 'function' && typeof node.eventually['hasDirectText'] === 'function' && typeof node.eventually['hasAnyDirectText'] === 'function' && typeof node.eventually['containsDirectText'] === 'function'; }
[ "function", "isIElementNode", "(", "node", ")", "{", "return", "typeof", "node", "[", "'getText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", "'hasText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", "'hasAnyText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", "'containsText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "wait", "[", "'hasText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "wait", "[", "'hasAnyText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "wait", "[", "'containsText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "eventually", "[", "'hasText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "eventually", "[", "'hasAnyText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "eventually", "[", "'containsText'", "]", "===", "'function'", "&&", "typeof", "node", "[", "'getDirectText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", "'hasDirectText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", "'hasAnyDirectText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", "'containsDirectText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "wait", "[", "'hasDirectText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "wait", "[", "'hasAnyDirectText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "wait", "[", "'containsDirectText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "eventually", "[", "'hasDirectText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "eventually", "[", "'hasAnyDirectText'", "]", "===", "'function'", "&&", "typeof", "node", ".", "eventually", "[", "'containsDirectText'", "]", "===", "'function'", ";", "}" ]
type guards Returns true if the passed node supports all functions defined in IElementNode. @param node a PageNode
[ "type", "guards", "Returns", "true", "if", "the", "passed", "node", "supports", "all", "functions", "defined", "in", "IElementNode", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/page_objects/page_elements/PageElementGroup.js#L1358-L1379
train
emmetio/markup-formatters
format/haml.js
updateFormatting
function updateFormatting(outNode, profile) { const node = outNode.node; if (!node.isTextOnly && node.value) { // node with text: put a space before single-line text outNode.beforeText = reNl.test(node.value) ? outNode.newline + outNode.indent + profile.indent(1) : ' '; } return outNode; }
javascript
function updateFormatting(outNode, profile) { const node = outNode.node; if (!node.isTextOnly && node.value) { // node with text: put a space before single-line text outNode.beforeText = reNl.test(node.value) ? outNode.newline + outNode.indent + profile.indent(1) : ' '; } return outNode; }
[ "function", "updateFormatting", "(", "outNode", ",", "profile", ")", "{", "const", "node", "=", "outNode", ".", "node", ";", "if", "(", "!", "node", ".", "isTextOnly", "&&", "node", ".", "value", ")", "{", "outNode", ".", "beforeText", "=", "reNl", ".", "test", "(", "node", ".", "value", ")", "?", "outNode", ".", "newline", "+", "outNode", ".", "indent", "+", "profile", ".", "indent", "(", "1", ")", ":", "' '", ";", "}", "return", "outNode", ";", "}" ]
Updates formatting properties for given output node NB Unlike HTML, HAML is indent-based format so some formatting options from `profile` will not take effect, otherwise output will be broken @param {OutputNode} outNode Output wrapper of parsed abbreviation node @param {Profile} profile Output profile @return {OutputNode}
[ "Updates", "formatting", "properties", "for", "given", "output", "node", "NB", "Unlike", "HTML", "HAML", "is", "indent", "-", "based", "format", "so", "some", "formatting", "options", "from", "profile", "will", "not", "take", "effect", "otherwise", "output", "will", "be", "broken" ]
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/haml.js#L58-L69
train
flohil/wdio-workflo
config/wdio.conf.js
function (commandName, args, result, error) { if (error) { if ( error.type ) { errorType = error.type } else if ( error.toString().indexOf("Error: An element could not be located on the page using the given search parameters") > -1 ) { errorType = true } try { const screenshot = browser.saveScreenshot() // returns base64 string buffer const screenshotFolder = path.join(process.env.WDIO_WORKFLO_RUN_PATH, 'allure-results') const screenshotFilename = `${screenshotFolder}/${global.screenshotId}.png` global.errorScreenshotFilename = screenshotFilename fs.writeFileSync(screenshotFilename, screenshot) } catch (err) { console.log(`Failed to take screenshot: ${err.message}`) console.log(err.stack) } } if (typeof workfloConf.afterCommand === 'function') { return workfloConf.afterCommand(commandName, args, result, error) } }
javascript
function (commandName, args, result, error) { if (error) { if ( error.type ) { errorType = error.type } else if ( error.toString().indexOf("Error: An element could not be located on the page using the given search parameters") > -1 ) { errorType = true } try { const screenshot = browser.saveScreenshot() // returns base64 string buffer const screenshotFolder = path.join(process.env.WDIO_WORKFLO_RUN_PATH, 'allure-results') const screenshotFilename = `${screenshotFolder}/${global.screenshotId}.png` global.errorScreenshotFilename = screenshotFilename fs.writeFileSync(screenshotFilename, screenshot) } catch (err) { console.log(`Failed to take screenshot: ${err.message}`) console.log(err.stack) } } if (typeof workfloConf.afterCommand === 'function') { return workfloConf.afterCommand(commandName, args, result, error) } }
[ "function", "(", "commandName", ",", "args", ",", "result", ",", "error", ")", "{", "if", "(", "error", ")", "{", "if", "(", "error", ".", "type", ")", "{", "errorType", "=", "error", ".", "type", "}", "else", "if", "(", "error", ".", "toString", "(", ")", ".", "indexOf", "(", "\"Error: An element could not be located on the page using the given search parameters\"", ")", ">", "-", "1", ")", "{", "errorType", "=", "true", "}", "try", "{", "const", "screenshot", "=", "browser", ".", "saveScreenshot", "(", ")", "const", "screenshotFolder", "=", "path", ".", "join", "(", "process", ".", "env", ".", "WDIO_WORKFLO_RUN_PATH", ",", "'allure-results'", ")", "const", "screenshotFilename", "=", "`", "${", "screenshotFolder", "}", "${", "global", ".", "screenshotId", "}", "`", "global", ".", "errorScreenshotFilename", "=", "screenshotFilename", "fs", ".", "writeFileSync", "(", "screenshotFilename", ",", "screenshot", ")", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "`", "${", "err", ".", "message", "}", "`", ")", "console", ".", "log", "(", "err", ".", "stack", ")", "}", "}", "if", "(", "typeof", "workfloConf", ".", "afterCommand", "===", "'function'", ")", "{", "return", "workfloConf", ".", "afterCommand", "(", "commandName", ",", "args", ",", "result", ",", "error", ")", "}", "}" ]
Runs after a WebdriverIO command gets executed
[ "Runs", "after", "a", "WebdriverIO", "command", "gets", "executed" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/config/wdio.conf.js#L267-L293
train
canjs/worker-render
src/simple_extend.js
extend
function extend(a, b){ var p, type; for(p in b) { type = typeof b[p]; if(type !== "object" && type !== "function") { a[p] = b[p]; } } return a; }
javascript
function extend(a, b){ var p, type; for(p in b) { type = typeof b[p]; if(type !== "object" && type !== "function") { a[p] = b[p]; } } return a; }
[ "function", "extend", "(", "a", ",", "b", ")", "{", "var", "p", ",", "type", ";", "for", "(", "p", "in", "b", ")", "{", "type", "=", "typeof", "b", "[", "p", "]", ";", "if", "(", "type", "!==", "\"object\"", "&&", "type", "!==", "\"function\"", ")", "{", "a", "[", "p", "]", "=", "b", "[", "p", "]", ";", "}", "}", "return", "a", ";", "}" ]
A simple extend that doesn't go deep
[ "A", "simple", "extend", "that", "doesn", "t", "go", "deep" ]
e36dbb886a8453bd9e4d4fc9f73a4bc84146d6e5
https://github.com/canjs/worker-render/blob/e36dbb886a8453bd9e4d4fc9f73a4bc84146d6e5/src/simple_extend.js#L4-L13
train
flohil/wdio-workflo
dist/lib/cli.js
completeSpecFiles
function completeSpecFiles(argv, _filters) { // if user manually defined an empty specFiles array, do not add specFiles from folder if (Object.keys(_filters.specFiles).length === 0 && !argv.specFiles) { io_1.getAllFiles(specsDir, '.spec.ts').forEach(specFile => _filters.specFiles[specFile] = true); return true; } else { let removeOnly = true; const removeSpecFiles = {}; for (const specFile in _filters.specFiles) { let remove = false; let matchStr = specFile; if (specFile.substr(0, 1) === '-') { remove = true; matchStr = specFile.substr(1, specFile.length - 1); } else { removeOnly = false; } if (remove) { delete _filters.specFiles[specFile]; removeSpecFiles[matchStr] = true; } } if (removeOnly) { io_1.getAllFiles(specsDir, '.spec.ts') .filter(specFile => !(specFile in removeSpecFiles)) .forEach(specFile => _filters.specFiles[specFile] = true); } } return false; }
javascript
function completeSpecFiles(argv, _filters) { // if user manually defined an empty specFiles array, do not add specFiles from folder if (Object.keys(_filters.specFiles).length === 0 && !argv.specFiles) { io_1.getAllFiles(specsDir, '.spec.ts').forEach(specFile => _filters.specFiles[specFile] = true); return true; } else { let removeOnly = true; const removeSpecFiles = {}; for (const specFile in _filters.specFiles) { let remove = false; let matchStr = specFile; if (specFile.substr(0, 1) === '-') { remove = true; matchStr = specFile.substr(1, specFile.length - 1); } else { removeOnly = false; } if (remove) { delete _filters.specFiles[specFile]; removeSpecFiles[matchStr] = true; } } if (removeOnly) { io_1.getAllFiles(specsDir, '.spec.ts') .filter(specFile => !(specFile in removeSpecFiles)) .forEach(specFile => _filters.specFiles[specFile] = true); } } return false; }
[ "function", "completeSpecFiles", "(", "argv", ",", "_filters", ")", "{", "if", "(", "Object", ".", "keys", "(", "_filters", ".", "specFiles", ")", ".", "length", "===", "0", "&&", "!", "argv", ".", "specFiles", ")", "{", "io_1", ".", "getAllFiles", "(", "specsDir", ",", "'.spec.ts'", ")", ".", "forEach", "(", "specFile", "=>", "_filters", ".", "specFiles", "[", "specFile", "]", "=", "true", ")", ";", "return", "true", ";", "}", "else", "{", "let", "removeOnly", "=", "true", ";", "const", "removeSpecFiles", "=", "{", "}", ";", "for", "(", "const", "specFile", "in", "_filters", ".", "specFiles", ")", "{", "let", "remove", "=", "false", ";", "let", "matchStr", "=", "specFile", ";", "if", "(", "specFile", ".", "substr", "(", "0", ",", "1", ")", "===", "'-'", ")", "{", "remove", "=", "true", ";", "matchStr", "=", "specFile", ".", "substr", "(", "1", ",", "specFile", ".", "length", "-", "1", ")", ";", "}", "else", "{", "removeOnly", "=", "false", ";", "}", "if", "(", "remove", ")", "{", "delete", "_filters", ".", "specFiles", "[", "specFile", "]", ";", "removeSpecFiles", "[", "matchStr", "]", "=", "true", ";", "}", "}", "if", "(", "removeOnly", ")", "{", "io_1", ".", "getAllFiles", "(", "specsDir", ",", "'.spec.ts'", ")", ".", "filter", "(", "specFile", "=>", "!", "(", "specFile", "in", "removeSpecFiles", ")", ")", ".", "forEach", "(", "specFile", "=>", "_filters", ".", "specFiles", "[", "specFile", "]", "=", "true", ")", ";", "}", "}", "return", "false", ";", "}" ]
if no spec files are present in filters, use all spec files in specs folder
[ "if", "no", "spec", "files", "are", "present", "in", "filters", "use", "all", "spec", "files", "in", "specs", "folder" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/cli.js#L735-L766
train
flohil/wdio-workflo
dist/lib/cli.js
mergeLists
function mergeLists(list, _filters) { if (list.specFiles) { list.specFiles.forEach(value => _filters.specFiles[value] = true); } if (list.testcaseFiles) { list.testcaseFiles.forEach(value => _filters.testcaseFiles[value] = true); } if (list.features) { list.features.forEach(value => _filters.features[value] = true); } if (list.specs) { list.specs.forEach(value => _filters.specs[value] = true); } if (list.testcases) { list.testcases.forEach(value => _filters.testcases[value] = true); } if (list.listFiles) { for (const listFile of list.listFiles) { // complete cli listFiles paths const listFilePath = path.join(listsDir, `${listFile}.list.ts`); if (!fs.existsSync(listFilePath)) { throw new Error(`List file could not be found: ${listFilePath}`); } else { const sublist = require(listFilePath).default; // recursively traverse sub list files mergeLists(sublist, _filters); } } } }
javascript
function mergeLists(list, _filters) { if (list.specFiles) { list.specFiles.forEach(value => _filters.specFiles[value] = true); } if (list.testcaseFiles) { list.testcaseFiles.forEach(value => _filters.testcaseFiles[value] = true); } if (list.features) { list.features.forEach(value => _filters.features[value] = true); } if (list.specs) { list.specs.forEach(value => _filters.specs[value] = true); } if (list.testcases) { list.testcases.forEach(value => _filters.testcases[value] = true); } if (list.listFiles) { for (const listFile of list.listFiles) { // complete cli listFiles paths const listFilePath = path.join(listsDir, `${listFile}.list.ts`); if (!fs.existsSync(listFilePath)) { throw new Error(`List file could not be found: ${listFilePath}`); } else { const sublist = require(listFilePath).default; // recursively traverse sub list files mergeLists(sublist, _filters); } } } }
[ "function", "mergeLists", "(", "list", ",", "_filters", ")", "{", "if", "(", "list", ".", "specFiles", ")", "{", "list", ".", "specFiles", ".", "forEach", "(", "value", "=>", "_filters", ".", "specFiles", "[", "value", "]", "=", "true", ")", ";", "}", "if", "(", "list", ".", "testcaseFiles", ")", "{", "list", ".", "testcaseFiles", ".", "forEach", "(", "value", "=>", "_filters", ".", "testcaseFiles", "[", "value", "]", "=", "true", ")", ";", "}", "if", "(", "list", ".", "features", ")", "{", "list", ".", "features", ".", "forEach", "(", "value", "=>", "_filters", ".", "features", "[", "value", "]", "=", "true", ")", ";", "}", "if", "(", "list", ".", "specs", ")", "{", "list", ".", "specs", ".", "forEach", "(", "value", "=>", "_filters", ".", "specs", "[", "value", "]", "=", "true", ")", ";", "}", "if", "(", "list", ".", "testcases", ")", "{", "list", ".", "testcases", ".", "forEach", "(", "value", "=>", "_filters", ".", "testcases", "[", "value", "]", "=", "true", ")", ";", "}", "if", "(", "list", ".", "listFiles", ")", "{", "for", "(", "const", "listFile", "of", "list", ".", "listFiles", ")", "{", "const", "listFilePath", "=", "path", ".", "join", "(", "listsDir", ",", "`", "${", "listFile", "}", "`", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "listFilePath", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "listFilePath", "}", "`", ")", ";", "}", "else", "{", "const", "sublist", "=", "require", "(", "listFilePath", ")", ".", "default", ";", "mergeLists", "(", "sublist", ",", "_filters", ")", ";", "}", "}", "}", "}" ]
Loads all specFiles, testcaseFiles, features, specs and testcases defined in lists and sublists of argv.listFiles @param argv
[ "Loads", "all", "specFiles", "testcaseFiles", "features", "specs", "and", "testcases", "defined", "in", "lists", "and", "sublists", "of", "argv", ".", "listFiles" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/cli.js#L830-L860
train
flohil/wdio-workflo
dist/lib/cli.js
addFeatures
function addFeatures() { const features = {}; for (const spec in filters.specs) { features[parseResults.specs.specTable[spec].feature] = true; } filters.features = features; }
javascript
function addFeatures() { const features = {}; for (const spec in filters.specs) { features[parseResults.specs.specTable[spec].feature] = true; } filters.features = features; }
[ "function", "addFeatures", "(", ")", "{", "const", "features", "=", "{", "}", ";", "for", "(", "const", "spec", "in", "filters", ".", "specs", ")", "{", "features", "[", "parseResults", ".", "specs", ".", "specTable", "[", "spec", "]", ".", "feature", "]", "=", "true", ";", "}", "filters", ".", "features", "=", "features", ";", "}" ]
adds features to filters based on current content of filters.specs
[ "adds", "features", "to", "filters", "based", "on", "current", "content", "of", "filters", ".", "specs" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/cli.js#L1457-L1463
train
flohil/wdio-workflo
dist/lib/cli.js
addSpecFiles
function addSpecFiles() { const specFiles = {}; for (const spec in filters.specs) { specFiles[parseResults.specs.specTable[spec].specFile] = true; } filters.specFiles = specFiles; }
javascript
function addSpecFiles() { const specFiles = {}; for (const spec in filters.specs) { specFiles[parseResults.specs.specTable[spec].specFile] = true; } filters.specFiles = specFiles; }
[ "function", "addSpecFiles", "(", ")", "{", "const", "specFiles", "=", "{", "}", ";", "for", "(", "const", "spec", "in", "filters", ".", "specs", ")", "{", "specFiles", "[", "parseResults", ".", "specs", ".", "specTable", "[", "spec", "]", ".", "specFile", "]", "=", "true", ";", "}", "filters", ".", "specFiles", "=", "specFiles", ";", "}" ]
adds spec files to filters based on current content of filters.specFiles
[ "adds", "spec", "files", "to", "filters", "based", "on", "current", "content", "of", "filters", ".", "specFiles" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/cli.js#L1465-L1471
train
flohil/wdio-workflo
dist/lib/cli.js
cleanResultsStatus
function cleanResultsStatus() { // remove criterias and spec if no criteria in spec for (const spec in mergedResults.specs) { if (!(spec in parseResults.specs.specTable) || Object.keys(parseResults.specs.specTable[spec].criteria).length === 0) { delete mergedResults.specs[spec]; } else { const parsedCriteria = parseResults.specs.specTable[spec].criteria; const resultsCriteria = mergedResults.specs[spec]; for (const criteria in resultsCriteria) { if (!(criteria in parsedCriteria)) { delete mergedResults.specs[spec][criteria]; } } } } for (const testcase in mergedResults.testcases) { if (!(testcase in parseResults.testcases.testcaseTable)) { delete mergedResults.testcases[testcase]; } } // add criteria for (const spec in parseResults.specs.specTable) { if (!(spec in mergedResults.specs)) { mergedResults.specs[spec] = {}; } const parsedCriteria = parseResults.specs.specTable[spec].criteria; const resultsCriteria = mergedResults.specs[spec]; for (const criteria in parsedCriteria) { if (!(criteria in resultsCriteria)) { mergedResults.specs[spec][criteria] = { dateTime, status: 'unknown', resultsFolder: undefined, }; if (criteria in criteriaAnalysis.specs[spec].manual) { mergedResults.specs[spec][criteria].manual = true; } } } } for (const testcase in parseResults.testcases.testcaseTable) { if (!(testcase in mergedResults.testcases)) { mergedResults.testcases[testcase] = { dateTime, status: 'unknown', resultsFolder: undefined, }; } } fs.writeFileSync(mergedResultsPath, JSON.stringify(mergedResults), { encoding: 'utf8' }); }
javascript
function cleanResultsStatus() { // remove criterias and spec if no criteria in spec for (const spec in mergedResults.specs) { if (!(spec in parseResults.specs.specTable) || Object.keys(parseResults.specs.specTable[spec].criteria).length === 0) { delete mergedResults.specs[spec]; } else { const parsedCriteria = parseResults.specs.specTable[spec].criteria; const resultsCriteria = mergedResults.specs[spec]; for (const criteria in resultsCriteria) { if (!(criteria in parsedCriteria)) { delete mergedResults.specs[spec][criteria]; } } } } for (const testcase in mergedResults.testcases) { if (!(testcase in parseResults.testcases.testcaseTable)) { delete mergedResults.testcases[testcase]; } } // add criteria for (const spec in parseResults.specs.specTable) { if (!(spec in mergedResults.specs)) { mergedResults.specs[spec] = {}; } const parsedCriteria = parseResults.specs.specTable[spec].criteria; const resultsCriteria = mergedResults.specs[spec]; for (const criteria in parsedCriteria) { if (!(criteria in resultsCriteria)) { mergedResults.specs[spec][criteria] = { dateTime, status: 'unknown', resultsFolder: undefined, }; if (criteria in criteriaAnalysis.specs[spec].manual) { mergedResults.specs[spec][criteria].manual = true; } } } } for (const testcase in parseResults.testcases.testcaseTable) { if (!(testcase in mergedResults.testcases)) { mergedResults.testcases[testcase] = { dateTime, status: 'unknown', resultsFolder: undefined, }; } } fs.writeFileSync(mergedResultsPath, JSON.stringify(mergedResults), { encoding: 'utf8' }); }
[ "function", "cleanResultsStatus", "(", ")", "{", "for", "(", "const", "spec", "in", "mergedResults", ".", "specs", ")", "{", "if", "(", "!", "(", "spec", "in", "parseResults", ".", "specs", ".", "specTable", ")", "||", "Object", ".", "keys", "(", "parseResults", ".", "specs", ".", "specTable", "[", "spec", "]", ".", "criteria", ")", ".", "length", "===", "0", ")", "{", "delete", "mergedResults", ".", "specs", "[", "spec", "]", ";", "}", "else", "{", "const", "parsedCriteria", "=", "parseResults", ".", "specs", ".", "specTable", "[", "spec", "]", ".", "criteria", ";", "const", "resultsCriteria", "=", "mergedResults", ".", "specs", "[", "spec", "]", ";", "for", "(", "const", "criteria", "in", "resultsCriteria", ")", "{", "if", "(", "!", "(", "criteria", "in", "parsedCriteria", ")", ")", "{", "delete", "mergedResults", ".", "specs", "[", "spec", "]", "[", "criteria", "]", ";", "}", "}", "}", "}", "for", "(", "const", "testcase", "in", "mergedResults", ".", "testcases", ")", "{", "if", "(", "!", "(", "testcase", "in", "parseResults", ".", "testcases", ".", "testcaseTable", ")", ")", "{", "delete", "mergedResults", ".", "testcases", "[", "testcase", "]", ";", "}", "}", "for", "(", "const", "spec", "in", "parseResults", ".", "specs", ".", "specTable", ")", "{", "if", "(", "!", "(", "spec", "in", "mergedResults", ".", "specs", ")", ")", "{", "mergedResults", ".", "specs", "[", "spec", "]", "=", "{", "}", ";", "}", "const", "parsedCriteria", "=", "parseResults", ".", "specs", ".", "specTable", "[", "spec", "]", ".", "criteria", ";", "const", "resultsCriteria", "=", "mergedResults", ".", "specs", "[", "spec", "]", ";", "for", "(", "const", "criteria", "in", "parsedCriteria", ")", "{", "if", "(", "!", "(", "criteria", "in", "resultsCriteria", ")", ")", "{", "mergedResults", ".", "specs", "[", "spec", "]", "[", "criteria", "]", "=", "{", "dateTime", ",", "status", ":", "'unknown'", ",", "resultsFolder", ":", "undefined", ",", "}", ";", "if", "(", "criteria", "in", "criteriaAnalysis", ".", "specs", "[", "spec", "]", ".", "manual", ")", "{", "mergedResults", ".", "specs", "[", "spec", "]", "[", "criteria", "]", ".", "manual", "=", "true", ";", "}", "}", "}", "}", "for", "(", "const", "testcase", "in", "parseResults", ".", "testcases", ".", "testcaseTable", ")", "{", "if", "(", "!", "(", "testcase", "in", "mergedResults", ".", "testcases", ")", ")", "{", "mergedResults", ".", "testcases", "[", "testcase", "]", "=", "{", "dateTime", ",", "status", ":", "'unknown'", ",", "resultsFolder", ":", "undefined", ",", "}", ";", "}", "}", "fs", ".", "writeFileSync", "(", "mergedResultsPath", ",", "JSON", ".", "stringify", "(", "mergedResults", ")", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "}" ]
Removes specs and testcases from mergedResults that are no longer defined. Adds defined specs and testcases that have no status yet to mergedResults.
[ "Removes", "specs", "and", "testcases", "from", "mergedResults", "that", "are", "no", "longer", "defined", ".", "Adds", "defined", "specs", "and", "testcases", "that", "have", "no", "status", "yet", "to", "mergedResults", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/cli.js#L1484-L1535
train
flohil/wdio-workflo
dist/lib/utility_functions/string.js
splitToObj
function splitToObj(str, delim) { if (!(_.isString(str))) { throw new Error(`Input must be a string: ${str}`); } else { return util_1.convertToObject(str.split(delim), () => true); } }
javascript
function splitToObj(str, delim) { if (!(_.isString(str))) { throw new Error(`Input must be a string: ${str}`); } else { return util_1.convertToObject(str.split(delim), () => true); } }
[ "function", "splitToObj", "(", "str", ",", "delim", ")", "{", "if", "(", "!", "(", "_", ".", "isString", "(", "str", ")", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "str", "}", "`", ")", ";", "}", "else", "{", "return", "util_1", ".", "convertToObject", "(", "str", ".", "split", "(", "delim", ")", ",", "(", ")", "=>", "true", ")", ";", "}", "}" ]
Splits a string at delim and returns an object with the split string parts as keys and the values set to true. @param str @param delim
[ "Splits", "a", "string", "at", "delim", "and", "returns", "an", "object", "with", "the", "split", "string", "parts", "as", "keys", "and", "the", "values", "set", "to", "true", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/utility_functions/string.js#L12-L19
train
Bartvds/joi-assert
lib/assertion.js
assertion
function assertion(value, schema, message, vars, ssf) { return Joi.validate(value, schema, function(err, value) { // fast way if (!err) { return value; } // assemble message var msg = ''; // process message (if any) var mtype = typeof message; if (mtype === 'string') { if (vars && typeof vars === 'object') { // mini template message = message.replace(/\{([\w]+)\}/gi, function (match, key) { if (hasOwnProp.call(vars, key)) { return vars[key]; } }); } msg += message + ': '; } // append schema label msg += getLabel(schema.describe(), err); // append some of the errors var maxDetails = 4; msg += err.details.slice(0, maxDetails).map(function(det) { if (/^\w+\.\w/.test(det.path)) { return '[' + det.path + '] ' + det.message; } return det.message; }).join(', '); if (err.details.length > maxDetails) { var hidden = (err.details.length - maxDetails); msg += '... (showing ' + (err.details.length - hidden) + ' of ' + err.details.length + ')'; } // booya throw new AssertionError(msg, { details: err.details, value: value }, ssf); }); }
javascript
function assertion(value, schema, message, vars, ssf) { return Joi.validate(value, schema, function(err, value) { // fast way if (!err) { return value; } // assemble message var msg = ''; // process message (if any) var mtype = typeof message; if (mtype === 'string') { if (vars && typeof vars === 'object') { // mini template message = message.replace(/\{([\w]+)\}/gi, function (match, key) { if (hasOwnProp.call(vars, key)) { return vars[key]; } }); } msg += message + ': '; } // append schema label msg += getLabel(schema.describe(), err); // append some of the errors var maxDetails = 4; msg += err.details.slice(0, maxDetails).map(function(det) { if (/^\w+\.\w/.test(det.path)) { return '[' + det.path + '] ' + det.message; } return det.message; }).join(', '); if (err.details.length > maxDetails) { var hidden = (err.details.length - maxDetails); msg += '... (showing ' + (err.details.length - hidden) + ' of ' + err.details.length + ')'; } // booya throw new AssertionError(msg, { details: err.details, value: value }, ssf); }); }
[ "function", "assertion", "(", "value", ",", "schema", ",", "message", ",", "vars", ",", "ssf", ")", "{", "return", "Joi", ".", "validate", "(", "value", ",", "schema", ",", "function", "(", "err", ",", "value", ")", "{", "if", "(", "!", "err", ")", "{", "return", "value", ";", "}", "var", "msg", "=", "''", ";", "var", "mtype", "=", "typeof", "message", ";", "if", "(", "mtype", "===", "'string'", ")", "{", "if", "(", "vars", "&&", "typeof", "vars", "===", "'object'", ")", "{", "message", "=", "message", ".", "replace", "(", "/", "\\{([\\w]+)\\}", "/", "gi", ",", "function", "(", "match", ",", "key", ")", "{", "if", "(", "hasOwnProp", ".", "call", "(", "vars", ",", "key", ")", ")", "{", "return", "vars", "[", "key", "]", ";", "}", "}", ")", ";", "}", "msg", "+=", "message", "+", "': '", ";", "}", "msg", "+=", "getLabel", "(", "schema", ".", "describe", "(", ")", ",", "err", ")", ";", "var", "maxDetails", "=", "4", ";", "msg", "+=", "err", ".", "details", ".", "slice", "(", "0", ",", "maxDetails", ")", ".", "map", "(", "function", "(", "det", ")", "{", "if", "(", "/", "^\\w+\\.\\w", "/", ".", "test", "(", "det", ".", "path", ")", ")", "{", "return", "'['", "+", "det", ".", "path", "+", "'] '", "+", "det", ".", "message", ";", "}", "return", "det", ".", "message", ";", "}", ")", ".", "join", "(", "', '", ")", ";", "if", "(", "err", ".", "details", ".", "length", ">", "maxDetails", ")", "{", "var", "hidden", "=", "(", "err", ".", "details", ".", "length", "-", "maxDetails", ")", ";", "msg", "+=", "'... (showing '", "+", "(", "err", ".", "details", ".", "length", "-", "hidden", ")", "+", "' of '", "+", "err", ".", "details", ".", "length", "+", "')'", ";", "}", "throw", "new", "AssertionError", "(", "msg", ",", "{", "details", ":", "err", ".", "details", ",", "value", ":", "value", "}", ",", "ssf", ")", ";", "}", ")", ";", "}" ]
main assertino logic
[ "main", "assertino", "logic" ]
a4a920ad79a9b40ae38437244a5915e6cb76f3b3
https://github.com/Bartvds/joi-assert/blob/a4a920ad79a9b40ae38437244a5915e6cb76f3b3/lib/assertion.js#L25-L73
train
emmetio/markup-formatters
format/html.js
setFormatting
function setFormatting(outNode, profile) { const node = outNode.node; if (shouldFormatNode(node, profile)) { outNode.indent = profile.indent(getIndentLevel(node, profile)); outNode.newline = '\n'; const prefix = outNode.newline + outNode.indent; // do not format the very first node in output if (!isRoot(node.parent) || !isFirstChild(node)) { outNode.beforeOpen = prefix; if (node.isTextOnly) { outNode.beforeText = prefix; } } if (hasInnerFormatting(node, profile)) { if (!node.isTextOnly) { outNode.beforeText = prefix + profile.indent(1); } outNode.beforeClose = prefix; } } return outNode; }
javascript
function setFormatting(outNode, profile) { const node = outNode.node; if (shouldFormatNode(node, profile)) { outNode.indent = profile.indent(getIndentLevel(node, profile)); outNode.newline = '\n'; const prefix = outNode.newline + outNode.indent; // do not format the very first node in output if (!isRoot(node.parent) || !isFirstChild(node)) { outNode.beforeOpen = prefix; if (node.isTextOnly) { outNode.beforeText = prefix; } } if (hasInnerFormatting(node, profile)) { if (!node.isTextOnly) { outNode.beforeText = prefix + profile.indent(1); } outNode.beforeClose = prefix; } } return outNode; }
[ "function", "setFormatting", "(", "outNode", ",", "profile", ")", "{", "const", "node", "=", "outNode", ".", "node", ";", "if", "(", "shouldFormatNode", "(", "node", ",", "profile", ")", ")", "{", "outNode", ".", "indent", "=", "profile", ".", "indent", "(", "getIndentLevel", "(", "node", ",", "profile", ")", ")", ";", "outNode", ".", "newline", "=", "'\\n'", ";", "\\n", "const", "prefix", "=", "outNode", ".", "newline", "+", "outNode", ".", "indent", ";", "if", "(", "!", "isRoot", "(", "node", ".", "parent", ")", "||", "!", "isFirstChild", "(", "node", ")", ")", "{", "outNode", ".", "beforeOpen", "=", "prefix", ";", "if", "(", "node", ".", "isTextOnly", ")", "{", "outNode", ".", "beforeText", "=", "prefix", ";", "}", "}", "}", "if", "(", "hasInnerFormatting", "(", "node", ",", "profile", ")", ")", "{", "if", "(", "!", "node", ".", "isTextOnly", ")", "{", "outNode", ".", "beforeText", "=", "prefix", "+", "profile", ".", "indent", "(", "1", ")", ";", "}", "outNode", ".", "beforeClose", "=", "prefix", ";", "}", "}" ]
Updates formatting properties for given output node @param {OutputNode} outNode Output wrapper of farsed abbreviation node @param {Profile} profile Output profile @return {OutputNode}
[ "Updates", "formatting", "properties", "for", "given", "output", "node" ]
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/html.js#L70-L95
train
emmetio/markup-formatters
format/html.js
shouldFormatNode
function shouldFormatNode(node, profile) { if (!profile.get('format')) { return false; } if (node.parent.isTextOnly && node.parent.children.length === 1 && parseFields(node.parent.value).fields.length) { // Edge case: do not format the only child of text-only node, // but only if parent contains fields return false; } return isInline(node, profile) ? shouldFormatInline(node, profile) : true; }
javascript
function shouldFormatNode(node, profile) { if (!profile.get('format')) { return false; } if (node.parent.isTextOnly && node.parent.children.length === 1 && parseFields(node.parent.value).fields.length) { // Edge case: do not format the only child of text-only node, // but only if parent contains fields return false; } return isInline(node, profile) ? shouldFormatInline(node, profile) : true; }
[ "function", "shouldFormatNode", "(", "node", ",", "profile", ")", "{", "if", "(", "!", "profile", ".", "get", "(", "'format'", ")", ")", "{", "return", "false", ";", "}", "if", "(", "node", ".", "parent", ".", "isTextOnly", "&&", "node", ".", "parent", ".", "children", ".", "length", "===", "1", "&&", "parseFields", "(", "node", ".", "parent", ".", "value", ")", ".", "fields", ".", "length", ")", "{", "return", "false", ";", "}", "return", "isInline", "(", "node", ",", "profile", ")", "?", "shouldFormatInline", "(", "node", ",", "profile", ")", ":", "true", ";", "}" ]
Check if given node should be formatted @param {Node} node @param {Profile} profile @return {Boolean}
[ "Check", "if", "given", "node", "should", "be", "formatted" ]
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/html.js#L103-L117
train
emmetio/markup-formatters
format/html.js
formatAttributes
function formatAttributes(outNode, profile) { const node = outNode.node; return node.attributes.map(attr => { if (attr.options.implied && attr.value == null) { return null; } const attrName = profile.attribute(attr.name); let attrValue = null; // handle boolean attributes if (attr.options.boolean || profile.get('booleanAttributes').indexOf(attrName.toLowerCase()) !== -1) { if (profile.get('compactBooleanAttributes') && attr.value == null) { return ` ${attrName}`; } else if (attr.value == null) { attrValue = attrName; } } if (attrValue == null) { attrValue = outNode.renderFields(attr.value); } return attr.options.before && attr.options.after ? ` ${attrName}=${attr.options.before+attrValue+attr.options.after}` : ` ${attrName}=${profile.quote(attrValue)}`; }).join(''); }
javascript
function formatAttributes(outNode, profile) { const node = outNode.node; return node.attributes.map(attr => { if (attr.options.implied && attr.value == null) { return null; } const attrName = profile.attribute(attr.name); let attrValue = null; // handle boolean attributes if (attr.options.boolean || profile.get('booleanAttributes').indexOf(attrName.toLowerCase()) !== -1) { if (profile.get('compactBooleanAttributes') && attr.value == null) { return ` ${attrName}`; } else if (attr.value == null) { attrValue = attrName; } } if (attrValue == null) { attrValue = outNode.renderFields(attr.value); } return attr.options.before && attr.options.after ? ` ${attrName}=${attr.options.before+attrValue+attr.options.after}` : ` ${attrName}=${profile.quote(attrValue)}`; }).join(''); }
[ "function", "formatAttributes", "(", "outNode", ",", "profile", ")", "{", "const", "node", "=", "outNode", ".", "node", ";", "return", "node", ".", "attributes", ".", "map", "(", "attr", "=>", "{", "if", "(", "attr", ".", "options", ".", "implied", "&&", "attr", ".", "value", "==", "null", ")", "{", "return", "null", ";", "}", "const", "attrName", "=", "profile", ".", "attribute", "(", "attr", ".", "name", ")", ";", "let", "attrValue", "=", "null", ";", "if", "(", "attr", ".", "options", ".", "boolean", "||", "profile", ".", "get", "(", "'booleanAttributes'", ")", ".", "indexOf", "(", "attrName", ".", "toLowerCase", "(", ")", ")", "!==", "-", "1", ")", "{", "if", "(", "profile", ".", "get", "(", "'compactBooleanAttributes'", ")", "&&", "attr", ".", "value", "==", "null", ")", "{", "return", "`", "${", "attrName", "}", "`", ";", "}", "else", "if", "(", "attr", ".", "value", "==", "null", ")", "{", "attrValue", "=", "attrName", ";", "}", "}", "if", "(", "attrValue", "==", "null", ")", "{", "attrValue", "=", "outNode", ".", "renderFields", "(", "attr", ".", "value", ")", ";", "}", "return", "attr", ".", "options", ".", "before", "&&", "attr", ".", "options", ".", "after", "?", "`", "${", "attrName", "}", "${", "attr", ".", "options", ".", "before", "+", "attrValue", "+", "attr", ".", "options", ".", "after", "}", "`", ":", "`", "${", "attrName", "}", "${", "profile", ".", "quote", "(", "attrValue", ")", "}", "`", ";", "}", ")", ".", "join", "(", "''", ")", ";", "}" ]
Outputs attributes of given abbreviation node as HTML attributes @param {OutputNode} outNode @param {Profile} profile @return {String}
[ "Outputs", "attributes", "of", "given", "abbreviation", "node", "as", "HTML", "attributes" ]
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/html.js#L208-L236
train
emmetio/markup-formatters
format/html.js
getIndentLevel
function getIndentLevel(node, profile) { // Increase indent level IF NOT: // * parent is text-only node // * there’s a parent node with a name that is explicitly set to decrease level const skip = profile.get('formatSkip') || []; let level = node.parent.isTextOnly ? -2 : -1; let ctx = node; while (ctx = ctx.parent) { if (skip.indexOf( (ctx.name || '').toLowerCase() ) === -1) { level++; } } return level < 0 ? 0 : level; }
javascript
function getIndentLevel(node, profile) { // Increase indent level IF NOT: // * parent is text-only node // * there’s a parent node with a name that is explicitly set to decrease level const skip = profile.get('formatSkip') || []; let level = node.parent.isTextOnly ? -2 : -1; let ctx = node; while (ctx = ctx.parent) { if (skip.indexOf( (ctx.name || '').toLowerCase() ) === -1) { level++; } } return level < 0 ? 0 : level; }
[ "function", "getIndentLevel", "(", "node", ",", "profile", ")", "{", "const", "skip", "=", "profile", ".", "get", "(", "'formatSkip'", ")", "||", "[", "]", ";", "let", "level", "=", "node", ".", "parent", ".", "isTextOnly", "?", "-", "2", ":", "-", "1", ";", "let", "ctx", "=", "node", ";", "while", "(", "ctx", "=", "ctx", ".", "parent", ")", "{", "if", "(", "skip", ".", "indexOf", "(", "(", "ctx", ".", "name", "||", "''", ")", ".", "toLowerCase", "(", ")", ")", "===", "-", "1", ")", "{", "level", "++", ";", "}", "}", "return", "level", "<", "0", "?", "0", ":", "level", ";", "}" ]
Computes indent level for given node @param {Node} node @param {Profile} profile @param {Number} level @return {Number}
[ "Computes", "indent", "level", "for", "given", "node" ]
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/html.js#L266-L280
train
emmetio/markup-formatters
format/html.js
commentNode
function commentNode(outNode, options) { const node = outNode.node; if (!options.enabled || !options.trigger || !node.name) { return; } const attrs = outNode.node.attributes.reduce((out, attr) => { if (attr.name && attr.value != null) { out[attr.name.toUpperCase().replace(/-/g, '_')] = attr.value; } return out; }, {}); // add comment only if attribute trigger is present for (let i = 0, il = options.trigger.length; i < il; i++) { if (options.trigger[i].toUpperCase() in attrs) { outNode.open = template(options.before, attrs) + outNode.open; if (outNode.close) { outNode.close += template(options.after, attrs); } break; } } }
javascript
function commentNode(outNode, options) { const node = outNode.node; if (!options.enabled || !options.trigger || !node.name) { return; } const attrs = outNode.node.attributes.reduce((out, attr) => { if (attr.name && attr.value != null) { out[attr.name.toUpperCase().replace(/-/g, '_')] = attr.value; } return out; }, {}); // add comment only if attribute trigger is present for (let i = 0, il = options.trigger.length; i < il; i++) { if (options.trigger[i].toUpperCase() in attrs) { outNode.open = template(options.before, attrs) + outNode.open; if (outNode.close) { outNode.close += template(options.after, attrs); } break; } } }
[ "function", "commentNode", "(", "outNode", ",", "options", ")", "{", "const", "node", "=", "outNode", ".", "node", ";", "if", "(", "!", "options", ".", "enabled", "||", "!", "options", ".", "trigger", "||", "!", "node", ".", "name", ")", "{", "return", ";", "}", "const", "attrs", "=", "outNode", ".", "node", ".", "attributes", ".", "reduce", "(", "(", "out", ",", "attr", ")", "=>", "{", "if", "(", "attr", ".", "name", "&&", "attr", ".", "value", "!=", "null", ")", "{", "out", "[", "attr", ".", "name", ".", "toUpperCase", "(", ")", ".", "replace", "(", "/", "-", "/", "g", ",", "'_'", ")", "]", "=", "attr", ".", "value", ";", "}", "return", "out", ";", "}", ",", "{", "}", ")", ";", "for", "(", "let", "i", "=", "0", ",", "il", "=", "options", ".", "trigger", ".", "length", ";", "i", "<", "il", ";", "i", "++", ")", "{", "if", "(", "options", ".", "trigger", "[", "i", "]", ".", "toUpperCase", "(", ")", "in", "attrs", ")", "{", "outNode", ".", "open", "=", "template", "(", "options", ".", "before", ",", "attrs", ")", "+", "outNode", ".", "open", ";", "if", "(", "outNode", ".", "close", ")", "{", "outNode", ".", "close", "+=", "template", "(", "options", ".", "after", ",", "attrs", ")", ";", "}", "break", ";", "}", "}", "}" ]
Comments given output node, if required @param {OutputNode} outNode @param {Object} options
[ "Comments", "given", "output", "node", "if", "required" ]
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/html.js#L287-L312
train
flohil/wdio-workflo
dist/lib/page_objects/page_elements/ValuePageElementGroup.js
isIValueElementNode
function isIValueElementNode(node) { return typeof node['getValue'] === 'function' && typeof node['setValue'] === 'function' && typeof node.currently['getValue'] === 'function' && typeof node.currently['hasValue'] === 'function' && typeof node.currently['hasAnyValue'] === 'function' && typeof node.currently['containsValue'] === 'function' && typeof node.wait['hasValue'] === 'function' && typeof node.wait['hasAnyValue'] === 'function' && typeof node.wait['containsValue'] === 'function' && typeof node.eventually['hasValue'] === 'function' && typeof node.eventually['hasAnyValue'] === 'function' && typeof node.eventually['containsValue'] === 'function'; }
javascript
function isIValueElementNode(node) { return typeof node['getValue'] === 'function' && typeof node['setValue'] === 'function' && typeof node.currently['getValue'] === 'function' && typeof node.currently['hasValue'] === 'function' && typeof node.currently['hasAnyValue'] === 'function' && typeof node.currently['containsValue'] === 'function' && typeof node.wait['hasValue'] === 'function' && typeof node.wait['hasAnyValue'] === 'function' && typeof node.wait['containsValue'] === 'function' && typeof node.eventually['hasValue'] === 'function' && typeof node.eventually['hasAnyValue'] === 'function' && typeof node.eventually['containsValue'] === 'function'; }
[ "function", "isIValueElementNode", "(", "node", ")", "{", "return", "typeof", "node", "[", "'getValue'", "]", "===", "'function'", "&&", "typeof", "node", "[", "'setValue'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", "'getValue'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", "'hasValue'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", "'hasAnyValue'", "]", "===", "'function'", "&&", "typeof", "node", ".", "currently", "[", "'containsValue'", "]", "===", "'function'", "&&", "typeof", "node", ".", "wait", "[", "'hasValue'", "]", "===", "'function'", "&&", "typeof", "node", ".", "wait", "[", "'hasAnyValue'", "]", "===", "'function'", "&&", "typeof", "node", ".", "wait", "[", "'containsValue'", "]", "===", "'function'", "&&", "typeof", "node", ".", "eventually", "[", "'hasValue'", "]", "===", "'function'", "&&", "typeof", "node", ".", "eventually", "[", "'hasAnyValue'", "]", "===", "'function'", "&&", "typeof", "node", ".", "eventually", "[", "'containsValue'", "]", "===", "'function'", ";", "}" ]
type guards Returns true if the passed node supports all functions defined in IValueElementNode. @param node a PageNode
[ "type", "guards", "Returns", "true", "if", "the", "passed", "node", "supports", "all", "functions", "defined", "in", "IValueElementNode", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/page_objects/page_elements/ValuePageElementGroup.js#L432-L445
train
flohil/wdio-workflo
dist/lib/jasmineMatchers.js
prettifyDiffObj
function prettifyDiffObj(diff) { const obj = { kind: undefined, path: undefined, expect: undefined, actual: undefined, index: undefined, item: undefined, }; if (diff.kind) { switch (diff.kind) { case 'N': obj.kind = 'New'; break; case 'D': obj.kind = 'Missing'; break; case 'E': obj.kind = 'Changed'; break; case 'A': obj.kind = 'Array Canged'; break; } } if (diff.path) { let path = diff.path[0]; for (let i = 1; i < diff.path.length; i++) { path += `/${diff.path[i]}`; } obj.path = path; } if (typeof diff.lhs !== 'undefined') { obj.expect = diff.lhs; } if (typeof diff.rhs !== 'undefined') { obj.actual = diff.rhs; } if (diff.index) { obj.index = diff.index; } if (diff.item) { obj.item = prettifyDiffObj(diff.item); } return obj; }
javascript
function prettifyDiffObj(diff) { const obj = { kind: undefined, path: undefined, expect: undefined, actual: undefined, index: undefined, item: undefined, }; if (diff.kind) { switch (diff.kind) { case 'N': obj.kind = 'New'; break; case 'D': obj.kind = 'Missing'; break; case 'E': obj.kind = 'Changed'; break; case 'A': obj.kind = 'Array Canged'; break; } } if (diff.path) { let path = diff.path[0]; for (let i = 1; i < diff.path.length; i++) { path += `/${diff.path[i]}`; } obj.path = path; } if (typeof diff.lhs !== 'undefined') { obj.expect = diff.lhs; } if (typeof diff.rhs !== 'undefined') { obj.actual = diff.rhs; } if (diff.index) { obj.index = diff.index; } if (diff.item) { obj.item = prettifyDiffObj(diff.item); } return obj; }
[ "function", "prettifyDiffObj", "(", "diff", ")", "{", "const", "obj", "=", "{", "kind", ":", "undefined", ",", "path", ":", "undefined", ",", "expect", ":", "undefined", ",", "actual", ":", "undefined", ",", "index", ":", "undefined", ",", "item", ":", "undefined", ",", "}", ";", "if", "(", "diff", ".", "kind", ")", "{", "switch", "(", "diff", ".", "kind", ")", "{", "case", "'N'", ":", "obj", ".", "kind", "=", "'New'", ";", "break", ";", "case", "'D'", ":", "obj", ".", "kind", "=", "'Missing'", ";", "break", ";", "case", "'E'", ":", "obj", ".", "kind", "=", "'Changed'", ";", "break", ";", "case", "'A'", ":", "obj", ".", "kind", "=", "'Array Canged'", ";", "break", ";", "}", "}", "if", "(", "diff", ".", "path", ")", "{", "let", "path", "=", "diff", ".", "path", "[", "0", "]", ";", "for", "(", "let", "i", "=", "1", ";", "i", "<", "diff", ".", "path", ".", "length", ";", "i", "++", ")", "{", "path", "+=", "`", "${", "diff", ".", "path", "[", "i", "]", "}", "`", ";", "}", "obj", ".", "path", "=", "path", ";", "}", "if", "(", "typeof", "diff", ".", "lhs", "!==", "'undefined'", ")", "{", "obj", ".", "expect", "=", "diff", ".", "lhs", ";", "}", "if", "(", "typeof", "diff", ".", "rhs", "!==", "'undefined'", ")", "{", "obj", ".", "actual", "=", "diff", ".", "rhs", ";", "}", "if", "(", "diff", ".", "index", ")", "{", "obj", ".", "index", "=", "diff", ".", "index", ";", "}", "if", "(", "diff", ".", "item", ")", "{", "obj", ".", "item", "=", "prettifyDiffObj", "(", "diff", ".", "item", ")", ";", "}", "return", "obj", ";", "}" ]
DEFINE INTERNAL UTILITY FUNCTIONS BELOW makes output of a single diff more readable
[ "DEFINE", "INTERNAL", "UTILITY", "FUNCTIONS", "BELOW", "makes", "output", "of", "a", "single", "diff", "more", "readable" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/jasmineMatchers.js#L120-L165
train
flohil/wdio-workflo
dist/lib/jasmineMatchers.js
prettifyDiffOutput
function prettifyDiffOutput(diffArr) { const res = []; for (const diff of diffArr) { res.push(prettifyDiffObj(diff)); } return res; }
javascript
function prettifyDiffOutput(diffArr) { const res = []; for (const diff of diffArr) { res.push(prettifyDiffObj(diff)); } return res; }
[ "function", "prettifyDiffOutput", "(", "diffArr", ")", "{", "const", "res", "=", "[", "]", ";", "for", "(", "const", "diff", "of", "diffArr", ")", "{", "res", ".", "push", "(", "prettifyDiffObj", "(", "diff", ")", ")", ";", "}", "return", "res", ";", "}" ]
makes output of a diff object array more readable
[ "makes", "output", "of", "a", "diff", "object", "array", "more", "readable" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/jasmineMatchers.js#L167-L173
train
telehash/e3x-js
e3x.js
cleanup
function cleanup() { if(chan.timer) clearTimeout(chan.timer); chan.timer = setTimeout(function(){ chan.state = "gone"; // in case an app has a reference x.channels[chan.id] = {state:"gone"}; // remove our reference for gc }, chan.timeout); }
javascript
function cleanup() { if(chan.timer) clearTimeout(chan.timer); chan.timer = setTimeout(function(){ chan.state = "gone"; // in case an app has a reference x.channels[chan.id] = {state:"gone"}; // remove our reference for gc }, chan.timeout); }
[ "function", "cleanup", "(", ")", "{", "if", "(", "chan", ".", "timer", ")", "clearTimeout", "(", "chan", ".", "timer", ")", ";", "chan", ".", "timer", "=", "setTimeout", "(", "function", "(", ")", "{", "chan", ".", "state", "=", "\"gone\"", ";", "x", ".", "channels", "[", "chan", ".", "id", "]", "=", "{", "state", ":", "\"gone\"", "}", ";", "}", ",", "chan", ".", "timeout", ")", ";", "}" ]
track all active channels to route incoming packets called to do eventual cleanup
[ "track", "all", "active", "channels", "to", "route", "incoming", "packets", "called", "to", "do", "eventual", "cleanup" ]
0f96c0e57c85c81f340dba79df1ce6fd411fb0d6
https://github.com/telehash/e3x-js/blob/0f96c0e57c85c81f340dba79df1ce6fd411fb0d6/e3x.js#L313-L320
train
flohil/wdio-workflo
dist/lib/steps.js
proxifySteps
function proxifySteps(stepDefinitions) { return new Proxy(stepDefinitions, { get: (target, name, receiver) => stepsGetter(target, name, receiver), set: (target, name, value) => stepsSetter(target, name, value), }); }
javascript
function proxifySteps(stepDefinitions) { return new Proxy(stepDefinitions, { get: (target, name, receiver) => stepsGetter(target, name, receiver), set: (target, name, value) => stepsSetter(target, name, value), }); }
[ "function", "proxifySteps", "(", "stepDefinitions", ")", "{", "return", "new", "Proxy", "(", "stepDefinitions", ",", "{", "get", ":", "(", "target", ",", "name", ",", "receiver", ")", "=>", "stepsGetter", "(", "target", ",", "name", ",", "receiver", ")", ",", "set", ":", "(", "target", ",", "name", ",", "value", ")", "=>", "stepsSetter", "(", "target", ",", "name", ",", "value", ")", ",", "}", ")", ";", "}" ]
Creates a Proxy that adds custom getters and setters to the merged step definitions. Steps in wdio-workflo can only function properly if this proxy is used to interact with them. @param stepDefinitions the merged step definitions @returns the proxified steps
[ "Creates", "a", "Proxy", "that", "adds", "custom", "getters", "and", "setters", "to", "the", "merged", "step", "definitions", ".", "Steps", "in", "wdio", "-", "workflo", "can", "only", "function", "properly", "if", "this", "proxy", "is", "used", "to", "interact", "with", "them", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/steps.js#L57-L62
train
flohil/wdio-workflo
dist/lib/utility_functions/array.js
mapToObject
function mapToObject(input, mapFunc) { const obj = {}; for (const element of input) { obj[element] = mapFunc(element); } return obj; }
javascript
function mapToObject(input, mapFunc) { const obj = {}; for (const element of input) { obj[element] = mapFunc(element); } return obj; }
[ "function", "mapToObject", "(", "input", ",", "mapFunc", ")", "{", "const", "obj", "=", "{", "}", ";", "for", "(", "const", "element", "of", "input", ")", "{", "obj", "[", "element", "]", "=", "mapFunc", "(", "element", ")", ";", "}", "return", "obj", ";", "}" ]
Gets an input array and maps it to an object where the property keys correspond to the array elements and the property values are defiend by mapFunc. @param input @param mapFunc
[ "Gets", "an", "input", "array", "and", "maps", "it", "to", "an", "object", "where", "the", "property", "keys", "correspond", "to", "the", "array", "elements", "and", "the", "property", "values", "are", "defiend", "by", "mapFunc", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/utility_functions/array.js#L11-L17
train
igocreate/igo
cli/i18n.js
function(args, callback) { if (!config.i18n.spreadsheet_id) { return callback('Missing config.i18n.spreadsheet_id'); } const path = 'https://spreadsheets.google.com/feeds/list/' + config.i18n.spreadsheet_id + '/default/public/values?alt=json'; // request json data request(path, (err, res, body) => { if (err) { return callback(err); } const json = JSON.parse(body); //console.dir(json); const translations = {}; // parse json.feed.entry.forEach(entry => { // const key = _.get(entry, 'gsx$key.$t'); config.i18n.whitelist.forEach((lang) => { const value = _.get(entry, 'gsx$' + lang + '.$t'); if (value) { _.setWith(translations, lang + '.' + key, value, Object); } }); }); // write translation files config.i18n.whitelist.forEach((lang) => { const dir = `./locales/${lang}`; if (!fs.existsSync(dir)) { console.warn('Missing directory: ' + dir); return; } translations[lang]._meta = { generated_at: new Date(), lang }; const data = JSON.stringify(translations[lang], null, 2); const filename = `${dir}/translation.json`; console.log('Writing ' + filename); fs.writeFileSync(filename, data ); }); callback(); }); }
javascript
function(args, callback) { if (!config.i18n.spreadsheet_id) { return callback('Missing config.i18n.spreadsheet_id'); } const path = 'https://spreadsheets.google.com/feeds/list/' + config.i18n.spreadsheet_id + '/default/public/values?alt=json'; // request json data request(path, (err, res, body) => { if (err) { return callback(err); } const json = JSON.parse(body); //console.dir(json); const translations = {}; // parse json.feed.entry.forEach(entry => { // const key = _.get(entry, 'gsx$key.$t'); config.i18n.whitelist.forEach((lang) => { const value = _.get(entry, 'gsx$' + lang + '.$t'); if (value) { _.setWith(translations, lang + '.' + key, value, Object); } }); }); // write translation files config.i18n.whitelist.forEach((lang) => { const dir = `./locales/${lang}`; if (!fs.existsSync(dir)) { console.warn('Missing directory: ' + dir); return; } translations[lang]._meta = { generated_at: new Date(), lang }; const data = JSON.stringify(translations[lang], null, 2); const filename = `${dir}/translation.json`; console.log('Writing ' + filename); fs.writeFileSync(filename, data ); }); callback(); }); }
[ "function", "(", "args", ",", "callback", ")", "{", "if", "(", "!", "config", ".", "i18n", ".", "spreadsheet_id", ")", "{", "return", "callback", "(", "'Missing config.i18n.spreadsheet_id'", ")", ";", "}", "const", "path", "=", "'https://spreadsheets.google.com/feeds/list/'", "+", "config", ".", "i18n", ".", "spreadsheet_id", "+", "'/default/public/values?alt=json'", ";", "request", "(", "path", ",", "(", "err", ",", "res", ",", "body", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "const", "json", "=", "JSON", ".", "parse", "(", "body", ")", ";", "const", "translations", "=", "{", "}", ";", "json", ".", "feed", ".", "entry", ".", "forEach", "(", "entry", "=>", "{", "const", "key", "=", "_", ".", "get", "(", "entry", ",", "'gsx$key.$t'", ")", ";", "config", ".", "i18n", ".", "whitelist", ".", "forEach", "(", "(", "lang", ")", "=>", "{", "const", "value", "=", "_", ".", "get", "(", "entry", ",", "'gsx$'", "+", "lang", "+", "'.$t'", ")", ";", "if", "(", "value", ")", "{", "_", ".", "setWith", "(", "translations", ",", "lang", "+", "'.'", "+", "key", ",", "value", ",", "Object", ")", ";", "}", "}", ")", ";", "}", ")", ";", "config", ".", "i18n", ".", "whitelist", ".", "forEach", "(", "(", "lang", ")", "=>", "{", "const", "dir", "=", "`", "${", "lang", "}", "`", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "dir", ")", ")", "{", "console", ".", "warn", "(", "'Missing directory: '", "+", "dir", ")", ";", "return", ";", "}", "translations", "[", "lang", "]", ".", "_meta", "=", "{", "generated_at", ":", "new", "Date", "(", ")", ",", "lang", "}", ";", "const", "data", "=", "JSON", ".", "stringify", "(", "translations", "[", "lang", "]", ",", "null", ",", "2", ")", ";", "const", "filename", "=", "`", "${", "dir", "}", "`", ";", "console", ".", "log", "(", "'Writing '", "+", "filename", ")", ";", "fs", ".", "writeFileSync", "(", "filename", ",", "data", ")", ";", "}", ")", ";", "callback", "(", ")", ";", "}", ")", ";", "}" ]
igo i18n update
[ "igo", "i18n", "update" ]
fab4409260c648cad55f7b00b7a93ab2d9d8124c
https://github.com/igocreate/igo/blob/fab4409260c648cad55f7b00b7a93ab2d9d8124c/cli/i18n.js#L11-L60
train
flohil/wdio-workflo
dist/lib/matchers.js
convertDiffToMessages
function convertDiffToMessages(diff, actualOnly = false, includeTimeouts = false, timeout = undefined, comparisonLines = [], paths = []) { if (diff.tree && Object.keys(diff.tree).length > 0) { const keys = Object.keys(diff.tree); keys.forEach(key => { const _paths = [...paths]; _paths.push(key); convertDiffToMessages(diff.tree[key], actualOnly, includeTimeouts, timeout, comparisonLines, _paths); }); } else { let _paths = paths.join(''); if (_paths.charAt(0) === '.') { _paths = _paths.substring(1); } const _actual = printValue(diff.actual); const _expected = printValue(diff.expected); let compareStr = ''; if (actualOnly) { compareStr = (typeof diff.actual === 'undefined') ? '' : `{actual: <${_actual}>}\n`; } else { compareStr = (typeof diff.actual === 'undefined' && typeof diff.expected === 'undefined') ? '' : `{actual: <${_actual}>, expected: <${_expected}>}\n`; } const timeoutStr = (includeTimeouts) ? ` within ${timeout || diff.timeout}ms` : ''; comparisonLines.push(`${diff.constructorName} at path '${_paths}'${timeoutStr}\n${compareStr}( ${diff.selector} )`); } return comparisonLines; }
javascript
function convertDiffToMessages(diff, actualOnly = false, includeTimeouts = false, timeout = undefined, comparisonLines = [], paths = []) { if (diff.tree && Object.keys(diff.tree).length > 0) { const keys = Object.keys(diff.tree); keys.forEach(key => { const _paths = [...paths]; _paths.push(key); convertDiffToMessages(diff.tree[key], actualOnly, includeTimeouts, timeout, comparisonLines, _paths); }); } else { let _paths = paths.join(''); if (_paths.charAt(0) === '.') { _paths = _paths.substring(1); } const _actual = printValue(diff.actual); const _expected = printValue(diff.expected); let compareStr = ''; if (actualOnly) { compareStr = (typeof diff.actual === 'undefined') ? '' : `{actual: <${_actual}>}\n`; } else { compareStr = (typeof diff.actual === 'undefined' && typeof diff.expected === 'undefined') ? '' : `{actual: <${_actual}>, expected: <${_expected}>}\n`; } const timeoutStr = (includeTimeouts) ? ` within ${timeout || diff.timeout}ms` : ''; comparisonLines.push(`${diff.constructorName} at path '${_paths}'${timeoutStr}\n${compareStr}( ${diff.selector} )`); } return comparisonLines; }
[ "function", "convertDiffToMessages", "(", "diff", ",", "actualOnly", "=", "false", ",", "includeTimeouts", "=", "false", ",", "timeout", "=", "undefined", ",", "comparisonLines", "=", "[", "]", ",", "paths", "=", "[", "]", ")", "{", "if", "(", "diff", ".", "tree", "&&", "Object", ".", "keys", "(", "diff", ".", "tree", ")", ".", "length", ">", "0", ")", "{", "const", "keys", "=", "Object", ".", "keys", "(", "diff", ".", "tree", ")", ";", "keys", ".", "forEach", "(", "key", "=>", "{", "const", "_paths", "=", "[", "...", "paths", "]", ";", "_paths", ".", "push", "(", "key", ")", ";", "convertDiffToMessages", "(", "diff", ".", "tree", "[", "key", "]", ",", "actualOnly", ",", "includeTimeouts", ",", "timeout", ",", "comparisonLines", ",", "_paths", ")", ";", "}", ")", ";", "}", "else", "{", "let", "_paths", "=", "paths", ".", "join", "(", "''", ")", ";", "if", "(", "_paths", ".", "charAt", "(", "0", ")", "===", "'.'", ")", "{", "_paths", "=", "_paths", ".", "substring", "(", "1", ")", ";", "}", "const", "_actual", "=", "printValue", "(", "diff", ".", "actual", ")", ";", "const", "_expected", "=", "printValue", "(", "diff", ".", "expected", ")", ";", "let", "compareStr", "=", "''", ";", "if", "(", "actualOnly", ")", "{", "compareStr", "=", "(", "typeof", "diff", ".", "actual", "===", "'undefined'", ")", "?", "''", ":", "`", "${", "_actual", "}", "\\n", "`", ";", "}", "else", "{", "compareStr", "=", "(", "typeof", "diff", ".", "actual", "===", "'undefined'", "&&", "typeof", "diff", ".", "expected", "===", "'undefined'", ")", "?", "''", ":", "`", "${", "_actual", "}", "${", "_expected", "}", "\\n", "`", ";", "}", "const", "timeoutStr", "=", "(", "includeTimeouts", ")", "?", "`", "${", "timeout", "||", "diff", ".", "timeout", "}", "`", ":", "''", ";", "comparisonLines", ".", "push", "(", "`", "${", "diff", ".", "constructorName", "}", "${", "_paths", "}", "${", "timeoutStr", "}", "\\n", "${", "compareStr", "}", "${", "diff", ".", "selector", "}", "`", ")", ";", "}", "return", "comparisonLines", ";", "}" ]
ERROR TEXT FUNCTIONS
[ "ERROR", "TEXT", "FUNCTIONS" ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/matchers.js#L281-L310
train
flohil/wdio-workflo
dist/lib/utility_functions/util.js
convertToObject
function convertToObject(unknownTypedInput, valueFunc = undefined) { let obj = {}; if (typeof unknownTypedInput !== 'undefined') { if (typeof unknownTypedInput === 'string') { unknownTypedInput = [unknownTypedInput]; } if (_.isArray(unknownTypedInput)) { for (const element of unknownTypedInput) { let value; if (typeof valueFunc !== 'undefined') { value = valueFunc(element); } else { value = undefined; } obj[element] = value; } } else { obj = _.cloneDeep(unknownTypedInput); } } return obj; }
javascript
function convertToObject(unknownTypedInput, valueFunc = undefined) { let obj = {}; if (typeof unknownTypedInput !== 'undefined') { if (typeof unknownTypedInput === 'string') { unknownTypedInput = [unknownTypedInput]; } if (_.isArray(unknownTypedInput)) { for (const element of unknownTypedInput) { let value; if (typeof valueFunc !== 'undefined') { value = valueFunc(element); } else { value = undefined; } obj[element] = value; } } else { obj = _.cloneDeep(unknownTypedInput); } } return obj; }
[ "function", "convertToObject", "(", "unknownTypedInput", ",", "valueFunc", "=", "undefined", ")", "{", "let", "obj", "=", "{", "}", ";", "if", "(", "typeof", "unknownTypedInput", "!==", "'undefined'", ")", "{", "if", "(", "typeof", "unknownTypedInput", "===", "'string'", ")", "{", "unknownTypedInput", "=", "[", "unknownTypedInput", "]", ";", "}", "if", "(", "_", ".", "isArray", "(", "unknownTypedInput", ")", ")", "{", "for", "(", "const", "element", "of", "unknownTypedInput", ")", "{", "let", "value", ";", "if", "(", "typeof", "valueFunc", "!==", "'undefined'", ")", "{", "value", "=", "valueFunc", "(", "element", ")", ";", "}", "else", "{", "value", "=", "undefined", ";", "}", "obj", "[", "element", "]", "=", "value", ";", "}", "}", "else", "{", "obj", "=", "_", ".", "cloneDeep", "(", "unknownTypedInput", ")", ";", "}", "}", "return", "obj", ";", "}" ]
Converts strings, arrays and objects into objects. If input is string, output is an object with one entry where the key is the string. If input is array, output is an object where each key represents one element in the array. If input is object, output is a clone of the input object. For strings and arrays, valueFunc is used to calculate the resulting object's property values. For objects, valueFunc has no effect -> original property values will be preserved! @param unknownTypedInput @param valueFunc
[ "Converts", "strings", "arrays", "and", "objects", "into", "objects", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/utility_functions/util.js#L20-L43
train
flohil/wdio-workflo
dist/lib/utility_functions/util.js
compare
function compare(var1, var2, operator) { switch (operator) { case Workflo.Comparator.equalTo || Workflo.Comparator.eq: return var1 === var2; case Workflo.Comparator.notEqualTo || Workflo.Comparator.ne: return var1 !== var2; case Workflo.Comparator.greaterThan || Workflo.Comparator.gt: return var1 > var2; case Workflo.Comparator.lessThan || Workflo.Comparator.lt: return var1 < var2; } }
javascript
function compare(var1, var2, operator) { switch (operator) { case Workflo.Comparator.equalTo || Workflo.Comparator.eq: return var1 === var2; case Workflo.Comparator.notEqualTo || Workflo.Comparator.ne: return var1 !== var2; case Workflo.Comparator.greaterThan || Workflo.Comparator.gt: return var1 > var2; case Workflo.Comparator.lessThan || Workflo.Comparator.lt: return var1 < var2; } }
[ "function", "compare", "(", "var1", ",", "var2", ",", "operator", ")", "{", "switch", "(", "operator", ")", "{", "case", "Workflo", ".", "Comparator", ".", "equalTo", "||", "Workflo", ".", "Comparator", ".", "eq", ":", "return", "var1", "===", "var2", ";", "case", "Workflo", ".", "Comparator", ".", "notEqualTo", "||", "Workflo", ".", "Comparator", ".", "ne", ":", "return", "var1", "!==", "var2", ";", "case", "Workflo", ".", "Comparator", ".", "greaterThan", "||", "Workflo", ".", "Comparator", ".", "gt", ":", "return", "var1", ">", "var2", ";", "case", "Workflo", ".", "Comparator", ".", "lessThan", "||", "Workflo", ".", "Comparator", ".", "lt", ":", "return", "var1", "<", "var2", ";", "}", "}" ]
This function compares the values of two passed variables with a compare method defined in `operator`. The following compare methods are supported: - equals - not equals - less than - greater than @template Type the type of the compared variables @param var1 the first variable to be compared @param var2 the second variable to be compared @param operator defines the method to be used for the comparison (===, !==, <, >) @returns the result of the comparison
[ "This", "function", "compares", "the", "values", "of", "two", "passed", "variables", "with", "a", "compare", "method", "defined", "in", "operator", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/utility_functions/util.js#L61-L72
train
uber-archive/thriftify
compiler/spec.js
Types
function Types() { this.binary = specs.ABinary; this.string = specs.AString; this.bool = specs.ABoolean; this.byte = specs.AByte; this.i16 = specs.AInt16; this.i32 = specs.AInt32; this.i64 = specs.AInt64; this.double = specs.ADouble; }
javascript
function Types() { this.binary = specs.ABinary; this.string = specs.AString; this.bool = specs.ABoolean; this.byte = specs.AByte; this.i16 = specs.AInt16; this.i32 = specs.AInt32; this.i64 = specs.AInt64; this.double = specs.ADouble; }
[ "function", "Types", "(", ")", "{", "this", ".", "binary", "=", "specs", ".", "ABinary", ";", "this", ".", "string", "=", "specs", ".", "AString", ";", "this", ".", "bool", "=", "specs", ".", "ABoolean", ";", "this", ".", "byte", "=", "specs", ".", "AByte", ";", "this", ".", "i16", "=", "specs", ".", "AInt16", ";", "this", ".", "i32", "=", "specs", ".", "AInt32", ";", "this", ".", "i64", "=", "specs", ".", "AInt64", ";", "this", ".", "double", "=", "specs", ".", "ADouble", ";", "}" ]
The types structure starts with the default types, and devolves into a dictionary of type declarations.
[ "The", "types", "structure", "starts", "with", "the", "default", "types", "and", "devolves", "into", "a", "dictionary", "of", "type", "declarations", "." ]
f54e97e02dd22190a779a4b316b15f0c81087ebf
https://github.com/uber-archive/thriftify/blob/f54e97e02dd22190a779a4b316b15f0c81087ebf/compiler/spec.js#L37-L46
train
jhudson8/react-mixin-manager
react-mixin-manager.js
get
function get(values, index, initiatedOnce, rtn) { /** * add the named mixin and all un-added dependencies to the return array * @param the mixin name */ function addTo(name) { var indexName = name, match = name.match(/^([^\(]*)\s*\(([^\)]*)\)\s*/), params = match && match[2]; name = match && match[1] || name; if (!index[indexName]) { if (params) { // there can be no function calls here because of the regex match /*jshint evil: true */ params = eval('[' + params + ']'); } var mixin = _mixins[name], checkAgain = false, skip = false; if (mixin) { if (typeof mixin === 'function') { if (_initiatedOnce[name]) { if (!initiatedOnce[name]) { initiatedOnce[name] = []; // add the placeholder so the mixin ends up in the right place // we will replace all names with the appropriate mixins at the end // (so we have all of the appropriate arguments) mixin = name; } else { // but we only want to add it a single time skip = true; } if (params) { initiatedOnce[name].push(params); } } else { mixin = mixin.apply(this, params || []); checkAgain = true; } } else if (params) { throw new Error('the mixin "' + name + '" does not support parameters'); } get(_dependsOn[name], index, initiatedOnce, rtn); get(_dependsInjected[name], index, initiatedOnce, rtn); index[indexName] = true; if (checkAgain) { get([mixin], index, initiatedOnce, rtn); } else if (!skip) { checkForInlineMixins(mixin, rtn); rtn.push(mixin); } } else { throw new Error('invalid mixin "' + name + '"'); } } } // if the mixin has a "mixins" attribute, clone and add those dependencies first function checkForInlineMixins(mixin, rtn) { if (mixin.mixins) { get(mixin.mixins, index, initiatedOnce, rtn); } } function handleMixin(mixin) { if (mixin) { if (Array.isArray(mixin)) { // flatten it out get(mixin, index, initiatedOnce, rtn); } else if (typeof mixin === 'string') { // add the named mixin and all of it's dependencies addTo(mixin); } else { checkForInlineMixins(mixin, rtn); // just add the mixin normally rtn.push(mixin); } } } if (Array.isArray(values)) { for (var i = 0; i < values.length; i++) { handleMixin(values[i]); } } else { handleMixin(values); } }
javascript
function get(values, index, initiatedOnce, rtn) { /** * add the named mixin and all un-added dependencies to the return array * @param the mixin name */ function addTo(name) { var indexName = name, match = name.match(/^([^\(]*)\s*\(([^\)]*)\)\s*/), params = match && match[2]; name = match && match[1] || name; if (!index[indexName]) { if (params) { // there can be no function calls here because of the regex match /*jshint evil: true */ params = eval('[' + params + ']'); } var mixin = _mixins[name], checkAgain = false, skip = false; if (mixin) { if (typeof mixin === 'function') { if (_initiatedOnce[name]) { if (!initiatedOnce[name]) { initiatedOnce[name] = []; // add the placeholder so the mixin ends up in the right place // we will replace all names with the appropriate mixins at the end // (so we have all of the appropriate arguments) mixin = name; } else { // but we only want to add it a single time skip = true; } if (params) { initiatedOnce[name].push(params); } } else { mixin = mixin.apply(this, params || []); checkAgain = true; } } else if (params) { throw new Error('the mixin "' + name + '" does not support parameters'); } get(_dependsOn[name], index, initiatedOnce, rtn); get(_dependsInjected[name], index, initiatedOnce, rtn); index[indexName] = true; if (checkAgain) { get([mixin], index, initiatedOnce, rtn); } else if (!skip) { checkForInlineMixins(mixin, rtn); rtn.push(mixin); } } else { throw new Error('invalid mixin "' + name + '"'); } } } // if the mixin has a "mixins" attribute, clone and add those dependencies first function checkForInlineMixins(mixin, rtn) { if (mixin.mixins) { get(mixin.mixins, index, initiatedOnce, rtn); } } function handleMixin(mixin) { if (mixin) { if (Array.isArray(mixin)) { // flatten it out get(mixin, index, initiatedOnce, rtn); } else if (typeof mixin === 'string') { // add the named mixin and all of it's dependencies addTo(mixin); } else { checkForInlineMixins(mixin, rtn); // just add the mixin normally rtn.push(mixin); } } } if (Array.isArray(values)) { for (var i = 0; i < values.length; i++) { handleMixin(values[i]); } } else { handleMixin(values); } }
[ "function", "get", "(", "values", ",", "index", ",", "initiatedOnce", ",", "rtn", ")", "{", "function", "addTo", "(", "name", ")", "{", "var", "indexName", "=", "name", ",", "match", "=", "name", ".", "match", "(", "/", "^([^\\(]*)\\s*\\(([^\\)]*)\\)\\s*", "/", ")", ",", "params", "=", "match", "&&", "match", "[", "2", "]", ";", "name", "=", "match", "&&", "match", "[", "1", "]", "||", "name", ";", "if", "(", "!", "index", "[", "indexName", "]", ")", "{", "if", "(", "params", ")", "{", "params", "=", "eval", "(", "'['", "+", "params", "+", "']'", ")", ";", "}", "var", "mixin", "=", "_mixins", "[", "name", "]", ",", "checkAgain", "=", "false", ",", "skip", "=", "false", ";", "if", "(", "mixin", ")", "{", "if", "(", "typeof", "mixin", "===", "'function'", ")", "{", "if", "(", "_initiatedOnce", "[", "name", "]", ")", "{", "if", "(", "!", "initiatedOnce", "[", "name", "]", ")", "{", "initiatedOnce", "[", "name", "]", "=", "[", "]", ";", "mixin", "=", "name", ";", "}", "else", "{", "skip", "=", "true", ";", "}", "if", "(", "params", ")", "{", "initiatedOnce", "[", "name", "]", ".", "push", "(", "params", ")", ";", "}", "}", "else", "{", "mixin", "=", "mixin", ".", "apply", "(", "this", ",", "params", "||", "[", "]", ")", ";", "checkAgain", "=", "true", ";", "}", "}", "else", "if", "(", "params", ")", "{", "throw", "new", "Error", "(", "'the mixin \"'", "+", "name", "+", "'\" does not support parameters'", ")", ";", "}", "get", "(", "_dependsOn", "[", "name", "]", ",", "index", ",", "initiatedOnce", ",", "rtn", ")", ";", "get", "(", "_dependsInjected", "[", "name", "]", ",", "index", ",", "initiatedOnce", ",", "rtn", ")", ";", "index", "[", "indexName", "]", "=", "true", ";", "if", "(", "checkAgain", ")", "{", "get", "(", "[", "mixin", "]", ",", "index", ",", "initiatedOnce", ",", "rtn", ")", ";", "}", "else", "if", "(", "!", "skip", ")", "{", "checkForInlineMixins", "(", "mixin", ",", "rtn", ")", ";", "rtn", ".", "push", "(", "mixin", ")", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'invalid mixin \"'", "+", "name", "+", "'\"'", ")", ";", "}", "}", "}", "function", "checkForInlineMixins", "(", "mixin", ",", "rtn", ")", "{", "if", "(", "mixin", ".", "mixins", ")", "{", "get", "(", "mixin", ".", "mixins", ",", "index", ",", "initiatedOnce", ",", "rtn", ")", ";", "}", "}", "function", "handleMixin", "(", "mixin", ")", "{", "if", "(", "mixin", ")", "{", "if", "(", "Array", ".", "isArray", "(", "mixin", ")", ")", "{", "get", "(", "mixin", ",", "index", ",", "initiatedOnce", ",", "rtn", ")", ";", "}", "else", "if", "(", "typeof", "mixin", "===", "'string'", ")", "{", "addTo", "(", "mixin", ")", ";", "}", "else", "{", "checkForInlineMixins", "(", "mixin", ",", "rtn", ")", ";", "rtn", ".", "push", "(", "mixin", ")", ";", "}", "}", "}", "if", "(", "Array", ".", "isArray", "(", "values", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "values", ".", "length", ";", "i", "++", ")", "{", "handleMixin", "(", "values", "[", "i", "]", ")", ";", "}", "}", "else", "{", "handleMixin", "(", "values", ")", ";", "}", "}" ]
return the normalized mixin list @param values {Array} list of mixin entries @param index {Object} hash which contains a truthy value for all named mixins that have been added @param initiatedOnce {Object} hash which collects mixins and their parameters that should be initiated once @param rtn {Array} the normalized return array
[ "return", "the", "normalized", "mixin", "list" ]
a2ea6d1ed6cbb7aaa6f15e90352fbec746842430
https://github.com/jhudson8/react-mixin-manager/blob/a2ea6d1ed6cbb7aaa6f15e90352fbec746842430/react-mixin-manager.js#L88-L180
train
jhudson8/react-mixin-manager
react-mixin-manager.js
addTo
function addTo(name) { var indexName = name, match = name.match(/^([^\(]*)\s*\(([^\)]*)\)\s*/), params = match && match[2]; name = match && match[1] || name; if (!index[indexName]) { if (params) { // there can be no function calls here because of the regex match /*jshint evil: true */ params = eval('[' + params + ']'); } var mixin = _mixins[name], checkAgain = false, skip = false; if (mixin) { if (typeof mixin === 'function') { if (_initiatedOnce[name]) { if (!initiatedOnce[name]) { initiatedOnce[name] = []; // add the placeholder so the mixin ends up in the right place // we will replace all names with the appropriate mixins at the end // (so we have all of the appropriate arguments) mixin = name; } else { // but we only want to add it a single time skip = true; } if (params) { initiatedOnce[name].push(params); } } else { mixin = mixin.apply(this, params || []); checkAgain = true; } } else if (params) { throw new Error('the mixin "' + name + '" does not support parameters'); } get(_dependsOn[name], index, initiatedOnce, rtn); get(_dependsInjected[name], index, initiatedOnce, rtn); index[indexName] = true; if (checkAgain) { get([mixin], index, initiatedOnce, rtn); } else if (!skip) { checkForInlineMixins(mixin, rtn); rtn.push(mixin); } } else { throw new Error('invalid mixin "' + name + '"'); } } }
javascript
function addTo(name) { var indexName = name, match = name.match(/^([^\(]*)\s*\(([^\)]*)\)\s*/), params = match && match[2]; name = match && match[1] || name; if (!index[indexName]) { if (params) { // there can be no function calls here because of the regex match /*jshint evil: true */ params = eval('[' + params + ']'); } var mixin = _mixins[name], checkAgain = false, skip = false; if (mixin) { if (typeof mixin === 'function') { if (_initiatedOnce[name]) { if (!initiatedOnce[name]) { initiatedOnce[name] = []; // add the placeholder so the mixin ends up in the right place // we will replace all names with the appropriate mixins at the end // (so we have all of the appropriate arguments) mixin = name; } else { // but we only want to add it a single time skip = true; } if (params) { initiatedOnce[name].push(params); } } else { mixin = mixin.apply(this, params || []); checkAgain = true; } } else if (params) { throw new Error('the mixin "' + name + '" does not support parameters'); } get(_dependsOn[name], index, initiatedOnce, rtn); get(_dependsInjected[name], index, initiatedOnce, rtn); index[indexName] = true; if (checkAgain) { get([mixin], index, initiatedOnce, rtn); } else if (!skip) { checkForInlineMixins(mixin, rtn); rtn.push(mixin); } } else { throw new Error('invalid mixin "' + name + '"'); } } }
[ "function", "addTo", "(", "name", ")", "{", "var", "indexName", "=", "name", ",", "match", "=", "name", ".", "match", "(", "/", "^([^\\(]*)\\s*\\(([^\\)]*)\\)\\s*", "/", ")", ",", "params", "=", "match", "&&", "match", "[", "2", "]", ";", "name", "=", "match", "&&", "match", "[", "1", "]", "||", "name", ";", "if", "(", "!", "index", "[", "indexName", "]", ")", "{", "if", "(", "params", ")", "{", "params", "=", "eval", "(", "'['", "+", "params", "+", "']'", ")", ";", "}", "var", "mixin", "=", "_mixins", "[", "name", "]", ",", "checkAgain", "=", "false", ",", "skip", "=", "false", ";", "if", "(", "mixin", ")", "{", "if", "(", "typeof", "mixin", "===", "'function'", ")", "{", "if", "(", "_initiatedOnce", "[", "name", "]", ")", "{", "if", "(", "!", "initiatedOnce", "[", "name", "]", ")", "{", "initiatedOnce", "[", "name", "]", "=", "[", "]", ";", "mixin", "=", "name", ";", "}", "else", "{", "skip", "=", "true", ";", "}", "if", "(", "params", ")", "{", "initiatedOnce", "[", "name", "]", ".", "push", "(", "params", ")", ";", "}", "}", "else", "{", "mixin", "=", "mixin", ".", "apply", "(", "this", ",", "params", "||", "[", "]", ")", ";", "checkAgain", "=", "true", ";", "}", "}", "else", "if", "(", "params", ")", "{", "throw", "new", "Error", "(", "'the mixin \"'", "+", "name", "+", "'\" does not support parameters'", ")", ";", "}", "get", "(", "_dependsOn", "[", "name", "]", ",", "index", ",", "initiatedOnce", ",", "rtn", ")", ";", "get", "(", "_dependsInjected", "[", "name", "]", ",", "index", ",", "initiatedOnce", ",", "rtn", ")", ";", "index", "[", "indexName", "]", "=", "true", ";", "if", "(", "checkAgain", ")", "{", "get", "(", "[", "mixin", "]", ",", "index", ",", "initiatedOnce", ",", "rtn", ")", ";", "}", "else", "if", "(", "!", "skip", ")", "{", "checkForInlineMixins", "(", "mixin", ",", "rtn", ")", ";", "rtn", ".", "push", "(", "mixin", ")", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'invalid mixin \"'", "+", "name", "+", "'\"'", ")", ";", "}", "}", "}" ]
add the named mixin and all un-added dependencies to the return array @param the mixin name
[ "add", "the", "named", "mixin", "and", "all", "un", "-", "added", "dependencies", "to", "the", "return", "array" ]
a2ea6d1ed6cbb7aaa6f15e90352fbec746842430
https://github.com/jhudson8/react-mixin-manager/blob/a2ea6d1ed6cbb7aaa6f15e90352fbec746842430/react-mixin-manager.js#L93-L147
train
jhudson8/react-mixin-manager
react-mixin-manager.js
checkForInlineMixins
function checkForInlineMixins(mixin, rtn) { if (mixin.mixins) { get(mixin.mixins, index, initiatedOnce, rtn); } }
javascript
function checkForInlineMixins(mixin, rtn) { if (mixin.mixins) { get(mixin.mixins, index, initiatedOnce, rtn); } }
[ "function", "checkForInlineMixins", "(", "mixin", ",", "rtn", ")", "{", "if", "(", "mixin", ".", "mixins", ")", "{", "get", "(", "mixin", ".", "mixins", ",", "index", ",", "initiatedOnce", ",", "rtn", ")", ";", "}", "}" ]
if the mixin has a "mixins" attribute, clone and add those dependencies first
[ "if", "the", "mixin", "has", "a", "mixins", "attribute", "clone", "and", "add", "those", "dependencies", "first" ]
a2ea6d1ed6cbb7aaa6f15e90352fbec746842430
https://github.com/jhudson8/react-mixin-manager/blob/a2ea6d1ed6cbb7aaa6f15e90352fbec746842430/react-mixin-manager.js#L150-L154
train
jhudson8/react-mixin-manager
react-mixin-manager.js
applyInitiatedOnceArgs
function applyInitiatedOnceArgs(mixins, rtn) { /** * added once initiated mixins to return array */ function addInitiatedOnce(name, mixin, params) { mixin = mixin.call(this, params || []); // find the name placeholder in the return arr and replace it with the mixin var index = rtn.indexOf(name); rtn.splice(index, 1, mixin); } for (var m in mixins) { if (mixins.hasOwnProperty(m)) { addInitiatedOnce(m, _mixins[m], mixins[m]); } } }
javascript
function applyInitiatedOnceArgs(mixins, rtn) { /** * added once initiated mixins to return array */ function addInitiatedOnce(name, mixin, params) { mixin = mixin.call(this, params || []); // find the name placeholder in the return arr and replace it with the mixin var index = rtn.indexOf(name); rtn.splice(index, 1, mixin); } for (var m in mixins) { if (mixins.hasOwnProperty(m)) { addInitiatedOnce(m, _mixins[m], mixins[m]); } } }
[ "function", "applyInitiatedOnceArgs", "(", "mixins", ",", "rtn", ")", "{", "function", "addInitiatedOnce", "(", "name", ",", "mixin", ",", "params", ")", "{", "mixin", "=", "mixin", ".", "call", "(", "this", ",", "params", "||", "[", "]", ")", ";", "var", "index", "=", "rtn", ".", "indexOf", "(", "name", ")", ";", "rtn", ".", "splice", "(", "index", ",", "1", ",", "mixin", ")", ";", "}", "for", "(", "var", "m", "in", "mixins", ")", "{", "if", "(", "mixins", ".", "hasOwnProperty", "(", "m", ")", ")", "{", "addInitiatedOnce", "(", "m", ",", "_mixins", "[", "m", "]", ",", "mixins", "[", "m", "]", ")", ";", "}", "}", "}" ]
add the mixins that should be once initiated to the normalized mixin list @param mixins {Object} hash of mixins keys and list of its parameters @param rtn {Array} the normalized return array
[ "add", "the", "mixins", "that", "should", "be", "once", "initiated", "to", "the", "normalized", "mixin", "list" ]
a2ea6d1ed6cbb7aaa6f15e90352fbec746842430
https://github.com/jhudson8/react-mixin-manager/blob/a2ea6d1ed6cbb7aaa6f15e90352fbec746842430/react-mixin-manager.js#L187-L204
train
jhudson8/react-mixin-manager
react-mixin-manager.js
addInitiatedOnce
function addInitiatedOnce(name, mixin, params) { mixin = mixin.call(this, params || []); // find the name placeholder in the return arr and replace it with the mixin var index = rtn.indexOf(name); rtn.splice(index, 1, mixin); }
javascript
function addInitiatedOnce(name, mixin, params) { mixin = mixin.call(this, params || []); // find the name placeholder in the return arr and replace it with the mixin var index = rtn.indexOf(name); rtn.splice(index, 1, mixin); }
[ "function", "addInitiatedOnce", "(", "name", ",", "mixin", ",", "params", ")", "{", "mixin", "=", "mixin", ".", "call", "(", "this", ",", "params", "||", "[", "]", ")", ";", "var", "index", "=", "rtn", ".", "indexOf", "(", "name", ")", ";", "rtn", ".", "splice", "(", "index", ",", "1", ",", "mixin", ")", ";", "}" ]
added once initiated mixins to return array
[ "added", "once", "initiated", "mixins", "to", "return", "array" ]
a2ea6d1ed6cbb7aaa6f15e90352fbec746842430
https://github.com/jhudson8/react-mixin-manager/blob/a2ea6d1ed6cbb7aaa6f15e90352fbec746842430/react-mixin-manager.js#L192-L197
train
jhudson8/react-mixin-manager
react-mixin-manager.js
function(name) { var l = _dependsInjected[name]; if (!l) { l = _dependsInjected[name] = []; } l.push(Array.prototype.slice.call(arguments, 1)); }
javascript
function(name) { var l = _dependsInjected[name]; if (!l) { l = _dependsInjected[name] = []; } l.push(Array.prototype.slice.call(arguments, 1)); }
[ "function", "(", "name", ")", "{", "var", "l", "=", "_dependsInjected", "[", "name", "]", ";", "if", "(", "!", "l", ")", "{", "l", "=", "_dependsInjected", "[", "name", "]", "=", "[", "]", ";", "}", "l", ".", "push", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "}" ]
Inject dependencies that were not originally defined when a mixin was registered @param name {string} the main mixin name @param (any additional) {string} dependencies that should be registered against the mixin
[ "Inject", "dependencies", "that", "were", "not", "originally", "defined", "when", "a", "mixin", "was", "registered" ]
a2ea6d1ed6cbb7aaa6f15e90352fbec746842430
https://github.com/jhudson8/react-mixin-manager/blob/a2ea6d1ed6cbb7aaa6f15e90352fbec746842430/react-mixin-manager.js#L301-L307
train
igocreate/igo
src/connect/errorhandler.js
function(err, req, res) { console.log('handle error:'); console.dir(err); // uri error if (err instanceof URIError) { return res.status(404).render('errors/404'); } logger.error(req.method + ' ' + getURL(req) + ' : ' + err); logger.error(err.stack); if (!res._headerSent) { // show error if (config.showerrstack) { // const stacktrace = [ '<h1>', req.originalUrl, '</h1>', '<pre>', err.stack, '</pre>' ].join(''); res.status(500).send(stacktrace); } else { res.status(500).render('errors/500'); } } if (config.mailcrashto) { mailer.send('crash', { to: config.mailcrashto, subject: [ config.appname, 'Crash:', err ].join(' '), body: formatMessage(req, err) }) } }
javascript
function(err, req, res) { console.log('handle error:'); console.dir(err); // uri error if (err instanceof URIError) { return res.status(404).render('errors/404'); } logger.error(req.method + ' ' + getURL(req) + ' : ' + err); logger.error(err.stack); if (!res._headerSent) { // show error if (config.showerrstack) { // const stacktrace = [ '<h1>', req.originalUrl, '</h1>', '<pre>', err.stack, '</pre>' ].join(''); res.status(500).send(stacktrace); } else { res.status(500).render('errors/500'); } } if (config.mailcrashto) { mailer.send('crash', { to: config.mailcrashto, subject: [ config.appname, 'Crash:', err ].join(' '), body: formatMessage(req, err) }) } }
[ "function", "(", "err", ",", "req", ",", "res", ")", "{", "console", ".", "log", "(", "'handle error:'", ")", ";", "console", ".", "dir", "(", "err", ")", ";", "if", "(", "err", "instanceof", "URIError", ")", "{", "return", "res", ".", "status", "(", "404", ")", ".", "render", "(", "'errors/404'", ")", ";", "}", "logger", ".", "error", "(", "req", ".", "method", "+", "' '", "+", "getURL", "(", "req", ")", "+", "' : '", "+", "err", ")", ";", "logger", ".", "error", "(", "err", ".", "stack", ")", ";", "if", "(", "!", "res", ".", "_headerSent", ")", "{", "if", "(", "config", ".", "showerrstack", ")", "{", "const", "stacktrace", "=", "[", "'<h1>'", ",", "req", ".", "originalUrl", ",", "'</h1>'", ",", "'<pre>'", ",", "err", ".", "stack", ",", "'</pre>'", "]", ".", "join", "(", "''", ")", ";", "res", ".", "status", "(", "500", ")", ".", "send", "(", "stacktrace", ")", ";", "}", "else", "{", "res", ".", "status", "(", "500", ")", ".", "render", "(", "'errors/500'", ")", ";", "}", "}", "if", "(", "config", ".", "mailcrashto", ")", "{", "mailer", ".", "send", "(", "'crash'", ",", "{", "to", ":", "config", ".", "mailcrashto", ",", "subject", ":", "[", "config", ".", "appname", ",", "'Crash:'", ",", "err", "]", ".", "join", "(", "' '", ")", ",", "body", ":", "formatMessage", "(", "req", ",", "err", ")", "}", ")", "}", "}" ]
log and show error
[ "log", "and", "show", "error" ]
fab4409260c648cad55f7b00b7a93ab2d9d8124c
https://github.com/igocreate/igo/blob/fab4409260c648cad55f7b00b7a93ab2d9d8124c/src/connect/errorhandler.js#L37-L71
train
flohil/wdio-workflo
dist/lib/utility_functions/object.js
mapProperties
function mapProperties(obj, func) { if (_.isArray(obj)) { throw new Error(`Input must be an object: ${obj}`); } else { const resultObj = Object.create(Object.prototype); for (const key in obj) { if (obj.hasOwnProperty(key)) { resultObj[key] = func(obj[key], key); } } return resultObj; } }
javascript
function mapProperties(obj, func) { if (_.isArray(obj)) { throw new Error(`Input must be an object: ${obj}`); } else { const resultObj = Object.create(Object.prototype); for (const key in obj) { if (obj.hasOwnProperty(key)) { resultObj[key] = func(obj[key], key); } } return resultObj; } }
[ "function", "mapProperties", "(", "obj", ",", "func", ")", "{", "if", "(", "_", ".", "isArray", "(", "obj", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "obj", "}", "`", ")", ";", "}", "else", "{", "const", "resultObj", "=", "Object", ".", "create", "(", "Object", ".", "prototype", ")", ";", "for", "(", "const", "key", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "resultObj", "[", "key", "]", "=", "func", "(", "obj", "[", "key", "]", ",", "key", ")", ";", "}", "}", "return", "resultObj", ";", "}", "}" ]
Iterates over all properties in an object and executes func on each. Returns a new object with the same keys as the input object and the values as result of the func. @param obj an object for which a func should be executed on each property @param func the function to be executed on each property of the passed object
[ "Iterates", "over", "all", "properties", "in", "an", "object", "and", "executes", "func", "on", "each", "." ]
e5fea8ddab2c3cc32247070850eb831dd40d419c
https://github.com/flohil/wdio-workflo/blob/e5fea8ddab2c3cc32247070850eb831dd40d419c/dist/lib/utility_functions/object.js#L14-L27
train
syntax-tree/unist-util-modify-children
index.js
iteratorFactory
function iteratorFactory(callback) { return iterator function iterator(parent) { var children = parent && parent.children if (!children) { throw new Error('Missing children in `parent` for `modifier`') } return iterate(children, callback, parent) } }
javascript
function iteratorFactory(callback) { return iterator function iterator(parent) { var children = parent && parent.children if (!children) { throw new Error('Missing children in `parent` for `modifier`') } return iterate(children, callback, parent) } }
[ "function", "iteratorFactory", "(", "callback", ")", "{", "return", "iterator", "function", "iterator", "(", "parent", ")", "{", "var", "children", "=", "parent", "&&", "parent", ".", "children", "if", "(", "!", "children", ")", "{", "throw", "new", "Error", "(", "'Missing children in `parent` for `modifier`'", ")", "}", "return", "iterate", "(", "children", ",", "callback", ",", "parent", ")", "}", "}" ]
Turn `callback` into a `iterator' accepting a parent.
[ "Turn", "callback", "into", "a", "iterator", "accepting", "a", "parent", "." ]
ff6dd063db36a5df30f4585c27d74a58eb1e27fa
https://github.com/syntax-tree/unist-util-modify-children/blob/ff6dd063db36a5df30f4585c27d74a58eb1e27fa/index.js#L14-L26
train
canjs/worker-render
src/worker/handlers/initial.js
setIfPresent
function setIfPresent(docEl, nodeName){ var node = getBaseElement(docEl, nodeName); if(node) { document[nodeName] = node; } }
javascript
function setIfPresent(docEl, nodeName){ var node = getBaseElement(docEl, nodeName); if(node) { document[nodeName] = node; } }
[ "function", "setIfPresent", "(", "docEl", ",", "nodeName", ")", "{", "var", "node", "=", "getBaseElement", "(", "docEl", ",", "nodeName", ")", ";", "if", "(", "node", ")", "{", "document", "[", "nodeName", "]", "=", "node", ";", "}", "}" ]
Set the document.body and document.head properties.
[ "Set", "the", "document", ".", "body", "and", "document", ".", "head", "properties", "." ]
e36dbb886a8453bd9e4d4fc9f73a4bc84146d6e5
https://github.com/canjs/worker-render/blob/e36dbb886a8453bd9e4d4fc9f73a4bc84146d6e5/src/worker/handlers/initial.js#L40-L46
train
emmetio/markup-formatters
format/slim.js
updateFormatting
function updateFormatting(outNode, profile) { const node = outNode.node; const parent = node.parent; // Edge case: a single inline-level child inside node without text: // allow it to be inlined if (profile.get('inlineBreak') === 0 && isInline(node, profile) && !isRoot(parent) && parent.value == null && parent.children.length === 1) { outNode.beforeOpen = ': '; } if (!node.isTextOnly && node.value) { // node with text: put a space before single-line text outNode.beforeText = reNl.test(node.value) ? outNode.newline + outNode.indent + profile.indent(1) : ' '; } return outNode; }
javascript
function updateFormatting(outNode, profile) { const node = outNode.node; const parent = node.parent; // Edge case: a single inline-level child inside node without text: // allow it to be inlined if (profile.get('inlineBreak') === 0 && isInline(node, profile) && !isRoot(parent) && parent.value == null && parent.children.length === 1) { outNode.beforeOpen = ': '; } if (!node.isTextOnly && node.value) { // node with text: put a space before single-line text outNode.beforeText = reNl.test(node.value) ? outNode.newline + outNode.indent + profile.indent(1) : ' '; } return outNode; }
[ "function", "updateFormatting", "(", "outNode", ",", "profile", ")", "{", "const", "node", "=", "outNode", ".", "node", ";", "const", "parent", "=", "node", ".", "parent", ";", "if", "(", "profile", ".", "get", "(", "'inlineBreak'", ")", "===", "0", "&&", "isInline", "(", "node", ",", "profile", ")", "&&", "!", "isRoot", "(", "parent", ")", "&&", "parent", ".", "value", "==", "null", "&&", "parent", ".", "children", ".", "length", "===", "1", ")", "{", "outNode", ".", "beforeOpen", "=", "': '", ";", "}", "if", "(", "!", "node", ".", "isTextOnly", "&&", "node", ".", "value", ")", "{", "outNode", ".", "beforeText", "=", "reNl", ".", "test", "(", "node", ".", "value", ")", "?", "outNode", ".", "newline", "+", "outNode", ".", "indent", "+", "profile", ".", "indent", "(", "1", ")", ":", "' '", ";", "}", "return", "outNode", ";", "}" ]
Updates formatting properties for given output node NB Unlike HTML, Slim is indent-based format so some formatting options from `profile` will not take effect, otherwise output will be broken @param {OutputNode} outNode Output wrapper of farsed abbreviation node @param {Profile} profile Output profile @return {OutputNode}
[ "Updates", "formatting", "properties", "for", "given", "output", "node", "NB", "Unlike", "HTML", "Slim", "is", "indent", "-", "based", "format", "so", "some", "formatting", "options", "from", "profile", "will", "not", "take", "effect", "otherwise", "output", "will", "be", "broken" ]
a9f93994fa5cb6aef6b0148b9ec485846fb4a338
https://github.com/emmetio/markup-formatters/blob/a9f93994fa5cb6aef6b0148b9ec485846fb4a338/format/slim.js#L72-L91
train
novacrazy/bluebird-co
benchmark/co/index.js
next
function next( ret ) { if( ret.done ) { return resolve( ret.value ); } var value = toPromise.call( ctx, ret.value ); if( value && isPromise( value ) ) { return value.then( onFulfilled, onRejected ); } return onRejected( new TypeError( 'You may only yield a function, promise, generator, array, or object, ' + 'but the following object was passed: "' + String( ret.value ) + '"' ) ); }
javascript
function next( ret ) { if( ret.done ) { return resolve( ret.value ); } var value = toPromise.call( ctx, ret.value ); if( value && isPromise( value ) ) { return value.then( onFulfilled, onRejected ); } return onRejected( new TypeError( 'You may only yield a function, promise, generator, array, or object, ' + 'but the following object was passed: "' + String( ret.value ) + '"' ) ); }
[ "function", "next", "(", "ret", ")", "{", "if", "(", "ret", ".", "done", ")", "{", "return", "resolve", "(", "ret", ".", "value", ")", ";", "}", "var", "value", "=", "toPromise", ".", "call", "(", "ctx", ",", "ret", ".", "value", ")", ";", "if", "(", "value", "&&", "isPromise", "(", "value", ")", ")", "{", "return", "value", ".", "then", "(", "onFulfilled", ",", "onRejected", ")", ";", "}", "return", "onRejected", "(", "new", "TypeError", "(", "'You may only yield a function, promise, generator, array, or object, '", "+", "'but the following object was passed: \"'", "+", "String", "(", "ret", ".", "value", ")", "+", "'\"'", ")", ")", ";", "}" ]
Get the next value in the generator, return a promise. @param {Object} ret @return {Promise} @api private
[ "Get", "the", "next", "value", "in", "the", "generator", "return", "a", "promise", "." ]
0f98755d326b99f8e3968308e4be43041ec5fde7
https://github.com/novacrazy/bluebird-co/blob/0f98755d326b99f8e3968308e4be43041ec5fde7/benchmark/co/index.js#L106-L117
train
novacrazy/bluebird-co
benchmark/co/index.js
toPromise
function toPromise( obj ) { if( !obj ) { return obj; } if( isPromise( obj ) ) { return obj; } if( isGeneratorFunction( obj ) || isGenerator( obj ) ) { return co.call( this, obj ); } if( 'function' == typeof obj ) { return thunkToPromise.call( this, obj ); } if( Array.isArray( obj ) ) { return arrayToPromise.call( this, obj ); } if( isObject( obj ) ) { return objectToPromise.call( this, obj ); } return obj; }
javascript
function toPromise( obj ) { if( !obj ) { return obj; } if( isPromise( obj ) ) { return obj; } if( isGeneratorFunction( obj ) || isGenerator( obj ) ) { return co.call( this, obj ); } if( 'function' == typeof obj ) { return thunkToPromise.call( this, obj ); } if( Array.isArray( obj ) ) { return arrayToPromise.call( this, obj ); } if( isObject( obj ) ) { return objectToPromise.call( this, obj ); } return obj; }
[ "function", "toPromise", "(", "obj", ")", "{", "if", "(", "!", "obj", ")", "{", "return", "obj", ";", "}", "if", "(", "isPromise", "(", "obj", ")", ")", "{", "return", "obj", ";", "}", "if", "(", "isGeneratorFunction", "(", "obj", ")", "||", "isGenerator", "(", "obj", ")", ")", "{", "return", "co", ".", "call", "(", "this", ",", "obj", ")", ";", "}", "if", "(", "'function'", "==", "typeof", "obj", ")", "{", "return", "thunkToPromise", ".", "call", "(", "this", ",", "obj", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "return", "arrayToPromise", ".", "call", "(", "this", ",", "obj", ")", ";", "}", "if", "(", "isObject", "(", "obj", ")", ")", "{", "return", "objectToPromise", ".", "call", "(", "this", ",", "obj", ")", ";", "}", "return", "obj", ";", "}" ]
Convert a `yield`ed value into a promise. @param {Mixed} obj @return {Promise} @api private
[ "Convert", "a", "yield", "ed", "value", "into", "a", "promise", "." ]
0f98755d326b99f8e3968308e4be43041ec5fde7
https://github.com/novacrazy/bluebird-co/blob/0f98755d326b99f8e3968308e4be43041ec5fde7/benchmark/co/index.js#L129-L149
train
Jam3/ae-to-json
src/getEaseForKeyFrame.js
getEaseType
function getEaseType(type){ switch(type) { case KeyframeInterpolationType.BEZIER: return EASE_TYPE.BEZIER; break; case KeyframeInterpolationType.LINEAR: return EASE_TYPE.LINEAR; break; case KeyframeInterpolationType.HOLD: return EASE_TYPE.HOLD; break; default: throw new Error('unknown ease type'); break; } }
javascript
function getEaseType(type){ switch(type) { case KeyframeInterpolationType.BEZIER: return EASE_TYPE.BEZIER; break; case KeyframeInterpolationType.LINEAR: return EASE_TYPE.LINEAR; break; case KeyframeInterpolationType.HOLD: return EASE_TYPE.HOLD; break; default: throw new Error('unknown ease type'); break; } }
[ "function", "getEaseType", "(", "type", ")", "{", "switch", "(", "type", ")", "{", "case", "KeyframeInterpolationType", ".", "BEZIER", ":", "return", "EASE_TYPE", ".", "BEZIER", ";", "break", ";", "case", "KeyframeInterpolationType", ".", "LINEAR", ":", "return", "EASE_TYPE", ".", "LINEAR", ";", "break", ";", "case", "KeyframeInterpolationType", ".", "HOLD", ":", "return", "EASE_TYPE", ".", "HOLD", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "'unknown ease type'", ")", ";", "break", ";", "}", "}" ]
get ease type
[ "get", "ease", "type" ]
9c7cf53287c90b9d3d7c72c302a076badf589758
https://github.com/Jam3/ae-to-json/blob/9c7cf53287c90b9d3d7c72c302a076badf589758/src/getEaseForKeyFrame.js#L30-L48
train
Jam3/ae-to-json
src/util/getNonObjectValues.js
getTypeOf
function getTypeOf(item) { var type = null; if(item) { var strValue = item.toString(); var isObject = /\[object/.test(strValue); var isFunction = /function/.test(strValue); var isArray = Array.isArray(item); if(isArray) { type = Array; } else if(isFunction) { type = Function; } else if(isObject) { type = Object; } else { type = null; } } else { type = null; } return type; }
javascript
function getTypeOf(item) { var type = null; if(item) { var strValue = item.toString(); var isObject = /\[object/.test(strValue); var isFunction = /function/.test(strValue); var isArray = Array.isArray(item); if(isArray) { type = Array; } else if(isFunction) { type = Function; } else if(isObject) { type = Object; } else { type = null; } } else { type = null; } return type; }
[ "function", "getTypeOf", "(", "item", ")", "{", "var", "type", "=", "null", ";", "if", "(", "item", ")", "{", "var", "strValue", "=", "item", ".", "toString", "(", ")", ";", "var", "isObject", "=", "/", "\\[object", "/", ".", "test", "(", "strValue", ")", ";", "var", "isFunction", "=", "/", "function", "/", ".", "test", "(", "strValue", ")", ";", "var", "isArray", "=", "Array", ".", "isArray", "(", "item", ")", ";", "if", "(", "isArray", ")", "{", "type", "=", "Array", ";", "}", "else", "if", "(", "isFunction", ")", "{", "type", "=", "Function", ";", "}", "else", "if", "(", "isObject", ")", "{", "type", "=", "Object", ";", "}", "else", "{", "type", "=", "null", ";", "}", "}", "else", "{", "type", "=", "null", ";", "}", "return", "type", ";", "}" ]
for some reason typeof is breaking in AE
[ "for", "some", "reason", "typeof", "is", "breaking", "in", "AE" ]
9c7cf53287c90b9d3d7c72c302a076badf589758
https://github.com/Jam3/ae-to-json/blob/9c7cf53287c90b9d3d7c72c302a076badf589758/src/util/getNonObjectValues.js#L40-L63
train
timbeadle/tv4-reporter
lib/reporter.js
extractSchemaLabel
function extractSchemaLabel(schema, limit) { limit = typeof limit === 'undefined' ? strimLimit : limit; var label = ''; if (schema.id) { label = style.accent(schema.id); } if (schema.title) { label += style.accent(label ? ' (' + schema.title + ')' : style.accent(schema.title)); } if (!label) { if (schema.description) { label = style.accent('<no id>') + ' ' + valueStrim(schema.description, limit); } else { label = style.accent('<no id>') + ' ' + valueStrim(schema, limit); } } return label; }
javascript
function extractSchemaLabel(schema, limit) { limit = typeof limit === 'undefined' ? strimLimit : limit; var label = ''; if (schema.id) { label = style.accent(schema.id); } if (schema.title) { label += style.accent(label ? ' (' + schema.title + ')' : style.accent(schema.title)); } if (!label) { if (schema.description) { label = style.accent('<no id>') + ' ' + valueStrim(schema.description, limit); } else { label = style.accent('<no id>') + ' ' + valueStrim(schema, limit); } } return label; }
[ "function", "extractSchemaLabel", "(", "schema", ",", "limit", ")", "{", "limit", "=", "typeof", "limit", "===", "'undefined'", "?", "strimLimit", ":", "limit", ";", "var", "label", "=", "''", ";", "if", "(", "schema", ".", "id", ")", "{", "label", "=", "style", ".", "accent", "(", "schema", ".", "id", ")", ";", "}", "if", "(", "schema", ".", "title", ")", "{", "label", "+=", "style", ".", "accent", "(", "label", "?", "' ('", "+", "schema", ".", "title", "+", "')'", ":", "style", ".", "accent", "(", "schema", ".", "title", ")", ")", ";", "}", "if", "(", "!", "label", ")", "{", "if", "(", "schema", ".", "description", ")", "{", "label", "=", "style", ".", "accent", "(", "'<no id>'", ")", "+", "' '", "+", "valueStrim", "(", "schema", ".", "description", ",", "limit", ")", ";", "}", "else", "{", "label", "=", "style", ".", "accent", "(", "'<no id>'", ")", "+", "' '", "+", "valueStrim", "(", "schema", ",", "limit", ")", ";", "}", "}", "return", "label", ";", "}" ]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - best-effort
[ "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "best", "-", "effort" ]
d489eaa4d4f16d2ac6256785eca2c40031980c1e
https://github.com/timbeadle/tv4-reporter/blob/d489eaa4d4f16d2ac6256785eca2c40031980c1e/lib/reporter.js#L118-L137
train
timbeadle/tv4-reporter
lib/reporter.js
extractCTXLabel
function extractCTXLabel(test, limit) { limit = typeof limit === 'undefined' ? strimLimit : limit; var label; if (test.label) { label = style.accent(test.label); } if (!label) { label = style.accent('<no label>') + ' ' + valueStrim(test.value, limit); } return label; }
javascript
function extractCTXLabel(test, limit) { limit = typeof limit === 'undefined' ? strimLimit : limit; var label; if (test.label) { label = style.accent(test.label); } if (!label) { label = style.accent('<no label>') + ' ' + valueStrim(test.value, limit); } return label; }
[ "function", "extractCTXLabel", "(", "test", ",", "limit", ")", "{", "limit", "=", "typeof", "limit", "===", "'undefined'", "?", "strimLimit", ":", "limit", ";", "var", "label", ";", "if", "(", "test", ".", "label", ")", "{", "label", "=", "style", ".", "accent", "(", "test", ".", "label", ")", ";", "}", "if", "(", "!", "label", ")", "{", "label", "=", "style", ".", "accent", "(", "'<no label>'", ")", "+", "' '", "+", "valueStrim", "(", "test", ".", "value", ",", "limit", ")", ";", "}", "return", "label", ";", "}" ]
best-effort
[ "best", "-", "effort" ]
d489eaa4d4f16d2ac6256785eca2c40031980c1e
https://github.com/timbeadle/tv4-reporter/blob/d489eaa4d4f16d2ac6256785eca2c40031980c1e/lib/reporter.js#L140-L150
train
YR/time
index.js
init
function init() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; dayStartsAt = options.dayStartsAt || DEFAULT_DAY_STARTS_AT; nightStartsAt = options.nightStartsAt || DEFAULT_NIGHT_STARTS_AT; }
javascript
function init() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; dayStartsAt = options.dayStartsAt || DEFAULT_DAY_STARTS_AT; nightStartsAt = options.nightStartsAt || DEFAULT_NIGHT_STARTS_AT; }
[ "function", "init", "(", ")", "{", "var", "options", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "{", "}", ";", "dayStartsAt", "=", "options", ".", "dayStartsAt", "||", "DEFAULT_DAY_STARTS_AT", ";", "nightStartsAt", "=", "options", ".", "nightStartsAt", "||", "DEFAULT_NIGHT_STARTS_AT", ";", "}" ]
Initialize with defaults @param {Object} [options] - {Number} dayStartsAt - {Number} nightStartsAt - {Array} parseKeys
[ "Initialize", "with", "defaults" ]
d5507b8edc0ba1c828256c0d732b8e51033ad82d
https://github.com/YR/time/blob/d5507b8edc0ba1c828256c0d732b8e51033ad82d/index.js#L50-L55
train
YR/time
index.js
clientNow
function clientNow() { var d = new Date(); var offset = -1 * d.getTimezoneOffset(); d.setUTCMinutes(d.getUTCMinutes() + offset); return d.toISOString().replace('Z', minutesToOffsetString(offset)); }
javascript
function clientNow() { var d = new Date(); var offset = -1 * d.getTimezoneOffset(); d.setUTCMinutes(d.getUTCMinutes() + offset); return d.toISOString().replace('Z', minutesToOffsetString(offset)); }
[ "function", "clientNow", "(", ")", "{", "var", "d", "=", "new", "Date", "(", ")", ";", "var", "offset", "=", "-", "1", "*", "d", ".", "getTimezoneOffset", "(", ")", ";", "d", ".", "setUTCMinutes", "(", "d", ".", "getUTCMinutes", "(", ")", "+", "offset", ")", ";", "return", "d", ".", "toISOString", "(", ")", ".", "replace", "(", "'Z'", ",", "minutesToOffsetString", "(", "offset", ")", ")", ";", "}" ]
Retrieve timestring for client "now" @returns {String}
[ "Retrieve", "timestring", "for", "client", "now" ]
d5507b8edc0ba1c828256c0d732b8e51033ad82d
https://github.com/YR/time/blob/d5507b8edc0ba1c828256c0d732b8e51033ad82d/index.js#L798-L804
train
YR/time
index.js
update
function update(instance) { instance.isValid = isValid(instance._date); instance.timeString = instance.toString(); return instance; }
javascript
function update(instance) { instance.isValid = isValid(instance._date); instance.timeString = instance.toString(); return instance; }
[ "function", "update", "(", "instance", ")", "{", "instance", ".", "isValid", "=", "isValid", "(", "instance", ".", "_date", ")", ";", "instance", ".", "timeString", "=", "instance", ".", "toString", "(", ")", ";", "return", "instance", ";", "}" ]
Update 'instance' state @param {Time} instance @returns {Time}
[ "Update", "instance", "state" ]
d5507b8edc0ba1c828256c0d732b8e51033ad82d
https://github.com/YR/time/blob/d5507b8edc0ba1c828256c0d732b8e51033ad82d/index.js#L811-L815
train
YR/time
index.js
isValid
function isValid(date) { return Object.prototype.toString.call(date) == '[object Date]' && !isNaN(date.getTime()); }
javascript
function isValid(date) { return Object.prototype.toString.call(date) == '[object Date]' && !isNaN(date.getTime()); }
[ "function", "isValid", "(", "date", ")", "{", "return", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "date", ")", "==", "'[object Date]'", "&&", "!", "isNaN", "(", "date", ".", "getTime", "(", ")", ")", ";", "}" ]
Validate 'date' object @param {Date} date @returns {Boolean}
[ "Validate", "date", "object" ]
d5507b8edc0ba1c828256c0d732b8e51033ad82d
https://github.com/YR/time/blob/d5507b8edc0ba1c828256c0d732b8e51033ad82d/index.js#L867-L869
train
YR/time
index.js
isTime
function isTime(time) { return time != null && time._manipulate != null && time._date != null; }
javascript
function isTime(time) { return time != null && time._manipulate != null && time._date != null; }
[ "function", "isTime", "(", "time", ")", "{", "return", "time", "!=", "null", "&&", "time", ".", "_manipulate", "!=", "null", "&&", "time", ".", "_date", "!=", "null", ";", "}" ]
Determine if 'time' is a Time instance @param {Time} time @returns {Boolean}
[ "Determine", "if", "time", "is", "a", "Time", "instance" ]
d5507b8edc0ba1c828256c0d732b8e51033ad82d
https://github.com/YR/time/blob/d5507b8edc0ba1c828256c0d732b8e51033ad82d/index.js#L876-L878
train
YR/time
index.js
pad
function pad(value, length) { value = String(value); length = length || 2; while (value.length < length) { value = '0' + value; } return value; }
javascript
function pad(value, length) { value = String(value); length = length || 2; while (value.length < length) { value = '0' + value; } return value; }
[ "function", "pad", "(", "value", ",", "length", ")", "{", "value", "=", "String", "(", "value", ")", ";", "length", "=", "length", "||", "2", ";", "while", "(", "value", ".", "length", "<", "length", ")", "{", "value", "=", "'0'", "+", "value", ";", "}", "return", "value", ";", "}" ]
Pad 'value' with zeros up to desired 'length' @param {String|Number} value @param {Number} [length] @returns {String}
[ "Pad", "value", "with", "zeros", "up", "to", "desired", "length" ]
d5507b8edc0ba1c828256c0d732b8e51033ad82d
https://github.com/YR/time/blob/d5507b8edc0ba1c828256c0d732b8e51033ad82d/index.js#L896-L905
train
YR/time
index.js
minutesToOffsetString
function minutesToOffsetString(minutes) { var t = String(Math.abs(minutes / 60)).split('.'); var H = pad(t[0]); var m = t[1] ? parseInt(t[1], 10) * 0.6 : 0; var sign = minutes < 0 ? '-' : '+'; return '' + sign + H + ':' + pad(m); }
javascript
function minutesToOffsetString(minutes) { var t = String(Math.abs(minutes / 60)).split('.'); var H = pad(t[0]); var m = t[1] ? parseInt(t[1], 10) * 0.6 : 0; var sign = minutes < 0 ? '-' : '+'; return '' + sign + H + ':' + pad(m); }
[ "function", "minutesToOffsetString", "(", "minutes", ")", "{", "var", "t", "=", "String", "(", "Math", ".", "abs", "(", "minutes", "/", "60", ")", ")", ".", "split", "(", "'.'", ")", ";", "var", "H", "=", "pad", "(", "t", "[", "0", "]", ")", ";", "var", "m", "=", "t", "[", "1", "]", "?", "parseInt", "(", "t", "[", "1", "]", ",", "10", ")", "*", "0.6", ":", "0", ";", "var", "sign", "=", "minutes", "<", "0", "?", "'-'", ":", "'+'", ";", "return", "''", "+", "sign", "+", "H", "+", "':'", "+", "pad", "(", "m", ")", ";", "}" ]
Convert 'minutes' to offset string @param {Number} minutes @returns {String}
[ "Convert", "minutes", "to", "offset", "string" ]
d5507b8edc0ba1c828256c0d732b8e51033ad82d
https://github.com/YR/time/blob/d5507b8edc0ba1c828256c0d732b8e51033ad82d/index.js#L912-L919
train
ryanwalters/sticky-events
sticky-events.js
addSentinels
function addSentinels(container, className, stickySelector = STICKY_SELECTOR) { return Array.from(container.querySelectorAll(stickySelector)).map((stickyElement) => { const sentinel = document.createElement('div'); const stickyParent = stickyElement.parentElement; // Apply styles to the sticky element stickyElement.style.cssText = ` position: -webkit-sticky; position: sticky; `; // Apply default sentinel styles sentinel.classList.add(ClassName.SENTINEL, className); Object.assign(sentinel.style,{ left: 0, position: 'absolute', right: 0, visibility: 'hidden', }); switch (className) { case ClassName.SENTINEL_TOP: { stickyParent.insertBefore(sentinel, stickyElement); // Apply styles specific to the top sentinel Object.assign( sentinel.style, getSentinelPosition(stickyElement, sentinel, className), { position: 'relative' }, ); break; } case ClassName.SENTINEL_BOTTOM: { stickyParent.appendChild(sentinel); // Apply styles specific to the bottom sentinel Object.assign(sentinel.style, getSentinelPosition(stickyElement, sentinel, className)); break; } } return sentinel; }); }
javascript
function addSentinels(container, className, stickySelector = STICKY_SELECTOR) { return Array.from(container.querySelectorAll(stickySelector)).map((stickyElement) => { const sentinel = document.createElement('div'); const stickyParent = stickyElement.parentElement; // Apply styles to the sticky element stickyElement.style.cssText = ` position: -webkit-sticky; position: sticky; `; // Apply default sentinel styles sentinel.classList.add(ClassName.SENTINEL, className); Object.assign(sentinel.style,{ left: 0, position: 'absolute', right: 0, visibility: 'hidden', }); switch (className) { case ClassName.SENTINEL_TOP: { stickyParent.insertBefore(sentinel, stickyElement); // Apply styles specific to the top sentinel Object.assign( sentinel.style, getSentinelPosition(stickyElement, sentinel, className), { position: 'relative' }, ); break; } case ClassName.SENTINEL_BOTTOM: { stickyParent.appendChild(sentinel); // Apply styles specific to the bottom sentinel Object.assign(sentinel.style, getSentinelPosition(stickyElement, sentinel, className)); break; } } return sentinel; }); }
[ "function", "addSentinels", "(", "container", ",", "className", ",", "stickySelector", "=", "STICKY_SELECTOR", ")", "{", "return", "Array", ".", "from", "(", "container", ".", "querySelectorAll", "(", "stickySelector", ")", ")", ".", "map", "(", "(", "stickyElement", ")", "=>", "{", "const", "sentinel", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "const", "stickyParent", "=", "stickyElement", ".", "parentElement", ";", "stickyElement", ".", "style", ".", "cssText", "=", "`", "`", ";", "sentinel", ".", "classList", ".", "add", "(", "ClassName", ".", "SENTINEL", ",", "className", ")", ";", "Object", ".", "assign", "(", "sentinel", ".", "style", ",", "{", "left", ":", "0", ",", "position", ":", "'absolute'", ",", "right", ":", "0", ",", "visibility", ":", "'hidden'", ",", "}", ")", ";", "switch", "(", "className", ")", "{", "case", "ClassName", ".", "SENTINEL_TOP", ":", "{", "stickyParent", ".", "insertBefore", "(", "sentinel", ",", "stickyElement", ")", ";", "Object", ".", "assign", "(", "sentinel", ".", "style", ",", "getSentinelPosition", "(", "stickyElement", ",", "sentinel", ",", "className", ")", ",", "{", "position", ":", "'relative'", "}", ",", ")", ";", "break", ";", "}", "case", "ClassName", ".", "SENTINEL_BOTTOM", ":", "{", "stickyParent", ".", "appendChild", "(", "sentinel", ")", ";", "Object", ".", "assign", "(", "sentinel", ".", "style", ",", "getSentinelPosition", "(", "stickyElement", ",", "sentinel", ",", "className", ")", ")", ";", "break", ";", "}", "}", "return", "sentinel", ";", "}", ")", ";", "}" ]
Add sticky sentinels @param {Element|HTMLDocument} container @param {String} className @param {string} stickySelector The CSS selector applied to the sticky DOM elements @returns {Array<Element>}
[ "Add", "sticky", "sentinels" ]
39a7a2be10ccc7c51f98231377a57ccafa23f35d
https://github.com/ryanwalters/sticky-events/blob/39a7a2be10ccc7c51f98231377a57ccafa23f35d/sticky-events.js#L230-L281
train
ryanwalters/sticky-events
sticky-events.js
getSentinelPosition
function getSentinelPosition(stickyElement, sentinel, className) { const stickyStyle = window.getComputedStyle(stickyElement); const parentStyle = window.getComputedStyle(stickyElement.parentElement); switch (className) { case ClassName.SENTINEL_TOP: return { top: `calc(${stickyStyle.getPropertyValue('top')} * -1)`, height: 0, }; case ClassName.SENTINEL_BOTTOM: const parentPadding = parseInt(parentStyle.paddingTop); return { bottom: stickyStyle.top, height: `${stickyElement.getBoundingClientRect().height + parentPadding}px`, }; } }
javascript
function getSentinelPosition(stickyElement, sentinel, className) { const stickyStyle = window.getComputedStyle(stickyElement); const parentStyle = window.getComputedStyle(stickyElement.parentElement); switch (className) { case ClassName.SENTINEL_TOP: return { top: `calc(${stickyStyle.getPropertyValue('top')} * -1)`, height: 0, }; case ClassName.SENTINEL_BOTTOM: const parentPadding = parseInt(parentStyle.paddingTop); return { bottom: stickyStyle.top, height: `${stickyElement.getBoundingClientRect().height + parentPadding}px`, }; } }
[ "function", "getSentinelPosition", "(", "stickyElement", ",", "sentinel", ",", "className", ")", "{", "const", "stickyStyle", "=", "window", ".", "getComputedStyle", "(", "stickyElement", ")", ";", "const", "parentStyle", "=", "window", ".", "getComputedStyle", "(", "stickyElement", ".", "parentElement", ")", ";", "switch", "(", "className", ")", "{", "case", "ClassName", ".", "SENTINEL_TOP", ":", "return", "{", "top", ":", "`", "${", "stickyStyle", ".", "getPropertyValue", "(", "'top'", ")", "}", "`", ",", "height", ":", "0", ",", "}", ";", "case", "ClassName", ".", "SENTINEL_BOTTOM", ":", "const", "parentPadding", "=", "parseInt", "(", "parentStyle", ".", "paddingTop", ")", ";", "return", "{", "bottom", ":", "stickyStyle", ".", "top", ",", "height", ":", "`", "${", "stickyElement", ".", "getBoundingClientRect", "(", ")", ".", "height", "+", "parentPadding", "}", "`", ",", "}", ";", "}", "}" ]
Determine the position of the sentinel @param {Element|Node} stickyElement @param {Element|Node} sentinel @param {String} className @returns {Object}
[ "Determine", "the", "position", "of", "the", "sentinel" ]
39a7a2be10ccc7c51f98231377a57ccafa23f35d
https://github.com/ryanwalters/sticky-events/blob/39a7a2be10ccc7c51f98231377a57ccafa23f35d/sticky-events.js#L293-L312
train
ryanwalters/sticky-events
sticky-events.js
isSticking
function isSticking(stickyElement) { const topSentinel = stickyElement.previousElementSibling; const stickyOffset = stickyElement.getBoundingClientRect().top; const topSentinelOffset = topSentinel.getBoundingClientRect().top; const difference = Math.round(Math.abs(stickyOffset - topSentinelOffset)); const topSentinelTopPosition = Math.abs(parseInt(window.getComputedStyle(topSentinel).getPropertyValue('top'))); return difference !== topSentinelTopPosition; }
javascript
function isSticking(stickyElement) { const topSentinel = stickyElement.previousElementSibling; const stickyOffset = stickyElement.getBoundingClientRect().top; const topSentinelOffset = topSentinel.getBoundingClientRect().top; const difference = Math.round(Math.abs(stickyOffset - topSentinelOffset)); const topSentinelTopPosition = Math.abs(parseInt(window.getComputedStyle(topSentinel).getPropertyValue('top'))); return difference !== topSentinelTopPosition; }
[ "function", "isSticking", "(", "stickyElement", ")", "{", "const", "topSentinel", "=", "stickyElement", ".", "previousElementSibling", ";", "const", "stickyOffset", "=", "stickyElement", ".", "getBoundingClientRect", "(", ")", ".", "top", ";", "const", "topSentinelOffset", "=", "topSentinel", ".", "getBoundingClientRect", "(", ")", ".", "top", ";", "const", "difference", "=", "Math", ".", "round", "(", "Math", ".", "abs", "(", "stickyOffset", "-", "topSentinelOffset", ")", ")", ";", "const", "topSentinelTopPosition", "=", "Math", ".", "abs", "(", "parseInt", "(", "window", ".", "getComputedStyle", "(", "topSentinel", ")", ".", "getPropertyValue", "(", "'top'", ")", ")", ")", ";", "return", "difference", "!==", "topSentinelTopPosition", ";", "}" ]
Determine if the sticky element is currently sticking in the browser @param {Element} stickyElement @returns {boolean}
[ "Determine", "if", "the", "sticky", "element", "is", "currently", "sticking", "in", "the", "browser" ]
39a7a2be10ccc7c51f98231377a57ccafa23f35d
https://github.com/ryanwalters/sticky-events/blob/39a7a2be10ccc7c51f98231377a57ccafa23f35d/sticky-events.js#L322-L332
train
intelie/immutable-js-diff
src/lcs.js
computeLcsMatrix
function computeLcsMatrix(xs, ys) { var n = xs.size||0; var m = ys.size||0; var a = makeMatrix(n + 1, m + 1, 0); for (var i = 0; i < n; i++) { for (var j = 0; j < m; j++) { if (Immutable.is(xs.get(i), ys.get(j))) { a[i + 1][j + 1] = a[i][j] + 1; } else { a[i + 1][j + 1] = Math.max(a[i + 1][j], a[i][j + 1]); } } } return a; }
javascript
function computeLcsMatrix(xs, ys) { var n = xs.size||0; var m = ys.size||0; var a = makeMatrix(n + 1, m + 1, 0); for (var i = 0; i < n; i++) { for (var j = 0; j < m; j++) { if (Immutable.is(xs.get(i), ys.get(j))) { a[i + 1][j + 1] = a[i][j] + 1; } else { a[i + 1][j + 1] = Math.max(a[i + 1][j], a[i][j + 1]); } } } return a; }
[ "function", "computeLcsMatrix", "(", "xs", ",", "ys", ")", "{", "var", "n", "=", "xs", ".", "size", "||", "0", ";", "var", "m", "=", "ys", ".", "size", "||", "0", ";", "var", "a", "=", "makeMatrix", "(", "n", "+", "1", ",", "m", "+", "1", ",", "0", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "m", ";", "j", "++", ")", "{", "if", "(", "Immutable", ".", "is", "(", "xs", ".", "get", "(", "i", ")", ",", "ys", ".", "get", "(", "j", ")", ")", ")", "{", "a", "[", "i", "+", "1", "]", "[", "j", "+", "1", "]", "=", "a", "[", "i", "]", "[", "j", "]", "+", "1", ";", "}", "else", "{", "a", "[", "i", "+", "1", "]", "[", "j", "+", "1", "]", "=", "Math", ".", "max", "(", "a", "[", "i", "+", "1", "]", "[", "j", "]", ",", "a", "[", "i", "]", "[", "j", "+", "1", "]", ")", ";", "}", "}", "}", "return", "a", ";", "}" ]
Computes the Longest Common Subsequence table @param xs Indexed Sequence 1 @param ys Indexed Sequence 2
[ "Computes", "the", "Longest", "Common", "Subsequence", "table" ]
0c1b48516368c6c955a36cba10d74dcffa361ec8
https://github.com/intelie/immutable-js-diff/blob/0c1b48516368c6c955a36cba10d74dcffa361ec8/src/lcs.js#L100-L117
train
intelie/immutable-js-diff
src/lcs.js
function(xs, ys, matrix){ var lcs = []; for(var i = xs.size, j = ys.size; i !== 0 && j !== 0;){ if (matrix[i][j] === matrix[i-1][j]){ i--; } else if (matrix[i][j] === matrix[i][j-1]){ j--; } else{ if(Immutable.is(xs.get(i-1), ys.get(j-1))){ lcs.push(xs.get(i-1)); i--; j--; } } } return lcs.reverse(); }
javascript
function(xs, ys, matrix){ var lcs = []; for(var i = xs.size, j = ys.size; i !== 0 && j !== 0;){ if (matrix[i][j] === matrix[i-1][j]){ i--; } else if (matrix[i][j] === matrix[i][j-1]){ j--; } else{ if(Immutable.is(xs.get(i-1), ys.get(j-1))){ lcs.push(xs.get(i-1)); i--; j--; } } } return lcs.reverse(); }
[ "function", "(", "xs", ",", "ys", ",", "matrix", ")", "{", "var", "lcs", "=", "[", "]", ";", "for", "(", "var", "i", "=", "xs", ".", "size", ",", "j", "=", "ys", ".", "size", ";", "i", "!==", "0", "&&", "j", "!==", "0", ";", ")", "{", "if", "(", "matrix", "[", "i", "]", "[", "j", "]", "===", "matrix", "[", "i", "-", "1", "]", "[", "j", "]", ")", "{", "i", "--", ";", "}", "else", "if", "(", "matrix", "[", "i", "]", "[", "j", "]", "===", "matrix", "[", "i", "]", "[", "j", "-", "1", "]", ")", "{", "j", "--", ";", "}", "else", "{", "if", "(", "Immutable", ".", "is", "(", "xs", ".", "get", "(", "i", "-", "1", ")", ",", "ys", ".", "get", "(", "j", "-", "1", ")", ")", ")", "{", "lcs", ".", "push", "(", "xs", ".", "get", "(", "i", "-", "1", ")", ")", ";", "i", "--", ";", "j", "--", ";", "}", "}", "}", "return", "lcs", ".", "reverse", "(", ")", ";", "}" ]
Extracts a LCS from matrix M @param xs Indexed Sequence 1 @param ys Indexed Sequence 2 @param matrix LCS Matrix @returns {Array.<T>} Longest Common Subsequence
[ "Extracts", "a", "LCS", "from", "matrix", "M" ]
0c1b48516368c6c955a36cba10d74dcffa361ec8
https://github.com/intelie/immutable-js-diff/blob/0c1b48516368c6c955a36cba10d74dcffa361ec8/src/lcs.js#L126-L140
train
nolanlawson/vdom-serialized-patch
lib/serialize/index.js
serializeCurrentNode
function serializeCurrentNode(currentNode) { var children = currentNode.children; if (!children) { return null; } var len = children.length; var arr = new Array(len); var i = -1; while (++i < len) { arr[i] = serializeCurrentNode(children[i]); } if (currentNode.count) { return [arr, currentNode.count]; } else { return [arr]; } }
javascript
function serializeCurrentNode(currentNode) { var children = currentNode.children; if (!children) { return null; } var len = children.length; var arr = new Array(len); var i = -1; while (++i < len) { arr[i] = serializeCurrentNode(children[i]); } if (currentNode.count) { return [arr, currentNode.count]; } else { return [arr]; } }
[ "function", "serializeCurrentNode", "(", "currentNode", ")", "{", "var", "children", "=", "currentNode", ".", "children", ";", "if", "(", "!", "children", ")", "{", "return", "null", ";", "}", "var", "len", "=", "children", ".", "length", ";", "var", "arr", "=", "new", "Array", "(", "len", ")", ";", "var", "i", "=", "-", "1", ";", "while", "(", "++", "i", "<", "len", ")", "{", "arr", "[", "i", "]", "=", "serializeCurrentNode", "(", "children", "[", "i", "]", ")", ";", "}", "if", "(", "currentNode", ".", "count", ")", "{", "return", "[", "arr", ",", "currentNode", ".", "count", "]", ";", "}", "else", "{", "return", "[", "arr", "]", ";", "}", "}" ]
traverse the thing that the original patch structure called "a', i.e. the virtual tree representing the current node structure. this thing only really needs two properties - "children" and "count", so trim out everything else
[ "traverse", "the", "thing", "that", "the", "original", "patch", "structure", "called", "a", "i", ".", "e", ".", "the", "virtual", "tree", "representing", "the", "current", "node", "structure", ".", "this", "thing", "only", "really", "needs", "two", "properties", "-", "children", "and", "count", "so", "trim", "out", "everything", "else" ]
158af827e062dac63a626b938f7fa32e55b70b46
https://github.com/nolanlawson/vdom-serialized-patch/blob/158af827e062dac63a626b938f7fa32e55b70b46/lib/serialize/index.js#L8-L24
train