id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
18,800
brianleroux/lawnchair
src/plugins/aggregation.js
function (property, callback) { this.sum(property, function (sum) { this.count(property, function (count) { this.fn('avg', callback).call(this, sum/count) }) }) }
javascript
function (property, callback) { this.sum(property, function (sum) { this.count(property, function (count) { this.fn('avg', callback).call(this, sum/count) }) }) }
[ "function", "(", "property", ",", "callback", ")", "{", "this", ".", "sum", "(", "property", ",", "function", "(", "sum", ")", "{", "this", ".", "count", "(", "property", ",", "function", "(", "count", ")", "{", "this", ".", "fn", "(", "'avg'", ",", "callback", ")", ".", "call", "(", "this", ",", "sum", "/", "count", ")", "}", ")", "}", ")", "}" ]
averages a property
[ "averages", "a", "property" ]
4a20309b14cee3b6eb74b24c688c5a4a5a98f879
https://github.com/brianleroux/lawnchair/blob/4a20309b14cee3b6eb74b24c688c5a4a5a98f879/src/plugins/aggregation.js#L27-L33
18,801
brianleroux/lawnchair
src/plugins/query.js
function() { // ever notice we do this sort thing lots? var args = [].slice.call(arguments) , tmpl = args.shift() , last = args[args.length - 1] , qs = tmpl.match(/\?/g) , q = qs && qs.length > 0 ? interpolate(tmpl, args.slice(0, qs.length)) : tmpl , is = new Function(this.record, 'return !!(' + q + ')') , r = [] , cb // iterate the entire collection // TODO should we allow for chained where() to filter __results? (I'm thinking no b/c creates funny behvaiors w/ callbacks) this.all(function(all){ for (var i = 0, l = all.length; i < l; i++) { if (is.call(all[i], all[i])) r.push(all[i]) } // overwrite working results this.__results = r // callback / chain if (args.length === 1) this.fn(this.name, last).call(this, this.__results) }) return this }
javascript
function() { // ever notice we do this sort thing lots? var args = [].slice.call(arguments) , tmpl = args.shift() , last = args[args.length - 1] , qs = tmpl.match(/\?/g) , q = qs && qs.length > 0 ? interpolate(tmpl, args.slice(0, qs.length)) : tmpl , is = new Function(this.record, 'return !!(' + q + ')') , r = [] , cb // iterate the entire collection // TODO should we allow for chained where() to filter __results? (I'm thinking no b/c creates funny behvaiors w/ callbacks) this.all(function(all){ for (var i = 0, l = all.length; i < l; i++) { if (is.call(all[i], all[i])) r.push(all[i]) } // overwrite working results this.__results = r // callback / chain if (args.length === 1) this.fn(this.name, last).call(this, this.__results) }) return this }
[ "function", "(", ")", "{", "// ever notice we do this sort thing lots?", "var", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ",", "tmpl", "=", "args", ".", "shift", "(", ")", ",", "last", "=", "args", "[", "args", ".", "length", "-", "1", "]", ",", "qs", "=", "tmpl", ".", "match", "(", "/", "\\?", "/", "g", ")", ",", "q", "=", "qs", "&&", "qs", ".", "length", ">", "0", "?", "interpolate", "(", "tmpl", ",", "args", ".", "slice", "(", "0", ",", "qs", ".", "length", ")", ")", ":", "tmpl", ",", "is", "=", "new", "Function", "(", "this", ".", "record", ",", "'return !!('", "+", "q", "+", "')'", ")", ",", "r", "=", "[", "]", ",", "cb", "// iterate the entire collection", "// TODO should we allow for chained where() to filter __results? (I'm thinking no b/c creates funny behvaiors w/ callbacks)", "this", ".", "all", "(", "function", "(", "all", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "all", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "is", ".", "call", "(", "all", "[", "i", "]", ",", "all", "[", "i", "]", ")", ")", "r", ".", "push", "(", "all", "[", "i", "]", ")", "}", "// overwrite working results", "this", ".", "__results", "=", "r", "// callback / chain", "if", "(", "args", ".", "length", "===", "1", ")", "this", ".", "fn", "(", "this", ".", "name", ",", "last", ")", ".", "call", "(", "this", ",", "this", ".", "__results", ")", "}", ")", "return", "this", "}" ]
query the storage obj
[ "query", "the", "storage", "obj" ]
4a20309b14cee3b6eb74b24c688c5a4a5a98f879
https://github.com/brianleroux/lawnchair/blob/4a20309b14cee3b6eb74b24c688c5a4a5a98f879/src/plugins/query.js#L27-L49
18,802
ace-diff/ace-diff
src/index.js
showDiff
function showDiff(acediff, editor, startLine, endLine, className) { var editor = acediff.editors[editor]; if (endLine < startLine) { // can this occur? Just in case. endLine = startLine; } const classNames = `${className} ${(endLine > startLine) ? 'lines' : 'targetOnly'}`; endLine--; // because endLine is always + 1 // to get Ace to highlight the full row we just set the start and end chars to 0 and 1 editor.markers.push(editor.ace.session.addMarker(new Range(startLine, 0, endLine, 1), classNames, 'fullLine')); }
javascript
function showDiff(acediff, editor, startLine, endLine, className) { var editor = acediff.editors[editor]; if (endLine < startLine) { // can this occur? Just in case. endLine = startLine; } const classNames = `${className} ${(endLine > startLine) ? 'lines' : 'targetOnly'}`; endLine--; // because endLine is always + 1 // to get Ace to highlight the full row we just set the start and end chars to 0 and 1 editor.markers.push(editor.ace.session.addMarker(new Range(startLine, 0, endLine, 1), classNames, 'fullLine')); }
[ "function", "showDiff", "(", "acediff", ",", "editor", ",", "startLine", ",", "endLine", ",", "className", ")", "{", "var", "editor", "=", "acediff", ".", "editors", "[", "editor", "]", ";", "if", "(", "endLine", "<", "startLine", ")", "{", "// can this occur? Just in case.", "endLine", "=", "startLine", ";", "}", "const", "classNames", "=", "`", "${", "className", "}", "${", "(", "endLine", ">", "startLine", ")", "?", "'lines'", ":", "'targetOnly'", "}", "`", ";", "endLine", "--", ";", "// because endLine is always + 1", "// to get Ace to highlight the full row we just set the start and end chars to 0 and 1", "editor", ".", "markers", ".", "push", "(", "editor", ".", "ace", ".", "session", ".", "addMarker", "(", "new", "Range", "(", "startLine", ",", "0", ",", "endLine", ",", "1", ")", ",", "classNames", ",", "'fullLine'", ")", ")", ";", "}" ]
shows a diff in one of the two editors.
[ "shows", "a", "diff", "in", "one", "of", "the", "two", "editors", "." ]
9b226804d4642cbc046c3c9da780ad3c270c6a3b
https://github.com/ace-diff/ace-diff/blob/9b226804d4642cbc046c3c9da780ad3c270c6a3b/src/index.js#L349-L361
18,803
ace-diff/ace-diff
src/index.js
updateGap
function updateGap(acediff, editor, scroll) { clearDiffs(acediff); decorate(acediff); // reposition the copy containers containing all the arrows positionCopyContainers(acediff); }
javascript
function updateGap(acediff, editor, scroll) { clearDiffs(acediff); decorate(acediff); // reposition the copy containers containing all the arrows positionCopyContainers(acediff); }
[ "function", "updateGap", "(", "acediff", ",", "editor", ",", "scroll", ")", "{", "clearDiffs", "(", "acediff", ")", ";", "decorate", "(", "acediff", ")", ";", "// reposition the copy containers containing all the arrows", "positionCopyContainers", "(", "acediff", ")", ";", "}" ]
called onscroll. Updates the gap to ensure the connectors are all lining up
[ "called", "onscroll", ".", "Updates", "the", "gap", "to", "ensure", "the", "connectors", "are", "all", "lining", "up" ]
9b226804d4642cbc046c3c9da780ad3c270c6a3b
https://github.com/ace-diff/ace-diff/blob/9b226804d4642cbc046c3c9da780ad3c270c6a3b/src/index.js#L365-L371
18,804
ace-diff/ace-diff
src/index.js
getSingleDiffInfo
function getSingleDiffInfo(editor, offset, diffString) { const info = { startLine: 0, startChar: 0, endLine: 0, endChar: 0, }; const endCharNum = offset + diffString.length; let runningTotal = 0; let startLineSet = false, endLineSet = false; editor.lineLengths.forEach((lineLength, lineIndex) => { runningTotal += lineLength; if (!startLineSet && offset < runningTotal) { info.startLine = lineIndex; info.startChar = offset - runningTotal + lineLength; startLineSet = true; } if (!endLineSet && endCharNum <= runningTotal) { info.endLine = lineIndex; info.endChar = endCharNum - runningTotal + lineLength; endLineSet = true; } }); // if the start char is the final char on the line, it's a newline & we ignore it if (info.startChar > 0 && getCharsOnLine(editor, info.startLine) === info.startChar) { info.startLine++; info.startChar = 0; } // if the end char is the first char on the line, we don't want to highlight that extra line if (info.endChar === 0) { info.endLine--; } const endsWithNewline = /\n$/.test(diffString); if (info.startChar > 0 && endsWithNewline) { info.endLine++; } return info; }
javascript
function getSingleDiffInfo(editor, offset, diffString) { const info = { startLine: 0, startChar: 0, endLine: 0, endChar: 0, }; const endCharNum = offset + diffString.length; let runningTotal = 0; let startLineSet = false, endLineSet = false; editor.lineLengths.forEach((lineLength, lineIndex) => { runningTotal += lineLength; if (!startLineSet && offset < runningTotal) { info.startLine = lineIndex; info.startChar = offset - runningTotal + lineLength; startLineSet = true; } if (!endLineSet && endCharNum <= runningTotal) { info.endLine = lineIndex; info.endChar = endCharNum - runningTotal + lineLength; endLineSet = true; } }); // if the start char is the final char on the line, it's a newline & we ignore it if (info.startChar > 0 && getCharsOnLine(editor, info.startLine) === info.startChar) { info.startLine++; info.startChar = 0; } // if the end char is the first char on the line, we don't want to highlight that extra line if (info.endChar === 0) { info.endLine--; } const endsWithNewline = /\n$/.test(diffString); if (info.startChar > 0 && endsWithNewline) { info.endLine++; } return info; }
[ "function", "getSingleDiffInfo", "(", "editor", ",", "offset", ",", "diffString", ")", "{", "const", "info", "=", "{", "startLine", ":", "0", ",", "startChar", ":", "0", ",", "endLine", ":", "0", ",", "endChar", ":", "0", ",", "}", ";", "const", "endCharNum", "=", "offset", "+", "diffString", ".", "length", ";", "let", "runningTotal", "=", "0", ";", "let", "startLineSet", "=", "false", ",", "endLineSet", "=", "false", ";", "editor", ".", "lineLengths", ".", "forEach", "(", "(", "lineLength", ",", "lineIndex", ")", "=>", "{", "runningTotal", "+=", "lineLength", ";", "if", "(", "!", "startLineSet", "&&", "offset", "<", "runningTotal", ")", "{", "info", ".", "startLine", "=", "lineIndex", ";", "info", ".", "startChar", "=", "offset", "-", "runningTotal", "+", "lineLength", ";", "startLineSet", "=", "true", ";", "}", "if", "(", "!", "endLineSet", "&&", "endCharNum", "<=", "runningTotal", ")", "{", "info", ".", "endLine", "=", "lineIndex", ";", "info", ".", "endChar", "=", "endCharNum", "-", "runningTotal", "+", "lineLength", ";", "endLineSet", "=", "true", ";", "}", "}", ")", ";", "// if the start char is the final char on the line, it's a newline & we ignore it", "if", "(", "info", ".", "startChar", ">", "0", "&&", "getCharsOnLine", "(", "editor", ",", "info", ".", "startLine", ")", "===", "info", ".", "startChar", ")", "{", "info", ".", "startLine", "++", ";", "info", ".", "startChar", "=", "0", ";", "}", "// if the end char is the first char on the line, we don't want to highlight that extra line", "if", "(", "info", ".", "endChar", "===", "0", ")", "{", "info", ".", "endLine", "--", ";", "}", "const", "endsWithNewline", "=", "/", "\\n$", "/", ".", "test", "(", "diffString", ")", ";", "if", "(", "info", ".", "startChar", ">", "0", "&&", "endsWithNewline", ")", "{", "info", ".", "endLine", "++", ";", "}", "return", "info", ";", "}" ]
helper to return the startline, endline, startChar and endChar for a diff in a particular editor. Pretty fussy function
[ "helper", "to", "return", "the", "startline", "endline", "startChar", "and", "endChar", "for", "a", "diff", "in", "a", "particular", "editor", ".", "Pretty", "fussy", "function" ]
9b226804d4642cbc046c3c9da780ad3c270c6a3b
https://github.com/ace-diff/ace-diff/blob/9b226804d4642cbc046c3c9da780ad3c270c6a3b/src/index.js#L575-L620
18,805
ace-diff/ace-diff
src/index.js
createCopyContainers
function createCopyContainers(acediff) { acediff.copyRightContainer = document.createElement('div'); acediff.copyRightContainer.setAttribute('class', acediff.options.classes.copyRightContainer); acediff.copyLeftContainer = document.createElement('div'); acediff.copyLeftContainer.setAttribute('class', acediff.options.classes.copyLeftContainer); document.getElementById(acediff.options.classes.gutterID).appendChild(acediff.copyRightContainer); document.getElementById(acediff.options.classes.gutterID).appendChild(acediff.copyLeftContainer); }
javascript
function createCopyContainers(acediff) { acediff.copyRightContainer = document.createElement('div'); acediff.copyRightContainer.setAttribute('class', acediff.options.classes.copyRightContainer); acediff.copyLeftContainer = document.createElement('div'); acediff.copyLeftContainer.setAttribute('class', acediff.options.classes.copyLeftContainer); document.getElementById(acediff.options.classes.gutterID).appendChild(acediff.copyRightContainer); document.getElementById(acediff.options.classes.gutterID).appendChild(acediff.copyLeftContainer); }
[ "function", "createCopyContainers", "(", "acediff", ")", "{", "acediff", ".", "copyRightContainer", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "acediff", ".", "copyRightContainer", ".", "setAttribute", "(", "'class'", ",", "acediff", ".", "options", ".", "classes", ".", "copyRightContainer", ")", ";", "acediff", ".", "copyLeftContainer", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "acediff", ".", "copyLeftContainer", ".", "setAttribute", "(", "'class'", ",", "acediff", ".", "options", ".", "classes", ".", "copyLeftContainer", ")", ";", "document", ".", "getElementById", "(", "acediff", ".", "options", ".", "classes", ".", "gutterID", ")", ".", "appendChild", "(", "acediff", ".", "copyRightContainer", ")", ";", "document", ".", "getElementById", "(", "acediff", ".", "options", ".", "classes", ".", "gutterID", ")", ".", "appendChild", "(", "acediff", ".", "copyLeftContainer", ")", ";", "}" ]
creates two contains for positioning the copy left + copy right arrows
[ "creates", "two", "contains", "for", "positioning", "the", "copy", "left", "+", "copy", "right", "arrows" ]
9b226804d4642cbc046c3c9da780ad3c270c6a3b
https://github.com/ace-diff/ace-diff/blob/9b226804d4642cbc046c3c9da780ad3c270c6a3b/src/index.js#L709-L717
18,806
andywer/ava-ts
types/make.js
generatePrefixed
function generatePrefixed(prefix) { let output = ''; let children = ''; for (const part of allParts) { const parts = prefix.concat([part]); if (prefix.indexOf(part) !== -1 || !verify(parts, true)) { // Function already in prefix or not allowed here continue; } // If `parts` is not sorted, we alias it to the sorted chain if (!isArraySorted(parts)) { if (exists(parts)) { parts.sort(); let chain; if (hasChildren(parts)) { chain = parts.join('_') + '<T>'; } else { // This is a single function, not a namespace, so there's no type associated // and we need to dereference it as a property type const last = parts.pop(); const joined = parts.join('_'); chain = `${joined}<T>['${last}']`; } output += `\t${part}: Register_${chain};\n`; } continue; } // Check that `part` is a valid function name. // `always` is a valid prefix, for instance of `always.after`, // but not a valid function name. if (verify(parts, false)) { if (arrayHas(parts)('todo')) { // 'todo' functions don't have a function argument, just a string output += `\t${part}: (name: string) => void;\n`; } else { if (arrayHas(parts)('cb')) { output += `\t${part}: CallbackRegisterBase<T>`; } else { output += `\t${part}: RegisterBase<T>`; } if (hasChildren(parts)) { // This chain can be continued, make the property an intersection type with the chain continuation const joined = parts.join('_'); output += ` & Register_${joined}<T>`; } output += ';\n'; } } children += generatePrefixed(parts); } if (output === '') { return children; } const typeBody = `{\n${output}}\n${children}`; if (prefix.length === 0) { // No prefix, so this is the type for the default export return `export interface Register<T> extends RegisterBase<T> ${typeBody}`; } const namespace = ['Register'].concat(prefix).join('_'); return `interface ${namespace}<T> ${typeBody}`; }
javascript
function generatePrefixed(prefix) { let output = ''; let children = ''; for (const part of allParts) { const parts = prefix.concat([part]); if (prefix.indexOf(part) !== -1 || !verify(parts, true)) { // Function already in prefix or not allowed here continue; } // If `parts` is not sorted, we alias it to the sorted chain if (!isArraySorted(parts)) { if (exists(parts)) { parts.sort(); let chain; if (hasChildren(parts)) { chain = parts.join('_') + '<T>'; } else { // This is a single function, not a namespace, so there's no type associated // and we need to dereference it as a property type const last = parts.pop(); const joined = parts.join('_'); chain = `${joined}<T>['${last}']`; } output += `\t${part}: Register_${chain};\n`; } continue; } // Check that `part` is a valid function name. // `always` is a valid prefix, for instance of `always.after`, // but not a valid function name. if (verify(parts, false)) { if (arrayHas(parts)('todo')) { // 'todo' functions don't have a function argument, just a string output += `\t${part}: (name: string) => void;\n`; } else { if (arrayHas(parts)('cb')) { output += `\t${part}: CallbackRegisterBase<T>`; } else { output += `\t${part}: RegisterBase<T>`; } if (hasChildren(parts)) { // This chain can be continued, make the property an intersection type with the chain continuation const joined = parts.join('_'); output += ` & Register_${joined}<T>`; } output += ';\n'; } } children += generatePrefixed(parts); } if (output === '') { return children; } const typeBody = `{\n${output}}\n${children}`; if (prefix.length === 0) { // No prefix, so this is the type for the default export return `export interface Register<T> extends RegisterBase<T> ${typeBody}`; } const namespace = ['Register'].concat(prefix).join('_'); return `interface ${namespace}<T> ${typeBody}`; }
[ "function", "generatePrefixed", "(", "prefix", ")", "{", "let", "output", "=", "''", ";", "let", "children", "=", "''", ";", "for", "(", "const", "part", "of", "allParts", ")", "{", "const", "parts", "=", "prefix", ".", "concat", "(", "[", "part", "]", ")", ";", "if", "(", "prefix", ".", "indexOf", "(", "part", ")", "!==", "-", "1", "||", "!", "verify", "(", "parts", ",", "true", ")", ")", "{", "// Function already in prefix or not allowed here", "continue", ";", "}", "// If `parts` is not sorted, we alias it to the sorted chain", "if", "(", "!", "isArraySorted", "(", "parts", ")", ")", "{", "if", "(", "exists", "(", "parts", ")", ")", "{", "parts", ".", "sort", "(", ")", ";", "let", "chain", ";", "if", "(", "hasChildren", "(", "parts", ")", ")", "{", "chain", "=", "parts", ".", "join", "(", "'_'", ")", "+", "'<T>'", ";", "}", "else", "{", "// This is a single function, not a namespace, so there's no type associated", "// and we need to dereference it as a property type", "const", "last", "=", "parts", ".", "pop", "(", ")", ";", "const", "joined", "=", "parts", ".", "join", "(", "'_'", ")", ";", "chain", "=", "`", "${", "joined", "}", "${", "last", "}", "`", ";", "}", "output", "+=", "`", "\\t", "${", "part", "}", "${", "chain", "}", "\\n", "`", ";", "}", "continue", ";", "}", "// Check that `part` is a valid function name.", "// `always` is a valid prefix, for instance of `always.after`,", "// but not a valid function name.", "if", "(", "verify", "(", "parts", ",", "false", ")", ")", "{", "if", "(", "arrayHas", "(", "parts", ")", "(", "'todo'", ")", ")", "{", "// 'todo' functions don't have a function argument, just a string", "output", "+=", "`", "\\t", "${", "part", "}", "\\n", "`", ";", "}", "else", "{", "if", "(", "arrayHas", "(", "parts", ")", "(", "'cb'", ")", ")", "{", "output", "+=", "`", "\\t", "${", "part", "}", "`", ";", "}", "else", "{", "output", "+=", "`", "\\t", "${", "part", "}", "`", ";", "}", "if", "(", "hasChildren", "(", "parts", ")", ")", "{", "// This chain can be continued, make the property an intersection type with the chain continuation", "const", "joined", "=", "parts", ".", "join", "(", "'_'", ")", ";", "output", "+=", "`", "${", "joined", "}", "`", ";", "}", "output", "+=", "';\\n'", ";", "}", "}", "children", "+=", "generatePrefixed", "(", "parts", ")", ";", "}", "if", "(", "output", "===", "''", ")", "{", "return", "children", ";", "}", "const", "typeBody", "=", "`", "\\n", "${", "output", "}", "\\n", "${", "children", "}", "`", ";", "if", "(", "prefix", ".", "length", "===", "0", ")", "{", "// No prefix, so this is the type for the default export", "return", "`", "${", "typeBody", "}", "`", ";", "}", "const", "namespace", "=", "[", "'Register'", "]", ".", "concat", "(", "prefix", ")", ".", "join", "(", "'_'", ")", ";", "return", "`", "${", "namespace", "}", "${", "typeBody", "}", "`", ";", "}" ]
Generates type definitions, for the specified prefix The prefix is an array of function names
[ "Generates", "type", "definitions", "for", "the", "specified", "prefix", "The", "prefix", "is", "an", "array", "of", "function", "names" ]
e1b7a7d97fdbf687648da270785bc028f291f290
https://github.com/andywer/ava-ts/blob/e1b7a7d97fdbf687648da270785bc028f291f290/types/make.js#L35-L108
18,807
andywer/ava-ts
types/make.js
hasChildren
function hasChildren(parts) { // Concatenate the chain with each other part, and see if any concatenations are valid functions const validChildren = allParts .filter(newPart => parts.indexOf(newPart) === -1) .map(newPart => parts.concat([newPart])) .filter(longer => verify(longer, false)); return validChildren.length > 0; }
javascript
function hasChildren(parts) { // Concatenate the chain with each other part, and see if any concatenations are valid functions const validChildren = allParts .filter(newPart => parts.indexOf(newPart) === -1) .map(newPart => parts.concat([newPart])) .filter(longer => verify(longer, false)); return validChildren.length > 0; }
[ "function", "hasChildren", "(", "parts", ")", "{", "// Concatenate the chain with each other part, and see if any concatenations are valid functions", "const", "validChildren", "=", "allParts", ".", "filter", "(", "newPart", "=>", "parts", ".", "indexOf", "(", "newPart", ")", "===", "-", "1", ")", ".", "map", "(", "newPart", "=>", "parts", ".", "concat", "(", "[", "newPart", "]", ")", ")", ".", "filter", "(", "longer", "=>", "verify", "(", "longer", ",", "false", ")", ")", ";", "return", "validChildren", ".", "length", ">", "0", ";", "}" ]
Returns true if a chain can have any child properties
[ "Returns", "true", "if", "a", "chain", "can", "have", "any", "child", "properties" ]
e1b7a7d97fdbf687648da270785bc028f291f290
https://github.com/andywer/ava-ts/blob/e1b7a7d97fdbf687648da270785bc028f291f290/types/make.js#L154-L162
18,808
andywer/ava-ts
types/make.js
exists
function exists(parts) { if (verify(parts, false)) { // Valid function name return true; } if (!verify(parts, true)) { // Not valid prefix return false; } // Valid prefix, check whether it has members for (const prefix of allParts) { if (parts.indexOf(prefix) === -1 && exists(parts.concat([prefix]))) { return true; } } return false; }
javascript
function exists(parts) { if (verify(parts, false)) { // Valid function name return true; } if (!verify(parts, true)) { // Not valid prefix return false; } // Valid prefix, check whether it has members for (const prefix of allParts) { if (parts.indexOf(prefix) === -1 && exists(parts.concat([prefix]))) { return true; } } return false; }
[ "function", "exists", "(", "parts", ")", "{", "if", "(", "verify", "(", "parts", ",", "false", ")", ")", "{", "// Valid function name", "return", "true", ";", "}", "if", "(", "!", "verify", "(", "parts", ",", "true", ")", ")", "{", "// Not valid prefix", "return", "false", ";", "}", "// Valid prefix, check whether it has members", "for", "(", "const", "prefix", "of", "allParts", ")", "{", "if", "(", "parts", ".", "indexOf", "(", "prefix", ")", "===", "-", "1", "&&", "exists", "(", "parts", ".", "concat", "(", "[", "prefix", "]", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether a chain is a valid function name or a valid prefix with some member
[ "Checks", "whether", "a", "chain", "is", "a", "valid", "function", "name", "or", "a", "valid", "prefix", "with", "some", "member" ]
e1b7a7d97fdbf687648da270785bc028f291f290
https://github.com/andywer/ava-ts/blob/e1b7a7d97fdbf687648da270785bc028f291f290/types/make.js#L165-L184
18,809
pillarjs/csrf
index.js
hash
function hash (str) { return crypto .createHash('sha1') .update(str, 'ascii') .digest('base64') .replace(PLUS_GLOBAL_REGEXP, '-') .replace(SLASH_GLOBAL_REGEXP, '_') .replace(EQUAL_GLOBAL_REGEXP, '') }
javascript
function hash (str) { return crypto .createHash('sha1') .update(str, 'ascii') .digest('base64') .replace(PLUS_GLOBAL_REGEXP, '-') .replace(SLASH_GLOBAL_REGEXP, '_') .replace(EQUAL_GLOBAL_REGEXP, '') }
[ "function", "hash", "(", "str", ")", "{", "return", "crypto", ".", "createHash", "(", "'sha1'", ")", ".", "update", "(", "str", ",", "'ascii'", ")", ".", "digest", "(", "'base64'", ")", ".", "replace", "(", "PLUS_GLOBAL_REGEXP", ",", "'-'", ")", ".", "replace", "(", "SLASH_GLOBAL_REGEXP", ",", "'_'", ")", ".", "replace", "(", "EQUAL_GLOBAL_REGEXP", ",", "''", ")", "}" ]
Hash a string with SHA1, returning url-safe base64 @param {string} str @private
[ "Hash", "a", "string", "with", "SHA1", "returning", "url", "-", "safe", "base64" ]
775fb78ebc9ab5fda902c8cc27f8d16eb7066e8f
https://github.com/pillarjs/csrf/blob/775fb78ebc9ab5fda902c8cc27f8d16eb7066e8f/index.js#L151-L159
18,810
memcachier/memjs
lib/memjs/memjs.js
function(servers, options) { this.servers = servers; this.seq = 0; this.options = merge(options || {}, {failoverTime: 60, retries: 2, retry_delay: 0.2, expires: 0, logger: console}); }
javascript
function(servers, options) { this.servers = servers; this.seq = 0; this.options = merge(options || {}, {failoverTime: 60, retries: 2, retry_delay: 0.2, expires: 0, logger: console}); }
[ "function", "(", "servers", ",", "options", ")", "{", "this", ".", "servers", "=", "servers", ";", "this", ".", "seq", "=", "0", ";", "this", ".", "options", "=", "merge", "(", "options", "||", "{", "}", ",", "{", "failoverTime", ":", "60", ",", "retries", ":", "2", ",", "retry_delay", ":", "0.2", ",", "expires", ":", "0", ",", "logger", ":", "console", "}", ")", ";", "}" ]
Client initializer takes a list of `Server`s and an `options` dictionary. See `Client.create` for details.
[ "Client", "initializer", "takes", "a", "list", "of", "Server", "s", "and", "an", "options", "dictionary", ".", "See", "Client", ".", "create", "for", "details", "." ]
d756670da3a85afb86eebeab6a3baa0738701273
https://github.com/memcachier/memjs/blob/d756670da3a85afb86eebeab6a3baa0738701273/lib/memjs/memjs.js#L13-L18
18,811
flatiron/flatiron
lib/flatiron/cli/create.js
prompt
function prompt (next) { var fields = ['name', 'author', 'description', 'homepage']; app.prompt.override = {name: name}; app.prompt.start(); app.prompt.addProperties(info, fields, next); }
javascript
function prompt (next) { var fields = ['name', 'author', 'description', 'homepage']; app.prompt.override = {name: name}; app.prompt.start(); app.prompt.addProperties(info, fields, next); }
[ "function", "prompt", "(", "next", ")", "{", "var", "fields", "=", "[", "'name'", ",", "'author'", ",", "'description'", ",", "'homepage'", "]", ";", "app", ".", "prompt", ".", "override", "=", "{", "name", ":", "name", "}", ";", "app", ".", "prompt", ".", "start", "(", ")", ";", "app", ".", "prompt", ".", "addProperties", "(", "info", ",", "fields", ",", "next", ")", ";", "}" ]
Prompts user for details about their app to put in `package.json`.
[ "Prompts", "user", "for", "details", "about", "their", "app", "to", "put", "in", "package", ".", "json", "." ]
2c34fe7ec160831945977c6cbe3dde11d7a32da5
https://github.com/flatiron/flatiron/blob/2c34fe7ec160831945977c6cbe3dde11d7a32da5/lib/flatiron/cli/create.js#L24-L29
18,812
flatiron/flatiron
lib/flatiron/plugins/cli.js
ensureDestroy
function ensureDestroy(callback) { app.prompt.get(['destroy'], function (err, result) { if (result.destroy !== 'yes' && result.destroy !== 'y') { app.log.warn('Destructive operation cancelled'); return callback(true); } callback(); }); }
javascript
function ensureDestroy(callback) { app.prompt.get(['destroy'], function (err, result) { if (result.destroy !== 'yes' && result.destroy !== 'y') { app.log.warn('Destructive operation cancelled'); return callback(true); } callback(); }); }
[ "function", "ensureDestroy", "(", "callback", ")", "{", "app", ".", "prompt", ".", "get", "(", "[", "'destroy'", "]", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "result", ".", "destroy", "!==", "'yes'", "&&", "result", ".", "destroy", "!==", "'y'", ")", "{", "app", ".", "log", ".", "warn", "(", "'Destructive operation cancelled'", ")", ";", "return", "callback", "(", "true", ")", ";", "}", "callback", "(", ")", ";", "}", ")", ";", "}" ]
Helper function to ensure the user wishes to execute a destructive command.
[ "Helper", "function", "to", "ensure", "the", "user", "wishes", "to", "execute", "a", "destructive", "command", "." ]
2c34fe7ec160831945977c6cbe3dde11d7a32da5
https://github.com/flatiron/flatiron/blob/2c34fe7ec160831945977c6cbe3dde11d7a32da5/lib/flatiron/plugins/cli.js#L243-L252
18,813
flatiron/flatiron
lib/flatiron/plugins/cli.js
executeCommand
function executeCommand(parts, callback) { var name, shouldLoad = true, command, usage; if (typeof parts === 'undefined' || typeof parts === 'function') { throw(new Error('parts is a required argument of type Array')); } name = parts.shift(); if (app.cli.source || app.commands[name]) { if (app.commands[name]) { shouldLoad = false; if (typeof app.commands[name] != 'function' && !app.commands[name][parts[0]]) { shouldLoad = true; } } if (shouldLoad && !loadCommand(name, parts[0])) { return callback(); } command = app.commands[name]; while (command) { usage = command.usage; if (!app.argv.h && !app.argv.help && typeof command === 'function') { while (parts.length + 1 < command.length) { parts.push(null); } if (command.destructive) { return ensureDestroy(function (err) { return err ? callback() : command.apply(app, parts.concat(callback)); }) } command.apply(app, parts.concat(callback)); return; } command = command[parts.shift()]; } // // Since we have not resolved a needle, try and print out a usage message // if (usage || app.cli.usage) { showUsage(usage || app.cli.usage); callback(false); } } else if (app.usage) { // // If there's no directory we're supposed to search for modules, simply // print out usage notice if it's provided. // showUsage(app.cli.usage); callback(true); } }
javascript
function executeCommand(parts, callback) { var name, shouldLoad = true, command, usage; if (typeof parts === 'undefined' || typeof parts === 'function') { throw(new Error('parts is a required argument of type Array')); } name = parts.shift(); if (app.cli.source || app.commands[name]) { if (app.commands[name]) { shouldLoad = false; if (typeof app.commands[name] != 'function' && !app.commands[name][parts[0]]) { shouldLoad = true; } } if (shouldLoad && !loadCommand(name, parts[0])) { return callback(); } command = app.commands[name]; while (command) { usage = command.usage; if (!app.argv.h && !app.argv.help && typeof command === 'function') { while (parts.length + 1 < command.length) { parts.push(null); } if (command.destructive) { return ensureDestroy(function (err) { return err ? callback() : command.apply(app, parts.concat(callback)); }) } command.apply(app, parts.concat(callback)); return; } command = command[parts.shift()]; } // // Since we have not resolved a needle, try and print out a usage message // if (usage || app.cli.usage) { showUsage(usage || app.cli.usage); callback(false); } } else if (app.usage) { // // If there's no directory we're supposed to search for modules, simply // print out usage notice if it's provided. // showUsage(app.cli.usage); callback(true); } }
[ "function", "executeCommand", "(", "parts", ",", "callback", ")", "{", "var", "name", ",", "shouldLoad", "=", "true", ",", "command", ",", "usage", ";", "if", "(", "typeof", "parts", "===", "'undefined'", "||", "typeof", "parts", "===", "'function'", ")", "{", "throw", "(", "new", "Error", "(", "'parts is a required argument of type Array'", ")", ")", ";", "}", "name", "=", "parts", ".", "shift", "(", ")", ";", "if", "(", "app", ".", "cli", ".", "source", "||", "app", ".", "commands", "[", "name", "]", ")", "{", "if", "(", "app", ".", "commands", "[", "name", "]", ")", "{", "shouldLoad", "=", "false", ";", "if", "(", "typeof", "app", ".", "commands", "[", "name", "]", "!=", "'function'", "&&", "!", "app", ".", "commands", "[", "name", "]", "[", "parts", "[", "0", "]", "]", ")", "{", "shouldLoad", "=", "true", ";", "}", "}", "if", "(", "shouldLoad", "&&", "!", "loadCommand", "(", "name", ",", "parts", "[", "0", "]", ")", ")", "{", "return", "callback", "(", ")", ";", "}", "command", "=", "app", ".", "commands", "[", "name", "]", ";", "while", "(", "command", ")", "{", "usage", "=", "command", ".", "usage", ";", "if", "(", "!", "app", ".", "argv", ".", "h", "&&", "!", "app", ".", "argv", ".", "help", "&&", "typeof", "command", "===", "'function'", ")", "{", "while", "(", "parts", ".", "length", "+", "1", "<", "command", ".", "length", ")", "{", "parts", ".", "push", "(", "null", ")", ";", "}", "if", "(", "command", ".", "destructive", ")", "{", "return", "ensureDestroy", "(", "function", "(", "err", ")", "{", "return", "err", "?", "callback", "(", ")", ":", "command", ".", "apply", "(", "app", ",", "parts", ".", "concat", "(", "callback", ")", ")", ";", "}", ")", "}", "command", ".", "apply", "(", "app", ",", "parts", ".", "concat", "(", "callback", ")", ")", ";", "return", ";", "}", "command", "=", "command", "[", "parts", ".", "shift", "(", ")", "]", ";", "}", "//", "// Since we have not resolved a needle, try and print out a usage message", "//", "if", "(", "usage", "||", "app", ".", "cli", ".", "usage", ")", "{", "showUsage", "(", "usage", "||", "app", ".", "cli", ".", "usage", ")", ";", "callback", "(", "false", ")", ";", "}", "}", "else", "if", "(", "app", ".", "usage", ")", "{", "//", "// If there's no directory we're supposed to search for modules, simply", "// print out usage notice if it's provided.", "//", "showUsage", "(", "app", ".", "cli", ".", "usage", ")", ";", "callback", "(", "true", ")", ";", "}", "}" ]
Helper function which executes the command represented by the Array of `parts` passing control to the `callback`.
[ "Helper", "function", "which", "executes", "the", "command", "represented", "by", "the", "Array", "of", "parts", "passing", "control", "to", "the", "callback", "." ]
2c34fe7ec160831945977c6cbe3dde11d7a32da5
https://github.com/flatiron/flatiron/blob/2c34fe7ec160831945977c6cbe3dde11d7a32da5/lib/flatiron/plugins/cli.js#L259-L321
18,814
jonschlinkert/randomatic
benchmark/code/for.js
randomatic
function randomatic(pattern, length, options) { if (typeof pattern === 'undefined') { throw new Error('randomatic expects a string or number.'); } var custom = false; if (arguments.length === 1) { if (typeof pattern === 'string') { length = pattern.length; } else if (isNumber(pattern)) { options = {}; length = pattern; pattern = '*'; } } if(typeOf(length) === 'object' && length.hasOwnProperty('chars')) { options = length; pattern = options.chars; length = pattern.length; custom = true; } var opts = options || {}; var mask = ''; var res = ''; // Characters to be used if (pattern.indexOf('?') !== -1) mask += opts.chars; if (pattern.indexOf('a') !== -1) mask += type.lower; if (pattern.indexOf('A') !== -1) mask += type.upper; if (pattern.indexOf('0') !== -1) mask += type.number; if (pattern.indexOf('!') !== -1) mask += type.special; if (pattern.indexOf('*') !== -1) mask += type.all; if (custom) mask += pattern; for (var i = 0; i < length; i++) { res += mask.charAt(parseInt(Math.random() * mask.length)); } return res; }
javascript
function randomatic(pattern, length, options) { if (typeof pattern === 'undefined') { throw new Error('randomatic expects a string or number.'); } var custom = false; if (arguments.length === 1) { if (typeof pattern === 'string') { length = pattern.length; } else if (isNumber(pattern)) { options = {}; length = pattern; pattern = '*'; } } if(typeOf(length) === 'object' && length.hasOwnProperty('chars')) { options = length; pattern = options.chars; length = pattern.length; custom = true; } var opts = options || {}; var mask = ''; var res = ''; // Characters to be used if (pattern.indexOf('?') !== -1) mask += opts.chars; if (pattern.indexOf('a') !== -1) mask += type.lower; if (pattern.indexOf('A') !== -1) mask += type.upper; if (pattern.indexOf('0') !== -1) mask += type.number; if (pattern.indexOf('!') !== -1) mask += type.special; if (pattern.indexOf('*') !== -1) mask += type.all; if (custom) mask += pattern; for (var i = 0; i < length; i++) { res += mask.charAt(parseInt(Math.random() * mask.length)); } return res; }
[ "function", "randomatic", "(", "pattern", ",", "length", ",", "options", ")", "{", "if", "(", "typeof", "pattern", "===", "'undefined'", ")", "{", "throw", "new", "Error", "(", "'randomatic expects a string or number.'", ")", ";", "}", "var", "custom", "=", "false", ";", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "if", "(", "typeof", "pattern", "===", "'string'", ")", "{", "length", "=", "pattern", ".", "length", ";", "}", "else", "if", "(", "isNumber", "(", "pattern", ")", ")", "{", "options", "=", "{", "}", ";", "length", "=", "pattern", ";", "pattern", "=", "'*'", ";", "}", "}", "if", "(", "typeOf", "(", "length", ")", "===", "'object'", "&&", "length", ".", "hasOwnProperty", "(", "'chars'", ")", ")", "{", "options", "=", "length", ";", "pattern", "=", "options", ".", "chars", ";", "length", "=", "pattern", ".", "length", ";", "custom", "=", "true", ";", "}", "var", "opts", "=", "options", "||", "{", "}", ";", "var", "mask", "=", "''", ";", "var", "res", "=", "''", ";", "// Characters to be used", "if", "(", "pattern", ".", "indexOf", "(", "'?'", ")", "!==", "-", "1", ")", "mask", "+=", "opts", ".", "chars", ";", "if", "(", "pattern", ".", "indexOf", "(", "'a'", ")", "!==", "-", "1", ")", "mask", "+=", "type", ".", "lower", ";", "if", "(", "pattern", ".", "indexOf", "(", "'A'", ")", "!==", "-", "1", ")", "mask", "+=", "type", ".", "upper", ";", "if", "(", "pattern", ".", "indexOf", "(", "'0'", ")", "!==", "-", "1", ")", "mask", "+=", "type", ".", "number", ";", "if", "(", "pattern", ".", "indexOf", "(", "'!'", ")", "!==", "-", "1", ")", "mask", "+=", "type", ".", "special", ";", "if", "(", "pattern", ".", "indexOf", "(", "'*'", ")", "!==", "-", "1", ")", "mask", "+=", "type", ".", "all", ";", "if", "(", "custom", ")", "mask", "+=", "pattern", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "res", "+=", "mask", ".", "charAt", "(", "parseInt", "(", "Math", ".", "random", "(", ")", "*", "mask", ".", "length", ")", ")", ";", "}", "return", "res", ";", "}" ]
Generate random character sequences of a specified `length`, based on the given `pattern`. @param {String} `pattern` The pattern to use for generating the random string. @param {String} `length` The length of the string to generate. @param {String} `options` @return {String} @api public
[ "Generate", "random", "character", "sequences", "of", "a", "specified", "length", "based", "on", "the", "given", "pattern", "." ]
b7451f4dac44a9920790f76a4d8a1dd081c37a5a
https://github.com/jonschlinkert/randomatic/blob/b7451f4dac44a9920790f76a4d8a1dd081c37a5a/benchmark/code/for.js#L46-L88
18,815
vuetwo/vuetron
packages/vuetron-app/src/sockets/SocketPlugin.js
function (port = 9090) { return store => { const getId = idGenerator(); // initialize socket connection const socket = io('http://localhost:' + port); // register event noting connection to sockets (client app) let initEvent = buildEvent(getId(), 'CONNECTED TO SERVER', 'Successfully connected Vuetron to server.'); store.commit('addNewEvent', initEvent); socket.on('clientAppConnected', function () { let event = buildEvent(getId(), 'CLIENT APP CONNECTED', 'Successfully connected to client application.'); store.commit('addNewEvent', event); }); socket.on('setInitState', function (state) { let event = buildEvent(getId(), 'STATE INITIALIZED', state); // register event noting receipt of initial client state store.commit('addNewEvent', event); // initialize client state value store.commit('updateClientState', state); }); // listen for state changes from client and update // vuetron's client state store accordingly along // with mutation log socket.on('stateUpdate', function (changes, mutation, newState) { let updatedState = buildEvent(getId(), 'STATE CHANGE', {'changes': changes}); // add mutations updatedState.mutation = mutation; // add newState updatedState.state = JSON.stringify(newState); // register event for state change store.commit('addNewEvent', updatedState); // update client's current state to newState store.commit('updateClientState', newState); // check if any of the mutations are subscribed if (changes) { for (let change of changes) { const parsedPath = pathParser(JSON.stringify(change.path)); // if subscribed, push to that path's array for display for (let key of Object.keys(store.state.subscriptions)) { if (key === parsedPath || parsedPath.search(key) !== -1) { store.commit('addEventToSubscription', { key, change }); } } } } }); socket.on('eventUpdate', function (event) { let newEvent = buildEvent(getId(), 'EVENT EMITTED', event); store.commit('addNewEvent', newEvent); }); socket.on('domUpdate', function (dom) { store.commit('updateClientDom', dom); }); // listen for API responses made from FETCH requests and add to Event Stream socket.on('apiRequestResponse', function (response) { const display = { requestObj: response.requestConfig.slice(0), responseObj: response }; delete display.responseObj.requestConfig; const apiEvent = buildEvent(getId(), 'API REQUEST / RESPONSE', display); store.commit('addNewEvent', apiEvent); }); }; }
javascript
function (port = 9090) { return store => { const getId = idGenerator(); // initialize socket connection const socket = io('http://localhost:' + port); // register event noting connection to sockets (client app) let initEvent = buildEvent(getId(), 'CONNECTED TO SERVER', 'Successfully connected Vuetron to server.'); store.commit('addNewEvent', initEvent); socket.on('clientAppConnected', function () { let event = buildEvent(getId(), 'CLIENT APP CONNECTED', 'Successfully connected to client application.'); store.commit('addNewEvent', event); }); socket.on('setInitState', function (state) { let event = buildEvent(getId(), 'STATE INITIALIZED', state); // register event noting receipt of initial client state store.commit('addNewEvent', event); // initialize client state value store.commit('updateClientState', state); }); // listen for state changes from client and update // vuetron's client state store accordingly along // with mutation log socket.on('stateUpdate', function (changes, mutation, newState) { let updatedState = buildEvent(getId(), 'STATE CHANGE', {'changes': changes}); // add mutations updatedState.mutation = mutation; // add newState updatedState.state = JSON.stringify(newState); // register event for state change store.commit('addNewEvent', updatedState); // update client's current state to newState store.commit('updateClientState', newState); // check if any of the mutations are subscribed if (changes) { for (let change of changes) { const parsedPath = pathParser(JSON.stringify(change.path)); // if subscribed, push to that path's array for display for (let key of Object.keys(store.state.subscriptions)) { if (key === parsedPath || parsedPath.search(key) !== -1) { store.commit('addEventToSubscription', { key, change }); } } } } }); socket.on('eventUpdate', function (event) { let newEvent = buildEvent(getId(), 'EVENT EMITTED', event); store.commit('addNewEvent', newEvent); }); socket.on('domUpdate', function (dom) { store.commit('updateClientDom', dom); }); // listen for API responses made from FETCH requests and add to Event Stream socket.on('apiRequestResponse', function (response) { const display = { requestObj: response.requestConfig.slice(0), responseObj: response }; delete display.responseObj.requestConfig; const apiEvent = buildEvent(getId(), 'API REQUEST / RESPONSE', display); store.commit('addNewEvent', apiEvent); }); }; }
[ "function", "(", "port", "=", "9090", ")", "{", "return", "store", "=>", "{", "const", "getId", "=", "idGenerator", "(", ")", ";", "// initialize socket connection", "const", "socket", "=", "io", "(", "'http://localhost:'", "+", "port", ")", ";", "// register event noting connection to sockets (client app)", "let", "initEvent", "=", "buildEvent", "(", "getId", "(", ")", ",", "'CONNECTED TO SERVER'", ",", "'Successfully connected Vuetron to server.'", ")", ";", "store", ".", "commit", "(", "'addNewEvent'", ",", "initEvent", ")", ";", "socket", ".", "on", "(", "'clientAppConnected'", ",", "function", "(", ")", "{", "let", "event", "=", "buildEvent", "(", "getId", "(", ")", ",", "'CLIENT APP CONNECTED'", ",", "'Successfully connected to client application.'", ")", ";", "store", ".", "commit", "(", "'addNewEvent'", ",", "event", ")", ";", "}", ")", ";", "socket", ".", "on", "(", "'setInitState'", ",", "function", "(", "state", ")", "{", "let", "event", "=", "buildEvent", "(", "getId", "(", ")", ",", "'STATE INITIALIZED'", ",", "state", ")", ";", "// register event noting receipt of initial client state", "store", ".", "commit", "(", "'addNewEvent'", ",", "event", ")", ";", "// initialize client state value", "store", ".", "commit", "(", "'updateClientState'", ",", "state", ")", ";", "}", ")", ";", "// listen for state changes from client and update", "// vuetron's client state store accordingly along", "// with mutation log", "socket", ".", "on", "(", "'stateUpdate'", ",", "function", "(", "changes", ",", "mutation", ",", "newState", ")", "{", "let", "updatedState", "=", "buildEvent", "(", "getId", "(", ")", ",", "'STATE CHANGE'", ",", "{", "'changes'", ":", "changes", "}", ")", ";", "// add mutations", "updatedState", ".", "mutation", "=", "mutation", ";", "// add newState", "updatedState", ".", "state", "=", "JSON", ".", "stringify", "(", "newState", ")", ";", "// register event for state change", "store", ".", "commit", "(", "'addNewEvent'", ",", "updatedState", ")", ";", "// update client's current state to newState", "store", ".", "commit", "(", "'updateClientState'", ",", "newState", ")", ";", "// check if any of the mutations are subscribed", "if", "(", "changes", ")", "{", "for", "(", "let", "change", "of", "changes", ")", "{", "const", "parsedPath", "=", "pathParser", "(", "JSON", ".", "stringify", "(", "change", ".", "path", ")", ")", ";", "// if subscribed, push to that path's array for display", "for", "(", "let", "key", "of", "Object", ".", "keys", "(", "store", ".", "state", ".", "subscriptions", ")", ")", "{", "if", "(", "key", "===", "parsedPath", "||", "parsedPath", ".", "search", "(", "key", ")", "!==", "-", "1", ")", "{", "store", ".", "commit", "(", "'addEventToSubscription'", ",", "{", "key", ",", "change", "}", ")", ";", "}", "}", "}", "}", "}", ")", ";", "socket", ".", "on", "(", "'eventUpdate'", ",", "function", "(", "event", ")", "{", "let", "newEvent", "=", "buildEvent", "(", "getId", "(", ")", ",", "'EVENT EMITTED'", ",", "event", ")", ";", "store", ".", "commit", "(", "'addNewEvent'", ",", "newEvent", ")", ";", "}", ")", ";", "socket", ".", "on", "(", "'domUpdate'", ",", "function", "(", "dom", ")", "{", "store", ".", "commit", "(", "'updateClientDom'", ",", "dom", ")", ";", "}", ")", ";", "// listen for API responses made from FETCH requests and add to Event Stream", "socket", ".", "on", "(", "'apiRequestResponse'", ",", "function", "(", "response", ")", "{", "const", "display", "=", "{", "requestObj", ":", "response", ".", "requestConfig", ".", "slice", "(", "0", ")", ",", "responseObj", ":", "response", "}", ";", "delete", "display", ".", "responseObj", ".", "requestConfig", ";", "const", "apiEvent", "=", "buildEvent", "(", "getId", "(", ")", ",", "'API REQUEST / RESPONSE'", ",", "display", ")", ";", "store", ".", "commit", "(", "'addNewEvent'", ",", "apiEvent", ")", ";", "}", ")", ";", "}", ";", "}" ]
setup plugin to connect vuex store to server sockets
[ "setup", "plugin", "to", "connect", "vuex", "store", "to", "server", "sockets" ]
bf3faf1dd576a01aa2331c85447272b5b630474e
https://github.com/vuetwo/vuetron/blob/bf3faf1dd576a01aa2331c85447272b5b630474e/packages/vuetron-app/src/sockets/SocketPlugin.js#L16-L85
18,816
vuetwo/vuetron
packages/vuetron-app/src/sockets/SocketPlugin.js
buildEvent
function buildEvent (id, title, display, hidden = {}) { const eventObj = { id, title, display, hidden, status: 'active', timestamp: new Date(Date.now()).toISOString() }; return eventObj; }
javascript
function buildEvent (id, title, display, hidden = {}) { const eventObj = { id, title, display, hidden, status: 'active', timestamp: new Date(Date.now()).toISOString() }; return eventObj; }
[ "function", "buildEvent", "(", "id", ",", "title", ",", "display", ",", "hidden", "=", "{", "}", ")", "{", "const", "eventObj", "=", "{", "id", ",", "title", ",", "display", ",", "hidden", ",", "status", ":", "'active'", ",", "timestamp", ":", "new", "Date", "(", "Date", ".", "now", "(", ")", ")", ".", "toISOString", "(", ")", "}", ";", "return", "eventObj", ";", "}" ]
Build events for display in EventStream
[ "Build", "events", "for", "display", "in", "EventStream" ]
bf3faf1dd576a01aa2331c85447272b5b630474e
https://github.com/vuetwo/vuetron/blob/bf3faf1dd576a01aa2331c85447272b5b630474e/packages/vuetron-app/src/sockets/SocketPlugin.js#L88-L98
18,817
xebia/VisualReview-protractor
lib/vr-client.js
sendScreenshot
function sendScreenshot (name, runId, metaData, properties, compareSettings, png) { return _callServer('post', 'runs/' + runId + '/screenshots', null, { meta: JSON.stringify(metaData), properties: JSON.stringify(properties), compareSettings: JSON.stringify(compareSettings), screenshotName: name, file: { value: new Buffer(png, 'base64'), options: { filename: 'file.png', contentType: 'image/png' } } }).catch(function (error) { return q.reject('an error occured while sending a screenshot to the VisualReview server: ' + error); }); }
javascript
function sendScreenshot (name, runId, metaData, properties, compareSettings, png) { return _callServer('post', 'runs/' + runId + '/screenshots', null, { meta: JSON.stringify(metaData), properties: JSON.stringify(properties), compareSettings: JSON.stringify(compareSettings), screenshotName: name, file: { value: new Buffer(png, 'base64'), options: { filename: 'file.png', contentType: 'image/png' } } }).catch(function (error) { return q.reject('an error occured while sending a screenshot to the VisualReview server: ' + error); }); }
[ "function", "sendScreenshot", "(", "name", ",", "runId", ",", "metaData", ",", "properties", ",", "compareSettings", ",", "png", ")", "{", "return", "_callServer", "(", "'post'", ",", "'runs/'", "+", "runId", "+", "'/screenshots'", ",", "null", ",", "{", "meta", ":", "JSON", ".", "stringify", "(", "metaData", ")", ",", "properties", ":", "JSON", ".", "stringify", "(", "properties", ")", ",", "compareSettings", ":", "JSON", ".", "stringify", "(", "compareSettings", ")", ",", "screenshotName", ":", "name", ",", "file", ":", "{", "value", ":", "new", "Buffer", "(", "png", ",", "'base64'", ")", ",", "options", ":", "{", "filename", ":", "'file.png'", ",", "contentType", ":", "'image/png'", "}", "}", "}", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "return", "q", ".", "reject", "(", "'an error occured while sending a screenshot to the VisualReview server: '", "+", "error", ")", ";", "}", ")", ";", "}" ]
Uploads an new screenshot to the given run. @param name @param runId @param metaData @param properties @param png @returns {Promise} a promise. If an error has occured, the promise will reject with a string containing an error message.
[ "Uploads", "an", "new", "screenshot", "to", "the", "given", "run", "." ]
64412828140b2cb76e441cabf720b0d31bf5a631
https://github.com/xebia/VisualReview-protractor/blob/64412828140b2cb76e441cabf720b0d31bf5a631/lib/vr-client.js#L81-L97
18,818
xebia/VisualReview-protractor
visualreview-protractor.js
initRun
function initRun (projectName, suiteName, branchName) { if(_disabled) { return q.resolve(); } return _client.createRun(projectName, suiteName, branchName).then( function (createdRun) { if (createdRun) { _logMessage('created run with ID ' + createdRun.run_id); return _writeRunIdFile(JSON.stringify(createdRun)); } }.bind(this), function (err) { _throwError(err); }); }
javascript
function initRun (projectName, suiteName, branchName) { if(_disabled) { return q.resolve(); } return _client.createRun(projectName, suiteName, branchName).then( function (createdRun) { if (createdRun) { _logMessage('created run with ID ' + createdRun.run_id); return _writeRunIdFile(JSON.stringify(createdRun)); } }.bind(this), function (err) { _throwError(err); }); }
[ "function", "initRun", "(", "projectName", ",", "suiteName", ",", "branchName", ")", "{", "if", "(", "_disabled", ")", "{", "return", "q", ".", "resolve", "(", ")", ";", "}", "return", "_client", ".", "createRun", "(", "projectName", ",", "suiteName", ",", "branchName", ")", ".", "then", "(", "function", "(", "createdRun", ")", "{", "if", "(", "createdRun", ")", "{", "_logMessage", "(", "'created run with ID '", "+", "createdRun", ".", "run_id", ")", ";", "return", "_writeRunIdFile", "(", "JSON", ".", "stringify", "(", "createdRun", ")", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ",", "function", "(", "err", ")", "{", "_throwError", "(", "err", ")", ";", "}", ")", ";", "}" ]
Initializes a run on the given project's suite name. @param projectName @param suiteName @param branchName @returns {Promise} a promise which resolves a new Run object with the fields run_id, project_id, suite_id and branch_name. If an error has occurred, the promise will reject with a string containing an error message.
[ "Initializes", "a", "run", "on", "the", "given", "project", "s", "suite", "name", "." ]
64412828140b2cb76e441cabf720b0d31bf5a631
https://github.com/xebia/VisualReview-protractor/blob/64412828140b2cb76e441cabf720b0d31bf5a631/visualreview-protractor.js#L58-L71
18,819
xebia/VisualReview-protractor
visualreview-protractor.js
takeScreenshot
function takeScreenshot (name) { if(_disabled) { return q.resolve(); } return browser.driver.controlFlow().execute(function () { return q.all([_getProperties(browser), _getMetaData(browser), browser.takeScreenshot(), _readRunIdFile()]).then(function (results) { var properties = results[0], metaData = results[1], compareSettings = _compareSettingsFn, png = results[2], run = results[3]; if (!run || !run.run_id) { _throwError('VisualReview-protractor: Could not send screenshot to VisualReview server, could not find any run ID. Was initRun called before starting this test? See VisualReview-protractor\'s documentation for more details on how to set this up.'); } return _client.sendScreenshot(name, run.run_id, metaData, properties, compareSettings, png) .catch(function (err) { _throwError('Something went wrong while sending a screenshot to the VisualReview server. ' + err); }); }); }.bind(this)); }
javascript
function takeScreenshot (name) { if(_disabled) { return q.resolve(); } return browser.driver.controlFlow().execute(function () { return q.all([_getProperties(browser), _getMetaData(browser), browser.takeScreenshot(), _readRunIdFile()]).then(function (results) { var properties = results[0], metaData = results[1], compareSettings = _compareSettingsFn, png = results[2], run = results[3]; if (!run || !run.run_id) { _throwError('VisualReview-protractor: Could not send screenshot to VisualReview server, could not find any run ID. Was initRun called before starting this test? See VisualReview-protractor\'s documentation for more details on how to set this up.'); } return _client.sendScreenshot(name, run.run_id, metaData, properties, compareSettings, png) .catch(function (err) { _throwError('Something went wrong while sending a screenshot to the VisualReview server. ' + err); }); }); }.bind(this)); }
[ "function", "takeScreenshot", "(", "name", ")", "{", "if", "(", "_disabled", ")", "{", "return", "q", ".", "resolve", "(", ")", ";", "}", "return", "browser", ".", "driver", ".", "controlFlow", "(", ")", ".", "execute", "(", "function", "(", ")", "{", "return", "q", ".", "all", "(", "[", "_getProperties", "(", "browser", ")", ",", "_getMetaData", "(", "browser", ")", ",", "browser", ".", "takeScreenshot", "(", ")", ",", "_readRunIdFile", "(", ")", "]", ")", ".", "then", "(", "function", "(", "results", ")", "{", "var", "properties", "=", "results", "[", "0", "]", ",", "metaData", "=", "results", "[", "1", "]", ",", "compareSettings", "=", "_compareSettingsFn", ",", "png", "=", "results", "[", "2", "]", ",", "run", "=", "results", "[", "3", "]", ";", "if", "(", "!", "run", "||", "!", "run", ".", "run_id", ")", "{", "_throwError", "(", "'VisualReview-protractor: Could not send screenshot to VisualReview server, could not find any run ID. Was initRun called before starting this test? See VisualReview-protractor\\'s documentation for more details on how to set this up.'", ")", ";", "}", "return", "_client", ".", "sendScreenshot", "(", "name", ",", "run", ".", "run_id", ",", "metaData", ",", "properties", ",", "compareSettings", ",", "png", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "_throwError", "(", "'Something went wrong while sending a screenshot to the VisualReview server. '", "+", "err", ")", ";", "}", ")", ";", "}", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Instructs Protractor to create a screenshot of the current browser and sends it to the VisualReview server. @param name the screenshot's name. @returns {Promise}
[ "Instructs", "Protractor", "to", "create", "a", "screenshot", "of", "the", "current", "browser", "and", "sends", "it", "to", "the", "VisualReview", "server", "." ]
64412828140b2cb76e441cabf720b0d31bf5a631
https://github.com/xebia/VisualReview-protractor/blob/64412828140b2cb76e441cabf720b0d31bf5a631/visualreview-protractor.js#L78-L102
18,820
xebia/VisualReview-protractor
visualreview-protractor.js
cleanup
function cleanup (exitCode) { if(_disabled) { return q.resolve(); } var defer = q.defer(); _readRunIdFile().then(function (run) { _logMessage('test finished. Your results can be viewed at: ' + 'http://' + _hostname + ':' + _port + '/#/' + run.project_id + '/' + run.suite_id + '/' + run.run_id + '/rp'); fs.unlink(RUN_PID_FILE, function (err) { if (err) { defer.reject(err); } else { defer.resolve(); } }); }); return defer.promise; }
javascript
function cleanup (exitCode) { if(_disabled) { return q.resolve(); } var defer = q.defer(); _readRunIdFile().then(function (run) { _logMessage('test finished. Your results can be viewed at: ' + 'http://' + _hostname + ':' + _port + '/#/' + run.project_id + '/' + run.suite_id + '/' + run.run_id + '/rp'); fs.unlink(RUN_PID_FILE, function (err) { if (err) { defer.reject(err); } else { defer.resolve(); } }); }); return defer.promise; }
[ "function", "cleanup", "(", "exitCode", ")", "{", "if", "(", "_disabled", ")", "{", "return", "q", ".", "resolve", "(", ")", ";", "}", "var", "defer", "=", "q", ".", "defer", "(", ")", ";", "_readRunIdFile", "(", ")", ".", "then", "(", "function", "(", "run", ")", "{", "_logMessage", "(", "'test finished. Your results can be viewed at: '", "+", "'http://'", "+", "_hostname", "+", "':'", "+", "_port", "+", "'/#/'", "+", "run", ".", "project_id", "+", "'/'", "+", "run", ".", "suite_id", "+", "'/'", "+", "run", ".", "run_id", "+", "'/rp'", ")", ";", "fs", ".", "unlink", "(", "RUN_PID_FILE", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "defer", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "defer", ".", "resolve", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "return", "defer", ".", "promise", ";", "}" ]
Cleans up any created temporary files. Call this in Protractor's afterLaunch configuration function. @param exitCode Protractor's exit code, used to indicate if the test run generated errors. @returns {Promise}
[ "Cleans", "up", "any", "created", "temporary", "files", ".", "Call", "this", "in", "Protractor", "s", "afterLaunch", "configuration", "function", "." ]
64412828140b2cb76e441cabf720b0d31bf5a631
https://github.com/xebia/VisualReview-protractor/blob/64412828140b2cb76e441cabf720b0d31bf5a631/visualreview-protractor.js#L110-L130
18,821
7eggs/node-druid-query
lib/fields/extractionFunction.js
extractionFunction
function extractionFunction(type) { if (utils.isObject(type)) { return type } else if (!fns.hasOwnProperty(type)) { throw new FieldError('Unknown DimExtractionFn type: ' + type) } var args = utils.args(arguments, 1) , fn = { type: type } fns[type].apply(fn, args) return fn }
javascript
function extractionFunction(type) { if (utils.isObject(type)) { return type } else if (!fns.hasOwnProperty(type)) { throw new FieldError('Unknown DimExtractionFn type: ' + type) } var args = utils.args(arguments, 1) , fn = { type: type } fns[type].apply(fn, args) return fn }
[ "function", "extractionFunction", "(", "type", ")", "{", "if", "(", "utils", ".", "isObject", "(", "type", ")", ")", "{", "return", "type", "}", "else", "if", "(", "!", "fns", ".", "hasOwnProperty", "(", "type", ")", ")", "{", "throw", "new", "FieldError", "(", "'Unknown DimExtractionFn type: '", "+", "type", ")", "}", "var", "args", "=", "utils", ".", "args", "(", "arguments", ",", "1", ")", ",", "fn", "=", "{", "type", ":", "type", "}", "fns", "[", "type", "]", ".", "apply", "(", "fn", ",", "args", ")", "return", "fn", "}" ]
Generate dimension extraction function object @see http://druid.io/docs/0.6.121/DimensionSpecs.html @see {extractionFunctions} @param {string|object} type Extraction function type @param {...*} arguments Extraction-specific arguments @returns {object} Best extraction function object ever
[ "Generate", "dimension", "extraction", "function", "object" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/extractionFunction.js#L21-L37
18,822
7eggs/node-druid-query
lib/query.js
loadFields
function loadFields(list, callback) { list.forEach(loadMethods) function loadMethods(field) { var module = require('./fields/' + field + '.js') , methods if (typeof module === 'function' || typeof module === 'string') { methods = {} methods[field] = module } else { methods = module } callback(methods) } }
javascript
function loadFields(list, callback) { list.forEach(loadMethods) function loadMethods(field) { var module = require('./fields/' + field + '.js') , methods if (typeof module === 'function' || typeof module === 'string') { methods = {} methods[field] = module } else { methods = module } callback(methods) } }
[ "function", "loadFields", "(", "list", ",", "callback", ")", "{", "list", ".", "forEach", "(", "loadMethods", ")", "function", "loadMethods", "(", "field", ")", "{", "var", "module", "=", "require", "(", "'./fields/'", "+", "field", "+", "'.js'", ")", ",", "methods", "if", "(", "typeof", "module", "===", "'function'", "||", "typeof", "module", "===", "'string'", ")", "{", "methods", "=", "{", "}", "methods", "[", "field", "]", "=", "module", "}", "else", "{", "methods", "=", "module", "}", "callback", "(", "methods", ")", "}", "}" ]
Load fields setters @param {string[]} list List of fields @param {function} callback Accepts arguments: (methods)
[ "Load", "fields", "setters" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/query.js#L19-L36
18,823
7eggs/node-druid-query
lib/query.js
Query
function Query(client, rawQuery) { if (client) { /** * If set, query is attached to given client instance * * @private * @type {Druid|Client} */ this.client = client } /** * Actual query object * * @private */ this._query = { queryType: this._queryType } if (rawQuery) { // we do not want to change query type, aren't we? this._queryType && delete rawQuery.queryType assign(this._query, rawQuery) } }
javascript
function Query(client, rawQuery) { if (client) { /** * If set, query is attached to given client instance * * @private * @type {Druid|Client} */ this.client = client } /** * Actual query object * * @private */ this._query = { queryType: this._queryType } if (rawQuery) { // we do not want to change query type, aren't we? this._queryType && delete rawQuery.queryType assign(this._query, rawQuery) } }
[ "function", "Query", "(", "client", ",", "rawQuery", ")", "{", "if", "(", "client", ")", "{", "/**\n * If set, query is attached to given client instance\n *\n * @private\n * @type {Druid|Client}\n */", "this", ".", "client", "=", "client", "}", "/**\n * Actual query object\n *\n * @private\n */", "this", ".", "_query", "=", "{", "queryType", ":", "this", ".", "_queryType", "}", "if", "(", "rawQuery", ")", "{", "// we do not want to change query type, aren't we?", "this", ".", "_queryType", "&&", "delete", "rawQuery", ".", "queryType", "assign", "(", "this", ".", "_query", ",", "rawQuery", ")", "}", "}" ]
Druid query representation @class @constructor @param {Druid|Client} client Client instance @param {object} [rawQuery] Raw query data
[ "Druid", "query", "representation" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/query.js#L57-L84
18,824
7eggs/node-druid-query
lib/fields/aggregations.js
aggregation
function aggregation(type, name) { if (utils.isObject(type)) { return type } if (!name) { throw new FieldError('Missing aggregation output name') } else if (!aggregations.hasOwnProperty(type)) { throw new FieldError('Unknown aggregation type: ' + type) } var args = utils.args(arguments, 2) , aggregation = { type: type, name: name } aggregations[type].apply(aggregation, args) return aggregation }
javascript
function aggregation(type, name) { if (utils.isObject(type)) { return type } if (!name) { throw new FieldError('Missing aggregation output name') } else if (!aggregations.hasOwnProperty(type)) { throw new FieldError('Unknown aggregation type: ' + type) } var args = utils.args(arguments, 2) , aggregation = { type: type, name: name } aggregations[type].apply(aggregation, args) return aggregation }
[ "function", "aggregation", "(", "type", ",", "name", ")", "{", "if", "(", "utils", ".", "isObject", "(", "type", ")", ")", "{", "return", "type", "}", "if", "(", "!", "name", ")", "{", "throw", "new", "FieldError", "(", "'Missing aggregation output name'", ")", "}", "else", "if", "(", "!", "aggregations", ".", "hasOwnProperty", "(", "type", ")", ")", "{", "throw", "new", "FieldError", "(", "'Unknown aggregation type: '", "+", "type", ")", "}", "var", "args", "=", "utils", ".", "args", "(", "arguments", ",", "2", ")", ",", "aggregation", "=", "{", "type", ":", "type", ",", "name", ":", "name", "}", "aggregations", "[", "type", "]", ".", "apply", "(", "aggregation", ",", "args", ")", "return", "aggregation", "}" ]
Generate aggregation object @param {string|object} type Aggregation type or aggregation object @param {string} name Name of aggregated value @returns {object} Omg, it's aggregation JS object.
[ "Generate", "aggregation", "object" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/aggregations.js#L42-L63
18,825
7eggs/node-druid-query
lib/druid.js
asyncMap
function asyncMap(array, iterator, done) { if (!array || !array.length) { return done(null, []) } var error , out = [] , todo = array.length array.forEach(exec) function exec(item) { process.nextTick(function tick() { iterator(item, add) }) } function add(err, data) { if (error) { return } else if (err) { error = true return done(err) } out.push(data) if (--todo === 0) { done(null, out) } } }
javascript
function asyncMap(array, iterator, done) { if (!array || !array.length) { return done(null, []) } var error , out = [] , todo = array.length array.forEach(exec) function exec(item) { process.nextTick(function tick() { iterator(item, add) }) } function add(err, data) { if (error) { return } else if (err) { error = true return done(err) } out.push(data) if (--todo === 0) { done(null, out) } } }
[ "function", "asyncMap", "(", "array", ",", "iterator", ",", "done", ")", "{", "if", "(", "!", "array", "||", "!", "array", ".", "length", ")", "{", "return", "done", "(", "null", ",", "[", "]", ")", "}", "var", "error", ",", "out", "=", "[", "]", ",", "todo", "=", "array", ".", "length", "array", ".", "forEach", "(", "exec", ")", "function", "exec", "(", "item", ")", "{", "process", ".", "nextTick", "(", "function", "tick", "(", ")", "{", "iterator", "(", "item", ",", "add", ")", "}", ")", "}", "function", "add", "(", "err", ",", "data", ")", "{", "if", "(", "error", ")", "{", "return", "}", "else", "if", "(", "err", ")", "{", "error", "=", "true", "return", "done", "(", "err", ")", "}", "out", ".", "push", "(", "data", ")", "if", "(", "--", "todo", "===", "0", ")", "{", "done", "(", "null", ",", "out", ")", "}", "}", "}" ]
Works like async.map @param array @param iterator @param done
[ "Works", "like", "async", ".", "map" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/druid.js#L28-L60
18,826
7eggs/node-druid-query
lib/druid.js
getLessLoaded
function getLessLoaded(client, dataSource) { var ids = client.dataSources[dataSource] , nodes , node nodes = ids.map(id2client) function id2client(id) { return client.nodes[id] } node = nodes.reduce(lessLoaded) function lessLoaded(nodeA, nodeB) { if (nodeA.active < nodeB.active) { return nodeA } else { return nodeB } } return node }
javascript
function getLessLoaded(client, dataSource) { var ids = client.dataSources[dataSource] , nodes , node nodes = ids.map(id2client) function id2client(id) { return client.nodes[id] } node = nodes.reduce(lessLoaded) function lessLoaded(nodeA, nodeB) { if (nodeA.active < nodeB.active) { return nodeA } else { return nodeB } } return node }
[ "function", "getLessLoaded", "(", "client", ",", "dataSource", ")", "{", "var", "ids", "=", "client", ".", "dataSources", "[", "dataSource", "]", ",", "nodes", ",", "node", "nodes", "=", "ids", ".", "map", "(", "id2client", ")", "function", "id2client", "(", "id", ")", "{", "return", "client", ".", "nodes", "[", "id", "]", "}", "node", "=", "nodes", ".", "reduce", "(", "lessLoaded", ")", "function", "lessLoaded", "(", "nodeA", ",", "nodeB", ")", "{", "if", "(", "nodeA", ".", "active", "<", "nodeB", ".", "active", ")", "{", "return", "nodeA", "}", "else", "{", "return", "nodeB", "}", "}", "return", "node", "}" ]
Bad-ass load-balancing @param {Druid} client Client instance @param {string} dataSource Data source name @returns {DruidNode}
[ "Bad", "-", "ass", "load", "-", "balancing" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/druid.js#L100-L123
18,827
7eggs/node-druid-query
lib/druid.js
getNodeData
function getNodeData(client, id, callback) { var path = client.discoveryPath + '/' + id , preferSSL = client.options.preferSSL client.zk.getData(path, handleData) function handleData(err, jsonBuffer) { if (err) { return callback(new DruidError('Error getting node data', err)) } debug('ZooKeeper data for path ' + path + ': ' + jsonBuffer) var data , proto , port try { data = JSON.parse(jsonBuffer.toString('utf8')) } catch (ex) { return callback(ex) } if (preferSSL && data.sslPort) { proto = 'https' port = data.sslPort } else { proto = 'http' port = data.port } data.path = path data.url = util.format('%s://%s:%s', proto, data.address, port) getDataSources(data, callback) } }
javascript
function getNodeData(client, id, callback) { var path = client.discoveryPath + '/' + id , preferSSL = client.options.preferSSL client.zk.getData(path, handleData) function handleData(err, jsonBuffer) { if (err) { return callback(new DruidError('Error getting node data', err)) } debug('ZooKeeper data for path ' + path + ': ' + jsonBuffer) var data , proto , port try { data = JSON.parse(jsonBuffer.toString('utf8')) } catch (ex) { return callback(ex) } if (preferSSL && data.sslPort) { proto = 'https' port = data.sslPort } else { proto = 'http' port = data.port } data.path = path data.url = util.format('%s://%s:%s', proto, data.address, port) getDataSources(data, callback) } }
[ "function", "getNodeData", "(", "client", ",", "id", ",", "callback", ")", "{", "var", "path", "=", "client", ".", "discoveryPath", "+", "'/'", "+", "id", ",", "preferSSL", "=", "client", ".", "options", ".", "preferSSL", "client", ".", "zk", ".", "getData", "(", "path", ",", "handleData", ")", "function", "handleData", "(", "err", ",", "jsonBuffer", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "new", "DruidError", "(", "'Error getting node data'", ",", "err", ")", ")", "}", "debug", "(", "'ZooKeeper data for path '", "+", "path", "+", "': '", "+", "jsonBuffer", ")", "var", "data", ",", "proto", ",", "port", "try", "{", "data", "=", "JSON", ".", "parse", "(", "jsonBuffer", ".", "toString", "(", "'utf8'", ")", ")", "}", "catch", "(", "ex", ")", "{", "return", "callback", "(", "ex", ")", "}", "if", "(", "preferSSL", "&&", "data", ".", "sslPort", ")", "{", "proto", "=", "'https'", "port", "=", "data", ".", "sslPort", "}", "else", "{", "proto", "=", "'http'", "port", "=", "data", ".", "port", "}", "data", ".", "path", "=", "path", "data", ".", "url", "=", "util", ".", "format", "(", "'%s://%s:%s'", ",", "proto", ",", "data", ".", "address", ",", "port", ")", "getDataSources", "(", "data", ",", "callback", ")", "}", "}" ]
Get Druid node data from ZooKeeper and list of data sources @private @param {Druid} client Client instance @param {string} id Druid Node ID @param {function} callback Accepts arguments: (err, nodeData)
[ "Get", "Druid", "node", "data", "from", "ZooKeeper", "and", "list", "of", "data", "sources" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/druid.js#L136-L174
18,828
7eggs/node-druid-query
lib/druid.js
initZookeeper
function initZookeeper(client, connectionString) { var zk = zookeeper.createClient(connectionString, client.options.zookeeper) var error = false var connected = false client.ready = false client.zk = zk zk.connect() zk.on('connected', onconnected) zk.on('expired', setError) zk.on('authenticationFailed', setError) zk.on('disconnected', ondisconnected) zk.on('error', onerror) function onconnected() { if (!connected) { connected = true; client.updateBrokerList() } error = false; } function setError() { error = true; } function ondisconnected() { if (client.closed) { return } debug('Lost connection with ZooKeeper. Reconnecting...'); if (error) { zk.removeListener('error', onerror) zk.removeListener('disconnected', ondisconnected) zk.removeListener('expired', setError) zk.removeListener('authenticationFailed', setError) zk.close() initZookeeper(client, connectionString); } } function onerror(err) { client.emit('error', err) } }
javascript
function initZookeeper(client, connectionString) { var zk = zookeeper.createClient(connectionString, client.options.zookeeper) var error = false var connected = false client.ready = false client.zk = zk zk.connect() zk.on('connected', onconnected) zk.on('expired', setError) zk.on('authenticationFailed', setError) zk.on('disconnected', ondisconnected) zk.on('error', onerror) function onconnected() { if (!connected) { connected = true; client.updateBrokerList() } error = false; } function setError() { error = true; } function ondisconnected() { if (client.closed) { return } debug('Lost connection with ZooKeeper. Reconnecting...'); if (error) { zk.removeListener('error', onerror) zk.removeListener('disconnected', ondisconnected) zk.removeListener('expired', setError) zk.removeListener('authenticationFailed', setError) zk.close() initZookeeper(client, connectionString); } } function onerror(err) { client.emit('error', err) } }
[ "function", "initZookeeper", "(", "client", ",", "connectionString", ")", "{", "var", "zk", "=", "zookeeper", ".", "createClient", "(", "connectionString", ",", "client", ".", "options", ".", "zookeeper", ")", "var", "error", "=", "false", "var", "connected", "=", "false", "client", ".", "ready", "=", "false", "client", ".", "zk", "=", "zk", "zk", ".", "connect", "(", ")", "zk", ".", "on", "(", "'connected'", ",", "onconnected", ")", "zk", ".", "on", "(", "'expired'", ",", "setError", ")", "zk", ".", "on", "(", "'authenticationFailed'", ",", "setError", ")", "zk", ".", "on", "(", "'disconnected'", ",", "ondisconnected", ")", "zk", ".", "on", "(", "'error'", ",", "onerror", ")", "function", "onconnected", "(", ")", "{", "if", "(", "!", "connected", ")", "{", "connected", "=", "true", ";", "client", ".", "updateBrokerList", "(", ")", "}", "error", "=", "false", ";", "}", "function", "setError", "(", ")", "{", "error", "=", "true", ";", "}", "function", "ondisconnected", "(", ")", "{", "if", "(", "client", ".", "closed", ")", "{", "return", "}", "debug", "(", "'Lost connection with ZooKeeper. Reconnecting...'", ")", ";", "if", "(", "error", ")", "{", "zk", ".", "removeListener", "(", "'error'", ",", "onerror", ")", "zk", ".", "removeListener", "(", "'disconnected'", ",", "ondisconnected", ")", "zk", ".", "removeListener", "(", "'expired'", ",", "setError", ")", "zk", ".", "removeListener", "(", "'authenticationFailed'", ",", "setError", ")", "zk", ".", "close", "(", ")", "initZookeeper", "(", "client", ",", "connectionString", ")", ";", "}", "}", "function", "onerror", "(", "err", ")", "{", "client", ".", "emit", "(", "'error'", ",", "err", ")", "}", "}" ]
Initiate ZooKeeper client @param {Druid} client @param {string} connectionString ZooKeeper connection string
[ "Initiate", "ZooKeeper", "client" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/druid.js#L185-L235
18,829
7eggs/node-druid-query
lib/druid.js
Druid
function Druid(connectionString, discoveryPath, options) { EventEmitter.call(this) this.setMaxListeners(0) if (arguments.length === 2) { options = {} } /** * Services discovery path * * @protected * @type {string} */ this.discoveryPath = discoveryPath /** * Client options * * @protected */ this.options = options /** * (Re)loaded info about nodes and datasources * * @public * @type {boolean} */ this.ready; /** * Nodes (id -> node) * * @protected */ this.nodes = {} /** * Nodes associated with each data source (dataSource -> [nodeA, nodeB, ..., nodeN]) * * @protected */ this.dataSources = {} /** * ZooKeeper client * * @protected */ initZookeeper(this, connectionString) }
javascript
function Druid(connectionString, discoveryPath, options) { EventEmitter.call(this) this.setMaxListeners(0) if (arguments.length === 2) { options = {} } /** * Services discovery path * * @protected * @type {string} */ this.discoveryPath = discoveryPath /** * Client options * * @protected */ this.options = options /** * (Re)loaded info about nodes and datasources * * @public * @type {boolean} */ this.ready; /** * Nodes (id -> node) * * @protected */ this.nodes = {} /** * Nodes associated with each data source (dataSource -> [nodeA, nodeB, ..., nodeN]) * * @protected */ this.dataSources = {} /** * ZooKeeper client * * @protected */ initZookeeper(this, connectionString) }
[ "function", "Druid", "(", "connectionString", ",", "discoveryPath", ",", "options", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", "this", ".", "setMaxListeners", "(", "0", ")", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "options", "=", "{", "}", "}", "/**\n * Services discovery path\n *\n * @protected\n * @type {string}\n */", "this", ".", "discoveryPath", "=", "discoveryPath", "/**\n * Client options\n *\n * @protected\n */", "this", ".", "options", "=", "options", "/**\n * (Re)loaded info about nodes and datasources\n *\n * @public\n * @type {boolean}\n */", "this", ".", "ready", ";", "/**\n * Nodes (id -> node)\n *\n * @protected\n */", "this", ".", "nodes", "=", "{", "}", "/**\n * Nodes associated with each data source (dataSource -> [nodeA, nodeB, ..., nodeN])\n *\n * @protected\n */", "this", ".", "dataSources", "=", "{", "}", "/**\n * ZooKeeper client\n *\n * @protected\n */", "initZookeeper", "(", "this", ",", "connectionString", ")", "}" ]
Druid client relying on ZooKeeper nodes data @constructor @extends EventEmitter @param {string} connectionString ZooKeeper connection string @param {string} discoveryPath Nodes discovery path @param {object} [options] node-zookeeper-client options @param {boolean} [options.preferSSL] Prefer SSL connection to Druid nodes if available @param {boolean} [options.zookeeper] node-zookeeper-client createClient() options
[ "Druid", "client", "relying", "on", "ZooKeeper", "nodes", "data" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/druid.js#L314-L371
18,830
7eggs/node-druid-query
lib/fields/filter.js
filter
function filter(type) { if (utils.isObject(type)) { return type } else if (!filters.hasOwnProperty(type)) { throw new FieldError('Bad filter type: ' + type) } var args = utils.args(arguments, 1) , filter = { type: type } filters[type].apply(filter, args) return filter }
javascript
function filter(type) { if (utils.isObject(type)) { return type } else if (!filters.hasOwnProperty(type)) { throw new FieldError('Bad filter type: ' + type) } var args = utils.args(arguments, 1) , filter = { type: type } filters[type].apply(filter, args) return filter }
[ "function", "filter", "(", "type", ")", "{", "if", "(", "utils", ".", "isObject", "(", "type", ")", ")", "{", "return", "type", "}", "else", "if", "(", "!", "filters", ".", "hasOwnProperty", "(", "type", ")", ")", "{", "throw", "new", "FieldError", "(", "'Bad filter type: '", "+", "type", ")", "}", "var", "args", "=", "utils", ".", "args", "(", "arguments", ",", "1", ")", ",", "filter", "=", "{", "type", ":", "type", "}", "filters", "[", "type", "]", ".", "apply", "(", "filter", ",", "args", ")", "return", "filter", "}" ]
Generate query filter object @param {string|object} type Filter type or ready filter object @returns {object} Brand new ready to use filter!
[ "Generate", "query", "filter", "object" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/filter.js#L18-L34
18,831
7eggs/node-druid-query
lib/fields/dataSource.js
dataSource
function dataSource(type) { if (arguments.length === 1 && (utils.isObject(type) || typeof type === 'string')) { return type } else if (!ds.hasOwnProperty(type)) { throw new FieldError('Unknown data source type: ' + type) } var args = utils.args(arguments, 1) , dataSource = { type: type } ds[type].apply(dataSource, args) return dataSource }
javascript
function dataSource(type) { if (arguments.length === 1 && (utils.isObject(type) || typeof type === 'string')) { return type } else if (!ds.hasOwnProperty(type)) { throw new FieldError('Unknown data source type: ' + type) } var args = utils.args(arguments, 1) , dataSource = { type: type } ds[type].apply(dataSource, args) return dataSource }
[ "function", "dataSource", "(", "type", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", "&&", "(", "utils", ".", "isObject", "(", "type", ")", "||", "typeof", "type", "===", "'string'", ")", ")", "{", "return", "type", "}", "else", "if", "(", "!", "ds", ".", "hasOwnProperty", "(", "type", ")", ")", "{", "throw", "new", "FieldError", "(", "'Unknown data source type: '", "+", "type", ")", "}", "var", "args", "=", "utils", ".", "args", "(", "arguments", ",", "1", ")", ",", "dataSource", "=", "{", "type", ":", "type", "}", "ds", "[", "type", "]", ".", "apply", "(", "dataSource", ",", "args", ")", "return", "dataSource", "}" ]
Set data source @param {string} type Data source as string or as object. Or data source type @param {...*} args Arguments specific to each data source type
[ "Set", "data", "source" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/dataSource.js#L18-L34
18,832
7eggs/node-druid-query
lib/fields/orderBy.js
orderBy
function orderBy(dimension, direction) { if (arguments.length === 1) { direction = 'ASCENDING' } if (!dimension) { throw new FieldError('Dimension is not specified') } else if (!~['ascending', 'descending'].indexOf(direction.toLowerCase())) { throw new FieldError('Bad orderBy direction: ' + direction) } return { dimension: dimension, direction: direction } }
javascript
function orderBy(dimension, direction) { if (arguments.length === 1) { direction = 'ASCENDING' } if (!dimension) { throw new FieldError('Dimension is not specified') } else if (!~['ascending', 'descending'].indexOf(direction.toLowerCase())) { throw new FieldError('Bad orderBy direction: ' + direction) } return { dimension: dimension, direction: direction } }
[ "function", "orderBy", "(", "dimension", ",", "direction", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "direction", "=", "'ASCENDING'", "}", "if", "(", "!", "dimension", ")", "{", "throw", "new", "FieldError", "(", "'Dimension is not specified'", ")", "}", "else", "if", "(", "!", "~", "[", "'ascending'", ",", "'descending'", "]", ".", "indexOf", "(", "direction", ".", "toLowerCase", "(", ")", ")", ")", "{", "throw", "new", "FieldError", "(", "'Bad orderBy direction: '", "+", "direction", ")", "}", "return", "{", "dimension", ":", "dimension", ",", "direction", ":", "direction", "}", "}" ]
Set orderBy spec @param {string} dimension Dimension to sort by @param {string} direction Sorting direction @returns {object}
[ "Set", "orderBy", "spec" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/orderBy.js#L17-L33
18,833
7eggs/node-druid-query
lib/fields/sort.js
sort
function sort(type) { if (!~SORT_TYPES.indexOf(type)) { throw new FieldError('Sorting type can be ' + SORT_TYPES.join(' or ')) } return { type: type } }
javascript
function sort(type) { if (!~SORT_TYPES.indexOf(type)) { throw new FieldError('Sorting type can be ' + SORT_TYPES.join(' or ')) } return { type: type } }
[ "function", "sort", "(", "type", ")", "{", "if", "(", "!", "~", "SORT_TYPES", ".", "indexOf", "(", "type", ")", ")", "{", "throw", "new", "FieldError", "(", "'Sorting type can be '", "+", "SORT_TYPES", ".", "join", "(", "' or '", ")", ")", "}", "return", "{", "type", ":", "type", "}", "}" ]
Set sort field @see http://druid.io/docs/0.6.121/SearchQuerySpec.html @param {string} type Sort type @returns {object}
[ "Set", "sort", "field" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/sort.js#L19-L27
18,834
7eggs/node-druid-query
lib/fields/dimension.js
dimension
function dimension(dimension, outputName, fn) { if (!dimension) { throw new FieldError('At least dimension must be specified') } if (arguments.length === 1 && typeof dimension === 'object') { return dimension } if (arguments.length === 1) { return { type: 'default', dimension: dimension } } else if (arguments.length === 2 && typeof outputName !== 'object') { return { type: 'default', dimension: dimension, outputName: outputName } } else if (arguments.length === 2) { fn = outputName return { type: 'extraction', dimension: dimension, dimExtractionFn: fn } } else if (arguments.length === 3) { return { type: 'extraction', dimension: dimension, outputName: outputName, dimExtractionFn: fn } } else { throw new FieldError('Bad arguments number: ' + arguments.length) } }
javascript
function dimension(dimension, outputName, fn) { if (!dimension) { throw new FieldError('At least dimension must be specified') } if (arguments.length === 1 && typeof dimension === 'object') { return dimension } if (arguments.length === 1) { return { type: 'default', dimension: dimension } } else if (arguments.length === 2 && typeof outputName !== 'object') { return { type: 'default', dimension: dimension, outputName: outputName } } else if (arguments.length === 2) { fn = outputName return { type: 'extraction', dimension: dimension, dimExtractionFn: fn } } else if (arguments.length === 3) { return { type: 'extraction', dimension: dimension, outputName: outputName, dimExtractionFn: fn } } else { throw new FieldError('Bad arguments number: ' + arguments.length) } }
[ "function", "dimension", "(", "dimension", ",", "outputName", ",", "fn", ")", "{", "if", "(", "!", "dimension", ")", "{", "throw", "new", "FieldError", "(", "'At least dimension must be specified'", ")", "}", "if", "(", "arguments", ".", "length", "===", "1", "&&", "typeof", "dimension", "===", "'object'", ")", "{", "return", "dimension", "}", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "return", "{", "type", ":", "'default'", ",", "dimension", ":", "dimension", "}", "}", "else", "if", "(", "arguments", ".", "length", "===", "2", "&&", "typeof", "outputName", "!==", "'object'", ")", "{", "return", "{", "type", ":", "'default'", ",", "dimension", ":", "dimension", ",", "outputName", ":", "outputName", "}", "}", "else", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "fn", "=", "outputName", "return", "{", "type", ":", "'extraction'", ",", "dimension", ":", "dimension", ",", "dimExtractionFn", ":", "fn", "}", "}", "else", "if", "(", "arguments", ".", "length", "===", "3", ")", "{", "return", "{", "type", ":", "'extraction'", ",", "dimension", ":", "dimension", ",", "outputName", ":", "outputName", ",", "dimExtractionFn", ":", "fn", "}", "}", "else", "{", "throw", "new", "FieldError", "(", "'Bad arguments number: '", "+", "arguments", ".", "length", ")", "}", "}" ]
Set dimension spec Depending on arguments length creates default or extraction dimension spec. If second or third argument is object ExtractionDimensionSpec is created. In other cases DefaultDimensionSpec is created. @see http://druid.io/docs/0.6.121/DimensionSpecs.html @param {string|object} dimension Dimension name or dimension object @param {string} [outputName] Renamed name @param {object} [fn] Extraction function object @returns {object}
[ "Set", "dimension", "spec" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/dimension.js#L25-L67
18,835
7eggs/node-druid-query
lib/fields/query.js
query
function query(type, value, caseSensitive) { if (utils.isObject(type)) { return type } else if (!type || !value) { throw new FieldError('Type or value is not specified') } // InsensitiveContainsSearchQuerySpec else if (type === 'insensitive_contains') { return { type: 'insensitive_contains', value: value + '' } } // FragmentSearchQuerySpec else if (type === 'fragment') { if (!Array.isArray(value)) { throw new FieldError('value is not an array') } return { type: 'fragment', values: value, caseSensitive: caseSensitive || false } } else if (type === 'contains') { return { type: 'contains', value: value + '', caseSensitive: caseSensitive || false } } else { throw new FieldError('Bad SearchQuerySpec type: ' + type) } }
javascript
function query(type, value, caseSensitive) { if (utils.isObject(type)) { return type } else if (!type || !value) { throw new FieldError('Type or value is not specified') } // InsensitiveContainsSearchQuerySpec else if (type === 'insensitive_contains') { return { type: 'insensitive_contains', value: value + '' } } // FragmentSearchQuerySpec else if (type === 'fragment') { if (!Array.isArray(value)) { throw new FieldError('value is not an array') } return { type: 'fragment', values: value, caseSensitive: caseSensitive || false } } else if (type === 'contains') { return { type: 'contains', value: value + '', caseSensitive: caseSensitive || false } } else { throw new FieldError('Bad SearchQuerySpec type: ' + type) } }
[ "function", "query", "(", "type", ",", "value", ",", "caseSensitive", ")", "{", "if", "(", "utils", ".", "isObject", "(", "type", ")", ")", "{", "return", "type", "}", "else", "if", "(", "!", "type", "||", "!", "value", ")", "{", "throw", "new", "FieldError", "(", "'Type or value is not specified'", ")", "}", "// InsensitiveContainsSearchQuerySpec", "else", "if", "(", "type", "===", "'insensitive_contains'", ")", "{", "return", "{", "type", ":", "'insensitive_contains'", ",", "value", ":", "value", "+", "''", "}", "}", "// FragmentSearchQuerySpec", "else", "if", "(", "type", "===", "'fragment'", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "value", ")", ")", "{", "throw", "new", "FieldError", "(", "'value is not an array'", ")", "}", "return", "{", "type", ":", "'fragment'", ",", "values", ":", "value", ",", "caseSensitive", ":", "caseSensitive", "||", "false", "}", "}", "else", "if", "(", "type", "===", "'contains'", ")", "{", "return", "{", "type", ":", "'contains'", ",", "value", ":", "value", "+", "''", ",", "caseSensitive", ":", "caseSensitive", "||", "false", "}", "}", "else", "{", "throw", "new", "FieldError", "(", "'Bad SearchQuerySpec type: '", "+", "type", ")", "}", "}" ]
Set search-query spec @see http://druid.io/docs/0.6.121/SearchQuerySpec.html @param {string|object} type Query spec type @param {string|string[]} value Value or array of fragments @param {boolean} caseSensitive Whether strings should be compared as case sensitive or not @returns {object}
[ "Set", "search", "-", "query", "spec" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/query.js#L20-L57
18,836
7eggs/node-druid-query
lib/fields/limitSpec.js
limitSpec
function limitSpec(type, limit, orderByColumns) { if (utils.isObject(type)) { return type } if (typeof limit !== 'number') { limit = parseInt(limit, 10) } if (type !== 'default') { throw new FieldError('Currently only DefaultLimitSpec is supported') } else if (isNaN(limit)) { throw new FieldTypeError('limitSpec.limit', 'number') } else if (!Array.isArray(orderByColumns)) { throw new FieldTypeError('limitSpec.columns', 'array') } return { type: type, limit: parseInt(limit, 10), columns: orderByColumns } }
javascript
function limitSpec(type, limit, orderByColumns) { if (utils.isObject(type)) { return type } if (typeof limit !== 'number') { limit = parseInt(limit, 10) } if (type !== 'default') { throw new FieldError('Currently only DefaultLimitSpec is supported') } else if (isNaN(limit)) { throw new FieldTypeError('limitSpec.limit', 'number') } else if (!Array.isArray(orderByColumns)) { throw new FieldTypeError('limitSpec.columns', 'array') } return { type: type, limit: parseInt(limit, 10), columns: orderByColumns } }
[ "function", "limitSpec", "(", "type", ",", "limit", ",", "orderByColumns", ")", "{", "if", "(", "utils", ".", "isObject", "(", "type", ")", ")", "{", "return", "type", "}", "if", "(", "typeof", "limit", "!==", "'number'", ")", "{", "limit", "=", "parseInt", "(", "limit", ",", "10", ")", "}", "if", "(", "type", "!==", "'default'", ")", "{", "throw", "new", "FieldError", "(", "'Currently only DefaultLimitSpec is supported'", ")", "}", "else", "if", "(", "isNaN", "(", "limit", ")", ")", "{", "throw", "new", "FieldTypeError", "(", "'limitSpec.limit'", ",", "'number'", ")", "}", "else", "if", "(", "!", "Array", ".", "isArray", "(", "orderByColumns", ")", ")", "{", "throw", "new", "FieldTypeError", "(", "'limitSpec.columns'", ",", "'array'", ")", "}", "return", "{", "type", ":", "type", ",", "limit", ":", "parseInt", "(", "limit", ",", "10", ")", ",", "columns", ":", "orderByColumns", "}", "}" ]
Set limit spec @see http://druid.io/docs/0.6.120/LimitSpec.html @param {string|object} [type=default] Type of LimitSpec or LimitSpec object @param {number} [limit] Limit of records @param {object[]} [orderByColumns] Sorting columns returns {object}
[ "Set", "limit", "spec" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/limitSpec.js#L22-L46
18,837
7eggs/node-druid-query
lib/fields/context.js
context
function context(value) { var out = {} value = value || {} ;['priority', 'timeout'].forEach(function eachIntKey(key) { if (value.hasOwnProperty(key)) { out[key] = parseInt(value[key], 10) if (isNaN(out[key])) { throw new FieldTypeError('context.' + key, 'number') } } }) if (value.hasOwnProperty('queryId')) { out.queryId = value.queryId + '' } ['bySegment', 'populateCache', 'useCache', 'finalize', 'skipEmptyBuckets'].forEach(function eachBoolKey(key) { if (value.hasOwnProperty(key)) { out[key] = !!((value[key]||false).valueOf()) } }) return out }
javascript
function context(value) { var out = {} value = value || {} ;['priority', 'timeout'].forEach(function eachIntKey(key) { if (value.hasOwnProperty(key)) { out[key] = parseInt(value[key], 10) if (isNaN(out[key])) { throw new FieldTypeError('context.' + key, 'number') } } }) if (value.hasOwnProperty('queryId')) { out.queryId = value.queryId + '' } ['bySegment', 'populateCache', 'useCache', 'finalize', 'skipEmptyBuckets'].forEach(function eachBoolKey(key) { if (value.hasOwnProperty(key)) { out[key] = !!((value[key]||false).valueOf()) } }) return out }
[ "function", "context", "(", "value", ")", "{", "var", "out", "=", "{", "}", "value", "=", "value", "||", "{", "}", ";", "[", "'priority'", ",", "'timeout'", "]", ".", "forEach", "(", "function", "eachIntKey", "(", "key", ")", "{", "if", "(", "value", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "out", "[", "key", "]", "=", "parseInt", "(", "value", "[", "key", "]", ",", "10", ")", "if", "(", "isNaN", "(", "out", "[", "key", "]", ")", ")", "{", "throw", "new", "FieldTypeError", "(", "'context.'", "+", "key", ",", "'number'", ")", "}", "}", "}", ")", "if", "(", "value", ".", "hasOwnProperty", "(", "'queryId'", ")", ")", "{", "out", ".", "queryId", "=", "value", ".", "queryId", "+", "''", "}", "[", "'bySegment'", ",", "'populateCache'", ",", "'useCache'", ",", "'finalize'", ",", "'skipEmptyBuckets'", "]", ".", "forEach", "(", "function", "eachBoolKey", "(", "key", ")", "{", "if", "(", "value", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "out", "[", "key", "]", "=", "!", "!", "(", "(", "value", "[", "key", "]", "||", "false", ")", ".", "valueOf", "(", ")", ")", "}", "}", ")", "return", "out", "}" ]
Set mystique context field value @param {object} value @returns {object}
[ "Set", "mystique", "context", "field", "value" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/context.js#L16-L43
18,838
7eggs/node-druid-query
lib/fields/postAggregations.js
postAggregation
function postAggregation(type, name) { if (utils.isObject(type)) { return type } if (!name) { throw new FieldError('Missing post-aggregation name') } else if (!postAggregations.hasOwnProperty(type)) { throw new FieldError('Unknown post-aggregation type: ' + type) } var args = utils.args(arguments, 2) , postAggregation = { type: type, name: name } postAggregations[type].apply(postAggregation, args) return postAggregation }
javascript
function postAggregation(type, name) { if (utils.isObject(type)) { return type } if (!name) { throw new FieldError('Missing post-aggregation name') } else if (!postAggregations.hasOwnProperty(type)) { throw new FieldError('Unknown post-aggregation type: ' + type) } var args = utils.args(arguments, 2) , postAggregation = { type: type, name: name } postAggregations[type].apply(postAggregation, args) return postAggregation }
[ "function", "postAggregation", "(", "type", ",", "name", ")", "{", "if", "(", "utils", ".", "isObject", "(", "type", ")", ")", "{", "return", "type", "}", "if", "(", "!", "name", ")", "{", "throw", "new", "FieldError", "(", "'Missing post-aggregation name'", ")", "}", "else", "if", "(", "!", "postAggregations", ".", "hasOwnProperty", "(", "type", ")", ")", "{", "throw", "new", "FieldError", "(", "'Unknown post-aggregation type: '", "+", "type", ")", "}", "var", "args", "=", "utils", ".", "args", "(", "arguments", ",", "2", ")", ",", "postAggregation", "=", "{", "type", ":", "type", ",", "name", ":", "name", "}", "postAggregations", "[", "type", "]", ".", "apply", "(", "postAggregation", ",", "args", ")", "return", "postAggregation", "}" ]
Generate post-aggregation object @param {string|object} type Post-aggregation type or post-aggregation object @param {string} name Name of aggregated value @returns {object} Dude, you know? It's a post-aggregation thing!
[ "Generate", "post", "-", "aggregation", "object" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/postAggregations.js#L42-L63
18,839
7eggs/node-druid-query
lib/fields/toInclude.js
toInclude
function toInclude(value) { if (Array.isArray(value)) { return { type: 'list', columns: value } } else if (typeof value === 'string' && (value === 'all' || value === 'none')) { return { type: value } } else if (utils.isObject(value)) { return value } else { throw new FieldError('Unknown toInclude value: ' + value) } }
javascript
function toInclude(value) { if (Array.isArray(value)) { return { type: 'list', columns: value } } else if (typeof value === 'string' && (value === 'all' || value === 'none')) { return { type: value } } else if (utils.isObject(value)) { return value } else { throw new FieldError('Unknown toInclude value: ' + value) } }
[ "function", "toInclude", "(", "value", ")", "{", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "return", "{", "type", ":", "'list'", ",", "columns", ":", "value", "}", "}", "else", "if", "(", "typeof", "value", "===", "'string'", "&&", "(", "value", "===", "'all'", "||", "value", "===", "'none'", ")", ")", "{", "return", "{", "type", ":", "value", "}", "}", "else", "if", "(", "utils", ".", "isObject", "(", "value", ")", ")", "{", "return", "value", "}", "else", "{", "throw", "new", "FieldError", "(", "'Unknown toInclude value: '", "+", "value", ")", "}", "}" ]
Set toInclude field @see http://druid.io/docs/0.6.121/SegmentMetadataQuery.html @param {string|string[]} value @returns {object}
[ "Set", "toInclude", "field" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/toInclude.js#L18-L36
18,840
7eggs/node-druid-query
lib/fields/interval.js
interval
function interval(start, end) { if (arguments.length === 1 && typeof start === 'string') { return start } else if (arguments.length === 2) { var interval = utils.args(arguments, 0) return interval.map(function(original) { var arg = utils.date(original) if (!arg) { throw new FieldError('Bad date specified: ' + original) } return JSON.stringify(arg).replace(/"/g, '') }).join('/') } else { throw new FieldError('Bad arguments') } }
javascript
function interval(start, end) { if (arguments.length === 1 && typeof start === 'string') { return start } else if (arguments.length === 2) { var interval = utils.args(arguments, 0) return interval.map(function(original) { var arg = utils.date(original) if (!arg) { throw new FieldError('Bad date specified: ' + original) } return JSON.stringify(arg).replace(/"/g, '') }).join('/') } else { throw new FieldError('Bad arguments') } }
[ "function", "interval", "(", "start", ",", "end", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", "&&", "typeof", "start", "===", "'string'", ")", "{", "return", "start", "}", "else", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "var", "interval", "=", "utils", ".", "args", "(", "arguments", ",", "0", ")", "return", "interval", ".", "map", "(", "function", "(", "original", ")", "{", "var", "arg", "=", "utils", ".", "date", "(", "original", ")", "if", "(", "!", "arg", ")", "{", "throw", "new", "FieldError", "(", "'Bad date specified: '", "+", "original", ")", "}", "return", "JSON", ".", "stringify", "(", "arg", ")", ".", "replace", "(", "/", "\"", "/", "g", ",", "''", ")", "}", ")", ".", "join", "(", "'/'", ")", "}", "else", "{", "throw", "new", "FieldError", "(", "'Bad arguments'", ")", "}", "}" ]
Generate interval string @param {string|number|Date} start Start time or interval string @param {string|number|Date} [end] End time @returns {string} Interval string
[ "Generate", "interval", "string" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/interval.js#L25-L45
18,841
7eggs/node-druid-query
lib/fields/having.js
having
function having(type) { if (utils.isObject(type)) { return type } else if (!specs.hasOwnProperty(type)) { throw new FieldError('Bad having type: ' + type) } var args = utils.args(arguments, 1) , having = { type: type } specs[type].apply(having, args) return having }
javascript
function having(type) { if (utils.isObject(type)) { return type } else if (!specs.hasOwnProperty(type)) { throw new FieldError('Bad having type: ' + type) } var args = utils.args(arguments, 1) , having = { type: type } specs[type].apply(having, args) return having }
[ "function", "having", "(", "type", ")", "{", "if", "(", "utils", ".", "isObject", "(", "type", ")", ")", "{", "return", "type", "}", "else", "if", "(", "!", "specs", ".", "hasOwnProperty", "(", "type", ")", ")", "{", "throw", "new", "FieldError", "(", "'Bad having type: '", "+", "type", ")", "}", "var", "args", "=", "utils", ".", "args", "(", "arguments", ",", "1", ")", ",", "having", "=", "{", "type", ":", "type", "}", "specs", "[", "type", "]", ".", "apply", "(", "having", ",", "args", ")", "return", "having", "}" ]
Generate Having field @see http://druid.io/docs/0.6.120/Having.html @param {string|object} type Filter type or ready filter object @returns {object} Brand new ready to use filter!
[ "Generate", "Having", "field" ]
03100683607e08acfce96c51218ce1c6d8620e86
https://github.com/7eggs/node-druid-query/blob/03100683607e08acfce96c51218ce1c6d8620e86/lib/fields/having.js#L19-L35
18,842
breakdance/breakdance
lib/tables.js
createBody
function createBody(ast) { if (util.hasType(ast, 'tbody')) return; var open = ast.nodes.shift(); var close = ast.nodes.pop(); var started; var nodes = []; var tbody; var len = ast.nodes.length; var idx = -1; while (++idx < len) { var node = ast.nodes[idx]; if (node.type === 'tr' && !started) { started = true; tbody = { type: 'tbody', nodes: [] }; define(tbody, 'parent', ast); nodes.push(tbody); } if (started) { define(node, 'parent', tbody); tbody.nodes.push(node); } else { nodes.push(node); } } if (tbody) { util.wrapNodes(tbody, Node); } ast.nodes = [open]; ast.nodes = ast.nodes.concat(nodes); ast.nodes.push(close); }
javascript
function createBody(ast) { if (util.hasType(ast, 'tbody')) return; var open = ast.nodes.shift(); var close = ast.nodes.pop(); var started; var nodes = []; var tbody; var len = ast.nodes.length; var idx = -1; while (++idx < len) { var node = ast.nodes[idx]; if (node.type === 'tr' && !started) { started = true; tbody = { type: 'tbody', nodes: [] }; define(tbody, 'parent', ast); nodes.push(tbody); } if (started) { define(node, 'parent', tbody); tbody.nodes.push(node); } else { nodes.push(node); } } if (tbody) { util.wrapNodes(tbody, Node); } ast.nodes = [open]; ast.nodes = ast.nodes.concat(nodes); ast.nodes.push(close); }
[ "function", "createBody", "(", "ast", ")", "{", "if", "(", "util", ".", "hasType", "(", "ast", ",", "'tbody'", ")", ")", "return", ";", "var", "open", "=", "ast", ".", "nodes", ".", "shift", "(", ")", ";", "var", "close", "=", "ast", ".", "nodes", ".", "pop", "(", ")", ";", "var", "started", ";", "var", "nodes", "=", "[", "]", ";", "var", "tbody", ";", "var", "len", "=", "ast", ".", "nodes", ".", "length", ";", "var", "idx", "=", "-", "1", ";", "while", "(", "++", "idx", "<", "len", ")", "{", "var", "node", "=", "ast", ".", "nodes", "[", "idx", "]", ";", "if", "(", "node", ".", "type", "===", "'tr'", "&&", "!", "started", ")", "{", "started", "=", "true", ";", "tbody", "=", "{", "type", ":", "'tbody'", ",", "nodes", ":", "[", "]", "}", ";", "define", "(", "tbody", ",", "'parent'", ",", "ast", ")", ";", "nodes", ".", "push", "(", "tbody", ")", ";", "}", "if", "(", "started", ")", "{", "define", "(", "node", ",", "'parent'", ",", "tbody", ")", ";", "tbody", ".", "nodes", ".", "push", "(", "node", ")", ";", "}", "else", "{", "nodes", ".", "push", "(", "node", ")", ";", "}", "}", "if", "(", "tbody", ")", "{", "util", ".", "wrapNodes", "(", "tbody", ",", "Node", ")", ";", "}", "ast", ".", "nodes", "=", "[", "open", "]", ";", "ast", ".", "nodes", "=", "ast", ".", "nodes", ".", "concat", "(", "nodes", ")", ";", "ast", ".", "nodes", ".", "push", "(", "close", ")", ";", "}" ]
Add `tbody` nodes if they don't exist
[ "Add", "tbody", "nodes", "if", "they", "don", "t", "exist" ]
578388666acebfe3977508bdb9bb9839d41c085f
https://github.com/breakdance/breakdance/blob/578388666acebfe3977508bdb9bb9839d41c085f/lib/tables.js#L188-L222
18,843
breakdance/breakdance
lib/handlers/text.js
needsSpace
function needsSpace(a, b) { var aa = a.slice(-1); var bb = b.charAt(0); if (bb === '.' && /\w/.test(b.charAt(1)) && aa !== '\n') { return true; } if (utils.isEndingChar(bb)) { return false; } if (aa === '`' && !/\s/.test(a.charAt(a.length - 2))) { return true; } if (/[*_]/.test(aa) && /\w/.test(bb)) { return true; } if (utils.isOpeningChar(aa)) { return false; } if (utils.isTightSeparator(aa) || utils.isTightSeparator(bb)) { return false; } if ((utils.isLooseSeparator(aa) || utils.isLooseSeparator(bb)) && !/\s/.test(aa)) { return true; } if (/\s/.test(aa) && utils.isStartingChar(bb)) { return false; } if (utils.isWrappingChar(aa) && utils.isStartingChar(bb)) { return true; } if (utils.isEndingChar(aa) && !/<br>$/.test(a) && !/\s/.test(bb) && !utils.isEndingChar(bb)) { return true; } if ((utils.isStartingChar(bb) || utils.isWrappingChar(bb) || utils.isWrappingChar(aa)) && !utils.isStartingChar(aa)) { return true; } if (utils.isWordChar(aa) && utils.isWordChar(bb)) { return true; } if (/\W/.test(bb) && !utils.isStartingChar(bb) && !utils.isOpeningChar(bb) && !utils.isEndingChar(bb) && !utils.isSpecialChar(bb) && !utils.isSeparator(bb) && !utils.isStartingChar(aa)) { return true; } return false; }
javascript
function needsSpace(a, b) { var aa = a.slice(-1); var bb = b.charAt(0); if (bb === '.' && /\w/.test(b.charAt(1)) && aa !== '\n') { return true; } if (utils.isEndingChar(bb)) { return false; } if (aa === '`' && !/\s/.test(a.charAt(a.length - 2))) { return true; } if (/[*_]/.test(aa) && /\w/.test(bb)) { return true; } if (utils.isOpeningChar(aa)) { return false; } if (utils.isTightSeparator(aa) || utils.isTightSeparator(bb)) { return false; } if ((utils.isLooseSeparator(aa) || utils.isLooseSeparator(bb)) && !/\s/.test(aa)) { return true; } if (/\s/.test(aa) && utils.isStartingChar(bb)) { return false; } if (utils.isWrappingChar(aa) && utils.isStartingChar(bb)) { return true; } if (utils.isEndingChar(aa) && !/<br>$/.test(a) && !/\s/.test(bb) && !utils.isEndingChar(bb)) { return true; } if ((utils.isStartingChar(bb) || utils.isWrappingChar(bb) || utils.isWrappingChar(aa)) && !utils.isStartingChar(aa)) { return true; } if (utils.isWordChar(aa) && utils.isWordChar(bb)) { return true; } if (/\W/.test(bb) && !utils.isStartingChar(bb) && !utils.isOpeningChar(bb) && !utils.isEndingChar(bb) && !utils.isSpecialChar(bb) && !utils.isSeparator(bb) && !utils.isStartingChar(aa)) { return true; } return false; }
[ "function", "needsSpace", "(", "a", ",", "b", ")", "{", "var", "aa", "=", "a", ".", "slice", "(", "-", "1", ")", ";", "var", "bb", "=", "b", ".", "charAt", "(", "0", ")", ";", "if", "(", "bb", "===", "'.'", "&&", "/", "\\w", "/", ".", "test", "(", "b", ".", "charAt", "(", "1", ")", ")", "&&", "aa", "!==", "'\\n'", ")", "{", "return", "true", ";", "}", "if", "(", "utils", ".", "isEndingChar", "(", "bb", ")", ")", "{", "return", "false", ";", "}", "if", "(", "aa", "===", "'`'", "&&", "!", "/", "\\s", "/", ".", "test", "(", "a", ".", "charAt", "(", "a", ".", "length", "-", "2", ")", ")", ")", "{", "return", "true", ";", "}", "if", "(", "/", "[*_]", "/", ".", "test", "(", "aa", ")", "&&", "/", "\\w", "/", ".", "test", "(", "bb", ")", ")", "{", "return", "true", ";", "}", "if", "(", "utils", ".", "isOpeningChar", "(", "aa", ")", ")", "{", "return", "false", ";", "}", "if", "(", "utils", ".", "isTightSeparator", "(", "aa", ")", "||", "utils", ".", "isTightSeparator", "(", "bb", ")", ")", "{", "return", "false", ";", "}", "if", "(", "(", "utils", ".", "isLooseSeparator", "(", "aa", ")", "||", "utils", ".", "isLooseSeparator", "(", "bb", ")", ")", "&&", "!", "/", "\\s", "/", ".", "test", "(", "aa", ")", ")", "{", "return", "true", ";", "}", "if", "(", "/", "\\s", "/", ".", "test", "(", "aa", ")", "&&", "utils", ".", "isStartingChar", "(", "bb", ")", ")", "{", "return", "false", ";", "}", "if", "(", "utils", ".", "isWrappingChar", "(", "aa", ")", "&&", "utils", ".", "isStartingChar", "(", "bb", ")", ")", "{", "return", "true", ";", "}", "if", "(", "utils", ".", "isEndingChar", "(", "aa", ")", "&&", "!", "/", "<br>$", "/", ".", "test", "(", "a", ")", "&&", "!", "/", "\\s", "/", ".", "test", "(", "bb", ")", "&&", "!", "utils", ".", "isEndingChar", "(", "bb", ")", ")", "{", "return", "true", ";", "}", "if", "(", "(", "utils", ".", "isStartingChar", "(", "bb", ")", "||", "utils", ".", "isWrappingChar", "(", "bb", ")", "||", "utils", ".", "isWrappingChar", "(", "aa", ")", ")", "&&", "!", "utils", ".", "isStartingChar", "(", "aa", ")", ")", "{", "return", "true", ";", "}", "if", "(", "utils", ".", "isWordChar", "(", "aa", ")", "&&", "utils", ".", "isWordChar", "(", "bb", ")", ")", "{", "return", "true", ";", "}", "if", "(", "/", "\\W", "/", ".", "test", "(", "bb", ")", "&&", "!", "utils", ".", "isStartingChar", "(", "bb", ")", "&&", "!", "utils", ".", "isOpeningChar", "(", "bb", ")", "&&", "!", "utils", ".", "isEndingChar", "(", "bb", ")", "&&", "!", "utils", ".", "isSpecialChar", "(", "bb", ")", "&&", "!", "utils", ".", "isSeparator", "(", "bb", ")", "&&", "!", "utils", ".", "isStartingChar", "(", "aa", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
a => ending character b => starting character
[ "a", "=", ">", "ending", "character", "b", "=", ">", "starting", "character" ]
578388666acebfe3977508bdb9bb9839d41c085f
https://github.com/breakdance/breakdance/blob/578388666acebfe3977508bdb9bb9839d41c085f/lib/handlers/text.js#L277-L334
18,844
breakdance/breakdance
index.js
Breakdance
function Breakdance(options) { if (typeof options === 'string') { let proto = Object.create(Breakdance.prototype); Breakdance.call(proto); return proto.render.apply(proto, arguments); } if (!(this instanceof Breakdance)) { let proto = Object.create(Breakdance.prototype); Breakdance.call(proto); return proto; } this.define('cache', {}); this.options = extend({}, options); this.plugins = { fns: [], preprocess: [], handlers: {}, before: {}, after: {} }; }
javascript
function Breakdance(options) { if (typeof options === 'string') { let proto = Object.create(Breakdance.prototype); Breakdance.call(proto); return proto.render.apply(proto, arguments); } if (!(this instanceof Breakdance)) { let proto = Object.create(Breakdance.prototype); Breakdance.call(proto); return proto; } this.define('cache', {}); this.options = extend({}, options); this.plugins = { fns: [], preprocess: [], handlers: {}, before: {}, after: {} }; }
[ "function", "Breakdance", "(", "options", ")", "{", "if", "(", "typeof", "options", "===", "'string'", ")", "{", "let", "proto", "=", "Object", ".", "create", "(", "Breakdance", ".", "prototype", ")", ";", "Breakdance", ".", "call", "(", "proto", ")", ";", "return", "proto", ".", "render", ".", "apply", "(", "proto", ",", "arguments", ")", ";", "}", "if", "(", "!", "(", "this", "instanceof", "Breakdance", ")", ")", "{", "let", "proto", "=", "Object", ".", "create", "(", "Breakdance", ".", "prototype", ")", ";", "Breakdance", ".", "call", "(", "proto", ")", ";", "return", "proto", ";", "}", "this", ".", "define", "(", "'cache'", ",", "{", "}", ")", ";", "this", ".", "options", "=", "extend", "(", "{", "}", ",", "options", ")", ";", "this", ".", "plugins", "=", "{", "fns", ":", "[", "]", ",", "preprocess", ":", "[", "]", ",", "handlers", ":", "{", "}", ",", "before", ":", "{", "}", ",", "after", ":", "{", "}", "}", ";", "}" ]
Create an instance of `Breakdance` with the given `options`. {{example "Breakdance"}} @param {Object|String} `options` Pass options if you need to instantiate Breakdance, or a string to convert HTML to markdown. @api public
[ "Create", "an", "instance", "of", "Breakdance", "with", "the", "given", "options", "." ]
578388666acebfe3977508bdb9bb9839d41c085f
https://github.com/breakdance/breakdance/blob/578388666acebfe3977508bdb9bb9839d41c085f/index.js#L22-L44
18,845
scinos/webpack-plugin-hash-output
src/OutputHash.js
replaceStringInAsset
function replaceStringInAsset(asset, source, target) { const sourceRE = new RegExp(source, 'g'); if (typeof asset === 'string') { return asset.replace(sourceRE, target); } // ReplaceSource if ('_source' in asset) { asset._source = replaceStringInAsset(asset._source, source, target); return asset; } // CachedSource if ('_cachedSource' in asset) { asset._cachedSource = asset.source().replace(sourceRE, target); return asset; } // RawSource / SourceMapSource if ('_value' in asset) { asset._value = asset.source().replace(sourceRE, target); return asset; } // ConcatSource if ('children' in asset) { asset.children = asset.children.map(child => replaceStringInAsset(child, source, target)); return asset; } throw new Error( `Unknown asset type (${asset.constructor.name})!. ` + 'Unfortunately this type of asset is not supported yet. ' + 'Please raise an issue and we will look into it asap' ); }
javascript
function replaceStringInAsset(asset, source, target) { const sourceRE = new RegExp(source, 'g'); if (typeof asset === 'string') { return asset.replace(sourceRE, target); } // ReplaceSource if ('_source' in asset) { asset._source = replaceStringInAsset(asset._source, source, target); return asset; } // CachedSource if ('_cachedSource' in asset) { asset._cachedSource = asset.source().replace(sourceRE, target); return asset; } // RawSource / SourceMapSource if ('_value' in asset) { asset._value = asset.source().replace(sourceRE, target); return asset; } // ConcatSource if ('children' in asset) { asset.children = asset.children.map(child => replaceStringInAsset(child, source, target)); return asset; } throw new Error( `Unknown asset type (${asset.constructor.name})!. ` + 'Unfortunately this type of asset is not supported yet. ' + 'Please raise an issue and we will look into it asap' ); }
[ "function", "replaceStringInAsset", "(", "asset", ",", "source", ",", "target", ")", "{", "const", "sourceRE", "=", "new", "RegExp", "(", "source", ",", "'g'", ")", ";", "if", "(", "typeof", "asset", "===", "'string'", ")", "{", "return", "asset", ".", "replace", "(", "sourceRE", ",", "target", ")", ";", "}", "// ReplaceSource", "if", "(", "'_source'", "in", "asset", ")", "{", "asset", ".", "_source", "=", "replaceStringInAsset", "(", "asset", ".", "_source", ",", "source", ",", "target", ")", ";", "return", "asset", ";", "}", "// CachedSource", "if", "(", "'_cachedSource'", "in", "asset", ")", "{", "asset", ".", "_cachedSource", "=", "asset", ".", "source", "(", ")", ".", "replace", "(", "sourceRE", ",", "target", ")", ";", "return", "asset", ";", "}", "// RawSource / SourceMapSource", "if", "(", "'_value'", "in", "asset", ")", "{", "asset", ".", "_value", "=", "asset", ".", "source", "(", ")", ".", "replace", "(", "sourceRE", ",", "target", ")", ";", "return", "asset", ";", "}", "// ConcatSource", "if", "(", "'children'", "in", "asset", ")", "{", "asset", ".", "children", "=", "asset", ".", "children", ".", "map", "(", "child", "=>", "replaceStringInAsset", "(", "child", ",", "source", ",", "target", ")", ")", ";", "return", "asset", ";", "}", "throw", "new", "Error", "(", "`", "${", "asset", ".", "constructor", ".", "name", "}", "`", "+", "'Unfortunately this type of asset is not supported yet. '", "+", "'Please raise an issue and we will look into it asap'", ")", ";", "}" ]
Replaces a string in an asset
[ "Replaces", "a", "string", "in", "an", "asset" ]
0b4adc20111fa0a798581703b51cd2e138b59b0e
https://github.com/scinos/webpack-plugin-hash-output/blob/0b4adc20111fa0a798581703b51cd2e138b59b0e/src/OutputHash.js#L13-L49
18,846
scinos/webpack-plugin-hash-output
src/OutputHash.js
reHashChunk
function reHashChunk(chunk, assets, hashFn, nameMap) { const isMainFile = file => file.endsWith('.js') || file.endsWith('.css'); // Update the name of the main files chunk.files.filter(isMainFile).forEach((oldChunkName, index) => { const asset = assets[oldChunkName]; const { fullHash, shortHash: newHash } = hashFn(asset.source()); let newChunkName; if (oldChunkName.includes(chunk.renderedHash)) { // Save the hash map for replacing the secondary files nameMap[chunk.renderedHash] = newHash; newChunkName = oldChunkName.replace(chunk.renderedHash, newHash); // Keep the chunk hashes in sync chunk.hash = fullHash; chunk.renderedHash = newHash; } else { // This is a massive hack: // // The oldHash of the main file is in `chunk.renderedHash`. But some plugins add a // second "main" file to the chunk (for example, `mini-css-extract-plugin` adds a // css file). That other main file has to be rehashed too, but we don't know the // oldHash of the file, so we don't know what string we have to replace by the new // hash. // // However, the hash present in the file name must be one of the hashes of the // modules inside the chunk (modules[].renderedHash). So we try to replace each // module hash with the new hash. const module = Array.from(chunk.modulesIterable).find(m => oldChunkName.includes(m.renderedHash) ); // Can't find a module with this hash... not sure what is going on, just return and // hope for the best. if (!module) return; // Save the hash map for replacing the secondary files nameMap[module.renderedHash] = newHash; newChunkName = oldChunkName.replace(module.renderedHash, newHash); // Keep the module hashes in sync module.hash = fullHash; module.renderedHash = newHash; } // Change file name to include the new hash chunk.files[index] = newChunkName; asset._name = newChunkName; delete assets[oldChunkName]; assets[newChunkName] = asset; }); // Update the content of the rest of the files in the chunk chunk.files .filter(file => !isMainFile(file)) .forEach(file => { Object.keys(nameMap).forEach(old => { const newHash = nameMap[old]; replaceStringInAsset(assets[file], old, newHash); }); }); }
javascript
function reHashChunk(chunk, assets, hashFn, nameMap) { const isMainFile = file => file.endsWith('.js') || file.endsWith('.css'); // Update the name of the main files chunk.files.filter(isMainFile).forEach((oldChunkName, index) => { const asset = assets[oldChunkName]; const { fullHash, shortHash: newHash } = hashFn(asset.source()); let newChunkName; if (oldChunkName.includes(chunk.renderedHash)) { // Save the hash map for replacing the secondary files nameMap[chunk.renderedHash] = newHash; newChunkName = oldChunkName.replace(chunk.renderedHash, newHash); // Keep the chunk hashes in sync chunk.hash = fullHash; chunk.renderedHash = newHash; } else { // This is a massive hack: // // The oldHash of the main file is in `chunk.renderedHash`. But some plugins add a // second "main" file to the chunk (for example, `mini-css-extract-plugin` adds a // css file). That other main file has to be rehashed too, but we don't know the // oldHash of the file, so we don't know what string we have to replace by the new // hash. // // However, the hash present in the file name must be one of the hashes of the // modules inside the chunk (modules[].renderedHash). So we try to replace each // module hash with the new hash. const module = Array.from(chunk.modulesIterable).find(m => oldChunkName.includes(m.renderedHash) ); // Can't find a module with this hash... not sure what is going on, just return and // hope for the best. if (!module) return; // Save the hash map for replacing the secondary files nameMap[module.renderedHash] = newHash; newChunkName = oldChunkName.replace(module.renderedHash, newHash); // Keep the module hashes in sync module.hash = fullHash; module.renderedHash = newHash; } // Change file name to include the new hash chunk.files[index] = newChunkName; asset._name = newChunkName; delete assets[oldChunkName]; assets[newChunkName] = asset; }); // Update the content of the rest of the files in the chunk chunk.files .filter(file => !isMainFile(file)) .forEach(file => { Object.keys(nameMap).forEach(old => { const newHash = nameMap[old]; replaceStringInAsset(assets[file], old, newHash); }); }); }
[ "function", "reHashChunk", "(", "chunk", ",", "assets", ",", "hashFn", ",", "nameMap", ")", "{", "const", "isMainFile", "=", "file", "=>", "file", ".", "endsWith", "(", "'.js'", ")", "||", "file", ".", "endsWith", "(", "'.css'", ")", ";", "// Update the name of the main files", "chunk", ".", "files", ".", "filter", "(", "isMainFile", ")", ".", "forEach", "(", "(", "oldChunkName", ",", "index", ")", "=>", "{", "const", "asset", "=", "assets", "[", "oldChunkName", "]", ";", "const", "{", "fullHash", ",", "shortHash", ":", "newHash", "}", "=", "hashFn", "(", "asset", ".", "source", "(", ")", ")", ";", "let", "newChunkName", ";", "if", "(", "oldChunkName", ".", "includes", "(", "chunk", ".", "renderedHash", ")", ")", "{", "// Save the hash map for replacing the secondary files", "nameMap", "[", "chunk", ".", "renderedHash", "]", "=", "newHash", ";", "newChunkName", "=", "oldChunkName", ".", "replace", "(", "chunk", ".", "renderedHash", ",", "newHash", ")", ";", "// Keep the chunk hashes in sync", "chunk", ".", "hash", "=", "fullHash", ";", "chunk", ".", "renderedHash", "=", "newHash", ";", "}", "else", "{", "// This is a massive hack:", "//", "// The oldHash of the main file is in `chunk.renderedHash`. But some plugins add a", "// second \"main\" file to the chunk (for example, `mini-css-extract-plugin` adds a", "// css file). That other main file has to be rehashed too, but we don't know the", "// oldHash of the file, so we don't know what string we have to replace by the new", "// hash.", "//", "// However, the hash present in the file name must be one of the hashes of the", "// modules inside the chunk (modules[].renderedHash). So we try to replace each", "// module hash with the new hash.", "const", "module", "=", "Array", ".", "from", "(", "chunk", ".", "modulesIterable", ")", ".", "find", "(", "m", "=>", "oldChunkName", ".", "includes", "(", "m", ".", "renderedHash", ")", ")", ";", "// Can't find a module with this hash... not sure what is going on, just return and", "// hope for the best.", "if", "(", "!", "module", ")", "return", ";", "// Save the hash map for replacing the secondary files", "nameMap", "[", "module", ".", "renderedHash", "]", "=", "newHash", ";", "newChunkName", "=", "oldChunkName", ".", "replace", "(", "module", ".", "renderedHash", ",", "newHash", ")", ";", "// Keep the module hashes in sync", "module", ".", "hash", "=", "fullHash", ";", "module", ".", "renderedHash", "=", "newHash", ";", "}", "// Change file name to include the new hash", "chunk", ".", "files", "[", "index", "]", "=", "newChunkName", ";", "asset", ".", "_name", "=", "newChunkName", ";", "delete", "assets", "[", "oldChunkName", "]", ";", "assets", "[", "newChunkName", "]", "=", "asset", ";", "}", ")", ";", "// Update the content of the rest of the files in the chunk", "chunk", ".", "files", ".", "filter", "(", "file", "=>", "!", "isMainFile", "(", "file", ")", ")", ".", "forEach", "(", "file", "=>", "{", "Object", ".", "keys", "(", "nameMap", ")", ".", "forEach", "(", "old", "=>", "{", "const", "newHash", "=", "nameMap", "[", "old", "]", ";", "replaceStringInAsset", "(", "assets", "[", "file", "]", ",", "old", ",", "newHash", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Computes the new hash of a chunk. This function updates the *name* of the main file (i.e. source code), and the *content* of the secondary files (i.e source maps)
[ "Computes", "the", "new", "hash", "of", "a", "chunk", "." ]
0b4adc20111fa0a798581703b51cd2e138b59b0e
https://github.com/scinos/webpack-plugin-hash-output/blob/0b4adc20111fa0a798581703b51cd2e138b59b0e/src/OutputHash.js#L57-L120
18,847
scinos/webpack-plugin-hash-output
src/OutputHash.js
replaceOldHashForNewInChunkFiles
function replaceOldHashForNewInChunkFiles(chunk, assets, oldHashToNewHashMap) { chunk.files.forEach(file => { Object.keys(oldHashToNewHashMap).forEach(oldHash => { const newHash = oldHashToNewHashMap[oldHash]; replaceStringInAsset(assets[file], oldHash, newHash); }); }); }
javascript
function replaceOldHashForNewInChunkFiles(chunk, assets, oldHashToNewHashMap) { chunk.files.forEach(file => { Object.keys(oldHashToNewHashMap).forEach(oldHash => { const newHash = oldHashToNewHashMap[oldHash]; replaceStringInAsset(assets[file], oldHash, newHash); }); }); }
[ "function", "replaceOldHashForNewInChunkFiles", "(", "chunk", ",", "assets", ",", "oldHashToNewHashMap", ")", "{", "chunk", ".", "files", ".", "forEach", "(", "file", "=>", "{", "Object", ".", "keys", "(", "oldHashToNewHashMap", ")", ".", "forEach", "(", "oldHash", "=>", "{", "const", "newHash", "=", "oldHashToNewHashMap", "[", "oldHash", "]", ";", "replaceStringInAsset", "(", "assets", "[", "file", "]", ",", "oldHash", ",", "newHash", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Replaces old hashes for new hashes in chunk files. This function iterates through file contents and replaces all the ocurrences of old hashes for new ones. We assume hashes are unique enough, so that we don't accidentally hit a collision and replace existing data.
[ "Replaces", "old", "hashes", "for", "new", "hashes", "in", "chunk", "files", "." ]
0b4adc20111fa0a798581703b51cd2e138b59b0e
https://github.com/scinos/webpack-plugin-hash-output/blob/0b4adc20111fa0a798581703b51cd2e138b59b0e/src/OutputHash.js#L129-L136
18,848
kof/animation-frame
lib/animation-frame.js
AnimationFrame
function AnimationFrame(options) { if (!(this instanceof AnimationFrame)) return new AnimationFrame(options) options || (options = {}) // Its a frame rate. if (typeof options == 'number') options = {frameRate: options} options.useNative != null || (options.useNative = true) this.options = options this.frameRate = options.frameRate || AnimationFrame.FRAME_RATE this._frameLength = 1000 / this.frameRate this._isCustomFrameRate = this.frameRate !== AnimationFrame.FRAME_RATE this._timeoutId = null this._callbacks = {} this._lastTickTime = 0 this._tickCounter = 0 }
javascript
function AnimationFrame(options) { if (!(this instanceof AnimationFrame)) return new AnimationFrame(options) options || (options = {}) // Its a frame rate. if (typeof options == 'number') options = {frameRate: options} options.useNative != null || (options.useNative = true) this.options = options this.frameRate = options.frameRate || AnimationFrame.FRAME_RATE this._frameLength = 1000 / this.frameRate this._isCustomFrameRate = this.frameRate !== AnimationFrame.FRAME_RATE this._timeoutId = null this._callbacks = {} this._lastTickTime = 0 this._tickCounter = 0 }
[ "function", "AnimationFrame", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AnimationFrame", ")", ")", "return", "new", "AnimationFrame", "(", "options", ")", "options", "||", "(", "options", "=", "{", "}", ")", "// Its a frame rate.", "if", "(", "typeof", "options", "==", "'number'", ")", "options", "=", "{", "frameRate", ":", "options", "}", "options", ".", "useNative", "!=", "null", "||", "(", "options", ".", "useNative", "=", "true", ")", "this", ".", "options", "=", "options", "this", ".", "frameRate", "=", "options", ".", "frameRate", "||", "AnimationFrame", ".", "FRAME_RATE", "this", ".", "_frameLength", "=", "1000", "/", "this", ".", "frameRate", "this", ".", "_isCustomFrameRate", "=", "this", ".", "frameRate", "!==", "AnimationFrame", ".", "FRAME_RATE", "this", ".", "_timeoutId", "=", "null", "this", ".", "_callbacks", "=", "{", "}", "this", ".", "_lastTickTime", "=", "0", "this", ".", "_tickCounter", "=", "0", "}" ]
Animation frame constructor. Options: - `useNative` use the native animation frame if possible, defaults to true - `frameRate` pass a custom frame rate @param {Object|Number} options
[ "Animation", "frame", "constructor", "." ]
a2ccde941f5a7fbc92e2313edbaaac4181328315
https://github.com/kof/animation-frame/blob/a2ccde941f5a7fbc92e2313edbaaac4181328315/lib/animation-frame.js#L21-L36
18,849
openleap/aframe-leap-hands
src/helpers/intersector.js
Intersector
function Intersector () { this.arrowHelper = this.createArrowHelper(); this.raycaster = new THREE.Raycaster(new THREE.Vector3(), new THREE.Vector3(), 0, 0.2); }
javascript
function Intersector () { this.arrowHelper = this.createArrowHelper(); this.raycaster = new THREE.Raycaster(new THREE.Vector3(), new THREE.Vector3(), 0, 0.2); }
[ "function", "Intersector", "(", ")", "{", "this", ".", "arrowHelper", "=", "this", ".", "createArrowHelper", "(", ")", ";", "this", ".", "raycaster", "=", "new", "THREE", ".", "Raycaster", "(", "new", "THREE", ".", "Vector3", "(", ")", ",", "new", "THREE", ".", "Vector3", "(", ")", ",", "0", ",", "0.2", ")", ";", "}" ]
Helper for raycasting, which chooses a raycaster direction based on hand position. Also supports a debugging mode, in which the ray is visible.
[ "Helper", "for", "raycasting", "which", "chooses", "a", "raycaster", "direction", "based", "on", "hand", "position", ".", "Also", "supports", "a", "debugging", "mode", "in", "which", "the", "ray", "is", "visible", "." ]
d377683c51f8af3f19312322f60039cf0af08096
https://github.com/openleap/aframe-leap-hands/blob/d377683c51f8af3f19312322f60039cf0af08096/src/helpers/intersector.js#L5-L8
18,850
openleap/aframe-leap-hands
src/helpers/hand-body.js
HandBody
function HandBody (el, handComponent) { this.el = el; this.handComponent = handComponent; this.system = this.el.sceneEl.systems.leap; this.physics = this.el.sceneEl.systems.physics; this.physics.addComponent(this); this.palmBody = /** @type {CANNON.Body} */ null; this.fingerBodies = /** @type {{string: CANNON.Body}} */ {}; }
javascript
function HandBody (el, handComponent) { this.el = el; this.handComponent = handComponent; this.system = this.el.sceneEl.systems.leap; this.physics = this.el.sceneEl.systems.physics; this.physics.addComponent(this); this.palmBody = /** @type {CANNON.Body} */ null; this.fingerBodies = /** @type {{string: CANNON.Body}} */ {}; }
[ "function", "HandBody", "(", "el", ",", "handComponent", ")", "{", "this", ".", "el", "=", "el", ";", "this", ".", "handComponent", "=", "handComponent", ";", "this", ".", "system", "=", "this", ".", "el", ".", "sceneEl", ".", "systems", ".", "leap", ";", "this", ".", "physics", "=", "this", ".", "el", ".", "sceneEl", ".", "systems", ".", "physics", ";", "this", ".", "physics", ".", "addComponent", "(", "this", ")", ";", "this", ".", "palmBody", "=", "/** @type {CANNON.Body} */", "null", ";", "this", ".", "fingerBodies", "=", "/** @type {{string: CANNON.Body}} */", "{", "}", ";", "}" ]
CANNON body controller for a single Leap Motion hand.
[ "CANNON", "body", "controller", "for", "a", "single", "Leap", "Motion", "hand", "." ]
d377683c51f8af3f19312322f60039cf0af08096
https://github.com/openleap/aframe-leap-hands/blob/d377683c51f8af3f19312322f60039cf0af08096/src/helpers/hand-body.js#L4-L13
18,851
openleap/aframe-leap-hands
lib/leap.hand-mesh.js
HandMesh
function HandMesh(options) { this.options = options = Object.assign({}, DEFAULTS, options || {}); this.options.jointColor = this.options.jointColor || JOINT_COLORS[numInstances % 2]; this.object3D = new THREE.Object3D(); this.material = !isNaN(options.opacity) ? new THREE.MeshPhongMaterial({ fog: false, transparent: true, opacity: options.opacity }) : new THREE.MeshPhongMaterial({fog: false}); this.createFingers(); this.createArm(); numInstances++; }
javascript
function HandMesh(options) { this.options = options = Object.assign({}, DEFAULTS, options || {}); this.options.jointColor = this.options.jointColor || JOINT_COLORS[numInstances % 2]; this.object3D = new THREE.Object3D(); this.material = !isNaN(options.opacity) ? new THREE.MeshPhongMaterial({ fog: false, transparent: true, opacity: options.opacity }) : new THREE.MeshPhongMaterial({fog: false}); this.createFingers(); this.createArm(); numInstances++; }
[ "function", "HandMesh", "(", "options", ")", "{", "this", ".", "options", "=", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "DEFAULTS", ",", "options", "||", "{", "}", ")", ";", "this", ".", "options", ".", "jointColor", "=", "this", ".", "options", ".", "jointColor", "||", "JOINT_COLORS", "[", "numInstances", "%", "2", "]", ";", "this", ".", "object3D", "=", "new", "THREE", ".", "Object3D", "(", ")", ";", "this", ".", "material", "=", "!", "isNaN", "(", "options", ".", "opacity", ")", "?", "new", "THREE", ".", "MeshPhongMaterial", "(", "{", "fog", ":", "false", ",", "transparent", ":", "true", ",", "opacity", ":", "options", ".", "opacity", "}", ")", ":", "new", "THREE", ".", "MeshPhongMaterial", "(", "{", "fog", ":", "false", "}", ")", ";", "this", ".", "createFingers", "(", ")", ";", "this", ".", "createArm", "(", ")", ";", "numInstances", "++", ";", "}" ]
Wrapper for a THREE.Mesh instance fitted to a single Leap Motion hand. @param {Object} options
[ "Wrapper", "for", "a", "THREE", ".", "Mesh", "instance", "fitted", "to", "a", "single", "Leap", "Motion", "hand", "." ]
d377683c51f8af3f19312322f60039cf0af08096
https://github.com/openleap/aframe-leap-hands/blob/d377683c51f8af3f19312322f60039cf0af08096/lib/leap.hand-mesh.js#L22-L35
18,852
raphamorim/origami.js
src/utilities.js
exists
function exists(el, arr) { for (var i = 0; i < arr.length; i++) { if (arr[i].element.isEqualNode(el)) return arr[i]; } return false; }
javascript
function exists(el, arr) { for (var i = 0; i < arr.length; i++) { if (arr[i].element.isEqualNode(el)) return arr[i]; } return false; }
[ "function", "exists", "(", "el", ",", "arr", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "if", "(", "arr", "[", "i", "]", ".", "element", ".", "isEqualNode", "(", "el", ")", ")", "return", "arr", "[", "i", "]", ";", "}", "return", "false", ";", "}" ]
Check if element exists in a Array of NodeItems @param {NodeItem} current nodeItem to check @param {Array} array of NodeItems @returns {NodeItem} NodeItem exitent in array
[ "Check", "if", "element", "exists", "in", "a", "Array", "of", "NodeItems" ]
bb47a42cbafb226dce5ed024d88afb7053728a42
https://github.com/raphamorim/origami.js/blob/bb47a42cbafb226dce5ed024d88afb7053728a42/src/utilities.js#L11-L17
18,853
raphamorim/origami.js
src/utilities.js
argsByRules
function argsByRules(argsArray, rules) { var params = rules || ['x', 'y', 'width', 'height'], args = {}; for (var i = 0; i < argsArray.length; i++) { if (typeof(argsArray[i]) === "object") args["style"] = argsArray[i]; else if (params.length) args[params.shift()] = argsArray[i]; } args.style = normalizeStyle(args.style); if ((typeof(args.x) === 'string') && (typeof(args.y) === 'string')) args = smartCoordinates(args); return args; }
javascript
function argsByRules(argsArray, rules) { var params = rules || ['x', 'y', 'width', 'height'], args = {}; for (var i = 0; i < argsArray.length; i++) { if (typeof(argsArray[i]) === "object") args["style"] = argsArray[i]; else if (params.length) args[params.shift()] = argsArray[i]; } args.style = normalizeStyle(args.style); if ((typeof(args.x) === 'string') && (typeof(args.y) === 'string')) args = smartCoordinates(args); return args; }
[ "function", "argsByRules", "(", "argsArray", ",", "rules", ")", "{", "var", "params", "=", "rules", "||", "[", "'x'", ",", "'y'", ",", "'width'", ",", "'height'", "]", ",", "args", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "argsArray", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeof", "(", "argsArray", "[", "i", "]", ")", "===", "\"object\"", ")", "args", "[", "\"style\"", "]", "=", "argsArray", "[", "i", "]", ";", "else", "if", "(", "params", ".", "length", ")", "args", "[", "params", ".", "shift", "(", ")", "]", "=", "argsArray", "[", "i", "]", ";", "}", "args", ".", "style", "=", "normalizeStyle", "(", "args", ".", "style", ")", ";", "if", "(", "(", "typeof", "(", "args", ".", "x", ")", "===", "'string'", ")", "&&", "(", "typeof", "(", "args", ".", "y", ")", "===", "'string'", ")", ")", "args", "=", "smartCoordinates", "(", "args", ")", ";", "return", "args", ";", "}" ]
Filter arguments by rules @param {Array} methods arguments @param {Object} rules to apply @returns {Object} arguments filtered
[ "Filter", "arguments", "by", "rules" ]
bb47a42cbafb226dce5ed024d88afb7053728a42
https://github.com/raphamorim/origami.js/blob/bb47a42cbafb226dce5ed024d88afb7053728a42/src/utilities.js#L25-L43
18,854
raphamorim/origami.js
src/utilities.js
smartCoordinates
function smartCoordinates(args) { var x = args.x, y = args.y; var paper = Origami.getPaper(), elmWidth = paper.element.width, elmHeight = paper.element.height, radius = (args.r || 0); var width = (args.width || radius), height = (args.height || width); var axis = { x: [ 'right', 'center', 'left' ], y: [ 'top', 'center', 'bottom' ] }; if (axis.x.indexOf(x) !== -1) { if (x === 'right') x = Math.floor(elmWidth - width); else if (x === 'center') if (radius) x = Math.floor(elmWidth / 2) else x = Math.floor((elmWidth / 2) - (width / 2)); else if (x === 'left') x = radius; } else if ((x + '').substr(-1) === '%') { x = (elmWidth * parseInt(x, 10)) / 100; } else { x = 0; } if (axis.y.indexOf(y) !== -1) { if (y === 'top') y = radius; else if (y === 'center') if (radius) y = Math.floor(elmHeight / 2); else y = Math.floor((elmHeight / 2) - (height / 2)); else if (y === 'bottom') y = Math.floor(elmHeight - height); } else if ((y + '').substr(-1) === '%') { y = (elmHeight * parseInt(y, 10)) / 100; } else { y = 0; } args.y = y; args.x = x; return args; }
javascript
function smartCoordinates(args) { var x = args.x, y = args.y; var paper = Origami.getPaper(), elmWidth = paper.element.width, elmHeight = paper.element.height, radius = (args.r || 0); var width = (args.width || radius), height = (args.height || width); var axis = { x: [ 'right', 'center', 'left' ], y: [ 'top', 'center', 'bottom' ] }; if (axis.x.indexOf(x) !== -1) { if (x === 'right') x = Math.floor(elmWidth - width); else if (x === 'center') if (radius) x = Math.floor(elmWidth / 2) else x = Math.floor((elmWidth / 2) - (width / 2)); else if (x === 'left') x = radius; } else if ((x + '').substr(-1) === '%') { x = (elmWidth * parseInt(x, 10)) / 100; } else { x = 0; } if (axis.y.indexOf(y) !== -1) { if (y === 'top') y = radius; else if (y === 'center') if (radius) y = Math.floor(elmHeight / 2); else y = Math.floor((elmHeight / 2) - (height / 2)); else if (y === 'bottom') y = Math.floor(elmHeight - height); } else if ((y + '').substr(-1) === '%') { y = (elmHeight * parseInt(y, 10)) / 100; } else { y = 0; } args.y = y; args.x = x; return args; }
[ "function", "smartCoordinates", "(", "args", ")", "{", "var", "x", "=", "args", ".", "x", ",", "y", "=", "args", ".", "y", ";", "var", "paper", "=", "Origami", ".", "getPaper", "(", ")", ",", "elmWidth", "=", "paper", ".", "element", ".", "width", ",", "elmHeight", "=", "paper", ".", "element", ".", "height", ",", "radius", "=", "(", "args", ".", "r", "||", "0", ")", ";", "var", "width", "=", "(", "args", ".", "width", "||", "radius", ")", ",", "height", "=", "(", "args", ".", "height", "||", "width", ")", ";", "var", "axis", "=", "{", "x", ":", "[", "'right'", ",", "'center'", ",", "'left'", "]", ",", "y", ":", "[", "'top'", ",", "'center'", ",", "'bottom'", "]", "}", ";", "if", "(", "axis", ".", "x", ".", "indexOf", "(", "x", ")", "!==", "-", "1", ")", "{", "if", "(", "x", "===", "'right'", ")", "x", "=", "Math", ".", "floor", "(", "elmWidth", "-", "width", ")", ";", "else", "if", "(", "x", "===", "'center'", ")", "if", "(", "radius", ")", "x", "=", "Math", ".", "floor", "(", "elmWidth", "/", "2", ")", "else", "x", "=", "Math", ".", "floor", "(", "(", "elmWidth", "/", "2", ")", "-", "(", "width", "/", "2", ")", ")", ";", "else", "if", "(", "x", "===", "'left'", ")", "x", "=", "radius", ";", "}", "else", "if", "(", "(", "x", "+", "''", ")", ".", "substr", "(", "-", "1", ")", "===", "'%'", ")", "{", "x", "=", "(", "elmWidth", "*", "parseInt", "(", "x", ",", "10", ")", ")", "/", "100", ";", "}", "else", "{", "x", "=", "0", ";", "}", "if", "(", "axis", ".", "y", ".", "indexOf", "(", "y", ")", "!==", "-", "1", ")", "{", "if", "(", "y", "===", "'top'", ")", "y", "=", "radius", ";", "else", "if", "(", "y", "===", "'center'", ")", "if", "(", "radius", ")", "y", "=", "Math", ".", "floor", "(", "elmHeight", "/", "2", ")", ";", "else", "y", "=", "Math", ".", "floor", "(", "(", "elmHeight", "/", "2", ")", "-", "(", "height", "/", "2", ")", ")", ";", "else", "if", "(", "y", "===", "'bottom'", ")", "y", "=", "Math", ".", "floor", "(", "elmHeight", "-", "height", ")", ";", "}", "else", "if", "(", "(", "y", "+", "''", ")", ".", "substr", "(", "-", "1", ")", "===", "'%'", ")", "{", "y", "=", "(", "elmHeight", "*", "parseInt", "(", "y", ",", "10", ")", ")", "/", "100", ";", "}", "else", "{", "y", "=", "0", ";", "}", "args", ".", "y", "=", "y", ";", "args", ".", "x", "=", "x", ";", "return", "args", ";", "}" ]
Return args object with new coordinates based on behavior @returns {Object} args
[ "Return", "args", "object", "with", "new", "coordinates", "based", "on", "behavior" ]
bb47a42cbafb226dce5ed024d88afb7053728a42
https://github.com/raphamorim/origami.js/blob/bb47a42cbafb226dce5ed024d88afb7053728a42/src/utilities.js#L102-L154
18,855
raphamorim/origami.js
src/utilities.js
defineDocumentStyles
function defineDocumentStyles() { for (var i = 0; i < document.styleSheets.length; i++) { var mysheet = document.styleSheets[i], myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules; config.documentStyles.push(myrules); } }
javascript
function defineDocumentStyles() { for (var i = 0; i < document.styleSheets.length; i++) { var mysheet = document.styleSheets[i], myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules; config.documentStyles.push(myrules); } }
[ "function", "defineDocumentStyles", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "document", ".", "styleSheets", ".", "length", ";", "i", "++", ")", "{", "var", "mysheet", "=", "document", ".", "styleSheets", "[", "i", "]", ",", "myrules", "=", "mysheet", ".", "cssRules", "?", "mysheet", ".", "cssRules", ":", "mysheet", ".", "rules", ";", "config", ".", "documentStyles", ".", "push", "(", "myrules", ")", ";", "}", "}" ]
Return all documentStyles to a especified origami context @returns undefined
[ "Return", "all", "documentStyles", "to", "a", "especified", "origami", "context" ]
bb47a42cbafb226dce5ed024d88afb7053728a42
https://github.com/raphamorim/origami.js/blob/bb47a42cbafb226dce5ed024d88afb7053728a42/src/utilities.js#L160-L166
18,856
raphamorim/origami.js
src/utilities.js
styleRuleValueFrom
function styleRuleValueFrom(selector, documentStyleRules) { for (var j = 0; j < documentStyleRules.length; j++) { if (documentStyleRules[j].selectorText && documentStyleRules[j].selectorText.toLowerCase() === selector) { return documentStyleRules[j].style; } } }
javascript
function styleRuleValueFrom(selector, documentStyleRules) { for (var j = 0; j < documentStyleRules.length; j++) { if (documentStyleRules[j].selectorText && documentStyleRules[j].selectorText.toLowerCase() === selector) { return documentStyleRules[j].style; } } }
[ "function", "styleRuleValueFrom", "(", "selector", ",", "documentStyleRules", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "documentStyleRules", ".", "length", ";", "j", "++", ")", "{", "if", "(", "documentStyleRules", "[", "j", "]", ".", "selectorText", "&&", "documentStyleRules", "[", "j", "]", ".", "selectorText", ".", "toLowerCase", "(", ")", "===", "selector", ")", "{", "return", "documentStyleRules", "[", "j", "]", ".", "style", ";", "}", "}", "}" ]
Get Style Rule from a specified element @param {String} selector from element @param {Array} Document Style Rules @returns {Object} Merged values of defaults and options
[ "Get", "Style", "Rule", "from", "a", "specified", "element" ]
bb47a42cbafb226dce5ed024d88afb7053728a42
https://github.com/raphamorim/origami.js/blob/bb47a42cbafb226dce5ed024d88afb7053728a42/src/utilities.js#L199-L205
18,857
Gottox/terminal.js
lib/term_state.js
setterFor
function setterFor(objName) { return function(name, value) { if(this["_"+objName+"sUsed"] === true) { this["_"+objName+"s"] = myUtil.extend({}, this["_"+objName+"s"]); this["_"+objName+"sUsed"] = false; } var obj = this["_"+objName+"s"]; if(!(name in obj)) throw new Error("Unknown "+objName+" `"+name+"`"); this.emit(objName+"change", name, value, obj[name]); obj[name] = value; }; }
javascript
function setterFor(objName) { return function(name, value) { if(this["_"+objName+"sUsed"] === true) { this["_"+objName+"s"] = myUtil.extend({}, this["_"+objName+"s"]); this["_"+objName+"sUsed"] = false; } var obj = this["_"+objName+"s"]; if(!(name in obj)) throw new Error("Unknown "+objName+" `"+name+"`"); this.emit(objName+"change", name, value, obj[name]); obj[name] = value; }; }
[ "function", "setterFor", "(", "objName", ")", "{", "return", "function", "(", "name", ",", "value", ")", "{", "if", "(", "this", "[", "\"_\"", "+", "objName", "+", "\"sUsed\"", "]", "===", "true", ")", "{", "this", "[", "\"_\"", "+", "objName", "+", "\"s\"", "]", "=", "myUtil", ".", "extend", "(", "{", "}", ",", "this", "[", "\"_\"", "+", "objName", "+", "\"s\"", "]", ")", ";", "this", "[", "\"_\"", "+", "objName", "+", "\"sUsed\"", "]", "=", "false", ";", "}", "var", "obj", "=", "this", "[", "\"_\"", "+", "objName", "+", "\"s\"", "]", ";", "if", "(", "!", "(", "name", "in", "obj", ")", ")", "throw", "new", "Error", "(", "\"Unknown \"", "+", "objName", "+", "\" `\"", "+", "name", "+", "\"`\"", ")", ";", "this", ".", "emit", "(", "objName", "+", "\"change\"", ",", "name", ",", "value", ",", "obj", "[", "name", "]", ")", ";", "obj", "[", "name", "]", "=", "value", ";", "}", ";", "}" ]
Creates setter for a specific property used on attributes, modes, and meta properties. If the object defines a property _fooUsed, copy on write is enabled. This makes sure that the object is is copied before any changes are made. This makes it possible to reference the object from other context without copying it every time. This reduces memory consumption in some cases. @private
[ "Creates", "setter", "for", "a", "specific", "property", "used", "on", "attributes", "modes", "and", "meta", "properties", "." ]
b9cb92ff43dd4374677fe3f7214c55fed04d99fd
https://github.com/Gottox/terminal.js/blob/b9cb92ff43dd4374677fe3f7214c55fed04d99fd/lib/term_state.js#L59-L72
18,858
Gottox/terminal.js
lib/term_state.js
TermState
function TermState(options) { TermState.super_.call(this, { decodeStrings: false }); options = myUtil.extend({ attributes: {}, }, options); this._defaultAttr = myUtil.extend({ fg: null, bg: null, bold: false, underline: false, italic: false, blink: false, inverse: false }, options.attributes); // This is used for copy on write. this._attributesUsed = true; this.rows = ~~options.rows || 24; this.columns = ~~options.columns || 80; this .on("newListener", this._newListener) .on("removeListener", this._removeListener) .on("pipe", this._pipe); // Reset all on first use this.reset(); }
javascript
function TermState(options) { TermState.super_.call(this, { decodeStrings: false }); options = myUtil.extend({ attributes: {}, }, options); this._defaultAttr = myUtil.extend({ fg: null, bg: null, bold: false, underline: false, italic: false, blink: false, inverse: false }, options.attributes); // This is used for copy on write. this._attributesUsed = true; this.rows = ~~options.rows || 24; this.columns = ~~options.columns || 80; this .on("newListener", this._newListener) .on("removeListener", this._removeListener) .on("pipe", this._pipe); // Reset all on first use this.reset(); }
[ "function", "TermState", "(", "options", ")", "{", "TermState", ".", "super_", ".", "call", "(", "this", ",", "{", "decodeStrings", ":", "false", "}", ")", ";", "options", "=", "myUtil", ".", "extend", "(", "{", "attributes", ":", "{", "}", ",", "}", ",", "options", ")", ";", "this", ".", "_defaultAttr", "=", "myUtil", ".", "extend", "(", "{", "fg", ":", "null", ",", "bg", ":", "null", ",", "bold", ":", "false", ",", "underline", ":", "false", ",", "italic", ":", "false", ",", "blink", ":", "false", ",", "inverse", ":", "false", "}", ",", "options", ".", "attributes", ")", ";", "// This is used for copy on write.", "this", ".", "_attributesUsed", "=", "true", ";", "this", ".", "rows", "=", "~", "~", "options", ".", "rows", "||", "24", ";", "this", ".", "columns", "=", "~", "~", "options", ".", "columns", "||", "80", ";", "this", ".", "on", "(", "\"newListener\"", ",", "this", ".", "_newListener", ")", ".", "on", "(", "\"removeListener\"", ",", "this", ".", "_removeListener", ")", ".", "on", "(", "\"pipe\"", ",", "this", ".", "_pipe", ")", ";", "// Reset all on first use", "this", ".", "reset", "(", ")", ";", "}" ]
A class which holds the terminals state and content @param {object} options - object to configure the terminal @param {number} [options.columns=80] - number of columns in the terminal @param {number} [options.rows=24] - number of rows in the terminal @param {object} [options.attributes] - initial attributes of the terminal @param {string} [options.attributes.fg=null] initial foreground color @param {string} [options.attributes.bg=null] initial background color @param {boolean} [options.attributes.bold=false] terminal is bold by default @param {boolean} [options.attributes.underline=false] terminal is underlined by default @param {boolean} [options.attributes.italic=false] terminal is italic by default @param {boolean} [options.attributes.blink=false] terminal blinks by default @param {boolean} [options.attributes.inverse=false] terminal has reverse colors by default @constructor
[ "A", "class", "which", "holds", "the", "terminals", "state", "and", "content" ]
b9cb92ff43dd4374677fe3f7214c55fed04d99fd
https://github.com/Gottox/terminal.js/blob/b9cb92ff43dd4374677fe3f7214c55fed04d99fd/lib/term_state.js#L89-L118
18,859
Gottox/terminal.js
lib/util.js
getWidth
function getWidth(stringWidth, str) { if (!stringWidth || !stringWidth.toLowerCase) return str.length; switch (stringWidth.toLowerCase()) { case "wcwidth": return wcwidth(str); case "dbcs": return dbcswidth(str); case "length": return str.length; default: return str.length; } }
javascript
function getWidth(stringWidth, str) { if (!stringWidth || !stringWidth.toLowerCase) return str.length; switch (stringWidth.toLowerCase()) { case "wcwidth": return wcwidth(str); case "dbcs": return dbcswidth(str); case "length": return str.length; default: return str.length; } }
[ "function", "getWidth", "(", "stringWidth", ",", "str", ")", "{", "if", "(", "!", "stringWidth", "||", "!", "stringWidth", ".", "toLowerCase", ")", "return", "str", ".", "length", ";", "switch", "(", "stringWidth", ".", "toLowerCase", "(", ")", ")", "{", "case", "\"wcwidth\"", ":", "return", "wcwidth", "(", "str", ")", ";", "case", "\"dbcs\"", ":", "return", "dbcswidth", "(", "str", ")", ";", "case", "\"length\"", ":", "return", "str", ".", "length", ";", "default", ":", "return", "str", ".", "length", ";", "}", "}" ]
calculate width of string. @params {string} str - string to calculate @params {boolean} stringWidth - calculate width by wcwidth or String.length
[ "calculate", "width", "of", "string", "." ]
b9cb92ff43dd4374677fe3f7214c55fed04d99fd
https://github.com/Gottox/terminal.js/blob/b9cb92ff43dd4374677fe3f7214c55fed04d99fd/lib/util.js#L54-L67
18,860
Gottox/terminal.js
lib/util.js
indexOfWidth
function indexOfWidth(stringWidth, str, width) { if (stringWidth === false) return width; for (var i = 0; i <= str.length; i++) { if (getWidth(stringWidth, str.substr(0, i)) > width) return i - 1; } return str.length; }
javascript
function indexOfWidth(stringWidth, str, width) { if (stringWidth === false) return width; for (var i = 0; i <= str.length; i++) { if (getWidth(stringWidth, str.substr(0, i)) > width) return i - 1; } return str.length; }
[ "function", "indexOfWidth", "(", "stringWidth", ",", "str", ",", "width", ")", "{", "if", "(", "stringWidth", "===", "false", ")", "return", "width", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<=", "str", ".", "length", ";", "i", "++", ")", "{", "if", "(", "getWidth", "(", "stringWidth", ",", "str", ".", "substr", "(", "0", ",", "i", ")", ")", ">", "width", ")", "return", "i", "-", "1", ";", "}", "return", "str", ".", "length", ";", "}" ]
calculate the position that the prefix of string is a specific width @params {string} str - string to calculate @params {number} width - the width of target string @params {boolean} stringWidth - calculate width by wcwidth or String.length
[ "calculate", "the", "position", "that", "the", "prefix", "of", "string", "is", "a", "specific", "width" ]
b9cb92ff43dd4374677fe3f7214c55fed04d99fd
https://github.com/Gottox/terminal.js/blob/b9cb92ff43dd4374677fe3f7214c55fed04d99fd/lib/util.js#L75-L83
18,861
Gottox/terminal.js
lib/util.js
substrWidth
function substrWidth(stringWidth, str, startWidth, width) { var length = width; var start = startWidth; var prefixSpace = 0, suffixSpace; if (stringWidth !== false) { start = indexOfWidth(stringWidth, str, startWidth); if (getWidth(stringWidth, str.substr(0, start)) < startWidth) { start++; prefixSpace = getWidth(stringWidth, str.substr(0, start)) - startWidth; } length = indexOfWidth(stringWidth, str.substr(start), width - prefixSpace); suffixSpace = Math.min(width, getWidth(stringWidth, str.substr(start))) - (prefixSpace + getWidth(stringWidth, str.substr(start, length))); } return repeat(" ", prefixSpace) + str.substr(start, length) + repeat(" ", suffixSpace); }
javascript
function substrWidth(stringWidth, str, startWidth, width) { var length = width; var start = startWidth; var prefixSpace = 0, suffixSpace; if (stringWidth !== false) { start = indexOfWidth(stringWidth, str, startWidth); if (getWidth(stringWidth, str.substr(0, start)) < startWidth) { start++; prefixSpace = getWidth(stringWidth, str.substr(0, start)) - startWidth; } length = indexOfWidth(stringWidth, str.substr(start), width - prefixSpace); suffixSpace = Math.min(width, getWidth(stringWidth, str.substr(start))) - (prefixSpace + getWidth(stringWidth, str.substr(start, length))); } return repeat(" ", prefixSpace) + str.substr(start, length) + repeat(" ", suffixSpace); }
[ "function", "substrWidth", "(", "stringWidth", ",", "str", ",", "startWidth", ",", "width", ")", "{", "var", "length", "=", "width", ";", "var", "start", "=", "startWidth", ";", "var", "prefixSpace", "=", "0", ",", "suffixSpace", ";", "if", "(", "stringWidth", "!==", "false", ")", "{", "start", "=", "indexOfWidth", "(", "stringWidth", ",", "str", ",", "startWidth", ")", ";", "if", "(", "getWidth", "(", "stringWidth", ",", "str", ".", "substr", "(", "0", ",", "start", ")", ")", "<", "startWidth", ")", "{", "start", "++", ";", "prefixSpace", "=", "getWidth", "(", "stringWidth", ",", "str", ".", "substr", "(", "0", ",", "start", ")", ")", "-", "startWidth", ";", "}", "length", "=", "indexOfWidth", "(", "stringWidth", ",", "str", ".", "substr", "(", "start", ")", ",", "width", "-", "prefixSpace", ")", ";", "suffixSpace", "=", "Math", ".", "min", "(", "width", ",", "getWidth", "(", "stringWidth", ",", "str", ".", "substr", "(", "start", ")", ")", ")", "-", "(", "prefixSpace", "+", "getWidth", "(", "stringWidth", ",", "str", ".", "substr", "(", "start", ",", "length", ")", ")", ")", ";", "}", "return", "repeat", "(", "\" \"", ",", "prefixSpace", ")", "+", "str", ".", "substr", "(", "start", ",", "length", ")", "+", "repeat", "(", "\" \"", ",", "suffixSpace", ")", ";", "}" ]
extract parts of string, beginning at the character at the specified position, and returns the specified width of characters. if the character is incomplete, it will be replaced by space. @params {string} str - string to calculate @params {number} start - the beginning position of string @params {number} width - the width of target string @params {boolean} stringWidth - calculate width by wcwidth or String.length
[ "extract", "parts", "of", "string", "beginning", "at", "the", "character", "at", "the", "specified", "position", "and", "returns", "the", "specified", "width", "of", "characters", ".", "if", "the", "character", "is", "incomplete", "it", "will", "be", "replaced", "by", "space", "." ]
b9cb92ff43dd4374677fe3f7214c55fed04d99fd
https://github.com/Gottox/terminal.js/blob/b9cb92ff43dd4374677fe3f7214c55fed04d99fd/lib/util.js#L94-L109
18,862
Gottox/terminal.js
lib/terminal.js
Terminal
function Terminal(options) { Terminal.super_.call(this, { decodeStrings: false }); this.options = myUtil.extend({ columns: 80, rows: 24, attributes: {} }, options || {}); this.rows = ~~this.rows; this.columns = ~~this.columns; this.state = new TermState(this.options); this.oldChunk = null; this.on("pipe", this._pipe); }
javascript
function Terminal(options) { Terminal.super_.call(this, { decodeStrings: false }); this.options = myUtil.extend({ columns: 80, rows: 24, attributes: {} }, options || {}); this.rows = ~~this.rows; this.columns = ~~this.columns; this.state = new TermState(this.options); this.oldChunk = null; this.on("pipe", this._pipe); }
[ "function", "Terminal", "(", "options", ")", "{", "Terminal", ".", "super_", ".", "call", "(", "this", ",", "{", "decodeStrings", ":", "false", "}", ")", ";", "this", ".", "options", "=", "myUtil", ".", "extend", "(", "{", "columns", ":", "80", ",", "rows", ":", "24", ",", "attributes", ":", "{", "}", "}", ",", "options", "||", "{", "}", ")", ";", "this", ".", "rows", "=", "~", "~", "this", ".", "rows", ";", "this", ".", "columns", "=", "~", "~", "this", ".", "columns", ";", "this", ".", "state", "=", "new", "TermState", "(", "this", ".", "options", ")", ";", "this", ".", "oldChunk", "=", "null", ";", "this", ".", "on", "(", "\"pipe\"", ",", "this", ".", "_pipe", ")", ";", "}" ]
Terminal is the glue between a TerminalState and the escape sequence interpreters. @constructor
[ "Terminal", "is", "the", "glue", "between", "a", "TerminalState", "and", "the", "escape", "sequence", "interpreters", "." ]
b9cb92ff43dd4374677fe3f7214c55fed04d99fd
https://github.com/Gottox/terminal.js/blob/b9cb92ff43dd4374677fe3f7214c55fed04d99fd/lib/terminal.js#L25-L38
18,863
MikeCoder/hexo-tag-cloud
lib/tagcanvas.js
ShadowAlphaBroken
function ShadowAlphaBroken() { var cv = NewCanvas(3,3), c, i; if(!cv) return false; c = cv.getContext('2d'); c.strokeStyle = '#000'; c.shadowColor = '#fff'; c.shadowBlur = 3; c.globalAlpha = 0; c.strokeRect(2,2,2,2); c.globalAlpha = 1; i = c.getImageData(2,2,1,1); cv = null; return (i.data[0] > 0); }
javascript
function ShadowAlphaBroken() { var cv = NewCanvas(3,3), c, i; if(!cv) return false; c = cv.getContext('2d'); c.strokeStyle = '#000'; c.shadowColor = '#fff'; c.shadowBlur = 3; c.globalAlpha = 0; c.strokeRect(2,2,2,2); c.globalAlpha = 1; i = c.getImageData(2,2,1,1); cv = null; return (i.data[0] > 0); }
[ "function", "ShadowAlphaBroken", "(", ")", "{", "var", "cv", "=", "NewCanvas", "(", "3", ",", "3", ")", ",", "c", ",", "i", ";", "if", "(", "!", "cv", ")", "return", "false", ";", "c", "=", "cv", ".", "getContext", "(", "'2d'", ")", ";", "c", ".", "strokeStyle", "=", "'#000'", ";", "c", ".", "shadowColor", "=", "'#fff'", ";", "c", ".", "shadowBlur", "=", "3", ";", "c", ".", "globalAlpha", "=", "0", ";", "c", ".", "strokeRect", "(", "2", ",", "2", ",", "2", ",", "2", ")", ";", "c", ".", "globalAlpha", "=", "1", ";", "i", "=", "c", ".", "getImageData", "(", "2", ",", "2", ",", "1", ",", "1", ")", ";", "cv", "=", "null", ";", "return", "(", "i", ".", "data", "[", "0", "]", ">", "0", ")", ";", "}" ]
I think all browsers pass this test now...
[ "I", "think", "all", "browsers", "pass", "this", "test", "now", "..." ]
90cbcfa7cbffc8ab46a7502ac09e85dc9ef4dfa6
https://github.com/MikeCoder/hexo-tag-cloud/blob/90cbcfa7cbffc8ab46a7502ac09e85dc9ef4dfa6/lib/tagcanvas.js#L229-L243
18,864
MikeCoder/hexo-tag-cloud
lib/tagcanvas.js
RoundImage
function RoundImage(i, r, iw, ih, s) { var cv, c, r1 = parseFloat(r), l = max(iw, ih); cv = NewCanvas(iw, ih); if(!cv) return null; if(r.indexOf('%') > 0) r1 = l * r1 / 100; else r1 = r1 * s; c = cv.getContext('2d'); c.globalCompositeOperation = 'source-over'; c.fillStyle = '#fff'; if(r1 >= l/2) { r1 = min(iw,ih) / 2; c.beginPath(); c.moveTo(iw/2,ih/2); c.arc(iw/2,ih/2,r1,0,2*Math.PI,false); c.fill(); c.closePath(); } else { r1 = min(iw/2,ih/2,r1); RRect(c, 0, 0, iw, ih, r1, true); c.fill(); } c.globalCompositeOperation = 'source-in'; c.drawImage(i, 0, 0, iw, ih); return cv; }
javascript
function RoundImage(i, r, iw, ih, s) { var cv, c, r1 = parseFloat(r), l = max(iw, ih); cv = NewCanvas(iw, ih); if(!cv) return null; if(r.indexOf('%') > 0) r1 = l * r1 / 100; else r1 = r1 * s; c = cv.getContext('2d'); c.globalCompositeOperation = 'source-over'; c.fillStyle = '#fff'; if(r1 >= l/2) { r1 = min(iw,ih) / 2; c.beginPath(); c.moveTo(iw/2,ih/2); c.arc(iw/2,ih/2,r1,0,2*Math.PI,false); c.fill(); c.closePath(); } else { r1 = min(iw/2,ih/2,r1); RRect(c, 0, 0, iw, ih, r1, true); c.fill(); } c.globalCompositeOperation = 'source-in'; c.drawImage(i, 0, 0, iw, ih); return cv; }
[ "function", "RoundImage", "(", "i", ",", "r", ",", "iw", ",", "ih", ",", "s", ")", "{", "var", "cv", ",", "c", ",", "r1", "=", "parseFloat", "(", "r", ")", ",", "l", "=", "max", "(", "iw", ",", "ih", ")", ";", "cv", "=", "NewCanvas", "(", "iw", ",", "ih", ")", ";", "if", "(", "!", "cv", ")", "return", "null", ";", "if", "(", "r", ".", "indexOf", "(", "'%'", ")", ">", "0", ")", "r1", "=", "l", "*", "r1", "/", "100", ";", "else", "r1", "=", "r1", "*", "s", ";", "c", "=", "cv", ".", "getContext", "(", "'2d'", ")", ";", "c", ".", "globalCompositeOperation", "=", "'source-over'", ";", "c", ".", "fillStyle", "=", "'#fff'", ";", "if", "(", "r1", ">=", "l", "/", "2", ")", "{", "r1", "=", "min", "(", "iw", ",", "ih", ")", "/", "2", ";", "c", ".", "beginPath", "(", ")", ";", "c", ".", "moveTo", "(", "iw", "/", "2", ",", "ih", "/", "2", ")", ";", "c", ".", "arc", "(", "iw", "/", "2", ",", "ih", "/", "2", ",", "r1", ",", "0", ",", "2", "*", "Math", ".", "PI", ",", "false", ")", ";", "c", ".", "fill", "(", ")", ";", "c", ".", "closePath", "(", ")", ";", "}", "else", "{", "r1", "=", "min", "(", "iw", "/", "2", ",", "ih", "/", "2", ",", "r1", ")", ";", "RRect", "(", "c", ",", "0", ",", "0", ",", "iw", ",", "ih", ",", "r1", ",", "true", ")", ";", "c", ".", "fill", "(", ")", ";", "}", "c", ".", "globalCompositeOperation", "=", "'source-in'", ";", "c", ".", "drawImage", "(", "i", ",", "0", ",", "0", ",", "iw", ",", "ih", ")", ";", "return", "cv", ";", "}" ]
Rounds off the corners of an image
[ "Rounds", "off", "the", "corners", "of", "an", "image" ]
90cbcfa7cbffc8ab46a7502ac09e85dc9ef4dfa6
https://github.com/MikeCoder/hexo-tag-cloud/blob/90cbcfa7cbffc8ab46a7502ac09e85dc9ef4dfa6/lib/tagcanvas.js#L489-L516
18,865
MikeCoder/hexo-tag-cloud
lib/tagcanvas.js
AddShadowToImage
function AddShadowToImage(i, w, h, scale, sc, sb, so) { var sw = abs(so[0]), sh = abs(so[1]), cw = w + (sw > sb ? sw + sb : sb * 2) * scale, ch = h + (sh > sb ? sh + sb : sb * 2) * scale, xo = scale * ((sb || 0) + (so[0] < 0 ? sw : 0)), yo = scale * ((sb || 0) + (so[1] < 0 ? sh : 0)), cv, c; cv = NewCanvas(cw, ch); if(!cv) return null; c = cv.getContext('2d'); sc && (c.shadowColor = sc); sb && (c.shadowBlur = sb * scale); so && (c.shadowOffsetX = so[0] * scale, c.shadowOffsetY = so[1] * scale); c.drawImage(i, xo, yo, w, h); return {image: cv, width: cw / scale, height: ch / scale}; }
javascript
function AddShadowToImage(i, w, h, scale, sc, sb, so) { var sw = abs(so[0]), sh = abs(so[1]), cw = w + (sw > sb ? sw + sb : sb * 2) * scale, ch = h + (sh > sb ? sh + sb : sb * 2) * scale, xo = scale * ((sb || 0) + (so[0] < 0 ? sw : 0)), yo = scale * ((sb || 0) + (so[1] < 0 ? sh : 0)), cv, c; cv = NewCanvas(cw, ch); if(!cv) return null; c = cv.getContext('2d'); sc && (c.shadowColor = sc); sb && (c.shadowBlur = sb * scale); so && (c.shadowOffsetX = so[0] * scale, c.shadowOffsetY = so[1] * scale); c.drawImage(i, xo, yo, w, h); return {image: cv, width: cw / scale, height: ch / scale}; }
[ "function", "AddShadowToImage", "(", "i", ",", "w", ",", "h", ",", "scale", ",", "sc", ",", "sb", ",", "so", ")", "{", "var", "sw", "=", "abs", "(", "so", "[", "0", "]", ")", ",", "sh", "=", "abs", "(", "so", "[", "1", "]", ")", ",", "cw", "=", "w", "+", "(", "sw", ">", "sb", "?", "sw", "+", "sb", ":", "sb", "*", "2", ")", "*", "scale", ",", "ch", "=", "h", "+", "(", "sh", ">", "sb", "?", "sh", "+", "sb", ":", "sb", "*", "2", ")", "*", "scale", ",", "xo", "=", "scale", "*", "(", "(", "sb", "||", "0", ")", "+", "(", "so", "[", "0", "]", "<", "0", "?", "sw", ":", "0", ")", ")", ",", "yo", "=", "scale", "*", "(", "(", "sb", "||", "0", ")", "+", "(", "so", "[", "1", "]", "<", "0", "?", "sh", ":", "0", ")", ")", ",", "cv", ",", "c", ";", "cv", "=", "NewCanvas", "(", "cw", ",", "ch", ")", ";", "if", "(", "!", "cv", ")", "return", "null", ";", "c", "=", "cv", ".", "getContext", "(", "'2d'", ")", ";", "sc", "&&", "(", "c", ".", "shadowColor", "=", "sc", ")", ";", "sb", "&&", "(", "c", ".", "shadowBlur", "=", "sb", "*", "scale", ")", ";", "so", "&&", "(", "c", ".", "shadowOffsetX", "=", "so", "[", "0", "]", "*", "scale", ",", "c", ".", "shadowOffsetY", "=", "so", "[", "1", "]", "*", "scale", ")", ";", "c", ".", "drawImage", "(", "i", ",", "xo", ",", "yo", ",", "w", ",", "h", ")", ";", "return", "{", "image", ":", "cv", ",", "width", ":", "cw", "/", "scale", ",", "height", ":", "ch", "/", "scale", "}", ";", "}" ]
Creates a new canvas containing the image and its shadow Returns an object containing the image and its dimensions at z=0
[ "Creates", "a", "new", "canvas", "containing", "the", "image", "and", "its", "shadow", "Returns", "an", "object", "containing", "the", "image", "and", "its", "dimensions", "at", "z", "=", "0" ]
90cbcfa7cbffc8ab46a7502ac09e85dc9ef4dfa6
https://github.com/MikeCoder/hexo-tag-cloud/blob/90cbcfa7cbffc8ab46a7502ac09e85dc9ef4dfa6/lib/tagcanvas.js#L521-L536
18,866
webduinoio/webduino-blockly
components/blockly-src/blocks/colour.js
function() { this.jsonInit({ "message0": "%1", "args0": [ { "type": "field_colour", "name": "COLOUR", "colour": "#ff0000" } ], "output": "Colour", "colour": Blockly.Blocks.colour.HUE, "helpUrl": Blockly.Msg.COLOUR_PICKER_HELPURL }); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; // Colour block is trivial. Use tooltip of parent block if it exists. this.setTooltip(function() { var parent = thisBlock.getParent(); return (parent && parent.tooltip) || Blockly.Msg.COLOUR_PICKER_TOOLTIP; }); }
javascript
function() { this.jsonInit({ "message0": "%1", "args0": [ { "type": "field_colour", "name": "COLOUR", "colour": "#ff0000" } ], "output": "Colour", "colour": Blockly.Blocks.colour.HUE, "helpUrl": Blockly.Msg.COLOUR_PICKER_HELPURL }); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; // Colour block is trivial. Use tooltip of parent block if it exists. this.setTooltip(function() { var parent = thisBlock.getParent(); return (parent && parent.tooltip) || Blockly.Msg.COLOUR_PICKER_TOOLTIP; }); }
[ "function", "(", ")", "{", "this", ".", "jsonInit", "(", "{", "\"message0\"", ":", "\"%1\"", ",", "\"args0\"", ":", "[", "{", "\"type\"", ":", "\"field_colour\"", ",", "\"name\"", ":", "\"COLOUR\"", ",", "\"colour\"", ":", "\"#ff0000\"", "}", "]", ",", "\"output\"", ":", "\"Colour\"", ",", "\"colour\"", ":", "Blockly", ".", "Blocks", ".", "colour", ".", "HUE", ",", "\"helpUrl\"", ":", "Blockly", ".", "Msg", ".", "COLOUR_PICKER_HELPURL", "}", ")", ";", "// Assign 'this' to a variable for use in the tooltip closure below.", "var", "thisBlock", "=", "this", ";", "// Colour block is trivial. Use tooltip of parent block if it exists.", "this", ".", "setTooltip", "(", "function", "(", ")", "{", "var", "parent", "=", "thisBlock", ".", "getParent", "(", ")", ";", "return", "(", "parent", "&&", "parent", ".", "tooltip", ")", "||", "Blockly", ".", "Msg", ".", "COLOUR_PICKER_TOOLTIP", ";", "}", ")", ";", "}" ]
Block for colour picker. @this Blockly.Block
[ "Block", "for", "colour", "picker", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/colour.js#L42-L63
18,867
webduinoio/webduino-blockly
components/blockly-src/blocks/colour.js
function() { this.jsonInit({ "message0": Blockly.Msg.COLOUR_RANDOM_TITLE, "output": "Colour", "colour": Blockly.Blocks.colour.HUE, "tooltip": Blockly.Msg.COLOUR_RANDOM_TOOLTIP, "helpUrl": Blockly.Msg.COLOUR_RANDOM_HELPURL }); }
javascript
function() { this.jsonInit({ "message0": Blockly.Msg.COLOUR_RANDOM_TITLE, "output": "Colour", "colour": Blockly.Blocks.colour.HUE, "tooltip": Blockly.Msg.COLOUR_RANDOM_TOOLTIP, "helpUrl": Blockly.Msg.COLOUR_RANDOM_HELPURL }); }
[ "function", "(", ")", "{", "this", ".", "jsonInit", "(", "{", "\"message0\"", ":", "Blockly", ".", "Msg", ".", "COLOUR_RANDOM_TITLE", ",", "\"output\"", ":", "\"Colour\"", ",", "\"colour\"", ":", "Blockly", ".", "Blocks", ".", "colour", ".", "HUE", ",", "\"tooltip\"", ":", "Blockly", ".", "Msg", ".", "COLOUR_RANDOM_TOOLTIP", ",", "\"helpUrl\"", ":", "Blockly", ".", "Msg", ".", "COLOUR_RANDOM_HELPURL", "}", ")", ";", "}" ]
Block for random colour. @this Blockly.Block
[ "Block", "for", "random", "colour", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/colour.js#L71-L79
18,868
webduinoio/webduino-blockly
components/blockly-src/blocks/colour.js
function() { this.setHelpUrl(Blockly.Msg.COLOUR_RGB_HELPURL); this.setColour(Blockly.Blocks.colour.HUE); this.appendValueInput('RED') .setCheck('Number') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_RGB_TITLE) .appendField(Blockly.Msg.COLOUR_RGB_RED); this.appendValueInput('GREEN') .setCheck('Number') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_RGB_GREEN); this.appendValueInput('BLUE') .setCheck('Number') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_RGB_BLUE); this.setOutput(true, 'Colour'); this.setTooltip(Blockly.Msg.COLOUR_RGB_TOOLTIP); }
javascript
function() { this.setHelpUrl(Blockly.Msg.COLOUR_RGB_HELPURL); this.setColour(Blockly.Blocks.colour.HUE); this.appendValueInput('RED') .setCheck('Number') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_RGB_TITLE) .appendField(Blockly.Msg.COLOUR_RGB_RED); this.appendValueInput('GREEN') .setCheck('Number') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_RGB_GREEN); this.appendValueInput('BLUE') .setCheck('Number') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_RGB_BLUE); this.setOutput(true, 'Colour'); this.setTooltip(Blockly.Msg.COLOUR_RGB_TOOLTIP); }
[ "function", "(", ")", "{", "this", ".", "setHelpUrl", "(", "Blockly", ".", "Msg", ".", "COLOUR_RGB_HELPURL", ")", ";", "this", ".", "setColour", "(", "Blockly", ".", "Blocks", ".", "colour", ".", "HUE", ")", ";", "this", ".", "appendValueInput", "(", "'RED'", ")", ".", "setCheck", "(", "'Number'", ")", ".", "setAlign", "(", "Blockly", ".", "ALIGN_RIGHT", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "COLOUR_RGB_TITLE", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "COLOUR_RGB_RED", ")", ";", "this", ".", "appendValueInput", "(", "'GREEN'", ")", ".", "setCheck", "(", "'Number'", ")", ".", "setAlign", "(", "Blockly", ".", "ALIGN_RIGHT", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "COLOUR_RGB_GREEN", ")", ";", "this", ".", "appendValueInput", "(", "'BLUE'", ")", ".", "setCheck", "(", "'Number'", ")", ".", "setAlign", "(", "Blockly", ".", "ALIGN_RIGHT", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "COLOUR_RGB_BLUE", ")", ";", "this", ".", "setOutput", "(", "true", ",", "'Colour'", ")", ";", "this", ".", "setTooltip", "(", "Blockly", ".", "Msg", ".", "COLOUR_RGB_TOOLTIP", ")", ";", "}" ]
Block for composing a colour from RGB components. @this Blockly.Block
[ "Block", "for", "composing", "a", "colour", "from", "RGB", "components", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/colour.js#L87-L105
18,869
webduinoio/webduino-blockly
components/blockly-src/blocks/colour.js
function() { this.setHelpUrl(Blockly.Msg.COLOUR_BLEND_HELPURL); this.setColour(Blockly.Blocks.colour.HUE); this.appendValueInput('COLOUR1') .setCheck('Colour') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_BLEND_TITLE) .appendField(Blockly.Msg.COLOUR_BLEND_COLOUR1); this.appendValueInput('COLOUR2') .setCheck('Colour') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_BLEND_COLOUR2); this.appendValueInput('RATIO') .setCheck('Number') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_BLEND_RATIO); this.setOutput(true, 'Colour'); this.setTooltip(Blockly.Msg.COLOUR_BLEND_TOOLTIP); }
javascript
function() { this.setHelpUrl(Blockly.Msg.COLOUR_BLEND_HELPURL); this.setColour(Blockly.Blocks.colour.HUE); this.appendValueInput('COLOUR1') .setCheck('Colour') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_BLEND_TITLE) .appendField(Blockly.Msg.COLOUR_BLEND_COLOUR1); this.appendValueInput('COLOUR2') .setCheck('Colour') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_BLEND_COLOUR2); this.appendValueInput('RATIO') .setCheck('Number') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.COLOUR_BLEND_RATIO); this.setOutput(true, 'Colour'); this.setTooltip(Blockly.Msg.COLOUR_BLEND_TOOLTIP); }
[ "function", "(", ")", "{", "this", ".", "setHelpUrl", "(", "Blockly", ".", "Msg", ".", "COLOUR_BLEND_HELPURL", ")", ";", "this", ".", "setColour", "(", "Blockly", ".", "Blocks", ".", "colour", ".", "HUE", ")", ";", "this", ".", "appendValueInput", "(", "'COLOUR1'", ")", ".", "setCheck", "(", "'Colour'", ")", ".", "setAlign", "(", "Blockly", ".", "ALIGN_RIGHT", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "COLOUR_BLEND_TITLE", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "COLOUR_BLEND_COLOUR1", ")", ";", "this", ".", "appendValueInput", "(", "'COLOUR2'", ")", ".", "setCheck", "(", "'Colour'", ")", ".", "setAlign", "(", "Blockly", ".", "ALIGN_RIGHT", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "COLOUR_BLEND_COLOUR2", ")", ";", "this", ".", "appendValueInput", "(", "'RATIO'", ")", ".", "setCheck", "(", "'Number'", ")", ".", "setAlign", "(", "Blockly", ".", "ALIGN_RIGHT", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "COLOUR_BLEND_RATIO", ")", ";", "this", ".", "setOutput", "(", "true", ",", "'Colour'", ")", ";", "this", ".", "setTooltip", "(", "Blockly", ".", "Msg", ".", "COLOUR_BLEND_TOOLTIP", ")", ";", "}" ]
Block for blending two colours together. @this Blockly.Block
[ "Block", "for", "blending", "two", "colours", "together", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/colour.js#L113-L131
18,870
webduinoio/webduino-blockly
components/blockly-src/demos/blockfactory/blocks.js
function() { this.appendDummyInput() .appendField('dropdown') .appendField(new Blockly.FieldTextInput('NAME'), 'FIELDNAME'); this.optionCount_ = 3; this.updateShape_(); this.setPreviousStatement(true, 'Field'); this.setNextStatement(true, 'Field'); this.setMutator(new Blockly.Mutator(['field_dropdown_option'])); this.setColour(160); this.setTooltip('Dropdown menu with a list of options.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=386'); }
javascript
function() { this.appendDummyInput() .appendField('dropdown') .appendField(new Blockly.FieldTextInput('NAME'), 'FIELDNAME'); this.optionCount_ = 3; this.updateShape_(); this.setPreviousStatement(true, 'Field'); this.setNextStatement(true, 'Field'); this.setMutator(new Blockly.Mutator(['field_dropdown_option'])); this.setColour(160); this.setTooltip('Dropdown menu with a list of options.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=386'); }
[ "function", "(", ")", "{", "this", ".", "appendDummyInput", "(", ")", ".", "appendField", "(", "'dropdown'", ")", ".", "appendField", "(", "new", "Blockly", ".", "FieldTextInput", "(", "'NAME'", ")", ",", "'FIELDNAME'", ")", ";", "this", ".", "optionCount_", "=", "3", ";", "this", ".", "updateShape_", "(", ")", ";", "this", ".", "setPreviousStatement", "(", "true", ",", "'Field'", ")", ";", "this", ".", "setNextStatement", "(", "true", ",", "'Field'", ")", ";", "this", ".", "setMutator", "(", "new", "Blockly", ".", "Mutator", "(", "[", "'field_dropdown_option'", "]", ")", ")", ";", "this", ".", "setColour", "(", "160", ")", ";", "this", ".", "setTooltip", "(", "'Dropdown menu with a list of options.'", ")", ";", "this", ".", "setHelpUrl", "(", "'https://www.youtube.com/watch?v=s2_xaEvcVI0#t=386'", ")", ";", "}" ]
Dropdown menu.
[ "Dropdown", "menu", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/demos/blockfactory/blocks.js#L267-L279
18,871
webduinoio/webduino-blockly
components/blockly-src/demos/blockfactory/blocks.js
function() { this.setColour(160); this.appendDummyInput() .appendField('option'); this.setPreviousStatement(true); this.setNextStatement(true); this.setTooltip('Add a new option to the dropdown menu.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=386'); this.contextMenu = false; }
javascript
function() { this.setColour(160); this.appendDummyInput() .appendField('option'); this.setPreviousStatement(true); this.setNextStatement(true); this.setTooltip('Add a new option to the dropdown menu.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=386'); this.contextMenu = false; }
[ "function", "(", ")", "{", "this", ".", "setColour", "(", "160", ")", ";", "this", ".", "appendDummyInput", "(", ")", ".", "appendField", "(", "'option'", ")", ";", "this", ".", "setPreviousStatement", "(", "true", ")", ";", "this", ".", "setNextStatement", "(", "true", ")", ";", "this", ".", "setTooltip", "(", "'Add a new option to the dropdown menu.'", ")", ";", "this", ".", "setHelpUrl", "(", "'https://www.youtube.com/watch?v=s2_xaEvcVI0#t=386'", ")", ";", "this", ".", "contextMenu", "=", "false", ";", "}" ]
Add option.
[ "Add", "option", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/demos/blockfactory/blocks.js#L376-L385
18,872
webduinoio/webduino-blockly
components/blockly-src/demos/blockfactory/blocks.js
function() { this.setColour(160); this.appendDummyInput() .appendField('variable') .appendField(new Blockly.FieldTextInput('item'), 'TEXT') .appendField(',') .appendField(new Blockly.FieldTextInput('NAME'), 'FIELDNAME'); this.setPreviousStatement(true, 'Field'); this.setNextStatement(true, 'Field'); this.setTooltip('Dropdown menu for variable names.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=510'); }
javascript
function() { this.setColour(160); this.appendDummyInput() .appendField('variable') .appendField(new Blockly.FieldTextInput('item'), 'TEXT') .appendField(',') .appendField(new Blockly.FieldTextInput('NAME'), 'FIELDNAME'); this.setPreviousStatement(true, 'Field'); this.setNextStatement(true, 'Field'); this.setTooltip('Dropdown menu for variable names.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=510'); }
[ "function", "(", ")", "{", "this", ".", "setColour", "(", "160", ")", ";", "this", ".", "appendDummyInput", "(", ")", ".", "appendField", "(", "'variable'", ")", ".", "appendField", "(", "new", "Blockly", ".", "FieldTextInput", "(", "'item'", ")", ",", "'TEXT'", ")", ".", "appendField", "(", "','", ")", ".", "appendField", "(", "new", "Blockly", ".", "FieldTextInput", "(", "'NAME'", ")", ",", "'FIELDNAME'", ")", ";", "this", ".", "setPreviousStatement", "(", "true", ",", "'Field'", ")", ";", "this", ".", "setNextStatement", "(", "true", ",", "'Field'", ")", ";", "this", ".", "setTooltip", "(", "'Dropdown menu for variable names.'", ")", ";", "this", ".", "setHelpUrl", "(", "'https://www.youtube.com/watch?v=s2_xaEvcVI0#t=510'", ")", ";", "}" ]
Dropdown for variables.
[ "Dropdown", "for", "variables", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/demos/blockfactory/blocks.js#L446-L457
18,873
webduinoio/webduino-blockly
components/blockly-src/demos/blockfactory/blocks.js
function() { this.typeCount_ = 2; this.updateShape_(); this.setOutput(true, 'Type'); this.setMutator(new Blockly.Mutator(['type_group_item'])); this.setColour(230); this.setTooltip('Allows more than one type to be accepted.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=677'); }
javascript
function() { this.typeCount_ = 2; this.updateShape_(); this.setOutput(true, 'Type'); this.setMutator(new Blockly.Mutator(['type_group_item'])); this.setColour(230); this.setTooltip('Allows more than one type to be accepted.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=677'); }
[ "function", "(", ")", "{", "this", ".", "typeCount_", "=", "2", ";", "this", ".", "updateShape_", "(", ")", ";", "this", ".", "setOutput", "(", "true", ",", "'Type'", ")", ";", "this", ".", "setMutator", "(", "new", "Blockly", ".", "Mutator", "(", "[", "'type_group_item'", "]", ")", ")", ";", "this", ".", "setColour", "(", "230", ")", ";", "this", ".", "setTooltip", "(", "'Allows more than one type to be accepted.'", ")", ";", "this", ".", "setHelpUrl", "(", "'https://www.youtube.com/watch?v=s2_xaEvcVI0#t=677'", ")", ";", "}" ]
Group of types.
[ "Group", "of", "types", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/demos/blockfactory/blocks.js#L491-L499
18,874
webduinoio/webduino-blockly
components/blockly-src/demos/blockfactory/blocks.js
function() { this.appendDummyInput() .appendField('hue:') .appendField(new Blockly.FieldAngle('0', this.validator), 'HUE'); this.setOutput(true, 'Colour'); this.setTooltip('Paint the block with this colour.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=55'); }
javascript
function() { this.appendDummyInput() .appendField('hue:') .appendField(new Blockly.FieldAngle('0', this.validator), 'HUE'); this.setOutput(true, 'Colour'); this.setTooltip('Paint the block with this colour.'); this.setHelpUrl('https://www.youtube.com/watch?v=s2_xaEvcVI0#t=55'); }
[ "function", "(", ")", "{", "this", ".", "appendDummyInput", "(", ")", ".", "appendField", "(", "'hue:'", ")", ".", "appendField", "(", "new", "Blockly", ".", "FieldAngle", "(", "'0'", ",", "this", ".", "validator", ")", ",", "'HUE'", ")", ";", "this", ".", "setOutput", "(", "true", ",", "'Colour'", ")", ";", "this", ".", "setTooltip", "(", "'Paint the block with this colour.'", ")", ";", "this", ".", "setHelpUrl", "(", "'https://www.youtube.com/watch?v=s2_xaEvcVI0#t=55'", ")", ";", "}" ]
Set the colour of the block.
[ "Set", "the", "colour", "of", "the", "block", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/demos/blockfactory/blocks.js#L705-L712
18,875
webduinoio/webduino-blockly
components/blockly-src/blocks/variables.js
function() { this.setHelpUrl(Blockly.Msg.VARIABLES_GET_HELPURL); this.setColour(Blockly.Blocks.variables.HUE); this.appendDummyInput() .appendField(new Blockly.FieldVariable( Blockly.Msg.VARIABLES_DEFAULT_NAME), 'VAR'); this.setOutput(true); this.setTooltip(Blockly.Msg.VARIABLES_GET_TOOLTIP); this.contextMenuMsg_ = Blockly.Msg.VARIABLES_GET_CREATE_SET; }
javascript
function() { this.setHelpUrl(Blockly.Msg.VARIABLES_GET_HELPURL); this.setColour(Blockly.Blocks.variables.HUE); this.appendDummyInput() .appendField(new Blockly.FieldVariable( Blockly.Msg.VARIABLES_DEFAULT_NAME), 'VAR'); this.setOutput(true); this.setTooltip(Blockly.Msg.VARIABLES_GET_TOOLTIP); this.contextMenuMsg_ = Blockly.Msg.VARIABLES_GET_CREATE_SET; }
[ "function", "(", ")", "{", "this", ".", "setHelpUrl", "(", "Blockly", ".", "Msg", ".", "VARIABLES_GET_HELPURL", ")", ";", "this", ".", "setColour", "(", "Blockly", ".", "Blocks", ".", "variables", ".", "HUE", ")", ";", "this", ".", "appendDummyInput", "(", ")", ".", "appendField", "(", "new", "Blockly", ".", "FieldVariable", "(", "Blockly", ".", "Msg", ".", "VARIABLES_DEFAULT_NAME", ")", ",", "'VAR'", ")", ";", "this", ".", "setOutput", "(", "true", ")", ";", "this", ".", "setTooltip", "(", "Blockly", ".", "Msg", ".", "VARIABLES_GET_TOOLTIP", ")", ";", "this", ".", "contextMenuMsg_", "=", "Blockly", ".", "Msg", ".", "VARIABLES_GET_CREATE_SET", ";", "}" ]
Block for variable getter. @this Blockly.Block
[ "Block", "for", "variable", "getter", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/variables.js#L42-L51
18,876
webduinoio/webduino-blockly
components/blockly-src/blocks/variables.js
function() { this.jsonInit({ "message0": Blockly.Msg.VARIABLES_SET, "args0": [ { "type": "field_variable", "name": "VAR", "variable": Blockly.Msg.VARIABLES_DEFAULT_NAME }, { "type": "input_value", "name": "VALUE" } ], "previousStatement": null, "nextStatement": null, "colour": Blockly.Blocks.variables.HUE, "tooltip": Blockly.Msg.VARIABLES_SET_TOOLTIP, "helpUrl": Blockly.Msg.VARIABLES_SET_HELPURL }); this.contextMenuMsg_ = Blockly.Msg.VARIABLES_SET_CREATE_GET; }
javascript
function() { this.jsonInit({ "message0": Blockly.Msg.VARIABLES_SET, "args0": [ { "type": "field_variable", "name": "VAR", "variable": Blockly.Msg.VARIABLES_DEFAULT_NAME }, { "type": "input_value", "name": "VALUE" } ], "previousStatement": null, "nextStatement": null, "colour": Blockly.Blocks.variables.HUE, "tooltip": Blockly.Msg.VARIABLES_SET_TOOLTIP, "helpUrl": Blockly.Msg.VARIABLES_SET_HELPURL }); this.contextMenuMsg_ = Blockly.Msg.VARIABLES_SET_CREATE_GET; }
[ "function", "(", ")", "{", "this", ".", "jsonInit", "(", "{", "\"message0\"", ":", "Blockly", ".", "Msg", ".", "VARIABLES_SET", ",", "\"args0\"", ":", "[", "{", "\"type\"", ":", "\"field_variable\"", ",", "\"name\"", ":", "\"VAR\"", ",", "\"variable\"", ":", "Blockly", ".", "Msg", ".", "VARIABLES_DEFAULT_NAME", "}", ",", "{", "\"type\"", ":", "\"input_value\"", ",", "\"name\"", ":", "\"VALUE\"", "}", "]", ",", "\"previousStatement\"", ":", "null", ",", "\"nextStatement\"", ":", "null", ",", "\"colour\"", ":", "Blockly", ".", "Blocks", ".", "variables", ".", "HUE", ",", "\"tooltip\"", ":", "Blockly", ".", "Msg", ".", "VARIABLES_SET_TOOLTIP", ",", "\"helpUrl\"", ":", "Blockly", ".", "Msg", ".", "VARIABLES_SET_HELPURL", "}", ")", ";", "this", ".", "contextMenuMsg_", "=", "Blockly", ".", "Msg", ".", "VARIABLES_SET_CREATE_GET", ";", "}" ]
Block for variable setter. @this Blockly.Block
[ "Block", "for", "variable", "setter", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/variables.js#L76-L97
18,877
webduinoio/webduino-blockly
components/blockly-src/blocks/loops.js
function() { this.jsonInit({ "message0": Blockly.Msg.CONTROLS_FOR_TITLE, "args0": [ { "type": "field_variable", "name": "VAR", "variable": null }, { "type": "input_value", "name": "FROM", "check": "Number", "align": "RIGHT" }, { "type": "input_value", "name": "TO", "check": "Number", "align": "RIGHT" }, { "type": "input_value", "name": "BY", "check": "Number", "align": "RIGHT" } ], "inputsInline": true, "previousStatement": null, "nextStatement": null, "colour": Blockly.Blocks.loops.HUE, "helpUrl": Blockly.Msg.CONTROLS_FOR_HELPURL }); this.appendStatementInput('DO') .appendField(Blockly.Msg.CONTROLS_FOR_INPUT_DO); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { return Blockly.Msg.CONTROLS_FOR_TOOLTIP.replace('%1', thisBlock.getFieldValue('VAR')); }); }
javascript
function() { this.jsonInit({ "message0": Blockly.Msg.CONTROLS_FOR_TITLE, "args0": [ { "type": "field_variable", "name": "VAR", "variable": null }, { "type": "input_value", "name": "FROM", "check": "Number", "align": "RIGHT" }, { "type": "input_value", "name": "TO", "check": "Number", "align": "RIGHT" }, { "type": "input_value", "name": "BY", "check": "Number", "align": "RIGHT" } ], "inputsInline": true, "previousStatement": null, "nextStatement": null, "colour": Blockly.Blocks.loops.HUE, "helpUrl": Blockly.Msg.CONTROLS_FOR_HELPURL }); this.appendStatementInput('DO') .appendField(Blockly.Msg.CONTROLS_FOR_INPUT_DO); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { return Blockly.Msg.CONTROLS_FOR_TOOLTIP.replace('%1', thisBlock.getFieldValue('VAR')); }); }
[ "function", "(", ")", "{", "this", ".", "jsonInit", "(", "{", "\"message0\"", ":", "Blockly", ".", "Msg", ".", "CONTROLS_FOR_TITLE", ",", "\"args0\"", ":", "[", "{", "\"type\"", ":", "\"field_variable\"", ",", "\"name\"", ":", "\"VAR\"", ",", "\"variable\"", ":", "null", "}", ",", "{", "\"type\"", ":", "\"input_value\"", ",", "\"name\"", ":", "\"FROM\"", ",", "\"check\"", ":", "\"Number\"", ",", "\"align\"", ":", "\"RIGHT\"", "}", ",", "{", "\"type\"", ":", "\"input_value\"", ",", "\"name\"", ":", "\"TO\"", ",", "\"check\"", ":", "\"Number\"", ",", "\"align\"", ":", "\"RIGHT\"", "}", ",", "{", "\"type\"", ":", "\"input_value\"", ",", "\"name\"", ":", "\"BY\"", ",", "\"check\"", ":", "\"Number\"", ",", "\"align\"", ":", "\"RIGHT\"", "}", "]", ",", "\"inputsInline\"", ":", "true", ",", "\"previousStatement\"", ":", "null", ",", "\"nextStatement\"", ":", "null", ",", "\"colour\"", ":", "Blockly", ".", "Blocks", ".", "loops", ".", "HUE", ",", "\"helpUrl\"", ":", "Blockly", ".", "Msg", ".", "CONTROLS_FOR_HELPURL", "}", ")", ";", "this", ".", "appendStatementInput", "(", "'DO'", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "CONTROLS_FOR_INPUT_DO", ")", ";", "// Assign 'this' to a variable for use in the tooltip closure below.", "var", "thisBlock", "=", "this", ";", "this", ".", "setTooltip", "(", "function", "(", ")", "{", "return", "Blockly", ".", "Msg", ".", "CONTROLS_FOR_TOOLTIP", ".", "replace", "(", "'%1'", ",", "thisBlock", ".", "getFieldValue", "(", "'VAR'", ")", ")", ";", "}", ")", ";", "}" ]
Block for 'for' loop. @this Blockly.Block
[ "Block", "for", "for", "loop", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/loops.js#L128-L170
18,878
webduinoio/webduino-blockly
components/blockly-src/blocks/loops.js
function() { this.jsonInit({ "message0": Blockly.Msg.CONTROLS_FOREACH_TITLE, "args0": [ { "type": "field_variable", "name": "VAR", "variable": null }, { "type": "input_value", "name": "LIST", "check": "Array" } ], "previousStatement": null, "nextStatement": null, "colour": Blockly.Blocks.loops.HUE, "helpUrl": Blockly.Msg.CONTROLS_FOREACH_HELPURL }); this.appendStatementInput('DO') .appendField(Blockly.Msg.CONTROLS_FOREACH_INPUT_DO); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { return Blockly.Msg.CONTROLS_FOREACH_TOOLTIP.replace('%1', thisBlock.getFieldValue('VAR')); }); }
javascript
function() { this.jsonInit({ "message0": Blockly.Msg.CONTROLS_FOREACH_TITLE, "args0": [ { "type": "field_variable", "name": "VAR", "variable": null }, { "type": "input_value", "name": "LIST", "check": "Array" } ], "previousStatement": null, "nextStatement": null, "colour": Blockly.Blocks.loops.HUE, "helpUrl": Blockly.Msg.CONTROLS_FOREACH_HELPURL }); this.appendStatementInput('DO') .appendField(Blockly.Msg.CONTROLS_FOREACH_INPUT_DO); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { return Blockly.Msg.CONTROLS_FOREACH_TOOLTIP.replace('%1', thisBlock.getFieldValue('VAR')); }); }
[ "function", "(", ")", "{", "this", ".", "jsonInit", "(", "{", "\"message0\"", ":", "Blockly", ".", "Msg", ".", "CONTROLS_FOREACH_TITLE", ",", "\"args0\"", ":", "[", "{", "\"type\"", ":", "\"field_variable\"", ",", "\"name\"", ":", "\"VAR\"", ",", "\"variable\"", ":", "null", "}", ",", "{", "\"type\"", ":", "\"input_value\"", ",", "\"name\"", ":", "\"LIST\"", ",", "\"check\"", ":", "\"Array\"", "}", "]", ",", "\"previousStatement\"", ":", "null", ",", "\"nextStatement\"", ":", "null", ",", "\"colour\"", ":", "Blockly", ".", "Blocks", ".", "loops", ".", "HUE", ",", "\"helpUrl\"", ":", "Blockly", ".", "Msg", ".", "CONTROLS_FOREACH_HELPURL", "}", ")", ";", "this", ".", "appendStatementInput", "(", "'DO'", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "CONTROLS_FOREACH_INPUT_DO", ")", ";", "// Assign 'this' to a variable for use in the tooltip closure below.", "var", "thisBlock", "=", "this", ";", "this", ".", "setTooltip", "(", "function", "(", ")", "{", "return", "Blockly", ".", "Msg", ".", "CONTROLS_FOREACH_TOOLTIP", ".", "replace", "(", "'%1'", ",", "thisBlock", ".", "getFieldValue", "(", "'VAR'", ")", ")", ";", "}", ")", ";", "}" ]
Block for 'for each' loop. @this Blockly.Block
[ "Block", "for", "for", "each", "loop", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/loops.js#L196-L224
18,879
webduinoio/webduino-blockly
components/blockly-src/demos/plane/plane.js
updateBlocks
function updateBlocks(blocks) { for (var i = 0, block; block = blocks[i]; i++) { block.customUpdate && block.customUpdate(); } }
javascript
function updateBlocks(blocks) { for (var i = 0, block; block = blocks[i]; i++) { block.customUpdate && block.customUpdate(); } }
[ "function", "updateBlocks", "(", "blocks", ")", "{", "for", "(", "var", "i", "=", "0", ",", "block", ";", "block", "=", "blocks", "[", "i", "]", ";", "i", "++", ")", "{", "block", ".", "customUpdate", "&&", "block", ".", "customUpdate", "(", ")", ";", "}", "}" ]
Update blocks to show values.
[ "Update", "blocks", "to", "show", "values", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/demos/plane/plane.js#L357-L361
18,880
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function(hasStatements) { if (this.hasStatements_ === hasStatements) { return; } if (hasStatements) { this.appendStatementInput('STACK') .appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_DO); if (this.getInput('RETURN')) { this.moveInputBefore('STACK', 'RETURN'); } } else { this.removeInput('STACK', true); } this.hasStatements_ = hasStatements; }
javascript
function(hasStatements) { if (this.hasStatements_ === hasStatements) { return; } if (hasStatements) { this.appendStatementInput('STACK') .appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_DO); if (this.getInput('RETURN')) { this.moveInputBefore('STACK', 'RETURN'); } } else { this.removeInput('STACK', true); } this.hasStatements_ = hasStatements; }
[ "function", "(", "hasStatements", ")", "{", "if", "(", "this", ".", "hasStatements_", "===", "hasStatements", ")", "{", "return", ";", "}", "if", "(", "hasStatements", ")", "{", "this", ".", "appendStatementInput", "(", "'STACK'", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_DEFNORETURN_DO", ")", ";", "if", "(", "this", ".", "getInput", "(", "'RETURN'", ")", ")", "{", "this", ".", "moveInputBefore", "(", "'STACK'", ",", "'RETURN'", ")", ";", "}", "}", "else", "{", "this", ".", "removeInput", "(", "'STACK'", ",", "true", ")", ";", "}", "this", ".", "hasStatements_", "=", "hasStatements", ";", "}" ]
Add or remove the statement block from this function definition. @param {boolean} hasStatements True if a statement block is needed. @this Blockly.Block
[ "Add", "or", "remove", "the", "statement", "block", "from", "this", "function", "definition", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L77-L91
18,881
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function() { // Check for duplicated arguments. var badArg = false; var hash = {}; for (var i = 0; i < this.arguments_.length; i++) { if (hash['arg_' + this.arguments_[i].toLowerCase()]) { badArg = true; break; } hash['arg_' + this.arguments_[i].toLowerCase()] = true; } if (badArg) { this.setWarningText(Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING); } else { this.setWarningText(null); } // Merge the arguments into a human-readable list. var paramString = ''; if (this.arguments_.length) { paramString = Blockly.Msg.PROCEDURES_BEFORE_PARAMS + ' ' + this.arguments_.join(', '); } // The params field is deterministic based on the mutation, // no need to fire a change event. Blockly.Events.disable(); this.setFieldValue(paramString, 'PARAMS'); Blockly.Events.enable(); }
javascript
function() { // Check for duplicated arguments. var badArg = false; var hash = {}; for (var i = 0; i < this.arguments_.length; i++) { if (hash['arg_' + this.arguments_[i].toLowerCase()]) { badArg = true; break; } hash['arg_' + this.arguments_[i].toLowerCase()] = true; } if (badArg) { this.setWarningText(Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING); } else { this.setWarningText(null); } // Merge the arguments into a human-readable list. var paramString = ''; if (this.arguments_.length) { paramString = Blockly.Msg.PROCEDURES_BEFORE_PARAMS + ' ' + this.arguments_.join(', '); } // The params field is deterministic based on the mutation, // no need to fire a change event. Blockly.Events.disable(); this.setFieldValue(paramString, 'PARAMS'); Blockly.Events.enable(); }
[ "function", "(", ")", "{", "// Check for duplicated arguments.", "var", "badArg", "=", "false", ";", "var", "hash", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "arguments_", ".", "length", ";", "i", "++", ")", "{", "if", "(", "hash", "[", "'arg_'", "+", "this", ".", "arguments_", "[", "i", "]", ".", "toLowerCase", "(", ")", "]", ")", "{", "badArg", "=", "true", ";", "break", ";", "}", "hash", "[", "'arg_'", "+", "this", ".", "arguments_", "[", "i", "]", ".", "toLowerCase", "(", ")", "]", "=", "true", ";", "}", "if", "(", "badArg", ")", "{", "this", ".", "setWarningText", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_DEF_DUPLICATE_WARNING", ")", ";", "}", "else", "{", "this", ".", "setWarningText", "(", "null", ")", ";", "}", "// Merge the arguments into a human-readable list.", "var", "paramString", "=", "''", ";", "if", "(", "this", ".", "arguments_", ".", "length", ")", "{", "paramString", "=", "Blockly", ".", "Msg", ".", "PROCEDURES_BEFORE_PARAMS", "+", "' '", "+", "this", ".", "arguments_", ".", "join", "(", "', '", ")", ";", "}", "// The params field is deterministic based on the mutation,", "// no need to fire a change event.", "Blockly", ".", "Events", ".", "disable", "(", ")", ";", "this", ".", "setFieldValue", "(", "paramString", ",", "'PARAMS'", ")", ";", "Blockly", ".", "Events", ".", "enable", "(", ")", ";", "}" ]
Update the display of parameters for this procedure definition block. Display a warning if there are duplicately named parameters. @private @this Blockly.Block
[ "Update", "the", "display", "of", "parameters", "for", "this", "procedure", "definition", "block", ".", "Display", "a", "warning", "if", "there", "are", "duplicately", "named", "parameters", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L98-L125
18,882
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function(opt_paramIds) { var container = document.createElement('mutation'); if (opt_paramIds) { container.setAttribute('name', this.getFieldValue('NAME')); } for (var i = 0; i < this.arguments_.length; i++) { var parameter = document.createElement('arg'); parameter.setAttribute('name', this.arguments_[i]); if (opt_paramIds && this.paramIds_) { parameter.setAttribute('paramId', this.paramIds_[i]); } container.appendChild(parameter); } // Save whether the statement input is visible. if (!this.hasStatements_) { container.setAttribute('statements', 'false'); } return container; }
javascript
function(opt_paramIds) { var container = document.createElement('mutation'); if (opt_paramIds) { container.setAttribute('name', this.getFieldValue('NAME')); } for (var i = 0; i < this.arguments_.length; i++) { var parameter = document.createElement('arg'); parameter.setAttribute('name', this.arguments_[i]); if (opt_paramIds && this.paramIds_) { parameter.setAttribute('paramId', this.paramIds_[i]); } container.appendChild(parameter); } // Save whether the statement input is visible. if (!this.hasStatements_) { container.setAttribute('statements', 'false'); } return container; }
[ "function", "(", "opt_paramIds", ")", "{", "var", "container", "=", "document", ".", "createElement", "(", "'mutation'", ")", ";", "if", "(", "opt_paramIds", ")", "{", "container", ".", "setAttribute", "(", "'name'", ",", "this", ".", "getFieldValue", "(", "'NAME'", ")", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "arguments_", ".", "length", ";", "i", "++", ")", "{", "var", "parameter", "=", "document", ".", "createElement", "(", "'arg'", ")", ";", "parameter", ".", "setAttribute", "(", "'name'", ",", "this", ".", "arguments_", "[", "i", "]", ")", ";", "if", "(", "opt_paramIds", "&&", "this", ".", "paramIds_", ")", "{", "parameter", ".", "setAttribute", "(", "'paramId'", ",", "this", ".", "paramIds_", "[", "i", "]", ")", ";", "}", "container", ".", "appendChild", "(", "parameter", ")", ";", "}", "// Save whether the statement input is visible.", "if", "(", "!", "this", ".", "hasStatements_", ")", "{", "container", ".", "setAttribute", "(", "'statements'", ",", "'false'", ")", ";", "}", "return", "container", ";", "}" ]
Create XML to represent the argument inputs. @param {=boolean} opt_paramIds If true include the IDs of the parameter quarks. Used by Blockly.Procedures.mutateCallers for reconnection. @return {!Element} XML storage element. @this Blockly.Block
[ "Create", "XML", "to", "represent", "the", "argument", "inputs", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L133-L152
18,883
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function(xmlElement) { this.arguments_ = []; for (var i = 0, childNode; childNode = xmlElement.childNodes[i]; i++) { if (childNode.nodeName.toLowerCase() == 'arg') { this.arguments_.push(childNode.getAttribute('name')); } } this.updateParams_(); Blockly.Procedures.mutateCallers(this); // Show or hide the statement input. this.setStatements_(xmlElement.getAttribute('statements') !== 'false'); }
javascript
function(xmlElement) { this.arguments_ = []; for (var i = 0, childNode; childNode = xmlElement.childNodes[i]; i++) { if (childNode.nodeName.toLowerCase() == 'arg') { this.arguments_.push(childNode.getAttribute('name')); } } this.updateParams_(); Blockly.Procedures.mutateCallers(this); // Show or hide the statement input. this.setStatements_(xmlElement.getAttribute('statements') !== 'false'); }
[ "function", "(", "xmlElement", ")", "{", "this", ".", "arguments_", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "childNode", ";", "childNode", "=", "xmlElement", ".", "childNodes", "[", "i", "]", ";", "i", "++", ")", "{", "if", "(", "childNode", ".", "nodeName", ".", "toLowerCase", "(", ")", "==", "'arg'", ")", "{", "this", ".", "arguments_", ".", "push", "(", "childNode", ".", "getAttribute", "(", "'name'", ")", ")", ";", "}", "}", "this", ".", "updateParams_", "(", ")", ";", "Blockly", ".", "Procedures", ".", "mutateCallers", "(", "this", ")", ";", "// Show or hide the statement input.", "this", ".", "setStatements_", "(", "xmlElement", ".", "getAttribute", "(", "'statements'", ")", "!==", "'false'", ")", ";", "}" ]
Parse XML to restore the argument inputs. @param {!Element} xmlElement XML storage element. @this Blockly.Block
[ "Parse", "XML", "to", "restore", "the", "argument", "inputs", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L158-L170
18,884
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function(options) { // Add option to create caller. var option = {enabled: true}; var name = this.getFieldValue('NAME'); option.text = Blockly.Msg.PROCEDURES_CREATE_DO.replace('%1', name); var xmlMutation = goog.dom.createDom('mutation'); xmlMutation.setAttribute('name', name); for (var i = 0; i < this.arguments_.length; i++) { var xmlArg = goog.dom.createDom('arg'); xmlArg.setAttribute('name', this.arguments_[i]); xmlMutation.appendChild(xmlArg); } var xmlBlock = goog.dom.createDom('block', null, xmlMutation); xmlBlock.setAttribute('type', this.callType_); option.callback = Blockly.ContextMenu.callbackFactory(this, xmlBlock); options.push(option); // Add options to create getters for each parameter. if (!this.isCollapsed()) { for (var i = 0; i < this.arguments_.length; i++) { var option = {enabled: true}; var name = this.arguments_[i]; option.text = Blockly.Msg.VARIABLES_SET_CREATE_GET.replace('%1', name); var xmlField = goog.dom.createDom('field', null, name); xmlField.setAttribute('name', 'VAR'); var xmlBlock = goog.dom.createDom('block', null, xmlField); xmlBlock.setAttribute('type', 'variables_get'); option.callback = Blockly.ContextMenu.callbackFactory(this, xmlBlock); options.push(option); } } }
javascript
function(options) { // Add option to create caller. var option = {enabled: true}; var name = this.getFieldValue('NAME'); option.text = Blockly.Msg.PROCEDURES_CREATE_DO.replace('%1', name); var xmlMutation = goog.dom.createDom('mutation'); xmlMutation.setAttribute('name', name); for (var i = 0; i < this.arguments_.length; i++) { var xmlArg = goog.dom.createDom('arg'); xmlArg.setAttribute('name', this.arguments_[i]); xmlMutation.appendChild(xmlArg); } var xmlBlock = goog.dom.createDom('block', null, xmlMutation); xmlBlock.setAttribute('type', this.callType_); option.callback = Blockly.ContextMenu.callbackFactory(this, xmlBlock); options.push(option); // Add options to create getters for each parameter. if (!this.isCollapsed()) { for (var i = 0; i < this.arguments_.length; i++) { var option = {enabled: true}; var name = this.arguments_[i]; option.text = Blockly.Msg.VARIABLES_SET_CREATE_GET.replace('%1', name); var xmlField = goog.dom.createDom('field', null, name); xmlField.setAttribute('name', 'VAR'); var xmlBlock = goog.dom.createDom('block', null, xmlField); xmlBlock.setAttribute('type', 'variables_get'); option.callback = Blockly.ContextMenu.callbackFactory(this, xmlBlock); options.push(option); } } }
[ "function", "(", "options", ")", "{", "// Add option to create caller.", "var", "option", "=", "{", "enabled", ":", "true", "}", ";", "var", "name", "=", "this", ".", "getFieldValue", "(", "'NAME'", ")", ";", "option", ".", "text", "=", "Blockly", ".", "Msg", ".", "PROCEDURES_CREATE_DO", ".", "replace", "(", "'%1'", ",", "name", ")", ";", "var", "xmlMutation", "=", "goog", ".", "dom", ".", "createDom", "(", "'mutation'", ")", ";", "xmlMutation", ".", "setAttribute", "(", "'name'", ",", "name", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "arguments_", ".", "length", ";", "i", "++", ")", "{", "var", "xmlArg", "=", "goog", ".", "dom", ".", "createDom", "(", "'arg'", ")", ";", "xmlArg", ".", "setAttribute", "(", "'name'", ",", "this", ".", "arguments_", "[", "i", "]", ")", ";", "xmlMutation", ".", "appendChild", "(", "xmlArg", ")", ";", "}", "var", "xmlBlock", "=", "goog", ".", "dom", ".", "createDom", "(", "'block'", ",", "null", ",", "xmlMutation", ")", ";", "xmlBlock", ".", "setAttribute", "(", "'type'", ",", "this", ".", "callType_", ")", ";", "option", ".", "callback", "=", "Blockly", ".", "ContextMenu", ".", "callbackFactory", "(", "this", ",", "xmlBlock", ")", ";", "options", ".", "push", "(", "option", ")", ";", "// Add options to create getters for each parameter.", "if", "(", "!", "this", ".", "isCollapsed", "(", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "arguments_", ".", "length", ";", "i", "++", ")", "{", "var", "option", "=", "{", "enabled", ":", "true", "}", ";", "var", "name", "=", "this", ".", "arguments_", "[", "i", "]", ";", "option", ".", "text", "=", "Blockly", ".", "Msg", ".", "VARIABLES_SET_CREATE_GET", ".", "replace", "(", "'%1'", ",", "name", ")", ";", "var", "xmlField", "=", "goog", ".", "dom", ".", "createDom", "(", "'field'", ",", "null", ",", "name", ")", ";", "xmlField", ".", "setAttribute", "(", "'name'", ",", "'VAR'", ")", ";", "var", "xmlBlock", "=", "goog", ".", "dom", ".", "createDom", "(", "'block'", ",", "null", ",", "xmlField", ")", ";", "xmlBlock", ".", "setAttribute", "(", "'type'", ",", "'variables_get'", ")", ";", "option", ".", "callback", "=", "Blockly", ".", "ContextMenu", ".", "callbackFactory", "(", "this", ",", "xmlBlock", ")", ";", "options", ".", "push", "(", "option", ")", ";", "}", "}", "}" ]
Add custom menu options to this block's context menu. @param {!Array} options List of menu options to add to. @this Blockly.Block
[ "Add", "custom", "menu", "options", "to", "this", "block", "s", "context", "menu", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L310-L341
18,885
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function() { var nameField = new Blockly.FieldTextInput( Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE, Blockly.Procedures.rename); nameField.setSpellcheck(false); this.appendDummyInput() .appendField(Blockly.Msg.PROCEDURES_DEFRETURN_TITLE) .appendField(nameField, 'NAME') .appendField('', 'PARAMS'); this.appendValueInput('RETURN') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN); this.setMutator(new Blockly.Mutator(['procedures_mutatorarg'])); if (Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT) { this.setCommentText(Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT); } this.setColour(Blockly.Blocks.procedures.HUE); this.setTooltip(Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP); this.setHelpUrl(Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL); this.arguments_ = []; this.setStatements_(true); this.statementConnection_ = null; }
javascript
function() { var nameField = new Blockly.FieldTextInput( Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE, Blockly.Procedures.rename); nameField.setSpellcheck(false); this.appendDummyInput() .appendField(Blockly.Msg.PROCEDURES_DEFRETURN_TITLE) .appendField(nameField, 'NAME') .appendField('', 'PARAMS'); this.appendValueInput('RETURN') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN); this.setMutator(new Blockly.Mutator(['procedures_mutatorarg'])); if (Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT) { this.setCommentText(Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT); } this.setColour(Blockly.Blocks.procedures.HUE); this.setTooltip(Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP); this.setHelpUrl(Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL); this.arguments_ = []; this.setStatements_(true); this.statementConnection_ = null; }
[ "function", "(", ")", "{", "var", "nameField", "=", "new", "Blockly", ".", "FieldTextInput", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_DEFRETURN_PROCEDURE", ",", "Blockly", ".", "Procedures", ".", "rename", ")", ";", "nameField", ".", "setSpellcheck", "(", "false", ")", ";", "this", ".", "appendDummyInput", "(", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_DEFRETURN_TITLE", ")", ".", "appendField", "(", "nameField", ",", "'NAME'", ")", ".", "appendField", "(", "''", ",", "'PARAMS'", ")", ";", "this", ".", "appendValueInput", "(", "'RETURN'", ")", ".", "setAlign", "(", "Blockly", ".", "ALIGN_RIGHT", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_DEFRETURN_RETURN", ")", ";", "this", ".", "setMutator", "(", "new", "Blockly", ".", "Mutator", "(", "[", "'procedures_mutatorarg'", "]", ")", ")", ";", "if", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_DEFRETURN_COMMENT", ")", "{", "this", ".", "setCommentText", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_DEFRETURN_COMMENT", ")", ";", "}", "this", ".", "setColour", "(", "Blockly", ".", "Blocks", ".", "procedures", ".", "HUE", ")", ";", "this", ".", "setTooltip", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_DEFRETURN_TOOLTIP", ")", ";", "this", ".", "setHelpUrl", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_DEFRETURN_HELPURL", ")", ";", "this", ".", "arguments_", "=", "[", "]", ";", "this", ".", "setStatements_", "(", "true", ")", ";", "this", ".", "statementConnection_", "=", "null", ";", "}" ]
Block for defining a procedure with a return value. @this Blockly.Block
[ "Block", "for", "defining", "a", "procedure", "with", "a", "return", "value", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L350-L372
18,886
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function() { this.appendDummyInput() .appendField(Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE); this.appendStatementInput('STACK'); this.appendDummyInput('STATEMENT_INPUT') .appendField(Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS) .appendField(new Blockly.FieldCheckbox('TRUE'), 'STATEMENTS'); this.setColour(Blockly.Blocks.procedures.HUE); this.setTooltip(Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP); this.contextMenu = false; }
javascript
function() { this.appendDummyInput() .appendField(Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE); this.appendStatementInput('STACK'); this.appendDummyInput('STATEMENT_INPUT') .appendField(Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS) .appendField(new Blockly.FieldCheckbox('TRUE'), 'STATEMENTS'); this.setColour(Blockly.Blocks.procedures.HUE); this.setTooltip(Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP); this.contextMenu = false; }
[ "function", "(", ")", "{", "this", ".", "appendDummyInput", "(", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_MUTATORCONTAINER_TITLE", ")", ";", "this", ".", "appendStatementInput", "(", "'STACK'", ")", ";", "this", ".", "appendDummyInput", "(", "'STATEMENT_INPUT'", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_ALLOW_STATEMENTS", ")", ".", "appendField", "(", "new", "Blockly", ".", "FieldCheckbox", "(", "'TRUE'", ")", ",", "'STATEMENTS'", ")", ";", "this", ".", "setColour", "(", "Blockly", ".", "Blocks", ".", "procedures", ".", "HUE", ")", ";", "this", ".", "setTooltip", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_MUTATORCONTAINER_TOOLTIP", ")", ";", "this", ".", "contextMenu", "=", "false", ";", "}" ]
Mutator block for procedure container. @this Blockly.Block
[ "Mutator", "block", "for", "procedure", "container", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L403-L413
18,887
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function(oldName, newName) { if (Blockly.Names.equals(oldName, this.getProcedureCall())) { this.setFieldValue(newName, 'NAME'); this.setTooltip( (this.outputConnection ? Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP : Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP) .replace('%1', newName)); } }
javascript
function(oldName, newName) { if (Blockly.Names.equals(oldName, this.getProcedureCall())) { this.setFieldValue(newName, 'NAME'); this.setTooltip( (this.outputConnection ? Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP : Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP) .replace('%1', newName)); } }
[ "function", "(", "oldName", ",", "newName", ")", "{", "if", "(", "Blockly", ".", "Names", ".", "equals", "(", "oldName", ",", "this", ".", "getProcedureCall", "(", ")", ")", ")", "{", "this", ".", "setFieldValue", "(", "newName", ",", "'NAME'", ")", ";", "this", ".", "setTooltip", "(", "(", "this", ".", "outputConnection", "?", "Blockly", ".", "Msg", ".", "PROCEDURES_CALLRETURN_TOOLTIP", ":", "Blockly", ".", "Msg", ".", "PROCEDURES_CALLNORETURN_TOOLTIP", ")", ".", "replace", "(", "'%1'", ",", "newName", ")", ")", ";", "}", "}" ]
Notification that a procedure is renaming. If the name matches this block's procedure, rename it. @param {string} oldName Previous name of procedure. @param {string} newName Renamed procedure. @this Blockly.Block
[ "Notification", "that", "a", "procedure", "is", "renaming", ".", "If", "the", "name", "matches", "this", "block", "s", "procedure", "rename", "it", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L479-L487
18,888
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function(paramNames, paramIds) { // Data structures: // this.arguments = ['x', 'y'] // Existing param names. // this.quarkConnections_ {piua: null, f8b_: Blockly.Connection} // Look-up of paramIds to connections plugged into the call block. // this.quarkIds_ = ['piua', 'f8b_'] // Existing param IDs. // Note that quarkConnections_ may include IDs that no longer exist, but // which might reappear if a param is reattached in the mutator. var defBlock = Blockly.Procedures.getDefinition(this.getProcedureCall(), this.workspace); var mutatorOpen = defBlock && defBlock.mutator && defBlock.mutator.isVisible(); if (!mutatorOpen) { this.quarkConnections_ = {}; this.quarkIds_ = null; } if (!paramIds) { // Reset the quarks (a mutator is about to open). return; } if (goog.array.equals(this.arguments_, paramNames)) { // No change. this.quarkIds_ = paramIds; return; } if (paramIds.length != paramNames.length) { throw 'Error: paramNames and paramIds must be the same length.'; } this.setCollapsed(false); if (!this.quarkIds_) { // Initialize tracking for this block. this.quarkConnections_ = {}; if (paramNames.join('\n') == this.arguments_.join('\n')) { // No change to the parameters, allow quarkConnections_ to be // populated with the existing connections. this.quarkIds_ = paramIds; } else { this.quarkIds_ = []; } } // Switch off rendering while the block is rebuilt. var savedRendered = this.rendered; this.rendered = false; // Update the quarkConnections_ with existing connections. for (var i = 0; i < this.arguments_.length; i++) { var input = this.getInput('ARG' + i); if (input) { var connection = input.connection.targetConnection; this.quarkConnections_[this.quarkIds_[i]] = connection; if (mutatorOpen && connection && paramIds.indexOf(this.quarkIds_[i]) == -1) { // This connection should no longer be attached to this block. connection.disconnect(); connection.getSourceBlock().bumpNeighbours_(); } } } // Rebuild the block's arguments. this.arguments_ = [].concat(paramNames); this.updateShape_(); this.quarkIds_ = paramIds; // Reconnect any child blocks. if (this.quarkIds_) { for (var i = 0; i < this.arguments_.length; i++) { var quarkId = this.quarkIds_[i]; if (quarkId in this.quarkConnections_) { var connection = this.quarkConnections_[quarkId]; if (!Blockly.Mutator.reconnect(connection, this, 'ARG' + i)) { // Block no longer exists or has been attached elsewhere. delete this.quarkConnections_[quarkId]; } } } } // Restore rendering and show the changes. this.rendered = savedRendered; if (this.rendered) { this.render(); } }
javascript
function(paramNames, paramIds) { // Data structures: // this.arguments = ['x', 'y'] // Existing param names. // this.quarkConnections_ {piua: null, f8b_: Blockly.Connection} // Look-up of paramIds to connections plugged into the call block. // this.quarkIds_ = ['piua', 'f8b_'] // Existing param IDs. // Note that quarkConnections_ may include IDs that no longer exist, but // which might reappear if a param is reattached in the mutator. var defBlock = Blockly.Procedures.getDefinition(this.getProcedureCall(), this.workspace); var mutatorOpen = defBlock && defBlock.mutator && defBlock.mutator.isVisible(); if (!mutatorOpen) { this.quarkConnections_ = {}; this.quarkIds_ = null; } if (!paramIds) { // Reset the quarks (a mutator is about to open). return; } if (goog.array.equals(this.arguments_, paramNames)) { // No change. this.quarkIds_ = paramIds; return; } if (paramIds.length != paramNames.length) { throw 'Error: paramNames and paramIds must be the same length.'; } this.setCollapsed(false); if (!this.quarkIds_) { // Initialize tracking for this block. this.quarkConnections_ = {}; if (paramNames.join('\n') == this.arguments_.join('\n')) { // No change to the parameters, allow quarkConnections_ to be // populated with the existing connections. this.quarkIds_ = paramIds; } else { this.quarkIds_ = []; } } // Switch off rendering while the block is rebuilt. var savedRendered = this.rendered; this.rendered = false; // Update the quarkConnections_ with existing connections. for (var i = 0; i < this.arguments_.length; i++) { var input = this.getInput('ARG' + i); if (input) { var connection = input.connection.targetConnection; this.quarkConnections_[this.quarkIds_[i]] = connection; if (mutatorOpen && connection && paramIds.indexOf(this.quarkIds_[i]) == -1) { // This connection should no longer be attached to this block. connection.disconnect(); connection.getSourceBlock().bumpNeighbours_(); } } } // Rebuild the block's arguments. this.arguments_ = [].concat(paramNames); this.updateShape_(); this.quarkIds_ = paramIds; // Reconnect any child blocks. if (this.quarkIds_) { for (var i = 0; i < this.arguments_.length; i++) { var quarkId = this.quarkIds_[i]; if (quarkId in this.quarkConnections_) { var connection = this.quarkConnections_[quarkId]; if (!Blockly.Mutator.reconnect(connection, this, 'ARG' + i)) { // Block no longer exists or has been attached elsewhere. delete this.quarkConnections_[quarkId]; } } } } // Restore rendering and show the changes. this.rendered = savedRendered; if (this.rendered) { this.render(); } }
[ "function", "(", "paramNames", ",", "paramIds", ")", "{", "// Data structures:", "// this.arguments = ['x', 'y']", "// Existing param names.", "// this.quarkConnections_ {piua: null, f8b_: Blockly.Connection}", "// Look-up of paramIds to connections plugged into the call block.", "// this.quarkIds_ = ['piua', 'f8b_']", "// Existing param IDs.", "// Note that quarkConnections_ may include IDs that no longer exist, but", "// which might reappear if a param is reattached in the mutator.", "var", "defBlock", "=", "Blockly", ".", "Procedures", ".", "getDefinition", "(", "this", ".", "getProcedureCall", "(", ")", ",", "this", ".", "workspace", ")", ";", "var", "mutatorOpen", "=", "defBlock", "&&", "defBlock", ".", "mutator", "&&", "defBlock", ".", "mutator", ".", "isVisible", "(", ")", ";", "if", "(", "!", "mutatorOpen", ")", "{", "this", ".", "quarkConnections_", "=", "{", "}", ";", "this", ".", "quarkIds_", "=", "null", ";", "}", "if", "(", "!", "paramIds", ")", "{", "// Reset the quarks (a mutator is about to open).", "return", ";", "}", "if", "(", "goog", ".", "array", ".", "equals", "(", "this", ".", "arguments_", ",", "paramNames", ")", ")", "{", "// No change.", "this", ".", "quarkIds_", "=", "paramIds", ";", "return", ";", "}", "if", "(", "paramIds", ".", "length", "!=", "paramNames", ".", "length", ")", "{", "throw", "'Error: paramNames and paramIds must be the same length.'", ";", "}", "this", ".", "setCollapsed", "(", "false", ")", ";", "if", "(", "!", "this", ".", "quarkIds_", ")", "{", "// Initialize tracking for this block.", "this", ".", "quarkConnections_", "=", "{", "}", ";", "if", "(", "paramNames", ".", "join", "(", "'\\n'", ")", "==", "this", ".", "arguments_", ".", "join", "(", "'\\n'", ")", ")", "{", "// No change to the parameters, allow quarkConnections_ to be", "// populated with the existing connections.", "this", ".", "quarkIds_", "=", "paramIds", ";", "}", "else", "{", "this", ".", "quarkIds_", "=", "[", "]", ";", "}", "}", "// Switch off rendering while the block is rebuilt.", "var", "savedRendered", "=", "this", ".", "rendered", ";", "this", ".", "rendered", "=", "false", ";", "// Update the quarkConnections_ with existing connections.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "arguments_", ".", "length", ";", "i", "++", ")", "{", "var", "input", "=", "this", ".", "getInput", "(", "'ARG'", "+", "i", ")", ";", "if", "(", "input", ")", "{", "var", "connection", "=", "input", ".", "connection", ".", "targetConnection", ";", "this", ".", "quarkConnections_", "[", "this", ".", "quarkIds_", "[", "i", "]", "]", "=", "connection", ";", "if", "(", "mutatorOpen", "&&", "connection", "&&", "paramIds", ".", "indexOf", "(", "this", ".", "quarkIds_", "[", "i", "]", ")", "==", "-", "1", ")", "{", "// This connection should no longer be attached to this block.", "connection", ".", "disconnect", "(", ")", ";", "connection", ".", "getSourceBlock", "(", ")", ".", "bumpNeighbours_", "(", ")", ";", "}", "}", "}", "// Rebuild the block's arguments.", "this", ".", "arguments_", "=", "[", "]", ".", "concat", "(", "paramNames", ")", ";", "this", ".", "updateShape_", "(", ")", ";", "this", ".", "quarkIds_", "=", "paramIds", ";", "// Reconnect any child blocks.", "if", "(", "this", ".", "quarkIds_", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "arguments_", ".", "length", ";", "i", "++", ")", "{", "var", "quarkId", "=", "this", ".", "quarkIds_", "[", "i", "]", ";", "if", "(", "quarkId", "in", "this", ".", "quarkConnections_", ")", "{", "var", "connection", "=", "this", ".", "quarkConnections_", "[", "quarkId", "]", ";", "if", "(", "!", "Blockly", ".", "Mutator", ".", "reconnect", "(", "connection", ",", "this", ",", "'ARG'", "+", "i", ")", ")", "{", "// Block no longer exists or has been attached elsewhere.", "delete", "this", ".", "quarkConnections_", "[", "quarkId", "]", ";", "}", "}", "}", "}", "// Restore rendering and show the changes.", "this", ".", "rendered", "=", "savedRendered", ";", "if", "(", "this", ".", "rendered", ")", "{", "this", ".", "render", "(", ")", ";", "}", "}" ]
Notification that the procedure's parameters have changed. @param {!Array.<string>} paramNames New param names, e.g. ['x', 'y', 'z']. @param {!Array.<string>} paramIds IDs of params (consistent for each parameter through the life of a mutator, regardless of param renaming), e.g. ['piua', 'f8b_', 'oi.o']. @private @this Blockly.Block
[ "Notification", "that", "the", "procedure", "s", "parameters", "have", "changed", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L497-L578
18,889
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function() { for (var i = 0; i < this.arguments_.length; i++) { var field = this.getField('ARGNAME' + i); if (field) { // Ensure argument name is up to date. // The argument name field is deterministic based on the mutation, // no need to fire a change event. Blockly.Events.disable(); field.setValue(this.arguments_[i]); Blockly.Events.enable(); } else { // Add new input. field = new Blockly.FieldLabel(this.arguments_[i]); var input = this.appendValueInput('ARG' + i) .setAlign(Blockly.ALIGN_RIGHT) .appendField(field, 'ARGNAME' + i); input.init(); } } // Remove deleted inputs. while (this.getInput('ARG' + i)) { this.removeInput('ARG' + i); i++; } // Add 'with:' if there are parameters, remove otherwise. var topRow = this.getInput('TOPROW'); if (topRow) { if (this.arguments_.length) { if (!this.getField('WITH')) { topRow.appendField(Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS, 'WITH'); topRow.init(); } } else { if (this.getField('WITH')) { topRow.removeField('WITH'); } } } }
javascript
function() { for (var i = 0; i < this.arguments_.length; i++) { var field = this.getField('ARGNAME' + i); if (field) { // Ensure argument name is up to date. // The argument name field is deterministic based on the mutation, // no need to fire a change event. Blockly.Events.disable(); field.setValue(this.arguments_[i]); Blockly.Events.enable(); } else { // Add new input. field = new Blockly.FieldLabel(this.arguments_[i]); var input = this.appendValueInput('ARG' + i) .setAlign(Blockly.ALIGN_RIGHT) .appendField(field, 'ARGNAME' + i); input.init(); } } // Remove deleted inputs. while (this.getInput('ARG' + i)) { this.removeInput('ARG' + i); i++; } // Add 'with:' if there are parameters, remove otherwise. var topRow = this.getInput('TOPROW'); if (topRow) { if (this.arguments_.length) { if (!this.getField('WITH')) { topRow.appendField(Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS, 'WITH'); topRow.init(); } } else { if (this.getField('WITH')) { topRow.removeField('WITH'); } } } }
[ "function", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "arguments_", ".", "length", ";", "i", "++", ")", "{", "var", "field", "=", "this", ".", "getField", "(", "'ARGNAME'", "+", "i", ")", ";", "if", "(", "field", ")", "{", "// Ensure argument name is up to date.", "// The argument name field is deterministic based on the mutation,", "// no need to fire a change event.", "Blockly", ".", "Events", ".", "disable", "(", ")", ";", "field", ".", "setValue", "(", "this", ".", "arguments_", "[", "i", "]", ")", ";", "Blockly", ".", "Events", ".", "enable", "(", ")", ";", "}", "else", "{", "// Add new input.", "field", "=", "new", "Blockly", ".", "FieldLabel", "(", "this", ".", "arguments_", "[", "i", "]", ")", ";", "var", "input", "=", "this", ".", "appendValueInput", "(", "'ARG'", "+", "i", ")", ".", "setAlign", "(", "Blockly", ".", "ALIGN_RIGHT", ")", ".", "appendField", "(", "field", ",", "'ARGNAME'", "+", "i", ")", ";", "input", ".", "init", "(", ")", ";", "}", "}", "// Remove deleted inputs.", "while", "(", "this", ".", "getInput", "(", "'ARG'", "+", "i", ")", ")", "{", "this", ".", "removeInput", "(", "'ARG'", "+", "i", ")", ";", "i", "++", ";", "}", "// Add 'with:' if there are parameters, remove otherwise.", "var", "topRow", "=", "this", ".", "getInput", "(", "'TOPROW'", ")", ";", "if", "(", "topRow", ")", "{", "if", "(", "this", ".", "arguments_", ".", "length", ")", "{", "if", "(", "!", "this", ".", "getField", "(", "'WITH'", ")", ")", "{", "topRow", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_CALL_BEFORE_PARAMS", ",", "'WITH'", ")", ";", "topRow", ".", "init", "(", ")", ";", "}", "}", "else", "{", "if", "(", "this", ".", "getField", "(", "'WITH'", ")", ")", "{", "topRow", ".", "removeField", "(", "'WITH'", ")", ";", "}", "}", "}", "}" ]
Modify this block to have the correct number of arguments. @private @this Blockly.Block
[ "Modify", "this", "block", "to", "have", "the", "correct", "number", "of", "arguments", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L584-L622
18,890
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function(options) { var option = {enabled: true}; option.text = Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF; var name = this.getProcedureCall(); var workspace = this.workspace; option.callback = function() { var def = Blockly.Procedures.getDefinition(name, workspace); def && def.select(); }; options.push(option); }
javascript
function(options) { var option = {enabled: true}; option.text = Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF; var name = this.getProcedureCall(); var workspace = this.workspace; option.callback = function() { var def = Blockly.Procedures.getDefinition(name, workspace); def && def.select(); }; options.push(option); }
[ "function", "(", "options", ")", "{", "var", "option", "=", "{", "enabled", ":", "true", "}", ";", "option", ".", "text", "=", "Blockly", ".", "Msg", ".", "PROCEDURES_HIGHLIGHT_DEF", ";", "var", "name", "=", "this", ".", "getProcedureCall", "(", ")", ";", "var", "workspace", "=", "this", ".", "workspace", ";", "option", ".", "callback", "=", "function", "(", ")", "{", "var", "def", "=", "Blockly", ".", "Procedures", ".", "getDefinition", "(", "name", ",", "workspace", ")", ";", "def", "&&", "def", ".", "select", "(", ")", ";", "}", ";", "options", ".", "push", "(", "option", ")", ";", "}" ]
Add menu option to find the definition block for this call. @param {!Array} options List of menu options to add to. @this Blockly.Block
[ "Add", "menu", "option", "to", "find", "the", "definition", "block", "for", "this", "call", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L676-L686
18,891
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function() { this.appendDummyInput('TOPROW') .appendField('', 'NAME'); this.setOutput(true); this.setColour(Blockly.Blocks.procedures.HUE); // Tooltip is set in domToMutation. this.setHelpUrl(Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL); this.arguments_ = []; this.quarkConnections_ = {}; this.quarkIds_ = null; }
javascript
function() { this.appendDummyInput('TOPROW') .appendField('', 'NAME'); this.setOutput(true); this.setColour(Blockly.Blocks.procedures.HUE); // Tooltip is set in domToMutation. this.setHelpUrl(Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL); this.arguments_ = []; this.quarkConnections_ = {}; this.quarkIds_ = null; }
[ "function", "(", ")", "{", "this", ".", "appendDummyInput", "(", "'TOPROW'", ")", ".", "appendField", "(", "''", ",", "'NAME'", ")", ";", "this", ".", "setOutput", "(", "true", ")", ";", "this", ".", "setColour", "(", "Blockly", ".", "Blocks", ".", "procedures", ".", "HUE", ")", ";", "// Tooltip is set in domToMutation.", "this", ".", "setHelpUrl", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_CALLRETURN_HELPURL", ")", ";", "this", ".", "arguments_", "=", "[", "]", ";", "this", ".", "quarkConnections_", "=", "{", "}", ";", "this", ".", "quarkIds_", "=", "null", ";", "}" ]
Block for calling a procedure with a return value. @this Blockly.Block
[ "Block", "for", "calling", "a", "procedure", "with", "a", "return", "value", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L694-L704
18,892
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function() { this.appendValueInput('CONDITION') .setCheck('Boolean') .appendField(Blockly.Msg.CONTROLS_IF_MSG_IF); this.appendValueInput('VALUE') .appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN); this.setInputsInline(true); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour(Blockly.Blocks.procedures.HUE); this.setTooltip(Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP); this.setHelpUrl(Blockly.Msg.PROCEDURES_IFRETURN_HELPURL); this.hasReturnValue_ = true; }
javascript
function() { this.appendValueInput('CONDITION') .setCheck('Boolean') .appendField(Blockly.Msg.CONTROLS_IF_MSG_IF); this.appendValueInput('VALUE') .appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN); this.setInputsInline(true); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour(Blockly.Blocks.procedures.HUE); this.setTooltip(Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP); this.setHelpUrl(Blockly.Msg.PROCEDURES_IFRETURN_HELPURL); this.hasReturnValue_ = true; }
[ "function", "(", ")", "{", "this", ".", "appendValueInput", "(", "'CONDITION'", ")", ".", "setCheck", "(", "'Boolean'", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "CONTROLS_IF_MSG_IF", ")", ";", "this", ".", "appendValueInput", "(", "'VALUE'", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_DEFRETURN_RETURN", ")", ";", "this", ".", "setInputsInline", "(", "true", ")", ";", "this", ".", "setPreviousStatement", "(", "true", ")", ";", "this", ".", "setNextStatement", "(", "true", ")", ";", "this", ".", "setColour", "(", "Blockly", ".", "Blocks", ".", "procedures", ".", "HUE", ")", ";", "this", ".", "setTooltip", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_IFRETURN_TOOLTIP", ")", ";", "this", ".", "setHelpUrl", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_IFRETURN_HELPURL", ")", ";", "this", ".", "hasReturnValue_", "=", "true", ";", "}" ]
Block for conditionally returning a value from a procedure. @this Blockly.Block
[ "Block", "for", "conditionally", "returning", "a", "value", "from", "a", "procedure", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L721-L734
18,893
webduinoio/webduino-blockly
components/blockly-src/blocks/procedures.js
function(xmlElement) { var value = xmlElement.getAttribute('value'); this.hasReturnValue_ = (value == 1); if (!this.hasReturnValue_) { this.removeInput('VALUE'); this.appendDummyInput('VALUE') .appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN); } }
javascript
function(xmlElement) { var value = xmlElement.getAttribute('value'); this.hasReturnValue_ = (value == 1); if (!this.hasReturnValue_) { this.removeInput('VALUE'); this.appendDummyInput('VALUE') .appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN); } }
[ "function", "(", "xmlElement", ")", "{", "var", "value", "=", "xmlElement", ".", "getAttribute", "(", "'value'", ")", ";", "this", ".", "hasReturnValue_", "=", "(", "value", "==", "1", ")", ";", "if", "(", "!", "this", ".", "hasReturnValue_", ")", "{", "this", ".", "removeInput", "(", "'VALUE'", ")", ";", "this", ".", "appendDummyInput", "(", "'VALUE'", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "PROCEDURES_DEFRETURN_RETURN", ")", ";", "}", "}" ]
Parse XML to restore whether this block has a return value. @param {!Element} xmlElement XML storage element. @this Blockly.Block
[ "Parse", "XML", "to", "restore", "whether", "this", "block", "has", "a", "return", "value", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/procedures.js#L750-L758
18,894
webduinoio/webduino-blockly
components/blockly-src/blocks/text.js
function() { this.setHelpUrl(Blockly.Msg.TEXT_TEXT_HELPURL); this.setColour(Blockly.Blocks.texts.HUE); this.appendDummyInput() .appendField(this.newQuote_(true)) .appendField(new Blockly.FieldTextInput(''), 'TEXT') .appendField(this.newQuote_(false)); this.setOutput(true, 'String'); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; // Text block is trivial. Use tooltip of parent block if it exists. this.setTooltip(function() { var parent = thisBlock.getParent(); return (parent && parent.tooltip) || Blockly.Msg.TEXT_TEXT_TOOLTIP; }); }
javascript
function() { this.setHelpUrl(Blockly.Msg.TEXT_TEXT_HELPURL); this.setColour(Blockly.Blocks.texts.HUE); this.appendDummyInput() .appendField(this.newQuote_(true)) .appendField(new Blockly.FieldTextInput(''), 'TEXT') .appendField(this.newQuote_(false)); this.setOutput(true, 'String'); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; // Text block is trivial. Use tooltip of parent block if it exists. this.setTooltip(function() { var parent = thisBlock.getParent(); return (parent && parent.tooltip) || Blockly.Msg.TEXT_TEXT_TOOLTIP; }); }
[ "function", "(", ")", "{", "this", ".", "setHelpUrl", "(", "Blockly", ".", "Msg", ".", "TEXT_TEXT_HELPURL", ")", ";", "this", ".", "setColour", "(", "Blockly", ".", "Blocks", ".", "texts", ".", "HUE", ")", ";", "this", ".", "appendDummyInput", "(", ")", ".", "appendField", "(", "this", ".", "newQuote_", "(", "true", ")", ")", ".", "appendField", "(", "new", "Blockly", ".", "FieldTextInput", "(", "''", ")", ",", "'TEXT'", ")", ".", "appendField", "(", "this", ".", "newQuote_", "(", "false", ")", ")", ";", "this", ".", "setOutput", "(", "true", ",", "'String'", ")", ";", "// Assign 'this' to a variable for use in the tooltip closure below.", "var", "thisBlock", "=", "this", ";", "// Text block is trivial. Use tooltip of parent block if it exists.", "this", ".", "setTooltip", "(", "function", "(", ")", "{", "var", "parent", "=", "thisBlock", ".", "getParent", "(", ")", ";", "return", "(", "parent", "&&", "parent", ".", "tooltip", ")", "||", "Blockly", ".", "Msg", ".", "TEXT_TEXT_TOOLTIP", ";", "}", ")", ";", "}" ]
Block for text value. @this Blockly.Block
[ "Block", "for", "text", "value", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/text.js#L42-L57
18,895
webduinoio/webduino-blockly
components/blockly-src/blocks/text.js
function() { this.setColour(Blockly.Blocks.texts.HUE); this.appendDummyInput() .appendField(Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN); this.appendStatementInput('STACK'); this.setTooltip(Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP); this.contextMenu = false; }
javascript
function() { this.setColour(Blockly.Blocks.texts.HUE); this.appendDummyInput() .appendField(Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN); this.appendStatementInput('STACK'); this.setTooltip(Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP); this.contextMenu = false; }
[ "function", "(", ")", "{", "this", ".", "setColour", "(", "Blockly", ".", "Blocks", ".", "texts", ".", "HUE", ")", ";", "this", ".", "appendDummyInput", "(", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "TEXT_CREATE_JOIN_TITLE_JOIN", ")", ";", "this", ".", "appendStatementInput", "(", "'STACK'", ")", ";", "this", ".", "setTooltip", "(", "Blockly", ".", "Msg", ".", "TEXT_CREATE_JOIN_TOOLTIP", ")", ";", "this", ".", "contextMenu", "=", "false", ";", "}" ]
Mutator block for container. @this Blockly.Block
[ "Mutator", "block", "for", "container", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/text.js#L206-L213
18,896
webduinoio/webduino-blockly
components/blockly-src/blocks/text.js
function() { this.jsonInit({ "message0": Blockly.Msg.TEXT_LENGTH_TITLE, "args0": [ { "type": "input_value", "name": "VALUE", "check": ['String', 'Array'] } ], "output": 'Number', "colour": Blockly.Blocks.texts.HUE, "tooltip": Blockly.Msg.TEXT_LENGTH_TOOLTIP, "helpUrl": Blockly.Msg.TEXT_LENGTH_HELPURL }); }
javascript
function() { this.jsonInit({ "message0": Blockly.Msg.TEXT_LENGTH_TITLE, "args0": [ { "type": "input_value", "name": "VALUE", "check": ['String', 'Array'] } ], "output": 'Number', "colour": Blockly.Blocks.texts.HUE, "tooltip": Blockly.Msg.TEXT_LENGTH_TOOLTIP, "helpUrl": Blockly.Msg.TEXT_LENGTH_HELPURL }); }
[ "function", "(", ")", "{", "this", ".", "jsonInit", "(", "{", "\"message0\"", ":", "Blockly", ".", "Msg", ".", "TEXT_LENGTH_TITLE", ",", "\"args0\"", ":", "[", "{", "\"type\"", ":", "\"input_value\"", ",", "\"name\"", ":", "\"VALUE\"", ",", "\"check\"", ":", "[", "'String'", ",", "'Array'", "]", "}", "]", ",", "\"output\"", ":", "'Number'", ",", "\"colour\"", ":", "Blockly", ".", "Blocks", ".", "texts", ".", "HUE", ",", "\"tooltip\"", ":", "Blockly", ".", "Msg", ".", "TEXT_LENGTH_TOOLTIP", ",", "\"helpUrl\"", ":", "Blockly", ".", "Msg", ".", "TEXT_LENGTH_HELPURL", "}", ")", ";", "}" ]
Block for string length. @this Blockly.Block
[ "Block", "for", "string", "length", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/text.js#L261-L276
18,897
webduinoio/webduino-blockly
components/blockly-src/blocks/text.js
function() { this.jsonInit({ "message0": Blockly.Msg.TEXT_ISEMPTY_TITLE, "args0": [ { "type": "input_value", "name": "VALUE", "check": ['String', 'Array'] } ], "output": 'Boolean', "colour": Blockly.Blocks.texts.HUE, "tooltip": Blockly.Msg.TEXT_ISEMPTY_TOOLTIP, "helpUrl": Blockly.Msg.TEXT_ISEMPTY_HELPURL }); }
javascript
function() { this.jsonInit({ "message0": Blockly.Msg.TEXT_ISEMPTY_TITLE, "args0": [ { "type": "input_value", "name": "VALUE", "check": ['String', 'Array'] } ], "output": 'Boolean', "colour": Blockly.Blocks.texts.HUE, "tooltip": Blockly.Msg.TEXT_ISEMPTY_TOOLTIP, "helpUrl": Blockly.Msg.TEXT_ISEMPTY_HELPURL }); }
[ "function", "(", ")", "{", "this", ".", "jsonInit", "(", "{", "\"message0\"", ":", "Blockly", ".", "Msg", ".", "TEXT_ISEMPTY_TITLE", ",", "\"args0\"", ":", "[", "{", "\"type\"", ":", "\"input_value\"", ",", "\"name\"", ":", "\"VALUE\"", ",", "\"check\"", ":", "[", "'String'", ",", "'Array'", "]", "}", "]", ",", "\"output\"", ":", "'Boolean'", ",", "\"colour\"", ":", "Blockly", ".", "Blocks", ".", "texts", ".", "HUE", ",", "\"tooltip\"", ":", "Blockly", ".", "Msg", ".", "TEXT_ISEMPTY_TOOLTIP", ",", "\"helpUrl\"", ":", "Blockly", ".", "Msg", ".", "TEXT_ISEMPTY_HELPURL", "}", ")", ";", "}" ]
Block for is the string null? @this Blockly.Block
[ "Block", "for", "is", "the", "string", "null?" ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/text.js#L284-L299
18,898
webduinoio/webduino-blockly
components/blockly-src/blocks/text.js
function() { this.WHERE_OPTIONS = [[Blockly.Msg.TEXT_CHARAT_FROM_START, 'FROM_START'], [Blockly.Msg.TEXT_CHARAT_FROM_END, 'FROM_END'], [Blockly.Msg.TEXT_CHARAT_FIRST, 'FIRST'], [Blockly.Msg.TEXT_CHARAT_LAST, 'LAST'], [Blockly.Msg.TEXT_CHARAT_RANDOM, 'RANDOM']]; this.setHelpUrl(Blockly.Msg.TEXT_CHARAT_HELPURL); this.setColour(Blockly.Blocks.texts.HUE); this.setOutput(true, 'String'); this.appendValueInput('VALUE') .setCheck('String') .appendField(Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT); this.appendDummyInput('AT'); this.setInputsInline(true); this.updateAt_(true); this.setTooltip(Blockly.Msg.TEXT_CHARAT_TOOLTIP); }
javascript
function() { this.WHERE_OPTIONS = [[Blockly.Msg.TEXT_CHARAT_FROM_START, 'FROM_START'], [Blockly.Msg.TEXT_CHARAT_FROM_END, 'FROM_END'], [Blockly.Msg.TEXT_CHARAT_FIRST, 'FIRST'], [Blockly.Msg.TEXT_CHARAT_LAST, 'LAST'], [Blockly.Msg.TEXT_CHARAT_RANDOM, 'RANDOM']]; this.setHelpUrl(Blockly.Msg.TEXT_CHARAT_HELPURL); this.setColour(Blockly.Blocks.texts.HUE); this.setOutput(true, 'String'); this.appendValueInput('VALUE') .setCheck('String') .appendField(Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT); this.appendDummyInput('AT'); this.setInputsInline(true); this.updateAt_(true); this.setTooltip(Blockly.Msg.TEXT_CHARAT_TOOLTIP); }
[ "function", "(", ")", "{", "this", ".", "WHERE_OPTIONS", "=", "[", "[", "Blockly", ".", "Msg", ".", "TEXT_CHARAT_FROM_START", ",", "'FROM_START'", "]", ",", "[", "Blockly", ".", "Msg", ".", "TEXT_CHARAT_FROM_END", ",", "'FROM_END'", "]", ",", "[", "Blockly", ".", "Msg", ".", "TEXT_CHARAT_FIRST", ",", "'FIRST'", "]", ",", "[", "Blockly", ".", "Msg", ".", "TEXT_CHARAT_LAST", ",", "'LAST'", "]", ",", "[", "Blockly", ".", "Msg", ".", "TEXT_CHARAT_RANDOM", ",", "'RANDOM'", "]", "]", ";", "this", ".", "setHelpUrl", "(", "Blockly", ".", "Msg", ".", "TEXT_CHARAT_HELPURL", ")", ";", "this", ".", "setColour", "(", "Blockly", ".", "Blocks", ".", "texts", ".", "HUE", ")", ";", "this", ".", "setOutput", "(", "true", ",", "'String'", ")", ";", "this", ".", "appendValueInput", "(", "'VALUE'", ")", ".", "setCheck", "(", "'String'", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "TEXT_CHARAT_INPUT_INTEXT", ")", ";", "this", ".", "appendDummyInput", "(", "'AT'", ")", ";", "this", ".", "setInputsInline", "(", "true", ")", ";", "this", ".", "updateAt_", "(", "true", ")", ";", "this", ".", "setTooltip", "(", "Blockly", ".", "Msg", ".", "TEXT_CHARAT_TOOLTIP", ")", ";", "}" ]
Block for getting a character from the string. @this Blockly.Block
[ "Block", "for", "getting", "a", "character", "from", "the", "string", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/text.js#L333-L350
18,899
webduinoio/webduino-blockly
components/blockly-src/blocks/text.js
function(isAt) { // Destroy old 'AT' and 'ORDINAL' inputs. this.removeInput('AT'); this.removeInput('ORDINAL', true); // Create either a value 'AT' input or a dummy input. if (isAt) { this.appendValueInput('AT').setCheck('Number'); if (Blockly.Msg.ORDINAL_NUMBER_SUFFIX) { this.appendDummyInput('ORDINAL') .appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX); } } else { this.appendDummyInput('AT'); } if (Blockly.Msg.TEXT_CHARAT_TAIL) { this.removeInput('TAIL', true); this.appendDummyInput('TAIL') .appendField(Blockly.Msg.TEXT_CHARAT_TAIL); } var menu = new Blockly.FieldDropdown(this.WHERE_OPTIONS, function(value) { var newAt = (value == 'FROM_START') || (value == 'FROM_END'); // The 'isAt' variable is available due to this function being a closure. if (newAt != isAt) { var block = this.sourceBlock_; block.updateAt_(newAt); // This menu has been destroyed and replaced. Update the replacement. block.setFieldValue(value, 'WHERE'); return null; } return undefined; }); this.getInput('AT').appendField(menu, 'WHERE'); }
javascript
function(isAt) { // Destroy old 'AT' and 'ORDINAL' inputs. this.removeInput('AT'); this.removeInput('ORDINAL', true); // Create either a value 'AT' input or a dummy input. if (isAt) { this.appendValueInput('AT').setCheck('Number'); if (Blockly.Msg.ORDINAL_NUMBER_SUFFIX) { this.appendDummyInput('ORDINAL') .appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX); } } else { this.appendDummyInput('AT'); } if (Blockly.Msg.TEXT_CHARAT_TAIL) { this.removeInput('TAIL', true); this.appendDummyInput('TAIL') .appendField(Blockly.Msg.TEXT_CHARAT_TAIL); } var menu = new Blockly.FieldDropdown(this.WHERE_OPTIONS, function(value) { var newAt = (value == 'FROM_START') || (value == 'FROM_END'); // The 'isAt' variable is available due to this function being a closure. if (newAt != isAt) { var block = this.sourceBlock_; block.updateAt_(newAt); // This menu has been destroyed and replaced. Update the replacement. block.setFieldValue(value, 'WHERE'); return null; } return undefined; }); this.getInput('AT').appendField(menu, 'WHERE'); }
[ "function", "(", "isAt", ")", "{", "// Destroy old 'AT' and 'ORDINAL' inputs.", "this", ".", "removeInput", "(", "'AT'", ")", ";", "this", ".", "removeInput", "(", "'ORDINAL'", ",", "true", ")", ";", "// Create either a value 'AT' input or a dummy input.", "if", "(", "isAt", ")", "{", "this", ".", "appendValueInput", "(", "'AT'", ")", ".", "setCheck", "(", "'Number'", ")", ";", "if", "(", "Blockly", ".", "Msg", ".", "ORDINAL_NUMBER_SUFFIX", ")", "{", "this", ".", "appendDummyInput", "(", "'ORDINAL'", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "ORDINAL_NUMBER_SUFFIX", ")", ";", "}", "}", "else", "{", "this", ".", "appendDummyInput", "(", "'AT'", ")", ";", "}", "if", "(", "Blockly", ".", "Msg", ".", "TEXT_CHARAT_TAIL", ")", "{", "this", ".", "removeInput", "(", "'TAIL'", ",", "true", ")", ";", "this", ".", "appendDummyInput", "(", "'TAIL'", ")", ".", "appendField", "(", "Blockly", ".", "Msg", ".", "TEXT_CHARAT_TAIL", ")", ";", "}", "var", "menu", "=", "new", "Blockly", ".", "FieldDropdown", "(", "this", ".", "WHERE_OPTIONS", ",", "function", "(", "value", ")", "{", "var", "newAt", "=", "(", "value", "==", "'FROM_START'", ")", "||", "(", "value", "==", "'FROM_END'", ")", ";", "// The 'isAt' variable is available due to this function being a closure.", "if", "(", "newAt", "!=", "isAt", ")", "{", "var", "block", "=", "this", ".", "sourceBlock_", ";", "block", ".", "updateAt_", "(", "newAt", ")", ";", "// This menu has been destroyed and replaced. Update the replacement.", "block", ".", "setFieldValue", "(", "value", ",", "'WHERE'", ")", ";", "return", "null", ";", "}", "return", "undefined", ";", "}", ")", ";", "this", ".", "getInput", "(", "'AT'", ")", ".", "appendField", "(", "menu", ",", "'WHERE'", ")", ";", "}" ]
Create or delete an input for the numeric index. @param {boolean} isAt True if the input should exist. @private @this Blockly.Block
[ "Create", "or", "delete", "an", "input", "for", "the", "numeric", "index", "." ]
f656474c6e4ba1fc12fda217280714c3ca044bbe
https://github.com/webduinoio/webduino-blockly/blob/f656474c6e4ba1fc12fda217280714c3ca044bbe/components/blockly-src/blocks/text.js#L379-L411