id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
44,800
Kawba/MoLIR
molir.js
returnRankedIntents
function returnRankedIntents(input, intents) { return new Promise((resolve, reject) => { let lowerCase = input.toLowerCase(); let totalScore = 0; //loop through all loaded intents intents.forEach((intent) => { intent.score = 0; intent.utterences.forEach((utterence) => { let words = utterence.toLowerCase().split(" "); let utterenceMatch = 0; let ppw = 100 / words.length; //how many words in input match intent samples words.forEach((word) => { if (lowerCase.includes(word)) { utterenceMatch = utterenceMatch + ppw; } }); if (intent.score < utterenceMatch) { intent.score = utterenceMatch } }); //each intent keyword in the input multiplies the intent score by 2 intent.keywords.forEach((keyword) => { if (input.includes(keyword.toLowerCase())) { intent.score = intent.score * 2 } }); //add intent score to totalscore totalScore = totalScore + intent.score; }); //work out confident by deviding each intents score by the total intents.forEach((intent) => { intent.confidence = intent.score / totalScore }); //Sort intents let sorted = intents.sort((a, b) => { return b.confidence - a.confidence }); //sent back the classified intents resolve(sorted); } ) }
javascript
function returnRankedIntents(input, intents) { return new Promise((resolve, reject) => { let lowerCase = input.toLowerCase(); let totalScore = 0; //loop through all loaded intents intents.forEach((intent) => { intent.score = 0; intent.utterences.forEach((utterence) => { let words = utterence.toLowerCase().split(" "); let utterenceMatch = 0; let ppw = 100 / words.length; //how many words in input match intent samples words.forEach((word) => { if (lowerCase.includes(word)) { utterenceMatch = utterenceMatch + ppw; } }); if (intent.score < utterenceMatch) { intent.score = utterenceMatch } }); //each intent keyword in the input multiplies the intent score by 2 intent.keywords.forEach((keyword) => { if (input.includes(keyword.toLowerCase())) { intent.score = intent.score * 2 } }); //add intent score to totalscore totalScore = totalScore + intent.score; }); //work out confident by deviding each intents score by the total intents.forEach((intent) => { intent.confidence = intent.score / totalScore }); //Sort intents let sorted = intents.sort((a, b) => { return b.confidence - a.confidence }); //sent back the classified intents resolve(sorted); } ) }
[ "function", "returnRankedIntents", "(", "input", ",", "intents", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "lowerCase", "=", "input", ".", "toLowerCase", "(", ")", ";", "let", "totalScore", "=", "0", ";", "//loop through all loaded intents", "intents", ".", "forEach", "(", "(", "intent", ")", "=>", "{", "intent", ".", "score", "=", "0", ";", "intent", ".", "utterences", ".", "forEach", "(", "(", "utterence", ")", "=>", "{", "let", "words", "=", "utterence", ".", "toLowerCase", "(", ")", ".", "split", "(", "\" \"", ")", ";", "let", "utterenceMatch", "=", "0", ";", "let", "ppw", "=", "100", "/", "words", ".", "length", ";", "//how many words in input match intent samples", "words", ".", "forEach", "(", "(", "word", ")", "=>", "{", "if", "(", "lowerCase", ".", "includes", "(", "word", ")", ")", "{", "utterenceMatch", "=", "utterenceMatch", "+", "ppw", ";", "}", "}", ")", ";", "if", "(", "intent", ".", "score", "<", "utterenceMatch", ")", "{", "intent", ".", "score", "=", "utterenceMatch", "}", "}", ")", ";", "//each intent keyword in the input multiplies the intent score by 2", "intent", ".", "keywords", ".", "forEach", "(", "(", "keyword", ")", "=>", "{", "if", "(", "input", ".", "includes", "(", "keyword", ".", "toLowerCase", "(", ")", ")", ")", "{", "intent", ".", "score", "=", "intent", ".", "score", "*", "2", "}", "}", ")", ";", "//add intent score to totalscore", "totalScore", "=", "totalScore", "+", "intent", ".", "score", ";", "}", ")", ";", "//work out confident by deviding each intents score by the total", "intents", ".", "forEach", "(", "(", "intent", ")", "=>", "{", "intent", ".", "confidence", "=", "intent", ".", "score", "/", "totalScore", "}", ")", ";", "//Sort intents", "let", "sorted", "=", "intents", ".", "sort", "(", "(", "a", ",", "b", ")", "=>", "{", "return", "b", ".", "confidence", "-", "a", ".", "confidence", "}", ")", ";", "//sent back the classified intents", "resolve", "(", "sorted", ")", ";", "}", ")", "}" ]
Function to classify input based on loaded intents
[ "Function", "to", "classify", "input", "based", "on", "loaded", "intents" ]
f235a565854e6d20ad8fc064022434b0d6a6718e
https://github.com/Kawba/MoLIR/blob/f235a565854e6d20ad8fc064022434b0d6a6718e/molir.js#L37-L91
44,801
bonesoul/node-hpool-web
public/js/plugins/iCheck/icheck.js
operate
function operate(input, direct, method) { var node = input[0], state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked, active = method == _update ? { checked: node[_checked], disabled: node[_disabled], indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false' } : node[state]; // Check, disable or indeterminate if (/^(ch|di|in)/.test(method) && !active) { on(input, state); // Uncheck, enable or determinate } else if (/^(un|en|de)/.test(method) && active) { off(input, state); // Update } else if (method == _update) { // Handle states for (var state in active) { if (active[state]) { on(input, state, true); } else { off(input, state, true); }; }; } else if (!direct || method == 'toggle') { // Helper or label was clicked if (!direct) { input[_callback]('ifClicked'); }; // Toggle checked state if (active) { if (node[_type] !== _radio) { off(input, state); }; } else { on(input, state); }; }; }
javascript
function operate(input, direct, method) { var node = input[0], state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked, active = method == _update ? { checked: node[_checked], disabled: node[_disabled], indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false' } : node[state]; // Check, disable or indeterminate if (/^(ch|di|in)/.test(method) && !active) { on(input, state); // Uncheck, enable or determinate } else if (/^(un|en|de)/.test(method) && active) { off(input, state); // Update } else if (method == _update) { // Handle states for (var state in active) { if (active[state]) { on(input, state, true); } else { off(input, state, true); }; }; } else if (!direct || method == 'toggle') { // Helper or label was clicked if (!direct) { input[_callback]('ifClicked'); }; // Toggle checked state if (active) { if (node[_type] !== _radio) { off(input, state); }; } else { on(input, state); }; }; }
[ "function", "operate", "(", "input", ",", "direct", ",", "method", ")", "{", "var", "node", "=", "input", "[", "0", "]", ",", "state", "=", "/", "er", "/", ".", "test", "(", "method", ")", "?", "_indeterminate", ":", "/", "bl", "/", ".", "test", "(", "method", ")", "?", "_disabled", ":", "_checked", ",", "active", "=", "method", "==", "_update", "?", "{", "checked", ":", "node", "[", "_checked", "]", ",", "disabled", ":", "node", "[", "_disabled", "]", ",", "indeterminate", ":", "input", ".", "attr", "(", "_indeterminate", ")", "==", "'true'", "||", "input", ".", "attr", "(", "_determinate", ")", "==", "'false'", "}", ":", "node", "[", "state", "]", ";", "// Check, disable or indeterminate", "if", "(", "/", "^(ch|di|in)", "/", ".", "test", "(", "method", ")", "&&", "!", "active", ")", "{", "on", "(", "input", ",", "state", ")", ";", "// Uncheck, enable or determinate", "}", "else", "if", "(", "/", "^(un|en|de)", "/", ".", "test", "(", "method", ")", "&&", "active", ")", "{", "off", "(", "input", ",", "state", ")", ";", "// Update", "}", "else", "if", "(", "method", "==", "_update", ")", "{", "// Handle states", "for", "(", "var", "state", "in", "active", ")", "{", "if", "(", "active", "[", "state", "]", ")", "{", "on", "(", "input", ",", "state", ",", "true", ")", ";", "}", "else", "{", "off", "(", "input", ",", "state", ",", "true", ")", ";", "}", ";", "}", ";", "}", "else", "if", "(", "!", "direct", "||", "method", "==", "'toggle'", ")", "{", "// Helper or label was clicked", "if", "(", "!", "direct", ")", "{", "input", "[", "_callback", "]", "(", "'ifClicked'", ")", ";", "}", ";", "// Toggle checked state", "if", "(", "active", ")", "{", "if", "(", "node", "[", "_type", "]", "!==", "_radio", ")", "{", "off", "(", "input", ",", "state", ")", ";", "}", ";", "}", "else", "{", "on", "(", "input", ",", "state", ")", ";", "}", ";", "}", ";", "}" ]
Do something with inputs
[ "Do", "something", "with", "inputs" ]
3d7749b2bcff8b59243939b5b3da19396c4878ff
https://github.com/bonesoul/node-hpool-web/blob/3d7749b2bcff8b59243939b5b3da19396c4878ff/public/js/plugins/iCheck/icheck.js#L309-L354
44,802
bonesoul/node-hpool-web
public/js/plugins/iCheck/icheck.js
on
function on(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, disabled = state == _disabled, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== true) { // Toggle assigned radio buttons if (!keep && state == _checked && node[_type] == _radio && node.name) { var form = input.closest('form'), inputs = 'input[name="' + node.name + '"]'; inputs = form.length ? form.find(inputs) : $(inputs); inputs.each(function() { if (this !== node && $(this).data(_iCheck)) { off($(this), state); }; }); }; // Indeterminate state if (indeterminate) { // Add indeterminate state node[state] = true; // Remove checked state if (node[_checked]) { off(input, _checked, 'force'); }; // Checked or disabled state } else { // Add checked or disabled state if (!keep) { node[state] = true; }; // Remove indeterminate state if (checked && node[_indeterminate]) { off(input, _indeterminate, false); }; }; // Trigger callbacks callbacks(input, checked, state, keep); }; // Add proper cursor if (node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'default'); }; // Add state class parent[_add](specific || option(input, state) || ''); // Set ARIA attribute disabled ? parent.attr('aria-disabled', 'true') : parent.attr('aria-checked', indeterminate ? 'mixed' : 'true'); // Remove regular state class parent[_remove](regular || option(input, callback) || ''); }
javascript
function on(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, disabled = state == _disabled, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== true) { // Toggle assigned radio buttons if (!keep && state == _checked && node[_type] == _radio && node.name) { var form = input.closest('form'), inputs = 'input[name="' + node.name + '"]'; inputs = form.length ? form.find(inputs) : $(inputs); inputs.each(function() { if (this !== node && $(this).data(_iCheck)) { off($(this), state); }; }); }; // Indeterminate state if (indeterminate) { // Add indeterminate state node[state] = true; // Remove checked state if (node[_checked]) { off(input, _checked, 'force'); }; // Checked or disabled state } else { // Add checked or disabled state if (!keep) { node[state] = true; }; // Remove indeterminate state if (checked && node[_indeterminate]) { off(input, _indeterminate, false); }; }; // Trigger callbacks callbacks(input, checked, state, keep); }; // Add proper cursor if (node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'default'); }; // Add state class parent[_add](specific || option(input, state) || ''); // Set ARIA attribute disabled ? parent.attr('aria-disabled', 'true') : parent.attr('aria-checked', indeterminate ? 'mixed' : 'true'); // Remove regular state class parent[_remove](regular || option(input, callback) || ''); }
[ "function", "on", "(", "input", ",", "state", ",", "keep", ")", "{", "var", "node", "=", "input", "[", "0", "]", ",", "parent", "=", "input", ".", "parent", "(", ")", ",", "checked", "=", "state", "==", "_checked", ",", "indeterminate", "=", "state", "==", "_indeterminate", ",", "disabled", "=", "state", "==", "_disabled", ",", "callback", "=", "indeterminate", "?", "_determinate", ":", "checked", "?", "_unchecked", ":", "'enabled'", ",", "regular", "=", "option", "(", "input", ",", "callback", "+", "capitalize", "(", "node", "[", "_type", "]", ")", ")", ",", "specific", "=", "option", "(", "input", ",", "state", "+", "capitalize", "(", "node", "[", "_type", "]", ")", ")", ";", "// Prevent unnecessary actions", "if", "(", "node", "[", "state", "]", "!==", "true", ")", "{", "// Toggle assigned radio buttons", "if", "(", "!", "keep", "&&", "state", "==", "_checked", "&&", "node", "[", "_type", "]", "==", "_radio", "&&", "node", ".", "name", ")", "{", "var", "form", "=", "input", ".", "closest", "(", "'form'", ")", ",", "inputs", "=", "'input[name=\"'", "+", "node", ".", "name", "+", "'\"]'", ";", "inputs", "=", "form", ".", "length", "?", "form", ".", "find", "(", "inputs", ")", ":", "$", "(", "inputs", ")", ";", "inputs", ".", "each", "(", "function", "(", ")", "{", "if", "(", "this", "!==", "node", "&&", "$", "(", "this", ")", ".", "data", "(", "_iCheck", ")", ")", "{", "off", "(", "$", "(", "this", ")", ",", "state", ")", ";", "}", ";", "}", ")", ";", "}", ";", "// Indeterminate state", "if", "(", "indeterminate", ")", "{", "// Add indeterminate state", "node", "[", "state", "]", "=", "true", ";", "// Remove checked state", "if", "(", "node", "[", "_checked", "]", ")", "{", "off", "(", "input", ",", "_checked", ",", "'force'", ")", ";", "}", ";", "// Checked or disabled state", "}", "else", "{", "// Add checked or disabled state", "if", "(", "!", "keep", ")", "{", "node", "[", "state", "]", "=", "true", ";", "}", ";", "// Remove indeterminate state", "if", "(", "checked", "&&", "node", "[", "_indeterminate", "]", ")", "{", "off", "(", "input", ",", "_indeterminate", ",", "false", ")", ";", "}", ";", "}", ";", "// Trigger callbacks", "callbacks", "(", "input", ",", "checked", ",", "state", ",", "keep", ")", ";", "}", ";", "// Add proper cursor", "if", "(", "node", "[", "_disabled", "]", "&&", "!", "!", "option", "(", "input", ",", "_cursor", ",", "true", ")", ")", "{", "parent", ".", "find", "(", "'.'", "+", "_iCheckHelper", ")", ".", "css", "(", "_cursor", ",", "'default'", ")", ";", "}", ";", "// Add state class", "parent", "[", "_add", "]", "(", "specific", "||", "option", "(", "input", ",", "state", ")", "||", "''", ")", ";", "// Set ARIA attribute", "disabled", "?", "parent", ".", "attr", "(", "'aria-disabled'", ",", "'true'", ")", ":", "parent", ".", "attr", "(", "'aria-checked'", ",", "indeterminate", "?", "'mixed'", ":", "'true'", ")", ";", "// Remove regular state class", "parent", "[", "_remove", "]", "(", "regular", "||", "option", "(", "input", ",", "callback", ")", "||", "''", ")", ";", "}" ]
Add checked, disabled or indeterminate state
[ "Add", "checked", "disabled", "or", "indeterminate", "state" ]
3d7749b2bcff8b59243939b5b3da19396c4878ff
https://github.com/bonesoul/node-hpool-web/blob/3d7749b2bcff8b59243939b5b3da19396c4878ff/public/js/plugins/iCheck/icheck.js#L357-L426
44,803
bonesoul/node-hpool-web
public/js/plugins/iCheck/icheck.js
off
function off(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, disabled = state == _disabled, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== false) { // Toggle state if (indeterminate || !keep || keep == 'force') { node[state] = false; }; // Trigger callbacks callbacks(input, checked, callback, keep); }; // Add proper cursor if (!node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'pointer'); }; // Remove state class parent[_remove](specific || option(input, state) || ''); // Set ARIA attribute disabled ? parent.attr('aria-disabled', 'false') : parent.attr('aria-checked', 'false'); // Add regular state class parent[_add](regular || option(input, callback) || ''); }
javascript
function off(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, disabled = state == _disabled, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== false) { // Toggle state if (indeterminate || !keep || keep == 'force') { node[state] = false; }; // Trigger callbacks callbacks(input, checked, callback, keep); }; // Add proper cursor if (!node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'pointer'); }; // Remove state class parent[_remove](specific || option(input, state) || ''); // Set ARIA attribute disabled ? parent.attr('aria-disabled', 'false') : parent.attr('aria-checked', 'false'); // Add regular state class parent[_add](regular || option(input, callback) || ''); }
[ "function", "off", "(", "input", ",", "state", ",", "keep", ")", "{", "var", "node", "=", "input", "[", "0", "]", ",", "parent", "=", "input", ".", "parent", "(", ")", ",", "checked", "=", "state", "==", "_checked", ",", "indeterminate", "=", "state", "==", "_indeterminate", ",", "disabled", "=", "state", "==", "_disabled", ",", "callback", "=", "indeterminate", "?", "_determinate", ":", "checked", "?", "_unchecked", ":", "'enabled'", ",", "regular", "=", "option", "(", "input", ",", "callback", "+", "capitalize", "(", "node", "[", "_type", "]", ")", ")", ",", "specific", "=", "option", "(", "input", ",", "state", "+", "capitalize", "(", "node", "[", "_type", "]", ")", ")", ";", "// Prevent unnecessary actions", "if", "(", "node", "[", "state", "]", "!==", "false", ")", "{", "// Toggle state", "if", "(", "indeterminate", "||", "!", "keep", "||", "keep", "==", "'force'", ")", "{", "node", "[", "state", "]", "=", "false", ";", "}", ";", "// Trigger callbacks", "callbacks", "(", "input", ",", "checked", ",", "callback", ",", "keep", ")", ";", "}", ";", "// Add proper cursor", "if", "(", "!", "node", "[", "_disabled", "]", "&&", "!", "!", "option", "(", "input", ",", "_cursor", ",", "true", ")", ")", "{", "parent", ".", "find", "(", "'.'", "+", "_iCheckHelper", ")", ".", "css", "(", "_cursor", ",", "'pointer'", ")", ";", "}", ";", "// Remove state class", "parent", "[", "_remove", "]", "(", "specific", "||", "option", "(", "input", ",", "state", ")", "||", "''", ")", ";", "// Set ARIA attribute", "disabled", "?", "parent", ".", "attr", "(", "'aria-disabled'", ",", "'false'", ")", ":", "parent", ".", "attr", "(", "'aria-checked'", ",", "'false'", ")", ";", "// Add regular state class", "parent", "[", "_add", "]", "(", "regular", "||", "option", "(", "input", ",", "callback", ")", "||", "''", ")", ";", "}" ]
Remove checked, disabled or indeterminate state
[ "Remove", "checked", "disabled", "or", "indeterminate", "state" ]
3d7749b2bcff8b59243939b5b3da19396c4878ff
https://github.com/bonesoul/node-hpool-web/blob/3d7749b2bcff8b59243939b5b3da19396c4878ff/public/js/plugins/iCheck/icheck.js#L429-L464
44,804
bonesoul/node-hpool-web
public/js/plugins/iCheck/icheck.js
tidy
function tidy(input, callback) { if (input.data(_iCheck)) { // Remove everything except input input.parent().html(input.attr('style', input.data(_iCheck).s || '')); // Callback if (callback) { input[_callback](callback); }; // Unbind events input.off('.i').unwrap(); $(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i'); }; }
javascript
function tidy(input, callback) { if (input.data(_iCheck)) { // Remove everything except input input.parent().html(input.attr('style', input.data(_iCheck).s || '')); // Callback if (callback) { input[_callback](callback); }; // Unbind events input.off('.i').unwrap(); $(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i'); }; }
[ "function", "tidy", "(", "input", ",", "callback", ")", "{", "if", "(", "input", ".", "data", "(", "_iCheck", ")", ")", "{", "// Remove everything except input", "input", ".", "parent", "(", ")", ".", "html", "(", "input", ".", "attr", "(", "'style'", ",", "input", ".", "data", "(", "_iCheck", ")", ".", "s", "||", "''", ")", ")", ";", "// Callback", "if", "(", "callback", ")", "{", "input", "[", "_callback", "]", "(", "callback", ")", ";", "}", ";", "// Unbind events", "input", ".", "off", "(", "'.i'", ")", ".", "unwrap", "(", ")", ";", "$", "(", "_label", "+", "'[for=\"'", "+", "input", "[", "0", "]", ".", "id", "+", "'\"]'", ")", ".", "add", "(", "input", ".", "closest", "(", "_label", ")", ")", ".", "off", "(", "'.i'", ")", ";", "}", ";", "}" ]
Remove all traces
[ "Remove", "all", "traces" ]
3d7749b2bcff8b59243939b5b3da19396c4878ff
https://github.com/bonesoul/node-hpool-web/blob/3d7749b2bcff8b59243939b5b3da19396c4878ff/public/js/plugins/iCheck/icheck.js#L467-L482
44,805
bonesoul/node-hpool-web
public/js/plugins/iCheck/icheck.js
option
function option(input, state, regular) { if (input.data(_iCheck)) { return input.data(_iCheck).o[state + (regular ? '' : 'Class')]; }; }
javascript
function option(input, state, regular) { if (input.data(_iCheck)) { return input.data(_iCheck).o[state + (regular ? '' : 'Class')]; }; }
[ "function", "option", "(", "input", ",", "state", ",", "regular", ")", "{", "if", "(", "input", ".", "data", "(", "_iCheck", ")", ")", "{", "return", "input", ".", "data", "(", "_iCheck", ")", ".", "o", "[", "state", "+", "(", "regular", "?", "''", ":", "'Class'", ")", "]", ";", "}", ";", "}" ]
Get some option
[ "Get", "some", "option" ]
3d7749b2bcff8b59243939b5b3da19396c4878ff
https://github.com/bonesoul/node-hpool-web/blob/3d7749b2bcff8b59243939b5b3da19396c4878ff/public/js/plugins/iCheck/icheck.js#L485-L489
44,806
onecommons/base
public/js/data.js
ajaxCallback
function ajaxCallback(data, textStatus) { //responses should be a list of successful responses //if any request failed it *may or may not* be an http-level error //depending on server-side implementation // konsole.log("datarequest", data, textStatus, 'dbdata.'+txnId, comment); if (textStatus == 'success') { data.getErrors = function() { if (this.error) return [this.error]; var errors = []; for (var i=0; i < this.length; i++) { if (this[i].error) errors.push(this[i].error); } return errors; }; data.hasErrors = function() { return this.getErrors().length > 0;} if (false !== $(elem).triggerHandler('dbdata-'+txnId, [data, request, comment])) { $(elem).trigger('dbdata', [data, request, comment]); } } else { //when textStatus != 'success', data param will be a XMLHttpRequest obj var errorObj = {"jsonrpc": "2.0", "id": null, "error": {"code": -32000, "message": data.statusText || textStatus, 'data' : data.responseText }, hasErrors: function() { return true;}, getErrors: function() { return [this.error];} }; if (false !== $(elem).triggerHandler('dbdata-'+txnId, [errorObj, request, comment])) { $(elem).trigger('dbdata', [errorObj, request, comment]); } } }
javascript
function ajaxCallback(data, textStatus) { //responses should be a list of successful responses //if any request failed it *may or may not* be an http-level error //depending on server-side implementation // konsole.log("datarequest", data, textStatus, 'dbdata.'+txnId, comment); if (textStatus == 'success') { data.getErrors = function() { if (this.error) return [this.error]; var errors = []; for (var i=0; i < this.length; i++) { if (this[i].error) errors.push(this[i].error); } return errors; }; data.hasErrors = function() { return this.getErrors().length > 0;} if (false !== $(elem).triggerHandler('dbdata-'+txnId, [data, request, comment])) { $(elem).trigger('dbdata', [data, request, comment]); } } else { //when textStatus != 'success', data param will be a XMLHttpRequest obj var errorObj = {"jsonrpc": "2.0", "id": null, "error": {"code": -32000, "message": data.statusText || textStatus, 'data' : data.responseText }, hasErrors: function() { return true;}, getErrors: function() { return [this.error];} }; if (false !== $(elem).triggerHandler('dbdata-'+txnId, [errorObj, request, comment])) { $(elem).trigger('dbdata', [errorObj, request, comment]); } } }
[ "function", "ajaxCallback", "(", "data", ",", "textStatus", ")", "{", "//responses should be a list of successful responses", "//if any request failed it *may or may not* be an http-level error", "//depending on server-side implementation", "// konsole.log(\"datarequest\", data, textStatus, 'dbdata.'+txnId, comment);", "if", "(", "textStatus", "==", "'success'", ")", "{", "data", ".", "getErrors", "=", "function", "(", ")", "{", "if", "(", "this", ".", "error", ")", "return", "[", "this", ".", "error", "]", ";", "var", "errors", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "length", ";", "i", "++", ")", "{", "if", "(", "this", "[", "i", "]", ".", "error", ")", "errors", ".", "push", "(", "this", "[", "i", "]", ".", "error", ")", ";", "}", "return", "errors", ";", "}", ";", "data", ".", "hasErrors", "=", "function", "(", ")", "{", "return", "this", ".", "getErrors", "(", ")", ".", "length", ">", "0", ";", "}", "if", "(", "false", "!==", "$", "(", "elem", ")", ".", "triggerHandler", "(", "'dbdata-'", "+", "txnId", ",", "[", "data", ",", "request", ",", "comment", "]", ")", ")", "{", "$", "(", "elem", ")", ".", "trigger", "(", "'dbdata'", ",", "[", "data", ",", "request", ",", "comment", "]", ")", ";", "}", "}", "else", "{", "//when textStatus != 'success', data param will be a XMLHttpRequest obj", "var", "errorObj", "=", "{", "\"jsonrpc\"", ":", "\"2.0\"", ",", "\"id\"", ":", "null", ",", "\"error\"", ":", "{", "\"code\"", ":", "-", "32000", ",", "\"message\"", ":", "data", ".", "statusText", "||", "textStatus", ",", "'data'", ":", "data", ".", "responseText", "}", ",", "hasErrors", ":", "function", "(", ")", "{", "return", "true", ";", "}", ",", "getErrors", ":", "function", "(", ")", "{", "return", "[", "this", ".", "error", "]", ";", "}", "}", ";", "if", "(", "false", "!==", "$", "(", "elem", ")", ".", "triggerHandler", "(", "'dbdata-'", "+", "txnId", ",", "[", "errorObj", ",", "request", ",", "comment", "]", ")", ")", "{", "$", "(", "elem", ")", ".", "trigger", "(", "'dbdata'", ",", "[", "errorObj", ",", "request", ",", "comment", "]", ")", ";", "}", "}", "}" ]
var clientErrorMsg = this.clientErrorMsg;
[ "var", "clientErrorMsg", "=", "this", ".", "clientErrorMsg", ";" ]
4f35d9f714d0367b0622a3504802363404290246
https://github.com/onecommons/base/blob/4f35d9f714d0367b0622a3504802363404290246/public/js/data.js#L188-L221
44,807
onecommons/base
public/js/data.js
function( obj ) { var accessor = this._getAccessor( obj ); var seen = {}; for( var i = 0; i < this.form.elements.length; i++) { this.serializeField( this.form.elements[i], accessor, seen); } return accessor.target; }
javascript
function( obj ) { var accessor = this._getAccessor( obj ); var seen = {}; for( var i = 0; i < this.form.elements.length; i++) { this.serializeField( this.form.elements[i], accessor, seen); } return accessor.target; }
[ "function", "(", "obj", ")", "{", "var", "accessor", "=", "this", ".", "_getAccessor", "(", "obj", ")", ";", "var", "seen", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "form", ".", "elements", ".", "length", ";", "i", "++", ")", "{", "this", ".", "serializeField", "(", "this", ".", "form", ".", "elements", "[", "i", "]", ",", "accessor", ",", "seen", ")", ";", "}", "return", "accessor", ".", "target", ";", "}" ]
set the obj with form's current values
[ "set", "the", "obj", "with", "form", "s", "current", "values" ]
4f35d9f714d0367b0622a3504802363404290246
https://github.com/onecommons/base/blob/4f35d9f714d0367b0622a3504802363404290246/public/js/data.js#L1030-L1037
44,808
onecommons/base
public/js/data.js
function( obj ) { //set form html var accessor = this._getAccessor( obj ); for( var i = 0; i < this.form.elements.length; i++) { this.deserializeField( this.form.elements[i], accessor ); } return accessor.target; }
javascript
function( obj ) { //set form html var accessor = this._getAccessor( obj ); for( var i = 0; i < this.form.elements.length; i++) { this.deserializeField( this.form.elements[i], accessor ); } return accessor.target; }
[ "function", "(", "obj", ")", "{", "//set form html", "var", "accessor", "=", "this", ".", "_getAccessor", "(", "obj", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "form", ".", "elements", ".", "length", ";", "i", "++", ")", "{", "this", ".", "deserializeField", "(", "this", ".", "form", ".", "elements", "[", "i", "]", ",", "accessor", ")", ";", "}", "return", "accessor", ".", "target", ";", "}" ]
update the form with the object
[ "update", "the", "form", "with", "the", "object" ]
4f35d9f714d0367b0622a3504802363404290246
https://github.com/onecommons/base/blob/4f35d9f714d0367b0622a3504802363404290246/public/js/data.js#L1142-L1148
44,809
onecommons/base
public/js/data.js
function( element, obj ) { var accessor = this._getAccessor( obj ); var value = accessor.get( element.name || ''); value = this._format( element.name, value, element ); if( element.type == "radio" || element.type == "checkbox" ) { element.checked = this._isSelected( element.value, value ); } else if ( element.type == "select-one" || element.type == "select-multiple" ) { for( var j = 0; j < element.options.length; j++ ) { element.options[j].selected = this._isSelected( element.options[j].value, value ); } } else { element.value = value || ""; // reset defaultValue if we only want to serialize changed fields if (this.changedOnly) { element.defaultValue = value; } } }
javascript
function( element, obj ) { var accessor = this._getAccessor( obj ); var value = accessor.get( element.name || ''); value = this._format( element.name, value, element ); if( element.type == "radio" || element.type == "checkbox" ) { element.checked = this._isSelected( element.value, value ); } else if ( element.type == "select-one" || element.type == "select-multiple" ) { for( var j = 0; j < element.options.length; j++ ) { element.options[j].selected = this._isSelected( element.options[j].value, value ); } } else { element.value = value || ""; // reset defaultValue if we only want to serialize changed fields if (this.changedOnly) { element.defaultValue = value; } } }
[ "function", "(", "element", ",", "obj", ")", "{", "var", "accessor", "=", "this", ".", "_getAccessor", "(", "obj", ")", ";", "var", "value", "=", "accessor", ".", "get", "(", "element", ".", "name", "||", "''", ")", ";", "value", "=", "this", ".", "_format", "(", "element", ".", "name", ",", "value", ",", "element", ")", ";", "if", "(", "element", ".", "type", "==", "\"radio\"", "||", "element", ".", "type", "==", "\"checkbox\"", ")", "{", "element", ".", "checked", "=", "this", ".", "_isSelected", "(", "element", ".", "value", ",", "value", ")", ";", "}", "else", "if", "(", "element", ".", "type", "==", "\"select-one\"", "||", "element", ".", "type", "==", "\"select-multiple\"", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "element", ".", "options", ".", "length", ";", "j", "++", ")", "{", "element", ".", "options", "[", "j", "]", ".", "selected", "=", "this", ".", "_isSelected", "(", "element", ".", "options", "[", "j", "]", ".", "value", ",", "value", ")", ";", "}", "}", "else", "{", "element", ".", "value", "=", "value", "||", "\"\"", ";", "// reset defaultValue if we only want to serialize changed fields", "if", "(", "this", ".", "changedOnly", ")", "{", "element", ".", "defaultValue", "=", "value", ";", "}", "}", "}" ]
update the form field with the property value
[ "update", "the", "form", "field", "with", "the", "property", "value" ]
4f35d9f714d0367b0622a3504802363404290246
https://github.com/onecommons/base/blob/4f35d9f714d0367b0622a3504802363404290246/public/js/data.js#L1151-L1168
44,810
feedhenry/fh-mbaas-client
lib/app/appforms/submissions.js
uploadSubmissionFile
function uploadSubmissionFile(params, cb) { var resourcePath = config.addURIParams("/appforms/submissions/:id/fields/:fieldId/files/:fileId", params); var method = "POST"; var data = params.fileDetails; params.resourcePath = resourcePath; params.method = method; params.data = data; //Flagging This Request As A File Request params.fileRequest = true; params.fileUploadRequest = true; mbaasRequest.app(params, cb); }
javascript
function uploadSubmissionFile(params, cb) { var resourcePath = config.addURIParams("/appforms/submissions/:id/fields/:fieldId/files/:fileId", params); var method = "POST"; var data = params.fileDetails; params.resourcePath = resourcePath; params.method = method; params.data = data; //Flagging This Request As A File Request params.fileRequest = true; params.fileUploadRequest = true; mbaasRequest.app(params, cb); }
[ "function", "uploadSubmissionFile", "(", "params", ",", "cb", ")", "{", "var", "resourcePath", "=", "config", ".", "addURIParams", "(", "\"/appforms/submissions/:id/fields/:fieldId/files/:fileId\"", ",", "params", ")", ";", "var", "method", "=", "\"POST\"", ";", "var", "data", "=", "params", ".", "fileDetails", ";", "params", ".", "resourcePath", "=", "resourcePath", ";", "params", ".", "method", "=", "method", ";", "params", ".", "data", "=", "data", ";", "//Flagging This Request As A File Request", "params", ".", "fileRequest", "=", "true", ";", "params", ".", "fileUploadRequest", "=", "true", ";", "mbaasRequest", ".", "app", "(", "params", ",", "cb", ")", ";", "}" ]
Upload A File Associated With A Submission
[ "Upload", "A", "File", "Associated", "With", "A", "Submission" ]
2d5a9cbb32e1b2464d71ffa18513358fea388859
https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/app/appforms/submissions.js#L38-L52
44,811
feedhenry/fh-mbaas-client
lib/app/appforms/submissions.js
getSubmissionStatus
function getSubmissionStatus(params, cb) { var resourcePath = config.addURIParams("/appforms/submissions/:id/status", params); var method = "GET"; var data = {}; params.resourcePath = resourcePath; params.method = method; params.data = data; //Flagging This Request As A File Request params.fileRequest = true; mbaasRequest.app(params, cb); }
javascript
function getSubmissionStatus(params, cb) { var resourcePath = config.addURIParams("/appforms/submissions/:id/status", params); var method = "GET"; var data = {}; params.resourcePath = resourcePath; params.method = method; params.data = data; //Flagging This Request As A File Request params.fileRequest = true; mbaasRequest.app(params, cb); }
[ "function", "getSubmissionStatus", "(", "params", ",", "cb", ")", "{", "var", "resourcePath", "=", "config", ".", "addURIParams", "(", "\"/appforms/submissions/:id/status\"", ",", "params", ")", ";", "var", "method", "=", "\"GET\"", ";", "var", "data", "=", "{", "}", ";", "params", ".", "resourcePath", "=", "resourcePath", ";", "params", ".", "method", "=", "method", ";", "params", ".", "data", "=", "data", ";", "//Flagging This Request As A File Request", "params", ".", "fileRequest", "=", "true", ";", "mbaasRequest", ".", "app", "(", "params", ",", "cb", ")", ";", "}" ]
Get The Current Status Of A Submission
[ "Get", "The", "Current", "Status", "Of", "A", "Submission" ]
2d5a9cbb32e1b2464d71ffa18513358fea388859
https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/app/appforms/submissions.js#L73-L86
44,812
feedhenry/fh-mbaas-client
lib/app/appforms/submissions.js
exportCSV
function exportCSV(params, cb) { var resourcePath = config.addURIParams("/appforms/submissions/export", params); var method = "POST"; var data = params.queryParams; params.resourcePath = resourcePath; params.method = method; params.data = data; params.fileRequest = true; mbaasRequest.app(params, cb); }
javascript
function exportCSV(params, cb) { var resourcePath = config.addURIParams("/appforms/submissions/export", params); var method = "POST"; var data = params.queryParams; params.resourcePath = resourcePath; params.method = method; params.data = data; params.fileRequest = true; mbaasRequest.app(params, cb); }
[ "function", "exportCSV", "(", "params", ",", "cb", ")", "{", "var", "resourcePath", "=", "config", ".", "addURIParams", "(", "\"/appforms/submissions/export\"", ",", "params", ")", ";", "var", "method", "=", "\"POST\"", ";", "var", "data", "=", "params", ".", "queryParams", ";", "params", ".", "resourcePath", "=", "resourcePath", ";", "params", ".", "method", "=", "method", ";", "params", ".", "data", "=", "data", ";", "params", ".", "fileRequest", "=", "true", ";", "mbaasRequest", ".", "app", "(", "params", ",", "cb", ")", ";", "}" ]
Export Submissions As A Zip File Containing CSVs. @param params @param cb
[ "Export", "Submissions", "As", "A", "Zip", "File", "Containing", "CSVs", "." ]
2d5a9cbb32e1b2464d71ffa18513358fea388859
https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/app/appforms/submissions.js#L152-L164
44,813
eHealthAfrica/data-models-deprecated
index.js
validate
function validate(candidate) { if (candidate.doc_type) { var schema = schemasDeepCopy()[candidate.doc_type]; validator.validate(candidate, schema); var errors = validator.getLastErrors(); return errors; } return [{ dataModel: 'the object to be validated is missing a `doc_type` property' }]; }
javascript
function validate(candidate) { if (candidate.doc_type) { var schema = schemasDeepCopy()[candidate.doc_type]; validator.validate(candidate, schema); var errors = validator.getLastErrors(); return errors; } return [{ dataModel: 'the object to be validated is missing a `doc_type` property' }]; }
[ "function", "validate", "(", "candidate", ")", "{", "if", "(", "candidate", ".", "doc_type", ")", "{", "var", "schema", "=", "schemasDeepCopy", "(", ")", "[", "candidate", ".", "doc_type", "]", ";", "validator", ".", "validate", "(", "candidate", ",", "schema", ")", ";", "var", "errors", "=", "validator", ".", "getLastErrors", "(", ")", ";", "return", "errors", ";", "}", "return", "[", "{", "dataModel", ":", "'the object to be validated is missing a `doc_type` property'", "}", "]", ";", "}" ]
Thin wrapper to make validation more convenient @param {Object} candidate A model instance to validate @return {[Error]} A list of errors or null
[ "Thin", "wrapper", "to", "make", "validation", "more", "convenient" ]
93da821ed51f79b9b0411969b7721b49c7089890
https://github.com/eHealthAfrica/data-models-deprecated/blob/93da821ed51f79b9b0411969b7721b49c7089890/index.js#L47-L58
44,814
eHealthAfrica/data-models-deprecated
index.js
generate
function generate(model, count) { count = count || 1; var registry = {}; var models = []; if (model) { models = typeof model === 'string' ? [model] : model; } else { models = Object.keys(schemas); } function build(model) { var instance = jsf(schemas[model]); var invalid = validate(instance); if (invalid) { var errors = JSON.stringify(invalid, null, 2); throw new Error('Invalid "' + model + '" instance:\n' + errors); } return instance; } function factory(model) { var instances = []; for (var i = 0, len = count; i < len; i++) { var instance = build(model); instances.push(instance); } registry[model] = instances; } models.forEach(factory); return registry; }
javascript
function generate(model, count) { count = count || 1; var registry = {}; var models = []; if (model) { models = typeof model === 'string' ? [model] : model; } else { models = Object.keys(schemas); } function build(model) { var instance = jsf(schemas[model]); var invalid = validate(instance); if (invalid) { var errors = JSON.stringify(invalid, null, 2); throw new Error('Invalid "' + model + '" instance:\n' + errors); } return instance; } function factory(model) { var instances = []; for (var i = 0, len = count; i < len; i++) { var instance = build(model); instances.push(instance); } registry[model] = instances; } models.forEach(factory); return registry; }
[ "function", "generate", "(", "model", ",", "count", ")", "{", "count", "=", "count", "||", "1", ";", "var", "registry", "=", "{", "}", ";", "var", "models", "=", "[", "]", ";", "if", "(", "model", ")", "{", "models", "=", "typeof", "model", "===", "'string'", "?", "[", "model", "]", ":", "model", ";", "}", "else", "{", "models", "=", "Object", ".", "keys", "(", "schemas", ")", ";", "}", "function", "build", "(", "model", ")", "{", "var", "instance", "=", "jsf", "(", "schemas", "[", "model", "]", ")", ";", "var", "invalid", "=", "validate", "(", "instance", ")", ";", "if", "(", "invalid", ")", "{", "var", "errors", "=", "JSON", ".", "stringify", "(", "invalid", ",", "null", ",", "2", ")", ";", "throw", "new", "Error", "(", "'Invalid \"'", "+", "model", "+", "'\" instance:\\n'", "+", "errors", ")", ";", "}", "return", "instance", ";", "}", "function", "factory", "(", "model", ")", "{", "var", "instances", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "count", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "instance", "=", "build", "(", "model", ")", ";", "instances", ".", "push", "(", "instance", ")", ";", "}", "registry", "[", "model", "]", "=", "instances", ";", "}", "models", ".", "forEach", "(", "factory", ")", ";", "return", "registry", ";", "}" ]
Generate instances populated with pseudo random data @param {(String|[String])} model An optional model or list of models @param {Number} count An optional number of instances to generate @return {Object} A map of model-instances
[ "Generate", "instances", "populated", "with", "pseudo", "random", "data" ]
93da821ed51f79b9b0411969b7721b49c7089890
https://github.com/eHealthAfrica/data-models-deprecated/blob/93da821ed51f79b9b0411969b7721b49c7089890/index.js#L67-L99
44,815
KTH/kth-node-server
index.js
serverClose
function serverClose (signal, done) { _logger.info('Process received ' + signal + ', exiting ....') if (done === undefined) { done = function () { process.exit(0) } } if (server) { server.close(done) } else { done() } }
javascript
function serverClose (signal, done) { _logger.info('Process received ' + signal + ', exiting ....') if (done === undefined) { done = function () { process.exit(0) } } if (server) { server.close(done) } else { done() } }
[ "function", "serverClose", "(", "signal", ",", "done", ")", "{", "_logger", ".", "info", "(", "'Process received '", "+", "signal", "+", "', exiting ....'", ")", "if", "(", "done", "===", "undefined", ")", "{", "done", "=", "function", "(", ")", "{", "process", ".", "exit", "(", "0", ")", "}", "}", "if", "(", "server", ")", "{", "server", ".", "close", "(", "done", ")", "}", "else", "{", "done", "(", ")", "}", "}" ]
Closing the server @param signal the log message depending on the given signal.
[ "Closing", "the", "server" ]
0880a801c3d0298258084ba830929c9798e2275c
https://github.com/KTH/kth-node-server/blob/0880a801c3d0298258084ba830929c9798e2275c/index.js#L17-L29
44,816
nodejitsu/contour
pagelets/nodejitsu/anchor/base.js
scroll
function scroll(e) { var attr = e.element.attributes; if (!(attr || attr.href)) return; var target = $(attr.href.value).plain(0); if (!target) return; e.preventDefault(); // // Store the current window top Y and difference. // this.y = document.body.scrollTop; this.target = target.offsetTop; this.direction = this.target > this.y ? 1 : -1; this.delta = Math.abs(this.y - this.target); // // Start the animation. // this.animated = setInterval(this.animate.bind(this), 10); }
javascript
function scroll(e) { var attr = e.element.attributes; if (!(attr || attr.href)) return; var target = $(attr.href.value).plain(0); if (!target) return; e.preventDefault(); // // Store the current window top Y and difference. // this.y = document.body.scrollTop; this.target = target.offsetTop; this.direction = this.target > this.y ? 1 : -1; this.delta = Math.abs(this.y - this.target); // // Start the animation. // this.animated = setInterval(this.animate.bind(this), 10); }
[ "function", "scroll", "(", "e", ")", "{", "var", "attr", "=", "e", ".", "element", ".", "attributes", ";", "if", "(", "!", "(", "attr", "||", "attr", ".", "href", ")", ")", "return", ";", "var", "target", "=", "$", "(", "attr", ".", "href", ".", "value", ")", ".", "plain", "(", "0", ")", ";", "if", "(", "!", "target", ")", "return", ";", "e", ".", "preventDefault", "(", ")", ";", "//", "// Store the current window top Y and difference.", "//", "this", ".", "y", "=", "document", ".", "body", ".", "scrollTop", ";", "this", ".", "target", "=", "target", ".", "offsetTop", ";", "this", ".", "direction", "=", "this", ".", "target", ">", "this", ".", "y", "?", "1", ":", "-", "1", ";", "this", ".", "delta", "=", "Math", ".", "abs", "(", "this", ".", "y", "-", "this", ".", "target", ")", ";", "//", "// Start the animation.", "//", "this", ".", "animated", "=", "setInterval", "(", "this", ".", "animate", ".", "bind", "(", "this", ")", ",", "10", ")", ";", "}" ]
Scroll to the target of data-scroll. @param {Event} e @api private
[ "Scroll", "to", "the", "target", "of", "data", "-", "scroll", "." ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/nodejitsu/anchor/base.js#L33-L54
44,817
nodejitsu/contour
pagelets/nodejitsu/anchor/base.js
animate
function animate() { var diff = this.speed; // // If we're getting close to the endpoint stop at 0. // if (this.delta < diff) { clearInterval(this.animated); diff = this.delta; } // // Keep track of how much is scrolled. // this.delta = this.delta - diff; this.y = this.y + diff * this.direction; // // Animate the scroll position. // window.scrollTo(0, this.y); }
javascript
function animate() { var diff = this.speed; // // If we're getting close to the endpoint stop at 0. // if (this.delta < diff) { clearInterval(this.animated); diff = this.delta; } // // Keep track of how much is scrolled. // this.delta = this.delta - diff; this.y = this.y + diff * this.direction; // // Animate the scroll position. // window.scrollTo(0, this.y); }
[ "function", "animate", "(", ")", "{", "var", "diff", "=", "this", ".", "speed", ";", "//", "// If we're getting close to the endpoint stop at 0.", "//", "if", "(", "this", ".", "delta", "<", "diff", ")", "{", "clearInterval", "(", "this", ".", "animated", ")", ";", "diff", "=", "this", ".", "delta", ";", "}", "//", "// Keep track of how much is scrolled.", "//", "this", ".", "delta", "=", "this", ".", "delta", "-", "diff", ";", "this", ".", "y", "=", "this", ".", "y", "+", "diff", "*", "this", ".", "direction", ";", "//", "// Animate the scroll position.", "//", "window", ".", "scrollTo", "(", "0", ",", "this", ".", "y", ")", ";", "}" ]
Calculations for the animation. @api private
[ "Calculations", "for", "the", "animation", "." ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/nodejitsu/anchor/base.js#L61-L82
44,818
writetome51/array-has
dist/privy/arrayHasAdjacent.js
arrayHasAdjacent
function arrayHasAdjacent(values, array) { error_if_not_array_1.errorIfNotArray(values); if (is_empty_not_empty_1.isEmpty(values)) return false; var indexes = array_get_indexes_1.getIndexesOf(values[0], array); var i = -1; while (++i < indexes.length) { if (indexes[i] + values.length > array.length) return false; var adjacentItems = array_get_adjacent_at_1.getAdjacentAt(indexes[i], values.length, array); if (arrays_match_1.arraysMatch(values, adjacentItems)) return true; } return false; }
javascript
function arrayHasAdjacent(values, array) { error_if_not_array_1.errorIfNotArray(values); if (is_empty_not_empty_1.isEmpty(values)) return false; var indexes = array_get_indexes_1.getIndexesOf(values[0], array); var i = -1; while (++i < indexes.length) { if (indexes[i] + values.length > array.length) return false; var adjacentItems = array_get_adjacent_at_1.getAdjacentAt(indexes[i], values.length, array); if (arrays_match_1.arraysMatch(values, adjacentItems)) return true; } return false; }
[ "function", "arrayHasAdjacent", "(", "values", ",", "array", ")", "{", "error_if_not_array_1", ".", "errorIfNotArray", "(", "values", ")", ";", "if", "(", "is_empty_not_empty_1", ".", "isEmpty", "(", "values", ")", ")", "return", "false", ";", "var", "indexes", "=", "array_get_indexes_1", ".", "getIndexesOf", "(", "values", "[", "0", "]", ",", "array", ")", ";", "var", "i", "=", "-", "1", ";", "while", "(", "++", "i", "<", "indexes", ".", "length", ")", "{", "if", "(", "indexes", "[", "i", "]", "+", "values", ".", "length", ">", "array", ".", "length", ")", "return", "false", ";", "var", "adjacentItems", "=", "array_get_adjacent_at_1", ".", "getAdjacentAt", "(", "indexes", "[", "i", "]", ",", "values", ".", "length", ",", "array", ")", ";", "if", "(", "arrays_match_1", ".", "arraysMatch", "(", "values", ",", "adjacentItems", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks if array contains adjacent values anywhere inside it. values cannot contain object.
[ "Checks", "if", "array", "contains", "adjacent", "values", "anywhere", "inside", "it", ".", "values", "cannot", "contain", "object", "." ]
8ced3fda5818940b814bbcdc37e03c65f285a965
https://github.com/writetome51/array-has/blob/8ced3fda5818940b814bbcdc37e03c65f285a965/dist/privy/arrayHasAdjacent.js#L10-L24
44,819
haraldrudell/nodegod
lib/appentity.js
restartAppFromWatching
function restartAppFromWatching(err) { updateWatcherCount() if (err) self.emit('error', err) if (dashboard.state !== 'stop') { log('Restarting ' + conf.name + ' due to file watch trigger') appLink.afterThat('restart') } else log('Watcher restart ignored in stop state') }
javascript
function restartAppFromWatching(err) { updateWatcherCount() if (err) self.emit('error', err) if (dashboard.state !== 'stop') { log('Restarting ' + conf.name + ' due to file watch trigger') appLink.afterThat('restart') } else log('Watcher restart ignored in stop state') }
[ "function", "restartAppFromWatching", "(", "err", ")", "{", "updateWatcherCount", "(", ")", "if", "(", "err", ")", "self", ".", "emit", "(", "'error'", ",", "err", ")", "if", "(", "dashboard", ".", "state", "!==", "'stop'", ")", "{", "log", "(", "'Restarting '", "+", "conf", ".", "name", "+", "' due to file watch trigger'", ")", "appLink", ".", "afterThat", "(", "'restart'", ")", "}", "else", "log", "(", "'Watcher restart ignored in stop state'", ")", "}" ]
restart due to file change or copy change
[ "restart", "due", "to", "file", "change", "or", "copy", "change" ]
3be4fb280fb18e0ec0a1c1a8fea3254d92f00b21
https://github.com/haraldrudell/nodegod/blob/3be4fb280fb18e0ec0a1c1a8fea3254d92f00b21/lib/appentity.js#L165-L172
44,820
jldec/pub-generator
render.js
renderTemplate
function renderTemplate(fragment, templateName) { if (templateName === 'none') return fragment._txt; var t = generator.template$[templateName]; if (!t) { log('Unknown template %s for %s, using default.', templateName, fragment._href); t = generator.template$.default; } var out; try { out = t(fragment); } catch(err) { var msg = u.format('Error rendering %s\n\ntemplate: %s\n', fragment._href, templateName, err.stack || err); log(msg); out = opts.production ? '' : '<pre>' + esc(msg) + '</pre>'; } return out; }
javascript
function renderTemplate(fragment, templateName) { if (templateName === 'none') return fragment._txt; var t = generator.template$[templateName]; if (!t) { log('Unknown template %s for %s, using default.', templateName, fragment._href); t = generator.template$.default; } var out; try { out = t(fragment); } catch(err) { var msg = u.format('Error rendering %s\n\ntemplate: %s\n', fragment._href, templateName, err.stack || err); log(msg); out = opts.production ? '' : '<pre>' + esc(msg) + '</pre>'; } return out; }
[ "function", "renderTemplate", "(", "fragment", ",", "templateName", ")", "{", "if", "(", "templateName", "===", "'none'", ")", "return", "fragment", ".", "_txt", ";", "var", "t", "=", "generator", ".", "template$", "[", "templateName", "]", ";", "if", "(", "!", "t", ")", "{", "log", "(", "'Unknown template %s for %s, using default.'", ",", "templateName", ",", "fragment", ".", "_href", ")", ";", "t", "=", "generator", ".", "template$", ".", "default", ";", "}", "var", "out", ";", "try", "{", "out", "=", "t", "(", "fragment", ")", ";", "}", "catch", "(", "err", ")", "{", "var", "msg", "=", "u", ".", "format", "(", "'Error rendering %s\\n\\ntemplate: %s\\n'", ",", "fragment", ".", "_href", ",", "templateName", ",", "err", ".", "stack", "||", "err", ")", ";", "log", "(", "msg", ")", ";", "out", "=", "opts", ".", "production", "?", "''", ":", "'<pre>'", "+", "esc", "(", "msg", ")", "+", "'</pre>'", ";", "}", "return", "out", ";", "}" ]
template renderer handles missing template and template runtime errors
[ "template", "renderer", "handles", "missing", "template", "and", "template", "runtime", "errors" ]
524081509921ac8cb897753142324d61e10afdf3
https://github.com/jldec/pub-generator/blob/524081509921ac8cb897753142324d61e10afdf3/render.js#L79-L97
44,821
jldec/pub-generator
render.js
renderPage
function renderPage(page) { var template = pageTemplate(page); var html = renderTemplate(page, template); return '<div data-render-page="' + esc(template) + '">' + html + '</div>'; }
javascript
function renderPage(page) { var template = pageTemplate(page); var html = renderTemplate(page, template); return '<div data-render-page="' + esc(template) + '">' + html + '</div>'; }
[ "function", "renderPage", "(", "page", ")", "{", "var", "template", "=", "pageTemplate", "(", "page", ")", ";", "var", "html", "=", "renderTemplate", "(", "page", ",", "template", ")", ";", "return", "'<div data-render-page=\"'", "+", "esc", "(", "template", ")", "+", "'\">'", "+", "html", "+", "'</div>'", ";", "}" ]
render a page with a non-layout page-specific template this provides the primary mode of offline navigation on sites with a single layout this function always wraps in marker divs
[ "render", "a", "page", "with", "a", "non", "-", "layout", "page", "-", "specific", "template", "this", "provides", "the", "primary", "mode", "of", "offline", "navigation", "on", "sites", "with", "a", "single", "layout", "this", "function", "always", "wraps", "in", "marker", "divs" ]
524081509921ac8cb897753142324d61e10afdf3
https://github.com/jldec/pub-generator/blob/524081509921ac8cb897753142324d61e10afdf3/render.js#L124-L128
44,822
jldec/pub-generator
render.js
docTemplate
function docTemplate(page) { return page.doclayout || (page.notemplate && 'none') || (page.nolayout && page.template) || (generator.template$['doc-layout'] && 'doc-layout') || layoutTemplate(page); }
javascript
function docTemplate(page) { return page.doclayout || (page.notemplate && 'none') || (page.nolayout && page.template) || (generator.template$['doc-layout'] && 'doc-layout') || layoutTemplate(page); }
[ "function", "docTemplate", "(", "page", ")", "{", "return", "page", ".", "doclayout", "||", "(", "page", ".", "notemplate", "&&", "'none'", ")", "||", "(", "page", ".", "nolayout", "&&", "page", ".", "template", ")", "||", "(", "generator", ".", "template$", "[", "'doc-layout'", "]", "&&", "'doc-layout'", ")", "||", "layoutTemplate", "(", "page", ")", ";", "}" ]
return name of document template for a page delegate to layoutTemplate if site has no doc template page.notemplate bypasses default templates and returns literal text
[ "return", "name", "of", "document", "template", "for", "a", "page", "delegate", "to", "layoutTemplate", "if", "site", "has", "no", "doc", "template", "page", ".", "notemplate", "bypasses", "default", "templates", "and", "returns", "literal", "text" ]
524081509921ac8cb897753142324d61e10afdf3
https://github.com/jldec/pub-generator/blob/524081509921ac8cb897753142324d61e10afdf3/render.js#L133-L139
44,823
jldec/pub-generator
render.js
rewriteLink
function rewriteLink(href, renderOpts) { var imgRoute = renderOpts.fqImages && (renderOpts.fqImages.route || '/images/'); var imgPrefix = renderOpts.fqImages && renderOpts.fqImages.url; var linkPrefix = renderOpts.fqLinks || renderOpts.relPath; if (imgPrefix && u.startsWith(href, imgRoute)) { href = imgPrefix + href; } else if (linkPrefix && /^\/([^/]|$)/.test(href)) { href = linkPrefix + href; } return href; }
javascript
function rewriteLink(href, renderOpts) { var imgRoute = renderOpts.fqImages && (renderOpts.fqImages.route || '/images/'); var imgPrefix = renderOpts.fqImages && renderOpts.fqImages.url; var linkPrefix = renderOpts.fqLinks || renderOpts.relPath; if (imgPrefix && u.startsWith(href, imgRoute)) { href = imgPrefix + href; } else if (linkPrefix && /^\/([^/]|$)/.test(href)) { href = linkPrefix + href; } return href; }
[ "function", "rewriteLink", "(", "href", ",", "renderOpts", ")", "{", "var", "imgRoute", "=", "renderOpts", ".", "fqImages", "&&", "(", "renderOpts", ".", "fqImages", ".", "route", "||", "'/images/'", ")", ";", "var", "imgPrefix", "=", "renderOpts", ".", "fqImages", "&&", "renderOpts", ".", "fqImages", ".", "url", ";", "var", "linkPrefix", "=", "renderOpts", ".", "fqLinks", "||", "renderOpts", ".", "relPath", ";", "if", "(", "imgPrefix", "&&", "u", ".", "startsWith", "(", "href", ",", "imgRoute", ")", ")", "{", "href", "=", "imgPrefix", "+", "href", ";", "}", "else", "if", "(", "linkPrefix", "&&", "/", "^\\/([^/]|$)", "/", ".", "test", "(", "href", ")", ")", "{", "href", "=", "linkPrefix", "+", "href", ";", "}", "return", "href", ";", "}" ]
Link rewriting logic - shared by renderLink and renderImage and hb.fixPath
[ "Link", "rewriting", "logic", "-", "shared", "by", "renderLink", "and", "renderImage", "and", "hb", ".", "fixPath" ]
524081509921ac8cb897753142324d61e10afdf3
https://github.com/jldec/pub-generator/blob/524081509921ac8cb897753142324d61e10afdf3/render.js#L276-L285
44,824
jldec/pub-generator
render.js
inventory
function inventory() { var images = generator.images = {}; var currentPage; var baseRenderImage = generator.renderer.image; generator.renderer.image = function(href, title, text) { if (!images[href]) { images[href] = []; } images[href].push(currentPage._href); return baseRenderImage(href, title, text); }; u.each(generator.pages, function(pg) { currentPage=pg; renderDoc(pg); }); generator.renderer.image = baseRenderImage; }
javascript
function inventory() { var images = generator.images = {}; var currentPage; var baseRenderImage = generator.renderer.image; generator.renderer.image = function(href, title, text) { if (!images[href]) { images[href] = []; } images[href].push(currentPage._href); return baseRenderImage(href, title, text); }; u.each(generator.pages, function(pg) { currentPage=pg; renderDoc(pg); }); generator.renderer.image = baseRenderImage; }
[ "function", "inventory", "(", ")", "{", "var", "images", "=", "generator", ".", "images", "=", "{", "}", ";", "var", "currentPage", ";", "var", "baseRenderImage", "=", "generator", ".", "renderer", ".", "image", ";", "generator", ".", "renderer", ".", "image", "=", "function", "(", "href", ",", "title", ",", "text", ")", "{", "if", "(", "!", "images", "[", "href", "]", ")", "{", "images", "[", "href", "]", "=", "[", "]", ";", "}", "images", "[", "href", "]", ".", "push", "(", "currentPage", ".", "_href", ")", ";", "return", "baseRenderImage", "(", "href", ",", "title", ",", "text", ")", ";", "}", ";", "u", ".", "each", "(", "generator", ".", "pages", ",", "function", "(", "pg", ")", "{", "currentPage", "=", "pg", ";", "renderDoc", "(", "pg", ")", ";", "}", ")", ";", "generator", ".", "renderer", ".", "image", "=", "baseRenderImage", ";", "}" ]
similar to parseLinks temporarily hooks generator renderer to compile images and links for all pages
[ "similar", "to", "parseLinks", "temporarily", "hooks", "generator", "renderer", "to", "compile", "images", "and", "links", "for", "all", "pages" ]
524081509921ac8cb897753142324d61e10afdf3
https://github.com/jldec/pub-generator/blob/524081509921ac8cb897753142324d61e10afdf3/render.js#L342-L360
44,825
vadr-vr/VR-Analytics-JSCore
js/dataManager/sessionManager.js
createSession
function createSession(){ // can also check if any ealier session can be used if (!currentSession){ const createNewSession = _setSessionReferrer(); const currentSessionCookie = utils.getCookie(constants.sessionCookieName); if (currentSessionCookie && !createNewSession){ const currentSessionSplit = currentSessionCookie.split('__'); currentSession = new session(currentSessionSplit[0], parseInt(currentSessionSplit[1]), {}); logger.debug('Found existing session', currentSessionSplit[0], currentSessionSplit[1]); } else{ currentSession = new session(null, null, {}); setSessionCookie(); logger.debug('Creating new session', currentSession.getSessionToken(), currentSession.getSessionUnixTime()); } // associate session referrer with the session if (sessionReferrer){ currentSession.setExtra('referrer', sessionReferrer); } } return currentSession; }
javascript
function createSession(){ // can also check if any ealier session can be used if (!currentSession){ const createNewSession = _setSessionReferrer(); const currentSessionCookie = utils.getCookie(constants.sessionCookieName); if (currentSessionCookie && !createNewSession){ const currentSessionSplit = currentSessionCookie.split('__'); currentSession = new session(currentSessionSplit[0], parseInt(currentSessionSplit[1]), {}); logger.debug('Found existing session', currentSessionSplit[0], currentSessionSplit[1]); } else{ currentSession = new session(null, null, {}); setSessionCookie(); logger.debug('Creating new session', currentSession.getSessionToken(), currentSession.getSessionUnixTime()); } // associate session referrer with the session if (sessionReferrer){ currentSession.setExtra('referrer', sessionReferrer); } } return currentSession; }
[ "function", "createSession", "(", ")", "{", "// can also check if any ealier session can be used", "if", "(", "!", "currentSession", ")", "{", "const", "createNewSession", "=", "_setSessionReferrer", "(", ")", ";", "const", "currentSessionCookie", "=", "utils", ".", "getCookie", "(", "constants", ".", "sessionCookieName", ")", ";", "if", "(", "currentSessionCookie", "&&", "!", "createNewSession", ")", "{", "const", "currentSessionSplit", "=", "currentSessionCookie", ".", "split", "(", "'__'", ")", ";", "currentSession", "=", "new", "session", "(", "currentSessionSplit", "[", "0", "]", ",", "parseInt", "(", "currentSessionSplit", "[", "1", "]", ")", ",", "{", "}", ")", ";", "logger", ".", "debug", "(", "'Found existing session'", ",", "currentSessionSplit", "[", "0", "]", ",", "currentSessionSplit", "[", "1", "]", ")", ";", "}", "else", "{", "currentSession", "=", "new", "session", "(", "null", ",", "null", ",", "{", "}", ")", ";", "setSessionCookie", "(", ")", ";", "logger", ".", "debug", "(", "'Creating new session'", ",", "currentSession", ".", "getSessionToken", "(", ")", ",", "currentSession", ".", "getSessionUnixTime", "(", ")", ")", ";", "}", "// associate session referrer with the session", "if", "(", "sessionReferrer", ")", "{", "currentSession", ".", "setExtra", "(", "'referrer'", ",", "sessionReferrer", ")", ";", "}", "}", "return", "currentSession", ";", "}" ]
Manages creation of current session. @memberof DataManager @private
[ "Manages", "creation", "of", "current", "session", "." ]
7e4a493c824c2c1716360dcb6a3bfecfede5df3b
https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/dataManager/sessionManager.js#L19-L57
44,826
chapmanu/hb
lib/services/instagram/subscriber.js
function(subscription_id) { var params = { client_id: this._credentials.client_id, client_secret: this._credentials.client_secret }; if (subscription_id==='users') { params.object = 'user'; } else if (subscription_id==='all') { params.object = 'all'; } else { params.id = subscription_id; } return params; }
javascript
function(subscription_id) { var params = { client_id: this._credentials.client_id, client_secret: this._credentials.client_secret }; if (subscription_id==='users') { params.object = 'user'; } else if (subscription_id==='all') { params.object = 'all'; } else { params.id = subscription_id; } return params; }
[ "function", "(", "subscription_id", ")", "{", "var", "params", "=", "{", "client_id", ":", "this", ".", "_credentials", ".", "client_id", ",", "client_secret", ":", "this", ".", "_credentials", ".", "client_secret", "}", ";", "if", "(", "subscription_id", "===", "'users'", ")", "{", "params", ".", "object", "=", "'user'", ";", "}", "else", "if", "(", "subscription_id", "===", "'all'", ")", "{", "params", ".", "object", "=", "'all'", ";", "}", "else", "{", "params", ".", "id", "=", "subscription_id", ";", "}", "return", "params", ";", "}" ]
Generate request parameters for unsubscribing
[ "Generate", "request", "parameters", "for", "unsubscribing" ]
5edd8de89c7c5fdffc3df0c627513889220f7d51
https://github.com/chapmanu/hb/blob/5edd8de89c7c5fdffc3df0c627513889220f7d51/lib/services/instagram/subscriber.js#L43-L56
44,827
chapmanu/hb
lib/services/instagram/subscriber.js
function() { this.subscribe('user', function(error, response) { if (!error && response) { logger.info('instagram -', 'users', 'subscription confirmed'); Subscriber.prototype.subscriptions['users'] = response.id; } }); }
javascript
function() { this.subscribe('user', function(error, response) { if (!error && response) { logger.info('instagram -', 'users', 'subscription confirmed'); Subscriber.prototype.subscriptions['users'] = response.id; } }); }
[ "function", "(", ")", "{", "this", ".", "subscribe", "(", "'user'", ",", "function", "(", "error", ",", "response", ")", "{", "if", "(", "!", "error", "&&", "response", ")", "{", "logger", ".", "info", "(", "'instagram -'", ",", "'users'", ",", "'subscription confirmed'", ")", ";", "Subscriber", ".", "prototype", ".", "subscriptions", "[", "'users'", "]", "=", "response", ".", "id", ";", "}", "}", ")", ";", "}" ]
Make a users subscription request
[ "Make", "a", "users", "subscription", "request" ]
5edd8de89c7c5fdffc3df0c627513889220f7d51
https://github.com/chapmanu/hb/blob/5edd8de89c7c5fdffc3df0c627513889220f7d51/lib/services/instagram/subscriber.js#L119-L126
44,828
vid/SenseBase
lib/annotations.js
createAnnotation
function createAnnotation(desc) { utils.check(['type', 'hasTarget', 'annotatedBy'], desc); var anno = { type: desc.type, hasTarget: desc.hasTarget, annotatedAt : desc.annotatedAt || new Date().toISOString(), annotatedBy : desc.annotatedBy, state: desc.state || utils.states.annotations.unvalidated}; // used to create a hierarchical position // FIXME reconcile roots / position var position = desc.roots || [], flattened = desc.type + unitSep; anno.roots = desc.roots || []; if (desc.type === 'quote') { utils.check(['ranges', 'quote'], desc); if (!desc.ranges || desc.ranges.length < 1) { utils.checkError(desc, 'missing ranges'); } anno.quote = desc.quote; anno.ranges = desc.ranges; position.push(anno.quote); flattened += position.join(unitSep); } else if (desc.type === 'category') { utils.check(['category'], desc); anno.category = Array.isArray(desc.category) ? desc.category : [desc.category]; position = position.concat(anno.category); flattened += position.join(unitSep); } else if (desc.type === 'value' || desc.type === 'valueQuote') { utils.check(['key', 'value'], desc); if (desc.type === 'valueQuote') { utils.check(['ranges'], desc); anno.ranges = desc.ranges; } anno.key = desc.key; anno.value = desc.value; position.push(desc.key); flattened += position.join(unitSep) + unitSep + desc.value; // add data types if (desc.isA) { try { anno.isA = desc.isA; anno.typed = {}; anno.typed[desc.isA] = dataTypes[desc.isA](desc.value); } catch (e) { anno.typed.failure = e; GLOBAL.warn('isA failed', e, desc); } } } else { throw new Error('unknown type ' + desc.type); } anno.position = position; anno.flattened = flattened; if (anno.attributes) { anno.attributes = desc.attributes; // additional attributes } return anno; }
javascript
function createAnnotation(desc) { utils.check(['type', 'hasTarget', 'annotatedBy'], desc); var anno = { type: desc.type, hasTarget: desc.hasTarget, annotatedAt : desc.annotatedAt || new Date().toISOString(), annotatedBy : desc.annotatedBy, state: desc.state || utils.states.annotations.unvalidated}; // used to create a hierarchical position // FIXME reconcile roots / position var position = desc.roots || [], flattened = desc.type + unitSep; anno.roots = desc.roots || []; if (desc.type === 'quote') { utils.check(['ranges', 'quote'], desc); if (!desc.ranges || desc.ranges.length < 1) { utils.checkError(desc, 'missing ranges'); } anno.quote = desc.quote; anno.ranges = desc.ranges; position.push(anno.quote); flattened += position.join(unitSep); } else if (desc.type === 'category') { utils.check(['category'], desc); anno.category = Array.isArray(desc.category) ? desc.category : [desc.category]; position = position.concat(anno.category); flattened += position.join(unitSep); } else if (desc.type === 'value' || desc.type === 'valueQuote') { utils.check(['key', 'value'], desc); if (desc.type === 'valueQuote') { utils.check(['ranges'], desc); anno.ranges = desc.ranges; } anno.key = desc.key; anno.value = desc.value; position.push(desc.key); flattened += position.join(unitSep) + unitSep + desc.value; // add data types if (desc.isA) { try { anno.isA = desc.isA; anno.typed = {}; anno.typed[desc.isA] = dataTypes[desc.isA](desc.value); } catch (e) { anno.typed.failure = e; GLOBAL.warn('isA failed', e, desc); } } } else { throw new Error('unknown type ' + desc.type); } anno.position = position; anno.flattened = flattened; if (anno.attributes) { anno.attributes = desc.attributes; // additional attributes } return anno; }
[ "function", "createAnnotation", "(", "desc", ")", "{", "utils", ".", "check", "(", "[", "'type'", ",", "'hasTarget'", ",", "'annotatedBy'", "]", ",", "desc", ")", ";", "var", "anno", "=", "{", "type", ":", "desc", ".", "type", ",", "hasTarget", ":", "desc", ".", "hasTarget", ",", "annotatedAt", ":", "desc", ".", "annotatedAt", "||", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ",", "annotatedBy", ":", "desc", ".", "annotatedBy", ",", "state", ":", "desc", ".", "state", "||", "utils", ".", "states", ".", "annotations", ".", "unvalidated", "}", ";", "// used to create a hierarchical position", "// FIXME reconcile roots / position", "var", "position", "=", "desc", ".", "roots", "||", "[", "]", ",", "flattened", "=", "desc", ".", "type", "+", "unitSep", ";", "anno", ".", "roots", "=", "desc", ".", "roots", "||", "[", "]", ";", "if", "(", "desc", ".", "type", "===", "'quote'", ")", "{", "utils", ".", "check", "(", "[", "'ranges'", ",", "'quote'", "]", ",", "desc", ")", ";", "if", "(", "!", "desc", ".", "ranges", "||", "desc", ".", "ranges", ".", "length", "<", "1", ")", "{", "utils", ".", "checkError", "(", "desc", ",", "'missing ranges'", ")", ";", "}", "anno", ".", "quote", "=", "desc", ".", "quote", ";", "anno", ".", "ranges", "=", "desc", ".", "ranges", ";", "position", ".", "push", "(", "anno", ".", "quote", ")", ";", "flattened", "+=", "position", ".", "join", "(", "unitSep", ")", ";", "}", "else", "if", "(", "desc", ".", "type", "===", "'category'", ")", "{", "utils", ".", "check", "(", "[", "'category'", "]", ",", "desc", ")", ";", "anno", ".", "category", "=", "Array", ".", "isArray", "(", "desc", ".", "category", ")", "?", "desc", ".", "category", ":", "[", "desc", ".", "category", "]", ";", "position", "=", "position", ".", "concat", "(", "anno", ".", "category", ")", ";", "flattened", "+=", "position", ".", "join", "(", "unitSep", ")", ";", "}", "else", "if", "(", "desc", ".", "type", "===", "'value'", "||", "desc", ".", "type", "===", "'valueQuote'", ")", "{", "utils", ".", "check", "(", "[", "'key'", ",", "'value'", "]", ",", "desc", ")", ";", "if", "(", "desc", ".", "type", "===", "'valueQuote'", ")", "{", "utils", ".", "check", "(", "[", "'ranges'", "]", ",", "desc", ")", ";", "anno", ".", "ranges", "=", "desc", ".", "ranges", ";", "}", "anno", ".", "key", "=", "desc", ".", "key", ";", "anno", ".", "value", "=", "desc", ".", "value", ";", "position", ".", "push", "(", "desc", ".", "key", ")", ";", "flattened", "+=", "position", ".", "join", "(", "unitSep", ")", "+", "unitSep", "+", "desc", ".", "value", ";", "// add data types", "if", "(", "desc", ".", "isA", ")", "{", "try", "{", "anno", ".", "isA", "=", "desc", ".", "isA", ";", "anno", ".", "typed", "=", "{", "}", ";", "anno", ".", "typed", "[", "desc", ".", "isA", "]", "=", "dataTypes", "[", "desc", ".", "isA", "]", "(", "desc", ".", "value", ")", ";", "}", "catch", "(", "e", ")", "{", "anno", ".", "typed", ".", "failure", "=", "e", ";", "GLOBAL", ".", "warn", "(", "'isA failed'", ",", "e", ",", "desc", ")", ";", "}", "}", "}", "else", "{", "throw", "new", "Error", "(", "'unknown type '", "+", "desc", ".", "type", ")", ";", "}", "anno", ".", "position", "=", "position", ";", "anno", ".", "flattened", "=", "flattened", ";", "if", "(", "anno", ".", "attributes", ")", "{", "anno", ".", "attributes", "=", "desc", ".", "attributes", ";", "// additional attributes", "}", "return", "anno", ";", "}" ]
validates and creates an annotation. pass .roots to insert into hierarchy
[ "validates", "and", "creates", "an", "annotation", ".", "pass", ".", "roots", "to", "insert", "into", "hierarchy" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/annotations.js#L74-L128
44,829
vid/SenseBase
lib/annotations.js
createRange
function createRange(desc) { var fields = ['exact', 'offset', 'selector']; utils.check(fields, desc); return { exact: desc.exact, offset: desc.offset, selector: desc.selector}; }
javascript
function createRange(desc) { var fields = ['exact', 'offset', 'selector']; utils.check(fields, desc); return { exact: desc.exact, offset: desc.offset, selector: desc.selector}; }
[ "function", "createRange", "(", "desc", ")", "{", "var", "fields", "=", "[", "'exact'", ",", "'offset'", ",", "'selector'", "]", ";", "utils", ".", "check", "(", "fields", ",", "desc", ")", ";", "return", "{", "exact", ":", "desc", ".", "exact", ",", "offset", ":", "desc", ".", "offset", ",", "selector", ":", "desc", ".", "selector", "}", ";", "}" ]
validates and creates an annotation range
[ "validates", "and", "creates", "an", "annotation", "range" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/annotations.js#L132-L136
44,830
vid/SenseBase
lib/annotations.js
createInstance
function createInstance(desc) { var fields = ['exact', 'instance', 'selector']; utils.check(fields, desc); return { exact: desc.exact, instance: desc.instance, selector: desc.selector}; }
javascript
function createInstance(desc) { var fields = ['exact', 'instance', 'selector']; utils.check(fields, desc); return { exact: desc.exact, instance: desc.instance, selector: desc.selector}; }
[ "function", "createInstance", "(", "desc", ")", "{", "var", "fields", "=", "[", "'exact'", ",", "'instance'", ",", "'selector'", "]", ";", "utils", ".", "check", "(", "fields", ",", "desc", ")", ";", "return", "{", "exact", ":", "desc", ".", "exact", ",", "instance", ":", "desc", ".", "instance", ",", "selector", ":", "desc", ".", "selector", "}", ";", "}" ]
validates and creates an annotation instance
[ "validates", "and", "creates", "an", "annotation", "instance" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/annotations.js#L139-L143
44,831
vid/SenseBase
web/iframe/injected-iframe.js
diffTable
function diffTable(results) { var curRefs = $('.references-list li').text().toString().split('\n').map(function(r) { return r.trim(); }); $('#sbResults').html('<table><thead><tr><th>Title</th><th>Created</th><th>Source</th></tr></thead><tbody></tbody></table>'); console.log('diffResults', results); if (results && results.hits.total > 0) { var t, created; t += '<tr><th colspan="4">Included</th></tr>'; _.pluck(results.hits.hits, '_source').forEach(function(r) { created = false; // included annos r.annotations.forEach(function(a) { if (a.key === 'DateCreated' && new Date(a.typed.Date) < new Date(2013, 4)) { if (curRefs.indexOf(r.title) > -1) { created = a.typed.Date; } } }); if (created) { r.created = created; t += _.template('<tr><td><a href="<%= uri %>"><%= title %></a></td><td><%= created %></td><td><div class="ui tiny buttons"><div class="ui basic tiny button">PubMed</div></td></tr>', r); } $('#sbResults table').append(t); }); t += '<tr><th colspan="4">Not included</th></tr>'; _.pluck(results.hits.hits, '_source').forEach(function(r) { created = false; // included annos r.annotations.forEach(function(a) { if (a.key === 'DateCreated' && new Date(a.typed.Date) < new Date(2013, 4)) { if (curRefs.indexOf(r.title) < 0) { created = a.typed.Date; } } }); if (created) { r.created = created; t += _.template('<tr><td><a href="<%= uri %>"><%= title %></a></td><td><%= created %></td><td><div class="ui tiny buttons"><div class="ui basic tiny button">PubMed</div></td></tr>', r); } $('#sbResults tbody').append(t); }); t += '<tr><th colspan="4">New</th></tr>'; _.pluck(results.hits.hits, '_source').forEach(function(r) { created = false; // included annos r.annotations.forEach(function(a) { if (a.key === 'DateCreated' && new Date(a.typed.Date) > new Date(2013, 3)) { created = a.typed.Date; } }); if (created) { r.created = created; t += _.template('<tr><td><a href="<%= uri %>"><%= title %></a></td><td><%= created %></td><td><div class="ui tiny buttons"><div class="ui basic tiny button">PubMed</div></td></tr>', r); } $('#sbResults table').html(t); }); } }
javascript
function diffTable(results) { var curRefs = $('.references-list li').text().toString().split('\n').map(function(r) { return r.trim(); }); $('#sbResults').html('<table><thead><tr><th>Title</th><th>Created</th><th>Source</th></tr></thead><tbody></tbody></table>'); console.log('diffResults', results); if (results && results.hits.total > 0) { var t, created; t += '<tr><th colspan="4">Included</th></tr>'; _.pluck(results.hits.hits, '_source').forEach(function(r) { created = false; // included annos r.annotations.forEach(function(a) { if (a.key === 'DateCreated' && new Date(a.typed.Date) < new Date(2013, 4)) { if (curRefs.indexOf(r.title) > -1) { created = a.typed.Date; } } }); if (created) { r.created = created; t += _.template('<tr><td><a href="<%= uri %>"><%= title %></a></td><td><%= created %></td><td><div class="ui tiny buttons"><div class="ui basic tiny button">PubMed</div></td></tr>', r); } $('#sbResults table').append(t); }); t += '<tr><th colspan="4">Not included</th></tr>'; _.pluck(results.hits.hits, '_source').forEach(function(r) { created = false; // included annos r.annotations.forEach(function(a) { if (a.key === 'DateCreated' && new Date(a.typed.Date) < new Date(2013, 4)) { if (curRefs.indexOf(r.title) < 0) { created = a.typed.Date; } } }); if (created) { r.created = created; t += _.template('<tr><td><a href="<%= uri %>"><%= title %></a></td><td><%= created %></td><td><div class="ui tiny buttons"><div class="ui basic tiny button">PubMed</div></td></tr>', r); } $('#sbResults tbody').append(t); }); t += '<tr><th colspan="4">New</th></tr>'; _.pluck(results.hits.hits, '_source').forEach(function(r) { created = false; // included annos r.annotations.forEach(function(a) { if (a.key === 'DateCreated' && new Date(a.typed.Date) > new Date(2013, 3)) { created = a.typed.Date; } }); if (created) { r.created = created; t += _.template('<tr><td><a href="<%= uri %>"><%= title %></a></td><td><%= created %></td><td><div class="ui tiny buttons"><div class="ui basic tiny button">PubMed</div></td></tr>', r); } $('#sbResults table').html(t); }); } }
[ "function", "diffTable", "(", "results", ")", "{", "var", "curRefs", "=", "$", "(", "'.references-list li'", ")", ".", "text", "(", ")", ".", "toString", "(", ")", ".", "split", "(", "'\\n'", ")", ".", "map", "(", "function", "(", "r", ")", "{", "return", "r", ".", "trim", "(", ")", ";", "}", ")", ";", "$", "(", "'#sbResults'", ")", ".", "html", "(", "'<table><thead><tr><th>Title</th><th>Created</th><th>Source</th></tr></thead><tbody></tbody></table>'", ")", ";", "console", ".", "log", "(", "'diffResults'", ",", "results", ")", ";", "if", "(", "results", "&&", "results", ".", "hits", ".", "total", ">", "0", ")", "{", "var", "t", ",", "created", ";", "t", "+=", "'<tr><th colspan=\"4\">Included</th></tr>'", ";", "_", ".", "pluck", "(", "results", ".", "hits", ".", "hits", ",", "'_source'", ")", ".", "forEach", "(", "function", "(", "r", ")", "{", "created", "=", "false", ";", "// included annos", "r", ".", "annotations", ".", "forEach", "(", "function", "(", "a", ")", "{", "if", "(", "a", ".", "key", "===", "'DateCreated'", "&&", "new", "Date", "(", "a", ".", "typed", ".", "Date", ")", "<", "new", "Date", "(", "2013", ",", "4", ")", ")", "{", "if", "(", "curRefs", ".", "indexOf", "(", "r", ".", "title", ")", ">", "-", "1", ")", "{", "created", "=", "a", ".", "typed", ".", "Date", ";", "}", "}", "}", ")", ";", "if", "(", "created", ")", "{", "r", ".", "created", "=", "created", ";", "t", "+=", "_", ".", "template", "(", "'<tr><td><a href=\"<%= uri %>\"><%= title %></a></td><td><%= created %></td><td><div class=\"ui tiny buttons\"><div class=\"ui basic tiny button\">PubMed</div></td></tr>'", ",", "r", ")", ";", "}", "$", "(", "'#sbResults table'", ")", ".", "append", "(", "t", ")", ";", "}", ")", ";", "t", "+=", "'<tr><th colspan=\"4\">Not included</th></tr>'", ";", "_", ".", "pluck", "(", "results", ".", "hits", ".", "hits", ",", "'_source'", ")", ".", "forEach", "(", "function", "(", "r", ")", "{", "created", "=", "false", ";", "// included annos", "r", ".", "annotations", ".", "forEach", "(", "function", "(", "a", ")", "{", "if", "(", "a", ".", "key", "===", "'DateCreated'", "&&", "new", "Date", "(", "a", ".", "typed", ".", "Date", ")", "<", "new", "Date", "(", "2013", ",", "4", ")", ")", "{", "if", "(", "curRefs", ".", "indexOf", "(", "r", ".", "title", ")", "<", "0", ")", "{", "created", "=", "a", ".", "typed", ".", "Date", ";", "}", "}", "}", ")", ";", "if", "(", "created", ")", "{", "r", ".", "created", "=", "created", ";", "t", "+=", "_", ".", "template", "(", "'<tr><td><a href=\"<%= uri %>\"><%= title %></a></td><td><%= created %></td><td><div class=\"ui tiny buttons\"><div class=\"ui basic tiny button\">PubMed</div></td></tr>'", ",", "r", ")", ";", "}", "$", "(", "'#sbResults tbody'", ")", ".", "append", "(", "t", ")", ";", "}", ")", ";", "t", "+=", "'<tr><th colspan=\"4\">New</th></tr>'", ";", "_", ".", "pluck", "(", "results", ".", "hits", ".", "hits", ",", "'_source'", ")", ".", "forEach", "(", "function", "(", "r", ")", "{", "created", "=", "false", ";", "// included annos", "r", ".", "annotations", ".", "forEach", "(", "function", "(", "a", ")", "{", "if", "(", "a", ".", "key", "===", "'DateCreated'", "&&", "new", "Date", "(", "a", ".", "typed", ".", "Date", ")", ">", "new", "Date", "(", "2013", ",", "3", ")", ")", "{", "created", "=", "a", ".", "typed", ".", "Date", ";", "}", "}", ")", ";", "if", "(", "created", ")", "{", "r", ".", "created", "=", "created", ";", "t", "+=", "_", ".", "template", "(", "'<tr><td><a href=\"<%= uri %>\"><%= title %></a></td><td><%= created %></td><td><div class=\"ui tiny buttons\"><div class=\"ui basic tiny button\">PubMed</div></td></tr>'", ",", "r", ")", ";", "}", "$", "(", "'#sbResults table'", ")", ".", "html", "(", "t", ")", ";", "}", ")", ";", "}", "}" ]
for a demo. sigh.
[ "for", "a", "demo", ".", "sigh", "." ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/web/iframe/injected-iframe.js#L22-L83
44,832
vid/SenseBase
web/iframe/injected-iframe.js
findInstanceOffset
function findInstanceOffset(anno, text) { var re = new RegExp('\\b'+anno.exact+'\\b', 'g'), cur = 1, match; while ((match = re.exec(text)) !== null) { if (cur === anno.instance) { return match.index; } cur++; } }
javascript
function findInstanceOffset(anno, text) { var re = new RegExp('\\b'+anno.exact+'\\b', 'g'), cur = 1, match; while ((match = re.exec(text)) !== null) { if (cur === anno.instance) { return match.index; } cur++; } }
[ "function", "findInstanceOffset", "(", "anno", ",", "text", ")", "{", "var", "re", "=", "new", "RegExp", "(", "'\\\\b'", "+", "anno", ".", "exact", "+", "'\\\\b'", ",", "'g'", ")", ",", "cur", "=", "1", ",", "match", ";", "while", "(", "(", "match", "=", "re", ".", "exec", "(", "text", ")", ")", "!==", "null", ")", "{", "if", "(", "cur", "===", "anno", ".", "instance", ")", "{", "return", "match", ".", "index", ";", "}", "cur", "++", ";", "}", "}" ]
find the starting position of an instance
[ "find", "the", "starting", "position", "of", "an", "instance" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/web/iframe/injected-iframe.js#L168-L176
44,833
vid/SenseBase
web/iframe/injected-iframe.js
displayAllAnnos
function displayAllAnnos(treeItems) { var items = [], selector, newHTML, i; // two passes; first assign offsets and add to array with the same selector for (i in treeItems.map) { var anno = treeItems.map[i]; console.log(anno); if (anno.selector === 'body') { anno.selector = '#SBEnclosure'; } if (anno.instance && (!selector || selector === anno.selector)) { if (!newHTML) { selector = anno.selector; newHTML = $(selector, doc).html(); } anno.offset = findInstanceOffset(anno, newHTML); items.push(anno); } } console.log(items.length, 'eligible in', selector, 'out of', i); // second pass, sort and display annotations, later first. var latest = 1, item; while (latest > -1) { latest = -1; for (i = 0; i < items.length; i++) { item = items[i]; if (item && item.offset > latest) { latest = i; } } if (latest > -1) { newHTML = insertAnno(items[latest], newHTML); delete items[latest]; } } try { $(selector, doc).html(newHTML); } catch (e) { console.log('failed for', selector, newHTML.length); console.log(e); } }
javascript
function displayAllAnnos(treeItems) { var items = [], selector, newHTML, i; // two passes; first assign offsets and add to array with the same selector for (i in treeItems.map) { var anno = treeItems.map[i]; console.log(anno); if (anno.selector === 'body') { anno.selector = '#SBEnclosure'; } if (anno.instance && (!selector || selector === anno.selector)) { if (!newHTML) { selector = anno.selector; newHTML = $(selector, doc).html(); } anno.offset = findInstanceOffset(anno, newHTML); items.push(anno); } } console.log(items.length, 'eligible in', selector, 'out of', i); // second pass, sort and display annotations, later first. var latest = 1, item; while (latest > -1) { latest = -1; for (i = 0; i < items.length; i++) { item = items[i]; if (item && item.offset > latest) { latest = i; } } if (latest > -1) { newHTML = insertAnno(items[latest], newHTML); delete items[latest]; } } try { $(selector, doc).html(newHTML); } catch (e) { console.log('failed for', selector, newHTML.length); console.log(e); } }
[ "function", "displayAllAnnos", "(", "treeItems", ")", "{", "var", "items", "=", "[", "]", ",", "selector", ",", "newHTML", ",", "i", ";", "// two passes; first assign offsets and add to array with the same selector", "for", "(", "i", "in", "treeItems", ".", "map", ")", "{", "var", "anno", "=", "treeItems", ".", "map", "[", "i", "]", ";", "console", ".", "log", "(", "anno", ")", ";", "if", "(", "anno", ".", "selector", "===", "'body'", ")", "{", "anno", ".", "selector", "=", "'#SBEnclosure'", ";", "}", "if", "(", "anno", ".", "instance", "&&", "(", "!", "selector", "||", "selector", "===", "anno", ".", "selector", ")", ")", "{", "if", "(", "!", "newHTML", ")", "{", "selector", "=", "anno", ".", "selector", ";", "newHTML", "=", "$", "(", "selector", ",", "doc", ")", ".", "html", "(", ")", ";", "}", "anno", ".", "offset", "=", "findInstanceOffset", "(", "anno", ",", "newHTML", ")", ";", "items", ".", "push", "(", "anno", ")", ";", "}", "}", "console", ".", "log", "(", "items", ".", "length", ",", "'eligible in'", ",", "selector", ",", "'out of'", ",", "i", ")", ";", "// second pass, sort and display annotations, later first.", "var", "latest", "=", "1", ",", "item", ";", "while", "(", "latest", ">", "-", "1", ")", "{", "latest", "=", "-", "1", ";", "for", "(", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", "{", "item", "=", "items", "[", "i", "]", ";", "if", "(", "item", "&&", "item", ".", "offset", ">", "latest", ")", "{", "latest", "=", "i", ";", "}", "}", "if", "(", "latest", ">", "-", "1", ")", "{", "newHTML", "=", "insertAnno", "(", "items", "[", "latest", "]", ",", "newHTML", ")", ";", "delete", "items", "[", "latest", "]", ";", "}", "}", "try", "{", "$", "(", "selector", ",", "doc", ")", ".", "html", "(", "newHTML", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "'failed for'", ",", "selector", ",", "newHTML", ".", "length", ")", ";", "console", ".", "log", "(", "e", ")", ";", "}", "}" ]
prepare and display eligible annotations
[ "prepare", "and", "display", "eligible", "annotations" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/web/iframe/injected-iframe.js#L179-L220
44,834
vid/SenseBase
web/iframe/injected-iframe.js
insertAnno
function insertAnno(anno, newHTML) { var annoID = 'SB-anno-' + anno.__id; var startTag = '<span id="' + annoID + '" class="sbAnnotation sbAnnotation-b">', endTag = '</span>'; anno.offset = findInstanceOffset(anno, newHTML); return newHTML.substring(0, anno.offset) + startTag + anno.exact + endTag + newHTML.substring(anno.offset + anno.exact.length); }
javascript
function insertAnno(anno, newHTML) { var annoID = 'SB-anno-' + anno.__id; var startTag = '<span id="' + annoID + '" class="sbAnnotation sbAnnotation-b">', endTag = '</span>'; anno.offset = findInstanceOffset(anno, newHTML); return newHTML.substring(0, anno.offset) + startTag + anno.exact + endTag + newHTML.substring(anno.offset + anno.exact.length); }
[ "function", "insertAnno", "(", "anno", ",", "newHTML", ")", "{", "var", "annoID", "=", "'SB-anno-'", "+", "anno", ".", "__id", ";", "var", "startTag", "=", "'<span id=\"'", "+", "annoID", "+", "'\" class=\"sbAnnotation sbAnnotation-b\">'", ",", "endTag", "=", "'</span>'", ";", "anno", ".", "offset", "=", "findInstanceOffset", "(", "anno", ",", "newHTML", ")", ";", "return", "newHTML", ".", "substring", "(", "0", ",", "anno", ".", "offset", ")", "+", "startTag", "+", "anno", ".", "exact", "+", "endTag", "+", "newHTML", ".", "substring", "(", "anno", ".", "offset", "+", "anno", ".", "exact", ".", "length", ")", ";", "}" ]
insert annotation categories at correct position
[ "insert", "annotation", "categories", "at", "correct", "position" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/web/iframe/injected-iframe.js#L223-L229
44,835
Whitebolt/require-extra
src/Module.js
_getParent
function _getParent(config) { if (config.hasOwnProperty('parent')) { if (!isString(config.parent)) return config.parent; if (cache.has(config.parent)) return cache.get(config.parent); } return settings.get('parent').parent || settings.get('parent'); }
javascript
function _getParent(config) { if (config.hasOwnProperty('parent')) { if (!isString(config.parent)) return config.parent; if (cache.has(config.parent)) return cache.get(config.parent); } return settings.get('parent').parent || settings.get('parent'); }
[ "function", "_getParent", "(", "config", ")", "{", "if", "(", "config", ".", "hasOwnProperty", "(", "'parent'", ")", ")", "{", "if", "(", "!", "isString", "(", "config", ".", "parent", ")", ")", "return", "config", ".", "parent", ";", "if", "(", "cache", ".", "has", "(", "config", ".", "parent", ")", ")", "return", "cache", ".", "get", "(", "config", ".", "parent", ")", ";", "}", "return", "settings", ".", "get", "(", "'parent'", ")", ".", "parent", "||", "settings", ".", "get", "(", "'parent'", ")", ";", "}" ]
Get the parent of the module we are trying to create. Use the given config object supplied to the constructor. @private @param {Object} config Constructor config. @returns {Module} The parent.
[ "Get", "the", "parent", "of", "the", "module", "we", "are", "trying", "to", "create", ".", "Use", "the", "given", "config", "object", "supplied", "to", "the", "constructor", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/Module.js#L17-L24
44,836
Whitebolt/require-extra
src/Module.js
_getRequire
function _getRequire(config) { if (!config.syncRequire && !config.resolveModulePath) return requireLike(config.filename); const _requireResolver = { basedir:config.basedir||path.dirname(config.filename), parent:config.filename, scope:config.scope, useSandbox:config.useSandbox, squashErrors:!!((config.resolver ||{}).squashErrors || config.squashErrors) }; const requireX = require('./index'); const _mergeResolver = resolver=>Object.assign({}, _requireResolver, resolver); const _getResolver = (params, resolverId=0)=>{ if (isString(params[resolverId]) || Array.isArray(params[resolverId])) return _requireResolver; return _mergeResolver(params.shift()); }; return Object.assign(function(...params) { return config.syncRequire(_getResolver(params), ...params); }, requireX, { resolve: (...params)=>config.resolveModulePathSync(_getResolver(params), ...params), resolveAsync: (...params)=>config.resolveModulePath(_getResolver(params), ...params), async: (...params)=>requireX(_getResolver(params), ...params), native: moduleId=>requireLike(config.filename)(moduleId), import: (dirPath, options, callback)=>requireX.import(dirPath, _mergeResolver(options), callback) }); }
javascript
function _getRequire(config) { if (!config.syncRequire && !config.resolveModulePath) return requireLike(config.filename); const _requireResolver = { basedir:config.basedir||path.dirname(config.filename), parent:config.filename, scope:config.scope, useSandbox:config.useSandbox, squashErrors:!!((config.resolver ||{}).squashErrors || config.squashErrors) }; const requireX = require('./index'); const _mergeResolver = resolver=>Object.assign({}, _requireResolver, resolver); const _getResolver = (params, resolverId=0)=>{ if (isString(params[resolverId]) || Array.isArray(params[resolverId])) return _requireResolver; return _mergeResolver(params.shift()); }; return Object.assign(function(...params) { return config.syncRequire(_getResolver(params), ...params); }, requireX, { resolve: (...params)=>config.resolveModulePathSync(_getResolver(params), ...params), resolveAsync: (...params)=>config.resolveModulePath(_getResolver(params), ...params), async: (...params)=>requireX(_getResolver(params), ...params), native: moduleId=>requireLike(config.filename)(moduleId), import: (dirPath, options, callback)=>requireX.import(dirPath, _mergeResolver(options), callback) }); }
[ "function", "_getRequire", "(", "config", ")", "{", "if", "(", "!", "config", ".", "syncRequire", "&&", "!", "config", ".", "resolveModulePath", ")", "return", "requireLike", "(", "config", ".", "filename", ")", ";", "const", "_requireResolver", "=", "{", "basedir", ":", "config", ".", "basedir", "||", "path", ".", "dirname", "(", "config", ".", "filename", ")", ",", "parent", ":", "config", ".", "filename", ",", "scope", ":", "config", ".", "scope", ",", "useSandbox", ":", "config", ".", "useSandbox", ",", "squashErrors", ":", "!", "!", "(", "(", "config", ".", "resolver", "||", "{", "}", ")", ".", "squashErrors", "||", "config", ".", "squashErrors", ")", "}", ";", "const", "requireX", "=", "require", "(", "'./index'", ")", ";", "const", "_mergeResolver", "=", "resolver", "=>", "Object", ".", "assign", "(", "{", "}", ",", "_requireResolver", ",", "resolver", ")", ";", "const", "_getResolver", "=", "(", "params", ",", "resolverId", "=", "0", ")", "=>", "{", "if", "(", "isString", "(", "params", "[", "resolverId", "]", ")", "||", "Array", ".", "isArray", "(", "params", "[", "resolverId", "]", ")", ")", "return", "_requireResolver", ";", "return", "_mergeResolver", "(", "params", ".", "shift", "(", ")", ")", ";", "}", ";", "return", "Object", ".", "assign", "(", "function", "(", "...", "params", ")", "{", "return", "config", ".", "syncRequire", "(", "_getResolver", "(", "params", ")", ",", "...", "params", ")", ";", "}", ",", "requireX", ",", "{", "resolve", ":", "(", "...", "params", ")", "=>", "config", ".", "resolveModulePathSync", "(", "_getResolver", "(", "params", ")", ",", "...", "params", ")", ",", "resolveAsync", ":", "(", "...", "params", ")", "=>", "config", ".", "resolveModulePath", "(", "_getResolver", "(", "params", ")", ",", "...", "params", ")", ",", "async", ":", "(", "...", "params", ")", "=>", "requireX", "(", "_getResolver", "(", "params", ")", ",", "...", "params", ")", ",", "native", ":", "moduleId", "=>", "requireLike", "(", "config", ".", "filename", ")", "(", "moduleId", ")", ",", "import", ":", "(", "dirPath", ",", "options", ",", "callback", ")", "=>", "requireX", ".", "import", "(", "dirPath", ",", "_mergeResolver", "(", "options", ")", ",", "callback", ")", "}", ")", ";", "}" ]
Create a require function to pass into the module. @private @param {Object} config Module construction config. @returns {Function} The require function.
[ "Create", "a", "require", "function", "to", "pass", "into", "the", "module", "." ]
2a8f737aab67305c9fda3ee56aa7953e97cee859
https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/Module.js#L33-L60
44,837
robeio/robe-json-server
src/server/mixins.js
createId
function createId (coll) { var _ = this var idProperty = _.__id() if (_.isEmpty(coll)) { return 1 } else { var id = _.maxBy(coll, function (doc) { return doc[idProperty] })[idProperty] if (_.isFinite(id)) { // Increment integer id return ++id } else { // Generate string id return uuid() } } }
javascript
function createId (coll) { var _ = this var idProperty = _.__id() if (_.isEmpty(coll)) { return 1 } else { var id = _.maxBy(coll, function (doc) { return doc[idProperty] })[idProperty] if (_.isFinite(id)) { // Increment integer id return ++id } else { // Generate string id return uuid() } } }
[ "function", "createId", "(", "coll", ")", "{", "var", "_", "=", "this", "var", "idProperty", "=", "_", ".", "__id", "(", ")", "if", "(", "_", ".", "isEmpty", "(", "coll", ")", ")", "{", "return", "1", "}", "else", "{", "var", "id", "=", "_", ".", "maxBy", "(", "coll", ",", "function", "(", "doc", ")", "{", "return", "doc", "[", "idProperty", "]", "}", ")", "[", "idProperty", "]", "if", "(", "_", ".", "isFinite", "(", "id", ")", ")", "{", "// Increment integer id", "return", "++", "id", "}", "else", "{", "// Generate string id", "return", "uuid", "(", ")", "}", "}", "}" ]
Return incremented id or uuid Used to override underscore-db's createId with utils.createId
[ "Return", "incremented", "id", "or", "uuid", "Used", "to", "override", "underscore", "-", "db", "s", "createId", "with", "utils", ".", "createId" ]
89b217b08b9d01a8e7b5a72c8505337c85f68629
https://github.com/robeio/robe-json-server/blob/89b217b08b9d01a8e7b5a72c8505337c85f68629/src/server/mixins.js#L38-L56
44,838
socialally/air
lib/air/class.js
hasClass
function hasClass(className) { var i, val; for(i = 0;i < this.length;i++) { val = this.get(i).getAttribute(attr); val = val ? val.split(/\s+/) : []; if(~val.indexOf(className)) { return true; } } return false; }
javascript
function hasClass(className) { var i, val; for(i = 0;i < this.length;i++) { val = this.get(i).getAttribute(attr); val = val ? val.split(/\s+/) : []; if(~val.indexOf(className)) { return true; } } return false; }
[ "function", "hasClass", "(", "className", ")", "{", "var", "i", ",", "val", ";", "for", "(", "i", "=", "0", ";", "i", "<", "this", ".", "length", ";", "i", "++", ")", "{", "val", "=", "this", ".", "get", "(", "i", ")", ".", "getAttribute", "(", "attr", ")", ";", "val", "=", "val", "?", "val", ".", "split", "(", "/", "\\s+", "/", ")", ":", "[", "]", ";", "if", "(", "~", "val", ".", "indexOf", "(", "className", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine whether any of the matched elements are assigned the given class.
[ "Determine", "whether", "any", "of", "the", "matched", "elements", "are", "assigned", "the", "given", "class", "." ]
a3d94de58aaa4930a425fbcc7266764bf6ca8ca6
https://github.com/socialally/air/blob/a3d94de58aaa4930a425fbcc7266764bf6ca8ca6/lib/air/class.js#L32-L42
44,839
socialally/air
lib/air/class.js
removeClass
function removeClass(className) { if(!className) { // remove all classes from all matched elements this.each(function(el) { el.removeAttribute(attr); }); return this; } var classes = className.split(/\s+/); this.each(function(el) { var val = el.getAttribute(attr); // no class attribute - nothing to remove if(!val) { return; } var names = val.split(/\s+/); names = names.filter(function(nm) { return ~classes.indexOf(nm) ? false : nm; }); el.setAttribute(attr, names.join(' ')); }); return this; }
javascript
function removeClass(className) { if(!className) { // remove all classes from all matched elements this.each(function(el) { el.removeAttribute(attr); }); return this; } var classes = className.split(/\s+/); this.each(function(el) { var val = el.getAttribute(attr); // no class attribute - nothing to remove if(!val) { return; } var names = val.split(/\s+/); names = names.filter(function(nm) { return ~classes.indexOf(nm) ? false : nm; }); el.setAttribute(attr, names.join(' ')); }); return this; }
[ "function", "removeClass", "(", "className", ")", "{", "if", "(", "!", "className", ")", "{", "// remove all classes from all matched elements", "this", ".", "each", "(", "function", "(", "el", ")", "{", "el", ".", "removeAttribute", "(", "attr", ")", ";", "}", ")", ";", "return", "this", ";", "}", "var", "classes", "=", "className", ".", "split", "(", "/", "\\s+", "/", ")", ";", "this", ".", "each", "(", "function", "(", "el", ")", "{", "var", "val", "=", "el", ".", "getAttribute", "(", "attr", ")", ";", "// no class attribute - nothing to remove", "if", "(", "!", "val", ")", "{", "return", ";", "}", "var", "names", "=", "val", ".", "split", "(", "/", "\\s+", "/", ")", ";", "names", "=", "names", ".", "filter", "(", "function", "(", "nm", ")", "{", "return", "~", "classes", ".", "indexOf", "(", "nm", ")", "?", "false", ":", "nm", ";", "}", ")", ";", "el", ".", "setAttribute", "(", "attr", ",", "names", ".", "join", "(", "' '", ")", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
[ "Remove", "a", "single", "class", "multiple", "classes", "or", "all", "classes", "from", "each", "element", "in", "the", "set", "of", "matched", "elements", "." ]
a3d94de58aaa4930a425fbcc7266764bf6ca8ca6
https://github.com/socialally/air/blob/a3d94de58aaa4930a425fbcc7266764bf6ca8ca6/lib/air/class.js#L48-L70
44,840
socialally/air
lib/air/class.js
toggleClass
function toggleClass(className) { var classes = className.split(/\s+/) , name , i; for(i = 0;i < classes.length;i++) { name = classes[i]; if(this.hasClass(name)) { this.removeClass(name) }else{ this.addClass(name) } } }
javascript
function toggleClass(className) { var classes = className.split(/\s+/) , name , i; for(i = 0;i < classes.length;i++) { name = classes[i]; if(this.hasClass(name)) { this.removeClass(name) }else{ this.addClass(name) } } }
[ "function", "toggleClass", "(", "className", ")", "{", "var", "classes", "=", "className", ".", "split", "(", "/", "\\s+", "/", ")", ",", "name", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "classes", ".", "length", ";", "i", "++", ")", "{", "name", "=", "classes", "[", "i", "]", ";", "if", "(", "this", ".", "hasClass", "(", "name", ")", ")", "{", "this", ".", "removeClass", "(", "name", ")", "}", "else", "{", "this", ".", "addClass", "(", "name", ")", "}", "}", "}" ]
Add or remove one or more classes from each element in the set of matched elements depending on the class's presence.
[ "Add", "or", "remove", "one", "or", "more", "classes", "from", "each", "element", "in", "the", "set", "of", "matched", "elements", "depending", "on", "the", "class", "s", "presence", "." ]
a3d94de58aaa4930a425fbcc7266764bf6ca8ca6
https://github.com/socialally/air/blob/a3d94de58aaa4930a425fbcc7266764bf6ca8ca6/lib/air/class.js#L76-L88
44,841
DScheglov/merest
lib/controllers/del-by-id.js
delById
function delById(req, res, next) { res.__apiMethod = 'delete'; var self = this; var id = req.params.id; var filter = this.option('delete', 'filter'); if (filter instanceof Function) filter = filter.call(this, req); var query = extend({_id: id}, filter); this.model.remove(query).exec(function(err, affected) { if (err) return next(err); if (affected.result.n == 0) { return next(new ModelAPIError( 404, `The ${self.nameSingle} was not found by ${id}` )); } res.status(200); return res.json({}); }); }
javascript
function delById(req, res, next) { res.__apiMethod = 'delete'; var self = this; var id = req.params.id; var filter = this.option('delete', 'filter'); if (filter instanceof Function) filter = filter.call(this, req); var query = extend({_id: id}, filter); this.model.remove(query).exec(function(err, affected) { if (err) return next(err); if (affected.result.n == 0) { return next(new ModelAPIError( 404, `The ${self.nameSingle} was not found by ${id}` )); } res.status(200); return res.json({}); }); }
[ "function", "delById", "(", "req", ",", "res", ",", "next", ")", "{", "res", ".", "__apiMethod", "=", "'delete'", ";", "var", "self", "=", "this", ";", "var", "id", "=", "req", ".", "params", ".", "id", ";", "var", "filter", "=", "this", ".", "option", "(", "'delete'", ",", "'filter'", ")", ";", "if", "(", "filter", "instanceof", "Function", ")", "filter", "=", "filter", ".", "call", "(", "this", ",", "req", ")", ";", "var", "query", "=", "extend", "(", "{", "_id", ":", "id", "}", ",", "filter", ")", ";", "this", ".", "model", ".", "remove", "(", "query", ")", ".", "exec", "(", "function", "(", "err", ",", "affected", ")", "{", "if", "(", "err", ")", "return", "next", "(", "err", ")", ";", "if", "(", "affected", ".", "result", ".", "n", "==", "0", ")", "{", "return", "next", "(", "new", "ModelAPIError", "(", "404", ",", "`", "${", "self", ".", "nameSingle", "}", "${", "id", "}", "`", ")", ")", ";", "}", "res", ".", "status", "(", "200", ")", ";", "return", "res", ".", "json", "(", "{", "}", ")", ";", "}", ")", ";", "}" ]
delById - controller that deletes a model instance @param {express.Request} req the http(s) request @param {express.Response} res the http(s) response @param {Function} next the callback should be called if controller fails @memberof ModelAPIRouter
[ "delById", "-", "controller", "that", "deletes", "a", "model", "instance" ]
d39e7ef0d56236247773467e9bfe83cb128ebc01
https://github.com/DScheglov/merest/blob/d39e7ef0d56236247773467e9bfe83cb128ebc01/lib/controllers/del-by-id.js#L13-L30
44,842
jldec/pub-generator
update.js
labelFragment
function labelFragment(fragment, func, source) { // use 'in' to handle case where delim is set to '' var leftDelim = 'leftDelim' in source ? source.leftDelim : '----'; var rightDelim = 'rightDelim' in source ? source.rightDelim : '----'; var headerDelim = 'headerDelim' in source ? source.headerDelim : ''; if (fragment._hdr) { var lines = fragment._hdr.split('\n'); var fl = lines[0]; // sanity check - make sure this fragments does not have a (func) label already var lbl = parseLabel(fl.slice(leftDelim.length, fl.length - rightDelim.length), false, source.slugify); if (lbl.func) return false; lines[0] = fl.slice(0, fl.length - rightDelim.length) + ' (' + func + ') ' + rightDelim; fragment._hdr = lines.join('\n'); } else { fragment._hdr = leftDelim + ' (' + func + ') ' + rightDelim + '\n' + headerDelim + '\n'; } return true; }
javascript
function labelFragment(fragment, func, source) { // use 'in' to handle case where delim is set to '' var leftDelim = 'leftDelim' in source ? source.leftDelim : '----'; var rightDelim = 'rightDelim' in source ? source.rightDelim : '----'; var headerDelim = 'headerDelim' in source ? source.headerDelim : ''; if (fragment._hdr) { var lines = fragment._hdr.split('\n'); var fl = lines[0]; // sanity check - make sure this fragments does not have a (func) label already var lbl = parseLabel(fl.slice(leftDelim.length, fl.length - rightDelim.length), false, source.slugify); if (lbl.func) return false; lines[0] = fl.slice(0, fl.length - rightDelim.length) + ' (' + func + ') ' + rightDelim; fragment._hdr = lines.join('\n'); } else { fragment._hdr = leftDelim + ' (' + func + ') ' + rightDelim + '\n' + headerDelim + '\n'; } return true; }
[ "function", "labelFragment", "(", "fragment", ",", "func", ",", "source", ")", "{", "// use 'in' to handle case where delim is set to ''", "var", "leftDelim", "=", "'leftDelim'", "in", "source", "?", "source", ".", "leftDelim", ":", "'----'", ";", "var", "rightDelim", "=", "'rightDelim'", "in", "source", "?", "source", ".", "rightDelim", ":", "'----'", ";", "var", "headerDelim", "=", "'headerDelim'", "in", "source", "?", "source", ".", "headerDelim", ":", "''", ";", "if", "(", "fragment", ".", "_hdr", ")", "{", "var", "lines", "=", "fragment", ".", "_hdr", ".", "split", "(", "'\\n'", ")", ";", "var", "fl", "=", "lines", "[", "0", "]", ";", "// sanity check - make sure this fragments does not have a (func) label already", "var", "lbl", "=", "parseLabel", "(", "fl", ".", "slice", "(", "leftDelim", ".", "length", ",", "fl", ".", "length", "-", "rightDelim", ".", "length", ")", ",", "false", ",", "source", ".", "slugify", ")", ";", "if", "(", "lbl", ".", "func", ")", "return", "false", ";", "lines", "[", "0", "]", "=", "fl", ".", "slice", "(", "0", ",", "fl", ".", "length", "-", "rightDelim", ".", "length", ")", "+", "' ('", "+", "func", "+", "') '", "+", "rightDelim", ";", "fragment", ".", "_hdr", "=", "lines", ".", "join", "(", "'\\n'", ")", ";", "}", "else", "{", "fragment", ".", "_hdr", "=", "leftDelim", "+", "' ('", "+", "func", "+", "') '", "+", "rightDelim", "+", "'\\n'", "+", "headerDelim", "+", "'\\n'", ";", "}", "return", "true", ";", "}" ]
should move into util or parsefragments.js
[ "should", "move", "into", "util", "or", "parsefragments", ".", "js" ]
524081509921ac8cb897753142324d61e10afdf3
https://github.com/jldec/pub-generator/blob/524081509921ac8cb897753142324d61e10afdf3/update.js#L158-L181
44,843
jldec/pub-generator
update.js
clientSave
function clientSave() { u.each(sources, function(source) { var dirtyFiles = u.filter(source.files, function(file) { if (file._dirty) { // 1 means unsaved, 2 means saving file._dirty = 2; // side effect of filter return true; } return false; }); if (dirtyFiles.length) { var files = u.map(dirtyFiles, generator.serializeFile); debug('clientSave %s files, %s...', files.length, files[0].text.slice(0,200)); // static save from browser directly to source if (opts.staticHost && source.staticSrc && source.src) { // NOTE: subtle difference in data compared to httpClient.put() source.src.put(files, function(err, savedFiles) { if (err || (u.size(savedFiles) !== u.size(dirtyFiles))) { // notify user on save errors return notify('error saving files, please check your internet connection'); } u.each(dirtyFiles, function(file) { // no collision detection support with static saves (for now) file._oldtext = file.text; // only mark as clean if unchanged while waiting for save if (file._dirty === 2) { delete file._dirty; } }); return source.verbose && notify(u.size(savedFiles) + ' file(s) saved'); }); } // normal (non-static) save from browser to pub-server else { httpClient.put({ source:source.name, files:files }, function(err, savedFiles) { if (err || (u.size(savedFiles) !== u.size(dirtyFiles))) { if (err) { log(err); } // notify user on save errors return notify('error saving files, please check your internet connection'); } u.each(dirtyFiles, function(file, idx) { var savedFile = savedFiles[idx]; if (typeof savedFile !== 'object') { // most likely a collision - must notify user return notify('error saving file: ' + savedFile); } // preserve for next update file._oldtext = savedFile.text; // only mark as clean if unchanged while waiting for save if (file._dirty === 2) { delete file._dirty; } }); return source.verbose && notify(u.size(savedFiles) + ' file(s) saved'); }); } } }); }
javascript
function clientSave() { u.each(sources, function(source) { var dirtyFiles = u.filter(source.files, function(file) { if (file._dirty) { // 1 means unsaved, 2 means saving file._dirty = 2; // side effect of filter return true; } return false; }); if (dirtyFiles.length) { var files = u.map(dirtyFiles, generator.serializeFile); debug('clientSave %s files, %s...', files.length, files[0].text.slice(0,200)); // static save from browser directly to source if (opts.staticHost && source.staticSrc && source.src) { // NOTE: subtle difference in data compared to httpClient.put() source.src.put(files, function(err, savedFiles) { if (err || (u.size(savedFiles) !== u.size(dirtyFiles))) { // notify user on save errors return notify('error saving files, please check your internet connection'); } u.each(dirtyFiles, function(file) { // no collision detection support with static saves (for now) file._oldtext = file.text; // only mark as clean if unchanged while waiting for save if (file._dirty === 2) { delete file._dirty; } }); return source.verbose && notify(u.size(savedFiles) + ' file(s) saved'); }); } // normal (non-static) save from browser to pub-server else { httpClient.put({ source:source.name, files:files }, function(err, savedFiles) { if (err || (u.size(savedFiles) !== u.size(dirtyFiles))) { if (err) { log(err); } // notify user on save errors return notify('error saving files, please check your internet connection'); } u.each(dirtyFiles, function(file, idx) { var savedFile = savedFiles[idx]; if (typeof savedFile !== 'object') { // most likely a collision - must notify user return notify('error saving file: ' + savedFile); } // preserve for next update file._oldtext = savedFile.text; // only mark as clean if unchanged while waiting for save if (file._dirty === 2) { delete file._dirty; } }); return source.verbose && notify(u.size(savedFiles) + ' file(s) saved'); }); } } }); }
[ "function", "clientSave", "(", ")", "{", "u", ".", "each", "(", "sources", ",", "function", "(", "source", ")", "{", "var", "dirtyFiles", "=", "u", ".", "filter", "(", "source", ".", "files", ",", "function", "(", "file", ")", "{", "if", "(", "file", ".", "_dirty", ")", "{", "// 1 means unsaved, 2 means saving", "file", ".", "_dirty", "=", "2", ";", "// side effect of filter", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "if", "(", "dirtyFiles", ".", "length", ")", "{", "var", "files", "=", "u", ".", "map", "(", "dirtyFiles", ",", "generator", ".", "serializeFile", ")", ";", "debug", "(", "'clientSave %s files, %s...'", ",", "files", ".", "length", ",", "files", "[", "0", "]", ".", "text", ".", "slice", "(", "0", ",", "200", ")", ")", ";", "// static save from browser directly to source", "if", "(", "opts", ".", "staticHost", "&&", "source", ".", "staticSrc", "&&", "source", ".", "src", ")", "{", "// NOTE: subtle difference in data compared to httpClient.put()", "source", ".", "src", ".", "put", "(", "files", ",", "function", "(", "err", ",", "savedFiles", ")", "{", "if", "(", "err", "||", "(", "u", ".", "size", "(", "savedFiles", ")", "!==", "u", ".", "size", "(", "dirtyFiles", ")", ")", ")", "{", "// notify user on save errors", "return", "notify", "(", "'error saving files, please check your internet connection'", ")", ";", "}", "u", ".", "each", "(", "dirtyFiles", ",", "function", "(", "file", ")", "{", "// no collision detection support with static saves (for now)", "file", ".", "_oldtext", "=", "file", ".", "text", ";", "// only mark as clean if unchanged while waiting for save", "if", "(", "file", ".", "_dirty", "===", "2", ")", "{", "delete", "file", ".", "_dirty", ";", "}", "}", ")", ";", "return", "source", ".", "verbose", "&&", "notify", "(", "u", ".", "size", "(", "savedFiles", ")", "+", "' file(s) saved'", ")", ";", "}", ")", ";", "}", "// normal (non-static) save from browser to pub-server", "else", "{", "httpClient", ".", "put", "(", "{", "source", ":", "source", ".", "name", ",", "files", ":", "files", "}", ",", "function", "(", "err", ",", "savedFiles", ")", "{", "if", "(", "err", "||", "(", "u", ".", "size", "(", "savedFiles", ")", "!==", "u", ".", "size", "(", "dirtyFiles", ")", ")", ")", "{", "if", "(", "err", ")", "{", "log", "(", "err", ")", ";", "}", "// notify user on save errors", "return", "notify", "(", "'error saving files, please check your internet connection'", ")", ";", "}", "u", ".", "each", "(", "dirtyFiles", ",", "function", "(", "file", ",", "idx", ")", "{", "var", "savedFile", "=", "savedFiles", "[", "idx", "]", ";", "if", "(", "typeof", "savedFile", "!==", "'object'", ")", "{", "// most likely a collision - must notify user", "return", "notify", "(", "'error saving file: '", "+", "savedFile", ")", ";", "}", "// preserve for next update", "file", ".", "_oldtext", "=", "savedFile", ".", "text", ";", "// only mark as clean if unchanged while waiting for save", "if", "(", "file", ".", "_dirty", "===", "2", ")", "{", "delete", "file", ".", "_dirty", ";", "}", "}", ")", ";", "return", "source", ".", "verbose", "&&", "notify", "(", "u", ".", "size", "(", "savedFiles", ")", "+", "' file(s) saved'", ")", ";", "}", ")", ";", "}", "}", "}", ")", ";", "}" ]
clientSave currently used only in browser
[ "clientSave", "currently", "used", "only", "in", "browser" ]
524081509921ac8cb897753142324d61e10afdf3
https://github.com/jldec/pub-generator/blob/524081509921ac8cb897753142324d61e10afdf3/update.js#L184-L258
44,844
jldec/pub-generator
update.js
reloadSources
function reloadSources(names) { names = u.isArray(names) ? names : names ? [names] : u.keys(opts.source$); var results = []; u.each(names, function(name) { var source = opts.source$[name]; if (source) { source._reloadFromSource = true; results.push(name); } else { results.push(log('reloadSources unknown source ' + name)); } }); generator.reload(); // throttled return results; }
javascript
function reloadSources(names) { names = u.isArray(names) ? names : names ? [names] : u.keys(opts.source$); var results = []; u.each(names, function(name) { var source = opts.source$[name]; if (source) { source._reloadFromSource = true; results.push(name); } else { results.push(log('reloadSources unknown source ' + name)); } }); generator.reload(); // throttled return results; }
[ "function", "reloadSources", "(", "names", ")", "{", "names", "=", "u", ".", "isArray", "(", "names", ")", "?", "names", ":", "names", "?", "[", "names", "]", ":", "u", ".", "keys", "(", "opts", ".", "source$", ")", ";", "var", "results", "=", "[", "]", ";", "u", ".", "each", "(", "names", ",", "function", "(", "name", ")", "{", "var", "source", "=", "opts", ".", "source$", "[", "name", "]", ";", "if", "(", "source", ")", "{", "source", ".", "_reloadFromSource", "=", "true", ";", "results", ".", "push", "(", "name", ")", ";", "}", "else", "{", "results", ".", "push", "(", "log", "(", "'reloadSources unknown source '", "+", "name", ")", ")", ";", "}", "}", ")", ";", "generator", ".", "reload", "(", ")", ";", "// throttled", "return", "results", ";", "}" ]
trigger reload from source input = string or array of source names, nothing => all
[ "trigger", "reload", "from", "source", "input", "=", "string", "or", "array", "of", "source", "names", "nothing", "=", ">", "all" ]
524081509921ac8cb897753142324d61e10afdf3
https://github.com/jldec/pub-generator/blob/524081509921ac8cb897753142324d61e10afdf3/update.js#L324-L344
44,845
bigpipe/alcatraz
index.js
Alcatraz
function Alcatraz(method, source, domain) { if (!(this instanceof Alcatraz)) return new Alcatraz(method, source); this.domain = domain || ('undefined' !== typeof document ? document.domain : ''); this.method = 'if ('+method+') '+ method; this.source = source; this.compiled = null; }
javascript
function Alcatraz(method, source, domain) { if (!(this instanceof Alcatraz)) return new Alcatraz(method, source); this.domain = domain || ('undefined' !== typeof document ? document.domain : ''); this.method = 'if ('+method+') '+ method; this.source = source; this.compiled = null; }
[ "function", "Alcatraz", "(", "method", ",", "source", ",", "domain", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Alcatraz", ")", ")", "return", "new", "Alcatraz", "(", "method", ",", "source", ")", ";", "this", ".", "domain", "=", "domain", "||", "(", "'undefined'", "!==", "typeof", "document", "?", "document", ".", "domain", ":", "''", ")", ";", "this", ".", "method", "=", "'if ('", "+", "method", "+", "') '", "+", "method", ";", "this", ".", "source", "=", "source", ";", "this", ".", "compiled", "=", "null", ";", "}" ]
Alcatraz is our source code sandboxing. @constructor @param {String} method The global/method name that processes messages. @param {String} source The actual code. @param {String} domain The domain name. @api private
[ "Alcatraz", "is", "our", "source", "code", "sandboxing", "." ]
d754bb8607e9c75810b7ff5127d8d30393cb2f34
https://github.com/bigpipe/alcatraz/blob/d754bb8607e9c75810b7ff5127d8d30393cb2f34/index.js#L12-L19
44,846
bigpipe/alcatraz
index.js
polyconsole
function polyconsole(method) { var attach = { debug: 1, error: 1, log: 1, warn: 1 }; // // Ensure that this host environment always has working console. // global.console[method] = function polyfilled() { var args = Array.prototype.slice.call(arguments, 0); // // If the host supports this given method natively, execute it. // if (method in fconsole) fconsole[method].apply(fconsole, args); // // Proxy messages to the container. // this._alcatraz_method_({ attach: method in attach, type: 'console', scope: method, args: args }); }; }
javascript
function polyconsole(method) { var attach = { debug: 1, error: 1, log: 1, warn: 1 }; // // Ensure that this host environment always has working console. // global.console[method] = function polyfilled() { var args = Array.prototype.slice.call(arguments, 0); // // If the host supports this given method natively, execute it. // if (method in fconsole) fconsole[method].apply(fconsole, args); // // Proxy messages to the container. // this._alcatraz_method_({ attach: method in attach, type: 'console', scope: method, args: args }); }; }
[ "function", "polyconsole", "(", "method", ")", "{", "var", "attach", "=", "{", "debug", ":", "1", ",", "error", ":", "1", ",", "log", ":", "1", ",", "warn", ":", "1", "}", ";", "//", "// Ensure that this host environment always has working console.", "//", "global", ".", "console", "[", "method", "]", "=", "function", "polyfilled", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "//", "// If the host supports this given method natively, execute it.", "//", "if", "(", "method", "in", "fconsole", ")", "fconsole", "[", "method", "]", ".", "apply", "(", "fconsole", ",", "args", ")", ";", "//", "// Proxy messages to the container.", "//", "this", ".", "_alcatraz_method_", "(", "{", "attach", ":", "method", "in", "attach", ",", "type", ":", "'console'", ",", "scope", ":", "method", ",", "args", ":", "args", "}", ")", ";", "}", ";", "}" ]
Helper method to polyfill our global console method so we can proxy it's usage to the @param {String} method The console method we want to polyfill. @api private
[ "Helper", "method", "to", "polyfill", "our", "global", "console", "method", "so", "we", "can", "proxy", "it", "s", "usage", "to", "the" ]
d754bb8607e9c75810b7ff5127d8d30393cb2f34
https://github.com/bigpipe/alcatraz/blob/d754bb8607e9c75810b7ff5127d8d30393cb2f34/index.js#L138-L162
44,847
haraldrudell/nodegod
lib/linearcalendar.js
getDate
function getDate(ymValue) { checkNumber(ymValue) var utcFullYear = Math.floor(ymValue / monthsPerYear) + zeroUtcFullYear var utcMonth = modFix(Math.floor(ymValue), monthsPerYear) + zeroUtcMonth return new Date(Date.UTC(utcFullYear, utcMonth)) }
javascript
function getDate(ymValue) { checkNumber(ymValue) var utcFullYear = Math.floor(ymValue / monthsPerYear) + zeroUtcFullYear var utcMonth = modFix(Math.floor(ymValue), monthsPerYear) + zeroUtcMonth return new Date(Date.UTC(utcFullYear, utcMonth)) }
[ "function", "getDate", "(", "ymValue", ")", "{", "checkNumber", "(", "ymValue", ")", "var", "utcFullYear", "=", "Math", ".", "floor", "(", "ymValue", "/", "monthsPerYear", ")", "+", "zeroUtcFullYear", "var", "utcMonth", "=", "modFix", "(", "Math", ".", "floor", "(", "ymValue", ")", ",", "monthsPerYear", ")", "+", "zeroUtcMonth", "return", "new", "Date", "(", "Date", ".", "UTC", "(", "utcFullYear", ",", "utcMonth", ")", ")", "}" ]
convert linearValue to Date object
[ "convert", "linearValue", "to", "Date", "object" ]
3be4fb280fb18e0ec0a1c1a8fea3254d92f00b21
https://github.com/haraldrudell/nodegod/blob/3be4fb280fb18e0ec0a1c1a8fea3254d92f00b21/lib/linearcalendar.js#L35-L40
44,848
haraldrudell/nodegod
lib/linearcalendar.js
encodeDate
function encodeDate(date) { if (!(date instanceof Date)) throw new Error('Value not Date: ' + date) return (date.getUTCFullYear() * monthsPerYear + date.getUTCMonth()) - yearMonthZero }
javascript
function encodeDate(date) { if (!(date instanceof Date)) throw new Error('Value not Date: ' + date) return (date.getUTCFullYear() * monthsPerYear + date.getUTCMonth()) - yearMonthZero }
[ "function", "encodeDate", "(", "date", ")", "{", "if", "(", "!", "(", "date", "instanceof", "Date", ")", ")", "throw", "new", "Error", "(", "'Value not Date: '", "+", "date", ")", "return", "(", "date", ".", "getUTCFullYear", "(", ")", "*", "monthsPerYear", "+", "date", ".", "getUTCMonth", "(", ")", ")", "-", "yearMonthZero", "}" ]
get linearValue from Date object
[ "get", "linearValue", "from", "Date", "object" ]
3be4fb280fb18e0ec0a1c1a8fea3254d92f00b21
https://github.com/haraldrudell/nodegod/blob/3be4fb280fb18e0ec0a1c1a8fea3254d92f00b21/lib/linearcalendar.js#L43-L46
44,849
ryb73/dealers-choice-meta
packages/server/lib/game-managers/choice-provider/rock-paper-scissors.js
handleIt
function handleIt(cb) { callbacks = cb; broadcast = callbacks.broadcast; let msg = { cmd: MessageType.RockPaperScissors, handlerId: id }; broadcast("action", msg); // Return a promise for the result deferred = q.defer(); return deferred.promise; }
javascript
function handleIt(cb) { callbacks = cb; broadcast = callbacks.broadcast; let msg = { cmd: MessageType.RockPaperScissors, handlerId: id }; broadcast("action", msg); // Return a promise for the result deferred = q.defer(); return deferred.promise; }
[ "function", "handleIt", "(", "cb", ")", "{", "callbacks", "=", "cb", ";", "broadcast", "=", "callbacks", ".", "broadcast", ";", "let", "msg", "=", "{", "cmd", ":", "MessageType", ".", "RockPaperScissors", ",", "handlerId", ":", "id", "}", ";", "broadcast", "(", "\"action\"", ",", "msg", ")", ";", "// Return a promise for the result", "deferred", "=", "q", ".", "defer", "(", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Returns a promise for the ID of the player who won the game
[ "Returns", "a", "promise", "for", "the", "ID", "of", "the", "player", "who", "won", "the", "game" ]
4632e8897c832b01d944a340cf87d5c807809925
https://github.com/ryb73/dealers-choice-meta/blob/4632e8897c832b01d944a340cf87d5c807809925/packages/server/lib/game-managers/choice-provider/rock-paper-scissors.js#L34-L47
44,850
ryb73/dealers-choice-meta
packages/server/lib/game-managers/choice-provider/rock-paper-scissors.js
beginCountdown
function beginCountdown() { let msg = { cmd: MessageType.RpsCountdown }; broadcast("action", msg); q.delay(COUNTDOWN_DELAY).done(determineWinner); }
javascript
function beginCountdown() { let msg = { cmd: MessageType.RpsCountdown }; broadcast("action", msg); q.delay(COUNTDOWN_DELAY).done(determineWinner); }
[ "function", "beginCountdown", "(", ")", "{", "let", "msg", "=", "{", "cmd", ":", "MessageType", ".", "RpsCountdown", "}", ";", "broadcast", "(", "\"action\"", ",", "msg", ")", ";", "q", ".", "delay", "(", "COUNTDOWN_DELAY", ")", ".", "done", "(", "determineWinner", ")", ";", "}" ]
This rock-paper-scissors game is SERIOUS
[ "This", "rock", "-", "paper", "-", "scissors", "game", "is", "SERIOUS" ]
4632e8897c832b01d944a340cf87d5c807809925
https://github.com/ryb73/dealers-choice-meta/blob/4632e8897c832b01d944a340cf87d5c807809925/packages/server/lib/game-managers/choice-provider/rock-paper-scissors.js#L63-L70
44,851
ryb73/dealers-choice-meta
packages/server/lib/game-managers/choice-provider/rock-paper-scissors.js
restartGame
function restartGame(players) { // Replace the current instance with a new instance let newGame = new RockPaperScissors(game, players, winCounter, id); proxy.swap(newGame); q.delay(RESULTS_DELAY) .done(function() { deferred.resolve(newGame.handleIt(callbacks)); }); }
javascript
function restartGame(players) { // Replace the current instance with a new instance let newGame = new RockPaperScissors(game, players, winCounter, id); proxy.swap(newGame); q.delay(RESULTS_DELAY) .done(function() { deferred.resolve(newGame.handleIt(callbacks)); }); }
[ "function", "restartGame", "(", "players", ")", "{", "// Replace the current instance with a new instance", "let", "newGame", "=", "new", "RockPaperScissors", "(", "game", ",", "players", ",", "winCounter", ",", "id", ")", ";", "proxy", ".", "swap", "(", "newGame", ")", ";", "q", ".", "delay", "(", "RESULTS_DELAY", ")", ".", "done", "(", "function", "(", ")", "{", "deferred", ".", "resolve", "(", "newGame", ".", "handleIt", "(", "callbacks", ")", ")", ";", "}", ")", ";", "}" ]
Starts a new game of RPS with the given array of players. A delay is added so that the client has time to show the results to the user.
[ "Starts", "a", "new", "game", "of", "RPS", "with", "the", "given", "array", "of", "players", ".", "A", "delay", "is", "added", "so", "that", "the", "client", "has", "time", "to", "show", "the", "results", "to", "the", "user", "." ]
4632e8897c832b01d944a340cf87d5c807809925
https://github.com/ryb73/dealers-choice-meta/blob/4632e8897c832b01d944a340cf87d5c807809925/packages/server/lib/game-managers/choice-provider/rock-paper-scissors.js#L106-L115
44,852
nodeca/hike-js
lib/shared.js
containsPath
function containsPath(self, dirname) { return self.__paths__.some(function(p) { return p === dirname.substr(0, p.length); }); }
javascript
function containsPath(self, dirname) { return self.__paths__.some(function(p) { return p === dirname.substr(0, p.length); }); }
[ "function", "containsPath", "(", "self", ",", "dirname", ")", "{", "return", "self", ".", "__paths__", ".", "some", "(", "function", "(", "p", ")", "{", "return", "p", "===", "dirname", ".", "substr", "(", "0", ",", "p", ".", "length", ")", ";", "}", ")", ";", "}" ]
Returns true if `dirname` is a subdirectory of any of the `paths`
[ "Returns", "true", "if", "dirname", "is", "a", "subdirectory", "of", "any", "of", "the", "paths" ]
8d9b71473c7b1fa46991738b02e8f1e60b843d99
https://github.com/nodeca/hike-js/blob/8d9b71473c7b1fa46991738b02e8f1e60b843d99/lib/shared.js#L59-L63
44,853
nodeca/hike-js
lib/shared.js
sortMatches
function sortMatches(self, matches, basename) { var weights = {}; var ext_name = path.extname(basename); var aliases = has(self.__aliases__, ext_name) ? self.__aliases__[ext_name] : []; matches.forEach(function(match) { // XXX: this doesn't work well with aliases // i.e. entry=index.php, extnames=index.html var extnames = match.replace(basename, '').split('.'); weights[match] = extnames.reduce(function(sum, ext) { if (!ext) { return sum; } ext = '.' + ext; if (self.__extensions__.indexOf(ext) >= 0) { return sum + self.__extensions__.indexOf(ext) + 1; } if (aliases.indexOf(ext) >= 0) { return sum + aliases.indexOf(ext) + 11; } return sum; }, 0); }); return matches.sort(function(a, b) { return weights[a] > weights[b] ? 1 : -1; }); }
javascript
function sortMatches(self, matches, basename) { var weights = {}; var ext_name = path.extname(basename); var aliases = has(self.__aliases__, ext_name) ? self.__aliases__[ext_name] : []; matches.forEach(function(match) { // XXX: this doesn't work well with aliases // i.e. entry=index.php, extnames=index.html var extnames = match.replace(basename, '').split('.'); weights[match] = extnames.reduce(function(sum, ext) { if (!ext) { return sum; } ext = '.' + ext; if (self.__extensions__.indexOf(ext) >= 0) { return sum + self.__extensions__.indexOf(ext) + 1; } if (aliases.indexOf(ext) >= 0) { return sum + aliases.indexOf(ext) + 11; } return sum; }, 0); }); return matches.sort(function(a, b) { return weights[a] > weights[b] ? 1 : -1; }); }
[ "function", "sortMatches", "(", "self", ",", "matches", ",", "basename", ")", "{", "var", "weights", "=", "{", "}", ";", "var", "ext_name", "=", "path", ".", "extname", "(", "basename", ")", ";", "var", "aliases", "=", "has", "(", "self", ".", "__aliases__", ",", "ext_name", ")", "?", "self", ".", "__aliases__", "[", "ext_name", "]", ":", "[", "]", ";", "matches", ".", "forEach", "(", "function", "(", "match", ")", "{", "// XXX: this doesn't work well with aliases", "// i.e. entry=index.php, extnames=index.html", "var", "extnames", "=", "match", ".", "replace", "(", "basename", ",", "''", ")", ".", "split", "(", "'.'", ")", ";", "weights", "[", "match", "]", "=", "extnames", ".", "reduce", "(", "function", "(", "sum", ",", "ext", ")", "{", "if", "(", "!", "ext", ")", "{", "return", "sum", ";", "}", "ext", "=", "'.'", "+", "ext", ";", "if", "(", "self", ".", "__extensions__", ".", "indexOf", "(", "ext", ")", ">=", "0", ")", "{", "return", "sum", "+", "self", ".", "__extensions__", ".", "indexOf", "(", "ext", ")", "+", "1", ";", "}", "if", "(", "aliases", ".", "indexOf", "(", "ext", ")", ">=", "0", ")", "{", "return", "sum", "+", "aliases", ".", "indexOf", "(", "ext", ")", "+", "11", ";", "}", "return", "sum", ";", "}", ",", "0", ")", ";", "}", ")", ";", "return", "matches", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "weights", "[", "a", "]", ">", "weights", "[", "b", "]", "?", "1", ":", "-", "1", ";", "}", ")", ";", "}" ]
Sorts candidate matches by their extension priority. Extensions in the front of the `extensions` carry more weight.
[ "Sorts", "candidate", "matches", "by", "their", "extension", "priority", ".", "Extensions", "in", "the", "front", "of", "the", "extensions", "carry", "more", "weight", "." ]
8d9b71473c7b1fa46991738b02e8f1e60b843d99
https://github.com/nodeca/hike-js/blob/8d9b71473c7b1fa46991738b02e8f1e60b843d99/lib/shared.js#L92-L126
44,854
nodeca/hike-js
lib/shared.js
match
function match(self, dirname, basename, callback) { var pathname, stats, pattern, matches; pattern = patternFor(self, basename); matches = self.entries(dirname).filter(function(m) { return pattern.test(m); }); matches = sortMatches(self, matches, basename); while (matches.length) { pathname = path.join(dirname, matches.shift()); stats = self.stat(pathname); if (stats && stats.isFile() && callback(pathname)) { return pathname; } } }
javascript
function match(self, dirname, basename, callback) { var pathname, stats, pattern, matches; pattern = patternFor(self, basename); matches = self.entries(dirname).filter(function(m) { return pattern.test(m); }); matches = sortMatches(self, matches, basename); while (matches.length) { pathname = path.join(dirname, matches.shift()); stats = self.stat(pathname); if (stats && stats.isFile() && callback(pathname)) { return pathname; } } }
[ "function", "match", "(", "self", ",", "dirname", ",", "basename", ",", "callback", ")", "{", "var", "pathname", ",", "stats", ",", "pattern", ",", "matches", ";", "pattern", "=", "patternFor", "(", "self", ",", "basename", ")", ";", "matches", "=", "self", ".", "entries", "(", "dirname", ")", ".", "filter", "(", "function", "(", "m", ")", "{", "return", "pattern", ".", "test", "(", "m", ")", ";", "}", ")", ";", "matches", "=", "sortMatches", "(", "self", ",", "matches", ",", "basename", ")", ";", "while", "(", "matches", ".", "length", ")", "{", "pathname", "=", "path", ".", "join", "(", "dirname", ",", "matches", ".", "shift", "(", ")", ")", ";", "stats", "=", "self", ".", "stat", "(", "pathname", ")", ";", "if", "(", "stats", "&&", "stats", ".", "isFile", "(", ")", "&&", "callback", "(", "pathname", ")", ")", "{", "return", "pathname", ";", "}", "}", "}" ]
Checks if the path is actually on the file system and performs any syscalls if necessary.
[ "Checks", "if", "the", "path", "is", "actually", "on", "the", "file", "system", "and", "performs", "any", "syscalls", "if", "necessary", "." ]
8d9b71473c7b1fa46991738b02e8f1e60b843d99
https://github.com/nodeca/hike-js/blob/8d9b71473c7b1fa46991738b02e8f1e60b843d99/lib/shared.js#L130-L145
44,855
vadr-vr/VR-Analytics-JSCore
js/dataCollector/dataCollector.js
setPositionCallback
function setPositionCallback(positionFunction){ if (typeof(positionFunction) == 'function'){ orientationCollector.setPositionCallback(positionFunction); callbacks.positionCallback = positionFunction; } else logger.warn('Trying to set a non function object as position callback'); }
javascript
function setPositionCallback(positionFunction){ if (typeof(positionFunction) == 'function'){ orientationCollector.setPositionCallback(positionFunction); callbacks.positionCallback = positionFunction; } else logger.warn('Trying to set a non function object as position callback'); }
[ "function", "setPositionCallback", "(", "positionFunction", ")", "{", "if", "(", "typeof", "(", "positionFunction", ")", "==", "'function'", ")", "{", "orientationCollector", ".", "setPositionCallback", "(", "positionFunction", ")", ";", "callbacks", ".", "positionCallback", "=", "positionFunction", ";", "}", "else", "logger", ".", "warn", "(", "'Trying to set a non function object as position callback'", ")", ";", "}" ]
Sets the function to call when setting position @memberof DataCollector @param {function} positionFunction
[ "Sets", "the", "function", "to", "call", "when", "setting", "position" ]
7e4a493c824c2c1716360dcb6a3bfecfede5df3b
https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/dataCollector/dataCollector.js#L65-L76
44,856
vadr-vr/VR-Analytics-JSCore
js/dataCollector/dataCollector.js
configureEventCollection
function configureEventCollection(eventType, collectionStatus, timePeriod){ if (eventType in dataConfig){ // check that collection status is present as true or false collectionStatus = collectionStatus == false ? false : true; dataConfig[eventType].status = collectionStatus; if(!isNaN(timePeriod)){ timePeriod = parseInt(timePeriod); if(timePeriod > 0){ dataConfig[eventType].timePeriod = timePeriod; }else{ dataConfig[eventType].status = false; } } } }
javascript
function configureEventCollection(eventType, collectionStatus, timePeriod){ if (eventType in dataConfig){ // check that collection status is present as true or false collectionStatus = collectionStatus == false ? false : true; dataConfig[eventType].status = collectionStatus; if(!isNaN(timePeriod)){ timePeriod = parseInt(timePeriod); if(timePeriod > 0){ dataConfig[eventType].timePeriod = timePeriod; }else{ dataConfig[eventType].status = false; } } } }
[ "function", "configureEventCollection", "(", "eventType", ",", "collectionStatus", ",", "timePeriod", ")", "{", "if", "(", "eventType", "in", "dataConfig", ")", "{", "// check that collection status is present as true or false", "collectionStatus", "=", "collectionStatus", "==", "false", "?", "false", ":", "true", ";", "dataConfig", "[", "eventType", "]", ".", "status", "=", "collectionStatus", ";", "if", "(", "!", "isNaN", "(", "timePeriod", ")", ")", "{", "timePeriod", "=", "parseInt", "(", "timePeriod", ")", ";", "if", "(", "timePeriod", ">", "0", ")", "{", "dataConfig", "[", "eventType", "]", ".", "timePeriod", "=", "timePeriod", ";", "}", "else", "{", "dataConfig", "[", "eventType", "]", ".", "status", "=", "false", ";", "}", "}", "}", "}" ]
Configures which events to collect by default and by what frequency @memberof DataCollector @param {string} eventType type of event - Orientation, Gaze, Performance @param {boolean} collectionStatus set to true if you want to collect the event @param {number} timePeriod time period in milliseconds after which to collect the data
[ "Configures", "which", "events", "to", "collect", "by", "default", "and", "by", "what", "frequency" ]
7e4a493c824c2c1716360dcb6a3bfecfede5df3b
https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/dataCollector/dataCollector.js#L121-L146
44,857
vadr-vr/VR-Analytics-JSCore
js/dataCollector/dataCollector.js
tick
function tick(){ performanceCollector.tick(); const useMedia = dataManager.getMediaState(); const playTimeSinceStart = timeManager.getPlayTimeSinceStart(); for (let key in dataConfig){ const infoDict = dataConfig[key]; if (infoDict.status && playTimeSinceStart - infoDict.lastFetchTime > infoDict.timePeriod){ const timeDifferene = playTimeSinceStart - infoDict.lastFetchTime; if (useMedia) _setEvents(infoDict.calculator.getMediaEvents(timeDifferene)); // always collecting default events _setEvents(infoDict.calculator.getEvents(timeDifferene)); infoDict.lastFetchTime = playTimeSinceStart; } } }
javascript
function tick(){ performanceCollector.tick(); const useMedia = dataManager.getMediaState(); const playTimeSinceStart = timeManager.getPlayTimeSinceStart(); for (let key in dataConfig){ const infoDict = dataConfig[key]; if (infoDict.status && playTimeSinceStart - infoDict.lastFetchTime > infoDict.timePeriod){ const timeDifferene = playTimeSinceStart - infoDict.lastFetchTime; if (useMedia) _setEvents(infoDict.calculator.getMediaEvents(timeDifferene)); // always collecting default events _setEvents(infoDict.calculator.getEvents(timeDifferene)); infoDict.lastFetchTime = playTimeSinceStart; } } }
[ "function", "tick", "(", ")", "{", "performanceCollector", ".", "tick", "(", ")", ";", "const", "useMedia", "=", "dataManager", ".", "getMediaState", "(", ")", ";", "const", "playTimeSinceStart", "=", "timeManager", ".", "getPlayTimeSinceStart", "(", ")", ";", "for", "(", "let", "key", "in", "dataConfig", ")", "{", "const", "infoDict", "=", "dataConfig", "[", "key", "]", ";", "if", "(", "infoDict", ".", "status", "&&", "playTimeSinceStart", "-", "infoDict", ".", "lastFetchTime", ">", "infoDict", ".", "timePeriod", ")", "{", "const", "timeDifferene", "=", "playTimeSinceStart", "-", "infoDict", ".", "lastFetchTime", ";", "if", "(", "useMedia", ")", "_setEvents", "(", "infoDict", ".", "calculator", ".", "getMediaEvents", "(", "timeDifferene", ")", ")", ";", "// always collecting default events", "_setEvents", "(", "infoDict", ".", "calculator", ".", "getEvents", "(", "timeDifferene", ")", ")", ";", "infoDict", ".", "lastFetchTime", "=", "playTimeSinceStart", ";", "}", "}", "}" ]
Checks if any default data needs to be collected after each frame @memberof DataCollector
[ "Checks", "if", "any", "default", "data", "needs", "to", "be", "collected", "after", "each", "frame" ]
7e4a493c824c2c1716360dcb6a3bfecfede5df3b
https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/dataCollector/dataCollector.js#L152-L180
44,858
vadr-vr/VR-Analytics-JSCore
js/dataCollector/dataCollector.js
_setEvents
function _setEvents(eventsArray){ for (let i = 0; i < eventsArray.length; i++){ let event = eventsArray[i]; dataManager.registerEvent(event[0], event[1], event[2]); } }
javascript
function _setEvents(eventsArray){ for (let i = 0; i < eventsArray.length; i++){ let event = eventsArray[i]; dataManager.registerEvent(event[0], event[1], event[2]); } }
[ "function", "_setEvents", "(", "eventsArray", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "eventsArray", ".", "length", ";", "i", "++", ")", "{", "let", "event", "=", "eventsArray", "[", "i", "]", ";", "dataManager", ".", "registerEvent", "(", "event", "[", "0", "]", ",", "event", "[", "1", "]", ",", "event", "[", "2", "]", ")", ";", "}", "}" ]
collects the events from the given array and adds to datamanager
[ "collects", "the", "events", "from", "the", "given", "array", "and", "adds", "to", "datamanager" ]
7e4a493c824c2c1716360dcb6a3bfecfede5df3b
https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/dataCollector/dataCollector.js#L183-L192
44,859
mesmotronic/conbo
src/conbo/binding/BindingUtils.js
function(propertyName, value) { if (this[propertyName] === value) { return this; } // Ensure numbers are returned as Number not String if (value && conbo.isString(value) && !isNaN(value)) { value = parseFloat(value); if (isNaN(value)) value = ''; } this[propertyName] = value; return this; }
javascript
function(propertyName, value) { if (this[propertyName] === value) { return this; } // Ensure numbers are returned as Number not String if (value && conbo.isString(value) && !isNaN(value)) { value = parseFloat(value); if (isNaN(value)) value = ''; } this[propertyName] = value; return this; }
[ "function", "(", "propertyName", ",", "value", ")", "{", "if", "(", "this", "[", "propertyName", "]", "===", "value", ")", "{", "return", "this", ";", "}", "// Ensure numbers are returned as Number not String\r", "if", "(", "value", "&&", "conbo", ".", "isString", "(", "value", ")", "&&", "!", "isNaN", "(", "value", ")", ")", "{", "value", "=", "parseFloat", "(", "value", ")", ";", "if", "(", "isNaN", "(", "value", ")", ")", "value", "=", "''", ";", "}", "this", "[", "propertyName", "]", "=", "value", ";", "return", "this", ";", "}" ]
Set the value of a property, ensuring Numbers are types correctly @private @param propertyName @param value @example BindingUtils__set.call(target, 'n', 123); @returns this
[ "Set", "the", "value", "of", "a", "property", "ensuring", "Numbers", "are", "types", "correctly" ]
339df613eefc48e054e115337079573ad842f717
https://github.com/mesmotronic/conbo/blob/339df613eefc48e054e115337079573ad842f717/src/conbo/binding/BindingUtils.js#L18-L35
44,860
mesmotronic/conbo
src/conbo/binding/BindingUtils.js
function(source, propertyName) { if (!conbo.isAccessor(source, propertyName) && !conbo.isFunc(source, propertyName)) { if (source instanceof conbo.EventDispatcher) { conbo.makeBindable(source, [propertyName]); } else { conbo.warn('It will not be possible to detect changes to "'+propertyName+'" because "'+source.toString()+'" is not an EventDispatcher'); } } }
javascript
function(source, propertyName) { if (!conbo.isAccessor(source, propertyName) && !conbo.isFunc(source, propertyName)) { if (source instanceof conbo.EventDispatcher) { conbo.makeBindable(source, [propertyName]); } else { conbo.warn('It will not be possible to detect changes to "'+propertyName+'" because "'+source.toString()+'" is not an EventDispatcher'); } } }
[ "function", "(", "source", ",", "propertyName", ")", "{", "if", "(", "!", "conbo", ".", "isAccessor", "(", "source", ",", "propertyName", ")", "&&", "!", "conbo", ".", "isFunc", "(", "source", ",", "propertyName", ")", ")", "{", "if", "(", "source", "instanceof", "conbo", ".", "EventDispatcher", ")", "{", "conbo", ".", "makeBindable", "(", "source", ",", "[", "propertyName", "]", ")", ";", "}", "else", "{", "conbo", ".", "warn", "(", "'It will not be possible to detect changes to \"'", "+", "propertyName", "+", "'\" because \"'", "+", "source", ".", "toString", "(", ")", "+", "'\" is not an EventDispatcher'", ")", ";", "}", "}", "}" ]
Attempt to make a property bindable if it isn't already @private @param {string} value @returns {Boolean}
[ "Attempt", "to", "make", "a", "property", "bindable", "if", "it", "isn", "t", "already" ]
339df613eefc48e054e115337079573ad842f717
https://github.com/mesmotronic/conbo/blob/339df613eefc48e054e115337079573ad842f717/src/conbo/binding/BindingUtils.js#L56-L69
44,861
mesmotronic/conbo
src/conbo/binding/BindingUtils.js
function(element, attributeName) { if (this.attributeExists(attributeName)) { var camelCase = conbo.toCamelCase(attributeName), ns = attributeName.split('-')[0], attrFuncs = (ns == 'cb') ? BindingUtils__cbAttrs : BindingUtils__customAttrs, fn = attrFuncs[camelCase] ; if (fn.readOnly) { fn.call(attrFuncs, element); } else { conbo.warn(attributeName+' attribute cannot be used without a value'); } } else { conbo.warn(attributeName+' attribute does not exist'); } return this; }
javascript
function(element, attributeName) { if (this.attributeExists(attributeName)) { var camelCase = conbo.toCamelCase(attributeName), ns = attributeName.split('-')[0], attrFuncs = (ns == 'cb') ? BindingUtils__cbAttrs : BindingUtils__customAttrs, fn = attrFuncs[camelCase] ; if (fn.readOnly) { fn.call(attrFuncs, element); } else { conbo.warn(attributeName+' attribute cannot be used without a value'); } } else { conbo.warn(attributeName+' attribute does not exist'); } return this; }
[ "function", "(", "element", ",", "attributeName", ")", "{", "if", "(", "this", ".", "attributeExists", "(", "attributeName", ")", ")", "{", "var", "camelCase", "=", "conbo", ".", "toCamelCase", "(", "attributeName", ")", ",", "ns", "=", "attributeName", ".", "split", "(", "'-'", ")", "[", "0", "]", ",", "attrFuncs", "=", "(", "ns", "==", "'cb'", ")", "?", "BindingUtils__cbAttrs", ":", "BindingUtils__customAttrs", ",", "fn", "=", "attrFuncs", "[", "camelCase", "]", ";", "if", "(", "fn", ".", "readOnly", ")", "{", "fn", ".", "call", "(", "attrFuncs", ",", "element", ")", ";", "}", "else", "{", "conbo", ".", "warn", "(", "attributeName", "+", "' attribute cannot be used without a value'", ")", ";", "}", "}", "else", "{", "conbo", ".", "warn", "(", "attributeName", "+", "' attribute does not exist'", ")", ";", "}", "return", "this", ";", "}" ]
Applies the specified read-only Conbo or custom attribute to the specified element @param {HTMLElement} element - DOM element to bind value to (two-way bind on input/form elements) @param {string} attributeName - The attribute to bind as it appears in HTML, e.g. "cb-prop-name" @returns {conbo.BindingUtils} A reference to this object @example conbo.bindingUtils.applyAttribute(el, "my-custom-attr");
[ "Applies", "the", "specified", "read", "-", "only", "Conbo", "or", "custom", "attribute", "to", "the", "specified", "element" ]
339df613eefc48e054e115337079573ad842f717
https://github.com/mesmotronic/conbo/blob/339df613eefc48e054e115337079573ad842f717/src/conbo/binding/BindingUtils.js#L512-L537
44,862
mesmotronic/conbo
src/conbo/binding/BindingUtils.js
function(view) { if (!view) { throw new Error('view is undefined'); } if (!view.__bindings || !view.__bindings.length) { return this; } var bindings = view.__bindings; while (bindings.length) { var binding = bindings.pop(); try { binding[0].removeEventListener(binding[1], binding[2]); } catch (e) {} } delete view.__bindings; return this; }
javascript
function(view) { if (!view) { throw new Error('view is undefined'); } if (!view.__bindings || !view.__bindings.length) { return this; } var bindings = view.__bindings; while (bindings.length) { var binding = bindings.pop(); try { binding[0].removeEventListener(binding[1], binding[2]); } catch (e) {} } delete view.__bindings; return this; }
[ "function", "(", "view", ")", "{", "if", "(", "!", "view", ")", "{", "throw", "new", "Error", "(", "'view is undefined'", ")", ";", "}", "if", "(", "!", "view", ".", "__bindings", "||", "!", "view", ".", "__bindings", ".", "length", ")", "{", "return", "this", ";", "}", "var", "bindings", "=", "view", ".", "__bindings", ";", "while", "(", "bindings", ".", "length", ")", "{", "var", "binding", "=", "bindings", ".", "pop", "(", ")", ";", "try", "{", "binding", "[", "0", "]", ".", "removeEventListener", "(", "binding", "[", "1", "]", ",", "binding", "[", "2", "]", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "delete", "view", ".", "__bindings", ";", "return", "this", ";", "}" ]
Removes all data binding from the specified View instance @param {conbo.View} view @returns {conbo.BindingUtils} A reference to this object
[ "Removes", "all", "data", "binding", "from", "the", "specified", "View", "instance" ]
339df613eefc48e054e115337079573ad842f717
https://github.com/mesmotronic/conbo/blob/339df613eefc48e054e115337079573ad842f717/src/conbo/binding/BindingUtils.js#L712-L740
44,863
mesmotronic/conbo
src/conbo/binding/BindingUtils.js
function(rootView, namespace, type) { type || (type = 'view'); if (['view', 'glimpse'].indexOf(type) == -1) { throw new Error(type+' is not a valid type parameter for applyView'); } var typeClass = conbo[type.charAt(0).toUpperCase()+type.slice(1)], scope = this ; var rootEl = conbo.isElement(rootView) ? rootView : rootView.el; for (var className in namespace) { var classReference = scope.getClass(className, namespace); var isView = conbo.isClass(classReference, conbo.View); var isGlimpse = conbo.isClass(classReference, conbo.Glimpse) && !isView; if ((type == 'glimpse' && isGlimpse) || (type == 'view' && isView)) { var tagName = conbo.toKebabCase(className); var nodes = conbo.toArray(rootEl.querySelectorAll(tagName+':not(.cb-'+type+'):not([cb-repeat]), [cb-'+type+'='+className+']:not(.cb-'+type+'):not([cb-repeat])')); nodes.forEach(function(el) { var ep = __ep(el); // Ignore anything that's inside a cb-repeat if (!ep.closest('[cb-repeat]')) { var closestView = ep.closest('.cb-view'); var context = closestView ? closestView.cbView.subcontext : rootView.subcontext; new classReference({el:el, context:context}); } }); } } return this; }
javascript
function(rootView, namespace, type) { type || (type = 'view'); if (['view', 'glimpse'].indexOf(type) == -1) { throw new Error(type+' is not a valid type parameter for applyView'); } var typeClass = conbo[type.charAt(0).toUpperCase()+type.slice(1)], scope = this ; var rootEl = conbo.isElement(rootView) ? rootView : rootView.el; for (var className in namespace) { var classReference = scope.getClass(className, namespace); var isView = conbo.isClass(classReference, conbo.View); var isGlimpse = conbo.isClass(classReference, conbo.Glimpse) && !isView; if ((type == 'glimpse' && isGlimpse) || (type == 'view' && isView)) { var tagName = conbo.toKebabCase(className); var nodes = conbo.toArray(rootEl.querySelectorAll(tagName+':not(.cb-'+type+'):not([cb-repeat]), [cb-'+type+'='+className+']:not(.cb-'+type+'):not([cb-repeat])')); nodes.forEach(function(el) { var ep = __ep(el); // Ignore anything that's inside a cb-repeat if (!ep.closest('[cb-repeat]')) { var closestView = ep.closest('.cb-view'); var context = closestView ? closestView.cbView.subcontext : rootView.subcontext; new classReference({el:el, context:context}); } }); } } return this; }
[ "function", "(", "rootView", ",", "namespace", ",", "type", ")", "{", "type", "||", "(", "type", "=", "'view'", ")", ";", "if", "(", "[", "'view'", ",", "'glimpse'", "]", ".", "indexOf", "(", "type", ")", "==", "-", "1", ")", "{", "throw", "new", "Error", "(", "type", "+", "' is not a valid type parameter for applyView'", ")", ";", "}", "var", "typeClass", "=", "conbo", "[", "type", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "type", ".", "slice", "(", "1", ")", "]", ",", "scope", "=", "this", ";", "var", "rootEl", "=", "conbo", ".", "isElement", "(", "rootView", ")", "?", "rootView", ":", "rootView", ".", "el", ";", "for", "(", "var", "className", "in", "namespace", ")", "{", "var", "classReference", "=", "scope", ".", "getClass", "(", "className", ",", "namespace", ")", ";", "var", "isView", "=", "conbo", ".", "isClass", "(", "classReference", ",", "conbo", ".", "View", ")", ";", "var", "isGlimpse", "=", "conbo", ".", "isClass", "(", "classReference", ",", "conbo", ".", "Glimpse", ")", "&&", "!", "isView", ";", "if", "(", "(", "type", "==", "'glimpse'", "&&", "isGlimpse", ")", "||", "(", "type", "==", "'view'", "&&", "isView", ")", ")", "{", "var", "tagName", "=", "conbo", ".", "toKebabCase", "(", "className", ")", ";", "var", "nodes", "=", "conbo", ".", "toArray", "(", "rootEl", ".", "querySelectorAll", "(", "tagName", "+", "':not(.cb-'", "+", "type", "+", "'):not([cb-repeat]), [cb-'", "+", "type", "+", "'='", "+", "className", "+", "']:not(.cb-'", "+", "type", "+", "'):not([cb-repeat])'", ")", ")", ";", "nodes", ".", "forEach", "(", "function", "(", "el", ")", "{", "var", "ep", "=", "__ep", "(", "el", ")", ";", "// Ignore anything that's inside a cb-repeat\r", "if", "(", "!", "ep", ".", "closest", "(", "'[cb-repeat]'", ")", ")", "{", "var", "closestView", "=", "ep", ".", "closest", "(", "'.cb-view'", ")", ";", "var", "context", "=", "closestView", "?", "closestView", ".", "cbView", ".", "subcontext", ":", "rootView", ".", "subcontext", ";", "new", "classReference", "(", "{", "el", ":", "el", ",", "context", ":", "context", "}", ")", ";", "}", "}", ")", ";", "}", "}", "return", "this", ";", "}" ]
Applies View and Glimpse classes DOM elements based on their cb-view attribute or tag name @param {HTMLElement} rootView - DOM element, View or Application class instance @param {conbo.Namespace} namespace - The current namespace @param {string} [type=view] - View type, 'view' or 'glimpse' @returns {conbo.BindingUtils} A reference to this object
[ "Applies", "View", "and", "Glimpse", "classes", "DOM", "elements", "based", "on", "their", "cb", "-", "view", "attribute", "or", "tag", "name" ]
339df613eefc48e054e115337079573ad842f717
https://github.com/mesmotronic/conbo/blob/339df613eefc48e054e115337079573ad842f717/src/conbo/binding/BindingUtils.js#L751-L794
44,864
mesmotronic/conbo
src/conbo/binding/BindingUtils.js
function(className, namespace) { if (!className || !namespace) return; try { var classReference = namespace[className]; if (conbo.isClass(classReference)) { return classReference; } } catch (e) {} }
javascript
function(className, namespace) { if (!className || !namespace) return; try { var classReference = namespace[className]; if (conbo.isClass(classReference)) { return classReference; } } catch (e) {} }
[ "function", "(", "className", ",", "namespace", ")", "{", "if", "(", "!", "className", "||", "!", "namespace", ")", "return", ";", "try", "{", "var", "classReference", "=", "namespace", "[", "className", "]", ";", "if", "(", "conbo", ".", "isClass", "(", "classReference", ")", ")", "{", "return", "classReference", ";", "}", "}", "catch", "(", "e", ")", "{", "}", "}" ]
Attempt to convert string into a conbo.Class in the specified namespace @param {string} className - The name of the class @param {conbo.Namespace} namespace - The namespace containing the class @returns {*}
[ "Attempt", "to", "convert", "string", "into", "a", "conbo", ".", "Class", "in", "the", "specified", "namespace" ]
339df613eefc48e054e115337079573ad842f717
https://github.com/mesmotronic/conbo/blob/339df613eefc48e054e115337079573ad842f717/src/conbo/binding/BindingUtils.js#L892-L906
44,865
mesmotronic/conbo
src/conbo/binding/BindingUtils.js
function(name, handler, readOnly, raw) { if (!conbo.isString(name) || !conbo.isFunction(handler)) { conbo.warn("registerAttribute: both 'name' and 'handler' parameters are required"); return this; } var split = conbo.toUnderscoreCase(name).split('_'); if (split.length < 2) { conbo.warn("registerAttribute: "+name+" does not include a namespace, e.g. "+conbo.toCamelCase('my-'+name)); return this; } var ns = split[0]; if (BindingUtils__reservedNamespaces.indexOf(ns) != -1) { conbo.warn("registerAttribute: custom attributes cannot to use the "+ns+" namespace"); return this; } BindingUtils__registeredNamespaces = conbo.union(BindingUtils__registeredNamespaces, [ns]); conbo.assign(handler, { readOnly: !!readOnly, raw: !!raw }); BindingUtils__customAttrs[name] = handler; return this; }
javascript
function(name, handler, readOnly, raw) { if (!conbo.isString(name) || !conbo.isFunction(handler)) { conbo.warn("registerAttribute: both 'name' and 'handler' parameters are required"); return this; } var split = conbo.toUnderscoreCase(name).split('_'); if (split.length < 2) { conbo.warn("registerAttribute: "+name+" does not include a namespace, e.g. "+conbo.toCamelCase('my-'+name)); return this; } var ns = split[0]; if (BindingUtils__reservedNamespaces.indexOf(ns) != -1) { conbo.warn("registerAttribute: custom attributes cannot to use the "+ns+" namespace"); return this; } BindingUtils__registeredNamespaces = conbo.union(BindingUtils__registeredNamespaces, [ns]); conbo.assign(handler, { readOnly: !!readOnly, raw: !!raw }); BindingUtils__customAttrs[name] = handler; return this; }
[ "function", "(", "name", ",", "handler", ",", "readOnly", ",", "raw", ")", "{", "if", "(", "!", "conbo", ".", "isString", "(", "name", ")", "||", "!", "conbo", ".", "isFunction", "(", "handler", ")", ")", "{", "conbo", ".", "warn", "(", "\"registerAttribute: both 'name' and 'handler' parameters are required\"", ")", ";", "return", "this", ";", "}", "var", "split", "=", "conbo", ".", "toUnderscoreCase", "(", "name", ")", ".", "split", "(", "'_'", ")", ";", "if", "(", "split", ".", "length", "<", "2", ")", "{", "conbo", ".", "warn", "(", "\"registerAttribute: \"", "+", "name", "+", "\" does not include a namespace, e.g. \"", "+", "conbo", ".", "toCamelCase", "(", "'my-'", "+", "name", ")", ")", ";", "return", "this", ";", "}", "var", "ns", "=", "split", "[", "0", "]", ";", "if", "(", "BindingUtils__reservedNamespaces", ".", "indexOf", "(", "ns", ")", "!=", "-", "1", ")", "{", "conbo", ".", "warn", "(", "\"registerAttribute: custom attributes cannot to use the \"", "+", "ns", "+", "\" namespace\"", ")", ";", "return", "this", ";", "}", "BindingUtils__registeredNamespaces", "=", "conbo", ".", "union", "(", "BindingUtils__registeredNamespaces", ",", "[", "ns", "]", ")", ";", "conbo", ".", "assign", "(", "handler", ",", "{", "readOnly", ":", "!", "!", "readOnly", ",", "raw", ":", "!", "!", "raw", "}", ")", ";", "BindingUtils__customAttrs", "[", "name", "]", "=", "handler", ";", "return", "this", ";", "}" ]
Register a custom attribute handler @param {string} name - camelCase version of the attribute name (must include a namespace prefix) @param {Function} handler - function that will handle the data bound to the element @param {boolean} readOnly - Whether or not the attribute is read-only (default: false) @param {boolean} [raw=false] - Whether or not parameters should be passed to the handler as a raw String instead of a bound value @returns {conbo.BindingUtils} A reference to this object @example // HTML: <div my-font-name="myProperty"></div> conbo.bindingUtils.registerAttribute('myFontName', function(el, value, options, param) { el.style.fontName = value; });
[ "Register", "a", "custom", "attribute", "handler" ]
339df613eefc48e054e115337079573ad842f717
https://github.com/mesmotronic/conbo/blob/339df613eefc48e054e115337079573ad842f717/src/conbo/binding/BindingUtils.js#L924-L959
44,866
invercity/easy-report
lib.js
function(mask) { var borders = ['border-top','border-right', 'border-bottom', 'border-left']; var res = {}; for (var i = 0; i < 4; i++) { if (!(mask & bin(i))) res[borders[i]] = 'none'; } return res; }
javascript
function(mask) { var borders = ['border-top','border-right', 'border-bottom', 'border-left']; var res = {}; for (var i = 0; i < 4; i++) { if (!(mask & bin(i))) res[borders[i]] = 'none'; } return res; }
[ "function", "(", "mask", ")", "{", "var", "borders", "=", "[", "'border-top'", ",", "'border-right'", ",", "'border-bottom'", ",", "'border-left'", "]", ";", "var", "res", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "if", "(", "!", "(", "mask", "&", "bin", "(", "i", ")", ")", ")", "res", "[", "borders", "[", "i", "]", "]", "=", "'none'", ";", "}", "return", "res", ";", "}" ]
Exclude borders with 'none-border @param mask @return {{}}
[ "Exclude", "borders", "with", "none", "-", "border" ]
92e56a1fd98e6f07d31d5c91149eda9981d3b4b3
https://github.com/invercity/easy-report/blob/92e56a1fd98e6f07d31d5c91149eda9981d3b4b3/lib.js#L50-L57
44,867
invercity/easy-report
lib.js
function (obj) { var clone = _.clone(obj); if (obj.style) { var style = obj.style; clone.style = { "font-family": style.fontFamily, "font-size": style.fontSize + "px", "font-weight": (style.mask & bin(4)) ? "bold" : "normal", "font-style": (style.mask & bin(5)) ? "italic" : "normal", "text-decoration": (((style.mask & bin(6)) ? "underline " : "") + ((style.mask & bin(7)) ? "line-through" : "")), "text-align": style.textAlign, "color": style.color, "background-color": style.backgroundColor, "border": [style.borderWidth + "px", style.borderStyle, style.borderColor].join(" "), "padding": style.padding.join("px ") + "px" }; _.extend(clone.style, checkBorder(style.mask)); } // init style if null clone.style || (clone.style = {}); return clone; }
javascript
function (obj) { var clone = _.clone(obj); if (obj.style) { var style = obj.style; clone.style = { "font-family": style.fontFamily, "font-size": style.fontSize + "px", "font-weight": (style.mask & bin(4)) ? "bold" : "normal", "font-style": (style.mask & bin(5)) ? "italic" : "normal", "text-decoration": (((style.mask & bin(6)) ? "underline " : "") + ((style.mask & bin(7)) ? "line-through" : "")), "text-align": style.textAlign, "color": style.color, "background-color": style.backgroundColor, "border": [style.borderWidth + "px", style.borderStyle, style.borderColor].join(" "), "padding": style.padding.join("px ") + "px" }; _.extend(clone.style, checkBorder(style.mask)); } // init style if null clone.style || (clone.style = {}); return clone; }
[ "function", "(", "obj", ")", "{", "var", "clone", "=", "_", ".", "clone", "(", "obj", ")", ";", "if", "(", "obj", ".", "style", ")", "{", "var", "style", "=", "obj", ".", "style", ";", "clone", ".", "style", "=", "{", "\"font-family\"", ":", "style", ".", "fontFamily", ",", "\"font-size\"", ":", "style", ".", "fontSize", "+", "\"px\"", ",", "\"font-weight\"", ":", "(", "style", ".", "mask", "&", "bin", "(", "4", ")", ")", "?", "\"bold\"", ":", "\"normal\"", ",", "\"font-style\"", ":", "(", "style", ".", "mask", "&", "bin", "(", "5", ")", ")", "?", "\"italic\"", ":", "\"normal\"", ",", "\"text-decoration\"", ":", "(", "(", "(", "style", ".", "mask", "&", "bin", "(", "6", ")", ")", "?", "\"underline \"", ":", "\"\"", ")", "+", "(", "(", "style", ".", "mask", "&", "bin", "(", "7", ")", ")", "?", "\"line-through\"", ":", "\"\"", ")", ")", ",", "\"text-align\"", ":", "style", ".", "textAlign", ",", "\"color\"", ":", "style", ".", "color", ",", "\"background-color\"", ":", "style", ".", "backgroundColor", ",", "\"border\"", ":", "[", "style", ".", "borderWidth", "+", "\"px\"", ",", "style", ".", "borderStyle", ",", "style", ".", "borderColor", "]", ".", "join", "(", "\" \"", ")", ",", "\"padding\"", ":", "style", ".", "padding", ".", "join", "(", "\"px \"", ")", "+", "\"px\"", "}", ";", "_", ".", "extend", "(", "clone", ".", "style", ",", "checkBorder", "(", "style", ".", "mask", ")", ")", ";", "}", "// init style if null", "clone", ".", "style", "||", "(", "clone", ".", "style", "=", "{", "}", ")", ";", "return", "clone", ";", "}" ]
Replace object.style with real style @param obj @return {*}
[ "Replace", "object", ".", "style", "with", "real", "style" ]
92e56a1fd98e6f07d31d5c91149eda9981d3b4b3
https://github.com/invercity/easy-report/blob/92e56a1fd98e6f07d31d5c91149eda9981d3b4b3/lib.js#L64-L85
44,868
AlexisNo/pebo
index.js
callListenersSequentially
function callListenersSequentially(i, args) { if (!this.events[eventName][i]) { // If there is no more listener to execute, we return a promise of the event arguments/result // So we are getting out of the recursive function return new Promise((resolve, reject) => { resolve(args); }); } const p = Promise.resolve(this.events[eventName][i].apply(this.events[eventName][i], args)); return p.then(function propagateArguments() { // We cannot use the "=>" notation here because we use `"arguments" // When an event listener has been executed, we move to the next one (recursivity) if (propagateResponses) { // Case the event must pass the result of a listener to the next one // This use case allow to transmit and alter primitive (strings, numbers ...) return callListenersSequentially.bind(this)(i + 1, arguments[0]); } // Case the event can pass the arguments to each listener // This use case allow a simple syntax for listener, compatible with fireConcurrently() // But it is not possible to transmit alterations made on primitive arguments return callListenersSequentially.bind(this)(i + 1, args); }.bind(this)); }
javascript
function callListenersSequentially(i, args) { if (!this.events[eventName][i]) { // If there is no more listener to execute, we return a promise of the event arguments/result // So we are getting out of the recursive function return new Promise((resolve, reject) => { resolve(args); }); } const p = Promise.resolve(this.events[eventName][i].apply(this.events[eventName][i], args)); return p.then(function propagateArguments() { // We cannot use the "=>" notation here because we use `"arguments" // When an event listener has been executed, we move to the next one (recursivity) if (propagateResponses) { // Case the event must pass the result of a listener to the next one // This use case allow to transmit and alter primitive (strings, numbers ...) return callListenersSequentially.bind(this)(i + 1, arguments[0]); } // Case the event can pass the arguments to each listener // This use case allow a simple syntax for listener, compatible with fireConcurrently() // But it is not possible to transmit alterations made on primitive arguments return callListenersSequentially.bind(this)(i + 1, args); }.bind(this)); }
[ "function", "callListenersSequentially", "(", "i", ",", "args", ")", "{", "if", "(", "!", "this", ".", "events", "[", "eventName", "]", "[", "i", "]", ")", "{", "// If there is no more listener to execute, we return a promise of the event arguments/result", "// So we are getting out of the recursive function", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "resolve", "(", "args", ")", ";", "}", ")", ";", "}", "const", "p", "=", "Promise", ".", "resolve", "(", "this", ".", "events", "[", "eventName", "]", "[", "i", "]", ".", "apply", "(", "this", ".", "events", "[", "eventName", "]", "[", "i", "]", ",", "args", ")", ")", ";", "return", "p", ".", "then", "(", "function", "propagateArguments", "(", ")", "{", "// We cannot use the \"=>\" notation here because we use `\"arguments\"", "// When an event listener has been executed, we move to the next one (recursivity)", "if", "(", "propagateResponses", ")", "{", "// Case the event must pass the result of a listener to the next one", "// This use case allow to transmit and alter primitive (strings, numbers ...)", "return", "callListenersSequentially", ".", "bind", "(", "this", ")", "(", "i", "+", "1", ",", "arguments", "[", "0", "]", ")", ";", "}", "// Case the event can pass the arguments to each listener", "// This use case allow a simple syntax for listener, compatible with fireConcurrently()", "// But it is not possible to transmit alterations made on primitive arguments", "return", "callListenersSequentially", ".", "bind", "(", "this", ")", "(", "i", "+", "1", ",", "args", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Define a recusive function that will check if a plugin implements the hook, execute it and pass the eventually transformed arguments to the next one
[ "Define", "a", "recusive", "function", "that", "will", "check", "if", "a", "plugin", "implements", "the", "hook", "execute", "it", "and", "pass", "the", "eventually", "transformed", "arguments", "to", "the", "next", "one" ]
59fe7698a099a12c469b09d3c1cda2a9e334f87e
https://github.com/AlexisNo/pebo/blob/59fe7698a099a12c469b09d3c1cda2a9e334f87e/index.js#L57-L80
44,869
xudafeng/passme
demo/editor/kissy.js
function (arr, callback, initialValue) { var len = arr.length; if (typeof callback !== 'function') { throw new TypeError('callback is not function!'); } // no value to return if no initial value and an empty array if (len === 0 && arguments.length == 2) { throw new TypeError('arguments invalid'); } var k = 0; var accumulator; if (arguments.length >= 3) { accumulator = arguments[2]; } else { do { if (k in arr) { accumulator = arr[k++]; break; } // if array contains no values, no initial value to return k += 1; if (k >= len) { throw new TypeError(); } } while (TRUE); } while (k < len) { if (k in arr) { accumulator = callback.call(undefined, accumulator, arr[k], k, arr); } k++; } return accumulator; }
javascript
function (arr, callback, initialValue) { var len = arr.length; if (typeof callback !== 'function') { throw new TypeError('callback is not function!'); } // no value to return if no initial value and an empty array if (len === 0 && arguments.length == 2) { throw new TypeError('arguments invalid'); } var k = 0; var accumulator; if (arguments.length >= 3) { accumulator = arguments[2]; } else { do { if (k in arr) { accumulator = arr[k++]; break; } // if array contains no values, no initial value to return k += 1; if (k >= len) { throw new TypeError(); } } while (TRUE); } while (k < len) { if (k in arr) { accumulator = callback.call(undefined, accumulator, arr[k], k, arr); } k++; } return accumulator; }
[ "function", "(", "arr", ",", "callback", ",", "initialValue", ")", "{", "var", "len", "=", "arr", ".", "length", ";", "if", "(", "typeof", "callback", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'callback is not function!'", ")", ";", "}", "// no value to return if no initial value and an empty array", "if", "(", "len", "===", "0", "&&", "arguments", ".", "length", "==", "2", ")", "{", "throw", "new", "TypeError", "(", "'arguments invalid'", ")", ";", "}", "var", "k", "=", "0", ";", "var", "accumulator", ";", "if", "(", "arguments", ".", "length", ">=", "3", ")", "{", "accumulator", "=", "arguments", "[", "2", "]", ";", "}", "else", "{", "do", "{", "if", "(", "k", "in", "arr", ")", "{", "accumulator", "=", "arr", "[", "k", "++", "]", ";", "break", ";", "}", "// if array contains no values, no initial value to return", "k", "+=", "1", ";", "if", "(", "k", ">=", "len", ")", "{", "throw", "new", "TypeError", "(", ")", ";", "}", "}", "while", "(", "TRUE", ")", ";", "}", "while", "(", "k", "<", "len", ")", "{", "if", "(", "k", "in", "arr", ")", "{", "accumulator", "=", "callback", ".", "call", "(", "undefined", ",", "accumulator", ",", "arr", "[", "k", "]", ",", "k", ",", "arr", ")", ";", "}", "k", "++", ";", "}", "return", "accumulator", ";", "}" ]
Executes the supplied function on each item in the array. Returns a value which is accumulation of the value that the supplied function returned. @param arr {Array} the array to iterate @param callback {Function} the function to execute on each item @param initialValue {number} optional context object refer: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/reduce @return {Array} The items on which the supplied function returned @member KISSY
[ "Executes", "the", "supplied", "function", "on", "each", "item", "in", "the", "array", ".", "Returns", "a", "value", "which", "is", "accumulation", "of", "the", "value", "that", "the", "supplied", "function", "returned", "." ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L906-L946
44,870
xudafeng/passme
demo/editor/kissy.js
function (o) { if (o == null) { return []; } if (S.isArray(o)) { return o; } var lengthType = typeof o.length, oType = typeof o; // The strings and functions also have 'length' if (lengthType != 'number' || // form.elements in ie78 has nodeName 'form' // then caution select // o.nodeName // window o.alert || oType == 'string' || // https://github.com/ariya/phantomjs/issues/11478 (oType == 'function' && !( 'item' in o && lengthType == 'number'))) { return [o]; } var ret = []; for (var i = 0, l = o.length; i < l; i++) { ret[i] = o[i]; } return ret; }
javascript
function (o) { if (o == null) { return []; } if (S.isArray(o)) { return o; } var lengthType = typeof o.length, oType = typeof o; // The strings and functions also have 'length' if (lengthType != 'number' || // form.elements in ie78 has nodeName 'form' // then caution select // o.nodeName // window o.alert || oType == 'string' || // https://github.com/ariya/phantomjs/issues/11478 (oType == 'function' && !( 'item' in o && lengthType == 'number'))) { return [o]; } var ret = []; for (var i = 0, l = o.length; i < l; i++) { ret[i] = o[i]; } return ret; }
[ "function", "(", "o", ")", "{", "if", "(", "o", "==", "null", ")", "{", "return", "[", "]", ";", "}", "if", "(", "S", ".", "isArray", "(", "o", ")", ")", "{", "return", "o", ";", "}", "var", "lengthType", "=", "typeof", "o", ".", "length", ",", "oType", "=", "typeof", "o", ";", "// The strings and functions also have 'length'", "if", "(", "lengthType", "!=", "'number'", "||", "// form.elements in ie78 has nodeName 'form'", "// then caution select", "// o.nodeName", "// window", "o", ".", "alert", "||", "oType", "==", "'string'", "||", "// https://github.com/ariya/phantomjs/issues/11478", "(", "oType", "==", "'function'", "&&", "!", "(", "'item'", "in", "o", "&&", "lengthType", "==", "'number'", ")", ")", ")", "{", "return", "[", "o", "]", ";", "}", "var", "ret", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "o", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "ret", "[", "i", "]", "=", "o", "[", "i", "]", ";", "}", "return", "ret", ";", "}" ]
Converts object to a TRUE array. @param o {object|Array} array like object or array @return {Array} native Array @member KISSY
[ "Converts", "object", "to", "a", "TRUE", "array", "." ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L999-L1025
44,871
xudafeng/passme
demo/editor/kissy.js
function (path, ext) { var result = path.match(splitPathRe) || [], basename; basename = result[3] || ''; if (ext && basename && basename.slice(-1 * ext.length) == ext) { basename = basename.slice(0, -1 * ext.length); } return basename; }
javascript
function (path, ext) { var result = path.match(splitPathRe) || [], basename; basename = result[3] || ''; if (ext && basename && basename.slice(-1 * ext.length) == ext) { basename = basename.slice(0, -1 * ext.length); } return basename; }
[ "function", "(", "path", ",", "ext", ")", "{", "var", "result", "=", "path", ".", "match", "(", "splitPathRe", ")", "||", "[", "]", ",", "basename", ";", "basename", "=", "result", "[", "3", "]", "||", "''", ";", "if", "(", "ext", "&&", "basename", "&&", "basename", ".", "slice", "(", "-", "1", "*", "ext", ".", "length", ")", "==", "ext", ")", "{", "basename", "=", "basename", ".", "slice", "(", "0", ",", "-", "1", "*", "ext", ".", "length", ")", ";", "}", "return", "basename", ";", "}" ]
Get base name of path @param {String} path @param {String} [ext] ext to be stripped from result returned. @return {String}
[ "Get", "base", "name", "of", "path" ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L2180-L2188
44,872
xudafeng/passme
demo/editor/kissy.js
function (key, value) { var self = this, _queryMap, currentValue; if (typeof key == 'string') { parseQuery(self); _queryMap = self._queryMap; currentValue = _queryMap[key]; if (currentValue === undefined) { currentValue = value; } else { currentValue = [].concat(currentValue).concat(value); } _queryMap[key] = currentValue; } else { if (key instanceof Query) { key = key.get(); } for (var k in key) { self.add(k, key[k]); } } return self; }
javascript
function (key, value) { var self = this, _queryMap, currentValue; if (typeof key == 'string') { parseQuery(self); _queryMap = self._queryMap; currentValue = _queryMap[key]; if (currentValue === undefined) { currentValue = value; } else { currentValue = [].concat(currentValue).concat(value); } _queryMap[key] = currentValue; } else { if (key instanceof Query) { key = key.get(); } for (var k in key) { self.add(k, key[k]); } } return self; }
[ "function", "(", "key", ",", "value", ")", "{", "var", "self", "=", "this", ",", "_queryMap", ",", "currentValue", ";", "if", "(", "typeof", "key", "==", "'string'", ")", "{", "parseQuery", "(", "self", ")", ";", "_queryMap", "=", "self", ".", "_queryMap", ";", "currentValue", "=", "_queryMap", "[", "key", "]", ";", "if", "(", "currentValue", "===", "undefined", ")", "{", "currentValue", "=", "value", ";", "}", "else", "{", "currentValue", "=", "[", "]", ".", "concat", "(", "currentValue", ")", ".", "concat", "(", "value", ")", ";", "}", "_queryMap", "[", "key", "]", "=", "currentValue", ";", "}", "else", "{", "if", "(", "key", "instanceof", "Query", ")", "{", "key", "=", "key", ".", "get", "(", ")", ";", "}", "for", "(", "var", "k", "in", "key", ")", "{", "self", ".", "add", "(", "k", ",", "key", "[", "k", "]", ")", ";", "}", "}", "return", "self", ";", "}" ]
Add parameter value corresponding to current key @param {String} key @param value @chainable
[ "Add", "parameter", "value", "corresponding", "to", "current", "key" ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L2450-L2473
44,873
xudafeng/passme
demo/editor/kissy.js
function (other) { var self = this; // port and hostname has to be same return equalsIgnoreCase(self.hostname, other['hostname']) && equalsIgnoreCase(self.scheme, other['scheme']) && equalsIgnoreCase(self.port, other['port']); }
javascript
function (other) { var self = this; // port and hostname has to be same return equalsIgnoreCase(self.hostname, other['hostname']) && equalsIgnoreCase(self.scheme, other['scheme']) && equalsIgnoreCase(self.port, other['port']); }
[ "function", "(", "other", ")", "{", "var", "self", "=", "this", ";", "// port and hostname has to be same", "return", "equalsIgnoreCase", "(", "self", ".", "hostname", ",", "other", "[", "'hostname'", "]", ")", "&&", "equalsIgnoreCase", "(", "self", ".", "scheme", ",", "other", "[", "'scheme'", "]", ")", "&&", "equalsIgnoreCase", "(", "self", ".", "port", ",", "other", "[", "'port'", "]", ")", ";", "}" ]
Judge whether two uri has same domain. @param {KISSY.Uri} other @return {Boolean}
[ "Judge", "whether", "two", "uri", "has", "same", "domain", "." ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L2809-L2815
44,874
xudafeng/passme
demo/editor/kissy.js
function (serializeArray) { var out = [], self = this, scheme, hostname, path, port, fragment, query, userInfo; if (scheme = self.scheme) { out.push(encodeSpecialChars(scheme, reDisallowedInSchemeOrUserInfo)); out.push(':'); } if (hostname = self.hostname) { out.push('//'); if (userInfo = self.userInfo) { out.push(encodeSpecialChars(userInfo, reDisallowedInSchemeOrUserInfo)); out.push('@'); } out.push(encodeURIComponent(hostname)); if (port = self.port) { out.push(':'); out.push(port); } } if (path = self.path) { if (hostname && !S.startsWith(path, '/')) { path = '/' + path; } path = Path.normalize(path); out.push(encodeSpecialChars(path, reDisallowedInPathName)); } if (query = ( self.query.toString.call(self.query, serializeArray))) { out.push('?'); out.push(query); } if (fragment = self.fragment) { out.push('#'); out.push(encodeSpecialChars(fragment, reDisallowedInFragment)) } return out.join(''); }
javascript
function (serializeArray) { var out = [], self = this, scheme, hostname, path, port, fragment, query, userInfo; if (scheme = self.scheme) { out.push(encodeSpecialChars(scheme, reDisallowedInSchemeOrUserInfo)); out.push(':'); } if (hostname = self.hostname) { out.push('//'); if (userInfo = self.userInfo) { out.push(encodeSpecialChars(userInfo, reDisallowedInSchemeOrUserInfo)); out.push('@'); } out.push(encodeURIComponent(hostname)); if (port = self.port) { out.push(':'); out.push(port); } } if (path = self.path) { if (hostname && !S.startsWith(path, '/')) { path = '/' + path; } path = Path.normalize(path); out.push(encodeSpecialChars(path, reDisallowedInPathName)); } if (query = ( self.query.toString.call(self.query, serializeArray))) { out.push('?'); out.push(query); } if (fragment = self.fragment) { out.push('#'); out.push(encodeSpecialChars(fragment, reDisallowedInFragment)) } return out.join(''); }
[ "function", "(", "serializeArray", ")", "{", "var", "out", "=", "[", "]", ",", "self", "=", "this", ",", "scheme", ",", "hostname", ",", "path", ",", "port", ",", "fragment", ",", "query", ",", "userInfo", ";", "if", "(", "scheme", "=", "self", ".", "scheme", ")", "{", "out", ".", "push", "(", "encodeSpecialChars", "(", "scheme", ",", "reDisallowedInSchemeOrUserInfo", ")", ")", ";", "out", ".", "push", "(", "':'", ")", ";", "}", "if", "(", "hostname", "=", "self", ".", "hostname", ")", "{", "out", ".", "push", "(", "'//'", ")", ";", "if", "(", "userInfo", "=", "self", ".", "userInfo", ")", "{", "out", ".", "push", "(", "encodeSpecialChars", "(", "userInfo", ",", "reDisallowedInSchemeOrUserInfo", ")", ")", ";", "out", ".", "push", "(", "'@'", ")", ";", "}", "out", ".", "push", "(", "encodeURIComponent", "(", "hostname", ")", ")", ";", "if", "(", "port", "=", "self", ".", "port", ")", "{", "out", ".", "push", "(", "':'", ")", ";", "out", ".", "push", "(", "port", ")", ";", "}", "}", "if", "(", "path", "=", "self", ".", "path", ")", "{", "if", "(", "hostname", "&&", "!", "S", ".", "startsWith", "(", "path", ",", "'/'", ")", ")", "{", "path", "=", "'/'", "+", "path", ";", "}", "path", "=", "Path", ".", "normalize", "(", "path", ")", ";", "out", ".", "push", "(", "encodeSpecialChars", "(", "path", ",", "reDisallowedInPathName", ")", ")", ";", "}", "if", "(", "query", "=", "(", "self", ".", "query", ".", "toString", ".", "call", "(", "self", ".", "query", ",", "serializeArray", ")", ")", ")", "{", "out", ".", "push", "(", "'?'", ")", ";", "out", ".", "push", "(", "query", ")", ";", "}", "if", "(", "fragment", "=", "self", ".", "fragment", ")", "{", "out", ".", "push", "(", "'#'", ")", ";", "out", ".", "push", "(", "encodeSpecialChars", "(", "fragment", ",", "reDisallowedInFragment", ")", ")", "}", "return", "out", ".", "join", "(", "''", ")", ";", "}" ]
Serialize to string. See rfc 5.3 Component Recomposition. But kissy does not differentiate between undefined and empty. @param {Boolean} [serializeArray=true] whether append [] to key name when value 's type is array @return {String}
[ "Serialize", "to", "string", ".", "See", "rfc", "5", ".", "3", "Component", "Recomposition", ".", "But", "kissy", "does", "not", "differentiate", "between", "undefined", "and", "empty", "." ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L2825-L2876
44,875
xudafeng/passme
demo/editor/kissy.js
function (runtime, modNames) { S.each(modNames, function (m) { Utils.createModuleInfo(runtime, m); }); }
javascript
function (runtime, modNames) { S.each(modNames, function (m) { Utils.createModuleInfo(runtime, m); }); }
[ "function", "(", "runtime", ",", "modNames", ")", "{", "S", ".", "each", "(", "modNames", ",", "function", "(", "m", ")", "{", "Utils", ".", "createModuleInfo", "(", "runtime", ",", "m", ")", ";", "}", ")", ";", "}" ]
create modules info @param runtime Module container, such as KISSY @param {String[]} modNames to be created module names
[ "create", "modules", "info" ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L3619-L3623
44,876
xudafeng/passme
demo/editor/kissy.js
function (runtime, modNames) { var mods = [runtime], mod, unalias, allOk, m, runtimeMods = runtime.Env.mods; S.each(modNames, function (modName) { mod = runtimeMods[modName]; if (!mod || mod.getType() != 'css') { unalias = Utils.unalias(runtime, modName); allOk = S.reduce(unalias, function (a, n) { m = runtimeMods[n]; return a && m && m.status == ATTACHED; }, true); if (allOk) { mods.push(runtimeMods[unalias[0]].value); } else { mods.push(null); } } }); return mods; }
javascript
function (runtime, modNames) { var mods = [runtime], mod, unalias, allOk, m, runtimeMods = runtime.Env.mods; S.each(modNames, function (modName) { mod = runtimeMods[modName]; if (!mod || mod.getType() != 'css') { unalias = Utils.unalias(runtime, modName); allOk = S.reduce(unalias, function (a, n) { m = runtimeMods[n]; return a && m && m.status == ATTACHED; }, true); if (allOk) { mods.push(runtimeMods[unalias[0]].value); } else { mods.push(null); } } }); return mods; }
[ "function", "(", "runtime", ",", "modNames", ")", "{", "var", "mods", "=", "[", "runtime", "]", ",", "mod", ",", "unalias", ",", "allOk", ",", "m", ",", "runtimeMods", "=", "runtime", ".", "Env", ".", "mods", ";", "S", ".", "each", "(", "modNames", ",", "function", "(", "modName", ")", "{", "mod", "=", "runtimeMods", "[", "modName", "]", ";", "if", "(", "!", "mod", "||", "mod", ".", "getType", "(", ")", "!=", "'css'", ")", "{", "unalias", "=", "Utils", ".", "unalias", "(", "runtime", ",", "modName", ")", ";", "allOk", "=", "S", ".", "reduce", "(", "unalias", ",", "function", "(", "a", ",", "n", ")", "{", "m", "=", "runtimeMods", "[", "n", "]", ";", "return", "a", "&&", "m", "&&", "m", ".", "status", "==", "ATTACHED", ";", "}", ",", "true", ")", ";", "if", "(", "allOk", ")", "{", "mods", ".", "push", "(", "runtimeMods", "[", "unalias", "[", "0", "]", "]", ".", "value", ")", ";", "}", "else", "{", "mods", ".", "push", "(", "null", ")", ";", "}", "}", "}", ")", ";", "return", "mods", ";", "}" ]
Get module values @param runtime Module container, such as KISSY @param {String[]} modNames module names @return {Array} module values
[ "Get", "module", "values" ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L3667-L3691
44,877
xudafeng/passme
demo/editor/kissy.js
function (runtime, mod) { if (mod.status != LOADED) { return; } var fn = mod.fn; if (typeof fn === 'function') { // 需要解开 index,相对路径 // 但是需要保留 alias,防止值不对应 mod.value = fn.apply(mod, Utils.getModules(runtime, mod.getRequiresWithAlias())); } else { mod.value = fn; } mod.status = ATTACHED; }
javascript
function (runtime, mod) { if (mod.status != LOADED) { return; } var fn = mod.fn; if (typeof fn === 'function') { // 需要解开 index,相对路径 // 但是需要保留 alias,防止值不对应 mod.value = fn.apply(mod, Utils.getModules(runtime, mod.getRequiresWithAlias())); } else { mod.value = fn; } mod.status = ATTACHED; }
[ "function", "(", "runtime", ",", "mod", ")", "{", "if", "(", "mod", ".", "status", "!=", "LOADED", ")", "{", "return", ";", "}", "var", "fn", "=", "mod", ".", "fn", ";", "if", "(", "typeof", "fn", "===", "'function'", ")", "{", "// 需要解开 index,相对路径", "// 但是需要保留 alias,防止值不对应", "mod", ".", "value", "=", "fn", ".", "apply", "(", "mod", ",", "Utils", ".", "getModules", "(", "runtime", ",", "mod", ".", "getRequiresWithAlias", "(", ")", ")", ")", ";", "}", "else", "{", "mod", ".", "value", "=", "fn", ";", "}", "mod", ".", "status", "=", "ATTACHED", ";", "}" ]
Attach specified mod. @param runtime Module container, such as KISSY @param {KISSY.Loader.Module} mod module instance
[ "Attach", "specified", "mod", "." ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L3768-L3784
44,878
xudafeng/passme
demo/editor/kissy.js
function (runtime, path, rules) { var mappedRules = rules || runtime.Config.mappedRules || [], i, m, rule; for (i = 0; i < mappedRules.length; i++) { rule = mappedRules[i]; if (m = path.match(rule[0])) { return path.replace(rule[0], rule[1]); } } return path; }
javascript
function (runtime, path, rules) { var mappedRules = rules || runtime.Config.mappedRules || [], i, m, rule; for (i = 0; i < mappedRules.length; i++) { rule = mappedRules[i]; if (m = path.match(rule[0])) { return path.replace(rule[0], rule[1]); } } return path; }
[ "function", "(", "runtime", ",", "path", ",", "rules", ")", "{", "var", "mappedRules", "=", "rules", "||", "runtime", ".", "Config", ".", "mappedRules", "||", "[", "]", ",", "i", ",", "m", ",", "rule", ";", "for", "(", "i", "=", "0", ";", "i", "<", "mappedRules", ".", "length", ";", "i", "++", ")", "{", "rule", "=", "mappedRules", "[", "i", "]", ";", "if", "(", "m", "=", "path", ".", "match", "(", "rule", "[", "0", "]", ")", ")", "{", "return", "path", ".", "replace", "(", "rule", "[", "0", "]", ",", "rule", "[", "1", "]", ")", ";", "}", "}", "return", "path", ";", "}" ]
Get mapped path. @param runtime Module container, such as KISSY @param {String} path module path @param [rules] map rules @return {String} mapped path
[ "Get", "mapped", "path", "." ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L3912-L3926
44,879
xudafeng/passme
demo/editor/kissy.js
function () { var self = this; if (self.packageUri) { return self.packageUri; } return self.packageUri = new S.Uri(this.getPrefixUriForCombo()); }
javascript
function () { var self = this; if (self.packageUri) { return self.packageUri; } return self.packageUri = new S.Uri(this.getPrefixUriForCombo()); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "if", "(", "self", ".", "packageUri", ")", "{", "return", "self", ".", "packageUri", ";", "}", "return", "self", ".", "packageUri", "=", "new", "S", ".", "Uri", "(", "this", ".", "getPrefixUriForCombo", "(", ")", ")", ";", "}" ]
get package uri
[ "get", "package", "uri" ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L4011-L4017
44,880
xudafeng/passme
demo/editor/kissy.js
function () { var self = this, t, fullPathUri, packageBaseUri, packageInfo, packageName, path; if (!self.fullPathUri) { if (self.fullpath) { fullPathUri = new S.Uri(self.fullpath); } else { packageInfo = self.getPackage(); packageBaseUri = packageInfo.getBaseUri(); path = self.getPath(); // #262 if (packageInfo.isIgnorePackageNameInUri() && // native mod does not allow ignore package name (packageName = packageInfo.getName())) { path = Path.relative(packageName, path); } fullPathUri = packageBaseUri.resolve(path); if (t = self.getTag()) { t += '.' + self.getType(); fullPathUri.query.set('t', t); } } self.fullPathUri = fullPathUri; } return self.fullPathUri; }
javascript
function () { var self = this, t, fullPathUri, packageBaseUri, packageInfo, packageName, path; if (!self.fullPathUri) { if (self.fullpath) { fullPathUri = new S.Uri(self.fullpath); } else { packageInfo = self.getPackage(); packageBaseUri = packageInfo.getBaseUri(); path = self.getPath(); // #262 if (packageInfo.isIgnorePackageNameInUri() && // native mod does not allow ignore package name (packageName = packageInfo.getName())) { path = Path.relative(packageName, path); } fullPathUri = packageBaseUri.resolve(path); if (t = self.getTag()) { t += '.' + self.getType(); fullPathUri.query.set('t', t); } } self.fullPathUri = fullPathUri; } return self.fullPathUri; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "t", ",", "fullPathUri", ",", "packageBaseUri", ",", "packageInfo", ",", "packageName", ",", "path", ";", "if", "(", "!", "self", ".", "fullPathUri", ")", "{", "if", "(", "self", ".", "fullpath", ")", "{", "fullPathUri", "=", "new", "S", ".", "Uri", "(", "self", ".", "fullpath", ")", ";", "}", "else", "{", "packageInfo", "=", "self", ".", "getPackage", "(", ")", ";", "packageBaseUri", "=", "packageInfo", ".", "getBaseUri", "(", ")", ";", "path", "=", "self", ".", "getPath", "(", ")", ";", "// #262", "if", "(", "packageInfo", ".", "isIgnorePackageNameInUri", "(", ")", "&&", "// native mod does not allow ignore package name", "(", "packageName", "=", "packageInfo", ".", "getName", "(", ")", ")", ")", "{", "path", "=", "Path", ".", "relative", "(", "packageName", ",", "path", ")", ";", "}", "fullPathUri", "=", "packageBaseUri", ".", "resolve", "(", "path", ")", ";", "if", "(", "t", "=", "self", ".", "getTag", "(", ")", ")", "{", "t", "+=", "'.'", "+", "self", ".", "getType", "(", ")", ";", "fullPathUri", ".", "query", ".", "set", "(", "'t'", ",", "t", ")", ";", "}", "}", "self", ".", "fullPathUri", "=", "fullPathUri", ";", "}", "return", "self", ".", "fullPathUri", ";", "}" ]
Get the fullpath uri of current module if load dynamically @return {KISSY.Uri}
[ "Get", "the", "fullpath", "uri", "of", "current", "module", "if", "load", "dynamically" ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L4133-L4163
44,881
xudafeng/passme
demo/editor/kissy.js
function () { var self = this, fullPathUri; if (!self.fullpath) { fullPathUri = self.getFullPathUri(); self.fullpath = Utils.getMappedPath(self.runtime, fullPathUri.toString()); } return self.fullpath; }
javascript
function () { var self = this, fullPathUri; if (!self.fullpath) { fullPathUri = self.getFullPathUri(); self.fullpath = Utils.getMappedPath(self.runtime, fullPathUri.toString()); } return self.fullpath; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "fullPathUri", ";", "if", "(", "!", "self", ".", "fullpath", ")", "{", "fullPathUri", "=", "self", ".", "getFullPathUri", "(", ")", ";", "self", ".", "fullpath", "=", "Utils", ".", "getMappedPath", "(", "self", ".", "runtime", ",", "fullPathUri", ".", "toString", "(", ")", ")", ";", "}", "return", "self", ".", "fullpath", ";", "}" ]
Get the fullpath of current module if load dynamically @return {String}
[ "Get", "the", "fullpath", "of", "current", "module", "if", "load", "dynamically" ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L4169-L4177
44,882
xudafeng/passme
demo/editor/kissy.js
function () { var self = this, runtime = self.runtime; return S.map(self.getNormalizedRequires(), function (r) { return Utils.createModuleInfo(runtime, r); }); }
javascript
function () { var self = this, runtime = self.runtime; return S.map(self.getNormalizedRequires(), function (r) { return Utils.createModuleInfo(runtime, r); }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "runtime", "=", "self", ".", "runtime", ";", "return", "S", ".", "map", "(", "self", ".", "getNormalizedRequires", "(", ")", ",", "function", "(", "r", ")", "{", "return", "Utils", ".", "createModuleInfo", "(", "runtime", ",", "r", ")", ";", "}", ")", ";", "}" ]
Get module objects required by this module @return {KISSY.Loader.Module[]}
[ "Get", "module", "objects", "required", "by", "this", "module" ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L4238-L4244
44,883
xudafeng/passme
demo/editor/kissy.js
function () { var self = this, normalizedRequires, normalizedRequiresStatus = self.normalizedRequiresStatus, status = self.status, requires = self.requires; if (!requires || requires.length == 0) { return requires || []; } else if ((normalizedRequires = self.normalizedRequires) && // 事先声明的依赖不能当做 loaded 状态下真正的依赖 (normalizedRequiresStatus == status)) { return normalizedRequires; } else { self.normalizedRequiresStatus = status; return self.normalizedRequires = Utils.normalizeModNames(self.runtime, requires, self.name); } }
javascript
function () { var self = this, normalizedRequires, normalizedRequiresStatus = self.normalizedRequiresStatus, status = self.status, requires = self.requires; if (!requires || requires.length == 0) { return requires || []; } else if ((normalizedRequires = self.normalizedRequires) && // 事先声明的依赖不能当做 loaded 状态下真正的依赖 (normalizedRequiresStatus == status)) { return normalizedRequires; } else { self.normalizedRequiresStatus = status; return self.normalizedRequires = Utils.normalizeModNames(self.runtime, requires, self.name); } }
[ "function", "(", ")", "{", "var", "self", "=", "this", ",", "normalizedRequires", ",", "normalizedRequiresStatus", "=", "self", ".", "normalizedRequiresStatus", ",", "status", "=", "self", ".", "status", ",", "requires", "=", "self", ".", "requires", ";", "if", "(", "!", "requires", "||", "requires", ".", "length", "==", "0", ")", "{", "return", "requires", "||", "[", "]", ";", "}", "else", "if", "(", "(", "normalizedRequires", "=", "self", ".", "normalizedRequires", ")", "&&", "// 事先声明的依赖不能当做 loaded 状态下真正的依赖", "(", "normalizedRequiresStatus", "==", "status", ")", ")", "{", "return", "normalizedRequires", ";", "}", "else", "{", "self", ".", "normalizedRequiresStatus", "=", "status", ";", "return", "self", ".", "normalizedRequires", "=", "Utils", ".", "normalizeModNames", "(", "self", ".", "runtime", ",", "requires", ",", "self", ".", "name", ")", ";", "}", "}" ]
Get module names required by this module @return {KISSY.Loader.Module[]}
[ "Get", "module", "names", "required", "by", "this", "module" ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L4263-L4280
44,884
xudafeng/passme
demo/editor/kissy.js
function (moduleName) { var moduleNames = Utils.unalias(S, Utils.normalizeModNamesWithAlias(S, [moduleName])); if (Utils.attachModsRecursively(moduleNames, S)) { return Utils.getModules(S, moduleNames)[1]; } return undefined; }
javascript
function (moduleName) { var moduleNames = Utils.unalias(S, Utils.normalizeModNamesWithAlias(S, [moduleName])); if (Utils.attachModsRecursively(moduleNames, S)) { return Utils.getModules(S, moduleNames)[1]; } return undefined; }
[ "function", "(", "moduleName", ")", "{", "var", "moduleNames", "=", "Utils", ".", "unalias", "(", "S", ",", "Utils", ".", "normalizeModNamesWithAlias", "(", "S", ",", "[", "moduleName", "]", ")", ")", ";", "if", "(", "Utils", ".", "attachModsRecursively", "(", "moduleNames", ",", "S", ")", ")", "{", "return", "Utils", ".", "getModules", "(", "S", ",", "moduleNames", ")", "[", "1", "]", ";", "}", "return", "undefined", ";", "}" ]
get module value from KISSY module cache @param {String} moduleName module name @member KISSY @return {*} value of module which name is moduleName
[ "get", "module", "value", "from", "KISSY", "module", "cache" ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L5349-L5355
44,885
xudafeng/passme
demo/editor/kissy.js
function (data) { if (data && RE_NOT_WHITESPACE.test(data)) { // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context // http://msdn.microsoft.com/en-us/library/ie/ms536420(v=vs.85).aspx always return null ( win.execScript || function (data) { win[ 'eval' ].call(win, data); } )(data); } }
javascript
function (data) { if (data && RE_NOT_WHITESPACE.test(data)) { // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context // http://msdn.microsoft.com/en-us/library/ie/ms536420(v=vs.85).aspx always return null ( win.execScript || function (data) { win[ 'eval' ].call(win, data); } )(data); } }
[ "function", "(", "data", ")", "{", "if", "(", "data", "&&", "RE_NOT_WHITESPACE", ".", "test", "(", "data", ")", ")", "{", "// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context", "// http://msdn.microsoft.com/en-us/library/ie/ms536420(v=vs.85).aspx always return null", "(", "win", ".", "execScript", "||", "function", "(", "data", ")", "{", "win", "[", "'eval'", "]", ".", "call", "(", "win", ",", "data", ")", ";", "}", ")", "(", "data", ")", ";", "}", "}" ]
Evaluates a script in a global context. @member KISSY
[ "Evaluates", "a", "script", "in", "a", "global", "context", "." ]
14c5a9d76569fc67101b35284ea2f049bcc9896e
https://github.com/xudafeng/passme/blob/14c5a9d76569fc67101b35284ea2f049bcc9896e/demo/editor/kissy.js#L5570-L5578
44,886
nodejitsu/contour
pagelets/pills.js
links
function links(options) { var page = this.page; return this.navigation.reduce(function reduce(menu, item) { if (page === item.page) item.class = (item.class || '') + ' active'; if (item.class) item.class = ' class="' + item.class + '"'; if (item.swap) item.swap = ' data-swap="' + item.swap.hide + '@' + item.swap.show + '"'; if (item.effect) item.effect = ' data-effect="' + item.effect + '"'; item.href = item.href || '#'; return menu + options.fn(item); }, ''); }
javascript
function links(options) { var page = this.page; return this.navigation.reduce(function reduce(menu, item) { if (page === item.page) item.class = (item.class || '') + ' active'; if (item.class) item.class = ' class="' + item.class + '"'; if (item.swap) item.swap = ' data-swap="' + item.swap.hide + '@' + item.swap.show + '"'; if (item.effect) item.effect = ' data-effect="' + item.effect + '"'; item.href = item.href || '#'; return menu + options.fn(item); }, ''); }
[ "function", "links", "(", "options", ")", "{", "var", "page", "=", "this", ".", "page", ";", "return", "this", ".", "navigation", ".", "reduce", "(", "function", "reduce", "(", "menu", ",", "item", ")", "{", "if", "(", "page", "===", "item", ".", "page", ")", "item", ".", "class", "=", "(", "item", ".", "class", "||", "''", ")", "+", "' active'", ";", "if", "(", "item", ".", "class", ")", "item", ".", "class", "=", "' class=\"'", "+", "item", ".", "class", "+", "'\"'", ";", "if", "(", "item", ".", "swap", ")", "item", ".", "swap", "=", "' data-swap=\"'", "+", "item", ".", "swap", ".", "hide", "+", "'@'", "+", "item", ".", "swap", ".", "show", "+", "'\"'", ";", "if", "(", "item", ".", "effect", ")", "item", ".", "effect", "=", "' data-effect=\"'", "+", "item", ".", "effect", "+", "'\"'", ";", "item", ".", "href", "=", "item", ".", "href", "||", "'#'", ";", "return", "menu", "+", "options", ".", "fn", "(", "item", ")", ";", "}", ",", "''", ")", ";", "}" ]
Handblebar helper to generate each pill. The base is defined by the active page and should match the page defined in the navigation. @param {Object} options @return {String} generated template @api private
[ "Handblebar", "helper", "to", "generate", "each", "pill", ".", "The", "base", "is", "defined", "by", "the", "active", "page", "and", "should", "match", "the", "page", "defined", "in", "the", "navigation", "." ]
0828e9bd25ef1eeb97ea231c447118d9867021b6
https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/pills.js#L46-L59
44,887
vid/SenseBase
lib/pubsub-client.js
publish
function publish(loc, data) { data = data || {}; data.clientID = clientID; fayeClient.publish(loc, data); }
javascript
function publish(loc, data) { data = data || {}; data.clientID = clientID; fayeClient.publish(loc, data); }
[ "function", "publish", "(", "loc", ",", "data", ")", "{", "data", "=", "data", "||", "{", "}", ";", "data", ".", "clientID", "=", "clientID", ";", "fayeClient", ".", "publish", "(", "loc", ",", "data", ")", ";", "}" ]
send clientID with publish
[ "send", "clientID", "with", "publish" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/pubsub-client.js#L16-L20
44,888
vid/SenseBase
lib/pubsub-client.js
function(title, content, callback) { console.log('mltc'); publish('/query/moreLikeThisContent', { title: title, content: content }); results(callback); }
javascript
function(title, content, callback) { console.log('mltc'); publish('/query/moreLikeThisContent', { title: title, content: content }); results(callback); }
[ "function", "(", "title", ",", "content", ",", "callback", ")", "{", "console", ".", "log", "(", "'mltc'", ")", ";", "publish", "(", "'/query/moreLikeThisContent'", ",", "{", "title", ":", "title", ",", "content", ":", "content", "}", ")", ";", "results", "(", "callback", ")", ";", "}" ]
Perform a moreLikeThis query for text
[ "Perform", "a", "moreLikeThis", "query", "for", "text" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/pubsub-client.js#L93-L97
44,889
vid/SenseBase
lib/pubsub-client.js
function(options, cb) { console.log('/watch/request', options); publish('/watch/request', options); fayeClient.subscribe('/watch/results/' + clientID, cb); }
javascript
function(options, cb) { console.log('/watch/request', options); publish('/watch/request', options); fayeClient.subscribe('/watch/results/' + clientID, cb); }
[ "function", "(", "options", ",", "cb", ")", "{", "console", ".", "log", "(", "'/watch/request'", ",", "options", ")", ";", "publish", "(", "'/watch/request'", ",", "options", ")", ";", "fayeClient", ".", "subscribe", "(", "'/watch/results/'", "+", "clientID", ",", "cb", ")", ";", "}" ]
Request subscriptions for user.
[ "Request", "subscriptions", "for", "user", "." ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/pubsub-client.js#L213-L217
44,890
folkelib/folke-ko-infinite-scroll
dist/index.js
isElementInViewport
function isElementInViewport(el) { var eap; var rect = el.getBoundingClientRect(); var docEl = document.documentElement; var vWidth = window.innerWidth || docEl.clientWidth; var vHeight = window.innerHeight || docEl.clientHeight; var efp = function (x, y) { return document.elementFromPoint(x, y); }; var contains = el.contains ? (function (node) { return el.contains(node); }) : (function (node) { return el.compareDocumentPosition(node) == 0x10; }); // Return false if it's not in the viewport if (rect.right < 0 || rect.bottom < 0 || rect.left > vWidth || rect.top > vHeight) return false; // Return true if any of its four corners are visible return ((eap = efp(rect.left, rect.top)) == el || contains(eap) || (eap = efp(rect.right, rect.top)) == el || contains(eap) || (eap = efp(rect.right, rect.bottom)) == el || contains(eap) || (eap = efp(rect.left, rect.bottom)) == el || contains(eap)); }
javascript
function isElementInViewport(el) { var eap; var rect = el.getBoundingClientRect(); var docEl = document.documentElement; var vWidth = window.innerWidth || docEl.clientWidth; var vHeight = window.innerHeight || docEl.clientHeight; var efp = function (x, y) { return document.elementFromPoint(x, y); }; var contains = el.contains ? (function (node) { return el.contains(node); }) : (function (node) { return el.compareDocumentPosition(node) == 0x10; }); // Return false if it's not in the viewport if (rect.right < 0 || rect.bottom < 0 || rect.left > vWidth || rect.top > vHeight) return false; // Return true if any of its four corners are visible return ((eap = efp(rect.left, rect.top)) == el || contains(eap) || (eap = efp(rect.right, rect.top)) == el || contains(eap) || (eap = efp(rect.right, rect.bottom)) == el || contains(eap) || (eap = efp(rect.left, rect.bottom)) == el || contains(eap)); }
[ "function", "isElementInViewport", "(", "el", ")", "{", "var", "eap", ";", "var", "rect", "=", "el", ".", "getBoundingClientRect", "(", ")", ";", "var", "docEl", "=", "document", ".", "documentElement", ";", "var", "vWidth", "=", "window", ".", "innerWidth", "||", "docEl", ".", "clientWidth", ";", "var", "vHeight", "=", "window", ".", "innerHeight", "||", "docEl", ".", "clientHeight", ";", "var", "efp", "=", "function", "(", "x", ",", "y", ")", "{", "return", "document", ".", "elementFromPoint", "(", "x", ",", "y", ")", ";", "}", ";", "var", "contains", "=", "el", ".", "contains", "?", "(", "function", "(", "node", ")", "{", "return", "el", ".", "contains", "(", "node", ")", ";", "}", ")", ":", "(", "function", "(", "node", ")", "{", "return", "el", ".", "compareDocumentPosition", "(", "node", ")", "==", "0x10", ";", "}", ")", ";", "// Return false if it's not in the viewport", "if", "(", "rect", ".", "right", "<", "0", "||", "rect", ".", "bottom", "<", "0", "||", "rect", ".", "left", ">", "vWidth", "||", "rect", ".", "top", ">", "vHeight", ")", "return", "false", ";", "// Return true if any of its four corners are visible", "return", "(", "(", "eap", "=", "efp", "(", "rect", ".", "left", ",", "rect", ".", "top", ")", ")", "==", "el", "||", "contains", "(", "eap", ")", "||", "(", "eap", "=", "efp", "(", "rect", ".", "right", ",", "rect", ".", "top", ")", ")", "==", "el", "||", "contains", "(", "eap", ")", "||", "(", "eap", "=", "efp", "(", "rect", ".", "right", ",", "rect", ".", "bottom", ")", ")", "==", "el", "||", "contains", "(", "eap", ")", "||", "(", "eap", "=", "efp", "(", "rect", ".", "left", ",", "rect", ".", "bottom", ")", ")", "==", "el", "||", "contains", "(", "eap", ")", ")", ";", "}" ]
Checks if an element is in the viewport
[ "Checks", "if", "an", "element", "is", "in", "the", "viewport" ]
49aa555139b4f5cc7f75d47553b2b9b50b87bdf4
https://github.com/folkelib/folke-ko-infinite-scroll/blob/49aa555139b4f5cc7f75d47553b2b9b50b87bdf4/dist/index.js#L17-L34
44,891
canvaspop/grunt-static-versioning
tasks/versioning.js
versioningJSON
function versioningJSON ( obj, dest, ns ) { var content = {}; content[ ns ] = obj; var json = JSON.stringify( content, null, 2 ); grunt.log.subhead( 'Generating JSON config file' ); grunt.file.write( dest + '/assets.config.json', json ); grunt.log.ok( 'File "' + dest + '/assets.config.json" created.' ); }
javascript
function versioningJSON ( obj, dest, ns ) { var content = {}; content[ ns ] = obj; var json = JSON.stringify( content, null, 2 ); grunt.log.subhead( 'Generating JSON config file' ); grunt.file.write( dest + '/assets.config.json', json ); grunt.log.ok( 'File "' + dest + '/assets.config.json" created.' ); }
[ "function", "versioningJSON", "(", "obj", ",", "dest", ",", "ns", ")", "{", "var", "content", "=", "{", "}", ";", "content", "[", "ns", "]", "=", "obj", ";", "var", "json", "=", "JSON", ".", "stringify", "(", "content", ",", "null", ",", "2", ")", ";", "grunt", ".", "log", ".", "subhead", "(", "'Generating JSON config file'", ")", ";", "grunt", ".", "file", ".", "write", "(", "dest", "+", "'/assets.config.json'", ",", "json", ")", ";", "grunt", ".", "log", ".", "ok", "(", "'File \"'", "+", "dest", "+", "'/assets.config.json\" created.'", ")", ";", "}" ]
Generate a JSON config file @todo Determine if keeping these in this file is the right approach @param {Object} obj Versioning object created by the task @param {String} dest Location to save the generated config file @param {String} ns Namespace to wrap config content @return {undefined}
[ "Generate", "a", "JSON", "config", "file" ]
f347fd40e86aee639ba0e3502ae3828705ed9434
https://github.com/canvaspop/grunt-static-versioning/blob/f347fd40e86aee639ba0e3502ae3828705ed9434/tasks/versioning.js#L134-L141
44,892
canvaspop/grunt-static-versioning
tasks/versioning.js
versioningPHP
function versioningPHP ( obj, dest, ns ) { var contents = '<?php\n'; contents += 'return array(\n'; contents += ' \'' + ns + '\' => array(\n'; for ( var key in obj ) { if ( obj.hasOwnProperty( key ) ) { contents += ' \'' + key + '\' => array(\n'; contents += ' \'css\' => array(\n'; contents += extractFiles( obj[ key ].css ); contents += ' ),\n'; contents += ' \'js\' => array(\n'; contents += extractFiles( obj[ key ].js ); contents += ' ),\n'; contents += ' ),\n'; } } contents += ' )\n'; contents += ');\n'; grunt.log.subhead( 'Generating PHP config file' ); grunt.file.write( dest + '/assets.config.php', contents ); grunt.log.ok( 'File "' + dest + '/assets.config.php" created.' ); }
javascript
function versioningPHP ( obj, dest, ns ) { var contents = '<?php\n'; contents += 'return array(\n'; contents += ' \'' + ns + '\' => array(\n'; for ( var key in obj ) { if ( obj.hasOwnProperty( key ) ) { contents += ' \'' + key + '\' => array(\n'; contents += ' \'css\' => array(\n'; contents += extractFiles( obj[ key ].css ); contents += ' ),\n'; contents += ' \'js\' => array(\n'; contents += extractFiles( obj[ key ].js ); contents += ' ),\n'; contents += ' ),\n'; } } contents += ' )\n'; contents += ');\n'; grunt.log.subhead( 'Generating PHP config file' ); grunt.file.write( dest + '/assets.config.php', contents ); grunt.log.ok( 'File "' + dest + '/assets.config.php" created.' ); }
[ "function", "versioningPHP", "(", "obj", ",", "dest", ",", "ns", ")", "{", "var", "contents", "=", "'<?php\\n'", ";", "contents", "+=", "'return array(\\n'", ";", "contents", "+=", "' \\''", "+", "ns", "+", "'\\' => array(\\n'", ";", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "contents", "+=", "' \\''", "+", "key", "+", "'\\' => array(\\n'", ";", "contents", "+=", "' \\'css\\' => array(\\n'", ";", "contents", "+=", "extractFiles", "(", "obj", "[", "key", "]", ".", "css", ")", ";", "contents", "+=", "' ),\\n'", ";", "contents", "+=", "' \\'js\\' => array(\\n'", ";", "contents", "+=", "extractFiles", "(", "obj", "[", "key", "]", ".", "js", ")", ";", "contents", "+=", "' ),\\n'", ";", "contents", "+=", "' ),\\n'", ";", "}", "}", "contents", "+=", "' )\\n'", ";", "contents", "+=", "');\\n'", ";", "grunt", ".", "log", ".", "subhead", "(", "'Generating PHP config file'", ")", ";", "grunt", ".", "file", ".", "write", "(", "dest", "+", "'/assets.config.php'", ",", "contents", ")", ";", "grunt", ".", "log", ".", "ok", "(", "'File \"'", "+", "dest", "+", "'/assets.config.php\" created.'", ")", ";", "}" ]
Generate a PHP config file @todo Determine if keeping these in this file is the right approach @param {Object} obj Versioning object created by the task @param {String} dest Location to save the generated config file @param {String} ns Namespace to wrap config content @return {undefined}
[ "Generate", "a", "PHP", "config", "file" ]
f347fd40e86aee639ba0e3502ae3828705ed9434
https://github.com/canvaspop/grunt-static-versioning/blob/f347fd40e86aee639ba0e3502ae3828705ed9434/tasks/versioning.js#L153-L175
44,893
Stitchuuuu/thread-promisify
index.js
ParseMessageFromThread
function ParseMessageFromThread(o) { var o = UnserializeFromProcess(o); if (typeof(o) == "object" && o.name && o.args) { // Process response from the thread // Electron: If we are in the Main Process, and it is not a global message, we executed it too if (!isElectron || electron.ipcRenderer || !o.electronSenderId) { var args = o.args; var name = o.name; ThreadMessage[name].apply(ThreadMessage, args); } else { // Electron: Send the message to the correct window var electronSenderId = o.electronSenderId; ipc.sendTo(electronSenderId, "threadify-message", o); } } }
javascript
function ParseMessageFromThread(o) { var o = UnserializeFromProcess(o); if (typeof(o) == "object" && o.name && o.args) { // Process response from the thread // Electron: If we are in the Main Process, and it is not a global message, we executed it too if (!isElectron || electron.ipcRenderer || !o.electronSenderId) { var args = o.args; var name = o.name; ThreadMessage[name].apply(ThreadMessage, args); } else { // Electron: Send the message to the correct window var electronSenderId = o.electronSenderId; ipc.sendTo(electronSenderId, "threadify-message", o); } } }
[ "function", "ParseMessageFromThread", "(", "o", ")", "{", "var", "o", "=", "UnserializeFromProcess", "(", "o", ")", ";", "if", "(", "typeof", "(", "o", ")", "==", "\"object\"", "&&", "o", ".", "name", "&&", "o", ".", "args", ")", "{", "// Process response from the thread", "// Electron: If we are in the Main Process, and it is not a global message, we executed it too", "if", "(", "!", "isElectron", "||", "electron", ".", "ipcRenderer", "||", "!", "o", ".", "electronSenderId", ")", "{", "var", "args", "=", "o", ".", "args", ";", "var", "name", "=", "o", ".", "name", ";", "ThreadMessage", "[", "name", "]", ".", "apply", "(", "ThreadMessage", ",", "args", ")", ";", "}", "else", "{", "// Electron: Send the message to the correct window", "var", "electronSenderId", "=", "o", ".", "electronSenderId", ";", "ipc", ".", "sendTo", "(", "electronSenderId", ",", "\"threadify-message\"", ",", "o", ")", ";", "}", "}", "}" ]
Parse the message from the thread or just passthrough to the Electron Renderer Process concerned
[ "Parse", "the", "message", "from", "the", "thread", "or", "just", "passthrough", "to", "the", "Electron", "Renderer", "Process", "concerned" ]
5c6fc0b481520049e2078461693ceee7c27ddd53
https://github.com/Stitchuuuu/thread-promisify/blob/5c6fc0b481520049e2078461693ceee7c27ddd53/index.js#L159-L175
44,894
Stitchuuuu/thread-promisify
index.js
CheckPendingThreadRequests
function CheckPendingThreadRequests() { while (PendingThreadRequests.length) { var tq = PendingThreadRequests.shift(); if (!SendThreadRequest(tq)) { // No available thread, we queue the request, again PendingThreadRequests.unshift(tq); break; } } }
javascript
function CheckPendingThreadRequests() { while (PendingThreadRequests.length) { var tq = PendingThreadRequests.shift(); if (!SendThreadRequest(tq)) { // No available thread, we queue the request, again PendingThreadRequests.unshift(tq); break; } } }
[ "function", "CheckPendingThreadRequests", "(", ")", "{", "while", "(", "PendingThreadRequests", ".", "length", ")", "{", "var", "tq", "=", "PendingThreadRequests", ".", "shift", "(", ")", ";", "if", "(", "!", "SendThreadRequest", "(", "tq", ")", ")", "{", "// No available thread, we queue the request, again", "PendingThreadRequests", ".", "unshift", "(", "tq", ")", ";", "break", ";", "}", "}", "}" ]
Check if there is a request waiting and execute it on an inactive thread available
[ "Check", "if", "there", "is", "a", "request", "waiting", "and", "execute", "it", "on", "an", "inactive", "thread", "available" ]
5c6fc0b481520049e2078461693ceee7c27ddd53
https://github.com/Stitchuuuu/thread-promisify/blob/5c6fc0b481520049e2078461693ceee7c27ddd53/index.js#L183-L192
44,895
Stitchuuuu/thread-promisify
index.js
findObject
function findObject(c, obj, path, alreadyParsed) { if (!path) { path = []; } // Recursive reference : boooh, very wrong if (!alreadyParsed) { alreadyParsed = []; } var keys = Object.keys(obj); alreadyParsed.push(obj); for (var key = 0; key < keys.length; key++) { var i = keys[key]; if (i == "NativeModule" && isElectron) { break; } if (obj[i] === c) { path.push(i); return path; } else if (["object", "function"].indexOf(typeof(obj[i])) >= 0 && alreadyParsed.indexOf(obj[i]) == -1 && obj[i] !== null && obj[i] !== undefined) { path.push(i); var founded = findObject(c, obj[i], path, alreadyParsed); if (founded) { return founded; } else { path.pop(); } } }; return null; }
javascript
function findObject(c, obj, path, alreadyParsed) { if (!path) { path = []; } // Recursive reference : boooh, very wrong if (!alreadyParsed) { alreadyParsed = []; } var keys = Object.keys(obj); alreadyParsed.push(obj); for (var key = 0; key < keys.length; key++) { var i = keys[key]; if (i == "NativeModule" && isElectron) { break; } if (obj[i] === c) { path.push(i); return path; } else if (["object", "function"].indexOf(typeof(obj[i])) >= 0 && alreadyParsed.indexOf(obj[i]) == -1 && obj[i] !== null && obj[i] !== undefined) { path.push(i); var founded = findObject(c, obj[i], path, alreadyParsed); if (founded) { return founded; } else { path.pop(); } } }; return null; }
[ "function", "findObject", "(", "c", ",", "obj", ",", "path", ",", "alreadyParsed", ")", "{", "if", "(", "!", "path", ")", "{", "path", "=", "[", "]", ";", "}", "// Recursive reference : boooh, very wrong", "if", "(", "!", "alreadyParsed", ")", "{", "alreadyParsed", "=", "[", "]", ";", "}", "var", "keys", "=", "Object", ".", "keys", "(", "obj", ")", ";", "alreadyParsed", ".", "push", "(", "obj", ")", ";", "for", "(", "var", "key", "=", "0", ";", "key", "<", "keys", ".", "length", ";", "key", "++", ")", "{", "var", "i", "=", "keys", "[", "key", "]", ";", "if", "(", "i", "==", "\"NativeModule\"", "&&", "isElectron", ")", "{", "break", ";", "}", "if", "(", "obj", "[", "i", "]", "===", "c", ")", "{", "path", ".", "push", "(", "i", ")", ";", "return", "path", ";", "}", "else", "if", "(", "[", "\"object\"", ",", "\"function\"", "]", ".", "indexOf", "(", "typeof", "(", "obj", "[", "i", "]", ")", ")", ">=", "0", "&&", "alreadyParsed", ".", "indexOf", "(", "obj", "[", "i", "]", ")", "==", "-", "1", "&&", "obj", "[", "i", "]", "!==", "null", "&&", "obj", "[", "i", "]", "!==", "undefined", ")", "{", "path", ".", "push", "(", "i", ")", ";", "var", "founded", "=", "findObject", "(", "c", ",", "obj", "[", "i", "]", ",", "path", ",", "alreadyParsed", ")", ";", "if", "(", "founded", ")", "{", "return", "founded", ";", "}", "else", "{", "path", ".", "pop", "(", ")", ";", "}", "}", "}", ";", "return", "null", ";", "}" ]
Find an object recursively and return the path where it was founded Use in Threadify function to find the module and the path to the object so we can clone it in the thread
[ "Find", "an", "object", "recursively", "and", "return", "the", "path", "where", "it", "was", "founded", "Use", "in", "Threadify", "function", "to", "find", "the", "module", "and", "the", "path", "to", "the", "object", "so", "we", "can", "clone", "it", "in", "the", "thread" ]
5c6fc0b481520049e2078461693ceee7c27ddd53
https://github.com/Stitchuuuu/thread-promisify/blob/5c6fc0b481520049e2078461693ceee7c27ddd53/index.js#L414-L444
44,896
Stitchuuuu/thread-promisify
index.js
Threadify
function Threadify(options) { if (typeof(options) == "string") { options = {methods: [options]}; } else if (Array.isArray(options)) { options = {methods: options}; } else { if (options !== undefined && typeof(options) != "object") { throw new Error("[Threadify] You must specify either: \nNothing\nA string\nAn array of string\n") } } var options = Object.assign({ module: null, exportsPath: null, methods: [] }, options); // We automatically search the class or the object in the module loaded if (!options.module) { var cacheFounded = null; var pathExport = []; var parsedModule = [require.main, require.cache]; for (var i in require.cache) { var cache = require.cache[i]; // If module have exports, we search the class/object in it if (cache.exports) { var objectToSearch = {}; // We exclude electron modules because of a lot of loop references if (isElectron && cache.filename.indexOf("/node_modules/electron/") >= 0) { continue; } var pathObject = []; if (cache.exports !== this) { pathObject = findObject(this, cache.exports, [], parsedModule); } if (pathObject !== null) { cacheFounded = {module: cache, pathToClass: pathObject}; break; } } } if (!cacheFounded) { throw new Error("[Threadify] Class to threadify must be in a non-core separate module."); } else { options.module = cacheFounded.module.filename; options.exportsPath = cacheFounded.pathToClass; } } return ThreadifyAll(this, options); }
javascript
function Threadify(options) { if (typeof(options) == "string") { options = {methods: [options]}; } else if (Array.isArray(options)) { options = {methods: options}; } else { if (options !== undefined && typeof(options) != "object") { throw new Error("[Threadify] You must specify either: \nNothing\nA string\nAn array of string\n") } } var options = Object.assign({ module: null, exportsPath: null, methods: [] }, options); // We automatically search the class or the object in the module loaded if (!options.module) { var cacheFounded = null; var pathExport = []; var parsedModule = [require.main, require.cache]; for (var i in require.cache) { var cache = require.cache[i]; // If module have exports, we search the class/object in it if (cache.exports) { var objectToSearch = {}; // We exclude electron modules because of a lot of loop references if (isElectron && cache.filename.indexOf("/node_modules/electron/") >= 0) { continue; } var pathObject = []; if (cache.exports !== this) { pathObject = findObject(this, cache.exports, [], parsedModule); } if (pathObject !== null) { cacheFounded = {module: cache, pathToClass: pathObject}; break; } } } if (!cacheFounded) { throw new Error("[Threadify] Class to threadify must be in a non-core separate module."); } else { options.module = cacheFounded.module.filename; options.exportsPath = cacheFounded.pathToClass; } } return ThreadifyAll(this, options); }
[ "function", "Threadify", "(", "options", ")", "{", "if", "(", "typeof", "(", "options", ")", "==", "\"string\"", ")", "{", "options", "=", "{", "methods", ":", "[", "options", "]", "}", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "options", ")", ")", "{", "options", "=", "{", "methods", ":", "options", "}", ";", "}", "else", "{", "if", "(", "options", "!==", "undefined", "&&", "typeof", "(", "options", ")", "!=", "\"object\"", ")", "{", "throw", "new", "Error", "(", "\"[Threadify] You must specify either: \\nNothing\\nA string\\nAn array of string\\n\"", ")", "}", "}", "var", "options", "=", "Object", ".", "assign", "(", "{", "module", ":", "null", ",", "exportsPath", ":", "null", ",", "methods", ":", "[", "]", "}", ",", "options", ")", ";", "// We automatically search the class or the object in the module loaded", "if", "(", "!", "options", ".", "module", ")", "{", "var", "cacheFounded", "=", "null", ";", "var", "pathExport", "=", "[", "]", ";", "var", "parsedModule", "=", "[", "require", ".", "main", ",", "require", ".", "cache", "]", ";", "for", "(", "var", "i", "in", "require", ".", "cache", ")", "{", "var", "cache", "=", "require", ".", "cache", "[", "i", "]", ";", "// If module have exports, we search the class/object in it", "if", "(", "cache", ".", "exports", ")", "{", "var", "objectToSearch", "=", "{", "}", ";", "// We exclude electron modules because of a lot of loop references", "if", "(", "isElectron", "&&", "cache", ".", "filename", ".", "indexOf", "(", "\"/node_modules/electron/\"", ")", ">=", "0", ")", "{", "continue", ";", "}", "var", "pathObject", "=", "[", "]", ";", "if", "(", "cache", ".", "exports", "!==", "this", ")", "{", "pathObject", "=", "findObject", "(", "this", ",", "cache", ".", "exports", ",", "[", "]", ",", "parsedModule", ")", ";", "}", "if", "(", "pathObject", "!==", "null", ")", "{", "cacheFounded", "=", "{", "module", ":", "cache", ",", "pathToClass", ":", "pathObject", "}", ";", "break", ";", "}", "}", "}", "if", "(", "!", "cacheFounded", ")", "{", "throw", "new", "Error", "(", "\"[Threadify] Class to threadify must be in a non-core separate module.\"", ")", ";", "}", "else", "{", "options", ".", "module", "=", "cacheFounded", ".", "module", ".", "filename", ";", "options", ".", "exportsPath", "=", "cacheFounded", ".", "pathToClass", ";", "}", "}", "return", "ThreadifyAll", "(", "this", ",", "options", ")", ";", "}" ]
Threadify a class or an object defined in a separate uncore module Cored module like fs, path, and others can't be threadified Options can be: - Nothing: all functions are threadified - A String: the specific function is threadified - An array of string: all the functions specified are threadified For class only: The current object is sent to the thread and then reproduced If you want to use some properties, be sure to have them accessible (public properties) Private ones can't be accessed
[ "Threadify", "a", "class", "or", "an", "object", "defined", "in", "a", "separate", "uncore", "module", "Cored", "module", "like", "fs", "path", "and", "others", "can", "t", "be", "threadified" ]
5c6fc0b481520049e2078461693ceee7c27ddd53
https://github.com/Stitchuuuu/thread-promisify/blob/5c6fc0b481520049e2078461693ceee7c27ddd53/index.js#L461-L512
44,897
fullcube/loopback-component-meta
index.js
getSettings
function getSettings (def) { var settings = {} for (var s in def) { if (def.hasOwnProperty(s)) { if (s !== 'name' || s !== 'properties') { settings[ s ] = def[ s ] } } } return settings }
javascript
function getSettings (def) { var settings = {} for (var s in def) { if (def.hasOwnProperty(s)) { if (s !== 'name' || s !== 'properties') { settings[ s ] = def[ s ] } } } return settings }
[ "function", "getSettings", "(", "def", ")", "{", "var", "settings", "=", "{", "}", "for", "(", "var", "s", "in", "def", ")", "{", "if", "(", "def", ".", "hasOwnProperty", "(", "s", ")", ")", "{", "if", "(", "s", "!==", "'name'", "||", "s", "!==", "'properties'", ")", "{", "settings", "[", "s", "]", "=", "def", "[", "s", "]", "}", "}", "}", "return", "settings", "}" ]
Remove properties that will confuse LB
[ "Remove", "properties", "that", "will", "confuse", "LB" ]
b91bc0e93881f8e47ac88a77d4a91231053b219a
https://github.com/fullcube/loopback-component-meta/blob/b91bc0e93881f8e47ac88a77d4a91231053b219a/index.js#L5-L15
44,898
vid/SenseBase
services/annotators/annotateLib.js
instancesFromMatches
function instancesFromMatches(word, text, selector) { var match, ret = []; var re = new RegExp('\\b'+utils.escapeRegex(word)+'\\b', 'gi'); var instance = 1; while ((match = re.exec(text)) !== null) { GLOBAL.debug(text.length, text.substring(0, 10), word, match.index, text.substr(match.index, word.length)); // It's not in a tag if (text.indexOf('<' < 0) || (text.indexOf('>', match.index) > text.indexOf('<'.match.index))) { ret.push(annoLib.createInstance({exact: text.substr(match.index, word.length), instance: instance, selector: selector})); } instance++; } return ret; }
javascript
function instancesFromMatches(word, text, selector) { var match, ret = []; var re = new RegExp('\\b'+utils.escapeRegex(word)+'\\b', 'gi'); var instance = 1; while ((match = re.exec(text)) !== null) { GLOBAL.debug(text.length, text.substring(0, 10), word, match.index, text.substr(match.index, word.length)); // It's not in a tag if (text.indexOf('<' < 0) || (text.indexOf('>', match.index) > text.indexOf('<'.match.index))) { ret.push(annoLib.createInstance({exact: text.substr(match.index, word.length), instance: instance, selector: selector})); } instance++; } return ret; }
[ "function", "instancesFromMatches", "(", "word", ",", "text", ",", "selector", ")", "{", "var", "match", ",", "ret", "=", "[", "]", ";", "var", "re", "=", "new", "RegExp", "(", "'\\\\b'", "+", "utils", ".", "escapeRegex", "(", "word", ")", "+", "'\\\\b'", ",", "'gi'", ")", ";", "var", "instance", "=", "1", ";", "while", "(", "(", "match", "=", "re", ".", "exec", "(", "text", ")", ")", "!==", "null", ")", "{", "GLOBAL", ".", "debug", "(", "text", ".", "length", ",", "text", ".", "substring", "(", "0", ",", "10", ")", ",", "word", ",", "match", ".", "index", ",", "text", ".", "substr", "(", "match", ".", "index", ",", "word", ".", "length", ")", ")", ";", "// It's not in a tag", "if", "(", "text", ".", "indexOf", "(", "'<'", "<", "0", ")", "||", "(", "text", ".", "indexOf", "(", "'>'", ",", "match", ".", "index", ")", ">", "text", ".", "indexOf", "(", "'<'", ".", "match", ".", "index", ")", ")", ")", "{", "ret", ".", "push", "(", "annoLib", ".", "createInstance", "(", "{", "exact", ":", "text", ".", "substr", "(", "match", ".", "index", ",", "word", ".", "length", ")", ",", "instance", ":", "instance", ",", "selector", ":", "selector", "}", ")", ")", ";", "}", "instance", "++", ";", "}", "return", "ret", ";", "}" ]
convert instances of a match to instances
[ "convert", "instances", "of", "a", "match", "to", "instances" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/services/annotators/annotateLib.js#L40-L53
44,899
vid/SenseBase
services/annotators/annotateLib.js
rangesFromMatches
function rangesFromMatches(word, text, selector) { var ret = [], match; var re = new RegExp('\\b'+word+'\\b', 'gi'); while ((match = re.exec(text)) !== null) { GLOBAL.debug(text.length, text.substring(0, 10), word, match.index, text.substr(match.index, word.length)); ret.push(annoLib.createRange({exact: text.substr(match.index, word.length), offset: match.index, selector: selector})); } return ret; }
javascript
function rangesFromMatches(word, text, selector) { var ret = [], match; var re = new RegExp('\\b'+word+'\\b', 'gi'); while ((match = re.exec(text)) !== null) { GLOBAL.debug(text.length, text.substring(0, 10), word, match.index, text.substr(match.index, word.length)); ret.push(annoLib.createRange({exact: text.substr(match.index, word.length), offset: match.index, selector: selector})); } return ret; }
[ "function", "rangesFromMatches", "(", "word", ",", "text", ",", "selector", ")", "{", "var", "ret", "=", "[", "]", ",", "match", ";", "var", "re", "=", "new", "RegExp", "(", "'\\\\b'", "+", "word", "+", "'\\\\b'", ",", "'gi'", ")", ";", "while", "(", "(", "match", "=", "re", ".", "exec", "(", "text", ")", ")", "!==", "null", ")", "{", "GLOBAL", ".", "debug", "(", "text", ".", "length", ",", "text", ".", "substring", "(", "0", ",", "10", ")", ",", "word", ",", "match", ".", "index", ",", "text", ".", "substr", "(", "match", ".", "index", ",", "word", ".", "length", ")", ")", ";", "ret", ".", "push", "(", "annoLib", ".", "createRange", "(", "{", "exact", ":", "text", ".", "substr", "(", "match", ".", "index", ",", "word", ".", "length", ")", ",", "offset", ":", "match", ".", "index", ",", "selector", ":", "selector", "}", ")", ")", ";", "}", "return", "ret", ";", "}" ]
convert instances of a match to ranges
[ "convert", "instances", "of", "a", "match", "to", "ranges" ]
d60bcf28239e7dde437d8a6bdae41a6921dcd05b
https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/services/annotators/annotateLib.js#L55-L63