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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
54,600
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/magicline/plugin.js
getAscendantTrigger
function getAscendantTrigger( that ) { var node = that.element, trigger; if ( node && isHtml( node ) ) { trigger = node.getAscendant( that.triggers, true ); // If trigger is an element, neither editable nor editable's ascendant. if ( trigger && that.editable.contains( trigger ) ) { // Check for closest editable limit. // Don't consider trigger as a limit as it may be nested editable (includeSelf=false) (#12009). var limit = getClosestEditableLimit( trigger ); // Trigger in nested editable area. if ( limit.getAttribute( 'contenteditable' ) == 'true' ) return trigger; // Trigger in non-editable area. else if ( limit.is( that.triggers ) ) return limit; else return null; return trigger; } else return null; } return null; }
javascript
function getAscendantTrigger( that ) { var node = that.element, trigger; if ( node && isHtml( node ) ) { trigger = node.getAscendant( that.triggers, true ); // If trigger is an element, neither editable nor editable's ascendant. if ( trigger && that.editable.contains( trigger ) ) { // Check for closest editable limit. // Don't consider trigger as a limit as it may be nested editable (includeSelf=false) (#12009). var limit = getClosestEditableLimit( trigger ); // Trigger in nested editable area. if ( limit.getAttribute( 'contenteditable' ) == 'true' ) return trigger; // Trigger in non-editable area. else if ( limit.is( that.triggers ) ) return limit; else return null; return trigger; } else return null; } return null; }
[ "function", "getAscendantTrigger", "(", "that", ")", "{", "var", "node", "=", "that", ".", "element", ",", "trigger", ";", "if", "(", "node", "&&", "isHtml", "(", "node", ")", ")", "{", "trigger", "=", "node", ".", "getAscendant", "(", "that", ".", "triggers", ",", "true", ")", ";", "// If trigger is an element, neither editable nor editable's ascendant.\r", "if", "(", "trigger", "&&", "that", ".", "editable", ".", "contains", "(", "trigger", ")", ")", "{", "// Check for closest editable limit.\r", "// Don't consider trigger as a limit as it may be nested editable (includeSelf=false) (#12009).\r", "var", "limit", "=", "getClosestEditableLimit", "(", "trigger", ")", ";", "// Trigger in nested editable area.\r", "if", "(", "limit", ".", "getAttribute", "(", "'contenteditable'", ")", "==", "'true'", ")", "return", "trigger", ";", "// Trigger in non-editable area.\r", "else", "if", "(", "limit", ".", "is", "(", "that", ".", "triggers", ")", ")", "return", "limit", ";", "else", "return", "null", ";", "return", "trigger", ";", "}", "else", "return", "null", ";", "}", "return", "null", ";", "}" ]
Gets the closest parent node that belongs to triggers group.
[ "Gets", "the", "closest", "parent", "node", "that", "belongs", "to", "triggers", "group", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/magicline/plugin.js#L478-L506
54,601
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/magicline/plugin.js
function() { that.debug.groupStart( 'mouseNear' ); // %REMOVE_LINE% updateSize( that, this ); var offset = that.holdDistance, size = this.size; // Determine neighborhood by element dimensions and offsets. if ( size && inBetween( that.mouse.y, size.top - offset, size.bottom + offset ) && inBetween( that.mouse.x, size.left - offset, size.right + offset ) ) { that.debug.logEnd( 'Mouse is near.' ); // %REMOVE_LINE% return true; } that.debug.logEnd( 'Mouse isn\'t near.' ); // %REMOVE_LINE% return false; }
javascript
function() { that.debug.groupStart( 'mouseNear' ); // %REMOVE_LINE% updateSize( that, this ); var offset = that.holdDistance, size = this.size; // Determine neighborhood by element dimensions and offsets. if ( size && inBetween( that.mouse.y, size.top - offset, size.bottom + offset ) && inBetween( that.mouse.x, size.left - offset, size.right + offset ) ) { that.debug.logEnd( 'Mouse is near.' ); // %REMOVE_LINE% return true; } that.debug.logEnd( 'Mouse isn\'t near.' ); // %REMOVE_LINE% return false; }
[ "function", "(", ")", "{", "that", ".", "debug", ".", "groupStart", "(", "'mouseNear'", ")", ";", "// %REMOVE_LINE%\r", "updateSize", "(", "that", ",", "this", ")", ";", "var", "offset", "=", "that", ".", "holdDistance", ",", "size", "=", "this", ".", "size", ";", "// Determine neighborhood by element dimensions and offsets.\r", "if", "(", "size", "&&", "inBetween", "(", "that", ".", "mouse", ".", "y", ",", "size", ".", "top", "-", "offset", ",", "size", ".", "bottom", "+", "offset", ")", "&&", "inBetween", "(", "that", ".", "mouse", ".", "x", ",", "size", ".", "left", "-", "offset", ",", "size", ".", "right", "+", "offset", ")", ")", "{", "that", ".", "debug", ".", "logEnd", "(", "'Mouse is near.'", ")", ";", "// %REMOVE_LINE%\r", "return", "true", ";", "}", "that", ".", "debug", ".", "logEnd", "(", "'Mouse isn\\'t near.'", ")", ";", "// %REMOVE_LINE%\r", "return", "false", ";", "}" ]
Checks whether mouseY is around an element by comparing boundaries and considering an offset distance.
[ "Checks", "whether", "mouseY", "is", "around", "an", "element", "by", "comparing", "boundaries", "and", "considering", "an", "offset", "distance", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/magicline/plugin.js#L632-L647
54,602
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/magicline/plugin.js
isChildBetweenPointerAndEdge
function isChildBetweenPointerAndEdge( that, parent, edgeBottom ) { var edgeChild = parent[ edgeBottom ? 'getLast' : 'getFirst' ]( function( node ) { return that.isRelevant( node ) && !node.is( DTD_TABLECONTENT ); } ); if ( !edgeChild ) return false; updateSize( that, edgeChild ); return edgeBottom ? edgeChild.size.top > that.mouse.y : edgeChild.size.bottom < that.mouse.y; }
javascript
function isChildBetweenPointerAndEdge( that, parent, edgeBottom ) { var edgeChild = parent[ edgeBottom ? 'getLast' : 'getFirst' ]( function( node ) { return that.isRelevant( node ) && !node.is( DTD_TABLECONTENT ); } ); if ( !edgeChild ) return false; updateSize( that, edgeChild ); return edgeBottom ? edgeChild.size.top > that.mouse.y : edgeChild.size.bottom < that.mouse.y; }
[ "function", "isChildBetweenPointerAndEdge", "(", "that", ",", "parent", ",", "edgeBottom", ")", "{", "var", "edgeChild", "=", "parent", "[", "edgeBottom", "?", "'getLast'", ":", "'getFirst'", "]", "(", "function", "(", "node", ")", "{", "return", "that", ".", "isRelevant", "(", "node", ")", "&&", "!", "node", ".", "is", "(", "DTD_TABLECONTENT", ")", ";", "}", ")", ";", "if", "(", "!", "edgeChild", ")", "return", "false", ";", "updateSize", "(", "that", ",", "edgeChild", ")", ";", "return", "edgeBottom", "?", "edgeChild", ".", "size", ".", "top", ">", "that", ".", "mouse", ".", "y", ":", "edgeChild", ".", "size", ".", "bottom", "<", "that", ".", "mouse", ".", "y", ";", "}" ]
This function checks vertically is there's a relevant child between element's edge and the pointer. \-> Table contents are omitted.
[ "This", "function", "checks", "vertically", "is", "there", "s", "a", "relevant", "child", "between", "element", "s", "edge", "and", "the", "pointer", ".", "\\", "-", ">", "Table", "contents", "are", "omitted", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/magicline/plugin.js#L1077-L1088
54,603
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/magicline/plugin.js
expandSelector
function expandSelector( that, node ) { return !( isTextNode( node ) || isComment( node ) || isFlowBreaker( node ) || isLine( that, node ) || ( node.type == CKEDITOR.NODE_ELEMENT && node.$ && node.is( 'br' ) ) ); }
javascript
function expandSelector( that, node ) { return !( isTextNode( node ) || isComment( node ) || isFlowBreaker( node ) || isLine( that, node ) || ( node.type == CKEDITOR.NODE_ELEMENT && node.$ && node.is( 'br' ) ) ); }
[ "function", "expandSelector", "(", "that", ",", "node", ")", "{", "return", "!", "(", "isTextNode", "(", "node", ")", "||", "isComment", "(", "node", ")", "||", "isFlowBreaker", "(", "node", ")", "||", "isLine", "(", "that", ",", "node", ")", "||", "(", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "node", ".", "$", "&&", "node", ".", "is", "(", "'br'", ")", ")", ")", ";", "}" ]
This is default element selector used by the engine.
[ "This", "is", "default", "element", "selector", "used", "by", "the", "engine", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/magicline/plugin.js#L1537-L1543
54,604
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/magicline/plugin.js
expandFilter
function expandFilter( that, trigger ) { that.debug.groupStart( 'expandFilter' ); // %REMOVE_LINE% var upper = trigger.upper, lower = trigger.lower; if ( !upper || !lower // NOT: EDGE_MIDDLE trigger ALWAYS has two elements. || isFlowBreaker( lower ) || isFlowBreaker( upper ) // NOT: one of the elements is floated or positioned || lower.equals( upper ) || upper.equals( lower ) // NOT: two trigger elements, one equals another. || lower.contains( upper ) || upper.contains( lower ) ) { // NOT: two trigger elements, one contains another. that.debug.logEnd( 'REJECTED. No upper or no lower or they contain each other.' ); // %REMOVE_LINE% return false; } // YES: two trigger elements, pure siblings. else if ( isTrigger( that, upper ) && isTrigger( that, lower ) && areSiblings( that, upper, lower ) ) { that.debug.logElementsEnd( [ upper, lower ], // %REMOVE_LINE% [ 'upper', 'lower' ], 'APPROVED EDGE_MIDDLE' ); // %REMOVE_LINE% return true; } that.debug.logElementsEnd( [ upper, lower ], // %REMOVE_LINE% [ 'upper', 'lower' ], 'Rejected unknown pair' ); // %REMOVE_LINE% return false; }
javascript
function expandFilter( that, trigger ) { that.debug.groupStart( 'expandFilter' ); // %REMOVE_LINE% var upper = trigger.upper, lower = trigger.lower; if ( !upper || !lower // NOT: EDGE_MIDDLE trigger ALWAYS has two elements. || isFlowBreaker( lower ) || isFlowBreaker( upper ) // NOT: one of the elements is floated or positioned || lower.equals( upper ) || upper.equals( lower ) // NOT: two trigger elements, one equals another. || lower.contains( upper ) || upper.contains( lower ) ) { // NOT: two trigger elements, one contains another. that.debug.logEnd( 'REJECTED. No upper or no lower or they contain each other.' ); // %REMOVE_LINE% return false; } // YES: two trigger elements, pure siblings. else if ( isTrigger( that, upper ) && isTrigger( that, lower ) && areSiblings( that, upper, lower ) ) { that.debug.logElementsEnd( [ upper, lower ], // %REMOVE_LINE% [ 'upper', 'lower' ], 'APPROVED EDGE_MIDDLE' ); // %REMOVE_LINE% return true; } that.debug.logElementsEnd( [ upper, lower ], // %REMOVE_LINE% [ 'upper', 'lower' ], 'Rejected unknown pair' ); // %REMOVE_LINE% return false; }
[ "function", "expandFilter", "(", "that", ",", "trigger", ")", "{", "that", ".", "debug", ".", "groupStart", "(", "'expandFilter'", ")", ";", "// %REMOVE_LINE%\r", "var", "upper", "=", "trigger", ".", "upper", ",", "lower", "=", "trigger", ".", "lower", ";", "if", "(", "!", "upper", "||", "!", "lower", "// NOT: EDGE_MIDDLE trigger ALWAYS has two elements.\r", "||", "isFlowBreaker", "(", "lower", ")", "||", "isFlowBreaker", "(", "upper", ")", "// NOT: one of the elements is floated or positioned\r", "||", "lower", ".", "equals", "(", "upper", ")", "||", "upper", ".", "equals", "(", "lower", ")", "// NOT: two trigger elements, one equals another.\r", "||", "lower", ".", "contains", "(", "upper", ")", "||", "upper", ".", "contains", "(", "lower", ")", ")", "{", "// NOT: two trigger elements, one contains another.\r", "that", ".", "debug", ".", "logEnd", "(", "'REJECTED. No upper or no lower or they contain each other.'", ")", ";", "// %REMOVE_LINE%\r", "return", "false", ";", "}", "// YES: two trigger elements, pure siblings.\r", "else", "if", "(", "isTrigger", "(", "that", ",", "upper", ")", "&&", "isTrigger", "(", "that", ",", "lower", ")", "&&", "areSiblings", "(", "that", ",", "upper", ",", "lower", ")", ")", "{", "that", ".", "debug", ".", "logElementsEnd", "(", "[", "upper", ",", "lower", "]", ",", "// %REMOVE_LINE%\r", "[", "'upper'", ",", "'lower'", "]", ",", "'APPROVED EDGE_MIDDLE'", ")", ";", "// %REMOVE_LINE%\r", "return", "true", ";", "}", "that", ".", "debug", ".", "logElementsEnd", "(", "[", "upper", ",", "lower", "]", ",", "// %REMOVE_LINE%\r", "[", "'upper'", ",", "'lower'", "]", ",", "'Rejected unknown pair'", ")", ";", "// %REMOVE_LINE%\r", "return", "false", ";", "}" ]
A method for trigger filtering. Accepts or rejects trigger pairs by their location in DOM etc.
[ "A", "method", "for", "trigger", "filtering", ".", "Accepts", "or", "rejects", "trigger", "pairs", "by", "their", "location", "in", "DOM", "etc", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/magicline/plugin.js#L1571-L1598
54,605
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/magicline/plugin.js
verticalSearch
function verticalSearch( that, stopCondition, selectCriterion, startElement ) { var upper = startElement, lower = startElement, mouseStep = 0, upperFound = false, lowerFound = false, viewPaneHeight = that.view.pane.height, mouse = that.mouse; while ( mouse.y + mouseStep < viewPaneHeight && mouse.y - mouseStep > 0 ) { if ( !upperFound ) upperFound = stopCondition( upper, startElement ); if ( !lowerFound ) lowerFound = stopCondition( lower, startElement ); // Still not found... if ( !upperFound && mouse.y - mouseStep > 0 ) upper = selectCriterion( that, { x: mouse.x, y: mouse.y - mouseStep } ); if ( !lowerFound && mouse.y + mouseStep < viewPaneHeight ) lower = selectCriterion( that, { x: mouse.x, y: mouse.y + mouseStep } ); if ( upperFound && lowerFound ) break; // Instead of ++ to reduce the number of invocations by half. // It's trades off accuracy in some edge cases for improved performance. mouseStep += 2; } return new boxTrigger( [ upper, lower, null, null ] ); }
javascript
function verticalSearch( that, stopCondition, selectCriterion, startElement ) { var upper = startElement, lower = startElement, mouseStep = 0, upperFound = false, lowerFound = false, viewPaneHeight = that.view.pane.height, mouse = that.mouse; while ( mouse.y + mouseStep < viewPaneHeight && mouse.y - mouseStep > 0 ) { if ( !upperFound ) upperFound = stopCondition( upper, startElement ); if ( !lowerFound ) lowerFound = stopCondition( lower, startElement ); // Still not found... if ( !upperFound && mouse.y - mouseStep > 0 ) upper = selectCriterion( that, { x: mouse.x, y: mouse.y - mouseStep } ); if ( !lowerFound && mouse.y + mouseStep < viewPaneHeight ) lower = selectCriterion( that, { x: mouse.x, y: mouse.y + mouseStep } ); if ( upperFound && lowerFound ) break; // Instead of ++ to reduce the number of invocations by half. // It's trades off accuracy in some edge cases for improved performance. mouseStep += 2; } return new boxTrigger( [ upper, lower, null, null ] ); }
[ "function", "verticalSearch", "(", "that", ",", "stopCondition", ",", "selectCriterion", ",", "startElement", ")", "{", "var", "upper", "=", "startElement", ",", "lower", "=", "startElement", ",", "mouseStep", "=", "0", ",", "upperFound", "=", "false", ",", "lowerFound", "=", "false", ",", "viewPaneHeight", "=", "that", ".", "view", ".", "pane", ".", "height", ",", "mouse", "=", "that", ".", "mouse", ";", "while", "(", "mouse", ".", "y", "+", "mouseStep", "<", "viewPaneHeight", "&&", "mouse", ".", "y", "-", "mouseStep", ">", "0", ")", "{", "if", "(", "!", "upperFound", ")", "upperFound", "=", "stopCondition", "(", "upper", ",", "startElement", ")", ";", "if", "(", "!", "lowerFound", ")", "lowerFound", "=", "stopCondition", "(", "lower", ",", "startElement", ")", ";", "// Still not found...\r", "if", "(", "!", "upperFound", "&&", "mouse", ".", "y", "-", "mouseStep", ">", "0", ")", "upper", "=", "selectCriterion", "(", "that", ",", "{", "x", ":", "mouse", ".", "x", ",", "y", ":", "mouse", ".", "y", "-", "mouseStep", "}", ")", ";", "if", "(", "!", "lowerFound", "&&", "mouse", ".", "y", "+", "mouseStep", "<", "viewPaneHeight", ")", "lower", "=", "selectCriterion", "(", "that", ",", "{", "x", ":", "mouse", ".", "x", ",", "y", ":", "mouse", ".", "y", "+", "mouseStep", "}", ")", ";", "if", "(", "upperFound", "&&", "lowerFound", ")", "break", ";", "// Instead of ++ to reduce the number of invocations by half.\r", "// It's trades off accuracy in some edge cases for improved performance.\r", "mouseStep", "+=", "2", ";", "}", "return", "new", "boxTrigger", "(", "[", "upper", ",", "lower", ",", "null", ",", "null", "]", ")", ";", "}" ]
This method searches document vertically using given select criterion until stop criterion is fulfilled.
[ "This", "method", "searches", "document", "vertically", "using", "given", "select", "criterion", "until", "stop", "criterion", "is", "fulfilled", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/magicline/plugin.js#L1731-L1763
54,606
Pocketbrain/native-ads-web-ad-library
src/events.js
addListener
function addListener(event, callback) { checkEventValid(event); if (listeners[event]) { listeners[event].push(callback); } else { listeners[event] = [callback]; } }
javascript
function addListener(event, callback) { checkEventValid(event); if (listeners[event]) { listeners[event].push(callback); } else { listeners[event] = [callback]; } }
[ "function", "addListener", "(", "event", ",", "callback", ")", "{", "checkEventValid", "(", "event", ")", ";", "if", "(", "listeners", "[", "event", "]", ")", "{", "listeners", "[", "event", "]", ".", "push", "(", "callback", ")", ";", "}", "else", "{", "listeners", "[", "event", "]", "=", "[", "callback", "]", ";", "}", "}" ]
Add a new event listener @param {events} event - The name of the event listener to add an event for @param {function} callback - The callback to invoke when the event is called
[ "Add", "a", "new", "event", "listener" ]
aafee1c42e0569ee77f334fc2c4eb71eb146957e
https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/events.js#L31-L39
54,607
Pocketbrain/native-ads-web-ad-library
src/events.js
removeListener
function removeListener(event, eventHandler) { checkEventValid(event); if (listeners[event] && listeners[event].length) { var indexOfListener = listeners[event].indexOf(eventHandler); if (indexOfListener > -1) { listeners[event].splice(indexOfListener, 1); } } }
javascript
function removeListener(event, eventHandler) { checkEventValid(event); if (listeners[event] && listeners[event].length) { var indexOfListener = listeners[event].indexOf(eventHandler); if (indexOfListener > -1) { listeners[event].splice(indexOfListener, 1); } } }
[ "function", "removeListener", "(", "event", ",", "eventHandler", ")", "{", "checkEventValid", "(", "event", ")", ";", "if", "(", "listeners", "[", "event", "]", "&&", "listeners", "[", "event", "]", ".", "length", ")", "{", "var", "indexOfListener", "=", "listeners", "[", "event", "]", ".", "indexOf", "(", "eventHandler", ")", ";", "if", "(", "indexOfListener", ">", "-", "1", ")", "{", "listeners", "[", "event", "]", ".", "splice", "(", "indexOfListener", ",", "1", ")", ";", "}", "}", "}" ]
Remove a certain event listener @param {events} event - The name of the event to listen to @param {function} eventHandler - The eventHandler that is bound to this listener and should be removed
[ "Remove", "a", "certain", "event", "listener" ]
aafee1c42e0569ee77f334fc2c4eb71eb146957e
https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/events.js#L46-L55
54,608
JrSchild/grunt-retinafy
tasks/retinafy.js
processSize
function processSize(targetSize, origSize) { var match = (targetSize.match(r_percentage) || [])[1]; if (match /= 100) { return { width: origSize.width * match, height: 0 }; } else { return { width: (targetSize.match(r_width) || [])[1] || 0, height: (targetSize.match(r_height) || [])[1] || 0 }; } }
javascript
function processSize(targetSize, origSize) { var match = (targetSize.match(r_percentage) || [])[1]; if (match /= 100) { return { width: origSize.width * match, height: 0 }; } else { return { width: (targetSize.match(r_width) || [])[1] || 0, height: (targetSize.match(r_height) || [])[1] || 0 }; } }
[ "function", "processSize", "(", "targetSize", ",", "origSize", ")", "{", "var", "match", "=", "(", "targetSize", ".", "match", "(", "r_percentage", ")", "||", "[", "]", ")", "[", "1", "]", ";", "if", "(", "match", "/=", "100", ")", "{", "return", "{", "width", ":", "origSize", ".", "width", "*", "match", ",", "height", ":", "0", "}", ";", "}", "else", "{", "return", "{", "width", ":", "(", "targetSize", ".", "match", "(", "r_width", ")", "||", "[", "]", ")", "[", "1", "]", "||", "0", ",", "height", ":", "(", "targetSize", ".", "match", "(", "r_height", ")", "||", "[", "]", ")", "[", "1", "]", "||", "0", "}", ";", "}", "}" ]
Height matching. Process the size, return object of new size. Currently only test percentages.
[ "Height", "matching", ".", "Process", "the", "size", "return", "object", "of", "new", "size", ".", "Currently", "only", "test", "percentages", "." ]
85ae8bf7c17bfdcf3a860448848be0e3fe4b1f0e
https://github.com/JrSchild/grunt-retinafy/blob/85ae8bf7c17bfdcf3a860448848be0e3fe4b1f0e/tasks/retinafy.js#L26-L40
54,609
JrSchild/grunt-retinafy
tasks/retinafy.js
convertSizes
function convertSizes(sizes) { var tmp = []; for (var size in sizes) { tmp.push({ size: size, settings: _.extend({suffix: '', prefix: ''}, sizes[size]) }); } return tmp; }
javascript
function convertSizes(sizes) { var tmp = []; for (var size in sizes) { tmp.push({ size: size, settings: _.extend({suffix: '', prefix: ''}, sizes[size]) }); } return tmp; }
[ "function", "convertSizes", "(", "sizes", ")", "{", "var", "tmp", "=", "[", "]", ";", "for", "(", "var", "size", "in", "sizes", ")", "{", "tmp", ".", "push", "(", "{", "size", ":", "size", ",", "settings", ":", "_", ".", "extend", "(", "{", "suffix", ":", "''", ",", "prefix", ":", "''", "}", ",", "sizes", "[", "size", "]", ")", "}", ")", ";", "}", "return", "tmp", ";", "}" ]
In order to do async.each we have to iterate over an array Turn the sizes-object into an array of objects. @param {Object} sizes @return {Object}
[ "In", "order", "to", "do", "async", ".", "each", "we", "have", "to", "iterate", "over", "an", "array", "Turn", "the", "sizes", "-", "object", "into", "an", "array", "of", "objects", "." ]
85ae8bf7c17bfdcf3a860448848be0e3fe4b1f0e
https://github.com/JrSchild/grunt-retinafy/blob/85ae8bf7c17bfdcf3a860448848be0e3fe4b1f0e/tasks/retinafy.js#L48-L57
54,610
jakub-g/grunt-run-phantom-specs
tasks/grunt-run-phantom-specs.js
getPhantomExitCb
function getPhantomExitCb (specId, allSpecs, cfg, done) { var spawnCb = function (error, result, code) { if (error) { ok = false; if (cfg.debug) { console.log("PhantomJS exited with code " + code); } } var nextSpecId = specId + 1; if (nextSpecId == allSpecs.length) { // last spec done(ok); } else { startSpec (nextSpecId, allSpecs, cfg, done); } }; return spawnCb; }
javascript
function getPhantomExitCb (specId, allSpecs, cfg, done) { var spawnCb = function (error, result, code) { if (error) { ok = false; if (cfg.debug) { console.log("PhantomJS exited with code " + code); } } var nextSpecId = specId + 1; if (nextSpecId == allSpecs.length) { // last spec done(ok); } else { startSpec (nextSpecId, allSpecs, cfg, done); } }; return spawnCb; }
[ "function", "getPhantomExitCb", "(", "specId", ",", "allSpecs", ",", "cfg", ",", "done", ")", "{", "var", "spawnCb", "=", "function", "(", "error", ",", "result", ",", "code", ")", "{", "if", "(", "error", ")", "{", "ok", "=", "false", ";", "if", "(", "cfg", ".", "debug", ")", "{", "console", ".", "log", "(", "\"PhantomJS exited with code \"", "+", "code", ")", ";", "}", "}", "var", "nextSpecId", "=", "specId", "+", "1", ";", "if", "(", "nextSpecId", "==", "allSpecs", ".", "length", ")", "{", "// last spec", "done", "(", "ok", ")", ";", "}", "else", "{", "startSpec", "(", "nextSpecId", ",", "allSpecs", ",", "cfg", ",", "done", ")", ";", "}", "}", ";", "return", "spawnCb", ";", "}" ]
Factory of phantom exit callbacks. Created callback for n-th spec runs the n+1-st spec, or finishes the grunt task for the last spec. @return {Function} standard node process-exit callback
[ "Factory", "of", "phantom", "exit", "callbacks", ".", "Created", "callback", "for", "n", "-", "th", "spec", "runs", "the", "n", "+", "1", "-", "st", "spec", "or", "finishes", "the", "grunt", "task", "for", "the", "last", "spec", "." ]
a3dc6a8f058bbd4edb161edca5234caa6b2fb27a
https://github.com/jakub-g/grunt-run-phantom-specs/blob/a3dc6a8f058bbd4edb161edca5234caa6b2fb27a/tasks/grunt-run-phantom-specs.js#L52-L68
54,611
jakub-g/grunt-run-phantom-specs
tasks/grunt-run-phantom-specs.js
startPhantom
function startPhantom (specPath, cfg, cb) { var args = [specPath]; if (cfg.verbose) { args.push("--verbose"); // custom, to be handled by spec runner } if (cfg.debug) { args.push("--debug"); // custom, to be handled by spec runner } if (cfg.color) { args.push("--color"); // custom, to be handled by spec runner } args.push("--xunitName=" + cfg.xunitName); var phantomProcess = grunt.util.spawn({ cmd : 'phantomjs', args : args }, cb); phantomProcess.stdout.pipe(process.stdout); phantomProcess.stderr.pipe(process.stderr); return phantomProcess; }
javascript
function startPhantom (specPath, cfg, cb) { var args = [specPath]; if (cfg.verbose) { args.push("--verbose"); // custom, to be handled by spec runner } if (cfg.debug) { args.push("--debug"); // custom, to be handled by spec runner } if (cfg.color) { args.push("--color"); // custom, to be handled by spec runner } args.push("--xunitName=" + cfg.xunitName); var phantomProcess = grunt.util.spawn({ cmd : 'phantomjs', args : args }, cb); phantomProcess.stdout.pipe(process.stdout); phantomProcess.stderr.pipe(process.stderr); return phantomProcess; }
[ "function", "startPhantom", "(", "specPath", ",", "cfg", ",", "cb", ")", "{", "var", "args", "=", "[", "specPath", "]", ";", "if", "(", "cfg", ".", "verbose", ")", "{", "args", ".", "push", "(", "\"--verbose\"", ")", ";", "// custom, to be handled by spec runner", "}", "if", "(", "cfg", ".", "debug", ")", "{", "args", ".", "push", "(", "\"--debug\"", ")", ";", "// custom, to be handled by spec runner", "}", "if", "(", "cfg", ".", "color", ")", "{", "args", ".", "push", "(", "\"--color\"", ")", ";", "// custom, to be handled by spec runner", "}", "args", ".", "push", "(", "\"--xunitName=\"", "+", "cfg", ".", "xunitName", ")", ";", "var", "phantomProcess", "=", "grunt", ".", "util", ".", "spawn", "(", "{", "cmd", ":", "'phantomjs'", ",", "args", ":", "args", "}", ",", "cb", ")", ";", "phantomProcess", ".", "stdout", ".", "pipe", "(", "process", ".", "stdout", ")", ";", "phantomProcess", ".", "stderr", ".", "pipe", "(", "process", ".", "stderr", ")", ";", "return", "phantomProcess", ";", "}" ]
Boots phantomjs executable with `specPath` as a param, and executes given callback `cb` when phantom process exits. @param {String} specPath @param {Object} cfg @param {Function} cb
[ "Boots", "phantomjs", "executable", "with", "specPath", "as", "a", "param", "and", "executes", "given", "callback", "cb", "when", "phantom", "process", "exits", "." ]
a3dc6a8f058bbd4edb161edca5234caa6b2fb27a
https://github.com/jakub-g/grunt-run-phantom-specs/blob/a3dc6a8f058bbd4edb161edca5234caa6b2fb27a/tasks/grunt-run-phantom-specs.js#L77-L97
54,612
jakub-g/grunt-run-phantom-specs
tasks/grunt-run-phantom-specs.js
startSpec
function startSpec (n, allSpecs, cfg, done) { var printId = n + 1; var specPath = allSpecs[n]; var nSpecs = allSpecs.length; var msg = "Running spec file " + specPath + " [" + printId + "/" + nSpecs + "]"; var bar = Array(process.stdout.columns).join("*"); console.log("\n" + bar.cyan); console.log(alignCenter(msg).cyan); console.log(bar.cyan + "\n"); var cb = getPhantomExitCb(n, allSpecs, cfg, done); startPhantom(specPath, cfg, cb); }
javascript
function startSpec (n, allSpecs, cfg, done) { var printId = n + 1; var specPath = allSpecs[n]; var nSpecs = allSpecs.length; var msg = "Running spec file " + specPath + " [" + printId + "/" + nSpecs + "]"; var bar = Array(process.stdout.columns).join("*"); console.log("\n" + bar.cyan); console.log(alignCenter(msg).cyan); console.log(bar.cyan + "\n"); var cb = getPhantomExitCb(n, allSpecs, cfg, done); startPhantom(specPath, cfg, cb); }
[ "function", "startSpec", "(", "n", ",", "allSpecs", ",", "cfg", ",", "done", ")", "{", "var", "printId", "=", "n", "+", "1", ";", "var", "specPath", "=", "allSpecs", "[", "n", "]", ";", "var", "nSpecs", "=", "allSpecs", ".", "length", ";", "var", "msg", "=", "\"Running spec file \"", "+", "specPath", "+", "\" [\"", "+", "printId", "+", "\"/\"", "+", "nSpecs", "+", "\"]\"", ";", "var", "bar", "=", "Array", "(", "process", ".", "stdout", ".", "columns", ")", ".", "join", "(", "\"*\"", ")", ";", "console", ".", "log", "(", "\"\\n\"", "+", "bar", ".", "cyan", ")", ";", "console", ".", "log", "(", "alignCenter", "(", "msg", ")", ".", "cyan", ")", ";", "console", ".", "log", "(", "bar", ".", "cyan", "+", "\"\\n\"", ")", ";", "var", "cb", "=", "getPhantomExitCb", "(", "n", ",", "allSpecs", ",", "cfg", ",", "done", ")", ";", "startPhantom", "(", "specPath", ",", "cfg", ",", "cb", ")", ";", "}" ]
Prints some info and relays config to start the n-th spec @param {Integer} n @param {Array} allSpecs @param {Object} cfg @param {Function} done
[ "Prints", "some", "info", "and", "relays", "config", "to", "start", "the", "n", "-", "th", "spec" ]
a3dc6a8f058bbd4edb161edca5234caa6b2fb27a
https://github.com/jakub-g/grunt-run-phantom-specs/blob/a3dc6a8f058bbd4edb161edca5234caa6b2fb27a/tasks/grunt-run-phantom-specs.js#L106-L119
54,613
phated/grunt-enyo
tasks/init/enyo/root/enyo/source/touch/Scroller.js
function(inSender, e) { // if a scroll event originated here, pass it to our strategy to handle if (this.$.strategy.domScroll && e.originator == this) { this.$.strategy.scroll(inSender, e); } this.doScroll(e); return true; }
javascript
function(inSender, e) { // if a scroll event originated here, pass it to our strategy to handle if (this.$.strategy.domScroll && e.originator == this) { this.$.strategy.scroll(inSender, e); } this.doScroll(e); return true; }
[ "function", "(", "inSender", ",", "e", ")", "{", "// if a scroll event originated here, pass it to our strategy to handle", "if", "(", "this", ".", "$", ".", "strategy", ".", "domScroll", "&&", "e", ".", "originator", "==", "this", ")", "{", "this", ".", "$", ".", "strategy", ".", "scroll", "(", "inSender", ",", "e", ")", ";", "}", "this", ".", "doScroll", "(", "e", ")", ";", "return", "true", ";", "}" ]
Normalizes scroll event to onScroll.
[ "Normalizes", "scroll", "event", "to", "onScroll", "." ]
d2990ee4cd85eea8db4108c43086c6d8c3c90c30
https://github.com/phated/grunt-enyo/blob/d2990ee4cd85eea8db4108c43086c6d8c3c90c30/tasks/init/enyo/root/enyo/source/touch/Scroller.js#L231-L238
54,614
edinella/ploud
public/js/jquery.filedrop.js
function() { var fileIndex; if (stop_loop) { return false; } // Check to see if are in queue mode if (opts.queuefiles > 0 && processingQueue.length >= opts.queuefiles) { return pause(opts.queuewait); } else { // Take first thing off work queue fileIndex = workQueue[0]; workQueue.splice(0, 1); // Add to processing queue processingQueue.push(fileIndex); } try { if (beforeEach(files[fileIndex]) !== false) { if (fileIndex === files_count) { return; } var reader = new FileReader(), max_file_size = 1048576 * opts.maxfilesize; reader.index = fileIndex; if (files[fileIndex].size > max_file_size) { opts.error(errors[2], files[fileIndex], fileIndex); // Remove from queue processingQueue.forEach(function(value, key) { if (value === fileIndex) { processingQueue.splice(key, 1); } }); filesRejected++; return true; } reader.onloadend = !opts.beforeSend ? send : function (e) { opts.beforeSend(files[fileIndex], fileIndex, function () { send(e); }); }; reader.readAsBinaryString(files[fileIndex]); } else { filesRejected++; } } catch (err) { // Remove from queue processingQueue.forEach(function(value, key) { if (value === fileIndex) { processingQueue.splice(key, 1); } }); opts.error(errors[0]); return false; } // If we still have work to do, if (workQueue.length > 0) { process(); } }
javascript
function() { var fileIndex; if (stop_loop) { return false; } // Check to see if are in queue mode if (opts.queuefiles > 0 && processingQueue.length >= opts.queuefiles) { return pause(opts.queuewait); } else { // Take first thing off work queue fileIndex = workQueue[0]; workQueue.splice(0, 1); // Add to processing queue processingQueue.push(fileIndex); } try { if (beforeEach(files[fileIndex]) !== false) { if (fileIndex === files_count) { return; } var reader = new FileReader(), max_file_size = 1048576 * opts.maxfilesize; reader.index = fileIndex; if (files[fileIndex].size > max_file_size) { opts.error(errors[2], files[fileIndex], fileIndex); // Remove from queue processingQueue.forEach(function(value, key) { if (value === fileIndex) { processingQueue.splice(key, 1); } }); filesRejected++; return true; } reader.onloadend = !opts.beforeSend ? send : function (e) { opts.beforeSend(files[fileIndex], fileIndex, function () { send(e); }); }; reader.readAsBinaryString(files[fileIndex]); } else { filesRejected++; } } catch (err) { // Remove from queue processingQueue.forEach(function(value, key) { if (value === fileIndex) { processingQueue.splice(key, 1); } }); opts.error(errors[0]); return false; } // If we still have work to do, if (workQueue.length > 0) { process(); } }
[ "function", "(", ")", "{", "var", "fileIndex", ";", "if", "(", "stop_loop", ")", "{", "return", "false", ";", "}", "// Check to see if are in queue mode", "if", "(", "opts", ".", "queuefiles", ">", "0", "&&", "processingQueue", ".", "length", ">=", "opts", ".", "queuefiles", ")", "{", "return", "pause", "(", "opts", ".", "queuewait", ")", ";", "}", "else", "{", "// Take first thing off work queue", "fileIndex", "=", "workQueue", "[", "0", "]", ";", "workQueue", ".", "splice", "(", "0", ",", "1", ")", ";", "// Add to processing queue", "processingQueue", ".", "push", "(", "fileIndex", ")", ";", "}", "try", "{", "if", "(", "beforeEach", "(", "files", "[", "fileIndex", "]", ")", "!==", "false", ")", "{", "if", "(", "fileIndex", "===", "files_count", ")", "{", "return", ";", "}", "var", "reader", "=", "new", "FileReader", "(", ")", ",", "max_file_size", "=", "1048576", "*", "opts", ".", "maxfilesize", ";", "reader", ".", "index", "=", "fileIndex", ";", "if", "(", "files", "[", "fileIndex", "]", ".", "size", ">", "max_file_size", ")", "{", "opts", ".", "error", "(", "errors", "[", "2", "]", ",", "files", "[", "fileIndex", "]", ",", "fileIndex", ")", ";", "// Remove from queue", "processingQueue", ".", "forEach", "(", "function", "(", "value", ",", "key", ")", "{", "if", "(", "value", "===", "fileIndex", ")", "{", "processingQueue", ".", "splice", "(", "key", ",", "1", ")", ";", "}", "}", ")", ";", "filesRejected", "++", ";", "return", "true", ";", "}", "reader", ".", "onloadend", "=", "!", "opts", ".", "beforeSend", "?", "send", ":", "function", "(", "e", ")", "{", "opts", ".", "beforeSend", "(", "files", "[", "fileIndex", "]", ",", "fileIndex", ",", "function", "(", ")", "{", "send", "(", "e", ")", ";", "}", ")", ";", "}", ";", "reader", ".", "readAsBinaryString", "(", "files", "[", "fileIndex", "]", ")", ";", "}", "else", "{", "filesRejected", "++", ";", "}", "}", "catch", "(", "err", ")", "{", "// Remove from queue", "processingQueue", ".", "forEach", "(", "function", "(", "value", ",", "key", ")", "{", "if", "(", "value", "===", "fileIndex", ")", "{", "processingQueue", ".", "splice", "(", "key", ",", "1", ")", ";", "}", "}", ")", ";", "opts", ".", "error", "(", "errors", "[", "0", "]", ")", ";", "return", "false", ";", "}", "// If we still have work to do,", "if", "(", "workQueue", ".", "length", ">", "0", ")", "{", "process", "(", ")", ";", "}", "}" ]
Process an upload, recursive
[ "Process", "an", "upload", "recursive" ]
ccf01fd213482b320a0a804f100eaae007103b6d
https://github.com/edinella/ploud/blob/ccf01fd213482b320a0a804f100eaae007103b6d/public/js/jquery.filedrop.js#L224-L289
54,615
Magneds/hapi-plugin-barcode
source/QR.js
ratio
function ratio(options) { const { width, height } = options; if ((width || height) && !(width && height)) { if (width) { options.height = width; } if (height) { options.width = height; } } return options; }
javascript
function ratio(options) { const { width, height } = options; if ((width || height) && !(width && height)) { if (width) { options.height = width; } if (height) { options.width = height; } } return options; }
[ "function", "ratio", "(", "options", ")", "{", "const", "{", "width", ",", "height", "}", "=", "options", ";", "if", "(", "(", "width", "||", "height", ")", "&&", "!", "(", "width", "&&", "height", ")", ")", "{", "if", "(", "width", ")", "{", "options", ".", "height", "=", "width", ";", "}", "if", "(", "height", ")", "{", "options", ".", "width", "=", "height", ";", "}", "}", "return", "options", ";", "}" ]
Determine the correct "opposite" dimension in case only one of width or height is provided @param {object} options @returns {object} options
[ "Determine", "the", "correct", "opposite", "dimension", "in", "case", "only", "one", "of", "width", "or", "height", "is", "provided" ]
4822bd2d1aa327a752a9573151396496c080424d
https://github.com/Magneds/hapi-plugin-barcode/blob/4822bd2d1aa327a752a9573151396496c080424d/source/QR.js#L18-L31
54,616
shinuza/captain-core
lib/util/index.js
loginRequired
function loginRequired(fn) { return function(req, res, next) { if(isLoggedIn(req)) { fn(req, res, next); } else { next(new exceptions.PermissionRequired()); } } }
javascript
function loginRequired(fn) { return function(req, res, next) { if(isLoggedIn(req)) { fn(req, res, next); } else { next(new exceptions.PermissionRequired()); } } }
[ "function", "loginRequired", "(", "fn", ")", "{", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "isLoggedIn", "(", "req", ")", ")", "{", "fn", "(", "req", ",", "res", ",", "next", ")", ";", "}", "else", "{", "next", "(", "new", "exceptions", ".", "PermissionRequired", "(", ")", ")", ";", "}", "}", "}" ]
Middleware indicating that the view `fn` requires login @param fn @returns {Function}
[ "Middleware", "indicating", "that", "the", "view", "fn", "requires", "login" ]
02f3a404cdfca608e8726bbacc33e32fec484b21
https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/util/index.js#L25-L33
54,617
bahmutov/jshint-solid
src/jshint-solid.js
settingsPercentage
function settingsPercentage(projectJshintSettings) { verify.object(projectJshintSettings, 'expected jshint object'); //console.log('looking at jshint settings\n' + // JSON.stringify(projectJshintSettings, null, 2)); var allSettings = getAllSettings(); verify.object(allSettings, 'could not get all jshint settings'); var totalSettings = Object.keys(allSettings).length; verify.positiveNumber(totalSettings, 'epected all settings to have properties'); Object.keys(projectJshintSettings).forEach(function (key) { if (key === 'predef') { return; } if (typeof allSettings[key] === 'undefined') { console.error('unknown setting', key, projectJshintSettings[key]); } }); var specifiedSettings = Object.keys(projectJshintSettings).length; return +(specifiedSettings / totalSettings * 100).toPrecision(2); }
javascript
function settingsPercentage(projectJshintSettings) { verify.object(projectJshintSettings, 'expected jshint object'); //console.log('looking at jshint settings\n' + // JSON.stringify(projectJshintSettings, null, 2)); var allSettings = getAllSettings(); verify.object(allSettings, 'could not get all jshint settings'); var totalSettings = Object.keys(allSettings).length; verify.positiveNumber(totalSettings, 'epected all settings to have properties'); Object.keys(projectJshintSettings).forEach(function (key) { if (key === 'predef') { return; } if (typeof allSettings[key] === 'undefined') { console.error('unknown setting', key, projectJshintSettings[key]); } }); var specifiedSettings = Object.keys(projectJshintSettings).length; return +(specifiedSettings / totalSettings * 100).toPrecision(2); }
[ "function", "settingsPercentage", "(", "projectJshintSettings", ")", "{", "verify", ".", "object", "(", "projectJshintSettings", ",", "'expected jshint object'", ")", ";", "//console.log('looking at jshint settings\\n' +", "// JSON.stringify(projectJshintSettings, null, 2));", "var", "allSettings", "=", "getAllSettings", "(", ")", ";", "verify", ".", "object", "(", "allSettings", ",", "'could not get all jshint settings'", ")", ";", "var", "totalSettings", "=", "Object", ".", "keys", "(", "allSettings", ")", ".", "length", ";", "verify", ".", "positiveNumber", "(", "totalSettings", ",", "'epected all settings to have properties'", ")", ";", "Object", ".", "keys", "(", "projectJshintSettings", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "key", "===", "'predef'", ")", "{", "return", ";", "}", "if", "(", "typeof", "allSettings", "[", "key", "]", "===", "'undefined'", ")", "{", "console", ".", "error", "(", "'unknown setting'", ",", "key", ",", "projectJshintSettings", "[", "key", "]", ")", ";", "}", "}", ")", ";", "var", "specifiedSettings", "=", "Object", ".", "keys", "(", "projectJshintSettings", ")", ".", "length", ";", "return", "+", "(", "specifiedSettings", "/", "totalSettings", "*", "100", ")", ".", "toPrecision", "(", "2", ")", ";", "}" ]
returns percent 0 - no valid settings, 100 - all settings specified
[ "returns", "percent", "0", "-", "no", "valid", "settings", "100", "-", "all", "settings", "specified" ]
26f86494a9961cdc3cec566d2a6809daac8c2e29
https://github.com/bahmutov/jshint-solid/blob/26f86494a9961cdc3cec566d2a6809daac8c2e29/src/jshint-solid.js#L17-L39
54,618
airbrite/muni
collection.js
function() { var ret = Backbone.Collection.prototype.set.apply(this, arguments); this.each(function(model) { // Assign `db` to all models in the collection if (this.db) { model.db = this.db; } // Assign `user` to all models in the collection if (this.user) { model.user = this.user; } }.bind(this)); return ret; }
javascript
function() { var ret = Backbone.Collection.prototype.set.apply(this, arguments); this.each(function(model) { // Assign `db` to all models in the collection if (this.db) { model.db = this.db; } // Assign `user` to all models in the collection if (this.user) { model.user = this.user; } }.bind(this)); return ret; }
[ "function", "(", ")", "{", "var", "ret", "=", "Backbone", ".", "Collection", ".", "prototype", ".", "set", ".", "apply", "(", "this", ",", "arguments", ")", ";", "this", ".", "each", "(", "function", "(", "model", ")", "{", "// Assign `db` to all models in the collection", "if", "(", "this", ".", "db", ")", "{", "model", ".", "db", "=", "this", ".", "db", ";", "}", "// Assign `user` to all models in the collection", "if", "(", "this", ".", "user", ")", "{", "model", ".", "user", "=", "this", ".", "user", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "return", "ret", ";", "}" ]
Override to assign `db` and `user` to all models in the collection on `set` Note that the prototype must be called first and returned at the end
[ "Override", "to", "assign", "db", "and", "user", "to", "all", "models", "in", "the", "collection", "on", "set", "Note", "that", "the", "prototype", "must", "be", "called", "first", "and", "returned", "at", "the", "end" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/collection.js#L51-L67
54,619
iAmNathanJ/file-pluck
index.js
writeJSON
function writeJSON(filename, obj) { return new Promise(function (resolve, reject) { if (!Object.is(obj)) resolve(new Error('writeJSON requires the second argument to be an object')); _fs2['default'].writeFile(filename, JSON.stringify(obj, null, 2) + '\n', function (err) { if (err) reject(err); resolve(obj); }); }); }
javascript
function writeJSON(filename, obj) { return new Promise(function (resolve, reject) { if (!Object.is(obj)) resolve(new Error('writeJSON requires the second argument to be an object')); _fs2['default'].writeFile(filename, JSON.stringify(obj, null, 2) + '\n', function (err) { if (err) reject(err); resolve(obj); }); }); }
[ "function", "writeJSON", "(", "filename", ",", "obj", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "!", "Object", ".", "is", "(", "obj", ")", ")", "resolve", "(", "new", "Error", "(", "'writeJSON requires the second argument to be an object'", ")", ")", ";", "_fs2", "[", "'default'", "]", ".", "writeFile", "(", "filename", ",", "JSON", ".", "stringify", "(", "obj", ",", "null", ",", "2", ")", "+", "'\\n'", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "reject", "(", "err", ")", ";", "resolve", "(", "obj", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
write json file, return promise
[ "write", "json", "file", "return", "promise" ]
bbdd91dd8afa21076108553676045a94c76922b3
https://github.com/iAmNathanJ/file-pluck/blob/bbdd91dd8afa21076108553676045a94c76922b3/index.js#L68-L79
54,620
binocarlos/rationalnestedset
lib/rationalnestedset.js
encode
function encode(position_array){ if(!_.isArray(position_array) || position_array.length<=0){ throw new Error('Array of tree positions required'); } var left_position_array = _.map(position_array, function(v){return v;}); var right_position_array = _.map(position_array, function(v){return v;}); // lets modify the last position in the right hand sequence so it is one more than the left var last_position = right_position_array.pop(); last_position++; right_position_array.push(last_position); return { left:calculate_encoding_from_tree_position(left_position_array), right:calculate_encoding_from_tree_position(right_position_array) } }
javascript
function encode(position_array){ if(!_.isArray(position_array) || position_array.length<=0){ throw new Error('Array of tree positions required'); } var left_position_array = _.map(position_array, function(v){return v;}); var right_position_array = _.map(position_array, function(v){return v;}); // lets modify the last position in the right hand sequence so it is one more than the left var last_position = right_position_array.pop(); last_position++; right_position_array.push(last_position); return { left:calculate_encoding_from_tree_position(left_position_array), right:calculate_encoding_from_tree_position(right_position_array) } }
[ "function", "encode", "(", "position_array", ")", "{", "if", "(", "!", "_", ".", "isArray", "(", "position_array", ")", "||", "position_array", ".", "length", "<=", "0", ")", "{", "throw", "new", "Error", "(", "'Array of tree positions required'", ")", ";", "}", "var", "left_position_array", "=", "_", ".", "map", "(", "position_array", ",", "function", "(", "v", ")", "{", "return", "v", ";", "}", ")", ";", "var", "right_position_array", "=", "_", ".", "map", "(", "position_array", ",", "function", "(", "v", ")", "{", "return", "v", ";", "}", ")", ";", "// lets modify the last position in the right hand sequence so it is one more than the left", "var", "last_position", "=", "right_position_array", ".", "pop", "(", ")", ";", "last_position", "++", ";", "right_position_array", ".", "push", "(", "last_position", ")", ";", "return", "{", "left", ":", "calculate_encoding_from_tree_position", "(", "left_position_array", ")", ",", "right", ":", "calculate_encoding_from_tree_position", "(", "right_position_array", ")", "}", "}" ]
Uses calculate_encoding_from_tree_position to calculate the left and right encoding for a given node It simply adds 1 to the last position in the array to get the encodings for its next sibling
[ "Uses", "calculate_encoding_from_tree_position", "to", "calculate", "the", "left", "and", "right", "encoding", "for", "a", "given", "node", "It", "simply", "adds", "1", "to", "the", "last", "position", "in", "the", "array", "to", "get", "the", "encodings", "for", "its", "next", "sibling" ]
a91b420e5de0deb00541fc547ad7e0b1f94e7d70
https://github.com/binocarlos/rationalnestedset/blob/a91b420e5de0deb00541fc547ad7e0b1f94e7d70/lib/rationalnestedset.js#L33-L53
54,621
binocarlos/rationalnestedset
lib/rationalnestedset.js
get_parsed_encodings
function get_parsed_encodings(data){ return { numerator:data.numerator, denominator:data.denominator, encoding:get_big_division(data.numerator, data.denominator) }; }
javascript
function get_parsed_encodings(data){ return { numerator:data.numerator, denominator:data.denominator, encoding:get_big_division(data.numerator, data.denominator) }; }
[ "function", "get_parsed_encodings", "(", "data", ")", "{", "return", "{", "numerator", ":", "data", ".", "numerator", ",", "denominator", ":", "data", ".", "denominator", ",", "encoding", ":", "get_big_division", "(", "data", ".", "numerator", ",", "data", ".", "denominator", ")", "}", ";", "}" ]
uses GMP to divide the numerator by the denominator and convert all values to string @access public @param object $data containing GMP numerator and denominator resources @return object $data containing refactored integer, numerator and denominator string properties
[ "uses", "GMP", "to", "divide", "the", "numerator", "by", "the", "denominator", "and", "convert", "all", "values", "to", "string" ]
a91b420e5de0deb00541fc547ad7e0b1f94e7d70
https://github.com/binocarlos/rationalnestedset/blob/a91b420e5de0deb00541fc547ad7e0b1f94e7d70/lib/rationalnestedset.js#L62-L73
54,622
binocarlos/rationalnestedset
lib/rationalnestedset.js
calculate_encoding_from_tree_position
function calculate_encoding_from_tree_position(position_array){ // if we have only one position then it means we have a root element (i.e. one at the top of the tree) // and this is an easy fraction to calculate (i.e. x / 1) if(position_array.length==1){ return get_parsed_encodings({ // the numerator is the position of the root element numerator:position_array[0], // the denominator is always 1 denominator:1 }); } // initialize the data array we will work with var data = { parts:_.map(position_array, function(v){return v;}), unityparts:[] }; // lets insert the alternate unity into the position array for(var i=0; i<data.parts.length; i++) { // add the next element into the array // and as long as we are not the last element, insert unity data.unityparts.push(data.parts[i]); if(i<data.parts.length-1) { data.unityparts.push(1); } } // There will always be AT LEAST 3 elements in the array at this point // initialize values by purging the last element from the array as the initial numerator // the denominator will always start off as null because the first fraction will be just the last_element (i.e. last_element / 1) data.numerator = data.unityparts.pop(); data.denominator = 1; // the integer starts off as 0 to deal with the not-possible event of if we only had 1 or 2 array elements data.integer = 0; // now lets start reducing the continued fraction! while(data.unityparts.length>0) { data.integer = data.unityparts.pop(); data = reduce_continued_fraction_step(data); // this has just performed: // a,b -> a + 1 / b } return get_parsed_encodings(data); }
javascript
function calculate_encoding_from_tree_position(position_array){ // if we have only one position then it means we have a root element (i.e. one at the top of the tree) // and this is an easy fraction to calculate (i.e. x / 1) if(position_array.length==1){ return get_parsed_encodings({ // the numerator is the position of the root element numerator:position_array[0], // the denominator is always 1 denominator:1 }); } // initialize the data array we will work with var data = { parts:_.map(position_array, function(v){return v;}), unityparts:[] }; // lets insert the alternate unity into the position array for(var i=0; i<data.parts.length; i++) { // add the next element into the array // and as long as we are not the last element, insert unity data.unityparts.push(data.parts[i]); if(i<data.parts.length-1) { data.unityparts.push(1); } } // There will always be AT LEAST 3 elements in the array at this point // initialize values by purging the last element from the array as the initial numerator // the denominator will always start off as null because the first fraction will be just the last_element (i.e. last_element / 1) data.numerator = data.unityparts.pop(); data.denominator = 1; // the integer starts off as 0 to deal with the not-possible event of if we only had 1 or 2 array elements data.integer = 0; // now lets start reducing the continued fraction! while(data.unityparts.length>0) { data.integer = data.unityparts.pop(); data = reduce_continued_fraction_step(data); // this has just performed: // a,b -> a + 1 / b } return get_parsed_encodings(data); }
[ "function", "calculate_encoding_from_tree_position", "(", "position_array", ")", "{", "// if we have only one position then it means we have a root element (i.e. one at the top of the tree)", "// and this is an easy fraction to calculate (i.e. x / 1)", "if", "(", "position_array", ".", "length", "==", "1", ")", "{", "return", "get_parsed_encodings", "(", "{", "// the numerator is the position of the root element", "numerator", ":", "position_array", "[", "0", "]", ",", "// the denominator is always 1", "denominator", ":", "1", "}", ")", ";", "}", "// initialize the data array we will work with", "var", "data", "=", "{", "parts", ":", "_", ".", "map", "(", "position_array", ",", "function", "(", "v", ")", "{", "return", "v", ";", "}", ")", ",", "unityparts", ":", "[", "]", "}", ";", "// lets insert the alternate unity into the position array", "for", "(", "var", "i", "=", "0", ";", "i", "<", "data", ".", "parts", ".", "length", ";", "i", "++", ")", "{", "// add the next element into the array", "// and as long as we are not the last element, insert unity", "data", ".", "unityparts", ".", "push", "(", "data", ".", "parts", "[", "i", "]", ")", ";", "if", "(", "i", "<", "data", ".", "parts", ".", "length", "-", "1", ")", "{", "data", ".", "unityparts", ".", "push", "(", "1", ")", ";", "}", "}", "// There will always be AT LEAST 3 elements in the array at this point", "// initialize values by purging the last element from the array as the initial numerator", "// the denominator will always start off as null because the first fraction will be just the last_element (i.e. last_element / 1)", "data", ".", "numerator", "=", "data", ".", "unityparts", ".", "pop", "(", ")", ";", "data", ".", "denominator", "=", "1", ";", "// the integer starts off as 0 to deal with the not-possible event of if we only had 1 or 2 array elements", "data", ".", "integer", "=", "0", ";", "// now lets start reducing the continued fraction!", "while", "(", "data", ".", "unityparts", ".", "length", ">", "0", ")", "{", "data", ".", "integer", "=", "data", ".", "unityparts", ".", "pop", "(", ")", ";", "data", "=", "reduce_continued_fraction_step", "(", "data", ")", ";", "// this has just performed:", "// a,b -> a + 1 / b", "}", "return", "get_parsed_encodings", "(", "data", ")", ";", "}" ]
Calculates a finite continued fraction encoding of tree position returning a numerator and denominator representing the encoding The tree position is provided as an array of positions, so for example the 3rd element of the 7th element of the 2nd element is represented as: // returns array('n' => 65, 'd' => 23) // passed array represents root -> 2nd node -> 4th node -> 3rd node // Tree_Nestedsetencoder::calculate_encoding_from_tree_position(array(2, 4, 3)); This will return a numerator and denominator in an object that can be saved to the database It reduces a continued fraction after alternating unity into the position array @access public @param array $tree_position_array (default: array()) an array of the numeric tree positions for the node to calculate an encoding for @return object and object containing 'numerator', 'denominator' and 'rational' string properties
[ "Calculates", "a", "finite", "continued", "fraction", "encoding", "of", "tree", "position", "returning", "a", "numerator", "and", "denominator", "representing", "the", "encoding" ]
a91b420e5de0deb00541fc547ad7e0b1f94e7d70
https://github.com/binocarlos/rationalnestedset/blob/a91b420e5de0deb00541fc547ad7e0b1f94e7d70/lib/rationalnestedset.js#L175-L232
54,623
AntouanK/consologger
dist/browser-consologger.js
builder
function builder() { // make the arguments one string var args = stringify.apply(null, arguments); // make the final styles object builder._curStyles.forEach(function (thisStyle) { objectAssign(builder._curStyle, thisStyle); }); loggerInstance._inputsBuffer.push({ arg: args, style: builder._curStyle }); // reset the state builder._curStyle = objectAssign({}, defaults.style); builder._curStyles = []; return builder; }
javascript
function builder() { // make the arguments one string var args = stringify.apply(null, arguments); // make the final styles object builder._curStyles.forEach(function (thisStyle) { objectAssign(builder._curStyle, thisStyle); }); loggerInstance._inputsBuffer.push({ arg: args, style: builder._curStyle }); // reset the state builder._curStyle = objectAssign({}, defaults.style); builder._curStyles = []; return builder; }
[ "function", "builder", "(", ")", "{", "// make the arguments one string", "var", "args", "=", "stringify", ".", "apply", "(", "null", ",", "arguments", ")", ";", "// make the final styles object", "builder", ".", "_curStyles", ".", "forEach", "(", "function", "(", "thisStyle", ")", "{", "objectAssign", "(", "builder", ".", "_curStyle", ",", "thisStyle", ")", ";", "}", ")", ";", "loggerInstance", ".", "_inputsBuffer", ".", "push", "(", "{", "arg", ":", "args", ",", "style", ":", "builder", ".", "_curStyle", "}", ")", ";", "// reset the state", "builder", ".", "_curStyle", "=", "objectAssign", "(", "{", "}", ",", "defaults", ".", "style", ")", ";", "builder", ".", "_curStyles", "=", "[", "]", ";", "return", "builder", ";", "}" ]
the main builder function that's what we return, and all the presets are properties of this
[ "the", "main", "builder", "function", "that", "s", "what", "we", "return", "and", "all", "the", "presets", "are", "properties", "of", "this" ]
fb021a8bf3dda16f151ba9237124eb6f1c680ef1
https://github.com/AntouanK/consologger/blob/fb021a8bf3dda16f151ba9237124eb6f1c680ef1/dist/browser-consologger.js#L122-L142
54,624
olizilla/grunt-asciify
tasks/asciify.js
trimToMaxWidth
function trimToMaxWidth (width, text) { var truncated = text.split('\n').map(function (line) { return line.substring(0, width); }); return truncated.join('\n'); }
javascript
function trimToMaxWidth (width, text) { var truncated = text.split('\n').map(function (line) { return line.substring(0, width); }); return truncated.join('\n'); }
[ "function", "trimToMaxWidth", "(", "width", ",", "text", ")", "{", "var", "truncated", "=", "text", ".", "split", "(", "'\\n'", ")", ".", "map", "(", "function", "(", "line", ")", "{", "return", "line", ".", "substring", "(", "0", ",", "width", ")", ";", "}", ")", ";", "return", "truncated", ".", "join", "(", "'\\n'", ")", ";", "}" ]
truncate the ascii art to fit a thing
[ "truncate", "the", "ascii", "art", "to", "fit", "a", "thing" ]
0a72ed3451478334fae4e96b0f8e2cd58cfeee2a
https://github.com/olizilla/grunt-asciify/blob/0a72ed3451478334fae4e96b0f8e2cd58cfeee2a/tasks/asciify.js#L58-L63
54,625
mwyatt/feedback-queue
js/feedbackQueue.js
getContainer
function getContainer() { if (container) { return container; } body.insertAdjacentHTML('afterbegin', mustache.render(containerTemplate)); container = document.querySelector('.js-feedback-queue'); return container; }
javascript
function getContainer() { if (container) { return container; } body.insertAdjacentHTML('afterbegin', mustache.render(containerTemplate)); container = document.querySelector('.js-feedback-queue'); return container; }
[ "function", "getContainer", "(", ")", "{", "if", "(", "container", ")", "{", "return", "container", ";", "}", "body", ".", "insertAdjacentHTML", "(", "'afterbegin'", ",", "mustache", ".", "render", "(", "containerTemplate", ")", ")", ";", "container", "=", "document", ".", "querySelector", "(", "'.js-feedback-queue'", ")", ";", "return", "container", ";", "}" ]
create and or return dom node
[ "create", "and", "or", "return", "dom", "node" ]
25a7b13bd783db190dc85c6709db4616aa7e14b4
https://github.com/mwyatt/feedback-queue/blob/25a7b13bd783db190dc85c6709db4616aa7e14b4/js/feedbackQueue.js#L13-L22
54,626
huafu/ember-dev-fixtures
private/adapters/dev-fixtures.js
function (store, type, record, addId) { var json; type = this._parseModelOrType(store, type); json = record.serialize({includeId: true}); if (!json.id && addId) { json.id = this.generateId(store, type); } type.eachRelationship(function (key, meta) { var records; if (!meta.async && meta.kind === 'hasMany' && (records = record.get(key)) && !json[key]) { json[key] = records.mapBy('id').filter(Boolean); } }); return json; }
javascript
function (store, type, record, addId) { var json; type = this._parseModelOrType(store, type); json = record.serialize({includeId: true}); if (!json.id && addId) { json.id = this.generateId(store, type); } type.eachRelationship(function (key, meta) { var records; if (!meta.async && meta.kind === 'hasMany' && (records = record.get(key)) && !json[key]) { json[key] = records.mapBy('id').filter(Boolean); } }); return json; }
[ "function", "(", "store", ",", "type", ",", "record", ",", "addId", ")", "{", "var", "json", ";", "type", "=", "this", ".", "_parseModelOrType", "(", "store", ",", "type", ")", ";", "json", "=", "record", ".", "serialize", "(", "{", "includeId", ":", "true", "}", ")", ";", "if", "(", "!", "json", ".", "id", "&&", "addId", ")", "{", "json", ".", "id", "=", "this", ".", "generateId", "(", "store", ",", "type", ")", ";", "}", "type", ".", "eachRelationship", "(", "function", "(", "key", ",", "meta", ")", "{", "var", "records", ";", "if", "(", "!", "meta", ".", "async", "&&", "meta", ".", "kind", "===", "'hasMany'", "&&", "(", "records", "=", "record", ".", "get", "(", "key", ")", ")", "&&", "!", "json", "[", "key", "]", ")", "{", "json", "[", "key", "]", "=", "records", ".", "mapBy", "(", "'id'", ")", ".", "filter", "(", "Boolean", ")", ";", "}", "}", ")", ";", "return", "json", ";", "}" ]
Generate the JSON for a record @method mockJSON @param {DS.Store} store @param {subclass of DS.Model|string} type @param {DS.Model} record @param {boolean} [addId=false] @return {Object}
[ "Generate", "the", "JSON", "for", "a", "record" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/adapters/dev-fixtures.js#L169-L183
54,627
huafu/ember-dev-fixtures
private/adapters/dev-fixtures.js
function (store, type/*, record*/) { var key, counters; key = dasherize(this._parseModelOrType(store, type).typeKey); counters = this.get('_generatedCounterId'); if (!counters[key]) { counters[key] = 1; } return 'fixture-' + key + '-' + (counters[key]++); }
javascript
function (store, type/*, record*/) { var key, counters; key = dasherize(this._parseModelOrType(store, type).typeKey); counters = this.get('_generatedCounterId'); if (!counters[key]) { counters[key] = 1; } return 'fixture-' + key + '-' + (counters[key]++); }
[ "function", "(", "store", ",", "type", "/*, record*/", ")", "{", "var", "key", ",", "counters", ";", "key", "=", "dasherize", "(", "this", ".", "_parseModelOrType", "(", "store", ",", "type", ")", ".", "typeKey", ")", ";", "counters", "=", "this", ".", "get", "(", "'_generatedCounterId'", ")", ";", "if", "(", "!", "counters", "[", "key", "]", ")", "{", "counters", "[", "key", "]", "=", "1", ";", "}", "return", "'fixture-'", "+", "key", "+", "'-'", "+", "(", "counters", "[", "key", "]", "++", ")", ";", "}" ]
Generates an ID for a record @method generateId @param {DS.Store} store @param {subclass of DS.Model|string} type @param {DS.Model} record @return {String} id
[ "Generates", "an", "ID", "for", "a", "record" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/adapters/dev-fixtures.js#L194-L202
54,628
huafu/ember-dev-fixtures
private/adapters/dev-fixtures.js
function (store, type, id) { id = coerceId(id); return this.fixturesForType(store, type).find(function (record) { return coerceId(record.id) === id; }); }
javascript
function (store, type, id) { id = coerceId(id); return this.fixturesForType(store, type).find(function (record) { return coerceId(record.id) === id; }); }
[ "function", "(", "store", ",", "type", ",", "id", ")", "{", "id", "=", "coerceId", "(", "id", ")", ";", "return", "this", ".", "fixturesForType", "(", "store", ",", "type", ")", ".", "find", "(", "function", "(", "record", ")", "{", "return", "coerceId", "(", "record", ".", "id", ")", "===", "id", ";", "}", ")", ";", "}" ]
Get a fixture for a given type and ID @method fixtureForId @param {DS.Store} store @param {DS.Model} type @param {string|number} id @return {Object}
[ "Get", "a", "fixture", "for", "a", "given", "type", "and", "ID" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/adapters/dev-fixtures.js#L323-L328
54,629
huafu/ember-dev-fixtures
private/adapters/dev-fixtures.js
function (response, statusCode, statusText) { var adapter = this, responseFunction, isOk, shouldCopy, isInvalid; statusCode = statusCode || 200; statusText = statusText || HTTP_STATUS_MESSAGES[statusCode]; isOk = Math.round(statusCode / 100) === 2; if (typeof response === 'function') { shouldCopy = true; responseFunction = bind(this, response); } else { isInvalid = response instanceof DS.InvalidError; if (isInvalid) { response = new DS.InvalidError(response.errors); } else { response = copy(response, true); } responseFunction = function () { return response; }; } return new Ember.RSVP.Promise(function (resolve, reject) { var value, func, data; func = isOk ? resolve : reject; data = responseFunction(); if (shouldCopy) { data = copy(data, true); } value = isOk ? data : (isInvalid ? data : { response: data || {error: statusText}, responseJSON: data || {error: statusText}, status: statusCode, statusText: statusText }); Ember.runInDebug(function () { console[isOk ? 'log' : 'error']( fmt('[dev-fixtures] Simulating %@ response:', isOk ? 'success' : 'error'), copy(response, true) ); }); if (adapter.get('simulateRemoteResponse')) { // Schedule with setTimeout later(null, func, value, adapter.get('latency')); } else { // Asynchronous, but at the of the run-loop with zero latency schedule('actions', null, func, value); } }, "DS: DevFixtureAdapter#simulateRemoteCall"); }
javascript
function (response, statusCode, statusText) { var adapter = this, responseFunction, isOk, shouldCopy, isInvalid; statusCode = statusCode || 200; statusText = statusText || HTTP_STATUS_MESSAGES[statusCode]; isOk = Math.round(statusCode / 100) === 2; if (typeof response === 'function') { shouldCopy = true; responseFunction = bind(this, response); } else { isInvalid = response instanceof DS.InvalidError; if (isInvalid) { response = new DS.InvalidError(response.errors); } else { response = copy(response, true); } responseFunction = function () { return response; }; } return new Ember.RSVP.Promise(function (resolve, reject) { var value, func, data; func = isOk ? resolve : reject; data = responseFunction(); if (shouldCopy) { data = copy(data, true); } value = isOk ? data : (isInvalid ? data : { response: data || {error: statusText}, responseJSON: data || {error: statusText}, status: statusCode, statusText: statusText }); Ember.runInDebug(function () { console[isOk ? 'log' : 'error']( fmt('[dev-fixtures] Simulating %@ response:', isOk ? 'success' : 'error'), copy(response, true) ); }); if (adapter.get('simulateRemoteResponse')) { // Schedule with setTimeout later(null, func, value, adapter.get('latency')); } else { // Asynchronous, but at the of the run-loop with zero latency schedule('actions', null, func, value); } }, "DS: DevFixtureAdapter#simulateRemoteCall"); }
[ "function", "(", "response", ",", "statusCode", ",", "statusText", ")", "{", "var", "adapter", "=", "this", ",", "responseFunction", ",", "isOk", ",", "shouldCopy", ",", "isInvalid", ";", "statusCode", "=", "statusCode", "||", "200", ";", "statusText", "=", "statusText", "||", "HTTP_STATUS_MESSAGES", "[", "statusCode", "]", ";", "isOk", "=", "Math", ".", "round", "(", "statusCode", "/", "100", ")", "===", "2", ";", "if", "(", "typeof", "response", "===", "'function'", ")", "{", "shouldCopy", "=", "true", ";", "responseFunction", "=", "bind", "(", "this", ",", "response", ")", ";", "}", "else", "{", "isInvalid", "=", "response", "instanceof", "DS", ".", "InvalidError", ";", "if", "(", "isInvalid", ")", "{", "response", "=", "new", "DS", ".", "InvalidError", "(", "response", ".", "errors", ")", ";", "}", "else", "{", "response", "=", "copy", "(", "response", ",", "true", ")", ";", "}", "responseFunction", "=", "function", "(", ")", "{", "return", "response", ";", "}", ";", "}", "return", "new", "Ember", ".", "RSVP", ".", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "value", ",", "func", ",", "data", ";", "func", "=", "isOk", "?", "resolve", ":", "reject", ";", "data", "=", "responseFunction", "(", ")", ";", "if", "(", "shouldCopy", ")", "{", "data", "=", "copy", "(", "data", ",", "true", ")", ";", "}", "value", "=", "isOk", "?", "data", ":", "(", "isInvalid", "?", "data", ":", "{", "response", ":", "data", "||", "{", "error", ":", "statusText", "}", ",", "responseJSON", ":", "data", "||", "{", "error", ":", "statusText", "}", ",", "status", ":", "statusCode", ",", "statusText", ":", "statusText", "}", ")", ";", "Ember", ".", "runInDebug", "(", "function", "(", ")", "{", "console", "[", "isOk", "?", "'log'", ":", "'error'", "]", "(", "fmt", "(", "'[dev-fixtures] Simulating %@ response:'", ",", "isOk", "?", "'success'", ":", "'error'", ")", ",", "copy", "(", "response", ",", "true", ")", ")", ";", "}", ")", ";", "if", "(", "adapter", ".", "get", "(", "'simulateRemoteResponse'", ")", ")", "{", "// Schedule with setTimeout", "later", "(", "null", ",", "func", ",", "value", ",", "adapter", ".", "get", "(", "'latency'", ")", ")", ";", "}", "else", "{", "// Asynchronous, but at the of the run-loop with zero latency", "schedule", "(", "'actions'", ",", "null", ",", "func", ",", "value", ")", ";", "}", "}", ",", "\"DS: DevFixtureAdapter#simulateRemoteCall\"", ")", ";", "}" ]
Better method for simulating a remote call @method simulateRemoteCall @param {Object|Function} response @param {number} [statusCode=200] @param {string} [statusText] @return {Promise}
[ "Better", "method", "for", "simulating", "a", "remote", "call" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/adapters/dev-fixtures.js#L340-L389
54,630
huafu/ember-dev-fixtures
private/adapters/dev-fixtures.js
function (store, json) { var handledRecords = [], key, records, handleRecord, Model; handleRecord = function (record) { this.completeJsonForRecord(store, record, Model, json, handledRecords); }; for (key in json) { if (json.hasOwnProperty(key)) { records = json[key]; Model = store.modelFor(singularize(key)); forEach(records, handleRecord, this); } } return json; }
javascript
function (store, json) { var handledRecords = [], key, records, handleRecord, Model; handleRecord = function (record) { this.completeJsonForRecord(store, record, Model, json, handledRecords); }; for (key in json) { if (json.hasOwnProperty(key)) { records = json[key]; Model = store.modelFor(singularize(key)); forEach(records, handleRecord, this); } } return json; }
[ "function", "(", "store", ",", "json", ")", "{", "var", "handledRecords", "=", "[", "]", ",", "key", ",", "records", ",", "handleRecord", ",", "Model", ";", "handleRecord", "=", "function", "(", "record", ")", "{", "this", ".", "completeJsonForRecord", "(", "store", ",", "record", ",", "Model", ",", "json", ",", "handledRecords", ")", ";", "}", ";", "for", "(", "key", "in", "json", ")", "{", "if", "(", "json", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "records", "=", "json", "[", "key", "]", ";", "Model", "=", "store", ".", "modelFor", "(", "singularize", "(", "key", ")", ")", ";", "forEach", "(", "records", ",", "handleRecord", ",", "this", ")", ";", "}", "}", "return", "json", ";", "}" ]
Complete a JSON response to add linked records which are not async @method completeJsonResponse @param {DS.Store} store @param {Object} json @param {string|DS.Model|Object} [injections...]
[ "Complete", "a", "JSON", "response", "to", "add", "linked", "records", "which", "are", "not", "async" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/adapters/dev-fixtures.js#L400-L413
54,631
huafu/ember-dev-fixtures
private/adapters/dev-fixtures.js
function (store, record, Model, json, handledRecords) { if (handledRecords.indexOf(record) === -1) { handledRecords.push(record); Model.eachRelationship(function (name, meta) { var related, fixtures, relatedTypeKey, ids; if (!meta.async && record[name]) { fixtures = Ember.A(this.fixturesForType(store, meta.type)); ids = coerceId(record[name]); if (meta.kind === 'hasMany') { if (ids && ids.length) { related = fixtures.filter(function (r) { return ids.indexOf(coerceId(r.id)) !== -1; }); } } else if (meta.kind === 'belongsTo') { related = fixtures.find(function (r) { return coerceId(r.id) === ids; }); if (related) { related = [related]; } } if (related) { relatedTypeKey = pluralize(meta.type.typeKey); if (!json[relatedTypeKey]) { json[relatedTypeKey] = []; } related.forEach(function (record) { if (json[relatedTypeKey].indexOf(record) === -1) { json[relatedTypeKey].push(record); } this.completeJsonForRecord(store, record, meta.type, json, handledRecords); }, this); } } }, this); } }
javascript
function (store, record, Model, json, handledRecords) { if (handledRecords.indexOf(record) === -1) { handledRecords.push(record); Model.eachRelationship(function (name, meta) { var related, fixtures, relatedTypeKey, ids; if (!meta.async && record[name]) { fixtures = Ember.A(this.fixturesForType(store, meta.type)); ids = coerceId(record[name]); if (meta.kind === 'hasMany') { if (ids && ids.length) { related = fixtures.filter(function (r) { return ids.indexOf(coerceId(r.id)) !== -1; }); } } else if (meta.kind === 'belongsTo') { related = fixtures.find(function (r) { return coerceId(r.id) === ids; }); if (related) { related = [related]; } } if (related) { relatedTypeKey = pluralize(meta.type.typeKey); if (!json[relatedTypeKey]) { json[relatedTypeKey] = []; } related.forEach(function (record) { if (json[relatedTypeKey].indexOf(record) === -1) { json[relatedTypeKey].push(record); } this.completeJsonForRecord(store, record, meta.type, json, handledRecords); }, this); } } }, this); } }
[ "function", "(", "store", ",", "record", ",", "Model", ",", "json", ",", "handledRecords", ")", "{", "if", "(", "handledRecords", ".", "indexOf", "(", "record", ")", "===", "-", "1", ")", "{", "handledRecords", ".", "push", "(", "record", ")", ";", "Model", ".", "eachRelationship", "(", "function", "(", "name", ",", "meta", ")", "{", "var", "related", ",", "fixtures", ",", "relatedTypeKey", ",", "ids", ";", "if", "(", "!", "meta", ".", "async", "&&", "record", "[", "name", "]", ")", "{", "fixtures", "=", "Ember", ".", "A", "(", "this", ".", "fixturesForType", "(", "store", ",", "meta", ".", "type", ")", ")", ";", "ids", "=", "coerceId", "(", "record", "[", "name", "]", ")", ";", "if", "(", "meta", ".", "kind", "===", "'hasMany'", ")", "{", "if", "(", "ids", "&&", "ids", ".", "length", ")", "{", "related", "=", "fixtures", ".", "filter", "(", "function", "(", "r", ")", "{", "return", "ids", ".", "indexOf", "(", "coerceId", "(", "r", ".", "id", ")", ")", "!==", "-", "1", ";", "}", ")", ";", "}", "}", "else", "if", "(", "meta", ".", "kind", "===", "'belongsTo'", ")", "{", "related", "=", "fixtures", ".", "find", "(", "function", "(", "r", ")", "{", "return", "coerceId", "(", "r", ".", "id", ")", "===", "ids", ";", "}", ")", ";", "if", "(", "related", ")", "{", "related", "=", "[", "related", "]", ";", "}", "}", "if", "(", "related", ")", "{", "relatedTypeKey", "=", "pluralize", "(", "meta", ".", "type", ".", "typeKey", ")", ";", "if", "(", "!", "json", "[", "relatedTypeKey", "]", ")", "{", "json", "[", "relatedTypeKey", "]", "=", "[", "]", ";", "}", "related", ".", "forEach", "(", "function", "(", "record", ")", "{", "if", "(", "json", "[", "relatedTypeKey", "]", ".", "indexOf", "(", "record", ")", "===", "-", "1", ")", "{", "json", "[", "relatedTypeKey", "]", ".", "push", "(", "record", ")", ";", "}", "this", ".", "completeJsonForRecord", "(", "store", ",", "record", ",", "meta", ".", "type", ",", "json", ",", "handledRecords", ")", ";", "}", ",", "this", ")", ";", "}", "}", "}", ",", "this", ")", ";", "}", "}" ]
Complete a record adding in the given json the related records which are not defined as async @method completeJsonForRecord @param {DS.Store} store @param {DS.Model} record @param {subclass of DS.Model} Model @param {Object} json @param {Array.<DS.Model>} handledRecords
[ "Complete", "a", "record", "adding", "in", "the", "given", "json", "the", "related", "records", "which", "are", "not", "defined", "as", "async" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/adapters/dev-fixtures.js#L425-L463
54,632
huafu/ember-dev-fixtures
private/adapters/dev-fixtures.js
function (store, type, records) { var json = {}; type = this._parseModelOrType(store, type); json[pluralize(type.typeKey)] = records; this._injectFixturesInResponse.apply(this, [store, json].concat(slice.call(arguments, 3))); return this.completeJsonResponse(store, json); }
javascript
function (store, type, records) { var json = {}; type = this._parseModelOrType(store, type); json[pluralize(type.typeKey)] = records; this._injectFixturesInResponse.apply(this, [store, json].concat(slice.call(arguments, 3))); return this.completeJsonResponse(store, json); }
[ "function", "(", "store", ",", "type", ",", "records", ")", "{", "var", "json", "=", "{", "}", ";", "type", "=", "this", ".", "_parseModelOrType", "(", "store", ",", "type", ")", ";", "json", "[", "pluralize", "(", "type", ".", "typeKey", ")", "]", "=", "records", ";", "this", ".", "_injectFixturesInResponse", ".", "apply", "(", "this", ",", "[", "store", ",", "json", "]", ".", "concat", "(", "slice", ".", "call", "(", "arguments", ",", "3", ")", ")", ")", ";", "return", "this", ".", "completeJsonResponse", "(", "store", ",", "json", ")", ";", "}" ]
Creates a multi-records response for the given type and records array @method createMultiRecordsResponse @param {DS.Store} store @param {DS.Model} type @param {Array.<Object>} records @return {Object}
[ "Creates", "a", "multi", "-", "records", "response", "for", "the", "given", "type", "and", "records", "array" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/adapters/dev-fixtures.js#L491-L497
54,633
huafu/ember-dev-fixtures
private/adapters/dev-fixtures.js
function (errors) { if (typeof errors === 'string' || errors instanceof Error) { errors = {'*': '' + errors}; } else if (errors == null) { errors = {'*': 'Unknown error'}; } return new DS.InvalidError(errors); }
javascript
function (errors) { if (typeof errors === 'string' || errors instanceof Error) { errors = {'*': '' + errors}; } else if (errors == null) { errors = {'*': 'Unknown error'}; } return new DS.InvalidError(errors); }
[ "function", "(", "errors", ")", "{", "if", "(", "typeof", "errors", "===", "'string'", "||", "errors", "instanceof", "Error", ")", "{", "errors", "=", "{", "'*'", ":", "''", "+", "errors", "}", ";", "}", "else", "if", "(", "errors", "==", "null", ")", "{", "errors", "=", "{", "'*'", ":", "'Unknown error'", "}", ";", "}", "return", "new", "DS", ".", "InvalidError", "(", "errors", ")", ";", "}" ]
Creates an error response to be used with simulateResponseCall @method createErrorResponse @param {Object|Error|string} errors @return {Object}
[ "Creates", "an", "error", "response", "to", "be", "used", "with", "simulateResponseCall" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/adapters/dev-fixtures.js#L519-L527
54,634
huafu/ember-dev-fixtures
private/adapters/dev-fixtures.js
function (store, type, fixtureRecord) { var fixture; if (fixtureRecord.id) { type = this._parseModelOrType(store, type); // lookup for a fixture fixture = this.fixtureForId(store, type, fixtureRecord.id); if (fixture) { Ember.merge(fixture, fixtureRecord); this._touchDateAttr(store, type, fixture, 'updatedAt'); return fixture; } } else { throw new Error('Updating a fixture requires an ID.'); } // new fixture this._touchDateAttr(store, type, fixtureRecord, 'createdAt', 'updatedAt'); this.fixturesForType(store, type).pushObject(fixtureRecord); return fixtureRecord; }
javascript
function (store, type, fixtureRecord) { var fixture; if (fixtureRecord.id) { type = this._parseModelOrType(store, type); // lookup for a fixture fixture = this.fixtureForId(store, type, fixtureRecord.id); if (fixture) { Ember.merge(fixture, fixtureRecord); this._touchDateAttr(store, type, fixture, 'updatedAt'); return fixture; } } else { throw new Error('Updating a fixture requires an ID.'); } // new fixture this._touchDateAttr(store, type, fixtureRecord, 'createdAt', 'updatedAt'); this.fixturesForType(store, type).pushObject(fixtureRecord); return fixtureRecord; }
[ "function", "(", "store", ",", "type", ",", "fixtureRecord", ")", "{", "var", "fixture", ";", "if", "(", "fixtureRecord", ".", "id", ")", "{", "type", "=", "this", ".", "_parseModelOrType", "(", "store", ",", "type", ")", ";", "// lookup for a fixture", "fixture", "=", "this", ".", "fixtureForId", "(", "store", ",", "type", ",", "fixtureRecord", ".", "id", ")", ";", "if", "(", "fixture", ")", "{", "Ember", ".", "merge", "(", "fixture", ",", "fixtureRecord", ")", ";", "this", ".", "_touchDateAttr", "(", "store", ",", "type", ",", "fixture", ",", "'updatedAt'", ")", ";", "return", "fixture", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'Updating a fixture requires an ID.'", ")", ";", "}", "// new fixture", "this", ".", "_touchDateAttr", "(", "store", ",", "type", ",", "fixtureRecord", ",", "'createdAt'", ",", "'updatedAt'", ")", ";", "this", ".", "fixturesForType", "(", "store", ",", "type", ")", ".", "pushObject", "(", "fixtureRecord", ")", ";", "return", "fixtureRecord", ";", "}" ]
Update the fixture for given type and fixture record @method updateFixtures @param {DS.Store} store @param {DS.Model|string} type @param {Object} fixtureRecord @return {Object}
[ "Update", "the", "fixture", "for", "given", "type", "and", "fixture", "record" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/adapters/dev-fixtures.js#L538-L557
54,635
huafu/ember-dev-fixtures
private/adapters/dev-fixtures.js
function (store, type, fixtureRecord) { var fixture = fixtureRecord || {}; type = this._parseModelOrType(store, type); if (!fixtureRecord.id) { fixtureRecord.id = this.generateId(store, type); } if (this.fixtureForId(store, type, fixture.id)) { throw new Error('Fixture `' + type.typeKey + '` with id `' + fixture.id + '` already exists.'); } return this.updateFixtures(store, type, fixture); }
javascript
function (store, type, fixtureRecord) { var fixture = fixtureRecord || {}; type = this._parseModelOrType(store, type); if (!fixtureRecord.id) { fixtureRecord.id = this.generateId(store, type); } if (this.fixtureForId(store, type, fixture.id)) { throw new Error('Fixture `' + type.typeKey + '` with id `' + fixture.id + '` already exists.'); } return this.updateFixtures(store, type, fixture); }
[ "function", "(", "store", ",", "type", ",", "fixtureRecord", ")", "{", "var", "fixture", "=", "fixtureRecord", "||", "{", "}", ";", "type", "=", "this", ".", "_parseModelOrType", "(", "store", ",", "type", ")", ";", "if", "(", "!", "fixtureRecord", ".", "id", ")", "{", "fixtureRecord", ".", "id", "=", "this", ".", "generateId", "(", "store", ",", "type", ")", ";", "}", "if", "(", "this", ".", "fixtureForId", "(", "store", ",", "type", ",", "fixture", ".", "id", ")", ")", "{", "throw", "new", "Error", "(", "'Fixture `'", "+", "type", ".", "typeKey", "+", "'` with id `'", "+", "fixture", ".", "id", "+", "'` already exists.'", ")", ";", "}", "return", "this", ".", "updateFixtures", "(", "store", ",", "type", ",", "fixture", ")", ";", "}" ]
Creates a new fixture record and update fixtures with it @method createFixture @param {DS.Store} store @param {DS.Model|string} type @param {Object} [fixtureRecord={}] @return {Object}
[ "Creates", "a", "new", "fixture", "record", "and", "update", "fixtures", "with", "it" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/adapters/dev-fixtures.js#L568-L578
54,636
huafu/ember-dev-fixtures
private/adapters/dev-fixtures.js
function (store, type, fixtureRecord) { var fixture, fixturesArray; if (fixtureRecord.id) { fixture = this.fixtureForId(store, type, fixtureRecord.id); if (fixture) { fixturesArray = this.fixturesForType(store, type); fixturesArray.splice(fixturesArray.indexOf(fixtureRecord), 1); } } else { throw new Error('Deleting a fixture requires an ID.'); } return null; }
javascript
function (store, type, fixtureRecord) { var fixture, fixturesArray; if (fixtureRecord.id) { fixture = this.fixtureForId(store, type, fixtureRecord.id); if (fixture) { fixturesArray = this.fixturesForType(store, type); fixturesArray.splice(fixturesArray.indexOf(fixtureRecord), 1); } } else { throw new Error('Deleting a fixture requires an ID.'); } return null; }
[ "function", "(", "store", ",", "type", ",", "fixtureRecord", ")", "{", "var", "fixture", ",", "fixturesArray", ";", "if", "(", "fixtureRecord", ".", "id", ")", "{", "fixture", "=", "this", ".", "fixtureForId", "(", "store", ",", "type", ",", "fixtureRecord", ".", "id", ")", ";", "if", "(", "fixture", ")", "{", "fixturesArray", "=", "this", ".", "fixturesForType", "(", "store", ",", "type", ")", ";", "fixturesArray", ".", "splice", "(", "fixturesArray", ".", "indexOf", "(", "fixtureRecord", ")", ",", "1", ")", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'Deleting a fixture requires an ID.'", ")", ";", "}", "return", "null", ";", "}" ]
Deletes a fixture for given type and record @method deleteLoadedFixture @param {DS.Store} store @param {DS.Model} type @param {Object} fixtureRecord @return {null}
[ "Deletes", "a", "fixture", "for", "given", "type", "and", "record" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/adapters/dev-fixtures.js#L590-L603
54,637
huafu/ember-dev-fixtures
private/adapters/dev-fixtures.js
function (store, json) { var i, args = slice.call(arguments, 2), len = args.length, records, typeKey; for (i = 0; i < len; i += 2) { records = args[i + 1]; records = records ? (isArray(records) ? records.slice() : [records]) : []; typeKey = pluralize(this._parseModelOrType(store, args[i]).typeKey); if (!json[typeKey]) { json[typeKey] = records; } else { injectNoConflict(json[typeKey], records); } } return json; }
javascript
function (store, json) { var i, args = slice.call(arguments, 2), len = args.length, records, typeKey; for (i = 0; i < len; i += 2) { records = args[i + 1]; records = records ? (isArray(records) ? records.slice() : [records]) : []; typeKey = pluralize(this._parseModelOrType(store, args[i]).typeKey); if (!json[typeKey]) { json[typeKey] = records; } else { injectNoConflict(json[typeKey], records); } } return json; }
[ "function", "(", "store", ",", "json", ")", "{", "var", "i", ",", "args", "=", "slice", ".", "call", "(", "arguments", ",", "2", ")", ",", "len", "=", "args", ".", "length", ",", "records", ",", "typeKey", ";", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "+=", "2", ")", "{", "records", "=", "args", "[", "i", "+", "1", "]", ";", "records", "=", "records", "?", "(", "isArray", "(", "records", ")", "?", "records", ".", "slice", "(", ")", ":", "[", "records", "]", ")", ":", "[", "]", ";", "typeKey", "=", "pluralize", "(", "this", ".", "_parseModelOrType", "(", "store", ",", "args", "[", "i", "]", ")", ".", "typeKey", ")", ";", "if", "(", "!", "json", "[", "typeKey", "]", ")", "{", "json", "[", "typeKey", "]", "=", "records", ";", "}", "else", "{", "injectNoConflict", "(", "json", "[", "typeKey", "]", ",", "records", ")", ";", "}", "}", "return", "json", ";", "}" ]
Inject fixtures into the given json @method _injectFixturesInResponse @param {DS.Store} store @param {Object} json @return {Object}
[ "Inject", "fixtures", "into", "the", "given", "json" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/adapters/dev-fixtures.js#L614-L628
54,638
ugate/pulses
lib/catheter.js
artery
function artery(pw, iv, meds) { if (!iv.artery) iv.artery = new Artery(); plet.props(iv.artery, sprops, meds || iv, true); iv.artery.count = iv.count; iv.artery.data = iv.data; iv.artery.passes = iv.passes; iv.artery.pass = iv.pass; return iv.artery; }
javascript
function artery(pw, iv, meds) { if (!iv.artery) iv.artery = new Artery(); plet.props(iv.artery, sprops, meds || iv, true); iv.artery.count = iv.count; iv.artery.data = iv.data; iv.artery.passes = iv.passes; iv.artery.pass = iv.pass; return iv.artery; }
[ "function", "artery", "(", "pw", ",", "iv", ",", "meds", ")", "{", "if", "(", "!", "iv", ".", "artery", ")", "iv", ".", "artery", "=", "new", "Artery", "(", ")", ";", "plet", ".", "props", "(", "iv", ".", "artery", ",", "sprops", ",", "meds", "||", "iv", ",", "true", ")", ";", "iv", ".", "artery", ".", "count", "=", "iv", ".", "count", ";", "iv", ".", "artery", ".", "data", "=", "iv", ".", "data", ";", "iv", ".", "artery", ".", "passes", "=", "iv", ".", "passes", ";", "iv", ".", "artery", ".", "pass", "=", "iv", ".", "pass", ";", "return", "iv", ".", "artery", ";", "}" ]
Generates an artery or sets properties an artery when the I.V. artery already exists @private @arg {PulseEmitter} pw the pulse emitter @arg {Array} iv the I.V. catheter @arg {Array} meds the pulse events @returns {Artery} the artery
[ "Generates", "an", "artery", "or", "sets", "properties", "an", "artery", "when", "the", "I", ".", "V", ".", "artery", "already", "exists" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/lib/catheter.js#L153-L161
54,639
ugate/pulses
lib/catheter.js
Pulse
function Pulse(pw, iv, drip) { var pulse = this; plet.merge(pulse, drip.pulse); pulse.count = drip.cbCount + 1; pulse.event = drip.pulse.event; }
javascript
function Pulse(pw, iv, drip) { var pulse = this; plet.merge(pulse, drip.pulse); pulse.count = drip.cbCount + 1; pulse.event = drip.pulse.event; }
[ "function", "Pulse", "(", "pw", ",", "iv", ",", "drip", ")", "{", "var", "pulse", "=", "this", ";", "plet", ".", "merge", "(", "pulse", ",", "drip", ".", "pulse", ")", ";", "pulse", ".", "count", "=", "drip", ".", "cbCount", "+", "1", ";", "pulse", ".", "event", "=", "drip", ".", "pulse", ".", "event", ";", "}" ]
Pulse event passed to listeners @private @class Pulse @arg {PulseEmitter} pw the pulse emitter @arg {Array} iv the I.V. catheter @arg {Object} drip the drip
[ "Pulse", "event", "passed", "to", "listeners" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/lib/catheter.js#L172-L177
54,640
ugate/pulses
lib/catheter.js
assertlet
function assertlet(obj, other, objName, otherName) { plet.props(obj, sprops, other, false, false, objName || '1st', otherName || '2nd'); }
javascript
function assertlet(obj, other, objName, otherName) { plet.props(obj, sprops, other, false, false, objName || '1st', otherName || '2nd'); }
[ "function", "assertlet", "(", "obj", ",", "other", ",", "objName", ",", "otherName", ")", "{", "plet", ".", "props", "(", "obj", ",", "sprops", ",", "other", ",", "false", ",", "false", ",", "objName", "||", "'1st'", ",", "otherName", "||", "'2nd'", ")", ";", "}" ]
Asserts that all of the properties shared between arteries and pulses are equivalent between two arteries or pulses @arg {Object} obj object that contains artery/pulse properties @arg {Object} other another object that contains artery/pulse properties @arg {String} [objName=1st] a name to use for the obj object when assertion fails @arg {String} [otherName=2nd] a name to use for the obj object when assertion fails
[ "Asserts", "that", "all", "of", "the", "properties", "shared", "between", "arteries", "and", "pulses", "are", "equivalent", "between", "two", "arteries", "or", "pulses" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/lib/catheter.js#L187-L189
54,641
ugate/pulses
lib/catheter.js
pulselet
function pulselet(artery, event, endEvent) { return (new Drip(null, artery, event, endEvent)).pulse; }
javascript
function pulselet(artery, event, endEvent) { return (new Drip(null, artery, event, endEvent)).pulse; }
[ "function", "pulselet", "(", "artery", ",", "event", ",", "endEvent", ")", "{", "return", "(", "new", "Drip", "(", "null", ",", "artery", ",", "event", ",", "endEvent", ")", ")", ".", "pulse", ";", "}" ]
Adds or creates an object with pulse-like properties @arg {Object} artery the artery object that will be used to inherit from for shared pulse property values that have not been set on the event @arg {(Object | String)} event either an object that contains pulse properties or a string representing the event name @arg {String} endEvent the name of the event that will be fired when the artery has completed execution @returns {Object} an object that represents a pulse (not an instance of the actual pulse used during emission)
[ "Adds", "or", "creates", "an", "object", "with", "pulse", "-", "like", "properties" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/lib/catheter.js#L209-L211
54,642
ugate/pulses
lib/catheter.js
emits
function emits(pw, iv, i) { for (var ci = i, a; iv[ci] && (ci === i || iv[ci].cbCount < iv[ci].repeat); ci++) iv[ci].emit(pw, iv); }
javascript
function emits(pw, iv, i) { for (var ci = i, a; iv[ci] && (ci === i || iv[ci].cbCount < iv[ci].repeat); ci++) iv[ci].emit(pw, iv); }
[ "function", "emits", "(", "pw", ",", "iv", ",", "i", ")", "{", "for", "(", "var", "ci", "=", "i", ",", "a", ";", "iv", "[", "ci", "]", "&&", "(", "ci", "===", "i", "||", "iv", "[", "ci", "]", ".", "cbCount", "<", "iv", "[", "ci", "]", ".", "repeat", ")", ";", "ci", "++", ")", "iv", "[", "ci", "]", ".", "emit", "(", "pw", ",", "iv", ")", ";", "}" ]
When the event at the specified index is not async and has not been called back, the event for the passed index will be emitted Also, if the pulse event is async, events are consecutively emitted until a sync event is encountered @private @arg {PulseEmitter} pw the pulse emitter @arg {Array} iv the I.V. catheter @arg {Integer} i the pulse event index to start from in the I.V.
[ "When", "the", "event", "at", "the", "specified", "index", "is", "not", "async", "and", "has", "not", "been", "called", "back", "the", "event", "for", "the", "passed", "index", "will", "be", "emitted", "Also", "if", "the", "pulse", "event", "is", "async", "events", "are", "consecutively", "emitted", "until", "a", "sync", "event", "is", "encountered" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/lib/catheter.js#L222-L224
54,643
ugate/pulses
lib/catheter.js
Drip
function Drip(pw, iv, evt, endEvent, emit) { var ieo = typeof evt === 'object', eo = ieo ? evt : null, pulse = { event: ieo ? evt.event : evt }; if (!pulse.event) throw new Error('Event is required'); if (eo && eo.id) pulse.id = eo.id; // IDs are not inherited because iv/pulse IDs are non-transferable this.pulse = plet.props(plet.props(pulse, sprops, eo, true, true), sprops, iv); // pulse should only contain values from the event or inherited from the iv this.cbCount = 0; if (emit) this.emit(pw, iv); }
javascript
function Drip(pw, iv, evt, endEvent, emit) { var ieo = typeof evt === 'object', eo = ieo ? evt : null, pulse = { event: ieo ? evt.event : evt }; if (!pulse.event) throw new Error('Event is required'); if (eo && eo.id) pulse.id = eo.id; // IDs are not inherited because iv/pulse IDs are non-transferable this.pulse = plet.props(plet.props(pulse, sprops, eo, true, true), sprops, iv); // pulse should only contain values from the event or inherited from the iv this.cbCount = 0; if (emit) this.emit(pw, iv); }
[ "function", "Drip", "(", "pw", ",", "iv", ",", "evt", ",", "endEvent", ",", "emit", ")", "{", "var", "ieo", "=", "typeof", "evt", "===", "'object'", ",", "eo", "=", "ieo", "?", "evt", ":", "null", ",", "pulse", "=", "{", "event", ":", "ieo", "?", "evt", ".", "event", ":", "evt", "}", ";", "if", "(", "!", "pulse", ".", "event", ")", "throw", "new", "Error", "(", "'Event is required'", ")", ";", "if", "(", "eo", "&&", "eo", ".", "id", ")", "pulse", ".", "id", "=", "eo", ".", "id", ";", "// IDs are not inherited because iv/pulse IDs are non-transferable", "this", ".", "pulse", "=", "plet", ".", "props", "(", "plet", ".", "props", "(", "pulse", ",", "sprops", ",", "eo", ",", "true", ",", "true", ")", ",", "sprops", ",", "iv", ")", ";", "// pulse should only contain values from the event or inherited from the iv", "this", ".", "cbCount", "=", "0", ";", "if", "(", "emit", ")", "this", ".", "emit", "(", "pw", ",", "iv", ")", ";", "}" ]
Creates a drip for an I.V. catheter @private @class Drip @arg {PulseEmitter} pw the pulse emitter @arg {Array} iv the I.V. catheter @arg {(String | Object)} evt the pulse event @arg {String} endEvent the end event @arg {Boolean} [emit] true to emit @returns {Object} the drip / pulse
[ "Creates", "a", "drip", "for", "an", "I", ".", "V", ".", "catheter" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/lib/catheter.js#L238-L245
54,644
ugate/pulses
lib/catheter.js
inlet
function inlet(pw, iv, drip) { var ib = drip ? drip.pulse.inbound : iv.inbound; if (!ib) return true; var tgs = ib.selector && typeof iv.target.querySelectorAll === 'function' ? iv.target.querySelectorAll(ib.selector) : [iv.target]; var ttl = tgs.length; var fn = function inboundListener() { if (arguments.length) iv.pass.push.apply(iv.pass, arguments); if (++ib.count >= ib.repeat) { plet.event(ib.event, tgs, fn, ib.useCapture, true); // remove listener if (drip) drip.emit(pw, iv, true); // TODO : no drip should continue i.v. emission } }; plet.event(ib.event, tgs, fn, ib.useCapture); }
javascript
function inlet(pw, iv, drip) { var ib = drip ? drip.pulse.inbound : iv.inbound; if (!ib) return true; var tgs = ib.selector && typeof iv.target.querySelectorAll === 'function' ? iv.target.querySelectorAll(ib.selector) : [iv.target]; var ttl = tgs.length; var fn = function inboundListener() { if (arguments.length) iv.pass.push.apply(iv.pass, arguments); if (++ib.count >= ib.repeat) { plet.event(ib.event, tgs, fn, ib.useCapture, true); // remove listener if (drip) drip.emit(pw, iv, true); // TODO : no drip should continue i.v. emission } }; plet.event(ib.event, tgs, fn, ib.useCapture); }
[ "function", "inlet", "(", "pw", ",", "iv", ",", "drip", ")", "{", "var", "ib", "=", "drip", "?", "drip", ".", "pulse", ".", "inbound", ":", "iv", ".", "inbound", ";", "if", "(", "!", "ib", ")", "return", "true", ";", "var", "tgs", "=", "ib", ".", "selector", "&&", "typeof", "iv", ".", "target", ".", "querySelectorAll", "===", "'function'", "?", "iv", ".", "target", ".", "querySelectorAll", "(", "ib", ".", "selector", ")", ":", "[", "iv", ".", "target", "]", ";", "var", "ttl", "=", "tgs", ".", "length", ";", "var", "fn", "=", "function", "inboundListener", "(", ")", "{", "if", "(", "arguments", ".", "length", ")", "iv", ".", "pass", ".", "push", ".", "apply", "(", "iv", ".", "pass", ",", "arguments", ")", ";", "if", "(", "++", "ib", ".", "count", ">=", "ib", ".", "repeat", ")", "{", "plet", ".", "event", "(", "ib", ".", "event", ",", "tgs", ",", "fn", ",", "ib", ".", "useCapture", ",", "true", ")", ";", "// remove listener", "if", "(", "drip", ")", "drip", ".", "emit", "(", "pw", ",", "iv", ",", "true", ")", ";", "// TODO : no drip should continue i.v. emission", "}", "}", ";", "plet", ".", "event", "(", "ib", ".", "event", ",", "tgs", ",", "fn", ",", "ib", ".", "useCapture", ")", ";", "}" ]
Universal inlet for inbound event deferment @arg {PulseEmitter} pw the pulse emitter @arg {Array} iv the I.V. catheter @arg {Drip} [drip] the drip to check/process the inbound deferment (omit to check/process the I.V. instead)
[ "Universal", "inlet", "for", "inbound", "event", "deferment" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/lib/catheter.js#L283-L297
54,645
AVVS/node-errors
index.js
commonErrorHandler
function commonErrorHandler(err, req, res, next) { // jshint ignore:line debug(err); // if we got here without an error, it's a 404 case if (!err) { err = new NotFoundError(); } // here we've got an error, it could be a different one than // the one we've constructed, so provide defaults to be safe err.message = err.message || 'Internal Server Error'; res .status(err.code || err.statusCode || 500) .type('application/json') .send(stringify(err)); }
javascript
function commonErrorHandler(err, req, res, next) { // jshint ignore:line debug(err); // if we got here without an error, it's a 404 case if (!err) { err = new NotFoundError(); } // here we've got an error, it could be a different one than // the one we've constructed, so provide defaults to be safe err.message = err.message || 'Internal Server Error'; res .status(err.code || err.statusCode || 500) .type('application/json') .send(stringify(err)); }
[ "function", "commonErrorHandler", "(", "err", ",", "req", ",", "res", ",", "next", ")", "{", "// jshint ignore:line", "debug", "(", "err", ")", ";", "// if we got here without an error, it's a 404 case", "if", "(", "!", "err", ")", "{", "err", "=", "new", "NotFoundError", "(", ")", ";", "}", "// here we've got an error, it could be a different one than", "// the one we've constructed, so provide defaults to be safe", "err", ".", "message", "=", "err", ".", "message", "||", "'Internal Server Error'", ";", "res", ".", "status", "(", "err", ".", "code", "||", "err", ".", "statusCode", "||", "500", ")", ".", "type", "(", "'application/json'", ")", ".", "send", "(", "stringify", "(", "err", ")", ")", ";", "}" ]
Middleware for sending errors based on passed error @param {Error} err - error object @param {Object} req - http request @param {Object} res - http response @param {Function} next - next
[ "Middleware", "for", "sending", "errors", "based", "on", "passed", "error" ]
d3813792ee01abc6f0b590f840daa70fd6622d9e
https://github.com/AVVS/node-errors/blob/d3813792ee01abc6f0b590f840daa70fd6622d9e/index.js#L114-L131
54,646
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
function( newRules, featureName, overrideCustom ) { // Check arguments and constraints. Clear cache. if ( !beforeAddingRule( this, newRules, overrideCustom ) ) return false; var i, ret; if ( typeof newRules == 'string' ) newRules = parseRulesString( newRules ); else if ( newRules instanceof CKEDITOR.style ) { // If style has the cast method defined, use it and abort. if ( newRules.toAllowedContentRules ) return this.allow( newRules.toAllowedContentRules( this.editor ), featureName, overrideCustom ); newRules = convertStyleToRules( newRules ); } else if ( CKEDITOR.tools.isArray( newRules ) ) { for ( i = 0; i < newRules.length; ++i ) ret = this.allow( newRules[ i ], featureName, overrideCustom ); return ret; // Return last status. } addAndOptimizeRules( this, newRules, featureName, this.allowedContent, this._.allowedRules ); return true; }
javascript
function( newRules, featureName, overrideCustom ) { // Check arguments and constraints. Clear cache. if ( !beforeAddingRule( this, newRules, overrideCustom ) ) return false; var i, ret; if ( typeof newRules == 'string' ) newRules = parseRulesString( newRules ); else if ( newRules instanceof CKEDITOR.style ) { // If style has the cast method defined, use it and abort. if ( newRules.toAllowedContentRules ) return this.allow( newRules.toAllowedContentRules( this.editor ), featureName, overrideCustom ); newRules = convertStyleToRules( newRules ); } else if ( CKEDITOR.tools.isArray( newRules ) ) { for ( i = 0; i < newRules.length; ++i ) ret = this.allow( newRules[ i ], featureName, overrideCustom ); return ret; // Return last status. } addAndOptimizeRules( this, newRules, featureName, this.allowedContent, this._.allowedRules ); return true; }
[ "function", "(", "newRules", ",", "featureName", ",", "overrideCustom", ")", "{", "// Check arguments and constraints. Clear cache.", "if", "(", "!", "beforeAddingRule", "(", "this", ",", "newRules", ",", "overrideCustom", ")", ")", "return", "false", ";", "var", "i", ",", "ret", ";", "if", "(", "typeof", "newRules", "==", "'string'", ")", "newRules", "=", "parseRulesString", "(", "newRules", ")", ";", "else", "if", "(", "newRules", "instanceof", "CKEDITOR", ".", "style", ")", "{", "// If style has the cast method defined, use it and abort.", "if", "(", "newRules", ".", "toAllowedContentRules", ")", "return", "this", ".", "allow", "(", "newRules", ".", "toAllowedContentRules", "(", "this", ".", "editor", ")", ",", "featureName", ",", "overrideCustom", ")", ";", "newRules", "=", "convertStyleToRules", "(", "newRules", ")", ";", "}", "else", "if", "(", "CKEDITOR", ".", "tools", ".", "isArray", "(", "newRules", ")", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "newRules", ".", "length", ";", "++", "i", ")", "ret", "=", "this", ".", "allow", "(", "newRules", "[", "i", "]", ",", "featureName", ",", "overrideCustom", ")", ";", "return", "ret", ";", "// Return last status.", "}", "addAndOptimizeRules", "(", "this", ",", "newRules", ",", "featureName", ",", "this", ".", "allowedContent", ",", "this", ".", "_", ".", "allowedRules", ")", ";", "return", "true", ";", "}" ]
Adds allowed content rules to the filter. Read about rules formats in [Allowed Content Rules guide](#!/guide/dev_allowed_content_rules). // Add a basic rule for custom image feature (e.g. 'MyImage' button). editor.filter.allow( 'img[!src,alt]', 'MyImage' ); // Add rules for two header styles allowed by 'HeadersCombo'. var header1Style = new CKEDITOR.style( { element: 'h1' } ), header2Style = new CKEDITOR.style( { element: 'h2' } ); editor.filter.allow( [ header1Style, header2Style ], 'HeadersCombo' ); @param {CKEDITOR.filter.allowedContentRules} newRules Rule(s) to be added. @param {String} [featureName] Name of a feature that allows this content (most often plugin/button/command name). @param {Boolean} [overrideCustom] By default this method will reject any rules if {@link CKEDITOR.config#allowedContent} is defined to avoid overriding it. Pass `true` to force rules addition. @returns {Boolean} Whether the rules were accepted.
[ "Adds", "allowed", "content", "rules", "to", "the", "filter", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L231-L255
54,647
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
function( newRules ) { // Check arguments and constraints. Clear cache. // Note: we pass true in the 3rd argument, because disallow() should never // be blocked by custom configuration. if ( !beforeAddingRule( this, newRules, true ) ) return false; if ( typeof newRules == 'string' ) newRules = parseRulesString( newRules ); addAndOptimizeRules( this, newRules, null, this.disallowedContent, this._.disallowedRules ); return true; }
javascript
function( newRules ) { // Check arguments and constraints. Clear cache. // Note: we pass true in the 3rd argument, because disallow() should never // be blocked by custom configuration. if ( !beforeAddingRule( this, newRules, true ) ) return false; if ( typeof newRules == 'string' ) newRules = parseRulesString( newRules ); addAndOptimizeRules( this, newRules, null, this.disallowedContent, this._.disallowedRules ); return true; }
[ "function", "(", "newRules", ")", "{", "// Check arguments and constraints. Clear cache.", "// Note: we pass true in the 3rd argument, because disallow() should never", "// be blocked by custom configuration.", "if", "(", "!", "beforeAddingRule", "(", "this", ",", "newRules", ",", "true", ")", ")", "return", "false", ";", "if", "(", "typeof", "newRules", "==", "'string'", ")", "newRules", "=", "parseRulesString", "(", "newRules", ")", ";", "addAndOptimizeRules", "(", "this", ",", "newRules", ",", "null", ",", "this", ".", "disallowedContent", ",", "this", ".", "_", ".", "disallowedRules", ")", ";", "return", "true", ";", "}" ]
Adds disallowed content rules to the filter. Read about rules formats in the [Allowed Content Rules guide](#!/guide/dev_allowed_content_rules). // Disallow all styles on the image elements. editor.filter.disallow( 'img{*}' ); // Disallow all span and div elements. editor.filter.disallow( 'span div' ); @since 4.4 @param {CKEDITOR.filter.disallowedContentRules} newRules Rule(s) to be added.
[ "Adds", "disallowed", "content", "rules", "to", "the", "filter", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L434-L447
54,648
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
function( feature ) { if ( this.disabled ) return true; if ( !feature ) return true; // Some features may want to register other features. // E.g. a button may return a command bound to it. if ( feature.toFeature ) feature = feature.toFeature( this.editor ); // If default configuration (will be checked inside #allow()), // then add allowed content rules. this.allow( feature.allowedContent, feature.name ); this.addTransformations( feature.contentTransformations ); this.addContentForms( feature.contentForms ); // If custom configuration or any DACRs, then check if required content is allowed. if ( feature.requiredContent && ( this.customConfig || this.disallowedContent.length ) ) return this.check( feature.requiredContent ); return true; }
javascript
function( feature ) { if ( this.disabled ) return true; if ( !feature ) return true; // Some features may want to register other features. // E.g. a button may return a command bound to it. if ( feature.toFeature ) feature = feature.toFeature( this.editor ); // If default configuration (will be checked inside #allow()), // then add allowed content rules. this.allow( feature.allowedContent, feature.name ); this.addTransformations( feature.contentTransformations ); this.addContentForms( feature.contentForms ); // If custom configuration or any DACRs, then check if required content is allowed. if ( feature.requiredContent && ( this.customConfig || this.disallowedContent.length ) ) return this.check( feature.requiredContent ); return true; }
[ "function", "(", "feature", ")", "{", "if", "(", "this", ".", "disabled", ")", "return", "true", ";", "if", "(", "!", "feature", ")", "return", "true", ";", "// Some features may want to register other features.", "// E.g. a button may return a command bound to it.", "if", "(", "feature", ".", "toFeature", ")", "feature", "=", "feature", ".", "toFeature", "(", "this", ".", "editor", ")", ";", "// If default configuration (will be checked inside #allow()),", "// then add allowed content rules.", "this", ".", "allow", "(", "feature", ".", "allowedContent", ",", "feature", ".", "name", ")", ";", "this", ".", "addTransformations", "(", "feature", ".", "contentTransformations", ")", ";", "this", ".", "addContentForms", "(", "feature", ".", "contentForms", ")", ";", "// If custom configuration or any DACRs, then check if required content is allowed.", "if", "(", "feature", ".", "requiredContent", "&&", "(", "this", ".", "customConfig", "||", "this", ".", "disallowedContent", ".", "length", ")", ")", "return", "this", ".", "check", "(", "feature", ".", "requiredContent", ")", ";", "return", "true", ";", "}" ]
Checks whether a feature can be enabled for the HTML restrictions in place for the current CKEditor instance, based on the HTML code the feature might generate and the minimal HTML code the feature needs to be able to generate. // TODO example @param {CKEDITOR.feature} feature @returns {Boolean} Whether this feature can be enabled.
[ "Checks", "whether", "a", "feature", "can", "be", "enabled", "for", "the", "HTML", "restrictions", "in", "place", "for", "the", "current", "CKEditor", "instance", "based", "on", "the", "HTML", "code", "the", "feature", "might", "generate", "and", "the", "minimal", "HTML", "code", "the", "feature", "needs", "to", "be", "able", "to", "generate", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L540-L564
54,649
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
function( transformations ) { if ( this.disabled ) return; if ( !transformations ) return; var optimized = this._.transformations, group, i; for ( i = 0; i < transformations.length; ++i ) { group = optimizeTransformationsGroup( transformations[ i ] ); if ( !optimized[ group.name ] ) optimized[ group.name ] = []; optimized[ group.name ].push( group.rules ); } }
javascript
function( transformations ) { if ( this.disabled ) return; if ( !transformations ) return; var optimized = this._.transformations, group, i; for ( i = 0; i < transformations.length; ++i ) { group = optimizeTransformationsGroup( transformations[ i ] ); if ( !optimized[ group.name ] ) optimized[ group.name ] = []; optimized[ group.name ].push( group.rules ); } }
[ "function", "(", "transformations", ")", "{", "if", "(", "this", ".", "disabled", ")", "return", ";", "if", "(", "!", "transformations", ")", "return", ";", "var", "optimized", "=", "this", ".", "_", ".", "transformations", ",", "group", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "transformations", ".", "length", ";", "++", "i", ")", "{", "group", "=", "optimizeTransformationsGroup", "(", "transformations", "[", "i", "]", ")", ";", "if", "(", "!", "optimized", "[", "group", ".", "name", "]", ")", "optimized", "[", "group", ".", "name", "]", "=", "[", "]", ";", "optimized", "[", "group", ".", "name", "]", ".", "push", "(", "group", ".", "rules", ")", ";", "}", "}" ]
Adds an array of content transformation groups. One group may contain many transformation rules, but only the first matching rule in a group is executed. A single transformation rule is an object with four properties: * `check` (optional) &ndash; if set and {@link CKEDITOR.filter} does not accept this {@link CKEDITOR.filter.contentRule}, this transformation rule will not be executed (it does not *match*). This value is passed to {@link #check}. * `element` (optional) &ndash; this string property tells the filter on which element this transformation can be run. It is optional, because the element name can be obtained from `check` (if it is a String format) or `left` (if it is a {@link CKEDITOR.style} instance). * `left` (optional) &ndash; a function accepting an element or a {@link CKEDITOR.style} instance verifying whether the transformation should be executed on this specific element. If it returns `false` or if an element does not match this style, this transformation rule does not *match*. * `right` &ndash; a function accepting an element and {@link CKEDITOR.filter.transformationsTools} or a string containing the name of the {@link CKEDITOR.filter.transformationsTools} method that should be called on an element. A shorthand format is also available. A transformation rule can be defined by a single string `'check:right'`. The string before `':'` will be used as the `check` property and the second part as the `right` property. Transformation rules can be grouped. The filter will try to apply the first rule in a group. If it *matches*, the filter will ignore subsequent rules and will move to the next group. If it does not *match*, the next rule will be checked. Examples: editor.filter.addTransformations( [ // First group. [ // First rule. If table{width} is allowed, it // executes {@link CKEDITOR.filter.transformationsTools#sizeToStyle} on a table element. 'table{width}: sizeToStyle', // Second rule should not be executed if the first was. 'table[width]: sizeToAttribute' ], // Second group. [ // This rule will add the foo="1" attribute to all images that // do not have it. { element: 'img', left: function( el ) { return !el.attributes.foo; }, right: function( el, tools ) { el.attributes.foo = '1'; } } ] ] ); // Case 1: // config.allowedContent = 'table{height,width}; tr td'. // // '<table style="height:100px; width:200px">...</table>' -> '<table style="height:100px; width:200px">...</table>' // '<table height="100" width="200">...</table>' -> '<table style="height:100px; width:200px">...</table>' // Case 2: // config.allowedContent = 'table[height,width]; tr td'. // // '<table style="height:100px; width:200px">...</table>' -> '<table height="100" width="200">...</table>' // '<table height="100" width="200">...</table>' -> '<table height="100" width="200"">...</table>' // Case 3: // config.allowedContent = 'table{width,height}[height,width]; tr td'. // // '<table style="height:100px; width:200px">...</table>' -> '<table style="height:100px; width:200px">...</table>' // '<table height="100" width="200">...</table>' -> '<table style="height:100px; width:200px">...</table>' // // Note: Both forms are allowed (size set by style and by attributes), but only // the first transformation is applied &mdash; the size is always transformed to a style. // This is because only the first transformation matching allowed content rules is applied. This method is used by the editor to add {@link CKEDITOR.feature#contentTransformations} when adding a feature by {@link #addFeature} or {@link CKEDITOR.editor#addFeature}. @param {Array} transformations
[ "Adds", "an", "array", "of", "content", "transformation", "groups", ".", "One", "group", "may", "contain", "many", "transformation", "rules", "but", "only", "the", "first", "matching", "rule", "in", "a", "group", "is", "executed", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L651-L669
54,650
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
function( test, applyTransformations, strictCheck ) { if ( this.disabled ) return true; // If rules are an array, expand it and return the logical OR value of // the rules. if ( CKEDITOR.tools.isArray( test ) ) { for ( var i = test.length ; i-- ; ) { if ( this.check( test[ i ], applyTransformations, strictCheck ) ) return true; } return false; } var element, result, cacheKey; if ( typeof test == 'string' ) { cacheKey = test + '<' + ( applyTransformations === false ? '0' : '1' ) + ( strictCheck ? '1' : '0' ) + '>'; // Check if result of this check hasn't been already cached. if ( cacheKey in this._.cachedChecks ) return this._.cachedChecks[ cacheKey ]; // Create test element from string. element = mockElementFromString( test ); } else { // Create test element from CKEDITOR.style. element = mockElementFromStyle( test ); } // Make a deep copy. var clone = CKEDITOR.tools.clone( element ), toBeRemoved = [], transformations; // Apply transformations to original element. // Transformations will be applied to clone by the filter function. if ( applyTransformations !== false && ( transformations = this._.transformations[ element.name ] ) ) { for ( i = 0; i < transformations.length; ++i ) applyTransformationsGroup( this, element, transformations[ i ] ); // Transformations could modify styles or classes, so they need to be copied // to attributes object. updateAttributes( element ); } // Filter clone of mocked element. processElement( this, clone, toBeRemoved, { doFilter: true, doTransform: applyTransformations !== false, skipRequired: !strictCheck, skipFinalValidation: !strictCheck } ); // Element has been marked for removal. if ( toBeRemoved.length > 0 ) { result = false; // Compare only left to right, because clone may be only trimmed version of original element. } else if ( !CKEDITOR.tools.objectCompare( element.attributes, clone.attributes, true ) ) { result = false; } else { result = true; } // Cache result of this test - we can build cache only for string tests. if ( typeof test == 'string' ) this._.cachedChecks[ cacheKey ] = result; return result; }
javascript
function( test, applyTransformations, strictCheck ) { if ( this.disabled ) return true; // If rules are an array, expand it and return the logical OR value of // the rules. if ( CKEDITOR.tools.isArray( test ) ) { for ( var i = test.length ; i-- ; ) { if ( this.check( test[ i ], applyTransformations, strictCheck ) ) return true; } return false; } var element, result, cacheKey; if ( typeof test == 'string' ) { cacheKey = test + '<' + ( applyTransformations === false ? '0' : '1' ) + ( strictCheck ? '1' : '0' ) + '>'; // Check if result of this check hasn't been already cached. if ( cacheKey in this._.cachedChecks ) return this._.cachedChecks[ cacheKey ]; // Create test element from string. element = mockElementFromString( test ); } else { // Create test element from CKEDITOR.style. element = mockElementFromStyle( test ); } // Make a deep copy. var clone = CKEDITOR.tools.clone( element ), toBeRemoved = [], transformations; // Apply transformations to original element. // Transformations will be applied to clone by the filter function. if ( applyTransformations !== false && ( transformations = this._.transformations[ element.name ] ) ) { for ( i = 0; i < transformations.length; ++i ) applyTransformationsGroup( this, element, transformations[ i ] ); // Transformations could modify styles or classes, so they need to be copied // to attributes object. updateAttributes( element ); } // Filter clone of mocked element. processElement( this, clone, toBeRemoved, { doFilter: true, doTransform: applyTransformations !== false, skipRequired: !strictCheck, skipFinalValidation: !strictCheck } ); // Element has been marked for removal. if ( toBeRemoved.length > 0 ) { result = false; // Compare only left to right, because clone may be only trimmed version of original element. } else if ( !CKEDITOR.tools.objectCompare( element.attributes, clone.attributes, true ) ) { result = false; } else { result = true; } // Cache result of this test - we can build cache only for string tests. if ( typeof test == 'string' ) this._.cachedChecks[ cacheKey ] = result; return result; }
[ "function", "(", "test", ",", "applyTransformations", ",", "strictCheck", ")", "{", "if", "(", "this", ".", "disabled", ")", "return", "true", ";", "// If rules are an array, expand it and return the logical OR value of", "// the rules.", "if", "(", "CKEDITOR", ".", "tools", ".", "isArray", "(", "test", ")", ")", "{", "for", "(", "var", "i", "=", "test", ".", "length", ";", "i", "--", ";", ")", "{", "if", "(", "this", ".", "check", "(", "test", "[", "i", "]", ",", "applyTransformations", ",", "strictCheck", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}", "var", "element", ",", "result", ",", "cacheKey", ";", "if", "(", "typeof", "test", "==", "'string'", ")", "{", "cacheKey", "=", "test", "+", "'<'", "+", "(", "applyTransformations", "===", "false", "?", "'0'", ":", "'1'", ")", "+", "(", "strictCheck", "?", "'1'", ":", "'0'", ")", "+", "'>'", ";", "// Check if result of this check hasn't been already cached.", "if", "(", "cacheKey", "in", "this", ".", "_", ".", "cachedChecks", ")", "return", "this", ".", "_", ".", "cachedChecks", "[", "cacheKey", "]", ";", "// Create test element from string.", "element", "=", "mockElementFromString", "(", "test", ")", ";", "}", "else", "{", "// Create test element from CKEDITOR.style.", "element", "=", "mockElementFromStyle", "(", "test", ")", ";", "}", "// Make a deep copy.", "var", "clone", "=", "CKEDITOR", ".", "tools", ".", "clone", "(", "element", ")", ",", "toBeRemoved", "=", "[", "]", ",", "transformations", ";", "// Apply transformations to original element.", "// Transformations will be applied to clone by the filter function.", "if", "(", "applyTransformations", "!==", "false", "&&", "(", "transformations", "=", "this", ".", "_", ".", "transformations", "[", "element", ".", "name", "]", ")", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "transformations", ".", "length", ";", "++", "i", ")", "applyTransformationsGroup", "(", "this", ",", "element", ",", "transformations", "[", "i", "]", ")", ";", "// Transformations could modify styles or classes, so they need to be copied", "// to attributes object.", "updateAttributes", "(", "element", ")", ";", "}", "// Filter clone of mocked element.", "processElement", "(", "this", ",", "clone", ",", "toBeRemoved", ",", "{", "doFilter", ":", "true", ",", "doTransform", ":", "applyTransformations", "!==", "false", ",", "skipRequired", ":", "!", "strictCheck", ",", "skipFinalValidation", ":", "!", "strictCheck", "}", ")", ";", "// Element has been marked for removal.", "if", "(", "toBeRemoved", ".", "length", ">", "0", ")", "{", "result", "=", "false", ";", "// Compare only left to right, because clone may be only trimmed version of original element.", "}", "else", "if", "(", "!", "CKEDITOR", ".", "tools", ".", "objectCompare", "(", "element", ".", "attributes", ",", "clone", ".", "attributes", ",", "true", ")", ")", "{", "result", "=", "false", ";", "}", "else", "{", "result", "=", "true", ";", "}", "// Cache result of this test - we can build cache only for string tests.", "if", "(", "typeof", "test", "==", "'string'", ")", "this", ".", "_", ".", "cachedChecks", "[", "cacheKey", "]", "=", "result", ";", "return", "result", ";", "}" ]
Checks whether the content defined in the `test` argument is allowed by this filter. If `strictCheck` is set to `false` (default value), this method checks if all parts of the `test` (styles, attributes, and classes) are accepted by the filter. If `strictCheck` is set to `true`, the test must also contain the required attributes, styles, and classes. For example: // Rule: 'img[!src,alt]'. filter.check( 'img[alt]' ); // -> true filter.check( 'img[alt]', true, true ); // -> false Second `check()` call returned `false` because `src` is required. **Note:** The `test` argument is of {@link CKEDITOR.filter.contentRule} type, which is a limited version of {@link CKEDITOR.filter.allowedContentRules}. Read more about it in the {@link CKEDITOR.filter.contentRule}'s documentation. @param {CKEDITOR.filter.contentRule} test @param {Boolean} [applyTransformations=true] Whether to use registered transformations. @param {Boolean} [strictCheck] Whether the filter should check if an element with exactly these properties is allowed. @returns {Boolean} Returns `true` if the content is allowed.
[ "Checks", "whether", "the", "content", "defined", "in", "the", "test", "argument", "is", "allowed", "by", "this", "filter", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L698-L767
54,651
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
applyAllowedRule
function applyAllowedRule( rule, element, status, skipRequired ) { // This rule doesn't match this element - skip it. if ( rule.match && !rule.match( element ) ) return; // If element doesn't have all required styles/attrs/classes // this rule doesn't match it. if ( !skipRequired && !hasAllRequired( rule, element ) ) return; // If this rule doesn't validate properties only mark element as valid. if ( !rule.propertiesOnly ) status.valid = true; // Apply rule only when all attrs/styles/classes haven't been marked as valid. if ( !status.allAttributes ) status.allAttributes = applyAllowedRuleToHash( rule.attributes, element.attributes, status.validAttributes ); if ( !status.allStyles ) status.allStyles = applyAllowedRuleToHash( rule.styles, element.styles, status.validStyles ); if ( !status.allClasses ) status.allClasses = applyAllowedRuleToArray( rule.classes, element.classes, status.validClasses ); }
javascript
function applyAllowedRule( rule, element, status, skipRequired ) { // This rule doesn't match this element - skip it. if ( rule.match && !rule.match( element ) ) return; // If element doesn't have all required styles/attrs/classes // this rule doesn't match it. if ( !skipRequired && !hasAllRequired( rule, element ) ) return; // If this rule doesn't validate properties only mark element as valid. if ( !rule.propertiesOnly ) status.valid = true; // Apply rule only when all attrs/styles/classes haven't been marked as valid. if ( !status.allAttributes ) status.allAttributes = applyAllowedRuleToHash( rule.attributes, element.attributes, status.validAttributes ); if ( !status.allStyles ) status.allStyles = applyAllowedRuleToHash( rule.styles, element.styles, status.validStyles ); if ( !status.allClasses ) status.allClasses = applyAllowedRuleToArray( rule.classes, element.classes, status.validClasses ); }
[ "function", "applyAllowedRule", "(", "rule", ",", "element", ",", "status", ",", "skipRequired", ")", "{", "// This rule doesn't match this element - skip it.", "if", "(", "rule", ".", "match", "&&", "!", "rule", ".", "match", "(", "element", ")", ")", "return", ";", "// If element doesn't have all required styles/attrs/classes", "// this rule doesn't match it.", "if", "(", "!", "skipRequired", "&&", "!", "hasAllRequired", "(", "rule", ",", "element", ")", ")", "return", ";", "// If this rule doesn't validate properties only mark element as valid.", "if", "(", "!", "rule", ".", "propertiesOnly", ")", "status", ".", "valid", "=", "true", ";", "// Apply rule only when all attrs/styles/classes haven't been marked as valid.", "if", "(", "!", "status", ".", "allAttributes", ")", "status", ".", "allAttributes", "=", "applyAllowedRuleToHash", "(", "rule", ".", "attributes", ",", "element", ".", "attributes", ",", "status", ".", "validAttributes", ")", ";", "if", "(", "!", "status", ".", "allStyles", ")", "status", ".", "allStyles", "=", "applyAllowedRuleToHash", "(", "rule", ".", "styles", ",", "element", ".", "styles", ",", "status", ".", "validStyles", ")", ";", "if", "(", "!", "status", ".", "allClasses", ")", "status", ".", "allClasses", "=", "applyAllowedRuleToArray", "(", "rule", ".", "classes", ",", "element", ".", "classes", ",", "status", ".", "validClasses", ")", ";", "}" ]
Apply ACR to an element. @param rule @param element @param status Object containing status of element's filtering. @param {Boolean} skipRequired If true don't check if element has all required properties.
[ "Apply", "ACR", "to", "an", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L863-L886
54,652
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
applyDisallowedRule
function applyDisallowedRule( rule, element, status ) { // This rule doesn't match this element - skip it. if ( rule.match && !rule.match( element ) ) return; // No properties - it's an element only rule so it disallows entire element. // Early return is handled in filterElement. if ( rule.noProperties ) return false; // Apply rule to attributes, styles and classes. Switch hadInvalid* to true if method returned true. status.hadInvalidAttribute = applyDisallowedRuleToHash( rule.attributes, element.attributes ) || status.hadInvalidAttribute; status.hadInvalidStyle = applyDisallowedRuleToHash( rule.styles, element.styles ) || status.hadInvalidStyle; status.hadInvalidClass = applyDisallowedRuleToArray( rule.classes, element.classes ) || status.hadInvalidClass; }
javascript
function applyDisallowedRule( rule, element, status ) { // This rule doesn't match this element - skip it. if ( rule.match && !rule.match( element ) ) return; // No properties - it's an element only rule so it disallows entire element. // Early return is handled in filterElement. if ( rule.noProperties ) return false; // Apply rule to attributes, styles and classes. Switch hadInvalid* to true if method returned true. status.hadInvalidAttribute = applyDisallowedRuleToHash( rule.attributes, element.attributes ) || status.hadInvalidAttribute; status.hadInvalidStyle = applyDisallowedRuleToHash( rule.styles, element.styles ) || status.hadInvalidStyle; status.hadInvalidClass = applyDisallowedRuleToArray( rule.classes, element.classes ) || status.hadInvalidClass; }
[ "function", "applyDisallowedRule", "(", "rule", ",", "element", ",", "status", ")", "{", "// This rule doesn't match this element - skip it.", "if", "(", "rule", ".", "match", "&&", "!", "rule", ".", "match", "(", "element", ")", ")", "return", ";", "// No properties - it's an element only rule so it disallows entire element.", "// Early return is handled in filterElement.", "if", "(", "rule", ".", "noProperties", ")", "return", "false", ";", "// Apply rule to attributes, styles and classes. Switch hadInvalid* to true if method returned true.", "status", ".", "hadInvalidAttribute", "=", "applyDisallowedRuleToHash", "(", "rule", ".", "attributes", ",", "element", ".", "attributes", ")", "||", "status", ".", "hadInvalidAttribute", ";", "status", ".", "hadInvalidStyle", "=", "applyDisallowedRuleToHash", "(", "rule", ".", "styles", ",", "element", ".", "styles", ")", "||", "status", ".", "hadInvalidStyle", ";", "status", ".", "hadInvalidClass", "=", "applyDisallowedRuleToArray", "(", "rule", ".", "classes", ",", "element", ".", "classes", ")", "||", "status", ".", "hadInvalidClass", ";", "}" ]
Apply DACR rule to an element.
[ "Apply", "DACR", "rule", "to", "an", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L924-L938
54,653
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
convertStyleToRules
function convertStyleToRules( style ) { var styleDef = style.getDefinition(), rules = {}, rule, attrs = styleDef.attributes; rules[ styleDef.element ] = rule = { styles: styleDef.styles, requiredStyles: styleDef.styles && CKEDITOR.tools.objectKeys( styleDef.styles ) }; if ( attrs ) { attrs = copy( attrs ); rule.classes = attrs[ 'class' ] ? attrs[ 'class' ].split( /\s+/ ) : null; rule.requiredClasses = rule.classes; delete attrs[ 'class' ]; rule.attributes = attrs; rule.requiredAttributes = attrs && CKEDITOR.tools.objectKeys( attrs ); } return rules; }
javascript
function convertStyleToRules( style ) { var styleDef = style.getDefinition(), rules = {}, rule, attrs = styleDef.attributes; rules[ styleDef.element ] = rule = { styles: styleDef.styles, requiredStyles: styleDef.styles && CKEDITOR.tools.objectKeys( styleDef.styles ) }; if ( attrs ) { attrs = copy( attrs ); rule.classes = attrs[ 'class' ] ? attrs[ 'class' ].split( /\s+/ ) : null; rule.requiredClasses = rule.classes; delete attrs[ 'class' ]; rule.attributes = attrs; rule.requiredAttributes = attrs && CKEDITOR.tools.objectKeys( attrs ); } return rules; }
[ "function", "convertStyleToRules", "(", "style", ")", "{", "var", "styleDef", "=", "style", ".", "getDefinition", "(", ")", ",", "rules", "=", "{", "}", ",", "rule", ",", "attrs", "=", "styleDef", ".", "attributes", ";", "rules", "[", "styleDef", ".", "element", "]", "=", "rule", "=", "{", "styles", ":", "styleDef", ".", "styles", ",", "requiredStyles", ":", "styleDef", ".", "styles", "&&", "CKEDITOR", ".", "tools", ".", "objectKeys", "(", "styleDef", ".", "styles", ")", "}", ";", "if", "(", "attrs", ")", "{", "attrs", "=", "copy", "(", "attrs", ")", ";", "rule", ".", "classes", "=", "attrs", "[", "'class'", "]", "?", "attrs", "[", "'class'", "]", ".", "split", "(", "/", "\\s+", "/", ")", ":", "null", ";", "rule", ".", "requiredClasses", "=", "rule", ".", "classes", ";", "delete", "attrs", "[", "'class'", "]", ";", "rule", ".", "attributes", "=", "attrs", ";", "rule", ".", "requiredAttributes", "=", "attrs", "&&", "CKEDITOR", ".", "tools", ".", "objectKeys", "(", "attrs", ")", ";", "}", "return", "rules", ";", "}" ]
Convert CKEDITOR.style to filter's rule.
[ "Convert", "CKEDITOR", ".", "style", "to", "filter", "s", "rule", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L996-L1017
54,654
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
filterElement
function filterElement( that, element, opts ) { var name = element.name, privObj = that._, allowedRules = privObj.allowedRules.elements[ name ], genericAllowedRules = privObj.allowedRules.generic, disallowedRules = privObj.disallowedRules.elements[ name ], genericDisallowedRules = privObj.disallowedRules.generic, skipRequired = opts.skipRequired, status = { // Whether any of rules accepted element. // If not - it will be stripped. valid: false, // Objects containing accepted attributes, classes and styles. validAttributes: {}, validClasses: {}, validStyles: {}, // Whether all are valid. // If we know that all element's attrs/classes/styles are valid // we can skip their validation, to improve performance. allAttributes: false, allClasses: false, allStyles: false, // Whether element had (before applying DACRs) at least one invalid attribute/class/style. hadInvalidAttribute: false, hadInvalidClass: false, hadInvalidStyle: false }, i, l; // Early return - if there are no rules for this element (specific or generic), remove it. if ( !allowedRules && !genericAllowedRules ) return null; // Could not be done yet if there were no transformations and if this // is real (not mocked) object. populateProperties( element ); // Note - this step modifies element's styles, classes and attributes. if ( disallowedRules ) { for ( i = 0, l = disallowedRules.length; i < l; ++i ) { // Apply rule and make an early return if false is returned what means // that element is completely disallowed. if ( applyDisallowedRule( disallowedRules[ i ], element, status ) === false ) return null; } } // Note - this step modifies element's styles, classes and attributes. if ( genericDisallowedRules ) { for ( i = 0, l = genericDisallowedRules.length; i < l; ++i ) applyDisallowedRule( genericDisallowedRules[ i ], element, status ); } if ( allowedRules ) { for ( i = 0, l = allowedRules.length; i < l; ++i ) applyAllowedRule( allowedRules[ i ], element, status, skipRequired ); } if ( genericAllowedRules ) { for ( i = 0, l = genericAllowedRules.length; i < l; ++i ) applyAllowedRule( genericAllowedRules[ i ], element, status, skipRequired ); } return status; }
javascript
function filterElement( that, element, opts ) { var name = element.name, privObj = that._, allowedRules = privObj.allowedRules.elements[ name ], genericAllowedRules = privObj.allowedRules.generic, disallowedRules = privObj.disallowedRules.elements[ name ], genericDisallowedRules = privObj.disallowedRules.generic, skipRequired = opts.skipRequired, status = { // Whether any of rules accepted element. // If not - it will be stripped. valid: false, // Objects containing accepted attributes, classes and styles. validAttributes: {}, validClasses: {}, validStyles: {}, // Whether all are valid. // If we know that all element's attrs/classes/styles are valid // we can skip their validation, to improve performance. allAttributes: false, allClasses: false, allStyles: false, // Whether element had (before applying DACRs) at least one invalid attribute/class/style. hadInvalidAttribute: false, hadInvalidClass: false, hadInvalidStyle: false }, i, l; // Early return - if there are no rules for this element (specific or generic), remove it. if ( !allowedRules && !genericAllowedRules ) return null; // Could not be done yet if there were no transformations and if this // is real (not mocked) object. populateProperties( element ); // Note - this step modifies element's styles, classes and attributes. if ( disallowedRules ) { for ( i = 0, l = disallowedRules.length; i < l; ++i ) { // Apply rule and make an early return if false is returned what means // that element is completely disallowed. if ( applyDisallowedRule( disallowedRules[ i ], element, status ) === false ) return null; } } // Note - this step modifies element's styles, classes and attributes. if ( genericDisallowedRules ) { for ( i = 0, l = genericDisallowedRules.length; i < l; ++i ) applyDisallowedRule( genericDisallowedRules[ i ], element, status ); } if ( allowedRules ) { for ( i = 0, l = allowedRules.length; i < l; ++i ) applyAllowedRule( allowedRules[ i ], element, status, skipRequired ); } if ( genericAllowedRules ) { for ( i = 0, l = genericAllowedRules.length; i < l; ++i ) applyAllowedRule( genericAllowedRules[ i ], element, status, skipRequired ); } return status; }
[ "function", "filterElement", "(", "that", ",", "element", ",", "opts", ")", "{", "var", "name", "=", "element", ".", "name", ",", "privObj", "=", "that", ".", "_", ",", "allowedRules", "=", "privObj", ".", "allowedRules", ".", "elements", "[", "name", "]", ",", "genericAllowedRules", "=", "privObj", ".", "allowedRules", ".", "generic", ",", "disallowedRules", "=", "privObj", ".", "disallowedRules", ".", "elements", "[", "name", "]", ",", "genericDisallowedRules", "=", "privObj", ".", "disallowedRules", ".", "generic", ",", "skipRequired", "=", "opts", ".", "skipRequired", ",", "status", "=", "{", "// Whether any of rules accepted element.", "// If not - it will be stripped.", "valid", ":", "false", ",", "// Objects containing accepted attributes, classes and styles.", "validAttributes", ":", "{", "}", ",", "validClasses", ":", "{", "}", ",", "validStyles", ":", "{", "}", ",", "// Whether all are valid.", "// If we know that all element's attrs/classes/styles are valid", "// we can skip their validation, to improve performance.", "allAttributes", ":", "false", ",", "allClasses", ":", "false", ",", "allStyles", ":", "false", ",", "// Whether element had (before applying DACRs) at least one invalid attribute/class/style.", "hadInvalidAttribute", ":", "false", ",", "hadInvalidClass", ":", "false", ",", "hadInvalidStyle", ":", "false", "}", ",", "i", ",", "l", ";", "// Early return - if there are no rules for this element (specific or generic), remove it.", "if", "(", "!", "allowedRules", "&&", "!", "genericAllowedRules", ")", "return", "null", ";", "// Could not be done yet if there were no transformations and if this", "// is real (not mocked) object.", "populateProperties", "(", "element", ")", ";", "// Note - this step modifies element's styles, classes and attributes.", "if", "(", "disallowedRules", ")", "{", "for", "(", "i", "=", "0", ",", "l", "=", "disallowedRules", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "{", "// Apply rule and make an early return if false is returned what means", "// that element is completely disallowed.", "if", "(", "applyDisallowedRule", "(", "disallowedRules", "[", "i", "]", ",", "element", ",", "status", ")", "===", "false", ")", "return", "null", ";", "}", "}", "// Note - this step modifies element's styles, classes and attributes.", "if", "(", "genericDisallowedRules", ")", "{", "for", "(", "i", "=", "0", ",", "l", "=", "genericDisallowedRules", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "applyDisallowedRule", "(", "genericDisallowedRules", "[", "i", "]", ",", "element", ",", "status", ")", ";", "}", "if", "(", "allowedRules", ")", "{", "for", "(", "i", "=", "0", ",", "l", "=", "allowedRules", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "applyAllowedRule", "(", "allowedRules", "[", "i", "]", ",", "element", ",", "status", ",", "skipRequired", ")", ";", "}", "if", "(", "genericAllowedRules", ")", "{", "for", "(", "i", "=", "0", ",", "l", "=", "genericAllowedRules", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "applyAllowedRule", "(", "genericAllowedRules", "[", "i", "]", ",", "element", ",", "status", ",", "skipRequired", ")", ";", "}", "return", "status", ";", "}" ]
Does the actual filtering by appling allowed content rules to the element. @param {CKEDITOR.filter} that The context. @param {CKEDITOR.htmlParser.element} element @param {Object} opts The same as in processElement.
[ "Does", "the", "actual", "filtering", "by", "appling", "allowed", "content", "rules", "to", "the", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1109-L1173
54,655
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
mockElementFromString
function mockElementFromString( str ) { var element = parseRulesString( str ).$1, styles = element.styles, classes = element.classes; element.name = element.elements; element.classes = classes = ( classes ? classes.split( /\s*,\s*/ ) : [] ); element.styles = mockHash( styles ); element.attributes = mockHash( element.attributes ); element.children = []; if ( classes.length ) element.attributes[ 'class' ] = classes.join( ' ' ); if ( styles ) element.attributes.style = CKEDITOR.tools.writeCssText( element.styles ); return element; }
javascript
function mockElementFromString( str ) { var element = parseRulesString( str ).$1, styles = element.styles, classes = element.classes; element.name = element.elements; element.classes = classes = ( classes ? classes.split( /\s*,\s*/ ) : [] ); element.styles = mockHash( styles ); element.attributes = mockHash( element.attributes ); element.children = []; if ( classes.length ) element.attributes[ 'class' ] = classes.join( ' ' ); if ( styles ) element.attributes.style = CKEDITOR.tools.writeCssText( element.styles ); return element; }
[ "function", "mockElementFromString", "(", "str", ")", "{", "var", "element", "=", "parseRulesString", "(", "str", ")", ".", "$1", ",", "styles", "=", "element", ".", "styles", ",", "classes", "=", "element", ".", "classes", ";", "element", ".", "name", "=", "element", ".", "elements", ";", "element", ".", "classes", "=", "classes", "=", "(", "classes", "?", "classes", ".", "split", "(", "/", "\\s*,\\s*", "/", ")", ":", "[", "]", ")", ";", "element", ".", "styles", "=", "mockHash", "(", "styles", ")", ";", "element", ".", "attributes", "=", "mockHash", "(", "element", ".", "attributes", ")", ";", "element", ".", "children", "=", "[", "]", ";", "if", "(", "classes", ".", "length", ")", "element", ".", "attributes", "[", "'class'", "]", "=", "classes", ".", "join", "(", "' '", ")", ";", "if", "(", "styles", ")", "element", ".", "attributes", ".", "style", "=", "CKEDITOR", ".", "tools", ".", "writeCssText", "(", "element", ".", "styles", ")", ";", "return", "element", ";", "}" ]
Create pseudo element that will be passed through filter to check if tested string is allowed.
[ "Create", "pseudo", "element", "that", "will", "be", "passed", "through", "filter", "to", "check", "if", "tested", "string", "is", "allowed", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1225-L1242
54,656
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
mockElementFromStyle
function mockElementFromStyle( style ) { var styleDef = style.getDefinition(), styles = styleDef.styles, attrs = styleDef.attributes || {}; if ( styles ) { styles = copy( styles ); attrs.style = CKEDITOR.tools.writeCssText( styles, true ); } else { styles = {}; } var el = { name: styleDef.element, attributes: attrs, classes: attrs[ 'class' ] ? attrs[ 'class' ].split( /\s+/ ) : [], styles: styles, children: [] }; return el; }
javascript
function mockElementFromStyle( style ) { var styleDef = style.getDefinition(), styles = styleDef.styles, attrs = styleDef.attributes || {}; if ( styles ) { styles = copy( styles ); attrs.style = CKEDITOR.tools.writeCssText( styles, true ); } else { styles = {}; } var el = { name: styleDef.element, attributes: attrs, classes: attrs[ 'class' ] ? attrs[ 'class' ].split( /\s+/ ) : [], styles: styles, children: [] }; return el; }
[ "function", "mockElementFromStyle", "(", "style", ")", "{", "var", "styleDef", "=", "style", ".", "getDefinition", "(", ")", ",", "styles", "=", "styleDef", ".", "styles", ",", "attrs", "=", "styleDef", ".", "attributes", "||", "{", "}", ";", "if", "(", "styles", ")", "{", "styles", "=", "copy", "(", "styles", ")", ";", "attrs", ".", "style", "=", "CKEDITOR", ".", "tools", ".", "writeCssText", "(", "styles", ",", "true", ")", ";", "}", "else", "{", "styles", "=", "{", "}", ";", "}", "var", "el", "=", "{", "name", ":", "styleDef", ".", "element", ",", "attributes", ":", "attrs", ",", "classes", ":", "attrs", "[", "'class'", "]", "?", "attrs", "[", "'class'", "]", ".", "split", "(", "/", "\\s+", "/", ")", ":", "[", "]", ",", "styles", ":", "styles", ",", "children", ":", "[", "]", "}", ";", "return", "el", ";", "}" ]
Create pseudo element that will be passed through filter to check if tested style is allowed.
[ "Create", "pseudo", "element", "that", "will", "be", "passed", "through", "filter", "to", "check", "if", "tested", "style", "is", "allowed", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1246-L1267
54,657
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
optimizeRule
function optimizeRule( rule ) { var validatorName, requiredProperties, i; for ( validatorName in validators ) rule[ validatorName ] = validatorFunction( rule[ validatorName ] ); var nothingRequired = true; for ( i in validatorsRequired ) { validatorName = validatorsRequired[ i ]; requiredProperties = optimizeRequiredProperties( rule[ validatorName ] ); // Don't set anything if there are no required properties. This will allow to // save some memory by GCing all empty arrays (requiredProperties). if ( requiredProperties.length ) { rule[ validatorName ] = requiredProperties; nothingRequired = false; } } rule.nothingRequired = nothingRequired; rule.noProperties = !( rule.attributes || rule.classes || rule.styles ); }
javascript
function optimizeRule( rule ) { var validatorName, requiredProperties, i; for ( validatorName in validators ) rule[ validatorName ] = validatorFunction( rule[ validatorName ] ); var nothingRequired = true; for ( i in validatorsRequired ) { validatorName = validatorsRequired[ i ]; requiredProperties = optimizeRequiredProperties( rule[ validatorName ] ); // Don't set anything if there are no required properties. This will allow to // save some memory by GCing all empty arrays (requiredProperties). if ( requiredProperties.length ) { rule[ validatorName ] = requiredProperties; nothingRequired = false; } } rule.nothingRequired = nothingRequired; rule.noProperties = !( rule.attributes || rule.classes || rule.styles ); }
[ "function", "optimizeRule", "(", "rule", ")", "{", "var", "validatorName", ",", "requiredProperties", ",", "i", ";", "for", "(", "validatorName", "in", "validators", ")", "rule", "[", "validatorName", "]", "=", "validatorFunction", "(", "rule", "[", "validatorName", "]", ")", ";", "var", "nothingRequired", "=", "true", ";", "for", "(", "i", "in", "validatorsRequired", ")", "{", "validatorName", "=", "validatorsRequired", "[", "i", "]", ";", "requiredProperties", "=", "optimizeRequiredProperties", "(", "rule", "[", "validatorName", "]", ")", ";", "// Don't set anything if there are no required properties. This will allow to", "// save some memory by GCing all empty arrays (requiredProperties).", "if", "(", "requiredProperties", ".", "length", ")", "{", "rule", "[", "validatorName", "]", "=", "requiredProperties", ";", "nothingRequired", "=", "false", ";", "}", "}", "rule", ".", "nothingRequired", "=", "nothingRequired", ";", "rule", ".", "noProperties", "=", "!", "(", "rule", ".", "attributes", "||", "rule", ".", "classes", "||", "rule", ".", "styles", ")", ";", "}" ]
Optimize a rule by replacing validators with functions and rewriting requiredXXX validators to arrays.
[ "Optimize", "a", "rule", "by", "replacing", "validators", "with", "functions", "and", "rewriting", "requiredXXX", "validators", "to", "arrays", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1312-L1334
54,658
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
optimizeRules
function optimizeRules( optimizedRules, rules ) { var elementsRules = optimizedRules.elements, genericRules = optimizedRules.generic, i, l, rule, element, priority; for ( i = 0, l = rules.length; i < l; ++i ) { // Shallow copy. Do not modify original rule. rule = copy( rules[ i ] ); priority = rule.classes === true || rule.styles === true || rule.attributes === true; optimizeRule( rule ); // E.g. "*(xxx)[xxx]" - it's a generic rule that // validates properties only. // Or '$1': { match: function() {...} } if ( rule.elements === true || rule.elements === null ) { // Add priority rules at the beginning. genericRules[ priority ? 'unshift' : 'push' ]( rule ); } // If elements list was explicitly defined, // add this rule for every defined element. else { // We don't need elements validator for this kind of rule. var elements = rule.elements; delete rule.elements; for ( element in elements ) { if ( !elementsRules[ element ] ) elementsRules[ element ] = [ rule ]; else elementsRules[ element ][ priority ? 'unshift' : 'push' ]( rule ); } } } }
javascript
function optimizeRules( optimizedRules, rules ) { var elementsRules = optimizedRules.elements, genericRules = optimizedRules.generic, i, l, rule, element, priority; for ( i = 0, l = rules.length; i < l; ++i ) { // Shallow copy. Do not modify original rule. rule = copy( rules[ i ] ); priority = rule.classes === true || rule.styles === true || rule.attributes === true; optimizeRule( rule ); // E.g. "*(xxx)[xxx]" - it's a generic rule that // validates properties only. // Or '$1': { match: function() {...} } if ( rule.elements === true || rule.elements === null ) { // Add priority rules at the beginning. genericRules[ priority ? 'unshift' : 'push' ]( rule ); } // If elements list was explicitly defined, // add this rule for every defined element. else { // We don't need elements validator for this kind of rule. var elements = rule.elements; delete rule.elements; for ( element in elements ) { if ( !elementsRules[ element ] ) elementsRules[ element ] = [ rule ]; else elementsRules[ element ][ priority ? 'unshift' : 'push' ]( rule ); } } } }
[ "function", "optimizeRules", "(", "optimizedRules", ",", "rules", ")", "{", "var", "elementsRules", "=", "optimizedRules", ".", "elements", ",", "genericRules", "=", "optimizedRules", ".", "generic", ",", "i", ",", "l", ",", "rule", ",", "element", ",", "priority", ";", "for", "(", "i", "=", "0", ",", "l", "=", "rules", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "{", "// Shallow copy. Do not modify original rule.", "rule", "=", "copy", "(", "rules", "[", "i", "]", ")", ";", "priority", "=", "rule", ".", "classes", "===", "true", "||", "rule", ".", "styles", "===", "true", "||", "rule", ".", "attributes", "===", "true", ";", "optimizeRule", "(", "rule", ")", ";", "// E.g. \"*(xxx)[xxx]\" - it's a generic rule that", "// validates properties only.", "// Or '$1': { match: function() {...} }", "if", "(", "rule", ".", "elements", "===", "true", "||", "rule", ".", "elements", "===", "null", ")", "{", "// Add priority rules at the beginning.", "genericRules", "[", "priority", "?", "'unshift'", ":", "'push'", "]", "(", "rule", ")", ";", "}", "// If elements list was explicitly defined,", "// add this rule for every defined element.", "else", "{", "// We don't need elements validator for this kind of rule.", "var", "elements", "=", "rule", ".", "elements", ";", "delete", "rule", ".", "elements", ";", "for", "(", "element", "in", "elements", ")", "{", "if", "(", "!", "elementsRules", "[", "element", "]", ")", "elementsRules", "[", "element", "]", "=", "[", "rule", "]", ";", "else", "elementsRules", "[", "element", "]", "[", "priority", "?", "'unshift'", ":", "'push'", "]", "(", "rule", ")", ";", "}", "}", "}", "}" ]
Add optimized version of rule to optimizedRules object.
[ "Add", "optimized", "version", "of", "rule", "to", "optimizedRules", "object", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1337-L1370
54,659
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
processProtectedElement
function processProtectedElement( that, comment, protectedRegexs, filterOpts ) { var source = decodeURIComponent( comment.value.replace( /^\{cke_protected\}/, '' ) ), protectedFrag, toBeRemoved = [], node, i, match; // Protected element's and protected source's comments look exactly the same. // Check if what we have isn't a protected source instead of protected script/noscript. if ( protectedRegexs ) { for ( i = 0; i < protectedRegexs.length; ++i ) { if ( ( match = source.match( protectedRegexs[ i ] ) ) && match[ 0 ].length == source.length // Check whether this pattern matches entire source // to avoid '<script>alert("<? 1 ?>")</script>' matching // the PHP's protectedSource regexp. ) return true; } } protectedFrag = CKEDITOR.htmlParser.fragment.fromHtml( source ); if ( protectedFrag.children.length == 1 && ( node = protectedFrag.children[ 0 ] ).type == CKEDITOR.NODE_ELEMENT ) processElement( that, node, toBeRemoved, filterOpts ); // If protected element has been marked to be removed, return 'false' - comment was rejected. return !toBeRemoved.length; }
javascript
function processProtectedElement( that, comment, protectedRegexs, filterOpts ) { var source = decodeURIComponent( comment.value.replace( /^\{cke_protected\}/, '' ) ), protectedFrag, toBeRemoved = [], node, i, match; // Protected element's and protected source's comments look exactly the same. // Check if what we have isn't a protected source instead of protected script/noscript. if ( protectedRegexs ) { for ( i = 0; i < protectedRegexs.length; ++i ) { if ( ( match = source.match( protectedRegexs[ i ] ) ) && match[ 0 ].length == source.length // Check whether this pattern matches entire source // to avoid '<script>alert("<? 1 ?>")</script>' matching // the PHP's protectedSource regexp. ) return true; } } protectedFrag = CKEDITOR.htmlParser.fragment.fromHtml( source ); if ( protectedFrag.children.length == 1 && ( node = protectedFrag.children[ 0 ] ).type == CKEDITOR.NODE_ELEMENT ) processElement( that, node, toBeRemoved, filterOpts ); // If protected element has been marked to be removed, return 'false' - comment was rejected. return !toBeRemoved.length; }
[ "function", "processProtectedElement", "(", "that", ",", "comment", ",", "protectedRegexs", ",", "filterOpts", ")", "{", "var", "source", "=", "decodeURIComponent", "(", "comment", ".", "value", ".", "replace", "(", "/", "^\\{cke_protected\\}", "/", ",", "''", ")", ")", ",", "protectedFrag", ",", "toBeRemoved", "=", "[", "]", ",", "node", ",", "i", ",", "match", ";", "// Protected element's and protected source's comments look exactly the same.", "// Check if what we have isn't a protected source instead of protected script/noscript.", "if", "(", "protectedRegexs", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "protectedRegexs", ".", "length", ";", "++", "i", ")", "{", "if", "(", "(", "match", "=", "source", ".", "match", "(", "protectedRegexs", "[", "i", "]", ")", ")", "&&", "match", "[", "0", "]", ".", "length", "==", "source", ".", "length", "// Check whether this pattern matches entire source", "// to avoid '<script>alert(\"<? 1 ?>\")</script>' matching", "// the PHP's protectedSource regexp.", ")", "return", "true", ";", "}", "}", "protectedFrag", "=", "CKEDITOR", ".", "htmlParser", ".", "fragment", ".", "fromHtml", "(", "source", ")", ";", "if", "(", "protectedFrag", ".", "children", ".", "length", "==", "1", "&&", "(", "node", "=", "protectedFrag", ".", "children", "[", "0", "]", ")", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", ")", "processElement", "(", "that", ",", "node", ",", "toBeRemoved", ",", "filterOpts", ")", ";", "// If protected element has been marked to be removed, return 'false' - comment was rejected.", "return", "!", "toBeRemoved", ".", "length", ";", "}" ]
Filter element protected with a comment. Returns true if protected content is ok, false otherwise.
[ "Filter", "element", "protected", "with", "a", "comment", ".", "Returns", "true", "if", "protected", "content", "is", "ok", "false", "otherwise", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1435-L1461
54,660
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
processElement
function processElement( that, element, toBeRemoved, opts ) { var status, retVal = 0, callbacksRetVal; // Unprotect elements names previously protected by htmlDataProcessor // (see protectElementNames and protectSelfClosingElements functions). // Note: body, title, etc. are not protected by htmlDataP (or are protected and then unprotected). if ( opts.toHtml ) element.name = element.name.replace( unprotectElementsNamesRegexp, '$1' ); // Execute element callbacks and return if one of them returned any value. if ( opts.doCallbacks && that.elementCallbacks ) { // For now we only support here FILTER_SKIP_TREE, so we can early return if retVal is truly value. if ( ( callbacksRetVal = executeElementCallbacks( element, that.elementCallbacks ) ) ) return callbacksRetVal; } // If transformations are set apply all groups. if ( opts.doTransform ) transformElement( that, element ); if ( opts.doFilter ) { // Apply all filters. status = filterElement( that, element, opts ); // Handle early return from filterElement. if ( !status ) { toBeRemoved.push( element ); return FILTER_ELEMENT_MODIFIED; } // Finally, if after running all filter rules it still hasn't been allowed - remove it. if ( !status.valid ) { toBeRemoved.push( element ); return FILTER_ELEMENT_MODIFIED; } // Update element's attributes based on status of filtering. if ( updateElement( element, status ) ) retVal = FILTER_ELEMENT_MODIFIED; if ( !opts.skipFinalValidation && !validateElement( element ) ) { toBeRemoved.push( element ); return FILTER_ELEMENT_MODIFIED; } } // Protect previously unprotected elements. if ( opts.toHtml ) element.name = element.name.replace( protectElementsNamesRegexp, 'cke:$1' ); return retVal; }
javascript
function processElement( that, element, toBeRemoved, opts ) { var status, retVal = 0, callbacksRetVal; // Unprotect elements names previously protected by htmlDataProcessor // (see protectElementNames and protectSelfClosingElements functions). // Note: body, title, etc. are not protected by htmlDataP (or are protected and then unprotected). if ( opts.toHtml ) element.name = element.name.replace( unprotectElementsNamesRegexp, '$1' ); // Execute element callbacks and return if one of them returned any value. if ( opts.doCallbacks && that.elementCallbacks ) { // For now we only support here FILTER_SKIP_TREE, so we can early return if retVal is truly value. if ( ( callbacksRetVal = executeElementCallbacks( element, that.elementCallbacks ) ) ) return callbacksRetVal; } // If transformations are set apply all groups. if ( opts.doTransform ) transformElement( that, element ); if ( opts.doFilter ) { // Apply all filters. status = filterElement( that, element, opts ); // Handle early return from filterElement. if ( !status ) { toBeRemoved.push( element ); return FILTER_ELEMENT_MODIFIED; } // Finally, if after running all filter rules it still hasn't been allowed - remove it. if ( !status.valid ) { toBeRemoved.push( element ); return FILTER_ELEMENT_MODIFIED; } // Update element's attributes based on status of filtering. if ( updateElement( element, status ) ) retVal = FILTER_ELEMENT_MODIFIED; if ( !opts.skipFinalValidation && !validateElement( element ) ) { toBeRemoved.push( element ); return FILTER_ELEMENT_MODIFIED; } } // Protect previously unprotected elements. if ( opts.toHtml ) element.name = element.name.replace( protectElementsNamesRegexp, 'cke:$1' ); return retVal; }
[ "function", "processElement", "(", "that", ",", "element", ",", "toBeRemoved", ",", "opts", ")", "{", "var", "status", ",", "retVal", "=", "0", ",", "callbacksRetVal", ";", "// Unprotect elements names previously protected by htmlDataProcessor", "// (see protectElementNames and protectSelfClosingElements functions).", "// Note: body, title, etc. are not protected by htmlDataP (or are protected and then unprotected).", "if", "(", "opts", ".", "toHtml", ")", "element", ".", "name", "=", "element", ".", "name", ".", "replace", "(", "unprotectElementsNamesRegexp", ",", "'$1'", ")", ";", "// Execute element callbacks and return if one of them returned any value.", "if", "(", "opts", ".", "doCallbacks", "&&", "that", ".", "elementCallbacks", ")", "{", "// For now we only support here FILTER_SKIP_TREE, so we can early return if retVal is truly value.", "if", "(", "(", "callbacksRetVal", "=", "executeElementCallbacks", "(", "element", ",", "that", ".", "elementCallbacks", ")", ")", ")", "return", "callbacksRetVal", ";", "}", "// If transformations are set apply all groups.", "if", "(", "opts", ".", "doTransform", ")", "transformElement", "(", "that", ",", "element", ")", ";", "if", "(", "opts", ".", "doFilter", ")", "{", "// Apply all filters.", "status", "=", "filterElement", "(", "that", ",", "element", ",", "opts", ")", ";", "// Handle early return from filterElement.", "if", "(", "!", "status", ")", "{", "toBeRemoved", ".", "push", "(", "element", ")", ";", "return", "FILTER_ELEMENT_MODIFIED", ";", "}", "// Finally, if after running all filter rules it still hasn't been allowed - remove it.", "if", "(", "!", "status", ".", "valid", ")", "{", "toBeRemoved", ".", "push", "(", "element", ")", ";", "return", "FILTER_ELEMENT_MODIFIED", ";", "}", "// Update element's attributes based on status of filtering.", "if", "(", "updateElement", "(", "element", ",", "status", ")", ")", "retVal", "=", "FILTER_ELEMENT_MODIFIED", ";", "if", "(", "!", "opts", ".", "skipFinalValidation", "&&", "!", "validateElement", "(", "element", ")", ")", "{", "toBeRemoved", ".", "push", "(", "element", ")", ";", "return", "FILTER_ELEMENT_MODIFIED", ";", "}", "}", "// Protect previously unprotected elements.", "if", "(", "opts", ".", "toHtml", ")", "element", ".", "name", "=", "element", ".", "name", ".", "replace", "(", "protectElementsNamesRegexp", ",", "'cke:$1'", ")", ";", "return", "retVal", ";", "}" ]
The actual function which filters, transforms and does other funny things with an element. @param {CKEDITOR.filter} that Context. @param {CKEDITOR.htmlParser.element} element The element to be processed. @param {Array} toBeRemoved Array into which elements rejected by the filter will be pushed. @param {Boolean} [opts.doFilter] Whether element should be filtered. @param {Boolean} [opts.doTransform] Whether transformations should be applied. @param {Boolean} [opts.doCallbacks] Whether to execute element callbacks. @param {Boolean} [opts.toHtml] Set to true if filter used together with htmlDP#toHtml @param {Boolean} [opts.skipRequired] Whether element's required properties shouldn't be verified. @param {Boolean} [opts.skipFinalValidation] Whether to not perform final element validation (a,img). @returns {Number} Possible flags: * FILTER_ELEMENT_MODIFIED, * FILTER_SKIP_TREE.
[ "The", "actual", "function", "which", "filters", "transforms", "and", "does", "other", "funny", "things", "with", "an", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1480-L1533
54,661
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
regexifyPropertiesWithWildcards
function regexifyPropertiesWithWildcards( validators ) { var patterns = [], i; for ( i in validators ) { if ( i.indexOf( '*' ) > -1 ) patterns.push( i.replace( /\*/g, '.*' ) ); } if ( patterns.length ) return new RegExp( '^(?:' + patterns.join( '|' ) + ')$' ); else return null; }
javascript
function regexifyPropertiesWithWildcards( validators ) { var patterns = [], i; for ( i in validators ) { if ( i.indexOf( '*' ) > -1 ) patterns.push( i.replace( /\*/g, '.*' ) ); } if ( patterns.length ) return new RegExp( '^(?:' + patterns.join( '|' ) + ')$' ); else return null; }
[ "function", "regexifyPropertiesWithWildcards", "(", "validators", ")", "{", "var", "patterns", "=", "[", "]", ",", "i", ";", "for", "(", "i", "in", "validators", ")", "{", "if", "(", "i", ".", "indexOf", "(", "'*'", ")", ">", "-", "1", ")", "patterns", ".", "push", "(", "i", ".", "replace", "(", "/", "\\*", "/", "g", ",", "'.*'", ")", ")", ";", "}", "if", "(", "patterns", ".", "length", ")", "return", "new", "RegExp", "(", "'^(?:'", "+", "patterns", ".", "join", "(", "'|'", ")", "+", "')$'", ")", ";", "else", "return", "null", ";", "}" ]
Returns a regexp object which can be used to test if a property matches one of wildcard validators.
[ "Returns", "a", "regexp", "object", "which", "can", "be", "used", "to", "test", "if", "a", "property", "matches", "one", "of", "wildcard", "validators", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1537-L1550
54,662
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
standardizeRule
function standardizeRule( rule ) { rule.elements = convertValidatorToHash( rule.elements, /\s+/ ) || null; rule.propertiesOnly = rule.propertiesOnly || ( rule.elements === true ); var delim = /\s*,\s*/, i; for ( i in validators ) { rule[ i ] = convertValidatorToHash( rule[ i ], delim ) || null; rule[ validatorsRequired[ i ] ] = extractRequired( convertValidatorToHash( rule[ validatorsRequired[ i ] ], delim ), rule[ i ] ) || null; } rule.match = rule.match || null; }
javascript
function standardizeRule( rule ) { rule.elements = convertValidatorToHash( rule.elements, /\s+/ ) || null; rule.propertiesOnly = rule.propertiesOnly || ( rule.elements === true ); var delim = /\s*,\s*/, i; for ( i in validators ) { rule[ i ] = convertValidatorToHash( rule[ i ], delim ) || null; rule[ validatorsRequired[ i ] ] = extractRequired( convertValidatorToHash( rule[ validatorsRequired[ i ] ], delim ), rule[ i ] ) || null; } rule.match = rule.match || null; }
[ "function", "standardizeRule", "(", "rule", ")", "{", "rule", ".", "elements", "=", "convertValidatorToHash", "(", "rule", ".", "elements", ",", "/", "\\s+", "/", ")", "||", "null", ";", "rule", ".", "propertiesOnly", "=", "rule", ".", "propertiesOnly", "||", "(", "rule", ".", "elements", "===", "true", ")", ";", "var", "delim", "=", "/", "\\s*,\\s*", "/", ",", "i", ";", "for", "(", "i", "in", "validators", ")", "{", "rule", "[", "i", "]", "=", "convertValidatorToHash", "(", "rule", "[", "i", "]", ",", "delim", ")", "||", "null", ";", "rule", "[", "validatorsRequired", "[", "i", "]", "]", "=", "extractRequired", "(", "convertValidatorToHash", "(", "rule", "[", "validatorsRequired", "[", "i", "]", "]", ",", "delim", ")", ",", "rule", "[", "i", "]", ")", "||", "null", ";", "}", "rule", ".", "match", "=", "rule", ".", "match", "||", "null", ";", "}" ]
Standardize a rule by converting all validators to hashes.
[ "Standardize", "a", "rule", "by", "converting", "all", "validators", "to", "hashes", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1553-L1567
54,663
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
transformElement
function transformElement( that, element ) { var transformations = that._.transformations[ element.name ], i; if ( !transformations ) return; populateProperties( element ); for ( i = 0; i < transformations.length; ++i ) applyTransformationsGroup( that, element, transformations[ i ] ); // Do not count on updateElement() which is called in processElement, because it: // * may not be called, // * may skip some properties when all are marked as valid. updateAttributes( element ); }
javascript
function transformElement( that, element ) { var transformations = that._.transformations[ element.name ], i; if ( !transformations ) return; populateProperties( element ); for ( i = 0; i < transformations.length; ++i ) applyTransformationsGroup( that, element, transformations[ i ] ); // Do not count on updateElement() which is called in processElement, because it: // * may not be called, // * may skip some properties when all are marked as valid. updateAttributes( element ); }
[ "function", "transformElement", "(", "that", ",", "element", ")", "{", "var", "transformations", "=", "that", ".", "_", ".", "transformations", "[", "element", ".", "name", "]", ",", "i", ";", "if", "(", "!", "transformations", ")", "return", ";", "populateProperties", "(", "element", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "transformations", ".", "length", ";", "++", "i", ")", "applyTransformationsGroup", "(", "that", ",", "element", ",", "transformations", "[", "i", "]", ")", ";", "// Do not count on updateElement() which is called in processElement, because it:", "// * may not be called,", "// * may skip some properties when all are marked as valid.", "updateAttributes", "(", "element", ")", ";", "}" ]
Does the element transformation by applying registered transformation rules.
[ "Does", "the", "element", "transformation", "by", "applying", "registered", "transformation", "rules", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1571-L1587
54,664
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
updateAttributes
function updateAttributes( element ) { var attrs = element.attributes, styles; // Will be recreated later if any of styles/classes exists. delete attrs.style; delete attrs[ 'class' ]; if ( ( styles = CKEDITOR.tools.writeCssText( element.styles, true ) ) ) attrs.style = styles; if ( element.classes.length ) attrs[ 'class' ] = element.classes.sort().join( ' ' ); }
javascript
function updateAttributes( element ) { var attrs = element.attributes, styles; // Will be recreated later if any of styles/classes exists. delete attrs.style; delete attrs[ 'class' ]; if ( ( styles = CKEDITOR.tools.writeCssText( element.styles, true ) ) ) attrs.style = styles; if ( element.classes.length ) attrs[ 'class' ] = element.classes.sort().join( ' ' ); }
[ "function", "updateAttributes", "(", "element", ")", "{", "var", "attrs", "=", "element", ".", "attributes", ",", "styles", ";", "// Will be recreated later if any of styles/classes exists.", "delete", "attrs", ".", "style", ";", "delete", "attrs", "[", "'class'", "]", ";", "if", "(", "(", "styles", "=", "CKEDITOR", ".", "tools", ".", "writeCssText", "(", "element", ".", "styles", ",", "true", ")", ")", ")", "attrs", ".", "style", "=", "styles", ";", "if", "(", "element", ".", "classes", ".", "length", ")", "attrs", "[", "'class'", "]", "=", "element", ".", "classes", ".", "sort", "(", ")", ".", "join", "(", "' '", ")", ";", "}" ]
Copy element's styles and classes back to attributes array.
[ "Copy", "element", "s", "styles", "and", "classes", "back", "to", "attributes", "array", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1590-L1603
54,665
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
updateElement
function updateElement( element, status ) { var validAttrs = status.validAttributes, validStyles = status.validStyles, validClasses = status.validClasses, attrs = element.attributes, styles = element.styles, classes = element.classes, origClasses = element.classBackup, origStyles = element.styleBackup, name, origName, i, stylesArr = [], classesArr = [], internalAttr = /^data-cke-/, isModified = false; // Will be recreated later if any of styles/classes were passed. delete attrs.style; delete attrs[ 'class' ]; // Clean up. delete element.classBackup; delete element.styleBackup; if ( !status.allAttributes ) { for ( name in attrs ) { // If not valid and not internal attribute delete it. if ( !validAttrs[ name ] ) { // Allow all internal attibutes... if ( internalAttr.test( name ) ) { // ... unless this is a saved attribute and the original one isn't allowed. if ( name != ( origName = name.replace( /^data-cke-saved-/, '' ) ) && !validAttrs[ origName ] ) { delete attrs[ name ]; isModified = true; } } else { delete attrs[ name ]; isModified = true; } } } } if ( !status.allStyles || status.hadInvalidStyle ) { for ( name in styles ) { // We check status.allStyles because when there was a '*' ACR and some // DACR we have now both properties true - status.allStyles and status.hadInvalidStyle. // However unlike in the case when we only have '*' ACR, in which we can just copy original // styles, in this case we must copy only those styles which were not removed by DACRs. if ( status.allStyles || validStyles[ name ] ) stylesArr.push( name + ':' + styles[ name ] ); else isModified = true; } if ( stylesArr.length ) attrs.style = stylesArr.sort().join( '; ' ); } else if ( origStyles ) { attrs.style = origStyles; } if ( !status.allClasses || status.hadInvalidClass ) { for ( i = 0; i < classes.length; ++i ) { // See comment for styles. if ( status.allClasses || validClasses[ classes[ i ] ] ) classesArr.push( classes[ i ] ); } if ( classesArr.length ) attrs[ 'class' ] = classesArr.sort().join( ' ' ); if ( origClasses && classesArr.length < origClasses.split( /\s+/ ).length ) isModified = true; } else if ( origClasses ) { attrs[ 'class' ] = origClasses; } return isModified; }
javascript
function updateElement( element, status ) { var validAttrs = status.validAttributes, validStyles = status.validStyles, validClasses = status.validClasses, attrs = element.attributes, styles = element.styles, classes = element.classes, origClasses = element.classBackup, origStyles = element.styleBackup, name, origName, i, stylesArr = [], classesArr = [], internalAttr = /^data-cke-/, isModified = false; // Will be recreated later if any of styles/classes were passed. delete attrs.style; delete attrs[ 'class' ]; // Clean up. delete element.classBackup; delete element.styleBackup; if ( !status.allAttributes ) { for ( name in attrs ) { // If not valid and not internal attribute delete it. if ( !validAttrs[ name ] ) { // Allow all internal attibutes... if ( internalAttr.test( name ) ) { // ... unless this is a saved attribute and the original one isn't allowed. if ( name != ( origName = name.replace( /^data-cke-saved-/, '' ) ) && !validAttrs[ origName ] ) { delete attrs[ name ]; isModified = true; } } else { delete attrs[ name ]; isModified = true; } } } } if ( !status.allStyles || status.hadInvalidStyle ) { for ( name in styles ) { // We check status.allStyles because when there was a '*' ACR and some // DACR we have now both properties true - status.allStyles and status.hadInvalidStyle. // However unlike in the case when we only have '*' ACR, in which we can just copy original // styles, in this case we must copy only those styles which were not removed by DACRs. if ( status.allStyles || validStyles[ name ] ) stylesArr.push( name + ':' + styles[ name ] ); else isModified = true; } if ( stylesArr.length ) attrs.style = stylesArr.sort().join( '; ' ); } else if ( origStyles ) { attrs.style = origStyles; } if ( !status.allClasses || status.hadInvalidClass ) { for ( i = 0; i < classes.length; ++i ) { // See comment for styles. if ( status.allClasses || validClasses[ classes[ i ] ] ) classesArr.push( classes[ i ] ); } if ( classesArr.length ) attrs[ 'class' ] = classesArr.sort().join( ' ' ); if ( origClasses && classesArr.length < origClasses.split( /\s+/ ).length ) isModified = true; } else if ( origClasses ) { attrs[ 'class' ] = origClasses; } return isModified; }
[ "function", "updateElement", "(", "element", ",", "status", ")", "{", "var", "validAttrs", "=", "status", ".", "validAttributes", ",", "validStyles", "=", "status", ".", "validStyles", ",", "validClasses", "=", "status", ".", "validClasses", ",", "attrs", "=", "element", ".", "attributes", ",", "styles", "=", "element", ".", "styles", ",", "classes", "=", "element", ".", "classes", ",", "origClasses", "=", "element", ".", "classBackup", ",", "origStyles", "=", "element", ".", "styleBackup", ",", "name", ",", "origName", ",", "i", ",", "stylesArr", "=", "[", "]", ",", "classesArr", "=", "[", "]", ",", "internalAttr", "=", "/", "^data-cke-", "/", ",", "isModified", "=", "false", ";", "// Will be recreated later if any of styles/classes were passed.", "delete", "attrs", ".", "style", ";", "delete", "attrs", "[", "'class'", "]", ";", "// Clean up.", "delete", "element", ".", "classBackup", ";", "delete", "element", ".", "styleBackup", ";", "if", "(", "!", "status", ".", "allAttributes", ")", "{", "for", "(", "name", "in", "attrs", ")", "{", "// If not valid and not internal attribute delete it.", "if", "(", "!", "validAttrs", "[", "name", "]", ")", "{", "// Allow all internal attibutes...", "if", "(", "internalAttr", ".", "test", "(", "name", ")", ")", "{", "// ... unless this is a saved attribute and the original one isn't allowed.", "if", "(", "name", "!=", "(", "origName", "=", "name", ".", "replace", "(", "/", "^data-cke-saved-", "/", ",", "''", ")", ")", "&&", "!", "validAttrs", "[", "origName", "]", ")", "{", "delete", "attrs", "[", "name", "]", ";", "isModified", "=", "true", ";", "}", "}", "else", "{", "delete", "attrs", "[", "name", "]", ";", "isModified", "=", "true", ";", "}", "}", "}", "}", "if", "(", "!", "status", ".", "allStyles", "||", "status", ".", "hadInvalidStyle", ")", "{", "for", "(", "name", "in", "styles", ")", "{", "// We check status.allStyles because when there was a '*' ACR and some", "// DACR we have now both properties true - status.allStyles and status.hadInvalidStyle.", "// However unlike in the case when we only have '*' ACR, in which we can just copy original", "// styles, in this case we must copy only those styles which were not removed by DACRs.", "if", "(", "status", ".", "allStyles", "||", "validStyles", "[", "name", "]", ")", "stylesArr", ".", "push", "(", "name", "+", "':'", "+", "styles", "[", "name", "]", ")", ";", "else", "isModified", "=", "true", ";", "}", "if", "(", "stylesArr", ".", "length", ")", "attrs", ".", "style", "=", "stylesArr", ".", "sort", "(", ")", ".", "join", "(", "'; '", ")", ";", "}", "else", "if", "(", "origStyles", ")", "{", "attrs", ".", "style", "=", "origStyles", ";", "}", "if", "(", "!", "status", ".", "allClasses", "||", "status", ".", "hadInvalidClass", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "classes", ".", "length", ";", "++", "i", ")", "{", "// See comment for styles.", "if", "(", "status", ".", "allClasses", "||", "validClasses", "[", "classes", "[", "i", "]", "]", ")", "classesArr", ".", "push", "(", "classes", "[", "i", "]", ")", ";", "}", "if", "(", "classesArr", ".", "length", ")", "attrs", "[", "'class'", "]", "=", "classesArr", ".", "sort", "(", ")", ".", "join", "(", "' '", ")", ";", "if", "(", "origClasses", "&&", "classesArr", ".", "length", "<", "origClasses", ".", "split", "(", "/", "\\s+", "/", ")", ".", "length", ")", "isModified", "=", "true", ";", "}", "else", "if", "(", "origClasses", ")", "{", "attrs", "[", "'class'", "]", "=", "origClasses", ";", "}", "return", "isModified", ";", "}" ]
Update element object based on status of filtering. @returns Whether element was modified.
[ "Update", "element", "object", "based", "on", "status", "of", "filtering", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1607-L1686
54,666
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
inlineNode
function inlineNode( node ) { return node.type == CKEDITOR.NODE_TEXT || node.type == CKEDITOR.NODE_ELEMENT && DTD.$inline[ node.name ]; }
javascript
function inlineNode( node ) { return node.type == CKEDITOR.NODE_TEXT || node.type == CKEDITOR.NODE_ELEMENT && DTD.$inline[ node.name ]; }
[ "function", "inlineNode", "(", "node", ")", "{", "return", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_TEXT", "||", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "DTD", ".", "$inline", "[", "node", ".", "name", "]", ";", "}" ]
Whether this is an inline element or text.
[ "Whether", "this", "is", "an", "inline", "element", "or", "text", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1744-L1747
54,667
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
removeElement
function removeElement( element, enterTag, toBeChecked ) { var name = element.name; if ( DTD.$empty[ name ] || !element.children.length ) { // Special case - hr in br mode should be replaced with br, not removed. if ( name == 'hr' && enterTag == 'br' ) element.replaceWith( createBr() ); else { // Parent might become an empty inline specified in $removeEmpty or empty a[href]. if ( element.parent ) toBeChecked.push( { check: 'it', el: element.parent } ); element.remove(); } } else if ( DTD.$block[ name ] || name == 'tr' ) { if ( enterTag == 'br' ) stripBlockBr( element, toBeChecked ); else stripBlock( element, enterTag, toBeChecked ); } // Special case - elements that may contain CDATA // should be removed completely. <script> is handled // by processProtectedElement(). else if ( name == 'style' ) element.remove(); // The rest of inline elements. May also be the last resort // for some special elements. else { // Parent might become an empty inline specified in $removeEmpty or empty a[href]. if ( element.parent ) toBeChecked.push( { check: 'it', el: element.parent } ); element.replaceWithChildren(); } }
javascript
function removeElement( element, enterTag, toBeChecked ) { var name = element.name; if ( DTD.$empty[ name ] || !element.children.length ) { // Special case - hr in br mode should be replaced with br, not removed. if ( name == 'hr' && enterTag == 'br' ) element.replaceWith( createBr() ); else { // Parent might become an empty inline specified in $removeEmpty or empty a[href]. if ( element.parent ) toBeChecked.push( { check: 'it', el: element.parent } ); element.remove(); } } else if ( DTD.$block[ name ] || name == 'tr' ) { if ( enterTag == 'br' ) stripBlockBr( element, toBeChecked ); else stripBlock( element, enterTag, toBeChecked ); } // Special case - elements that may contain CDATA // should be removed completely. <script> is handled // by processProtectedElement(). else if ( name == 'style' ) element.remove(); // The rest of inline elements. May also be the last resort // for some special elements. else { // Parent might become an empty inline specified in $removeEmpty or empty a[href]. if ( element.parent ) toBeChecked.push( { check: 'it', el: element.parent } ); element.replaceWithChildren(); } }
[ "function", "removeElement", "(", "element", ",", "enterTag", ",", "toBeChecked", ")", "{", "var", "name", "=", "element", ".", "name", ";", "if", "(", "DTD", ".", "$empty", "[", "name", "]", "||", "!", "element", ".", "children", ".", "length", ")", "{", "// Special case - hr in br mode should be replaced with br, not removed.", "if", "(", "name", "==", "'hr'", "&&", "enterTag", "==", "'br'", ")", "element", ".", "replaceWith", "(", "createBr", "(", ")", ")", ";", "else", "{", "// Parent might become an empty inline specified in $removeEmpty or empty a[href].", "if", "(", "element", ".", "parent", ")", "toBeChecked", ".", "push", "(", "{", "check", ":", "'it'", ",", "el", ":", "element", ".", "parent", "}", ")", ";", "element", ".", "remove", "(", ")", ";", "}", "}", "else", "if", "(", "DTD", ".", "$block", "[", "name", "]", "||", "name", "==", "'tr'", ")", "{", "if", "(", "enterTag", "==", "'br'", ")", "stripBlockBr", "(", "element", ",", "toBeChecked", ")", ";", "else", "stripBlock", "(", "element", ",", "enterTag", ",", "toBeChecked", ")", ";", "}", "// Special case - elements that may contain CDATA", "// should be removed completely. <script> is handled", "// by processProtectedElement().", "else", "if", "(", "name", "==", "'style'", ")", "element", ".", "remove", "(", ")", ";", "// The rest of inline elements. May also be the last resort", "// for some special elements.", "else", "{", "// Parent might become an empty inline specified in $removeEmpty or empty a[href].", "if", "(", "element", ".", "parent", ")", "toBeChecked", ".", "push", "(", "{", "check", ":", "'it'", ",", "el", ":", "element", ".", "parent", "}", ")", ";", "element", ".", "replaceWithChildren", "(", ")", ";", "}", "}" ]
Try to remove element in the best possible way. @param {Array} toBeChecked After executing this function this array will contain elements that should be checked because they were marked as potentially: * in wrong context (e.g. li in body), * empty elements from $removeEmpty, * incorrect img/a/other element validated by validateElement().
[ "Try", "to", "remove", "element", "in", "the", "best", "possible", "way", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1762-L1795
54,668
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
stripBlock
function stripBlock( element, enterTag, toBeChecked ) { var children = element.children; // First, check if element's children may be wrapped with <p/div>. // Ignore that <p/div> may not be allowed in element.parent. // This will be fixed when removing parent or by toBeChecked rule. if ( checkChildren( children, enterTag ) ) { element.name = enterTag; element.attributes = {}; // Check if this p/div was put in correct context. // If not - strip parent. toBeChecked.push( { check: 'parent-down', el: element } ); return; } var parent = element.parent, shouldAutoP = parent.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT || parent.name == 'body', i, child, p; for ( i = children.length; i > 0; ) { child = children[ --i ]; // If parent requires auto paragraphing and child is inline node, // insert this child into newly created paragraph. if ( shouldAutoP && inlineNode( child ) ) { if ( !p ) { p = new CKEDITOR.htmlParser.element( enterTag ); p.insertAfter( element ); // Check if this p/div was put in correct context. // If not - strip parent. toBeChecked.push( { check: 'parent-down', el: p } ); } p.add( child, 0 ); } // Child which doesn't need to be auto paragraphed. else { p = null; child.insertAfter( element ); // If inserted into invalid context, mark it and check // after removing all elements. if ( parent.type != CKEDITOR.NODE_DOCUMENT_FRAGMENT && child.type == CKEDITOR.NODE_ELEMENT && !DTD[ parent.name ][ child.name ] ) toBeChecked.push( { check: 'el-up', el: child } ); } } // All children have been moved to element's parent, so remove it. element.remove(); }
javascript
function stripBlock( element, enterTag, toBeChecked ) { var children = element.children; // First, check if element's children may be wrapped with <p/div>. // Ignore that <p/div> may not be allowed in element.parent. // This will be fixed when removing parent or by toBeChecked rule. if ( checkChildren( children, enterTag ) ) { element.name = enterTag; element.attributes = {}; // Check if this p/div was put in correct context. // If not - strip parent. toBeChecked.push( { check: 'parent-down', el: element } ); return; } var parent = element.parent, shouldAutoP = parent.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT || parent.name == 'body', i, child, p; for ( i = children.length; i > 0; ) { child = children[ --i ]; // If parent requires auto paragraphing and child is inline node, // insert this child into newly created paragraph. if ( shouldAutoP && inlineNode( child ) ) { if ( !p ) { p = new CKEDITOR.htmlParser.element( enterTag ); p.insertAfter( element ); // Check if this p/div was put in correct context. // If not - strip parent. toBeChecked.push( { check: 'parent-down', el: p } ); } p.add( child, 0 ); } // Child which doesn't need to be auto paragraphed. else { p = null; child.insertAfter( element ); // If inserted into invalid context, mark it and check // after removing all elements. if ( parent.type != CKEDITOR.NODE_DOCUMENT_FRAGMENT && child.type == CKEDITOR.NODE_ELEMENT && !DTD[ parent.name ][ child.name ] ) toBeChecked.push( { check: 'el-up', el: child } ); } } // All children have been moved to element's parent, so remove it. element.remove(); }
[ "function", "stripBlock", "(", "element", ",", "enterTag", ",", "toBeChecked", ")", "{", "var", "children", "=", "element", ".", "children", ";", "// First, check if element's children may be wrapped with <p/div>.", "// Ignore that <p/div> may not be allowed in element.parent.", "// This will be fixed when removing parent or by toBeChecked rule.", "if", "(", "checkChildren", "(", "children", ",", "enterTag", ")", ")", "{", "element", ".", "name", "=", "enterTag", ";", "element", ".", "attributes", "=", "{", "}", ";", "// Check if this p/div was put in correct context.", "// If not - strip parent.", "toBeChecked", ".", "push", "(", "{", "check", ":", "'parent-down'", ",", "el", ":", "element", "}", ")", ";", "return", ";", "}", "var", "parent", "=", "element", ".", "parent", ",", "shouldAutoP", "=", "parent", ".", "type", "==", "CKEDITOR", ".", "NODE_DOCUMENT_FRAGMENT", "||", "parent", ".", "name", "==", "'body'", ",", "i", ",", "child", ",", "p", ";", "for", "(", "i", "=", "children", ".", "length", ";", "i", ">", "0", ";", ")", "{", "child", "=", "children", "[", "--", "i", "]", ";", "// If parent requires auto paragraphing and child is inline node,", "// insert this child into newly created paragraph.", "if", "(", "shouldAutoP", "&&", "inlineNode", "(", "child", ")", ")", "{", "if", "(", "!", "p", ")", "{", "p", "=", "new", "CKEDITOR", ".", "htmlParser", ".", "element", "(", "enterTag", ")", ";", "p", ".", "insertAfter", "(", "element", ")", ";", "// Check if this p/div was put in correct context.", "// If not - strip parent.", "toBeChecked", ".", "push", "(", "{", "check", ":", "'parent-down'", ",", "el", ":", "p", "}", ")", ";", "}", "p", ".", "add", "(", "child", ",", "0", ")", ";", "}", "// Child which doesn't need to be auto paragraphed.", "else", "{", "p", "=", "null", ";", "child", ".", "insertAfter", "(", "element", ")", ";", "// If inserted into invalid context, mark it and check", "// after removing all elements.", "if", "(", "parent", ".", "type", "!=", "CKEDITOR", ".", "NODE_DOCUMENT_FRAGMENT", "&&", "child", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "!", "DTD", "[", "parent", ".", "name", "]", "[", "child", ".", "name", "]", ")", "toBeChecked", ".", "push", "(", "{", "check", ":", "'el-up'", ",", "el", ":", "child", "}", ")", ";", "}", "}", "// All children have been moved to element's parent, so remove it.", "element", ".", "remove", "(", ")", ";", "}" ]
Strip element block, but leave its content. Works in 'div' and 'p' enter modes.
[ "Strip", "element", "block", "but", "leave", "its", "content", ".", "Works", "in", "div", "and", "p", "enter", "modes", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1799-L1850
54,669
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
getContentFormTransformationGroup
function getContentFormTransformationGroup( form, preferredForm ) { var element, left; if ( typeof form == 'string' ) element = form; else if ( form instanceof CKEDITOR.style ) left = form; else { element = form[ 0 ]; left = form[ 1 ]; } return [ { element: element, left: left, right: function( el, tools ) { tools.transform( el, preferredForm ); } } ]; }
javascript
function getContentFormTransformationGroup( form, preferredForm ) { var element, left; if ( typeof form == 'string' ) element = form; else if ( form instanceof CKEDITOR.style ) left = form; else { element = form[ 0 ]; left = form[ 1 ]; } return [ { element: element, left: left, right: function( el, tools ) { tools.transform( el, preferredForm ); } } ]; }
[ "function", "getContentFormTransformationGroup", "(", "form", ",", "preferredForm", ")", "{", "var", "element", ",", "left", ";", "if", "(", "typeof", "form", "==", "'string'", ")", "element", "=", "form", ";", "else", "if", "(", "form", "instanceof", "CKEDITOR", ".", "style", ")", "left", "=", "form", ";", "else", "{", "element", "=", "form", "[", "0", "]", ";", "left", "=", "form", "[", "1", "]", ";", "}", "return", "[", "{", "element", ":", "element", ",", "left", ":", "left", ",", "right", ":", "function", "(", "el", ",", "tools", ")", "{", "tools", ".", "transform", "(", "el", ",", "preferredForm", ")", ";", "}", "}", "]", ";", "}" ]
Return transformation group for content form. One content form makes one transformation rule in one group.
[ "Return", "transformation", "group", "for", "content", "form", ".", "One", "content", "form", "makes", "one", "transformation", "rule", "in", "one", "group", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L1932-L1951
54,670
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
function( element ) { if ( !( 'float' in element.styles ) ) { var value = element.attributes.align; if ( value == 'left' || value == 'right' ) element.styles[ 'float' ] = value; // Uh... GCC doesn't like the 'float' prop name. } delete element.attributes.align; }
javascript
function( element ) { if ( !( 'float' in element.styles ) ) { var value = element.attributes.align; if ( value == 'left' || value == 'right' ) element.styles[ 'float' ] = value; // Uh... GCC doesn't like the 'float' prop name. } delete element.attributes.align; }
[ "function", "(", "element", ")", "{", "if", "(", "!", "(", "'float'", "in", "element", ".", "styles", ")", ")", "{", "var", "value", "=", "element", ".", "attributes", ".", "align", ";", "if", "(", "value", "==", "'left'", "||", "value", "==", "'right'", ")", "element", ".", "styles", "[", "'float'", "]", "=", "value", ";", "// Uh... GCC doesn't like the 'float' prop name.", "}", "delete", "element", ".", "attributes", ".", "align", ";", "}" ]
Converts the `align` attribute to the `float` style if not set. Attribute is always removed. @param {CKEDITOR.htmlParser.element} element
[ "Converts", "the", "align", "attribute", "to", "the", "float", "style", "if", "not", "set", ".", "Attribute", "is", "always", "removed", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L2099-L2108
54,671
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/filter.js
function( el, form ) { if ( typeof form == 'string' ) el.name = form; // Form is an instance of CKEDITOR.style. else { var def = form.getDefinition(), defStyles = def.styles, defAttrs = def.attributes, attrName, styleName, existingClassesPattern, defClasses, cl; el.name = def.element; for ( attrName in defAttrs ) { if ( attrName == 'class' ) { existingClassesPattern = el.classes.join( '|' ); defClasses = defAttrs[ attrName ].split( /\s+/ ); while ( ( cl = defClasses.pop() ) ) { if ( existingClassesPattern.indexOf( cl ) == -1 ) el.classes.push( cl ); } } else { el.attributes[ attrName ] = defAttrs[ attrName ]; } } for ( styleName in defStyles ) { el.styles[ styleName ] = defStyles[ styleName ]; } } }
javascript
function( el, form ) { if ( typeof form == 'string' ) el.name = form; // Form is an instance of CKEDITOR.style. else { var def = form.getDefinition(), defStyles = def.styles, defAttrs = def.attributes, attrName, styleName, existingClassesPattern, defClasses, cl; el.name = def.element; for ( attrName in defAttrs ) { if ( attrName == 'class' ) { existingClassesPattern = el.classes.join( '|' ); defClasses = defAttrs[ attrName ].split( /\s+/ ); while ( ( cl = defClasses.pop() ) ) { if ( existingClassesPattern.indexOf( cl ) == -1 ) el.classes.push( cl ); } } else { el.attributes[ attrName ] = defAttrs[ attrName ]; } } for ( styleName in defStyles ) { el.styles[ styleName ] = defStyles[ styleName ]; } } }
[ "function", "(", "el", ",", "form", ")", "{", "if", "(", "typeof", "form", "==", "'string'", ")", "el", ".", "name", "=", "form", ";", "// Form is an instance of CKEDITOR.style.", "else", "{", "var", "def", "=", "form", ".", "getDefinition", "(", ")", ",", "defStyles", "=", "def", ".", "styles", ",", "defAttrs", "=", "def", ".", "attributes", ",", "attrName", ",", "styleName", ",", "existingClassesPattern", ",", "defClasses", ",", "cl", ";", "el", ".", "name", "=", "def", ".", "element", ";", "for", "(", "attrName", "in", "defAttrs", ")", "{", "if", "(", "attrName", "==", "'class'", ")", "{", "existingClassesPattern", "=", "el", ".", "classes", ".", "join", "(", "'|'", ")", ";", "defClasses", "=", "defAttrs", "[", "attrName", "]", ".", "split", "(", "/", "\\s+", "/", ")", ";", "while", "(", "(", "cl", "=", "defClasses", ".", "pop", "(", ")", ")", ")", "{", "if", "(", "existingClassesPattern", ".", "indexOf", "(", "cl", ")", "==", "-", "1", ")", "el", ".", "classes", ".", "push", "(", "cl", ")", ";", "}", "}", "else", "{", "el", ".", "attributes", "[", "attrName", "]", "=", "defAttrs", "[", "attrName", "]", ";", "}", "}", "for", "(", "styleName", "in", "defStyles", ")", "{", "el", ".", "styles", "[", "styleName", "]", "=", "defStyles", "[", "styleName", "]", ";", "}", "}", "}" ]
Transforms element to given form. Form may be a: * {@link CKEDITOR.style}, * string &ndash; the new name of an element. @param {CKEDITOR.htmlParser.element} el @param {CKEDITOR.style/String} form
[ "Transforms", "element", "to", "given", "form", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/filter.js#L2148-L2180
54,672
klugjo/express-route-manager
index.js
RouteManager
function RouteManager(opts) { var defaultActions = { // Encapsulation of the next callback in express routes next: function(req, res, next) { next(); }, // Render view render: function (req, res, next, data) { res.render(data.render.viewPath, data.render.viewData); }, // Send back json json: function (req, res, next, data) { res.send(data.json); }, // Redirect to URL redirect: function (req, res, next, data) { res.redirect(data.redirect); } }; // Default authenticated function var defaultAuthenticated = function (req, res, next) { console.warn('No authentication function setup'); next(); }; // This function should return a express route function. var defaultCheckRole = function (role) { return function (req, res, next) { console.warn('No check role function setup'); next(); }; }; opts = opts || {}; this._app = opts.app; this._customActions = defaultActions; this._authenticated = opts.authenticated || defaultAuthenticated; this._checkRole = opts.checkRole || defaultCheckRole; if(opts.actions) { _.merge(this._customActions, opts.actions); } }
javascript
function RouteManager(opts) { var defaultActions = { // Encapsulation of the next callback in express routes next: function(req, res, next) { next(); }, // Render view render: function (req, res, next, data) { res.render(data.render.viewPath, data.render.viewData); }, // Send back json json: function (req, res, next, data) { res.send(data.json); }, // Redirect to URL redirect: function (req, res, next, data) { res.redirect(data.redirect); } }; // Default authenticated function var defaultAuthenticated = function (req, res, next) { console.warn('No authentication function setup'); next(); }; // This function should return a express route function. var defaultCheckRole = function (role) { return function (req, res, next) { console.warn('No check role function setup'); next(); }; }; opts = opts || {}; this._app = opts.app; this._customActions = defaultActions; this._authenticated = opts.authenticated || defaultAuthenticated; this._checkRole = opts.checkRole || defaultCheckRole; if(opts.actions) { _.merge(this._customActions, opts.actions); } }
[ "function", "RouteManager", "(", "opts", ")", "{", "var", "defaultActions", "=", "{", "// Encapsulation of the next callback in express routes", "next", ":", "function", "(", "req", ",", "res", ",", "next", ")", "{", "next", "(", ")", ";", "}", ",", "// Render view", "render", ":", "function", "(", "req", ",", "res", ",", "next", ",", "data", ")", "{", "res", ".", "render", "(", "data", ".", "render", ".", "viewPath", ",", "data", ".", "render", ".", "viewData", ")", ";", "}", ",", "// Send back json", "json", ":", "function", "(", "req", ",", "res", ",", "next", ",", "data", ")", "{", "res", ".", "send", "(", "data", ".", "json", ")", ";", "}", ",", "// Redirect to URL", "redirect", ":", "function", "(", "req", ",", "res", ",", "next", ",", "data", ")", "{", "res", ".", "redirect", "(", "data", ".", "redirect", ")", ";", "}", "}", ";", "// Default authenticated function", "var", "defaultAuthenticated", "=", "function", "(", "req", ",", "res", ",", "next", ")", "{", "console", ".", "warn", "(", "'No authentication function setup'", ")", ";", "next", "(", ")", ";", "}", ";", "// This function should return a express route function.", "var", "defaultCheckRole", "=", "function", "(", "role", ")", "{", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "console", ".", "warn", "(", "'No check role function setup'", ")", ";", "next", "(", ")", ";", "}", ";", "}", ";", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "_app", "=", "opts", ".", "app", ";", "this", ".", "_customActions", "=", "defaultActions", ";", "this", ".", "_authenticated", "=", "opts", ".", "authenticated", "||", "defaultAuthenticated", ";", "this", ".", "_checkRole", "=", "opts", ".", "checkRole", "||", "defaultCheckRole", ";", "if", "(", "opts", ".", "actions", ")", "{", "_", ".", "merge", "(", "this", ".", "_customActions", ",", "opts", ".", "actions", ")", ";", "}", "}" ]
Initialize the Route Manager @param opts - initialization options @param opts.app - express app @param opts.authenticated - used to check if the user is authenticated. fn(req, res, next) {..} -> call next if authenticated. @param opts.checkRole - used to check the role. fn(role) { return fn(req, res, next) {..}} -> call next if role is OK. @param opts.actions - Additional actions @constructor
[ "Initialize", "the", "Route", "Manager" ]
f83043bd66bf5108ed0ca696605967d9dd3407f1
https://github.com/klugjo/express-route-manager/blob/f83043bd66bf5108ed0ca696605967d9dd3407f1/index.js#L13-L66
54,673
egg-/log-notifier
lib/notifier.js
function(message) { var identifier = _makeIdentifier(message); if (typeof _filter[identifier] !== 'undefined' && _filter[identifier] < ((+new Date()) + 10 * 60000)) { console.error('duplicated error', identifier, message); return _filter[identifier]; } _filter[identifier] = +new Date(); return false; }
javascript
function(message) { var identifier = _makeIdentifier(message); if (typeof _filter[identifier] !== 'undefined' && _filter[identifier] < ((+new Date()) + 10 * 60000)) { console.error('duplicated error', identifier, message); return _filter[identifier]; } _filter[identifier] = +new Date(); return false; }
[ "function", "(", "message", ")", "{", "var", "identifier", "=", "_makeIdentifier", "(", "message", ")", ";", "if", "(", "typeof", "_filter", "[", "identifier", "]", "!==", "'undefined'", "&&", "_filter", "[", "identifier", "]", "<", "(", "(", "+", "new", "Date", "(", ")", ")", "+", "10", "*", "60000", ")", ")", "{", "console", ".", "error", "(", "'duplicated error'", ",", "identifier", ",", "message", ")", ";", "return", "_filter", "[", "identifier", "]", ";", "}", "_filter", "[", "identifier", "]", "=", "+", "new", "Date", "(", ")", ";", "return", "false", ";", "}" ]
check whether duplicated message. @param {object} message @return {boolean | integer} whether duplicated
[ "check", "whether", "duplicated", "message", "." ]
ada3b90f8893140a5ed5757eb14d777b700fadb7
https://github.com/egg-/log-notifier/blob/ada3b90f8893140a5ed5757eb14d777b700fadb7/lib/notifier.js#L149-L158
54,674
nodesource/ah-fs
ah-fs.js
findWriteStream
function findWriteStream(arg, copy) { if (copy.proto !== 'ReadableState') return null if (copy.pipes != null && copy.pipes.proto !== 'WriteStream') return null return arg.pipes }
javascript
function findWriteStream(arg, copy) { if (copy.proto !== 'ReadableState') return null if (copy.pipes != null && copy.pipes.proto !== 'WriteStream') return null return arg.pipes }
[ "function", "findWriteStream", "(", "arg", ",", "copy", ")", "{", "if", "(", "copy", ".", "proto", "!==", "'ReadableState'", ")", "return", "null", "if", "(", "copy", ".", "pipes", "!=", "null", "&&", "copy", ".", "pipes", ".", "proto", "!==", "'WriteStream'", ")", "return", "null", "return", "arg", ".", "pipes", "}" ]
The WriteStream is attached to the pipes of a ReadableState of the ReadStream that is piped into it. If one is found, it is returned so it can be added to the copied args. @name findWriteStream @function @private @param {Object} arg the original arg found on the resource @param {Object} copy the clone of the arg
[ "The", "WriteStream", "is", "attached", "to", "the", "pipes", "of", "a", "ReadableState", "of", "the", "ReadStream", "that", "is", "piped", "into", "it", "." ]
5b52cb492a9e07c6beae60d42af548dca0a3ad8e
https://github.com/nodesource/ah-fs/blob/5b52cb492a9e07c6beae60d42af548dca0a3ad8e/ah-fs.js#L37-L41
54,675
bredele/mouth
index.js
parse
function parse(str, arr) { return str.replace(/\.\w+|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g, function(expr) { if(forbidden.indexOf(expr[0]) > -1) return expr; if(!~arr.indexOf(expr)) arr.push(expr); return 'model.' + expr; }); }
javascript
function parse(str, arr) { return str.replace(/\.\w+|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g, function(expr) { if(forbidden.indexOf(expr[0]) > -1) return expr; if(!~arr.indexOf(expr)) arr.push(expr); return 'model.' + expr; }); }
[ "function", "parse", "(", "str", ",", "arr", ")", "{", "return", "str", ".", "replace", "(", "/", "\\.\\w+|\"[^\"]*\"|'[^']*'|\\/([^/]+)\\/|[a-zA-Z_]\\w*", "/", "g", ",", "function", "(", "expr", ")", "{", "if", "(", "forbidden", ".", "indexOf", "(", "expr", "[", "0", "]", ")", ">", "-", "1", ")", "return", "expr", ";", "if", "(", "!", "~", "arr", ".", "indexOf", "(", "expr", ")", ")", "arr", ".", "push", "(", "expr", ")", ";", "return", "'model.'", "+", "expr", ";", "}", ")", ";", "}" ]
Parse expression and replace identifier. Examples: compile('name + last'); // => model.name + model.last compile('name[0]'); // => model.name[0] @param {String} str @param {Array} arr @return {String} @api private
[ "Parse", "expression", "and", "replace", "identifier", "." ]
9d5846e50c64155e28670a076c7cb6a8d3c7c087
https://github.com/bredele/mouth/blob/9d5846e50c64155e28670a076c7cb6a8d3c7c087/index.js#L57-L63
54,676
darrencruse/sugarlisp-core
gentab-native.js
handleYield
function handleYield(forms) { var yieldType = sl.valueOf(forms[0]); // "yield" or "yield*" if (forms.length != 2) { forms.error(yieldType + " expects a single expression"); } this.indent += this.indentSize; this.transpileSubExpressions(forms); var generated = sl.generated(); generated.push([yieldType, " ", forms[1]]); this.indent -= this.indentSize; return generated; }
javascript
function handleYield(forms) { var yieldType = sl.valueOf(forms[0]); // "yield" or "yield*" if (forms.length != 2) { forms.error(yieldType + " expects a single expression"); } this.indent += this.indentSize; this.transpileSubExpressions(forms); var generated = sl.generated(); generated.push([yieldType, " ", forms[1]]); this.indent -= this.indentSize; return generated; }
[ "function", "handleYield", "(", "forms", ")", "{", "var", "yieldType", "=", "sl", ".", "valueOf", "(", "forms", "[", "0", "]", ")", ";", "// \"yield\" or \"yield*\"", "if", "(", "forms", ".", "length", "!=", "2", ")", "{", "forms", ".", "error", "(", "yieldType", "+", "\" expects a single expression\"", ")", ";", "}", "this", ".", "indent", "+=", "this", ".", "indentSize", ";", "this", ".", "transpileSubExpressions", "(", "forms", ")", ";", "var", "generated", "=", "sl", ".", "generated", "(", ")", ";", "generated", ".", "push", "(", "[", "yieldType", ",", "\" \"", ",", "forms", "[", "1", "]", "]", ")", ";", "this", ".", "indent", "-=", "this", ".", "indentSize", ";", "return", "generated", ";", "}" ]
es6 yield expressions
[ "es6", "yield", "expressions" ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/gentab-native.js#L144-L156
54,677
darrencruse/sugarlisp-core
gentab-native.js
function(forms) { if (forms.length < 2) { forms.error("missing argument for operator"); } if(forms.length > 2) { // it's a normal binary (or more) minus return handleArithOperator.call(this, forms); } // it's a unary minus this.transpileSubExpressions(forms) var generated = sl.generated() generated.push(["-", sl.valueOf(forms[1])]); generated.callable = false; return generated; }
javascript
function(forms) { if (forms.length < 2) { forms.error("missing argument for operator"); } if(forms.length > 2) { // it's a normal binary (or more) minus return handleArithOperator.call(this, forms); } // it's a unary minus this.transpileSubExpressions(forms) var generated = sl.generated() generated.push(["-", sl.valueOf(forms[1])]); generated.callable = false; return generated; }
[ "function", "(", "forms", ")", "{", "if", "(", "forms", ".", "length", "<", "2", ")", "{", "forms", ".", "error", "(", "\"missing argument for operator\"", ")", ";", "}", "if", "(", "forms", ".", "length", ">", "2", ")", "{", "// it's a normal binary (or more) minus", "return", "handleArithOperator", ".", "call", "(", "this", ",", "forms", ")", ";", "}", "// it's a unary minus", "this", ".", "transpileSubExpressions", "(", "forms", ")", "var", "generated", "=", "sl", ".", "generated", "(", ")", "generated", ".", "push", "(", "[", "\"-\"", ",", "sl", ".", "valueOf", "(", "forms", "[", "1", "]", ")", "]", ")", ";", "generated", ".", "callable", "=", "false", ";", "return", "generated", ";", "}" ]
Minus is unique in that it can be a unary minus
[ "Minus", "is", "unique", "in", "that", "it", "can", "be", "a", "unary", "minus" ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/gentab-native.js#L795-L810
54,678
forfuturellc/svc-fbr
src/lib/cli.js
startService
function startService() { let me = this; return server.start(me, function(err) { if (err) { return out.error("service failed to start: %j", err); } return server.ping(me, function() { out.success("service started"); }); }); }
javascript
function startService() { let me = this; return server.start(me, function(err) { if (err) { return out.error("service failed to start: %j", err); } return server.ping(me, function() { out.success("service started"); }); }); }
[ "function", "startService", "(", ")", "{", "let", "me", "=", "this", ";", "return", "server", ".", "start", "(", "me", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "out", ".", "error", "(", "\"service failed to start: %j\"", ",", "err", ")", ";", "}", "return", "server", ".", "ping", "(", "me", ",", "function", "(", ")", "{", "out", ".", "success", "(", "\"service started\"", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Start the service
[ "Start", "the", "service" ]
8c07c71d6423d1dbd4f903a032dea0bfec63894e
https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/cli.js#L35-L45
54,679
forfuturellc/svc-fbr
src/lib/cli.js
stopService
function stopService() { return server.stop(this, function(err) { if (err) { return out.error("service did not respond well: %j", err); } return out.success("service stopped"); }); }
javascript
function stopService() { return server.stop(this, function(err) { if (err) { return out.error("service did not respond well: %j", err); } return out.success("service stopped"); }); }
[ "function", "stopService", "(", ")", "{", "return", "server", ".", "stop", "(", "this", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "out", ".", "error", "(", "\"service did not respond well: %j\"", ",", "err", ")", ";", "}", "return", "out", ".", "success", "(", "\"service stopped\"", ")", ";", "}", ")", ";", "}" ]
Stop the service
[ "Stop", "the", "service" ]
8c07c71d6423d1dbd4f903a032dea0bfec63894e
https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/cli.js#L51-L58
54,680
forfuturellc/svc-fbr
src/lib/cli.js
checkStatus
function checkStatus() { return server.ping(this, function(err, res) { if (err) { return out.error("error occurred: %j", err); } if (res.running) { return out.success("service running"); } return out.error("service not running"); }); }
javascript
function checkStatus() { return server.ping(this, function(err, res) { if (err) { return out.error("error occurred: %j", err); } if (res.running) { return out.success("service running"); } return out.error("service not running"); }); }
[ "function", "checkStatus", "(", ")", "{", "return", "server", ".", "ping", "(", "this", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "return", "out", ".", "error", "(", "\"error occurred: %j\"", ",", "err", ")", ";", "}", "if", "(", "res", ".", "running", ")", "{", "return", "out", ".", "success", "(", "\"service running\"", ")", ";", "}", "return", "out", ".", "error", "(", "\"service not running\"", ")", ";", "}", ")", ";", "}" ]
Check status of the service
[ "Check", "status", "of", "the", "service" ]
8c07c71d6423d1dbd4f903a032dea0bfec63894e
https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/cli.js#L64-L74
54,681
75lb/common-dir
index.js
commonDir
function commonDir (files) { return files .map(path.dirname) .map(function (dir) { return dir.split(path.sep) }) .reduce(commonSequence) .concat(['']) .join(path.sep) }
javascript
function commonDir (files) { return files .map(path.dirname) .map(function (dir) { return dir.split(path.sep) }) .reduce(commonSequence) .concat(['']) .join(path.sep) }
[ "function", "commonDir", "(", "files", ")", "{", "return", "files", ".", "map", "(", "path", ".", "dirname", ")", ".", "map", "(", "function", "(", "dir", ")", "{", "return", "dir", ".", "split", "(", "path", ".", "sep", ")", "}", ")", ".", "reduce", "(", "commonSequence", ")", ".", "concat", "(", "[", "''", "]", ")", ".", "join", "(", "path", ".", "sep", ")", "}" ]
Returns the parent directory common to each path. @param {Array} files - An array of file paths to inspect @returns {string} A single path ending with the path separator, e.g. '/user/some/folder/' @alias module:common-dir @example > const commonDir = require('common-dir') > files = [ '/Users/75lb/one/package.json', '/Users/75lb/one/test', '/Users/75lb/two/test/main.js' ] > commonDir(files) '/Users/75lb/'
[ "Returns", "the", "parent", "directory", "common", "to", "each", "path", "." ]
501382e13ae44a97eefa11a09b747cd740445d9f
https://github.com/75lb/common-dir/blob/501382e13ae44a97eefa11a09b747cd740445d9f/index.js#L25-L34
54,682
ItsAsbreuk/itsa-jsext
lib/object.js
function (fn, context) { var obj = this, keys = Object.keys(obj), l = keys.length, i = -1, key; while (++i < l) { key = keys[i]; fn.call(context || obj, obj[key], key, obj); } return obj; }
javascript
function (fn, context) { var obj = this, keys = Object.keys(obj), l = keys.length, i = -1, key; while (++i < l) { key = keys[i]; fn.call(context || obj, obj[key], key, obj); } return obj; }
[ "function", "(", "fn", ",", "context", ")", "{", "var", "obj", "=", "this", ",", "keys", "=", "Object", ".", "keys", "(", "obj", ")", ",", "l", "=", "keys", ".", "length", ",", "i", "=", "-", "1", ",", "key", ";", "while", "(", "++", "i", "<", "l", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "fn", ".", "call", "(", "context", "||", "obj", ",", "obj", "[", "key", "]", ",", "key", ",", "obj", ")", ";", "}", "return", "obj", ";", "}" ]
Loops through all properties in the object. Equivalent to Array.forEach. The callback is provided with the value of the property, the name of the property and a reference to the whole object itself. The context to run the callback in can be overriden, otherwise it is undefined. @method itsa_each @param fn {Function} Function to be executed on each item in the object. It will receive value {any} value of the property key {string} name of the property obj {Object} the whole of the object @chainable
[ "Loops", "through", "all", "properties", "in", "the", "object", ".", "Equivalent", "to", "Array", ".", "forEach", ".", "The", "callback", "is", "provided", "with", "the", "value", "of", "the", "property", "the", "name", "of", "the", "property", "and", "a", "reference", "to", "the", "whole", "object", "itself", ".", "The", "context", "to", "run", "the", "callback", "in", "can", "be", "overriden", "otherwise", "it", "is", "undefined", "." ]
792987963309c3d081b2495c15f68f23dcf617ab
https://github.com/ItsAsbreuk/itsa-jsext/blob/792987963309c3d081b2495c15f68f23dcf617ab/lib/object.js#L166-L177
54,683
ItsAsbreuk/itsa-jsext
lib/object.js
function (descriptors) { var instance = this, m = Object.create(Object.getPrototypeOf(instance)), keys = Object.getOwnPropertyNames(instance), l = keys.length, i = -1, key, propDescriptor; while (++i < l) { key = keys[i]; if (descriptors) { propDescriptor = Object.getOwnPropertyDescriptor(instance, key); if (!propDescriptor.writable) { m[key] = instance[key]; } else { Object.defineProperty(m, key, propDescriptor); } } else { m[key] = instance[key]; } } return m; }
javascript
function (descriptors) { var instance = this, m = Object.create(Object.getPrototypeOf(instance)), keys = Object.getOwnPropertyNames(instance), l = keys.length, i = -1, key, propDescriptor; while (++i < l) { key = keys[i]; if (descriptors) { propDescriptor = Object.getOwnPropertyDescriptor(instance, key); if (!propDescriptor.writable) { m[key] = instance[key]; } else { Object.defineProperty(m, key, propDescriptor); } } else { m[key] = instance[key]; } } return m; }
[ "function", "(", "descriptors", ")", "{", "var", "instance", "=", "this", ",", "m", "=", "Object", ".", "create", "(", "Object", ".", "getPrototypeOf", "(", "instance", ")", ")", ",", "keys", "=", "Object", ".", "getOwnPropertyNames", "(", "instance", ")", ",", "l", "=", "keys", ".", "length", ",", "i", "=", "-", "1", ",", "key", ",", "propDescriptor", ";", "while", "(", "++", "i", "<", "l", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "descriptors", ")", "{", "propDescriptor", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "instance", ",", "key", ")", ";", "if", "(", "!", "propDescriptor", ".", "writable", ")", "{", "m", "[", "key", "]", "=", "instance", "[", "key", "]", ";", "}", "else", "{", "Object", ".", "defineProperty", "(", "m", ",", "key", ",", "propDescriptor", ")", ";", "}", "}", "else", "{", "m", "[", "key", "]", "=", "instance", "[", "key", "]", ";", "}", "}", "return", "m", ";", "}" ]
Returns a shallow copy of the object. It does not clone objects within the object, it does a simple, shallow clone. Fast, mostly useful for plain hash maps. @method itsa_shallowClone @param [options.descriptors=false] {Boolean} If true, the full descriptors will be set. This takes more time, but avoids any info to be lost. @return {Object} shallow copy of the original
[ "Returns", "a", "shallow", "copy", "of", "the", "object", ".", "It", "does", "not", "clone", "objects", "within", "the", "object", "it", "does", "a", "simple", "shallow", "clone", ".", "Fast", "mostly", "useful", "for", "plain", "hash", "maps", "." ]
792987963309c3d081b2495c15f68f23dcf617ab
https://github.com/ItsAsbreuk/itsa-jsext/blob/792987963309c3d081b2495c15f68f23dcf617ab/lib/object.js#L314-L337
54,684
ItsAsbreuk/itsa-jsext
lib/object.js
function(refObj) { var instance = this, keys = Object.getOwnPropertyNames(instance), l = keys.length, i = -1, same, key; same = (l===refObj.itsa_size(true)); // loop through the members: while (same && (++i < l)) { key = keys[i]; same = refObj.hasOwnProperty(key) ? valuesAreTheSame(instance[key], refObj[key]) : false; } return same; }
javascript
function(refObj) { var instance = this, keys = Object.getOwnPropertyNames(instance), l = keys.length, i = -1, same, key; same = (l===refObj.itsa_size(true)); // loop through the members: while (same && (++i < l)) { key = keys[i]; same = refObj.hasOwnProperty(key) ? valuesAreTheSame(instance[key], refObj[key]) : false; } return same; }
[ "function", "(", "refObj", ")", "{", "var", "instance", "=", "this", ",", "keys", "=", "Object", ".", "getOwnPropertyNames", "(", "instance", ")", ",", "l", "=", "keys", ".", "length", ",", "i", "=", "-", "1", ",", "same", ",", "key", ";", "same", "=", "(", "l", "===", "refObj", ".", "itsa_size", "(", "true", ")", ")", ";", "// loop through the members:", "while", "(", "same", "&&", "(", "++", "i", "<", "l", ")", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "same", "=", "refObj", ".", "hasOwnProperty", "(", "key", ")", "?", "valuesAreTheSame", "(", "instance", "[", "key", "]", ",", "refObj", "[", "key", "]", ")", ":", "false", ";", "}", "return", "same", ";", "}" ]
Compares this object with the reference-object whether they have the same value. Not by reference, but their content as simple types. Compares both JSON.stringify objects @method itsa_sameValue @param refObj {Object} the object to compare with @return {Boolean} whether both objects have the same value
[ "Compares", "this", "object", "with", "the", "reference", "-", "object", "whether", "they", "have", "the", "same", "value", ".", "Not", "by", "reference", "but", "their", "content", "as", "simple", "types", "." ]
792987963309c3d081b2495c15f68f23dcf617ab
https://github.com/ItsAsbreuk/itsa-jsext/blob/792987963309c3d081b2495c15f68f23dcf617ab/lib/object.js#L349-L362
54,685
ItsAsbreuk/itsa-jsext
lib/object.js
function (obj, options) { var instance = this, i = -1, deepForce, keys, l, key, force, replace, descriptors, propDescriptor; if (!Object.itsa_isObject(obj)) { return instance; } options || (options={}); keys = options.full ? Object.getOwnPropertyNames(obj) : Object.keys(obj); l = keys.length; force = options.force; deepForce = (force==="deep"); replace = options.replace; descriptors = options.descriptors; // we cannot use obj.each --> obj might be an object defined through Object.create(null) and missing Object.prototype! while (++i < l) { key = keys[i]; if ((force && !replace) || (!replace && !(key in instance)) || (replace && (key in instance))) { if (deepForce && Object.itsa_isObject(instance[key]) && Object.itsa_isObject(obj[key])) { instance[key].itsa_merge(obj[key], options); } else { if (descriptors) { propDescriptor = Object.getOwnPropertyDescriptor(obj, key); if (!propDescriptor.writable) { instance[key] = obj[key]; } else { Object.defineProperty(instance, key, propDescriptor); } } else { instance[key] = obj[key]; } } } } return instance; }
javascript
function (obj, options) { var instance = this, i = -1, deepForce, keys, l, key, force, replace, descriptors, propDescriptor; if (!Object.itsa_isObject(obj)) { return instance; } options || (options={}); keys = options.full ? Object.getOwnPropertyNames(obj) : Object.keys(obj); l = keys.length; force = options.force; deepForce = (force==="deep"); replace = options.replace; descriptors = options.descriptors; // we cannot use obj.each --> obj might be an object defined through Object.create(null) and missing Object.prototype! while (++i < l) { key = keys[i]; if ((force && !replace) || (!replace && !(key in instance)) || (replace && (key in instance))) { if (deepForce && Object.itsa_isObject(instance[key]) && Object.itsa_isObject(obj[key])) { instance[key].itsa_merge(obj[key], options); } else { if (descriptors) { propDescriptor = Object.getOwnPropertyDescriptor(obj, key); if (!propDescriptor.writable) { instance[key] = obj[key]; } else { Object.defineProperty(instance, key, propDescriptor); } } else { instance[key] = obj[key]; } } } } return instance; }
[ "function", "(", "obj", ",", "options", ")", "{", "var", "instance", "=", "this", ",", "i", "=", "-", "1", ",", "deepForce", ",", "keys", ",", "l", ",", "key", ",", "force", ",", "replace", ",", "descriptors", ",", "propDescriptor", ";", "if", "(", "!", "Object", ".", "itsa_isObject", "(", "obj", ")", ")", "{", "return", "instance", ";", "}", "options", "||", "(", "options", "=", "{", "}", ")", ";", "keys", "=", "options", ".", "full", "?", "Object", ".", "getOwnPropertyNames", "(", "obj", ")", ":", "Object", ".", "keys", "(", "obj", ")", ";", "l", "=", "keys", ".", "length", ";", "force", "=", "options", ".", "force", ";", "deepForce", "=", "(", "force", "===", "\"deep\"", ")", ";", "replace", "=", "options", ".", "replace", ";", "descriptors", "=", "options", ".", "descriptors", ";", "// we cannot use obj.each --> obj might be an object defined through Object.create(null) and missing Object.prototype!", "while", "(", "++", "i", "<", "l", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "(", "force", "&&", "!", "replace", ")", "||", "(", "!", "replace", "&&", "!", "(", "key", "in", "instance", ")", ")", "||", "(", "replace", "&&", "(", "key", "in", "instance", ")", ")", ")", "{", "if", "(", "deepForce", "&&", "Object", ".", "itsa_isObject", "(", "instance", "[", "key", "]", ")", "&&", "Object", ".", "itsa_isObject", "(", "obj", "[", "key", "]", ")", ")", "{", "instance", "[", "key", "]", ".", "itsa_merge", "(", "obj", "[", "key", "]", ",", "options", ")", ";", "}", "else", "{", "if", "(", "descriptors", ")", "{", "propDescriptor", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "obj", ",", "key", ")", ";", "if", "(", "!", "propDescriptor", ".", "writable", ")", "{", "instance", "[", "key", "]", "=", "obj", "[", "key", "]", ";", "}", "else", "{", "Object", ".", "defineProperty", "(", "instance", ",", "key", ",", "propDescriptor", ")", ";", "}", "}", "else", "{", "instance", "[", "key", "]", "=", "obj", "[", "key", "]", ";", "}", "}", "}", "}", "return", "instance", ";", "}" ]
Merges into this object the properties of the given object. If the second argument is true, the properties on the source object will be overwritten by those of the second object of the same name, otherwise, they are preserved. @method itsa_merge @param obj {Object} Object with the properties to be added to the original object @param [options] {Object} @param [options.force=false] {Boolean|'deep'} true ==> the properties in `obj` will override those of the same name in the original object false ==> the properties in `obj` will NOT be set if the name already exists in the original object 'deep' ==> the properties in `obj` will completely be deep-merged with the original object: both deep-proerties will endure. When both `obj` and the original object have the same `simple-type`-property, the `obj` its proerty will be used @param [options.full=false] {Boolean} If true, also any non-enumerable properties will be merged @param [options.replace=false] {Boolean} If true, only properties that already exist on the instance will be merged (forced replaced). No need to set force as well. @param [options.descriptors=false] {Boolean} If true, the full descriptors will be set. This takes more time, but avoids any info to be lost. @chainable
[ "Merges", "into", "this", "object", "the", "properties", "of", "the", "given", "object", ".", "If", "the", "second", "argument", "is", "true", "the", "properties", "on", "the", "source", "object", "will", "be", "overwritten", "by", "those", "of", "the", "second", "object", "of", "the", "same", "name", "otherwise", "they", "are", "preserved", "." ]
792987963309c3d081b2495c15f68f23dcf617ab
https://github.com/ItsAsbreuk/itsa-jsext/blob/792987963309c3d081b2495c15f68f23dcf617ab/lib/object.js#L421-L459
54,686
ItsAsbreuk/itsa-jsext
lib/object.js
function(obj, clone) { var thisObj = this; thisObj.itsa_emptyObject(); if (clone) { deepCloneObj(obj, thisObj, true); } else { thisObj.itsa_merge(obj); } return thisObj; }
javascript
function(obj, clone) { var thisObj = this; thisObj.itsa_emptyObject(); if (clone) { deepCloneObj(obj, thisObj, true); } else { thisObj.itsa_merge(obj); } return thisObj; }
[ "function", "(", "obj", ",", "clone", ")", "{", "var", "thisObj", "=", "this", ";", "thisObj", ".", "itsa_emptyObject", "(", ")", ";", "if", "(", "clone", ")", "{", "deepCloneObj", "(", "obj", ",", "thisObj", ",", "true", ")", ";", "}", "else", "{", "thisObj", ".", "itsa_merge", "(", "obj", ")", ";", "}", "return", "thisObj", ";", "}" ]
Sets the properties of `obj` to the instance. This will redefine the object, while remaining the instance. This way, external references to the object-instance remain valid. @method itsa_defineData @param obj {Object} the Object that holds the new properties. @param [clone=false] {Boolean} whether the properties should be cloned @chainable
[ "Sets", "the", "properties", "of", "obj", "to", "the", "instance", ".", "This", "will", "redefine", "the", "object", "while", "remaining", "the", "instance", ".", "This", "way", "external", "references", "to", "the", "object", "-", "instance", "remain", "valid", "." ]
792987963309c3d081b2495c15f68f23dcf617ab
https://github.com/ItsAsbreuk/itsa-jsext/blob/792987963309c3d081b2495c15f68f23dcf617ab/lib/object.js#L470-L480
54,687
mikehedman/ampersand-hoodie-mixin
ampersand-hoodie-mixin.js
function (method, model, options) { options = options ? _.clone(options) : {}; var jsonPayload; var promise; // Ensure that we have a hoodie object type. if (!model.HOODIE_TYPE) { throw new Error('A HOODIE_TYPE property must be specified'); } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { jsonPayload = options.attrs || model.toJSON(options) || options.data; } switch(method) { case 'read': if (options && options.id) { promise = window.hoodie.store.find(model.HOODIE_TYPE, options.id); } else { promise = window.hoodie.store.findAll(model.HOODIE_TYPE); } break; case 'create': if (!jsonPayload) { throw new Error('Trying to add a model, but no data provided'); } else { promise = window.hoodie.store.add(model.HOODIE_TYPE, jsonPayload, options.silent); } break; case 'update': case 'patch': if (! jsonPayload) { throw new Error('Trying to update a model, but no data provided'); } else if (!model.id) { throw new Error('Cannot update model - no id provided'); } else { promise = window.hoodie.store.update(model.HOODIE_TYPE, model.id, jsonPayload, options.silent); } break; case 'delete': if (!model.id) { throw new Error('Cannot delete model - no id provided'); } else { promise = window.hoodie.store.remove(model.HOODIE_TYPE, model.id, options.silent); } break; default: throw new Error('Undefined hoodie method requested: ' + methodMap[method] + ' original: ' + method); break } promise.done(function(body) { if (options.success) return options.success(body, 'success'); }); promise.fail(function(error) { if (options.error) return options.error({}, 'error', error); }); }
javascript
function (method, model, options) { options = options ? _.clone(options) : {}; var jsonPayload; var promise; // Ensure that we have a hoodie object type. if (!model.HOODIE_TYPE) { throw new Error('A HOODIE_TYPE property must be specified'); } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { jsonPayload = options.attrs || model.toJSON(options) || options.data; } switch(method) { case 'read': if (options && options.id) { promise = window.hoodie.store.find(model.HOODIE_TYPE, options.id); } else { promise = window.hoodie.store.findAll(model.HOODIE_TYPE); } break; case 'create': if (!jsonPayload) { throw new Error('Trying to add a model, but no data provided'); } else { promise = window.hoodie.store.add(model.HOODIE_TYPE, jsonPayload, options.silent); } break; case 'update': case 'patch': if (! jsonPayload) { throw new Error('Trying to update a model, but no data provided'); } else if (!model.id) { throw new Error('Cannot update model - no id provided'); } else { promise = window.hoodie.store.update(model.HOODIE_TYPE, model.id, jsonPayload, options.silent); } break; case 'delete': if (!model.id) { throw new Error('Cannot delete model - no id provided'); } else { promise = window.hoodie.store.remove(model.HOODIE_TYPE, model.id, options.silent); } break; default: throw new Error('Undefined hoodie method requested: ' + methodMap[method] + ' original: ' + method); break } promise.done(function(body) { if (options.success) return options.success(body, 'success'); }); promise.fail(function(error) { if (options.error) return options.error({}, 'error', error); }); }
[ "function", "(", "method", ",", "model", ",", "options", ")", "{", "options", "=", "options", "?", "_", ".", "clone", "(", "options", ")", ":", "{", "}", ";", "var", "jsonPayload", ";", "var", "promise", ";", "// Ensure that we have a hoodie object type.", "if", "(", "!", "model", ".", "HOODIE_TYPE", ")", "{", "throw", "new", "Error", "(", "'A HOODIE_TYPE property must be specified'", ")", ";", "}", "// Ensure that we have the appropriate request data.", "if", "(", "options", ".", "data", "==", "null", "&&", "model", "&&", "(", "method", "===", "'create'", "||", "method", "===", "'update'", "||", "method", "===", "'patch'", ")", ")", "{", "jsonPayload", "=", "options", ".", "attrs", "||", "model", ".", "toJSON", "(", "options", ")", "||", "options", ".", "data", ";", "}", "switch", "(", "method", ")", "{", "case", "'read'", ":", "if", "(", "options", "&&", "options", ".", "id", ")", "{", "promise", "=", "window", ".", "hoodie", ".", "store", ".", "find", "(", "model", ".", "HOODIE_TYPE", ",", "options", ".", "id", ")", ";", "}", "else", "{", "promise", "=", "window", ".", "hoodie", ".", "store", ".", "findAll", "(", "model", ".", "HOODIE_TYPE", ")", ";", "}", "break", ";", "case", "'create'", ":", "if", "(", "!", "jsonPayload", ")", "{", "throw", "new", "Error", "(", "'Trying to add a model, but no data provided'", ")", ";", "}", "else", "{", "promise", "=", "window", ".", "hoodie", ".", "store", ".", "add", "(", "model", ".", "HOODIE_TYPE", ",", "jsonPayload", ",", "options", ".", "silent", ")", ";", "}", "break", ";", "case", "'update'", ":", "case", "'patch'", ":", "if", "(", "!", "jsonPayload", ")", "{", "throw", "new", "Error", "(", "'Trying to update a model, but no data provided'", ")", ";", "}", "else", "if", "(", "!", "model", ".", "id", ")", "{", "throw", "new", "Error", "(", "'Cannot update model - no id provided'", ")", ";", "}", "else", "{", "promise", "=", "window", ".", "hoodie", ".", "store", ".", "update", "(", "model", ".", "HOODIE_TYPE", ",", "model", ".", "id", ",", "jsonPayload", ",", "options", ".", "silent", ")", ";", "}", "break", ";", "case", "'delete'", ":", "if", "(", "!", "model", ".", "id", ")", "{", "throw", "new", "Error", "(", "'Cannot delete model - no id provided'", ")", ";", "}", "else", "{", "promise", "=", "window", ".", "hoodie", ".", "store", ".", "remove", "(", "model", ".", "HOODIE_TYPE", ",", "model", ".", "id", ",", "options", ".", "silent", ")", ";", "}", "break", ";", "default", ":", "throw", "new", "Error", "(", "'Undefined hoodie method requested: '", "+", "methodMap", "[", "method", "]", "+", "' original: '", "+", "method", ")", ";", "break", "}", "promise", ".", "done", "(", "function", "(", "body", ")", "{", "if", "(", "options", ".", "success", ")", "return", "options", ".", "success", "(", "body", ",", "'success'", ")", ";", "}", ")", ";", "promise", ".", "fail", "(", "function", "(", "error", ")", "{", "if", "(", "options", ".", "error", ")", "return", "options", ".", "error", "(", "{", "}", ",", "'error'", ",", "error", ")", ";", "}", ")", ";", "}" ]
This sync function is a modified version of the code in ampersand-sync
[ "This", "sync", "function", "is", "a", "modified", "version", "of", "the", "code", "in", "ampersand", "-", "sync" ]
0f66961cfed776b2a20182bdef481efb49da7592
https://github.com/mikehedman/ampersand-hoodie-mixin/blob/0f66961cfed776b2a20182bdef481efb49da7592/ampersand-hoodie-mixin.js#L11-L69
54,688
fritbot/fb-opt-facts
import_facts.js
processLine
function processLine (line, callback) { var trigger = line[0]; // Required to drop the args to callback so async doesn't think we're throwing an error. function cb () { callback(); } if (trigger === 'alias') { bot.db.schemas.factTrigger.saveAlias(line[1], line[2]).then(cb); } else { bot.db.schemas.factTrigger.saveFactoid(trigger, line[1], line[2]).then(cb); } }
javascript
function processLine (line, callback) { var trigger = line[0]; // Required to drop the args to callback so async doesn't think we're throwing an error. function cb () { callback(); } if (trigger === 'alias') { bot.db.schemas.factTrigger.saveAlias(line[1], line[2]).then(cb); } else { bot.db.schemas.factTrigger.saveFactoid(trigger, line[1], line[2]).then(cb); } }
[ "function", "processLine", "(", "line", ",", "callback", ")", "{", "var", "trigger", "=", "line", "[", "0", "]", ";", "// Required to drop the args to callback so async doesn't think we're throwing an error.", "function", "cb", "(", ")", "{", "callback", "(", ")", ";", "}", "if", "(", "trigger", "===", "'alias'", ")", "{", "bot", ".", "db", ".", "schemas", ".", "factTrigger", ".", "saveAlias", "(", "line", "[", "1", "]", ",", "line", "[", "2", "]", ")", ".", "then", "(", "cb", ")", ";", "}", "else", "{", "bot", ".", "db", ".", "schemas", ".", "factTrigger", ".", "saveFactoid", "(", "trigger", ",", "line", "[", "1", "]", ",", "line", "[", "2", "]", ")", ".", "then", "(", "cb", ")", ";", "}", "}" ]
Function to process a single line. Since we need these to happen strictly in sequence, so we can get aliases matched, we need to mix Q and async.
[ "Function", "to", "process", "a", "single", "line", ".", "Since", "we", "need", "these", "to", "happen", "strictly", "in", "sequence", "so", "we", "can", "get", "aliases", "matched", "we", "need", "to", "mix", "Q", "and", "async", "." ]
3ce703c931aca344932564dd52e780fb5a259ca1
https://github.com/fritbot/fb-opt-facts/blob/3ce703c931aca344932564dd52e780fb5a259ca1/import_facts.js#L31-L44
54,689
isuttell/two-factor
lib/generate.js
randomString
function randomString(options) { var set = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'; if (options.symbols === true) { set += '!@#$%^&*()<>?/[]{},.:;'; } var key = ''; for (var i = 0; i < options.length; i++) { key += set.charAt(Math.floor(Math.random() * set.length)); } return key; }
javascript
function randomString(options) { var set = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'; if (options.symbols === true) { set += '!@#$%^&*()<>?/[]{},.:;'; } var key = ''; for (var i = 0; i < options.length; i++) { key += set.charAt(Math.floor(Math.random() * set.length)); } return key; }
[ "function", "randomString", "(", "options", ")", "{", "var", "set", "=", "'0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'", ";", "if", "(", "options", ".", "symbols", "===", "true", ")", "{", "set", "+=", "'!@#$%^&*()<>?/[]{},.:;'", ";", "}", "var", "key", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "options", ".", "length", ";", "i", "++", ")", "{", "key", "+=", "set", ".", "charAt", "(", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "set", ".", "length", ")", ")", ";", "}", "return", "key", ";", "}" ]
Creates a random string @param {Object} options @return {String}
[ "Creates", "a", "random", "string" ]
7572daa479774af1514b24d8e23738d8a8f55352
https://github.com/isuttell/two-factor/blob/7572daa479774af1514b24d8e23738d8a8f55352/lib/generate.js#L19-L32
54,690
isuttell/two-factor
lib/generate.js
otpauth
function otpauth(key, name) { var code = 'otpauth://totp/' + encodeURIComponent(name); code += '?secret=' + encodeURIComponent(key); code += '&issuer=' + encodeURIComponent('One Sony'); return code; }
javascript
function otpauth(key, name) { var code = 'otpauth://totp/' + encodeURIComponent(name); code += '?secret=' + encodeURIComponent(key); code += '&issuer=' + encodeURIComponent('One Sony'); return code; }
[ "function", "otpauth", "(", "key", ",", "name", ")", "{", "var", "code", "=", "'otpauth://totp/'", "+", "encodeURIComponent", "(", "name", ")", ";", "code", "+=", "'?secret='", "+", "encodeURIComponent", "(", "key", ")", ";", "code", "+=", "'&issuer='", "+", "encodeURIComponent", "(", "'One Sony'", ")", ";", "return", "code", ";", "}" ]
Generate link to encode in qrcode @param {String} key @param {String} name @return {String}
[ "Generate", "link", "to", "encode", "in", "qrcode" ]
7572daa479774af1514b24d8e23738d8a8f55352
https://github.com/isuttell/two-factor/blob/7572daa479774af1514b24d8e23738d8a8f55352/lib/generate.js#L41-L46
54,691
isuttell/two-factor
lib/generate.js
link
function link(key, options) { if (options.google && options.name) { return 'https://chart.googleapis.com/chart?chs=166x166&chld=L|0&cht=qr&chl=' + otpauth(key, options.name); } else { return 'https://chart.googleapis.com/chart?chs=166x166&chld=L|0&cht=qr&chl=' + encodeURIComponent(key); } }
javascript
function link(key, options) { if (options.google && options.name) { return 'https://chart.googleapis.com/chart?chs=166x166&chld=L|0&cht=qr&chl=' + otpauth(key, options.name); } else { return 'https://chart.googleapis.com/chart?chs=166x166&chld=L|0&cht=qr&chl=' + encodeURIComponent(key); } }
[ "function", "link", "(", "key", ",", "options", ")", "{", "if", "(", "options", ".", "google", "&&", "options", ".", "name", ")", "{", "return", "'https://chart.googleapis.com/chart?chs=166x166&chld=L|0&cht=qr&chl='", "+", "otpauth", "(", "key", ",", "options", ".", "name", ")", ";", "}", "else", "{", "return", "'https://chart.googleapis.com/chart?chs=166x166&chld=L|0&cht=qr&chl='", "+", "encodeURIComponent", "(", "key", ")", ";", "}", "}" ]
Create a Google charts link to a QR Code with the key embeded in it @param {String} key @param {Object} options @return {String}
[ "Create", "a", "Google", "charts", "link", "to", "a", "QR", "Code", "with", "the", "key", "embeded", "in", "it" ]
7572daa479774af1514b24d8e23738d8a8f55352
https://github.com/isuttell/two-factor/blob/7572daa479774af1514b24d8e23738d8a8f55352/lib/generate.js#L55-L61
54,692
isuttell/two-factor
lib/generate.js
qrcode
function qrcode(key, name, options) { // Options options = _.extend({ type: 'svg', sync: false }, options || {}); var link = otpauth(key, name); if (options.sync) { return qr.imageSync(link, { type: options.type, margin: 0 }); } else { return qr.image(link, { type: options.type, margin: 0 }); } }
javascript
function qrcode(key, name, options) { // Options options = _.extend({ type: 'svg', sync: false }, options || {}); var link = otpauth(key, name); if (options.sync) { return qr.imageSync(link, { type: options.type, margin: 0 }); } else { return qr.image(link, { type: options.type, margin: 0 }); } }
[ "function", "qrcode", "(", "key", ",", "name", ",", "options", ")", "{", "// Options", "options", "=", "_", ".", "extend", "(", "{", "type", ":", "'svg'", ",", "sync", ":", "false", "}", ",", "options", "||", "{", "}", ")", ";", "var", "link", "=", "otpauth", "(", "key", ",", "name", ")", ";", "if", "(", "options", ".", "sync", ")", "{", "return", "qr", ".", "imageSync", "(", "link", ",", "{", "type", ":", "options", ".", "type", ",", "margin", ":", "0", "}", ")", ";", "}", "else", "{", "return", "qr", ".", "image", "(", "link", ",", "{", "type", ":", "options", ".", "type", ",", "margin", ":", "0", "}", ")", ";", "}", "}" ]
Creates a QR Code @param {String} key @param {Name} name @param {Object} options @return {Stream}
[ "Creates", "a", "QR", "Code" ]
7572daa479774af1514b24d8e23738d8a8f55352
https://github.com/isuttell/two-factor/blob/7572daa479774af1514b24d8e23738d8a8f55352/lib/generate.js#L71-L91
54,693
isuttell/two-factor
lib/generate.js
generateKey
function generateKey(options) { // Options options = _.extend({ length: 32, name: '', symbols: false, google: false, qrCode: false, type: 'base32' }, options || {}); // Generate the random string var key = randomString(options); if (options.type === 'ascii') { return key; } else if (options.type === 'base32') { // Encode the ascii string into base32 and remove any `=` signs which google // doesn't like key = base32.encode(key).toString().replace(/=/g, ''); return key; } else { throw new Error('InvalidKeyType'); } }
javascript
function generateKey(options) { // Options options = _.extend({ length: 32, name: '', symbols: false, google: false, qrCode: false, type: 'base32' }, options || {}); // Generate the random string var key = randomString(options); if (options.type === 'ascii') { return key; } else if (options.type === 'base32') { // Encode the ascii string into base32 and remove any `=` signs which google // doesn't like key = base32.encode(key).toString().replace(/=/g, ''); return key; } else { throw new Error('InvalidKeyType'); } }
[ "function", "generateKey", "(", "options", ")", "{", "// Options", "options", "=", "_", ".", "extend", "(", "{", "length", ":", "32", ",", "name", ":", "''", ",", "symbols", ":", "false", ",", "google", ":", "false", ",", "qrCode", ":", "false", ",", "type", ":", "'base32'", "}", ",", "options", "||", "{", "}", ")", ";", "// Generate the random string", "var", "key", "=", "randomString", "(", "options", ")", ";", "if", "(", "options", ".", "type", "===", "'ascii'", ")", "{", "return", "key", ";", "}", "else", "if", "(", "options", ".", "type", "===", "'base32'", ")", "{", "// Encode the ascii string into base32 and remove any `=` signs which google", "// doesn't like", "key", "=", "base32", ".", "encode", "(", "key", ")", ".", "toString", "(", ")", ".", "replace", "(", "/", "=", "/", "g", ",", "''", ")", ";", "return", "key", ";", "}", "else", "{", "throw", "new", "Error", "(", "'InvalidKeyType'", ")", ";", "}", "}" ]
Generates a random base32 secret key and optionally a qrcode @param {Object} options @return {Object}
[ "Generates", "a", "random", "base32", "secret", "key", "and", "optionally", "a", "qrcode" ]
7572daa479774af1514b24d8e23738d8a8f55352
https://github.com/isuttell/two-factor/blob/7572daa479774af1514b24d8e23738d8a8f55352/lib/generate.js#L99-L124
54,694
mrfishie/starmap
lib/Model.js
Model
function Model(io, name, itemDef, modelDef, filter) { EventEmitter.call(this); //name = name.toLowerCase(); this.io = io; this.name = name; this.url = utils.resolveName(name); this.itemDef = itemDef || {}; this.modelDef = modelDef || {}; this.filter = filter || {}; this.children = []; this.eventHandlers = {}; this.bindings = []; this.value = publicModel(this, new Promise(function(resolve, reject) { this.on('ready', resolve()); }.bind(this))); this.on('created', this._onCreated.bind(this)); this.on('updated', this._onUpdated.bind(this)); this.on('destroyed', this._onDestroyed.bind(this)); io.socket.on(name, function(message) { this.emit(message.verb, message); }.bind(this)); this.refresh().then(function() { this.emit('ready'); }.bind(this)); }
javascript
function Model(io, name, itemDef, modelDef, filter) { EventEmitter.call(this); //name = name.toLowerCase(); this.io = io; this.name = name; this.url = utils.resolveName(name); this.itemDef = itemDef || {}; this.modelDef = modelDef || {}; this.filter = filter || {}; this.children = []; this.eventHandlers = {}; this.bindings = []; this.value = publicModel(this, new Promise(function(resolve, reject) { this.on('ready', resolve()); }.bind(this))); this.on('created', this._onCreated.bind(this)); this.on('updated', this._onUpdated.bind(this)); this.on('destroyed', this._onDestroyed.bind(this)); io.socket.on(name, function(message) { this.emit(message.verb, message); }.bind(this)); this.refresh().then(function() { this.emit('ready'); }.bind(this)); }
[ "function", "Model", "(", "io", ",", "name", ",", "itemDef", ",", "modelDef", ",", "filter", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "//name = name.toLowerCase();", "this", ".", "io", "=", "io", ";", "this", ".", "name", "=", "name", ";", "this", ".", "url", "=", "utils", ".", "resolveName", "(", "name", ")", ";", "this", ".", "itemDef", "=", "itemDef", "||", "{", "}", ";", "this", ".", "modelDef", "=", "modelDef", "||", "{", "}", ";", "this", ".", "filter", "=", "filter", "||", "{", "}", ";", "this", ".", "children", "=", "[", "]", ";", "this", ".", "eventHandlers", "=", "{", "}", ";", "this", ".", "bindings", "=", "[", "]", ";", "this", ".", "value", "=", "publicModel", "(", "this", ",", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "this", ".", "on", "(", "'ready'", ",", "resolve", "(", ")", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ")", ";", "this", ".", "on", "(", "'created'", ",", "this", ".", "_onCreated", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "on", "(", "'updated'", ",", "this", ".", "_onUpdated", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "on", "(", "'destroyed'", ",", "this", ".", "_onDestroyed", ".", "bind", "(", "this", ")", ")", ";", "io", ".", "socket", ".", "on", "(", "name", ",", "function", "(", "message", ")", "{", "this", ".", "emit", "(", "message", ".", "verb", ",", "message", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "refresh", "(", ")", ".", "then", "(", "function", "(", ")", "{", "this", ".", "emit", "(", "'ready'", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
An actual model that syncs with the server This object contains the internal model representation, and updates any objects bound to it. @param {object} io the socket.io object @param {string} name @param itemDef {object?} @param modelDef {object?} @param filter {object?} @constructor
[ "An", "actual", "model", "that", "syncs", "with", "the", "server" ]
0d2637e7863d65c165abf63766605e6a643d2580
https://github.com/mrfishie/starmap/blob/0d2637e7863d65c165abf63766605e6a643d2580/lib/Model.js#L23-L54
54,695
mongodb-js/mj
commands/create.js
function(callback) { if (Object.keys(templateDependencies).indexOf(args['<template>']) === -1) { return callback(new Error(format('Unknown template "%s". Run ' + '`mj help create` for list of valid templates.', args['<template>']))); } return callback(null); }
javascript
function(callback) { if (Object.keys(templateDependencies).indexOf(args['<template>']) === -1) { return callback(new Error(format('Unknown template "%s". Run ' + '`mj help create` for list of valid templates.', args['<template>']))); } return callback(null); }
[ "function", "(", "callback", ")", "{", "if", "(", "Object", ".", "keys", "(", "templateDependencies", ")", ".", "indexOf", "(", "args", "[", "'<template>'", "]", ")", "===", "-", "1", ")", "{", "return", "callback", "(", "new", "Error", "(", "format", "(", "'Unknown template \"%s\". Run '", "+", "'`mj help create` for list of valid templates.'", ",", "args", "[", "'<template>'", "]", ")", ")", ")", ";", "}", "return", "callback", "(", "null", ")", ";", "}" ]
make sure the template exists.
[ "make", "sure", "the", "template", "exists", "." ]
a643970372c74baf8cfc7087cda80d3f6001fe7b
https://github.com/mongodb-js/mj/blob/a643970372c74baf8cfc7087cda80d3f6001fe7b/commands/create.js#L28-L34
54,696
mongodb-js/mj
commands/create.js
function(callback) { fs.readdir(args['<directory>'], function(err, files) { // error here means it does not exist, which is good. if (err || args['--force']) { return callback(null, args['<directory>']); } if (files.length > 0) { return callback(new Error(format('destination ' + 'directory %s is not empty.', path.resolve(args['<directory>'])))); } return callback(null, args['<directory>']); }); }
javascript
function(callback) { fs.readdir(args['<directory>'], function(err, files) { // error here means it does not exist, which is good. if (err || args['--force']) { return callback(null, args['<directory>']); } if (files.length > 0) { return callback(new Error(format('destination ' + 'directory %s is not empty.', path.resolve(args['<directory>'])))); } return callback(null, args['<directory>']); }); }
[ "function", "(", "callback", ")", "{", "fs", ".", "readdir", "(", "args", "[", "'<directory>'", "]", ",", "function", "(", "err", ",", "files", ")", "{", "// error here means it does not exist, which is good.", "if", "(", "err", "||", "args", "[", "'--force'", "]", ")", "{", "return", "callback", "(", "null", ",", "args", "[", "'<directory>'", "]", ")", ";", "}", "if", "(", "files", ".", "length", ">", "0", ")", "{", "return", "callback", "(", "new", "Error", "(", "format", "(", "'destination '", "+", "'directory %s is not empty.'", ",", "path", ".", "resolve", "(", "args", "[", "'<directory>'", "]", ")", ")", ")", ")", ";", "}", "return", "callback", "(", "null", ",", "args", "[", "'<directory>'", "]", ")", ";", "}", ")", ";", "}" ]
before copying, make sure the target directory is empty or does not exist.
[ "before", "copying", "make", "sure", "the", "target", "directory", "is", "empty", "or", "does", "not", "exist", "." ]
a643970372c74baf8cfc7087cda80d3f6001fe7b
https://github.com/mongodb-js/mj/blob/a643970372c74baf8cfc7087cda80d3f6001fe7b/commands/create.js#L36-L48
54,697
mongodb-js/mj
commands/create.js
function(template, parent) { var templateLocation; if (templateNameToRepo[template].startsWith('file://')) { templateLocation = templateNameToRepo[template].slice(7); } else { templateLocation = path.join(path.homedir(), '.khaos', 'templates', template); } return function(callback, results) { var processTemplate = function(location, cb) { var khaos = new Khaos(path.join(templateLocation, 'template')); khaos.read(function(err, files) { if (err) return cb(err); khaos.parse(files, function(err2, schema) { if (err2) return cb(err2); // only prompt for new variables var newVars = _.omit(schema, _.keys(results[parent] || args.answers)); khaos.prompt(newVars, function(err3, answers) { if (err3) return cb(err3); // merge new answers with existing ones and pass to next template answers = _.merge(answers, results[parent] || args.answers || {}); khaos.write(results.destination, files, answers, function(err4) { cb(err4, answers); }); }); }); }); }; // download from github if not yet locally cached if (!exists(templateLocation)) { download(templateNameToRepo[template], templateLocation, function(err) { if (err) return callback(err); processTemplate(templateLocation, callback); }); } else { processTemplate(templateLocation, callback); } }; }
javascript
function(template, parent) { var templateLocation; if (templateNameToRepo[template].startsWith('file://')) { templateLocation = templateNameToRepo[template].slice(7); } else { templateLocation = path.join(path.homedir(), '.khaos', 'templates', template); } return function(callback, results) { var processTemplate = function(location, cb) { var khaos = new Khaos(path.join(templateLocation, 'template')); khaos.read(function(err, files) { if (err) return cb(err); khaos.parse(files, function(err2, schema) { if (err2) return cb(err2); // only prompt for new variables var newVars = _.omit(schema, _.keys(results[parent] || args.answers)); khaos.prompt(newVars, function(err3, answers) { if (err3) return cb(err3); // merge new answers with existing ones and pass to next template answers = _.merge(answers, results[parent] || args.answers || {}); khaos.write(results.destination, files, answers, function(err4) { cb(err4, answers); }); }); }); }); }; // download from github if not yet locally cached if (!exists(templateLocation)) { download(templateNameToRepo[template], templateLocation, function(err) { if (err) return callback(err); processTemplate(templateLocation, callback); }); } else { processTemplate(templateLocation, callback); } }; }
[ "function", "(", "template", ",", "parent", ")", "{", "var", "templateLocation", ";", "if", "(", "templateNameToRepo", "[", "template", "]", ".", "startsWith", "(", "'file://'", ")", ")", "{", "templateLocation", "=", "templateNameToRepo", "[", "template", "]", ".", "slice", "(", "7", ")", ";", "}", "else", "{", "templateLocation", "=", "path", ".", "join", "(", "path", ".", "homedir", "(", ")", ",", "'.khaos'", ",", "'templates'", ",", "template", ")", ";", "}", "return", "function", "(", "callback", ",", "results", ")", "{", "var", "processTemplate", "=", "function", "(", "location", ",", "cb", ")", "{", "var", "khaos", "=", "new", "Khaos", "(", "path", ".", "join", "(", "templateLocation", ",", "'template'", ")", ")", ";", "khaos", ".", "read", "(", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "khaos", ".", "parse", "(", "files", ",", "function", "(", "err2", ",", "schema", ")", "{", "if", "(", "err2", ")", "return", "cb", "(", "err2", ")", ";", "// only prompt for new variables", "var", "newVars", "=", "_", ".", "omit", "(", "schema", ",", "_", ".", "keys", "(", "results", "[", "parent", "]", "||", "args", ".", "answers", ")", ")", ";", "khaos", ".", "prompt", "(", "newVars", ",", "function", "(", "err3", ",", "answers", ")", "{", "if", "(", "err3", ")", "return", "cb", "(", "err3", ")", ";", "// merge new answers with existing ones and pass to next template", "answers", "=", "_", ".", "merge", "(", "answers", ",", "results", "[", "parent", "]", "||", "args", ".", "answers", "||", "{", "}", ")", ";", "khaos", ".", "write", "(", "results", ".", "destination", ",", "files", ",", "answers", ",", "function", "(", "err4", ")", "{", "cb", "(", "err4", ",", "answers", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "// download from github if not yet locally cached", "if", "(", "!", "exists", "(", "templateLocation", ")", ")", "{", "download", "(", "templateNameToRepo", "[", "template", "]", ",", "templateLocation", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "processTemplate", "(", "templateLocation", ",", "callback", ")", ";", "}", ")", ";", "}", "else", "{", "processTemplate", "(", "templateLocation", ",", "callback", ")", ";", "}", "}", ";", "}" ]
add khaos tasks for each template in the dependency tree
[ "add", "khaos", "tasks", "for", "each", "template", "in", "the", "dependency", "tree" ]
a643970372c74baf8cfc7087cda80d3f6001fe7b
https://github.com/mongodb-js/mj/blob/a643970372c74baf8cfc7087cda80d3f6001fe7b/commands/create.js#L92-L132
54,698
bredele/lineup-stream
index.js
insert
function insert(arr, index, values) { [].splice.apply(arr, [index, 0].concat(values)); }
javascript
function insert(arr, index, values) { [].splice.apply(arr, [index, 0].concat(values)); }
[ "function", "insert", "(", "arr", ",", "index", ",", "values", ")", "{", "[", "]", ".", "splice", ".", "apply", "(", "arr", ",", "[", "index", ",", "0", "]", ".", "concat", "(", "values", ")", ")", ";", "}" ]
Insert array into an other array. @param {Array} @param {Number} index @param {Any} values @api private
[ "Insert", "array", "into", "an", "other", "array", "." ]
006ee9b5a5461edc18da6f4e974376d1f9059ce1
https://github.com/bredele/lineup-stream/blob/006ee9b5a5461edc18da6f4e974376d1f9059ce1/index.js#L58-L60
54,699
RnbWd/parse-browserify
lib/query.js
function(objectId, options) { var self = this; self.equalTo('objectId', objectId); var firstOptions = {}; if (options && _.has(options, 'useMasterKey')) { firstOptions = { useMasterKey: options.useMasterKey }; } return self.first(firstOptions).then(function(response) { if (response) { return response; } var errorObject = new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, "Object not found."); return Parse.Promise.error(errorObject); })._thenRunCallbacks(options, null); }
javascript
function(objectId, options) { var self = this; self.equalTo('objectId', objectId); var firstOptions = {}; if (options && _.has(options, 'useMasterKey')) { firstOptions = { useMasterKey: options.useMasterKey }; } return self.first(firstOptions).then(function(response) { if (response) { return response; } var errorObject = new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, "Object not found."); return Parse.Promise.error(errorObject); })._thenRunCallbacks(options, null); }
[ "function", "(", "objectId", ",", "options", ")", "{", "var", "self", "=", "this", ";", "self", ".", "equalTo", "(", "'objectId'", ",", "objectId", ")", ";", "var", "firstOptions", "=", "{", "}", ";", "if", "(", "options", "&&", "_", ".", "has", "(", "options", ",", "'useMasterKey'", ")", ")", "{", "firstOptions", "=", "{", "useMasterKey", ":", "options", ".", "useMasterKey", "}", ";", "}", "return", "self", ".", "first", "(", "firstOptions", ")", ".", "then", "(", "function", "(", "response", ")", "{", "if", "(", "response", ")", "{", "return", "response", ";", "}", "var", "errorObject", "=", "new", "Parse", ".", "Error", "(", "Parse", ".", "Error", ".", "OBJECT_NOT_FOUND", ",", "\"Object not found.\"", ")", ";", "return", "Parse", ".", "Promise", ".", "error", "(", "errorObject", ")", ";", "}", ")", ".", "_thenRunCallbacks", "(", "options", ",", "null", ")", ";", "}" ]
Constructs a Parse.Object whose id is already known by fetching data from the server. Either options.success or options.error is called when the find completes. @param {String} objectId The id of the object to be fetched. @param {Object} options A Backbone-style options object. Valid options are:<ul> <li>success: A Backbone-style success callback <li>error: An Backbone-style error callback. <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to be used for this request. </ul>
[ "Constructs", "a", "Parse", ".", "Object", "whose", "id", "is", "already", "known", "by", "fetching", "data", "from", "the", "server", ".", "Either", "options", ".", "success", "or", "options", ".", "error", "is", "called", "when", "the", "find", "completes", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/query.js#L120-L139