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
partition
stringclasses
1 value
stadt-bielefeld/wms-capabilities-tools
index.js
determineWMSAbstract
function determineWMSAbstract(json, version) { var ret = ''; if (version == '1.3.0') { if (json.WMS_Capabilities.Service) { if (json.WMS_Capabilities.Service[0]) { if (json.WMS_Capabilities.Service[0].Abstract) { if (json.WMS_Capabilities.Service[0].Abstract[0]) { ret = json.WMS_Capabilities.Service[0].Abstract[0]; } } } } } else { if (version == '1.1.1' || version == '1.1.0' || version == '1.0.0') { if (json.WMT_MS_Capabilities.Service) { if (json.WMT_MS_Capabilities.Service[0]) { if (json.WMT_MS_Capabilities.Service[0].Abstract) { if (json.WMT_MS_Capabilities.Service[0].Abstract[0]) { ret = json.WMT_MS_Capabilities.Service[0].Abstract[0]; } } } } } } return ret; }
javascript
function determineWMSAbstract(json, version) { var ret = ''; if (version == '1.3.0') { if (json.WMS_Capabilities.Service) { if (json.WMS_Capabilities.Service[0]) { if (json.WMS_Capabilities.Service[0].Abstract) { if (json.WMS_Capabilities.Service[0].Abstract[0]) { ret = json.WMS_Capabilities.Service[0].Abstract[0]; } } } } } else { if (version == '1.1.1' || version == '1.1.0' || version == '1.0.0') { if (json.WMT_MS_Capabilities.Service) { if (json.WMT_MS_Capabilities.Service[0]) { if (json.WMT_MS_Capabilities.Service[0].Abstract) { if (json.WMT_MS_Capabilities.Service[0].Abstract[0]) { ret = json.WMT_MS_Capabilities.Service[0].Abstract[0]; } } } } } } return ret; }
[ "function", "determineWMSAbstract", "(", "json", ",", "version", ")", "{", "var", "ret", "=", "''", ";", "if", "(", "version", "==", "'1.3.0'", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ".", "Abstract", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ".", "Abstract", "[", "0", "]", ")", "{", "ret", "=", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ".", "Abstract", "[", "0", "]", ";", "}", "}", "}", "}", "}", "else", "{", "if", "(", "version", "==", "'1.1.1'", "||", "version", "==", "'1.1.0'", "||", "version", "==", "'1.0.0'", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "Service", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "Service", "[", "0", "]", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "Service", "[", "0", "]", ".", "Abstract", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "Service", "[", "0", "]", ".", "Abstract", "[", "0", "]", ")", "{", "ret", "=", "json", ".", "WMT_MS_Capabilities", ".", "Service", "[", "0", "]", ".", "Abstract", "[", "0", "]", ";", "}", "}", "}", "}", "}", "}", "return", "ret", ";", "}" ]
It determines the WMS abstract. @param {object} json GetCapabilities document as JSON. @param {string} version Version of GetCapabilities document. @returns {string} WMS abstract.
[ "It", "determines", "the", "WMS", "abstract", "." ]
647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1
https://github.com/stadt-bielefeld/wms-capabilities-tools/blob/647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1/index.js#L438-L466
train
sazze/node-thrift
lib/_thriftHttpClient.js
Client
function Client(host, port, path, service, transport, protocol) { if (!service.hasOwnProperty('Client')) { throw new Error('Thrift Service must have a Client'); } /** * The host of the thrift server * * @type {string} */ this.host = host; /** * The port of the thrift server * * @type {Number} */ this.port = port; /** * The path for the thrift server * * @type {string} */ this.path = path; /** * Whether or not to autoClose connection * * @type {boolean} */ this.autoClose = true; /** * The thrift service * * @type {Object} */ this.service = service; /** * The thrift transport * * @type {*|TBufferedTransport} */ this.transport = transport || thrift.TBufferedTransport; /** * The thrift protocol * * @type {*|exports.TBinaryProtocol} */ this.protocol = protocol || thrift.TBinaryProtocol; /** * The Thrift Service Client * @type {Client} */ this.client = new service.Client; /** * The Thrift Client Connection * * @type {*} * @private */ this._connection = null; /** * The Thrift Client * * @type {null} * @private */ this._client = null; /** * Whether or not we are connected to thrift * * @type {boolean} */ this.isConnected = false; /** * A Success Pre-parser Callback * @param {*} data * @param {Function} Success Callback * @param {Function} Error Callback * @type {Function|null} */ this.successCallback = null; /** * A Error Pre-parser Callback * @param {*} data * @param {Function} Error Callback * @type {Function|null} */ this.errorCallback = null; }
javascript
function Client(host, port, path, service, transport, protocol) { if (!service.hasOwnProperty('Client')) { throw new Error('Thrift Service must have a Client'); } /** * The host of the thrift server * * @type {string} */ this.host = host; /** * The port of the thrift server * * @type {Number} */ this.port = port; /** * The path for the thrift server * * @type {string} */ this.path = path; /** * Whether or not to autoClose connection * * @type {boolean} */ this.autoClose = true; /** * The thrift service * * @type {Object} */ this.service = service; /** * The thrift transport * * @type {*|TBufferedTransport} */ this.transport = transport || thrift.TBufferedTransport; /** * The thrift protocol * * @type {*|exports.TBinaryProtocol} */ this.protocol = protocol || thrift.TBinaryProtocol; /** * The Thrift Service Client * @type {Client} */ this.client = new service.Client; /** * The Thrift Client Connection * * @type {*} * @private */ this._connection = null; /** * The Thrift Client * * @type {null} * @private */ this._client = null; /** * Whether or not we are connected to thrift * * @type {boolean} */ this.isConnected = false; /** * A Success Pre-parser Callback * @param {*} data * @param {Function} Success Callback * @param {Function} Error Callback * @type {Function|null} */ this.successCallback = null; /** * A Error Pre-parser Callback * @param {*} data * @param {Function} Error Callback * @type {Function|null} */ this.errorCallback = null; }
[ "function", "Client", "(", "host", ",", "port", ",", "path", ",", "service", ",", "transport", ",", "protocol", ")", "{", "if", "(", "!", "service", ".", "hasOwnProperty", "(", "'Client'", ")", ")", "{", "throw", "new", "Error", "(", "'Thrift Service must have a Client'", ")", ";", "}", "this", ".", "host", "=", "host", ";", "this", ".", "port", "=", "port", ";", "this", ".", "path", "=", "path", ";", "this", ".", "autoClose", "=", "true", ";", "this", ".", "service", "=", "service", ";", "this", ".", "transport", "=", "transport", "||", "thrift", ".", "TBufferedTransport", ";", "this", ".", "protocol", "=", "protocol", "||", "thrift", ".", "TBinaryProtocol", ";", "this", ".", "client", "=", "new", "service", ".", "Client", ";", "this", ".", "_connection", "=", "null", ";", "this", ".", "_client", "=", "null", ";", "this", ".", "isConnected", "=", "false", ";", "this", ".", "successCallback", "=", "null", ";", "this", ".", "errorCallback", "=", "null", ";", "}" ]
Create a new thrift client @param {string} host @param {int} port @param {string} path @param {Object} service @param {Transport} transport @param {Protocol} protocol @throws {Error} error If thrift service does not have a Client property @constructor
[ "Create", "a", "new", "thrift", "client" ]
458d1829813cbd2d50dae610bc7210b75140e58f
https://github.com/sazze/node-thrift/blob/458d1829813cbd2d50dae610bc7210b75140e58f/lib/_thriftHttpClient.js#L31-L130
train
llamadeus/data-to-png
es/png.js
createChunk
function createChunk(type, data) { const length = typeof data != 'undefined' ? data.length : 0; const chunk = Buffer.alloc(4 + 4 + length + 4); chunk.writeUInt32BE(length, 0); chunk.fill(type, 4, 8, 'utf8'); if (typeof data != 'undefined') { chunk.fill(data, 8, chunk.length - 4); } chunk.writeUInt32BE(crc32(chunk.slice(4, -4)), chunk.length - 4); return chunk; }
javascript
function createChunk(type, data) { const length = typeof data != 'undefined' ? data.length : 0; const chunk = Buffer.alloc(4 + 4 + length + 4); chunk.writeUInt32BE(length, 0); chunk.fill(type, 4, 8, 'utf8'); if (typeof data != 'undefined') { chunk.fill(data, 8, chunk.length - 4); } chunk.writeUInt32BE(crc32(chunk.slice(4, -4)), chunk.length - 4); return chunk; }
[ "function", "createChunk", "(", "type", ",", "data", ")", "{", "const", "length", "=", "typeof", "data", "!=", "'undefined'", "?", "data", ".", "length", ":", "0", ";", "const", "chunk", "=", "Buffer", ".", "alloc", "(", "4", "+", "4", "+", "length", "+", "4", ")", ";", "chunk", ".", "writeUInt32BE", "(", "length", ",", "0", ")", ";", "chunk", ".", "fill", "(", "type", ",", "4", ",", "8", ",", "'utf8'", ")", ";", "if", "(", "typeof", "data", "!=", "'undefined'", ")", "{", "chunk", ".", "fill", "(", "data", ",", "8", ",", "chunk", ".", "length", "-", "4", ")", ";", "}", "chunk", ".", "writeUInt32BE", "(", "crc32", "(", "chunk", ".", "slice", "(", "4", ",", "-", "4", ")", ")", ",", "chunk", ".", "length", "-", "4", ")", ";", "return", "chunk", ";", "}" ]
Create a chunk of the given type with the given data. @param type @param data @returns {Buffer}
[ "Create", "a", "chunk", "of", "the", "given", "type", "with", "the", "given", "data", "." ]
8170197b4213d86a56c7b0cc4952f80a1e840766
https://github.com/llamadeus/data-to-png/blob/8170197b4213d86a56c7b0cc4952f80a1e840766/es/png.js#L27-L39
train
rootslab/shashi
lib/shashi.js
function ( n, buffer, bytes ) { var s = ( n % k ) * slen // how many bytes to read/consume from the input buffer [1 to 4] , rbytes = bytes >>> 0 ? abs( bytes ) % 5 : ibytes , blen = buffer.length - rbytes , bruint = null , sum = 0 , b = 0 ; /* * NOTE: js is not capable to handle integers larger than ~2^53, * when the sum exceeds this limit, we expect to get get biased * results, or in other words, more collisions. It will happens * when we are using large primes as range, or with long buffer * in input. If sum === sum + 1, we could break the for cycle. */ if ( rbytes === 1 ) { // use [] notation when reading input, 1 byte at the time. if ( ibytes === 1 ) { // read input and seed 1 byte at the time for ( ; b <= blen && s <= rlen; ++b, ++s ) sum += buffer[ b ] * result[ s ]; return sum % prange; } for ( ; b <= blen && s <= rlen; ++b, s += ibytes ) sum += buffer[ b ] * result[ ruint ]( s ); return sum % prange; } // build string for read method (16, 24 or 32 bits unsigned integers) bruint = bruint = 'readUInt' + ( rbytes << 3 ) + 'BE'; for ( ; b <= blen && s <= rlen; b += rbytes, s += ibytes ) { sum += buffer[ bruint ]( b ) * result[ ruint ]( s ); sum %= prange; } return sum; }
javascript
function ( n, buffer, bytes ) { var s = ( n % k ) * slen // how many bytes to read/consume from the input buffer [1 to 4] , rbytes = bytes >>> 0 ? abs( bytes ) % 5 : ibytes , blen = buffer.length - rbytes , bruint = null , sum = 0 , b = 0 ; /* * NOTE: js is not capable to handle integers larger than ~2^53, * when the sum exceeds this limit, we expect to get get biased * results, or in other words, more collisions. It will happens * when we are using large primes as range, or with long buffer * in input. If sum === sum + 1, we could break the for cycle. */ if ( rbytes === 1 ) { // use [] notation when reading input, 1 byte at the time. if ( ibytes === 1 ) { // read input and seed 1 byte at the time for ( ; b <= blen && s <= rlen; ++b, ++s ) sum += buffer[ b ] * result[ s ]; return sum % prange; } for ( ; b <= blen && s <= rlen; ++b, s += ibytes ) sum += buffer[ b ] * result[ ruint ]( s ); return sum % prange; } // build string for read method (16, 24 or 32 bits unsigned integers) bruint = bruint = 'readUInt' + ( rbytes << 3 ) + 'BE'; for ( ; b <= blen && s <= rlen; b += rbytes, s += ibytes ) { sum += buffer[ bruint ]( b ) * result[ ruint ]( s ); sum %= prange; } return sum; }
[ "function", "(", "n", ",", "buffer", ",", "bytes", ")", "{", "var", "s", "=", "(", "n", "%", "k", ")", "*", "slen", ",", "rbytes", "=", "bytes", ">>>", "0", "?", "abs", "(", "bytes", ")", "%", "5", ":", "ibytes", ",", "blen", "=", "buffer", ".", "length", "-", "rbytes", ",", "bruint", "=", "null", ",", "sum", "=", "0", ",", "b", "=", "0", ";", "if", "(", "rbytes", "===", "1", ")", "{", "if", "(", "ibytes", "===", "1", ")", "{", "for", "(", ";", "b", "<=", "blen", "&&", "s", "<=", "rlen", ";", "++", "b", ",", "++", "s", ")", "sum", "+=", "buffer", "[", "b", "]", "*", "result", "[", "s", "]", ";", "return", "sum", "%", "prange", ";", "}", "for", "(", ";", "b", "<=", "blen", "&&", "s", "<=", "rlen", ";", "++", "b", ",", "s", "+=", "ibytes", ")", "sum", "+=", "buffer", "[", "b", "]", "*", "result", "[", "ruint", "]", "(", "s", ")", ";", "return", "sum", "%", "prange", ";", "}", "bruint", "=", "bruint", "=", "'readUInt'", "+", "(", "rbytes", "<<", "3", ")", "+", "'BE'", ";", "for", "(", ";", "b", "<=", "blen", "&&", "s", "<=", "rlen", ";", "b", "+=", "rbytes", ",", "s", "+=", "ibytes", ")", "{", "sum", "+=", "buffer", "[", "bruint", "]", "(", "b", ")", "*", "result", "[", "ruint", "]", "(", "s", ")", ";", "sum", "%=", "prange", ";", "}", "return", "sum", ";", "}" ]
generate random seed sequence for requested range
[ "generate", "random", "seed", "sequence", "for", "requested", "range" ]
24a52dfe45035a387937de210a93411ecbac0bfc
https://github.com/rootslab/shashi/blob/24a52dfe45035a387937de210a93411ecbac0bfc/lib/shashi.js#L42-L77
train
daliwali/promise-middleware
lib/index.js
promiseMiddleware
function promiseMiddleware (request, response, middleware) { return new promiseMiddleware.Promise(function (resolve, reject) { middleware(request, response, function next (error) { return error ? reject(error) : resolve() }) }) }
javascript
function promiseMiddleware (request, response, middleware) { return new promiseMiddleware.Promise(function (resolve, reject) { middleware(request, response, function next (error) { return error ? reject(error) : resolve() }) }) }
[ "function", "promiseMiddleware", "(", "request", ",", "response", ",", "middleware", ")", "{", "return", "new", "promiseMiddleware", ".", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "middleware", "(", "request", ",", "response", ",", "function", "next", "(", "error", ")", "{", "return", "error", "?", "reject", "(", "error", ")", ":", "resolve", "(", ")", "}", ")", "}", ")", "}" ]
Use callback middleware functions as promises. @param {Object} request @param {Object} response @param {Function} middleware
[ "Use", "callback", "middleware", "functions", "as", "promises", "." ]
5dc63fc74e12fbd7804577b4694c2941f607ba64
https://github.com/daliwali/promise-middleware/blob/5dc63fc74e12fbd7804577b4694c2941f607ba64/lib/index.js#L14-L20
train
SimonSchick/esprintf
index.js
paddLeft
function paddLeft(str, length, what) { if (length <= str.length) { return str.substring(0, length); } what = what || ' '; return what.repeat(length - str.length) + str; }
javascript
function paddLeft(str, length, what) { if (length <= str.length) { return str.substring(0, length); } what = what || ' '; return what.repeat(length - str.length) + str; }
[ "function", "paddLeft", "(", "str", ",", "length", ",", "what", ")", "{", "if", "(", "length", "<=", "str", ".", "length", ")", "{", "return", "str", ".", "substring", "(", "0", ",", "length", ")", ";", "}", "what", "=", "what", "||", "' '", ";", "return", "what", ".", "repeat", "(", "length", "-", "str", ".", "length", ")", "+", "str", ";", "}" ]
Padds or truncates a string left. @param {String} str The string to be modified @param {Number} length Length of the final string @param {String} what The padding string(should be one character) @return {String}
[ "Padds", "or", "truncates", "a", "string", "left", "." ]
0aedf87a2c55a7daaa17a24d77625f5af86eea41
https://github.com/SimonSchick/esprintf/blob/0aedf87a2c55a7daaa17a24d77625f5af86eea41/index.js#L10-L16
train
SimonSchick/esprintf
index.js
paddRight
function paddRight(str, length, what) { if (length <= str.length) { return str.substring(0, length); } what = what || ' '; return str + what.repeat(length - str.length); }
javascript
function paddRight(str, length, what) { if (length <= str.length) { return str.substring(0, length); } what = what || ' '; return str + what.repeat(length - str.length); }
[ "function", "paddRight", "(", "str", ",", "length", ",", "what", ")", "{", "if", "(", "length", "<=", "str", ".", "length", ")", "{", "return", "str", ".", "substring", "(", "0", ",", "length", ")", ";", "}", "what", "=", "what", "||", "' '", ";", "return", "str", "+", "what", ".", "repeat", "(", "length", "-", "str", ".", "length", ")", ";", "}" ]
Padds or truncates a string right. @param {String} str The string to be modified @param {Number} length Length of the final string @param {String} what The padding string(should be one character) @return {String}
[ "Padds", "or", "truncates", "a", "string", "right", "." ]
0aedf87a2c55a7daaa17a24d77625f5af86eea41
https://github.com/SimonSchick/esprintf/blob/0aedf87a2c55a7daaa17a24d77625f5af86eea41/index.js#L25-L31
train
SimonSchick/esprintf
index.js
precBase
function precBase(base, value, precision) { const val = value.toString(base); const floatingPoint = val.indexOf('.'); if (precision === 0 && floatingPoint > -1) { return val.substring(0, floatingPoint);//Node version > 0.10.* } if (floatingPoint === -1) { return val; } if (val.length - floatingPoint > precision) { return val.substring(0, floatingPoint + precision + 1); } }
javascript
function precBase(base, value, precision) { const val = value.toString(base); const floatingPoint = val.indexOf('.'); if (precision === 0 && floatingPoint > -1) { return val.substring(0, floatingPoint);//Node version > 0.10.* } if (floatingPoint === -1) { return val; } if (val.length - floatingPoint > precision) { return val.substring(0, floatingPoint + precision + 1); } }
[ "function", "precBase", "(", "base", ",", "value", ",", "precision", ")", "{", "const", "val", "=", "value", ".", "toString", "(", "base", ")", ";", "const", "floatingPoint", "=", "val", ".", "indexOf", "(", "'.'", ")", ";", "if", "(", "precision", "===", "0", "&&", "floatingPoint", ">", "-", "1", ")", "{", "return", "val", ".", "substring", "(", "0", ",", "floatingPoint", ")", ";", "}", "if", "(", "floatingPoint", "===", "-", "1", ")", "{", "return", "val", ";", "}", "if", "(", "val", ".", "length", "-", "floatingPoint", ">", "precision", ")", "{", "return", "val", ".", "substring", "(", "0", ",", "floatingPoint", "+", "precision", "+", "1", ")", ";", "}", "}" ]
Converts the given value to the new numeric base and truncates the precision to the given value. @param {Number} base Should follow the restrictions of Number.prototype.toString() @param {Number} value @param {Number} precision @return {String}
[ "Converts", "the", "given", "value", "to", "the", "new", "numeric", "base", "and", "truncates", "the", "precision", "to", "the", "given", "value", "." ]
0aedf87a2c55a7daaa17a24d77625f5af86eea41
https://github.com/SimonSchick/esprintf/blob/0aedf87a2c55a7daaa17a24d77625f5af86eea41/index.js#L45-L57
train
pierrec/node-atok-parser
examples/simple_CSV.js
ParserContent
function ParserContent () { // Parser reference var self = this // Current row var data = [] // Define the parser rules var eol = ['\n','\r\n'] var sep = options.separator || ',' // Handlers are used instead of events atok // Ignore comments .ignore(true) // On rule match, do not do anything, skip the token .addRule('#', eol, 'comment') .ignore() // Turn the ignore property off // Anything else is data // Rule definition: // first argument: always an exact match. To match anything, use '' // next arguments: array of possible matches (first match wins) .addRule('', { firstOf: [ sep ].concat(eol) }, function (token, idx) { // token=the matched data // idx=when using array of patterns, the index of the matched pattern if (token === 'error') { // Build the error message using positioning var err = self.trackError(new Error('Dummy message'), token) self.emit('error', err) return } // Add the data data.push(token) // EOL reached, the parser emits the row if (idx > 0) { self.emit('data', data) data = [] } }) }
javascript
function ParserContent () { // Parser reference var self = this // Current row var data = [] // Define the parser rules var eol = ['\n','\r\n'] var sep = options.separator || ',' // Handlers are used instead of events atok // Ignore comments .ignore(true) // On rule match, do not do anything, skip the token .addRule('#', eol, 'comment') .ignore() // Turn the ignore property off // Anything else is data // Rule definition: // first argument: always an exact match. To match anything, use '' // next arguments: array of possible matches (first match wins) .addRule('', { firstOf: [ sep ].concat(eol) }, function (token, idx) { // token=the matched data // idx=when using array of patterns, the index of the matched pattern if (token === 'error') { // Build the error message using positioning var err = self.trackError(new Error('Dummy message'), token) self.emit('error', err) return } // Add the data data.push(token) // EOL reached, the parser emits the row if (idx > 0) { self.emit('data', data) data = [] } }) }
[ "function", "ParserContent", "(", ")", "{", "var", "self", "=", "this", "var", "data", "=", "[", "]", "var", "eol", "=", "[", "'\\n'", ",", "\\n", "]", "'\\r\\n'", "\\r", "}" ]
This is a rudimentary CSV parser In this simple version, the data must not contain any coma and double quotes are not processed.
[ "This", "is", "a", "rudimentary", "CSV", "parser", "In", "this", "simple", "version", "the", "data", "must", "not", "contain", "any", "coma", "and", "double", "quotes", "are", "not", "processed", "." ]
414d39904dff73ffdde049212076c14ca40aa20b
https://github.com/pierrec/node-atok-parser/blob/414d39904dff73ffdde049212076c14ca40aa20b/examples/simple_CSV.js#L6-L42
train
Asw20/session-data
lib/sessionData.js
_sessionData
function _sessionData(variable, value, parameter) { if (this.session === undefined) throw Error('req.sessionData() requires sessions'); var values = this.session.sessionData = this.session.sessionData || {}; if (variable && value) { // Special handling for configuration if (parameter=='setup') { delete values[variable]; } // Special handling for breadcrumb if (variable == 'breadcrumb') { // Do not Add the same Last Url (in case of refresh if (value=='back') { // console.log('%s values[variable].length',srcName,values[variable].length) if (values[variable].length < 2 ) { return values[variable][0] } else { values[variable].pop(); return values[variable].pop(); } } else { if (values[variable] && (values[variable][values[variable].length-1] == value)){ return; } } } // util.format is available in Node.js 0.6+ if (arguments.length > 2 && format && parameter != 'setup' && parameter != 'read') { var args = Array.prototype.slice.call(arguments, 1); value = format.apply(undefined, args); } else if (isArray(value)) { value.forEach(function(val){ (values[variable] = values[variable] || []).push(val); }); return values[variable].length; } return (values[variable] = values[variable] || []).push(value); } else if (variable) { var arr = values[variable]; if ((variable != 'breadcrumb') && (parameter != 'read')){ delete values[variable]; } return arr || []; } else { this.session._sessionData = {}; return values; } }
javascript
function _sessionData(variable, value, parameter) { if (this.session === undefined) throw Error('req.sessionData() requires sessions'); var values = this.session.sessionData = this.session.sessionData || {}; if (variable && value) { // Special handling for configuration if (parameter=='setup') { delete values[variable]; } // Special handling for breadcrumb if (variable == 'breadcrumb') { // Do not Add the same Last Url (in case of refresh if (value=='back') { // console.log('%s values[variable].length',srcName,values[variable].length) if (values[variable].length < 2 ) { return values[variable][0] } else { values[variable].pop(); return values[variable].pop(); } } else { if (values[variable] && (values[variable][values[variable].length-1] == value)){ return; } } } // util.format is available in Node.js 0.6+ if (arguments.length > 2 && format && parameter != 'setup' && parameter != 'read') { var args = Array.prototype.slice.call(arguments, 1); value = format.apply(undefined, args); } else if (isArray(value)) { value.forEach(function(val){ (values[variable] = values[variable] || []).push(val); }); return values[variable].length; } return (values[variable] = values[variable] || []).push(value); } else if (variable) { var arr = values[variable]; if ((variable != 'breadcrumb') && (parameter != 'read')){ delete values[variable]; } return arr || []; } else { this.session._sessionData = {}; return values; } }
[ "function", "_sessionData", "(", "variable", ",", "value", ",", "parameter", ")", "{", "if", "(", "this", ".", "session", "===", "undefined", ")", "throw", "Error", "(", "'req.sessionData() requires sessions'", ")", ";", "var", "values", "=", "this", ".", "session", ".", "sessionData", "=", "this", ".", "session", ".", "sessionData", "||", "{", "}", ";", "if", "(", "variable", "&&", "value", ")", "{", "if", "(", "parameter", "==", "'setup'", ")", "{", "delete", "values", "[", "variable", "]", ";", "}", "if", "(", "variable", "==", "'breadcrumb'", ")", "{", "if", "(", "value", "==", "'back'", ")", "{", "if", "(", "values", "[", "variable", "]", ".", "length", "<", "2", ")", "{", "return", "values", "[", "variable", "]", "[", "0", "]", "}", "else", "{", "values", "[", "variable", "]", ".", "pop", "(", ")", ";", "return", "values", "[", "variable", "]", ".", "pop", "(", ")", ";", "}", "}", "else", "{", "if", "(", "values", "[", "variable", "]", "&&", "(", "values", "[", "variable", "]", "[", "values", "[", "variable", "]", ".", "length", "-", "1", "]", "==", "value", ")", ")", "{", "return", ";", "}", "}", "}", "if", "(", "arguments", ".", "length", ">", "2", "&&", "format", "&&", "parameter", "!=", "'setup'", "&&", "parameter", "!=", "'read'", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "value", "=", "format", ".", "apply", "(", "undefined", ",", "args", ")", ";", "}", "else", "if", "(", "isArray", "(", "value", ")", ")", "{", "value", ".", "forEach", "(", "function", "(", "val", ")", "{", "(", "values", "[", "variable", "]", "=", "values", "[", "variable", "]", "||", "[", "]", ")", ".", "push", "(", "val", ")", ";", "}", ")", ";", "return", "values", "[", "variable", "]", ".", "length", ";", "}", "return", "(", "values", "[", "variable", "]", "=", "values", "[", "variable", "]", "||", "[", "]", ")", ".", "push", "(", "value", ")", ";", "}", "else", "if", "(", "variable", ")", "{", "var", "arr", "=", "values", "[", "variable", "]", ";", "if", "(", "(", "variable", "!=", "'breadcrumb'", ")", "&&", "(", "parameter", "!=", "'read'", ")", ")", "{", "delete", "values", "[", "variable", "]", ";", "}", "return", "arr", "||", "[", "]", ";", "}", "else", "{", "this", ".", "session", ".", "_sessionData", "=", "{", "}", ";", "return", "values", ";", "}", "}" ]
Queue sessionData `value` of the given `Variable`. Examples: Regular behavior: req.sessionData('var01', 'value01'); req.sessionData('var01', 'value02'); req.sessionData('var01', 'value03'); req.sessionData('var02', 'value20'); req.sessionData('var02', 'value21'); // req.sessionData('var01') => value01,value02,value03 // req.sessionData('var01') => [] // req.sessionData('var02') => value20,value21 // req.sessionData('var02') => [] Special behavior: config: req.sessionData('keyconf01','confvalue01', 'setup'); req.sessionData('keyconf02','confvalue01', 'setup'); req.sessionData('keyconf03','confvalue02', 'read'); // req.sessionData() => { var01 :[], var02: ['value20'], var03: ['value30','value31'] } Special behavior: breadcrumb req.sessionData('breadcrumb', 'value10'); req.sessionData('breadcrumb', 'value11'); req.sessionData('breadcrumb', 'value12'); // req.sessionData('breadcrumb') => value12 // req.sessionData('back') => value12 Formatting: sessionData notifications also support arbitrary formatting support. For example you may pass variable arguments to `req.sessionData()` and use the %s specifier to be replaced by the associated argument: req.sessionData('info', 'email has been sent to %s.', userName); Formatting uses `util.format()`, which is available on Node 0.6+. @param {String} variable (key) @param {String} value (value of the key) @param {String} parameter ( @return {Array|Object|Number} @api public
[ "Queue", "sessionData", "value", "of", "the", "given", "Variable", "." ]
3e3c645951661556354d387ebc4b8732c7c55331
https://github.com/Asw20/session-data/blob/3e3c645951661556354d387ebc4b8732c7c55331/lib/sessionData.js#L78-L130
train
Athaphian/grunt-websocket
tasks/websocket.js
function (server) { // Retrieve the configured handler. if (handler) { handler = require(require('path').resolve() + '/' + handler); } else { console.log('No handler defined for websocket server, not starting websocket.'); return; } // Attach websockets server to http server var WebSocketServer = require('websocket').server; var wsServer = new WebSocketServer({ httpServer: server }); // Handle requests wsServer.on('request', handler); }
javascript
function (server) { // Retrieve the configured handler. if (handler) { handler = require(require('path').resolve() + '/' + handler); } else { console.log('No handler defined for websocket server, not starting websocket.'); return; } // Attach websockets server to http server var WebSocketServer = require('websocket').server; var wsServer = new WebSocketServer({ httpServer: server }); // Handle requests wsServer.on('request', handler); }
[ "function", "(", "server", ")", "{", "if", "(", "handler", ")", "{", "handler", "=", "require", "(", "require", "(", "'path'", ")", ".", "resolve", "(", ")", "+", "'/'", "+", "handler", ")", ";", "}", "else", "{", "console", ".", "log", "(", "'No handler defined for websocket server, not starting websocket.'", ")", ";", "return", ";", "}", "var", "WebSocketServer", "=", "require", "(", "'websocket'", ")", ".", "server", ";", "var", "wsServer", "=", "new", "WebSocketServer", "(", "{", "httpServer", ":", "server", "}", ")", ";", "wsServer", ".", "on", "(", "'request'", ",", "handler", ")", ";", "}" ]
Attaches a websocket server to the specified http server.
[ "Attaches", "a", "websocket", "server", "to", "the", "specified", "http", "server", "." ]
5fad7f1a568f290f9ec7ac5597b49d588de7c2ec
https://github.com/Athaphian/grunt-websocket/blob/5fad7f1a568f290f9ec7ac5597b49d588de7c2ec/tasks/websocket.js#L26-L44
train
nopnop/docflux
lib/transform.js
transform
function transform() { var stack = []; var inside = false; var out = false; var writable = combiner(split(), through2(function(line, encoding, done) { line = line.toString(); if(out) { // Comment with a white space below are ignored if(line.trim() != '') { readable.write(parser(stack.join('\n'), line)) } out = false; stack = []; } else if(!inside) { if(/\s*\/\*\*/.test(line)) { stack = []; inside = true; } } else if(inside) { if(/\*\/\s*$/.test(line)) { inside = false out = true } else { stack.push(line.replace(/^\s*\*{1,2}\s?/,'')); } } done(); }, function(done) { // readable.write(null) readable.emit('end') done(); })) var readable = through2.obj(); return duplexer(writable, readable) }
javascript
function transform() { var stack = []; var inside = false; var out = false; var writable = combiner(split(), through2(function(line, encoding, done) { line = line.toString(); if(out) { // Comment with a white space below are ignored if(line.trim() != '') { readable.write(parser(stack.join('\n'), line)) } out = false; stack = []; } else if(!inside) { if(/\s*\/\*\*/.test(line)) { stack = []; inside = true; } } else if(inside) { if(/\*\/\s*$/.test(line)) { inside = false out = true } else { stack.push(line.replace(/^\s*\*{1,2}\s?/,'')); } } done(); }, function(done) { // readable.write(null) readable.emit('end') done(); })) var readable = through2.obj(); return duplexer(writable, readable) }
[ "function", "transform", "(", ")", "{", "var", "stack", "=", "[", "]", ";", "var", "inside", "=", "false", ";", "var", "out", "=", "false", ";", "var", "writable", "=", "combiner", "(", "split", "(", ")", ",", "through2", "(", "function", "(", "line", ",", "encoding", ",", "done", ")", "{", "line", "=", "line", ".", "toString", "(", ")", ";", "if", "(", "out", ")", "{", "if", "(", "line", ".", "trim", "(", ")", "!=", "''", ")", "{", "readable", ".", "write", "(", "parser", "(", "stack", ".", "join", "(", "'\\n'", ")", ",", "\\n", ")", ")", "}", "line", "out", "=", "false", ";", "}", "else", "stack", "=", "[", "]", ";", "if", "(", "!", "inside", ")", "{", "if", "(", "/", "\\s*\\/\\*\\*", "/", ".", "test", "(", "line", ")", ")", "{", "stack", "=", "[", "]", ";", "inside", "=", "true", ";", "}", "}", "else", "if", "(", "inside", ")", "{", "if", "(", "/", "\\*\\/\\s*$", "/", ".", "test", "(", "line", ")", ")", "{", "inside", "=", "false", "out", "=", "true", "}", "else", "{", "stack", ".", "push", "(", "line", ".", "replace", "(", "/", "^\\s*\\*{1,2}\\s?", "/", ",", "''", ")", ")", ";", "}", "}", "}", ",", "done", "(", ")", ";", ")", ")", "function", "(", "done", ")", "{", "readable", ".", "emit", "(", "'end'", ")", "done", "(", ")", ";", "}", "var", "readable", "=", "through2", ".", "obj", "(", ")", ";", "}" ]
Create a doc-block extractor stream This function take a buffer stream as input and output a object stream of docflux object (objectified documentation block) Example: ```javascript var docflux = require('docflux'); process.stdin(docflux()) .on('data', function(jsdoc) { console.log(JSON.stringify(jsdoc, null, 2)) }) ``` @return {Stream}
[ "Create", "a", "doc", "-", "block", "extractor", "stream" ]
3929fdac9d1e959946fb48f3e8a269d338841902
https://github.com/nopnop/docflux/blob/3929fdac9d1e959946fb48f3e8a269d338841902/lib/transform.js#L29-L66
train
seanmpuckett/sai
lib/saigrammar.js
TaskClauseFormatter
function TaskClauseFormatter(o) { var params=[]; if (!o.nodefaultparam) { params.push('p'); } var expects='',locals=[];//$unused=this'; if (o.expects && o.as) fail("SAI compile: cannot have both EXPECTS and AS in a function declaration"); if (o.expects && o.expects.length) { expects=GetExpectsTester(o.expects,'in-line'); } else if (o.as) { for (var i in o.as) { if (i==0) { locals.push(o.as[i][0][1]+'='+params[0]); } else { params.push(o.as[i][0][1]); } } } if (!o.preface) o.preface=''; if (!o.postface) o.postface=''; var finallocals=[]; for (var i in locals) if (!References[locals[i]]) finallocals.push(locals[i]); locals=locals.length?('var '+finallocals.join(',')+';'):''; var code = o.kind+'('+params.join(',')+'){'+o.preface+locals+expects+'{'+o.block+'}'+o.postface+'}'; if (o.execute) code+='()'; return code; }
javascript
function TaskClauseFormatter(o) { var params=[]; if (!o.nodefaultparam) { params.push('p'); } var expects='',locals=[];//$unused=this'; if (o.expects && o.as) fail("SAI compile: cannot have both EXPECTS and AS in a function declaration"); if (o.expects && o.expects.length) { expects=GetExpectsTester(o.expects,'in-line'); } else if (o.as) { for (var i in o.as) { if (i==0) { locals.push(o.as[i][0][1]+'='+params[0]); } else { params.push(o.as[i][0][1]); } } } if (!o.preface) o.preface=''; if (!o.postface) o.postface=''; var finallocals=[]; for (var i in locals) if (!References[locals[i]]) finallocals.push(locals[i]); locals=locals.length?('var '+finallocals.join(',')+';'):''; var code = o.kind+'('+params.join(',')+'){'+o.preface+locals+expects+'{'+o.block+'}'+o.postface+'}'; if (o.execute) code+='()'; return code; }
[ "function", "TaskClauseFormatter", "(", "o", ")", "{", "var", "params", "=", "[", "]", ";", "if", "(", "!", "o", ".", "nodefaultparam", ")", "{", "params", ".", "push", "(", "'p'", ")", ";", "}", "var", "expects", "=", "''", ",", "locals", "=", "[", "]", ";", "if", "(", "o", ".", "expects", "&&", "o", ".", "as", ")", "fail", "(", "\"SAI compile: cannot have both EXPECTS and AS in a function declaration\"", ")", ";", "if", "(", "o", ".", "expects", "&&", "o", ".", "expects", ".", "length", ")", "{", "expects", "=", "GetExpectsTester", "(", "o", ".", "expects", ",", "'in-line'", ")", ";", "}", "else", "if", "(", "o", ".", "as", ")", "{", "for", "(", "var", "i", "in", "o", ".", "as", ")", "{", "if", "(", "i", "==", "0", ")", "{", "locals", ".", "push", "(", "o", ".", "as", "[", "i", "]", "[", "0", "]", "[", "1", "]", "+", "'='", "+", "params", "[", "0", "]", ")", ";", "}", "else", "{", "params", ".", "push", "(", "o", ".", "as", "[", "i", "]", "[", "0", "]", "[", "1", "]", ")", ";", "}", "}", "}", "if", "(", "!", "o", ".", "preface", ")", "o", ".", "preface", "=", "''", ";", "if", "(", "!", "o", ".", "postface", ")", "o", ".", "postface", "=", "''", ";", "var", "finallocals", "=", "[", "]", ";", "for", "(", "var", "i", "in", "locals", ")", "if", "(", "!", "References", "[", "locals", "[", "i", "]", "]", ")", "finallocals", ".", "push", "(", "locals", "[", "i", "]", ")", ";", "locals", "=", "locals", ".", "length", "?", "(", "'var '", "+", "finallocals", ".", "join", "(", "','", ")", "+", "';'", ")", ":", "''", ";", "var", "code", "=", "o", ".", "kind", "+", "'('", "+", "params", ".", "join", "(", "','", ")", "+", "'){'", "+", "o", ".", "preface", "+", "locals", "+", "expects", "+", "'{'", "+", "o", ".", "block", "+", "'}'", "+", "o", ".", "postface", "+", "'}'", ";", "if", "(", "o", ".", "execute", ")", "code", "+=", "'()'", ";", "return", "code", ";", "}" ]
expects as kind body preface appendix
[ "expects", "as", "kind", "body", "preface", "appendix" ]
759274a3078bef6939e634f2761656dc8db547d2
https://github.com/seanmpuckett/sai/blob/759274a3078bef6939e634f2761656dc8db547d2/lib/saigrammar.js#L2352-L2378
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
handleFieldValidated
function handleFieldValidated( isValid, msg ) { var input = this.getInputElement(); if ( input ) isValid ? input.removeAttribute( 'aria-invalid' ) : input.setAttribute( 'aria-invalid', true ); if ( !isValid ) { if ( this.select ) this.select(); else this.focus(); } msg && alert( msg ); this.fire( 'validated', { valid: isValid, msg: msg } ); }
javascript
function handleFieldValidated( isValid, msg ) { var input = this.getInputElement(); if ( input ) isValid ? input.removeAttribute( 'aria-invalid' ) : input.setAttribute( 'aria-invalid', true ); if ( !isValid ) { if ( this.select ) this.select(); else this.focus(); } msg && alert( msg ); this.fire( 'validated', { valid: isValid, msg: msg } ); }
[ "function", "handleFieldValidated", "(", "isValid", ",", "msg", ")", "{", "var", "input", "=", "this", ".", "getInputElement", "(", ")", ";", "if", "(", "input", ")", "isValid", "?", "input", ".", "removeAttribute", "(", "'aria-invalid'", ")", ":", "input", ".", "setAttribute", "(", "'aria-invalid'", ",", "true", ")", ";", "if", "(", "!", "isValid", ")", "{", "if", "(", "this", ".", "select", ")", "this", ".", "select", "(", ")", ";", "else", "this", ".", "focus", "(", ")", ";", "}", "msg", "&&", "alert", "(", "msg", ")", ";", "this", ".", "fire", "(", "'validated'", ",", "{", "valid", ":", "isValid", ",", "msg", ":", "msg", "}", ")", ";", "}" ]
Handle dialog element validation state UI changes.
[ "Handle", "dialog", "element", "validation", "state", "UI", "changes", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L98-L113
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( func ) { var contents = me._.contents, stop = false; for ( var i in contents ) { for ( var j in contents[ i ] ) { stop = func.call( this, contents[ i ][ j ] ); if ( stop ) return; } } }
javascript
function( func ) { var contents = me._.contents, stop = false; for ( var i in contents ) { for ( var j in contents[ i ] ) { stop = func.call( this, contents[ i ][ j ] ); if ( stop ) return; } } }
[ "function", "(", "func", ")", "{", "var", "contents", "=", "me", ".", "_", ".", "contents", ",", "stop", "=", "false", ";", "for", "(", "var", "i", "in", "contents", ")", "{", "for", "(", "var", "j", "in", "contents", "[", "i", "]", ")", "{", "stop", "=", "func", ".", "call", "(", "this", ",", "contents", "[", "i", "]", "[", "j", "]", ")", ";", "if", "(", "stop", ")", "return", ";", "}", "}", "}" ]
Iterates over all items inside all content in the dialog, calling a function for each of them.
[ "Iterates", "over", "all", "items", "inside", "all", "content", "in", "the", "dialog", "calling", "a", "function", "for", "each", "of", "them", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L339-L350
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
setupFocus
function setupFocus() { var focusList = me._.focusList; focusList.sort( function( a, b ) { // Mimics browser tab order logics; if ( a.tabIndex != b.tabIndex ) return b.tabIndex - a.tabIndex; // Sort is not stable in some browsers, // fall-back the comparator to 'focusIndex'; else return a.focusIndex - b.focusIndex; } ); var size = focusList.length; for ( var i = 0; i < size; i++ ) focusList[ i ].focusIndex = i; }
javascript
function setupFocus() { var focusList = me._.focusList; focusList.sort( function( a, b ) { // Mimics browser tab order logics; if ( a.tabIndex != b.tabIndex ) return b.tabIndex - a.tabIndex; // Sort is not stable in some browsers, // fall-back the comparator to 'focusIndex'; else return a.focusIndex - b.focusIndex; } ); var size = focusList.length; for ( var i = 0; i < size; i++ ) focusList[ i ].focusIndex = i; }
[ "function", "setupFocus", "(", ")", "{", "var", "focusList", "=", "me", ".", "_", ".", "focusList", ";", "focusList", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "if", "(", "a", ".", "tabIndex", "!=", "b", ".", "tabIndex", ")", "return", "b", ".", "tabIndex", "-", "a", ".", "tabIndex", ";", "else", "return", "a", ".", "focusIndex", "-", "b", ".", "focusIndex", ";", "}", ")", ";", "var", "size", "=", "focusList", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "focusList", "[", "i", "]", ".", "focusIndex", "=", "i", ";", "}" ]
Sort focus list according to tab order definitions.
[ "Sort", "focus", "list", "according", "to", "tab", "order", "definitions", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L386-L401
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
Focusable
function Focusable( dialog, element, index ) { this.element = element; this.focusIndex = index; // TODO: support tabIndex for focusables. this.tabIndex = 0; this.isFocusable = function() { return !element.getAttribute( 'disabled' ) && element.isVisible(); }; this.focus = function() { dialog._.currentFocusIndex = this.focusIndex; this.element.focus(); }; // Bind events element.on( 'keydown', function( e ) { if ( e.data.getKeystroke() in { 32: 1, 13: 1 } ) this.fire( 'click' ); } ); element.on( 'focus', function() { this.fire( 'mouseover' ); } ); element.on( 'blur', function() { this.fire( 'mouseout' ); } ); }
javascript
function Focusable( dialog, element, index ) { this.element = element; this.focusIndex = index; // TODO: support tabIndex for focusables. this.tabIndex = 0; this.isFocusable = function() { return !element.getAttribute( 'disabled' ) && element.isVisible(); }; this.focus = function() { dialog._.currentFocusIndex = this.focusIndex; this.element.focus(); }; // Bind events element.on( 'keydown', function( e ) { if ( e.data.getKeystroke() in { 32: 1, 13: 1 } ) this.fire( 'click' ); } ); element.on( 'focus', function() { this.fire( 'mouseover' ); } ); element.on( 'blur', function() { this.fire( 'mouseout' ); } ); }
[ "function", "Focusable", "(", "dialog", ",", "element", ",", "index", ")", "{", "this", ".", "element", "=", "element", ";", "this", ".", "focusIndex", "=", "index", ";", "this", ".", "tabIndex", "=", "0", ";", "this", ".", "isFocusable", "=", "function", "(", ")", "{", "return", "!", "element", ".", "getAttribute", "(", "'disabled'", ")", "&&", "element", ".", "isVisible", "(", ")", ";", "}", ";", "this", ".", "focus", "=", "function", "(", ")", "{", "dialog", ".", "_", ".", "currentFocusIndex", "=", "this", ".", "focusIndex", ";", "this", ".", "element", ".", "focus", "(", ")", ";", "}", ";", "element", ".", "on", "(", "'keydown'", ",", "function", "(", "e", ")", "{", "if", "(", "e", ".", "data", ".", "getKeystroke", "(", ")", "in", "{", "32", ":", "1", ",", "13", ":", "1", "}", ")", "this", ".", "fire", "(", "'click'", ")", ";", "}", ")", ";", "element", ".", "on", "(", "'focus'", ",", "function", "(", ")", "{", "this", ".", "fire", "(", "'mouseover'", ")", ";", "}", ")", ";", "element", ".", "on", "(", "'blur'", ",", "function", "(", ")", "{", "this", ".", "fire", "(", "'mouseout'", ")", ";", "}", ")", ";", "}" ]
Focusable interface. Use it via dialog.addFocusable.
[ "Focusable", "interface", ".", "Use", "it", "via", "dialog", ".", "addFocusable", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L622-L645
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
resizeWithWindow
function resizeWithWindow( dialog ) { var win = CKEDITOR.document.getWindow(); function resizeHandler() { dialog.layout(); } win.on( 'resize', resizeHandler ); dialog.on( 'hide', function() { win.removeListener( 'resize', resizeHandler ); } ); }
javascript
function resizeWithWindow( dialog ) { var win = CKEDITOR.document.getWindow(); function resizeHandler() { dialog.layout(); } win.on( 'resize', resizeHandler ); dialog.on( 'hide', function() { win.removeListener( 'resize', resizeHandler ); } ); }
[ "function", "resizeWithWindow", "(", "dialog", ")", "{", "var", "win", "=", "CKEDITOR", ".", "document", ".", "getWindow", "(", ")", ";", "function", "resizeHandler", "(", ")", "{", "dialog", ".", "layout", "(", ")", ";", "}", "win", ".", "on", "(", "'resize'", ",", "resizeHandler", ")", ";", "dialog", ".", "on", "(", "'hide'", ",", "function", "(", ")", "{", "win", ".", "removeListener", "(", "'resize'", ",", "resizeHandler", ")", ";", "}", ")", ";", "}" ]
Re-layout the dialog on window resize.
[ "Re", "-", "layout", "the", "dialog", "on", "window", "resize", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L648-L653
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function() { var element = this._.element.getFirst(); return { width: element.$.offsetWidth || 0, height: element.$.offsetHeight || 0 }; }
javascript
function() { var element = this._.element.getFirst(); return { width: element.$.offsetWidth || 0, height: element.$.offsetHeight || 0 }; }
[ "function", "(", ")", "{", "var", "element", "=", "this", ".", "_", ".", "element", ".", "getFirst", "(", ")", ";", "return", "{", "width", ":", "element", ".", "$", ".", "offsetWidth", "||", "0", ",", "height", ":", "element", ".", "$", ".", "offsetHeight", "||", "0", "}", ";", "}" ]
Gets the current size of the dialog in pixels. var width = dialogObj.getSize().width; @returns {Object} @returns {Number} return.width @returns {Number} return.height
[ "Gets", "the", "current", "size", "of", "the", "dialog", "in", "pixels", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L709-L712
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function() { var el = this.parts.dialog; var dialogSize = this.getSize(); var win = CKEDITOR.document.getWindow(), viewSize = win.getViewPaneSize(); var posX = ( viewSize.width - dialogSize.width ) / 2, posY = ( viewSize.height - dialogSize.height ) / 2; // Switch to absolute position when viewport is smaller than dialog size. if ( !CKEDITOR.env.ie6Compat ) { if ( dialogSize.height + ( posY > 0 ? posY : 0 ) > viewSize.height || dialogSize.width + ( posX > 0 ? posX : 0 ) > viewSize.width ) el.setStyle( 'position', 'absolute' ); else el.setStyle( 'position', 'fixed' ); } this.move( this._.moved ? this._.position.x : posX, this._.moved ? this._.position.y : posY ); }
javascript
function() { var el = this.parts.dialog; var dialogSize = this.getSize(); var win = CKEDITOR.document.getWindow(), viewSize = win.getViewPaneSize(); var posX = ( viewSize.width - dialogSize.width ) / 2, posY = ( viewSize.height - dialogSize.height ) / 2; // Switch to absolute position when viewport is smaller than dialog size. if ( !CKEDITOR.env.ie6Compat ) { if ( dialogSize.height + ( posY > 0 ? posY : 0 ) > viewSize.height || dialogSize.width + ( posX > 0 ? posX : 0 ) > viewSize.width ) el.setStyle( 'position', 'absolute' ); else el.setStyle( 'position', 'fixed' ); } this.move( this._.moved ? this._.position.x : posX, this._.moved ? this._.position.y : posY ); }
[ "function", "(", ")", "{", "var", "el", "=", "this", ".", "parts", ".", "dialog", ";", "var", "dialogSize", "=", "this", ".", "getSize", "(", ")", ";", "var", "win", "=", "CKEDITOR", ".", "document", ".", "getWindow", "(", ")", ",", "viewSize", "=", "win", ".", "getViewPaneSize", "(", ")", ";", "var", "posX", "=", "(", "viewSize", ".", "width", "-", "dialogSize", ".", "width", ")", "/", "2", ",", "posY", "=", "(", "viewSize", ".", "height", "-", "dialogSize", ".", "height", ")", "/", "2", ";", "if", "(", "!", "CKEDITOR", ".", "env", ".", "ie6Compat", ")", "{", "if", "(", "dialogSize", ".", "height", "+", "(", "posY", ">", "0", "?", "posY", ":", "0", ")", ">", "viewSize", ".", "height", "||", "dialogSize", ".", "width", "+", "(", "posX", ">", "0", "?", "posX", ":", "0", ")", ">", "viewSize", ".", "width", ")", "el", ".", "setStyle", "(", "'position'", ",", "'absolute'", ")", ";", "else", "el", ".", "setStyle", "(", "'position'", ",", "'fixed'", ")", ";", "}", "this", ".", "move", "(", "this", ".", "_", ".", "moved", "?", "this", ".", "_", ".", "position", ".", "x", ":", "posX", ",", "this", ".", "_", ".", "moved", "?", "this", ".", "_", ".", "position", ".", "y", ":", "posY", ")", ";", "}" ]
Rearrange the dialog to its previous position or the middle of the window. @since 3.5
[ "Rearrange", "the", "dialog", "to", "its", "previous", "position", "or", "the", "middle", "of", "the", "window", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L890-L910
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( fn ) { for ( var i in this._.contents ) { for ( var j in this._.contents[ i ] ) fn.call( this, this._.contents[ i ][ j ] ); } return this; }
javascript
function( fn ) { for ( var i in this._.contents ) { for ( var j in this._.contents[ i ] ) fn.call( this, this._.contents[ i ][ j ] ); } return this; }
[ "function", "(", "fn", ")", "{", "for", "(", "var", "i", "in", "this", ".", "_", ".", "contents", ")", "{", "for", "(", "var", "j", "in", "this", ".", "_", ".", "contents", "[", "i", "]", ")", "fn", ".", "call", "(", "this", ",", "this", ".", "_", ".", "contents", "[", "i", "]", "[", "j", "]", ")", ";", "}", "return", "this", ";", "}" ]
Executes a function for each UI element. @param {Function} fn Function to execute for each UI element. @returns {CKEDITOR.dialog} The current dialog object.
[ "Executes", "a", "function", "for", "each", "UI", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L918-L924
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function() { if ( !this.parts.dialog.isVisible() ) return; this.fire( 'hide', {} ); this._.editor.fire( 'dialogHide', this ); // Reset the tab page. this.selectPage( this._.tabIdList[ 0 ] ); var element = this._.element; element.setStyle( 'display', 'none' ); this.parts.dialog.setStyle( 'visibility', 'hidden' ); // Unregister all access keys associated with this dialog. unregisterAccessKey( this ); // Close any child(top) dialogs first. while ( CKEDITOR.dialog._.currentTop != this ) CKEDITOR.dialog._.currentTop.hide(); // Maintain dialog ordering and remove cover if needed. if ( !this._.parentDialog ) hideCover( this._.editor ); else { var parentElement = this._.parentDialog.getElement().getFirst(); parentElement.setStyle( 'z-index', parseInt( parentElement.$.style.zIndex, 10 ) + Math.floor( this._.editor.config.baseFloatZIndex / 2 ) ); } CKEDITOR.dialog._.currentTop = this._.parentDialog; // Deduct or clear the z-index. if ( !this._.parentDialog ) { CKEDITOR.dialog._.currentZIndex = null; // Remove access key handlers. element.removeListener( 'keydown', accessKeyDownHandler ); element.removeListener( 'keyup', accessKeyUpHandler ); var editor = this._.editor; editor.focus(); // Give a while before unlock, waiting for focus to return to the editable. (#172) setTimeout( function() { editor.focusManager.unlock(); // Fixed iOS focus issue (#12381). // Keep in mind that editor.focus() does not work in this case. if ( CKEDITOR.env.iOS ) { editor.window.focus(); } }, 0 ); } else CKEDITOR.dialog._.currentZIndex -= 10; delete this._.parentDialog; // Reset the initial values of the dialog. this.foreach( function( contentObj ) { contentObj.resetInitValue && contentObj.resetInitValue(); } ); }
javascript
function() { if ( !this.parts.dialog.isVisible() ) return; this.fire( 'hide', {} ); this._.editor.fire( 'dialogHide', this ); // Reset the tab page. this.selectPage( this._.tabIdList[ 0 ] ); var element = this._.element; element.setStyle( 'display', 'none' ); this.parts.dialog.setStyle( 'visibility', 'hidden' ); // Unregister all access keys associated with this dialog. unregisterAccessKey( this ); // Close any child(top) dialogs first. while ( CKEDITOR.dialog._.currentTop != this ) CKEDITOR.dialog._.currentTop.hide(); // Maintain dialog ordering and remove cover if needed. if ( !this._.parentDialog ) hideCover( this._.editor ); else { var parentElement = this._.parentDialog.getElement().getFirst(); parentElement.setStyle( 'z-index', parseInt( parentElement.$.style.zIndex, 10 ) + Math.floor( this._.editor.config.baseFloatZIndex / 2 ) ); } CKEDITOR.dialog._.currentTop = this._.parentDialog; // Deduct or clear the z-index. if ( !this._.parentDialog ) { CKEDITOR.dialog._.currentZIndex = null; // Remove access key handlers. element.removeListener( 'keydown', accessKeyDownHandler ); element.removeListener( 'keyup', accessKeyUpHandler ); var editor = this._.editor; editor.focus(); // Give a while before unlock, waiting for focus to return to the editable. (#172) setTimeout( function() { editor.focusManager.unlock(); // Fixed iOS focus issue (#12381). // Keep in mind that editor.focus() does not work in this case. if ( CKEDITOR.env.iOS ) { editor.window.focus(); } }, 0 ); } else CKEDITOR.dialog._.currentZIndex -= 10; delete this._.parentDialog; // Reset the initial values of the dialog. this.foreach( function( contentObj ) { contentObj.resetInitValue && contentObj.resetInitValue(); } ); }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "parts", ".", "dialog", ".", "isVisible", "(", ")", ")", "return", ";", "this", ".", "fire", "(", "'hide'", ",", "{", "}", ")", ";", "this", ".", "_", ".", "editor", ".", "fire", "(", "'dialogHide'", ",", "this", ")", ";", "this", ".", "selectPage", "(", "this", ".", "_", ".", "tabIdList", "[", "0", "]", ")", ";", "var", "element", "=", "this", ".", "_", ".", "element", ";", "element", ".", "setStyle", "(", "'display'", ",", "'none'", ")", ";", "this", ".", "parts", ".", "dialog", ".", "setStyle", "(", "'visibility'", ",", "'hidden'", ")", ";", "unregisterAccessKey", "(", "this", ")", ";", "while", "(", "CKEDITOR", ".", "dialog", ".", "_", ".", "currentTop", "!=", "this", ")", "CKEDITOR", ".", "dialog", ".", "_", ".", "currentTop", ".", "hide", "(", ")", ";", "if", "(", "!", "this", ".", "_", ".", "parentDialog", ")", "hideCover", "(", "this", ".", "_", ".", "editor", ")", ";", "else", "{", "var", "parentElement", "=", "this", ".", "_", ".", "parentDialog", ".", "getElement", "(", ")", ".", "getFirst", "(", ")", ";", "parentElement", ".", "setStyle", "(", "'z-index'", ",", "parseInt", "(", "parentElement", ".", "$", ".", "style", ".", "zIndex", ",", "10", ")", "+", "Math", ".", "floor", "(", "this", ".", "_", ".", "editor", ".", "config", ".", "baseFloatZIndex", "/", "2", ")", ")", ";", "}", "CKEDITOR", ".", "dialog", ".", "_", ".", "currentTop", "=", "this", ".", "_", ".", "parentDialog", ";", "if", "(", "!", "this", ".", "_", ".", "parentDialog", ")", "{", "CKEDITOR", ".", "dialog", ".", "_", ".", "currentZIndex", "=", "null", ";", "element", ".", "removeListener", "(", "'keydown'", ",", "accessKeyDownHandler", ")", ";", "element", ".", "removeListener", "(", "'keyup'", ",", "accessKeyUpHandler", ")", ";", "var", "editor", "=", "this", ".", "_", ".", "editor", ";", "editor", ".", "focus", "(", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "editor", ".", "focusManager", ".", "unlock", "(", ")", ";", "if", "(", "CKEDITOR", ".", "env", ".", "iOS", ")", "{", "editor", ".", "window", ".", "focus", "(", ")", ";", "}", "}", ",", "0", ")", ";", "}", "else", "CKEDITOR", ".", "dialog", ".", "_", ".", "currentZIndex", "-=", "10", ";", "delete", "this", ".", "_", ".", "parentDialog", ";", "this", ".", "foreach", "(", "function", "(", "contentObj", ")", "{", "contentObj", ".", "resetInitValue", "&&", "contentObj", ".", "resetInitValue", "(", ")", ";", "}", ")", ";", "}" ]
Hides the dialog box. dialogObj.hide();
[ "Hides", "the", "dialog", "box", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L991-L1048
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( id ) { if ( this._.currentTabId == id ) return; if ( this._.tabs[ id ][ 0 ].hasClass( 'cke_dialog_tab_disabled' ) ) return; // If event was canceled - do nothing. if ( this.fire( 'selectPage', { page: id, currentPage: this._.currentTabId } ) === false ) return; // Hide the non-selected tabs and pages. for ( var i in this._.tabs ) { var tab = this._.tabs[ i ][ 0 ], page = this._.tabs[ i ][ 1 ]; if ( i != id ) { tab.removeClass( 'cke_dialog_tab_selected' ); page.hide(); } page.setAttribute( 'aria-hidden', i != id ); } var selected = this._.tabs[ id ]; selected[ 0 ].addClass( 'cke_dialog_tab_selected' ); // [IE] an invisible input[type='text'] will enlarge it's width // if it's value is long when it shows, so we clear it's value // before it shows and then recover it (#5649) if ( CKEDITOR.env.ie6Compat || CKEDITOR.env.ie7Compat ) { clearOrRecoverTextInputValue( selected[ 1 ] ); selected[ 1 ].show(); setTimeout( function() { clearOrRecoverTextInputValue( selected[ 1 ], 1 ); }, 0 ); } else selected[ 1 ].show(); this._.currentTabId = id; this._.currentTabIndex = CKEDITOR.tools.indexOf( this._.tabIdList, id ); }
javascript
function( id ) { if ( this._.currentTabId == id ) return; if ( this._.tabs[ id ][ 0 ].hasClass( 'cke_dialog_tab_disabled' ) ) return; // If event was canceled - do nothing. if ( this.fire( 'selectPage', { page: id, currentPage: this._.currentTabId } ) === false ) return; // Hide the non-selected tabs and pages. for ( var i in this._.tabs ) { var tab = this._.tabs[ i ][ 0 ], page = this._.tabs[ i ][ 1 ]; if ( i != id ) { tab.removeClass( 'cke_dialog_tab_selected' ); page.hide(); } page.setAttribute( 'aria-hidden', i != id ); } var selected = this._.tabs[ id ]; selected[ 0 ].addClass( 'cke_dialog_tab_selected' ); // [IE] an invisible input[type='text'] will enlarge it's width // if it's value is long when it shows, so we clear it's value // before it shows and then recover it (#5649) if ( CKEDITOR.env.ie6Compat || CKEDITOR.env.ie7Compat ) { clearOrRecoverTextInputValue( selected[ 1 ] ); selected[ 1 ].show(); setTimeout( function() { clearOrRecoverTextInputValue( selected[ 1 ], 1 ); }, 0 ); } else selected[ 1 ].show(); this._.currentTabId = id; this._.currentTabIndex = CKEDITOR.tools.indexOf( this._.tabIdList, id ); }
[ "function", "(", "id", ")", "{", "if", "(", "this", ".", "_", ".", "currentTabId", "==", "id", ")", "return", ";", "if", "(", "this", ".", "_", ".", "tabs", "[", "id", "]", "[", "0", "]", ".", "hasClass", "(", "'cke_dialog_tab_disabled'", ")", ")", "return", ";", "if", "(", "this", ".", "fire", "(", "'selectPage'", ",", "{", "page", ":", "id", ",", "currentPage", ":", "this", ".", "_", ".", "currentTabId", "}", ")", "===", "false", ")", "return", ";", "for", "(", "var", "i", "in", "this", ".", "_", ".", "tabs", ")", "{", "var", "tab", "=", "this", ".", "_", ".", "tabs", "[", "i", "]", "[", "0", "]", ",", "page", "=", "this", ".", "_", ".", "tabs", "[", "i", "]", "[", "1", "]", ";", "if", "(", "i", "!=", "id", ")", "{", "tab", ".", "removeClass", "(", "'cke_dialog_tab_selected'", ")", ";", "page", ".", "hide", "(", ")", ";", "}", "page", ".", "setAttribute", "(", "'aria-hidden'", ",", "i", "!=", "id", ")", ";", "}", "var", "selected", "=", "this", ".", "_", ".", "tabs", "[", "id", "]", ";", "selected", "[", "0", "]", ".", "addClass", "(", "'cke_dialog_tab_selected'", ")", ";", "if", "(", "CKEDITOR", ".", "env", ".", "ie6Compat", "||", "CKEDITOR", ".", "env", ".", "ie7Compat", ")", "{", "clearOrRecoverTextInputValue", "(", "selected", "[", "1", "]", ")", ";", "selected", "[", "1", "]", ".", "show", "(", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "clearOrRecoverTextInputValue", "(", "selected", "[", "1", "]", ",", "1", ")", ";", "}", ",", "0", ")", ";", "}", "else", "selected", "[", "1", "]", ".", "show", "(", ")", ";", "this", ".", "_", ".", "currentTabId", "=", "id", ";", "this", ".", "_", ".", "currentTabIndex", "=", "CKEDITOR", ".", "tools", ".", "indexOf", "(", "this", ".", "_", ".", "tabIdList", ",", "id", ")", ";", "}" ]
Activates a tab page in the dialog by its id. dialogObj.selectPage( 'tab_1' ); @param {String} id The id of the dialog tab to be activated.
[ "Activates", "a", "tab", "page", "in", "the", "dialog", "by", "its", "id", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L1141-L1180
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( id ) { var tab = this._.tabs[ id ] && this._.tabs[ id ][ 0 ]; if ( !tab || this._.pageCount == 1 || !tab.isVisible() ) return; // Switch to other tab first when we're hiding the active tab. else if ( id == this._.currentTabId ) this.selectPage( getPreviousVisibleTab.call( this ) ); tab.hide(); this._.pageCount--; this.updateStyle(); }
javascript
function( id ) { var tab = this._.tabs[ id ] && this._.tabs[ id ][ 0 ]; if ( !tab || this._.pageCount == 1 || !tab.isVisible() ) return; // Switch to other tab first when we're hiding the active tab. else if ( id == this._.currentTabId ) this.selectPage( getPreviousVisibleTab.call( this ) ); tab.hide(); this._.pageCount--; this.updateStyle(); }
[ "function", "(", "id", ")", "{", "var", "tab", "=", "this", ".", "_", ".", "tabs", "[", "id", "]", "&&", "this", ".", "_", ".", "tabs", "[", "id", "]", "[", "0", "]", ";", "if", "(", "!", "tab", "||", "this", ".", "_", ".", "pageCount", "==", "1", "||", "!", "tab", ".", "isVisible", "(", ")", ")", "return", ";", "else", "if", "(", "id", "==", "this", ".", "_", ".", "currentTabId", ")", "this", ".", "selectPage", "(", "getPreviousVisibleTab", ".", "call", "(", "this", ")", ")", ";", "tab", ".", "hide", "(", ")", ";", "this", ".", "_", ".", "pageCount", "--", ";", "this", ".", "updateStyle", "(", ")", ";", "}" ]
Hides a page's tab away from the dialog. dialog.hidePage( 'tab_3' ); @param {String} id The page's Id.
[ "Hides", "a", "page", "s", "tab", "away", "from", "the", "dialog", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L1197-L1208
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( id ) { var tab = this._.tabs[ id ] && this._.tabs[ id ][ 0 ]; if ( !tab ) return; tab.show(); this._.pageCount++; this.updateStyle(); }
javascript
function( id ) { var tab = this._.tabs[ id ] && this._.tabs[ id ][ 0 ]; if ( !tab ) return; tab.show(); this._.pageCount++; this.updateStyle(); }
[ "function", "(", "id", ")", "{", "var", "tab", "=", "this", ".", "_", ".", "tabs", "[", "id", "]", "&&", "this", ".", "_", ".", "tabs", "[", "id", "]", "[", "0", "]", ";", "if", "(", "!", "tab", ")", "return", ";", "tab", ".", "show", "(", ")", ";", "this", ".", "_", ".", "pageCount", "++", ";", "this", ".", "updateStyle", "(", ")", ";", "}" ]
Unhides a page's tab. dialog.showPage( 'tab_2' ); @param {String} id The page's Id.
[ "Unhides", "a", "page", "s", "tab", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L1217-L1224
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( element, index ) { if ( typeof index == 'undefined' ) { index = this._.focusList.length; this._.focusList.push( new Focusable( this, element, index ) ); } else { this._.focusList.splice( index, 0, new Focusable( this, element, index ) ); for ( var i = index + 1; i < this._.focusList.length; i++ ) this._.focusList[ i ].focusIndex++; } }
javascript
function( element, index ) { if ( typeof index == 'undefined' ) { index = this._.focusList.length; this._.focusList.push( new Focusable( this, element, index ) ); } else { this._.focusList.splice( index, 0, new Focusable( this, element, index ) ); for ( var i = index + 1; i < this._.focusList.length; i++ ) this._.focusList[ i ].focusIndex++; } }
[ "function", "(", "element", ",", "index", ")", "{", "if", "(", "typeof", "index", "==", "'undefined'", ")", "{", "index", "=", "this", ".", "_", ".", "focusList", ".", "length", ";", "this", ".", "_", ".", "focusList", ".", "push", "(", "new", "Focusable", "(", "this", ",", "element", ",", "index", ")", ")", ";", "}", "else", "{", "this", ".", "_", ".", "focusList", ".", "splice", "(", "index", ",", "0", ",", "new", "Focusable", "(", "this", ",", "element", ",", "index", ")", ")", ";", "for", "(", "var", "i", "=", "index", "+", "1", ";", "i", "<", "this", ".", "_", ".", "focusList", ".", "length", ";", "i", "++", ")", "this", ".", "_", ".", "focusList", "[", "i", "]", ".", "focusIndex", "++", ";", "}", "}" ]
Adds element to dialog's focusable list. @param {CKEDITOR.dom.element} element @param {Number} [index]
[ "Adds", "element", "to", "dialog", "s", "focusable", "list", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L1362-L1371
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( name, dialogDefinition ) { // Avoid path registration from multiple instances override definition. if ( !this._.dialogDefinitions[ name ] || typeof dialogDefinition == 'function' ) this._.dialogDefinitions[ name ] = dialogDefinition; }
javascript
function( name, dialogDefinition ) { // Avoid path registration from multiple instances override definition. if ( !this._.dialogDefinitions[ name ] || typeof dialogDefinition == 'function' ) this._.dialogDefinitions[ name ] = dialogDefinition; }
[ "function", "(", "name", ",", "dialogDefinition", ")", "{", "if", "(", "!", "this", ".", "_", ".", "dialogDefinitions", "[", "name", "]", "||", "typeof", "dialogDefinition", "==", "'function'", ")", "this", ".", "_", ".", "dialogDefinitions", "[", "name", "]", "=", "dialogDefinition", ";", "}" ]
Registers a dialog. // Full sample plugin, which does not only register a dialog window but also adds an item to the context menu. // To open the dialog window, choose "Open dialog" in the context menu. CKEDITOR.plugins.add( 'myplugin', { init: function( editor ) { editor.addCommand( 'mydialog',new CKEDITOR.dialogCommand( 'mydialog' ) ); if ( editor.contextMenu ) { editor.addMenuGroup( 'mygroup', 10 ); editor.addMenuItem( 'My Dialog', { label: 'Open dialog', command: 'mydialog', group: 'mygroup' } ); editor.contextMenu.addListener( function( element ) { return { 'My Dialog': CKEDITOR.TRISTATE_OFF }; } ); } CKEDITOR.dialog.add( 'mydialog', function( api ) { // CKEDITOR.dialog.definition var dialogDefinition = { title: 'Sample dialog', minWidth: 390, minHeight: 130, contents: [ { id: 'tab1', label: 'Label', title: 'Title', expand: true, padding: 0, elements: [ { type: 'html', html: '<p>This is some sample HTML content.</p>' }, { type: 'textarea', id: 'textareaId', rows: 4, cols: 40 } ] } ], buttons: [ CKEDITOR.dialog.okButton, CKEDITOR.dialog.cancelButton ], onOk: function() { // "this" is now a CKEDITOR.dialog object. // Accessing dialog elements: var textareaObj = this.getContentElement( 'tab1', 'textareaId' ); alert( "You have entered: " + textareaObj.getValue() ); } }; return dialogDefinition; } ); } } ); CKEDITOR.replace( 'editor1', { extraPlugins: 'myplugin' } ); @static @param {String} name The dialog's name. @param {Function/String} dialogDefinition A function returning the dialog's definition, or the URL to the `.js` file holding the function. The function should accept an argument `editor` which is the current editor instance, and return an object conforming to {@link CKEDITOR.dialog.definition}. @see CKEDITOR.dialog.definition
[ "Registers", "a", "dialog", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L1447-L1451
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( array, id, recurse ) { for ( var i = 0, item; ( item = array[ i ] ); i++ ) { if ( item.id == id ) return item; if ( recurse && item[ recurse ] ) { var retval = getById( item[ recurse ], id, recurse ); if ( retval ) return retval; } } return null; }
javascript
function( array, id, recurse ) { for ( var i = 0, item; ( item = array[ i ] ); i++ ) { if ( item.id == id ) return item; if ( recurse && item[ recurse ] ) { var retval = getById( item[ recurse ], id, recurse ); if ( retval ) return retval; } } return null; }
[ "function", "(", "array", ",", "id", ",", "recurse", ")", "{", "for", "(", "var", "i", "=", "0", ",", "item", ";", "(", "item", "=", "array", "[", "i", "]", ")", ";", "i", "++", ")", "{", "if", "(", "item", ".", "id", "==", "id", ")", "return", "item", ";", "if", "(", "recurse", "&&", "item", "[", "recurse", "]", ")", "{", "var", "retval", "=", "getById", "(", "item", "[", "recurse", "]", ",", "id", ",", "recurse", ")", ";", "if", "(", "retval", ")", "return", "retval", ";", "}", "}", "return", "null", ";", "}" ]
Tool function used to return an item from an array based on its id property.
[ "Tool", "function", "used", "to", "return", "an", "item", "from", "an", "array", "based", "on", "its", "id", "property", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L1581-L1593
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( array, newItem, nextSiblingId, recurse, nullIfNotFound ) { if ( nextSiblingId ) { for ( var i = 0, item; ( item = array[ i ] ); i++ ) { if ( item.id == nextSiblingId ) { array.splice( i, 0, newItem ); return newItem; } if ( recurse && item[ recurse ] ) { var retval = addById( item[ recurse ], newItem, nextSiblingId, recurse, true ); if ( retval ) return retval; } } if ( nullIfNotFound ) return null; } array.push( newItem ); return newItem; }
javascript
function( array, newItem, nextSiblingId, recurse, nullIfNotFound ) { if ( nextSiblingId ) { for ( var i = 0, item; ( item = array[ i ] ); i++ ) { if ( item.id == nextSiblingId ) { array.splice( i, 0, newItem ); return newItem; } if ( recurse && item[ recurse ] ) { var retval = addById( item[ recurse ], newItem, nextSiblingId, recurse, true ); if ( retval ) return retval; } } if ( nullIfNotFound ) return null; } array.push( newItem ); return newItem; }
[ "function", "(", "array", ",", "newItem", ",", "nextSiblingId", ",", "recurse", ",", "nullIfNotFound", ")", "{", "if", "(", "nextSiblingId", ")", "{", "for", "(", "var", "i", "=", "0", ",", "item", ";", "(", "item", "=", "array", "[", "i", "]", ")", ";", "i", "++", ")", "{", "if", "(", "item", ".", "id", "==", "nextSiblingId", ")", "{", "array", ".", "splice", "(", "i", ",", "0", ",", "newItem", ")", ";", "return", "newItem", ";", "}", "if", "(", "recurse", "&&", "item", "[", "recurse", "]", ")", "{", "var", "retval", "=", "addById", "(", "item", "[", "recurse", "]", ",", "newItem", ",", "nextSiblingId", ",", "recurse", ",", "true", ")", ";", "if", "(", "retval", ")", "return", "retval", ";", "}", "}", "if", "(", "nullIfNotFound", ")", "return", "null", ";", "}", "array", ".", "push", "(", "newItem", ")", ";", "return", "newItem", ";", "}" ]
Tool function used to add an item into an array.
[ "Tool", "function", "used", "to", "add", "an", "item", "into", "an", "array", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L1596-L1618
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( array, id, recurse ) { for ( var i = 0, item; ( item = array[ i ] ); i++ ) { if ( item.id == id ) return array.splice( i, 1 ); if ( recurse && item[ recurse ] ) { var retval = removeById( item[ recurse ], id, recurse ); if ( retval ) return retval; } } return null; }
javascript
function( array, id, recurse ) { for ( var i = 0, item; ( item = array[ i ] ); i++ ) { if ( item.id == id ) return array.splice( i, 1 ); if ( recurse && item[ recurse ] ) { var retval = removeById( item[ recurse ], id, recurse ); if ( retval ) return retval; } } return null; }
[ "function", "(", "array", ",", "id", ",", "recurse", ")", "{", "for", "(", "var", "i", "=", "0", ",", "item", ";", "(", "item", "=", "array", "[", "i", "]", ")", ";", "i", "++", ")", "{", "if", "(", "item", ".", "id", "==", "id", ")", "return", "array", ".", "splice", "(", "i", ",", "1", ")", ";", "if", "(", "recurse", "&&", "item", "[", "recurse", "]", ")", "{", "var", "retval", "=", "removeById", "(", "item", "[", "recurse", "]", ",", "id", ",", "recurse", ")", ";", "if", "(", "retval", ")", "return", "retval", ";", "}", "}", "return", "null", ";", "}" ]
Tool function used to remove an item from an array based on its id.
[ "Tool", "function", "used", "to", "remove", "an", "item", "from", "an", "array", "based", "on", "its", "id", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L1621-L1633
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( dialog, dialogDefinition ) { // TODO : Check if needed. this.dialog = dialog; // Transform the contents entries in contentObjects. var contents = dialogDefinition.contents; for ( var i = 0, content; ( content = contents[ i ] ); i++ ) contents[ i ] = content && new contentObject( dialog, content ); CKEDITOR.tools.extend( this, dialogDefinition ); }
javascript
function( dialog, dialogDefinition ) { // TODO : Check if needed. this.dialog = dialog; // Transform the contents entries in contentObjects. var contents = dialogDefinition.contents; for ( var i = 0, content; ( content = contents[ i ] ); i++ ) contents[ i ] = content && new contentObject( dialog, content ); CKEDITOR.tools.extend( this, dialogDefinition ); }
[ "function", "(", "dialog", ",", "dialogDefinition", ")", "{", "this", ".", "dialog", "=", "dialog", ";", "var", "contents", "=", "dialogDefinition", ".", "contents", ";", "for", "(", "var", "i", "=", "0", ",", "content", ";", "(", "content", "=", "contents", "[", "i", "]", ")", ";", "i", "++", ")", "contents", "[", "i", "]", "=", "content", "&&", "new", "contentObject", "(", "dialog", ",", "content", ")", ";", "CKEDITOR", ".", "tools", ".", "extend", "(", "this", ",", "dialogDefinition", ")", ";", "}" ]
This class is not really part of the API. It is the `definition` property value passed to `dialogDefinition` event handlers. CKEDITOR.on( 'dialogDefinition', function( evt ) { var definition = evt.data.definition; var content = definition.getContents( 'page1' ); // ... } ); @private @class CKEDITOR.dialog.definitionObject @extends CKEDITOR.dialog.definition @constructor Creates a definitionObject class instance.
[ "This", "class", "is", "not", "really", "part", "of", "the", "API", ".", "It", "is", "the", "definition", "property", "value", "passed", "to", "dialogDefinition", "event", "handlers", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L1650-L1661
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
contentObject
function contentObject( dialog, contentDefinition ) { this._ = { dialog: dialog }; CKEDITOR.tools.extend( this, contentDefinition ); }
javascript
function contentObject( dialog, contentDefinition ) { this._ = { dialog: dialog }; CKEDITOR.tools.extend( this, contentDefinition ); }
[ "function", "contentObject", "(", "dialog", ",", "contentDefinition", ")", "{", "this", ".", "_", "=", "{", "dialog", ":", "dialog", "}", ";", "CKEDITOR", ".", "tools", ".", "extend", "(", "this", ",", "contentDefinition", ")", ";", "}" ]
This class is not really part of the API. It is the template of the objects representing content pages inside the CKEDITOR.dialog.definitionObject. CKEDITOR.on( 'dialogDefinition', function( evt ) { var definition = evt.data.definition; var content = definition.getContents( 'page1' ); content.remove( 'textInput1' ); // ... } ); @private @class CKEDITOR.dialog.definition.contentObject @constructor Creates a contentObject class instance.
[ "This", "class", "is", "not", "really", "part", "of", "the", "API", ".", "It", "is", "the", "template", "of", "the", "objects", "representing", "content", "pages", "inside", "the", "CKEDITOR", ".", "dialog", ".", "definitionObject", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L1751-L1757
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( dialog, childObjList, childHtmlList, htmlList, elementDefinition ) { if ( arguments.length < 4 ) return; this._ || ( this._ = {} ); var children = this._.children = childObjList, widths = elementDefinition && elementDefinition.widths || null, height = elementDefinition && elementDefinition.height || null, styles = {}, i; /** @ignore */ var innerHTML = function() { var html = [ '<tbody><tr class="cke_dialog_ui_hbox">' ]; for ( i = 0; i < childHtmlList.length; i++ ) { var className = 'cke_dialog_ui_hbox_child', styles = []; if ( i === 0 ) className = 'cke_dialog_ui_hbox_first'; if ( i == childHtmlList.length - 1 ) className = 'cke_dialog_ui_hbox_last'; html.push( '<td class="', className, '" role="presentation" ' ); if ( widths ) { if ( widths[ i ] ) styles.push( 'width:' + cssLength( widths[ i ] ) ); } else styles.push( 'width:' + Math.floor( 100 / childHtmlList.length ) + '%' ); if ( height ) styles.push( 'height:' + cssLength( height ) ); if ( elementDefinition && elementDefinition.padding != undefined ) styles.push( 'padding:' + cssLength( elementDefinition.padding ) ); // In IE Quirks alignment has to be done on table cells. (#7324) if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && children[ i ].align ) styles.push( 'text-align:' + children[ i ].align ); if ( styles.length > 0 ) html.push( 'style="' + styles.join( '; ' ) + '" ' ); html.push( '>', childHtmlList[ i ], '</td>' ); } html.push( '</tr></tbody>' ); return html.join( '' ); }; var attribs = { role: 'presentation' }; elementDefinition && elementDefinition.align && ( attribs.align = elementDefinition.align ); CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition || { type: 'hbox' }, htmlList, 'table', styles, attribs, innerHTML ); }
javascript
function( dialog, childObjList, childHtmlList, htmlList, elementDefinition ) { if ( arguments.length < 4 ) return; this._ || ( this._ = {} ); var children = this._.children = childObjList, widths = elementDefinition && elementDefinition.widths || null, height = elementDefinition && elementDefinition.height || null, styles = {}, i; /** @ignore */ var innerHTML = function() { var html = [ '<tbody><tr class="cke_dialog_ui_hbox">' ]; for ( i = 0; i < childHtmlList.length; i++ ) { var className = 'cke_dialog_ui_hbox_child', styles = []; if ( i === 0 ) className = 'cke_dialog_ui_hbox_first'; if ( i == childHtmlList.length - 1 ) className = 'cke_dialog_ui_hbox_last'; html.push( '<td class="', className, '" role="presentation" ' ); if ( widths ) { if ( widths[ i ] ) styles.push( 'width:' + cssLength( widths[ i ] ) ); } else styles.push( 'width:' + Math.floor( 100 / childHtmlList.length ) + '%' ); if ( height ) styles.push( 'height:' + cssLength( height ) ); if ( elementDefinition && elementDefinition.padding != undefined ) styles.push( 'padding:' + cssLength( elementDefinition.padding ) ); // In IE Quirks alignment has to be done on table cells. (#7324) if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && children[ i ].align ) styles.push( 'text-align:' + children[ i ].align ); if ( styles.length > 0 ) html.push( 'style="' + styles.join( '; ' ) + '" ' ); html.push( '>', childHtmlList[ i ], '</td>' ); } html.push( '</tr></tbody>' ); return html.join( '' ); }; var attribs = { role: 'presentation' }; elementDefinition && elementDefinition.align && ( attribs.align = elementDefinition.align ); CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition || { type: 'hbox' }, htmlList, 'table', styles, attribs, innerHTML ); }
[ "function", "(", "dialog", ",", "childObjList", ",", "childHtmlList", ",", "htmlList", ",", "elementDefinition", ")", "{", "if", "(", "arguments", ".", "length", "<", "4", ")", "return", ";", "this", ".", "_", "||", "(", "this", ".", "_", "=", "{", "}", ")", ";", "var", "children", "=", "this", ".", "_", ".", "children", "=", "childObjList", ",", "widths", "=", "elementDefinition", "&&", "elementDefinition", ".", "widths", "||", "null", ",", "height", "=", "elementDefinition", "&&", "elementDefinition", ".", "height", "||", "null", ",", "styles", "=", "{", "}", ",", "i", ";", "var", "innerHTML", "=", "function", "(", ")", "{", "var", "html", "=", "[", "'<tbody><tr class=\"cke_dialog_ui_hbox\">'", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "childHtmlList", ".", "length", ";", "i", "++", ")", "{", "var", "className", "=", "'cke_dialog_ui_hbox_child'", ",", "styles", "=", "[", "]", ";", "if", "(", "i", "===", "0", ")", "className", "=", "'cke_dialog_ui_hbox_first'", ";", "if", "(", "i", "==", "childHtmlList", ".", "length", "-", "1", ")", "className", "=", "'cke_dialog_ui_hbox_last'", ";", "html", ".", "push", "(", "'<td class=\"'", ",", "className", ",", "'\" role=\"presentation\" '", ")", ";", "if", "(", "widths", ")", "{", "if", "(", "widths", "[", "i", "]", ")", "styles", ".", "push", "(", "'width:'", "+", "cssLength", "(", "widths", "[", "i", "]", ")", ")", ";", "}", "else", "styles", ".", "push", "(", "'width:'", "+", "Math", ".", "floor", "(", "100", "/", "childHtmlList", ".", "length", ")", "+", "'%'", ")", ";", "if", "(", "height", ")", "styles", ".", "push", "(", "'height:'", "+", "cssLength", "(", "height", ")", ")", ";", "if", "(", "elementDefinition", "&&", "elementDefinition", ".", "padding", "!=", "undefined", ")", "styles", ".", "push", "(", "'padding:'", "+", "cssLength", "(", "elementDefinition", ".", "padding", ")", ")", ";", "if", "(", "CKEDITOR", ".", "env", ".", "ie", "&&", "CKEDITOR", ".", "env", ".", "quirks", "&&", "children", "[", "i", "]", ".", "align", ")", "styles", ".", "push", "(", "'text-align:'", "+", "children", "[", "i", "]", ".", "align", ")", ";", "if", "(", "styles", ".", "length", ">", "0", ")", "html", ".", "push", "(", "'style=\"'", "+", "styles", ".", "join", "(", "'; '", ")", "+", "'\" '", ")", ";", "html", ".", "push", "(", "'>'", ",", "childHtmlList", "[", "i", "]", ",", "'</td>'", ")", ";", "}", "html", ".", "push", "(", "'</tr></tbody>'", ")", ";", "return", "html", ".", "join", "(", "''", ")", ";", "}", ";", "var", "attribs", "=", "{", "role", ":", "'presentation'", "}", ";", "elementDefinition", "&&", "elementDefinition", ".", "align", "&&", "(", "attribs", ".", "align", "=", "elementDefinition", ".", "align", ")", ";", "CKEDITOR", ".", "ui", ".", "dialog", ".", "uiElement", ".", "call", "(", "this", ",", "dialog", ",", "elementDefinition", "||", "{", "type", ":", "'hbox'", "}", ",", "htmlList", ",", "'table'", ",", "styles", ",", "attribs", ",", "innerHTML", ")", ";", "}" ]
Horizontal layout box for dialog UI elements, auto-expends to available width of container. @class CKEDITOR.ui.dialog.hbox @extends CKEDITOR.ui.dialog.uiElement @constructor Creates a hbox class instance. @param {CKEDITOR.dialog} dialog Parent dialog object. @param {Array} childObjList Array of {@link CKEDITOR.ui.dialog.uiElement} objects inside this container. @param {Array} childHtmlList Array of HTML code that correspond to the HTML output of all the objects in childObjList. @param {Array} htmlList Array of HTML code that this element will output to. @param {CKEDITOR.dialog.definition.uiElement} elementDefinition The element definition. Accepted fields: * `widths` (Optional) The widths of child cells. * `height` (Optional) The height of the layout. * `padding` (Optional) The padding width inside child cells. * `align` (Optional) The alignment of the whole layout.
[ "Horizontal", "layout", "box", "for", "dialog", "UI", "elements", "auto", "-", "expends", "to", "available", "width", "of", "container", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L2407-L2453
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( dialog, childObjList, childHtmlList, htmlList, elementDefinition ) { if ( arguments.length < 3 ) return; this._ || ( this._ = {} ); var children = this._.children = childObjList, width = elementDefinition && elementDefinition.width || null, heights = elementDefinition && elementDefinition.heights || null; /** @ignore */ var innerHTML = function() { var html = [ '<table role="presentation" cellspacing="0" border="0" ' ]; html.push( 'style="' ); if ( elementDefinition && elementDefinition.expand ) html.push( 'height:100%;' ); html.push( 'width:' + cssLength( width || '100%' ), ';' ); // (#10123) Temp fix for dialog broken layout in latest webkit. if ( CKEDITOR.env.webkit ) html.push( 'float:none;' ); html.push( '"' ); html.push( 'align="', CKEDITOR.tools.htmlEncode( ( elementDefinition && elementDefinition.align ) || ( dialog.getParentEditor().lang.dir == 'ltr' ? 'left' : 'right' ) ), '" ' ); html.push( '><tbody>' ); for ( var i = 0; i < childHtmlList.length; i++ ) { var styles = []; html.push( '<tr><td role="presentation" ' ); if ( width ) styles.push( 'width:' + cssLength( width || '100%' ) ); if ( heights ) styles.push( 'height:' + cssLength( heights[ i ] ) ); else if ( elementDefinition && elementDefinition.expand ) styles.push( 'height:' + Math.floor( 100 / childHtmlList.length ) + '%' ); if ( elementDefinition && elementDefinition.padding != undefined ) styles.push( 'padding:' + cssLength( elementDefinition.padding ) ); // In IE Quirks alignment has to be done on table cells. (#7324) if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && children[ i ].align ) styles.push( 'text-align:' + children[ i ].align ); if ( styles.length > 0 ) html.push( 'style="', styles.join( '; ' ), '" ' ); html.push( ' class="cke_dialog_ui_vbox_child">', childHtmlList[ i ], '</td></tr>' ); } html.push( '</tbody></table>' ); return html.join( '' ); }; CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition || { type: 'vbox' }, htmlList, 'div', null, { role: 'presentation' }, innerHTML ); }
javascript
function( dialog, childObjList, childHtmlList, htmlList, elementDefinition ) { if ( arguments.length < 3 ) return; this._ || ( this._ = {} ); var children = this._.children = childObjList, width = elementDefinition && elementDefinition.width || null, heights = elementDefinition && elementDefinition.heights || null; /** @ignore */ var innerHTML = function() { var html = [ '<table role="presentation" cellspacing="0" border="0" ' ]; html.push( 'style="' ); if ( elementDefinition && elementDefinition.expand ) html.push( 'height:100%;' ); html.push( 'width:' + cssLength( width || '100%' ), ';' ); // (#10123) Temp fix for dialog broken layout in latest webkit. if ( CKEDITOR.env.webkit ) html.push( 'float:none;' ); html.push( '"' ); html.push( 'align="', CKEDITOR.tools.htmlEncode( ( elementDefinition && elementDefinition.align ) || ( dialog.getParentEditor().lang.dir == 'ltr' ? 'left' : 'right' ) ), '" ' ); html.push( '><tbody>' ); for ( var i = 0; i < childHtmlList.length; i++ ) { var styles = []; html.push( '<tr><td role="presentation" ' ); if ( width ) styles.push( 'width:' + cssLength( width || '100%' ) ); if ( heights ) styles.push( 'height:' + cssLength( heights[ i ] ) ); else if ( elementDefinition && elementDefinition.expand ) styles.push( 'height:' + Math.floor( 100 / childHtmlList.length ) + '%' ); if ( elementDefinition && elementDefinition.padding != undefined ) styles.push( 'padding:' + cssLength( elementDefinition.padding ) ); // In IE Quirks alignment has to be done on table cells. (#7324) if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && children[ i ].align ) styles.push( 'text-align:' + children[ i ].align ); if ( styles.length > 0 ) html.push( 'style="', styles.join( '; ' ), '" ' ); html.push( ' class="cke_dialog_ui_vbox_child">', childHtmlList[ i ], '</td></tr>' ); } html.push( '</tbody></table>' ); return html.join( '' ); }; CKEDITOR.ui.dialog.uiElement.call( this, dialog, elementDefinition || { type: 'vbox' }, htmlList, 'div', null, { role: 'presentation' }, innerHTML ); }
[ "function", "(", "dialog", ",", "childObjList", ",", "childHtmlList", ",", "htmlList", ",", "elementDefinition", ")", "{", "if", "(", "arguments", ".", "length", "<", "3", ")", "return", ";", "this", ".", "_", "||", "(", "this", ".", "_", "=", "{", "}", ")", ";", "var", "children", "=", "this", ".", "_", ".", "children", "=", "childObjList", ",", "width", "=", "elementDefinition", "&&", "elementDefinition", ".", "width", "||", "null", ",", "heights", "=", "elementDefinition", "&&", "elementDefinition", ".", "heights", "||", "null", ";", "var", "innerHTML", "=", "function", "(", ")", "{", "var", "html", "=", "[", "'<table role=\"presentation\" cellspacing=\"0\" border=\"0\" '", "]", ";", "html", ".", "push", "(", "'style=\"'", ")", ";", "if", "(", "elementDefinition", "&&", "elementDefinition", ".", "expand", ")", "html", ".", "push", "(", "'height:100%;'", ")", ";", "html", ".", "push", "(", "'width:'", "+", "cssLength", "(", "width", "||", "'100%'", ")", ",", "';'", ")", ";", "if", "(", "CKEDITOR", ".", "env", ".", "webkit", ")", "html", ".", "push", "(", "'float:none;'", ")", ";", "html", ".", "push", "(", "'\"'", ")", ";", "html", ".", "push", "(", "'align=\"'", ",", "CKEDITOR", ".", "tools", ".", "htmlEncode", "(", "(", "elementDefinition", "&&", "elementDefinition", ".", "align", ")", "||", "(", "dialog", ".", "getParentEditor", "(", ")", ".", "lang", ".", "dir", "==", "'ltr'", "?", "'left'", ":", "'right'", ")", ")", ",", "'\" '", ")", ";", "html", ".", "push", "(", "'><tbody>'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "childHtmlList", ".", "length", ";", "i", "++", ")", "{", "var", "styles", "=", "[", "]", ";", "html", ".", "push", "(", "'<tr><td role=\"presentation\" '", ")", ";", "if", "(", "width", ")", "styles", ".", "push", "(", "'width:'", "+", "cssLength", "(", "width", "||", "'100%'", ")", ")", ";", "if", "(", "heights", ")", "styles", ".", "push", "(", "'height:'", "+", "cssLength", "(", "heights", "[", "i", "]", ")", ")", ";", "else", "if", "(", "elementDefinition", "&&", "elementDefinition", ".", "expand", ")", "styles", ".", "push", "(", "'height:'", "+", "Math", ".", "floor", "(", "100", "/", "childHtmlList", ".", "length", ")", "+", "'%'", ")", ";", "if", "(", "elementDefinition", "&&", "elementDefinition", ".", "padding", "!=", "undefined", ")", "styles", ".", "push", "(", "'padding:'", "+", "cssLength", "(", "elementDefinition", ".", "padding", ")", ")", ";", "if", "(", "CKEDITOR", ".", "env", ".", "ie", "&&", "CKEDITOR", ".", "env", ".", "quirks", "&&", "children", "[", "i", "]", ".", "align", ")", "styles", ".", "push", "(", "'text-align:'", "+", "children", "[", "i", "]", ".", "align", ")", ";", "if", "(", "styles", ".", "length", ">", "0", ")", "html", ".", "push", "(", "'style=\"'", ",", "styles", ".", "join", "(", "'; '", ")", ",", "'\" '", ")", ";", "html", ".", "push", "(", "' class=\"cke_dialog_ui_vbox_child\">'", ",", "childHtmlList", "[", "i", "]", ",", "'</td></tr>'", ")", ";", "}", "html", ".", "push", "(", "'</tbody></table>'", ")", ";", "return", "html", ".", "join", "(", "''", ")", ";", "}", ";", "CKEDITOR", ".", "ui", ".", "dialog", ".", "uiElement", ".", "call", "(", "this", ",", "dialog", ",", "elementDefinition", "||", "{", "type", ":", "'vbox'", "}", ",", "htmlList", ",", "'div'", ",", "null", ",", "{", "role", ":", "'presentation'", "}", ",", "innerHTML", ")", ";", "}" ]
Vertical layout box for dialog UI elements. @class CKEDITOR.ui.dialog.vbox @extends CKEDITOR.ui.dialog.hbox @constructor Creates a vbox class instance. @param {CKEDITOR.dialog} dialog Parent dialog object. @param {Array} childObjList Array of {@link CKEDITOR.ui.dialog.uiElement} objects inside this container. @param {Array} childHtmlList Array of HTML code that correspond to the HTML output of all the objects in childObjList. @param {Array} htmlList Array of HTML code that this element will output to. @param {CKEDITOR.dialog.definition.uiElement} elementDefinition The element definition. Accepted fields: * `width` (Optional) The width of the layout. * `heights` (Optional) The heights of individual cells. * `align` (Optional) The alignment of the layout. * `padding` (Optional) The padding width inside child cells. * `expand` (Optional) Whether the layout should expand vertically to fill its container.
[ "Vertical", "layout", "box", "for", "dialog", "UI", "elements", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L2478-L2526
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( indices ) { // If no arguments, return a clone of the children array. if ( arguments.length < 1 ) return this._.children.concat(); // If indices isn't array, make it one. if ( !indices.splice ) indices = [ indices ]; // Retrieve the child element according to tree position. if ( indices.length < 2 ) return this._.children[ indices[ 0 ] ]; else return ( this._.children[ indices[ 0 ] ] && this._.children[ indices[ 0 ] ].getChild ) ? this._.children[ indices[ 0 ] ].getChild( indices.slice( 1, indices.length ) ) : null; }
javascript
function( indices ) { // If no arguments, return a clone of the children array. if ( arguments.length < 1 ) return this._.children.concat(); // If indices isn't array, make it one. if ( !indices.splice ) indices = [ indices ]; // Retrieve the child element according to tree position. if ( indices.length < 2 ) return this._.children[ indices[ 0 ] ]; else return ( this._.children[ indices[ 0 ] ] && this._.children[ indices[ 0 ] ].getChild ) ? this._.children[ indices[ 0 ] ].getChild( indices.slice( 1, indices.length ) ) : null; }
[ "function", "(", "indices", ")", "{", "if", "(", "arguments", ".", "length", "<", "1", ")", "return", "this", ".", "_", ".", "children", ".", "concat", "(", ")", ";", "if", "(", "!", "indices", ".", "splice", ")", "indices", "=", "[", "indices", "]", ";", "if", "(", "indices", ".", "length", "<", "2", ")", "return", "this", ".", "_", ".", "children", "[", "indices", "[", "0", "]", "]", ";", "else", "return", "(", "this", ".", "_", ".", "children", "[", "indices", "[", "0", "]", "]", "&&", "this", ".", "_", ".", "children", "[", "indices", "[", "0", "]", "]", ".", "getChild", ")", "?", "this", ".", "_", ".", "children", "[", "indices", "[", "0", "]", "]", ".", "getChild", "(", "indices", ".", "slice", "(", "1", ",", "indices", ".", "length", ")", ")", ":", "null", ";", "}" ]
Gets a child UI element inside this container. var checkbox = hbox.getChild( [0,1] ); checkbox.setValue( true ); @param {Array/Number} indices An array or a single number to indicate the child's position in the container's descendant tree. Omit to get all the children in an array. @returns {Array/CKEDITOR.ui.dialog.uiElement} Array of all UI elements in the container if no argument given, or the specified UI element if indices is given.
[ "Gets", "a", "child", "UI", "element", "inside", "this", "container", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L2817-L2831
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/dialog/plugin.js
function( dialogName, callback ) { var dialog = null, dialogDefinitions = CKEDITOR.dialog._.dialogDefinitions[ dialogName ]; if ( CKEDITOR.dialog._.currentTop === null ) showCover( this ); // If the dialogDefinition is already loaded, open it immediately. if ( typeof dialogDefinitions == 'function' ) { var storedDialogs = this._.storedDialogs || ( this._.storedDialogs = {} ); dialog = storedDialogs[ dialogName ] || ( storedDialogs[ dialogName ] = new CKEDITOR.dialog( this, dialogName ) ); callback && callback.call( dialog, dialog ); dialog.show(); } else if ( dialogDefinitions == 'failed' ) { hideCover( this ); throw new Error( '[CKEDITOR.dialog.openDialog] Dialog "' + dialogName + '" failed when loading definition.' ); } else if ( typeof dialogDefinitions == 'string' ) { CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( dialogDefinitions ), function() { var dialogDefinition = CKEDITOR.dialog._.dialogDefinitions[ dialogName ]; // In case of plugin error, mark it as loading failed. if ( typeof dialogDefinition != 'function' ) CKEDITOR.dialog._.dialogDefinitions[ dialogName ] = 'failed'; this.openDialog( dialogName, callback ); }, this, 0, 1 ); } CKEDITOR.skin.loadPart( 'dialog' ); return dialog; }
javascript
function( dialogName, callback ) { var dialog = null, dialogDefinitions = CKEDITOR.dialog._.dialogDefinitions[ dialogName ]; if ( CKEDITOR.dialog._.currentTop === null ) showCover( this ); // If the dialogDefinition is already loaded, open it immediately. if ( typeof dialogDefinitions == 'function' ) { var storedDialogs = this._.storedDialogs || ( this._.storedDialogs = {} ); dialog = storedDialogs[ dialogName ] || ( storedDialogs[ dialogName ] = new CKEDITOR.dialog( this, dialogName ) ); callback && callback.call( dialog, dialog ); dialog.show(); } else if ( dialogDefinitions == 'failed' ) { hideCover( this ); throw new Error( '[CKEDITOR.dialog.openDialog] Dialog "' + dialogName + '" failed when loading definition.' ); } else if ( typeof dialogDefinitions == 'string' ) { CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( dialogDefinitions ), function() { var dialogDefinition = CKEDITOR.dialog._.dialogDefinitions[ dialogName ]; // In case of plugin error, mark it as loading failed. if ( typeof dialogDefinition != 'function' ) CKEDITOR.dialog._.dialogDefinitions[ dialogName ] = 'failed'; this.openDialog( dialogName, callback ); }, this, 0, 1 ); } CKEDITOR.skin.loadPart( 'dialog' ); return dialog; }
[ "function", "(", "dialogName", ",", "callback", ")", "{", "var", "dialog", "=", "null", ",", "dialogDefinitions", "=", "CKEDITOR", ".", "dialog", ".", "_", ".", "dialogDefinitions", "[", "dialogName", "]", ";", "if", "(", "CKEDITOR", ".", "dialog", ".", "_", ".", "currentTop", "===", "null", ")", "showCover", "(", "this", ")", ";", "if", "(", "typeof", "dialogDefinitions", "==", "'function'", ")", "{", "var", "storedDialogs", "=", "this", ".", "_", ".", "storedDialogs", "||", "(", "this", ".", "_", ".", "storedDialogs", "=", "{", "}", ")", ";", "dialog", "=", "storedDialogs", "[", "dialogName", "]", "||", "(", "storedDialogs", "[", "dialogName", "]", "=", "new", "CKEDITOR", ".", "dialog", "(", "this", ",", "dialogName", ")", ")", ";", "callback", "&&", "callback", ".", "call", "(", "dialog", ",", "dialog", ")", ";", "dialog", ".", "show", "(", ")", ";", "}", "else", "if", "(", "dialogDefinitions", "==", "'failed'", ")", "{", "hideCover", "(", "this", ")", ";", "throw", "new", "Error", "(", "'[CKEDITOR.dialog.openDialog] Dialog \"'", "+", "dialogName", "+", "'\" failed when loading definition.'", ")", ";", "}", "else", "if", "(", "typeof", "dialogDefinitions", "==", "'string'", ")", "{", "CKEDITOR", ".", "scriptLoader", ".", "load", "(", "CKEDITOR", ".", "getUrl", "(", "dialogDefinitions", ")", ",", "function", "(", ")", "{", "var", "dialogDefinition", "=", "CKEDITOR", ".", "dialog", ".", "_", ".", "dialogDefinitions", "[", "dialogName", "]", ";", "if", "(", "typeof", "dialogDefinition", "!=", "'function'", ")", "CKEDITOR", ".", "dialog", ".", "_", ".", "dialogDefinitions", "[", "dialogName", "]", "=", "'failed'", ";", "this", ".", "openDialog", "(", "dialogName", ",", "callback", ")", ";", "}", ",", "this", ",", "0", ",", "1", ")", ";", "}", "CKEDITOR", ".", "skin", ".", "loadPart", "(", "'dialog'", ")", ";", "return", "dialog", ";", "}" ]
Loads and opens a registered dialog. CKEDITOR.instances.editor1.openDialog( 'smiley' ); @member CKEDITOR.editor @param {String} dialogName The registered name of the dialog. @param {Function} callback The function to be invoked after dialog instance created. @returns {CKEDITOR.dialog} The dialog object corresponding to the dialog displayed. `null` if the dialog name is not registered. @see CKEDITOR.dialog#add
[ "Loads", "and", "opens", "a", "registered", "dialog", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/dialog/plugin.js#L3027-L3061
train
open-nata/nata-device
src/utils.js
getWidgetsFromXml
async function getWidgetsFromXml(target) { const $ = await parseFile(target) const widgets = [] let widget $('node').each((i, elem) => { const node = $(elem) widget = new Widget() widget.text = node.attr('text') widget.resourceId = node.attr('resource-id') widget.className = node.attr('class') widget.packageName = node.attr('package') widget.contentDesc = node.attr('content-desc') widget.checkable = node.attr('checkable') widget.checked = node.attr('checked') widget.clickable = node.attr('clickable') widget.enabled = node.attr('enabled') widget.focusable = node.attr('focusable') widget.focused = node.attr('focused') widget.scrollable = node.attr('scrollable') widget.longClickable = node.attr('long-clickable') widget.password = node.attr('password') widget.selected = node.attr('selected') widget.bounds = node.attr('bounds') widgets.push(widget) }) return widgets }
javascript
async function getWidgetsFromXml(target) { const $ = await parseFile(target) const widgets = [] let widget $('node').each((i, elem) => { const node = $(elem) widget = new Widget() widget.text = node.attr('text') widget.resourceId = node.attr('resource-id') widget.className = node.attr('class') widget.packageName = node.attr('package') widget.contentDesc = node.attr('content-desc') widget.checkable = node.attr('checkable') widget.checked = node.attr('checked') widget.clickable = node.attr('clickable') widget.enabled = node.attr('enabled') widget.focusable = node.attr('focusable') widget.focused = node.attr('focused') widget.scrollable = node.attr('scrollable') widget.longClickable = node.attr('long-clickable') widget.password = node.attr('password') widget.selected = node.attr('selected') widget.bounds = node.attr('bounds') widgets.push(widget) }) return widgets }
[ "async", "function", "getWidgetsFromXml", "(", "target", ")", "{", "const", "$", "=", "await", "parseFile", "(", "target", ")", "const", "widgets", "=", "[", "]", "let", "widget", "$", "(", "'node'", ")", ".", "each", "(", "(", "i", ",", "elem", ")", "=>", "{", "const", "node", "=", "$", "(", "elem", ")", "widget", "=", "new", "Widget", "(", ")", "widget", ".", "text", "=", "node", ".", "attr", "(", "'text'", ")", "widget", ".", "resourceId", "=", "node", ".", "attr", "(", "'resource-id'", ")", "widget", ".", "className", "=", "node", ".", "attr", "(", "'class'", ")", "widget", ".", "packageName", "=", "node", ".", "attr", "(", "'package'", ")", "widget", ".", "contentDesc", "=", "node", ".", "attr", "(", "'content-desc'", ")", "widget", ".", "checkable", "=", "node", ".", "attr", "(", "'checkable'", ")", "widget", ".", "checked", "=", "node", ".", "attr", "(", "'checked'", ")", "widget", ".", "clickable", "=", "node", ".", "attr", "(", "'clickable'", ")", "widget", ".", "enabled", "=", "node", ".", "attr", "(", "'enabled'", ")", "widget", ".", "focusable", "=", "node", ".", "attr", "(", "'focusable'", ")", "widget", ".", "focused", "=", "node", ".", "attr", "(", "'focused'", ")", "widget", ".", "scrollable", "=", "node", ".", "attr", "(", "'scrollable'", ")", "widget", ".", "longClickable", "=", "node", ".", "attr", "(", "'long-clickable'", ")", "widget", ".", "password", "=", "node", ".", "attr", "(", "'password'", ")", "widget", ".", "selected", "=", "node", ".", "attr", "(", "'selected'", ")", "widget", ".", "bounds", "=", "node", ".", "attr", "(", "'bounds'", ")", "widgets", ".", "push", "(", "widget", ")", "}", ")", "return", "widgets", "}" ]
get widgets from dumpfile.xml @param {String} target the local path of dumpfile.xml @return {[Widget]} Array of avaliable widgets
[ "get", "widgets", "from", "dumpfile", ".", "xml" ]
c2c1292fb0f634eab72e6770ee5b835b67186405
https://github.com/open-nata/nata-device/blob/c2c1292fb0f634eab72e6770ee5b835b67186405/src/utils.js#L26-L54
train
jeremenichelli/threshold
src/threshold.js
threshold
function threshold(element) { var rects = element.getBoundingClientRect(); var upperThreshold = (threshold._viewport.height - rects.top) / rects.height; var bottomThreshold = rects.bottom / rects.height; var leftThreshold = (threshold._viewport.width - rects.left) / rects.width; var rightThreshold = rects.right / rects.width; var horizontalTrajectory = rects.width + threshold._viewport.width; var verticalTrajectory = rects.height + threshold._viewport.height; /** * area * * This value represents the area of the component present in the viewport * * It is calculated by using the min value between the distance from the * top, right, bottom and left edges of the element and its height and weight * */ var minXArea = Math.min(leftThreshold, rightThreshold); var xArea = Math.min(1, Math.max(minXArea, 0)); var minYArea = Math.min(upperThreshold, bottomThreshold); var yArea = Math.min(1, Math.max(minYArea, 0)); /** * trajectory * * This value represents the translation of the element from the moment * it enters the viewport until it gets out * * It is calculated by measuring the distance between the top and left edge * of the viewport and the bottom and right edge of the element * */ var xTrajectory = (horizontalTrajectory - rects.right) / horizontalTrajectory; var yTrajectory = (verticalTrajectory - rects.bottom) / verticalTrajectory; return { area: xArea * yArea, trajectory: { x: xTrajectory, y: yTrajectory } }; }
javascript
function threshold(element) { var rects = element.getBoundingClientRect(); var upperThreshold = (threshold._viewport.height - rects.top) / rects.height; var bottomThreshold = rects.bottom / rects.height; var leftThreshold = (threshold._viewport.width - rects.left) / rects.width; var rightThreshold = rects.right / rects.width; var horizontalTrajectory = rects.width + threshold._viewport.width; var verticalTrajectory = rects.height + threshold._viewport.height; /** * area * * This value represents the area of the component present in the viewport * * It is calculated by using the min value between the distance from the * top, right, bottom and left edges of the element and its height and weight * */ var minXArea = Math.min(leftThreshold, rightThreshold); var xArea = Math.min(1, Math.max(minXArea, 0)); var minYArea = Math.min(upperThreshold, bottomThreshold); var yArea = Math.min(1, Math.max(minYArea, 0)); /** * trajectory * * This value represents the translation of the element from the moment * it enters the viewport until it gets out * * It is calculated by measuring the distance between the top and left edge * of the viewport and the bottom and right edge of the element * */ var xTrajectory = (horizontalTrajectory - rects.right) / horizontalTrajectory; var yTrajectory = (verticalTrajectory - rects.bottom) / verticalTrajectory; return { area: xArea * yArea, trajectory: { x: xTrajectory, y: yTrajectory } }; }
[ "function", "threshold", "(", "element", ")", "{", "var", "rects", "=", "element", ".", "getBoundingClientRect", "(", ")", ";", "var", "upperThreshold", "=", "(", "threshold", ".", "_viewport", ".", "height", "-", "rects", ".", "top", ")", "/", "rects", ".", "height", ";", "var", "bottomThreshold", "=", "rects", ".", "bottom", "/", "rects", ".", "height", ";", "var", "leftThreshold", "=", "(", "threshold", ".", "_viewport", ".", "width", "-", "rects", ".", "left", ")", "/", "rects", ".", "width", ";", "var", "rightThreshold", "=", "rects", ".", "right", "/", "rects", ".", "width", ";", "var", "horizontalTrajectory", "=", "rects", ".", "width", "+", "threshold", ".", "_viewport", ".", "width", ";", "var", "verticalTrajectory", "=", "rects", ".", "height", "+", "threshold", ".", "_viewport", ".", "height", ";", "var", "minXArea", "=", "Math", ".", "min", "(", "leftThreshold", ",", "rightThreshold", ")", ";", "var", "xArea", "=", "Math", ".", "min", "(", "1", ",", "Math", ".", "max", "(", "minXArea", ",", "0", ")", ")", ";", "var", "minYArea", "=", "Math", ".", "min", "(", "upperThreshold", ",", "bottomThreshold", ")", ";", "var", "yArea", "=", "Math", ".", "min", "(", "1", ",", "Math", ".", "max", "(", "minYArea", ",", "0", ")", ")", ";", "var", "xTrajectory", "=", "(", "horizontalTrajectory", "-", "rects", ".", "right", ")", "/", "horizontalTrajectory", ";", "var", "yTrajectory", "=", "(", "verticalTrajectory", "-", "rects", ".", "bottom", ")", "/", "verticalTrajectory", ";", "return", "{", "area", ":", "xArea", "*", "yArea", ",", "trajectory", ":", "{", "x", ":", "xTrajectory", ",", "y", ":", "yTrajectory", "}", "}", ";", "}" ]
Returns metrics regarding an element's position in the viewport @method threshold @param {Node} element @returns {Object}
[ "Returns", "metrics", "regarding", "an", "element", "s", "position", "in", "the", "viewport" ]
17793f53eacaf34a398075266eeb5e1a2c020881
https://github.com/jeremenichelli/threshold/blob/17793f53eacaf34a398075266eeb5e1a2c020881/src/threshold.js#L7-L55
train
jeremenichelli/threshold
src/threshold.js
updateViewport
function updateViewport() { threshold._viewport.height = window.innerHeight; threshold._viewport.width = window.innerWidth; }
javascript
function updateViewport() { threshold._viewport.height = window.innerHeight; threshold._viewport.width = window.innerWidth; }
[ "function", "updateViewport", "(", ")", "{", "threshold", ".", "_viewport", ".", "height", "=", "window", ".", "innerHeight", ";", "threshold", ".", "_viewport", ".", "width", "=", "window", ".", "innerWidth", ";", "}" ]
Updates memoized viewport metrics @method updateViewport
[ "Updates", "memoized", "viewport", "metrics" ]
17793f53eacaf34a398075266eeb5e1a2c020881
https://github.com/jeremenichelli/threshold/blob/17793f53eacaf34a398075266eeb5e1a2c020881/src/threshold.js#L67-L70
train
bbusschots-mu/mu-qunit-util
dist/index.es.js
all
function all(func) { return function() { var params = getParams(arguments); var length = params.length; for (var i = 0; i < length; i++) { if (!func.call(null, params[i])) { return false; } } return true; }; }
javascript
function all(func) { return function() { var params = getParams(arguments); var length = params.length; for (var i = 0; i < length; i++) { if (!func.call(null, params[i])) { return false; } } return true; }; }
[ "function", "all", "(", "func", ")", "{", "return", "function", "(", ")", "{", "var", "params", "=", "getParams", "(", "arguments", ")", ";", "var", "length", "=", "params", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "!", "func", ".", "call", "(", "null", ",", "params", "[", "i", "]", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", ";", "}" ]
helper function which call predicate function per parameter and return true if all pass
[ "helper", "function", "which", "call", "predicate", "function", "per", "parameter", "and", "return", "true", "if", "all", "pass" ]
1ed4414e8b307cf6452918496ff48cf373ccb654
https://github.com/bbusschots-mu/mu-qunit-util/blob/1ed4414e8b307cf6452918496ff48cf373ccb654/dist/index.es.js#L42-L53
train
bbusschots-mu/mu-qunit-util
dist/index.es.js
compareVersion
function compareVersion(version, range) { var string = (range + ''); var n = +(string.match(/\d+/) || NaN); var op = string.match(/^[<>]=?|/)[0]; return comparator[op] ? comparator[op](version, n) : (version == n || n !== n); }
javascript
function compareVersion(version, range) { var string = (range + ''); var n = +(string.match(/\d+/) || NaN); var op = string.match(/^[<>]=?|/)[0]; return comparator[op] ? comparator[op](version, n) : (version == n || n !== n); }
[ "function", "compareVersion", "(", "version", ",", "range", ")", "{", "var", "string", "=", "(", "range", "+", "''", ")", ";", "var", "n", "=", "+", "(", "string", ".", "match", "(", "/", "\\d+", "/", ")", "||", "NaN", ")", ";", "var", "op", "=", "string", ".", "match", "(", "/", "^[<>]=?|", "/", ")", "[", "0", "]", ";", "return", "comparator", "[", "op", "]", "?", "comparator", "[", "op", "]", "(", "version", ",", "n", ")", ":", "(", "version", "==", "n", "||", "n", "!==", "n", ")", ";", "}" ]
helper function which compares a version to a range
[ "helper", "function", "which", "compares", "a", "version", "to", "a", "range" ]
1ed4414e8b307cf6452918496ff48cf373ccb654
https://github.com/bbusschots-mu/mu-qunit-util/blob/1ed4414e8b307cf6452918496ff48cf373ccb654/dist/index.es.js#L78-L83
train
bbusschots-mu/mu-qunit-util
dist/index.es.js
getParams
function getParams(args) { var params = slice.call(args); var length = params.length; if (length === 1 && is.array(params[0])) { // support array params = params[0]; } return params; }
javascript
function getParams(args) { var params = slice.call(args); var length = params.length; if (length === 1 && is.array(params[0])) { // support array params = params[0]; } return params; }
[ "function", "getParams", "(", "args", ")", "{", "var", "params", "=", "slice", ".", "call", "(", "args", ")", ";", "var", "length", "=", "params", ".", "length", ";", "if", "(", "length", "===", "1", "&&", "is", ".", "array", "(", "params", "[", "0", "]", ")", ")", "{", "params", "=", "params", "[", "0", "]", ";", "}", "return", "params", ";", "}" ]
helper function which extracts params from arguments
[ "helper", "function", "which", "extracts", "params", "from", "arguments" ]
1ed4414e8b307cf6452918496ff48cf373ccb654
https://github.com/bbusschots-mu/mu-qunit-util/blob/1ed4414e8b307cf6452918496ff48cf373ccb654/dist/index.es.js#L86-L93
train
dominictarr/header-stream
index.js
merge
function merge (a, b) { for (var k in b) a[k] = a[k] || b[k] }
javascript
function merge (a, b) { for (var k in b) a[k] = a[k] || b[k] }
[ "function", "merge", "(", "a", ",", "b", ")", "{", "for", "(", "var", "k", "in", "b", ")", "a", "[", "k", "]", "=", "a", "[", "k", "]", "||", "b", "[", "k", "]", "}" ]
the first line is header, in JSON format, with no whitespace.
[ "the", "first", "line", "is", "header", "in", "JSON", "format", "with", "no", "whitespace", "." ]
1d784d589edd11c94601ca8db93d8befd4878326
https://github.com/dominictarr/header-stream/blob/1d784d589edd11c94601ca8db93d8befd4878326/index.js#L4-L7
train
IonicaBizau/cross-style.js
lib/index.js
CrossStyle
function CrossStyle(input) { var uInput = UFirst(input); return [ "webkit" + uInput , "moz" + uInput , "ms" + uInput , "o" + uInput , input ] }
javascript
function CrossStyle(input) { var uInput = UFirst(input); return [ "webkit" + uInput , "moz" + uInput , "ms" + uInput , "o" + uInput , input ] }
[ "function", "CrossStyle", "(", "input", ")", "{", "var", "uInput", "=", "UFirst", "(", "input", ")", ";", "return", "[", "\"webkit\"", "+", "uInput", ",", "\"moz\"", "+", "uInput", ",", "\"ms\"", "+", "uInput", ",", "\"o\"", "+", "uInput", ",", "input", "]", "}" ]
CrossStyle Returns an array of cross-browser CSS properties for given input. @name CrossStyle @function @param {String} input The CSS property (e.g. `"transform"` or `"transformOrigin"`). @return {Array} An array of strings representing the cross-browser CSS properties for the given input.
[ "CrossStyle", "Returns", "an", "array", "of", "cross", "-", "browser", "CSS", "properties", "for", "given", "input", "." ]
f3bc8b153710168a6fd5346c35d0851bd1b02f25
https://github.com/IonicaBizau/cross-style.js/blob/f3bc8b153710168a6fd5346c35d0851bd1b02f25/lib/index.js#L13-L22
train
brettz9/imf
dist/index-cjs.js
IMFClass
function IMFClass(opts) { if (!(this instanceof IMFClass)) { return new IMFClass(opts); } opts = opts || {}; this.defaultNamespace = opts.defaultNamespace || ''; this.defaultSeparator = opts.defaultSeparator === undefined ? '.' : opts.defaultSeparator; this.basePath = opts.basePath || 'locales/'; this.fallbackLanguages = opts.fallbackLanguages; this.localeFileResolver = opts.localeFileResolver || function (lang) { return this.basePath + lang + '.json'; }; this.locales = opts.locales || []; this.langs = opts.langs; this.fallbackLocales = opts.fallbackLocales || []; const loadFallbacks = cb => { this.loadLocales(this.fallbackLanguages, function (...fallbackLocales) { this.fallbackLocales.push(...fallbackLocales); if (cb) { return cb(fallbackLocales); } }, true); }; if (opts.languages || opts.callback) { this.loadLocales(opts.languages, () => { const locales = Array.from(arguments); const runCallback = fallbackLocales => { if (opts.callback) { opts.callback.apply(this, [this.getFormatter(opts.namespace), this.getFormatter.bind(this), locales, fallbackLocales]); } }; if (opts.hasOwnProperty('fallbackLanguages')) { loadFallbacks(runCallback); } else { runCallback(); } }); } else if (opts.hasOwnProperty('fallbackLanguages')) { loadFallbacks(); } }
javascript
function IMFClass(opts) { if (!(this instanceof IMFClass)) { return new IMFClass(opts); } opts = opts || {}; this.defaultNamespace = opts.defaultNamespace || ''; this.defaultSeparator = opts.defaultSeparator === undefined ? '.' : opts.defaultSeparator; this.basePath = opts.basePath || 'locales/'; this.fallbackLanguages = opts.fallbackLanguages; this.localeFileResolver = opts.localeFileResolver || function (lang) { return this.basePath + lang + '.json'; }; this.locales = opts.locales || []; this.langs = opts.langs; this.fallbackLocales = opts.fallbackLocales || []; const loadFallbacks = cb => { this.loadLocales(this.fallbackLanguages, function (...fallbackLocales) { this.fallbackLocales.push(...fallbackLocales); if (cb) { return cb(fallbackLocales); } }, true); }; if (opts.languages || opts.callback) { this.loadLocales(opts.languages, () => { const locales = Array.from(arguments); const runCallback = fallbackLocales => { if (opts.callback) { opts.callback.apply(this, [this.getFormatter(opts.namespace), this.getFormatter.bind(this), locales, fallbackLocales]); } }; if (opts.hasOwnProperty('fallbackLanguages')) { loadFallbacks(runCallback); } else { runCallback(); } }); } else if (opts.hasOwnProperty('fallbackLanguages')) { loadFallbacks(); } }
[ "function", "IMFClass", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "IMFClass", ")", ")", "{", "return", "new", "IMFClass", "(", "opts", ")", ";", "}", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "defaultNamespace", "=", "opts", ".", "defaultNamespace", "||", "''", ";", "this", ".", "defaultSeparator", "=", "opts", ".", "defaultSeparator", "===", "undefined", "?", "'.'", ":", "opts", ".", "defaultSeparator", ";", "this", ".", "basePath", "=", "opts", ".", "basePath", "||", "'locales/'", ";", "this", ".", "fallbackLanguages", "=", "opts", ".", "fallbackLanguages", ";", "this", ".", "localeFileResolver", "=", "opts", ".", "localeFileResolver", "||", "function", "(", "lang", ")", "{", "return", "this", ".", "basePath", "+", "lang", "+", "'.json'", ";", "}", ";", "this", ".", "locales", "=", "opts", ".", "locales", "||", "[", "]", ";", "this", ".", "langs", "=", "opts", ".", "langs", ";", "this", ".", "fallbackLocales", "=", "opts", ".", "fallbackLocales", "||", "[", "]", ";", "const", "loadFallbacks", "=", "cb", "=>", "{", "this", ".", "loadLocales", "(", "this", ".", "fallbackLanguages", ",", "function", "(", "...", "fallbackLocales", ")", "{", "this", ".", "fallbackLocales", ".", "push", "(", "...", "fallbackLocales", ")", ";", "if", "(", "cb", ")", "{", "return", "cb", "(", "fallbackLocales", ")", ";", "}", "}", ",", "true", ")", ";", "}", ";", "if", "(", "opts", ".", "languages", "||", "opts", ".", "callback", ")", "{", "this", ".", "loadLocales", "(", "opts", ".", "languages", ",", "(", ")", "=>", "{", "const", "locales", "=", "Array", ".", "from", "(", "arguments", ")", ";", "const", "runCallback", "=", "fallbackLocales", "=>", "{", "if", "(", "opts", ".", "callback", ")", "{", "opts", ".", "callback", ".", "apply", "(", "this", ",", "[", "this", ".", "getFormatter", "(", "opts", ".", "namespace", ")", ",", "this", ".", "getFormatter", ".", "bind", "(", "this", ")", ",", "locales", ",", "fallbackLocales", "]", ")", ";", "}", "}", ";", "if", "(", "opts", ".", "hasOwnProperty", "(", "'fallbackLanguages'", ")", ")", "{", "loadFallbacks", "(", "runCallback", ")", ";", "}", "else", "{", "runCallback", "(", ")", ";", "}", "}", ")", ";", "}", "else", "if", "(", "opts", ".", "hasOwnProperty", "(", "'fallbackLanguages'", ")", ")", "{", "loadFallbacks", "(", ")", ";", "}", "}" ]
If strawman approved, this would only be
[ "If", "strawman", "approved", "this", "would", "only", "be" ]
7c701afb770517887d937f334c240964086bf86d
https://github.com/brettz9/imf/blob/7c701afb770517887d937f334c240964086bf86d/dist/index-cjs.js#L10-L58
train
Nichejs/Seminarjs
private/lib/core/users.js
users
function users() { var seminarjs = this; var exports = {}; exports.list = []; /** * Add a user * @param {string} name User name * @param {Object} attributes List of attributes to be added to the user */ exports.add = function (name, attributes) { if (exports.find(name)) { return false; } else { exports.list.push(new User(name, attributes)); } }; /** * Finds users * @param {string} name User name * @return {int} Integer >-1 if the user is found, or -1 if not. */ exports.find = function (name) { var total = exports.list.length; for (var i = 0; i < total; i++) { if (exports.list[i].name == name) { return i; } } return -1; }; /** * Removes a user from the list * @param {string} name User name */ exports.remove = function (name) { var index = exports.find(name); exports.list.splice(index, 1); }; /** * Set a property for a user * @param {string} name Username * @param {String} param Parameter name * @param {String} value Parameter value */ exports.set = function (name, param, value) { var index = exports.find(name); exports.list[index][param] = value; }; /** * Get a parameter * @param {string} name User name * @param {String} param Parameter name * @return {String} Parameter value */ exports.get = function (name, param) { var index = exports.find(name); return exports.list[index][param]; }; /** * User constructor * @param {string} name User name * @param {object} attributes User properties */ function User(name, attributes) { var ret = { name: user }; return extend(ret, attributes); } return exports; }
javascript
function users() { var seminarjs = this; var exports = {}; exports.list = []; /** * Add a user * @param {string} name User name * @param {Object} attributes List of attributes to be added to the user */ exports.add = function (name, attributes) { if (exports.find(name)) { return false; } else { exports.list.push(new User(name, attributes)); } }; /** * Finds users * @param {string} name User name * @return {int} Integer >-1 if the user is found, or -1 if not. */ exports.find = function (name) { var total = exports.list.length; for (var i = 0; i < total; i++) { if (exports.list[i].name == name) { return i; } } return -1; }; /** * Removes a user from the list * @param {string} name User name */ exports.remove = function (name) { var index = exports.find(name); exports.list.splice(index, 1); }; /** * Set a property for a user * @param {string} name Username * @param {String} param Parameter name * @param {String} value Parameter value */ exports.set = function (name, param, value) { var index = exports.find(name); exports.list[index][param] = value; }; /** * Get a parameter * @param {string} name User name * @param {String} param Parameter name * @return {String} Parameter value */ exports.get = function (name, param) { var index = exports.find(name); return exports.list[index][param]; }; /** * User constructor * @param {string} name User name * @param {object} attributes User properties */ function User(name, attributes) { var ret = { name: user }; return extend(ret, attributes); } return exports; }
[ "function", "users", "(", ")", "{", "var", "seminarjs", "=", "this", ";", "var", "exports", "=", "{", "}", ";", "exports", ".", "list", "=", "[", "]", ";", "exports", ".", "add", "=", "function", "(", "name", ",", "attributes", ")", "{", "if", "(", "exports", ".", "find", "(", "name", ")", ")", "{", "return", "false", ";", "}", "else", "{", "exports", ".", "list", ".", "push", "(", "new", "User", "(", "name", ",", "attributes", ")", ")", ";", "}", "}", ";", "exports", ".", "find", "=", "function", "(", "name", ")", "{", "var", "total", "=", "exports", ".", "list", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "total", ";", "i", "++", ")", "{", "if", "(", "exports", ".", "list", "[", "i", "]", ".", "name", "==", "name", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}", ";", "exports", ".", "remove", "=", "function", "(", "name", ")", "{", "var", "index", "=", "exports", ".", "find", "(", "name", ")", ";", "exports", ".", "list", ".", "splice", "(", "index", ",", "1", ")", ";", "}", ";", "exports", ".", "set", "=", "function", "(", "name", ",", "param", ",", "value", ")", "{", "var", "index", "=", "exports", ".", "find", "(", "name", ")", ";", "exports", ".", "list", "[", "index", "]", "[", "param", "]", "=", "value", ";", "}", ";", "exports", ".", "get", "=", "function", "(", "name", ",", "param", ")", "{", "var", "index", "=", "exports", ".", "find", "(", "name", ")", ";", "return", "exports", ".", "list", "[", "index", "]", "[", "param", "]", ";", "}", ";", "function", "User", "(", "name", ",", "attributes", ")", "{", "var", "ret", "=", "{", "name", ":", "user", "}", ";", "return", "extend", "(", "ret", ",", "attributes", ")", ";", "}", "return", "exports", ";", "}" ]
User handling for Seminarjs, this should hold the logged in users at any moment, and should be shared by the contest, the chat... etc
[ "User", "handling", "for", "Seminarjs", "this", "should", "hold", "the", "logged", "in", "users", "at", "any", "moment", "and", "should", "be", "shared", "by", "the", "contest", "the", "chat", "...", "etc" ]
53c4c1d5c33ffbf6320b10f25679bf181cbf853e
https://github.com/Nichejs/Seminarjs/blob/53c4c1d5c33ffbf6320b10f25679bf181cbf853e/private/lib/core/users.js#L8-L94
train
getstacker/stacker-args
lib/help/formatter.js
function (parts, indent, prefix) { var lines = []; var line = []; var lineLength = !!prefix ? prefix.length - 1: indent.length - 1; parts.forEach(function (part) { if (lineLength + 1 + part.length > textWidth) { lines.push(indent + line.join(' ')); line = []; lineLength = indent.length - 1; } line.push(part); lineLength += part.length + 1; }); if (line) { lines.push(indent + line.join(' ')); } if (prefix) { lines[0] = lines[0].substr(indent.length); } return lines; }
javascript
function (parts, indent, prefix) { var lines = []; var line = []; var lineLength = !!prefix ? prefix.length - 1: indent.length - 1; parts.forEach(function (part) { if (lineLength + 1 + part.length > textWidth) { lines.push(indent + line.join(' ')); line = []; lineLength = indent.length - 1; } line.push(part); lineLength += part.length + 1; }); if (line) { lines.push(indent + line.join(' ')); } if (prefix) { lines[0] = lines[0].substr(indent.length); } return lines; }
[ "function", "(", "parts", ",", "indent", ",", "prefix", ")", "{", "var", "lines", "=", "[", "]", ";", "var", "line", "=", "[", "]", ";", "var", "lineLength", "=", "!", "!", "prefix", "?", "prefix", ".", "length", "-", "1", ":", "indent", ".", "length", "-", "1", ";", "parts", ".", "forEach", "(", "function", "(", "part", ")", "{", "if", "(", "lineLength", "+", "1", "+", "part", ".", "length", ">", "textWidth", ")", "{", "lines", ".", "push", "(", "indent", "+", "line", ".", "join", "(", "' '", ")", ")", ";", "line", "=", "[", "]", ";", "lineLength", "=", "indent", ".", "length", "-", "1", ";", "}", "line", ".", "push", "(", "part", ")", ";", "lineLength", "+=", "part", ".", "length", "+", "1", ";", "}", ")", ";", "if", "(", "line", ")", "{", "lines", ".", "push", "(", "indent", "+", "line", ".", "join", "(", "' '", ")", ")", ";", "}", "if", "(", "prefix", ")", "{", "lines", "[", "0", "]", "=", "lines", "[", "0", "]", ".", "substr", "(", "indent", ".", "length", ")", ";", "}", "return", "lines", ";", "}" ]
helper for wrapping lines
[ "helper", "for", "wrapping", "lines" ]
38282619b67274c0524507abc992ab03a37f8dcb
https://github.com/getstacker/stacker-args/blob/38282619b67274c0524507abc992ab03a37f8dcb/lib/help/formatter.js#L372-L395
train
phun-ky/patsy
lib/proxy/index.js
function(cfg){ var self = this; var route_opts; patsy.scripture.print('[Patsy]'.yellow + ': Here\'s the proxy my King!\n'); var _getHeaders = function(path, local_headers){ var global_headers = {}; if(typeof cfg.proxy.options.headers !== 'undefined' && typeof cfg.proxy.options.headers === 'object'){ global_headers = xtend({},cfg.proxy.options.headers); } if(typeof local_headers === 'undefined'){ local_headers = {}; } try{ return xtend(global_headers, local_headers); } catch(e){ if(opts.verbose){ utils.fail('Could not extend headers!'); console.log(global_headers, local_headers, e); } else { utils.fail(); } } }; var gotMatch = false, // Find match method _findMatch = function(url, resource){ gotMatch = false; var parsed_resource_pass; if(typeof resource === 'array' || typeof resource === 'object'){ resource.forEach(function(route){ parsed_resource_pass = node_url.parse(route.pass); // First, turn the URL into a regex. // NOTE: Turning user input directly into a Regular Expression is NOT SAFE. var matchPath = new RegExp(route.path.replace(/\//, '\\/')); var matchedPath = matchPath.exec(url); //if(url.match(route.path) && (url !== '/' && route.path.indexOf(url) !== -1)){ if(matchedPath && matchedPath[0] !== '/'){ route_opts = { route : { host: parsed_resource_pass.hostname, port: parsed_resource_pass.port }, from_path : route.path, url : url.replace(route.path, parsed_resource_pass.pathname), headers: _getHeaders(route.path, route.headers || {}) }; //console.log(matchedPath[0],url, route_opts.url, route.path); gotMatch = true; } }); } else if(typeof resource === 'string'){ gotMatch = false; parsed_resource_pass = node_url.parse(resource); if(url.match(resource) && resource.indexOf(url) !== -1){ route_opts = { route : { host: parsed_resource_pass.hostname, port: parsed_resource_pass.port }, url : url, headers: cfg.proxy.options.headers || {} }; gotMatch = true; } } }; try{ // // Create a proxy server with custom application logic // var proxyServer = httpProxy.createServer(function (req, res, proxy) { // // Put your custom server logic here // _findMatch(req.url, cfg.proxy.resources); var _opts = typeof route_opts === 'object' ? route_opts : false; var _route; if(opts.verbose){ util.print('>>'.cyan + ' Setting up route for ' + req.url.cyan + '...'); } if(_opts && gotMatch){ _route = _opts.route; req.url = _opts.url; if(opts.verbose){ utils.ok(); } if(typeof _route !== 'object'){ throw new Error('Required object for proxy is not valid'); } // Set headers // Headers are overwritten like this: // Request headers are overwritten by global headers // Global headers are overwritten by local headers req.headers = xtend(req.headers,_opts.headers || {}); // Set headers with the path we're forwarding from req.headers = xtend(req.headers, { "x-forwarded-path" : _opts.from_path, "x-original-url" : req.url }); if(opts.verbose){ util.print('>>'.cyan + ' Guiding ' + req.url.cyan + ' to ' + _route.host.inverse.magenta + ':' + _route.port.inverse.magenta +'...'); } try{ // Proxy the request proxy.proxyRequest(req, res, _route); } catch( error ){ if(opts.verbose){ utils.fail('Could not proxy given URL when we have match: ' + req.url.cyan); console.log(error, 'Headers',req.headers,'Options',_opts); } else { utils.fail(); } res.writeHead(500, { 'Content-Type': 'text/plain' }); res.write('Could not proxy given URL: ' + req.url +'\n' + 'Given route: ' + JSON.stringify(_route || 'no route found', true, 2) +'\n' + 'Headers:' + JSON.stringify(req.headers, true, 2) +'\n' + 'Given options: ' + JSON.stringify(_opts, true, 2)); res.end(); } if(opts.verbose){ utils.ok(); } } else { // No match found in proxy table for incoming URL, try relay the request to the local webserver instead try{ util.print("WARN".yellow + '\n'); if(opts.verbose){ util.print('>> '.yellow + ' No match found, relaying to: ' + String(cfg.project.environment.host).inverse.magenta +':'+ String(cfg.project.environment.port).inverse.magenta + '...' ); } _route = { host: cfg.project.environment.host, port: cfg.project.environment.port }; // Set headers // Headers are overwritten like this: // Request headers are overwritten by global headers // Global headers are overwritten by local headers req.headers = xtend(req.headers,cfg.proxy.options.headers || {}); // Proxy the request proxy.proxyRequest(req, res, _route); if(opts.verbose){ utils.ok(); } } catch(error){ if(opts.verbose){ utils.fail('Could not proxy given URL with no match found: ' + req.url.cyan); console.log(error, 'Headers',req.headers,'Options',_opts); } else { utils.fail(); } res.writeHead(404, { 'Content-Type': 'text/plain' }); res.write('Could not proxy given URL: ' + req.url +'\n' + 'Headers:' + JSON.stringify(req.headers, true, 2) +'\n' + 'Given options: ' + JSON.stringify(_opts, true, 2)); res.end(); } } // Clean up vars }); proxyServer.listen(cfg.proxy.options.port || 80); proxyServer.proxy.on('proxyError', function (err, req, res) { /*if(typeof req.headers['x-forwarded-path'] !== 'undefined'){ self.mock(res, req); } else {*/ res.writeHead(500, { 'Content-Type': 'text/plain' }); res.write('Something went wrong. And we are reporting a custom error message.') res.write('Could not proxy given URL: ' + req.url +'\n' + 'Headers:' + JSON.stringify(req.headers, true, 2) +'\n'); res.end(); //} }); } catch(e){ util.puts('>> FAIL'.red + ': Could not create proxy server',e); } }
javascript
function(cfg){ var self = this; var route_opts; patsy.scripture.print('[Patsy]'.yellow + ': Here\'s the proxy my King!\n'); var _getHeaders = function(path, local_headers){ var global_headers = {}; if(typeof cfg.proxy.options.headers !== 'undefined' && typeof cfg.proxy.options.headers === 'object'){ global_headers = xtend({},cfg.proxy.options.headers); } if(typeof local_headers === 'undefined'){ local_headers = {}; } try{ return xtend(global_headers, local_headers); } catch(e){ if(opts.verbose){ utils.fail('Could not extend headers!'); console.log(global_headers, local_headers, e); } else { utils.fail(); } } }; var gotMatch = false, // Find match method _findMatch = function(url, resource){ gotMatch = false; var parsed_resource_pass; if(typeof resource === 'array' || typeof resource === 'object'){ resource.forEach(function(route){ parsed_resource_pass = node_url.parse(route.pass); // First, turn the URL into a regex. // NOTE: Turning user input directly into a Regular Expression is NOT SAFE. var matchPath = new RegExp(route.path.replace(/\//, '\\/')); var matchedPath = matchPath.exec(url); //if(url.match(route.path) && (url !== '/' && route.path.indexOf(url) !== -1)){ if(matchedPath && matchedPath[0] !== '/'){ route_opts = { route : { host: parsed_resource_pass.hostname, port: parsed_resource_pass.port }, from_path : route.path, url : url.replace(route.path, parsed_resource_pass.pathname), headers: _getHeaders(route.path, route.headers || {}) }; //console.log(matchedPath[0],url, route_opts.url, route.path); gotMatch = true; } }); } else if(typeof resource === 'string'){ gotMatch = false; parsed_resource_pass = node_url.parse(resource); if(url.match(resource) && resource.indexOf(url) !== -1){ route_opts = { route : { host: parsed_resource_pass.hostname, port: parsed_resource_pass.port }, url : url, headers: cfg.proxy.options.headers || {} }; gotMatch = true; } } }; try{ // // Create a proxy server with custom application logic // var proxyServer = httpProxy.createServer(function (req, res, proxy) { // // Put your custom server logic here // _findMatch(req.url, cfg.proxy.resources); var _opts = typeof route_opts === 'object' ? route_opts : false; var _route; if(opts.verbose){ util.print('>>'.cyan + ' Setting up route for ' + req.url.cyan + '...'); } if(_opts && gotMatch){ _route = _opts.route; req.url = _opts.url; if(opts.verbose){ utils.ok(); } if(typeof _route !== 'object'){ throw new Error('Required object for proxy is not valid'); } // Set headers // Headers are overwritten like this: // Request headers are overwritten by global headers // Global headers are overwritten by local headers req.headers = xtend(req.headers,_opts.headers || {}); // Set headers with the path we're forwarding from req.headers = xtend(req.headers, { "x-forwarded-path" : _opts.from_path, "x-original-url" : req.url }); if(opts.verbose){ util.print('>>'.cyan + ' Guiding ' + req.url.cyan + ' to ' + _route.host.inverse.magenta + ':' + _route.port.inverse.magenta +'...'); } try{ // Proxy the request proxy.proxyRequest(req, res, _route); } catch( error ){ if(opts.verbose){ utils.fail('Could not proxy given URL when we have match: ' + req.url.cyan); console.log(error, 'Headers',req.headers,'Options',_opts); } else { utils.fail(); } res.writeHead(500, { 'Content-Type': 'text/plain' }); res.write('Could not proxy given URL: ' + req.url +'\n' + 'Given route: ' + JSON.stringify(_route || 'no route found', true, 2) +'\n' + 'Headers:' + JSON.stringify(req.headers, true, 2) +'\n' + 'Given options: ' + JSON.stringify(_opts, true, 2)); res.end(); } if(opts.verbose){ utils.ok(); } } else { // No match found in proxy table for incoming URL, try relay the request to the local webserver instead try{ util.print("WARN".yellow + '\n'); if(opts.verbose){ util.print('>> '.yellow + ' No match found, relaying to: ' + String(cfg.project.environment.host).inverse.magenta +':'+ String(cfg.project.environment.port).inverse.magenta + '...' ); } _route = { host: cfg.project.environment.host, port: cfg.project.environment.port }; // Set headers // Headers are overwritten like this: // Request headers are overwritten by global headers // Global headers are overwritten by local headers req.headers = xtend(req.headers,cfg.proxy.options.headers || {}); // Proxy the request proxy.proxyRequest(req, res, _route); if(opts.verbose){ utils.ok(); } } catch(error){ if(opts.verbose){ utils.fail('Could not proxy given URL with no match found: ' + req.url.cyan); console.log(error, 'Headers',req.headers,'Options',_opts); } else { utils.fail(); } res.writeHead(404, { 'Content-Type': 'text/plain' }); res.write('Could not proxy given URL: ' + req.url +'\n' + 'Headers:' + JSON.stringify(req.headers, true, 2) +'\n' + 'Given options: ' + JSON.stringify(_opts, true, 2)); res.end(); } } // Clean up vars }); proxyServer.listen(cfg.proxy.options.port || 80); proxyServer.proxy.on('proxyError', function (err, req, res) { /*if(typeof req.headers['x-forwarded-path'] !== 'undefined'){ self.mock(res, req); } else {*/ res.writeHead(500, { 'Content-Type': 'text/plain' }); res.write('Something went wrong. And we are reporting a custom error message.') res.write('Could not proxy given URL: ' + req.url +'\n' + 'Headers:' + JSON.stringify(req.headers, true, 2) +'\n'); res.end(); //} }); } catch(e){ util.puts('>> FAIL'.red + ': Could not create proxy server',e); } }
[ "function", "(", "cfg", ")", "{", "var", "self", "=", "this", ";", "var", "route_opts", ";", "patsy", ".", "scripture", ".", "print", "(", "'[Patsy]'", ".", "yellow", "+", "': Here\\'s the proxy my King!\\n'", ")", ";", "\\'", "\\n", "var", "_getHeaders", "=", "function", "(", "path", ",", "local_headers", ")", "{", "var", "global_headers", "=", "{", "}", ";", "if", "(", "typeof", "cfg", ".", "proxy", ".", "options", ".", "headers", "!==", "'undefined'", "&&", "typeof", "cfg", ".", "proxy", ".", "options", ".", "headers", "===", "'object'", ")", "{", "global_headers", "=", "xtend", "(", "{", "}", ",", "cfg", ".", "proxy", ".", "options", ".", "headers", ")", ";", "}", "if", "(", "typeof", "local_headers", "===", "'undefined'", ")", "{", "local_headers", "=", "{", "}", ";", "}", "try", "{", "return", "xtend", "(", "global_headers", ",", "local_headers", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "opts", ".", "verbose", ")", "{", "utils", ".", "fail", "(", "'Could not extend headers!'", ")", ";", "console", ".", "log", "(", "global_headers", ",", "local_headers", ",", "e", ")", ";", "}", "else", "{", "utils", ".", "fail", "(", ")", ";", "}", "}", "}", ";", "}" ]
The purpose of this method is to start the proxy server and route API urls from the patsy config.proxy.resources object
[ "The", "purpose", "of", "this", "method", "is", "to", "start", "the", "proxy", "server", "and", "route", "API", "urls", "from", "the", "patsy", "config", ".", "proxy", ".", "resources", "object" ]
b2bf3e6c72e17c38d9b2cf2fa4306478fc3858a5
https://github.com/phun-ky/patsy/blob/b2bf3e6c72e17c38d9b2cf2fa4306478fc3858a5/lib/proxy/index.js#L111-L379
train
melvincarvalho/rdf-shell
lib/put.js
put
function put(argv, callback) { if (!argv[2]) { console.error("url is required"); console.error("Usage : put <url> <data>"); process.exit(-1); } if (!argv[3]) { console.error("data is required"); console.error("Usage : put <url> <data>"); process.exit(-1); } util.put(argv[2], argv[3], function(err, val, uri) { if (!err) { console.log('PUT to : ' + argv[2]); } }); }
javascript
function put(argv, callback) { if (!argv[2]) { console.error("url is required"); console.error("Usage : put <url> <data>"); process.exit(-1); } if (!argv[3]) { console.error("data is required"); console.error("Usage : put <url> <data>"); process.exit(-1); } util.put(argv[2], argv[3], function(err, val, uri) { if (!err) { console.log('PUT to : ' + argv[2]); } }); }
[ "function", "put", "(", "argv", ",", "callback", ")", "{", "if", "(", "!", "argv", "[", "2", "]", ")", "{", "console", ".", "error", "(", "\"url is required\"", ")", ";", "console", ".", "error", "(", "\"Usage : put <url> <data>\"", ")", ";", "process", ".", "exit", "(", "-", "1", ")", ";", "}", "if", "(", "!", "argv", "[", "3", "]", ")", "{", "console", ".", "error", "(", "\"data is required\"", ")", ";", "console", ".", "error", "(", "\"Usage : put <url> <data>\"", ")", ";", "process", ".", "exit", "(", "-", "1", ")", ";", "}", "util", ".", "put", "(", "argv", "[", "2", "]", ",", "argv", "[", "3", "]", ",", "function", "(", "err", ",", "val", ",", "uri", ")", "{", "if", "(", "!", "err", ")", "{", "console", ".", "log", "(", "'PUT to : '", "+", "argv", "[", "2", "]", ")", ";", "}", "}", ")", ";", "}" ]
put gets list of files for a given container @param {String} argv[2] url @param {String} argv[3] data @callback {bin~cb} callback
[ "put", "gets", "list", "of", "files", "for", "a", "given", "container" ]
bf2015f6f333855e69a18ce3ec9e917bbddfb425
https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/put.js#L12-L28
train
MomsFriendlyDevCo/mfdc-email
index.js
init
function init() { // Locate config if we dont have one {{{ if (_.isUndefined(appConfig)) { appConfigLocations.forEach(function(key) { if (_.has(global, key)) { appConfig = _.get(global, key); return false; } }); if (_.isUndefined(appConfig)) throw new Error('Cannot find email config in', appConfigLocations); } // }}} this.config = { // Reset basics from: appConfig.email.from, to: appConfig.email.to, subject: appConfig.email.subject || '', cc: appConfig.email.cc || [], bcc: appConfig.email.bcc || [], }; // Work out mail transport {{{ if (appConfig.email.enabled) { switch (appConfig.email.method) { case 'mailgun': if ( /^https?:\/\//.test(appConfig.mailgun.domain) || /mailgun/.test(appConfig.mailgun.domain) ) throw new Error("Mailgun domain should not contain 'http(s)://' prefix or mailgun. Should resemble the domain name e.g. 'acme.com'"); transporter = nodemailer.createTransport(nodemailerMailgun({ auth: { api_key: appConfig.mailgun.apiKey, domain: appConfig.mailgun.domain, }, })); break case 'sendmail': transporter = nodemailer.createTransport(nodemailerSendmail()); break; default: next('Unknown mail transport method: ' + appConfig.email.method); } } // }}} return this; }
javascript
function init() { // Locate config if we dont have one {{{ if (_.isUndefined(appConfig)) { appConfigLocations.forEach(function(key) { if (_.has(global, key)) { appConfig = _.get(global, key); return false; } }); if (_.isUndefined(appConfig)) throw new Error('Cannot find email config in', appConfigLocations); } // }}} this.config = { // Reset basics from: appConfig.email.from, to: appConfig.email.to, subject: appConfig.email.subject || '', cc: appConfig.email.cc || [], bcc: appConfig.email.bcc || [], }; // Work out mail transport {{{ if (appConfig.email.enabled) { switch (appConfig.email.method) { case 'mailgun': if ( /^https?:\/\//.test(appConfig.mailgun.domain) || /mailgun/.test(appConfig.mailgun.domain) ) throw new Error("Mailgun domain should not contain 'http(s)://' prefix or mailgun. Should resemble the domain name e.g. 'acme.com'"); transporter = nodemailer.createTransport(nodemailerMailgun({ auth: { api_key: appConfig.mailgun.apiKey, domain: appConfig.mailgun.domain, }, })); break case 'sendmail': transporter = nodemailer.createTransport(nodemailerSendmail()); break; default: next('Unknown mail transport method: ' + appConfig.email.method); } } // }}} return this; }
[ "function", "init", "(", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "appConfig", ")", ")", "{", "appConfigLocations", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "_", ".", "has", "(", "global", ",", "key", ")", ")", "{", "appConfig", "=", "_", ".", "get", "(", "global", ",", "key", ")", ";", "return", "false", ";", "}", "}", ")", ";", "if", "(", "_", ".", "isUndefined", "(", "appConfig", ")", ")", "throw", "new", "Error", "(", "'Cannot find email config in'", ",", "appConfigLocations", ")", ";", "}", "this", ".", "config", "=", "{", "from", ":", "appConfig", ".", "email", ".", "from", ",", "to", ":", "appConfig", ".", "email", ".", "to", ",", "subject", ":", "appConfig", ".", "email", ".", "subject", "||", "''", ",", "cc", ":", "appConfig", ".", "email", ".", "cc", "||", "[", "]", ",", "bcc", ":", "appConfig", ".", "email", ".", "bcc", "||", "[", "]", ",", "}", ";", "if", "(", "appConfig", ".", "email", ".", "enabled", ")", "{", "switch", "(", "appConfig", ".", "email", ".", "method", ")", "{", "case", "'mailgun'", ":", "if", "(", "/", "^https?:\\/\\/", "/", ".", "test", "(", "appConfig", ".", "mailgun", ".", "domain", ")", "||", "/", "mailgun", "/", ".", "test", "(", "appConfig", ".", "mailgun", ".", "domain", ")", ")", "throw", "new", "Error", "(", "\"Mailgun domain should not contain 'http(s)://' prefix or mailgun. Should resemble the domain name e.g. 'acme.com'\"", ")", ";", "transporter", "=", "nodemailer", ".", "createTransport", "(", "nodemailerMailgun", "(", "{", "auth", ":", "{", "api_key", ":", "appConfig", ".", "mailgun", ".", "apiKey", ",", "domain", ":", "appConfig", ".", "mailgun", ".", "domain", ",", "}", ",", "}", ")", ")", ";", "break", "case", "'sendmail'", ":", "transporter", "=", "nodemailer", ".", "createTransport", "(", "nodemailerSendmail", "(", ")", ")", ";", "break", ";", "default", ":", "next", "(", "'Unknown mail transport method: '", "+", "appConfig", ".", "email", ".", "method", ")", ";", "}", "}", "return", "this", ";", "}" ]
Array of places to look for config Is expected to contain at least a 'email' object and possibly 'mailgun' Initalize the emailer If this is called multiple times it restarts the mail transport @return {Object} This chainable object
[ "Array", "of", "places", "to", "look", "for", "config", "Is", "expected", "to", "contain", "at", "least", "a", "email", "object", "and", "possibly", "mailgun", "Initalize", "the", "emailer", "If", "this", "is", "called", "multiple", "times", "it", "restarts", "the", "mail", "transport" ]
95cfc411d4f42cd5ddd446979b7c443ded87b93f
https://github.com/MomsFriendlyDevCo/mfdc-email/blob/95cfc411d4f42cd5ddd446979b7c443ded87b93f/index.js#L26-L73
train
widgetworks/nopt-grunt-fix
index.js
parseOptions
function parseOptions(nopt, optlist){ var params = getParams(optlist); var parsedOptions = nopt(params.known, params.aliases, process.argv, 2); initArrays(optlist, parsedOptions); return parsedOptions; }
javascript
function parseOptions(nopt, optlist){ var params = getParams(optlist); var parsedOptions = nopt(params.known, params.aliases, process.argv, 2); initArrays(optlist, parsedOptions); return parsedOptions; }
[ "function", "parseOptions", "(", "nopt", ",", "optlist", ")", "{", "var", "params", "=", "getParams", "(", "optlist", ")", ";", "var", "parsedOptions", "=", "nopt", "(", "params", ".", "known", ",", "params", ".", "aliases", ",", "process", ".", "argv", ",", "2", ")", ";", "initArrays", "(", "optlist", ",", "parsedOptions", ")", ";", "return", "parsedOptions", ";", "}" ]
Normalise the parameters and then parse them.
[ "Normalise", "the", "parameters", "and", "then", "parse", "them", "." ]
44017cb96567763124d42ab5819e71bd98d98465
https://github.com/widgetworks/nopt-grunt-fix/blob/44017cb96567763124d42ab5819e71bd98d98465/index.js#L23-L29
train
widgetworks/nopt-grunt-fix
index.js
resetOptions
function resetOptions(grunt, parsedOptions){ for (var i in parsedOptions){ if (parsedOptions.hasOwnProperty(i) && i != 'argv'){ grunt.option(i, parsedOptions[i]); } } }
javascript
function resetOptions(grunt, parsedOptions){ for (var i in parsedOptions){ if (parsedOptions.hasOwnProperty(i) && i != 'argv'){ grunt.option(i, parsedOptions[i]); } } }
[ "function", "resetOptions", "(", "grunt", ",", "parsedOptions", ")", "{", "for", "(", "var", "i", "in", "parsedOptions", ")", "{", "if", "(", "parsedOptions", ".", "hasOwnProperty", "(", "i", ")", "&&", "i", "!=", "'argv'", ")", "{", "grunt", ".", "option", "(", "i", ",", "parsedOptions", "[", "i", "]", ")", ";", "}", "}", "}" ]
Reassign the options on the Grunt instance.
[ "Reassign", "the", "options", "on", "the", "Grunt", "instance", "." ]
44017cb96567763124d42ab5819e71bd98d98465
https://github.com/widgetworks/nopt-grunt-fix/blob/44017cb96567763124d42ab5819e71bd98d98465/index.js#L33-L39
train
widgetworks/nopt-grunt-fix
index.js
getParams
function getParams(optlist){ var aliases = {}; var known = {}; Object.keys(optlist).forEach(function(key) { var short = optlist[key].short; if (short) { aliases[short] = '--' + key; } known[key] = optlist[key].type; }); return { known: known, aliases: aliases } }
javascript
function getParams(optlist){ var aliases = {}; var known = {}; Object.keys(optlist).forEach(function(key) { var short = optlist[key].short; if (short) { aliases[short] = '--' + key; } known[key] = optlist[key].type; }); return { known: known, aliases: aliases } }
[ "function", "getParams", "(", "optlist", ")", "{", "var", "aliases", "=", "{", "}", ";", "var", "known", "=", "{", "}", ";", "Object", ".", "keys", "(", "optlist", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "short", "=", "optlist", "[", "key", "]", ".", "short", ";", "if", "(", "short", ")", "{", "aliases", "[", "short", "]", "=", "'--'", "+", "key", ";", "}", "known", "[", "key", "]", "=", "optlist", "[", "key", "]", ".", "type", ";", "}", ")", ";", "return", "{", "known", ":", "known", ",", "aliases", ":", "aliases", "}", "}" ]
Parse `optlist` into a form that nopt can handle.
[ "Parse", "optlist", "into", "a", "form", "that", "nopt", "can", "handle", "." ]
44017cb96567763124d42ab5819e71bd98d98465
https://github.com/widgetworks/nopt-grunt-fix/blob/44017cb96567763124d42ab5819e71bd98d98465/index.js#L43-L59
train
widgetworks/nopt-grunt-fix
index.js
initArrays
function initArrays(optlist, parsedOptions){ Object.keys(optlist).forEach(function(key) { if (optlist[key].type === Array && !(key in parsedOptions)) { parsedOptions[key] = []; } }); }
javascript
function initArrays(optlist, parsedOptions){ Object.keys(optlist).forEach(function(key) { if (optlist[key].type === Array && !(key in parsedOptions)) { parsedOptions[key] = []; } }); }
[ "function", "initArrays", "(", "optlist", ",", "parsedOptions", ")", "{", "Object", ".", "keys", "(", "optlist", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "optlist", "[", "key", "]", ".", "type", "===", "Array", "&&", "!", "(", "key", "in", "parsedOptions", ")", ")", "{", "parsedOptions", "[", "key", "]", "=", "[", "]", ";", "}", "}", ")", ";", "}" ]
Initialize any Array options that weren't initialized.
[ "Initialize", "any", "Array", "options", "that", "weren", "t", "initialized", "." ]
44017cb96567763124d42ab5819e71bd98d98465
https://github.com/widgetworks/nopt-grunt-fix/blob/44017cb96567763124d42ab5819e71bd98d98465/index.js#L63-L69
train
sagiegurari/funcs-js
funcs.js
function (fn) { /** * Chain function. * * @function * @memberof! funcs * @alias funcs.maxTimesChain * @private * @param {Number} times - The max times the provided function will be invoked * @returns {function} The new wrapper function */ fn.maxTimes = function (times) { return funcs.maxTimes(fn, times); }; /** * Chain function. * * @function * @memberof! funcs * @alias funcs.onceChain * @private * @returns {function} The new wrapper function */ fn.once = function () { return funcs.once(fn); }; /** * Chain function. * * @function * @memberof! funcs * @alias funcs.delayChain * @private * @param {Number} delay - The invocation delay in millies * @returns {function} The new wrapper function */ fn.delay = function (delay) { return funcs.delay(fn, delay); }; /** * Chain function. * * @function * @memberof! funcs * @alias funcs.asyncChain * @private * @returns {function} The new wrapper function */ fn.async = function () { return funcs.async(fn); }; }
javascript
function (fn) { /** * Chain function. * * @function * @memberof! funcs * @alias funcs.maxTimesChain * @private * @param {Number} times - The max times the provided function will be invoked * @returns {function} The new wrapper function */ fn.maxTimes = function (times) { return funcs.maxTimes(fn, times); }; /** * Chain function. * * @function * @memberof! funcs * @alias funcs.onceChain * @private * @returns {function} The new wrapper function */ fn.once = function () { return funcs.once(fn); }; /** * Chain function. * * @function * @memberof! funcs * @alias funcs.delayChain * @private * @param {Number} delay - The invocation delay in millies * @returns {function} The new wrapper function */ fn.delay = function (delay) { return funcs.delay(fn, delay); }; /** * Chain function. * * @function * @memberof! funcs * @alias funcs.asyncChain * @private * @returns {function} The new wrapper function */ fn.async = function () { return funcs.async(fn); }; }
[ "function", "(", "fn", ")", "{", "fn", ".", "maxTimes", "=", "function", "(", "times", ")", "{", "return", "funcs", ".", "maxTimes", "(", "fn", ",", "times", ")", ";", "}", ";", "fn", ".", "once", "=", "function", "(", ")", "{", "return", "funcs", ".", "once", "(", "fn", ")", ";", "}", ";", "fn", ".", "delay", "=", "function", "(", "delay", ")", "{", "return", "funcs", ".", "delay", "(", "fn", ",", "delay", ")", ";", "}", ";", "fn", ".", "async", "=", "function", "(", ")", "{", "return", "funcs", ".", "async", "(", "fn", ")", ";", "}", ";", "}" ]
Adds chaining support for the provided function. @function @memberof! funcs @alias funcs.addChaining @private @param {function} fn - Adds the funcs APIs to the provided function with this function as a context
[ "Adds", "chaining", "support", "for", "the", "provided", "function", "." ]
8ddd8b04b703d8c424818ba9d2adc0281427864c
https://github.com/sagiegurari/funcs-js/blob/8ddd8b04b703d8c424818ba9d2adc0281427864c/funcs.js#L68-L122
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
nonCharactersBoundary
function nonCharactersBoundary( node ) { return !( node.type == CKEDITOR.NODE_ELEMENT && node.isBlockBoundary( CKEDITOR.tools.extend( {}, CKEDITOR.dtd.$empty, CKEDITOR.dtd.$nonEditable ) ) ); }
javascript
function nonCharactersBoundary( node ) { return !( node.type == CKEDITOR.NODE_ELEMENT && node.isBlockBoundary( CKEDITOR.tools.extend( {}, CKEDITOR.dtd.$empty, CKEDITOR.dtd.$nonEditable ) ) ); }
[ "function", "nonCharactersBoundary", "(", "node", ")", "{", "return", "!", "(", "node", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "node", ".", "isBlockBoundary", "(", "CKEDITOR", ".", "tools", ".", "extend", "(", "{", "}", ",", "CKEDITOR", ".", "dtd", ".", "$empty", ",", "CKEDITOR", ".", "dtd", ".", "$nonEditable", ")", ")", ")", ";", "}" ]
Elements which break characters been considered as sequence.
[ "Elements", "which", "break", "characters", "been", "considered", "as", "sequence", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L14-L16
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function() { return { textNode: this.textNode, offset: this.offset, character: this.textNode ? this.textNode.getText().charAt( this.offset ) : null, hitMatchBoundary: this._.matchBoundary }; }
javascript
function() { return { textNode: this.textNode, offset: this.offset, character: this.textNode ? this.textNode.getText().charAt( this.offset ) : null, hitMatchBoundary: this._.matchBoundary }; }
[ "function", "(", ")", "{", "return", "{", "textNode", ":", "this", ".", "textNode", ",", "offset", ":", "this", ".", "offset", ",", "character", ":", "this", ".", "textNode", "?", "this", ".", "textNode", ".", "getText", "(", ")", ".", "charAt", "(", "this", ".", "offset", ")", ":", "null", ",", "hitMatchBoundary", ":", "this", ".", "_", ".", "matchBoundary", "}", ";", "}" ]
Get the cursor object which represent both current character and it's dom position thing.
[ "Get", "the", "cursor", "object", "which", "represent", "both", "current", "character", "and", "it", "s", "dom", "position", "thing", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L20-L27
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
syncFieldsBetweenTabs
function syncFieldsBetweenTabs( currentPageId ) { var sourceIndex, targetIndex, sourceField, targetField; sourceIndex = currentPageId === 'find' ? 1 : 0; targetIndex = 1 - sourceIndex; var i, l = fieldsMapping.length; for ( i = 0; i < l; i++ ) { sourceField = this.getContentElement( pages[ sourceIndex ], fieldsMapping[ i ][ sourceIndex ] ); targetField = this.getContentElement( pages[ targetIndex ], fieldsMapping[ i ][ targetIndex ] ); targetField.setValue( sourceField.getValue() ); } }
javascript
function syncFieldsBetweenTabs( currentPageId ) { var sourceIndex, targetIndex, sourceField, targetField; sourceIndex = currentPageId === 'find' ? 1 : 0; targetIndex = 1 - sourceIndex; var i, l = fieldsMapping.length; for ( i = 0; i < l; i++ ) { sourceField = this.getContentElement( pages[ sourceIndex ], fieldsMapping[ i ][ sourceIndex ] ); targetField = this.getContentElement( pages[ targetIndex ], fieldsMapping[ i ][ targetIndex ] ); targetField.setValue( sourceField.getValue() ); } }
[ "function", "syncFieldsBetweenTabs", "(", "currentPageId", ")", "{", "var", "sourceIndex", ",", "targetIndex", ",", "sourceField", ",", "targetField", ";", "sourceIndex", "=", "currentPageId", "===", "'find'", "?", "1", ":", "0", ";", "targetIndex", "=", "1", "-", "sourceIndex", ";", "var", "i", ",", "l", "=", "fieldsMapping", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "sourceField", "=", "this", ".", "getContentElement", "(", "pages", "[", "sourceIndex", "]", ",", "fieldsMapping", "[", "i", "]", "[", "sourceIndex", "]", ")", ";", "targetField", "=", "this", ".", "getContentElement", "(", "pages", "[", "targetIndex", "]", ",", "fieldsMapping", "[", "i", "]", "[", "targetIndex", "]", ")", ";", "targetField", ".", "setValue", "(", "sourceField", ".", "getValue", "(", ")", ")", ";", "}", "}" ]
Synchronize corresponding filed values between 'replace' and 'find' pages. @param {String} currentPageId The page id which receive values.
[ "Synchronize", "corresponding", "filed", "values", "between", "replace", "and", "find", "pages", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L38-L51
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function( range, matchWord ) { var self = this; var walker = new CKEDITOR.dom.walker( range ); walker.guard = matchWord ? nonCharactersBoundary : function( node ) { !nonCharactersBoundary( node ) && ( self._.matchBoundary = true ); }; walker[ 'evaluator' ] = findEvaluator; walker.breakOnFalse = 1; if ( range.startContainer.type == CKEDITOR.NODE_TEXT ) { this.textNode = range.startContainer; this.offset = range.startOffset - 1; } this._ = { matchWord: matchWord, walker: walker, matchBoundary: false }; }
javascript
function( range, matchWord ) { var self = this; var walker = new CKEDITOR.dom.walker( range ); walker.guard = matchWord ? nonCharactersBoundary : function( node ) { !nonCharactersBoundary( node ) && ( self._.matchBoundary = true ); }; walker[ 'evaluator' ] = findEvaluator; walker.breakOnFalse = 1; if ( range.startContainer.type == CKEDITOR.NODE_TEXT ) { this.textNode = range.startContainer; this.offset = range.startOffset - 1; } this._ = { matchWord: matchWord, walker: walker, matchBoundary: false }; }
[ "function", "(", "range", ",", "matchWord", ")", "{", "var", "self", "=", "this", ";", "var", "walker", "=", "new", "CKEDITOR", ".", "dom", ".", "walker", "(", "range", ")", ";", "walker", ".", "guard", "=", "matchWord", "?", "nonCharactersBoundary", ":", "function", "(", "node", ")", "{", "!", "nonCharactersBoundary", "(", "node", ")", "&&", "(", "self", ".", "_", ".", "matchBoundary", "=", "true", ")", ";", "}", ";", "walker", "[", "'evaluator'", "]", "=", "findEvaluator", ";", "walker", ".", "breakOnFalse", "=", "1", ";", "if", "(", "range", ".", "startContainer", ".", "type", "==", "CKEDITOR", ".", "NODE_TEXT", ")", "{", "this", ".", "textNode", "=", "range", ".", "startContainer", ";", "this", ".", "offset", "=", "range", ".", "startOffset", "-", "1", ";", "}", "this", ".", "_", "=", "{", "matchWord", ":", "matchWord", ",", "walker", ":", "walker", ",", "matchBoundary", ":", "false", "}", ";", "}" ]
Iterator which walk through the specified range char by char. By default the walking will not stop at the character boundaries, until the end of the range is encountered. @param { CKEDITOR.dom.range } range @param {Boolean} matchWord Whether the walking will stop at character boundary.
[ "Iterator", "which", "walk", "through", "the", "specified", "range", "char", "by", "char", ".", "By", "default", "the", "walking", "will", "not", "stop", "at", "the", "character", "boundaries", "until", "the", "end", "of", "the", "range", "is", "encountered", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L68-L87
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function( characterWalker, rangeLength ) { this._ = { walker: characterWalker, cursors: [], rangeLength: rangeLength, highlightRange: null, isMatched: 0 }; }
javascript
function( characterWalker, rangeLength ) { this._ = { walker: characterWalker, cursors: [], rangeLength: rangeLength, highlightRange: null, isMatched: 0 }; }
[ "function", "(", "characterWalker", ",", "rangeLength", ")", "{", "this", ".", "_", "=", "{", "walker", ":", "characterWalker", ",", "cursors", ":", "[", "]", ",", "rangeLength", ":", "rangeLength", ",", "highlightRange", ":", "null", ",", "isMatched", ":", "0", "}", ";", "}" ]
A range of cursors which represent a trunk of characters which try to match, it has the same length as the pattern string. **Note:** This class isn't accessible from global scope. @private @class CKEDITOR.plugins.find.characterRange @constructor Creates a characterRange class instance.
[ "A", "range", "of", "cursors", "which", "represent", "a", "trunk", "of", "characters", "which", "try", "to", "match", "it", "has", "the", "same", "length", "as", "the", "pattern", "string", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L147-L155
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function( domRange ) { var cursor, walker = new characterWalker( domRange ); this._.cursors = []; do { cursor = walker.next(); if ( cursor.character ) this._.cursors.push( cursor ); } while ( cursor.character ); this._.rangeLength = this._.cursors.length; }
javascript
function( domRange ) { var cursor, walker = new characterWalker( domRange ); this._.cursors = []; do { cursor = walker.next(); if ( cursor.character ) this._.cursors.push( cursor ); } while ( cursor.character ); this._.rangeLength = this._.cursors.length; }
[ "function", "(", "domRange", ")", "{", "var", "cursor", ",", "walker", "=", "new", "characterWalker", "(", "domRange", ")", ";", "this", ".", "_", ".", "cursors", "=", "[", "]", ";", "do", "{", "cursor", "=", "walker", ".", "next", "(", ")", ";", "if", "(", "cursor", ".", "character", ")", "this", ".", "_", ".", "cursors", ".", "push", "(", "cursor", ")", ";", "}", "while", "(", "cursor", ".", "character", ")", ";", "this", ".", "_", ".", "rangeLength", "=", "this", ".", "_", ".", "cursors", ".", "length", ";", "}" ]
Reflect the latest changes from dom range.
[ "Reflect", "the", "latest", "changes", "from", "dom", "range", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L184-L194
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function() { // Do not apply if nothing is found. if ( this._.cursors.length < 1 ) return; // Remove the previous highlight if there's one. if ( this._.highlightRange ) this.removeHighlight(); // Apply the highlight. var range = this.toDomRange(), bookmark = range.createBookmark(); highlightStyle.applyToRange( range, editor ); range.moveToBookmark( bookmark ); this._.highlightRange = range; // Scroll the editor to the highlighted area. var element = range.startContainer; if ( element.type != CKEDITOR.NODE_ELEMENT ) element = element.getParent(); element.scrollIntoView(); // Update the character cursors. this.updateFromDomRange( range ); }
javascript
function() { // Do not apply if nothing is found. if ( this._.cursors.length < 1 ) return; // Remove the previous highlight if there's one. if ( this._.highlightRange ) this.removeHighlight(); // Apply the highlight. var range = this.toDomRange(), bookmark = range.createBookmark(); highlightStyle.applyToRange( range, editor ); range.moveToBookmark( bookmark ); this._.highlightRange = range; // Scroll the editor to the highlighted area. var element = range.startContainer; if ( element.type != CKEDITOR.NODE_ELEMENT ) element = element.getParent(); element.scrollIntoView(); // Update the character cursors. this.updateFromDomRange( range ); }
[ "function", "(", ")", "{", "if", "(", "this", ".", "_", ".", "cursors", ".", "length", "<", "1", ")", "return", ";", "if", "(", "this", ".", "_", ".", "highlightRange", ")", "this", ".", "removeHighlight", "(", ")", ";", "var", "range", "=", "this", ".", "toDomRange", "(", ")", ",", "bookmark", "=", "range", ".", "createBookmark", "(", ")", ";", "highlightStyle", ".", "applyToRange", "(", "range", ",", "editor", ")", ";", "range", ".", "moveToBookmark", "(", "bookmark", ")", ";", "this", ".", "_", ".", "highlightRange", "=", "range", ";", "var", "element", "=", "range", ".", "startContainer", ";", "if", "(", "element", ".", "type", "!=", "CKEDITOR", ".", "NODE_ELEMENT", ")", "element", "=", "element", ".", "getParent", "(", ")", ";", "element", ".", "scrollIntoView", "(", ")", ";", "this", ".", "updateFromDomRange", "(", "range", ")", ";", "}" ]
Hightlight the current matched chunk of text.
[ "Hightlight", "the", "current", "matched", "chunk", "of", "text", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L211-L235
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function() { if ( !this._.highlightRange ) return; var bookmark = this._.highlightRange.createBookmark(); highlightStyle.removeFromRange( this._.highlightRange, editor ); this._.highlightRange.moveToBookmark( bookmark ); this.updateFromDomRange( this._.highlightRange ); this._.highlightRange = null; }
javascript
function() { if ( !this._.highlightRange ) return; var bookmark = this._.highlightRange.createBookmark(); highlightStyle.removeFromRange( this._.highlightRange, editor ); this._.highlightRange.moveToBookmark( bookmark ); this.updateFromDomRange( this._.highlightRange ); this._.highlightRange = null; }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "_", ".", "highlightRange", ")", "return", ";", "var", "bookmark", "=", "this", ".", "_", ".", "highlightRange", ".", "createBookmark", "(", ")", ";", "highlightStyle", ".", "removeFromRange", "(", "this", ".", "_", ".", "highlightRange", ",", "editor", ")", ";", "this", ".", "_", ".", "highlightRange", ".", "moveToBookmark", "(", "bookmark", ")", ";", "this", ".", "updateFromDomRange", "(", "this", ".", "_", ".", "highlightRange", ")", ";", "this", ".", "_", ".", "highlightRange", "=", "null", ";", "}" ]
Remove highlighted find result.
[ "Remove", "highlighted", "find", "result", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L240-L249
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
getRangeAfterCursor
function getRangeAfterCursor( cursor, inclusive ) { var range = editor.createRange(); range.setStart( cursor.textNode, ( inclusive ? cursor.offset : cursor.offset + 1 ) ); range.setEndAt( editor.editable(), CKEDITOR.POSITION_BEFORE_END ); return range; }
javascript
function getRangeAfterCursor( cursor, inclusive ) { var range = editor.createRange(); range.setStart( cursor.textNode, ( inclusive ? cursor.offset : cursor.offset + 1 ) ); range.setEndAt( editor.editable(), CKEDITOR.POSITION_BEFORE_END ); return range; }
[ "function", "getRangeAfterCursor", "(", "cursor", ",", "inclusive", ")", "{", "var", "range", "=", "editor", ".", "createRange", "(", ")", ";", "range", ".", "setStart", "(", "cursor", ".", "textNode", ",", "(", "inclusive", "?", "cursor", ".", "offset", ":", "cursor", ".", "offset", "+", "1", ")", ")", ";", "range", ".", "setEndAt", "(", "editor", ".", "editable", "(", ")", ",", "CKEDITOR", ".", "POSITION_BEFORE_END", ")", ";", "return", "range", ";", "}" ]
The remaining document range after the character cursor.
[ "The", "remaining", "document", "range", "after", "the", "character", "cursor", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L315-L320
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
getRangeBeforeCursor
function getRangeBeforeCursor( cursor ) { var range = editor.createRange(); range.setStartAt( editor.editable(), CKEDITOR.POSITION_AFTER_START ); range.setEnd( cursor.textNode, cursor.offset ); return range; }
javascript
function getRangeBeforeCursor( cursor ) { var range = editor.createRange(); range.setStartAt( editor.editable(), CKEDITOR.POSITION_AFTER_START ); range.setEnd( cursor.textNode, cursor.offset ); return range; }
[ "function", "getRangeBeforeCursor", "(", "cursor", ")", "{", "var", "range", "=", "editor", ".", "createRange", "(", ")", ";", "range", ".", "setStartAt", "(", "editor", ".", "editable", "(", ")", ",", "CKEDITOR", ".", "POSITION_AFTER_START", ")", ";", "range", ".", "setEnd", "(", "cursor", ".", "textNode", ",", "cursor", ".", "offset", ")", ";", "return", "range", ";", "}" ]
The document range before the character cursor.
[ "The", "document", "range", "before", "the", "character", "cursor", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L323-L328
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/find/dialogs/find.js
function( pattern, ignoreCase ) { var overlap = [ -1 ]; if ( ignoreCase ) pattern = pattern.toLowerCase(); for ( var i = 0; i < pattern.length; i++ ) { overlap.push( overlap[ i ] + 1 ); while ( overlap[ i + 1 ] > 0 && pattern.charAt( i ) != pattern.charAt( overlap[ i + 1 ] - 1 ) ) overlap[ i + 1 ] = overlap[ overlap[ i + 1 ] - 1 ] + 1; } this._ = { overlap: overlap, state: 0, ignoreCase: !!ignoreCase, pattern: pattern }; }
javascript
function( pattern, ignoreCase ) { var overlap = [ -1 ]; if ( ignoreCase ) pattern = pattern.toLowerCase(); for ( var i = 0; i < pattern.length; i++ ) { overlap.push( overlap[ i ] + 1 ); while ( overlap[ i + 1 ] > 0 && pattern.charAt( i ) != pattern.charAt( overlap[ i + 1 ] - 1 ) ) overlap[ i + 1 ] = overlap[ overlap[ i + 1 ] - 1 ] + 1; } this._ = { overlap: overlap, state: 0, ignoreCase: !!ignoreCase, pattern: pattern }; }
[ "function", "(", "pattern", ",", "ignoreCase", ")", "{", "var", "overlap", "=", "[", "-", "1", "]", ";", "if", "(", "ignoreCase", ")", "pattern", "=", "pattern", ".", "toLowerCase", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "pattern", ".", "length", ";", "i", "++", ")", "{", "overlap", ".", "push", "(", "overlap", "[", "i", "]", "+", "1", ")", ";", "while", "(", "overlap", "[", "i", "+", "1", "]", ">", "0", "&&", "pattern", ".", "charAt", "(", "i", ")", "!=", "pattern", ".", "charAt", "(", "overlap", "[", "i", "+", "1", "]", "-", "1", ")", ")", "overlap", "[", "i", "+", "1", "]", "=", "overlap", "[", "overlap", "[", "i", "+", "1", "]", "-", "1", "]", "+", "1", ";", "}", "this", ".", "_", "=", "{", "overlap", ":", "overlap", ",", "state", ":", "0", ",", "ignoreCase", ":", "!", "!", "ignoreCase", ",", "pattern", ":", "pattern", "}", ";", "}" ]
Examination the occurrence of a word which implement KMP algorithm.
[ "Examination", "the", "occurrence", "of", "a", "word", "which", "implement", "KMP", "algorithm", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/find/dialogs/find.js#L335-L351
train
ultraq/dumb-query-selector
dumb-query-selector.js
function(query, scope) { return Array.prototype.slice.call((scope || document).querySelectorAll(query)); }
javascript
function(query, scope) { return Array.prototype.slice.call((scope || document).querySelectorAll(query)); }
[ "function", "(", "query", ",", "scope", ")", "{", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "(", "scope", "||", "document", ")", ".", "querySelectorAll", "(", "query", ")", ")", ";", "}" ]
An element list selector, returning an array of elements because `NodeList`s are dumb. @param {String} query @param {Node} [scope=document] The scope to limit the search to for non-ID queries. Defaults to `document` scope. @return {Array} The list of matching elements.
[ "An", "element", "list", "selector", "returning", "an", "array", "of", "elements", "because", "NodeList", "s", "are", "dumb", "." ]
f4af7d4d7e5ef364ea455ad538c4ae1acde24bba
https://github.com/ultraq/dumb-query-selector/blob/f4af7d4d7e5ef364ea455ad538c4ae1acde24bba/dumb-query-selector.js#L62-L64
train
mairatma/es6-imports-renamer
lib/ES6ImportsRenamer.js
ES6ImportsRenamer
function ES6ImportsRenamer(config, callback) { config = config || {}; this._basePath = config.basePath; this._renameDependencies = config.renameDependencies; this._renameFn = config.renameFn; this._callback = callback; this._addedMap = {}; this._initStack(config.sources || []); this._renameNextAst(); }
javascript
function ES6ImportsRenamer(config, callback) { config = config || {}; this._basePath = config.basePath; this._renameDependencies = config.renameDependencies; this._renameFn = config.renameFn; this._callback = callback; this._addedMap = {}; this._initStack(config.sources || []); this._renameNextAst(); }
[ "function", "ES6ImportsRenamer", "(", "config", ",", "callback", ")", "{", "config", "=", "config", "||", "{", "}", ";", "this", ".", "_basePath", "=", "config", ".", "basePath", ";", "this", ".", "_renameDependencies", "=", "config", ".", "renameDependencies", ";", "this", ".", "_renameFn", "=", "config", ".", "renameFn", ";", "this", ".", "_callback", "=", "callback", ";", "this", ".", "_addedMap", "=", "{", "}", ";", "this", ".", "_initStack", "(", "config", ".", "sources", "||", "[", "]", ")", ";", "this", ".", "_renameNextAst", "(", ")", ";", "}" ]
Class responsible for renaming import paths present in both the given source files and their dependencies, according to the given rename function. @param {{sources: !Array<{ast: !Object, path: string}>, basePath: ?string}} config @param {function(Error, Array)} callback Function to be called when the renaming is done. @constructor
[ "Class", "responsible", "for", "renaming", "import", "paths", "present", "in", "both", "the", "given", "source", "files", "and", "their", "dependencies", "according", "to", "the", "given", "rename", "function", "." ]
ad03988f485ad4b116ce2fcad54200aca3edb67e
https://github.com/mairatma/es6-imports-renamer/blob/ad03988f485ad4b116ce2fcad54200aca3edb67e/lib/ES6ImportsRenamer.js#L17-L28
train
jamestalmage/firebase-copy
index.js
createRequireFunc
function createRequireFunc(customResolver) { return function (requestedPath) { var resolvedPath = null; try { resolvedPath = resolve.sync(requestedPath, {basedir: FIRBASE_DIR}); } catch (e) {} return customResolver(requestedPath, resolvedPath); }; }
javascript
function createRequireFunc(customResolver) { return function (requestedPath) { var resolvedPath = null; try { resolvedPath = resolve.sync(requestedPath, {basedir: FIRBASE_DIR}); } catch (e) {} return customResolver(requestedPath, resolvedPath); }; }
[ "function", "createRequireFunc", "(", "customResolver", ")", "{", "return", "function", "(", "requestedPath", ")", "{", "var", "resolvedPath", "=", "null", ";", "try", "{", "resolvedPath", "=", "resolve", ".", "sync", "(", "requestedPath", ",", "{", "basedir", ":", "FIRBASE_DIR", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "return", "customResolver", "(", "requestedPath", ",", "resolvedPath", ")", ";", "}", ";", "}" ]
eslint-disable-line no-new-func
[ "eslint", "-", "disable", "-", "line", "no", "-", "new", "-", "func" ]
e876693afa6d5ec0c40a95c4314a113e3432aa75
https://github.com/jamestalmage/firebase-copy/blob/e876693afa6d5ec0c40a95c4314a113e3432aa75/index.js#L9-L17
train
dennismckinnon/tmsp-server
lib/server.js
runNextRequest
function runNextRequest(){ var self = this; var req = parser.read() if (req){ var res = new Response(req); res.assignSocket(socket) //No matter how the response object gets closed this //will trigger the next one if there is one. res.once('close', function(){ //Check if there is work. if(self.work){ runNextRequest.call(self) } else { //Let the system know that you have stopped working self.working = false; } }); this.emit('request', req, res); } }
javascript
function runNextRequest(){ var self = this; var req = parser.read() if (req){ var res = new Response(req); res.assignSocket(socket) //No matter how the response object gets closed this //will trigger the next one if there is one. res.once('close', function(){ //Check if there is work. if(self.work){ runNextRequest.call(self) } else { //Let the system know that you have stopped working self.working = false; } }); this.emit('request', req, res); } }
[ "function", "runNextRequest", "(", ")", "{", "var", "self", "=", "this", ";", "var", "req", "=", "parser", ".", "read", "(", ")", "if", "(", "req", ")", "{", "var", "res", "=", "new", "Response", "(", "req", ")", ";", "res", ".", "assignSocket", "(", "socket", ")", "res", ".", "once", "(", "'close'", ",", "function", "(", ")", "{", "if", "(", "self", ".", "work", ")", "{", "runNextRequest", ".", "call", "(", "self", ")", "}", "else", "{", "self", ".", "working", "=", "false", ";", "}", "}", ")", ";", "this", ".", "emit", "(", "'request'", ",", "req", ",", "res", ")", ";", "}", "}" ]
This is the request processor loop using events to trigger the next request in the Queue.
[ "This", "is", "the", "request", "processor", "loop", "using", "events", "to", "trigger", "the", "next", "request", "in", "the", "Queue", "." ]
24d054c5a3eeacc6552645a2e3a7ed353112b171
https://github.com/dennismckinnon/tmsp-server/blob/24d054c5a3eeacc6552645a2e3a7ed353112b171/lib/server.js#L85-L107
train
leowang721/k-core
util.js
rand16Num
function rand16Num(len) { let result = []; for (let i = 0; i < len; i++) { result.push('0123456789abcdef'.charAt( Math.floor(Math.random() * 16)) ); } return result.join(''); }
javascript
function rand16Num(len) { let result = []; for (let i = 0; i < len; i++) { result.push('0123456789abcdef'.charAt( Math.floor(Math.random() * 16)) ); } return result.join(''); }
[ "function", "rand16Num", "(", "len", ")", "{", "let", "result", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "result", ".", "push", "(", "'0123456789abcdef'", ".", "charAt", "(", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "16", ")", ")", ")", ";", "}", "return", "result", ".", "join", "(", "''", ")", ";", "}" ]
Generates a random GUID legal string of the given length. @param {number} len 要生成串的长度 @return {string} 指定长度的16进制数随机串
[ "Generates", "a", "random", "GUID", "legal", "string", "of", "the", "given", "length", "." ]
582a526b43856d8e0312dd5fe1e617b19db4861d
https://github.com/leowang721/k-core/blob/582a526b43856d8e0312dd5fe1e617b19db4861d/util.js#L16-L24
train
valerii-zinchenko/class-wrapper
lib/ClassBuilder.js
ClassBuilder
function ClassBuilder(InstanceBuilder, Parent, Constructor, props) { // Last input argument is an object of properties for a new class props = arguments[arguments.length - 1]; // Second last input argument is a constructor function Constructor = arguments[arguments.length - 2]; // Set default Parent class if it is not provided if (arguments.length === 3) { Parent = Object; } // Validate input arguments // -------------------------------------------------- if (arguments.length < 3 || typeof InstanceBuilder !== 'function' || Object.prototype.toString.call(Parent) !== '[object Function]' || (Constructor !== null && typeof Constructor !== 'function') || Object.prototype.toString.call(props) !== '[object Object]') { throw new Error('Incorrect input arguments. It should be: ClassBuilder(Function, [Function], Function | null, Object)'); } // -------------------------------------------------- // Extract class name if defined // -------------------------------------------------- var className = ''; if (typeof props.__name === 'string' && props.__name) { className = props.__name; } delete props.__name; // -------------------------------------------------- // Prepare an array of what is going to be encapsulated into a new class // -------------------------------------------------- var encapsulations = []; // Collect objects properties and methods if (props.Encapsulate) { if (Object.prototype.toString.call(props.Encapsulate) === '[object Array]') { encapsulations = encapsulations.concat(props.Encapsulate); } else { encapsulations.push(props.Encapsulate); } // Remove "Encapsulate" property, because it is not need to be encapsulated delete props.Encapsulate; } // Put parent's defaults into an encapsulation stack if (Parent.prototype.__defaults) { encapsulations.unshift(Parent.prototype.__defaults); } // Put properties and methods for a new class into the encapsulation stack encapsulations.push(props); // Validate what is going to be encapsulated if (encapsulations.some(function(item) { var type = Object.prototype.toString.call(item); return type !== '[object Function]' && type !== '[object Object]'; })) { throw new Error('Some of the items for encapsulation is incorrect. An item can be: Object, Function, Class'); } // -------------------------------------------------- // Clone class constructor function to prevent a sharing of instance builder function // -------------------------------------------------- var Class; var declaration = className ? 'var ' + className + '; Class = ' + className + ' = ' : 'Class = '; eval(declaration + InstanceBuilder.toString()); // -------------------------------------------------- // Inheritance chain // -------------------------------------------------- // Derive a new class from a Parent class Class.prototype = Object.create(Parent.prototype); // Revert back the reference to the instance builder function Class.prototype.constructor = Class; // Store the reference to the constructor function if (Constructor) { Class.prototype.__constructor = Constructor; } // Create a storage for default properties Class.prototype.__defaults = {}; // Store a reference to a parent's prototype object for internal usage Class.__parent = Parent.prototype; // -------------------------------------------------- // Encapsulate properties and methods // -------------------------------------------------- for (var n = 0, N = encapsulations.length; n < N; n++) { ClassBuilder.encapsulate(encapsulations[n], Class); } // -------------------------------------------------- return Class; }
javascript
function ClassBuilder(InstanceBuilder, Parent, Constructor, props) { // Last input argument is an object of properties for a new class props = arguments[arguments.length - 1]; // Second last input argument is a constructor function Constructor = arguments[arguments.length - 2]; // Set default Parent class if it is not provided if (arguments.length === 3) { Parent = Object; } // Validate input arguments // -------------------------------------------------- if (arguments.length < 3 || typeof InstanceBuilder !== 'function' || Object.prototype.toString.call(Parent) !== '[object Function]' || (Constructor !== null && typeof Constructor !== 'function') || Object.prototype.toString.call(props) !== '[object Object]') { throw new Error('Incorrect input arguments. It should be: ClassBuilder(Function, [Function], Function | null, Object)'); } // -------------------------------------------------- // Extract class name if defined // -------------------------------------------------- var className = ''; if (typeof props.__name === 'string' && props.__name) { className = props.__name; } delete props.__name; // -------------------------------------------------- // Prepare an array of what is going to be encapsulated into a new class // -------------------------------------------------- var encapsulations = []; // Collect objects properties and methods if (props.Encapsulate) { if (Object.prototype.toString.call(props.Encapsulate) === '[object Array]') { encapsulations = encapsulations.concat(props.Encapsulate); } else { encapsulations.push(props.Encapsulate); } // Remove "Encapsulate" property, because it is not need to be encapsulated delete props.Encapsulate; } // Put parent's defaults into an encapsulation stack if (Parent.prototype.__defaults) { encapsulations.unshift(Parent.prototype.__defaults); } // Put properties and methods for a new class into the encapsulation stack encapsulations.push(props); // Validate what is going to be encapsulated if (encapsulations.some(function(item) { var type = Object.prototype.toString.call(item); return type !== '[object Function]' && type !== '[object Object]'; })) { throw new Error('Some of the items for encapsulation is incorrect. An item can be: Object, Function, Class'); } // -------------------------------------------------- // Clone class constructor function to prevent a sharing of instance builder function // -------------------------------------------------- var Class; var declaration = className ? 'var ' + className + '; Class = ' + className + ' = ' : 'Class = '; eval(declaration + InstanceBuilder.toString()); // -------------------------------------------------- // Inheritance chain // -------------------------------------------------- // Derive a new class from a Parent class Class.prototype = Object.create(Parent.prototype); // Revert back the reference to the instance builder function Class.prototype.constructor = Class; // Store the reference to the constructor function if (Constructor) { Class.prototype.__constructor = Constructor; } // Create a storage for default properties Class.prototype.__defaults = {}; // Store a reference to a parent's prototype object for internal usage Class.__parent = Parent.prototype; // -------------------------------------------------- // Encapsulate properties and methods // -------------------------------------------------- for (var n = 0, N = encapsulations.length; n < N; n++) { ClassBuilder.encapsulate(encapsulations[n], Class); } // -------------------------------------------------- return Class; }
[ "function", "ClassBuilder", "(", "InstanceBuilder", ",", "Parent", ",", "Constructor", ",", "props", ")", "{", "props", "=", "arguments", "[", "arguments", ".", "length", "-", "1", "]", ";", "Constructor", "=", "arguments", "[", "arguments", ".", "length", "-", "2", "]", ";", "if", "(", "arguments", ".", "length", "===", "3", ")", "{", "Parent", "=", "Object", ";", "}", "if", "(", "arguments", ".", "length", "<", "3", "||", "typeof", "InstanceBuilder", "!==", "'function'", "||", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "Parent", ")", "!==", "'[object Function]'", "||", "(", "Constructor", "!==", "null", "&&", "typeof", "Constructor", "!==", "'function'", ")", "||", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "props", ")", "!==", "'[object Object]'", ")", "{", "throw", "new", "Error", "(", "'Incorrect input arguments. It should be: ClassBuilder(Function, [Function], Function | null, Object)'", ")", ";", "}", "var", "className", "=", "''", ";", "if", "(", "typeof", "props", ".", "__name", "===", "'string'", "&&", "props", ".", "__name", ")", "{", "className", "=", "props", ".", "__name", ";", "}", "delete", "props", ".", "__name", ";", "var", "encapsulations", "=", "[", "]", ";", "if", "(", "props", ".", "Encapsulate", ")", "{", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "props", ".", "Encapsulate", ")", "===", "'[object Array]'", ")", "{", "encapsulations", "=", "encapsulations", ".", "concat", "(", "props", ".", "Encapsulate", ")", ";", "}", "else", "{", "encapsulations", ".", "push", "(", "props", ".", "Encapsulate", ")", ";", "}", "delete", "props", ".", "Encapsulate", ";", "}", "if", "(", "Parent", ".", "prototype", ".", "__defaults", ")", "{", "encapsulations", ".", "unshift", "(", "Parent", ".", "prototype", ".", "__defaults", ")", ";", "}", "encapsulations", ".", "push", "(", "props", ")", ";", "if", "(", "encapsulations", ".", "some", "(", "function", "(", "item", ")", "{", "var", "type", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "item", ")", ";", "return", "type", "!==", "'[object Function]'", "&&", "type", "!==", "'[object Object]'", ";", "}", ")", ")", "{", "throw", "new", "Error", "(", "'Some of the items for encapsulation is incorrect. An item can be: Object, Function, Class'", ")", ";", "}", "var", "Class", ";", "var", "declaration", "=", "className", "?", "'var '", "+", "className", "+", "'; Class = '", "+", "className", "+", "' = '", ":", "'Class = '", ";", "eval", "(", "declaration", "+", "InstanceBuilder", ".", "toString", "(", ")", ")", ";", "Class", ".", "prototype", "=", "Object", ".", "create", "(", "Parent", ".", "prototype", ")", ";", "Class", ".", "prototype", ".", "constructor", "=", "Class", ";", "if", "(", "Constructor", ")", "{", "Class", ".", "prototype", ".", "__constructor", "=", "Constructor", ";", "}", "Class", ".", "prototype", ".", "__defaults", "=", "{", "}", ";", "Class", ".", "__parent", "=", "Parent", ".", "prototype", ";", "for", "(", "var", "n", "=", "0", ",", "N", "=", "encapsulations", ".", "length", ";", "n", "<", "N", ";", "n", "++", ")", "{", "ClassBuilder", ".", "encapsulate", "(", "encapsulations", "[", "n", "]", ",", "Class", ")", ";", "}", "return", "Class", ";", "}" ]
Main class builder. It takes the constructor function and wraps it to add few automated processes for constructing a new class. Properties and features: - set the parent class - save the inheritance chain - define the classes/functions/objects that are going to be encapsulated into the resulting class. The last encapsulated object will have a precedence over the previous objects, even parent class. Only the own properties of the new class will have the highest precedence - the reference to the parent class is stored in 'parent' property - inherited methods are stored in class prototype object - store default class properties in '__default' object where the objects will be copied, not shared @see {@link Class} @see {@link SingletonClass} @throws {Error} Incorrect input arguments. It should be: ClassBuilder(Function, [Function], Function | null, Object) @throws {Error} Some of the items for encapsulation is incorrect. An item can be: Object, Function, Class @param {Function} InstanceBuilder - Function that defines how instances will be created, how constructor(s) will be executed @param {Function} [Parent = Object] - Parent class @param {Function | null} Constructor - Constructor function @param {Object} props - Object of properties and methods for a new class. Property names that are used internally and will be ignored by encapsulation: - __constructor - __parent If some of the object has "__defaults" object, then all of it's properties will be treated as an object of default properties that a new class should have. @param {Object | Function | Class | Array} [props.Encapsulate] - Define which object/function/class or an array of objects/functions/classes should be encapsulated into the new class @param {String} [props.__name = "Class"] - Specify the class name what will be visible near the variables during the debugging. @returns {Function} Class
[ "Main", "class", "builder", ".", "It", "takes", "the", "constructor", "function", "and", "wraps", "it", "to", "add", "few", "automated", "processes", "for", "constructing", "a", "new", "class", "." ]
b9f71c5a64eb023abca6d9d8f80c0c713d85e15d
https://github.com/valerii-zinchenko/class-wrapper/blob/b9f71c5a64eb023abca6d9d8f80c0c713d85e15d/lib/ClassBuilder.js#L50-L156
train
hmapjs/hmap-parser
index.js
function() { var block = this.emptyBlock(0); while ('eos' != this.peek().type) { if ('newline' == this.peek().type) { this.advance(); } else if ('text-html' == this.peek().type) { block.nodes = block.nodes.concat(this.parseTextHtml()); } else { var expr = this.parseExpr(); if (expr) block.nodes.push(expr); } } return block; }
javascript
function() { var block = this.emptyBlock(0); while ('eos' != this.peek().type) { if ('newline' == this.peek().type) { this.advance(); } else if ('text-html' == this.peek().type) { block.nodes = block.nodes.concat(this.parseTextHtml()); } else { var expr = this.parseExpr(); if (expr) block.nodes.push(expr); } } return block; }
[ "function", "(", ")", "{", "var", "block", "=", "this", ".", "emptyBlock", "(", "0", ")", ";", "while", "(", "'eos'", "!=", "this", ".", "peek", "(", ")", ".", "type", ")", "{", "if", "(", "'newline'", "==", "this", ".", "peek", "(", ")", ".", "type", ")", "{", "this", ".", "advance", "(", ")", ";", "}", "else", "if", "(", "'text-html'", "==", "this", ".", "peek", "(", ")", ".", "type", ")", "{", "block", ".", "nodes", "=", "block", ".", "nodes", ".", "concat", "(", "this", ".", "parseTextHtml", "(", ")", ")", ";", "}", "else", "{", "var", "expr", "=", "this", ".", "parseExpr", "(", ")", ";", "if", "(", "expr", ")", "block", ".", "nodes", ".", "push", "(", "expr", ")", ";", "}", "}", "return", "block", ";", "}" ]
Parse input returning a string of js for evaluation. @return {String} @api public
[ "Parse", "input", "returning", "a", "string", "of", "js", "for", "evaluation", "." ]
6d7f38dc66d95246c1f8f271ab88e858f17bd1f5
https://github.com/hmapjs/hmap-parser/blob/6d7f38dc66d95246c1f8f271ab88e858f17bd1f5/index.js#L103-L119
train
hmapjs/hmap-parser
index.js
function() { var tok = this.expect('filter'); var block, attrs = []; if (this.peek().type === 'start-attributes') { attrs = this.attrs(); } if (this.peek().type === 'text') { var textToken = this.advance(); block = this.initBlock(textToken.line, [ { type: 'Text', val: textToken.val, line: textToken.line, filename: this.filename } ]); } else if (this.peek().type === 'filter') { block = this.initBlock(tok.line, [this.parseFilter()]); } else { block = this.parseTextBlock() || this.emptyBlock(tok.line); } return { type: 'Filter', name: tok.val, block: block, attrs: attrs, line: tok.line, filename: this.filename }; }
javascript
function() { var tok = this.expect('filter'); var block, attrs = []; if (this.peek().type === 'start-attributes') { attrs = this.attrs(); } if (this.peek().type === 'text') { var textToken = this.advance(); block = this.initBlock(textToken.line, [ { type: 'Text', val: textToken.val, line: textToken.line, filename: this.filename } ]); } else if (this.peek().type === 'filter') { block = this.initBlock(tok.line, [this.parseFilter()]); } else { block = this.parseTextBlock() || this.emptyBlock(tok.line); } return { type: 'Filter', name: tok.val, block: block, attrs: attrs, line: tok.line, filename: this.filename }; }
[ "function", "(", ")", "{", "var", "tok", "=", "this", ".", "expect", "(", "'filter'", ")", ";", "var", "block", ",", "attrs", "=", "[", "]", ";", "if", "(", "this", ".", "peek", "(", ")", ".", "type", "===", "'start-attributes'", ")", "{", "attrs", "=", "this", ".", "attrs", "(", ")", ";", "}", "if", "(", "this", ".", "peek", "(", ")", ".", "type", "===", "'text'", ")", "{", "var", "textToken", "=", "this", ".", "advance", "(", ")", ";", "block", "=", "this", ".", "initBlock", "(", "textToken", ".", "line", ",", "[", "{", "type", ":", "'Text'", ",", "val", ":", "textToken", ".", "val", ",", "line", ":", "textToken", ".", "line", ",", "filename", ":", "this", ".", "filename", "}", "]", ")", ";", "}", "else", "if", "(", "this", ".", "peek", "(", ")", ".", "type", "===", "'filter'", ")", "{", "block", "=", "this", ".", "initBlock", "(", "tok", ".", "line", ",", "[", "this", ".", "parseFilter", "(", ")", "]", ")", ";", "}", "else", "{", "block", "=", "this", ".", "parseTextBlock", "(", ")", "||", "this", ".", "emptyBlock", "(", "tok", ".", "line", ")", ";", "}", "return", "{", "type", ":", "'Filter'", ",", "name", ":", "tok", ".", "val", ",", "block", ":", "block", ",", "attrs", ":", "attrs", ",", "line", ":", "tok", ".", "line", ",", "filename", ":", "this", ".", "filename", "}", ";", "}" ]
filter attrs? text-block
[ "filter", "attrs?", "text", "-", "block" ]
6d7f38dc66d95246c1f8f271ab88e858f17bd1f5
https://github.com/hmapjs/hmap-parser/blob/6d7f38dc66d95246c1f8f271ab88e858f17bd1f5/index.js#L645-L678
train
hmapjs/hmap-parser
index.js
function() { var tok = this.expect('block'); var node = 'indent' == this.peek().type ? this.block() : this.emptyBlock(tok.line); node.type = 'NamedBlock'; node.name = tok.val.trim(); node.mode = tok.mode; node.line = tok.line; return node; }
javascript
function() { var tok = this.expect('block'); var node = 'indent' == this.peek().type ? this.block() : this.emptyBlock(tok.line); node.type = 'NamedBlock'; node.name = tok.val.trim(); node.mode = tok.mode; node.line = tok.line; return node; }
[ "function", "(", ")", "{", "var", "tok", "=", "this", ".", "expect", "(", "'block'", ")", ";", "var", "node", "=", "'indent'", "==", "this", ".", "peek", "(", ")", ".", "type", "?", "this", ".", "block", "(", ")", ":", "this", ".", "emptyBlock", "(", "tok", ".", "line", ")", ";", "node", ".", "type", "=", "'NamedBlock'", ";", "node", ".", "name", "=", "tok", ".", "val", ".", "trim", "(", ")", ";", "node", ".", "mode", "=", "tok", ".", "mode", ";", "node", ".", "line", "=", "tok", ".", "line", ";", "return", "node", ";", "}" ]
'block' name block
[ "block", "name", "block" ]
6d7f38dc66d95246c1f8f271ab88e858f17bd1f5
https://github.com/hmapjs/hmap-parser/blob/6d7f38dc66d95246c1f8f271ab88e858f17bd1f5/index.js#L726-L738
train
fabioricali/stringme
index.js
Stringme
function Stringme(val, opt) { if (val === undefined) { val = '"undefined"'; } else if (val === null) { val = '"null"'; } else { var replace = opt && opt.replace ? opt.replace : null; var space = opt && opt.space ? opt.space : null; val = JSON.stringify(val, replace, space); } if (opt && opt.quotes === false && !/(^{|\[).*?([}\]])$/gm.test(val)) val = val.slice(1, val.length - 1); return val; }
javascript
function Stringme(val, opt) { if (val === undefined) { val = '"undefined"'; } else if (val === null) { val = '"null"'; } else { var replace = opt && opt.replace ? opt.replace : null; var space = opt && opt.space ? opt.space : null; val = JSON.stringify(val, replace, space); } if (opt && opt.quotes === false && !/(^{|\[).*?([}\]])$/gm.test(val)) val = val.slice(1, val.length - 1); return val; }
[ "function", "Stringme", "(", "val", ",", "opt", ")", "{", "if", "(", "val", "===", "undefined", ")", "{", "val", "=", "'\"undefined\"'", ";", "}", "else", "if", "(", "val", "===", "null", ")", "{", "val", "=", "'\"null\"'", ";", "}", "else", "{", "var", "replace", "=", "opt", "&&", "opt", ".", "replace", "?", "opt", ".", "replace", ":", "null", ";", "var", "space", "=", "opt", "&&", "opt", ".", "space", "?", "opt", ".", "space", ":", "null", ";", "val", "=", "JSON", ".", "stringify", "(", "val", ",", "replace", ",", "space", ")", ";", "}", "if", "(", "opt", "&&", "opt", ".", "quotes", "===", "false", "&&", "!", "/", "(^{|\\[).*?([}\\]])$", "/", "gm", ".", "test", "(", "val", ")", ")", "val", "=", "val", ".", "slice", "(", "1", ",", "val", ".", "length", "-", "1", ")", ";", "return", "val", ";", "}" ]
Convert also undefined and null to string @param {*} val Anything you want stringify @param {object} [opt] Options @param {boolean} [opt.quotes=true] If false remove quotes @param {function|array|string|number} [opt.replace=null] Replace (JSON.stringify 2# param) @param {number|string} [opt.space=0] Space (JSON.stringify 3# param) @link https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify @returns {string} @constructor
[ "Convert", "also", "undefined", "and", "null", "to", "string" ]
d14d51cdb4aa5f821e26ac29feeba7fc1e4ae868
https://github.com/fabioricali/stringme/blob/d14d51cdb4aa5f821e26ac29feeba7fc1e4ae868/index.js#L12-L28
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/filebrowser/plugin.js
ucFirst
function ucFirst( str ) { str += ''; var f = str.charAt( 0 ).toUpperCase(); return f + str.substr( 1 ); }
javascript
function ucFirst( str ) { str += ''; var f = str.charAt( 0 ).toUpperCase(); return f + str.substr( 1 ); }
[ "function", "ucFirst", "(", "str", ")", "{", "str", "+=", "''", ";", "var", "f", "=", "str", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", ";", "return", "f", "+", "str", ".", "substr", "(", "1", ")", ";", "}" ]
Make a string's first character uppercase. @param {String} str String.
[ "Make", "a", "string", "s", "first", "character", "uppercase", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/filebrowser/plugin.js#L140-L144
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/filebrowser/plugin.js
browseServer
function browseServer( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; var width = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowWidth' ] || editor.config.filebrowserWindowWidth || '80%'; var height = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowHeight' ] || editor.config.filebrowserWindowHeight || '70%'; var params = this.filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; var url = addQueryString( this.filebrowser.url, params ); // TODO: V4: Remove backward compatibility (#8163). editor.popup( url, width, height, editor.config.filebrowserWindowFeatures || editor.config.fileBrowserWindowFeatures ); }
javascript
function browseServer( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; var width = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowWidth' ] || editor.config.filebrowserWindowWidth || '80%'; var height = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowHeight' ] || editor.config.filebrowserWindowHeight || '70%'; var params = this.filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; var url = addQueryString( this.filebrowser.url, params ); // TODO: V4: Remove backward compatibility (#8163). editor.popup( url, width, height, editor.config.filebrowserWindowFeatures || editor.config.fileBrowserWindowFeatures ); }
[ "function", "browseServer", "(", "evt", ")", "{", "var", "dialog", "=", "this", ".", "getDialog", "(", ")", ";", "var", "editor", "=", "dialog", ".", "getParentEditor", "(", ")", ";", "editor", ".", "_", ".", "filebrowserSe", "=", "this", ";", "var", "width", "=", "editor", ".", "config", "[", "'filebrowser'", "+", "ucFirst", "(", "dialog", ".", "getName", "(", ")", ")", "+", "'WindowWidth'", "]", "||", "editor", ".", "config", ".", "filebrowserWindowWidth", "||", "'80%'", ";", "var", "height", "=", "editor", ".", "config", "[", "'filebrowser'", "+", "ucFirst", "(", "dialog", ".", "getName", "(", ")", ")", "+", "'WindowHeight'", "]", "||", "editor", ".", "config", ".", "filebrowserWindowHeight", "||", "'70%'", ";", "var", "params", "=", "this", ".", "filebrowser", ".", "params", "||", "{", "}", ";", "params", ".", "CKEditor", "=", "editor", ".", "name", ";", "params", ".", "CKEditorFuncNum", "=", "editor", ".", "_", ".", "filebrowserFn", ";", "if", "(", "!", "params", ".", "langCode", ")", "params", ".", "langCode", "=", "editor", ".", "langCode", ";", "var", "url", "=", "addQueryString", "(", "this", ".", "filebrowser", ".", "url", ",", "params", ")", ";", "editor", ".", "popup", "(", "url", ",", "width", ",", "height", ",", "editor", ".", "config", ".", "filebrowserWindowFeatures", "||", "editor", ".", "config", ".", "fileBrowserWindowFeatures", ")", ";", "}" ]
The onlick function assigned to the 'Browse Server' button. Opens the file browser and updates target field when file is selected. @param {CKEDITOR.event} evt The event object.
[ "The", "onlick", "function", "assigned", "to", "the", "Browse", "Server", "button", ".", "Opens", "the", "file", "browser", "and", "updates", "target", "field", "when", "file", "is", "selected", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/filebrowser/plugin.js#L151-L169
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/filebrowser/plugin.js
uploadFile
function uploadFile( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; // If user didn't select the file, stop the upload. if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getInputElement().$.value ) return false; if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getAction() ) return false; return true; }
javascript
function uploadFile( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; // If user didn't select the file, stop the upload. if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getInputElement().$.value ) return false; if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getAction() ) return false; return true; }
[ "function", "uploadFile", "(", "evt", ")", "{", "var", "dialog", "=", "this", ".", "getDialog", "(", ")", ";", "var", "editor", "=", "dialog", ".", "getParentEditor", "(", ")", ";", "editor", ".", "_", ".", "filebrowserSe", "=", "this", ";", "if", "(", "!", "dialog", ".", "getContentElement", "(", "this", "[", "'for'", "]", "[", "0", "]", ",", "this", "[", "'for'", "]", "[", "1", "]", ")", ".", "getInputElement", "(", ")", ".", "$", ".", "value", ")", "return", "false", ";", "if", "(", "!", "dialog", ".", "getContentElement", "(", "this", "[", "'for'", "]", "[", "0", "]", ",", "this", "[", "'for'", "]", "[", "1", "]", ")", ".", "getAction", "(", ")", ")", "return", "false", ";", "return", "true", ";", "}" ]
The onlick function assigned to the 'Upload' button. Makes the final decision whether form is really submitted and updates target field when file is uploaded. @param {CKEDITOR.event} evt The event object.
[ "The", "onlick", "function", "assigned", "to", "the", "Upload", "button", ".", "Makes", "the", "final", "decision", "whether", "form", "is", "really", "submitted", "and", "updates", "target", "field", "when", "file", "is", "uploaded", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/filebrowser/plugin.js#L177-L191
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/filebrowser/plugin.js
setupFileElement
function setupFileElement( editor, fileInput, filebrowser ) { var params = filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; fileInput.action = addQueryString( filebrowser.url, params ); fileInput.filebrowser = filebrowser; }
javascript
function setupFileElement( editor, fileInput, filebrowser ) { var params = filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; fileInput.action = addQueryString( filebrowser.url, params ); fileInput.filebrowser = filebrowser; }
[ "function", "setupFileElement", "(", "editor", ",", "fileInput", ",", "filebrowser", ")", "{", "var", "params", "=", "filebrowser", ".", "params", "||", "{", "}", ";", "params", ".", "CKEditor", "=", "editor", ".", "name", ";", "params", ".", "CKEditorFuncNum", "=", "editor", ".", "_", ".", "filebrowserFn", ";", "if", "(", "!", "params", ".", "langCode", ")", "params", ".", "langCode", "=", "editor", ".", "langCode", ";", "fileInput", ".", "action", "=", "addQueryString", "(", "filebrowser", ".", "url", ",", "params", ")", ";", "fileInput", ".", "filebrowser", "=", "filebrowser", ";", "}" ]
Setups the file element. @param {CKEDITOR.ui.dialog.file} fileInput The file element used during file upload. @param {Object} filebrowser Object containing filebrowser settings assigned to the fileButton associated with this file element.
[ "Setups", "the", "file", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/filebrowser/plugin.js#L200-L209
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/filebrowser/plugin.js
attachFileBrowser
function attachFileBrowser( editor, dialogName, definition, elements ) { if ( !elements || !elements.length ) return; var element, fileInput; for ( var i = elements.length; i--; ) { element = elements[ i ]; if ( element.type == 'hbox' || element.type == 'vbox' || element.type == 'fieldset' ) attachFileBrowser( editor, dialogName, definition, element.children ); if ( !element.filebrowser ) continue; if ( typeof element.filebrowser == 'string' ) { var fb = { action: ( element.type == 'fileButton' ) ? 'QuickUpload' : 'Browse', target: element.filebrowser }; element.filebrowser = fb; } if ( element.filebrowser.action == 'Browse' ) { var url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'BrowseUrl' ]; if ( url === undefined ) url = editor.config.filebrowserBrowseUrl; } if ( url ) { element.onClick = browseServer; element.filebrowser.url = url; element.hidden = false; } } else if ( element.filebrowser.action == 'QuickUpload' && element[ 'for' ] ) { url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'UploadUrl' ]; if ( url === undefined ) url = editor.config.filebrowserUploadUrl; } if ( url ) { var onClick = element.onClick; element.onClick = function( evt ) { // "element" here means the definition object, so we need to find the correct // button to scope the event call var sender = evt.sender; if ( onClick && onClick.call( sender, evt ) === false ) return false; return uploadFile.call( sender, evt ); }; element.filebrowser.url = url; element.hidden = false; setupFileElement( editor, definition.getContents( element[ 'for' ][ 0 ] ).get( element[ 'for' ][ 1 ] ), element.filebrowser ); } } } }
javascript
function attachFileBrowser( editor, dialogName, definition, elements ) { if ( !elements || !elements.length ) return; var element, fileInput; for ( var i = elements.length; i--; ) { element = elements[ i ]; if ( element.type == 'hbox' || element.type == 'vbox' || element.type == 'fieldset' ) attachFileBrowser( editor, dialogName, definition, element.children ); if ( !element.filebrowser ) continue; if ( typeof element.filebrowser == 'string' ) { var fb = { action: ( element.type == 'fileButton' ) ? 'QuickUpload' : 'Browse', target: element.filebrowser }; element.filebrowser = fb; } if ( element.filebrowser.action == 'Browse' ) { var url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'BrowseUrl' ]; if ( url === undefined ) url = editor.config.filebrowserBrowseUrl; } if ( url ) { element.onClick = browseServer; element.filebrowser.url = url; element.hidden = false; } } else if ( element.filebrowser.action == 'QuickUpload' && element[ 'for' ] ) { url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'UploadUrl' ]; if ( url === undefined ) url = editor.config.filebrowserUploadUrl; } if ( url ) { var onClick = element.onClick; element.onClick = function( evt ) { // "element" here means the definition object, so we need to find the correct // button to scope the event call var sender = evt.sender; if ( onClick && onClick.call( sender, evt ) === false ) return false; return uploadFile.call( sender, evt ); }; element.filebrowser.url = url; element.hidden = false; setupFileElement( editor, definition.getContents( element[ 'for' ][ 0 ] ).get( element[ 'for' ][ 1 ] ), element.filebrowser ); } } } }
[ "function", "attachFileBrowser", "(", "editor", ",", "dialogName", ",", "definition", ",", "elements", ")", "{", "if", "(", "!", "elements", "||", "!", "elements", ".", "length", ")", "return", ";", "var", "element", ",", "fileInput", ";", "for", "(", "var", "i", "=", "elements", ".", "length", ";", "i", "--", ";", ")", "{", "element", "=", "elements", "[", "i", "]", ";", "if", "(", "element", ".", "type", "==", "'hbox'", "||", "element", ".", "type", "==", "'vbox'", "||", "element", ".", "type", "==", "'fieldset'", ")", "attachFileBrowser", "(", "editor", ",", "dialogName", ",", "definition", ",", "element", ".", "children", ")", ";", "if", "(", "!", "element", ".", "filebrowser", ")", "continue", ";", "if", "(", "typeof", "element", ".", "filebrowser", "==", "'string'", ")", "{", "var", "fb", "=", "{", "action", ":", "(", "element", ".", "type", "==", "'fileButton'", ")", "?", "'QuickUpload'", ":", "'Browse'", ",", "target", ":", "element", ".", "filebrowser", "}", ";", "element", ".", "filebrowser", "=", "fb", ";", "}", "if", "(", "element", ".", "filebrowser", ".", "action", "==", "'Browse'", ")", "{", "var", "url", "=", "element", ".", "filebrowser", ".", "url", ";", "if", "(", "url", "===", "undefined", ")", "{", "url", "=", "editor", ".", "config", "[", "'filebrowser'", "+", "ucFirst", "(", "dialogName", ")", "+", "'BrowseUrl'", "]", ";", "if", "(", "url", "===", "undefined", ")", "url", "=", "editor", ".", "config", ".", "filebrowserBrowseUrl", ";", "}", "if", "(", "url", ")", "{", "element", ".", "onClick", "=", "browseServer", ";", "element", ".", "filebrowser", ".", "url", "=", "url", ";", "element", ".", "hidden", "=", "false", ";", "}", "}", "else", "if", "(", "element", ".", "filebrowser", ".", "action", "==", "'QuickUpload'", "&&", "element", "[", "'for'", "]", ")", "{", "url", "=", "element", ".", "filebrowser", ".", "url", ";", "if", "(", "url", "===", "undefined", ")", "{", "url", "=", "editor", ".", "config", "[", "'filebrowser'", "+", "ucFirst", "(", "dialogName", ")", "+", "'UploadUrl'", "]", ";", "if", "(", "url", "===", "undefined", ")", "url", "=", "editor", ".", "config", ".", "filebrowserUploadUrl", ";", "}", "if", "(", "url", ")", "{", "var", "onClick", "=", "element", ".", "onClick", ";", "element", ".", "onClick", "=", "function", "(", "evt", ")", "{", "var", "sender", "=", "evt", ".", "sender", ";", "if", "(", "onClick", "&&", "onClick", ".", "call", "(", "sender", ",", "evt", ")", "===", "false", ")", "return", "false", ";", "return", "uploadFile", ".", "call", "(", "sender", ",", "evt", ")", ";", "}", ";", "element", ".", "filebrowser", ".", "url", "=", "url", ";", "element", ".", "hidden", "=", "false", ";", "setupFileElement", "(", "editor", ",", "definition", ".", "getContents", "(", "element", "[", "'for'", "]", "[", "0", "]", ")", ".", "get", "(", "element", "[", "'for'", "]", "[", "1", "]", ")", ",", "element", ".", "filebrowser", ")", ";", "}", "}", "}", "}" ]
Traverse through the content definition and attach filebrowser to elements with 'filebrowser' attribute. @param String dialogName Dialog name. @param {CKEDITOR.dialog.definitionObject} definition Dialog definition. @param {Array} elements Array of {@link CKEDITOR.dialog.definition.content} objects.
[ "Traverse", "through", "the", "content", "definition", "and", "attach", "filebrowser", "to", "elements", "with", "filebrowser", "attribute", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/filebrowser/plugin.js#L221-L283
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/filebrowser/plugin.js
isConfigured
function isConfigured( definition, tabId, elementId ) { if ( elementId.indexOf( ";" ) !== -1 ) { var ids = elementId.split( ";" ); for ( var i = 0; i < ids.length; i++ ) { if ( isConfigured( definition, tabId, ids[ i ] ) ) return true; } return false; } var elementFileBrowser = definition.getContents( tabId ).get( elementId ).filebrowser; return ( elementFileBrowser && elementFileBrowser.url ); }
javascript
function isConfigured( definition, tabId, elementId ) { if ( elementId.indexOf( ";" ) !== -1 ) { var ids = elementId.split( ";" ); for ( var i = 0; i < ids.length; i++ ) { if ( isConfigured( definition, tabId, ids[ i ] ) ) return true; } return false; } var elementFileBrowser = definition.getContents( tabId ).get( elementId ).filebrowser; return ( elementFileBrowser && elementFileBrowser.url ); }
[ "function", "isConfigured", "(", "definition", ",", "tabId", ",", "elementId", ")", "{", "if", "(", "elementId", ".", "indexOf", "(", "\";\"", ")", "!==", "-", "1", ")", "{", "var", "ids", "=", "elementId", ".", "split", "(", "\";\"", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ids", ".", "length", ";", "i", "++", ")", "{", "if", "(", "isConfigured", "(", "definition", ",", "tabId", ",", "ids", "[", "i", "]", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}", "var", "elementFileBrowser", "=", "definition", ".", "getContents", "(", "tabId", ")", ".", "get", "(", "elementId", ")", ".", "filebrowser", ";", "return", "(", "elementFileBrowser", "&&", "elementFileBrowser", ".", "url", ")", ";", "}" ]
Returns true if filebrowser is configured in one of the elements. @param {CKEDITOR.dialog.definitionObject} definition Dialog definition. @param String tabId The tab id where element(s) can be found. @param String elementId The element id (or ids, separated with a semicolon) to check.
[ "Returns", "true", "if", "filebrowser", "is", "configured", "in", "one", "of", "the", "elements", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/filebrowser/plugin.js#L312-L324
train
pvorb/node-confdir
confdir.js
findDirRec
function findDirRec(dir, callback) { var result = path.resolve(dir, dirmod); fs.stat(result, function stat(err, stat) { if (err || !stat.isDirectory()) { if (lastResult == result) { callback(new Error('No configuration directory found.')); return; } lastResult = result; findDirRec(path.resolve(dir, '..'), callback); } else { callback(null, result); } }); }
javascript
function findDirRec(dir, callback) { var result = path.resolve(dir, dirmod); fs.stat(result, function stat(err, stat) { if (err || !stat.isDirectory()) { if (lastResult == result) { callback(new Error('No configuration directory found.')); return; } lastResult = result; findDirRec(path.resolve(dir, '..'), callback); } else { callback(null, result); } }); }
[ "function", "findDirRec", "(", "dir", ",", "callback", ")", "{", "var", "result", "=", "path", ".", "resolve", "(", "dir", ",", "dirmod", ")", ";", "fs", ".", "stat", "(", "result", ",", "function", "stat", "(", "err", ",", "stat", ")", "{", "if", "(", "err", "||", "!", "stat", ".", "isDirectory", "(", ")", ")", "{", "if", "(", "lastResult", "==", "result", ")", "{", "callback", "(", "new", "Error", "(", "'No configuration directory found.'", ")", ")", ";", "return", ";", "}", "lastResult", "=", "result", ";", "findDirRec", "(", "path", ".", "resolve", "(", "dir", ",", "'..'", ")", ",", "callback", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "result", ")", ";", "}", "}", ")", ";", "}" ]
find dirname by recursively walking up the path hierarchy
[ "find", "dirname", "by", "recursively", "walking", "up", "the", "path", "hierarchy" ]
11464820356ea1878b63733f80e923edc7db9d72
https://github.com/pvorb/node-confdir/blob/11464820356ea1878b63733f80e923edc7db9d72/confdir.js#L16-L30
train
airbrite/muni
mongo.js
function(obj) { _.forEach(obj, function(val, key) { if (_.isString(val)) { if (Mixins.isObjectId(val)) { obj[key] = Mixins.newObjectId(val); } else if (Mixins.isValidISO8601String(val)) { obj[key] = new Date(val); } } else if (_.isDate(val)) { obj[key] = val; } else if (_.isObject(val)) { if (val['$oid']) { obj[key] = val['$oid']; } else { obj[key] = this.cast(val); } } }.bind(this)); return obj; }
javascript
function(obj) { _.forEach(obj, function(val, key) { if (_.isString(val)) { if (Mixins.isObjectId(val)) { obj[key] = Mixins.newObjectId(val); } else if (Mixins.isValidISO8601String(val)) { obj[key] = new Date(val); } } else if (_.isDate(val)) { obj[key] = val; } else if (_.isObject(val)) { if (val['$oid']) { obj[key] = val['$oid']; } else { obj[key] = this.cast(val); } } }.bind(this)); return obj; }
[ "function", "(", "obj", ")", "{", "_", ".", "forEach", "(", "obj", ",", "function", "(", "val", ",", "key", ")", "{", "if", "(", "_", ".", "isString", "(", "val", ")", ")", "{", "if", "(", "Mixins", ".", "isObjectId", "(", "val", ")", ")", "{", "obj", "[", "key", "]", "=", "Mixins", ".", "newObjectId", "(", "val", ")", ";", "}", "else", "if", "(", "Mixins", ".", "isValidISO8601String", "(", "val", ")", ")", "{", "obj", "[", "key", "]", "=", "new", "Date", "(", "val", ")", ";", "}", "}", "else", "if", "(", "_", ".", "isDate", "(", "val", ")", ")", "{", "obj", "[", "key", "]", "=", "val", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "val", ")", ")", "{", "if", "(", "val", "[", "'$oid'", "]", ")", "{", "obj", "[", "key", "]", "=", "val", "[", "'$oid'", "]", ";", "}", "else", "{", "obj", "[", "key", "]", "=", "this", ".", "cast", "(", "val", ")", ";", "}", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "return", "obj", ";", "}" ]
Automatically cast to HexString to ObjectId Automatically cast ISO8601 date strings to Javascript Date Will mutate the original object obj can be an object or an array
[ "Automatically", "cast", "to", "HexString", "to", "ObjectId", "Automatically", "cast", "ISO8601", "date", "strings", "to", "Javascript", "Date", "Will", "mutate", "the", "original", "object", "obj", "can", "be", "an", "object", "or", "an", "array" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/mongo.js#L117-L137
train
airbrite/muni
mongo.js
function(obj) { _.forEach(obj, function(val, key) { if (val && _.isFunction(val.toHexString)) { obj[key] = val.toHexString(); } else if (_.isDate(val)) { obj[key] = val; } else if (_.isObject(val)) { if (val['$oid']) { obj[key] = val['$oid']; } else { obj[key] = this.uncast(val); } } }.bind(this)); return obj; }
javascript
function(obj) { _.forEach(obj, function(val, key) { if (val && _.isFunction(val.toHexString)) { obj[key] = val.toHexString(); } else if (_.isDate(val)) { obj[key] = val; } else if (_.isObject(val)) { if (val['$oid']) { obj[key] = val['$oid']; } else { obj[key] = this.uncast(val); } } }.bind(this)); return obj; }
[ "function", "(", "obj", ")", "{", "_", ".", "forEach", "(", "obj", ",", "function", "(", "val", ",", "key", ")", "{", "if", "(", "val", "&&", "_", ".", "isFunction", "(", "val", ".", "toHexString", ")", ")", "{", "obj", "[", "key", "]", "=", "val", ".", "toHexString", "(", ")", ";", "}", "else", "if", "(", "_", ".", "isDate", "(", "val", ")", ")", "{", "obj", "[", "key", "]", "=", "val", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "val", ")", ")", "{", "if", "(", "val", "[", "'$oid'", "]", ")", "{", "obj", "[", "key", "]", "=", "val", "[", "'$oid'", "]", ";", "}", "else", "{", "obj", "[", "key", "]", "=", "this", ".", "uncast", "(", "val", ")", ";", "}", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "return", "obj", ";", "}" ]
Automatically uncast ObjectId to HexString Will mutate the original object obj can be an object or an array
[ "Automatically", "uncast", "ObjectId", "to", "HexString", "Will", "mutate", "the", "original", "object", "obj", "can", "be", "an", "object", "or", "an", "array" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/mongo.js#L142-L158
train
bocallaghan/JADS
objects/jads_directory.js
function (requestURL, filename, fileType) { if (gc.coreFunctions.getReqestExtension(filename) == '.ipa'){ // The template of an entry as well as the indicator variable for a file or dir. // This is used for IPA files that need to be installed on iOS devices so .manifest is appended to search for the appropriate manifest. var listingEntry = '<tr><td>{itemType}</td><td><a href="itms-services://?action=download-manifest&url={hrefLink}.plist">{itemName}</a></td></tr>\n'; // Populate the template now using the placeholders as text to be replaced. listingEntry = listingEntry.replace('{itemType}', "iOS"); listingEntry = listingEntry.replace('{hrefLink}', gc.coreFunctions.joinPaths(requestURL, filename)); listingEntry = listingEntry.replace('{itemName}', filename); } else { // The template of an entry as well as the indicator variable for a file or dir. var listingEntry = '<tr><td>{itemType}</td><td><a href="{hrefLink}">{itemName}</a></td></tr>\n'; // Populate the template now using the placeholders as text to be replaced. listingEntry = listingEntry.replace('{itemType}', fileType); listingEntry = listingEntry.replace('{hrefLink}', gc.coreFunctions.joinPaths(requestURL, filename)); listingEntry = listingEntry.replace('{itemName}', filename); } // Return the entry. return listingEntry; }
javascript
function (requestURL, filename, fileType) { if (gc.coreFunctions.getReqestExtension(filename) == '.ipa'){ // The template of an entry as well as the indicator variable for a file or dir. // This is used for IPA files that need to be installed on iOS devices so .manifest is appended to search for the appropriate manifest. var listingEntry = '<tr><td>{itemType}</td><td><a href="itms-services://?action=download-manifest&url={hrefLink}.plist">{itemName}</a></td></tr>\n'; // Populate the template now using the placeholders as text to be replaced. listingEntry = listingEntry.replace('{itemType}', "iOS"); listingEntry = listingEntry.replace('{hrefLink}', gc.coreFunctions.joinPaths(requestURL, filename)); listingEntry = listingEntry.replace('{itemName}', filename); } else { // The template of an entry as well as the indicator variable for a file or dir. var listingEntry = '<tr><td>{itemType}</td><td><a href="{hrefLink}">{itemName}</a></td></tr>\n'; // Populate the template now using the placeholders as text to be replaced. listingEntry = listingEntry.replace('{itemType}', fileType); listingEntry = listingEntry.replace('{hrefLink}', gc.coreFunctions.joinPaths(requestURL, filename)); listingEntry = listingEntry.replace('{itemName}', filename); } // Return the entry. return listingEntry; }
[ "function", "(", "requestURL", ",", "filename", ",", "fileType", ")", "{", "if", "(", "gc", ".", "coreFunctions", ".", "getReqestExtension", "(", "filename", ")", "==", "'.ipa'", ")", "{", "var", "listingEntry", "=", "'<tr><td>{itemType}</td><td><a href=\"itms-services://?action=download-manifest&url={hrefLink}.plist\">{itemName}</a></td></tr>\\n'", ";", "\\n", "listingEntry", "=", "listingEntry", ".", "replace", "(", "'{itemType}'", ",", "\"iOS\"", ")", ";", "listingEntry", "=", "listingEntry", ".", "replace", "(", "'{hrefLink}'", ",", "gc", ".", "coreFunctions", ".", "joinPaths", "(", "requestURL", ",", "filename", ")", ")", ";", "}", "else", "listingEntry", "=", "listingEntry", ".", "replace", "(", "'{itemName}'", ",", "filename", ")", ";", "{", "var", "listingEntry", "=", "'<tr><td>{itemType}</td><td><a href=\"{hrefLink}\">{itemName}</a></td></tr>\\n'", ";", "\\n", "listingEntry", "=", "listingEntry", ".", "replace", "(", "'{itemType}'", ",", "fileType", ")", ";", "listingEntry", "=", "listingEntry", ".", "replace", "(", "'{hrefLink}'", ",", "gc", ".", "coreFunctions", ".", "joinPaths", "(", "requestURL", ",", "filename", ")", ")", ";", "}", "}" ]
Node file system object. Formats an entry for the directory listing based on whether its a file or dir.
[ "Node", "file", "system", "object", ".", "Formats", "an", "entry", "for", "the", "directory", "listing", "based", "on", "whether", "its", "a", "file", "or", "dir", "." ]
fb022d86138998d9d7fd22bb2148989e6ec7b981
https://github.com/bocallaghan/JADS/blob/fb022d86138998d9d7fd22bb2148989e6ec7b981/objects/jads_directory.js#L6-L30
train
welefen/thinkit
src/index.js
Class
function Class(superCtor, props){ let cls = function (...args) { if (!(this instanceof cls)) { throw new Error('Class constructors cannot be invoked without \'new\''); } //extend prototype data to instance //avoid instance change data to pullte prototype cls.extend(cls.__props__, this); if(isFunction(this.init)){ this.__initReturn = this.init(...args); } }; cls.__props__ = {}; cls.extend = function(props, target){ target = target || cls.prototype; let name, value; for(name in props){ value = props[name]; if (isArray(value)) { cls.__props__[name] = target[name] = extend([], value); }else if(isObject(value)){ cls.__props__[name] = target[name] = extend({}, value); }else{ target[name] = value; } } return cls; }; cls.inherits = function(superCtor){ cls.super_ = superCtor; //if superCtor.prototype is not enumerable if(Object.keys(superCtor.prototype).length === 0){ cls.prototype = Object.create(superCtor.prototype, { constructor: { value: cls, enumerable: false, writable: true, configurable: true } }); }else{ extend(cls.prototype, superCtor.prototype); } return cls; }; if (!isFunction(superCtor)) { props = superCtor; }else if (isFunction(superCtor)) { cls.inherits(superCtor); } if (props) { cls.extend(props); } /** * invoke super class method * @param {String} name [] * @param {Mixed} data [] * @return {Mixed} [] */ cls.prototype.super = function(name, data){ if (!this[name]) { this.super_c = null; return; } let super_ = this.super_c ? this.super_c.super_ : this.constructor.super_; if (!super_ || !isFunction(super_.prototype[name])) { this.super_c = null; return; } while(this[name] === super_.prototype[name] && super_.super_){ super_ = super_.super_; } this.super_c = super_; if (!this.super_t) { this.super_t = 1; } if (!isArray(data) && !isArguments(data)) { data = arguments.length === 1 ? [] : [data]; } let t = ++this.super_t, ret, method = super_.prototype[name]; ret = method.apply(this, data); if (t === this.super_t) { this.super_c = null; this.super_t = 0; } return ret; }; return cls; }
javascript
function Class(superCtor, props){ let cls = function (...args) { if (!(this instanceof cls)) { throw new Error('Class constructors cannot be invoked without \'new\''); } //extend prototype data to instance //avoid instance change data to pullte prototype cls.extend(cls.__props__, this); if(isFunction(this.init)){ this.__initReturn = this.init(...args); } }; cls.__props__ = {}; cls.extend = function(props, target){ target = target || cls.prototype; let name, value; for(name in props){ value = props[name]; if (isArray(value)) { cls.__props__[name] = target[name] = extend([], value); }else if(isObject(value)){ cls.__props__[name] = target[name] = extend({}, value); }else{ target[name] = value; } } return cls; }; cls.inherits = function(superCtor){ cls.super_ = superCtor; //if superCtor.prototype is not enumerable if(Object.keys(superCtor.prototype).length === 0){ cls.prototype = Object.create(superCtor.prototype, { constructor: { value: cls, enumerable: false, writable: true, configurable: true } }); }else{ extend(cls.prototype, superCtor.prototype); } return cls; }; if (!isFunction(superCtor)) { props = superCtor; }else if (isFunction(superCtor)) { cls.inherits(superCtor); } if (props) { cls.extend(props); } /** * invoke super class method * @param {String} name [] * @param {Mixed} data [] * @return {Mixed} [] */ cls.prototype.super = function(name, data){ if (!this[name]) { this.super_c = null; return; } let super_ = this.super_c ? this.super_c.super_ : this.constructor.super_; if (!super_ || !isFunction(super_.prototype[name])) { this.super_c = null; return; } while(this[name] === super_.prototype[name] && super_.super_){ super_ = super_.super_; } this.super_c = super_; if (!this.super_t) { this.super_t = 1; } if (!isArray(data) && !isArguments(data)) { data = arguments.length === 1 ? [] : [data]; } let t = ++this.super_t, ret, method = super_.prototype[name]; ret = method.apply(this, data); if (t === this.super_t) { this.super_c = null; this.super_t = 0; } return ret; }; return cls; }
[ "function", "Class", "(", "superCtor", ",", "props", ")", "{", "let", "cls", "=", "function", "(", "...", "args", ")", "{", "if", "(", "!", "(", "this", "instanceof", "cls", ")", ")", "{", "throw", "new", "Error", "(", "'Class constructors cannot be invoked without \\'new\\''", ")", ";", "}", "\\'", "\\'", "}", ";", "cls", ".", "extend", "(", "cls", ".", "__props__", ",", "this", ")", ";", "if", "(", "isFunction", "(", "this", ".", "init", ")", ")", "{", "this", ".", "__initReturn", "=", "this", ".", "init", "(", "...", "args", ")", ";", "}", "cls", ".", "__props__", "=", "{", "}", ";", "cls", ".", "extend", "=", "function", "(", "props", ",", "target", ")", "{", "target", "=", "target", "||", "cls", ".", "prototype", ";", "let", "name", ",", "value", ";", "for", "(", "name", "in", "props", ")", "{", "value", "=", "props", "[", "name", "]", ";", "if", "(", "isArray", "(", "value", ")", ")", "{", "cls", ".", "__props__", "[", "name", "]", "=", "target", "[", "name", "]", "=", "extend", "(", "[", "]", ",", "value", ")", ";", "}", "else", "if", "(", "isObject", "(", "value", ")", ")", "{", "cls", ".", "__props__", "[", "name", "]", "=", "target", "[", "name", "]", "=", "extend", "(", "{", "}", ",", "value", ")", ";", "}", "else", "{", "target", "[", "name", "]", "=", "value", ";", "}", "}", "return", "cls", ";", "}", ";", "cls", ".", "inherits", "=", "function", "(", "superCtor", ")", "{", "cls", ".", "super_", "=", "superCtor", ";", "if", "(", "Object", ".", "keys", "(", "superCtor", ".", "prototype", ")", ".", "length", "===", "0", ")", "{", "cls", ".", "prototype", "=", "Object", ".", "create", "(", "superCtor", ".", "prototype", ",", "{", "constructor", ":", "{", "value", ":", "cls", ",", "enumerable", ":", "false", ",", "writable", ":", "true", ",", "configurable", ":", "true", "}", "}", ")", ";", "}", "else", "{", "extend", "(", "cls", ".", "prototype", ",", "superCtor", ".", "prototype", ")", ";", "}", "return", "cls", ";", "}", ";", "if", "(", "!", "isFunction", "(", "superCtor", ")", ")", "{", "props", "=", "superCtor", ";", "}", "else", "if", "(", "isFunction", "(", "superCtor", ")", ")", "{", "cls", ".", "inherits", "(", "superCtor", ")", ";", "}", "if", "(", "props", ")", "{", "cls", ".", "extend", "(", "props", ")", ";", "}", "}" ]
create Class in javascript @param {Function} superCtor [super constructor] @param {Object} props []
[ "create", "Class", "in", "javascript" ]
7f4096c7ae744eadb055daba9d9a6b0312bc6177
https://github.com/welefen/thinkit/blob/7f4096c7ae744eadb055daba9d9a6b0312bc6177/src/index.js#L55-L143
train
byu-oit/fully-typed
bin/array.js
TypedArray
function TypedArray (config) { const array = this; // validate min items if (config.hasOwnProperty('minItems') && (!util.isInteger(config.minItems) || config.minItems < 0)) { throw Error('Invalid configuration value for property: minItems. Must be an integer that is greater than or equal to zero. Received: ' + config.minItems); } const minItems = config.hasOwnProperty('minItems') ? config.minItems : 0; // validate max items if (config.hasOwnProperty('maxItems') && (!util.isInteger(config.maxItems) || config.maxItems < minItems)) { throw Error('Invalid configuration value for property: maxItems. Must be an integer that is greater than or equal to the minItems. Received: ' + config.maxItems); } // validate schema if (config.hasOwnProperty('schema')) config.schema = FullyTyped(config.schema); // define properties Object.defineProperties(array, { maxItems: { /** * @property * @name TypedArray#maxItems * @type {number} */ value: Math.round(config.maxItems), writable: false }, minItems: { /** * @property * @name TypedArray#minItems * @type {number} */ value: Math.round(config.minItems), writable: false }, schema: { /** * @property * @name TypedArray#schema * @type {object} */ value: config.schema, writable: false }, uniqueItems: { /** * @property * @name TypedArray#uniqueItems * @type {boolean} */ value: !!config.uniqueItems, writable: false } }); return array; }
javascript
function TypedArray (config) { const array = this; // validate min items if (config.hasOwnProperty('minItems') && (!util.isInteger(config.minItems) || config.minItems < 0)) { throw Error('Invalid configuration value for property: minItems. Must be an integer that is greater than or equal to zero. Received: ' + config.minItems); } const minItems = config.hasOwnProperty('minItems') ? config.minItems : 0; // validate max items if (config.hasOwnProperty('maxItems') && (!util.isInteger(config.maxItems) || config.maxItems < minItems)) { throw Error('Invalid configuration value for property: maxItems. Must be an integer that is greater than or equal to the minItems. Received: ' + config.maxItems); } // validate schema if (config.hasOwnProperty('schema')) config.schema = FullyTyped(config.schema); // define properties Object.defineProperties(array, { maxItems: { /** * @property * @name TypedArray#maxItems * @type {number} */ value: Math.round(config.maxItems), writable: false }, minItems: { /** * @property * @name TypedArray#minItems * @type {number} */ value: Math.round(config.minItems), writable: false }, schema: { /** * @property * @name TypedArray#schema * @type {object} */ value: config.schema, writable: false }, uniqueItems: { /** * @property * @name TypedArray#uniqueItems * @type {boolean} */ value: !!config.uniqueItems, writable: false } }); return array; }
[ "function", "TypedArray", "(", "config", ")", "{", "const", "array", "=", "this", ";", "if", "(", "config", ".", "hasOwnProperty", "(", "'minItems'", ")", "&&", "(", "!", "util", ".", "isInteger", "(", "config", ".", "minItems", ")", "||", "config", ".", "minItems", "<", "0", ")", ")", "{", "throw", "Error", "(", "'Invalid configuration value for property: minItems. Must be an integer that is greater than or equal to zero. Received: '", "+", "config", ".", "minItems", ")", ";", "}", "const", "minItems", "=", "config", ".", "hasOwnProperty", "(", "'minItems'", ")", "?", "config", ".", "minItems", ":", "0", ";", "if", "(", "config", ".", "hasOwnProperty", "(", "'maxItems'", ")", "&&", "(", "!", "util", ".", "isInteger", "(", "config", ".", "maxItems", ")", "||", "config", ".", "maxItems", "<", "minItems", ")", ")", "{", "throw", "Error", "(", "'Invalid configuration value for property: maxItems. Must be an integer that is greater than or equal to the minItems. Received: '", "+", "config", ".", "maxItems", ")", ";", "}", "if", "(", "config", ".", "hasOwnProperty", "(", "'schema'", ")", ")", "config", ".", "schema", "=", "FullyTyped", "(", "config", ".", "schema", ")", ";", "Object", ".", "defineProperties", "(", "array", ",", "{", "maxItems", ":", "{", "value", ":", "Math", ".", "round", "(", "config", ".", "maxItems", ")", ",", "writable", ":", "false", "}", ",", "minItems", ":", "{", "value", ":", "Math", ".", "round", "(", "config", ".", "minItems", ")", ",", "writable", ":", "false", "}", ",", "schema", ":", "{", "value", ":", "config", ".", "schema", ",", "writable", ":", "false", "}", ",", "uniqueItems", ":", "{", "value", ":", "!", "!", "config", ".", "uniqueItems", ",", "writable", ":", "false", "}", "}", ")", ";", "return", "array", ";", "}" ]
Create a TypedArray instance. @param {object} config @returns {TypedArray} @augments Typed @constructor
[ "Create", "a", "TypedArray", "instance", "." ]
ed6b3ed88ffc72990acffb765232eaaee261afef
https://github.com/byu-oit/fully-typed/blob/ed6b3ed88ffc72990acffb765232eaaee261afef/bin/array.js#L30-L93
train
jurca/szn-options
szn-options.js
registerOptionsObserver
function registerOptionsObserver(instance) { if (!instance._mounted || !instance._options) { return } instance._observer.observe(instance._options, { childList: true, attributes: true, characterData: true, subtree: true, attributeFilter: ['disabled', 'label', 'selected', 'title', 'multiple'], }) }
javascript
function registerOptionsObserver(instance) { if (!instance._mounted || !instance._options) { return } instance._observer.observe(instance._options, { childList: true, attributes: true, characterData: true, subtree: true, attributeFilter: ['disabled', 'label', 'selected', 'title', 'multiple'], }) }
[ "function", "registerOptionsObserver", "(", "instance", ")", "{", "if", "(", "!", "instance", ".", "_mounted", "||", "!", "instance", ".", "_options", ")", "{", "return", "}", "instance", ".", "_observer", ".", "observe", "(", "instance", ".", "_options", ",", "{", "childList", ":", "true", ",", "attributes", ":", "true", ",", "characterData", ":", "true", ",", "subtree", ":", "true", ",", "attributeFilter", ":", "[", "'disabled'", ",", "'label'", ",", "'selected'", ",", "'title'", ",", "'multiple'", "]", ",", "}", ")", "}" ]
Registers the provided szn-options element's DOM mutation observer to observe the related options for changes. @param {SznElements.SznOptions} instance The szn-options element instance.
[ "Registers", "the", "provided", "szn", "-", "options", "element", "s", "DOM", "mutation", "observer", "to", "observe", "the", "related", "options", "for", "changes", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L157-L169
train
jurca/szn-options
szn-options.js
addEventListeners
function addEventListeners(instance) { if (!instance._mounted || !instance._options) { return } instance._options.addEventListener('change', instance._onSelectionChange) instance._root.addEventListener('mouseover', instance._onItemHovered) instance._root.addEventListener('mousedown', instance._onItemSelectionStart) instance._root.addEventListener('mouseup', instance._onItemClicked) addEventListener('mouseup', instance._onSelectionEnd) }
javascript
function addEventListeners(instance) { if (!instance._mounted || !instance._options) { return } instance._options.addEventListener('change', instance._onSelectionChange) instance._root.addEventListener('mouseover', instance._onItemHovered) instance._root.addEventListener('mousedown', instance._onItemSelectionStart) instance._root.addEventListener('mouseup', instance._onItemClicked) addEventListener('mouseup', instance._onSelectionEnd) }
[ "function", "addEventListeners", "(", "instance", ")", "{", "if", "(", "!", "instance", ".", "_mounted", "||", "!", "instance", ".", "_options", ")", "{", "return", "}", "instance", ".", "_options", ".", "addEventListener", "(", "'change'", ",", "instance", ".", "_onSelectionChange", ")", "instance", ".", "_root", ".", "addEventListener", "(", "'mouseover'", ",", "instance", ".", "_onItemHovered", ")", "instance", ".", "_root", ".", "addEventListener", "(", "'mousedown'", ",", "instance", ".", "_onItemSelectionStart", ")", "instance", ".", "_root", ".", "addEventListener", "(", "'mouseup'", ",", "instance", ".", "_onItemClicked", ")", "addEventListener", "(", "'mouseup'", ",", "instance", ".", "_onSelectionEnd", ")", "}" ]
Registers event listeners that the provided szn-options instance requires to function correctly. The function has no effect if the provided szn-options element is not mounted into the document or has not been provided with its options yet. @param {SznElements.SznOptions} instance The szn-options element instance.
[ "Registers", "event", "listeners", "that", "the", "provided", "szn", "-", "options", "instance", "requires", "to", "function", "correctly", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L179-L189
train
jurca/szn-options
szn-options.js
removeEventListeners
function removeEventListeners(instance) { if (instance._options) { instance._options.removeEventListener('change', instance._onSelectionChange) } instance._root.removeEventListener('mouseover', instance._onItemHovered) instance._root.removeEventListener('mousedown', instance._onItemSelectionStart) instance._root.removeEventListener('mouseup', instance._onItemClicked) removeEventListener('mouseup', instance._onSelectionEnd) }
javascript
function removeEventListeners(instance) { if (instance._options) { instance._options.removeEventListener('change', instance._onSelectionChange) } instance._root.removeEventListener('mouseover', instance._onItemHovered) instance._root.removeEventListener('mousedown', instance._onItemSelectionStart) instance._root.removeEventListener('mouseup', instance._onItemClicked) removeEventListener('mouseup', instance._onSelectionEnd) }
[ "function", "removeEventListeners", "(", "instance", ")", "{", "if", "(", "instance", ".", "_options", ")", "{", "instance", ".", "_options", ".", "removeEventListener", "(", "'change'", ",", "instance", ".", "_onSelectionChange", ")", "}", "instance", ".", "_root", ".", "removeEventListener", "(", "'mouseover'", ",", "instance", ".", "_onItemHovered", ")", "instance", ".", "_root", ".", "removeEventListener", "(", "'mousedown'", ",", "instance", ".", "_onItemSelectionStart", ")", "instance", ".", "_root", ".", "removeEventListener", "(", "'mouseup'", ",", "instance", ".", "_onItemClicked", ")", "removeEventListener", "(", "'mouseup'", ",", "instance", ".", "_onSelectionEnd", ")", "}" ]
Deregisters all event listeners used by the provided szn-options element. @param {SznElements.SznOptions} instance The szn-options element instance.
[ "Deregisters", "all", "event", "listeners", "used", "by", "the", "provided", "szn", "-", "options", "element", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L196-L204
train
jurca/szn-options
szn-options.js
onItemHovered
function onItemHovered(instance, itemUi) { if (instance._options.disabled || !isEnabledOptionUi(itemUi)) { return } if (instance._options.multiple) { if (instance._dragSelectionStartOption) { updateMultiSelection(instance, itemUi) } return } instance._root.setAttribute('data-szn-options--highlighting', '') const previouslyHighlighted = instance._root.querySelector('[data-szn-options--highlighted]') if (previouslyHighlighted) { previouslyHighlighted.removeAttribute('data-szn-options--highlighted') } itemUi.setAttribute('data-szn-options--highlighted', '') }
javascript
function onItemHovered(instance, itemUi) { if (instance._options.disabled || !isEnabledOptionUi(itemUi)) { return } if (instance._options.multiple) { if (instance._dragSelectionStartOption) { updateMultiSelection(instance, itemUi) } return } instance._root.setAttribute('data-szn-options--highlighting', '') const previouslyHighlighted = instance._root.querySelector('[data-szn-options--highlighted]') if (previouslyHighlighted) { previouslyHighlighted.removeAttribute('data-szn-options--highlighted') } itemUi.setAttribute('data-szn-options--highlighted', '') }
[ "function", "onItemHovered", "(", "instance", ",", "itemUi", ")", "{", "if", "(", "instance", ".", "_options", ".", "disabled", "||", "!", "isEnabledOptionUi", "(", "itemUi", ")", ")", "{", "return", "}", "if", "(", "instance", ".", "_options", ".", "multiple", ")", "{", "if", "(", "instance", ".", "_dragSelectionStartOption", ")", "{", "updateMultiSelection", "(", "instance", ",", "itemUi", ")", "}", "return", "}", "instance", ".", "_root", ".", "setAttribute", "(", "'data-szn-options--highlighting'", ",", "''", ")", "const", "previouslyHighlighted", "=", "instance", ".", "_root", ".", "querySelector", "(", "'[data-szn-options--highlighted]'", ")", "if", "(", "previouslyHighlighted", ")", "{", "previouslyHighlighted", ".", "removeAttribute", "(", "'data-szn-options--highlighted'", ")", "}", "itemUi", ".", "setAttribute", "(", "'data-szn-options--highlighted'", ",", "''", ")", "}" ]
Handles the user moving the mouse pointer over an option in the szn-options element's UI. The function updates the current multiple-items selection if the element represents a multi-select, or updates the currently highlighted item in the UI of a single-select. @param {SznElements.SznOptions} instance The szn-options element instance. @param {Element} itemUi The element which's area the mouse pointer entered.
[ "Handles", "the", "user", "moving", "the", "mouse", "pointer", "over", "an", "option", "in", "the", "szn", "-", "options", "element", "s", "UI", ".", "The", "function", "updates", "the", "current", "multiple", "-", "items", "selection", "if", "the", "element", "represents", "a", "multi", "-", "select", "or", "updates", "the", "currently", "highlighted", "item", "in", "the", "UI", "of", "a", "single", "-", "select", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L214-L232
train
jurca/szn-options
szn-options.js
onItemClicked
function onItemClicked(instance, itemUi) { if (instance._dragSelectionStartOption) { // multi-select instance._dragSelectionStartOption = null return } if (instance._options.disabled || !isEnabledOptionUi(itemUi)) { return } instance._root.removeAttribute('data-szn-options--highlighting') instance._options.selectedIndex = itemUi._option.index instance._options.dispatchEvent(new CustomEvent('change', {bubbles: true, cancelable: true})) }
javascript
function onItemClicked(instance, itemUi) { if (instance._dragSelectionStartOption) { // multi-select instance._dragSelectionStartOption = null return } if (instance._options.disabled || !isEnabledOptionUi(itemUi)) { return } instance._root.removeAttribute('data-szn-options--highlighting') instance._options.selectedIndex = itemUi._option.index instance._options.dispatchEvent(new CustomEvent('change', {bubbles: true, cancelable: true})) }
[ "function", "onItemClicked", "(", "instance", ",", "itemUi", ")", "{", "if", "(", "instance", ".", "_dragSelectionStartOption", ")", "{", "instance", ".", "_dragSelectionStartOption", "=", "null", "return", "}", "if", "(", "instance", ".", "_options", ".", "disabled", "||", "!", "isEnabledOptionUi", "(", "itemUi", ")", ")", "{", "return", "}", "instance", ".", "_root", ".", "removeAttribute", "(", "'data-szn-options--highlighting'", ")", "instance", ".", "_options", ".", "selectedIndex", "=", "itemUi", ".", "_option", ".", "index", "instance", ".", "_options", ".", "dispatchEvent", "(", "new", "CustomEvent", "(", "'change'", ",", "{", "bubbles", ":", "true", ",", "cancelable", ":", "true", "}", ")", ")", "}" ]
Handles the user releasing the primary mouse button over an element representing an item. The function ends multiple-items selection for multi-selects, ends options highlighting and marks the the selected option for single-selects. @param {SznElements.SznOptions} instance The szn-options element instance. @param {Element} itemUi The element at which the user released the primary mouse button.
[ "Handles", "the", "user", "releasing", "the", "primary", "mouse", "button", "over", "an", "element", "representing", "an", "item", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L243-L256
train
jurca/szn-options
szn-options.js
onItemSelectionStart
function onItemSelectionStart(instance, itemUi, event) { if (instance._options.disabled || !instance._options.multiple || !isEnabledOptionUi(itemUi)) { return } const options = instance._options.options if (event.shiftKey && instance._previousSelectionStartIndex > -1) { instance._dragSelectionStartOption = options.item(instance._previousSelectionStartIndex) } else { if (event.ctrlKey) { instance._additionalSelectedIndexes = [] for (let i = 0, length = options.length; i < length; i++) { if (options.item(i).selected) { instance._additionalSelectedIndexes.push(i) } } instance._invertSelection = itemUi._option.selected } else { instance._invertSelection = false } instance._dragSelectionStartOption = itemUi._option } instance._previousSelectionStartIndex = instance._dragSelectionStartOption.index updateMultiSelection(instance, itemUi) }
javascript
function onItemSelectionStart(instance, itemUi, event) { if (instance._options.disabled || !instance._options.multiple || !isEnabledOptionUi(itemUi)) { return } const options = instance._options.options if (event.shiftKey && instance._previousSelectionStartIndex > -1) { instance._dragSelectionStartOption = options.item(instance._previousSelectionStartIndex) } else { if (event.ctrlKey) { instance._additionalSelectedIndexes = [] for (let i = 0, length = options.length; i < length; i++) { if (options.item(i).selected) { instance._additionalSelectedIndexes.push(i) } } instance._invertSelection = itemUi._option.selected } else { instance._invertSelection = false } instance._dragSelectionStartOption = itemUi._option } instance._previousSelectionStartIndex = instance._dragSelectionStartOption.index updateMultiSelection(instance, itemUi) }
[ "function", "onItemSelectionStart", "(", "instance", ",", "itemUi", ",", "event", ")", "{", "if", "(", "instance", ".", "_options", ".", "disabled", "||", "!", "instance", ".", "_options", ".", "multiple", "||", "!", "isEnabledOptionUi", "(", "itemUi", ")", ")", "{", "return", "}", "const", "options", "=", "instance", ".", "_options", ".", "options", "if", "(", "event", ".", "shiftKey", "&&", "instance", ".", "_previousSelectionStartIndex", ">", "-", "1", ")", "{", "instance", ".", "_dragSelectionStartOption", "=", "options", ".", "item", "(", "instance", ".", "_previousSelectionStartIndex", ")", "}", "else", "{", "if", "(", "event", ".", "ctrlKey", ")", "{", "instance", ".", "_additionalSelectedIndexes", "=", "[", "]", "for", "(", "let", "i", "=", "0", ",", "length", "=", "options", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "options", ".", "item", "(", "i", ")", ".", "selected", ")", "{", "instance", ".", "_additionalSelectedIndexes", ".", "push", "(", "i", ")", "}", "}", "instance", ".", "_invertSelection", "=", "itemUi", ".", "_option", ".", "selected", "}", "else", "{", "instance", ".", "_invertSelection", "=", "false", "}", "instance", ".", "_dragSelectionStartOption", "=", "itemUi", ".", "_option", "}", "instance", ".", "_previousSelectionStartIndex", "=", "instance", ".", "_dragSelectionStartOption", ".", "index", "updateMultiSelection", "(", "instance", ",", "itemUi", ")", "}" ]
Handles start of the user dragging the mouse pointer over the UI of a multi-selection szn-options element. The function marks the starting item. The function marks the starting item used previously as the current starting item if the Shift key is pressed. The function marks the indexes of the currently selected items if the Ctrl key is pressed and the Shift key is not. Also, if the Ctrl key pressed, the Shift key is not, and the user starts at an already selected item, the function will mark this as inverted selection. The function has no effect for single-selects. @param {SznElements.SznOptions} instance The szn-options element instance. @param {Element} itemUi The element at which the user pressed the primary mouse button down. @param {MouseEvent} event The mouse event representing the user's action.
[ "Handles", "start", "of", "the", "user", "dragging", "the", "mouse", "pointer", "over", "the", "UI", "of", "a", "multi", "-", "selection", "szn", "-", "options", "element", ".", "The", "function", "marks", "the", "starting", "item", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L273-L297
train
jurca/szn-options
szn-options.js
scrollToSelection
function scrollToSelection(instance, selectionStartIndex, selectionEndIndex) { const lastSelectionIndexes = instance._lastSelectionIndexes if ( selectionStartIndex !== -1 && (selectionStartIndex !== lastSelectionIndexes.start || selectionEndIndex !== lastSelectionIndexes.end) ) { const changedIndex = selectionStartIndex !== lastSelectionIndexes.start ? selectionStartIndex : selectionEndIndex scrollToOption(instance, changedIndex) } lastSelectionIndexes.start = selectionStartIndex lastSelectionIndexes.end = selectionEndIndex }
javascript
function scrollToSelection(instance, selectionStartIndex, selectionEndIndex) { const lastSelectionIndexes = instance._lastSelectionIndexes if ( selectionStartIndex !== -1 && (selectionStartIndex !== lastSelectionIndexes.start || selectionEndIndex !== lastSelectionIndexes.end) ) { const changedIndex = selectionStartIndex !== lastSelectionIndexes.start ? selectionStartIndex : selectionEndIndex scrollToOption(instance, changedIndex) } lastSelectionIndexes.start = selectionStartIndex lastSelectionIndexes.end = selectionEndIndex }
[ "function", "scrollToSelection", "(", "instance", ",", "selectionStartIndex", ",", "selectionEndIndex", ")", "{", "const", "lastSelectionIndexes", "=", "instance", ".", "_lastSelectionIndexes", "if", "(", "selectionStartIndex", "!==", "-", "1", "&&", "(", "selectionStartIndex", "!==", "lastSelectionIndexes", ".", "start", "||", "selectionEndIndex", "!==", "lastSelectionIndexes", ".", "end", ")", ")", "{", "const", "changedIndex", "=", "selectionStartIndex", "!==", "lastSelectionIndexes", ".", "start", "?", "selectionStartIndex", ":", "selectionEndIndex", "scrollToOption", "(", "instance", ",", "changedIndex", ")", "}", "lastSelectionIndexes", ".", "start", "=", "selectionStartIndex", "lastSelectionIndexes", ".", "end", "=", "selectionEndIndex", "}" ]
Scrolls, only if necessary, the UI of the provided szn-options element to make the last selected option visible. Which option is the last selected one is determined by comparing the provided index with the indexes passed to the previous call of this function. @param {SznElements.SznOptions} instance The szn-options element instance. @param {number} selectionStartIndex The index of the first selected option. The index must be a non-negative integer and cannot be greater that the total number of options; or set to <code>-1</code> if there is no option currently selected. @param {number} selectionEndIndex The index of the last selected option. The index must be a non-negative integer, cannot be greater than the total number of options and must not be lower than the <code>selectionStartIndex</code>; or set to <code>-1</code> if there is no option currently selected.
[ "Scrolls", "only", "if", "necessary", "the", "UI", "of", "the", "provided", "szn", "-", "options", "element", "to", "make", "the", "last", "selected", "option", "visible", ".", "Which", "option", "is", "the", "last", "selected", "one", "is", "determined", "by", "comparing", "the", "provided", "index", "with", "the", "indexes", "passed", "to", "the", "previous", "call", "of", "this", "function", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L312-L324
train
jurca/szn-options
szn-options.js
scrollToOption
function scrollToOption(instance, optionIndex) { const ui = instance._root if (ui.clientHeight >= ui.scrollHeight) { return } const uiBounds = ui.getBoundingClientRect() const options = instance._root.querySelectorAll('[data-szn-options--option]') const optionBounds = options[optionIndex].getBoundingClientRect() if (optionBounds.top >= uiBounds.top && optionBounds.bottom <= uiBounds.bottom) { return } const delta = optionBounds.top < uiBounds.top ? optionBounds.top - uiBounds.top : optionBounds.bottom - uiBounds.bottom ui.scrollTop += delta }
javascript
function scrollToOption(instance, optionIndex) { const ui = instance._root if (ui.clientHeight >= ui.scrollHeight) { return } const uiBounds = ui.getBoundingClientRect() const options = instance._root.querySelectorAll('[data-szn-options--option]') const optionBounds = options[optionIndex].getBoundingClientRect() if (optionBounds.top >= uiBounds.top && optionBounds.bottom <= uiBounds.bottom) { return } const delta = optionBounds.top < uiBounds.top ? optionBounds.top - uiBounds.top : optionBounds.bottom - uiBounds.bottom ui.scrollTop += delta }
[ "function", "scrollToOption", "(", "instance", ",", "optionIndex", ")", "{", "const", "ui", "=", "instance", ".", "_root", "if", "(", "ui", ".", "clientHeight", ">=", "ui", ".", "scrollHeight", ")", "{", "return", "}", "const", "uiBounds", "=", "ui", ".", "getBoundingClientRect", "(", ")", "const", "options", "=", "instance", ".", "_root", ".", "querySelectorAll", "(", "'[data-szn-options--option]'", ")", "const", "optionBounds", "=", "options", "[", "optionIndex", "]", ".", "getBoundingClientRect", "(", ")", "if", "(", "optionBounds", ".", "top", ">=", "uiBounds", ".", "top", "&&", "optionBounds", ".", "bottom", "<=", "uiBounds", ".", "bottom", ")", "{", "return", "}", "const", "delta", "=", "optionBounds", ".", "top", "<", "uiBounds", ".", "top", "?", "optionBounds", ".", "top", "-", "uiBounds", ".", "top", ":", "optionBounds", ".", "bottom", "-", "uiBounds", ".", "bottom", "ui", ".", "scrollTop", "+=", "delta", "}" ]
Scrolls, only if necessary, the UI of the provided szn-options element to make the option at the specified index fully visible. @param {SznElements.SznOptions} instance The szn-options element instance. @param {number} optionIndex The index of the option to select. The index must be a non-negative integer and cannot be greater than the total number of options.
[ "Scrolls", "only", "if", "necessary", "the", "UI", "of", "the", "provided", "szn", "-", "options", "element", "to", "make", "the", "option", "at", "the", "specified", "index", "fully", "visible", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L334-L352
train
jurca/szn-options
szn-options.js
updateMultiSelection
function updateMultiSelection(instance, lastHoveredItem) { const startIndex = instance._dragSelectionStartOption.index const lastIndex = lastHoveredItem._option.index const minIndex = Math.min(startIndex, lastIndex) const maxIndex = Math.max(startIndex, lastIndex) const options = instance._options.options const additionalIndexes = instance._additionalSelectedIndexes for (let i = 0, length = options.length; i < length; i++) { const option = options.item(i) if (isOptionEnabled(option)) { let isOptionSelected = additionalIndexes.indexOf(i) > -1 if (i >= minIndex && i <= maxIndex) { isOptionSelected = !instance._invertSelection } option.selected = isOptionSelected } } instance._options.dispatchEvent(new CustomEvent('change', {bubbles: true, cancelable: true})) }
javascript
function updateMultiSelection(instance, lastHoveredItem) { const startIndex = instance._dragSelectionStartOption.index const lastIndex = lastHoveredItem._option.index const minIndex = Math.min(startIndex, lastIndex) const maxIndex = Math.max(startIndex, lastIndex) const options = instance._options.options const additionalIndexes = instance._additionalSelectedIndexes for (let i = 0, length = options.length; i < length; i++) { const option = options.item(i) if (isOptionEnabled(option)) { let isOptionSelected = additionalIndexes.indexOf(i) > -1 if (i >= minIndex && i <= maxIndex) { isOptionSelected = !instance._invertSelection } option.selected = isOptionSelected } } instance._options.dispatchEvent(new CustomEvent('change', {bubbles: true, cancelable: true})) }
[ "function", "updateMultiSelection", "(", "instance", ",", "lastHoveredItem", ")", "{", "const", "startIndex", "=", "instance", ".", "_dragSelectionStartOption", ".", "index", "const", "lastIndex", "=", "lastHoveredItem", ".", "_option", ".", "index", "const", "minIndex", "=", "Math", ".", "min", "(", "startIndex", ",", "lastIndex", ")", "const", "maxIndex", "=", "Math", ".", "max", "(", "startIndex", ",", "lastIndex", ")", "const", "options", "=", "instance", ".", "_options", ".", "options", "const", "additionalIndexes", "=", "instance", ".", "_additionalSelectedIndexes", "for", "(", "let", "i", "=", "0", ",", "length", "=", "options", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "const", "option", "=", "options", ".", "item", "(", "i", ")", "if", "(", "isOptionEnabled", "(", "option", ")", ")", "{", "let", "isOptionSelected", "=", "additionalIndexes", ".", "indexOf", "(", "i", ")", ">", "-", "1", "if", "(", "i", ">=", "minIndex", "&&", "i", "<=", "maxIndex", ")", "{", "isOptionSelected", "=", "!", "instance", ".", "_invertSelection", "}", "option", ".", "selected", "=", "isOptionSelected", "}", "}", "instance", ".", "_options", ".", "dispatchEvent", "(", "new", "CustomEvent", "(", "'change'", ",", "{", "bubbles", ":", "true", ",", "cancelable", ":", "true", "}", ")", ")", "}" ]
Updates the multiple-items selection. This function is meant to be used with multi-selects when the user is selecting multiple items by dragging the mouse pointer over them. Any item which's index is in the provided instance's list of additionally selected items will be marked as selected as well. @param {SznElements.SznOptions} instance The szn-options element instance. @param {Element} lastHoveredItem The element representing the UI of the last option the user has hovered using their mouse pointer.
[ "Updates", "the", "multiple", "-", "items", "selection", ".", "This", "function", "is", "meant", "to", "be", "used", "with", "multi", "-", "selects", "when", "the", "user", "is", "selecting", "multiple", "items", "by", "dragging", "the", "mouse", "pointer", "over", "them", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L365-L385
train
jurca/szn-options
szn-options.js
updateUi
function updateUi(instance) { if (!instance._options) { return } if (instance._options.disabled) { instance._root.setAttribute('disabled', '') } else { instance._root.removeAttribute('disabled') } if (instance._options.multiple) { instance._root.setAttribute('data-szn-options--multiple', '') } else { instance._root.removeAttribute('data-szn-options--multiple') } updateGroupUi(instance._root, instance._options) if (instance._mounted) { const options = instance._options.options let lastSelectedIndex = -1 for (let i = options.length - 1; i >= 0; i--) { if (options.item(i).selected) { lastSelectedIndex = i break } } scrollToSelection(instance, instance._options.selectedIndex, lastSelectedIndex) } }
javascript
function updateUi(instance) { if (!instance._options) { return } if (instance._options.disabled) { instance._root.setAttribute('disabled', '') } else { instance._root.removeAttribute('disabled') } if (instance._options.multiple) { instance._root.setAttribute('data-szn-options--multiple', '') } else { instance._root.removeAttribute('data-szn-options--multiple') } updateGroupUi(instance._root, instance._options) if (instance._mounted) { const options = instance._options.options let lastSelectedIndex = -1 for (let i = options.length - 1; i >= 0; i--) { if (options.item(i).selected) { lastSelectedIndex = i break } } scrollToSelection(instance, instance._options.selectedIndex, lastSelectedIndex) } }
[ "function", "updateUi", "(", "instance", ")", "{", "if", "(", "!", "instance", ".", "_options", ")", "{", "return", "}", "if", "(", "instance", ".", "_options", ".", "disabled", ")", "{", "instance", ".", "_root", ".", "setAttribute", "(", "'disabled'", ",", "''", ")", "}", "else", "{", "instance", ".", "_root", ".", "removeAttribute", "(", "'disabled'", ")", "}", "if", "(", "instance", ".", "_options", ".", "multiple", ")", "{", "instance", ".", "_root", ".", "setAttribute", "(", "'data-szn-options--multiple'", ",", "''", ")", "}", "else", "{", "instance", ".", "_root", ".", "removeAttribute", "(", "'data-szn-options--multiple'", ")", "}", "updateGroupUi", "(", "instance", ".", "_root", ",", "instance", ".", "_options", ")", "if", "(", "instance", ".", "_mounted", ")", "{", "const", "options", "=", "instance", ".", "_options", ".", "options", "let", "lastSelectedIndex", "=", "-", "1", "for", "(", "let", "i", "=", "options", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "options", ".", "item", "(", "i", ")", ".", "selected", ")", "{", "lastSelectedIndex", "=", "i", "break", "}", "}", "scrollToSelection", "(", "instance", ",", "instance", ".", "_options", ".", "selectedIndex", ",", "lastSelectedIndex", ")", "}", "}" ]
Updates the UI, if the provided szn-options element has already been provided with the options to display. The functions synchronizes the displayed UI to reflect the available options, their status, and scrolls to the last selected option if it is not visible. @param {SznElements.SznOptions} instance The szn-options element's instance.
[ "Updates", "the", "UI", "if", "the", "provided", "szn", "-", "options", "element", "has", "already", "been", "provided", "with", "the", "options", "to", "display", ".", "The", "functions", "synchronizes", "the", "displayed", "UI", "to", "reflect", "the", "available", "options", "their", "status", "and", "scrolls", "to", "the", "last", "selected", "option", "if", "it", "is", "not", "visible", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L422-L450
train
jurca/szn-options
szn-options.js
updateGroupUi
function updateGroupUi(uiContainer, optionsGroup) { removeRemovedItems(uiContainer, optionsGroup) updateExistingItems(uiContainer) addMissingItems(uiContainer, optionsGroup) }
javascript
function updateGroupUi(uiContainer, optionsGroup) { removeRemovedItems(uiContainer, optionsGroup) updateExistingItems(uiContainer) addMissingItems(uiContainer, optionsGroup) }
[ "function", "updateGroupUi", "(", "uiContainer", ",", "optionsGroup", ")", "{", "removeRemovedItems", "(", "uiContainer", ",", "optionsGroup", ")", "updateExistingItems", "(", "uiContainer", ")", "addMissingItems", "(", "uiContainer", ",", "optionsGroup", ")", "}" ]
Updates the contents of the provided UI to reflect the options in the provided options container. The function removes removed options from the UI, updates the existing and adds the missing ones. @param {Element} uiContainer The element containing the constructed UI reflecting the provided options. @param {HTMLElement} optionsGroup The element containing the options to be reflected in the UI.
[ "Updates", "the", "contents", "of", "the", "provided", "UI", "to", "reflect", "the", "options", "in", "the", "provided", "options", "container", ".", "The", "function", "removes", "removed", "options", "from", "the", "UI", "updates", "the", "existing", "and", "adds", "the", "missing", "ones", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L459-L463
train
jurca/szn-options
szn-options.js
removeRemovedItems
function removeRemovedItems(uiContainer, optionsGroup) { const options = Array.prototype.slice.call(optionsGroup.children) let currentItemUi = uiContainer.firstElementChild while (currentItemUi) { if (options.indexOf(currentItemUi._option) > -1) { currentItemUi = currentItemUi.nextElementSibling continue } const itemToRemove = currentItemUi currentItemUi = currentItemUi.nextElementSibling uiContainer.removeChild(itemToRemove) } }
javascript
function removeRemovedItems(uiContainer, optionsGroup) { const options = Array.prototype.slice.call(optionsGroup.children) let currentItemUi = uiContainer.firstElementChild while (currentItemUi) { if (options.indexOf(currentItemUi._option) > -1) { currentItemUi = currentItemUi.nextElementSibling continue } const itemToRemove = currentItemUi currentItemUi = currentItemUi.nextElementSibling uiContainer.removeChild(itemToRemove) } }
[ "function", "removeRemovedItems", "(", "uiContainer", ",", "optionsGroup", ")", "{", "const", "options", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "optionsGroup", ".", "children", ")", "let", "currentItemUi", "=", "uiContainer", ".", "firstElementChild", "while", "(", "currentItemUi", ")", "{", "if", "(", "options", ".", "indexOf", "(", "currentItemUi", ".", "_option", ")", ">", "-", "1", ")", "{", "currentItemUi", "=", "currentItemUi", ".", "nextElementSibling", "continue", "}", "const", "itemToRemove", "=", "currentItemUi", "currentItemUi", "=", "currentItemUi", ".", "nextElementSibling", "uiContainer", ".", "removeChild", "(", "itemToRemove", ")", "}", "}" ]
Removes UI items from the UI that have been representing the options and option groups that have been removed from the provided container of options. @param {Element} uiContainer The element containing the elements reflecting the provided options and providing the UI for the options. @param {HTMLElement} optionsGroup The element containing the options for which this szn-options element is providing the UI.
[ "Removes", "UI", "items", "from", "the", "UI", "that", "have", "been", "representing", "the", "options", "and", "option", "groups", "that", "have", "been", "removed", "from", "the", "provided", "container", "of", "options", "." ]
dc1c2e1f74e25d78643904389cdbaaf48a20b52e
https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L474-L487
train