repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
wavesoft/jbb
encoder.js
encodeArray_PRIM_BULK_PLAIN
function encodeArray_PRIM_BULK_PLAIN( encoder, data, properties ) { // // Bulk Array of Primitives (PRIM_BULK_PLAIN) // // ........ + Signature ID // 01111000 [16-bit] // // Lookup signature var eid = encoder.getSignatureID( properties ), weave = []; encoder.counters.arr_prim_bulk_plain+=1; encoder.log(LOG.ARR, "array.prim.bulk_plain, len="+data.length+ ", signature="+properties.toString()+ ", eid="+eid+" ["); encoder.logIndent(1); // Put header encoder.stream8.write( pack1b( ARR_OP.PRIM_BULK_PLAIN ) ); encoder.stream16.write( pack2b( eid, false ) ); encoder.counters.arr_hdr+=3; // Write bulked properties var weaveArrays = []; for (var i=0, pl=properties.length; i<pl; ++i) { // Read property of all entries var prop = [], p = properties[i]; for (var j=0, el=data.length; j<el; ++j) { weaveArrays.push( data[j][p] ); } } // Encode cmpact weaved array encodeArray( encoder, weaveArrays ); // Close log group encoder.logIndent(-1); encoder.log(LOG.ARR, "]"); }
javascript
function encodeArray_PRIM_BULK_PLAIN( encoder, data, properties ) { // // Bulk Array of Primitives (PRIM_BULK_PLAIN) // // ........ + Signature ID // 01111000 [16-bit] // // Lookup signature var eid = encoder.getSignatureID( properties ), weave = []; encoder.counters.arr_prim_bulk_plain+=1; encoder.log(LOG.ARR, "array.prim.bulk_plain, len="+data.length+ ", signature="+properties.toString()+ ", eid="+eid+" ["); encoder.logIndent(1); // Put header encoder.stream8.write( pack1b( ARR_OP.PRIM_BULK_PLAIN ) ); encoder.stream16.write( pack2b( eid, false ) ); encoder.counters.arr_hdr+=3; // Write bulked properties var weaveArrays = []; for (var i=0, pl=properties.length; i<pl; ++i) { // Read property of all entries var prop = [], p = properties[i]; for (var j=0, el=data.length; j<el; ++j) { weaveArrays.push( data[j][p] ); } } // Encode cmpact weaved array encodeArray( encoder, weaveArrays ); // Close log group encoder.logIndent(-1); encoder.log(LOG.ARR, "]"); }
[ "function", "encodeArray_PRIM_BULK_PLAIN", "(", "encoder", ",", "data", ",", "properties", ")", "{", "var", "eid", "=", "encoder", ".", "getSignatureID", "(", "properties", ")", ",", "weave", "=", "[", "]", ";", "encoder", ".", "counters", ".", "arr_prim_bulk_plain", "+=", "1", ";", "encoder", ".", "log", "(", "LOG", ".", "ARR", ",", "\"array.prim.bulk_plain, len=\"", "+", "data", ".", "length", "+", "\", signature=\"", "+", "properties", ".", "toString", "(", ")", "+", "\", eid=\"", "+", "eid", "+", "\" [\"", ")", ";", "encoder", ".", "logIndent", "(", "1", ")", ";", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "ARR_OP", ".", "PRIM_BULK_PLAIN", ")", ")", ";", "encoder", ".", "stream16", ".", "write", "(", "pack2b", "(", "eid", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "arr_hdr", "+=", "3", ";", "var", "weaveArrays", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "pl", "=", "properties", ".", "length", ";", "i", "<", "pl", ";", "++", "i", ")", "{", "var", "prop", "=", "[", "]", ",", "p", "=", "properties", "[", "i", "]", ";", "for", "(", "var", "j", "=", "0", ",", "el", "=", "data", ".", "length", ";", "j", "<", "el", ";", "++", "j", ")", "{", "weaveArrays", ".", "push", "(", "data", "[", "j", "]", "[", "p", "]", ")", ";", "}", "}", "encodeArray", "(", "encoder", ",", "weaveArrays", ")", ";", "encoder", ".", "logIndent", "(", "-", "1", ")", ";", "encoder", ".", "log", "(", "LOG", ".", "ARR", ",", "\"]\"", ")", ";", "}" ]
Encode array data as bulk of plain objects
[ "Encode", "array", "data", "as", "bulk", "of", "plain", "objects" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2178-L2219
train
wavesoft/jbb
encoder.js
encodeLIREF
function encodeLIREF(encoder, op8, op16, local_ids, xrid) { var DEBUG_THIS = false; // Check if the given object is part of the array var id=-1, i=0, l=local_ids.length; for (;i<l;++i) { if (i > 65535) break; if (local_ids[i] === xrid) { id = i; break; } } if (id === -1) { // IREF op8.push( pack1b( PRIM_BULK_KNOWN_OP.IREF | ((xrid >> 16) & 0xF), false ) ); op16.push( pack2b( xrid & 0xFFFF, false ) ); encoder.counters.op_iref+=3; local_ids.push(xrid); if (DEBUG_THIS) console.log("->- IREF(",xrid,",",id,")"); } else if (id < 128) { // LREF_7 op8.push( pack1b( PRIM_BULK_KNOWN_OP.LREF_7 | (id & 0x7F), false ) ); encoder.counters.op_iref+=1; if (DEBUG_THIS) console.log("->- LREF_7(",xrid,",",id,")"); } else if (id < 2048) { // LREF_11 op8.push( pack1b( PRIM_BULK_KNOWN_OP.LREF_11 | ((id >> 8) & 0x7), false ) ); op8.push( pack1b( id & 0xFF, false ) ); encoder.counters.op_iref+=2; if (DEBUG_THIS) console.log("->- LREF_11(",xrid,",",id,")"); } else if (id < 65536) { // LREF_16 op8.push( pack1b( PRIM_BULK_KNOWN_OP.LREF_16, false ) ); op16.push( pack2b( id & 0xFFFF, false ) ); encoder.counters.op_iref+=3; if (DEBUG_THIS) console.log("->- LREF_16(",xrid,",",id,")"); } }
javascript
function encodeLIREF(encoder, op8, op16, local_ids, xrid) { var DEBUG_THIS = false; // Check if the given object is part of the array var id=-1, i=0, l=local_ids.length; for (;i<l;++i) { if (i > 65535) break; if (local_ids[i] === xrid) { id = i; break; } } if (id === -1) { // IREF op8.push( pack1b( PRIM_BULK_KNOWN_OP.IREF | ((xrid >> 16) & 0xF), false ) ); op16.push( pack2b( xrid & 0xFFFF, false ) ); encoder.counters.op_iref+=3; local_ids.push(xrid); if (DEBUG_THIS) console.log("->- IREF(",xrid,",",id,")"); } else if (id < 128) { // LREF_7 op8.push( pack1b( PRIM_BULK_KNOWN_OP.LREF_7 | (id & 0x7F), false ) ); encoder.counters.op_iref+=1; if (DEBUG_THIS) console.log("->- LREF_7(",xrid,",",id,")"); } else if (id < 2048) { // LREF_11 op8.push( pack1b( PRIM_BULK_KNOWN_OP.LREF_11 | ((id >> 8) & 0x7), false ) ); op8.push( pack1b( id & 0xFF, false ) ); encoder.counters.op_iref+=2; if (DEBUG_THIS) console.log("->- LREF_11(",xrid,",",id,")"); } else if (id < 65536) { // LREF_16 op8.push( pack1b( PRIM_BULK_KNOWN_OP.LREF_16, false ) ); op16.push( pack2b( id & 0xFFFF, false ) ); encoder.counters.op_iref+=3; if (DEBUG_THIS) console.log("->- LREF_16(",xrid,",",id,")"); } }
[ "function", "encodeLIREF", "(", "encoder", ",", "op8", ",", "op16", ",", "local_ids", ",", "xrid", ")", "{", "var", "DEBUG_THIS", "=", "false", ";", "var", "id", "=", "-", "1", ",", "i", "=", "0", ",", "l", "=", "local_ids", ".", "length", ";", "for", "(", ";", "i", "<", "l", ";", "++", "i", ")", "{", "if", "(", "i", ">", "65535", ")", "break", ";", "if", "(", "local_ids", "[", "i", "]", "===", "xrid", ")", "{", "id", "=", "i", ";", "break", ";", "}", "}", "if", "(", "id", "===", "-", "1", ")", "{", "op8", ".", "push", "(", "pack1b", "(", "PRIM_BULK_KNOWN_OP", ".", "IREF", "|", "(", "(", "xrid", ">>", "16", ")", "&", "0xF", ")", ",", "false", ")", ")", ";", "op16", ".", "push", "(", "pack2b", "(", "xrid", "&", "0xFFFF", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "op_iref", "+=", "3", ";", "local_ids", ".", "push", "(", "xrid", ")", ";", "if", "(", "DEBUG_THIS", ")", "console", ".", "log", "(", "\"->- IREF(\"", ",", "xrid", ",", "\",\"", ",", "id", ",", "\")\"", ")", ";", "}", "else", "if", "(", "id", "<", "128", ")", "{", "op8", ".", "push", "(", "pack1b", "(", "PRIM_BULK_KNOWN_OP", ".", "LREF_7", "|", "(", "id", "&", "0x7F", ")", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "op_iref", "+=", "1", ";", "if", "(", "DEBUG_THIS", ")", "console", ".", "log", "(", "\"->- LREF_7(\"", ",", "xrid", ",", "\",\"", ",", "id", ",", "\")\"", ")", ";", "}", "else", "if", "(", "id", "<", "2048", ")", "{", "op8", ".", "push", "(", "pack1b", "(", "PRIM_BULK_KNOWN_OP", ".", "LREF_11", "|", "(", "(", "id", ">>", "8", ")", "&", "0x7", ")", ",", "false", ")", ")", ";", "op8", ".", "push", "(", "pack1b", "(", "id", "&", "0xFF", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "op_iref", "+=", "2", ";", "if", "(", "DEBUG_THIS", ")", "console", ".", "log", "(", "\"->- LREF_11(\"", ",", "xrid", ",", "\",\"", ",", "id", ",", "\")\"", ")", ";", "}", "else", "if", "(", "id", "<", "65536", ")", "{", "op8", ".", "push", "(", "pack1b", "(", "PRIM_BULK_KNOWN_OP", ".", "LREF_16", ",", "false", ")", ")", ";", "op16", ".", "push", "(", "pack2b", "(", "id", "&", "0xFFFF", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "op_iref", "+=", "3", ";", "if", "(", "DEBUG_THIS", ")", "console", ".", "log", "(", "\"->- LREF_16(\"", ",", "xrid", ",", "\",\"", ",", "id", ",", "\")\"", ")", ";", "}", "}" ]
Helper function to encode local-lookup internal references
[ "Helper", "function", "to", "encode", "local", "-", "lookup", "internal", "references" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2225-L2260
train
wavesoft/jbb
encoder.js
encodeArray_PRIM_SHORT
function encodeArray_PRIM_SHORT( encoder, data ) { // // Short Primitive Array (PRIM_SHORT) // // ........ // 01111100 // // Open log group encoder.counters.arr_prim_short+=1; encoder.log(LOG.ARR, "array.prim.short, len="+data.length+ ", peek="+data[0]+" ["); encoder.logIndent(1); // Encode primitives one after the other encoder.stream8.write( pack1b( ARR_OP.PRIM_SHORT ) ); encoder.stream8.write( pack1b( data.length, false ) ); encoder.counters.arr_hdr+=2; // Encode each primitive individually for (var i=0, llen=data.length; i<llen; ++i) { encodePrimitive( encoder, data[i] ); } // Close log group encoder.logIndent(-1); encoder.log(LOG.ARR, "]"); }
javascript
function encodeArray_PRIM_SHORT( encoder, data ) { // // Short Primitive Array (PRIM_SHORT) // // ........ // 01111100 // // Open log group encoder.counters.arr_prim_short+=1; encoder.log(LOG.ARR, "array.prim.short, len="+data.length+ ", peek="+data[0]+" ["); encoder.logIndent(1); // Encode primitives one after the other encoder.stream8.write( pack1b( ARR_OP.PRIM_SHORT ) ); encoder.stream8.write( pack1b( data.length, false ) ); encoder.counters.arr_hdr+=2; // Encode each primitive individually for (var i=0, llen=data.length; i<llen; ++i) { encodePrimitive( encoder, data[i] ); } // Close log group encoder.logIndent(-1); encoder.log(LOG.ARR, "]"); }
[ "function", "encodeArray_PRIM_SHORT", "(", "encoder", ",", "data", ")", "{", "encoder", ".", "counters", ".", "arr_prim_short", "+=", "1", ";", "encoder", ".", "log", "(", "LOG", ".", "ARR", ",", "\"array.prim.short, len=\"", "+", "data", ".", "length", "+", "\", peek=\"", "+", "data", "[", "0", "]", "+", "\" [\"", ")", ";", "encoder", ".", "logIndent", "(", "1", ")", ";", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "ARR_OP", ".", "PRIM_SHORT", ")", ")", ";", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "data", ".", "length", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "arr_hdr", "+=", "2", ";", "for", "(", "var", "i", "=", "0", ",", "llen", "=", "data", ".", "length", ";", "i", "<", "llen", ";", "++", "i", ")", "{", "encodePrimitive", "(", "encoder", ",", "data", "[", "i", "]", ")", ";", "}", "encoder", ".", "logIndent", "(", "-", "1", ")", ";", "encoder", ".", "log", "(", "LOG", ".", "ARR", ",", "\"]\"", ")", ";", "}" ]
Encode array data as a short array of primitives
[ "Encode", "array", "data", "as", "a", "short", "array", "of", "primitives" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2488-L2517
train
wavesoft/jbb
encoder.js
encodeArray_PRIM_REPEATED
function encodeArray_PRIM_REPEATED( encoder, data ) { // // Repeated Primitive Array (PRIM_REPEATED) // // ....... . + Signature ID // 0111100 [LN] [16-bit] // encoder.counters.arr_prim_repeated+=1; encoder.log(LOG.ARR, "array.prim.repeated, len="+data.length+ ", peek="+data[0]); if (data.length < UINT16_MAX) { // 16-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_REPEATED | NUMTYPE_LN.UINT16 ) ); encoder.stream16.write( pack2b( data.length, false ) ); encoder.counters.arr_hdr+=3; } else { // 32-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_REPEATED | NUMTYPE_LN.UINT32 ) ); encoder.stream32.write( pack4b( data.length, false ) ); encoder.counters.arr_hdr+=5; } // Encode the short array encodePrimitive( encoder, data[0] ); }
javascript
function encodeArray_PRIM_REPEATED( encoder, data ) { // // Repeated Primitive Array (PRIM_REPEATED) // // ....... . + Signature ID // 0111100 [LN] [16-bit] // encoder.counters.arr_prim_repeated+=1; encoder.log(LOG.ARR, "array.prim.repeated, len="+data.length+ ", peek="+data[0]); if (data.length < UINT16_MAX) { // 16-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_REPEATED | NUMTYPE_LN.UINT16 ) ); encoder.stream16.write( pack2b( data.length, false ) ); encoder.counters.arr_hdr+=3; } else { // 32-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_REPEATED | NUMTYPE_LN.UINT32 ) ); encoder.stream32.write( pack4b( data.length, false ) ); encoder.counters.arr_hdr+=5; } // Encode the short array encodePrimitive( encoder, data[0] ); }
[ "function", "encodeArray_PRIM_REPEATED", "(", "encoder", ",", "data", ")", "{", "encoder", ".", "counters", ".", "arr_prim_repeated", "+=", "1", ";", "encoder", ".", "log", "(", "LOG", ".", "ARR", ",", "\"array.prim.repeated, len=\"", "+", "data", ".", "length", "+", "\", peek=\"", "+", "data", "[", "0", "]", ")", ";", "if", "(", "data", ".", "length", "<", "UINT16_MAX", ")", "{", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "ARR_OP", ".", "PRIM_REPEATED", "|", "NUMTYPE_LN", ".", "UINT16", ")", ")", ";", "encoder", ".", "stream16", ".", "write", "(", "pack2b", "(", "data", ".", "length", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "arr_hdr", "+=", "3", ";", "}", "else", "{", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "ARR_OP", ".", "PRIM_REPEATED", "|", "NUMTYPE_LN", ".", "UINT32", ")", ")", ";", "encoder", ".", "stream32", ".", "write", "(", "pack4b", "(", "data", ".", "length", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "arr_hdr", "+=", "5", ";", "}", "encodePrimitive", "(", "encoder", ",", "data", "[", "0", "]", ")", ";", "}" ]
Encode array data as one repeated chunk
[ "Encode", "array", "data", "as", "one", "repeated", "chunk" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2522-L2548
train
wavesoft/jbb
encoder.js
encodeArray_PRIM_RAW
function encodeArray_PRIM_RAW( encoder, data ) { // // Raw Primitive Array (PRIM_RAW) // // ....... . + Signature ID // 0110101 [LN] [16-bit] // // Write chunk header encoder.counters.arr_prim_raw+=1; encoder.log(LOG.ARR, "array.prim.raw, len="+data.length+ ", peek="+data[0]+" ["); encoder.logIndent(1); if (data.length < UINT16_MAX) { // 16-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_RAW | NUMTYPE_LN.UINT16 ) ); encoder.stream16.write( pack2b( data.length, false ) ); encoder.counters.arr_hdr+=3; } else { // 32-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_RAW | NUMTYPE_LN.UINT32 ) ); encoder.stream32.write( pack4b( data.length, false ) ); encoder.counters.arr_hdr+=5; } // Write primitives for (var i=0, l=data.length; i<l; ++i) encodePrimitive( encoder, data[i] ); // Close log group encoder.logIndent(-1); encoder.log(LOG.ARR, "]"); }
javascript
function encodeArray_PRIM_RAW( encoder, data ) { // // Raw Primitive Array (PRIM_RAW) // // ....... . + Signature ID // 0110101 [LN] [16-bit] // // Write chunk header encoder.counters.arr_prim_raw+=1; encoder.log(LOG.ARR, "array.prim.raw, len="+data.length+ ", peek="+data[0]+" ["); encoder.logIndent(1); if (data.length < UINT16_MAX) { // 16-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_RAW | NUMTYPE_LN.UINT16 ) ); encoder.stream16.write( pack2b( data.length, false ) ); encoder.counters.arr_hdr+=3; } else { // 32-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_RAW | NUMTYPE_LN.UINT32 ) ); encoder.stream32.write( pack4b( data.length, false ) ); encoder.counters.arr_hdr+=5; } // Write primitives for (var i=0, l=data.length; i<l; ++i) encodePrimitive( encoder, data[i] ); // Close log group encoder.logIndent(-1); encoder.log(LOG.ARR, "]"); }
[ "function", "encodeArray_PRIM_RAW", "(", "encoder", ",", "data", ")", "{", "encoder", ".", "counters", ".", "arr_prim_raw", "+=", "1", ";", "encoder", ".", "log", "(", "LOG", ".", "ARR", ",", "\"array.prim.raw, len=\"", "+", "data", ".", "length", "+", "\", peek=\"", "+", "data", "[", "0", "]", "+", "\" [\"", ")", ";", "encoder", ".", "logIndent", "(", "1", ")", ";", "if", "(", "data", ".", "length", "<", "UINT16_MAX", ")", "{", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "ARR_OP", ".", "PRIM_RAW", "|", "NUMTYPE_LN", ".", "UINT16", ")", ")", ";", "encoder", ".", "stream16", ".", "write", "(", "pack2b", "(", "data", ".", "length", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "arr_hdr", "+=", "3", ";", "}", "else", "{", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "ARR_OP", ".", "PRIM_RAW", "|", "NUMTYPE_LN", ".", "UINT32", ")", ")", ";", "encoder", ".", "stream32", ".", "write", "(", "pack4b", "(", "data", ".", "length", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "arr_hdr", "+=", "5", ";", "}", "for", "(", "var", "i", "=", "0", ",", "l", "=", "data", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "encodePrimitive", "(", "encoder", ",", "data", "[", "i", "]", ")", ";", "encoder", ".", "logIndent", "(", "-", "1", ")", ";", "encoder", ".", "log", "(", "LOG", ".", "ARR", ",", "\"]\"", ")", ";", "}" ]
Encode a number of consecutive primitives
[ "Encode", "a", "number", "of", "consecutive", "primitives" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2553-L2586
train
wavesoft/jbb
encoder.js
encodeArray_PRIM_CHUNK
function encodeArray_PRIM_CHUNK( encoder, data, chunks ) { // // Chunked Primitive Array (PRIM_CHUNK) // // ........ // 01111101 // var chunk, chunkType, chunkSize, chunkSubType, part, num_flag = 0x2; // Check if all chunks are numeric if (!chunks.is_numeric) num_flag = 0; // Write chunk header if (data.length < UINT16_MAX) { // 16-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_CHUNK | NUMTYPE_LN.UINT16 | num_flag ) ); encoder.stream16.write( pack2b( data.length, false ) ); encoder.counters.arr_hdr+=3; } else { // 32-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_CHUNK | NUMTYPE_LN.UINT32 | num_flag ) ); encoder.stream32.write( pack4b( data.length, false ) ); encoder.counters.arr_hdr+=5; } // Log encoder.counters.arr_prim_chunk+=1; encoder.log(LOG.ARR, "array.prim.chunk, len="+data.length+ ", chunks="+chunks.length+", peek="+data[0]+" ["); encoder.logIndent(1); // Encode individual chunks for (var i=0, ofs=0, llen=chunks.length; i<llen; ++i) { encodeArray_Chunk( encoder, data.slice(ofs, ofs+chunks[i][1]), chunks[i] ); ofs += chunks[i][1]; } // Write chunk termination // encoder.stream8.write( pack1b( ARR_OP.PRIM_CHUNK_END ) ); // encoder.counters.arr_hdr+=1; encoder.logIndent(-1); encoder.log(LOG.ARR, "]"); }
javascript
function encodeArray_PRIM_CHUNK( encoder, data, chunks ) { // // Chunked Primitive Array (PRIM_CHUNK) // // ........ // 01111101 // var chunk, chunkType, chunkSize, chunkSubType, part, num_flag = 0x2; // Check if all chunks are numeric if (!chunks.is_numeric) num_flag = 0; // Write chunk header if (data.length < UINT16_MAX) { // 16-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_CHUNK | NUMTYPE_LN.UINT16 | num_flag ) ); encoder.stream16.write( pack2b( data.length, false ) ); encoder.counters.arr_hdr+=3; } else { // 32-bit length prefix encoder.stream8.write( pack1b( ARR_OP.PRIM_CHUNK | NUMTYPE_LN.UINT32 | num_flag ) ); encoder.stream32.write( pack4b( data.length, false ) ); encoder.counters.arr_hdr+=5; } // Log encoder.counters.arr_prim_chunk+=1; encoder.log(LOG.ARR, "array.prim.chunk, len="+data.length+ ", chunks="+chunks.length+", peek="+data[0]+" ["); encoder.logIndent(1); // Encode individual chunks for (var i=0, ofs=0, llen=chunks.length; i<llen; ++i) { encodeArray_Chunk( encoder, data.slice(ofs, ofs+chunks[i][1]), chunks[i] ); ofs += chunks[i][1]; } // Write chunk termination // encoder.stream8.write( pack1b( ARR_OP.PRIM_CHUNK_END ) ); // encoder.counters.arr_hdr+=1; encoder.logIndent(-1); encoder.log(LOG.ARR, "]"); }
[ "function", "encodeArray_PRIM_CHUNK", "(", "encoder", ",", "data", ",", "chunks", ")", "{", "var", "chunk", ",", "chunkType", ",", "chunkSize", ",", "chunkSubType", ",", "part", ",", "num_flag", "=", "0x2", ";", "if", "(", "!", "chunks", ".", "is_numeric", ")", "num_flag", "=", "0", ";", "if", "(", "data", ".", "length", "<", "UINT16_MAX", ")", "{", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "ARR_OP", ".", "PRIM_CHUNK", "|", "NUMTYPE_LN", ".", "UINT16", "|", "num_flag", ")", ")", ";", "encoder", ".", "stream16", ".", "write", "(", "pack2b", "(", "data", ".", "length", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "arr_hdr", "+=", "3", ";", "}", "else", "{", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "ARR_OP", ".", "PRIM_CHUNK", "|", "NUMTYPE_LN", ".", "UINT32", "|", "num_flag", ")", ")", ";", "encoder", ".", "stream32", ".", "write", "(", "pack4b", "(", "data", ".", "length", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "arr_hdr", "+=", "5", ";", "}", "encoder", ".", "counters", ".", "arr_prim_chunk", "+=", "1", ";", "encoder", ".", "log", "(", "LOG", ".", "ARR", ",", "\"array.prim.chunk, len=\"", "+", "data", ".", "length", "+", "\", chunks=\"", "+", "chunks", ".", "length", "+", "\", peek=\"", "+", "data", "[", "0", "]", "+", "\" [\"", ")", ";", "encoder", ".", "logIndent", "(", "1", ")", ";", "for", "(", "var", "i", "=", "0", ",", "ofs", "=", "0", ",", "llen", "=", "chunks", ".", "length", ";", "i", "<", "llen", ";", "++", "i", ")", "{", "encodeArray_Chunk", "(", "encoder", ",", "data", ".", "slice", "(", "ofs", ",", "ofs", "+", "chunks", "[", "i", "]", "[", "1", "]", ")", ",", "chunks", "[", "i", "]", ")", ";", "ofs", "+=", "chunks", "[", "i", "]", "[", "1", "]", ";", "}", "encoder", ".", "logIndent", "(", "-", "1", ")", ";", "encoder", ".", "log", "(", "LOG", ".", "ARR", ",", "\"]\"", ")", ";", "}" ]
Encode array data as one or more chunks of other types
[ "Encode", "array", "data", "as", "one", "or", "more", "chunks", "of", "other", "types" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2591-L2635
train
wavesoft/jbb
encoder.js
encodeArray_EMPTY
function encodeArray_EMPTY( encoder ) { // // Empty Array (EMPTY) // // ........ // 01111110 // encoder.counters.arr_empty+=1; encoder.log(LOG.ARR, "array.empty"); encoder.stream8.write( pack1b( ARR_OP.EMPTY ) ); encoder.counters.op_prm+=1; }
javascript
function encodeArray_EMPTY( encoder ) { // // Empty Array (EMPTY) // // ........ // 01111110 // encoder.counters.arr_empty+=1; encoder.log(LOG.ARR, "array.empty"); encoder.stream8.write( pack1b( ARR_OP.EMPTY ) ); encoder.counters.op_prm+=1; }
[ "function", "encodeArray_EMPTY", "(", "encoder", ")", "{", "encoder", ".", "counters", ".", "arr_empty", "+=", "1", ";", "encoder", ".", "log", "(", "LOG", ".", "ARR", ",", "\"array.empty\"", ")", ";", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "ARR_OP", ".", "EMPTY", ")", ")", ";", "encoder", ".", "counters", ".", "op_prm", "+=", "1", ";", "}" ]
Encode array data as an empty array
[ "Encode", "array", "data", "as", "an", "empty", "array" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2640-L2654
train
wavesoft/jbb
encoder.js
encodeArray_Chunk
function encodeArray_Chunk( encoder, data, chunk ) { var n_type, na; // console.log(">>> CFWA Chunk="+_ARR_CHUNK[chunk[2]],", from=" + chunk[0] + ", len=" + chunk[1] + ", arr=" + data.length); // console.log(">>> =",data); // Encode array component according to chunk type switch (chunk[2]) { // Encode as an array of primitives case ARR_CHUNK.PRIMITIVES: if (data.length < 256) { encodeArray_PRIM_SHORT( encoder, data ); } else { encodeArray_PRIM_RAW( encoder, data ); } break; // Encode as a repeated array case ARR_CHUNK.REPEAT: // Prioritize numeric type suggested by chunk n_type = chunk[4]; if (n_type === NUMTYPE.UNKNOWN) n_type = getTypedArrayType( data ); // Check if the repeated items are numeric or primitivie if ( n_type <= NUMTYPE.NUMERIC ) { /* If that's numeric, perform fast numeric analysis to find it's type. */ if (n_type === NUMTYPE.NUMERIC) { na = analyzeNumericArray( data, false ); n_type = na.type; } // Encode numeric repeated array if number encodeArray_NUM_REPEATED( encoder, data, n_type ); } else { // Encode primitive repeated array otherwise encodeArray_PRIM_REPEATED( encoder, data ); } break; // encode as a numeric array case ARR_CHUNK.NUMERIC: encodeArray_Numeric( encoder, data, chunk[3] ); break; // Encode as a bulk of plain objects case ARR_CHUNK.BULK_PLAIN: encodeArray_PRIM_BULK_PLAIN( encoder, data, chunk[3] ); break; // Encode as a bulk of known objects case ARR_CHUNK.BULK_KNOWN: encodeArray_PRIM_BULK_KNOWN( encoder, data, chunk[3] ); break; // Just precaution default: throw new Errors.EncodeError('Trying to encode an unknown chunk (type='+chunkType+')!'); } }
javascript
function encodeArray_Chunk( encoder, data, chunk ) { var n_type, na; // console.log(">>> CFWA Chunk="+_ARR_CHUNK[chunk[2]],", from=" + chunk[0] + ", len=" + chunk[1] + ", arr=" + data.length); // console.log(">>> =",data); // Encode array component according to chunk type switch (chunk[2]) { // Encode as an array of primitives case ARR_CHUNK.PRIMITIVES: if (data.length < 256) { encodeArray_PRIM_SHORT( encoder, data ); } else { encodeArray_PRIM_RAW( encoder, data ); } break; // Encode as a repeated array case ARR_CHUNK.REPEAT: // Prioritize numeric type suggested by chunk n_type = chunk[4]; if (n_type === NUMTYPE.UNKNOWN) n_type = getTypedArrayType( data ); // Check if the repeated items are numeric or primitivie if ( n_type <= NUMTYPE.NUMERIC ) { /* If that's numeric, perform fast numeric analysis to find it's type. */ if (n_type === NUMTYPE.NUMERIC) { na = analyzeNumericArray( data, false ); n_type = na.type; } // Encode numeric repeated array if number encodeArray_NUM_REPEATED( encoder, data, n_type ); } else { // Encode primitive repeated array otherwise encodeArray_PRIM_REPEATED( encoder, data ); } break; // encode as a numeric array case ARR_CHUNK.NUMERIC: encodeArray_Numeric( encoder, data, chunk[3] ); break; // Encode as a bulk of plain objects case ARR_CHUNK.BULK_PLAIN: encodeArray_PRIM_BULK_PLAIN( encoder, data, chunk[3] ); break; // Encode as a bulk of known objects case ARR_CHUNK.BULK_KNOWN: encodeArray_PRIM_BULK_KNOWN( encoder, data, chunk[3] ); break; // Just precaution default: throw new Errors.EncodeError('Trying to encode an unknown chunk (type='+chunkType+')!'); } }
[ "function", "encodeArray_Chunk", "(", "encoder", ",", "data", ",", "chunk", ")", "{", "var", "n_type", ",", "na", ";", "switch", "(", "chunk", "[", "2", "]", ")", "{", "case", "ARR_CHUNK", ".", "PRIMITIVES", ":", "if", "(", "data", ".", "length", "<", "256", ")", "{", "encodeArray_PRIM_SHORT", "(", "encoder", ",", "data", ")", ";", "}", "else", "{", "encodeArray_PRIM_RAW", "(", "encoder", ",", "data", ")", ";", "}", "break", ";", "case", "ARR_CHUNK", ".", "REPEAT", ":", "n_type", "=", "chunk", "[", "4", "]", ";", "if", "(", "n_type", "===", "NUMTYPE", ".", "UNKNOWN", ")", "n_type", "=", "getTypedArrayType", "(", "data", ")", ";", "if", "(", "n_type", "<=", "NUMTYPE", ".", "NUMERIC", ")", "{", "if", "(", "n_type", "===", "NUMTYPE", ".", "NUMERIC", ")", "{", "na", "=", "analyzeNumericArray", "(", "data", ",", "false", ")", ";", "n_type", "=", "na", ".", "type", ";", "}", "encodeArray_NUM_REPEATED", "(", "encoder", ",", "data", ",", "n_type", ")", ";", "}", "else", "{", "encodeArray_PRIM_REPEATED", "(", "encoder", ",", "data", ")", ";", "}", "break", ";", "case", "ARR_CHUNK", ".", "NUMERIC", ":", "encodeArray_Numeric", "(", "encoder", ",", "data", ",", "chunk", "[", "3", "]", ")", ";", "break", ";", "case", "ARR_CHUNK", ".", "BULK_PLAIN", ":", "encodeArray_PRIM_BULK_PLAIN", "(", "encoder", ",", "data", ",", "chunk", "[", "3", "]", ")", ";", "break", ";", "case", "ARR_CHUNK", ".", "BULK_KNOWN", ":", "encodeArray_PRIM_BULK_KNOWN", "(", "encoder", ",", "data", ",", "chunk", "[", "3", "]", ")", ";", "break", ";", "default", ":", "throw", "new", "Errors", ".", "EncodeError", "(", "'Trying to encode an unknown chunk (type='", "+", "chunkType", "+", "')!'", ")", ";", "}", "}" ]
Encode an array chunk, previously constructed by chunkForwardanalysis
[ "Encode", "an", "array", "chunk", "previously", "constructed", "by", "chunkForwardanalysis" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2660-L2724
train
wavesoft/jbb
encoder.js
encodeArray_Numeric
function encodeArray_Numeric( encoder, data, n_type ) { var na, keep = true, v, lv, same = true; // Separate small array case if (data.length < 256) { // If the numeric type is unknown, try to find actual type if (n_type === NUMTYPE.NUMERIC) { // Perform fast numeric analysis (skip delta) na = analyzeNumericArray( data, false ); // Check if this is not a numeric array (getTypedArrayType can fail // in Array cases since it's optimised for speed, not accuracy) if (na === null) { keep = false; } else { n_type = na.type; same = na.same; } } else { // Test for same lv = data[0]; for (var i=1, len=data.length; i<len; ++i) { v = data[i]; if (v !== lv) { same = false; break; } lv = v; } } // If for any reason this array is not numeric, don't // try to encode it if (keep) { if (same) { // If all values are the same, prefer repeated instead of short // console.log(">ARR>",data.length,"itms as REPEATED"); encodeArray_NUM_REPEATED( encoder, data, n_type ); } else { // Encode small numeric array // console.log(">ARR>",data.length,"itms as SHORT"); encodeArray_NUM_SHORT( encoder, data, n_type ); } } else { // Pass it to primitive encoder encodeArray_Primitive( encoder, data ); } } else { // Perform full numeric type analysis and encode numeric array na = analyzeNumericArray( data, true ); // Check if this is not a numeric array (getTypedArrayType can fail // in Array cases since it's optimised for speed, not accuracy) if (na !== null) { // Define generic type if (n_type === NUMTYPE.NUMERIC) { n_type = na.type; } // If all values are the same, encode using same numeric encoding if (na.same) { // console.log(">ARR>",data.length,"itms as REPEATED"); encodeArray_NUM_REPEATED( encoder, data, n_type ); return; } // If we have more than <thresshold> items with the same // value, break into chunked array if (na.psame >= encoder.optimize.repeat_break_thresshold) { encodeArray_Primitive( encoder, data ); return; } // Perform detailed analysis for downscaling and delta-encoding var n_dws = getDownscaleType( n_type, na ); // console.log(">>[DWS]>> n_type="+_NUMTYPE[n_type]+", analysis=",na,":",_NUMTYPE[n_dws]); // Get sizes of different encoding approaches var b_raw = sizeOfType( n_type ), b_dws = sizeOfType( n_dws ), b_delta = sizeOfType( na.delta_type ), b_min = Math.min(b_raw, b_dws, b_delta); // Pick best, according to speed preference if (b_min === b_raw) { // Encode raw // console.log(">ARR>",data.length,"itms as RAW (type="+_NUMTYPE[n_type]+")"); encodeArray_NUM_RAW( encoder, data, n_type ); } else if (b_min === b_dws) { // Encode downscaled // console.log(">ARR>",data.length,"itms as DOWNSCALED"); encodeArray_NUM_DWS( encoder, data, n_type, n_dws ); } else if (b_min === b_delta) { // Encode delta if ( encoder.optimize.enable_delta ) { // console.log(">ARR>",data.length,"itms as DELTA"); if (na.dmode == 1) { encodeArray_NUM_DELTA_INT( encoder, data, n_type, na.delta_type ); return; } else if ((na.dmode == 2) && encoder.optimize.float_int_downscale) { encodeArray_NUM_DELTA_FLOAT( encoder, data, n_type, na.delta_type, na.mean, na.fscale ); return; } } // Fallback case -> Raw encode // console.log(">ARR>",data.length,"itms as RAW (type="+_NUMTYPE[n_type]+") (Fallback)"); encodeArray_NUM_RAW( encoder, data, n_type ); } } else { // Pass it to primitive encoder encodeArray_Primitive( encoder, data ); } } }
javascript
function encodeArray_Numeric( encoder, data, n_type ) { var na, keep = true, v, lv, same = true; // Separate small array case if (data.length < 256) { // If the numeric type is unknown, try to find actual type if (n_type === NUMTYPE.NUMERIC) { // Perform fast numeric analysis (skip delta) na = analyzeNumericArray( data, false ); // Check if this is not a numeric array (getTypedArrayType can fail // in Array cases since it's optimised for speed, not accuracy) if (na === null) { keep = false; } else { n_type = na.type; same = na.same; } } else { // Test for same lv = data[0]; for (var i=1, len=data.length; i<len; ++i) { v = data[i]; if (v !== lv) { same = false; break; } lv = v; } } // If for any reason this array is not numeric, don't // try to encode it if (keep) { if (same) { // If all values are the same, prefer repeated instead of short // console.log(">ARR>",data.length,"itms as REPEATED"); encodeArray_NUM_REPEATED( encoder, data, n_type ); } else { // Encode small numeric array // console.log(">ARR>",data.length,"itms as SHORT"); encodeArray_NUM_SHORT( encoder, data, n_type ); } } else { // Pass it to primitive encoder encodeArray_Primitive( encoder, data ); } } else { // Perform full numeric type analysis and encode numeric array na = analyzeNumericArray( data, true ); // Check if this is not a numeric array (getTypedArrayType can fail // in Array cases since it's optimised for speed, not accuracy) if (na !== null) { // Define generic type if (n_type === NUMTYPE.NUMERIC) { n_type = na.type; } // If all values are the same, encode using same numeric encoding if (na.same) { // console.log(">ARR>",data.length,"itms as REPEATED"); encodeArray_NUM_REPEATED( encoder, data, n_type ); return; } // If we have more than <thresshold> items with the same // value, break into chunked array if (na.psame >= encoder.optimize.repeat_break_thresshold) { encodeArray_Primitive( encoder, data ); return; } // Perform detailed analysis for downscaling and delta-encoding var n_dws = getDownscaleType( n_type, na ); // console.log(">>[DWS]>> n_type="+_NUMTYPE[n_type]+", analysis=",na,":",_NUMTYPE[n_dws]); // Get sizes of different encoding approaches var b_raw = sizeOfType( n_type ), b_dws = sizeOfType( n_dws ), b_delta = sizeOfType( na.delta_type ), b_min = Math.min(b_raw, b_dws, b_delta); // Pick best, according to speed preference if (b_min === b_raw) { // Encode raw // console.log(">ARR>",data.length,"itms as RAW (type="+_NUMTYPE[n_type]+")"); encodeArray_NUM_RAW( encoder, data, n_type ); } else if (b_min === b_dws) { // Encode downscaled // console.log(">ARR>",data.length,"itms as DOWNSCALED"); encodeArray_NUM_DWS( encoder, data, n_type, n_dws ); } else if (b_min === b_delta) { // Encode delta if ( encoder.optimize.enable_delta ) { // console.log(">ARR>",data.length,"itms as DELTA"); if (na.dmode == 1) { encodeArray_NUM_DELTA_INT( encoder, data, n_type, na.delta_type ); return; } else if ((na.dmode == 2) && encoder.optimize.float_int_downscale) { encodeArray_NUM_DELTA_FLOAT( encoder, data, n_type, na.delta_type, na.mean, na.fscale ); return; } } // Fallback case -> Raw encode // console.log(">ARR>",data.length,"itms as RAW (type="+_NUMTYPE[n_type]+") (Fallback)"); encodeArray_NUM_RAW( encoder, data, n_type ); } } else { // Pass it to primitive encoder encodeArray_Primitive( encoder, data ); } } }
[ "function", "encodeArray_Numeric", "(", "encoder", ",", "data", ",", "n_type", ")", "{", "var", "na", ",", "keep", "=", "true", ",", "v", ",", "lv", ",", "same", "=", "true", ";", "if", "(", "data", ".", "length", "<", "256", ")", "{", "if", "(", "n_type", "===", "NUMTYPE", ".", "NUMERIC", ")", "{", "na", "=", "analyzeNumericArray", "(", "data", ",", "false", ")", ";", "if", "(", "na", "===", "null", ")", "{", "keep", "=", "false", ";", "}", "else", "{", "n_type", "=", "na", ".", "type", ";", "same", "=", "na", ".", "same", ";", "}", "}", "else", "{", "lv", "=", "data", "[", "0", "]", ";", "for", "(", "var", "i", "=", "1", ",", "len", "=", "data", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "v", "=", "data", "[", "i", "]", ";", "if", "(", "v", "!==", "lv", ")", "{", "same", "=", "false", ";", "break", ";", "}", "lv", "=", "v", ";", "}", "}", "if", "(", "keep", ")", "{", "if", "(", "same", ")", "{", "encodeArray_NUM_REPEATED", "(", "encoder", ",", "data", ",", "n_type", ")", ";", "}", "else", "{", "encodeArray_NUM_SHORT", "(", "encoder", ",", "data", ",", "n_type", ")", ";", "}", "}", "else", "{", "encodeArray_Primitive", "(", "encoder", ",", "data", ")", ";", "}", "}", "else", "{", "na", "=", "analyzeNumericArray", "(", "data", ",", "true", ")", ";", "if", "(", "na", "!==", "null", ")", "{", "if", "(", "n_type", "===", "NUMTYPE", ".", "NUMERIC", ")", "{", "n_type", "=", "na", ".", "type", ";", "}", "if", "(", "na", ".", "same", ")", "{", "encodeArray_NUM_REPEATED", "(", "encoder", ",", "data", ",", "n_type", ")", ";", "return", ";", "}", "if", "(", "na", ".", "psame", ">=", "encoder", ".", "optimize", ".", "repeat_break_thresshold", ")", "{", "encodeArray_Primitive", "(", "encoder", ",", "data", ")", ";", "return", ";", "}", "var", "n_dws", "=", "getDownscaleType", "(", "n_type", ",", "na", ")", ";", "var", "b_raw", "=", "sizeOfType", "(", "n_type", ")", ",", "b_dws", "=", "sizeOfType", "(", "n_dws", ")", ",", "b_delta", "=", "sizeOfType", "(", "na", ".", "delta_type", ")", ",", "b_min", "=", "Math", ".", "min", "(", "b_raw", ",", "b_dws", ",", "b_delta", ")", ";", "if", "(", "b_min", "===", "b_raw", ")", "{", "encodeArray_NUM_RAW", "(", "encoder", ",", "data", ",", "n_type", ")", ";", "}", "else", "if", "(", "b_min", "===", "b_dws", ")", "{", "encodeArray_NUM_DWS", "(", "encoder", ",", "data", ",", "n_type", ",", "n_dws", ")", ";", "}", "else", "if", "(", "b_min", "===", "b_delta", ")", "{", "if", "(", "encoder", ".", "optimize", ".", "enable_delta", ")", "{", "if", "(", "na", ".", "dmode", "==", "1", ")", "{", "encodeArray_NUM_DELTA_INT", "(", "encoder", ",", "data", ",", "n_type", ",", "na", ".", "delta_type", ")", ";", "return", ";", "}", "else", "if", "(", "(", "na", ".", "dmode", "==", "2", ")", "&&", "encoder", ".", "optimize", ".", "float_int_downscale", ")", "{", "encodeArray_NUM_DELTA_FLOAT", "(", "encoder", ",", "data", ",", "n_type", ",", "na", ".", "delta_type", ",", "na", ".", "mean", ",", "na", ".", "fscale", ")", ";", "return", ";", "}", "}", "encodeArray_NUM_RAW", "(", "encoder", ",", "data", ",", "n_type", ")", ";", "}", "}", "else", "{", "encodeArray_Primitive", "(", "encoder", ",", "data", ")", ";", "}", "}", "}" ]
Encode an array that is already classified as numeric
[ "Encode", "an", "array", "that", "is", "already", "classified", "as", "numeric" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2729-L2856
train
wavesoft/jbb
encoder.js
encodeArray_Primitive
function encodeArray_Primitive( encoder, data ) { // Analyze primitive array and return clusters of values // that can be efficiently merged (such as numbers, repeated values, // primitives etc.) var chunks = analyzePrimitiveArray( encoder, data ); if (chunks.length === 1) { // Just check if (chunks[0][1] !== data.length) { throw new Errors.AssertError('Primitive array analysis reported single chunk but does not match array length!'); } // Just encode a single chunk as array component encodeArray_Chunk( encoder, data, chunks[0] ); } else { // We have more than one chunk, start encoding chunked array encodeArray_PRIM_CHUNK( encoder, data, chunks ); } }
javascript
function encodeArray_Primitive( encoder, data ) { // Analyze primitive array and return clusters of values // that can be efficiently merged (such as numbers, repeated values, // primitives etc.) var chunks = analyzePrimitiveArray( encoder, data ); if (chunks.length === 1) { // Just check if (chunks[0][1] !== data.length) { throw new Errors.AssertError('Primitive array analysis reported single chunk but does not match array length!'); } // Just encode a single chunk as array component encodeArray_Chunk( encoder, data, chunks[0] ); } else { // We have more than one chunk, start encoding chunked array encodeArray_PRIM_CHUNK( encoder, data, chunks ); } }
[ "function", "encodeArray_Primitive", "(", "encoder", ",", "data", ")", "{", "var", "chunks", "=", "analyzePrimitiveArray", "(", "encoder", ",", "data", ")", ";", "if", "(", "chunks", ".", "length", "===", "1", ")", "{", "if", "(", "chunks", "[", "0", "]", "[", "1", "]", "!==", "data", ".", "length", ")", "{", "throw", "new", "Errors", ".", "AssertError", "(", "'Primitive array analysis reported single chunk but does not match array length!'", ")", ";", "}", "encodeArray_Chunk", "(", "encoder", ",", "data", ",", "chunks", "[", "0", "]", ")", ";", "}", "else", "{", "encodeArray_PRIM_CHUNK", "(", "encoder", ",", "data", ",", "chunks", ")", ";", "}", "}" ]
Encode an array that is already classified as primitive
[ "Encode", "an", "array", "that", "is", "already", "classified", "as", "primitive" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2861-L2884
train
wavesoft/jbb
encoder.js
encodeArray
function encodeArray( encoder, data ) { encoder.log(LOG.PRM, "array, len="+data.length+", peek="+data[0]); // Check for empty array if (data.length === 0) { encodeArray_EMPTY( encoder ); return; } // Get typed array typed var tt = getTypedArrayType(data); // Check for numerical array if ( tt <= NUMTYPE.NUMERIC ) { encodeArray_Numeric( encoder, data, tt ); } else { encodeArray_Primitive( encoder, data ); } }
javascript
function encodeArray( encoder, data ) { encoder.log(LOG.PRM, "array, len="+data.length+", peek="+data[0]); // Check for empty array if (data.length === 0) { encodeArray_EMPTY( encoder ); return; } // Get typed array typed var tt = getTypedArrayType(data); // Check for numerical array if ( tt <= NUMTYPE.NUMERIC ) { encodeArray_Numeric( encoder, data, tt ); } else { encodeArray_Primitive( encoder, data ); } }
[ "function", "encodeArray", "(", "encoder", ",", "data", ")", "{", "encoder", ".", "log", "(", "LOG", ".", "PRM", ",", "\"array, len=\"", "+", "data", ".", "length", "+", "\", peek=\"", "+", "data", "[", "0", "]", ")", ";", "if", "(", "data", ".", "length", "===", "0", ")", "{", "encodeArray_EMPTY", "(", "encoder", ")", ";", "return", ";", "}", "var", "tt", "=", "getTypedArrayType", "(", "data", ")", ";", "if", "(", "tt", "<=", "NUMTYPE", ".", "NUMERIC", ")", "{", "encodeArray_Numeric", "(", "encoder", ",", "data", ",", "tt", ")", ";", "}", "else", "{", "encodeArray_Primitive", "(", "encoder", ",", "data", ")", ";", "}", "}" ]
Encode the specified array
[ "Encode", "the", "specified", "array" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2889-L2908
train
wavesoft/jbb
encoder.js
encodeBuffer
function encodeBuffer( encoder, buffer_type, mime_type, buffer ) { // Write buffer header according to buffer length if (buffer.length < UINT8_MAX) { encoder.stream8.write( pack1b( PRIM_OP.BUFFER | buffer_type | 0x00 ) ); encoder.stream8.write( pack1b( buffer.length ) ); encoder.counters.dat_hdr+=2; } else if (buffer.length < UINT16_MAX) { encoder.stream8.write( pack1b( PRIM_OP.BUFFER | buffer_type | 0x08 ) ); encoder.stream16.write( pack2b( buffer.length ) ); encoder.counters.dat_hdr+=3; } else if (buffer.length < UINT32_MAX) { encoder.stream8.write( pack1b( PRIM_OP.BUFFER | buffer_type | 0x10 ) ); encoder.stream32.write( pack4b( buffer.length ) ); encoder.counters.dat_hdr+=5; } else { // 4 Gigs? Are you serious? Of course we can fit it in a Float64, but WHY? throw new Errors.RangeError('The buffer you are trying to encode is bigger than the supported size!'); } // Write MIME Type (from string lookup table) if (mime_type != null) { encoder.stream16.write( pack2b( mime_type ) ); encoder.counters.dat_hdr+=2; } // Write buffer if (buffer_type === PRIM_BUFFER_TYPE.STRING_UTF8) { // NOTE: UTF-8 is a special case. For optimisation // purposes it's better to use the 16-bit stream // rather than downcasting to 8-bit and then // re-constructing the 16-bit stream at decoding time. encoder.stream16.write( packTypedArray(buffer) ); } else { encoder.stream8.write( packTypedArray(buffer) ); } }
javascript
function encodeBuffer( encoder, buffer_type, mime_type, buffer ) { // Write buffer header according to buffer length if (buffer.length < UINT8_MAX) { encoder.stream8.write( pack1b( PRIM_OP.BUFFER | buffer_type | 0x00 ) ); encoder.stream8.write( pack1b( buffer.length ) ); encoder.counters.dat_hdr+=2; } else if (buffer.length < UINT16_MAX) { encoder.stream8.write( pack1b( PRIM_OP.BUFFER | buffer_type | 0x08 ) ); encoder.stream16.write( pack2b( buffer.length ) ); encoder.counters.dat_hdr+=3; } else if (buffer.length < UINT32_MAX) { encoder.stream8.write( pack1b( PRIM_OP.BUFFER | buffer_type | 0x10 ) ); encoder.stream32.write( pack4b( buffer.length ) ); encoder.counters.dat_hdr+=5; } else { // 4 Gigs? Are you serious? Of course we can fit it in a Float64, but WHY? throw new Errors.RangeError('The buffer you are trying to encode is bigger than the supported size!'); } // Write MIME Type (from string lookup table) if (mime_type != null) { encoder.stream16.write( pack2b( mime_type ) ); encoder.counters.dat_hdr+=2; } // Write buffer if (buffer_type === PRIM_BUFFER_TYPE.STRING_UTF8) { // NOTE: UTF-8 is a special case. For optimisation // purposes it's better to use the 16-bit stream // rather than downcasting to 8-bit and then // re-constructing the 16-bit stream at decoding time. encoder.stream16.write( packTypedArray(buffer) ); } else { encoder.stream8.write( packTypedArray(buffer) ); } }
[ "function", "encodeBuffer", "(", "encoder", ",", "buffer_type", ",", "mime_type", ",", "buffer", ")", "{", "if", "(", "buffer", ".", "length", "<", "UINT8_MAX", ")", "{", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "PRIM_OP", ".", "BUFFER", "|", "buffer_type", "|", "0x00", ")", ")", ";", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "buffer", ".", "length", ")", ")", ";", "encoder", ".", "counters", ".", "dat_hdr", "+=", "2", ";", "}", "else", "if", "(", "buffer", ".", "length", "<", "UINT16_MAX", ")", "{", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "PRIM_OP", ".", "BUFFER", "|", "buffer_type", "|", "0x08", ")", ")", ";", "encoder", ".", "stream16", ".", "write", "(", "pack2b", "(", "buffer", ".", "length", ")", ")", ";", "encoder", ".", "counters", ".", "dat_hdr", "+=", "3", ";", "}", "else", "if", "(", "buffer", ".", "length", "<", "UINT32_MAX", ")", "{", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "PRIM_OP", ".", "BUFFER", "|", "buffer_type", "|", "0x10", ")", ")", ";", "encoder", ".", "stream32", ".", "write", "(", "pack4b", "(", "buffer", ".", "length", ")", ")", ";", "encoder", ".", "counters", ".", "dat_hdr", "+=", "5", ";", "}", "else", "{", "throw", "new", "Errors", ".", "RangeError", "(", "'The buffer you are trying to encode is bigger than the supported size!'", ")", ";", "}", "if", "(", "mime_type", "!=", "null", ")", "{", "encoder", ".", "stream16", ".", "write", "(", "pack2b", "(", "mime_type", ")", ")", ";", "encoder", ".", "counters", ".", "dat_hdr", "+=", "2", ";", "}", "if", "(", "buffer_type", "===", "PRIM_BUFFER_TYPE", ".", "STRING_UTF8", ")", "{", "encoder", ".", "stream16", ".", "write", "(", "packTypedArray", "(", "buffer", ")", ")", ";", "}", "else", "{", "encoder", ".", "stream8", ".", "write", "(", "packTypedArray", "(", "buffer", ")", ")", ";", "}", "}" ]
Encode buffer in the array
[ "Encode", "buffer", "in", "the", "array" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2913-L2952
train
wavesoft/jbb
encoder.js
encodeEmbeddedFileBuffer
function encodeEmbeddedFileBuffer( encoder, buffer_type, filename, mime_type ) { // Get MIME And payload var mime = mime_type || mimeTypeFromFilename( filename ), mime_id = encoder.stringID( mime ), buffer = bufferFromFile( filename ); // Write buffer header encoder.log(LOG.EMB,"file='"+filename+"', mime="+mime+", len="+buffer.length); encodeBuffer( encoder, buffer_type, mime_id, buffer ); }
javascript
function encodeEmbeddedFileBuffer( encoder, buffer_type, filename, mime_type ) { // Get MIME And payload var mime = mime_type || mimeTypeFromFilename( filename ), mime_id = encoder.stringID( mime ), buffer = bufferFromFile( filename ); // Write buffer header encoder.log(LOG.EMB,"file='"+filename+"', mime="+mime+", len="+buffer.length); encodeBuffer( encoder, buffer_type, mime_id, buffer ); }
[ "function", "encodeEmbeddedFileBuffer", "(", "encoder", ",", "buffer_type", ",", "filename", ",", "mime_type", ")", "{", "var", "mime", "=", "mime_type", "||", "mimeTypeFromFilename", "(", "filename", ")", ",", "mime_id", "=", "encoder", ".", "stringID", "(", "mime", ")", ",", "buffer", "=", "bufferFromFile", "(", "filename", ")", ";", "encoder", ".", "log", "(", "LOG", ".", "EMB", ",", "\"file='\"", "+", "filename", "+", "\"', mime=\"", "+", "mime", "+", "\", len=\"", "+", "buffer", ".", "length", ")", ";", "encodeBuffer", "(", "encoder", ",", "buffer_type", ",", "mime_id", ",", "buffer", ")", ";", "}" ]
Enbode a file as an embedded buffer
[ "Enbode", "a", "file", "as", "an", "embedded", "buffer" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2957-L2967
train
wavesoft/jbb
encoder.js
encodeEmbeddedBlobBuffer
function encodeEmbeddedBlobBuffer( encoder, buffer_type, buffer, mime_type ) { // Get MIME And payload var mime_id = encoder.stringID( mime_type ); // Write buffer header encoder.log(LOG.EMB,"file=[blob]', mime="+mime+", len="+buffer.length); encodeBuffer( encoder, buffer_type, mime_id, buffer ); }
javascript
function encodeEmbeddedBlobBuffer( encoder, buffer_type, buffer, mime_type ) { // Get MIME And payload var mime_id = encoder.stringID( mime_type ); // Write buffer header encoder.log(LOG.EMB,"file=[blob]', mime="+mime+", len="+buffer.length); encodeBuffer( encoder, buffer_type, mime_id, buffer ); }
[ "function", "encodeEmbeddedBlobBuffer", "(", "encoder", ",", "buffer_type", ",", "buffer", ",", "mime_type", ")", "{", "var", "mime_id", "=", "encoder", ".", "stringID", "(", "mime_type", ")", ";", "encoder", ".", "log", "(", "LOG", ".", "EMB", ",", "\"file=[blob]', mime=\"", "+", "mime", "+", "\", len=\"", "+", "buffer", ".", "length", ")", ";", "encodeBuffer", "(", "encoder", ",", "buffer_type", ",", "mime_id", ",", "buffer", ")", ";", "}" ]
Enbod a blob as an embedded buffer
[ "Enbod", "a", "blob", "as", "an", "embedded", "buffer" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2972-L2980
train
wavesoft/jbb
encoder.js
encodeStringBuffer
function encodeStringBuffer( encoder, str, utf8 ) { // If we do not have an explicit utf8 or not decision, pick one now if (utf8 === undefined) { utf8 = false; // Assume false for (var i=0, strLen=str.length; i<strLen; ++i) { if (str.charCodeAt(i) > 255) { utf8 = true; break; } } } // Allocate buffer var buf, bufView, bufType; if (utf8) { buf = new ArrayBuffer(str.length*2); // 2 bytes for each char bufView = new Uint16Array(buf); bufType = PRIM_BUFFER_TYPE.STRING_UTF8; encoder.log(LOG.STR,"string='"+str+"', encoding=utf-8, len="+str.length); } else { buf = new ArrayBuffer(str.length); // 1 byte for each char bufView = new Uint8Array(buf); bufType = PRIM_BUFFER_TYPE.STRING_LATIN; encoder.log(LOG.STR,"string='"+str+"', encoding=latin, len="+str.length); } // Copy into buffer for (var i=0, strLen=str.length; i<strLen; ++i) { bufView[i] = str.charCodeAt(i); } // Write down encodeBuffer( encoder, bufType, null, bufView ); }
javascript
function encodeStringBuffer( encoder, str, utf8 ) { // If we do not have an explicit utf8 or not decision, pick one now if (utf8 === undefined) { utf8 = false; // Assume false for (var i=0, strLen=str.length; i<strLen; ++i) { if (str.charCodeAt(i) > 255) { utf8 = true; break; } } } // Allocate buffer var buf, bufView, bufType; if (utf8) { buf = new ArrayBuffer(str.length*2); // 2 bytes for each char bufView = new Uint16Array(buf); bufType = PRIM_BUFFER_TYPE.STRING_UTF8; encoder.log(LOG.STR,"string='"+str+"', encoding=utf-8, len="+str.length); } else { buf = new ArrayBuffer(str.length); // 1 byte for each char bufView = new Uint8Array(buf); bufType = PRIM_BUFFER_TYPE.STRING_LATIN; encoder.log(LOG.STR,"string='"+str+"', encoding=latin, len="+str.length); } // Copy into buffer for (var i=0, strLen=str.length; i<strLen; ++i) { bufView[i] = str.charCodeAt(i); } // Write down encodeBuffer( encoder, bufType, null, bufView ); }
[ "function", "encodeStringBuffer", "(", "encoder", ",", "str", ",", "utf8", ")", "{", "if", "(", "utf8", "===", "undefined", ")", "{", "utf8", "=", "false", ";", "for", "(", "var", "i", "=", "0", ",", "strLen", "=", "str", ".", "length", ";", "i", "<", "strLen", ";", "++", "i", ")", "{", "if", "(", "str", ".", "charCodeAt", "(", "i", ")", ">", "255", ")", "{", "utf8", "=", "true", ";", "break", ";", "}", "}", "}", "var", "buf", ",", "bufView", ",", "bufType", ";", "if", "(", "utf8", ")", "{", "buf", "=", "new", "ArrayBuffer", "(", "str", ".", "length", "*", "2", ")", ";", "bufView", "=", "new", "Uint16Array", "(", "buf", ")", ";", "bufType", "=", "PRIM_BUFFER_TYPE", ".", "STRING_UTF8", ";", "encoder", ".", "log", "(", "LOG", ".", "STR", ",", "\"string='\"", "+", "str", "+", "\"', encoding=utf-8, len=\"", "+", "str", ".", "length", ")", ";", "}", "else", "{", "buf", "=", "new", "ArrayBuffer", "(", "str", ".", "length", ")", ";", "bufView", "=", "new", "Uint8Array", "(", "buf", ")", ";", "bufType", "=", "PRIM_BUFFER_TYPE", ".", "STRING_LATIN", ";", "encoder", ".", "log", "(", "LOG", ".", "STR", ",", "\"string='\"", "+", "str", "+", "\"', encoding=latin, len=\"", "+", "str", ".", "length", ")", ";", "}", "for", "(", "var", "i", "=", "0", ",", "strLen", "=", "str", ".", "length", ";", "i", "<", "strLen", ";", "++", "i", ")", "{", "bufView", "[", "i", "]", "=", "str", ".", "charCodeAt", "(", "i", ")", ";", "}", "encodeBuffer", "(", "encoder", ",", "bufType", ",", "null", ",", "bufView", ")", ";", "}" ]
Encode a string as buffer
[ "Encode", "a", "string", "as", "buffer" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L2985-L3019
train
wavesoft/jbb
encoder.js
encodeIREF
function encodeIREF( encoder, id ) { var hi = (id & 0xF0000) >> 16, lo = (id & 0xFFFF) // Write opcode splitted inti 8-bit and 16-bit encoder.log(LOG.IREF, "iref="+id); encoder.stream8.write( pack1b( PRIM_OP.REF | hi, false ) ); encoder.stream16.write( pack2b( lo, false ) ); encoder.counters.op_iref+=3; }
javascript
function encodeIREF( encoder, id ) { var hi = (id & 0xF0000) >> 16, lo = (id & 0xFFFF) // Write opcode splitted inti 8-bit and 16-bit encoder.log(LOG.IREF, "iref="+id); encoder.stream8.write( pack1b( PRIM_OP.REF | hi, false ) ); encoder.stream16.write( pack2b( lo, false ) ); encoder.counters.op_iref+=3; }
[ "function", "encodeIREF", "(", "encoder", ",", "id", ")", "{", "var", "hi", "=", "(", "id", "&", "0xF0000", ")", ">>", "16", ",", "lo", "=", "(", "id", "&", "0xFFFF", ")", "encoder", ".", "log", "(", "LOG", ".", "IREF", ",", "\"iref=\"", "+", "id", ")", ";", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "PRIM_OP", ".", "REF", "|", "hi", ",", "false", ")", ")", ";", "encoder", ".", "stream16", ".", "write", "(", "pack2b", "(", "lo", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "op_iref", "+=", "3", ";", "}" ]
Encode an 20-bit I-REF opcode
[ "Encode", "an", "20", "-", "bit", "I", "-", "REF", "opcode" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3024-L3034
train
wavesoft/jbb
encoder.js
encodeXREF
function encodeXREF( encoder, id ) { // Write opcode for 16-bit lookup encoder.log(LOG.XREF, "xref="+id+" [" + encoder.stringLookup[id] + "]") encoder.stream8.write( pack1b( PRIM_OP.IMPORT, false ) ); encoder.stream16.write( pack2b( id, false ) ); encoder.counters.op_xref+=3; }
javascript
function encodeXREF( encoder, id ) { // Write opcode for 16-bit lookup encoder.log(LOG.XREF, "xref="+id+" [" + encoder.stringLookup[id] + "]") encoder.stream8.write( pack1b( PRIM_OP.IMPORT, false ) ); encoder.stream16.write( pack2b( id, false ) ); encoder.counters.op_xref+=3; }
[ "function", "encodeXREF", "(", "encoder", ",", "id", ")", "{", "encoder", ".", "log", "(", "LOG", ".", "XREF", ",", "\"xref=\"", "+", "id", "+", "\" [\"", "+", "encoder", ".", "stringLookup", "[", "id", "]", "+", "\"]\"", ")", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "PRIM_OP", ".", "IMPORT", ",", "false", ")", ")", ";", "encoder", ".", "stream16", ".", "write", "(", "pack2b", "(", "id", ",", "false", ")", ")", ";", "encoder", ".", "counters", ".", "op_xref", "+=", "3", ";", "}" ]
Encode an 16-bit X-REF opcode
[ "Encode", "an", "16", "-", "bit", "X", "-", "REF", "opcode" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3039-L3047
train
wavesoft/jbb
encoder.js
encodeObject
function encodeObject( encoder, object ) { // Check ByRef internally var id = encoder.lookupIRef( object ); if (id > -1) { encodeIREF( encoder, id ); return; } // Check ByRef externally id = encoder.lookupXRef( object ); if (id > -1) { encodeXREF( encoder, id); return } // Lookup object type var enc = encoder.profile.encode(object); if (!enc) { throw new Errors.XRefError('An object trying to encode was not declared in the object table!'); } // Populate property table var eid = enc[0], propertyTable = enc[1]( object ); // Check ByVal ref id = encoder.lookupIVal( propertyTable, eid ); if (id > -1) { encodeIREF( encoder, id ); return; } // Keep this object for internal cross-refferencing encoder.log(LOG.OBJ,"eid="+eid+", properties="+propertyTable.length); encoder.keepIRef( object, propertyTable, eid ); // Check if we should use 12-bit or 5-bit index if (eid < 32) { // Write entity opcode encoder.stream8.write( pack1b( PRIM_OP.OBJECT | OBJ_OP.KNOWN_5 | eid ) ); encoder.counters.op_prm+=1; } else { // Split 12-bit number var eid_hi = (eid & 0xF00) >> 8, eid_lo = eid & 0xFF; // Write entity encoder.stream8.write( pack1b( PRIM_OP.OBJECT | OBJ_OP.KNOWN_12 | eid_hi ) ); encoder.stream8.write( pack1b( eid_lo ) ); encoder.counters.op_prm+=2; } // Write property table as an array encodeArray( encoder, propertyTable ); }
javascript
function encodeObject( encoder, object ) { // Check ByRef internally var id = encoder.lookupIRef( object ); if (id > -1) { encodeIREF( encoder, id ); return; } // Check ByRef externally id = encoder.lookupXRef( object ); if (id > -1) { encodeXREF( encoder, id); return } // Lookup object type var enc = encoder.profile.encode(object); if (!enc) { throw new Errors.XRefError('An object trying to encode was not declared in the object table!'); } // Populate property table var eid = enc[0], propertyTable = enc[1]( object ); // Check ByVal ref id = encoder.lookupIVal( propertyTable, eid ); if (id > -1) { encodeIREF( encoder, id ); return; } // Keep this object for internal cross-refferencing encoder.log(LOG.OBJ,"eid="+eid+", properties="+propertyTable.length); encoder.keepIRef( object, propertyTable, eid ); // Check if we should use 12-bit or 5-bit index if (eid < 32) { // Write entity opcode encoder.stream8.write( pack1b( PRIM_OP.OBJECT | OBJ_OP.KNOWN_5 | eid ) ); encoder.counters.op_prm+=1; } else { // Split 12-bit number var eid_hi = (eid & 0xF00) >> 8, eid_lo = eid & 0xFF; // Write entity encoder.stream8.write( pack1b( PRIM_OP.OBJECT | OBJ_OP.KNOWN_12 | eid_hi ) ); encoder.stream8.write( pack1b( eid_lo ) ); encoder.counters.op_prm+=2; } // Write property table as an array encodeArray( encoder, propertyTable ); }
[ "function", "encodeObject", "(", "encoder", ",", "object", ")", "{", "var", "id", "=", "encoder", ".", "lookupIRef", "(", "object", ")", ";", "if", "(", "id", ">", "-", "1", ")", "{", "encodeIREF", "(", "encoder", ",", "id", ")", ";", "return", ";", "}", "id", "=", "encoder", ".", "lookupXRef", "(", "object", ")", ";", "if", "(", "id", ">", "-", "1", ")", "{", "encodeXREF", "(", "encoder", ",", "id", ")", ";", "return", "}", "var", "enc", "=", "encoder", ".", "profile", ".", "encode", "(", "object", ")", ";", "if", "(", "!", "enc", ")", "{", "throw", "new", "Errors", ".", "XRefError", "(", "'An object trying to encode was not declared in the object table!'", ")", ";", "}", "var", "eid", "=", "enc", "[", "0", "]", ",", "propertyTable", "=", "enc", "[", "1", "]", "(", "object", ")", ";", "id", "=", "encoder", ".", "lookupIVal", "(", "propertyTable", ",", "eid", ")", ";", "if", "(", "id", ">", "-", "1", ")", "{", "encodeIREF", "(", "encoder", ",", "id", ")", ";", "return", ";", "}", "encoder", ".", "log", "(", "LOG", ".", "OBJ", ",", "\"eid=\"", "+", "eid", "+", "\", properties=\"", "+", "propertyTable", ".", "length", ")", ";", "encoder", ".", "keepIRef", "(", "object", ",", "propertyTable", ",", "eid", ")", ";", "if", "(", "eid", "<", "32", ")", "{", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "PRIM_OP", ".", "OBJECT", "|", "OBJ_OP", ".", "KNOWN_5", "|", "eid", ")", ")", ";", "encoder", ".", "counters", ".", "op_prm", "+=", "1", ";", "}", "else", "{", "var", "eid_hi", "=", "(", "eid", "&", "0xF00", ")", ">>", "8", ",", "eid_lo", "=", "eid", "&", "0xFF", ";", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "PRIM_OP", ".", "OBJECT", "|", "OBJ_OP", ".", "KNOWN_12", "|", "eid_hi", ")", ")", ";", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "eid_lo", ")", ")", ";", "encoder", ".", "counters", ".", "op_prm", "+=", "2", ";", "}", "encodeArray", "(", "encoder", ",", "propertyTable", ")", ";", "}" ]
Encode a javascript object
[ "Encode", "a", "javascript", "object" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3052-L3103
train
wavesoft/jbb
encoder.js
encodePrimitiveDate
function encodePrimitiveDate( encoder, object ) { // We have a date primitive encoder.stream8.write( pack1b( PRIM_OP.OBJECT | OBJ_OP.PRIMITIVE | OBJ_PRIM.DATE ) ); // Save date and timezone encoder.stream64.write( pack8f( Number(object) ) ); encoder.stream16.write( pack1b( object.getTimezoneOffset() / 10, true ) ); }
javascript
function encodePrimitiveDate( encoder, object ) { // We have a date primitive encoder.stream8.write( pack1b( PRIM_OP.OBJECT | OBJ_OP.PRIMITIVE | OBJ_PRIM.DATE ) ); // Save date and timezone encoder.stream64.write( pack8f( Number(object) ) ); encoder.stream16.write( pack1b( object.getTimezoneOffset() / 10, true ) ); }
[ "function", "encodePrimitiveDate", "(", "encoder", ",", "object", ")", "{", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "PRIM_OP", ".", "OBJECT", "|", "OBJ_OP", ".", "PRIMITIVE", "|", "OBJ_PRIM", ".", "DATE", ")", ")", ";", "encoder", ".", "stream64", ".", "write", "(", "pack8f", "(", "Number", "(", "object", ")", ")", ")", ";", "encoder", ".", "stream16", ".", "write", "(", "pack1b", "(", "object", ".", "getTimezoneOffset", "(", ")", "/", "10", ",", "true", ")", ")", ";", "}" ]
Encode primitive date
[ "Encode", "primitive", "date" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3108-L3117
train
wavesoft/jbb
encoder.js
encodePlainObject
function encodePlainObject( encoder, object ) { // Extract plain object signature var o_keys =Object.keys(object); // signature = o_keys.join("+"), var sid = encoder.getSignatureID( o_keys ); // Collect values of all properties var values = []; for (var i=0, len=o_keys.length; i<len; ++i) values.push( object[o_keys[i]] ); encoder.log(LOG.PLO, "plain["+sid+"], signature="+o_keys.toString()+", sid="+sid); // Split entity ID in a 11-bit number var sid_hi = (sid & 0x700) >> 8, sid_lo = sid & 0xFF; // We have a known entity ID, re-use it encoder.stream8.write( pack1b( PRIM_OP.OBJECT | OBJ_OP.PLAIN_LOOKUP | sid_hi ) ); encoder.stream8.write( pack1b( sid_lo ) ); encoder.counters.op_prm+=2; // Keep iref and encode encodeArray( encoder, values ); }
javascript
function encodePlainObject( encoder, object ) { // Extract plain object signature var o_keys =Object.keys(object); // signature = o_keys.join("+"), var sid = encoder.getSignatureID( o_keys ); // Collect values of all properties var values = []; for (var i=0, len=o_keys.length; i<len; ++i) values.push( object[o_keys[i]] ); encoder.log(LOG.PLO, "plain["+sid+"], signature="+o_keys.toString()+", sid="+sid); // Split entity ID in a 11-bit number var sid_hi = (sid & 0x700) >> 8, sid_lo = sid & 0xFF; // We have a known entity ID, re-use it encoder.stream8.write( pack1b( PRIM_OP.OBJECT | OBJ_OP.PLAIN_LOOKUP | sid_hi ) ); encoder.stream8.write( pack1b( sid_lo ) ); encoder.counters.op_prm+=2; // Keep iref and encode encodeArray( encoder, values ); }
[ "function", "encodePlainObject", "(", "encoder", ",", "object", ")", "{", "var", "o_keys", "=", "Object", ".", "keys", "(", "object", ")", ";", "var", "sid", "=", "encoder", ".", "getSignatureID", "(", "o_keys", ")", ";", "var", "values", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "o_keys", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "values", ".", "push", "(", "object", "[", "o_keys", "[", "i", "]", "]", ")", ";", "encoder", ".", "log", "(", "LOG", ".", "PLO", ",", "\"plain[\"", "+", "sid", "+", "\"], signature=\"", "+", "o_keys", ".", "toString", "(", ")", "+", "\", sid=\"", "+", "sid", ")", ";", "var", "sid_hi", "=", "(", "sid", "&", "0x700", ")", ">>", "8", ",", "sid_lo", "=", "sid", "&", "0xFF", ";", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "PRIM_OP", ".", "OBJECT", "|", "OBJ_OP", ".", "PLAIN_LOOKUP", "|", "sid_hi", ")", ")", ";", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "sid_lo", ")", ")", ";", "encoder", ".", "counters", ".", "op_prm", "+=", "2", ";", "encodeArray", "(", "encoder", ",", "values", ")", ";", "}" ]
Encode plain object
[ "Encode", "plain", "object" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3122-L3148
train
wavesoft/jbb
encoder.js
encodePrimitive_NUMBER
function encodePrimitive_NUMBER(encoder, data, type) { // Write header encoder.log(LOG.PRM, "primitive.number, type="+_NUMTYPE[numType]+", n="+data); encoder.stream8.write( pack1b( PRIM_OP.NUMBER | numType ) ); encoder.counters.op_prm+=1; // Write data pickStream( encoder, numType ) .write( packByNumType[numType]( data ) ); }
javascript
function encodePrimitive_NUMBER(encoder, data, type) { // Write header encoder.log(LOG.PRM, "primitive.number, type="+_NUMTYPE[numType]+", n="+data); encoder.stream8.write( pack1b( PRIM_OP.NUMBER | numType ) ); encoder.counters.op_prm+=1; // Write data pickStream( encoder, numType ) .write( packByNumType[numType]( data ) ); }
[ "function", "encodePrimitive_NUMBER", "(", "encoder", ",", "data", ",", "type", ")", "{", "encoder", ".", "log", "(", "LOG", ".", "PRM", ",", "\"primitive.number, type=\"", "+", "_NUMTYPE", "[", "numType", "]", "+", "\", n=\"", "+", "data", ")", ";", "encoder", ".", "stream8", ".", "write", "(", "pack1b", "(", "PRIM_OP", ".", "NUMBER", "|", "numType", ")", ")", ";", "encoder", ".", "counters", ".", "op_prm", "+=", "1", ";", "pickStream", "(", "encoder", ",", "numType", ")", ".", "write", "(", "packByNumType", "[", "numType", "]", "(", "data", ")", ")", ";", "}" ]
Encode a primitive number
[ "Encode", "a", "primitive", "number" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3153-L3164
train
wavesoft/jbb
encoder.js
function(string) { var index = this.stringLookupQuick[string]; // If missing, allocate now if (index === undefined) { index = this.stringLookup.length; this.stringLookup.push( string ); this.stringLookupQuick[string]= index; } return index; }
javascript
function(string) { var index = this.stringLookupQuick[string]; // If missing, allocate now if (index === undefined) { index = this.stringLookup.length; this.stringLookup.push( string ); this.stringLookupQuick[string]= index; } return index; }
[ "function", "(", "string", ")", "{", "var", "index", "=", "this", ".", "stringLookupQuick", "[", "string", "]", ";", "if", "(", "index", "===", "undefined", ")", "{", "index", "=", "this", ".", "stringLookup", ".", "length", ";", "this", ".", "stringLookup", ".", "push", "(", "string", ")", ";", "this", ".", "stringLookupQuick", "[", "string", "]", "=", "index", ";", "}", "return", "index", ";", "}" ]
Allocate new ID to return the ID of an existring string from file string lookup table.
[ "Allocate", "new", "ID", "to", "return", "the", "ID", "of", "an", "existring", "string", "from", "file", "string", "lookup", "table", "." ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3685-L3694
train
wavesoft/jbb
encoder.js
function( propertyTable, eid ) { // Check if we have a BST for this type if (this.indexVal[eid] !== undefined) { var id = this.indexVal[eid].search( propertyTable ); if (id.length > 0) return id[0]; } // We don't have the item or the BST return -1; }
javascript
function( propertyTable, eid ) { // Check if we have a BST for this type if (this.indexVal[eid] !== undefined) { var id = this.indexVal[eid].search( propertyTable ); if (id.length > 0) return id[0]; } // We don't have the item or the BST return -1; }
[ "function", "(", "propertyTable", ",", "eid", ")", "{", "if", "(", "this", ".", "indexVal", "[", "eid", "]", "!==", "undefined", ")", "{", "var", "id", "=", "this", ".", "indexVal", "[", "eid", "]", ".", "search", "(", "propertyTable", ")", ";", "if", "(", "id", ".", "length", ">", "0", ")", "return", "id", "[", "0", "]", ";", "}", "return", "-", "1", ";", "}" ]
Lookup if that object already exits in the i-ref table and return it's ID, using it's values and not it's contents.
[ "Lookup", "if", "that", "object", "already", "exits", "in", "the", "i", "-", "ref", "table", "and", "return", "it", "s", "ID", "using", "it", "s", "values", "and", "not", "it", "s", "contents", "." ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3713-L3721
train
wavesoft/jbb
encoder.js
function( object, propertyTable, eid ) { // Create a new BST for this entity for by-value matching if (this.indexVal[eid] === undefined) this.indexVal[eid] = new BinarySearchTree({ compareKeys: objectBstComparison, checkValueEquality: objectBstEquals, unique: true, }); // Keep object references var nid = this.indexRef.length; this.indexVal[eid].insert( propertyTable, nid ); this.indexRef.push( object ); // Keep ID on the object itself so we have a faster lookup, // and do it in a non-enumerable property so it doesn't pollute the objects. Object.defineProperty( object, "__iref__", { enumerable: false, value: nid, } ); }
javascript
function( object, propertyTable, eid ) { // Create a new BST for this entity for by-value matching if (this.indexVal[eid] === undefined) this.indexVal[eid] = new BinarySearchTree({ compareKeys: objectBstComparison, checkValueEquality: objectBstEquals, unique: true, }); // Keep object references var nid = this.indexRef.length; this.indexVal[eid].insert( propertyTable, nid ); this.indexRef.push( object ); // Keep ID on the object itself so we have a faster lookup, // and do it in a non-enumerable property so it doesn't pollute the objects. Object.defineProperty( object, "__iref__", { enumerable: false, value: nid, } ); }
[ "function", "(", "object", ",", "propertyTable", ",", "eid", ")", "{", "if", "(", "this", ".", "indexVal", "[", "eid", "]", "===", "undefined", ")", "this", ".", "indexVal", "[", "eid", "]", "=", "new", "BinarySearchTree", "(", "{", "compareKeys", ":", "objectBstComparison", ",", "checkValueEquality", ":", "objectBstEquals", ",", "unique", ":", "true", ",", "}", ")", ";", "var", "nid", "=", "this", ".", "indexRef", ".", "length", ";", "this", ".", "indexVal", "[", "eid", "]", ".", "insert", "(", "propertyTable", ",", "nid", ")", ";", "this", ".", "indexRef", ".", "push", "(", "object", ")", ";", "Object", ".", "defineProperty", "(", "object", ",", "\"__iref__\"", ",", "{", "enumerable", ":", "false", ",", "value", ":", "nid", ",", "}", ")", ";", "}" ]
Keep the specified object in the lookup tables
[ "Keep", "the", "specified", "object", "in", "the", "lookup", "tables" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3735-L3759
train
wavesoft/jbb
encoder.js
function( object ) { var keys = Object.keys(object), k, v, lVals = [], lArrays = [], lObjects = []; // Sort to values, arrays and objects var lookupString = ""; for (var i=0; i<keys.length; ++i) { k = keys[i]; v = object[k]; if ((v instanceof Uint8Array) || (v instanceof Int8Array) || (v instanceof Uint16Array) || (v instanceof Int16Array) || (v instanceof Uint32Array) || (v instanceof Int32Array) || (v instanceof Float32Array) || (v instanceof Float64Array) || (v instanceof Array) ) { lookupString += "@"+k; } else if (v.constructor === ({}).constructor) { lookupString += "%"+k; } else { lookupString += "$"+k; } } // Return lookup string return lookupString; }
javascript
function( object ) { var keys = Object.keys(object), k, v, lVals = [], lArrays = [], lObjects = []; // Sort to values, arrays and objects var lookupString = ""; for (var i=0; i<keys.length; ++i) { k = keys[i]; v = object[k]; if ((v instanceof Uint8Array) || (v instanceof Int8Array) || (v instanceof Uint16Array) || (v instanceof Int16Array) || (v instanceof Uint32Array) || (v instanceof Int32Array) || (v instanceof Float32Array) || (v instanceof Float64Array) || (v instanceof Array) ) { lookupString += "@"+k; } else if (v.constructor === ({}).constructor) { lookupString += "%"+k; } else { lookupString += "$"+k; } } // Return lookup string return lookupString; }
[ "function", "(", "object", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "object", ")", ",", "k", ",", "v", ",", "lVals", "=", "[", "]", ",", "lArrays", "=", "[", "]", ",", "lObjects", "=", "[", "]", ";", "var", "lookupString", "=", "\"\"", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "{", "k", "=", "keys", "[", "i", "]", ";", "v", "=", "object", "[", "k", "]", ";", "if", "(", "(", "v", "instanceof", "Uint8Array", ")", "||", "(", "v", "instanceof", "Int8Array", ")", "||", "(", "v", "instanceof", "Uint16Array", ")", "||", "(", "v", "instanceof", "Int16Array", ")", "||", "(", "v", "instanceof", "Uint32Array", ")", "||", "(", "v", "instanceof", "Int32Array", ")", "||", "(", "v", "instanceof", "Float32Array", ")", "||", "(", "v", "instanceof", "Float64Array", ")", "||", "(", "v", "instanceof", "Array", ")", ")", "{", "lookupString", "+=", "\"@\"", "+", "k", ";", "}", "else", "if", "(", "v", ".", "constructor", "===", "(", "{", "}", ")", ".", "constructor", ")", "{", "lookupString", "+=", "\"%\"", "+", "k", ";", "}", "else", "{", "lookupString", "+=", "\"$\"", "+", "k", ";", "}", "}", "return", "lookupString", ";", "}" ]
Calculate object signature without registering it
[ "Calculate", "object", "signature", "without", "registering", "it" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3764-L3787
train
wavesoft/jbb
encoder.js
function( object ) { var keys = Object.keys(object), k, v, lookupString, lVals = [], lArrays = [], lObjects = []; // Sort to values, arrays and objects lookupString = ""; for (var i=0; i<keys.length; ++i) { k = keys[i]; v = object[k]; if ((v instanceof Uint8Array) || (v instanceof Int8Array) || (v instanceof Uint16Array) || (v instanceof Int16Array) || (v instanceof Uint32Array) || (v instanceof Int32Array) || (v instanceof Float32Array) || (v instanceof Float64Array) || (v instanceof Array) ) { lArrays.push(k); lookupString += "@"+k; } else if (v.constructor === ({}).constructor) { lObjects.push(k); lookupString += "%"+k; } else { lVals.push(k); lookupString += "$"+k; } } // Lookup or create signature i = this.plainObjectSignatureLookup[lookupString]; if (i === undefined) { // Compile signature var sigbuf = []; sigbuf.push( pack2b( lVals.length ) ); for (var i=0; i<lVals.length; ++i) { sigbuf.push( pack2b( this.stringID(lVals[i]) ) ); } sigbuf.push( pack2b( lArrays.length ) ); for (var i=0; i<lArrays.length; ++i) { sigbuf.push( pack2b( this.stringID(lArrays[i]) ) ); } sigbuf.push( pack2b( lObjects.length ) ); for (var i=0; i<lObjects.length; ++i) { sigbuf.push( pack2b( this.stringID(lObjects[i]) ) ); } // Encode to the 16-bit stream this.plainObjectSignatureTable.push( Buffer.concat( sigbuf ) ); this.plainObjectSignatureLookup[lookupString] = i = this.plainObjectSignatureTable.length - 1; } // Return index return [i, lVals, lArrays, lObjects]; }
javascript
function( object ) { var keys = Object.keys(object), k, v, lookupString, lVals = [], lArrays = [], lObjects = []; // Sort to values, arrays and objects lookupString = ""; for (var i=0; i<keys.length; ++i) { k = keys[i]; v = object[k]; if ((v instanceof Uint8Array) || (v instanceof Int8Array) || (v instanceof Uint16Array) || (v instanceof Int16Array) || (v instanceof Uint32Array) || (v instanceof Int32Array) || (v instanceof Float32Array) || (v instanceof Float64Array) || (v instanceof Array) ) { lArrays.push(k); lookupString += "@"+k; } else if (v.constructor === ({}).constructor) { lObjects.push(k); lookupString += "%"+k; } else { lVals.push(k); lookupString += "$"+k; } } // Lookup or create signature i = this.plainObjectSignatureLookup[lookupString]; if (i === undefined) { // Compile signature var sigbuf = []; sigbuf.push( pack2b( lVals.length ) ); for (var i=0; i<lVals.length; ++i) { sigbuf.push( pack2b( this.stringID(lVals[i]) ) ); } sigbuf.push( pack2b( lArrays.length ) ); for (var i=0; i<lArrays.length; ++i) { sigbuf.push( pack2b( this.stringID(lArrays[i]) ) ); } sigbuf.push( pack2b( lObjects.length ) ); for (var i=0; i<lObjects.length; ++i) { sigbuf.push( pack2b( this.stringID(lObjects[i]) ) ); } // Encode to the 16-bit stream this.plainObjectSignatureTable.push( Buffer.concat( sigbuf ) ); this.plainObjectSignatureLookup[lookupString] = i = this.plainObjectSignatureTable.length - 1; } // Return index return [i, lVals, lArrays, lObjects]; }
[ "function", "(", "object", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "object", ")", ",", "k", ",", "v", ",", "lookupString", ",", "lVals", "=", "[", "]", ",", "lArrays", "=", "[", "]", ",", "lObjects", "=", "[", "]", ";", "lookupString", "=", "\"\"", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "{", "k", "=", "keys", "[", "i", "]", ";", "v", "=", "object", "[", "k", "]", ";", "if", "(", "(", "v", "instanceof", "Uint8Array", ")", "||", "(", "v", "instanceof", "Int8Array", ")", "||", "(", "v", "instanceof", "Uint16Array", ")", "||", "(", "v", "instanceof", "Int16Array", ")", "||", "(", "v", "instanceof", "Uint32Array", ")", "||", "(", "v", "instanceof", "Int32Array", ")", "||", "(", "v", "instanceof", "Float32Array", ")", "||", "(", "v", "instanceof", "Float64Array", ")", "||", "(", "v", "instanceof", "Array", ")", ")", "{", "lArrays", ".", "push", "(", "k", ")", ";", "lookupString", "+=", "\"@\"", "+", "k", ";", "}", "else", "if", "(", "v", ".", "constructor", "===", "(", "{", "}", ")", ".", "constructor", ")", "{", "lObjects", ".", "push", "(", "k", ")", ";", "lookupString", "+=", "\"%\"", "+", "k", ";", "}", "else", "{", "lVals", ".", "push", "(", "k", ")", ";", "lookupString", "+=", "\"$\"", "+", "k", ";", "}", "}", "i", "=", "this", ".", "plainObjectSignatureLookup", "[", "lookupString", "]", ";", "if", "(", "i", "===", "undefined", ")", "{", "var", "sigbuf", "=", "[", "]", ";", "sigbuf", ".", "push", "(", "pack2b", "(", "lVals", ".", "length", ")", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lVals", ".", "length", ";", "++", "i", ")", "{", "sigbuf", ".", "push", "(", "pack2b", "(", "this", ".", "stringID", "(", "lVals", "[", "i", "]", ")", ")", ")", ";", "}", "sigbuf", ".", "push", "(", "pack2b", "(", "lArrays", ".", "length", ")", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lArrays", ".", "length", ";", "++", "i", ")", "{", "sigbuf", ".", "push", "(", "pack2b", "(", "this", ".", "stringID", "(", "lArrays", "[", "i", "]", ")", ")", ")", ";", "}", "sigbuf", ".", "push", "(", "pack2b", "(", "lObjects", ".", "length", ")", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lObjects", ".", "length", ";", "++", "i", ")", "{", "sigbuf", ".", "push", "(", "pack2b", "(", "this", ".", "stringID", "(", "lObjects", "[", "i", "]", ")", ")", ")", ";", "}", "this", ".", "plainObjectSignatureTable", ".", "push", "(", "Buffer", ".", "concat", "(", "sigbuf", ")", ")", ";", "this", ".", "plainObjectSignatureLookup", "[", "lookupString", "]", "=", "i", "=", "this", ".", "plainObjectSignatureTable", ".", "length", "-", "1", ";", "}", "return", "[", "i", ",", "lVals", ",", "lArrays", ",", "lObjects", "]", ";", "}" ]
Get object signature
[ "Get", "object", "signature" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3792-L3843
train
wavesoft/jbb
encoder.js
function( db, prefix ) { if (!prefix) prefix=""; // Import into an easy-to-process format var keys = Object.keys(db), k, v; for (var i=0; i<keys.length; ++i) { k = keys[i]; v = db[k]; if (!db.hasOwnProperty(k)) continue; this.dbTags.push( prefix+k ); this.dbObjects.push( db[k] ); // Define the XRef property for faster lookup of the key Object.defineProperty( v, "__xref__", { enumerable: false, value: k, } ); } // Keep reference of database this.database = db; }
javascript
function( db, prefix ) { if (!prefix) prefix=""; // Import into an easy-to-process format var keys = Object.keys(db), k, v; for (var i=0; i<keys.length; ++i) { k = keys[i]; v = db[k]; if (!db.hasOwnProperty(k)) continue; this.dbTags.push( prefix+k ); this.dbObjects.push( db[k] ); // Define the XRef property for faster lookup of the key Object.defineProperty( v, "__xref__", { enumerable: false, value: k, } ); } // Keep reference of database this.database = db; }
[ "function", "(", "db", ",", "prefix", ")", "{", "if", "(", "!", "prefix", ")", "prefix", "=", "\"\"", ";", "var", "keys", "=", "Object", ".", "keys", "(", "db", ")", ",", "k", ",", "v", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "{", "k", "=", "keys", "[", "i", "]", ";", "v", "=", "db", "[", "k", "]", ";", "if", "(", "!", "db", ".", "hasOwnProperty", "(", "k", ")", ")", "continue", ";", "this", ".", "dbTags", ".", "push", "(", "prefix", "+", "k", ")", ";", "this", ".", "dbObjects", ".", "push", "(", "db", "[", "k", "]", ")", ";", "Object", ".", "defineProperty", "(", "v", ",", "\"__xref__\"", ",", "{", "enumerable", ":", "false", ",", "value", ":", "k", ",", "}", ")", ";", "}", "this", ".", "database", "=", "db", ";", "}" ]
Define an external database of tagged objects to use for cross-referencing external entities.
[ "Define", "an", "external", "database", "of", "tagged", "objects", "to", "use", "for", "cross", "-", "referencing", "external", "entities", "." ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3884-L3906
train
wavesoft/jbb
encoder.js
function( filename, mime_type ) { // Calculate relative path var relPath = filename; if (relPath.substr(0,this.baseDir.length) === this.baseDir) relPath = relPath.substr( this.baseDir.lengh ); // Write control operation this.stream8.write( pack1b( CTRL_OP.EMBED ) ); this.counters.op_ctr++; // Write string ID from the string lookup table this.stream16.write( pack2b( this.stringID(this.bundleName + "/" + relPath) ) ); this.counters.ref_str+=2; // Encode primitive encodePrimitive( this, new FileResource( filename, mime_type) ); }
javascript
function( filename, mime_type ) { // Calculate relative path var relPath = filename; if (relPath.substr(0,this.baseDir.length) === this.baseDir) relPath = relPath.substr( this.baseDir.lengh ); // Write control operation this.stream8.write( pack1b( CTRL_OP.EMBED ) ); this.counters.op_ctr++; // Write string ID from the string lookup table this.stream16.write( pack2b( this.stringID(this.bundleName + "/" + relPath) ) ); this.counters.ref_str+=2; // Encode primitive encodePrimitive( this, new FileResource( filename, mime_type) ); }
[ "function", "(", "filename", ",", "mime_type", ")", "{", "var", "relPath", "=", "filename", ";", "if", "(", "relPath", ".", "substr", "(", "0", ",", "this", ".", "baseDir", ".", "length", ")", "===", "this", ".", "baseDir", ")", "relPath", "=", "relPath", ".", "substr", "(", "this", ".", "baseDir", ".", "lengh", ")", ";", "this", ".", "stream8", ".", "write", "(", "pack1b", "(", "CTRL_OP", ".", "EMBED", ")", ")", ";", "this", ".", "counters", ".", "op_ctr", "++", ";", "this", ".", "stream16", ".", "write", "(", "pack2b", "(", "this", ".", "stringID", "(", "this", ".", "bundleName", "+", "\"/\"", "+", "relPath", ")", ")", ")", ";", "this", ".", "counters", ".", "ref_str", "+=", "2", ";", "encodePrimitive", "(", "this", ",", "new", "FileResource", "(", "filename", ",", "mime_type", ")", ")", ";", "}" ]
Embed specified resource
[ "Embed", "specified", "resource" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3937-L3953
train
wavesoft/jbb
encoder.js
function( buffer, name, mime_type ) { // Write control operation this.stream8.write( pack1b( CTRL_OP.EMBED ) ); this.counters.op_ctr++; // Write string ID from the string lookup table this.stream16.write( pack2b( this.stringID(this.bundleName + "/" + name) ) ); this.counters.ref_str+=2; // Encode primitive encodePrimitive( this, new BlobResource( buffer, mime_type) ); }
javascript
function( buffer, name, mime_type ) { // Write control operation this.stream8.write( pack1b( CTRL_OP.EMBED ) ); this.counters.op_ctr++; // Write string ID from the string lookup table this.stream16.write( pack2b( this.stringID(this.bundleName + "/" + name) ) ); this.counters.ref_str+=2; // Encode primitive encodePrimitive( this, new BlobResource( buffer, mime_type) ); }
[ "function", "(", "buffer", ",", "name", ",", "mime_type", ")", "{", "this", ".", "stream8", ".", "write", "(", "pack1b", "(", "CTRL_OP", ".", "EMBED", ")", ")", ";", "this", ".", "counters", ".", "op_ctr", "++", ";", "this", ".", "stream16", ".", "write", "(", "pack2b", "(", "this", ".", "stringID", "(", "this", ".", "bundleName", "+", "\"/\"", "+", "name", ")", ")", ")", ";", "this", ".", "counters", ".", "ref_str", "+=", "2", ";", "encodePrimitive", "(", "this", ",", "new", "BlobResource", "(", "buffer", ",", "mime_type", ")", ")", ";", "}" ]
Embed specified blob
[ "Embed", "specified", "blob" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3958-L3969
train
wavesoft/jbb
encoder.js
function(flags) { // Set log flags this.logFlags = flags; // Update flags on streams this.stream64.logWrites = ((this.logFlags & LOG.WRT) != 0); this.stream32.logWrites = ((this.logFlags & LOG.WRT) != 0); this.stream16.logWrites = ((this.logFlags & LOG.WRT) != 0); this.stream8.logWrites = ((this.logFlags & LOG.WRT) != 0); }
javascript
function(flags) { // Set log flags this.logFlags = flags; // Update flags on streams this.stream64.logWrites = ((this.logFlags & LOG.WRT) != 0); this.stream32.logWrites = ((this.logFlags & LOG.WRT) != 0); this.stream16.logWrites = ((this.logFlags & LOG.WRT) != 0); this.stream8.logWrites = ((this.logFlags & LOG.WRT) != 0); }
[ "function", "(", "flags", ")", "{", "this", ".", "logFlags", "=", "flags", ";", "this", ".", "stream64", ".", "logWrites", "=", "(", "(", "this", ".", "logFlags", "&", "LOG", ".", "WRT", ")", "!=", "0", ")", ";", "this", ".", "stream32", ".", "logWrites", "=", "(", "(", "this", ".", "logFlags", "&", "LOG", ".", "WRT", ")", "!=", "0", ")", ";", "this", ".", "stream16", ".", "logWrites", "=", "(", "(", "this", ".", "logFlags", "&", "LOG", ".", "WRT", ")", "!=", "0", ")", ";", "this", ".", "stream8", ".", "logWrites", "=", "(", "(", "this", ".", "logFlags", "&", "LOG", ".", "WRT", ")", "!=", "0", ")", ";", "}" ]
Set log flags
[ "Set", "log", "flags" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L3974-L3985
train
wavesoft/jbb
encoder.js
function(indent, c) { var iChar = c || ">"; if (indent > 0) { for (var i=0; i<indent; ++i) this.logPrefix+=iChar; } else { this.logPrefix = this.logPrefix.substr(0,this.logPrefix.length+indent*iChar.length); } }
javascript
function(indent, c) { var iChar = c || ">"; if (indent > 0) { for (var i=0; i<indent; ++i) this.logPrefix+=iChar; } else { this.logPrefix = this.logPrefix.substr(0,this.logPrefix.length+indent*iChar.length); } }
[ "function", "(", "indent", ",", "c", ")", "{", "var", "iChar", "=", "c", "||", "\">\"", ";", "if", "(", "indent", ">", "0", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "indent", ";", "++", "i", ")", "this", ".", "logPrefix", "+=", "iChar", ";", "}", "else", "{", "this", ".", "logPrefix", "=", "this", ".", "logPrefix", ".", "substr", "(", "0", ",", "this", ".", "logPrefix", ".", "length", "+", "indent", "*", "iChar", ".", "length", ")", ";", "}", "}" ]
Log identation modification
[ "Log", "identation", "modification" ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/encoder.js#L4006-L4013
train
wavesoft/jbb
loader.js
function( parent, name ) { /** * State of the bundle item in queue * * 0 - Requested * 1 - Specs loaded * 2 - Imports satisfied * 3 - Loaded */ this.state = STATE_REQUESTED; /** * Reference to the Bundles instance */ this.bundles = parent; /** * The bundle name */ this.name = name; /** * The bundle base directory */ this.bundleURL = null; /** * Suffix to append to bundle files */ this.bundleURLSuffix = ""; /** * Bundle-specific resources */ this.resources = {}; this.blobs = {}; /** * The bundle specifications */ this.specs = null; /** * Callbacks of interested parties */ this.callbacks = []; /** * Dependencies of this node */ this.depends = []; /** * The loaded bundle item */ this.bundle = null; }
javascript
function( parent, name ) { /** * State of the bundle item in queue * * 0 - Requested * 1 - Specs loaded * 2 - Imports satisfied * 3 - Loaded */ this.state = STATE_REQUESTED; /** * Reference to the Bundles instance */ this.bundles = parent; /** * The bundle name */ this.name = name; /** * The bundle base directory */ this.bundleURL = null; /** * Suffix to append to bundle files */ this.bundleURLSuffix = ""; /** * Bundle-specific resources */ this.resources = {}; this.blobs = {}; /** * The bundle specifications */ this.specs = null; /** * Callbacks of interested parties */ this.callbacks = []; /** * Dependencies of this node */ this.depends = []; /** * The loaded bundle item */ this.bundle = null; }
[ "function", "(", "parent", ",", "name", ")", "{", "this", ".", "state", "=", "STATE_REQUESTED", ";", "this", ".", "bundles", "=", "parent", ";", "this", ".", "name", "=", "name", ";", "this", ".", "bundleURL", "=", "null", ";", "this", ".", "bundleURLSuffix", "=", "\"\"", ";", "this", ".", "resources", "=", "{", "}", ";", "this", ".", "blobs", "=", "{", "}", ";", "this", ".", "specs", "=", "null", ";", "this", ".", "callbacks", "=", "[", "]", ";", "this", ".", "depends", "=", "[", "]", ";", "this", ".", "bundle", "=", "null", ";", "}" ]
A bundle description pending in the loading queue, waiting to be processed at loading time.
[ "A", "bundle", "description", "pending", "in", "the", "loading", "queue", "waiting", "to", "be", "processed", "at", "loading", "time", "." ]
46c40e0bca02d74201fb99925843cde49e9fe68a
https://github.com/wavesoft/jbb/blob/46c40e0bca02d74201fb99925843cde49e9fe68a/loader.js#L91-L149
train
godaddy/slay
lib/app.js
App
function App(root, options) { options = options || {}; if (!root || typeof root !== 'string') { throw new Error('Application root is not provided or not a string.'); } if (typeof options !== 'object') { throw new Error('Application options is not provided or not an object.'); } Broadway.call(this, options, express()); App.bootstrap(this, root); }
javascript
function App(root, options) { options = options || {}; if (!root || typeof root !== 'string') { throw new Error('Application root is not provided or not a string.'); } if (typeof options !== 'object') { throw new Error('Application options is not provided or not an object.'); } Broadway.call(this, options, express()); App.bootstrap(this, root); }
[ "function", "App", "(", "root", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "root", "||", "typeof", "root", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Application root is not provided or not a string.'", ")", ";", "}", "if", "(", "typeof", "options", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "'Application options is not provided or not an object.'", ")", ";", "}", "Broadway", ".", "call", "(", "this", ",", "options", ",", "express", "(", ")", ")", ";", "App", ".", "bootstrap", "(", "this", ",", "root", ")", ";", "}" ]
Constructor function for the Slay app object. @param {string} root Root directory of the application @param {object} options Options for this app instance. @constructor
[ "Constructor", "function", "for", "the", "Slay", "app", "object", "." ]
d96b2d103b21605c62705eeb29e4faac9d41972e
https://github.com/godaddy/slay/blob/d96b2d103b21605c62705eeb29e4faac9d41972e/lib/app.js#L19-L30
train
inikulin/ineed
lib/api_host.js
validatePluginName
function validatePluginName(plugin, pluginList) { if (!plugin.name) throw new Error(ApiHost.ERR_PLUGIN_MISSING_NAME_PROPERTY); pluginList.forEach(function (collectorPlugin) { if (plugin.name === collectorPlugin.name) { var msg = util.format(ApiHost.ERR_DUPLICATE_PLUGIN_NAME, plugin.name, plugin.extends); throw new Error(msg); } }); }
javascript
function validatePluginName(plugin, pluginList) { if (!plugin.name) throw new Error(ApiHost.ERR_PLUGIN_MISSING_NAME_PROPERTY); pluginList.forEach(function (collectorPlugin) { if (plugin.name === collectorPlugin.name) { var msg = util.format(ApiHost.ERR_DUPLICATE_PLUGIN_NAME, plugin.name, plugin.extends); throw new Error(msg); } }); }
[ "function", "validatePluginName", "(", "plugin", ",", "pluginList", ")", "{", "if", "(", "!", "plugin", ".", "name", ")", "throw", "new", "Error", "(", "ApiHost", ".", "ERR_PLUGIN_MISSING_NAME_PROPERTY", ")", ";", "pluginList", ".", "forEach", "(", "function", "(", "collectorPlugin", ")", "{", "if", "(", "plugin", ".", "name", "===", "collectorPlugin", ".", "name", ")", "{", "var", "msg", "=", "util", ".", "format", "(", "ApiHost", ".", "ERR_DUPLICATE_PLUGIN_NAME", ",", "plugin", ".", "name", ",", "plugin", ".", "extends", ")", ";", "throw", "new", "Error", "(", "msg", ")", ";", "}", "}", ")", ";", "}" ]
Plugin name validation
[ "Plugin", "name", "validation" ]
ca83abe7d65805ece349ced944f1be8ee787e1c0
https://github.com/inikulin/ineed/blob/ca83abe7d65805ece349ced944f1be8ee787e1c0/lib/api_host.js#L7-L17
train
swift-nav/gpstime
lib/index.js
gpsTimestampToUtcTimestamp
function gpsTimestampToUtcTimestamp(gpsTimestamp) { // Get lastIndex for which our gpsTimestamp is greater var lastIndex = void 0; for (lastIndex = 0; lastIndex < gpsLeapSeconds.length; ++lastIndex) { if (gpsTimestamp - gpsLeapSeconds[lastIndex] > 0) { break; } } var leapSecondsOffset = gpsLeapSeconds.length - lastIndex; return new Date(gpsTimestamp.getTime() - leapSecondsOffset * 1000); }
javascript
function gpsTimestampToUtcTimestamp(gpsTimestamp) { // Get lastIndex for which our gpsTimestamp is greater var lastIndex = void 0; for (lastIndex = 0; lastIndex < gpsLeapSeconds.length; ++lastIndex) { if (gpsTimestamp - gpsLeapSeconds[lastIndex] > 0) { break; } } var leapSecondsOffset = gpsLeapSeconds.length - lastIndex; return new Date(gpsTimestamp.getTime() - leapSecondsOffset * 1000); }
[ "function", "gpsTimestampToUtcTimestamp", "(", "gpsTimestamp", ")", "{", "var", "lastIndex", "=", "void", "0", ";", "for", "(", "lastIndex", "=", "0", ";", "lastIndex", "<", "gpsLeapSeconds", ".", "length", ";", "++", "lastIndex", ")", "{", "if", "(", "gpsTimestamp", "-", "gpsLeapSeconds", "[", "lastIndex", "]", ">", "0", ")", "{", "break", ";", "}", "}", "var", "leapSecondsOffset", "=", "gpsLeapSeconds", ".", "length", "-", "lastIndex", ";", "return", "new", "Date", "(", "gpsTimestamp", ".", "getTime", "(", ")", "-", "leapSecondsOffset", "*", "1000", ")", ";", "}" ]
Convert GPS timestamp without leap seconds to a UTC timestamps with leap seconds. @param {Date} timestamp - A `moment` object representing a GPS timestamp, w/o leap-seconds. @returns {Date} - A `moment` object representing a UTC timestamp, with leap-seconds.
[ "Convert", "GPS", "timestamp", "without", "leap", "seconds", "to", "a", "UTC", "timestamps", "with", "leap", "seconds", "." ]
8af11e96aa7b1d4dc439e0565491693bfdc04a7a
https://github.com/swift-nav/gpstime/blob/8af11e96aa7b1d4dc439e0565491693bfdc04a7a/lib/index.js#L90-L102
train
swift-nav/gpstime
lib/index.js
utcTimestampToGpsTimestamp
function utcTimestampToGpsTimestamp(utcTimestamp) { // Get lastIndex for which our gpsTimestamp is greater var lastIndex = void 0; for (lastIndex = 0; lastIndex < gpsLeapSeconds.length; ++lastIndex) { if (utcTimestamp - gpsLeapSeconds[lastIndex] > 0) { break; } } var leapSecondsOffset = gpsLeapSeconds.length - lastIndex; return new Date(utcTimestamp.getTime() + leapSecondsOffset * 1000); }
javascript
function utcTimestampToGpsTimestamp(utcTimestamp) { // Get lastIndex for which our gpsTimestamp is greater var lastIndex = void 0; for (lastIndex = 0; lastIndex < gpsLeapSeconds.length; ++lastIndex) { if (utcTimestamp - gpsLeapSeconds[lastIndex] > 0) { break; } } var leapSecondsOffset = gpsLeapSeconds.length - lastIndex; return new Date(utcTimestamp.getTime() + leapSecondsOffset * 1000); }
[ "function", "utcTimestampToGpsTimestamp", "(", "utcTimestamp", ")", "{", "var", "lastIndex", "=", "void", "0", ";", "for", "(", "lastIndex", "=", "0", ";", "lastIndex", "<", "gpsLeapSeconds", ".", "length", ";", "++", "lastIndex", ")", "{", "if", "(", "utcTimestamp", "-", "gpsLeapSeconds", "[", "lastIndex", "]", ">", "0", ")", "{", "break", ";", "}", "}", "var", "leapSecondsOffset", "=", "gpsLeapSeconds", ".", "length", "-", "lastIndex", ";", "return", "new", "Date", "(", "utcTimestamp", ".", "getTime", "(", ")", "+", "leapSecondsOffset", "*", "1000", ")", ";", "}" ]
Convert UTC timestamp with leap seconds to a GPS timestamps without leap seconds. @param {Date} timestamp - A `moment` object representing a GPS timestamp, w/o leap-seconds. @returns {Date} - A `moment` object representing a UTC timestamp, with leap-seconds.
[ "Convert", "UTC", "timestamp", "with", "leap", "seconds", "to", "a", "GPS", "timestamps", "without", "leap", "seconds", "." ]
8af11e96aa7b1d4dc439e0565491693bfdc04a7a
https://github.com/swift-nav/gpstime/blob/8af11e96aa7b1d4dc439e0565491693bfdc04a7a/lib/index.js#L110-L122
train
oncletom/grunt-crx
lib/crx.js
getTaskConfiguration
function getTaskConfiguration(profile){ var config; profile = profile || 'default'; config = require(__dirname + '/../data/config-'+ profile +'.json'); return config; }
javascript
function getTaskConfiguration(profile){ var config; profile = profile || 'default'; config = require(__dirname + '/../data/config-'+ profile +'.json'); return config; }
[ "function", "getTaskConfiguration", "(", "profile", ")", "{", "var", "config", ";", "profile", "=", "profile", "||", "'default'", ";", "config", "=", "require", "(", "__dirname", "+", "'/../data/config-'", "+", "profile", "+", "'.json'", ")", ";", "return", "config", ";", "}" ]
Returns a task configuration profile @param {String=} profile @return {Object}
[ "Returns", "a", "task", "configuration", "profile" ]
f28cfb02294f85af903257850225817e15c95a48
https://github.com/oncletom/grunt-crx/blob/f28cfb02294f85af903257850225817e15c95a48/lib/crx.js#L31-L39
train
oncletom/grunt-crx
lib/crx.js
build
function build(TaskConfig, crx) { return new Promise(function(resolve, reject){ mkdir(path.dirname(TaskConfig.dest), function(err){ if (err) { return reject(err); } resolve(); }); }) .then(function(){ return crx.load(TaskConfig.src); }) .then(function(){ return crx.loadContents(); }) .then(function(archiveBuffer){ if (path.extname(TaskConfig.dest) === '.zip') { grunt.file.write(TaskConfig.dest, archiveBuffer); grunt.log.ok(TaskConfig.dest + ' has been created.'); } return archiveBuffer; }) .then(function writeCrxArchive(archiveBuffer){ if (path.extname(TaskConfig.dest) === '.crx') { return crx.pack(archiveBuffer).then(function(crxBuffer) { grunt.file.write(TaskConfig.dest, crxBuffer); grunt.log.ok(TaskConfig.dest + ' has been created.'); }).catch(grunt.log.error); } }); }
javascript
function build(TaskConfig, crx) { return new Promise(function(resolve, reject){ mkdir(path.dirname(TaskConfig.dest), function(err){ if (err) { return reject(err); } resolve(); }); }) .then(function(){ return crx.load(TaskConfig.src); }) .then(function(){ return crx.loadContents(); }) .then(function(archiveBuffer){ if (path.extname(TaskConfig.dest) === '.zip') { grunt.file.write(TaskConfig.dest, archiveBuffer); grunt.log.ok(TaskConfig.dest + ' has been created.'); } return archiveBuffer; }) .then(function writeCrxArchive(archiveBuffer){ if (path.extname(TaskConfig.dest) === '.crx') { return crx.pack(archiveBuffer).then(function(crxBuffer) { grunt.file.write(TaskConfig.dest, crxBuffer); grunt.log.ok(TaskConfig.dest + ' has been created.'); }).catch(grunt.log.error); } }); }
[ "function", "build", "(", "TaskConfig", ",", "crx", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "mkdir", "(", "path", ".", "dirname", "(", "TaskConfig", ".", "dest", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "crx", ".", "load", "(", "TaskConfig", ".", "src", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "crx", ".", "loadContents", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", "archiveBuffer", ")", "{", "if", "(", "path", ".", "extname", "(", "TaskConfig", ".", "dest", ")", "===", "'.zip'", ")", "{", "grunt", ".", "file", ".", "write", "(", "TaskConfig", ".", "dest", ",", "archiveBuffer", ")", ";", "grunt", ".", "log", ".", "ok", "(", "TaskConfig", ".", "dest", "+", "' has been created.'", ")", ";", "}", "return", "archiveBuffer", ";", "}", ")", ".", "then", "(", "function", "writeCrxArchive", "(", "archiveBuffer", ")", "{", "if", "(", "path", ".", "extname", "(", "TaskConfig", ".", "dest", ")", "===", "'.crx'", ")", "{", "return", "crx", ".", "pack", "(", "archiveBuffer", ")", ".", "then", "(", "function", "(", "crxBuffer", ")", "{", "grunt", ".", "file", ".", "write", "(", "TaskConfig", ".", "dest", ",", "crxBuffer", ")", ";", "grunt", ".", "log", ".", "ok", "(", "TaskConfig", ".", "dest", "+", "' has been created.'", ")", ";", "}", ")", ".", "catch", "(", "grunt", ".", "log", ".", "error", ")", ";", "}", "}", ")", ";", "}" ]
Builds a pre-configured chrome extension in 3 steps @api @param {crx} WebExtension @return null
[ "Builds", "a", "pre", "-", "configured", "chrome", "extension", "in", "3", "steps" ]
f28cfb02294f85af903257850225817e15c95a48
https://github.com/oncletom/grunt-crx/blob/f28cfb02294f85af903257850225817e15c95a48/lib/crx.js#L55-L87
train
FungusHumungus/pongular
lib/loader.js
loadUses
function loadUses() { var globs = Array.prototype.slice.call(arguments, 0); var path = require('path'); utils.forEach(globs, function(patt) { var files = glob.sync(patt, {}); utils.forEach(files, function(file) { require(path.join(process.cwd(), file)); }); }); return moduleInstance; }
javascript
function loadUses() { var globs = Array.prototype.slice.call(arguments, 0); var path = require('path'); utils.forEach(globs, function(patt) { var files = glob.sync(patt, {}); utils.forEach(files, function(file) { require(path.join(process.cwd(), file)); }); }); return moduleInstance; }
[ "function", "loadUses", "(", ")", "{", "var", "globs", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "var", "path", "=", "require", "(", "'path'", ")", ";", "utils", ".", "forEach", "(", "globs", ",", "function", "(", "patt", ")", "{", "var", "files", "=", "glob", ".", "sync", "(", "patt", ",", "{", "}", ")", ";", "utils", ".", "forEach", "(", "files", ",", "function", "(", "file", ")", "{", "require", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "file", ")", ")", ";", "}", ")", ";", "}", ")", ";", "return", "moduleInstance", ";", "}" ]
Requires any modules that match the given glob patterns
[ "Requires", "any", "modules", "that", "match", "the", "given", "glob", "patterns" ]
fe1552889e485e5c36d8ab8b19b1a6879e01cb77
https://github.com/FungusHumungus/pongular/blob/fe1552889e485e5c36d8ab8b19b1a6879e01cb77/lib/loader.js#L258-L269
train
firmata/firmata-builder
lib/builder.js
setEnabledFeatures
function setEnabledFeatures(selectedFeature) { switch (selectedFeature) { case "AnalogInputFirmata": analogInputEnabled = true; break; case "AnalogOutputFirmata": analogOutputEnabled = true; break; case "DigitalInputFirmata": digitalInputEnabled = true; break; case "DigitalOutputFirmata": digitalOutputEnabled = true; break; case "ServoFirmata": servoEnabled = true; break; case "FirmataScheduler": schedulerEnabled = true; break; } }
javascript
function setEnabledFeatures(selectedFeature) { switch (selectedFeature) { case "AnalogInputFirmata": analogInputEnabled = true; break; case "AnalogOutputFirmata": analogOutputEnabled = true; break; case "DigitalInputFirmata": digitalInputEnabled = true; break; case "DigitalOutputFirmata": digitalOutputEnabled = true; break; case "ServoFirmata": servoEnabled = true; break; case "FirmataScheduler": schedulerEnabled = true; break; } }
[ "function", "setEnabledFeatures", "(", "selectedFeature", ")", "{", "switch", "(", "selectedFeature", ")", "{", "case", "\"AnalogInputFirmata\"", ":", "analogInputEnabled", "=", "true", ";", "break", ";", "case", "\"AnalogOutputFirmata\"", ":", "analogOutputEnabled", "=", "true", ";", "break", ";", "case", "\"DigitalInputFirmata\"", ":", "digitalInputEnabled", "=", "true", ";", "break", ";", "case", "\"DigitalOutputFirmata\"", ":", "digitalOutputEnabled", "=", "true", ";", "break", ";", "case", "\"ServoFirmata\"", ":", "servoEnabled", "=", "true", ";", "break", ";", "case", "\"FirmataScheduler\"", ":", "schedulerEnabled", "=", "true", ";", "break", ";", "}", "}" ]
Additional features should not be added to this function. Ideally these comparisons will be eliminated at some point. @private
[ "Additional", "features", "should", "not", "be", "added", "to", "this", "function", ".", "Ideally", "these", "comparisons", "will", "be", "eliminated", "at", "some", "point", "." ]
77be548e38fe3f7872ce8b4bf428a870f9612b04
https://github.com/firmata/firmata-builder/blob/77be548e38fe3f7872ce8b4bf428a870f9612b04/lib/builder.js#L28-L49
train
firmata/firmata-builder
lib/builder.js
function(config) { var transport; if (config.wifi) { transport = new WiFiTransport({ configuration: config.wifi }); } else if (config.ethernet) { transport = new EthernetTransport({ configuration: config.ethernet }); } else if (config.ble) { transport = new BLETransport({ configuration: config.ble }); } else if (config.serial) { transport = new SerialTransport({ configuration: config.serial }); } else { throw new Error("Must specify a valid connection type"); } return transport; }
javascript
function(config) { var transport; if (config.wifi) { transport = new WiFiTransport({ configuration: config.wifi }); } else if (config.ethernet) { transport = new EthernetTransport({ configuration: config.ethernet }); } else if (config.ble) { transport = new BLETransport({ configuration: config.ble }); } else if (config.serial) { transport = new SerialTransport({ configuration: config.serial }); } else { throw new Error("Must specify a valid connection type"); } return transport; }
[ "function", "(", "config", ")", "{", "var", "transport", ";", "if", "(", "config", ".", "wifi", ")", "{", "transport", "=", "new", "WiFiTransport", "(", "{", "configuration", ":", "config", ".", "wifi", "}", ")", ";", "}", "else", "if", "(", "config", ".", "ethernet", ")", "{", "transport", "=", "new", "EthernetTransport", "(", "{", "configuration", ":", "config", ".", "ethernet", "}", ")", ";", "}", "else", "if", "(", "config", ".", "ble", ")", "{", "transport", "=", "new", "BLETransport", "(", "{", "configuration", ":", "config", ".", "ble", "}", ")", ";", "}", "else", "if", "(", "config", ".", "serial", ")", "{", "transport", "=", "new", "SerialTransport", "(", "{", "configuration", ":", "config", ".", "serial", "}", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Must specify a valid connection type\"", ")", ";", "}", "return", "transport", ";", "}" ]
Create a transport object for the specified connection type. Throws an error if no valid connection type was specified. @param {Object} config The connection type object @return {Object}
[ "Create", "a", "transport", "object", "for", "the", "specified", "connection", "type", ".", "Throws", "an", "error", "if", "no", "valid", "connection", "type", "was", "specified", "." ]
77be548e38fe3f7872ce8b4bf428a870f9612b04
https://github.com/firmata/firmata-builder/blob/77be548e38fe3f7872ce8b4bf428a870f9612b04/lib/builder.js#L127-L149
train
firmata/firmata-builder
lib/builder.js
function() { var len = this.selectedFeatures.length; clearEnabledFeatures(); for (var i = 0; i < len; i++) { setEnabledFeatures(this.selectedFeatures[i]); var feature = this.allFeatures[this.selectedFeatures[i]]; if (feature.reporting) { this.featuresWithReporting.push(feature); } if (feature.update) { this.featuresWithUpdate.push(feature); } } if (this.featuresWithReporting.length > 0) { this.reportingEnabled = true; } if (this.featuresWithUpdate.length > 0) { this.updateEnabled = true; } }
javascript
function() { var len = this.selectedFeatures.length; clearEnabledFeatures(); for (var i = 0; i < len; i++) { setEnabledFeatures(this.selectedFeatures[i]); var feature = this.allFeatures[this.selectedFeatures[i]]; if (feature.reporting) { this.featuresWithReporting.push(feature); } if (feature.update) { this.featuresWithUpdate.push(feature); } } if (this.featuresWithReporting.length > 0) { this.reportingEnabled = true; } if (this.featuresWithUpdate.length > 0) { this.updateEnabled = true; } }
[ "function", "(", ")", "{", "var", "len", "=", "this", ".", "selectedFeatures", ".", "length", ";", "clearEnabledFeatures", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "setEnabledFeatures", "(", "this", ".", "selectedFeatures", "[", "i", "]", ")", ";", "var", "feature", "=", "this", ".", "allFeatures", "[", "this", ".", "selectedFeatures", "[", "i", "]", "]", ";", "if", "(", "feature", ".", "reporting", ")", "{", "this", ".", "featuresWithReporting", ".", "push", "(", "feature", ")", ";", "}", "if", "(", "feature", ".", "update", ")", "{", "this", ".", "featuresWithUpdate", ".", "push", "(", "feature", ")", ";", "}", "}", "if", "(", "this", ".", "featuresWithReporting", ".", "length", ">", "0", ")", "{", "this", ".", "reportingEnabled", "=", "true", ";", "}", "if", "(", "this", ".", "featuresWithUpdate", ".", "length", ">", "0", ")", "{", "this", ".", "updateEnabled", "=", "true", ";", "}", "}" ]
Determine which features use reporting and which are updated on each iteration of the main loop. @private
[ "Determine", "which", "features", "use", "reporting", "and", "which", "are", "updated", "on", "each", "iteration", "of", "the", "main", "loop", "." ]
77be548e38fe3f7872ce8b4bf428a870f9612b04
https://github.com/firmata/firmata-builder/blob/77be548e38fe3f7872ce8b4bf428a870f9612b04/lib/builder.js#L156-L179
train
firmata/firmata-builder
lib/builder.js
function() { var includes = "#include <ConfigurableFirmata.h>\n\n"; includes += this.transport.createConfigBlock(); for (var i = 0, len = this.selectedFeatures.length; i < len; i++) { var feature = this.allFeatures[this.selectedFeatures[i]]; if (feature.dependencies) { for (var j = 0; j < feature.dependencies.length; j++) { var d = feature.dependencies[j]; // prevent duplicate includes if (d.className && !this.dependencies[d.className]) { includes += "#include <" + d.className + ".h>\n"; this.dependencies[d.className] = true; } } } includes += "#include <" + feature.className + ".h>\n"; includes += feature.className + " " + feature.instanceName + ";\n\n"; } // necessary until Servo can be decoupled from analog output if (servoEnabled && !analogOutputEnabled) { includes += "#include <AnalogOutputFirmata.h>\n"; includes += "AnalogOutputFirmata analogOutput;\n\n"; } // always include FirmataExt includes += "#include <FirmataExt.h>\n"; includes += "FirmataExt firmataExt;\n\n"; return includes; }
javascript
function() { var includes = "#include <ConfigurableFirmata.h>\n\n"; includes += this.transport.createConfigBlock(); for (var i = 0, len = this.selectedFeatures.length; i < len; i++) { var feature = this.allFeatures[this.selectedFeatures[i]]; if (feature.dependencies) { for (var j = 0; j < feature.dependencies.length; j++) { var d = feature.dependencies[j]; // prevent duplicate includes if (d.className && !this.dependencies[d.className]) { includes += "#include <" + d.className + ".h>\n"; this.dependencies[d.className] = true; } } } includes += "#include <" + feature.className + ".h>\n"; includes += feature.className + " " + feature.instanceName + ";\n\n"; } // necessary until Servo can be decoupled from analog output if (servoEnabled && !analogOutputEnabled) { includes += "#include <AnalogOutputFirmata.h>\n"; includes += "AnalogOutputFirmata analogOutput;\n\n"; } // always include FirmataExt includes += "#include <FirmataExt.h>\n"; includes += "FirmataExt firmataExt;\n\n"; return includes; }
[ "function", "(", ")", "{", "var", "includes", "=", "\"#include <ConfigurableFirmata.h>\\n\\n\"", ";", "\\n", "\\n", "includes", "+=", "this", ".", "transport", ".", "createConfigBlock", "(", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "this", ".", "selectedFeatures", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "feature", "=", "this", ".", "allFeatures", "[", "this", ".", "selectedFeatures", "[", "i", "]", "]", ";", "if", "(", "feature", ".", "dependencies", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "feature", ".", "dependencies", ".", "length", ";", "j", "++", ")", "{", "var", "d", "=", "feature", ".", "dependencies", "[", "j", "]", ";", "if", "(", "d", ".", "className", "&&", "!", "this", ".", "dependencies", "[", "d", ".", "className", "]", ")", "{", "includes", "+=", "\"#include <\"", "+", "d", ".", "className", "+", "\".h>\\n\"", ";", "\\n", "}", "}", "}", "this", ".", "dependencies", "[", "d", ".", "className", "]", "=", "true", ";", "includes", "+=", "\"#include <\"", "+", "feature", ".", "className", "+", "\".h>\\n\"", ";", "}", "\\n", "includes", "+=", "feature", ".", "className", "+", "\" \"", "+", "feature", ".", "instanceName", "+", "\";\\n\\n\"", ";", "}" ]
Creates the block of includes, macros and global variables at the top of the file. @private
[ "Creates", "the", "block", "of", "includes", "macros", "and", "global", "variables", "at", "the", "top", "of", "the", "file", "." ]
77be548e38fe3f7872ce8b4bf428a870f9612b04
https://github.com/firmata/firmata-builder/blob/77be548e38fe3f7872ce8b4bf428a870f9612b04/lib/builder.js#L195-L229
train
firmata/firmata-builder
lib/transports/ble.js
BLETransport
function BLETransport(opts) { if (!(this instanceof BLETransport)) { return new BLETransport(opts); } this.configuration = opts.configuration; this.controller = Controllers[this.configuration.controller]; if (!this.controller) { throw new Error("No valid BLE controller defined"); } }
javascript
function BLETransport(opts) { if (!(this instanceof BLETransport)) { return new BLETransport(opts); } this.configuration = opts.configuration; this.controller = Controllers[this.configuration.controller]; if (!this.controller) { throw new Error("No valid BLE controller defined"); } }
[ "function", "BLETransport", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "BLETransport", ")", ")", "{", "return", "new", "BLETransport", "(", "opts", ")", ";", "}", "this", ".", "configuration", "=", "opts", ".", "configuration", ";", "this", ".", "controller", "=", "Controllers", "[", "this", ".", "configuration", ".", "controller", "]", ";", "if", "(", "!", "this", ".", "controller", ")", "{", "throw", "new", "Error", "(", "\"No valid BLE controller defined\"", ")", ";", "}", "}" ]
BLE transport. @constructor @param {Object} opts
[ "BLE", "transport", "." ]
77be548e38fe3f7872ce8b4bf428a870f9612b04
https://github.com/firmata/firmata-builder/blob/77be548e38fe3f7872ce8b4bf428a870f9612b04/lib/transports/ble.js#L17-L27
train
jaredhanson/xmlb
lib/index.js
parse
function parse(str, options) { var doc = options.document || 'xml' , pretty = options.pretty || false , js = str; return '' + 'var ' + doc + ' = factory();\n' + (options.self ? 'var self = locals || {};\n' + js : 'with (locals || {}) {\n' + js + '\n}\n') + 'return ' + doc + '.toString({ pretty: ' + pretty + ' })'; }
javascript
function parse(str, options) { var doc = options.document || 'xml' , pretty = options.pretty || false , js = str; return '' + 'var ' + doc + ' = factory();\n' + (options.self ? 'var self = locals || {};\n' + js : 'with (locals || {}) {\n' + js + '\n}\n') + 'return ' + doc + '.toString({ pretty: ' + pretty + ' })'; }
[ "function", "parse", "(", "str", ",", "options", ")", "{", "var", "doc", "=", "options", ".", "document", "||", "'xml'", ",", "pretty", "=", "options", ".", "pretty", "||", "false", ",", "js", "=", "str", ";", "return", "''", "+", "'var '", "+", "doc", "+", "' = factory();\\n'", "+", "\\n", "+", "(", "options", ".", "self", "?", "'var self = locals || {};\\n'", "+", "\\n", ":", "js", ")", "+", "'with (locals || {}) {\\n'", "+", "\\n", "+", "js", "+", "'\\n}\\n'", "+", "\\n", "+", "\\n", ";", "}" ]
Parse the given `str` of XML builder and return a function body. @param {String} str @param {Object} options @return {String} @api private
[ "Parse", "the", "given", "str", "of", "XML", "builder", "and", "return", "a", "function", "body", "." ]
4ad94523a44e1ca3a2528ead1defdc3844aa59a7
https://github.com/jaredhanson/xmlb/blob/4ad94523a44e1ca3a2528ead1defdc3844aa59a7/lib/index.js#L66-L77
train
firmata/firmata-builder
lib/transports/wifi.js
WiFiTransport
function WiFiTransport(opts) { if (!(this instanceof WiFiTransport)) { return new WiFiTransport(opts); } this.configuration = opts.configuration; this.controller = Controllers[this.configuration.controller]; if (!this.controller) { throw new Error("No valid Wi-Fi controller defined"); } }
javascript
function WiFiTransport(opts) { if (!(this instanceof WiFiTransport)) { return new WiFiTransport(opts); } this.configuration = opts.configuration; this.controller = Controllers[this.configuration.controller]; if (!this.controller) { throw new Error("No valid Wi-Fi controller defined"); } }
[ "function", "WiFiTransport", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "WiFiTransport", ")", ")", "{", "return", "new", "WiFiTransport", "(", "opts", ")", ";", "}", "this", ".", "configuration", "=", "opts", ".", "configuration", ";", "this", ".", "controller", "=", "Controllers", "[", "this", ".", "configuration", ".", "controller", "]", ";", "if", "(", "!", "this", ".", "controller", ")", "{", "throw", "new", "Error", "(", "\"No valid Wi-Fi controller defined\"", ")", ";", "}", "}" ]
Wi-Fi transport. Currently configurable as server only on Arduino. @constructor @param {Object} opts
[ "Wi", "-", "Fi", "transport", ".", "Currently", "configurable", "as", "server", "only", "on", "Arduino", "." ]
77be548e38fe3f7872ce8b4bf428a870f9612b04
https://github.com/firmata/firmata-builder/blob/77be548e38fe3f7872ce8b4bf428a870f9612b04/lib/transports/wifi.js#L27-L37
train
webmodules/dom-serialize
index.js
serialize
function serialize (node, context, fn, eventTarget) { if (!node) return ''; if ('function' === typeof context) { fn = context; context = null; } if (!context) context = null; var rtn; var nodeType = node.nodeType; if (!nodeType && 'number' === typeof node.length) { // assume it's a NodeList or Array of Nodes rtn = exports.serializeNodeList(node, context, fn); } else { if ('function' === typeof fn) { // one-time "serialize" event listener node.addEventListener('serialize', fn, false); } // emit a custom "serialize" event on `node`, in case there // are event listeners for custom serialization of this node var e = new CustomEvent('serialize', { bubbles: true, cancelable: true, detail: { serialize: null, context: context } }); e.serializeTarget = node; var target = eventTarget || node; var cancelled = !target.dispatchEvent(e); // `e.detail.serialize` can be set to a: // String - returned directly // Node - goes through serializer logic instead of `node` // Anything else - get Stringified first, and then returned directly var s = e.detail.serialize; if (s != null) { if ('string' === typeof s) { rtn = s; } else if ('number' === typeof s.nodeType) { // make it go through the serialization logic rtn = serialize(s, context, null, target); } else { rtn = String(s); } } else if (!cancelled) { // default serialization logic switch (nodeType) { case 1 /* element */: rtn = exports.serializeElement(node, context, eventTarget); break; case 2 /* attribute */: rtn = exports.serializeAttribute(node); break; case 3 /* text */: rtn = exports.serializeText(node); break; case 8 /* comment */: rtn = exports.serializeComment(node); break; case 9 /* document */: rtn = exports.serializeDocument(node, context, eventTarget); break; case 10 /* doctype */: rtn = exports.serializeDoctype(node); break; case 11 /* document fragment */: rtn = exports.serializeDocumentFragment(node, context, eventTarget); break; } } if ('function' === typeof fn) { node.removeEventListener('serialize', fn, false); } } return rtn || ''; }
javascript
function serialize (node, context, fn, eventTarget) { if (!node) return ''; if ('function' === typeof context) { fn = context; context = null; } if (!context) context = null; var rtn; var nodeType = node.nodeType; if (!nodeType && 'number' === typeof node.length) { // assume it's a NodeList or Array of Nodes rtn = exports.serializeNodeList(node, context, fn); } else { if ('function' === typeof fn) { // one-time "serialize" event listener node.addEventListener('serialize', fn, false); } // emit a custom "serialize" event on `node`, in case there // are event listeners for custom serialization of this node var e = new CustomEvent('serialize', { bubbles: true, cancelable: true, detail: { serialize: null, context: context } }); e.serializeTarget = node; var target = eventTarget || node; var cancelled = !target.dispatchEvent(e); // `e.detail.serialize` can be set to a: // String - returned directly // Node - goes through serializer logic instead of `node` // Anything else - get Stringified first, and then returned directly var s = e.detail.serialize; if (s != null) { if ('string' === typeof s) { rtn = s; } else if ('number' === typeof s.nodeType) { // make it go through the serialization logic rtn = serialize(s, context, null, target); } else { rtn = String(s); } } else if (!cancelled) { // default serialization logic switch (nodeType) { case 1 /* element */: rtn = exports.serializeElement(node, context, eventTarget); break; case 2 /* attribute */: rtn = exports.serializeAttribute(node); break; case 3 /* text */: rtn = exports.serializeText(node); break; case 8 /* comment */: rtn = exports.serializeComment(node); break; case 9 /* document */: rtn = exports.serializeDocument(node, context, eventTarget); break; case 10 /* doctype */: rtn = exports.serializeDoctype(node); break; case 11 /* document fragment */: rtn = exports.serializeDocumentFragment(node, context, eventTarget); break; } } if ('function' === typeof fn) { node.removeEventListener('serialize', fn, false); } } return rtn || ''; }
[ "function", "serialize", "(", "node", ",", "context", ",", "fn", ",", "eventTarget", ")", "{", "if", "(", "!", "node", ")", "return", "''", ";", "if", "(", "'function'", "===", "typeof", "context", ")", "{", "fn", "=", "context", ";", "context", "=", "null", ";", "}", "if", "(", "!", "context", ")", "context", "=", "null", ";", "var", "rtn", ";", "var", "nodeType", "=", "node", ".", "nodeType", ";", "if", "(", "!", "nodeType", "&&", "'number'", "===", "typeof", "node", ".", "length", ")", "{", "rtn", "=", "exports", ".", "serializeNodeList", "(", "node", ",", "context", ",", "fn", ")", ";", "}", "else", "{", "if", "(", "'function'", "===", "typeof", "fn", ")", "{", "node", ".", "addEventListener", "(", "'serialize'", ",", "fn", ",", "false", ")", ";", "}", "var", "e", "=", "new", "CustomEvent", "(", "'serialize'", ",", "{", "bubbles", ":", "true", ",", "cancelable", ":", "true", ",", "detail", ":", "{", "serialize", ":", "null", ",", "context", ":", "context", "}", "}", ")", ";", "e", ".", "serializeTarget", "=", "node", ";", "var", "target", "=", "eventTarget", "||", "node", ";", "var", "cancelled", "=", "!", "target", ".", "dispatchEvent", "(", "e", ")", ";", "var", "s", "=", "e", ".", "detail", ".", "serialize", ";", "if", "(", "s", "!=", "null", ")", "{", "if", "(", "'string'", "===", "typeof", "s", ")", "{", "rtn", "=", "s", ";", "}", "else", "if", "(", "'number'", "===", "typeof", "s", ".", "nodeType", ")", "{", "rtn", "=", "serialize", "(", "s", ",", "context", ",", "null", ",", "target", ")", ";", "}", "else", "{", "rtn", "=", "String", "(", "s", ")", ";", "}", "}", "else", "if", "(", "!", "cancelled", ")", "{", "switch", "(", "nodeType", ")", "{", "case", "1", ":", "rtn", "=", "exports", ".", "serializeElement", "(", "node", ",", "context", ",", "eventTarget", ")", ";", "break", ";", "case", "2", ":", "rtn", "=", "exports", ".", "serializeAttribute", "(", "node", ")", ";", "break", ";", "case", "3", ":", "rtn", "=", "exports", ".", "serializeText", "(", "node", ")", ";", "break", ";", "case", "8", ":", "rtn", "=", "exports", ".", "serializeComment", "(", "node", ")", ";", "break", ";", "case", "9", ":", "rtn", "=", "exports", ".", "serializeDocument", "(", "node", ",", "context", ",", "eventTarget", ")", ";", "break", ";", "case", "10", ":", "rtn", "=", "exports", ".", "serializeDoctype", "(", "node", ")", ";", "break", ";", "case", "11", ":", "rtn", "=", "exports", ".", "serializeDocumentFragment", "(", "node", ",", "context", ",", "eventTarget", ")", ";", "break", ";", "}", "}", "if", "(", "'function'", "===", "typeof", "fn", ")", "{", "node", ".", "removeEventListener", "(", "'serialize'", ",", "fn", ",", "false", ")", ";", "}", "}", "return", "rtn", "||", "''", ";", "}" ]
Serializes any DOM node. Returns a string. @param {Node} node - DOM Node to serialize @param {String} [context] - optional arbitrary "context" string to use (useful for event listeners) @param {Function} [fn] - optional callback function to use in the "serialize" event for this call @param {EventTarget} [eventTarget] - optional EventTarget instance to emit the "serialize" event on (defaults to `node`) return {String} @public
[ "Serializes", "any", "DOM", "node", ".", "Returns", "a", "string", "." ]
205ac26068649f57b70c1625ea7ff311e44886ae
https://github.com/webmodules/dom-serialize/blob/205ac26068649f57b70c1625ea7ff311e44886ae/index.js#L36-L120
train
webmodules/dom-serialize
index.js
serializeAttribute
function serializeAttribute (node, opts) { return node.name + '="' + encode(node.value, extend({ named: true }, opts)) + '"'; }
javascript
function serializeAttribute (node, opts) { return node.name + '="' + encode(node.value, extend({ named: true }, opts)) + '"'; }
[ "function", "serializeAttribute", "(", "node", ",", "opts", ")", "{", "return", "node", ".", "name", "+", "'=\"'", "+", "encode", "(", "node", ".", "value", ",", "extend", "(", "{", "named", ":", "true", "}", ",", "opts", ")", ")", "+", "'\"'", ";", "}" ]
Serialize an Attribute node.
[ "Serialize", "an", "Attribute", "node", "." ]
205ac26068649f57b70c1625ea7ff311e44886ae
https://github.com/webmodules/dom-serialize/blob/205ac26068649f57b70c1625ea7ff311e44886ae/index.js#L126-L130
train
webmodules/dom-serialize
index.js
serializeElement
function serializeElement (node, context, eventTarget) { var c, i, l; var name = node.nodeName.toLowerCase(); // opening tag var r = '<' + name; // attributes for (i = 0, c = node.attributes, l = c.length; i < l; i++) { r += ' ' + exports.serializeAttribute(c[i]); } r += '>'; // child nodes r += exports.serializeNodeList(node.childNodes, context, null, eventTarget); // closing tag, only for non-void elements if (!voidElements[name]) { r += '</' + name + '>'; } return r; }
javascript
function serializeElement (node, context, eventTarget) { var c, i, l; var name = node.nodeName.toLowerCase(); // opening tag var r = '<' + name; // attributes for (i = 0, c = node.attributes, l = c.length; i < l; i++) { r += ' ' + exports.serializeAttribute(c[i]); } r += '>'; // child nodes r += exports.serializeNodeList(node.childNodes, context, null, eventTarget); // closing tag, only for non-void elements if (!voidElements[name]) { r += '</' + name + '>'; } return r; }
[ "function", "serializeElement", "(", "node", ",", "context", ",", "eventTarget", ")", "{", "var", "c", ",", "i", ",", "l", ";", "var", "name", "=", "node", ".", "nodeName", ".", "toLowerCase", "(", ")", ";", "var", "r", "=", "'<'", "+", "name", ";", "for", "(", "i", "=", "0", ",", "c", "=", "node", ".", "attributes", ",", "l", "=", "c", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "r", "+=", "' '", "+", "exports", ".", "serializeAttribute", "(", "c", "[", "i", "]", ")", ";", "}", "r", "+=", "'>'", ";", "r", "+=", "exports", ".", "serializeNodeList", "(", "node", ".", "childNodes", ",", "context", ",", "null", ",", "eventTarget", ")", ";", "if", "(", "!", "voidElements", "[", "name", "]", ")", "{", "r", "+=", "'</'", "+", "name", "+", "'>'", ";", "}", "return", "r", ";", "}" ]
Serialize a DOM element.
[ "Serialize", "a", "DOM", "element", "." ]
205ac26068649f57b70c1625ea7ff311e44886ae
https://github.com/webmodules/dom-serialize/blob/205ac26068649f57b70c1625ea7ff311e44886ae/index.js#L136-L159
train
webmodules/dom-serialize
index.js
serializeText
function serializeText (node, opts) { return encode(node.nodeValue, extend({ named: true, special: { '<': true, '>': true, '&': true } }, opts)); }
javascript
function serializeText (node, opts) { return encode(node.nodeValue, extend({ named: true, special: { '<': true, '>': true, '&': true } }, opts)); }
[ "function", "serializeText", "(", "node", ",", "opts", ")", "{", "return", "encode", "(", "node", ".", "nodeValue", ",", "extend", "(", "{", "named", ":", "true", ",", "special", ":", "{", "'<'", ":", "true", ",", "'>'", ":", "true", ",", "'&'", ":", "true", "}", "}", ",", "opts", ")", ")", ";", "}" ]
Serialize a text node.
[ "Serialize", "a", "text", "node", "." ]
205ac26068649f57b70c1625ea7ff311e44886ae
https://github.com/webmodules/dom-serialize/blob/205ac26068649f57b70c1625ea7ff311e44886ae/index.js#L165-L170
train
webmodules/dom-serialize
index.js
serializeDocument
function serializeDocument (node, context, eventTarget) { return exports.serializeNodeList(node.childNodes, context, null, eventTarget); }
javascript
function serializeDocument (node, context, eventTarget) { return exports.serializeNodeList(node.childNodes, context, null, eventTarget); }
[ "function", "serializeDocument", "(", "node", ",", "context", ",", "eventTarget", ")", "{", "return", "exports", ".", "serializeNodeList", "(", "node", ".", "childNodes", ",", "context", ",", "null", ",", "eventTarget", ")", ";", "}" ]
Serialize a Document node.
[ "Serialize", "a", "Document", "node", "." ]
205ac26068649f57b70c1625ea7ff311e44886ae
https://github.com/webmodules/dom-serialize/blob/205ac26068649f57b70c1625ea7ff311e44886ae/index.js#L184-L186
train
webmodules/dom-serialize
index.js
serializeDocumentFragment
function serializeDocumentFragment (node, context, eventTarget) { return exports.serializeNodeList(node.childNodes, context, null, eventTarget); }
javascript
function serializeDocumentFragment (node, context, eventTarget) { return exports.serializeNodeList(node.childNodes, context, null, eventTarget); }
[ "function", "serializeDocumentFragment", "(", "node", ",", "context", ",", "eventTarget", ")", "{", "return", "exports", ".", "serializeNodeList", "(", "node", ".", "childNodes", ",", "context", ",", "null", ",", "eventTarget", ")", ";", "}" ]
Serialize a DocumentFragment instance.
[ "Serialize", "a", "DocumentFragment", "instance", "." ]
205ac26068649f57b70c1625ea7ff311e44886ae
https://github.com/webmodules/dom-serialize/blob/205ac26068649f57b70c1625ea7ff311e44886ae/index.js#L216-L218
train
firmata/firmata-builder
lib/transports/ethernet.js
EthernetTransport
function EthernetTransport(opts) { if (!(this instanceof EthernetTransport)) { return new EthernetTransport(opts); } this.configuration = opts.configuration; this.controller = ""; switch (Controllers[this.configuration.controller].driver) { case Controllers.WIZ5100.driver: this.controller = Controllers.WIZ5100; break; case Controllers.ENC28J60.driver: this.controller = Controllers.ENC28J60; break; case Controllers.YUN.driver: this.controller = Controllers.YUN; break; default: throw new Error("No valid Ethernet controller defined"); } }
javascript
function EthernetTransport(opts) { if (!(this instanceof EthernetTransport)) { return new EthernetTransport(opts); } this.configuration = opts.configuration; this.controller = ""; switch (Controllers[this.configuration.controller].driver) { case Controllers.WIZ5100.driver: this.controller = Controllers.WIZ5100; break; case Controllers.ENC28J60.driver: this.controller = Controllers.ENC28J60; break; case Controllers.YUN.driver: this.controller = Controllers.YUN; break; default: throw new Error("No valid Ethernet controller defined"); } }
[ "function", "EthernetTransport", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "EthernetTransport", ")", ")", "{", "return", "new", "EthernetTransport", "(", "opts", ")", ";", "}", "this", ".", "configuration", "=", "opts", ".", "configuration", ";", "this", ".", "controller", "=", "\"\"", ";", "switch", "(", "Controllers", "[", "this", ".", "configuration", ".", "controller", "]", ".", "driver", ")", "{", "case", "Controllers", ".", "WIZ5100", ".", "driver", ":", "this", ".", "controller", "=", "Controllers", ".", "WIZ5100", ";", "break", ";", "case", "Controllers", ".", "ENC28J60", ".", "driver", ":", "this", ".", "controller", "=", "Controllers", ".", "ENC28J60", ";", "break", ";", "case", "Controllers", ".", "YUN", ".", "driver", ":", "this", ".", "controller", "=", "Controllers", ".", "YUN", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "\"No valid Ethernet controller defined\"", ")", ";", "}", "}" ]
Ethernet transport. Currently configurable as client only on Arduino. @constructor @param {Objedt} opts
[ "Ethernet", "transport", ".", "Currently", "configurable", "as", "client", "only", "on", "Arduino", "." ]
77be548e38fe3f7872ce8b4bf428a870f9612b04
https://github.com/firmata/firmata-builder/blob/77be548e38fe3f7872ce8b4bf428a870f9612b04/lib/transports/ethernet.js#L39-L60
train
artdecocode/reloquent
build/lib/ask-questions.js
askQuestions
async function askQuestions(questions, timeout) { if (typeof questions != 'object') throw new Error('Please give an object with questions') const keys = Object.keys(/** @type {!Object} */ (questions)) const res = await keys.reduce(async (acc, key) => { const accRes = await acc const value = questions[key] /** @type {!_reloquent.Question} */ let question switch (typeof value) { case 'object': question = /** @type {!_reloquent.Question} */ ({ ...value }) break case 'string': question = { text: value } break default: throw new Error('A question must be a string or an object.') } question.text = `${question.text}${question.text.endsWith('?') ? '' : ':'} ` let defaultValue let gotDefaultValue if (question.defaultValue) { defaultValue = question.defaultValue } if (question.getDefault) { gotDefaultValue = await question.getDefault() } let dv = defaultValue || '' if (defaultValue && gotDefaultValue && defaultValue != gotDefaultValue) { dv = c(defaultValue) } else if (defaultValue && defaultValue == gotDefaultValue) { dv = '' } let gtd = gotDefaultValue || '' const text = `${question.text}${dv ? `[${dv}] ` : ''}${gtd ? `[${gtd}] ` : ''}` const { 'promise': promise } = ask(text, { timeout, password: question.password, }) const a = await promise let answer = a || gotDefaultValue || question.defaultValue if (typeof question.validation == 'function') { question.validation(answer) } if (typeof question.postProcess == 'function') { answer = await question.postProcess(answer) } return { ...accRes, [key]: answer, } }, {}) return res }
javascript
async function askQuestions(questions, timeout) { if (typeof questions != 'object') throw new Error('Please give an object with questions') const keys = Object.keys(/** @type {!Object} */ (questions)) const res = await keys.reduce(async (acc, key) => { const accRes = await acc const value = questions[key] /** @type {!_reloquent.Question} */ let question switch (typeof value) { case 'object': question = /** @type {!_reloquent.Question} */ ({ ...value }) break case 'string': question = { text: value } break default: throw new Error('A question must be a string or an object.') } question.text = `${question.text}${question.text.endsWith('?') ? '' : ':'} ` let defaultValue let gotDefaultValue if (question.defaultValue) { defaultValue = question.defaultValue } if (question.getDefault) { gotDefaultValue = await question.getDefault() } let dv = defaultValue || '' if (defaultValue && gotDefaultValue && defaultValue != gotDefaultValue) { dv = c(defaultValue) } else if (defaultValue && defaultValue == gotDefaultValue) { dv = '' } let gtd = gotDefaultValue || '' const text = `${question.text}${dv ? `[${dv}] ` : ''}${gtd ? `[${gtd}] ` : ''}` const { 'promise': promise } = ask(text, { timeout, password: question.password, }) const a = await promise let answer = a || gotDefaultValue || question.defaultValue if (typeof question.validation == 'function') { question.validation(answer) } if (typeof question.postProcess == 'function') { answer = await question.postProcess(answer) } return { ...accRes, [key]: answer, } }, {}) return res }
[ "async", "function", "askQuestions", "(", "questions", ",", "timeout", ")", "{", "if", "(", "typeof", "questions", "!=", "'object'", ")", "throw", "new", "Error", "(", "'Please give an object with questions'", ")", "const", "keys", "=", "Object", ".", "keys", "(", "(", "questions", ")", ")", "const", "res", "=", "await", "keys", ".", "reduce", "(", "async", "(", "acc", ",", "key", ")", "=>", "{", "const", "accRes", "=", "await", "acc", "const", "value", "=", "questions", "[", "key", "]", "let", "question", "switch", "(", "typeof", "value", ")", "{", "case", "'object'", ":", "question", "=", "(", "{", "...", "value", "}", ")", "break", "case", "'string'", ":", "question", "=", "{", "text", ":", "value", "}", "break", "default", ":", "throw", "new", "Error", "(", "'A question must be a string or an object.'", ")", "}", "question", ".", "text", "=", "`", "${", "question", ".", "text", "}", "${", "question", ".", "text", ".", "endsWith", "(", "'?'", ")", "?", "''", ":", "':'", "}", "`", "let", "defaultValue", "let", "gotDefaultValue", "if", "(", "question", ".", "defaultValue", ")", "{", "defaultValue", "=", "question", ".", "defaultValue", "}", "if", "(", "question", ".", "getDefault", ")", "{", "gotDefaultValue", "=", "await", "question", ".", "getDefault", "(", ")", "}", "let", "dv", "=", "defaultValue", "||", "''", "if", "(", "defaultValue", "&&", "gotDefaultValue", "&&", "defaultValue", "!=", "gotDefaultValue", ")", "{", "dv", "=", "c", "(", "defaultValue", ")", "}", "else", "if", "(", "defaultValue", "&&", "defaultValue", "==", "gotDefaultValue", ")", "{", "dv", "=", "''", "}", "let", "gtd", "=", "gotDefaultValue", "||", "''", "const", "text", "=", "`", "${", "question", ".", "text", "}", "${", "dv", "?", "`", "${", "dv", "}", "`", ":", "''", "}", "${", "gtd", "?", "`", "${", "gtd", "}", "`", ":", "''", "}", "`", "const", "{", "'promise'", ":", "promise", "}", "=", "ask", "(", "text", ",", "{", "timeout", ",", "password", ":", "question", ".", "password", ",", "}", ")", "const", "a", "=", "await", "promise", "let", "answer", "=", "a", "||", "gotDefaultValue", "||", "question", ".", "defaultValue", "if", "(", "typeof", "question", ".", "validation", "==", "'function'", ")", "{", "question", ".", "validation", "(", "answer", ")", "}", "if", "(", "typeof", "question", ".", "postProcess", "==", "'function'", ")", "{", "answer", "=", "await", "question", ".", "postProcess", "(", "answer", ")", "}", "return", "{", "...", "accRes", ",", "[", "key", "]", ":", "answer", ",", "}", "}", ",", "{", "}", ")", "return", "res", "}" ]
Ask a set of questions. @param {_reloquent.Questions} questions An object with questions as values @param {number} [timeout] How long to wait before answer @returns {!Promise<!Object<string, string>>} A promise where keys from the questions object are validated, assigned default values if required, and populated with answers. Validation function should either throw or return nothing, or throw an error.
[ "Ask", "a", "set", "of", "questions", "." ]
438131dca204ff7a5912f1c09e1d0df04b7dfee1
https://github.com/artdecocode/reloquent/blob/438131dca204ff7a5912f1c09e1d0df04b7dfee1/build/lib/ask-questions.js#L17-L79
train
ringa-js/ringa
src/ModelWatcher.js
objPath
function objPath(obj, path) { if (!path) { return obj; } path = path.split('.'); let i = 0; while (obj && i < path.length) { obj = obj[path[i++]]; } return obj; }
javascript
function objPath(obj, path) { if (!path) { return obj; } path = path.split('.'); let i = 0; while (obj && i < path.length) { obj = obj[path[i++]]; } return obj; }
[ "function", "objPath", "(", "obj", ",", "path", ")", "{", "if", "(", "!", "path", ")", "{", "return", "obj", ";", "}", "path", "=", "path", ".", "split", "(", "'.'", ")", ";", "let", "i", "=", "0", ";", "while", "(", "obj", "&&", "i", "<", "path", ".", "length", ")", "{", "obj", "=", "obj", "[", "path", "[", "i", "++", "]", "]", ";", "}", "return", "obj", ";", "}" ]
Retrieves a property by a dot-delimited path on a provided object. @param obj The object to search. @param path A dot-delimited path like 'prop1.prop2.prop3' @returns {*}
[ "Retrieves", "a", "property", "by", "a", "dot", "-", "delimited", "path", "on", "a", "provided", "object", "." ]
8773c00a21c05ffc942868a65fe2bd6f0f04d19e
https://github.com/ringa-js/ringa/blob/8773c00a21c05ffc942868a65fe2bd6f0f04d19e/src/ModelWatcher.js#L11-L21
train
artdecocode/reloquent
build/index.js
reloquent
async function reloquent(questions, timeout) { const res = await askQuestions(questions, timeout) return res }
javascript
async function reloquent(questions, timeout) { const res = await askQuestions(questions, timeout) return res }
[ "async", "function", "reloquent", "(", "questions", ",", "timeout", ")", "{", "const", "res", "=", "await", "askQuestions", "(", "questions", ",", "timeout", ")", "return", "res", "}" ]
Ask user questions via the CLI. Returns an object with keys as questions' texts and values as answers. @param {_reloquent.Questions} questions A set of questions. @param {number} [timeout] How long to wait before rejecting the promise. Waits forever by default.
[ "Ask", "user", "questions", "via", "the", "CLI", ".", "Returns", "an", "object", "with", "keys", "as", "questions", "texts", "and", "values", "as", "answers", "." ]
438131dca204ff7a5912f1c09e1d0df04b7dfee1
https://github.com/artdecocode/reloquent/blob/438131dca204ff7a5912f1c09e1d0df04b7dfee1/build/index.js#L8-L11
train
artdecocode/reloquent
build/index.js
askSingle
async function askSingle(question, timeout) { const { question: answer } = await askQuestions({ question }, timeout) return answer }
javascript
async function askSingle(question, timeout) { const { question: answer } = await askQuestions({ question }, timeout) return answer }
[ "async", "function", "askSingle", "(", "question", ",", "timeout", ")", "{", "const", "{", "question", ":", "answer", "}", "=", "await", "askQuestions", "(", "{", "question", "}", ",", "timeout", ")", "return", "answer", "}" ]
Ask user a question via the CLI. Returns the answer to the question. @param {string|!_reloquent.Question} question A question to present to the user. @param {number} [timeout] How long to wait before rejecting the promise. Waits forever by default.
[ "Ask", "user", "a", "question", "via", "the", "CLI", ".", "Returns", "the", "answer", "to", "the", "question", "." ]
438131dca204ff7a5912f1c09e1d0df04b7dfee1
https://github.com/artdecocode/reloquent/blob/438131dca204ff7a5912f1c09e1d0df04b7dfee1/build/index.js#L18-L21
train
ringa-js/ringa
src/Model.js
function (model, pojo, options) { pojo = pojo || {}; let props = model.serializeProperties || model.properties; props = props.filter(prop => (!model.propertyOptions[prop] || model.propertyOptions[prop].serialize !== false)); props.forEach(key => { let obj; let o = model.propertyOptions[key]; if (o && o.preSerialize) { obj = o.preSerialize(options); } else { obj = model[key]; } if (obj instanceof Array) { let newArr = []; obj.forEach(item => { newArr.push(item instanceof Model ? item.serialize() : item); }); pojo[key] = newArr; } else if (obj instanceof Model) { pojo[key] = obj.serialize(options); } else { pojo[key] = obj; } if (o && o.postSerialize) { o.postSerialize(options); } }); if (model.postSerialize) { model.postSerialize(pojo, options); } return pojo; }
javascript
function (model, pojo, options) { pojo = pojo || {}; let props = model.serializeProperties || model.properties; props = props.filter(prop => (!model.propertyOptions[prop] || model.propertyOptions[prop].serialize !== false)); props.forEach(key => { let obj; let o = model.propertyOptions[key]; if (o && o.preSerialize) { obj = o.preSerialize(options); } else { obj = model[key]; } if (obj instanceof Array) { let newArr = []; obj.forEach(item => { newArr.push(item instanceof Model ? item.serialize() : item); }); pojo[key] = newArr; } else if (obj instanceof Model) { pojo[key] = obj.serialize(options); } else { pojo[key] = obj; } if (o && o.postSerialize) { o.postSerialize(options); } }); if (model.postSerialize) { model.postSerialize(pojo, options); } return pojo; }
[ "function", "(", "model", ",", "pojo", ",", "options", ")", "{", "pojo", "=", "pojo", "||", "{", "}", ";", "let", "props", "=", "model", ".", "serializeProperties", "||", "model", ".", "properties", ";", "props", "=", "props", ".", "filter", "(", "prop", "=>", "(", "!", "model", ".", "propertyOptions", "[", "prop", "]", "||", "model", ".", "propertyOptions", "[", "prop", "]", ".", "serialize", "!==", "false", ")", ")", ";", "props", ".", "forEach", "(", "key", "=>", "{", "let", "obj", ";", "let", "o", "=", "model", ".", "propertyOptions", "[", "key", "]", ";", "if", "(", "o", "&&", "o", ".", "preSerialize", ")", "{", "obj", "=", "o", ".", "preSerialize", "(", "options", ")", ";", "}", "else", "{", "obj", "=", "model", "[", "key", "]", ";", "}", "if", "(", "obj", "instanceof", "Array", ")", "{", "let", "newArr", "=", "[", "]", ";", "obj", ".", "forEach", "(", "item", "=>", "{", "newArr", ".", "push", "(", "item", "instanceof", "Model", "?", "item", ".", "serialize", "(", ")", ":", "item", ")", ";", "}", ")", ";", "pojo", "[", "key", "]", "=", "newArr", ";", "}", "else", "if", "(", "obj", "instanceof", "Model", ")", "{", "pojo", "[", "key", "]", "=", "obj", ".", "serialize", "(", "options", ")", ";", "}", "else", "{", "pojo", "[", "key", "]", "=", "obj", ";", "}", "if", "(", "o", "&&", "o", ".", "postSerialize", ")", "{", "o", ".", "postSerialize", "(", "options", ")", ";", "}", "}", ")", ";", "if", "(", "model", ".", "postSerialize", ")", "{", "model", ".", "postSerialize", "(", "pojo", ",", "options", ")", ";", "}", "return", "pojo", ";", "}" ]
Serialize a Ringa Model object to a POJO by iterating over properties recursively on any descendent Model instances. @param model @param pojo @returns {*|{}} @private
[ "Serialize", "a", "Ringa", "Model", "object", "to", "a", "POJO", "by", "iterating", "over", "properties", "recursively", "on", "any", "descendent", "Model", "instances", "." ]
8773c00a21c05ffc942868a65fe2bd6f0f04d19e
https://github.com/ringa-js/ringa/blob/8773c00a21c05ffc942868a65fe2bd6f0f04d19e/src/Model.js#L22-L64
train
deskpro/apps-sdk-core
src/main/javascript/WebAPI/index.js
registerEventHandlers
function registerEventHandlers(windowBridge, app) { "use strict"; handleOutgoingEvent(windowBridge, app, WebAPIEvents.EVENT_WEBAPI_REQUEST_DESKPRO, WebAPIEvents.props.EVENT_WEBAPI_REQUEST_DESKPRO); handleOutgoingEvent(windowBridge, app, WebAPIEvents.EVENT_WEBAPI_REQUEST_FETCH, WebAPIEvents.props.EVENT_WEBAPI_REQUEST_FETCH); }
javascript
function registerEventHandlers(windowBridge, app) { "use strict"; handleOutgoingEvent(windowBridge, app, WebAPIEvents.EVENT_WEBAPI_REQUEST_DESKPRO, WebAPIEvents.props.EVENT_WEBAPI_REQUEST_DESKPRO); handleOutgoingEvent(windowBridge, app, WebAPIEvents.EVENT_WEBAPI_REQUEST_FETCH, WebAPIEvents.props.EVENT_WEBAPI_REQUEST_FETCH); }
[ "function", "registerEventHandlers", "(", "windowBridge", ",", "app", ")", "{", "\"use strict\"", ";", "handleOutgoingEvent", "(", "windowBridge", ",", "app", ",", "WebAPIEvents", ".", "EVENT_WEBAPI_REQUEST_DESKPRO", ",", "WebAPIEvents", ".", "props", ".", "EVENT_WEBAPI_REQUEST_DESKPRO", ")", ";", "handleOutgoingEvent", "(", "windowBridge", ",", "app", ",", "WebAPIEvents", ".", "EVENT_WEBAPI_REQUEST_FETCH", ",", "WebAPIEvents", ".", "props", ".", "EVENT_WEBAPI_REQUEST_FETCH", ")", ";", "}" ]
Registers the WebAPI events with the event dispatching system @param {WidgetWindowBridge} windowBridge @param {AppClient} app
[ "Registers", "the", "WebAPI", "events", "with", "the", "event", "dispatching", "system" ]
27f41bdf9b25dc7f007836ca96e156f6e8ec47a5
https://github.com/deskpro/apps-sdk-core/blob/27f41bdf9b25dc7f007836ca96e156f6e8ec47a5/src/main/javascript/WebAPI/index.js#L16-L21
train
artdecocode/reloquent
build/lib/ask.js
ask
function ask(question, options = {}) { const { timeout, password = false, output = process.stdout, input = process.stdin, ...rest } = options const rl = createInterface(/** @type {!readline.ReadLineOptions} */ ({ input, output, ...rest, })) if (password) { /** * Undocumented API. * @type {!NodeJS.WriteStream} * @suppress {checkTypes} */ const o = rl['output'] /** * Undocumented API. * @suppress {checkTypes} */ rl['_writeToOutput'] = (s) => { if (['\r\n', '\n', '\r'].includes(s)) return o.write(s) const v = s.split(question) if (v.length == '2') { o.write(question) o.write('*'.repeat(v[1].length)) } else { o.write('*') } } } const p = new Promise(rl.question.bind(rl, question)) const promise = timeout ? promto(p, timeout, `reloquent: ${question}`) : p /** * @suppress {checkTypes} */ rl['promise'] = tryPromise(promise, rl) return rl }
javascript
function ask(question, options = {}) { const { timeout, password = false, output = process.stdout, input = process.stdin, ...rest } = options const rl = createInterface(/** @type {!readline.ReadLineOptions} */ ({ input, output, ...rest, })) if (password) { /** * Undocumented API. * @type {!NodeJS.WriteStream} * @suppress {checkTypes} */ const o = rl['output'] /** * Undocumented API. * @suppress {checkTypes} */ rl['_writeToOutput'] = (s) => { if (['\r\n', '\n', '\r'].includes(s)) return o.write(s) const v = s.split(question) if (v.length == '2') { o.write(question) o.write('*'.repeat(v[1].length)) } else { o.write('*') } } } const p = new Promise(rl.question.bind(rl, question)) const promise = timeout ? promto(p, timeout, `reloquent: ${question}`) : p /** * @suppress {checkTypes} */ rl['promise'] = tryPromise(promise, rl) return rl }
[ "function", "ask", "(", "question", ",", "options", "=", "{", "}", ")", "{", "const", "{", "timeout", ",", "password", "=", "false", ",", "output", "=", "process", ".", "stdout", ",", "input", "=", "process", ".", "stdin", ",", "...", "rest", "}", "=", "options", "const", "rl", "=", "createInterface", "(", "(", "{", "input", ",", "output", ",", "...", "rest", ",", "}", ")", ")", "if", "(", "password", ")", "{", "const", "o", "=", "rl", "[", "'output'", "]", "rl", "[", "'_writeToOutput'", "]", "=", "(", "s", ")", "=>", "{", "if", "(", "[", "'\\r\\n'", ",", "\\r", ",", "\\n", "]", ".", "'\\n'", "\\n", ")", "'\\r'", "\\r", "includes", "}", "}", "(", "s", ")", "return", "o", ".", "write", "(", "s", ")", "const", "v", "=", "s", ".", "split", "(", "question", ")", "if", "(", "v", ".", "length", "==", "'2'", ")", "{", "o", ".", "write", "(", "question", ")", "o", ".", "write", "(", "'*'", ".", "repeat", "(", "v", "[", "1", "]", ".", "length", ")", ")", "}", "else", "{", "o", ".", "write", "(", "'*'", ")", "}", "}" ]
Ask user a question and wait for an answer. @param {string} question Question to present to the user. @param {{ password: (boolean| undefined), timeout: (number|undefined), input: (stream.Readable|NodeJS.ReadStream|undefined), output: (stream.Writable|NodeJS.WriteStream|undefined) }} options The options.
[ "Ask", "user", "a", "question", "and", "wait", "for", "an", "answer", "." ]
438131dca204ff7a5912f1c09e1d0df04b7dfee1
https://github.com/artdecocode/reloquent/blob/438131dca204ff7a5912f1c09e1d0df04b7dfee1/build/lib/ask.js#L9-L56
train
rigtorp/statkit
statkit.js
hm
function hm(n, v, incv, offv, tau, b, offb) { // Apply householder transformation b = b - tau v v' b // LAPACK: DLARF if (tau === 0.0) { return; } // compute v' b var d = b[offb + 0]; for (var i = 1; i < n; ++i) { d += b[offb + i] * v[offv + incv*i]; } // compute b = b - tau v v' b b[offb + 0] -= tau * d; for (var i = 1; i < n; ++i) { b[offb + i] -= tau * v[offv + incv*i] * d; } }
javascript
function hm(n, v, incv, offv, tau, b, offb) { // Apply householder transformation b = b - tau v v' b // LAPACK: DLARF if (tau === 0.0) { return; } // compute v' b var d = b[offb + 0]; for (var i = 1; i < n; ++i) { d += b[offb + i] * v[offv + incv*i]; } // compute b = b - tau v v' b b[offb + 0] -= tau * d; for (var i = 1; i < n; ++i) { b[offb + i] -= tau * v[offv + incv*i] * d; } }
[ "function", "hm", "(", "n", ",", "v", ",", "incv", ",", "offv", ",", "tau", ",", "b", ",", "offb", ")", "{", "if", "(", "tau", "===", "0.0", ")", "{", "return", ";", "}", "var", "d", "=", "b", "[", "offb", "+", "0", "]", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "n", ";", "++", "i", ")", "{", "d", "+=", "b", "[", "offb", "+", "i", "]", "*", "v", "[", "offv", "+", "incv", "*", "i", "]", ";", "}", "b", "[", "offb", "+", "0", "]", "-=", "tau", "*", "d", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "n", ";", "++", "i", ")", "{", "b", "[", "offb", "+", "i", "]", "-=", "tau", "*", "v", "[", "offv", "+", "incv", "*", "i", "]", "*", "d", ";", "}", "}" ]
Solve the least squares problem min ||Ax=b||
[ "Solve", "the", "least", "squares", "problem", "min", "||Ax", "=", "b||" ]
9946254429aa592195c606ac3e93740b58206065
https://github.com/rigtorp/statkit/blob/9946254429aa592195c606ac3e93740b58206065/statkit.js#L594-L613
train
erossignon/node-STEP
stepIndexer.js
check_STEP_file
function check_STEP_file(filename, callback) { "use strict"; // "ISO-10303-21;" // "HEADER;" var stream = fs.createReadStream(filename, {flags:"r"}); var fileData = ""; stream.on('data', function (data) { fileData += data; // The next lines should be improved var lines = fileData.split("\n"); if (lines.length >= 2) { stream.destroy(); if (!pattern_ISO_10303_21.test(lines[0])) { my_callback(new Error("this file is not a STEP FILE : ISO_10303_21 missing")); } else { my_callback(null, lines[0]); } } }); stream.on('error', function () { my_callback('Error', null); }); stream.on('end', function () { my_callback('File end reached without finding line', null); }); var callback_called = false; function my_callback(err, data) { if (!callback_called) { callback_called = true; callback(err, data); } } }
javascript
function check_STEP_file(filename, callback) { "use strict"; // "ISO-10303-21;" // "HEADER;" var stream = fs.createReadStream(filename, {flags:"r"}); var fileData = ""; stream.on('data', function (data) { fileData += data; // The next lines should be improved var lines = fileData.split("\n"); if (lines.length >= 2) { stream.destroy(); if (!pattern_ISO_10303_21.test(lines[0])) { my_callback(new Error("this file is not a STEP FILE : ISO_10303_21 missing")); } else { my_callback(null, lines[0]); } } }); stream.on('error', function () { my_callback('Error', null); }); stream.on('end', function () { my_callback('File end reached without finding line', null); }); var callback_called = false; function my_callback(err, data) { if (!callback_called) { callback_called = true; callback(err, data); } } }
[ "function", "check_STEP_file", "(", "filename", ",", "callback", ")", "{", "\"use strict\"", ";", "var", "stream", "=", "fs", ".", "createReadStream", "(", "filename", ",", "{", "flags", ":", "\"r\"", "}", ")", ";", "var", "fileData", "=", "\"\"", ";", "stream", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "fileData", "+=", "data", ";", "var", "lines", "=", "fileData", ".", "split", "(", "\"\\n\"", ")", ";", "\\n", "}", ")", ";", "if", "(", "lines", ".", "length", ">=", "2", ")", "{", "stream", ".", "destroy", "(", ")", ";", "if", "(", "!", "pattern_ISO_10303_21", ".", "test", "(", "lines", "[", "0", "]", ")", ")", "{", "my_callback", "(", "new", "Error", "(", "\"this file is not a STEP FILE : ISO_10303_21 missing\"", ")", ")", ";", "}", "else", "{", "my_callback", "(", "null", ",", "lines", "[", "0", "]", ")", ";", "}", "}", "stream", ".", "on", "(", "'error'", ",", "function", "(", ")", "{", "my_callback", "(", "'Error'", ",", "null", ")", ";", "}", ")", ";", "stream", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "my_callback", "(", "'File end reached without finding line'", ",", "null", ")", ";", "}", ")", ";", "var", "callback_called", "=", "false", ";", "}" ]
return true if the file is a correct STEP file a correct STEP file starts with ISO-10303-21; HEADER; @param filename @param callback
[ "return", "true", "if", "the", "file", "is", "a", "correct", "STEP", "file", "a", "correct", "STEP", "file", "starts", "with", "ISO", "-", "10303", "-", "21", ";", "HEADER", ";" ]
8814e5b95633f1fb314a6f10e482c14a878dee52
https://github.com/erossignon/node-STEP/blob/8814e5b95633f1fb314a6f10e482c14a878dee52/stepIndexer.js#L276-L317
train
rstacruz/ionicons-inline
support/convert.js
process
function process (svg, { prefix }) { // Inject a <style> in the SVG document to allow changing colors svg = svg.replace(/<(path|circle) /gi, (_, tag) => `<${tag} fill="__COLOR__" `) // Since this is a data: URI, we want to encode it with %23 and such svg = encodeURIComponent(svg) // We want the #{...} interpolation to be outside the URI encoding svg = svg.replace(/__COLOR__/g, '#{' + prefix + '-fix-color($color)}') svg = 'data:image/svg+xml;charset=utf-8,' + svg return svg }
javascript
function process (svg, { prefix }) { // Inject a <style> in the SVG document to allow changing colors svg = svg.replace(/<(path|circle) /gi, (_, tag) => `<${tag} fill="__COLOR__" `) // Since this is a data: URI, we want to encode it with %23 and such svg = encodeURIComponent(svg) // We want the #{...} interpolation to be outside the URI encoding svg = svg.replace(/__COLOR__/g, '#{' + prefix + '-fix-color($color)}') svg = 'data:image/svg+xml;charset=utf-8,' + svg return svg }
[ "function", "process", "(", "svg", ",", "{", "prefix", "}", ")", "{", "svg", "=", "svg", ".", "replace", "(", "/", "<(path|circle) ", "/", "gi", ",", "(", "_", ",", "tag", ")", "=>", "`", "${", "tag", "}", "`", ")", "svg", "=", "encodeURIComponent", "(", "svg", ")", "svg", "=", "svg", ".", "replace", "(", "/", "__COLOR__", "/", "g", ",", "'#{'", "+", "prefix", "+", "'-fix-color($color)}'", ")", "svg", "=", "'data:image/svg+xml;charset=utf-8,'", "+", "svg", "return", "svg", "}" ]
Converts the SVG into a data URI. @private
[ "Converts", "the", "SVG", "into", "a", "data", "URI", "." ]
3ee918cc07d93b853daeaff361bdd634594a3763
https://github.com/rstacruz/ionicons-inline/blob/3ee918cc07d93b853daeaff361bdd634594a3763/support/convert.js#L60-L73
train
DarkXaHTeP/vk-auth
lib/scrapper/index.js
function (login, pass) { try { document.getElementsByName("email")[0].value = login; document.getElementsByName("pass")[0].value = pass; document.getElementById("login_submit").submit(); } catch (e) { } }
javascript
function (login, pass) { try { document.getElementsByName("email")[0].value = login; document.getElementsByName("pass")[0].value = pass; document.getElementById("login_submit").submit(); } catch (e) { } }
[ "function", "(", "login", ",", "pass", ")", "{", "try", "{", "document", ".", "getElementsByName", "(", "\"email\"", ")", "[", "0", "]", ".", "value", "=", "login", ";", "document", ".", "getElementsByName", "(", "\"pass\"", ")", "[", "0", "]", ".", "value", "=", "pass", ";", "document", ".", "getElementById", "(", "\"login_submit\"", ")", ".", "submit", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}" ]
that enters user's credentials on VK login page
[ "that", "enters", "user", "s", "credentials", "on", "VK", "login", "page" ]
ff4cf2675b4f450eee59c620634eea6d94143985
https://github.com/DarkXaHTeP/vk-auth/blob/ff4cf2675b4f450eee59c620634eea6d94143985/lib/scrapper/index.js#L41-L48
train
xixilive/weapp-next
es6/weapp/enhancements.js
shortcutRequest
function shortcutRequest(req){ req.get = shortcut(req, 'GET') req.post = shortcut(req, 'POST') req.put = shortcut(req, 'PUT') req.patch = shortcut(req, 'PATCH') req['delete'] = shortcut(req, 'DELETE') req.options = shortcut(req, 'OPTIONS') req.head = shortcut(req, 'HEAD') req.trace = shortcut(req, 'TRACE') req.connect = shortcut(req, 'CONNECT') return req }
javascript
function shortcutRequest(req){ req.get = shortcut(req, 'GET') req.post = shortcut(req, 'POST') req.put = shortcut(req, 'PUT') req.patch = shortcut(req, 'PATCH') req['delete'] = shortcut(req, 'DELETE') req.options = shortcut(req, 'OPTIONS') req.head = shortcut(req, 'HEAD') req.trace = shortcut(req, 'TRACE') req.connect = shortcut(req, 'CONNECT') return req }
[ "function", "shortcutRequest", "(", "req", ")", "{", "req", ".", "get", "=", "shortcut", "(", "req", ",", "'GET'", ")", "req", ".", "post", "=", "shortcut", "(", "req", ",", "'POST'", ")", "req", ".", "put", "=", "shortcut", "(", "req", ",", "'PUT'", ")", "req", ".", "patch", "=", "shortcut", "(", "req", ",", "'PATCH'", ")", "req", "[", "'delete'", "]", "=", "shortcut", "(", "req", ",", "'DELETE'", ")", "req", ".", "options", "=", "shortcut", "(", "req", ",", "'OPTIONS'", ")", "req", ".", "head", "=", "shortcut", "(", "req", ",", "'HEAD'", ")", "req", ".", "trace", "=", "shortcut", "(", "req", ",", "'TRACE'", ")", "req", ".", "connect", "=", "shortcut", "(", "req", ",", "'CONNECT'", ")", "return", "req", "}" ]
to decorate promisified request function
[ "to", "decorate", "promisified", "request", "function" ]
4390d7dbabc73206d3b82fb909a13375b7eaa945
https://github.com/xixilive/weapp-next/blob/4390d7dbabc73206d3b82fb909a13375b7eaa945/es6/weapp/enhancements.js#L27-L38
train
rigtorp/statkit
examples/mcmc.js
lnprior
function lnprior(theta) { var m = theta[0], b = theta[1], t = theta[2]; if (0.0 < m && m < 1.0 && 0.0 < b && b < 10.0 && 0.0 < t && t < 100.0) { return 0.0; } return -Infinity; }
javascript
function lnprior(theta) { var m = theta[0], b = theta[1], t = theta[2]; if (0.0 < m && m < 1.0 && 0.0 < b && b < 10.0 && 0.0 < t && t < 100.0) { return 0.0; } return -Infinity; }
[ "function", "lnprior", "(", "theta", ")", "{", "var", "m", "=", "theta", "[", "0", "]", ",", "b", "=", "theta", "[", "1", "]", ",", "t", "=", "theta", "[", "2", "]", ";", "if", "(", "0.0", "<", "m", "&&", "m", "<", "1.0", "&&", "0.0", "<", "b", "&&", "b", "<", "10.0", "&&", "0.0", "<", "t", "&&", "t", "<", "100.0", ")", "{", "return", "0.0", ";", "}", "return", "-", "Infinity", ";", "}" ]
uniform log-prior for m, b, t
[ "uniform", "log", "-", "prior", "for", "m", "b", "t" ]
9946254429aa592195c606ac3e93740b58206065
https://github.com/rigtorp/statkit/blob/9946254429aa592195c606ac3e93740b58206065/examples/mcmc.js#L15-L21
train
rigtorp/statkit
examples/mcmc.js
lnpost
function lnpost(theta, x, y) { var lp = lnprior(theta); if (!isFinite(lp)) { return -Infinity; } return lp + lnlike(theta, x, y); }
javascript
function lnpost(theta, x, y) { var lp = lnprior(theta); if (!isFinite(lp)) { return -Infinity; } return lp + lnlike(theta, x, y); }
[ "function", "lnpost", "(", "theta", ",", "x", ",", "y", ")", "{", "var", "lp", "=", "lnprior", "(", "theta", ")", ";", "if", "(", "!", "isFinite", "(", "lp", ")", ")", "{", "return", "-", "Infinity", ";", "}", "return", "lp", "+", "lnlike", "(", "theta", ",", "x", ",", "y", ")", ";", "}" ]
posterior log-probability function
[ "posterior", "log", "-", "probability", "function" ]
9946254429aa592195c606ac3e93740b58206065
https://github.com/rigtorp/statkit/blob/9946254429aa592195c606ac3e93740b58206065/examples/mcmc.js#L24-L30
train
ctxhou/postcss-hash-classname
index.js
renameSelector
function renameSelector(selector, sourcePath, opts, mappings) { return selector.map(function(selector){ return parser(function(sels) { sels.map(function(sel) { renameNodes(sel.nodes, sourcePath, opts, mappings); }) }).process(selector).result }); }
javascript
function renameSelector(selector, sourcePath, opts, mappings) { return selector.map(function(selector){ return parser(function(sels) { sels.map(function(sel) { renameNodes(sel.nodes, sourcePath, opts, mappings); }) }).process(selector).result }); }
[ "function", "renameSelector", "(", "selector", ",", "sourcePath", ",", "opts", ",", "mappings", ")", "{", "return", "selector", ".", "map", "(", "function", "(", "selector", ")", "{", "return", "parser", "(", "function", "(", "sels", ")", "{", "sels", ".", "map", "(", "function", "(", "sel", ")", "{", "renameNodes", "(", "sel", ".", "nodes", ",", "sourcePath", ",", "opts", ",", "mappings", ")", ";", "}", ")", "}", ")", ".", "process", "(", "selector", ")", ".", "result", "}", ")", ";", "}" ]
Renames all classnames in a css rule selector @param selector css selector @param sourcePath Source file's path @param opts Options object @param mappings Classname to renamed classname mappings repository @return {*} Renamed css rule selector
[ "Renames", "all", "classnames", "in", "a", "css", "rule", "selector" ]
325d824acc0a1e2ba21832eadeb06106f8d1b8f1
https://github.com/ctxhou/postcss-hash-classname/blob/325d824acc0a1e2ba21832eadeb06106f8d1b8f1/index.js#L15-L23
train
ctxhou/postcss-hash-classname
index.js
renameNodes
function renameNodes(nodes, sourcePath, opts, mappings) { return nodes.map(function(node) { // Process CSS node if (node.type === 'class') { // Process "class" node var orgValue = node.value, newValue = renameClassNode(node.value, sourcePath, opts); // Edit node and store mapping of classname renaming node.value = mappings[orgValue] = newValue; } else if (node.type === 'pseudo' && node.value === ':not') { // Process ":not([selector])" pseudo node renameNodes(node.nodes, sourcePath, opts, mappings); } else if (node.type === 'selector') { // Rename selector nodes renameNodes(node.nodes, sourcePath, opts, mappings) } }); }
javascript
function renameNodes(nodes, sourcePath, opts, mappings) { return nodes.map(function(node) { // Process CSS node if (node.type === 'class') { // Process "class" node var orgValue = node.value, newValue = renameClassNode(node.value, sourcePath, opts); // Edit node and store mapping of classname renaming node.value = mappings[orgValue] = newValue; } else if (node.type === 'pseudo' && node.value === ':not') { // Process ":not([selector])" pseudo node renameNodes(node.nodes, sourcePath, opts, mappings); } else if (node.type === 'selector') { // Rename selector nodes renameNodes(node.nodes, sourcePath, opts, mappings) } }); }
[ "function", "renameNodes", "(", "nodes", ",", "sourcePath", ",", "opts", ",", "mappings", ")", "{", "return", "nodes", ".", "map", "(", "function", "(", "node", ")", "{", "if", "(", "node", ".", "type", "===", "'class'", ")", "{", "var", "orgValue", "=", "node", ".", "value", ",", "newValue", "=", "renameClassNode", "(", "node", ".", "value", ",", "sourcePath", ",", "opts", ")", ";", "node", ".", "value", "=", "mappings", "[", "orgValue", "]", "=", "newValue", ";", "}", "else", "if", "(", "node", ".", "type", "===", "'pseudo'", "&&", "node", ".", "value", "===", "':not'", ")", "{", "renameNodes", "(", "node", ".", "nodes", ",", "sourcePath", ",", "opts", ",", "mappings", ")", ";", "}", "else", "if", "(", "node", ".", "type", "===", "'selector'", ")", "{", "renameNodes", "(", "node", ".", "nodes", ",", "sourcePath", ",", "opts", ",", "mappings", ")", "}", "}", ")", ";", "}" ]
Renames all classnames in css nodes @param nodes css nodes @param sourcePath Source file's path @param opts Options object @param mappings Classname to renamed classname mappings repository @return {*} Renamed css nodes
[ "Renames", "all", "classnames", "in", "css", "nodes" ]
325d824acc0a1e2ba21832eadeb06106f8d1b8f1
https://github.com/ctxhou/postcss-hash-classname/blob/325d824acc0a1e2ba21832eadeb06106f8d1b8f1/index.js#L33-L50
train
ctxhou/postcss-hash-classname
index.js
renameClassNode
function renameClassNode(value, sourcePath, opts) { // Generate hashes var className = value, compositeHash = loaderUtils.getHashDigest( (sourcePath ? sourcePath + className : className), opts.hashType, opts.digestType, opts.maxLength), classHash = loaderUtils.getHashDigest( className, opts.hashType, opts.digestType, opts.maxLength), sourcePathHash = (sourcePath ? loaderUtils.getHashDigest( sourcePath, opts.hashType, opts.digestType, opts.maxLength) : ''), newClassName; // Check classname format type if (typeof opts.classnameFormat === 'string') { // Process classname as template newClassName = opts.classnameFormat .replace(/\[classname\]/gi, className) .replace(/\[hash\]/gi, compositeHash) .replace(/\[classnamehash\]/gi, classHash) .replace(/\[sourcepathash\]/gi, sourcePathHash); } else if (typeof opts.classnameFormat === 'function') { // Get new classname from callback newClassName = opts.classnameFormat(className, sourcePath); } else { // Keep classname newClassName = className; } // Return generated replacement classname return newClassName; }
javascript
function renameClassNode(value, sourcePath, opts) { // Generate hashes var className = value, compositeHash = loaderUtils.getHashDigest( (sourcePath ? sourcePath + className : className), opts.hashType, opts.digestType, opts.maxLength), classHash = loaderUtils.getHashDigest( className, opts.hashType, opts.digestType, opts.maxLength), sourcePathHash = (sourcePath ? loaderUtils.getHashDigest( sourcePath, opts.hashType, opts.digestType, opts.maxLength) : ''), newClassName; // Check classname format type if (typeof opts.classnameFormat === 'string') { // Process classname as template newClassName = opts.classnameFormat .replace(/\[classname\]/gi, className) .replace(/\[hash\]/gi, compositeHash) .replace(/\[classnamehash\]/gi, classHash) .replace(/\[sourcepathash\]/gi, sourcePathHash); } else if (typeof opts.classnameFormat === 'function') { // Get new classname from callback newClassName = opts.classnameFormat(className, sourcePath); } else { // Keep classname newClassName = className; } // Return generated replacement classname return newClassName; }
[ "function", "renameClassNode", "(", "value", ",", "sourcePath", ",", "opts", ")", "{", "var", "className", "=", "value", ",", "compositeHash", "=", "loaderUtils", ".", "getHashDigest", "(", "(", "sourcePath", "?", "sourcePath", "+", "className", ":", "className", ")", ",", "opts", ".", "hashType", ",", "opts", ".", "digestType", ",", "opts", ".", "maxLength", ")", ",", "classHash", "=", "loaderUtils", ".", "getHashDigest", "(", "className", ",", "opts", ".", "hashType", ",", "opts", ".", "digestType", ",", "opts", ".", "maxLength", ")", ",", "sourcePathHash", "=", "(", "sourcePath", "?", "loaderUtils", ".", "getHashDigest", "(", "sourcePath", ",", "opts", ".", "hashType", ",", "opts", ".", "digestType", ",", "opts", ".", "maxLength", ")", ":", "''", ")", ",", "newClassName", ";", "if", "(", "typeof", "opts", ".", "classnameFormat", "===", "'string'", ")", "{", "newClassName", "=", "opts", ".", "classnameFormat", ".", "replace", "(", "/", "\\[classname\\]", "/", "gi", ",", "className", ")", ".", "replace", "(", "/", "\\[hash\\]", "/", "gi", ",", "compositeHash", ")", ".", "replace", "(", "/", "\\[classnamehash\\]", "/", "gi", ",", "classHash", ")", ".", "replace", "(", "/", "\\[sourcepathash\\]", "/", "gi", ",", "sourcePathHash", ")", ";", "}", "else", "if", "(", "typeof", "opts", ".", "classnameFormat", "===", "'function'", ")", "{", "newClassName", "=", "opts", ".", "classnameFormat", "(", "className", ",", "sourcePath", ")", ";", "}", "else", "{", "newClassName", "=", "className", ";", "}", "return", "newClassName", ";", "}" ]
Generates a replacement css classname @param value Original classname @param sourcePath Source file's path @param opts Options object
[ "Generates", "a", "replacement", "css", "classname" ]
325d824acc0a1e2ba21832eadeb06106f8d1b8f1
https://github.com/ctxhou/postcss-hash-classname/blob/325d824acc0a1e2ba21832eadeb06106f8d1b8f1/index.js#L58-L82
train
ctxhou/postcss-hash-classname
index.js
verifyOptionType
function verifyOptionType(sourcePath, name, value) { if (typeof value === 'object') { var msg = 'POSTCSS-HASH-CLASSNAME ERROR: Object value not supported for option "' + name + '"!'; console.error(msg); throw new Error(msg); } else if (!sourcePath && typeof value === 'function') { var msg = 'POSTCSS-HASH-CLASSNAME ERROR: Source file\'s path isn not determined - only explicit values for option "' + name + '" supported! Value passed is a function.'; console.error(msg); throw new Error(msg); } else if (!sourcePath && ((value.toString().indexOf('[') >= 0) || (value.toString().indexOf(']') >= 0))) { var msg = 'POSTCSS-HASH-CLASSNAME WARNING: Source file\'s path isn not determined - only explicit values for option "' + name + '" supported! Value passed detected as using templating.'; console.warn(msg); } }
javascript
function verifyOptionType(sourcePath, name, value) { if (typeof value === 'object') { var msg = 'POSTCSS-HASH-CLASSNAME ERROR: Object value not supported for option "' + name + '"!'; console.error(msg); throw new Error(msg); } else if (!sourcePath && typeof value === 'function') { var msg = 'POSTCSS-HASH-CLASSNAME ERROR: Source file\'s path isn not determined - only explicit values for option "' + name + '" supported! Value passed is a function.'; console.error(msg); throw new Error(msg); } else if (!sourcePath && ((value.toString().indexOf('[') >= 0) || (value.toString().indexOf(']') >= 0))) { var msg = 'POSTCSS-HASH-CLASSNAME WARNING: Source file\'s path isn not determined - only explicit values for option "' + name + '" supported! Value passed detected as using templating.'; console.warn(msg); } }
[ "function", "verifyOptionType", "(", "sourcePath", ",", "name", ",", "value", ")", "{", "if", "(", "typeof", "value", "===", "'object'", ")", "{", "var", "msg", "=", "'POSTCSS-HASH-CLASSNAME ERROR: Object value not supported for option \"'", "+", "name", "+", "'\"!'", ";", "console", ".", "error", "(", "msg", ")", ";", "throw", "new", "Error", "(", "msg", ")", ";", "}", "else", "if", "(", "!", "sourcePath", "&&", "typeof", "value", "===", "'function'", ")", "{", "var", "msg", "=", "'POSTCSS-HASH-CLASSNAME ERROR: Source file\\'s path isn not determined - only explicit values for option \"'", "+", "\\'", "+", "name", ";", "'\" supported! Value passed is a function.'", "console", ".", "error", "(", "msg", ")", ";", "}", "else", "throw", "new", "Error", "(", "msg", ")", ";", "}" ]
Makes sure option is a string and outputs a warning to console if it seems like option is using templating @param sourcePath Source file's path @param name Validating option's name @param value Validating option's value
[ "Makes", "sure", "option", "is", "a", "string", "and", "outputs", "a", "warning", "to", "console", "if", "it", "seems", "like", "option", "is", "using", "templating" ]
325d824acc0a1e2ba21832eadeb06106f8d1b8f1
https://github.com/ctxhou/postcss-hash-classname/blob/325d824acc0a1e2ba21832eadeb06106f8d1b8f1/index.js#L90-L103
train
ctxhou/postcss-hash-classname
index.js
formatFileOutput
function formatFileOutput(mappings, type) { var string = JSON.stringify(mappings, null, 2); if (type === '.js') { return 'module.exports=' + string; } else if (type === '.json') { return string; } }
javascript
function formatFileOutput(mappings, type) { var string = JSON.stringify(mappings, null, 2); if (type === '.js') { return 'module.exports=' + string; } else if (type === '.json') { return string; } }
[ "function", "formatFileOutput", "(", "mappings", ",", "type", ")", "{", "var", "string", "=", "JSON", ".", "stringify", "(", "mappings", ",", "null", ",", "2", ")", ";", "if", "(", "type", "===", "'.js'", ")", "{", "return", "'module.exports='", "+", "string", ";", "}", "else", "if", "(", "type", "===", "'.json'", ")", "{", "return", "string", ";", "}", "}" ]
Formats class mapping output for writing to a file of specified type @param mappings Classname to renamed classname mappings repository @param type Output file type @return {string} Formatted output file contents
[ "Formats", "class", "mapping", "output", "for", "writing", "to", "a", "file", "of", "specified", "type" ]
325d824acc0a1e2ba21832eadeb06106f8d1b8f1
https://github.com/ctxhou/postcss-hash-classname/blob/325d824acc0a1e2ba21832eadeb06106f8d1b8f1/index.js#L111-L118
train
therebelbeta/json-mock
src/utils.js
createId
function createId(coll) { if (_.isEmpty(coll)) { return 1 } else { var id = _.max(coll, function(doc) { return doc.id }).id if (_.isFinite(id)) { // Increment integer id return ++id } else { // Generate string id return uuid() } } }
javascript
function createId(coll) { if (_.isEmpty(coll)) { return 1 } else { var id = _.max(coll, function(doc) { return doc.id }).id if (_.isFinite(id)) { // Increment integer id return ++id } else { // Generate string id return uuid() } } }
[ "function", "createId", "(", "coll", ")", "{", "if", "(", "_", ".", "isEmpty", "(", "coll", ")", ")", "{", "return", "1", "}", "else", "{", "var", "id", "=", "_", ".", "max", "(", "coll", ",", "function", "(", "doc", ")", "{", "return", "doc", ".", "id", "}", ")", ".", "id", "if", "(", "_", ".", "isFinite", "(", "id", ")", ")", "{", "return", "++", "id", "}", "else", "{", "return", "uuid", "(", ")", "}", "}", "}" ]
Return incremented id or uuid
[ "Return", "incremented", "id", "or", "uuid" ]
a138d20d943733ce85556d8b6cd45c23d4d5676d
https://github.com/therebelbeta/json-mock/blob/a138d20d943733ce85556d8b6cd45c23d4d5676d/src/utils.js#L24-L40
train
blakeembrey/simulate-event
simulate-event.js
getOverrides
function getOverrides (eventType, options) { if (eventType === 'KeyboardEvent' && options) { return { keyCode: options.keyCode || 0, key: options.key || 0, which: options.which || options.keyCode || 0 } } }
javascript
function getOverrides (eventType, options) { if (eventType === 'KeyboardEvent' && options) { return { keyCode: options.keyCode || 0, key: options.key || 0, which: options.which || options.keyCode || 0 } } }
[ "function", "getOverrides", "(", "eventType", ",", "options", ")", "{", "if", "(", "eventType", "===", "'KeyboardEvent'", "&&", "options", ")", "{", "return", "{", "keyCode", ":", "options", ".", "keyCode", "||", "0", ",", "key", ":", "options", ".", "key", "||", "0", ",", "which", ":", "options", ".", "which", "||", "options", ".", "keyCode", "||", "0", "}", "}", "}" ]
Get attributes which must be overriden manually. @param {String} eventType @param {Object} options.
[ "Get", "attributes", "which", "must", "be", "overriden", "manually", "." ]
56196882e66d0f7d033de4c71e99cef724b2adb1
https://github.com/blakeembrey/simulate-event/blob/56196882e66d0f7d033de4c71e99cef724b2adb1/simulate-event.js#L282-L290
train
samuelneff/topsort
lib/topsort.js
topsort
function topsort(edges, options) { var nodes = {}; options = options || { continueOnCircularDependency: false }; var sorted = []; // hash: id of already visited node => true var visited = {}; // 1. build data structures edges.forEach(function (edge) { var fromEdge = edge[0]; var fromStr = fromEdge.toString(); var fromNode; if (!(fromNode = nodes[fromStr])) { fromNode = nodes[fromStr] = new EdgeNode(fromEdge); } edge.forEach(function (toEdge) { // since from and to are in same array, we'll always see from again, so make sure we skip it.. if (toEdge == fromEdge) { return; } var toEdgeStr = toEdge.toString(); if (!nodes[toEdgeStr]) { nodes[toEdgeStr] = new EdgeNode(toEdge); } fromNode.afters.push(toEdge); }); }); // 2. topological sort var keys = Object.keys(nodes); keys.sort(sortDesc); keys.forEach(function visit(idstr, ancestorsIn) { var node = nodes[idstr]; var id = node.id; // if already exists, do nothing if (visited[idstr]) { return; } var ancestors = Array.isArray(ancestorsIn) ? ancestorsIn : []; ancestors.push(id); visited[idstr] = true; node.afters.sort(sortDesc); node.afters.forEach(function (afterID) { // if already in ancestors, a closed chain exists. if (ancestors.indexOf(afterID) >= 0) { if (options.continueOnCircularDependency) { return; } throw new Error('Circular chain found: ' + id + ' must be before ' + afterID + ' due to a direct order specification, but ' + afterID + ' must be before ' + id + ' based on other specifications.'); } // recursive call visit(afterID.toString(), ancestors.map(function (v) { return v; })); }); sorted.unshift(id); }); return sorted; }
javascript
function topsort(edges, options) { var nodes = {}; options = options || { continueOnCircularDependency: false }; var sorted = []; // hash: id of already visited node => true var visited = {}; // 1. build data structures edges.forEach(function (edge) { var fromEdge = edge[0]; var fromStr = fromEdge.toString(); var fromNode; if (!(fromNode = nodes[fromStr])) { fromNode = nodes[fromStr] = new EdgeNode(fromEdge); } edge.forEach(function (toEdge) { // since from and to are in same array, we'll always see from again, so make sure we skip it.. if (toEdge == fromEdge) { return; } var toEdgeStr = toEdge.toString(); if (!nodes[toEdgeStr]) { nodes[toEdgeStr] = new EdgeNode(toEdge); } fromNode.afters.push(toEdge); }); }); // 2. topological sort var keys = Object.keys(nodes); keys.sort(sortDesc); keys.forEach(function visit(idstr, ancestorsIn) { var node = nodes[idstr]; var id = node.id; // if already exists, do nothing if (visited[idstr]) { return; } var ancestors = Array.isArray(ancestorsIn) ? ancestorsIn : []; ancestors.push(id); visited[idstr] = true; node.afters.sort(sortDesc); node.afters.forEach(function (afterID) { // if already in ancestors, a closed chain exists. if (ancestors.indexOf(afterID) >= 0) { if (options.continueOnCircularDependency) { return; } throw new Error('Circular chain found: ' + id + ' must be before ' + afterID + ' due to a direct order specification, but ' + afterID + ' must be before ' + id + ' based on other specifications.'); } // recursive call visit(afterID.toString(), ancestors.map(function (v) { return v; })); }); sorted.unshift(id); }); return sorted; }
[ "function", "topsort", "(", "edges", ",", "options", ")", "{", "var", "nodes", "=", "{", "}", ";", "options", "=", "options", "||", "{", "continueOnCircularDependency", ":", "false", "}", ";", "var", "sorted", "=", "[", "]", ";", "var", "visited", "=", "{", "}", ";", "edges", ".", "forEach", "(", "function", "(", "edge", ")", "{", "var", "fromEdge", "=", "edge", "[", "0", "]", ";", "var", "fromStr", "=", "fromEdge", ".", "toString", "(", ")", ";", "var", "fromNode", ";", "if", "(", "!", "(", "fromNode", "=", "nodes", "[", "fromStr", "]", ")", ")", "{", "fromNode", "=", "nodes", "[", "fromStr", "]", "=", "new", "EdgeNode", "(", "fromEdge", ")", ";", "}", "edge", ".", "forEach", "(", "function", "(", "toEdge", ")", "{", "if", "(", "toEdge", "==", "fromEdge", ")", "{", "return", ";", "}", "var", "toEdgeStr", "=", "toEdge", ".", "toString", "(", ")", ";", "if", "(", "!", "nodes", "[", "toEdgeStr", "]", ")", "{", "nodes", "[", "toEdgeStr", "]", "=", "new", "EdgeNode", "(", "toEdge", ")", ";", "}", "fromNode", ".", "afters", ".", "push", "(", "toEdge", ")", ";", "}", ")", ";", "}", ")", ";", "var", "keys", "=", "Object", ".", "keys", "(", "nodes", ")", ";", "keys", ".", "sort", "(", "sortDesc", ")", ";", "keys", ".", "forEach", "(", "function", "visit", "(", "idstr", ",", "ancestorsIn", ")", "{", "var", "node", "=", "nodes", "[", "idstr", "]", ";", "var", "id", "=", "node", ".", "id", ";", "if", "(", "visited", "[", "idstr", "]", ")", "{", "return", ";", "}", "var", "ancestors", "=", "Array", ".", "isArray", "(", "ancestorsIn", ")", "?", "ancestorsIn", ":", "[", "]", ";", "ancestors", ".", "push", "(", "id", ")", ";", "visited", "[", "idstr", "]", "=", "true", ";", "node", ".", "afters", ".", "sort", "(", "sortDesc", ")", ";", "node", ".", "afters", ".", "forEach", "(", "function", "(", "afterID", ")", "{", "if", "(", "ancestors", ".", "indexOf", "(", "afterID", ")", ">=", "0", ")", "{", "if", "(", "options", ".", "continueOnCircularDependency", ")", "{", "return", ";", "}", "throw", "new", "Error", "(", "'Circular chain found: '", "+", "id", "+", "' must be before '", "+", "afterID", "+", "' due to a direct order specification, but '", "+", "afterID", "+", "' must be before '", "+", "id", "+", "' based on other specifications.'", ")", ";", "}", "visit", "(", "afterID", ".", "toString", "(", ")", ",", "ancestors", ".", "map", "(", "function", "(", "v", ")", "{", "return", "v", ";", "}", ")", ")", ";", "}", ")", ";", "sorted", ".", "unshift", "(", "id", ")", ";", "}", ")", ";", "return", "sorted", ";", "}" ]
general topological sort @param edges : list of edges. each edge forms Array<ID,ID> e.g. [12 , 3] @param options When provided with 'continueOnCircularDependency' set to true, sorting will continue even if a circular dependency is found. The precise sort is not guaranteed. @returns Array : topological sorted list of IDs
[ "general", "topological", "sort" ]
1b5f4ea075d3f6a6fac9898ba94642dec222c928
https://github.com/samuelneff/topsort/blob/1b5f4ea075d3f6a6fac9898ba94642dec222c928/lib/topsort.js#L36-L107
train
DeviaVir/node-vultr
vultr.js
Vultr
function Vultr(apiKey) { this.version = 'v1'; this.endpoint = 'https://api.vultr.com/' + this.version + '/'; this.apiKey = (apiKey ? apiKey : config.vultr.apiKey); this.account = new account(this); this.dns = new dns(this); this.os = new os(this); this.iso = new iso(this); this.backup = new backup(this); this.plans = new plans(this); this.regions = new regions(this); this.server = new server(this); this.snapshot = new snapshot(this); this.sshkey = new sshkey(this); this.startupscript = new startupscript(this); }
javascript
function Vultr(apiKey) { this.version = 'v1'; this.endpoint = 'https://api.vultr.com/' + this.version + '/'; this.apiKey = (apiKey ? apiKey : config.vultr.apiKey); this.account = new account(this); this.dns = new dns(this); this.os = new os(this); this.iso = new iso(this); this.backup = new backup(this); this.plans = new plans(this); this.regions = new regions(this); this.server = new server(this); this.snapshot = new snapshot(this); this.sshkey = new sshkey(this); this.startupscript = new startupscript(this); }
[ "function", "Vultr", "(", "apiKey", ")", "{", "this", ".", "version", "=", "'v1'", ";", "this", ".", "endpoint", "=", "'https://api.vultr.com/'", "+", "this", ".", "version", "+", "'/'", ";", "this", ".", "apiKey", "=", "(", "apiKey", "?", "apiKey", ":", "config", ".", "vultr", ".", "apiKey", ")", ";", "this", ".", "account", "=", "new", "account", "(", "this", ")", ";", "this", ".", "dns", "=", "new", "dns", "(", "this", ")", ";", "this", ".", "os", "=", "new", "os", "(", "this", ")", ";", "this", ".", "iso", "=", "new", "iso", "(", "this", ")", ";", "this", ".", "backup", "=", "new", "backup", "(", "this", ")", ";", "this", ".", "plans", "=", "new", "plans", "(", "this", ")", ";", "this", ".", "regions", "=", "new", "regions", "(", "this", ")", ";", "this", ".", "server", "=", "new", "server", "(", "this", ")", ";", "this", ".", "snapshot", "=", "new", "snapshot", "(", "this", ")", ";", "this", ".", "sshkey", "=", "new", "sshkey", "(", "this", ")", ";", "this", ".", "startupscript", "=", "new", "startupscript", "(", "this", ")", ";", "}" ]
Vultr instance constructor @prototype @class Vultr
[ "Vultr", "instance", "constructor" ]
2f13708d3ce0716b4c4adc4772173cf1cf7e7150
https://github.com/DeviaVir/node-vultr/blob/2f13708d3ce0716b4c4adc4772173cf1cf7e7150/vultr.js#L25-L41
train
therebelbeta/json-mock
bin/index.js
start
function start(object, filename) { var port = process.env.PORT || argv.port var hostname = argv.host === '0.0.0.0' ? 'localhost' : argv.host for (var prop in object) { console.log(chalk.gray(' http://' + hostname + ':' + port + '/') + chalk.cyan(prop)) } console.log( '\nYou can now go to ' + chalk.gray('http://' + hostname + ':' + port + '/\n') ) console.log( 'Enter ' + chalk.cyan('`s`') + ' at any time to create a snapshot of the db\n' ) process.stdin.resume() process.stdin.setEncoding('utf8') process.stdin.on('data', function (chunk) { if (chunk.trim().toLowerCase() === 's') { var file = 'db-' + Date.now() + '.json' _db.save(object, file) console.log('\nSaved snapshot to ' + chalk.cyan(file) + '\n') } }) if (filename) { var router = jsonServer.router(filename) } else { var router = jsonServer.router(object) } var server = jsonServer.create() server.use(jsonServer.defaults) server.use(router) server.listen(port, argv.host) }
javascript
function start(object, filename) { var port = process.env.PORT || argv.port var hostname = argv.host === '0.0.0.0' ? 'localhost' : argv.host for (var prop in object) { console.log(chalk.gray(' http://' + hostname + ':' + port + '/') + chalk.cyan(prop)) } console.log( '\nYou can now go to ' + chalk.gray('http://' + hostname + ':' + port + '/\n') ) console.log( 'Enter ' + chalk.cyan('`s`') + ' at any time to create a snapshot of the db\n' ) process.stdin.resume() process.stdin.setEncoding('utf8') process.stdin.on('data', function (chunk) { if (chunk.trim().toLowerCase() === 's') { var file = 'db-' + Date.now() + '.json' _db.save(object, file) console.log('\nSaved snapshot to ' + chalk.cyan(file) + '\n') } }) if (filename) { var router = jsonServer.router(filename) } else { var router = jsonServer.router(object) } var server = jsonServer.create() server.use(jsonServer.defaults) server.use(router) server.listen(port, argv.host) }
[ "function", "start", "(", "object", ",", "filename", ")", "{", "var", "port", "=", "process", ".", "env", ".", "PORT", "||", "argv", ".", "port", "var", "hostname", "=", "argv", ".", "host", "===", "'0.0.0.0'", "?", "'localhost'", ":", "argv", ".", "host", "for", "(", "var", "prop", "in", "object", ")", "{", "console", ".", "log", "(", "chalk", ".", "gray", "(", "' http://'", "+", "hostname", "+", "':'", "+", "port", "+", "'/'", ")", "+", "chalk", ".", "cyan", "(", "prop", ")", ")", "}", "console", ".", "log", "(", "'\\nYou can now go to '", "+", "\\n", ")", "chalk", ".", "gray", "(", "'http://'", "+", "hostname", "+", "':'", "+", "port", "+", "'/\\n'", ")", "\\n", "console", ".", "log", "(", "'Enter '", "+", "chalk", ".", "cyan", "(", "'`s`'", ")", "+", "' at any time to create a snapshot of the db\\n'", ")", "\\n", "process", ".", "stdin", ".", "resume", "(", ")", "process", ".", "stdin", ".", "setEncoding", "(", "'utf8'", ")", "process", ".", "stdin", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "if", "(", "chunk", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", "===", "'s'", ")", "{", "var", "file", "=", "'db-'", "+", "Date", ".", "now", "(", ")", "+", "'.json'", "_db", ".", "save", "(", "object", ",", "file", ")", "console", ".", "log", "(", "'\\nSaved snapshot to '", "+", "\\n", "+", "chalk", ".", "cyan", "(", "file", ")", ")", "}", "}", ")", "'\\n'", "\\n", "}" ]
Start server function
[ "Start", "server", "function" ]
a138d20d943733ce85556d8b6cd45c23d4d5676d
https://github.com/therebelbeta/json-mock/blob/a138d20d943733ce85556d8b6cd45c23d4d5676d/bin/index.js#L36-L72
train
dynmeth/mongo-statsd-backend
lib/index.js
function(metric_type, metric) { var ary = metric.split('.'); if (options.prefix) ary.shift(); ary.unshift(metric_type); return ary.join('.')+'_'+options.rate; }
javascript
function(metric_type, metric) { var ary = metric.split('.'); if (options.prefix) ary.shift(); ary.unshift(metric_type); return ary.join('.')+'_'+options.rate; }
[ "function", "(", "metric_type", ",", "metric", ")", "{", "var", "ary", "=", "metric", ".", "split", "(", "'.'", ")", ";", "if", "(", "options", ".", "prefix", ")", "ary", ".", "shift", "(", ")", ";", "ary", ".", "unshift", "(", "metric_type", ")", ";", "return", "ary", ".", "join", "(", "'.'", ")", "+", "'_'", "+", "options", ".", "rate", ";", "}" ]
Prefix a collection name
[ "Prefix", "a", "collection", "name" ]
d51b32bcd5df4d4053a50c9bbca6d16cb859097b
https://github.com/dynmeth/mongo-statsd-backend/blob/d51b32bcd5df4d4053a50c9bbca6d16cb859097b/lib/index.js#L52-L57
train
dynmeth/mongo-statsd-backend
lib/index.js
function(time, key, val) { return { db: dbPrefix(key), col: colPrefix('gauges', key), data: { time: time, gauge: val }, }; }
javascript
function(time, key, val) { return { db: dbPrefix(key), col: colPrefix('gauges', key), data: { time: time, gauge: val }, }; }
[ "function", "(", "time", ",", "key", ",", "val", ")", "{", "return", "{", "db", ":", "dbPrefix", "(", "key", ")", ",", "col", ":", "colPrefix", "(", "'gauges'", ",", "key", ")", ",", "data", ":", "{", "time", ":", "time", ",", "gauge", ":", "val", "}", ",", "}", ";", "}" ]
Aggregate some metrics bro @param {Number} time @param {Stirng} key @param {String} val
[ "Aggregate", "some", "metrics", "bro" ]
d51b32bcd5df4d4053a50c9bbca6d16cb859097b
https://github.com/dynmeth/mongo-statsd-backend/blob/d51b32bcd5df4d4053a50c9bbca6d16cb859097b/lib/index.js#L69-L78
train
dynmeth/mongo-statsd-backend
lib/index.js
function(dbName, collection, metric, callback) { var colInfo = {capped:true, size:options.size*options.max, max:options.max}; database(dbName, function(err, db) { if (err) { db.close(); return callback(err); }; db.createCollection(collection, colInfo, function(err, collClient) { collClient.insert(metric, function(err, data){ if (err) callback(err); if (!err) callback(false, collection); }); }); }); }
javascript
function(dbName, collection, metric, callback) { var colInfo = {capped:true, size:options.size*options.max, max:options.max}; database(dbName, function(err, db) { if (err) { db.close(); return callback(err); }; db.createCollection(collection, colInfo, function(err, collClient) { collClient.insert(metric, function(err, data){ if (err) callback(err); if (!err) callback(false, collection); }); }); }); }
[ "function", "(", "dbName", ",", "collection", ",", "metric", ",", "callback", ")", "{", "var", "colInfo", "=", "{", "capped", ":", "true", ",", "size", ":", "options", ".", "size", "*", "options", ".", "max", ",", "max", ":", "options", ".", "max", "}", ";", "database", "(", "dbName", ",", "function", "(", "err", ",", "db", ")", "{", "if", "(", "err", ")", "{", "db", ".", "close", "(", ")", ";", "return", "callback", "(", "err", ")", ";", "}", ";", "db", ".", "createCollection", "(", "collection", ",", "colInfo", ",", "function", "(", "err", ",", "collClient", ")", "{", "collClient", ".", "insert", "(", "metric", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "callback", "(", "err", ")", ";", "if", "(", "!", "err", ")", "callback", "(", "false", ",", "collection", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Insert the data to the database @method insert @param {String} database @param {String} collection @param {Object} metric @param {Function} callback
[ "Insert", "the", "data", "to", "the", "database" ]
d51b32bcd5df4d4053a50c9bbca6d16cb859097b
https://github.com/dynmeth/mongo-statsd-backend/blob/d51b32bcd5df4d4053a50c9bbca6d16cb859097b/lib/index.js#L151-L167
train
dynmeth/mongo-statsd-backend
lib/index.js
function(time, metrics) { var metricTypes = ['gauges', 'timer_data', 'timers', 'counters', 'sets']; metricTypes.forEach(function(type, i){ var obj; for (var key in metrics[type]) { obj = aggregate[type](time, key, metrics[type][key]); insert(obj.db, obj.col, obj.data, function(err){ if (err) console.log(err); }); }; }); }
javascript
function(time, metrics) { var metricTypes = ['gauges', 'timer_data', 'timers', 'counters', 'sets']; metricTypes.forEach(function(type, i){ var obj; for (var key in metrics[type]) { obj = aggregate[type](time, key, metrics[type][key]); insert(obj.db, obj.col, obj.data, function(err){ if (err) console.log(err); }); }; }); }
[ "function", "(", "time", ",", "metrics", ")", "{", "var", "metricTypes", "=", "[", "'gauges'", ",", "'timer_data'", ",", "'timers'", ",", "'counters'", ",", "'sets'", "]", ";", "metricTypes", ".", "forEach", "(", "function", "(", "type", ",", "i", ")", "{", "var", "obj", ";", "for", "(", "var", "key", "in", "metrics", "[", "type", "]", ")", "{", "obj", "=", "aggregate", "[", "type", "]", "(", "time", ",", "key", ",", "metrics", "[", "type", "]", "[", "key", "]", ")", ";", "insert", "(", "obj", ".", "db", ",", "obj", ".", "col", ",", "obj", ".", "data", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "console", ".", "log", "(", "err", ")", ";", "}", ")", ";", "}", ";", "}", ")", ";", "}" ]
our `flush` event handler
[ "our", "flush", "event", "handler" ]
d51b32bcd5df4d4053a50c9bbca6d16cb859097b
https://github.com/dynmeth/mongo-statsd-backend/blob/d51b32bcd5df4d4053a50c9bbca6d16cb859097b/lib/index.js#L172-L186
train
ohjames/angular-promise-extras
angular-promise-extras.js
function(obj, callback) { if (angular.isArray(obj)) return obj.map(callback) var ret = {} Object.keys(obj).forEach(function(key, val) { ret[key] = callback(obj[key], key) }) return ret }
javascript
function(obj, callback) { if (angular.isArray(obj)) return obj.map(callback) var ret = {} Object.keys(obj).forEach(function(key, val) { ret[key] = callback(obj[key], key) }) return ret }
[ "function", "(", "obj", ",", "callback", ")", "{", "if", "(", "angular", ".", "isArray", "(", "obj", ")", ")", "return", "obj", ".", "map", "(", "callback", ")", "var", "ret", "=", "{", "}", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "key", ",", "val", ")", "{", "ret", "[", "key", "]", "=", "callback", "(", "obj", "[", "key", "]", ",", "key", ")", "}", ")", "return", "ret", "}" ]
Called with an array this acts like map, otherwise it acts like _.mapValues in lodash. @return {Array|Object} The same type as the input argument.
[ "Called", "with", "an", "array", "this", "acts", "like", "map", "otherwise", "it", "acts", "like", "_", ".", "mapValues", "in", "lodash", "." ]
df4cf5ca35cc6080bfd7e71ed3d4f3d0c0c51540
https://github.com/ohjames/angular-promise-extras/blob/df4cf5ca35cc6080bfd7e71ed3d4f3d0c0c51540/angular-promise-extras.js#L9-L18
train
bfanger/angular-keyboard
src/directives/KbContainerController.js
function (model) { if (!this.ngModel) { return; // A kb-item can't be selected without a ng-model on the container element. } if (this.multiple) { if (this.isSelected(model) === false) { this.selected.push(model); this.ngModel.$setViewValue(this.selected); } } else { this.selected[0] = model; this.ngModel.$setViewValue(model); } }
javascript
function (model) { if (!this.ngModel) { return; // A kb-item can't be selected without a ng-model on the container element. } if (this.multiple) { if (this.isSelected(model) === false) { this.selected.push(model); this.ngModel.$setViewValue(this.selected); } } else { this.selected[0] = model; this.ngModel.$setViewValue(model); } }
[ "function", "(", "model", ")", "{", "if", "(", "!", "this", ".", "ngModel", ")", "{", "return", ";", "}", "if", "(", "this", ".", "multiple", ")", "{", "if", "(", "this", ".", "isSelected", "(", "model", ")", "===", "false", ")", "{", "this", ".", "selected", ".", "push", "(", "model", ")", ";", "this", ".", "ngModel", ".", "$setViewValue", "(", "this", ".", "selected", ")", ";", "}", "}", "else", "{", "this", ".", "selected", "[", "0", "]", "=", "model", ";", "this", ".", "ngModel", ".", "$setViewValue", "(", "model", ")", ";", "}", "}" ]
Select the given model. Or in multiselect mode, add the given model to the selection. @param {*} model
[ "Select", "the", "given", "model", ".", "Or", "in", "multiselect", "mode", "add", "the", "given", "model", "to", "the", "selection", "." ]
543741a68ceb06f023bc4474297ba0c835ea6f0a
https://github.com/bfanger/angular-keyboard/blob/543741a68ceb06f023bc4474297ba0c835ea6f0a/src/directives/KbContainerController.js#L59-L72
train
bfanger/angular-keyboard
src/directives/KbContainerController.js
function (model) { if (!this.ngModel) { return; } var index = this.selected.indexOf(model); if (index !== -1) { this.selected.splice(index, 1); if (this.multiple) { this.ngModel.$setViewValue(this.selected); } else { this.ngModel.$setViewValue(undefined); } } }
javascript
function (model) { if (!this.ngModel) { return; } var index = this.selected.indexOf(model); if (index !== -1) { this.selected.splice(index, 1); if (this.multiple) { this.ngModel.$setViewValue(this.selected); } else { this.ngModel.$setViewValue(undefined); } } }
[ "function", "(", "model", ")", "{", "if", "(", "!", "this", ".", "ngModel", ")", "{", "return", ";", "}", "var", "index", "=", "this", ".", "selected", ".", "indexOf", "(", "model", ")", ";", "if", "(", "index", "!==", "-", "1", ")", "{", "this", ".", "selected", ".", "splice", "(", "index", ",", "1", ")", ";", "if", "(", "this", ".", "multiple", ")", "{", "this", ".", "ngModel", ".", "$setViewValue", "(", "this", ".", "selected", ")", ";", "}", "else", "{", "this", ".", "ngModel", ".", "$setViewValue", "(", "undefined", ")", ";", "}", "}", "}" ]
Deselect the given model. Does nothing if the given model isn't selected. @param {*} model
[ "Deselect", "the", "given", "model", ".", "Does", "nothing", "if", "the", "given", "model", "isn", "t", "selected", "." ]
543741a68ceb06f023bc4474297ba0c835ea6f0a
https://github.com/bfanger/angular-keyboard/blob/543741a68ceb06f023bc4474297ba0c835ea6f0a/src/directives/KbContainerController.js#L79-L93
train
bfanger/angular-keyboard
src/directives/KbContainerController.js
function (kbItem) { var element = kbItem.element[0]; var items = this._element.querySelectorAll('[kb-item]'); for (var i = 0; i < items.length; i++) { var el = items.item(i); if (el === element) { var siblings = {}; if (i !== 0) { siblings.previous = angular.element(items.item(i - 1)).controller('kbItem'); } if (i < items.length - 1) { siblings.next = angular.element(items.item(i + 1)).controller('kbItem'); } return siblings; } } return {}; }
javascript
function (kbItem) { var element = kbItem.element[0]; var items = this._element.querySelectorAll('[kb-item]'); for (var i = 0; i < items.length; i++) { var el = items.item(i); if (el === element) { var siblings = {}; if (i !== 0) { siblings.previous = angular.element(items.item(i - 1)).controller('kbItem'); } if (i < items.length - 1) { siblings.next = angular.element(items.item(i + 1)).controller('kbItem'); } return siblings; } } return {}; }
[ "function", "(", "kbItem", ")", "{", "var", "element", "=", "kbItem", ".", "element", "[", "0", "]", ";", "var", "items", "=", "this", ".", "_element", ".", "querySelectorAll", "(", "'[kb-item]'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", "{", "var", "el", "=", "items", ".", "item", "(", "i", ")", ";", "if", "(", "el", "===", "element", ")", "{", "var", "siblings", "=", "{", "}", ";", "if", "(", "i", "!==", "0", ")", "{", "siblings", ".", "previous", "=", "angular", ".", "element", "(", "items", ".", "item", "(", "i", "-", "1", ")", ")", ".", "controller", "(", "'kbItem'", ")", ";", "}", "if", "(", "i", "<", "items", ".", "length", "-", "1", ")", "{", "siblings", ".", "next", "=", "angular", ".", "element", "(", "items", ".", "item", "(", "i", "+", "1", ")", ")", ".", "controller", "(", "'kbItem'", ")", ";", "}", "return", "siblings", ";", "}", "}", "return", "{", "}", ";", "}" ]
Returns the element, controller and models from the current, prevous and next item. @param {KbItemController} kbItem @returns {Object} with up to 2 KbItemControllers: previous and next.
[ "Returns", "the", "element", "controller", "and", "models", "from", "the", "current", "prevous", "and", "next", "item", "." ]
543741a68ceb06f023bc4474297ba0c835ea6f0a
https://github.com/bfanger/angular-keyboard/blob/543741a68ceb06f023bc4474297ba0c835ea6f0a/src/directives/KbContainerController.js#L185-L202
train
bfanger/angular-keyboard
src/directives/KbContainerController.js
function () { var nodes = this._element.querySelectorAll('[kb-item]'); if (nodes.length) { return angular.element(nodes[nodes.length - 1]).controller('kbItem'); } }
javascript
function () { var nodes = this._element.querySelectorAll('[kb-item]'); if (nodes.length) { return angular.element(nodes[nodes.length - 1]).controller('kbItem'); } }
[ "function", "(", ")", "{", "var", "nodes", "=", "this", ".", "_element", ".", "querySelectorAll", "(", "'[kb-item]'", ")", ";", "if", "(", "nodes", ".", "length", ")", "{", "return", "angular", ".", "element", "(", "nodes", "[", "nodes", ".", "length", "-", "1", "]", ")", ".", "controller", "(", "'kbItem'", ")", ";", "}", "}" ]
Returns the first item. @returns {kbItemController}
[ "Returns", "the", "first", "item", "." ]
543741a68ceb06f023bc4474297ba0c835ea6f0a
https://github.com/bfanger/angular-keyboard/blob/543741a68ceb06f023bc4474297ba0c835ea6f0a/src/directives/KbContainerController.js#L217-L222
train
bfanger/angular-keyboard
src/directives/kbItem.js
distance
function distance(direction, currentRect, targetRect) { if (direction === 'left' && targetRect.left < currentRect.left) { return currentRect.left - targetRect.left; } if (direction === 'up' && targetRect.top < currentRect.top) { return currentRect.top - targetRect.top; } if (direction === 'right' && targetRect.left > currentRect.left) { return targetRect.left - currentRect.left; } if (direction === 'down' && targetRect.top > currentRect.top) { return targetRect.top - currentRect.top; } return 0; }
javascript
function distance(direction, currentRect, targetRect) { if (direction === 'left' && targetRect.left < currentRect.left) { return currentRect.left - targetRect.left; } if (direction === 'up' && targetRect.top < currentRect.top) { return currentRect.top - targetRect.top; } if (direction === 'right' && targetRect.left > currentRect.left) { return targetRect.left - currentRect.left; } if (direction === 'down' && targetRect.top > currentRect.top) { return targetRect.top - currentRect.top; } return 0; }
[ "function", "distance", "(", "direction", ",", "currentRect", ",", "targetRect", ")", "{", "if", "(", "direction", "===", "'left'", "&&", "targetRect", ".", "left", "<", "currentRect", ".", "left", ")", "{", "return", "currentRect", ".", "left", "-", "targetRect", ".", "left", ";", "}", "if", "(", "direction", "===", "'up'", "&&", "targetRect", ".", "top", "<", "currentRect", ".", "top", ")", "{", "return", "currentRect", ".", "top", "-", "targetRect", ".", "top", ";", "}", "if", "(", "direction", "===", "'right'", "&&", "targetRect", ".", "left", ">", "currentRect", ".", "left", ")", "{", "return", "targetRect", ".", "left", "-", "currentRect", ".", "left", ";", "}", "if", "(", "direction", "===", "'down'", "&&", "targetRect", ".", "top", ">", "currentRect", ".", "top", ")", "{", "return", "targetRect", ".", "top", "-", "currentRect", ".", "top", ";", "}", "return", "0", ";", "}" ]
Calculates the distance to the ClientRect in a given direction. Allows for keyboard navigation based on the relative visual location of the element. @param {string} direction 'up', 'left', 'right' or 'down', @param {ClientRect} currentRect The position of the current item. @return {Number}
[ "Calculates", "the", "distance", "to", "the", "ClientRect", "in", "a", "given", "direction", ".", "Allows", "for", "keyboard", "navigation", "based", "on", "the", "relative", "visual", "location", "of", "the", "element", "." ]
543741a68ceb06f023bc4474297ba0c835ea6f0a
https://github.com/bfanger/angular-keyboard/blob/543741a68ceb06f023bc4474297ba0c835ea6f0a/src/directives/kbItem.js#L70-L84
train
ticketmaster/tm-nucleus
gulpfile.js
copyNormalize
function copyNormalize() { var stream = gulp.src(src.normalize) .pipe(plugins.rename(function(path) { path.basename = '_' + path.basename, path.extname = '.scss' })) .pipe(gulp.dest(paths.sourcefiles + '/sass/vendors/normalize')); }
javascript
function copyNormalize() { var stream = gulp.src(src.normalize) .pipe(plugins.rename(function(path) { path.basename = '_' + path.basename, path.extname = '.scss' })) .pipe(gulp.dest(paths.sourcefiles + '/sass/vendors/normalize')); }
[ "function", "copyNormalize", "(", ")", "{", "var", "stream", "=", "gulp", ".", "src", "(", "src", ".", "normalize", ")", ".", "pipe", "(", "plugins", ".", "rename", "(", "function", "(", "path", ")", "{", "path", ".", "basename", "=", "'_'", "+", "path", ".", "basename", ",", "path", ".", "extname", "=", "'.scss'", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "paths", ".", "sourcefiles", "+", "'/sass/vendors/normalize'", ")", ")", ";", "}" ]
copy normalize.css from node_modules into project and rename to .scss so that it can be imported into our sass compile process
[ "copy", "normalize", ".", "css", "from", "node_modules", "into", "project", "and", "rename", "to", ".", "scss", "so", "that", "it", "can", "be", "imported", "into", "our", "sass", "compile", "process" ]
9305ee91ec6c157b8778acf4736ed20f5f561d5b
https://github.com/ticketmaster/tm-nucleus/blob/9305ee91ec6c157b8778acf4736ed20f5f561d5b/gulpfile.js#L54-L61
train
ticketmaster/tm-nucleus
gulpfile.js
copySvg4Everybody
function copySvg4Everybody(dir) { gulp.src(src.svg4everybody) .pipe(gulp.dest(dir)); }
javascript
function copySvg4Everybody(dir) { gulp.src(src.svg4everybody) .pipe(gulp.dest(dir)); }
[ "function", "copySvg4Everybody", "(", "dir", ")", "{", "gulp", ".", "src", "(", "src", ".", "svg4everybody", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "dir", ")", ")", ";", "}" ]
copy svg4everybody into directory
[ "copy", "svg4everybody", "into", "directory" ]
9305ee91ec6c157b8778acf4736ed20f5f561d5b
https://github.com/ticketmaster/tm-nucleus/blob/9305ee91ec6c157b8778acf4736ed20f5f561d5b/gulpfile.js#L64-L67
train
ticketmaster/tm-nucleus
gulpfile.js
copyFont
function copyFont(dir) { gulp.src(src.font) .pipe(gulp.dest(dir)); }
javascript
function copyFont(dir) { gulp.src(src.font) .pipe(gulp.dest(dir)); }
[ "function", "copyFont", "(", "dir", ")", "{", "gulp", ".", "src", "(", "src", ".", "font", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "dir", ")", ")", ";", "}" ]
file copying functions
[ "file", "copying", "functions" ]
9305ee91ec6c157b8778acf4736ed20f5f561d5b
https://github.com/ticketmaster/tm-nucleus/blob/9305ee91ec6c157b8778acf4736ed20f5f561d5b/gulpfile.js#L70-L73
train
ticketmaster/tm-nucleus
gulpfile.js
compileSass
function compileSass() { var stream = gulp.src(src.scss) .pipe(plugins.sourcemaps.init()) .pipe(plugins.sass().on('error', plugins.sass.logError)) .pipe(plugins.autoprefixer({ browsers: ['last 2 versions', 'ie >= 9'] })) .pipe(plugins.sourcemaps.write()) .pipe(gulp.dest(compiled.css)) .pipe(reload({ stream: true })); return stream; }
javascript
function compileSass() { var stream = gulp.src(src.scss) .pipe(plugins.sourcemaps.init()) .pipe(plugins.sass().on('error', plugins.sass.logError)) .pipe(plugins.autoprefixer({ browsers: ['last 2 versions', 'ie >= 9'] })) .pipe(plugins.sourcemaps.write()) .pipe(gulp.dest(compiled.css)) .pipe(reload({ stream: true })); return stream; }
[ "function", "compileSass", "(", ")", "{", "var", "stream", "=", "gulp", ".", "src", "(", "src", ".", "scss", ")", ".", "pipe", "(", "plugins", ".", "sourcemaps", ".", "init", "(", ")", ")", ".", "pipe", "(", "plugins", ".", "sass", "(", ")", ".", "on", "(", "'error'", ",", "plugins", ".", "sass", ".", "logError", ")", ")", ".", "pipe", "(", "plugins", ".", "autoprefixer", "(", "{", "browsers", ":", "[", "'last 2 versions'", ",", "'ie >= 9'", "]", "}", ")", ")", ".", "pipe", "(", "plugins", ".", "sourcemaps", ".", "write", "(", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "compiled", ".", "css", ")", ")", ".", "pipe", "(", "reload", "(", "{", "stream", ":", "true", "}", ")", ")", ";", "return", "stream", ";", "}" ]
compile sass and apply autoprefixer
[ "compile", "sass", "and", "apply", "autoprefixer" ]
9305ee91ec6c157b8778acf4736ed20f5f561d5b
https://github.com/ticketmaster/tm-nucleus/blob/9305ee91ec6c157b8778acf4736ed20f5f561d5b/gulpfile.js#L87-L96
train
ticketmaster/tm-nucleus
gulpfile.js
minifyCss
function minifyCss() { var stream = gulp.src([compiled.css + '/**/*', '!' + compiled.css + '/styleguide*']) .pipe(plugins.minifyCss()) .pipe(plugins.rename({ suffix: '.min' })) .pipe(gulp.dest(dist.css)); return stream; }
javascript
function minifyCss() { var stream = gulp.src([compiled.css + '/**/*', '!' + compiled.css + '/styleguide*']) .pipe(plugins.minifyCss()) .pipe(plugins.rename({ suffix: '.min' })) .pipe(gulp.dest(dist.css)); return stream; }
[ "function", "minifyCss", "(", ")", "{", "var", "stream", "=", "gulp", ".", "src", "(", "[", "compiled", ".", "css", "+", "'/**/*'", ",", "'!'", "+", "compiled", ".", "css", "+", "'/styleguide*'", "]", ")", ".", "pipe", "(", "plugins", ".", "minifyCss", "(", ")", ")", ".", "pipe", "(", "plugins", ".", "rename", "(", "{", "suffix", ":", "'.min'", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "dist", ".", "css", ")", ")", ";", "return", "stream", ";", "}" ]
minify css from public dir and drop into dist dir
[ "minify", "css", "from", "public", "dir", "and", "drop", "into", "dist", "dir" ]
9305ee91ec6c157b8778acf4736ed20f5f561d5b
https://github.com/ticketmaster/tm-nucleus/blob/9305ee91ec6c157b8778acf4736ed20f5f561d5b/gulpfile.js#L99-L105
train
ticketmaster/tm-nucleus
gulpfile.js
minifySvg
function minifySvg() { var stream = gulp.src([src.svg, '!' + src.icons]) .pipe(plugins.svgmin({ plugins: [ { removeViewBox: false }, { removeUselessStrokeAndFill: false }, { removeEmptyAttrs: false }, { removeTitle: false }, { removeDesc: true } ], js2svg: { pretty: true }})) .pipe(gulp.dest(compiled.img)); return stream; }
javascript
function minifySvg() { var stream = gulp.src([src.svg, '!' + src.icons]) .pipe(plugins.svgmin({ plugins: [ { removeViewBox: false }, { removeUselessStrokeAndFill: false }, { removeEmptyAttrs: false }, { removeTitle: false }, { removeDesc: true } ], js2svg: { pretty: true }})) .pipe(gulp.dest(compiled.img)); return stream; }
[ "function", "minifySvg", "(", ")", "{", "var", "stream", "=", "gulp", ".", "src", "(", "[", "src", ".", "svg", ",", "'!'", "+", "src", ".", "icons", "]", ")", ".", "pipe", "(", "plugins", ".", "svgmin", "(", "{", "plugins", ":", "[", "{", "removeViewBox", ":", "false", "}", ",", "{", "removeUselessStrokeAndFill", ":", "false", "}", ",", "{", "removeEmptyAttrs", ":", "false", "}", ",", "{", "removeTitle", ":", "false", "}", ",", "{", "removeDesc", ":", "true", "}", "]", ",", "js2svg", ":", "{", "pretty", ":", "true", "}", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "compiled", ".", "img", ")", ")", ";", "return", "stream", ";", "}" ]
minify all svg's except icons
[ "minify", "all", "svg", "s", "except", "icons" ]
9305ee91ec6c157b8778acf4736ed20f5f561d5b
https://github.com/ticketmaster/tm-nucleus/blob/9305ee91ec6c157b8778acf4736ed20f5f561d5b/gulpfile.js#L118-L133
train
ticketmaster/tm-nucleus
gulpfile.js
makeSvgSprite
function makeSvgSprite() { var stream = gulp.src([src.icons]) .pipe(plugins.svgmin({ plugins: [ { removeViewBox: false }, { removeUselessStrokeAndFill: false }, { removeEmptyAttrs: false }, { removeTitle: false }, { removeDesc: true } ], js2svg: { pretty: true }})) .pipe(plugins.svgstore()) .pipe(plugins.rename({ basename: 'sprite' })) .pipe(gulp.dest(compiled.img)); return stream; }
javascript
function makeSvgSprite() { var stream = gulp.src([src.icons]) .pipe(plugins.svgmin({ plugins: [ { removeViewBox: false }, { removeUselessStrokeAndFill: false }, { removeEmptyAttrs: false }, { removeTitle: false }, { removeDesc: true } ], js2svg: { pretty: true }})) .pipe(plugins.svgstore()) .pipe(plugins.rename({ basename: 'sprite' })) .pipe(gulp.dest(compiled.img)); return stream; }
[ "function", "makeSvgSprite", "(", ")", "{", "var", "stream", "=", "gulp", ".", "src", "(", "[", "src", ".", "icons", "]", ")", ".", "pipe", "(", "plugins", ".", "svgmin", "(", "{", "plugins", ":", "[", "{", "removeViewBox", ":", "false", "}", ",", "{", "removeUselessStrokeAndFill", ":", "false", "}", ",", "{", "removeEmptyAttrs", ":", "false", "}", ",", "{", "removeTitle", ":", "false", "}", ",", "{", "removeDesc", ":", "true", "}", "]", ",", "js2svg", ":", "{", "pretty", ":", "true", "}", "}", ")", ")", ".", "pipe", "(", "plugins", ".", "svgstore", "(", ")", ")", ".", "pipe", "(", "plugins", ".", "rename", "(", "{", "basename", ":", "'sprite'", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "compiled", ".", "img", ")", ")", ";", "return", "stream", ";", "}" ]
combine icon svg's into sprite
[ "combine", "icon", "svg", "s", "into", "sprite" ]
9305ee91ec6c157b8778acf4736ed20f5f561d5b
https://github.com/ticketmaster/tm-nucleus/blob/9305ee91ec6c157b8778acf4736ed20f5f561d5b/gulpfile.js#L136-L155
train
Collaborne/aws-sns-subscription-confirmation
index.js
snsConfirmHandler
function snsConfirmHandler() { return (req, res, next) => { // Handle call for SNS confirmation // @see http://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.html if (req.headers['x-amz-sns-message-type'] === 'SubscriptionConfirmation') { const subscribeUrl = req.body.SubscribeURL; debug(`Received SubscriptionConfirmation request: ${subscribeUrl}`); return request({ uri: subscribeUrl }, (err, response, body) => { if (err) { return res.status(400).send({error: err.message}); } // Parse the response and extract the subscription ARN const parser = new xml2js.Parser(); return parser.parseString(body, function callback(err, doc) { if (err) { return res.status(400).send({error: err.message}); } let subscriptionArn; try { subscriptionArn = doc.ConfirmSubscriptionResponse.ConfirmSubscriptionResult[0].SubscriptionArn[0]; if (!subscriptionArn) { return res.status(400).send({ error: 'Cannot find SubscriptionArn' }); } debug(`Subscription: ${subscriptionArn}`); } catch (e) { // Ignore errors related to accessing the value return res.status(400).send({ error: 'Cannot find SubscriptionArn' }); } // Retain the subscription ARN on the request for testing res.subscriptionArn = subscriptionArn; return res.send('Subscribed'); }); }); } else { return next(); } }; }
javascript
function snsConfirmHandler() { return (req, res, next) => { // Handle call for SNS confirmation // @see http://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.html if (req.headers['x-amz-sns-message-type'] === 'SubscriptionConfirmation') { const subscribeUrl = req.body.SubscribeURL; debug(`Received SubscriptionConfirmation request: ${subscribeUrl}`); return request({ uri: subscribeUrl }, (err, response, body) => { if (err) { return res.status(400).send({error: err.message}); } // Parse the response and extract the subscription ARN const parser = new xml2js.Parser(); return parser.parseString(body, function callback(err, doc) { if (err) { return res.status(400).send({error: err.message}); } let subscriptionArn; try { subscriptionArn = doc.ConfirmSubscriptionResponse.ConfirmSubscriptionResult[0].SubscriptionArn[0]; if (!subscriptionArn) { return res.status(400).send({ error: 'Cannot find SubscriptionArn' }); } debug(`Subscription: ${subscriptionArn}`); } catch (e) { // Ignore errors related to accessing the value return res.status(400).send({ error: 'Cannot find SubscriptionArn' }); } // Retain the subscription ARN on the request for testing res.subscriptionArn = subscriptionArn; return res.send('Subscribed'); }); }); } else { return next(); } }; }
[ "function", "snsConfirmHandler", "(", ")", "{", "return", "(", "req", ",", "res", ",", "next", ")", "=>", "{", "if", "(", "req", ".", "headers", "[", "'x-amz-sns-message-type'", "]", "===", "'SubscriptionConfirmation'", ")", "{", "const", "subscribeUrl", "=", "req", ".", "body", ".", "SubscribeURL", ";", "debug", "(", "`", "${", "subscribeUrl", "}", "`", ")", ";", "return", "request", "(", "{", "uri", ":", "subscribeUrl", "}", ",", "(", "err", ",", "response", ",", "body", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "res", ".", "status", "(", "400", ")", ".", "send", "(", "{", "error", ":", "err", ".", "message", "}", ")", ";", "}", "const", "parser", "=", "new", "xml2js", ".", "Parser", "(", ")", ";", "return", "parser", ".", "parseString", "(", "body", ",", "function", "callback", "(", "err", ",", "doc", ")", "{", "if", "(", "err", ")", "{", "return", "res", ".", "status", "(", "400", ")", ".", "send", "(", "{", "error", ":", "err", ".", "message", "}", ")", ";", "}", "let", "subscriptionArn", ";", "try", "{", "subscriptionArn", "=", "doc", ".", "ConfirmSubscriptionResponse", ".", "ConfirmSubscriptionResult", "[", "0", "]", ".", "SubscriptionArn", "[", "0", "]", ";", "if", "(", "!", "subscriptionArn", ")", "{", "return", "res", ".", "status", "(", "400", ")", ".", "send", "(", "{", "error", ":", "'Cannot find SubscriptionArn'", "}", ")", ";", "}", "debug", "(", "`", "${", "subscriptionArn", "}", "`", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "res", ".", "status", "(", "400", ")", ".", "send", "(", "{", "error", ":", "'Cannot find SubscriptionArn'", "}", ")", ";", "}", "res", ".", "subscriptionArn", "=", "subscriptionArn", ";", "return", "res", ".", "send", "(", "'Subscribed'", ")", ";", "}", ")", ";", "}", ")", ";", "}", "else", "{", "return", "next", "(", ")", ";", "}", "}", ";", "}" ]
Middleware to handle SNS subscription confirmations @returns
[ "Middleware", "to", "handle", "SNS", "subscription", "confirmations" ]
4fdc20b096bc073a1c09028c2c304526b6f2417a
https://github.com/Collaborne/aws-sns-subscription-confirmation/blob/4fdc20b096bc073a1c09028c2c304526b6f2417a/index.js#L28-L69
train
jmjuanes/electron-auth
index.js
function(url) { //Parse the redirected url return provider.authorization_done(opt, url, window, function() { //Destroy the window window.destroy(); //Get the arguments var args = [].slice.call(arguments); //Do the callback with the provided arguments return cb.apply(null, args); }); }
javascript
function(url) { //Parse the redirected url return provider.authorization_done(opt, url, window, function() { //Destroy the window window.destroy(); //Get the arguments var args = [].slice.call(arguments); //Do the callback with the provided arguments return cb.apply(null, args); }); }
[ "function", "(", "url", ")", "{", "return", "provider", ".", "authorization_done", "(", "opt", ",", "url", ",", "window", ",", "function", "(", ")", "{", "window", ".", "destroy", "(", ")", ";", "var", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ";", "return", "cb", ".", "apply", "(", "null", ",", "args", ")", ";", "}", ")", ";", "}" ]
Handle the callback
[ "Handle", "the", "callback" ]
8dfae2745b9feada875624cba3eec5324c6b8d18
https://github.com/jmjuanes/electron-auth/blob/8dfae2745b9feada875624cba3eec5324c6b8d18/index.js#L35-L49
train
iarna/wide-align
align.js
createPadding
function createPadding (width) { var result = '' var string = ' ' var n = width do { if (n % 2) { result += string; } n = Math.floor(n / 2); string += string; } while (n); return result; }
javascript
function createPadding (width) { var result = '' var string = ' ' var n = width do { if (n % 2) { result += string; } n = Math.floor(n / 2); string += string; } while (n); return result; }
[ "function", "createPadding", "(", "width", ")", "{", "var", "result", "=", "''", "var", "string", "=", "' '", "var", "n", "=", "width", "do", "{", "if", "(", "n", "%", "2", ")", "{", "result", "+=", "string", ";", "}", "n", "=", "Math", ".", "floor", "(", "n", "/", "2", ")", ";", "string", "+=", "string", ";", "}", "while", "(", "n", ")", ";", "return", "result", ";", "}" ]
lodash's way of generating pad characters.
[ "lodash", "s", "way", "of", "generating", "pad", "characters", "." ]
6b766c9874a1e5157eda2ac75b90ccc01b313620
https://github.com/iarna/wide-align/blob/6b766c9874a1e5157eda2ac75b90ccc01b313620/align.js#L10-L23
train
finger563/webgme-hfsm
src/common/processor.js
function(obj, objDict) { var parent = objDict[ obj.parentPath ]; if (parent) { if (parent.Substates == undefined) parent.Substates = []; parent.Substates.push( obj ); } }
javascript
function(obj, objDict) { var parent = objDict[ obj.parentPath ]; if (parent) { if (parent.Substates == undefined) parent.Substates = []; parent.Substates.push( obj ); } }
[ "function", "(", "obj", ",", "objDict", ")", "{", "var", "parent", "=", "objDict", "[", "obj", ".", "parentPath", "]", ";", "if", "(", "parent", ")", "{", "if", "(", "parent", ".", "Substates", "==", "undefined", ")", "parent", ".", "Substates", "=", "[", "]", ";", "parent", ".", "Substates", ".", "push", "(", "obj", ")", ";", "}", "}" ]
MAKE CONVENIENCE FOR WHAT EVENTS ARE HANDLED BY WHICH STATES
[ "MAKE", "CONVENIENCE", "FOR", "WHAT", "EVENTS", "ARE", "HANDLED", "BY", "WHICH", "STATES" ]
efff2b5b63d95f9fd3cf6300c389571cb5979539
https://github.com/finger563/webgme-hfsm/blob/efff2b5b63d95f9fd3cf6300c389571cb5979539/src/common/processor.js#L244-L251
train
jaredhanson/node-jsonrpc-tcp
lib/jsonrpc-tcp/connection.js
Connection
function Connection(socket) { var self = this; events.EventEmitter.call(this); this._methods = {}; this._socket = socket || new net.Socket(); this._socket.setEncoding('utf8'); this._socket.addListener('connect', function() { var remote = new Remote(self); self.emit('connect', remote); }); this._socket.addListener('data', function(data) { //console.log('RECV: ' + data); self._parser.parse(data); }); this._socket.addListener('end', this.emit.bind(this, 'end')); this._socket.addListener('timeout', this.emit.bind(this, 'timeout')); this._socket.addListener('drain', this.emit.bind(this, 'drain')); this._socket.addListener('error', this.emit.bind(this, 'error')); this._socket.addListener('close', this.emit.bind(this, 'close')); this._parser = new jsonsp.Parser(function(obj) { if (obj.result !== undefined || obj.error !== undefined) { self.emit('response', obj); } else if (obj.id !== null) { self.emit('request', obj); self._handleRequest(obj); } else { self.emit('notification', obj); self._handleRequest(obj); } }); this._parser.addListener('error', function(err) { self._socket.destroy(); self.emit('error', err); }) }
javascript
function Connection(socket) { var self = this; events.EventEmitter.call(this); this._methods = {}; this._socket = socket || new net.Socket(); this._socket.setEncoding('utf8'); this._socket.addListener('connect', function() { var remote = new Remote(self); self.emit('connect', remote); }); this._socket.addListener('data', function(data) { //console.log('RECV: ' + data); self._parser.parse(data); }); this._socket.addListener('end', this.emit.bind(this, 'end')); this._socket.addListener('timeout', this.emit.bind(this, 'timeout')); this._socket.addListener('drain', this.emit.bind(this, 'drain')); this._socket.addListener('error', this.emit.bind(this, 'error')); this._socket.addListener('close', this.emit.bind(this, 'close')); this._parser = new jsonsp.Parser(function(obj) { if (obj.result !== undefined || obj.error !== undefined) { self.emit('response', obj); } else if (obj.id !== null) { self.emit('request', obj); self._handleRequest(obj); } else { self.emit('notification', obj); self._handleRequest(obj); } }); this._parser.addListener('error', function(err) { self._socket.destroy(); self.emit('error', err); }) }
[ "function", "Connection", "(", "socket", ")", "{", "var", "self", "=", "this", ";", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_methods", "=", "{", "}", ";", "this", ".", "_socket", "=", "socket", "||", "new", "net", ".", "Socket", "(", ")", ";", "this", ".", "_socket", ".", "setEncoding", "(", "'utf8'", ")", ";", "this", ".", "_socket", ".", "addListener", "(", "'connect'", ",", "function", "(", ")", "{", "var", "remote", "=", "new", "Remote", "(", "self", ")", ";", "self", ".", "emit", "(", "'connect'", ",", "remote", ")", ";", "}", ")", ";", "this", ".", "_socket", ".", "addListener", "(", "'data'", ",", "function", "(", "data", ")", "{", "self", ".", "_parser", ".", "parse", "(", "data", ")", ";", "}", ")", ";", "this", ".", "_socket", ".", "addListener", "(", "'end'", ",", "this", ".", "emit", ".", "bind", "(", "this", ",", "'end'", ")", ")", ";", "this", ".", "_socket", ".", "addListener", "(", "'timeout'", ",", "this", ".", "emit", ".", "bind", "(", "this", ",", "'timeout'", ")", ")", ";", "this", ".", "_socket", ".", "addListener", "(", "'drain'", ",", "this", ".", "emit", ".", "bind", "(", "this", ",", "'drain'", ")", ")", ";", "this", ".", "_socket", ".", "addListener", "(", "'error'", ",", "this", ".", "emit", ".", "bind", "(", "this", ",", "'error'", ")", ")", ";", "this", ".", "_socket", ".", "addListener", "(", "'close'", ",", "this", ".", "emit", ".", "bind", "(", "this", ",", "'close'", ")", ")", ";", "this", ".", "_parser", "=", "new", "jsonsp", ".", "Parser", "(", "function", "(", "obj", ")", "{", "if", "(", "obj", ".", "result", "!==", "undefined", "||", "obj", ".", "error", "!==", "undefined", ")", "{", "self", ".", "emit", "(", "'response'", ",", "obj", ")", ";", "}", "else", "if", "(", "obj", ".", "id", "!==", "null", ")", "{", "self", ".", "emit", "(", "'request'", ",", "obj", ")", ";", "self", ".", "_handleRequest", "(", "obj", ")", ";", "}", "else", "{", "self", ".", "emit", "(", "'notification'", ",", "obj", ")", ";", "self", ".", "_handleRequest", "(", "obj", ")", ";", "}", "}", ")", ";", "this", ".", "_parser", ".", "addListener", "(", "'error'", ",", "function", "(", "err", ")", "{", "self", ".", "_socket", ".", "destroy", "(", ")", ";", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", "}" ]
Create a new JSON-RPC connection. Creates a new JSON-RPC over TCP connection. The optional `socket` argument is used to create a connection on an existing socket, otherwise a new socket will be allocated. Events: Event: 'connect' `function(remote) { }` Emitted when a connection is established to a server. `remote` is a `Remote`, to be used for invoking remote methods on the server. Event: 'request' `function(req) { }` Emitted when a request (method invocation) is received on the connection. Event: 'response' `function(res) { }` Emitted when a response (to a method invocation) is received on the connection. Event: 'notification' `function(notif) { }` Emitted when a notification is received on the connection. Event: 'error' `function(err) { }` Emitted when an error occurs. Examples: var connection = new Connection(); @return {Connection} @api public
[ "Create", "a", "new", "JSON", "-", "RPC", "connection", "." ]
d9dc271b8f50da9fb08ebb46c390fd4c57a89bfc
https://github.com/jaredhanson/node-jsonrpc-tcp/blob/d9dc271b8f50da9fb08ebb46c390fd4c57a89bfc/lib/jsonrpc-tcp/connection.js#L59-L95
train
tblobaum/rconsole
rconsole.js
send
function send (severity, msg) { var len output(severity, msg, msg.length) // this should probably be 1024 if (msg.length > 1024) process.stderr.write(new Error('maximum log length is 1024 bytes') +'\n') if (rc.syslog) { // add a hashtag based on the severity level msg = formatIf(rc.syslogHashTags, '#%s %s', [severity, msg], msg) // send the log to syslog bindings.log(sev[severity], msg) } }
javascript
function send (severity, msg) { var len output(severity, msg, msg.length) // this should probably be 1024 if (msg.length > 1024) process.stderr.write(new Error('maximum log length is 1024 bytes') +'\n') if (rc.syslog) { // add a hashtag based on the severity level msg = formatIf(rc.syslogHashTags, '#%s %s', [severity, msg], msg) // send the log to syslog bindings.log(sev[severity], msg) } }
[ "function", "send", "(", "severity", ",", "msg", ")", "{", "var", "len", "output", "(", "severity", ",", "msg", ",", "msg", ".", "length", ")", "if", "(", "msg", ".", "length", ">", "1024", ")", "process", ".", "stderr", ".", "write", "(", "new", "Error", "(", "'maximum log length is 1024 bytes'", ")", "+", "'\\n'", ")", "\\n", "}" ]
Send message to syslog and stdio @return {undefined} @api private
[ "Send", "message", "to", "syslog", "and", "stdio" ]
857b9af7b668976a976ac8197c8bd564ecf803bd
https://github.com/tblobaum/rconsole/blob/857b9af7b668976a976ac8197c8bd564ecf803bd/rconsole.js#L228-L243
train