repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
AppGeo/cartodb | lib/compiler.js | where | function where() {
var wheres = this.grouped.where;
if (!wheres) {
return undefined;
}
var i = -1,
sql = [];
while (++i < wheres.length) {
var stmt = wheres[i];
var val = this[stmt.type](stmt);
if (val) {
if (sql.length === 0) {
sql[0] = 'where';
} else {
sql.push(stmt.bool);
}
sql.push(val);
}
}
return sql.length > 1 ? sql.join(' ') : '';
} | javascript | function where() {
var wheres = this.grouped.where;
if (!wheres) {
return undefined;
}
var i = -1,
sql = [];
while (++i < wheres.length) {
var stmt = wheres[i];
var val = this[stmt.type](stmt);
if (val) {
if (sql.length === 0) {
sql[0] = 'where';
} else {
sql.push(stmt.bool);
}
sql.push(val);
}
}
return sql.length > 1 ? sql.join(' ') : '';
} | [
"function",
"where",
"(",
")",
"{",
"var",
"wheres",
"=",
"this",
".",
"grouped",
".",
"where",
";",
"if",
"(",
"!",
"wheres",
")",
"{",
"return",
"undefined",
";",
"}",
"var",
"i",
"=",
"-",
"1",
",",
"sql",
"=",
"[",
"]",
";",
"while",
"(",
"++",
"i",
"<",
"wheres",
".",
"length",
")",
"{",
"var",
"stmt",
"=",
"wheres",
"[",
"i",
"]",
";",
"var",
"val",
"=",
"this",
"[",
"stmt",
".",
"type",
"]",
"(",
"stmt",
")",
";",
"if",
"(",
"val",
")",
"{",
"if",
"(",
"sql",
".",
"length",
"===",
"0",
")",
"{",
"sql",
"[",
"0",
"]",
"=",
"'where'",
";",
"}",
"else",
"{",
"sql",
".",
"push",
"(",
"stmt",
".",
"bool",
")",
";",
"}",
"sql",
".",
"push",
"(",
"val",
")",
";",
"}",
"}",
"return",
"sql",
".",
"length",
">",
"1",
"?",
"sql",
".",
"join",
"(",
"' '",
")",
":",
"''",
";",
"}"
] | Compiles all `where` statements on the query. | [
"Compiles",
"all",
"where",
"statements",
"on",
"the",
"query",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L211-L231 | train |
AppGeo/cartodb | lib/compiler.js | having | function having() {
var havings = this.grouped.having;
if (!havings) {
return '';
}
var sql = ['having'];
for (var i = 0, l = havings.length; i < l; i++) {
var str = '',
s = havings[i];
if (i !== 0) {
str = s.bool + ' ';
}
if (s.type === 'havingBasic') {
sql.push(str + this.formatter.columnize(s.column) + ' ' + this.formatter.operator(s.operator) + ' ' + this.formatter.parameter(s.value));
} else {
if (s.type === 'whereWrapped') {
var val = this.whereWrapped(s);
if (val) {
sql.push(val);
}
} else {
sql.push(str + this.formatter.unwrapRaw(s.value));
}
}
}
return sql.length > 1 ? sql.join(' ') : '';
} | javascript | function having() {
var havings = this.grouped.having;
if (!havings) {
return '';
}
var sql = ['having'];
for (var i = 0, l = havings.length; i < l; i++) {
var str = '',
s = havings[i];
if (i !== 0) {
str = s.bool + ' ';
}
if (s.type === 'havingBasic') {
sql.push(str + this.formatter.columnize(s.column) + ' ' + this.formatter.operator(s.operator) + ' ' + this.formatter.parameter(s.value));
} else {
if (s.type === 'whereWrapped') {
var val = this.whereWrapped(s);
if (val) {
sql.push(val);
}
} else {
sql.push(str + this.formatter.unwrapRaw(s.value));
}
}
}
return sql.length > 1 ? sql.join(' ') : '';
} | [
"function",
"having",
"(",
")",
"{",
"var",
"havings",
"=",
"this",
".",
"grouped",
".",
"having",
";",
"if",
"(",
"!",
"havings",
")",
"{",
"return",
"''",
";",
"}",
"var",
"sql",
"=",
"[",
"'having'",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"havings",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"var",
"str",
"=",
"''",
",",
"s",
"=",
"havings",
"[",
"i",
"]",
";",
"if",
"(",
"i",
"!==",
"0",
")",
"{",
"str",
"=",
"s",
".",
"bool",
"+",
"' '",
";",
"}",
"if",
"(",
"s",
".",
"type",
"===",
"'havingBasic'",
")",
"{",
"sql",
".",
"push",
"(",
"str",
"+",
"this",
".",
"formatter",
".",
"columnize",
"(",
"s",
".",
"column",
")",
"+",
"' '",
"+",
"this",
".",
"formatter",
".",
"operator",
"(",
"s",
".",
"operator",
")",
"+",
"' '",
"+",
"this",
".",
"formatter",
".",
"parameter",
"(",
"s",
".",
"value",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"s",
".",
"type",
"===",
"'whereWrapped'",
")",
"{",
"var",
"val",
"=",
"this",
".",
"whereWrapped",
"(",
"s",
")",
";",
"if",
"(",
"val",
")",
"{",
"sql",
".",
"push",
"(",
"val",
")",
";",
"}",
"}",
"else",
"{",
"sql",
".",
"push",
"(",
"str",
"+",
"this",
".",
"formatter",
".",
"unwrapRaw",
"(",
"s",
".",
"value",
")",
")",
";",
"}",
"}",
"}",
"return",
"sql",
".",
"length",
">",
"1",
"?",
"sql",
".",
"join",
"(",
"' '",
")",
":",
"''",
";",
"}"
] | Compiles the `having` statements. | [
"Compiles",
"the",
"having",
"statements",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L242-L268 | train |
AppGeo/cartodb | lib/compiler.js | _union | function _union() {
var onlyUnions = this.onlyUnions();
var unions = this.grouped.union;
if (!unions) {
return '';
}
var sql = '';
for (var i = 0, l = unions.length; i < l; i++) {
var union = unions[i];
if (i > 0) {
sql += ' ';
}
if (i > 0 || !onlyUnions) {
sql += union.clause + ' ';
}
var statement = this.formatter.rawOrFn(union.value);
if (statement) {
if (union.wrap) {
sql += '(';
}
sql += statement;
if (union.wrap) {
sql += ')';
}
}
}
return sql;
} | javascript | function _union() {
var onlyUnions = this.onlyUnions();
var unions = this.grouped.union;
if (!unions) {
return '';
}
var sql = '';
for (var i = 0, l = unions.length; i < l; i++) {
var union = unions[i];
if (i > 0) {
sql += ' ';
}
if (i > 0 || !onlyUnions) {
sql += union.clause + ' ';
}
var statement = this.formatter.rawOrFn(union.value);
if (statement) {
if (union.wrap) {
sql += '(';
}
sql += statement;
if (union.wrap) {
sql += ')';
}
}
}
return sql;
} | [
"function",
"_union",
"(",
")",
"{",
"var",
"onlyUnions",
"=",
"this",
".",
"onlyUnions",
"(",
")",
";",
"var",
"unions",
"=",
"this",
".",
"grouped",
".",
"union",
";",
"if",
"(",
"!",
"unions",
")",
"{",
"return",
"''",
";",
"}",
"var",
"sql",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"unions",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"var",
"union",
"=",
"unions",
"[",
"i",
"]",
";",
"if",
"(",
"i",
">",
"0",
")",
"{",
"sql",
"+=",
"' '",
";",
"}",
"if",
"(",
"i",
">",
"0",
"||",
"!",
"onlyUnions",
")",
"{",
"sql",
"+=",
"union",
".",
"clause",
"+",
"' '",
";",
"}",
"var",
"statement",
"=",
"this",
".",
"formatter",
".",
"rawOrFn",
"(",
"union",
".",
"value",
")",
";",
"if",
"(",
"statement",
")",
"{",
"if",
"(",
"union",
".",
"wrap",
")",
"{",
"sql",
"+=",
"'('",
";",
"}",
"sql",
"+=",
"statement",
";",
"if",
"(",
"union",
".",
"wrap",
")",
"{",
"sql",
"+=",
"')'",
";",
"}",
"}",
"}",
"return",
"sql",
";",
"}"
] | Compile the "union" queries attached to the main query. | [
"Compile",
"the",
"union",
"queries",
"attached",
"to",
"the",
"main",
"query",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L271-L298 | train |
AppGeo/cartodb | lib/compiler.js | del | function del() {
// Make sure tableName is processed by the formatter first.
var tableName = this.tableName;
var wheres = this.where();
var sql = 'delete from ' + tableName + (wheres ? ' ' + wheres : '');
var returning = this.single.returning;
return {
sql: sql + this._returning(returning),
returning: returning
};
} | javascript | function del() {
// Make sure tableName is processed by the formatter first.
var tableName = this.tableName;
var wheres = this.where();
var sql = 'delete from ' + tableName + (wheres ? ' ' + wheres : '');
var returning = this.single.returning;
return {
sql: sql + this._returning(returning),
returning: returning
};
} | [
"function",
"del",
"(",
")",
"{",
"var",
"tableName",
"=",
"this",
".",
"tableName",
";",
"var",
"wheres",
"=",
"this",
".",
"where",
"(",
")",
";",
"var",
"sql",
"=",
"'delete from '",
"+",
"tableName",
"+",
"(",
"wheres",
"?",
"' '",
"+",
"wheres",
":",
"''",
")",
";",
"var",
"returning",
"=",
"this",
".",
"single",
".",
"returning",
";",
"return",
"{",
"sql",
":",
"sql",
"+",
"this",
".",
"_returning",
"(",
"returning",
")",
",",
"returning",
":",
"returning",
"}",
";",
"}"
] | Compiles a `delete` query. | [
"Compiles",
"a",
"delete",
"query",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L322-L332 | train |
AppGeo/cartodb | lib/compiler.js | _counter | function _counter() {
var counter = this.single.counter;
var toUpdate = {};
toUpdate[counter.column] = this.client.raw(this.formatter.wrap(counter.column) + ' ' + (counter.symbol || '+') + ' ' + counter.amount);
this.single.update = toUpdate;
return this.update();
} | javascript | function _counter() {
var counter = this.single.counter;
var toUpdate = {};
toUpdate[counter.column] = this.client.raw(this.formatter.wrap(counter.column) + ' ' + (counter.symbol || '+') + ' ' + counter.amount);
this.single.update = toUpdate;
return this.update();
} | [
"function",
"_counter",
"(",
")",
"{",
"var",
"counter",
"=",
"this",
".",
"single",
".",
"counter",
";",
"var",
"toUpdate",
"=",
"{",
"}",
";",
"toUpdate",
"[",
"counter",
".",
"column",
"]",
"=",
"this",
".",
"client",
".",
"raw",
"(",
"this",
".",
"formatter",
".",
"wrap",
"(",
"counter",
".",
"column",
")",
"+",
"' '",
"+",
"(",
"counter",
".",
"symbol",
"||",
"'+'",
")",
"+",
"' '",
"+",
"counter",
".",
"amount",
")",
";",
"this",
".",
"single",
".",
"update",
"=",
"toUpdate",
";",
"return",
"this",
".",
"update",
"(",
")",
";",
"}"
] | Compile the "counter". | [
"Compile",
"the",
"counter",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L351-L357 | train |
AppGeo/cartodb | lib/compiler.js | whereBasic | function whereBasic(statement) {
return this._not(statement, '') + this.formatter.wrap(statement.column) + ' ' + this.formatter.operator(statement.operator) + ' ' + this.formatter.parameter(statement.value);
} | javascript | function whereBasic(statement) {
return this._not(statement, '') + this.formatter.wrap(statement.column) + ' ' + this.formatter.operator(statement.operator) + ' ' + this.formatter.parameter(statement.value);
} | [
"function",
"whereBasic",
"(",
"statement",
")",
"{",
"return",
"this",
".",
"_not",
"(",
"statement",
",",
"''",
")",
"+",
"this",
".",
"formatter",
".",
"wrap",
"(",
"statement",
".",
"column",
")",
"+",
"' '",
"+",
"this",
".",
"formatter",
".",
"operator",
"(",
"statement",
".",
"operator",
")",
"+",
"' '",
"+",
"this",
".",
"formatter",
".",
"parameter",
"(",
"statement",
".",
"value",
")",
";",
"}"
] | Compiles a basic "where" clause. | [
"Compiles",
"a",
"basic",
"where",
"clause",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L387-L389 | train |
AppGeo/cartodb | lib/compiler.js | _prepUpdate | function _prepUpdate(data) {
var vals = [];
var sorted = Object.keys(data).sort();
var i = -1;
while (++i < sorted.length) {
vals.push(this.formatter.wrap(sorted[i]) + ' = ' + this.formatter.parameter(data[sorted[i]]));
}
return vals;
} | javascript | function _prepUpdate(data) {
var vals = [];
var sorted = Object.keys(data).sort();
var i = -1;
while (++i < sorted.length) {
vals.push(this.formatter.wrap(sorted[i]) + ' = ' + this.formatter.parameter(data[sorted[i]]));
}
return vals;
} | [
"function",
"_prepUpdate",
"(",
"data",
")",
"{",
"var",
"vals",
"=",
"[",
"]",
";",
"var",
"sorted",
"=",
"Object",
".",
"keys",
"(",
"data",
")",
".",
"sort",
"(",
")",
";",
"var",
"i",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"i",
"<",
"sorted",
".",
"length",
")",
"{",
"vals",
".",
"push",
"(",
"this",
".",
"formatter",
".",
"wrap",
"(",
"sorted",
"[",
"i",
"]",
")",
"+",
"' = '",
"+",
"this",
".",
"formatter",
".",
"parameter",
"(",
"data",
"[",
"sorted",
"[",
"i",
"]",
"]",
")",
")",
";",
"}",
"return",
"vals",
";",
"}"
] | "Preps" the update. | [
"Preps",
"the",
"update",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L453-L461 | train |
AppGeo/cartodb | lib/compiler.js | _groupsOrders | function _groupsOrders(type) {
var items = this.grouped[type];
if (!items) {
return '';
}
var formatter = this.formatter;
var sql = items.map(function (item) {
return (item.value instanceof Raw ? formatter.unwrapRaw(item.value) : formatter.columnize(item.value)) + (type === 'order' && item.type !== 'orderByRaw' ? ' ' + formatter.direction(item.direction) : '');
});
return sql.length ? type + ' by ' + sql.join(', ') : '';
} | javascript | function _groupsOrders(type) {
var items = this.grouped[type];
if (!items) {
return '';
}
var formatter = this.formatter;
var sql = items.map(function (item) {
return (item.value instanceof Raw ? formatter.unwrapRaw(item.value) : formatter.columnize(item.value)) + (type === 'order' && item.type !== 'orderByRaw' ? ' ' + formatter.direction(item.direction) : '');
});
return sql.length ? type + ' by ' + sql.join(', ') : '';
} | [
"function",
"_groupsOrders",
"(",
"type",
")",
"{",
"var",
"items",
"=",
"this",
".",
"grouped",
"[",
"type",
"]",
";",
"if",
"(",
"!",
"items",
")",
"{",
"return",
"''",
";",
"}",
"var",
"formatter",
"=",
"this",
".",
"formatter",
";",
"var",
"sql",
"=",
"items",
".",
"map",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"(",
"item",
".",
"value",
"instanceof",
"Raw",
"?",
"formatter",
".",
"unwrapRaw",
"(",
"item",
".",
"value",
")",
":",
"formatter",
".",
"columnize",
"(",
"item",
".",
"value",
")",
")",
"+",
"(",
"type",
"===",
"'order'",
"&&",
"item",
".",
"type",
"!==",
"'orderByRaw'",
"?",
"' '",
"+",
"formatter",
".",
"direction",
"(",
"item",
".",
"direction",
")",
":",
"''",
")",
";",
"}",
")",
";",
"return",
"sql",
".",
"length",
"?",
"type",
"+",
"' by '",
"+",
"sql",
".",
"join",
"(",
"', '",
")",
":",
"''",
";",
"}"
] | Compiles the `order by` statements. | [
"Compiles",
"the",
"order",
"by",
"statements",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L464-L474 | train |
AppGeo/cartodb | lib/compiler.js | columnInfo | function columnInfo() {
var column = this.single.columnInfo;
return {
sql: 'select * from information_schema.columns where table_name = ? and table_catalog = ?',
bindings: [this.single.table, this.client.database()],
output: function output(resp) {
var out = resp.rows.reduce(function (columns, val) {
columns[val.column_name] = {
type: val.data_type,
maxLength: val.character_maximum_length,
nullable: val.is_nullable === 'YES',
defaultValue: val.column_default
};
return columns;
}, {});
return column && out[column] || out;
}
};
} | javascript | function columnInfo() {
var column = this.single.columnInfo;
return {
sql: 'select * from information_schema.columns where table_name = ? and table_catalog = ?',
bindings: [this.single.table, this.client.database()],
output: function output(resp) {
var out = resp.rows.reduce(function (columns, val) {
columns[val.column_name] = {
type: val.data_type,
maxLength: val.character_maximum_length,
nullable: val.is_nullable === 'YES',
defaultValue: val.column_default
};
return columns;
}, {});
return column && out[column] || out;
}
};
} | [
"function",
"columnInfo",
"(",
")",
"{",
"var",
"column",
"=",
"this",
".",
"single",
".",
"columnInfo",
";",
"return",
"{",
"sql",
":",
"'select * from information_schema.columns where table_name = ? and table_catalog = ?'",
",",
"bindings",
":",
"[",
"this",
".",
"single",
".",
"table",
",",
"this",
".",
"client",
".",
"database",
"(",
")",
"]",
",",
"output",
":",
"function",
"output",
"(",
"resp",
")",
"{",
"var",
"out",
"=",
"resp",
".",
"rows",
".",
"reduce",
"(",
"function",
"(",
"columns",
",",
"val",
")",
"{",
"columns",
"[",
"val",
".",
"column_name",
"]",
"=",
"{",
"type",
":",
"val",
".",
"data_type",
",",
"maxLength",
":",
"val",
".",
"character_maximum_length",
",",
"nullable",
":",
"val",
".",
"is_nullable",
"===",
"'YES'",
",",
"defaultValue",
":",
"val",
".",
"column_default",
"}",
";",
"return",
"columns",
";",
"}",
",",
"{",
"}",
")",
";",
"return",
"column",
"&&",
"out",
"[",
"column",
"]",
"||",
"out",
";",
"}",
"}",
";",
"}"
] | Compiles a columnInfo query | [
"Compiles",
"a",
"columnInfo",
"query"
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L489-L507 | train |
crcn/celeri | lib/plugins/command.route.js | fixRoute | function fixRoute(route) {
//protect special chars while we replace
return route.replace(/\s*OR\s*/g,'__OR__').
replace(/\s*->\s*/g,'__->__').
replace(/[\s\t\n]+/g,'/').
replace(/__/g,' ');
} | javascript | function fixRoute(route) {
//protect special chars while we replace
return route.replace(/\s*OR\s*/g,'__OR__').
replace(/\s*->\s*/g,'__->__').
replace(/[\s\t\n]+/g,'/').
replace(/__/g,' ');
} | [
"function",
"fixRoute",
"(",
"route",
")",
"{",
"return",
"route",
".",
"replace",
"(",
"/",
"\\s*OR\\s*",
"/",
"g",
",",
"'__OR__'",
")",
".",
"replace",
"(",
"/",
"\\s*->\\s*",
"/",
"g",
",",
"'__->__'",
")",
".",
"replace",
"(",
"/",
"[\\s\\t\\n]+",
"/",
"g",
",",
"'/'",
")",
".",
"replace",
"(",
"/",
"__",
"/",
"g",
",",
"' '",
")",
";",
"}"
] | changes for beanpole prohibit the use of whitespace | [
"changes",
"for",
"beanpole",
"prohibit",
"the",
"use",
"of",
"whitespace"
] | f10471478b9119485c7c72a49015e22ec4339e29 | https://github.com/crcn/celeri/blob/f10471478b9119485c7c72a49015e22ec4339e29/lib/plugins/command.route.js#L9-L16 | train |
dirkbonhomme/infinite-timeout | lib/timeout.js | function(callback, timeout){
var id = index++;
if(timeout > MAX_INT){
timeouts[id] = setTimeout(set.bind(undefined, callback, timeout - MAX_INT), MAX_INT);
}else{
if(timeout < 0) timeout = 0;
timeouts[id] = setTimeout(function(){
delete timeouts[id];
callback();
}, timeout);
}
return id;
} | javascript | function(callback, timeout){
var id = index++;
if(timeout > MAX_INT){
timeouts[id] = setTimeout(set.bind(undefined, callback, timeout - MAX_INT), MAX_INT);
}else{
if(timeout < 0) timeout = 0;
timeouts[id] = setTimeout(function(){
delete timeouts[id];
callback();
}, timeout);
}
return id;
} | [
"function",
"(",
"callback",
",",
"timeout",
")",
"{",
"var",
"id",
"=",
"index",
"++",
";",
"if",
"(",
"timeout",
">",
"MAX_INT",
")",
"{",
"timeouts",
"[",
"id",
"]",
"=",
"setTimeout",
"(",
"set",
".",
"bind",
"(",
"undefined",
",",
"callback",
",",
"timeout",
"-",
"MAX_INT",
")",
",",
"MAX_INT",
")",
";",
"}",
"else",
"{",
"if",
"(",
"timeout",
"<",
"0",
")",
"timeout",
"=",
"0",
";",
"timeouts",
"[",
"id",
"]",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"delete",
"timeouts",
"[",
"id",
"]",
";",
"callback",
"(",
")",
";",
"}",
",",
"timeout",
")",
";",
"}",
"return",
"id",
";",
"}"
] | Set new timeout | [
"Set",
"new",
"timeout"
] | adf33ec4f94feb2226fcae4d0eb80e808292d7a7 | https://github.com/dirkbonhomme/infinite-timeout/blob/adf33ec4f94feb2226fcae4d0eb80e808292d7a7/lib/timeout.js#L7-L19 | train |
|
rootsdev/gedcomx-js | src/core/SourceDescription.js | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof SourceDescription)){
return new SourceDescription(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(SourceDescription.isInstance(json)){
return json;
}
this.init(json);
} | javascript | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof SourceDescription)){
return new SourceDescription(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(SourceDescription.isInstance(json)){
return json;
}
this.init(json);
} | [
"function",
"(",
"json",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"SourceDescription",
")",
")",
"{",
"return",
"new",
"SourceDescription",
"(",
"json",
")",
";",
"}",
"if",
"(",
"SourceDescription",
".",
"isInstance",
"(",
"json",
")",
")",
"{",
"return",
"json",
";",
"}",
"this",
".",
"init",
"(",
"json",
")",
";",
"}"
] | A description of a source.
@see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#source-description|GEDCOM X JSON Spec}
@class
@extends ExtensibleData
@apram {Object} [json] | [
"A",
"description",
"of",
"a",
"source",
"."
] | 08b2fcde96f1e301c78561bfb7a8b0cac606e26e | https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/SourceDescription.js#L13-L26 | train |
|
apparebit/js-junction | packages/proact/vdom/component.js | from | function from(renderFn, name = renderFn.name) {
if (typeof name === 'function') {
[renderFn, name] = [name, renderFn];
} else if (typeof renderFn !== 'function') {
throw InvalidArgType({ renderFn }, 'a function');
}
name = String(name);
if (!name) {
throw InvalidArgValue({ name }, 'should not be empty');
}
function RenderFunction(...args) {
if (!new.target) return new RenderFunction(...args);
// 1st argument may be constructor itself to (redundantly) capture identity.
if (args[0] === RenderFunction) args.shift();
// Delegate processing of properties to Node.
apply(Node, this, args);
}
// The isViewComponent, toStringTag, and provideContext properties are the
// same for all render function components and could thus be moved into a
// shared prototype. While that may reduce memory pressure, it also increases
// the length of the prototype chain and thus property lookup latency.
const RenderFunctionPrototype = create(NodePrototype, {
constructor: { configurable, value: RenderFunction },
isViewComponent: { configurable, value: true }, // Flag to detect view component type.
[toStringTag]: { configurable, value: 'Proact.Component' },
name: { configurable, enumerable, value: name },
render: { configurable, value: renderFn },
provideContext: { configurable, value: provideContext },
});
defineProperties(RenderFunction, {
prototype: { value: RenderFunctionPrototype },
name: { configurable, enumerable, value: name },
});
return RenderFunction;
} | javascript | function from(renderFn, name = renderFn.name) {
if (typeof name === 'function') {
[renderFn, name] = [name, renderFn];
} else if (typeof renderFn !== 'function') {
throw InvalidArgType({ renderFn }, 'a function');
}
name = String(name);
if (!name) {
throw InvalidArgValue({ name }, 'should not be empty');
}
function RenderFunction(...args) {
if (!new.target) return new RenderFunction(...args);
// 1st argument may be constructor itself to (redundantly) capture identity.
if (args[0] === RenderFunction) args.shift();
// Delegate processing of properties to Node.
apply(Node, this, args);
}
// The isViewComponent, toStringTag, and provideContext properties are the
// same for all render function components and could thus be moved into a
// shared prototype. While that may reduce memory pressure, it also increases
// the length of the prototype chain and thus property lookup latency.
const RenderFunctionPrototype = create(NodePrototype, {
constructor: { configurable, value: RenderFunction },
isViewComponent: { configurable, value: true }, // Flag to detect view component type.
[toStringTag]: { configurable, value: 'Proact.Component' },
name: { configurable, enumerable, value: name },
render: { configurable, value: renderFn },
provideContext: { configurable, value: provideContext },
});
defineProperties(RenderFunction, {
prototype: { value: RenderFunctionPrototype },
name: { configurable, enumerable, value: name },
});
return RenderFunction;
} | [
"function",
"from",
"(",
"renderFn",
",",
"name",
"=",
"renderFn",
".",
"name",
")",
"{",
"if",
"(",
"typeof",
"name",
"===",
"'function'",
")",
"{",
"[",
"renderFn",
",",
"name",
"]",
"=",
"[",
"name",
",",
"renderFn",
"]",
";",
"}",
"else",
"if",
"(",
"typeof",
"renderFn",
"!==",
"'function'",
")",
"{",
"throw",
"InvalidArgType",
"(",
"{",
"renderFn",
"}",
",",
"'a function'",
")",
";",
"}",
"name",
"=",
"String",
"(",
"name",
")",
";",
"if",
"(",
"!",
"name",
")",
"{",
"throw",
"InvalidArgValue",
"(",
"{",
"name",
"}",
",",
"'should not be empty'",
")",
";",
"}",
"function",
"RenderFunction",
"(",
"...",
"args",
")",
"{",
"if",
"(",
"!",
"new",
".",
"target",
")",
"return",
"new",
"RenderFunction",
"(",
"...",
"args",
")",
";",
"if",
"(",
"args",
"[",
"0",
"]",
"===",
"RenderFunction",
")",
"args",
".",
"shift",
"(",
")",
";",
"apply",
"(",
"Node",
",",
"this",
",",
"args",
")",
";",
"}",
"const",
"RenderFunctionPrototype",
"=",
"create",
"(",
"NodePrototype",
",",
"{",
"constructor",
":",
"{",
"configurable",
",",
"value",
":",
"RenderFunction",
"}",
",",
"isViewComponent",
":",
"{",
"configurable",
",",
"value",
":",
"true",
"}",
",",
"[",
"toStringTag",
"]",
":",
"{",
"configurable",
",",
"value",
":",
"'Proact.Component'",
"}",
",",
"name",
":",
"{",
"configurable",
",",
"enumerable",
",",
"value",
":",
"name",
"}",
",",
"render",
":",
"{",
"configurable",
",",
"value",
":",
"renderFn",
"}",
",",
"provideContext",
":",
"{",
"configurable",
",",
"value",
":",
"provideContext",
"}",
",",
"}",
")",
";",
"defineProperties",
"(",
"RenderFunction",
",",
"{",
"prototype",
":",
"{",
"value",
":",
"RenderFunctionPrototype",
"}",
",",
"name",
":",
"{",
"configurable",
",",
"enumerable",
",",
"value",
":",
"name",
"}",
",",
"}",
")",
";",
"return",
"RenderFunction",
";",
"}"
] | Create a functional component with the given render function and name. For
named functions, the name may be omitted to avoid repetition. The name may
also be specified before the render function to accommodate arrow functions
while also optimizing for readability. | [
"Create",
"a",
"functional",
"component",
"with",
"the",
"given",
"render",
"function",
"and",
"name",
".",
"For",
"named",
"functions",
"the",
"name",
"may",
"be",
"omitted",
"to",
"avoid",
"repetition",
".",
"The",
"name",
"may",
"also",
"be",
"specified",
"before",
"the",
"render",
"function",
"to",
"accommodate",
"arrow",
"functions",
"while",
"also",
"optimizing",
"for",
"readability",
"."
] | 240b15961c35f19c3a1effd9df51e0bf8e0bbffc | https://github.com/apparebit/js-junction/blob/240b15961c35f19c3a1effd9df51e0bf8e0bbffc/packages/proact/vdom/component.js#L33-L74 | train |
codeactual/apidox | lib/apidox/index.js | ApiDox | function ApiDox() {
this.settings = {
input: '',
inputText: null,
inputTitle: '',
output: '',
fullSourceDescription: false
};
this.anchors = {};
this.comments = [];
this.curSection = null;
this.fileComment = {};
this.lines = [];
this.params = {};
this.returns = {};
this.sees = [];
this.toc = [];
this.throws = [];
} | javascript | function ApiDox() {
this.settings = {
input: '',
inputText: null,
inputTitle: '',
output: '',
fullSourceDescription: false
};
this.anchors = {};
this.comments = [];
this.curSection = null;
this.fileComment = {};
this.lines = [];
this.params = {};
this.returns = {};
this.sees = [];
this.toc = [];
this.throws = [];
} | [
"function",
"ApiDox",
"(",
")",
"{",
"this",
".",
"settings",
"=",
"{",
"input",
":",
"''",
",",
"inputText",
":",
"null",
",",
"inputTitle",
":",
"''",
",",
"output",
":",
"''",
",",
"fullSourceDescription",
":",
"false",
"}",
";",
"this",
".",
"anchors",
"=",
"{",
"}",
";",
"this",
".",
"comments",
"=",
"[",
"]",
";",
"this",
".",
"curSection",
"=",
"null",
";",
"this",
".",
"fileComment",
"=",
"{",
"}",
";",
"this",
".",
"lines",
"=",
"[",
"]",
";",
"this",
".",
"params",
"=",
"{",
"}",
";",
"this",
".",
"returns",
"=",
"{",
"}",
";",
"this",
".",
"sees",
"=",
"[",
"]",
";",
"this",
".",
"toc",
"=",
"[",
"]",
";",
"this",
".",
"throws",
"=",
"[",
"]",
";",
"}"
] | ApiDox constructor.
Usage:
var dox = require('apidox').create();
var markdown = dox
.set('input', '/path/to/source.js')
.set('output', '/path/to/output.md')
.parse()
.convert();
Configuration:
- `{string} input` Source file to read
- `{string} inputText` Alternative to `input`
- `{string|boolean} [inputTitle=input]` Customize `Source: ...` link text
- `false`: Omit `Source: ...` entirely from markdown
- `string`: Set link text (does not affect link URL)
- `{string} output` Markdown file to write
Properties:
- `{object} anchors` Keys are object paths which already have anchors
- For duplicate prevention
- `{array} comments` Filtered dox-provided objects to convert
- `{string curSection` Current section being converted, ex. 'Klass.prototype'.
- `{object} fileComment` First dox-provided comment found in the file
- `{array} lines` Markdown lines
- `{object} params` Collected `@param` meta indexed by method name
- `{array} types` Type names
- `{string} description` First line
- `{array} overflow` Additional lines
- `{object} returns` Collected `@return` metadata indexed by method name
- `{array} types` Type names
- `{string} description` First line
- `{array} overflow` Additional lines
- `{array} sees` Collected `@see` lines
- `{array} toc` Collected table-of-contents metadata objects
- `{string} title` Link title
- `{string} url` Link URL
- `{array} throws` Collected `@throws` lines | [
"ApiDox",
"constructor",
"."
] | 3dd28222035d511bd210f518694b9d3cfdbf81ed | https://github.com/codeactual/apidox/blob/3dd28222035d511bd210f518694b9d3cfdbf81ed/lib/apidox/index.js#L90-L108 | train |
angie-framework/angie | src/Server.js | forceEnd | function forceEnd(path, response) {
// Send a custom response for gateway timeout
new $CustomResponse().head(504, null, {
'Content-Type': 'text/html'
}).writeSync(`<h1>${RESPONSE_HEADER_MESSAGES[ 504 ]}</h1>`);
// Log something
$LogProvider.error(path, response._header);
// End the response
end(response);
} | javascript | function forceEnd(path, response) {
// Send a custom response for gateway timeout
new $CustomResponse().head(504, null, {
'Content-Type': 'text/html'
}).writeSync(`<h1>${RESPONSE_HEADER_MESSAGES[ 504 ]}</h1>`);
// Log something
$LogProvider.error(path, response._header);
// End the response
end(response);
} | [
"function",
"forceEnd",
"(",
"path",
",",
"response",
")",
"{",
"new",
"$CustomResponse",
"(",
")",
".",
"head",
"(",
"504",
",",
"null",
",",
"{",
"'Content-Type'",
":",
"'text/html'",
"}",
")",
".",
"writeSync",
"(",
"`",
"${",
"RESPONSE_HEADER_MESSAGES",
"[",
"504",
"]",
"}",
"`",
")",
";",
"$LogProvider",
".",
"error",
"(",
"path",
",",
"response",
".",
"_header",
")",
";",
"end",
"(",
"response",
")",
";",
"}"
] | Force an ended response with a timeout | [
"Force",
"an",
"ended",
"response",
"with",
"a",
"timeout"
] | 7d0793f6125e60e0473b17ffd40305d6d6fdbc12 | https://github.com/angie-framework/angie/blob/7d0793f6125e60e0473b17ffd40305d6d6fdbc12/src/Server.js#L325-L337 | train |
edwardhotchkiss/github3 | lib/github3.js | function(opts){
//defaults
opts = opts || {};
this.username = opts.username || '';
this.password = opts.password || '';
// oAuth Token
this.accessToken = opts.accessToken || '';
// API Rate Limit Details
this.rateLimit = 5000;
this.rateLimitRemaining = this.rateLimit; //rateLimitRemaining starts as rateLimit
} | javascript | function(opts){
//defaults
opts = opts || {};
this.username = opts.username || '';
this.password = opts.password || '';
// oAuth Token
this.accessToken = opts.accessToken || '';
// API Rate Limit Details
this.rateLimit = 5000;
this.rateLimitRemaining = this.rateLimit; //rateLimitRemaining starts as rateLimit
} | [
"function",
"(",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"username",
"=",
"opts",
".",
"username",
"||",
"''",
";",
"this",
".",
"password",
"=",
"opts",
".",
"password",
"||",
"''",
";",
"this",
".",
"accessToken",
"=",
"opts",
".",
"accessToken",
"||",
"''",
";",
"this",
".",
"rateLimit",
"=",
"5000",
";",
"this",
".",
"rateLimitRemaining",
"=",
"this",
".",
"rateLimit",
";",
"}"
] | Sets credentials for GitHub access.
@class Github3
@constructor
@param {Object} opts
{String} .username GitHub username
{String} .password GitHub password
{Token } .accessToken GitHub oAuth Token | [
"Sets",
"credentials",
"for",
"GitHub",
"access",
"."
] | ad6cf10b63b2b92a58d0517ffab4c0af692b1db9 | https://github.com/edwardhotchkiss/github3/blob/ad6cf10b63b2b92a58d0517ffab4c0af692b1db9/lib/github3.js#L24-L34 | train |
|
jhermsmeier/node-async-emitter | emitter.js | function( type, handler ) {
if( handler === void 0 || handler === null )
throw new Error( 'Missing argument "handler"' )
if( typeof handler !== 'function' && typeof handler.handleEvent !== 'function' )
throw new TypeError( 'Handler must be a function.' )
this._events[ type ] ?
this._events[ type ].push( handler ) :
this._events[ type ] = [ handler ]
if( Emitter.warn && this._events[ type ].length > this._maxListeners ) {
if( this._maxListeners > 0 && !this._memLeakDetected ) {
this._memLeakDetected = true
console.warn(
'WARNING: Possible event emitter memory leak detected.',
this._events[ type ].length, 'event handlers added.',
'Use emitter.setMaxListeners() to increase the threshold.'
)
console.trace()
}
}
return this
} | javascript | function( type, handler ) {
if( handler === void 0 || handler === null )
throw new Error( 'Missing argument "handler"' )
if( typeof handler !== 'function' && typeof handler.handleEvent !== 'function' )
throw new TypeError( 'Handler must be a function.' )
this._events[ type ] ?
this._events[ type ].push( handler ) :
this._events[ type ] = [ handler ]
if( Emitter.warn && this._events[ type ].length > this._maxListeners ) {
if( this._maxListeners > 0 && !this._memLeakDetected ) {
this._memLeakDetected = true
console.warn(
'WARNING: Possible event emitter memory leak detected.',
this._events[ type ].length, 'event handlers added.',
'Use emitter.setMaxListeners() to increase the threshold.'
)
console.trace()
}
}
return this
} | [
"function",
"(",
"type",
",",
"handler",
")",
"{",
"if",
"(",
"handler",
"===",
"void",
"0",
"||",
"handler",
"===",
"null",
")",
"throw",
"new",
"Error",
"(",
"'Missing argument \"handler\"'",
")",
"if",
"(",
"typeof",
"handler",
"!==",
"'function'",
"&&",
"typeof",
"handler",
".",
"handleEvent",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'Handler must be a function.'",
")",
"this",
".",
"_events",
"[",
"type",
"]",
"?",
"this",
".",
"_events",
"[",
"type",
"]",
".",
"push",
"(",
"handler",
")",
":",
"this",
".",
"_events",
"[",
"type",
"]",
"=",
"[",
"handler",
"]",
"if",
"(",
"Emitter",
".",
"warn",
"&&",
"this",
".",
"_events",
"[",
"type",
"]",
".",
"length",
">",
"this",
".",
"_maxListeners",
")",
"{",
"if",
"(",
"this",
".",
"_maxListeners",
">",
"0",
"&&",
"!",
"this",
".",
"_memLeakDetected",
")",
"{",
"this",
".",
"_memLeakDetected",
"=",
"true",
"console",
".",
"warn",
"(",
"'WARNING: Possible event emitter memory leak detected.'",
",",
"this",
".",
"_events",
"[",
"type",
"]",
".",
"length",
",",
"'event handlers added.'",
",",
"'Use emitter.setMaxListeners() to increase the threshold.'",
")",
"console",
".",
"trace",
"(",
")",
"}",
"}",
"return",
"this",
"}"
] | Adds a listener for the specified event
@param {String} type
@param {Function} handler
@return {Emitter} | [
"Adds",
"a",
"listener",
"for",
"the",
"specified",
"event"
] | d710b4be188ca47d2f124c2c5280330691665774 | https://github.com/jhermsmeier/node-async-emitter/blob/d710b4be188ca47d2f124c2c5280330691665774/emitter.js#L72-L98 | train |
|
jhermsmeier/node-async-emitter | emitter.js | function( type, handler ) {
if( handler === void 0 || handler === null )
throw new Error( 'Missing argument "handler"' )
if( typeof handler !== 'function' && typeof handler.handleEvent !== 'function' )
throw new TypeError( 'Handler must be a function.' )
function wrapper() {
this.removeListener( type, wrapper )
typeof handler !== 'function'
? handler.handleEvent.apply( handler, arguments )
: handler.apply( this, arguments )
}
this._events[ type ] ?
this._events[ type ].push( wrapper ) :
this._events[ type ] = [ wrapper ]
return this
} | javascript | function( type, handler ) {
if( handler === void 0 || handler === null )
throw new Error( 'Missing argument "handler"' )
if( typeof handler !== 'function' && typeof handler.handleEvent !== 'function' )
throw new TypeError( 'Handler must be a function.' )
function wrapper() {
this.removeListener( type, wrapper )
typeof handler !== 'function'
? handler.handleEvent.apply( handler, arguments )
: handler.apply( this, arguments )
}
this._events[ type ] ?
this._events[ type ].push( wrapper ) :
this._events[ type ] = [ wrapper ]
return this
} | [
"function",
"(",
"type",
",",
"handler",
")",
"{",
"if",
"(",
"handler",
"===",
"void",
"0",
"||",
"handler",
"===",
"null",
")",
"throw",
"new",
"Error",
"(",
"'Missing argument \"handler\"'",
")",
"if",
"(",
"typeof",
"handler",
"!==",
"'function'",
"&&",
"typeof",
"handler",
".",
"handleEvent",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'Handler must be a function.'",
")",
"function",
"wrapper",
"(",
")",
"{",
"this",
".",
"removeListener",
"(",
"type",
",",
"wrapper",
")",
"typeof",
"handler",
"!==",
"'function'",
"?",
"handler",
".",
"handleEvent",
".",
"apply",
"(",
"handler",
",",
"arguments",
")",
":",
"handler",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
"}",
"this",
".",
"_events",
"[",
"type",
"]",
"?",
"this",
".",
"_events",
"[",
"type",
"]",
".",
"push",
"(",
"wrapper",
")",
":",
"this",
".",
"_events",
"[",
"type",
"]",
"=",
"[",
"wrapper",
"]",
"return",
"this",
"}"
] | Adds a one time listener for the specified event
@param {String} type
@param {Function} handler
@return {Emitter} | [
"Adds",
"a",
"one",
"time",
"listener",
"for",
"the",
"specified",
"event"
] | d710b4be188ca47d2f124c2c5280330691665774 | https://github.com/jhermsmeier/node-async-emitter/blob/d710b4be188ca47d2f124c2c5280330691665774/emitter.js#L106-L127 | train |
|
jhermsmeier/node-async-emitter | emitter.js | function( type ) {
var emitter = this
var listeners = this._events[ type ]
if( type === 'error' && !listeners ) {
if( !this._events.error ) {
throw !( arguments[1] instanceof Error ) ?
new Error( 'Unhandled "error" event.' ) :
arguments[1]
}
} else if( !listeners ) {
return false
}
var argv = [].slice.call( arguments, 1 )
var i, len = listeners.length
function fire( handler, argv ) {
typeof handler !== 'function' ?
handler.handleEvent.apply( handler, argv ) :
handler.apply( this, argv )
}
for( i = 0; i < len; i++ ) {
Emitter.nextTick(
fire.bind( this, listeners[i], argv )
)
}
return true
} | javascript | function( type ) {
var emitter = this
var listeners = this._events[ type ]
if( type === 'error' && !listeners ) {
if( !this._events.error ) {
throw !( arguments[1] instanceof Error ) ?
new Error( 'Unhandled "error" event.' ) :
arguments[1]
}
} else if( !listeners ) {
return false
}
var argv = [].slice.call( arguments, 1 )
var i, len = listeners.length
function fire( handler, argv ) {
typeof handler !== 'function' ?
handler.handleEvent.apply( handler, argv ) :
handler.apply( this, argv )
}
for( i = 0; i < len; i++ ) {
Emitter.nextTick(
fire.bind( this, listeners[i], argv )
)
}
return true
} | [
"function",
"(",
"type",
")",
"{",
"var",
"emitter",
"=",
"this",
"var",
"listeners",
"=",
"this",
".",
"_events",
"[",
"type",
"]",
"if",
"(",
"type",
"===",
"'error'",
"&&",
"!",
"listeners",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_events",
".",
"error",
")",
"{",
"throw",
"!",
"(",
"arguments",
"[",
"1",
"]",
"instanceof",
"Error",
")",
"?",
"new",
"Error",
"(",
"'Unhandled \"error\" event.'",
")",
":",
"arguments",
"[",
"1",
"]",
"}",
"}",
"else",
"if",
"(",
"!",
"listeners",
")",
"{",
"return",
"false",
"}",
"var",
"argv",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
"var",
"i",
",",
"len",
"=",
"listeners",
".",
"length",
"function",
"fire",
"(",
"handler",
",",
"argv",
")",
"{",
"typeof",
"handler",
"!==",
"'function'",
"?",
"handler",
".",
"handleEvent",
".",
"apply",
"(",
"handler",
",",
"argv",
")",
":",
"handler",
".",
"apply",
"(",
"this",
",",
"argv",
")",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"Emitter",
".",
"nextTick",
"(",
"fire",
".",
"bind",
"(",
"this",
",",
"listeners",
"[",
"i",
"]",
",",
"argv",
")",
")",
"}",
"return",
"true",
"}"
] | Execute each of the listeners in order
with the supplied arguments
@param {String} type
@return {Boolean} | [
"Execute",
"each",
"of",
"the",
"listeners",
"in",
"order",
"with",
"the",
"supplied",
"arguments"
] | d710b4be188ca47d2f124c2c5280330691665774 | https://github.com/jhermsmeier/node-async-emitter/blob/d710b4be188ca47d2f124c2c5280330691665774/emitter.js#L135-L167 | train |
|
jhermsmeier/node-async-emitter | emitter.js | function( type, handler ) {
var handlers = this._events[ type ]
var position = handlers.indexOf( handler )
if( handlers && ~position ) {
if( handlers.length === 1 ) {
this._events[ type ] = undefined
delete this._events[ type ]
} else {
handlers.splice( position, 1 )
}
}
return this
} | javascript | function( type, handler ) {
var handlers = this._events[ type ]
var position = handlers.indexOf( handler )
if( handlers && ~position ) {
if( handlers.length === 1 ) {
this._events[ type ] = undefined
delete this._events[ type ]
} else {
handlers.splice( position, 1 )
}
}
return this
} | [
"function",
"(",
"type",
",",
"handler",
")",
"{",
"var",
"handlers",
"=",
"this",
".",
"_events",
"[",
"type",
"]",
"var",
"position",
"=",
"handlers",
".",
"indexOf",
"(",
"handler",
")",
"if",
"(",
"handlers",
"&&",
"~",
"position",
")",
"{",
"if",
"(",
"handlers",
".",
"length",
"===",
"1",
")",
"{",
"this",
".",
"_events",
"[",
"type",
"]",
"=",
"undefined",
"delete",
"this",
".",
"_events",
"[",
"type",
"]",
"}",
"else",
"{",
"handlers",
".",
"splice",
"(",
"position",
",",
"1",
")",
"}",
"}",
"return",
"this",
"}"
] | Remove a listener for the specified event
@param {String} type
@param {Function} handler
@return {Emitter} | [
"Remove",
"a",
"listener",
"for",
"the",
"specified",
"event"
] | d710b4be188ca47d2f124c2c5280330691665774 | https://github.com/jhermsmeier/node-async-emitter/blob/d710b4be188ca47d2f124c2c5280330691665774/emitter.js#L239-L255 | train |
|
jhermsmeier/node-async-emitter | emitter.js | function( type ) {
if( arguments.length === 0 ) {
for( type in this._events ) {
this.removeAllListeners( type )
}
} else {
this._events[ type ] = undefined
delete this._events[ type ]
}
return this
} | javascript | function( type ) {
if( arguments.length === 0 ) {
for( type in this._events ) {
this.removeAllListeners( type )
}
} else {
this._events[ type ] = undefined
delete this._events[ type ]
}
return this
} | [
"function",
"(",
"type",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"0",
")",
"{",
"for",
"(",
"type",
"in",
"this",
".",
"_events",
")",
"{",
"this",
".",
"removeAllListeners",
"(",
"type",
")",
"}",
"}",
"else",
"{",
"this",
".",
"_events",
"[",
"type",
"]",
"=",
"undefined",
"delete",
"this",
".",
"_events",
"[",
"type",
"]",
"}",
"return",
"this",
"}"
] | Removes all listeners,
or those of the specified event
@param {String} type
@return {Emitter} | [
"Removes",
"all",
"listeners",
"or",
"those",
"of",
"the",
"specified",
"event"
] | d710b4be188ca47d2f124c2c5280330691665774 | https://github.com/jhermsmeier/node-async-emitter/blob/d710b4be188ca47d2f124c2c5280330691665774/emitter.js#L263-L276 | train |
|
phillipsdata/unicode-passgen | index.js | getOptions | function getOptions(options) {
var opts = {
include: [
{
chars: [[0x0000, 0xFFFF]],
min: 0
}
],
exclude: []
};
// Merge the properties of our options
for (var property in options) {
// Ignore options that are not in our opts set or are not an array
if (!opts.hasOwnProperty(property) || !Array.isArray(options[property])) {
continue;
}
// Reset the default value for this property since it's being overridden
if (property === 'include') {
opts.include = [];
}
// Merge the options given
for (var set in options[property]) {
if (typeof options[property][set] === 'object' &&
options[property][set].hasOwnProperty('chars') &&
Array.isArray(options[property][set].chars)
) {
// Add the character set to the options
var charSet = {
chars: options[property][set].chars,
min: 0
};
// Set the minimum value if given
if (options[property][set].hasOwnProperty('min') &&
isInt(options[property][set].min) &&
options[property][set].min > 0
) {
charSet.min = options[property][set].min;
}
opts[property].push(charSet);
}
}
}
return opts;
} | javascript | function getOptions(options) {
var opts = {
include: [
{
chars: [[0x0000, 0xFFFF]],
min: 0
}
],
exclude: []
};
// Merge the properties of our options
for (var property in options) {
// Ignore options that are not in our opts set or are not an array
if (!opts.hasOwnProperty(property) || !Array.isArray(options[property])) {
continue;
}
// Reset the default value for this property since it's being overridden
if (property === 'include') {
opts.include = [];
}
// Merge the options given
for (var set in options[property]) {
if (typeof options[property][set] === 'object' &&
options[property][set].hasOwnProperty('chars') &&
Array.isArray(options[property][set].chars)
) {
// Add the character set to the options
var charSet = {
chars: options[property][set].chars,
min: 0
};
// Set the minimum value if given
if (options[property][set].hasOwnProperty('min') &&
isInt(options[property][set].min) &&
options[property][set].min > 0
) {
charSet.min = options[property][set].min;
}
opts[property].push(charSet);
}
}
}
return opts;
} | [
"function",
"getOptions",
"(",
"options",
")",
"{",
"var",
"opts",
"=",
"{",
"include",
":",
"[",
"{",
"chars",
":",
"[",
"[",
"0x0000",
",",
"0xFFFF",
"]",
"]",
",",
"min",
":",
"0",
"}",
"]",
",",
"exclude",
":",
"[",
"]",
"}",
";",
"for",
"(",
"var",
"property",
"in",
"options",
")",
"{",
"if",
"(",
"!",
"opts",
".",
"hasOwnProperty",
"(",
"property",
")",
"||",
"!",
"Array",
".",
"isArray",
"(",
"options",
"[",
"property",
"]",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"property",
"===",
"'include'",
")",
"{",
"opts",
".",
"include",
"=",
"[",
"]",
";",
"}",
"for",
"(",
"var",
"set",
"in",
"options",
"[",
"property",
"]",
")",
"{",
"if",
"(",
"typeof",
"options",
"[",
"property",
"]",
"[",
"set",
"]",
"===",
"'object'",
"&&",
"options",
"[",
"property",
"]",
"[",
"set",
"]",
".",
"hasOwnProperty",
"(",
"'chars'",
")",
"&&",
"Array",
".",
"isArray",
"(",
"options",
"[",
"property",
"]",
"[",
"set",
"]",
".",
"chars",
")",
")",
"{",
"var",
"charSet",
"=",
"{",
"chars",
":",
"options",
"[",
"property",
"]",
"[",
"set",
"]",
".",
"chars",
",",
"min",
":",
"0",
"}",
";",
"if",
"(",
"options",
"[",
"property",
"]",
"[",
"set",
"]",
".",
"hasOwnProperty",
"(",
"'min'",
")",
"&&",
"isInt",
"(",
"options",
"[",
"property",
"]",
"[",
"set",
"]",
".",
"min",
")",
"&&",
"options",
"[",
"property",
"]",
"[",
"set",
"]",
".",
"min",
">",
"0",
")",
"{",
"charSet",
".",
"min",
"=",
"options",
"[",
"property",
"]",
"[",
"set",
"]",
".",
"min",
";",
"}",
"opts",
"[",
"property",
"]",
".",
"push",
"(",
"charSet",
")",
";",
"}",
"}",
"}",
"return",
"opts",
";",
"}"
] | Creates a set of options for the generator from the given options
@param {Object} options An Object containing:
- include (optional) - An Object containing an Array of Objects, each of which contain:
- chars - An Array containing an Array of 1 character per index:
- 0 - A single character, hex character, or unicode character.
This may be a single character to include, or the beginning of a
range of characters to include
- 1 - A single character, hex character, or unicode character.
This must be the end of the range of the characters to include.
- min (optional) - An Integer representing the minimum number of
characters from the 'chars' set that *must* be included in the generated
string
- exclude (optional) - An Object containing an Array of Objects, each of which contain:
- chars - An Array containing an Array of 1 character per index:
- 0 - A single character, hex character, or unicode character.
This may be a single character to exclude, or the beginning of a
range of characters to exclude
- 1 - A single character, hex character, or unicode character.
This must be the end of the range of the characters to exclude.
@returns {Object} An Object representing the given options | [
"Creates",
"a",
"set",
"of",
"options",
"for",
"the",
"generator",
"from",
"the",
"given",
"options"
] | b412707e45933cfc5da0428fa656d053883baadf | https://github.com/phillipsdata/unicode-passgen/blob/b412707e45933cfc5da0428fa656d053883baadf/index.js#L100-L149 | train |
phillipsdata/unicode-passgen | index.js | generateString | function generateString(set, length) {
var content = '';
// Cannot generate a string from an empty set
if (set.length <= 0) {
return content;
}
for (var i = 0; i < length; i++) {
content += String.fromCharCode(
set[Math.floor(Math.random() * set.length)]
);
}
return content;
} | javascript | function generateString(set, length) {
var content = '';
// Cannot generate a string from an empty set
if (set.length <= 0) {
return content;
}
for (var i = 0; i < length; i++) {
content += String.fromCharCode(
set[Math.floor(Math.random() * set.length)]
);
}
return content;
} | [
"function",
"generateString",
"(",
"set",
",",
"length",
")",
"{",
"var",
"content",
"=",
"''",
";",
"if",
"(",
"set",
".",
"length",
"<=",
"0",
")",
"{",
"return",
"content",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"content",
"+=",
"String",
".",
"fromCharCode",
"(",
"set",
"[",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"set",
".",
"length",
")",
"]",
")",
";",
"}",
"return",
"content",
";",
"}"
] | Generates a string of the given length from the given set of characters
@param {Array} set An Array of decimal characters
@param {Integer} length The length of the string to generate
@returns {String} The random generated string | [
"Generates",
"a",
"string",
"of",
"the",
"given",
"length",
"from",
"the",
"given",
"set",
"of",
"characters"
] | b412707e45933cfc5da0428fa656d053883baadf | https://github.com/phillipsdata/unicode-passgen/blob/b412707e45933cfc5da0428fa656d053883baadf/index.js#L158-L173 | train |
phillipsdata/unicode-passgen | index.js | getCharacterList | function getCharacterList(options) {
var regen = regenerate();
var include = options.include;
for (var i in include) {
for (var j in include[i].chars) {
// There should always be a 0th-index element
if (include[i].chars[j][0] === undefined) {
continue;
}
regen = addCharacters(regen, include[i].chars[j]);
}
}
removeCharacters(regen, options.exclude);
return regen.valueOf();
} | javascript | function getCharacterList(options) {
var regen = regenerate();
var include = options.include;
for (var i in include) {
for (var j in include[i].chars) {
// There should always be a 0th-index element
if (include[i].chars[j][0] === undefined) {
continue;
}
regen = addCharacters(regen, include[i].chars[j]);
}
}
removeCharacters(regen, options.exclude);
return regen.valueOf();
} | [
"function",
"getCharacterList",
"(",
"options",
")",
"{",
"var",
"regen",
"=",
"regenerate",
"(",
")",
";",
"var",
"include",
"=",
"options",
".",
"include",
";",
"for",
"(",
"var",
"i",
"in",
"include",
")",
"{",
"for",
"(",
"var",
"j",
"in",
"include",
"[",
"i",
"]",
".",
"chars",
")",
"{",
"if",
"(",
"include",
"[",
"i",
"]",
".",
"chars",
"[",
"j",
"]",
"[",
"0",
"]",
"===",
"undefined",
")",
"{",
"continue",
";",
"}",
"regen",
"=",
"addCharacters",
"(",
"regen",
",",
"include",
"[",
"i",
"]",
".",
"chars",
"[",
"j",
"]",
")",
";",
"}",
"}",
"removeCharacters",
"(",
"regen",
",",
"options",
".",
"exclude",
")",
";",
"return",
"regen",
".",
"valueOf",
"(",
")",
";",
"}"
] | Retrieves a complete list of all characters from the given options
@param {Object} options An Object containing:
- include (optional) - An Object containing an Array of Objects, each of which contain:
- chars - An Array containing an Array of 1 character per index:
- 0 - A single character, hex character, or unicode character.
This may be a single character to include, or the beginning of a
range of characters to include
- 1 - A single character, hex character, or unicode character.
This must be the end of the range of the characters to include.
- min (optional) - An Integer representing the minimum number of
characters from the 'chars' set that *must* be included in the generated
string
- exclude (optional) - An Object containing an Array of Objects, each of which contain:
- chars - An Array containing an Array of 1 character per index:
- 0 - A single character, hex character, or unicode character.
This may be a single character to exclude, or the beginning of a
range of characters to exclude
- 1 - A single character, hex character, or unicode character.
This must be the end of the range of the characters to exclude.
@returns {Array} an array of characters | [
"Retrieves",
"a",
"complete",
"list",
"of",
"all",
"characters",
"from",
"the",
"given",
"options"
] | b412707e45933cfc5da0428fa656d053883baadf | https://github.com/phillipsdata/unicode-passgen/blob/b412707e45933cfc5da0428fa656d053883baadf/index.js#L198-L216 | train |
phillipsdata/unicode-passgen | index.js | getCharacterSets | function getCharacterSets(options) {
var regen;
var include = options.include;
var sets = [];
for (var i in include) {
regen = regenerate();
for (var j in include[i].chars) {
// There should always be a 0th-index element
if (include[i].chars[j][0] === undefined) {
continue;
}
// Add the characters from the set
regen = addCharacters(regen, include[i].chars[j]);
}
// Remove the characters from the exclusion set
regen = removeCharacters(regen, options.exclude);
sets.push(
{
set: regen.valueOf(),
min: include[i].min
}
);
}
return sets;
} | javascript | function getCharacterSets(options) {
var regen;
var include = options.include;
var sets = [];
for (var i in include) {
regen = regenerate();
for (var j in include[i].chars) {
// There should always be a 0th-index element
if (include[i].chars[j][0] === undefined) {
continue;
}
// Add the characters from the set
regen = addCharacters(regen, include[i].chars[j]);
}
// Remove the characters from the exclusion set
regen = removeCharacters(regen, options.exclude);
sets.push(
{
set: regen.valueOf(),
min: include[i].min
}
);
}
return sets;
} | [
"function",
"getCharacterSets",
"(",
"options",
")",
"{",
"var",
"regen",
";",
"var",
"include",
"=",
"options",
".",
"include",
";",
"var",
"sets",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"in",
"include",
")",
"{",
"regen",
"=",
"regenerate",
"(",
")",
";",
"for",
"(",
"var",
"j",
"in",
"include",
"[",
"i",
"]",
".",
"chars",
")",
"{",
"if",
"(",
"include",
"[",
"i",
"]",
".",
"chars",
"[",
"j",
"]",
"[",
"0",
"]",
"===",
"undefined",
")",
"{",
"continue",
";",
"}",
"regen",
"=",
"addCharacters",
"(",
"regen",
",",
"include",
"[",
"i",
"]",
".",
"chars",
"[",
"j",
"]",
")",
";",
"}",
"regen",
"=",
"removeCharacters",
"(",
"regen",
",",
"options",
".",
"exclude",
")",
";",
"sets",
".",
"push",
"(",
"{",
"set",
":",
"regen",
".",
"valueOf",
"(",
")",
",",
"min",
":",
"include",
"[",
"i",
"]",
".",
"min",
"}",
")",
";",
"}",
"return",
"sets",
";",
"}"
] | Retrieves a complete list of all character sets from the given options
@param {Object} options An Object containing:
- include (optional) - An Object containing an Array of Objects, each of which contain:
- chars - An Array containing an Array of 1 character per index:
- 0 - A single character, hex character, or unicode character.
This may be a single character to include, or the beginning of a
range of characters to include
- 1 - A single character, hex character, or unicode character.
This must be the end of the range of the characters to include.
- min (optional) - An Integer representing the minimum number of
characters from the 'chars' set that *must* be included in the generated
string
- exclude (optional) - An Object containing an Array of Objects, each of which contain:
- chars - An Array containing an Array of 1 character per index:
- 0 - A single character, hex character, or unicode character.
This may be a single character to exclude, or the beginning of a
range of characters to exclude
- 1 - A single character, hex character, or unicode character.
This must be the end of the range of the characters to exclude.
@returns {Array} An Array of Objects, each of which include:
- set - An Array of decimal characters
- min - An Integer representing the minimum number of characters from the
set that must be included in the generated string | [
"Retrieves",
"a",
"complete",
"list",
"of",
"all",
"character",
"sets",
"from",
"the",
"given",
"options"
] | b412707e45933cfc5da0428fa656d053883baadf | https://github.com/phillipsdata/unicode-passgen/blob/b412707e45933cfc5da0428fa656d053883baadf/index.js#L244-L274 | train |
Baqend/jahcode | jahcode.js | function() {
var objectDescriptor = arguments[arguments.length - 1];
var klass = objectDescriptor.constructor !== Object? objectDescriptor.constructor: function Class(toCast) {
if (!(this instanceof klass)) {
return klass.asInstance(toCast);
}
if (this.initialize)
arguments.length ? this.initialize.apply(this, arguments) : this.initialize();
};
var proto = Object.createPrototypeChain(klass, this, Array.prototype.slice.call(arguments, 0, arguments.length - 1));
var names = Object.getOwnPropertyNames(objectDescriptor);
for ( var i = 0; i < names.length; ++i) {
var name = names[i];
var result = false;
if (Object.properties.hasOwnProperty(name)) {
result = Object.properties[name](proto, objectDescriptor, name);
}
if (!result) {
var d = Object.getOwnPropertyDescriptor(objectDescriptor, name);
if (d.value) {
var val = d.value;
if (val instanceof Function) {
if (/this\.superCall/.test(val.toString())) {
d.value = Object.createSuperCallWrapper(klass, name, val);
}
} else if (val && (val.hasOwnProperty('get') || val.hasOwnProperty('value'))) {
d = val;
}
}
Object.defineProperty(proto, name, d);
}
}
if (klass.initialize) {
klass.initialize();
}
return klass;
} | javascript | function() {
var objectDescriptor = arguments[arguments.length - 1];
var klass = objectDescriptor.constructor !== Object? objectDescriptor.constructor: function Class(toCast) {
if (!(this instanceof klass)) {
return klass.asInstance(toCast);
}
if (this.initialize)
arguments.length ? this.initialize.apply(this, arguments) : this.initialize();
};
var proto = Object.createPrototypeChain(klass, this, Array.prototype.slice.call(arguments, 0, arguments.length - 1));
var names = Object.getOwnPropertyNames(objectDescriptor);
for ( var i = 0; i < names.length; ++i) {
var name = names[i];
var result = false;
if (Object.properties.hasOwnProperty(name)) {
result = Object.properties[name](proto, objectDescriptor, name);
}
if (!result) {
var d = Object.getOwnPropertyDescriptor(objectDescriptor, name);
if (d.value) {
var val = d.value;
if (val instanceof Function) {
if (/this\.superCall/.test(val.toString())) {
d.value = Object.createSuperCallWrapper(klass, name, val);
}
} else if (val && (val.hasOwnProperty('get') || val.hasOwnProperty('value'))) {
d = val;
}
}
Object.defineProperty(proto, name, d);
}
}
if (klass.initialize) {
klass.initialize();
}
return klass;
} | [
"function",
"(",
")",
"{",
"var",
"objectDescriptor",
"=",
"arguments",
"[",
"arguments",
".",
"length",
"-",
"1",
"]",
";",
"var",
"klass",
"=",
"objectDescriptor",
".",
"constructor",
"!==",
"Object",
"?",
"objectDescriptor",
".",
"constructor",
":",
"function",
"Class",
"(",
"toCast",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"klass",
")",
")",
"{",
"return",
"klass",
".",
"asInstance",
"(",
"toCast",
")",
";",
"}",
"if",
"(",
"this",
".",
"initialize",
")",
"arguments",
".",
"length",
"?",
"this",
".",
"initialize",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
":",
"this",
".",
"initialize",
"(",
")",
";",
"}",
";",
"var",
"proto",
"=",
"Object",
".",
"createPrototypeChain",
"(",
"klass",
",",
"this",
",",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
",",
"arguments",
".",
"length",
"-",
"1",
")",
")",
";",
"var",
"names",
"=",
"Object",
".",
"getOwnPropertyNames",
"(",
"objectDescriptor",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"names",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"name",
"=",
"names",
"[",
"i",
"]",
";",
"var",
"result",
"=",
"false",
";",
"if",
"(",
"Object",
".",
"properties",
".",
"hasOwnProperty",
"(",
"name",
")",
")",
"{",
"result",
"=",
"Object",
".",
"properties",
"[",
"name",
"]",
"(",
"proto",
",",
"objectDescriptor",
",",
"name",
")",
";",
"}",
"if",
"(",
"!",
"result",
")",
"{",
"var",
"d",
"=",
"Object",
".",
"getOwnPropertyDescriptor",
"(",
"objectDescriptor",
",",
"name",
")",
";",
"if",
"(",
"d",
".",
"value",
")",
"{",
"var",
"val",
"=",
"d",
".",
"value",
";",
"if",
"(",
"val",
"instanceof",
"Function",
")",
"{",
"if",
"(",
"/",
"this\\.superCall",
"/",
".",
"test",
"(",
"val",
".",
"toString",
"(",
")",
")",
")",
"{",
"d",
".",
"value",
"=",
"Object",
".",
"createSuperCallWrapper",
"(",
"klass",
",",
"name",
",",
"val",
")",
";",
"}",
"}",
"else",
"if",
"(",
"val",
"&&",
"(",
"val",
".",
"hasOwnProperty",
"(",
"'get'",
")",
"||",
"val",
".",
"hasOwnProperty",
"(",
"'value'",
")",
")",
")",
"{",
"d",
"=",
"val",
";",
"}",
"}",
"Object",
".",
"defineProperty",
"(",
"proto",
",",
"name",
",",
"d",
")",
";",
"}",
"}",
"if",
"(",
"klass",
".",
"initialize",
")",
"{",
"klass",
".",
"initialize",
"(",
")",
";",
"}",
"return",
"klass",
";",
"}"
] | Inherits this constructor and extends it by additional properties and methods. Optional there can be mixined
additional Traits
@param {Trait...} traits Additional traits to mixin
@param {Object} classDescriptor The descriptor of the class properties and methods
@returns {Function} The new created child class | [
"Inherits",
"this",
"constructor",
"and",
"extends",
"it",
"by",
"additional",
"properties",
"and",
"methods",
".",
"Optional",
"there",
"can",
"be",
"mixined",
"additional",
"Traits"
] | 92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402 | https://github.com/Baqend/jahcode/blob/92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402/jahcode.js#L45-L89 | train |
|
Baqend/jahcode | jahcode.js | function(obj) {
if (obj === null || obj === void 0)
return false;
return Object(obj) instanceof this || classOf(obj).linearizedTypes.lastIndexOf(this) != -1;
} | javascript | function(obj) {
if (obj === null || obj === void 0)
return false;
return Object(obj) instanceof this || classOf(obj).linearizedTypes.lastIndexOf(this) != -1;
} | [
"function",
"(",
"obj",
")",
"{",
"if",
"(",
"obj",
"===",
"null",
"||",
"obj",
"===",
"void",
"0",
")",
"return",
"false",
";",
"return",
"Object",
"(",
"obj",
")",
"instanceof",
"this",
"||",
"classOf",
"(",
"obj",
")",
".",
"linearizedTypes",
".",
"lastIndexOf",
"(",
"this",
")",
"!=",
"-",
"1",
";",
"}"
] | Indicates if the object is an instance of this class
@param obj The object to check for
@returns {boolean} <code>true</code> if the object is defined and | [
"Indicates",
"if",
"the",
"object",
"is",
"an",
"instance",
"of",
"this",
"class"
] | 92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402 | https://github.com/Baqend/jahcode/blob/92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402/jahcode.js#L105-L110 | train |
|
Baqend/jahcode | jahcode.js | function(object) {
if (object === null || object === void 0)
return object;
return Object.getPrototypeOf(Object(object)).constructor;
} | javascript | function(object) {
if (object === null || object === void 0)
return object;
return Object.getPrototypeOf(Object(object)).constructor;
} | [
"function",
"(",
"object",
")",
"{",
"if",
"(",
"object",
"===",
"null",
"||",
"object",
"===",
"void",
"0",
")",
"return",
"object",
";",
"return",
"Object",
".",
"getPrototypeOf",
"(",
"Object",
"(",
"object",
")",
")",
".",
"constructor",
";",
"}"
] | Returns the constructor of the given object, works for objects and primitive types
@param {*} object The constructor to return for
@returns {Function} The constructor of the object
@global | [
"Returns",
"the",
"constructor",
"of",
"the",
"given",
"object",
"works",
"for",
"objects",
"and",
"primitive",
"types"
] | 92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402 | https://github.com/Baqend/jahcode/blob/92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402/jahcode.js#L255-L260 | train |
|
Baqend/jahcode | jahcode.js | function(obj) {
if (!obj.constructor.Bind) {
try {
var descr = {};
Bind.each(obj, function(name, method) {
descr[name] = {
get : function() {
return this[name] = method.bind(this.self);
},
set : function(val) {
Object.defineProperty(this, name, {
value : val
});
},
configurable : true
};
});
obj.constructor.Bind = Bind.Object.inherit(descr);
} catch (e) {
obj.constructor.Bind = Bind.Object.inherit({});
}
}
return new obj.constructor.Bind(obj);
} | javascript | function(obj) {
if (!obj.constructor.Bind) {
try {
var descr = {};
Bind.each(obj, function(name, method) {
descr[name] = {
get : function() {
return this[name] = method.bind(this.self);
},
set : function(val) {
Object.defineProperty(this, name, {
value : val
});
},
configurable : true
};
});
obj.constructor.Bind = Bind.Object.inherit(descr);
} catch (e) {
obj.constructor.Bind = Bind.Object.inherit({});
}
}
return new obj.constructor.Bind(obj);
} | [
"function",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
".",
"constructor",
".",
"Bind",
")",
"{",
"try",
"{",
"var",
"descr",
"=",
"{",
"}",
";",
"Bind",
".",
"each",
"(",
"obj",
",",
"function",
"(",
"name",
",",
"method",
")",
"{",
"descr",
"[",
"name",
"]",
"=",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
"[",
"name",
"]",
"=",
"method",
".",
"bind",
"(",
"this",
".",
"self",
")",
";",
"}",
",",
"set",
":",
"function",
"(",
"val",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"name",
",",
"{",
"value",
":",
"val",
"}",
")",
";",
"}",
",",
"configurable",
":",
"true",
"}",
";",
"}",
")",
";",
"obj",
".",
"constructor",
".",
"Bind",
"=",
"Bind",
".",
"Object",
".",
"inherit",
"(",
"descr",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"obj",
".",
"constructor",
".",
"Bind",
"=",
"Bind",
".",
"Object",
".",
"inherit",
"(",
"{",
"}",
")",
";",
"}",
"}",
"return",
"new",
"obj",
".",
"constructor",
".",
"Bind",
"(",
"obj",
")",
";",
"}"
] | Creates a bind proxy for the given object
Each method of the given object is reflected on the proxy and
bound to the object context
@param {*} obj The object which will be bound
@returns {Bind} The bound proxy | [
"Creates",
"a",
"bind",
"proxy",
"for",
"the",
"given",
"object",
"Each",
"method",
"of",
"the",
"given",
"object",
"is",
"reflected",
"on",
"the",
"proxy",
"and",
"bound",
"to",
"the",
"object",
"context"
] | 92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402 | https://github.com/Baqend/jahcode/blob/92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402/jahcode.js#L316-L340 | train |
|
juttle/juttle-viz | src/lib/layout/facet.js | function(svg, options) {
var widthCfg;
// the svg element to render charts to
this._svg = svg.classed('facet-layout',true);
this._attributes = options || {};
this._animDuration = commonOptionDefaults.duration;
// outer margins
this._margin = {
top: 0,
bottom: 50,
left: this._attributes.yScales.primary.displayOnAxis === 'left' ? 75 : 25,
right: this._attributes.yScales.primary.displayOnAxis === 'left' ? 25 : 75
};
// collection of facet panels created
this._facetPanels = [];
this._chartCount = 0; // the number of facetd charts to be displayed
this._colCount = 0; // number of columns
this._rowCount = 1; // number of rows
this._colWidth = 0; // width of column
this._chartHeight = 0; // the height of the chart
// facet.width configuration needs to be interpreted
// could be column width (FIXED) OR number of columns (FLEXING)
widthCfg = this._interpretWidthConfig(options.facet.width);
this._layoutMode = widthCfg.mode;
if (widthCfg.mode === 'fixed') {
this._colWidth = widthCfg.value;
}
else if (widthCfg.mode === 'flex') {
this._colCount = widthCfg.value;
}
this._facetTitleHeight = (options.facet.fields.length * FACET_LABEL_HEIGHT) + FACET_LABEL_PADDING; // the total height of vertically stacked facet field labels
this._facetHeight = this._getFacetHeight(); // the height of the facet (incl titles and chart)
} | javascript | function(svg, options) {
var widthCfg;
// the svg element to render charts to
this._svg = svg.classed('facet-layout',true);
this._attributes = options || {};
this._animDuration = commonOptionDefaults.duration;
// outer margins
this._margin = {
top: 0,
bottom: 50,
left: this._attributes.yScales.primary.displayOnAxis === 'left' ? 75 : 25,
right: this._attributes.yScales.primary.displayOnAxis === 'left' ? 25 : 75
};
// collection of facet panels created
this._facetPanels = [];
this._chartCount = 0; // the number of facetd charts to be displayed
this._colCount = 0; // number of columns
this._rowCount = 1; // number of rows
this._colWidth = 0; // width of column
this._chartHeight = 0; // the height of the chart
// facet.width configuration needs to be interpreted
// could be column width (FIXED) OR number of columns (FLEXING)
widthCfg = this._interpretWidthConfig(options.facet.width);
this._layoutMode = widthCfg.mode;
if (widthCfg.mode === 'fixed') {
this._colWidth = widthCfg.value;
}
else if (widthCfg.mode === 'flex') {
this._colCount = widthCfg.value;
}
this._facetTitleHeight = (options.facet.fields.length * FACET_LABEL_HEIGHT) + FACET_LABEL_PADDING; // the total height of vertically stacked facet field labels
this._facetHeight = this._getFacetHeight(); // the height of the facet (incl titles and chart)
} | [
"function",
"(",
"svg",
",",
"options",
")",
"{",
"var",
"widthCfg",
";",
"this",
".",
"_svg",
"=",
"svg",
".",
"classed",
"(",
"'facet-layout'",
",",
"true",
")",
";",
"this",
".",
"_attributes",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"_animDuration",
"=",
"commonOptionDefaults",
".",
"duration",
";",
"this",
".",
"_margin",
"=",
"{",
"top",
":",
"0",
",",
"bottom",
":",
"50",
",",
"left",
":",
"this",
".",
"_attributes",
".",
"yScales",
".",
"primary",
".",
"displayOnAxis",
"===",
"'left'",
"?",
"75",
":",
"25",
",",
"right",
":",
"this",
".",
"_attributes",
".",
"yScales",
".",
"primary",
".",
"displayOnAxis",
"===",
"'left'",
"?",
"25",
":",
"75",
"}",
";",
"this",
".",
"_facetPanels",
"=",
"[",
"]",
";",
"this",
".",
"_chartCount",
"=",
"0",
";",
"this",
".",
"_colCount",
"=",
"0",
";",
"this",
".",
"_rowCount",
"=",
"1",
";",
"this",
".",
"_colWidth",
"=",
"0",
";",
"this",
".",
"_chartHeight",
"=",
"0",
";",
"widthCfg",
"=",
"this",
".",
"_interpretWidthConfig",
"(",
"options",
".",
"facet",
".",
"width",
")",
";",
"this",
".",
"_layoutMode",
"=",
"widthCfg",
".",
"mode",
";",
"if",
"(",
"widthCfg",
".",
"mode",
"===",
"'fixed'",
")",
"{",
"this",
".",
"_colWidth",
"=",
"widthCfg",
".",
"value",
";",
"}",
"else",
"if",
"(",
"widthCfg",
".",
"mode",
"===",
"'flex'",
")",
"{",
"this",
".",
"_colCount",
"=",
"widthCfg",
".",
"value",
";",
"}",
"this",
".",
"_facetTitleHeight",
"=",
"(",
"options",
".",
"facet",
".",
"fields",
".",
"length",
"*",
"FACET_LABEL_HEIGHT",
")",
"+",
"FACET_LABEL_PADDING",
";",
"this",
".",
"_facetHeight",
"=",
"this",
".",
"_getFacetHeight",
"(",
")",
";",
"}"
] | Faceted Chart Layout
@param {Object} svg the element
@param {Object} options | [
"Faceted",
"Chart",
"Layout"
] | 834d13a66256d9c9177f46968b0ef05b8143e762 | https://github.com/juttle/juttle-viz/blob/834d13a66256d9c9177f46968b0ef05b8143e762/src/lib/layout/facet.js#L36-L76 | train |
|
gyselroth/balloon-node-sync | lib/delta/delta.js | applyGroupedDelta | function applyGroupedDelta(groupedDelta, callback) {
var createdCandidates = [];
logger.debug('Applying grouped delta', {category: 'sync-delta'});
async.eachSeries(groupedDelta, (node, cb) => {
if(node.actions.create && utility.isExcludeFile(utility.getNameFromPath(node.actions.create.path))) {
//do not process files which match exclude pattern.
return cb(null);
}
syncDb.findByRemoteId(node.id, (err, oldLocalNode) => {
if(err) return cbDeltaActions(err);
if(node.actions.create && node.actions.delete) delete node.actions.delete;
if(!oldLocalNode) {
//node localy not found by remote id -> process later to avoid conflicts
//nodes which don't have a create action can be ignored (deleted nodes not present localy)
if(node.actions.create) createdCandidates.push(node);
cb(null);
} else {
applyDeltaActions(node, oldLocalNode, (err, syncedNode) => {
resolveConflicts(err, syncedNode, cb);
});
}
});
}, (err, results) => {
if(err) return callback(err);
async.eachSeries(createdCandidates, (node, cb) => {
applyDeltaActions(node, undefined, (err, syncedNode) => {
resolveConflicts(err, syncedNode, cb);
});
}, callback);
});
} | javascript | function applyGroupedDelta(groupedDelta, callback) {
var createdCandidates = [];
logger.debug('Applying grouped delta', {category: 'sync-delta'});
async.eachSeries(groupedDelta, (node, cb) => {
if(node.actions.create && utility.isExcludeFile(utility.getNameFromPath(node.actions.create.path))) {
//do not process files which match exclude pattern.
return cb(null);
}
syncDb.findByRemoteId(node.id, (err, oldLocalNode) => {
if(err) return cbDeltaActions(err);
if(node.actions.create && node.actions.delete) delete node.actions.delete;
if(!oldLocalNode) {
//node localy not found by remote id -> process later to avoid conflicts
//nodes which don't have a create action can be ignored (deleted nodes not present localy)
if(node.actions.create) createdCandidates.push(node);
cb(null);
} else {
applyDeltaActions(node, oldLocalNode, (err, syncedNode) => {
resolveConflicts(err, syncedNode, cb);
});
}
});
}, (err, results) => {
if(err) return callback(err);
async.eachSeries(createdCandidates, (node, cb) => {
applyDeltaActions(node, undefined, (err, syncedNode) => {
resolveConflicts(err, syncedNode, cb);
});
}, callback);
});
} | [
"function",
"applyGroupedDelta",
"(",
"groupedDelta",
",",
"callback",
")",
"{",
"var",
"createdCandidates",
"=",
"[",
"]",
";",
"logger",
".",
"debug",
"(",
"'Applying grouped delta'",
",",
"{",
"category",
":",
"'sync-delta'",
"}",
")",
";",
"async",
".",
"eachSeries",
"(",
"groupedDelta",
",",
"(",
"node",
",",
"cb",
")",
"=>",
"{",
"if",
"(",
"node",
".",
"actions",
".",
"create",
"&&",
"utility",
".",
"isExcludeFile",
"(",
"utility",
".",
"getNameFromPath",
"(",
"node",
".",
"actions",
".",
"create",
".",
"path",
")",
")",
")",
"{",
"return",
"cb",
"(",
"null",
")",
";",
"}",
"syncDb",
".",
"findByRemoteId",
"(",
"node",
".",
"id",
",",
"(",
"err",
",",
"oldLocalNode",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cbDeltaActions",
"(",
"err",
")",
";",
"if",
"(",
"node",
".",
"actions",
".",
"create",
"&&",
"node",
".",
"actions",
".",
"delete",
")",
"delete",
"node",
".",
"actions",
".",
"delete",
";",
"if",
"(",
"!",
"oldLocalNode",
")",
"{",
"if",
"(",
"node",
".",
"actions",
".",
"create",
")",
"createdCandidates",
".",
"push",
"(",
"node",
")",
";",
"cb",
"(",
"null",
")",
";",
"}",
"else",
"{",
"applyDeltaActions",
"(",
"node",
",",
"oldLocalNode",
",",
"(",
"err",
",",
"syncedNode",
")",
"=>",
"{",
"resolveConflicts",
"(",
"err",
",",
"syncedNode",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"(",
"err",
",",
"results",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"async",
".",
"eachSeries",
"(",
"createdCandidates",
",",
"(",
"node",
",",
"cb",
")",
"=>",
"{",
"applyDeltaActions",
"(",
"node",
",",
"undefined",
",",
"(",
"err",
",",
"syncedNode",
")",
"=>",
"{",
"resolveConflicts",
"(",
"err",
",",
"syncedNode",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | Applies grouped remote delta to database
@see ./remote-delta.js groupDelta
@param {Object} groupedDelta - grouped remote delta
@param {Function} callback - callback function
@returns {void} - no return value | [
"Applies",
"grouped",
"remote",
"delta",
"to",
"database"
] | 0ae8d3a6c505e33fe8af220a95fee84aa54e386b | https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L19-L54 | train |
gyselroth/balloon-node-sync | lib/delta/delta.js | updateNode | function updateNode(node, callback) {
syncDb.update(node._id, node, (err, result) => {
if(err) return callback(err);
callback(null, node);
});
} | javascript | function updateNode(node, callback) {
syncDb.update(node._id, node, (err, result) => {
if(err) return callback(err);
callback(null, node);
});
} | [
"function",
"updateNode",
"(",
"node",
",",
"callback",
")",
"{",
"syncDb",
".",
"update",
"(",
"node",
".",
"_id",
",",
"node",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"callback",
"(",
"null",
",",
"node",
")",
";",
"}",
")",
";",
"}"
] | Updates a node in the database
@param {Object} node - database node to update
@param {Function} callback - callback function
@returns {void} - no return value | [
"Updates",
"a",
"node",
"in",
"the",
"database"
] | 0ae8d3a6c505e33fe8af220a95fee84aa54e386b | https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L63-L69 | train |
gyselroth/balloon-node-sync | lib/delta/delta.js | resolveConflicts | function resolveConflicts(err, syncedNode, callback) {
if(err) return callback(err);
if(!syncedNode) return callback(null);
async.series([
(cb) => {
if(syncedNode.directory === true) {
resolveDirectoryConflicts(syncedNode, cb);
} else {
resolveFileConflicts(syncedNode, cb);
}
},
(cb) => {
findLocalConflict(syncedNode, cb);
}
], (err, res) => {
if(err) return callback(err);
callback(null);
});
} | javascript | function resolveConflicts(err, syncedNode, callback) {
if(err) return callback(err);
if(!syncedNode) return callback(null);
async.series([
(cb) => {
if(syncedNode.directory === true) {
resolveDirectoryConflicts(syncedNode, cb);
} else {
resolveFileConflicts(syncedNode, cb);
}
},
(cb) => {
findLocalConflict(syncedNode, cb);
}
], (err, res) => {
if(err) return callback(err);
callback(null);
});
} | [
"function",
"resolveConflicts",
"(",
"err",
",",
"syncedNode",
",",
"callback",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"if",
"(",
"!",
"syncedNode",
")",
"return",
"callback",
"(",
"null",
")",
";",
"async",
".",
"series",
"(",
"[",
"(",
"cb",
")",
"=>",
"{",
"if",
"(",
"syncedNode",
".",
"directory",
"===",
"true",
")",
"{",
"resolveDirectoryConflicts",
"(",
"syncedNode",
",",
"cb",
")",
";",
"}",
"else",
"{",
"resolveFileConflicts",
"(",
"syncedNode",
",",
"cb",
")",
";",
"}",
"}",
",",
"(",
"cb",
")",
"=>",
"{",
"findLocalConflict",
"(",
"syncedNode",
",",
"cb",
")",
";",
"}",
"]",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"callback",
"(",
"null",
")",
";",
"}",
")",
";",
"}"
] | Resolves conflicts after remote delta actions have been applied
@param {Object|null} err - error object
@param {Object} snycedNode - node with applied actions from database
@param {Function} callback - callback function
@returns {void} - no return value | [
"Resolves",
"conflicts",
"after",
"remote",
"delta",
"actions",
"have",
"been",
"applied"
] | 0ae8d3a6c505e33fe8af220a95fee84aa54e386b | https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L232-L252 | train |
gyselroth/balloon-node-sync | lib/delta/delta.js | resolveDirectoryConflicts | function resolveDirectoryConflicts(node, callback) {
var rActions = node.remoteActions;
var lActions = node.localActions;
if(rActions && lActions) {
if(rActions.create && lActions.create) {
//on both sides created, we just need to add remoteId and remoteParent
node.remoteId = rActions.create.remoteId;
node.remoteParent = rActions.create.remoteParent;
delete node.remoteActions;
delete node.localActions;
}
//both sides renamed, remote wins
if(rActions.rename && lActions.rename) delete lActions.rename;
//both sides moved, remote wins
if(rActions.move && lActions.move) delete lActions.move;
//if remotely created and localy deleted node should be created localy
if(rActions.create && lActions.delete) delete lActions.delete;
//if localy created and remotely deleted node should be created remotely
if(rActions.delete && lActions.create) delete rActions.delete;
return syncDb.update(node._id, node, (err, updatedNode) => {
return callback(null);
});
}
return callback(null);
} | javascript | function resolveDirectoryConflicts(node, callback) {
var rActions = node.remoteActions;
var lActions = node.localActions;
if(rActions && lActions) {
if(rActions.create && lActions.create) {
//on both sides created, we just need to add remoteId and remoteParent
node.remoteId = rActions.create.remoteId;
node.remoteParent = rActions.create.remoteParent;
delete node.remoteActions;
delete node.localActions;
}
//both sides renamed, remote wins
if(rActions.rename && lActions.rename) delete lActions.rename;
//both sides moved, remote wins
if(rActions.move && lActions.move) delete lActions.move;
//if remotely created and localy deleted node should be created localy
if(rActions.create && lActions.delete) delete lActions.delete;
//if localy created and remotely deleted node should be created remotely
if(rActions.delete && lActions.create) delete rActions.delete;
return syncDb.update(node._id, node, (err, updatedNode) => {
return callback(null);
});
}
return callback(null);
} | [
"function",
"resolveDirectoryConflicts",
"(",
"node",
",",
"callback",
")",
"{",
"var",
"rActions",
"=",
"node",
".",
"remoteActions",
";",
"var",
"lActions",
"=",
"node",
".",
"localActions",
";",
"if",
"(",
"rActions",
"&&",
"lActions",
")",
"{",
"if",
"(",
"rActions",
".",
"create",
"&&",
"lActions",
".",
"create",
")",
"{",
"node",
".",
"remoteId",
"=",
"rActions",
".",
"create",
".",
"remoteId",
";",
"node",
".",
"remoteParent",
"=",
"rActions",
".",
"create",
".",
"remoteParent",
";",
"delete",
"node",
".",
"remoteActions",
";",
"delete",
"node",
".",
"localActions",
";",
"}",
"if",
"(",
"rActions",
".",
"rename",
"&&",
"lActions",
".",
"rename",
")",
"delete",
"lActions",
".",
"rename",
";",
"if",
"(",
"rActions",
".",
"move",
"&&",
"lActions",
".",
"move",
")",
"delete",
"lActions",
".",
"move",
";",
"if",
"(",
"rActions",
".",
"create",
"&&",
"lActions",
".",
"delete",
")",
"delete",
"lActions",
".",
"delete",
";",
"if",
"(",
"rActions",
".",
"delete",
"&&",
"lActions",
".",
"create",
")",
"delete",
"rActions",
".",
"delete",
";",
"return",
"syncDb",
".",
"update",
"(",
"node",
".",
"_id",
",",
"node",
",",
"(",
"err",
",",
"updatedNode",
")",
"=>",
"{",
"return",
"callback",
"(",
"null",
")",
";",
"}",
")",
";",
"}",
"return",
"callback",
"(",
"null",
")",
";",
"}"
] | Resolves conflicts for a directory node
@param {Object} node - node with applied actions from database
@param {Function} callback - callback function
@returns {void} - no return value | [
"Resolves",
"conflicts",
"for",
"a",
"directory",
"node"
] | 0ae8d3a6c505e33fe8af220a95fee84aa54e386b | https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L261-L293 | train |
gyselroth/balloon-node-sync | lib/delta/delta.js | resolveFileConflicts | function resolveFileConflicts(node, callback) {
var rActions = node.remoteActions;
var lActions = node.localActions;
if(!rActions || !lActions) {
//only one side changed, no conflicts
return callback(null);
}
if(rActions.create && lActions.create) {
//on both sides created or updated
var currentLocalPath = utility.joinPath(node.parent, node.name);
var localHash, stat;
try {
localHash = fsWrap.md5FileSync(currentLocalPath);
stat = fsWrap.lstatSync(currentLocalPath);
} catch(e) {
logger.warning('resolveFileConflicts failed', {category: 'sync-delta', node, err: e});
var err = new BlnDeltaError(e.message);
throw err;
}
if(rActions.create.hash && rActions.create.hash === localHash && rActions.create.size === stat.size) {
delete node.remoteActions;
delete node.localActions;
node.hash = localHash;
node.version = rActions.create.version;
node.size = stat.size;
node.mtime = stat.mtime;
node.ctime = stat.ctime;
node.remoteId = rActions.create.remoteId;
node.remoteParent = rActions.create.remoteParent;
return syncDb.update(node._id, node, callback);
} else if(!rActions.delete) {
//if remote path changed upload local version as new version on old path
var remoteNode;
return async.series([
(cb) => {
//create remote localy
var name = rActions.rename ? rActions.rename.remoteName : node.name;
var parent = rActions.move ? rActions.move.parent : node.parent;
var remoteParent = rActions.move ? rActions.move.remoteParent : rActions.create.remoteParent;
var newNode = {
name: name,
parent: parent,
directory: node.directory,
remoteId: node.remoteId,
remoteParent: remoteParent,
remoteActions: {create: rActions.create}
}
syncDb.create(newNode, (err, createdNode) => {
remoteNode = createdNode;
cb(err);
});
},
(cb) => {
delete node.remoteActions;
delete node.remoteParent;
delete node.remoteId;
delete node.hash;
delete node.version;
syncDb.update(node._id, node, cb);
},
(cb) => {
//as a new node has been created conflict resolution has to be executed for the new node
resolveConflicts(null, remoteNode, cb);
}
], callback);
}
}
if(rActions.delete && lActions.delete) {
//on both sides deleted, just remove it from db
return syncDb.delete(node._id, (err) => {
return callback(null);
});
}
return callback(null);
} | javascript | function resolveFileConflicts(node, callback) {
var rActions = node.remoteActions;
var lActions = node.localActions;
if(!rActions || !lActions) {
//only one side changed, no conflicts
return callback(null);
}
if(rActions.create && lActions.create) {
//on both sides created or updated
var currentLocalPath = utility.joinPath(node.parent, node.name);
var localHash, stat;
try {
localHash = fsWrap.md5FileSync(currentLocalPath);
stat = fsWrap.lstatSync(currentLocalPath);
} catch(e) {
logger.warning('resolveFileConflicts failed', {category: 'sync-delta', node, err: e});
var err = new BlnDeltaError(e.message);
throw err;
}
if(rActions.create.hash && rActions.create.hash === localHash && rActions.create.size === stat.size) {
delete node.remoteActions;
delete node.localActions;
node.hash = localHash;
node.version = rActions.create.version;
node.size = stat.size;
node.mtime = stat.mtime;
node.ctime = stat.ctime;
node.remoteId = rActions.create.remoteId;
node.remoteParent = rActions.create.remoteParent;
return syncDb.update(node._id, node, callback);
} else if(!rActions.delete) {
//if remote path changed upload local version as new version on old path
var remoteNode;
return async.series([
(cb) => {
//create remote localy
var name = rActions.rename ? rActions.rename.remoteName : node.name;
var parent = rActions.move ? rActions.move.parent : node.parent;
var remoteParent = rActions.move ? rActions.move.remoteParent : rActions.create.remoteParent;
var newNode = {
name: name,
parent: parent,
directory: node.directory,
remoteId: node.remoteId,
remoteParent: remoteParent,
remoteActions: {create: rActions.create}
}
syncDb.create(newNode, (err, createdNode) => {
remoteNode = createdNode;
cb(err);
});
},
(cb) => {
delete node.remoteActions;
delete node.remoteParent;
delete node.remoteId;
delete node.hash;
delete node.version;
syncDb.update(node._id, node, cb);
},
(cb) => {
//as a new node has been created conflict resolution has to be executed for the new node
resolveConflicts(null, remoteNode, cb);
}
], callback);
}
}
if(rActions.delete && lActions.delete) {
//on both sides deleted, just remove it from db
return syncDb.delete(node._id, (err) => {
return callback(null);
});
}
return callback(null);
} | [
"function",
"resolveFileConflicts",
"(",
"node",
",",
"callback",
")",
"{",
"var",
"rActions",
"=",
"node",
".",
"remoteActions",
";",
"var",
"lActions",
"=",
"node",
".",
"localActions",
";",
"if",
"(",
"!",
"rActions",
"||",
"!",
"lActions",
")",
"{",
"return",
"callback",
"(",
"null",
")",
";",
"}",
"if",
"(",
"rActions",
".",
"create",
"&&",
"lActions",
".",
"create",
")",
"{",
"var",
"currentLocalPath",
"=",
"utility",
".",
"joinPath",
"(",
"node",
".",
"parent",
",",
"node",
".",
"name",
")",
";",
"var",
"localHash",
",",
"stat",
";",
"try",
"{",
"localHash",
"=",
"fsWrap",
".",
"md5FileSync",
"(",
"currentLocalPath",
")",
";",
"stat",
"=",
"fsWrap",
".",
"lstatSync",
"(",
"currentLocalPath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"logger",
".",
"warning",
"(",
"'resolveFileConflicts failed'",
",",
"{",
"category",
":",
"'sync-delta'",
",",
"node",
",",
"err",
":",
"e",
"}",
")",
";",
"var",
"err",
"=",
"new",
"BlnDeltaError",
"(",
"e",
".",
"message",
")",
";",
"throw",
"err",
";",
"}",
"if",
"(",
"rActions",
".",
"create",
".",
"hash",
"&&",
"rActions",
".",
"create",
".",
"hash",
"===",
"localHash",
"&&",
"rActions",
".",
"create",
".",
"size",
"===",
"stat",
".",
"size",
")",
"{",
"delete",
"node",
".",
"remoteActions",
";",
"delete",
"node",
".",
"localActions",
";",
"node",
".",
"hash",
"=",
"localHash",
";",
"node",
".",
"version",
"=",
"rActions",
".",
"create",
".",
"version",
";",
"node",
".",
"size",
"=",
"stat",
".",
"size",
";",
"node",
".",
"mtime",
"=",
"stat",
".",
"mtime",
";",
"node",
".",
"ctime",
"=",
"stat",
".",
"ctime",
";",
"node",
".",
"remoteId",
"=",
"rActions",
".",
"create",
".",
"remoteId",
";",
"node",
".",
"remoteParent",
"=",
"rActions",
".",
"create",
".",
"remoteParent",
";",
"return",
"syncDb",
".",
"update",
"(",
"node",
".",
"_id",
",",
"node",
",",
"callback",
")",
";",
"}",
"else",
"if",
"(",
"!",
"rActions",
".",
"delete",
")",
"{",
"var",
"remoteNode",
";",
"return",
"async",
".",
"series",
"(",
"[",
"(",
"cb",
")",
"=>",
"{",
"var",
"name",
"=",
"rActions",
".",
"rename",
"?",
"rActions",
".",
"rename",
".",
"remoteName",
":",
"node",
".",
"name",
";",
"var",
"parent",
"=",
"rActions",
".",
"move",
"?",
"rActions",
".",
"move",
".",
"parent",
":",
"node",
".",
"parent",
";",
"var",
"remoteParent",
"=",
"rActions",
".",
"move",
"?",
"rActions",
".",
"move",
".",
"remoteParent",
":",
"rActions",
".",
"create",
".",
"remoteParent",
";",
"var",
"newNode",
"=",
"{",
"name",
":",
"name",
",",
"parent",
":",
"parent",
",",
"directory",
":",
"node",
".",
"directory",
",",
"remoteId",
":",
"node",
".",
"remoteId",
",",
"remoteParent",
":",
"remoteParent",
",",
"remoteActions",
":",
"{",
"create",
":",
"rActions",
".",
"create",
"}",
"}",
"syncDb",
".",
"create",
"(",
"newNode",
",",
"(",
"err",
",",
"createdNode",
")",
"=>",
"{",
"remoteNode",
"=",
"createdNode",
";",
"cb",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
",",
"(",
"cb",
")",
"=>",
"{",
"delete",
"node",
".",
"remoteActions",
";",
"delete",
"node",
".",
"remoteParent",
";",
"delete",
"node",
".",
"remoteId",
";",
"delete",
"node",
".",
"hash",
";",
"delete",
"node",
".",
"version",
";",
"syncDb",
".",
"update",
"(",
"node",
".",
"_id",
",",
"node",
",",
"cb",
")",
";",
"}",
",",
"(",
"cb",
")",
"=>",
"{",
"resolveConflicts",
"(",
"null",
",",
"remoteNode",
",",
"cb",
")",
";",
"}",
"]",
",",
"callback",
")",
";",
"}",
"}",
"if",
"(",
"rActions",
".",
"delete",
"&&",
"lActions",
".",
"delete",
")",
"{",
"return",
"syncDb",
".",
"delete",
"(",
"node",
".",
"_id",
",",
"(",
"err",
")",
"=>",
"{",
"return",
"callback",
"(",
"null",
")",
";",
"}",
")",
";",
"}",
"return",
"callback",
"(",
"null",
")",
";",
"}"
] | Resolves conflicts for a file node
@param {Object} node - node with applied actions from database
@param {Function} callback - callback function
@returns {void} - no return value | [
"Resolves",
"conflicts",
"for",
"a",
"file",
"node"
] | 0ae8d3a6c505e33fe8af220a95fee84aa54e386b | https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L302-L390 | train |
gyselroth/balloon-node-sync | lib/delta/delta.js | renameConflictNode | function renameConflictNode(newParent, oldPath, name, node, conflictingNode, callback) {
var newLocalName = utility.renameConflictNode(newParent, name);
try {
fsWrap.renameSync(oldPath, utility.joinPath(newParent, newLocalName));
} catch(err) {
return renameRemoteNode(node, name, callback);
}
conflictingNode.name = newLocalName;
conflictingNode.localActions = conflictingNode.localActions || {};
if(!conflictingNode.localActions.create && !conflictingNode.localActions.rename) {
//rename the node if not localy created or localy renamed (always keep original local rename actions)
conflictingNode.localActions.rename = {immediate: false, actionInitialized: new Date(), oldName: name};
}
return syncDb.update(conflictingNode._id, conflictingNode, callback);
} | javascript | function renameConflictNode(newParent, oldPath, name, node, conflictingNode, callback) {
var newLocalName = utility.renameConflictNode(newParent, name);
try {
fsWrap.renameSync(oldPath, utility.joinPath(newParent, newLocalName));
} catch(err) {
return renameRemoteNode(node, name, callback);
}
conflictingNode.name = newLocalName;
conflictingNode.localActions = conflictingNode.localActions || {};
if(!conflictingNode.localActions.create && !conflictingNode.localActions.rename) {
//rename the node if not localy created or localy renamed (always keep original local rename actions)
conflictingNode.localActions.rename = {immediate: false, actionInitialized: new Date(), oldName: name};
}
return syncDb.update(conflictingNode._id, conflictingNode, callback);
} | [
"function",
"renameConflictNode",
"(",
"newParent",
",",
"oldPath",
",",
"name",
",",
"node",
",",
"conflictingNode",
",",
"callback",
")",
"{",
"var",
"newLocalName",
"=",
"utility",
".",
"renameConflictNode",
"(",
"newParent",
",",
"name",
")",
";",
"try",
"{",
"fsWrap",
".",
"renameSync",
"(",
"oldPath",
",",
"utility",
".",
"joinPath",
"(",
"newParent",
",",
"newLocalName",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"renameRemoteNode",
"(",
"node",
",",
"name",
",",
"callback",
")",
";",
"}",
"conflictingNode",
".",
"name",
"=",
"newLocalName",
";",
"conflictingNode",
".",
"localActions",
"=",
"conflictingNode",
".",
"localActions",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"conflictingNode",
".",
"localActions",
".",
"create",
"&&",
"!",
"conflictingNode",
".",
"localActions",
".",
"rename",
")",
"{",
"conflictingNode",
".",
"localActions",
".",
"rename",
"=",
"{",
"immediate",
":",
"false",
",",
"actionInitialized",
":",
"new",
"Date",
"(",
")",
",",
"oldName",
":",
"name",
"}",
";",
"}",
"return",
"syncDb",
".",
"update",
"(",
"conflictingNode",
".",
"_id",
",",
"conflictingNode",
",",
"callback",
")",
";",
"}"
] | renames a conflict file
@param {string} newParent - new parent of the file
@param {Object} oldPath - old path of the file
@param {string} name - current name of the file
@param {Object} node - node A from database
@param {Object} conflictingNode - node B conflicting with node A from database
@param {Function} callback - callback function
@returns {void} - no return value | [
"renames",
"a",
"conflict",
"file"
] | 0ae8d3a6c505e33fe8af220a95fee84aa54e386b | https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L465-L484 | train |
gyselroth/balloon-node-sync | lib/delta/delta.js | renameRemoteNode | function renameRemoteNode(node, name, callback) {
var rActions = node.remoteActions || {};
var newLocalName = utility.renameConflictNodeRemote(name);
var oldLocalName = node.name;
var newLocalPath = utility.joinPath(node.parent, newLocalName);
var oldLocalPath = utility.joinPath(node.parent, oldLocalName);
if(!rActions.create && fsWrap.existsSync(oldLocalPath)) {
try {
fsWrap.renameSync(oldLocalPath, newLocalPath);
} catch(err) {
logger.warning('rename local node failed', {category: 'sync-delta', oldLocalPath, newLocalPath, err})
throw new BlnDeltaError(err.message);
return;
}
}
node.name = newLocalName;
node.localActions = node.localActions || {};
var remoteId = node.remoteId || node.remoteActions.create.remoteId;
return blnApi.renameNode({remoteId, name: node.name}, (err) => {
if(err) {
logger.warning('rename remote node failed', {category: 'sync-delta', params: {remoteId, name: node.name}, err});
throw new BlnDeltaError(err.message);
return;
}
if(rActions.rename) {
delete node.remoteActions.rename;
}
syncDb.update(node._id, node, callback);
});
} | javascript | function renameRemoteNode(node, name, callback) {
var rActions = node.remoteActions || {};
var newLocalName = utility.renameConflictNodeRemote(name);
var oldLocalName = node.name;
var newLocalPath = utility.joinPath(node.parent, newLocalName);
var oldLocalPath = utility.joinPath(node.parent, oldLocalName);
if(!rActions.create && fsWrap.existsSync(oldLocalPath)) {
try {
fsWrap.renameSync(oldLocalPath, newLocalPath);
} catch(err) {
logger.warning('rename local node failed', {category: 'sync-delta', oldLocalPath, newLocalPath, err})
throw new BlnDeltaError(err.message);
return;
}
}
node.name = newLocalName;
node.localActions = node.localActions || {};
var remoteId = node.remoteId || node.remoteActions.create.remoteId;
return blnApi.renameNode({remoteId, name: node.name}, (err) => {
if(err) {
logger.warning('rename remote node failed', {category: 'sync-delta', params: {remoteId, name: node.name}, err});
throw new BlnDeltaError(err.message);
return;
}
if(rActions.rename) {
delete node.remoteActions.rename;
}
syncDb.update(node._id, node, callback);
});
} | [
"function",
"renameRemoteNode",
"(",
"node",
",",
"name",
",",
"callback",
")",
"{",
"var",
"rActions",
"=",
"node",
".",
"remoteActions",
"||",
"{",
"}",
";",
"var",
"newLocalName",
"=",
"utility",
".",
"renameConflictNodeRemote",
"(",
"name",
")",
";",
"var",
"oldLocalName",
"=",
"node",
".",
"name",
";",
"var",
"newLocalPath",
"=",
"utility",
".",
"joinPath",
"(",
"node",
".",
"parent",
",",
"newLocalName",
")",
";",
"var",
"oldLocalPath",
"=",
"utility",
".",
"joinPath",
"(",
"node",
".",
"parent",
",",
"oldLocalName",
")",
";",
"if",
"(",
"!",
"rActions",
".",
"create",
"&&",
"fsWrap",
".",
"existsSync",
"(",
"oldLocalPath",
")",
")",
"{",
"try",
"{",
"fsWrap",
".",
"renameSync",
"(",
"oldLocalPath",
",",
"newLocalPath",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"logger",
".",
"warning",
"(",
"'rename local node failed'",
",",
"{",
"category",
":",
"'sync-delta'",
",",
"oldLocalPath",
",",
"newLocalPath",
",",
"err",
"}",
")",
"throw",
"new",
"BlnDeltaError",
"(",
"err",
".",
"message",
")",
";",
"return",
";",
"}",
"}",
"node",
".",
"name",
"=",
"newLocalName",
";",
"node",
".",
"localActions",
"=",
"node",
".",
"localActions",
"||",
"{",
"}",
";",
"var",
"remoteId",
"=",
"node",
".",
"remoteId",
"||",
"node",
".",
"remoteActions",
".",
"create",
".",
"remoteId",
";",
"return",
"blnApi",
".",
"renameNode",
"(",
"{",
"remoteId",
",",
"name",
":",
"node",
".",
"name",
"}",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"warning",
"(",
"'rename remote node failed'",
",",
"{",
"category",
":",
"'sync-delta'",
",",
"params",
":",
"{",
"remoteId",
",",
"name",
":",
"node",
".",
"name",
"}",
",",
"err",
"}",
")",
";",
"throw",
"new",
"BlnDeltaError",
"(",
"err",
".",
"message",
")",
";",
"return",
";",
"}",
"if",
"(",
"rActions",
".",
"rename",
")",
"{",
"delete",
"node",
".",
"remoteActions",
".",
"rename",
";",
"}",
"syncDb",
".",
"update",
"(",
"node",
".",
"_id",
",",
"node",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | renames a conflicting node remotely
@param {Object} node - node A from database
@param {string} name - current name of the file
@param {Function} callback - callback function
@returns {void} - no return value | [
"renames",
"a",
"conflicting",
"node",
"remotely"
] | 0ae8d3a6c505e33fe8af220a95fee84aa54e386b | https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L494-L533 | train |
gyselroth/balloon-node-sync | lib/delta/delta.js | function(dirPath, lastCursor, callback) {
async.parallel([
(cb) => {
localDelta.getDelta(dirPath, cb);
},
(cb) => {
remoteDelta.getDelta(lastCursor, cb);
}
], (err, results) => {
logger.info('getDelta ended', {category: 'sync-delta'});
if(err) return callback(err);
var currentRemoteCursor = results[1];
applyGroupedDelta(remoteDelta.getGroupedDelta(), (err) => {
if(err) return callback(err);
callback(null, currentRemoteCursor);
});
});
} | javascript | function(dirPath, lastCursor, callback) {
async.parallel([
(cb) => {
localDelta.getDelta(dirPath, cb);
},
(cb) => {
remoteDelta.getDelta(lastCursor, cb);
}
], (err, results) => {
logger.info('getDelta ended', {category: 'sync-delta'});
if(err) return callback(err);
var currentRemoteCursor = results[1];
applyGroupedDelta(remoteDelta.getGroupedDelta(), (err) => {
if(err) return callback(err);
callback(null, currentRemoteCursor);
});
});
} | [
"function",
"(",
"dirPath",
",",
"lastCursor",
",",
"callback",
")",
"{",
"async",
".",
"parallel",
"(",
"[",
"(",
"cb",
")",
"=>",
"{",
"localDelta",
".",
"getDelta",
"(",
"dirPath",
",",
"cb",
")",
";",
"}",
",",
"(",
"cb",
")",
"=>",
"{",
"remoteDelta",
".",
"getDelta",
"(",
"lastCursor",
",",
"cb",
")",
";",
"}",
"]",
",",
"(",
"err",
",",
"results",
")",
"=>",
"{",
"logger",
".",
"info",
"(",
"'getDelta ended'",
",",
"{",
"category",
":",
"'sync-delta'",
"}",
")",
";",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"var",
"currentRemoteCursor",
"=",
"results",
"[",
"1",
"]",
";",
"applyGroupedDelta",
"(",
"remoteDelta",
".",
"getGroupedDelta",
"(",
")",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"callback",
"(",
"null",
",",
"currentRemoteCursor",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | gets the remote and local delta and merges it
@param {string} dirPath - path to the root directory
@param {string} lastCursor - last cursor or undefined if cursor has been reset
@param {Function} callback - callback function
@returns {void} - no return value | [
"gets",
"the",
"remote",
"and",
"local",
"delta",
"and",
"merges",
"it"
] | 0ae8d3a6c505e33fe8af220a95fee84aa54e386b | https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L546-L567 | train |
|
rvagg/ghrepos | ghrepos.js | function (auth, org, repo, ref, options, callback) {
if (typeof options == 'function') {
callback = options
options = {}
}
// a valid ref but we're not using this format
ref = ref.replace(/^refs\//, '')
var url = refsBaseUrl(org, repo, type) + '/' + ref
ghutils.ghget(auth, url, options, callback)
} | javascript | function (auth, org, repo, ref, options, callback) {
if (typeof options == 'function') {
callback = options
options = {}
}
// a valid ref but we're not using this format
ref = ref.replace(/^refs\//, '')
var url = refsBaseUrl(org, repo, type) + '/' + ref
ghutils.ghget(auth, url, options, callback)
} | [
"function",
"(",
"auth",
",",
"org",
",",
"repo",
",",
"ref",
",",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"options",
"==",
"'function'",
")",
"{",
"callback",
"=",
"options",
"options",
"=",
"{",
"}",
"}",
"ref",
"=",
"ref",
".",
"replace",
"(",
"/",
"^refs\\/",
"/",
",",
"''",
")",
"var",
"url",
"=",
"refsBaseUrl",
"(",
"org",
",",
"repo",
",",
"type",
")",
"+",
"'/'",
"+",
"ref",
"ghutils",
".",
"ghget",
"(",
"auth",
",",
"url",
",",
"options",
",",
"callback",
")",
"}"
] | no getTag API | [
"no",
"getTag",
"API"
] | e5ff8fded0fb421d4cc0610c1f84d5cc242c0dc0 | https://github.com/rvagg/ghrepos/blob/e5ff8fded0fb421d4cc0610c1f84d5cc242c0dc0/ghrepos.js#L59-L70 | train |
|
tgroshon/street.js | src/street.js | getOldManifest | async function getOldManifest () {
try {
var data = await getFile('.manifest.json.gz')
} catch (err) {
if (err.code === 'NoSuchKey') return {}
else throw err
}
var unzippedBody = zlib.gunzipSync(data.Body)
return JSON.parse(unzippedBody)
} | javascript | async function getOldManifest () {
try {
var data = await getFile('.manifest.json.gz')
} catch (err) {
if (err.code === 'NoSuchKey') return {}
else throw err
}
var unzippedBody = zlib.gunzipSync(data.Body)
return JSON.parse(unzippedBody)
} | [
"async",
"function",
"getOldManifest",
"(",
")",
"{",
"try",
"{",
"var",
"data",
"=",
"await",
"getFile",
"(",
"'.manifest.json.gz'",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"'NoSuchKey'",
")",
"return",
"{",
"}",
"else",
"throw",
"err",
"}",
"var",
"unzippedBody",
"=",
"zlib",
".",
"gunzipSync",
"(",
"data",
".",
"Body",
")",
"return",
"JSON",
".",
"parse",
"(",
"unzippedBody",
")",
"}"
] | Download, unzip, and parse the manifest from remote storage | [
"Download",
"unzip",
"and",
"parse",
"the",
"manifest",
"from",
"remote",
"storage"
] | 8d68d4bc6dd2d6a75a698ac7f361cf3fa1a16c19 | https://github.com/tgroshon/street.js/blob/8d68d4bc6dd2d6a75a698ac7f361cf3fa1a16c19/src/street.js#L55-L64 | train |
tgroshon/street.js | src/street.js | upload | function upload (uploadables) {
var promises = uploadables.map((uploadable) => putUploadable(uploadable))
return Promise.all(promises)
} | javascript | function upload (uploadables) {
var promises = uploadables.map((uploadable) => putUploadable(uploadable))
return Promise.all(promises)
} | [
"function",
"upload",
"(",
"uploadables",
")",
"{",
"var",
"promises",
"=",
"uploadables",
".",
"map",
"(",
"(",
"uploadable",
")",
"=>",
"putUploadable",
"(",
"uploadable",
")",
")",
"return",
"Promise",
".",
"all",
"(",
"promises",
")",
"}"
] | Upload files to storage destination
@param Array<Uploadable>: List of uploadables to upload
@param Object: Street option object
@return Promise: A promise chain of all upload actions | [
"Upload",
"files",
"to",
"storage",
"destination"
] | 8d68d4bc6dd2d6a75a698ac7f361cf3fa1a16c19 | https://github.com/tgroshon/street.js/blob/8d68d4bc6dd2d6a75a698ac7f361cf3fa1a16c19/src/street.js#L83-L86 | train |
suguru/cql-client | lib/client.js | toCassandraValues | function toCassandraValues(metadata, values) {
if (values === null || values === undefined) {
return null;
}
var specs = metadata.columnSpecs;
var list = [];
for (var i = 0; i < specs.length; i++) {
var value = values[i];
if (value === null || value === undefined) {
list.push(null);
} else {
var spec = specs[i];
var type = types.fromType(spec.type);
list.push(type.serialize(value));
}
}
return list;
} | javascript | function toCassandraValues(metadata, values) {
if (values === null || values === undefined) {
return null;
}
var specs = metadata.columnSpecs;
var list = [];
for (var i = 0; i < specs.length; i++) {
var value = values[i];
if (value === null || value === undefined) {
list.push(null);
} else {
var spec = specs[i];
var type = types.fromType(spec.type);
list.push(type.serialize(value));
}
}
return list;
} | [
"function",
"toCassandraValues",
"(",
"metadata",
",",
"values",
")",
"{",
"if",
"(",
"values",
"===",
"null",
"||",
"values",
"===",
"undefined",
")",
"{",
"return",
"null",
";",
"}",
"var",
"specs",
"=",
"metadata",
".",
"columnSpecs",
";",
"var",
"list",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"specs",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"value",
"=",
"values",
"[",
"i",
"]",
";",
"if",
"(",
"value",
"===",
"null",
"||",
"value",
"===",
"undefined",
")",
"{",
"list",
".",
"push",
"(",
"null",
")",
";",
"}",
"else",
"{",
"var",
"spec",
"=",
"specs",
"[",
"i",
"]",
";",
"var",
"type",
"=",
"types",
".",
"fromType",
"(",
"spec",
".",
"type",
")",
";",
"list",
".",
"push",
"(",
"type",
".",
"serialize",
"(",
"value",
")",
")",
";",
"}",
"}",
"return",
"list",
";",
"}"
] | Convert values to binaries to be set for cassandra
@param {object} metadata - metadata
@param {array} values - value list | [
"Convert",
"values",
"to",
"binaries",
"to",
"be",
"set",
"for",
"cassandra"
] | c80563526827d13505e4821f7091d4db75e556c1 | https://github.com/suguru/cql-client/blob/c80563526827d13505e4821f7091d4db75e556c1/lib/client.js#L424-L441 | train |
benbowes/singleline | index.js | singleline | function singleline(multiLineString, noSpaces) {
const delimiter = noSpaces ? '' : ' ';
return multiLineString.replace(/\s\s+/g, delimiter).trim();
} | javascript | function singleline(multiLineString, noSpaces) {
const delimiter = noSpaces ? '' : ' ';
return multiLineString.replace(/\s\s+/g, delimiter).trim();
} | [
"function",
"singleline",
"(",
"multiLineString",
",",
"noSpaces",
")",
"{",
"const",
"delimiter",
"=",
"noSpaces",
"?",
"''",
":",
"' '",
";",
"return",
"multiLineString",
".",
"replace",
"(",
"/",
"\\s\\s+",
"/",
"g",
",",
"delimiter",
")",
".",
"trim",
"(",
")",
";",
"}"
] | Turns a multiline string into a single line string, optionallly with or without spaces.
@param {String} multiLineString - If using an es6 template string be sure to tab out.
@param {Boolean} noSpaces - If you'd like there to be no spaces between say your HTML add this boolean.
@returns {String} | [
"Turns",
"a",
"multiline",
"string",
"into",
"a",
"single",
"line",
"string",
"optionallly",
"with",
"or",
"without",
"spaces",
"."
] | ce5c4df7972584b9345b34fa4f30e01918c2dc51 | https://github.com/benbowes/singleline/blob/ce5c4df7972584b9345b34fa4f30e01918c2dc51/index.js#L8-L11 | train |
socialtables/geometry-utils | lib/split-arc.js | closestButNotGreaterThan | function closestButNotGreaterThan(numbers, maxNumber) {
var positiveNumbers = numbers.map(function(number){
return Math.abs(number);
});
var positiveMaxNumber = Math.abs(maxNumber);
var winner = positiveMaxNumber;
var winningDifference = positiveMaxNumber;
for (var i=0; i < positiveNumbers.length; i++) {
var lessThanMax = positiveNumbers[i] <= positiveMaxNumber;
var closerToMax = (positiveMaxNumber - positiveNumbers[i]) < winningDifference;
if (lessThanMax && closerToMax) {
winner = positiveNumbers[i];
winningDifference = positiveMaxNumber-positiveNumbers[i];
}
}
return winner;
} | javascript | function closestButNotGreaterThan(numbers, maxNumber) {
var positiveNumbers = numbers.map(function(number){
return Math.abs(number);
});
var positiveMaxNumber = Math.abs(maxNumber);
var winner = positiveMaxNumber;
var winningDifference = positiveMaxNumber;
for (var i=0; i < positiveNumbers.length; i++) {
var lessThanMax = positiveNumbers[i] <= positiveMaxNumber;
var closerToMax = (positiveMaxNumber - positiveNumbers[i]) < winningDifference;
if (lessThanMax && closerToMax) {
winner = positiveNumbers[i];
winningDifference = positiveMaxNumber-positiveNumbers[i];
}
}
return winner;
} | [
"function",
"closestButNotGreaterThan",
"(",
"numbers",
",",
"maxNumber",
")",
"{",
"var",
"positiveNumbers",
"=",
"numbers",
".",
"map",
"(",
"function",
"(",
"number",
")",
"{",
"return",
"Math",
".",
"abs",
"(",
"number",
")",
";",
"}",
")",
";",
"var",
"positiveMaxNumber",
"=",
"Math",
".",
"abs",
"(",
"maxNumber",
")",
";",
"var",
"winner",
"=",
"positiveMaxNumber",
";",
"var",
"winningDifference",
"=",
"positiveMaxNumber",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"positiveNumbers",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"lessThanMax",
"=",
"positiveNumbers",
"[",
"i",
"]",
"<=",
"positiveMaxNumber",
";",
"var",
"closerToMax",
"=",
"(",
"positiveMaxNumber",
"-",
"positiveNumbers",
"[",
"i",
"]",
")",
"<",
"winningDifference",
";",
"if",
"(",
"lessThanMax",
"&&",
"closerToMax",
")",
"{",
"winner",
"=",
"positiveNumbers",
"[",
"i",
"]",
";",
"winningDifference",
"=",
"positiveMaxNumber",
"-",
"positiveNumbers",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"winner",
";",
"}"
] | Return number with closest absolute value to maxNumber without exceeding it | [
"Return",
"number",
"with",
"closest",
"absolute",
"value",
"to",
"maxNumber",
"without",
"exceeding",
"it"
] | 4dc13529696a52dbe2d2cfcad3204dd39fca2f88 | https://github.com/socialtables/geometry-utils/blob/4dc13529696a52dbe2d2cfcad3204dd39fca2f88/lib/split-arc.js#L6-L24 | train |
socialtables/geometry-utils | lib/split-arc.js | closestToZero | function closestToZero(numbers, maxNumber) {
//returns the index of value closest to 0
var positiveNumbers = numbers.map(function(number) {
return Math.abs(number);
});
var sortedPositiveNumbers = positiveNumbers.sort(function(a, b) {
return (a - b);
});
return sortedPositiveNumbers[0];
} | javascript | function closestToZero(numbers, maxNumber) {
//returns the index of value closest to 0
var positiveNumbers = numbers.map(function(number) {
return Math.abs(number);
});
var sortedPositiveNumbers = positiveNumbers.sort(function(a, b) {
return (a - b);
});
return sortedPositiveNumbers[0];
} | [
"function",
"closestToZero",
"(",
"numbers",
",",
"maxNumber",
")",
"{",
"var",
"positiveNumbers",
"=",
"numbers",
".",
"map",
"(",
"function",
"(",
"number",
")",
"{",
"return",
"Math",
".",
"abs",
"(",
"number",
")",
";",
"}",
")",
";",
"var",
"sortedPositiveNumbers",
"=",
"positiveNumbers",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"(",
"a",
"-",
"b",
")",
";",
"}",
")",
";",
"return",
"sortedPositiveNumbers",
"[",
"0",
"]",
";",
"}"
] | Return the number that's closest to zero | [
"Return",
"the",
"number",
"that",
"s",
"closest",
"to",
"zero"
] | 4dc13529696a52dbe2d2cfcad3204dd39fca2f88 | https://github.com/socialtables/geometry-utils/blob/4dc13529696a52dbe2d2cfcad3204dd39fca2f88/lib/split-arc.js#L27-L38 | train |
socialtables/geometry-utils | lib/split-arc.js | findArcHeight | function findArcHeight(distance, radius, maxArcHeight, greaterThan180) {
var heightOptions = [];
heightOptions.push(radius + Math.sqrt(Math.pow(radius,2) - Math.pow(distance,2)));
heightOptions.push(radius - Math.sqrt(Math.pow(radius,2) - Math.pow(distance,2)));
if(greaterThan180){
return closestButNotGreaterThan(heightOptions, maxArcHeight);
}
else{
return closestToZero(heightOptions, maxArcHeight);
}
} | javascript | function findArcHeight(distance, radius, maxArcHeight, greaterThan180) {
var heightOptions = [];
heightOptions.push(radius + Math.sqrt(Math.pow(radius,2) - Math.pow(distance,2)));
heightOptions.push(radius - Math.sqrt(Math.pow(radius,2) - Math.pow(distance,2)));
if(greaterThan180){
return closestButNotGreaterThan(heightOptions, maxArcHeight);
}
else{
return closestToZero(heightOptions, maxArcHeight);
}
} | [
"function",
"findArcHeight",
"(",
"distance",
",",
"radius",
",",
"maxArcHeight",
",",
"greaterThan180",
")",
"{",
"var",
"heightOptions",
"=",
"[",
"]",
";",
"heightOptions",
".",
"push",
"(",
"radius",
"+",
"Math",
".",
"sqrt",
"(",
"Math",
".",
"pow",
"(",
"radius",
",",
"2",
")",
"-",
"Math",
".",
"pow",
"(",
"distance",
",",
"2",
")",
")",
")",
";",
"heightOptions",
".",
"push",
"(",
"radius",
"-",
"Math",
".",
"sqrt",
"(",
"Math",
".",
"pow",
"(",
"radius",
",",
"2",
")",
"-",
"Math",
".",
"pow",
"(",
"distance",
",",
"2",
")",
")",
")",
";",
"if",
"(",
"greaterThan180",
")",
"{",
"return",
"closestButNotGreaterThan",
"(",
"heightOptions",
",",
"maxArcHeight",
")",
";",
"}",
"else",
"{",
"return",
"closestToZero",
"(",
"heightOptions",
",",
"maxArcHeight",
")",
";",
"}",
"}"
] | Compute the height of a circular arc given `distance` is half the length of the chord of the circle, `radius` is the radius of the circle in question | [
"Compute",
"the",
"height",
"of",
"a",
"circular",
"arc",
"given",
"distance",
"is",
"half",
"the",
"length",
"of",
"the",
"chord",
"of",
"the",
"circle",
"radius",
"is",
"the",
"radius",
"of",
"the",
"circle",
"in",
"question"
] | 4dc13529696a52dbe2d2cfcad3204dd39fca2f88 | https://github.com/socialtables/geometry-utils/blob/4dc13529696a52dbe2d2cfcad3204dd39fca2f88/lib/split-arc.js#L42-L53 | train |
logikum/md-site-engine | source/utilities/negotiate-language.js | negotiateLanguage | function negotiateLanguage( acceptable, supported, engineDefault ) {
var candidates = [];
var enumeration = acceptable || '';
if (enumeration) {
// Create list of candidate locales.
var re = /;q=[01]\.\d,?/g;
var matches = enumeration.match( re );
if (matches)
// Create weighted list of locales.
for (var i = 0; i < matches.length; i++) {
var q = matches[ i ];
var index = enumeration.indexOf( q );
var group = enumeration.substring( 0, index );
var members = group.split( ',' );
var value = +q.substr( 3, 3 );
members.forEach( function ( member ) {
candidates.push( { locale: member, weight: value } );
} );
enumeration = enumeration.substring( index + q.length );
}
else {
// Create simple list of locales.
var locales = enumeration.split( ',' );
locales.forEach( function ( member ) {
candidates.push( { locale: member, weight: 1.0 } );
} );
}
}
// Sort locales by weight DESC, locale length DESC.
candidates.sort( function ( a, b ) {
if (a.weight < b.weight)
return 1;
if (a.weight > b.weight)
return -1;
if (a.locale.length < b.locale.length)
return 1;
if (a.locale.length > b.locale.length)
return -1;
return 0;
} );
// Find candidates among supported locales.
for (var c = 0; c < candidates.length; c++) {
var item = candidates[ c ].locale;
do {
if (supported.indexOf( item ) > -1)
return item;
// Try without country/region code.
item = item.substring( 0, item.lastIndexOf( '-' ) );
}
while (item);
}
// No supported candidate: return engine's default locale.
return engineDefault;
} | javascript | function negotiateLanguage( acceptable, supported, engineDefault ) {
var candidates = [];
var enumeration = acceptable || '';
if (enumeration) {
// Create list of candidate locales.
var re = /;q=[01]\.\d,?/g;
var matches = enumeration.match( re );
if (matches)
// Create weighted list of locales.
for (var i = 0; i < matches.length; i++) {
var q = matches[ i ];
var index = enumeration.indexOf( q );
var group = enumeration.substring( 0, index );
var members = group.split( ',' );
var value = +q.substr( 3, 3 );
members.forEach( function ( member ) {
candidates.push( { locale: member, weight: value } );
} );
enumeration = enumeration.substring( index + q.length );
}
else {
// Create simple list of locales.
var locales = enumeration.split( ',' );
locales.forEach( function ( member ) {
candidates.push( { locale: member, weight: 1.0 } );
} );
}
}
// Sort locales by weight DESC, locale length DESC.
candidates.sort( function ( a, b ) {
if (a.weight < b.weight)
return 1;
if (a.weight > b.weight)
return -1;
if (a.locale.length < b.locale.length)
return 1;
if (a.locale.length > b.locale.length)
return -1;
return 0;
} );
// Find candidates among supported locales.
for (var c = 0; c < candidates.length; c++) {
var item = candidates[ c ].locale;
do {
if (supported.indexOf( item ) > -1)
return item;
// Try without country/region code.
item = item.substring( 0, item.lastIndexOf( '-' ) );
}
while (item);
}
// No supported candidate: return engine's default locale.
return engineDefault;
} | [
"function",
"negotiateLanguage",
"(",
"acceptable",
",",
"supported",
",",
"engineDefault",
")",
"{",
"var",
"candidates",
"=",
"[",
"]",
";",
"var",
"enumeration",
"=",
"acceptable",
"||",
"''",
";",
"if",
"(",
"enumeration",
")",
"{",
"var",
"re",
"=",
"/",
";q=[01]\\.\\d,?",
"/",
"g",
";",
"var",
"matches",
"=",
"enumeration",
".",
"match",
"(",
"re",
")",
";",
"if",
"(",
"matches",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"matches",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"q",
"=",
"matches",
"[",
"i",
"]",
";",
"var",
"index",
"=",
"enumeration",
".",
"indexOf",
"(",
"q",
")",
";",
"var",
"group",
"=",
"enumeration",
".",
"substring",
"(",
"0",
",",
"index",
")",
";",
"var",
"members",
"=",
"group",
".",
"split",
"(",
"','",
")",
";",
"var",
"value",
"=",
"+",
"q",
".",
"substr",
"(",
"3",
",",
"3",
")",
";",
"members",
".",
"forEach",
"(",
"function",
"(",
"member",
")",
"{",
"candidates",
".",
"push",
"(",
"{",
"locale",
":",
"member",
",",
"weight",
":",
"value",
"}",
")",
";",
"}",
")",
";",
"enumeration",
"=",
"enumeration",
".",
"substring",
"(",
"index",
"+",
"q",
".",
"length",
")",
";",
"}",
"else",
"{",
"var",
"locales",
"=",
"enumeration",
".",
"split",
"(",
"','",
")",
";",
"locales",
".",
"forEach",
"(",
"function",
"(",
"member",
")",
"{",
"candidates",
".",
"push",
"(",
"{",
"locale",
":",
"member",
",",
"weight",
":",
"1.0",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
"candidates",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
".",
"weight",
"<",
"b",
".",
"weight",
")",
"return",
"1",
";",
"if",
"(",
"a",
".",
"weight",
">",
"b",
".",
"weight",
")",
"return",
"-",
"1",
";",
"if",
"(",
"a",
".",
"locale",
".",
"length",
"<",
"b",
".",
"locale",
".",
"length",
")",
"return",
"1",
";",
"if",
"(",
"a",
".",
"locale",
".",
"length",
">",
"b",
".",
"locale",
".",
"length",
")",
"return",
"-",
"1",
";",
"return",
"0",
";",
"}",
")",
";",
"for",
"(",
"var",
"c",
"=",
"0",
";",
"c",
"<",
"candidates",
".",
"length",
";",
"c",
"++",
")",
"{",
"var",
"item",
"=",
"candidates",
"[",
"c",
"]",
".",
"locale",
";",
"do",
"{",
"if",
"(",
"supported",
".",
"indexOf",
"(",
"item",
")",
">",
"-",
"1",
")",
"return",
"item",
";",
"item",
"=",
"item",
".",
"substring",
"(",
"0",
",",
"item",
".",
"lastIndexOf",
"(",
"'-'",
")",
")",
";",
"}",
"while",
"(",
"item",
")",
";",
"}",
"return",
"engineDefault",
";",
"}"
] | Tries to determine the default language based on the acceptable languages of
the browser and the supported languages of the site.
@param {string} acceptable - The acceptable languages of the browser.
@param {Array.<string>} supported - The supported languages of the site.
@param {string} engineDefault - The default language when no common one found.
@returns {string} The language to use. | [
"Tries",
"to",
"determine",
"the",
"default",
"language",
"based",
"on",
"the",
"acceptable",
"languages",
"of",
"the",
"browser",
"and",
"the",
"supported",
"languages",
"of",
"the",
"site",
"."
] | 1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784 | https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/utilities/negotiate-language.js#L11-L67 | train |
Evo-Forge/Crux | lib/components/tasks/lib/entry.js | CruxTaskEntry | function CruxTaskEntry(name) {
this.autorun = true; // we can disable auto running.
this.name = name;
this.debug = false;
this.type = 'serial'; // the type of this task. Can be: serial or parallel
this.__queue = [];
this.__actions = {};
this.__hasActions = false;
this.__started = false;
this.__scheduled = false;
this.__wait = 0;
this.__running = false;
this.__handlers = {}; // currently, only "failed", "timeout" and "completed"
this.__options = {
delay: 10, // number of seconds to delay the run.
timeout: 0, // number of seconds until we consider the task failed.
timer: 0 // number of seconds between calls. Defaults to 0(cyclic disabled)
};
this.__run_queue = []; // we place any run requests while running here.
EventEmitter.call(this);
} | javascript | function CruxTaskEntry(name) {
this.autorun = true; // we can disable auto running.
this.name = name;
this.debug = false;
this.type = 'serial'; // the type of this task. Can be: serial or parallel
this.__queue = [];
this.__actions = {};
this.__hasActions = false;
this.__started = false;
this.__scheduled = false;
this.__wait = 0;
this.__running = false;
this.__handlers = {}; // currently, only "failed", "timeout" and "completed"
this.__options = {
delay: 10, // number of seconds to delay the run.
timeout: 0, // number of seconds until we consider the task failed.
timer: 0 // number of seconds between calls. Defaults to 0(cyclic disabled)
};
this.__run_queue = []; // we place any run requests while running here.
EventEmitter.call(this);
} | [
"function",
"CruxTaskEntry",
"(",
"name",
")",
"{",
"this",
".",
"autorun",
"=",
"true",
";",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"debug",
"=",
"false",
";",
"this",
".",
"type",
"=",
"'serial'",
";",
"this",
".",
"__queue",
"=",
"[",
"]",
";",
"this",
".",
"__actions",
"=",
"{",
"}",
";",
"this",
".",
"__hasActions",
"=",
"false",
";",
"this",
".",
"__started",
"=",
"false",
";",
"this",
".",
"__scheduled",
"=",
"false",
";",
"this",
".",
"__wait",
"=",
"0",
";",
"this",
".",
"__running",
"=",
"false",
";",
"this",
".",
"__handlers",
"=",
"{",
"}",
";",
"this",
".",
"__options",
"=",
"{",
"delay",
":",
"10",
",",
"timeout",
":",
"0",
",",
"timer",
":",
"0",
"}",
";",
"this",
".",
"__run_queue",
"=",
"[",
"]",
";",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"}"
] | the "this" context for each scheduled action. Also a singleton. | [
"the",
"this",
"context",
"for",
"each",
"scheduled",
"action",
".",
"Also",
"a",
"singleton",
"."
] | f5264fbc2eb053e3170cf2b7b38d46d08f779feb | https://github.com/Evo-Forge/Crux/blob/f5264fbc2eb053e3170cf2b7b38d46d08f779feb/lib/components/tasks/lib/entry.js#L15-L35 | train |
brandon-barker/node-xgminer | lib/xgminer.js | xgminer | function xgminer(host, port, options) {
this.host = host || this.defaults.host;
this.port = port || this.defaults.port;
this.options = this.defaults;
if (options) {
_.defaults(this.options, options);
}
} | javascript | function xgminer(host, port, options) {
this.host = host || this.defaults.host;
this.port = port || this.defaults.port;
this.options = this.defaults;
if (options) {
_.defaults(this.options, options);
}
} | [
"function",
"xgminer",
"(",
"host",
",",
"port",
",",
"options",
")",
"{",
"this",
".",
"host",
"=",
"host",
"||",
"this",
".",
"defaults",
".",
"host",
";",
"this",
".",
"port",
"=",
"port",
"||",
"this",
".",
"defaults",
".",
"port",
";",
"this",
".",
"options",
"=",
"this",
".",
"defaults",
";",
"if",
"(",
"options",
")",
"{",
"_",
".",
"defaults",
"(",
"this",
".",
"options",
",",
"options",
")",
";",
"}",
"}"
] | Create an instance of xgminer.
@param {Name} name
@param {Host} host
@param {Port} port
@param {Options} options | [
"Create",
"an",
"instance",
"of",
"xgminer",
"."
] | a90416e0a8929f794b5cdfc284ee6675fd705d68 | https://github.com/brandon-barker/node-xgminer/blob/a90416e0a8929f794b5cdfc284ee6675fd705d68/lib/xgminer.js#L25-L33 | train |
kvnneff/s3-public-url | index.js | encodeSpecialCharacters | function encodeSpecialCharacters (str) {
return encodeURI(str).replace(/[!'()* ]/g, function (char) {
return '%' + char.charCodeAt(0).toString(16)
})
} | javascript | function encodeSpecialCharacters (str) {
return encodeURI(str).replace(/[!'()* ]/g, function (char) {
return '%' + char.charCodeAt(0).toString(16)
})
} | [
"function",
"encodeSpecialCharacters",
"(",
"str",
")",
"{",
"return",
"encodeURI",
"(",
"str",
")",
".",
"replace",
"(",
"/",
"[!'()* ]",
"/",
"g",
",",
"function",
"(",
"char",
")",
"{",
"return",
"'%'",
"+",
"char",
".",
"charCodeAt",
"(",
"0",
")",
".",
"toString",
"(",
"16",
")",
"}",
")",
"}"
] | Remove characters that are valid in URIs, but S3 does not like them for
some reason.
@param {String} str String to encode
@return {String} Encoded string
@api prviate | [
"Remove",
"characters",
"that",
"are",
"valid",
"in",
"URIs",
"but",
"S3",
"does",
"not",
"like",
"them",
"for",
"some",
"reason",
"."
] | 29839e12812bdd0c20eea27d067490ff443904a7 | https://github.com/kvnneff/s3-public-url/blob/29839e12812bdd0c20eea27d067490ff443904a7/index.js#L10-L14 | train |
logikum/md-site-engine | source/storage/insert-static-segments.js | insertStaticSegments | function insertStaticSegments( components, segments, languages ) {
for (var componentName in components) {
if (components.hasOwnProperty( componentName )) {
var language;
var appliedTokens = [ ];
var component = components[ componentName ];
// Determine the language of the component.
if (typeof languages === 'string')
language = languages;
else {
var parts = componentName.split( '/', 2 );
language = languages.indexOf( parts[ 0 ] ) >= 0 ? parts[ 0 ] : '';
}
// Insert static segments into a language specific component only.
if (language) {
// Get static segment tokens of the component.
component.tokens.filter( function ( token ) {
return token.isStatic;
} )
.forEach( function ( token ) {
// Get segment.
var segment = segments.get( language, token.name );
// Insert the static segment into the component.
var re = new RegExp( token.expression, 'g' );
component.html = component.html.replace( re, segment.html );
appliedTokens.push( token.name );
} );
// Remove applied segment tokens.
component.tokens = component.tokens.filter( function ( token ) {
return appliedTokens.indexOf( token.name ) < 0;
} );
}
}
}
} | javascript | function insertStaticSegments( components, segments, languages ) {
for (var componentName in components) {
if (components.hasOwnProperty( componentName )) {
var language;
var appliedTokens = [ ];
var component = components[ componentName ];
// Determine the language of the component.
if (typeof languages === 'string')
language = languages;
else {
var parts = componentName.split( '/', 2 );
language = languages.indexOf( parts[ 0 ] ) >= 0 ? parts[ 0 ] : '';
}
// Insert static segments into a language specific component only.
if (language) {
// Get static segment tokens of the component.
component.tokens.filter( function ( token ) {
return token.isStatic;
} )
.forEach( function ( token ) {
// Get segment.
var segment = segments.get( language, token.name );
// Insert the static segment into the component.
var re = new RegExp( token.expression, 'g' );
component.html = component.html.replace( re, segment.html );
appliedTokens.push( token.name );
} );
// Remove applied segment tokens.
component.tokens = component.tokens.filter( function ( token ) {
return appliedTokens.indexOf( token.name ) < 0;
} );
}
}
}
} | [
"function",
"insertStaticSegments",
"(",
"components",
",",
"segments",
",",
"languages",
")",
"{",
"for",
"(",
"var",
"componentName",
"in",
"components",
")",
"{",
"if",
"(",
"components",
".",
"hasOwnProperty",
"(",
"componentName",
")",
")",
"{",
"var",
"language",
";",
"var",
"appliedTokens",
"=",
"[",
"]",
";",
"var",
"component",
"=",
"components",
"[",
"componentName",
"]",
";",
"if",
"(",
"typeof",
"languages",
"===",
"'string'",
")",
"language",
"=",
"languages",
";",
"else",
"{",
"var",
"parts",
"=",
"componentName",
".",
"split",
"(",
"'/'",
",",
"2",
")",
";",
"language",
"=",
"languages",
".",
"indexOf",
"(",
"parts",
"[",
"0",
"]",
")",
">=",
"0",
"?",
"parts",
"[",
"0",
"]",
":",
"''",
";",
"}",
"if",
"(",
"language",
")",
"{",
"component",
".",
"tokens",
".",
"filter",
"(",
"function",
"(",
"token",
")",
"{",
"return",
"token",
".",
"isStatic",
";",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"token",
")",
"{",
"var",
"segment",
"=",
"segments",
".",
"get",
"(",
"language",
",",
"token",
".",
"name",
")",
";",
"var",
"re",
"=",
"new",
"RegExp",
"(",
"token",
".",
"expression",
",",
"'g'",
")",
";",
"component",
".",
"html",
"=",
"component",
".",
"html",
".",
"replace",
"(",
"re",
",",
"segment",
".",
"html",
")",
";",
"appliedTokens",
".",
"push",
"(",
"token",
".",
"name",
")",
";",
"}",
")",
";",
"component",
".",
"tokens",
"=",
"component",
".",
"tokens",
".",
"filter",
"(",
"function",
"(",
"token",
")",
"{",
"return",
"appliedTokens",
".",
"indexOf",
"(",
"token",
".",
"name",
")",
"<",
"0",
";",
"}",
")",
";",
"}",
"}",
"}",
"}"
] | Inserts static segments into all components.
@param {object} components - The components to process.
@param {SegmentDrawer} segments - The segment storage.
@param {Array.<string>} languages - The list of languages. | [
"Inserts",
"static",
"segments",
"into",
"all",
"components",
"."
] | 1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784 | https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/storage/insert-static-segments.js#L9-L49 | train |
enmasseio/babble | lib/Conversation.js | Conversation | function Conversation (config) {
if (!(this instanceof Conversation)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
// public properties
this.id = config && config.id || uuid.v4();
this.self = config && config.self || null;
this.other = config && config.other || null;
this.context = config && config.context || {};
// private properties
this._send = config && config.send || null;
this._inbox = []; // queue with received but not yet picked messages
this._receivers = []; // queue with handlers waiting for a new message
} | javascript | function Conversation (config) {
if (!(this instanceof Conversation)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
// public properties
this.id = config && config.id || uuid.v4();
this.self = config && config.self || null;
this.other = config && config.other || null;
this.context = config && config.context || {};
// private properties
this._send = config && config.send || null;
this._inbox = []; // queue with received but not yet picked messages
this._receivers = []; // queue with handlers waiting for a new message
} | [
"function",
"Conversation",
"(",
"config",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Conversation",
")",
")",
"{",
"throw",
"new",
"SyntaxError",
"(",
"'Constructor must be called with the new operator'",
")",
";",
"}",
"this",
".",
"id",
"=",
"config",
"&&",
"config",
".",
"id",
"||",
"uuid",
".",
"v4",
"(",
")",
";",
"this",
".",
"self",
"=",
"config",
"&&",
"config",
".",
"self",
"||",
"null",
";",
"this",
".",
"other",
"=",
"config",
"&&",
"config",
".",
"other",
"||",
"null",
";",
"this",
".",
"context",
"=",
"config",
"&&",
"config",
".",
"context",
"||",
"{",
"}",
";",
"this",
".",
"_send",
"=",
"config",
"&&",
"config",
".",
"send",
"||",
"null",
";",
"this",
".",
"_inbox",
"=",
"[",
"]",
";",
"this",
".",
"_receivers",
"=",
"[",
"]",
";",
"}"
] | A conversation
Holds meta data for a conversation between two peers
@param {Object} [config] Configuration options:
{string} [id] A unique id for the conversation. If not provided, a uuid is generated
{string} self Id of the peer on this side of the conversation
{string} other Id of the peer on the other side of the conversation
{Object} [context] Context passed with all callbacks of the conversation
{function(to: string, message: *): Promise} send Function to send a message
@constructor | [
"A",
"conversation",
"Holds",
"meta",
"data",
"for",
"a",
"conversation",
"between",
"two",
"peers"
] | 6b7e84d7fb0df2d1129f0646b37a9d89d3da2539 | https://github.com/enmasseio/babble/blob/6b7e84d7fb0df2d1129f0646b37a9d89d3da2539/lib/Conversation.js#L15-L30 | train |
logikum/md-site-engine | source/utilities/r-and-d.js | setDeveloperRoutes | function setDeveloperRoutes( app, filingCabinet, paths, develop ) {
// Create document template for resources.
var head = '\n' +
' <link rel="stylesheet" href="' + develop.cssBootstrap + '" />\n' +
' <link rel="stylesheet" href="' + develop.cssHighlight + '">\n';
var foot = '\n' +
' <script src="' + develop.jsJQuery + '"></script>\n' +
' <script src="' + develop.jsBootstrap + '"></script>\n' +
' <script src="' + develop.jsHighlight + '"></script>\n' +
' <script>hljs.initHighlightingOnLoad();</script>\n';
function wrap( title, body ) {
return '<html>\n<head>' + head + '</head>\n<style>\n' + css + '\n</style>\n\n' +
'<h1>' + title + '</h1>\n' +
'<p><i>' + pkgInfo.name + ' v' + pkgInfo.version + '</i></p>\n' +
body + foot + '\n</body>\n</html>\n';
}
// Set up developer paths.
PATH.init( paths.develop );
// Developer home page.
app.get( PATH.root, function ( req, res ) {
res.status( 200 ).send( wrap( 'Resources',
'<ul>\n' +
' <li><a href="' + PATH.list.languages + '">Languages</a></li>\n' +
' <li><a href="' + PATH.list.documents + '">Documents</a></li>\n' +
' <li><a href="' + PATH.list.layouts + '">Layouts</a></li>\n' +
' <li><a href="' + PATH.list.segments + '">Segments</a></li>\n' +
' <li><a href="' + PATH.list.contents + '">Contents</a></li>\n' +
' <li><a href="' + PATH.list.menus + '">Menus</a></li>\n' +
' <li><a href="' + PATH.list.locales + '">Locales</a></li>\n' +
' <li><a href="' + PATH.list.references + '">References</a></li>\n' +
' <li><a href="' + PATH.list.controls + '">Controls</a></li>\n' +
'</ul>\n' +
'<p><a class="btn btn-success" href="/">Go to site</a></p>\n'
) );
} );
logger.routeAdded( PATH.root );
// Lists all languages.
app.get( PATH.list.languages, function ( req, res ) {
res.status( 200 ).send( wrap( 'Languages',
filingCabinet.listLanguages() +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.languages );
// Lists all documents.
app.get( PATH.list.documents, function ( req, res ) {
res.status( 200 ).send( wrap( 'Documents',
filingCabinet.documents.list( PATH.show.document ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.documents );
// Display a document.
app.get( PATH.show.document + '/:key', function ( req, res ) {
var key = PATH.unsafe( req.params[ 'key' ] );
res.status( 200 ).send( wrap( 'Document: ' + show( key ),
filingCabinet.documents.show( key ) +
backTo( PATH.list.documents ) ) );
} );
logger.routeAdded( PATH.show.document );
// Lists all layouts.
app.get( PATH.list.layouts, function ( req, res ) {
res.status( 200 ).send( wrap( 'Layouts',
filingCabinet.layouts.list( PATH.show.layout ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.layouts );
// Display a layout.
app.get( PATH.show.layout + '/:key', function ( req, res ) {
var key = PATH.unsafe( req.params[ 'key' ] );
res.status( 200 ).send( wrap( 'Layout: ' + show( key ),
filingCabinet.layouts.show( key ) +
backTo( PATH.list.layouts ) ) );
} );
logger.routeAdded( PATH.show.layout );
// Lists all segments.
app.get( PATH.list.segments, function ( req, res ) {
res.status( 200 ).send( wrap( 'Segments',
filingCabinet.segments.list( PATH.show.segment ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.segments );
// Display a segment.
app.get( PATH.show.segment + '/:key', function ( req, res ) {
var key = PATH.unsafe( req.params[ 'key' ] );
res.status( 200 ).send( wrap( 'Segment: ' + show( key ),
filingCabinet.segments.show( key ) +
backTo( PATH.list.segments ) ) );
} );
logger.routeAdded( PATH.show.segment );
// Lists all contents.
app.get( PATH.list.contents, function ( req, res ) {
res.status( 200 ).send( wrap( 'Contents',
filingCabinet.contents.list( PATH.show.content ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.contents );
// Display a content.
app.get( PATH.show.content + '/:language/:key', function ( req, res ) {
var language = req.params[ 'language' ];
var key = PATH.unsafe( req.params[ 'key' ] );
res.status( 200 ).send( wrap( 'Content: ' + show( key ),
filingCabinet.contents.show( language, key ) +
backTo( PATH.list.contents ) ) );
} );
logger.routeAdded( PATH.show.content );
// Lists all menus.
app.get( PATH.list.menus, function ( req, res ) {
res.status( 200 ).send( wrap( 'Menus',
filingCabinet.menus.list( PATH.show.menu ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.menus );
// Display a menu.
app.get( PATH.show.menu + '/:language/:key', function ( req, res ) {
var language = req.params[ 'language' ];
var key = req.params[ 'key' ];
var result = filingCabinet.menus.show( language, +key );
res.status( 200 ).send( wrap( 'Menu: ' + show( result.title ),
result.list +
backTo( PATH.list.menus ) ) );
} );
logger.routeAdded( PATH.show.menu );
// Lists all locales.
app.get( PATH.list.locales, function ( req, res ) {
res.status( 200 ).send( wrap( 'Locales',
filingCabinet.locales.list( filingCabinet.languages ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.locales );
// Lists all references.
app.get( PATH.list.references, function ( req, res ) {
res.status( 200 ).send( wrap( 'References',
filingCabinet.references.list( PATH.show.reference ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.references );
// Display a reference.
app.get( PATH.show.reference + '/:key', function ( req, res ) {
var key = PATH.unsafe( req.params[ 'key' ] );
res.status( 200 ).send( wrap( 'Reference: ' + show( key ),
filingCabinet.references.show( key ) +
backTo( PATH.list.references ) ) );
} );
logger.routeAdded( PATH.show.reference );
// Lists all controls.
app.get( PATH.list.controls, function ( req, res ) {
res.status( 200 ).send( wrap( 'Controls',
filingCabinet.controls.list( PATH.show.control ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.controls );
// Display a control.
app.get( PATH.show.control + '/:key', function ( req, res ) {
var key = PATH.unsafe( req.params[ 'key' ] );
res.status( 200 ).send( wrap( 'Control: ' + show( key ),
filingCabinet.controls.show( key ) +
backTo( PATH.list.controls ) ) );
} );
logger.routeAdded( PATH.show.control );
} | javascript | function setDeveloperRoutes( app, filingCabinet, paths, develop ) {
// Create document template for resources.
var head = '\n' +
' <link rel="stylesheet" href="' + develop.cssBootstrap + '" />\n' +
' <link rel="stylesheet" href="' + develop.cssHighlight + '">\n';
var foot = '\n' +
' <script src="' + develop.jsJQuery + '"></script>\n' +
' <script src="' + develop.jsBootstrap + '"></script>\n' +
' <script src="' + develop.jsHighlight + '"></script>\n' +
' <script>hljs.initHighlightingOnLoad();</script>\n';
function wrap( title, body ) {
return '<html>\n<head>' + head + '</head>\n<style>\n' + css + '\n</style>\n\n' +
'<h1>' + title + '</h1>\n' +
'<p><i>' + pkgInfo.name + ' v' + pkgInfo.version + '</i></p>\n' +
body + foot + '\n</body>\n</html>\n';
}
// Set up developer paths.
PATH.init( paths.develop );
// Developer home page.
app.get( PATH.root, function ( req, res ) {
res.status( 200 ).send( wrap( 'Resources',
'<ul>\n' +
' <li><a href="' + PATH.list.languages + '">Languages</a></li>\n' +
' <li><a href="' + PATH.list.documents + '">Documents</a></li>\n' +
' <li><a href="' + PATH.list.layouts + '">Layouts</a></li>\n' +
' <li><a href="' + PATH.list.segments + '">Segments</a></li>\n' +
' <li><a href="' + PATH.list.contents + '">Contents</a></li>\n' +
' <li><a href="' + PATH.list.menus + '">Menus</a></li>\n' +
' <li><a href="' + PATH.list.locales + '">Locales</a></li>\n' +
' <li><a href="' + PATH.list.references + '">References</a></li>\n' +
' <li><a href="' + PATH.list.controls + '">Controls</a></li>\n' +
'</ul>\n' +
'<p><a class="btn btn-success" href="/">Go to site</a></p>\n'
) );
} );
logger.routeAdded( PATH.root );
// Lists all languages.
app.get( PATH.list.languages, function ( req, res ) {
res.status( 200 ).send( wrap( 'Languages',
filingCabinet.listLanguages() +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.languages );
// Lists all documents.
app.get( PATH.list.documents, function ( req, res ) {
res.status( 200 ).send( wrap( 'Documents',
filingCabinet.documents.list( PATH.show.document ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.documents );
// Display a document.
app.get( PATH.show.document + '/:key', function ( req, res ) {
var key = PATH.unsafe( req.params[ 'key' ] );
res.status( 200 ).send( wrap( 'Document: ' + show( key ),
filingCabinet.documents.show( key ) +
backTo( PATH.list.documents ) ) );
} );
logger.routeAdded( PATH.show.document );
// Lists all layouts.
app.get( PATH.list.layouts, function ( req, res ) {
res.status( 200 ).send( wrap( 'Layouts',
filingCabinet.layouts.list( PATH.show.layout ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.layouts );
// Display a layout.
app.get( PATH.show.layout + '/:key', function ( req, res ) {
var key = PATH.unsafe( req.params[ 'key' ] );
res.status( 200 ).send( wrap( 'Layout: ' + show( key ),
filingCabinet.layouts.show( key ) +
backTo( PATH.list.layouts ) ) );
} );
logger.routeAdded( PATH.show.layout );
// Lists all segments.
app.get( PATH.list.segments, function ( req, res ) {
res.status( 200 ).send( wrap( 'Segments',
filingCabinet.segments.list( PATH.show.segment ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.segments );
// Display a segment.
app.get( PATH.show.segment + '/:key', function ( req, res ) {
var key = PATH.unsafe( req.params[ 'key' ] );
res.status( 200 ).send( wrap( 'Segment: ' + show( key ),
filingCabinet.segments.show( key ) +
backTo( PATH.list.segments ) ) );
} );
logger.routeAdded( PATH.show.segment );
// Lists all contents.
app.get( PATH.list.contents, function ( req, res ) {
res.status( 200 ).send( wrap( 'Contents',
filingCabinet.contents.list( PATH.show.content ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.contents );
// Display a content.
app.get( PATH.show.content + '/:language/:key', function ( req, res ) {
var language = req.params[ 'language' ];
var key = PATH.unsafe( req.params[ 'key' ] );
res.status( 200 ).send( wrap( 'Content: ' + show( key ),
filingCabinet.contents.show( language, key ) +
backTo( PATH.list.contents ) ) );
} );
logger.routeAdded( PATH.show.content );
// Lists all menus.
app.get( PATH.list.menus, function ( req, res ) {
res.status( 200 ).send( wrap( 'Menus',
filingCabinet.menus.list( PATH.show.menu ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.menus );
// Display a menu.
app.get( PATH.show.menu + '/:language/:key', function ( req, res ) {
var language = req.params[ 'language' ];
var key = req.params[ 'key' ];
var result = filingCabinet.menus.show( language, +key );
res.status( 200 ).send( wrap( 'Menu: ' + show( result.title ),
result.list +
backTo( PATH.list.menus ) ) );
} );
logger.routeAdded( PATH.show.menu );
// Lists all locales.
app.get( PATH.list.locales, function ( req, res ) {
res.status( 200 ).send( wrap( 'Locales',
filingCabinet.locales.list( filingCabinet.languages ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.locales );
// Lists all references.
app.get( PATH.list.references, function ( req, res ) {
res.status( 200 ).send( wrap( 'References',
filingCabinet.references.list( PATH.show.reference ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.references );
// Display a reference.
app.get( PATH.show.reference + '/:key', function ( req, res ) {
var key = PATH.unsafe( req.params[ 'key' ] );
res.status( 200 ).send( wrap( 'Reference: ' + show( key ),
filingCabinet.references.show( key ) +
backTo( PATH.list.references ) ) );
} );
logger.routeAdded( PATH.show.reference );
// Lists all controls.
app.get( PATH.list.controls, function ( req, res ) {
res.status( 200 ).send( wrap( 'Controls',
filingCabinet.controls.list( PATH.show.control ) +
backToRoot() ) );
} );
logger.routeAdded( PATH.list.controls );
// Display a control.
app.get( PATH.show.control + '/:key', function ( req, res ) {
var key = PATH.unsafe( req.params[ 'key' ] );
res.status( 200 ).send( wrap( 'Control: ' + show( key ),
filingCabinet.controls.show( key ) +
backTo( PATH.list.controls ) ) );
} );
logger.routeAdded( PATH.show.control );
} | [
"function",
"setDeveloperRoutes",
"(",
"app",
",",
"filingCabinet",
",",
"paths",
",",
"develop",
")",
"{",
"var",
"head",
"=",
"'\\n'",
"+",
"\\n",
"+",
"' <link rel=\"stylesheet\" href=\"'",
"+",
"develop",
".",
"cssBootstrap",
"+",
"'\" />\\n'",
"+",
"\\n",
"+",
"' <link rel=\"stylesheet\" href=\"'",
";",
"develop",
".",
"cssHighlight",
"'\">\\n'",
"\\n",
"var",
"foot",
"=",
"'\\n'",
"+",
"\\n",
"+",
"' <script src=\"'",
"+",
"develop",
".",
"jsJQuery",
"+",
"'\"></script>\\n'",
"+",
"\\n",
"+",
"' <script src=\"'",
"+",
"develop",
".",
"jsBootstrap",
"+",
"'\"></script>\\n'",
"+",
"\\n",
"+",
"' <script src=\"'",
";",
"develop",
".",
"jsHighlight",
"'\"></script>\\n'",
"\\n",
"' <script>hljs.initHighlightingOnLoad();</script>\\n'",
"\\n",
"function",
"wrap",
"(",
"title",
",",
"body",
")",
"{",
"return",
"'<html>\\n<head>'",
"+",
"\\n",
"+",
"head",
"+",
"'</head>\\n<style>\\n'",
"+",
"\\n",
"+",
"\\n",
"+",
"css",
"+",
"'\\n</style>\\n\\n'",
"+",
"\\n",
"+",
"\\n",
"+",
"\\n",
"+",
"'<h1>'",
"+",
"title",
"+",
"'</h1>\\n'",
"+",
"\\n",
"+",
"'<p><i>'",
";",
"}",
"pkgInfo",
".",
"name",
"' v'",
"pkgInfo",
".",
"version",
"'</i></p>\\n'",
"\\n",
"body",
"foot",
"'\\n</body>\\n</html>\\n'",
"\\n",
"\\n",
"\\n",
"PATH",
".",
"init",
"(",
"paths",
".",
"develop",
")",
";",
"app",
".",
"get",
"(",
"PATH",
".",
"root",
",",
"function",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"status",
"(",
"200",
")",
".",
"send",
"(",
"wrap",
"(",
"'Resources'",
",",
"'<ul>\\n'",
"+",
"\\n",
"+",
"' <li><a href=\"'",
"+",
"PATH",
".",
"list",
".",
"languages",
"+",
"'\">Languages</a></li>\\n'",
"+",
"\\n",
"+",
"' <li><a href=\"'",
"+",
"PATH",
".",
"list",
".",
"documents",
"+",
"'\">Documents</a></li>\\n'",
"+",
"\\n",
"+",
"' <li><a href=\"'",
"+",
"PATH",
".",
"list",
".",
"layouts",
"+",
"'\">Layouts</a></li>\\n'",
"+",
"\\n",
"+",
"' <li><a href=\"'",
"+",
"PATH",
".",
"list",
".",
"segments",
"+",
"'\">Segments</a></li>\\n'",
"+",
"\\n",
"+",
"' <li><a href=\"'",
"+",
"PATH",
".",
"list",
".",
"contents",
"+",
"'\">Contents</a></li>\\n'",
"+",
"\\n",
"+",
"' <li><a href=\"'",
"+",
"PATH",
".",
"list",
".",
"menus",
"+",
"'\">Menus</a></li>\\n'",
"+",
"\\n",
"+",
"' <li><a href=\"'",
"+",
"PATH",
".",
"list",
".",
"locales",
"+",
"'\">Locales</a></li>\\n'",
"+",
"\\n",
")",
")",
";",
"}",
")",
";",
"' <li><a href=\"'",
"PATH",
".",
"list",
".",
"references",
"'\">References</a></li>\\n'",
"\\n",
"' <li><a href=\"'",
"PATH",
".",
"list",
".",
"controls",
"'\">Controls</a></li>\\n'",
"\\n",
"'</ul>\\n'",
"\\n",
"'<p><a class=\"btn btn-success\" href=\"/\">Go to site</a></p>\\n'",
"\\n",
"logger",
".",
"routeAdded",
"(",
"PATH",
".",
"root",
")",
";",
"app",
".",
"get",
"(",
"PATH",
".",
"list",
".",
"languages",
",",
"function",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"status",
"(",
"200",
")",
".",
"send",
"(",
"wrap",
"(",
"'Languages'",
",",
"filingCabinet",
".",
"listLanguages",
"(",
")",
"+",
"backToRoot",
"(",
")",
")",
")",
";",
"}",
")",
";",
"}"
] | Sets the helper routes to support development.
@param {Express.Application} app - The express.js application object.
@param {FilingCabinet} filingCabinet - The file manager object.
@param {object} paths - The configuration paths. | [
"Sets",
"the",
"helper",
"routes",
"to",
"support",
"development",
"."
] | 1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784 | https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/utilities/r-and-d.js#L30-L208 | train |
ansuz/ansuzjs | ansuz.js | function(){ // the generator we will return
var res=f(); // get the first result
if(cond(res)&&failed){ // if we've failed twice, then we're done
return; // return an undefined result
}else if(cond(res)){ // otherwise, if we fail, try moving on
f=function(){return next();} // now use the second list
failed=true; // but remember that we failed once
return fn(); // return the next element
}else
return res; // otherwise, we must have a good result, return it
} | javascript | function(){ // the generator we will return
var res=f(); // get the first result
if(cond(res)&&failed){ // if we've failed twice, then we're done
return; // return an undefined result
}else if(cond(res)){ // otherwise, if we fail, try moving on
f=function(){return next();} // now use the second list
failed=true; // but remember that we failed once
return fn(); // return the next element
}else
return res; // otherwise, we must have a good result, return it
} | [
"function",
"(",
")",
"{",
"var",
"res",
"=",
"f",
"(",
")",
";",
"if",
"(",
"cond",
"(",
"res",
")",
"&&",
"failed",
")",
"{",
"return",
";",
"}",
"else",
"if",
"(",
"cond",
"(",
"res",
")",
")",
"{",
"f",
"=",
"function",
"(",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"failed",
"=",
"true",
";",
"return",
"fn",
"(",
")",
";",
"}",
"else",
"return",
"res",
";",
"}"
] | this keeps us from an infinite loop | [
"this",
"keeps",
"us",
"from",
"an",
"infinite",
"loop"
] | d029cb8d33315eec2ec5a6b8a581b27640d0c19f | https://github.com/ansuz/ansuzjs/blob/d029cb8d33315eec2ec5a6b8a581b27640d0c19f/ansuz.js#L562-L572 | train |
|
ansuz/ansuzjs | ansuz.js | function(){ // the main generator you'll return
var res=kid(); // call the child function and store the result
if(cond(res)&&failed){ // if both generators have failed
return done(); // then you're done
}else if(cond(res)){ // if just the child has failed
par(); // regenerate the child array
return fn(); // return the next child value
}else{ // otherwise..
return [temp,res]; // return combined parent and child values
}
} | javascript | function(){ // the main generator you'll return
var res=kid(); // call the child function and store the result
if(cond(res)&&failed){ // if both generators have failed
return done(); // then you're done
}else if(cond(res)){ // if just the child has failed
par(); // regenerate the child array
return fn(); // return the next child value
}else{ // otherwise..
return [temp,res]; // return combined parent and child values
}
} | [
"function",
"(",
")",
"{",
"var",
"res",
"=",
"kid",
"(",
")",
";",
"if",
"(",
"cond",
"(",
"res",
")",
"&&",
"failed",
")",
"{",
"return",
"done",
"(",
")",
";",
"}",
"else",
"if",
"(",
"cond",
"(",
"res",
")",
")",
"{",
"par",
"(",
")",
";",
"return",
"fn",
"(",
")",
";",
"}",
"else",
"{",
"return",
"[",
"temp",
",",
"res",
"]",
";",
"}",
"}"
] | now that the parent handler is defined, increment it | [
"now",
"that",
"the",
"parent",
"handler",
"is",
"defined",
"increment",
"it"
] | d029cb8d33315eec2ec5a6b8a581b27640d0c19f | https://github.com/ansuz/ansuzjs/blob/d029cb8d33315eec2ec5a6b8a581b27640d0c19f/ansuz.js#L610-L620 | train |
|
fin-hypergrid/fin-hypergrid-sorting-plugin | mix-ins/behavior.js | removeHiddenColumns | function removeHiddenColumns(oldSorted, hiddenColumns){
var dirty = false;
oldSorted.forEach(function(i) {
var j = 0,
colIndex;
while (j < hiddenColumns.length) {
colIndex = hiddenColumns[j].index + 1; //hack to get around 0 index
if (colIndex === i) {
hiddenColumns[j].unSort();
dirty = true;
break;
}
j++;
}
});
return dirty;
} | javascript | function removeHiddenColumns(oldSorted, hiddenColumns){
var dirty = false;
oldSorted.forEach(function(i) {
var j = 0,
colIndex;
while (j < hiddenColumns.length) {
colIndex = hiddenColumns[j].index + 1; //hack to get around 0 index
if (colIndex === i) {
hiddenColumns[j].unSort();
dirty = true;
break;
}
j++;
}
});
return dirty;
} | [
"function",
"removeHiddenColumns",
"(",
"oldSorted",
",",
"hiddenColumns",
")",
"{",
"var",
"dirty",
"=",
"false",
";",
"oldSorted",
".",
"forEach",
"(",
"function",
"(",
"i",
")",
"{",
"var",
"j",
"=",
"0",
",",
"colIndex",
";",
"while",
"(",
"j",
"<",
"hiddenColumns",
".",
"length",
")",
"{",
"colIndex",
"=",
"hiddenColumns",
"[",
"j",
"]",
".",
"index",
"+",
"1",
";",
"if",
"(",
"colIndex",
"===",
"i",
")",
"{",
"hiddenColumns",
"[",
"j",
"]",
".",
"unSort",
"(",
")",
";",
"dirty",
"=",
"true",
";",
"break",
";",
"}",
"j",
"++",
";",
"}",
"}",
")",
";",
"return",
"dirty",
";",
"}"
] | Logic to moved to adapter layer outside of Hypergrid Core | [
"Logic",
"to",
"moved",
"to",
"adapter",
"layer",
"outside",
"of",
"Hypergrid",
"Core"
] | 008242e2d5b7b0d250eed83eaf692cbcdb9f8687 | https://github.com/fin-hypergrid/fin-hypergrid-sorting-plugin/blob/008242e2d5b7b0d250eed83eaf692cbcdb9f8687/mix-ins/behavior.js#L29-L45 | train |
codekirei/columnize-array | lib/methods/solve.js | solve | function solve() {
while (true) {
// establish vars for current loop
//----------------------------------------------------------
const row = this.state.i % this.state.rows
const col = Math.floor(this.state.i / this.state.rows)
const str = this.props.ar[this.state.i]
const len = str.length
const tooLong = len > this.props.maxRowLen
// str is too long ? set rows to maximum
//----------------------------------------------------------
if (tooLong && this.state.rows !== this.props.arLen) {
this.bindState(this.props.arLen)
continue
}
// at new col ? indent previous col
//----------------------------------------------------------
if (row === 0 && this.state.i !== 0) {
const prevCol = col - 1
const reqLen = this.state.widths[prevCol] + this.props.gap.len
this.state.indices.forEach((ar, i) => {
const prevLen = this.props.ar[ar[prevCol]].length
const diff = reqLen - prevLen
this.state.strs[i] += this.props.gap.ch.repeat(diff)
})
}
// add str to row
//----------------------------------------------------------
this.state.strs[row] += str
// row not too long ? update state : reset state with rows + 1
//----------------------------------------------------------
if (
this.state.strs[row].length <= this.props.maxRowLen ||
tooLong
) {
if (len > this.state.widths[col]) this.state.widths[col] = len
this.state.indices[row].push(this.state.i)
this.state.i++
}
else this.bindState(this.state.rows + 1)
// solution reached ? exit loop
//----------------------------------------------------------
if (this.state.i === this.props.arLen) break
}
} | javascript | function solve() {
while (true) {
// establish vars for current loop
//----------------------------------------------------------
const row = this.state.i % this.state.rows
const col = Math.floor(this.state.i / this.state.rows)
const str = this.props.ar[this.state.i]
const len = str.length
const tooLong = len > this.props.maxRowLen
// str is too long ? set rows to maximum
//----------------------------------------------------------
if (tooLong && this.state.rows !== this.props.arLen) {
this.bindState(this.props.arLen)
continue
}
// at new col ? indent previous col
//----------------------------------------------------------
if (row === 0 && this.state.i !== 0) {
const prevCol = col - 1
const reqLen = this.state.widths[prevCol] + this.props.gap.len
this.state.indices.forEach((ar, i) => {
const prevLen = this.props.ar[ar[prevCol]].length
const diff = reqLen - prevLen
this.state.strs[i] += this.props.gap.ch.repeat(diff)
})
}
// add str to row
//----------------------------------------------------------
this.state.strs[row] += str
// row not too long ? update state : reset state with rows + 1
//----------------------------------------------------------
if (
this.state.strs[row].length <= this.props.maxRowLen ||
tooLong
) {
if (len > this.state.widths[col]) this.state.widths[col] = len
this.state.indices[row].push(this.state.i)
this.state.i++
}
else this.bindState(this.state.rows + 1)
// solution reached ? exit loop
//----------------------------------------------------------
if (this.state.i === this.props.arLen) break
}
} | [
"function",
"solve",
"(",
")",
"{",
"while",
"(",
"true",
")",
"{",
"const",
"row",
"=",
"this",
".",
"state",
".",
"i",
"%",
"this",
".",
"state",
".",
"rows",
"const",
"col",
"=",
"Math",
".",
"floor",
"(",
"this",
".",
"state",
".",
"i",
"/",
"this",
".",
"state",
".",
"rows",
")",
"const",
"str",
"=",
"this",
".",
"props",
".",
"ar",
"[",
"this",
".",
"state",
".",
"i",
"]",
"const",
"len",
"=",
"str",
".",
"length",
"const",
"tooLong",
"=",
"len",
">",
"this",
".",
"props",
".",
"maxRowLen",
"if",
"(",
"tooLong",
"&&",
"this",
".",
"state",
".",
"rows",
"!==",
"this",
".",
"props",
".",
"arLen",
")",
"{",
"this",
".",
"bindState",
"(",
"this",
".",
"props",
".",
"arLen",
")",
"continue",
"}",
"if",
"(",
"row",
"===",
"0",
"&&",
"this",
".",
"state",
".",
"i",
"!==",
"0",
")",
"{",
"const",
"prevCol",
"=",
"col",
"-",
"1",
"const",
"reqLen",
"=",
"this",
".",
"state",
".",
"widths",
"[",
"prevCol",
"]",
"+",
"this",
".",
"props",
".",
"gap",
".",
"len",
"this",
".",
"state",
".",
"indices",
".",
"forEach",
"(",
"(",
"ar",
",",
"i",
")",
"=>",
"{",
"const",
"prevLen",
"=",
"this",
".",
"props",
".",
"ar",
"[",
"ar",
"[",
"prevCol",
"]",
"]",
".",
"length",
"const",
"diff",
"=",
"reqLen",
"-",
"prevLen",
"this",
".",
"state",
".",
"strs",
"[",
"i",
"]",
"+=",
"this",
".",
"props",
".",
"gap",
".",
"ch",
".",
"repeat",
"(",
"diff",
")",
"}",
")",
"}",
"this",
".",
"state",
".",
"strs",
"[",
"row",
"]",
"+=",
"str",
"if",
"(",
"this",
".",
"state",
".",
"strs",
"[",
"row",
"]",
".",
"length",
"<=",
"this",
".",
"props",
".",
"maxRowLen",
"||",
"tooLong",
")",
"{",
"if",
"(",
"len",
">",
"this",
".",
"state",
".",
"widths",
"[",
"col",
"]",
")",
"this",
".",
"state",
".",
"widths",
"[",
"col",
"]",
"=",
"len",
"this",
".",
"state",
".",
"indices",
"[",
"row",
"]",
".",
"push",
"(",
"this",
".",
"state",
".",
"i",
")",
"this",
".",
"state",
".",
"i",
"++",
"}",
"else",
"this",
".",
"bindState",
"(",
"this",
".",
"state",
".",
"rows",
"+",
"1",
")",
"if",
"(",
"this",
".",
"state",
".",
"i",
"===",
"this",
".",
"props",
".",
"arLen",
")",
"break",
"}",
"}"
] | Iteratively solves columnization given constraints in props.
Solution is captured by this.state.
@returns {undefined} | [
"Iteratively",
"solves",
"columnization",
"given",
"constraints",
"in",
"props",
".",
"Solution",
"is",
"captured",
"by",
"this",
".",
"state",
"."
] | ba100d1d9cf707fa249a58fa177d6b26ec131278 | https://github.com/codekirei/columnize-array/blob/ba100d1d9cf707fa249a58fa177d6b26ec131278/lib/methods/solve.js#L9-L59 | train |
avigoldman/fuse-email | lib/index.js | isInvalidInboundAddress | function isInvalidInboundAddress(inboundAddress) {
if (fuse.config.restrict_inbound === false)
return false;
return cleanAddress(inboundAddress) !== fuse.config.inbound_address;
} | javascript | function isInvalidInboundAddress(inboundAddress) {
if (fuse.config.restrict_inbound === false)
return false;
return cleanAddress(inboundAddress) !== fuse.config.inbound_address;
} | [
"function",
"isInvalidInboundAddress",
"(",
"inboundAddress",
")",
"{",
"if",
"(",
"fuse",
".",
"config",
".",
"restrict_inbound",
"===",
"false",
")",
"return",
"false",
";",
"return",
"cleanAddress",
"(",
"inboundAddress",
")",
"!==",
"fuse",
".",
"config",
".",
"inbound_address",
";",
"}"
] | returns boolean on if the recieving email is accepted
@param {string} inboundAddress | [
"returns",
"boolean",
"on",
"if",
"the",
"recieving",
"email",
"is",
"accepted"
] | ebb44934d7be8ce95d2aff30c5a94505a06e34eb | https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/index.js#L270-L275 | train |
avigoldman/fuse-email | lib/index.js | getEventType | function getEventType(inboundMessage) {
let recipientAddresses = _.map(inboundMessage.recipients, 'email');
let ccAddresses = _.map(inboundMessage.cc, 'email');
if (_.max([recipientAddresses.indexOf(fuse.config.inbound_address),
recipientAddresses.indexOf(inboundMessage.to.email)]) >= 0) {
return 'direct_email';
}
else if (_.max([ccAddresses.indexOf(fuse.config.inbound_address),
ccAddresses.indexOf(inboundMessage.to.email)]) >= 0) {
return 'cc_email';
}
else {
return 'bcc_email';
}
} | javascript | function getEventType(inboundMessage) {
let recipientAddresses = _.map(inboundMessage.recipients, 'email');
let ccAddresses = _.map(inboundMessage.cc, 'email');
if (_.max([recipientAddresses.indexOf(fuse.config.inbound_address),
recipientAddresses.indexOf(inboundMessage.to.email)]) >= 0) {
return 'direct_email';
}
else if (_.max([ccAddresses.indexOf(fuse.config.inbound_address),
ccAddresses.indexOf(inboundMessage.to.email)]) >= 0) {
return 'cc_email';
}
else {
return 'bcc_email';
}
} | [
"function",
"getEventType",
"(",
"inboundMessage",
")",
"{",
"let",
"recipientAddresses",
"=",
"_",
".",
"map",
"(",
"inboundMessage",
".",
"recipients",
",",
"'email'",
")",
";",
"let",
"ccAddresses",
"=",
"_",
".",
"map",
"(",
"inboundMessage",
".",
"cc",
",",
"'email'",
")",
";",
"if",
"(",
"_",
".",
"max",
"(",
"[",
"recipientAddresses",
".",
"indexOf",
"(",
"fuse",
".",
"config",
".",
"inbound_address",
")",
",",
"recipientAddresses",
".",
"indexOf",
"(",
"inboundMessage",
".",
"to",
".",
"email",
")",
"]",
")",
">=",
"0",
")",
"{",
"return",
"'direct_email'",
";",
"}",
"else",
"if",
"(",
"_",
".",
"max",
"(",
"[",
"ccAddresses",
".",
"indexOf",
"(",
"fuse",
".",
"config",
".",
"inbound_address",
")",
",",
"ccAddresses",
".",
"indexOf",
"(",
"inboundMessage",
".",
"to",
".",
"email",
")",
"]",
")",
">=",
"0",
")",
"{",
"return",
"'cc_email'",
";",
"}",
"else",
"{",
"return",
"'bcc_email'",
";",
"}",
"}"
] | returns a string with the event type of this message
@param {InboundMessage} inboundMessage
@returns {string} eventType | [
"returns",
"a",
"string",
"with",
"the",
"event",
"type",
"of",
"this",
"message"
] | ebb44934d7be8ce95d2aff30c5a94505a06e34eb | https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/index.js#L293-L308 | train |
avigoldman/fuse-email | lib/index.js | addFromAddress | function addFromAddress(inboundMessage, outboundMessage) {
if (inboundMessage && _.has(inboundMessage, 'from')) {
outboundMessage.recipients = outboundMessage.recipients || [];
outboundMessage.recipients.push(inboundMessage.from);
}
return outboundMessage;
} | javascript | function addFromAddress(inboundMessage, outboundMessage) {
if (inboundMessage && _.has(inboundMessage, 'from')) {
outboundMessage.recipients = outboundMessage.recipients || [];
outboundMessage.recipients.push(inboundMessage.from);
}
return outboundMessage;
} | [
"function",
"addFromAddress",
"(",
"inboundMessage",
",",
"outboundMessage",
")",
"{",
"if",
"(",
"inboundMessage",
"&&",
"_",
".",
"has",
"(",
"inboundMessage",
",",
"'from'",
")",
")",
"{",
"outboundMessage",
".",
"recipients",
"=",
"outboundMessage",
".",
"recipients",
"||",
"[",
"]",
";",
"outboundMessage",
".",
"recipients",
".",
"push",
"(",
"inboundMessage",
".",
"from",
")",
";",
"}",
"return",
"outboundMessage",
";",
"}"
] | gets the address that sent the inbound message and adds it as a recipient to the outbound message
@param {InboundMessage} inboundMessage
@param {OutboundMessage} outboundMessage
@returns {OutboundMessage} outboundMessage | [
"gets",
"the",
"address",
"that",
"sent",
"the",
"inbound",
"message",
"and",
"adds",
"it",
"as",
"a",
"recipient",
"to",
"the",
"outbound",
"message"
] | ebb44934d7be8ce95d2aff30c5a94505a06e34eb | https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/index.js#L323-L331 | train |
avigoldman/fuse-email | lib/index.js | defaultConfiguration | function defaultConfiguration(config) {
config = _.defaults({}, config, {
name: 'Sparky',
endpoint: '/relay',
convos: [],
sending_address: config.address,
inbound_address: config.address,
transport: 'sparkpost',
restrict_inbound: true,
logger: 'verbose',
size_limit: '50mb'
});
config.address = cleanAddress(config.address);
config.sending_address = cleanAddress(config.sending_address);
config.inbound_address = cleanAddress(config.inbound_address);
config.logger = _.isString(config.logger) ? require('./logger')(config.logger) : config.logger;
return config;
} | javascript | function defaultConfiguration(config) {
config = _.defaults({}, config, {
name: 'Sparky',
endpoint: '/relay',
convos: [],
sending_address: config.address,
inbound_address: config.address,
transport: 'sparkpost',
restrict_inbound: true,
logger: 'verbose',
size_limit: '50mb'
});
config.address = cleanAddress(config.address);
config.sending_address = cleanAddress(config.sending_address);
config.inbound_address = cleanAddress(config.inbound_address);
config.logger = _.isString(config.logger) ? require('./logger')(config.logger) : config.logger;
return config;
} | [
"function",
"defaultConfiguration",
"(",
"config",
")",
"{",
"config",
"=",
"_",
".",
"defaults",
"(",
"{",
"}",
",",
"config",
",",
"{",
"name",
":",
"'Sparky'",
",",
"endpoint",
":",
"'/relay'",
",",
"convos",
":",
"[",
"]",
",",
"sending_address",
":",
"config",
".",
"address",
",",
"inbound_address",
":",
"config",
".",
"address",
",",
"transport",
":",
"'sparkpost'",
",",
"restrict_inbound",
":",
"true",
",",
"logger",
":",
"'verbose'",
",",
"size_limit",
":",
"'50mb'",
"}",
")",
";",
"config",
".",
"address",
"=",
"cleanAddress",
"(",
"config",
".",
"address",
")",
";",
"config",
".",
"sending_address",
"=",
"cleanAddress",
"(",
"config",
".",
"sending_address",
")",
";",
"config",
".",
"inbound_address",
"=",
"cleanAddress",
"(",
"config",
".",
"inbound_address",
")",
";",
"config",
".",
"logger",
"=",
"_",
".",
"isString",
"(",
"config",
".",
"logger",
")",
"?",
"require",
"(",
"'./logger'",
")",
"(",
"config",
".",
"logger",
")",
":",
"config",
".",
"logger",
";",
"return",
"config",
";",
"}"
] | generate the config
@param {Object} config - the given config
@returns {Configuration} config | [
"generate",
"the",
"config"
] | ebb44934d7be8ce95d2aff30c5a94505a06e34eb | https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/index.js#L380-L400 | train |
enmasseio/babble | lib/block/Decision.js | Decision | function Decision (arg1, arg2) {
var decision, choices;
if (!(this instanceof Decision)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (typeof arg1 === 'function') {
decision = arg1;
choices = arg2;
}
else {
decision = null;
choices = arg1;
}
if (decision) {
if (typeof decision !== 'function') {
throw new TypeError('Parameter decision must be a function');
}
}
else {
decision = function (message, context) {
return message;
}
}
if (choices && (typeof choices === 'function')) {
throw new TypeError('Parameter choices must be an object');
}
this.decision = decision;
this.choices = {};
// append all choices
if (choices) {
var me = this;
Object.keys(choices).forEach(function (id) {
me.addChoice(id, choices[id]);
});
}
} | javascript | function Decision (arg1, arg2) {
var decision, choices;
if (!(this instanceof Decision)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (typeof arg1 === 'function') {
decision = arg1;
choices = arg2;
}
else {
decision = null;
choices = arg1;
}
if (decision) {
if (typeof decision !== 'function') {
throw new TypeError('Parameter decision must be a function');
}
}
else {
decision = function (message, context) {
return message;
}
}
if (choices && (typeof choices === 'function')) {
throw new TypeError('Parameter choices must be an object');
}
this.decision = decision;
this.choices = {};
// append all choices
if (choices) {
var me = this;
Object.keys(choices).forEach(function (id) {
me.addChoice(id, choices[id]);
});
}
} | [
"function",
"Decision",
"(",
"arg1",
",",
"arg2",
")",
"{",
"var",
"decision",
",",
"choices",
";",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Decision",
")",
")",
"{",
"throw",
"new",
"SyntaxError",
"(",
"'Constructor must be called with the new operator'",
")",
";",
"}",
"if",
"(",
"typeof",
"arg1",
"===",
"'function'",
")",
"{",
"decision",
"=",
"arg1",
";",
"choices",
"=",
"arg2",
";",
"}",
"else",
"{",
"decision",
"=",
"null",
";",
"choices",
"=",
"arg1",
";",
"}",
"if",
"(",
"decision",
")",
"{",
"if",
"(",
"typeof",
"decision",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Parameter decision must be a function'",
")",
";",
"}",
"}",
"else",
"{",
"decision",
"=",
"function",
"(",
"message",
",",
"context",
")",
"{",
"return",
"message",
";",
"}",
"}",
"if",
"(",
"choices",
"&&",
"(",
"typeof",
"choices",
"===",
"'function'",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Parameter choices must be an object'",
")",
";",
"}",
"this",
".",
"decision",
"=",
"decision",
";",
"this",
".",
"choices",
"=",
"{",
"}",
";",
"if",
"(",
"choices",
")",
"{",
"var",
"me",
"=",
"this",
";",
"Object",
".",
"keys",
"(",
"choices",
")",
".",
"forEach",
"(",
"function",
"(",
"id",
")",
"{",
"me",
".",
"addChoice",
"(",
"id",
",",
"choices",
"[",
"id",
"]",
")",
";",
"}",
")",
";",
"}",
"}"
] | extend Block with function then
Decision
A decision is made by executing the provided callback function, which returns
a next control flow block.
Syntax:
new Decision(choices)
new Decision(decision, choices)
Where:
{Function | Object} [decision]
When a `decision` function is provided, the
function is invoked as decision(message, context),
where `message` is the output from the previous
block in the chain, and `context` is an object
where state can be stored during a conversation.
The function must return the id for the next
block in the control flow, which must be
available in the provided `choices`.
If `decision` is not provided, the next block
will be mapped directly from the message.
{Object.<String, Block>} choices
A map with the possible next blocks in the flow
The next block is selected by the id returned
by the decision function.
There is one special id for choices: 'default'. This id is called when either
the decision function returns an id which does not match any of the available
choices.
@param arg1
@param arg2
@constructor
@extends {Block} | [
"extend",
"Block",
"with",
"function",
"then",
"Decision",
"A",
"decision",
"is",
"made",
"by",
"executing",
"the",
"provided",
"callback",
"function",
"which",
"returns",
"a",
"next",
"control",
"flow",
"block",
"."
] | 6b7e84d7fb0df2d1129f0646b37a9d89d3da2539 | https://github.com/enmasseio/babble/blob/6b7e84d7fb0df2d1129f0646b37a9d89d3da2539/lib/block/Decision.js#L46-L87 | train |
kant2002/crowdin-cli | api.js | function (projectName, files, params, callback) {
if (callback === undefined) {
callback = params;
params = {};
}
var filesInformation = {};
files.forEach(function (fileName) {
var index = "files[" + fileName + "]";
filesInformation[index] = fs.createReadStream(fileName);
});
return postApiCallWithFormData('project/' + projectName + '/add-file', extend(filesInformation, params), callback);
} | javascript | function (projectName, files, params, callback) {
if (callback === undefined) {
callback = params;
params = {};
}
var filesInformation = {};
files.forEach(function (fileName) {
var index = "files[" + fileName + "]";
filesInformation[index] = fs.createReadStream(fileName);
});
return postApiCallWithFormData('project/' + projectName + '/add-file', extend(filesInformation, params), callback);
} | [
"function",
"(",
"projectName",
",",
"files",
",",
"params",
",",
"callback",
")",
"{",
"if",
"(",
"callback",
"===",
"undefined",
")",
"{",
"callback",
"=",
"params",
";",
"params",
"=",
"{",
"}",
";",
"}",
"var",
"filesInformation",
"=",
"{",
"}",
";",
"files",
".",
"forEach",
"(",
"function",
"(",
"fileName",
")",
"{",
"var",
"index",
"=",
"\"files[\"",
"+",
"fileName",
"+",
"\"]\"",
";",
"filesInformation",
"[",
"index",
"]",
"=",
"fs",
".",
"createReadStream",
"(",
"fileName",
")",
";",
"}",
")",
";",
"return",
"postApiCallWithFormData",
"(",
"'project/'",
"+",
"projectName",
"+",
"'/add-file'",
",",
"extend",
"(",
"filesInformation",
",",
"params",
")",
",",
"callback",
")",
";",
"}"
] | Add new file to Crowdin project
@param projectName {String} Should contain the project identifier
@param files {Array} Files array that should be added to Crowdin project.
Array keys should contain file names with path in Crowdin project.
Note! 20 files max are allowed to upload per one time file transfer.
@param params {Object} Information about uploaded files.
@param callback {Function} Callback to call on function completition. | [
"Add",
"new",
"file",
"to",
"Crowdin",
"project"
] | b15df0715c4e6ae7d5447fd418af94dfe4dbb7a3 | https://github.com/kant2002/crowdin-cli/blob/b15df0715c4e6ae7d5447fd418af94dfe4dbb7a3/api.js#L132-L146 | train |
|
kant2002/crowdin-cli | api.js | function (projectName, fileNameOrStream, callback) {
if (typeof fileNameOrStream === "string") {
fileNameOrStream = fs.createReadStream(fileNameOrStream);
}
return postApiCallWithFormData('project/' + projectName + '/upload-glossary', { file: fileNameOrStream }, callback);
} | javascript | function (projectName, fileNameOrStream, callback) {
if (typeof fileNameOrStream === "string") {
fileNameOrStream = fs.createReadStream(fileNameOrStream);
}
return postApiCallWithFormData('project/' + projectName + '/upload-glossary', { file: fileNameOrStream }, callback);
} | [
"function",
"(",
"projectName",
",",
"fileNameOrStream",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"fileNameOrStream",
"===",
"\"string\"",
")",
"{",
"fileNameOrStream",
"=",
"fs",
".",
"createReadStream",
"(",
"fileNameOrStream",
")",
";",
"}",
"return",
"postApiCallWithFormData",
"(",
"'project/'",
"+",
"projectName",
"+",
"'/upload-glossary'",
",",
"{",
"file",
":",
"fileNameOrStream",
"}",
",",
"callback",
")",
";",
"}"
] | Upload your glossaries for Crowdin Project in TBX file format.
@param projectName {String} Should contain the project identifier.
@param fileNameOrStream {String} Name of the file to upload or stream which contains file to upload.
@param callback {Function} Callback to call on function completition. | [
"Upload",
"your",
"glossaries",
"for",
"Crowdin",
"Project",
"in",
"TBX",
"file",
"format",
"."
] | b15df0715c4e6ae7d5447fd418af94dfe4dbb7a3 | https://github.com/kant2002/crowdin-cli/blob/b15df0715c4e6ae7d5447fd418af94dfe4dbb7a3/api.js#L298-L304 | train |
|
treojs/idb-request | src/index.js | handleError | function handleError(reject) {
return (e) => {
// prevent global error throw https://bugzilla.mozilla.org/show_bug.cgi?id=872873
if (typeof e.preventDefault === 'function') e.preventDefault()
reject(e.target.error)
}
} | javascript | function handleError(reject) {
return (e) => {
// prevent global error throw https://bugzilla.mozilla.org/show_bug.cgi?id=872873
if (typeof e.preventDefault === 'function') e.preventDefault()
reject(e.target.error)
}
} | [
"function",
"handleError",
"(",
"reject",
")",
"{",
"return",
"(",
"e",
")",
"=>",
"{",
"if",
"(",
"typeof",
"e",
".",
"preventDefault",
"===",
"'function'",
")",
"e",
".",
"preventDefault",
"(",
")",
"reject",
"(",
"e",
".",
"target",
".",
"error",
")",
"}",
"}"
] | Helper to handle errors and call `reject`.
@param {Function} reject - from Promise constructor
@return {Function} | [
"Helper",
"to",
"handle",
"errors",
"and",
"call",
"reject",
"."
] | 123794d051387c54fab1a9d4371554f0872f5d0b | https://github.com/treojs/idb-request/blob/123794d051387c54fab1a9d4371554f0872f5d0b/src/index.js#L98-L104 | train |
juttle/juttle-viz | src/views/text.js | function(newData, limit) {
if ((this.buffer.length + newData.length) > options.limit) {
this.buffer = this.buffer.concat(newData.slice(0, options.limit - this.buffer.length));
self._sendDisplayLimitReachedMessage(limit);
}
else {
this.buffer = this.buffer.concat(newData);
}
} | javascript | function(newData, limit) {
if ((this.buffer.length + newData.length) > options.limit) {
this.buffer = this.buffer.concat(newData.slice(0, options.limit - this.buffer.length));
self._sendDisplayLimitReachedMessage(limit);
}
else {
this.buffer = this.buffer.concat(newData);
}
} | [
"function",
"(",
"newData",
",",
"limit",
")",
"{",
"if",
"(",
"(",
"this",
".",
"buffer",
".",
"length",
"+",
"newData",
".",
"length",
")",
">",
"options",
".",
"limit",
")",
"{",
"this",
".",
"buffer",
"=",
"this",
".",
"buffer",
".",
"concat",
"(",
"newData",
".",
"slice",
"(",
"0",
",",
"options",
".",
"limit",
"-",
"this",
".",
"buffer",
".",
"length",
")",
")",
";",
"self",
".",
"_sendDisplayLimitReachedMessage",
"(",
"limit",
")",
";",
"}",
"else",
"{",
"this",
".",
"buffer",
"=",
"this",
".",
"buffer",
".",
"concat",
"(",
"newData",
")",
";",
"}",
"}"
] | Appends the new data to the buffer up to the current limit.
Sends a message if limit is reached.
@param {[type]} data [description]
@return {[type]} [description] | [
"Appends",
"the",
"new",
"data",
"to",
"the",
"buffer",
"up",
"to",
"the",
"current",
"limit",
".",
"Sends",
"a",
"message",
"if",
"limit",
"is",
"reached",
"."
] | 834d13a66256d9c9177f46968b0ef05b8143e762 | https://github.com/juttle/juttle-viz/blob/834d13a66256d9c9177f46968b0ef05b8143e762/src/views/text.js#L74-L82 | train |
|
dowjones/distribucache-redis-store | src/util.js | addReconnectOnReadonly | function addReconnectOnReadonly(cfg) {
const noop = () => false;
const userReconn = (typeof cfg.reconnectOnError === 'function') ? cfg.reconnectOnError : noop;
cfg.reconnectOnError = err => {
const shouldReconnect = (isReadonlyError(err) || userReconn(err)) ? 2 : false;
if (shouldReconnect) console.warn(RECONNECT_WARNING);
return shouldReconnect;
};
} | javascript | function addReconnectOnReadonly(cfg) {
const noop = () => false;
const userReconn = (typeof cfg.reconnectOnError === 'function') ? cfg.reconnectOnError : noop;
cfg.reconnectOnError = err => {
const shouldReconnect = (isReadonlyError(err) || userReconn(err)) ? 2 : false;
if (shouldReconnect) console.warn(RECONNECT_WARNING);
return shouldReconnect;
};
} | [
"function",
"addReconnectOnReadonly",
"(",
"cfg",
")",
"{",
"const",
"noop",
"=",
"(",
")",
"=>",
"false",
";",
"const",
"userReconn",
"=",
"(",
"typeof",
"cfg",
".",
"reconnectOnError",
"===",
"'function'",
")",
"?",
"cfg",
".",
"reconnectOnError",
":",
"noop",
";",
"cfg",
".",
"reconnectOnError",
"=",
"err",
"=>",
"{",
"const",
"shouldReconnect",
"=",
"(",
"isReadonlyError",
"(",
"err",
")",
"||",
"userReconn",
"(",
"err",
")",
")",
"?",
"2",
":",
"false",
";",
"if",
"(",
"shouldReconnect",
")",
"console",
".",
"warn",
"(",
"RECONNECT_WARNING",
")",
";",
"return",
"shouldReconnect",
";",
"}",
";",
"}"
] | This is necessary for the store to handle the case when
another master is selected in ElastiCache, while
connecting to the Primary Endpoint.
@see https://github.com/dowjones/distribucache-redis-store/issues/3
@see https://github.com/luin/ioredis#reconnect-on-error | [
"This",
"is",
"necessary",
"for",
"the",
"store",
"to",
"handle",
"the",
"case",
"when",
"another",
"master",
"is",
"selected",
"in",
"ElastiCache",
"while",
"connecting",
"to",
"the",
"Primary",
"Endpoint",
"."
] | 25bd7b9cf790cd1f15920fc98b5732d7f2b8548f | https://github.com/dowjones/distribucache-redis-store/blob/25bd7b9cf790cd1f15920fc98b5732d7f2b8548f/src/util.js#L97-L105 | train |
doggan/three-debug-draw | index.js | _drawLine | function _drawLine(v0, v1, color) {
var p = new Primitive();
p.vertices = [v0, v1];
p.color = toColor(color);
renderer.addPrimitive(p);
} | javascript | function _drawLine(v0, v1, color) {
var p = new Primitive();
p.vertices = [v0, v1];
p.color = toColor(color);
renderer.addPrimitive(p);
} | [
"function",
"_drawLine",
"(",
"v0",
",",
"v1",
",",
"color",
")",
"{",
"var",
"p",
"=",
"new",
"Primitive",
"(",
")",
";",
"p",
".",
"vertices",
"=",
"[",
"v0",
",",
"v1",
"]",
";",
"p",
".",
"color",
"=",
"toColor",
"(",
"color",
")",
";",
"renderer",
".",
"addPrimitive",
"(",
"p",
")",
";",
"}"
] | Draws a single line from v0 to v1 with the given color.
Each point is a THREE.Vector3 object. | [
"Draws",
"a",
"single",
"line",
"from",
"v0",
"to",
"v1",
"with",
"the",
"given",
"color",
"."
] | d5640ebb4e704a875348e8f88a8ee988ea041f14 | https://github.com/doggan/three-debug-draw/blob/d5640ebb4e704a875348e8f88a8ee988ea041f14/index.js#L44-L51 | train |
doggan/three-debug-draw | index.js | _drawArrow | function _drawArrow(pStart, pEnd, arrowSize, color) {
var p = new Primitive();
p.color = toColor(color);
p.vertices.push(pStart);
p.vertices.push(pEnd);
var dir = new THREE.Vector3();
dir.subVectors(pEnd, pStart);
dir.normalize();
var right = new THREE.Vector3();
var dot = dir.dot(UNIT_Y);
if (dot > 0.99 || dot < -0.99) {
right.crossVectors(dir, UNIT_X);
} else {
right.crossVectors(dir, UNIT_Y);
}
var top = new THREE.Vector3();
top.crossVectors(right, dir);
dir.multiplyScalar(arrowSize);
right.multiplyScalar(arrowSize);
top.multiplyScalar(arrowSize);
// Right slant.
var tmp = new THREE.Vector3();
p.vertices.push(pEnd);
p.vertices.push(tmp.addVectors(pEnd, right).sub(dir));
// Left slant.
tmp = new THREE.Vector3();
p.vertices.push(pEnd);
p.vertices.push(tmp.subVectors(pEnd, right).sub(dir));
// Top slant.
tmp = new THREE.Vector3();
p.vertices.push(pEnd);
p.vertices.push(tmp.addVectors(pEnd, top).sub(dir));
// Bottom slant.
tmp = new THREE.Vector3();
p.vertices.push(pEnd);
p.vertices.push(tmp.subVectors(pEnd, top).sub(dir));
renderer.addPrimitive(p);
} | javascript | function _drawArrow(pStart, pEnd, arrowSize, color) {
var p = new Primitive();
p.color = toColor(color);
p.vertices.push(pStart);
p.vertices.push(pEnd);
var dir = new THREE.Vector3();
dir.subVectors(pEnd, pStart);
dir.normalize();
var right = new THREE.Vector3();
var dot = dir.dot(UNIT_Y);
if (dot > 0.99 || dot < -0.99) {
right.crossVectors(dir, UNIT_X);
} else {
right.crossVectors(dir, UNIT_Y);
}
var top = new THREE.Vector3();
top.crossVectors(right, dir);
dir.multiplyScalar(arrowSize);
right.multiplyScalar(arrowSize);
top.multiplyScalar(arrowSize);
// Right slant.
var tmp = new THREE.Vector3();
p.vertices.push(pEnd);
p.vertices.push(tmp.addVectors(pEnd, right).sub(dir));
// Left slant.
tmp = new THREE.Vector3();
p.vertices.push(pEnd);
p.vertices.push(tmp.subVectors(pEnd, right).sub(dir));
// Top slant.
tmp = new THREE.Vector3();
p.vertices.push(pEnd);
p.vertices.push(tmp.addVectors(pEnd, top).sub(dir));
// Bottom slant.
tmp = new THREE.Vector3();
p.vertices.push(pEnd);
p.vertices.push(tmp.subVectors(pEnd, top).sub(dir));
renderer.addPrimitive(p);
} | [
"function",
"_drawArrow",
"(",
"pStart",
",",
"pEnd",
",",
"arrowSize",
",",
"color",
")",
"{",
"var",
"p",
"=",
"new",
"Primitive",
"(",
")",
";",
"p",
".",
"color",
"=",
"toColor",
"(",
"color",
")",
";",
"p",
".",
"vertices",
".",
"push",
"(",
"pStart",
")",
";",
"p",
".",
"vertices",
".",
"push",
"(",
"pEnd",
")",
";",
"var",
"dir",
"=",
"new",
"THREE",
".",
"Vector3",
"(",
")",
";",
"dir",
".",
"subVectors",
"(",
"pEnd",
",",
"pStart",
")",
";",
"dir",
".",
"normalize",
"(",
")",
";",
"var",
"right",
"=",
"new",
"THREE",
".",
"Vector3",
"(",
")",
";",
"var",
"dot",
"=",
"dir",
".",
"dot",
"(",
"UNIT_Y",
")",
";",
"if",
"(",
"dot",
">",
"0.99",
"||",
"dot",
"<",
"-",
"0.99",
")",
"{",
"right",
".",
"crossVectors",
"(",
"dir",
",",
"UNIT_X",
")",
";",
"}",
"else",
"{",
"right",
".",
"crossVectors",
"(",
"dir",
",",
"UNIT_Y",
")",
";",
"}",
"var",
"top",
"=",
"new",
"THREE",
".",
"Vector3",
"(",
")",
";",
"top",
".",
"crossVectors",
"(",
"right",
",",
"dir",
")",
";",
"dir",
".",
"multiplyScalar",
"(",
"arrowSize",
")",
";",
"right",
".",
"multiplyScalar",
"(",
"arrowSize",
")",
";",
"top",
".",
"multiplyScalar",
"(",
"arrowSize",
")",
";",
"var",
"tmp",
"=",
"new",
"THREE",
".",
"Vector3",
"(",
")",
";",
"p",
".",
"vertices",
".",
"push",
"(",
"pEnd",
")",
";",
"p",
".",
"vertices",
".",
"push",
"(",
"tmp",
".",
"addVectors",
"(",
"pEnd",
",",
"right",
")",
".",
"sub",
"(",
"dir",
")",
")",
";",
"tmp",
"=",
"new",
"THREE",
".",
"Vector3",
"(",
")",
";",
"p",
".",
"vertices",
".",
"push",
"(",
"pEnd",
")",
";",
"p",
".",
"vertices",
".",
"push",
"(",
"tmp",
".",
"subVectors",
"(",
"pEnd",
",",
"right",
")",
".",
"sub",
"(",
"dir",
")",
")",
";",
"tmp",
"=",
"new",
"THREE",
".",
"Vector3",
"(",
")",
";",
"p",
".",
"vertices",
".",
"push",
"(",
"pEnd",
")",
";",
"p",
".",
"vertices",
".",
"push",
"(",
"tmp",
".",
"addVectors",
"(",
"pEnd",
",",
"top",
")",
".",
"sub",
"(",
"dir",
")",
")",
";",
"tmp",
"=",
"new",
"THREE",
".",
"Vector3",
"(",
")",
";",
"p",
".",
"vertices",
".",
"push",
"(",
"pEnd",
")",
";",
"p",
".",
"vertices",
".",
"push",
"(",
"tmp",
".",
"subVectors",
"(",
"pEnd",
",",
"top",
")",
".",
"sub",
"(",
"dir",
")",
")",
";",
"renderer",
".",
"addPrimitive",
"(",
"p",
")",
";",
"}"
] | Draws an arrow pointing from pStart to pEnd.
Specify the size of the arrow with arrowSize. | [
"Draws",
"an",
"arrow",
"pointing",
"from",
"pStart",
"to",
"pEnd",
".",
"Specify",
"the",
"size",
"of",
"the",
"arrow",
"with",
"arrowSize",
"."
] | d5640ebb4e704a875348e8f88a8ee988ea041f14 | https://github.com/doggan/three-debug-draw/blob/d5640ebb4e704a875348e8f88a8ee988ea041f14/index.js#L76-L123 | train |
doggan/three-debug-draw | index.js | _drawSphere | function _drawSphere(pos, r, color) {
var p = new Primitive();
p.color = toColor(color);
// Decreasing these angles will increase complexity of sphere.
var dtheta = 35; var dphi = 35;
for (var theta = -90; theta <= (90 - dtheta); theta += dtheta) {
for (var phi = 0; phi <= (360 - dphi); phi += dphi) {
p.vertices.push(new THREE.Vector3(
pos.x + r * Math.cos(theta * DEG_TO_RAD) * Math.cos(phi * DEG_TO_RAD),
pos.y + r * Math.cos(theta * DEG_TO_RAD) * Math.sin(phi * DEG_TO_RAD),
pos.z + r * Math.sin(theta * DEG_TO_RAD)
));
p.vertices.push(new THREE.Vector3(
pos.x + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.cos(phi * DEG_TO_RAD),
pos.y + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.sin(phi * DEG_TO_RAD),
pos.z + r * Math.sin((theta + dtheta) * DEG_TO_RAD)
));
p.vertices.push(new THREE.Vector3(
pos.x + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.cos((phi + dphi) * DEG_TO_RAD),
pos.y + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.sin((phi + dphi) * DEG_TO_RAD),
pos.z + r * Math.sin((theta + dtheta) * DEG_TO_RAD)
));
if ((theta > -90) && (theta < 90)) {
p.vertices.push(new THREE.Vector3(
pos.x + r * Math.cos(theta * DEG_TO_RAD) * Math.cos((phi + dphi) * DEG_TO_RAD),
pos.y + r * Math.cos(theta * DEG_TO_RAD) * Math.sin((phi + dphi) * DEG_TO_RAD),
pos.z + r * Math.sin(theta * DEG_TO_RAD)
));
}
}
}
renderer.addPrimitive(p);
} | javascript | function _drawSphere(pos, r, color) {
var p = new Primitive();
p.color = toColor(color);
// Decreasing these angles will increase complexity of sphere.
var dtheta = 35; var dphi = 35;
for (var theta = -90; theta <= (90 - dtheta); theta += dtheta) {
for (var phi = 0; phi <= (360 - dphi); phi += dphi) {
p.vertices.push(new THREE.Vector3(
pos.x + r * Math.cos(theta * DEG_TO_RAD) * Math.cos(phi * DEG_TO_RAD),
pos.y + r * Math.cos(theta * DEG_TO_RAD) * Math.sin(phi * DEG_TO_RAD),
pos.z + r * Math.sin(theta * DEG_TO_RAD)
));
p.vertices.push(new THREE.Vector3(
pos.x + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.cos(phi * DEG_TO_RAD),
pos.y + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.sin(phi * DEG_TO_RAD),
pos.z + r * Math.sin((theta + dtheta) * DEG_TO_RAD)
));
p.vertices.push(new THREE.Vector3(
pos.x + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.cos((phi + dphi) * DEG_TO_RAD),
pos.y + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.sin((phi + dphi) * DEG_TO_RAD),
pos.z + r * Math.sin((theta + dtheta) * DEG_TO_RAD)
));
if ((theta > -90) && (theta < 90)) {
p.vertices.push(new THREE.Vector3(
pos.x + r * Math.cos(theta * DEG_TO_RAD) * Math.cos((phi + dphi) * DEG_TO_RAD),
pos.y + r * Math.cos(theta * DEG_TO_RAD) * Math.sin((phi + dphi) * DEG_TO_RAD),
pos.z + r * Math.sin(theta * DEG_TO_RAD)
));
}
}
}
renderer.addPrimitive(p);
} | [
"function",
"_drawSphere",
"(",
"pos",
",",
"r",
",",
"color",
")",
"{",
"var",
"p",
"=",
"new",
"Primitive",
"(",
")",
";",
"p",
".",
"color",
"=",
"toColor",
"(",
"color",
")",
";",
"var",
"dtheta",
"=",
"35",
";",
"var",
"dphi",
"=",
"35",
";",
"for",
"(",
"var",
"theta",
"=",
"-",
"90",
";",
"theta",
"<=",
"(",
"90",
"-",
"dtheta",
")",
";",
"theta",
"+=",
"dtheta",
")",
"{",
"for",
"(",
"var",
"phi",
"=",
"0",
";",
"phi",
"<=",
"(",
"360",
"-",
"dphi",
")",
";",
"phi",
"+=",
"dphi",
")",
"{",
"p",
".",
"vertices",
".",
"push",
"(",
"new",
"THREE",
".",
"Vector3",
"(",
"pos",
".",
"x",
"+",
"r",
"*",
"Math",
".",
"cos",
"(",
"theta",
"*",
"DEG_TO_RAD",
")",
"*",
"Math",
".",
"cos",
"(",
"phi",
"*",
"DEG_TO_RAD",
")",
",",
"pos",
".",
"y",
"+",
"r",
"*",
"Math",
".",
"cos",
"(",
"theta",
"*",
"DEG_TO_RAD",
")",
"*",
"Math",
".",
"sin",
"(",
"phi",
"*",
"DEG_TO_RAD",
")",
",",
"pos",
".",
"z",
"+",
"r",
"*",
"Math",
".",
"sin",
"(",
"theta",
"*",
"DEG_TO_RAD",
")",
")",
")",
";",
"p",
".",
"vertices",
".",
"push",
"(",
"new",
"THREE",
".",
"Vector3",
"(",
"pos",
".",
"x",
"+",
"r",
"*",
"Math",
".",
"cos",
"(",
"(",
"theta",
"+",
"dtheta",
")",
"*",
"DEG_TO_RAD",
")",
"*",
"Math",
".",
"cos",
"(",
"phi",
"*",
"DEG_TO_RAD",
")",
",",
"pos",
".",
"y",
"+",
"r",
"*",
"Math",
".",
"cos",
"(",
"(",
"theta",
"+",
"dtheta",
")",
"*",
"DEG_TO_RAD",
")",
"*",
"Math",
".",
"sin",
"(",
"phi",
"*",
"DEG_TO_RAD",
")",
",",
"pos",
".",
"z",
"+",
"r",
"*",
"Math",
".",
"sin",
"(",
"(",
"theta",
"+",
"dtheta",
")",
"*",
"DEG_TO_RAD",
")",
")",
")",
";",
"p",
".",
"vertices",
".",
"push",
"(",
"new",
"THREE",
".",
"Vector3",
"(",
"pos",
".",
"x",
"+",
"r",
"*",
"Math",
".",
"cos",
"(",
"(",
"theta",
"+",
"dtheta",
")",
"*",
"DEG_TO_RAD",
")",
"*",
"Math",
".",
"cos",
"(",
"(",
"phi",
"+",
"dphi",
")",
"*",
"DEG_TO_RAD",
")",
",",
"pos",
".",
"y",
"+",
"r",
"*",
"Math",
".",
"cos",
"(",
"(",
"theta",
"+",
"dtheta",
")",
"*",
"DEG_TO_RAD",
")",
"*",
"Math",
".",
"sin",
"(",
"(",
"phi",
"+",
"dphi",
")",
"*",
"DEG_TO_RAD",
")",
",",
"pos",
".",
"z",
"+",
"r",
"*",
"Math",
".",
"sin",
"(",
"(",
"theta",
"+",
"dtheta",
")",
"*",
"DEG_TO_RAD",
")",
")",
")",
";",
"if",
"(",
"(",
"theta",
">",
"-",
"90",
")",
"&&",
"(",
"theta",
"<",
"90",
")",
")",
"{",
"p",
".",
"vertices",
".",
"push",
"(",
"new",
"THREE",
".",
"Vector3",
"(",
"pos",
".",
"x",
"+",
"r",
"*",
"Math",
".",
"cos",
"(",
"theta",
"*",
"DEG_TO_RAD",
")",
"*",
"Math",
".",
"cos",
"(",
"(",
"phi",
"+",
"dphi",
")",
"*",
"DEG_TO_RAD",
")",
",",
"pos",
".",
"y",
"+",
"r",
"*",
"Math",
".",
"cos",
"(",
"theta",
"*",
"DEG_TO_RAD",
")",
"*",
"Math",
".",
"sin",
"(",
"(",
"phi",
"+",
"dphi",
")",
"*",
"DEG_TO_RAD",
")",
",",
"pos",
".",
"z",
"+",
"r",
"*",
"Math",
".",
"sin",
"(",
"theta",
"*",
"DEG_TO_RAD",
")",
")",
")",
";",
"}",
"}",
"}",
"renderer",
".",
"addPrimitive",
"(",
"p",
")",
";",
"}"
] | Draw a sphere at pos with radius r. | [
"Draw",
"a",
"sphere",
"at",
"pos",
"with",
"radius",
"r",
"."
] | d5640ebb4e704a875348e8f88a8ee988ea041f14 | https://github.com/doggan/three-debug-draw/blob/d5640ebb4e704a875348e8f88a8ee988ea041f14/index.js#L175-L213 | train |
lethexa/lethexa-motionpredict | lethexa-motionpredict.js | function(position, velocity, dt) {
return mf.add(position, mf.mulScalar(velocity, dt));
} | javascript | function(position, velocity, dt) {
return mf.add(position, mf.mulScalar(velocity, dt));
} | [
"function",
"(",
"position",
",",
"velocity",
",",
"dt",
")",
"{",
"return",
"mf",
".",
"add",
"(",
"position",
",",
"mf",
".",
"mulScalar",
"(",
"velocity",
",",
"dt",
")",
")",
";",
"}"
] | calculates the new position by speed and delta-time.
@method getPositionByVeloAndTime
@param position {Vector3d} The old position.
@param velocity {Velocity} The velocity.
@param dt {Number} The delta-time.
@return {Vector3d} The new position.
@for motionpredict | [
"calculates",
"the",
"new",
"position",
"by",
"speed",
"and",
"delta",
"-",
"time",
"."
] | 84095c2cca246c02d9931d501a10959f46f54cfa | https://github.com/lethexa/lethexa-motionpredict/blob/84095c2cca246c02d9931d501a10959f46f54cfa/lethexa-motionpredict.js#L21-L23 | train |
|
lethexa/lethexa-motionpredict | lethexa-motionpredict.js | function( p, q ) {
var wurzel = Math.sqrt((p * p / 4) - q);
var vorwurzel = (-p / 2);
var result = [];
if( wurzel > 0 ) {
result = [vorwurzel + wurzel, vorwurzel - wurzel];
}
else if( wurzel === 0 ) {
result = [vorwurzel];
}
return result;
} | javascript | function( p, q ) {
var wurzel = Math.sqrt((p * p / 4) - q);
var vorwurzel = (-p / 2);
var result = [];
if( wurzel > 0 ) {
result = [vorwurzel + wurzel, vorwurzel - wurzel];
}
else if( wurzel === 0 ) {
result = [vorwurzel];
}
return result;
} | [
"function",
"(",
"p",
",",
"q",
")",
"{",
"var",
"wurzel",
"=",
"Math",
".",
"sqrt",
"(",
"(",
"p",
"*",
"p",
"/",
"4",
")",
"-",
"q",
")",
";",
"var",
"vorwurzel",
"=",
"(",
"-",
"p",
"/",
"2",
")",
";",
"var",
"result",
"=",
"[",
"]",
";",
"if",
"(",
"wurzel",
">",
"0",
")",
"{",
"result",
"=",
"[",
"vorwurzel",
"+",
"wurzel",
",",
"vorwurzel",
"-",
"wurzel",
"]",
";",
"}",
"else",
"if",
"(",
"wurzel",
"===",
"0",
")",
"{",
"result",
"=",
"[",
"vorwurzel",
"]",
";",
"}",
"return",
"result",
";",
"}"
] | Solves the quadratic equation for p and q.
@method quadEquation
@param p {Number} The parameter p.
@param q {Number} The parameter q.
@return {Array} The result with zero, one or two solutions.
@for motionpredict | [
"Solves",
"the",
"quadratic",
"equation",
"for",
"p",
"and",
"q",
"."
] | 84095c2cca246c02d9931d501a10959f46f54cfa | https://github.com/lethexa/lethexa-motionpredict/blob/84095c2cca246c02d9931d501a10959f46f54cfa/lethexa-motionpredict.js#L34-L45 | train |
|
lethexa/lethexa-motionpredict | lethexa-motionpredict.js | function(myPos, myVelo, targetPos, targetVelo) {
var relTargetPos = mf.sub(targetPos, myPos);
var a = mf.lengthSquared(targetVelo) - myVelo * myVelo;
var b = 2.0 * mf.dot(targetVelo, relTargetPos);
var c = mf.lengthSquared(relTargetPos);
if( a === 0 ) {
if( b !== 0 ) {
var time = -c / b;
if( time > 0.0 )
return time;
}
}
else {
// P und Q berechnen...
var p = b / a;
var q = c / a;
// Quadratische Gleichung lösen...
var times = this.quadEquation(p, q);
if( times.length === 0 )
return [];
if( times.length === 2 ) {
var icptTime = Math.min(times[0], times[1]);
if( icptTime < 0.0 ) {
icptTime = Math.max(times[0], times[1]);
}
return icptTime;
}
else if( times.length === 1 ) {
if( times[0] >= 0.0 ) {
return times[0];
}
}
}
return undefined;
} | javascript | function(myPos, myVelo, targetPos, targetVelo) {
var relTargetPos = mf.sub(targetPos, myPos);
var a = mf.lengthSquared(targetVelo) - myVelo * myVelo;
var b = 2.0 * mf.dot(targetVelo, relTargetPos);
var c = mf.lengthSquared(relTargetPos);
if( a === 0 ) {
if( b !== 0 ) {
var time = -c / b;
if( time > 0.0 )
return time;
}
}
else {
// P und Q berechnen...
var p = b / a;
var q = c / a;
// Quadratische Gleichung lösen...
var times = this.quadEquation(p, q);
if( times.length === 0 )
return [];
if( times.length === 2 ) {
var icptTime = Math.min(times[0], times[1]);
if( icptTime < 0.0 ) {
icptTime = Math.max(times[0], times[1]);
}
return icptTime;
}
else if( times.length === 1 ) {
if( times[0] >= 0.0 ) {
return times[0];
}
}
}
return undefined;
} | [
"function",
"(",
"myPos",
",",
"myVelo",
",",
"targetPos",
",",
"targetVelo",
")",
"{",
"var",
"relTargetPos",
"=",
"mf",
".",
"sub",
"(",
"targetPos",
",",
"myPos",
")",
";",
"var",
"a",
"=",
"mf",
".",
"lengthSquared",
"(",
"targetVelo",
")",
"-",
"myVelo",
"*",
"myVelo",
";",
"var",
"b",
"=",
"2.0",
"*",
"mf",
".",
"dot",
"(",
"targetVelo",
",",
"relTargetPos",
")",
";",
"var",
"c",
"=",
"mf",
".",
"lengthSquared",
"(",
"relTargetPos",
")",
";",
"if",
"(",
"a",
"===",
"0",
")",
"{",
"if",
"(",
"b",
"!==",
"0",
")",
"{",
"var",
"time",
"=",
"-",
"c",
"/",
"b",
";",
"if",
"(",
"time",
">",
"0.0",
")",
"return",
"time",
";",
"}",
"}",
"else",
"{",
"var",
"p",
"=",
"b",
"/",
"a",
";",
"var",
"q",
"=",
"c",
"/",
"a",
";",
"var",
"times",
"=",
"this",
".",
"quadEquation",
"(",
"p",
",",
"q",
")",
";",
"if",
"(",
"times",
".",
"length",
"===",
"0",
")",
"return",
"[",
"]",
";",
"if",
"(",
"times",
".",
"length",
"===",
"2",
")",
"{",
"var",
"icptTime",
"=",
"Math",
".",
"min",
"(",
"times",
"[",
"0",
"]",
",",
"times",
"[",
"1",
"]",
")",
";",
"if",
"(",
"icptTime",
"<",
"0.0",
")",
"{",
"icptTime",
"=",
"Math",
".",
"max",
"(",
"times",
"[",
"0",
"]",
",",
"times",
"[",
"1",
"]",
")",
";",
"}",
"return",
"icptTime",
";",
"}",
"else",
"if",
"(",
"times",
".",
"length",
"===",
"1",
")",
"{",
"if",
"(",
"times",
"[",
"0",
"]",
">=",
"0.0",
")",
"{",
"return",
"times",
"[",
"0",
"]",
";",
"}",
"}",
"}",
"return",
"undefined",
";",
"}"
] | Calculates the intercepttime to the target at a given speed.
@method calcInterceptTime
@param myPos {Vector3d} The position of the interceptor.
@param myVelo {Number} The velocity at which the target should be intercepted.
@param targetPos {Vector3d} The position of the target.
@param targetVelo {Vector3d} The velocity and direction in which the target is moving.
@return {Number} The time from now at which the target is reached.
@for motionpredict | [
"Calculates",
"the",
"intercepttime",
"to",
"the",
"target",
"at",
"a",
"given",
"speed",
"."
] | 84095c2cca246c02d9931d501a10959f46f54cfa | https://github.com/lethexa/lethexa-motionpredict/blob/84095c2cca246c02d9931d501a10959f46f54cfa/lethexa-motionpredict.js#L115-L152 | train |
|
lethexa/lethexa-motionpredict | lethexa-motionpredict.js | function(myPos, myVelo, targetPos, targetVelo) {
var ticpt = this.calcInterceptTime(myPos, myVelo, targetPos, targetVelo);
if(ticpt === undefined)
return undefined;
return this.getPositionByVeloAndTime(targetPos, targetVelo, ticpt);
} | javascript | function(myPos, myVelo, targetPos, targetVelo) {
var ticpt = this.calcInterceptTime(myPos, myVelo, targetPos, targetVelo);
if(ticpt === undefined)
return undefined;
return this.getPositionByVeloAndTime(targetPos, targetVelo, ticpt);
} | [
"function",
"(",
"myPos",
",",
"myVelo",
",",
"targetPos",
",",
"targetVelo",
")",
"{",
"var",
"ticpt",
"=",
"this",
".",
"calcInterceptTime",
"(",
"myPos",
",",
"myVelo",
",",
"targetPos",
",",
"targetVelo",
")",
";",
"if",
"(",
"ticpt",
"===",
"undefined",
")",
"return",
"undefined",
";",
"return",
"this",
".",
"getPositionByVeloAndTime",
"(",
"targetPos",
",",
"targetVelo",
",",
"ticpt",
")",
";",
"}"
] | Calculates the intercept-position of the target.
@method calcInterceptPosition
@param myPos {Vector3d} The position of the interceptor.
@param myVelo {Number} The velocity at which the target should be intercepted.
@param targetPos {Vector3d} The position of the target.
@param targetVelo {Vector3d} The velocity and direction in which the target is moving.
@return {Vector3d} The position at which the target is reached.
@for motionpredict | [
"Calculates",
"the",
"intercept",
"-",
"position",
"of",
"the",
"target",
"."
] | 84095c2cca246c02d9931d501a10959f46f54cfa | https://github.com/lethexa/lethexa-motionpredict/blob/84095c2cca246c02d9931d501a10959f46f54cfa/lethexa-motionpredict.js#L165-L170 | train |
|
lethexa/lethexa-motionpredict | lethexa-motionpredict.js | function(myPos, myVelo, targetPos, targetVelo ) {
var distance = Math.sqrt(mf.lengthSquared(mf.sub(targetPos, myPos)));
var approachSpeed = this.calcApproachSpeed(myPos, myVelo, targetPos, targetVelo);
if( approachSpeed > 0.0 ) {
return distance / approachSpeed;
}
else {
return undefined;
}
} | javascript | function(myPos, myVelo, targetPos, targetVelo ) {
var distance = Math.sqrt(mf.lengthSquared(mf.sub(targetPos, myPos)));
var approachSpeed = this.calcApproachSpeed(myPos, myVelo, targetPos, targetVelo);
if( approachSpeed > 0.0 ) {
return distance / approachSpeed;
}
else {
return undefined;
}
} | [
"function",
"(",
"myPos",
",",
"myVelo",
",",
"targetPos",
",",
"targetVelo",
")",
"{",
"var",
"distance",
"=",
"Math",
".",
"sqrt",
"(",
"mf",
".",
"lengthSquared",
"(",
"mf",
".",
"sub",
"(",
"targetPos",
",",
"myPos",
")",
")",
")",
";",
"var",
"approachSpeed",
"=",
"this",
".",
"calcApproachSpeed",
"(",
"myPos",
",",
"myVelo",
",",
"targetPos",
",",
"targetVelo",
")",
";",
"if",
"(",
"approachSpeed",
">",
"0.0",
")",
"{",
"return",
"distance",
"/",
"approachSpeed",
";",
"}",
"else",
"{",
"return",
"undefined",
";",
"}",
"}"
] | Calculates the arrivaltime of the target to my position.
@method calcArrivalTime
@param myPos {Vector3d} The position of me.
@param myVelo {Vector3d} The velocity of me.
@param targetPos {Vector3d} The position of the target.
@param targetVelo {Vector3d} The velocity and direction in which the target is moving.
@return {Number} The time in which the target has reached me or undefined if not reachable.
@for motionpredict | [
"Calculates",
"the",
"arrivaltime",
"of",
"the",
"target",
"to",
"my",
"position",
"."
] | 84095c2cca246c02d9931d501a10959f46f54cfa | https://github.com/lethexa/lethexa-motionpredict/blob/84095c2cca246c02d9931d501a10959f46f54cfa/lethexa-motionpredict.js#L183-L192 | train |
|
lethexa/lethexa-motionpredict | lethexa-motionpredict.js | function(myPos, myVelo, targetPos, targetVelo) {
var posDiff = mf.sub(targetPos, myPos);
var veloDiff = mf.sub(targetVelo, myVelo);
var approachSpeed = mf.dot(posDiff, veloDiff);
var posDiffLength = Math.sqrt(mf.lengthSquared(posDiff));
if( posDiffLength <= 0.0 )
return 0.0;
return -approachSpeed / posDiffLength;
} | javascript | function(myPos, myVelo, targetPos, targetVelo) {
var posDiff = mf.sub(targetPos, myPos);
var veloDiff = mf.sub(targetVelo, myVelo);
var approachSpeed = mf.dot(posDiff, veloDiff);
var posDiffLength = Math.sqrt(mf.lengthSquared(posDiff));
if( posDiffLength <= 0.0 )
return 0.0;
return -approachSpeed / posDiffLength;
} | [
"function",
"(",
"myPos",
",",
"myVelo",
",",
"targetPos",
",",
"targetVelo",
")",
"{",
"var",
"posDiff",
"=",
"mf",
".",
"sub",
"(",
"targetPos",
",",
"myPos",
")",
";",
"var",
"veloDiff",
"=",
"mf",
".",
"sub",
"(",
"targetVelo",
",",
"myVelo",
")",
";",
"var",
"approachSpeed",
"=",
"mf",
".",
"dot",
"(",
"posDiff",
",",
"veloDiff",
")",
";",
"var",
"posDiffLength",
"=",
"Math",
".",
"sqrt",
"(",
"mf",
".",
"lengthSquared",
"(",
"posDiff",
")",
")",
";",
"if",
"(",
"posDiffLength",
"<=",
"0.0",
")",
"return",
"0.0",
";",
"return",
"-",
"approachSpeed",
"/",
"posDiffLength",
";",
"}"
] | Calculates the approachspeed of the target to my position.
@method calcApproachSpeed
@param myPos {Vector3d} The position of me.
@param myVelo {Vector3d} The velocity of me.
@param targetPos {Vector3d} The position of the target.
@param targetVelo {Vector3d} The velocity and direction in which the target is moving.
@return {Number} The speed at which the target is approaching.
@for motionpredict | [
"Calculates",
"the",
"approachspeed",
"of",
"the",
"target",
"to",
"my",
"position",
"."
] | 84095c2cca246c02d9931d501a10959f46f54cfa | https://github.com/lethexa/lethexa-motionpredict/blob/84095c2cca246c02d9931d501a10959f46f54cfa/lethexa-motionpredict.js#L205-L213 | train |
|
pattern-lab/patternengine-node-underscore | lib/engine_underscore.js | function (partialString) {
var edgeQuotesMatcher = /^["']|["']$/g;
var partialIDWithQuotes = partialString.replace(this.findPartialsRE, '$1');
var partialID = partialIDWithQuotes.replace(edgeQuotesMatcher, '');
return partialID;
} | javascript | function (partialString) {
var edgeQuotesMatcher = /^["']|["']$/g;
var partialIDWithQuotes = partialString.replace(this.findPartialsRE, '$1');
var partialID = partialIDWithQuotes.replace(edgeQuotesMatcher, '');
return partialID;
} | [
"function",
"(",
"partialString",
")",
"{",
"var",
"edgeQuotesMatcher",
"=",
"/",
"^[\"']|[\"']$",
"/",
"g",
";",
"var",
"partialIDWithQuotes",
"=",
"partialString",
".",
"replace",
"(",
"this",
".",
"findPartialsRE",
",",
"'$1'",
")",
";",
"var",
"partialID",
"=",
"partialIDWithQuotes",
".",
"replace",
"(",
"edgeQuotesMatcher",
",",
"''",
")",
";",
"return",
"partialID",
";",
"}"
] | given a pattern, and a partial string, tease out the "pattern key" and return it. | [
"given",
"a",
"pattern",
"and",
"a",
"partial",
"string",
"tease",
"out",
"the",
"pattern",
"key",
"and",
"return",
"it",
"."
] | 79ba1b4697f25cebf797bd46c5d9dc84937b4deb | https://github.com/pattern-lab/patternengine-node-underscore/blob/79ba1b4697f25cebf797bd46c5d9dc84937b4deb/lib/engine_underscore.js#L170-L176 | train |
|
avigoldman/fuse-email | lib/transports/transport.js | formatInboundRecipients | function formatInboundRecipients(recipients) {
return _.map(recipients, (recipient) => {
if (_.isString(recipient)) {
return {
email: recipient,
name: '',
};
}
else {
return {
email: recipient.address || '',
name: recipient.name || ''
}
}
});
} | javascript | function formatInboundRecipients(recipients) {
return _.map(recipients, (recipient) => {
if (_.isString(recipient)) {
return {
email: recipient,
name: '',
};
}
else {
return {
email: recipient.address || '',
name: recipient.name || ''
}
}
});
} | [
"function",
"formatInboundRecipients",
"(",
"recipients",
")",
"{",
"return",
"_",
".",
"map",
"(",
"recipients",
",",
"(",
"recipient",
")",
"=>",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"recipient",
")",
")",
"{",
"return",
"{",
"email",
":",
"recipient",
",",
"name",
":",
"''",
",",
"}",
";",
"}",
"else",
"{",
"return",
"{",
"email",
":",
"recipient",
".",
"address",
"||",
"''",
",",
"name",
":",
"recipient",
".",
"name",
"||",
"''",
"}",
"}",
"}",
")",
";",
"}"
] | takes an array of emails and formats them to the fuse recipient pattern
@param {string[]} recipients
@param {object[]} recipients | [
"takes",
"an",
"array",
"of",
"emails",
"and",
"formats",
"them",
"to",
"the",
"fuse",
"recipient",
"pattern"
] | ebb44934d7be8ce95d2aff30c5a94505a06e34eb | https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/transports/transport.js#L200-L215 | train |
binaryoung/laravel-elixir-vue-loader | index.js | function (webpackConfig, paths) {
var defaultWebpackConfig = {
output: {
filename: paths.output.name,
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
]
},
};
if (fs.existsSync('webpack.config.js')) {
var customWebpackConfig = require('./../../webpack.config.js');
defaultWebpackConfig = _.extend(defaultWebpackConfig, customWebpackConfig);
}
webpackConfig = _.extend(defaultWebpackConfig, webpackConfig);
if (!_.contains(webpackConfig.module.loaders, {test: /\.vue$/, loader: 'vue'})) {
webpackConfig.module.loaders.push({
test: /\.vue$/,
loader: 'vue'
});
}
if (config.sourcemaps) {
webpackConfig = _.defaults(
webpackConfig,
{devtool: '#source-map'}
);
}
if (config.production) {
var currPlugins = _.isArray(webpackConfig.plugins) ? webpackConfig.plugins : [];
webpackConfig.plugins = currPlugins.concat([new UglifyJsPlugin({sourceMap: false})]);
}
return webpackConfig;
} | javascript | function (webpackConfig, paths) {
var defaultWebpackConfig = {
output: {
filename: paths.output.name,
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
]
},
};
if (fs.existsSync('webpack.config.js')) {
var customWebpackConfig = require('./../../webpack.config.js');
defaultWebpackConfig = _.extend(defaultWebpackConfig, customWebpackConfig);
}
webpackConfig = _.extend(defaultWebpackConfig, webpackConfig);
if (!_.contains(webpackConfig.module.loaders, {test: /\.vue$/, loader: 'vue'})) {
webpackConfig.module.loaders.push({
test: /\.vue$/,
loader: 'vue'
});
}
if (config.sourcemaps) {
webpackConfig = _.defaults(
webpackConfig,
{devtool: '#source-map'}
);
}
if (config.production) {
var currPlugins = _.isArray(webpackConfig.plugins) ? webpackConfig.plugins : [];
webpackConfig.plugins = currPlugins.concat([new UglifyJsPlugin({sourceMap: false})]);
}
return webpackConfig;
} | [
"function",
"(",
"webpackConfig",
",",
"paths",
")",
"{",
"var",
"defaultWebpackConfig",
"=",
"{",
"output",
":",
"{",
"filename",
":",
"paths",
".",
"output",
".",
"name",
",",
"}",
",",
"module",
":",
"{",
"loaders",
":",
"[",
"{",
"test",
":",
"/",
"\\.vue$",
"/",
",",
"loader",
":",
"'vue'",
"}",
",",
"]",
"}",
",",
"}",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"'webpack.config.js'",
")",
")",
"{",
"var",
"customWebpackConfig",
"=",
"require",
"(",
"'./../../webpack.config.js'",
")",
";",
"defaultWebpackConfig",
"=",
"_",
".",
"extend",
"(",
"defaultWebpackConfig",
",",
"customWebpackConfig",
")",
";",
"}",
"webpackConfig",
"=",
"_",
".",
"extend",
"(",
"defaultWebpackConfig",
",",
"webpackConfig",
")",
";",
"if",
"(",
"!",
"_",
".",
"contains",
"(",
"webpackConfig",
".",
"module",
".",
"loaders",
",",
"{",
"test",
":",
"/",
"\\.vue$",
"/",
",",
"loader",
":",
"'vue'",
"}",
")",
")",
"{",
"webpackConfig",
".",
"module",
".",
"loaders",
".",
"push",
"(",
"{",
"test",
":",
"/",
"\\.vue$",
"/",
",",
"loader",
":",
"'vue'",
"}",
")",
";",
"}",
"if",
"(",
"config",
".",
"sourcemaps",
")",
"{",
"webpackConfig",
"=",
"_",
".",
"defaults",
"(",
"webpackConfig",
",",
"{",
"devtool",
":",
"'#source-map'",
"}",
")",
";",
"}",
"if",
"(",
"config",
".",
"production",
")",
"{",
"var",
"currPlugins",
"=",
"_",
".",
"isArray",
"(",
"webpackConfig",
".",
"plugins",
")",
"?",
"webpackConfig",
".",
"plugins",
":",
"[",
"]",
";",
"webpackConfig",
".",
"plugins",
"=",
"currPlugins",
".",
"concat",
"(",
"[",
"new",
"UglifyJsPlugin",
"(",
"{",
"sourceMap",
":",
"false",
"}",
")",
"]",
")",
";",
"}",
"return",
"webpackConfig",
";",
"}"
] | Handle webpack config such as sourcemaps and
minification or user's cunstom webpack config.
@param {object} options
@return {object} | [
"Handle",
"webpack",
"config",
"such",
"as",
"sourcemaps",
"and",
"minification",
"or",
"user",
"s",
"cunstom",
"webpack",
"config",
"."
] | 06ddb9c010f59917f0b9997df2fe9a26c444ab24 | https://github.com/binaryoung/laravel-elixir-vue-loader/blob/06ddb9c010f59917f0b9997df2fe9a26c444ab24/index.js#L63-L106 | train |
|
brockfanning/docpad-plugin-lunr | out/lunrdoc.js | function(index, placeholder) {
if (typeof this.config.indexes[index] === 'undefined') {
console.log('LUNR: getLunrSearchPage will not work unless you specify a valid index from plugins.lunr.indexes in your Docpad configuration file.');
return;
}
placeholder = placeholder || 'Search terms';
var scriptElements = '';
var dataFilename = this.config.indexes[index].indexFilename;
var scripts = ['lunr.min.js', dataFilename, 'lunr-ui.min.js'];
for (var i in scripts) {
scriptElements += '<script src="/lunr/' + scripts[i] +
'" type="text/javascript"></script>';
}
return '<input type="text" class="search-bar" id="lunr-input" placeholder="' + placeholder + '" />' +
'<input type="hidden" id="lunr-hidden" />' +
scriptElements;
} | javascript | function(index, placeholder) {
if (typeof this.config.indexes[index] === 'undefined') {
console.log('LUNR: getLunrSearchPage will not work unless you specify a valid index from plugins.lunr.indexes in your Docpad configuration file.');
return;
}
placeholder = placeholder || 'Search terms';
var scriptElements = '';
var dataFilename = this.config.indexes[index].indexFilename;
var scripts = ['lunr.min.js', dataFilename, 'lunr-ui.min.js'];
for (var i in scripts) {
scriptElements += '<script src="/lunr/' + scripts[i] +
'" type="text/javascript"></script>';
}
return '<input type="text" class="search-bar" id="lunr-input" placeholder="' + placeholder + '" />' +
'<input type="hidden" id="lunr-hidden" />' +
scriptElements;
} | [
"function",
"(",
"index",
",",
"placeholder",
")",
"{",
"if",
"(",
"typeof",
"this",
".",
"config",
".",
"indexes",
"[",
"index",
"]",
"===",
"'undefined'",
")",
"{",
"console",
".",
"log",
"(",
"'LUNR: getLunrSearchPage will not work unless you specify a valid index from plugins.lunr.indexes in your Docpad configuration file.'",
")",
";",
"return",
";",
"}",
"placeholder",
"=",
"placeholder",
"||",
"'Search terms'",
";",
"var",
"scriptElements",
"=",
"''",
";",
"var",
"dataFilename",
"=",
"this",
".",
"config",
".",
"indexes",
"[",
"index",
"]",
".",
"indexFilename",
";",
"var",
"scripts",
"=",
"[",
"'lunr.min.js'",
",",
"dataFilename",
",",
"'lunr-ui.min.js'",
"]",
";",
"for",
"(",
"var",
"i",
"in",
"scripts",
")",
"{",
"scriptElements",
"+=",
"'<script src=\"/lunr/'",
"+",
"scripts",
"[",
"i",
"]",
"+",
"'\" type=\"text/javascript\"></script>'",
";",
"}",
"return",
"'<input type=\"text\" class=\"search-bar\" id=\"lunr-input\" placeholder=\"'",
"+",
"placeholder",
"+",
"'\" />'",
"+",
"'<input type=\"hidden\" id=\"lunr-hidden\" />'",
"+",
"scriptElements",
";",
"}"
] | some helper functions we'll provide to the template | [
"some",
"helper",
"functions",
"we",
"ll",
"provide",
"to",
"the",
"template"
] | d5c23dda9e1ca5e0edbf87c26ef9035ddc840c50 | https://github.com/brockfanning/docpad-plugin-lunr/blob/d5c23dda9e1ca5e0edbf87c26ef9035ddc840c50/out/lunrdoc.js#L218-L234 | train |
|
dy/slidy | picker.js | handle2dkeys | function handle2dkeys (keys, value, step, min, max) {
//up and right - increase by one
if (keys[38]) {
value[1] = inc(value[1], plainify(step, 1), 1);
}
if (keys[39]) {
value[0] = inc(value[0], plainify(step, 0), 1);
}
if (keys[40]) {
value[1] = inc(value[1], plainify(step, 1), -1);
}
if (keys[37]) {
value[0] = inc(value[0], plainify(step, 0), -1);
}
//meta
var coordIdx = 1;
if (keys[18] || keys[91] || keys[17] || keys[16]) coordIdx = 0;
//home - min
if (keys[36]) {
value[coordIdx] = min[coordIdx];
}
//end - max
if (keys[35]) {
value[coordIdx] = max[coordIdx];
}
//pageup
if (keys[33]) {
value[coordIdx] = inc(value[coordIdx], plainify(step, coordIdx), PAGE);
}
//pagedown
if (keys[34]) {
value[coordIdx] = inc(value[coordIdx], plainify(step, coordIdx), -PAGE);
}
return value;
} | javascript | function handle2dkeys (keys, value, step, min, max) {
//up and right - increase by one
if (keys[38]) {
value[1] = inc(value[1], plainify(step, 1), 1);
}
if (keys[39]) {
value[0] = inc(value[0], plainify(step, 0), 1);
}
if (keys[40]) {
value[1] = inc(value[1], plainify(step, 1), -1);
}
if (keys[37]) {
value[0] = inc(value[0], plainify(step, 0), -1);
}
//meta
var coordIdx = 1;
if (keys[18] || keys[91] || keys[17] || keys[16]) coordIdx = 0;
//home - min
if (keys[36]) {
value[coordIdx] = min[coordIdx];
}
//end - max
if (keys[35]) {
value[coordIdx] = max[coordIdx];
}
//pageup
if (keys[33]) {
value[coordIdx] = inc(value[coordIdx], plainify(step, coordIdx), PAGE);
}
//pagedown
if (keys[34]) {
value[coordIdx] = inc(value[coordIdx], plainify(step, coordIdx), -PAGE);
}
return value;
} | [
"function",
"handle2dkeys",
"(",
"keys",
",",
"value",
",",
"step",
",",
"min",
",",
"max",
")",
"{",
"if",
"(",
"keys",
"[",
"38",
"]",
")",
"{",
"value",
"[",
"1",
"]",
"=",
"inc",
"(",
"value",
"[",
"1",
"]",
",",
"plainify",
"(",
"step",
",",
"1",
")",
",",
"1",
")",
";",
"}",
"if",
"(",
"keys",
"[",
"39",
"]",
")",
"{",
"value",
"[",
"0",
"]",
"=",
"inc",
"(",
"value",
"[",
"0",
"]",
",",
"plainify",
"(",
"step",
",",
"0",
")",
",",
"1",
")",
";",
"}",
"if",
"(",
"keys",
"[",
"40",
"]",
")",
"{",
"value",
"[",
"1",
"]",
"=",
"inc",
"(",
"value",
"[",
"1",
"]",
",",
"plainify",
"(",
"step",
",",
"1",
")",
",",
"-",
"1",
")",
";",
"}",
"if",
"(",
"keys",
"[",
"37",
"]",
")",
"{",
"value",
"[",
"0",
"]",
"=",
"inc",
"(",
"value",
"[",
"0",
"]",
",",
"plainify",
"(",
"step",
",",
"0",
")",
",",
"-",
"1",
")",
";",
"}",
"var",
"coordIdx",
"=",
"1",
";",
"if",
"(",
"keys",
"[",
"18",
"]",
"||",
"keys",
"[",
"91",
"]",
"||",
"keys",
"[",
"17",
"]",
"||",
"keys",
"[",
"16",
"]",
")",
"coordIdx",
"=",
"0",
";",
"if",
"(",
"keys",
"[",
"36",
"]",
")",
"{",
"value",
"[",
"coordIdx",
"]",
"=",
"min",
"[",
"coordIdx",
"]",
";",
"}",
"if",
"(",
"keys",
"[",
"35",
"]",
")",
"{",
"value",
"[",
"coordIdx",
"]",
"=",
"max",
"[",
"coordIdx",
"]",
";",
"}",
"if",
"(",
"keys",
"[",
"33",
"]",
")",
"{",
"value",
"[",
"coordIdx",
"]",
"=",
"inc",
"(",
"value",
"[",
"coordIdx",
"]",
",",
"plainify",
"(",
"step",
",",
"coordIdx",
")",
",",
"PAGE",
")",
";",
"}",
"if",
"(",
"keys",
"[",
"34",
"]",
")",
"{",
"value",
"[",
"coordIdx",
"]",
"=",
"inc",
"(",
"value",
"[",
"coordIdx",
"]",
",",
"plainify",
"(",
"step",
",",
"coordIdx",
")",
",",
"-",
"PAGE",
")",
";",
"}",
"return",
"value",
";",
"}"
] | Apply pressed keys on the 2d value | [
"Apply",
"pressed",
"keys",
"on",
"the",
"2d",
"value"
] | 18c57d07face0ea8f297060434fb1c13b33cd888 | https://github.com/dy/slidy/blob/18c57d07face0ea8f297060434fb1c13b33cd888/picker.js#L714-L755 | train |
dy/slidy | picker.js | handle1dkeys | function handle1dkeys (keys, value, step, min, max) {
step = step || 1;
//up and right - increase by one
if (keys[38] || keys[39]) {
value = inc(value, step, 1);
}
//down and left - decrease by one
if (keys[40] || keys[37]) {
value = inc(value, step, -1);
}
//home - min
if (keys[36]) {
value = min;
}
//end - max
if (keys[35]) {
value = max;
}
//pageup
if (keys[33]) {
value = inc(value, step, PAGE);
}
//pagedown
if (keys[34]) {
value = inc(value, step, -PAGE);
}
return value;
} | javascript | function handle1dkeys (keys, value, step, min, max) {
step = step || 1;
//up and right - increase by one
if (keys[38] || keys[39]) {
value = inc(value, step, 1);
}
//down and left - decrease by one
if (keys[40] || keys[37]) {
value = inc(value, step, -1);
}
//home - min
if (keys[36]) {
value = min;
}
//end - max
if (keys[35]) {
value = max;
}
//pageup
if (keys[33]) {
value = inc(value, step, PAGE);
}
//pagedown
if (keys[34]) {
value = inc(value, step, -PAGE);
}
return value;
} | [
"function",
"handle1dkeys",
"(",
"keys",
",",
"value",
",",
"step",
",",
"min",
",",
"max",
")",
"{",
"step",
"=",
"step",
"||",
"1",
";",
"if",
"(",
"keys",
"[",
"38",
"]",
"||",
"keys",
"[",
"39",
"]",
")",
"{",
"value",
"=",
"inc",
"(",
"value",
",",
"step",
",",
"1",
")",
";",
"}",
"if",
"(",
"keys",
"[",
"40",
"]",
"||",
"keys",
"[",
"37",
"]",
")",
"{",
"value",
"=",
"inc",
"(",
"value",
",",
"step",
",",
"-",
"1",
")",
";",
"}",
"if",
"(",
"keys",
"[",
"36",
"]",
")",
"{",
"value",
"=",
"min",
";",
"}",
"if",
"(",
"keys",
"[",
"35",
"]",
")",
"{",
"value",
"=",
"max",
";",
"}",
"if",
"(",
"keys",
"[",
"33",
"]",
")",
"{",
"value",
"=",
"inc",
"(",
"value",
",",
"step",
",",
"PAGE",
")",
";",
"}",
"if",
"(",
"keys",
"[",
"34",
"]",
")",
"{",
"value",
"=",
"inc",
"(",
"value",
",",
"step",
",",
"-",
"PAGE",
")",
";",
"}",
"return",
"value",
";",
"}"
] | Apply pressed keys on the 1d value | [
"Apply",
"pressed",
"keys",
"on",
"the",
"1d",
"value"
] | 18c57d07face0ea8f297060434fb1c13b33cd888 | https://github.com/dy/slidy/blob/18c57d07face0ea8f297060434fb1c13b33cd888/picker.js#L759-L793 | train |
juttle/juttle-viz | src/lib/generators/event-markers.js | function(el, options) {
// default options for the line
var defaults = require('../utils/default-options')();
// if we don't pass options, just
// make it an empty object
if (typeof options === 'undefined' ) {
options = {};
}
options = _.defaults(options, defaults);
this.width = options.width;
this.height = options.height;
this.margin = options.margin;
this.useMarkdown = options.useMarkdown;
this.el = el;
this._data = [];
this.selection = d3.select(el).append('g')
.attr('class', 'markerSeries');
if (options.clipId) {
this.selection.attr('clip-path', 'url(#' + options.clipId + ')');
}
this.xScale = function() {
throw new Error('X scale not set');
};
this.xfield = options.xfield;
this.xfieldFormat = options.xfieldFormat;
this.title = options.title;
this.text = options.text;
this.type = options.type;
// XXX wire this up
this.duration = options.duration || 250;
this.currentDatapoint = null;
this.draw_range = null;
} | javascript | function(el, options) {
// default options for the line
var defaults = require('../utils/default-options')();
// if we don't pass options, just
// make it an empty object
if (typeof options === 'undefined' ) {
options = {};
}
options = _.defaults(options, defaults);
this.width = options.width;
this.height = options.height;
this.margin = options.margin;
this.useMarkdown = options.useMarkdown;
this.el = el;
this._data = [];
this.selection = d3.select(el).append('g')
.attr('class', 'markerSeries');
if (options.clipId) {
this.selection.attr('clip-path', 'url(#' + options.clipId + ')');
}
this.xScale = function() {
throw new Error('X scale not set');
};
this.xfield = options.xfield;
this.xfieldFormat = options.xfieldFormat;
this.title = options.title;
this.text = options.text;
this.type = options.type;
// XXX wire this up
this.duration = options.duration || 250;
this.currentDatapoint = null;
this.draw_range = null;
} | [
"function",
"(",
"el",
",",
"options",
")",
"{",
"var",
"defaults",
"=",
"require",
"(",
"'../utils/default-options'",
")",
"(",
")",
";",
"if",
"(",
"typeof",
"options",
"===",
"'undefined'",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"options",
"=",
"_",
".",
"defaults",
"(",
"options",
",",
"defaults",
")",
";",
"this",
".",
"width",
"=",
"options",
".",
"width",
";",
"this",
".",
"height",
"=",
"options",
".",
"height",
";",
"this",
".",
"margin",
"=",
"options",
".",
"margin",
";",
"this",
".",
"useMarkdown",
"=",
"options",
".",
"useMarkdown",
";",
"this",
".",
"el",
"=",
"el",
";",
"this",
".",
"_data",
"=",
"[",
"]",
";",
"this",
".",
"selection",
"=",
"d3",
".",
"select",
"(",
"el",
")",
".",
"append",
"(",
"'g'",
")",
".",
"attr",
"(",
"'class'",
",",
"'markerSeries'",
")",
";",
"if",
"(",
"options",
".",
"clipId",
")",
"{",
"this",
".",
"selection",
".",
"attr",
"(",
"'clip-path'",
",",
"'url(#'",
"+",
"options",
".",
"clipId",
"+",
"')'",
")",
";",
"}",
"this",
".",
"xScale",
"=",
"function",
"(",
")",
"{",
"throw",
"new",
"Error",
"(",
"'X scale not set'",
")",
";",
"}",
";",
"this",
".",
"xfield",
"=",
"options",
".",
"xfield",
";",
"this",
".",
"xfieldFormat",
"=",
"options",
".",
"xfieldFormat",
";",
"this",
".",
"title",
"=",
"options",
".",
"title",
";",
"this",
".",
"text",
"=",
"options",
".",
"text",
";",
"this",
".",
"type",
"=",
"options",
".",
"type",
";",
"this",
".",
"duration",
"=",
"options",
".",
"duration",
"||",
"250",
";",
"this",
".",
"currentDatapoint",
"=",
"null",
";",
"this",
".",
"draw_range",
"=",
"null",
";",
"}"
] | event marker constructor | [
"event",
"marker",
"constructor"
] | 834d13a66256d9c9177f46968b0ef05b8143e762 | https://github.com/juttle/juttle-viz/blob/834d13a66256d9c9177f46968b0ef05b8143e762/src/lib/generators/event-markers.js#L11-L54 | train |
|
aspectron/iris-translator | lib/i18n.js | scanFolders | function scanFolders(rootFolderPath, folders, folderFileExtensions, callback) {
var result = [];
console.log('Scanning:: Folders', folders);
console.log('Scanning:: Root folder path', rootFolderPath);
var fileExtensions = self.fileExtensions.slice();
scanFolder();
function scanFolder() {
var folder = folders.shift();
if (folder === undefined) {
// console.log('Scanning:: Finished with result', result);
return callback(null, result);
}
if(folderFileExtensions.length){
fileExtensions = folderFileExtensions.shift();
}
//var path = rootFolderPath + '/' + folder;
var path = rootFolderPath + folder;
console.log('Scanning:: Full path to folder', path, fileExtensions);
fs.readdir(path, function (err, list) {
if (err) {
console.error("Error scanning folder: ", path);
return scanFolder();
}
var files = [];
for (var i = 0; i < list.length; i++) {
if (acceptFile(path, list[i], fileExtensions)) {
//files.push((folder.length ? folder + '/' : folder) + list[i]);
files.push(path + '/' + list[i]);
}
}
result = result.concat(files);
scanFolder();
});
}
} | javascript | function scanFolders(rootFolderPath, folders, folderFileExtensions, callback) {
var result = [];
console.log('Scanning:: Folders', folders);
console.log('Scanning:: Root folder path', rootFolderPath);
var fileExtensions = self.fileExtensions.slice();
scanFolder();
function scanFolder() {
var folder = folders.shift();
if (folder === undefined) {
// console.log('Scanning:: Finished with result', result);
return callback(null, result);
}
if(folderFileExtensions.length){
fileExtensions = folderFileExtensions.shift();
}
//var path = rootFolderPath + '/' + folder;
var path = rootFolderPath + folder;
console.log('Scanning:: Full path to folder', path, fileExtensions);
fs.readdir(path, function (err, list) {
if (err) {
console.error("Error scanning folder: ", path);
return scanFolder();
}
var files = [];
for (var i = 0; i < list.length; i++) {
if (acceptFile(path, list[i], fileExtensions)) {
//files.push((folder.length ? folder + '/' : folder) + list[i]);
files.push(path + '/' + list[i]);
}
}
result = result.concat(files);
scanFolder();
});
}
} | [
"function",
"scanFolders",
"(",
"rootFolderPath",
",",
"folders",
",",
"folderFileExtensions",
",",
"callback",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"console",
".",
"log",
"(",
"'Scanning:: Folders'",
",",
"folders",
")",
";",
"console",
".",
"log",
"(",
"'Scanning:: Root folder path'",
",",
"rootFolderPath",
")",
";",
"var",
"fileExtensions",
"=",
"self",
".",
"fileExtensions",
".",
"slice",
"(",
")",
";",
"scanFolder",
"(",
")",
";",
"function",
"scanFolder",
"(",
")",
"{",
"var",
"folder",
"=",
"folders",
".",
"shift",
"(",
")",
";",
"if",
"(",
"folder",
"===",
"undefined",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"result",
")",
";",
"}",
"if",
"(",
"folderFileExtensions",
".",
"length",
")",
"{",
"fileExtensions",
"=",
"folderFileExtensions",
".",
"shift",
"(",
")",
";",
"}",
"var",
"path",
"=",
"rootFolderPath",
"+",
"folder",
";",
"console",
".",
"log",
"(",
"'Scanning:: Full path to folder'",
",",
"path",
",",
"fileExtensions",
")",
";",
"fs",
".",
"readdir",
"(",
"path",
",",
"function",
"(",
"err",
",",
"list",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"\"Error scanning folder: \"",
",",
"path",
")",
";",
"return",
"scanFolder",
"(",
")",
";",
"}",
"var",
"files",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"list",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"acceptFile",
"(",
"path",
",",
"list",
"[",
"i",
"]",
",",
"fileExtensions",
")",
")",
"{",
"files",
".",
"push",
"(",
"path",
"+",
"'/'",
"+",
"list",
"[",
"i",
"]",
")",
";",
"}",
"}",
"result",
"=",
"result",
".",
"concat",
"(",
"files",
")",
";",
"scanFolder",
"(",
")",
";",
"}",
")",
";",
"}",
"}"
] | Private functions
Gets files from folders
@param rootFolderPath
@param folders {Array}
@param callback
@return {Array} array of files | [
"Private",
"functions",
"Gets",
"files",
"from",
"folders"
] | 3e09348f08274a0608e6b5b7f8c2b726639b31ba | https://github.com/aspectron/iris-translator/blob/3e09348f08274a0608e6b5b7f8c2b726639b31ba/lib/i18n.js#L342-L384 | train |
dy/slidy | index.js | Slidy | function Slidy(target, options) {
//force constructor
if (!(this instanceof Slidy)) return new Slidy(target, options);
var self = this;
//ensure target & options
if (!options) {
if (target instanceof Element) {
options = {};
}
else {
options = target;
target = doc.createElement('div');
}
}
//get preferred element
self.element = target;
//adopt options
extend(self, options);
//calculate value & step
//detect step automatically based on min/max range (1/100 by default)
//native behaviour is always 1, so ignore it
if (options.step === undefined) {
self.step = detectStep(self.min, self.max);
}
//calc undefined valuea as a middle of range
if (options.value === undefined) {
self.value = detectValue(self.min, self.max);
}
//bind passed callbacks, if any
if (options.created) on(self, 'created', options.created);
//save refrence
instancesCache.set(self.element, self);
//generate id
self.id = getUid();
self.ns = 'slidy-' + self.id;
if (!self.element.id) self.element.id = self.ns;
//init instance
self.element.classList.add('slidy');
//create pickers, if passed a list
self.pickers = [];
if (isArray(options.pickers) && options.pickers.length) {
options.pickers.forEach(function (opts) {
self.addPicker(opts);
});
}
//ensure at least one picker exists, if not passed in options separately
else if (!options.hasOwnProperty('pickers')) {
self.addPicker(options.pickers);
}
// Define value as active picker value getter
//FIXME: case of multiple pickers
Object.defineProperty(self, 'value', {
set: function (value) {
var picker = this.getActivePicker();
picker && (picker.value = value);
},
get: function () {
var picker = this.getActivePicker();
return picker && picker.value;
}
});
if (self.aria) {
//a11y
//@ref http://www.w3.org/TR/wai-aria/roles#slider
self.element.setAttribute('role', 'slider');
target.setAttribute('aria-valuemax', self.max);
target.setAttribute('aria-valuemin', self.min);
target.setAttribute('aria-orientation', self.orientation);
target.setAttribute('aria-atomic', true);
//update controls
target.setAttribute('aria-controls', self.pickers.map(
function (item) {
return item.element.id;
}).join(' '));
}
//turn on events etc
if (!self.element.hasAttribute('disabled')) self.enable();
//emit callback
self.emit('created');
} | javascript | function Slidy(target, options) {
//force constructor
if (!(this instanceof Slidy)) return new Slidy(target, options);
var self = this;
//ensure target & options
if (!options) {
if (target instanceof Element) {
options = {};
}
else {
options = target;
target = doc.createElement('div');
}
}
//get preferred element
self.element = target;
//adopt options
extend(self, options);
//calculate value & step
//detect step automatically based on min/max range (1/100 by default)
//native behaviour is always 1, so ignore it
if (options.step === undefined) {
self.step = detectStep(self.min, self.max);
}
//calc undefined valuea as a middle of range
if (options.value === undefined) {
self.value = detectValue(self.min, self.max);
}
//bind passed callbacks, if any
if (options.created) on(self, 'created', options.created);
//save refrence
instancesCache.set(self.element, self);
//generate id
self.id = getUid();
self.ns = 'slidy-' + self.id;
if (!self.element.id) self.element.id = self.ns;
//init instance
self.element.classList.add('slidy');
//create pickers, if passed a list
self.pickers = [];
if (isArray(options.pickers) && options.pickers.length) {
options.pickers.forEach(function (opts) {
self.addPicker(opts);
});
}
//ensure at least one picker exists, if not passed in options separately
else if (!options.hasOwnProperty('pickers')) {
self.addPicker(options.pickers);
}
// Define value as active picker value getter
//FIXME: case of multiple pickers
Object.defineProperty(self, 'value', {
set: function (value) {
var picker = this.getActivePicker();
picker && (picker.value = value);
},
get: function () {
var picker = this.getActivePicker();
return picker && picker.value;
}
});
if (self.aria) {
//a11y
//@ref http://www.w3.org/TR/wai-aria/roles#slider
self.element.setAttribute('role', 'slider');
target.setAttribute('aria-valuemax', self.max);
target.setAttribute('aria-valuemin', self.min);
target.setAttribute('aria-orientation', self.orientation);
target.setAttribute('aria-atomic', true);
//update controls
target.setAttribute('aria-controls', self.pickers.map(
function (item) {
return item.element.id;
}).join(' '));
}
//turn on events etc
if (!self.element.hasAttribute('disabled')) self.enable();
//emit callback
self.emit('created');
} | [
"function",
"Slidy",
"(",
"target",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Slidy",
")",
")",
"return",
"new",
"Slidy",
"(",
"target",
",",
"options",
")",
";",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"options",
")",
"{",
"if",
"(",
"target",
"instanceof",
"Element",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"else",
"{",
"options",
"=",
"target",
";",
"target",
"=",
"doc",
".",
"createElement",
"(",
"'div'",
")",
";",
"}",
"}",
"self",
".",
"element",
"=",
"target",
";",
"extend",
"(",
"self",
",",
"options",
")",
";",
"if",
"(",
"options",
".",
"step",
"===",
"undefined",
")",
"{",
"self",
".",
"step",
"=",
"detectStep",
"(",
"self",
".",
"min",
",",
"self",
".",
"max",
")",
";",
"}",
"if",
"(",
"options",
".",
"value",
"===",
"undefined",
")",
"{",
"self",
".",
"value",
"=",
"detectValue",
"(",
"self",
".",
"min",
",",
"self",
".",
"max",
")",
";",
"}",
"if",
"(",
"options",
".",
"created",
")",
"on",
"(",
"self",
",",
"'created'",
",",
"options",
".",
"created",
")",
";",
"instancesCache",
".",
"set",
"(",
"self",
".",
"element",
",",
"self",
")",
";",
"self",
".",
"id",
"=",
"getUid",
"(",
")",
";",
"self",
".",
"ns",
"=",
"'slidy-'",
"+",
"self",
".",
"id",
";",
"if",
"(",
"!",
"self",
".",
"element",
".",
"id",
")",
"self",
".",
"element",
".",
"id",
"=",
"self",
".",
"ns",
";",
"self",
".",
"element",
".",
"classList",
".",
"add",
"(",
"'slidy'",
")",
";",
"self",
".",
"pickers",
"=",
"[",
"]",
";",
"if",
"(",
"isArray",
"(",
"options",
".",
"pickers",
")",
"&&",
"options",
".",
"pickers",
".",
"length",
")",
"{",
"options",
".",
"pickers",
".",
"forEach",
"(",
"function",
"(",
"opts",
")",
"{",
"self",
".",
"addPicker",
"(",
"opts",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"!",
"options",
".",
"hasOwnProperty",
"(",
"'pickers'",
")",
")",
"{",
"self",
".",
"addPicker",
"(",
"options",
".",
"pickers",
")",
";",
"}",
"Object",
".",
"defineProperty",
"(",
"self",
",",
"'value'",
",",
"{",
"set",
":",
"function",
"(",
"value",
")",
"{",
"var",
"picker",
"=",
"this",
".",
"getActivePicker",
"(",
")",
";",
"picker",
"&&",
"(",
"picker",
".",
"value",
"=",
"value",
")",
";",
"}",
",",
"get",
":",
"function",
"(",
")",
"{",
"var",
"picker",
"=",
"this",
".",
"getActivePicker",
"(",
")",
";",
"return",
"picker",
"&&",
"picker",
".",
"value",
";",
"}",
"}",
")",
";",
"if",
"(",
"self",
".",
"aria",
")",
"{",
"self",
".",
"element",
".",
"setAttribute",
"(",
"'role'",
",",
"'slider'",
")",
";",
"target",
".",
"setAttribute",
"(",
"'aria-valuemax'",
",",
"self",
".",
"max",
")",
";",
"target",
".",
"setAttribute",
"(",
"'aria-valuemin'",
",",
"self",
".",
"min",
")",
";",
"target",
".",
"setAttribute",
"(",
"'aria-orientation'",
",",
"self",
".",
"orientation",
")",
";",
"target",
".",
"setAttribute",
"(",
"'aria-atomic'",
",",
"true",
")",
";",
"target",
".",
"setAttribute",
"(",
"'aria-controls'",
",",
"self",
".",
"pickers",
".",
"map",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"item",
".",
"element",
".",
"id",
";",
"}",
")",
".",
"join",
"(",
"' '",
")",
")",
";",
"}",
"if",
"(",
"!",
"self",
".",
"element",
".",
"hasAttribute",
"(",
"'disabled'",
")",
")",
"self",
".",
"enable",
"(",
")",
";",
"self",
".",
"emit",
"(",
"'created'",
")",
";",
"}"
] | Create slider over a target
@constructor | [
"Create",
"slider",
"over",
"a",
"target"
] | 18c57d07face0ea8f297060434fb1c13b33cd888 | https://github.com/dy/slidy/blob/18c57d07face0ea8f297060434fb1c13b33cd888/index.js#L38-L135 | train |
dy/slidy | index.js | detectStep | function detectStep (min, max) {
var range = getTransformer(function (a, b) {
return Math.abs(a - b);
})(max, min);
var step = getTransformer(function (a) {
return a < 100 ? 0.01 : 1;
})(range);
return step;
} | javascript | function detectStep (min, max) {
var range = getTransformer(function (a, b) {
return Math.abs(a - b);
})(max, min);
var step = getTransformer(function (a) {
return a < 100 ? 0.01 : 1;
})(range);
return step;
} | [
"function",
"detectStep",
"(",
"min",
",",
"max",
")",
"{",
"var",
"range",
"=",
"getTransformer",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"Math",
".",
"abs",
"(",
"a",
"-",
"b",
")",
";",
"}",
")",
"(",
"max",
",",
"min",
")",
";",
"var",
"step",
"=",
"getTransformer",
"(",
"function",
"(",
"a",
")",
"{",
"return",
"a",
"<",
"100",
"?",
"0.01",
":",
"1",
";",
"}",
")",
"(",
"range",
")",
";",
"return",
"step",
";",
"}"
] | Default step detector
Step is 0.1 or 1 | [
"Default",
"step",
"detector",
"Step",
"is",
"0",
".",
"1",
"or",
"1"
] | 18c57d07face0ea8f297060434fb1c13b33cd888 | https://github.com/dy/slidy/blob/18c57d07face0ea8f297060434fb1c13b33cd888/index.js#L510-L520 | train |
dy/slidy | index.js | detectValue | function detectValue (min, max) {
return getTransformer(function (a, b) {
return (a + b) * 0.5;
})(min, max);
} | javascript | function detectValue (min, max) {
return getTransformer(function (a, b) {
return (a + b) * 0.5;
})(min, max);
} | [
"function",
"detectValue",
"(",
"min",
",",
"max",
")",
"{",
"return",
"getTransformer",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"(",
"a",
"+",
"b",
")",
"*",
"0.5",
";",
"}",
")",
"(",
"min",
",",
"max",
")",
";",
"}"
] | Default value detector
Default value is half of range | [
"Default",
"value",
"detector",
"Default",
"value",
"is",
"half",
"of",
"range"
] | 18c57d07face0ea8f297060434fb1c13b33cd888 | https://github.com/dy/slidy/blob/18c57d07face0ea8f297060434fb1c13b33cd888/index.js#L527-L531 | train |
weexteam/weexpack-create | src/options.js | setDefault | function setDefault (opts, key, val) {
if (opts.schema) {
opts.prompts = opts.schema;
delete opts.schema;
}
const prompts = opts.prompts || (opts.prompts = {});
if (!prompts[key] || typeof prompts[key] !== 'object') {
prompts[key] = {
'type': 'string',
'default': val
};
}
else {
prompts[key]['default'] = val;
}
} | javascript | function setDefault (opts, key, val) {
if (opts.schema) {
opts.prompts = opts.schema;
delete opts.schema;
}
const prompts = opts.prompts || (opts.prompts = {});
if (!prompts[key] || typeof prompts[key] !== 'object') {
prompts[key] = {
'type': 'string',
'default': val
};
}
else {
prompts[key]['default'] = val;
}
} | [
"function",
"setDefault",
"(",
"opts",
",",
"key",
",",
"val",
")",
"{",
"if",
"(",
"opts",
".",
"schema",
")",
"{",
"opts",
".",
"prompts",
"=",
"opts",
".",
"schema",
";",
"delete",
"opts",
".",
"schema",
";",
"}",
"const",
"prompts",
"=",
"opts",
".",
"prompts",
"||",
"(",
"opts",
".",
"prompts",
"=",
"{",
"}",
")",
";",
"if",
"(",
"!",
"prompts",
"[",
"key",
"]",
"||",
"typeof",
"prompts",
"[",
"key",
"]",
"!==",
"'object'",
")",
"{",
"prompts",
"[",
"key",
"]",
"=",
"{",
"'type'",
":",
"'string'",
",",
"'default'",
":",
"val",
"}",
";",
"}",
"else",
"{",
"prompts",
"[",
"key",
"]",
"[",
"'default'",
"]",
"=",
"val",
";",
"}",
"}"
] | Set the default value for a prompt question
@param {Object} opts
@param {String} key
@param {String} val | [
"Set",
"the",
"default",
"value",
"for",
"a",
"prompt",
"question"
] | 5046f4c68a2684fb51e3f2d878e706fd02a30884 | https://github.com/weexteam/weexpack-create/blob/5046f4c68a2684fb51e3f2d878e706fd02a30884/src/options.js#L66-L81 | train |
emmetio/css-abbreviation | index.js | consumeIdent | function consumeIdent(stream) {
stream.start = stream.pos;
stream.eatWhile(isIdentPrefix);
stream.eatWhile(isIdent);
return stream.start !== stream.pos ? stream.current() : null;
} | javascript | function consumeIdent(stream) {
stream.start = stream.pos;
stream.eatWhile(isIdentPrefix);
stream.eatWhile(isIdent);
return stream.start !== stream.pos ? stream.current() : null;
} | [
"function",
"consumeIdent",
"(",
"stream",
")",
"{",
"stream",
".",
"start",
"=",
"stream",
".",
"pos",
";",
"stream",
".",
"eatWhile",
"(",
"isIdentPrefix",
")",
";",
"stream",
".",
"eatWhile",
"(",
"isIdent",
")",
";",
"return",
"stream",
".",
"start",
"!==",
"stream",
".",
"pos",
"?",
"stream",
".",
"current",
"(",
")",
":",
"null",
";",
"}"
] | Consumes CSS property identifier from given stream
@param {StreamReader} stream
@return {String} | [
"Consumes",
"CSS",
"property",
"identifier",
"from",
"given",
"stream"
] | af922be7317caba3662162ee271f01ae63849e14 | https://github.com/emmetio/css-abbreviation/blob/af922be7317caba3662162ee271f01ae63849e14/index.js#L68-L73 | train |
emmetio/css-abbreviation | index.js | consumeValue | function consumeValue(stream) {
const values = new CSSValue();
let value;
while (!stream.eof()) {
// use colon as value separator
stream.eat(COLON);
if (value = consumeNumericValue(stream) || consumeColor(stream)) {
// edge case: a dash after unit-less numeric value or color should
// be treated as value separator, not negative sign
if (!value.unit) {
stream.eat(DASH);
}
} else {
stream.eat(DASH);
value = consumeKeyword(stream, true);
}
if (!value) {
break;
}
values.add(value);
}
return values;
} | javascript | function consumeValue(stream) {
const values = new CSSValue();
let value;
while (!stream.eof()) {
// use colon as value separator
stream.eat(COLON);
if (value = consumeNumericValue(stream) || consumeColor(stream)) {
// edge case: a dash after unit-less numeric value or color should
// be treated as value separator, not negative sign
if (!value.unit) {
stream.eat(DASH);
}
} else {
stream.eat(DASH);
value = consumeKeyword(stream, true);
}
if (!value) {
break;
}
values.add(value);
}
return values;
} | [
"function",
"consumeValue",
"(",
"stream",
")",
"{",
"const",
"values",
"=",
"new",
"CSSValue",
"(",
")",
";",
"let",
"value",
";",
"while",
"(",
"!",
"stream",
".",
"eof",
"(",
")",
")",
"{",
"stream",
".",
"eat",
"(",
"COLON",
")",
";",
"if",
"(",
"value",
"=",
"consumeNumericValue",
"(",
"stream",
")",
"||",
"consumeColor",
"(",
"stream",
")",
")",
"{",
"if",
"(",
"!",
"value",
".",
"unit",
")",
"{",
"stream",
".",
"eat",
"(",
"DASH",
")",
";",
"}",
"}",
"else",
"{",
"stream",
".",
"eat",
"(",
"DASH",
")",
";",
"value",
"=",
"consumeKeyword",
"(",
"stream",
",",
"true",
")",
";",
"}",
"if",
"(",
"!",
"value",
")",
"{",
"break",
";",
"}",
"values",
".",
"add",
"(",
"value",
")",
";",
"}",
"return",
"values",
";",
"}"
] | Consumes embedded value from Emmet CSS abbreviation stream
@param {StreamReader} stream
@return {CSSValue} | [
"Consumes",
"embedded",
"value",
"from",
"Emmet",
"CSS",
"abbreviation",
"stream"
] | af922be7317caba3662162ee271f01ae63849e14 | https://github.com/emmetio/css-abbreviation/blob/af922be7317caba3662162ee271f01ae63849e14/index.js#L80-L106 | train |
dy/to-float32 | index.js | fract32 | function fract32 (arr) {
if (arr.length) {
var fract = float32(arr)
for (var i = 0, l = fract.length; i < l; i++) {
fract[i] = arr[i] - fract[i]
}
return fract
}
// number
return float32(arr - float32(arr))
} | javascript | function fract32 (arr) {
if (arr.length) {
var fract = float32(arr)
for (var i = 0, l = fract.length; i < l; i++) {
fract[i] = arr[i] - fract[i]
}
return fract
}
// number
return float32(arr - float32(arr))
} | [
"function",
"fract32",
"(",
"arr",
")",
"{",
"if",
"(",
"arr",
".",
"length",
")",
"{",
"var",
"fract",
"=",
"float32",
"(",
"arr",
")",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"fract",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"fract",
"[",
"i",
"]",
"=",
"arr",
"[",
"i",
"]",
"-",
"fract",
"[",
"i",
"]",
"}",
"return",
"fract",
"}",
"return",
"float32",
"(",
"arr",
"-",
"float32",
"(",
"arr",
")",
")",
"}"
] | return fractional part of float32 array | [
"return",
"fractional",
"part",
"of",
"float32",
"array"
] | cd5621ec047c2aa3a776466646ea8b77b56ef9bf | https://github.com/dy/to-float32/blob/cd5621ec047c2aa3a776466646ea8b77b56ef9bf/index.js#L14-L25 | train |
dy/to-float32 | index.js | float32 | function float32 (arr) {
if (arr.length) {
if (arr instanceof Float32Array) return arr
var float = new Float32Array(arr)
float.set(arr)
return float
}
// number
narr[0] = arr
return narr[0]
} | javascript | function float32 (arr) {
if (arr.length) {
if (arr instanceof Float32Array) return arr
var float = new Float32Array(arr)
float.set(arr)
return float
}
// number
narr[0] = arr
return narr[0]
} | [
"function",
"float32",
"(",
"arr",
")",
"{",
"if",
"(",
"arr",
".",
"length",
")",
"{",
"if",
"(",
"arr",
"instanceof",
"Float32Array",
")",
"return",
"arr",
"var",
"float",
"=",
"new",
"Float32Array",
"(",
"arr",
")",
"float",
".",
"set",
"(",
"arr",
")",
"return",
"float",
"}",
"narr",
"[",
"0",
"]",
"=",
"arr",
"return",
"narr",
"[",
"0",
"]",
"}"
] | make sure data is float32 array | [
"make",
"sure",
"data",
"is",
"float32",
"array"
] | cd5621ec047c2aa3a776466646ea8b77b56ef9bf | https://github.com/dy/to-float32/blob/cd5621ec047c2aa3a776466646ea8b77b56ef9bf/index.js#L28-L39 | train |
aleksei0807/cors-prefetch-middleware | lib/index.js | corsPrefetch | function corsPrefetch(req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, *');
res.setHeader('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
return;
}
next();
} | javascript | function corsPrefetch(req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, *');
res.setHeader('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
return;
}
next();
} | [
"function",
"corsPrefetch",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"header",
"(",
"'Access-Control-Allow-Origin'",
",",
"req",
".",
"headers",
".",
"origin",
")",
";",
"res",
".",
"header",
"(",
"'Access-Control-Allow-Methods'",
",",
"'GET,PUT,POST,DELETE'",
")",
";",
"res",
".",
"header",
"(",
"'Access-Control-Allow-Headers'",
",",
"'Content-Type, *'",
")",
";",
"res",
".",
"setHeader",
"(",
"'Access-Control-Allow-Credentials'",
",",
"'true'",
")",
";",
"if",
"(",
"req",
".",
"method",
"===",
"'OPTIONS'",
")",
"{",
"res",
".",
"sendStatus",
"(",
"200",
")",
";",
"return",
";",
"}",
"next",
"(",
")",
";",
"}"
] | This middleware stands for prevent blocking
in latest Firefox and Chrome because of
prefetch checks
@param req express.request
@param res express.response
@param next next experss middleware | [
"This",
"middleware",
"stands",
"for",
"prevent",
"blocking",
"in",
"latest",
"Firefox",
"and",
"Chrome",
"because",
"of",
"prefetch",
"checks"
] | d678f5b9954d30699fbea172bc16d5a20ea80eb5 | https://github.com/aleksei0807/cors-prefetch-middleware/blob/d678f5b9954d30699fbea172bc16d5a20ea80eb5/lib/index.js#L17-L29 | train |
Phineas/mc-utils | lib/index.js | writePCBuffer | function writePCBuffer(client, buffer) {
var length = pcbuffer.createBuffer();
length.writeVarInt(buffer.buffer().length);
client.write(Buffer.concat([length.buffer(), buffer.buffer()]));
} | javascript | function writePCBuffer(client, buffer) {
var length = pcbuffer.createBuffer();
length.writeVarInt(buffer.buffer().length);
client.write(Buffer.concat([length.buffer(), buffer.buffer()]));
} | [
"function",
"writePCBuffer",
"(",
"client",
",",
"buffer",
")",
"{",
"var",
"length",
"=",
"pcbuffer",
".",
"createBuffer",
"(",
")",
";",
"length",
".",
"writeVarInt",
"(",
"buffer",
".",
"buffer",
"(",
")",
".",
"length",
")",
";",
"client",
".",
"write",
"(",
"Buffer",
".",
"concat",
"(",
"[",
"length",
".",
"buffer",
"(",
")",
",",
"buffer",
".",
"buffer",
"(",
")",
"]",
")",
")",
";",
"}"
] | Wraps our Buffer into another to fit the Minecraft protocol. | [
"Wraps",
"our",
"Buffer",
"into",
"another",
"to",
"fit",
"the",
"Minecraft",
"protocol",
"."
] | 9b8f7e0637978abb88f060ed63ede2995a836677 | https://github.com/Phineas/mc-utils/blob/9b8f7e0637978abb88f060ed63ede2995a836677/lib/index.js#L243-L250 | train |
JohnMcLear/ep_email_notifications | index.js | sendContent | function sendContent(res, args, action, padId, padURL, resultDb) {
console.debug("starting sendContent: args ->", action, " / ", padId, " / ", padURL, " / ", resultDb);
if (action == 'subscribe') {
var actionMsg = "Subscribing '" + resultDb.email + "' to pad " + padId;
} else {
var actionMsg = "Unsubscribing '" + resultDb.email + "' from pad " + padId;
}
var msgCause, resultMsg, classResult;
if (resultDb.foundInDb == true && resultDb.timeDiffGood == true) {
// Pending data were found un Db and updated -> good
resultMsg = "Success";
classResult = "validationGood";
if (action == 'subscribe') {
msgCause = "You will receive email when someone changes this pad.";
} else {
msgCause = "You won't receive anymore email when someone changes this pad.";
}
} else if (resultDb.foundInDb == true) {
// Pending data were found but older than a day -> fail
resultMsg = "Too late!";
classResult = "validationBad";
msgCause = "You have max 24h to click the link in your confirmation email.";
} else {
// Pending data weren't found in Db -> fail
resultMsg = "Fail";
classResult = "validationBad";
msgCause = "We couldn't find any pending " + (action == 'subscribe'?'subscription':'unsubscription') + "<br />in our system with this Id.<br />Maybe you wait more than 24h before validating";
}
args.content = fs.readFileSync(__dirname + "/templates/response.ejs", 'utf-8');
args.content = args.content
.replace(/\<%action%\>/, actionMsg)
.replace(/\<%classResult%\>/, classResult)
.replace(/\<%result%\>/, resultMsg)
.replace(/\<%explanation%\>/, msgCause)
.replace(/\<%padUrl%\>/g, padURL);
res.contentType("text/html; charset=utf-8");
res.send(args.content); // Send it to the requester*/
} | javascript | function sendContent(res, args, action, padId, padURL, resultDb) {
console.debug("starting sendContent: args ->", action, " / ", padId, " / ", padURL, " / ", resultDb);
if (action == 'subscribe') {
var actionMsg = "Subscribing '" + resultDb.email + "' to pad " + padId;
} else {
var actionMsg = "Unsubscribing '" + resultDb.email + "' from pad " + padId;
}
var msgCause, resultMsg, classResult;
if (resultDb.foundInDb == true && resultDb.timeDiffGood == true) {
// Pending data were found un Db and updated -> good
resultMsg = "Success";
classResult = "validationGood";
if (action == 'subscribe') {
msgCause = "You will receive email when someone changes this pad.";
} else {
msgCause = "You won't receive anymore email when someone changes this pad.";
}
} else if (resultDb.foundInDb == true) {
// Pending data were found but older than a day -> fail
resultMsg = "Too late!";
classResult = "validationBad";
msgCause = "You have max 24h to click the link in your confirmation email.";
} else {
// Pending data weren't found in Db -> fail
resultMsg = "Fail";
classResult = "validationBad";
msgCause = "We couldn't find any pending " + (action == 'subscribe'?'subscription':'unsubscription') + "<br />in our system with this Id.<br />Maybe you wait more than 24h before validating";
}
args.content = fs.readFileSync(__dirname + "/templates/response.ejs", 'utf-8');
args.content = args.content
.replace(/\<%action%\>/, actionMsg)
.replace(/\<%classResult%\>/, classResult)
.replace(/\<%result%\>/, resultMsg)
.replace(/\<%explanation%\>/, msgCause)
.replace(/\<%padUrl%\>/g, padURL);
res.contentType("text/html; charset=utf-8");
res.send(args.content); // Send it to the requester*/
} | [
"function",
"sendContent",
"(",
"res",
",",
"args",
",",
"action",
",",
"padId",
",",
"padURL",
",",
"resultDb",
")",
"{",
"console",
".",
"debug",
"(",
"\"starting sendContent: args ->\"",
",",
"action",
",",
"\" / \"",
",",
"padId",
",",
"\" / \"",
",",
"padURL",
",",
"\" / \"",
",",
"resultDb",
")",
";",
"if",
"(",
"action",
"==",
"'subscribe'",
")",
"{",
"var",
"actionMsg",
"=",
"\"Subscribing '\"",
"+",
"resultDb",
".",
"email",
"+",
"\"' to pad \"",
"+",
"padId",
";",
"}",
"else",
"{",
"var",
"actionMsg",
"=",
"\"Unsubscribing '\"",
"+",
"resultDb",
".",
"email",
"+",
"\"' from pad \"",
"+",
"padId",
";",
"}",
"var",
"msgCause",
",",
"resultMsg",
",",
"classResult",
";",
"if",
"(",
"resultDb",
".",
"foundInDb",
"==",
"true",
"&&",
"resultDb",
".",
"timeDiffGood",
"==",
"true",
")",
"{",
"resultMsg",
"=",
"\"Success\"",
";",
"classResult",
"=",
"\"validationGood\"",
";",
"if",
"(",
"action",
"==",
"'subscribe'",
")",
"{",
"msgCause",
"=",
"\"You will receive email when someone changes this pad.\"",
";",
"}",
"else",
"{",
"msgCause",
"=",
"\"You won't receive anymore email when someone changes this pad.\"",
";",
"}",
"}",
"else",
"if",
"(",
"resultDb",
".",
"foundInDb",
"==",
"true",
")",
"{",
"resultMsg",
"=",
"\"Too late!\"",
";",
"classResult",
"=",
"\"validationBad\"",
";",
"msgCause",
"=",
"\"You have max 24h to click the link in your confirmation email.\"",
";",
"}",
"else",
"{",
"resultMsg",
"=",
"\"Fail\"",
";",
"classResult",
"=",
"\"validationBad\"",
";",
"msgCause",
"=",
"\"We couldn't find any pending \"",
"+",
"(",
"action",
"==",
"'subscribe'",
"?",
"'subscription'",
":",
"'unsubscription'",
")",
"+",
"\"<br />in our system with this Id.<br />Maybe you wait more than 24h before validating\"",
";",
"}",
"args",
".",
"content",
"=",
"fs",
".",
"readFileSync",
"(",
"__dirname",
"+",
"\"/templates/response.ejs\"",
",",
"'utf-8'",
")",
";",
"args",
".",
"content",
"=",
"args",
".",
"content",
".",
"replace",
"(",
"/",
"\\<%action%\\>",
"/",
",",
"actionMsg",
")",
".",
"replace",
"(",
"/",
"\\<%classResult%\\>",
"/",
",",
"classResult",
")",
".",
"replace",
"(",
"/",
"\\<%result%\\>",
"/",
",",
"resultMsg",
")",
".",
"replace",
"(",
"/",
"\\<%explanation%\\>",
"/",
",",
"msgCause",
")",
".",
"replace",
"(",
"/",
"\\<%padUrl%\\>",
"/",
"g",
",",
"padURL",
")",
";",
"res",
".",
"contentType",
"(",
"\"text/html; charset=utf-8\"",
")",
";",
"res",
".",
"send",
"(",
"args",
".",
"content",
")",
";",
"}"
] | Create html output with the status of the process | [
"Create",
"html",
"output",
"with",
"the",
"status",
"of",
"the",
"process"
] | 68fabc173bcb44b0936690d59767bf1f927c951a | https://github.com/JohnMcLear/ep_email_notifications/blob/68fabc173bcb44b0936690d59767bf1f927c951a/index.js#L214-L255 | train |
InfinniPlatform/InfinniUI | extensions/pdfViewer/pdf/web/viewer.js | preferencesReset | function preferencesReset() {
return this.initializedPromise.then(function() {
this.prefs = Object.create(DEFAULT_PREFERENCES);
return this._writeToStorage(DEFAULT_PREFERENCES);
}.bind(this));
} | javascript | function preferencesReset() {
return this.initializedPromise.then(function() {
this.prefs = Object.create(DEFAULT_PREFERENCES);
return this._writeToStorage(DEFAULT_PREFERENCES);
}.bind(this));
} | [
"function",
"preferencesReset",
"(",
")",
"{",
"return",
"this",
".",
"initializedPromise",
".",
"then",
"(",
"function",
"(",
")",
"{",
"this",
".",
"prefs",
"=",
"Object",
".",
"create",
"(",
"DEFAULT_PREFERENCES",
")",
";",
"return",
"this",
".",
"_writeToStorage",
"(",
"DEFAULT_PREFERENCES",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Reset the preferences to their default values and update storage.
@return {Promise} A promise that is resolved when the preference values
have been reset. | [
"Reset",
"the",
"preferences",
"to",
"their",
"default",
"values",
"and",
"update",
"storage",
"."
] | fb14898a843da70f9117fa197b8aca07c858f49f | https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/web/viewer.js#L517-L522 | train |
InfinniPlatform/InfinniUI | extensions/pdfViewer/pdf/web/viewer.js | preferencesGet | function preferencesGet(name) {
return this.initializedPromise.then(function () {
var defaultValue = DEFAULT_PREFERENCES[name];
if (defaultValue === undefined) {
throw new Error('preferencesGet: \'' + name + '\' is undefined.');
} else {
var prefValue = this.prefs[name];
if (prefValue !== undefined) {
return prefValue;
}
}
return defaultValue;
}.bind(this));
} | javascript | function preferencesGet(name) {
return this.initializedPromise.then(function () {
var defaultValue = DEFAULT_PREFERENCES[name];
if (defaultValue === undefined) {
throw new Error('preferencesGet: \'' + name + '\' is undefined.');
} else {
var prefValue = this.prefs[name];
if (prefValue !== undefined) {
return prefValue;
}
}
return defaultValue;
}.bind(this));
} | [
"function",
"preferencesGet",
"(",
"name",
")",
"{",
"return",
"this",
".",
"initializedPromise",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"defaultValue",
"=",
"DEFAULT_PREFERENCES",
"[",
"name",
"]",
";",
"if",
"(",
"defaultValue",
"===",
"undefined",
")",
"{",
"throw",
"new",
"Error",
"(",
"'preferencesGet: \\''",
"+",
"\\'",
"+",
"name",
")",
";",
"}",
"else",
"'\\' is undefined.'",
"\\'",
"}",
".",
"{",
"var",
"prefValue",
"=",
"this",
".",
"prefs",
"[",
"name",
"]",
";",
"if",
"(",
"prefValue",
"!==",
"undefined",
")",
"{",
"return",
"prefValue",
";",
"}",
"}",
"return",
"defaultValue",
";",
")",
";",
"}"
] | Get the value of a preference.
@param {string} name The name of the preference whose value is requested.
@return {Promise} A promise that is resolved with a {boolean|number|string}
containing the value of the preference. | [
"Get",
"the",
"value",
"of",
"a",
"preference",
"."
] | fb14898a843da70f9117fa197b8aca07c858f49f | https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/web/viewer.js#L580-L595 | train |
InfinniPlatform/InfinniUI | extensions/pdfViewer/pdf/web/viewer.js | secondaryToolbarSetMaxHeight | function secondaryToolbarSetMaxHeight(container) {
if (!container || !this.buttonContainer) {
return;
}
this.newContainerHeight = container.clientHeight;
if (this.previousContainerHeight === this.newContainerHeight) {
return;
}
this.buttonContainer.setAttribute('style',
'max-height: ' + (this.newContainerHeight - SCROLLBAR_PADDING) + 'px;');
this.previousContainerHeight = this.newContainerHeight;
} | javascript | function secondaryToolbarSetMaxHeight(container) {
if (!container || !this.buttonContainer) {
return;
}
this.newContainerHeight = container.clientHeight;
if (this.previousContainerHeight === this.newContainerHeight) {
return;
}
this.buttonContainer.setAttribute('style',
'max-height: ' + (this.newContainerHeight - SCROLLBAR_PADDING) + 'px;');
this.previousContainerHeight = this.newContainerHeight;
} | [
"function",
"secondaryToolbarSetMaxHeight",
"(",
"container",
")",
"{",
"if",
"(",
"!",
"container",
"||",
"!",
"this",
".",
"buttonContainer",
")",
"{",
"return",
";",
"}",
"this",
".",
"newContainerHeight",
"=",
"container",
".",
"clientHeight",
";",
"if",
"(",
"this",
".",
"previousContainerHeight",
"===",
"this",
".",
"newContainerHeight",
")",
"{",
"return",
";",
"}",
"this",
".",
"buttonContainer",
".",
"setAttribute",
"(",
"'style'",
",",
"'max-height: '",
"+",
"(",
"this",
".",
"newContainerHeight",
"-",
"SCROLLBAR_PADDING",
")",
"+",
"'px;'",
")",
";",
"this",
".",
"previousContainerHeight",
"=",
"this",
".",
"newContainerHeight",
";",
"}"
] | Misc. functions for interacting with the toolbar. | [
"Misc",
".",
"functions",
"for",
"interacting",
"with",
"the",
"toolbar",
"."
] | fb14898a843da70f9117fa197b8aca07c858f49f | https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/web/viewer.js#L2209-L2220 | train |
InfinniPlatform/InfinniUI | extensions/pdfViewer/pdf/web/viewer.js | PDFPresentationMode_request | function PDFPresentationMode_request() {
if (this.switchInProgress || this.active ||
!this.viewer.hasChildNodes()) {
return false;
}
this._addFullscreenChangeListeners();
this._setSwitchInProgress();
this._notifyStateChange();
if (this.container.requestFullscreen) {
this.container.requestFullscreen();
} else if (this.container.mozRequestFullScreen) {
this.container.mozRequestFullScreen();
} else if (this.container.webkitRequestFullscreen) {
this.container.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
} else if (this.container.msRequestFullscreen) {
this.container.msRequestFullscreen();
} else {
return false;
}
this.args = {
page: PDFViewerApplication.page,
previousScale: PDFViewerApplication.currentScaleValue
};
return true;
} | javascript | function PDFPresentationMode_request() {
if (this.switchInProgress || this.active ||
!this.viewer.hasChildNodes()) {
return false;
}
this._addFullscreenChangeListeners();
this._setSwitchInProgress();
this._notifyStateChange();
if (this.container.requestFullscreen) {
this.container.requestFullscreen();
} else if (this.container.mozRequestFullScreen) {
this.container.mozRequestFullScreen();
} else if (this.container.webkitRequestFullscreen) {
this.container.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
} else if (this.container.msRequestFullscreen) {
this.container.msRequestFullscreen();
} else {
return false;
}
this.args = {
page: PDFViewerApplication.page,
previousScale: PDFViewerApplication.currentScaleValue
};
return true;
} | [
"function",
"PDFPresentationMode_request",
"(",
")",
"{",
"if",
"(",
"this",
".",
"switchInProgress",
"||",
"this",
".",
"active",
"||",
"!",
"this",
".",
"viewer",
".",
"hasChildNodes",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"this",
".",
"_addFullscreenChangeListeners",
"(",
")",
";",
"this",
".",
"_setSwitchInProgress",
"(",
")",
";",
"this",
".",
"_notifyStateChange",
"(",
")",
";",
"if",
"(",
"this",
".",
"container",
".",
"requestFullscreen",
")",
"{",
"this",
".",
"container",
".",
"requestFullscreen",
"(",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"container",
".",
"mozRequestFullScreen",
")",
"{",
"this",
".",
"container",
".",
"mozRequestFullScreen",
"(",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"container",
".",
"webkitRequestFullscreen",
")",
"{",
"this",
".",
"container",
".",
"webkitRequestFullscreen",
"(",
"Element",
".",
"ALLOW_KEYBOARD_INPUT",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"container",
".",
"msRequestFullscreen",
")",
"{",
"this",
".",
"container",
".",
"msRequestFullscreen",
"(",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"this",
".",
"args",
"=",
"{",
"page",
":",
"PDFViewerApplication",
".",
"page",
",",
"previousScale",
":",
"PDFViewerApplication",
".",
"currentScaleValue",
"}",
";",
"return",
"true",
";",
"}"
] | Request the browser to enter fullscreen mode.
@returns {boolean} Indicating if the request was successful. | [
"Request",
"the",
"browser",
"to",
"enter",
"fullscreen",
"mode",
"."
] | fb14898a843da70f9117fa197b8aca07c858f49f | https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/web/viewer.js#L2303-L2330 | train |
InfinniPlatform/InfinniUI | extensions/pdfViewer/pdf/web/viewer.js | isLeftMouseReleased | function isLeftMouseReleased(event) {
if ('buttons' in event && isNotIEorIsIE10plus) {
// http://www.w3.org/TR/DOM-Level-3-Events/#events-MouseEvent-buttons
// Firefox 15+
// Internet Explorer 10+
return !(event.buttons | 1);
}
if (isChrome15OrOpera15plus || isSafari6plus) {
// Chrome 14+
// Opera 15+
// Safari 6.0+
return event.which === 0;
}
} | javascript | function isLeftMouseReleased(event) {
if ('buttons' in event && isNotIEorIsIE10plus) {
// http://www.w3.org/TR/DOM-Level-3-Events/#events-MouseEvent-buttons
// Firefox 15+
// Internet Explorer 10+
return !(event.buttons | 1);
}
if (isChrome15OrOpera15plus || isSafari6plus) {
// Chrome 14+
// Opera 15+
// Safari 6.0+
return event.which === 0;
}
} | [
"function",
"isLeftMouseReleased",
"(",
"event",
")",
"{",
"if",
"(",
"'buttons'",
"in",
"event",
"&&",
"isNotIEorIsIE10plus",
")",
"{",
"return",
"!",
"(",
"event",
".",
"buttons",
"|",
"1",
")",
";",
"}",
"if",
"(",
"isChrome15OrOpera15plus",
"||",
"isSafari6plus",
")",
"{",
"return",
"event",
".",
"which",
"===",
"0",
";",
"}",
"}"
] | Whether the left mouse is not pressed.
@param event {MouseEvent}
@return {boolean} True if the left mouse button is not pressed.
False if unsure or if the left mouse button is pressed. | [
"Whether",
"the",
"left",
"mouse",
"is",
"not",
"pressed",
"."
] | fb14898a843da70f9117fa197b8aca07c858f49f | https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/web/viewer.js#L2833-L2846 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.