id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
51,000
sendanor/nor-nopg
src/nopg.js
wrap_casts
function wrap_casts(x) { x = '' + x; if(/^\(.+\)$/.test(x)) { return '(' + x + ')'; } if(/::[a-z]+$/.test(x)) { if(/^[a-z]+ \->> /.test(x)) { return '((' + x + '))'; } return '(' + x + ')'; } return x; }
javascript
function wrap_casts(x) { x = '' + x; if(/^\(.+\)$/.test(x)) { return '(' + x + ')'; } if(/::[a-z]+$/.test(x)) { if(/^[a-z]+ \->> /.test(x)) { return '((' + x + '))'; } return '(' + x + ')'; } return x; }
[ "function", "wrap_casts", "(", "x", ")", "{", "x", "=", "''", "+", "x", ";", "if", "(", "/", "^\\(.+\\)$", "/", ".", "test", "(", "x", ")", ")", "{", "return", "'('", "+", "x", "+", "')'", ";", "}", "if", "(", "/", "::[a-z]+$", "/", ".", "test", "(", "x", ")", ")", "{", "if", "(", "/", "^[a-z]+ \\->> ", "/", ".", "test", "(", "x", ")", ")", "{", "return", "'(('", "+", "x", "+", "'))'", ";", "}", "return", "'('", "+", "x", "+", "')'", ";", "}", "return", "x", ";", "}" ]
Wrap parenthesis around casts @param x @return {*}
[ "Wrap", "parenthesis", "around", "casts" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1448-L1460
51,001
sendanor/nor-nopg
src/nopg.js
pg_create_index_query_internal_v1
function pg_create_index_query_internal_v1(self, ObjType, type, field, typefield, is_unique) { var query; var pgcast = parse_predicate_pgcast(ObjType, type, field); var colname = _parse_predicate_key(ObjType, {'epoch':false}, field); var name = pg_create_index_name(self, ObjType, type, field, typefield); query = "CREATE " + (is_unique?'UNIQUE ':'') + "INDEX "+name+" ON " + (ObjType.meta.table) + " USING btree "; if( (ObjType === NoPg.Document) && (typefield !== undefined)) { if(!typefield) { throw new TypeError("No typefield set for NoPg.Document!"); } query += "(" + typefield+", "+ wrap_casts(pgcast(colname.getString())) + ")"; } else { query += "(" + wrap_casts(pgcast(colname.getString())) + ")"; } return query; }
javascript
function pg_create_index_query_internal_v1(self, ObjType, type, field, typefield, is_unique) { var query; var pgcast = parse_predicate_pgcast(ObjType, type, field); var colname = _parse_predicate_key(ObjType, {'epoch':false}, field); var name = pg_create_index_name(self, ObjType, type, field, typefield); query = "CREATE " + (is_unique?'UNIQUE ':'') + "INDEX "+name+" ON " + (ObjType.meta.table) + " USING btree "; if( (ObjType === NoPg.Document) && (typefield !== undefined)) { if(!typefield) { throw new TypeError("No typefield set for NoPg.Document!"); } query += "(" + typefield+", "+ wrap_casts(pgcast(colname.getString())) + ")"; } else { query += "(" + wrap_casts(pgcast(colname.getString())) + ")"; } return query; }
[ "function", "pg_create_index_query_internal_v1", "(", "self", ",", "ObjType", ",", "type", ",", "field", ",", "typefield", ",", "is_unique", ")", "{", "var", "query", ";", "var", "pgcast", "=", "parse_predicate_pgcast", "(", "ObjType", ",", "type", ",", "field", ")", ";", "var", "colname", "=", "_parse_predicate_key", "(", "ObjType", ",", "{", "'epoch'", ":", "false", "}", ",", "field", ")", ";", "var", "name", "=", "pg_create_index_name", "(", "self", ",", "ObjType", ",", "type", ",", "field", ",", "typefield", ")", ";", "query", "=", "\"CREATE \"", "+", "(", "is_unique", "?", "'UNIQUE '", ":", "''", ")", "+", "\"INDEX \"", "+", "name", "+", "\" ON \"", "+", "(", "ObjType", ".", "meta", ".", "table", ")", "+", "\" USING btree \"", ";", "if", "(", "(", "ObjType", "===", "NoPg", ".", "Document", ")", "&&", "(", "typefield", "!==", "undefined", ")", ")", "{", "if", "(", "!", "typefield", ")", "{", "throw", "new", "TypeError", "(", "\"No typefield set for NoPg.Document!\"", ")", ";", "}", "query", "+=", "\"(\"", "+", "typefield", "+", "\", \"", "+", "wrap_casts", "(", "pgcast", "(", "colname", ".", "getString", "(", ")", ")", ")", "+", "\")\"", ";", "}", "else", "{", "query", "+=", "\"(\"", "+", "wrap_casts", "(", "pgcast", "(", "colname", ".", "getString", "(", ")", ")", ")", "+", "\")\"", ";", "}", "return", "query", ";", "}" ]
Returns index query @param self @param ObjType @param type @param field @param typefield @param is_unique @return {string | *}
[ "Returns", "index", "query" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1471-L1486
51,002
sendanor/nor-nopg
src/nopg.js
pg_declare_index
function pg_declare_index(self, ObjType, type, field, typefield, is_unique) { var colname = _parse_predicate_key(ObjType, {'epoch':false}, field); var datakey = colname.getMeta('datakey'); var field_name = (datakey ? datakey + '.' : '' ) + colname.getMeta('key'); var name = pg_create_index_name(self, ObjType, type, field, typefield, is_unique); return pg_relation_exists(self, name).then(function(exists) { if(!exists) { return pg_create_index(self, ObjType, type, field, typefield, is_unique); } return pg_get_indexdef(self, name).then(function(old_indexdef) { var new_indexdef_v1 = pg_create_index_query_v1(self, ObjType, type, field, typefield, is_unique); var new_indexdef_v2 = pg_create_index_query_v2(self, ObjType, type, field, typefield, is_unique); if (new_indexdef_v1 === old_indexdef) return self; if (new_indexdef_v2 === old_indexdef) return self; if (NoPg.debug) { debug.info('Rebuilding index...'); debug.log('old index is: ', old_indexdef); debug.log('new index is: ', new_indexdef_v1); } return pg_drop_index(self, ObjType, type, field, typefield).then(function() { return pg_create_index(self, ObjType, type, field, typefield, is_unique); }); }); }); }
javascript
function pg_declare_index(self, ObjType, type, field, typefield, is_unique) { var colname = _parse_predicate_key(ObjType, {'epoch':false}, field); var datakey = colname.getMeta('datakey'); var field_name = (datakey ? datakey + '.' : '' ) + colname.getMeta('key'); var name = pg_create_index_name(self, ObjType, type, field, typefield, is_unique); return pg_relation_exists(self, name).then(function(exists) { if(!exists) { return pg_create_index(self, ObjType, type, field, typefield, is_unique); } return pg_get_indexdef(self, name).then(function(old_indexdef) { var new_indexdef_v1 = pg_create_index_query_v1(self, ObjType, type, field, typefield, is_unique); var new_indexdef_v2 = pg_create_index_query_v2(self, ObjType, type, field, typefield, is_unique); if (new_indexdef_v1 === old_indexdef) return self; if (new_indexdef_v2 === old_indexdef) return self; if (NoPg.debug) { debug.info('Rebuilding index...'); debug.log('old index is: ', old_indexdef); debug.log('new index is: ', new_indexdef_v1); } return pg_drop_index(self, ObjType, type, field, typefield).then(function() { return pg_create_index(self, ObjType, type, field, typefield, is_unique); }); }); }); }
[ "function", "pg_declare_index", "(", "self", ",", "ObjType", ",", "type", ",", "field", ",", "typefield", ",", "is_unique", ")", "{", "var", "colname", "=", "_parse_predicate_key", "(", "ObjType", ",", "{", "'epoch'", ":", "false", "}", ",", "field", ")", ";", "var", "datakey", "=", "colname", ".", "getMeta", "(", "'datakey'", ")", ";", "var", "field_name", "=", "(", "datakey", "?", "datakey", "+", "'.'", ":", "''", ")", "+", "colname", ".", "getMeta", "(", "'key'", ")", ";", "var", "name", "=", "pg_create_index_name", "(", "self", ",", "ObjType", ",", "type", ",", "field", ",", "typefield", ",", "is_unique", ")", ";", "return", "pg_relation_exists", "(", "self", ",", "name", ")", ".", "then", "(", "function", "(", "exists", ")", "{", "if", "(", "!", "exists", ")", "{", "return", "pg_create_index", "(", "self", ",", "ObjType", ",", "type", ",", "field", ",", "typefield", ",", "is_unique", ")", ";", "}", "return", "pg_get_indexdef", "(", "self", ",", "name", ")", ".", "then", "(", "function", "(", "old_indexdef", ")", "{", "var", "new_indexdef_v1", "=", "pg_create_index_query_v1", "(", "self", ",", "ObjType", ",", "type", ",", "field", ",", "typefield", ",", "is_unique", ")", ";", "var", "new_indexdef_v2", "=", "pg_create_index_query_v2", "(", "self", ",", "ObjType", ",", "type", ",", "field", ",", "typefield", ",", "is_unique", ")", ";", "if", "(", "new_indexdef_v1", "===", "old_indexdef", ")", "return", "self", ";", "if", "(", "new_indexdef_v2", "===", "old_indexdef", ")", "return", "self", ";", "if", "(", "NoPg", ".", "debug", ")", "{", "debug", ".", "info", "(", "'Rebuilding index...'", ")", ";", "debug", ".", "log", "(", "'old index is: '", ",", "old_indexdef", ")", ";", "debug", ".", "log", "(", "'new index is: '", ",", "new_indexdef_v1", ")", ";", "}", "return", "pg_drop_index", "(", "self", ",", "ObjType", ",", "type", ",", "field", ",", "typefield", ")", ".", "then", "(", "function", "(", ")", "{", "return", "pg_create_index", "(", "self", ",", "ObjType", ",", "type", ",", "field", ",", "typefield", ",", "is_unique", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Internal CREATE INDEX query that will create the index only if the relation does not exists already @param self @param ObjType @param type @param field @param typefield @param is_unique @return {Promise.<TResult>}
[ "Internal", "CREATE", "INDEX", "query", "that", "will", "create", "the", "index", "only", "if", "the", "relation", "does", "not", "exists", "already" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1594-L1622
51,003
sendanor/nor-nopg
src/nopg.js
pg_query
function pg_query(query, params) { return function(db) { var start_time = new Date(); return do_query(db, query, params).then(function() { var end_time = new Date(); db._record_sample({ 'event': 'query', 'start': start_time, 'end': end_time, 'query': query, 'params': params }); return db; }); }; }
javascript
function pg_query(query, params) { return function(db) { var start_time = new Date(); return do_query(db, query, params).then(function() { var end_time = new Date(); db._record_sample({ 'event': 'query', 'start': start_time, 'end': end_time, 'query': query, 'params': params }); return db; }); }; }
[ "function", "pg_query", "(", "query", ",", "params", ")", "{", "return", "function", "(", "db", ")", "{", "var", "start_time", "=", "new", "Date", "(", ")", ";", "return", "do_query", "(", "db", ",", "query", ",", "params", ")", ".", "then", "(", "function", "(", ")", "{", "var", "end_time", "=", "new", "Date", "(", ")", ";", "db", ".", "_record_sample", "(", "{", "'event'", ":", "'query'", ",", "'start'", ":", "start_time", ",", "'end'", ":", "end_time", ",", "'query'", ":", "query", ",", "'params'", ":", "params", "}", ")", ";", "return", "db", ";", "}", ")", ";", "}", ";", "}" ]
Run query on the PostgreSQL server @param query @param params @return {Function}
[ "Run", "query", "on", "the", "PostgreSQL", "server" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1731-L1749
51,004
sendanor/nor-nopg
src/nopg.js
create_watchdog
function create_watchdog(db, opts) { debug.assert(db).is('object'); opts = opts || {}; debug.assert(opts).is('object'); opts.timeout = opts.timeout || 30000; debug.assert(opts.timeout).is('number'); var w = {}; w.db = db; w.opts = opts; /* Setup */ w.timeout = setTimeout(function() { debug.warn('Got timeout.'); w.timeout = undefined; Q.fcall(function() { var tr_open, tr_commit, tr_rollback, state, tr_unknown, tr_disconnect; // NoPg instance if(w.db === undefined) { debug.warn("Timeout exceeded and database instance undefined. Nothing done."); return; } if(!(w.db && w.db._tr_state)) { debug.warn("Timeout exceeded but db was not NoPg instance."); return; } state = w.db._tr_state; tr_open = (state === 'open') ? true : false; tr_commit = (state === 'commit') ? true : false; tr_rollback = (state === 'rollback') ? true : false; tr_disconnect = (state === 'disconnect') ? true : false; tr_unknown = ((!tr_open) && (!tr_commit) && (!tr_rollback) && (!tr_disconnect)) ? true : false; if(tr_unknown) { debug.warn("Timeout exceeded and transaction state was unknown ("+state+"). Nothing done."); return; } if(tr_open) { debug.warn("Timeout exceeded and transaction still open. Closing it by rollback."); return w.db.rollback().fail(function(err) { debug.error("Rollback failed: " + (err.stack || err) ); }); } if(tr_disconnect) { //debug.log('...but .disconnect() was already done.'); return; } if(tr_commit) { //debug.log('...but .commit() was already done.'); return; } if(tr_rollback) { //debug.log('...but .rollback() was already done.'); return; } }).fin(function() { if(w && w.db) { w.db._events.emit('timeout'); } }).done(); }, opts.timeout); /* Set object */ w.reset = function(o) { debug.assert(o).is('object'); //debug.log('Resetting the watchdog.'); w.db = o; }; /** Clear the timeout */ w.clear = function() { if(w.timeout) { //debug.log('Clearing the watchdog.'); clearTimeout(w.timeout); w.timeout = undefined; } }; return w; }
javascript
function create_watchdog(db, opts) { debug.assert(db).is('object'); opts = opts || {}; debug.assert(opts).is('object'); opts.timeout = opts.timeout || 30000; debug.assert(opts.timeout).is('number'); var w = {}; w.db = db; w.opts = opts; /* Setup */ w.timeout = setTimeout(function() { debug.warn('Got timeout.'); w.timeout = undefined; Q.fcall(function() { var tr_open, tr_commit, tr_rollback, state, tr_unknown, tr_disconnect; // NoPg instance if(w.db === undefined) { debug.warn("Timeout exceeded and database instance undefined. Nothing done."); return; } if(!(w.db && w.db._tr_state)) { debug.warn("Timeout exceeded but db was not NoPg instance."); return; } state = w.db._tr_state; tr_open = (state === 'open') ? true : false; tr_commit = (state === 'commit') ? true : false; tr_rollback = (state === 'rollback') ? true : false; tr_disconnect = (state === 'disconnect') ? true : false; tr_unknown = ((!tr_open) && (!tr_commit) && (!tr_rollback) && (!tr_disconnect)) ? true : false; if(tr_unknown) { debug.warn("Timeout exceeded and transaction state was unknown ("+state+"). Nothing done."); return; } if(tr_open) { debug.warn("Timeout exceeded and transaction still open. Closing it by rollback."); return w.db.rollback().fail(function(err) { debug.error("Rollback failed: " + (err.stack || err) ); }); } if(tr_disconnect) { //debug.log('...but .disconnect() was already done.'); return; } if(tr_commit) { //debug.log('...but .commit() was already done.'); return; } if(tr_rollback) { //debug.log('...but .rollback() was already done.'); return; } }).fin(function() { if(w && w.db) { w.db._events.emit('timeout'); } }).done(); }, opts.timeout); /* Set object */ w.reset = function(o) { debug.assert(o).is('object'); //debug.log('Resetting the watchdog.'); w.db = o; }; /** Clear the timeout */ w.clear = function() { if(w.timeout) { //debug.log('Clearing the watchdog.'); clearTimeout(w.timeout); w.timeout = undefined; } }; return w; }
[ "function", "create_watchdog", "(", "db", ",", "opts", ")", "{", "debug", ".", "assert", "(", "db", ")", ".", "is", "(", "'object'", ")", ";", "opts", "=", "opts", "||", "{", "}", ";", "debug", ".", "assert", "(", "opts", ")", ".", "is", "(", "'object'", ")", ";", "opts", ".", "timeout", "=", "opts", ".", "timeout", "||", "30000", ";", "debug", ".", "assert", "(", "opts", ".", "timeout", ")", ".", "is", "(", "'number'", ")", ";", "var", "w", "=", "{", "}", ";", "w", ".", "db", "=", "db", ";", "w", ".", "opts", "=", "opts", ";", "/* Setup */", "w", ".", "timeout", "=", "setTimeout", "(", "function", "(", ")", "{", "debug", ".", "warn", "(", "'Got timeout.'", ")", ";", "w", ".", "timeout", "=", "undefined", ";", "Q", ".", "fcall", "(", "function", "(", ")", "{", "var", "tr_open", ",", "tr_commit", ",", "tr_rollback", ",", "state", ",", "tr_unknown", ",", "tr_disconnect", ";", "// NoPg instance", "if", "(", "w", ".", "db", "===", "undefined", ")", "{", "debug", ".", "warn", "(", "\"Timeout exceeded and database instance undefined. Nothing done.\"", ")", ";", "return", ";", "}", "if", "(", "!", "(", "w", ".", "db", "&&", "w", ".", "db", ".", "_tr_state", ")", ")", "{", "debug", ".", "warn", "(", "\"Timeout exceeded but db was not NoPg instance.\"", ")", ";", "return", ";", "}", "state", "=", "w", ".", "db", ".", "_tr_state", ";", "tr_open", "=", "(", "state", "===", "'open'", ")", "?", "true", ":", "false", ";", "tr_commit", "=", "(", "state", "===", "'commit'", ")", "?", "true", ":", "false", ";", "tr_rollback", "=", "(", "state", "===", "'rollback'", ")", "?", "true", ":", "false", ";", "tr_disconnect", "=", "(", "state", "===", "'disconnect'", ")", "?", "true", ":", "false", ";", "tr_unknown", "=", "(", "(", "!", "tr_open", ")", "&&", "(", "!", "tr_commit", ")", "&&", "(", "!", "tr_rollback", ")", "&&", "(", "!", "tr_disconnect", ")", ")", "?", "true", ":", "false", ";", "if", "(", "tr_unknown", ")", "{", "debug", ".", "warn", "(", "\"Timeout exceeded and transaction state was unknown (\"", "+", "state", "+", "\"). Nothing done.\"", ")", ";", "return", ";", "}", "if", "(", "tr_open", ")", "{", "debug", ".", "warn", "(", "\"Timeout exceeded and transaction still open. Closing it by rollback.\"", ")", ";", "return", "w", ".", "db", ".", "rollback", "(", ")", ".", "fail", "(", "function", "(", "err", ")", "{", "debug", ".", "error", "(", "\"Rollback failed: \"", "+", "(", "err", ".", "stack", "||", "err", ")", ")", ";", "}", ")", ";", "}", "if", "(", "tr_disconnect", ")", "{", "//debug.log('...but .disconnect() was already done.');", "return", ";", "}", "if", "(", "tr_commit", ")", "{", "//debug.log('...but .commit() was already done.');", "return", ";", "}", "if", "(", "tr_rollback", ")", "{", "//debug.log('...but .rollback() was already done.');", "return", ";", "}", "}", ")", ".", "fin", "(", "function", "(", ")", "{", "if", "(", "w", "&&", "w", ".", "db", ")", "{", "w", ".", "db", ".", "_events", ".", "emit", "(", "'timeout'", ")", ";", "}", "}", ")", ".", "done", "(", ")", ";", "}", ",", "opts", ".", "timeout", ")", ";", "/* Set object */", "w", ".", "reset", "=", "function", "(", "o", ")", "{", "debug", ".", "assert", "(", "o", ")", ".", "is", "(", "'object'", ")", ";", "//debug.log('Resetting the watchdog.');", "w", ".", "db", "=", "o", ";", "}", ";", "/** Clear the timeout */", "w", ".", "clear", "=", "function", "(", ")", "{", "if", "(", "w", ".", "timeout", ")", "{", "//debug.log('Clearing the watchdog.');", "clearTimeout", "(", "w", ".", "timeout", ")", ";", "w", ".", "timeout", "=", "undefined", ";", "}", "}", ";", "return", "w", ";", "}" ]
Create watchdog timer @param db @param opts @return {{}}
[ "Create", "watchdog", "timer" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1756-L1847
51,005
sendanor/nor-nopg
src/nopg.js
create_tcn_listener
function create_tcn_listener(events, when) { debug.assert(events).is('object'); debug.assert(when).is('object'); // Normalize event object back to event name var when_str = NoPg.stringifyEventName(when); return function tcn_listener(payload) { payload = NoPg.parseTCNPayload(payload); var event = tcn_event_mapping[''+payload.table+','+payload.op]; if(!event) { debug.warn('Could not find event name for payload: ', payload); return; } // Verify we don't emit, if matching id enabled and does not match if( when.hasOwnProperty('id') && (payload.keys.id !== when.id) ) { return; } // Verify we don't emit, if matching event name enabled and does not match if( when.hasOwnProperty('name') && (event !== when.name) ) { return; } events.emit(when_str, payload.keys.id, event, when.type); }; }
javascript
function create_tcn_listener(events, when) { debug.assert(events).is('object'); debug.assert(when).is('object'); // Normalize event object back to event name var when_str = NoPg.stringifyEventName(when); return function tcn_listener(payload) { payload = NoPg.parseTCNPayload(payload); var event = tcn_event_mapping[''+payload.table+','+payload.op]; if(!event) { debug.warn('Could not find event name for payload: ', payload); return; } // Verify we don't emit, if matching id enabled and does not match if( when.hasOwnProperty('id') && (payload.keys.id !== when.id) ) { return; } // Verify we don't emit, if matching event name enabled and does not match if( when.hasOwnProperty('name') && (event !== when.name) ) { return; } events.emit(when_str, payload.keys.id, event, when.type); }; }
[ "function", "create_tcn_listener", "(", "events", ",", "when", ")", "{", "debug", ".", "assert", "(", "events", ")", ".", "is", "(", "'object'", ")", ";", "debug", ".", "assert", "(", "when", ")", ".", "is", "(", "'object'", ")", ";", "// Normalize event object back to event name", "var", "when_str", "=", "NoPg", ".", "stringifyEventName", "(", "when", ")", ";", "return", "function", "tcn_listener", "(", "payload", ")", "{", "payload", "=", "NoPg", ".", "parseTCNPayload", "(", "payload", ")", ";", "var", "event", "=", "tcn_event_mapping", "[", "''", "+", "payload", ".", "table", "+", "','", "+", "payload", ".", "op", "]", ";", "if", "(", "!", "event", ")", "{", "debug", ".", "warn", "(", "'Could not find event name for payload: '", ",", "payload", ")", ";", "return", ";", "}", "// Verify we don't emit, if matching id enabled and does not match", "if", "(", "when", ".", "hasOwnProperty", "(", "'id'", ")", "&&", "(", "payload", ".", "keys", ".", "id", "!==", "when", ".", "id", ")", ")", "{", "return", ";", "}", "// Verify we don't emit, if matching event name enabled and does not match", "if", "(", "when", ".", "hasOwnProperty", "(", "'name'", ")", "&&", "(", "event", "!==", "when", ".", "name", ")", ")", "{", "return", ";", "}", "events", ".", "emit", "(", "when_str", ",", "payload", ".", "keys", ".", "id", ",", "event", ",", "when", ".", "type", ")", ";", "}", ";", "}" ]
Returns a listener for notifications from TCN extension @param events {EventEmitter} The event emitter where we should trigger matching events. @param when {object} We should only trigger events that match this specification. Object with optional properties `type`, `id` and `name`.
[ "Returns", "a", "listener", "for", "notifications", "from", "TCN", "extension" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L2456-L2485
51,006
sendanor/nor-nopg
src/nopg.js
new_listener
function new_listener(event/*, listener*/) { // Ignore if not tcn event if(NoPg.isLocalEventName(event)) { return; } event = NoPg.parseEventName(event); // Stringifying back the event normalizes the original event name var event_name = NoPg.stringifyEventName(event); var channel_name = NoPg.parseTCNChannelName(event); // If we are already listening, just increase the counter. if(counter.hasOwnProperty(event_name)) { counter[event_name] += 1; return; } // Create the listener if necessary var tcn_listener; if(!tcn_listeners.hasOwnProperty(event_name)) { tcn_listener = tcn_listeners[event_name] = create_tcn_listener(self._events, event); } else { tcn_listener = tcn_listeners[event_name]; } // Start listening tcn events for this channel //debug.log('Listening channel ' + channel_name + ' for ' + event_name); self._db.on(channel_name, tcn_listener); counter[event_name] = 1; }
javascript
function new_listener(event/*, listener*/) { // Ignore if not tcn event if(NoPg.isLocalEventName(event)) { return; } event = NoPg.parseEventName(event); // Stringifying back the event normalizes the original event name var event_name = NoPg.stringifyEventName(event); var channel_name = NoPg.parseTCNChannelName(event); // If we are already listening, just increase the counter. if(counter.hasOwnProperty(event_name)) { counter[event_name] += 1; return; } // Create the listener if necessary var tcn_listener; if(!tcn_listeners.hasOwnProperty(event_name)) { tcn_listener = tcn_listeners[event_name] = create_tcn_listener(self._events, event); } else { tcn_listener = tcn_listeners[event_name]; } // Start listening tcn events for this channel //debug.log('Listening channel ' + channel_name + ' for ' + event_name); self._db.on(channel_name, tcn_listener); counter[event_name] = 1; }
[ "function", "new_listener", "(", "event", "/*, listener*/", ")", "{", "// Ignore if not tcn event", "if", "(", "NoPg", ".", "isLocalEventName", "(", "event", ")", ")", "{", "return", ";", "}", "event", "=", "NoPg", ".", "parseEventName", "(", "event", ")", ";", "// Stringifying back the event normalizes the original event name", "var", "event_name", "=", "NoPg", ".", "stringifyEventName", "(", "event", ")", ";", "var", "channel_name", "=", "NoPg", ".", "parseTCNChannelName", "(", "event", ")", ";", "// If we are already listening, just increase the counter.", "if", "(", "counter", ".", "hasOwnProperty", "(", "event_name", ")", ")", "{", "counter", "[", "event_name", "]", "+=", "1", ";", "return", ";", "}", "// Create the listener if necessary", "var", "tcn_listener", ";", "if", "(", "!", "tcn_listeners", ".", "hasOwnProperty", "(", "event_name", ")", ")", "{", "tcn_listener", "=", "tcn_listeners", "[", "event_name", "]", "=", "create_tcn_listener", "(", "self", ".", "_events", ",", "event", ")", ";", "}", "else", "{", "tcn_listener", "=", "tcn_listeners", "[", "event_name", "]", ";", "}", "// Start listening tcn events for this channel", "//debug.log('Listening channel ' + channel_name + ' for ' + event_name);", "self", ".", "_db", ".", "on", "(", "channel_name", ",", "tcn_listener", ")", ";", "counter", "[", "event_name", "]", "=", "1", ";", "}" ]
Listener for new listeners
[ "Listener", "for", "new", "listeners" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L2508-L2540
51,007
sendanor/nor-nopg
src/nopg.js
remove_listener
function remove_listener(event/*, listener*/) { // Ignore if not tcn event if(NoPg.isLocalEventName(event)) { return; } event = NoPg.parseEventName(event); // Stringifying back the event normalizes the original event name var event_name = NoPg.stringifyEventName(event); var channel_name = NoPg.parseTCNChannelName(event); counter[event_name] -= 1; if(counter[event_name] === 0) { //debug.log('Stopped listening channel ' + channel_name + ' for ' + event_name); self._db.removeListener(channel_name, tcn_listeners[event_name]); delete counter[event_name]; } }
javascript
function remove_listener(event/*, listener*/) { // Ignore if not tcn event if(NoPg.isLocalEventName(event)) { return; } event = NoPg.parseEventName(event); // Stringifying back the event normalizes the original event name var event_name = NoPg.stringifyEventName(event); var channel_name = NoPg.parseTCNChannelName(event); counter[event_name] -= 1; if(counter[event_name] === 0) { //debug.log('Stopped listening channel ' + channel_name + ' for ' + event_name); self._db.removeListener(channel_name, tcn_listeners[event_name]); delete counter[event_name]; } }
[ "function", "remove_listener", "(", "event", "/*, listener*/", ")", "{", "// Ignore if not tcn event", "if", "(", "NoPg", ".", "isLocalEventName", "(", "event", ")", ")", "{", "return", ";", "}", "event", "=", "NoPg", ".", "parseEventName", "(", "event", ")", ";", "// Stringifying back the event normalizes the original event name", "var", "event_name", "=", "NoPg", ".", "stringifyEventName", "(", "event", ")", ";", "var", "channel_name", "=", "NoPg", ".", "parseTCNChannelName", "(", "event", ")", ";", "counter", "[", "event_name", "]", "-=", "1", ";", "if", "(", "counter", "[", "event_name", "]", "===", "0", ")", "{", "//debug.log('Stopped listening channel ' + channel_name + ' for ' + event_name);", "self", ".", "_db", ".", "removeListener", "(", "channel_name", ",", "tcn_listeners", "[", "event_name", "]", ")", ";", "delete", "counter", "[", "event_name", "]", ";", "}", "}" ]
Listener for removing listeners
[ "Listener", "for", "removing", "listeners" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L2543-L2564
51,008
sendanor/nor-nopg
src/nopg.js
pad
function pad(num, size) { var s = num+""; while (s.length < size) { s = "0" + s; } return s; }
javascript
function pad(num, size) { var s = num+""; while (s.length < size) { s = "0" + s; } return s; }
[ "function", "pad", "(", "num", ",", "size", ")", "{", "var", "s", "=", "num", "+", "\"\"", ";", "while", "(", "s", ".", "length", "<", "size", ")", "{", "s", "=", "\"0\"", "+", "s", ";", "}", "return", "s", ";", "}" ]
Returns a number padded to specific width @param num @param size @return {string}
[ "Returns", "a", "number", "padded", "to", "specific", "width" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L2655-L2661
51,009
sendanor/nor-nopg
src/nopg.js
reset_methods
function reset_methods(doc) { if(is.array(doc)) { return ARRAY(doc).map(reset_methods).valueOf(); } if(is.object(doc)) { ARRAY(methods).forEach(function(method) { delete doc[method.$name]; }); } return doc; }
javascript
function reset_methods(doc) { if(is.array(doc)) { return ARRAY(doc).map(reset_methods).valueOf(); } if(is.object(doc)) { ARRAY(methods).forEach(function(method) { delete doc[method.$name]; }); } return doc; }
[ "function", "reset_methods", "(", "doc", ")", "{", "if", "(", "is", ".", "array", "(", "doc", ")", ")", "{", "return", "ARRAY", "(", "doc", ")", ".", "map", "(", "reset_methods", ")", ".", "valueOf", "(", ")", ";", "}", "if", "(", "is", ".", "object", "(", "doc", ")", ")", "{", "ARRAY", "(", "methods", ")", ".", "forEach", "(", "function", "(", "method", ")", "{", "delete", "doc", "[", "method", ".", "$name", "]", ";", "}", ")", ";", "}", "return", "doc", ";", "}" ]
Removes methods from doc
[ "Removes", "methods", "from", "doc" ]
0d99b86c1a1996b5828b56de8de23700df8bbc0c
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L3175-L3188
51,010
gyuwon/node-fwalker
fwalker.js
Walker
function Walker () { var self = this; var walkSync = function (dir, trace, callback) { fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name) , stat = fs.lstatSync(file) , isDir = stat.isDirectory() , _trace = trace; try { callback(name, file, isDir, function () { return _trace.slice(0); }); } finally { _trace = null; } if (isDir) { trace.push(name); try { walkSync(file, trace, callback); } finally { trace.pop(); } } }); }; /** * Traverse the directory synchronously. * * Parameters * - dir: A directory to traverse * - callback: A function to be called for each file recursively * * Returns: The list of information of files contained in 'dir' */ self.walkSync = function (dir, callback) { if (typeof callback != 'function') { throw new Error("'callback' is not a function."); } walkSync(dir, [], callback); }; }
javascript
function Walker () { var self = this; var walkSync = function (dir, trace, callback) { fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name) , stat = fs.lstatSync(file) , isDir = stat.isDirectory() , _trace = trace; try { callback(name, file, isDir, function () { return _trace.slice(0); }); } finally { _trace = null; } if (isDir) { trace.push(name); try { walkSync(file, trace, callback); } finally { trace.pop(); } } }); }; /** * Traverse the directory synchronously. * * Parameters * - dir: A directory to traverse * - callback: A function to be called for each file recursively * * Returns: The list of information of files contained in 'dir' */ self.walkSync = function (dir, callback) { if (typeof callback != 'function') { throw new Error("'callback' is not a function."); } walkSync(dir, [], callback); }; }
[ "function", "Walker", "(", ")", "{", "var", "self", "=", "this", ";", "var", "walkSync", "=", "function", "(", "dir", ",", "trace", ",", "callback", ")", "{", "fs", ".", "readdirSync", "(", "dir", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "var", "file", "=", "path", ".", "join", "(", "dir", ",", "name", ")", ",", "stat", "=", "fs", ".", "lstatSync", "(", "file", ")", ",", "isDir", "=", "stat", ".", "isDirectory", "(", ")", ",", "_trace", "=", "trace", ";", "try", "{", "callback", "(", "name", ",", "file", ",", "isDir", ",", "function", "(", ")", "{", "return", "_trace", ".", "slice", "(", "0", ")", ";", "}", ")", ";", "}", "finally", "{", "_trace", "=", "null", ";", "}", "if", "(", "isDir", ")", "{", "trace", ".", "push", "(", "name", ")", ";", "try", "{", "walkSync", "(", "file", ",", "trace", ",", "callback", ")", ";", "}", "finally", "{", "trace", ".", "pop", "(", ")", ";", "}", "}", "}", ")", ";", "}", ";", "/**\n * Traverse the directory synchronously.\n *\n * Parameters\n * - dir: A directory to traverse\n * - callback: A function to be called for each file recursively\n *\n * Returns: The list of information of files contained in 'dir'\n */", "self", ".", "walkSync", "=", "function", "(", "dir", ",", "callback", ")", "{", "if", "(", "typeof", "callback", "!=", "'function'", ")", "{", "throw", "new", "Error", "(", "\"'callback' is not a function.\"", ")", ";", "}", "walkSync", "(", "dir", ",", "[", "]", ",", "callback", ")", ";", "}", ";", "}" ]
Initialize a new instance of the simple file traversal modules.
[ "Initialize", "a", "new", "instance", "of", "the", "simple", "file", "traversal", "modules", "." ]
6e31a1f6da9b0be516ceab9035e87f2934d6aac6
https://github.com/gyuwon/node-fwalker/blob/6e31a1f6da9b0be516ceab9035e87f2934d6aac6/fwalker.js#L33-L77
51,011
MostlyJS/mostly-feathers-mongoose
src/mongoose.js
getModel
function getModel (app, name, Model) { const mongooseClient = app.get('mongoose'); assert(mongooseClient, 'mongoose client not set by app'); const modelNames = mongooseClient.modelNames(); if (modelNames.includes(name)) { return mongooseClient.model(name); } else { assert(Model && typeof Model === 'function', 'Model function not privided.'); return Model(app, name); } }
javascript
function getModel (app, name, Model) { const mongooseClient = app.get('mongoose'); assert(mongooseClient, 'mongoose client not set by app'); const modelNames = mongooseClient.modelNames(); if (modelNames.includes(name)) { return mongooseClient.model(name); } else { assert(Model && typeof Model === 'function', 'Model function not privided.'); return Model(app, name); } }
[ "function", "getModel", "(", "app", ",", "name", ",", "Model", ")", "{", "const", "mongooseClient", "=", "app", ".", "get", "(", "'mongoose'", ")", ";", "assert", "(", "mongooseClient", ",", "'mongoose client not set by app'", ")", ";", "const", "modelNames", "=", "mongooseClient", ".", "modelNames", "(", ")", ";", "if", "(", "modelNames", ".", "includes", "(", "name", ")", ")", "{", "return", "mongooseClient", ".", "model", "(", "name", ")", ";", "}", "else", "{", "assert", "(", "Model", "&&", "typeof", "Model", "===", "'function'", ",", "'Model function not privided.'", ")", ";", "return", "Model", "(", "app", ",", "name", ")", ";", "}", "}" ]
Get or create the mongoose model if not exists
[ "Get", "or", "create", "the", "mongoose", "model", "if", "not", "exists" ]
d20e150e054c784cc7db7c2487399e4f4eb730de
https://github.com/MostlyJS/mostly-feathers-mongoose/blob/d20e150e054c784cc7db7c2487399e4f4eb730de/src/mongoose.js#L46-L56
51,012
MostlyJS/mostly-feathers-mongoose
src/mongoose.js
createModel
function createModel (app, name, options) { const mongooseClient = app.get('mongoose'); assert(mongooseClient, 'mongoose client not set by app'); const schema = new mongooseClient.Schema({ any: {} }, {strict: false}); return mongooseClient.model(name, schema); }
javascript
function createModel (app, name, options) { const mongooseClient = app.get('mongoose'); assert(mongooseClient, 'mongoose client not set by app'); const schema = new mongooseClient.Schema({ any: {} }, {strict: false}); return mongooseClient.model(name, schema); }
[ "function", "createModel", "(", "app", ",", "name", ",", "options", ")", "{", "const", "mongooseClient", "=", "app", ".", "get", "(", "'mongoose'", ")", ";", "assert", "(", "mongooseClient", ",", "'mongoose client not set by app'", ")", ";", "const", "schema", "=", "new", "mongooseClient", ".", "Schema", "(", "{", "any", ":", "{", "}", "}", ",", "{", "strict", ":", "false", "}", ")", ";", "return", "mongooseClient", ".", "model", "(", "name", ",", "schema", ")", ";", "}" ]
Create a mongoose model with free schema
[ "Create", "a", "mongoose", "model", "with", "free", "schema" ]
d20e150e054c784cc7db7c2487399e4f4eb730de
https://github.com/MostlyJS/mostly-feathers-mongoose/blob/d20e150e054c784cc7db7c2487399e4f4eb730de/src/mongoose.js#L61-L66
51,013
MostlyJS/mostly-feathers-mongoose
src/mongoose.js
createService
function createService (app, Service, Model, options) { Model = options.Model || Model; if (typeof Model === 'function') { assert(options.ModelName, 'createService but options.ModelName not provided'); options.Model = Model(app, options.ModelName); } else { options.Model = Model; } const service = new Service(options); return service; }
javascript
function createService (app, Service, Model, options) { Model = options.Model || Model; if (typeof Model === 'function') { assert(options.ModelName, 'createService but options.ModelName not provided'); options.Model = Model(app, options.ModelName); } else { options.Model = Model; } const service = new Service(options); return service; }
[ "function", "createService", "(", "app", ",", "Service", ",", "Model", ",", "options", ")", "{", "Model", "=", "options", ".", "Model", "||", "Model", ";", "if", "(", "typeof", "Model", "===", "'function'", ")", "{", "assert", "(", "options", ".", "ModelName", ",", "'createService but options.ModelName not provided'", ")", ";", "options", ".", "Model", "=", "Model", "(", "app", ",", "options", ".", "ModelName", ")", ";", "}", "else", "{", "options", ".", "Model", "=", "Model", ";", "}", "const", "service", "=", "new", "Service", "(", "options", ")", ";", "return", "service", ";", "}" ]
Create a service with mogoose model
[ "Create", "a", "service", "with", "mogoose", "model" ]
d20e150e054c784cc7db7c2487399e4f4eb730de
https://github.com/MostlyJS/mostly-feathers-mongoose/blob/d20e150e054c784cc7db7c2487399e4f4eb730de/src/mongoose.js#L71-L81
51,014
gethuman/pancakes-angular
lib/ngapp/tpl.helper.js
setDefaults
function setDefaults(scope, defaults) { if (!defaults) { return; } // store defaults for use in generateRemodel scope.defaults = defaults; for (var name in defaults) { if (defaults.hasOwnProperty(name) && scope[name] === undefined) { scope[name] = defaults[name]; } } }
javascript
function setDefaults(scope, defaults) { if (!defaults) { return; } // store defaults for use in generateRemodel scope.defaults = defaults; for (var name in defaults) { if (defaults.hasOwnProperty(name) && scope[name] === undefined) { scope[name] = defaults[name]; } } }
[ "function", "setDefaults", "(", "scope", ",", "defaults", ")", "{", "if", "(", "!", "defaults", ")", "{", "return", ";", "}", "// store defaults for use in generateRemodel", "scope", ".", "defaults", "=", "defaults", ";", "for", "(", "var", "name", "in", "defaults", ")", "{", "if", "(", "defaults", ".", "hasOwnProperty", "(", "name", ")", "&&", "scope", "[", "name", "]", "===", "undefined", ")", "{", "scope", "[", "name", "]", "=", "defaults", "[", "name", "]", ";", "}", "}", "}" ]
Given a set of default values, add them to the scope if a value does not already exist. @param scope @param defaults
[ "Given", "a", "set", "of", "default", "values", "add", "them", "to", "the", "scope", "if", "a", "value", "does", "not", "already", "exist", "." ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/ngapp/tpl.helper.js#L17-L28
51,015
gethuman/pancakes-angular
lib/ngapp/tpl.helper.js
addValidations
function addValidations(scope, validations) { for (var name in validations) { if (validations.hasOwnProperty(name) && validations[name]) { scope[name] = $injector.invoke(validations[name]); } } }
javascript
function addValidations(scope, validations) { for (var name in validations) { if (validations.hasOwnProperty(name) && validations[name]) { scope[name] = $injector.invoke(validations[name]); } } }
[ "function", "addValidations", "(", "scope", ",", "validations", ")", "{", "for", "(", "var", "name", "in", "validations", ")", "{", "if", "(", "validations", ".", "hasOwnProperty", "(", "name", ")", "&&", "validations", "[", "name", "]", ")", "{", "scope", "[", "name", "]", "=", "$injector", ".", "invoke", "(", "validations", "[", "name", "]", ")", ";", "}", "}", "}" ]
Add validations to the scope @param scope @param validations
[ "Add", "validations", "to", "the", "scope" ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/ngapp/tpl.helper.js#L173-L179
51,016
gethuman/pancakes-angular
lib/ngapp/tpl.helper.js
attachToScope
function attachToScope(scope, itemsToAttach) { if (!itemsToAttach || !itemsToAttach.length) { return; } itemsToAttach.push(function () { var i, val; for (i = 0; i < arguments.length; i++) { val = arguments[i]; scope[itemsToAttach[i]] = val; } }); $injector.invoke(itemsToAttach); }
javascript
function attachToScope(scope, itemsToAttach) { if (!itemsToAttach || !itemsToAttach.length) { return; } itemsToAttach.push(function () { var i, val; for (i = 0; i < arguments.length; i++) { val = arguments[i]; scope[itemsToAttach[i]] = val; } }); $injector.invoke(itemsToAttach); }
[ "function", "attachToScope", "(", "scope", ",", "itemsToAttach", ")", "{", "if", "(", "!", "itemsToAttach", "||", "!", "itemsToAttach", ".", "length", ")", "{", "return", ";", "}", "itemsToAttach", ".", "push", "(", "function", "(", ")", "{", "var", "i", ",", "val", ";", "for", "(", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "val", "=", "arguments", "[", "i", "]", ";", "scope", "[", "itemsToAttach", "[", "i", "]", "]", "=", "val", ";", "}", "}", ")", ";", "$injector", ".", "invoke", "(", "itemsToAttach", ")", ";", "}" ]
Given an array of items, instantiate them and attach them to the scope. @param scope @param itemsToAttach
[ "Given", "an", "array", "of", "items", "instantiate", "them", "and", "attach", "them", "to", "the", "scope", "." ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/ngapp/tpl.helper.js#L186-L198
51,017
gethuman/pancakes-angular
lib/ngapp/tpl.helper.js
addInitModel
function addInitModel(scope, initialModel, pageName) { angular.extend(scope, initialModel); if (scope.pageHead && scope.pageHead.title) { var title = scope.pageHead.title; pageSettings.updateHead(title, scope.pageHead.description || title); pageSettings.updatePageStyle(pageName); } }
javascript
function addInitModel(scope, initialModel, pageName) { angular.extend(scope, initialModel); if (scope.pageHead && scope.pageHead.title) { var title = scope.pageHead.title; pageSettings.updateHead(title, scope.pageHead.description || title); pageSettings.updatePageStyle(pageName); } }
[ "function", "addInitModel", "(", "scope", ",", "initialModel", ",", "pageName", ")", "{", "angular", ".", "extend", "(", "scope", ",", "initialModel", ")", ";", "if", "(", "scope", ".", "pageHead", "&&", "scope", ".", "pageHead", ".", "title", ")", "{", "var", "title", "=", "scope", ".", "pageHead", ".", "title", ";", "pageSettings", ".", "updateHead", "(", "title", ",", "scope", ".", "pageHead", ".", "description", "||", "title", ")", ";", "pageSettings", ".", "updatePageStyle", "(", "pageName", ")", ";", "}", "}" ]
Add the initial model to the scope and set the page title, desc, etc. @param scope @param initialModel @param pageName
[ "Add", "the", "initial", "model", "to", "the", "scope", "and", "set", "the", "page", "title", "desc", "etc", "." ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/ngapp/tpl.helper.js#L338-L346
51,018
gethuman/pancakes-angular
lib/ngapp/tpl.helper.js
registerListeners
function registerListeners(scope, listeners) { var fns = []; for (var name in listeners) { if (listeners.hasOwnProperty(name) && listeners[name]) { fns.push(eventBus.on(name, $injector.invoke(listeners[name]))); } } // make sure handlers are destroyed along with scope scope.$on('$destroy', function () { for (var i = 0; i < fns.length; i++) { fns[i](); } }); }
javascript
function registerListeners(scope, listeners) { var fns = []; for (var name in listeners) { if (listeners.hasOwnProperty(name) && listeners[name]) { fns.push(eventBus.on(name, $injector.invoke(listeners[name]))); } } // make sure handlers are destroyed along with scope scope.$on('$destroy', function () { for (var i = 0; i < fns.length; i++) { fns[i](); } }); }
[ "function", "registerListeners", "(", "scope", ",", "listeners", ")", "{", "var", "fns", "=", "[", "]", ";", "for", "(", "var", "name", "in", "listeners", ")", "{", "if", "(", "listeners", ".", "hasOwnProperty", "(", "name", ")", "&&", "listeners", "[", "name", "]", ")", "{", "fns", ".", "push", "(", "eventBus", ".", "on", "(", "name", ",", "$injector", ".", "invoke", "(", "listeners", "[", "name", "]", ")", ")", ")", ";", "}", "}", "// make sure handlers are destroyed along with scope", "scope", ".", "$on", "(", "'$destroy'", ",", "function", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "fns", ".", "length", ";", "i", "++", ")", "{", "fns", "[", "i", "]", "(", ")", ";", "}", "}", ")", ";", "}" ]
Register listeners and make sure they will be destoryed once the scope is destroyed. @param scope @param listeners
[ "Register", "listeners", "and", "make", "sure", "they", "will", "be", "destoryed", "once", "the", "scope", "is", "destroyed", "." ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/ngapp/tpl.helper.js#L355-L370
51,019
gethuman/pancakes-angular
lib/ngapp/tpl.helper.js
addEventHandlers
function addEventHandlers(scope, ctrlName, handlers) { if (!handlers) { return; } for (var name in handlers) { if (handlers.hasOwnProperty(name) && handlers[name]) { scope[name] = $injector.invoke(handlers[name]); // if it is not a function, throw error b/c dev likely made a mistake if (!angular.isFunction(scope[name])) { throw new Error(ctrlName + ' has uiEventHandler ' + name + ' that does not return a function'); } } } }
javascript
function addEventHandlers(scope, ctrlName, handlers) { if (!handlers) { return; } for (var name in handlers) { if (handlers.hasOwnProperty(name) && handlers[name]) { scope[name] = $injector.invoke(handlers[name]); // if it is not a function, throw error b/c dev likely made a mistake if (!angular.isFunction(scope[name])) { throw new Error(ctrlName + ' has uiEventHandler ' + name + ' that does not return a function'); } } } }
[ "function", "addEventHandlers", "(", "scope", ",", "ctrlName", ",", "handlers", ")", "{", "if", "(", "!", "handlers", ")", "{", "return", ";", "}", "for", "(", "var", "name", "in", "handlers", ")", "{", "if", "(", "handlers", ".", "hasOwnProperty", "(", "name", ")", "&&", "handlers", "[", "name", "]", ")", "{", "scope", "[", "name", "]", "=", "$injector", ".", "invoke", "(", "handlers", "[", "name", "]", ")", ";", "// if it is not a function, throw error b/c dev likely made a mistake", "if", "(", "!", "angular", ".", "isFunction", "(", "scope", "[", "name", "]", ")", ")", "{", "throw", "new", "Error", "(", "ctrlName", "+", "' has uiEventHandler '", "+", "name", "+", "' that does not return a function'", ")", ";", "}", "}", "}", "}" ]
Add the UI event handlers to the scope @param scope @param ctrlName @param handlers
[ "Add", "the", "UI", "event", "handlers", "to", "the", "scope" ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/ngapp/tpl.helper.js#L378-L391
51,020
cliffano/bagofcli
lib/bagofcli.js
exec
function exec(command, fallthrough, cb) { execute(command, fallthrough, false, function(err, stdOutOuput, stdErrOuput, result) { // drop stdOutOuput and stdErrOuput parameters to keep exec backwards compatible. cb(err, result); }); }
javascript
function exec(command, fallthrough, cb) { execute(command, fallthrough, false, function(err, stdOutOuput, stdErrOuput, result) { // drop stdOutOuput and stdErrOuput parameters to keep exec backwards compatible. cb(err, result); }); }
[ "function", "exec", "(", "command", ",", "fallthrough", ",", "cb", ")", "{", "execute", "(", "command", ",", "fallthrough", ",", "false", ",", "function", "(", "err", ",", "stdOutOuput", ",", "stdErrOuput", ",", "result", ")", "{", "// drop stdOutOuput and stdErrOuput parameters to keep exec backwards compatible.", "cb", "(", "err", ",", "result", ")", ";", "}", ")", ";", "}" ]
Execute a one-liner command. The output emitted on stderr and stdout of the child process will be written to process.stdout and process.stderr of this process. Fallthrough is handy in situation where there are multiple execs running in sequence/parallel, and they all have to be executed regardless of success/error on either one of them. @param {String} command: command to execute @param {Boolean} fallthrough: allow error to be camouflaged as a non-error @param {Function} cb: standard cb(err, result) callback
[ "Execute", "a", "one", "-", "liner", "command", "." ]
0950716c5a670ca5c73b3d27494b58d5b78f2179
https://github.com/cliffano/bagofcli/blob/0950716c5a670ca5c73b3d27494b58d5b78f2179/lib/bagofcli.js#L202-L207
51,021
cliffano/bagofcli
lib/bagofcli.js
execute
function execute(command, fallthrough, collectOutput, cb) { var collectedStdOut = ''; var collectedStdErr = ''; var _exec = child.exec(command, function (err) { var result; if (err && fallthrough) { // camouflage error to allow other execs to keep running result = err; err = null; } cb(err, collectedStdOut, collectedStdErr, result); }); _exec.stdout.on('data', function (data) { if (collectOutput) { collectedStdOut += data.toString().trim(); } else { process.stdout.write(colors.green(data.toString())); } }); _exec.stderr.on('data', function (data) { if (collectOutput) { collectedStdErr += data.toString().trim(); } else { process.stderr.write(colors.red(data.toString())); } }); }
javascript
function execute(command, fallthrough, collectOutput, cb) { var collectedStdOut = ''; var collectedStdErr = ''; var _exec = child.exec(command, function (err) { var result; if (err && fallthrough) { // camouflage error to allow other execs to keep running result = err; err = null; } cb(err, collectedStdOut, collectedStdErr, result); }); _exec.stdout.on('data', function (data) { if (collectOutput) { collectedStdOut += data.toString().trim(); } else { process.stdout.write(colors.green(data.toString())); } }); _exec.stderr.on('data', function (data) { if (collectOutput) { collectedStdErr += data.toString().trim(); } else { process.stderr.write(colors.red(data.toString())); } }); }
[ "function", "execute", "(", "command", ",", "fallthrough", ",", "collectOutput", ",", "cb", ")", "{", "var", "collectedStdOut", "=", "''", ";", "var", "collectedStdErr", "=", "''", ";", "var", "_exec", "=", "child", ".", "exec", "(", "command", ",", "function", "(", "err", ")", "{", "var", "result", ";", "if", "(", "err", "&&", "fallthrough", ")", "{", "// camouflage error to allow other execs to keep running", "result", "=", "err", ";", "err", "=", "null", ";", "}", "cb", "(", "err", ",", "collectedStdOut", ",", "collectedStdErr", ",", "result", ")", ";", "}", ")", ";", "_exec", ".", "stdout", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "if", "(", "collectOutput", ")", "{", "collectedStdOut", "+=", "data", ".", "toString", "(", ")", ".", "trim", "(", ")", ";", "}", "else", "{", "process", ".", "stdout", ".", "write", "(", "colors", ".", "green", "(", "data", ".", "toString", "(", ")", ")", ")", ";", "}", "}", ")", ";", "_exec", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "if", "(", "collectOutput", ")", "{", "collectedStdErr", "+=", "data", ".", "toString", "(", ")", ".", "trim", "(", ")", ";", "}", "else", "{", "process", ".", "stderr", ".", "write", "(", "colors", ".", "red", "(", "data", ".", "toString", "(", ")", ")", ")", ";", "}", "}", ")", ";", "}" ]
not exported Execute a one-liner command. The output emitted on stderr and stdout of the child process will either be written to process.stdout and process.stderr of this process or collected and passed on to the given callback, depending on collectOutput. Fallthrough is handy in situation where there are multiple execs running in sequence/parallel, and they all have to be executed regardless of success/error on either one of them. @param {String} command: command to execute @param {Boolean} fallthrough: allow error to be camouflaged as a non-error @param {Boolean} collectOutput: pass the output of the child process to the callback instead of writing it to error to be camouflaged as a non-error @param {Function} cb: (err, stdOutOuput, stdErrOuput, result) callback @private
[ "not", "exported", "Execute", "a", "one", "-", "liner", "command", "." ]
0950716c5a670ca5c73b3d27494b58d5b78f2179
https://github.com/cliffano/bagofcli/blob/0950716c5a670ca5c73b3d27494b58d5b78f2179/lib/bagofcli.js#L244-L273
51,022
cliffano/bagofcli
lib/bagofcli.js
exit
function exit(err, result) { if (err) { console.error(colors.red(err.message || JSON.stringify(err))); process.exit(1); } else { process.exit(0); } }
javascript
function exit(err, result) { if (err) { console.error(colors.red(err.message || JSON.stringify(err))); process.exit(1); } else { process.exit(0); } }
[ "function", "exit", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "console", ".", "error", "(", "colors", ".", "red", "(", "err", ".", "message", "||", "JSON", ".", "stringify", "(", "err", ")", ")", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "else", "{", "process", ".", "exit", "(", "0", ")", ";", "}", "}" ]
Handle process exit based on the existence of error. This is handy for command-line tools to use as the final callback. Exit status code 1 indicates an error, exit status code 0 indicates a success. Error message will be logged to the console. Result object is only used for convenient debugging. @param {Error} err: error object existence indicates the occurence of an error @param {Object} result: result object
[ "Handle", "process", "exit", "based", "on", "the", "existence", "of", "error", ".", "This", "is", "handy", "for", "command", "-", "line", "tools", "to", "use", "as", "the", "final", "callback", ".", "Exit", "status", "code", "1", "indicates", "an", "error", "exit", "status", "code", "0", "indicates", "a", "success", ".", "Error", "message", "will", "be", "logged", "to", "the", "console", ".", "Result", "object", "is", "only", "used", "for", "convenient", "debugging", "." ]
0950716c5a670ca5c73b3d27494b58d5b78f2179
https://github.com/cliffano/bagofcli/blob/0950716c5a670ca5c73b3d27494b58d5b78f2179/lib/bagofcli.js#L284-L291
51,023
cliffano/bagofcli
lib/bagofcli.js
files
function files(items, opts) { opts = opts || {}; var data = []; function addMatch(item) { if (opts.match === undefined || (opts.match && item.match(new RegExp(opts.match)))) { data.push(item); } } items.forEach(function (item) { var stat = fs.statSync(item); if (stat.isFile()) { addMatch(item); } else if (stat.isDirectory()) { var _items = wrench.readdirSyncRecursive(item); _items.forEach(function (_item) { _item = p.join(item, _item); if (fs.statSync(_item).isFile()) { addMatch(_item); } }); } }); return data; }
javascript
function files(items, opts) { opts = opts || {}; var data = []; function addMatch(item) { if (opts.match === undefined || (opts.match && item.match(new RegExp(opts.match)))) { data.push(item); } } items.forEach(function (item) { var stat = fs.statSync(item); if (stat.isFile()) { addMatch(item); } else if (stat.isDirectory()) { var _items = wrench.readdirSyncRecursive(item); _items.forEach(function (_item) { _item = p.join(item, _item); if (fs.statSync(_item).isFile()) { addMatch(_item); } }); } }); return data; }
[ "function", "files", "(", "items", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "data", "=", "[", "]", ";", "function", "addMatch", "(", "item", ")", "{", "if", "(", "opts", ".", "match", "===", "undefined", "||", "(", "opts", ".", "match", "&&", "item", ".", "match", "(", "new", "RegExp", "(", "opts", ".", "match", ")", ")", ")", ")", "{", "data", ".", "push", "(", "item", ")", ";", "}", "}", "items", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "stat", "=", "fs", ".", "statSync", "(", "item", ")", ";", "if", "(", "stat", ".", "isFile", "(", ")", ")", "{", "addMatch", "(", "item", ")", ";", "}", "else", "if", "(", "stat", ".", "isDirectory", "(", ")", ")", "{", "var", "_items", "=", "wrench", ".", "readdirSyncRecursive", "(", "item", ")", ";", "_items", ".", "forEach", "(", "function", "(", "_item", ")", "{", "_item", "=", "p", ".", "join", "(", "item", ",", "_item", ")", ";", "if", "(", "fs", ".", "statSync", "(", "_item", ")", ".", "isFile", "(", ")", ")", "{", "addMatch", "(", "_item", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "return", "data", ";", "}" ]
Get an array of files contained in specified items. When a directory is specified, all files contained within that directory and its sub-directories will be included. @param {Array} items: an array of files and/or directories @param {Object} opts: optional - match: regular expression to match against the file name @return {Array} all files
[ "Get", "an", "array", "of", "files", "contained", "in", "specified", "items", ".", "When", "a", "directory", "is", "specified", "all", "files", "contained", "within", "that", "directory", "and", "its", "sub", "-", "directories", "will", "be", "included", "." ]
0950716c5a670ca5c73b3d27494b58d5b78f2179
https://github.com/cliffano/bagofcli/blob/0950716c5a670ca5c73b3d27494b58d5b78f2179/lib/bagofcli.js#L335-L362
51,024
bcrespy/creenv-canvas
lib/index.js
Canvas
function Canvas (canvasElement, fullWindow, autoInit) { if( !(this instanceof Canvas) ) { return new Canvas.apply(null, arguments); } /** * @type {HTMLCanvasElement} * @public */ this.canvas = null; /** * @type {CanvasRenderingContext2D} * @public */ this.context = null; /** * @type {boolean} * @private */ this.fullWindow = true; /** * if a path has started - reset when drawing a path * @type {boolean} * @private */ this.pathStarted = false; /** * width of the canvas, in px * @type {number} * @public */ this.width = 0; /** * height of the canvas, in px * @type {number} * @public */ this.height = 0; if (canvasElement === undefined) { canvasElement = document.createElement("canvas"); document.body.appendChild(canvasElement); } if (fullWindow === undefined) { fullWindow = true; } if (autoInit === undefined) { autoInit = true; } this.canvas = canvasElement; this.canvas.classList.add("creenv"); this.context = this.canvas.getContext('2d'); this.fullWindow = fullWindow; this.onWindowResizeHandler = this.onWindowResizeHandler.bind(this); if (autoInit) { this.init(); } }
javascript
function Canvas (canvasElement, fullWindow, autoInit) { if( !(this instanceof Canvas) ) { return new Canvas.apply(null, arguments); } /** * @type {HTMLCanvasElement} * @public */ this.canvas = null; /** * @type {CanvasRenderingContext2D} * @public */ this.context = null; /** * @type {boolean} * @private */ this.fullWindow = true; /** * if a path has started - reset when drawing a path * @type {boolean} * @private */ this.pathStarted = false; /** * width of the canvas, in px * @type {number} * @public */ this.width = 0; /** * height of the canvas, in px * @type {number} * @public */ this.height = 0; if (canvasElement === undefined) { canvasElement = document.createElement("canvas"); document.body.appendChild(canvasElement); } if (fullWindow === undefined) { fullWindow = true; } if (autoInit === undefined) { autoInit = true; } this.canvas = canvasElement; this.canvas.classList.add("creenv"); this.context = this.canvas.getContext('2d'); this.fullWindow = fullWindow; this.onWindowResizeHandler = this.onWindowResizeHandler.bind(this); if (autoInit) { this.init(); } }
[ "function", "Canvas", "(", "canvasElement", ",", "fullWindow", ",", "autoInit", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Canvas", ")", ")", "{", "return", "new", "Canvas", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", "/**\n * @type {HTMLCanvasElement}\n * @public\n */", "this", ".", "canvas", "=", "null", ";", "/**\n * @type {CanvasRenderingContext2D}\n * @public\n */", "this", ".", "context", "=", "null", ";", "/**\n * @type {boolean}\n * @private\n */", "this", ".", "fullWindow", "=", "true", ";", "/**\n * if a path has started - reset when drawing a path \n * @type {boolean}\n * @private\n */", "this", ".", "pathStarted", "=", "false", ";", "/**\n * width of the canvas, in px\n * @type {number}\n * @public\n */", "this", ".", "width", "=", "0", ";", "/**\n * height of the canvas, in px\n * @type {number}\n * @public\n */", "this", ".", "height", "=", "0", ";", "if", "(", "canvasElement", "===", "undefined", ")", "{", "canvasElement", "=", "document", ".", "createElement", "(", "\"canvas\"", ")", ";", "document", ".", "body", ".", "appendChild", "(", "canvasElement", ")", ";", "}", "if", "(", "fullWindow", "===", "undefined", ")", "{", "fullWindow", "=", "true", ";", "}", "if", "(", "autoInit", "===", "undefined", ")", "{", "autoInit", "=", "true", ";", "}", "this", ".", "canvas", "=", "canvasElement", ";", "this", ".", "canvas", ".", "classList", ".", "add", "(", "\"creenv\"", ")", ";", "this", ".", "context", "=", "this", ".", "canvas", ".", "getContext", "(", "'2d'", ")", ";", "this", ".", "fullWindow", "=", "fullWindow", ";", "this", ".", "onWindowResizeHandler", "=", "this", ".", "onWindowResizeHandler", ".", "bind", "(", "this", ")", ";", "if", "(", "autoInit", ")", "{", "this", ".", "init", "(", ")", ";", "}", "}" ]
The canvas class provides an interface to work with the html canvas API. Most of the drawing methods of this class directly call the built-in functions, it is just faster to write and think code using this @param {?HTMLCanvasElement} canvasElement the html canvas element, if none is provided, one will be added to the body @param {?boolean} fullWindow (default = false) if the canvas fills the window @param {?boolean} autoInit (default = true) if the canvas will be automatically at the class instanciation. You can set this parameter to false and call the init method manually
[ "The", "canvas", "class", "provides", "an", "interface", "to", "work", "with", "the", "html", "canvas", "API", ".", "Most", "of", "the", "drawing", "methods", "of", "this", "class", "directly", "call", "the", "built", "-", "in", "functions", "it", "is", "just", "faster", "to", "write", "and", "think", "code", "using", "this" ]
7890ca08a9fafebb2cff1ea830d0523ab697dffe
https://github.com/bcrespy/creenv-canvas/blob/7890ca08a9fafebb2cff1ea830d0523ab697dffe/lib/index.js#L25-L93
51,025
bcrespy/creenv-canvas
lib/index.js
function (color) { if (color === undefined) { this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); } else { let fillstyle = this.context.fillStyle; this.fillStyle(color); this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); this.fillStyle(fillstyle); } }
javascript
function (color) { if (color === undefined) { this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); } else { let fillstyle = this.context.fillStyle; this.fillStyle(color); this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); this.fillStyle(fillstyle); } }
[ "function", "(", "color", ")", "{", "if", "(", "color", "===", "undefined", ")", "{", "this", ".", "context", ".", "fillRect", "(", "0", ",", "0", ",", "this", ".", "canvas", ".", "width", ",", "this", ".", "canvas", ".", "height", ")", ";", "}", "else", "{", "let", "fillstyle", "=", "this", ".", "context", ".", "fillStyle", ";", "this", ".", "fillStyle", "(", "color", ")", ";", "this", ".", "context", ".", "fillRect", "(", "0", ",", "0", ",", "this", ".", "canvas", ".", "width", ",", "this", ".", "canvas", ".", "height", ")", ";", "this", ".", "fillStyle", "(", "fillstyle", ")", ";", "}", "}" ]
"Rewriting" some of the most useful context functions so that coding goes faster Fills the canvas with the provided color, in no color is provided fills it with the active color. Fillstyle is reset to its previous value after this function's call @param {Color|string} color either a @creenv/color object or a html compliant string
[ "Rewriting", "some", "of", "the", "most", "useful", "context", "functions", "so", "that", "coding", "goes", "faster", "Fills", "the", "canvas", "with", "the", "provided", "color", "in", "no", "color", "is", "provided", "fills", "it", "with", "the", "active", "color", ".", "Fillstyle", "is", "reset", "to", "its", "previous", "value", "after", "this", "function", "s", "call" ]
7890ca08a9fafebb2cff1ea830d0523ab697dffe
https://github.com/bcrespy/creenv-canvas/blob/7890ca08a9fafebb2cff1ea830d0523ab697dffe/lib/index.js#L128-L137
51,026
bcrespy/creenv-canvas
lib/index.js
function (x, y) { if (!this.pathStarted) { this.context.beginPath(); this.context.moveTo(x,y); this.pathStarted = true; } else { this.context.lineTo(x,y); } }
javascript
function (x, y) { if (!this.pathStarted) { this.context.beginPath(); this.context.moveTo(x,y); this.pathStarted = true; } else { this.context.lineTo(x,y); } }
[ "function", "(", "x", ",", "y", ")", "{", "if", "(", "!", "this", ".", "pathStarted", ")", "{", "this", ".", "context", ".", "beginPath", "(", ")", ";", "this", ".", "context", ".", "moveTo", "(", "x", ",", "y", ")", ";", "this", ".", "pathStarted", "=", "true", ";", "}", "else", "{", "this", ".", "context", ".", "lineTo", "(", "x", ",", "y", ")", ";", "}", "}" ]
Adds a point to the path. If a path has not been started, create one @param {number} x the x coordinate of the point @param {number} y the y coordinate of the point
[ "Adds", "a", "point", "to", "the", "path", ".", "If", "a", "path", "has", "not", "been", "started", "create", "one" ]
7890ca08a9fafebb2cff1ea830d0523ab697dffe
https://github.com/bcrespy/creenv-canvas/blob/7890ca08a9fafebb2cff1ea830d0523ab697dffe/lib/index.js#L201-L209
51,027
inviqa/deck-task-registry
src/styles/buildStyles.js
buildStyles
function buildStyles(conf, undertaker) { // Config that gets passed to node-sass. const sassConfig = conf.themeConfig.sass.nodeSassConf || {}; // If we're in production mode, then compress the output CSS. if (conf.productionMode) { sassConfig.outputStyle = 'compressed'; } // Any PostCSS conf and settings. const postCSSConf = [ autoprefixer({ browsers: conf.themeConfig.sass.browserSupport || 'last 2 versions' }) ]; const sassSrc = path.join(conf.themeConfig.root, conf.themeConfig.sass.src, '**', '*.scss'); const sassDest = path.join(conf.themeConfig.root, conf.themeConfig.sass.dest); // The task itself. return undertaker.src(sassSrc) .pipe(gulpIf(!conf.productionMode, sourcemaps.init())) .pipe(sass(sassConfig).on('error', sass.logError)) .pipe(postcss(postCSSConf)) .pipe(gulpIf(!conf.productionMode, sourcemaps.write('.'))) .pipe(undertaker.dest(sassDest)); }
javascript
function buildStyles(conf, undertaker) { // Config that gets passed to node-sass. const sassConfig = conf.themeConfig.sass.nodeSassConf || {}; // If we're in production mode, then compress the output CSS. if (conf.productionMode) { sassConfig.outputStyle = 'compressed'; } // Any PostCSS conf and settings. const postCSSConf = [ autoprefixer({ browsers: conf.themeConfig.sass.browserSupport || 'last 2 versions' }) ]; const sassSrc = path.join(conf.themeConfig.root, conf.themeConfig.sass.src, '**', '*.scss'); const sassDest = path.join(conf.themeConfig.root, conf.themeConfig.sass.dest); // The task itself. return undertaker.src(sassSrc) .pipe(gulpIf(!conf.productionMode, sourcemaps.init())) .pipe(sass(sassConfig).on('error', sass.logError)) .pipe(postcss(postCSSConf)) .pipe(gulpIf(!conf.productionMode, sourcemaps.write('.'))) .pipe(undertaker.dest(sassDest)); }
[ "function", "buildStyles", "(", "conf", ",", "undertaker", ")", "{", "// Config that gets passed to node-sass.", "const", "sassConfig", "=", "conf", ".", "themeConfig", ".", "sass", ".", "nodeSassConf", "||", "{", "}", ";", "// If we're in production mode, then compress the output CSS.", "if", "(", "conf", ".", "productionMode", ")", "{", "sassConfig", ".", "outputStyle", "=", "'compressed'", ";", "}", "// Any PostCSS conf and settings.", "const", "postCSSConf", "=", "[", "autoprefixer", "(", "{", "browsers", ":", "conf", ".", "themeConfig", ".", "sass", ".", "browserSupport", "||", "'last 2 versions'", "}", ")", "]", ";", "const", "sassSrc", "=", "path", ".", "join", "(", "conf", ".", "themeConfig", ".", "root", ",", "conf", ".", "themeConfig", ".", "sass", ".", "src", ",", "'**'", ",", "'*.scss'", ")", ";", "const", "sassDest", "=", "path", ".", "join", "(", "conf", ".", "themeConfig", ".", "root", ",", "conf", ".", "themeConfig", ".", "sass", ".", "dest", ")", ";", "// The task itself.", "return", "undertaker", ".", "src", "(", "sassSrc", ")", ".", "pipe", "(", "gulpIf", "(", "!", "conf", ".", "productionMode", ",", "sourcemaps", ".", "init", "(", ")", ")", ")", ".", "pipe", "(", "sass", "(", "sassConfig", ")", ".", "on", "(", "'error'", ",", "sass", ".", "logError", ")", ")", ".", "pipe", "(", "postcss", "(", "postCSSConf", ")", ")", ".", "pipe", "(", "gulpIf", "(", "!", "conf", ".", "productionMode", ",", "sourcemaps", ".", "write", "(", "'.'", ")", ")", ")", ".", "pipe", "(", "undertaker", ".", "dest", "(", "sassDest", ")", ")", ";", "}" ]
Build project styles. @param {ConfigParser} conf A configuration parser object. @param {Undertaker} undertaker An Undertaker instance. @returns {Stream} A stream of files.
[ "Build", "project", "styles", "." ]
4c31787b978e9d99a47052e090d4589a50cd3015
https://github.com/inviqa/deck-task-registry/blob/4c31787b978e9d99a47052e090d4589a50cd3015/src/styles/buildStyles.js#L18-L46
51,028
Psychopoulet/node-promfs
lib/extends/_copyFile.js
_copyFile
function _copyFile (origin, target, callback) { if ("undefined" === typeof origin) { throw new ReferenceError("Missing \"origin\" argument"); } else if ("string" !== typeof origin) { throw new TypeError("\"origin\" argument is not a string"); } else if ("" === origin.trim()) { throw new TypeError("\"origin\" argument is empty"); } else if ("undefined" === typeof target) { throw new ReferenceError("Missing \"target\" argument"); } else if ("string" !== typeof target) { throw new TypeError("\"target\" argument is not a string"); } else if ("" === target.trim()) { throw new Error("\"target\" argument is empty"); } else if ("undefined" === typeof callback) { throw new ReferenceError("Missing \"callback\" argument"); } else if ("function" !== typeof callback) { throw new TypeError("\"callback\" argument is not a function"); } else { isFileProm(origin).then((exists) => { return exists ? Promise.resolve() : Promise.reject(new Error("There is no origin file \"" + origin + "\"")); }).then(() => { let error = false; const writeStream = createWriteStream(target).once("error", (_err) => { error = true; writeStream.close(); callback(_err); }).once("close", () => { return error ? null : callback(null); }); createReadStream(origin).once("error", (_err) => { error = true; callback(_err); }).pipe(writeStream); }).catch(callback); } }
javascript
function _copyFile (origin, target, callback) { if ("undefined" === typeof origin) { throw new ReferenceError("Missing \"origin\" argument"); } else if ("string" !== typeof origin) { throw new TypeError("\"origin\" argument is not a string"); } else if ("" === origin.trim()) { throw new TypeError("\"origin\" argument is empty"); } else if ("undefined" === typeof target) { throw new ReferenceError("Missing \"target\" argument"); } else if ("string" !== typeof target) { throw new TypeError("\"target\" argument is not a string"); } else if ("" === target.trim()) { throw new Error("\"target\" argument is empty"); } else if ("undefined" === typeof callback) { throw new ReferenceError("Missing \"callback\" argument"); } else if ("function" !== typeof callback) { throw new TypeError("\"callback\" argument is not a function"); } else { isFileProm(origin).then((exists) => { return exists ? Promise.resolve() : Promise.reject(new Error("There is no origin file \"" + origin + "\"")); }).then(() => { let error = false; const writeStream = createWriteStream(target).once("error", (_err) => { error = true; writeStream.close(); callback(_err); }).once("close", () => { return error ? null : callback(null); }); createReadStream(origin).once("error", (_err) => { error = true; callback(_err); }).pipe(writeStream); }).catch(callback); } }
[ "function", "_copyFile", "(", "origin", ",", "target", ",", "callback", ")", "{", "if", "(", "\"undefined\"", "===", "typeof", "origin", ")", "{", "throw", "new", "ReferenceError", "(", "\"Missing \\\"origin\\\" argument\"", ")", ";", "}", "else", "if", "(", "\"string\"", "!==", "typeof", "origin", ")", "{", "throw", "new", "TypeError", "(", "\"\\\"origin\\\" argument is not a string\"", ")", ";", "}", "else", "if", "(", "\"\"", "===", "origin", ".", "trim", "(", ")", ")", "{", "throw", "new", "TypeError", "(", "\"\\\"origin\\\" argument is empty\"", ")", ";", "}", "else", "if", "(", "\"undefined\"", "===", "typeof", "target", ")", "{", "throw", "new", "ReferenceError", "(", "\"Missing \\\"target\\\" argument\"", ")", ";", "}", "else", "if", "(", "\"string\"", "!==", "typeof", "target", ")", "{", "throw", "new", "TypeError", "(", "\"\\\"target\\\" argument is not a string\"", ")", ";", "}", "else", "if", "(", "\"\"", "===", "target", ".", "trim", "(", ")", ")", "{", "throw", "new", "Error", "(", "\"\\\"target\\\" argument is empty\"", ")", ";", "}", "else", "if", "(", "\"undefined\"", "===", "typeof", "callback", ")", "{", "throw", "new", "ReferenceError", "(", "\"Missing \\\"callback\\\" argument\"", ")", ";", "}", "else", "if", "(", "\"function\"", "!==", "typeof", "callback", ")", "{", "throw", "new", "TypeError", "(", "\"\\\"callback\\\" argument is not a function\"", ")", ";", "}", "else", "{", "isFileProm", "(", "origin", ")", ".", "then", "(", "(", "exists", ")", "=>", "{", "return", "exists", "?", "Promise", ".", "resolve", "(", ")", ":", "Promise", ".", "reject", "(", "new", "Error", "(", "\"There is no origin file \\\"\"", "+", "origin", "+", "\"\\\"\"", ")", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "let", "error", "=", "false", ";", "const", "writeStream", "=", "createWriteStream", "(", "target", ")", ".", "once", "(", "\"error\"", ",", "(", "_err", ")", "=>", "{", "error", "=", "true", ";", "writeStream", ".", "close", "(", ")", ";", "callback", "(", "_err", ")", ";", "}", ")", ".", "once", "(", "\"close\"", ",", "(", ")", "=>", "{", "return", "error", "?", "null", ":", "callback", "(", "null", ")", ";", "}", ")", ";", "createReadStream", "(", "origin", ")", ".", "once", "(", "\"error\"", ",", "(", "_err", ")", "=>", "{", "error", "=", "true", ";", "callback", "(", "_err", ")", ";", "}", ")", ".", "pipe", "(", "writeStream", ")", ";", "}", ")", ".", "catch", "(", "callback", ")", ";", "}", "}" ]
methods Async copyFile @param {string} origin : file to copy @param {string} target : file to copy in @param {function|null} callback : operation's result @returns {void}
[ "methods", "Async", "copyFile" ]
016e272fc58c6ef6eae5ea551a0e8873f0ac20cc
https://github.com/Psychopoulet/node-promfs/blob/016e272fc58c6ef6eae5ea551a0e8873f0ac20cc/lib/extends/_copyFile.js#L22-L75
51,029
aureooms/js-array
lib/reduce/reduce.js
reduce
function reduce(accumulator, iterable, initializer) { var i, len; i = 0; len = iterable.length; if (len === 0) { return initializer; } for (; i < len; ++i) { initializer = accumulator(initializer, iterable[i]); } return initializer; }
javascript
function reduce(accumulator, iterable, initializer) { var i, len; i = 0; len = iterable.length; if (len === 0) { return initializer; } for (; i < len; ++i) { initializer = accumulator(initializer, iterable[i]); } return initializer; }
[ "function", "reduce", "(", "accumulator", ",", "iterable", ",", "initializer", ")", "{", "var", "i", ",", "len", ";", "i", "=", "0", ";", "len", "=", "iterable", ".", "length", ";", "if", "(", "len", "===", "0", ")", "{", "return", "initializer", ";", "}", "for", "(", ";", "i", "<", "len", ";", "++", "i", ")", "{", "initializer", "=", "accumulator", "(", "initializer", ",", "iterable", "[", "i", "]", ")", ";", "}", "return", "initializer", ";", "}" ]
Applies the accumulator function iteratively on the last return value of the accumulator and the next value in the iterable. The initial value is the initializer parameter. /!\ currently only works with an accumulator that is a function object and an array iterable
[ "Applies", "the", "accumulator", "function", "iteratively", "on", "the", "last", "return", "value", "of", "the", "accumulator", "and", "the", "next", "value", "in", "the", "iterable", ".", "The", "initial", "value", "is", "the", "initializer", "parameter", "." ]
b062caceaf08f79cc5f36f6b265e50b984f5e85e
https://github.com/aureooms/js-array/blob/b062caceaf08f79cc5f36f6b265e50b984f5e85e/lib/reduce/reduce.js#L20-L37
51,030
fnogatz/tconsole
lib/index.js
load
function load (location) { var required = requireAll(location) var config = {} for (var key in required) { config[key.replace(/^array\./, 'array:')] = required[key] } var konsole = createConsole(config) return konsole }
javascript
function load (location) { var required = requireAll(location) var config = {} for (var key in required) { config[key.replace(/^array\./, 'array:')] = required[key] } var konsole = createConsole(config) return konsole }
[ "function", "load", "(", "location", ")", "{", "var", "required", "=", "requireAll", "(", "location", ")", "var", "config", "=", "{", "}", "for", "(", "var", "key", "in", "required", ")", "{", "config", "[", "key", ".", "replace", "(", "/", "^array\\.", "/", ",", "'array:'", ")", "]", "=", "required", "[", "key", "]", "}", "var", "konsole", "=", "createConsole", "(", "config", ")", "return", "konsole", "}" ]
Create a console by requiring all renderers in a given location. @param {String} location Filesystem path to use with require-all @return {tconsole}
[ "Create", "a", "console", "by", "requiring", "all", "renderers", "in", "a", "given", "location", "." ]
debcdaf916f7e8f43b35c4c907b585f5c1c69f0f
https://github.com/fnogatz/tconsole/blob/debcdaf916f7e8f43b35c4c907b585f5c1c69f0f/lib/index.js#L58-L66
51,031
fnogatz/tconsole
lib/index.js
combine
function combine () { var config = {} Array.prototype.forEach.call(arguments, function (tconsoleInstance) { mergeObject(config, tconsoleInstance._tconsoleConfig) }) return createConsole(config) }
javascript
function combine () { var config = {} Array.prototype.forEach.call(arguments, function (tconsoleInstance) { mergeObject(config, tconsoleInstance._tconsoleConfig) }) return createConsole(config) }
[ "function", "combine", "(", ")", "{", "var", "config", "=", "{", "}", "Array", ".", "prototype", ".", "forEach", ".", "call", "(", "arguments", ",", "function", "(", "tconsoleInstance", ")", "{", "mergeObject", "(", "config", ",", "tconsoleInstance", ".", "_tconsoleConfig", ")", "}", ")", "return", "createConsole", "(", "config", ")", "}" ]
Combine multiple tconsole instances. @return {tconsole}
[ "Combine", "multiple", "tconsole", "instances", "." ]
debcdaf916f7e8f43b35c4c907b585f5c1c69f0f
https://github.com/fnogatz/tconsole/blob/debcdaf916f7e8f43b35c4c907b585f5c1c69f0f/lib/index.js#L72-L78
51,032
redisjs/jsr-store
lib/type/hash.js
HashMap
function HashMap(source) { this._rtype = TYPE_NAMES.HASH; this.reset(); if(source) { for(var k in source) { this.setKey(k, source[k]); } } }
javascript
function HashMap(source) { this._rtype = TYPE_NAMES.HASH; this.reset(); if(source) { for(var k in source) { this.setKey(k, source[k]); } } }
[ "function", "HashMap", "(", "source", ")", "{", "this", ".", "_rtype", "=", "TYPE_NAMES", ".", "HASH", ";", "this", ".", "reset", "(", ")", ";", "if", "(", "source", ")", "{", "for", "(", "var", "k", "in", "source", ")", "{", "this", ".", "setKey", "(", "k", ",", "source", "[", "k", "]", ")", ";", "}", "}", "}" ]
Represents the hash map type. This is actually a linked list. Keys are stored in an array so that calls to retrieve the keys do not need to call Object.keys(). Key list retrieval will be fast, sacrificing memory for less cpu under the assumption that it is easier to supply more memory and harder to supply more cpu cycles given that this is designed to run within a single process work cannot be split between multiple cores. Maintaining a list of keys also allows commands such as RANDOMKEY to execute with an O(1) time complexity.
[ "Represents", "the", "hash", "map", "type", "." ]
b2b5c5b0347819f8a388b5d67e121ee8d73f328c
https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/type/hash.js#L21-L29
51,033
redisjs/jsr-store
lib/type/hash.js
setExpiry
function setExpiry(key, ms, req) { var rval = this.getRawKey(key); if(rval === undefined) return 0; // expiry is in the past or now, delete immediately // but return 1 to indicate the expiry was set if(ms <= Date.now()) { this.delKey(key, req); return 1; } if(!this._expires[key]) { this._ekeys.push(key); } this._expires[key] = ms; rval.e = ms; return 1; }
javascript
function setExpiry(key, ms, req) { var rval = this.getRawKey(key); if(rval === undefined) return 0; // expiry is in the past or now, delete immediately // but return 1 to indicate the expiry was set if(ms <= Date.now()) { this.delKey(key, req); return 1; } if(!this._expires[key]) { this._ekeys.push(key); } this._expires[key] = ms; rval.e = ms; return 1; }
[ "function", "setExpiry", "(", "key", ",", "ms", ",", "req", ")", "{", "var", "rval", "=", "this", ".", "getRawKey", "(", "key", ")", ";", "if", "(", "rval", "===", "undefined", ")", "return", "0", ";", "// expiry is in the past or now, delete immediately", "// but return 1 to indicate the expiry was set", "if", "(", "ms", "<=", "Date", ".", "now", "(", ")", ")", "{", "this", ".", "delKey", "(", "key", ",", "req", ")", ";", "return", "1", ";", "}", "if", "(", "!", "this", ".", "_expires", "[", "key", "]", ")", "{", "this", ".", "_ekeys", ".", "push", "(", "key", ")", ";", "}", "this", ".", "_expires", "[", "key", "]", "=", "ms", ";", "rval", ".", "e", "=", "ms", ";", "return", "1", ";", "}" ]
Set expiry on a key as a unix timestamp in ms.
[ "Set", "expiry", "on", "a", "key", "as", "a", "unix", "timestamp", "in", "ms", "." ]
b2b5c5b0347819f8a388b5d67e121ee8d73f328c
https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/type/hash.js#L128-L143
51,034
redisjs/jsr-store
lib/type/hash.js
delExpiry
function delExpiry(key, req) { var rval = this.getRawKey(key); if(rval === undefined || rval.e === undefined) return 0; // the code flow ensures we have a valid // index into the expiring keys array this._ekeys.splice(ArrayIndex.indexOf(key, this._ekeys), 1); delete this._expires[key]; delete rval.e; return 1; }
javascript
function delExpiry(key, req) { var rval = this.getRawKey(key); if(rval === undefined || rval.e === undefined) return 0; // the code flow ensures we have a valid // index into the expiring keys array this._ekeys.splice(ArrayIndex.indexOf(key, this._ekeys), 1); delete this._expires[key]; delete rval.e; return 1; }
[ "function", "delExpiry", "(", "key", ",", "req", ")", "{", "var", "rval", "=", "this", ".", "getRawKey", "(", "key", ")", ";", "if", "(", "rval", "===", "undefined", "||", "rval", ".", "e", "===", "undefined", ")", "return", "0", ";", "// the code flow ensures we have a valid", "// index into the expiring keys array", "this", ".", "_ekeys", ".", "splice", "(", "ArrayIndex", ".", "indexOf", "(", "key", ",", "this", ".", "_ekeys", ")", ",", "1", ")", ";", "delete", "this", ".", "_expires", "[", "key", "]", ";", "delete", "rval", ".", "e", ";", "return", "1", ";", "}" ]
Delete expiry on a key.
[ "Delete", "expiry", "on", "a", "key", "." ]
b2b5c5b0347819f8a388b5d67e121ee8d73f328c
https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/type/hash.js#L148-L157
51,035
redisjs/jsr-store
lib/type/hash.js
delExpiredKeys
function delExpiredKeys(num, threshold) { function removeExpiredKeys(count) { if(!this._ekeys.length) return 0; var num = num || 100 , threshold = threshold || 25 , count = count || 0 , i , key , ind; for(i = 0;i < num;i++) { ind = Math.floor(Math.random() * this._ekeys.length); key = this._ekeys[ind]; if(this._expires[key] <= Date.now()) { this.emit('expired', key); this.delKey(key); count++; } } if(count >= threshold) { setImmediate(removeExpiredKeys); } return count; } removeExpiredKeys = removeExpiredKeys.bind(this); return removeExpiredKeys(); }
javascript
function delExpiredKeys(num, threshold) { function removeExpiredKeys(count) { if(!this._ekeys.length) return 0; var num = num || 100 , threshold = threshold || 25 , count = count || 0 , i , key , ind; for(i = 0;i < num;i++) { ind = Math.floor(Math.random() * this._ekeys.length); key = this._ekeys[ind]; if(this._expires[key] <= Date.now()) { this.emit('expired', key); this.delKey(key); count++; } } if(count >= threshold) { setImmediate(removeExpiredKeys); } return count; } removeExpiredKeys = removeExpiredKeys.bind(this); return removeExpiredKeys(); }
[ "function", "delExpiredKeys", "(", "num", ",", "threshold", ")", "{", "function", "removeExpiredKeys", "(", "count", ")", "{", "if", "(", "!", "this", ".", "_ekeys", ".", "length", ")", "return", "0", ";", "var", "num", "=", "num", "||", "100", ",", "threshold", "=", "threshold", "||", "25", ",", "count", "=", "count", "||", "0", ",", "i", ",", "key", ",", "ind", ";", "for", "(", "i", "=", "0", ";", "i", "<", "num", ";", "i", "++", ")", "{", "ind", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "this", ".", "_ekeys", ".", "length", ")", ";", "key", "=", "this", ".", "_ekeys", "[", "ind", "]", ";", "if", "(", "this", ".", "_expires", "[", "key", "]", "<=", "Date", ".", "now", "(", ")", ")", "{", "this", ".", "emit", "(", "'expired'", ",", "key", ")", ";", "this", ".", "delKey", "(", "key", ")", ";", "count", "++", ";", "}", "}", "if", "(", "count", ">=", "threshold", ")", "{", "setImmediate", "(", "removeExpiredKeys", ")", ";", "}", "return", "count", ";", "}", "removeExpiredKeys", "=", "removeExpiredKeys", ".", "bind", "(", "this", ")", ";", "return", "removeExpiredKeys", "(", ")", ";", "}" ]
Passive expiry. Picks 100 keys at random from the list of expired keys and if the number of expired keys exceeds 25 continue to delete expired keys.
[ "Passive", "expiry", "." ]
b2b5c5b0347819f8a388b5d67e121ee8d73f328c
https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/type/hash.js#L231-L261
51,036
redisjs/jsr-store
lib/type/hash.js
getValueBuffer
function getValueBuffer(key, req, stringify) { var val = this.getKey(key, req); // should have buffer, string or number if(val !== undefined) { if(typeof val === 'number' && !stringify) val = new Buffer([val]); val = (val instanceof Buffer) ? val : new Buffer('' + val); } return val; }
javascript
function getValueBuffer(key, req, stringify) { var val = this.getKey(key, req); // should have buffer, string or number if(val !== undefined) { if(typeof val === 'number' && !stringify) val = new Buffer([val]); val = (val instanceof Buffer) ? val : new Buffer('' + val); } return val; }
[ "function", "getValueBuffer", "(", "key", ",", "req", ",", "stringify", ")", "{", "var", "val", "=", "this", ".", "getKey", "(", "key", ",", "req", ")", ";", "// should have buffer, string or number", "if", "(", "val", "!==", "undefined", ")", "{", "if", "(", "typeof", "val", "===", "'number'", "&&", "!", "stringify", ")", "val", "=", "new", "Buffer", "(", "[", "val", "]", ")", ";", "val", "=", "(", "val", "instanceof", "Buffer", ")", "?", "val", ":", "new", "Buffer", "(", "''", "+", "val", ")", ";", "}", "return", "val", ";", "}" ]
Get the value for a key as a buffer regardless of it being a string, number or existing buffer. @param key The key. @param req The request object. @param stringify Convert numbers to strings then buffer.
[ "Get", "the", "value", "for", "a", "key", "as", "a", "buffer", "regardless", "of", "it", "being", "a", "string", "number", "or", "existing", "buffer", "." ]
b2b5c5b0347819f8a388b5d67e121ee8d73f328c
https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/type/hash.js#L288-L296
51,037
bholloway/browserify-anonymous-labeler
lib/interleave.js
interleave
function interleave(additional) { return function reduce(reduced, value, i) { if (i === 0) { reduced.push(value); } else { reduced.push(additional, value); } return reduced; } }
javascript
function interleave(additional) { return function reduce(reduced, value, i) { if (i === 0) { reduced.push(value); } else { reduced.push(additional, value); } return reduced; } }
[ "function", "interleave", "(", "additional", ")", "{", "return", "function", "reduce", "(", "reduced", ",", "value", ",", "i", ")", "{", "if", "(", "i", "===", "0", ")", "{", "reduced", ".", "push", "(", "value", ")", ";", "}", "else", "{", "reduced", ".", "push", "(", "additional", ",", "value", ")", ";", "}", "return", "reduced", ";", "}", "}" ]
Get a reduce method that interleaves the given additional value between each existing element in an array. @param {*} additional The value to interleave @returns {function} A method that reduces an array a returns an interleaved array
[ "Get", "a", "reduce", "method", "that", "interleaves", "the", "given", "additional", "value", "between", "each", "existing", "element", "in", "an", "array", "." ]
651b124eefe8d1a567b2a03a0b8a3dfea87c2703
https://github.com/bholloway/browserify-anonymous-labeler/blob/651b124eefe8d1a567b2a03a0b8a3dfea87c2703/lib/interleave.js#L8-L17
51,038
oconnore/harmony-enumerables
collections.js
Node
function Node(value, prev, next) { this.value = value; this.prev = prev; this.next = next; }
javascript
function Node(value, prev, next) { this.value = value; this.prev = prev; this.next = next; }
[ "function", "Node", "(", "value", ",", "prev", ",", "next", ")", "{", "this", ".", "value", "=", "value", ";", "this", ".", "prev", "=", "prev", ";", "this", ".", "next", "=", "next", ";", "}" ]
A doubly linked node
[ "A", "doubly", "linked", "node" ]
77a0a6b6726bcbb877c494f6c14f175de7225699
https://github.com/oconnore/harmony-enumerables/blob/77a0a6b6726bcbb877c494f6c14f175de7225699/collections.js#L68-L72
51,039
oconnore/harmony-enumerables
collections.js
Sequence
function Sequence(iterable) { this.sequence = null; this._size = 0; this.nodeMap = new rMap(); if (iterable) { if (typeof iterable.length === 'number') { for (var i = 0; i < iterable.length; i++) { this.add.apply(this, iterable[i]); } } else if (typeof iterable.entries === 'function') { var it = iterable.entries(); while (!it.done) { var tmp = it.next(); this.add.apply(this, tmp);//it.next()); } } } }
javascript
function Sequence(iterable) { this.sequence = null; this._size = 0; this.nodeMap = new rMap(); if (iterable) { if (typeof iterable.length === 'number') { for (var i = 0; i < iterable.length; i++) { this.add.apply(this, iterable[i]); } } else if (typeof iterable.entries === 'function') { var it = iterable.entries(); while (!it.done) { var tmp = it.next(); this.add.apply(this, tmp);//it.next()); } } } }
[ "function", "Sequence", "(", "iterable", ")", "{", "this", ".", "sequence", "=", "null", ";", "this", ".", "_size", "=", "0", ";", "this", ".", "nodeMap", "=", "new", "rMap", "(", ")", ";", "if", "(", "iterable", ")", "{", "if", "(", "typeof", "iterable", ".", "length", "===", "'number'", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "iterable", ".", "length", ";", "i", "++", ")", "{", "this", ".", "add", ".", "apply", "(", "this", ",", "iterable", "[", "i", "]", ")", ";", "}", "}", "else", "if", "(", "typeof", "iterable", ".", "entries", "===", "'function'", ")", "{", "var", "it", "=", "iterable", ".", "entries", "(", ")", ";", "while", "(", "!", "it", ".", "done", ")", "{", "var", "tmp", "=", "it", ".", "next", "(", ")", ";", "this", ".", "add", ".", "apply", "(", "this", ",", "tmp", ")", ";", "//it.next());", "}", "}", "}", "}" ]
A Sequence is a doubly linked list where the conses are also stored in a Map and accessible by a key.
[ "A", "Sequence", "is", "a", "doubly", "linked", "list", "where", "the", "conses", "are", "also", "stored", "in", "a", "Map", "and", "accessible", "by", "a", "key", "." ]
77a0a6b6726bcbb877c494f6c14f175de7225699
https://github.com/oconnore/harmony-enumerables/blob/77a0a6b6726bcbb877c494f6c14f175de7225699/collections.js#L99-L116
51,040
oconnore/harmony-enumerables
collections.js
bindHelper
function bindHelper(fn) { return function() { var p = priv.get(this); return fn.apply(p.sequence, Array.prototype.slice.call(arguments)); } }
javascript
function bindHelper(fn) { return function() { var p = priv.get(this); return fn.apply(p.sequence, Array.prototype.slice.call(arguments)); } }
[ "function", "bindHelper", "(", "fn", ")", "{", "return", "function", "(", ")", "{", "var", "p", "=", "priv", ".", "get", "(", "this", ")", ";", "return", "fn", ".", "apply", "(", "p", ".", "sequence", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ";", "}", "}" ]
bindHelper calls a function on our private internal Sequence. It is used by EnumMap and EnumSet to delegate to the private sequence object.
[ "bindHelper", "calls", "a", "function", "on", "our", "private", "internal", "Sequence", ".", "It", "is", "used", "by", "EnumMap", "and", "EnumSet", "to", "delegate", "to", "the", "private", "sequence", "object", "." ]
77a0a6b6726bcbb877c494f6c14f175de7225699
https://github.com/oconnore/harmony-enumerables/blob/77a0a6b6726bcbb877c494f6c14f175de7225699/collections.js#L189-L194
51,041
oconnore/harmony-enumerables
collections.js
EnumMap
function EnumMap(iter) { var p = {}; priv.set(this, p); var newIter = iter; if(iter && typeof iter.entries === 'function') { if (iter instanceof EnumSet) { newIter = { entries: function() { var pi = priv.get(iter); return new Iterator(pi.sequence.sequence, 0); } }; } } p.sequence = new Sequence(newIter); }
javascript
function EnumMap(iter) { var p = {}; priv.set(this, p); var newIter = iter; if(iter && typeof iter.entries === 'function') { if (iter instanceof EnumSet) { newIter = { entries: function() { var pi = priv.get(iter); return new Iterator(pi.sequence.sequence, 0); } }; } } p.sequence = new Sequence(newIter); }
[ "function", "EnumMap", "(", "iter", ")", "{", "var", "p", "=", "{", "}", ";", "priv", ".", "set", "(", "this", ",", "p", ")", ";", "var", "newIter", "=", "iter", ";", "if", "(", "iter", "&&", "typeof", "iter", ".", "entries", "===", "'function'", ")", "{", "if", "(", "iter", "instanceof", "EnumSet", ")", "{", "newIter", "=", "{", "entries", ":", "function", "(", ")", "{", "var", "pi", "=", "priv", ".", "get", "(", "iter", ")", ";", "return", "new", "Iterator", "(", "pi", ".", "sequence", ".", "sequence", ",", "0", ")", ";", "}", "}", ";", "}", "}", "p", ".", "sequence", "=", "new", "Sequence", "(", "newIter", ")", ";", "}" ]
This is our poly-filled Map, which we can enumerate using Sequence
[ "This", "is", "our", "poly", "-", "filled", "Map", "which", "we", "can", "enumerate", "using", "Sequence" ]
77a0a6b6726bcbb877c494f6c14f175de7225699
https://github.com/oconnore/harmony-enumerables/blob/77a0a6b6726bcbb877c494f6c14f175de7225699/collections.js#L197-L212
51,042
oconnore/harmony-enumerables
collections.js
EnumSet
function EnumSet(iter) { var p = {}; priv.set(this, p); var newIter = iter; if (Array.isArray(iter)) { newIter = Array.prototype.map.call(iter, function(x) { return [x, x]; }); } else if(iter && typeof iter.entries === 'function') { if (iter instanceof EnumMap) { newIter = { entries: function() { var pi = priv.get(iter); return new Iterator(pi.sequence.sequence, undefined, function(x) { return [x, x]; }); } }; } } p.sequence = new Sequence(newIter); }
javascript
function EnumSet(iter) { var p = {}; priv.set(this, p); var newIter = iter; if (Array.isArray(iter)) { newIter = Array.prototype.map.call(iter, function(x) { return [x, x]; }); } else if(iter && typeof iter.entries === 'function') { if (iter instanceof EnumMap) { newIter = { entries: function() { var pi = priv.get(iter); return new Iterator(pi.sequence.sequence, undefined, function(x) { return [x, x]; }); } }; } } p.sequence = new Sequence(newIter); }
[ "function", "EnumSet", "(", "iter", ")", "{", "var", "p", "=", "{", "}", ";", "priv", ".", "set", "(", "this", ",", "p", ")", ";", "var", "newIter", "=", "iter", ";", "if", "(", "Array", ".", "isArray", "(", "iter", ")", ")", "{", "newIter", "=", "Array", ".", "prototype", ".", "map", ".", "call", "(", "iter", ",", "function", "(", "x", ")", "{", "return", "[", "x", ",", "x", "]", ";", "}", ")", ";", "}", "else", "if", "(", "iter", "&&", "typeof", "iter", ".", "entries", "===", "'function'", ")", "{", "if", "(", "iter", "instanceof", "EnumMap", ")", "{", "newIter", "=", "{", "entries", ":", "function", "(", ")", "{", "var", "pi", "=", "priv", ".", "get", "(", "iter", ")", ";", "return", "new", "Iterator", "(", "pi", ".", "sequence", ".", "sequence", ",", "undefined", ",", "function", "(", "x", ")", "{", "return", "[", "x", ",", "x", "]", ";", "}", ")", ";", "}", "}", ";", "}", "}", "p", ".", "sequence", "=", "new", "Sequence", "(", "newIter", ")", ";", "}" ]
This is our poly-filled Set, which we can enumerate using Sequence
[ "This", "is", "our", "poly", "-", "filled", "Set", "which", "we", "can", "enumerate", "using", "Sequence" ]
77a0a6b6726bcbb877c494f6c14f175de7225699
https://github.com/oconnore/harmony-enumerables/blob/77a0a6b6726bcbb877c494f6c14f175de7225699/collections.js#L235-L256
51,043
freshtilledsoil/FTS-grunt
Gruntfile.js
loadConfig
function loadConfig(path) { var glob = require('glob'); var object = {}; var key; glob.sync('*', {cwd: path}).forEach(function(option) { key = option.replace(/\.js$/,''); object[key] = require(path + option); }); return object; }
javascript
function loadConfig(path) { var glob = require('glob'); var object = {}; var key; glob.sync('*', {cwd: path}).forEach(function(option) { key = option.replace(/\.js$/,''); object[key] = require(path + option); }); return object; }
[ "function", "loadConfig", "(", "path", ")", "{", "var", "glob", "=", "require", "(", "'glob'", ")", ";", "var", "object", "=", "{", "}", ";", "var", "key", ";", "glob", ".", "sync", "(", "'*'", ",", "{", "cwd", ":", "path", "}", ")", ".", "forEach", "(", "function", "(", "option", ")", "{", "key", "=", "option", ".", "replace", "(", "/", "\\.js$", "/", ",", "''", ")", ";", "object", "[", "key", "]", "=", "require", "(", "path", "+", "option", ")", ";", "}", ")", ";", "return", "object", ";", "}" ]
Utility to load the different option files based on their names
[ "Utility", "to", "load", "the", "different", "option", "files", "based", "on", "their", "names" ]
955bafdffb57d7d2df08b6fdf67b56c75bb6c4ce
https://github.com/freshtilledsoil/FTS-grunt/blob/955bafdffb57d7d2df08b6fdf67b56c75bb6c4ce/Gruntfile.js#L5-L16
51,044
gethuman/pancakes-recipe
batch/db.clear/db.clear.batch.js
clearDatabase
function clearDatabase() { var promises = []; _.each(resources, function (resource) { var service = pancakes.getService(resource.name); if (service.removePermanently) { log.info('purging ' + resource.name); promises.push(service.removePermanently({ where: {}, multi: true })); } }); return Q.all(promises); }
javascript
function clearDatabase() { var promises = []; _.each(resources, function (resource) { var service = pancakes.getService(resource.name); if (service.removePermanently) { log.info('purging ' + resource.name); promises.push(service.removePermanently({ where: {}, multi: true })); } }); return Q.all(promises); }
[ "function", "clearDatabase", "(", ")", "{", "var", "promises", "=", "[", "]", ";", "_", ".", "each", "(", "resources", ",", "function", "(", "resource", ")", "{", "var", "service", "=", "pancakes", ".", "getService", "(", "resource", ".", "name", ")", ";", "if", "(", "service", ".", "removePermanently", ")", "{", "log", ".", "info", "(", "'purging '", "+", "resource", ".", "name", ")", ";", "promises", ".", "push", "(", "service", ".", "removePermanently", "(", "{", "where", ":", "{", "}", ",", "multi", ":", "true", "}", ")", ")", ";", "}", "}", ")", ";", "return", "Q", ".", "all", "(", "promises", ")", ";", "}" ]
Purge everything in the database
[ "Purge", "everything", "in", "the", "database" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/batch/db.clear/db.clear.batch.js#L27-L39
51,045
gethuman/pancakes-recipe
batch/db.clear/db.clear.batch.js
confirmClear
function confirmClear() { var promptSchema = { properties: { confirm: { description: 'Delete everything in the ' + config.env.toUpperCase() + ' database? (y or n) ', pattern: /^[yn]$/, message: 'Please respond with y or n. ', required: true } } }; // for safety reasons, we can't use this in production if (config.env === 'production') { return Q.reject('purging is NOT available for prod.'); } // prompt the user to confirm they are deleting everything in the database var deferred = Q.defer(); prompt.start(); prompt.get(promptSchema, function (err, result) { if (err) { deferred.reject(err); } else if (result.confirm !== 'y') { log.info('purge cancelled'); deferred.resolve(false); } // else user confirmed deletion so do it else { deferred.resolve(true); } }); return deferred.promise; }
javascript
function confirmClear() { var promptSchema = { properties: { confirm: { description: 'Delete everything in the ' + config.env.toUpperCase() + ' database? (y or n) ', pattern: /^[yn]$/, message: 'Please respond with y or n. ', required: true } } }; // for safety reasons, we can't use this in production if (config.env === 'production') { return Q.reject('purging is NOT available for prod.'); } // prompt the user to confirm they are deleting everything in the database var deferred = Q.defer(); prompt.start(); prompt.get(promptSchema, function (err, result) { if (err) { deferred.reject(err); } else if (result.confirm !== 'y') { log.info('purge cancelled'); deferred.resolve(false); } // else user confirmed deletion so do it else { deferred.resolve(true); } }); return deferred.promise; }
[ "function", "confirmClear", "(", ")", "{", "var", "promptSchema", "=", "{", "properties", ":", "{", "confirm", ":", "{", "description", ":", "'Delete everything in the '", "+", "config", ".", "env", ".", "toUpperCase", "(", ")", "+", "' database? (y or n) '", ",", "pattern", ":", "/", "^[yn]$", "/", ",", "message", ":", "'Please respond with y or n. '", ",", "required", ":", "true", "}", "}", "}", ";", "// for safety reasons, we can't use this in production", "if", "(", "config", ".", "env", "===", "'production'", ")", "{", "return", "Q", ".", "reject", "(", "'purging is NOT available for prod.'", ")", ";", "}", "// prompt the user to confirm they are deleting everything in the database", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "prompt", ".", "start", "(", ")", ";", "prompt", ".", "get", "(", "promptSchema", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "deferred", ".", "reject", "(", "err", ")", ";", "}", "else", "if", "(", "result", ".", "confirm", "!==", "'y'", ")", "{", "log", ".", "info", "(", "'purge cancelled'", ")", ";", "deferred", ".", "resolve", "(", "false", ")", ";", "}", "// else user confirmed deletion so do it", "else", "{", "deferred", ".", "resolve", "(", "true", ")", ";", "}", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Confirm with the user that they definitately want to purge @returns {*}
[ "Confirm", "with", "the", "user", "that", "they", "definitately", "want", "to", "purge" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/batch/db.clear/db.clear.batch.js#L45-L80
51,046
blixt/js-workerproxy
index.js
createWorkerProxy
function createWorkerProxy(workersOrFunctions, opt_options) { var options = { // Automatically call the callback after a call if the return value is not // undefined. autoCallback: false, // Catch errors and automatically respond with an error callback. Off by // default since it breaks standard behavior. catchErrors: false, // A list of functions that can be called. This list will be used to make // the proxy functions available when Proxy is not supported. Note that // this is generally not needed since the worker will also publish its // known functions. functionNames: [], // Call console.time and console.timeEnd for calls sent though the proxy. timeCalls: false }; if (opt_options) { for (var key in opt_options) { if (!(key in options)) continue; options[key] = opt_options[key]; } } Object.freeze(options); // Ensure that we have an array of workers (even if only using one worker). if (typeof Worker != 'undefined' && (workersOrFunctions instanceof Worker)) { workersOrFunctions = [workersOrFunctions]; } if (Array.isArray(workersOrFunctions)) { return sendCallsToWorker(workersOrFunctions, options); } else { receiveCallsFromOwner(workersOrFunctions, options); } }
javascript
function createWorkerProxy(workersOrFunctions, opt_options) { var options = { // Automatically call the callback after a call if the return value is not // undefined. autoCallback: false, // Catch errors and automatically respond with an error callback. Off by // default since it breaks standard behavior. catchErrors: false, // A list of functions that can be called. This list will be used to make // the proxy functions available when Proxy is not supported. Note that // this is generally not needed since the worker will also publish its // known functions. functionNames: [], // Call console.time and console.timeEnd for calls sent though the proxy. timeCalls: false }; if (opt_options) { for (var key in opt_options) { if (!(key in options)) continue; options[key] = opt_options[key]; } } Object.freeze(options); // Ensure that we have an array of workers (even if only using one worker). if (typeof Worker != 'undefined' && (workersOrFunctions instanceof Worker)) { workersOrFunctions = [workersOrFunctions]; } if (Array.isArray(workersOrFunctions)) { return sendCallsToWorker(workersOrFunctions, options); } else { receiveCallsFromOwner(workersOrFunctions, options); } }
[ "function", "createWorkerProxy", "(", "workersOrFunctions", ",", "opt_options", ")", "{", "var", "options", "=", "{", "// Automatically call the callback after a call if the return value is not", "// undefined.", "autoCallback", ":", "false", ",", "// Catch errors and automatically respond with an error callback. Off by", "// default since it breaks standard behavior.", "catchErrors", ":", "false", ",", "// A list of functions that can be called. This list will be used to make", "// the proxy functions available when Proxy is not supported. Note that", "// this is generally not needed since the worker will also publish its", "// known functions.", "functionNames", ":", "[", "]", ",", "// Call console.time and console.timeEnd for calls sent though the proxy.", "timeCalls", ":", "false", "}", ";", "if", "(", "opt_options", ")", "{", "for", "(", "var", "key", "in", "opt_options", ")", "{", "if", "(", "!", "(", "key", "in", "options", ")", ")", "continue", ";", "options", "[", "key", "]", "=", "opt_options", "[", "key", "]", ";", "}", "}", "Object", ".", "freeze", "(", "options", ")", ";", "// Ensure that we have an array of workers (even if only using one worker).", "if", "(", "typeof", "Worker", "!=", "'undefined'", "&&", "(", "workersOrFunctions", "instanceof", "Worker", ")", ")", "{", "workersOrFunctions", "=", "[", "workersOrFunctions", "]", ";", "}", "if", "(", "Array", ".", "isArray", "(", "workersOrFunctions", ")", ")", "{", "return", "sendCallsToWorker", "(", "workersOrFunctions", ",", "options", ")", ";", "}", "else", "{", "receiveCallsFromOwner", "(", "workersOrFunctions", ",", "options", ")", ";", "}", "}" ]
Call this function with either a Worker instance, a list of them, or a map of functions that can be called inside the worker.
[ "Call", "this", "function", "with", "either", "a", "Worker", "instance", "a", "list", "of", "them", "or", "a", "map", "of", "functions", "that", "can", "be", "called", "inside", "the", "worker", "." ]
8e7649e1392a1e0d42e0fabce6245916fdc8fb01
https://github.com/blixt/js-workerproxy/blob/8e7649e1392a1e0d42e0fabce6245916fdc8fb01/index.js#L223-L258
51,047
sogko/pecker
lib/manifest.js
Manifest
function Manifest(options) { this.options = options; this.destDir = options.destDir || process.cwd(); this.content = {}; this.filePath = path.join(this.destDir, MANIFEST_FILENAME); // get or create manifest content this.content = this.read(); }
javascript
function Manifest(options) { this.options = options; this.destDir = options.destDir || process.cwd(); this.content = {}; this.filePath = path.join(this.destDir, MANIFEST_FILENAME); // get or create manifest content this.content = this.read(); }
[ "function", "Manifest", "(", "options", ")", "{", "this", ".", "options", "=", "options", ";", "this", ".", "destDir", "=", "options", ".", "destDir", "||", "process", ".", "cwd", "(", ")", ";", "this", ".", "content", "=", "{", "}", ";", "this", ".", "filePath", "=", "path", ".", "join", "(", "this", ".", "destDir", ",", "MANIFEST_FILENAME", ")", ";", "// get or create manifest content", "this", ".", "content", "=", "this", ".", "read", "(", ")", ";", "}" ]
Pecker.Manifest class @param options @constructor
[ "Pecker", ".", "Manifest", "class" ]
fc84cbcd06176e74a15d4e49cc366dbd0a7041b0
https://github.com/sogko/pecker/blob/fc84cbcd06176e74a15d4e49cc366dbd0a7041b0/lib/manifest.js#L22-L30
51,048
Runnable/cluster-man
index.js
ClusterManager
function ClusterManager(opts) { if (isFunction(opts)) { opts = { worker: opts }; } this.options = opts || {}; this.givenNumWorkers = exists(this.options.numWorkers) || exists(process.env.CLUSTER_WORKERS); defaults(this.options, { debugScope: process.env.CLUSTER_DEBUG || 'cluster-man', master: noop, numWorkers: process.env.CLUSTER_WORKERS || os.cpus().length, killOnError: true, beforeExit: function (err, done) { done(); } }); this._addLogger('info', [this.options.debugScope, 'info'].join(':')); this._addLogger('warning', [this.options.debugScope, 'warning'].join(':')); this._addLogger('error', [this.options.debugScope, 'error'].join(':')); if (!this.options.worker || !isFunction(this.options.worker)) { throw new Error('Cluster must be provided with a worker closure.'); } if (!isFunction(this.options.beforeExit)) { this.log.warning('Before exit callback is not a function, removing.'); this.options.beforeExit = noop; } this.workers = []; // This is here to expose the cluster without having to re-require in the // script that uses cluster-man this.cluster = cluster; }
javascript
function ClusterManager(opts) { if (isFunction(opts)) { opts = { worker: opts }; } this.options = opts || {}; this.givenNumWorkers = exists(this.options.numWorkers) || exists(process.env.CLUSTER_WORKERS); defaults(this.options, { debugScope: process.env.CLUSTER_DEBUG || 'cluster-man', master: noop, numWorkers: process.env.CLUSTER_WORKERS || os.cpus().length, killOnError: true, beforeExit: function (err, done) { done(); } }); this._addLogger('info', [this.options.debugScope, 'info'].join(':')); this._addLogger('warning', [this.options.debugScope, 'warning'].join(':')); this._addLogger('error', [this.options.debugScope, 'error'].join(':')); if (!this.options.worker || !isFunction(this.options.worker)) { throw new Error('Cluster must be provided with a worker closure.'); } if (!isFunction(this.options.beforeExit)) { this.log.warning('Before exit callback is not a function, removing.'); this.options.beforeExit = noop; } this.workers = []; // This is here to expose the cluster without having to re-require in the // script that uses cluster-man this.cluster = cluster; }
[ "function", "ClusterManager", "(", "opts", ")", "{", "if", "(", "isFunction", "(", "opts", ")", ")", "{", "opts", "=", "{", "worker", ":", "opts", "}", ";", "}", "this", ".", "options", "=", "opts", "||", "{", "}", ";", "this", ".", "givenNumWorkers", "=", "exists", "(", "this", ".", "options", ".", "numWorkers", ")", "||", "exists", "(", "process", ".", "env", ".", "CLUSTER_WORKERS", ")", ";", "defaults", "(", "this", ".", "options", ",", "{", "debugScope", ":", "process", ".", "env", ".", "CLUSTER_DEBUG", "||", "'cluster-man'", ",", "master", ":", "noop", ",", "numWorkers", ":", "process", ".", "env", ".", "CLUSTER_WORKERS", "||", "os", ".", "cpus", "(", ")", ".", "length", ",", "killOnError", ":", "true", ",", "beforeExit", ":", "function", "(", "err", ",", "done", ")", "{", "done", "(", ")", ";", "}", "}", ")", ";", "this", ".", "_addLogger", "(", "'info'", ",", "[", "this", ".", "options", ".", "debugScope", ",", "'info'", "]", ".", "join", "(", "':'", ")", ")", ";", "this", ".", "_addLogger", "(", "'warning'", ",", "[", "this", ".", "options", ".", "debugScope", ",", "'warning'", "]", ".", "join", "(", "':'", ")", ")", ";", "this", ".", "_addLogger", "(", "'error'", ",", "[", "this", ".", "options", ".", "debugScope", ",", "'error'", "]", ".", "join", "(", "':'", ")", ")", ";", "if", "(", "!", "this", ".", "options", ".", "worker", "||", "!", "isFunction", "(", "this", ".", "options", ".", "worker", ")", ")", "{", "throw", "new", "Error", "(", "'Cluster must be provided with a worker closure.'", ")", ";", "}", "if", "(", "!", "isFunction", "(", "this", ".", "options", ".", "beforeExit", ")", ")", "{", "this", ".", "log", ".", "warning", "(", "'Before exit callback is not a function, removing.'", ")", ";", "this", ".", "options", ".", "beforeExit", "=", "noop", ";", "}", "this", ".", "workers", "=", "[", "]", ";", "// This is here to expose the cluster without having to re-require in the", "// script that uses cluster-man", "this", ".", "cluster", "=", "cluster", ";", "}" ]
Utility class for creating new server clusters. @example var ClusterManager = require('cluster-man'); var server = require('./lib/server'); // Basic usage (if you only need to handle workers) new ClusterManager(server.start).start(); @example var ClusterManager = require('cluster-man'); var server = require('./lib/server'); // Create a new cluster manager using options, for handling master process // and worker processes with a specific number of workers. var serverCluster = new ClusterManager({ worker: server.start, master: masterStart, numWorkers: 4 }); function masterStart(clusterManager) { // Any additional things you'd like to do after the cluster // has started... } // Start the cluster serverCluster.start(); @author Ryan Sandor Richards. @class @param {object|function} opts Options for the cluster or a worker function to execute on worker processes. @param {cluster-man~Callback} opt.worker Function to execute on the worker processes. @param {cluster-man~Callback} opt.master Function to execute on the master process. @param {Number} opt.numWorkers Number of workers to spawn. Defaults to the value in `process.env.CLUSTER_WORKERS` if present, and if not then the number of CPUs as reported by `os.cpus().length`. @param {String} opt.debugScope Root scope for debug logging. Defaults to the value in `process.env.CLUSTER_DEBUG` if present, and if not then defaults to 'cluster-man'. @param {Boolean} opt.killOnError=true Whether or not to kill the master process on and unhandled error. @param {cluster-man~BeforeExit} opt.beforeExit Callback to execute before the master process exits in response to an error. @throws Error If a opt.worker was not specified or was not a function.
[ "Utility", "class", "for", "creating", "new", "server", "clusters", "." ]
fa60bc78501c4261ad288b7e0d1fb661284cf640
https://github.com/Runnable/cluster-man/blob/fa60bc78501c4261ad288b7e0d1fb661284cf640/index.js#L72-L110
51,049
skpapam/i-encrypt
index.js
function(data){ return typeof data === 'object' ? JSON.stringify(data) : (typeof data === 'string' || typeof data === 'number' ? String(data) : null); }
javascript
function(data){ return typeof data === 'object' ? JSON.stringify(data) : (typeof data === 'string' || typeof data === 'number' ? String(data) : null); }
[ "function", "(", "data", ")", "{", "return", "typeof", "data", "===", "'object'", "?", "JSON", ".", "stringify", "(", "data", ")", ":", "(", "typeof", "data", "===", "'string'", "||", "typeof", "data", "===", "'number'", "?", "String", "(", "data", ")", ":", "null", ")", ";", "}" ]
Private serialization method @private @param data {Object} || {String} || {Number} @returns {String} or null on fail
[ "Private", "serialization", "method" ]
ebc93e25d7340817eaa8eccfde8b1b24aeb2f802
https://github.com/skpapam/i-encrypt/blob/ebc93e25d7340817eaa8eccfde8b1b24aeb2f802/index.js#L150-L154
51,050
andrewscwei/requiem
src/dom/getElementRegistry.js
getElementRegistry
function getElementRegistry(identifier) { if (!window.__private__) window.__private__ = {}; if (window.__private__.elementRegistry === undefined) window.__private__.elementRegistry = {}; if (typeof identifier === 'string') { if (!~identifier.indexOf('-')) identifier = identifier + '-element'; return window.__private__.elementRegistry[identifier]; } if (typeof identifier === 'function') { for (let tag in window.__private__.elementRegistry) { let Class = window.__private__.elementRegistry[tag]; if (Class.__proto__ === identifier) return Class; } return null; } return window.__private__.elementRegistry; }
javascript
function getElementRegistry(identifier) { if (!window.__private__) window.__private__ = {}; if (window.__private__.elementRegistry === undefined) window.__private__.elementRegistry = {}; if (typeof identifier === 'string') { if (!~identifier.indexOf('-')) identifier = identifier + '-element'; return window.__private__.elementRegistry[identifier]; } if (typeof identifier === 'function') { for (let tag in window.__private__.elementRegistry) { let Class = window.__private__.elementRegistry[tag]; if (Class.__proto__ === identifier) return Class; } return null; } return window.__private__.elementRegistry; }
[ "function", "getElementRegistry", "(", "identifier", ")", "{", "if", "(", "!", "window", ".", "__private__", ")", "window", ".", "__private__", "=", "{", "}", ";", "if", "(", "window", ".", "__private__", ".", "elementRegistry", "===", "undefined", ")", "window", ".", "__private__", ".", "elementRegistry", "=", "{", "}", ";", "if", "(", "typeof", "identifier", "===", "'string'", ")", "{", "if", "(", "!", "~", "identifier", ".", "indexOf", "(", "'-'", ")", ")", "identifier", "=", "identifier", "+", "'-element'", ";", "return", "window", ".", "__private__", ".", "elementRegistry", "[", "identifier", "]", ";", "}", "if", "(", "typeof", "identifier", "===", "'function'", ")", "{", "for", "(", "let", "tag", "in", "window", ".", "__private__", ".", "elementRegistry", ")", "{", "let", "Class", "=", "window", ".", "__private__", ".", "elementRegistry", "[", "tag", "]", ";", "if", "(", "Class", ".", "__proto__", "===", "identifier", ")", "return", "Class", ";", "}", "return", "null", ";", "}", "return", "window", ".", "__private__", ".", "elementRegistry", ";", "}" ]
Gets the element registry. @param {string|Function} [identifier] - Either a tag or the element class to look for. If unspecified the entire registry will be returned. @return {Object} The element registry. @alias module:requiem~dom.getElementRegistry
[ "Gets", "the", "element", "registry", "." ]
c4182bfffc9841c6de5718f689ad3c2060511777
https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/dom/getElementRegistry.js#L16-L31
51,051
Encentivize/kwaai-crud
lib/crud.js
validated
function validated(invalid){ if (invalid) { return callback(invalid) } if(options.coerce){crudUtils.coerceData(options,coerced())} else{coerced(null,options.data)} }
javascript
function validated(invalid){ if (invalid) { return callback(invalid) } if(options.coerce){crudUtils.coerceData(options,coerced())} else{coerced(null,options.data)} }
[ "function", "validated", "(", "invalid", ")", "{", "if", "(", "invalid", ")", "{", "return", "callback", "(", "invalid", ")", "}", "if", "(", "options", ".", "coerce", ")", "{", "crudUtils", ".", "coerceData", "(", "options", ",", "coerced", "(", ")", ")", "}", "else", "{", "coerced", "(", "null", ",", "options", ".", "data", ")", "}", "}" ]
coerce to schema
[ "coerce", "to", "schema" ]
aefcfab619b4447f78c2e863e8bdb9035b021995
https://github.com/Encentivize/kwaai-crud/blob/aefcfab619b4447f78c2e863e8bdb9035b021995/lib/crud.js#L661-L665
51,052
gasolin/provecss
index.js
provecss
function provecss(string, options) { options = options || {}; this.browsers = options.browsers; if (options.path) { this.import_path = path.basename(options.path); this.import_base = options.base || path.dirname(options.path); } this.import_filter = options.import_filter; this.vars = options.vars; this.media_match = options.media_match; this.media_extract = options.media_extract; //not run autoprefixer by default if (this.browsers) { string = prefixes(this.browsers).process(string).css; } //handle import inlining if any if (this.import_path) { var opts = { path: this.import_path, base: this.import_base, target: this.import_filter }; string = rework(string).use(imprt(opts)).toString(); } //filter media query if any if (this.media_match) { if (!this.media_match.width || !this.media_match.height) { throw new Error('Must provide device width and device height'); } var extractOptions = { deviceOptions: { width: this.media_match.width, height: this.media_match.height, orientation: this.media_match.orientation || 'any' }, extractQuery: this.media_extract }; string = rework(string).use(move).use(extract(extractOptions)).toString(); } if (this.vars) { string = rework(string).use(vars).toString(); } return rework(string, options) .use(hex) .use(color) .use(calc) .toString(options); }
javascript
function provecss(string, options) { options = options || {}; this.browsers = options.browsers; if (options.path) { this.import_path = path.basename(options.path); this.import_base = options.base || path.dirname(options.path); } this.import_filter = options.import_filter; this.vars = options.vars; this.media_match = options.media_match; this.media_extract = options.media_extract; //not run autoprefixer by default if (this.browsers) { string = prefixes(this.browsers).process(string).css; } //handle import inlining if any if (this.import_path) { var opts = { path: this.import_path, base: this.import_base, target: this.import_filter }; string = rework(string).use(imprt(opts)).toString(); } //filter media query if any if (this.media_match) { if (!this.media_match.width || !this.media_match.height) { throw new Error('Must provide device width and device height'); } var extractOptions = { deviceOptions: { width: this.media_match.width, height: this.media_match.height, orientation: this.media_match.orientation || 'any' }, extractQuery: this.media_extract }; string = rework(string).use(move).use(extract(extractOptions)).toString(); } if (this.vars) { string = rework(string).use(vars).toString(); } return rework(string, options) .use(hex) .use(color) .use(calc) .toString(options); }
[ "function", "provecss", "(", "string", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "browsers", "=", "options", ".", "browsers", ";", "if", "(", "options", ".", "path", ")", "{", "this", ".", "import_path", "=", "path", ".", "basename", "(", "options", ".", "path", ")", ";", "this", ".", "import_base", "=", "options", ".", "base", "||", "path", ".", "dirname", "(", "options", ".", "path", ")", ";", "}", "this", ".", "import_filter", "=", "options", ".", "import_filter", ";", "this", ".", "vars", "=", "options", ".", "vars", ";", "this", ".", "media_match", "=", "options", ".", "media_match", ";", "this", ".", "media_extract", "=", "options", ".", "media_extract", ";", "//not run autoprefixer by default", "if", "(", "this", ".", "browsers", ")", "{", "string", "=", "prefixes", "(", "this", ".", "browsers", ")", ".", "process", "(", "string", ")", ".", "css", ";", "}", "//handle import inlining if any", "if", "(", "this", ".", "import_path", ")", "{", "var", "opts", "=", "{", "path", ":", "this", ".", "import_path", ",", "base", ":", "this", ".", "import_base", ",", "target", ":", "this", ".", "import_filter", "}", ";", "string", "=", "rework", "(", "string", ")", ".", "use", "(", "imprt", "(", "opts", ")", ")", ".", "toString", "(", ")", ";", "}", "//filter media query if any", "if", "(", "this", ".", "media_match", ")", "{", "if", "(", "!", "this", ".", "media_match", ".", "width", "||", "!", "this", ".", "media_match", ".", "height", ")", "{", "throw", "new", "Error", "(", "'Must provide device width and device height'", ")", ";", "}", "var", "extractOptions", "=", "{", "deviceOptions", ":", "{", "width", ":", "this", ".", "media_match", ".", "width", ",", "height", ":", "this", ".", "media_match", ".", "height", ",", "orientation", ":", "this", ".", "media_match", ".", "orientation", "||", "'any'", "}", ",", "extractQuery", ":", "this", ".", "media_extract", "}", ";", "string", "=", "rework", "(", "string", ")", ".", "use", "(", "move", ")", ".", "use", "(", "extract", "(", "extractOptions", ")", ")", ".", "toString", "(", ")", ";", "}", "if", "(", "this", ".", "vars", ")", "{", "string", "=", "rework", "(", "string", ")", ".", "use", "(", "vars", ")", ".", "toString", "(", ")", ";", "}", "return", "rework", "(", "string", ",", "options", ")", ".", "use", "(", "hex", ")", ".", "use", "(", "color", ")", ".", "use", "(", "calc", ")", ".", "toString", "(", "options", ")", ";", "}" ]
Rework a CSS `string` @param {String} string (optional) @param {Object} options (optional) @return {String}
[ "Rework", "a", "CSS", "string" ]
7d92512c0bbd600be83055231c5644dbd0cc704a
https://github.com/gasolin/provecss/blob/7d92512c0bbd600be83055231c5644dbd0cc704a/index.js#L26-L78
51,053
nodeGame/shelf.js
build/shelf.js
function (fileName, key, value) { var file = fileName || store.filename; if (!file) { store.log('You must specify a valid file.', 'ERR'); return false; } if (!key) return; var item = store.stringify(key) + ": " + store.stringify(value) + ",\n"; return fs.appendFileSync(file, item, 'utf-8'); }
javascript
function (fileName, key, value) { var file = fileName || store.filename; if (!file) { store.log('You must specify a valid file.', 'ERR'); return false; } if (!key) return; var item = store.stringify(key) + ": " + store.stringify(value) + ",\n"; return fs.appendFileSync(file, item, 'utf-8'); }
[ "function", "(", "fileName", ",", "key", ",", "value", ")", "{", "var", "file", "=", "fileName", "||", "store", ".", "filename", ";", "if", "(", "!", "file", ")", "{", "store", ".", "log", "(", "'You must specify a valid file.'", ",", "'ERR'", ")", ";", "return", "false", ";", "}", "if", "(", "!", "key", ")", "return", ";", "var", "item", "=", "store", ".", "stringify", "(", "key", ")", "+", "\": \"", "+", "store", ".", "stringify", "(", "value", ")", "+", "\",\\n\"", ";", "return", "fs", ".", "appendFileSync", "(", "file", ",", "item", ",", "'utf-8'", ")", ";", "}" ]
node 0.8
[ "node", "0", ".", "8" ]
49eabcf55337c2f70b7ba94a483952cc514c76e1
https://github.com/nodeGame/shelf.js/blob/49eabcf55337c2f70b7ba94a483952cc514c76e1/build/shelf.js#L1609-L1621
51,054
nodeGame/shelf.js
build/shelf.js
function (fileName, key, value) { var file = fileName || store.filename; if (!file) { store.log('You must specify a valid file.', 'ERR'); return false; } if (!key) return; var item = store.stringify(key) + ": " + store.stringify(value) + ",\n"; var fd = fs.openSync(file, 'a', '0666'); fs.writeSync(fd, item, null, 'utf8'); fs.closeSync(fd); return true; }
javascript
function (fileName, key, value) { var file = fileName || store.filename; if (!file) { store.log('You must specify a valid file.', 'ERR'); return false; } if (!key) return; var item = store.stringify(key) + ": " + store.stringify(value) + ",\n"; var fd = fs.openSync(file, 'a', '0666'); fs.writeSync(fd, item, null, 'utf8'); fs.closeSync(fd); return true; }
[ "function", "(", "fileName", ",", "key", ",", "value", ")", "{", "var", "file", "=", "fileName", "||", "store", ".", "filename", ";", "if", "(", "!", "file", ")", "{", "store", ".", "log", "(", "'You must specify a valid file.'", ",", "'ERR'", ")", ";", "return", "false", ";", "}", "if", "(", "!", "key", ")", "return", ";", "var", "item", "=", "store", ".", "stringify", "(", "key", ")", "+", "\": \"", "+", "store", ".", "stringify", "(", "value", ")", "+", "\",\\n\"", ";", "var", "fd", "=", "fs", ".", "openSync", "(", "file", ",", "'a'", ",", "'0666'", ")", ";", "fs", ".", "writeSync", "(", "fd", ",", "item", ",", "null", ",", "'utf8'", ")", ";", "fs", ".", "closeSync", "(", "fd", ")", ";", "return", "true", ";", "}" ]
node < 0.8
[ "node", "<", "0", ".", "8" ]
49eabcf55337c2f70b7ba94a483952cc514c76e1
https://github.com/nodeGame/shelf.js/blob/49eabcf55337c2f70b7ba94a483952cc514c76e1/build/shelf.js#L1625-L1642
51,055
inviqa/deck-task-registry
src/other/default.js
defaultTask
function defaultTask(conf, undertaker, done) { return undertaker.series( require('../build/build').bind(null, conf, undertaker), require('../other/watch').bind(null, conf, undertaker) )(done); }
javascript
function defaultTask(conf, undertaker, done) { return undertaker.series( require('../build/build').bind(null, conf, undertaker), require('../other/watch').bind(null, conf, undertaker) )(done); }
[ "function", "defaultTask", "(", "conf", ",", "undertaker", ",", "done", ")", "{", "return", "undertaker", ".", "series", "(", "require", "(", "'../build/build'", ")", ".", "bind", "(", "null", ",", "conf", ",", "undertaker", ")", ",", "require", "(", "'../other/watch'", ")", ".", "bind", "(", "null", ",", "conf", ",", "undertaker", ")", ")", "(", "done", ")", ";", "}" ]
The default task to be run. @param {ConfigParser} conf A configuration parser object. @param {Undertaker} undertaker An Undertaker instance. @returns {Stream} A stream of files.
[ "The", "default", "task", "to", "be", "run", "." ]
4c31787b978e9d99a47052e090d4589a50cd3015
https://github.com/inviqa/deck-task-registry/blob/4c31787b978e9d99a47052e090d4589a50cd3015/src/other/default.js#L11-L16
51,056
ianusmagnus/passport-relayr
lib/strategy.js
RelayrStrategy
function RelayrStrategy(options, verifyCallback) { if (!verifyCallback) { throw new TypeError('verify callback is required'); } options = options || {}; options.authorizationURL = options.authorizationURL || 'https://api.relayr.io/oauth2/auth'; options.responseType = options.responseType || 'token'; options.tokenURL = 'https://api.relayr.io/oauth2/token'; options.scope = 'access-own-user-info+configure-devices'; options.scopeSeparator = options.scopeSeparator || ' '; OAuth2Strategy.call(this, options, verifyCallback); this.name = 'relayr'; this._profileURL = options.profileURL || 'https://api.relayr.io/oauth2/user-info'; this._appURL = options.appURL || 'https://api.relayr.io/oauth2/app-info'; this._infocall = options.fetch || 'user'; this._oauth2.useAuthorizationHeaderforGET(true); }
javascript
function RelayrStrategy(options, verifyCallback) { if (!verifyCallback) { throw new TypeError('verify callback is required'); } options = options || {}; options.authorizationURL = options.authorizationURL || 'https://api.relayr.io/oauth2/auth'; options.responseType = options.responseType || 'token'; options.tokenURL = 'https://api.relayr.io/oauth2/token'; options.scope = 'access-own-user-info+configure-devices'; options.scopeSeparator = options.scopeSeparator || ' '; OAuth2Strategy.call(this, options, verifyCallback); this.name = 'relayr'; this._profileURL = options.profileURL || 'https://api.relayr.io/oauth2/user-info'; this._appURL = options.appURL || 'https://api.relayr.io/oauth2/app-info'; this._infocall = options.fetch || 'user'; this._oauth2.useAuthorizationHeaderforGET(true); }
[ "function", "RelayrStrategy", "(", "options", ",", "verifyCallback", ")", "{", "if", "(", "!", "verifyCallback", ")", "{", "throw", "new", "TypeError", "(", "'verify callback is required'", ")", ";", "}", "options", "=", "options", "||", "{", "}", ";", "options", ".", "authorizationURL", "=", "options", ".", "authorizationURL", "||", "'https://api.relayr.io/oauth2/auth'", ";", "options", ".", "responseType", "=", "options", ".", "responseType", "||", "'token'", ";", "options", ".", "tokenURL", "=", "'https://api.relayr.io/oauth2/token'", ";", "options", ".", "scope", "=", "'access-own-user-info+configure-devices'", ";", "options", ".", "scopeSeparator", "=", "options", ".", "scopeSeparator", "||", "' '", ";", "OAuth2Strategy", ".", "call", "(", "this", ",", "options", ",", "verifyCallback", ")", ";", "this", ".", "name", "=", "'relayr'", ";", "this", ".", "_profileURL", "=", "options", ".", "profileURL", "||", "'https://api.relayr.io/oauth2/user-info'", ";", "this", ".", "_appURL", "=", "options", ".", "appURL", "||", "'https://api.relayr.io/oauth2/app-info'", ";", "this", ".", "_infocall", "=", "options", ".", "fetch", "||", "'user'", ";", "this", ".", "_oauth2", ".", "useAuthorizationHeaderforGET", "(", "true", ")", ";", "}" ]
`RelayrStrategy` constructor.
[ "RelayrStrategy", "constructor", "." ]
9b5e7ec8f9e759f5b34a486d14399a6ea7694db0
https://github.com/ianusmagnus/passport-relayr/blob/9b5e7ec8f9e759f5b34a486d14399a6ea7694db0/lib/strategy.js#L9-L26
51,057
Degree53/takeown
index.js
attemptCallback
function attemptCallback(filePath, callback, attempts) { try { callback(); return; } catch (error) { if (attempts === 0) { console.error('takeown: callback failed - exceeded attempts'); throw error; } switch (error.code) { case 'EPERM': case 'EACCES': case 'EBUSY': case 'ENOTEMPTY': return attemptCallback(filePath, callback, --attempts); default: throw error; } } }
javascript
function attemptCallback(filePath, callback, attempts) { try { callback(); return; } catch (error) { if (attempts === 0) { console.error('takeown: callback failed - exceeded attempts'); throw error; } switch (error.code) { case 'EPERM': case 'EACCES': case 'EBUSY': case 'ENOTEMPTY': return attemptCallback(filePath, callback, --attempts); default: throw error; } } }
[ "function", "attemptCallback", "(", "filePath", ",", "callback", ",", "attempts", ")", "{", "try", "{", "callback", "(", ")", ";", "return", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "attempts", "===", "0", ")", "{", "console", ".", "error", "(", "'takeown: callback failed - exceeded attempts'", ")", ";", "throw", "error", ";", "}", "switch", "(", "error", ".", "code", ")", "{", "case", "'EPERM'", ":", "case", "'EACCES'", ":", "case", "'EBUSY'", ":", "case", "'ENOTEMPTY'", ":", "return", "attemptCallback", "(", "filePath", ",", "callback", ",", "--", "attempts", ")", ";", "default", ":", "throw", "error", ";", "}", "}", "}" ]
Intentionally locks up javascript thread for a fixed number of recursive calls to give Windows time to get its arse in gear.
[ "Intentionally", "locks", "up", "javascript", "thread", "for", "a", "fixed", "number", "of", "recursive", "calls", "to", "give", "Windows", "time", "to", "get", "its", "arse", "in", "gear", "." ]
93040b0fadd1625a5dfa553e50cc16e10c8e361a
https://github.com/Degree53/takeown/blob/93040b0fadd1625a5dfa553e50cc16e10c8e361a/index.js#L14-L40
51,058
Degree53/takeown
index.js
takeOwnership
function takeOwnership(filePath) { try { var stats = fs.lstatSync(filePath); if (stats.isDirectory()) { execSyncElevated('takeown /f "' + filePath + '" /r /d y'); } else { execSyncElevated('takeown /f "' + filePath + '"'); } return; } catch (error) { if (error.code === 'ENOENT') { console.warn('takeown:', filePath, 'does not exist.'); return; } // fs.lstatSync can fail with EPERM on Windows so retry // after taking control of this specific path. if (error.code === 'EPERM') { execSyncElevated('takeown /f "' + filePath + '"'); return takeOwnership(filePath); } } }
javascript
function takeOwnership(filePath) { try { var stats = fs.lstatSync(filePath); if (stats.isDirectory()) { execSyncElevated('takeown /f "' + filePath + '" /r /d y'); } else { execSyncElevated('takeown /f "' + filePath + '"'); } return; } catch (error) { if (error.code === 'ENOENT') { console.warn('takeown:', filePath, 'does not exist.'); return; } // fs.lstatSync can fail with EPERM on Windows so retry // after taking control of this specific path. if (error.code === 'EPERM') { execSyncElevated('takeown /f "' + filePath + '"'); return takeOwnership(filePath); } } }
[ "function", "takeOwnership", "(", "filePath", ")", "{", "try", "{", "var", "stats", "=", "fs", ".", "lstatSync", "(", "filePath", ")", ";", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "execSyncElevated", "(", "'takeown /f \"'", "+", "filePath", "+", "'\" /r /d y'", ")", ";", "}", "else", "{", "execSyncElevated", "(", "'takeown /f \"'", "+", "filePath", "+", "'\"'", ")", ";", "}", "return", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "error", ".", "code", "===", "'ENOENT'", ")", "{", "console", ".", "warn", "(", "'takeown:'", ",", "filePath", ",", "'does not exist.'", ")", ";", "return", ";", "}", "// fs.lstatSync can fail with EPERM on Windows so retry", "// after taking control of this specific path.", "if", "(", "error", ".", "code", "===", "'EPERM'", ")", "{", "execSyncElevated", "(", "'takeown /f \"'", "+", "filePath", "+", "'\"'", ")", ";", "return", "takeOwnership", "(", "filePath", ")", ";", "}", "}", "}" ]
Calls fire and forget Windows specific command to seize control of a file or directory. Never seems to fail but we don't get any confirmation of success.
[ "Calls", "fire", "and", "forget", "Windows", "specific", "command", "to", "seize", "control", "of", "a", "file", "or", "directory", ".", "Never", "seems", "to", "fail", "but", "we", "don", "t", "get", "any", "confirmation", "of", "success", "." ]
93040b0fadd1625a5dfa553e50cc16e10c8e361a
https://github.com/Degree53/takeown/blob/93040b0fadd1625a5dfa553e50cc16e10c8e361a/index.js#L45-L73
51,059
RoboterHund/April1
modules/spec.js
expand
function expand (node, args, i) { var n = args.length; var arg; for (; i < n; i++) { arg = args [i]; if (isNodeType (arg, types.MACRO)) { expand (node, arg, 1); } else { node.push (arg); } } return node; }
javascript
function expand (node, args, i) { var n = args.length; var arg; for (; i < n; i++) { arg = args [i]; if (isNodeType (arg, types.MACRO)) { expand (node, arg, 1); } else { node.push (arg); } } return node; }
[ "function", "expand", "(", "node", ",", "args", ",", "i", ")", "{", "var", "n", "=", "args", ".", "length", ";", "var", "arg", ";", "for", "(", ";", "i", "<", "n", ";", "i", "++", ")", "{", "arg", "=", "args", "[", "i", "]", ";", "if", "(", "isNodeType", "(", "arg", ",", "types", ".", "MACRO", ")", ")", "{", "expand", "(", "node", ",", "arg", ",", "1", ")", ";", "}", "else", "{", "node", ".", "push", "(", "arg", ")", ";", "}", "}", "return", "node", ";", "}" ]
push node items onto the spec node array expand macros @param {Array} node the spec node array to be generated @param args node items @param i @returns {Array} the spec node array, with the items appended
[ "push", "node", "items", "onto", "the", "spec", "node", "array", "expand", "macros" ]
f4fead4d8190d0b7bdc7b649f4c2c0e9728ef30b
https://github.com/RoboterHund/April1/blob/f4fead4d8190d0b7bdc7b649f4c2c0e9728ef30b/modules/spec.js#L27-L40
51,060
redisjs/jsr-server
lib/command/connection/ping.js
validate
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); if(args.length > 1) { throw new CommandArgLength(cmd); } }
javascript
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); if(args.length > 1) { throw new CommandArgLength(cmd); } }
[ "function", "validate", "(", "cmd", ",", "args", ",", "info", ")", "{", "AbstractCommand", ".", "prototype", ".", "validate", ".", "apply", "(", "this", ",", "arguments", ")", ";", "if", "(", "args", ".", "length", ">", "1", ")", "{", "throw", "new", "CommandArgLength", "(", "cmd", ")", ";", "}", "}" ]
Validate the PING command.
[ "Validate", "the", "PING", "command", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/connection/ping.js#L19-L24
51,061
redisjs/jsr-server
lib/command/connection/ping.js
execute
function execute(req, res) { if(req.args.length) return res.send(null, req.args[0]); res.send(null, Constants.PONG); }
javascript
function execute(req, res) { if(req.args.length) return res.send(null, req.args[0]); res.send(null, Constants.PONG); }
[ "function", "execute", "(", "req", ",", "res", ")", "{", "if", "(", "req", ".", "args", ".", "length", ")", "return", "res", ".", "send", "(", "null", ",", "req", ".", "args", "[", "0", "]", ")", ";", "res", ".", "send", "(", "null", ",", "Constants", ".", "PONG", ")", ";", "}" ]
Respond to the PING command.
[ "Respond", "to", "the", "PING", "command", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/connection/ping.js#L29-L32
51,062
olivoil/migrate-js
lib/migrate.js
defaultMigrationLoader
function defaultMigrationLoader(dir) { let list = new List; return new Promise((resolve, reject) => { fs.readdir(dir, function(err, files) { if (err) return reject(err); const migrationFiles = files.filter((file) => file.match(/^\d+.*\.js$/)).sort(); migrationFiles.forEach((file) => { let mod; try { mod = require(path.join(dir, file)); } catch (err) { return reject(err); } list = list.addMigration(file, mod.up, mod.down); }); resolve(list); }); }); }
javascript
function defaultMigrationLoader(dir) { let list = new List; return new Promise((resolve, reject) => { fs.readdir(dir, function(err, files) { if (err) return reject(err); const migrationFiles = files.filter((file) => file.match(/^\d+.*\.js$/)).sort(); migrationFiles.forEach((file) => { let mod; try { mod = require(path.join(dir, file)); } catch (err) { return reject(err); } list = list.addMigration(file, mod.up, mod.down); }); resolve(list); }); }); }
[ "function", "defaultMigrationLoader", "(", "dir", ")", "{", "let", "list", "=", "new", "List", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "readdir", "(", "dir", ",", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "const", "migrationFiles", "=", "files", ".", "filter", "(", "(", "file", ")", "=>", "file", ".", "match", "(", "/", "^\\d+.*\\.js$", "/", ")", ")", ".", "sort", "(", ")", ";", "migrationFiles", ".", "forEach", "(", "(", "file", ")", "=>", "{", "let", "mod", ";", "try", "{", "mod", "=", "require", "(", "path", ".", "join", "(", "dir", ",", "file", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "list", "=", "list", ".", "addMigration", "(", "file", ",", "mod", ".", "up", ",", "mod", ".", "down", ")", ";", "}", ")", ";", "resolve", "(", "list", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
default migration loader. load files from disk.
[ "default", "migration", "loader", ".", "load", "files", "from", "disk", "." ]
130b1afe7715696df2a7841769a19dbfb4966b78
https://github.com/olivoil/migrate-js/blob/130b1afe7715696df2a7841769a19dbfb4966b78/lib/migrate.js#L16-L40
51,063
Tennu/tennu-admin
plugin.js
checkHostmask
function checkHostmask (hostmask, admin) { return names.every(function (name) { const result = admin[name].test(hostmask[name]); client.debug("PluginAdmin", format("%s: %s, %s (%s)", name, hostmask[name], admin[name], result)); return result; }); }
javascript
function checkHostmask (hostmask, admin) { return names.every(function (name) { const result = admin[name].test(hostmask[name]); client.debug("PluginAdmin", format("%s: %s, %s (%s)", name, hostmask[name], admin[name], result)); return result; }); }
[ "function", "checkHostmask", "(", "hostmask", ",", "admin", ")", "{", "return", "names", ".", "every", "(", "function", "(", "name", ")", "{", "const", "result", "=", "admin", "[", "name", "]", ".", "test", "(", "hostmask", "[", "name", "]", ")", ";", "client", ".", "debug", "(", "\"PluginAdmin\"", ",", "format", "(", "\"%s: %s, %s (%s)\"", ",", "name", ",", "hostmask", "[", "name", "]", ",", "admin", "[", "name", "]", ",", "result", ")", ")", ";", "return", "result", ";", "}", ")", ";", "}" ]
tennu.Client! -> Hostmask -> Admin -> boolean
[ "tennu", ".", "Client!", "-", ">", "Hostmask", "-", ">", "Admin", "-", ">", "boolean" ]
19d68570a0db845251877ee6f3b29f74678f7bbb
https://github.com/Tennu/tennu-admin/blob/19d68570a0db845251877ee6f3b29f74678f7bbb/plugin.js#L69-L78
51,064
Tennu/tennu-admin
plugin.js
function (hostmask, opts) { return Promise.try(function () { if (opts && opts.allowAll === true) { return true; } const customAdmins = opts && opts.customAdmins; const memoizationKey = opts && opts.memoizeOver; const hostmask_passed = (customAdmins || admins).filter(function (admin) { return checkHostmask(hostmask, admin); }); if (hostmask_passed.some(notHasIdentifiedasProperty)) { client.debug("PluginAdmin", "Admin object w/o identifiedas property (true)"); return true; } client.debug("PluginAdmin", "Admin object w/o identifiedas property (false)"); return (function recur () { if (hostmask_passed.length === 0) { client.debug("PluginAdmin", "User passes an identifiedas check (false)"); return false; } return Promise.try(function () { const hostmask = hostmask_passed.pop(); return hostmask.identifiedas; }) .then(function (accountname) { return isIdentifiedAs(hostmask.nickname, accountname, {memoizeOver: memoizationKey}); }) .then(function (isIdentifiedAs) { if (isIdentifiedAs) { client.debug("PluginAdmin", "User passes an identifiedas check (true)"); return true; } else { return recur(); } }); }()); }); }
javascript
function (hostmask, opts) { return Promise.try(function () { if (opts && opts.allowAll === true) { return true; } const customAdmins = opts && opts.customAdmins; const memoizationKey = opts && opts.memoizeOver; const hostmask_passed = (customAdmins || admins).filter(function (admin) { return checkHostmask(hostmask, admin); }); if (hostmask_passed.some(notHasIdentifiedasProperty)) { client.debug("PluginAdmin", "Admin object w/o identifiedas property (true)"); return true; } client.debug("PluginAdmin", "Admin object w/o identifiedas property (false)"); return (function recur () { if (hostmask_passed.length === 0) { client.debug("PluginAdmin", "User passes an identifiedas check (false)"); return false; } return Promise.try(function () { const hostmask = hostmask_passed.pop(); return hostmask.identifiedas; }) .then(function (accountname) { return isIdentifiedAs(hostmask.nickname, accountname, {memoizeOver: memoizationKey}); }) .then(function (isIdentifiedAs) { if (isIdentifiedAs) { client.debug("PluginAdmin", "User passes an identifiedas check (true)"); return true; } else { return recur(); } }); }()); }); }
[ "function", "(", "hostmask", ",", "opts", ")", "{", "return", "Promise", ".", "try", "(", "function", "(", ")", "{", "if", "(", "opts", "&&", "opts", ".", "allowAll", "===", "true", ")", "{", "return", "true", ";", "}", "const", "customAdmins", "=", "opts", "&&", "opts", ".", "customAdmins", ";", "const", "memoizationKey", "=", "opts", "&&", "opts", ".", "memoizeOver", ";", "const", "hostmask_passed", "=", "(", "customAdmins", "||", "admins", ")", ".", "filter", "(", "function", "(", "admin", ")", "{", "return", "checkHostmask", "(", "hostmask", ",", "admin", ")", ";", "}", ")", ";", "if", "(", "hostmask_passed", ".", "some", "(", "notHasIdentifiedasProperty", ")", ")", "{", "client", ".", "debug", "(", "\"PluginAdmin\"", ",", "\"Admin object w/o identifiedas property (true)\"", ")", ";", "return", "true", ";", "}", "client", ".", "debug", "(", "\"PluginAdmin\"", ",", "\"Admin object w/o identifiedas property (false)\"", ")", ";", "return", "(", "function", "recur", "(", ")", "{", "if", "(", "hostmask_passed", ".", "length", "===", "0", ")", "{", "client", ".", "debug", "(", "\"PluginAdmin\"", ",", "\"User passes an identifiedas check (false)\"", ")", ";", "return", "false", ";", "}", "return", "Promise", ".", "try", "(", "function", "(", ")", "{", "const", "hostmask", "=", "hostmask_passed", ".", "pop", "(", ")", ";", "return", "hostmask", ".", "identifiedas", ";", "}", ")", ".", "then", "(", "function", "(", "accountname", ")", "{", "return", "isIdentifiedAs", "(", "hostmask", ".", "nickname", ",", "accountname", ",", "{", "memoizeOver", ":", "memoizationKey", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "isIdentifiedAs", ")", "{", "if", "(", "isIdentifiedAs", ")", "{", "client", ".", "debug", "(", "\"PluginAdmin\"", ",", "\"User passes an identifiedas check (true)\"", ")", ";", "return", "true", ";", "}", "else", "{", "return", "recur", "(", ")", ";", "}", "}", ")", ";", "}", "(", ")", ")", ";", "}", ")", ";", "}" ]
Hostmask -> Promise boolean
[ "Hostmask", "-", ">", "Promise", "boolean" ]
19d68570a0db845251877ee6f3b29f74678f7bbb
https://github.com/Tennu/tennu-admin/blob/19d68570a0db845251877ee6f3b29f74678f7bbb/plugin.js#L84-L126
51,065
vesln/obsessed
lib/obsessed-error.js
ObsessedError
function ObsessedError(message, errors) { Error.captureStackTrace(this, ObsessedError); this.message = this.combine(message, errors); }
javascript
function ObsessedError(message, errors) { Error.captureStackTrace(this, ObsessedError); this.message = this.combine(message, errors); }
[ "function", "ObsessedError", "(", "message", ",", "errors", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "ObsessedError", ")", ";", "this", ".", "message", "=", "this", ".", "combine", "(", "message", ",", "errors", ")", ";", "}" ]
Custom error. Includes all error messages. @param {String} message @param {Array} errors @constructor
[ "Custom", "error", ".", "Includes", "all", "error", "messages", "." ]
4878dfafdea241bff9ad5c57acc2395a4f3487a6
https://github.com/vesln/obsessed/blob/4878dfafdea241bff9ad5c57acc2395a4f3487a6/lib/obsessed-error.js#L10-L13
51,066
vkiding/judpack-lib
src/cordova/prepare.js
preparePlatforms
function preparePlatforms (platformList, projectRoot, options) { return Q.all(platformList.map(function(platform) { // TODO: this need to be replaced by real projectInfo // instance for current project. var project = { root: projectRoot, projectConfig: new ConfigParser(cordova_util.projectConfig(projectRoot)), locations: { plugins: path.join(projectRoot, 'plugins'), www: cordova_util.projectWww(projectRoot) } }; // CB-9987 We need to reinstall the plugins for the platform it they were added by cordova@<5.4.0 return restoreMissingPluginsForPlatform(platform, projectRoot, options) .then(function () { // platformApi prepare takes care of all functionality // which previously had been executed by cordova.prepare: // - reset config.xml and then merge changes from project's one, // - update www directory from project's one and merge assets from platform_www, // - reapply config changes, made by plugins, // - update platform's project // Please note that plugins' changes, such as installed js files, assets and // config changes is not being reinstalled on each prepare. var platformApi = platforms.getPlatformApi(platform); return platformApi.prepare(project, _.clone(options)) .then(function () { if (platform === 'windows' && !(platformApi instanceof PlatformApiPoly)) { // Windows Api doesn't fire 'pre_package' hook, so we fire it here return new HooksRunner(projectRoot).fire('pre_package', { wwwPath: platformApi.getPlatformInfo().locations.www, platforms: ['windows'], nohooks: options.nohooks }); } }) .then(function () { if (options.browserify) { var browserify = require('../plugman/browserify'); return browserify(project, platformApi); } }) .then(function () { // Handle edit-config in config.xml var platformRoot = path.join(projectRoot, 'platforms', platform); var platformJson = PlatformJson.load(platformRoot, platform); var munger = new PlatformMunger(platform, platformRoot, platformJson); munger.add_config_changes(project.projectConfig, /*should_increment=*/true).save_all(); }); }); })); }
javascript
function preparePlatforms (platformList, projectRoot, options) { return Q.all(platformList.map(function(platform) { // TODO: this need to be replaced by real projectInfo // instance for current project. var project = { root: projectRoot, projectConfig: new ConfigParser(cordova_util.projectConfig(projectRoot)), locations: { plugins: path.join(projectRoot, 'plugins'), www: cordova_util.projectWww(projectRoot) } }; // CB-9987 We need to reinstall the plugins for the platform it they were added by cordova@<5.4.0 return restoreMissingPluginsForPlatform(platform, projectRoot, options) .then(function () { // platformApi prepare takes care of all functionality // which previously had been executed by cordova.prepare: // - reset config.xml and then merge changes from project's one, // - update www directory from project's one and merge assets from platform_www, // - reapply config changes, made by plugins, // - update platform's project // Please note that plugins' changes, such as installed js files, assets and // config changes is not being reinstalled on each prepare. var platformApi = platforms.getPlatformApi(platform); return platformApi.prepare(project, _.clone(options)) .then(function () { if (platform === 'windows' && !(platformApi instanceof PlatformApiPoly)) { // Windows Api doesn't fire 'pre_package' hook, so we fire it here return new HooksRunner(projectRoot).fire('pre_package', { wwwPath: platformApi.getPlatformInfo().locations.www, platforms: ['windows'], nohooks: options.nohooks }); } }) .then(function () { if (options.browserify) { var browserify = require('../plugman/browserify'); return browserify(project, platformApi); } }) .then(function () { // Handle edit-config in config.xml var platformRoot = path.join(projectRoot, 'platforms', platform); var platformJson = PlatformJson.load(platformRoot, platform); var munger = new PlatformMunger(platform, platformRoot, platformJson); munger.add_config_changes(project.projectConfig, /*should_increment=*/true).save_all(); }); }); })); }
[ "function", "preparePlatforms", "(", "platformList", ",", "projectRoot", ",", "options", ")", "{", "return", "Q", ".", "all", "(", "platformList", ".", "map", "(", "function", "(", "platform", ")", "{", "// TODO: this need to be replaced by real projectInfo", "// instance for current project.", "var", "project", "=", "{", "root", ":", "projectRoot", ",", "projectConfig", ":", "new", "ConfigParser", "(", "cordova_util", ".", "projectConfig", "(", "projectRoot", ")", ")", ",", "locations", ":", "{", "plugins", ":", "path", ".", "join", "(", "projectRoot", ",", "'plugins'", ")", ",", "www", ":", "cordova_util", ".", "projectWww", "(", "projectRoot", ")", "}", "}", ";", "// CB-9987 We need to reinstall the plugins for the platform it they were added by cordova@<5.4.0", "return", "restoreMissingPluginsForPlatform", "(", "platform", ",", "projectRoot", ",", "options", ")", ".", "then", "(", "function", "(", ")", "{", "// platformApi prepare takes care of all functionality", "// which previously had been executed by cordova.prepare:", "// - reset config.xml and then merge changes from project's one,", "// - update www directory from project's one and merge assets from platform_www,", "// - reapply config changes, made by plugins,", "// - update platform's project", "// Please note that plugins' changes, such as installed js files, assets and", "// config changes is not being reinstalled on each prepare.", "var", "platformApi", "=", "platforms", ".", "getPlatformApi", "(", "platform", ")", ";", "return", "platformApi", ".", "prepare", "(", "project", ",", "_", ".", "clone", "(", "options", ")", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "platform", "===", "'windows'", "&&", "!", "(", "platformApi", "instanceof", "PlatformApiPoly", ")", ")", "{", "// Windows Api doesn't fire 'pre_package' hook, so we fire it here", "return", "new", "HooksRunner", "(", "projectRoot", ")", ".", "fire", "(", "'pre_package'", ",", "{", "wwwPath", ":", "platformApi", ".", "getPlatformInfo", "(", ")", ".", "locations", ".", "www", ",", "platforms", ":", "[", "'windows'", "]", ",", "nohooks", ":", "options", ".", "nohooks", "}", ")", ";", "}", "}", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "options", ".", "browserify", ")", "{", "var", "browserify", "=", "require", "(", "'../plugman/browserify'", ")", ";", "return", "browserify", "(", "project", ",", "platformApi", ")", ";", "}", "}", ")", ".", "then", "(", "function", "(", ")", "{", "// Handle edit-config in config.xml", "var", "platformRoot", "=", "path", ".", "join", "(", "projectRoot", ",", "'platforms'", ",", "platform", ")", ";", "var", "platformJson", "=", "PlatformJson", ".", "load", "(", "platformRoot", ",", "platform", ")", ";", "var", "munger", "=", "new", "PlatformMunger", "(", "platform", ",", "platformRoot", ",", "platformJson", ")", ";", "munger", ".", "add_config_changes", "(", "project", ".", "projectConfig", ",", "/*should_increment=*/", "true", ")", ".", "save_all", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ")", ";", "}" ]
Calls `platformApi.prepare` for each platform in project @param {string[]} platformList List of platforms, added to current project @param {string} projectRoot Project root directory @return {Promise}
[ "Calls", "platformApi", ".", "prepare", "for", "each", "platform", "in", "project" ]
8657cecfec68221109279106adca8dbc81f430f4
https://github.com/vkiding/judpack-lib/blob/8657cecfec68221109279106adca8dbc81f430f4/src/cordova/prepare.js#L80-L131
51,067
rowanmanning/mocha-srv
lib/mocha-srv.js
defaultOpts
function defaultOpts (opts) { opts = opts || {}; opts.title = opts.title || 'Test Suite'; opts.ui = (opts.ui && opts.ui.toLowerCase() === 'tdd' ? 'tdd' : 'bdd'); opts.path = path.resolve(opts.path || '.'); opts.host = opts.host || 'localhost'; opts.port = opts.port || 3000; return opts; }
javascript
function defaultOpts (opts) { opts = opts || {}; opts.title = opts.title || 'Test Suite'; opts.ui = (opts.ui && opts.ui.toLowerCase() === 'tdd' ? 'tdd' : 'bdd'); opts.path = path.resolve(opts.path || '.'); opts.host = opts.host || 'localhost'; opts.port = opts.port || 3000; return opts; }
[ "function", "defaultOpts", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "opts", ".", "title", "=", "opts", ".", "title", "||", "'Test Suite'", ";", "opts", ".", "ui", "=", "(", "opts", ".", "ui", "&&", "opts", ".", "ui", ".", "toLowerCase", "(", ")", "===", "'tdd'", "?", "'tdd'", ":", "'bdd'", ")", ";", "opts", ".", "path", "=", "path", ".", "resolve", "(", "opts", ".", "path", "||", "'.'", ")", ";", "opts", ".", "host", "=", "opts", ".", "host", "||", "'localhost'", ";", "opts", ".", "port", "=", "opts", ".", "port", "||", "3000", ";", "return", "opts", ";", "}" ]
Default server options
[ "Default", "server", "options" ]
47af5e5bc91bb37ba5ccdb0ea7cf1771748fdff2
https://github.com/rowanmanning/mocha-srv/blob/47af5e5bc91bb37ba5ccdb0ea7cf1771748fdff2/lib/mocha-srv.js#L7-L15
51,068
AVVS/callback-queue
index.js
cleanup
function cleanup(key) { callbackQueue[key] = null; if (++nulls > nullThreshold) { callbackQueue = omit(callbackQueue, function removeNulls(datum) { return datum === null; }); } }
javascript
function cleanup(key) { callbackQueue[key] = null; if (++nulls > nullThreshold) { callbackQueue = omit(callbackQueue, function removeNulls(datum) { return datum === null; }); } }
[ "function", "cleanup", "(", "key", ")", "{", "callbackQueue", "[", "key", "]", "=", "null", ";", "if", "(", "++", "nulls", ">", "nullThreshold", ")", "{", "callbackQueue", "=", "omit", "(", "callbackQueue", ",", "function", "removeNulls", "(", "datum", ")", "{", "return", "datum", "===", "null", ";", "}", ")", ";", "}", "}" ]
Performs cleanup on queue object @param {String} key
[ "Performs", "cleanup", "on", "queue", "object" ]
3edc65093812dd713f0a24c951dbfdd9e8ca6135
https://github.com/AVVS/callback-queue/blob/3edc65093812dd713f0a24c951dbfdd9e8ca6135/index.js#L29-L36
51,069
AVVS/callback-queue
index.js
iterateOverCallbacks
function iterateOverCallbacks(bucket, args) { bucket.forEach(function iterator(callback) { nextTick(function queuedCallback() { callback.apply(null, args); }); }); }
javascript
function iterateOverCallbacks(bucket, args) { bucket.forEach(function iterator(callback) { nextTick(function queuedCallback() { callback.apply(null, args); }); }); }
[ "function", "iterateOverCallbacks", "(", "bucket", ",", "args", ")", "{", "bucket", ".", "forEach", "(", "function", "iterator", "(", "callback", ")", "{", "nextTick", "(", "function", "queuedCallback", "(", ")", "{", "callback", ".", "apply", "(", "null", ",", "args", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Iterates over callbacks and calls them with passed args @param {Array} bucket @param {Array} args
[ "Iterates", "over", "callbacks", "and", "calls", "them", "with", "passed", "args" ]
3edc65093812dd713f0a24c951dbfdd9e8ca6135
https://github.com/AVVS/callback-queue/blob/3edc65093812dd713f0a24c951dbfdd9e8ca6135/index.js#L43-L49
51,070
vkiding/jud-vue-render
src/render/browser/render/gesture.js
touchstartHandler
function touchstartHandler(event) { if (Object.keys(gestures).length === 0) { docEl.addEventListener('touchmove', touchmoveHandler, false) docEl.addEventListener('touchend', touchendHandler, false) docEl.addEventListener('touchcancel', touchcancelHandler, false) } // record every touch for (var i = 0; i < event.changedTouches.length; i++) { var touch = event.changedTouches[i] var touchRecord = {} for (var p in touch) { touchRecord[p] = touch[p] } var gesture = { startTouch: touchRecord, startTime: Date.now(), status: 'tapping', element: event.srcElement || event.target, pressingHandler: setTimeout(function (element, touch) { return function () { if (gesture.status === 'tapping') { gesture.status = 'pressing' fireEvent(element, 'longpress', { // add touch data for jud touch: touch, touches: event.touches, changedTouches: event.changedTouches, touchEvent: event }) } clearTimeout(gesture.pressingHandler) gesture.pressingHandler = null } }(event.srcElement || event.target, event.changedTouches[i]), 500) } gestures[touch.identifier] = gesture } if (Object.keys(gestures).length == 2) { var elements = [] for (var p in gestures) { elements.push(gestures[p].element) } fireEvent(getCommonAncestor(elements[0], elements[1]), 'dualtouchstart', { touches: slice.call(event.touches), touchEvent: event }) } }
javascript
function touchstartHandler(event) { if (Object.keys(gestures).length === 0) { docEl.addEventListener('touchmove', touchmoveHandler, false) docEl.addEventListener('touchend', touchendHandler, false) docEl.addEventListener('touchcancel', touchcancelHandler, false) } // record every touch for (var i = 0; i < event.changedTouches.length; i++) { var touch = event.changedTouches[i] var touchRecord = {} for (var p in touch) { touchRecord[p] = touch[p] } var gesture = { startTouch: touchRecord, startTime: Date.now(), status: 'tapping', element: event.srcElement || event.target, pressingHandler: setTimeout(function (element, touch) { return function () { if (gesture.status === 'tapping') { gesture.status = 'pressing' fireEvent(element, 'longpress', { // add touch data for jud touch: touch, touches: event.touches, changedTouches: event.changedTouches, touchEvent: event }) } clearTimeout(gesture.pressingHandler) gesture.pressingHandler = null } }(event.srcElement || event.target, event.changedTouches[i]), 500) } gestures[touch.identifier] = gesture } if (Object.keys(gestures).length == 2) { var elements = [] for (var p in gestures) { elements.push(gestures[p].element) } fireEvent(getCommonAncestor(elements[0], elements[1]), 'dualtouchstart', { touches: slice.call(event.touches), touchEvent: event }) } }
[ "function", "touchstartHandler", "(", "event", ")", "{", "if", "(", "Object", ".", "keys", "(", "gestures", ")", ".", "length", "===", "0", ")", "{", "docEl", ".", "addEventListener", "(", "'touchmove'", ",", "touchmoveHandler", ",", "false", ")", "docEl", ".", "addEventListener", "(", "'touchend'", ",", "touchendHandler", ",", "false", ")", "docEl", ".", "addEventListener", "(", "'touchcancel'", ",", "touchcancelHandler", ",", "false", ")", "}", "// record every touch", "for", "(", "var", "i", "=", "0", ";", "i", "<", "event", ".", "changedTouches", ".", "length", ";", "i", "++", ")", "{", "var", "touch", "=", "event", ".", "changedTouches", "[", "i", "]", "var", "touchRecord", "=", "{", "}", "for", "(", "var", "p", "in", "touch", ")", "{", "touchRecord", "[", "p", "]", "=", "touch", "[", "p", "]", "}", "var", "gesture", "=", "{", "startTouch", ":", "touchRecord", ",", "startTime", ":", "Date", ".", "now", "(", ")", ",", "status", ":", "'tapping'", ",", "element", ":", "event", ".", "srcElement", "||", "event", ".", "target", ",", "pressingHandler", ":", "setTimeout", "(", "function", "(", "element", ",", "touch", ")", "{", "return", "function", "(", ")", "{", "if", "(", "gesture", ".", "status", "===", "'tapping'", ")", "{", "gesture", ".", "status", "=", "'pressing'", "fireEvent", "(", "element", ",", "'longpress'", ",", "{", "// add touch data for jud", "touch", ":", "touch", ",", "touches", ":", "event", ".", "touches", ",", "changedTouches", ":", "event", ".", "changedTouches", ",", "touchEvent", ":", "event", "}", ")", "}", "clearTimeout", "(", "gesture", ".", "pressingHandler", ")", "gesture", ".", "pressingHandler", "=", "null", "}", "}", "(", "event", ".", "srcElement", "||", "event", ".", "target", ",", "event", ".", "changedTouches", "[", "i", "]", ")", ",", "500", ")", "}", "gestures", "[", "touch", ".", "identifier", "]", "=", "gesture", "}", "if", "(", "Object", ".", "keys", "(", "gestures", ")", ".", "length", "==", "2", ")", "{", "var", "elements", "=", "[", "]", "for", "(", "var", "p", "in", "gestures", ")", "{", "elements", ".", "push", "(", "gestures", "[", "p", "]", ".", "element", ")", "}", "fireEvent", "(", "getCommonAncestor", "(", "elements", "[", "0", "]", ",", "elements", "[", "1", "]", ")", ",", "'dualtouchstart'", ",", "{", "touches", ":", "slice", ".", "call", "(", "event", ".", "touches", ")", ",", "touchEvent", ":", "event", "}", ")", "}", "}" ]
take over the touchstart events. Add new touches to the gestures. If there is no previous records, then bind touchmove, tochend and touchcancel events. new touches initialized with state 'tapping', and within 500 milliseconds if the state is still tapping, then trigger gesture 'press'. If there are two touche points, then the 'dualtouchstart' is triggerd. The node of the touch gesture is their cloest common ancestor. @event @param {event} event
[ "take", "over", "the", "touchstart", "events", ".", "Add", "new", "touches", "to", "the", "gestures", ".", "If", "there", "is", "no", "previous", "records", "then", "bind", "touchmove", "tochend", "and", "touchcancel", "events", ".", "new", "touches", "initialized", "with", "state", "tapping", "and", "within", "500", "milliseconds", "if", "the", "state", "is", "still", "tapping", "then", "trigger", "gesture", "press", ".", "If", "there", "are", "two", "touche", "points", "then", "the", "dualtouchstart", "is", "triggerd", ".", "The", "node", "of", "the", "touch", "gesture", "is", "their", "cloest", "common", "ancestor", "." ]
07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47
https://github.com/vkiding/jud-vue-render/blob/07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47/src/render/browser/render/gesture.js#L121-L177
51,071
vkiding/jud-vue-render
src/render/browser/render/gesture.js
touchendHandler
function touchendHandler(event) { if (Object.keys(gestures).length == 2) { var elements = [] for (var p in gestures) { elements.push(gestures[p].element) } fireEvent(getCommonAncestor(elements[0], elements[1]), 'dualtouchend', { touches: slice.call(event.touches), touchEvent: event }) } for (var i = 0; i < event.changedTouches.length; i++) { var touch = event.changedTouches[i] var id = touch.identifier var gesture = gestures[id] if (!gesture) { continue } if (gesture.pressingHandler) { clearTimeout(gesture.pressingHandler) gesture.pressingHandler = null } if (gesture.status === 'tapping') { gesture.timestamp = Date.now() fireEvent(gesture.element, 'tap', { touch: touch, touchEvent: event }) if (lastTap && gesture.timestamp - lastTap.timestamp < 300) { fireEvent(gesture.element, 'doubletap', { touch: touch, touchEvent: event }) } lastTap = gesture } if (gesture.status === 'panning') { var now = Date.now() var duration = now - gesture.startTime var displacementX = touch.clientX - gesture.startTouch.clientX var displacementY = touch.clientY - gesture.startTouch.clientY var velocity = Math.sqrt(gesture.velocityY * gesture.velocityY + gesture.velocityX * gesture.velocityX) var isSwipe = velocity > 0.5 && (now - gesture.lastTime) < 100 var extra = { duration: duration, isSwipe: isSwipe, velocityX: gesture.velocityX, velocityY: gesture.velocityY, displacementX: displacementX, displacementY: displacementY, touch: touch, touches: event.touches, changedTouches: event.changedTouches, touchEvent: event, isVertical: gesture.isVertical, direction: gesture.direction } fireEvent(gesture.element, 'panend', extra) if (isSwipe) { fireEvent(gesture.element, 'swipe', extra) } } if (gesture.status === 'pressing') { fireEvent(gesture.element, 'pressend', { touch: touch, touchEvent: event }) } delete gestures[id] } if (Object.keys(gestures).length === 0) { docEl.removeEventListener('touchmove', touchmoveHandler, false) docEl.removeEventListener('touchend', touchendHandler, false) docEl.removeEventListener('touchcancel', touchcancelHandler, false) } }
javascript
function touchendHandler(event) { if (Object.keys(gestures).length == 2) { var elements = [] for (var p in gestures) { elements.push(gestures[p].element) } fireEvent(getCommonAncestor(elements[0], elements[1]), 'dualtouchend', { touches: slice.call(event.touches), touchEvent: event }) } for (var i = 0; i < event.changedTouches.length; i++) { var touch = event.changedTouches[i] var id = touch.identifier var gesture = gestures[id] if (!gesture) { continue } if (gesture.pressingHandler) { clearTimeout(gesture.pressingHandler) gesture.pressingHandler = null } if (gesture.status === 'tapping') { gesture.timestamp = Date.now() fireEvent(gesture.element, 'tap', { touch: touch, touchEvent: event }) if (lastTap && gesture.timestamp - lastTap.timestamp < 300) { fireEvent(gesture.element, 'doubletap', { touch: touch, touchEvent: event }) } lastTap = gesture } if (gesture.status === 'panning') { var now = Date.now() var duration = now - gesture.startTime var displacementX = touch.clientX - gesture.startTouch.clientX var displacementY = touch.clientY - gesture.startTouch.clientY var velocity = Math.sqrt(gesture.velocityY * gesture.velocityY + gesture.velocityX * gesture.velocityX) var isSwipe = velocity > 0.5 && (now - gesture.lastTime) < 100 var extra = { duration: duration, isSwipe: isSwipe, velocityX: gesture.velocityX, velocityY: gesture.velocityY, displacementX: displacementX, displacementY: displacementY, touch: touch, touches: event.touches, changedTouches: event.changedTouches, touchEvent: event, isVertical: gesture.isVertical, direction: gesture.direction } fireEvent(gesture.element, 'panend', extra) if (isSwipe) { fireEvent(gesture.element, 'swipe', extra) } } if (gesture.status === 'pressing') { fireEvent(gesture.element, 'pressend', { touch: touch, touchEvent: event }) } delete gestures[id] } if (Object.keys(gestures).length === 0) { docEl.removeEventListener('touchmove', touchmoveHandler, false) docEl.removeEventListener('touchend', touchendHandler, false) docEl.removeEventListener('touchcancel', touchcancelHandler, false) } }
[ "function", "touchendHandler", "(", "event", ")", "{", "if", "(", "Object", ".", "keys", "(", "gestures", ")", ".", "length", "==", "2", ")", "{", "var", "elements", "=", "[", "]", "for", "(", "var", "p", "in", "gestures", ")", "{", "elements", ".", "push", "(", "gestures", "[", "p", "]", ".", "element", ")", "}", "fireEvent", "(", "getCommonAncestor", "(", "elements", "[", "0", "]", ",", "elements", "[", "1", "]", ")", ",", "'dualtouchend'", ",", "{", "touches", ":", "slice", ".", "call", "(", "event", ".", "touches", ")", ",", "touchEvent", ":", "event", "}", ")", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "event", ".", "changedTouches", ".", "length", ";", "i", "++", ")", "{", "var", "touch", "=", "event", ".", "changedTouches", "[", "i", "]", "var", "id", "=", "touch", ".", "identifier", "var", "gesture", "=", "gestures", "[", "id", "]", "if", "(", "!", "gesture", ")", "{", "continue", "}", "if", "(", "gesture", ".", "pressingHandler", ")", "{", "clearTimeout", "(", "gesture", ".", "pressingHandler", ")", "gesture", ".", "pressingHandler", "=", "null", "}", "if", "(", "gesture", ".", "status", "===", "'tapping'", ")", "{", "gesture", ".", "timestamp", "=", "Date", ".", "now", "(", ")", "fireEvent", "(", "gesture", ".", "element", ",", "'tap'", ",", "{", "touch", ":", "touch", ",", "touchEvent", ":", "event", "}", ")", "if", "(", "lastTap", "&&", "gesture", ".", "timestamp", "-", "lastTap", ".", "timestamp", "<", "300", ")", "{", "fireEvent", "(", "gesture", ".", "element", ",", "'doubletap'", ",", "{", "touch", ":", "touch", ",", "touchEvent", ":", "event", "}", ")", "}", "lastTap", "=", "gesture", "}", "if", "(", "gesture", ".", "status", "===", "'panning'", ")", "{", "var", "now", "=", "Date", ".", "now", "(", ")", "var", "duration", "=", "now", "-", "gesture", ".", "startTime", "var", "displacementX", "=", "touch", ".", "clientX", "-", "gesture", ".", "startTouch", ".", "clientX", "var", "displacementY", "=", "touch", ".", "clientY", "-", "gesture", ".", "startTouch", ".", "clientY", "var", "velocity", "=", "Math", ".", "sqrt", "(", "gesture", ".", "velocityY", "*", "gesture", ".", "velocityY", "+", "gesture", ".", "velocityX", "*", "gesture", ".", "velocityX", ")", "var", "isSwipe", "=", "velocity", ">", "0.5", "&&", "(", "now", "-", "gesture", ".", "lastTime", ")", "<", "100", "var", "extra", "=", "{", "duration", ":", "duration", ",", "isSwipe", ":", "isSwipe", ",", "velocityX", ":", "gesture", ".", "velocityX", ",", "velocityY", ":", "gesture", ".", "velocityY", ",", "displacementX", ":", "displacementX", ",", "displacementY", ":", "displacementY", ",", "touch", ":", "touch", ",", "touches", ":", "event", ".", "touches", ",", "changedTouches", ":", "event", ".", "changedTouches", ",", "touchEvent", ":", "event", ",", "isVertical", ":", "gesture", ".", "isVertical", ",", "direction", ":", "gesture", ".", "direction", "}", "fireEvent", "(", "gesture", ".", "element", ",", "'panend'", ",", "extra", ")", "if", "(", "isSwipe", ")", "{", "fireEvent", "(", "gesture", ".", "element", ",", "'swipe'", ",", "extra", ")", "}", "}", "if", "(", "gesture", ".", "status", "===", "'pressing'", ")", "{", "fireEvent", "(", "gesture", ".", "element", ",", "'pressend'", ",", "{", "touch", ":", "touch", ",", "touchEvent", ":", "event", "}", ")", "}", "delete", "gestures", "[", "id", "]", "}", "if", "(", "Object", ".", "keys", "(", "gestures", ")", ".", "length", "===", "0", ")", "{", "docEl", ".", "removeEventListener", "(", "'touchmove'", ",", "touchmoveHandler", ",", "false", ")", "docEl", ".", "removeEventListener", "(", "'touchend'", ",", "touchendHandler", ",", "false", ")", "docEl", ".", "removeEventListener", "(", "'touchcancel'", ",", "touchcancelHandler", ",", "false", ")", "}", "}" ]
handle touchend event 1. if there are tow touch points, then trigger 'dualtouchend'如 2. traverse every touch piont: > if tapping, then trigger 'tap'. If there is a tap 300 milliseconds before, then it's a 'doubletap'. > if padding, then decide to trigger 'panend' or 'swipe' > if pressing, then trigger 'pressend'. 3. remove listeners. @event @param {event} event
[ "handle", "touchend", "event" ]
07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47
https://github.com/vkiding/jud-vue-render/blob/07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47/src/render/browser/render/gesture.js#L333-L422
51,072
fernandofranca/launchpod
lib/repl-utils.js
replWriter
function replWriter(output) { if (output){ if (output.constructor && output.constructor.name !== "String"){ return util.inspect(output, {colors:true}) + '\n'; } } return output + '\n'; }
javascript
function replWriter(output) { if (output){ if (output.constructor && output.constructor.name !== "String"){ return util.inspect(output, {colors:true}) + '\n'; } } return output + '\n'; }
[ "function", "replWriter", "(", "output", ")", "{", "if", "(", "output", ")", "{", "if", "(", "output", ".", "constructor", "&&", "output", ".", "constructor", ".", "name", "!==", "\"String\"", ")", "{", "return", "util", ".", "inspect", "(", "output", ",", "{", "colors", ":", "true", "}", ")", "+", "'\\n'", ";", "}", "}", "return", "output", "+", "'\\n'", ";", "}" ]
Can I haz colorz? Does objects pretty printing
[ "Can", "I", "haz", "colorz?", "Does", "objects", "pretty", "printing" ]
882d614a4271846e17b3ba0ca319340a607580bc
https://github.com/fernandofranca/launchpod/blob/882d614a4271846e17b3ba0ca319340a607580bc/lib/repl-utils.js#L9-L17
51,073
hiproxy/conf-parser
src/input.js
function (msg, line, column) { this._info(line || this.line, column || this.column, msg, true, true); }
javascript
function (msg, line, column) { this._info(line || this.line, column || this.column, msg, true, true); }
[ "function", "(", "msg", ",", "line", ",", "column", ")", "{", "this", ".", "_info", "(", "line", "||", "this", ".", "line", ",", "column", "||", "this", ".", "column", ",", "msg", ",", "true", ",", "true", ")", ";", "}" ]
print error message
[ "print", "error", "message" ]
fcfdde3b933afdbb573eb5f9e01baec7e489e7dc
https://github.com/hiproxy/conf-parser/blob/fcfdde3b933afdbb573eb5f9e01baec7e489e7dc/src/input.js#L56-L58
51,074
tolokoban/ToloFrameWork
ker/mod/tfw.view.slider.js
xToValue
function xToValue(x) { const rect = this.$.getBoundingClientRect(), percent = x / rect.width, range = this.max - this.min, value = Math.floor(percent * range + 0.5); return this.min + this.step * Math.floor(value / this.step); }
javascript
function xToValue(x) { const rect = this.$.getBoundingClientRect(), percent = x / rect.width, range = this.max - this.min, value = Math.floor(percent * range + 0.5); return this.min + this.step * Math.floor(value / this.step); }
[ "function", "xToValue", "(", "x", ")", "{", "const", "rect", "=", "this", ".", "$", ".", "getBoundingClientRect", "(", ")", ",", "percent", "=", "x", "/", "rect", ".", "width", ",", "range", "=", "this", ".", "max", "-", "this", ".", "min", ",", "value", "=", "Math", ".", "floor", "(", "percent", "*", "range", "+", "0.5", ")", ";", "return", "this", ".", "min", "+", "this", ".", "step", "*", "Math", ".", "floor", "(", "value", "/", "this", ".", "step", ")", ";", "}" ]
Convert a X position into the nearest value. @this ViewXJS @param {float} x - X position relative to the View. @returns {integer} The nearest integer value.
[ "Convert", "a", "X", "position", "into", "the", "nearest", "value", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.slider.js#L48-L55
51,075
tolokoban/ToloFrameWork
ker/mod/tfw.view.slider.js
valueToX
function valueToX(value) { const rect = this.$.getBoundingClientRect(), percent = (value - this.min) / (this.max - this.min); return rect.width * percent; }
javascript
function valueToX(value) { const rect = this.$.getBoundingClientRect(), percent = (value - this.min) / (this.max - this.min); return rect.width * percent; }
[ "function", "valueToX", "(", "value", ")", "{", "const", "rect", "=", "this", ".", "$", ".", "getBoundingClientRect", "(", ")", ",", "percent", "=", "(", "value", "-", "this", ".", "min", ")", "/", "(", "this", ".", "max", "-", "this", ".", "min", ")", ";", "return", "rect", ".", "width", "*", "percent", ";", "}" ]
Convert a value into X position relative to View. @this ViewXJS @param {integer} value - Current value. @returns {float} X position.
[ "Convert", "a", "value", "into", "X", "position", "relative", "to", "View", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.slider.js#L64-L69
51,076
tolokoban/ToloFrameWork
ker/mod/tfw.view.slider.js
onDrag
function onDrag(evt) { const rect = this._rect, x = valueToX.call(this, this._value), min = -x, max = rect.width - x, tx = clamp(evt.x - evt.x0, min, max), value = xToValue.call(this, x + tx); Dom.css(this.$elements.button, { transform: `translateX(${tx}px)` }); this.displayedValue = valueToDisplayedValue.call(this, value); if (this.smooth) { this._dragging = true; this.value = value; } }
javascript
function onDrag(evt) { const rect = this._rect, x = valueToX.call(this, this._value), min = -x, max = rect.width - x, tx = clamp(evt.x - evt.x0, min, max), value = xToValue.call(this, x + tx); Dom.css(this.$elements.button, { transform: `translateX(${tx}px)` }); this.displayedValue = valueToDisplayedValue.call(this, value); if (this.smooth) { this._dragging = true; this.value = value; } }
[ "function", "onDrag", "(", "evt", ")", "{", "const", "rect", "=", "this", ".", "_rect", ",", "x", "=", "valueToX", ".", "call", "(", "this", ",", "this", ".", "_value", ")", ",", "min", "=", "-", "x", ",", "max", "=", "rect", ".", "width", "-", "x", ",", "tx", "=", "clamp", "(", "evt", ".", "x", "-", "evt", ".", "x0", ",", "min", ",", "max", ")", ",", "value", "=", "xToValue", ".", "call", "(", "this", ",", "x", "+", "tx", ")", ";", "Dom", ".", "css", "(", "this", ".", "$elements", ".", "button", ",", "{", "transform", ":", "`", "${", "tx", "}", "`", "}", ")", ";", "this", ".", "displayedValue", "=", "valueToDisplayedValue", ".", "call", "(", "this", ",", "value", ")", ";", "if", "(", "this", ".", "smooth", ")", "{", "this", ".", "_dragging", "=", "true", ";", "this", ".", "value", "=", "value", ";", "}", "}" ]
Drag the button. @this ViewXJS @param {object} evt - `{ x, ... }` @returns {undefined}
[ "Drag", "the", "button", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.slider.js#L90-L104
51,077
tolokoban/ToloFrameWork
ker/mod/tfw.view.slider.js
onDragEnd
function onDragEnd(evt) { this._dragging = false; const rect = this._rect, x = valueToX.call(this, this._value), min = -x, max = rect.width - x, tx = clamp(evt.x - evt.x0, min, max); Dom.css(this.$elements.button, { transform: `translateX(0px)` }); this.value = xToValue.call(this, x + tx); }
javascript
function onDragEnd(evt) { this._dragging = false; const rect = this._rect, x = valueToX.call(this, this._value), min = -x, max = rect.width - x, tx = clamp(evt.x - evt.x0, min, max); Dom.css(this.$elements.button, { transform: `translateX(0px)` }); this.value = xToValue.call(this, x + tx); }
[ "function", "onDragEnd", "(", "evt", ")", "{", "this", ".", "_dragging", "=", "false", ";", "const", "rect", "=", "this", ".", "_rect", ",", "x", "=", "valueToX", ".", "call", "(", "this", ",", "this", ".", "_value", ")", ",", "min", "=", "-", "x", ",", "max", "=", "rect", ".", "width", "-", "x", ",", "tx", "=", "clamp", "(", "evt", ".", "x", "-", "evt", ".", "x0", ",", "min", ",", "max", ")", ";", "Dom", ".", "css", "(", "this", ".", "$elements", ".", "button", ",", "{", "transform", ":", "`", "`", "}", ")", ";", "this", ".", "value", "=", "xToValue", ".", "call", "(", "this", ",", "x", "+", "tx", ")", ";", "}" ]
Enf of grag for the button. We can remove the temporaty translation. @this ViewXJS @param {object} evt - `{ x, ... }` @returns {undefined}
[ "Enf", "of", "grag", "for", "the", "button", ".", "We", "can", "remove", "the", "temporaty", "translation", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.slider.js#L113-L124
51,078
tolokoban/ToloFrameWork
ker/mod/tfw.view.slider.js
moveToValue
function moveToValue(value) { const left = 100 * (value - this.min) / (this.max - this.min); Dom.css(this.$elements.button, { left: `${left}%` }); }
javascript
function moveToValue(value) { const left = 100 * (value - this.min) / (this.max - this.min); Dom.css(this.$elements.button, { left: `${left}%` }); }
[ "function", "moveToValue", "(", "value", ")", "{", "const", "left", "=", "100", "*", "(", "value", "-", "this", ".", "min", ")", "/", "(", "this", ".", "max", "-", "this", ".", "min", ")", ";", "Dom", ".", "css", "(", "this", ".", "$elements", ".", "button", ",", "{", "left", ":", "`", "${", "left", "}", "`", "}", ")", ";", "}" ]
Move button to a position mapping the value. @this ViewXJS @param {integer} value - Value. @returns {undefined}
[ "Move", "button", "to", "a", "position", "mapping", "the", "value", "." ]
730845a833a9660ebfdb60ad027ebaab5ac871b6
https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.slider.js#L144-L147
51,079
pattern-library/pattern-library-utilities
lib/get-category-path.js
categoryPathPlain
function categoryPathPlain(patternObject) { 'use strict'; // check for subcategory if (patternObject.subcategory) { return path.join(patternObject.category, patternObject.subcategory); } else { return patternObject.category; } }
javascript
function categoryPathPlain(patternObject) { 'use strict'; // check for subcategory if (patternObject.subcategory) { return path.join(patternObject.category, patternObject.subcategory); } else { return patternObject.category; } }
[ "function", "categoryPathPlain", "(", "patternObject", ")", "{", "'use strict'", ";", "// check for subcategory", "if", "(", "patternObject", ".", "subcategory", ")", "{", "return", "path", ".", "join", "(", "patternObject", ".", "category", ",", "patternObject", ".", "subcategory", ")", ";", "}", "else", "{", "return", "patternObject", ".", "category", ";", "}", "}" ]
Determines the category directory structure without any conversion @param {Object} patternObject individual pattern's data (from /pattern-name/pattern.yml) @return {String} categoryPath internal path url to category
[ "Determines", "the", "category", "directory", "structure", "without", "any", "conversion" ]
a0198f7bb698eb5b859576b11afa3d0ebd3e5911
https://github.com/pattern-library/pattern-library-utilities/blob/a0198f7bb698eb5b859576b11afa3d0ebd3e5911/lib/get-category-path.js#L58-L68
51,080
pattern-library/pattern-library-utilities
lib/get-category-path.js
categoryPathConverted
function categoryPathConverted(categoryObject, patternObject) { 'use strict'; // convert our category path using the categoryObject var categoryPath = utility.categoryNameConverter(categoryObject.categories, patternObject.category); // check for subcategory if (patternObject.subcategory) { var subcategoryPath = utility.categoryNameConverter(categoryObject.subcategories[categoryPath], patternObject.subcategory); return path.join(categoryPath, subcategoryPath); } else { return categoryPath; } }
javascript
function categoryPathConverted(categoryObject, patternObject) { 'use strict'; // convert our category path using the categoryObject var categoryPath = utility.categoryNameConverter(categoryObject.categories, patternObject.category); // check for subcategory if (patternObject.subcategory) { var subcategoryPath = utility.categoryNameConverter(categoryObject.subcategories[categoryPath], patternObject.subcategory); return path.join(categoryPath, subcategoryPath); } else { return categoryPath; } }
[ "function", "categoryPathConverted", "(", "categoryObject", ",", "patternObject", ")", "{", "'use strict'", ";", "// convert our category path using the categoryObject", "var", "categoryPath", "=", "utility", ".", "categoryNameConverter", "(", "categoryObject", ".", "categories", ",", "patternObject", ".", "category", ")", ";", "// check for subcategory", "if", "(", "patternObject", ".", "subcategory", ")", "{", "var", "subcategoryPath", "=", "utility", ".", "categoryNameConverter", "(", "categoryObject", ".", "subcategories", "[", "categoryPath", "]", ",", "patternObject", ".", "subcategory", ")", ";", "return", "path", ".", "join", "(", "categoryPath", ",", "subcategoryPath", ")", ";", "}", "else", "{", "return", "categoryPath", ";", "}", "}" ]
Determines the category directory structure by converting names according to a category object @param {Object} categoryObject object of category names and their conversion titles @param {Object} patternObject individual pattern's data (from /pattern-name/pattern.yml) @return {String} categoryPath internal path url to category
[ "Determines", "the", "category", "directory", "structure", "by", "converting", "names", "according", "to", "a", "category", "object" ]
a0198f7bb698eb5b859576b11afa3d0ebd3e5911
https://github.com/pattern-library/pattern-library-utilities/blob/a0198f7bb698eb5b859576b11afa3d0ebd3e5911/lib/get-category-path.js#L79-L93
51,081
humanise-ai/botmaster-humanise-ware
examples/watson-fb-messenger/botmaster/middleware/wrapped/humanise.js
getHandoffFromUpdate
async function getHandoffFromUpdate (update) { if (!has(update, 'message.text')) { return } // having to do own request as watson-developer-cloud package is broken for // Tone analyzer const toneAnalyzerUrl = 'https://gateway.watsonplatform.net/tone-analyzer/api' const params = { // Get the text from the JSON file. text: update.message.text, tones: 'emotion', version: '2016-05-19' } const requestOptions = { url: `${toneAnalyzerUrl}/v3/tone`, method: 'GET', qs: params, auth: { username: TONE_ANALYSIS_USERNAME, password: TONE_ANALYSIS_PASSWORD }, json: true } const tone = await request(requestOptions) if (has(tone, 'document_tone.tone_categories[0].tones')) { const sentiments = tone.document_tone.tone_categories[0].tones // return sentiment before const badSentimentThreshold = 0.7 for (const sentiment of sentiments) { // not too sure about the ones other than anger for now tbh if (['Anger', 'Disgust', 'Fear', 'Sadness'].indexOf(sentiment.tone_name) > -1 && sentiment.score > badSentimentThreshold) { return 'lowSentiment' } } } }
javascript
async function getHandoffFromUpdate (update) { if (!has(update, 'message.text')) { return } // having to do own request as watson-developer-cloud package is broken for // Tone analyzer const toneAnalyzerUrl = 'https://gateway.watsonplatform.net/tone-analyzer/api' const params = { // Get the text from the JSON file. text: update.message.text, tones: 'emotion', version: '2016-05-19' } const requestOptions = { url: `${toneAnalyzerUrl}/v3/tone`, method: 'GET', qs: params, auth: { username: TONE_ANALYSIS_USERNAME, password: TONE_ANALYSIS_PASSWORD }, json: true } const tone = await request(requestOptions) if (has(tone, 'document_tone.tone_categories[0].tones')) { const sentiments = tone.document_tone.tone_categories[0].tones // return sentiment before const badSentimentThreshold = 0.7 for (const sentiment of sentiments) { // not too sure about the ones other than anger for now tbh if (['Anger', 'Disgust', 'Fear', 'Sadness'].indexOf(sentiment.tone_name) > -1 && sentiment.score > badSentimentThreshold) { return 'lowSentiment' } } } }
[ "async", "function", "getHandoffFromUpdate", "(", "update", ")", "{", "if", "(", "!", "has", "(", "update", ",", "'message.text'", ")", ")", "{", "return", "}", "// having to do own request as watson-developer-cloud package is broken for", "// Tone analyzer", "const", "toneAnalyzerUrl", "=", "'https://gateway.watsonplatform.net/tone-analyzer/api'", "const", "params", "=", "{", "// Get the text from the JSON file.", "text", ":", "update", ".", "message", ".", "text", ",", "tones", ":", "'emotion'", ",", "version", ":", "'2016-05-19'", "}", "const", "requestOptions", "=", "{", "url", ":", "`", "${", "toneAnalyzerUrl", "}", "`", ",", "method", ":", "'GET'", ",", "qs", ":", "params", ",", "auth", ":", "{", "username", ":", "TONE_ANALYSIS_USERNAME", ",", "password", ":", "TONE_ANALYSIS_PASSWORD", "}", ",", "json", ":", "true", "}", "const", "tone", "=", "await", "request", "(", "requestOptions", ")", "if", "(", "has", "(", "tone", ",", "'document_tone.tone_categories[0].tones'", ")", ")", "{", "const", "sentiments", "=", "tone", ".", "document_tone", ".", "tone_categories", "[", "0", "]", ".", "tones", "// return sentiment before", "const", "badSentimentThreshold", "=", "0.7", "for", "(", "const", "sentiment", "of", "sentiments", ")", "{", "// not too sure about the ones other than anger for now tbh", "if", "(", "[", "'Anger'", ",", "'Disgust'", ",", "'Fear'", ",", "'Sadness'", "]", ".", "indexOf", "(", "sentiment", ".", "tone_name", ")", ">", "-", "1", "&&", "sentiment", ".", "score", ">", "badSentimentThreshold", ")", "{", "return", "'lowSentiment'", "}", "}", "}", "}" ]
This is an example implementation of the getHandoffFromUpdate optional parameter. In this example, we determine wether an update should be handed off to a human based on the tone of a certain message
[ "This", "is", "an", "example", "implementation", "of", "the", "getHandoffFromUpdate", "optional", "parameter", ".", "In", "this", "example", "we", "determine", "wether", "an", "update", "should", "be", "handed", "off", "to", "a", "human", "based", "on", "the", "tone", "of", "a", "certain", "message" ]
a94af55ace6a4c90f7f795d84d08ac7f2a920f82
https://github.com/humanise-ai/botmaster-humanise-ware/blob/a94af55ace6a4c90f7f795d84d08ac7f2a920f82/examples/watson-fb-messenger/botmaster/middleware/wrapped/humanise.js#L28-L71
51,082
christkv/vitesse-jsonspec
lib/json_schema.js
function(path, obj) { if(path == '#') return obj; path = path.substr(1); var parts = path.split('/'); parts.shift(); // Locate object for(var i = 0; i < parts.length; i++) { obj = obj[parts[i]]; } return obj; }
javascript
function(path, obj) { if(path == '#') return obj; path = path.substr(1); var parts = path.split('/'); parts.shift(); // Locate object for(var i = 0; i < parts.length; i++) { obj = obj[parts[i]]; } return obj; }
[ "function", "(", "path", ",", "obj", ")", "{", "if", "(", "path", "==", "'#'", ")", "return", "obj", ";", "path", "=", "path", ".", "substr", "(", "1", ")", ";", "var", "parts", "=", "path", ".", "split", "(", "'/'", ")", ";", "parts", ".", "shift", "(", ")", ";", "// Locate object", "for", "(", "var", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "obj", "=", "obj", "[", "parts", "[", "i", "]", "]", ";", "}", "return", "obj", ";", "}" ]
Let's resolve the path
[ "Let", "s", "resolve", "the", "path" ]
7c95dfac43b258b1a7ad6afb5bfe90eb95ef90b1
https://github.com/christkv/vitesse-jsonspec/blob/7c95dfac43b258b1a7ad6afb5bfe90eb95ef90b1/lib/json_schema.js#L512-L524
51,083
christkv/vitesse-jsonspec
lib/json_schema.js
function(reference, callback) { var url = reference.url; var uri = reference.uri; var schema = reference.schema; // Execute the request request(url, function(error, response, body) { // We have an error if(error) return callback(error); // Got the body, parse it var obj = JSON.parse(body); // Resolve the object explode(obj, function(err, obj) { if(err) return callback(err); // Split the url out to locate the right place var path = url.substr(url.indexOf('#')); // Locate the actual document we want var pathObj = resolve(path, obj); // Replace the node delete schema['$ref']; for(var name in pathObj) { schema[name] = pathObj[name]; } // Return the result callback(); }) }); }
javascript
function(reference, callback) { var url = reference.url; var uri = reference.uri; var schema = reference.schema; // Execute the request request(url, function(error, response, body) { // We have an error if(error) return callback(error); // Got the body, parse it var obj = JSON.parse(body); // Resolve the object explode(obj, function(err, obj) { if(err) return callback(err); // Split the url out to locate the right place var path = url.substr(url.indexOf('#')); // Locate the actual document we want var pathObj = resolve(path, obj); // Replace the node delete schema['$ref']; for(var name in pathObj) { schema[name] = pathObj[name]; } // Return the result callback(); }) }); }
[ "function", "(", "reference", ",", "callback", ")", "{", "var", "url", "=", "reference", ".", "url", ";", "var", "uri", "=", "reference", ".", "uri", ";", "var", "schema", "=", "reference", ".", "schema", ";", "// Execute the request", "request", "(", "url", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "// We have an error", "if", "(", "error", ")", "return", "callback", "(", "error", ")", ";", "// Got the body, parse it", "var", "obj", "=", "JSON", ".", "parse", "(", "body", ")", ";", "// Resolve the object", "explode", "(", "obj", ",", "function", "(", "err", ",", "obj", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "// Split the url out to locate the right place", "var", "path", "=", "url", ".", "substr", "(", "url", ".", "indexOf", "(", "'#'", ")", ")", ";", "// Locate the actual document we want", "var", "pathObj", "=", "resolve", "(", "path", ",", "obj", ")", ";", "// Replace the node", "delete", "schema", "[", "'$ref'", "]", ";", "for", "(", "var", "name", "in", "pathObj", ")", "{", "schema", "[", "name", "]", "=", "pathObj", "[", "name", "]", ";", "}", "// Return the result", "callback", "(", ")", ";", "}", ")", "}", ")", ";", "}" ]
Grab the url
[ "Grab", "the", "url" ]
7c95dfac43b258b1a7ad6afb5bfe90eb95ef90b1
https://github.com/christkv/vitesse-jsonspec/blob/7c95dfac43b258b1a7ad6afb5bfe90eb95ef90b1/lib/json_schema.js#L527-L559
51,084
christkv/vitesse-jsonspec
lib/json_schema.js
function(schema, field, reference, seenObjects, path, options) { // Don't resolve recursive relation if(reference == '#') return {$ref: '#'} // Get the path var path = reference.substr(1).split('/').slice(1); path = path.map(function(x) { x = x.replace(/~1/g, '/').replace(/~0/g, '~'); return decodeURI(x); }) // Get a pointer to the schema var pointer = schema; // Traverse the schema for(var i = 0; i < path.length; i++) { pointer = pointer[path[i]]; } // Check if we have seen the object var objects = seenObjects.filter(function(x) { return x.obj === pointer; }); if(objects.length == 1) { seenObjects[0].count = objects[0].count + 1; } else { seenObjects.push({obj: pointer, count: 1}); } // Do we have a reference if(pointer['$ref']) { return deref(schema, field, pointer['$ref'], seenObjects, path, options); } else { extractReferences(schema, pointer, seenObjects, path, options); } return pointer; }
javascript
function(schema, field, reference, seenObjects, path, options) { // Don't resolve recursive relation if(reference == '#') return {$ref: '#'} // Get the path var path = reference.substr(1).split('/').slice(1); path = path.map(function(x) { x = x.replace(/~1/g, '/').replace(/~0/g, '~'); return decodeURI(x); }) // Get a pointer to the schema var pointer = schema; // Traverse the schema for(var i = 0; i < path.length; i++) { pointer = pointer[path[i]]; } // Check if we have seen the object var objects = seenObjects.filter(function(x) { return x.obj === pointer; }); if(objects.length == 1) { seenObjects[0].count = objects[0].count + 1; } else { seenObjects.push({obj: pointer, count: 1}); } // Do we have a reference if(pointer['$ref']) { return deref(schema, field, pointer['$ref'], seenObjects, path, options); } else { extractReferences(schema, pointer, seenObjects, path, options); } return pointer; }
[ "function", "(", "schema", ",", "field", ",", "reference", ",", "seenObjects", ",", "path", ",", "options", ")", "{", "// Don't resolve recursive relation", "if", "(", "reference", "==", "'#'", ")", "return", "{", "$ref", ":", "'#'", "}", "// Get the path", "var", "path", "=", "reference", ".", "substr", "(", "1", ")", ".", "split", "(", "'/'", ")", ".", "slice", "(", "1", ")", ";", "path", "=", "path", ".", "map", "(", "function", "(", "x", ")", "{", "x", "=", "x", ".", "replace", "(", "/", "~1", "/", "g", ",", "'/'", ")", ".", "replace", "(", "/", "~0", "/", "g", ",", "'~'", ")", ";", "return", "decodeURI", "(", "x", ")", ";", "}", ")", "// Get a pointer to the schema", "var", "pointer", "=", "schema", ";", "// Traverse the schema", "for", "(", "var", "i", "=", "0", ";", "i", "<", "path", ".", "length", ";", "i", "++", ")", "{", "pointer", "=", "pointer", "[", "path", "[", "i", "]", "]", ";", "}", "// Check if we have seen the object", "var", "objects", "=", "seenObjects", ".", "filter", "(", "function", "(", "x", ")", "{", "return", "x", ".", "obj", "===", "pointer", ";", "}", ")", ";", "if", "(", "objects", ".", "length", "==", "1", ")", "{", "seenObjects", "[", "0", "]", ".", "count", "=", "objects", "[", "0", "]", ".", "count", "+", "1", ";", "}", "else", "{", "seenObjects", ".", "push", "(", "{", "obj", ":", "pointer", ",", "count", ":", "1", "}", ")", ";", "}", "// Do we have a reference", "if", "(", "pointer", "[", "'$ref'", "]", ")", "{", "return", "deref", "(", "schema", ",", "field", ",", "pointer", "[", "'$ref'", "]", ",", "seenObjects", ",", "path", ",", "options", ")", ";", "}", "else", "{", "extractReferences", "(", "schema", ",", "pointer", ",", "seenObjects", ",", "path", ",", "options", ")", ";", "}", "return", "pointer", ";", "}" ]
De-reference
[ "De", "-", "reference" ]
7c95dfac43b258b1a7ad6afb5bfe90eb95ef90b1
https://github.com/christkv/vitesse-jsonspec/blob/7c95dfac43b258b1a7ad6afb5bfe90eb95ef90b1/lib/json_schema.js#L610-L648
51,085
csbun/grunt-cmd
lib/cmd.js
pathToId
function pathToId(file, base, rel) { var id = rel ? path.resolve(rel, '..', file) : file; id = path.relative(base, id); // replace \ with / in windows' path and remove extname in path id = id.replace(BACKLASH_RE, '/').replace(JS_EXT_RE, ''); return id; }
javascript
function pathToId(file, base, rel) { var id = rel ? path.resolve(rel, '..', file) : file; id = path.relative(base, id); // replace \ with / in windows' path and remove extname in path id = id.replace(BACKLASH_RE, '/').replace(JS_EXT_RE, ''); return id; }
[ "function", "pathToId", "(", "file", ",", "base", ",", "rel", ")", "{", "var", "id", "=", "rel", "?", "path", ".", "resolve", "(", "rel", ",", "'..'", ",", "file", ")", ":", "file", ";", "id", "=", "path", ".", "relative", "(", "base", ",", "id", ")", ";", "// replace \\ with / in windows' path and remove extname in path", "id", "=", "id", ".", "replace", "(", "BACKLASH_RE", ",", "'/'", ")", ".", "replace", "(", "JS_EXT_RE", ",", "''", ")", ";", "return", "id", ";", "}" ]
Convert filepath to toplevel module id @param {String} file - filepath to convert @param {String} base - basepath of seajs @param {String} [rel] - relative path of file @returns {String} id
[ "Convert", "filepath", "to", "toplevel", "module", "id" ]
a806eb8b890e4e6d218341fc4bd45fdd080375ca
https://github.com/csbun/grunt-cmd/blob/a806eb8b890e4e6d218341fc4bd45fdd080375ca/lib/cmd.js#L23-L29
51,086
csbun/grunt-cmd
lib/cmd.js
idToPath
function idToPath(id, config) { var alias = config.alias || {}; return alias.hasOwnProperty(id) ? path.resolve(alias[id]) : path.resolve(config.base, id) + '.js'; }
javascript
function idToPath(id, config) { var alias = config.alias || {}; return alias.hasOwnProperty(id) ? path.resolve(alias[id]) : path.resolve(config.base, id) + '.js'; }
[ "function", "idToPath", "(", "id", ",", "config", ")", "{", "var", "alias", "=", "config", ".", "alias", "||", "{", "}", ";", "return", "alias", ".", "hasOwnProperty", "(", "id", ")", "?", "path", ".", "resolve", "(", "alias", "[", "id", "]", ")", ":", "path", ".", "resolve", "(", "config", ".", "base", ",", "id", ")", "+", "'.js'", ";", "}" ]
Convert toplevel module id to filepath @private
[ "Convert", "toplevel", "module", "id", "to", "filepath" ]
a806eb8b890e4e6d218341fc4bd45fdd080375ca
https://github.com/csbun/grunt-cmd/blob/a806eb8b890e4e6d218341fc4bd45fdd080375ca/lib/cmd.js#L35-L40
51,087
writetome51/array-replace-adjacent-at
dist/index.js
replaceAdjacentAt
function replaceAdjacentAt(index, newValues, array) { error_if_not_array_1.errorIfNotArray(newValues); // The other parameters, index and array, are type-checked here: array_replace_adjacent_items_1._replaceAdjacentItems(index, newValues.length, newValues, array); }
javascript
function replaceAdjacentAt(index, newValues, array) { error_if_not_array_1.errorIfNotArray(newValues); // The other parameters, index and array, are type-checked here: array_replace_adjacent_items_1._replaceAdjacentItems(index, newValues.length, newValues, array); }
[ "function", "replaceAdjacentAt", "(", "index", ",", "newValues", ",", "array", ")", "{", "error_if_not_array_1", ".", "errorIfNotArray", "(", "newValues", ")", ";", "// The other parameters, index and array, are type-checked here:", "array_replace_adjacent_items_1", ".", "_replaceAdjacentItems", "(", "index", ",", "newValues", ".", "length", ",", "newValues", ",", "array", ")", ";", "}" ]
Replaces adjacent items, beginning at `index`, with the same number of `newValues`, in `array`. `index` can be negative or positive. The number of adjacent items that get replaced equals `newValues.length`.
[ "Replaces", "adjacent", "items", "beginning", "at", "index", "with", "the", "same", "number", "of", "newValues", "in", "array", ".", "index", "can", "be", "negative", "or", "positive", ".", "The", "number", "of", "adjacent", "items", "that", "get", "replaced", "equals", "newValues", ".", "length", "." ]
06d86d3b28adbd3ab2d82616beb7824f475c322e
https://github.com/writetome51/array-replace-adjacent-at/blob/06d86d3b28adbd3ab2d82616beb7824f475c322e/dist/index.js#L8-L12
51,088
integreat-io/great-uri-template
lib/filters/append.js
append
function append (value, string) { if ( value === null || value === undefined || value === '' || string === null || string === undefined ) { return value } return value + string }
javascript
function append (value, string) { if ( value === null || value === undefined || value === '' || string === null || string === undefined ) { return value } return value + string }
[ "function", "append", "(", "value", ",", "string", ")", "{", "if", "(", "value", "===", "null", "||", "value", "===", "undefined", "||", "value", "===", "''", "||", "string", "===", "null", "||", "string", "===", "undefined", ")", "{", "return", "value", "}", "return", "value", "+", "string", "}" ]
Append the given string to the value, unless the value is empty. @param {string} value - The value to append to @returns {string} The appended result
[ "Append", "the", "given", "string", "to", "the", "value", "unless", "the", "value", "is", "empty", "." ]
0e896ead0567737cf31a4a8b76a26cfa6ce60759
https://github.com/integreat-io/great-uri-template/blob/0e896ead0567737cf31a4a8b76a26cfa6ce60759/lib/filters/append.js#L6-L14
51,089
WebArtWork/derer
lib/parser.js
TokenParser
function TokenParser(tokens, filters, autoescape, line, filename) { this.out = []; this.state = []; this.filterApplyIdx = []; this._parsers = {}; this.line = line; this.filename = filename; this.filters = filters; this.escape = autoescape; this.parse = function () { var self = this; if (self._parsers.start) { self._parsers.start.call(self); } utils.each(tokens, function (token, i) { var prevToken = tokens[i - 1]; self.isLast = (i === tokens.length - 1); if (prevToken) { while (prevToken.type === _t.WHITESPACE) { i -= 1; prevToken = tokens[i - 1]; } } self.prevToken = prevToken; self.parseToken(token); }); if (self._parsers.end) { self._parsers.end.call(self); } if (self.escape) { self.filterApplyIdx = [0]; if (typeof self.escape === 'string') { self.parseToken({ type: _t.FILTER, match: 'e' }); self.parseToken({ type: _t.COMMA, match: ',' }); self.parseToken({ type: _t.STRING, match: String(autoescape) }); self.parseToken({ type: _t.PARENCLOSE, match: ')'}); } else { self.parseToken({ type: _t.FILTEREMPTY, match: 'e' }); } } return self.out; }; }
javascript
function TokenParser(tokens, filters, autoescape, line, filename) { this.out = []; this.state = []; this.filterApplyIdx = []; this._parsers = {}; this.line = line; this.filename = filename; this.filters = filters; this.escape = autoescape; this.parse = function () { var self = this; if (self._parsers.start) { self._parsers.start.call(self); } utils.each(tokens, function (token, i) { var prevToken = tokens[i - 1]; self.isLast = (i === tokens.length - 1); if (prevToken) { while (prevToken.type === _t.WHITESPACE) { i -= 1; prevToken = tokens[i - 1]; } } self.prevToken = prevToken; self.parseToken(token); }); if (self._parsers.end) { self._parsers.end.call(self); } if (self.escape) { self.filterApplyIdx = [0]; if (typeof self.escape === 'string') { self.parseToken({ type: _t.FILTER, match: 'e' }); self.parseToken({ type: _t.COMMA, match: ',' }); self.parseToken({ type: _t.STRING, match: String(autoescape) }); self.parseToken({ type: _t.PARENCLOSE, match: ')'}); } else { self.parseToken({ type: _t.FILTEREMPTY, match: 'e' }); } } return self.out; }; }
[ "function", "TokenParser", "(", "tokens", ",", "filters", ",", "autoescape", ",", "line", ",", "filename", ")", "{", "this", ".", "out", "=", "[", "]", ";", "this", ".", "state", "=", "[", "]", ";", "this", ".", "filterApplyIdx", "=", "[", "]", ";", "this", ".", "_parsers", "=", "{", "}", ";", "this", ".", "line", "=", "line", ";", "this", ".", "filename", "=", "filename", ";", "this", ".", "filters", "=", "filters", ";", "this", ".", "escape", "=", "autoescape", ";", "this", ".", "parse", "=", "function", "(", ")", "{", "var", "self", "=", "this", ";", "if", "(", "self", ".", "_parsers", ".", "start", ")", "{", "self", ".", "_parsers", ".", "start", ".", "call", "(", "self", ")", ";", "}", "utils", ".", "each", "(", "tokens", ",", "function", "(", "token", ",", "i", ")", "{", "var", "prevToken", "=", "tokens", "[", "i", "-", "1", "]", ";", "self", ".", "isLast", "=", "(", "i", "===", "tokens", ".", "length", "-", "1", ")", ";", "if", "(", "prevToken", ")", "{", "while", "(", "prevToken", ".", "type", "===", "_t", ".", "WHITESPACE", ")", "{", "i", "-=", "1", ";", "prevToken", "=", "tokens", "[", "i", "-", "1", "]", ";", "}", "}", "self", ".", "prevToken", "=", "prevToken", ";", "self", ".", "parseToken", "(", "token", ")", ";", "}", ")", ";", "if", "(", "self", ".", "_parsers", ".", "end", ")", "{", "self", ".", "_parsers", ".", "end", ".", "call", "(", "self", ")", ";", "}", "if", "(", "self", ".", "escape", ")", "{", "self", ".", "filterApplyIdx", "=", "[", "0", "]", ";", "if", "(", "typeof", "self", ".", "escape", "===", "'string'", ")", "{", "self", ".", "parseToken", "(", "{", "type", ":", "_t", ".", "FILTER", ",", "match", ":", "'e'", "}", ")", ";", "self", ".", "parseToken", "(", "{", "type", ":", "_t", ".", "COMMA", ",", "match", ":", "','", "}", ")", ";", "self", ".", "parseToken", "(", "{", "type", ":", "_t", ".", "STRING", ",", "match", ":", "String", "(", "autoescape", ")", "}", ")", ";", "self", ".", "parseToken", "(", "{", "type", ":", "_t", ".", "PARENCLOSE", ",", "match", ":", "')'", "}", ")", ";", "}", "else", "{", "self", ".", "parseToken", "(", "{", "type", ":", "_t", ".", "FILTEREMPTY", ",", "match", ":", "'e'", "}", ")", ";", "}", "}", "return", "self", ".", "out", ";", "}", ";", "}" ]
Parse strings of variables and tags into tokens for future compilation. @class @param {array} tokens Pre-split tokens read by the Lexer. @param {object} filters Keyed object of filters that may be applied to variables. @param {boolean} autoescape Whether or not this should be autoescaped. @param {number} line Beginning line number for the first token. @param {string} [filename] Name of the file being parsed. @private
[ "Parse", "strings", "of", "variables", "and", "tags", "into", "tokens", "for", "future", "compilation", "." ]
edf9f82c8042b543e6f291f605430fac84702b2d
https://github.com/WebArtWork/derer/blob/edf9f82c8042b543e6f291f605430fac84702b2d/lib/parser.js#L60-L106
51,090
WebArtWork/derer
lib/parser.js
function (token, match, lastState) { var self = this; match = match.split('.'); if (_reserved.indexOf(match[0]) !== -1) { utils.throwError('Reserved keyword "' + match[0] + '" attempted to be used as a variable', self.line, self.filename); } self.filterApplyIdx.push(self.out.length); if (lastState === _t.CURLYOPEN) { if (match.length > 1) { utils.throwError('Unexpected dot', self.line, self.filename); } self.out.push(match[0]); return; } self.out.push(self.checkMatch(match)); }
javascript
function (token, match, lastState) { var self = this; match = match.split('.'); if (_reserved.indexOf(match[0]) !== -1) { utils.throwError('Reserved keyword "' + match[0] + '" attempted to be used as a variable', self.line, self.filename); } self.filterApplyIdx.push(self.out.length); if (lastState === _t.CURLYOPEN) { if (match.length > 1) { utils.throwError('Unexpected dot', self.line, self.filename); } self.out.push(match[0]); return; } self.out.push(self.checkMatch(match)); }
[ "function", "(", "token", ",", "match", ",", "lastState", ")", "{", "var", "self", "=", "this", ";", "match", "=", "match", ".", "split", "(", "'.'", ")", ";", "if", "(", "_reserved", ".", "indexOf", "(", "match", "[", "0", "]", ")", "!==", "-", "1", ")", "{", "utils", ".", "throwError", "(", "'Reserved keyword \"'", "+", "match", "[", "0", "]", "+", "'\" attempted to be used as a variable'", ",", "self", ".", "line", ",", "self", ".", "filename", ")", ";", "}", "self", ".", "filterApplyIdx", ".", "push", "(", "self", ".", "out", ".", "length", ")", ";", "if", "(", "lastState", "===", "_t", ".", "CURLYOPEN", ")", "{", "if", "(", "match", ".", "length", ">", "1", ")", "{", "utils", ".", "throwError", "(", "'Unexpected dot'", ",", "self", ".", "line", ",", "self", ".", "filename", ")", ";", "}", "self", ".", "out", ".", "push", "(", "match", "[", "0", "]", ")", ";", "return", ";", "}", "self", ".", "out", ".", "push", "(", "self", ".", "checkMatch", "(", "match", ")", ")", ";", "}" ]
Parse variable token @param {{match: string, type: number, line: number}} token Lexer token object. @param {string} match Shortcut for token.match @param {number} lastState Lexer token type state. @return {undefined} @private
[ "Parse", "variable", "token" ]
edf9f82c8042b543e6f291f605430fac84702b2d
https://github.com/WebArtWork/derer/blob/edf9f82c8042b543e6f291f605430fac84702b2d/lib/parser.js#L368-L387
51,091
WebArtWork/derer
lib/parser.js
function (match) { var temp = match[0], result; function checkDot(ctx) { var c = ctx + temp, m = match, build = ''; build = '(typeof ' + c + ' !== "undefined" && ' + c + ' !== null'; utils.each(m, function (v, i) { if (i === 0) { return; } build += ' && ' + c + '.' + v + ' !== undefined && ' + c + '.' + v + ' !== null'; c += '.' + v; }); build += ')'; return build; } function buildDot(ctx) { return '(' + checkDot(ctx) + ' ? ' + ctx + match.join('.') + ' : "")'; } result = '(' + checkDot('_ctx.') + ' ? ' + buildDot('_ctx.') + ' : ' + buildDot('') + ')'; return '(' + result + ' !== null ? ' + result + ' : ' + '"" )'; }
javascript
function (match) { var temp = match[0], result; function checkDot(ctx) { var c = ctx + temp, m = match, build = ''; build = '(typeof ' + c + ' !== "undefined" && ' + c + ' !== null'; utils.each(m, function (v, i) { if (i === 0) { return; } build += ' && ' + c + '.' + v + ' !== undefined && ' + c + '.' + v + ' !== null'; c += '.' + v; }); build += ')'; return build; } function buildDot(ctx) { return '(' + checkDot(ctx) + ' ? ' + ctx + match.join('.') + ' : "")'; } result = '(' + checkDot('_ctx.') + ' ? ' + buildDot('_ctx.') + ' : ' + buildDot('') + ')'; return '(' + result + ' !== null ? ' + result + ' : ' + '"" )'; }
[ "function", "(", "match", ")", "{", "var", "temp", "=", "match", "[", "0", "]", ",", "result", ";", "function", "checkDot", "(", "ctx", ")", "{", "var", "c", "=", "ctx", "+", "temp", ",", "m", "=", "match", ",", "build", "=", "''", ";", "build", "=", "'(typeof '", "+", "c", "+", "' !== \"undefined\" && '", "+", "c", "+", "' !== null'", ";", "utils", ".", "each", "(", "m", ",", "function", "(", "v", ",", "i", ")", "{", "if", "(", "i", "===", "0", ")", "{", "return", ";", "}", "build", "+=", "' && '", "+", "c", "+", "'.'", "+", "v", "+", "' !== undefined && '", "+", "c", "+", "'.'", "+", "v", "+", "' !== null'", ";", "c", "+=", "'.'", "+", "v", ";", "}", ")", ";", "build", "+=", "')'", ";", "return", "build", ";", "}", "function", "buildDot", "(", "ctx", ")", "{", "return", "'('", "+", "checkDot", "(", "ctx", ")", "+", "' ? '", "+", "ctx", "+", "match", ".", "join", "(", "'.'", ")", "+", "' : \"\")'", ";", "}", "result", "=", "'('", "+", "checkDot", "(", "'_ctx.'", ")", "+", "' ? '", "+", "buildDot", "(", "'_ctx.'", ")", "+", "' : '", "+", "buildDot", "(", "''", ")", "+", "')'", ";", "return", "'('", "+", "result", "+", "' !== null ? '", "+", "result", "+", "' : '", "+", "'\"\" )'", ";", "}" ]
Return contextual dot-check string for a match @param {string} match Shortcut for token.match @private
[ "Return", "contextual", "dot", "-", "check", "string", "for", "a", "match" ]
edf9f82c8042b543e6f291f605430fac84702b2d
https://github.com/WebArtWork/derer/blob/edf9f82c8042b543e6f291f605430fac84702b2d/lib/parser.js#L394-L420
51,092
WebArtWork/derer
lib/parser.js
parseVariable
function parseVariable(str, line) { var tokens = lexer.read(utils.strip(str)), parser, out; parser = new TokenParser(tokens, filters, escape, line, opts.filename); out = parser.parse().join(''); if (parser.state.length) { utils.throwError('Unable to parse "' + str + '"', line, opts.filename); } /** * A parsed variable token. * @typedef {object} VarToken * @property {function} compile Method for compiling this token. */ return { compile: function () { return '_output += ' + out + ';\n'; } }; }
javascript
function parseVariable(str, line) { var tokens = lexer.read(utils.strip(str)), parser, out; parser = new TokenParser(tokens, filters, escape, line, opts.filename); out = parser.parse().join(''); if (parser.state.length) { utils.throwError('Unable to parse "' + str + '"', line, opts.filename); } /** * A parsed variable token. * @typedef {object} VarToken * @property {function} compile Method for compiling this token. */ return { compile: function () { return '_output += ' + out + ';\n'; } }; }
[ "function", "parseVariable", "(", "str", ",", "line", ")", "{", "var", "tokens", "=", "lexer", ".", "read", "(", "utils", ".", "strip", "(", "str", ")", ")", ",", "parser", ",", "out", ";", "parser", "=", "new", "TokenParser", "(", "tokens", ",", "filters", ",", "escape", ",", "line", ",", "opts", ".", "filename", ")", ";", "out", "=", "parser", ".", "parse", "(", ")", ".", "join", "(", "''", ")", ";", "if", "(", "parser", ".", "state", ".", "length", ")", "{", "utils", ".", "throwError", "(", "'Unable to parse \"'", "+", "str", "+", "'\"'", ",", "line", ",", "opts", ".", "filename", ")", ";", "}", "/**\n * A parsed variable token.\n * @typedef {object} VarToken\n * @property {function} compile Method for compiling this token.\n */", "return", "{", "compile", ":", "function", "(", ")", "{", "return", "'_output += '", "+", "out", "+", "';\\n'", ";", "}", "}", ";", "}" ]
Parse a variable. @param {string} str String contents of the variable, between <i>{{</i> and <i>}}</i> @param {number} line The line number that this variable starts on. @return {VarToken} Parsed variable token object. @private
[ "Parse", "a", "variable", "." ]
edf9f82c8042b543e6f291f605430fac84702b2d
https://github.com/WebArtWork/derer/blob/edf9f82c8042b543e6f291f605430fac84702b2d/lib/parser.js#L481-L503
51,093
WebArtWork/derer
lib/parser.js
parseTag
function parseTag(str, line) { var tokens, parser, chunks, tagName, tag, args, last; if (utils.startsWith(str, 'end')) { last = stack[stack.length - 1]; if (last && last.name === str.split(/\s+/)[0].replace(/^end/, '') && last.ends) { switch (last.name) { case 'autoescape': escape = opts.autoescape; break; case 'raw': inRaw = false; break; } stack.pop(); return; } if (!inRaw) { utils.throwError('Unexpected end of tag "' + str.replace(/^end/, '') + '"', line, opts.filename); } } if (inRaw) { return; } chunks = str.split(/\s+(.+)?/); tagName = chunks.shift(); if (!tags.hasOwnProperty(tagName)) { utils.throwError('Unexpected tag "' + str + '"', line, opts.filename); } tokens = lexer.read(utils.strip(chunks.join(' '))); parser = new TokenParser(tokens, filters, false, line, opts.filename); tag = tags[tagName]; /** * Define custom parsing methods for your tag. * @callback parse * * @example * exports.parse = function (str, line, parser, types, options, swig) { * parser.on('start', function () { * // ... * }); * parser.on(types.STRING, function (token) { * // ... * }); * }; * * @param {string} str The full token string of the tag. * @param {number} line The line number that this tag appears on. * @param {TokenParser} parser A TokenParser instance. * @param {TYPES} types Lexer token type enum. * @param {TagToken[]} stack The current stack of open tags. * @param {SwigOpts} options Swig Options Object. * @param {object} swig The Swig instance (gives acces to loaders, parsers, etc) */ if (!tag.parse(chunks[1], line, parser, _t, stack, opts, swig)) { utils.throwError('Unexpected tag "' + tagName + '"', line, opts.filename); } parser.parse(); args = parser.out; switch (tagName) { case 'autoescape': escape = (args[0] !== 'false') ? args[0] : false; break; case 'raw': inRaw = true; break; } /** * A parsed tag token. * @typedef {Object} TagToken * @property {compile} [compile] Method for compiling this token. * @property {array} [args] Array of arguments for the tag. * @property {Token[]} [content=[]] An array of tokens that are children of this Token. * @property {boolean} [ends] Whether or not this tag requires an end tag. * @property {string} name The name of this tag. */ return { block: !!tags[tagName].block, compile: tag.compile, args: args, content: [], ends: tag.ends, name: tagName }; }
javascript
function parseTag(str, line) { var tokens, parser, chunks, tagName, tag, args, last; if (utils.startsWith(str, 'end')) { last = stack[stack.length - 1]; if (last && last.name === str.split(/\s+/)[0].replace(/^end/, '') && last.ends) { switch (last.name) { case 'autoescape': escape = opts.autoescape; break; case 'raw': inRaw = false; break; } stack.pop(); return; } if (!inRaw) { utils.throwError('Unexpected end of tag "' + str.replace(/^end/, '') + '"', line, opts.filename); } } if (inRaw) { return; } chunks = str.split(/\s+(.+)?/); tagName = chunks.shift(); if (!tags.hasOwnProperty(tagName)) { utils.throwError('Unexpected tag "' + str + '"', line, opts.filename); } tokens = lexer.read(utils.strip(chunks.join(' '))); parser = new TokenParser(tokens, filters, false, line, opts.filename); tag = tags[tagName]; /** * Define custom parsing methods for your tag. * @callback parse * * @example * exports.parse = function (str, line, parser, types, options, swig) { * parser.on('start', function () { * // ... * }); * parser.on(types.STRING, function (token) { * // ... * }); * }; * * @param {string} str The full token string of the tag. * @param {number} line The line number that this tag appears on. * @param {TokenParser} parser A TokenParser instance. * @param {TYPES} types Lexer token type enum. * @param {TagToken[]} stack The current stack of open tags. * @param {SwigOpts} options Swig Options Object. * @param {object} swig The Swig instance (gives acces to loaders, parsers, etc) */ if (!tag.parse(chunks[1], line, parser, _t, stack, opts, swig)) { utils.throwError('Unexpected tag "' + tagName + '"', line, opts.filename); } parser.parse(); args = parser.out; switch (tagName) { case 'autoescape': escape = (args[0] !== 'false') ? args[0] : false; break; case 'raw': inRaw = true; break; } /** * A parsed tag token. * @typedef {Object} TagToken * @property {compile} [compile] Method for compiling this token. * @property {array} [args] Array of arguments for the tag. * @property {Token[]} [content=[]] An array of tokens that are children of this Token. * @property {boolean} [ends] Whether or not this tag requires an end tag. * @property {string} name The name of this tag. */ return { block: !!tags[tagName].block, compile: tag.compile, args: args, content: [], ends: tag.ends, name: tagName }; }
[ "function", "parseTag", "(", "str", ",", "line", ")", "{", "var", "tokens", ",", "parser", ",", "chunks", ",", "tagName", ",", "tag", ",", "args", ",", "last", ";", "if", "(", "utils", ".", "startsWith", "(", "str", ",", "'end'", ")", ")", "{", "last", "=", "stack", "[", "stack", ".", "length", "-", "1", "]", ";", "if", "(", "last", "&&", "last", ".", "name", "===", "str", ".", "split", "(", "/", "\\s+", "/", ")", "[", "0", "]", ".", "replace", "(", "/", "^end", "/", ",", "''", ")", "&&", "last", ".", "ends", ")", "{", "switch", "(", "last", ".", "name", ")", "{", "case", "'autoescape'", ":", "escape", "=", "opts", ".", "autoescape", ";", "break", ";", "case", "'raw'", ":", "inRaw", "=", "false", ";", "break", ";", "}", "stack", ".", "pop", "(", ")", ";", "return", ";", "}", "if", "(", "!", "inRaw", ")", "{", "utils", ".", "throwError", "(", "'Unexpected end of tag \"'", "+", "str", ".", "replace", "(", "/", "^end", "/", ",", "''", ")", "+", "'\"'", ",", "line", ",", "opts", ".", "filename", ")", ";", "}", "}", "if", "(", "inRaw", ")", "{", "return", ";", "}", "chunks", "=", "str", ".", "split", "(", "/", "\\s+(.+)?", "/", ")", ";", "tagName", "=", "chunks", ".", "shift", "(", ")", ";", "if", "(", "!", "tags", ".", "hasOwnProperty", "(", "tagName", ")", ")", "{", "utils", ".", "throwError", "(", "'Unexpected tag \"'", "+", "str", "+", "'\"'", ",", "line", ",", "opts", ".", "filename", ")", ";", "}", "tokens", "=", "lexer", ".", "read", "(", "utils", ".", "strip", "(", "chunks", ".", "join", "(", "' '", ")", ")", ")", ";", "parser", "=", "new", "TokenParser", "(", "tokens", ",", "filters", ",", "false", ",", "line", ",", "opts", ".", "filename", ")", ";", "tag", "=", "tags", "[", "tagName", "]", ";", "/**\n * Define custom parsing methods for your tag.\n * @callback parse\n *\n * @example\n * exports.parse = function (str, line, parser, types, options, swig) {\n * parser.on('start', function () {\n * // ...\n * });\n * parser.on(types.STRING, function (token) {\n * // ...\n * });\n * };\n *\n * @param {string} str The full token string of the tag.\n * @param {number} line The line number that this tag appears on.\n * @param {TokenParser} parser A TokenParser instance.\n * @param {TYPES} types Lexer token type enum.\n * @param {TagToken[]} stack The current stack of open tags.\n * @param {SwigOpts} options Swig Options Object.\n * @param {object} swig The Swig instance (gives acces to loaders, parsers, etc)\n */", "if", "(", "!", "tag", ".", "parse", "(", "chunks", "[", "1", "]", ",", "line", ",", "parser", ",", "_t", ",", "stack", ",", "opts", ",", "swig", ")", ")", "{", "utils", ".", "throwError", "(", "'Unexpected tag \"'", "+", "tagName", "+", "'\"'", ",", "line", ",", "opts", ".", "filename", ")", ";", "}", "parser", ".", "parse", "(", ")", ";", "args", "=", "parser", ".", "out", ";", "switch", "(", "tagName", ")", "{", "case", "'autoescape'", ":", "escape", "=", "(", "args", "[", "0", "]", "!==", "'false'", ")", "?", "args", "[", "0", "]", ":", "false", ";", "break", ";", "case", "'raw'", ":", "inRaw", "=", "true", ";", "break", ";", "}", "/**\n * A parsed tag token.\n * @typedef {Object} TagToken\n * @property {compile} [compile] Method for compiling this token.\n * @property {array} [args] Array of arguments for the tag.\n * @property {Token[]} [content=[]] An array of tokens that are children of this Token.\n * @property {boolean} [ends] Whether or not this tag requires an end tag.\n * @property {string} name The name of this tag.\n */", "return", "{", "block", ":", "!", "!", "tags", "[", "tagName", "]", ".", "block", ",", "compile", ":", "tag", ".", "compile", ",", "args", ":", "args", ",", "content", ":", "[", "]", ",", "ends", ":", "tag", ".", "ends", ",", "name", ":", "tagName", "}", ";", "}" ]
Parse a tag. @param {string} str String contents of the tag, between <i>{%</i> and <i>%}</i> @param {number} line The line number that this tag starts on. @return {TagToken} Parsed token object. @private
[ "Parse", "a", "tag", "." ]
edf9f82c8042b543e6f291f605430fac84702b2d
https://github.com/WebArtWork/derer/blob/edf9f82c8042b543e6f291f605430fac84702b2d/lib/parser.js#L513-L606
51,094
vkiding/judpack-lib
src/platforms/PlatformApiPoly.js
getBuildArgs
function getBuildArgs(options) { // if no options passed, empty object will be returned if (!options) return []; var downstreamArgs = []; var argNames =[ 'debug', 'release', 'device', 'emulator', 'nobuild', 'list' ]; argNames.forEach(function(flag) { if (options[flag]) { downstreamArgs.push('--' + flag); } }); if (options.buildConfig) { downstreamArgs.push('--buildConfig=' + options.buildConfig); } if (options.target) { downstreamArgs.push('--target=' + options.target); } if (options.archs) { downstreamArgs.push('--archs=' + options.archs); } var unparsedArgs = options.argv || []; return downstreamArgs.concat(unparsedArgs); }
javascript
function getBuildArgs(options) { // if no options passed, empty object will be returned if (!options) return []; var downstreamArgs = []; var argNames =[ 'debug', 'release', 'device', 'emulator', 'nobuild', 'list' ]; argNames.forEach(function(flag) { if (options[flag]) { downstreamArgs.push('--' + flag); } }); if (options.buildConfig) { downstreamArgs.push('--buildConfig=' + options.buildConfig); } if (options.target) { downstreamArgs.push('--target=' + options.target); } if (options.archs) { downstreamArgs.push('--archs=' + options.archs); } var unparsedArgs = options.argv || []; return downstreamArgs.concat(unparsedArgs); }
[ "function", "getBuildArgs", "(", "options", ")", "{", "// if no options passed, empty object will be returned", "if", "(", "!", "options", ")", "return", "[", "]", ";", "var", "downstreamArgs", "=", "[", "]", ";", "var", "argNames", "=", "[", "'debug'", ",", "'release'", ",", "'device'", ",", "'emulator'", ",", "'nobuild'", ",", "'list'", "]", ";", "argNames", ".", "forEach", "(", "function", "(", "flag", ")", "{", "if", "(", "options", "[", "flag", "]", ")", "{", "downstreamArgs", ".", "push", "(", "'--'", "+", "flag", ")", ";", "}", "}", ")", ";", "if", "(", "options", ".", "buildConfig", ")", "{", "downstreamArgs", ".", "push", "(", "'--buildConfig='", "+", "options", ".", "buildConfig", ")", ";", "}", "if", "(", "options", ".", "target", ")", "{", "downstreamArgs", ".", "push", "(", "'--target='", "+", "options", ".", "target", ")", ";", "}", "if", "(", "options", ".", "archs", ")", "{", "downstreamArgs", ".", "push", "(", "'--archs='", "+", "options", ".", "archs", ")", ";", "}", "var", "unparsedArgs", "=", "options", ".", "argv", "||", "[", "]", ";", "return", "downstreamArgs", ".", "concat", "(", "unparsedArgs", ")", ";", "}" ]
Reconstructs the buildOptions tat will be passed along to platform scripts. This is an ugly temporary fix. The code spawning or otherwise calling into platform code should be dealing with this based on the parsed args object. @param {Object} options A build options set, passed to `build` method @return {String[]} An array or arguments which can be passed to `create` build script.
[ "Reconstructs", "the", "buildOptions", "tat", "will", "be", "passed", "along", "to", "platform", "scripts", ".", "This", "is", "an", "ugly", "temporary", "fix", ".", "The", "code", "spawning", "or", "otherwise", "calling", "into", "platform", "code", "should", "be", "dealing", "with", "this", "based", "on", "the", "parsed", "args", "object", "." ]
8657cecfec68221109279106adca8dbc81f430f4
https://github.com/vkiding/judpack-lib/blob/8657cecfec68221109279106adca8dbc81f430f4/src/platforms/PlatformApiPoly.js#L519-L551
51,095
vkiding/judpack-lib
src/platforms/PlatformApiPoly.js
getPlatformVersion
function getPlatformVersion (platformRoot) { var versionFile = path.join(platformRoot, 'cordova/version'); if (!fs.existsSync(versionFile)) { return null; } var version = shell.cat(versionFile).match(/VERSION\s=\s["'](.*)["'];/m); return version && version[1]; }
javascript
function getPlatformVersion (platformRoot) { var versionFile = path.join(platformRoot, 'cordova/version'); if (!fs.existsSync(versionFile)) { return null; } var version = shell.cat(versionFile).match(/VERSION\s=\s["'](.*)["'];/m); return version && version[1]; }
[ "function", "getPlatformVersion", "(", "platformRoot", ")", "{", "var", "versionFile", "=", "path", ".", "join", "(", "platformRoot", ",", "'cordova/version'", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "versionFile", ")", ")", "{", "return", "null", ";", "}", "var", "version", "=", "shell", ".", "cat", "(", "versionFile", ")", ".", "match", "(", "/", "VERSION\\s=\\s[\"'](.*)[\"'];", "/", "m", ")", ";", "return", "version", "&&", "version", "[", "1", "]", ";", "}" ]
Gets platform version from 'version' file @param {String} platformRoot Platform location @return {String|null} Stringified version of platform or null if it is not possible to retrieve version
[ "Gets", "platform", "version", "from", "version", "file" ]
8657cecfec68221109279106adca8dbc81f430f4
https://github.com/vkiding/judpack-lib/blob/8657cecfec68221109279106adca8dbc81f430f4/src/platforms/PlatformApiPoly.js#L732-L741
51,096
robojones/functs
functs.js
functs
function functs(...f) { /** * execute all included functions * @param {...*} [args] - arguments passed to all included functions * @returns {*[]} */ function functs(...args) { return functs.run(this, args); } if(Array.isArray(f[0])) { f = f[0]; } functs._f = f.filter((f) => { return typeof f === 'function'; }); functs.add = add.bind(functs); functs.remove = remove.bind(functs); functs.run = run.bind(functs); return functs; }
javascript
function functs(...f) { /** * execute all included functions * @param {...*} [args] - arguments passed to all included functions * @returns {*[]} */ function functs(...args) { return functs.run(this, args); } if(Array.isArray(f[0])) { f = f[0]; } functs._f = f.filter((f) => { return typeof f === 'function'; }); functs.add = add.bind(functs); functs.remove = remove.bind(functs); functs.run = run.bind(functs); return functs; }
[ "function", "functs", "(", "...", "f", ")", "{", "/**\n * execute all included functions\n * @param {...*} [args] - arguments passed to all included functions\n * @returns {*[]}\n */", "function", "functs", "(", "...", "args", ")", "{", "return", "functs", ".", "run", "(", "this", ",", "args", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "f", "[", "0", "]", ")", ")", "{", "f", "=", "f", "[", "0", "]", ";", "}", "functs", ".", "_f", "=", "f", ".", "filter", "(", "(", "f", ")", "=>", "{", "return", "typeof", "f", "===", "'function'", ";", "}", ")", ";", "functs", ".", "add", "=", "add", ".", "bind", "(", "functs", ")", ";", "functs", ".", "remove", "=", "remove", ".", "bind", "(", "functs", ")", ";", "functs", ".", "run", "=", "run", ".", "bind", "(", "functs", ")", ";", "return", "functs", ";", "}" ]
merge multiple functions into one @param {...function} [f] - functions to merge @returns {function}
[ "merge", "multiple", "functions", "into", "one" ]
ecb2d92f79cc1352a1f5ab90eb78c1c958295fe6
https://github.com/robojones/functs/blob/ecb2d92f79cc1352a1f5ab90eb78c1c958295fe6/functs.js#L9-L30
51,097
robojones/functs
functs.js
add
function add(...f) { if(Array.isArray(f[0])) { f = f[0]; } f = f.filter((f) => { return typeof f === 'function'; }); this._f.push.apply(this._f, f); return f; }
javascript
function add(...f) { if(Array.isArray(f[0])) { f = f[0]; } f = f.filter((f) => { return typeof f === 'function'; }); this._f.push.apply(this._f, f); return f; }
[ "function", "add", "(", "...", "f", ")", "{", "if", "(", "Array", ".", "isArray", "(", "f", "[", "0", "]", ")", ")", "{", "f", "=", "f", "[", "0", "]", ";", "}", "f", "=", "f", ".", "filter", "(", "(", "f", ")", "=>", "{", "return", "typeof", "f", "===", "'function'", ";", "}", ")", ";", "this", ".", "_f", ".", "push", ".", "apply", "(", "this", ".", "_f", ",", "f", ")", ";", "return", "f", ";", "}" ]
add functions to the functs-object @param {...function|function[]} f - functions to be added @returns {function[]}
[ "add", "functions", "to", "the", "functs", "-", "object" ]
ecb2d92f79cc1352a1f5ab90eb78c1c958295fe6
https://github.com/robojones/functs/blob/ecb2d92f79cc1352a1f5ab90eb78c1c958295fe6/functs.js#L38-L47
51,098
robojones/functs
functs.js
remove
function remove(...key) { const self = this; if(Array.isArray(key[0])) { key = key[0]; } key.forEach(k => { self._f = self._f.filter(f => { return f !== k; }); }); }
javascript
function remove(...key) { const self = this; if(Array.isArray(key[0])) { key = key[0]; } key.forEach(k => { self._f = self._f.filter(f => { return f !== k; }); }); }
[ "function", "remove", "(", "...", "key", ")", "{", "const", "self", "=", "this", ";", "if", "(", "Array", ".", "isArray", "(", "key", "[", "0", "]", ")", ")", "{", "key", "=", "key", "[", "0", "]", ";", "}", "key", ".", "forEach", "(", "k", "=>", "{", "self", ".", "_f", "=", "self", ".", "_f", ".", "filter", "(", "f", "=>", "{", "return", "f", "!==", "k", ";", "}", ")", ";", "}", ")", ";", "}" ]
remove functions from the functs-object @param {...function|function[]} f - functions to be removed
[ "remove", "functions", "from", "the", "functs", "-", "object" ]
ecb2d92f79cc1352a1f5ab90eb78c1c958295fe6
https://github.com/robojones/functs/blob/ecb2d92f79cc1352a1f5ab90eb78c1c958295fe6/functs.js#L54-L65
51,099
robojones/functs
functs.js
run
function run(thisArg, args) { var end = -1; const r = this._f.map((f, i) => { if(end === -1) { return f.apply(thisArg, args.concat(abort)); } function abort() { end = i; } }); if(end === -1) { return r; } return r.slice(0, end); }
javascript
function run(thisArg, args) { var end = -1; const r = this._f.map((f, i) => { if(end === -1) { return f.apply(thisArg, args.concat(abort)); } function abort() { end = i; } }); if(end === -1) { return r; } return r.slice(0, end); }
[ "function", "run", "(", "thisArg", ",", "args", ")", "{", "var", "end", "=", "-", "1", ";", "const", "r", "=", "this", ".", "_f", ".", "map", "(", "(", "f", ",", "i", ")", "=>", "{", "if", "(", "end", "===", "-", "1", ")", "{", "return", "f", ".", "apply", "(", "thisArg", ",", "args", ".", "concat", "(", "abort", ")", ")", ";", "}", "function", "abort", "(", ")", "{", "end", "=", "i", ";", "}", "}", ")", ";", "if", "(", "end", "===", "-", "1", ")", "{", "return", "r", ";", "}", "return", "r", ".", "slice", "(", "0", ",", "end", ")", ";", "}" ]
execute all included functions @param {*} thisArg - thisArg to be applied on all included functions @param {*[]} args - array of arguments passed to all included functions
[ "execute", "all", "included", "functions" ]
ecb2d92f79cc1352a1f5ab90eb78c1c958295fe6
https://github.com/robojones/functs/blob/ecb2d92f79cc1352a1f5ab90eb78c1c958295fe6/functs.js#L73-L88