id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
5,900 | stylus/stylus | lib/parser.js | function(){
var type = this.expect('atrule').val
, node = new nodes.Atrule(type)
, tok;
this.skipSpacesAndComments();
node.segments = this.selectorParts();
this.skipSpacesAndComments();
tok = this.peek().type;
if ('indent' == tok || '{' == tok || ('newline' == tok
&& '{' == this.lookahead(2).type)) {
this.state.push('atrule');
node.block = this.block(node);
this.state.pop();
}
return node;
} | javascript | function(){
var type = this.expect('atrule').val
, node = new nodes.Atrule(type)
, tok;
this.skipSpacesAndComments();
node.segments = this.selectorParts();
this.skipSpacesAndComments();
tok = this.peek().type;
if ('indent' == tok || '{' == tok || ('newline' == tok
&& '{' == this.lookahead(2).type)) {
this.state.push('atrule');
node.block = this.block(node);
this.state.pop();
}
return node;
} | [
"function",
"(",
")",
"{",
"var",
"type",
"=",
"this",
".",
"expect",
"(",
"'atrule'",
")",
".",
"val",
",",
"node",
"=",
"new",
"nodes",
".",
"Atrule",
"(",
"type",
")",
",",
"tok",
";",
"this",
".",
"skipSpacesAndComments",
"(",
")",
";",
"node",
".",
"segments",
"=",
"this",
".",
"selectorParts",
"(",
")",
";",
"this",
".",
"skipSpacesAndComments",
"(",
")",
";",
"tok",
"=",
"this",
".",
"peek",
"(",
")",
".",
"type",
";",
"if",
"(",
"'indent'",
"==",
"tok",
"||",
"'{'",
"==",
"tok",
"||",
"(",
"'newline'",
"==",
"tok",
"&&",
"'{'",
"==",
"this",
".",
"lookahead",
"(",
"2",
")",
".",
"type",
")",
")",
"{",
"this",
".",
"state",
".",
"push",
"(",
"'atrule'",
")",
";",
"node",
".",
"block",
"=",
"this",
".",
"block",
"(",
"node",
")",
";",
"this",
".",
"state",
".",
"pop",
"(",
")",
";",
"}",
"return",
"node",
";",
"}"
] | atrule selector? block? | [
"atrule",
"selector?",
"block?"
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/parser.js#L1055-L1070 |
|
5,901 | stylus/stylus | lib/parser.js | function(){
var node = this.supportsNegation()
|| this.supportsOp();
if (!node) {
this.cond = true;
node = this.expression();
this.cond = false;
}
return node;
} | javascript | function(){
var node = this.supportsNegation()
|| this.supportsOp();
if (!node) {
this.cond = true;
node = this.expression();
this.cond = false;
}
return node;
} | [
"function",
"(",
")",
"{",
"var",
"node",
"=",
"this",
".",
"supportsNegation",
"(",
")",
"||",
"this",
".",
"supportsOp",
"(",
")",
";",
"if",
"(",
"!",
"node",
")",
"{",
"this",
".",
"cond",
"=",
"true",
";",
"node",
"=",
"this",
".",
"expression",
"(",
")",
";",
"this",
".",
"cond",
"=",
"false",
";",
"}",
"return",
"node",
";",
"}"
] | supports negation
| supports op
| expression | [
"supports",
"negation",
"|",
"supports",
"op",
"|",
"expression"
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/parser.js#L1104-L1113 |
|
5,902 | stylus/stylus | lib/parser.js | function(){
if (this.accept('not')) {
var node = new nodes.Expression;
node.push(new nodes.Literal('not'));
node.push(this.supportsFeature());
return node;
}
} | javascript | function(){
if (this.accept('not')) {
var node = new nodes.Expression;
node.push(new nodes.Literal('not'));
node.push(this.supportsFeature());
return node;
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"accept",
"(",
"'not'",
")",
")",
"{",
"var",
"node",
"=",
"new",
"nodes",
".",
"Expression",
";",
"node",
".",
"push",
"(",
"new",
"nodes",
".",
"Literal",
"(",
"'not'",
")",
")",
";",
"node",
".",
"push",
"(",
"this",
".",
"supportsFeature",
"(",
")",
")",
";",
"return",
"node",
";",
"}",
"}"
] | 'not' supports feature | [
"not",
"supports",
"feature"
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/parser.js#L1119-L1126 |
|
5,903 | stylus/stylus | lib/parser.js | function() {
var tok = this.expect('keyframes')
, keyframes;
this.skipSpacesAndComments();
keyframes = new nodes.Keyframes(this.selectorParts(), tok.val);
keyframes.column = tok.column;
this.skipSpacesAndComments();
// block
this.state.push('atrule');
keyframes.block = this.block(keyframes);
this.state.pop();
return keyframes;
} | javascript | function() {
var tok = this.expect('keyframes')
, keyframes;
this.skipSpacesAndComments();
keyframes = new nodes.Keyframes(this.selectorParts(), tok.val);
keyframes.column = tok.column;
this.skipSpacesAndComments();
// block
this.state.push('atrule');
keyframes.block = this.block(keyframes);
this.state.pop();
return keyframes;
} | [
"function",
"(",
")",
"{",
"var",
"tok",
"=",
"this",
".",
"expect",
"(",
"'keyframes'",
")",
",",
"keyframes",
";",
"this",
".",
"skipSpacesAndComments",
"(",
")",
";",
"keyframes",
"=",
"new",
"nodes",
".",
"Keyframes",
"(",
"this",
".",
"selectorParts",
"(",
")",
",",
"tok",
".",
"val",
")",
";",
"keyframes",
".",
"column",
"=",
"tok",
".",
"column",
";",
"this",
".",
"skipSpacesAndComments",
"(",
")",
";",
"// block",
"this",
".",
"state",
".",
"push",
"(",
"'atrule'",
")",
";",
"keyframes",
".",
"block",
"=",
"this",
".",
"block",
"(",
"keyframes",
")",
";",
"this",
".",
"state",
".",
"pop",
"(",
")",
";",
"return",
"keyframes",
";",
"}"
] | keyframes name block | [
"keyframes",
"name",
"block"
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/parser.js#L1376-L1392 |
|
5,904 | stylus/stylus | lib/parser.js | function() {
var arr
, group = new nodes.Group
, scope = this.selectorScope
, isRoot = 'root' == this.currentState()
, selector;
do {
// Clobber newline after ,
this.accept('newline');
arr = this.selectorParts();
// Push the selector
if (isRoot && scope) arr.unshift(new nodes.Literal(scope + ' '));
if (arr.length) {
selector = new nodes.Selector(arr);
selector.lineno = arr[0].lineno;
selector.column = arr[0].column;
group.push(selector);
}
} while (this.accept(',') || this.accept('newline'));
if ('selector-parts' == this.currentState()) return group.nodes;
this.state.push('selector');
group.block = this.block(group);
this.state.pop();
return group;
} | javascript | function() {
var arr
, group = new nodes.Group
, scope = this.selectorScope
, isRoot = 'root' == this.currentState()
, selector;
do {
// Clobber newline after ,
this.accept('newline');
arr = this.selectorParts();
// Push the selector
if (isRoot && scope) arr.unshift(new nodes.Literal(scope + ' '));
if (arr.length) {
selector = new nodes.Selector(arr);
selector.lineno = arr[0].lineno;
selector.column = arr[0].column;
group.push(selector);
}
} while (this.accept(',') || this.accept('newline'));
if ('selector-parts' == this.currentState()) return group.nodes;
this.state.push('selector');
group.block = this.block(group);
this.state.pop();
return group;
} | [
"function",
"(",
")",
"{",
"var",
"arr",
",",
"group",
"=",
"new",
"nodes",
".",
"Group",
",",
"scope",
"=",
"this",
".",
"selectorScope",
",",
"isRoot",
"=",
"'root'",
"==",
"this",
".",
"currentState",
"(",
")",
",",
"selector",
";",
"do",
"{",
"// Clobber newline after ,",
"this",
".",
"accept",
"(",
"'newline'",
")",
";",
"arr",
"=",
"this",
".",
"selectorParts",
"(",
")",
";",
"// Push the selector",
"if",
"(",
"isRoot",
"&&",
"scope",
")",
"arr",
".",
"unshift",
"(",
"new",
"nodes",
".",
"Literal",
"(",
"scope",
"+",
"' '",
")",
")",
";",
"if",
"(",
"arr",
".",
"length",
")",
"{",
"selector",
"=",
"new",
"nodes",
".",
"Selector",
"(",
"arr",
")",
";",
"selector",
".",
"lineno",
"=",
"arr",
"[",
"0",
"]",
".",
"lineno",
";",
"selector",
".",
"column",
"=",
"arr",
"[",
"0",
"]",
".",
"column",
";",
"group",
".",
"push",
"(",
"selector",
")",
";",
"}",
"}",
"while",
"(",
"this",
".",
"accept",
"(",
"','",
")",
"||",
"this",
".",
"accept",
"(",
"'newline'",
")",
")",
";",
"if",
"(",
"'selector-parts'",
"==",
"this",
".",
"currentState",
"(",
")",
")",
"return",
"group",
".",
"nodes",
";",
"this",
".",
"state",
".",
"push",
"(",
"'selector'",
")",
";",
"group",
".",
"block",
"=",
"this",
".",
"block",
"(",
"group",
")",
";",
"this",
".",
"state",
".",
"pop",
"(",
")",
";",
"return",
"group",
";",
"}"
] | selector ',' selector
| selector newline selector
| selector block | [
"selector",
"selector",
"|",
"selector",
"newline",
"selector",
"|",
"selector",
"block"
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/parser.js#L1594-L1624 |
|
5,905 | stylus/stylus | lib/parser.js | function() {
var parens = 1
, i = 2
, tok;
// Lookahead and determine if we are dealing
// with a function call or definition. Here
// we pair parens to prevent false negatives
out:
while (tok = this.lookahead(i++)) {
switch (tok.type) {
case 'function':
case '(':
++parens;
break;
case ')':
if (!--parens) break out;
break;
case 'eos':
this.error('failed to find closing paren ")"');
}
}
// Definition or call
switch (this.currentState()) {
case 'expression':
return this.functionCall();
default:
return this.looksLikeFunctionDefinition(i)
? this.functionDefinition()
: this.expression();
}
} | javascript | function() {
var parens = 1
, i = 2
, tok;
// Lookahead and determine if we are dealing
// with a function call or definition. Here
// we pair parens to prevent false negatives
out:
while (tok = this.lookahead(i++)) {
switch (tok.type) {
case 'function':
case '(':
++parens;
break;
case ')':
if (!--parens) break out;
break;
case 'eos':
this.error('failed to find closing paren ")"');
}
}
// Definition or call
switch (this.currentState()) {
case 'expression':
return this.functionCall();
default:
return this.looksLikeFunctionDefinition(i)
? this.functionDefinition()
: this.expression();
}
} | [
"function",
"(",
")",
"{",
"var",
"parens",
"=",
"1",
",",
"i",
"=",
"2",
",",
"tok",
";",
"// Lookahead and determine if we are dealing",
"// with a function call or definition. Here",
"// we pair parens to prevent false negatives",
"out",
":",
"while",
"(",
"tok",
"=",
"this",
".",
"lookahead",
"(",
"i",
"++",
")",
")",
"{",
"switch",
"(",
"tok",
".",
"type",
")",
"{",
"case",
"'function'",
":",
"case",
"'('",
":",
"++",
"parens",
";",
"break",
";",
"case",
"')'",
":",
"if",
"(",
"!",
"--",
"parens",
")",
"break",
"out",
";",
"break",
";",
"case",
"'eos'",
":",
"this",
".",
"error",
"(",
"'failed to find closing paren \")\"'",
")",
";",
"}",
"}",
"// Definition or call",
"switch",
"(",
"this",
".",
"currentState",
"(",
")",
")",
"{",
"case",
"'expression'",
":",
"return",
"this",
".",
"functionCall",
"(",
")",
";",
"default",
":",
"return",
"this",
".",
"looksLikeFunctionDefinition",
"(",
"i",
")",
"?",
"this",
".",
"functionDefinition",
"(",
")",
":",
"this",
".",
"expression",
"(",
")",
";",
"}",
"}"
] | definition
| call | [
"definition",
"|",
"call"
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/parser.js#L1729-L1761 |
|
5,906 | stylus/stylus | lib/parser.js | function() {
var tok
, node
, params = new nodes.Params;
while (tok = this.accept('ident')) {
this.accept('space');
params.push(node = tok.val);
if (this.accept('...')) {
node.rest = true;
} else if (this.accept('=')) {
node.val = this.expression();
}
this.skipWhitespace();
this.accept(',');
this.skipWhitespace();
}
return params;
} | javascript | function() {
var tok
, node
, params = new nodes.Params;
while (tok = this.accept('ident')) {
this.accept('space');
params.push(node = tok.val);
if (this.accept('...')) {
node.rest = true;
} else if (this.accept('=')) {
node.val = this.expression();
}
this.skipWhitespace();
this.accept(',');
this.skipWhitespace();
}
return params;
} | [
"function",
"(",
")",
"{",
"var",
"tok",
",",
"node",
",",
"params",
"=",
"new",
"nodes",
".",
"Params",
";",
"while",
"(",
"tok",
"=",
"this",
".",
"accept",
"(",
"'ident'",
")",
")",
"{",
"this",
".",
"accept",
"(",
"'space'",
")",
";",
"params",
".",
"push",
"(",
"node",
"=",
"tok",
".",
"val",
")",
";",
"if",
"(",
"this",
".",
"accept",
"(",
"'...'",
")",
")",
"{",
"node",
".",
"rest",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"this",
".",
"accept",
"(",
"'='",
")",
")",
"{",
"node",
".",
"val",
"=",
"this",
".",
"expression",
"(",
")",
";",
"}",
"this",
".",
"skipWhitespace",
"(",
")",
";",
"this",
".",
"accept",
"(",
"','",
")",
";",
"this",
".",
"skipWhitespace",
"(",
")",
";",
"}",
"return",
"params",
";",
"}"
] | ident
| ident '...'
| ident '=' expression
| ident ',' ident | [
"ident",
"|",
"ident",
"...",
"|",
"ident",
"=",
"expression",
"|",
"ident",
"ident"
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/parser.js#L1835-L1852 |
|
5,907 | stylus/stylus | lib/parser.js | function() {
var node = this.unary();
if (this.accept('is defined')) {
if (!node) this.error('illegal unary "is defined", missing left-hand operand');
node = new nodes.BinOp('is defined', node);
}
return node;
} | javascript | function() {
var node = this.unary();
if (this.accept('is defined')) {
if (!node) this.error('illegal unary "is defined", missing left-hand operand');
node = new nodes.BinOp('is defined', node);
}
return node;
} | [
"function",
"(",
")",
"{",
"var",
"node",
"=",
"this",
".",
"unary",
"(",
")",
";",
"if",
"(",
"this",
".",
"accept",
"(",
"'is defined'",
")",
")",
"{",
"if",
"(",
"!",
"node",
")",
"this",
".",
"error",
"(",
"'illegal unary \"is defined\", missing left-hand operand'",
")",
";",
"node",
"=",
"new",
"nodes",
".",
"BinOp",
"(",
"'is defined'",
",",
"node",
")",
";",
"}",
"return",
"node",
";",
"}"
] | unary 'is defined'
| unary | [
"unary",
"is",
"defined",
"|",
"unary"
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/parser.js#L2087-L2094 |
|
5,908 | stylus/stylus | lib/functions/adjust.js | adjust | function adjust(color, prop, amount){
utils.assertColor(color, 'color');
utils.assertString(prop, 'prop');
utils.assertType(amount, 'unit', 'amount');
var hsl = color.hsla.clone();
prop = { hue: 'h', saturation: 's', lightness: 'l' }[prop.string];
if (!prop) throw new Error('invalid adjustment property');
var val = amount.val;
if ('%' == amount.type){
val = 'l' == prop && val > 0
? (100 - hsl[prop]) * val / 100
: hsl[prop] * (val / 100);
}
hsl[prop] += val;
return hsl.rgba;
} | javascript | function adjust(color, prop, amount){
utils.assertColor(color, 'color');
utils.assertString(prop, 'prop');
utils.assertType(amount, 'unit', 'amount');
var hsl = color.hsla.clone();
prop = { hue: 'h', saturation: 's', lightness: 'l' }[prop.string];
if (!prop) throw new Error('invalid adjustment property');
var val = amount.val;
if ('%' == amount.type){
val = 'l' == prop && val > 0
? (100 - hsl[prop]) * val / 100
: hsl[prop] * (val / 100);
}
hsl[prop] += val;
return hsl.rgba;
} | [
"function",
"adjust",
"(",
"color",
",",
"prop",
",",
"amount",
")",
"{",
"utils",
".",
"assertColor",
"(",
"color",
",",
"'color'",
")",
";",
"utils",
".",
"assertString",
"(",
"prop",
",",
"'prop'",
")",
";",
"utils",
".",
"assertType",
"(",
"amount",
",",
"'unit'",
",",
"'amount'",
")",
";",
"var",
"hsl",
"=",
"color",
".",
"hsla",
".",
"clone",
"(",
")",
";",
"prop",
"=",
"{",
"hue",
":",
"'h'",
",",
"saturation",
":",
"'s'",
",",
"lightness",
":",
"'l'",
"}",
"[",
"prop",
".",
"string",
"]",
";",
"if",
"(",
"!",
"prop",
")",
"throw",
"new",
"Error",
"(",
"'invalid adjustment property'",
")",
";",
"var",
"val",
"=",
"amount",
".",
"val",
";",
"if",
"(",
"'%'",
"==",
"amount",
".",
"type",
")",
"{",
"val",
"=",
"'l'",
"==",
"prop",
"&&",
"val",
">",
"0",
"?",
"(",
"100",
"-",
"hsl",
"[",
"prop",
"]",
")",
"*",
"val",
"/",
"100",
":",
"hsl",
"[",
"prop",
"]",
"*",
"(",
"val",
"/",
"100",
")",
";",
"}",
"hsl",
"[",
"prop",
"]",
"+=",
"val",
";",
"return",
"hsl",
".",
"rgba",
";",
"}"
] | Adjust HSL `color` `prop` by `amount`.
@param {RGBA|HSLA} color
@param {String} prop
@param {Unit} amount
@return {RGBA}
@api private | [
"Adjust",
"HSL",
"color",
"prop",
"by",
"amount",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/adjust.js#L13-L28 |
5,909 | stylus/stylus | lib/functions/green.js | green | function green(color, value){
color = color.rgba;
if (value) {
return rgba(
new nodes.Unit(color.r),
value,
new nodes.Unit(color.b),
new nodes.Unit(color.a)
);
}
return new nodes.Unit(color.g, '');
} | javascript | function green(color, value){
color = color.rgba;
if (value) {
return rgba(
new nodes.Unit(color.r),
value,
new nodes.Unit(color.b),
new nodes.Unit(color.a)
);
}
return new nodes.Unit(color.g, '');
} | [
"function",
"green",
"(",
"color",
",",
"value",
")",
"{",
"color",
"=",
"color",
".",
"rgba",
";",
"if",
"(",
"value",
")",
"{",
"return",
"rgba",
"(",
"new",
"nodes",
".",
"Unit",
"(",
"color",
".",
"r",
")",
",",
"value",
",",
"new",
"nodes",
".",
"Unit",
"(",
"color",
".",
"b",
")",
",",
"new",
"nodes",
".",
"Unit",
"(",
"color",
".",
"a",
")",
")",
";",
"}",
"return",
"new",
"nodes",
".",
"Unit",
"(",
"color",
".",
"g",
",",
"''",
")",
";",
"}"
] | Return the green component of the given `color`,
or set the green component to the optional second `value` argument.
Examples:
green(#0c0)
// => 204
green(#000, 255)
// => #0f0
@param {RGBA|HSLA} color
@param {Unit} [value]
@return {Unit|RGBA}
@api public | [
"Return",
"the",
"green",
"component",
"of",
"the",
"given",
"color",
"or",
"set",
"the",
"green",
"component",
"to",
"the",
"optional",
"second",
"value",
"argument",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/green.js#L22-L33 |
5,910 | stylus/stylus | lib/functions/transparentify.js | transparentify | function transparentify(top, bottom, alpha){
utils.assertColor(top);
top = top.rgba;
// Handle default arguments
bottom = bottom || new nodes.RGBA(255, 255, 255, 1);
if (!alpha && bottom && !bottom.rgba) {
alpha = bottom;
bottom = new nodes.RGBA(255, 255, 255, 1);
}
utils.assertColor(bottom);
bottom = bottom.rgba;
var bestAlpha = ['r', 'g', 'b'].map(function(channel){
return (top[channel] - bottom[channel]) / ((0 < (top[channel] - bottom[channel]) ? 255 : 0) - bottom[channel]);
}).sort(function(a, b){return b - a;})[0];
if (alpha) {
utils.assertType(alpha, 'unit', 'alpha');
if ('%' == alpha.type) {
bestAlpha = alpha.val / 100;
} else if (!alpha.type) {
bestAlpha = alpha = alpha.val;
}
}
bestAlpha = Math.max(Math.min(bestAlpha, 1), 0);
// Calculate the resulting color
function processChannel(channel) {
if (0 == bestAlpha) {
return bottom[channel]
} else {
return bottom[channel] + (top[channel] - bottom[channel]) / bestAlpha
}
}
return new nodes.RGBA(
processChannel('r'),
processChannel('g'),
processChannel('b'),
Math.round(bestAlpha * 100) / 100
);
} | javascript | function transparentify(top, bottom, alpha){
utils.assertColor(top);
top = top.rgba;
// Handle default arguments
bottom = bottom || new nodes.RGBA(255, 255, 255, 1);
if (!alpha && bottom && !bottom.rgba) {
alpha = bottom;
bottom = new nodes.RGBA(255, 255, 255, 1);
}
utils.assertColor(bottom);
bottom = bottom.rgba;
var bestAlpha = ['r', 'g', 'b'].map(function(channel){
return (top[channel] - bottom[channel]) / ((0 < (top[channel] - bottom[channel]) ? 255 : 0) - bottom[channel]);
}).sort(function(a, b){return b - a;})[0];
if (alpha) {
utils.assertType(alpha, 'unit', 'alpha');
if ('%' == alpha.type) {
bestAlpha = alpha.val / 100;
} else if (!alpha.type) {
bestAlpha = alpha = alpha.val;
}
}
bestAlpha = Math.max(Math.min(bestAlpha, 1), 0);
// Calculate the resulting color
function processChannel(channel) {
if (0 == bestAlpha) {
return bottom[channel]
} else {
return bottom[channel] + (top[channel] - bottom[channel]) / bestAlpha
}
}
return new nodes.RGBA(
processChannel('r'),
processChannel('g'),
processChannel('b'),
Math.round(bestAlpha * 100) / 100
);
} | [
"function",
"transparentify",
"(",
"top",
",",
"bottom",
",",
"alpha",
")",
"{",
"utils",
".",
"assertColor",
"(",
"top",
")",
";",
"top",
"=",
"top",
".",
"rgba",
";",
"// Handle default arguments",
"bottom",
"=",
"bottom",
"||",
"new",
"nodes",
".",
"RGBA",
"(",
"255",
",",
"255",
",",
"255",
",",
"1",
")",
";",
"if",
"(",
"!",
"alpha",
"&&",
"bottom",
"&&",
"!",
"bottom",
".",
"rgba",
")",
"{",
"alpha",
"=",
"bottom",
";",
"bottom",
"=",
"new",
"nodes",
".",
"RGBA",
"(",
"255",
",",
"255",
",",
"255",
",",
"1",
")",
";",
"}",
"utils",
".",
"assertColor",
"(",
"bottom",
")",
";",
"bottom",
"=",
"bottom",
".",
"rgba",
";",
"var",
"bestAlpha",
"=",
"[",
"'r'",
",",
"'g'",
",",
"'b'",
"]",
".",
"map",
"(",
"function",
"(",
"channel",
")",
"{",
"return",
"(",
"top",
"[",
"channel",
"]",
"-",
"bottom",
"[",
"channel",
"]",
")",
"/",
"(",
"(",
"0",
"<",
"(",
"top",
"[",
"channel",
"]",
"-",
"bottom",
"[",
"channel",
"]",
")",
"?",
"255",
":",
"0",
")",
"-",
"bottom",
"[",
"channel",
"]",
")",
";",
"}",
")",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"b",
"-",
"a",
";",
"}",
")",
"[",
"0",
"]",
";",
"if",
"(",
"alpha",
")",
"{",
"utils",
".",
"assertType",
"(",
"alpha",
",",
"'unit'",
",",
"'alpha'",
")",
";",
"if",
"(",
"'%'",
"==",
"alpha",
".",
"type",
")",
"{",
"bestAlpha",
"=",
"alpha",
".",
"val",
"/",
"100",
";",
"}",
"else",
"if",
"(",
"!",
"alpha",
".",
"type",
")",
"{",
"bestAlpha",
"=",
"alpha",
"=",
"alpha",
".",
"val",
";",
"}",
"}",
"bestAlpha",
"=",
"Math",
".",
"max",
"(",
"Math",
".",
"min",
"(",
"bestAlpha",
",",
"1",
")",
",",
"0",
")",
";",
"// Calculate the resulting color",
"function",
"processChannel",
"(",
"channel",
")",
"{",
"if",
"(",
"0",
"==",
"bestAlpha",
")",
"{",
"return",
"bottom",
"[",
"channel",
"]",
"}",
"else",
"{",
"return",
"bottom",
"[",
"channel",
"]",
"+",
"(",
"top",
"[",
"channel",
"]",
"-",
"bottom",
"[",
"channel",
"]",
")",
"/",
"bestAlpha",
"}",
"}",
"return",
"new",
"nodes",
".",
"RGBA",
"(",
"processChannel",
"(",
"'r'",
")",
",",
"processChannel",
"(",
"'g'",
")",
",",
"processChannel",
"(",
"'b'",
")",
",",
"Math",
".",
"round",
"(",
"bestAlpha",
"*",
"100",
")",
"/",
"100",
")",
";",
"}"
] | Returns the transparent version of the given `top` color,
as if it was blend over the given `bottom` color.
Examples:
transparentify(#808080)
=> rgba(0,0,0,0.5)
transparentify(#414141, #000)
=> rgba(255,255,255,0.25)
transparentify(#91974C, #F34949, 0.5)
=> rgba(47,229,79,0.5)
@param {RGBA|HSLA} top
@param {RGBA|HSLA} [bottom=#fff]
@param {Unit} [alpha]
@return {RGBA}
@api public | [
"Returns",
"the",
"transparent",
"version",
"of",
"the",
"given",
"top",
"color",
"as",
"if",
"it",
"was",
"blend",
"over",
"the",
"given",
"bottom",
"color",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/transparentify.js#L26-L63 |
5,911 | stylus/stylus | lib/functions/transparentify.js | processChannel | function processChannel(channel) {
if (0 == bestAlpha) {
return bottom[channel]
} else {
return bottom[channel] + (top[channel] - bottom[channel]) / bestAlpha
}
} | javascript | function processChannel(channel) {
if (0 == bestAlpha) {
return bottom[channel]
} else {
return bottom[channel] + (top[channel] - bottom[channel]) / bestAlpha
}
} | [
"function",
"processChannel",
"(",
"channel",
")",
"{",
"if",
"(",
"0",
"==",
"bestAlpha",
")",
"{",
"return",
"bottom",
"[",
"channel",
"]",
"}",
"else",
"{",
"return",
"bottom",
"[",
"channel",
"]",
"+",
"(",
"top",
"[",
"channel",
"]",
"-",
"bottom",
"[",
"channel",
"]",
")",
"/",
"bestAlpha",
"}",
"}"
] | Calculate the resulting color | [
"Calculate",
"the",
"resulting",
"color"
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/transparentify.js#L50-L56 |
5,912 | stylus/stylus | lib/functions/selector-exists.js | selectorExists | function selectorExists(sel) {
utils.assertString(sel, 'selector');
if (!this.__selectorsMap__) {
var Normalizer = require('../visitor/normalizer')
, visitor = new Normalizer(this.root.clone());
visitor.visit(visitor.root);
this.__selectorsMap__ = visitor.map;
}
return sel.string in this.__selectorsMap__;
} | javascript | function selectorExists(sel) {
utils.assertString(sel, 'selector');
if (!this.__selectorsMap__) {
var Normalizer = require('../visitor/normalizer')
, visitor = new Normalizer(this.root.clone());
visitor.visit(visitor.root);
this.__selectorsMap__ = visitor.map;
}
return sel.string in this.__selectorsMap__;
} | [
"function",
"selectorExists",
"(",
"sel",
")",
"{",
"utils",
".",
"assertString",
"(",
"sel",
",",
"'selector'",
")",
";",
"if",
"(",
"!",
"this",
".",
"__selectorsMap__",
")",
"{",
"var",
"Normalizer",
"=",
"require",
"(",
"'../visitor/normalizer'",
")",
",",
"visitor",
"=",
"new",
"Normalizer",
"(",
"this",
".",
"root",
".",
"clone",
"(",
")",
")",
";",
"visitor",
".",
"visit",
"(",
"visitor",
".",
"root",
")",
";",
"this",
".",
"__selectorsMap__",
"=",
"visitor",
".",
"map",
";",
"}",
"return",
"sel",
".",
"string",
"in",
"this",
".",
"__selectorsMap__",
";",
"}"
] | Returns true if the given selector exists.
@param {String} sel
@return {Boolean}
@api public | [
"Returns",
"true",
"if",
"the",
"given",
"selector",
"exists",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/selector-exists.js#L11-L23 |
5,913 | stylus/stylus | lib/functions/remove.js | remove | function remove(object, key){
utils.assertType(object, 'object', 'object');
utils.assertString(key, 'key');
delete object.vals[key.string];
return object;
} | javascript | function remove(object, key){
utils.assertType(object, 'object', 'object');
utils.assertString(key, 'key');
delete object.vals[key.string];
return object;
} | [
"function",
"remove",
"(",
"object",
",",
"key",
")",
"{",
"utils",
".",
"assertType",
"(",
"object",
",",
"'object'",
",",
"'object'",
")",
";",
"utils",
".",
"assertString",
"(",
"key",
",",
"'key'",
")",
";",
"delete",
"object",
".",
"vals",
"[",
"key",
".",
"string",
"]",
";",
"return",
"object",
";",
"}"
] | Remove the given `key` from the `object`.
@param {Object} object
@param {String} key
@return {Object}
@api public | [
"Remove",
"the",
"given",
"key",
"from",
"the",
"object",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/remove.js#L12-L17 |
5,914 | stylus/stylus | lib/nodes/node.js | CoercionError | function CoercionError(msg) {
this.name = 'CoercionError'
this.message = msg
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CoercionError);
}
} | javascript | function CoercionError(msg) {
this.name = 'CoercionError'
this.message = msg
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CoercionError);
}
} | [
"function",
"CoercionError",
"(",
"msg",
")",
"{",
"this",
".",
"name",
"=",
"'CoercionError'",
"this",
".",
"message",
"=",
"msg",
"if",
"(",
"Error",
".",
"captureStackTrace",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"CoercionError",
")",
";",
"}",
"}"
] | Initialize a new `CoercionError` with the given `msg`.
@param {String} msg
@api private | [
"Initialize",
"a",
"new",
"CoercionError",
"with",
"the",
"given",
"msg",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/nodes/node.js#L23-L29 |
5,915 | stylus/stylus | lib/nodes/node.js | function(op, right){
switch (op) {
case 'is a':
if ('string' == right.first.nodeName) {
return nodes.Boolean(this.nodeName == right.val);
} else {
throw new Error('"is a" expects a string, got ' + right.toString());
}
case '==':
return nodes.Boolean(this.hash == right.hash);
case '!=':
return nodes.Boolean(this.hash != right.hash);
case '>=':
return nodes.Boolean(this.hash >= right.hash);
case '<=':
return nodes.Boolean(this.hash <= right.hash);
case '>':
return nodes.Boolean(this.hash > right.hash);
case '<':
return nodes.Boolean(this.hash < right.hash);
case '||':
return this.toBoolean().isTrue
? this
: right;
case 'in':
var vals = utils.unwrap(right).nodes
, len = vals && vals.length
, hash = this.hash;
if (!vals) throw new Error('"in" given invalid right-hand operand, expecting an expression');
// 'prop' in obj
if (1 == len && 'object' == vals[0].nodeName) {
return nodes.Boolean(vals[0].has(this.hash));
}
for (var i = 0; i < len; ++i) {
if (hash == vals[i].hash) {
return nodes.true;
}
}
return nodes.false;
case '&&':
var a = this.toBoolean()
, b = right.toBoolean();
return a.isTrue && b.isTrue
? right
: a.isFalse
? this
: right;
default:
if ('[]' == op) {
var msg = 'cannot perform '
+ this
+ '[' + right + ']';
} else {
var msg = 'cannot perform'
+ ' ' + this
+ ' ' + op
+ ' ' + right;
}
throw new Error(msg);
}
} | javascript | function(op, right){
switch (op) {
case 'is a':
if ('string' == right.first.nodeName) {
return nodes.Boolean(this.nodeName == right.val);
} else {
throw new Error('"is a" expects a string, got ' + right.toString());
}
case '==':
return nodes.Boolean(this.hash == right.hash);
case '!=':
return nodes.Boolean(this.hash != right.hash);
case '>=':
return nodes.Boolean(this.hash >= right.hash);
case '<=':
return nodes.Boolean(this.hash <= right.hash);
case '>':
return nodes.Boolean(this.hash > right.hash);
case '<':
return nodes.Boolean(this.hash < right.hash);
case '||':
return this.toBoolean().isTrue
? this
: right;
case 'in':
var vals = utils.unwrap(right).nodes
, len = vals && vals.length
, hash = this.hash;
if (!vals) throw new Error('"in" given invalid right-hand operand, expecting an expression');
// 'prop' in obj
if (1 == len && 'object' == vals[0].nodeName) {
return nodes.Boolean(vals[0].has(this.hash));
}
for (var i = 0; i < len; ++i) {
if (hash == vals[i].hash) {
return nodes.true;
}
}
return nodes.false;
case '&&':
var a = this.toBoolean()
, b = right.toBoolean();
return a.isTrue && b.isTrue
? right
: a.isFalse
? this
: right;
default:
if ('[]' == op) {
var msg = 'cannot perform '
+ this
+ '[' + right + ']';
} else {
var msg = 'cannot perform'
+ ' ' + this
+ ' ' + op
+ ' ' + right;
}
throw new Error(msg);
}
} | [
"function",
"(",
"op",
",",
"right",
")",
"{",
"switch",
"(",
"op",
")",
"{",
"case",
"'is a'",
":",
"if",
"(",
"'string'",
"==",
"right",
".",
"first",
".",
"nodeName",
")",
"{",
"return",
"nodes",
".",
"Boolean",
"(",
"this",
".",
"nodeName",
"==",
"right",
".",
"val",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'\"is a\" expects a string, got '",
"+",
"right",
".",
"toString",
"(",
")",
")",
";",
"}",
"case",
"'=='",
":",
"return",
"nodes",
".",
"Boolean",
"(",
"this",
".",
"hash",
"==",
"right",
".",
"hash",
")",
";",
"case",
"'!='",
":",
"return",
"nodes",
".",
"Boolean",
"(",
"this",
".",
"hash",
"!=",
"right",
".",
"hash",
")",
";",
"case",
"'>='",
":",
"return",
"nodes",
".",
"Boolean",
"(",
"this",
".",
"hash",
">=",
"right",
".",
"hash",
")",
";",
"case",
"'<='",
":",
"return",
"nodes",
".",
"Boolean",
"(",
"this",
".",
"hash",
"<=",
"right",
".",
"hash",
")",
";",
"case",
"'>'",
":",
"return",
"nodes",
".",
"Boolean",
"(",
"this",
".",
"hash",
">",
"right",
".",
"hash",
")",
";",
"case",
"'<'",
":",
"return",
"nodes",
".",
"Boolean",
"(",
"this",
".",
"hash",
"<",
"right",
".",
"hash",
")",
";",
"case",
"'||'",
":",
"return",
"this",
".",
"toBoolean",
"(",
")",
".",
"isTrue",
"?",
"this",
":",
"right",
";",
"case",
"'in'",
":",
"var",
"vals",
"=",
"utils",
".",
"unwrap",
"(",
"right",
")",
".",
"nodes",
",",
"len",
"=",
"vals",
"&&",
"vals",
".",
"length",
",",
"hash",
"=",
"this",
".",
"hash",
";",
"if",
"(",
"!",
"vals",
")",
"throw",
"new",
"Error",
"(",
"'\"in\" given invalid right-hand operand, expecting an expression'",
")",
";",
"// 'prop' in obj",
"if",
"(",
"1",
"==",
"len",
"&&",
"'object'",
"==",
"vals",
"[",
"0",
"]",
".",
"nodeName",
")",
"{",
"return",
"nodes",
".",
"Boolean",
"(",
"vals",
"[",
"0",
"]",
".",
"has",
"(",
"this",
".",
"hash",
")",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"if",
"(",
"hash",
"==",
"vals",
"[",
"i",
"]",
".",
"hash",
")",
"{",
"return",
"nodes",
".",
"true",
";",
"}",
"}",
"return",
"nodes",
".",
"false",
";",
"case",
"'&&'",
":",
"var",
"a",
"=",
"this",
".",
"toBoolean",
"(",
")",
",",
"b",
"=",
"right",
".",
"toBoolean",
"(",
")",
";",
"return",
"a",
".",
"isTrue",
"&&",
"b",
".",
"isTrue",
"?",
"right",
":",
"a",
".",
"isFalse",
"?",
"this",
":",
"right",
";",
"default",
":",
"if",
"(",
"'[]'",
"==",
"op",
")",
"{",
"var",
"msg",
"=",
"'cannot perform '",
"+",
"this",
"+",
"'['",
"+",
"right",
"+",
"']'",
";",
"}",
"else",
"{",
"var",
"msg",
"=",
"'cannot perform'",
"+",
"' '",
"+",
"this",
"+",
"' '",
"+",
"op",
"+",
"' '",
"+",
"right",
";",
"}",
"throw",
"new",
"Error",
"(",
"msg",
")",
";",
"}",
"}"
] | Operate on `right` with the given `op`.
@param {String} op
@param {Node} right
@return {Node}
@api public | [
"Operate",
"on",
"right",
"with",
"the",
"given",
"op",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/nodes/node.js#L176-L238 |
|
5,916 | stylus/stylus | lib/convert/css.js | Converter | function Converter(css) {
var parse = require('css-parse');
this.css = css;
this.root = parse(css, { position: false });
this.indents = 0;
} | javascript | function Converter(css) {
var parse = require('css-parse');
this.css = css;
this.root = parse(css, { position: false });
this.indents = 0;
} | [
"function",
"Converter",
"(",
"css",
")",
"{",
"var",
"parse",
"=",
"require",
"(",
"'css-parse'",
")",
";",
"this",
".",
"css",
"=",
"css",
";",
"this",
".",
"root",
"=",
"parse",
"(",
"css",
",",
"{",
"position",
":",
"false",
"}",
")",
";",
"this",
".",
"indents",
"=",
"0",
";",
"}"
] | Initialize a new `Converter` with the given `css`.
@param {String} css
@api private | [
"Initialize",
"a",
"new",
"Converter",
"with",
"the",
"given",
"css",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/convert/css.js#L26-L31 |
5,917 | stylus/stylus | lib/functions/hsla.js | hsla | function hsla(hue, saturation, lightness, alpha){
switch (arguments.length) {
case 1:
utils.assertColor(hue);
return hue.hsla;
case 2:
utils.assertColor(hue);
var color = hue.hsla;
utils.assertType(saturation, 'unit', 'alpha');
var alpha = saturation.clone();
if ('%' == alpha.type) alpha.val /= 100;
return new nodes.HSLA(
color.h
, color.s
, color.l
, alpha.val);
default:
utils.assertType(hue, 'unit', 'hue');
utils.assertType(saturation, 'unit', 'saturation');
utils.assertType(lightness, 'unit', 'lightness');
utils.assertType(alpha, 'unit', 'alpha');
var alpha = alpha.clone();
if (alpha && '%' == alpha.type) alpha.val /= 100;
return new nodes.HSLA(
hue.val
, saturation.val
, lightness.val
, alpha.val);
}
} | javascript | function hsla(hue, saturation, lightness, alpha){
switch (arguments.length) {
case 1:
utils.assertColor(hue);
return hue.hsla;
case 2:
utils.assertColor(hue);
var color = hue.hsla;
utils.assertType(saturation, 'unit', 'alpha');
var alpha = saturation.clone();
if ('%' == alpha.type) alpha.val /= 100;
return new nodes.HSLA(
color.h
, color.s
, color.l
, alpha.val);
default:
utils.assertType(hue, 'unit', 'hue');
utils.assertType(saturation, 'unit', 'saturation');
utils.assertType(lightness, 'unit', 'lightness');
utils.assertType(alpha, 'unit', 'alpha');
var alpha = alpha.clone();
if (alpha && '%' == alpha.type) alpha.val /= 100;
return new nodes.HSLA(
hue.val
, saturation.val
, lightness.val
, alpha.val);
}
} | [
"function",
"hsla",
"(",
"hue",
",",
"saturation",
",",
"lightness",
",",
"alpha",
")",
"{",
"switch",
"(",
"arguments",
".",
"length",
")",
"{",
"case",
"1",
":",
"utils",
".",
"assertColor",
"(",
"hue",
")",
";",
"return",
"hue",
".",
"hsla",
";",
"case",
"2",
":",
"utils",
".",
"assertColor",
"(",
"hue",
")",
";",
"var",
"color",
"=",
"hue",
".",
"hsla",
";",
"utils",
".",
"assertType",
"(",
"saturation",
",",
"'unit'",
",",
"'alpha'",
")",
";",
"var",
"alpha",
"=",
"saturation",
".",
"clone",
"(",
")",
";",
"if",
"(",
"'%'",
"==",
"alpha",
".",
"type",
")",
"alpha",
".",
"val",
"/=",
"100",
";",
"return",
"new",
"nodes",
".",
"HSLA",
"(",
"color",
".",
"h",
",",
"color",
".",
"s",
",",
"color",
".",
"l",
",",
"alpha",
".",
"val",
")",
";",
"default",
":",
"utils",
".",
"assertType",
"(",
"hue",
",",
"'unit'",
",",
"'hue'",
")",
";",
"utils",
".",
"assertType",
"(",
"saturation",
",",
"'unit'",
",",
"'saturation'",
")",
";",
"utils",
".",
"assertType",
"(",
"lightness",
",",
"'unit'",
",",
"'lightness'",
")",
";",
"utils",
".",
"assertType",
"(",
"alpha",
",",
"'unit'",
",",
"'alpha'",
")",
";",
"var",
"alpha",
"=",
"alpha",
".",
"clone",
"(",
")",
";",
"if",
"(",
"alpha",
"&&",
"'%'",
"==",
"alpha",
".",
"type",
")",
"alpha",
".",
"val",
"/=",
"100",
";",
"return",
"new",
"nodes",
".",
"HSLA",
"(",
"hue",
".",
"val",
",",
"saturation",
".",
"val",
",",
"lightness",
".",
"val",
",",
"alpha",
".",
"val",
")",
";",
"}",
"}"
] | Convert the given `color` to an `HSLA` node,
or h,s,l,a component values.
Examples:
hsla(10deg, 50%, 30%, 0.5)
// => HSLA
hsla(#ffcc00)
// => HSLA
@param {RGBA|HSLA|Unit} hue
@param {Unit} saturation
@param {Unit} lightness
@param {Unit} alpha
@return {HSLA}
@api public | [
"Convert",
"the",
"given",
"color",
"to",
"an",
"HSLA",
"node",
"or",
"h",
"s",
"l",
"a",
"component",
"values",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/hsla.js#L24-L53 |
5,918 | stylus/stylus | lib/functions/rgb.js | rgb | function rgb(red, green, blue){
switch (arguments.length) {
case 1:
utils.assertColor(red);
var color = red.rgba;
return new nodes.RGBA(
color.r
, color.g
, color.b
, 1);
default:
return rgba(
red
, green
, blue
, new nodes.Unit(1));
}
} | javascript | function rgb(red, green, blue){
switch (arguments.length) {
case 1:
utils.assertColor(red);
var color = red.rgba;
return new nodes.RGBA(
color.r
, color.g
, color.b
, 1);
default:
return rgba(
red
, green
, blue
, new nodes.Unit(1));
}
} | [
"function",
"rgb",
"(",
"red",
",",
"green",
",",
"blue",
")",
"{",
"switch",
"(",
"arguments",
".",
"length",
")",
"{",
"case",
"1",
":",
"utils",
".",
"assertColor",
"(",
"red",
")",
";",
"var",
"color",
"=",
"red",
".",
"rgba",
";",
"return",
"new",
"nodes",
".",
"RGBA",
"(",
"color",
".",
"r",
",",
"color",
".",
"g",
",",
"color",
".",
"b",
",",
"1",
")",
";",
"default",
":",
"return",
"rgba",
"(",
"red",
",",
"green",
",",
"blue",
",",
"new",
"nodes",
".",
"Unit",
"(",
"1",
")",
")",
";",
"}",
"}"
] | Return a `RGBA` from the r,g,b channels.
Examples:
rgb(255,204,0)
// => #ffcc00
rgb(#fff)
// => #fff
@param {Unit|RGBA|HSLA} red
@param {Unit} green
@param {Unit} blue
@return {RGBA}
@api public | [
"Return",
"a",
"RGBA",
"from",
"the",
"r",
"g",
"b",
"channels",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/rgb.js#L23-L40 |
5,919 | stylus/stylus | lib/functions/unit.js | unit | function unit(unit, type){
utils.assertType(unit, 'unit', 'unit');
// Assign
if (type) {
utils.assertString(type, 'type');
return new nodes.Unit(unit.val, type.string);
} else {
return unit.type || '';
}
} | javascript | function unit(unit, type){
utils.assertType(unit, 'unit', 'unit');
// Assign
if (type) {
utils.assertString(type, 'type');
return new nodes.Unit(unit.val, type.string);
} else {
return unit.type || '';
}
} | [
"function",
"unit",
"(",
"unit",
",",
"type",
")",
"{",
"utils",
".",
"assertType",
"(",
"unit",
",",
"'unit'",
",",
"'unit'",
")",
";",
"// Assign",
"if",
"(",
"type",
")",
"{",
"utils",
".",
"assertString",
"(",
"type",
",",
"'type'",
")",
";",
"return",
"new",
"nodes",
".",
"Unit",
"(",
"unit",
".",
"val",
",",
"type",
".",
"string",
")",
";",
"}",
"else",
"{",
"return",
"unit",
".",
"type",
"||",
"''",
";",
"}",
"}"
] | Assign `type` to the given `unit` or return `unit`'s type.
@param {Unit} unit
@param {String|Ident} type
@return {Unit}
@api public | [
"Assign",
"type",
"to",
"the",
"given",
"unit",
"or",
"return",
"unit",
"s",
"type",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/unit.js#L13-L23 |
5,920 | stylus/stylus | lib/functions/hsl.js | hsl | function hsl(hue, saturation, lightness){
if (1 == arguments.length) {
utils.assertColor(hue, 'color');
return hue.hsla;
} else {
return hsla(
hue
, saturation
, lightness
, new nodes.Unit(1));
}
} | javascript | function hsl(hue, saturation, lightness){
if (1 == arguments.length) {
utils.assertColor(hue, 'color');
return hue.hsla;
} else {
return hsla(
hue
, saturation
, lightness
, new nodes.Unit(1));
}
} | [
"function",
"hsl",
"(",
"hue",
",",
"saturation",
",",
"lightness",
")",
"{",
"if",
"(",
"1",
"==",
"arguments",
".",
"length",
")",
"{",
"utils",
".",
"assertColor",
"(",
"hue",
",",
"'color'",
")",
";",
"return",
"hue",
".",
"hsla",
";",
"}",
"else",
"{",
"return",
"hsla",
"(",
"hue",
",",
"saturation",
",",
"lightness",
",",
"new",
"nodes",
".",
"Unit",
"(",
"1",
")",
")",
";",
"}",
"}"
] | Convert the given `color` to an `HSLA` node,
or h,s,l component values.
Examples:
hsl(10, 50, 30)
// => HSLA
hsl(#ffcc00)
// => HSLA
@param {Unit|HSLA|RGBA} hue
@param {Unit} saturation
@param {Unit} lightness
@return {HSLA}
@api public | [
"Convert",
"the",
"given",
"color",
"to",
"an",
"HSLA",
"node",
"or",
"h",
"s",
"l",
"component",
"values",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/hsl.js#L24-L35 |
5,921 | stylus/stylus | lib/functions/lookup.js | lookup | function lookup(name){
utils.assertType(name, 'string', 'name');
var node = this.lookup(name.val);
if (!node) return nodes.null;
return this.visit(node);
} | javascript | function lookup(name){
utils.assertType(name, 'string', 'name');
var node = this.lookup(name.val);
if (!node) return nodes.null;
return this.visit(node);
} | [
"function",
"lookup",
"(",
"name",
")",
"{",
"utils",
".",
"assertType",
"(",
"name",
",",
"'string'",
",",
"'name'",
")",
";",
"var",
"node",
"=",
"this",
".",
"lookup",
"(",
"name",
".",
"val",
")",
";",
"if",
"(",
"!",
"node",
")",
"return",
"nodes",
".",
"null",
";",
"return",
"this",
".",
"visit",
"(",
"node",
")",
";",
"}"
] | Lookup variable `name` or return Null.
@param {String} name
@return {Mixed}
@api public | [
"Lookup",
"variable",
"name",
"or",
"return",
"Null",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/lookup.js#L12-L17 |
5,922 | stylus/stylus | lib/functions/substr.js | substr | function substr(val, start, length){
utils.assertString(val, 'val');
utils.assertType(start, 'unit', 'start');
length = length && length.val;
var res = val.string.substr(start.val, length);
return val instanceof nodes.Ident
? new nodes.Ident(res)
: new nodes.String(res);
} | javascript | function substr(val, start, length){
utils.assertString(val, 'val');
utils.assertType(start, 'unit', 'start');
length = length && length.val;
var res = val.string.substr(start.val, length);
return val instanceof nodes.Ident
? new nodes.Ident(res)
: new nodes.String(res);
} | [
"function",
"substr",
"(",
"val",
",",
"start",
",",
"length",
")",
"{",
"utils",
".",
"assertString",
"(",
"val",
",",
"'val'",
")",
";",
"utils",
".",
"assertType",
"(",
"start",
",",
"'unit'",
",",
"'start'",
")",
";",
"length",
"=",
"length",
"&&",
"length",
".",
"val",
";",
"var",
"res",
"=",
"val",
".",
"string",
".",
"substr",
"(",
"start",
".",
"val",
",",
"length",
")",
";",
"return",
"val",
"instanceof",
"nodes",
".",
"Ident",
"?",
"new",
"nodes",
".",
"Ident",
"(",
"res",
")",
":",
"new",
"nodes",
".",
"String",
"(",
"res",
")",
";",
"}"
] | Returns substring of the given `val`.
@param {String|Ident} val
@param {Number} start
@param {Number} [length]
@return {String|Ident}
@api public | [
"Returns",
"substring",
"of",
"the",
"given",
"val",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/substr.js#L14-L22 |
5,923 | stylus/stylus | lib/functions/image-size.js | imageSize | function imageSize(img, ignoreErr) {
utils.assertType(img, 'string', 'img');
try {
var img = new Image(this, img.string);
} catch (err) {
if (ignoreErr) {
return [new nodes.Unit(0), new nodes.Unit(0)];
} else {
throw err;
}
}
// Read size
img.open();
var size = img.size();
img.close();
// Return (w h)
var expr = [];
expr.push(new nodes.Unit(size[0], 'px'));
expr.push(new nodes.Unit(size[1], 'px'));
return expr;
} | javascript | function imageSize(img, ignoreErr) {
utils.assertType(img, 'string', 'img');
try {
var img = new Image(this, img.string);
} catch (err) {
if (ignoreErr) {
return [new nodes.Unit(0), new nodes.Unit(0)];
} else {
throw err;
}
}
// Read size
img.open();
var size = img.size();
img.close();
// Return (w h)
var expr = [];
expr.push(new nodes.Unit(size[0], 'px'));
expr.push(new nodes.Unit(size[1], 'px'));
return expr;
} | [
"function",
"imageSize",
"(",
"img",
",",
"ignoreErr",
")",
"{",
"utils",
".",
"assertType",
"(",
"img",
",",
"'string'",
",",
"'img'",
")",
";",
"try",
"{",
"var",
"img",
"=",
"new",
"Image",
"(",
"this",
",",
"img",
".",
"string",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"ignoreErr",
")",
"{",
"return",
"[",
"new",
"nodes",
".",
"Unit",
"(",
"0",
")",
",",
"new",
"nodes",
".",
"Unit",
"(",
"0",
")",
"]",
";",
"}",
"else",
"{",
"throw",
"err",
";",
"}",
"}",
"// Read size",
"img",
".",
"open",
"(",
")",
";",
"var",
"size",
"=",
"img",
".",
"size",
"(",
")",
";",
"img",
".",
"close",
"(",
")",
";",
"// Return (w h)",
"var",
"expr",
"=",
"[",
"]",
";",
"expr",
".",
"push",
"(",
"new",
"nodes",
".",
"Unit",
"(",
"size",
"[",
"0",
"]",
",",
"'px'",
")",
")",
";",
"expr",
".",
"push",
"(",
"new",
"nodes",
".",
"Unit",
"(",
"size",
"[",
"1",
"]",
",",
"'px'",
")",
")",
";",
"return",
"expr",
";",
"}"
] | Return the width and height of the given `img` path.
Examples:
image-size('foo.png')
// => 200px 100px
image-size('foo.png')[0]
// => 200px
image-size('foo.png')[1]
// => 100px
Can be used to test if the image exists,
using an optional argument set to `true`
(without this argument this function throws error
if there is no such image).
Example:
image-size('nosuchimage.png', true)[0]
// => 0
@param {String} img
@param {Boolean} ignoreErr
@return {Expression}
@api public | [
"Return",
"the",
"width",
"and",
"height",
"of",
"the",
"given",
"img",
"path",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/image-size.js#L35-L58 |
5,924 | stylus/stylus | lib/functions/saturation.js | saturation | function saturation(color, value){
if (value) {
var hslaColor = color.hsla;
return hsla(
new nodes.Unit(hslaColor.h),
value,
new nodes.Unit(hslaColor.l),
new nodes.Unit(hslaColor.a)
)
}
return component(color, new nodes.String('saturation'));
} | javascript | function saturation(color, value){
if (value) {
var hslaColor = color.hsla;
return hsla(
new nodes.Unit(hslaColor.h),
value,
new nodes.Unit(hslaColor.l),
new nodes.Unit(hslaColor.a)
)
}
return component(color, new nodes.String('saturation'));
} | [
"function",
"saturation",
"(",
"color",
",",
"value",
")",
"{",
"if",
"(",
"value",
")",
"{",
"var",
"hslaColor",
"=",
"color",
".",
"hsla",
";",
"return",
"hsla",
"(",
"new",
"nodes",
".",
"Unit",
"(",
"hslaColor",
".",
"h",
")",
",",
"value",
",",
"new",
"nodes",
".",
"Unit",
"(",
"hslaColor",
".",
"l",
")",
",",
"new",
"nodes",
".",
"Unit",
"(",
"hslaColor",
".",
"a",
")",
")",
"}",
"return",
"component",
"(",
"color",
",",
"new",
"nodes",
".",
"String",
"(",
"'saturation'",
")",
")",
";",
"}"
] | Return the saturation component of the given `color`,
or set the saturation component to the optional second `value` argument.
Examples:
saturation(#00c)
// => 100%
saturation(#00c, 50%)
// => #339
@param {RGBA|HSLA} color
@param {Unit} [value]
@return {Unit|RGBA}
@api public | [
"Return",
"the",
"saturation",
"component",
"of",
"the",
"given",
"color",
"or",
"set",
"the",
"saturation",
"component",
"to",
"the",
"optional",
"second",
"value",
"argument",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/saturation.js#L23-L34 |
5,925 | stylus/stylus | lib/functions/error.js | error | function error(msg){
utils.assertType(msg, 'string', 'msg');
var err = new Error(msg.val);
err.fromStylus = true;
throw err;
} | javascript | function error(msg){
utils.assertType(msg, 'string', 'msg');
var err = new Error(msg.val);
err.fromStylus = true;
throw err;
} | [
"function",
"error",
"(",
"msg",
")",
"{",
"utils",
".",
"assertType",
"(",
"msg",
",",
"'string'",
",",
"'msg'",
")",
";",
"var",
"err",
"=",
"new",
"Error",
"(",
"msg",
".",
"val",
")",
";",
"err",
".",
"fromStylus",
"=",
"true",
";",
"throw",
"err",
";",
"}"
] | Throw an error with the given `msg`.
@param {String} msg
@api public | [
"Throw",
"an",
"error",
"with",
"the",
"given",
"msg",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/error.js#L10-L15 |
5,926 | stylus/stylus | lib/visitor/evaluator.js | importFile | function importFile(node, file, literal) {
var importStack = this.importStack
, Parser = require('../parser')
, stat;
// Handling the `require`
if (node.once) {
if (this.requireHistory[file]) return nodes.null;
this.requireHistory[file] = true;
if (literal && !this.includeCSS) {
return node;
}
}
// Avoid overflows from importing the same file over again
if (~importStack.indexOf(file))
throw new Error('import loop has been found');
var str = fs.readFileSync(file, 'utf8');
// shortcut for empty files
if (!str.trim()) return nodes.null;
// Expose imports
node.path = file;
node.dirname = dirname(file);
// Store the modified time
stat = fs.statSync(file);
node.mtime = stat.mtime;
this.paths.push(node.dirname);
if (this.options._imports) this.options._imports.push(node.clone());
// Parse the file
importStack.push(file);
nodes.filename = file;
if (literal) {
literal = new nodes.Literal(str.replace(/\r\n?/g, '\n'));
literal.lineno = literal.column = 1;
if (!this.resolveURL) return literal;
}
// parse
var block = new nodes.Block
, parser = new Parser(str, utils.merge({ root: block }, this.options));
try {
block = parser.parse();
} catch (err) {
var line = parser.lexer.lineno
, column = parser.lexer.column;
if (literal && this.includeCSS && this.resolveURL) {
this.warn('ParseError: ' + file + ':' + line + ':' + column + '. This file included as-is');
return literal;
} else {
err.filename = file;
err.lineno = line;
err.column = column;
err.input = str;
throw err;
}
}
// Evaluate imported "root"
block = block.clone(this.currentBlock);
block.parent = this.currentBlock;
block.scope = false;
var ret = this.visit(block);
importStack.pop();
if (!this.resolveURL || this.resolveURL.nocheck) this.paths.pop();
return ret;
} | javascript | function importFile(node, file, literal) {
var importStack = this.importStack
, Parser = require('../parser')
, stat;
// Handling the `require`
if (node.once) {
if (this.requireHistory[file]) return nodes.null;
this.requireHistory[file] = true;
if (literal && !this.includeCSS) {
return node;
}
}
// Avoid overflows from importing the same file over again
if (~importStack.indexOf(file))
throw new Error('import loop has been found');
var str = fs.readFileSync(file, 'utf8');
// shortcut for empty files
if (!str.trim()) return nodes.null;
// Expose imports
node.path = file;
node.dirname = dirname(file);
// Store the modified time
stat = fs.statSync(file);
node.mtime = stat.mtime;
this.paths.push(node.dirname);
if (this.options._imports) this.options._imports.push(node.clone());
// Parse the file
importStack.push(file);
nodes.filename = file;
if (literal) {
literal = new nodes.Literal(str.replace(/\r\n?/g, '\n'));
literal.lineno = literal.column = 1;
if (!this.resolveURL) return literal;
}
// parse
var block = new nodes.Block
, parser = new Parser(str, utils.merge({ root: block }, this.options));
try {
block = parser.parse();
} catch (err) {
var line = parser.lexer.lineno
, column = parser.lexer.column;
if (literal && this.includeCSS && this.resolveURL) {
this.warn('ParseError: ' + file + ':' + line + ':' + column + '. This file included as-is');
return literal;
} else {
err.filename = file;
err.lineno = line;
err.column = column;
err.input = str;
throw err;
}
}
// Evaluate imported "root"
block = block.clone(this.currentBlock);
block.parent = this.currentBlock;
block.scope = false;
var ret = this.visit(block);
importStack.pop();
if (!this.resolveURL || this.resolveURL.nocheck) this.paths.pop();
return ret;
} | [
"function",
"importFile",
"(",
"node",
",",
"file",
",",
"literal",
")",
"{",
"var",
"importStack",
"=",
"this",
".",
"importStack",
",",
"Parser",
"=",
"require",
"(",
"'../parser'",
")",
",",
"stat",
";",
"// Handling the `require`",
"if",
"(",
"node",
".",
"once",
")",
"{",
"if",
"(",
"this",
".",
"requireHistory",
"[",
"file",
"]",
")",
"return",
"nodes",
".",
"null",
";",
"this",
".",
"requireHistory",
"[",
"file",
"]",
"=",
"true",
";",
"if",
"(",
"literal",
"&&",
"!",
"this",
".",
"includeCSS",
")",
"{",
"return",
"node",
";",
"}",
"}",
"// Avoid overflows from importing the same file over again",
"if",
"(",
"~",
"importStack",
".",
"indexOf",
"(",
"file",
")",
")",
"throw",
"new",
"Error",
"(",
"'import loop has been found'",
")",
";",
"var",
"str",
"=",
"fs",
".",
"readFileSync",
"(",
"file",
",",
"'utf8'",
")",
";",
"// shortcut for empty files",
"if",
"(",
"!",
"str",
".",
"trim",
"(",
")",
")",
"return",
"nodes",
".",
"null",
";",
"// Expose imports",
"node",
".",
"path",
"=",
"file",
";",
"node",
".",
"dirname",
"=",
"dirname",
"(",
"file",
")",
";",
"// Store the modified time",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"file",
")",
";",
"node",
".",
"mtime",
"=",
"stat",
".",
"mtime",
";",
"this",
".",
"paths",
".",
"push",
"(",
"node",
".",
"dirname",
")",
";",
"if",
"(",
"this",
".",
"options",
".",
"_imports",
")",
"this",
".",
"options",
".",
"_imports",
".",
"push",
"(",
"node",
".",
"clone",
"(",
")",
")",
";",
"// Parse the file",
"importStack",
".",
"push",
"(",
"file",
")",
";",
"nodes",
".",
"filename",
"=",
"file",
";",
"if",
"(",
"literal",
")",
"{",
"literal",
"=",
"new",
"nodes",
".",
"Literal",
"(",
"str",
".",
"replace",
"(",
"/",
"\\r\\n?",
"/",
"g",
",",
"'\\n'",
")",
")",
";",
"literal",
".",
"lineno",
"=",
"literal",
".",
"column",
"=",
"1",
";",
"if",
"(",
"!",
"this",
".",
"resolveURL",
")",
"return",
"literal",
";",
"}",
"// parse",
"var",
"block",
"=",
"new",
"nodes",
".",
"Block",
",",
"parser",
"=",
"new",
"Parser",
"(",
"str",
",",
"utils",
".",
"merge",
"(",
"{",
"root",
":",
"block",
"}",
",",
"this",
".",
"options",
")",
")",
";",
"try",
"{",
"block",
"=",
"parser",
".",
"parse",
"(",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"var",
"line",
"=",
"parser",
".",
"lexer",
".",
"lineno",
",",
"column",
"=",
"parser",
".",
"lexer",
".",
"column",
";",
"if",
"(",
"literal",
"&&",
"this",
".",
"includeCSS",
"&&",
"this",
".",
"resolveURL",
")",
"{",
"this",
".",
"warn",
"(",
"'ParseError: '",
"+",
"file",
"+",
"':'",
"+",
"line",
"+",
"':'",
"+",
"column",
"+",
"'. This file included as-is'",
")",
";",
"return",
"literal",
";",
"}",
"else",
"{",
"err",
".",
"filename",
"=",
"file",
";",
"err",
".",
"lineno",
"=",
"line",
";",
"err",
".",
"column",
"=",
"column",
";",
"err",
".",
"input",
"=",
"str",
";",
"throw",
"err",
";",
"}",
"}",
"// Evaluate imported \"root\"",
"block",
"=",
"block",
".",
"clone",
"(",
"this",
".",
"currentBlock",
")",
";",
"block",
".",
"parent",
"=",
"this",
".",
"currentBlock",
";",
"block",
".",
"scope",
"=",
"false",
";",
"var",
"ret",
"=",
"this",
".",
"visit",
"(",
"block",
")",
";",
"importStack",
".",
"pop",
"(",
")",
";",
"if",
"(",
"!",
"this",
".",
"resolveURL",
"||",
"this",
".",
"resolveURL",
".",
"nocheck",
")",
"this",
".",
"paths",
".",
"pop",
"(",
")",
";",
"return",
"ret",
";",
"}"
] | Import `file` and return Block node.
@api private | [
"Import",
"file",
"and",
"return",
"Block",
"node",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/visitor/evaluator.js#L29-L104 |
5,927 | stylus/stylus | lib/functions/define.js | define | function define(name, expr, global){
utils.assertType(name, 'string', 'name');
expr = utils.unwrap(expr);
var scope = this.currentScope;
if (global && global.toBoolean().isTrue) {
scope = this.global.scope;
}
var node = new nodes.Ident(name.val, expr);
scope.add(node);
return nodes.null;
} | javascript | function define(name, expr, global){
utils.assertType(name, 'string', 'name');
expr = utils.unwrap(expr);
var scope = this.currentScope;
if (global && global.toBoolean().isTrue) {
scope = this.global.scope;
}
var node = new nodes.Ident(name.val, expr);
scope.add(node);
return nodes.null;
} | [
"function",
"define",
"(",
"name",
",",
"expr",
",",
"global",
")",
"{",
"utils",
".",
"assertType",
"(",
"name",
",",
"'string'",
",",
"'name'",
")",
";",
"expr",
"=",
"utils",
".",
"unwrap",
"(",
"expr",
")",
";",
"var",
"scope",
"=",
"this",
".",
"currentScope",
";",
"if",
"(",
"global",
"&&",
"global",
".",
"toBoolean",
"(",
")",
".",
"isTrue",
")",
"{",
"scope",
"=",
"this",
".",
"global",
".",
"scope",
";",
"}",
"var",
"node",
"=",
"new",
"nodes",
".",
"Ident",
"(",
"name",
".",
"val",
",",
"expr",
")",
";",
"scope",
".",
"add",
"(",
"node",
")",
";",
"return",
"nodes",
".",
"null",
";",
"}"
] | Set a variable `name` on current scope.
@param {String} name
@param {Expression} expr
@param {Boolean} [global]
@api public | [
"Set",
"a",
"variable",
"name",
"on",
"current",
"scope",
"."
] | 7e98dc17368c62a6f8a95aa2e300e4ab02faf007 | https://github.com/stylus/stylus/blob/7e98dc17368c62a6f8a95aa2e300e4ab02faf007/lib/functions/define.js#L13-L23 |
5,928 | ssbc/patchwork | modules/invite/invite.js | function (invite, cb) {
var id = api.keys.sync.id()
var data = ref.parseInvite(invite)
api.contact.async.followerOf(id, data.key, function (_, follows) {
if (follows) console.log('already following', cb())
else console.log('accept invite:' + invite, accept(invite, cb))
})
} | javascript | function (invite, cb) {
var id = api.keys.sync.id()
var data = ref.parseInvite(invite)
api.contact.async.followerOf(id, data.key, function (_, follows) {
if (follows) console.log('already following', cb())
else console.log('accept invite:' + invite, accept(invite, cb))
})
} | [
"function",
"(",
"invite",
",",
"cb",
")",
"{",
"var",
"id",
"=",
"api",
".",
"keys",
".",
"sync",
".",
"id",
"(",
")",
"var",
"data",
"=",
"ref",
".",
"parseInvite",
"(",
"invite",
")",
"api",
".",
"contact",
".",
"async",
".",
"followerOf",
"(",
"id",
",",
"data",
".",
"key",
",",
"function",
"(",
"_",
",",
"follows",
")",
"{",
"if",
"(",
"follows",
")",
"console",
".",
"log",
"(",
"'already following'",
",",
"cb",
"(",
")",
")",
"else",
"console",
".",
"log",
"(",
"'accept invite:'",
"+",
"invite",
",",
"accept",
"(",
"invite",
",",
"cb",
")",
")",
"}",
")",
"}"
] | like invite, but check whether we already follow them first | [
"like",
"invite",
"but",
"check",
"whether",
"we",
"already",
"follow",
"them",
"first"
] | 24108357c6dba54c0cbb481db26b5376510af529 | https://github.com/ssbc/patchwork/blob/24108357c6dba54c0cbb481db26b5376510af529/modules/invite/invite.js#L84-L91 |
|
5,929 | ssbc/patchwork | modules/intl/sync/i18n.js | _init | function _init () {
if (_locale) return
// TODO: Depject this!
i18nL.configure({
directory: appRoot + '/locales',
defaultLocale: 'en'
})
watch(api.settings.obs.get('patchwork.lang'), currentLocale => {
currentLocale = currentLocale || navigator.language
var locales = i18nL.getLocales()
// Try BCP47 codes, otherwise load family language if exist
if (locales.indexOf(currentLocale) !== -1) {
i18nL.setLocale(currentLocale)
} else {
i18nL.setLocale(getSimilar(locales, currentLocale))
}
// Only refresh if the language has already been selected once.
// This will prevent the update loop
if (_locale) {
electron.remote.getCurrentWebContents().reloadIgnoringCache()
}
})
_locale = true
} | javascript | function _init () {
if (_locale) return
// TODO: Depject this!
i18nL.configure({
directory: appRoot + '/locales',
defaultLocale: 'en'
})
watch(api.settings.obs.get('patchwork.lang'), currentLocale => {
currentLocale = currentLocale || navigator.language
var locales = i18nL.getLocales()
// Try BCP47 codes, otherwise load family language if exist
if (locales.indexOf(currentLocale) !== -1) {
i18nL.setLocale(currentLocale)
} else {
i18nL.setLocale(getSimilar(locales, currentLocale))
}
// Only refresh if the language has already been selected once.
// This will prevent the update loop
if (_locale) {
electron.remote.getCurrentWebContents().reloadIgnoringCache()
}
})
_locale = true
} | [
"function",
"_init",
"(",
")",
"{",
"if",
"(",
"_locale",
")",
"return",
"// TODO: Depject this!",
"i18nL",
".",
"configure",
"(",
"{",
"directory",
":",
"appRoot",
"+",
"'/locales'",
",",
"defaultLocale",
":",
"'en'",
"}",
")",
"watch",
"(",
"api",
".",
"settings",
".",
"obs",
".",
"get",
"(",
"'patchwork.lang'",
")",
",",
"currentLocale",
"=>",
"{",
"currentLocale",
"=",
"currentLocale",
"||",
"navigator",
".",
"language",
"var",
"locales",
"=",
"i18nL",
".",
"getLocales",
"(",
")",
"// Try BCP47 codes, otherwise load family language if exist",
"if",
"(",
"locales",
".",
"indexOf",
"(",
"currentLocale",
")",
"!==",
"-",
"1",
")",
"{",
"i18nL",
".",
"setLocale",
"(",
"currentLocale",
")",
"}",
"else",
"{",
"i18nL",
".",
"setLocale",
"(",
"getSimilar",
"(",
"locales",
",",
"currentLocale",
")",
")",
"}",
"// Only refresh if the language has already been selected once.",
"// This will prevent the update loop",
"if",
"(",
"_locale",
")",
"{",
"electron",
".",
"remote",
".",
"getCurrentWebContents",
"(",
")",
".",
"reloadIgnoringCache",
"(",
")",
"}",
"}",
")",
"_locale",
"=",
"true",
"}"
] | Init an subscribe to settings changes. | [
"Init",
"an",
"subscribe",
"to",
"settings",
"changes",
"."
] | 24108357c6dba54c0cbb481db26b5376510af529 | https://github.com/ssbc/patchwork/blob/24108357c6dba54c0cbb481db26b5376510af529/modules/intl/sync/i18n.js#L95-L122 |
5,930 | ssbc/patchwork | index.js | quitIfAlreadyRunning | function quitIfAlreadyRunning () {
if (!electron.app.requestSingleInstanceLock()) {
return electron.app.quit()
}
electron.app.on('second-instance', (event, commandLine, workingDirectory) => {
// Someone tried to run a second instance, we should focus our window.
if (windows.main) {
if (windows.main.isMinimized()) windows.main.restore()
windows.main.focus()
}
})
} | javascript | function quitIfAlreadyRunning () {
if (!electron.app.requestSingleInstanceLock()) {
return electron.app.quit()
}
electron.app.on('second-instance', (event, commandLine, workingDirectory) => {
// Someone tried to run a second instance, we should focus our window.
if (windows.main) {
if (windows.main.isMinimized()) windows.main.restore()
windows.main.focus()
}
})
} | [
"function",
"quitIfAlreadyRunning",
"(",
")",
"{",
"if",
"(",
"!",
"electron",
".",
"app",
".",
"requestSingleInstanceLock",
"(",
")",
")",
"{",
"return",
"electron",
".",
"app",
".",
"quit",
"(",
")",
"}",
"electron",
".",
"app",
".",
"on",
"(",
"'second-instance'",
",",
"(",
"event",
",",
"commandLine",
",",
"workingDirectory",
")",
"=>",
"{",
"// Someone tried to run a second instance, we should focus our window.",
"if",
"(",
"windows",
".",
"main",
")",
"{",
"if",
"(",
"windows",
".",
"main",
".",
"isMinimized",
"(",
")",
")",
"windows",
".",
"main",
".",
"restore",
"(",
")",
"windows",
".",
"main",
".",
"focus",
"(",
")",
"}",
"}",
")",
"}"
] | It's not possible to run two instances of patchwork as it would create two
ssb-server instances that conflict on the same port. Before opening patchwork,
we check if it's already running and if it is we focus the existing window
rather than opening a new instance. | [
"It",
"s",
"not",
"possible",
"to",
"run",
"two",
"instances",
"of",
"patchwork",
"as",
"it",
"would",
"create",
"two",
"ssb",
"-",
"server",
"instances",
"that",
"conflict",
"on",
"the",
"same",
"port",
".",
"Before",
"opening",
"patchwork",
"we",
"check",
"if",
"it",
"s",
"already",
"running",
"and",
"if",
"it",
"is",
"we",
"focus",
"the",
"existing",
"window",
"rather",
"than",
"opening",
"a",
"new",
"instance",
"."
] | 24108357c6dba54c0cbb481db26b5376510af529 | https://github.com/ssbc/patchwork/blob/24108357c6dba54c0cbb481db26b5376510af529/index.js#L28-L39 |
5,931 | ssbc/patchwork | lib/sustained.js | Sustained | function Sustained (obs, timeThreshold, checkUpdateImmediately) {
var outputValue = Value(obs())
var lastValue = null
var timer = null
return computed(outputValue, v => v, {
onListen: () => watch(obs, onChange)
})
function onChange (value) {
if (checkUpdateImmediately && checkUpdateImmediately(value)) {
clearTimeout(timer)
update()
} else if (value !== lastValue) {
clearTimeout(timer)
var delay = typeof timeThreshold === 'function' ? timeThreshold(value, outputValue()) : timeThreshold
timer = setTimeout(update, delay)
}
lastValue = value
}
function update () {
var value = obs()
if (value !== outputValue()) {
outputValue.set(value)
}
}
} | javascript | function Sustained (obs, timeThreshold, checkUpdateImmediately) {
var outputValue = Value(obs())
var lastValue = null
var timer = null
return computed(outputValue, v => v, {
onListen: () => watch(obs, onChange)
})
function onChange (value) {
if (checkUpdateImmediately && checkUpdateImmediately(value)) {
clearTimeout(timer)
update()
} else if (value !== lastValue) {
clearTimeout(timer)
var delay = typeof timeThreshold === 'function' ? timeThreshold(value, outputValue()) : timeThreshold
timer = setTimeout(update, delay)
}
lastValue = value
}
function update () {
var value = obs()
if (value !== outputValue()) {
outputValue.set(value)
}
}
} | [
"function",
"Sustained",
"(",
"obs",
",",
"timeThreshold",
",",
"checkUpdateImmediately",
")",
"{",
"var",
"outputValue",
"=",
"Value",
"(",
"obs",
"(",
")",
")",
"var",
"lastValue",
"=",
"null",
"var",
"timer",
"=",
"null",
"return",
"computed",
"(",
"outputValue",
",",
"v",
"=>",
"v",
",",
"{",
"onListen",
":",
"(",
")",
"=>",
"watch",
"(",
"obs",
",",
"onChange",
")",
"}",
")",
"function",
"onChange",
"(",
"value",
")",
"{",
"if",
"(",
"checkUpdateImmediately",
"&&",
"checkUpdateImmediately",
"(",
"value",
")",
")",
"{",
"clearTimeout",
"(",
"timer",
")",
"update",
"(",
")",
"}",
"else",
"if",
"(",
"value",
"!==",
"lastValue",
")",
"{",
"clearTimeout",
"(",
"timer",
")",
"var",
"delay",
"=",
"typeof",
"timeThreshold",
"===",
"'function'",
"?",
"timeThreshold",
"(",
"value",
",",
"outputValue",
"(",
")",
")",
":",
"timeThreshold",
"timer",
"=",
"setTimeout",
"(",
"update",
",",
"delay",
")",
"}",
"lastValue",
"=",
"value",
"}",
"function",
"update",
"(",
")",
"{",
"var",
"value",
"=",
"obs",
"(",
")",
"if",
"(",
"value",
"!==",
"outputValue",
"(",
")",
")",
"{",
"outputValue",
".",
"set",
"(",
"value",
")",
"}",
"}",
"}"
] | only broadcast value changes once a truthy value has stayed constant for more than timeThreshold | [
"only",
"broadcast",
"value",
"changes",
"once",
"a",
"truthy",
"value",
"has",
"stayed",
"constant",
"for",
"more",
"than",
"timeThreshold"
] | 24108357c6dba54c0cbb481db26b5376510af529 | https://github.com/ssbc/patchwork/blob/24108357c6dba54c0cbb481db26b5376510af529/lib/sustained.js#L9-L36 |
5,932 | katspaugh/wavesurfer.js | build-config/fragments/plugins.js | buildPluginEntry | function buildPluginEntry(plugins) {
const result = {};
plugins.forEach(
plugin =>
(result[path.basename(plugin, '.js')] = path.join(
pluginSrcDir,
plugin
))
);
return result;
} | javascript | function buildPluginEntry(plugins) {
const result = {};
plugins.forEach(
plugin =>
(result[path.basename(plugin, '.js')] = path.join(
pluginSrcDir,
plugin
))
);
return result;
} | [
"function",
"buildPluginEntry",
"(",
"plugins",
")",
"{",
"const",
"result",
"=",
"{",
"}",
";",
"plugins",
".",
"forEach",
"(",
"plugin",
"=>",
"(",
"result",
"[",
"path",
".",
"basename",
"(",
"plugin",
",",
"'.js'",
")",
"]",
"=",
"path",
".",
"join",
"(",
"pluginSrcDir",
",",
"plugin",
")",
")",
")",
";",
"return",
"result",
";",
"}"
] | buildPluginEntry - Description
@param {Array} plugins Name of plugins in src/plugin
@returns {object} Entry object { name: nameUrl } | [
"buildPluginEntry",
"-",
"Description"
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/build-config/fragments/plugins.js#L22-L32 |
5,933 | katspaugh/wavesurfer.js | example/panner/main.js | function() {
var xDeg = parseInt(slider.value);
var x = Math.sin(xDeg * (Math.PI / 180));
wavesurfer.panner.setPosition(x, 0, 0);
} | javascript | function() {
var xDeg = parseInt(slider.value);
var x = Math.sin(xDeg * (Math.PI / 180));
wavesurfer.panner.setPosition(x, 0, 0);
} | [
"function",
"(",
")",
"{",
"var",
"xDeg",
"=",
"parseInt",
"(",
"slider",
".",
"value",
")",
";",
"var",
"x",
"=",
"Math",
".",
"sin",
"(",
"xDeg",
"*",
"(",
"Math",
".",
"PI",
"/",
"180",
")",
")",
";",
"wavesurfer",
".",
"panner",
".",
"setPosition",
"(",
"x",
",",
"0",
",",
"0",
")",
";",
"}"
] | Bind panner slider @see http://stackoverflow.com/a/14412601/352796 | [
"Bind",
"panner",
"slider"
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/panner/main.js#L28-L32 |
|
5,934 | katspaugh/wavesurfer.js | example/stretcher/soundtouch.js | function(
aSampleRate,
aSequenceMS,
aSeekWindowMS,
aOverlapMS
) {
// accept only positive parameter values - if zero or negative, use old values instead
if (aSampleRate > 0) {
this.sampleRate = aSampleRate;
}
if (aOverlapMS > 0) {
this.overlapMs = aOverlapMS;
}
if (aSequenceMS > 0) {
this.sequenceMs = aSequenceMS;
this.bAutoSeqSetting = false;
} else {
// zero or below, use automatic setting
this.bAutoSeqSetting = true;
}
if (aSeekWindowMS > 0) {
this.seekWindowMs = aSeekWindowMS;
this.bAutoSeekSetting = false;
} else {
// zero or below, use automatic setting
this.bAutoSeekSetting = true;
}
this.calcSeqParameters();
this.calculateOverlapLength(this.overlapMs);
// set tempo to recalculate 'sampleReq'
this.tempo = this._tempo;
} | javascript | function(
aSampleRate,
aSequenceMS,
aSeekWindowMS,
aOverlapMS
) {
// accept only positive parameter values - if zero or negative, use old values instead
if (aSampleRate > 0) {
this.sampleRate = aSampleRate;
}
if (aOverlapMS > 0) {
this.overlapMs = aOverlapMS;
}
if (aSequenceMS > 0) {
this.sequenceMs = aSequenceMS;
this.bAutoSeqSetting = false;
} else {
// zero or below, use automatic setting
this.bAutoSeqSetting = true;
}
if (aSeekWindowMS > 0) {
this.seekWindowMs = aSeekWindowMS;
this.bAutoSeekSetting = false;
} else {
// zero or below, use automatic setting
this.bAutoSeekSetting = true;
}
this.calcSeqParameters();
this.calculateOverlapLength(this.overlapMs);
// set tempo to recalculate 'sampleReq'
this.tempo = this._tempo;
} | [
"function",
"(",
"aSampleRate",
",",
"aSequenceMS",
",",
"aSeekWindowMS",
",",
"aOverlapMS",
")",
"{",
"// accept only positive parameter values - if zero or negative, use old values instead",
"if",
"(",
"aSampleRate",
">",
"0",
")",
"{",
"this",
".",
"sampleRate",
"=",
"aSampleRate",
";",
"}",
"if",
"(",
"aOverlapMS",
">",
"0",
")",
"{",
"this",
".",
"overlapMs",
"=",
"aOverlapMS",
";",
"}",
"if",
"(",
"aSequenceMS",
">",
"0",
")",
"{",
"this",
".",
"sequenceMs",
"=",
"aSequenceMS",
";",
"this",
".",
"bAutoSeqSetting",
"=",
"false",
";",
"}",
"else",
"{",
"// zero or below, use automatic setting",
"this",
".",
"bAutoSeqSetting",
"=",
"true",
";",
"}",
"if",
"(",
"aSeekWindowMS",
">",
"0",
")",
"{",
"this",
".",
"seekWindowMs",
"=",
"aSeekWindowMS",
";",
"this",
".",
"bAutoSeekSetting",
"=",
"false",
";",
"}",
"else",
"{",
"// zero or below, use automatic setting",
"this",
".",
"bAutoSeekSetting",
"=",
"true",
";",
"}",
"this",
".",
"calcSeqParameters",
"(",
")",
";",
"this",
".",
"calculateOverlapLength",
"(",
"this",
".",
"overlapMs",
")",
";",
"// set tempo to recalculate 'sampleReq'",
"this",
".",
"tempo",
"=",
"this",
".",
"_tempo",
";",
"}"
] | Sets routine control parameters. These control are certain time constants
defining how the sound is stretched to the desired duration.
'sampleRate' = sample rate of the sound
'sequenceMS' = one processing sequence length in milliseconds (default = 82 ms)
'seekwindowMS' = seeking window length for scanning the best overlapping
position (default = 28 ms)
'overlapMS' = overlapping length (default = 12 ms) | [
"Sets",
"routine",
"control",
"parameters",
".",
"These",
"control",
"are",
"certain",
"time",
"constants",
"defining",
"how",
"the",
"sound",
"is",
"stretched",
"to",
"the",
"desired",
"duration",
"."
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/stretcher/soundtouch.js#L588-L624 |
|
5,935 | katspaugh/wavesurfer.js | example/stretcher/soundtouch.js | function(overlapInMsec) {
var newOvl;
// TODO assert(overlapInMsec >= 0);
newOvl = (this.sampleRate * overlapInMsec) / 1000;
if (newOvl < 16) newOvl = 16;
// must be divisible by 8
newOvl -= newOvl % 8;
this.overlapLength = newOvl;
this.pRefMidBuffer = new Float32Array(this.overlapLength * 2);
this.pMidBuffer = new Float32Array(this.overlapLength * 2);
} | javascript | function(overlapInMsec) {
var newOvl;
// TODO assert(overlapInMsec >= 0);
newOvl = (this.sampleRate * overlapInMsec) / 1000;
if (newOvl < 16) newOvl = 16;
// must be divisible by 8
newOvl -= newOvl % 8;
this.overlapLength = newOvl;
this.pRefMidBuffer = new Float32Array(this.overlapLength * 2);
this.pMidBuffer = new Float32Array(this.overlapLength * 2);
} | [
"function",
"(",
"overlapInMsec",
")",
"{",
"var",
"newOvl",
";",
"// TODO assert(overlapInMsec >= 0);",
"newOvl",
"=",
"(",
"this",
".",
"sampleRate",
"*",
"overlapInMsec",
")",
"/",
"1000",
";",
"if",
"(",
"newOvl",
"<",
"16",
")",
"newOvl",
"=",
"16",
";",
"// must be divisible by 8",
"newOvl",
"-=",
"newOvl",
"%",
"8",
";",
"this",
".",
"overlapLength",
"=",
"newOvl",
";",
"this",
".",
"pRefMidBuffer",
"=",
"new",
"Float32Array",
"(",
"this",
".",
"overlapLength",
"*",
"2",
")",
";",
"this",
".",
"pMidBuffer",
"=",
"new",
"Float32Array",
"(",
"this",
".",
"overlapLength",
"*",
"2",
")",
";",
"}"
] | Calculates overlapInMsec period length in samples. | [
"Calculates",
"overlapInMsec",
"period",
"length",
"in",
"samples",
"."
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/stretcher/soundtouch.js#L663-L677 |
|
5,936 | katspaugh/wavesurfer.js | example/stretcher/soundtouch.js | function() {
var seq;
var seek;
if (this.bAutoSeqSetting) {
seq = AUTOSEQ_C + AUTOSEQ_K * this._tempo;
seq = this.checkLimits(seq, AUTOSEQ_AT_MAX, AUTOSEQ_AT_MIN);
this.sequenceMs = Math.floor(seq + 0.5);
}
if (this.bAutoSeekSetting) {
seek = AUTOSEEK_C + AUTOSEEK_K * this._tempo;
seek = this.checkLimits(seek, AUTOSEEK_AT_MAX, AUTOSEEK_AT_MIN);
this.seekWindowMs = Math.floor(seek + 0.5);
}
// Update seek window lengths
this.seekWindowLength = Math.floor(
(this.sampleRate * this.sequenceMs) / 1000
);
this.seekLength = Math.floor(
(this.sampleRate * this.seekWindowMs) / 1000
);
} | javascript | function() {
var seq;
var seek;
if (this.bAutoSeqSetting) {
seq = AUTOSEQ_C + AUTOSEQ_K * this._tempo;
seq = this.checkLimits(seq, AUTOSEQ_AT_MAX, AUTOSEQ_AT_MIN);
this.sequenceMs = Math.floor(seq + 0.5);
}
if (this.bAutoSeekSetting) {
seek = AUTOSEEK_C + AUTOSEEK_K * this._tempo;
seek = this.checkLimits(seek, AUTOSEEK_AT_MAX, AUTOSEEK_AT_MIN);
this.seekWindowMs = Math.floor(seek + 0.5);
}
// Update seek window lengths
this.seekWindowLength = Math.floor(
(this.sampleRate * this.sequenceMs) / 1000
);
this.seekLength = Math.floor(
(this.sampleRate * this.seekWindowMs) / 1000
);
} | [
"function",
"(",
")",
"{",
"var",
"seq",
";",
"var",
"seek",
";",
"if",
"(",
"this",
".",
"bAutoSeqSetting",
")",
"{",
"seq",
"=",
"AUTOSEQ_C",
"+",
"AUTOSEQ_K",
"*",
"this",
".",
"_tempo",
";",
"seq",
"=",
"this",
".",
"checkLimits",
"(",
"seq",
",",
"AUTOSEQ_AT_MAX",
",",
"AUTOSEQ_AT_MIN",
")",
";",
"this",
".",
"sequenceMs",
"=",
"Math",
".",
"floor",
"(",
"seq",
"+",
"0.5",
")",
";",
"}",
"if",
"(",
"this",
".",
"bAutoSeekSetting",
")",
"{",
"seek",
"=",
"AUTOSEEK_C",
"+",
"AUTOSEEK_K",
"*",
"this",
".",
"_tempo",
";",
"seek",
"=",
"this",
".",
"checkLimits",
"(",
"seek",
",",
"AUTOSEEK_AT_MAX",
",",
"AUTOSEEK_AT_MIN",
")",
";",
"this",
".",
"seekWindowMs",
"=",
"Math",
".",
"floor",
"(",
"seek",
"+",
"0.5",
")",
";",
"}",
"// Update seek window lengths",
"this",
".",
"seekWindowLength",
"=",
"Math",
".",
"floor",
"(",
"(",
"this",
".",
"sampleRate",
"*",
"this",
".",
"sequenceMs",
")",
"/",
"1000",
")",
";",
"this",
".",
"seekLength",
"=",
"Math",
".",
"floor",
"(",
"(",
"this",
".",
"sampleRate",
"*",
"this",
".",
"seekWindowMs",
")",
"/",
"1000",
")",
";",
"}"
] | Calculates processing sequence length according to tempo setting | [
"Calculates",
"processing",
"sequence",
"length",
"according",
"to",
"tempo",
"setting"
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/stretcher/soundtouch.js#L685-L708 |
|
5,937 | katspaugh/wavesurfer.js | example/stretcher/soundtouch.js | function() {
var i, cnt2, temp;
for (i = 0; i < this.overlapLength; i++) {
temp = i * (this.overlapLength - i);
cnt2 = i * 2;
this.pRefMidBuffer[cnt2] = this.pMidBuffer[cnt2] * temp;
this.pRefMidBuffer[cnt2 + 1] = this.pMidBuffer[cnt2 + 1] * temp;
}
} | javascript | function() {
var i, cnt2, temp;
for (i = 0; i < this.overlapLength; i++) {
temp = i * (this.overlapLength - i);
cnt2 = i * 2;
this.pRefMidBuffer[cnt2] = this.pMidBuffer[cnt2] * temp;
this.pRefMidBuffer[cnt2 + 1] = this.pMidBuffer[cnt2 + 1] * temp;
}
} | [
"function",
"(",
")",
"{",
"var",
"i",
",",
"cnt2",
",",
"temp",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"overlapLength",
";",
"i",
"++",
")",
"{",
"temp",
"=",
"i",
"*",
"(",
"this",
".",
"overlapLength",
"-",
"i",
")",
";",
"cnt2",
"=",
"i",
"*",
"2",
";",
"this",
".",
"pRefMidBuffer",
"[",
"cnt2",
"]",
"=",
"this",
".",
"pMidBuffer",
"[",
"cnt2",
"]",
"*",
"temp",
";",
"this",
".",
"pRefMidBuffer",
"[",
"cnt2",
"+",
"1",
"]",
"=",
"this",
".",
"pMidBuffer",
"[",
"cnt2",
"+",
"1",
"]",
"*",
"temp",
";",
"}",
"}"
] | Slopes the amplitude of the 'midBuffer' samples so that cross correlation
is faster to calculate | [
"Slopes",
"the",
"amplitude",
"of",
"the",
"midBuffer",
"samples",
"so",
"that",
"cross",
"correlation",
"is",
"faster",
"to",
"calculate"
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/stretcher/soundtouch.js#L817-L826 |
|
5,938 | katspaugh/wavesurfer.js | example/stretcher/soundtouch.js | function(pInputPos) {
var pInput = this._inputBuffer.vector;
pInputPos += this._inputBuffer.startIndex;
var pOutput = this._outputBuffer.vector,
pOutputPos = this._outputBuffer.endIndex,
i,
cnt2,
fTemp,
fScale,
fi,
pInputOffset,
pOutputOffset;
fScale = 1 / this.overlapLength;
for (i = 0; i < this.overlapLength; i++) {
fTemp = (this.overlapLength - i) * fScale;
fi = i * fScale;
cnt2 = 2 * i;
pInputOffset = cnt2 + pInputPos;
pOutputOffset = cnt2 + pOutputPos;
pOutput[pOutputOffset + 0] =
pInput[pInputOffset + 0] * fi +
this.pMidBuffer[cnt2 + 0] * fTemp;
pOutput[pOutputOffset + 1] =
pInput[pInputOffset + 1] * fi +
this.pMidBuffer[cnt2 + 1] * fTemp;
}
} | javascript | function(pInputPos) {
var pInput = this._inputBuffer.vector;
pInputPos += this._inputBuffer.startIndex;
var pOutput = this._outputBuffer.vector,
pOutputPos = this._outputBuffer.endIndex,
i,
cnt2,
fTemp,
fScale,
fi,
pInputOffset,
pOutputOffset;
fScale = 1 / this.overlapLength;
for (i = 0; i < this.overlapLength; i++) {
fTemp = (this.overlapLength - i) * fScale;
fi = i * fScale;
cnt2 = 2 * i;
pInputOffset = cnt2 + pInputPos;
pOutputOffset = cnt2 + pOutputPos;
pOutput[pOutputOffset + 0] =
pInput[pInputOffset + 0] * fi +
this.pMidBuffer[cnt2 + 0] * fTemp;
pOutput[pOutputOffset + 1] =
pInput[pInputOffset + 1] * fi +
this.pMidBuffer[cnt2 + 1] * fTemp;
}
} | [
"function",
"(",
"pInputPos",
")",
"{",
"var",
"pInput",
"=",
"this",
".",
"_inputBuffer",
".",
"vector",
";",
"pInputPos",
"+=",
"this",
".",
"_inputBuffer",
".",
"startIndex",
";",
"var",
"pOutput",
"=",
"this",
".",
"_outputBuffer",
".",
"vector",
",",
"pOutputPos",
"=",
"this",
".",
"_outputBuffer",
".",
"endIndex",
",",
"i",
",",
"cnt2",
",",
"fTemp",
",",
"fScale",
",",
"fi",
",",
"pInputOffset",
",",
"pOutputOffset",
";",
"fScale",
"=",
"1",
"/",
"this",
".",
"overlapLength",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"overlapLength",
";",
"i",
"++",
")",
"{",
"fTemp",
"=",
"(",
"this",
".",
"overlapLength",
"-",
"i",
")",
"*",
"fScale",
";",
"fi",
"=",
"i",
"*",
"fScale",
";",
"cnt2",
"=",
"2",
"*",
"i",
";",
"pInputOffset",
"=",
"cnt2",
"+",
"pInputPos",
";",
"pOutputOffset",
"=",
"cnt2",
"+",
"pOutputPos",
";",
"pOutput",
"[",
"pOutputOffset",
"+",
"0",
"]",
"=",
"pInput",
"[",
"pInputOffset",
"+",
"0",
"]",
"*",
"fi",
"+",
"this",
".",
"pMidBuffer",
"[",
"cnt2",
"+",
"0",
"]",
"*",
"fTemp",
";",
"pOutput",
"[",
"pOutputOffset",
"+",
"1",
"]",
"=",
"pInput",
"[",
"pInputOffset",
"+",
"1",
"]",
"*",
"fi",
"+",
"this",
".",
"pMidBuffer",
"[",
"cnt2",
"+",
"1",
"]",
"*",
"fTemp",
";",
"}",
"}"
] | Overlaps samples in 'midBuffer' with the samples in 'pInput' | [
"Overlaps",
"samples",
"in",
"midBuffer",
"with",
"the",
"samples",
"in",
"pInput"
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/stretcher/soundtouch.js#L855-L883 |
|
5,939 | katspaugh/wavesurfer.js | example/timeline-notches/main.js | formatTimeCallback | function formatTimeCallback(seconds, pxPerSec) {
seconds = Number(seconds);
var minutes = Math.floor(seconds / 60);
seconds = seconds % 60;
// fill up seconds with zeroes
var secondsStr = Math.round(seconds).toString();
if (pxPerSec >= 25 * 10) {
secondsStr = seconds.toFixed(2);
} else if (pxPerSec >= 25 * 1) {
secondsStr = seconds.toFixed(1);
}
if (minutes > 0) {
if (seconds < 10) {
secondsStr = '0' + secondsStr;
}
return `${minutes}:${secondsStr}`;
}
return secondsStr;
} | javascript | function formatTimeCallback(seconds, pxPerSec) {
seconds = Number(seconds);
var minutes = Math.floor(seconds / 60);
seconds = seconds % 60;
// fill up seconds with zeroes
var secondsStr = Math.round(seconds).toString();
if (pxPerSec >= 25 * 10) {
secondsStr = seconds.toFixed(2);
} else if (pxPerSec >= 25 * 1) {
secondsStr = seconds.toFixed(1);
}
if (minutes > 0) {
if (seconds < 10) {
secondsStr = '0' + secondsStr;
}
return `${minutes}:${secondsStr}`;
}
return secondsStr;
} | [
"function",
"formatTimeCallback",
"(",
"seconds",
",",
"pxPerSec",
")",
"{",
"seconds",
"=",
"Number",
"(",
"seconds",
")",
";",
"var",
"minutes",
"=",
"Math",
".",
"floor",
"(",
"seconds",
"/",
"60",
")",
";",
"seconds",
"=",
"seconds",
"%",
"60",
";",
"// fill up seconds with zeroes",
"var",
"secondsStr",
"=",
"Math",
".",
"round",
"(",
"seconds",
")",
".",
"toString",
"(",
")",
";",
"if",
"(",
"pxPerSec",
">=",
"25",
"*",
"10",
")",
"{",
"secondsStr",
"=",
"seconds",
".",
"toFixed",
"(",
"2",
")",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
">=",
"25",
"*",
"1",
")",
"{",
"secondsStr",
"=",
"seconds",
".",
"toFixed",
"(",
"1",
")",
";",
"}",
"if",
"(",
"minutes",
">",
"0",
")",
"{",
"if",
"(",
"seconds",
"<",
"10",
")",
"{",
"secondsStr",
"=",
"'0'",
"+",
"secondsStr",
";",
"}",
"return",
"`",
"${",
"minutes",
"}",
"${",
"secondsStr",
"}",
"`",
";",
"}",
"return",
"secondsStr",
";",
"}"
] | Use formatTimeCallback to style the notch labels as you wish, such
as with more detail as the number of pixels per second increases.
Here we format as M:SS.frac, with M suppressed for times < 1 minute,
and frac having 0, 1, or 2 digits as the zoom increases.
Note that if you override the default function, you'll almost
certainly want to override timeInterval, primaryLabelInterval and/or
secondaryLabelInterval so they all work together.
@param: seconds
@param: pxPerSec | [
"Use",
"formatTimeCallback",
"to",
"style",
"the",
"notch",
"labels",
"as",
"you",
"wish",
"such",
"as",
"with",
"more",
"detail",
"as",
"the",
"number",
"of",
"pixels",
"per",
"second",
"increases",
"."
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/timeline-notches/main.js#L20-L40 |
5,940 | katspaugh/wavesurfer.js | example/timeline-notches/main.js | timeInterval | function timeInterval(pxPerSec) {
var retval = 1;
if (pxPerSec >= 25 * 100) {
retval = 0.01;
} else if (pxPerSec >= 25 * 40) {
retval = 0.025;
} else if (pxPerSec >= 25 * 10) {
retval = 0.1;
} else if (pxPerSec >= 25 * 4) {
retval = 0.25;
} else if (pxPerSec >= 25) {
retval = 1;
} else if (pxPerSec * 5 >= 25) {
retval = 5;
} else if (pxPerSec * 15 >= 25) {
retval = 15;
} else {
retval = Math.ceil(0.5 / pxPerSec) * 60;
}
return retval;
} | javascript | function timeInterval(pxPerSec) {
var retval = 1;
if (pxPerSec >= 25 * 100) {
retval = 0.01;
} else if (pxPerSec >= 25 * 40) {
retval = 0.025;
} else if (pxPerSec >= 25 * 10) {
retval = 0.1;
} else if (pxPerSec >= 25 * 4) {
retval = 0.25;
} else if (pxPerSec >= 25) {
retval = 1;
} else if (pxPerSec * 5 >= 25) {
retval = 5;
} else if (pxPerSec * 15 >= 25) {
retval = 15;
} else {
retval = Math.ceil(0.5 / pxPerSec) * 60;
}
return retval;
} | [
"function",
"timeInterval",
"(",
"pxPerSec",
")",
"{",
"var",
"retval",
"=",
"1",
";",
"if",
"(",
"pxPerSec",
">=",
"25",
"*",
"100",
")",
"{",
"retval",
"=",
"0.01",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
">=",
"25",
"*",
"40",
")",
"{",
"retval",
"=",
"0.025",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
">=",
"25",
"*",
"10",
")",
"{",
"retval",
"=",
"0.1",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
">=",
"25",
"*",
"4",
")",
"{",
"retval",
"=",
"0.25",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
">=",
"25",
")",
"{",
"retval",
"=",
"1",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
"*",
"5",
">=",
"25",
")",
"{",
"retval",
"=",
"5",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
"*",
"15",
">=",
"25",
")",
"{",
"retval",
"=",
"15",
";",
"}",
"else",
"{",
"retval",
"=",
"Math",
".",
"ceil",
"(",
"0.5",
"/",
"pxPerSec",
")",
"*",
"60",
";",
"}",
"return",
"retval",
";",
"}"
] | Use timeInterval to set the period between notches, in seconds,
adding notches as the number of pixels per second increases.
Note that if you override the default function, you'll almost
certainly want to override formatTimeCallback, primaryLabelInterval
and/or secondaryLabelInterval so they all work together.
@param: pxPerSec | [
"Use",
"timeInterval",
"to",
"set",
"the",
"period",
"between",
"notches",
"in",
"seconds",
"adding",
"notches",
"as",
"the",
"number",
"of",
"pixels",
"per",
"second",
"increases",
"."
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/timeline-notches/main.js#L52-L72 |
5,941 | katspaugh/wavesurfer.js | example/timeline-notches/main.js | primaryLabelInterval | function primaryLabelInterval(pxPerSec) {
var retval = 1;
if (pxPerSec >= 25 * 100) {
retval = 10;
} else if (pxPerSec >= 25 * 40) {
retval = 4;
} else if (pxPerSec >= 25 * 10) {
retval = 10;
} else if (pxPerSec >= 25 * 4) {
retval = 4;
} else if (pxPerSec >= 25) {
retval = 1;
} else if (pxPerSec * 5 >= 25) {
retval = 5;
} else if (pxPerSec * 15 >= 25) {
retval = 15;
} else {
retval = Math.ceil(0.5 / pxPerSec) * 60;
}
return retval;
} | javascript | function primaryLabelInterval(pxPerSec) {
var retval = 1;
if (pxPerSec >= 25 * 100) {
retval = 10;
} else if (pxPerSec >= 25 * 40) {
retval = 4;
} else if (pxPerSec >= 25 * 10) {
retval = 10;
} else if (pxPerSec >= 25 * 4) {
retval = 4;
} else if (pxPerSec >= 25) {
retval = 1;
} else if (pxPerSec * 5 >= 25) {
retval = 5;
} else if (pxPerSec * 15 >= 25) {
retval = 15;
} else {
retval = Math.ceil(0.5 / pxPerSec) * 60;
}
return retval;
} | [
"function",
"primaryLabelInterval",
"(",
"pxPerSec",
")",
"{",
"var",
"retval",
"=",
"1",
";",
"if",
"(",
"pxPerSec",
">=",
"25",
"*",
"100",
")",
"{",
"retval",
"=",
"10",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
">=",
"25",
"*",
"40",
")",
"{",
"retval",
"=",
"4",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
">=",
"25",
"*",
"10",
")",
"{",
"retval",
"=",
"10",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
">=",
"25",
"*",
"4",
")",
"{",
"retval",
"=",
"4",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
">=",
"25",
")",
"{",
"retval",
"=",
"1",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
"*",
"5",
">=",
"25",
")",
"{",
"retval",
"=",
"5",
";",
"}",
"else",
"if",
"(",
"pxPerSec",
"*",
"15",
">=",
"25",
")",
"{",
"retval",
"=",
"15",
";",
"}",
"else",
"{",
"retval",
"=",
"Math",
".",
"ceil",
"(",
"0.5",
"/",
"pxPerSec",
")",
"*",
"60",
";",
"}",
"return",
"retval",
";",
"}"
] | Return the cadence of notches that get labels in the primary color.
EG, return 2 if every 2nd notch should be labeled,
return 10 if every 10th notch should be labeled, etc.
Note that if you override the default function, you'll almost
certainly want to override formatTimeCallback, primaryLabelInterval
and/or secondaryLabelInterval so they all work together.
@param pxPerSec | [
"Return",
"the",
"cadence",
"of",
"notches",
"that",
"get",
"labels",
"in",
"the",
"primary",
"color",
".",
"EG",
"return",
"2",
"if",
"every",
"2nd",
"notch",
"should",
"be",
"labeled",
"return",
"10",
"if",
"every",
"10th",
"notch",
"should",
"be",
"labeled",
"etc",
"."
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/timeline-notches/main.js#L85-L105 |
5,942 | katspaugh/wavesurfer.js | example/playlist/app.js | function(index) {
links[currentTrack].classList.remove('active');
currentTrack = index;
links[currentTrack].classList.add('active');
wavesurfer.load(links[currentTrack].href);
} | javascript | function(index) {
links[currentTrack].classList.remove('active');
currentTrack = index;
links[currentTrack].classList.add('active');
wavesurfer.load(links[currentTrack].href);
} | [
"function",
"(",
"index",
")",
"{",
"links",
"[",
"currentTrack",
"]",
".",
"classList",
".",
"remove",
"(",
"'active'",
")",
";",
"currentTrack",
"=",
"index",
";",
"links",
"[",
"currentTrack",
"]",
".",
"classList",
".",
"add",
"(",
"'active'",
")",
";",
"wavesurfer",
".",
"load",
"(",
"links",
"[",
"currentTrack",
"]",
".",
"href",
")",
";",
"}"
] | Load a track by index and highlight the corresponding link | [
"Load",
"a",
"track",
"by",
"index",
"and",
"highlight",
"the",
"corresponding",
"link"
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/playlist/app.js#L37-L42 |
|
5,943 | katspaugh/wavesurfer.js | example/annotation/app.js | saveRegions | function saveRegions() {
localStorage.regions = JSON.stringify(
Object.keys(wavesurfer.regions.list).map(function(id) {
var region = wavesurfer.regions.list[id];
return {
start: region.start,
end: region.end,
attributes: region.attributes,
data: region.data
};
})
);
} | javascript | function saveRegions() {
localStorage.regions = JSON.stringify(
Object.keys(wavesurfer.regions.list).map(function(id) {
var region = wavesurfer.regions.list[id];
return {
start: region.start,
end: region.end,
attributes: region.attributes,
data: region.data
};
})
);
} | [
"function",
"saveRegions",
"(",
")",
"{",
"localStorage",
".",
"regions",
"=",
"JSON",
".",
"stringify",
"(",
"Object",
".",
"keys",
"(",
"wavesurfer",
".",
"regions",
".",
"list",
")",
".",
"map",
"(",
"function",
"(",
"id",
")",
"{",
"var",
"region",
"=",
"wavesurfer",
".",
"regions",
".",
"list",
"[",
"id",
"]",
";",
"return",
"{",
"start",
":",
"region",
".",
"start",
",",
"end",
":",
"region",
".",
"end",
",",
"attributes",
":",
"region",
".",
"attributes",
",",
"data",
":",
"region",
".",
"data",
"}",
";",
"}",
")",
")",
";",
"}"
] | Save annotations to localStorage. | [
"Save",
"annotations",
"to",
"localStorage",
"."
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/annotation/app.js#L105-L117 |
5,944 | katspaugh/wavesurfer.js | example/annotation/app.js | loadRegions | function loadRegions(regions) {
regions.forEach(function(region) {
region.color = randomColor(0.1);
wavesurfer.addRegion(region);
});
} | javascript | function loadRegions(regions) {
regions.forEach(function(region) {
region.color = randomColor(0.1);
wavesurfer.addRegion(region);
});
} | [
"function",
"loadRegions",
"(",
"regions",
")",
"{",
"regions",
".",
"forEach",
"(",
"function",
"(",
"region",
")",
"{",
"region",
".",
"color",
"=",
"randomColor",
"(",
"0.1",
")",
";",
"wavesurfer",
".",
"addRegion",
"(",
"region",
")",
";",
"}",
")",
";",
"}"
] | Load regions from localStorage. | [
"Load",
"regions",
"from",
"localStorage",
"."
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/annotation/app.js#L122-L127 |
5,945 | katspaugh/wavesurfer.js | example/annotation/app.js | extractRegions | function extractRegions(peaks, duration) {
// Silence params
var minValue = 0.0015;
var minSeconds = 0.25;
var length = peaks.length;
var coef = duration / length;
var minLen = minSeconds / coef;
// Gather silence indeces
var silences = [];
Array.prototype.forEach.call(peaks, function(val, index) {
if (Math.abs(val) <= minValue) {
silences.push(index);
}
});
// Cluster silence values
var clusters = [];
silences.forEach(function(val, index) {
if (clusters.length && val == silences[index - 1] + 1) {
clusters[clusters.length - 1].push(val);
} else {
clusters.push([val]);
}
});
// Filter silence clusters by minimum length
var fClusters = clusters.filter(function(cluster) {
return cluster.length >= minLen;
});
// Create regions on the edges of silences
var regions = fClusters.map(function(cluster, index) {
var next = fClusters[index + 1];
return {
start: cluster[cluster.length - 1],
end: next ? next[0] : length - 1
};
});
// Add an initial region if the audio doesn't start with silence
var firstCluster = fClusters[0];
if (firstCluster && firstCluster[0] != 0) {
regions.unshift({
start: 0,
end: firstCluster[firstCluster.length - 1]
});
}
// Filter regions by minimum length
var fRegions = regions.filter(function(reg) {
return reg.end - reg.start >= minLen;
});
// Return time-based regions
return fRegions.map(function(reg) {
return {
start: Math.round(reg.start * coef * 10) / 10,
end: Math.round(reg.end * coef * 10) / 10
};
});
} | javascript | function extractRegions(peaks, duration) {
// Silence params
var minValue = 0.0015;
var minSeconds = 0.25;
var length = peaks.length;
var coef = duration / length;
var minLen = minSeconds / coef;
// Gather silence indeces
var silences = [];
Array.prototype.forEach.call(peaks, function(val, index) {
if (Math.abs(val) <= minValue) {
silences.push(index);
}
});
// Cluster silence values
var clusters = [];
silences.forEach(function(val, index) {
if (clusters.length && val == silences[index - 1] + 1) {
clusters[clusters.length - 1].push(val);
} else {
clusters.push([val]);
}
});
// Filter silence clusters by minimum length
var fClusters = clusters.filter(function(cluster) {
return cluster.length >= minLen;
});
// Create regions on the edges of silences
var regions = fClusters.map(function(cluster, index) {
var next = fClusters[index + 1];
return {
start: cluster[cluster.length - 1],
end: next ? next[0] : length - 1
};
});
// Add an initial region if the audio doesn't start with silence
var firstCluster = fClusters[0];
if (firstCluster && firstCluster[0] != 0) {
regions.unshift({
start: 0,
end: firstCluster[firstCluster.length - 1]
});
}
// Filter regions by minimum length
var fRegions = regions.filter(function(reg) {
return reg.end - reg.start >= minLen;
});
// Return time-based regions
return fRegions.map(function(reg) {
return {
start: Math.round(reg.start * coef * 10) / 10,
end: Math.round(reg.end * coef * 10) / 10
};
});
} | [
"function",
"extractRegions",
"(",
"peaks",
",",
"duration",
")",
"{",
"// Silence params",
"var",
"minValue",
"=",
"0.0015",
";",
"var",
"minSeconds",
"=",
"0.25",
";",
"var",
"length",
"=",
"peaks",
".",
"length",
";",
"var",
"coef",
"=",
"duration",
"/",
"length",
";",
"var",
"minLen",
"=",
"minSeconds",
"/",
"coef",
";",
"// Gather silence indeces",
"var",
"silences",
"=",
"[",
"]",
";",
"Array",
".",
"prototype",
".",
"forEach",
".",
"call",
"(",
"peaks",
",",
"function",
"(",
"val",
",",
"index",
")",
"{",
"if",
"(",
"Math",
".",
"abs",
"(",
"val",
")",
"<=",
"minValue",
")",
"{",
"silences",
".",
"push",
"(",
"index",
")",
";",
"}",
"}",
")",
";",
"// Cluster silence values",
"var",
"clusters",
"=",
"[",
"]",
";",
"silences",
".",
"forEach",
"(",
"function",
"(",
"val",
",",
"index",
")",
"{",
"if",
"(",
"clusters",
".",
"length",
"&&",
"val",
"==",
"silences",
"[",
"index",
"-",
"1",
"]",
"+",
"1",
")",
"{",
"clusters",
"[",
"clusters",
".",
"length",
"-",
"1",
"]",
".",
"push",
"(",
"val",
")",
";",
"}",
"else",
"{",
"clusters",
".",
"push",
"(",
"[",
"val",
"]",
")",
";",
"}",
"}",
")",
";",
"// Filter silence clusters by minimum length",
"var",
"fClusters",
"=",
"clusters",
".",
"filter",
"(",
"function",
"(",
"cluster",
")",
"{",
"return",
"cluster",
".",
"length",
">=",
"minLen",
";",
"}",
")",
";",
"// Create regions on the edges of silences",
"var",
"regions",
"=",
"fClusters",
".",
"map",
"(",
"function",
"(",
"cluster",
",",
"index",
")",
"{",
"var",
"next",
"=",
"fClusters",
"[",
"index",
"+",
"1",
"]",
";",
"return",
"{",
"start",
":",
"cluster",
"[",
"cluster",
".",
"length",
"-",
"1",
"]",
",",
"end",
":",
"next",
"?",
"next",
"[",
"0",
"]",
":",
"length",
"-",
"1",
"}",
";",
"}",
")",
";",
"// Add an initial region if the audio doesn't start with silence",
"var",
"firstCluster",
"=",
"fClusters",
"[",
"0",
"]",
";",
"if",
"(",
"firstCluster",
"&&",
"firstCluster",
"[",
"0",
"]",
"!=",
"0",
")",
"{",
"regions",
".",
"unshift",
"(",
"{",
"start",
":",
"0",
",",
"end",
":",
"firstCluster",
"[",
"firstCluster",
".",
"length",
"-",
"1",
"]",
"}",
")",
";",
"}",
"// Filter regions by minimum length",
"var",
"fRegions",
"=",
"regions",
".",
"filter",
"(",
"function",
"(",
"reg",
")",
"{",
"return",
"reg",
".",
"end",
"-",
"reg",
".",
"start",
">=",
"minLen",
";",
"}",
")",
";",
"// Return time-based regions",
"return",
"fRegions",
".",
"map",
"(",
"function",
"(",
"reg",
")",
"{",
"return",
"{",
"start",
":",
"Math",
".",
"round",
"(",
"reg",
".",
"start",
"*",
"coef",
"*",
"10",
")",
"/",
"10",
",",
"end",
":",
"Math",
".",
"round",
"(",
"reg",
".",
"end",
"*",
"coef",
"*",
"10",
")",
"/",
"10",
"}",
";",
"}",
")",
";",
"}"
] | Extract regions separated by silence. | [
"Extract",
"regions",
"separated",
"by",
"silence",
"."
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/annotation/app.js#L132-L194 |
5,946 | katspaugh/wavesurfer.js | example/annotation/app.js | editAnnotation | function editAnnotation(region) {
var form = document.forms.edit;
form.style.opacity = 1;
(form.elements.start.value = Math.round(region.start * 10) / 10),
(form.elements.end.value = Math.round(region.end * 10) / 10);
form.elements.note.value = region.data.note || '';
form.onsubmit = function(e) {
e.preventDefault();
region.update({
start: form.elements.start.value,
end: form.elements.end.value,
data: {
note: form.elements.note.value
}
});
form.style.opacity = 0;
};
form.onreset = function() {
form.style.opacity = 0;
form.dataset.region = null;
};
form.dataset.region = region.id;
} | javascript | function editAnnotation(region) {
var form = document.forms.edit;
form.style.opacity = 1;
(form.elements.start.value = Math.round(region.start * 10) / 10),
(form.elements.end.value = Math.round(region.end * 10) / 10);
form.elements.note.value = region.data.note || '';
form.onsubmit = function(e) {
e.preventDefault();
region.update({
start: form.elements.start.value,
end: form.elements.end.value,
data: {
note: form.elements.note.value
}
});
form.style.opacity = 0;
};
form.onreset = function() {
form.style.opacity = 0;
form.dataset.region = null;
};
form.dataset.region = region.id;
} | [
"function",
"editAnnotation",
"(",
"region",
")",
"{",
"var",
"form",
"=",
"document",
".",
"forms",
".",
"edit",
";",
"form",
".",
"style",
".",
"opacity",
"=",
"1",
";",
"(",
"form",
".",
"elements",
".",
"start",
".",
"value",
"=",
"Math",
".",
"round",
"(",
"region",
".",
"start",
"*",
"10",
")",
"/",
"10",
")",
",",
"(",
"form",
".",
"elements",
".",
"end",
".",
"value",
"=",
"Math",
".",
"round",
"(",
"region",
".",
"end",
"*",
"10",
")",
"/",
"10",
")",
";",
"form",
".",
"elements",
".",
"note",
".",
"value",
"=",
"region",
".",
"data",
".",
"note",
"||",
"''",
";",
"form",
".",
"onsubmit",
"=",
"function",
"(",
"e",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"region",
".",
"update",
"(",
"{",
"start",
":",
"form",
".",
"elements",
".",
"start",
".",
"value",
",",
"end",
":",
"form",
".",
"elements",
".",
"end",
".",
"value",
",",
"data",
":",
"{",
"note",
":",
"form",
".",
"elements",
".",
"note",
".",
"value",
"}",
"}",
")",
";",
"form",
".",
"style",
".",
"opacity",
"=",
"0",
";",
"}",
";",
"form",
".",
"onreset",
"=",
"function",
"(",
")",
"{",
"form",
".",
"style",
".",
"opacity",
"=",
"0",
";",
"form",
".",
"dataset",
".",
"region",
"=",
"null",
";",
"}",
";",
"form",
".",
"dataset",
".",
"region",
"=",
"region",
".",
"id",
";",
"}"
] | Edit annotation for a region. | [
"Edit",
"annotation",
"for",
"a",
"region",
"."
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/example/annotation/app.js#L215-L237 |
5,947 | katspaugh/wavesurfer.js | spec/plugin-api.spec.js | mockPlugin | function mockPlugin(name, deferInit = false) {
class MockPlugin {
constructor(params, ws) {
this.ws = ws;
// using the instance factory unfortunately makes it
// difficult to use the spyOn function, so we use this
// instead
this.isInitialised = false;
}
init() {
this.isInitialised = true;
}
destroy() {}
}
return {
name,
deferInit,
staticProps: {
[`${name}Static`]: 'static property value'
},
instance: MockPlugin
};
} | javascript | function mockPlugin(name, deferInit = false) {
class MockPlugin {
constructor(params, ws) {
this.ws = ws;
// using the instance factory unfortunately makes it
// difficult to use the spyOn function, so we use this
// instead
this.isInitialised = false;
}
init() {
this.isInitialised = true;
}
destroy() {}
}
return {
name,
deferInit,
staticProps: {
[`${name}Static`]: 'static property value'
},
instance: MockPlugin
};
} | [
"function",
"mockPlugin",
"(",
"name",
",",
"deferInit",
"=",
"false",
")",
"{",
"class",
"MockPlugin",
"{",
"constructor",
"(",
"params",
",",
"ws",
")",
"{",
"this",
".",
"ws",
"=",
"ws",
";",
"// using the instance factory unfortunately makes it",
"// difficult to use the spyOn function, so we use this",
"// instead",
"this",
".",
"isInitialised",
"=",
"false",
";",
"}",
"init",
"(",
")",
"{",
"this",
".",
"isInitialised",
"=",
"true",
";",
"}",
"destroy",
"(",
")",
"{",
"}",
"}",
"return",
"{",
"name",
",",
"deferInit",
",",
"staticProps",
":",
"{",
"[",
"`",
"${",
"name",
"}",
"`",
"]",
":",
"'static property value'",
"}",
",",
"instance",
":",
"MockPlugin",
"}",
";",
"}"
] | utility function to generate a mock plugin object | [
"utility",
"function",
"to",
"generate",
"a",
"mock",
"plugin",
"object"
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/spec/plugin-api.spec.js#L24-L46 |
5,948 | katspaugh/wavesurfer.js | spec/plugin-api.spec.js | __createWaveform | function __createWaveform(options = {}) {
waveformDiv = document.createElement('div');
document.getElementsByTagName('body')[0].appendChild(waveformDiv);
wavesurfer = WaveSurfer.create(
Object.assign(
{
container: waveformDiv
},
options
)
);
wavesurfer.load(TestHelpers.EXAMPLE_FILE_PATH);
} | javascript | function __createWaveform(options = {}) {
waveformDiv = document.createElement('div');
document.getElementsByTagName('body')[0].appendChild(waveformDiv);
wavesurfer = WaveSurfer.create(
Object.assign(
{
container: waveformDiv
},
options
)
);
wavesurfer.load(TestHelpers.EXAMPLE_FILE_PATH);
} | [
"function",
"__createWaveform",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"waveformDiv",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"document",
".",
"getElementsByTagName",
"(",
"'body'",
")",
"[",
"0",
"]",
".",
"appendChild",
"(",
"waveformDiv",
")",
";",
"wavesurfer",
"=",
"WaveSurfer",
".",
"create",
"(",
"Object",
".",
"assign",
"(",
"{",
"container",
":",
"waveformDiv",
"}",
",",
"options",
")",
")",
";",
"wavesurfer",
".",
"load",
"(",
"TestHelpers",
".",
"EXAMPLE_FILE_PATH",
")",
";",
"}"
] | utility function to generate wavesurfer instances for testing | [
"utility",
"function",
"to",
"generate",
"wavesurfer",
"instances",
"for",
"testing"
] | 45144cf7d4a0424aff3878d918bda9a44197b6e4 | https://github.com/katspaugh/wavesurfer.js/blob/45144cf7d4a0424aff3878d918bda9a44197b6e4/spec/plugin-api.spec.js#L49-L62 |
5,949 | jashkenas/coffeescript | lib/coffeescript/cake.js | function(name, description, action) {
if (!action) {
[action, description] = [description, action];
}
return tasks[name] = {name, description, action};
} | javascript | function(name, description, action) {
if (!action) {
[action, description] = [description, action];
}
return tasks[name] = {name, description, action};
} | [
"function",
"(",
"name",
",",
"description",
",",
"action",
")",
"{",
"if",
"(",
"!",
"action",
")",
"{",
"[",
"action",
",",
"description",
"]",
"=",
"[",
"description",
",",
"action",
"]",
";",
"}",
"return",
"tasks",
"[",
"name",
"]",
"=",
"{",
"name",
",",
"description",
",",
"action",
"}",
";",
"}"
] | Define a Cake task with a short name, an optional sentence description, and the function to run as the action itself. | [
"Define",
"a",
"Cake",
"task",
"with",
"a",
"short",
"name",
"an",
"optional",
"sentence",
"description",
"and",
"the",
"function",
"to",
"run",
"as",
"the",
"action",
"itself",
"."
] | 71750554c3a94d276a5c5344d77292fff5205e49 | https://github.com/jashkenas/coffeescript/blob/71750554c3a94d276a5c5344d77292fff5205e49/lib/coffeescript/cake.js#L40-L45 |
|
5,950 | autoNumeric/autoNumeric | src/AutoNumericOptions.js | freezeOptions | function freezeOptions(options) {
// Freeze each property objects
Object.getOwnPropertyNames(options).forEach(optionName => {
if (optionName === 'valuesToStrings') {
const vsProps = Object.getOwnPropertyNames(options.valuesToStrings);
vsProps.forEach(valuesToStringObjectName => {
if (!AutoNumericHelper.isIE11() && options.valuesToStrings[valuesToStringObjectName] !== null) {
Object.freeze(options.valuesToStrings[valuesToStringObjectName]);
}
});
} else if (optionName !== 'styleRules') {
if (!AutoNumericHelper.isIE11() && options[optionName] !== null) {
Object.freeze(options[optionName]);
}
}
});
// Then freeze the options object globally
return Object.freeze(options);
} | javascript | function freezeOptions(options) {
// Freeze each property objects
Object.getOwnPropertyNames(options).forEach(optionName => {
if (optionName === 'valuesToStrings') {
const vsProps = Object.getOwnPropertyNames(options.valuesToStrings);
vsProps.forEach(valuesToStringObjectName => {
if (!AutoNumericHelper.isIE11() && options.valuesToStrings[valuesToStringObjectName] !== null) {
Object.freeze(options.valuesToStrings[valuesToStringObjectName]);
}
});
} else if (optionName !== 'styleRules') {
if (!AutoNumericHelper.isIE11() && options[optionName] !== null) {
Object.freeze(options[optionName]);
}
}
});
// Then freeze the options object globally
return Object.freeze(options);
} | [
"function",
"freezeOptions",
"(",
"options",
")",
"{",
"// Freeze each property objects",
"Object",
".",
"getOwnPropertyNames",
"(",
"options",
")",
".",
"forEach",
"(",
"optionName",
"=>",
"{",
"if",
"(",
"optionName",
"===",
"'valuesToStrings'",
")",
"{",
"const",
"vsProps",
"=",
"Object",
".",
"getOwnPropertyNames",
"(",
"options",
".",
"valuesToStrings",
")",
";",
"vsProps",
".",
"forEach",
"(",
"valuesToStringObjectName",
"=>",
"{",
"if",
"(",
"!",
"AutoNumericHelper",
".",
"isIE11",
"(",
")",
"&&",
"options",
".",
"valuesToStrings",
"[",
"valuesToStringObjectName",
"]",
"!==",
"null",
")",
"{",
"Object",
".",
"freeze",
"(",
"options",
".",
"valuesToStrings",
"[",
"valuesToStringObjectName",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"optionName",
"!==",
"'styleRules'",
")",
"{",
"if",
"(",
"!",
"AutoNumericHelper",
".",
"isIE11",
"(",
")",
"&&",
"options",
"[",
"optionName",
"]",
"!==",
"null",
")",
"{",
"Object",
".",
"freeze",
"(",
"options",
"[",
"optionName",
"]",
")",
";",
"}",
"}",
"}",
")",
";",
"// Then freeze the options object globally",
"return",
"Object",
".",
"freeze",
"(",
"options",
")",
";",
"}"
] | Simple function that will semi-deep freeze the `AutoNumeric.options` object.
By 'semi' it means the nested objects in the `styleRules` option are not frozen.
The ones in the `valuesToStrings` are though, since they are much more simple.
@param {object} options
@returns {ReadonlyArray<any>} | [
"Simple",
"function",
"that",
"will",
"semi",
"-",
"deep",
"freeze",
"the",
"AutoNumeric",
".",
"options",
"object",
".",
"By",
"semi",
"it",
"means",
"the",
"nested",
"objects",
"in",
"the",
"styleRules",
"option",
"are",
"not",
"frozen",
".",
"The",
"ones",
"in",
"the",
"valuesToStrings",
"are",
"though",
"since",
"they",
"are",
"much",
"more",
"simple",
"."
] | c54267b08f87ae5727a211e25d0f43259b75e573 | https://github.com/autoNumeric/autoNumeric/blob/c54267b08f87ae5727a211e25d0f43259b75e573/src/AutoNumericOptions.js#L866-L885 |
5,951 | Netflix/falcor | lib/errors/InvalidDerefInputError.js | InvalidDerefInputError | function InvalidDerefInputError() {
var instance = new Error("Deref can only be used with a non-primitive object from get, set, or call.");
instance.name = "InvalidDerefInputError";
if (Object.setPrototypeOf) {
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
}
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, InvalidDerefInputError);
}
return instance;
} | javascript | function InvalidDerefInputError() {
var instance = new Error("Deref can only be used with a non-primitive object from get, set, or call.");
instance.name = "InvalidDerefInputError";
if (Object.setPrototypeOf) {
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
}
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, InvalidDerefInputError);
}
return instance;
} | [
"function",
"InvalidDerefInputError",
"(",
")",
"{",
"var",
"instance",
"=",
"new",
"Error",
"(",
"\"Deref can only be used with a non-primitive object from get, set, or call.\"",
")",
";",
"instance",
".",
"name",
"=",
"\"InvalidDerefInputError\"",
";",
"if",
"(",
"Object",
".",
"setPrototypeOf",
")",
"{",
"Object",
".",
"setPrototypeOf",
"(",
"instance",
",",
"Object",
".",
"getPrototypeOf",
"(",
"this",
")",
")",
";",
"}",
"if",
"(",
"Error",
".",
"captureStackTrace",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"instance",
",",
"InvalidDerefInputError",
")",
";",
"}",
"return",
"instance",
";",
"}"
] | An invalid deref input is when deref is used with input that is not generated
from a get, set, or a call.
@private | [
"An",
"invalid",
"deref",
"input",
"is",
"when",
"deref",
"is",
"used",
"with",
"input",
"that",
"is",
"not",
"generated",
"from",
"a",
"get",
"set",
"or",
"a",
"call",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/errors/InvalidDerefInputError.js#L9-L23 |
5,952 | Netflix/falcor | lib/request/GetRequestV2.js | function(scheduler, requestQueue) {
this.sent = false;
this.scheduled = false;
this.requestQueue = requestQueue;
this.id = ++REQUEST_ID;
this.type = GetRequestType;
this._scheduler = scheduler;
this._pathMap = {};
this._optimizedPaths = [];
this._requestedPaths = [];
this._callbacks = [];
this._count = 0;
this._disposable = null;
this._collapsed = null;
this._disposed = false;
} | javascript | function(scheduler, requestQueue) {
this.sent = false;
this.scheduled = false;
this.requestQueue = requestQueue;
this.id = ++REQUEST_ID;
this.type = GetRequestType;
this._scheduler = scheduler;
this._pathMap = {};
this._optimizedPaths = [];
this._requestedPaths = [];
this._callbacks = [];
this._count = 0;
this._disposable = null;
this._collapsed = null;
this._disposed = false;
} | [
"function",
"(",
"scheduler",
",",
"requestQueue",
")",
"{",
"this",
".",
"sent",
"=",
"false",
";",
"this",
".",
"scheduled",
"=",
"false",
";",
"this",
".",
"requestQueue",
"=",
"requestQueue",
";",
"this",
".",
"id",
"=",
"++",
"REQUEST_ID",
";",
"this",
".",
"type",
"=",
"GetRequestType",
";",
"this",
".",
"_scheduler",
"=",
"scheduler",
";",
"this",
".",
"_pathMap",
"=",
"{",
"}",
";",
"this",
".",
"_optimizedPaths",
"=",
"[",
"]",
";",
"this",
".",
"_requestedPaths",
"=",
"[",
"]",
";",
"this",
".",
"_callbacks",
"=",
"[",
"]",
";",
"this",
".",
"_count",
"=",
"0",
";",
"this",
".",
"_disposable",
"=",
"null",
";",
"this",
".",
"_collapsed",
"=",
"null",
";",
"this",
".",
"_disposed",
"=",
"false",
";",
"}"
] | Creates a new GetRequest. This GetRequest takes a scheduler and
the request queue. Once the scheduler fires, all batched requests
will be sent to the server. Upon request completion, the data is
merged back into the cache and all callbacks are notified.
@param {Scheduler} scheduler -
@param {RequestQueueV2} requestQueue - | [
"Creates",
"a",
"new",
"GetRequest",
".",
"This",
"GetRequest",
"takes",
"a",
"scheduler",
"and",
"the",
"request",
"queue",
".",
"Once",
"the",
"scheduler",
"fires",
"all",
"batched",
"requests",
"will",
"be",
"sent",
"to",
"the",
"server",
".",
"Upon",
"request",
"completion",
"the",
"data",
"is",
"merged",
"back",
"into",
"the",
"cache",
"and",
"all",
"callbacks",
"are",
"notified",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/request/GetRequestV2.js#L23-L39 |
|
5,953 | Netflix/falcor | lib/request/GetRequestV2.js | function(requestedPaths, optimizedPaths, callback) {
var self = this;
var oPaths = self._optimizedPaths;
var rPaths = self._requestedPaths;
var callbacks = self._callbacks;
var idx = oPaths.length;
// If its not sent, simply add it to the requested paths
// and callbacks.
oPaths[idx] = optimizedPaths;
rPaths[idx] = requestedPaths;
callbacks[idx] = callback;
++self._count;
// If it has not been scheduled, then schedule the action
if (!self.scheduled) {
self.scheduled = true;
var flushedDisposable;
var scheduleDisposable = self._scheduler.schedule(function() {
flushedDisposable = flushGetRequest(self, oPaths, function(err, data) {
var i, fn, len;
var model = self.requestQueue.model;
self.requestQueue.removeRequest(self);
self._disposed = true;
if (model._treatDataSourceErrorsAsJSONGraphErrors ? err instanceof InvalidSourceError : !!err) {
for (i = 0, len = callbacks.length; i < len; ++i) {
fn = callbacks[i];
if (fn) {
fn(err);
}
}
return;
}
// If there is at least one callback remaining, then
// callback the callbacks.
if (self._count) {
// currentVersion will get added to each inserted
// node as node.$_version inside of self._merge.
//
// atom values just downloaded with $expires: 0
// (now-expired) will get assigned $_version equal
// to currentVersion, and checkCacheAndReport will
// later consider those nodes to not have expired
// for the duration of current event loop tick
//
// we unset currentCacheVersion after all callbacks
// have been called, to ensure that only these
// particular callbacks and any synchronous model.get
// callbacks inside of these, get the now-expired
// values
var currentVersion = incrementVersion.getCurrentVersion();
currentCacheVersion.setVersion(currentVersion);
var mergeContext = { hasInvalidatedResult: false };
var pathsErr = model._useServerPaths && data && data.paths === undefined ?
new Error("Server responses must include a 'paths' field when Model._useServerPaths === true") : undefined;
if (!pathsErr) {
self._merge(rPaths, err, data, mergeContext);
}
// Call the callbacks. The first one inserts all
// the data so that the rest do not have consider
// if their data is present or not.
for (i = 0, len = callbacks.length; i < len; ++i) {
fn = callbacks[i];
if (fn) {
fn(pathsErr || err, data, mergeContext.hasInvalidatedResult);
}
}
currentCacheVersion.setVersion(null);
}
});
self._disposable = flushedDisposable;
});
// If the scheduler is sync then `flushedDisposable` will be
// defined, and we want to use it, because that's what aborts an
// in-flight XHR request, for example.
// But if the scheduler is async, then `flushedDisposable` won't be
// defined yet, and so we must use the scheduler's disposable until
// `flushedDisposable` is defined. Since we want to still use
// `flushedDisposable` once it is defined (to be able to abort in-
// flight XHR requests), hence the reassignment of `_disposable`
// above.
self._disposable = flushedDisposable || scheduleDisposable;
}
// Disposes this batched request. This does not mean that the
// entire request has been disposed, but just the local one, if all
// requests are disposed, then the outer disposable will be removed.
return createDisposable(self, idx);
} | javascript | function(requestedPaths, optimizedPaths, callback) {
var self = this;
var oPaths = self._optimizedPaths;
var rPaths = self._requestedPaths;
var callbacks = self._callbacks;
var idx = oPaths.length;
// If its not sent, simply add it to the requested paths
// and callbacks.
oPaths[idx] = optimizedPaths;
rPaths[idx] = requestedPaths;
callbacks[idx] = callback;
++self._count;
// If it has not been scheduled, then schedule the action
if (!self.scheduled) {
self.scheduled = true;
var flushedDisposable;
var scheduleDisposable = self._scheduler.schedule(function() {
flushedDisposable = flushGetRequest(self, oPaths, function(err, data) {
var i, fn, len;
var model = self.requestQueue.model;
self.requestQueue.removeRequest(self);
self._disposed = true;
if (model._treatDataSourceErrorsAsJSONGraphErrors ? err instanceof InvalidSourceError : !!err) {
for (i = 0, len = callbacks.length; i < len; ++i) {
fn = callbacks[i];
if (fn) {
fn(err);
}
}
return;
}
// If there is at least one callback remaining, then
// callback the callbacks.
if (self._count) {
// currentVersion will get added to each inserted
// node as node.$_version inside of self._merge.
//
// atom values just downloaded with $expires: 0
// (now-expired) will get assigned $_version equal
// to currentVersion, and checkCacheAndReport will
// later consider those nodes to not have expired
// for the duration of current event loop tick
//
// we unset currentCacheVersion after all callbacks
// have been called, to ensure that only these
// particular callbacks and any synchronous model.get
// callbacks inside of these, get the now-expired
// values
var currentVersion = incrementVersion.getCurrentVersion();
currentCacheVersion.setVersion(currentVersion);
var mergeContext = { hasInvalidatedResult: false };
var pathsErr = model._useServerPaths && data && data.paths === undefined ?
new Error("Server responses must include a 'paths' field when Model._useServerPaths === true") : undefined;
if (!pathsErr) {
self._merge(rPaths, err, data, mergeContext);
}
// Call the callbacks. The first one inserts all
// the data so that the rest do not have consider
// if their data is present or not.
for (i = 0, len = callbacks.length; i < len; ++i) {
fn = callbacks[i];
if (fn) {
fn(pathsErr || err, data, mergeContext.hasInvalidatedResult);
}
}
currentCacheVersion.setVersion(null);
}
});
self._disposable = flushedDisposable;
});
// If the scheduler is sync then `flushedDisposable` will be
// defined, and we want to use it, because that's what aborts an
// in-flight XHR request, for example.
// But if the scheduler is async, then `flushedDisposable` won't be
// defined yet, and so we must use the scheduler's disposable until
// `flushedDisposable` is defined. Since we want to still use
// `flushedDisposable` once it is defined (to be able to abort in-
// flight XHR requests), hence the reassignment of `_disposable`
// above.
self._disposable = flushedDisposable || scheduleDisposable;
}
// Disposes this batched request. This does not mean that the
// entire request has been disposed, but just the local one, if all
// requests are disposed, then the outer disposable will be removed.
return createDisposable(self, idx);
} | [
"function",
"(",
"requestedPaths",
",",
"optimizedPaths",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"oPaths",
"=",
"self",
".",
"_optimizedPaths",
";",
"var",
"rPaths",
"=",
"self",
".",
"_requestedPaths",
";",
"var",
"callbacks",
"=",
"self",
".",
"_callbacks",
";",
"var",
"idx",
"=",
"oPaths",
".",
"length",
";",
"// If its not sent, simply add it to the requested paths",
"// and callbacks.",
"oPaths",
"[",
"idx",
"]",
"=",
"optimizedPaths",
";",
"rPaths",
"[",
"idx",
"]",
"=",
"requestedPaths",
";",
"callbacks",
"[",
"idx",
"]",
"=",
"callback",
";",
"++",
"self",
".",
"_count",
";",
"// If it has not been scheduled, then schedule the action",
"if",
"(",
"!",
"self",
".",
"scheduled",
")",
"{",
"self",
".",
"scheduled",
"=",
"true",
";",
"var",
"flushedDisposable",
";",
"var",
"scheduleDisposable",
"=",
"self",
".",
"_scheduler",
".",
"schedule",
"(",
"function",
"(",
")",
"{",
"flushedDisposable",
"=",
"flushGetRequest",
"(",
"self",
",",
"oPaths",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"var",
"i",
",",
"fn",
",",
"len",
";",
"var",
"model",
"=",
"self",
".",
"requestQueue",
".",
"model",
";",
"self",
".",
"requestQueue",
".",
"removeRequest",
"(",
"self",
")",
";",
"self",
".",
"_disposed",
"=",
"true",
";",
"if",
"(",
"model",
".",
"_treatDataSourceErrorsAsJSONGraphErrors",
"?",
"err",
"instanceof",
"InvalidSourceError",
":",
"!",
"!",
"err",
")",
"{",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"callbacks",
".",
"length",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"fn",
"=",
"callbacks",
"[",
"i",
"]",
";",
"if",
"(",
"fn",
")",
"{",
"fn",
"(",
"err",
")",
";",
"}",
"}",
"return",
";",
"}",
"// If there is at least one callback remaining, then",
"// callback the callbacks.",
"if",
"(",
"self",
".",
"_count",
")",
"{",
"// currentVersion will get added to each inserted",
"// node as node.$_version inside of self._merge.",
"//",
"// atom values just downloaded with $expires: 0",
"// (now-expired) will get assigned $_version equal",
"// to currentVersion, and checkCacheAndReport will",
"// later consider those nodes to not have expired",
"// for the duration of current event loop tick",
"//",
"// we unset currentCacheVersion after all callbacks",
"// have been called, to ensure that only these",
"// particular callbacks and any synchronous model.get",
"// callbacks inside of these, get the now-expired",
"// values",
"var",
"currentVersion",
"=",
"incrementVersion",
".",
"getCurrentVersion",
"(",
")",
";",
"currentCacheVersion",
".",
"setVersion",
"(",
"currentVersion",
")",
";",
"var",
"mergeContext",
"=",
"{",
"hasInvalidatedResult",
":",
"false",
"}",
";",
"var",
"pathsErr",
"=",
"model",
".",
"_useServerPaths",
"&&",
"data",
"&&",
"data",
".",
"paths",
"===",
"undefined",
"?",
"new",
"Error",
"(",
"\"Server responses must include a 'paths' field when Model._useServerPaths === true\"",
")",
":",
"undefined",
";",
"if",
"(",
"!",
"pathsErr",
")",
"{",
"self",
".",
"_merge",
"(",
"rPaths",
",",
"err",
",",
"data",
",",
"mergeContext",
")",
";",
"}",
"// Call the callbacks. The first one inserts all",
"// the data so that the rest do not have consider",
"// if their data is present or not.",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"callbacks",
".",
"length",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"fn",
"=",
"callbacks",
"[",
"i",
"]",
";",
"if",
"(",
"fn",
")",
"{",
"fn",
"(",
"pathsErr",
"||",
"err",
",",
"data",
",",
"mergeContext",
".",
"hasInvalidatedResult",
")",
";",
"}",
"}",
"currentCacheVersion",
".",
"setVersion",
"(",
"null",
")",
";",
"}",
"}",
")",
";",
"self",
".",
"_disposable",
"=",
"flushedDisposable",
";",
"}",
")",
";",
"// If the scheduler is sync then `flushedDisposable` will be",
"// defined, and we want to use it, because that's what aborts an",
"// in-flight XHR request, for example.",
"// But if the scheduler is async, then `flushedDisposable` won't be",
"// defined yet, and so we must use the scheduler's disposable until",
"// `flushedDisposable` is defined. Since we want to still use",
"// `flushedDisposable` once it is defined (to be able to abort in-",
"// flight XHR requests), hence the reassignment of `_disposable`",
"// above.",
"self",
".",
"_disposable",
"=",
"flushedDisposable",
"||",
"scheduleDisposable",
";",
"}",
"// Disposes this batched request. This does not mean that the",
"// entire request has been disposed, but just the local one, if all",
"// requests are disposed, then the outer disposable will be removed.",
"return",
"createDisposable",
"(",
"self",
",",
"idx",
")",
";",
"}"
] | batches the paths that are passed in. Once the request is complete,
all callbacks will be called and the request will be removed from
parent queue.
@param {Array} requestedPaths -
@param {Array} optimizedPaths -
@param {Function} callback - | [
"batches",
"the",
"paths",
"that",
"are",
"passed",
"in",
".",
"Once",
"the",
"request",
"is",
"complete",
"all",
"callbacks",
"will",
"be",
"called",
"and",
"the",
"request",
"will",
"be",
"removed",
"from",
"parent",
"queue",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/request/GetRequestV2.js#L50-L145 |
|
5,954 | Netflix/falcor | lib/request/GetRequestV2.js | function(requested, optimized, callback) {
// uses the length tree complement calculator.
var self = this;
var complementResult = complement(requested, optimized, self._pathMap);
var inserted = false;
var disposable = false;
// If we found an intersection, then just add new callback
// as one of the dependents of that request
if (complementResult.intersection.length) {
inserted = true;
var idx = self._callbacks.length;
self._callbacks[idx] = callback;
self._requestedPaths[idx] = complementResult.intersection;
self._optimizedPaths[idx] = [];
++self._count;
disposable = createDisposable(self, idx);
}
return [inserted, complementResult.requestedComplement, complementResult.optimizedComplement, disposable];
} | javascript | function(requested, optimized, callback) {
// uses the length tree complement calculator.
var self = this;
var complementResult = complement(requested, optimized, self._pathMap);
var inserted = false;
var disposable = false;
// If we found an intersection, then just add new callback
// as one of the dependents of that request
if (complementResult.intersection.length) {
inserted = true;
var idx = self._callbacks.length;
self._callbacks[idx] = callback;
self._requestedPaths[idx] = complementResult.intersection;
self._optimizedPaths[idx] = [];
++self._count;
disposable = createDisposable(self, idx);
}
return [inserted, complementResult.requestedComplement, complementResult.optimizedComplement, disposable];
} | [
"function",
"(",
"requested",
",",
"optimized",
",",
"callback",
")",
"{",
"// uses the length tree complement calculator.",
"var",
"self",
"=",
"this",
";",
"var",
"complementResult",
"=",
"complement",
"(",
"requested",
",",
"optimized",
",",
"self",
".",
"_pathMap",
")",
";",
"var",
"inserted",
"=",
"false",
";",
"var",
"disposable",
"=",
"false",
";",
"// If we found an intersection, then just add new callback",
"// as one of the dependents of that request",
"if",
"(",
"complementResult",
".",
"intersection",
".",
"length",
")",
"{",
"inserted",
"=",
"true",
";",
"var",
"idx",
"=",
"self",
".",
"_callbacks",
".",
"length",
";",
"self",
".",
"_callbacks",
"[",
"idx",
"]",
"=",
"callback",
";",
"self",
".",
"_requestedPaths",
"[",
"idx",
"]",
"=",
"complementResult",
".",
"intersection",
";",
"self",
".",
"_optimizedPaths",
"[",
"idx",
"]",
"=",
"[",
"]",
";",
"++",
"self",
".",
"_count",
";",
"disposable",
"=",
"createDisposable",
"(",
"self",
",",
"idx",
")",
";",
"}",
"return",
"[",
"inserted",
",",
"complementResult",
".",
"requestedComplement",
",",
"complementResult",
".",
"optimizedComplement",
",",
"disposable",
"]",
";",
"}"
] | Attempts to add paths to the outgoing request. If there are added
paths then the request callback will be added to the callback list.
Handles adding partial paths as well
@returns {Array} - whether new requested paths were inserted in this
request, the remaining paths that could not be added,
and disposable for the inserted requested paths. | [
"Attempts",
"to",
"add",
"paths",
"to",
"the",
"outgoing",
"request",
".",
"If",
"there",
"are",
"added",
"paths",
"then",
"the",
"request",
"callback",
"will",
"be",
"added",
"to",
"the",
"callback",
"list",
".",
"Handles",
"adding",
"partial",
"paths",
"as",
"well"
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/request/GetRequestV2.js#L156-L178 |
|
5,955 | Netflix/falcor | lib/request/GetRequestV2.js | function(requested, err, data, mergeContext) {
var self = this;
var model = self.requestQueue.model;
var modelRoot = model._root;
var errorSelector = modelRoot.errorSelector;
var comparator = modelRoot.comparator;
var boundPath = model._path;
model._path = emptyArray;
// flatten all the requested paths, adds them to the
var nextPaths = model._useServerPaths ? data.paths : flattenRequestedPaths(requested);
// Insert errors in every requested position.
if (err && model._treatDataSourceErrorsAsJSONGraphErrors) {
var error = err;
// Converts errors to objects, a more friendly storage
// of errors.
if (error instanceof Error) {
error = {
message: error.message
};
}
// Not all errors are value $types.
if (!error.$type) {
error = {
$type: $error,
value: error
};
}
var pathValues = nextPaths.map(function(x) {
return {
path: x,
value: error
};
});
setPathValues(model, pathValues, null, errorSelector, comparator, mergeContext);
}
// Insert the jsonGraph from the dataSource.
else {
setJSONGraphs(model, [{
paths: nextPaths,
jsonGraph: data.jsonGraph
}], null, errorSelector, comparator, mergeContext);
}
// return the model"s boundPath
model._path = boundPath;
} | javascript | function(requested, err, data, mergeContext) {
var self = this;
var model = self.requestQueue.model;
var modelRoot = model._root;
var errorSelector = modelRoot.errorSelector;
var comparator = modelRoot.comparator;
var boundPath = model._path;
model._path = emptyArray;
// flatten all the requested paths, adds them to the
var nextPaths = model._useServerPaths ? data.paths : flattenRequestedPaths(requested);
// Insert errors in every requested position.
if (err && model._treatDataSourceErrorsAsJSONGraphErrors) {
var error = err;
// Converts errors to objects, a more friendly storage
// of errors.
if (error instanceof Error) {
error = {
message: error.message
};
}
// Not all errors are value $types.
if (!error.$type) {
error = {
$type: $error,
value: error
};
}
var pathValues = nextPaths.map(function(x) {
return {
path: x,
value: error
};
});
setPathValues(model, pathValues, null, errorSelector, comparator, mergeContext);
}
// Insert the jsonGraph from the dataSource.
else {
setJSONGraphs(model, [{
paths: nextPaths,
jsonGraph: data.jsonGraph
}], null, errorSelector, comparator, mergeContext);
}
// return the model"s boundPath
model._path = boundPath;
} | [
"function",
"(",
"requested",
",",
"err",
",",
"data",
",",
"mergeContext",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"model",
"=",
"self",
".",
"requestQueue",
".",
"model",
";",
"var",
"modelRoot",
"=",
"model",
".",
"_root",
";",
"var",
"errorSelector",
"=",
"modelRoot",
".",
"errorSelector",
";",
"var",
"comparator",
"=",
"modelRoot",
".",
"comparator",
";",
"var",
"boundPath",
"=",
"model",
".",
"_path",
";",
"model",
".",
"_path",
"=",
"emptyArray",
";",
"// flatten all the requested paths, adds them to the",
"var",
"nextPaths",
"=",
"model",
".",
"_useServerPaths",
"?",
"data",
".",
"paths",
":",
"flattenRequestedPaths",
"(",
"requested",
")",
";",
"// Insert errors in every requested position.",
"if",
"(",
"err",
"&&",
"model",
".",
"_treatDataSourceErrorsAsJSONGraphErrors",
")",
"{",
"var",
"error",
"=",
"err",
";",
"// Converts errors to objects, a more friendly storage",
"// of errors.",
"if",
"(",
"error",
"instanceof",
"Error",
")",
"{",
"error",
"=",
"{",
"message",
":",
"error",
".",
"message",
"}",
";",
"}",
"// Not all errors are value $types.",
"if",
"(",
"!",
"error",
".",
"$type",
")",
"{",
"error",
"=",
"{",
"$type",
":",
"$error",
",",
"value",
":",
"error",
"}",
";",
"}",
"var",
"pathValues",
"=",
"nextPaths",
".",
"map",
"(",
"function",
"(",
"x",
")",
"{",
"return",
"{",
"path",
":",
"x",
",",
"value",
":",
"error",
"}",
";",
"}",
")",
";",
"setPathValues",
"(",
"model",
",",
"pathValues",
",",
"null",
",",
"errorSelector",
",",
"comparator",
",",
"mergeContext",
")",
";",
"}",
"// Insert the jsonGraph from the dataSource.",
"else",
"{",
"setJSONGraphs",
"(",
"model",
",",
"[",
"{",
"paths",
":",
"nextPaths",
",",
"jsonGraph",
":",
"data",
".",
"jsonGraph",
"}",
"]",
",",
"null",
",",
"errorSelector",
",",
"comparator",
",",
"mergeContext",
")",
";",
"}",
"// return the model\"s boundPath",
"model",
".",
"_path",
"=",
"boundPath",
";",
"}"
] | merges the response into the model"s cache. | [
"merges",
"the",
"response",
"into",
"the",
"model",
"s",
"cache",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/request/GetRequestV2.js#L183-L235 |
|
5,956 | Netflix/falcor | lib/request/GetRequestV2.js | createDisposable | function createDisposable(request, idx) {
var disposed = false;
return function() {
if (disposed || request._disposed) {
return;
}
disposed = true;
request._callbacks[idx] = null;
request._optimizedPaths[idx] = [];
request._requestedPaths[idx] = [];
// If there are no more requests, then dispose all of the request.
var count = --request._count;
var disposable = request._disposable;
if (count === 0) {
// looking for unsubscribe here to support more data sources (Rx)
if (disposable.unsubscribe) {
disposable.unsubscribe();
} else {
disposable.dispose();
}
request.requestQueue.removeRequest(request);
}
};
} | javascript | function createDisposable(request, idx) {
var disposed = false;
return function() {
if (disposed || request._disposed) {
return;
}
disposed = true;
request._callbacks[idx] = null;
request._optimizedPaths[idx] = [];
request._requestedPaths[idx] = [];
// If there are no more requests, then dispose all of the request.
var count = --request._count;
var disposable = request._disposable;
if (count === 0) {
// looking for unsubscribe here to support more data sources (Rx)
if (disposable.unsubscribe) {
disposable.unsubscribe();
} else {
disposable.dispose();
}
request.requestQueue.removeRequest(request);
}
};
} | [
"function",
"createDisposable",
"(",
"request",
",",
"idx",
")",
"{",
"var",
"disposed",
"=",
"false",
";",
"return",
"function",
"(",
")",
"{",
"if",
"(",
"disposed",
"||",
"request",
".",
"_disposed",
")",
"{",
"return",
";",
"}",
"disposed",
"=",
"true",
";",
"request",
".",
"_callbacks",
"[",
"idx",
"]",
"=",
"null",
";",
"request",
".",
"_optimizedPaths",
"[",
"idx",
"]",
"=",
"[",
"]",
";",
"request",
".",
"_requestedPaths",
"[",
"idx",
"]",
"=",
"[",
"]",
";",
"// If there are no more requests, then dispose all of the request.",
"var",
"count",
"=",
"--",
"request",
".",
"_count",
";",
"var",
"disposable",
"=",
"request",
".",
"_disposable",
";",
"if",
"(",
"count",
"===",
"0",
")",
"{",
"// looking for unsubscribe here to support more data sources (Rx)",
"if",
"(",
"disposable",
".",
"unsubscribe",
")",
"{",
"disposable",
".",
"unsubscribe",
"(",
")",
";",
"}",
"else",
"{",
"disposable",
".",
"dispose",
"(",
")",
";",
"}",
"request",
".",
"requestQueue",
".",
"removeRequest",
"(",
"request",
")",
";",
"}",
"}",
";",
"}"
] | Creates a more efficient closure of the things that are needed. So the request and the idx. Also prevents code duplication. | [
"Creates",
"a",
"more",
"efficient",
"closure",
"of",
"the",
"things",
"that",
"are",
"needed",
".",
"So",
"the",
"request",
"and",
"the",
"idx",
".",
"Also",
"prevents",
"code",
"duplication",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/request/GetRequestV2.js#L241-L266 |
5,957 | Netflix/falcor | lib/response/AssignableDisposable.js | dispose | function dispose() {
if (this.disposed || !this.currentDisposable) {
return;
}
this.disposed = true;
// If the current disposable fulfills the disposable interface or just
// a disposable function.
var currentDisposable = this.currentDisposable;
if (currentDisposable.dispose) {
currentDisposable.dispose();
}
else {
currentDisposable();
}
} | javascript | function dispose() {
if (this.disposed || !this.currentDisposable) {
return;
}
this.disposed = true;
// If the current disposable fulfills the disposable interface or just
// a disposable function.
var currentDisposable = this.currentDisposable;
if (currentDisposable.dispose) {
currentDisposable.dispose();
}
else {
currentDisposable();
}
} | [
"function",
"dispose",
"(",
")",
"{",
"if",
"(",
"this",
".",
"disposed",
"||",
"!",
"this",
".",
"currentDisposable",
")",
"{",
"return",
";",
"}",
"this",
".",
"disposed",
"=",
"true",
";",
"// If the current disposable fulfills the disposable interface or just",
"// a disposable function.",
"var",
"currentDisposable",
"=",
"this",
".",
"currentDisposable",
";",
"if",
"(",
"currentDisposable",
".",
"dispose",
")",
"{",
"currentDisposable",
".",
"dispose",
"(",
")",
";",
"}",
"else",
"{",
"currentDisposable",
"(",
")",
";",
"}",
"}"
] | Disposes of the current disposable. This would be the getRequestCycle
disposable. | [
"Disposes",
"of",
"the",
"current",
"disposable",
".",
"This",
"would",
"be",
"the",
"getRequestCycle",
"disposable",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/response/AssignableDisposable.js#L18-L34 |
5,958 | Netflix/falcor | lib/response/set/SetResponse.js | SetResponse | function SetResponse(model, args, isJSONGraph,
isProgressive) {
// The response properties.
this._model = model;
this._isJSONGraph = isJSONGraph || false;
this._isProgressive = isProgressive || false;
this._initialArgs = args;
this._value = [{}];
var groups = [];
var group, groupType;
var argIndex = -1;
var argCount = args.length;
// Validation of arguments have been moved out of this function.
while (++argIndex < argCount) {
var arg = args[argIndex];
var argType;
if (isArray(arg) || typeof arg === "string") {
arg = pathSyntax.fromPath(arg);
argType = "PathValues";
} else if (isPathValue(arg)) {
arg.path = pathSyntax.fromPath(arg.path);
argType = "PathValues";
} else if (isJSONGraphEnvelope(arg)) {
argType = "JSONGs";
} else if (isJSONEnvelope(arg)) {
argType = "PathMaps";
}
if (groupType !== argType) {
groupType = argType;
group = {
inputType: argType,
arguments: []
};
groups.push(group);
}
group.arguments.push(arg);
}
this._groups = groups;
} | javascript | function SetResponse(model, args, isJSONGraph,
isProgressive) {
// The response properties.
this._model = model;
this._isJSONGraph = isJSONGraph || false;
this._isProgressive = isProgressive || false;
this._initialArgs = args;
this._value = [{}];
var groups = [];
var group, groupType;
var argIndex = -1;
var argCount = args.length;
// Validation of arguments have been moved out of this function.
while (++argIndex < argCount) {
var arg = args[argIndex];
var argType;
if (isArray(arg) || typeof arg === "string") {
arg = pathSyntax.fromPath(arg);
argType = "PathValues";
} else if (isPathValue(arg)) {
arg.path = pathSyntax.fromPath(arg.path);
argType = "PathValues";
} else if (isJSONGraphEnvelope(arg)) {
argType = "JSONGs";
} else if (isJSONEnvelope(arg)) {
argType = "PathMaps";
}
if (groupType !== argType) {
groupType = argType;
group = {
inputType: argType,
arguments: []
};
groups.push(group);
}
group.arguments.push(arg);
}
this._groups = groups;
} | [
"function",
"SetResponse",
"(",
"model",
",",
"args",
",",
"isJSONGraph",
",",
"isProgressive",
")",
"{",
"// The response properties.",
"this",
".",
"_model",
"=",
"model",
";",
"this",
".",
"_isJSONGraph",
"=",
"isJSONGraph",
"||",
"false",
";",
"this",
".",
"_isProgressive",
"=",
"isProgressive",
"||",
"false",
";",
"this",
".",
"_initialArgs",
"=",
"args",
";",
"this",
".",
"_value",
"=",
"[",
"{",
"}",
"]",
";",
"var",
"groups",
"=",
"[",
"]",
";",
"var",
"group",
",",
"groupType",
";",
"var",
"argIndex",
"=",
"-",
"1",
";",
"var",
"argCount",
"=",
"args",
".",
"length",
";",
"// Validation of arguments have been moved out of this function.",
"while",
"(",
"++",
"argIndex",
"<",
"argCount",
")",
"{",
"var",
"arg",
"=",
"args",
"[",
"argIndex",
"]",
";",
"var",
"argType",
";",
"if",
"(",
"isArray",
"(",
"arg",
")",
"||",
"typeof",
"arg",
"===",
"\"string\"",
")",
"{",
"arg",
"=",
"pathSyntax",
".",
"fromPath",
"(",
"arg",
")",
";",
"argType",
"=",
"\"PathValues\"",
";",
"}",
"else",
"if",
"(",
"isPathValue",
"(",
"arg",
")",
")",
"{",
"arg",
".",
"path",
"=",
"pathSyntax",
".",
"fromPath",
"(",
"arg",
".",
"path",
")",
";",
"argType",
"=",
"\"PathValues\"",
";",
"}",
"else",
"if",
"(",
"isJSONGraphEnvelope",
"(",
"arg",
")",
")",
"{",
"argType",
"=",
"\"JSONGs\"",
";",
"}",
"else",
"if",
"(",
"isJSONEnvelope",
"(",
"arg",
")",
")",
"{",
"argType",
"=",
"\"PathMaps\"",
";",
"}",
"if",
"(",
"groupType",
"!==",
"argType",
")",
"{",
"groupType",
"=",
"argType",
";",
"group",
"=",
"{",
"inputType",
":",
"argType",
",",
"arguments",
":",
"[",
"]",
"}",
";",
"groups",
".",
"push",
"(",
"group",
")",
";",
"}",
"group",
".",
"arguments",
".",
"push",
"(",
"arg",
")",
";",
"}",
"this",
".",
"_groups",
"=",
"groups",
";",
"}"
] | The set response is responsible for doing the request loop for the set
operation and subscribing to the follow up get.
The constructors job is to parse out the arguments and put them in their
groups. The following subscribe will do the actual cache set and dataSource
operation remoting.
@param {Model} model -
@param {Array} args - The array of arguments that can be JSONGraph, JSON, or
pathValues.
@param {Boolean} isJSONGraph - if the request is a jsonGraph output format.
@param {Boolean} isProgressive - progressive output.
@augments ModelResponse
@private | [
"The",
"set",
"response",
"is",
"responsible",
"for",
"doing",
"the",
"request",
"loop",
"for",
"the",
"set",
"operation",
"and",
"subscribing",
"to",
"the",
"follow",
"up",
"get",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/response/set/SetResponse.js#L25-L69 |
5,959 | Netflix/falcor | lib/errors/BoundJSONGraphModelError.js | BoundJSONGraphModelError | function BoundJSONGraphModelError() {
var instance = new Error("It is not legal to use the JSON Graph " +
"format from a bound Model. JSON Graph format" +
" can only be used from a root model.");
instance.name = "BoundJSONGraphModelError";
if (Object.setPrototypeOf) {
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
}
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, BoundJSONGraphModelError);
}
return instance;
} | javascript | function BoundJSONGraphModelError() {
var instance = new Error("It is not legal to use the JSON Graph " +
"format from a bound Model. JSON Graph format" +
" can only be used from a root model.");
instance.name = "BoundJSONGraphModelError";
if (Object.setPrototypeOf) {
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
}
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, BoundJSONGraphModelError);
}
return instance;
} | [
"function",
"BoundJSONGraphModelError",
"(",
")",
"{",
"var",
"instance",
"=",
"new",
"Error",
"(",
"\"It is not legal to use the JSON Graph \"",
"+",
"\"format from a bound Model. JSON Graph format\"",
"+",
"\" can only be used from a root model.\"",
")",
";",
"instance",
".",
"name",
"=",
"\"BoundJSONGraphModelError\"",
";",
"if",
"(",
"Object",
".",
"setPrototypeOf",
")",
"{",
"Object",
".",
"setPrototypeOf",
"(",
"instance",
",",
"Object",
".",
"getPrototypeOf",
"(",
"this",
")",
")",
";",
"}",
"if",
"(",
"Error",
".",
"captureStackTrace",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"instance",
",",
"BoundJSONGraphModelError",
")",
";",
"}",
"return",
"instance",
";",
"}"
] | When a bound model attempts to retrieve JSONGraph it should throw an
error.
@private | [
"When",
"a",
"bound",
"model",
"attempts",
"to",
"retrieve",
"JSONGraph",
"it",
"should",
"throw",
"an",
"error",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/errors/BoundJSONGraphModelError.js#L9-L25 |
5,960 | Netflix/falcor | lib/errors/InvalidModelError.js | InvalidModelError | function InvalidModelError(boundPath, shortedPath) {
var instance = new Error("The boundPath of the model is not valid since a value or error was found before the path end.");
instance.name = "InvalidModelError";
instance.boundPath = boundPath;
instance.shortedPath = shortedPath;
if (Object.setPrototypeOf) {
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
}
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, InvalidModelError);
}
return instance;
} | javascript | function InvalidModelError(boundPath, shortedPath) {
var instance = new Error("The boundPath of the model is not valid since a value or error was found before the path end.");
instance.name = "InvalidModelError";
instance.boundPath = boundPath;
instance.shortedPath = shortedPath;
if (Object.setPrototypeOf) {
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
}
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, InvalidModelError);
}
return instance;
} | [
"function",
"InvalidModelError",
"(",
"boundPath",
",",
"shortedPath",
")",
"{",
"var",
"instance",
"=",
"new",
"Error",
"(",
"\"The boundPath of the model is not valid since a value or error was found before the path end.\"",
")",
";",
"instance",
".",
"name",
"=",
"\"InvalidModelError\"",
";",
"instance",
".",
"boundPath",
"=",
"boundPath",
";",
"instance",
".",
"shortedPath",
"=",
"shortedPath",
";",
"if",
"(",
"Object",
".",
"setPrototypeOf",
")",
"{",
"Object",
".",
"setPrototypeOf",
"(",
"instance",
",",
"Object",
".",
"getPrototypeOf",
"(",
"this",
")",
")",
";",
"}",
"if",
"(",
"Error",
".",
"captureStackTrace",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"instance",
",",
"InvalidModelError",
")",
";",
"}",
"return",
"instance",
";",
"}"
] | An InvalidModelError can only happen when a user binds, whether sync
or async to shorted value. See the unit tests for examples.
@param {*} boundPath
@param {*} shortedPath
@private | [
"An",
"InvalidModelError",
"can",
"only",
"happen",
"when",
"a",
"user",
"binds",
"whether",
"sync",
"or",
"async",
"to",
"shorted",
"value",
".",
"See",
"the",
"unit",
"tests",
"for",
"examples",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/errors/InvalidModelError.js#L12-L28 |
5,961 | Netflix/falcor | examples/datasource/webWorkerSource.js | function(action) {
var self = this;
// The subscribe function runs when the Observable is observed.
return Rx.Observable.create(function subscribe(observer) {
var id = self.id++,
handler = function(e) {
var response = e.data,
error,
value;
// The response is an array like this [id, error, data]
if (response[0] === id) {
error = response[1];
if (error) {
observer.onError(error);
} else {
value = response[2];
observer.onNext(value);
observer.onCompleted();
}
}
};
// Add the identifier to the front of the message
action.unshift(id);
self._worker.postMessage(action);
self._worker.addEventListener('message', handler);
// This is the action to perform if the consumer unsubscribes from the observable
return function() {
self._worker.removeEventListener('message', handler);
};
});
} | javascript | function(action) {
var self = this;
// The subscribe function runs when the Observable is observed.
return Rx.Observable.create(function subscribe(observer) {
var id = self.id++,
handler = function(e) {
var response = e.data,
error,
value;
// The response is an array like this [id, error, data]
if (response[0] === id) {
error = response[1];
if (error) {
observer.onError(error);
} else {
value = response[2];
observer.onNext(value);
observer.onCompleted();
}
}
};
// Add the identifier to the front of the message
action.unshift(id);
self._worker.postMessage(action);
self._worker.addEventListener('message', handler);
// This is the action to perform if the consumer unsubscribes from the observable
return function() {
self._worker.removeEventListener('message', handler);
};
});
} | [
"function",
"(",
"action",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// The subscribe function runs when the Observable is observed.",
"return",
"Rx",
".",
"Observable",
".",
"create",
"(",
"function",
"subscribe",
"(",
"observer",
")",
"{",
"var",
"id",
"=",
"self",
".",
"id",
"++",
",",
"handler",
"=",
"function",
"(",
"e",
")",
"{",
"var",
"response",
"=",
"e",
".",
"data",
",",
"error",
",",
"value",
";",
"// The response is an array like this [id, error, data]",
"if",
"(",
"response",
"[",
"0",
"]",
"===",
"id",
")",
"{",
"error",
"=",
"response",
"[",
"1",
"]",
";",
"if",
"(",
"error",
")",
"{",
"observer",
".",
"onError",
"(",
"error",
")",
";",
"}",
"else",
"{",
"value",
"=",
"response",
"[",
"2",
"]",
";",
"observer",
".",
"onNext",
"(",
"value",
")",
";",
"observer",
".",
"onCompleted",
"(",
")",
";",
"}",
"}",
"}",
";",
"// Add the identifier to the front of the message",
"action",
".",
"unshift",
"(",
"id",
")",
";",
"self",
".",
"_worker",
".",
"postMessage",
"(",
"action",
")",
";",
"self",
".",
"_worker",
".",
"addEventListener",
"(",
"'message'",
",",
"handler",
")",
";",
"// This is the action to perform if the consumer unsubscribes from the observable",
"return",
"function",
"(",
")",
"{",
"self",
".",
"_worker",
".",
"removeEventListener",
"(",
"'message'",
",",
"handler",
")",
";",
"}",
";",
"}",
")",
";",
"}"
] | Creates an observable stream that will send a request to a Model server, and retrieve the response. The request and response are correlated using a unique identifier which the client sends with the request and the server echoes back along with the response. | [
"Creates",
"an",
"observable",
"stream",
"that",
"will",
"send",
"a",
"request",
"to",
"a",
"Model",
"server",
"and",
"retrieve",
"the",
"response",
".",
"The",
"request",
"and",
"response",
"are",
"correlated",
"using",
"a",
"unique",
"identifier",
"which",
"the",
"client",
"sends",
"with",
"the",
"request",
"and",
"the",
"server",
"echoes",
"back",
"along",
"with",
"the",
"response",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/examples/datasource/webWorkerSource.js#L110-L146 |
|
5,962 | Netflix/falcor | lib/Model.js | Model | function Model(o) {
var options = o || {};
this._root = options._root || new ModelRoot(options);
this._path = options.path || options._path || [];
this._scheduler = options.scheduler || options._scheduler || new ImmediateScheduler();
this._source = options.source || options._source;
this._request = options.request || options._request || new RequestQueue(this, this._scheduler);
this._ID = ID++;
if (typeof options.maxSize === "number") {
this._maxSize = options.maxSize;
} else {
this._maxSize = options._maxSize || Model.prototype._maxSize;
}
if (typeof options.maxRetries === "number") {
this._maxRetries = options.maxRetries;
} else {
this._maxRetries = options._maxRetries || Model.prototype._maxRetries;
}
if (typeof options.collectRatio === "number") {
this._collectRatio = options.collectRatio;
} else {
this._collectRatio = options._collectRatio || Model.prototype._collectRatio;
}
if (options.boxed || options.hasOwnProperty("_boxed")) {
this._boxed = options.boxed || options._boxed;
}
if (options.materialized || options.hasOwnProperty("_materialized")) {
this._materialized = options.materialized || options._materialized;
}
if (typeof options.treatErrorsAsValues === "boolean") {
this._treatErrorsAsValues = options.treatErrorsAsValues;
} else if (options.hasOwnProperty("_treatErrorsAsValues")) {
this._treatErrorsAsValues = options._treatErrorsAsValues;
}
this._useServerPaths = options._useServerPaths || false;
this._allowFromWhenceYouCame = options.allowFromWhenceYouCame ||
options._allowFromWhenceYouCame || false;
this._treatDataSourceErrorsAsJSONGraphErrors = options._treatDataSourceErrorsAsJSONGraphErrors || false;
if (options.cache) {
this.setCache(options.cache);
}
} | javascript | function Model(o) {
var options = o || {};
this._root = options._root || new ModelRoot(options);
this._path = options.path || options._path || [];
this._scheduler = options.scheduler || options._scheduler || new ImmediateScheduler();
this._source = options.source || options._source;
this._request = options.request || options._request || new RequestQueue(this, this._scheduler);
this._ID = ID++;
if (typeof options.maxSize === "number") {
this._maxSize = options.maxSize;
} else {
this._maxSize = options._maxSize || Model.prototype._maxSize;
}
if (typeof options.maxRetries === "number") {
this._maxRetries = options.maxRetries;
} else {
this._maxRetries = options._maxRetries || Model.prototype._maxRetries;
}
if (typeof options.collectRatio === "number") {
this._collectRatio = options.collectRatio;
} else {
this._collectRatio = options._collectRatio || Model.prototype._collectRatio;
}
if (options.boxed || options.hasOwnProperty("_boxed")) {
this._boxed = options.boxed || options._boxed;
}
if (options.materialized || options.hasOwnProperty("_materialized")) {
this._materialized = options.materialized || options._materialized;
}
if (typeof options.treatErrorsAsValues === "boolean") {
this._treatErrorsAsValues = options.treatErrorsAsValues;
} else if (options.hasOwnProperty("_treatErrorsAsValues")) {
this._treatErrorsAsValues = options._treatErrorsAsValues;
}
this._useServerPaths = options._useServerPaths || false;
this._allowFromWhenceYouCame = options.allowFromWhenceYouCame ||
options._allowFromWhenceYouCame || false;
this._treatDataSourceErrorsAsJSONGraphErrors = options._treatDataSourceErrorsAsJSONGraphErrors || false;
if (options.cache) {
this.setCache(options.cache);
}
} | [
"function",
"Model",
"(",
"o",
")",
"{",
"var",
"options",
"=",
"o",
"||",
"{",
"}",
";",
"this",
".",
"_root",
"=",
"options",
".",
"_root",
"||",
"new",
"ModelRoot",
"(",
"options",
")",
";",
"this",
".",
"_path",
"=",
"options",
".",
"path",
"||",
"options",
".",
"_path",
"||",
"[",
"]",
";",
"this",
".",
"_scheduler",
"=",
"options",
".",
"scheduler",
"||",
"options",
".",
"_scheduler",
"||",
"new",
"ImmediateScheduler",
"(",
")",
";",
"this",
".",
"_source",
"=",
"options",
".",
"source",
"||",
"options",
".",
"_source",
";",
"this",
".",
"_request",
"=",
"options",
".",
"request",
"||",
"options",
".",
"_request",
"||",
"new",
"RequestQueue",
"(",
"this",
",",
"this",
".",
"_scheduler",
")",
";",
"this",
".",
"_ID",
"=",
"ID",
"++",
";",
"if",
"(",
"typeof",
"options",
".",
"maxSize",
"===",
"\"number\"",
")",
"{",
"this",
".",
"_maxSize",
"=",
"options",
".",
"maxSize",
";",
"}",
"else",
"{",
"this",
".",
"_maxSize",
"=",
"options",
".",
"_maxSize",
"||",
"Model",
".",
"prototype",
".",
"_maxSize",
";",
"}",
"if",
"(",
"typeof",
"options",
".",
"maxRetries",
"===",
"\"number\"",
")",
"{",
"this",
".",
"_maxRetries",
"=",
"options",
".",
"maxRetries",
";",
"}",
"else",
"{",
"this",
".",
"_maxRetries",
"=",
"options",
".",
"_maxRetries",
"||",
"Model",
".",
"prototype",
".",
"_maxRetries",
";",
"}",
"if",
"(",
"typeof",
"options",
".",
"collectRatio",
"===",
"\"number\"",
")",
"{",
"this",
".",
"_collectRatio",
"=",
"options",
".",
"collectRatio",
";",
"}",
"else",
"{",
"this",
".",
"_collectRatio",
"=",
"options",
".",
"_collectRatio",
"||",
"Model",
".",
"prototype",
".",
"_collectRatio",
";",
"}",
"if",
"(",
"options",
".",
"boxed",
"||",
"options",
".",
"hasOwnProperty",
"(",
"\"_boxed\"",
")",
")",
"{",
"this",
".",
"_boxed",
"=",
"options",
".",
"boxed",
"||",
"options",
".",
"_boxed",
";",
"}",
"if",
"(",
"options",
".",
"materialized",
"||",
"options",
".",
"hasOwnProperty",
"(",
"\"_materialized\"",
")",
")",
"{",
"this",
".",
"_materialized",
"=",
"options",
".",
"materialized",
"||",
"options",
".",
"_materialized",
";",
"}",
"if",
"(",
"typeof",
"options",
".",
"treatErrorsAsValues",
"===",
"\"boolean\"",
")",
"{",
"this",
".",
"_treatErrorsAsValues",
"=",
"options",
".",
"treatErrorsAsValues",
";",
"}",
"else",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"\"_treatErrorsAsValues\"",
")",
")",
"{",
"this",
".",
"_treatErrorsAsValues",
"=",
"options",
".",
"_treatErrorsAsValues",
";",
"}",
"this",
".",
"_useServerPaths",
"=",
"options",
".",
"_useServerPaths",
"||",
"false",
";",
"this",
".",
"_allowFromWhenceYouCame",
"=",
"options",
".",
"allowFromWhenceYouCame",
"||",
"options",
".",
"_allowFromWhenceYouCame",
"||",
"false",
";",
"this",
".",
"_treatDataSourceErrorsAsJSONGraphErrors",
"=",
"options",
".",
"_treatDataSourceErrorsAsJSONGraphErrors",
"||",
"false",
";",
"if",
"(",
"options",
".",
"cache",
")",
"{",
"this",
".",
"setCache",
"(",
"options",
".",
"cache",
")",
";",
"}",
"}"
] | This function is invoked every time a value in the Model cache is about to be replaced with a new value. If the function returns true, the existing value is replaced with a new value and the version flag on all of the value's ancestors in the tree are incremented.
@callback Model~comparator
@param {Object} existingValue - the current value in the Model cache.
@param {Object} newValue - the value about to be set into the Model cache.
@returns {Boolean} the Boolean value indicating whether the new value and the existing value are equal.
A Model object is used to execute commands against a {@link JSONGraph} object. {@link Model}s can work with a local JSONGraph cache, or it can work with a remote {@link JSONGraph} object through a {@link DataSource}.
@constructor
@param {?Object} options - a set of options to customize behavior
@param {?DataSource} options.source - a data source to retrieve and manage the {@link JSONGraph}
@param {?JSONGraph} options.cache - initial state of the {@link JSONGraph}
@param {?number} options.maxSize - the maximum size of the cache. This value roughly correlates to item count (where itemCount = maxSize / 50). Each item by default is given a metadata `$size` of 50 (or its length when it's an array or string). You can get better control of falcor's memory usage by tweaking `$size`
@param {?number} options.maxRetries - the maximum number of times that the Model will attempt to retrieve the value from the server.
@param {?number} options.collectRatio - the ratio of the maximum size to collect when the maxSize is exceeded
@param {?Model~errorSelector} options.errorSelector - a function used to translate errors before they are returned
@param {?Model~onChange} options.onChange - a function called whenever the Model's cache is changed
@param {?Model~comparator} options.comparator - a function called whenever a value in the Model's cache is about to be replaced with a new value. | [
"This",
"function",
"is",
"invoked",
"every",
"time",
"a",
"value",
"in",
"the",
"Model",
"cache",
"is",
"about",
"to",
"be",
"replaced",
"with",
"a",
"new",
"value",
".",
"If",
"the",
"function",
"returns",
"true",
"the",
"existing",
"value",
"is",
"replaced",
"with",
"a",
"new",
"value",
"and",
"the",
"version",
"flag",
"on",
"all",
"of",
"the",
"value",
"s",
"ancestors",
"in",
"the",
"tree",
"are",
"incremented",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/Model.js#L74-L126 |
5,963 | Netflix/falcor | performance/models/legacy/macro/_Falcor.js | allUnique | function allUnique(arr) {
var hash = {},
index,
len;
for (index = 0, len = arr.length; index < len; index++) {
if (hash[arr[index]]) {
return false;
}
hash[arr[index]] = true;
}
return true;
} | javascript | function allUnique(arr) {
var hash = {},
index,
len;
for (index = 0, len = arr.length; index < len; index++) {
if (hash[arr[index]]) {
return false;
}
hash[arr[index]] = true;
}
return true;
} | [
"function",
"allUnique",
"(",
"arr",
")",
"{",
"var",
"hash",
"=",
"{",
"}",
",",
"index",
",",
"len",
";",
"for",
"(",
"index",
"=",
"0",
",",
"len",
"=",
"arr",
".",
"length",
";",
"index",
"<",
"len",
";",
"index",
"++",
")",
"{",
"if",
"(",
"hash",
"[",
"arr",
"[",
"index",
"]",
"]",
")",
"{",
"return",
"false",
";",
"}",
"hash",
"[",
"arr",
"[",
"index",
"]",
"]",
"=",
"true",
";",
"}",
"return",
"true",
";",
"}"
] | allUnique
return true if every number in an array is unique | [
"allUnique",
"return",
"true",
"if",
"every",
"number",
"in",
"an",
"array",
"is",
"unique"
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/performance/models/legacy/macro/_Falcor.js#L535-L547 |
5,964 | Netflix/falcor | lib/errors/MaxRetryExceededError.js | MaxRetryExceededError | function MaxRetryExceededError(missingOptimizedPaths) {
var instance = new Error("The allowed number of retries have been exceeded.");
instance.name = "MaxRetryExceededError";
instance.missingOptimizedPaths = missingOptimizedPaths || [];
if (Object.setPrototypeOf) {
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
}
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, MaxRetryExceededError);
}
return instance;
} | javascript | function MaxRetryExceededError(missingOptimizedPaths) {
var instance = new Error("The allowed number of retries have been exceeded.");
instance.name = "MaxRetryExceededError";
instance.missingOptimizedPaths = missingOptimizedPaths || [];
if (Object.setPrototypeOf) {
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
}
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, MaxRetryExceededError);
}
return instance;
} | [
"function",
"MaxRetryExceededError",
"(",
"missingOptimizedPaths",
")",
"{",
"var",
"instance",
"=",
"new",
"Error",
"(",
"\"The allowed number of retries have been exceeded.\"",
")",
";",
"instance",
".",
"name",
"=",
"\"MaxRetryExceededError\"",
";",
"instance",
".",
"missingOptimizedPaths",
"=",
"missingOptimizedPaths",
"||",
"[",
"]",
";",
"if",
"(",
"Object",
".",
"setPrototypeOf",
")",
"{",
"Object",
".",
"setPrototypeOf",
"(",
"instance",
",",
"Object",
".",
"getPrototypeOf",
"(",
"this",
")",
")",
";",
"}",
"if",
"(",
"Error",
".",
"captureStackTrace",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"instance",
",",
"MaxRetryExceededError",
")",
";",
"}",
"return",
"instance",
";",
"}"
] | A request can only be retried up to a specified limit. Once that
limit is exceeded, then an error will be thrown.
@param {*} missingOptimizedPaths
@private | [
"A",
"request",
"can",
"only",
"be",
"retried",
"up",
"to",
"a",
"specified",
"limit",
".",
"Once",
"that",
"limit",
"is",
"exceeded",
"then",
"an",
"error",
"will",
"be",
"thrown",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/errors/MaxRetryExceededError.js#L11-L26 |
5,965 | Netflix/falcor | lib/errors/NullInPathError.js | NullInPathError | function NullInPathError() {
var instance = new Error("`null` and `undefined` are not allowed in branch key positions");
instance.name = "NullInPathError";
if (Object.setPrototypeOf) {
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
}
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, NullInPathError);
}
return instance;
} | javascript | function NullInPathError() {
var instance = new Error("`null` and `undefined` are not allowed in branch key positions");
instance.name = "NullInPathError";
if (Object.setPrototypeOf) {
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
}
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, NullInPathError);
}
return instance;
} | [
"function",
"NullInPathError",
"(",
")",
"{",
"var",
"instance",
"=",
"new",
"Error",
"(",
"\"`null` and `undefined` are not allowed in branch key positions\"",
")",
";",
"instance",
".",
"name",
"=",
"\"NullInPathError\"",
";",
"if",
"(",
"Object",
".",
"setPrototypeOf",
")",
"{",
"Object",
".",
"setPrototypeOf",
"(",
"instance",
",",
"Object",
".",
"getPrototypeOf",
"(",
"this",
")",
")",
";",
"}",
"if",
"(",
"Error",
".",
"captureStackTrace",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"instance",
",",
"NullInPathError",
")",
";",
"}",
"return",
"instance",
";",
"}"
] | Does not allow null in path
@private | [
"Does",
"not",
"allow",
"null",
"in",
"path"
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/errors/NullInPathError.js#L8-L22 |
5,966 | Netflix/falcor | lib/response/get/GetResponse.js | GetResponse | function GetResponse(model, paths, isJSONGraph,
isProgressive, forceCollect) {
this.model = model;
this.currentRemainingPaths = paths;
this.isJSONGraph = isJSONGraph || false;
this.isProgressive = isProgressive || false;
this.forceCollect = forceCollect || false;
} | javascript | function GetResponse(model, paths, isJSONGraph,
isProgressive, forceCollect) {
this.model = model;
this.currentRemainingPaths = paths;
this.isJSONGraph = isJSONGraph || false;
this.isProgressive = isProgressive || false;
this.forceCollect = forceCollect || false;
} | [
"function",
"GetResponse",
"(",
"model",
",",
"paths",
",",
"isJSONGraph",
",",
"isProgressive",
",",
"forceCollect",
")",
"{",
"this",
".",
"model",
"=",
"model",
";",
"this",
".",
"currentRemainingPaths",
"=",
"paths",
";",
"this",
".",
"isJSONGraph",
"=",
"isJSONGraph",
"||",
"false",
";",
"this",
".",
"isProgressive",
"=",
"isProgressive",
"||",
"false",
";",
"this",
".",
"forceCollect",
"=",
"forceCollect",
"||",
"false",
";",
"}"
] | The get response. It takes in a model and paths and starts
the request cycle. It has been optimized for cache first requests
and closures.
@param {Model} model -
@param {Array} paths -
@augments ModelResponse
@private | [
"The",
"get",
"response",
".",
"It",
"takes",
"in",
"a",
"model",
"and",
"paths",
"and",
"starts",
"the",
"request",
"cycle",
".",
"It",
"has",
"been",
"optimized",
"for",
"cache",
"first",
"requests",
"and",
"closures",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/lib/response/get/GetResponse.js#L17-L24 |
5,967 | Netflix/falcor | build/falcor-jsdoc-template/publish.js | linkToWithTarget | function linkToWithTarget(doc, linkText) {
var linkTag = linkto(doc.longname, linkText || doc.name);
return linkTag.slice(0, linkTag.indexOf('>')) + ' data-target="#' +
escapeDocId(doc.id) + '"' + linkTag.slice(linkTag.indexOf('>'));
} | javascript | function linkToWithTarget(doc, linkText) {
var linkTag = linkto(doc.longname, linkText || doc.name);
return linkTag.slice(0, linkTag.indexOf('>')) + ' data-target="#' +
escapeDocId(doc.id) + '"' + linkTag.slice(linkTag.indexOf('>'));
} | [
"function",
"linkToWithTarget",
"(",
"doc",
",",
"linkText",
")",
"{",
"var",
"linkTag",
"=",
"linkto",
"(",
"doc",
".",
"longname",
",",
"linkText",
"||",
"doc",
".",
"name",
")",
";",
"return",
"linkTag",
".",
"slice",
"(",
"0",
",",
"linkTag",
".",
"indexOf",
"(",
"'>'",
")",
")",
"+",
"' data-target=\"#'",
"+",
"escapeDocId",
"(",
"doc",
".",
"id",
")",
"+",
"'\"'",
"+",
"linkTag",
".",
"slice",
"(",
"linkTag",
".",
"indexOf",
"(",
"'>'",
")",
")",
";",
"}"
] | Returns a link just like linkto, but with an id to its target header on the page added so bootstrap scrollspy can pick it up use it to work. Also sanitizes the input because jsdoc uses all sorts of weird characters in their ids. Optionally, link text can be passed in to use instead of the doc's name inside the link. | [
"Returns",
"a",
"link",
"just",
"like",
"linkto",
"but",
"with",
"an",
"id",
"to",
"its",
"target",
"header",
"on",
"the",
"page",
"added",
"so",
"bootstrap",
"scrollspy",
"can",
"pick",
"it",
"up",
"use",
"it",
"to",
"work",
".",
"Also",
"sanitizes",
"the",
"input",
"because",
"jsdoc",
"uses",
"all",
"sorts",
"of",
"weird",
"characters",
"in",
"their",
"ids",
".",
"Optionally",
"link",
"text",
"can",
"be",
"passed",
"in",
"to",
"use",
"instead",
"of",
"the",
"doc",
"s",
"name",
"inside",
"the",
"link",
"."
] | c0cea8518b44b999493da9ccb9c71fc3b2fb313d | https://github.com/Netflix/falcor/blob/c0cea8518b44b999493da9ccb9c71fc3b2fb313d/build/falcor-jsdoc-template/publish.js#L333-L337 |
5,968 | janl/mustache.js | mustache.js | primitiveHasOwnProperty | function primitiveHasOwnProperty (primitive, propName) {
return (
primitive != null
&& typeof primitive !== 'object'
&& primitive.hasOwnProperty
&& primitive.hasOwnProperty(propName)
);
} | javascript | function primitiveHasOwnProperty (primitive, propName) {
return (
primitive != null
&& typeof primitive !== 'object'
&& primitive.hasOwnProperty
&& primitive.hasOwnProperty(propName)
);
} | [
"function",
"primitiveHasOwnProperty",
"(",
"primitive",
",",
"propName",
")",
"{",
"return",
"(",
"primitive",
"!=",
"null",
"&&",
"typeof",
"primitive",
"!==",
"'object'",
"&&",
"primitive",
".",
"hasOwnProperty",
"&&",
"primitive",
".",
"hasOwnProperty",
"(",
"propName",
")",
")",
";",
"}"
] | Safe way of detecting whether or not the given thing is a primitive and
whether it has the given property | [
"Safe",
"way",
"of",
"detecting",
"whether",
"or",
"not",
"the",
"given",
"thing",
"is",
"a",
"primitive",
"and",
"whether",
"it",
"has",
"the",
"given",
"property"
] | 38b1448e65f1d4716c3e3ad792ae6ab3aaf487ab | https://github.com/janl/mustache.js/blob/38b1448e65f1d4716c3e3ad792ae6ab3aaf487ab/mustache.js#L52-L59 |
5,969 | oliver-moran/jimp | packages/core/src/index.js | bufferFromArrayBuffer | function bufferFromArrayBuffer(arrayBuffer) {
const buffer = Buffer.alloc(arrayBuffer.byteLength);
const view = new Uint8Array(arrayBuffer);
for (let i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
return buffer;
} | javascript | function bufferFromArrayBuffer(arrayBuffer) {
const buffer = Buffer.alloc(arrayBuffer.byteLength);
const view = new Uint8Array(arrayBuffer);
for (let i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
return buffer;
} | [
"function",
"bufferFromArrayBuffer",
"(",
"arrayBuffer",
")",
"{",
"const",
"buffer",
"=",
"Buffer",
".",
"alloc",
"(",
"arrayBuffer",
".",
"byteLength",
")",
";",
"const",
"view",
"=",
"new",
"Uint8Array",
"(",
"arrayBuffer",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"buffer",
".",
"length",
";",
"++",
"i",
")",
"{",
"buffer",
"[",
"i",
"]",
"=",
"view",
"[",
"i",
"]",
";",
"}",
"return",
"buffer",
";",
"}"
] | Prepare a Buffer object from the arrayBuffer. Necessary in the browser > node conversion, But this function is not useful when running in node directly | [
"Prepare",
"a",
"Buffer",
"object",
"from",
"the",
"arrayBuffer",
".",
"Necessary",
"in",
"the",
"browser",
">",
"node",
"conversion",
"But",
"this",
"function",
"is",
"not",
"useful",
"when",
"running",
"in",
"node",
"directly"
] | 736054ef1bea6b6fb03db3e75f05cd922a9c104f | https://github.com/oliver-moran/jimp/blob/736054ef1bea6b6fb03db3e75f05cd922a9c104f/packages/core/src/index.js#L50-L59 |
5,970 | oliver-moran/jimp | packages/jimp/tools/browser-build.js | minify | function minify(code) {
console.error('Compressing...');
return UglifyJS.minify(code, { warnings: false }).code;
} | javascript | function minify(code) {
console.error('Compressing...');
return UglifyJS.minify(code, { warnings: false }).code;
} | [
"function",
"minify",
"(",
"code",
")",
"{",
"console",
".",
"error",
"(",
"'Compressing...'",
")",
";",
"return",
"UglifyJS",
".",
"minify",
"(",
"code",
",",
"{",
"warnings",
":",
"false",
"}",
")",
".",
"code",
";",
"}"
] | Browserify and Babelize. | [
"Browserify",
"and",
"Babelize",
"."
] | 736054ef1bea6b6fb03db3e75f05cd922a9c104f | https://github.com/oliver-moran/jimp/blob/736054ef1bea6b6fb03db3e75f05cd922a9c104f/packages/jimp/tools/browser-build.js#L34-L38 |
5,971 | oliver-moran/jimp | packages/plugin-dither/src/index.js | dither | function dither(cb) {
const rgb565Matrix = [1, 9, 3, 11, 13, 5, 15, 7, 4, 12, 2, 10, 16, 8, 14, 6];
this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
x,
y,
idx
) {
const thresholdId = ((y & 3) << 2) + (x % 4);
const dither = rgb565Matrix[thresholdId];
this.bitmap.data[idx] = Math.min(this.bitmap.data[idx] + dither, 0xff);
this.bitmap.data[idx + 1] = Math.min(
this.bitmap.data[idx + 1] + dither,
0xff
);
this.bitmap.data[idx + 2] = Math.min(
this.bitmap.data[idx + 2] + dither,
0xff
);
});
if (isNodePattern(cb)) {
cb.call(this, null, this);
}
return this;
} | javascript | function dither(cb) {
const rgb565Matrix = [1, 9, 3, 11, 13, 5, 15, 7, 4, 12, 2, 10, 16, 8, 14, 6];
this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
x,
y,
idx
) {
const thresholdId = ((y & 3) << 2) + (x % 4);
const dither = rgb565Matrix[thresholdId];
this.bitmap.data[idx] = Math.min(this.bitmap.data[idx] + dither, 0xff);
this.bitmap.data[idx + 1] = Math.min(
this.bitmap.data[idx + 1] + dither,
0xff
);
this.bitmap.data[idx + 2] = Math.min(
this.bitmap.data[idx + 2] + dither,
0xff
);
});
if (isNodePattern(cb)) {
cb.call(this, null, this);
}
return this;
} | [
"function",
"dither",
"(",
"cb",
")",
"{",
"const",
"rgb565Matrix",
"=",
"[",
"1",
",",
"9",
",",
"3",
",",
"11",
",",
"13",
",",
"5",
",",
"15",
",",
"7",
",",
"4",
",",
"12",
",",
"2",
",",
"10",
",",
"16",
",",
"8",
",",
"14",
",",
"6",
"]",
";",
"this",
".",
"scanQuiet",
"(",
"0",
",",
"0",
",",
"this",
".",
"bitmap",
".",
"width",
",",
"this",
".",
"bitmap",
".",
"height",
",",
"function",
"(",
"x",
",",
"y",
",",
"idx",
")",
"{",
"const",
"thresholdId",
"=",
"(",
"(",
"y",
"&",
"3",
")",
"<<",
"2",
")",
"+",
"(",
"x",
"%",
"4",
")",
";",
"const",
"dither",
"=",
"rgb565Matrix",
"[",
"thresholdId",
"]",
";",
"this",
".",
"bitmap",
".",
"data",
"[",
"idx",
"]",
"=",
"Math",
".",
"min",
"(",
"this",
".",
"bitmap",
".",
"data",
"[",
"idx",
"]",
"+",
"dither",
",",
"0xff",
")",
";",
"this",
".",
"bitmap",
".",
"data",
"[",
"idx",
"+",
"1",
"]",
"=",
"Math",
".",
"min",
"(",
"this",
".",
"bitmap",
".",
"data",
"[",
"idx",
"+",
"1",
"]",
"+",
"dither",
",",
"0xff",
")",
";",
"this",
".",
"bitmap",
".",
"data",
"[",
"idx",
"+",
"2",
"]",
"=",
"Math",
".",
"min",
"(",
"this",
".",
"bitmap",
".",
"data",
"[",
"idx",
"+",
"2",
"]",
"+",
"dither",
",",
"0xff",
")",
";",
"}",
")",
";",
"if",
"(",
"isNodePattern",
"(",
"cb",
")",
")",
"{",
"cb",
".",
"call",
"(",
"this",
",",
"null",
",",
"this",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Apply a ordered dithering effect
@param {function(Error, Jimp)} cb (optional) a callback for when complete
@returns {Jimp} this for chaining of methods | [
"Apply",
"a",
"ordered",
"dithering",
"effect"
] | 736054ef1bea6b6fb03db3e75f05cd922a9c104f | https://github.com/oliver-moran/jimp/blob/736054ef1bea6b6fb03db3e75f05cd922a9c104f/packages/plugin-dither/src/index.js#L8-L33 |
5,972 | oliver-moran/jimp | packages/plugin-flip/src/index.js | flipFn | function flipFn(horizontal, vertical, cb) {
if (typeof horizontal !== 'boolean' || typeof vertical !== 'boolean')
return throwError.call(
this,
'horizontal and vertical must be Booleans',
cb
);
if (horizontal && vertical) {
// shortcut
return this.rotate(180, true, cb);
}
const bitmap = Buffer.alloc(this.bitmap.data.length);
this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
x,
y,
idx
) {
const _x = horizontal ? this.bitmap.width - 1 - x : x;
const _y = vertical ? this.bitmap.height - 1 - y : y;
const _idx = (this.bitmap.width * _y + _x) << 2;
const data = this.bitmap.data.readUInt32BE(idx);
bitmap.writeUInt32BE(data, _idx);
});
this.bitmap.data = Buffer.from(bitmap);
if (isNodePattern(cb)) {
cb.call(this, null, this);
}
return this;
} | javascript | function flipFn(horizontal, vertical, cb) {
if (typeof horizontal !== 'boolean' || typeof vertical !== 'boolean')
return throwError.call(
this,
'horizontal and vertical must be Booleans',
cb
);
if (horizontal && vertical) {
// shortcut
return this.rotate(180, true, cb);
}
const bitmap = Buffer.alloc(this.bitmap.data.length);
this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
x,
y,
idx
) {
const _x = horizontal ? this.bitmap.width - 1 - x : x;
const _y = vertical ? this.bitmap.height - 1 - y : y;
const _idx = (this.bitmap.width * _y + _x) << 2;
const data = this.bitmap.data.readUInt32BE(idx);
bitmap.writeUInt32BE(data, _idx);
});
this.bitmap.data = Buffer.from(bitmap);
if (isNodePattern(cb)) {
cb.call(this, null, this);
}
return this;
} | [
"function",
"flipFn",
"(",
"horizontal",
",",
"vertical",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"horizontal",
"!==",
"'boolean'",
"||",
"typeof",
"vertical",
"!==",
"'boolean'",
")",
"return",
"throwError",
".",
"call",
"(",
"this",
",",
"'horizontal and vertical must be Booleans'",
",",
"cb",
")",
";",
"if",
"(",
"horizontal",
"&&",
"vertical",
")",
"{",
"// shortcut",
"return",
"this",
".",
"rotate",
"(",
"180",
",",
"true",
",",
"cb",
")",
";",
"}",
"const",
"bitmap",
"=",
"Buffer",
".",
"alloc",
"(",
"this",
".",
"bitmap",
".",
"data",
".",
"length",
")",
";",
"this",
".",
"scanQuiet",
"(",
"0",
",",
"0",
",",
"this",
".",
"bitmap",
".",
"width",
",",
"this",
".",
"bitmap",
".",
"height",
",",
"function",
"(",
"x",
",",
"y",
",",
"idx",
")",
"{",
"const",
"_x",
"=",
"horizontal",
"?",
"this",
".",
"bitmap",
".",
"width",
"-",
"1",
"-",
"x",
":",
"x",
";",
"const",
"_y",
"=",
"vertical",
"?",
"this",
".",
"bitmap",
".",
"height",
"-",
"1",
"-",
"y",
":",
"y",
";",
"const",
"_idx",
"=",
"(",
"this",
".",
"bitmap",
".",
"width",
"*",
"_y",
"+",
"_x",
")",
"<<",
"2",
";",
"const",
"data",
"=",
"this",
".",
"bitmap",
".",
"data",
".",
"readUInt32BE",
"(",
"idx",
")",
";",
"bitmap",
".",
"writeUInt32BE",
"(",
"data",
",",
"_idx",
")",
";",
"}",
")",
";",
"this",
".",
"bitmap",
".",
"data",
"=",
"Buffer",
".",
"from",
"(",
"bitmap",
")",
";",
"if",
"(",
"isNodePattern",
"(",
"cb",
")",
")",
"{",
"cb",
".",
"call",
"(",
"this",
",",
"null",
",",
"this",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Flip the image horizontally
@param {boolean} horizontal a Boolean, if true the image will be flipped horizontally
@param {boolean} vertical a Boolean, if true the image will be flipped vertically
@param {function(Error, Jimp)} cb (optional) a callback for when complete
@returns {Jimp} this for chaining of methods | [
"Flip",
"the",
"image",
"horizontally"
] | 736054ef1bea6b6fb03db3e75f05cd922a9c104f | https://github.com/oliver-moran/jimp/blob/736054ef1bea6b6fb03db3e75f05cd922a9c104f/packages/plugin-flip/src/index.js#L10-L44 |
5,973 | oliver-moran/jimp | packages/plugin-normalize/src/index.js | histogram | function histogram() {
const histogram = {
r: new Array(256).fill(0),
g: new Array(256).fill(0),
b: new Array(256).fill(0)
};
this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
x,
y,
index
) {
histogram.r[this.bitmap.data[index + 0]]++;
histogram.g[this.bitmap.data[index + 1]]++;
histogram.b[this.bitmap.data[index + 2]]++;
});
return histogram;
} | javascript | function histogram() {
const histogram = {
r: new Array(256).fill(0),
g: new Array(256).fill(0),
b: new Array(256).fill(0)
};
this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function(
x,
y,
index
) {
histogram.r[this.bitmap.data[index + 0]]++;
histogram.g[this.bitmap.data[index + 1]]++;
histogram.b[this.bitmap.data[index + 2]]++;
});
return histogram;
} | [
"function",
"histogram",
"(",
")",
"{",
"const",
"histogram",
"=",
"{",
"r",
":",
"new",
"Array",
"(",
"256",
")",
".",
"fill",
"(",
"0",
")",
",",
"g",
":",
"new",
"Array",
"(",
"256",
")",
".",
"fill",
"(",
"0",
")",
",",
"b",
":",
"new",
"Array",
"(",
"256",
")",
".",
"fill",
"(",
"0",
")",
"}",
";",
"this",
".",
"scanQuiet",
"(",
"0",
",",
"0",
",",
"this",
".",
"bitmap",
".",
"width",
",",
"this",
".",
"bitmap",
".",
"height",
",",
"function",
"(",
"x",
",",
"y",
",",
"index",
")",
"{",
"histogram",
".",
"r",
"[",
"this",
".",
"bitmap",
".",
"data",
"[",
"index",
"+",
"0",
"]",
"]",
"++",
";",
"histogram",
".",
"g",
"[",
"this",
".",
"bitmap",
".",
"data",
"[",
"index",
"+",
"1",
"]",
"]",
"++",
";",
"histogram",
".",
"b",
"[",
"this",
".",
"bitmap",
".",
"data",
"[",
"index",
"+",
"2",
"]",
"]",
"++",
";",
"}",
")",
";",
"return",
"histogram",
";",
"}"
] | Get an image's histogram
@return {object} An object with an array of color occurrence counts for each channel (r,g,b) | [
"Get",
"an",
"image",
"s",
"histogram"
] | 736054ef1bea6b6fb03db3e75f05cd922a9c104f | https://github.com/oliver-moran/jimp/blob/736054ef1bea6b6fb03db3e75f05cd922a9c104f/packages/plugin-normalize/src/index.js#L9-L27 |
5,974 | Alex-D/Trumbowyg | plugins/mention/trumbowyg.mention.js | buildDropdown | function buildDropdown(items, trumbowyg) {
var dropdown = [];
$.each(items, function (i, item) {
var btn = 'mention-' + i,
btnDef = {
hasIcon: false,
text: trumbowyg.o.plugins.mention.formatDropdownItem(item),
fn: function () {
trumbowyg.execCmd('insertHTML', trumbowyg.o.plugins.mention.formatResult(item));
return true;
}
};
trumbowyg.addBtnDef(btn, btnDef);
dropdown.push(btn);
});
return dropdown;
} | javascript | function buildDropdown(items, trumbowyg) {
var dropdown = [];
$.each(items, function (i, item) {
var btn = 'mention-' + i,
btnDef = {
hasIcon: false,
text: trumbowyg.o.plugins.mention.formatDropdownItem(item),
fn: function () {
trumbowyg.execCmd('insertHTML', trumbowyg.o.plugins.mention.formatResult(item));
return true;
}
};
trumbowyg.addBtnDef(btn, btnDef);
dropdown.push(btn);
});
return dropdown;
} | [
"function",
"buildDropdown",
"(",
"items",
",",
"trumbowyg",
")",
"{",
"var",
"dropdown",
"=",
"[",
"]",
";",
"$",
".",
"each",
"(",
"items",
",",
"function",
"(",
"i",
",",
"item",
")",
"{",
"var",
"btn",
"=",
"'mention-'",
"+",
"i",
",",
"btnDef",
"=",
"{",
"hasIcon",
":",
"false",
",",
"text",
":",
"trumbowyg",
".",
"o",
".",
"plugins",
".",
"mention",
".",
"formatDropdownItem",
"(",
"item",
")",
",",
"fn",
":",
"function",
"(",
")",
"{",
"trumbowyg",
".",
"execCmd",
"(",
"'insertHTML'",
",",
"trumbowyg",
".",
"o",
".",
"plugins",
".",
"mention",
".",
"formatResult",
"(",
"item",
")",
")",
";",
"return",
"true",
";",
"}",
"}",
";",
"trumbowyg",
".",
"addBtnDef",
"(",
"btn",
",",
"btnDef",
")",
";",
"dropdown",
".",
"push",
"(",
"btn",
")",
";",
"}",
")",
";",
"return",
"dropdown",
";",
"}"
] | Build dropdown list
@param {Array} items Items
@param {object} trumbowyg Editor
@return {Array} | [
"Build",
"dropdown",
"list"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/plugins/mention/trumbowyg.mention.js#L70-L90 |
5,975 | Alex-D/Trumbowyg | plugins/template/trumbowyg.template.js | templateSelector | function templateSelector(trumbowyg) {
var available = trumbowyg.o.plugins.templates;
var templates = [];
$.each(available, function (index, template) {
trumbowyg.addBtnDef('template_' + index, {
fn: function () {
trumbowyg.html(template.html);
},
hasIcon: false,
title: template.name
});
templates.push('template_' + index);
});
return templates;
} | javascript | function templateSelector(trumbowyg) {
var available = trumbowyg.o.plugins.templates;
var templates = [];
$.each(available, function (index, template) {
trumbowyg.addBtnDef('template_' + index, {
fn: function () {
trumbowyg.html(template.html);
},
hasIcon: false,
title: template.name
});
templates.push('template_' + index);
});
return templates;
} | [
"function",
"templateSelector",
"(",
"trumbowyg",
")",
"{",
"var",
"available",
"=",
"trumbowyg",
".",
"o",
".",
"plugins",
".",
"templates",
";",
"var",
"templates",
"=",
"[",
"]",
";",
"$",
".",
"each",
"(",
"available",
",",
"function",
"(",
"index",
",",
"template",
")",
"{",
"trumbowyg",
".",
"addBtnDef",
"(",
"'template_'",
"+",
"index",
",",
"{",
"fn",
":",
"function",
"(",
")",
"{",
"trumbowyg",
".",
"html",
"(",
"template",
".",
"html",
")",
";",
"}",
",",
"hasIcon",
":",
"false",
",",
"title",
":",
"template",
".",
"name",
"}",
")",
";",
"templates",
".",
"push",
"(",
"'template_'",
"+",
"index",
")",
";",
"}",
")",
";",
"return",
"templates",
";",
"}"
] | Creates the template-selector dropdown. | [
"Creates",
"the",
"template",
"-",
"selector",
"dropdown",
"."
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/plugins/template/trumbowyg.template.js#L56-L72 |
5,976 | Alex-D/Trumbowyg | plugins/lineheight/trumbowyg.lineheight.js | buildDropdown | function buildDropdown(trumbowyg) {
var dropdown = [];
$.each(trumbowyg.o.plugins.lineheight.sizeList, function(index, size) {
trumbowyg.addBtnDef('lineheight_' + size, {
text: trumbowyg.lang.lineheights[size] || size,
hasIcon: false,
fn: function(){
trumbowyg.saveRange();
var text = trumbowyg.getRangeText();
if (text.replace(/\s/g, '') !== '') {
try {
var parent = getSelectionParentElement();
$(parent).css('lineHeight', size);
} catch (e) {
}
}
}
});
dropdown.push('lineheight_' + size);
});
return dropdown;
} | javascript | function buildDropdown(trumbowyg) {
var dropdown = [];
$.each(trumbowyg.o.plugins.lineheight.sizeList, function(index, size) {
trumbowyg.addBtnDef('lineheight_' + size, {
text: trumbowyg.lang.lineheights[size] || size,
hasIcon: false,
fn: function(){
trumbowyg.saveRange();
var text = trumbowyg.getRangeText();
if (text.replace(/\s/g, '') !== '') {
try {
var parent = getSelectionParentElement();
$(parent).css('lineHeight', size);
} catch (e) {
}
}
}
});
dropdown.push('lineheight_' + size);
});
return dropdown;
} | [
"function",
"buildDropdown",
"(",
"trumbowyg",
")",
"{",
"var",
"dropdown",
"=",
"[",
"]",
";",
"$",
".",
"each",
"(",
"trumbowyg",
".",
"o",
".",
"plugins",
".",
"lineheight",
".",
"sizeList",
",",
"function",
"(",
"index",
",",
"size",
")",
"{",
"trumbowyg",
".",
"addBtnDef",
"(",
"'lineheight_'",
"+",
"size",
",",
"{",
"text",
":",
"trumbowyg",
".",
"lang",
".",
"lineheights",
"[",
"size",
"]",
"||",
"size",
",",
"hasIcon",
":",
"false",
",",
"fn",
":",
"function",
"(",
")",
"{",
"trumbowyg",
".",
"saveRange",
"(",
")",
";",
"var",
"text",
"=",
"trumbowyg",
".",
"getRangeText",
"(",
")",
";",
"if",
"(",
"text",
".",
"replace",
"(",
"/",
"\\s",
"/",
"g",
",",
"''",
")",
"!==",
"''",
")",
"{",
"try",
"{",
"var",
"parent",
"=",
"getSelectionParentElement",
"(",
")",
";",
"$",
"(",
"parent",
")",
".",
"css",
"(",
"'lineHeight'",
",",
"size",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}",
"}",
"}",
")",
";",
"dropdown",
".",
"push",
"(",
"'lineheight_'",
"+",
"size",
")",
";",
"}",
")",
";",
"return",
"dropdown",
";",
"}"
] | Build the dropdown | [
"Build",
"the",
"dropdown"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/plugins/lineheight/trumbowyg.lineheight.js#L111-L134 |
5,977 | Alex-D/Trumbowyg | src/trumbowyg.js | function () {
var t = this;
t.$ed.removeClass('autogrow-on-enter');
var oldHeight = t.$ed[0].clientHeight;
t.$ed.height('auto');
var totalHeight = t.$ed[0].scrollHeight;
t.$ed.addClass('autogrow-on-enter');
if (oldHeight !== totalHeight) {
t.$ed.height(oldHeight);
setTimeout(function () {
t.$ed.css({height: totalHeight});
t.$c.trigger('tbwresize');
}, 0);
}
} | javascript | function () {
var t = this;
t.$ed.removeClass('autogrow-on-enter');
var oldHeight = t.$ed[0].clientHeight;
t.$ed.height('auto');
var totalHeight = t.$ed[0].scrollHeight;
t.$ed.addClass('autogrow-on-enter');
if (oldHeight !== totalHeight) {
t.$ed.height(oldHeight);
setTimeout(function () {
t.$ed.css({height: totalHeight});
t.$c.trigger('tbwresize');
}, 0);
}
} | [
"function",
"(",
")",
"{",
"var",
"t",
"=",
"this",
";",
"t",
".",
"$ed",
".",
"removeClass",
"(",
"'autogrow-on-enter'",
")",
";",
"var",
"oldHeight",
"=",
"t",
".",
"$ed",
"[",
"0",
"]",
".",
"clientHeight",
";",
"t",
".",
"$ed",
".",
"height",
"(",
"'auto'",
")",
";",
"var",
"totalHeight",
"=",
"t",
".",
"$ed",
"[",
"0",
"]",
".",
"scrollHeight",
";",
"t",
".",
"$ed",
".",
"addClass",
"(",
"'autogrow-on-enter'",
")",
";",
"if",
"(",
"oldHeight",
"!==",
"totalHeight",
")",
"{",
"t",
".",
"$ed",
".",
"height",
"(",
"oldHeight",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"t",
".",
"$ed",
".",
"css",
"(",
"{",
"height",
":",
"totalHeight",
"}",
")",
";",
"t",
".",
"$c",
".",
"trigger",
"(",
"'tbwresize'",
")",
";",
"}",
",",
"0",
")",
";",
"}",
"}"
] | autogrow when entering logic | [
"autogrow",
"when",
"entering",
"logic"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L725-L739 |
|
5,978 | Alex-D/Trumbowyg | src/trumbowyg.js | function () {
var t = this,
prefix = t.o.prefix;
var $btnPane = t.$btnPane = $('<div/>', {
class: prefix + 'button-pane'
});
$.each(t.o.btns, function (i, btnGrp) {
if (!$.isArray(btnGrp)) {
btnGrp = [btnGrp];
}
var $btnGroup = $('<div/>', {
class: prefix + 'button-group ' + ((btnGrp.indexOf('fullscreen') >= 0) ? prefix + 'right' : '')
});
$.each(btnGrp, function (i, btn) {
try { // Prevent buildBtn error
if (t.isSupportedBtn(btn)) { // It's a supported button
$btnGroup.append(t.buildBtn(btn));
}
} catch (c) {
}
});
if ($btnGroup.html().trim().length > 0) {
$btnPane.append($btnGroup);
}
});
t.$box.prepend($btnPane);
} | javascript | function () {
var t = this,
prefix = t.o.prefix;
var $btnPane = t.$btnPane = $('<div/>', {
class: prefix + 'button-pane'
});
$.each(t.o.btns, function (i, btnGrp) {
if (!$.isArray(btnGrp)) {
btnGrp = [btnGrp];
}
var $btnGroup = $('<div/>', {
class: prefix + 'button-group ' + ((btnGrp.indexOf('fullscreen') >= 0) ? prefix + 'right' : '')
});
$.each(btnGrp, function (i, btn) {
try { // Prevent buildBtn error
if (t.isSupportedBtn(btn)) { // It's a supported button
$btnGroup.append(t.buildBtn(btn));
}
} catch (c) {
}
});
if ($btnGroup.html().trim().length > 0) {
$btnPane.append($btnGroup);
}
});
t.$box.prepend($btnPane);
} | [
"function",
"(",
")",
"{",
"var",
"t",
"=",
"this",
",",
"prefix",
"=",
"t",
".",
"o",
".",
"prefix",
";",
"var",
"$btnPane",
"=",
"t",
".",
"$btnPane",
"=",
"$",
"(",
"'<div/>'",
",",
"{",
"class",
":",
"prefix",
"+",
"'button-pane'",
"}",
")",
";",
"$",
".",
"each",
"(",
"t",
".",
"o",
".",
"btns",
",",
"function",
"(",
"i",
",",
"btnGrp",
")",
"{",
"if",
"(",
"!",
"$",
".",
"isArray",
"(",
"btnGrp",
")",
")",
"{",
"btnGrp",
"=",
"[",
"btnGrp",
"]",
";",
"}",
"var",
"$btnGroup",
"=",
"$",
"(",
"'<div/>'",
",",
"{",
"class",
":",
"prefix",
"+",
"'button-group '",
"+",
"(",
"(",
"btnGrp",
".",
"indexOf",
"(",
"'fullscreen'",
")",
">=",
"0",
")",
"?",
"prefix",
"+",
"'right'",
":",
"''",
")",
"}",
")",
";",
"$",
".",
"each",
"(",
"btnGrp",
",",
"function",
"(",
"i",
",",
"btn",
")",
"{",
"try",
"{",
"// Prevent buildBtn error",
"if",
"(",
"t",
".",
"isSupportedBtn",
"(",
"btn",
")",
")",
"{",
"// It's a supported button",
"$btnGroup",
".",
"append",
"(",
"t",
".",
"buildBtn",
"(",
"btn",
")",
")",
";",
"}",
"}",
"catch",
"(",
"c",
")",
"{",
"}",
"}",
")",
";",
"if",
"(",
"$btnGroup",
".",
"html",
"(",
")",
".",
"trim",
"(",
")",
".",
"length",
">",
"0",
")",
"{",
"$btnPane",
".",
"append",
"(",
"$btnGroup",
")",
";",
"}",
"}",
")",
";",
"t",
".",
"$box",
".",
"prepend",
"(",
"$btnPane",
")",
";",
"}"
] | Build button pane, use o.btns option | [
"Build",
"button",
"pane",
"use",
"o",
".",
"btns",
"option"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L743-L774 |
|
5,979 | Alex-D/Trumbowyg | src/trumbowyg.js | function (btnName) {
var t = this,
prefix = t.o.prefix,
btn = t.btnsDef[btnName],
hasIcon = btn.hasIcon != null ? btn.hasIcon : true;
if (btn.key) {
t.keys[btn.key] = {
fn: btn.fn || btnName,
param: btn.param || btnName
};
}
t.tagToButton[(btn.tag || btnName).toLowerCase()] = btnName;
return $('<button/>', {
type: 'button',
class: prefix + btnName + '-dropdown-button ' + (btn.class || '') + (btn.ico ? ' ' + prefix + btn.ico + '-button' : ''),
html: t.hasSvg && hasIcon ?
'<svg><use xlink:href="' + t.svgPath + '#' + prefix + (btn.ico || btnName).replace(/([A-Z]+)/g, '-$1').toLowerCase() + '"/></svg>' + (btn.text || btn.title || t.lang[btnName] || btnName) :
(btn.text || btn.title || t.lang[btnName] || btnName),
title: (btn.key ? '(' + (t.isMac ? 'Cmd' : 'Ctrl') + ' + ' + btn.key + ')' : null),
style: btn.style || null,
mousedown: function () {
$('body', t.doc).trigger('mousedown');
t.execCmd(btn.fn || btnName, btn.param || btnName, btn.forceCss);
return false;
}
});
} | javascript | function (btnName) {
var t = this,
prefix = t.o.prefix,
btn = t.btnsDef[btnName],
hasIcon = btn.hasIcon != null ? btn.hasIcon : true;
if (btn.key) {
t.keys[btn.key] = {
fn: btn.fn || btnName,
param: btn.param || btnName
};
}
t.tagToButton[(btn.tag || btnName).toLowerCase()] = btnName;
return $('<button/>', {
type: 'button',
class: prefix + btnName + '-dropdown-button ' + (btn.class || '') + (btn.ico ? ' ' + prefix + btn.ico + '-button' : ''),
html: t.hasSvg && hasIcon ?
'<svg><use xlink:href="' + t.svgPath + '#' + prefix + (btn.ico || btnName).replace(/([A-Z]+)/g, '-$1').toLowerCase() + '"/></svg>' + (btn.text || btn.title || t.lang[btnName] || btnName) :
(btn.text || btn.title || t.lang[btnName] || btnName),
title: (btn.key ? '(' + (t.isMac ? 'Cmd' : 'Ctrl') + ' + ' + btn.key + ')' : null),
style: btn.style || null,
mousedown: function () {
$('body', t.doc).trigger('mousedown');
t.execCmd(btn.fn || btnName, btn.param || btnName, btn.forceCss);
return false;
}
});
} | [
"function",
"(",
"btnName",
")",
"{",
"var",
"t",
"=",
"this",
",",
"prefix",
"=",
"t",
".",
"o",
".",
"prefix",
",",
"btn",
"=",
"t",
".",
"btnsDef",
"[",
"btnName",
"]",
",",
"hasIcon",
"=",
"btn",
".",
"hasIcon",
"!=",
"null",
"?",
"btn",
".",
"hasIcon",
":",
"true",
";",
"if",
"(",
"btn",
".",
"key",
")",
"{",
"t",
".",
"keys",
"[",
"btn",
".",
"key",
"]",
"=",
"{",
"fn",
":",
"btn",
".",
"fn",
"||",
"btnName",
",",
"param",
":",
"btn",
".",
"param",
"||",
"btnName",
"}",
";",
"}",
"t",
".",
"tagToButton",
"[",
"(",
"btn",
".",
"tag",
"||",
"btnName",
")",
".",
"toLowerCase",
"(",
")",
"]",
"=",
"btnName",
";",
"return",
"$",
"(",
"'<button/>'",
",",
"{",
"type",
":",
"'button'",
",",
"class",
":",
"prefix",
"+",
"btnName",
"+",
"'-dropdown-button '",
"+",
"(",
"btn",
".",
"class",
"||",
"''",
")",
"+",
"(",
"btn",
".",
"ico",
"?",
"' '",
"+",
"prefix",
"+",
"btn",
".",
"ico",
"+",
"'-button'",
":",
"''",
")",
",",
"html",
":",
"t",
".",
"hasSvg",
"&&",
"hasIcon",
"?",
"'<svg><use xlink:href=\"'",
"+",
"t",
".",
"svgPath",
"+",
"'#'",
"+",
"prefix",
"+",
"(",
"btn",
".",
"ico",
"||",
"btnName",
")",
".",
"replace",
"(",
"/",
"([A-Z]+)",
"/",
"g",
",",
"'-$1'",
")",
".",
"toLowerCase",
"(",
")",
"+",
"'\"/></svg>'",
"+",
"(",
"btn",
".",
"text",
"||",
"btn",
".",
"title",
"||",
"t",
".",
"lang",
"[",
"btnName",
"]",
"||",
"btnName",
")",
":",
"(",
"btn",
".",
"text",
"||",
"btn",
".",
"title",
"||",
"t",
".",
"lang",
"[",
"btnName",
"]",
"||",
"btnName",
")",
",",
"title",
":",
"(",
"btn",
".",
"key",
"?",
"'('",
"+",
"(",
"t",
".",
"isMac",
"?",
"'Cmd'",
":",
"'Ctrl'",
")",
"+",
"' + '",
"+",
"btn",
".",
"key",
"+",
"')'",
":",
"null",
")",
",",
"style",
":",
"btn",
".",
"style",
"||",
"null",
",",
"mousedown",
":",
"function",
"(",
")",
"{",
"$",
"(",
"'body'",
",",
"t",
".",
"doc",
")",
".",
"trigger",
"(",
"'mousedown'",
")",
";",
"t",
".",
"execCmd",
"(",
"btn",
".",
"fn",
"||",
"btnName",
",",
"btn",
".",
"param",
"||",
"btnName",
",",
"btn",
".",
"forceCss",
")",
";",
"return",
"false",
";",
"}",
"}",
")",
";",
"}"
] | Build a button for dropdown menu @param n : name of the subbutton | [
"Build",
"a",
"button",
"for",
"dropdown",
"menu"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L840-L871 |
|
5,980 | Alex-D/Trumbowyg | src/trumbowyg.js | function () {
var t = this,
fixedFullWidth = t.o.fixedFullWidth,
$box = t.$box;
if (!t.o.fixedBtnPane) {
return;
}
t.isFixed = false;
$(window)
.on('scroll.' + t.eventNamespace + ' resize.' + t.eventNamespace, function () {
if (!$box) {
return;
}
t.syncCode();
var scrollTop = $(window).scrollTop(),
offset = $box.offset().top + 1,
bp = t.$btnPane,
oh = bp.outerHeight() - 2;
if ((scrollTop - offset > 0) && ((scrollTop - offset - t.height) < 0)) {
if (!t.isFixed) {
t.isFixed = true;
bp.css({
position: 'fixed',
top: 0,
left: fixedFullWidth ? '0' : 'auto',
zIndex: 7
});
$([t.$ta, t.$ed]).css({marginTop: bp.height()});
}
bp.css({
width: fixedFullWidth ? '100%' : (($box.width() - 1) + 'px')
});
$('.' + t.o.prefix + 'fixed-top', $box).css({
position: fixedFullWidth ? 'fixed' : 'absolute',
top: fixedFullWidth ? oh : oh + (scrollTop - offset) + 'px',
zIndex: 15
});
} else if (t.isFixed) {
t.isFixed = false;
bp.removeAttr('style');
$([t.$ta, t.$ed]).css({marginTop: 0});
$('.' + t.o.prefix + 'fixed-top', $box).css({
position: 'absolute',
top: oh
});
}
});
} | javascript | function () {
var t = this,
fixedFullWidth = t.o.fixedFullWidth,
$box = t.$box;
if (!t.o.fixedBtnPane) {
return;
}
t.isFixed = false;
$(window)
.on('scroll.' + t.eventNamespace + ' resize.' + t.eventNamespace, function () {
if (!$box) {
return;
}
t.syncCode();
var scrollTop = $(window).scrollTop(),
offset = $box.offset().top + 1,
bp = t.$btnPane,
oh = bp.outerHeight() - 2;
if ((scrollTop - offset > 0) && ((scrollTop - offset - t.height) < 0)) {
if (!t.isFixed) {
t.isFixed = true;
bp.css({
position: 'fixed',
top: 0,
left: fixedFullWidth ? '0' : 'auto',
zIndex: 7
});
$([t.$ta, t.$ed]).css({marginTop: bp.height()});
}
bp.css({
width: fixedFullWidth ? '100%' : (($box.width() - 1) + 'px')
});
$('.' + t.o.prefix + 'fixed-top', $box).css({
position: fixedFullWidth ? 'fixed' : 'absolute',
top: fixedFullWidth ? oh : oh + (scrollTop - offset) + 'px',
zIndex: 15
});
} else if (t.isFixed) {
t.isFixed = false;
bp.removeAttr('style');
$([t.$ta, t.$ed]).css({marginTop: 0});
$('.' + t.o.prefix + 'fixed-top', $box).css({
position: 'absolute',
top: oh
});
}
});
} | [
"function",
"(",
")",
"{",
"var",
"t",
"=",
"this",
",",
"fixedFullWidth",
"=",
"t",
".",
"o",
".",
"fixedFullWidth",
",",
"$box",
"=",
"t",
".",
"$box",
";",
"if",
"(",
"!",
"t",
".",
"o",
".",
"fixedBtnPane",
")",
"{",
"return",
";",
"}",
"t",
".",
"isFixed",
"=",
"false",
";",
"$",
"(",
"window",
")",
".",
"on",
"(",
"'scroll.'",
"+",
"t",
".",
"eventNamespace",
"+",
"' resize.'",
"+",
"t",
".",
"eventNamespace",
",",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"$box",
")",
"{",
"return",
";",
"}",
"t",
".",
"syncCode",
"(",
")",
";",
"var",
"scrollTop",
"=",
"$",
"(",
"window",
")",
".",
"scrollTop",
"(",
")",
",",
"offset",
"=",
"$box",
".",
"offset",
"(",
")",
".",
"top",
"+",
"1",
",",
"bp",
"=",
"t",
".",
"$btnPane",
",",
"oh",
"=",
"bp",
".",
"outerHeight",
"(",
")",
"-",
"2",
";",
"if",
"(",
"(",
"scrollTop",
"-",
"offset",
">",
"0",
")",
"&&",
"(",
"(",
"scrollTop",
"-",
"offset",
"-",
"t",
".",
"height",
")",
"<",
"0",
")",
")",
"{",
"if",
"(",
"!",
"t",
".",
"isFixed",
")",
"{",
"t",
".",
"isFixed",
"=",
"true",
";",
"bp",
".",
"css",
"(",
"{",
"position",
":",
"'fixed'",
",",
"top",
":",
"0",
",",
"left",
":",
"fixedFullWidth",
"?",
"'0'",
":",
"'auto'",
",",
"zIndex",
":",
"7",
"}",
")",
";",
"$",
"(",
"[",
"t",
".",
"$ta",
",",
"t",
".",
"$ed",
"]",
")",
".",
"css",
"(",
"{",
"marginTop",
":",
"bp",
".",
"height",
"(",
")",
"}",
")",
";",
"}",
"bp",
".",
"css",
"(",
"{",
"width",
":",
"fixedFullWidth",
"?",
"'100%'",
":",
"(",
"(",
"$box",
".",
"width",
"(",
")",
"-",
"1",
")",
"+",
"'px'",
")",
"}",
")",
";",
"$",
"(",
"'.'",
"+",
"t",
".",
"o",
".",
"prefix",
"+",
"'fixed-top'",
",",
"$box",
")",
".",
"css",
"(",
"{",
"position",
":",
"fixedFullWidth",
"?",
"'fixed'",
":",
"'absolute'",
",",
"top",
":",
"fixedFullWidth",
"?",
"oh",
":",
"oh",
"+",
"(",
"scrollTop",
"-",
"offset",
")",
"+",
"'px'",
",",
"zIndex",
":",
"15",
"}",
")",
";",
"}",
"else",
"if",
"(",
"t",
".",
"isFixed",
")",
"{",
"t",
".",
"isFixed",
"=",
"false",
";",
"bp",
".",
"removeAttr",
"(",
"'style'",
")",
";",
"$",
"(",
"[",
"t",
".",
"$ta",
",",
"t",
".",
"$ed",
"]",
")",
".",
"css",
"(",
"{",
"marginTop",
":",
"0",
"}",
")",
";",
"$",
"(",
"'.'",
"+",
"t",
".",
"o",
".",
"prefix",
"+",
"'fixed-top'",
",",
"$box",
")",
".",
"css",
"(",
"{",
"position",
":",
"'absolute'",
",",
"top",
":",
"oh",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Management of fixed button pane | [
"Management",
"of",
"fixed",
"button",
"pane"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L902-L956 |
|
5,981 | Alex-D/Trumbowyg | src/trumbowyg.js | function () {
var t = this,
prefix = t.o.prefix;
if (t.isTextarea) {
t.$box.after(
t.$ta
.css({height: ''})
.val(t.html())
.removeClass(prefix + 'textarea')
.show()
);
} else {
t.$box.after(
t.$ed
.css({height: ''})
.removeClass(prefix + 'editor')
.removeAttr('contenteditable')
.removeAttr('dir')
.html(t.html())
.show()
);
}
t.$ed.off('dblclick', 'img');
t.destroyPlugins();
t.$box.remove();
t.$c.removeData('trumbowyg');
$('body').removeClass(prefix + 'body-fullscreen');
t.$c.trigger('tbwclose');
$(window).off('scroll.' + t.eventNamespace + ' resize.' + t.eventNamespace);
} | javascript | function () {
var t = this,
prefix = t.o.prefix;
if (t.isTextarea) {
t.$box.after(
t.$ta
.css({height: ''})
.val(t.html())
.removeClass(prefix + 'textarea')
.show()
);
} else {
t.$box.after(
t.$ed
.css({height: ''})
.removeClass(prefix + 'editor')
.removeAttr('contenteditable')
.removeAttr('dir')
.html(t.html())
.show()
);
}
t.$ed.off('dblclick', 'img');
t.destroyPlugins();
t.$box.remove();
t.$c.removeData('trumbowyg');
$('body').removeClass(prefix + 'body-fullscreen');
t.$c.trigger('tbwclose');
$(window).off('scroll.' + t.eventNamespace + ' resize.' + t.eventNamespace);
} | [
"function",
"(",
")",
"{",
"var",
"t",
"=",
"this",
",",
"prefix",
"=",
"t",
".",
"o",
".",
"prefix",
";",
"if",
"(",
"t",
".",
"isTextarea",
")",
"{",
"t",
".",
"$box",
".",
"after",
"(",
"t",
".",
"$ta",
".",
"css",
"(",
"{",
"height",
":",
"''",
"}",
")",
".",
"val",
"(",
"t",
".",
"html",
"(",
")",
")",
".",
"removeClass",
"(",
"prefix",
"+",
"'textarea'",
")",
".",
"show",
"(",
")",
")",
";",
"}",
"else",
"{",
"t",
".",
"$box",
".",
"after",
"(",
"t",
".",
"$ed",
".",
"css",
"(",
"{",
"height",
":",
"''",
"}",
")",
".",
"removeClass",
"(",
"prefix",
"+",
"'editor'",
")",
".",
"removeAttr",
"(",
"'contenteditable'",
")",
".",
"removeAttr",
"(",
"'dir'",
")",
".",
"html",
"(",
"t",
".",
"html",
"(",
")",
")",
".",
"show",
"(",
")",
")",
";",
"}",
"t",
".",
"$ed",
".",
"off",
"(",
"'dblclick'",
",",
"'img'",
")",
";",
"t",
".",
"destroyPlugins",
"(",
")",
";",
"t",
".",
"$box",
".",
"remove",
"(",
")",
";",
"t",
".",
"$c",
".",
"removeData",
"(",
"'trumbowyg'",
")",
";",
"$",
"(",
"'body'",
")",
".",
"removeClass",
"(",
"prefix",
"+",
"'body-fullscreen'",
")",
";",
"t",
".",
"$c",
".",
"trigger",
"(",
"'tbwclose'",
")",
";",
"$",
"(",
"window",
")",
".",
"off",
"(",
"'scroll.'",
"+",
"t",
".",
"eventNamespace",
"+",
"' resize.'",
"+",
"t",
".",
"eventNamespace",
")",
";",
"}"
] | Destroy the editor | [
"Destroy",
"the",
"editor"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L975-L1008 |
|
5,982 | Alex-D/Trumbowyg | src/trumbowyg.js | function () {
var t = this,
prefix = t.o.prefix;
if (t.o.autogrowOnEnter) {
t.autogrowOnEnterDontClose = !t.$box.hasClass(prefix + 'editor-hidden');
}
t.semanticCode(false, true);
setTimeout(function () {
t.doc.activeElement.blur();
t.$box.toggleClass(prefix + 'editor-hidden ' + prefix + 'editor-visible');
t.$btnPane.toggleClass(prefix + 'disable');
$('.' + prefix + 'viewHTML-button', t.$btnPane).toggleClass(prefix + 'active');
if (t.$box.hasClass(prefix + 'editor-visible')) {
t.$ta.attr('tabindex', -1);
} else {
t.$ta.removeAttr('tabindex');
}
if (t.o.autogrowOnEnter && !t.autogrowOnEnterDontClose) {
t.autogrowEditorOnEnter();
}
}, 0);
} | javascript | function () {
var t = this,
prefix = t.o.prefix;
if (t.o.autogrowOnEnter) {
t.autogrowOnEnterDontClose = !t.$box.hasClass(prefix + 'editor-hidden');
}
t.semanticCode(false, true);
setTimeout(function () {
t.doc.activeElement.blur();
t.$box.toggleClass(prefix + 'editor-hidden ' + prefix + 'editor-visible');
t.$btnPane.toggleClass(prefix + 'disable');
$('.' + prefix + 'viewHTML-button', t.$btnPane).toggleClass(prefix + 'active');
if (t.$box.hasClass(prefix + 'editor-visible')) {
t.$ta.attr('tabindex', -1);
} else {
t.$ta.removeAttr('tabindex');
}
if (t.o.autogrowOnEnter && !t.autogrowOnEnterDontClose) {
t.autogrowEditorOnEnter();
}
}, 0);
} | [
"function",
"(",
")",
"{",
"var",
"t",
"=",
"this",
",",
"prefix",
"=",
"t",
".",
"o",
".",
"prefix",
";",
"if",
"(",
"t",
".",
"o",
".",
"autogrowOnEnter",
")",
"{",
"t",
".",
"autogrowOnEnterDontClose",
"=",
"!",
"t",
".",
"$box",
".",
"hasClass",
"(",
"prefix",
"+",
"'editor-hidden'",
")",
";",
"}",
"t",
".",
"semanticCode",
"(",
"false",
",",
"true",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"t",
".",
"doc",
".",
"activeElement",
".",
"blur",
"(",
")",
";",
"t",
".",
"$box",
".",
"toggleClass",
"(",
"prefix",
"+",
"'editor-hidden '",
"+",
"prefix",
"+",
"'editor-visible'",
")",
";",
"t",
".",
"$btnPane",
".",
"toggleClass",
"(",
"prefix",
"+",
"'disable'",
")",
";",
"$",
"(",
"'.'",
"+",
"prefix",
"+",
"'viewHTML-button'",
",",
"t",
".",
"$btnPane",
")",
".",
"toggleClass",
"(",
"prefix",
"+",
"'active'",
")",
";",
"if",
"(",
"t",
".",
"$box",
".",
"hasClass",
"(",
"prefix",
"+",
"'editor-visible'",
")",
")",
"{",
"t",
".",
"$ta",
".",
"attr",
"(",
"'tabindex'",
",",
"-",
"1",
")",
";",
"}",
"else",
"{",
"t",
".",
"$ta",
".",
"removeAttr",
"(",
"'tabindex'",
")",
";",
"}",
"if",
"(",
"t",
".",
"o",
".",
"autogrowOnEnter",
"&&",
"!",
"t",
".",
"autogrowOnEnterDontClose",
")",
"{",
"t",
".",
"autogrowEditorOnEnter",
"(",
")",
";",
"}",
"}",
",",
"0",
")",
";",
"}"
] | Function call when click on viewHTML button | [
"Function",
"call",
"when",
"click",
"on",
"viewHTML",
"button"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L1019-L1044 |
|
5,983 | Alex-D/Trumbowyg | src/trumbowyg.js | function (name) {
var t = this,
d = t.doc,
prefix = t.o.prefix,
$dropdown = $('[data-' + prefix + 'dropdown=' + name + ']', t.$box),
$btn = $('.' + prefix + name + '-button', t.$btnPane),
show = $dropdown.is(':hidden');
$('body', d).trigger('mousedown');
if (show) {
var o = $btn.offset().left;
$btn.addClass(prefix + 'active');
$dropdown.css({
position: 'absolute',
top: $btn.offset().top - t.$btnPane.offset().top + $btn.outerHeight(),
left: (t.o.fixedFullWidth && t.isFixed) ? o + 'px' : (o - t.$btnPane.offset().left) + 'px'
}).show();
$(window).trigger('scroll');
$('body', d).on('mousedown.' + t.eventNamespace, function (e) {
if (!$dropdown.is(e.target)) {
$('.' + prefix + 'dropdown', t.$box).hide();
$('.' + prefix + 'active', t.$btnPane).removeClass(prefix + 'active');
$('body', d).off('mousedown.' + t.eventNamespace);
}
});
}
} | javascript | function (name) {
var t = this,
d = t.doc,
prefix = t.o.prefix,
$dropdown = $('[data-' + prefix + 'dropdown=' + name + ']', t.$box),
$btn = $('.' + prefix + name + '-button', t.$btnPane),
show = $dropdown.is(':hidden');
$('body', d).trigger('mousedown');
if (show) {
var o = $btn.offset().left;
$btn.addClass(prefix + 'active');
$dropdown.css({
position: 'absolute',
top: $btn.offset().top - t.$btnPane.offset().top + $btn.outerHeight(),
left: (t.o.fixedFullWidth && t.isFixed) ? o + 'px' : (o - t.$btnPane.offset().left) + 'px'
}).show();
$(window).trigger('scroll');
$('body', d).on('mousedown.' + t.eventNamespace, function (e) {
if (!$dropdown.is(e.target)) {
$('.' + prefix + 'dropdown', t.$box).hide();
$('.' + prefix + 'active', t.$btnPane).removeClass(prefix + 'active');
$('body', d).off('mousedown.' + t.eventNamespace);
}
});
}
} | [
"function",
"(",
"name",
")",
"{",
"var",
"t",
"=",
"this",
",",
"d",
"=",
"t",
".",
"doc",
",",
"prefix",
"=",
"t",
".",
"o",
".",
"prefix",
",",
"$dropdown",
"=",
"$",
"(",
"'[data-'",
"+",
"prefix",
"+",
"'dropdown='",
"+",
"name",
"+",
"']'",
",",
"t",
".",
"$box",
")",
",",
"$btn",
"=",
"$",
"(",
"'.'",
"+",
"prefix",
"+",
"name",
"+",
"'-button'",
",",
"t",
".",
"$btnPane",
")",
",",
"show",
"=",
"$dropdown",
".",
"is",
"(",
"':hidden'",
")",
";",
"$",
"(",
"'body'",
",",
"d",
")",
".",
"trigger",
"(",
"'mousedown'",
")",
";",
"if",
"(",
"show",
")",
"{",
"var",
"o",
"=",
"$btn",
".",
"offset",
"(",
")",
".",
"left",
";",
"$btn",
".",
"addClass",
"(",
"prefix",
"+",
"'active'",
")",
";",
"$dropdown",
".",
"css",
"(",
"{",
"position",
":",
"'absolute'",
",",
"top",
":",
"$btn",
".",
"offset",
"(",
")",
".",
"top",
"-",
"t",
".",
"$btnPane",
".",
"offset",
"(",
")",
".",
"top",
"+",
"$btn",
".",
"outerHeight",
"(",
")",
",",
"left",
":",
"(",
"t",
".",
"o",
".",
"fixedFullWidth",
"&&",
"t",
".",
"isFixed",
")",
"?",
"o",
"+",
"'px'",
":",
"(",
"o",
"-",
"t",
".",
"$btnPane",
".",
"offset",
"(",
")",
".",
"left",
")",
"+",
"'px'",
"}",
")",
".",
"show",
"(",
")",
";",
"$",
"(",
"window",
")",
".",
"trigger",
"(",
"'scroll'",
")",
";",
"$",
"(",
"'body'",
",",
"d",
")",
".",
"on",
"(",
"'mousedown.'",
"+",
"t",
".",
"eventNamespace",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"!",
"$dropdown",
".",
"is",
"(",
"e",
".",
"target",
")",
")",
"{",
"$",
"(",
"'.'",
"+",
"prefix",
"+",
"'dropdown'",
",",
"t",
".",
"$box",
")",
".",
"hide",
"(",
")",
";",
"$",
"(",
"'.'",
"+",
"prefix",
"+",
"'active'",
",",
"t",
".",
"$btnPane",
")",
".",
"removeClass",
"(",
"prefix",
"+",
"'active'",
")",
";",
"$",
"(",
"'body'",
",",
"d",
")",
".",
"off",
"(",
"'mousedown.'",
"+",
"t",
".",
"eventNamespace",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Open dropdown when click on a button which open that | [
"Open",
"dropdown",
"when",
"click",
"on",
"a",
"button",
"which",
"open",
"that"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L1047-L1077 |
|
5,984 | Alex-D/Trumbowyg | src/trumbowyg.js | function (html) {
var t = this;
if (html != null) {
t.$ta.val(html);
t.syncCode(true);
t.$c.trigger('tbwchange');
return t;
}
return t.$ta.val();
} | javascript | function (html) {
var t = this;
if (html != null) {
t.$ta.val(html);
t.syncCode(true);
t.$c.trigger('tbwchange');
return t;
}
return t.$ta.val();
} | [
"function",
"(",
"html",
")",
"{",
"var",
"t",
"=",
"this",
";",
"if",
"(",
"html",
"!=",
"null",
")",
"{",
"t",
".",
"$ta",
".",
"val",
"(",
"html",
")",
";",
"t",
".",
"syncCode",
"(",
"true",
")",
";",
"t",
".",
"$c",
".",
"trigger",
"(",
"'tbwchange'",
")",
";",
"return",
"t",
";",
"}",
"return",
"t",
".",
"$ta",
".",
"val",
"(",
")",
";",
"}"
] | HTML Code management | [
"HTML",
"Code",
"management"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L1081-L1092 |
|
5,985 | Alex-D/Trumbowyg | src/trumbowyg.js | function (force, full, keepRange) {
var t = this;
t.saveRange();
t.syncCode(force);
if (t.o.semantic) {
t.semanticTag('b', t.o.semanticKeepAttributes);
t.semanticTag('i', t.o.semanticKeepAttributes);
t.semanticTag('s', t.o.semanticKeepAttributes);
t.semanticTag('strike', t.o.semanticKeepAttributes);
if (full) {
var inlineElementsSelector = t.o.inlineElementsSelector,
blockElementsSelector = ':not(' + inlineElementsSelector + ')';
// Wrap text nodes in span for easier processing
t.$ed.contents().filter(function () {
return this.nodeType === 3 && this.nodeValue.trim().length > 0;
}).wrap('<span data-tbw/>');
// Wrap groups of inline elements in paragraphs (recursive)
var wrapInlinesInParagraphsFrom = function ($from) {
if ($from.length !== 0) {
var $finalParagraph = $from.nextUntil(blockElementsSelector).addBack().wrapAll('<p/>').parent(),
$nextElement = $finalParagraph.nextAll(inlineElementsSelector).first();
$finalParagraph.next('br').remove();
wrapInlinesInParagraphsFrom($nextElement);
}
};
wrapInlinesInParagraphsFrom(t.$ed.children(inlineElementsSelector).first());
t.semanticTag('div', true);
// Unwrap paragraphs content, containing nothing useful
t.$ed.find('p').filter(function () {
// Don't remove currently being edited element
if (t.range && this === t.range.startContainer) {
return false;
}
return $(this).text().trim().length === 0 && $(this).children().not('br,span').length === 0;
}).contents().unwrap();
// Get rid of temporary span's
$('[data-tbw]', t.$ed).contents().unwrap();
// Remove empty <p>
t.$ed.find('p:empty').remove();
}
if (!keepRange) {
t.restoreRange();
}
t.syncTextarea();
}
} | javascript | function (force, full, keepRange) {
var t = this;
t.saveRange();
t.syncCode(force);
if (t.o.semantic) {
t.semanticTag('b', t.o.semanticKeepAttributes);
t.semanticTag('i', t.o.semanticKeepAttributes);
t.semanticTag('s', t.o.semanticKeepAttributes);
t.semanticTag('strike', t.o.semanticKeepAttributes);
if (full) {
var inlineElementsSelector = t.o.inlineElementsSelector,
blockElementsSelector = ':not(' + inlineElementsSelector + ')';
// Wrap text nodes in span for easier processing
t.$ed.contents().filter(function () {
return this.nodeType === 3 && this.nodeValue.trim().length > 0;
}).wrap('<span data-tbw/>');
// Wrap groups of inline elements in paragraphs (recursive)
var wrapInlinesInParagraphsFrom = function ($from) {
if ($from.length !== 0) {
var $finalParagraph = $from.nextUntil(blockElementsSelector).addBack().wrapAll('<p/>').parent(),
$nextElement = $finalParagraph.nextAll(inlineElementsSelector).first();
$finalParagraph.next('br').remove();
wrapInlinesInParagraphsFrom($nextElement);
}
};
wrapInlinesInParagraphsFrom(t.$ed.children(inlineElementsSelector).first());
t.semanticTag('div', true);
// Unwrap paragraphs content, containing nothing useful
t.$ed.find('p').filter(function () {
// Don't remove currently being edited element
if (t.range && this === t.range.startContainer) {
return false;
}
return $(this).text().trim().length === 0 && $(this).children().not('br,span').length === 0;
}).contents().unwrap();
// Get rid of temporary span's
$('[data-tbw]', t.$ed).contents().unwrap();
// Remove empty <p>
t.$ed.find('p:empty').remove();
}
if (!keepRange) {
t.restoreRange();
}
t.syncTextarea();
}
} | [
"function",
"(",
"force",
",",
"full",
",",
"keepRange",
")",
"{",
"var",
"t",
"=",
"this",
";",
"t",
".",
"saveRange",
"(",
")",
";",
"t",
".",
"syncCode",
"(",
"force",
")",
";",
"if",
"(",
"t",
".",
"o",
".",
"semantic",
")",
"{",
"t",
".",
"semanticTag",
"(",
"'b'",
",",
"t",
".",
"o",
".",
"semanticKeepAttributes",
")",
";",
"t",
".",
"semanticTag",
"(",
"'i'",
",",
"t",
".",
"o",
".",
"semanticKeepAttributes",
")",
";",
"t",
".",
"semanticTag",
"(",
"'s'",
",",
"t",
".",
"o",
".",
"semanticKeepAttributes",
")",
";",
"t",
".",
"semanticTag",
"(",
"'strike'",
",",
"t",
".",
"o",
".",
"semanticKeepAttributes",
")",
";",
"if",
"(",
"full",
")",
"{",
"var",
"inlineElementsSelector",
"=",
"t",
".",
"o",
".",
"inlineElementsSelector",
",",
"blockElementsSelector",
"=",
"':not('",
"+",
"inlineElementsSelector",
"+",
"')'",
";",
"// Wrap text nodes in span for easier processing",
"t",
".",
"$ed",
".",
"contents",
"(",
")",
".",
"filter",
"(",
"function",
"(",
")",
"{",
"return",
"this",
".",
"nodeType",
"===",
"3",
"&&",
"this",
".",
"nodeValue",
".",
"trim",
"(",
")",
".",
"length",
">",
"0",
";",
"}",
")",
".",
"wrap",
"(",
"'<span data-tbw/>'",
")",
";",
"// Wrap groups of inline elements in paragraphs (recursive)",
"var",
"wrapInlinesInParagraphsFrom",
"=",
"function",
"(",
"$from",
")",
"{",
"if",
"(",
"$from",
".",
"length",
"!==",
"0",
")",
"{",
"var",
"$finalParagraph",
"=",
"$from",
".",
"nextUntil",
"(",
"blockElementsSelector",
")",
".",
"addBack",
"(",
")",
".",
"wrapAll",
"(",
"'<p/>'",
")",
".",
"parent",
"(",
")",
",",
"$nextElement",
"=",
"$finalParagraph",
".",
"nextAll",
"(",
"inlineElementsSelector",
")",
".",
"first",
"(",
")",
";",
"$finalParagraph",
".",
"next",
"(",
"'br'",
")",
".",
"remove",
"(",
")",
";",
"wrapInlinesInParagraphsFrom",
"(",
"$nextElement",
")",
";",
"}",
"}",
";",
"wrapInlinesInParagraphsFrom",
"(",
"t",
".",
"$ed",
".",
"children",
"(",
"inlineElementsSelector",
")",
".",
"first",
"(",
")",
")",
";",
"t",
".",
"semanticTag",
"(",
"'div'",
",",
"true",
")",
";",
"// Unwrap paragraphs content, containing nothing useful",
"t",
".",
"$ed",
".",
"find",
"(",
"'p'",
")",
".",
"filter",
"(",
"function",
"(",
")",
"{",
"// Don't remove currently being edited element",
"if",
"(",
"t",
".",
"range",
"&&",
"this",
"===",
"t",
".",
"range",
".",
"startContainer",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"(",
"this",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
".",
"length",
"===",
"0",
"&&",
"$",
"(",
"this",
")",
".",
"children",
"(",
")",
".",
"not",
"(",
"'br,span'",
")",
".",
"length",
"===",
"0",
";",
"}",
")",
".",
"contents",
"(",
")",
".",
"unwrap",
"(",
")",
";",
"// Get rid of temporary span's",
"$",
"(",
"'[data-tbw]'",
",",
"t",
".",
"$ed",
")",
".",
"contents",
"(",
")",
".",
"unwrap",
"(",
")",
";",
"// Remove empty <p>",
"t",
".",
"$ed",
".",
"find",
"(",
"'p:empty'",
")",
".",
"remove",
"(",
")",
";",
"}",
"if",
"(",
"!",
"keepRange",
")",
"{",
"t",
".",
"restoreRange",
"(",
")",
";",
"}",
"t",
".",
"syncTextarea",
"(",
")",
";",
"}",
"}"
] | Analyse and update to semantic code @param force : force to sync code from textarea @param full : wrap text nodes in <p> @param keepRange : leave selection range as it is | [
"Analyse",
"and",
"update",
"to",
"semantic",
"code"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L1132-L1187 |
|
5,986 | Alex-D/Trumbowyg | src/trumbowyg.js | function () {
var t = this,
documentSelection = t.doc.getSelection(),
node = documentSelection.focusNode,
text = new XMLSerializer().serializeToString(documentSelection.getRangeAt(0).cloneContents()),
url,
title,
target;
while (['A', 'DIV'].indexOf(node.nodeName) < 0) {
node = node.parentNode;
}
if (node && node.nodeName === 'A') {
var $a = $(node);
text = $a.text();
url = $a.attr('href');
if (!t.o.minimalLinks) {
title = $a.attr('title');
target = $a.attr('target');
}
var range = t.doc.createRange();
range.selectNode(node);
documentSelection.removeAllRanges();
documentSelection.addRange(range);
}
t.saveRange();
var options = {
url: {
label: 'URL',
required: true,
value: url
},
text: {
label: t.lang.text,
value: text
}
};
if (!t.o.minimalLinks) {
Object.assign(options, {
title: {
label: t.lang.title,
value: title
},
target: {
label: t.lang.target,
value: target
}
});
}
t.openModalInsert(t.lang.createLink, options, function (v) { // v is value
var url = t.prependUrlPrefix(v.url);
if (!url.length) {
return false;
}
var link = $(['<a href="', url, '">', v.text || v.url, '</a>'].join(''));
if (!t.o.minimalLinks) {
if (v.title.length > 0) {
link.attr('title', v.title);
}
if (v.target.length > 0) {
link.attr('target', v.target);
}
}
t.range.deleteContents();
t.range.insertNode(link[0]);
t.syncCode();
t.$c.trigger('tbwchange');
return true;
});
} | javascript | function () {
var t = this,
documentSelection = t.doc.getSelection(),
node = documentSelection.focusNode,
text = new XMLSerializer().serializeToString(documentSelection.getRangeAt(0).cloneContents()),
url,
title,
target;
while (['A', 'DIV'].indexOf(node.nodeName) < 0) {
node = node.parentNode;
}
if (node && node.nodeName === 'A') {
var $a = $(node);
text = $a.text();
url = $a.attr('href');
if (!t.o.minimalLinks) {
title = $a.attr('title');
target = $a.attr('target');
}
var range = t.doc.createRange();
range.selectNode(node);
documentSelection.removeAllRanges();
documentSelection.addRange(range);
}
t.saveRange();
var options = {
url: {
label: 'URL',
required: true,
value: url
},
text: {
label: t.lang.text,
value: text
}
};
if (!t.o.minimalLinks) {
Object.assign(options, {
title: {
label: t.lang.title,
value: title
},
target: {
label: t.lang.target,
value: target
}
});
}
t.openModalInsert(t.lang.createLink, options, function (v) { // v is value
var url = t.prependUrlPrefix(v.url);
if (!url.length) {
return false;
}
var link = $(['<a href="', url, '">', v.text || v.url, '</a>'].join(''));
if (!t.o.minimalLinks) {
if (v.title.length > 0) {
link.attr('title', v.title);
}
if (v.target.length > 0) {
link.attr('target', v.target);
}
}
t.range.deleteContents();
t.range.insertNode(link[0]);
t.syncCode();
t.$c.trigger('tbwchange');
return true;
});
} | [
"function",
"(",
")",
"{",
"var",
"t",
"=",
"this",
",",
"documentSelection",
"=",
"t",
".",
"doc",
".",
"getSelection",
"(",
")",
",",
"node",
"=",
"documentSelection",
".",
"focusNode",
",",
"text",
"=",
"new",
"XMLSerializer",
"(",
")",
".",
"serializeToString",
"(",
"documentSelection",
".",
"getRangeAt",
"(",
"0",
")",
".",
"cloneContents",
"(",
")",
")",
",",
"url",
",",
"title",
",",
"target",
";",
"while",
"(",
"[",
"'A'",
",",
"'DIV'",
"]",
".",
"indexOf",
"(",
"node",
".",
"nodeName",
")",
"<",
"0",
")",
"{",
"node",
"=",
"node",
".",
"parentNode",
";",
"}",
"if",
"(",
"node",
"&&",
"node",
".",
"nodeName",
"===",
"'A'",
")",
"{",
"var",
"$a",
"=",
"$",
"(",
"node",
")",
";",
"text",
"=",
"$a",
".",
"text",
"(",
")",
";",
"url",
"=",
"$a",
".",
"attr",
"(",
"'href'",
")",
";",
"if",
"(",
"!",
"t",
".",
"o",
".",
"minimalLinks",
")",
"{",
"title",
"=",
"$a",
".",
"attr",
"(",
"'title'",
")",
";",
"target",
"=",
"$a",
".",
"attr",
"(",
"'target'",
")",
";",
"}",
"var",
"range",
"=",
"t",
".",
"doc",
".",
"createRange",
"(",
")",
";",
"range",
".",
"selectNode",
"(",
"node",
")",
";",
"documentSelection",
".",
"removeAllRanges",
"(",
")",
";",
"documentSelection",
".",
"addRange",
"(",
"range",
")",
";",
"}",
"t",
".",
"saveRange",
"(",
")",
";",
"var",
"options",
"=",
"{",
"url",
":",
"{",
"label",
":",
"'URL'",
",",
"required",
":",
"true",
",",
"value",
":",
"url",
"}",
",",
"text",
":",
"{",
"label",
":",
"t",
".",
"lang",
".",
"text",
",",
"value",
":",
"text",
"}",
"}",
";",
"if",
"(",
"!",
"t",
".",
"o",
".",
"minimalLinks",
")",
"{",
"Object",
".",
"assign",
"(",
"options",
",",
"{",
"title",
":",
"{",
"label",
":",
"t",
".",
"lang",
".",
"title",
",",
"value",
":",
"title",
"}",
",",
"target",
":",
"{",
"label",
":",
"t",
".",
"lang",
".",
"target",
",",
"value",
":",
"target",
"}",
"}",
")",
";",
"}",
"t",
".",
"openModalInsert",
"(",
"t",
".",
"lang",
".",
"createLink",
",",
"options",
",",
"function",
"(",
"v",
")",
"{",
"// v is value",
"var",
"url",
"=",
"t",
".",
"prependUrlPrefix",
"(",
"v",
".",
"url",
")",
";",
"if",
"(",
"!",
"url",
".",
"length",
")",
"{",
"return",
"false",
";",
"}",
"var",
"link",
"=",
"$",
"(",
"[",
"'<a href=\"'",
",",
"url",
",",
"'\">'",
",",
"v",
".",
"text",
"||",
"v",
".",
"url",
",",
"'</a>'",
"]",
".",
"join",
"(",
"''",
")",
")",
";",
"if",
"(",
"!",
"t",
".",
"o",
".",
"minimalLinks",
")",
"{",
"if",
"(",
"v",
".",
"title",
".",
"length",
">",
"0",
")",
"{",
"link",
".",
"attr",
"(",
"'title'",
",",
"v",
".",
"title",
")",
";",
"}",
"if",
"(",
"v",
".",
"target",
".",
"length",
">",
"0",
")",
"{",
"link",
".",
"attr",
"(",
"'target'",
",",
"v",
".",
"target",
")",
";",
"}",
"}",
"t",
".",
"range",
".",
"deleteContents",
"(",
")",
";",
"t",
".",
"range",
".",
"insertNode",
"(",
"link",
"[",
"0",
"]",
")",
";",
"t",
".",
"syncCode",
"(",
")",
";",
"t",
".",
"$c",
".",
"trigger",
"(",
"'tbwchange'",
")",
";",
"return",
"true",
";",
"}",
")",
";",
"}"
] | Function call when user click on "Insert Link" | [
"Function",
"call",
"when",
"user",
"click",
"on",
"Insert",
"Link"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L1217-L1292 |
|
5,987 | Alex-D/Trumbowyg | src/trumbowyg.js | function (title, content) {
var t = this,
prefix = t.o.prefix;
// No open a modal box when exist other modal box
if ($('.' + prefix + 'modal-box', t.$box).length > 0) {
return false;
}
if (t.o.autogrowOnEnter) {
t.autogrowOnEnterDontClose = true;
}
t.saveRange();
t.showOverlay();
// Disable all btnPane btns
t.$btnPane.addClass(prefix + 'disable');
// Build out of ModalBox, it's the mask for animations
var $modal = $('<div/>', {
class: prefix + 'modal ' + prefix + 'fixed-top'
}).css({
top: t.$box.offset().top + t.$btnPane.height(),
zIndex: 99999
}).appendTo($(t.doc.body));
// Click on overlay close modal by cancelling them
t.$overlay.one('click', function () {
$modal.trigger(CANCEL_EVENT);
return false;
});
// Build the form
var $form = $('<form/>', {
action: '',
html: content
})
.on('submit', function () {
$modal.trigger(CONFIRM_EVENT);
return false;
})
.on('reset', function () {
$modal.trigger(CANCEL_EVENT);
return false;
})
.on('submit reset', function () {
if (t.o.autogrowOnEnter) {
t.autogrowOnEnterDontClose = false;
}
});
// Build ModalBox and animate to show them
var $box = $('<div/>', {
class: prefix + 'modal-box',
html: $form
})
.css({
top: '-' + t.$btnPane.outerHeight() + 'px',
opacity: 0
})
.appendTo($modal)
.animate({
top: 0,
opacity: 1
}, 100);
// Append title
$('<span/>', {
text: title,
class: prefix + 'modal-title'
}).prependTo($box);
$modal.height($box.outerHeight() + 10);
// Focus in modal box
$('input:first', $box).focus();
// Append Confirm and Cancel buttons
t.buildModalBtn('submit', $box);
t.buildModalBtn('reset', $box);
$(window).trigger('scroll');
return $modal;
} | javascript | function (title, content) {
var t = this,
prefix = t.o.prefix;
// No open a modal box when exist other modal box
if ($('.' + prefix + 'modal-box', t.$box).length > 0) {
return false;
}
if (t.o.autogrowOnEnter) {
t.autogrowOnEnterDontClose = true;
}
t.saveRange();
t.showOverlay();
// Disable all btnPane btns
t.$btnPane.addClass(prefix + 'disable');
// Build out of ModalBox, it's the mask for animations
var $modal = $('<div/>', {
class: prefix + 'modal ' + prefix + 'fixed-top'
}).css({
top: t.$box.offset().top + t.$btnPane.height(),
zIndex: 99999
}).appendTo($(t.doc.body));
// Click on overlay close modal by cancelling them
t.$overlay.one('click', function () {
$modal.trigger(CANCEL_EVENT);
return false;
});
// Build the form
var $form = $('<form/>', {
action: '',
html: content
})
.on('submit', function () {
$modal.trigger(CONFIRM_EVENT);
return false;
})
.on('reset', function () {
$modal.trigger(CANCEL_EVENT);
return false;
})
.on('submit reset', function () {
if (t.o.autogrowOnEnter) {
t.autogrowOnEnterDontClose = false;
}
});
// Build ModalBox and animate to show them
var $box = $('<div/>', {
class: prefix + 'modal-box',
html: $form
})
.css({
top: '-' + t.$btnPane.outerHeight() + 'px',
opacity: 0
})
.appendTo($modal)
.animate({
top: 0,
opacity: 1
}, 100);
// Append title
$('<span/>', {
text: title,
class: prefix + 'modal-title'
}).prependTo($box);
$modal.height($box.outerHeight() + 10);
// Focus in modal box
$('input:first', $box).focus();
// Append Confirm and Cancel buttons
t.buildModalBtn('submit', $box);
t.buildModalBtn('reset', $box);
$(window).trigger('scroll');
return $modal;
} | [
"function",
"(",
"title",
",",
"content",
")",
"{",
"var",
"t",
"=",
"this",
",",
"prefix",
"=",
"t",
".",
"o",
".",
"prefix",
";",
"// No open a modal box when exist other modal box",
"if",
"(",
"$",
"(",
"'.'",
"+",
"prefix",
"+",
"'modal-box'",
",",
"t",
".",
"$box",
")",
".",
"length",
">",
"0",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"t",
".",
"o",
".",
"autogrowOnEnter",
")",
"{",
"t",
".",
"autogrowOnEnterDontClose",
"=",
"true",
";",
"}",
"t",
".",
"saveRange",
"(",
")",
";",
"t",
".",
"showOverlay",
"(",
")",
";",
"// Disable all btnPane btns",
"t",
".",
"$btnPane",
".",
"addClass",
"(",
"prefix",
"+",
"'disable'",
")",
";",
"// Build out of ModalBox, it's the mask for animations",
"var",
"$modal",
"=",
"$",
"(",
"'<div/>'",
",",
"{",
"class",
":",
"prefix",
"+",
"'modal '",
"+",
"prefix",
"+",
"'fixed-top'",
"}",
")",
".",
"css",
"(",
"{",
"top",
":",
"t",
".",
"$box",
".",
"offset",
"(",
")",
".",
"top",
"+",
"t",
".",
"$btnPane",
".",
"height",
"(",
")",
",",
"zIndex",
":",
"99999",
"}",
")",
".",
"appendTo",
"(",
"$",
"(",
"t",
".",
"doc",
".",
"body",
")",
")",
";",
"// Click on overlay close modal by cancelling them",
"t",
".",
"$overlay",
".",
"one",
"(",
"'click'",
",",
"function",
"(",
")",
"{",
"$modal",
".",
"trigger",
"(",
"CANCEL_EVENT",
")",
";",
"return",
"false",
";",
"}",
")",
";",
"// Build the form",
"var",
"$form",
"=",
"$",
"(",
"'<form/>'",
",",
"{",
"action",
":",
"''",
",",
"html",
":",
"content",
"}",
")",
".",
"on",
"(",
"'submit'",
",",
"function",
"(",
")",
"{",
"$modal",
".",
"trigger",
"(",
"CONFIRM_EVENT",
")",
";",
"return",
"false",
";",
"}",
")",
".",
"on",
"(",
"'reset'",
",",
"function",
"(",
")",
"{",
"$modal",
".",
"trigger",
"(",
"CANCEL_EVENT",
")",
";",
"return",
"false",
";",
"}",
")",
".",
"on",
"(",
"'submit reset'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"t",
".",
"o",
".",
"autogrowOnEnter",
")",
"{",
"t",
".",
"autogrowOnEnterDontClose",
"=",
"false",
";",
"}",
"}",
")",
";",
"// Build ModalBox and animate to show them",
"var",
"$box",
"=",
"$",
"(",
"'<div/>'",
",",
"{",
"class",
":",
"prefix",
"+",
"'modal-box'",
",",
"html",
":",
"$form",
"}",
")",
".",
"css",
"(",
"{",
"top",
":",
"'-'",
"+",
"t",
".",
"$btnPane",
".",
"outerHeight",
"(",
")",
"+",
"'px'",
",",
"opacity",
":",
"0",
"}",
")",
".",
"appendTo",
"(",
"$modal",
")",
".",
"animate",
"(",
"{",
"top",
":",
"0",
",",
"opacity",
":",
"1",
"}",
",",
"100",
")",
";",
"// Append title",
"$",
"(",
"'<span/>'",
",",
"{",
"text",
":",
"title",
",",
"class",
":",
"prefix",
"+",
"'modal-title'",
"}",
")",
".",
"prependTo",
"(",
"$box",
")",
";",
"$modal",
".",
"height",
"(",
"$box",
".",
"outerHeight",
"(",
")",
"+",
"10",
")",
";",
"// Focus in modal box",
"$",
"(",
"'input:first'",
",",
"$box",
")",
".",
"focus",
"(",
")",
";",
"// Append Confirm and Cancel buttons",
"t",
".",
"buildModalBtn",
"(",
"'submit'",
",",
"$box",
")",
";",
"t",
".",
"buildModalBtn",
"(",
"'reset'",
",",
"$box",
")",
";",
"$",
"(",
"window",
")",
".",
"trigger",
"(",
"'scroll'",
")",
";",
"return",
"$modal",
";",
"}"
] | Open a modal box | [
"Open",
"a",
"modal",
"box"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L1425-L1514 |
|
5,988 | Alex-D/Trumbowyg | src/trumbowyg.js | function () {
var t = this,
prefix = t.o.prefix;
t.$btnPane.removeClass(prefix + 'disable');
t.$overlay.off();
// Find the modal box
var $modalBox = $('.' + prefix + 'modal-box', $(t.doc.body));
$modalBox.animate({
top: '-' + $modalBox.height()
}, 100, function () {
$modalBox.parent().remove();
t.hideOverlay();
});
t.restoreRange();
} | javascript | function () {
var t = this,
prefix = t.o.prefix;
t.$btnPane.removeClass(prefix + 'disable');
t.$overlay.off();
// Find the modal box
var $modalBox = $('.' + prefix + 'modal-box', $(t.doc.body));
$modalBox.animate({
top: '-' + $modalBox.height()
}, 100, function () {
$modalBox.parent().remove();
t.hideOverlay();
});
t.restoreRange();
} | [
"function",
"(",
")",
"{",
"var",
"t",
"=",
"this",
",",
"prefix",
"=",
"t",
".",
"o",
".",
"prefix",
";",
"t",
".",
"$btnPane",
".",
"removeClass",
"(",
"prefix",
"+",
"'disable'",
")",
";",
"t",
".",
"$overlay",
".",
"off",
"(",
")",
";",
"// Find the modal box",
"var",
"$modalBox",
"=",
"$",
"(",
"'.'",
"+",
"prefix",
"+",
"'modal-box'",
",",
"$",
"(",
"t",
".",
"doc",
".",
"body",
")",
")",
";",
"$modalBox",
".",
"animate",
"(",
"{",
"top",
":",
"'-'",
"+",
"$modalBox",
".",
"height",
"(",
")",
"}",
",",
"100",
",",
"function",
"(",
")",
"{",
"$modalBox",
".",
"parent",
"(",
")",
".",
"remove",
"(",
")",
";",
"t",
".",
"hideOverlay",
"(",
")",
";",
"}",
")",
";",
"t",
".",
"restoreRange",
"(",
")",
";",
"}"
] | close current modal box | [
"close",
"current",
"modal",
"box"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L1527-L1545 |
|
5,989 | Alex-D/Trumbowyg | src/trumbowyg.js | function (title, fields, cmd) {
var t = this,
prefix = t.o.prefix,
lg = t.lang,
html = '';
$.each(fields, function (fieldName, field) {
var l = field.label || fieldName,
n = field.name || fieldName,
a = field.attributes || {};
var attr = Object.keys(a).map(function (prop) {
return prop + '="' + a[prop] + '"';
}).join(' ');
html += '<label><input type="' + (field.type || 'text') + '" name="' + n + '"' +
(field.type === 'checkbox' && field.value ? ' checked="checked"' : ' value="' + (field.value || '').replace(/"/g, '"')) +
'"' + attr + '><span class="' + prefix + 'input-infos"><span>' +
(lg[l] ? lg[l] : l) +
'</span></span></label>';
});
return t.openModal(title, html)
.on(CONFIRM_EVENT, function () {
var $form = $('form', $(this)),
valid = true,
values = {};
$.each(fields, function (fieldName, field) {
var n = field.name || fieldName;
var $field = $('input[name="' + n + '"]', $form),
inputType = $field.attr('type');
switch (inputType.toLowerCase()) {
case 'checkbox':
values[n] = $field.is(':checked');
break;
case 'radio':
values[n] = $field.filter(':checked').val();
break;
default:
values[n] = $.trim($field.val());
break;
}
// Validate value
if (field.required && values[n] === '') {
valid = false;
t.addErrorOnModalField($field, t.lang.required);
} else if (field.pattern && !field.pattern.test(values[n])) {
valid = false;
t.addErrorOnModalField($field, field.patternError);
}
});
if (valid) {
t.restoreRange();
if (cmd(values, fields)) {
t.syncCode();
t.$c.trigger('tbwchange');
t.closeModal();
$(this).off(CONFIRM_EVENT);
}
}
})
.one(CANCEL_EVENT, function () {
$(this).off(CONFIRM_EVENT);
t.closeModal();
});
} | javascript | function (title, fields, cmd) {
var t = this,
prefix = t.o.prefix,
lg = t.lang,
html = '';
$.each(fields, function (fieldName, field) {
var l = field.label || fieldName,
n = field.name || fieldName,
a = field.attributes || {};
var attr = Object.keys(a).map(function (prop) {
return prop + '="' + a[prop] + '"';
}).join(' ');
html += '<label><input type="' + (field.type || 'text') + '" name="' + n + '"' +
(field.type === 'checkbox' && field.value ? ' checked="checked"' : ' value="' + (field.value || '').replace(/"/g, '"')) +
'"' + attr + '><span class="' + prefix + 'input-infos"><span>' +
(lg[l] ? lg[l] : l) +
'</span></span></label>';
});
return t.openModal(title, html)
.on(CONFIRM_EVENT, function () {
var $form = $('form', $(this)),
valid = true,
values = {};
$.each(fields, function (fieldName, field) {
var n = field.name || fieldName;
var $field = $('input[name="' + n + '"]', $form),
inputType = $field.attr('type');
switch (inputType.toLowerCase()) {
case 'checkbox':
values[n] = $field.is(':checked');
break;
case 'radio':
values[n] = $field.filter(':checked').val();
break;
default:
values[n] = $.trim($field.val());
break;
}
// Validate value
if (field.required && values[n] === '') {
valid = false;
t.addErrorOnModalField($field, t.lang.required);
} else if (field.pattern && !field.pattern.test(values[n])) {
valid = false;
t.addErrorOnModalField($field, field.patternError);
}
});
if (valid) {
t.restoreRange();
if (cmd(values, fields)) {
t.syncCode();
t.$c.trigger('tbwchange');
t.closeModal();
$(this).off(CONFIRM_EVENT);
}
}
})
.one(CANCEL_EVENT, function () {
$(this).off(CONFIRM_EVENT);
t.closeModal();
});
} | [
"function",
"(",
"title",
",",
"fields",
",",
"cmd",
")",
"{",
"var",
"t",
"=",
"this",
",",
"prefix",
"=",
"t",
".",
"o",
".",
"prefix",
",",
"lg",
"=",
"t",
".",
"lang",
",",
"html",
"=",
"''",
";",
"$",
".",
"each",
"(",
"fields",
",",
"function",
"(",
"fieldName",
",",
"field",
")",
"{",
"var",
"l",
"=",
"field",
".",
"label",
"||",
"fieldName",
",",
"n",
"=",
"field",
".",
"name",
"||",
"fieldName",
",",
"a",
"=",
"field",
".",
"attributes",
"||",
"{",
"}",
";",
"var",
"attr",
"=",
"Object",
".",
"keys",
"(",
"a",
")",
".",
"map",
"(",
"function",
"(",
"prop",
")",
"{",
"return",
"prop",
"+",
"'=\"'",
"+",
"a",
"[",
"prop",
"]",
"+",
"'\"'",
";",
"}",
")",
".",
"join",
"(",
"' '",
")",
";",
"html",
"+=",
"'<label><input type=\"'",
"+",
"(",
"field",
".",
"type",
"||",
"'text'",
")",
"+",
"'\" name=\"'",
"+",
"n",
"+",
"'\"'",
"+",
"(",
"field",
".",
"type",
"===",
"'checkbox'",
"&&",
"field",
".",
"value",
"?",
"' checked=\"checked\"'",
":",
"' value=\"'",
"+",
"(",
"field",
".",
"value",
"||",
"''",
")",
".",
"replace",
"(",
"/",
"\"",
"/",
"g",
",",
"'"'",
")",
")",
"+",
"'\"'",
"+",
"attr",
"+",
"'><span class=\"'",
"+",
"prefix",
"+",
"'input-infos\"><span>'",
"+",
"(",
"lg",
"[",
"l",
"]",
"?",
"lg",
"[",
"l",
"]",
":",
"l",
")",
"+",
"'</span></span></label>'",
";",
"}",
")",
";",
"return",
"t",
".",
"openModal",
"(",
"title",
",",
"html",
")",
".",
"on",
"(",
"CONFIRM_EVENT",
",",
"function",
"(",
")",
"{",
"var",
"$form",
"=",
"$",
"(",
"'form'",
",",
"$",
"(",
"this",
")",
")",
",",
"valid",
"=",
"true",
",",
"values",
"=",
"{",
"}",
";",
"$",
".",
"each",
"(",
"fields",
",",
"function",
"(",
"fieldName",
",",
"field",
")",
"{",
"var",
"n",
"=",
"field",
".",
"name",
"||",
"fieldName",
";",
"var",
"$field",
"=",
"$",
"(",
"'input[name=\"'",
"+",
"n",
"+",
"'\"]'",
",",
"$form",
")",
",",
"inputType",
"=",
"$field",
".",
"attr",
"(",
"'type'",
")",
";",
"switch",
"(",
"inputType",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"'checkbox'",
":",
"values",
"[",
"n",
"]",
"=",
"$field",
".",
"is",
"(",
"':checked'",
")",
";",
"break",
";",
"case",
"'radio'",
":",
"values",
"[",
"n",
"]",
"=",
"$field",
".",
"filter",
"(",
"':checked'",
")",
".",
"val",
"(",
")",
";",
"break",
";",
"default",
":",
"values",
"[",
"n",
"]",
"=",
"$",
".",
"trim",
"(",
"$field",
".",
"val",
"(",
")",
")",
";",
"break",
";",
"}",
"// Validate value",
"if",
"(",
"field",
".",
"required",
"&&",
"values",
"[",
"n",
"]",
"===",
"''",
")",
"{",
"valid",
"=",
"false",
";",
"t",
".",
"addErrorOnModalField",
"(",
"$field",
",",
"t",
".",
"lang",
".",
"required",
")",
";",
"}",
"else",
"if",
"(",
"field",
".",
"pattern",
"&&",
"!",
"field",
".",
"pattern",
".",
"test",
"(",
"values",
"[",
"n",
"]",
")",
")",
"{",
"valid",
"=",
"false",
";",
"t",
".",
"addErrorOnModalField",
"(",
"$field",
",",
"field",
".",
"patternError",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"valid",
")",
"{",
"t",
".",
"restoreRange",
"(",
")",
";",
"if",
"(",
"cmd",
"(",
"values",
",",
"fields",
")",
")",
"{",
"t",
".",
"syncCode",
"(",
")",
";",
"t",
".",
"$c",
".",
"trigger",
"(",
"'tbwchange'",
")",
";",
"t",
".",
"closeModal",
"(",
")",
";",
"$",
"(",
"this",
")",
".",
"off",
"(",
"CONFIRM_EVENT",
")",
";",
"}",
"}",
"}",
")",
".",
"one",
"(",
"CANCEL_EVENT",
",",
"function",
"(",
")",
"{",
"$",
"(",
"this",
")",
".",
"off",
"(",
"CONFIRM_EVENT",
")",
";",
"t",
".",
"closeModal",
"(",
")",
";",
"}",
")",
";",
"}"
] | Preformatted build and management modal | [
"Preformatted",
"build",
"and",
"management",
"modal"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/src/trumbowyg.js#L1547-L1617 |
|
5,990 | Alex-D/Trumbowyg | plugins/highlight/trumbowyg.highlight.js | buildButtonDef | function buildButtonDef(trumbowyg) {
return {
fn: function () {
var $modal = trumbowyg.openModal('Code', [
'<div class="' + trumbowyg.o.prefix + 'highlight-form-group">',
' <select class="' + trumbowyg.o.prefix + 'highlight-form-control language">',
(function () {
var options = '';
for (var lang in Prism.languages) {
if (Prism.languages.hasOwnProperty(lang)) {
options += '<option value="' + lang + '">' + lang + '</option>';
}
}
return options;
})(),
' </select>',
'</div>',
'<div class="' + trumbowyg.o.prefix + 'highlight-form-group">',
' <textarea class="' + trumbowyg.o.prefix + 'highlight-form-control code"></textarea>',
'</div>',
].join('\n')),
$language = $modal.find('.language'),
$code = $modal.find('.code');
// Listen clicks on modal box buttons
$modal.on('tbwconfirm', function () {
trumbowyg.restoreRange();
trumbowyg.execCmd('insertHTML', highlightIt($code.val(), $language.val()));
trumbowyg.execCmd('insertHTML', '<p><br></p>');
trumbowyg.closeModal();
});
$modal.on('tbwcancel', function () {
trumbowyg.closeModal();
});
}
};
} | javascript | function buildButtonDef(trumbowyg) {
return {
fn: function () {
var $modal = trumbowyg.openModal('Code', [
'<div class="' + trumbowyg.o.prefix + 'highlight-form-group">',
' <select class="' + trumbowyg.o.prefix + 'highlight-form-control language">',
(function () {
var options = '';
for (var lang in Prism.languages) {
if (Prism.languages.hasOwnProperty(lang)) {
options += '<option value="' + lang + '">' + lang + '</option>';
}
}
return options;
})(),
' </select>',
'</div>',
'<div class="' + trumbowyg.o.prefix + 'highlight-form-group">',
' <textarea class="' + trumbowyg.o.prefix + 'highlight-form-control code"></textarea>',
'</div>',
].join('\n')),
$language = $modal.find('.language'),
$code = $modal.find('.code');
// Listen clicks on modal box buttons
$modal.on('tbwconfirm', function () {
trumbowyg.restoreRange();
trumbowyg.execCmd('insertHTML', highlightIt($code.val(), $language.val()));
trumbowyg.execCmd('insertHTML', '<p><br></p>');
trumbowyg.closeModal();
});
$modal.on('tbwcancel', function () {
trumbowyg.closeModal();
});
}
};
} | [
"function",
"buildButtonDef",
"(",
"trumbowyg",
")",
"{",
"return",
"{",
"fn",
":",
"function",
"(",
")",
"{",
"var",
"$modal",
"=",
"trumbowyg",
".",
"openModal",
"(",
"'Code'",
",",
"[",
"'<div class=\"'",
"+",
"trumbowyg",
".",
"o",
".",
"prefix",
"+",
"'highlight-form-group\">'",
",",
"' <select class=\"'",
"+",
"trumbowyg",
".",
"o",
".",
"prefix",
"+",
"'highlight-form-control language\">'",
",",
"(",
"function",
"(",
")",
"{",
"var",
"options",
"=",
"''",
";",
"for",
"(",
"var",
"lang",
"in",
"Prism",
".",
"languages",
")",
"{",
"if",
"(",
"Prism",
".",
"languages",
".",
"hasOwnProperty",
"(",
"lang",
")",
")",
"{",
"options",
"+=",
"'<option value=\"'",
"+",
"lang",
"+",
"'\">'",
"+",
"lang",
"+",
"'</option>'",
";",
"}",
"}",
"return",
"options",
";",
"}",
")",
"(",
")",
",",
"' </select>'",
",",
"'</div>'",
",",
"'<div class=\"'",
"+",
"trumbowyg",
".",
"o",
".",
"prefix",
"+",
"'highlight-form-group\">'",
",",
"' <textarea class=\"'",
"+",
"trumbowyg",
".",
"o",
".",
"prefix",
"+",
"'highlight-form-control code\"></textarea>'",
",",
"'</div>'",
",",
"]",
".",
"join",
"(",
"'\\n'",
")",
")",
",",
"$language",
"=",
"$modal",
".",
"find",
"(",
"'.language'",
")",
",",
"$code",
"=",
"$modal",
".",
"find",
"(",
"'.code'",
")",
";",
"// Listen clicks on modal box buttons",
"$modal",
".",
"on",
"(",
"'tbwconfirm'",
",",
"function",
"(",
")",
"{",
"trumbowyg",
".",
"restoreRange",
"(",
")",
";",
"trumbowyg",
".",
"execCmd",
"(",
"'insertHTML'",
",",
"highlightIt",
"(",
"$code",
".",
"val",
"(",
")",
",",
"$language",
".",
"val",
"(",
")",
")",
")",
";",
"trumbowyg",
".",
"execCmd",
"(",
"'insertHTML'",
",",
"'<p><br></p>'",
")",
";",
"trumbowyg",
".",
"closeModal",
"(",
")",
";",
"}",
")",
";",
"$modal",
".",
"on",
"(",
"'tbwcancel'",
",",
"function",
"(",
")",
"{",
"trumbowyg",
".",
"closeModal",
"(",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"}"
] | If my plugin is a button | [
"If",
"my",
"plugin",
"is",
"a",
"button"
] | 98995a217241bf76f0c07eff1398f5592c061309 | https://github.com/Alex-D/Trumbowyg/blob/98995a217241bf76f0c07eff1398f5592c061309/plugins/highlight/trumbowyg.highlight.js#L17-L57 |
5,991 | Netflix/vizceral | src/dns/dnsConnectionView.js | CalculateCircleCenter | function CalculateCircleCenter (A, B, C) {
const aSlope = (B.y - A.y) / (B.x - A.x);
const bSlope = (C.y - B.y) / (C.x - B.x);
if (aSlope === 0 || bSlope === 0) {
// rotate the points about origin to retry and then rotate the answer back.
// this should avoid div by zero.
// we could pick any acute angle here and be garuanteed this will take less than three tries.
// i've discovered a clever proof for this, but I don't have room in the margin.
const angle = Math.PI / 3;
return rotate(CalculateCircleCenter(rotate(A, angle), rotate(B, angle), rotate(C, angle)), -1 * angle);
}
const center = {};
center.x = (aSlope * bSlope * (A.y - C.y) + bSlope * (A.x + B.x) - aSlope * (B.x + C.x)) / (2 * (bSlope - aSlope));
center.y = -1 * (center.x - (A.x + B.x) / 2) / aSlope + (A.y + B.y) / 2;
return center;
} | javascript | function CalculateCircleCenter (A, B, C) {
const aSlope = (B.y - A.y) / (B.x - A.x);
const bSlope = (C.y - B.y) / (C.x - B.x);
if (aSlope === 0 || bSlope === 0) {
// rotate the points about origin to retry and then rotate the answer back.
// this should avoid div by zero.
// we could pick any acute angle here and be garuanteed this will take less than three tries.
// i've discovered a clever proof for this, but I don't have room in the margin.
const angle = Math.PI / 3;
return rotate(CalculateCircleCenter(rotate(A, angle), rotate(B, angle), rotate(C, angle)), -1 * angle);
}
const center = {};
center.x = (aSlope * bSlope * (A.y - C.y) + bSlope * (A.x + B.x) - aSlope * (B.x + C.x)) / (2 * (bSlope - aSlope));
center.y = -1 * (center.x - (A.x + B.x) / 2) / aSlope + (A.y + B.y) / 2;
return center;
} | [
"function",
"CalculateCircleCenter",
"(",
"A",
",",
"B",
",",
"C",
")",
"{",
"const",
"aSlope",
"=",
"(",
"B",
".",
"y",
"-",
"A",
".",
"y",
")",
"/",
"(",
"B",
".",
"x",
"-",
"A",
".",
"x",
")",
";",
"const",
"bSlope",
"=",
"(",
"C",
".",
"y",
"-",
"B",
".",
"y",
")",
"/",
"(",
"C",
".",
"x",
"-",
"B",
".",
"x",
")",
";",
"if",
"(",
"aSlope",
"===",
"0",
"||",
"bSlope",
"===",
"0",
")",
"{",
"// rotate the points about origin to retry and then rotate the answer back.",
"// this should avoid div by zero.",
"// we could pick any acute angle here and be garuanteed this will take less than three tries.",
"// i've discovered a clever proof for this, but I don't have room in the margin.",
"const",
"angle",
"=",
"Math",
".",
"PI",
"/",
"3",
";",
"return",
"rotate",
"(",
"CalculateCircleCenter",
"(",
"rotate",
"(",
"A",
",",
"angle",
")",
",",
"rotate",
"(",
"B",
",",
"angle",
")",
",",
"rotate",
"(",
"C",
",",
"angle",
")",
")",
",",
"-",
"1",
"*",
"angle",
")",
";",
"}",
"const",
"center",
"=",
"{",
"}",
";",
"center",
".",
"x",
"=",
"(",
"aSlope",
"*",
"bSlope",
"*",
"(",
"A",
".",
"y",
"-",
"C",
".",
"y",
")",
"+",
"bSlope",
"*",
"(",
"A",
".",
"x",
"+",
"B",
".",
"x",
")",
"-",
"aSlope",
"*",
"(",
"B",
".",
"x",
"+",
"C",
".",
"x",
")",
")",
"/",
"(",
"2",
"*",
"(",
"bSlope",
"-",
"aSlope",
")",
")",
";",
"center",
".",
"y",
"=",
"-",
"1",
"*",
"(",
"center",
".",
"x",
"-",
"(",
"A",
".",
"x",
"+",
"B",
".",
"x",
")",
"/",
"2",
")",
"/",
"aSlope",
"+",
"(",
"A",
".",
"y",
"+",
"B",
".",
"y",
")",
"/",
"2",
";",
"return",
"center",
";",
"}"
] | Given three points, A B C, find the center of a circle that goes through all three. | [
"Given",
"three",
"points",
"A",
"B",
"C",
"find",
"the",
"center",
"of",
"a",
"circle",
"that",
"goes",
"through",
"all",
"three",
"."
] | 848db649b3baea5fd761d79b0f15154a205fb9f4 | https://github.com/Netflix/vizceral/blob/848db649b3baea5fd761d79b0f15154a205fb9f4/src/dns/dnsConnectionView.js#L44-L63 |
5,992 | louischatriot/nedb | lib/model.js | checkObject | function checkObject (obj) {
if (util.isArray(obj)) {
obj.forEach(function (o) {
checkObject(o);
});
}
if (typeof obj === 'object' && obj !== null) {
Object.keys(obj).forEach(function (k) {
checkKey(k, obj[k]);
checkObject(obj[k]);
});
}
} | javascript | function checkObject (obj) {
if (util.isArray(obj)) {
obj.forEach(function (o) {
checkObject(o);
});
}
if (typeof obj === 'object' && obj !== null) {
Object.keys(obj).forEach(function (k) {
checkKey(k, obj[k]);
checkObject(obj[k]);
});
}
} | [
"function",
"checkObject",
"(",
"obj",
")",
"{",
"if",
"(",
"util",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"obj",
".",
"forEach",
"(",
"function",
"(",
"o",
")",
"{",
"checkObject",
"(",
"o",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"typeof",
"obj",
"===",
"'object'",
"&&",
"obj",
"!==",
"null",
")",
"{",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"forEach",
"(",
"function",
"(",
"k",
")",
"{",
"checkKey",
"(",
"k",
",",
"obj",
"[",
"k",
"]",
")",
";",
"checkObject",
"(",
"obj",
"[",
"k",
"]",
")",
";",
"}",
")",
";",
"}",
"}"
] | Check a DB object and throw an error if it's not valid
Works by applying the above checkKey function to all fields recursively | [
"Check",
"a",
"DB",
"object",
"and",
"throw",
"an",
"error",
"if",
"it",
"s",
"not",
"valid",
"Works",
"by",
"applying",
"the",
"above",
"checkKey",
"function",
"to",
"all",
"fields",
"recursively"
] | aa3302e5dcefa471431901a8f3fe63e532a5a7b2 | https://github.com/louischatriot/nedb/blob/aa3302e5dcefa471431901a8f3fe63e532a5a7b2/lib/model.js#L45-L58 |
5,993 | louischatriot/nedb | lib/model.js | isPrimitiveType | function isPrimitiveType (obj) {
return ( typeof obj === 'boolean' ||
typeof obj === 'number' ||
typeof obj === 'string' ||
obj === null ||
util.isDate(obj) ||
util.isArray(obj));
} | javascript | function isPrimitiveType (obj) {
return ( typeof obj === 'boolean' ||
typeof obj === 'number' ||
typeof obj === 'string' ||
obj === null ||
util.isDate(obj) ||
util.isArray(obj));
} | [
"function",
"isPrimitiveType",
"(",
"obj",
")",
"{",
"return",
"(",
"typeof",
"obj",
"===",
"'boolean'",
"||",
"typeof",
"obj",
"===",
"'number'",
"||",
"typeof",
"obj",
"===",
"'string'",
"||",
"obj",
"===",
"null",
"||",
"util",
".",
"isDate",
"(",
"obj",
")",
"||",
"util",
".",
"isArray",
"(",
"obj",
")",
")",
";",
"}"
] | Tells if an object is a primitive type or a "real" object
Arrays are considered primitive | [
"Tells",
"if",
"an",
"object",
"is",
"a",
"primitive",
"type",
"or",
"a",
"real",
"object",
"Arrays",
"are",
"considered",
"primitive"
] | aa3302e5dcefa471431901a8f3fe63e532a5a7b2 | https://github.com/louischatriot/nedb/blob/aa3302e5dcefa471431901a8f3fe63e532a5a7b2/lib/model.js#L144-L151 |
5,994 | louischatriot/nedb | lib/model.js | createModifierFunction | function createModifierFunction (modifier) {
return function (obj, field, value) {
var fieldParts = typeof field === 'string' ? field.split('.') : field;
if (fieldParts.length === 1) {
lastStepModifierFunctions[modifier](obj, field, value);
} else {
if (obj[fieldParts[0]] === undefined) {
if (modifier === '$unset') { return; } // Bad looking specific fix, needs to be generalized modifiers that behave like $unset are implemented
obj[fieldParts[0]] = {};
}
modifierFunctions[modifier](obj[fieldParts[0]], fieldParts.slice(1), value);
}
};
} | javascript | function createModifierFunction (modifier) {
return function (obj, field, value) {
var fieldParts = typeof field === 'string' ? field.split('.') : field;
if (fieldParts.length === 1) {
lastStepModifierFunctions[modifier](obj, field, value);
} else {
if (obj[fieldParts[0]] === undefined) {
if (modifier === '$unset') { return; } // Bad looking specific fix, needs to be generalized modifiers that behave like $unset are implemented
obj[fieldParts[0]] = {};
}
modifierFunctions[modifier](obj[fieldParts[0]], fieldParts.slice(1), value);
}
};
} | [
"function",
"createModifierFunction",
"(",
"modifier",
")",
"{",
"return",
"function",
"(",
"obj",
",",
"field",
",",
"value",
")",
"{",
"var",
"fieldParts",
"=",
"typeof",
"field",
"===",
"'string'",
"?",
"field",
".",
"split",
"(",
"'.'",
")",
":",
"field",
";",
"if",
"(",
"fieldParts",
".",
"length",
"===",
"1",
")",
"{",
"lastStepModifierFunctions",
"[",
"modifier",
"]",
"(",
"obj",
",",
"field",
",",
"value",
")",
";",
"}",
"else",
"{",
"if",
"(",
"obj",
"[",
"fieldParts",
"[",
"0",
"]",
"]",
"===",
"undefined",
")",
"{",
"if",
"(",
"modifier",
"===",
"'$unset'",
")",
"{",
"return",
";",
"}",
"// Bad looking specific fix, needs to be generalized modifiers that behave like $unset are implemented",
"obj",
"[",
"fieldParts",
"[",
"0",
"]",
"]",
"=",
"{",
"}",
";",
"}",
"modifierFunctions",
"[",
"modifier",
"]",
"(",
"obj",
"[",
"fieldParts",
"[",
"0",
"]",
"]",
",",
"fieldParts",
".",
"slice",
"(",
"1",
")",
",",
"value",
")",
";",
"}",
"}",
";",
"}"
] | Given its name, create the complete modifier function | [
"Given",
"its",
"name",
"create",
"the",
"complete",
"modifier",
"function"
] | aa3302e5dcefa471431901a8f3fe63e532a5a7b2 | https://github.com/louischatriot/nedb/blob/aa3302e5dcefa471431901a8f3fe63e532a5a7b2/lib/model.js#L412-L426 |
5,995 | louischatriot/nedb | lib/model.js | areComparable | function areComparable (a, b) {
if (typeof a !== 'string' && typeof a !== 'number' && !util.isDate(a) &&
typeof b !== 'string' && typeof b !== 'number' && !util.isDate(b)) {
return false;
}
if (typeof a !== typeof b) { return false; }
return true;
} | javascript | function areComparable (a, b) {
if (typeof a !== 'string' && typeof a !== 'number' && !util.isDate(a) &&
typeof b !== 'string' && typeof b !== 'number' && !util.isDate(b)) {
return false;
}
if (typeof a !== typeof b) { return false; }
return true;
} | [
"function",
"areComparable",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"typeof",
"a",
"!==",
"'string'",
"&&",
"typeof",
"a",
"!==",
"'number'",
"&&",
"!",
"util",
".",
"isDate",
"(",
"a",
")",
"&&",
"typeof",
"b",
"!==",
"'string'",
"&&",
"typeof",
"b",
"!==",
"'number'",
"&&",
"!",
"util",
".",
"isDate",
"(",
"b",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"typeof",
"a",
"!==",
"typeof",
"b",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Check that two values are comparable | [
"Check",
"that",
"two",
"values",
"are",
"comparable"
] | aa3302e5dcefa471431901a8f3fe63e532a5a7b2 | https://github.com/louischatriot/nedb/blob/aa3302e5dcefa471431901a8f3fe63e532a5a7b2/lib/model.js#L563-L572 |
5,996 | louischatriot/nedb | benchmarks/commonUtilities.js | getRandomArray | function getRandomArray (n) {
var res = []
, i, j, temp
;
for (i = 0; i < n; i += 1) { res[i] = i; }
for (i = n - 1; i >= 1; i -= 1) {
j = Math.floor((i + 1) * Math.random());
temp = res[i];
res[i] = res[j];
res[j] = temp;
}
return res;
} | javascript | function getRandomArray (n) {
var res = []
, i, j, temp
;
for (i = 0; i < n; i += 1) { res[i] = i; }
for (i = n - 1; i >= 1; i -= 1) {
j = Math.floor((i + 1) * Math.random());
temp = res[i];
res[i] = res[j];
res[j] = temp;
}
return res;
} | [
"function",
"getRandomArray",
"(",
"n",
")",
"{",
"var",
"res",
"=",
"[",
"]",
",",
"i",
",",
"j",
",",
"temp",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"+=",
"1",
")",
"{",
"res",
"[",
"i",
"]",
"=",
"i",
";",
"}",
"for",
"(",
"i",
"=",
"n",
"-",
"1",
";",
"i",
">=",
"1",
";",
"i",
"-=",
"1",
")",
"{",
"j",
"=",
"Math",
".",
"floor",
"(",
"(",
"i",
"+",
"1",
")",
"*",
"Math",
".",
"random",
"(",
")",
")",
";",
"temp",
"=",
"res",
"[",
"i",
"]",
";",
"res",
"[",
"i",
"]",
"=",
"res",
"[",
"j",
"]",
";",
"res",
"[",
"j",
"]",
"=",
"temp",
";",
"}",
"return",
"res",
";",
"}"
] | Return an array with the numbers from 0 to n-1, in a random order
Uses Fisher Yates algorithm
Useful to get fair tests | [
"Return",
"an",
"array",
"with",
"the",
"numbers",
"from",
"0",
"to",
"n",
"-",
"1",
"in",
"a",
"random",
"order",
"Uses",
"Fisher",
"Yates",
"algorithm",
"Useful",
"to",
"get",
"fair",
"tests"
] | aa3302e5dcefa471431901a8f3fe63e532a5a7b2 | https://github.com/louischatriot/nedb/blob/aa3302e5dcefa471431901a8f3fe63e532a5a7b2/benchmarks/commonUtilities.js#L69-L84 |
5,997 | louischatriot/nedb | browser-version/out/nedb.js | Cursor | function Cursor (db, query, execFn) {
this.db = db;
this.query = query || {};
if (execFn) { this.execFn = execFn; }
} | javascript | function Cursor (db, query, execFn) {
this.db = db;
this.query = query || {};
if (execFn) { this.execFn = execFn; }
} | [
"function",
"Cursor",
"(",
"db",
",",
"query",
",",
"execFn",
")",
"{",
"this",
".",
"db",
"=",
"db",
";",
"this",
".",
"query",
"=",
"query",
"||",
"{",
"}",
";",
"if",
"(",
"execFn",
")",
"{",
"this",
".",
"execFn",
"=",
"execFn",
";",
"}",
"}"
] | Create a new cursor for this collection
@param {Datastore} db - The datastore this cursor is bound to
@param {Query} query - The query this cursor will operate on
@param {Function} execFn - Handler to be executed after cursor has found the results and before the callback passed to find/findOne/update/remove | [
"Create",
"a",
"new",
"cursor",
"for",
"this",
"collection"
] | aa3302e5dcefa471431901a8f3fe63e532a5a7b2 | https://github.com/louischatriot/nedb/blob/aa3302e5dcefa471431901a8f3fe63e532a5a7b2/browser-version/out/nedb.js#L795-L799 |
5,998 | louischatriot/nedb | browser-version/out/nedb.js | _AVLTree | function _AVLTree (options) {
options = options || {};
this.left = null;
this.right = null;
this.parent = options.parent !== undefined ? options.parent : null;
if (options.hasOwnProperty('key')) { this.key = options.key; }
this.data = options.hasOwnProperty('value') ? [options.value] : [];
this.unique = options.unique || false;
this.compareKeys = options.compareKeys || customUtils.defaultCompareKeysFunction;
this.checkValueEquality = options.checkValueEquality || customUtils.defaultCheckValueEquality;
} | javascript | function _AVLTree (options) {
options = options || {};
this.left = null;
this.right = null;
this.parent = options.parent !== undefined ? options.parent : null;
if (options.hasOwnProperty('key')) { this.key = options.key; }
this.data = options.hasOwnProperty('value') ? [options.value] : [];
this.unique = options.unique || false;
this.compareKeys = options.compareKeys || customUtils.defaultCompareKeysFunction;
this.checkValueEquality = options.checkValueEquality || customUtils.defaultCheckValueEquality;
} | [
"function",
"_AVLTree",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"left",
"=",
"null",
";",
"this",
".",
"right",
"=",
"null",
";",
"this",
".",
"parent",
"=",
"options",
".",
"parent",
"!==",
"undefined",
"?",
"options",
".",
"parent",
":",
"null",
";",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"'key'",
")",
")",
"{",
"this",
".",
"key",
"=",
"options",
".",
"key",
";",
"}",
"this",
".",
"data",
"=",
"options",
".",
"hasOwnProperty",
"(",
"'value'",
")",
"?",
"[",
"options",
".",
"value",
"]",
":",
"[",
"]",
";",
"this",
".",
"unique",
"=",
"options",
".",
"unique",
"||",
"false",
";",
"this",
".",
"compareKeys",
"=",
"options",
".",
"compareKeys",
"||",
"customUtils",
".",
"defaultCompareKeysFunction",
";",
"this",
".",
"checkValueEquality",
"=",
"options",
".",
"checkValueEquality",
"||",
"customUtils",
".",
"defaultCheckValueEquality",
";",
"}"
] | Constructor of the internal AVLTree
@param {Object} options Optional
@param {Boolean} options.unique Whether to enforce a 'unique' constraint on the key or not
@param {Key} options.key Initialize this BST's key with key
@param {Value} options.value Initialize this BST's data with [value]
@param {Function} options.compareKeys Initialize this BST's compareKeys | [
"Constructor",
"of",
"the",
"internal",
"AVLTree"
] | aa3302e5dcefa471431901a8f3fe63e532a5a7b2 | https://github.com/louischatriot/nedb/blob/aa3302e5dcefa471431901a8f3fe63e532a5a7b2/browser-version/out/nedb.js#L4393-L4405 |
5,999 | louischatriot/nedb | browser-version/out/nedb.js | append | function append (array, toAppend) {
var i;
for (i = 0; i < toAppend.length; i += 1) {
array.push(toAppend[i]);
}
} | javascript | function append (array, toAppend) {
var i;
for (i = 0; i < toAppend.length; i += 1) {
array.push(toAppend[i]);
}
} | [
"function",
"append",
"(",
"array",
",",
"toAppend",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"toAppend",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"array",
".",
"push",
"(",
"toAppend",
"[",
"i",
"]",
")",
";",
"}",
"}"
] | Append all elements in toAppend to array | [
"Append",
"all",
"elements",
"in",
"toAppend",
"to",
"array"
] | aa3302e5dcefa471431901a8f3fe63e532a5a7b2 | https://github.com/louischatriot/nedb/blob/aa3302e5dcefa471431901a8f3fe63e532a5a7b2/browser-version/out/nedb.js#L5151-L5157 |
Subsets and Splits