id int32 0 58k | repo stringlengths 5 67 | path stringlengths 4 116 | func_name stringlengths 0 58 | original_string stringlengths 52 373k | language stringclasses 1 value | code stringlengths 52 373k | code_tokens list | docstring stringlengths 4 11.8k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 86 226 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22,200 | wtfaremyinitials/osa-imessage | index.js | send | function send(handle, message) {
assert(typeof handle == 'string', 'handle must be a string')
assert(typeof message == 'string', 'message must be a string')
return osa((handle, message) => {
const Messages = Application('Messages')
let target
try {
target = Messages.buddies.whose({ handle: handle })[0]
} catch (e) {}
try {
target = Messages.textChats.byId('iMessage;+;' + handle)()
} catch (e) {}
try {
Messages.send(message, { to: target })
} catch (e) {
throw new Error(`no thread with handle '${handle}'`)
}
})(handle, message)
} | javascript | function send(handle, message) {
assert(typeof handle == 'string', 'handle must be a string')
assert(typeof message == 'string', 'message must be a string')
return osa((handle, message) => {
const Messages = Application('Messages')
let target
try {
target = Messages.buddies.whose({ handle: handle })[0]
} catch (e) {}
try {
target = Messages.textChats.byId('iMessage;+;' + handle)()
} catch (e) {}
try {
Messages.send(message, { to: target })
} catch (e) {
throw new Error(`no thread with handle '${handle}'`)
}
})(handle, message)
} | [
"function",
"send",
"(",
"handle",
",",
"message",
")",
"{",
"assert",
"(",
"typeof",
"handle",
"==",
"'string'",
",",
"'handle must be a string'",
")",
"assert",
"(",
"typeof",
"message",
"==",
"'string'",
",",
"'message must be a string'",
")",
"return",
"osa",
"(",
"(",
"handle",
",",
"message",
")",
"=>",
"{",
"const",
"Messages",
"=",
"Application",
"(",
"'Messages'",
")",
"let",
"target",
"try",
"{",
"target",
"=",
"Messages",
".",
"buddies",
".",
"whose",
"(",
"{",
"handle",
":",
"handle",
"}",
")",
"[",
"0",
"]",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"try",
"{",
"target",
"=",
"Messages",
".",
"textChats",
".",
"byId",
"(",
"'iMessage;+;'",
"+",
"handle",
")",
"(",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"try",
"{",
"Messages",
".",
"send",
"(",
"message",
",",
"{",
"to",
":",
"target",
"}",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"handle",
"}",
"`",
")",
"}",
"}",
")",
"(",
"handle",
",",
"message",
")",
"}"
] | Sends a message to the given handle | [
"Sends",
"a",
"message",
"to",
"the",
"given",
"handle"
] | 6532d837524d86d6cabdb7d1ce75fc1fab462044 | https://github.com/wtfaremyinitials/osa-imessage/blob/6532d837524d86d6cabdb7d1ce75fc1fab462044/index.js#L95-L117 |
22,201 | voilab/voilab-pdf-table | plugins/fitcolumn.js | function (table) {
table
.onBodyAdd(this.setWidth.bind(this))
.onColumnAdded(this.onColumnAdded.bind(this))
.onColumnPropertyChanged(this.onColumnPropertyChanged.bind(this));
} | javascript | function (table) {
table
.onBodyAdd(this.setWidth.bind(this))
.onColumnAdded(this.onColumnAdded.bind(this))
.onColumnPropertyChanged(this.onColumnPropertyChanged.bind(this));
} | [
"function",
"(",
"table",
")",
"{",
"table",
".",
"onBodyAdd",
"(",
"this",
".",
"setWidth",
".",
"bind",
"(",
"this",
")",
")",
".",
"onColumnAdded",
"(",
"this",
".",
"onColumnAdded",
".",
"bind",
"(",
"this",
")",
")",
".",
"onColumnPropertyChanged",
"(",
"this",
".",
"onColumnPropertyChanged",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Configure plugin by attaching functions to table events
@param {PdfTable}
@return {void} | [
"Configure",
"plugin",
"by",
"attaching",
"functions",
"to",
"table",
"events"
] | 03ac40155d41d3f871d40ae2281a30c7eaf10392 | https://github.com/voilab/voilab-pdf-table/blob/03ac40155d41d3f871d40ae2281a30c7eaf10392/plugins/fitcolumn.js#L47-L52 | |
22,202 | voilab/voilab-pdf-table | plugins/fitcolumn.js | function (table) {
if (!table.pdf.page) {
return;
}
if (this.calculatedWidth === null) {
var self = this,
content_width = this.maxWidth,
width = lodash.sumBy(table.getColumns(), function (column) {
return column.id !== self.column ? column.width : 0;
});
if (!content_width) {
content_width = table.pdf.page.width
- table.pdf.page.margins.left
- table.pdf.page.margins.right;
}
this.calculatedWidth = content_width - width;
if (this.calculatedWidth < 0) {
this.calculatedWidth = 0;
}
}
table.setColumnWidth(this.column, this.calculatedWidth, true);
} | javascript | function (table) {
if (!table.pdf.page) {
return;
}
if (this.calculatedWidth === null) {
var self = this,
content_width = this.maxWidth,
width = lodash.sumBy(table.getColumns(), function (column) {
return column.id !== self.column ? column.width : 0;
});
if (!content_width) {
content_width = table.pdf.page.width
- table.pdf.page.margins.left
- table.pdf.page.margins.right;
}
this.calculatedWidth = content_width - width;
if (this.calculatedWidth < 0) {
this.calculatedWidth = 0;
}
}
table.setColumnWidth(this.column, this.calculatedWidth, true);
} | [
"function",
"(",
"table",
")",
"{",
"if",
"(",
"!",
"table",
".",
"pdf",
".",
"page",
")",
"{",
"return",
";",
"}",
"if",
"(",
"this",
".",
"calculatedWidth",
"===",
"null",
")",
"{",
"var",
"self",
"=",
"this",
",",
"content_width",
"=",
"this",
".",
"maxWidth",
",",
"width",
"=",
"lodash",
".",
"sumBy",
"(",
"table",
".",
"getColumns",
"(",
")",
",",
"function",
"(",
"column",
")",
"{",
"return",
"column",
".",
"id",
"!==",
"self",
".",
"column",
"?",
"column",
".",
"width",
":",
"0",
";",
"}",
")",
";",
"if",
"(",
"!",
"content_width",
")",
"{",
"content_width",
"=",
"table",
".",
"pdf",
".",
"page",
".",
"width",
"-",
"table",
".",
"pdf",
".",
"page",
".",
"margins",
".",
"left",
"-",
"table",
".",
"pdf",
".",
"page",
".",
"margins",
".",
"right",
";",
"}",
"this",
".",
"calculatedWidth",
"=",
"content_width",
"-",
"width",
";",
"if",
"(",
"this",
".",
"calculatedWidth",
"<",
"0",
")",
"{",
"this",
".",
"calculatedWidth",
"=",
"0",
";",
"}",
"}",
"table",
".",
"setColumnWidth",
"(",
"this",
".",
"column",
",",
"this",
".",
"calculatedWidth",
",",
"true",
")",
";",
"}"
] | Check the max width of the stretched column. This method is called just
before we start to add data rows
@param {PdfTable} table
@return {void} | [
"Check",
"the",
"max",
"width",
"of",
"the",
"stretched",
"column",
".",
"This",
"method",
"is",
"called",
"just",
"before",
"we",
"start",
"to",
"add",
"data",
"rows"
] | 03ac40155d41d3f871d40ae2281a30c7eaf10392 | https://github.com/voilab/voilab-pdf-table/blob/03ac40155d41d3f871d40ae2281a30c7eaf10392/plugins/fitcolumn.js#L109-L132 | |
22,203 | lokiuz/redraft | src/RawParser.js | createNodes | function createNodes(entityRanges, decoratorRanges = [], textArray, block) {
let lastIndex = 0;
const mergedRanges = [...entityRanges, ...decoratorRanges].sort((a, b) => a.offset - b.offset);
const nodes = [];
// if thers no entities will return just a single item
if (mergedRanges.length < 1) {
nodes.push(new ContentNode({ block, start: 0, end: textArray.length }));
return nodes;
}
mergedRanges.forEach((range) => {
// create an empty node for content between previous and this entity
if (range.offset > lastIndex) {
nodes.push(new ContentNode({ block, start: lastIndex, end: range.offset }));
}
// push the node for the entity
nodes.push(new ContentNode({
block,
entity: range.key,
decorator: range.component,
decoratorProps: range.decoratorProps,
decoratedText: range.component
? getString(textArray, range.offset, range.offset + range.length)
: undefined,
start: range.offset,
end: range.offset + range.length,
contentState: range.contentState,
}));
lastIndex = range.offset + range.length;
});
// finaly add a node for the remaining text if any
if (lastIndex < textArray.length) {
nodes.push(new ContentNode({
block,
start: lastIndex,
end: textArray.length,
}));
}
return nodes;
} | javascript | function createNodes(entityRanges, decoratorRanges = [], textArray, block) {
let lastIndex = 0;
const mergedRanges = [...entityRanges, ...decoratorRanges].sort((a, b) => a.offset - b.offset);
const nodes = [];
// if thers no entities will return just a single item
if (mergedRanges.length < 1) {
nodes.push(new ContentNode({ block, start: 0, end: textArray.length }));
return nodes;
}
mergedRanges.forEach((range) => {
// create an empty node for content between previous and this entity
if (range.offset > lastIndex) {
nodes.push(new ContentNode({ block, start: lastIndex, end: range.offset }));
}
// push the node for the entity
nodes.push(new ContentNode({
block,
entity: range.key,
decorator: range.component,
decoratorProps: range.decoratorProps,
decoratedText: range.component
? getString(textArray, range.offset, range.offset + range.length)
: undefined,
start: range.offset,
end: range.offset + range.length,
contentState: range.contentState,
}));
lastIndex = range.offset + range.length;
});
// finaly add a node for the remaining text if any
if (lastIndex < textArray.length) {
nodes.push(new ContentNode({
block,
start: lastIndex,
end: textArray.length,
}));
}
return nodes;
} | [
"function",
"createNodes",
"(",
"entityRanges",
",",
"decoratorRanges",
"=",
"[",
"]",
",",
"textArray",
",",
"block",
")",
"{",
"let",
"lastIndex",
"=",
"0",
";",
"const",
"mergedRanges",
"=",
"[",
"...",
"entityRanges",
",",
"...",
"decoratorRanges",
"]",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"a",
".",
"offset",
"-",
"b",
".",
"offset",
")",
";",
"const",
"nodes",
"=",
"[",
"]",
";",
"// if thers no entities will return just a single item",
"if",
"(",
"mergedRanges",
".",
"length",
"<",
"1",
")",
"{",
"nodes",
".",
"push",
"(",
"new",
"ContentNode",
"(",
"{",
"block",
",",
"start",
":",
"0",
",",
"end",
":",
"textArray",
".",
"length",
"}",
")",
")",
";",
"return",
"nodes",
";",
"}",
"mergedRanges",
".",
"forEach",
"(",
"(",
"range",
")",
"=>",
"{",
"// create an empty node for content between previous and this entity",
"if",
"(",
"range",
".",
"offset",
">",
"lastIndex",
")",
"{",
"nodes",
".",
"push",
"(",
"new",
"ContentNode",
"(",
"{",
"block",
",",
"start",
":",
"lastIndex",
",",
"end",
":",
"range",
".",
"offset",
"}",
")",
")",
";",
"}",
"// push the node for the entity",
"nodes",
".",
"push",
"(",
"new",
"ContentNode",
"(",
"{",
"block",
",",
"entity",
":",
"range",
".",
"key",
",",
"decorator",
":",
"range",
".",
"component",
",",
"decoratorProps",
":",
"range",
".",
"decoratorProps",
",",
"decoratedText",
":",
"range",
".",
"component",
"?",
"getString",
"(",
"textArray",
",",
"range",
".",
"offset",
",",
"range",
".",
"offset",
"+",
"range",
".",
"length",
")",
":",
"undefined",
",",
"start",
":",
"range",
".",
"offset",
",",
"end",
":",
"range",
".",
"offset",
"+",
"range",
".",
"length",
",",
"contentState",
":",
"range",
".",
"contentState",
",",
"}",
")",
")",
";",
"lastIndex",
"=",
"range",
".",
"offset",
"+",
"range",
".",
"length",
";",
"}",
")",
";",
"// finaly add a node for the remaining text if any",
"if",
"(",
"lastIndex",
"<",
"textArray",
".",
"length",
")",
"{",
"nodes",
".",
"push",
"(",
"new",
"ContentNode",
"(",
"{",
"block",
",",
"start",
":",
"lastIndex",
",",
"end",
":",
"textArray",
".",
"length",
",",
"}",
")",
")",
";",
"}",
"return",
"nodes",
";",
"}"
] | creates nodes with entity keys and the endOffset | [
"creates",
"nodes",
"with",
"entity",
"keys",
"and",
"the",
"endOffset"
] | f2c776e4277ee74b98311bba8dc9345a37e8e130 | https://github.com/lokiuz/redraft/blob/f2c776e4277ee74b98311bba8dc9345a37e8e130/src/RawParser.js#L12-L52 |
22,204 | lokiuz/redraft | src/RawParser.js | getRelevantIndexes | function getRelevantIndexes(text, inlineRanges, entityRanges = [], decoratorRanges = []) {
let relevantIndexes = [];
// set indexes to corresponding keys to ensure uniquenes
relevantIndexes = addIndexes(relevantIndexes, inlineRanges);
relevantIndexes = addIndexes(relevantIndexes, entityRanges);
relevantIndexes = addIndexes(relevantIndexes, decoratorRanges);
// add text start and end to relevant indexes
relevantIndexes.push(0);
relevantIndexes.push(text.length);
const uniqueRelevantIndexes = relevantIndexes.filter(
(value, index, self) => self.indexOf(value) === index
);
// and sort it
return uniqueRelevantIndexes.sort((aa, bb) => (aa - bb));
} | javascript | function getRelevantIndexes(text, inlineRanges, entityRanges = [], decoratorRanges = []) {
let relevantIndexes = [];
// set indexes to corresponding keys to ensure uniquenes
relevantIndexes = addIndexes(relevantIndexes, inlineRanges);
relevantIndexes = addIndexes(relevantIndexes, entityRanges);
relevantIndexes = addIndexes(relevantIndexes, decoratorRanges);
// add text start and end to relevant indexes
relevantIndexes.push(0);
relevantIndexes.push(text.length);
const uniqueRelevantIndexes = relevantIndexes.filter(
(value, index, self) => self.indexOf(value) === index
);
// and sort it
return uniqueRelevantIndexes.sort((aa, bb) => (aa - bb));
} | [
"function",
"getRelevantIndexes",
"(",
"text",
",",
"inlineRanges",
",",
"entityRanges",
"=",
"[",
"]",
",",
"decoratorRanges",
"=",
"[",
"]",
")",
"{",
"let",
"relevantIndexes",
"=",
"[",
"]",
";",
"// set indexes to corresponding keys to ensure uniquenes",
"relevantIndexes",
"=",
"addIndexes",
"(",
"relevantIndexes",
",",
"inlineRanges",
")",
";",
"relevantIndexes",
"=",
"addIndexes",
"(",
"relevantIndexes",
",",
"entityRanges",
")",
";",
"relevantIndexes",
"=",
"addIndexes",
"(",
"relevantIndexes",
",",
"decoratorRanges",
")",
";",
"// add text start and end to relevant indexes",
"relevantIndexes",
".",
"push",
"(",
"0",
")",
";",
"relevantIndexes",
".",
"push",
"(",
"text",
".",
"length",
")",
";",
"const",
"uniqueRelevantIndexes",
"=",
"relevantIndexes",
".",
"filter",
"(",
"(",
"value",
",",
"index",
",",
"self",
")",
"=>",
"self",
".",
"indexOf",
"(",
"value",
")",
"===",
"index",
")",
";",
"// and sort it",
"return",
"uniqueRelevantIndexes",
".",
"sort",
"(",
"(",
"aa",
",",
"bb",
")",
"=>",
"(",
"aa",
"-",
"bb",
")",
")",
";",
"}"
] | Creates an array of sorted char indexes to avoid iterating over every single character | [
"Creates",
"an",
"array",
"of",
"sorted",
"char",
"indexes",
"to",
"avoid",
"iterating",
"over",
"every",
"single",
"character"
] | f2c776e4277ee74b98311bba8dc9345a37e8e130 | https://github.com/lokiuz/redraft/blob/f2c776e4277ee74b98311bba8dc9345a37e8e130/src/RawParser.js#L65-L79 |
22,205 | lo-th/uil | build/uil.module.js | function ( type, css, obj, dom, id ) {
return Tools.dom( type, css, obj, dom, id );
} | javascript | function ( type, css, obj, dom, id ) {
return Tools.dom( type, css, obj, dom, id );
} | [
"function",
"(",
"type",
",",
"css",
",",
"obj",
",",
"dom",
",",
"id",
")",
"{",
"return",
"Tools",
".",
"dom",
"(",
"type",
",",
"css",
",",
"obj",
",",
"dom",
",",
"id",
")",
";",
"}"
] | TRANS FUNCTIONS from Tools | [
"TRANS",
"FUNCTIONS",
"from",
"Tools"
] | 92d3b3e0181acd6549976f71fb4ff44a0258b57e | https://github.com/lo-th/uil/blob/92d3b3e0181acd6549976f71fb4ff44a0258b57e/build/uil.module.js#L1509-L1513 | |
22,206 | lo-th/uil | build/uil.module.js | function ( n ) {
var i = this.uis.indexOf( n );
if ( i !== -1 ) {
this.inner.removeChild( this.uis[i].c[0] );
this.uis.splice( i, 1 );
}
} | javascript | function ( n ) {
var i = this.uis.indexOf( n );
if ( i !== -1 ) {
this.inner.removeChild( this.uis[i].c[0] );
this.uis.splice( i, 1 );
}
} | [
"function",
"(",
"n",
")",
"{",
"var",
"i",
"=",
"this",
".",
"uis",
".",
"indexOf",
"(",
"n",
")",
";",
"if",
"(",
"i",
"!==",
"-",
"1",
")",
"{",
"this",
".",
"inner",
".",
"removeChild",
"(",
"this",
".",
"uis",
"[",
"i",
"]",
".",
"c",
"[",
"0",
"]",
")",
";",
"this",
".",
"uis",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"}",
"}"
] | call after uis clear | [
"call",
"after",
"uis",
"clear"
] | 92d3b3e0181acd6549976f71fb4ff44a0258b57e | https://github.com/lo-th/uil/blob/92d3b3e0181acd6549976f71fb4ff44a0258b57e/build/uil.module.js#L5652-L5660 | |
22,207 | lo-th/uil | _OLD/uil-1.0/build/uil.module.js | function( canvas, content, w, h ){
var ctx = canvas.getContext("2d");
var dcopy = null;
if( typeof content === 'string' ){
dcopy = Tools.dom( 'iframe', 'position:abolute; left:0; top:0; width:'+w+'px; height:'+h+'px;' );
dcopy.src = content;
}else{
dcopy = content.cloneNode(true);
dcopy.style.left = 0;
}
var svg = Tools.dom( 'foreignObject', 'position:abolute; left:0; top:0;', { width:w, height:h });
svg.childNodes[0].appendChild( dcopy );
svg.setAttribute("version", "1.1");
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg' );
svg.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
svg.setAttribute('width', w );
svg.setAttribute('height', h );
svg.childNodes[0].setAttribute('width', '100%' );
svg.childNodes[0].setAttribute('height', '100%' );
//console.log(svg)
var img = new Image();
var data = 'data:image/svg+xml;base64,'+ window.btoa((new XMLSerializer).serializeToString(svg));
dcopy = null;
img.onload = function() {
ctx.clearRect( 0, 0, w, h );
ctx.drawImage( img, 0, 0, w, h, 0, 0, w, h );
};
img.src = data;
/*setTimeout(function() {
ctx.clearRect( 0, 0, w, h );
ctx.drawImage( img, 0, 0, w, h, 0, 0, w, h );
}, 0);*/
// blob
/*var svgBlob = new Blob([(new XMLSerializer).serializeToString(svg)], {type: "image/svg+xml;charset=utf-8"});
var url = URL.createObjectURL(svgBlob);
img.onload = function() {
ctx.clearRect( 0, 0, w, h );
ctx.drawImage( img, 0, 0, w, h, 0, 0, w, h );
URL.revokeObjectURL(url);
};
img.src = url;*/
} | javascript | function( canvas, content, w, h ){
var ctx = canvas.getContext("2d");
var dcopy = null;
if( typeof content === 'string' ){
dcopy = Tools.dom( 'iframe', 'position:abolute; left:0; top:0; width:'+w+'px; height:'+h+'px;' );
dcopy.src = content;
}else{
dcopy = content.cloneNode(true);
dcopy.style.left = 0;
}
var svg = Tools.dom( 'foreignObject', 'position:abolute; left:0; top:0;', { width:w, height:h });
svg.childNodes[0].appendChild( dcopy );
svg.setAttribute("version", "1.1");
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg' );
svg.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
svg.setAttribute('width', w );
svg.setAttribute('height', h );
svg.childNodes[0].setAttribute('width', '100%' );
svg.childNodes[0].setAttribute('height', '100%' );
//console.log(svg)
var img = new Image();
var data = 'data:image/svg+xml;base64,'+ window.btoa((new XMLSerializer).serializeToString(svg));
dcopy = null;
img.onload = function() {
ctx.clearRect( 0, 0, w, h );
ctx.drawImage( img, 0, 0, w, h, 0, 0, w, h );
};
img.src = data;
/*setTimeout(function() {
ctx.clearRect( 0, 0, w, h );
ctx.drawImage( img, 0, 0, w, h, 0, 0, w, h );
}, 0);*/
// blob
/*var svgBlob = new Blob([(new XMLSerializer).serializeToString(svg)], {type: "image/svg+xml;charset=utf-8"});
var url = URL.createObjectURL(svgBlob);
img.onload = function() {
ctx.clearRect( 0, 0, w, h );
ctx.drawImage( img, 0, 0, w, h, 0, 0, w, h );
URL.revokeObjectURL(url);
};
img.src = url;*/
} | [
"function",
"(",
"canvas",
",",
"content",
",",
"w",
",",
"h",
")",
"{",
"var",
"ctx",
"=",
"canvas",
".",
"getContext",
"(",
"\"2d\"",
")",
";",
"var",
"dcopy",
"=",
"null",
";",
"if",
"(",
"typeof",
"content",
"===",
"'string'",
")",
"{",
"dcopy",
"=",
"Tools",
".",
"dom",
"(",
"'iframe'",
",",
"'position:abolute; left:0; top:0; width:'",
"+",
"w",
"+",
"'px; height:'",
"+",
"h",
"+",
"'px;'",
")",
";",
"dcopy",
".",
"src",
"=",
"content",
";",
"}",
"else",
"{",
"dcopy",
"=",
"content",
".",
"cloneNode",
"(",
"true",
")",
";",
"dcopy",
".",
"style",
".",
"left",
"=",
"0",
";",
"}",
"var",
"svg",
"=",
"Tools",
".",
"dom",
"(",
"'foreignObject'",
",",
"'position:abolute; left:0; top:0;'",
",",
"{",
"width",
":",
"w",
",",
"height",
":",
"h",
"}",
")",
";",
"svg",
".",
"childNodes",
"[",
"0",
"]",
".",
"appendChild",
"(",
"dcopy",
")",
";",
"svg",
".",
"setAttribute",
"(",
"\"version\"",
",",
"\"1.1\"",
")",
";",
"svg",
".",
"setAttribute",
"(",
"'xmlns'",
",",
"'http://www.w3.org/2000/svg'",
")",
";",
"svg",
".",
"setAttribute",
"(",
"\"xmlns:xlink\"",
",",
"\"http://www.w3.org/1999/xlink\"",
")",
";",
"svg",
".",
"setAttribute",
"(",
"'width'",
",",
"w",
")",
";",
"svg",
".",
"setAttribute",
"(",
"'height'",
",",
"h",
")",
";",
"svg",
".",
"childNodes",
"[",
"0",
"]",
".",
"setAttribute",
"(",
"'width'",
",",
"'100%'",
")",
";",
"svg",
".",
"childNodes",
"[",
"0",
"]",
".",
"setAttribute",
"(",
"'height'",
",",
"'100%'",
")",
";",
"//console.log(svg)",
"var",
"img",
"=",
"new",
"Image",
"(",
")",
";",
"var",
"data",
"=",
"'data:image/svg+xml;base64,'",
"+",
"window",
".",
"btoa",
"(",
"(",
"new",
"XMLSerializer",
")",
".",
"serializeToString",
"(",
"svg",
")",
")",
";",
"dcopy",
"=",
"null",
";",
"img",
".",
"onload",
"=",
"function",
"(",
")",
"{",
"ctx",
".",
"clearRect",
"(",
"0",
",",
"0",
",",
"w",
",",
"h",
")",
";",
"ctx",
".",
"drawImage",
"(",
"img",
",",
"0",
",",
"0",
",",
"w",
",",
"h",
",",
"0",
",",
"0",
",",
"w",
",",
"h",
")",
";",
"}",
";",
"img",
".",
"src",
"=",
"data",
";",
"/*setTimeout(function() {\n ctx.clearRect( 0, 0, w, h );\n ctx.drawImage( img, 0, 0, w, h, 0, 0, w, h );\n }, 0);*/",
"// blob",
"/*var svgBlob = new Blob([(new XMLSerializer).serializeToString(svg)], {type: \"image/svg+xml;charset=utf-8\"});\n var url = URL.createObjectURL(svgBlob);\n\n img.onload = function() {\n ctx.clearRect( 0, 0, w, h );\n ctx.drawImage( img, 0, 0, w, h, 0, 0, w, h );\n URL.revokeObjectURL(url);\n };\n img.src = url;*/",
"}"
] | svg to canvas test | [
"svg",
"to",
"canvas",
"test"
] | 92d3b3e0181acd6549976f71fb4ff44a0258b57e | https://github.com/lo-th/uil/blob/92d3b3e0181acd6549976f71fb4ff44a0258b57e/_OLD/uil-1.0/build/uil.module.js#L423-L484 | |
22,208 | jakiestfu/himawari.js | index.js | resolveDate | function resolveDate (base_url, input, callback) {
var date = input;
// If provided a date string
if ((typeof input == "string" || typeof input == "number") && input !== "latest") {
date = new Date(input);
}
// If provided a date object
if (moment.isDate(date)) { return callback(null, date); }
// If provided "latest"
else if (input === "latest") {
var latest = base_url + '/latest.json';
request({
method: 'GET',
uri: latest,
timeout: 30000
}, function (err, res) {
if (err) return callback(err);
try { date = new Date(JSON.parse(res.body).date); }
catch (e) { date = new Date(); }
return callback(null, date);
});
}
// Invalid string provided, return new Date
else { return callback(null, new Date()); }
} | javascript | function resolveDate (base_url, input, callback) {
var date = input;
// If provided a date string
if ((typeof input == "string" || typeof input == "number") && input !== "latest") {
date = new Date(input);
}
// If provided a date object
if (moment.isDate(date)) { return callback(null, date); }
// If provided "latest"
else if (input === "latest") {
var latest = base_url + '/latest.json';
request({
method: 'GET',
uri: latest,
timeout: 30000
}, function (err, res) {
if (err) return callback(err);
try { date = new Date(JSON.parse(res.body).date); }
catch (e) { date = new Date(); }
return callback(null, date);
});
}
// Invalid string provided, return new Date
else { return callback(null, new Date()); }
} | [
"function",
"resolveDate",
"(",
"base_url",
",",
"input",
",",
"callback",
")",
"{",
"var",
"date",
"=",
"input",
";",
"// If provided a date string",
"if",
"(",
"(",
"typeof",
"input",
"==",
"\"string\"",
"||",
"typeof",
"input",
"==",
"\"number\"",
")",
"&&",
"input",
"!==",
"\"latest\"",
")",
"{",
"date",
"=",
"new",
"Date",
"(",
"input",
")",
";",
"}",
"// If provided a date object",
"if",
"(",
"moment",
".",
"isDate",
"(",
"date",
")",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"date",
")",
";",
"}",
"// If provided \"latest\"",
"else",
"if",
"(",
"input",
"===",
"\"latest\"",
")",
"{",
"var",
"latest",
"=",
"base_url",
"+",
"'/latest.json'",
";",
"request",
"(",
"{",
"method",
":",
"'GET'",
",",
"uri",
":",
"latest",
",",
"timeout",
":",
"30000",
"}",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"try",
"{",
"date",
"=",
"new",
"Date",
"(",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
".",
"date",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"date",
"=",
"new",
"Date",
"(",
")",
";",
"}",
"return",
"callback",
"(",
"null",
",",
"date",
")",
";",
"}",
")",
";",
"}",
"// Invalid string provided, return new Date",
"else",
"{",
"return",
"callback",
"(",
"null",
",",
"new",
"Date",
"(",
")",
")",
";",
"}",
"}"
] | Takes an input, either a date object, a date timestamp, or the string "latest"
and resolves to a native Date object.
@param {String|Date} input The incoming date or the string "latest"
@param {Function} callback The function to be called when date is resolved | [
"Takes",
"an",
"input",
"either",
"a",
"date",
"object",
"a",
"date",
"timestamp",
"or",
"the",
"string",
"latest",
"and",
"resolves",
"to",
"a",
"native",
"Date",
"object",
"."
] | d83797be23181906367b82875f43eef8d94da479 | https://github.com/jakiestfu/himawari.js/blob/d83797be23181906367b82875f43eef8d94da479/index.js#L237-L266 |
22,209 | filamentgroup/Ajax-Include-Pattern | libs/shoestring-dev.js | recordProxy | function recordProxy( old, name ) {
return function() {
var tracked;
try {
tracked = JSON.parse(window.localStorage.getItem( shoestring.trackedMethodsKey ) || "{}");
} catch (e) {
if( e instanceof SyntaxError) {
tracked = {};
}
}
tracked[ name ] = true;
window.localStorage.setItem( shoestring.trackedMethodsKey, JSON.stringify(tracked) );
return old.apply(this, arguments);
};
} | javascript | function recordProxy( old, name ) {
return function() {
var tracked;
try {
tracked = JSON.parse(window.localStorage.getItem( shoestring.trackedMethodsKey ) || "{}");
} catch (e) {
if( e instanceof SyntaxError) {
tracked = {};
}
}
tracked[ name ] = true;
window.localStorage.setItem( shoestring.trackedMethodsKey, JSON.stringify(tracked) );
return old.apply(this, arguments);
};
} | [
"function",
"recordProxy",
"(",
"old",
",",
"name",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"tracked",
";",
"try",
"{",
"tracked",
"=",
"JSON",
".",
"parse",
"(",
"window",
".",
"localStorage",
".",
"getItem",
"(",
"shoestring",
".",
"trackedMethodsKey",
")",
"||",
"\"{}\"",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"SyntaxError",
")",
"{",
"tracked",
"=",
"{",
"}",
";",
"}",
"}",
"tracked",
"[",
"name",
"]",
"=",
"true",
";",
"window",
".",
"localStorage",
".",
"setItem",
"(",
"shoestring",
".",
"trackedMethodsKey",
",",
"JSON",
".",
"stringify",
"(",
"tracked",
")",
")",
";",
"return",
"old",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"}"
] | return a new function closed over the old implementation | [
"return",
"a",
"new",
"function",
"closed",
"over",
"the",
"old",
"implementation"
] | ab3f2aff182f7c9c73227fbdadd28c4f3bc02ffe | https://github.com/filamentgroup/Ajax-Include-Pattern/blob/ab3f2aff182f7c9c73227fbdadd28c4f3bc02ffe/libs/shoestring-dev.js#L2356-L2372 |
22,210 | filamentgroup/Ajax-Include-Pattern | dist/ajaxInclude.js | function( url, els, isHijax ) {
$.get( url, function( data, status, xhr ) {
els.trigger( "ajaxIncludeResponse", [ data, xhr ] );
});
} | javascript | function( url, els, isHijax ) {
$.get( url, function( data, status, xhr ) {
els.trigger( "ajaxIncludeResponse", [ data, xhr ] );
});
} | [
"function",
"(",
"url",
",",
"els",
",",
"isHijax",
")",
"{",
"$",
".",
"get",
"(",
"url",
",",
"function",
"(",
"data",
",",
"status",
",",
"xhr",
")",
"{",
"els",
".",
"trigger",
"(",
"\"ajaxIncludeResponse\"",
",",
"[",
"data",
",",
"xhr",
"]",
")",
";",
"}",
")",
";",
"}"
] | request a url and trigger ajaxInclude on elements upon response | [
"request",
"a",
"url",
"and",
"trigger",
"ajaxInclude",
"on",
"elements",
"upon",
"response"
] | ab3f2aff182f7c9c73227fbdadd28c4f3bc02ffe | https://github.com/filamentgroup/Ajax-Include-Pattern/blob/ab3f2aff182f7c9c73227fbdadd28c4f3bc02ffe/dist/ajaxInclude.js#L11-L15 | |
22,211 | filamentgroup/Ajax-Include-Pattern | dist/ajaxInclude.js | queueOrRequest | function queueOrRequest( el ){
var url = el.data( "url" );
if( o.proxy && $.inArray( url, urllist ) === -1 ){
urllist.push( url );
elQueue = elQueue.add( el );
}
else{
AI.makeReq( url, el );
}
} | javascript | function queueOrRequest( el ){
var url = el.data( "url" );
if( o.proxy && $.inArray( url, urllist ) === -1 ){
urllist.push( url );
elQueue = elQueue.add( el );
}
else{
AI.makeReq( url, el );
}
} | [
"function",
"queueOrRequest",
"(",
"el",
")",
"{",
"var",
"url",
"=",
"el",
".",
"data",
"(",
"\"url\"",
")",
";",
"if",
"(",
"o",
".",
"proxy",
"&&",
"$",
".",
"inArray",
"(",
"url",
",",
"urllist",
")",
"===",
"-",
"1",
")",
"{",
"urllist",
".",
"push",
"(",
"url",
")",
";",
"elQueue",
"=",
"elQueue",
".",
"add",
"(",
"el",
")",
";",
"}",
"else",
"{",
"AI",
".",
"makeReq",
"(",
"url",
",",
"el",
")",
";",
"}",
"}"
] | if it's a proxy, queue the element and its url, if not, request immediately | [
"if",
"it",
"s",
"a",
"proxy",
"queue",
"the",
"element",
"and",
"its",
"url",
"if",
"not",
"request",
"immediately"
] | ab3f2aff182f7c9c73227fbdadd28c4f3bc02ffe | https://github.com/filamentgroup/Ajax-Include-Pattern/blob/ab3f2aff182f7c9c73227fbdadd28c4f3bc02ffe/dist/ajaxInclude.js#L36-L45 |
22,212 | filamentgroup/Ajax-Include-Pattern | dist/ajaxInclude.js | runQueue | function runQueue(){
if( urllist.length ){
AI.makeReq( o.proxy + urllist.join( "," ), elQueue );
elQueue = $();
urllist = [];
}
} | javascript | function runQueue(){
if( urllist.length ){
AI.makeReq( o.proxy + urllist.join( "," ), elQueue );
elQueue = $();
urllist = [];
}
} | [
"function",
"runQueue",
"(",
")",
"{",
"if",
"(",
"urllist",
".",
"length",
")",
"{",
"AI",
".",
"makeReq",
"(",
"o",
".",
"proxy",
"+",
"urllist",
".",
"join",
"(",
"\",\"",
")",
",",
"elQueue",
")",
";",
"elQueue",
"=",
"$",
"(",
")",
";",
"urllist",
"=",
"[",
"]",
";",
"}",
"}"
] | if there's a url queue | [
"if",
"there",
"s",
"a",
"url",
"queue"
] | ab3f2aff182f7c9c73227fbdadd28c4f3bc02ffe | https://github.com/filamentgroup/Ajax-Include-Pattern/blob/ab3f2aff182f7c9c73227fbdadd28c4f3bc02ffe/dist/ajaxInclude.js#L48-L54 |
22,213 | filamentgroup/Ajax-Include-Pattern | dist/ajaxInclude.js | bindForLater | function bindForLater( el, media ){
var mm = win.matchMedia( media );
function cb(){
queueOrRequest( el );
runQueue();
mm.removeListener( cb );
}
if( mm.addListener ){
mm.addListener( cb );
}
} | javascript | function bindForLater( el, media ){
var mm = win.matchMedia( media );
function cb(){
queueOrRequest( el );
runQueue();
mm.removeListener( cb );
}
if( mm.addListener ){
mm.addListener( cb );
}
} | [
"function",
"bindForLater",
"(",
"el",
",",
"media",
")",
"{",
"var",
"mm",
"=",
"win",
".",
"matchMedia",
"(",
"media",
")",
";",
"function",
"cb",
"(",
")",
"{",
"queueOrRequest",
"(",
"el",
")",
";",
"runQueue",
"(",
")",
";",
"mm",
".",
"removeListener",
"(",
"cb",
")",
";",
"}",
"if",
"(",
"mm",
".",
"addListener",
")",
"{",
"mm",
".",
"addListener",
"(",
"cb",
")",
";",
"}",
"}"
] | bind a listener to a currently-inapplicable media query for potential later changes | [
"bind",
"a",
"listener",
"to",
"a",
"currently",
"-",
"inapplicable",
"media",
"query",
"for",
"potential",
"later",
"changes"
] | ab3f2aff182f7c9c73227fbdadd28c4f3bc02ffe | https://github.com/filamentgroup/Ajax-Include-Pattern/blob/ab3f2aff182f7c9c73227fbdadd28c4f3bc02ffe/dist/ajaxInclude.js#L57-L67 |
22,214 | bzarras/newsapi | src/index.js | splitArgsIntoOptionsAndCallback | function splitArgsIntoOptionsAndCallback (args) {
let params;
let options;
let cb;
if (args.length > 1) {
const possibleCb = args[args.length - 1];
if ('function' === typeof possibleCb) {
cb = possibleCb;
options = args.length === 3 ? args[1] : undefined;
} else {
options = args[1];
}
params = args[0];
} else if ('object' === typeof args[0]) {
params = args[0];
} else if ('function' === typeof args[0]) {
cb = args[0];
}
return { params, options, cb };
} | javascript | function splitArgsIntoOptionsAndCallback (args) {
let params;
let options;
let cb;
if (args.length > 1) {
const possibleCb = args[args.length - 1];
if ('function' === typeof possibleCb) {
cb = possibleCb;
options = args.length === 3 ? args[1] : undefined;
} else {
options = args[1];
}
params = args[0];
} else if ('object' === typeof args[0]) {
params = args[0];
} else if ('function' === typeof args[0]) {
cb = args[0];
}
return { params, options, cb };
} | [
"function",
"splitArgsIntoOptionsAndCallback",
"(",
"args",
")",
"{",
"let",
"params",
";",
"let",
"options",
";",
"let",
"cb",
";",
"if",
"(",
"args",
".",
"length",
">",
"1",
")",
"{",
"const",
"possibleCb",
"=",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"'function'",
"===",
"typeof",
"possibleCb",
")",
"{",
"cb",
"=",
"possibleCb",
";",
"options",
"=",
"args",
".",
"length",
"===",
"3",
"?",
"args",
"[",
"1",
"]",
":",
"undefined",
";",
"}",
"else",
"{",
"options",
"=",
"args",
"[",
"1",
"]",
";",
"}",
"params",
"=",
"args",
"[",
"0",
"]",
";",
"}",
"else",
"if",
"(",
"'object'",
"===",
"typeof",
"args",
"[",
"0",
"]",
")",
"{",
"params",
"=",
"args",
"[",
"0",
"]",
";",
"}",
"else",
"if",
"(",
"'function'",
"===",
"typeof",
"args",
"[",
"0",
"]",
")",
"{",
"cb",
"=",
"args",
"[",
"0",
"]",
";",
"}",
"return",
"{",
"params",
",",
"options",
",",
"cb",
"}",
";",
"}"
] | Takes a variable-length array that represents arguments to a function and attempts to split it into
an 'options' object and a 'cb' callback function.
@param {Array} args The arguments to the function
@return {Object} | [
"Takes",
"a",
"variable",
"-",
"length",
"array",
"that",
"represents",
"arguments",
"to",
"a",
"function",
"and",
"attempts",
"to",
"split",
"it",
"into",
"an",
"options",
"object",
"and",
"a",
"cb",
"callback",
"function",
"."
] | fd6fd40e5d3d5625d68ba004f7b19680598bb881 | https://github.com/bzarras/newsapi/blob/fd6fd40e5d3d5625d68ba004f7b19680598bb881/src/index.js#L71-L90 |
22,215 | bzarras/newsapi | src/index.js | createUrlFromEndpointAndOptions | function createUrlFromEndpointAndOptions (endpoint, options) {
const query = qs.stringify(options);
const baseURL = `${host}${endpoint}`;
return query ? `${baseURL}?${query}` : baseURL;
} | javascript | function createUrlFromEndpointAndOptions (endpoint, options) {
const query = qs.stringify(options);
const baseURL = `${host}${endpoint}`;
return query ? `${baseURL}?${query}` : baseURL;
} | [
"function",
"createUrlFromEndpointAndOptions",
"(",
"endpoint",
",",
"options",
")",
"{",
"const",
"query",
"=",
"qs",
".",
"stringify",
"(",
"options",
")",
";",
"const",
"baseURL",
"=",
"`",
"${",
"host",
"}",
"${",
"endpoint",
"}",
"`",
";",
"return",
"query",
"?",
"`",
"${",
"baseURL",
"}",
"${",
"query",
"}",
"`",
":",
"baseURL",
";",
"}"
] | Creates a url string from an endpoint and an options object by appending the endpoint
to the global "host" const and appending the options as querystring parameters.
@param {String} endpoint
@param {Object} [options]
@return {String} | [
"Creates",
"a",
"url",
"string",
"from",
"an",
"endpoint",
"and",
"an",
"options",
"object",
"by",
"appending",
"the",
"endpoint",
"to",
"the",
"global",
"host",
"const",
"and",
"appending",
"the",
"options",
"as",
"querystring",
"parameters",
"."
] | fd6fd40e5d3d5625d68ba004f7b19680598bb881 | https://github.com/bzarras/newsapi/blob/fd6fd40e5d3d5625d68ba004f7b19680598bb881/src/index.js#L99-L103 |
22,216 | bzarras/newsapi | src/index.js | getDataFromWeb | function getDataFromWeb(url, options, apiKey, cb) {
let useCallback = 'function' === typeof cb;
const reqOptions = { headers: {} };
if (apiKey) {
reqOptions.headers['X-Api-Key'] = apiKey;
}
if (options && options.noCache === true) {
reqOptions.headers['X-No-Cache'] = 'true';
}
return fetch(url, reqOptions).then(res => Promise.all([res, res.json()])).then(([res, body]) => {
if (body.status === 'error') throw new NewsAPIError(body);
// 'showHeaders' option can be used for clients to debug response headers
// response will be in form of { headers, body }
if (options && options.showHeaders) {
if (useCallback) return cb(null, { headers: res.headers, body });
return { headers: res.headers, body };
}
if (useCallback) return cb(null, body);
return body;
}).catch(err => {
if (useCallback) return cb(err);
throw err;
});
} | javascript | function getDataFromWeb(url, options, apiKey, cb) {
let useCallback = 'function' === typeof cb;
const reqOptions = { headers: {} };
if (apiKey) {
reqOptions.headers['X-Api-Key'] = apiKey;
}
if (options && options.noCache === true) {
reqOptions.headers['X-No-Cache'] = 'true';
}
return fetch(url, reqOptions).then(res => Promise.all([res, res.json()])).then(([res, body]) => {
if (body.status === 'error') throw new NewsAPIError(body);
// 'showHeaders' option can be used for clients to debug response headers
// response will be in form of { headers, body }
if (options && options.showHeaders) {
if (useCallback) return cb(null, { headers: res.headers, body });
return { headers: res.headers, body };
}
if (useCallback) return cb(null, body);
return body;
}).catch(err => {
if (useCallback) return cb(err);
throw err;
});
} | [
"function",
"getDataFromWeb",
"(",
"url",
",",
"options",
",",
"apiKey",
",",
"cb",
")",
"{",
"let",
"useCallback",
"=",
"'function'",
"===",
"typeof",
"cb",
";",
"const",
"reqOptions",
"=",
"{",
"headers",
":",
"{",
"}",
"}",
";",
"if",
"(",
"apiKey",
")",
"{",
"reqOptions",
".",
"headers",
"[",
"'X-Api-Key'",
"]",
"=",
"apiKey",
";",
"}",
"if",
"(",
"options",
"&&",
"options",
".",
"noCache",
"===",
"true",
")",
"{",
"reqOptions",
".",
"headers",
"[",
"'X-No-Cache'",
"]",
"=",
"'true'",
";",
"}",
"return",
"fetch",
"(",
"url",
",",
"reqOptions",
")",
".",
"then",
"(",
"res",
"=>",
"Promise",
".",
"all",
"(",
"[",
"res",
",",
"res",
".",
"json",
"(",
")",
"]",
")",
")",
".",
"then",
"(",
"(",
"[",
"res",
",",
"body",
"]",
")",
"=>",
"{",
"if",
"(",
"body",
".",
"status",
"===",
"'error'",
")",
"throw",
"new",
"NewsAPIError",
"(",
"body",
")",
";",
"// 'showHeaders' option can be used for clients to debug response headers",
"// response will be in form of { headers, body }",
"if",
"(",
"options",
"&&",
"options",
".",
"showHeaders",
")",
"{",
"if",
"(",
"useCallback",
")",
"return",
"cb",
"(",
"null",
",",
"{",
"headers",
":",
"res",
".",
"headers",
",",
"body",
"}",
")",
";",
"return",
"{",
"headers",
":",
"res",
".",
"headers",
",",
"body",
"}",
";",
"}",
"if",
"(",
"useCallback",
")",
"return",
"cb",
"(",
"null",
",",
"body",
")",
";",
"return",
"body",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"if",
"(",
"useCallback",
")",
"return",
"cb",
"(",
"err",
")",
";",
"throw",
"err",
";",
"}",
")",
";",
"}"
] | Takes a URL string and returns a Promise containing
a buffer with the data from the web.
@param {String} url A URL String
@param {String} apiKey (Optional) A key to be used for authentication
@return {Promise<Buffer>} A Promise containing a Buffer | [
"Takes",
"a",
"URL",
"string",
"and",
"returns",
"a",
"Promise",
"containing",
"a",
"buffer",
"with",
"the",
"data",
"from",
"the",
"web",
"."
] | fd6fd40e5d3d5625d68ba004f7b19680598bb881 | https://github.com/bzarras/newsapi/blob/fd6fd40e5d3d5625d68ba004f7b19680598bb881/src/index.js#L112-L135 |
22,217 | Shopify/graphql-to-js-client-builder | src/sort-definitions.js | visitFragment | function visitFragment(fragment, fragments, fragmentsHash) {
if (fragment.marked) {
throw Error('Fragments cannot contain a cycle');
}
if (!fragment.visited) {
fragment.marked = true;
// Visit every spread in this fragment definition
visit(fragment, {
FragmentSpread(node) {
// Visit the corresponding fragment definition
visitFragment(fragmentsHash[node.name.value], fragments, fragmentsHash);
}
});
fragment.visited = true;
fragment.marked = false;
fragments.push(fragment);
}
} | javascript | function visitFragment(fragment, fragments, fragmentsHash) {
if (fragment.marked) {
throw Error('Fragments cannot contain a cycle');
}
if (!fragment.visited) {
fragment.marked = true;
// Visit every spread in this fragment definition
visit(fragment, {
FragmentSpread(node) {
// Visit the corresponding fragment definition
visitFragment(fragmentsHash[node.name.value], fragments, fragmentsHash);
}
});
fragment.visited = true;
fragment.marked = false;
fragments.push(fragment);
}
} | [
"function",
"visitFragment",
"(",
"fragment",
",",
"fragments",
",",
"fragmentsHash",
")",
"{",
"if",
"(",
"fragment",
".",
"marked",
")",
"{",
"throw",
"Error",
"(",
"'Fragments cannot contain a cycle'",
")",
";",
"}",
"if",
"(",
"!",
"fragment",
".",
"visited",
")",
"{",
"fragment",
".",
"marked",
"=",
"true",
";",
"// Visit every spread in this fragment definition",
"visit",
"(",
"fragment",
",",
"{",
"FragmentSpread",
"(",
"node",
")",
"{",
"// Visit the corresponding fragment definition",
"visitFragment",
"(",
"fragmentsHash",
"[",
"node",
".",
"name",
".",
"value",
"]",
",",
"fragments",
",",
"fragmentsHash",
")",
";",
"}",
"}",
")",
";",
"fragment",
".",
"visited",
"=",
"true",
";",
"fragment",
".",
"marked",
"=",
"false",
";",
"fragments",
".",
"push",
"(",
"fragment",
")",
";",
"}",
"}"
] | Recursive helper function for sortDefinitions | [
"Recursive",
"helper",
"function",
"for",
"sortDefinitions"
] | b23829fc52c69916b4e9728062d6e6b25ea53b79 | https://github.com/Shopify/graphql-to-js-client-builder/blob/b23829fc52c69916b4e9728062d6e6b25ea53b79/src/sort-definitions.js#L4-L21 |
22,218 | rguerreiro/express-device | lib/device.js | customCheck | function customCheck(req, mydevice) {
var useragent = req.headers['user-agent'];
if (!useragent || useragent === '') {
if (req.headers['cloudfront-is-mobile-viewer'] === 'true') return 'phone';
if (req.headers['cloudfront-is-tablet-viewer'] === 'true') return 'tablet';
if (req.headers['cloudfront-is-desktop-viewer'] === 'true') return 'desktop';
// No user agent.
return mydevice.parser.options.emptyUserAgentDeviceType;
}
return mydevice.type;
} | javascript | function customCheck(req, mydevice) {
var useragent = req.headers['user-agent'];
if (!useragent || useragent === '') {
if (req.headers['cloudfront-is-mobile-viewer'] === 'true') return 'phone';
if (req.headers['cloudfront-is-tablet-viewer'] === 'true') return 'tablet';
if (req.headers['cloudfront-is-desktop-viewer'] === 'true') return 'desktop';
// No user agent.
return mydevice.parser.options.emptyUserAgentDeviceType;
}
return mydevice.type;
} | [
"function",
"customCheck",
"(",
"req",
",",
"mydevice",
")",
"{",
"var",
"useragent",
"=",
"req",
".",
"headers",
"[",
"'user-agent'",
"]",
";",
"if",
"(",
"!",
"useragent",
"||",
"useragent",
"===",
"''",
")",
"{",
"if",
"(",
"req",
".",
"headers",
"[",
"'cloudfront-is-mobile-viewer'",
"]",
"===",
"'true'",
")",
"return",
"'phone'",
";",
"if",
"(",
"req",
".",
"headers",
"[",
"'cloudfront-is-tablet-viewer'",
"]",
"===",
"'true'",
")",
"return",
"'tablet'",
";",
"if",
"(",
"req",
".",
"headers",
"[",
"'cloudfront-is-desktop-viewer'",
"]",
"===",
"'true'",
")",
"return",
"'desktop'",
";",
"// No user agent.\r",
"return",
"mydevice",
".",
"parser",
".",
"options",
".",
"emptyUserAgentDeviceType",
";",
"}",
"return",
"mydevice",
".",
"type",
";",
"}"
] | should this be on 'device' instead? | [
"should",
"this",
"be",
"on",
"device",
"instead?"
] | 621ac384754de7a3d97e0c10a1a9e495da408ddf | https://github.com/rguerreiro/express-device/blob/621ac384754de7a3d97e0c10a1a9e495da408ddf/lib/device.js#L21-L33 |
22,219 | AssemblyScript/prototype | bin/asc.js | writeText | function writeText(wasmModule, format, output, callback) {
if (format === "linear" || format === "stack") {
if (!assemblyscript.util.wabt) {
process.stderr.write("\nwabt.js not found\n");
return callback(EFAILURE);
}
var binary = wasmModule.ascCurrentBinary || (wasmModule.ascCurrentBinary = wasmModule.emitBinary()); // reuse
output.write(assemblyscript.util.wasmToWast(binary, { readDebugNames: true }), "utf8", end);
} else
output.write(wasmModule.emitText(), "utf8", end);
function end(err) {
if (err || output === process.stdout) return callback(err);
output.end(callback);
}
} | javascript | function writeText(wasmModule, format, output, callback) {
if (format === "linear" || format === "stack") {
if (!assemblyscript.util.wabt) {
process.stderr.write("\nwabt.js not found\n");
return callback(EFAILURE);
}
var binary = wasmModule.ascCurrentBinary || (wasmModule.ascCurrentBinary = wasmModule.emitBinary()); // reuse
output.write(assemblyscript.util.wasmToWast(binary, { readDebugNames: true }), "utf8", end);
} else
output.write(wasmModule.emitText(), "utf8", end);
function end(err) {
if (err || output === process.stdout) return callback(err);
output.end(callback);
}
} | [
"function",
"writeText",
"(",
"wasmModule",
",",
"format",
",",
"output",
",",
"callback",
")",
"{",
"if",
"(",
"format",
"===",
"\"linear\"",
"||",
"format",
"===",
"\"stack\"",
")",
"{",
"if",
"(",
"!",
"assemblyscript",
".",
"util",
".",
"wabt",
")",
"{",
"process",
".",
"stderr",
".",
"write",
"(",
"\"\\nwabt.js not found\\n\"",
")",
";",
"return",
"callback",
"(",
"EFAILURE",
")",
";",
"}",
"var",
"binary",
"=",
"wasmModule",
".",
"ascCurrentBinary",
"||",
"(",
"wasmModule",
".",
"ascCurrentBinary",
"=",
"wasmModule",
".",
"emitBinary",
"(",
")",
")",
";",
"// reuse",
"output",
".",
"write",
"(",
"assemblyscript",
".",
"util",
".",
"wasmToWast",
"(",
"binary",
",",
"{",
"readDebugNames",
":",
"true",
"}",
")",
",",
"\"utf8\"",
",",
"end",
")",
";",
"}",
"else",
"output",
".",
"write",
"(",
"wasmModule",
".",
"emitText",
"(",
")",
",",
"\"utf8\"",
",",
"end",
")",
";",
"function",
"end",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"||",
"output",
"===",
"process",
".",
"stdout",
")",
"return",
"callback",
"(",
"err",
")",
";",
"output",
".",
"end",
"(",
"callback",
")",
";",
"}",
"}"
] | Writes text format of the specified module, using the specified format. | [
"Writes",
"text",
"format",
"of",
"the",
"specified",
"module",
"using",
"the",
"specified",
"format",
"."
] | a44bf654dda58f8bdd782e6ff170ccc6f0de92a8 | https://github.com/AssemblyScript/prototype/blob/a44bf654dda58f8bdd782e6ff170ccc6f0de92a8/bin/asc.js#L188-L203 |
22,220 | AssemblyScript/prototype | bin/asc.js | writeBinary | function writeBinary(wasmModule, output, callback) {
output.write(Buffer.from(wasmModule.emitBinary()), end);
function end(err) {
if (err || output === process.stdout) return callback(err);
output.end(callback);
}
} | javascript | function writeBinary(wasmModule, output, callback) {
output.write(Buffer.from(wasmModule.emitBinary()), end);
function end(err) {
if (err || output === process.stdout) return callback(err);
output.end(callback);
}
} | [
"function",
"writeBinary",
"(",
"wasmModule",
",",
"output",
",",
"callback",
")",
"{",
"output",
".",
"write",
"(",
"Buffer",
".",
"from",
"(",
"wasmModule",
".",
"emitBinary",
"(",
")",
")",
",",
"end",
")",
";",
"function",
"end",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"||",
"output",
"===",
"process",
".",
"stdout",
")",
"return",
"callback",
"(",
"err",
")",
";",
"output",
".",
"end",
"(",
"callback",
")",
";",
"}",
"}"
] | Writes a binary of the specified module. | [
"Writes",
"a",
"binary",
"of",
"the",
"specified",
"module",
"."
] | a44bf654dda58f8bdd782e6ff170ccc6f0de92a8 | https://github.com/AssemblyScript/prototype/blob/a44bf654dda58f8bdd782e6ff170ccc6f0de92a8/bin/asc.js#L208-L215 |
22,221 | AssemblyScript/prototype | bin/asc.js | writeAsmjs | function writeAsmjs(wasmModule, output, callback) {
output.write(Buffer.from(wasmModule.emitAsmjs()), end);
function end(err) {
if (err || output === process.stdout) return callback(err);
output.end(callback);
}
} | javascript | function writeAsmjs(wasmModule, output, callback) {
output.write(Buffer.from(wasmModule.emitAsmjs()), end);
function end(err) {
if (err || output === process.stdout) return callback(err);
output.end(callback);
}
} | [
"function",
"writeAsmjs",
"(",
"wasmModule",
",",
"output",
",",
"callback",
")",
"{",
"output",
".",
"write",
"(",
"Buffer",
".",
"from",
"(",
"wasmModule",
".",
"emitAsmjs",
"(",
")",
")",
",",
"end",
")",
";",
"function",
"end",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"||",
"output",
"===",
"process",
".",
"stdout",
")",
"return",
"callback",
"(",
"err",
")",
";",
"output",
".",
"end",
"(",
"callback",
")",
";",
"}",
"}"
] | Writes the asm.js representation of the specified module. | [
"Writes",
"the",
"asm",
".",
"js",
"representation",
"of",
"the",
"specified",
"module",
"."
] | a44bf654dda58f8bdd782e6ff170ccc6f0de92a8 | https://github.com/AssemblyScript/prototype/blob/a44bf654dda58f8bdd782e6ff170ccc6f0de92a8/bin/asc.js#L218-L225 |
22,222 | spirit/spirit | src/loadAnimation.js | createFromData | function createFromData(data, container) {
if (data === undefined) {
return Promise.resolve([])
}
if (!(isObject(data) || Array.isArray(data))) {
return Promise.reject(new Error('Invalid animation data'))
}
return Promise.resolve(create(data, container))
} | javascript | function createFromData(data, container) {
if (data === undefined) {
return Promise.resolve([])
}
if (!(isObject(data) || Array.isArray(data))) {
return Promise.reject(new Error('Invalid animation data'))
}
return Promise.resolve(create(data, container))
} | [
"function",
"createFromData",
"(",
"data",
",",
"container",
")",
"{",
"if",
"(",
"data",
"===",
"undefined",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"[",
"]",
")",
"}",
"if",
"(",
"!",
"(",
"isObject",
"(",
"data",
")",
"||",
"Array",
".",
"isArray",
"(",
"data",
")",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'Invalid animation data'",
")",
")",
"}",
"return",
"Promise",
".",
"resolve",
"(",
"create",
"(",
"data",
",",
"container",
")",
")",
"}"
] | Create from data
@param {object|Array} data
@param {Element} container
@return {Promise<Array|object>} | [
"Create",
"from",
"data"
] | 7403dfdba99dca7c03b149d4a830fadff80c3769 | https://github.com/spirit/spirit/blob/7403dfdba99dca7c03b149d4a830fadff80c3769/src/loadAnimation.js#L22-L31 |
22,223 | spirit/spirit | src/loadAnimation.js | loadFromPath | function loadFromPath(path, container) {
if (path && typeof path === 'string' && path.length > 0) {
return load(path, container)
}
return Promise.resolve([])
} | javascript | function loadFromPath(path, container) {
if (path && typeof path === 'string' && path.length > 0) {
return load(path, container)
}
return Promise.resolve([])
} | [
"function",
"loadFromPath",
"(",
"path",
",",
"container",
")",
"{",
"if",
"(",
"path",
"&&",
"typeof",
"path",
"===",
"'string'",
"&&",
"path",
".",
"length",
">",
"0",
")",
"{",
"return",
"load",
"(",
"path",
",",
"container",
")",
"}",
"return",
"Promise",
".",
"resolve",
"(",
"[",
"]",
")",
"}"
] | Load from path
@param {string} path
@param {Element} container
@return {Promise<Array|object>} | [
"Load",
"from",
"path"
] | 7403dfdba99dca7c03b149d4a830fadff80c3769 | https://github.com/spirit/spirit/blob/7403dfdba99dca7c03b149d4a830fadff80c3769/src/loadAnimation.js#L40-L45 |
22,224 | spirit/spirit | src/data/parser.js | groupsFactory | function groupsFactory() {
let list = []
const getGroupsByRoot = function(root) {
for (let i = 0; i < list.length; i++) {
let groups = list[i]
if (groups.rootEl === root) {
return groups
}
}
return null
}
return {
add: function(root, group) {
let groups = getGroupsByRoot(root)
if (!groups) {
groups = new Groups(root, [])
list.push(groups)
}
if (group) {
group._list = groups
group.resolve()
groups.add(group)
}
},
groups: function() {
return list.length === 1 ? list[0] : list
}
}
} | javascript | function groupsFactory() {
let list = []
const getGroupsByRoot = function(root) {
for (let i = 0; i < list.length; i++) {
let groups = list[i]
if (groups.rootEl === root) {
return groups
}
}
return null
}
return {
add: function(root, group) {
let groups = getGroupsByRoot(root)
if (!groups) {
groups = new Groups(root, [])
list.push(groups)
}
if (group) {
group._list = groups
group.resolve()
groups.add(group)
}
},
groups: function() {
return list.length === 1 ? list[0] : list
}
}
} | [
"function",
"groupsFactory",
"(",
")",
"{",
"let",
"list",
"=",
"[",
"]",
"const",
"getGroupsByRoot",
"=",
"function",
"(",
"root",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"list",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"groups",
"=",
"list",
"[",
"i",
"]",
"if",
"(",
"groups",
".",
"rootEl",
"===",
"root",
")",
"{",
"return",
"groups",
"}",
"}",
"return",
"null",
"}",
"return",
"{",
"add",
":",
"function",
"(",
"root",
",",
"group",
")",
"{",
"let",
"groups",
"=",
"getGroupsByRoot",
"(",
"root",
")",
"if",
"(",
"!",
"groups",
")",
"{",
"groups",
"=",
"new",
"Groups",
"(",
"root",
",",
"[",
"]",
")",
"list",
".",
"push",
"(",
"groups",
")",
"}",
"if",
"(",
"group",
")",
"{",
"group",
".",
"_list",
"=",
"groups",
"group",
".",
"resolve",
"(",
")",
"groups",
".",
"add",
"(",
"group",
")",
"}",
"}",
",",
"groups",
":",
"function",
"(",
")",
"{",
"return",
"list",
".",
"length",
"===",
"1",
"?",
"list",
"[",
"0",
"]",
":",
"list",
"}",
"}",
"}"
] | Create groups factory
@return {{add: {function} add, groups: {array|Groups} groups}} | [
"Create",
"groups",
"factory"
] | 7403dfdba99dca7c03b149d4a830fadff80c3769 | https://github.com/spirit/spirit/blob/7403dfdba99dca7c03b149d4a830fadff80c3769/src/data/parser.js#L9-L40 |
22,225 | browserify/common-shakeify | index.js | isUsed | function isUsed (name) {
if (module.isUsed(name)) {
return true
}
if (dupes.length > 0) {
return dupes.some((dupe) => {
const m = analyzer.modules.get(dupe.file)
return m && m.isUsed(name)
})
}
return false
} | javascript | function isUsed (name) {
if (module.isUsed(name)) {
return true
}
if (dupes.length > 0) {
return dupes.some((dupe) => {
const m = analyzer.modules.get(dupe.file)
return m && m.isUsed(name)
})
}
return false
} | [
"function",
"isUsed",
"(",
"name",
")",
"{",
"if",
"(",
"module",
".",
"isUsed",
"(",
"name",
")",
")",
"{",
"return",
"true",
"}",
"if",
"(",
"dupes",
".",
"length",
">",
"0",
")",
"{",
"return",
"dupes",
".",
"some",
"(",
"(",
"dupe",
")",
"=>",
"{",
"const",
"m",
"=",
"analyzer",
".",
"modules",
".",
"get",
"(",
"dupe",
".",
"file",
")",
"return",
"m",
"&&",
"m",
".",
"isUsed",
"(",
"name",
")",
"}",
")",
"}",
"return",
"false",
"}"
] | Check if a name was used in this module, or in any of this module's deduped versions. | [
"Check",
"if",
"a",
"name",
"was",
"used",
"in",
"this",
"module",
"or",
"in",
"any",
"of",
"this",
"module",
"s",
"deduped",
"versions",
"."
] | 1325412e3480b49cbfee4e0931a7fbf14d9e9beb | https://github.com/browserify/common-shakeify/blob/1325412e3480b49cbfee4e0931a7fbf14d9e9beb/index.js#L156-L167 |
22,226 | rexxars/sse-channel | lib/sse-channel.js | function(options) {
var opts = options || {};
if (opts.cors !== false) {
this.cors = access(merge({
origins: [],
methods: ['GET', 'HEAD', 'OPTIONS'],
headers: ['Last-Event-ID']
}, opts.cors || {}));
}
var jsonEncode = (
typeof opts.jsonEncode === 'undefined' ?
false :
Boolean(opts.jsonEncode)
);
this.jsonEncode = jsonEncode;
this.historySize = opts.historySize || 500;
this.retryTimeout = opts.retryTimeout || null;
this.pingInterval = (opts.pingInterval | 0) || 20000;
// Populate history with the entries specified
this.history = ((opts.history || [])
.filter(hasId)
.slice(0 - this.historySize)
.reverse()
.map(function(msg) {
return {
id: msg.id,
msg: parseMessage(msg, jsonEncode)
};
})
);
this.connections = [];
this.connectionCount = 0;
// Start a timer that will ping all connected clients at a given interval
this.timer = setInterval(this.ping.bind(this), this.pingInterval);
} | javascript | function(options) {
var opts = options || {};
if (opts.cors !== false) {
this.cors = access(merge({
origins: [],
methods: ['GET', 'HEAD', 'OPTIONS'],
headers: ['Last-Event-ID']
}, opts.cors || {}));
}
var jsonEncode = (
typeof opts.jsonEncode === 'undefined' ?
false :
Boolean(opts.jsonEncode)
);
this.jsonEncode = jsonEncode;
this.historySize = opts.historySize || 500;
this.retryTimeout = opts.retryTimeout || null;
this.pingInterval = (opts.pingInterval | 0) || 20000;
// Populate history with the entries specified
this.history = ((opts.history || [])
.filter(hasId)
.slice(0 - this.historySize)
.reverse()
.map(function(msg) {
return {
id: msg.id,
msg: parseMessage(msg, jsonEncode)
};
})
);
this.connections = [];
this.connectionCount = 0;
// Start a timer that will ping all connected clients at a given interval
this.timer = setInterval(this.ping.bind(this), this.pingInterval);
} | [
"function",
"(",
"options",
")",
"{",
"var",
"opts",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"opts",
".",
"cors",
"!==",
"false",
")",
"{",
"this",
".",
"cors",
"=",
"access",
"(",
"merge",
"(",
"{",
"origins",
":",
"[",
"]",
",",
"methods",
":",
"[",
"'GET'",
",",
"'HEAD'",
",",
"'OPTIONS'",
"]",
",",
"headers",
":",
"[",
"'Last-Event-ID'",
"]",
"}",
",",
"opts",
".",
"cors",
"||",
"{",
"}",
")",
")",
";",
"}",
"var",
"jsonEncode",
"=",
"(",
"typeof",
"opts",
".",
"jsonEncode",
"===",
"'undefined'",
"?",
"false",
":",
"Boolean",
"(",
"opts",
".",
"jsonEncode",
")",
")",
";",
"this",
".",
"jsonEncode",
"=",
"jsonEncode",
";",
"this",
".",
"historySize",
"=",
"opts",
".",
"historySize",
"||",
"500",
";",
"this",
".",
"retryTimeout",
"=",
"opts",
".",
"retryTimeout",
"||",
"null",
";",
"this",
".",
"pingInterval",
"=",
"(",
"opts",
".",
"pingInterval",
"|",
"0",
")",
"||",
"20000",
";",
"// Populate history with the entries specified",
"this",
".",
"history",
"=",
"(",
"(",
"opts",
".",
"history",
"||",
"[",
"]",
")",
".",
"filter",
"(",
"hasId",
")",
".",
"slice",
"(",
"0",
"-",
"this",
".",
"historySize",
")",
".",
"reverse",
"(",
")",
".",
"map",
"(",
"function",
"(",
"msg",
")",
"{",
"return",
"{",
"id",
":",
"msg",
".",
"id",
",",
"msg",
":",
"parseMessage",
"(",
"msg",
",",
"jsonEncode",
")",
"}",
";",
"}",
")",
")",
";",
"this",
".",
"connections",
"=",
"[",
"]",
";",
"this",
".",
"connectionCount",
"=",
"0",
";",
"// Start a timer that will ping all connected clients at a given interval",
"this",
".",
"timer",
"=",
"setInterval",
"(",
"this",
".",
"ping",
".",
"bind",
"(",
"this",
")",
",",
"this",
".",
"pingInterval",
")",
";",
"}"
] | Server-Sent Events "Channel"
The "channel"-concept is simply a collection of clients which should receive the same messages.
This is useful if you want to have one server which can easily handle different sources and
clients. History is automatically handled for you, as long as each event is accompanied by
a numeric ID. If a client reconnects with a `Last-Event-ID`-header, he receives all messages
newer than the given ID.
@param {Object} options Options for this SSE-channel
@param {Array} options.history An array of messages to pre-populate the history with.
Note: Number of items will equal the max history size,
where the last elements in the array will be the present
@param {Number} options.historySize The maximum number of messages to keep in history
@param {Number} options.retryTimeout Milliseconds clients should wait before reconnecting
@param {Number} options.pingInterval How often the server should send a "ping" to clients
@param {Boolean} options.jsonEncode Whether the client should auto-encode data as JSON before
sending. Defaults to false.
@param {Object} options.cors Cross-Origin request options - uses `access-control`-module,
see https://www.npmjs.org/package/access-control for the
available options. Note that the `Last-Event-ID`-header
needs to be allowed. By default we do not allow any origins.
Pass `false` to disable CORS-checking altogheter. | [
"Server",
"-",
"Sent",
"Events",
"Channel"
] | dc7c42e3c402cb59db256fbcfd5a17775197cede | https://github.com/rexxars/sse-channel/blob/dc7c42e3c402cb59db256fbcfd5a17775197cede/lib/sse-channel.js#L38-L77 | |
22,227 | rexxars/sse-channel | lib/sse-channel.js | initializeConnection | function initializeConnection(opts) {
opts.request.socket.setTimeout(0);
opts.request.socket.setNoDelay(true);
opts.request.socket.setKeepAlive(true);
opts.response.writeHead(200, {
'Content-Type': 'text/event-stream;charset=UTF-8',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
opts.response.write(':ok\n\n');
// Only set retry if it has a sane value
var retry = opts.retry | 0;
if (retry) {
opts.response.write('retry: ' + retry + '\n');
}
// Should we delivar a "preamble" to the client? Required in some cases by Internet Explorer,
// see https://github.com/amvtek/EventSource/wiki/UserGuide for more information
if (opts.preamble) {
opts.response.write(':' + preambleData);
}
flush(opts.response);
} | javascript | function initializeConnection(opts) {
opts.request.socket.setTimeout(0);
opts.request.socket.setNoDelay(true);
opts.request.socket.setKeepAlive(true);
opts.response.writeHead(200, {
'Content-Type': 'text/event-stream;charset=UTF-8',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
opts.response.write(':ok\n\n');
// Only set retry if it has a sane value
var retry = opts.retry | 0;
if (retry) {
opts.response.write('retry: ' + retry + '\n');
}
// Should we delivar a "preamble" to the client? Required in some cases by Internet Explorer,
// see https://github.com/amvtek/EventSource/wiki/UserGuide for more information
if (opts.preamble) {
opts.response.write(':' + preambleData);
}
flush(opts.response);
} | [
"function",
"initializeConnection",
"(",
"opts",
")",
"{",
"opts",
".",
"request",
".",
"socket",
".",
"setTimeout",
"(",
"0",
")",
";",
"opts",
".",
"request",
".",
"socket",
".",
"setNoDelay",
"(",
"true",
")",
";",
"opts",
".",
"request",
".",
"socket",
".",
"setKeepAlive",
"(",
"true",
")",
";",
"opts",
".",
"response",
".",
"writeHead",
"(",
"200",
",",
"{",
"'Content-Type'",
":",
"'text/event-stream;charset=UTF-8'",
",",
"'Cache-Control'",
":",
"'no-cache'",
",",
"'Connection'",
":",
"'keep-alive'",
"}",
")",
";",
"opts",
".",
"response",
".",
"write",
"(",
"':ok\\n\\n'",
")",
";",
"// Only set retry if it has a sane value",
"var",
"retry",
"=",
"opts",
".",
"retry",
"|",
"0",
";",
"if",
"(",
"retry",
")",
"{",
"opts",
".",
"response",
".",
"write",
"(",
"'retry: '",
"+",
"retry",
"+",
"'\\n'",
")",
";",
"}",
"// Should we delivar a \"preamble\" to the client? Required in some cases by Internet Explorer,",
"// see https://github.com/amvtek/EventSource/wiki/UserGuide for more information",
"if",
"(",
"opts",
".",
"preamble",
")",
"{",
"opts",
".",
"response",
".",
"write",
"(",
"':'",
"+",
"preambleData",
")",
";",
"}",
"flush",
"(",
"opts",
".",
"response",
")",
";",
"}"
] | Sends the initial, required headers for the connection
@param {Object} opts Options object
@param {Request} opts.request Request object to use
@param {Response} opts.response Response object to use
@param {Number} opts.retry Time in milliseconds to specify as reconnection timeout
@param {Boolean} opts.preamble Whether to send a "preamble" of dummy data to the client | [
"Sends",
"the",
"initial",
"required",
"headers",
"for",
"the",
"connection"
] | dc7c42e3c402cb59db256fbcfd5a17775197cede | https://github.com/rexxars/sse-channel/blob/dc7c42e3c402cb59db256fbcfd5a17775197cede/lib/sse-channel.js#L265-L290 |
22,228 | rexxars/sse-channel | lib/sse-channel.js | broadcast | function broadcast(connections, packet) {
var i = connections.length;
while (i--) {
connections[i].write(packet);
flush(connections[i]);
}
} | javascript | function broadcast(connections, packet) {
var i = connections.length;
while (i--) {
connections[i].write(packet);
flush(connections[i]);
}
} | [
"function",
"broadcast",
"(",
"connections",
",",
"packet",
")",
"{",
"var",
"i",
"=",
"connections",
".",
"length",
";",
"while",
"(",
"i",
"--",
")",
"{",
"connections",
"[",
"i",
"]",
".",
"write",
"(",
"packet",
")",
";",
"flush",
"(",
"connections",
"[",
"i",
"]",
")",
";",
"}",
"}"
] | Broadcast a packet to all connected clients
@param {Array} connections Array of connections (response instances) to write to
@param {String} packet The chunk of data to broadcast | [
"Broadcast",
"a",
"packet",
"to",
"all",
"connected",
"clients"
] | dc7c42e3c402cb59db256fbcfd5a17775197cede | https://github.com/rexxars/sse-channel/blob/dc7c42e3c402cb59db256fbcfd5a17775197cede/lib/sse-channel.js#L298-L304 |
22,229 | rexxars/sse-channel | lib/sse-channel.js | parseTextData | function parseTextData(text) {
var data = String(text).replace(/(\r\n|\r|\n)/g, '\n');
var lines = data.split(/\n/), line;
var output = '';
for (var i = 0, l = lines.length; i < l; ++i) {
line = lines[i];
output += 'data: ' + line;
output += (i + 1) === l ? '\n\n' : '\n';
}
return output;
} | javascript | function parseTextData(text) {
var data = String(text).replace(/(\r\n|\r|\n)/g, '\n');
var lines = data.split(/\n/), line;
var output = '';
for (var i = 0, l = lines.length; i < l; ++i) {
line = lines[i];
output += 'data: ' + line;
output += (i + 1) === l ? '\n\n' : '\n';
}
return output;
} | [
"function",
"parseTextData",
"(",
"text",
")",
"{",
"var",
"data",
"=",
"String",
"(",
"text",
")",
".",
"replace",
"(",
"/",
"(\\r\\n|\\r|\\n)",
"/",
"g",
",",
"'\\n'",
")",
";",
"var",
"lines",
"=",
"data",
".",
"split",
"(",
"/",
"\\n",
"/",
")",
",",
"line",
";",
"var",
"output",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"lines",
".",
"length",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"{",
"line",
"=",
"lines",
"[",
"i",
"]",
";",
"output",
"+=",
"'data: '",
"+",
"line",
";",
"output",
"+=",
"(",
"i",
"+",
"1",
")",
"===",
"l",
"?",
"'\\n\\n'",
":",
"'\\n'",
";",
"}",
"return",
"output",
";",
"}"
] | Parse text data, ensuring it doesn't break the SSE-protocol
@param {String} text
@return {String} | [
"Parse",
"text",
"data",
"ensuring",
"it",
"doesn",
"t",
"break",
"the",
"SSE",
"-",
"protocol"
] | dc7c42e3c402cb59db256fbcfd5a17775197cede | https://github.com/rexxars/sse-channel/blob/dc7c42e3c402cb59db256fbcfd5a17775197cede/lib/sse-channel.js#L365-L378 |
22,230 | rexxars/sse-channel | examples/client/client-example.js | drawChart | function drawChart(canvas, data) {
var ctx = canvas.getContext('2d'),
color = 'rgba(0, 0, 0, 0.75)',
height = canvas.height - 2,
width = canvas.width,
total = data.length,
max = Math.max.apply(Math, data),
xstep = 1,
ystep = max / height,
x = 0,
y = height - data[0] / ystep;
ctx.clearRect(0, 0, width, height);
ctx.beginPath();
ctx.strokeStyle = color;
ctx.moveTo(x, y);
for (var i = 1; i < total; i++) {
x += xstep;
y = height - data[i] / ystep + 1;
ctx.moveTo(x, height);
ctx.lineTo(x, y);
}
ctx.stroke();
} | javascript | function drawChart(canvas, data) {
var ctx = canvas.getContext('2d'),
color = 'rgba(0, 0, 0, 0.75)',
height = canvas.height - 2,
width = canvas.width,
total = data.length,
max = Math.max.apply(Math, data),
xstep = 1,
ystep = max / height,
x = 0,
y = height - data[0] / ystep;
ctx.clearRect(0, 0, width, height);
ctx.beginPath();
ctx.strokeStyle = color;
ctx.moveTo(x, y);
for (var i = 1; i < total; i++) {
x += xstep;
y = height - data[i] / ystep + 1;
ctx.moveTo(x, height);
ctx.lineTo(x, y);
}
ctx.stroke();
} | [
"function",
"drawChart",
"(",
"canvas",
",",
"data",
")",
"{",
"var",
"ctx",
"=",
"canvas",
".",
"getContext",
"(",
"'2d'",
")",
",",
"color",
"=",
"'rgba(0, 0, 0, 0.75)'",
",",
"height",
"=",
"canvas",
".",
"height",
"-",
"2",
",",
"width",
"=",
"canvas",
".",
"width",
",",
"total",
"=",
"data",
".",
"length",
",",
"max",
"=",
"Math",
".",
"max",
".",
"apply",
"(",
"Math",
",",
"data",
")",
",",
"xstep",
"=",
"1",
",",
"ystep",
"=",
"max",
"/",
"height",
",",
"x",
"=",
"0",
",",
"y",
"=",
"height",
"-",
"data",
"[",
"0",
"]",
"/",
"ystep",
";",
"ctx",
".",
"clearRect",
"(",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
";",
"ctx",
".",
"beginPath",
"(",
")",
";",
"ctx",
".",
"strokeStyle",
"=",
"color",
";",
"ctx",
".",
"moveTo",
"(",
"x",
",",
"y",
")",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"total",
";",
"i",
"++",
")",
"{",
"x",
"+=",
"xstep",
";",
"y",
"=",
"height",
"-",
"data",
"[",
"i",
"]",
"/",
"ystep",
"+",
"1",
";",
"ctx",
".",
"moveTo",
"(",
"x",
",",
"height",
")",
";",
"ctx",
".",
"lineTo",
"(",
"x",
",",
"y",
")",
";",
"}",
"ctx",
".",
"stroke",
"(",
")",
";",
"}"
] | Just a simple chart drawer, not related to SSE-channel | [
"Just",
"a",
"simple",
"chart",
"drawer",
"not",
"related",
"to",
"SSE",
"-",
"channel"
] | dc7c42e3c402cb59db256fbcfd5a17775197cede | https://github.com/rexxars/sse-channel/blob/dc7c42e3c402cb59db256fbcfd5a17775197cede/examples/client/client-example.js#L70-L95 |
22,231 | dirkgroenen/simple-jQuery-slider | src/jquery.simpleslider.js | triggerSlideEnd | function triggerSlideEnd(){
if(!slided){
if(options.transition == "fade"){
$(options.slidesContainer).find(options.slides).each(function(index){
if($(this).data('index') == obj.currentSlide){
$(this).show();
}
else{
$(this).hide();
}
});
}
// Reset to the first slide when neverEnding has been enabled and the 'faked' last slide is active
if(options.transition == "slide" && options.neverEnding){
// Check if it's the 'last' slide
if(obj.currentSlide == obj.totalSlides - 1 && prevSlide === 0){
if ($.support.transition && jQuery().transition)
$(movecontainer).stop().transition({x: -(obj.totalSlides) * 100 + "%"}, 1, 'linear');
else
$(movecontainer).css({left: -(obj.totalSlides) * 100 + "%"});
}
// Check if it's the 'first' slide
if(obj.currentSlide === 0 && prevSlide == obj.totalSlides - 1){
if ($.support.transition && jQuery().transition)
$(movecontainer).stop().transition({x: "-100%"}, 1, 'linear');
else
$(movecontainer).css({left: "-100%"});
}
}
// Trigger event
var afterSlidingEvent = jQuery.Event("afterSliding", {
prevSlide: prevSlide,
newSlide: obj.currentSlide
});
$(element).trigger(afterSlidingEvent);
slided = true;
}
} | javascript | function triggerSlideEnd(){
if(!slided){
if(options.transition == "fade"){
$(options.slidesContainer).find(options.slides).each(function(index){
if($(this).data('index') == obj.currentSlide){
$(this).show();
}
else{
$(this).hide();
}
});
}
// Reset to the first slide when neverEnding has been enabled and the 'faked' last slide is active
if(options.transition == "slide" && options.neverEnding){
// Check if it's the 'last' slide
if(obj.currentSlide == obj.totalSlides - 1 && prevSlide === 0){
if ($.support.transition && jQuery().transition)
$(movecontainer).stop().transition({x: -(obj.totalSlides) * 100 + "%"}, 1, 'linear');
else
$(movecontainer).css({left: -(obj.totalSlides) * 100 + "%"});
}
// Check if it's the 'first' slide
if(obj.currentSlide === 0 && prevSlide == obj.totalSlides - 1){
if ($.support.transition && jQuery().transition)
$(movecontainer).stop().transition({x: "-100%"}, 1, 'linear');
else
$(movecontainer).css({left: "-100%"});
}
}
// Trigger event
var afterSlidingEvent = jQuery.Event("afterSliding", {
prevSlide: prevSlide,
newSlide: obj.currentSlide
});
$(element).trigger(afterSlidingEvent);
slided = true;
}
} | [
"function",
"triggerSlideEnd",
"(",
")",
"{",
"if",
"(",
"!",
"slided",
")",
"{",
"if",
"(",
"options",
".",
"transition",
"==",
"\"fade\"",
")",
"{",
"$",
"(",
"options",
".",
"slidesContainer",
")",
".",
"find",
"(",
"options",
".",
"slides",
")",
".",
"each",
"(",
"function",
"(",
"index",
")",
"{",
"if",
"(",
"$",
"(",
"this",
")",
".",
"data",
"(",
"'index'",
")",
"==",
"obj",
".",
"currentSlide",
")",
"{",
"$",
"(",
"this",
")",
".",
"show",
"(",
")",
";",
"}",
"else",
"{",
"$",
"(",
"this",
")",
".",
"hide",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"// Reset to the first slide when neverEnding has been enabled and the 'faked' last slide is active",
"if",
"(",
"options",
".",
"transition",
"==",
"\"slide\"",
"&&",
"options",
".",
"neverEnding",
")",
"{",
"// Check if it's the 'last' slide",
"if",
"(",
"obj",
".",
"currentSlide",
"==",
"obj",
".",
"totalSlides",
"-",
"1",
"&&",
"prevSlide",
"===",
"0",
")",
"{",
"if",
"(",
"$",
".",
"support",
".",
"transition",
"&&",
"jQuery",
"(",
")",
".",
"transition",
")",
"$",
"(",
"movecontainer",
")",
".",
"stop",
"(",
")",
".",
"transition",
"(",
"{",
"x",
":",
"-",
"(",
"obj",
".",
"totalSlides",
")",
"*",
"100",
"+",
"\"%\"",
"}",
",",
"1",
",",
"'linear'",
")",
";",
"else",
"$",
"(",
"movecontainer",
")",
".",
"css",
"(",
"{",
"left",
":",
"-",
"(",
"obj",
".",
"totalSlides",
")",
"*",
"100",
"+",
"\"%\"",
"}",
")",
";",
"}",
"// Check if it's the 'first' slide",
"if",
"(",
"obj",
".",
"currentSlide",
"===",
"0",
"&&",
"prevSlide",
"==",
"obj",
".",
"totalSlides",
"-",
"1",
")",
"{",
"if",
"(",
"$",
".",
"support",
".",
"transition",
"&&",
"jQuery",
"(",
")",
".",
"transition",
")",
"$",
"(",
"movecontainer",
")",
".",
"stop",
"(",
")",
".",
"transition",
"(",
"{",
"x",
":",
"\"-100%\"",
"}",
",",
"1",
",",
"'linear'",
")",
";",
"else",
"$",
"(",
"movecontainer",
")",
".",
"css",
"(",
"{",
"left",
":",
"\"-100%\"",
"}",
")",
";",
"}",
"}",
"// Trigger event",
"var",
"afterSlidingEvent",
"=",
"jQuery",
".",
"Event",
"(",
"\"afterSliding\"",
",",
"{",
"prevSlide",
":",
"prevSlide",
",",
"newSlide",
":",
"obj",
".",
"currentSlide",
"}",
")",
";",
"$",
"(",
"element",
")",
".",
"trigger",
"(",
"afterSlidingEvent",
")",
";",
"slided",
"=",
"true",
";",
"}",
"}"
] | Create trigger point after a slide slides. All the slides return a TransitionEnd; to prevent a repeating trigger we keep a slided var | [
"Create",
"trigger",
"point",
"after",
"a",
"slide",
"slides",
".",
"All",
"the",
"slides",
"return",
"a",
"TransitionEnd",
";",
"to",
"prevent",
"a",
"repeating",
"trigger",
"we",
"keep",
"a",
"slided",
"var"
] | d4cf1c3192fcba28510598831f607b41cad88354 | https://github.com/dirkgroenen/simple-jQuery-slider/blob/d4cf1c3192fcba28510598831f607b41cad88354/src/jquery.simpleslider.js#L423-L465 |
22,232 | jaywcjlove/svgtofont | src/generate.js | buildPathsObject | async function buildPathsObject(files) {
return Promise.all(
files.map(async filepath => {
const name = path.basename(filepath, '.svg');
const svg = fs.readFileSync(filepath, 'utf-8');
const pathStrings = await svgo.optimize(svg, { path: filepath })
.then(({ data }) => data.match(/ d="[^"]+"/g) || [])
.then(paths => paths.map(s => s.slice(3)));
return `"${name}": [${pathStrings.join(',\n')}]`;
}),
);
} | javascript | async function buildPathsObject(files) {
return Promise.all(
files.map(async filepath => {
const name = path.basename(filepath, '.svg');
const svg = fs.readFileSync(filepath, 'utf-8');
const pathStrings = await svgo.optimize(svg, { path: filepath })
.then(({ data }) => data.match(/ d="[^"]+"/g) || [])
.then(paths => paths.map(s => s.slice(3)));
return `"${name}": [${pathStrings.join(',\n')}]`;
}),
);
} | [
"async",
"function",
"buildPathsObject",
"(",
"files",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"files",
".",
"map",
"(",
"async",
"filepath",
"=>",
"{",
"const",
"name",
"=",
"path",
".",
"basename",
"(",
"filepath",
",",
"'.svg'",
")",
";",
"const",
"svg",
"=",
"fs",
".",
"readFileSync",
"(",
"filepath",
",",
"'utf-8'",
")",
";",
"const",
"pathStrings",
"=",
"await",
"svgo",
".",
"optimize",
"(",
"svg",
",",
"{",
"path",
":",
"filepath",
"}",
")",
".",
"then",
"(",
"(",
"{",
"data",
"}",
")",
"=>",
"data",
".",
"match",
"(",
"/",
" d=\"[^\"]+\"",
"/",
"g",
")",
"||",
"[",
"]",
")",
".",
"then",
"(",
"paths",
"=>",
"paths",
".",
"map",
"(",
"s",
"=>",
"s",
".",
"slice",
"(",
"3",
")",
")",
")",
";",
"return",
"`",
"${",
"name",
"}",
"${",
"pathStrings",
".",
"join",
"(",
"',\\n'",
")",
"}",
"`",
";",
"}",
")",
",",
")",
";",
"}"
] | Loads SVG file for each icon, extracts path strings `d="path-string"`,
and constructs map of icon name to array of path strings.
@param {array} files | [
"Loads",
"SVG",
"file",
"for",
"each",
"icon",
"extracts",
"path",
"strings",
"d",
"=",
"path",
"-",
"string",
"and",
"constructs",
"map",
"of",
"icon",
"name",
"to",
"array",
"of",
"path",
"strings",
"."
] | 59473c853868e01968569e6ca6292d322cdc68fa | https://github.com/jaywcjlove/svgtofont/blob/59473c853868e01968569e6ca6292d322cdc68fa/src/generate.js#L29-L40 |
22,233 | blake-regalia/graphy.js | src/future/linked.js | mk_NodeSet | function mk_NodeSet(k_graph, a_terms, s_term_types) {
// prep to reduce nodes to a set
let h_nodes = {};
// nodes are all NamedNodes
if('NamedNode' === s_term_types) {
for(let i_term=0; i_term<a_terms.length; i_term++) {
let h_term = a_terms[i_term];
h_nodes[h_term.value] = h_term;
}
}
// nodes are all BlankNodes
else if('BlankNodes' === s_term_types) {
for(let i_term=0; i_term<a_terms.length; i_term++) {
let h_term = a_terms[i_term];
h_nodes['_:'+h_term.value] = h_term;
}
}
// nodes are mixed
else {
for(let i_term=0; i_term<a_terms.length; i_term++) {
let h_term = a_terms[i_term];
h_nodes[h_term.isBlankNode? '_:'+h_term.value: h_term.value] = h_term;
}
}
// reduce nodes to a set
let as_nodes = [];
for(let s_node_id in h_nodes) {
let k_node = k_graph.nodes[s_node_id]
|| k_graph.leafs[s_node_id]
|| (k_graph.leafs[s_node_id] = new Node(k_graph, [], h_nodes[s_node_id]));
// only add subject nodes that exist to the set
if(k_node) as_nodes.push(k_node);
}
// make instance
let h_methods = Object.assign(Object.create(NodeSet_prototype), {
graph: k_graph,
nodes: as_nodes,
areNodes: true,
});
// construct 'that'
let f_bound = NodeSet_operator.bind(h_methods);
// save to list so we can reuse it
a_terms.set = f_bound;
// make & return operator
Object.setPrototypeOf(f_bound, NodeSet_prototype);
return Object.assign(f_bound, h_methods);
} | javascript | function mk_NodeSet(k_graph, a_terms, s_term_types) {
// prep to reduce nodes to a set
let h_nodes = {};
// nodes are all NamedNodes
if('NamedNode' === s_term_types) {
for(let i_term=0; i_term<a_terms.length; i_term++) {
let h_term = a_terms[i_term];
h_nodes[h_term.value] = h_term;
}
}
// nodes are all BlankNodes
else if('BlankNodes' === s_term_types) {
for(let i_term=0; i_term<a_terms.length; i_term++) {
let h_term = a_terms[i_term];
h_nodes['_:'+h_term.value] = h_term;
}
}
// nodes are mixed
else {
for(let i_term=0; i_term<a_terms.length; i_term++) {
let h_term = a_terms[i_term];
h_nodes[h_term.isBlankNode? '_:'+h_term.value: h_term.value] = h_term;
}
}
// reduce nodes to a set
let as_nodes = [];
for(let s_node_id in h_nodes) {
let k_node = k_graph.nodes[s_node_id]
|| k_graph.leafs[s_node_id]
|| (k_graph.leafs[s_node_id] = new Node(k_graph, [], h_nodes[s_node_id]));
// only add subject nodes that exist to the set
if(k_node) as_nodes.push(k_node);
}
// make instance
let h_methods = Object.assign(Object.create(NodeSet_prototype), {
graph: k_graph,
nodes: as_nodes,
areNodes: true,
});
// construct 'that'
let f_bound = NodeSet_operator.bind(h_methods);
// save to list so we can reuse it
a_terms.set = f_bound;
// make & return operator
Object.setPrototypeOf(f_bound, NodeSet_prototype);
return Object.assign(f_bound, h_methods);
} | [
"function",
"mk_NodeSet",
"(",
"k_graph",
",",
"a_terms",
",",
"s_term_types",
")",
"{",
"// prep to reduce nodes to a set",
"let",
"h_nodes",
"=",
"{",
"}",
";",
"// nodes are all NamedNodes",
"if",
"(",
"'NamedNode'",
"===",
"s_term_types",
")",
"{",
"for",
"(",
"let",
"i_term",
"=",
"0",
";",
"i_term",
"<",
"a_terms",
".",
"length",
";",
"i_term",
"++",
")",
"{",
"let",
"h_term",
"=",
"a_terms",
"[",
"i_term",
"]",
";",
"h_nodes",
"[",
"h_term",
".",
"value",
"]",
"=",
"h_term",
";",
"}",
"}",
"// nodes are all BlankNodes",
"else",
"if",
"(",
"'BlankNodes'",
"===",
"s_term_types",
")",
"{",
"for",
"(",
"let",
"i_term",
"=",
"0",
";",
"i_term",
"<",
"a_terms",
".",
"length",
";",
"i_term",
"++",
")",
"{",
"let",
"h_term",
"=",
"a_terms",
"[",
"i_term",
"]",
";",
"h_nodes",
"[",
"'_:'",
"+",
"h_term",
".",
"value",
"]",
"=",
"h_term",
";",
"}",
"}",
"// nodes are mixed",
"else",
"{",
"for",
"(",
"let",
"i_term",
"=",
"0",
";",
"i_term",
"<",
"a_terms",
".",
"length",
";",
"i_term",
"++",
")",
"{",
"let",
"h_term",
"=",
"a_terms",
"[",
"i_term",
"]",
";",
"h_nodes",
"[",
"h_term",
".",
"isBlankNode",
"?",
"'_:'",
"+",
"h_term",
".",
"value",
":",
"h_term",
".",
"value",
"]",
"=",
"h_term",
";",
"}",
"}",
"// reduce nodes to a set",
"let",
"as_nodes",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"s_node_id",
"in",
"h_nodes",
")",
"{",
"let",
"k_node",
"=",
"k_graph",
".",
"nodes",
"[",
"s_node_id",
"]",
"||",
"k_graph",
".",
"leafs",
"[",
"s_node_id",
"]",
"||",
"(",
"k_graph",
".",
"leafs",
"[",
"s_node_id",
"]",
"=",
"new",
"Node",
"(",
"k_graph",
",",
"[",
"]",
",",
"h_nodes",
"[",
"s_node_id",
"]",
")",
")",
";",
"// only add subject nodes that exist to the set",
"if",
"(",
"k_node",
")",
"as_nodes",
".",
"push",
"(",
"k_node",
")",
";",
"}",
"// make instance",
"let",
"h_methods",
"=",
"Object",
".",
"assign",
"(",
"Object",
".",
"create",
"(",
"NodeSet_prototype",
")",
",",
"{",
"graph",
":",
"k_graph",
",",
"nodes",
":",
"as_nodes",
",",
"areNodes",
":",
"true",
",",
"}",
")",
";",
"// construct 'that'",
"let",
"f_bound",
"=",
"NodeSet_operator",
".",
"bind",
"(",
"h_methods",
")",
";",
"// save to list so we can reuse it",
"a_terms",
".",
"set",
"=",
"f_bound",
";",
"// make & return operator",
"Object",
".",
"setPrototypeOf",
"(",
"f_bound",
",",
"NodeSet_prototype",
")",
";",
"return",
"Object",
".",
"assign",
"(",
"f_bound",
",",
"h_methods",
")",
";",
"}"
] | makes a new NodeSet | [
"makes",
"a",
"new",
"NodeSet"
] | fa1373c59167ca448600eb94cd8690c21509d071 | https://github.com/blake-regalia/graphy.js/blob/fa1373c59167ca448600eb94cd8690c21509d071/src/future/linked.js#L250-L304 |
22,234 | blake-regalia/graphy.js | src/future/linked.js | mk_LiteralBunch | function mk_LiteralBunch(k_graph, a_terms) {
// append local methods to hash
let h_methods = Object.assign(Object.create(LiteralBunch_prototype), {
graph: k_graph,
terms: a_terms,
// for returning a different sample each time
sample_counter: 0,
});
// construct 'that'
let f_bound = LiteralBunch_operator.bind(h_methods);
// make & return operator
Object.setPrototypeOf(f_bound, LiteralBunch_prototype);
return Object.assign(f_bound, h_methods);
} | javascript | function mk_LiteralBunch(k_graph, a_terms) {
// append local methods to hash
let h_methods = Object.assign(Object.create(LiteralBunch_prototype), {
graph: k_graph,
terms: a_terms,
// for returning a different sample each time
sample_counter: 0,
});
// construct 'that'
let f_bound = LiteralBunch_operator.bind(h_methods);
// make & return operator
Object.setPrototypeOf(f_bound, LiteralBunch_prototype);
return Object.assign(f_bound, h_methods);
} | [
"function",
"mk_LiteralBunch",
"(",
"k_graph",
",",
"a_terms",
")",
"{",
"// append local methods to hash",
"let",
"h_methods",
"=",
"Object",
".",
"assign",
"(",
"Object",
".",
"create",
"(",
"LiteralBunch_prototype",
")",
",",
"{",
"graph",
":",
"k_graph",
",",
"terms",
":",
"a_terms",
",",
"// for returning a different sample each time",
"sample_counter",
":",
"0",
",",
"}",
")",
";",
"// construct 'that'",
"let",
"f_bound",
"=",
"LiteralBunch_operator",
".",
"bind",
"(",
"h_methods",
")",
";",
"// make & return operator",
"Object",
".",
"setPrototypeOf",
"(",
"f_bound",
",",
"LiteralBunch_prototype",
")",
";",
"return",
"Object",
".",
"assign",
"(",
"f_bound",
",",
"h_methods",
")",
";",
"}"
] | makes a new LiteralBunch | [
"makes",
"a",
"new",
"LiteralBunch"
] | fa1373c59167ca448600eb94cd8690c21509d071 | https://github.com/blake-regalia/graphy.js/blob/fa1373c59167ca448600eb94cd8690c21509d071/src/future/linked.js#L355-L371 |
22,235 | blake-regalia/graphy.js | src/future/linked.js | LiteralBunch_operator | function LiteralBunch_operator(z_literal_filter) {
// user wants to filter literal by language or datatype
if('string' === typeof z_literal_filter) {
// by language tag
if('@' === z_literal_filter[0]) {
// ref language tag
let s_language = z_literal_filter.slice(1).toLowerCase();
// apply filter
this.terms = this.terms.filter((h_term) => {
return s_language === h_term.language;
});
}
// by datatype
else {
// resolve datatype iri
let p_datatype = this.graph.resolve(z_literal_filter);
// apply filter
this.terms = this.terms.filter((h_term) => {
return p_datatype === h_term.datatype;
});
}
}
// user wants to filter literal by a function
else if('function' === typeof z_literal_filter) {
// apply filter
this.terms = this.terms.filter(z_literal_filter);
}
// results / no filtering
return this;
} | javascript | function LiteralBunch_operator(z_literal_filter) {
// user wants to filter literal by language or datatype
if('string' === typeof z_literal_filter) {
// by language tag
if('@' === z_literal_filter[0]) {
// ref language tag
let s_language = z_literal_filter.slice(1).toLowerCase();
// apply filter
this.terms = this.terms.filter((h_term) => {
return s_language === h_term.language;
});
}
// by datatype
else {
// resolve datatype iri
let p_datatype = this.graph.resolve(z_literal_filter);
// apply filter
this.terms = this.terms.filter((h_term) => {
return p_datatype === h_term.datatype;
});
}
}
// user wants to filter literal by a function
else if('function' === typeof z_literal_filter) {
// apply filter
this.terms = this.terms.filter(z_literal_filter);
}
// results / no filtering
return this;
} | [
"function",
"LiteralBunch_operator",
"(",
"z_literal_filter",
")",
"{",
"// user wants to filter literal by language or datatype",
"if",
"(",
"'string'",
"===",
"typeof",
"z_literal_filter",
")",
"{",
"// by language tag",
"if",
"(",
"'@'",
"===",
"z_literal_filter",
"[",
"0",
"]",
")",
"{",
"// ref language tag",
"let",
"s_language",
"=",
"z_literal_filter",
".",
"slice",
"(",
"1",
")",
".",
"toLowerCase",
"(",
")",
";",
"// apply filter",
"this",
".",
"terms",
"=",
"this",
".",
"terms",
".",
"filter",
"(",
"(",
"h_term",
")",
"=>",
"{",
"return",
"s_language",
"===",
"h_term",
".",
"language",
";",
"}",
")",
";",
"}",
"// by datatype",
"else",
"{",
"// resolve datatype iri",
"let",
"p_datatype",
"=",
"this",
".",
"graph",
".",
"resolve",
"(",
"z_literal_filter",
")",
";",
"// apply filter",
"this",
".",
"terms",
"=",
"this",
".",
"terms",
".",
"filter",
"(",
"(",
"h_term",
")",
"=>",
"{",
"return",
"p_datatype",
"===",
"h_term",
".",
"datatype",
";",
"}",
")",
";",
"}",
"}",
"// user wants to filter literal by a function",
"else",
"if",
"(",
"'function'",
"===",
"typeof",
"z_literal_filter",
")",
"{",
"// apply filter",
"this",
".",
"terms",
"=",
"this",
".",
"terms",
".",
"filter",
"(",
"z_literal_filter",
")",
";",
"}",
"// results / no filtering",
"return",
"this",
";",
"}"
] | mutates the LiteralBunch exactly once with the given filter argument | [
"mutates",
"the",
"LiteralBunch",
"exactly",
"once",
"with",
"the",
"given",
"filter",
"argument"
] | fa1373c59167ca448600eb94cd8690c21509d071 | https://github.com/blake-regalia/graphy.js/blob/fa1373c59167ca448600eb94cd8690c21509d071/src/future/linked.js#L374-L406 |
22,236 | mkloubert/nativescript-bitmap-factory | plugin/index.js | asBitmap | function asBitmap(v, throwException) {
if (throwException === void 0) { throwException = true; }
var result = BitmapFactory.asBitmapObject(v);
if (throwException && (false === result)) {
throw "No valid value for a bitmap!";
}
return result;
} | javascript | function asBitmap(v, throwException) {
if (throwException === void 0) { throwException = true; }
var result = BitmapFactory.asBitmapObject(v);
if (throwException && (false === result)) {
throw "No valid value for a bitmap!";
}
return result;
} | [
"function",
"asBitmap",
"(",
"v",
",",
"throwException",
")",
"{",
"if",
"(",
"throwException",
"===",
"void",
"0",
")",
"{",
"throwException",
"=",
"true",
";",
"}",
"var",
"result",
"=",
"BitmapFactory",
".",
"asBitmapObject",
"(",
"v",
")",
";",
"if",
"(",
"throwException",
"&&",
"(",
"false",
"===",
"result",
")",
")",
"{",
"throw",
"\"No valid value for a bitmap!\"",
";",
"}",
"return",
"result",
";",
"}"
] | Returns a value as bitmap object.
@param any v The input value.
@param {Boolean} [throwException] Throw exception if 'v' is invalid or return (false).
@throws Input value is invalid.
@return {IBitmap} The output value or (false) if input value is invalid. | [
"Returns",
"a",
"value",
"as",
"bitmap",
"object",
"."
] | 0e16a64f4b7c5794a1c66cd025c6f5759be899f6 | https://github.com/mkloubert/nativescript-bitmap-factory/blob/0e16a64f4b7c5794a1c66cd025c6f5759be899f6/plugin/index.js#L71-L78 |
22,237 | mkloubert/nativescript-bitmap-factory | plugin/index.js | create | function create(width, height, opts) {
if (TypeUtils.isNullOrUndefined(height)) {
height = width;
}
if (arguments.length < 3) {
opts = getDefaultOptions();
}
if (TypeUtils.isNullOrUndefined(opts)) {
opts = {};
}
return BitmapFactory.createBitmap(width, height, opts);
} | javascript | function create(width, height, opts) {
if (TypeUtils.isNullOrUndefined(height)) {
height = width;
}
if (arguments.length < 3) {
opts = getDefaultOptions();
}
if (TypeUtils.isNullOrUndefined(opts)) {
opts = {};
}
return BitmapFactory.createBitmap(width, height, opts);
} | [
"function",
"create",
"(",
"width",
",",
"height",
",",
"opts",
")",
"{",
"if",
"(",
"TypeUtils",
".",
"isNullOrUndefined",
"(",
"height",
")",
")",
"{",
"height",
"=",
"width",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
"<",
"3",
")",
"{",
"opts",
"=",
"getDefaultOptions",
"(",
")",
";",
"}",
"if",
"(",
"TypeUtils",
".",
"isNullOrUndefined",
"(",
"opts",
")",
")",
"{",
"opts",
"=",
"{",
"}",
";",
"}",
"return",
"BitmapFactory",
".",
"createBitmap",
"(",
"width",
",",
"height",
",",
"opts",
")",
";",
"}"
] | Creates a new bitmap.
@param {Number} width The width of the new image.
@param {Number} [height] The optional height of the new image. If not defined, the width is taken as value.
@param {ICreateBitmapOptions} [opts] Additional options for creating the bitmap.
@return {IBitmap} The new bitmap. | [
"Creates",
"a",
"new",
"bitmap",
"."
] | 0e16a64f4b7c5794a1c66cd025c6f5759be899f6 | https://github.com/mkloubert/nativescript-bitmap-factory/blob/0e16a64f4b7c5794a1c66cd025c6f5759be899f6/plugin/index.js#L89-L100 |
22,238 | prawnsalad/KiwiIRC | client/src/models/member.js | function (modes) {
var that = this;
return modes.sort(function (a, b) {
var a_idx, b_idx, i;
var user_prefixes = that.get('user_prefixes');
for (i = 0; i < user_prefixes.length; i++) {
if (user_prefixes[i].mode === a) {
a_idx = i;
}
}
for (i = 0; i < user_prefixes.length; i++) {
if (user_prefixes[i].mode === b) {
b_idx = i;
}
}
if (a_idx < b_idx) {
return -1;
} else if (a_idx > b_idx) {
return 1;
} else {
return 0;
}
});
} | javascript | function (modes) {
var that = this;
return modes.sort(function (a, b) {
var a_idx, b_idx, i;
var user_prefixes = that.get('user_prefixes');
for (i = 0; i < user_prefixes.length; i++) {
if (user_prefixes[i].mode === a) {
a_idx = i;
}
}
for (i = 0; i < user_prefixes.length; i++) {
if (user_prefixes[i].mode === b) {
b_idx = i;
}
}
if (a_idx < b_idx) {
return -1;
} else if (a_idx > b_idx) {
return 1;
} else {
return 0;
}
});
} | [
"function",
"(",
"modes",
")",
"{",
"var",
"that",
"=",
"this",
";",
"return",
"modes",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"var",
"a_idx",
",",
"b_idx",
",",
"i",
";",
"var",
"user_prefixes",
"=",
"that",
".",
"get",
"(",
"'user_prefixes'",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"user_prefixes",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"user_prefixes",
"[",
"i",
"]",
".",
"mode",
"===",
"a",
")",
"{",
"a_idx",
"=",
"i",
";",
"}",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"user_prefixes",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"user_prefixes",
"[",
"i",
"]",
".",
"mode",
"===",
"b",
")",
"{",
"b_idx",
"=",
"i",
";",
"}",
"}",
"if",
"(",
"a_idx",
"<",
"b_idx",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"a_idx",
">",
"b_idx",
")",
"{",
"return",
"1",
";",
"}",
"else",
"{",
"return",
"0",
";",
"}",
"}",
")",
";",
"}"
] | Sort modes in order of importance | [
"Sort",
"modes",
"in",
"order",
"of",
"importance"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/models/member.js#L24-L51 | |
22,239 | prawnsalad/KiwiIRC | client/src/models/member.js | function (modes) {
var prefix = '';
var user_prefixes = this.get('user_prefixes');
if (typeof modes[0] !== 'undefined') {
prefix = _.detect(user_prefixes, function (prefix) {
return prefix.mode === modes[0];
});
prefix = (prefix) ? prefix.symbol : '';
}
return prefix;
} | javascript | function (modes) {
var prefix = '';
var user_prefixes = this.get('user_prefixes');
if (typeof modes[0] !== 'undefined') {
prefix = _.detect(user_prefixes, function (prefix) {
return prefix.mode === modes[0];
});
prefix = (prefix) ? prefix.symbol : '';
}
return prefix;
} | [
"function",
"(",
"modes",
")",
"{",
"var",
"prefix",
"=",
"''",
";",
"var",
"user_prefixes",
"=",
"this",
".",
"get",
"(",
"'user_prefixes'",
")",
";",
"if",
"(",
"typeof",
"modes",
"[",
"0",
"]",
"!==",
"'undefined'",
")",
"{",
"prefix",
"=",
"_",
".",
"detect",
"(",
"user_prefixes",
",",
"function",
"(",
"prefix",
")",
"{",
"return",
"prefix",
".",
"mode",
"===",
"modes",
"[",
"0",
"]",
";",
"}",
")",
";",
"prefix",
"=",
"(",
"prefix",
")",
"?",
"prefix",
".",
"symbol",
":",
"''",
";",
"}",
"return",
"prefix",
";",
"}"
] | Figure out a valid prefix given modes.
If a user is an op but also has voice, the prefix
should be the op as it is more important. | [
"Figure",
"out",
"a",
"valid",
"prefix",
"given",
"modes",
".",
"If",
"a",
"user",
"is",
"an",
"op",
"but",
"also",
"has",
"voice",
"the",
"prefix",
"should",
"be",
"the",
"op",
"as",
"it",
"is",
"more",
"important",
"."
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/models/member.js#L94-L107 | |
22,240 | prawnsalad/KiwiIRC | client/src/models/member.js | function (nick) {
var tmp = nick, i, j, k, nick_char;
var user_prefixes = this.get('user_prefixes');
i = 0;
nick_character_loop:
for (j = 0; j < nick.length; j++) {
nick_char = nick.charAt(j);
for (k = 0; k < user_prefixes.length; k++) {
if (nick_char === user_prefixes[k].symbol) {
i++;
continue nick_character_loop;
}
}
break;
}
return tmp.substr(i);
} | javascript | function (nick) {
var tmp = nick, i, j, k, nick_char;
var user_prefixes = this.get('user_prefixes');
i = 0;
nick_character_loop:
for (j = 0; j < nick.length; j++) {
nick_char = nick.charAt(j);
for (k = 0; k < user_prefixes.length; k++) {
if (nick_char === user_prefixes[k].symbol) {
i++;
continue nick_character_loop;
}
}
break;
}
return tmp.substr(i);
} | [
"function",
"(",
"nick",
")",
"{",
"var",
"tmp",
"=",
"nick",
",",
"i",
",",
"j",
",",
"k",
",",
"nick_char",
";",
"var",
"user_prefixes",
"=",
"this",
".",
"get",
"(",
"'user_prefixes'",
")",
";",
"i",
"=",
"0",
";",
"nick_character_loop",
":",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"nick",
".",
"length",
";",
"j",
"++",
")",
"{",
"nick_char",
"=",
"nick",
".",
"charAt",
"(",
"j",
")",
";",
"for",
"(",
"k",
"=",
"0",
";",
"k",
"<",
"user_prefixes",
".",
"length",
";",
"k",
"++",
")",
"{",
"if",
"(",
"nick_char",
"===",
"user_prefixes",
"[",
"k",
"]",
".",
"symbol",
")",
"{",
"i",
"++",
";",
"continue",
"nick_character_loop",
";",
"}",
"}",
"break",
";",
"}",
"return",
"tmp",
".",
"substr",
"(",
"i",
")",
";",
"}"
] | Remove any recognised prefix from a nick | [
"Remove",
"any",
"recognised",
"prefix",
"from",
"a",
"nick"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/models/member.js#L113-L134 | |
22,241 | prawnsalad/KiwiIRC | client/src/models/member.js | function () {
var user_prefixes = this.get('user_prefixes'),
modes = this.get('modes'),
o, max_mode;
if (modes.length > 0) {
o = _.indexOf(user_prefixes, _.find(user_prefixes, function (prefix) {
return prefix.mode === 'o';
}));
max_mode = _.indexOf(user_prefixes, _.find(user_prefixes, function (prefix) {
return prefix.mode === modes[0];
}));
if ((max_mode === -1) || (max_mode > o)) {
this.set({"is_op": false}, {silent: true});
} else {
this.set({"is_op": true}, {silent: true});
}
} else {
this.set({"is_op": false}, {silent: true});
}
} | javascript | function () {
var user_prefixes = this.get('user_prefixes'),
modes = this.get('modes'),
o, max_mode;
if (modes.length > 0) {
o = _.indexOf(user_prefixes, _.find(user_prefixes, function (prefix) {
return prefix.mode === 'o';
}));
max_mode = _.indexOf(user_prefixes, _.find(user_prefixes, function (prefix) {
return prefix.mode === modes[0];
}));
if ((max_mode === -1) || (max_mode > o)) {
this.set({"is_op": false}, {silent: true});
} else {
this.set({"is_op": true}, {silent: true});
}
} else {
this.set({"is_op": false}, {silent: true});
}
} | [
"function",
"(",
")",
"{",
"var",
"user_prefixes",
"=",
"this",
".",
"get",
"(",
"'user_prefixes'",
")",
",",
"modes",
"=",
"this",
".",
"get",
"(",
"'modes'",
")",
",",
"o",
",",
"max_mode",
";",
"if",
"(",
"modes",
".",
"length",
">",
"0",
")",
"{",
"o",
"=",
"_",
".",
"indexOf",
"(",
"user_prefixes",
",",
"_",
".",
"find",
"(",
"user_prefixes",
",",
"function",
"(",
"prefix",
")",
"{",
"return",
"prefix",
".",
"mode",
"===",
"'o'",
";",
"}",
")",
")",
";",
"max_mode",
"=",
"_",
".",
"indexOf",
"(",
"user_prefixes",
",",
"_",
".",
"find",
"(",
"user_prefixes",
",",
"function",
"(",
"prefix",
")",
"{",
"return",
"prefix",
".",
"mode",
"===",
"modes",
"[",
"0",
"]",
";",
"}",
")",
")",
";",
"if",
"(",
"(",
"max_mode",
"===",
"-",
"1",
")",
"||",
"(",
"max_mode",
">",
"o",
")",
")",
"{",
"this",
".",
"set",
"(",
"{",
"\"is_op\"",
":",
"false",
"}",
",",
"{",
"silent",
":",
"true",
"}",
")",
";",
"}",
"else",
"{",
"this",
".",
"set",
"(",
"{",
"\"is_op\"",
":",
"true",
"}",
",",
"{",
"silent",
":",
"true",
"}",
")",
";",
"}",
"}",
"else",
"{",
"this",
".",
"set",
"(",
"{",
"\"is_op\"",
":",
"false",
"}",
",",
"{",
"silent",
":",
"true",
"}",
")",
";",
"}",
"}"
] | With the modes set on the user, make note if we have some sort of op status | [
"With",
"the",
"modes",
"set",
"on",
"the",
"user",
"make",
"note",
"if",
"we",
"have",
"some",
"sort",
"of",
"op",
"status"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/models/member.js#L167-L190 | |
22,242 | prawnsalad/KiwiIRC | server/weblistener.js | initialiseSocket | function initialiseSocket(socket, callback) {
var request = socket.request,
address = request.meta.remote_address,
revdns;
// Key/val data stored to the socket to be read later on
// May also be synced to a redis DB to lookup clients
socket.meta = socket.request.meta;
// If a forwarded-for header is found, switch the source address
if (request.headers[global.config.http_proxy_ip_header || 'x-forwarded-for']) {
// Check we're connecting from a whitelisted proxy
if (!global.config.http_proxies || !rangeCheck(address, global.config.http_proxies)) {
winston.info('Unlisted proxy: %s', address);
callback(null, false);
return;
}
// We're sent from a whitelisted proxy, replace the hosts
address = request.headers[global.config.http_proxy_ip_header || 'x-forwarded-for'];
// Multiple reverse proxies will have a comma delimited list of IPs. We only need the first
address = address.split(',')[0].trim();
// Some reverse proxies (IIS) may include the port, so lets remove that (if ipv4)
if (address.indexOf('.') > -1) {
address = (address || '').split(':')[0];
}
}
socket.meta.real_address = address;
// If enabled, don't go over the connection limit
if (global.config.max_client_conns && global.config.max_client_conns > 0) {
if (global.clients.numOnAddress(address) + 1 > global.config.max_client_conns) {
return callback(null, false);
}
}
try {
dns.reverse(address, function (err, domains) {
if (!err && domains.length > 0) {
revdns = _.first(domains);
}
if (!revdns) {
// No reverse DNS found, use the IP
socket.meta.revdns = address;
callback(null, true);
} else {
// Make sure the reverse DNS matches the A record to use the hostname..
dns.lookup(revdns, function (err, ip_address, family) {
if (!err && ip_address == address) {
// A record matches PTR, perfectly valid hostname
socket.meta.revdns = revdns;
} else {
// A record does not match the PTR, invalid hostname
socket.meta.revdns = address;
}
// We have all the info we need, proceed with the connection
callback(null, true);
});
}
});
} catch (err) {
socket.meta.revdns = address;
callback(null, true);
}
} | javascript | function initialiseSocket(socket, callback) {
var request = socket.request,
address = request.meta.remote_address,
revdns;
// Key/val data stored to the socket to be read later on
// May also be synced to a redis DB to lookup clients
socket.meta = socket.request.meta;
// If a forwarded-for header is found, switch the source address
if (request.headers[global.config.http_proxy_ip_header || 'x-forwarded-for']) {
// Check we're connecting from a whitelisted proxy
if (!global.config.http_proxies || !rangeCheck(address, global.config.http_proxies)) {
winston.info('Unlisted proxy: %s', address);
callback(null, false);
return;
}
// We're sent from a whitelisted proxy, replace the hosts
address = request.headers[global.config.http_proxy_ip_header || 'x-forwarded-for'];
// Multiple reverse proxies will have a comma delimited list of IPs. We only need the first
address = address.split(',')[0].trim();
// Some reverse proxies (IIS) may include the port, so lets remove that (if ipv4)
if (address.indexOf('.') > -1) {
address = (address || '').split(':')[0];
}
}
socket.meta.real_address = address;
// If enabled, don't go over the connection limit
if (global.config.max_client_conns && global.config.max_client_conns > 0) {
if (global.clients.numOnAddress(address) + 1 > global.config.max_client_conns) {
return callback(null, false);
}
}
try {
dns.reverse(address, function (err, domains) {
if (!err && domains.length > 0) {
revdns = _.first(domains);
}
if (!revdns) {
// No reverse DNS found, use the IP
socket.meta.revdns = address;
callback(null, true);
} else {
// Make sure the reverse DNS matches the A record to use the hostname..
dns.lookup(revdns, function (err, ip_address, family) {
if (!err && ip_address == address) {
// A record matches PTR, perfectly valid hostname
socket.meta.revdns = revdns;
} else {
// A record does not match the PTR, invalid hostname
socket.meta.revdns = address;
}
// We have all the info we need, proceed with the connection
callback(null, true);
});
}
});
} catch (err) {
socket.meta.revdns = address;
callback(null, true);
}
} | [
"function",
"initialiseSocket",
"(",
"socket",
",",
"callback",
")",
"{",
"var",
"request",
"=",
"socket",
".",
"request",
",",
"address",
"=",
"request",
".",
"meta",
".",
"remote_address",
",",
"revdns",
";",
"// Key/val data stored to the socket to be read later on",
"// May also be synced to a redis DB to lookup clients",
"socket",
".",
"meta",
"=",
"socket",
".",
"request",
".",
"meta",
";",
"// If a forwarded-for header is found, switch the source address",
"if",
"(",
"request",
".",
"headers",
"[",
"global",
".",
"config",
".",
"http_proxy_ip_header",
"||",
"'x-forwarded-for'",
"]",
")",
"{",
"// Check we're connecting from a whitelisted proxy",
"if",
"(",
"!",
"global",
".",
"config",
".",
"http_proxies",
"||",
"!",
"rangeCheck",
"(",
"address",
",",
"global",
".",
"config",
".",
"http_proxies",
")",
")",
"{",
"winston",
".",
"info",
"(",
"'Unlisted proxy: %s'",
",",
"address",
")",
";",
"callback",
"(",
"null",
",",
"false",
")",
";",
"return",
";",
"}",
"// We're sent from a whitelisted proxy, replace the hosts",
"address",
"=",
"request",
".",
"headers",
"[",
"global",
".",
"config",
".",
"http_proxy_ip_header",
"||",
"'x-forwarded-for'",
"]",
";",
"// Multiple reverse proxies will have a comma delimited list of IPs. We only need the first",
"address",
"=",
"address",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
".",
"trim",
"(",
")",
";",
"// Some reverse proxies (IIS) may include the port, so lets remove that (if ipv4)",
"if",
"(",
"address",
".",
"indexOf",
"(",
"'.'",
")",
">",
"-",
"1",
")",
"{",
"address",
"=",
"(",
"address",
"||",
"''",
")",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
";",
"}",
"}",
"socket",
".",
"meta",
".",
"real_address",
"=",
"address",
";",
"// If enabled, don't go over the connection limit",
"if",
"(",
"global",
".",
"config",
".",
"max_client_conns",
"&&",
"global",
".",
"config",
".",
"max_client_conns",
">",
"0",
")",
"{",
"if",
"(",
"global",
".",
"clients",
".",
"numOnAddress",
"(",
"address",
")",
"+",
"1",
">",
"global",
".",
"config",
".",
"max_client_conns",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"false",
")",
";",
"}",
"}",
"try",
"{",
"dns",
".",
"reverse",
"(",
"address",
",",
"function",
"(",
"err",
",",
"domains",
")",
"{",
"if",
"(",
"!",
"err",
"&&",
"domains",
".",
"length",
">",
"0",
")",
"{",
"revdns",
"=",
"_",
".",
"first",
"(",
"domains",
")",
";",
"}",
"if",
"(",
"!",
"revdns",
")",
"{",
"// No reverse DNS found, use the IP",
"socket",
".",
"meta",
".",
"revdns",
"=",
"address",
";",
"callback",
"(",
"null",
",",
"true",
")",
";",
"}",
"else",
"{",
"// Make sure the reverse DNS matches the A record to use the hostname..",
"dns",
".",
"lookup",
"(",
"revdns",
",",
"function",
"(",
"err",
",",
"ip_address",
",",
"family",
")",
"{",
"if",
"(",
"!",
"err",
"&&",
"ip_address",
"==",
"address",
")",
"{",
"// A record matches PTR, perfectly valid hostname",
"socket",
".",
"meta",
".",
"revdns",
"=",
"revdns",
";",
"}",
"else",
"{",
"// A record does not match the PTR, invalid hostname",
"socket",
".",
"meta",
".",
"revdns",
"=",
"address",
";",
"}",
"// We have all the info we need, proceed with the connection",
"callback",
"(",
"null",
",",
"true",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"socket",
".",
"meta",
".",
"revdns",
"=",
"address",
";",
"callback",
"(",
"null",
",",
"true",
")",
";",
"}",
"}"
] | Get the reverse DNS entry for this connection.
Used later on for webirc, etc functionality | [
"Get",
"the",
"reverse",
"DNS",
"entry",
"for",
"this",
"connection",
".",
"Used",
"later",
"on",
"for",
"webirc",
"etc",
"functionality"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/weblistener.js#L163-L235 |
22,243 | prawnsalad/KiwiIRC | client/src/views/application.js | function (ev) {
// If we're copying text, don't shift focus
if (ev.ctrlKey || ev.altKey || ev.metaKey) {
return;
}
// If we're typing into an input box somewhere, ignore
var elements = ['input', 'select', 'textarea', 'button', 'datalist', 'keygen'];
var do_not_refocus =
elements.indexOf(ev.target.tagName.toLowerCase()) > -1 ||
$(ev.target).attr('contenteditable');
if (do_not_refocus) {
return;
}
$('#kiwi .controlbox .inp').focus();
} | javascript | function (ev) {
// If we're copying text, don't shift focus
if (ev.ctrlKey || ev.altKey || ev.metaKey) {
return;
}
// If we're typing into an input box somewhere, ignore
var elements = ['input', 'select', 'textarea', 'button', 'datalist', 'keygen'];
var do_not_refocus =
elements.indexOf(ev.target.tagName.toLowerCase()) > -1 ||
$(ev.target).attr('contenteditable');
if (do_not_refocus) {
return;
}
$('#kiwi .controlbox .inp').focus();
} | [
"function",
"(",
"ev",
")",
"{",
"// If we're copying text, don't shift focus",
"if",
"(",
"ev",
".",
"ctrlKey",
"||",
"ev",
".",
"altKey",
"||",
"ev",
".",
"metaKey",
")",
"{",
"return",
";",
"}",
"// If we're typing into an input box somewhere, ignore",
"var",
"elements",
"=",
"[",
"'input'",
",",
"'select'",
",",
"'textarea'",
",",
"'button'",
",",
"'datalist'",
",",
"'keygen'",
"]",
";",
"var",
"do_not_refocus",
"=",
"elements",
".",
"indexOf",
"(",
"ev",
".",
"target",
".",
"tagName",
".",
"toLowerCase",
"(",
")",
")",
">",
"-",
"1",
"||",
"$",
"(",
"ev",
".",
"target",
")",
".",
"attr",
"(",
"'contenteditable'",
")",
";",
"if",
"(",
"do_not_refocus",
")",
"{",
"return",
";",
"}",
"$",
"(",
"'#kiwi .controlbox .inp'",
")",
".",
"focus",
"(",
")",
";",
"}"
] | Globally shift focus to the command input box on a keypress | [
"Globally",
"shift",
"focus",
"to",
"the",
"command",
"input",
"box",
"on",
"a",
"keypress"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/views/application.js#L140-L157 | |
22,244 | prawnsalad/KiwiIRC | client/assets/libs/jed.js | function ( options ) {
// Some minimal defaults
this.defaults = {
"locale_data" : {
"messages" : {
"" : {
"domain" : "messages",
"lang" : "en",
"plural_forms" : "nplurals=2; plural=(n != 1);"
}
// There are no default keys, though
}
},
// The default domain if one is missing
"domain" : "messages",
// enable debug mode to log untranslated strings to the console
"debug" : false
};
// Mix in the sent options with the default options
this.options = _.extend( {}, this.defaults, options );
this.textdomain( this.options.domain );
if ( options.domain && ! this.options.locale_data[ this.options.domain ] ) {
throw new Error('Text domain set to non-existent domain: `' + options.domain + '`');
}
} | javascript | function ( options ) {
// Some minimal defaults
this.defaults = {
"locale_data" : {
"messages" : {
"" : {
"domain" : "messages",
"lang" : "en",
"plural_forms" : "nplurals=2; plural=(n != 1);"
}
// There are no default keys, though
}
},
// The default domain if one is missing
"domain" : "messages",
// enable debug mode to log untranslated strings to the console
"debug" : false
};
// Mix in the sent options with the default options
this.options = _.extend( {}, this.defaults, options );
this.textdomain( this.options.domain );
if ( options.domain && ! this.options.locale_data[ this.options.domain ] ) {
throw new Error('Text domain set to non-existent domain: `' + options.domain + '`');
}
} | [
"function",
"(",
"options",
")",
"{",
"// Some minimal defaults\r",
"this",
".",
"defaults",
"=",
"{",
"\"locale_data\"",
":",
"{",
"\"messages\"",
":",
"{",
"\"\"",
":",
"{",
"\"domain\"",
":",
"\"messages\"",
",",
"\"lang\"",
":",
"\"en\"",
",",
"\"plural_forms\"",
":",
"\"nplurals=2; plural=(n != 1);\"",
"}",
"// There are no default keys, though\r",
"}",
"}",
",",
"// The default domain if one is missing\r",
"\"domain\"",
":",
"\"messages\"",
",",
"// enable debug mode to log untranslated strings to the console\r",
"\"debug\"",
":",
"false",
"}",
";",
"// Mix in the sent options with the default options\r",
"this",
".",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"this",
".",
"defaults",
",",
"options",
")",
";",
"this",
".",
"textdomain",
"(",
"this",
".",
"options",
".",
"domain",
")",
";",
"if",
"(",
"options",
".",
"domain",
"&&",
"!",
"this",
".",
"options",
".",
"locale_data",
"[",
"this",
".",
"options",
".",
"domain",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Text domain set to non-existent domain: `'",
"+",
"options",
".",
"domain",
"+",
"'`'",
")",
";",
"}",
"}"
] | END Miniature underscore impl Jed is a constructor function | [
"END",
"Miniature",
"underscore",
"impl",
"Jed",
"is",
"a",
"constructor",
"function"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/assets/libs/jed.js#L79-L105 | |
22,245 | prawnsalad/KiwiIRC | client/assets/libs/jed.js | function ( domain, context, singular_key, plural_key, val ) {
// Set some defaults
plural_key = plural_key || singular_key;
// Use the global domain default if one
// isn't explicitly passed in
domain = domain || this._textdomain;
var fallback;
// Handle special cases
// No options found
if ( ! this.options ) {
// There's likely something wrong, but we'll return the correct key for english
// We do this by instantiating a brand new Jed instance with the default set
// for everything that could be broken.
fallback = new Jed();
return fallback.dcnpgettext.call( fallback, undefined, undefined, singular_key, plural_key, val );
}
// No translation data provided
if ( ! this.options.locale_data ) {
throw new Error('No locale data provided.');
}
if ( ! this.options.locale_data[ domain ] ) {
throw new Error('Domain `' + domain + '` was not found.');
}
if ( ! this.options.locale_data[ domain ][ "" ] ) {
throw new Error('No locale meta information provided.');
}
// Make sure we have a truthy key. Otherwise we might start looking
// into the empty string key, which is the options for the locale
// data.
if ( ! singular_key ) {
throw new Error('No translation key found.');
}
var key = context ? context + Jed.context_delimiter + singular_key : singular_key,
locale_data = this.options.locale_data,
dict = locale_data[ domain ],
defaultConf = (locale_data.messages || this.defaults.locale_data.messages)[""],
pluralForms = dict[""].plural_forms || dict[""]["Plural-Forms"] || dict[""]["plural-forms"] || defaultConf.plural_forms || defaultConf["Plural-Forms"] || defaultConf["plural-forms"],
val_list,
res;
var val_idx;
if (val === undefined) {
// No value passed in; assume singular key lookup.
val_idx = 1;
} else {
// Value has been passed in; use plural-forms calculations.
// Handle invalid numbers, but try casting strings for good measure
if ( typeof val != 'number' ) {
val = parseInt( val, 10 );
if ( isNaN( val ) ) {
throw new Error('The number that was passed in is not a number.');
}
}
val_idx = getPluralFormFunc(pluralForms)(val) + 1;
}
// Throw an error if a domain isn't found
if ( ! dict ) {
throw new Error('No domain named `' + domain + '` could be found.');
}
val_list = dict[ key ];
// If there is no match, then revert back to
// english style singular/plural with the keys passed in.
if ( ! val_list || val_idx >= val_list.length ) {
if (this.options.missing_key_callback) {
this.options.missing_key_callback(key, domain);
}
res = [ null, singular_key, plural_key ];
// collect untranslated strings
if (this.options.debug===true) {
console.log(res[ getPluralFormFunc(pluralForms)( val ) + 1 ]);
}
return res[ getPluralFormFunc()( val ) + 1 ];
}
res = val_list[ val_idx ];
// This includes empty strings on purpose
if ( ! res ) {
res = [ null, singular_key, plural_key ];
return res[ getPluralFormFunc()( val ) + 1 ];
}
return res;
} | javascript | function ( domain, context, singular_key, plural_key, val ) {
// Set some defaults
plural_key = plural_key || singular_key;
// Use the global domain default if one
// isn't explicitly passed in
domain = domain || this._textdomain;
var fallback;
// Handle special cases
// No options found
if ( ! this.options ) {
// There's likely something wrong, but we'll return the correct key for english
// We do this by instantiating a brand new Jed instance with the default set
// for everything that could be broken.
fallback = new Jed();
return fallback.dcnpgettext.call( fallback, undefined, undefined, singular_key, plural_key, val );
}
// No translation data provided
if ( ! this.options.locale_data ) {
throw new Error('No locale data provided.');
}
if ( ! this.options.locale_data[ domain ] ) {
throw new Error('Domain `' + domain + '` was not found.');
}
if ( ! this.options.locale_data[ domain ][ "" ] ) {
throw new Error('No locale meta information provided.');
}
// Make sure we have a truthy key. Otherwise we might start looking
// into the empty string key, which is the options for the locale
// data.
if ( ! singular_key ) {
throw new Error('No translation key found.');
}
var key = context ? context + Jed.context_delimiter + singular_key : singular_key,
locale_data = this.options.locale_data,
dict = locale_data[ domain ],
defaultConf = (locale_data.messages || this.defaults.locale_data.messages)[""],
pluralForms = dict[""].plural_forms || dict[""]["Plural-Forms"] || dict[""]["plural-forms"] || defaultConf.plural_forms || defaultConf["Plural-Forms"] || defaultConf["plural-forms"],
val_list,
res;
var val_idx;
if (val === undefined) {
// No value passed in; assume singular key lookup.
val_idx = 1;
} else {
// Value has been passed in; use plural-forms calculations.
// Handle invalid numbers, but try casting strings for good measure
if ( typeof val != 'number' ) {
val = parseInt( val, 10 );
if ( isNaN( val ) ) {
throw new Error('The number that was passed in is not a number.');
}
}
val_idx = getPluralFormFunc(pluralForms)(val) + 1;
}
// Throw an error if a domain isn't found
if ( ! dict ) {
throw new Error('No domain named `' + domain + '` could be found.');
}
val_list = dict[ key ];
// If there is no match, then revert back to
// english style singular/plural with the keys passed in.
if ( ! val_list || val_idx >= val_list.length ) {
if (this.options.missing_key_callback) {
this.options.missing_key_callback(key, domain);
}
res = [ null, singular_key, plural_key ];
// collect untranslated strings
if (this.options.debug===true) {
console.log(res[ getPluralFormFunc(pluralForms)( val ) + 1 ]);
}
return res[ getPluralFormFunc()( val ) + 1 ];
}
res = val_list[ val_idx ];
// This includes empty strings on purpose
if ( ! res ) {
res = [ null, singular_key, plural_key ];
return res[ getPluralFormFunc()( val ) + 1 ];
}
return res;
} | [
"function",
"(",
"domain",
",",
"context",
",",
"singular_key",
",",
"plural_key",
",",
"val",
")",
"{",
"// Set some defaults\r",
"plural_key",
"=",
"plural_key",
"||",
"singular_key",
";",
"// Use the global domain default if one\r",
"// isn't explicitly passed in\r",
"domain",
"=",
"domain",
"||",
"this",
".",
"_textdomain",
";",
"var",
"fallback",
";",
"// Handle special cases\r",
"// No options found\r",
"if",
"(",
"!",
"this",
".",
"options",
")",
"{",
"// There's likely something wrong, but we'll return the correct key for english\r",
"// We do this by instantiating a brand new Jed instance with the default set\r",
"// for everything that could be broken.\r",
"fallback",
"=",
"new",
"Jed",
"(",
")",
";",
"return",
"fallback",
".",
"dcnpgettext",
".",
"call",
"(",
"fallback",
",",
"undefined",
",",
"undefined",
",",
"singular_key",
",",
"plural_key",
",",
"val",
")",
";",
"}",
"// No translation data provided\r",
"if",
"(",
"!",
"this",
".",
"options",
".",
"locale_data",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No locale data provided.'",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"options",
".",
"locale_data",
"[",
"domain",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Domain `'",
"+",
"domain",
"+",
"'` was not found.'",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"options",
".",
"locale_data",
"[",
"domain",
"]",
"[",
"\"\"",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No locale meta information provided.'",
")",
";",
"}",
"// Make sure we have a truthy key. Otherwise we might start looking\r",
"// into the empty string key, which is the options for the locale\r",
"// data.\r",
"if",
"(",
"!",
"singular_key",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No translation key found.'",
")",
";",
"}",
"var",
"key",
"=",
"context",
"?",
"context",
"+",
"Jed",
".",
"context_delimiter",
"+",
"singular_key",
":",
"singular_key",
",",
"locale_data",
"=",
"this",
".",
"options",
".",
"locale_data",
",",
"dict",
"=",
"locale_data",
"[",
"domain",
"]",
",",
"defaultConf",
"=",
"(",
"locale_data",
".",
"messages",
"||",
"this",
".",
"defaults",
".",
"locale_data",
".",
"messages",
")",
"[",
"\"\"",
"]",
",",
"pluralForms",
"=",
"dict",
"[",
"\"\"",
"]",
".",
"plural_forms",
"||",
"dict",
"[",
"\"\"",
"]",
"[",
"\"Plural-Forms\"",
"]",
"||",
"dict",
"[",
"\"\"",
"]",
"[",
"\"plural-forms\"",
"]",
"||",
"defaultConf",
".",
"plural_forms",
"||",
"defaultConf",
"[",
"\"Plural-Forms\"",
"]",
"||",
"defaultConf",
"[",
"\"plural-forms\"",
"]",
",",
"val_list",
",",
"res",
";",
"var",
"val_idx",
";",
"if",
"(",
"val",
"===",
"undefined",
")",
"{",
"// No value passed in; assume singular key lookup.\r",
"val_idx",
"=",
"1",
";",
"}",
"else",
"{",
"// Value has been passed in; use plural-forms calculations.\r",
"// Handle invalid numbers, but try casting strings for good measure\r",
"if",
"(",
"typeof",
"val",
"!=",
"'number'",
")",
"{",
"val",
"=",
"parseInt",
"(",
"val",
",",
"10",
")",
";",
"if",
"(",
"isNaN",
"(",
"val",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The number that was passed in is not a number.'",
")",
";",
"}",
"}",
"val_idx",
"=",
"getPluralFormFunc",
"(",
"pluralForms",
")",
"(",
"val",
")",
"+",
"1",
";",
"}",
"// Throw an error if a domain isn't found\r",
"if",
"(",
"!",
"dict",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No domain named `'",
"+",
"domain",
"+",
"'` could be found.'",
")",
";",
"}",
"val_list",
"=",
"dict",
"[",
"key",
"]",
";",
"// If there is no match, then revert back to\r",
"// english style singular/plural with the keys passed in.\r",
"if",
"(",
"!",
"val_list",
"||",
"val_idx",
">=",
"val_list",
".",
"length",
")",
"{",
"if",
"(",
"this",
".",
"options",
".",
"missing_key_callback",
")",
"{",
"this",
".",
"options",
".",
"missing_key_callback",
"(",
"key",
",",
"domain",
")",
";",
"}",
"res",
"=",
"[",
"null",
",",
"singular_key",
",",
"plural_key",
"]",
";",
"// collect untranslated strings\r",
"if",
"(",
"this",
".",
"options",
".",
"debug",
"===",
"true",
")",
"{",
"console",
".",
"log",
"(",
"res",
"[",
"getPluralFormFunc",
"(",
"pluralForms",
")",
"(",
"val",
")",
"+",
"1",
"]",
")",
";",
"}",
"return",
"res",
"[",
"getPluralFormFunc",
"(",
")",
"(",
"val",
")",
"+",
"1",
"]",
";",
"}",
"res",
"=",
"val_list",
"[",
"val_idx",
"]",
";",
"// This includes empty strings on purpose\r",
"if",
"(",
"!",
"res",
")",
"{",
"res",
"=",
"[",
"null",
",",
"singular_key",
",",
"plural_key",
"]",
";",
"return",
"res",
"[",
"getPluralFormFunc",
"(",
")",
"(",
"val",
")",
"+",
"1",
"]",
";",
"}",
"return",
"res",
";",
"}"
] | The most fully qualified gettext function. It has every option. Since it has every option, we can use it from every other method. This is the bread and butter. Technically there should be one more argument in this function for 'Category', but since we never use it, we might as well not waste the bytes to define it. | [
"The",
"most",
"fully",
"qualified",
"gettext",
"function",
".",
"It",
"has",
"every",
"option",
".",
"Since",
"it",
"has",
"every",
"option",
"we",
"can",
"use",
"it",
"from",
"every",
"other",
"method",
".",
"This",
"is",
"the",
"bread",
"and",
"butter",
".",
"Technically",
"there",
"should",
"be",
"one",
"more",
"argument",
"in",
"this",
"function",
"for",
"Category",
"but",
"since",
"we",
"never",
"use",
"it",
"we",
"might",
"as",
"well",
"not",
"waste",
"the",
"bytes",
"to",
"define",
"it",
"."
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/assets/libs/jed.js#L216-L316 | |
22,246 | prawnsalad/KiwiIRC | server/kiwi.js | function (list) {
var batch_size = 100,
cutoff;
if (list.length >= batch_size) {
// If we have more clients than our batch size, call ourself with the next batch
setTimeout(function () {
sendCommandBatch(list.slice(batch_size));
}, 200);
cutoff = batch_size;
} else {
cutoff = list.length;
}
list.slice(0, cutoff).forEach(function (client) {
if (!client.disposed) {
client.sendKiwiCommand(command, data);
}
});
if (cutoff === list.length && typeof callback === 'function') {
callback();
}
} | javascript | function (list) {
var batch_size = 100,
cutoff;
if (list.length >= batch_size) {
// If we have more clients than our batch size, call ourself with the next batch
setTimeout(function () {
sendCommandBatch(list.slice(batch_size));
}, 200);
cutoff = batch_size;
} else {
cutoff = list.length;
}
list.slice(0, cutoff).forEach(function (client) {
if (!client.disposed) {
client.sendKiwiCommand(command, data);
}
});
if (cutoff === list.length && typeof callback === 'function') {
callback();
}
} | [
"function",
"(",
"list",
")",
"{",
"var",
"batch_size",
"=",
"100",
",",
"cutoff",
";",
"if",
"(",
"list",
".",
"length",
">=",
"batch_size",
")",
"{",
"// If we have more clients than our batch size, call ourself with the next batch",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"sendCommandBatch",
"(",
"list",
".",
"slice",
"(",
"batch_size",
")",
")",
";",
"}",
",",
"200",
")",
";",
"cutoff",
"=",
"batch_size",
";",
"}",
"else",
"{",
"cutoff",
"=",
"list",
".",
"length",
";",
"}",
"list",
".",
"slice",
"(",
"0",
",",
"cutoff",
")",
".",
"forEach",
"(",
"function",
"(",
"client",
")",
"{",
"if",
"(",
"!",
"client",
".",
"disposed",
")",
"{",
"client",
".",
"sendKiwiCommand",
"(",
"command",
",",
"data",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"cutoff",
"===",
"list",
".",
"length",
"&&",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"callback",
"(",
")",
";",
"}",
"}"
] | Sending of the command in batches | [
"Sending",
"of",
"the",
"command",
"in",
"batches"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/kiwi.js#L146-L171 | |
22,247 | prawnsalad/KiwiIRC | server/httphandler.js | updateLocalesCache | function updateLocalesCache() {
cached_available_locales = [];
fs.readdir(global.config.public_http + '/assets/locales', function (err, files) {
if (err) {
if (err.code === 'ENOENT') {
winston.error('No locale files could be found at ' + err.path);
} else {
winston.error('Error reading locales.', err);
}
}
(files || []).forEach(function (file) {
if (file.substr(-5) === '.json') {
cached_available_locales.push(file.slice(0, -5));
}
});
});
} | javascript | function updateLocalesCache() {
cached_available_locales = [];
fs.readdir(global.config.public_http + '/assets/locales', function (err, files) {
if (err) {
if (err.code === 'ENOENT') {
winston.error('No locale files could be found at ' + err.path);
} else {
winston.error('Error reading locales.', err);
}
}
(files || []).forEach(function (file) {
if (file.substr(-5) === '.json') {
cached_available_locales.push(file.slice(0, -5));
}
});
});
} | [
"function",
"updateLocalesCache",
"(",
")",
"{",
"cached_available_locales",
"=",
"[",
"]",
";",
"fs",
".",
"readdir",
"(",
"global",
".",
"config",
".",
"public_http",
"+",
"'/assets/locales'",
",",
"function",
"(",
"err",
",",
"files",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"winston",
".",
"error",
"(",
"'No locale files could be found at '",
"+",
"err",
".",
"path",
")",
";",
"}",
"else",
"{",
"winston",
".",
"error",
"(",
"'Error reading locales.'",
",",
"err",
")",
";",
"}",
"}",
"(",
"files",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"if",
"(",
"file",
".",
"substr",
"(",
"-",
"5",
")",
"===",
"'.json'",
")",
"{",
"cached_available_locales",
".",
"push",
"(",
"file",
".",
"slice",
"(",
"0",
",",
"-",
"5",
")",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | Cache the available locales we have so we don't read the same directory for each request | [
"Cache",
"the",
"available",
"locales",
"we",
"have",
"so",
"we",
"don",
"t",
"read",
"the",
"same",
"directory",
"for",
"each",
"request"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/httphandler.js#L102-L120 |
22,248 | prawnsalad/KiwiIRC | server/httphandler.js | serveSettings | function serveSettings(request, response) {
var referrer_url,
debug = false;
// Check the referrer for a debug option
if (request.headers.referer) {
referrer_url = url.parse(request.headers.referer, true);
if (referrer_url.query && referrer_url.query.debug) {
debug = true;
}
}
SettingsGenerator.get(debug, function(err, settings) {
if (err) {
winston.error('Error generating settings', err);
response.writeHead(500, 'Internal Server Error');
return response.end();
}
if (request.headers['if-none-match'] && request.headers['if-none-match'] === settings.hash) {
response.writeHead(304, 'Not Modified');
return response.end();
}
response.writeHead(200, {
'ETag': settings.hash,
'Content-Type': 'application/json'
});
response.end(settings.settings);
});
} | javascript | function serveSettings(request, response) {
var referrer_url,
debug = false;
// Check the referrer for a debug option
if (request.headers.referer) {
referrer_url = url.parse(request.headers.referer, true);
if (referrer_url.query && referrer_url.query.debug) {
debug = true;
}
}
SettingsGenerator.get(debug, function(err, settings) {
if (err) {
winston.error('Error generating settings', err);
response.writeHead(500, 'Internal Server Error');
return response.end();
}
if (request.headers['if-none-match'] && request.headers['if-none-match'] === settings.hash) {
response.writeHead(304, 'Not Modified');
return response.end();
}
response.writeHead(200, {
'ETag': settings.hash,
'Content-Type': 'application/json'
});
response.end(settings.settings);
});
} | [
"function",
"serveSettings",
"(",
"request",
",",
"response",
")",
"{",
"var",
"referrer_url",
",",
"debug",
"=",
"false",
";",
"// Check the referrer for a debug option",
"if",
"(",
"request",
".",
"headers",
".",
"referer",
")",
"{",
"referrer_url",
"=",
"url",
".",
"parse",
"(",
"request",
".",
"headers",
".",
"referer",
",",
"true",
")",
";",
"if",
"(",
"referrer_url",
".",
"query",
"&&",
"referrer_url",
".",
"query",
".",
"debug",
")",
"{",
"debug",
"=",
"true",
";",
"}",
"}",
"SettingsGenerator",
".",
"get",
"(",
"debug",
",",
"function",
"(",
"err",
",",
"settings",
")",
"{",
"if",
"(",
"err",
")",
"{",
"winston",
".",
"error",
"(",
"'Error generating settings'",
",",
"err",
")",
";",
"response",
".",
"writeHead",
"(",
"500",
",",
"'Internal Server Error'",
")",
";",
"return",
"response",
".",
"end",
"(",
")",
";",
"}",
"if",
"(",
"request",
".",
"headers",
"[",
"'if-none-match'",
"]",
"&&",
"request",
".",
"headers",
"[",
"'if-none-match'",
"]",
"===",
"settings",
".",
"hash",
")",
"{",
"response",
".",
"writeHead",
"(",
"304",
",",
"'Not Modified'",
")",
";",
"return",
"response",
".",
"end",
"(",
")",
";",
"}",
"response",
".",
"writeHead",
"(",
"200",
",",
"{",
"'ETag'",
":",
"settings",
".",
"hash",
",",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
";",
"response",
".",
"end",
"(",
"settings",
".",
"settings",
")",
";",
"}",
")",
";",
"}"
] | Handle the settings.json request | [
"Handle",
"the",
"settings",
".",
"json",
"request"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/httphandler.js#L157-L187 |
22,249 | prawnsalad/KiwiIRC | client/src/helpers/desktopnotifications.js | function (timeout) {
if (!this.closed) {
if (this.notification) {
this._closeTimeout = this._closeTimeout || setTimeout(_.bind(this.close, this), timeout);
} else {
this.once('show', _.bind(this.closeAfter, this, timeout));
}
}
return this;
} | javascript | function (timeout) {
if (!this.closed) {
if (this.notification) {
this._closeTimeout = this._closeTimeout || setTimeout(_.bind(this.close, this), timeout);
} else {
this.once('show', _.bind(this.closeAfter, this, timeout));
}
}
return this;
} | [
"function",
"(",
"timeout",
")",
"{",
"if",
"(",
"!",
"this",
".",
"closed",
")",
"{",
"if",
"(",
"this",
".",
"notification",
")",
"{",
"this",
".",
"_closeTimeout",
"=",
"this",
".",
"_closeTimeout",
"||",
"setTimeout",
"(",
"_",
".",
"bind",
"(",
"this",
".",
"close",
",",
"this",
")",
",",
"timeout",
")",
";",
"}",
"else",
"{",
"this",
".",
"once",
"(",
"'show'",
",",
"_",
".",
"bind",
"(",
"this",
".",
"closeAfter",
",",
"this",
",",
"timeout",
")",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] | Close the notification after a given number of milliseconds.
@param {Number} timeout
@returns {this} | [
"Close",
"the",
"notification",
"after",
"a",
"given",
"number",
"of",
"milliseconds",
"."
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/helpers/desktopnotifications.js#L87-L96 | |
22,250 | prawnsalad/KiwiIRC | client/src/misc/clientuicommands.js | unknownCommand | function unknownCommand (ev) {
var raw_cmd = ev.command + ' ' + ev.params.join(' ');
this.app.connections.active_connection.gateway.raw(raw_cmd);
} | javascript | function unknownCommand (ev) {
var raw_cmd = ev.command + ' ' + ev.params.join(' ');
this.app.connections.active_connection.gateway.raw(raw_cmd);
} | [
"function",
"unknownCommand",
"(",
"ev",
")",
"{",
"var",
"raw_cmd",
"=",
"ev",
".",
"command",
"+",
"' '",
"+",
"ev",
".",
"params",
".",
"join",
"(",
"' '",
")",
";",
"this",
".",
"app",
".",
"connections",
".",
"active_connection",
".",
"gateway",
".",
"raw",
"(",
"raw_cmd",
")",
";",
"}"
] | A fallback action. Send a raw command to the server | [
"A",
"fallback",
"action",
".",
"Send",
"a",
"raw",
"command",
"to",
"the",
"server"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/misc/clientuicommands.js#L272-L275 |
22,251 | prawnsalad/KiwiIRC | server/clientcommands.js | function(rpc_method, fn) {
rpc.on(rpc_method, _.partial(moduleEventWrap, rpc_method, fn));
} | javascript | function(rpc_method, fn) {
rpc.on(rpc_method, _.partial(moduleEventWrap, rpc_method, fn));
} | [
"function",
"(",
"rpc_method",
",",
"fn",
")",
"{",
"rpc",
".",
"on",
"(",
"rpc_method",
",",
"_",
".",
"partial",
"(",
"moduleEventWrap",
",",
"rpc_method",
",",
"fn",
")",
")",
";",
"}"
] | Quick + easier way to call the above function | [
"Quick",
"+",
"easier",
"way",
"to",
"call",
"the",
"above",
"function"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/clientcommands.js#L62-L64 | |
22,252 | prawnsalad/KiwiIRC | server/clientcommands.js | truncateString | function truncateString(str, block_size) {
block_size = block_size || 350;
var blocks = [],
current_pos;
for (current_pos = 0; current_pos < str.length; current_pos = current_pos + block_size) {
blocks.push(str.substr(current_pos, block_size));
}
return blocks;
} | javascript | function truncateString(str, block_size) {
block_size = block_size || 350;
var blocks = [],
current_pos;
for (current_pos = 0; current_pos < str.length; current_pos = current_pos + block_size) {
blocks.push(str.substr(current_pos, block_size));
}
return blocks;
} | [
"function",
"truncateString",
"(",
"str",
",",
"block_size",
")",
"{",
"block_size",
"=",
"block_size",
"||",
"350",
";",
"var",
"blocks",
"=",
"[",
"]",
",",
"current_pos",
";",
"for",
"(",
"current_pos",
"=",
"0",
";",
"current_pos",
"<",
"str",
".",
"length",
";",
"current_pos",
"=",
"current_pos",
"+",
"block_size",
")",
"{",
"blocks",
".",
"push",
"(",
"str",
".",
"substr",
"(",
"current_pos",
",",
"block_size",
")",
")",
";",
"}",
"return",
"blocks",
";",
"}"
] | Truncate a string into blocks of a set size | [
"Truncate",
"a",
"string",
"into",
"blocks",
"of",
"a",
"set",
"size"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/clientcommands.js#L88-L99 |
22,253 | prawnsalad/KiwiIRC | server/irc/connection.js | function () {
var that = this,
connect_data;
// Build up data to be used for webirc/etc detection
connect_data = {
connection: this,
// Array of lines to be sent to the IRCd before anything else
prepend_data: []
};
// Let the webirc/etc detection modify any required parameters
connect_data = findWebIrc.call(this, connect_data);
global.modules.emit('irc authorize', connect_data).then(function ircAuthorizeCb() {
// Send any initial data for webirc/etc
if (connect_data.prepend_data) {
_.each(connect_data.prepend_data, function(data) {
that.write(data);
});
}
that.write('CAP LS');
if (that.password) {
that.write('PASS ' + that.password);
}
that.write('NICK ' + that.nick);
that.write('USER ' + that.username + ' 0 0 :' + that.gecos);
that.emit('connected');
});
} | javascript | function () {
var that = this,
connect_data;
// Build up data to be used for webirc/etc detection
connect_data = {
connection: this,
// Array of lines to be sent to the IRCd before anything else
prepend_data: []
};
// Let the webirc/etc detection modify any required parameters
connect_data = findWebIrc.call(this, connect_data);
global.modules.emit('irc authorize', connect_data).then(function ircAuthorizeCb() {
// Send any initial data for webirc/etc
if (connect_data.prepend_data) {
_.each(connect_data.prepend_data, function(data) {
that.write(data);
});
}
that.write('CAP LS');
if (that.password) {
that.write('PASS ' + that.password);
}
that.write('NICK ' + that.nick);
that.write('USER ' + that.username + ' 0 0 :' + that.gecos);
that.emit('connected');
});
} | [
"function",
"(",
")",
"{",
"var",
"that",
"=",
"this",
",",
"connect_data",
";",
"// Build up data to be used for webirc/etc detection",
"connect_data",
"=",
"{",
"connection",
":",
"this",
",",
"// Array of lines to be sent to the IRCd before anything else",
"prepend_data",
":",
"[",
"]",
"}",
";",
"// Let the webirc/etc detection modify any required parameters",
"connect_data",
"=",
"findWebIrc",
".",
"call",
"(",
"this",
",",
"connect_data",
")",
";",
"global",
".",
"modules",
".",
"emit",
"(",
"'irc authorize'",
",",
"connect_data",
")",
".",
"then",
"(",
"function",
"ircAuthorizeCb",
"(",
")",
"{",
"// Send any initial data for webirc/etc",
"if",
"(",
"connect_data",
".",
"prepend_data",
")",
"{",
"_",
".",
"each",
"(",
"connect_data",
".",
"prepend_data",
",",
"function",
"(",
"data",
")",
"{",
"that",
".",
"write",
"(",
"data",
")",
";",
"}",
")",
";",
"}",
"that",
".",
"write",
"(",
"'CAP LS'",
")",
";",
"if",
"(",
"that",
".",
"password",
")",
"{",
"that",
".",
"write",
"(",
"'PASS '",
"+",
"that",
".",
"password",
")",
";",
"}",
"that",
".",
"write",
"(",
"'NICK '",
"+",
"that",
".",
"nick",
")",
";",
"that",
".",
"write",
"(",
"'USER '",
"+",
"that",
".",
"username",
"+",
"' 0 0 :'",
"+",
"that",
".",
"gecos",
")",
";",
"that",
".",
"emit",
"(",
"'connected'",
")",
";",
"}",
")",
";",
"}"
] | Handle the socket connect event, starting the IRCd registration | [
"Handle",
"the",
"socket",
"connect",
"event",
"starting",
"the",
"IRCd",
"registration"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/irc/connection.js#L732-L766 | |
22,254 | prawnsalad/KiwiIRC | server/irc/connection.js | findWebIrc | function findWebIrc(connect_data) {
var webirc_pass = global.config.webirc_pass,
found_webirc_pass, tmp;
// Do we have a single WEBIRC password?
if (typeof webirc_pass === 'string' && webirc_pass) {
found_webirc_pass = webirc_pass;
// Do we have a WEBIRC password for this hostname?
} else if (typeof webirc_pass === 'object' && webirc_pass[this.irc_host.hostname.toLowerCase()]) {
found_webirc_pass = webirc_pass[this.irc_host.hostname.toLowerCase()];
}
if (found_webirc_pass) {
// Build the WEBIRC line to be sent before IRC registration
tmp = 'WEBIRC ' + found_webirc_pass + ' KiwiIRC ';
tmp += this.user.hostname + ' ' + this.user.address;
connect_data.prepend_data = [tmp];
}
return connect_data;
} | javascript | function findWebIrc(connect_data) {
var webirc_pass = global.config.webirc_pass,
found_webirc_pass, tmp;
// Do we have a single WEBIRC password?
if (typeof webirc_pass === 'string' && webirc_pass) {
found_webirc_pass = webirc_pass;
// Do we have a WEBIRC password for this hostname?
} else if (typeof webirc_pass === 'object' && webirc_pass[this.irc_host.hostname.toLowerCase()]) {
found_webirc_pass = webirc_pass[this.irc_host.hostname.toLowerCase()];
}
if (found_webirc_pass) {
// Build the WEBIRC line to be sent before IRC registration
tmp = 'WEBIRC ' + found_webirc_pass + ' KiwiIRC ';
tmp += this.user.hostname + ' ' + this.user.address;
connect_data.prepend_data = [tmp];
}
return connect_data;
} | [
"function",
"findWebIrc",
"(",
"connect_data",
")",
"{",
"var",
"webirc_pass",
"=",
"global",
".",
"config",
".",
"webirc_pass",
",",
"found_webirc_pass",
",",
"tmp",
";",
"// Do we have a single WEBIRC password?",
"if",
"(",
"typeof",
"webirc_pass",
"===",
"'string'",
"&&",
"webirc_pass",
")",
"{",
"found_webirc_pass",
"=",
"webirc_pass",
";",
"// Do we have a WEBIRC password for this hostname?",
"}",
"else",
"if",
"(",
"typeof",
"webirc_pass",
"===",
"'object'",
"&&",
"webirc_pass",
"[",
"this",
".",
"irc_host",
".",
"hostname",
".",
"toLowerCase",
"(",
")",
"]",
")",
"{",
"found_webirc_pass",
"=",
"webirc_pass",
"[",
"this",
".",
"irc_host",
".",
"hostname",
".",
"toLowerCase",
"(",
")",
"]",
";",
"}",
"if",
"(",
"found_webirc_pass",
")",
"{",
"// Build the WEBIRC line to be sent before IRC registration",
"tmp",
"=",
"'WEBIRC '",
"+",
"found_webirc_pass",
"+",
"' KiwiIRC '",
";",
"tmp",
"+=",
"this",
".",
"user",
".",
"hostname",
"+",
"' '",
"+",
"this",
".",
"user",
".",
"address",
";",
"connect_data",
".",
"prepend_data",
"=",
"[",
"tmp",
"]",
";",
"}",
"return",
"connect_data",
";",
"}"
] | Load any WEBIRC or alternative settings for this connection
Called in scope of the IrcConnection instance | [
"Load",
"any",
"WEBIRC",
"or",
"alternative",
"settings",
"for",
"this",
"connection",
"Called",
"in",
"scope",
"of",
"the",
"IrcConnection",
"instance"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/irc/connection.js#L774-L797 |
22,255 | prawnsalad/KiwiIRC | server/irc/connection.js | socketOnData | function socketOnData(data) {
var data_pos, // Current position within the data Buffer
line_start = 0,
lines = [],
i,
max_buffer_size = 1024; // 1024 bytes is the maximum length of two RFC1459 IRC messages.
// May need tweaking when IRCv3 message tags are more widespread
// Split data chunk into individual lines
for (data_pos = 0; data_pos < data.length; data_pos++) {
if (data[data_pos] === 0x0A) { // Check if byte is a line feed
lines.push(data.slice(line_start, data_pos));
line_start = data_pos + 1;
}
}
// No complete lines of data? Check to see if buffering the data would exceed the max buffer size
if (!lines[0]) {
if ((this.held_data ? this.held_data.length : 0 ) + data.length > max_buffer_size) {
// Buffering this data would exeed our max buffer size
this.emit('error', 'Message buffer too large');
this.socket.destroy();
} else {
// Append the incomplete line to our held_data and wait for more
if (this.held_data) {
this.held_data = Buffer.concat([this.held_data, data], this.held_data.length + data.length);
} else {
this.held_data = data;
}
}
// No complete lines to process..
return;
}
// If we have an incomplete line held from the previous chunk of data
// merge it with the first line from this chunk of data
if (this.hold_last && this.held_data !== null) {
lines[0] = Buffer.concat([this.held_data, lines[0]], this.held_data.length + lines[0].length);
this.hold_last = false;
this.held_data = null;
}
// If the last line of data in this chunk is not complete, hold it so
// it can be merged with the first line from the next chunk
if (line_start < data_pos) {
if ((data.length - line_start) > max_buffer_size) {
// Buffering this data would exeed our max buffer size
this.emit('error', 'Message buffer too large');
this.socket.destroy();
return;
}
this.hold_last = true;
this.held_data = new Buffer(data.length - line_start);
data.copy(this.held_data, 0, line_start);
}
this.read_buffer = this.read_buffer.concat(lines);
processIrcLines(this);
} | javascript | function socketOnData(data) {
var data_pos, // Current position within the data Buffer
line_start = 0,
lines = [],
i,
max_buffer_size = 1024; // 1024 bytes is the maximum length of two RFC1459 IRC messages.
// May need tweaking when IRCv3 message tags are more widespread
// Split data chunk into individual lines
for (data_pos = 0; data_pos < data.length; data_pos++) {
if (data[data_pos] === 0x0A) { // Check if byte is a line feed
lines.push(data.slice(line_start, data_pos));
line_start = data_pos + 1;
}
}
// No complete lines of data? Check to see if buffering the data would exceed the max buffer size
if (!lines[0]) {
if ((this.held_data ? this.held_data.length : 0 ) + data.length > max_buffer_size) {
// Buffering this data would exeed our max buffer size
this.emit('error', 'Message buffer too large');
this.socket.destroy();
} else {
// Append the incomplete line to our held_data and wait for more
if (this.held_data) {
this.held_data = Buffer.concat([this.held_data, data], this.held_data.length + data.length);
} else {
this.held_data = data;
}
}
// No complete lines to process..
return;
}
// If we have an incomplete line held from the previous chunk of data
// merge it with the first line from this chunk of data
if (this.hold_last && this.held_data !== null) {
lines[0] = Buffer.concat([this.held_data, lines[0]], this.held_data.length + lines[0].length);
this.hold_last = false;
this.held_data = null;
}
// If the last line of data in this chunk is not complete, hold it so
// it can be merged with the first line from the next chunk
if (line_start < data_pos) {
if ((data.length - line_start) > max_buffer_size) {
// Buffering this data would exeed our max buffer size
this.emit('error', 'Message buffer too large');
this.socket.destroy();
return;
}
this.hold_last = true;
this.held_data = new Buffer(data.length - line_start);
data.copy(this.held_data, 0, line_start);
}
this.read_buffer = this.read_buffer.concat(lines);
processIrcLines(this);
} | [
"function",
"socketOnData",
"(",
"data",
")",
"{",
"var",
"data_pos",
",",
"// Current position within the data Buffer",
"line_start",
"=",
"0",
",",
"lines",
"=",
"[",
"]",
",",
"i",
",",
"max_buffer_size",
"=",
"1024",
";",
"// 1024 bytes is the maximum length of two RFC1459 IRC messages.",
"// May need tweaking when IRCv3 message tags are more widespread",
"// Split data chunk into individual lines",
"for",
"(",
"data_pos",
"=",
"0",
";",
"data_pos",
"<",
"data",
".",
"length",
";",
"data_pos",
"++",
")",
"{",
"if",
"(",
"data",
"[",
"data_pos",
"]",
"===",
"0x0A",
")",
"{",
"// Check if byte is a line feed",
"lines",
".",
"push",
"(",
"data",
".",
"slice",
"(",
"line_start",
",",
"data_pos",
")",
")",
";",
"line_start",
"=",
"data_pos",
"+",
"1",
";",
"}",
"}",
"// No complete lines of data? Check to see if buffering the data would exceed the max buffer size",
"if",
"(",
"!",
"lines",
"[",
"0",
"]",
")",
"{",
"if",
"(",
"(",
"this",
".",
"held_data",
"?",
"this",
".",
"held_data",
".",
"length",
":",
"0",
")",
"+",
"data",
".",
"length",
">",
"max_buffer_size",
")",
"{",
"// Buffering this data would exeed our max buffer size",
"this",
".",
"emit",
"(",
"'error'",
",",
"'Message buffer too large'",
")",
";",
"this",
".",
"socket",
".",
"destroy",
"(",
")",
";",
"}",
"else",
"{",
"// Append the incomplete line to our held_data and wait for more",
"if",
"(",
"this",
".",
"held_data",
")",
"{",
"this",
".",
"held_data",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"this",
".",
"held_data",
",",
"data",
"]",
",",
"this",
".",
"held_data",
".",
"length",
"+",
"data",
".",
"length",
")",
";",
"}",
"else",
"{",
"this",
".",
"held_data",
"=",
"data",
";",
"}",
"}",
"// No complete lines to process..",
"return",
";",
"}",
"// If we have an incomplete line held from the previous chunk of data",
"// merge it with the first line from this chunk of data",
"if",
"(",
"this",
".",
"hold_last",
"&&",
"this",
".",
"held_data",
"!==",
"null",
")",
"{",
"lines",
"[",
"0",
"]",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"this",
".",
"held_data",
",",
"lines",
"[",
"0",
"]",
"]",
",",
"this",
".",
"held_data",
".",
"length",
"+",
"lines",
"[",
"0",
"]",
".",
"length",
")",
";",
"this",
".",
"hold_last",
"=",
"false",
";",
"this",
".",
"held_data",
"=",
"null",
";",
"}",
"// If the last line of data in this chunk is not complete, hold it so",
"// it can be merged with the first line from the next chunk",
"if",
"(",
"line_start",
"<",
"data_pos",
")",
"{",
"if",
"(",
"(",
"data",
".",
"length",
"-",
"line_start",
")",
">",
"max_buffer_size",
")",
"{",
"// Buffering this data would exeed our max buffer size",
"this",
".",
"emit",
"(",
"'error'",
",",
"'Message buffer too large'",
")",
";",
"this",
".",
"socket",
".",
"destroy",
"(",
")",
";",
"return",
";",
"}",
"this",
".",
"hold_last",
"=",
"true",
";",
"this",
".",
"held_data",
"=",
"new",
"Buffer",
"(",
"data",
".",
"length",
"-",
"line_start",
")",
";",
"data",
".",
"copy",
"(",
"this",
".",
"held_data",
",",
"0",
",",
"line_start",
")",
";",
"}",
"this",
".",
"read_buffer",
"=",
"this",
".",
"read_buffer",
".",
"concat",
"(",
"lines",
")",
";",
"processIrcLines",
"(",
"this",
")",
";",
"}"
] | Buffer any data we get from the IRCd until we have complete lines. | [
"Buffer",
"any",
"data",
"we",
"get",
"from",
"the",
"IRCd",
"until",
"we",
"have",
"complete",
"lines",
"."
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/irc/connection.js#L803-L865 |
22,256 | prawnsalad/KiwiIRC | server/irc/connection.js | processIrcLines | function processIrcLines(irc_con, continue_processing) {
if (irc_con.reading_buffer && !continue_processing) return;
irc_con.reading_buffer = true;
var lines_per_js_tick = 4,
processed_lines = 0;
while(processed_lines < lines_per_js_tick && irc_con.read_buffer.length > 0) {
parseIrcLine(irc_con, irc_con.read_buffer.shift());
processed_lines++;
Stats.incr('irc.connection.parsed_lines');
}
if (irc_con.read_buffer.length > 0) {
irc_con.setTimeout(processIrcLines, 1, irc_con, true);
} else {
irc_con.reading_buffer = false;
}
} | javascript | function processIrcLines(irc_con, continue_processing) {
if (irc_con.reading_buffer && !continue_processing) return;
irc_con.reading_buffer = true;
var lines_per_js_tick = 4,
processed_lines = 0;
while(processed_lines < lines_per_js_tick && irc_con.read_buffer.length > 0) {
parseIrcLine(irc_con, irc_con.read_buffer.shift());
processed_lines++;
Stats.incr('irc.connection.parsed_lines');
}
if (irc_con.read_buffer.length > 0) {
irc_con.setTimeout(processIrcLines, 1, irc_con, true);
} else {
irc_con.reading_buffer = false;
}
} | [
"function",
"processIrcLines",
"(",
"irc_con",
",",
"continue_processing",
")",
"{",
"if",
"(",
"irc_con",
".",
"reading_buffer",
"&&",
"!",
"continue_processing",
")",
"return",
";",
"irc_con",
".",
"reading_buffer",
"=",
"true",
";",
"var",
"lines_per_js_tick",
"=",
"4",
",",
"processed_lines",
"=",
"0",
";",
"while",
"(",
"processed_lines",
"<",
"lines_per_js_tick",
"&&",
"irc_con",
".",
"read_buffer",
".",
"length",
">",
"0",
")",
"{",
"parseIrcLine",
"(",
"irc_con",
",",
"irc_con",
".",
"read_buffer",
".",
"shift",
"(",
")",
")",
";",
"processed_lines",
"++",
";",
"Stats",
".",
"incr",
"(",
"'irc.connection.parsed_lines'",
")",
";",
"}",
"if",
"(",
"irc_con",
".",
"read_buffer",
".",
"length",
">",
"0",
")",
"{",
"irc_con",
".",
"setTimeout",
"(",
"processIrcLines",
",",
"1",
",",
"irc_con",
",",
"true",
")",
";",
"}",
"else",
"{",
"irc_con",
".",
"reading_buffer",
"=",
"false",
";",
"}",
"}"
] | Process the messages recieved from the IRCd that are buffered on an IrcConnection object
Will only process 4 lines per JS tick so that node can handle any other events while
handling a large buffer | [
"Process",
"the",
"messages",
"recieved",
"from",
"the",
"IRCd",
"that",
"are",
"buffered",
"on",
"an",
"IrcConnection",
"object",
"Will",
"only",
"process",
"4",
"lines",
"per",
"JS",
"tick",
"so",
"that",
"node",
"can",
"handle",
"any",
"other",
"events",
"while",
"handling",
"a",
"large",
"buffer"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/irc/connection.js#L896-L914 |
22,257 | prawnsalad/KiwiIRC | server/proxy.js | ProxySocket | function ProxySocket(proxy_port, proxy_addr, meta, proxy_opts) {
stream.Duplex.call(this);
this.connected_fn = null;
this.proxy_addr = proxy_addr;
this.proxy_port = proxy_port;
this.proxy_opts = proxy_opts || {};
this.setMeta(meta || {});
this.state = 'disconnected';
} | javascript | function ProxySocket(proxy_port, proxy_addr, meta, proxy_opts) {
stream.Duplex.call(this);
this.connected_fn = null;
this.proxy_addr = proxy_addr;
this.proxy_port = proxy_port;
this.proxy_opts = proxy_opts || {};
this.setMeta(meta || {});
this.state = 'disconnected';
} | [
"function",
"ProxySocket",
"(",
"proxy_port",
",",
"proxy_addr",
",",
"meta",
",",
"proxy_opts",
")",
"{",
"stream",
".",
"Duplex",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"connected_fn",
"=",
"null",
";",
"this",
".",
"proxy_addr",
"=",
"proxy_addr",
";",
"this",
".",
"proxy_port",
"=",
"proxy_port",
";",
"this",
".",
"proxy_opts",
"=",
"proxy_opts",
"||",
"{",
"}",
";",
"this",
".",
"setMeta",
"(",
"meta",
"||",
"{",
"}",
")",
";",
"this",
".",
"state",
"=",
"'disconnected'",
";",
"}"
] | ProxySocket
Transparent socket interface to a kiwi proxy | [
"ProxySocket",
"Transparent",
"socket",
"interface",
"to",
"a",
"kiwi",
"proxy"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/proxy.js#L273-L284 |
22,258 | prawnsalad/KiwiIRC | server_modules/dnsbl.js | isBlacklisted | function isBlacklisted(ip, callback) {
var host_lookup = reverseIp(ip) + bl_zones[current_bl];
dns.resolve4(host_lookup, function(err, domain) {
if (err) {
// Not blacklisted
callback(false);
} else {
// It is blacklisted
callback(true);
}
});
} | javascript | function isBlacklisted(ip, callback) {
var host_lookup = reverseIp(ip) + bl_zones[current_bl];
dns.resolve4(host_lookup, function(err, domain) {
if (err) {
// Not blacklisted
callback(false);
} else {
// It is blacklisted
callback(true);
}
});
} | [
"function",
"isBlacklisted",
"(",
"ip",
",",
"callback",
")",
"{",
"var",
"host_lookup",
"=",
"reverseIp",
"(",
"ip",
")",
"+",
"bl_zones",
"[",
"current_bl",
"]",
";",
"dns",
".",
"resolve4",
"(",
"host_lookup",
",",
"function",
"(",
"err",
",",
"domain",
")",
"{",
"if",
"(",
"err",
")",
"{",
"// Not blacklisted",
"callback",
"(",
"false",
")",
";",
"}",
"else",
"{",
"// It is blacklisted",
"callback",
"(",
"true",
")",
";",
"}",
"}",
")",
";",
"}"
] | The actual checking against the DNS blacklist | [
"The",
"actual",
"checking",
"against",
"the",
"DNS",
"blacklist"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server_modules/dnsbl.js#L45-L57 |
22,259 | prawnsalad/KiwiIRC | client/src/app.js | function() {
var network = typeof connection_id === 'undefined' ?
_kiwi.app.connections.active_connection :
_kiwi.app.connections.getByConnectionId(connection_id);
return network ?
network :
undefined;
} | javascript | function() {
var network = typeof connection_id === 'undefined' ?
_kiwi.app.connections.active_connection :
_kiwi.app.connections.getByConnectionId(connection_id);
return network ?
network :
undefined;
} | [
"function",
"(",
")",
"{",
"var",
"network",
"=",
"typeof",
"connection_id",
"===",
"'undefined'",
"?",
"_kiwi",
".",
"app",
".",
"connections",
".",
"active_connection",
":",
"_kiwi",
".",
"app",
".",
"connections",
".",
"getByConnectionId",
"(",
"connection_id",
")",
";",
"return",
"network",
"?",
"network",
":",
"undefined",
";",
"}"
] | Helper to get the network object | [
"Helper",
"to",
"get",
"the",
"network",
"object"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/app.js#L105-L113 | |
22,260 | prawnsalad/KiwiIRC | client/src/app.js | function (opts, callback) {
var locale_promise, theme_promise,
that = this;
opts = opts || {};
this.initUtils();
// Set up the settings datastore
_kiwi.global.settings = _kiwi.model.DataStore.instance('kiwi.settings');
_kiwi.global.settings.load();
// Set the window title
window.document.title = opts.server_settings.client.window_title || 'Kiwi IRC';
locale_promise = new Promise(function (resolve) {
// In order, find a locale from the users saved settings, the URL, default settings on the server, or auto detect
var locale = _kiwi.global.settings.get('locale') || opts.locale || opts.server_settings.client.settings.locale || 'magic';
$.getJSON(opts.base_path + '/assets/locales/' + locale + '.json', function (locale) {
if (locale) {
that.i18n = new Jed(locale);
} else {
that.i18n = new Jed();
}
resolve();
});
});
theme_promise = new Promise(function (resolve) {
var text_theme = opts.server_settings.client.settings.text_theme || 'default';
$.getJSON(opts.base_path + '/assets/text_themes/' + text_theme + '.json', function(text_theme) {
opts.text_theme = text_theme;
resolve();
});
});
Promise.all([locale_promise, theme_promise]).then(function () {
_kiwi.app = new _kiwi.model.Application(opts);
// Start the client up
_kiwi.app.initializeInterfaces();
// Event emitter to let plugins interface with parts of kiwi
_kiwi.global.events = new PluginInterface();
// Now everything has started up, load the plugin manager for third party plugins
_kiwi.global.plugins = new _kiwi.model.PluginManager();
callback();
}).then(null, function(err) {
console.error(err.stack);
});
} | javascript | function (opts, callback) {
var locale_promise, theme_promise,
that = this;
opts = opts || {};
this.initUtils();
// Set up the settings datastore
_kiwi.global.settings = _kiwi.model.DataStore.instance('kiwi.settings');
_kiwi.global.settings.load();
// Set the window title
window.document.title = opts.server_settings.client.window_title || 'Kiwi IRC';
locale_promise = new Promise(function (resolve) {
// In order, find a locale from the users saved settings, the URL, default settings on the server, or auto detect
var locale = _kiwi.global.settings.get('locale') || opts.locale || opts.server_settings.client.settings.locale || 'magic';
$.getJSON(opts.base_path + '/assets/locales/' + locale + '.json', function (locale) {
if (locale) {
that.i18n = new Jed(locale);
} else {
that.i18n = new Jed();
}
resolve();
});
});
theme_promise = new Promise(function (resolve) {
var text_theme = opts.server_settings.client.settings.text_theme || 'default';
$.getJSON(opts.base_path + '/assets/text_themes/' + text_theme + '.json', function(text_theme) {
opts.text_theme = text_theme;
resolve();
});
});
Promise.all([locale_promise, theme_promise]).then(function () {
_kiwi.app = new _kiwi.model.Application(opts);
// Start the client up
_kiwi.app.initializeInterfaces();
// Event emitter to let plugins interface with parts of kiwi
_kiwi.global.events = new PluginInterface();
// Now everything has started up, load the plugin manager for third party plugins
_kiwi.global.plugins = new _kiwi.model.PluginManager();
callback();
}).then(null, function(err) {
console.error(err.stack);
});
} | [
"function",
"(",
"opts",
",",
"callback",
")",
"{",
"var",
"locale_promise",
",",
"theme_promise",
",",
"that",
"=",
"this",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"initUtils",
"(",
")",
";",
"// Set up the settings datastore\r",
"_kiwi",
".",
"global",
".",
"settings",
"=",
"_kiwi",
".",
"model",
".",
"DataStore",
".",
"instance",
"(",
"'kiwi.settings'",
")",
";",
"_kiwi",
".",
"global",
".",
"settings",
".",
"load",
"(",
")",
";",
"// Set the window title\r",
"window",
".",
"document",
".",
"title",
"=",
"opts",
".",
"server_settings",
".",
"client",
".",
"window_title",
"||",
"'Kiwi IRC'",
";",
"locale_promise",
"=",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
")",
"{",
"// In order, find a locale from the users saved settings, the URL, default settings on the server, or auto detect\r",
"var",
"locale",
"=",
"_kiwi",
".",
"global",
".",
"settings",
".",
"get",
"(",
"'locale'",
")",
"||",
"opts",
".",
"locale",
"||",
"opts",
".",
"server_settings",
".",
"client",
".",
"settings",
".",
"locale",
"||",
"'magic'",
";",
"$",
".",
"getJSON",
"(",
"opts",
".",
"base_path",
"+",
"'/assets/locales/'",
"+",
"locale",
"+",
"'.json'",
",",
"function",
"(",
"locale",
")",
"{",
"if",
"(",
"locale",
")",
"{",
"that",
".",
"i18n",
"=",
"new",
"Jed",
"(",
"locale",
")",
";",
"}",
"else",
"{",
"that",
".",
"i18n",
"=",
"new",
"Jed",
"(",
")",
";",
"}",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"theme_promise",
"=",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
")",
"{",
"var",
"text_theme",
"=",
"opts",
".",
"server_settings",
".",
"client",
".",
"settings",
".",
"text_theme",
"||",
"'default'",
";",
"$",
".",
"getJSON",
"(",
"opts",
".",
"base_path",
"+",
"'/assets/text_themes/'",
"+",
"text_theme",
"+",
"'.json'",
",",
"function",
"(",
"text_theme",
")",
"{",
"opts",
".",
"text_theme",
"=",
"text_theme",
";",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"Promise",
".",
"all",
"(",
"[",
"locale_promise",
",",
"theme_promise",
"]",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"_kiwi",
".",
"app",
"=",
"new",
"_kiwi",
".",
"model",
".",
"Application",
"(",
"opts",
")",
";",
"// Start the client up\r",
"_kiwi",
".",
"app",
".",
"initializeInterfaces",
"(",
")",
";",
"// Event emitter to let plugins interface with parts of kiwi\r",
"_kiwi",
".",
"global",
".",
"events",
"=",
"new",
"PluginInterface",
"(",
")",
";",
"// Now everything has started up, load the plugin manager for third party plugins\r",
"_kiwi",
".",
"global",
".",
"plugins",
"=",
"new",
"_kiwi",
".",
"model",
".",
"PluginManager",
"(",
")",
";",
"callback",
"(",
")",
";",
"}",
")",
".",
"then",
"(",
"null",
",",
"function",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"err",
".",
"stack",
")",
";",
"}",
")",
";",
"}"
] | Entry point to start the kiwi application | [
"Entry",
"point",
"to",
"start",
"the",
"kiwi",
"application"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/app.js#L223-L277 | |
22,261 | prawnsalad/KiwiIRC | server/settingsgenerator.js | generateSettings | function generateSettings(debug) {
var vars = {
server_settings: {},
client_plugins: [],
translations: [],
scripts: [
[
'assets/libs/lodash.min.js'
],
['assets/libs/backbone.min.js', 'assets/libs/jed.js']
]
};
// Any restricted server mode set?
if (config.get().restrict_server) {
vars.server_settings = {
connection: {
server: config.get().restrict_server,
port: config.get().restrict_server_port || 6667,
ssl: config.get().restrict_server_ssl,
allow_change: false
}
};
}
// Any client default settings?
if (config.get().client) {
vars.server_settings.client = config.get().client;
}
// Client transport specified?
if (config.get().client_transports) {
vars.server_settings.transports = config.get().client_transports;
}
// Any client plugins?
if (config.get().client_plugins && config.get().client_plugins.length > 0) {
vars.client_plugins = config.get().client_plugins;
}
addScripts(vars, debug);
return Promise.all([addThemes().then(function (themes) {
vars.themes = themes;
}), addTranslations().then(function (translations) {
vars.translations = translations;
})]).then(function () {
var settings = JSON.stringify(vars);
return ({
settings: settings,
hash: crypto.createHash('md5').update(settings).digest('hex')
});
});
} | javascript | function generateSettings(debug) {
var vars = {
server_settings: {},
client_plugins: [],
translations: [],
scripts: [
[
'assets/libs/lodash.min.js'
],
['assets/libs/backbone.min.js', 'assets/libs/jed.js']
]
};
// Any restricted server mode set?
if (config.get().restrict_server) {
vars.server_settings = {
connection: {
server: config.get().restrict_server,
port: config.get().restrict_server_port || 6667,
ssl: config.get().restrict_server_ssl,
allow_change: false
}
};
}
// Any client default settings?
if (config.get().client) {
vars.server_settings.client = config.get().client;
}
// Client transport specified?
if (config.get().client_transports) {
vars.server_settings.transports = config.get().client_transports;
}
// Any client plugins?
if (config.get().client_plugins && config.get().client_plugins.length > 0) {
vars.client_plugins = config.get().client_plugins;
}
addScripts(vars, debug);
return Promise.all([addThemes().then(function (themes) {
vars.themes = themes;
}), addTranslations().then(function (translations) {
vars.translations = translations;
})]).then(function () {
var settings = JSON.stringify(vars);
return ({
settings: settings,
hash: crypto.createHash('md5').update(settings).digest('hex')
});
});
} | [
"function",
"generateSettings",
"(",
"debug",
")",
"{",
"var",
"vars",
"=",
"{",
"server_settings",
":",
"{",
"}",
",",
"client_plugins",
":",
"[",
"]",
",",
"translations",
":",
"[",
"]",
",",
"scripts",
":",
"[",
"[",
"'assets/libs/lodash.min.js'",
"]",
",",
"[",
"'assets/libs/backbone.min.js'",
",",
"'assets/libs/jed.js'",
"]",
"]",
"}",
";",
"// Any restricted server mode set?",
"if",
"(",
"config",
".",
"get",
"(",
")",
".",
"restrict_server",
")",
"{",
"vars",
".",
"server_settings",
"=",
"{",
"connection",
":",
"{",
"server",
":",
"config",
".",
"get",
"(",
")",
".",
"restrict_server",
",",
"port",
":",
"config",
".",
"get",
"(",
")",
".",
"restrict_server_port",
"||",
"6667",
",",
"ssl",
":",
"config",
".",
"get",
"(",
")",
".",
"restrict_server_ssl",
",",
"allow_change",
":",
"false",
"}",
"}",
";",
"}",
"// Any client default settings?",
"if",
"(",
"config",
".",
"get",
"(",
")",
".",
"client",
")",
"{",
"vars",
".",
"server_settings",
".",
"client",
"=",
"config",
".",
"get",
"(",
")",
".",
"client",
";",
"}",
"// Client transport specified?",
"if",
"(",
"config",
".",
"get",
"(",
")",
".",
"client_transports",
")",
"{",
"vars",
".",
"server_settings",
".",
"transports",
"=",
"config",
".",
"get",
"(",
")",
".",
"client_transports",
";",
"}",
"// Any client plugins?",
"if",
"(",
"config",
".",
"get",
"(",
")",
".",
"client_plugins",
"&&",
"config",
".",
"get",
"(",
")",
".",
"client_plugins",
".",
"length",
">",
"0",
")",
"{",
"vars",
".",
"client_plugins",
"=",
"config",
".",
"get",
"(",
")",
".",
"client_plugins",
";",
"}",
"addScripts",
"(",
"vars",
",",
"debug",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"[",
"addThemes",
"(",
")",
".",
"then",
"(",
"function",
"(",
"themes",
")",
"{",
"vars",
".",
"themes",
"=",
"themes",
";",
"}",
")",
",",
"addTranslations",
"(",
")",
".",
"then",
"(",
"function",
"(",
"translations",
")",
"{",
"vars",
".",
"translations",
"=",
"translations",
";",
"}",
")",
"]",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"settings",
"=",
"JSON",
".",
"stringify",
"(",
"vars",
")",
";",
"return",
"(",
"{",
"settings",
":",
"settings",
",",
"hash",
":",
"crypto",
".",
"createHash",
"(",
"'md5'",
")",
".",
"update",
"(",
"settings",
")",
".",
"digest",
"(",
"'hex'",
")",
"}",
")",
";",
"}",
")",
";",
"}"
] | Generate a settings object for the client.
Settings include available translations, default client config, etc | [
"Generate",
"a",
"settings",
"object",
"for",
"the",
"client",
".",
"Settings",
"include",
"available",
"translations",
"default",
"client",
"config",
"etc"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/settingsgenerator.js#L53-L106 |
22,262 | prawnsalad/KiwiIRC | client/src/views/channel.js | function(word, colourise) {
var members, member, nick, nick_re, style = '';
if (!(members = this.model.get('members')) || !(member = members.getByNick(word))) {
return;
}
nick = member.get('nick');
if (colourise !== false) {
// Use the nick from the member object so the style matches the letter casing
style = this.getNickStyles(nick).asCssString();
}
nick_re = new RegExp('(.*)(' + _.escapeRegExp(nick) + ')(.*)', 'i');
return word.replace(nick_re, function (__, before, nick_in_orig_case, after) {
return _.escape(before)
+ '<span class="inline-nick" style="' + style + '; cursor:pointer" data-nick="' + _.escape(nick) + '">'
+ _.escape(nick_in_orig_case)
+ '</span>'
+ _.escape(after);
});
} | javascript | function(word, colourise) {
var members, member, nick, nick_re, style = '';
if (!(members = this.model.get('members')) || !(member = members.getByNick(word))) {
return;
}
nick = member.get('nick');
if (colourise !== false) {
// Use the nick from the member object so the style matches the letter casing
style = this.getNickStyles(nick).asCssString();
}
nick_re = new RegExp('(.*)(' + _.escapeRegExp(nick) + ')(.*)', 'i');
return word.replace(nick_re, function (__, before, nick_in_orig_case, after) {
return _.escape(before)
+ '<span class="inline-nick" style="' + style + '; cursor:pointer" data-nick="' + _.escape(nick) + '">'
+ _.escape(nick_in_orig_case)
+ '</span>'
+ _.escape(after);
});
} | [
"function",
"(",
"word",
",",
"colourise",
")",
"{",
"var",
"members",
",",
"member",
",",
"nick",
",",
"nick_re",
",",
"style",
"=",
"''",
";",
"if",
"(",
"!",
"(",
"members",
"=",
"this",
".",
"model",
".",
"get",
"(",
"'members'",
")",
")",
"||",
"!",
"(",
"member",
"=",
"members",
".",
"getByNick",
"(",
"word",
")",
")",
")",
"{",
"return",
";",
"}",
"nick",
"=",
"member",
".",
"get",
"(",
"'nick'",
")",
";",
"if",
"(",
"colourise",
"!==",
"false",
")",
"{",
"// Use the nick from the member object so the style matches the letter casing",
"style",
"=",
"this",
".",
"getNickStyles",
"(",
"nick",
")",
".",
"asCssString",
"(",
")",
";",
"}",
"nick_re",
"=",
"new",
"RegExp",
"(",
"'(.*)('",
"+",
"_",
".",
"escapeRegExp",
"(",
"nick",
")",
"+",
"')(.*)'",
",",
"'i'",
")",
";",
"return",
"word",
".",
"replace",
"(",
"nick_re",
",",
"function",
"(",
"__",
",",
"before",
",",
"nick_in_orig_case",
",",
"after",
")",
"{",
"return",
"_",
".",
"escape",
"(",
"before",
")",
"+",
"'<span class=\"inline-nick\" style=\"'",
"+",
"style",
"+",
"'; cursor:pointer\" data-nick=\"'",
"+",
"_",
".",
"escape",
"(",
"nick",
")",
"+",
"'\">'",
"+",
"_",
".",
"escape",
"(",
"nick_in_orig_case",
")",
"+",
"'</span>'",
"+",
"_",
".",
"escape",
"(",
"after",
")",
";",
"}",
")",
";",
"}"
] | Let nicks be clickable + colourise within messages | [
"Let",
"nicks",
"be",
"clickable",
"+",
"colourise",
"within",
"messages"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/views/channel.js#L174-L195 | |
22,263 | prawnsalad/KiwiIRC | client/src/views/channel.js | function(word) {
var re,
parsed = false,
network = this.model.get('network');
if (!network) {
return;
}
re = new RegExp('(^|\\s)([' + _.escapeRegExp(network.get('channel_prefix')) + '][^ .,\\007]+)', 'g');
if (!word.match(re)) {
return parsed;
}
parsed = word.replace(re, function (m1, m2) {
return m2 + '<a class="chan" data-channel="' + _.escape(m1.trim()) + '">' + _.escape(m1.trim()) + '</a>';
});
return parsed;
} | javascript | function(word) {
var re,
parsed = false,
network = this.model.get('network');
if (!network) {
return;
}
re = new RegExp('(^|\\s)([' + _.escapeRegExp(network.get('channel_prefix')) + '][^ .,\\007]+)', 'g');
if (!word.match(re)) {
return parsed;
}
parsed = word.replace(re, function (m1, m2) {
return m2 + '<a class="chan" data-channel="' + _.escape(m1.trim()) + '">' + _.escape(m1.trim()) + '</a>';
});
return parsed;
} | [
"function",
"(",
"word",
")",
"{",
"var",
"re",
",",
"parsed",
"=",
"false",
",",
"network",
"=",
"this",
".",
"model",
".",
"get",
"(",
"'network'",
")",
";",
"if",
"(",
"!",
"network",
")",
"{",
"return",
";",
"}",
"re",
"=",
"new",
"RegExp",
"(",
"'(^|\\\\s)(['",
"+",
"_",
".",
"escapeRegExp",
"(",
"network",
".",
"get",
"(",
"'channel_prefix'",
")",
")",
"+",
"'][^ .,\\\\007]+)'",
",",
"'g'",
")",
";",
"if",
"(",
"!",
"word",
".",
"match",
"(",
"re",
")",
")",
"{",
"return",
"parsed",
";",
"}",
"parsed",
"=",
"word",
".",
"replace",
"(",
"re",
",",
"function",
"(",
"m1",
",",
"m2",
")",
"{",
"return",
"m2",
"+",
"'<a class=\"chan\" data-channel=\"'",
"+",
"_",
".",
"escape",
"(",
"m1",
".",
"trim",
"(",
")",
")",
"+",
"'\">'",
"+",
"_",
".",
"escape",
"(",
"m1",
".",
"trim",
"(",
")",
")",
"+",
"'</a>'",
";",
"}",
")",
";",
"return",
"parsed",
";",
"}"
] | Make channels clickable | [
"Make",
"channels",
"clickable"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/views/channel.js#L199-L219 | |
22,264 | prawnsalad/KiwiIRC | client/src/views/channel.js | function(msg) {
var nick_hex, time_difference,
message_words,
sb = this.model.get('scrollback'),
network = this.model.get('network'),
nick,
regexpStr,
prev_msg = sb[sb.length-2],
hour, pm, am_pm_locale_key;
// Clone the msg object so we dont modify the original
msg = _.clone(msg);
// Defaults
msg.css_classes = '';
msg.nick_style = '';
msg.is_highlight = false;
msg.time_string = '';
// Nick + custom highlight detecting
nick = network ? network.get('nick') : '';
if (nick && msg.nick.localeCompare(nick) !== 0) {
// Build a list of all highlights and escape them for regex
regexpStr = _.chain((_kiwi.global.settings.get('custom_highlights') || '').split(/[\s,]+/))
.compact()
.concat(nick)
.map(_.escapeRegExp)
.join('|')
.value();
if (msg.msg.search(new RegExp('(\\b|\\W|^)(' + regexpStr + ')(\\b|\\W|$)', 'i')) > -1) {
msg.is_highlight = true;
msg.css_classes += ' highlight';
}
}
message_words = msg.msg.split(' ');
message_words = _.map(message_words, function(word) {
var parsed_word;
parsed_word = this.parseMessageUrls(word);
if (typeof parsed_word === 'string') return parsed_word;
parsed_word = this.parseMessageChannels(word);
if (typeof parsed_word === 'string') return parsed_word;
parsed_word = this.parseMessageNicks(word, (msg.type === 'privmsg'));
if (typeof parsed_word === 'string') return parsed_word;
parsed_word = _.escape(word);
// Replace text emoticons with images
if (_kiwi.global.settings.get('show_emoticons')) {
parsed_word = emoticonFromText(parsed_word);
}
return parsed_word;
}, this);
msg.unparsed_msg = msg.msg;
msg.msg = message_words.join(' ');
// Convert IRC formatting into HTML formatting
msg.msg = formatIRCMsg(msg.msg);
// Add some style to the nick
msg.nick_style = this.getNickStyles(msg.nick).asCssString();
// Generate a hex string from the nick to be used as a CSS class name
nick_hex = '';
if (msg.nick) {
_.map(msg.nick.split(''), function (char) {
nick_hex += char.charCodeAt(0).toString(16);
});
msg.css_classes += ' nick_' + nick_hex;
}
if (prev_msg) {
// Time difference between this message and the last (in minutes)
time_difference = (msg.time.getTime() - prev_msg.time.getTime())/1000/60;
if (prev_msg.nick === msg.nick && time_difference < 1) {
msg.css_classes += ' repeated_nick';
}
}
// Build up and add the line
if (_kiwi.global.settings.get('use_24_hour_timestamps')) {
msg.time_string = msg.time.getHours().toString().lpad(2, "0") + ":" + msg.time.getMinutes().toString().lpad(2, "0") + ":" + msg.time.getSeconds().toString().lpad(2, "0");
} else {
hour = msg.time.getHours();
pm = hour > 11;
hour = hour % 12;
if (hour === 0)
hour = 12;
am_pm_locale_key = pm ?
'client_views_panel_timestamp_pm' :
'client_views_panel_timestamp_am';
msg.time_string = translateText(am_pm_locale_key, hour + ":" + msg.time.getMinutes().toString().lpad(2, "0") + ":" + msg.time.getSeconds().toString().lpad(2, "0"));
}
return msg;
} | javascript | function(msg) {
var nick_hex, time_difference,
message_words,
sb = this.model.get('scrollback'),
network = this.model.get('network'),
nick,
regexpStr,
prev_msg = sb[sb.length-2],
hour, pm, am_pm_locale_key;
// Clone the msg object so we dont modify the original
msg = _.clone(msg);
// Defaults
msg.css_classes = '';
msg.nick_style = '';
msg.is_highlight = false;
msg.time_string = '';
// Nick + custom highlight detecting
nick = network ? network.get('nick') : '';
if (nick && msg.nick.localeCompare(nick) !== 0) {
// Build a list of all highlights and escape them for regex
regexpStr = _.chain((_kiwi.global.settings.get('custom_highlights') || '').split(/[\s,]+/))
.compact()
.concat(nick)
.map(_.escapeRegExp)
.join('|')
.value();
if (msg.msg.search(new RegExp('(\\b|\\W|^)(' + regexpStr + ')(\\b|\\W|$)', 'i')) > -1) {
msg.is_highlight = true;
msg.css_classes += ' highlight';
}
}
message_words = msg.msg.split(' ');
message_words = _.map(message_words, function(word) {
var parsed_word;
parsed_word = this.parseMessageUrls(word);
if (typeof parsed_word === 'string') return parsed_word;
parsed_word = this.parseMessageChannels(word);
if (typeof parsed_word === 'string') return parsed_word;
parsed_word = this.parseMessageNicks(word, (msg.type === 'privmsg'));
if (typeof parsed_word === 'string') return parsed_word;
parsed_word = _.escape(word);
// Replace text emoticons with images
if (_kiwi.global.settings.get('show_emoticons')) {
parsed_word = emoticonFromText(parsed_word);
}
return parsed_word;
}, this);
msg.unparsed_msg = msg.msg;
msg.msg = message_words.join(' ');
// Convert IRC formatting into HTML formatting
msg.msg = formatIRCMsg(msg.msg);
// Add some style to the nick
msg.nick_style = this.getNickStyles(msg.nick).asCssString();
// Generate a hex string from the nick to be used as a CSS class name
nick_hex = '';
if (msg.nick) {
_.map(msg.nick.split(''), function (char) {
nick_hex += char.charCodeAt(0).toString(16);
});
msg.css_classes += ' nick_' + nick_hex;
}
if (prev_msg) {
// Time difference between this message and the last (in minutes)
time_difference = (msg.time.getTime() - prev_msg.time.getTime())/1000/60;
if (prev_msg.nick === msg.nick && time_difference < 1) {
msg.css_classes += ' repeated_nick';
}
}
// Build up and add the line
if (_kiwi.global.settings.get('use_24_hour_timestamps')) {
msg.time_string = msg.time.getHours().toString().lpad(2, "0") + ":" + msg.time.getMinutes().toString().lpad(2, "0") + ":" + msg.time.getSeconds().toString().lpad(2, "0");
} else {
hour = msg.time.getHours();
pm = hour > 11;
hour = hour % 12;
if (hour === 0)
hour = 12;
am_pm_locale_key = pm ?
'client_views_panel_timestamp_pm' :
'client_views_panel_timestamp_am';
msg.time_string = translateText(am_pm_locale_key, hour + ":" + msg.time.getMinutes().toString().lpad(2, "0") + ":" + msg.time.getSeconds().toString().lpad(2, "0"));
}
return msg;
} | [
"function",
"(",
"msg",
")",
"{",
"var",
"nick_hex",
",",
"time_difference",
",",
"message_words",
",",
"sb",
"=",
"this",
".",
"model",
".",
"get",
"(",
"'scrollback'",
")",
",",
"network",
"=",
"this",
".",
"model",
".",
"get",
"(",
"'network'",
")",
",",
"nick",
",",
"regexpStr",
",",
"prev_msg",
"=",
"sb",
"[",
"sb",
".",
"length",
"-",
"2",
"]",
",",
"hour",
",",
"pm",
",",
"am_pm_locale_key",
";",
"// Clone the msg object so we dont modify the original",
"msg",
"=",
"_",
".",
"clone",
"(",
"msg",
")",
";",
"// Defaults",
"msg",
".",
"css_classes",
"=",
"''",
";",
"msg",
".",
"nick_style",
"=",
"''",
";",
"msg",
".",
"is_highlight",
"=",
"false",
";",
"msg",
".",
"time_string",
"=",
"''",
";",
"// Nick + custom highlight detecting",
"nick",
"=",
"network",
"?",
"network",
".",
"get",
"(",
"'nick'",
")",
":",
"''",
";",
"if",
"(",
"nick",
"&&",
"msg",
".",
"nick",
".",
"localeCompare",
"(",
"nick",
")",
"!==",
"0",
")",
"{",
"// Build a list of all highlights and escape them for regex",
"regexpStr",
"=",
"_",
".",
"chain",
"(",
"(",
"_kiwi",
".",
"global",
".",
"settings",
".",
"get",
"(",
"'custom_highlights'",
")",
"||",
"''",
")",
".",
"split",
"(",
"/",
"[\\s,]+",
"/",
")",
")",
".",
"compact",
"(",
")",
".",
"concat",
"(",
"nick",
")",
".",
"map",
"(",
"_",
".",
"escapeRegExp",
")",
".",
"join",
"(",
"'|'",
")",
".",
"value",
"(",
")",
";",
"if",
"(",
"msg",
".",
"msg",
".",
"search",
"(",
"new",
"RegExp",
"(",
"'(\\\\b|\\\\W|^)('",
"+",
"regexpStr",
"+",
"')(\\\\b|\\\\W|$)'",
",",
"'i'",
")",
")",
">",
"-",
"1",
")",
"{",
"msg",
".",
"is_highlight",
"=",
"true",
";",
"msg",
".",
"css_classes",
"+=",
"' highlight'",
";",
"}",
"}",
"message_words",
"=",
"msg",
".",
"msg",
".",
"split",
"(",
"' '",
")",
";",
"message_words",
"=",
"_",
".",
"map",
"(",
"message_words",
",",
"function",
"(",
"word",
")",
"{",
"var",
"parsed_word",
";",
"parsed_word",
"=",
"this",
".",
"parseMessageUrls",
"(",
"word",
")",
";",
"if",
"(",
"typeof",
"parsed_word",
"===",
"'string'",
")",
"return",
"parsed_word",
";",
"parsed_word",
"=",
"this",
".",
"parseMessageChannels",
"(",
"word",
")",
";",
"if",
"(",
"typeof",
"parsed_word",
"===",
"'string'",
")",
"return",
"parsed_word",
";",
"parsed_word",
"=",
"this",
".",
"parseMessageNicks",
"(",
"word",
",",
"(",
"msg",
".",
"type",
"===",
"'privmsg'",
")",
")",
";",
"if",
"(",
"typeof",
"parsed_word",
"===",
"'string'",
")",
"return",
"parsed_word",
";",
"parsed_word",
"=",
"_",
".",
"escape",
"(",
"word",
")",
";",
"// Replace text emoticons with images",
"if",
"(",
"_kiwi",
".",
"global",
".",
"settings",
".",
"get",
"(",
"'show_emoticons'",
")",
")",
"{",
"parsed_word",
"=",
"emoticonFromText",
"(",
"parsed_word",
")",
";",
"}",
"return",
"parsed_word",
";",
"}",
",",
"this",
")",
";",
"msg",
".",
"unparsed_msg",
"=",
"msg",
".",
"msg",
";",
"msg",
".",
"msg",
"=",
"message_words",
".",
"join",
"(",
"' '",
")",
";",
"// Convert IRC formatting into HTML formatting",
"msg",
".",
"msg",
"=",
"formatIRCMsg",
"(",
"msg",
".",
"msg",
")",
";",
"// Add some style to the nick",
"msg",
".",
"nick_style",
"=",
"this",
".",
"getNickStyles",
"(",
"msg",
".",
"nick",
")",
".",
"asCssString",
"(",
")",
";",
"// Generate a hex string from the nick to be used as a CSS class name",
"nick_hex",
"=",
"''",
";",
"if",
"(",
"msg",
".",
"nick",
")",
"{",
"_",
".",
"map",
"(",
"msg",
".",
"nick",
".",
"split",
"(",
"''",
")",
",",
"function",
"(",
"char",
")",
"{",
"nick_hex",
"+=",
"char",
".",
"charCodeAt",
"(",
"0",
")",
".",
"toString",
"(",
"16",
")",
";",
"}",
")",
";",
"msg",
".",
"css_classes",
"+=",
"' nick_'",
"+",
"nick_hex",
";",
"}",
"if",
"(",
"prev_msg",
")",
"{",
"// Time difference between this message and the last (in minutes)",
"time_difference",
"=",
"(",
"msg",
".",
"time",
".",
"getTime",
"(",
")",
"-",
"prev_msg",
".",
"time",
".",
"getTime",
"(",
")",
")",
"/",
"1000",
"/",
"60",
";",
"if",
"(",
"prev_msg",
".",
"nick",
"===",
"msg",
".",
"nick",
"&&",
"time_difference",
"<",
"1",
")",
"{",
"msg",
".",
"css_classes",
"+=",
"' repeated_nick'",
";",
"}",
"}",
"// Build up and add the line",
"if",
"(",
"_kiwi",
".",
"global",
".",
"settings",
".",
"get",
"(",
"'use_24_hour_timestamps'",
")",
")",
"{",
"msg",
".",
"time_string",
"=",
"msg",
".",
"time",
".",
"getHours",
"(",
")",
".",
"toString",
"(",
")",
".",
"lpad",
"(",
"2",
",",
"\"0\"",
")",
"+",
"\":\"",
"+",
"msg",
".",
"time",
".",
"getMinutes",
"(",
")",
".",
"toString",
"(",
")",
".",
"lpad",
"(",
"2",
",",
"\"0\"",
")",
"+",
"\":\"",
"+",
"msg",
".",
"time",
".",
"getSeconds",
"(",
")",
".",
"toString",
"(",
")",
".",
"lpad",
"(",
"2",
",",
"\"0\"",
")",
";",
"}",
"else",
"{",
"hour",
"=",
"msg",
".",
"time",
".",
"getHours",
"(",
")",
";",
"pm",
"=",
"hour",
">",
"11",
";",
"hour",
"=",
"hour",
"%",
"12",
";",
"if",
"(",
"hour",
"===",
"0",
")",
"hour",
"=",
"12",
";",
"am_pm_locale_key",
"=",
"pm",
"?",
"'client_views_panel_timestamp_pm'",
":",
"'client_views_panel_timestamp_am'",
";",
"msg",
".",
"time_string",
"=",
"translateText",
"(",
"am_pm_locale_key",
",",
"hour",
"+",
"\":\"",
"+",
"msg",
".",
"time",
".",
"getMinutes",
"(",
")",
".",
"toString",
"(",
")",
".",
"lpad",
"(",
"2",
",",
"\"0\"",
")",
"+",
"\":\"",
"+",
"msg",
".",
"time",
".",
"getSeconds",
"(",
")",
".",
"toString",
"(",
")",
".",
"lpad",
"(",
"2",
",",
"\"0\"",
")",
")",
";",
"}",
"return",
"msg",
";",
"}"
] | Takes an IRC message object and parses it for displaying | [
"Takes",
"an",
"IRC",
"message",
"object",
"and",
"parses",
"it",
"for",
"displaying"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/views/channel.js#L298-L402 | |
22,265 | prawnsalad/KiwiIRC | client/src/views/channel.js | function (event) {
var $target = $(event.currentTarget),
nick,
members = this.model.get('members'),
member;
event.stopPropagation();
// Check this current element for a nick before resorting to the main message
// (eg. inline nicks has the nick on its own element within the message)
nick = $target.data('nick');
if (!nick) {
nick = $target.parent('.msg').data('message').nick;
}
// Make sure this nick is still in the channel
member = members ? members.getByNick(nick) : null;
if (!member) {
return;
}
_kiwi.global.events.emit('nick:select', {
target: $target,
member: member,
network: this.model.get('network'),
source: 'message',
$event: event
})
.then(_.bind(this.openUserMenuForNick, this, $target, member));
} | javascript | function (event) {
var $target = $(event.currentTarget),
nick,
members = this.model.get('members'),
member;
event.stopPropagation();
// Check this current element for a nick before resorting to the main message
// (eg. inline nicks has the nick on its own element within the message)
nick = $target.data('nick');
if (!nick) {
nick = $target.parent('.msg').data('message').nick;
}
// Make sure this nick is still in the channel
member = members ? members.getByNick(nick) : null;
if (!member) {
return;
}
_kiwi.global.events.emit('nick:select', {
target: $target,
member: member,
network: this.model.get('network'),
source: 'message',
$event: event
})
.then(_.bind(this.openUserMenuForNick, this, $target, member));
} | [
"function",
"(",
"event",
")",
"{",
"var",
"$target",
"=",
"$",
"(",
"event",
".",
"currentTarget",
")",
",",
"nick",
",",
"members",
"=",
"this",
".",
"model",
".",
"get",
"(",
"'members'",
")",
",",
"member",
";",
"event",
".",
"stopPropagation",
"(",
")",
";",
"// Check this current element for a nick before resorting to the main message",
"// (eg. inline nicks has the nick on its own element within the message)",
"nick",
"=",
"$target",
".",
"data",
"(",
"'nick'",
")",
";",
"if",
"(",
"!",
"nick",
")",
"{",
"nick",
"=",
"$target",
".",
"parent",
"(",
"'.msg'",
")",
".",
"data",
"(",
"'message'",
")",
".",
"nick",
";",
"}",
"// Make sure this nick is still in the channel",
"member",
"=",
"members",
"?",
"members",
".",
"getByNick",
"(",
"nick",
")",
":",
"null",
";",
"if",
"(",
"!",
"member",
")",
"{",
"return",
";",
"}",
"_kiwi",
".",
"global",
".",
"events",
".",
"emit",
"(",
"'nick:select'",
",",
"{",
"target",
":",
"$target",
",",
"member",
":",
"member",
",",
"network",
":",
"this",
".",
"model",
".",
"get",
"(",
"'network'",
")",
",",
"source",
":",
"'message'",
",",
"$event",
":",
"event",
"}",
")",
".",
"then",
"(",
"_",
".",
"bind",
"(",
"this",
".",
"openUserMenuForNick",
",",
"this",
",",
"$target",
",",
"member",
")",
")",
";",
"}"
] | Click on a nickname | [
"Click",
"on",
"a",
"nickname"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/views/channel.js#L426-L455 | |
22,266 | prawnsalad/KiwiIRC | client/src/views/channel.js | function (event) {
var nick_class;
// Find a valid class that this element has
_.each($(event.currentTarget).parent('.msg').attr('class').split(' '), function (css_class) {
if (css_class.match(/^nick_[a-z0-9]+/i)) {
nick_class = css_class;
}
});
// If no class was found..
if (!nick_class) return;
$('.'+nick_class).addClass('global_nick_highlight');
} | javascript | function (event) {
var nick_class;
// Find a valid class that this element has
_.each($(event.currentTarget).parent('.msg').attr('class').split(' '), function (css_class) {
if (css_class.match(/^nick_[a-z0-9]+/i)) {
nick_class = css_class;
}
});
// If no class was found..
if (!nick_class) return;
$('.'+nick_class).addClass('global_nick_highlight');
} | [
"function",
"(",
"event",
")",
"{",
"var",
"nick_class",
";",
"// Find a valid class that this element has",
"_",
".",
"each",
"(",
"$",
"(",
"event",
".",
"currentTarget",
")",
".",
"parent",
"(",
"'.msg'",
")",
".",
"attr",
"(",
"'class'",
")",
".",
"split",
"(",
"' '",
")",
",",
"function",
"(",
"css_class",
")",
"{",
"if",
"(",
"css_class",
".",
"match",
"(",
"/",
"^nick_[a-z0-9]+",
"/",
"i",
")",
")",
"{",
"nick_class",
"=",
"css_class",
";",
"}",
"}",
")",
";",
"// If no class was found..",
"if",
"(",
"!",
"nick_class",
")",
"return",
";",
"$",
"(",
"'.'",
"+",
"nick_class",
")",
".",
"addClass",
"(",
"'global_nick_highlight'",
")",
";",
"}"
] | Cursor hovers over a message | [
"Cursor",
"hovers",
"over",
"a",
"message"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/views/channel.js#L541-L555 | |
22,267 | prawnsalad/KiwiIRC | server/stats.js | statsTimer | function statsTimer(stat_name, data_start) {
var timer_started = new Date();
var timerStop = function timerStop(data_end) {
var time = (new Date()) - timer_started;
var data = shallowMergeObjects(data_start, data_end);
global.modules.emit('stat timer', {name: stat_name, time: time, data: data});
};
return {
stop: timerStop
};
} | javascript | function statsTimer(stat_name, data_start) {
var timer_started = new Date();
var timerStop = function timerStop(data_end) {
var time = (new Date()) - timer_started;
var data = shallowMergeObjects(data_start, data_end);
global.modules.emit('stat timer', {name: stat_name, time: time, data: data});
};
return {
stop: timerStop
};
} | [
"function",
"statsTimer",
"(",
"stat_name",
",",
"data_start",
")",
"{",
"var",
"timer_started",
"=",
"new",
"Date",
"(",
")",
";",
"var",
"timerStop",
"=",
"function",
"timerStop",
"(",
"data_end",
")",
"{",
"var",
"time",
"=",
"(",
"new",
"Date",
"(",
")",
")",
"-",
"timer_started",
";",
"var",
"data",
"=",
"shallowMergeObjects",
"(",
"data_start",
",",
"data_end",
")",
";",
"global",
".",
"modules",
".",
"emit",
"(",
"'stat timer'",
",",
"{",
"name",
":",
"stat_name",
",",
"time",
":",
"time",
",",
"data",
":",
"data",
"}",
")",
";",
"}",
";",
"return",
"{",
"stop",
":",
"timerStop",
"}",
";",
"}"
] | Send a timer value to the stats
Usage:
var timer = Stats.startTimer('stat_name', {some_data: 'value'});
// Do stuff
timer.stop({other_data: 'value'});
The object passed into .startTimer() and .stop(); are optional. If
given they will be shallow merged with .stop() overridding .startTimer() | [
"Send",
"a",
"timer",
"value",
"to",
"the",
"stats"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server/stats.js#L22-L35 |
22,268 | prawnsalad/KiwiIRC | server_modules/control.js | SocketClient | function SocketClient (socket) {
var that = this;
this.socket = socket;
this.socket_closing = false;
this.remoteAddress = this.socket.remoteAddress;
winston.info('Control connection from %s opened', this.socket.remoteAddress);
this.bindEvents();
socket.write("\nHello, you are connected to the Kiwi server :)\n\n");
this.control_interface = new ControlInterface(socket);
_.each(socket_commands, function(fn, command_name) {
that.control_interface.addCommand(command_name, fn.bind(that));
});
} | javascript | function SocketClient (socket) {
var that = this;
this.socket = socket;
this.socket_closing = false;
this.remoteAddress = this.socket.remoteAddress;
winston.info('Control connection from %s opened', this.socket.remoteAddress);
this.bindEvents();
socket.write("\nHello, you are connected to the Kiwi server :)\n\n");
this.control_interface = new ControlInterface(socket);
_.each(socket_commands, function(fn, command_name) {
that.control_interface.addCommand(command_name, fn.bind(that));
});
} | [
"function",
"SocketClient",
"(",
"socket",
")",
"{",
"var",
"that",
"=",
"this",
";",
"this",
".",
"socket",
"=",
"socket",
";",
"this",
".",
"socket_closing",
"=",
"false",
";",
"this",
".",
"remoteAddress",
"=",
"this",
".",
"socket",
".",
"remoteAddress",
";",
"winston",
".",
"info",
"(",
"'Control connection from %s opened'",
",",
"this",
".",
"socket",
".",
"remoteAddress",
")",
";",
"this",
".",
"bindEvents",
"(",
")",
";",
"socket",
".",
"write",
"(",
"\"\\nHello, you are connected to the Kiwi server :)\\n\\n\"",
")",
";",
"this",
".",
"control_interface",
"=",
"new",
"ControlInterface",
"(",
"socket",
")",
";",
"_",
".",
"each",
"(",
"socket_commands",
",",
"function",
"(",
"fn",
",",
"command_name",
")",
"{",
"that",
".",
"control_interface",
".",
"addCommand",
"(",
"command_name",
",",
"fn",
".",
"bind",
"(",
"that",
")",
")",
";",
"}",
")",
";",
"}"
] | The socket client | [
"The",
"socket",
"client"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/server_modules/control.js#L19-L36 |
22,269 | prawnsalad/KiwiIRC | client/src/models/applet.js | function (applet_object, applet_name) {
if (typeof applet_object === 'object') {
// Make sure this is a valid Applet
if (applet_object.get || applet_object.extend) {
// Try find a title for the applet
this.set('title', applet_object.get('title') || _kiwi.global.i18n.translate('client_models_applet_unknown').fetch());
// Update the tabs title if the applet changes it
applet_object.bind('change:title', function (obj, new_value) {
this.set('title', new_value);
}, this);
// If this applet has a UI, add it now
this.view.$el.html('');
if (applet_object.view) {
this.view.$el.append(applet_object.view.$el);
}
// Keep a reference to this applet
this.loaded_applet = applet_object;
this.loaded_applet.trigger('applet_loaded');
}
} else if (typeof applet_object === 'string') {
// Treat this as a URL to an applet script and load it
this.loadFromUrl(applet_object, applet_name);
}
return this;
} | javascript | function (applet_object, applet_name) {
if (typeof applet_object === 'object') {
// Make sure this is a valid Applet
if (applet_object.get || applet_object.extend) {
// Try find a title for the applet
this.set('title', applet_object.get('title') || _kiwi.global.i18n.translate('client_models_applet_unknown').fetch());
// Update the tabs title if the applet changes it
applet_object.bind('change:title', function (obj, new_value) {
this.set('title', new_value);
}, this);
// If this applet has a UI, add it now
this.view.$el.html('');
if (applet_object.view) {
this.view.$el.append(applet_object.view.$el);
}
// Keep a reference to this applet
this.loaded_applet = applet_object;
this.loaded_applet.trigger('applet_loaded');
}
} else if (typeof applet_object === 'string') {
// Treat this as a URL to an applet script and load it
this.loadFromUrl(applet_object, applet_name);
}
return this;
} | [
"function",
"(",
"applet_object",
",",
"applet_name",
")",
"{",
"if",
"(",
"typeof",
"applet_object",
"===",
"'object'",
")",
"{",
"// Make sure this is a valid Applet\r",
"if",
"(",
"applet_object",
".",
"get",
"||",
"applet_object",
".",
"extend",
")",
"{",
"// Try find a title for the applet\r",
"this",
".",
"set",
"(",
"'title'",
",",
"applet_object",
".",
"get",
"(",
"'title'",
")",
"||",
"_kiwi",
".",
"global",
".",
"i18n",
".",
"translate",
"(",
"'client_models_applet_unknown'",
")",
".",
"fetch",
"(",
")",
")",
";",
"// Update the tabs title if the applet changes it\r",
"applet_object",
".",
"bind",
"(",
"'change:title'",
",",
"function",
"(",
"obj",
",",
"new_value",
")",
"{",
"this",
".",
"set",
"(",
"'title'",
",",
"new_value",
")",
";",
"}",
",",
"this",
")",
";",
"// If this applet has a UI, add it now\r",
"this",
".",
"view",
".",
"$el",
".",
"html",
"(",
"''",
")",
";",
"if",
"(",
"applet_object",
".",
"view",
")",
"{",
"this",
".",
"view",
".",
"$el",
".",
"append",
"(",
"applet_object",
".",
"view",
".",
"$el",
")",
";",
"}",
"// Keep a reference to this applet\r",
"this",
".",
"loaded_applet",
"=",
"applet_object",
";",
"this",
".",
"loaded_applet",
".",
"trigger",
"(",
"'applet_loaded'",
")",
";",
"}",
"}",
"else",
"if",
"(",
"typeof",
"applet_object",
"===",
"'string'",
")",
"{",
"// Treat this as a URL to an applet script and load it\r",
"this",
".",
"loadFromUrl",
"(",
"applet_object",
",",
"applet_name",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Load an applet within this panel | [
"Load",
"an",
"applet",
"within",
"this",
"panel"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/models/applet.js#L17-L48 | |
22,270 | prawnsalad/KiwiIRC | client/src/models/applet.js | function (applet_name) {
// See if we have an instance loaded already
var applet = _.find(_kiwi.app.panels('applets'), function(panel) {
// Ignore if it's not an applet
if (!panel.isApplet()) return;
// Ignore if it doesn't have an applet loaded
if (!panel.loaded_applet) return;
if (panel.loaded_applet.get('_applet_name') === applet_name) {
return true;
}
});
if (applet) return applet;
// If we didn't find an instance, load a new one up
return this.load(applet_name);
} | javascript | function (applet_name) {
// See if we have an instance loaded already
var applet = _.find(_kiwi.app.panels('applets'), function(panel) {
// Ignore if it's not an applet
if (!panel.isApplet()) return;
// Ignore if it doesn't have an applet loaded
if (!panel.loaded_applet) return;
if (panel.loaded_applet.get('_applet_name') === applet_name) {
return true;
}
});
if (applet) return applet;
// If we didn't find an instance, load a new one up
return this.load(applet_name);
} | [
"function",
"(",
"applet_name",
")",
"{",
"// See if we have an instance loaded already\r",
"var",
"applet",
"=",
"_",
".",
"find",
"(",
"_kiwi",
".",
"app",
".",
"panels",
"(",
"'applets'",
")",
",",
"function",
"(",
"panel",
")",
"{",
"// Ignore if it's not an applet\r",
"if",
"(",
"!",
"panel",
".",
"isApplet",
"(",
")",
")",
"return",
";",
"// Ignore if it doesn't have an applet loaded\r",
"if",
"(",
"!",
"panel",
".",
"loaded_applet",
")",
"return",
";",
"if",
"(",
"panel",
".",
"loaded_applet",
".",
"get",
"(",
"'_applet_name'",
")",
"===",
"applet_name",
")",
"{",
"return",
"true",
";",
"}",
"}",
")",
";",
"if",
"(",
"applet",
")",
"return",
"applet",
";",
"// If we didn't find an instance, load a new one up\r",
"return",
"this",
".",
"load",
"(",
"applet_name",
")",
";",
"}"
] | Load an applet type once only. If it already exists, return that | [
"Load",
"an",
"applet",
"type",
"once",
"only",
".",
"If",
"it",
"already",
"exists",
"return",
"that"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/models/applet.js#L91-L111 | |
22,271 | prawnsalad/KiwiIRC | client/src/helpers/plugininterface.js | callListeners | function callListeners(listeners) {
var current_event_idx = -1;
// Make sure we have some data to pass to the listeners
event_data = event_data || undefined;
// If no bound listeners for this event, leave now
if (listeners.length === 0) {
emitComplete();
return;
}
// Call the next listener in our array
function nextListener() {
var listener, event_obj;
// We want the next listener
current_event_idx++;
// If we've ran out of listeners end this emit call
if (!listeners[current_event_idx]) {
emitComplete();
return;
}
// Object the listener ammends to tell us what it's going to do
event_obj = {
// If changed to true, expect this listener is going to callback
wait: false,
// If wait is true, this callback must be called to continue running listeners
callback: function () {
// Invalidate this callback incase a listener decides to call it again
event_obj.callback = undefined;
nextListener.apply(that);
},
// Prevents the default 'done' functions from executing
preventDefault: function () {
prevented = true;
}
};
listener = listeners[current_event_idx];
listener[1].call(listener[2] || that, event_obj, event_data);
// If the listener hasn't signalled it's going to wait, proceed to next listener
if (!event_obj.wait) {
// Invalidate the callback just incase a listener decides to call it anyway
event_obj.callback = undefined;
nextListener();
}
}
nextListener();
} | javascript | function callListeners(listeners) {
var current_event_idx = -1;
// Make sure we have some data to pass to the listeners
event_data = event_data || undefined;
// If no bound listeners for this event, leave now
if (listeners.length === 0) {
emitComplete();
return;
}
// Call the next listener in our array
function nextListener() {
var listener, event_obj;
// We want the next listener
current_event_idx++;
// If we've ran out of listeners end this emit call
if (!listeners[current_event_idx]) {
emitComplete();
return;
}
// Object the listener ammends to tell us what it's going to do
event_obj = {
// If changed to true, expect this listener is going to callback
wait: false,
// If wait is true, this callback must be called to continue running listeners
callback: function () {
// Invalidate this callback incase a listener decides to call it again
event_obj.callback = undefined;
nextListener.apply(that);
},
// Prevents the default 'done' functions from executing
preventDefault: function () {
prevented = true;
}
};
listener = listeners[current_event_idx];
listener[1].call(listener[2] || that, event_obj, event_data);
// If the listener hasn't signalled it's going to wait, proceed to next listener
if (!event_obj.wait) {
// Invalidate the callback just incase a listener decides to call it anyway
event_obj.callback = undefined;
nextListener();
}
}
nextListener();
} | [
"function",
"callListeners",
"(",
"listeners",
")",
"{",
"var",
"current_event_idx",
"=",
"-",
"1",
";",
"// Make sure we have some data to pass to the listeners",
"event_data",
"=",
"event_data",
"||",
"undefined",
";",
"// If no bound listeners for this event, leave now",
"if",
"(",
"listeners",
".",
"length",
"===",
"0",
")",
"{",
"emitComplete",
"(",
")",
";",
"return",
";",
"}",
"// Call the next listener in our array",
"function",
"nextListener",
"(",
")",
"{",
"var",
"listener",
",",
"event_obj",
";",
"// We want the next listener",
"current_event_idx",
"++",
";",
"// If we've ran out of listeners end this emit call",
"if",
"(",
"!",
"listeners",
"[",
"current_event_idx",
"]",
")",
"{",
"emitComplete",
"(",
")",
";",
"return",
";",
"}",
"// Object the listener ammends to tell us what it's going to do",
"event_obj",
"=",
"{",
"// If changed to true, expect this listener is going to callback",
"wait",
":",
"false",
",",
"// If wait is true, this callback must be called to continue running listeners",
"callback",
":",
"function",
"(",
")",
"{",
"// Invalidate this callback incase a listener decides to call it again",
"event_obj",
".",
"callback",
"=",
"undefined",
";",
"nextListener",
".",
"apply",
"(",
"that",
")",
";",
"}",
",",
"// Prevents the default 'done' functions from executing",
"preventDefault",
":",
"function",
"(",
")",
"{",
"prevented",
"=",
"true",
";",
"}",
"}",
";",
"listener",
"=",
"listeners",
"[",
"current_event_idx",
"]",
";",
"listener",
"[",
"1",
"]",
".",
"call",
"(",
"listener",
"[",
"2",
"]",
"||",
"that",
",",
"event_obj",
",",
"event_data",
")",
";",
"// If the listener hasn't signalled it's going to wait, proceed to next listener",
"if",
"(",
"!",
"event_obj",
".",
"wait",
")",
"{",
"// Invalidate the callback just incase a listener decides to call it anyway",
"event_obj",
".",
"callback",
"=",
"undefined",
";",
"nextListener",
"(",
")",
";",
"}",
"}",
"nextListener",
"(",
")",
";",
"}"
] | Emit this event to an array of listeners | [
"Emit",
"this",
"event",
"to",
"an",
"array",
"of",
"listeners"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/helpers/plugininterface.js#L140-L199 |
22,272 | prawnsalad/KiwiIRC | client/src/models/network.js | function (channels) {
var that = this,
panels = [];
// Multiple channels may come as comma-delimited
if (typeof channels === 'string') {
channels = channels.split(',');
}
$.each(channels, function (index, channel_name_key) {
// We may have a channel key so split it off
var spli = channel_name_key.trim().split(' '),
channel_name = spli[0],
channel_key = spli[1] || '';
// Trim any whitespace off the name
channel_name = channel_name.trim();
// Add channel_prefix in front of the first channel if missing
if (that.get('channel_prefix').indexOf(channel_name[0]) === -1) {
// Could be many prefixes but '#' is highly likely the required one
channel_name = '#' + channel_name;
}
// Check if we have the panel already. If not, create it
channel = that.panels.getByName(channel_name);
if (!channel) {
channel = new _kiwi.model.Channel({name: channel_name, network: that, key: channel_key||undefined});
that.panels.add(channel);
}
panels.push(channel);
that.gateway.join(channel_name, channel_key);
});
return panels;
} | javascript | function (channels) {
var that = this,
panels = [];
// Multiple channels may come as comma-delimited
if (typeof channels === 'string') {
channels = channels.split(',');
}
$.each(channels, function (index, channel_name_key) {
// We may have a channel key so split it off
var spli = channel_name_key.trim().split(' '),
channel_name = spli[0],
channel_key = spli[1] || '';
// Trim any whitespace off the name
channel_name = channel_name.trim();
// Add channel_prefix in front of the first channel if missing
if (that.get('channel_prefix').indexOf(channel_name[0]) === -1) {
// Could be many prefixes but '#' is highly likely the required one
channel_name = '#' + channel_name;
}
// Check if we have the panel already. If not, create it
channel = that.panels.getByName(channel_name);
if (!channel) {
channel = new _kiwi.model.Channel({name: channel_name, network: that, key: channel_key||undefined});
that.panels.add(channel);
}
panels.push(channel);
that.gateway.join(channel_name, channel_key);
});
return panels;
} | [
"function",
"(",
"channels",
")",
"{",
"var",
"that",
"=",
"this",
",",
"panels",
"=",
"[",
"]",
";",
"// Multiple channels may come as comma-delimited",
"if",
"(",
"typeof",
"channels",
"===",
"'string'",
")",
"{",
"channels",
"=",
"channels",
".",
"split",
"(",
"','",
")",
";",
"}",
"$",
".",
"each",
"(",
"channels",
",",
"function",
"(",
"index",
",",
"channel_name_key",
")",
"{",
"// We may have a channel key so split it off",
"var",
"spli",
"=",
"channel_name_key",
".",
"trim",
"(",
")",
".",
"split",
"(",
"' '",
")",
",",
"channel_name",
"=",
"spli",
"[",
"0",
"]",
",",
"channel_key",
"=",
"spli",
"[",
"1",
"]",
"||",
"''",
";",
"// Trim any whitespace off the name",
"channel_name",
"=",
"channel_name",
".",
"trim",
"(",
")",
";",
"// Add channel_prefix in front of the first channel if missing",
"if",
"(",
"that",
".",
"get",
"(",
"'channel_prefix'",
")",
".",
"indexOf",
"(",
"channel_name",
"[",
"0",
"]",
")",
"===",
"-",
"1",
")",
"{",
"// Could be many prefixes but '#' is highly likely the required one",
"channel_name",
"=",
"'#'",
"+",
"channel_name",
";",
"}",
"// Check if we have the panel already. If not, create it",
"channel",
"=",
"that",
".",
"panels",
".",
"getByName",
"(",
"channel_name",
")",
";",
"if",
"(",
"!",
"channel",
")",
"{",
"channel",
"=",
"new",
"_kiwi",
".",
"model",
".",
"Channel",
"(",
"{",
"name",
":",
"channel_name",
",",
"network",
":",
"that",
",",
"key",
":",
"channel_key",
"||",
"undefined",
"}",
")",
";",
"that",
".",
"panels",
".",
"add",
"(",
"channel",
")",
";",
"}",
"panels",
".",
"push",
"(",
"channel",
")",
";",
"that",
".",
"gateway",
".",
"join",
"(",
"channel_name",
",",
"channel_key",
")",
";",
"}",
")",
";",
"return",
"panels",
";",
"}"
] | Create panels and join the channel
This will not wait for the join event to create a panel. This
increases responsiveness in case of network lag | [
"Create",
"panels",
"and",
"join",
"the",
"channel",
"This",
"will",
"not",
"wait",
"for",
"the",
"join",
"event",
"to",
"create",
"a",
"panel",
".",
"This",
"increases",
"responsiveness",
"in",
"case",
"of",
"network",
"lag"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/models/network.js#L159-L197 | |
22,273 | prawnsalad/KiwiIRC | client/src/models/network.js | function() {
var that = this;
this.panels.forEach(function(panel) {
if (!panel.isChannel())
return;
that.gateway.join(panel.get('name'), panel.get('key') || undefined);
});
} | javascript | function() {
var that = this;
this.panels.forEach(function(panel) {
if (!panel.isChannel())
return;
that.gateway.join(panel.get('name'), panel.get('key') || undefined);
});
} | [
"function",
"(",
")",
"{",
"var",
"that",
"=",
"this",
";",
"this",
".",
"panels",
".",
"forEach",
"(",
"function",
"(",
"panel",
")",
"{",
"if",
"(",
"!",
"panel",
".",
"isChannel",
"(",
")",
")",
"return",
";",
"that",
".",
"gateway",
".",
"join",
"(",
"panel",
".",
"get",
"(",
"'name'",
")",
",",
"panel",
".",
"get",
"(",
"'key'",
")",
"||",
"undefined",
")",
";",
"}",
")",
";",
"}"
] | Join all the open channels we have open
Reconnecting to a network would typically call this. | [
"Join",
"all",
"the",
"open",
"channels",
"we",
"have",
"open",
"Reconnecting",
"to",
"a",
"network",
"would",
"typically",
"call",
"this",
"."
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/models/network.js#L204-L213 | |
22,274 | prawnsalad/KiwiIRC | client/src/models/network.js | function (mask) {
var found_mask;
if (typeof mask === "object") {
mask = (mask.nick||'*')+'!'+(mask.ident||'*')+'@'+(mask.hostname||'*');
} else if (typeof mask === "string") {
mask = toUserMask(mask);
}
found_mask = this.ignore_list.find(function(entry) {
return entry.get('regex').test(mask);
});
return !!found_mask;
} | javascript | function (mask) {
var found_mask;
if (typeof mask === "object") {
mask = (mask.nick||'*')+'!'+(mask.ident||'*')+'@'+(mask.hostname||'*');
} else if (typeof mask === "string") {
mask = toUserMask(mask);
}
found_mask = this.ignore_list.find(function(entry) {
return entry.get('regex').test(mask);
});
return !!found_mask;
} | [
"function",
"(",
"mask",
")",
"{",
"var",
"found_mask",
";",
"if",
"(",
"typeof",
"mask",
"===",
"\"object\"",
")",
"{",
"mask",
"=",
"(",
"mask",
".",
"nick",
"||",
"'*'",
")",
"+",
"'!'",
"+",
"(",
"mask",
".",
"ident",
"||",
"'*'",
")",
"+",
"'@'",
"+",
"(",
"mask",
".",
"hostname",
"||",
"'*'",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"mask",
"===",
"\"string\"",
")",
"{",
"mask",
"=",
"toUserMask",
"(",
"mask",
")",
";",
"}",
"found_mask",
"=",
"this",
".",
"ignore_list",
".",
"find",
"(",
"function",
"(",
"entry",
")",
"{",
"return",
"entry",
".",
"get",
"(",
"'regex'",
")",
".",
"test",
"(",
"mask",
")",
";",
"}",
")",
";",
"return",
"!",
"!",
"found_mask",
";",
"}"
] | Check if a user is ignored. Accepts an object with nick, ident and hostname OR a string. | [
"Check",
"if",
"a",
"user",
"is",
"ignored",
".",
"Accepts",
"an",
"object",
"with",
"nick",
"ident",
"and",
"hostname",
"OR",
"a",
"string",
"."
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/models/network.js#L224-L238 | |
22,275 | prawnsalad/KiwiIRC | client/src/models/network.js | function (nick) {
var that = this,
query;
// Check if we have the panel already. If not, create it
query = that.panels.getByName(nick);
if (!query) {
query = new _kiwi.model.Query({name: nick, network: this});
that.panels.add(query);
}
// In all cases, show the demanded query
query.view.show();
return query;
} | javascript | function (nick) {
var that = this,
query;
// Check if we have the panel already. If not, create it
query = that.panels.getByName(nick);
if (!query) {
query = new _kiwi.model.Query({name: nick, network: this});
that.panels.add(query);
}
// In all cases, show the demanded query
query.view.show();
return query;
} | [
"function",
"(",
"nick",
")",
"{",
"var",
"that",
"=",
"this",
",",
"query",
";",
"// Check if we have the panel already. If not, create it",
"query",
"=",
"that",
".",
"panels",
".",
"getByName",
"(",
"nick",
")",
";",
"if",
"(",
"!",
"query",
")",
"{",
"query",
"=",
"new",
"_kiwi",
".",
"model",
".",
"Query",
"(",
"{",
"name",
":",
"nick",
",",
"network",
":",
"this",
"}",
")",
";",
"that",
".",
"panels",
".",
"add",
"(",
"query",
")",
";",
"}",
"// In all cases, show the demanded query",
"query",
".",
"view",
".",
"show",
"(",
")",
";",
"return",
"query",
";",
"}"
] | Create a new query panel | [
"Create",
"a",
"new",
"query",
"panel"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/models/network.js#L241-L256 | |
22,276 | prawnsalad/KiwiIRC | client/src/models/network.js | friendlyModeString | function friendlyModeString (event_modes, alt_target) {
var modes = {}, return_string;
// If no default given, use the main event info
if (!event_modes) {
event_modes = event.modes;
alt_target = event.target;
}
// Reformat the mode object to make it easier to work with
_.each(event_modes, function (mode){
var param = mode.param || alt_target || '';
// Make sure we have some modes for this param
if (!modes[param]) {
modes[param] = {'+':'', '-':''};
}
modes[param][mode.mode[0]] += mode.mode.substr(1);
});
// Put the string together from each mode
return_string = [];
_.each(modes, function (modeset, param) {
var str = '';
if (modeset['+']) str += '+' + modeset['+'];
if (modeset['-']) str += '-' + modeset['-'];
return_string.push(str + ' ' + param);
});
return_string = return_string.join(', ');
return return_string;
} | javascript | function friendlyModeString (event_modes, alt_target) {
var modes = {}, return_string;
// If no default given, use the main event info
if (!event_modes) {
event_modes = event.modes;
alt_target = event.target;
}
// Reformat the mode object to make it easier to work with
_.each(event_modes, function (mode){
var param = mode.param || alt_target || '';
// Make sure we have some modes for this param
if (!modes[param]) {
modes[param] = {'+':'', '-':''};
}
modes[param][mode.mode[0]] += mode.mode.substr(1);
});
// Put the string together from each mode
return_string = [];
_.each(modes, function (modeset, param) {
var str = '';
if (modeset['+']) str += '+' + modeset['+'];
if (modeset['-']) str += '-' + modeset['-'];
return_string.push(str + ' ' + param);
});
return_string = return_string.join(', ');
return return_string;
} | [
"function",
"friendlyModeString",
"(",
"event_modes",
",",
"alt_target",
")",
"{",
"var",
"modes",
"=",
"{",
"}",
",",
"return_string",
";",
"// If no default given, use the main event info",
"if",
"(",
"!",
"event_modes",
")",
"{",
"event_modes",
"=",
"event",
".",
"modes",
";",
"alt_target",
"=",
"event",
".",
"target",
";",
"}",
"// Reformat the mode object to make it easier to work with",
"_",
".",
"each",
"(",
"event_modes",
",",
"function",
"(",
"mode",
")",
"{",
"var",
"param",
"=",
"mode",
".",
"param",
"||",
"alt_target",
"||",
"''",
";",
"// Make sure we have some modes for this param",
"if",
"(",
"!",
"modes",
"[",
"param",
"]",
")",
"{",
"modes",
"[",
"param",
"]",
"=",
"{",
"'+'",
":",
"''",
",",
"'-'",
":",
"''",
"}",
";",
"}",
"modes",
"[",
"param",
"]",
"[",
"mode",
".",
"mode",
"[",
"0",
"]",
"]",
"+=",
"mode",
".",
"mode",
".",
"substr",
"(",
"1",
")",
";",
"}",
")",
";",
"// Put the string together from each mode",
"return_string",
"=",
"[",
"]",
";",
"_",
".",
"each",
"(",
"modes",
",",
"function",
"(",
"modeset",
",",
"param",
")",
"{",
"var",
"str",
"=",
"''",
";",
"if",
"(",
"modeset",
"[",
"'+'",
"]",
")",
"str",
"+=",
"'+'",
"+",
"modeset",
"[",
"'+'",
"]",
";",
"if",
"(",
"modeset",
"[",
"'-'",
"]",
")",
"str",
"+=",
"'-'",
"+",
"modeset",
"[",
"'-'",
"]",
";",
"return_string",
".",
"push",
"(",
"str",
"+",
"' '",
"+",
"param",
")",
";",
"}",
")",
";",
"return_string",
"=",
"return_string",
".",
"join",
"(",
"', '",
")",
";",
"return",
"return_string",
";",
"}"
] | Build a nicely formatted string to be displayed to a regular human | [
"Build",
"a",
"nicely",
"formatted",
"string",
"to",
"be",
"displayed",
"to",
"a",
"regular",
"human"
] | e54d8e5b98f15a903f915335f985d6dc56011fcf | https://github.com/prawnsalad/KiwiIRC/blob/e54d8e5b98f15a903f915335f985d6dc56011fcf/client/src/models/network.js#L681-L713 |
22,277 | shannonmoeller/handlebars-layouts | index.js | layouts | function layouts(handlebars) {
var helpers = {
/**
* @method extend
* @param {String} name
* @param {?Object} customContext
* @param {Object} options
* @param {Function(Object)} options.fn
* @param {Object} options.hash
* @return {String} Rendered partial.
*/
extend: function (name, customContext, options) {
// Make `customContext` optional
if (arguments.length < 3) {
options = customContext;
customContext = null;
}
options = options || {};
var fn = options.fn || noop,
context = mixin({}, this, customContext, options.hash),
data = handlebars.createFrame(options.data),
template = handlebars.partials[name];
// Partial template required
if (template == null) {
throw new Error('Missing partial: \'' + name + '\'');
}
// Compile partial, if needed
if (typeof template !== 'function') {
template = handlebars.compile(template);
}
// Add overrides to stack
getStack(context).push(fn);
// Render partial
return template(context, { data: data });
},
/**
* @method embed
* @param {String} name
* @param {?Object} customContext
* @param {Object} options
* @param {Function(Object)} options.fn
* @param {Object} options.hash
* @return {String} Rendered partial.
*/
embed: function () {
var context = mixin({}, this || {});
// Reset context
context.$$layoutStack = null;
context.$$layoutActions = null;
// Extend
return helpers.extend.apply(context, arguments);
},
/**
* @method block
* @param {String} name
* @param {Object} options
* @param {Function(Object)} options.fn
* @return {String} Modified block content.
*/
block: function (name, options) {
options = options || {};
var fn = options.fn || noop,
data = handlebars.createFrame(options.data),
context = this || {};
applyStack(context);
return getActionsByName(context, name).reduce(
applyAction.bind(context),
fn(context, { data: data })
);
},
/**
* @method content
* @param {String} name
* @param {Object} options
* @param {Function(Object)} options.fn
* @param {Object} options.hash
* @param {String} options.hash.mode
* @return {String} Always empty.
*/
content: function (name, options) {
options = options || {};
var fn = options.fn,
data = handlebars.createFrame(options.data),
hash = options.hash || {},
mode = hash.mode || 'replace',
context = this || {};
applyStack(context);
// Getter
if (!fn) {
return name in getActions(context);
}
// Setter
getActionsByName(context, name).push({
options: { data: data },
mode: mode.toLowerCase(),
fn: fn
});
}
};
return helpers;
} | javascript | function layouts(handlebars) {
var helpers = {
/**
* @method extend
* @param {String} name
* @param {?Object} customContext
* @param {Object} options
* @param {Function(Object)} options.fn
* @param {Object} options.hash
* @return {String} Rendered partial.
*/
extend: function (name, customContext, options) {
// Make `customContext` optional
if (arguments.length < 3) {
options = customContext;
customContext = null;
}
options = options || {};
var fn = options.fn || noop,
context = mixin({}, this, customContext, options.hash),
data = handlebars.createFrame(options.data),
template = handlebars.partials[name];
// Partial template required
if (template == null) {
throw new Error('Missing partial: \'' + name + '\'');
}
// Compile partial, if needed
if (typeof template !== 'function') {
template = handlebars.compile(template);
}
// Add overrides to stack
getStack(context).push(fn);
// Render partial
return template(context, { data: data });
},
/**
* @method embed
* @param {String} name
* @param {?Object} customContext
* @param {Object} options
* @param {Function(Object)} options.fn
* @param {Object} options.hash
* @return {String} Rendered partial.
*/
embed: function () {
var context = mixin({}, this || {});
// Reset context
context.$$layoutStack = null;
context.$$layoutActions = null;
// Extend
return helpers.extend.apply(context, arguments);
},
/**
* @method block
* @param {String} name
* @param {Object} options
* @param {Function(Object)} options.fn
* @return {String} Modified block content.
*/
block: function (name, options) {
options = options || {};
var fn = options.fn || noop,
data = handlebars.createFrame(options.data),
context = this || {};
applyStack(context);
return getActionsByName(context, name).reduce(
applyAction.bind(context),
fn(context, { data: data })
);
},
/**
* @method content
* @param {String} name
* @param {Object} options
* @param {Function(Object)} options.fn
* @param {Object} options.hash
* @param {String} options.hash.mode
* @return {String} Always empty.
*/
content: function (name, options) {
options = options || {};
var fn = options.fn,
data = handlebars.createFrame(options.data),
hash = options.hash || {},
mode = hash.mode || 'replace',
context = this || {};
applyStack(context);
// Getter
if (!fn) {
return name in getActions(context);
}
// Setter
getActionsByName(context, name).push({
options: { data: data },
mode: mode.toLowerCase(),
fn: fn
});
}
};
return helpers;
} | [
"function",
"layouts",
"(",
"handlebars",
")",
"{",
"var",
"helpers",
"=",
"{",
"/**\n\t\t * @method extend\n\t\t * @param {String} name\n\t\t * @param {?Object} customContext\n\t\t * @param {Object} options\n\t\t * @param {Function(Object)} options.fn\n\t\t * @param {Object} options.hash\n\t\t * @return {String} Rendered partial.\n\t\t */",
"extend",
":",
"function",
"(",
"name",
",",
"customContext",
",",
"options",
")",
"{",
"// Make `customContext` optional",
"if",
"(",
"arguments",
".",
"length",
"<",
"3",
")",
"{",
"options",
"=",
"customContext",
";",
"customContext",
"=",
"null",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"fn",
"=",
"options",
".",
"fn",
"||",
"noop",
",",
"context",
"=",
"mixin",
"(",
"{",
"}",
",",
"this",
",",
"customContext",
",",
"options",
".",
"hash",
")",
",",
"data",
"=",
"handlebars",
".",
"createFrame",
"(",
"options",
".",
"data",
")",
",",
"template",
"=",
"handlebars",
".",
"partials",
"[",
"name",
"]",
";",
"// Partial template required",
"if",
"(",
"template",
"==",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing partial: \\''",
"+",
"name",
"+",
"'\\''",
")",
";",
"}",
"// Compile partial, if needed",
"if",
"(",
"typeof",
"template",
"!==",
"'function'",
")",
"{",
"template",
"=",
"handlebars",
".",
"compile",
"(",
"template",
")",
";",
"}",
"// Add overrides to stack",
"getStack",
"(",
"context",
")",
".",
"push",
"(",
"fn",
")",
";",
"// Render partial",
"return",
"template",
"(",
"context",
",",
"{",
"data",
":",
"data",
"}",
")",
";",
"}",
",",
"/**\n\t\t * @method embed\n\t\t * @param {String} name\n\t\t * @param {?Object} customContext\n\t\t * @param {Object} options\n\t\t * @param {Function(Object)} options.fn\n\t\t * @param {Object} options.hash\n\t\t * @return {String} Rendered partial.\n\t\t */",
"embed",
":",
"function",
"(",
")",
"{",
"var",
"context",
"=",
"mixin",
"(",
"{",
"}",
",",
"this",
"||",
"{",
"}",
")",
";",
"// Reset context",
"context",
".",
"$$layoutStack",
"=",
"null",
";",
"context",
".",
"$$layoutActions",
"=",
"null",
";",
"// Extend",
"return",
"helpers",
".",
"extend",
".",
"apply",
"(",
"context",
",",
"arguments",
")",
";",
"}",
",",
"/**\n\t\t * @method block\n\t\t * @param {String} name\n\t\t * @param {Object} options\n\t\t * @param {Function(Object)} options.fn\n\t\t * @return {String} Modified block content.\n\t\t */",
"block",
":",
"function",
"(",
"name",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"fn",
"=",
"options",
".",
"fn",
"||",
"noop",
",",
"data",
"=",
"handlebars",
".",
"createFrame",
"(",
"options",
".",
"data",
")",
",",
"context",
"=",
"this",
"||",
"{",
"}",
";",
"applyStack",
"(",
"context",
")",
";",
"return",
"getActionsByName",
"(",
"context",
",",
"name",
")",
".",
"reduce",
"(",
"applyAction",
".",
"bind",
"(",
"context",
")",
",",
"fn",
"(",
"context",
",",
"{",
"data",
":",
"data",
"}",
")",
")",
";",
"}",
",",
"/**\n\t\t * @method content\n\t\t * @param {String} name\n\t\t * @param {Object} options\n\t\t * @param {Function(Object)} options.fn\n\t\t * @param {Object} options.hash\n\t\t * @param {String} options.hash.mode\n\t\t * @return {String} Always empty.\n\t\t */",
"content",
":",
"function",
"(",
"name",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"fn",
"=",
"options",
".",
"fn",
",",
"data",
"=",
"handlebars",
".",
"createFrame",
"(",
"options",
".",
"data",
")",
",",
"hash",
"=",
"options",
".",
"hash",
"||",
"{",
"}",
",",
"mode",
"=",
"hash",
".",
"mode",
"||",
"'replace'",
",",
"context",
"=",
"this",
"||",
"{",
"}",
";",
"applyStack",
"(",
"context",
")",
";",
"// Getter",
"if",
"(",
"!",
"fn",
")",
"{",
"return",
"name",
"in",
"getActions",
"(",
"context",
")",
";",
"}",
"// Setter",
"getActionsByName",
"(",
"context",
",",
"name",
")",
".",
"push",
"(",
"{",
"options",
":",
"{",
"data",
":",
"data",
"}",
",",
"mode",
":",
"mode",
".",
"toLowerCase",
"(",
")",
",",
"fn",
":",
"fn",
"}",
")",
";",
"}",
"}",
";",
"return",
"helpers",
";",
"}"
] | Generates an object of layout helpers.
@type {Function}
@param {Object} handlebars Handlebars instance.
@return {Object} Object of helpers. | [
"Generates",
"an",
"object",
"of",
"layout",
"helpers",
"."
] | 50b533b0c02b47d57a6ee4f81531c9e52213b10c | https://github.com/shannonmoeller/handlebars-layouts/blob/50b533b0c02b47d57a6ee4f81531c9e52213b10c/index.js#L93-L212 |
22,278 | BlinkUX/sequelize-mock | src/queryinterface.js | QueryInterface | function QueryInterface (options) {
this.options = _.extend({
stopPropagation: false,
createdDefault: true,
fallbackFn: undefined,
}, options || {});
this._results = [];
this._handlers = [];
} | javascript | function QueryInterface (options) {
this.options = _.extend({
stopPropagation: false,
createdDefault: true,
fallbackFn: undefined,
}, options || {});
this._results = [];
this._handlers = [];
} | [
"function",
"QueryInterface",
"(",
"options",
")",
"{",
"this",
".",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"stopPropagation",
":",
"false",
",",
"createdDefault",
":",
"true",
",",
"fallbackFn",
":",
"undefined",
",",
"}",
",",
"options",
"||",
"{",
"}",
")",
";",
"this",
".",
"_results",
"=",
"[",
"]",
";",
"this",
".",
"_handlers",
"=",
"[",
"]",
";",
"}"
] | The `QueryInterface` class is used to provide common mock query functionality. New
instances of this class should mostly be created internally, however the functions on
the class are exposed on objects utilize this class.
@class QueryInterface
@constructor
@param {Object} [options] Options for the query interface to use
@param {QueryInterface} [options.parent] Parent `QueryInterface` object to propagate up to
@param {Boolean} [options.stopPropagation] Flag indicating if we should not propagate to the parent
@param {Boolean} [options.createdDefault] Default value to be used for if something has been created if one is not passed in by the query. Defaults to true
@param {Function} [options.fallbackFn] Default function to call as a fallback if nothing is left in the queue and a fallback function is not passed in with the query | [
"The",
"QueryInterface",
"class",
"is",
"used",
"to",
"provide",
"common",
"mock",
"query",
"functionality",
".",
"New",
"instances",
"of",
"this",
"class",
"should",
"mostly",
"be",
"created",
"internally",
"however",
"the",
"functions",
"on",
"the",
"class",
"are",
"exposed",
"on",
"objects",
"utilize",
"this",
"class",
"."
] | 2db72e5ce3e8d630cb93ed1814000627c31e5590 | https://github.com/BlinkUX/sequelize-mock/blob/2db72e5ce3e8d630cb93ed1814000627c31e5590/src/queryinterface.js#L40-L48 |
22,279 | BlinkUX/sequelize-mock | src/instance.js | fakeModelInstance | function fakeModelInstance (values, options) {
this.options = options || {};
/**
* As with Sequelize, we include a `dataValues` property which contains the values for the
* instance. As with Sequelize, you should use other methods to edit the values for any
* code that will also interact with Sequelize.
*
* For test code, when possible, we also recommend you use other means to validate. But
* this object is also available if needed.
*
* @name dataValues
* @alias _values
* @member {Object}
**/
this.dataValues = this._values = _.clone(values || {});
this.hasPrimaryKeys = this.Model.options.hasPrimaryKeys;
if(this.hasPrimaryKeys) {
this.dataValues.id = this.dataValues.id || (++id);
}
if(this.Model.options.timestamps) {
this.dataValues.createdAt = this.dataValues.createdAt || new Date();
this.dataValues.updatedAt = this.dataValues.updatedAt || new Date();
}
// Double underscore for test specific internal variables
this.__validationErrors = [];
// Add the items from the dataValues to be accessible via a simple `instance.value` call
var self = this;
_.each(this.dataValues, function (val, key) {
Object.defineProperty(self, key, {
get: function () {
return fakeModelInstance.prototype.get.call(self, key);
},
set: function (value) {
fakeModelInstance.prototype.set.call(self, key, value);
},
});
});
} | javascript | function fakeModelInstance (values, options) {
this.options = options || {};
/**
* As with Sequelize, we include a `dataValues` property which contains the values for the
* instance. As with Sequelize, you should use other methods to edit the values for any
* code that will also interact with Sequelize.
*
* For test code, when possible, we also recommend you use other means to validate. But
* this object is also available if needed.
*
* @name dataValues
* @alias _values
* @member {Object}
**/
this.dataValues = this._values = _.clone(values || {});
this.hasPrimaryKeys = this.Model.options.hasPrimaryKeys;
if(this.hasPrimaryKeys) {
this.dataValues.id = this.dataValues.id || (++id);
}
if(this.Model.options.timestamps) {
this.dataValues.createdAt = this.dataValues.createdAt || new Date();
this.dataValues.updatedAt = this.dataValues.updatedAt || new Date();
}
// Double underscore for test specific internal variables
this.__validationErrors = [];
// Add the items from the dataValues to be accessible via a simple `instance.value` call
var self = this;
_.each(this.dataValues, function (val, key) {
Object.defineProperty(self, key, {
get: function () {
return fakeModelInstance.prototype.get.call(self, key);
},
set: function (value) {
fakeModelInstance.prototype.set.call(self, key, value);
},
});
});
} | [
"function",
"fakeModelInstance",
"(",
"values",
",",
"options",
")",
"{",
"this",
".",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"/**\n\t * As with Sequelize, we include a `dataValues` property which contains the values for the\n\t * instance. As with Sequelize, you should use other methods to edit the values for any\n\t * code that will also interact with Sequelize.\n\t * \n\t * For test code, when possible, we also recommend you use other means to validate. But\n\t * this object is also available if needed.\n\t * \n\t * @name dataValues\n\t * @alias _values\n\t * @member {Object}\n\t **/",
"this",
".",
"dataValues",
"=",
"this",
".",
"_values",
"=",
"_",
".",
"clone",
"(",
"values",
"||",
"{",
"}",
")",
";",
"this",
".",
"hasPrimaryKeys",
"=",
"this",
".",
"Model",
".",
"options",
".",
"hasPrimaryKeys",
";",
"if",
"(",
"this",
".",
"hasPrimaryKeys",
")",
"{",
"this",
".",
"dataValues",
".",
"id",
"=",
"this",
".",
"dataValues",
".",
"id",
"||",
"(",
"++",
"id",
")",
";",
"}",
"if",
"(",
"this",
".",
"Model",
".",
"options",
".",
"timestamps",
")",
"{",
"this",
".",
"dataValues",
".",
"createdAt",
"=",
"this",
".",
"dataValues",
".",
"createdAt",
"||",
"new",
"Date",
"(",
")",
";",
"this",
".",
"dataValues",
".",
"updatedAt",
"=",
"this",
".",
"dataValues",
".",
"updatedAt",
"||",
"new",
"Date",
"(",
")",
";",
"}",
"// Double underscore for test specific internal variables",
"this",
".",
"__validationErrors",
"=",
"[",
"]",
";",
"// Add the items from the dataValues to be accessible via a simple `instance.value` call",
"var",
"self",
"=",
"this",
";",
"_",
".",
"each",
"(",
"this",
".",
"dataValues",
",",
"function",
"(",
"val",
",",
"key",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"self",
",",
"key",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"fakeModelInstance",
".",
"prototype",
".",
"get",
".",
"call",
"(",
"self",
",",
"key",
")",
";",
"}",
",",
"set",
":",
"function",
"(",
"value",
")",
"{",
"fakeModelInstance",
".",
"prototype",
".",
"set",
".",
"call",
"(",
"self",
",",
"key",
",",
"value",
")",
";",
"}",
",",
"}",
")",
";",
"}",
")",
";",
"}"
] | Instance Mock Object. Creation of this object should almost always be handled through the
`Model` class methods. In cases when you need to create an `Instance` directly, providing
the `defaults` parameter should be enough, as the `obj` overrides parameter is optional.
@class Instance
@constructor
@param {Object} defaults The default values. This will come from the Model when created via that class
@param {Object} [obj] Any overridden values that should be specific to this instance | [
"Instance",
"Mock",
"Object",
".",
"Creation",
"of",
"this",
"object",
"should",
"almost",
"always",
"be",
"handled",
"through",
"the",
"Model",
"class",
"methods",
".",
"In",
"cases",
"when",
"you",
"need",
"to",
"create",
"an",
"Instance",
"directly",
"providing",
"the",
"defaults",
"parameter",
"should",
"be",
"enough",
"as",
"the",
"obj",
"overrides",
"parameter",
"is",
"optional",
"."
] | 2db72e5ce3e8d630cb93ed1814000627c31e5590 | https://github.com/BlinkUX/sequelize-mock/blob/2db72e5ce3e8d630cb93ed1814000627c31e5590/src/instance.js#L43-L86 |
22,280 | BlinkUX/sequelize-mock | src/sequelize.js | Sequelize | function Sequelize(database, username, password, options) {
if(typeof database == 'object') {
options = database;
} else if (typeof username == 'object') {
options = username;
} else if (typeof password == 'object') {
options = password;
}
this.queryInterface = new QueryInterface( _.pick(options || {}, ['stopPropagation']) );
/**
* Options passed into the Sequelize initialization
*
* @member Sequelize
* @property
**/
this.options = _.extend({
dialect: 'mock',
}, options || {});
/**
* Used to cache and override model imports for easy mock model importing
*
* @member Sequelize
* @property
**/
this.importCache = {};
/**
* Models that have been defined in this Sequelize Mock instances
*
* @member Sequelize
* @property
**/
this.models = {};
} | javascript | function Sequelize(database, username, password, options) {
if(typeof database == 'object') {
options = database;
} else if (typeof username == 'object') {
options = username;
} else if (typeof password == 'object') {
options = password;
}
this.queryInterface = new QueryInterface( _.pick(options || {}, ['stopPropagation']) );
/**
* Options passed into the Sequelize initialization
*
* @member Sequelize
* @property
**/
this.options = _.extend({
dialect: 'mock',
}, options || {});
/**
* Used to cache and override model imports for easy mock model importing
*
* @member Sequelize
* @property
**/
this.importCache = {};
/**
* Models that have been defined in this Sequelize Mock instances
*
* @member Sequelize
* @property
**/
this.models = {};
} | [
"function",
"Sequelize",
"(",
"database",
",",
"username",
",",
"password",
",",
"options",
")",
"{",
"if",
"(",
"typeof",
"database",
"==",
"'object'",
")",
"{",
"options",
"=",
"database",
";",
"}",
"else",
"if",
"(",
"typeof",
"username",
"==",
"'object'",
")",
"{",
"options",
"=",
"username",
";",
"}",
"else",
"if",
"(",
"typeof",
"password",
"==",
"'object'",
")",
"{",
"options",
"=",
"password",
";",
"}",
"this",
".",
"queryInterface",
"=",
"new",
"QueryInterface",
"(",
"_",
".",
"pick",
"(",
"options",
"||",
"{",
"}",
",",
"[",
"'stopPropagation'",
"]",
")",
")",
";",
"/**\n\t * Options passed into the Sequelize initialization\n\t * \n\t * @member Sequelize\n\t * @property\n\t **/",
"this",
".",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"dialect",
":",
"'mock'",
",",
"}",
",",
"options",
"||",
"{",
"}",
")",
";",
"/**\n\t * Used to cache and override model imports for easy mock model importing\n\t * \n\t * @member Sequelize\n\t * @property\n\t **/",
"this",
".",
"importCache",
"=",
"{",
"}",
";",
"/**\n\t * Models that have been defined in this Sequelize Mock instances\n\t * \n\t * @member Sequelize\n\t * @property\n\t **/",
"this",
".",
"models",
"=",
"{",
"}",
";",
"}"
] | Sequelize Mock Object. This can be initialize much the same way that Sequelize itself
is initialized. Any configuration or options is ignored, so it can be used as a drop-in
replacement for Sequelize but does not have all the same functionality or features.
@class Sequelize
@constructor
@param {String} [database] Ignored for Mock objects, supported to match Sequelize
@param {String} [username] Ignored for Mock objects, supported to match Sequelize
@param {String} [password] Ignored for Mock objects, supported to match Sequelize
@param {String} [options] Options object. Most default Sequelize options are ignored unless listed below. All, however, are available by accessing `sequelize.options`
@param {String} [options.dialect='mock'] Dialect that the system will use. Avaible to be returned by `getDialect()` but has no other effect
@param {Boolean} [options.autoQueryFallback] Flag inherited by defined Models indicating if we should try and generate results based on the query automatically
@param {Boolean} [options.stopPropagation] Flag inherited by defined Models indicating if we should not propagate to the parent | [
"Sequelize",
"Mock",
"Object",
".",
"This",
"can",
"be",
"initialize",
"much",
"the",
"same",
"way",
"that",
"Sequelize",
"itself",
"is",
"initialized",
".",
"Any",
"configuration",
"or",
"options",
"is",
"ignored",
"so",
"it",
"can",
"be",
"used",
"as",
"a",
"drop",
"-",
"in",
"replacement",
"for",
"Sequelize",
"but",
"does",
"not",
"have",
"all",
"the",
"same",
"functionality",
"or",
"features",
"."
] | 2db72e5ce3e8d630cb93ed1814000627c31e5590 | https://github.com/BlinkUX/sequelize-mock/blob/2db72e5ce3e8d630cb93ed1814000627c31e5590/src/sequelize.js#L35-L71 |
22,281 | catamphetamine/react-time-ago | source/ReactTimeAgo.js | convertToDate | function convertToDate(input)
{
if (input.constructor === Date) {
return input
}
if (typeof input === 'number') {
return new Date(input)
}
throw new Error(`Unsupported react-time-ago input: ${typeof input}, ${input}`)
} | javascript | function convertToDate(input)
{
if (input.constructor === Date) {
return input
}
if (typeof input === 'number') {
return new Date(input)
}
throw new Error(`Unsupported react-time-ago input: ${typeof input}, ${input}`)
} | [
"function",
"convertToDate",
"(",
"input",
")",
"{",
"if",
"(",
"input",
".",
"constructor",
"===",
"Date",
")",
"{",
"return",
"input",
"}",
"if",
"(",
"typeof",
"input",
"===",
"'number'",
")",
"{",
"return",
"new",
"Date",
"(",
"input",
")",
"}",
"throw",
"new",
"Error",
"(",
"`",
"${",
"typeof",
"input",
"}",
"${",
"input",
"}",
"`",
")",
"}"
] | Converts argument into a `Date`. | [
"Converts",
"argument",
"into",
"a",
"Date",
"."
] | 2f7bf6d8981ec49cdb94a15d99ef0fddf410d90c | https://github.com/catamphetamine/react-time-ago/blob/2f7bf6d8981ec49cdb94a15d99ef0fddf410d90c/source/ReactTimeAgo.js#L238-L249 |
22,282 | design-first/system-runtime | src/helper.js | getPrefix | function getPrefix() {
var validPrefix = 'abcdef';
return validPrefix.charAt(Math.floor(Math.random() * validPrefix.length));
} | javascript | function getPrefix() {
var validPrefix = 'abcdef';
return validPrefix.charAt(Math.floor(Math.random() * validPrefix.length));
} | [
"function",
"getPrefix",
"(",
")",
"{",
"var",
"validPrefix",
"=",
"'abcdef'",
";",
"return",
"validPrefix",
".",
"charAt",
"(",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"validPrefix",
".",
"length",
")",
")",
";",
"}"
] | force the uuid to start with a letter | [
"force",
"the",
"uuid",
"to",
"start",
"with",
"a",
"letter"
] | 59b168886f307bd20531b3c7b082920998e5b700 | https://github.com/design-first/system-runtime/blob/59b168886f307bd20531b3c7b082920998e5b700/src/helper.js#L120-L123 |
22,283 | jieter/Leaflet.encoded | Polyline.encoded.js | function (num) {
var value, encoded = '';
while (num >= 0x20) {
value = (0x20 | (num & 0x1f)) + 63;
encoded += (String.fromCharCode(value));
num >>= 5;
}
value = num + 63;
encoded += (String.fromCharCode(value));
return encoded;
} | javascript | function (num) {
var value, encoded = '';
while (num >= 0x20) {
value = (0x20 | (num & 0x1f)) + 63;
encoded += (String.fromCharCode(value));
num >>= 5;
}
value = num + 63;
encoded += (String.fromCharCode(value));
return encoded;
} | [
"function",
"(",
"num",
")",
"{",
"var",
"value",
",",
"encoded",
"=",
"''",
";",
"while",
"(",
"num",
">=",
"0x20",
")",
"{",
"value",
"=",
"(",
"0x20",
"|",
"(",
"num",
"&",
"0x1f",
")",
")",
"+",
"63",
";",
"encoded",
"+=",
"(",
"String",
".",
"fromCharCode",
"(",
"value",
")",
")",
";",
"num",
">>=",
"5",
";",
"}",
"value",
"=",
"num",
"+",
"63",
";",
"encoded",
"+=",
"(",
"String",
".",
"fromCharCode",
"(",
"value",
")",
")",
";",
"return",
"encoded",
";",
"}"
] | This function is very similar to Google's, but I added some stuff to deal with the double slash issue. | [
"This",
"function",
"is",
"very",
"similar",
"to",
"Google",
"s",
"but",
"I",
"added",
"some",
"stuff",
"to",
"deal",
"with",
"the",
"double",
"slash",
"issue",
"."
] | 68e781908783fb12236fc7d8d90d71d785f892e9 | https://github.com/jieter/Leaflet.encoded/blob/68e781908783fb12236fc7d8d90d71d785f892e9/Polyline.encoded.js#L186-L197 | |
22,284 | errcw/gaussian | lib/gaussian.js | function(x) {
var z = Math.abs(x);
var t = 1 / (1 + z / 2);
var r = t * Math.exp(-z * z - 1.26551223 + t * (1.00002368 +
t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 +
t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 +
t * (-0.82215223 + t * 0.17087277)))))))))
return x >= 0 ? r : 2 - r;
} | javascript | function(x) {
var z = Math.abs(x);
var t = 1 / (1 + z / 2);
var r = t * Math.exp(-z * z - 1.26551223 + t * (1.00002368 +
t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 +
t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 +
t * (-0.82215223 + t * 0.17087277)))))))))
return x >= 0 ? r : 2 - r;
} | [
"function",
"(",
"x",
")",
"{",
"var",
"z",
"=",
"Math",
".",
"abs",
"(",
"x",
")",
";",
"var",
"t",
"=",
"1",
"/",
"(",
"1",
"+",
"z",
"/",
"2",
")",
";",
"var",
"r",
"=",
"t",
"*",
"Math",
".",
"exp",
"(",
"-",
"z",
"*",
"z",
"-",
"1.26551223",
"+",
"t",
"*",
"(",
"1.00002368",
"+",
"t",
"*",
"(",
"0.37409196",
"+",
"t",
"*",
"(",
"0.09678418",
"+",
"t",
"*",
"(",
"-",
"0.18628806",
"+",
"t",
"*",
"(",
"0.27886807",
"+",
"t",
"*",
"(",
"-",
"1.13520398",
"+",
"t",
"*",
"(",
"1.48851587",
"+",
"t",
"*",
"(",
"-",
"0.82215223",
"+",
"t",
"*",
"0.17087277",
")",
")",
")",
")",
")",
")",
")",
")",
")",
"return",
"x",
">=",
"0",
"?",
"r",
":",
"2",
"-",
"r",
";",
"}"
] | Complementary error function From Numerical Recipes in C 2e p221 | [
"Complementary",
"error",
"function",
"From",
"Numerical",
"Recipes",
"in",
"C",
"2e",
"p221"
] | 3b3e49cd35f278429af80e310aed85de94d1eb99 | https://github.com/errcw/gaussian/blob/3b3e49cd35f278429af80e310aed85de94d1eb99/lib/gaussian.js#L7-L15 | |
22,285 | errcw/gaussian | lib/gaussian.js | function(x) {
if (x >= 2) { return -100; }
if (x <= 0) { return 100; }
var xx = (x < 1) ? x : 2 - x;
var t = Math.sqrt(-2 * Math.log(xx / 2));
var r = -0.70711 * ((2.30753 + t * 0.27061) /
(1 + t * (0.99229 + t * 0.04481)) - t);
for (var j = 0; j < 2; j++) {
var err = erfc(r) - xx;
r += err / (1.12837916709551257 * Math.exp(-(r * r)) - r * err);
}
return (x < 1) ? r : -r;
} | javascript | function(x) {
if (x >= 2) { return -100; }
if (x <= 0) { return 100; }
var xx = (x < 1) ? x : 2 - x;
var t = Math.sqrt(-2 * Math.log(xx / 2));
var r = -0.70711 * ((2.30753 + t * 0.27061) /
(1 + t * (0.99229 + t * 0.04481)) - t);
for (var j = 0; j < 2; j++) {
var err = erfc(r) - xx;
r += err / (1.12837916709551257 * Math.exp(-(r * r)) - r * err);
}
return (x < 1) ? r : -r;
} | [
"function",
"(",
"x",
")",
"{",
"if",
"(",
"x",
">=",
"2",
")",
"{",
"return",
"-",
"100",
";",
"}",
"if",
"(",
"x",
"<=",
"0",
")",
"{",
"return",
"100",
";",
"}",
"var",
"xx",
"=",
"(",
"x",
"<",
"1",
")",
"?",
"x",
":",
"2",
"-",
"x",
";",
"var",
"t",
"=",
"Math",
".",
"sqrt",
"(",
"-",
"2",
"*",
"Math",
".",
"log",
"(",
"xx",
"/",
"2",
")",
")",
";",
"var",
"r",
"=",
"-",
"0.70711",
"*",
"(",
"(",
"2.30753",
"+",
"t",
"*",
"0.27061",
")",
"/",
"(",
"1",
"+",
"t",
"*",
"(",
"0.99229",
"+",
"t",
"*",
"0.04481",
")",
")",
"-",
"t",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"2",
";",
"j",
"++",
")",
"{",
"var",
"err",
"=",
"erfc",
"(",
"r",
")",
"-",
"xx",
";",
"r",
"+=",
"err",
"/",
"(",
"1.12837916709551257",
"*",
"Math",
".",
"exp",
"(",
"-",
"(",
"r",
"*",
"r",
")",
")",
"-",
"r",
"*",
"err",
")",
";",
"}",
"return",
"(",
"x",
"<",
"1",
")",
"?",
"r",
":",
"-",
"r",
";",
"}"
] | Inverse complementary error function From Numerical Recipes 3e p265 | [
"Inverse",
"complementary",
"error",
"function",
"From",
"Numerical",
"Recipes",
"3e",
"p265"
] | 3b3e49cd35f278429af80e310aed85de94d1eb99 | https://github.com/errcw/gaussian/blob/3b3e49cd35f278429af80e310aed85de94d1eb99/lib/gaussian.js#L19-L35 | |
22,286 | errcw/gaussian | lib/gaussian.js | function(mean, variance) {
if (variance <= 0) {
throw new Error('Variance must be > 0 (but was ' + variance + ')');
}
this.mean = mean;
this.variance = variance;
this.standardDeviation = Math.sqrt(variance);
} | javascript | function(mean, variance) {
if (variance <= 0) {
throw new Error('Variance must be > 0 (but was ' + variance + ')');
}
this.mean = mean;
this.variance = variance;
this.standardDeviation = Math.sqrt(variance);
} | [
"function",
"(",
"mean",
",",
"variance",
")",
"{",
"if",
"(",
"variance",
"<=",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Variance must be > 0 (but was '",
"+",
"variance",
"+",
"')'",
")",
";",
"}",
"this",
".",
"mean",
"=",
"mean",
";",
"this",
".",
"variance",
"=",
"variance",
";",
"this",
".",
"standardDeviation",
"=",
"Math",
".",
"sqrt",
"(",
"variance",
")",
";",
"}"
] | Models the normal distribution | [
"Models",
"the",
"normal",
"distribution"
] | 3b3e49cd35f278429af80e310aed85de94d1eb99 | https://github.com/errcw/gaussian/blob/3b3e49cd35f278429af80e310aed85de94d1eb99/lib/gaussian.js#L38-L45 | |
22,287 | mscdex/dicer | lib/HeaderParser.js | HeaderParser | function HeaderParser(cfg) {
EventEmitter.call(this);
var self = this;
this.nread = 0;
this.maxed = false;
this.npairs = 0;
this.maxHeaderPairs = (cfg && typeof cfg.maxHeaderPairs === 'number'
? cfg.maxHeaderPairs
: MAX_HEADER_PAIRS);
this.buffer = '';
this.header = {};
this.finished = false;
this.ss = new StreamSearch(B_DCRLF);
this.ss.on('info', function(isMatch, data, start, end) {
if (data && !self.maxed) {
if (self.nread + (end - start) > MAX_HEADER_SIZE) {
end = (MAX_HEADER_SIZE - self.nread);
self.nread = MAX_HEADER_SIZE;
} else
self.nread += (end - start);
if (self.nread === MAX_HEADER_SIZE)
self.maxed = true;
self.buffer += data.toString('binary', start, end);
}
if (isMatch)
self._finish();
});
} | javascript | function HeaderParser(cfg) {
EventEmitter.call(this);
var self = this;
this.nread = 0;
this.maxed = false;
this.npairs = 0;
this.maxHeaderPairs = (cfg && typeof cfg.maxHeaderPairs === 'number'
? cfg.maxHeaderPairs
: MAX_HEADER_PAIRS);
this.buffer = '';
this.header = {};
this.finished = false;
this.ss = new StreamSearch(B_DCRLF);
this.ss.on('info', function(isMatch, data, start, end) {
if (data && !self.maxed) {
if (self.nread + (end - start) > MAX_HEADER_SIZE) {
end = (MAX_HEADER_SIZE - self.nread);
self.nread = MAX_HEADER_SIZE;
} else
self.nread += (end - start);
if (self.nread === MAX_HEADER_SIZE)
self.maxed = true;
self.buffer += data.toString('binary', start, end);
}
if (isMatch)
self._finish();
});
} | [
"function",
"HeaderParser",
"(",
"cfg",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"var",
"self",
"=",
"this",
";",
"this",
".",
"nread",
"=",
"0",
";",
"this",
".",
"maxed",
"=",
"false",
";",
"this",
".",
"npairs",
"=",
"0",
";",
"this",
".",
"maxHeaderPairs",
"=",
"(",
"cfg",
"&&",
"typeof",
"cfg",
".",
"maxHeaderPairs",
"===",
"'number'",
"?",
"cfg",
".",
"maxHeaderPairs",
":",
"MAX_HEADER_PAIRS",
")",
";",
"this",
".",
"buffer",
"=",
"''",
";",
"this",
".",
"header",
"=",
"{",
"}",
";",
"this",
".",
"finished",
"=",
"false",
";",
"this",
".",
"ss",
"=",
"new",
"StreamSearch",
"(",
"B_DCRLF",
")",
";",
"this",
".",
"ss",
".",
"on",
"(",
"'info'",
",",
"function",
"(",
"isMatch",
",",
"data",
",",
"start",
",",
"end",
")",
"{",
"if",
"(",
"data",
"&&",
"!",
"self",
".",
"maxed",
")",
"{",
"if",
"(",
"self",
".",
"nread",
"+",
"(",
"end",
"-",
"start",
")",
">",
"MAX_HEADER_SIZE",
")",
"{",
"end",
"=",
"(",
"MAX_HEADER_SIZE",
"-",
"self",
".",
"nread",
")",
";",
"self",
".",
"nread",
"=",
"MAX_HEADER_SIZE",
";",
"}",
"else",
"self",
".",
"nread",
"+=",
"(",
"end",
"-",
"start",
")",
";",
"if",
"(",
"self",
".",
"nread",
"===",
"MAX_HEADER_SIZE",
")",
"self",
".",
"maxed",
"=",
"true",
";",
"self",
".",
"buffer",
"+=",
"data",
".",
"toString",
"(",
"'binary'",
",",
"start",
",",
"end",
")",
";",
"}",
"if",
"(",
"isMatch",
")",
"self",
".",
"_finish",
"(",
")",
";",
"}",
")",
";",
"}"
] | from node's http_parser | [
"from",
"node",
"s",
"http_parser"
] | 524254c4af4e8f2ed070facac8f6d91538b41eef | https://github.com/mscdex/dicer/blob/524254c4af4e8f2ed070facac8f6d91538b41eef/lib/HeaderParser.js#L12-L42 |
22,288 | josdejong/lossless-json | lib/parse.js | getToken | function getToken() {
tokenType = TOKENTYPE.NULL;
token = '';
// skip over whitespaces: space, tab, newline, and carriage return
while (c === ' ' || c === '\t' || c === '\n' || c === '\r') {
next();
}
// check for delimiters
if (DELIMITERS[c]) {
tokenType = TOKENTYPE.DELIMITER;
token = c;
next();
return;
}
// check for a number
if (isDigit(c) || c === '-') {
tokenType = TOKENTYPE.NUMBER;
if (c === '-') {
token += c;
next();
if (!isDigit(c)) {
throw createSyntaxError('Invalid number, digit expected', index);
}
}
else if (c === '0') {
token += c;
next();
}
else {
// digit 1-9, nothing extra to do
}
while (isDigit(c)) {
token += c;
next();
}
if (c === '.') {
token += c;
next();
if (!isDigit(c)) {
throw createSyntaxError('Invalid number, digit expected', index);
}
while (isDigit(c)) {
token += c;
next();
}
}
if (c === 'e' || c === 'E') {
token += c;
next();
if (c === '+' || c === '-') {
token += c;
next();
}
if (!isDigit(c)) {
throw createSyntaxError('Invalid number, digit expected', index);
}
while (isDigit(c)) {
token += c;
next();
}
}
return;
}
// check for a string
if (c === '"') {
tokenType = TOKENTYPE.STRING;
next();
while (c !== '' && c !== '"') {
if (c === '\\') {
// handle escape characters
next();
let unescaped = ESCAPE_CHARACTERS[c];
if (unescaped !== undefined) {
token += unescaped;
next();
}
else if (c === 'u') {
// parse escaped unicode character, like '\\u260E'
next();
let hex = '';
for (let u = 0; u < 4; u++) {
if (!isHex(c)) {
throw createSyntaxError('Invalid unicode character');
}
hex += c;
next();
}
token += String.fromCharCode(parseInt(hex, 16));
}
else {
throw createSyntaxError('Invalid escape character "\\' + c + '"', index);
}
}
else {
// a regular character
token += c;
next();
}
}
if (c !== '"') {
throw createSyntaxError('End of string expected');
}
next();
return;
}
// check for symbols (true, false, null)
if (isAlpha(c)) {
tokenType = TOKENTYPE.SYMBOL;
while (isAlpha(c)) {
token += c;
next();
}
return;
}
// something unknown is found, wrong characters -> a syntax error
tokenType = TOKENTYPE.UNKNOWN;
while (c !== '') {
token += c;
next();
}
throw createSyntaxError('Syntax error in part "' + token + '"');
} | javascript | function getToken() {
tokenType = TOKENTYPE.NULL;
token = '';
// skip over whitespaces: space, tab, newline, and carriage return
while (c === ' ' || c === '\t' || c === '\n' || c === '\r') {
next();
}
// check for delimiters
if (DELIMITERS[c]) {
tokenType = TOKENTYPE.DELIMITER;
token = c;
next();
return;
}
// check for a number
if (isDigit(c) || c === '-') {
tokenType = TOKENTYPE.NUMBER;
if (c === '-') {
token += c;
next();
if (!isDigit(c)) {
throw createSyntaxError('Invalid number, digit expected', index);
}
}
else if (c === '0') {
token += c;
next();
}
else {
// digit 1-9, nothing extra to do
}
while (isDigit(c)) {
token += c;
next();
}
if (c === '.') {
token += c;
next();
if (!isDigit(c)) {
throw createSyntaxError('Invalid number, digit expected', index);
}
while (isDigit(c)) {
token += c;
next();
}
}
if (c === 'e' || c === 'E') {
token += c;
next();
if (c === '+' || c === '-') {
token += c;
next();
}
if (!isDigit(c)) {
throw createSyntaxError('Invalid number, digit expected', index);
}
while (isDigit(c)) {
token += c;
next();
}
}
return;
}
// check for a string
if (c === '"') {
tokenType = TOKENTYPE.STRING;
next();
while (c !== '' && c !== '"') {
if (c === '\\') {
// handle escape characters
next();
let unescaped = ESCAPE_CHARACTERS[c];
if (unescaped !== undefined) {
token += unescaped;
next();
}
else if (c === 'u') {
// parse escaped unicode character, like '\\u260E'
next();
let hex = '';
for (let u = 0; u < 4; u++) {
if (!isHex(c)) {
throw createSyntaxError('Invalid unicode character');
}
hex += c;
next();
}
token += String.fromCharCode(parseInt(hex, 16));
}
else {
throw createSyntaxError('Invalid escape character "\\' + c + '"', index);
}
}
else {
// a regular character
token += c;
next();
}
}
if (c !== '"') {
throw createSyntaxError('End of string expected');
}
next();
return;
}
// check for symbols (true, false, null)
if (isAlpha(c)) {
tokenType = TOKENTYPE.SYMBOL;
while (isAlpha(c)) {
token += c;
next();
}
return;
}
// something unknown is found, wrong characters -> a syntax error
tokenType = TOKENTYPE.UNKNOWN;
while (c !== '') {
token += c;
next();
}
throw createSyntaxError('Syntax error in part "' + token + '"');
} | [
"function",
"getToken",
"(",
")",
"{",
"tokenType",
"=",
"TOKENTYPE",
".",
"NULL",
";",
"token",
"=",
"''",
";",
"// skip over whitespaces: space, tab, newline, and carriage return",
"while",
"(",
"c",
"===",
"' '",
"||",
"c",
"===",
"'\\t'",
"||",
"c",
"===",
"'\\n'",
"||",
"c",
"===",
"'\\r'",
")",
"{",
"next",
"(",
")",
";",
"}",
"// check for delimiters",
"if",
"(",
"DELIMITERS",
"[",
"c",
"]",
")",
"{",
"tokenType",
"=",
"TOKENTYPE",
".",
"DELIMITER",
";",
"token",
"=",
"c",
";",
"next",
"(",
")",
";",
"return",
";",
"}",
"// check for a number",
"if",
"(",
"isDigit",
"(",
"c",
")",
"||",
"c",
"===",
"'-'",
")",
"{",
"tokenType",
"=",
"TOKENTYPE",
".",
"NUMBER",
";",
"if",
"(",
"c",
"===",
"'-'",
")",
"{",
"token",
"+=",
"c",
";",
"next",
"(",
")",
";",
"if",
"(",
"!",
"isDigit",
"(",
"c",
")",
")",
"{",
"throw",
"createSyntaxError",
"(",
"'Invalid number, digit expected'",
",",
"index",
")",
";",
"}",
"}",
"else",
"if",
"(",
"c",
"===",
"'0'",
")",
"{",
"token",
"+=",
"c",
";",
"next",
"(",
")",
";",
"}",
"else",
"{",
"// digit 1-9, nothing extra to do",
"}",
"while",
"(",
"isDigit",
"(",
"c",
")",
")",
"{",
"token",
"+=",
"c",
";",
"next",
"(",
")",
";",
"}",
"if",
"(",
"c",
"===",
"'.'",
")",
"{",
"token",
"+=",
"c",
";",
"next",
"(",
")",
";",
"if",
"(",
"!",
"isDigit",
"(",
"c",
")",
")",
"{",
"throw",
"createSyntaxError",
"(",
"'Invalid number, digit expected'",
",",
"index",
")",
";",
"}",
"while",
"(",
"isDigit",
"(",
"c",
")",
")",
"{",
"token",
"+=",
"c",
";",
"next",
"(",
")",
";",
"}",
"}",
"if",
"(",
"c",
"===",
"'e'",
"||",
"c",
"===",
"'E'",
")",
"{",
"token",
"+=",
"c",
";",
"next",
"(",
")",
";",
"if",
"(",
"c",
"===",
"'+'",
"||",
"c",
"===",
"'-'",
")",
"{",
"token",
"+=",
"c",
";",
"next",
"(",
")",
";",
"}",
"if",
"(",
"!",
"isDigit",
"(",
"c",
")",
")",
"{",
"throw",
"createSyntaxError",
"(",
"'Invalid number, digit expected'",
",",
"index",
")",
";",
"}",
"while",
"(",
"isDigit",
"(",
"c",
")",
")",
"{",
"token",
"+=",
"c",
";",
"next",
"(",
")",
";",
"}",
"}",
"return",
";",
"}",
"// check for a string",
"if",
"(",
"c",
"===",
"'\"'",
")",
"{",
"tokenType",
"=",
"TOKENTYPE",
".",
"STRING",
";",
"next",
"(",
")",
";",
"while",
"(",
"c",
"!==",
"''",
"&&",
"c",
"!==",
"'\"'",
")",
"{",
"if",
"(",
"c",
"===",
"'\\\\'",
")",
"{",
"// handle escape characters",
"next",
"(",
")",
";",
"let",
"unescaped",
"=",
"ESCAPE_CHARACTERS",
"[",
"c",
"]",
";",
"if",
"(",
"unescaped",
"!==",
"undefined",
")",
"{",
"token",
"+=",
"unescaped",
";",
"next",
"(",
")",
";",
"}",
"else",
"if",
"(",
"c",
"===",
"'u'",
")",
"{",
"// parse escaped unicode character, like '\\\\u260E'",
"next",
"(",
")",
";",
"let",
"hex",
"=",
"''",
";",
"for",
"(",
"let",
"u",
"=",
"0",
";",
"u",
"<",
"4",
";",
"u",
"++",
")",
"{",
"if",
"(",
"!",
"isHex",
"(",
"c",
")",
")",
"{",
"throw",
"createSyntaxError",
"(",
"'Invalid unicode character'",
")",
";",
"}",
"hex",
"+=",
"c",
";",
"next",
"(",
")",
";",
"}",
"token",
"+=",
"String",
".",
"fromCharCode",
"(",
"parseInt",
"(",
"hex",
",",
"16",
")",
")",
";",
"}",
"else",
"{",
"throw",
"createSyntaxError",
"(",
"'Invalid escape character \"\\\\'",
"+",
"c",
"+",
"'\"'",
",",
"index",
")",
";",
"}",
"}",
"else",
"{",
"// a regular character",
"token",
"+=",
"c",
";",
"next",
"(",
")",
";",
"}",
"}",
"if",
"(",
"c",
"!==",
"'\"'",
")",
"{",
"throw",
"createSyntaxError",
"(",
"'End of string expected'",
")",
";",
"}",
"next",
"(",
")",
";",
"return",
";",
"}",
"// check for symbols (true, false, null)",
"if",
"(",
"isAlpha",
"(",
"c",
")",
")",
"{",
"tokenType",
"=",
"TOKENTYPE",
".",
"SYMBOL",
";",
"while",
"(",
"isAlpha",
"(",
"c",
")",
")",
"{",
"token",
"+=",
"c",
";",
"next",
"(",
")",
";",
"}",
"return",
";",
"}",
"// something unknown is found, wrong characters -> a syntax error",
"tokenType",
"=",
"TOKENTYPE",
".",
"UNKNOWN",
";",
"while",
"(",
"c",
"!==",
"''",
")",
"{",
"token",
"+=",
"c",
";",
"next",
"(",
")",
";",
"}",
"throw",
"createSyntaxError",
"(",
"'Syntax error in part \"'",
"+",
"token",
"+",
"'\"'",
")",
";",
"}"
] | Get next token in the current text.
The token and token type are available as token and tokenType
@private | [
"Get",
"next",
"token",
"in",
"the",
"current",
"text",
".",
"The",
"token",
"and",
"token",
"type",
"are",
"available",
"as",
"token",
"and",
"tokenType"
] | ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd | https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/parse.js#L110-L257 |
22,289 | josdejong/lossless-json | lib/parse.js | createSyntaxError | function createSyntaxError (message, c) {
if (c === undefined) {
c = index - token.length;
}
let error = new SyntaxError(message + ' (char ' + c + ')');
error['char'] = c;
return error;
} | javascript | function createSyntaxError (message, c) {
if (c === undefined) {
c = index - token.length;
}
let error = new SyntaxError(message + ' (char ' + c + ')');
error['char'] = c;
return error;
} | [
"function",
"createSyntaxError",
"(",
"message",
",",
"c",
")",
"{",
"if",
"(",
"c",
"===",
"undefined",
")",
"{",
"c",
"=",
"index",
"-",
"token",
".",
"length",
";",
"}",
"let",
"error",
"=",
"new",
"SyntaxError",
"(",
"message",
"+",
"' (char '",
"+",
"c",
"+",
"')'",
")",
";",
"error",
"[",
"'char'",
"]",
"=",
"c",
";",
"return",
"error",
";",
"}"
] | Create an error
@param {string} message
@param {number} [c] Optional index (character position) where the
error happened. If not provided, the start of
the current token is taken
@return {SyntaxError} instantiated error
@private | [
"Create",
"an",
"error"
] | ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd | https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/parse.js#L296-L304 |
22,290 | josdejong/lossless-json | lib/parse.js | parseNumber | function parseNumber () {
if (tokenType === TOKENTYPE.NUMBER) {
let number = new LosslessNumber(token);
getToken();
return number;
}
return parseSymbol();
} | javascript | function parseNumber () {
if (tokenType === TOKENTYPE.NUMBER) {
let number = new LosslessNumber(token);
getToken();
return number;
}
return parseSymbol();
} | [
"function",
"parseNumber",
"(",
")",
"{",
"if",
"(",
"tokenType",
"===",
"TOKENTYPE",
".",
"NUMBER",
")",
"{",
"let",
"number",
"=",
"new",
"LosslessNumber",
"(",
"token",
")",
";",
"getToken",
"(",
")",
";",
"return",
"number",
";",
"}",
"return",
"parseSymbol",
"(",
")",
";",
"}"
] | Parse a number. The number will be parsed as a LosslessNumber.
@return {*} | [
"Parse",
"a",
"number",
".",
"The",
"number",
"will",
"be",
"parsed",
"as",
"a",
"LosslessNumber",
"."
] | ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd | https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/parse.js#L437-L445 |
22,291 | josdejong/lossless-json | lib/parse.js | parseSymbol | function parseSymbol () {
if (tokenType === TOKENTYPE.SYMBOL) {
if (token === 'true') {
getToken();
return true;
}
if (token === 'false') {
getToken();
return false;
}
if (token === 'null') {
getToken();
return null;
}
throw createSyntaxError('Unknown symbol "' + token + '"');
}
return parseEnd();
} | javascript | function parseSymbol () {
if (tokenType === TOKENTYPE.SYMBOL) {
if (token === 'true') {
getToken();
return true;
}
if (token === 'false') {
getToken();
return false;
}
if (token === 'null') {
getToken();
return null;
}
throw createSyntaxError('Unknown symbol "' + token + '"');
}
return parseEnd();
} | [
"function",
"parseSymbol",
"(",
")",
"{",
"if",
"(",
"tokenType",
"===",
"TOKENTYPE",
".",
"SYMBOL",
")",
"{",
"if",
"(",
"token",
"===",
"'true'",
")",
"{",
"getToken",
"(",
")",
";",
"return",
"true",
";",
"}",
"if",
"(",
"token",
"===",
"'false'",
")",
"{",
"getToken",
"(",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"token",
"===",
"'null'",
")",
"{",
"getToken",
"(",
")",
";",
"return",
"null",
";",
"}",
"throw",
"createSyntaxError",
"(",
"'Unknown symbol \"'",
"+",
"token",
"+",
"'\"'",
")",
";",
"}",
"return",
"parseEnd",
"(",
")",
";",
"}"
] | Parse constants true, false, null
@return {boolean | null} | [
"Parse",
"constants",
"true",
"false",
"null"
] | ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd | https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/parse.js#L451-L470 |
22,292 | josdejong/lossless-json | lib/parse.js | parseCircular | function parseCircular(object) {
// if circular references are disabled, just return the refs object
if (!config().circularRefs) {
return object;
}
let pointerPath = parsePointer(object.$ref);
// validate whether the path corresponds with current stack
for (let i = 0; i < pointerPath.length; i++) {
if (pointerPath[i] !== path[i]) {
throw new Error('Invalid circular reference "' + object.$ref + '"');
}
}
return stack[pointerPath.length];
} | javascript | function parseCircular(object) {
// if circular references are disabled, just return the refs object
if (!config().circularRefs) {
return object;
}
let pointerPath = parsePointer(object.$ref);
// validate whether the path corresponds with current stack
for (let i = 0; i < pointerPath.length; i++) {
if (pointerPath[i] !== path[i]) {
throw new Error('Invalid circular reference "' + object.$ref + '"');
}
}
return stack[pointerPath.length];
} | [
"function",
"parseCircular",
"(",
"object",
")",
"{",
"// if circular references are disabled, just return the refs object",
"if",
"(",
"!",
"config",
"(",
")",
".",
"circularRefs",
")",
"{",
"return",
"object",
";",
"}",
"let",
"pointerPath",
"=",
"parsePointer",
"(",
"object",
".",
"$ref",
")",
";",
"// validate whether the path corresponds with current stack",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"pointerPath",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"pointerPath",
"[",
"i",
"]",
"!==",
"path",
"[",
"i",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid circular reference \"'",
"+",
"object",
".",
"$ref",
"+",
"'\"'",
")",
";",
"}",
"}",
"return",
"stack",
"[",
"pointerPath",
".",
"length",
"]",
";",
"}"
] | Resolve a circular reference.
Throws an error if the path cannot be resolved
@param {Object} object An object with a JSON Pointer URI fragment
like {$ref: '#/foo/bar'}
@return {Object | Array} | [
"Resolve",
"a",
"circular",
"reference",
".",
"Throws",
"an",
"error",
"if",
"the",
"path",
"cannot",
"be",
"resolved"
] | ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd | https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/parse.js#L500-L516 |
22,293 | josdejong/lossless-json | lib/stringify.js | stringifyValue | function stringifyValue(value, replacer, space, indent) {
// boolean, null, number, string, or date
if (typeof value === 'boolean' || value instanceof Boolean ||
value === null ||
typeof value === 'number' || value instanceof Number ||
typeof value === 'string' || value instanceof String ||
value instanceof Date) {
return JSON.stringify(value);
}
// lossless number, the secret ingredient :)
if (value && value.isLosslessNumber) {
return value.value;
}
// array
if (Array.isArray(value)) {
return stringifyArray(value, replacer, space, indent);
}
// object (test lastly!)
if (value && typeof value === 'object') {
return stringifyObject(value, replacer, space, indent);
}
return undefined;
} | javascript | function stringifyValue(value, replacer, space, indent) {
// boolean, null, number, string, or date
if (typeof value === 'boolean' || value instanceof Boolean ||
value === null ||
typeof value === 'number' || value instanceof Number ||
typeof value === 'string' || value instanceof String ||
value instanceof Date) {
return JSON.stringify(value);
}
// lossless number, the secret ingredient :)
if (value && value.isLosslessNumber) {
return value.value;
}
// array
if (Array.isArray(value)) {
return stringifyArray(value, replacer, space, indent);
}
// object (test lastly!)
if (value && typeof value === 'object') {
return stringifyObject(value, replacer, space, indent);
}
return undefined;
} | [
"function",
"stringifyValue",
"(",
"value",
",",
"replacer",
",",
"space",
",",
"indent",
")",
"{",
"// boolean, null, number, string, or date",
"if",
"(",
"typeof",
"value",
"===",
"'boolean'",
"||",
"value",
"instanceof",
"Boolean",
"||",
"value",
"===",
"null",
"||",
"typeof",
"value",
"===",
"'number'",
"||",
"value",
"instanceof",
"Number",
"||",
"typeof",
"value",
"===",
"'string'",
"||",
"value",
"instanceof",
"String",
"||",
"value",
"instanceof",
"Date",
")",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"value",
")",
";",
"}",
"// lossless number, the secret ingredient :)",
"if",
"(",
"value",
"&&",
"value",
".",
"isLosslessNumber",
")",
"{",
"return",
"value",
".",
"value",
";",
"}",
"// array",
"if",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"return",
"stringifyArray",
"(",
"value",
",",
"replacer",
",",
"space",
",",
"indent",
")",
";",
"}",
"// object (test lastly!)",
"if",
"(",
"value",
"&&",
"typeof",
"value",
"===",
"'object'",
")",
"{",
"return",
"stringifyObject",
"(",
"value",
",",
"replacer",
",",
"space",
",",
"indent",
")",
";",
"}",
"return",
"undefined",
";",
"}"
] | Stringify a value
@param {*} value
@param {function | Array.<string | number>} [replacer]
@param {string} [space]
@param {string} [indent]
@return {string | undefined} | [
"Stringify",
"a",
"value"
] | ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd | https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/stringify.js#L72-L98 |
22,294 | josdejong/lossless-json | lib/stringify.js | stringifyArray | function stringifyArray(array, replacer, space, indent) {
let childIndent = space ? (indent + space) : undefined;
let str = space ? '[\n' : '[';
// check for circular reference
if (isCircular(array)) {
return stringifyCircular(array, replacer, space, indent);
}
// add this array to the stack
const stackIndex = stack.length;
stack[stackIndex] = array;
for (let i = 0; i < array.length; i++) {
let key = i + '';
let item = (typeof replacer === 'function')
? replacer.call(array, key, array[i])
: array[i];
if (space) {
str += childIndent;
}
if (typeof item !== 'undefined' && typeof item !== 'function') {
path[stackIndex] = key;
str += stringifyValue(item, replacer, space, childIndent);
}
else {
str += 'null'
}
if (i < array.length - 1) {
str += space ? ',\n' : ',';
}
}
// remove current entry from the stack
stack.length = stackIndex;
path.length = stackIndex;
str += space ? ('\n' + indent + ']') : ']';
return str;
} | javascript | function stringifyArray(array, replacer, space, indent) {
let childIndent = space ? (indent + space) : undefined;
let str = space ? '[\n' : '[';
// check for circular reference
if (isCircular(array)) {
return stringifyCircular(array, replacer, space, indent);
}
// add this array to the stack
const stackIndex = stack.length;
stack[stackIndex] = array;
for (let i = 0; i < array.length; i++) {
let key = i + '';
let item = (typeof replacer === 'function')
? replacer.call(array, key, array[i])
: array[i];
if (space) {
str += childIndent;
}
if (typeof item !== 'undefined' && typeof item !== 'function') {
path[stackIndex] = key;
str += stringifyValue(item, replacer, space, childIndent);
}
else {
str += 'null'
}
if (i < array.length - 1) {
str += space ? ',\n' : ',';
}
}
// remove current entry from the stack
stack.length = stackIndex;
path.length = stackIndex;
str += space ? ('\n' + indent + ']') : ']';
return str;
} | [
"function",
"stringifyArray",
"(",
"array",
",",
"replacer",
",",
"space",
",",
"indent",
")",
"{",
"let",
"childIndent",
"=",
"space",
"?",
"(",
"indent",
"+",
"space",
")",
":",
"undefined",
";",
"let",
"str",
"=",
"space",
"?",
"'[\\n'",
":",
"'['",
";",
"// check for circular reference",
"if",
"(",
"isCircular",
"(",
"array",
")",
")",
"{",
"return",
"stringifyCircular",
"(",
"array",
",",
"replacer",
",",
"space",
",",
"indent",
")",
";",
"}",
"// add this array to the stack",
"const",
"stackIndex",
"=",
"stack",
".",
"length",
";",
"stack",
"[",
"stackIndex",
"]",
"=",
"array",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"array",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"key",
"=",
"i",
"+",
"''",
";",
"let",
"item",
"=",
"(",
"typeof",
"replacer",
"===",
"'function'",
")",
"?",
"replacer",
".",
"call",
"(",
"array",
",",
"key",
",",
"array",
"[",
"i",
"]",
")",
":",
"array",
"[",
"i",
"]",
";",
"if",
"(",
"space",
")",
"{",
"str",
"+=",
"childIndent",
";",
"}",
"if",
"(",
"typeof",
"item",
"!==",
"'undefined'",
"&&",
"typeof",
"item",
"!==",
"'function'",
")",
"{",
"path",
"[",
"stackIndex",
"]",
"=",
"key",
";",
"str",
"+=",
"stringifyValue",
"(",
"item",
",",
"replacer",
",",
"space",
",",
"childIndent",
")",
";",
"}",
"else",
"{",
"str",
"+=",
"'null'",
"}",
"if",
"(",
"i",
"<",
"array",
".",
"length",
"-",
"1",
")",
"{",
"str",
"+=",
"space",
"?",
"',\\n'",
":",
"','",
";",
"}",
"}",
"// remove current entry from the stack",
"stack",
".",
"length",
"=",
"stackIndex",
";",
"path",
".",
"length",
"=",
"stackIndex",
";",
"str",
"+=",
"space",
"?",
"(",
"'\\n'",
"+",
"indent",
"+",
"']'",
")",
":",
"']'",
";",
"return",
"str",
";",
"}"
] | Stringify an array
@param {Array} array
@param {function | Array.<string | number>} [replacer]
@param {string} [space]
@param {string} [indent]
@return {string} | [
"Stringify",
"an",
"array"
] | ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd | https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/stringify.js#L108-L150 |
22,295 | josdejong/lossless-json | lib/stringify.js | stringifyObject | function stringifyObject(object, replacer, space, indent) {
let childIndent = space ? (indent + space) : undefined;
let first = true;
let str = space ? '{\n' : '{';
if (typeof object.toJSON === 'function') {
return stringify(object.toJSON(), replacer, space);
}
// check for circular reference
if (isCircular(object)) {
return stringifyCircular(object, replacer, space, indent);
}
// add this object to the stack
const stackIndex = stack.length;
stack[stackIndex] = object;
for (let key in object) {
if (object.hasOwnProperty(key)) {
let value = (typeof replacer === 'function')
? replacer.call(object, key, object[key])
: object[key];
if (includeProperty(key, value, replacer)) {
if (first) {
first = false;
}
else {
str += space ? ',\n' : ',';
}
str += space
? (childIndent + '"' + key + '": ')
: ('"' + key + '":');
path[stackIndex] = key;
str += stringifyValue(value, replacer, space, childIndent);
}
}
}
// remove current entry from the stack
stack.length = stackIndex;
path.length = stackIndex;
str += space ? ('\n' + indent + '}') : '}';
return str;
} | javascript | function stringifyObject(object, replacer, space, indent) {
let childIndent = space ? (indent + space) : undefined;
let first = true;
let str = space ? '{\n' : '{';
if (typeof object.toJSON === 'function') {
return stringify(object.toJSON(), replacer, space);
}
// check for circular reference
if (isCircular(object)) {
return stringifyCircular(object, replacer, space, indent);
}
// add this object to the stack
const stackIndex = stack.length;
stack[stackIndex] = object;
for (let key in object) {
if (object.hasOwnProperty(key)) {
let value = (typeof replacer === 'function')
? replacer.call(object, key, object[key])
: object[key];
if (includeProperty(key, value, replacer)) {
if (first) {
first = false;
}
else {
str += space ? ',\n' : ',';
}
str += space
? (childIndent + '"' + key + '": ')
: ('"' + key + '":');
path[stackIndex] = key;
str += stringifyValue(value, replacer, space, childIndent);
}
}
}
// remove current entry from the stack
stack.length = stackIndex;
path.length = stackIndex;
str += space ? ('\n' + indent + '}') : '}';
return str;
} | [
"function",
"stringifyObject",
"(",
"object",
",",
"replacer",
",",
"space",
",",
"indent",
")",
"{",
"let",
"childIndent",
"=",
"space",
"?",
"(",
"indent",
"+",
"space",
")",
":",
"undefined",
";",
"let",
"first",
"=",
"true",
";",
"let",
"str",
"=",
"space",
"?",
"'{\\n'",
":",
"'{'",
";",
"if",
"(",
"typeof",
"object",
".",
"toJSON",
"===",
"'function'",
")",
"{",
"return",
"stringify",
"(",
"object",
".",
"toJSON",
"(",
")",
",",
"replacer",
",",
"space",
")",
";",
"}",
"// check for circular reference",
"if",
"(",
"isCircular",
"(",
"object",
")",
")",
"{",
"return",
"stringifyCircular",
"(",
"object",
",",
"replacer",
",",
"space",
",",
"indent",
")",
";",
"}",
"// add this object to the stack",
"const",
"stackIndex",
"=",
"stack",
".",
"length",
";",
"stack",
"[",
"stackIndex",
"]",
"=",
"object",
";",
"for",
"(",
"let",
"key",
"in",
"object",
")",
"{",
"if",
"(",
"object",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"let",
"value",
"=",
"(",
"typeof",
"replacer",
"===",
"'function'",
")",
"?",
"replacer",
".",
"call",
"(",
"object",
",",
"key",
",",
"object",
"[",
"key",
"]",
")",
":",
"object",
"[",
"key",
"]",
";",
"if",
"(",
"includeProperty",
"(",
"key",
",",
"value",
",",
"replacer",
")",
")",
"{",
"if",
"(",
"first",
")",
"{",
"first",
"=",
"false",
";",
"}",
"else",
"{",
"str",
"+=",
"space",
"?",
"',\\n'",
":",
"','",
";",
"}",
"str",
"+=",
"space",
"?",
"(",
"childIndent",
"+",
"'\"'",
"+",
"key",
"+",
"'\": '",
")",
":",
"(",
"'\"'",
"+",
"key",
"+",
"'\":'",
")",
";",
"path",
"[",
"stackIndex",
"]",
"=",
"key",
";",
"str",
"+=",
"stringifyValue",
"(",
"value",
",",
"replacer",
",",
"space",
",",
"childIndent",
")",
";",
"}",
"}",
"}",
"// remove current entry from the stack",
"stack",
".",
"length",
"=",
"stackIndex",
";",
"path",
".",
"length",
"=",
"stackIndex",
";",
"str",
"+=",
"space",
"?",
"(",
"'\\n'",
"+",
"indent",
"+",
"'}'",
")",
":",
"'}'",
";",
"return",
"str",
";",
"}"
] | Stringify an object
@param {Object} object
@param {function | Array.<string | number>} [replacer]
@param {string} [space]
@param {string} [indent]
@return {string} | [
"Stringify",
"an",
"object"
] | ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd | https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/stringify.js#L160-L208 |
22,296 | josdejong/lossless-json | lib/stringify.js | stringifyCircular | function stringifyCircular (value, replacer, space, indent) {
if (!config().circularRefs) {
throw new Error('Circular reference at "' + stringifyPointer(path) + '"');
}
let pathIndex = stack.indexOf(value);
let circular = {
$ref: stringifyPointer(path.slice(0, pathIndex))
};
return stringifyObject(circular, replacer, space, indent);
} | javascript | function stringifyCircular (value, replacer, space, indent) {
if (!config().circularRefs) {
throw new Error('Circular reference at "' + stringifyPointer(path) + '"');
}
let pathIndex = stack.indexOf(value);
let circular = {
$ref: stringifyPointer(path.slice(0, pathIndex))
};
return stringifyObject(circular, replacer, space, indent);
} | [
"function",
"stringifyCircular",
"(",
"value",
",",
"replacer",
",",
"space",
",",
"indent",
")",
"{",
"if",
"(",
"!",
"config",
"(",
")",
".",
"circularRefs",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Circular reference at \"'",
"+",
"stringifyPointer",
"(",
"path",
")",
"+",
"'\"'",
")",
";",
"}",
"let",
"pathIndex",
"=",
"stack",
".",
"indexOf",
"(",
"value",
")",
";",
"let",
"circular",
"=",
"{",
"$ref",
":",
"stringifyPointer",
"(",
"path",
".",
"slice",
"(",
"0",
",",
"pathIndex",
")",
")",
"}",
";",
"return",
"stringifyObject",
"(",
"circular",
",",
"replacer",
",",
"space",
",",
"indent",
")",
";",
"}"
] | Stringify a circular reference
@param {Object | Array} value
@param {function | Array.<string | number>} [replacer]
@param {string} [space]
@param {string} [indent]
@return {string} | [
"Stringify",
"a",
"circular",
"reference"
] | ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd | https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/stringify.js#L227-L239 |
22,297 | josdejong/lossless-json | lib/stringify.js | includeProperty | function includeProperty (key, value, replacer) {
return typeof value !== 'undefined'
&& typeof value !== 'function'
&& (!Array.isArray(replacer) || contains(replacer, key));
} | javascript | function includeProperty (key, value, replacer) {
return typeof value !== 'undefined'
&& typeof value !== 'function'
&& (!Array.isArray(replacer) || contains(replacer, key));
} | [
"function",
"includeProperty",
"(",
"key",
",",
"value",
",",
"replacer",
")",
"{",
"return",
"typeof",
"value",
"!==",
"'undefined'",
"&&",
"typeof",
"value",
"!==",
"'function'",
"&&",
"(",
"!",
"Array",
".",
"isArray",
"(",
"replacer",
")",
"||",
"contains",
"(",
"replacer",
",",
"key",
")",
")",
";",
"}"
] | Test whether to include a property in a stringified object or not.
@param {string} key
@param {*} value
@param {function(key: string, value: *) | Array<string | number>} [replacer]
@return {boolean} | [
"Test",
"whether",
"to",
"include",
"a",
"property",
"in",
"a",
"stringified",
"object",
"or",
"not",
"."
] | ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd | https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/stringify.js#L248-L252 |
22,298 | josdejong/lossless-json | lib/revive.js | reviveValue | function reviveValue (context, key, value, reviver) {
if (Array.isArray(value)) {
return reviver.call(context, key, reviveArray(value, reviver));
}
else if (value && typeof value === 'object' && !value.isLosslessNumber) {
// note the special case for LosslessNumber,
// we don't want to iterate over the internals of a LosslessNumber
return reviver.call(context, key, reviveObject(value, reviver))
}
else {
return reviver.call(context, key, value)
}
} | javascript | function reviveValue (context, key, value, reviver) {
if (Array.isArray(value)) {
return reviver.call(context, key, reviveArray(value, reviver));
}
else if (value && typeof value === 'object' && !value.isLosslessNumber) {
// note the special case for LosslessNumber,
// we don't want to iterate over the internals of a LosslessNumber
return reviver.call(context, key, reviveObject(value, reviver))
}
else {
return reviver.call(context, key, value)
}
} | [
"function",
"reviveValue",
"(",
"context",
",",
"key",
",",
"value",
",",
"reviver",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"return",
"reviver",
".",
"call",
"(",
"context",
",",
"key",
",",
"reviveArray",
"(",
"value",
",",
"reviver",
")",
")",
";",
"}",
"else",
"if",
"(",
"value",
"&&",
"typeof",
"value",
"===",
"'object'",
"&&",
"!",
"value",
".",
"isLosslessNumber",
")",
"{",
"// note the special case for LosslessNumber,",
"// we don't want to iterate over the internals of a LosslessNumber",
"return",
"reviver",
".",
"call",
"(",
"context",
",",
"key",
",",
"reviveObject",
"(",
"value",
",",
"reviver",
")",
")",
"}",
"else",
"{",
"return",
"reviver",
".",
"call",
"(",
"context",
",",
"key",
",",
"value",
")",
"}",
"}"
] | Revive a value
@param {Object | Array} context
@param {string} key
@param {*} value
@param {function(key: string, value: *)} reviver
@return {*} | [
"Revive",
"a",
"value"
] | ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd | https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/revive.js#L24-L36 |
22,299 | josdejong/lossless-json | lib/revive.js | reviveObject | function reviveObject (object, reviver) {
let revived = {};
for (let key in object) {
if (object.hasOwnProperty(key)) {
revived[key] = reviveValue(object, key, object[key], reviver);
}
}
return revived;
} | javascript | function reviveObject (object, reviver) {
let revived = {};
for (let key in object) {
if (object.hasOwnProperty(key)) {
revived[key] = reviveValue(object, key, object[key], reviver);
}
}
return revived;
} | [
"function",
"reviveObject",
"(",
"object",
",",
"reviver",
")",
"{",
"let",
"revived",
"=",
"{",
"}",
";",
"for",
"(",
"let",
"key",
"in",
"object",
")",
"{",
"if",
"(",
"object",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"revived",
"[",
"key",
"]",
"=",
"reviveValue",
"(",
"object",
",",
"key",
",",
"object",
"[",
"key",
"]",
",",
"reviver",
")",
";",
"}",
"}",
"return",
"revived",
";",
"}"
] | Revive the properties of an object
@param {Object} object
@param {function} reviver
@return {Object} | [
"Revive",
"the",
"properties",
"of",
"an",
"object"
] | ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd | https://github.com/josdejong/lossless-json/blob/ed6c201b37b5583d2c9c7a7d0b5fc1b3f01519bd/lib/revive.js#L44-L54 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.