code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
} | Creates a string based on an array of numeric code points.
@see `punycode.ucs2.decode`
@memberOf punycode.ucs2
@name encode
@param {Array} codePoints The array of numeric code points.
@returns {String} The new Unicode string (UCS-2). | ucs2encode | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
} | Converts a basic code point into a digit/integer.
@see `digitToBasic()`
@private
@param {Number} codePoint The basic numeric code point value.
@returns {Number} The numeric value of a basic code point (for use in
representing integers) in the range `0` to `base - 1`, or `base` if
the code point does not represent a value. | basicToDigit | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
} | Converts a digit/integer into a basic code point.
@see `basicToDigit()`
@private
@param {Number} digit The numeric value of a basic code point.
@returns {Number} The basic code point whose value (when used for
representing integers) is `digit`, which needs to be in the range
`0` to `base - 1`. If `flag` is non-zero, the uppercase form is
used; else, the lowercase form is used. The behavior is undefined
if `flag` is non-zero and `digit` has no uppercase form. | digitToBasic | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
} | Bias adaptation function as per section 3.4 of RFC 3492.
https://tools.ietf.org/html/rfc3492#section-3.4
@private | adapt | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
} | Converts a Punycode string of ASCII-only symbols to a string of Unicode
symbols.
@memberOf punycode
@param {String} input The Punycode string of ASCII-only symbols.
@returns {String} The resulting string of Unicode symbols. | decode | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
} | Converts a string of Unicode symbols (e.g. a domain name label) to a
Punycode string of ASCII-only symbols.
@memberOf punycode
@param {String} input The string of Unicode symbols.
@returns {String} The resulting Punycode string of ASCII-only symbols. | encode | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
} | Converts a Punycode string representing a domain name or an email address
to Unicode. Only the Punycoded parts of the input will be converted, i.e.
it doesn't matter if you call it on a string that has already been
converted to Unicode.
@memberOf punycode
@param {String} input The Punycoded domain name or email address to
convert to Unicode.
@returns {String} The Unicode representation of the given Punycode
string. | toUnicode | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
} | Converts a Unicode string representing a domain name or an email address to
Punycode. Only the non-ASCII parts of the domain name will be converted,
i.e. it doesn't matter if you call it with a domain that's already in
ASCII.
@memberOf punycode
@param {String} input The domain name or email address to convert, as a
Unicode string.
@returns {String} The Punycode representation of the given domain name or
email address. | toASCII | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
} | Mark that a method should not be used.
Returns a modified function which warns once by default.
If `localStorage.noDeprecation = true` is set, then it is a no-op.
If `localStorage.throwDeprecation = true` is set, then deprecated functions
will throw an Error when invoked.
If `localStorage.traceDeprecation = true` is set, then deprecated functions
will invoke `console.trace()` instead of `console.error()`.
@param {Function} fn - the function to deprecate
@param {String} msg - the string to print to the console when `fn` is invoked
@returns {Function} a new "deprecated" version of `fn`
@api public | deprecate | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
} | Mark that a method should not be used.
Returns a modified function which warns once by default.
If `localStorage.noDeprecation = true` is set, then it is a no-op.
If `localStorage.throwDeprecation = true` is set, then deprecated functions
will throw an Error when invoked.
If `localStorage.traceDeprecation = true` is set, then deprecated functions
will invoke `console.trace()` instead of `console.error()`.
@param {Function} fn - the function to deprecate
@param {String} msg - the string to print to the console when `fn` is invoked
@returns {Function} a new "deprecated" version of `fn`
@api public | deprecated | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
} | Checks `localStorage` for boolean values for the given `name`.
@param {String} name
@returns {Boolean}
@api private | config | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function parseAuthOptions (opts) {
var matches
if (opts.auth) {
matches = opts.auth.match(/^(.+):(.+)$/)
if (matches) {
opts.username = matches[1]
opts.password = matches[2]
} else {
opts.username = opts.auth
}
}
} | Parse the auth attribute and merge username and password in the options object.
@param {Object} [opts] option object | parseAuthOptions | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function connect (brokerUrl, opts) {
if ((typeof brokerUrl === 'object') && !opts) {
opts = brokerUrl
brokerUrl = null
}
opts = opts || {}
if (brokerUrl) {
opts = xtend(url.parse(brokerUrl, true), opts)
if (opts.protocol === null) {
throw new Error('Missing protocol')
}
opts.protocol = opts.protocol.replace(/:$/, '')
}
// merge in the auth options if supplied
parseAuthOptions(opts)
// support clientId passed in the query string of the url
if (opts.query && typeof opts.query.clientId === 'string') {
opts.clientId = opts.query.clientId
}
if (opts.cert && opts.key) {
if (opts.protocol) {
if (['mqtts', 'wss'].indexOf(opts.protocol) === -1) {
/*
* jshint and eslint
* complains that break from default cannot be reached after throw
* it is a foced exit from a control structure
* maybe add a check after switch to see if it went through default
* and then throw the error
*/
/* jshint -W027 */
/* eslint no-unreachable:1 */
switch (opts.protocol) {
case 'mqtt':
opts.protocol = 'mqtts'
break
case 'ws':
opts.protocol = 'wss'
break
default:
throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!')
break
}
/* eslint no-unreachable:0 */
/* jshint +W027 */
}
} else {
// don't know what protocol he want to use, mqtts or wss
throw new Error('Missing secure protocol key')
}
}
if (!protocols[opts.protocol]) {
var isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
opts.protocol = [
'mqtt',
'mqtts',
'ws',
'wss'
].filter(function (key, index) {
if (isSecure && index % 2 === 0) {
// Skip insecure protocols when requesting a secure one.
return false
}
return (typeof protocols[key] === 'function')
})[0]
}
if (opts.clean === false && !opts.clientId) {
throw new Error('Missing clientId for unclean clients')
}
function wrapper (client) {
if (opts.servers) {
if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
client._reconnectCount = 0
}
opts.host = opts.servers[client._reconnectCount].host
opts.port = opts.servers[client._reconnectCount].port
opts.hostname = opts.host
client._reconnectCount++
}
return protocols[opts.protocol](client, opts)
}
return new MqttClient(wrapper, opts)
} | connect - connect to an MQTT broker.
@param {String} [brokerUrl] - url of the broker, optional
@param {Object} opts - see MqttClient#constructor | connect | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function wrapper (client) {
if (opts.servers) {
if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
client._reconnectCount = 0
}
opts.host = opts.servers[client._reconnectCount].host
opts.port = opts.servers[client._reconnectCount].port
opts.hostname = opts.host
client._reconnectCount++
}
return protocols[opts.protocol](client, opts)
} | connect - connect to an MQTT broker.
@param {String} [brokerUrl] - url of the broker, optional
@param {Object} opts - see MqttClient#constructor | wrapper | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/browserMqtt.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/browserMqtt.js | MIT |
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | inspect | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | stylizeWithColor | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function stylizeNoColor(str, styleType) {
return str;
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | stylizeNoColor | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | arrayToHash | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | formatValue | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | formatPrimitive | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | formatError | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | formatArray | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | formatProperty | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | reduceToSingleString | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isArray(ar) {
return Array.isArray(ar);
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isArray | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isBoolean(arg) {
return typeof arg === 'boolean';
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isBoolean | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isNull(arg) {
return arg === null;
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isNull | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isNullOrUndefined(arg) {
return arg == null;
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isNullOrUndefined | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isNumber(arg) {
return typeof arg === 'number';
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isNumber | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isString(arg) {
return typeof arg === 'string';
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isString | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isSymbol(arg) {
return typeof arg === 'symbol';
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isSymbol | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isUndefined(arg) {
return arg === void 0;
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isUndefined | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isRegExp | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isObject | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isDate | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isError | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isFunction(arg) {
return typeof arg === 'function';
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isFunction | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | isPrimitive | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function objectToString(o) {
return Object.prototype.toString.call(o);
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | objectToString | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | pad | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
} | Echos the value of a value. Trys to print the value out
in the best way possible given the different types.
@param {Object} obj The object to print out.
@param {Object} opts Optional options object that alters the output. | timestamp | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
} | Inherit the prototype methods from one constructor into another.
The Function.prototype.inherits from lang.js rewritten as a standalone
function (not on Function.prototype). NOTE: If this file is to be loaded
during bootstrapping this function needs to be rewritten using some native
functions as prototype setup using normal JavaScript does not work as
expected during bootstrapping (see mirror.js in r114903).
@param {function} ctor Constructor function which needs to inherit the
prototype.
@param {function} superCtor Constructor function to inherit prototype from. | hasOwnProperty | javascript | node-pinus/pinus | tools/pinus-admin-web/public/js/util/mqttClient.js | https://github.com/node-pinus/pinus/blob/master/tools/pinus-admin-web/public/js/util/mqttClient.js | MIT |
function prepareMoveTransition (frags) {
var transition =
transitionEndEvent && // css transition supported?
frags && frags.length && // has frags to be moved?
frags[0].node.__v_trans // has transitions?
if (transition) {
var node = frags[0].node
var moveClass = transition.id + '-move'
var moving = node._pendingMoveCb
var hasTransition = false
if (!moving) {
// sniff whether element has a transition duration for transform
// with the move class applied
addClass(node, moveClass)
var type = transition.getCssTransitionType(moveClass)
if (type === 'transition') {
var computedStyles = window.getComputedStyle(node)
var transitionedProps = computedStyles[transitionProp + 'Property']
if (/\btransform(,|$)/.test(transitionedProps)) {
hasTransition = true
}
}
removeClass(node, moveClass)
}
if (moving || hasTransition) {
frags.forEach(function (frag) {
frag._oldPos = frag.node.getBoundingClientRect()
})
return true
}
}
} | Check if move transitions are needed, and if so,
record the bounding client rects for each item.
@param {Array<Fragment>|undefined} frags
@return {Boolean|undefined} | prepareMoveTransition | javascript | vuejs/vue-animated-list | vue-animated-list.js | https://github.com/vuejs/vue-animated-list/blob/master/vue-animated-list.js | MIT |
function applyMoveTransition (frags) {
frags.forEach(function (frag) {
frag._newPos = frag.node.getBoundingClientRect()
})
frags.forEach(function (frag) {
var node = frag.node
var oldPos = frag._oldPos
if (!oldPos) return
if (!frag.moved) {
// transition busting to ensure correct bounding rect:
// if an element has an ongoing transition and not "reinserted",
// the bounding rect will not be calculated at its target position,
// but rather an in-transition position.
var p = node.parentNode
var next = node.nextSibling
p.removeChild(node)
p.insertBefore(node, next)
}
var dx = oldPos.left - frag._newPos.left
var dy = oldPos.top - frag._newPos.top
if (dx !== 0 || dy !== 0) {
frag.moved = true
node.style.transform =
node.style.WebkitTransform =
'translate(' + dx + 'px, ' + dy + 'px)'
node.style.transitionDuration = '0s'
} else {
frag.moved = false
}
})
Vue.nextTick(function () {
var f = document.documentElement.offsetHeight
frags.forEach(function (frag) {
var node = frag.node
var moveClass = node.__v_trans.id + '-move'
if (frag.moved) {
addClass(node, moveClass)
node.style.transform = node.style.WebkitTransform = ''
node.style.transitionDuration = ''
if (node._pendingMoveCb) {
off(node, transitionEndEvent, node._pendingMoveCb)
}
node._pendingMoveCb = function cb () {
off(node, transitionEndEvent, cb)
node._pendingMoveCb = null
removeClass(node, moveClass)
}
on(node, transitionEndEvent, node._pendingMoveCb)
}
})
})
} | Apply move transitions.
Calculate new target positions after the move, then apply the
FLIP technique to trigger CSS transforms.
@param {Array<Fragment>} frags | applyMoveTransition | javascript | vuejs/vue-animated-list | vue-animated-list.js | https://github.com/vuejs/vue-animated-list/blob/master/vue-animated-list.js | MIT |
countObjProps = function (obj) {
var k, l = 0;
for (k in obj) {
if (obj.hasOwnProperty(k)) {
l++;
}
}
return l;
} | @name Hyphenator-docLanguages
@description
An object holding all languages used in the document. This is filled by
{@link Hyphenator-gatherDocumentInfos}
@type {Object}
@private | countObjProps | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
createElem = function (tagname, context) {
context = context || contextWindow;
if (document.createElementNS) {
return context.document.createElementNS('http://www.w3.org/1999/xhtml', tagname);
} else if (document.createElement) {
return context.document.createElement(tagname);
}
} | @name Hyphenator-onHyphenationDone
@description
A method to be called, when the last element has been hyphenated or the hyphenation has been
removed from the last element.
@see Hyphenator.config
@type {function()}
@private | createElem | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
onError = function (e) {
window.alert("Hyphenator.js says:\n\nAn Error ocurred:\n" + e.message);
} | @name Hyphenator-selectorFunction
@description
A function that has to return a HTMLNodeList of Elements to be hyphenated.
By default it uses the classname ('hyphenate') to select the elements.
@see Hyphenator.config
@type {function()}
@private | onError | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
selectorFunction = function () {
var tmp, el = [], i, l;
if (document.getElementsByClassName) {
el = contextWindow.document.getElementsByClassName(hyphenateClass);
} else {
tmp = contextWindow.document.getElementsByTagName('*');
l = tmp.length;
for (i = 0; i < l; i++)
{
if (tmp[i].className.indexOf(hyphenateClass) !== -1 && tmp[i].className.indexOf(dontHyphenateClass) === -1) {
el.push(tmp[i]);
}
}
}
return el;
} | @name Hyphenator-selectorFunction
@description
A function that has to return a HTMLNodeList of Elements to be hyphenated.
By default it uses the classname ('hyphenate') to select the elements.
@see Hyphenator.config
@type {function()}
@private | selectorFunction | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
getLang = function (el, fallback) {
if (!!el.getAttribute('lang')) {
return el.getAttribute('lang').toLowerCase();
}
// The following doesn't work in IE due to a bug when getAttribute('xml:lang') in a table
/*if (!!el.getAttribute('xml:lang')) {
return el.getAttribute('xml:lang').substring(0, 2);
}*/
//instead, we have to do this (thanks to borgzor):
try {
if (!!el.getAttribute('xml:lang')) {
return el.getAttribute('xml:lang').toLowerCase();
}
} catch (ex) {}
if (el.tagName !== 'HTML') {
return getLang(el.parentNode, true);
}
if (fallback) {
return mainLanguage;
}
return null;
} | @name Hyphenator-getLang
@description
Gets the language of an element. If no language is set, it may use the {@link Hyphenator-mainLanguage}.
@param {Object} el The first parameter is an DOM-Element-Object
@param {boolean} fallback The second parameter is a boolean to tell if the function should return the {@link Hyphenator-mainLanguage}
if there's no language found for the element.
@private | getLang | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
autoSetMainLanguage = function (w) {
w = w || contextWindow;
var el = w.document.getElementsByTagName('html')[0],
m = w.document.getElementsByTagName('meta'),
i, text, e, ul;
mainLanguage = getLang(el, false);
if (!mainLanguage) {
for (i = 0; i < m.length; i++) {
//<meta http-equiv = "content-language" content="xy">
if (!!m[i].getAttribute('http-equiv') && (m[i].getAttribute('http-equiv').toLowerCase() === 'content-language')) {
mainLanguage = m[i].getAttribute('content').toLowerCase();
}
//<meta name = "DC.Language" content="xy">
if (!!m[i].getAttribute('name') && (m[i].getAttribute('name').toLowerCase() === 'dc.language')) {
mainLanguage = m[i].getAttribute('content').toLowerCase();
}
//<meta name = "language" content = "xy">
if (!!m[i].getAttribute('name') && (m[i].getAttribute('name').toLowerCase() === 'language')) {
mainLanguage = m[i].getAttribute('content').toLowerCase();
}
}
}
//get lang for frame from enclosing document
if (!mainLanguage && doFrames && contextWindow != window.parent) {
autoSetMainLanguage(window.parent);
}
//fallback to defaultLang if set
if (!mainLanguage && defaultLanguage !== '') {
mainLanguage = defaultLanguage;
}
//ask user for lang
if (!mainLanguage) {
text = '';
ul = navigator.language ? navigator.language : navigator.userLanguage;
ul = ul.substring(0, 2);
if (prompterStrings.hasOwnProperty(ul)) {
text = prompterStrings[ul];
} else {
text = prompterStrings.en;
}
text += ' (ISO 639-1)\n\n' + languageHint;
mainLanguage = window.prompt(unescape(text), ul).toLowerCase();
}
if (!supportedLang.hasOwnProperty(mainLanguage)) {
if (supportedLang.hasOwnProperty(mainLanguage.split('-')[0])) { //try subtag
mainLanguage = mainLanguage.split('-')[0];
} else {
e = new Error('The language "' + mainLanguage + '" is not yet supported.');
throw e;
}
}
} | @name Hyphenator-autoSetMainLanguage
@description
Retrieves the language of the document from the DOM.
The function looks in the following places:
<ul>
<li>lang-attribute in the html-tag</li>
<li><meta http-equiv = "content-language" content = "xy" /></li>
<li><meta name = "DC.Language" content = "xy" /></li>
<li><meta name = "language" content = "xy" /></li>
</li>
If nothing can be found a prompt using {@link Hyphenator-languageHint} and {@link Hyphenator-prompterStrings} is displayed.
If the retrieved language is in the object {@link Hyphenator-supportedLang} it is copied to {@link Hyphenator-mainLanguage}
@private | autoSetMainLanguage | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
gatherDocumentInfos = function () {
var elToProcess, tmp, i = 0,
process = function (el, hide, lang) {
var n, i = 0, hyphenatorSettings = {};
if (hide && intermediateState === 'hidden') {
if (!!el.getAttribute('style')) {
hyphenatorSettings.hasOwnStyle = true;
} else {
hyphenatorSettings.hasOwnStyle = false;
}
hyphenatorSettings.isHidden = true;
el.style.visibility = 'hidden';
}
if (el.lang && typeof(el.lang) === 'string') {
hyphenatorSettings.language = el.lang.toLowerCase(); //copy attribute-lang to internal lang
} else if (lang) {
hyphenatorSettings.language = lang.toLowerCase();
} else {
hyphenatorSettings.language = getLang(el, true);
}
lang = hyphenatorSettings.language;
if (supportedLang[lang]) {
docLanguages[lang] = true;
} else {
if (supportedLang.hasOwnProperty(lang.split('-')[0])) { //try subtag
lang = lang.split('-')[0];
hyphenatorSettings.language = lang;
} else if (!isBookmarklet) {
onError(new Error('Language ' + lang + ' is not yet supported.'));
}
}
Expando.setDataForElem(el, hyphenatorSettings);
elements.push(el);
while (!!(n = el.childNodes[i++])) {
if (n.nodeType === 1 && !dontHyphenate[n.nodeName.toLowerCase()] &&
n.className.indexOf(dontHyphenateClass) === -1 && !(n in elToProcess)) {
process(n, false, lang);
}
}
};
if (isBookmarklet) {
elToProcess = contextWindow.document.getElementsByTagName('body')[0];
process(elToProcess, false, mainLanguage);
} else {
elToProcess = selectorFunction();
while (!!(tmp = elToProcess[i++]))
{
process(tmp, true, '');
}
}
if (!Hyphenator.languages.hasOwnProperty(mainLanguage)) {
docLanguages[mainLanguage] = true;
} else if (!Hyphenator.languages[mainLanguage].prepared) {
docLanguages[mainLanguage] = true;
}
if (elements.length > 0) {
Expando.appendDataForElem(elements[elements.length - 1], {isLast : true});
}
} | @name Hyphenator-gatherDocumentInfos
@description
This method runs through the DOM and executes the process()-function on:
- every node returned by the {@link Hyphenator-selectorFunction}.
The process()-function copies the element to the elements-variable, sets its visibility
to intermediateState, retrieves its language and recursivly descends the DOM-tree until
the child-Nodes aren't of type 1
@private | gatherDocumentInfos | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
process = function (el, hide, lang) {
var n, i = 0, hyphenatorSettings = {};
if (hide && intermediateState === 'hidden') {
if (!!el.getAttribute('style')) {
hyphenatorSettings.hasOwnStyle = true;
} else {
hyphenatorSettings.hasOwnStyle = false;
}
hyphenatorSettings.isHidden = true;
el.style.visibility = 'hidden';
}
if (el.lang && typeof(el.lang) === 'string') {
hyphenatorSettings.language = el.lang.toLowerCase(); //copy attribute-lang to internal lang
} else if (lang) {
hyphenatorSettings.language = lang.toLowerCase();
} else {
hyphenatorSettings.language = getLang(el, true);
}
lang = hyphenatorSettings.language;
if (supportedLang[lang]) {
docLanguages[lang] = true;
} else {
if (supportedLang.hasOwnProperty(lang.split('-')[0])) { //try subtag
lang = lang.split('-')[0];
hyphenatorSettings.language = lang;
} else if (!isBookmarklet) {
onError(new Error('Language ' + lang + ' is not yet supported.'));
}
}
Expando.setDataForElem(el, hyphenatorSettings);
elements.push(el);
while (!!(n = el.childNodes[i++])) {
if (n.nodeType === 1 && !dontHyphenate[n.nodeName.toLowerCase()] &&
n.className.indexOf(dontHyphenateClass) === -1 && !(n in elToProcess)) {
process(n, false, lang);
}
}
} | @name Hyphenator-gatherDocumentInfos
@description
This method runs through the DOM and executes the process()-function on:
- every node returned by the {@link Hyphenator-selectorFunction}.
The process()-function copies the element to the elements-variable, sets its visibility
to intermediateState, retrieves its language and recursivly descends the DOM-tree until
the child-Nodes aren't of type 1
@private | process | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
convertPatterns = function (lang) {
var plen, anfang, ende, pats, pat, key, tmp = {};
pats = Hyphenator.languages[lang].patterns;
for (plen in pats) {
if (pats.hasOwnProperty(plen)) {
plen = parseInt(plen, 10);
anfang = 0;
ende = plen;
while (!!(pat = pats[plen].substring(anfang, ende))) {
key = pat.replace(/\d/g, '');
tmp[key] = pat;
anfang = ende;
ende += plen;
}
}
}
Hyphenator.languages[lang].patterns = tmp;
Hyphenator.languages[lang].patternsConverted = true;
} | @name Hyphenator-convertPatterns
@description
Converts the patterns from string '_a6' to object '_a':'_a6'.
The result is stored in the {@link Hyphenator-patterns}-object.
@private
@param {string} lang the language whose patterns shall be converted | convertPatterns | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
convertExceptionsToObject = function (exc) {
var w = exc.split(', '),
r = {},
i, l, key;
for (i = 0, l = w.length; i < l; i++) {
key = w[i].replace(/-/g, '');
if (!r.hasOwnProperty(key)) {
r[key] = w[i];
}
}
return r;
} | @name Hyphenator-convertExceptionsToObject
@description
Converts a list of comma seprated exceptions to an object:
'Fortran,Hy-phen-a-tion' -> {'Fortran':'Fortran','Hyphenation':'Hy-phen-a-tion'}
@private
@param {string} exc a comma separated string of exceptions (without spaces) | convertExceptionsToObject | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
loadPatterns = function (lang) {
var url, xhr, head, script;
if (supportedLang[lang] && !Hyphenator.languages[lang]) {
url = basePath + 'patterns/' + supportedLang[lang];
} else {
return;
}
if (isLocal && !isBookmarklet) {
//check if 'url' is available:
xhr = null;
if (typeof XMLHttpRequest !== 'undefined') {
xhr = new XMLHttpRequest();
}
if (!xhr) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = null;
}
}
if (xhr) {
xhr.open('HEAD', url, false);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.send(null);
if (xhr.status === 404) {
onError(new Error('Could not load\n' + url));
delete docLanguages[lang];
return;
}
}
}
if (createElem) {
head = window.document.getElementsByTagName('head').item(0);
script = createElem('script', window);
script.src = url;
script.type = 'text/javascript';
head.appendChild(script);
}
} | @name Hyphenator-loadPatterns
@description
Adds a <script>-Tag to the DOM to load an externeal .js-file containing patterns and settings for the given language.
If the given language is not in the {@link Hyphenator-supportedLang}-Object it returns.
One may ask why we are not using AJAX to load the patterns. The XMLHttpRequest-Object
has a same-origin-policy. This makes the isBookmarklet-functionality impossible.
@param {string} lang The language to load the patterns for
@private
@see Hyphenator-basePath | loadPatterns | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
prepareLanguagesObj = function (lang) {
var lo = Hyphenator.languages[lang], wrd;
if (!lo.prepared) {
if (enableCache) {
lo.cache = {};
//Export
lo['cache'] = lo.cache;
}
if (enableReducedPatternSet) {
lo.redPatSet = {};
}
//add exceptions from the pattern file to the local 'exceptions'-obj
if (lo.hasOwnProperty('exceptions')) {
Hyphenator.addExceptions(lang, lo.exceptions);
delete lo.exceptions;
}
//copy global exceptions to the language specific exceptions
if (exceptions.hasOwnProperty('global')) {
if (exceptions.hasOwnProperty(lang)) {
exceptions[lang] += ', ' + exceptions.global;
} else {
exceptions[lang] = exceptions.global;
}
}
//move exceptions from the the local 'exceptions'-obj to the 'language'-object
if (exceptions.hasOwnProperty(lang)) {
lo.exceptions = convertExceptionsToObject(exceptions[lang]);
delete exceptions[lang];
} else {
lo.exceptions = {};
}
convertPatterns(lang);
wrd = '[\\w' + lo.specialChars + '@' + String.fromCharCode(173) + '-]{' + min + ',}';
lo.genRegExp = new RegExp('(' + url + ')|(' + mail + ')|(' + wrd + ')', 'gi');
lo.prepared = true;
}
if (!!storage) {
try {
storage.setItem('Hyphenator_' + lang, window.JSON.stringify(lo));
} catch (e) {
//onError(e);
}
}
} | @name Hyphenator-prepareLanguagesObj
@description
Adds a cache to each language and converts the exceptions-list to an object.
If storage is active the object is stored there.
@private
@param {string} lang the language ob the lang-obj | prepareLanguagesObj | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
prepare = function (callback) {
var lang, interval, tmp1, tmp2;
if (!enableRemoteLoading) {
for (lang in Hyphenator.languages) {
if (Hyphenator.languages.hasOwnProperty(lang)) {
prepareLanguagesObj(lang);
}
}
state = 2;
callback();
return;
}
// get all languages that are used and preload the patterns
state = 1;
for (lang in docLanguages) {
if (docLanguages.hasOwnProperty(lang)) {
if (!!storage && storage.getItem('Hyphenator_' + lang)) {
Hyphenator.languages[lang] = window.JSON.parse(storage.getItem('Hyphenator_' + lang));
if (exceptions.hasOwnProperty('global')) {
tmp1 = convertExceptionsToObject(exceptions.global);
for (tmp2 in tmp1) {
if (tmp1.hasOwnProperty(tmp2)) {
Hyphenator.languages[lang].exceptions[tmp2] = tmp1[tmp2];
}
}
}
//Replace exceptions since they may have been changed:
if (exceptions.hasOwnProperty(lang)) {
tmp1 = convertExceptionsToObject(exceptions[lang]);
for (tmp2 in tmp1) {
if (tmp1.hasOwnProperty(tmp2)) {
Hyphenator.languages[lang].exceptions[tmp2] = tmp1[tmp2];
}
}
delete exceptions[lang];
}
//Replace genRegExp since it may have been changed:
tmp1 = '[\\w' + Hyphenator.languages[lang].specialChars + '@' + String.fromCharCode(173) + '-]{' + min + ',}';
Hyphenator.languages[lang].genRegExp = new RegExp('(' + url + ')|(' + mail + ')|(' + tmp1 + ')', 'gi');
delete docLanguages[lang];
continue;
} else {
loadPatterns(lang);
}
}
}
// if all patterns are loaded from storage: callback
if (countObjProps(docLanguages) === 0) {
state = 2;
callback();
return;
}
// else async wait until patterns are loaded, then callback
interval = window.setInterval(function () {
var finishedLoading = true, lang;
for (lang in docLanguages) {
if (docLanguages.hasOwnProperty(lang)) {
finishedLoading = false;
if (!!Hyphenator.languages[lang]) {
delete docLanguages[lang];
//do conversion while other patterns are loading:
prepareLanguagesObj(lang);
}
}
}
if (finishedLoading) {
//console.log('callig callback for ' + contextWindow.location.href);
window.clearInterval(interval);
state = 2;
callback();
}
}, 100);
} | @name Hyphenator-prepare
@description
This funtion prepares the Hyphenator-Object: If RemoteLoading is turned off, it assumes
that the patternfiles are loaded, all conversions are made and the callback is called.
If storage is active the object is retrieved there.
If RemoteLoading is on (default), it loads the pattern files and waits until they are loaded,
by repeatedly checking Hyphenator.languages. If a patterfile is loaded the patterns are
converted to their object style and the lang-object extended.
Finally the callback is called.
@param {function()} callback to call, when all patterns are loaded
@private | prepare | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
toggleBox = function () {
var myBox, bdy, myIdAttribute, myTextNode, myClassAttribute,
text = (Hyphenator.doHyphenation ? 'Hy-phen-a-tion' : 'Hyphenation');
if (!!(myBox = contextWindow.document.getElementById('HyphenatorToggleBox'))) {
myBox.firstChild.data = text;
} else {
bdy = contextWindow.document.getElementsByTagName('body')[0];
myBox = createElem('div', contextWindow);
myIdAttribute = contextWindow.document.createAttribute('id');
myIdAttribute.nodeValue = 'HyphenatorToggleBox';
myClassAttribute = contextWindow.document.createAttribute('class');
myClassAttribute.nodeValue = dontHyphenateClass;
myTextNode = contextWindow.document.createTextNode(text);
myBox.appendChild(myTextNode);
myBox.setAttributeNode(myIdAttribute);
myBox.setAttributeNode(myClassAttribute);
myBox.onclick = Hyphenator.toggleHyphenation;
myBox.style.position = 'absolute';
myBox.style.top = '0px';
myBox.style.right = '0px';
myBox.style.margin = '0';
myBox.style.backgroundColor = '#AAAAAA';
myBox.style.color = '#FFFFFF';
myBox.style.font = '6pt Arial';
myBox.style.letterSpacing = '0.2em';
myBox.style.padding = '3px';
myBox.style.cursor = 'pointer';
myBox.style.WebkitBorderBottomLeftRadius = '4px';
myBox.style.MozBorderRadiusBottomleft = '4px';
bdy.appendChild(myBox);
}
} | @name Hyphenator-switchToggleBox
@description
Creates or hides the toggleBox: a small button to turn off/on hyphenation on a page.
@param {boolean} s true when hyphenation is on, false when it's off
@see Hyphenator.config
@private | toggleBox | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
hyphenateURL = function (url) {
return url.replace(/([:\/\.\?#&_,;!@]+)/gi, '$&' + urlhyphen);
} | @name Hyphenator-removeHyphenationFromElement
@description
Removes all hyphens from the element. If there are other elements, the function is
called recursively.
Removing hyphens is usefull if you like to copy text. Some browsers are buggy when the copy hyphenated texts.
@param {Object} el The element where to remove hyphenation.
@public | hyphenateURL | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
removeHyphenationFromElement = function (el) {
var h, i = 0, n;
switch (hyphen) {
case '|':
h = '\\|';
break;
case '+':
h = '\\+';
break;
case '*':
h = '\\*';
break;
default:
h = hyphen;
}
while (!!(n = el.childNodes[i++])) {
if (n.nodeType === 3) {
n.data = n.data.replace(new RegExp(h, 'g'), '');
n.data = n.data.replace(new RegExp(zeroWidthSpace, 'g'), '');
} else if (n.nodeType === 1) {
removeHyphenationFromElement(n);
}
}
} | @name Hyphenator-removeHyphenationFromElement
@description
Removes all hyphens from the element. If there are other elements, the function is
called recursively.
Removing hyphens is usefull if you like to copy text. Some browsers are buggy when the copy hyphenated texts.
@param {Object} el The element where to remove hyphenation.
@public | removeHyphenationFromElement | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
hyphenateElement = function (el) {
var hyphenatorSettings = Expando.getDataForElem(el),
lang = hyphenatorSettings.language, hyphenate, n, i,
controlOrphans = function (part) {
var h, r;
switch (hyphen) {
case '|':
h = '\\|';
break;
case '+':
h = '\\+';
break;
case '*':
h = '\\*';
break;
default:
h = hyphen;
}
if (orphanControl >= 2) {
//remove hyphen points from last word
r = part.split(' ');
r[1] = r[1].replace(new RegExp(h, 'g'), '');
r[1] = r[1].replace(new RegExp(zeroWidthSpace, 'g'), '');
r = r.join(' ');
}
if (orphanControl === 3) {
//replace spaces by non breaking spaces
r = r.replace(/[ ]+/g, String.fromCharCode(160));
}
return r;
};
if (Hyphenator.languages.hasOwnProperty(lang)) {
hyphenate = function (word) {
if (!Hyphenator.doHyphenation) {
return word;
} else if (urlOrMailRE.test(word)) {
return hyphenateURL(word);
} else {
return hyphenateWord(lang, word);
}
};
if (safeCopy && (el.tagName.toLowerCase() !== 'body')) {
registerOnCopy(el);
}
i = 0;
while (!!(n = el.childNodes[i++])) {
if (n.nodeType === 3 && n.data.length >= min) { //type 3 = #text -> hyphenate!
n.data = n.data.replace(Hyphenator.languages[lang].genRegExp, hyphenate);
if (orphanControl !== 1) {
n.data = n.data.replace(/[\S]+ [\S]+$/, controlOrphans);
}
}
}
}
if (hyphenatorSettings.isHidden && intermediateState === 'hidden') {
el.style.visibility = 'visible';
if (!hyphenatorSettings.hasOwnStyle) {
el.setAttribute('style', ''); // without this, removeAttribute doesn't work in Safari (thanks to molily)
el.removeAttribute('style');
} else {
if (el.style.removeProperty) {
el.style.removeProperty('visibility');
} else if (el.style.removeAttribute) { // IE
el.style.removeAttribute('visibility');
}
}
}
if (hyphenatorSettings.isLast) {
state = 3;
documentCount--;
if (documentCount > (-1000) && documentCount <= 0) {
documentCount = (-2000);
onHyphenationDone();
}
}
} | @name Hyphenator-hyphenateElement
@description
Takes the content of the given element and - if there's text - replaces the words
by hyphenated words. If there's another element, the function is called recursively.
When all words are hyphenated, the visibility of the element is set to 'visible'.
@param {Object} el The element to hyphenate
@private | hyphenateElement | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
controlOrphans = function (part) {
var h, r;
switch (hyphen) {
case '|':
h = '\\|';
break;
case '+':
h = '\\+';
break;
case '*':
h = '\\*';
break;
default:
h = hyphen;
}
if (orphanControl >= 2) {
//remove hyphen points from last word
r = part.split(' ');
r[1] = r[1].replace(new RegExp(h, 'g'), '');
r[1] = r[1].replace(new RegExp(zeroWidthSpace, 'g'), '');
r = r.join(' ');
}
if (orphanControl === 3) {
//replace spaces by non breaking spaces
r = r.replace(/[ ]+/g, String.fromCharCode(160));
}
return r;
} | @name Hyphenator-hyphenateElement
@description
Takes the content of the given element and - if there's text - replaces the words
by hyphenated words. If there's another element, the function is called recursively.
When all words are hyphenated, the visibility of the element is set to 'visible'.
@param {Object} el The element to hyphenate
@private | controlOrphans | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
hyphenateDocument = function () {
function bind(fun, arg) {
return function () {
return fun(arg);
};
}
var i = 0, el;
while (!!(el = elements[i++])) {
if (el.ownerDocument.location.href === contextWindow.location.href) {
window.setTimeout(bind(hyphenateElement, el), 0);
}
}
} | @name Hyphenator-removeHyphenationFromDocument
@description
Does what it says ;-)
@private | hyphenateDocument | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
function bind(fun, arg) {
return function () {
return fun(arg);
};
} | @name Hyphenator-removeHyphenationFromDocument
@description
Does what it says ;-)
@private | bind | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
removeHyphenationFromDocument = function () {
var i = 0, el;
while (!!(el = elements[i++])) {
removeHyphenationFromElement(el);
}
state = 4;
} | @name Hyphenator-createStorage
@description
inits the private var storage depending of the setting in storageType
and the supported features of the system.
@private | removeHyphenationFromDocument | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
createStorage = function () {
try {
if (storageType !== 'none' &&
typeof(window.localStorage) !== 'undefined' &&
typeof(window.sessionStorage) !== 'undefined' &&
typeof(window.JSON.stringify) !== 'undefined' &&
typeof(window.JSON.parse) !== 'undefined') {
switch (storageType) {
case 'session':
storage = window.sessionStorage;
break;
case 'local':
storage = window.localStorage;
break;
default:
storage = undefined;
break;
}
}
} catch (f) {
//FF throws an error if DOM.storage.enabled is set to false
}
} | @name Hyphenator-createStorage
@description
inits the private var storage depending of the setting in storageType
and the supported features of the system.
@private | createStorage | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
storeConfiguration = function () {
if (!storage) {
return;
}
var settings = {
'STORED': true,
'classname': hyphenateClass,
'donthyphenateclassname': dontHyphenateClass,
'minwordlength': min,
'hyphenchar': hyphen,
'urlhyphenchar': urlhyphen,
'togglebox': toggleBox,
'displaytogglebox': displayToggleBox,
'remoteloading': enableRemoteLoading,
'enablecache': enableCache,
'onhyphenationdonecallback': onHyphenationDone,
'onerrorhandler': onError,
'intermediatestate': intermediateState,
'selectorfunction': selectorFunction,
'safecopy': safeCopy,
'doframes': doFrames,
'storagetype': storageType,
'orphancontrol': orphanControl,
'dohyphenation': Hyphenator.doHyphenation,
'persistentconfig': persistentConfig,
'defaultlanguage': defaultLanguage
};
storage.setItem('Hyphenator_config', window.JSON.stringify(settings));
} | @name Hyphenator-storeConfiguration
@description
Stores the current config-options in DOM-Storage
@private | storeConfiguration | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
restoreConfiguration = function () {
var settings;
if (storage.getItem('Hyphenator_config')) {
settings = window.JSON.parse(storage.getItem('Hyphenator_config'));
Hyphenator.config(settings);
}
} | @name Hyphenator.version
@memberOf Hyphenator
@description
String containing the actual version of Hyphenator.js
[major release].[minor releas].[bugfix release]
major release: new API, new Features, big changes
minor release: new languages, improvements
@public | restoreConfiguration | javascript | cmod/bibliotype | js/Hyphenator.js | https://github.com/cmod/bibliotype/blob/master/js/Hyphenator.js | MIT |
function createMeterValue(value): UnitValue {
return {
unit: 'm',
value,
};
} | The `type` keyword indicates that this is a
flow specific declaration. These declarations
are not part of the distributed code! | createMeterValue | javascript | ryyppy/flow-guide | tutorial/00-basics/05-recap.js | https://github.com/ryyppy/flow-guide/blob/master/tutorial/00-basics/05-recap.js | MIT |
function guessParamType(value): UnitValue {
return {
unit: 'km',
value,
};
} | The `type` keyword indicates that this is a
flow specific declaration. These declarations
are not part of the distributed code! | guessParamType | javascript | ryyppy/flow-guide | tutorial/00-basics/05-recap.js | https://github.com/ryyppy/flow-guide/blob/master/tutorial/00-basics/05-recap.js | MIT |
renderData = () => {
switch (showAs) {
case 'list': return this._renderList(data);
case 'grid': return this._renderGrid(data);
default: return null;
}
} | We define the structure of our props,
which will usually be done during runtime
via React.PropTypes | renderData | javascript | ryyppy/flow-guide | tutorial/01-react/00-intro.js | https://github.com/ryyppy/flow-guide/blob/master/tutorial/01-react/00-intro.js | MIT |
renderData = () => {
switch (showAs) {
case 'list': return this._renderList(data);
case 'grid': return this._renderGrid(data);
default: return null;
}
} | We define the structure of our props,
which will usually be done during runtime
via React.PropTypes | renderData | javascript | ryyppy/flow-guide | tutorial/01-react/00-intro.js | https://github.com/ryyppy/flow-guide/blob/master/tutorial/01-react/00-intro.js | MIT |
if (!isLoading) {
return null;
} | We define the structure of our props,
which will usually be done during runtime
via React.PropTypes | if | javascript | ryyppy/flow-guide | tutorial/01-react/00-intro.js | https://github.com/ryyppy/flow-guide/blob/master/tutorial/01-react/00-intro.js | MIT |
function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 10001, //< Default Max Timout is 3s
start = new Date().getTime(),
condition = false,
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
// If not time-out yet and condition not yet fulfilled
condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
} else {
if(!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
console.log("'waitFor()' timeout");
phantom.exit(1);
} else {
// Condition fulfilled (timeout and/or condition is 'true')
//console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
clearInterval(interval); //< Stop this interval
}
}
}, 100); //< repeat check every 100ms
} | Wait until the test condition is true or a timeout occurs. Useful for waiting
on a server response or for a ui change (fadeIn, etc.) to occur.
@param testFx javascript condition that evaluates to a boolean,
it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
as a callback function.
@param onReady what to do when testFx condition is fulfilled,
it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
as a callback function.
@param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. | waitFor | javascript | smalot/bootstrap-datetimepicker | tests/run-qunit.js | https://github.com/smalot/bootstrap-datetimepicker/blob/master/tests/run-qunit.js | Apache-2.0 |
function readFileLines(filename) {
var stream = fs.open(filename, 'r');
var lines = [];
var line;
while (!stream.atEnd()) {
lines.push(stream.readLine());
}
stream.close();
return lines;
} | Wait until the test condition is true or a timeout occurs. Useful for waiting
on a server response or for a ui change (fadeIn, etc.) to occur.
@param testFx javascript condition that evaluates to a boolean,
it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
as a callback function.
@param onReady what to do when testFx condition is fulfilled,
it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
as a callback function.
@param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. | readFileLines | javascript | smalot/bootstrap-datetimepicker | tests/run-qunit.js | https://github.com/smalot/bootstrap-datetimepicker/blob/master/tests/run-qunit.js | Apache-2.0 |
performAction({ innerAccess, method, url, query, params, headers, body }) {
this.app.meta.util.deprecated('ctx.performAction', 'ctx.meta.util.performAction');
return this.meta.util.performAction({ innerAccess, method, url, query, params, headers, body });
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | performAction | javascript | cabloy/cabloy | packages/egg-born-backend/app/extend/context.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/app/extend/context.js | MIT |
getVal(name) {
return (
(this.params && this.params[name]) ||
(this.query && this.query[name]) ||
(this.request.body && this.request.body[name])
);
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | getVal | javascript | cabloy/cabloy | packages/egg-born-backend/app/extend/context.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/app/extend/context.js | MIT |
getInt(name) {
return parseInt(this.getVal(name));
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | getInt | javascript | cabloy/cabloy | packages/egg-born-backend/app/extend/context.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/app/extend/context.js | MIT |
getFloat(name) {
return parseFloat(this.getVal(name));
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | getFloat | javascript | cabloy/cabloy | packages/egg-born-backend/app/extend/context.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/app/extend/context.js | MIT |
getStr(name) {
const v = this.getVal(name);
return (v && v.toString()) || '';
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | getStr | javascript | cabloy/cabloy | packages/egg-born-backend/app/extend/context.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/app/extend/context.js | MIT |
getSafeStr(name) {
const v = this.getStr(name);
return v.replace(/'/gi, "''");
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | getSafeStr | javascript | cabloy/cabloy | packages/egg-born-backend/app/extend/context.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/app/extend/context.js | MIT |
successMore(list, index, size) {
this.success({ list, index: index + list.length, finished: size === -1 || size === 0 || list.length < size });
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | successMore | javascript | cabloy/cabloy | packages/egg-born-backend/app/extend/context.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/app/extend/context.js | MIT |
async getPayload(options) {
return await raw(inflate(this.req), options);
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | getPayload | javascript | cabloy/cabloy | packages/egg-born-backend/app/extend/context.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/app/extend/context.js | MIT |
function getText(locale, ...args) {
const key = args[0];
if (!key) return null;
// try locale
let resource = ebLocales[locale] || {};
let text = resource[key];
if (text === undefined && locale !== 'en-us') {
// try en-us
resource = ebLocales['en-us'] || {};
text = resource[key];
}
// equal key
if (text === undefined) {
text = key;
}
// format
args[0] = text;
return localeutil.getText.apply(localeutil, args);
} | based on koa-locales
https://github.com/koajs/locales/blob/master/index.js | getText | javascript | cabloy/cabloy | packages/egg-born-backend/lib/module/locales.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/module/locales.js | MIT |
function formatLocale(locale) {
// support zh_CN, en_US => zh-CN, en-US
return locale.replace('_', '-').toLowerCase();
} | based on koa-locales
https://github.com/koajs/locales/blob/master/index.js | formatLocale | javascript | cabloy/cabloy | packages/egg-born-backend/lib/module/locales.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/module/locales.js | MIT |
get() {
return ctxCaller.locale;
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | get | javascript | cabloy/cabloy | packages/egg-born-backend/lib/utils/performAction.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/utils/performAction.js | MIT |
get() {
return ctxCaller.subdomain;
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | get | javascript | cabloy/cabloy | packages/egg-born-backend/lib/utils/performAction.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/utils/performAction.js | MIT |
function delegateHeaders(ctx, ctxCaller, headers) {
if (ctxCaller && ctxCaller.headers) {
Object.assign(ctx.headers, ctxCaller.headers);
}
if (headers) {
Object.assign(ctx.headers, headers);
}
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | delegateHeaders | javascript | cabloy/cabloy | packages/egg-born-backend/lib/utils/performAction.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/utils/performAction.js | MIT |
function delegateCookies(ctx, ctxCaller) {
const _cookies = ctx.cookies;
Object.defineProperty(ctx, 'cookies', {
get() {
return ctxCaller.cookies || _cookies;
},
});
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | delegateCookies | javascript | cabloy/cabloy | packages/egg-born-backend/lib/utils/performAction.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/utils/performAction.js | MIT |
get() {
return ctxCaller.cookies || _cookies;
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | get | javascript | cabloy/cabloy | packages/egg-born-backend/lib/utils/performAction.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/utils/performAction.js | MIT |
function delegateProperty(ctx, ctxCaller, property) {
Object.defineProperty(ctx, property, {
get() {
return ctxCaller[property];
},
});
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | delegateProperty | javascript | cabloy/cabloy | packages/egg-born-backend/lib/utils/performAction.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/utils/performAction.js | MIT |
get() {
return ctxCaller[property];
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | get | javascript | cabloy/cabloy | packages/egg-born-backend/lib/utils/performAction.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/utils/performAction.js | MIT |
function createRequest({ method, url }, ctxCaller) {
// _req
const _req = ctxCaller.request;
// req
const req = new http.IncomingMessage();
req.headers = _req.headers;
req.host = _req.host;
req.hostname = _req.hostname;
req.protocol = _req.protocol;
req.secure = _req.secure;
req.method = method.toUpperCase();
req.url = url;
// path,
req.socket = {
remoteAddress: _req.socket.remoteAddress,
remotePort: _req.socket.remotePort,
};
return req;
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | createRequest | javascript | cabloy/cabloy | packages/egg-born-backend/lib/utils/performAction.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/utils/performAction.js | MIT |
async performAction({ innerAccess, method, url, query, params, headers, body }) {
return await performActionFn({
ctxCaller: ctx,
innerAccess,
method,
url,
query,
params,
headers,
body,
});
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | performAction | javascript | cabloy/cabloy | packages/egg-born-backend/lib/utils/utilCtx.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/utils/utilCtx.js | MIT |
getDbOriginal() {
const dbLevel = ctx.dbLevel;
const mysqlConfig = ctx.app.mysql.__ebdb_test;
if (!mysqlConfig) return ctx.app.mysql.get('__ebdb');
let dbs = ctx.app.mysql.__ebdb_test_dbs;
if (!dbs) {
dbs = ctx.app.mysql.__ebdb_test_dbs = [];
}
if (!dbs[dbLevel]) {
// need not to check connectionLimit
// if (dbLevel > 0) {
// const connectionLimit =
// mysqlConfig.connectionLimitInner || ctx.app.mysql.options.default.connectionLimitInner;
// mysqlConfig = Object.assign({}, mysqlConfig, { connectionLimit });
// }
dbs[dbLevel] = ctx.app.mysql.createInstance(mysqlConfig);
}
return dbs[dbLevel];
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | getDbOriginal | javascript | cabloy/cabloy | packages/egg-born-backend/lib/utils/utilCtx.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/utils/utilCtx.js | MIT |
createDatabase() {
const db = this.getDbOriginal();
return new Proxy(db, {
get(target, prop) {
const value = target[prop];
if (!is.function(value)) return value;
// if (value.name !== 'createPromise') return value;
// check if use transaction
if (!ctx.dbMeta.transaction.inTransaction) return value;
return function (...args) {
return ctx.dbMeta.transaction.connection[prop].apply(ctx.dbMeta.transaction.connection, args);
};
},
});
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | createDatabase | javascript | cabloy/cabloy | packages/egg-born-backend/lib/utils/utilCtx.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/utils/utilCtx.js | MIT |
get(target, prop) {
const value = target[prop];
if (!is.function(value)) return value;
// if (value.name !== 'createPromise') return value;
// check if use transaction
if (!ctx.dbMeta.transaction.inTransaction) return value;
return function (...args) {
return ctx.dbMeta.transaction.connection[prop].apply(ctx.dbMeta.transaction.connection, args);
};
} | perform action of this or that module
@param {string} options options
@param {string} options.method method
@param {string} options.url url
@param {json} options.body body(optional)
@return {promise} response.body.data or throw error | get | javascript | cabloy/cabloy | packages/egg-born-backend/lib/utils/utilCtx.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-backend/lib/utils/utilCtx.js | MIT |
description() {
return 'backend cov';
} | /dist/backend.js'];
// check dev server
const devServerRunning = yield utils.checkIfDevServerRunning({
warnWhenRunning: true,
});
if (devServerRunning) return;
yield super.run(context);
}
formatTestArgs({ argv, debugOptions }) {
const testArgv = Object.assign({}, argv);
/* istanbul ignore next | description | javascript | cabloy/cabloy | packages/egg-born-bin/lib/cmd/backend-cov.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-bin/lib/cmd/backend-cov.js | MIT |
*curl(url, options) {
return yield this.httpClient.request(url, options);
} | send curl to remote server
@param {String} url - target url
@param {Object} [options] - request options
@return {Object} response data | curl | javascript | cabloy/cabloy | packages/egg-born-bin/lib/cmd/test-update.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-bin/lib/cmd/test-update.js | MIT |
*getPackageInfo(pkgName, withFallback) {
this.log(`fetching npm info of ${pkgName}`);
try {
const result = yield this.curl(`${this.registryUrl}/${pkgName}/latest`, {
dataType: 'json',
followRedirect: true,
maxRedirects: 5,
timeout: 20000,
});
assert(result.status === 200, `npm info ${pkgName} got error: ${result.status}, ${result.data.reason}`);
return result.data;
} catch (err) {
if (withFallback) {
this.log(`use fallback from ${pkgName}`);
return require(`${pkgName}/package.json`);
}
throw err;
}
} | get package info from registry
@param {String} pkgName - package name
@param {Boolean} [withFallback] - when http request fail, whethe to require local
@return {Object} pkgInfo | getPackageInfo | javascript | cabloy/cabloy | packages/egg-born-bin/lib/cmd/test-update.js | https://github.com/cabloy/cabloy/blob/master/packages/egg-born-bin/lib/cmd/test-update.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.