id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
37,900
daffl/connect-injector
lib/connect-injector.js
function (data, encoding) { var self = this; var _super = this._super.bind(this); if (!this._interceptCheck()) { debug('not intercepting, ending with original .end'); return _super(data, encoding); } if (data) { this.write(data, encoding); } debug('resetting to original response.write'); this.write = oldWrite; // Responses without a body can just be ended if(!this._hasBody || !this._interceptBuffer) { debug('ending empty resopnse without injecting anything'); return _super(); } var gzipped = this.getHeader('content-encoding') === 'gzip'; var chain = Q(this._interceptBuffer.getContents()); if(gzipped) { debug('unzipping content'); // Unzip the buffer chain = chain.then(function(buffer) { return Q.nfcall(zlib.gunzip, buffer); }); } this.injectors.forEach(function(injector) { // Run all converters, if they are active // In series, using the previous output if(injector.active) { debug('adding injector to chain'); var converter = injector.converter.bind(self); chain = chain.then(function(prev) { return Q.nfcall(converter, prev, req, res); }); } }); if(gzipped) { debug('re-zipping content'); // Zip it again chain = chain.then(function(result) { return Q.nfcall(zlib.gzip, result); }); } chain.then(_super).fail(function(e) { debug('injector chain failed, emitting error event'); self.emit('error', e); }); return true; }
javascript
function (data, encoding) { var self = this; var _super = this._super.bind(this); if (!this._interceptCheck()) { debug('not intercepting, ending with original .end'); return _super(data, encoding); } if (data) { this.write(data, encoding); } debug('resetting to original response.write'); this.write = oldWrite; // Responses without a body can just be ended if(!this._hasBody || !this._interceptBuffer) { debug('ending empty resopnse without injecting anything'); return _super(); } var gzipped = this.getHeader('content-encoding') === 'gzip'; var chain = Q(this._interceptBuffer.getContents()); if(gzipped) { debug('unzipping content'); // Unzip the buffer chain = chain.then(function(buffer) { return Q.nfcall(zlib.gunzip, buffer); }); } this.injectors.forEach(function(injector) { // Run all converters, if they are active // In series, using the previous output if(injector.active) { debug('adding injector to chain'); var converter = injector.converter.bind(self); chain = chain.then(function(prev) { return Q.nfcall(converter, prev, req, res); }); } }); if(gzipped) { debug('re-zipping content'); // Zip it again chain = chain.then(function(result) { return Q.nfcall(zlib.gzip, result); }); } chain.then(_super).fail(function(e) { debug('injector chain failed, emitting error event'); self.emit('error', e); }); return true; }
[ "function", "(", "data", ",", "encoding", ")", "{", "var", "self", "=", "this", ";", "var", "_super", "=", "this", ".", "_super", ".", "bind", "(", "this", ")", ";", "if", "(", "!", "this", ".", "_interceptCheck", "(", ")", ")", "{", "debug", "(", "'not intercepting, ending with original .end'", ")", ";", "return", "_super", "(", "data", ",", "encoding", ")", ";", "}", "if", "(", "data", ")", "{", "this", ".", "write", "(", "data", ",", "encoding", ")", ";", "}", "debug", "(", "'resetting to original response.write'", ")", ";", "this", ".", "write", "=", "oldWrite", ";", "// Responses without a body can just be ended", "if", "(", "!", "this", ".", "_hasBody", "||", "!", "this", ".", "_interceptBuffer", ")", "{", "debug", "(", "'ending empty resopnse without injecting anything'", ")", ";", "return", "_super", "(", ")", ";", "}", "var", "gzipped", "=", "this", ".", "getHeader", "(", "'content-encoding'", ")", "===", "'gzip'", ";", "var", "chain", "=", "Q", "(", "this", ".", "_interceptBuffer", ".", "getContents", "(", ")", ")", ";", "if", "(", "gzipped", ")", "{", "debug", "(", "'unzipping content'", ")", ";", "// Unzip the buffer", "chain", "=", "chain", ".", "then", "(", "function", "(", "buffer", ")", "{", "return", "Q", ".", "nfcall", "(", "zlib", ".", "gunzip", ",", "buffer", ")", ";", "}", ")", ";", "}", "this", ".", "injectors", ".", "forEach", "(", "function", "(", "injector", ")", "{", "// Run all converters, if they are active", "// In series, using the previous output", "if", "(", "injector", ".", "active", ")", "{", "debug", "(", "'adding injector to chain'", ")", ";", "var", "converter", "=", "injector", ".", "converter", ".", "bind", "(", "self", ")", ";", "chain", "=", "chain", ".", "then", "(", "function", "(", "prev", ")", "{", "return", "Q", ".", "nfcall", "(", "converter", ",", "prev", ",", "req", ",", "res", ")", ";", "}", ")", ";", "}", "}", ")", ";", "if", "(", "gzipped", ")", "{", "debug", "(", "'re-zipping content'", ")", ";", "// Zip it again", "chain", "=", "chain", ".", "then", "(", "function", "(", "result", ")", "{", "return", "Q", ".", "nfcall", "(", "zlib", ".", "gzip", ",", "result", ")", ";", "}", ")", ";", "}", "chain", ".", "then", "(", "_super", ")", ".", "fail", "(", "function", "(", "e", ")", "{", "debug", "(", "'injector chain failed, emitting error event'", ")", ";", "self", ".", "emit", "(", "'error'", ",", "e", ")", ";", "}", ")", ";", "return", "true", ";", "}" ]
End the request.
[ "End", "the", "request", "." ]
a23b7c93b60464ca43273c58cba2c07b890124f0
https://github.com/daffl/connect-injector/blob/a23b7c93b60464ca43273c58cba2c07b890124f0/lib/connect-injector.js#L99-L158
37,901
jonschlinkert/export-files
index.js
isJavaScriptFile
function isJavaScriptFile(filepath) { if (!fs.statSync(filepath).isFile()) { return false; } if (path.basename(filepath) === 'index.js') { return false; } return filepath.slice(-3) === '.js'; }
javascript
function isJavaScriptFile(filepath) { if (!fs.statSync(filepath).isFile()) { return false; } if (path.basename(filepath) === 'index.js') { return false; } return filepath.slice(-3) === '.js'; }
[ "function", "isJavaScriptFile", "(", "filepath", ")", "{", "if", "(", "!", "fs", ".", "statSync", "(", "filepath", ")", ".", "isFile", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "path", ".", "basename", "(", "filepath", ")", "===", "'index.js'", ")", "{", "return", "false", ";", "}", "return", "filepath", ".", "slice", "(", "-", "3", ")", "===", "'.js'", ";", "}" ]
Return true if the file is a `.js` file. @param {String} filepath @return {Boolean}
[ "Return", "true", "if", "the", "file", "is", "a", ".", "js", "file", "." ]
2e99117e0925da4ca3154baf1bd404e2a4269a97
https://github.com/jonschlinkert/export-files/blob/2e99117e0925da4ca3154baf1bd404e2a4269a97/index.js#L42-L50
37,902
cuttingsoup/react-native-firebase-local-cache
dist/index.js
onValue
function onValue(dbRef, snapCallback, processedCallback, cancelCallbackOrContext, context) { var storageKey = getStorageKeyFromDbRef(dbRef, 'value'); return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) { // Called processedCallback with cached value. if (value !== null) { var cachedVal = JSON.parse(value); callWithContext(processedCallback, cachedVal, cancelCallbackOrContext, context); } }).then(function () { var callbackPeak = function callbackPeak(snap) { var processed = snapCallback.bind(this)(snap); snapPeak[storageKey] = JSON.stringify(processed); processedCallback.bind(this)(processed); }; dbRef.on('value', callbackPeak, cancelCallbackOrContext, context); }); }
javascript
function onValue(dbRef, snapCallback, processedCallback, cancelCallbackOrContext, context) { var storageKey = getStorageKeyFromDbRef(dbRef, 'value'); return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) { // Called processedCallback with cached value. if (value !== null) { var cachedVal = JSON.parse(value); callWithContext(processedCallback, cachedVal, cancelCallbackOrContext, context); } }).then(function () { var callbackPeak = function callbackPeak(snap) { var processed = snapCallback.bind(this)(snap); snapPeak[storageKey] = JSON.stringify(processed); processedCallback.bind(this)(processed); }; dbRef.on('value', callbackPeak, cancelCallbackOrContext, context); }); }
[ "function", "onValue", "(", "dbRef", ",", "snapCallback", ",", "processedCallback", ",", "cancelCallbackOrContext", ",", "context", ")", "{", "var", "storageKey", "=", "getStorageKeyFromDbRef", "(", "dbRef", ",", "'value'", ")", ";", "return", "_reactNative", ".", "AsyncStorage", ".", "getItem", "(", "storageKey", ")", ".", "then", "(", "function", "(", "value", ")", "{", "// Called processedCallback with cached value.", "if", "(", "value", "!==", "null", ")", "{", "var", "cachedVal", "=", "JSON", ".", "parse", "(", "value", ")", ";", "callWithContext", "(", "processedCallback", ",", "cachedVal", ",", "cancelCallbackOrContext", ",", "context", ")", ";", "}", "}", ")", ".", "then", "(", "function", "(", ")", "{", "var", "callbackPeak", "=", "function", "callbackPeak", "(", "snap", ")", "{", "var", "processed", "=", "snapCallback", ".", "bind", "(", "this", ")", "(", "snap", ")", ";", "snapPeak", "[", "storageKey", "]", "=", "JSON", ".", "stringify", "(", "processed", ")", ";", "processedCallback", ".", "bind", "(", "this", ")", "(", "processed", ")", ";", "}", ";", "dbRef", ".", "on", "(", "'value'", ",", "callbackPeak", ",", "cancelCallbackOrContext", ",", "context", ")", ";", "}", ")", ";", "}" ]
Create an 'value' on listener that will first return a cached version of the endpoint. @param {firebase.database.Reference} dbRef Firebase database reference to listen at. @param {Function} snapCallback Callback called when a new snapshot is available. Should return a JSON.stringify-able object that will be cached. @param {Function} processedCallback Callback called with data returned by snapCallback, or cached data if available. @param {Function|Object} cancelCallbackOrContext An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred. @param {Object} context If provided, this object will be used as this when calling your callback(s). @returns {Promise} Resolves when the cache has been read and listener attached to DB ref.
[ "Create", "an", "value", "on", "listener", "that", "will", "first", "return", "a", "cached", "version", "of", "the", "endpoint", "." ]
db755a66d6936710e85161ecfced56a1ea432887
https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L58-L75
37,903
cuttingsoup/react-native-firebase-local-cache
dist/index.js
offValue
function offValue(dbRef) { var storageKey = getStorageKeyFromDbRef(dbRef, 'value'); //Turn listener off. dbRef.off(); return new Promise(function (resolve, reject) { if (storageKey in snapPeak) { var dataToCache = snapPeak[storageKey]; delete snapPeak[storageKey]; resolve(_reactNative.AsyncStorage.setItem(storageKey, dataToCache)); } else { resolve(null); } }); }
javascript
function offValue(dbRef) { var storageKey = getStorageKeyFromDbRef(dbRef, 'value'); //Turn listener off. dbRef.off(); return new Promise(function (resolve, reject) { if (storageKey in snapPeak) { var dataToCache = snapPeak[storageKey]; delete snapPeak[storageKey]; resolve(_reactNative.AsyncStorage.setItem(storageKey, dataToCache)); } else { resolve(null); } }); }
[ "function", "offValue", "(", "dbRef", ")", "{", "var", "storageKey", "=", "getStorageKeyFromDbRef", "(", "dbRef", ",", "'value'", ")", ";", "//Turn listener off.", "dbRef", ".", "off", "(", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "storageKey", "in", "snapPeak", ")", "{", "var", "dataToCache", "=", "snapPeak", "[", "storageKey", "]", ";", "delete", "snapPeak", "[", "storageKey", "]", ";", "resolve", "(", "_reactNative", ".", "AsyncStorage", ".", "setItem", "(", "storageKey", ",", "dataToCache", ")", ")", ";", "}", "else", "{", "resolve", "(", "null", ")", ";", "}", "}", ")", ";", "}" ]
Remove any listeners from the specified ref, and save any existing data to the cache. @param {firebase.database.Reference} dbRef Firebase database reference to clear. @returns {Promise} Promis that will resolve after listener is switched off and cache has been written.
[ "Remove", "any", "listeners", "from", "the", "specified", "ref", "and", "save", "any", "existing", "data", "to", "the", "cache", "." ]
db755a66d6936710e85161ecfced56a1ea432887
https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L83-L98
37,904
cuttingsoup/react-native-firebase-local-cache
dist/index.js
onChildAdded
function onChildAdded(dbRef, fromCacheCallback, newDataArrivingCallback, snapCallback, cancelCallbackOrContext, context) { var storageKey = getStorageKeyFromDbRef(dbRef, 'child_added'); return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) { // Called processedCallback with cached value. if (value !== null) { var cachedVal = JSON.parse(value); callWithContext(fromCacheCallback, cachedVal, cancelCallbackOrContext, context); } }).then(function () { var firstData = true; var callbackIntercept = function callbackIntercept(snap) { //Call the data arriving callback the first time new data comes in. if (firstData) { firstData = false; newDataArrivingCallback.bind(this)(); } //Then call the snapCallback as normal. snapCallback.bind(this)(snap); }; dbRef.on('child_added', callbackIntercept, cancelCallbackOrContext, context); }); }
javascript
function onChildAdded(dbRef, fromCacheCallback, newDataArrivingCallback, snapCallback, cancelCallbackOrContext, context) { var storageKey = getStorageKeyFromDbRef(dbRef, 'child_added'); return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) { // Called processedCallback with cached value. if (value !== null) { var cachedVal = JSON.parse(value); callWithContext(fromCacheCallback, cachedVal, cancelCallbackOrContext, context); } }).then(function () { var firstData = true; var callbackIntercept = function callbackIntercept(snap) { //Call the data arriving callback the first time new data comes in. if (firstData) { firstData = false; newDataArrivingCallback.bind(this)(); } //Then call the snapCallback as normal. snapCallback.bind(this)(snap); }; dbRef.on('child_added', callbackIntercept, cancelCallbackOrContext, context); }); }
[ "function", "onChildAdded", "(", "dbRef", ",", "fromCacheCallback", ",", "newDataArrivingCallback", ",", "snapCallback", ",", "cancelCallbackOrContext", ",", "context", ")", "{", "var", "storageKey", "=", "getStorageKeyFromDbRef", "(", "dbRef", ",", "'child_added'", ")", ";", "return", "_reactNative", ".", "AsyncStorage", ".", "getItem", "(", "storageKey", ")", ".", "then", "(", "function", "(", "value", ")", "{", "// Called processedCallback with cached value.", "if", "(", "value", "!==", "null", ")", "{", "var", "cachedVal", "=", "JSON", ".", "parse", "(", "value", ")", ";", "callWithContext", "(", "fromCacheCallback", ",", "cachedVal", ",", "cancelCallbackOrContext", ",", "context", ")", ";", "}", "}", ")", ".", "then", "(", "function", "(", ")", "{", "var", "firstData", "=", "true", ";", "var", "callbackIntercept", "=", "function", "callbackIntercept", "(", "snap", ")", "{", "//Call the data arriving callback the first time new data comes in.", "if", "(", "firstData", ")", "{", "firstData", "=", "false", ";", "newDataArrivingCallback", ".", "bind", "(", "this", ")", "(", ")", ";", "}", "//Then call the snapCallback as normal.", "snapCallback", ".", "bind", "(", "this", ")", "(", "snap", ")", ";", "}", ";", "dbRef", ".", "on", "(", "'child_added'", ",", "callbackIntercept", ",", "cancelCallbackOrContext", ",", "context", ")", ";", "}", ")", ";", "}" ]
Create an 'child_added' on listener that will first return any cached data saved by a call to offChildAdded. When fresh data arrives, newDataArrivingCallback will be called once, followed by the standard snap callback. From this point on only the snapCallback will be called. @param {firebase.database.Reference} dbRef Firebase database reference to listen at. @param {*} fromCacheCallback Callback that will be called with cached data if any is available. @param {*} newDataArrivingCallback Callback called immediately before fresh data starts arriving. @param {*} snapCallback Callback called when new data snapshots arrive from the server. @param {*} cancelCallbackOrContext Optional callback that will be called in the case of an error, e.g. forbidden. @param {*} context Optional context that will be bound to `this` in callbacks. @returns {Promise} Resolves when the cache has been read and listener attached to DB ref.
[ "Create", "an", "child_added", "on", "listener", "that", "will", "first", "return", "any", "cached", "data", "saved", "by", "a", "call", "to", "offChildAdded", ".", "When", "fresh", "data", "arrives", "newDataArrivingCallback", "will", "be", "called", "once", "followed", "by", "the", "standard", "snap", "callback", ".", "From", "this", "point", "on", "only", "the", "snapCallback", "will", "be", "called", "." ]
db755a66d6936710e85161ecfced56a1ea432887
https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L111-L135
37,905
cuttingsoup/react-native-firebase-local-cache
dist/index.js
offChildAdded
function offChildAdded(dbRef, dataToCache) { var storageKey = getStorageKeyFromDbRef(dbRef, 'child_added'); //Turn listener off. dbRef.off(); return new Promise(function (resolve, reject) { resolve(_reactNative.AsyncStorage.setItem(storageKey, JSON.stringify(dataToCache))); }); }
javascript
function offChildAdded(dbRef, dataToCache) { var storageKey = getStorageKeyFromDbRef(dbRef, 'child_added'); //Turn listener off. dbRef.off(); return new Promise(function (resolve, reject) { resolve(_reactNative.AsyncStorage.setItem(storageKey, JSON.stringify(dataToCache))); }); }
[ "function", "offChildAdded", "(", "dbRef", ",", "dataToCache", ")", "{", "var", "storageKey", "=", "getStorageKeyFromDbRef", "(", "dbRef", ",", "'child_added'", ")", ";", "//Turn listener off.", "dbRef", ".", "off", "(", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "resolve", "(", "_reactNative", ".", "AsyncStorage", ".", "setItem", "(", "storageKey", ",", "JSON", ".", "stringify", "(", "dataToCache", ")", ")", ")", ";", "}", ")", ";", "}" ]
Turn off listeners at a certain database.Reference, and cache the data passed in so that it can be passed to a new "child_added" listener if one is created. @param {*} dbRef Reference to stop listening at. @param {*} dataToCache Data that should be cached for this location. Tip: [].slice(-20) to keep the latest 20 items.
[ "Turn", "off", "listeners", "at", "a", "certain", "database", ".", "Reference", "and", "cache", "the", "data", "passed", "in", "so", "that", "it", "can", "be", "passed", "to", "a", "new", "child_added", "listener", "if", "one", "is", "created", "." ]
db755a66d6936710e85161ecfced56a1ea432887
https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L143-L152
37,906
cuttingsoup/react-native-firebase-local-cache
dist/index.js
onChildRemoved
function onChildRemoved(dbRef, callback, cancelCallbackOrContext, context) { return dbRef.on('child_removed', callback, cancelCallbackOrContext, context); }
javascript
function onChildRemoved(dbRef, callback, cancelCallbackOrContext, context) { return dbRef.on('child_removed', callback, cancelCallbackOrContext, context); }
[ "function", "onChildRemoved", "(", "dbRef", ",", "callback", ",", "cancelCallbackOrContext", ",", "context", ")", "{", "return", "dbRef", ".", "on", "(", "'child_removed'", ",", "callback", ",", "cancelCallbackOrContext", ",", "context", ")", ";", "}" ]
Wrapper around Firebase on child_removed listener. @param {*} dbRef Database reference to listen at. @param {*} callback A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot. For ordering purposes, "child_added", "child_changed", and "child_moved" will also be passed a string containing the key of the previous child, by sort order, or null if it is the first child. @param {*} cancelCallbackOrContext An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred. @param {*} context If provided, this object will be used as this when calling your callback(s).
[ "Wrapper", "around", "Firebase", "on", "child_removed", "listener", "." ]
db755a66d6936710e85161ecfced56a1ea432887
https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L162-L164
37,907
cuttingsoup/react-native-firebase-local-cache
dist/index.js
onChildChanged
function onChildChanged(dbRef, callback, cancelCallbackOrContext, context) { return dbRef.on('child_changed', callback, cancelCallbackOrContext, context); }
javascript
function onChildChanged(dbRef, callback, cancelCallbackOrContext, context) { return dbRef.on('child_changed', callback, cancelCallbackOrContext, context); }
[ "function", "onChildChanged", "(", "dbRef", ",", "callback", ",", "cancelCallbackOrContext", ",", "context", ")", "{", "return", "dbRef", ".", "on", "(", "'child_changed'", ",", "callback", ",", "cancelCallbackOrContext", ",", "context", ")", ";", "}" ]
Wrapper around Firebase on child_changed listener. @param {*} dbRef Database reference to listen at. @param {*} callback A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot. For ordering purposes, "child_added", "child_changed", and "child_moved" will also be passed a string containing the key of the previous child, by sort order, or null if it is the first child. @param {*} cancelCallbackOrContext An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred. @param {*} context If provided, this object will be used as this when calling your callback(s).
[ "Wrapper", "around", "Firebase", "on", "child_changed", "listener", "." ]
db755a66d6936710e85161ecfced56a1ea432887
https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L174-L176
37,908
cuttingsoup/react-native-firebase-local-cache
dist/index.js
onChildMoved
function onChildMoved(dbRef, callback, cancelCallbackOrContext, context) { return dbRef.on('child_moved', callback, cancelCallbackOrContext, context); }
javascript
function onChildMoved(dbRef, callback, cancelCallbackOrContext, context) { return dbRef.on('child_moved', callback, cancelCallbackOrContext, context); }
[ "function", "onChildMoved", "(", "dbRef", ",", "callback", ",", "cancelCallbackOrContext", ",", "context", ")", "{", "return", "dbRef", ".", "on", "(", "'child_moved'", ",", "callback", ",", "cancelCallbackOrContext", ",", "context", ")", ";", "}" ]
Wrapper around Firebase on child_moved listener. @param {*} dbRef Database reference to listen at. @param {*} callback A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot. For ordering purposes, "child_added", "child_changed", and "child_moved" will also be passed a string containing the key of the previous child, by sort order, or null if it is the first child. @param {*} cancelCallbackOrContext An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred. @param {*} context If provided, this object will be used as this when calling your callback(s).
[ "Wrapper", "around", "Firebase", "on", "child_moved", "listener", "." ]
db755a66d6936710e85161ecfced56a1ea432887
https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L186-L188
37,909
cuttingsoup/react-native-firebase-local-cache
dist/index.js
twice
function twice(dbRef, snapCallback, processedCallback, cancelCallbackOrContext, context) { var storageKey = getStorageKeyFromDbRef(dbRef, 'twice'); return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) { // Called processedCallback with cached value. if (value !== null) { var cachedVal = JSON.parse(value); callWithContext(processedCallback, cachedVal, cancelCallbackOrContext, context); } }).then(function () { var callbackPeak = function callbackPeak(snap) { var processed = snapCallback.bind(this)(snap); //Store to cache. _reactNative.AsyncStorage.setItem(storageKey, JSON.stringify(processed)).then(function () { processedCallback.bind(this)(processed); }.bind(this)); }; dbRef.once('value', callbackPeak, cancelCallbackOrContext, context); }); }
javascript
function twice(dbRef, snapCallback, processedCallback, cancelCallbackOrContext, context) { var storageKey = getStorageKeyFromDbRef(dbRef, 'twice'); return _reactNative.AsyncStorage.getItem(storageKey).then(function (value) { // Called processedCallback with cached value. if (value !== null) { var cachedVal = JSON.parse(value); callWithContext(processedCallback, cachedVal, cancelCallbackOrContext, context); } }).then(function () { var callbackPeak = function callbackPeak(snap) { var processed = snapCallback.bind(this)(snap); //Store to cache. _reactNative.AsyncStorage.setItem(storageKey, JSON.stringify(processed)).then(function () { processedCallback.bind(this)(processed); }.bind(this)); }; dbRef.once('value', callbackPeak, cancelCallbackOrContext, context); }); }
[ "function", "twice", "(", "dbRef", ",", "snapCallback", ",", "processedCallback", ",", "cancelCallbackOrContext", ",", "context", ")", "{", "var", "storageKey", "=", "getStorageKeyFromDbRef", "(", "dbRef", ",", "'twice'", ")", ";", "return", "_reactNative", ".", "AsyncStorage", ".", "getItem", "(", "storageKey", ")", ".", "then", "(", "function", "(", "value", ")", "{", "// Called processedCallback with cached value.", "if", "(", "value", "!==", "null", ")", "{", "var", "cachedVal", "=", "JSON", ".", "parse", "(", "value", ")", ";", "callWithContext", "(", "processedCallback", ",", "cachedVal", ",", "cancelCallbackOrContext", ",", "context", ")", ";", "}", "}", ")", ".", "then", "(", "function", "(", ")", "{", "var", "callbackPeak", "=", "function", "callbackPeak", "(", "snap", ")", "{", "var", "processed", "=", "snapCallback", ".", "bind", "(", "this", ")", "(", "snap", ")", ";", "//Store to cache.", "_reactNative", ".", "AsyncStorage", ".", "setItem", "(", "storageKey", ",", "JSON", ".", "stringify", "(", "processed", ")", ")", ".", "then", "(", "function", "(", ")", "{", "processedCallback", ".", "bind", "(", "this", ")", "(", "processed", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}", ";", "dbRef", ".", "once", "(", "'value'", ",", "callbackPeak", ",", "cancelCallbackOrContext", ",", "context", ")", ";", "}", ")", ";", "}" ]
Twice, one better than once! Operates in a similar way to `onValue`, however `snapCallback` will only ever be called once when fresh data arrives. The value returned by `snapCallback` will be cached immediately, then passed to the `processedCallback`. If cached data is available when the listener is first turned on, it will be loaded and passed to `processedCallback`. Once data is cached then, each call to `twice` will call `processedCallback` twice, once with cached data, then once with fresh data after being processed by `snapCallback`. @param {*} dbRef Database reference to listen at. @param {Function} snapCallback Callback called when a new snapshot is available. Should return a JSON.stringify-able object that will be cached. @param {Function} processedCallback Callback called maximum of twice - once with cached data, once with freshly processed data. @param {Function|Object} cancelCallbackOrContext An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred. @param {Object} context If provided, this object will be used as this when calling your callback(s). @returns {Promise} Resolves when the cache has been read and listener attached to DB ref.
[ "Twice", "one", "better", "than", "once!", "Operates", "in", "a", "similar", "way", "to", "onValue", "however", "snapCallback", "will", "only", "ever", "be", "called", "once", "when", "fresh", "data", "arrives", ".", "The", "value", "returned", "by", "snapCallback", "will", "be", "cached", "immediately", "then", "passed", "to", "the", "processedCallback", ".", "If", "cached", "data", "is", "available", "when", "the", "listener", "is", "first", "turned", "on", "it", "will", "be", "loaded", "and", "passed", "to", "processedCallback", ".", "Once", "data", "is", "cached", "then", "each", "call", "to", "twice", "will", "call", "processedCallback", "twice", "once", "with", "cached", "data", "then", "once", "with", "fresh", "data", "after", "being", "processed", "by", "snapCallback", "." ]
db755a66d6936710e85161ecfced56a1ea432887
https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L200-L219
37,910
cuttingsoup/react-native-firebase-local-cache
dist/index.js
clearCacheForRef
function clearCacheForRef(dbRef) { var location = dbRef.toString().substring(dbRef.root.toString().length); var promises = []; acceptedOnVerbs.forEach(function (eventType) { var storageKey = '@FirebaseLocalCache:' + eventType + ':' + location; promises.push(_reactNative.AsyncStorage.removeItem(storageKey)); }); return Promise.all(promises); }
javascript
function clearCacheForRef(dbRef) { var location = dbRef.toString().substring(dbRef.root.toString().length); var promises = []; acceptedOnVerbs.forEach(function (eventType) { var storageKey = '@FirebaseLocalCache:' + eventType + ':' + location; promises.push(_reactNative.AsyncStorage.removeItem(storageKey)); }); return Promise.all(promises); }
[ "function", "clearCacheForRef", "(", "dbRef", ")", "{", "var", "location", "=", "dbRef", ".", "toString", "(", ")", ".", "substring", "(", "dbRef", ".", "root", ".", "toString", "(", ")", ".", "length", ")", ";", "var", "promises", "=", "[", "]", ";", "acceptedOnVerbs", ".", "forEach", "(", "function", "(", "eventType", ")", "{", "var", "storageKey", "=", "'@FirebaseLocalCache:'", "+", "eventType", "+", "':'", "+", "location", ";", "promises", ".", "push", "(", "_reactNative", ".", "AsyncStorage", ".", "removeItem", "(", "storageKey", ")", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "promises", ")", ";", "}" ]
Remove the currently cached data for a particular database.Reference. If there are any listeners still active, they will re-write their data to the cache when the .off method is called. @param {firebase.database.Reference} dbRef Firebase database reference to clear. @returns {Promise} Promise that resolves once all cached data for this ref has been cleared.
[ "Remove", "the", "currently", "cached", "data", "for", "a", "particular", "database", ".", "Reference", ".", "If", "there", "are", "any", "listeners", "still", "active", "they", "will", "re", "-", "write", "their", "data", "to", "the", "cache", "when", "the", ".", "off", "method", "is", "called", "." ]
db755a66d6936710e85161ecfced56a1ea432887
https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L227-L238
37,911
cuttingsoup/react-native-firebase-local-cache
dist/index.js
clearCache
function clearCache() { return _reactNative.AsyncStorage.getAllKeys().then(function (keys) { var promises = []; keys.forEach(function (key) { if (key.startsWith('@FirebaseLocalCache:')) { //delete it from the cache if it exists. promises.push(_reactNative.AsyncStorage.removeItem(key)); } }); return Promise.all(promises); }); }
javascript
function clearCache() { return _reactNative.AsyncStorage.getAllKeys().then(function (keys) { var promises = []; keys.forEach(function (key) { if (key.startsWith('@FirebaseLocalCache:')) { //delete it from the cache if it exists. promises.push(_reactNative.AsyncStorage.removeItem(key)); } }); return Promise.all(promises); }); }
[ "function", "clearCache", "(", ")", "{", "return", "_reactNative", ".", "AsyncStorage", ".", "getAllKeys", "(", ")", ".", "then", "(", "function", "(", "keys", ")", "{", "var", "promises", "=", "[", "]", ";", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "key", ".", "startsWith", "(", "'@FirebaseLocalCache:'", ")", ")", "{", "//delete it from the cache if it exists.", "promises", ".", "push", "(", "_reactNative", ".", "AsyncStorage", ".", "removeItem", "(", "key", ")", ")", ";", "}", "}", ")", ";", "return", "Promise", ".", "all", "(", "promises", ")", ";", "}", ")", ";", "}" ]
Remove all currently cached data. If there are any listeners still active, they will re-write their data to the cache when the .off method is called. @returns {Promise} Promise that resolves when all cached data has been deleted.
[ "Remove", "all", "currently", "cached", "data", ".", "If", "there", "are", "any", "listeners", "still", "active", "they", "will", "re", "-", "write", "their", "data", "to", "the", "cache", "when", "the", ".", "off", "method", "is", "called", "." ]
db755a66d6936710e85161ecfced56a1ea432887
https://github.com/cuttingsoup/react-native-firebase-local-cache/blob/db755a66d6936710e85161ecfced56a1ea432887/dist/index.js#L245-L258
37,912
tirish/steam-shortcut-editor
lib/parser.js
parseIntValue
function parseIntValue(input) { let value = input.buf.readInt32LE(input.i); input.i += 4; return value; }
javascript
function parseIntValue(input) { let value = input.buf.readInt32LE(input.i); input.i += 4; return value; }
[ "function", "parseIntValue", "(", "input", ")", "{", "let", "value", "=", "input", ".", "buf", ".", "readInt32LE", "(", "input", ".", "i", ")", ";", "input", ".", "i", "+=", "4", ";", "return", "value", ";", "}" ]
LE 32 bit number
[ "LE", "32", "bit", "number" ]
f60bfa1b7ef836bd29669e7eab42698433e07621
https://github.com/tirish/steam-shortcut-editor/blob/f60bfa1b7ef836bd29669e7eab42698433e07621/lib/parser.js#L22-L27
37,913
danShumway/serverboy.js
src/gameboy_core/audio/XAudioServer.js
XAudioJSMediaStreamPushAudio
function XAudioJSMediaStreamPushAudio(event) { var index = 0; var audioLengthRequested = event.data; var samplesPerCallbackAll = XAudioJSSamplesPerCallback * XAudioJSChannelsAllocated; var XAudioJSMediaStreamLengthAlias = audioLengthRequested % XAudioJSSamplesPerCallback; audioLengthRequested = audioLengthRequested - (XAudioJSMediaStreamLengthAliasCounter - (XAudioJSMediaStreamLengthAliasCounter % XAudioJSSamplesPerCallback)) - XAudioJSMediaStreamLengthAlias + XAudioJSSamplesPerCallback; XAudioJSMediaStreamLengthAliasCounter -= XAudioJSMediaStreamLengthAliasCounter - (XAudioJSMediaStreamLengthAliasCounter % XAudioJSSamplesPerCallback); XAudioJSMediaStreamLengthAliasCounter += XAudioJSSamplesPerCallback - XAudioJSMediaStreamLengthAlias; if (XAudioJSMediaStreamBuffer.length != samplesPerCallbackAll) { XAudioJSMediaStreamBuffer = new Float32Array(samplesPerCallbackAll); } XAudioJSResampleRefill(); while (index < audioLengthRequested) { var index2 = 0; while (index2 < samplesPerCallbackAll && XAudioJSResampleBufferStart != XAudioJSResampleBufferEnd) { XAudioJSMediaStreamBuffer[index2++] = XAudioJSResampledBuffer[XAudioJSResampleBufferStart++]; if (XAudioJSResampleBufferStart == XAudioJSResampleBufferSize) { XAudioJSResampleBufferStart = 0; } } XAudioJSMediaStreamWorker.postMessage([0, XAudioJSMediaStreamBuffer]); index += XAudioJSSamplesPerCallback; } }
javascript
function XAudioJSMediaStreamPushAudio(event) { var index = 0; var audioLengthRequested = event.data; var samplesPerCallbackAll = XAudioJSSamplesPerCallback * XAudioJSChannelsAllocated; var XAudioJSMediaStreamLengthAlias = audioLengthRequested % XAudioJSSamplesPerCallback; audioLengthRequested = audioLengthRequested - (XAudioJSMediaStreamLengthAliasCounter - (XAudioJSMediaStreamLengthAliasCounter % XAudioJSSamplesPerCallback)) - XAudioJSMediaStreamLengthAlias + XAudioJSSamplesPerCallback; XAudioJSMediaStreamLengthAliasCounter -= XAudioJSMediaStreamLengthAliasCounter - (XAudioJSMediaStreamLengthAliasCounter % XAudioJSSamplesPerCallback); XAudioJSMediaStreamLengthAliasCounter += XAudioJSSamplesPerCallback - XAudioJSMediaStreamLengthAlias; if (XAudioJSMediaStreamBuffer.length != samplesPerCallbackAll) { XAudioJSMediaStreamBuffer = new Float32Array(samplesPerCallbackAll); } XAudioJSResampleRefill(); while (index < audioLengthRequested) { var index2 = 0; while (index2 < samplesPerCallbackAll && XAudioJSResampleBufferStart != XAudioJSResampleBufferEnd) { XAudioJSMediaStreamBuffer[index2++] = XAudioJSResampledBuffer[XAudioJSResampleBufferStart++]; if (XAudioJSResampleBufferStart == XAudioJSResampleBufferSize) { XAudioJSResampleBufferStart = 0; } } XAudioJSMediaStreamWorker.postMessage([0, XAudioJSMediaStreamBuffer]); index += XAudioJSSamplesPerCallback; } }
[ "function", "XAudioJSMediaStreamPushAudio", "(", "event", ")", "{", "var", "index", "=", "0", ";", "var", "audioLengthRequested", "=", "event", ".", "data", ";", "var", "samplesPerCallbackAll", "=", "XAudioJSSamplesPerCallback", "*", "XAudioJSChannelsAllocated", ";", "var", "XAudioJSMediaStreamLengthAlias", "=", "audioLengthRequested", "%", "XAudioJSSamplesPerCallback", ";", "audioLengthRequested", "=", "audioLengthRequested", "-", "(", "XAudioJSMediaStreamLengthAliasCounter", "-", "(", "XAudioJSMediaStreamLengthAliasCounter", "%", "XAudioJSSamplesPerCallback", ")", ")", "-", "XAudioJSMediaStreamLengthAlias", "+", "XAudioJSSamplesPerCallback", ";", "XAudioJSMediaStreamLengthAliasCounter", "-=", "XAudioJSMediaStreamLengthAliasCounter", "-", "(", "XAudioJSMediaStreamLengthAliasCounter", "%", "XAudioJSSamplesPerCallback", ")", ";", "XAudioJSMediaStreamLengthAliasCounter", "+=", "XAudioJSSamplesPerCallback", "-", "XAudioJSMediaStreamLengthAlias", ";", "if", "(", "XAudioJSMediaStreamBuffer", ".", "length", "!=", "samplesPerCallbackAll", ")", "{", "XAudioJSMediaStreamBuffer", "=", "new", "Float32Array", "(", "samplesPerCallbackAll", ")", ";", "}", "XAudioJSResampleRefill", "(", ")", ";", "while", "(", "index", "<", "audioLengthRequested", ")", "{", "var", "index2", "=", "0", ";", "while", "(", "index2", "<", "samplesPerCallbackAll", "&&", "XAudioJSResampleBufferStart", "!=", "XAudioJSResampleBufferEnd", ")", "{", "XAudioJSMediaStreamBuffer", "[", "index2", "++", "]", "=", "XAudioJSResampledBuffer", "[", "XAudioJSResampleBufferStart", "++", "]", ";", "if", "(", "XAudioJSResampleBufferStart", "==", "XAudioJSResampleBufferSize", ")", "{", "XAudioJSResampleBufferStart", "=", "0", ";", "}", "}", "XAudioJSMediaStreamWorker", ".", "postMessage", "(", "[", "0", ",", "XAudioJSMediaStreamBuffer", "]", ")", ";", "index", "+=", "XAudioJSSamplesPerCallback", ";", "}", "}" ]
MediaStream API buffer push
[ "MediaStream", "API", "buffer", "push" ]
68f0ac88b5b280f64de2c8ae6d57d8a84cbe3628
https://github.com/danShumway/serverboy.js/blob/68f0ac88b5b280f64de2c8ae6d57d8a84cbe3628/src/gameboy_core/audio/XAudioServer.js#L445-L468
37,914
byron-dupreez/aws-core-utils
lambda-utils.js
listEventSourceMappings
function listEventSourceMappings(lambda, params, logger) { logger = logger || console; const functionName = params.FunctionName; const listEventSourceMappingsAsync = Promises.wrap(lambda.listEventSourceMappings); const startMs = Date.now(); return listEventSourceMappingsAsync.call(lambda, params).then( result => { if (logger.traceEnabled) { const mappings = Array.isArray(result.EventSourceMappings) ? result.EventSourceMappings : []; const n = mappings.length; logger.trace(`Found ${n} event source mapping${n !== 1 ? 's' : ''} for ${functionName} - took ${Date.now() - startMs} ms - result (${JSON.stringify(result)})`); } return result; }, err => { logger.error(`Failed to list event source mappings for function (${functionName}) - took ${Date.now() - startMs} ms`, err); throw err; } ); }
javascript
function listEventSourceMappings(lambda, params, logger) { logger = logger || console; const functionName = params.FunctionName; const listEventSourceMappingsAsync = Promises.wrap(lambda.listEventSourceMappings); const startMs = Date.now(); return listEventSourceMappingsAsync.call(lambda, params).then( result => { if (logger.traceEnabled) { const mappings = Array.isArray(result.EventSourceMappings) ? result.EventSourceMappings : []; const n = mappings.length; logger.trace(`Found ${n} event source mapping${n !== 1 ? 's' : ''} for ${functionName} - took ${Date.now() - startMs} ms - result (${JSON.stringify(result)})`); } return result; }, err => { logger.error(`Failed to list event source mappings for function (${functionName}) - took ${Date.now() - startMs} ms`, err); throw err; } ); }
[ "function", "listEventSourceMappings", "(", "lambda", ",", "params", ",", "logger", ")", "{", "logger", "=", "logger", "||", "console", ";", "const", "functionName", "=", "params", ".", "FunctionName", ";", "const", "listEventSourceMappingsAsync", "=", "Promises", ".", "wrap", "(", "lambda", ".", "listEventSourceMappings", ")", ";", "const", "startMs", "=", "Date", ".", "now", "(", ")", ";", "return", "listEventSourceMappingsAsync", ".", "call", "(", "lambda", ",", "params", ")", ".", "then", "(", "result", "=>", "{", "if", "(", "logger", ".", "traceEnabled", ")", "{", "const", "mappings", "=", "Array", ".", "isArray", "(", "result", ".", "EventSourceMappings", ")", "?", "result", ".", "EventSourceMappings", ":", "[", "]", ";", "const", "n", "=", "mappings", ".", "length", ";", "logger", ".", "trace", "(", "`", "${", "n", "}", "${", "n", "!==", "1", "?", "'s'", ":", "''", "}", "${", "functionName", "}", "${", "Date", ".", "now", "(", ")", "-", "startMs", "}", "${", "JSON", ".", "stringify", "(", "result", ")", "}", "`", ")", ";", "}", "return", "result", ";", "}", ",", "err", "=>", "{", "logger", ".", "error", "(", "`", "${", "functionName", "}", "${", "Date", ".", "now", "(", ")", "-", "startMs", "}", "`", ",", "err", ")", ";", "throw", "err", ";", "}", ")", ";", "}" ]
Lists the event source mappings for the given function name. @param {AWS.Lambda|AwsLambda} lambda - the AWS.Lambda instance to use @param {ListEventSourceMappingsParams} params - the parameters to use @param {Logger|console|undefined} [logger] - the logger to use (defaults to console if omitted) @returns {Promise.<ListEventSourceMappingsResult>}
[ "Lists", "the", "event", "source", "mappings", "for", "the", "given", "function", "name", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/lambda-utils.js#L39-L58
37,915
byron-dupreez/aws-core-utils
lambda-utils.js
updateEventSourceMapping
function updateEventSourceMapping(lambda, params, logger) { logger = logger || console; const functionName = params.FunctionName; const uuid = params.UUID; const updateEventSourceMappingAsync = Promises.wrap(lambda.updateEventSourceMapping); const startMs = Date.now(); return updateEventSourceMappingAsync.call(lambda, params).then( result => { logger.info(`Updated event source mapping (${uuid}) for function (${functionName}) - took ${Date.now() - startMs} ms - result (${JSON.stringify(result)})`); return result; }, err => { logger.error(`Failed to update event source mapping (${uuid}) for function (${functionName}) - took ${Date.now() - startMs} ms`, err); throw err; } ); }
javascript
function updateEventSourceMapping(lambda, params, logger) { logger = logger || console; const functionName = params.FunctionName; const uuid = params.UUID; const updateEventSourceMappingAsync = Promises.wrap(lambda.updateEventSourceMapping); const startMs = Date.now(); return updateEventSourceMappingAsync.call(lambda, params).then( result => { logger.info(`Updated event source mapping (${uuid}) for function (${functionName}) - took ${Date.now() - startMs} ms - result (${JSON.stringify(result)})`); return result; }, err => { logger.error(`Failed to update event source mapping (${uuid}) for function (${functionName}) - took ${Date.now() - startMs} ms`, err); throw err; } ); }
[ "function", "updateEventSourceMapping", "(", "lambda", ",", "params", ",", "logger", ")", "{", "logger", "=", "logger", "||", "console", ";", "const", "functionName", "=", "params", ".", "FunctionName", ";", "const", "uuid", "=", "params", ".", "UUID", ";", "const", "updateEventSourceMappingAsync", "=", "Promises", ".", "wrap", "(", "lambda", ".", "updateEventSourceMapping", ")", ";", "const", "startMs", "=", "Date", ".", "now", "(", ")", ";", "return", "updateEventSourceMappingAsync", ".", "call", "(", "lambda", ",", "params", ")", ".", "then", "(", "result", "=>", "{", "logger", ".", "info", "(", "`", "${", "uuid", "}", "${", "functionName", "}", "${", "Date", ".", "now", "(", ")", "-", "startMs", "}", "${", "JSON", ".", "stringify", "(", "result", ")", "}", "`", ")", ";", "return", "result", ";", "}", ",", "err", "=>", "{", "logger", ".", "error", "(", "`", "${", "uuid", "}", "${", "functionName", "}", "${", "Date", ".", "now", "(", ")", "-", "startMs", "}", "`", ",", "err", ")", ";", "throw", "err", ";", "}", ")", ";", "}" ]
Updates the Lambda function event source mapping identified by the given parameters with the given parameter values. @param {AWS.Lambda|AwsLambda} lambda - the AWS.Lambda instance to use @param {UpdateEventSourceMappingParams} params - the parameters to use @param {Logger|console|undefined} [logger] - the logger to use (defaults to console if omitted) @returns {Promise.<*>} a promise of the result returned by AWS Lambda
[ "Updates", "the", "Lambda", "function", "event", "source", "mapping", "identified", "by", "the", "given", "parameters", "with", "the", "given", "parameter", "values", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/lambda-utils.js#L67-L83
37,916
mojaie/kiwiii
src/component/formRangeBox.js
rangeBox
function rangeBox(selection, label) { selection .classed('form-row', true) .classed('form-group', true) .classed('align-items-center', true) .append('div') .classed('col-form-label', true) .classed('col-form-label-sm', true) .text(label); const minBox = selection.append('div'); minBox.append('label').text('min'); minBox.append('input').classed('min', true); const maxBox = selection.append('div'); maxBox.append('label').text('max'); maxBox.append('input').classed('max', true); selection.selectAll('div') .classed('form-group', true) .classed('col-4', true) .classed('mb-0', true); selection.selectAll('label') .classed('col-form-label', true) .classed('col-form-label-sm', true) .classed('py-0', true); selection.selectAll('input') .classed('form-control', true) .classed('form-control-sm', true) .attr('type', 'number'); selection.append('div') .classed('col-4', true); selection.append('div') .call(badge.invalidFeedback) .classed('col-8', true); }
javascript
function rangeBox(selection, label) { selection .classed('form-row', true) .classed('form-group', true) .classed('align-items-center', true) .append('div') .classed('col-form-label', true) .classed('col-form-label-sm', true) .text(label); const minBox = selection.append('div'); minBox.append('label').text('min'); minBox.append('input').classed('min', true); const maxBox = selection.append('div'); maxBox.append('label').text('max'); maxBox.append('input').classed('max', true); selection.selectAll('div') .classed('form-group', true) .classed('col-4', true) .classed('mb-0', true); selection.selectAll('label') .classed('col-form-label', true) .classed('col-form-label-sm', true) .classed('py-0', true); selection.selectAll('input') .classed('form-control', true) .classed('form-control-sm', true) .attr('type', 'number'); selection.append('div') .classed('col-4', true); selection.append('div') .call(badge.invalidFeedback) .classed('col-8', true); }
[ "function", "rangeBox", "(", "selection", ",", "label", ")", "{", "selection", ".", "classed", "(", "'form-row'", ",", "true", ")", ".", "classed", "(", "'form-group'", ",", "true", ")", ".", "classed", "(", "'align-items-center'", ",", "true", ")", ".", "append", "(", "'div'", ")", ".", "classed", "(", "'col-form-label'", ",", "true", ")", ".", "classed", "(", "'col-form-label-sm'", ",", "true", ")", ".", "text", "(", "label", ")", ";", "const", "minBox", "=", "selection", ".", "append", "(", "'div'", ")", ";", "minBox", ".", "append", "(", "'label'", ")", ".", "text", "(", "'min'", ")", ";", "minBox", ".", "append", "(", "'input'", ")", ".", "classed", "(", "'min'", ",", "true", ")", ";", "const", "maxBox", "=", "selection", ".", "append", "(", "'div'", ")", ";", "maxBox", ".", "append", "(", "'label'", ")", ".", "text", "(", "'max'", ")", ";", "maxBox", ".", "append", "(", "'input'", ")", ".", "classed", "(", "'max'", ",", "true", ")", ";", "selection", ".", "selectAll", "(", "'div'", ")", ".", "classed", "(", "'form-group'", ",", "true", ")", ".", "classed", "(", "'col-4'", ",", "true", ")", ".", "classed", "(", "'mb-0'", ",", "true", ")", ";", "selection", ".", "selectAll", "(", "'label'", ")", ".", "classed", "(", "'col-form-label'", ",", "true", ")", ".", "classed", "(", "'col-form-label-sm'", ",", "true", ")", ".", "classed", "(", "'py-0'", ",", "true", ")", ";", "selection", ".", "selectAll", "(", "'input'", ")", ".", "classed", "(", "'form-control'", ",", "true", ")", ".", "classed", "(", "'form-control-sm'", ",", "true", ")", ".", "attr", "(", "'type'", ",", "'number'", ")", ";", "selection", ".", "append", "(", "'div'", ")", ".", "classed", "(", "'col-4'", ",", "true", ")", ";", "selection", ".", "append", "(", "'div'", ")", ".", "call", "(", "badge", ".", "invalidFeedback", ")", ".", "classed", "(", "'col-8'", ",", "true", ")", ";", "}" ]
Render range box components @param {d3.selection} selection - selection of box container (div element)
[ "Render", "range", "box", "components" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/component/formRangeBox.js#L13-L51
37,917
EricCrosson/coinmarketcap-api
index.js
getMarketCaps
function getMarketCaps() { return new Promise(function (resolve, reject) { scraper .get(urlMarketCap) .then(function(tableData) { const coinmarketcapTable = tableData[0]; resolve(getAllMarketCaps(coinmarketcapTable)); }); }); }
javascript
function getMarketCaps() { return new Promise(function (resolve, reject) { scraper .get(urlMarketCap) .then(function(tableData) { const coinmarketcapTable = tableData[0]; resolve(getAllMarketCaps(coinmarketcapTable)); }); }); }
[ "function", "getMarketCaps", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "scraper", ".", "get", "(", "urlMarketCap", ")", ".", "then", "(", "function", "(", "tableData", ")", "{", "const", "coinmarketcapTable", "=", "tableData", "[", "0", "]", ";", "resolve", "(", "getAllMarketCaps", "(", "coinmarketcapTable", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Return array of market capitalizations, in order of size.
[ "Return", "array", "of", "market", "capitalizations", "in", "order", "of", "size", "." ]
ec6cf161a6e9219a85f049144b2b0d6c5462f3a0
https://github.com/EricCrosson/coinmarketcap-api/blob/ec6cf161a6e9219a85f049144b2b0d6c5462f3a0/index.js#L121-L132
37,918
etpinard/karma-benchmark-json-reporter
example/03-output-info/karma.conf.js
formatResults
function formatResults (results) { return results.map(function (r) { return { fullName: r.fullName, hz: r.hz, hzDeviation: r.hzDeviation } }) }
javascript
function formatResults (results) { return results.map(function (r) { return { fullName: r.fullName, hz: r.hz, hzDeviation: r.hzDeviation } }) }
[ "function", "formatResults", "(", "results", ")", "{", "return", "results", ".", "map", "(", "function", "(", "r", ")", "{", "return", "{", "fullName", ":", "r", ".", "fullName", ",", "hz", ":", "r", ".", "hz", ",", "hzDeviation", ":", "r", ".", "hzDeviation", "}", "}", ")", "}" ]
only keep full name and hz statistics
[ "only", "keep", "full", "name", "and", "hz", "statistics" ]
9e89e325dcf53bb7291e5ab2174dd7fd55cc572b
https://github.com/etpinard/karma-benchmark-json-reporter/blob/9e89e325dcf53bb7291e5ab2174dd7fd55cc572b/example/03-output-info/karma.conf.js#L28-L36
37,919
etpinard/karma-benchmark-json-reporter
example/03-output-info/karma.conf.js
formatOutput
function formatOutput (results) { var date = new Date() var commit try { commit = execSync('git rev-parse HEAD').toString().replace('\n', '') } catch (e) { commit = 'commit hash not found' } return { meta: { title: 'example benchmark', version: pkg.version, commit: commit, date: [ date.toLocaleDateString(), date.toLocaleTimeString(), date.toString().match(/\(([A-Za-z\s].*)\)/)[1] ].join(' ') }, results: results } }
javascript
function formatOutput (results) { var date = new Date() var commit try { commit = execSync('git rev-parse HEAD').toString().replace('\n', '') } catch (e) { commit = 'commit hash not found' } return { meta: { title: 'example benchmark', version: pkg.version, commit: commit, date: [ date.toLocaleDateString(), date.toLocaleTimeString(), date.toString().match(/\(([A-Za-z\s].*)\)/)[1] ].join(' ') }, results: results } }
[ "function", "formatOutput", "(", "results", ")", "{", "var", "date", "=", "new", "Date", "(", ")", "var", "commit", "try", "{", "commit", "=", "execSync", "(", "'git rev-parse HEAD'", ")", ".", "toString", "(", ")", ".", "replace", "(", "'\\n'", ",", "''", ")", "}", "catch", "(", "e", ")", "{", "commit", "=", "'commit hash not found'", "}", "return", "{", "meta", ":", "{", "title", ":", "'example benchmark'", ",", "version", ":", "pkg", ".", "version", ",", "commit", ":", "commit", ",", "date", ":", "[", "date", ".", "toLocaleDateString", "(", ")", ",", "date", ".", "toLocaleTimeString", "(", ")", ",", "date", ".", "toString", "(", ")", ".", "match", "(", "/", "\\(([A-Za-z\\s].*)\\)", "/", ")", "[", "1", "]", "]", ".", "join", "(", "' '", ")", "}", ",", "results", ":", "results", "}", "}" ]
add date, commit package version info to output JSON
[ "add", "date", "commit", "package", "version", "info", "to", "output", "JSON" ]
9e89e325dcf53bb7291e5ab2174dd7fd55cc572b
https://github.com/etpinard/karma-benchmark-json-reporter/blob/9e89e325dcf53bb7291e5ab2174dd7fd55cc572b/example/03-output-info/karma.conf.js#L39-L62
37,920
cgmartin/spa-express-static-server
src/middleware/request-logger.js
getConversationId
function getConversationId(req, res, options) { var cookieName = options.conversationIdCookieName; var headerName = options.conversationIdHeader; var conversationId = req.headers[headerName] || req.cookies && req.cookies[cookieName]; if (!conversationId) { conversationId = uuid.v1(); } req.conversationId = conversationId; res.cookie(cookieName, conversationId, { path: '/' }); return conversationId; }
javascript
function getConversationId(req, res, options) { var cookieName = options.conversationIdCookieName; var headerName = options.conversationIdHeader; var conversationId = req.headers[headerName] || req.cookies && req.cookies[cookieName]; if (!conversationId) { conversationId = uuid.v1(); } req.conversationId = conversationId; res.cookie(cookieName, conversationId, { path: '/' }); return conversationId; }
[ "function", "getConversationId", "(", "req", ",", "res", ",", "options", ")", "{", "var", "cookieName", "=", "options", ".", "conversationIdCookieName", ";", "var", "headerName", "=", "options", ".", "conversationIdHeader", ";", "var", "conversationId", "=", "req", ".", "headers", "[", "headerName", "]", "||", "req", ".", "cookies", "&&", "req", ".", "cookies", "[", "cookieName", "]", ";", "if", "(", "!", "conversationId", ")", "{", "conversationId", "=", "uuid", ".", "v1", "(", ")", ";", "}", "req", ".", "conversationId", "=", "conversationId", ";", "res", ".", "cookie", "(", "cookieName", ",", "conversationId", ",", "{", "path", ":", "'/'", "}", ")", ";", "return", "conversationId", ";", "}" ]
Create a "conversation" identifier to track requests per browser session
[ "Create", "a", "conversation", "identifier", "to", "track", "requests", "per", "browser", "session" ]
6f5d2e9cb394dcd634cc7e29f92c586ce5c61163
https://github.com/cgmartin/spa-express-static-server/blob/6f5d2e9cb394dcd634cc7e29f92c586ce5c61163/src/middleware/request-logger.js#L71-L81
37,921
artdecocode/erotic
build/callback.js
makeCallback
function makeCallback(entryCaller, entryStack, shadow = false) { /** * This callback should be called when an asynchronous error occurred. * @param {(string|Error)} messageOrError A message string or an _Error_ object at the point of actual error. * @returns {Error} An error with the updated stack which includes the callee. */ function cb(messageOrError) { const caller = getCallerFromArguments(arguments) const { stack: errorStack } = new Error() const calleeStackLine = getCalleeStackLine(errorStack) const isError = messageOrError instanceof Error const message = isError ? messageOrError.message : messageOrError const stackHeading = getStackHeading(message) const entryHasCallee = caller !== null && entryCaller === caller const stackMessage = [ stackHeading, ...(entryHasCallee || shadow ? [entryStack] : [ calleeStackLine, entryStack, ]), ].join('\n') const stack = cleanStack(stackMessage) const properties = { message, stack } const e = isError ? messageOrError : new Error() return /** @type {Error} */ (Object.assign(/** @type {!Object} */ (e), properties)) } return cb }
javascript
function makeCallback(entryCaller, entryStack, shadow = false) { /** * This callback should be called when an asynchronous error occurred. * @param {(string|Error)} messageOrError A message string or an _Error_ object at the point of actual error. * @returns {Error} An error with the updated stack which includes the callee. */ function cb(messageOrError) { const caller = getCallerFromArguments(arguments) const { stack: errorStack } = new Error() const calleeStackLine = getCalleeStackLine(errorStack) const isError = messageOrError instanceof Error const message = isError ? messageOrError.message : messageOrError const stackHeading = getStackHeading(message) const entryHasCallee = caller !== null && entryCaller === caller const stackMessage = [ stackHeading, ...(entryHasCallee || shadow ? [entryStack] : [ calleeStackLine, entryStack, ]), ].join('\n') const stack = cleanStack(stackMessage) const properties = { message, stack } const e = isError ? messageOrError : new Error() return /** @type {Error} */ (Object.assign(/** @type {!Object} */ (e), properties)) } return cb }
[ "function", "makeCallback", "(", "entryCaller", ",", "entryStack", ",", "shadow", "=", "false", ")", "{", "/**\n * This callback should be called when an asynchronous error occurred.\n * @param {(string|Error)} messageOrError A message string or an _Error_ object at the point of actual error.\n * @returns {Error} An error with the updated stack which includes the callee.\n */", "function", "cb", "(", "messageOrError", ")", "{", "const", "caller", "=", "getCallerFromArguments", "(", "arguments", ")", "const", "{", "stack", ":", "errorStack", "}", "=", "new", "Error", "(", ")", "const", "calleeStackLine", "=", "getCalleeStackLine", "(", "errorStack", ")", "const", "isError", "=", "messageOrError", "instanceof", "Error", "const", "message", "=", "isError", "?", "messageOrError", ".", "message", ":", "messageOrError", "const", "stackHeading", "=", "getStackHeading", "(", "message", ")", "const", "entryHasCallee", "=", "caller", "!==", "null", "&&", "entryCaller", "===", "caller", "const", "stackMessage", "=", "[", "stackHeading", ",", "...", "(", "entryHasCallee", "||", "shadow", "?", "[", "entryStack", "]", ":", "[", "calleeStackLine", ",", "entryStack", ",", "]", ")", ",", "]", ".", "join", "(", "'\\n'", ")", "const", "stack", "=", "cleanStack", "(", "stackMessage", ")", "const", "properties", "=", "{", "message", ",", "stack", "}", "const", "e", "=", "isError", "?", "messageOrError", ":", "new", "Error", "(", ")", "return", "/** @type {Error} */", "(", "Object", ".", "assign", "(", "/** @type {!Object} */", "(", "e", ")", ",", "properties", ")", ")", "}", "return", "cb", "}" ]
Create a callback. @param {!Function} entryCaller The function which was called at entry. @param {string} entryStack The first line of the error stack to be returned @param {boolean} [shadow=false] Print only entry stack.
[ "Create", "a", "callback", "." ]
2d8cb268bd6ddc64a8bb90ac25d388e553866a0a
https://github.com/artdecocode/erotic/blob/2d8cb268bd6ddc64a8bb90ac25d388e553866a0a/build/callback.js#L12-L43
37,922
nwtjs/nwt
src/anim/js/anim.js
function(duration, easing) { var newStylesheet = localnwt.node.create('<style type="text/css"></style>'); easing = easing || 'ease-in'; duration = duration || 1; var trail = ' ' + duration + 's ' + easing, // Just support all browsers for now cssTransitionProperties = { '-webkit-transition': 'all' + trail, '-moz-transition': ' all' + trail, '-o-ransition': ' all' + trail, 'ms-transition': ' all' + trail, 'transition': ' all' + trail }, newContent = ''; for (i in cssTransitionProperties) { newContent += i + ': ' + cssTransitionProperties[i] + ';'; } newStylesheet.setHtml('.' + this.animClass + '{' + newContent + '}'); localnwt.one('head').append(newStylesheet); setTimeout(function(){ newStylesheet.remove() }, duration*1001) }
javascript
function(duration, easing) { var newStylesheet = localnwt.node.create('<style type="text/css"></style>'); easing = easing || 'ease-in'; duration = duration || 1; var trail = ' ' + duration + 's ' + easing, // Just support all browsers for now cssTransitionProperties = { '-webkit-transition': 'all' + trail, '-moz-transition': ' all' + trail, '-o-ransition': ' all' + trail, 'ms-transition': ' all' + trail, 'transition': ' all' + trail }, newContent = ''; for (i in cssTransitionProperties) { newContent += i + ': ' + cssTransitionProperties[i] + ';'; } newStylesheet.setHtml('.' + this.animClass + '{' + newContent + '}'); localnwt.one('head').append(newStylesheet); setTimeout(function(){ newStylesheet.remove() }, duration*1001) }
[ "function", "(", "duration", ",", "easing", ")", "{", "var", "newStylesheet", "=", "localnwt", ".", "node", ".", "create", "(", "'<style type=\"text/css\"></style>'", ")", ";", "easing", "=", "easing", "||", "'ease-in'", ";", "duration", "=", "duration", "||", "1", ";", "var", "trail", "=", "' '", "+", "duration", "+", "'s '", "+", "easing", ",", "// Just support all browsers for now", "cssTransitionProperties", "=", "{", "'-webkit-transition'", ":", "'all'", "+", "trail", ",", "'-moz-transition'", ":", "' all'", "+", "trail", ",", "'-o-ransition'", ":", "' all'", "+", "trail", ",", "'ms-transition'", ":", "' all'", "+", "trail", ",", "'transition'", ":", "' all'", "+", "trail", "}", ",", "newContent", "=", "''", ";", "for", "(", "i", "in", "cssTransitionProperties", ")", "{", "newContent", "+=", "i", "+", "': '", "+", "cssTransitionProperties", "[", "i", "]", "+", "';'", ";", "}", "newStylesheet", ".", "setHtml", "(", "'.'", "+", "this", ".", "animClass", "+", "'{'", "+", "newContent", "+", "'}'", ")", ";", "localnwt", ".", "one", "(", "'head'", ")", ".", "append", "(", "newStylesheet", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "newStylesheet", ".", "remove", "(", ")", "}", ",", "duration", "*", "1001", ")", "}" ]
Initializes CSS for transforms
[ "Initializes", "CSS", "for", "transforms" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/anim/js/anim.js#L14-L45
37,923
nwtjs/nwt
src/anim/js/anim.js
function(node, styles, duration, easing) { animation.init(duration, easing); node.fire('anim:start', [styles, duration, easing]) setTimeout(function(){ node.fire('anim:done', [styles, duration, easing]) }, duration*1000) // Need to be sure to implement the transition function first node.addClass(animation.animClass); node.setStyles(styles); return node; }
javascript
function(node, styles, duration, easing) { animation.init(duration, easing); node.fire('anim:start', [styles, duration, easing]) setTimeout(function(){ node.fire('anim:done', [styles, duration, easing]) }, duration*1000) // Need to be sure to implement the transition function first node.addClass(animation.animClass); node.setStyles(styles); return node; }
[ "function", "(", "node", ",", "styles", ",", "duration", ",", "easing", ")", "{", "animation", ".", "init", "(", "duration", ",", "easing", ")", ";", "node", ".", "fire", "(", "'anim:start'", ",", "[", "styles", ",", "duration", ",", "easing", "]", ")", "setTimeout", "(", "function", "(", ")", "{", "node", ".", "fire", "(", "'anim:done'", ",", "[", "styles", ",", "duration", ",", "easing", "]", ")", "}", ",", "duration", "*", "1000", ")", "// Need to be sure to implement the transition function first", "node", ".", "addClass", "(", "animation", ".", "animClass", ")", ";", "node", ".", "setStyles", "(", "styles", ")", ";", "return", "node", ";", "}" ]
Method to animate a node @param object NWTNode instance @param object Object of styles to animate. E.g., {top: 10} @param integer Duration in seconds to animate @param string Easing type. One of: linear|ease|ease-in|ease-out|ease-in-out|cubic-bezier(n,n,n,n);
[ "Method", "to", "animate", "a", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/anim/js/anim.js#L55-L72
37,924
nwtjs/nwt
src/event/js/event.js
NWTEventInstance
function NWTEventInstance (e, attrs) { this._e = e; this.target = new NWTNodeInstance(e.target); for (var i in attrs) { this[i] = attrs[i]; } }
javascript
function NWTEventInstance (e, attrs) { this._e = e; this.target = new NWTNodeInstance(e.target); for (var i in attrs) { this[i] = attrs[i]; } }
[ "function", "NWTEventInstance", "(", "e", ",", "attrs", ")", "{", "this", ".", "_e", "=", "e", ";", "this", ".", "target", "=", "new", "NWTNodeInstance", "(", "e", ".", "target", ")", ";", "for", "(", "var", "i", "in", "attrs", ")", "{", "this", "[", "i", "]", "=", "attrs", "[", "i", "]", ";", "}", "}" ]
NWTEventInstance Class Event object wrapper @param event Event object @param object (Optional) attributes to populate the event object with @constructor
[ "NWTEventInstance", "Class", "Event", "object", "wrapper" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/event/js/event.js#L8-L15
37,925
nwtjs/nwt
src/event/js/event.js
function(attribute, pattern, callback, interaction, maxDepth) { var classPattern = new RegExp(pattern), interaction = interaction || 'click', maxSearch, dispatcher, body = localnwt.one('body'); // Currently only search one level for a mouse listener for performance reasons if (interaction == 'click') { maxSearch = 100; } else { maxSearch = maxDepth || 1; } dispatcher = function(e) { var originalTarget = e.target, target = originalTarget, // Did we find it? found = true, // Keep track of how many times we bubble up depthSearched = 0; while(target._node && target._node.parentNode) { if (target._node == localnwt.one('body')._node || depthSearched >= maxSearch) { break; } if (target.hasAttribute(attribute)) { var matches = target.getAttribute(attribute).match(pattern); if (matches) { callback(originalTarget, target, matches); // If we found a callback, we usually want to stop the event // Except for input elements (still want checkboxes to check and stuff) if( target.get('nodeName').toUpperCase() !== "INPUT") { e.stop(); } break; } } depthSearched++; target = target.parent(); }; return; }; var enableListener = function() { body.on(interaction, dispatcher); }; enableListener(); if (interaction !== 'click') { // Disable mouseover listeners on scroll var timer = false; localnwt.one(document).on('scroll', function() { body.off(interaction, dispatcher); if (timer) { clearTimeout(timer); timer = false; } timer = setTimeout(enableListener, 75); }); } }
javascript
function(attribute, pattern, callback, interaction, maxDepth) { var classPattern = new RegExp(pattern), interaction = interaction || 'click', maxSearch, dispatcher, body = localnwt.one('body'); // Currently only search one level for a mouse listener for performance reasons if (interaction == 'click') { maxSearch = 100; } else { maxSearch = maxDepth || 1; } dispatcher = function(e) { var originalTarget = e.target, target = originalTarget, // Did we find it? found = true, // Keep track of how many times we bubble up depthSearched = 0; while(target._node && target._node.parentNode) { if (target._node == localnwt.one('body')._node || depthSearched >= maxSearch) { break; } if (target.hasAttribute(attribute)) { var matches = target.getAttribute(attribute).match(pattern); if (matches) { callback(originalTarget, target, matches); // If we found a callback, we usually want to stop the event // Except for input elements (still want checkboxes to check and stuff) if( target.get('nodeName').toUpperCase() !== "INPUT") { e.stop(); } break; } } depthSearched++; target = target.parent(); }; return; }; var enableListener = function() { body.on(interaction, dispatcher); }; enableListener(); if (interaction !== 'click') { // Disable mouseover listeners on scroll var timer = false; localnwt.one(document).on('scroll', function() { body.off(interaction, dispatcher); if (timer) { clearTimeout(timer); timer = false; } timer = setTimeout(enableListener, 75); }); } }
[ "function", "(", "attribute", ",", "pattern", ",", "callback", ",", "interaction", ",", "maxDepth", ")", "{", "var", "classPattern", "=", "new", "RegExp", "(", "pattern", ")", ",", "interaction", "=", "interaction", "||", "'click'", ",", "maxSearch", ",", "dispatcher", ",", "body", "=", "localnwt", ".", "one", "(", "'body'", ")", ";", "// Currently only search one level for a mouse listener for performance reasons", "if", "(", "interaction", "==", "'click'", ")", "{", "maxSearch", "=", "100", ";", "}", "else", "{", "maxSearch", "=", "maxDepth", "||", "1", ";", "}", "dispatcher", "=", "function", "(", "e", ")", "{", "var", "originalTarget", "=", "e", ".", "target", ",", "target", "=", "originalTarget", ",", "// Did we find it?", "found", "=", "true", ",", "// Keep track of how many times we bubble up", "depthSearched", "=", "0", ";", "while", "(", "target", ".", "_node", "&&", "target", ".", "_node", ".", "parentNode", ")", "{", "if", "(", "target", ".", "_node", "==", "localnwt", ".", "one", "(", "'body'", ")", ".", "_node", "||", "depthSearched", ">=", "maxSearch", ")", "{", "break", ";", "}", "if", "(", "target", ".", "hasAttribute", "(", "attribute", ")", ")", "{", "var", "matches", "=", "target", ".", "getAttribute", "(", "attribute", ")", ".", "match", "(", "pattern", ")", ";", "if", "(", "matches", ")", "{", "callback", "(", "originalTarget", ",", "target", ",", "matches", ")", ";", "// If we found a callback, we usually want to stop the event", "// Except for input elements (still want checkboxes to check and stuff)", "if", "(", "target", ".", "get", "(", "'nodeName'", ")", ".", "toUpperCase", "(", ")", "!==", "\"INPUT\"", ")", "{", "e", ".", "stop", "(", ")", ";", "}", "break", ";", "}", "}", "depthSearched", "++", ";", "target", "=", "target", ".", "parent", "(", ")", ";", "}", ";", "return", ";", "}", ";", "var", "enableListener", "=", "function", "(", ")", "{", "body", ".", "on", "(", "interaction", ",", "dispatcher", ")", ";", "}", ";", "enableListener", "(", ")", ";", "if", "(", "interaction", "!==", "'click'", ")", "{", "// Disable mouseover listeners on scroll", "var", "timer", "=", "false", ";", "localnwt", ".", "one", "(", "document", ")", ".", "on", "(", "'scroll'", ",", "function", "(", ")", "{", "body", ".", "off", "(", "interaction", ",", "dispatcher", ")", ";", "if", "(", "timer", ")", "{", "clearTimeout", "(", "timer", ")", ";", "timer", "=", "false", ";", "}", "timer", "=", "setTimeout", "(", "enableListener", ",", "75", ")", ";", "}", ")", ";", "}", "}" ]
Adds a live listener to the page This allows us to update page components, and still have javascript function properly @param string Attribute to check on @param regex Pattern to match against the string @param function callback if matched @param string Type of listener to use, one of: click | mousemove | mouseout @param integer Max depth to search. Defaults to 1 for a mouseover action
[ "Adds", "a", "live", "listener", "to", "the", "page", "This", "allows", "us", "to", "update", "page", "components", "and", "still", "have", "javascript", "function", "properly" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/event/js/event.js#L99-L178
37,926
nwtjs/nwt
src/event/js/event.js
function (implementOn, event, callback) { var stringy = callback.toString(); if (this._cached[stringy]) { // Iteratre through the cached callbacks and remove the correct one based on reference for(var i=0,numCbs=this._cached[stringy].length; i < numCbs; i++) { if (this._cached[stringy][i].raw === callback) { implementOn.removeEventListener(event, this._cached[stringy][i].fn); } } } }
javascript
function (implementOn, event, callback) { var stringy = callback.toString(); if (this._cached[stringy]) { // Iteratre through the cached callbacks and remove the correct one based on reference for(var i=0,numCbs=this._cached[stringy].length; i < numCbs; i++) { if (this._cached[stringy][i].raw === callback) { implementOn.removeEventListener(event, this._cached[stringy][i].fn); } } } }
[ "function", "(", "implementOn", ",", "event", ",", "callback", ")", "{", "var", "stringy", "=", "callback", ".", "toString", "(", ")", ";", "if", "(", "this", ".", "_cached", "[", "stringy", "]", ")", "{", "// Iteratre through the cached callbacks and remove the correct one based on reference", "for", "(", "var", "i", "=", "0", ",", "numCbs", "=", "this", ".", "_cached", "[", "stringy", "]", ".", "length", ";", "i", "<", "numCbs", ";", "i", "++", ")", "{", "if", "(", "this", ".", "_cached", "[", "stringy", "]", "[", "i", "]", ".", "raw", "===", "callback", ")", "{", "implementOn", ".", "removeEventListener", "(", "event", ",", "this", ".", "_cached", "[", "stringy", "]", "[", "i", "]", ".", "fn", ")", ";", "}", "}", "}", "}" ]
Removes an event listener from an eventable object @param string Name Event name @param function Callback Event callback
[ "Removes", "an", "event", "listener", "from", "an", "eventable", "object" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/event/js/event.js#L250-L262
37,927
XOP/sass-vars-to-js
src/_get-expression-value.js
getExpressionValue
function getExpressionValue (varName, scssExpression) { if (is.undef(scssExpression) || is.args.empty(arguments)) { message('Error: Missing arguments'); return undefined; } if (!is.string(varName) || !is.string(scssExpression)) { message('Error: Check arguments type'); return undefined; } if (!~scssExpression.indexOf('$')) { message('Warning: Check scssExpression to contain valid code') } // print the interpolated value in comment string // /*#{$varName}*/ --> /*varValue*/ const scssContent = `${scssExpression}/*#{$${varName}}*/`; const sassResult = sass.renderSync({ data: scssContent }); const cssResult = sassResult.css.toString(); return extractExpressionValue(cssResult); }
javascript
function getExpressionValue (varName, scssExpression) { if (is.undef(scssExpression) || is.args.empty(arguments)) { message('Error: Missing arguments'); return undefined; } if (!is.string(varName) || !is.string(scssExpression)) { message('Error: Check arguments type'); return undefined; } if (!~scssExpression.indexOf('$')) { message('Warning: Check scssExpression to contain valid code') } // print the interpolated value in comment string // /*#{$varName}*/ --> /*varValue*/ const scssContent = `${scssExpression}/*#{$${varName}}*/`; const sassResult = sass.renderSync({ data: scssContent }); const cssResult = sassResult.css.toString(); return extractExpressionValue(cssResult); }
[ "function", "getExpressionValue", "(", "varName", ",", "scssExpression", ")", "{", "if", "(", "is", ".", "undef", "(", "scssExpression", ")", "||", "is", ".", "args", ".", "empty", "(", "arguments", ")", ")", "{", "message", "(", "'Error: Missing arguments'", ")", ";", "return", "undefined", ";", "}", "if", "(", "!", "is", ".", "string", "(", "varName", ")", "||", "!", "is", ".", "string", "(", "scssExpression", ")", ")", "{", "message", "(", "'Error: Check arguments type'", ")", ";", "return", "undefined", ";", "}", "if", "(", "!", "~", "scssExpression", ".", "indexOf", "(", "'$'", ")", ")", "{", "message", "(", "'Warning: Check scssExpression to contain valid code'", ")", "}", "// print the interpolated value in comment string", "// /*#{$varName}*/ --> /*varValue*/", "const", "scssContent", "=", "`", "${", "scssExpression", "}", "${", "varName", "}", "`", ";", "const", "sassResult", "=", "sass", ".", "renderSync", "(", "{", "data", ":", "scssContent", "}", ")", ";", "const", "cssResult", "=", "sassResult", ".", "css", ".", "toString", "(", ")", ";", "return", "extractExpressionValue", "(", "cssResult", ")", ";", "}" ]
Resolve variable value By variable name and previous code @param varName @param scssExpression
[ "Resolve", "variable", "value", "By", "variable", "name", "and", "previous", "code" ]
87ad8588701a9c2e69ace75931947d11698f25f0
https://github.com/XOP/sass-vars-to-js/blob/87ad8588701a9c2e69ace75931947d11698f25f0/src/_get-expression-value.js#L14-L40
37,928
XOP/sass-vars-to-js
src/_get-expression-value.js
extractExpressionValue
function extractExpressionValue (css) { // parse the comment string: // /*varValue*/ --> varValue const valueRegExp = /(?:\/\*)(.+)(?:\*\/)/; const value = css.match(valueRegExp)[1]; if (!value) { message('Warning: empty value'); } return value; }
javascript
function extractExpressionValue (css) { // parse the comment string: // /*varValue*/ --> varValue const valueRegExp = /(?:\/\*)(.+)(?:\*\/)/; const value = css.match(valueRegExp)[1]; if (!value) { message('Warning: empty value'); } return value; }
[ "function", "extractExpressionValue", "(", "css", ")", "{", "// parse the comment string:", "// /*varValue*/ --> varValue", "const", "valueRegExp", "=", "/", "(?:\\/\\*)(.+)(?:\\*\\/)", "/", ";", "const", "value", "=", "css", ".", "match", "(", "valueRegExp", ")", "[", "1", "]", ";", "if", "(", "!", "value", ")", "{", "message", "(", "'Warning: empty value'", ")", ";", "}", "return", "value", ";", "}" ]
Parse calculated variable value From CSS comment @param css @returns {*}
[ "Parse", "calculated", "variable", "value", "From", "CSS", "comment" ]
87ad8588701a9c2e69ace75931947d11698f25f0
https://github.com/XOP/sass-vars-to-js/blob/87ad8588701a9c2e69ace75931947d11698f25f0/src/_get-expression-value.js#L48-L60
37,929
byron-dupreez/aws-core-utils
regions.js
getRegion
function getRegion() { const awsRegion = trim(process.env.AWS_REGION); return awsRegion !== "undefined" && awsRegion !== "null" ? awsRegion : undefined; }
javascript
function getRegion() { const awsRegion = trim(process.env.AWS_REGION); return awsRegion !== "undefined" && awsRegion !== "null" ? awsRegion : undefined; }
[ "function", "getRegion", "(", ")", "{", "const", "awsRegion", "=", "trim", "(", "process", ".", "env", ".", "AWS_REGION", ")", ";", "return", "awsRegion", "!==", "\"undefined\"", "&&", "awsRegion", "!==", "\"null\"", "?", "awsRegion", ":", "undefined", ";", "}" ]
Gets the region in which this function is running from the `AWS_REGION` environment variable and returns it as is if it's neither "undefined" nor "null"; otherwise returns undefined. @returns {string|undefined} the AWS region (if it exists); otherwise undefined.
[ "Gets", "the", "region", "in", "which", "this", "function", "is", "running", "from", "the", "AWS_REGION", "environment", "variable", "and", "returns", "it", "as", "is", "if", "it", "s", "neither", "undefined", "nor", "null", ";", "otherwise", "returns", "undefined", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/regions.js#L41-L44
37,930
byron-dupreez/aws-core-utils
regions.js
configureRegion
function configureRegion(context) { // Resolve the AWS region, if it is not already defined on the context if (!context.region) { context.region = getRegion(); } const msg = `Using region (${process.env.AWS_REGION}) & context.region (${context.region})`; context.debug ? context.debug(msg) : console.log(msg); return context; }
javascript
function configureRegion(context) { // Resolve the AWS region, if it is not already defined on the context if (!context.region) { context.region = getRegion(); } const msg = `Using region (${process.env.AWS_REGION}) & context.region (${context.region})`; context.debug ? context.debug(msg) : console.log(msg); return context; }
[ "function", "configureRegion", "(", "context", ")", "{", "// Resolve the AWS region, if it is not already defined on the context", "if", "(", "!", "context", ".", "region", ")", "{", "context", ".", "region", "=", "getRegion", "(", ")", ";", "}", "const", "msg", "=", "`", "${", "process", ".", "env", ".", "AWS_REGION", "}", "${", "context", ".", "region", "}", "`", ";", "context", ".", "debug", "?", "context", ".", "debug", "(", "msg", ")", ":", "console", ".", "log", "(", "msg", ")", ";", "return", "context", ";", "}" ]
Keeps context.region as is if it's already configured on the given context, otherwise gets the current region from process.env.AWS_REGION and sets it on the context as context.region. @param {Object|RegionAware} context - a context on which to set the region @returns {RegionAware} the context with its existing region or the current AWS_REGION env variable value.
[ "Keeps", "context", ".", "region", "as", "is", "if", "it", "s", "already", "configured", "on", "the", "given", "context", "otherwise", "gets", "the", "current", "region", "from", "process", ".", "env", ".", "AWS_REGION", "and", "sets", "it", "on", "the", "context", "as", "context", ".", "region", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/regions.js#L143-L151
37,931
byron-dupreez/aws-core-utils
regions.js
getOrSetRegionKey
function getOrSetRegionKey(region) { const regionName = region ? region : getRegion(); let regionKey = regionKeysByRegion.get(regionName); if (!regionKey) { regionKey = {region: regionName}; regionKeysByRegion.set(regionName, regionKey); } return regionKey; }
javascript
function getOrSetRegionKey(region) { const regionName = region ? region : getRegion(); let regionKey = regionKeysByRegion.get(regionName); if (!regionKey) { regionKey = {region: regionName}; regionKeysByRegion.set(regionName, regionKey); } return regionKey; }
[ "function", "getOrSetRegionKey", "(", "region", ")", "{", "const", "regionName", "=", "region", "?", "region", ":", "getRegion", "(", ")", ";", "let", "regionKey", "=", "regionKeysByRegion", ".", "get", "(", "regionName", ")", ";", "if", "(", "!", "regionKey", ")", "{", "regionKey", "=", "{", "region", ":", "regionName", "}", ";", "regionKeysByRegion", ".", "set", "(", "regionName", ",", "regionKey", ")", ";", "}", "return", "regionKey", ";", "}" ]
Returns the existing region key object or sets & returns a new region key object for the given region name. @param {string|undefined} [region] - the name of the region (defaults to current region if not defined) @returns {{region: string}} a region key object
[ "Returns", "the", "existing", "region", "key", "object", "or", "sets", "&", "returns", "a", "new", "region", "key", "object", "for", "the", "given", "region", "name", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/regions.js#L168-L176
37,932
dutchenkoOleg/happiness-scss
linter.js
transformConfig
function transformConfig (config) { if (config === null || typeof config !== 'object') { config = {}; } if (!Object.keys(config).length) { return { options: {}, files: { ignore: [ignoreNodeModules()] } }; } let runConfig = { options: { showMaxStack: 0 } }; if (config.noDisabling) { runConfig.options.noDisabling = true; } if (config.formatter) { runConfig.options.formatter = config.formatter; } if (config.showMaxStack >= 0) { runConfig.options.showMaxStack = config.showMaxStack; } if (config.outputFile) { runConfig.options['output-file'] = config.outputFile; } if (Array.isArray(config.ignore)) { runConfig.files = { ignore: config.ignore.concat(ignoreNodeModules()) }; } else { runConfig.files = { ignore: [ignoreNodeModules()] }; } return runConfig; }
javascript
function transformConfig (config) { if (config === null || typeof config !== 'object') { config = {}; } if (!Object.keys(config).length) { return { options: {}, files: { ignore: [ignoreNodeModules()] } }; } let runConfig = { options: { showMaxStack: 0 } }; if (config.noDisabling) { runConfig.options.noDisabling = true; } if (config.formatter) { runConfig.options.formatter = config.formatter; } if (config.showMaxStack >= 0) { runConfig.options.showMaxStack = config.showMaxStack; } if (config.outputFile) { runConfig.options['output-file'] = config.outputFile; } if (Array.isArray(config.ignore)) { runConfig.files = { ignore: config.ignore.concat(ignoreNodeModules()) }; } else { runConfig.files = { ignore: [ignoreNodeModules()] }; } return runConfig; }
[ "function", "transformConfig", "(", "config", ")", "{", "if", "(", "config", "===", "null", "||", "typeof", "config", "!==", "'object'", ")", "{", "config", "=", "{", "}", ";", "}", "if", "(", "!", "Object", ".", "keys", "(", "config", ")", ".", "length", ")", "{", "return", "{", "options", ":", "{", "}", ",", "files", ":", "{", "ignore", ":", "[", "ignoreNodeModules", "(", ")", "]", "}", "}", ";", "}", "let", "runConfig", "=", "{", "options", ":", "{", "showMaxStack", ":", "0", "}", "}", ";", "if", "(", "config", ".", "noDisabling", ")", "{", "runConfig", ".", "options", ".", "noDisabling", "=", "true", ";", "}", "if", "(", "config", ".", "formatter", ")", "{", "runConfig", ".", "options", ".", "formatter", "=", "config", ".", "formatter", ";", "}", "if", "(", "config", ".", "showMaxStack", ">=", "0", ")", "{", "runConfig", ".", "options", ".", "showMaxStack", "=", "config", ".", "showMaxStack", ";", "}", "if", "(", "config", ".", "outputFile", ")", "{", "runConfig", ".", "options", "[", "'output-file'", "]", "=", "config", ".", "outputFile", ";", "}", "if", "(", "Array", ".", "isArray", "(", "config", ".", "ignore", ")", ")", "{", "runConfig", ".", "files", "=", "{", "ignore", ":", "config", ".", "ignore", ".", "concat", "(", "ignoreNodeModules", "(", ")", ")", "}", ";", "}", "else", "{", "runConfig", ".", "files", "=", "{", "ignore", ":", "[", "ignoreNodeModules", "(", ")", "]", "}", ";", "}", "return", "runConfig", ";", "}" ]
Transform user config for linter config @private @param {Object} [config] @returns {Object}
[ "Transform", "user", "config", "for", "linter", "config" ]
03307cd4ee5f7b3fa2ee000f69d91f80ebbbd04c
https://github.com/dutchenkoOleg/happiness-scss/blob/03307cd4ee5f7b3fa2ee000f69d91f80ebbbd04c/linter.js#L40-L84
37,933
dutchenkoOleg/happiness-scss
linter.js
lintMethod
function lintMethod (mtd, file, config, cb, configPath) { let runConfig = transformConfig(config); if (typeof cb !== 'function') { cb = function () {}; } try { let results = sassLint[mtd](file, runConfig, configPath); if (mtd !== 'lintFiles') { if (!Array.isArray(results)) { results = [results]; } } let data = { results, errorCount: sassLint.errorCount(results), warningCount: sassLint.warningCount(results) }; cb(null, data); } catch (err) { cb(err); } }
javascript
function lintMethod (mtd, file, config, cb, configPath) { let runConfig = transformConfig(config); if (typeof cb !== 'function') { cb = function () {}; } try { let results = sassLint[mtd](file, runConfig, configPath); if (mtd !== 'lintFiles') { if (!Array.isArray(results)) { results = [results]; } } let data = { results, errorCount: sassLint.errorCount(results), warningCount: sassLint.warningCount(results) }; cb(null, data); } catch (err) { cb(err); } }
[ "function", "lintMethod", "(", "mtd", ",", "file", ",", "config", ",", "cb", ",", "configPath", ")", "{", "let", "runConfig", "=", "transformConfig", "(", "config", ")", ";", "if", "(", "typeof", "cb", "!==", "'function'", ")", "{", "cb", "=", "function", "(", ")", "{", "}", ";", "}", "try", "{", "let", "results", "=", "sassLint", "[", "mtd", "]", "(", "file", ",", "runConfig", ",", "configPath", ")", ";", "if", "(", "mtd", "!==", "'lintFiles'", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "results", ")", ")", "{", "results", "=", "[", "results", "]", ";", "}", "}", "let", "data", "=", "{", "results", ",", "errorCount", ":", "sassLint", ".", "errorCount", "(", "results", ")", ",", "warningCount", ":", "sassLint", ".", "warningCount", "(", "results", ")", "}", ";", "cb", "(", "null", ",", "data", ")", ";", "}", "catch", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "}", "}" ]
Creating linting methods with happiness-scss configPath @param {string} mtd @param {string} file @param {Object} [config] @param {function} [cb] @param {string} configPath
[ "Creating", "linting", "methods", "with", "happiness", "-", "scss", "configPath" ]
03307cd4ee5f7b3fa2ee000f69d91f80ebbbd04c
https://github.com/dutchenkoOleg/happiness-scss/blob/03307cd4ee5f7b3fa2ee000f69d91f80ebbbd04c/linter.js#L94-L120
37,934
recidive/choko
lib/install.js
install
function install(destination, prg, callback) { prompt.start(); prompt.message = ':'.white.bold.bgBlack; prompt.delimiter = ': '.white.bold.bgBlack; var schema = { properties: { appName: { description: 'Application name'.white.bold.bgBlack, pattern: /^[a-zA-Z0-9\s\-]+$/, message: 'Application name must be only letters, spaces, or dashes', default: path.basename(destination), required: true }, appEmail: { description: 'Application email address'.white.bold.bgBlack, conform: validator.isEmail, message: 'Enter a valid email', required: true }, adminName: { description: 'Administrator username'.white.bold.bgBlack, conform: validator.isAlphanumeric, default: 'admin', message: 'Enter a valid username e.g. admin', required: true }, adminPass: { description: 'Administrator password (at least 6 characters)'.white.bold.bgBlack, hidden: true, conform: function (pass) { return validator.isLength(pass, 6); }, message: 'Password must have at least 6 characters.', required: true }, adminEmail: { description: 'Administrator email address'.white.bold.bgBlack, conform: validator.isEmail, message: 'Enter a valid email', required: true }, database: { description: 'Database URI'.white.bold.bgBlack, conform: function(uri) { return validator.isURL(uri, { protocols: ['mongodb'], require_protocol: true, allow_underscores: true }); }, default: 'mongodb://localhost/' + path.basename(destination), message: 'Enter a valid URI for your database e.g. mongodb://localhost/chokoapp', required: true } } }; prompt.get(schema, function (error, result) { if (error) { return console.log('\nInstall aborted, no changes were made.'); } doInstall({ application: { name: result.appName, email: result.appEmail }, database: result.database, sessionSecret: crypto.randomBytes(32).toString('base64') }, destination); var app = new Application(destination); app.start(prg.port, function(error, app) { if (error) { throw error; } createAdminUser(app, result, function(error, newAccount, errors) { // @todo: handle errors. util.log('Navigate to http://localhost:' + prg.port + ' to start building your new application.'); }); }); }); }
javascript
function install(destination, prg, callback) { prompt.start(); prompt.message = ':'.white.bold.bgBlack; prompt.delimiter = ': '.white.bold.bgBlack; var schema = { properties: { appName: { description: 'Application name'.white.bold.bgBlack, pattern: /^[a-zA-Z0-9\s\-]+$/, message: 'Application name must be only letters, spaces, or dashes', default: path.basename(destination), required: true }, appEmail: { description: 'Application email address'.white.bold.bgBlack, conform: validator.isEmail, message: 'Enter a valid email', required: true }, adminName: { description: 'Administrator username'.white.bold.bgBlack, conform: validator.isAlphanumeric, default: 'admin', message: 'Enter a valid username e.g. admin', required: true }, adminPass: { description: 'Administrator password (at least 6 characters)'.white.bold.bgBlack, hidden: true, conform: function (pass) { return validator.isLength(pass, 6); }, message: 'Password must have at least 6 characters.', required: true }, adminEmail: { description: 'Administrator email address'.white.bold.bgBlack, conform: validator.isEmail, message: 'Enter a valid email', required: true }, database: { description: 'Database URI'.white.bold.bgBlack, conform: function(uri) { return validator.isURL(uri, { protocols: ['mongodb'], require_protocol: true, allow_underscores: true }); }, default: 'mongodb://localhost/' + path.basename(destination), message: 'Enter a valid URI for your database e.g. mongodb://localhost/chokoapp', required: true } } }; prompt.get(schema, function (error, result) { if (error) { return console.log('\nInstall aborted, no changes were made.'); } doInstall({ application: { name: result.appName, email: result.appEmail }, database: result.database, sessionSecret: crypto.randomBytes(32).toString('base64') }, destination); var app = new Application(destination); app.start(prg.port, function(error, app) { if (error) { throw error; } createAdminUser(app, result, function(error, newAccount, errors) { // @todo: handle errors. util.log('Navigate to http://localhost:' + prg.port + ' to start building your new application.'); }); }); }); }
[ "function", "install", "(", "destination", ",", "prg", ",", "callback", ")", "{", "prompt", ".", "start", "(", ")", ";", "prompt", ".", "message", "=", "':'", ".", "white", ".", "bold", ".", "bgBlack", ";", "prompt", ".", "delimiter", "=", "': '", ".", "white", ".", "bold", ".", "bgBlack", ";", "var", "schema", "=", "{", "properties", ":", "{", "appName", ":", "{", "description", ":", "'Application name'", ".", "white", ".", "bold", ".", "bgBlack", ",", "pattern", ":", "/", "^[a-zA-Z0-9\\s\\-]+$", "/", ",", "message", ":", "'Application name must be only letters, spaces, or dashes'", ",", "default", ":", "path", ".", "basename", "(", "destination", ")", ",", "required", ":", "true", "}", ",", "appEmail", ":", "{", "description", ":", "'Application email address'", ".", "white", ".", "bold", ".", "bgBlack", ",", "conform", ":", "validator", ".", "isEmail", ",", "message", ":", "'Enter a valid email'", ",", "required", ":", "true", "}", ",", "adminName", ":", "{", "description", ":", "'Administrator username'", ".", "white", ".", "bold", ".", "bgBlack", ",", "conform", ":", "validator", ".", "isAlphanumeric", ",", "default", ":", "'admin'", ",", "message", ":", "'Enter a valid username e.g. admin'", ",", "required", ":", "true", "}", ",", "adminPass", ":", "{", "description", ":", "'Administrator password (at least 6 characters)'", ".", "white", ".", "bold", ".", "bgBlack", ",", "hidden", ":", "true", ",", "conform", ":", "function", "(", "pass", ")", "{", "return", "validator", ".", "isLength", "(", "pass", ",", "6", ")", ";", "}", ",", "message", ":", "'Password must have at least 6 characters.'", ",", "required", ":", "true", "}", ",", "adminEmail", ":", "{", "description", ":", "'Administrator email address'", ".", "white", ".", "bold", ".", "bgBlack", ",", "conform", ":", "validator", ".", "isEmail", ",", "message", ":", "'Enter a valid email'", ",", "required", ":", "true", "}", ",", "database", ":", "{", "description", ":", "'Database URI'", ".", "white", ".", "bold", ".", "bgBlack", ",", "conform", ":", "function", "(", "uri", ")", "{", "return", "validator", ".", "isURL", "(", "uri", ",", "{", "protocols", ":", "[", "'mongodb'", "]", ",", "require_protocol", ":", "true", ",", "allow_underscores", ":", "true", "}", ")", ";", "}", ",", "default", ":", "'mongodb://localhost/'", "+", "path", ".", "basename", "(", "destination", ")", ",", "message", ":", "'Enter a valid URI for your database e.g. mongodb://localhost/chokoapp'", ",", "required", ":", "true", "}", "}", "}", ";", "prompt", ".", "get", "(", "schema", ",", "function", "(", "error", ",", "result", ")", "{", "if", "(", "error", ")", "{", "return", "console", ".", "log", "(", "'\\nInstall aborted, no changes were made.'", ")", ";", "}", "doInstall", "(", "{", "application", ":", "{", "name", ":", "result", ".", "appName", ",", "email", ":", "result", ".", "appEmail", "}", ",", "database", ":", "result", ".", "database", ",", "sessionSecret", ":", "crypto", ".", "randomBytes", "(", "32", ")", ".", "toString", "(", "'base64'", ")", "}", ",", "destination", ")", ";", "var", "app", "=", "new", "Application", "(", "destination", ")", ";", "app", ".", "start", "(", "prg", ".", "port", ",", "function", "(", "error", ",", "app", ")", "{", "if", "(", "error", ")", "{", "throw", "error", ";", "}", "createAdminUser", "(", "app", ",", "result", ",", "function", "(", "error", ",", "newAccount", ",", "errors", ")", "{", "// @todo: handle errors.", "util", ".", "log", "(", "'Navigate to http://localhost:'", "+", "prg", ".", "port", "+", "' to start building your new application.'", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Run a questionnaire for interactively configuring the new application.
[ "Run", "a", "questionnaire", "for", "interactively", "configuring", "the", "new", "application", "." ]
7c0576c8c55543ec99d04ea609700765f178f73a
https://github.com/recidive/choko/blob/7c0576c8c55543ec99d04ea609700765f178f73a/lib/install.js#L17-L105
37,935
recidive/choko
lib/install.js
doInstall
function doInstall(settings, destination) { // Create application directories if they don't exist. var folders = [ destination, path.join(destination, '/public'), path.join(destination, '/extensions') ]; folders.forEach(function(folder) { if (!fs.existsSync(folder)) { fs.mkdirSync(folder); } }); // Create settings.json. fs.writeFileSync(path.join(destination, 'settings.json'), JSON.stringify(settings, null, ' '), {flag: 'w'}); }
javascript
function doInstall(settings, destination) { // Create application directories if they don't exist. var folders = [ destination, path.join(destination, '/public'), path.join(destination, '/extensions') ]; folders.forEach(function(folder) { if (!fs.existsSync(folder)) { fs.mkdirSync(folder); } }); // Create settings.json. fs.writeFileSync(path.join(destination, 'settings.json'), JSON.stringify(settings, null, ' '), {flag: 'w'}); }
[ "function", "doInstall", "(", "settings", ",", "destination", ")", "{", "// Create application directories if they don't exist.", "var", "folders", "=", "[", "destination", ",", "path", ".", "join", "(", "destination", ",", "'/public'", ")", ",", "path", ".", "join", "(", "destination", ",", "'/extensions'", ")", "]", ";", "folders", ".", "forEach", "(", "function", "(", "folder", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "folder", ")", ")", "{", "fs", ".", "mkdirSync", "(", "folder", ")", ";", "}", "}", ")", ";", "// Create settings.json.", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "destination", ",", "'settings.json'", ")", ",", "JSON", ".", "stringify", "(", "settings", ",", "null", ",", "' '", ")", ",", "{", "flag", ":", "'w'", "}", ")", ";", "}" ]
Create application folder structure and initial settings.
[ "Create", "application", "folder", "structure", "and", "initial", "settings", "." ]
7c0576c8c55543ec99d04ea609700765f178f73a
https://github.com/recidive/choko/blob/7c0576c8c55543ec99d04ea609700765f178f73a/lib/install.js#L110-L125
37,936
recidive/choko
lib/install.js
createAdminUser
function createAdminUser(app, result, callback) { // Create the admin user. var User = app.type('user'); var userData = { username: result.adminName, password: result.adminPass, email: result.adminEmail, roles: ['administrator'] }; User.validateAndSave(userData, callback); }
javascript
function createAdminUser(app, result, callback) { // Create the admin user. var User = app.type('user'); var userData = { username: result.adminName, password: result.adminPass, email: result.adminEmail, roles: ['administrator'] }; User.validateAndSave(userData, callback); }
[ "function", "createAdminUser", "(", "app", ",", "result", ",", "callback", ")", "{", "// Create the admin user.", "var", "User", "=", "app", ".", "type", "(", "'user'", ")", ";", "var", "userData", "=", "{", "username", ":", "result", ".", "adminName", ",", "password", ":", "result", ".", "adminPass", ",", "email", ":", "result", ".", "adminEmail", ",", "roles", ":", "[", "'administrator'", "]", "}", ";", "User", ".", "validateAndSave", "(", "userData", ",", "callback", ")", ";", "}" ]
Create administrator user.
[ "Create", "administrator", "user", "." ]
7c0576c8c55543ec99d04ea609700765f178f73a
https://github.com/recidive/choko/blob/7c0576c8c55543ec99d04ea609700765f178f73a/lib/install.js#L130-L140
37,937
jgable/react-native-fluxbone
lib/dispatcherEvents.js
function () { // Allow using a function or an object var events = _.result(this, 'dispatcherEvents'); if (_.isUndefined(events) || _.isEmpty(events)) { // Bug out early if no dispatcherEvents return; } var registrations = {}; _.each(events, function (funcOrName, actionType) { // Quick sanity check for whether there is a problem with the function/name passed if (!(_.isFunction(funcOrName) || _.isFunction(this[funcOrName]))) { console.warn('dispatcherEvent: "' + funcOrName + '" is not a function'); return; } if (_.isFunction(funcOrName)) { registrations[actionType] = funcOrName; } else { registrations[actionType] = this[funcOrName]; } }.bind(this)); this.dispatcherToken = dispatcher.register(registrations, this); }
javascript
function () { // Allow using a function or an object var events = _.result(this, 'dispatcherEvents'); if (_.isUndefined(events) || _.isEmpty(events)) { // Bug out early if no dispatcherEvents return; } var registrations = {}; _.each(events, function (funcOrName, actionType) { // Quick sanity check for whether there is a problem with the function/name passed if (!(_.isFunction(funcOrName) || _.isFunction(this[funcOrName]))) { console.warn('dispatcherEvent: "' + funcOrName + '" is not a function'); return; } if (_.isFunction(funcOrName)) { registrations[actionType] = funcOrName; } else { registrations[actionType] = this[funcOrName]; } }.bind(this)); this.dispatcherToken = dispatcher.register(registrations, this); }
[ "function", "(", ")", "{", "// Allow using a function or an object", "var", "events", "=", "_", ".", "result", "(", "this", ",", "'dispatcherEvents'", ")", ";", "if", "(", "_", ".", "isUndefined", "(", "events", ")", "||", "_", ".", "isEmpty", "(", "events", ")", ")", "{", "// Bug out early if no dispatcherEvents", "return", ";", "}", "var", "registrations", "=", "{", "}", ";", "_", ".", "each", "(", "events", ",", "function", "(", "funcOrName", ",", "actionType", ")", "{", "// Quick sanity check for whether there is a problem with the function/name passed", "if", "(", "!", "(", "_", ".", "isFunction", "(", "funcOrName", ")", "||", "_", ".", "isFunction", "(", "this", "[", "funcOrName", "]", ")", ")", ")", "{", "console", ".", "warn", "(", "'dispatcherEvent: \"'", "+", "funcOrName", "+", "'\" is not a function'", ")", ";", "return", ";", "}", "if", "(", "_", ".", "isFunction", "(", "funcOrName", ")", ")", "{", "registrations", "[", "actionType", "]", "=", "funcOrName", ";", "}", "else", "{", "registrations", "[", "actionType", "]", "=", "this", "[", "funcOrName", "]", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "dispatcherToken", "=", "dispatcher", ".", "register", "(", "registrations", ",", "this", ")", ";", "}" ]
Registers the dispatcherEvents hash
[ "Registers", "the", "dispatcherEvents", "hash" ]
9847a598da0cc72f056c6bd4d2e21909b146f530
https://github.com/jgable/react-native-fluxbone/blob/9847a598da0cc72f056c6bd4d2e21909b146f530/lib/dispatcherEvents.js#L16-L42
37,938
LeanKit-Labs/autohost
src/transport.js
getActions
function getActions( state, resource ) { var list = state.actionList[ resource.name ] = []; _.each( resource.actions, function( action, actionName ) { list.push( [ resource.name, actionName ].join( '.' ) ); } ); }
javascript
function getActions( state, resource ) { var list = state.actionList[ resource.name ] = []; _.each( resource.actions, function( action, actionName ) { list.push( [ resource.name, actionName ].join( '.' ) ); } ); }
[ "function", "getActions", "(", "state", ",", "resource", ")", "{", "var", "list", "=", "state", ".", "actionList", "[", "resource", ".", "name", "]", "=", "[", "]", ";", "_", ".", "each", "(", "resource", ".", "actions", ",", "function", "(", "action", ",", "actionName", ")", "{", "list", ".", "push", "(", "[", "resource", ".", "name", ",", "actionName", "]", ".", "join", "(", "'.'", ")", ")", ";", "}", ")", ";", "}" ]
store actions from the resource
[ "store", "actions", "from", "the", "resource" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/transport.js#L35-L40
37,939
LeanKit-Labs/autohost
src/transport.js
getArguments
function getArguments( fn ) { return _.isFunction( fn ) ? trim( /[(]([^)]*)[)]/.exec( fn.toString() )[ 1 ].split( ',' ) ) : []; }
javascript
function getArguments( fn ) { return _.isFunction( fn ) ? trim( /[(]([^)]*)[)]/.exec( fn.toString() )[ 1 ].split( ',' ) ) : []; }
[ "function", "getArguments", "(", "fn", ")", "{", "return", "_", ".", "isFunction", "(", "fn", ")", "?", "trim", "(", "/", "[(]([^)]*)[)]", "/", ".", "exec", "(", "fn", ".", "toString", "(", ")", ")", "[", "1", "]", ".", "split", "(", "','", ")", ")", ":", "[", "]", ";", "}" ]
reads argument names from a function
[ "reads", "argument", "names", "from", "a", "function" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/transport.js#L58-L60
37,940
LeanKit-Labs/autohost
src/transport.js
loadAll
function loadAll( state, resourcePath ) { var loadActions = [ loadResources( state, resourcePath ) ] || []; if ( state.config.modules ) { _.each( state.config.modules, function( mod ) { var modPath; if ( /[\/]/.test( mod ) ) { modPath = require.resolve( path.resolve( process.cwd(), mod ) ); } else { modPath = require.resolve( mod ); } loadActions.push( loadModule( state, modPath ) ); } ); } loadActions.push( loadModule( state, './ahResource' ) ); return when.all( loadActions ); }
javascript
function loadAll( state, resourcePath ) { var loadActions = [ loadResources( state, resourcePath ) ] || []; if ( state.config.modules ) { _.each( state.config.modules, function( mod ) { var modPath; if ( /[\/]/.test( mod ) ) { modPath = require.resolve( path.resolve( process.cwd(), mod ) ); } else { modPath = require.resolve( mod ); } loadActions.push( loadModule( state, modPath ) ); } ); } loadActions.push( loadModule( state, './ahResource' ) ); return when.all( loadActions ); }
[ "function", "loadAll", "(", "state", ",", "resourcePath", ")", "{", "var", "loadActions", "=", "[", "loadResources", "(", "state", ",", "resourcePath", ")", "]", "||", "[", "]", ";", "if", "(", "state", ".", "config", ".", "modules", ")", "{", "_", ".", "each", "(", "state", ".", "config", ".", "modules", ",", "function", "(", "mod", ")", "{", "var", "modPath", ";", "if", "(", "/", "[\\/]", "/", ".", "test", "(", "mod", ")", ")", "{", "modPath", "=", "require", ".", "resolve", "(", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "mod", ")", ")", ";", "}", "else", "{", "modPath", "=", "require", ".", "resolve", "(", "mod", ")", ";", "}", "loadActions", ".", "push", "(", "loadModule", "(", "state", ",", "modPath", ")", ")", ";", "}", ")", ";", "}", "loadActions", ".", "push", "(", "loadModule", "(", "state", ",", "'./ahResource'", ")", ")", ";", "return", "when", ".", "all", "(", "loadActions", ")", ";", "}" ]
loads internal resources, resources from config path and node module resources
[ "loads", "internal", "resources", "resources", "from", "config", "path", "and", "node", "module", "resources" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/transport.js#L80-L95
37,941
LeanKit-Labs/autohost
src/transport.js
loadModule
function loadModule( state, resourcePath ) { try { var key = path.resolve( resourcePath ); delete require.cache[ key ]; var modFn = require( resourcePath ); var args = getArguments( modFn ); args.shift(); if ( args.length ) { return state.fount.resolve( args ) .then( function( deps ) { var argList = _.map( args, function( arg ) { return deps[ arg ]; } ); argList.unshift( state.host ); var mod = modFn.apply( modFn, argList ); attachPath( state, mod, resourcePath ); return mod; } ); } else { var mod = modFn( state.host ); attachPath( state, mod, resourcePath ); return when( mod ); } } catch ( err ) { console.error( 'Error loading resource module at %s with: %s', resourcePath, err.stack ); return when( [] ); } }
javascript
function loadModule( state, resourcePath ) { try { var key = path.resolve( resourcePath ); delete require.cache[ key ]; var modFn = require( resourcePath ); var args = getArguments( modFn ); args.shift(); if ( args.length ) { return state.fount.resolve( args ) .then( function( deps ) { var argList = _.map( args, function( arg ) { return deps[ arg ]; } ); argList.unshift( state.host ); var mod = modFn.apply( modFn, argList ); attachPath( state, mod, resourcePath ); return mod; } ); } else { var mod = modFn( state.host ); attachPath( state, mod, resourcePath ); return when( mod ); } } catch ( err ) { console.error( 'Error loading resource module at %s with: %s', resourcePath, err.stack ); return when( [] ); } }
[ "function", "loadModule", "(", "state", ",", "resourcePath", ")", "{", "try", "{", "var", "key", "=", "path", ".", "resolve", "(", "resourcePath", ")", ";", "delete", "require", ".", "cache", "[", "key", "]", ";", "var", "modFn", "=", "require", "(", "resourcePath", ")", ";", "var", "args", "=", "getArguments", "(", "modFn", ")", ";", "args", ".", "shift", "(", ")", ";", "if", "(", "args", ".", "length", ")", "{", "return", "state", ".", "fount", ".", "resolve", "(", "args", ")", ".", "then", "(", "function", "(", "deps", ")", "{", "var", "argList", "=", "_", ".", "map", "(", "args", ",", "function", "(", "arg", ")", "{", "return", "deps", "[", "arg", "]", ";", "}", ")", ";", "argList", ".", "unshift", "(", "state", ".", "host", ")", ";", "var", "mod", "=", "modFn", ".", "apply", "(", "modFn", ",", "argList", ")", ";", "attachPath", "(", "state", ",", "mod", ",", "resourcePath", ")", ";", "return", "mod", ";", "}", ")", ";", "}", "else", "{", "var", "mod", "=", "modFn", "(", "state", ".", "host", ")", ";", "attachPath", "(", "state", ",", "mod", ",", "resourcePath", ")", ";", "return", "when", "(", "mod", ")", ";", "}", "}", "catch", "(", "err", ")", "{", "console", ".", "error", "(", "'Error loading resource module at %s with: %s'", ",", "resourcePath", ",", "err", ".", "stack", ")", ";", "return", "when", "(", "[", "]", ")", ";", "}", "}" ]
loads a module based on the file path and resolves the function promises and all
[ "loads", "a", "module", "based", "on", "the", "file", "path", "and", "resolves", "the", "function", "promises", "and", "all" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/transport.js#L100-L127
37,942
LeanKit-Labs/autohost
src/transport.js
loadResources
function loadResources( state, filePath ) { var resourcePath = path.resolve( process.cwd(), filePath ); return getResources( resourcePath ) .then( function( list ) { return when.all( _.map( _.filter( list ), loadModule.bind( undefined, state ) ) ) .then( function( lists ) { return _.flatten( lists ); } ); } ); }
javascript
function loadResources( state, filePath ) { var resourcePath = path.resolve( process.cwd(), filePath ); return getResources( resourcePath ) .then( function( list ) { return when.all( _.map( _.filter( list ), loadModule.bind( undefined, state ) ) ) .then( function( lists ) { return _.flatten( lists ); } ); } ); }
[ "function", "loadResources", "(", "state", ",", "filePath", ")", "{", "var", "resourcePath", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "filePath", ")", ";", "return", "getResources", "(", "resourcePath", ")", ".", "then", "(", "function", "(", "list", ")", "{", "return", "when", ".", "all", "(", "_", ".", "map", "(", "_", ".", "filter", "(", "list", ")", ",", "loadModule", ".", "bind", "(", "undefined", ",", "state", ")", ")", ")", ".", "then", "(", "function", "(", "lists", ")", "{", "return", "_", ".", "flatten", "(", "lists", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
loadResources from path and returns the modules once they're loaded
[ "loadResources", "from", "path", "and", "returns", "the", "modules", "once", "they", "re", "loaded" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/transport.js#L130-L139
37,943
nwtjs/nwt
src/node/js/node.js
function(other) { var me = this.region(), you = other.region(); return !( me.left > you.right || me.right < you.left || me.top > you.bottom || me.bottom < you.top || you.left > me.right || you.right < me.left || you.top > me.bottom || you.bottom < me.top ); }
javascript
function(other) { var me = this.region(), you = other.region(); return !( me.left > you.right || me.right < you.left || me.top > you.bottom || me.bottom < you.top || you.left > me.right || you.right < me.left || you.top > me.bottom || you.bottom < me.top ); }
[ "function", "(", "other", ")", "{", "var", "me", "=", "this", ".", "region", "(", ")", ",", "you", "=", "other", ".", "region", "(", ")", ";", "return", "!", "(", "me", ".", "left", ">", "you", ".", "right", "||", "me", ".", "right", "<", "you", ".", "left", "||", "me", ".", "top", ">", "you", ".", "bottom", "||", "me", ".", "bottom", "<", "you", ".", "top", "||", "you", ".", "left", ">", "me", ".", "right", "||", "you", ".", "right", "<", "me", ".", "left", "||", "you", ".", "top", ">", "me", ".", "bottom", "||", "you", ".", "bottom", "<", "me", ".", "top", ")", ";", "}" ]
Checks if a given node intersects another @param object Node to check against
[ "Checks", "if", "a", "given", "node", "intersects", "another" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L53-L68
37,944
nwtjs/nwt
src/node/js/node.js
function(selector) { var allMatches = localnwt.all(selector), testNode = this._node, ancestor = null, maxDepth = 0; if( allMatches.size() == 0 ) { return null; } while( true ) { // Iterate through all matches for each parent, and exit as soon as we have a match // Pretty bad performance, but super small. TODO: Omtimize allMatches.each(function (el) { if (el._node == testNode) { ancestor = el; } }); var parentNode = testNode.parentNode; if( ancestor || !parentNode) { break; } testNode = parentNode; } if( ancestor ) { return ancestor; } else { return null; } }
javascript
function(selector) { var allMatches = localnwt.all(selector), testNode = this._node, ancestor = null, maxDepth = 0; if( allMatches.size() == 0 ) { return null; } while( true ) { // Iterate through all matches for each parent, and exit as soon as we have a match // Pretty bad performance, but super small. TODO: Omtimize allMatches.each(function (el) { if (el._node == testNode) { ancestor = el; } }); var parentNode = testNode.parentNode; if( ancestor || !parentNode) { break; } testNode = parentNode; } if( ancestor ) { return ancestor; } else { return null; } }
[ "function", "(", "selector", ")", "{", "var", "allMatches", "=", "localnwt", ".", "all", "(", "selector", ")", ",", "testNode", "=", "this", ".", "_node", ",", "ancestor", "=", "null", ",", "maxDepth", "=", "0", ";", "if", "(", "allMatches", ".", "size", "(", ")", "==", "0", ")", "{", "return", "null", ";", "}", "while", "(", "true", ")", "{", "// Iterate through all matches for each parent, and exit as soon as we have a match", "// Pretty bad performance, but super small. TODO: Omtimize", "allMatches", ".", "each", "(", "function", "(", "el", ")", "{", "if", "(", "el", ".", "_node", "==", "testNode", ")", "{", "ancestor", "=", "el", ";", "}", "}", ")", ";", "var", "parentNode", "=", "testNode", ".", "parentNode", ";", "if", "(", "ancestor", "||", "!", "parentNode", ")", "{", "break", ";", "}", "testNode", "=", "parentNode", ";", "}", "if", "(", "ancestor", ")", "{", "return", "ancestor", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns the ancestor that matches the css selector @param string CSS Selector
[ "Returns", "the", "ancestor", "that", "matches", "the", "css", "selector" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L75-L107
37,945
nwtjs/nwt
src/node/js/node.js
function(property) { if( property === 'parentNode' ) { var node = this._node[property]; if( !node ) { return null; } return new NWTNodeInstance(node); } return this._node[property]; }
javascript
function(property) { if( property === 'parentNode' ) { var node = this._node[property]; if( !node ) { return null; } return new NWTNodeInstance(node); } return this._node[property]; }
[ "function", "(", "property", ")", "{", "if", "(", "property", "===", "'parentNode'", ")", "{", "var", "node", "=", "this", ".", "_node", "[", "property", "]", ";", "if", "(", "!", "node", ")", "{", "return", "null", ";", "}", "return", "new", "NWTNodeInstance", "(", "node", ")", ";", "}", "return", "this", ".", "_node", "[", "property", "]", ";", "}" ]
Gets a property from the node object @param string Attribute to get
[ "Gets", "a", "property", "from", "the", "node", "object" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L176-L185
37,946
nwtjs/nwt
src/node/js/node.js
function(property) { if( !this.getAttribute('style') ) { return ''; } property = this._jsStyle(property); var matchedStyle = this._node.style[property]; if( matchedStyle ) { return matchedStyle; } else { return null; } }
javascript
function(property) { if( !this.getAttribute('style') ) { return ''; } property = this._jsStyle(property); var matchedStyle = this._node.style[property]; if( matchedStyle ) { return matchedStyle; } else { return null; } }
[ "function", "(", "property", ")", "{", "if", "(", "!", "this", ".", "getAttribute", "(", "'style'", ")", ")", "{", "return", "''", ";", "}", "property", "=", "this", ".", "_jsStyle", "(", "property", ")", ";", "var", "matchedStyle", "=", "this", ".", "_node", ".", "style", "[", "property", "]", ";", "if", "(", "matchedStyle", ")", "{", "return", "matchedStyle", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Gets a style attribute set on the node @param string Style attribute to get
[ "Gets", "a", "style", "attribute", "set", "on", "the", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L241-L256
37,947
nwtjs/nwt
src/node/js/node.js
function(props) { // Default properties to an array if (typeof props == 'string') { props = [props]; } var i, propsLen = props.length; for (i = 0; i < propsLen; i += 1) { this._node.style[props[i]] = ''; } return this; }
javascript
function(props) { // Default properties to an array if (typeof props == 'string') { props = [props]; } var i, propsLen = props.length; for (i = 0; i < propsLen; i += 1) { this._node.style[props[i]] = ''; } return this; }
[ "function", "(", "props", ")", "{", "// Default properties to an array", "if", "(", "typeof", "props", "==", "'string'", ")", "{", "props", "=", "[", "props", "]", ";", "}", "var", "i", ",", "propsLen", "=", "props", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "propsLen", ";", "i", "+=", "1", ")", "{", "this", ".", "_node", ".", "style", "[", "props", "[", "i", "]", "]", "=", "''", ";", "}", "return", "this", ";", "}" ]
Removes an array of styles from a node @param array Array of styles to remove
[ "Removes", "an", "array", "of", "styles", "from", "a", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L272-L285
37,948
nwtjs/nwt
src/node/js/node.js
function(newStyles) { if( !this.getAttribute('style') ) { this.setAttribute('style', ''); } var newStyle = '', // If the style matches one of the following, and we pass in an integer, default the unit // E.g., 10 becomes 10px defaultToUnit = { top: 'px', left: 'px', width: 'px', height: 'px' }, i, eachStyleValue, // Keep track of an array of styles that we need to remove newStyleKeys = []; for( i in newStyles ) { var styleKey = this._jsStyle(i), eachStyleVal = newStyles[i]; // Default the unit if necessary if (defaultToUnit[styleKey] && !isNaN(eachStyleVal)) { eachStyleVal += defaultToUnit[styleKey]; } this._node.style[styleKey] = eachStyleVal; } return this; }
javascript
function(newStyles) { if( !this.getAttribute('style') ) { this.setAttribute('style', ''); } var newStyle = '', // If the style matches one of the following, and we pass in an integer, default the unit // E.g., 10 becomes 10px defaultToUnit = { top: 'px', left: 'px', width: 'px', height: 'px' }, i, eachStyleValue, // Keep track of an array of styles that we need to remove newStyleKeys = []; for( i in newStyles ) { var styleKey = this._jsStyle(i), eachStyleVal = newStyles[i]; // Default the unit if necessary if (defaultToUnit[styleKey] && !isNaN(eachStyleVal)) { eachStyleVal += defaultToUnit[styleKey]; } this._node.style[styleKey] = eachStyleVal; } return this; }
[ "function", "(", "newStyles", ")", "{", "if", "(", "!", "this", ".", "getAttribute", "(", "'style'", ")", ")", "{", "this", ".", "setAttribute", "(", "'style'", ",", "''", ")", ";", "}", "var", "newStyle", "=", "''", ",", "// If the style matches one of the following, and we pass in an integer, default the unit", "// E.g., 10 becomes 10px", "defaultToUnit", "=", "{", "top", ":", "'px'", ",", "left", ":", "'px'", ",", "width", ":", "'px'", ",", "height", ":", "'px'", "}", ",", "i", ",", "eachStyleValue", ",", "// Keep track of an array of styles that we need to remove", "newStyleKeys", "=", "[", "]", ";", "for", "(", "i", "in", "newStyles", ")", "{", "var", "styleKey", "=", "this", ".", "_jsStyle", "(", "i", ")", ",", "eachStyleVal", "=", "newStyles", "[", "i", "]", ";", "// Default the unit if necessary", "if", "(", "defaultToUnit", "[", "styleKey", "]", "&&", "!", "isNaN", "(", "eachStyleVal", ")", ")", "{", "eachStyleVal", "+=", "defaultToUnit", "[", "styleKey", "]", ";", "}", "this", ".", "_node", ".", "style", "[", "styleKey", "]", "=", "eachStyleVal", ";", "}", "return", "this", ";", "}" ]
Sets multiple styles @param object Object map of styles to set
[ "Sets", "multiple", "styles" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L304-L341
37,949
nwtjs/nwt
src/node/js/node.js
function() { var retVal = '', // Getting ALL elements inside of form element els = this._node.getElementsByTagName('*'); // Looping through all elements inside of form and checking to see if they're "form elements" for( var i = 0, el; el = els[i]; i++ ) { if( !el.disabled && el.name && el.name.length > 0 ) { switch(el.tagName.toLowerCase()) { case 'input': switch( el.type ) { // Note we SKIP Buttons and Submits since there are no reasons as to why we // should submit those anyway case 'checkbox': case 'radio': if( el.checked ) { if( retVal.length > 0 ) { retVal += '&'; } retVal += el.name + '=' + encodeURIComponent(el.value); } break; case 'hidden': case 'password': case 'text': if( retVal.length > 0 ) { retVal += '&'; } retVal += el.name + '=' + encodeURIComponent(el.value); break; } break; case 'select': case 'textarea': if( retVal.length > 0 ) { retVal += '&'; } retVal += el.name + '=' + encodeURIComponent(el.value); break; } } } return retVal; }
javascript
function() { var retVal = '', // Getting ALL elements inside of form element els = this._node.getElementsByTagName('*'); // Looping through all elements inside of form and checking to see if they're "form elements" for( var i = 0, el; el = els[i]; i++ ) { if( !el.disabled && el.name && el.name.length > 0 ) { switch(el.tagName.toLowerCase()) { case 'input': switch( el.type ) { // Note we SKIP Buttons and Submits since there are no reasons as to why we // should submit those anyway case 'checkbox': case 'radio': if( el.checked ) { if( retVal.length > 0 ) { retVal += '&'; } retVal += el.name + '=' + encodeURIComponent(el.value); } break; case 'hidden': case 'password': case 'text': if( retVal.length > 0 ) { retVal += '&'; } retVal += el.name + '=' + encodeURIComponent(el.value); break; } break; case 'select': case 'textarea': if( retVal.length > 0 ) { retVal += '&'; } retVal += el.name + '=' + encodeURIComponent(el.value); break; } } } return retVal; }
[ "function", "(", ")", "{", "var", "retVal", "=", "''", ",", "// Getting ALL elements inside of form element", "els", "=", "this", ".", "_node", ".", "getElementsByTagName", "(", "'*'", ")", ";", "// Looping through all elements inside of form and checking to see if they're \"form elements\"", "for", "(", "var", "i", "=", "0", ",", "el", ";", "el", "=", "els", "[", "i", "]", ";", "i", "++", ")", "{", "if", "(", "!", "el", ".", "disabled", "&&", "el", ".", "name", "&&", "el", ".", "name", ".", "length", ">", "0", ")", "{", "switch", "(", "el", ".", "tagName", ".", "toLowerCase", "(", ")", ")", "{", "case", "'input'", ":", "switch", "(", "el", ".", "type", ")", "{", "// Note we SKIP Buttons and Submits since there are no reasons as to why we ", "// should submit those anyway", "case", "'checkbox'", ":", "case", "'radio'", ":", "if", "(", "el", ".", "checked", ")", "{", "if", "(", "retVal", ".", "length", ">", "0", ")", "{", "retVal", "+=", "'&'", ";", "}", "retVal", "+=", "el", ".", "name", "+", "'='", "+", "encodeURIComponent", "(", "el", ".", "value", ")", ";", "}", "break", ";", "case", "'hidden'", ":", "case", "'password'", ":", "case", "'text'", ":", "if", "(", "retVal", ".", "length", ">", "0", ")", "{", "retVal", "+=", "'&'", ";", "}", "retVal", "+=", "el", ".", "name", "+", "'='", "+", "encodeURIComponent", "(", "el", ".", "value", ")", ";", "break", ";", "}", "break", ";", "case", "'select'", ":", "case", "'textarea'", ":", "if", "(", "retVal", ".", "length", ">", "0", ")", "{", "retVal", "+=", "'&'", ";", "}", "retVal", "+=", "el", ".", "name", "+", "'='", "+", "encodeURIComponent", "(", "el", ".", "value", ")", ";", "break", ";", "}", "}", "}", "return", "retVal", ";", "}" ]
Serializes sub children of the current node into post data
[ "Serializes", "sub", "children", "of", "the", "current", "node", "into", "post", "data" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L347-L392
37,950
nwtjs/nwt
src/node/js/node.js
function(method, criteria) { // Iterate on the raw node var node = this._node, // Method to iterate on siblingType = method + 'Sibling', // Filter to test the node filter, validItems; // CSS Selector case if (typeof criteria == "string") { validItems = n.all(criteria); filter = function(rawNode) { var found = false; validItems.each(function(el){ if (rawNode == el._node) { found = true; } }); return found; }; // Default the filter to return true } else if (!criteria) { filter = function(){ return true } } else { filter = function(rawEl) { return criteria(new NWTNodeInstance(rawEl)); } } while(node) { node = node[siblingType]; if (node && node.nodeType == 1 && filter(node)) { break; } } return node ? new NWTNodeInstance(node) : null; }
javascript
function(method, criteria) { // Iterate on the raw node var node = this._node, // Method to iterate on siblingType = method + 'Sibling', // Filter to test the node filter, validItems; // CSS Selector case if (typeof criteria == "string") { validItems = n.all(criteria); filter = function(rawNode) { var found = false; validItems.each(function(el){ if (rawNode == el._node) { found = true; } }); return found; }; // Default the filter to return true } else if (!criteria) { filter = function(){ return true } } else { filter = function(rawEl) { return criteria(new NWTNodeInstance(rawEl)); } } while(node) { node = node[siblingType]; if (node && node.nodeType == 1 && filter(node)) { break; } } return node ? new NWTNodeInstance(node) : null; }
[ "function", "(", "method", ",", "criteria", ")", "{", "// Iterate on the raw node", "var", "node", "=", "this", ".", "_node", ",", "// Method to iterate on", "siblingType", "=", "method", "+", "'Sibling'", ",", "// Filter to test the node", "filter", ",", "validItems", ";", "// CSS Selector case", "if", "(", "typeof", "criteria", "==", "\"string\"", ")", "{", "validItems", "=", "n", ".", "all", "(", "criteria", ")", ";", "filter", "=", "function", "(", "rawNode", ")", "{", "var", "found", "=", "false", ";", "validItems", ".", "each", "(", "function", "(", "el", ")", "{", "if", "(", "rawNode", "==", "el", ".", "_node", ")", "{", "found", "=", "true", ";", "}", "}", ")", ";", "return", "found", ";", "}", ";", "// Default the filter to return true", "}", "else", "if", "(", "!", "criteria", ")", "{", "filter", "=", "function", "(", ")", "{", "return", "true", "}", "}", "else", "{", "filter", "=", "function", "(", "rawEl", ")", "{", "return", "criteria", "(", "new", "NWTNodeInstance", "(", "rawEl", ")", ")", ";", "}", "}", "while", "(", "node", ")", "{", "node", "=", "node", "[", "siblingType", "]", ";", "if", "(", "node", "&&", "node", ".", "nodeType", "==", "1", "&&", "filter", "(", "node", ")", ")", "{", "break", ";", "}", "}", "return", "node", "?", "new", "NWTNodeInstance", "(", "node", ")", ":", "null", ";", "}" ]
Finds a node based on direction @param string Native method to iterate nodes {previous | next} @param string criteria CSS selector or Filtering function
[ "Finds", "a", "node", "based", "on", "direction" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L469-L513
37,951
nwtjs/nwt
src/node/js/node.js
function(node) { var newParent = ( node instanceof NWTNodeInstance ) ? node : localnwt.one(node); newParent.append(this); return this; }
javascript
function(node) { var newParent = ( node instanceof NWTNodeInstance ) ? node : localnwt.one(node); newParent.append(this); return this; }
[ "function", "(", "node", ")", "{", "var", "newParent", "=", "(", "node", "instanceof", "NWTNodeInstance", ")", "?", "node", ":", "localnwt", ".", "one", "(", "node", ")", ";", "newParent", ".", "append", "(", "this", ")", ";", "return", "this", ";", "}" ]
Appends the current node to another node @param {string|object} Either a CSS selector, or node instance @return object The node that we appended the current node to
[ "Appends", "the", "current", "node", "to", "another", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L572-L579
37,952
nwtjs/nwt
src/node/js/node.js
function(node) { if( node instanceof NWTNodeInstance ) { node = node._node; } var child = this.one('*'); this._node.insertBefore(node, (child._node? child._node : null)); return this; }
javascript
function(node) { if( node instanceof NWTNodeInstance ) { node = node._node; } var child = this.one('*'); this._node.insertBefore(node, (child._node? child._node : null)); return this; }
[ "function", "(", "node", ")", "{", "if", "(", "node", "instanceof", "NWTNodeInstance", ")", "{", "node", "=", "node", ".", "_node", ";", "}", "var", "child", "=", "this", ".", "one", "(", "'*'", ")", ";", "this", ".", "_node", ".", "insertBefore", "(", "node", ",", "(", "child", ".", "_node", "?", "child", ".", "_node", ":", "null", ")", ")", ";", "return", "this", ";", "}" ]
Prepends a node to the beginning of the children of this node
[ "Prepends", "a", "node", "to", "the", "beginning", "of", "the", "children", "of", "this", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L585-L596
37,953
nwtjs/nwt
src/node/js/node.js
function(node, position) { var newParent = ( node instanceof NWTNodeInstance ) ? node : localnwt.one(node); newParent.insert(this, position); return this; }
javascript
function(node, position) { var newParent = ( node instanceof NWTNodeInstance ) ? node : localnwt.one(node); newParent.insert(this, position); return this; }
[ "function", "(", "node", ",", "position", ")", "{", "var", "newParent", "=", "(", "node", "instanceof", "NWTNodeInstance", ")", "?", "node", ":", "localnwt", ".", "one", "(", "node", ")", ";", "newParent", ".", "insert", "(", "this", ",", "position", ")", ";", "return", "this", ";", "}" ]
Inserts the current node into another node @param {string|object} Either a CSS selector, or node instance @param string Position to insert at. Defaults to 'before' @return object The node that we inserted the current node into
[ "Inserts", "the", "current", "node", "into", "another", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L605-L612
37,954
nwtjs/nwt
src/node/js/node.js
function(node, position) { position = position || 'before'; if( position == 'before' ) { this._node.parentNode.insertBefore(node._node, this._node); } else if ( position == 'after' ) { this._node.parentNode.insertBefore(node._node, this.next() ? this.next()._node : null); } }
javascript
function(node, position) { position = position || 'before'; if( position == 'before' ) { this._node.parentNode.insertBefore(node._node, this._node); } else if ( position == 'after' ) { this._node.parentNode.insertBefore(node._node, this.next() ? this.next()._node : null); } }
[ "function", "(", "node", ",", "position", ")", "{", "position", "=", "position", "||", "'before'", ";", "if", "(", "position", "==", "'before'", ")", "{", "this", ".", "_node", ".", "parentNode", ".", "insertBefore", "(", "node", ".", "_node", ",", "this", ".", "_node", ")", ";", "}", "else", "if", "(", "position", "==", "'after'", ")", "{", "this", ".", "_node", ".", "parentNode", ".", "insertBefore", "(", "node", ".", "_node", ",", "this", ".", "next", "(", ")", "?", "this", ".", "next", "(", ")", ".", "_node", ":", "null", ")", ";", "}", "}" ]
Inserts a given node into this node at the proper position
[ "Inserts", "a", "given", "node", "into", "this", "node", "at", "the", "proper", "position" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L626-L634
37,955
nwtjs/nwt
src/node/js/node.js
function(event, fn, selector, context) { return localnwt.event.on(this, event, fn, selector,context); }
javascript
function(event, fn, selector, context) { return localnwt.event.on(this, event, fn, selector,context); }
[ "function", "(", "event", ",", "fn", ",", "selector", ",", "context", ")", "{", "return", "localnwt", ".", "event", ".", "on", "(", "this", ",", "event", ",", "fn", ",", "selector", ",", "context", ")", ";", "}" ]
Implement a node API to for event listeners @see NWTEvent::on
[ "Implement", "a", "node", "API", "to", "for", "event", "listeners" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L665-L667
37,956
nwtjs/nwt
src/node/js/node.js
function(type, callback, recurse) { var evt = localnwt.event; for (var i in evt._cached) { for(var j=0,numCbs=evt._cached[i].length; j < numCbs; j++) { var thisEvt = evt._cached[i][j]; if (this._node == thisEvt.obj._node && (!type || type == thisEvt.type)) { evt.off(thisEvt.obj, thisEvt.type, thisEvt.raw) } } } if (recurse) { this.all('*').each(function(el){ el.purge(type, callback, recurse); }) } }
javascript
function(type, callback, recurse) { var evt = localnwt.event; for (var i in evt._cached) { for(var j=0,numCbs=evt._cached[i].length; j < numCbs; j++) { var thisEvt = evt._cached[i][j]; if (this._node == thisEvt.obj._node && (!type || type == thisEvt.type)) { evt.off(thisEvt.obj, thisEvt.type, thisEvt.raw) } } } if (recurse) { this.all('*').each(function(el){ el.purge(type, callback, recurse); }) } }
[ "function", "(", "type", ",", "callback", ",", "recurse", ")", "{", "var", "evt", "=", "localnwt", ".", "event", ";", "for", "(", "var", "i", "in", "evt", ".", "_cached", ")", "{", "for", "(", "var", "j", "=", "0", ",", "numCbs", "=", "evt", ".", "_cached", "[", "i", "]", ".", "length", ";", "j", "<", "numCbs", ";", "j", "++", ")", "{", "var", "thisEvt", "=", "evt", ".", "_cached", "[", "i", "]", "[", "j", "]", ";", "if", "(", "this", ".", "_node", "==", "thisEvt", ".", "obj", ".", "_node", "&&", "(", "!", "type", "||", "type", "==", "thisEvt", ".", "type", ")", ")", "{", "evt", ".", "off", "(", "thisEvt", ".", "obj", ",", "thisEvt", ".", "type", ",", "thisEvt", ".", "raw", ")", "}", "}", "}", "if", "(", "recurse", ")", "{", "this", ".", "all", "(", "'*'", ")", ".", "each", "(", "function", "(", "el", ")", "{", "el", ".", "purge", "(", "type", ",", "callback", ",", "recurse", ")", ";", "}", ")", "}", "}" ]
Purges a node of all listeners @param string If passed, only purges this type of listener @param function If passed, only purges the node of this listener @param bool If true, purges children
[ "Purges", "a", "node", "of", "all", "listeners" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L694-L711
37,957
nwtjs/nwt
src/node/js/node.js
function(styles, duration, easing, pushState) { if (!pushState) { var styleAttrs = [], defaultStyles, animHistory, i for (i in styles) { styleAttrs.push(i) } defaultStyles = this.computeCss(styleAttrs) animHistory = { from: [defaultStyles, duration, easing, true /* This makes it so we do not push this again */], to: [styles, duration, easing] } fxObj[this.uuid()] = animHistory this.fire('anim:push', animHistory) } return localnwt.anim(this, styles, duration, easing); }
javascript
function(styles, duration, easing, pushState) { if (!pushState) { var styleAttrs = [], defaultStyles, animHistory, i for (i in styles) { styleAttrs.push(i) } defaultStyles = this.computeCss(styleAttrs) animHistory = { from: [defaultStyles, duration, easing, true /* This makes it so we do not push this again */], to: [styles, duration, easing] } fxObj[this.uuid()] = animHistory this.fire('anim:push', animHistory) } return localnwt.anim(this, styles, duration, easing); }
[ "function", "(", "styles", ",", "duration", ",", "easing", ",", "pushState", ")", "{", "if", "(", "!", "pushState", ")", "{", "var", "styleAttrs", "=", "[", "]", ",", "defaultStyles", ",", "animHistory", ",", "i", "for", "(", "i", "in", "styles", ")", "{", "styleAttrs", ".", "push", "(", "i", ")", "}", "defaultStyles", "=", "this", ".", "computeCss", "(", "styleAttrs", ")", "animHistory", "=", "{", "from", ":", "[", "defaultStyles", ",", "duration", ",", "easing", ",", "true", "/* This makes it so we do not push this again */", "]", ",", "to", ":", "[", "styles", ",", "duration", ",", "easing", "]", "}", "fxObj", "[", "this", ".", "uuid", "(", ")", "]", "=", "animHistory", "this", ".", "fire", "(", "'anim:push'", ",", "animHistory", ")", "}", "return", "localnwt", ".", "anim", "(", "this", ",", "styles", ",", "duration", ",", "easing", ")", ";", "}" ]
Implement a node API to animate Takes an additional argument, pushState which signals whether or not to push this anim state onto fxStack @see NWTAnimate::anin
[ "Implement", "a", "node", "API", "to", "animate", "Takes", "an", "additional", "argument", "pushState", "which", "signals", "whether", "or", "not", "to", "push", "this", "anim", "state", "onto", "fxStack" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L761-L785
37,958
nwtjs/nwt
src/node/js/node.js
function(plugin, config) { config = config || {}; config.node = this; return localnwt.plugin(plugin, config); }
javascript
function(plugin, config) { config = config || {}; config.node = this; return localnwt.plugin(plugin, config); }
[ "function", "(", "plugin", ",", "config", ")", "{", "config", "=", "config", "||", "{", "}", ";", "config", ".", "node", "=", "this", ";", "return", "localnwt", ".", "plugin", "(", "plugin", ",", "config", ")", ";", "}" ]
Implement a node API for plugins @see localnwt.plugin
[ "Implement", "a", "node", "API", "for", "plugins" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L809-L813
37,959
byron-dupreez/aws-core-utils
arns.js
getArnComponent
function getArnComponent(arn, index) { const components = isNotBlank(arn) ? trim(arn).split(':') : []; return components.length > index ? trimOrEmpty(components[index]) : ''; }
javascript
function getArnComponent(arn, index) { const components = isNotBlank(arn) ? trim(arn).split(':') : []; return components.length > index ? trimOrEmpty(components[index]) : ''; }
[ "function", "getArnComponent", "(", "arn", ",", "index", ")", "{", "const", "components", "=", "isNotBlank", "(", "arn", ")", "?", "trim", "(", "arn", ")", ".", "split", "(", "':'", ")", ":", "[", "]", ";", "return", "components", ".", "length", ">", "index", "?", "trimOrEmpty", "(", "components", "[", "index", "]", ")", ":", "''", ";", "}" ]
Extracts the component at the given index of the given ARN. @param {string} arn the ARN from which to extract the component @param {number} index the index of the ARN component to retrieve @returns {string} the component (if extracted) or empty string (if not)
[ "Extracts", "the", "component", "at", "the", "given", "index", "of", "the", "given", "ARN", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/arns.js#L41-L44
37,960
byron-dupreez/aws-core-utils
stream-events.js
getKinesisShardIdFromEventID
function getKinesisShardIdFromEventID(eventID) { if (eventID) { const sepPos = eventID.indexOf(':'); return sepPos !== -1 ? eventID.substring(0, sepPos) : ''; } return ''; }
javascript
function getKinesisShardIdFromEventID(eventID) { if (eventID) { const sepPos = eventID.indexOf(':'); return sepPos !== -1 ? eventID.substring(0, sepPos) : ''; } return ''; }
[ "function", "getKinesisShardIdFromEventID", "(", "eventID", ")", "{", "if", "(", "eventID", ")", "{", "const", "sepPos", "=", "eventID", ".", "indexOf", "(", "':'", ")", ";", "return", "sepPos", "!==", "-", "1", "?", "eventID", ".", "substring", "(", "0", ",", "sepPos", ")", ":", "''", ";", "}", "return", "''", ";", "}" ]
Extracts the shard id from the given Kinesis eventID. @param {string} eventID - an eventID from an AWS Kinesis stream event record. @return {string|undefined} the shard id (if any) or an empty string
[ "Extracts", "the", "shard", "id", "from", "the", "given", "Kinesis", "eventID", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L145-L151
37,961
byron-dupreez/aws-core-utils
stream-events.js
getKinesisShardIdAndEventNoFromEventID
function getKinesisShardIdAndEventNoFromEventID(eventID) { if (eventID) { const sepPos = eventID.indexOf(':'); return sepPos !== -1 ? [eventID.substring(0, sepPos), eventID.substring(sepPos + 1),] : ['', '']; } return ['', '']; }
javascript
function getKinesisShardIdAndEventNoFromEventID(eventID) { if (eventID) { const sepPos = eventID.indexOf(':'); return sepPos !== -1 ? [eventID.substring(0, sepPos), eventID.substring(sepPos + 1),] : ['', '']; } return ['', '']; }
[ "function", "getKinesisShardIdAndEventNoFromEventID", "(", "eventID", ")", "{", "if", "(", "eventID", ")", "{", "const", "sepPos", "=", "eventID", ".", "indexOf", "(", "':'", ")", ";", "return", "sepPos", "!==", "-", "1", "?", "[", "eventID", ".", "substring", "(", "0", ",", "sepPos", ")", ",", "eventID", ".", "substring", "(", "sepPos", "+", "1", ")", ",", "]", ":", "[", "''", ",", "''", "]", ";", "}", "return", "[", "''", ",", "''", "]", ";", "}" ]
Extracts the shard id and event number from the given Kinesis eventID. @param {string} eventID - an eventID from an AWS Kinesis stream event record. @return {[string,string]} an array containing: the shard id (if any) or an empty string; and the event number (if any) or an empty string
[ "Extracts", "the", "shard", "id", "and", "event", "number", "from", "the", "given", "Kinesis", "eventID", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L159-L166
37,962
byron-dupreez/aws-core-utils
stream-events.js
getKinesisSequenceNumber
function getKinesisSequenceNumber(record) { return record && record.kinesis && record.kinesis.sequenceNumber ? record.kinesis.sequenceNumber : ''; }
javascript
function getKinesisSequenceNumber(record) { return record && record.kinesis && record.kinesis.sequenceNumber ? record.kinesis.sequenceNumber : ''; }
[ "function", "getKinesisSequenceNumber", "(", "record", ")", "{", "return", "record", "&&", "record", ".", "kinesis", "&&", "record", ".", "kinesis", ".", "sequenceNumber", "?", "record", ".", "kinesis", ".", "sequenceNumber", ":", "''", ";", "}" ]
Gets the sequence number from the given Kinesis stream event record. @param {KinesisEventRecord|*} record - a Kinesis stream event record @returns {string} the sequence number (if any) or an empty string
[ "Gets", "the", "sequence", "number", "from", "the", "given", "Kinesis", "stream", "event", "record", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L173-L175
37,963
byron-dupreez/aws-core-utils
stream-events.js
getDynamoDBSequenceNumber
function getDynamoDBSequenceNumber(record) { return record && record.dynamodb && record.dynamodb.SequenceNumber ? record.dynamodb.SequenceNumber : ''; }
javascript
function getDynamoDBSequenceNumber(record) { return record && record.dynamodb && record.dynamodb.SequenceNumber ? record.dynamodb.SequenceNumber : ''; }
[ "function", "getDynamoDBSequenceNumber", "(", "record", ")", "{", "return", "record", "&&", "record", ".", "dynamodb", "&&", "record", ".", "dynamodb", ".", "SequenceNumber", "?", "record", ".", "dynamodb", ".", "SequenceNumber", ":", "''", ";", "}" ]
Returns the sequence number from the given DynamoDB stream event record. @param {DynamoDBEventRecord|*} record - a DynamoDB stream event record @returns {string} the sequence number (if any) or an empty string
[ "Returns", "the", "sequence", "number", "from", "the", "given", "DynamoDB", "stream", "event", "record", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L222-L224
37,964
byron-dupreez/aws-core-utils
stream-events.js
_validateKinesisStreamEventRecord
function _validateKinesisStreamEventRecord(record) { if (!record.kinesis) { throw new Error(`Missing kinesis property for Kinesis stream event record (${record.eventID})`); } if (!record.kinesis.data) { throw new Error(`Missing data property for Kinesis stream event record (${record.eventID})`); } if (!record.kinesis.partitionKey) { throw new Error(`Missing partitionKey property for Kinesis stream event record (${record.eventID})`); } if (!record.kinesis.sequenceNumber) { throw new Error(`Missing sequenceNumber property for Kinesis stream event record (${record.eventID})`); } }
javascript
function _validateKinesisStreamEventRecord(record) { if (!record.kinesis) { throw new Error(`Missing kinesis property for Kinesis stream event record (${record.eventID})`); } if (!record.kinesis.data) { throw new Error(`Missing data property for Kinesis stream event record (${record.eventID})`); } if (!record.kinesis.partitionKey) { throw new Error(`Missing partitionKey property for Kinesis stream event record (${record.eventID})`); } if (!record.kinesis.sequenceNumber) { throw new Error(`Missing sequenceNumber property for Kinesis stream event record (${record.eventID})`); } }
[ "function", "_validateKinesisStreamEventRecord", "(", "record", ")", "{", "if", "(", "!", "record", ".", "kinesis", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "kinesis", ".", "data", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "kinesis", ".", "partitionKey", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "kinesis", ".", "sequenceNumber", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "}" ]
Validates the given Kinesis stream event record. @param {KinesisEventRecord|*} record - a Kinesis stream event record @private
[ "Validates", "the", "given", "Kinesis", "stream", "event", "record", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L306-L319
37,965
byron-dupreez/aws-core-utils
stream-events.js
isDynamoDBEventNameValid
function isDynamoDBEventNameValid(recordOrEventName) { const eventName = recordOrEventName.eventName ? recordOrEventName.eventName : recordOrEventName; return eventName === DynamoDBEventName.INSERT || eventName === DynamoDBEventName.MODIFY || eventName === DynamoDBEventName.REMOVE; }
javascript
function isDynamoDBEventNameValid(recordOrEventName) { const eventName = recordOrEventName.eventName ? recordOrEventName.eventName : recordOrEventName; return eventName === DynamoDBEventName.INSERT || eventName === DynamoDBEventName.MODIFY || eventName === DynamoDBEventName.REMOVE; }
[ "function", "isDynamoDBEventNameValid", "(", "recordOrEventName", ")", "{", "const", "eventName", "=", "recordOrEventName", ".", "eventName", "?", "recordOrEventName", ".", "eventName", ":", "recordOrEventName", ";", "return", "eventName", "===", "DynamoDBEventName", ".", "INSERT", "||", "eventName", "===", "DynamoDBEventName", ".", "MODIFY", "||", "eventName", "===", "DynamoDBEventName", ".", "REMOVE", ";", "}" ]
Returns true if the given DynamoDB event name OR given DynamoDB stream event record's eventName is valid; false otherwise @param {string|DynamoDBEventRecord} recordOrEventName - a DynamoDB event name OR DynamoDB stream event record @returns {boolean} true if valid; false otherwise
[ "Returns", "true", "if", "the", "given", "DynamoDB", "event", "name", "OR", "given", "DynamoDB", "stream", "event", "record", "s", "eventName", "is", "valid", ";", "false", "otherwise" ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L345-L348
37,966
byron-dupreez/aws-core-utils
stream-events.js
_validateDynamoDBStreamEventRecord
function _validateDynamoDBStreamEventRecord(record) { if (!isDynamoDBEventNameValid(record)) { throw new Error(`Invalid eventName property (${record.eventName}) for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb) { throw new Error(`Missing dynamodb property for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb.Keys) { throw new Error(`Missing Keys property for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb.SequenceNumber) { throw new Error(`Missing SequenceNumber property for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb.StreamViewType) { throw new Error(`Missing StreamViewType property for DynamoDB stream event record (${record.eventID})`); } switch (record.dynamodb.StreamViewType) { case 'KEYS_ONLY': break; case 'NEW_IMAGE': if (!record.dynamodb.NewImage && record.eventName !== 'REMOVE') { throw new Error(`Missing NewImage property for DynamoDB stream event record (${record.eventID})`); } break; case 'OLD_IMAGE': if (!record.dynamodb.OldImage && record.eventName !== 'INSERT') { throw new Error(`Missing OldImage property for DynamoDB stream event record (${record.eventID})`); } break; case 'NEW_AND_OLD_IMAGES': if ((!record.dynamodb.NewImage && record.eventName !== 'REMOVE') || (!record.dynamodb.OldImage && record.eventName !== 'INSERT')) { throw new Error(`Missing both NewImage and OldImage properties for DynamoDB stream event record (${record.eventID})`); } break; default: throw new Error(`Unexpected StreamViewType (${record.dynamodb.StreamViewType}) on DynamoDB stream event record (${record.eventID})`); } }
javascript
function _validateDynamoDBStreamEventRecord(record) { if (!isDynamoDBEventNameValid(record)) { throw new Error(`Invalid eventName property (${record.eventName}) for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb) { throw new Error(`Missing dynamodb property for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb.Keys) { throw new Error(`Missing Keys property for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb.SequenceNumber) { throw new Error(`Missing SequenceNumber property for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb.StreamViewType) { throw new Error(`Missing StreamViewType property for DynamoDB stream event record (${record.eventID})`); } switch (record.dynamodb.StreamViewType) { case 'KEYS_ONLY': break; case 'NEW_IMAGE': if (!record.dynamodb.NewImage && record.eventName !== 'REMOVE') { throw new Error(`Missing NewImage property for DynamoDB stream event record (${record.eventID})`); } break; case 'OLD_IMAGE': if (!record.dynamodb.OldImage && record.eventName !== 'INSERT') { throw new Error(`Missing OldImage property for DynamoDB stream event record (${record.eventID})`); } break; case 'NEW_AND_OLD_IMAGES': if ((!record.dynamodb.NewImage && record.eventName !== 'REMOVE') || (!record.dynamodb.OldImage && record.eventName !== 'INSERT')) { throw new Error(`Missing both NewImage and OldImage properties for DynamoDB stream event record (${record.eventID})`); } break; default: throw new Error(`Unexpected StreamViewType (${record.dynamodb.StreamViewType}) on DynamoDB stream event record (${record.eventID})`); } }
[ "function", "_validateDynamoDBStreamEventRecord", "(", "record", ")", "{", "if", "(", "!", "isDynamoDBEventNameValid", "(", "record", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventName", "}", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "dynamodb", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "dynamodb", ".", "Keys", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "dynamodb", ".", "SequenceNumber", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "dynamodb", ".", "StreamViewType", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "switch", "(", "record", ".", "dynamodb", ".", "StreamViewType", ")", "{", "case", "'KEYS_ONLY'", ":", "break", ";", "case", "'NEW_IMAGE'", ":", "if", "(", "!", "record", ".", "dynamodb", ".", "NewImage", "&&", "record", ".", "eventName", "!==", "'REMOVE'", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "break", ";", "case", "'OLD_IMAGE'", ":", "if", "(", "!", "record", ".", "dynamodb", ".", "OldImage", "&&", "record", ".", "eventName", "!==", "'INSERT'", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "break", ";", "case", "'NEW_AND_OLD_IMAGES'", ":", "if", "(", "(", "!", "record", ".", "dynamodb", ".", "NewImage", "&&", "record", ".", "eventName", "!==", "'REMOVE'", ")", "||", "(", "!", "record", ".", "dynamodb", ".", "OldImage", "&&", "record", ".", "eventName", "!==", "'INSERT'", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "break", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "record", ".", "dynamodb", ".", "StreamViewType", "}", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "}" ]
Validates the given DynamoDB stream event record. @param {DynamoDBEventRecord|*} record - a DynamoDB stream event record @private
[ "Validates", "the", "given", "DynamoDB", "stream", "event", "record", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L355-L396
37,967
Streampunk/sevruga
index.js
createRenderStream
function createRenderStream(params) { return new Transform({ decodeStrings: params.decodeStrings || false, highWaterMark: params.highwaterMark || 16384, transform(svgStr, encoding, cb) { const renderBuf = Buffer.alloc(params.width * params.height * 4); // ARGB 8-bit per component addon.renderSVG(svgStr, renderBuf, params) .then(t => { renderBuf.timings = t; cb(null, renderBuf); }) .catch(cb); } }); }
javascript
function createRenderStream(params) { return new Transform({ decodeStrings: params.decodeStrings || false, highWaterMark: params.highwaterMark || 16384, transform(svgStr, encoding, cb) { const renderBuf = Buffer.alloc(params.width * params.height * 4); // ARGB 8-bit per component addon.renderSVG(svgStr, renderBuf, params) .then(t => { renderBuf.timings = t; cb(null, renderBuf); }) .catch(cb); } }); }
[ "function", "createRenderStream", "(", "params", ")", "{", "return", "new", "Transform", "(", "{", "decodeStrings", ":", "params", ".", "decodeStrings", "||", "false", ",", "highWaterMark", ":", "params", ".", "highwaterMark", "||", "16384", ",", "transform", "(", "svgStr", ",", "encoding", ",", "cb", ")", "{", "const", "renderBuf", "=", "Buffer", ".", "alloc", "(", "params", ".", "width", "*", "params", ".", "height", "*", "4", ")", ";", "// ARGB 8-bit per component", "addon", ".", "renderSVG", "(", "svgStr", ",", "renderBuf", ",", "params", ")", ".", "then", "(", "t", "=>", "{", "renderBuf", ".", "timings", "=", "t", ";", "cb", "(", "null", ",", "renderBuf", ")", ";", "}", ")", ".", "catch", "(", "cb", ")", ";", "}", "}", ")", ";", "}" ]
With no argument, SegfaultHandler will generate a generic log file name
[ "With", "no", "argument", "SegfaultHandler", "will", "generate", "a", "generic", "log", "file", "name" ]
f1bac605763f8025e836f5388cb8d034a78cc65d
https://github.com/Streampunk/sevruga/blob/f1bac605763f8025e836f5388cb8d034a78cc65d/index.js#L22-L36
37,968
ReedD/node-assetmanager
index.js
function (patterns) { // External restources have to be 1:1 dest to src, both strings // Check for external first, otherwise expand the pattern if (!_.isArray(patterns)) { if (isExternal(patterns)) { return [patterns]; } patterns = [patterns]; } return grunt.file.expand({filter: 'isFile'}, patterns); }
javascript
function (patterns) { // External restources have to be 1:1 dest to src, both strings // Check for external first, otherwise expand the pattern if (!_.isArray(patterns)) { if (isExternal(patterns)) { return [patterns]; } patterns = [patterns]; } return grunt.file.expand({filter: 'isFile'}, patterns); }
[ "function", "(", "patterns", ")", "{", "// External restources have to be 1:1 dest to src, both strings", "// Check for external first, otherwise expand the pattern", "if", "(", "!", "_", ".", "isArray", "(", "patterns", ")", ")", "{", "if", "(", "isExternal", "(", "patterns", ")", ")", "{", "return", "[", "patterns", "]", ";", "}", "patterns", "=", "[", "patterns", "]", ";", "}", "return", "grunt", ".", "file", ".", "expand", "(", "{", "filter", ":", "'isFile'", "}", ",", "patterns", ")", ";", "}" ]
Get assets from pattern. Pattern could be - an array - a string - external resource @param patterns
[ "Get", "assets", "from", "pattern", ".", "Pattern", "could", "be", "-", "an", "array", "-", "a", "string", "-", "external", "resource" ]
f25aab34554a98abe0d0eb0f1262444aaef8e056
https://github.com/ReedD/node-assetmanager/blob/f25aab34554a98abe0d0eb0f1262444aaef8e056/index.js#L45-L57
37,969
ReedD/node-assetmanager
index.js
function(files) { var regex; if (options.webroot instanceof RegExp) { regex = options.webroot; } else { regex = new RegExp('^' + options.webroot); } _.each(files, function (value, key) { files[key] = value.replace(regex, ''); }); return files; }
javascript
function(files) { var regex; if (options.webroot instanceof RegExp) { regex = options.webroot; } else { regex = new RegExp('^' + options.webroot); } _.each(files, function (value, key) { files[key] = value.replace(regex, ''); }); return files; }
[ "function", "(", "files", ")", "{", "var", "regex", ";", "if", "(", "options", ".", "webroot", "instanceof", "RegExp", ")", "{", "regex", "=", "options", ".", "webroot", ";", "}", "else", "{", "regex", "=", "new", "RegExp", "(", "'^'", "+", "options", ".", "webroot", ")", ";", "}", "_", ".", "each", "(", "files", ",", "function", "(", "value", ",", "key", ")", "{", "files", "[", "key", "]", "=", "value", ".", "replace", "(", "regex", ",", "''", ")", ";", "}", ")", ";", "return", "files", ";", "}" ]
Strip server path from from file path so that the file path is relative to the webroot @param array files @return array files clean filenames
[ "Strip", "server", "path", "from", "from", "file", "path", "so", "that", "the", "file", "path", "is", "relative", "to", "the", "webroot" ]
f25aab34554a98abe0d0eb0f1262444aaef8e056
https://github.com/ReedD/node-assetmanager/blob/f25aab34554a98abe0d0eb0f1262444aaef8e056/index.js#L66-L77
37,970
ReedD/node-assetmanager
index.js
md5
function md5(files) { var hash = crypto.createHash('md5'); _.each(files, function(file) { if (!isExternal(file)) hash.update(grunt.file.read(file), 'utf-8'); }); return hash.digest('hex'); }
javascript
function md5(files) { var hash = crypto.createHash('md5'); _.each(files, function(file) { if (!isExternal(file)) hash.update(grunt.file.read(file), 'utf-8'); }); return hash.digest('hex'); }
[ "function", "md5", "(", "files", ")", "{", "var", "hash", "=", "crypto", ".", "createHash", "(", "'md5'", ")", ";", "_", ".", "each", "(", "files", ",", "function", "(", "file", ")", "{", "if", "(", "!", "isExternal", "(", "file", ")", ")", "hash", ".", "update", "(", "grunt", ".", "file", ".", "read", "(", "file", ")", ",", "'utf-8'", ")", ";", "}", ")", ";", "return", "hash", ".", "digest", "(", "'hex'", ")", ";", "}" ]
Computes an MD5 digest of given files. @param array files @return MD5 hash (hex-encoded)
[ "Computes", "an", "MD5", "digest", "of", "given", "files", "." ]
f25aab34554a98abe0d0eb0f1262444aaef8e056
https://github.com/ReedD/node-assetmanager/blob/f25aab34554a98abe0d0eb0f1262444aaef8e056/index.js#L85-L92
37,971
KevinGrandon/sparky
index.js
function(command, callback) { command = 'curl https://api.spark.io/v1/devices/' + this.config.deviceId + '/' + command + '?access_token=' + this.config.token; this.debug('Running command: ', command); child = exec(command, function (error, stdout, stderr) { this.debug('stdout: ' + stdout); this.debug('stderr: ' + stderr); if (error !== null) { this.debug('exec error: ' + error); } if (callback) { try { callback(JSON.parse(stdout)); } catch (err) { callback(undefined); } } }.bind(this)); }
javascript
function(command, callback) { command = 'curl https://api.spark.io/v1/devices/' + this.config.deviceId + '/' + command + '?access_token=' + this.config.token; this.debug('Running command: ', command); child = exec(command, function (error, stdout, stderr) { this.debug('stdout: ' + stdout); this.debug('stderr: ' + stderr); if (error !== null) { this.debug('exec error: ' + error); } if (callback) { try { callback(JSON.parse(stdout)); } catch (err) { callback(undefined); } } }.bind(this)); }
[ "function", "(", "command", ",", "callback", ")", "{", "command", "=", "'curl https://api.spark.io/v1/devices/'", "+", "this", ".", "config", ".", "deviceId", "+", "'/'", "+", "command", "+", "'?access_token='", "+", "this", ".", "config", ".", "token", ";", "this", ".", "debug", "(", "'Running command: '", ",", "command", ")", ";", "child", "=", "exec", "(", "command", ",", "function", "(", "error", ",", "stdout", ",", "stderr", ")", "{", "this", ".", "debug", "(", "'stdout: '", "+", "stdout", ")", ";", "this", ".", "debug", "(", "'stderr: '", "+", "stderr", ")", ";", "if", "(", "error", "!==", "null", ")", "{", "this", ".", "debug", "(", "'exec error: '", "+", "error", ")", ";", "}", "if", "(", "callback", ")", "{", "try", "{", "callback", "(", "JSON", ".", "parse", "(", "stdout", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "callback", "(", "undefined", ")", ";", "}", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Gets a variable from the spark core
[ "Gets", "a", "variable", "from", "the", "spark", "core" ]
b91cbcc0946daf0fe7d39ff14741cfc950b204ac
https://github.com/KevinGrandon/sparky/blob/b91cbcc0946daf0fe7d39ff14741cfc950b204ac/index.js#L119-L138
37,972
segmentio/isodate-traverse
lib/index.js
traverse
function traverse(input, strict) { if (strict === undefined) strict = true; if (type(input) === 'object') { return traverseObject(input, strict); } else if (type(input) === 'array') { return traverseArray(input, strict); } else if (isodate.is(input, strict)) { return isodate.parse(input); } return input; }
javascript
function traverse(input, strict) { if (strict === undefined) strict = true; if (type(input) === 'object') { return traverseObject(input, strict); } else if (type(input) === 'array') { return traverseArray(input, strict); } else if (isodate.is(input, strict)) { return isodate.parse(input); } return input; }
[ "function", "traverse", "(", "input", ",", "strict", ")", "{", "if", "(", "strict", "===", "undefined", ")", "strict", "=", "true", ";", "if", "(", "type", "(", "input", ")", "===", "'object'", ")", "{", "return", "traverseObject", "(", "input", ",", "strict", ")", ";", "}", "else", "if", "(", "type", "(", "input", ")", "===", "'array'", ")", "{", "return", "traverseArray", "(", "input", ",", "strict", ")", ";", "}", "else", "if", "(", "isodate", ".", "is", "(", "input", ",", "strict", ")", ")", "{", "return", "isodate", ".", "parse", "(", "input", ")", ";", "}", "return", "input", ";", "}" ]
Recursively traverse an object or array, and convert all ISO date strings parse into Date objects. @param {Object} input - object, array, or string to convert @param {Boolean} strict - only convert strings with year, month, and date @return {Object}
[ "Recursively", "traverse", "an", "object", "or", "array", "and", "convert", "all", "ISO", "date", "strings", "parse", "into", "Date", "objects", "." ]
ae4025aaae6b0acdb957ca31aeda9518767dc8b0
https://github.com/segmentio/isodate-traverse/blob/ae4025aaae6b0acdb957ca31aeda9518767dc8b0/lib/index.js#L19-L29
37,973
segmentio/isodate-traverse
lib/index.js
traverseObject
function traverseObject(obj, strict) { Object.keys(obj).forEach(function(key) { obj[key] = traverse(obj[key], strict); }); return obj; }
javascript
function traverseObject(obj, strict) { Object.keys(obj).forEach(function(key) { obj[key] = traverse(obj[key], strict); }); return obj; }
[ "function", "traverseObject", "(", "obj", ",", "strict", ")", "{", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "obj", "[", "key", "]", "=", "traverse", "(", "obj", "[", "key", "]", ",", "strict", ")", ";", "}", ")", ";", "return", "obj", ";", "}" ]
Object traverser helper function. @param {Object} obj - object to traverse @param {Boolean} strict - only convert strings with year, month, and date @return {Object}
[ "Object", "traverser", "helper", "function", "." ]
ae4025aaae6b0acdb957ca31aeda9518767dc8b0
https://github.com/segmentio/isodate-traverse/blob/ae4025aaae6b0acdb957ca31aeda9518767dc8b0/lib/index.js#L38-L43
37,974
segmentio/isodate-traverse
lib/index.js
traverseArray
function traverseArray(arr, strict) { arr.forEach(function(value, index) { arr[index] = traverse(value, strict); }); return arr; }
javascript
function traverseArray(arr, strict) { arr.forEach(function(value, index) { arr[index] = traverse(value, strict); }); return arr; }
[ "function", "traverseArray", "(", "arr", ",", "strict", ")", "{", "arr", ".", "forEach", "(", "function", "(", "value", ",", "index", ")", "{", "arr", "[", "index", "]", "=", "traverse", "(", "value", ",", "strict", ")", ";", "}", ")", ";", "return", "arr", ";", "}" ]
Array traverser helper function @param {Array} arr - array to traverse @param {Boolean} strict - only convert strings with year, month, and date @return {Array}
[ "Array", "traverser", "helper", "function" ]
ae4025aaae6b0acdb957ca31aeda9518767dc8b0
https://github.com/segmentio/isodate-traverse/blob/ae4025aaae6b0acdb957ca31aeda9518767dc8b0/lib/index.js#L52-L57
37,975
nwtjs/nwt
plugins/bootstrap/datatable.js
standardizeCols
function standardizeCols(columns) { /** * Gets the default column name */ function getDefaultFormatter(colName) { return function(o) { return o[colName]; }; } /** * Gets the default column sorter */ function getDefaultSorter(colName) { return function(a, b, dir){ var firstRec = dir == 'asc' ? a : b, secondRec = dir == 'asc' ? b : a, fA = firstRec[colName].toLowerCase(), fB = secondRec[colName].toLowerCase(); // Handle numbers if (fA<fB) return -1 if (fA>fB) return +1 return 0 }; } for (var i in columns) { var column = columns[i]; if (typeof column == "string") { column = {name: column}; } column.dir = column.sortDir || 'asc'; column.formatter = column.formatter || getDefaultFormatter(column.key || column.name); column.sorter = column.sorter || getDefaultSorter(column.key || column.name); columns[i] = column; } return columns; }
javascript
function standardizeCols(columns) { /** * Gets the default column name */ function getDefaultFormatter(colName) { return function(o) { return o[colName]; }; } /** * Gets the default column sorter */ function getDefaultSorter(colName) { return function(a, b, dir){ var firstRec = dir == 'asc' ? a : b, secondRec = dir == 'asc' ? b : a, fA = firstRec[colName].toLowerCase(), fB = secondRec[colName].toLowerCase(); // Handle numbers if (fA<fB) return -1 if (fA>fB) return +1 return 0 }; } for (var i in columns) { var column = columns[i]; if (typeof column == "string") { column = {name: column}; } column.dir = column.sortDir || 'asc'; column.formatter = column.formatter || getDefaultFormatter(column.key || column.name); column.sorter = column.sorter || getDefaultSorter(column.key || column.name); columns[i] = column; } return columns; }
[ "function", "standardizeCols", "(", "columns", ")", "{", "/**\n\t * Gets the default column name\n\t */", "function", "getDefaultFormatter", "(", "colName", ")", "{", "return", "function", "(", "o", ")", "{", "return", "o", "[", "colName", "]", ";", "}", ";", "}", "/**\n\t * Gets the default column sorter\n\t */", "function", "getDefaultSorter", "(", "colName", ")", "{", "return", "function", "(", "a", ",", "b", ",", "dir", ")", "{", "var", "firstRec", "=", "dir", "==", "'asc'", "?", "a", ":", "b", ",", "secondRec", "=", "dir", "==", "'asc'", "?", "b", ":", "a", ",", "fA", "=", "firstRec", "[", "colName", "]", ".", "toLowerCase", "(", ")", ",", "fB", "=", "secondRec", "[", "colName", "]", ".", "toLowerCase", "(", ")", ";", "// Handle numbers", "if", "(", "fA", "<", "fB", ")", "return", "-", "1", "if", "(", "fA", ">", "fB", ")", "return", "+", "1", "return", "0", "}", ";", "}", "for", "(", "var", "i", "in", "columns", ")", "{", "var", "column", "=", "columns", "[", "i", "]", ";", "if", "(", "typeof", "column", "==", "\"string\"", ")", "{", "column", "=", "{", "name", ":", "column", "}", ";", "}", "column", ".", "dir", "=", "column", ".", "sortDir", "||", "'asc'", ";", "column", ".", "formatter", "=", "column", ".", "formatter", "||", "getDefaultFormatter", "(", "column", ".", "key", "||", "column", ".", "name", ")", ";", "column", ".", "sorter", "=", "column", ".", "sorter", "||", "getDefaultSorter", "(", "column", ".", "key", "||", "column", ".", "name", ")", ";", "columns", "[", "i", "]", "=", "column", ";", "}", "return", "columns", ";", "}" ]
Standardizes the column definitions E.g., if the user passes a string for a column def, fill out the defaults
[ "Standardizes", "the", "column", "definitions", "E", ".", "g", ".", "if", "the", "user", "passes", "a", "string", "for", "a", "column", "def", "fill", "out", "the", "defaults" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L18-L64
37,976
nwtjs/nwt
plugins/bootstrap/datatable.js
getDefaultSorter
function getDefaultSorter(colName) { return function(a, b, dir){ var firstRec = dir == 'asc' ? a : b, secondRec = dir == 'asc' ? b : a, fA = firstRec[colName].toLowerCase(), fB = secondRec[colName].toLowerCase(); // Handle numbers if (fA<fB) return -1 if (fA>fB) return +1 return 0 }; }
javascript
function getDefaultSorter(colName) { return function(a, b, dir){ var firstRec = dir == 'asc' ? a : b, secondRec = dir == 'asc' ? b : a, fA = firstRec[colName].toLowerCase(), fB = secondRec[colName].toLowerCase(); // Handle numbers if (fA<fB) return -1 if (fA>fB) return +1 return 0 }; }
[ "function", "getDefaultSorter", "(", "colName", ")", "{", "return", "function", "(", "a", ",", "b", ",", "dir", ")", "{", "var", "firstRec", "=", "dir", "==", "'asc'", "?", "a", ":", "b", ",", "secondRec", "=", "dir", "==", "'asc'", "?", "b", ":", "a", ",", "fA", "=", "firstRec", "[", "colName", "]", ".", "toLowerCase", "(", ")", ",", "fB", "=", "secondRec", "[", "colName", "]", ".", "toLowerCase", "(", ")", ";", "// Handle numbers", "if", "(", "fA", "<", "fB", ")", "return", "-", "1", "if", "(", "fA", ">", "fB", ")", "return", "+", "1", "return", "0", "}", ";", "}" ]
Gets the default column sorter
[ "Gets", "the", "default", "column", "sorter" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L32-L47
37,977
nwtjs/nwt
plugins/bootstrap/datatable.js
JSONDataSource
function JSONDataSource(config) { // Default to the first col ASC for sorting this.colSortIdx = config.defaultSortCol || -1 this.data = config.data; this.columns = standardizeCols(config.columns); }
javascript
function JSONDataSource(config) { // Default to the first col ASC for sorting this.colSortIdx = config.defaultSortCol || -1 this.data = config.data; this.columns = standardizeCols(config.columns); }
[ "function", "JSONDataSource", "(", "config", ")", "{", "// Default to the first col ASC for sorting", "this", ".", "colSortIdx", "=", "config", ".", "defaultSortCol", "||", "-", "1", "this", ".", "data", "=", "config", ".", "data", ";", "this", ".", "columns", "=", "standardizeCols", "(", "config", ".", "columns", ")", ";", "}" ]
Datasource from a local JSON object
[ "Datasource", "from", "a", "local", "JSON", "object" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L70-L76
37,978
nwtjs/nwt
plugins/bootstrap/datatable.js
IODataSource
function IODataSource(config) { this.columns = standardizeCols(config.columns); this.io = config.data; this.node = config.node; this.fetch = config.fetch || function(io, sort, dir) { io.post('sort=' + sort + '&dir=' + dir); } // Default to the first col ASC for sorting this.colSortIdx = config.defaultSortCol || -1 }
javascript
function IODataSource(config) { this.columns = standardizeCols(config.columns); this.io = config.data; this.node = config.node; this.fetch = config.fetch || function(io, sort, dir) { io.post('sort=' + sort + '&dir=' + dir); } // Default to the first col ASC for sorting this.colSortIdx = config.defaultSortCol || -1 }
[ "function", "IODataSource", "(", "config", ")", "{", "this", ".", "columns", "=", "standardizeCols", "(", "config", ".", "columns", ")", ";", "this", ".", "io", "=", "config", ".", "data", ";", "this", ".", "node", "=", "config", ".", "node", ";", "this", ".", "fetch", "=", "config", ".", "fetch", "||", "function", "(", "io", ",", "sort", ",", "dir", ")", "{", "io", ".", "post", "(", "'sort='", "+", "sort", "+", "'&dir='", "+", "dir", ")", ";", "}", "// Default to the first col ASC for sorting", "this", ".", "colSortIdx", "=", "config", ".", "defaultSortCol", "||", "-", "1", "}" ]
Datasource from a remote IO source
[ "Datasource", "from", "a", "remote", "IO", "source" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L97-L108
37,979
nwtjs/nwt
plugins/bootstrap/datatable.js
ElementDataSource
function ElementDataSource(config) { var newData = [], newColumns = []; var headings = config.data.all('tr th'); headings.each(function(th){ newColumns.push(th.getHtml()); }); config.data.all('tr').each(function(tr){ var newRow = {}, populated = false; for (var i = 0, numCols = headings.size(); i < numCols; i++) { if (!tr.all('td').item(i)) { continue; } newRow[headings.item(i).getHtml()] = tr.all('td').item(i).getHtml(); populated = true; } if (populated) { newData.push(newRow); } }); config.columns = newColumns; config.data = newData; return new JSONDataSource(config); }
javascript
function ElementDataSource(config) { var newData = [], newColumns = []; var headings = config.data.all('tr th'); headings.each(function(th){ newColumns.push(th.getHtml()); }); config.data.all('tr').each(function(tr){ var newRow = {}, populated = false; for (var i = 0, numCols = headings.size(); i < numCols; i++) { if (!tr.all('td').item(i)) { continue; } newRow[headings.item(i).getHtml()] = tr.all('td').item(i).getHtml(); populated = true; } if (populated) { newData.push(newRow); } }); config.columns = newColumns; config.data = newData; return new JSONDataSource(config); }
[ "function", "ElementDataSource", "(", "config", ")", "{", "var", "newData", "=", "[", "]", ",", "newColumns", "=", "[", "]", ";", "var", "headings", "=", "config", ".", "data", ".", "all", "(", "'tr th'", ")", ";", "headings", ".", "each", "(", "function", "(", "th", ")", "{", "newColumns", ".", "push", "(", "th", ".", "getHtml", "(", ")", ")", ";", "}", ")", ";", "config", ".", "data", ".", "all", "(", "'tr'", ")", ".", "each", "(", "function", "(", "tr", ")", "{", "var", "newRow", "=", "{", "}", ",", "populated", "=", "false", ";", "for", "(", "var", "i", "=", "0", ",", "numCols", "=", "headings", ".", "size", "(", ")", ";", "i", "<", "numCols", ";", "i", "++", ")", "{", "if", "(", "!", "tr", ".", "all", "(", "'td'", ")", ".", "item", "(", "i", ")", ")", "{", "continue", ";", "}", "newRow", "[", "headings", ".", "item", "(", "i", ")", ".", "getHtml", "(", ")", "]", "=", "tr", ".", "all", "(", "'td'", ")", ".", "item", "(", "i", ")", ".", "getHtml", "(", ")", ";", "populated", "=", "true", ";", "}", "if", "(", "populated", ")", "{", "newData", ".", "push", "(", "newRow", ")", ";", "}", "}", ")", ";", "config", ".", "columns", "=", "newColumns", ";", "config", ".", "data", "=", "newData", ";", "return", "new", "JSONDataSource", "(", "config", ")", ";", "}" ]
All we do is transform the table into json and reutrn a JSONDataSource
[ "All", "we", "do", "is", "transform", "the", "table", "into", "json", "and", "reutrn", "a", "JSONDataSource" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L129-L160
37,980
nwtjs/nwt
plugins/bootstrap/datatable.js
function(el) { var mythis = this; this.source.colSortIdx = el.data('col-idx'); this.source.columns[el.data('col-idx')].dir = this.source.columns[el.data('col-idx')].dir == 'asc' ? 'desc' : 'asc'; this.source.update(function() { mythis.render(); }); }
javascript
function(el) { var mythis = this; this.source.colSortIdx = el.data('col-idx'); this.source.columns[el.data('col-idx')].dir = this.source.columns[el.data('col-idx')].dir == 'asc' ? 'desc' : 'asc'; this.source.update(function() { mythis.render(); }); }
[ "function", "(", "el", ")", "{", "var", "mythis", "=", "this", ";", "this", ".", "source", ".", "colSortIdx", "=", "el", ".", "data", "(", "'col-idx'", ")", ";", "this", ".", "source", ".", "columns", "[", "el", ".", "data", "(", "'col-idx'", ")", "]", ".", "dir", "=", "this", ".", "source", ".", "columns", "[", "el", ".", "data", "(", "'col-idx'", ")", "]", ".", "dir", "==", "'asc'", "?", "'desc'", ":", "'asc'", ";", "this", ".", "source", ".", "update", "(", "function", "(", ")", "{", "mythis", ".", "render", "(", ")", ";", "}", ")", ";", "}" ]
Sorts the datatable
[ "Sorts", "the", "datatable" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L236-L245
37,981
nwtjs/nwt
plugins/bootstrap/datatable.js
function() { var self = this; // Populate table html var content = ['<table class="' + this.tableClass + '" data-instance="' + this.instanceCount + '"><thead>', '<tr>']; for (var i in this.source.columns) { var sortContent = this.source.columns[i].name, colDir = self.source.columns[i].dir; if (self.source.colSortIdx == i) { sortContent = self.formatSortHeader(this.source.columns[i].name, colDir) } content.push('<th class="col-' + i + '"><a data-col-idx="' + i + '" data-sort="sort" href="#" title="' + this.source.columns[i].name +'">' + sortContent + '</a></th>'); } content.push('</tr></thead><tbody>'); for (var i = 0, rows = this.source.data.length; i < rows; i++) { var datum = this.source.data[i]; // Add in a reference to the data dataLookup[this.instanceCount][i] = datum content.push('<tr class="row-' + i + '"">'); for (var j in this.source.columns) { content.push('<td class="col-' + j +'">' + this.source.columns[j].formatter(datum) + '</td>'); } content.push('</tr>'); } content.push('</tbody></table>'); this.node.setHtml(content.join('')); this.node.one('table thead').on('click', function(e) { if (e.target.data('sort')) { self.sort(e.target); self.node.all('th a').item(e.target.data('col-idx'))._node.focus() e.stop(); } }); this.node.fire('render') }
javascript
function() { var self = this; // Populate table html var content = ['<table class="' + this.tableClass + '" data-instance="' + this.instanceCount + '"><thead>', '<tr>']; for (var i in this.source.columns) { var sortContent = this.source.columns[i].name, colDir = self.source.columns[i].dir; if (self.source.colSortIdx == i) { sortContent = self.formatSortHeader(this.source.columns[i].name, colDir) } content.push('<th class="col-' + i + '"><a data-col-idx="' + i + '" data-sort="sort" href="#" title="' + this.source.columns[i].name +'">' + sortContent + '</a></th>'); } content.push('</tr></thead><tbody>'); for (var i = 0, rows = this.source.data.length; i < rows; i++) { var datum = this.source.data[i]; // Add in a reference to the data dataLookup[this.instanceCount][i] = datum content.push('<tr class="row-' + i + '"">'); for (var j in this.source.columns) { content.push('<td class="col-' + j +'">' + this.source.columns[j].formatter(datum) + '</td>'); } content.push('</tr>'); } content.push('</tbody></table>'); this.node.setHtml(content.join('')); this.node.one('table thead').on('click', function(e) { if (e.target.data('sort')) { self.sort(e.target); self.node.all('th a').item(e.target.data('col-idx'))._node.focus() e.stop(); } }); this.node.fire('render') }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "// Populate table html", "var", "content", "=", "[", "'<table class=\"'", "+", "this", ".", "tableClass", "+", "'\" data-instance=\"'", "+", "this", ".", "instanceCount", "+", "'\"><thead>'", ",", "'<tr>'", "]", ";", "for", "(", "var", "i", "in", "this", ".", "source", ".", "columns", ")", "{", "var", "sortContent", "=", "this", ".", "source", ".", "columns", "[", "i", "]", ".", "name", ",", "colDir", "=", "self", ".", "source", ".", "columns", "[", "i", "]", ".", "dir", ";", "if", "(", "self", ".", "source", ".", "colSortIdx", "==", "i", ")", "{", "sortContent", "=", "self", ".", "formatSortHeader", "(", "this", ".", "source", ".", "columns", "[", "i", "]", ".", "name", ",", "colDir", ")", "}", "content", ".", "push", "(", "'<th class=\"col-'", "+", "i", "+", "'\"><a data-col-idx=\"'", "+", "i", "+", "'\" data-sort=\"sort\" href=\"#\" title=\"'", "+", "this", ".", "source", ".", "columns", "[", "i", "]", ".", "name", "+", "'\">'", "+", "sortContent", "+", "'</a></th>'", ")", ";", "}", "content", ".", "push", "(", "'</tr></thead><tbody>'", ")", ";", "for", "(", "var", "i", "=", "0", ",", "rows", "=", "this", ".", "source", ".", "data", ".", "length", ";", "i", "<", "rows", ";", "i", "++", ")", "{", "var", "datum", "=", "this", ".", "source", ".", "data", "[", "i", "]", ";", "// Add in a reference to the data", "dataLookup", "[", "this", ".", "instanceCount", "]", "[", "i", "]", "=", "datum", "content", ".", "push", "(", "'<tr class=\"row-'", "+", "i", "+", "'\"\">'", ")", ";", "for", "(", "var", "j", "in", "this", ".", "source", ".", "columns", ")", "{", "content", ".", "push", "(", "'<td class=\"col-'", "+", "j", "+", "'\">'", "+", "this", ".", "source", ".", "columns", "[", "j", "]", ".", "formatter", "(", "datum", ")", "+", "'</td>'", ")", ";", "}", "content", ".", "push", "(", "'</tr>'", ")", ";", "}", "content", ".", "push", "(", "'</tbody></table>'", ")", ";", "this", ".", "node", ".", "setHtml", "(", "content", ".", "join", "(", "''", ")", ")", ";", "this", ".", "node", ".", "one", "(", "'table thead'", ")", ".", "on", "(", "'click'", ",", "function", "(", "e", ")", "{", "if", "(", "e", ".", "target", ".", "data", "(", "'sort'", ")", ")", "{", "self", ".", "sort", "(", "e", ".", "target", ")", ";", "self", ".", "node", ".", "all", "(", "'th a'", ")", ".", "item", "(", "e", ".", "target", ".", "data", "(", "'col-idx'", ")", ")", ".", "_node", ".", "focus", "(", ")", "e", ".", "stop", "(", ")", ";", "}", "}", ")", ";", "this", ".", "node", ".", "fire", "(", "'render'", ")", "}" ]
When we render, the datasource should be updated
[ "When", "we", "render", "the", "datasource", "should", "be", "updated" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L250-L300
37,982
brandonheyer/mazejs
js/foundation/foundation.js
function (el) { var opts = {}, ii, p, opts_arr = (el.attr('data-options') || ':').split(';'), opts_len = opts_arr.length; function isNumber (o) { return ! isNaN (o-0) && o !== null && o !== "" && o !== false && o !== true; } function trim(str) { if (typeof str === 'string') return $.trim(str); return str; } // parse options for (ii = opts_len - 1; ii >= 0; ii--) { p = opts_arr[ii].split(':'); if (/true/i.test(p[1])) p[1] = true; if (/false/i.test(p[1])) p[1] = false; if (isNumber(p[1])) p[1] = parseInt(p[1], 10); if (p.length === 2 && p[0].length > 0) { opts[trim(p[0])] = trim(p[1]); } } return opts; }
javascript
function (el) { var opts = {}, ii, p, opts_arr = (el.attr('data-options') || ':').split(';'), opts_len = opts_arr.length; function isNumber (o) { return ! isNaN (o-0) && o !== null && o !== "" && o !== false && o !== true; } function trim(str) { if (typeof str === 'string') return $.trim(str); return str; } // parse options for (ii = opts_len - 1; ii >= 0; ii--) { p = opts_arr[ii].split(':'); if (/true/i.test(p[1])) p[1] = true; if (/false/i.test(p[1])) p[1] = false; if (isNumber(p[1])) p[1] = parseInt(p[1], 10); if (p.length === 2 && p[0].length > 0) { opts[trim(p[0])] = trim(p[1]); } } return opts; }
[ "function", "(", "el", ")", "{", "var", "opts", "=", "{", "}", ",", "ii", ",", "p", ",", "opts_arr", "=", "(", "el", ".", "attr", "(", "'data-options'", ")", "||", "':'", ")", ".", "split", "(", "';'", ")", ",", "opts_len", "=", "opts_arr", ".", "length", ";", "function", "isNumber", "(", "o", ")", "{", "return", "!", "isNaN", "(", "o", "-", "0", ")", "&&", "o", "!==", "null", "&&", "o", "!==", "\"\"", "&&", "o", "!==", "false", "&&", "o", "!==", "true", ";", "}", "function", "trim", "(", "str", ")", "{", "if", "(", "typeof", "str", "===", "'string'", ")", "return", "$", ".", "trim", "(", "str", ")", ";", "return", "str", ";", "}", "// parse options", "for", "(", "ii", "=", "opts_len", "-", "1", ";", "ii", ">=", "0", ";", "ii", "--", ")", "{", "p", "=", "opts_arr", "[", "ii", "]", ".", "split", "(", "':'", ")", ";", "if", "(", "/", "true", "/", "i", ".", "test", "(", "p", "[", "1", "]", ")", ")", "p", "[", "1", "]", "=", "true", ";", "if", "(", "/", "false", "/", "i", ".", "test", "(", "p", "[", "1", "]", ")", ")", "p", "[", "1", "]", "=", "false", ";", "if", "(", "isNumber", "(", "p", "[", "1", "]", ")", ")", "p", "[", "1", "]", "=", "parseInt", "(", "p", "[", "1", "]", ",", "10", ")", ";", "if", "(", "p", ".", "length", "===", "2", "&&", "p", "[", "0", "]", ".", "length", ">", "0", ")", "{", "opts", "[", "trim", "(", "p", "[", "0", "]", ")", "]", "=", "trim", "(", "p", "[", "1", "]", ")", ";", "}", "}", "return", "opts", ";", "}" ]
parses data-options attribute on nodes and turns them into an object
[ "parses", "data", "-", "options", "attribute", "on", "nodes", "and", "turns", "them", "into", "an", "object" ]
5efffc0279eeb061a71ba243313d165c16300fe6
https://github.com/brandonheyer/mazejs/blob/5efffc0279eeb061a71ba243313d165c16300fe6/js/foundation/foundation.js#L254-L282
37,983
mojaie/kiwiii
src/common/idb.js
getAllItems
function getAllItems() { return new Promise(resolve => { const res = []; return instance.pkgs.then(db => { db.transaction(db.name) .objectStore(db.name).openCursor() .onsuccess = event => { const cursor = event.target.result; if (cursor) { res.push(cursor.value); cursor.continue(); } else { resolve(res); } }; }); }); }
javascript
function getAllItems() { return new Promise(resolve => { const res = []; return instance.pkgs.then(db => { db.transaction(db.name) .objectStore(db.name).openCursor() .onsuccess = event => { const cursor = event.target.result; if (cursor) { res.push(cursor.value); cursor.continue(); } else { resolve(res); } }; }); }); }
[ "function", "getAllItems", "(", ")", "{", "return", "new", "Promise", "(", "resolve", "=>", "{", "const", "res", "=", "[", "]", ";", "return", "instance", ".", "pkgs", ".", "then", "(", "db", "=>", "{", "db", ".", "transaction", "(", "db", ".", "name", ")", ".", "objectStore", "(", "db", ".", "name", ")", ".", "openCursor", "(", ")", ".", "onsuccess", "=", "event", "=>", "{", "const", "cursor", "=", "event", ".", "target", ".", "result", ";", "if", "(", "cursor", ")", "{", "res", ".", "push", "(", "cursor", ".", "value", ")", ";", "cursor", ".", "continue", "(", ")", ";", "}", "else", "{", "resolve", "(", "res", ")", ";", "}", "}", ";", "}", ")", ";", "}", ")", ";", "}" ]
Returns all packages @return {Promise} Promise of list of packages
[ "Returns", "all", "packages" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L67-L84
37,984
mojaie/kiwiii
src/common/idb.js
getItem
function getItem(id) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const req = db.transaction(db.name) .objectStore(db.name).get(id); req.onsuccess = event => resolve(event.target.result); req.onerror = event => reject(event); }); }); }
javascript
function getItem(id) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const req = db.transaction(db.name) .objectStore(db.name).get(id); req.onsuccess = event => resolve(event.target.result); req.onerror = event => reject(event); }); }); }
[ "function", "getItem", "(", "id", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "return", "instance", ".", "pkgs", ".", "then", "(", "db", "=>", "{", "const", "req", "=", "db", ".", "transaction", "(", "db", ".", "name", ")", ".", "objectStore", "(", "db", ".", "name", ")", ".", "get", "(", "id", ")", ";", "req", ".", "onsuccess", "=", "event", "=>", "resolve", "(", "event", ".", "target", ".", "result", ")", ";", "req", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Get packages by instance ID @param {string} id - Package instance ID @return {array} data store object
[ "Get", "packages", "by", "instance", "ID" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L92-L101
37,985
mojaie/kiwiii
src/common/idb.js
putItem
function putItem(value) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const obj = db.transaction(db.name, 'readwrite') .objectStore(db.name); const req = obj.put(value); req.onerror = event => reject(event); req.onsuccess = () => resolve(); }); }); }
javascript
function putItem(value) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const obj = db.transaction(db.name, 'readwrite') .objectStore(db.name); const req = obj.put(value); req.onerror = event => reject(event); req.onsuccess = () => resolve(); }); }); }
[ "function", "putItem", "(", "value", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "return", "instance", ".", "pkgs", ".", "then", "(", "db", "=>", "{", "const", "obj", "=", "db", ".", "transaction", "(", "db", ".", "name", ",", "'readwrite'", ")", ".", "objectStore", "(", "db", ".", "name", ")", ";", "const", "req", "=", "obj", ".", "put", "(", "value", ")", ";", "req", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "req", ".", "onsuccess", "=", "(", ")", "=>", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Put data object in the store @param {string} value - value to store
[ "Put", "data", "object", "in", "the", "store" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L108-L118
37,986
mojaie/kiwiii
src/common/idb.js
updateItem
function updateItem(id, updater) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const obj = db.transaction(db.name, 'readwrite') .objectStore(db.name); const req = obj.get(id); req.onerror = event => reject(event); req.onsuccess = event => { const res = event.target.result; updater(res); const upd = obj.put(res); upd.onsuccess = () => resolve(); upd.onerror = event => reject(event); }; }); }); }
javascript
function updateItem(id, updater) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const obj = db.transaction(db.name, 'readwrite') .objectStore(db.name); const req = obj.get(id); req.onerror = event => reject(event); req.onsuccess = event => { const res = event.target.result; updater(res); const upd = obj.put(res); upd.onsuccess = () => resolve(); upd.onerror = event => reject(event); }; }); }); }
[ "function", "updateItem", "(", "id", ",", "updater", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "return", "instance", ".", "pkgs", ".", "then", "(", "db", "=>", "{", "const", "obj", "=", "db", ".", "transaction", "(", "db", ".", "name", ",", "'readwrite'", ")", ".", "objectStore", "(", "db", ".", "name", ")", ";", "const", "req", "=", "obj", ".", "get", "(", "id", ")", ";", "req", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "req", ".", "onsuccess", "=", "event", "=>", "{", "const", "res", "=", "event", ".", "target", ".", "result", ";", "updater", "(", "res", ")", ";", "const", "upd", "=", "obj", ".", "put", "(", "res", ")", ";", "upd", ".", "onsuccess", "=", "(", ")", "=>", "resolve", "(", ")", ";", "upd", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "}", ";", "}", ")", ";", "}", ")", ";", "}" ]
Update package in the store @param {string} id - Package instance ID @param {function} updater - update function
[ "Update", "package", "in", "the", "store" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L126-L142
37,987
mojaie/kiwiii
src/common/idb.js
deleteItem
function deleteItem(id) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const req = db.transaction(db.name, 'readwrite') .objectStore(db.name).delete(id); req.onerror = event => reject(event); req.onsuccess = () => resolve(); }); }); }
javascript
function deleteItem(id) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const req = db.transaction(db.name, 'readwrite') .objectStore(db.name).delete(id); req.onerror = event => reject(event); req.onsuccess = () => resolve(); }); }); }
[ "function", "deleteItem", "(", "id", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "return", "instance", ".", "pkgs", ".", "then", "(", "db", "=>", "{", "const", "req", "=", "db", ".", "transaction", "(", "db", ".", "name", ",", "'readwrite'", ")", ".", "objectStore", "(", "db", ".", "name", ")", ".", "delete", "(", "id", ")", ";", "req", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "req", ".", "onsuccess", "=", "(", ")", "=>", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Delete a package @param {string} id - Package instance ID
[ "Delete", "a", "package" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L149-L158
37,988
mojaie/kiwiii
src/common/idb.js
getView
function getView(id, viewID) { return getItem(id) .then(pkg => pkg.views.find(e => e.viewID === viewID)); }
javascript
function getView(id, viewID) { return getItem(id) .then(pkg => pkg.views.find(e => e.viewID === viewID)); }
[ "function", "getView", "(", "id", ",", "viewID", ")", "{", "return", "getItem", "(", "id", ")", ".", "then", "(", "pkg", "=>", "pkg", ".", "views", ".", "find", "(", "e", "=>", "e", ".", "viewID", "===", "viewID", ")", ")", ";", "}" ]
Returns a view @param {string} id - Package instance ID @param {string} viewID - view ID @return {array} view objects
[ "Returns", "a", "view" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L167-L170
37,989
mojaie/kiwiii
src/common/idb.js
appendView
function appendView(id, viewID, viewObj) { return updateItem(id, item => { const pos = item.views.findIndex(e => e.viewID === viewID); item.views.splice(pos + 1, 0, viewObj); }); }
javascript
function appendView(id, viewID, viewObj) { return updateItem(id, item => { const pos = item.views.findIndex(e => e.viewID === viewID); item.views.splice(pos + 1, 0, viewObj); }); }
[ "function", "appendView", "(", "id", ",", "viewID", ",", "viewObj", ")", "{", "return", "updateItem", "(", "id", ",", "item", "=>", "{", "const", "pos", "=", "item", ".", "views", ".", "findIndex", "(", "e", "=>", "e", ".", "viewID", "===", "viewID", ")", ";", "item", ".", "views", ".", "splice", "(", "pos", "+", "1", ",", "0", ",", "viewObj", ")", ";", "}", ")", ";", "}" ]
Append a view next to a specific view @param {string} id - Package instance ID @param {string} viewID - view ID @param {object} viewObj - view object
[ "Append", "a", "view", "next", "to", "a", "specific", "view" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L179-L184
37,990
mojaie/kiwiii
src/common/idb.js
deleteView
function deleteView(id, viewID) { return updateItem(id, item => { const pos = item.views.findIndex(e => e.viewID === viewID); item.views.splice(pos, 1); // prune orphaned collections const bin = {}; item.dataset.forEach(e => { bin[e.collectionID] = 0; }); item.views.forEach(view => { ['rows', 'items', 'nodes', 'edges'] .filter(e => view.hasOwnProperty(e)) .forEach(e => { bin[view[e]] += 1; }); }); Object.entries(bin).forEach(entry => { if (!entry[1]) { const i = item.dataset.findIndex(e => e.collectionID === entry[0]); item.dataset.splice(i, 1); } }); }); }
javascript
function deleteView(id, viewID) { return updateItem(id, item => { const pos = item.views.findIndex(e => e.viewID === viewID); item.views.splice(pos, 1); // prune orphaned collections const bin = {}; item.dataset.forEach(e => { bin[e.collectionID] = 0; }); item.views.forEach(view => { ['rows', 'items', 'nodes', 'edges'] .filter(e => view.hasOwnProperty(e)) .forEach(e => { bin[view[e]] += 1; }); }); Object.entries(bin).forEach(entry => { if (!entry[1]) { const i = item.dataset.findIndex(e => e.collectionID === entry[0]); item.dataset.splice(i, 1); } }); }); }
[ "function", "deleteView", "(", "id", ",", "viewID", ")", "{", "return", "updateItem", "(", "id", ",", "item", "=>", "{", "const", "pos", "=", "item", ".", "views", ".", "findIndex", "(", "e", "=>", "e", ".", "viewID", "===", "viewID", ")", ";", "item", ".", "views", ".", "splice", "(", "pos", ",", "1", ")", ";", "// prune orphaned collections", "const", "bin", "=", "{", "}", ";", "item", ".", "dataset", ".", "forEach", "(", "e", "=>", "{", "bin", "[", "e", ".", "collectionID", "]", "=", "0", ";", "}", ")", ";", "item", ".", "views", ".", "forEach", "(", "view", "=>", "{", "[", "'rows'", ",", "'items'", ",", "'nodes'", ",", "'edges'", "]", ".", "filter", "(", "e", "=>", "view", ".", "hasOwnProperty", "(", "e", ")", ")", ".", "forEach", "(", "e", "=>", "{", "bin", "[", "view", "[", "e", "]", "]", "+=", "1", ";", "}", ")", ";", "}", ")", ";", "Object", ".", "entries", "(", "bin", ")", ".", "forEach", "(", "entry", "=>", "{", "if", "(", "!", "entry", "[", "1", "]", ")", "{", "const", "i", "=", "item", ".", "dataset", ".", "findIndex", "(", "e", "=>", "e", ".", "collectionID", "===", "entry", "[", "0", "]", ")", ";", "item", ".", "dataset", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Delete a data object from the store @param {string} id - Package instance ID @return {integer} - number of deleted items
[ "Delete", "a", "data", "object", "from", "the", "store" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L210-L229
37,991
mojaie/kiwiii
src/common/idb.js
getAllCollections
function getAllCollections() { return getAllItems() .then(items => _.flatten( items.map(item => { return item.dataset.map(coll => { coll.instance = item.id; return coll; }); }) )); }
javascript
function getAllCollections() { return getAllItems() .then(items => _.flatten( items.map(item => { return item.dataset.map(coll => { coll.instance = item.id; return coll; }); }) )); }
[ "function", "getAllCollections", "(", ")", "{", "return", "getAllItems", "(", ")", ".", "then", "(", "items", "=>", "_", ".", "flatten", "(", "items", ".", "map", "(", "item", "=>", "{", "return", "item", ".", "dataset", ".", "map", "(", "coll", "=>", "{", "coll", ".", "instance", "=", "item", ".", "id", ";", "return", "coll", ";", "}", ")", ";", "}", ")", ")", ")", ";", "}" ]
Returns all collections in the store @return {array} Collection objects
[ "Returns", "all", "collections", "in", "the", "store" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L236-L246
37,992
mojaie/kiwiii
src/common/idb.js
getCollection
function getCollection(id, collID) { return getItem(id) .then(pkg => pkg.dataset.find(e => e.collectionID === collID)); }
javascript
function getCollection(id, collID) { return getItem(id) .then(pkg => pkg.dataset.find(e => e.collectionID === collID)); }
[ "function", "getCollection", "(", "id", ",", "collID", ")", "{", "return", "getItem", "(", "id", ")", ".", "then", "(", "pkg", "=>", "pkg", ".", "dataset", ".", "find", "(", "e", "=>", "e", ".", "collectionID", "===", "collID", ")", ")", ";", "}" ]
Returns a collection @param {string} id - Package instance ID @param {string} collID - Collection ID @return {array} Collection objects
[ "Returns", "a", "collection" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L255-L258
37,993
mojaie/kiwiii
src/common/idb.js
newNetwork
function newNetwork(instance, nodesID, nodesName, response) { const viewID = misc.uuidv4().slice(0, 8); const edgesID = response.workflowID.slice(0, 8); return updateItem(instance, item => { item.views.push({ $schema: "https://mojaie.github.io/kiwiii/specs/network_v1.0.json", viewID: viewID, name: `${nodesName}_${response.name}`, viewType: 'network', nodes: nodesID, edges: edgesID, minConnThld: response.query.params.threshold }); item.dataset.push({ $schema: "https://mojaie.github.io/kiwiii/specs/collection_v1.0.json", collectionID: edgesID, name: response.name, contents: [response] }); }).then(() => viewID); }
javascript
function newNetwork(instance, nodesID, nodesName, response) { const viewID = misc.uuidv4().slice(0, 8); const edgesID = response.workflowID.slice(0, 8); return updateItem(instance, item => { item.views.push({ $schema: "https://mojaie.github.io/kiwiii/specs/network_v1.0.json", viewID: viewID, name: `${nodesName}_${response.name}`, viewType: 'network', nodes: nodesID, edges: edgesID, minConnThld: response.query.params.threshold }); item.dataset.push({ $schema: "https://mojaie.github.io/kiwiii/specs/collection_v1.0.json", collectionID: edgesID, name: response.name, contents: [response] }); }).then(() => viewID); }
[ "function", "newNetwork", "(", "instance", ",", "nodesID", ",", "nodesName", ",", "response", ")", "{", "const", "viewID", "=", "misc", ".", "uuidv4", "(", ")", ".", "slice", "(", "0", ",", "8", ")", ";", "const", "edgesID", "=", "response", ".", "workflowID", ".", "slice", "(", "0", ",", "8", ")", ";", "return", "updateItem", "(", "instance", ",", "item", "=>", "{", "item", ".", "views", ".", "push", "(", "{", "$schema", ":", "\"https://mojaie.github.io/kiwiii/specs/network_v1.0.json\"", ",", "viewID", ":", "viewID", ",", "name", ":", "`", "${", "nodesName", "}", "${", "response", ".", "name", "}", "`", ",", "viewType", ":", "'network'", ",", "nodes", ":", "nodesID", ",", "edges", ":", "edgesID", ",", "minConnThld", ":", "response", ".", "query", ".", "params", ".", "threshold", "}", ")", ";", "item", ".", "dataset", ".", "push", "(", "{", "$schema", ":", "\"https://mojaie.github.io/kiwiii/specs/collection_v1.0.json\"", ",", "collectionID", ":", "edgesID", ",", "name", ":", "response", ".", "name", ",", "contents", ":", "[", "response", "]", "}", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "viewID", ")", ";", "}" ]
Store new network view @param {string} instance - Package instance ID @param {string} nodesID - ID of nodes collection @param {string} nodesName - Name of nodes collection @param {object} response - Response object
[ "Store", "new", "network", "view" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L431-L451
37,994
mojaie/kiwiii
src/common/idb.js
getAsset
function getAsset(key) { return new Promise((resolve, reject) => { return instance.assets.then(db => { const req = db.transaction(db.name) .objectStore(db.name).get(key); req.onsuccess = event => { const undef = event.target.result === undefined; const value = undef ? undefined : event.target.result.value; resolve(value); }; req.onerror = event => reject(event); }); }); }
javascript
function getAsset(key) { return new Promise((resolve, reject) => { return instance.assets.then(db => { const req = db.transaction(db.name) .objectStore(db.name).get(key); req.onsuccess = event => { const undef = event.target.result === undefined; const value = undef ? undefined : event.target.result.value; resolve(value); }; req.onerror = event => reject(event); }); }); }
[ "function", "getAsset", "(", "key", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "return", "instance", ".", "assets", ".", "then", "(", "db", "=>", "{", "const", "req", "=", "db", ".", "transaction", "(", "db", ".", "name", ")", ".", "objectStore", "(", "db", ".", "name", ")", ".", "get", "(", "key", ")", ";", "req", ".", "onsuccess", "=", "event", "=>", "{", "const", "undef", "=", "event", ".", "target", ".", "result", "===", "undefined", ";", "const", "value", "=", "undef", "?", "undefined", ":", "event", ".", "target", ".", "result", ".", "value", ";", "resolve", "(", "value", ")", ";", "}", ";", "req", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Get asset by a key @param {string} key - key @return {array} asset object (if not found, resolve with undefined)
[ "Get", "asset", "by", "a", "key" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L459-L472
37,995
mojaie/kiwiii
src/common/idb.js
putAsset
function putAsset(key, content) { return new Promise((resolve, reject) => { return instance.assets.then(db => { const obj = db.transaction(db.name, 'readwrite') .objectStore(db.name); const req = obj.put({key: key, value: content}); req.onerror = event => reject(event); req.onsuccess = () => resolve(); }); }); }
javascript
function putAsset(key, content) { return new Promise((resolve, reject) => { return instance.assets.then(db => { const obj = db.transaction(db.name, 'readwrite') .objectStore(db.name); const req = obj.put({key: key, value: content}); req.onerror = event => reject(event); req.onsuccess = () => resolve(); }); }); }
[ "function", "putAsset", "(", "key", ",", "content", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "return", "instance", ".", "assets", ".", "then", "(", "db", "=>", "{", "const", "obj", "=", "db", ".", "transaction", "(", "db", ".", "name", ",", "'readwrite'", ")", ".", "objectStore", "(", "db", ".", "name", ")", ";", "const", "req", "=", "obj", ".", "put", "(", "{", "key", ":", "key", ",", "value", ":", "content", "}", ")", ";", "req", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "req", ".", "onsuccess", "=", "(", ")", "=>", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Put asset object with a key @param {string} key - key @param {string} content - asset to store
[ "Put", "asset", "object", "with", "a", "key" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L479-L489
37,996
mojaie/kiwiii
src/component/legend.js
updateLegendGroup
function updateLegendGroup(selection, viewBox, orient) { const widthFactor = 0.2; const scaleF = viewBox.right * widthFactor / 120; const o = orient.split('-'); const viewW = viewBox.right; const viewH = viewBox.bottom; const legW = viewW * widthFactor; const legH = legW * 50 / 120; const posX = {left: legW / 10, right: viewW - legW - (legW / 10)}[o[1]]; const posY = {top: legH / 10, bottom: viewH - legH - (legH / 10)}[o[0]]; selection.attr('transform', `translate(${posX}, ${posY}) scale(${scaleF})`); }
javascript
function updateLegendGroup(selection, viewBox, orient) { const widthFactor = 0.2; const scaleF = viewBox.right * widthFactor / 120; const o = orient.split('-'); const viewW = viewBox.right; const viewH = viewBox.bottom; const legW = viewW * widthFactor; const legH = legW * 50 / 120; const posX = {left: legW / 10, right: viewW - legW - (legW / 10)}[o[1]]; const posY = {top: legH / 10, bottom: viewH - legH - (legH / 10)}[o[0]]; selection.attr('transform', `translate(${posX}, ${posY}) scale(${scaleF})`); }
[ "function", "updateLegendGroup", "(", "selection", ",", "viewBox", ",", "orient", ")", "{", "const", "widthFactor", "=", "0.2", ";", "const", "scaleF", "=", "viewBox", ".", "right", "*", "widthFactor", "/", "120", ";", "const", "o", "=", "orient", ".", "split", "(", "'-'", ")", ";", "const", "viewW", "=", "viewBox", ".", "right", ";", "const", "viewH", "=", "viewBox", ".", "bottom", ";", "const", "legW", "=", "viewW", "*", "widthFactor", ";", "const", "legH", "=", "legW", "*", "50", "/", "120", ";", "const", "posX", "=", "{", "left", ":", "legW", "/", "10", ",", "right", ":", "viewW", "-", "legW", "-", "(", "legW", "/", "10", ")", "}", "[", "o", "[", "1", "]", "]", ";", "const", "posY", "=", "{", "top", ":", "legH", "/", "10", ",", "bottom", ":", "viewH", "-", "legH", "-", "(", "legH", "/", "10", ")", "}", "[", "o", "[", "0", "]", "]", ";", "selection", ".", "attr", "(", "'transform'", ",", "`", "${", "posX", "}", "${", "posY", "}", "${", "scaleF", "}", "`", ")", ";", "}" ]
Legend group component @param {d3.selection} selection - selection of group container (svg:g)
[ "Legend", "group", "component" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/component/legend.js#L61-L73
37,997
fnogatz/node-swtparser
build-structure.js
loadKeyValueCSV
function loadKeyValueCSV (filename, callback) { var out = {} csv() .from.path(filename, { delimiter: '\t' }) .on('record', function (data, index) { if (data[0].match(/^[\w\d]/)) { out[data[0]] = data[1] } }) .on('end', function (count) { callback(null, out) }) .on('error', function (err) { callback(err) }) }
javascript
function loadKeyValueCSV (filename, callback) { var out = {} csv() .from.path(filename, { delimiter: '\t' }) .on('record', function (data, index) { if (data[0].match(/^[\w\d]/)) { out[data[0]] = data[1] } }) .on('end', function (count) { callback(null, out) }) .on('error', function (err) { callback(err) }) }
[ "function", "loadKeyValueCSV", "(", "filename", ",", "callback", ")", "{", "var", "out", "=", "{", "}", "csv", "(", ")", ".", "from", ".", "path", "(", "filename", ",", "{", "delimiter", ":", "'\\t'", "}", ")", ".", "on", "(", "'record'", ",", "function", "(", "data", ",", "index", ")", "{", "if", "(", "data", "[", "0", "]", ".", "match", "(", "/", "^[\\w\\d]", "/", ")", ")", "{", "out", "[", "data", "[", "0", "]", "]", "=", "data", "[", "1", "]", "}", "}", ")", ".", "on", "(", "'end'", ",", "function", "(", "count", ")", "{", "callback", "(", "null", ",", "out", ")", "}", ")", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ")", "}", ")", "}" ]
Loads key-value-pairs saved in a CSV file into an object. @param {String} filename to read from @param {Function} callback that takes the object
[ "Loads", "key", "-", "value", "-", "pairs", "saved", "in", "a", "CSV", "file", "into", "an", "object", "." ]
4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3
https://github.com/fnogatz/node-swtparser/blob/4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3/build-structure.js#L16-L34
37,998
fnogatz/node-swtparser
build-structure.js
loadStructureCSV
function loadStructureCSV (filename, callback) { var out = {} csv() .from.path(filename, { delimiter: '\t' }) .transform(function (data) { // hex values to decimal if (!data[0].match(/^[0-9A-Fa-f]/)) { return false } // comment var ret = { field: parseInt(data[3]), type: data[2].substr(0, 3) } if (ret.type === 'sel') { if (data[2].length === 3) { ret.selection = ret.field } else { ret.selection = parseInt(data[2].replace(/^sel:/, '')) } } if (data[1].length > 0) { ret.from = parseInt(data[0], 16) ret.to = parseInt(data[1], 16) } else { ret.where = parseInt(data[0], 16) } return ret }) .on('record', function (data, index) { if (data) { var field = data.field delete data.field out[field] = data } }) .on('end', function (count) { callback(null, out) }) .on('error', function (err) { callback(err) }) }
javascript
function loadStructureCSV (filename, callback) { var out = {} csv() .from.path(filename, { delimiter: '\t' }) .transform(function (data) { // hex values to decimal if (!data[0].match(/^[0-9A-Fa-f]/)) { return false } // comment var ret = { field: parseInt(data[3]), type: data[2].substr(0, 3) } if (ret.type === 'sel') { if (data[2].length === 3) { ret.selection = ret.field } else { ret.selection = parseInt(data[2].replace(/^sel:/, '')) } } if (data[1].length > 0) { ret.from = parseInt(data[0], 16) ret.to = parseInt(data[1], 16) } else { ret.where = parseInt(data[0], 16) } return ret }) .on('record', function (data, index) { if (data) { var field = data.field delete data.field out[field] = data } }) .on('end', function (count) { callback(null, out) }) .on('error', function (err) { callback(err) }) }
[ "function", "loadStructureCSV", "(", "filename", ",", "callback", ")", "{", "var", "out", "=", "{", "}", "csv", "(", ")", ".", "from", ".", "path", "(", "filename", ",", "{", "delimiter", ":", "'\\t'", "}", ")", ".", "transform", "(", "function", "(", "data", ")", "{", "// hex values to decimal", "if", "(", "!", "data", "[", "0", "]", ".", "match", "(", "/", "^[0-9A-Fa-f]", "/", ")", ")", "{", "return", "false", "}", "// comment", "var", "ret", "=", "{", "field", ":", "parseInt", "(", "data", "[", "3", "]", ")", ",", "type", ":", "data", "[", "2", "]", ".", "substr", "(", "0", ",", "3", ")", "}", "if", "(", "ret", ".", "type", "===", "'sel'", ")", "{", "if", "(", "data", "[", "2", "]", ".", "length", "===", "3", ")", "{", "ret", ".", "selection", "=", "ret", ".", "field", "}", "else", "{", "ret", ".", "selection", "=", "parseInt", "(", "data", "[", "2", "]", ".", "replace", "(", "/", "^sel:", "/", ",", "''", ")", ")", "}", "}", "if", "(", "data", "[", "1", "]", ".", "length", ">", "0", ")", "{", "ret", ".", "from", "=", "parseInt", "(", "data", "[", "0", "]", ",", "16", ")", "ret", ".", "to", "=", "parseInt", "(", "data", "[", "1", "]", ",", "16", ")", "}", "else", "{", "ret", ".", "where", "=", "parseInt", "(", "data", "[", "0", "]", ",", "16", ")", "}", "return", "ret", "}", ")", ".", "on", "(", "'record'", ",", "function", "(", "data", ",", "index", ")", "{", "if", "(", "data", ")", "{", "var", "field", "=", "data", ".", "field", "delete", "data", ".", "field", "out", "[", "field", "]", "=", "data", "}", "}", ")", ".", "on", "(", "'end'", ",", "function", "(", "count", ")", "{", "callback", "(", "null", ",", "out", ")", "}", ")", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "callback", "(", "err", ")", "}", ")", "}" ]
Loads a CSV structure file into an object with specified field keys as object keys. @param {String} filename to read from @param {Function} callback that takes the object
[ "Loads", "a", "CSV", "structure", "file", "into", "an", "object", "with", "specified", "field", "keys", "as", "object", "keys", "." ]
4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3
https://github.com/fnogatz/node-swtparser/blob/4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3/build-structure.js#L43-L89
37,999
elb-min-uhh/markdown-elearnjs
assets/elearnjs/extensions/clickimage/assets/js/clickimage.js
initializeClickimages
function initializeClickimages() { var elements = document.querySelectorAll('[data-pins]'); for(var i = 0; i < elements.length; i++) { /* try/catch so it continues with the next element without breaking out of the loop, when any syntax error occurs. */ try { clickimagePins(elements[i]); } catch(err) { console.error(err); } } }
javascript
function initializeClickimages() { var elements = document.querySelectorAll('[data-pins]'); for(var i = 0; i < elements.length; i++) { /* try/catch so it continues with the next element without breaking out of the loop, when any syntax error occurs. */ try { clickimagePins(elements[i]); } catch(err) { console.error(err); } } }
[ "function", "initializeClickimages", "(", ")", "{", "var", "elements", "=", "document", ".", "querySelectorAll", "(", "'[data-pins]'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "i", "++", ")", "{", "/*\n try/catch so it continues with the next element without breaking\n out of the loop, when any syntax error occurs.\n */", "try", "{", "clickimagePins", "(", "elements", "[", "i", "]", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "error", "(", "err", ")", ";", "}", "}", "}" ]
Initializes all Clickimages. Clickimages are declared by the attribute `pins`.
[ "Initializes", "all", "Clickimages", ".", "Clickimages", "are", "declared", "by", "the", "attribute", "pins", "." ]
a09bcc497c3c50dd565b7f440fa1f7b62074d679
https://github.com/elb-min-uhh/markdown-elearnjs/blob/a09bcc497c3c50dd565b7f440fa1f7b62074d679/assets/elearnjs/extensions/clickimage/assets/js/clickimage.js#L233-L247