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
31,800
oskariorg/rpc-client
OskariRPC.js
function (name) { /** * Any of the allowed functions. Arguments are shifted if params is a function so there's no need to give an empty params array. * @param {Array} params optional array of parameters for the function. Treated as success callback if a function instead. * @param {function} success Callback function * @param {function} error Error handler */ RPC_API[name] = function (params, success, error) { if (name === 'getInfo') { // hide params from external getInfo calls error = success; success = params; params = [rpcClientVersion]; } if (typeof params === 'function') { error = success; success = params; params = []; } channel.call({ method: name, params: params, success: success, error: error || defaultErrorHandler }); }; }
javascript
function (name) { /** * Any of the allowed functions. Arguments are shifted if params is a function so there's no need to give an empty params array. * @param {Array} params optional array of parameters for the function. Treated as success callback if a function instead. * @param {function} success Callback function * @param {function} error Error handler */ RPC_API[name] = function (params, success, error) { if (name === 'getInfo') { // hide params from external getInfo calls error = success; success = params; params = [rpcClientVersion]; } if (typeof params === 'function') { error = success; success = params; params = []; } channel.call({ method: name, params: params, success: success, error: error || defaultErrorHandler }); }; }
[ "function", "(", "name", ")", "{", "/**\n * Any of the allowed functions. Arguments are shifted if params is a function so there's no need to give an empty params array.\n * @param {Array} params optional array of parameters for the function. Treated as success callback if ...
connect and setup allowed functions
[ "connect", "and", "setup", "allowed", "functions" ]
14a5fc2a5480dffbc35cc1e5b65e09edfb19da4c
https://github.com/oskariorg/rpc-client/blob/14a5fc2a5480dffbc35cc1e5b65e09edfb19da4c/OskariRPC.js#L200-L228
31,801
jkroso/abs-svg-path
index.js
absolutize
function absolutize(path){ var startX = 0 var startY = 0 var x = 0 var y = 0 return path.map(function(seg){ seg = seg.slice() var type = seg[0] var command = type.toUpperCase() // is relative if (type != command) { seg[0] = command switch (type) { case 'a': seg[6] += x seg[7] += y break case 'v': seg[1] += y break case 'h': seg[1] += x break default: for (var i = 1; i < seg.length;) { seg[i++] += x seg[i++] += y } } } // update cursor state switch (command) { case 'Z': x = startX y = startY break case 'H': x = seg[1] break case 'V': y = seg[1] break case 'M': x = startX = seg[1] y = startY = seg[2] break default: x = seg[seg.length - 2] y = seg[seg.length - 1] } return seg }) }
javascript
function absolutize(path){ var startX = 0 var startY = 0 var x = 0 var y = 0 return path.map(function(seg){ seg = seg.slice() var type = seg[0] var command = type.toUpperCase() // is relative if (type != command) { seg[0] = command switch (type) { case 'a': seg[6] += x seg[7] += y break case 'v': seg[1] += y break case 'h': seg[1] += x break default: for (var i = 1; i < seg.length;) { seg[i++] += x seg[i++] += y } } } // update cursor state switch (command) { case 'Z': x = startX y = startY break case 'H': x = seg[1] break case 'V': y = seg[1] break case 'M': x = startX = seg[1] y = startY = seg[2] break default: x = seg[seg.length - 2] y = seg[seg.length - 1] } return seg }) }
[ "function", "absolutize", "(", "path", ")", "{", "var", "startX", "=", "0", "var", "startY", "=", "0", "var", "x", "=", "0", "var", "y", "=", "0", "return", "path", ".", "map", "(", "function", "(", "seg", ")", "{", "seg", "=", "seg", ".", "sli...
redefine `path` with absolute coordinates @param {Array} path @return {Array}
[ "redefine", "path", "with", "absolute", "coordinates" ]
f0f57c97b12cdc4fc1d94798256fba357394e40a
https://github.com/jkroso/abs-svg-path/blob/f0f57c97b12cdc4fc1d94798256fba357394e40a/index.js#L11-L67
31,802
timwis/vizwit
src/scripts/views/basechart.js
function (config) { var guide = config.categoryAxis.guides[0] var filter = this.filteredCollection.getFilters(this.filteredCollection.getTriggerField()) if (filter) { if (config.categoryAxis.parseDates) { guide.date = filter.expression.value[0].value guide.toDate = filter.expression.value[1].value } else { guide.category = guide.toCategory = filter.expression.value } } else { if (guide.date) delete guide.date if (guide.toDate) delete guide.toDate if (guide.category) delete guide.category } }
javascript
function (config) { var guide = config.categoryAxis.guides[0] var filter = this.filteredCollection.getFilters(this.filteredCollection.getTriggerField()) if (filter) { if (config.categoryAxis.parseDates) { guide.date = filter.expression.value[0].value guide.toDate = filter.expression.value[1].value } else { guide.category = guide.toCategory = filter.expression.value } } else { if (guide.date) delete guide.date if (guide.toDate) delete guide.toDate if (guide.category) delete guide.category } }
[ "function", "(", "config", ")", "{", "var", "guide", "=", "config", ".", "categoryAxis", ".", "guides", "[", "0", "]", "var", "filter", "=", "this", ".", "filteredCollection", ".", "getFilters", "(", "this", ".", "filteredCollection", ".", "getTriggerField",...
Show guide on selected item or remove it if nothing's selected
[ "Show", "guide", "on", "selected", "item", "or", "remove", "it", "if", "nothing", "s", "selected" ]
cca5d4e8fb522e8359696c15d032074374bd6c5e
https://github.com/timwis/vizwit/blob/cca5d4e8fb522e8359696c15d032074374bd6c5e/src/scripts/views/basechart.js#L88-L103
31,803
timwis/vizwit
src/scripts/views/datetime.js
function (e) { // console.log('Filtered by', (new Date(e.start)).toISOString(), (new Date(e.end)).toISOString()) var field = this.collection.getTriggerField() var start = new Date(e.start) var startIso = trimLastCharacter(start.toISOString()) var startFriendly = start.toLocaleDateString() var end = new Date(e.end) var endIso = trimLastCharacter(end.toISOString()) var endFriendly = end.toLocaleDateString() // Trigger the global event handler with this filter this.vent.trigger(this.collection.getDataset() + '.filter', { field: field, expression: { type: 'and', value: [ { type: '>=', value: startIso, label: startFriendly }, { type: '<=', value: endIso, label: endFriendly } ] } }) }
javascript
function (e) { // console.log('Filtered by', (new Date(e.start)).toISOString(), (new Date(e.end)).toISOString()) var field = this.collection.getTriggerField() var start = new Date(e.start) var startIso = trimLastCharacter(start.toISOString()) var startFriendly = start.toLocaleDateString() var end = new Date(e.end) var endIso = trimLastCharacter(end.toISOString()) var endFriendly = end.toLocaleDateString() // Trigger the global event handler with this filter this.vent.trigger(this.collection.getDataset() + '.filter', { field: field, expression: { type: 'and', value: [ { type: '>=', value: startIso, label: startFriendly }, { type: '<=', value: endIso, label: endFriendly } ] } }) }
[ "function", "(", "e", ")", "{", "// console.log('Filtered by', (new Date(e.start)).toISOString(), (new Date(e.end)).toISOString())", "var", "field", "=", "this", ".", "collection", ".", "getTriggerField", "(", ")", "var", "start", "=", "new", "Date", "(", "e", ".", "s...
When the user clicks on a bar in this chart
[ "When", "the", "user", "clicks", "on", "a", "bar", "in", "this", "chart" ]
cca5d4e8fb522e8359696c15d032074374bd6c5e
https://github.com/timwis/vizwit/blob/cca5d4e8fb522e8359696c15d032074374bd6c5e/src/scripts/views/datetime.js#L102-L133
31,804
timwis/vizwit
src/scripts/views/table.js
function (tableState, dataTablesCallback, dataTablesSettings) { this.collection.setSearch(tableState.search.value ? tableState.search.value : null) this.collection.unsetRecordCount() this.renderFilters() // Get record count first because it needs to be passed into the collection.fetch callback this.collection.getRecordCount().then(_.bind(function (recordCount) { if (!this.recordsTotal) { this.recordsTotal = recordCount } var recordsTotal = this.recordsTotal // for use in callback below this.collection.setOffset(tableState.start || 0) this.collection.setLimit(tableState.length || 25) if (tableState.order.length) { this.collection.setOrder(tableState.columns[tableState.order[0].column].data + ' ' + tableState.order[0].dir) } this.collection.fetch({ success: function (collection, response, options) { dataTablesCallback({ data: collection.toJSON(), recordsTotal: recordsTotal, recordsFiltered: recordCount }) } }) }, this)) }
javascript
function (tableState, dataTablesCallback, dataTablesSettings) { this.collection.setSearch(tableState.search.value ? tableState.search.value : null) this.collection.unsetRecordCount() this.renderFilters() // Get record count first because it needs to be passed into the collection.fetch callback this.collection.getRecordCount().then(_.bind(function (recordCount) { if (!this.recordsTotal) { this.recordsTotal = recordCount } var recordsTotal = this.recordsTotal // for use in callback below this.collection.setOffset(tableState.start || 0) this.collection.setLimit(tableState.length || 25) if (tableState.order.length) { this.collection.setOrder(tableState.columns[tableState.order[0].column].data + ' ' + tableState.order[0].dir) } this.collection.fetch({ success: function (collection, response, options) { dataTablesCallback({ data: collection.toJSON(), recordsTotal: recordsTotal, recordsFiltered: recordCount }) } }) }, this)) }
[ "function", "(", "tableState", ",", "dataTablesCallback", ",", "dataTablesSettings", ")", "{", "this", ".", "collection", ".", "setSearch", "(", "tableState", ".", "search", ".", "value", "?", "tableState", ".", "search", ".", "value", ":", "null", ")", "thi...
Adjust collection using table state, then pass off to collection.fetch with datatables callback
[ "Adjust", "collection", "using", "table", "state", "then", "pass", "off", "to", "collection", ".", "fetch", "with", "datatables", "callback" ]
cca5d4e8fb522e8359696c15d032074374bd6c5e
https://github.com/timwis/vizwit/blob/cca5d4e8fb522e8359696c15d032074374bd6c5e/src/scripts/views/table.js#L74-L103
31,805
timwis/vizwit
src/scripts/views/table.js
function (data) { this.collection.setFilter(data) this.collection.unsetRecordCount() this.table.ajax.reload() this.renderFilters() }
javascript
function (data) { this.collection.setFilter(data) this.collection.unsetRecordCount() this.table.ajax.reload() this.renderFilters() }
[ "function", "(", "data", ")", "{", "this", ".", "collection", ".", "setFilter", "(", "data", ")", "this", ".", "collection", ".", "unsetRecordCount", "(", ")", "this", ".", "table", ".", "ajax", ".", "reload", "(", ")", "this", ".", "renderFilters", "(...
When another chart is filtered, filter this collection
[ "When", "another", "chart", "is", "filtered", "filter", "this", "collection" ]
cca5d4e8fb522e8359696c15d032074374bd6c5e
https://github.com/timwis/vizwit/blob/cca5d4e8fb522e8359696c15d032074374bd6c5e/src/scripts/views/table.js#L111-L116
31,806
timwis/vizwit
src/scripts/views/bar.js
function (e) { if (e.index == null) { this.hovering = null } else { this.hovering = this.chart.categoryAxis.data[e.index] } }
javascript
function (e) { if (e.index == null) { this.hovering = null } else { this.hovering = this.chart.categoryAxis.data[e.index] } }
[ "function", "(", "e", ")", "{", "if", "(", "e", ".", "index", "==", "null", ")", "{", "this", ".", "hovering", "=", "null", "}", "else", "{", "this", ".", "hovering", "=", "this", ".", "chart", ".", "categoryAxis", ".", "data", "[", "e", ".", "...
Keep track of which column the cursor is hovered over
[ "Keep", "track", "of", "which", "column", "the", "cursor", "is", "hovered", "over" ]
cca5d4e8fb522e8359696c15d032074374bd6c5e
https://github.com/timwis/vizwit/blob/cca5d4e8fb522e8359696c15d032074374bd6c5e/src/scripts/views/bar.js#L155-L161
31,807
timwis/vizwit
src/scripts/views/pie.js
function (data) { // Add the filter to the filtered collection and fetch it with the filter this.filteredCollection.setFilter(data) // Only re-fetch if it's another chart (since this view doesn't filter itself) if (data.field !== this.filteredCollection.getTriggerField()) { this.filteredCollection.fetch() // If it's this chart and the filter is being removed, re-render the chart } else if (!data.expression) { this.render() } this.renderFilters() }
javascript
function (data) { // Add the filter to the filtered collection and fetch it with the filter this.filteredCollection.setFilter(data) // Only re-fetch if it's another chart (since this view doesn't filter itself) if (data.field !== this.filteredCollection.getTriggerField()) { this.filteredCollection.fetch() // If it's this chart and the filter is being removed, re-render the chart } else if (!data.expression) { this.render() } this.renderFilters() }
[ "function", "(", "data", ")", "{", "// Add the filter to the filtered collection and fetch it with the filter", "this", ".", "filteredCollection", ".", "setFilter", "(", "data", ")", "// Only re-fetch if it's another chart (since this view doesn't filter itself)", "if", "(", "data"...
When a chart has been filtered
[ "When", "a", "chart", "has", "been", "filtered" ]
cca5d4e8fb522e8359696c15d032074374bd6c5e
https://github.com/timwis/vizwit/blob/cca5d4e8fb522e8359696c15d032074374bd6c5e/src/scripts/views/pie.js#L135-L148
31,808
timwis/vizwit
src/scripts/views/choropleth.js
function () { // Create hash table for easy reference var collectionValues = hashTable(this.collection.toJSON(), 'label', 'value') var filteredCollectionValues = hashTable(this.filteredCollection.toJSON(), 'label', 'value') // Add value from hash tables to geojson properties var idAttribute = this.boundaries.idAttribute var filtered = this.filteredCollection.getFilters().length this.boundaries.forEach(function (item) { var properties = item.get('properties') properties.value = collectionValues[properties[idAttribute]] if (filtered) { properties.filteredValue = filteredCollectionValues[properties[idAttribute]] || 0 } item.set('properties', properties) }, this) }
javascript
function () { // Create hash table for easy reference var collectionValues = hashTable(this.collection.toJSON(), 'label', 'value') var filteredCollectionValues = hashTable(this.filteredCollection.toJSON(), 'label', 'value') // Add value from hash tables to geojson properties var idAttribute = this.boundaries.idAttribute var filtered = this.filteredCollection.getFilters().length this.boundaries.forEach(function (item) { var properties = item.get('properties') properties.value = collectionValues[properties[idAttribute]] if (filtered) { properties.filteredValue = filteredCollectionValues[properties[idAttribute]] || 0 } item.set('properties', properties) }, this) }
[ "function", "(", ")", "{", "// Create hash table for easy reference", "var", "collectionValues", "=", "hashTable", "(", "this", ".", "collection", ".", "toJSON", "(", ")", ",", "'label'", ",", "'value'", ")", "var", "filteredCollectionValues", "=", "hashTable", "(...
Loop through features, find the matching dataset record, and put the specific field into the feature Done via reference
[ "Loop", "through", "features", "find", "the", "matching", "dataset", "record", "and", "put", "the", "specific", "field", "into", "the", "feature", "Done", "via", "reference" ]
cca5d4e8fb522e8359696c15d032074374bd6c5e
https://github.com/timwis/vizwit/blob/cca5d4e8fb522e8359696c15d032074374bd6c5e/src/scripts/views/choropleth.js#L102-L118
31,809
timwis/vizwit
gulpfile.js
scripts
function scripts (src, dest, watch) { var bundleOpts = _.extend({}, watchify.args) if (watch) bundleOpts.debug = true var bundle = browserify(src, bundleOpts) if (watch) { bundle = watchify(bundle) bundle.on('update', function () { compileBundle(bundle, dest) }) // when a dependency changes, recompile bundle.on('log', gutil.log) // output build logs to terminal } else { bundle.transform({ global: true }, 'uglifyify') } return compileBundle(bundle, dest) }
javascript
function scripts (src, dest, watch) { var bundleOpts = _.extend({}, watchify.args) if (watch) bundleOpts.debug = true var bundle = browserify(src, bundleOpts) if (watch) { bundle = watchify(bundle) bundle.on('update', function () { compileBundle(bundle, dest) }) // when a dependency changes, recompile bundle.on('log', gutil.log) // output build logs to terminal } else { bundle.transform({ global: true }, 'uglifyify') } return compileBundle(bundle, dest) }
[ "function", "scripts", "(", "src", ",", "dest", ",", "watch", ")", "{", "var", "bundleOpts", "=", "_", ".", "extend", "(", "{", "}", ",", "watchify", ".", "args", ")", "if", "(", "watch", ")", "bundleOpts", ".", "debug", "=", "true", "var", "bundle...
Build scripts and optionally watch for changes
[ "Build", "scripts", "and", "optionally", "watch", "for", "changes" ]
cca5d4e8fb522e8359696c15d032074374bd6c5e
https://github.com/timwis/vizwit/blob/cca5d4e8fb522e8359696c15d032074374bd6c5e/gulpfile.js#L69-L85
31,810
intervolga/optimize-cssnano-plugin
index.js
OptimizeCssnanoPlugin
function OptimizeCssnanoPlugin(options) { this.options = Object.assign({ sourceMap: false, cssnanoOptions: { preset: 'default', }, }, options); if (this.options.sourceMap) { this.options.sourceMap = Object.assign( {inline: false}, this.options.sourceMap || {}); } }
javascript
function OptimizeCssnanoPlugin(options) { this.options = Object.assign({ sourceMap: false, cssnanoOptions: { preset: 'default', }, }, options); if (this.options.sourceMap) { this.options.sourceMap = Object.assign( {inline: false}, this.options.sourceMap || {}); } }
[ "function", "OptimizeCssnanoPlugin", "(", "options", ")", "{", "this", ".", "options", "=", "Object", ".", "assign", "(", "{", "sourceMap", ":", "false", ",", "cssnanoOptions", ":", "{", "preset", ":", "'default'", ",", "}", ",", "}", ",", "options", ")"...
Optimize cssnano plugin @param {Object} options
[ "Optimize", "cssnano", "plugin" ]
123de8b2212dbe5335be1a5c49e981ec8c2e1268
https://github.com/intervolga/optimize-cssnano-plugin/blob/123de8b2212dbe5335be1a5c49e981ec8c2e1268/index.js#L9-L22
31,811
papnkukn/qrcode-svg
app.js
help
function help() { console.log("Usage:"); console.log(" qrcode-svg [options] <content>"); console.log(""); console.log("Options:"); console.log(" --help Print this message"); console.log(" --padding [value] Offset in number of modules"); console.log(" --width [px] Image width in pixels"); console.log(" --height [px] Image height in pixels"); console.log(" --color [color] Foreground color, hex or name"); console.log(" --background [color] Background color, hex or name"); console.log(" --ecl [value] Error correction level: L, M, H, Q"); console.log(" -o [file] Output file name"); console.log(" -f Force overwrite"); console.log(" -v Print version number"); console.log(""); console.log("Examples:"); console.log(" qrcode-svg http://github.com"); console.log(" qrcode-svg -f -o hello.svg \"Hello World\""); console.log(" qrcode-svg --padding 2 --width 120 --height 120 \"Little fox...\""); console.log(" qrcode-svg --color blue --background #ececec \"...jumps over\""); }
javascript
function help() { console.log("Usage:"); console.log(" qrcode-svg [options] <content>"); console.log(""); console.log("Options:"); console.log(" --help Print this message"); console.log(" --padding [value] Offset in number of modules"); console.log(" --width [px] Image width in pixels"); console.log(" --height [px] Image height in pixels"); console.log(" --color [color] Foreground color, hex or name"); console.log(" --background [color] Background color, hex or name"); console.log(" --ecl [value] Error correction level: L, M, H, Q"); console.log(" -o [file] Output file name"); console.log(" -f Force overwrite"); console.log(" -v Print version number"); console.log(""); console.log("Examples:"); console.log(" qrcode-svg http://github.com"); console.log(" qrcode-svg -f -o hello.svg \"Hello World\""); console.log(" qrcode-svg --padding 2 --width 120 --height 120 \"Little fox...\""); console.log(" qrcode-svg --color blue --background #ececec \"...jumps over\""); }
[ "function", "help", "(", ")", "{", "console", ".", "log", "(", "\"Usage:\"", ")", ";", "console", ".", "log", "(", "\" qrcode-svg [options] <content>\"", ")", ";", "console", ".", "log", "(", "\"\"", ")", ";", "console", ".", "log", "(", "\"Options:\"", ...
Prints help message
[ "Prints", "help", "message" ]
e48892136b1655fa557d45b521120f482afafd3d
https://github.com/papnkukn/qrcode-svg/blob/e48892136b1655fa557d45b521120f482afafd3d/app.js#L70-L91
31,812
vicapow/react-map-gl-heatmap-overlay
index.js
_getGradientTexture
function _getGradientTexture() { // Only update the texture when the gradient has changed. if (this._prevGradientColors === this.props.gradientColors) { return this._gradientTexture; } var canvas = document.createElement('canvas'); // 512, 10 because these are the same dimensions webgl-heatmap uses for its // built in gradient textures. var width = 512; var height = 10; canvas.width = String(width); canvas.height = String(height); var ctx = canvas.getContext('2d'); var gradient = ctx.createLinearGradient(0, height / 2, width, height / 2); var colors = this.props.gradientColors; colors.forEach(function each(color, index) { var position = index / (colors.size - 1); gradient.addColorStop(position, color); }); ctx.fillStyle = gradient; ctx.fillRect(0, 0, width, height); var image = new window.Image(); image.src = canvas.toDataURL('image/png'); return image; }
javascript
function _getGradientTexture() { // Only update the texture when the gradient has changed. if (this._prevGradientColors === this.props.gradientColors) { return this._gradientTexture; } var canvas = document.createElement('canvas'); // 512, 10 because these are the same dimensions webgl-heatmap uses for its // built in gradient textures. var width = 512; var height = 10; canvas.width = String(width); canvas.height = String(height); var ctx = canvas.getContext('2d'); var gradient = ctx.createLinearGradient(0, height / 2, width, height / 2); var colors = this.props.gradientColors; colors.forEach(function each(color, index) { var position = index / (colors.size - 1); gradient.addColorStop(position, color); }); ctx.fillStyle = gradient; ctx.fillRect(0, 0, width, height); var image = new window.Image(); image.src = canvas.toDataURL('image/png'); return image; }
[ "function", "_getGradientTexture", "(", ")", "{", "// Only update the texture when the gradient has changed.", "if", "(", "this", ".", "_prevGradientColors", "===", "this", ".", "props", ".", "gradientColors", ")", "{", "return", "this", ".", "_gradientTexture", ";", ...
Updates `this._gradientTexture` Image if `props.gradientColors` has changed. @returns {Image} `this._gradientTexture`.
[ "Updates", "this", ".", "_gradientTexture", "Image", "if", "props", ".", "gradientColors", "has", "changed", "." ]
3049506b58c1bbfc6592f2cd211a703d46216924
https://github.com/vicapow/react-map-gl-heatmap-overlay/blob/3049506b58c1bbfc6592f2cd211a703d46216924/index.js#L69-L93
31,813
realmq/realmq-web-sdk
lib/utils/utf8.js
decodeUTF8
function decodeUTF8(bytes) { var s = ''; var i = 0; while (i < bytes.length) { var c = bytes[i++]; if (c > 127) { if (c > 191 && c < 224) { if (i >= bytes.length) throw new Error('UTF-8 decode: incomplete 2-byte sequence'); c = ((c & 31) << 6) | (bytes[i] & 63); } else if (c > 223 && c < 240) { if (i + 1 >= bytes.length) throw new Error('UTF-8 decode: incomplete 3-byte sequence'); c = ((c & 15) << 12) | ((bytes[i] & 63) << 6) | (bytes[++i] & 63); } else if (c > 239 && c < 248) { if (i + 2 >= bytes.length) throw new Error('UTF-8 decode: incomplete 4-byte sequence'); c = ((c & 7) << 18) | ((bytes[i] & 63) << 12) | ((bytes[++i] & 63) << 6) | (bytes[++i] & 63); } else throw new Error( 'UTF-8 decode: unknown multibyte start 0x' + c.toString(16) + ' at index ' + (i - 1) ); ++i; } if (c <= 0xffff) s += String.fromCharCode(c); else if (c <= 0x10ffff) { c -= 0x10000; s += String.fromCharCode((c >> 10) | 0xd800); s += String.fromCharCode((c & 0x3ff) | 0xdc00); } else throw new Error( 'UTF-8 decode: code point 0x' + c.toString(16) + ' exceeds UTF-16 reach' ); } return s; }
javascript
function decodeUTF8(bytes) { var s = ''; var i = 0; while (i < bytes.length) { var c = bytes[i++]; if (c > 127) { if (c > 191 && c < 224) { if (i >= bytes.length) throw new Error('UTF-8 decode: incomplete 2-byte sequence'); c = ((c & 31) << 6) | (bytes[i] & 63); } else if (c > 223 && c < 240) { if (i + 1 >= bytes.length) throw new Error('UTF-8 decode: incomplete 3-byte sequence'); c = ((c & 15) << 12) | ((bytes[i] & 63) << 6) | (bytes[++i] & 63); } else if (c > 239 && c < 248) { if (i + 2 >= bytes.length) throw new Error('UTF-8 decode: incomplete 4-byte sequence'); c = ((c & 7) << 18) | ((bytes[i] & 63) << 12) | ((bytes[++i] & 63) << 6) | (bytes[++i] & 63); } else throw new Error( 'UTF-8 decode: unknown multibyte start 0x' + c.toString(16) + ' at index ' + (i - 1) ); ++i; } if (c <= 0xffff) s += String.fromCharCode(c); else if (c <= 0x10ffff) { c -= 0x10000; s += String.fromCharCode((c >> 10) | 0xd800); s += String.fromCharCode((c & 0x3ff) | 0xdc00); } else throw new Error( 'UTF-8 decode: code point 0x' + c.toString(16) + ' exceeds UTF-16 reach' ); } return s; }
[ "function", "decodeUTF8", "(", "bytes", ")", "{", "var", "s", "=", "''", ";", "var", "i", "=", "0", ";", "while", "(", "i", "<", "bytes", ".", "length", ")", "{", "var", "c", "=", "bytes", "[", "i", "++", "]", ";", "if", "(", "c", ">", "127...
Unmarshals an Uint8Array to string.
[ "Unmarshals", "an", "Uint8Array", "to", "string", "." ]
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/lib/utils/utf8.js#L8-L51
31,814
realmq/realmq-web-sdk
vendor/paho-mqtt.js
function(obj, keys) { for (var key in obj) { if (obj.hasOwnProperty(key)) { if (keys.hasOwnProperty(key)) { if (typeof obj[key] !== keys[key]) throw new Error(format(ERROR.INVALID_TYPE, [typeof obj[key], key])); } else { var errorStr = "Unknown property, " + key + ". Valid properties are:"; for (var validKey in keys) if (keys.hasOwnProperty(validKey)) errorStr = errorStr+" "+validKey; throw new Error(errorStr); } } } }
javascript
function(obj, keys) { for (var key in obj) { if (obj.hasOwnProperty(key)) { if (keys.hasOwnProperty(key)) { if (typeof obj[key] !== keys[key]) throw new Error(format(ERROR.INVALID_TYPE, [typeof obj[key], key])); } else { var errorStr = "Unknown property, " + key + ". Valid properties are:"; for (var validKey in keys) if (keys.hasOwnProperty(validKey)) errorStr = errorStr+" "+validKey; throw new Error(errorStr); } } } }
[ "function", "(", "obj", ",", "keys", ")", "{", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "if", "(", "keys", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "if", "(", ...
Collection of utility methods used to simplify module code and promote the DRY pattern. Validate an object's parameter names to ensure they match a list of expected variables name for this option type. Used to ensure option object passed into the API don't contain erroneous parameters. @param {Object} obj - User options object @param {Object} keys - valid keys and types that may exist in obj. @throws {Error} Invalid option parameter found. @private
[ "Collection", "of", "utility", "methods", "used", "to", "simplify", "module", "code", "and", "promote", "the", "DRY", "pattern", ".", "Validate", "an", "object", "s", "parameter", "names", "to", "ensure", "they", "match", "a", "list", "of", "expected", "vari...
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/vendor/paho-mqtt.js#L143-L158
31,815
realmq/realmq-web-sdk
vendor/paho-mqtt.js
function(client, window, timeoutSeconds, action, args) { this._window = window; if (!timeoutSeconds) timeoutSeconds = 30; var doTimeout = function (action, client, args) { return function () { return action.apply(client, args); }; }; this.timeout = setTimeout(doTimeout(action, client, args), timeoutSeconds * 1000); this.cancel = function() { this._window.clearTimeout(this.timeout); }; }
javascript
function(client, window, timeoutSeconds, action, args) { this._window = window; if (!timeoutSeconds) timeoutSeconds = 30; var doTimeout = function (action, client, args) { return function () { return action.apply(client, args); }; }; this.timeout = setTimeout(doTimeout(action, client, args), timeoutSeconds * 1000); this.cancel = function() { this._window.clearTimeout(this.timeout); }; }
[ "function", "(", "client", ",", "window", ",", "timeoutSeconds", ",", "action", ",", "args", ")", "{", "this", ".", "_window", "=", "window", ";", "if", "(", "!", "timeoutSeconds", ")", "timeoutSeconds", "=", "30", ";", "var", "doTimeout", "=", "function...
Monitor request completion. @ignore
[ "Monitor", "request", "completion", "." ]
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/vendor/paho-mqtt.js#L735-L750
31,816
realmq/realmq-web-sdk
lib/rtm-client.js
function() { var me = this; var connectionOptions = me._connectionOptions; return promised(function(cb) { if (me.isConnected || me.status === 'connecting') { return cb(new Error('Broker client already connected or connecting.')); } if (!me.mqttClient) { var mqttClient = new PahoMQTT.Client( connectionOptions.host, connectionOptions.port, connectionOptions.path, connectionOptions.clientId ); _registerPahoClientEventListeners(me, mqttClient); me.mqttClient = mqttClient; } me.status = 'connecting'; me.emit('connecting'); me.mqttClient.connect( merge(_getPahoCallbacks(cb), { cleanSession: connectionOptions.clean, keepAliveInterval: connectionOptions.keepAliveInterval, reconnect: connectionOptions.reconnect, useSSL: connectionOptions.useSSL }) ); }).then(function(connectResponse) { if (me.enableSubscriptionSyncEvents) { me.initSubscriptionSyncEvents(); } return connectResponse; }); }
javascript
function() { var me = this; var connectionOptions = me._connectionOptions; return promised(function(cb) { if (me.isConnected || me.status === 'connecting') { return cb(new Error('Broker client already connected or connecting.')); } if (!me.mqttClient) { var mqttClient = new PahoMQTT.Client( connectionOptions.host, connectionOptions.port, connectionOptions.path, connectionOptions.clientId ); _registerPahoClientEventListeners(me, mqttClient); me.mqttClient = mqttClient; } me.status = 'connecting'; me.emit('connecting'); me.mqttClient.connect( merge(_getPahoCallbacks(cb), { cleanSession: connectionOptions.clean, keepAliveInterval: connectionOptions.keepAliveInterval, reconnect: connectionOptions.reconnect, useSSL: connectionOptions.useSSL }) ); }).then(function(connectResponse) { if (me.enableSubscriptionSyncEvents) { me.initSubscriptionSyncEvents(); } return connectResponse; }); }
[ "function", "(", ")", "{", "var", "me", "=", "this", ";", "var", "connectionOptions", "=", "me", ".", "_connectionOptions", ";", "return", "promised", "(", "function", "(", "cb", ")", "{", "if", "(", "me", ".", "isConnected", "||", "me", ".", "status",...
Opens a connection to the @return {Promise}
[ "Opens", "a", "connection", "to", "the" ]
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/lib/rtm-client.js#L58-L97
31,817
realmq/realmq-web-sdk
lib/rtm-client.js
function(args) { var mqttClient = this.mqttClient; return promised(function(cb) { mqttClient.subscribe(args.channel, _getPahoCallbacks(cb)); }); }
javascript
function(args) { var mqttClient = this.mqttClient; return promised(function(cb) { mqttClient.subscribe(args.channel, _getPahoCallbacks(cb)); }); }
[ "function", "(", "args", ")", "{", "var", "mqttClient", "=", "this", ".", "mqttClient", ";", "return", "promised", "(", "function", "(", "cb", ")", "{", "mqttClient", ".", "subscribe", "(", "args", ".", "channel", ",", "_getPahoCallbacks", "(", "cb", ")"...
Subscribe to rtm channel. @param {Object} args @param {String} args.channel @return {Promise}
[ "Subscribe", "to", "rtm", "channel", "." ]
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/lib/rtm-client.js#L137-L142
31,818
realmq/realmq-web-sdk
lib/rtm-client.js
function(args) { var mqttClient = this.mqttClient; return promised(function(cb) { mqttClient.unsubscribe(args.channel, _getPahoCallbacks(cb)); }); }
javascript
function(args) { var mqttClient = this.mqttClient; return promised(function(cb) { mqttClient.unsubscribe(args.channel, _getPahoCallbacks(cb)); }); }
[ "function", "(", "args", ")", "{", "var", "mqttClient", "=", "this", ".", "mqttClient", ";", "return", "promised", "(", "function", "(", "cb", ")", "{", "mqttClient", ".", "unsubscribe", "(", "args", ".", "channel", ",", "_getPahoCallbacks", "(", "cb", "...
Unsubscribe from rtm channel. @param {Object} args @param {String} args.channel
[ "Unsubscribe", "from", "rtm", "channel", "." ]
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/lib/rtm-client.js#L150-L155
31,819
realmq/realmq-web-sdk
lib/rtm-client.js
function(event, handler) { return events.on({ listeners: this._listeners, event: event, handler: handler }); }
javascript
function(event, handler) { return events.on({ listeners: this._listeners, event: event, handler: handler }); }
[ "function", "(", "event", ",", "handler", ")", "{", "return", "events", ".", "on", "(", "{", "listeners", ":", "this", ".", "_listeners", ",", "event", ":", "event", ",", "handler", ":", "handler", "}", ")", ";", "}" ]
Register an event handler. @param {String} event @param {Function} handler
[ "Register", "an", "event", "handler", "." ]
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/lib/rtm-client.js#L163-L169
31,820
realmq/realmq-web-sdk
lib/rtm-client.js
function(event, handler) { return events.off({ listeners: this._listeners, event: event, handler: handler }); }
javascript
function(event, handler) { return events.off({ listeners: this._listeners, event: event, handler: handler }); }
[ "function", "(", "event", ",", "handler", ")", "{", "return", "events", ".", "off", "(", "{", "listeners", ":", "this", ".", "_listeners", ",", "event", ":", "event", ",", "handler", ":", "handler", "}", ")", ";", "}" ]
Unregister an event handler @param {String} event @param {Function} handler
[ "Unregister", "an", "event", "handler" ]
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/lib/rtm-client.js#L177-L183
31,821
realmq/realmq-web-sdk
lib/rtm-client.js
function(event, data) { return events.emit({ listeners: this._listeners, event: event, data: data }); }
javascript
function(event, data) { return events.emit({ listeners: this._listeners, event: event, data: data }); }
[ "function", "(", "event", ",", "data", ")", "{", "return", "events", ".", "emit", "(", "{", "listeners", ":", "this", ".", "_listeners", ",", "event", ":", "event", ",", "data", ":", "data", "}", ")", ";", "}" ]
Emit an event. @param event @param data
[ "Emit", "an", "event", "." ]
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/lib/rtm-client.js#L191-L197
31,822
realmq/realmq-web-sdk
lib/features/auto-subscribe.js
autoSubscribe
function autoSubscribe(args) { var rtm = args.rtm; var listSubscriptions = args.listSubscriptions; var filterFn = args.filterFn || _autoSubscribeDefaultFilterFn; var subscriptionLoadLimit = 50; _observeSubscriptionSyncEvents({ rtm: rtm, filterFn: filterFn }); return listSubscriptions({limit: subscriptionLoadLimit}).then(function(list) { return _fetchAllReadSubscriptions({ list: list, loadMore: listSubscriptions, batchSize: subscriptionLoadLimit }).then(function(fetchedSubscriptions) { var subscriptions = Array.prototype.concat.apply( [], fetchedSubscriptions ); return Promise.all(subscriptions.map(filterFn)).then(function( filterResults ) { var promisedSubscriptions = []; filterResults.forEach(function(canSubscribe, subscriptionIndex) { if (canSubscribe) { promisedSubscriptions.push( rtm.subscribe({ channel: subscriptions[subscriptionIndex].channelId }) ); } }); return Promise.all(promisedSubscriptions); }); }); }); }
javascript
function autoSubscribe(args) { var rtm = args.rtm; var listSubscriptions = args.listSubscriptions; var filterFn = args.filterFn || _autoSubscribeDefaultFilterFn; var subscriptionLoadLimit = 50; _observeSubscriptionSyncEvents({ rtm: rtm, filterFn: filterFn }); return listSubscriptions({limit: subscriptionLoadLimit}).then(function(list) { return _fetchAllReadSubscriptions({ list: list, loadMore: listSubscriptions, batchSize: subscriptionLoadLimit }).then(function(fetchedSubscriptions) { var subscriptions = Array.prototype.concat.apply( [], fetchedSubscriptions ); return Promise.all(subscriptions.map(filterFn)).then(function( filterResults ) { var promisedSubscriptions = []; filterResults.forEach(function(canSubscribe, subscriptionIndex) { if (canSubscribe) { promisedSubscriptions.push( rtm.subscribe({ channel: subscriptions[subscriptionIndex].channelId }) ); } }); return Promise.all(promisedSubscriptions); }); }); }); }
[ "function", "autoSubscribe", "(", "args", ")", "{", "var", "rtm", "=", "args", ".", "rtm", ";", "var", "listSubscriptions", "=", "args", ".", "listSubscriptions", ";", "var", "filterFn", "=", "args", ".", "filterFn", "||", "_autoSubscribeDefaultFilterFn", ";",...
Subscribe to all read allowed subscriptions. @param {Object} args @param {RtmClient} args.rtm @param {Function} args.listSubscriptions @param {Function} [args.filterFn] @return {Promise}
[ "Subscribe", "to", "all", "read", "allowed", "subscriptions", "." ]
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/lib/features/auto-subscribe.js#L14-L53
31,823
realmq/realmq-web-sdk
lib/features/auto-subscribe.js
_observeSubscriptionSyncEvents
function _observeSubscriptionSyncEvents(args) { var rtm = args.rtm; var filterFn = args.filterFn; rtm.on('subscription-created', function(subscription) { if (subscription.allowRead !== true) return; filterFn(subscription).then(function(ok) { if (ok) { rtm.subscribe({channel: subscription.channelId}); } }); }); rtm.on('subscription-deleted', function(subscription) { rtm.unsubscribe({channel: subscription.channelId}); }); rtm.on('subscription-updated', function(subscription) { if (subscription.allowRead === false) { return rtm.unsubscribe({channel: subscription.channelId}); } filterFn(subscription).then(function(ok) { if (ok) { rtm.subscribe({channel: subscription.channelId}); } }); }); }
javascript
function _observeSubscriptionSyncEvents(args) { var rtm = args.rtm; var filterFn = args.filterFn; rtm.on('subscription-created', function(subscription) { if (subscription.allowRead !== true) return; filterFn(subscription).then(function(ok) { if (ok) { rtm.subscribe({channel: subscription.channelId}); } }); }); rtm.on('subscription-deleted', function(subscription) { rtm.unsubscribe({channel: subscription.channelId}); }); rtm.on('subscription-updated', function(subscription) { if (subscription.allowRead === false) { return rtm.unsubscribe({channel: subscription.channelId}); } filterFn(subscription).then(function(ok) { if (ok) { rtm.subscribe({channel: subscription.channelId}); } }); }); }
[ "function", "_observeSubscriptionSyncEvents", "(", "args", ")", "{", "var", "rtm", "=", "args", ".", "rtm", ";", "var", "filterFn", "=", "args", ".", "filterFn", ";", "rtm", ".", "on", "(", "'subscription-created'", ",", "function", "(", "subscription", ")",...
Register event listeners for keeping subscriptions in sync. @param {Object} args @param {RtmClient} args.rtm @param {Function} args.filterFn @private
[ "Register", "event", "listeners", "for", "keeping", "subscriptions", "in", "sync", "." ]
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/lib/features/auto-subscribe.js#L102-L130
31,824
realmq/realmq-web-sdk
lib/errors/api-error.js
createApiError
function createApiError(options) { return { name: options.name || 'ApiError', message: options.message, status: options.status || 500, details: options.details, code: options.code || options.status || 500, toString: function() { return this.name + ' [' + this.status + '] - ' + this.message; } }; }
javascript
function createApiError(options) { return { name: options.name || 'ApiError', message: options.message, status: options.status || 500, details: options.details, code: options.code || options.status || 500, toString: function() { return this.name + ' [' + this.status + '] - ' + this.message; } }; }
[ "function", "createApiError", "(", "options", ")", "{", "return", "{", "name", ":", "options", ".", "name", "||", "'ApiError'", ",", "message", ":", "options", ".", "message", ",", "status", ":", "options", ".", "status", "||", "500", ",", "details", ":"...
Constructs a generalized api error object. @param options.message @param options.code @param options.details @param options.status @param options.name @return {{name: string, status: number, code: *|number, details, toString(): string}}
[ "Constructs", "a", "generalized", "api", "error", "object", "." ]
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/lib/errors/api-error.js#L13-L25
31,825
realmq/realmq-web-sdk
lib/api-client.js
function(args) { var baseUrl = this.baseUrl + this.basePath; var authToken = this.authToken; var qs = this._buildQueryString(args.params); return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (req.readyState === 4) { try { var response = JSON.parse(req.responseText); var status = req.status; if (status >= 200 && status < 400) { return resolve( addShadowProperty({ target: response, property: 'httpRequest', value: req }) ); } return reject( createApiError( merge(response, { status: status, httpRequest: req }) ) ); } catch (err) { reject(err); } } }; req.open(args.method, baseUrl + args.path + qs, true); req.setRequestHeader('Authorization', 'Bearer ' + authToken); req.setRequestHeader('Accept', 'application/json'); req.setRequestHeader('Content-type', 'application/json; charset=utf-8'); req.send(args.payload ? JSON.stringify(args.payload) : null); }); }
javascript
function(args) { var baseUrl = this.baseUrl + this.basePath; var authToken = this.authToken; var qs = this._buildQueryString(args.params); return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (req.readyState === 4) { try { var response = JSON.parse(req.responseText); var status = req.status; if (status >= 200 && status < 400) { return resolve( addShadowProperty({ target: response, property: 'httpRequest', value: req }) ); } return reject( createApiError( merge(response, { status: status, httpRequest: req }) ) ); } catch (err) { reject(err); } } }; req.open(args.method, baseUrl + args.path + qs, true); req.setRequestHeader('Authorization', 'Bearer ' + authToken); req.setRequestHeader('Accept', 'application/json'); req.setRequestHeader('Content-type', 'application/json; charset=utf-8'); req.send(args.payload ? JSON.stringify(args.payload) : null); }); }
[ "function", "(", "args", ")", "{", "var", "baseUrl", "=", "this", ".", "baseUrl", "+", "this", ".", "basePath", ";", "var", "authToken", "=", "this", ".", "authToken", ";", "var", "qs", "=", "this", ".", "_buildQueryString", "(", "args", ".", "params",...
Generic request method. @param args.method @param args.path @returns {Promise} @private
[ "Generic", "request", "method", "." ]
d9ef1b85bf4798beed1988f2e78ed04d862c19ef
https://github.com/realmq/realmq-web-sdk/blob/d9ef1b85bf4798beed1988f2e78ed04d862c19ef/lib/api-client.js#L51-L95
31,826
CHENXCHEN/hexo-renderer-markdown-it-plus
lib/renderer.js
checkValue
function checkValue(config, res, key, trueVal, falseVal) { res[key] = (config[key] == true || config[key] == undefined || config[key] == null) ? trueVal: falseVal; }
javascript
function checkValue(config, res, key, trueVal, falseVal) { res[key] = (config[key] == true || config[key] == undefined || config[key] == null) ? trueVal: falseVal; }
[ "function", "checkValue", "(", "config", ",", "res", ",", "key", ",", "trueVal", ",", "falseVal", ")", "{", "res", "[", "key", "]", "=", "(", "config", "[", "key", "]", "==", "true", "||", "config", "[", "key", "]", "==", "undefined", "||", "config...
General Default markdown-it config. @param {Object} config configuration @param {Object} res configuration @param {String} key the key of config @param {String} trueVal the val of config[key] == true @param {String} falseVal the val of config[key] == false @return {null}
[ "General", "Default", "markdown", "-", "it", "config", "." ]
f2dd1b25738992efc391ba9da398a9c6a7efb105
https://github.com/CHENXCHEN/hexo-renderer-markdown-it-plus/blob/f2dd1b25738992efc391ba9da398a9c6a7efb105/lib/renderer.js#L41-L43
31,827
CHENXCHEN/hexo-renderer-markdown-it-plus
lib/renderer.js
checkPlugins
function checkPlugins(pugs) { var def_pugs_obj = {}; for(var i = 0;i < def_pugs_lst.length;i++) def_pugs_obj[def_pugs_lst[i]] = {'name': def_pugs_lst[i], 'enable': true}; var _t = []; for(var i = 0;i < pugs.length;i++) { if(!(pugs[i] instanceof Object) || !(pugs[i].plugin instanceof Object)) continue; var pug_name = pugs[i].plugin.name; if(!pug_name) continue; if(pugs[i].plugin.enable == null || pugs[i].plugin.enable == undefined || pugs[i].plugin.enable != true) pugs[i].plugin.enable = false; if(def_pugs_obj[pug_name]) { def_pugs_obj[pug_name] = pugs[i].plugin; } else _t.push(pugs[i].plugin); } for(var i = def_pugs_lst.length - 1;i >= 0;i--) { _t.unshift(def_pugs_obj[def_pugs_lst[i]]); } return _t; }
javascript
function checkPlugins(pugs) { var def_pugs_obj = {}; for(var i = 0;i < def_pugs_lst.length;i++) def_pugs_obj[def_pugs_lst[i]] = {'name': def_pugs_lst[i], 'enable': true}; var _t = []; for(var i = 0;i < pugs.length;i++) { if(!(pugs[i] instanceof Object) || !(pugs[i].plugin instanceof Object)) continue; var pug_name = pugs[i].plugin.name; if(!pug_name) continue; if(pugs[i].plugin.enable == null || pugs[i].plugin.enable == undefined || pugs[i].plugin.enable != true) pugs[i].plugin.enable = false; if(def_pugs_obj[pug_name]) { def_pugs_obj[pug_name] = pugs[i].plugin; } else _t.push(pugs[i].plugin); } for(var i = def_pugs_lst.length - 1;i >= 0;i--) { _t.unshift(def_pugs_obj[def_pugs_lst[i]]); } return _t; }
[ "function", "checkPlugins", "(", "pugs", ")", "{", "var", "def_pugs_obj", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "def_pugs_lst", ".", "length", ";", "i", "++", ")", "def_pugs_obj", "[", "def_pugs_lst", "[", "i", "]", "...
General default plugin config @param {List} pugs plugin List. @return {List} plugin List.
[ "General", "default", "plugin", "config" ]
f2dd1b25738992efc391ba9da398a9c6a7efb105
https://github.com/CHENXCHEN/hexo-renderer-markdown-it-plus/blob/f2dd1b25738992efc391ba9da398a9c6a7efb105/lib/renderer.js#L80-L101
31,828
canjs/can-validate-legacy
map/validate/validate.js
function (behavior, attr, define) { var prop; var defaultProp; if (define) { prop = define[attr]; defaultProp = define["*"]; if (prop && prop[behavior] !== undefined) { return prop[behavior]; } else { if (defaultProp && defaultProp[behavior] !== undefined) { return defaultProp[behavior]; } } } }
javascript
function (behavior, attr, define) { var prop; var defaultProp; if (define) { prop = define[attr]; defaultProp = define["*"]; if (prop && prop[behavior] !== undefined) { return prop[behavior]; } else { if (defaultProp && defaultProp[behavior] !== undefined) { return defaultProp[behavior]; } } } }
[ "function", "(", "behavior", ",", "attr", ",", "define", ")", "{", "var", "prop", ";", "var", "defaultProp", ";", "if", "(", "define", ")", "{", "prop", "=", "define", "[", "attr", "]", ";", "defaultProp", "=", "define", "[", "\"*\"", "]", ";", "if...
Gets properties from the map"s define property.
[ "Gets", "properties", "from", "the", "map", "s", "define", "property", "." ]
a4a9919e7b1a9e7060331a3e2633a786ae53c65f
https://github.com/canjs/can-validate-legacy/blob/a4a9919e7b1a9e7060331a3e2633a786ae53c65f/map/validate/validate.js#L50-L66
31,829
IjzerenHein/node-web-bluetooth
src/utils.js
fromNobleUuid
function fromNobleUuid(uuid) { if (uuid.length !== 32) return uuid; return ( uuid.substring(0, 8) + '-' + uuid.substring(8, 12) + '-' + uuid.substring(12, 16) + '-' + uuid.substring(16, 20) + '-' + uuid.substring(20) ); }
javascript
function fromNobleUuid(uuid) { if (uuid.length !== 32) return uuid; return ( uuid.substring(0, 8) + '-' + uuid.substring(8, 12) + '-' + uuid.substring(12, 16) + '-' + uuid.substring(16, 20) + '-' + uuid.substring(20) ); }
[ "function", "fromNobleUuid", "(", "uuid", ")", "{", "if", "(", "uuid", ".", "length", "!==", "32", ")", "return", "uuid", ";", "return", "(", "uuid", ".", "substring", "(", "0", ",", "8", ")", "+", "'-'", "+", "uuid", ".", "substring", "(", "8", ...
00000001-1212-efde-1523-785feabcd124
[ "00000001", "-", "1212", "-", "efde", "-", "1523", "-", "785feabcd124" ]
6f9f40132473395b6fadb3c6365544e9f2251117
https://github.com/IjzerenHein/node-web-bluetooth/blob/6f9f40132473395b6fadb3c6365544e9f2251117/src/utils.js#L61-L74
31,830
thlorenz/v8-flags
scripts/preinstall.js
removeComplete
function removeComplete(regex, lines, start) { var matches = lines[start].match(regex); var i = 0; var s = lines[start]; matches = s.match(regex); while (!matches) { i++; if ((start + i) > lines.length) return; s += lines[start + i]; matches = s.match(regex); } lines.splice(start, i + 1); }
javascript
function removeComplete(regex, lines, start) { var matches = lines[start].match(regex); var i = 0; var s = lines[start]; matches = s.match(regex); while (!matches) { i++; if ((start + i) > lines.length) return; s += lines[start + i]; matches = s.match(regex); } lines.splice(start, i + 1); }
[ "function", "removeComplete", "(", "regex", ",", "lines", ",", "start", ")", "{", "var", "matches", "=", "lines", "[", "start", "]", ".", "match", "(", "regex", ")", ";", "var", "i", "=", "0", ";", "var", "s", "=", "lines", "[", "start", "]", ";"...
some calls stretch across multiple lines, so we need to ensure to remove them completely
[ "some", "calls", "stretch", "across", "multiple", "lines", "so", "we", "need", "to", "ensure", "to", "remove", "them", "completely" ]
ac622e813cdb3716e3f3d767d9e7da5220556a6f
https://github.com/thlorenz/v8-flags/blob/ac622e813cdb3716e3f3d767d9e7da5220556a6f/scripts/preinstall.js#L27-L40
31,831
que-etc/intersection-observer-polyfill
src/_IntersectionObserver.js
parseThresholds
function parseThresholds(thresholds = 0) { let result = thresholds; if (!Array.isArray(thresholds)) { result = [thresholds]; } else if (!thresholds.length) { result = [0]; } return result.map(threshold => { // We use Number function instead of parseFloat // to convert boolean values and null to theirs // numeric representation. This is done to act // in the same manner as a native implementation. threshold = Number(threshold); if (!window.isFinite(threshold)) { throw new TypeError('The provided double value is non-finite.'); } else if (threshold < 0 || threshold > 1) { throw new RangeError('Threshold values must be between 0 and 1.'); } return threshold; }).sort(); }
javascript
function parseThresholds(thresholds = 0) { let result = thresholds; if (!Array.isArray(thresholds)) { result = [thresholds]; } else if (!thresholds.length) { result = [0]; } return result.map(threshold => { // We use Number function instead of parseFloat // to convert boolean values and null to theirs // numeric representation. This is done to act // in the same manner as a native implementation. threshold = Number(threshold); if (!window.isFinite(threshold)) { throw new TypeError('The provided double value is non-finite.'); } else if (threshold < 0 || threshold > 1) { throw new RangeError('Threshold values must be between 0 and 1.'); } return threshold; }).sort(); }
[ "function", "parseThresholds", "(", "thresholds", "=", "0", ")", "{", "let", "result", "=", "thresholds", ";", "if", "(", "!", "Array", ".", "isArray", "(", "thresholds", ")", ")", "{", "result", "=", "[", "thresholds", "]", ";", "}", "else", "if", "...
Validates and parses threshold values. Throws an error if one of the thresholds is non-finite or not in range of 0 and 1. @param {(Array<Number>|Number)} [thresholds = 0] @returns {Array<Number>} An array of thresholds in ascending order.
[ "Validates", "and", "parses", "threshold", "values", ".", "Throws", "an", "error", "if", "one", "of", "the", "thresholds", "is", "non", "-", "finite", "or", "not", "in", "range", "of", "0", "and", "1", "." ]
39eae5569fe09ba840d2a4d92de5c0670bc11a71
https://github.com/que-etc/intersection-observer-polyfill/blob/39eae5569fe09ba840d2a4d92de5c0670bc11a71/src/_IntersectionObserver.js#L13-L37
31,832
koenkivits/nesnes
system/apu/index.js
function() { return ( ( (!!this.pulse1.lengthCounter) << 0 ) | ( (!!this.pulse2.lengthCounter) << 1 ) | ( (!!this.triangle.lengthCounter) << 2 ) | ( (!!this.noise.lengthCounter) << 3 ) | ( (!!this.dmc.sampleBytesLeft) << 4 ) ); }
javascript
function() { return ( ( (!!this.pulse1.lengthCounter) << 0 ) | ( (!!this.pulse2.lengthCounter) << 1 ) | ( (!!this.triangle.lengthCounter) << 2 ) | ( (!!this.noise.lengthCounter) << 3 ) | ( (!!this.dmc.sampleBytesLeft) << 4 ) ); }
[ "function", "(", ")", "{", "return", "(", "(", "(", "!", "!", "this", ".", "pulse1", ".", "lengthCounter", ")", "<<", "0", ")", "|", "(", "(", "!", "!", "this", ".", "pulse2", ".", "lengthCounter", ")", "<<", "1", ")", "|", "(", "(", "!", "!"...
Read channel status.
[ "Read", "channel", "status", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/apu/index.js#L53-L61
31,833
koenkivits/nesnes
system/apu/index.js
function( address, value ) { if ( address < 0x4 ) { // pulse 1 registers this.pulse1.writeRegister( address, value ); } else if ( address < 0x8 ) { // pulse 2 registers this.pulse2.writeRegister( address - 0x4, value ); } else if ( address < 0xc ) { // triangle registers this.triangle.writeRegister( address - 0x8, value ); } else if ( address < 0x10 ) { // noise registers this.noise.writeRegister( address - 0xc, value ); } else if ( address < 0x14 ) { // DMC registers this.dmc.writeRegister( address - 0x10, value ); } else if ( address === 0x15 ) { // enabling / disabling channels this.writeStatus( value ); } else if ( address === 0x17 ) { // set framecounter mode this.frameCounterMode = +!!(value & 0x80); this.frameCounterInterrupt = !( value & 0x40 ); this.cycles = 0; // TODO: // If the write occurs during an APU cycle, the effects occur 3 CPU cycles // after the $4017 write cycle, and if the write occurs between APU cycles, // the effects occurs 4 CPU cycles after the write cycle. if ( this.frameCounterMode ) { // Writing to $4017 with bit 7 set will immediately generate a clock for // both the quarter frame and the half frame units, regardless of what // the sequencer is doing. this.doQuarterFrame(); this.doHalfFrame(); } } }
javascript
function( address, value ) { if ( address < 0x4 ) { // pulse 1 registers this.pulse1.writeRegister( address, value ); } else if ( address < 0x8 ) { // pulse 2 registers this.pulse2.writeRegister( address - 0x4, value ); } else if ( address < 0xc ) { // triangle registers this.triangle.writeRegister( address - 0x8, value ); } else if ( address < 0x10 ) { // noise registers this.noise.writeRegister( address - 0xc, value ); } else if ( address < 0x14 ) { // DMC registers this.dmc.writeRegister( address - 0x10, value ); } else if ( address === 0x15 ) { // enabling / disabling channels this.writeStatus( value ); } else if ( address === 0x17 ) { // set framecounter mode this.frameCounterMode = +!!(value & 0x80); this.frameCounterInterrupt = !( value & 0x40 ); this.cycles = 0; // TODO: // If the write occurs during an APU cycle, the effects occur 3 CPU cycles // after the $4017 write cycle, and if the write occurs between APU cycles, // the effects occurs 4 CPU cycles after the write cycle. if ( this.frameCounterMode ) { // Writing to $4017 with bit 7 set will immediately generate a clock for // both the quarter frame and the half frame units, regardless of what // the sequencer is doing. this.doQuarterFrame(); this.doHalfFrame(); } } }
[ "function", "(", "address", ",", "value", ")", "{", "if", "(", "address", "<", "0x4", ")", "{", "// pulse 1 registers", "this", ".", "pulse1", ".", "writeRegister", "(", "address", ",", "value", ")", ";", "}", "else", "if", "(", "address", "<", "0x8", ...
Write to APU registers.
[ "Write", "to", "APU", "registers", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/apu/index.js#L66-L107
31,834
koenkivits/nesnes
system/apu/index.js
function() { switch( this.cycles ) { case 3728: case 7457: case 11186: case 14915: this.doQuarterFrame(); break; } switch( this.cycles ) { case 7457: case 14915: this.doHalfFrame(); break; } if ( this.cycles >= 14915 ) { this.cycles = 0; if( this.frameCounterInterrupt ) { this.system.cpu.requestIRQ(); } } }
javascript
function() { switch( this.cycles ) { case 3728: case 7457: case 11186: case 14915: this.doQuarterFrame(); break; } switch( this.cycles ) { case 7457: case 14915: this.doHalfFrame(); break; } if ( this.cycles >= 14915 ) { this.cycles = 0; if( this.frameCounterInterrupt ) { this.system.cpu.requestIRQ(); } } }
[ "function", "(", ")", "{", "switch", "(", "this", ".", "cycles", ")", "{", "case", "3728", ":", "case", "7457", ":", "case", "11186", ":", "case", "14915", ":", "this", ".", "doQuarterFrame", "(", ")", ";", "break", ";", "}", "switch", "(", "this",...
Tick for framecounter mode 0.
[ "Tick", "for", "framecounter", "mode", "0", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/apu/index.js#L141-L165
31,835
koenkivits/nesnes
system/apu/index.js
function() { var tndOut = 0, // triangle, noise, dmc pulseOut = 0; this.pulse1.doTimer(); this.pulse2.doTimer(); this.triangle.doTimer(); this.noise.doTimer(); this.dmc.doTimer(); if ( this.output.enabled ) { // no need to do calculations if output is disabled if ( this.sampleCounter >= this.sampleCounterMax ) { pulseOut = pulseTable[ this.pulse1.sample + this.pulse2.sample ]; tndOut = tndTable[ 3 * this.triangle.sample + 2 * this.noise.sample + this.dmc.sample ]; this.output.writeSample( pulseOut + tndOut ); this.sampleCounter -= this.sampleCounterMax; } this.sampleCounter += 1; } }
javascript
function() { var tndOut = 0, // triangle, noise, dmc pulseOut = 0; this.pulse1.doTimer(); this.pulse2.doTimer(); this.triangle.doTimer(); this.noise.doTimer(); this.dmc.doTimer(); if ( this.output.enabled ) { // no need to do calculations if output is disabled if ( this.sampleCounter >= this.sampleCounterMax ) { pulseOut = pulseTable[ this.pulse1.sample + this.pulse2.sample ]; tndOut = tndTable[ 3 * this.triangle.sample + 2 * this.noise.sample + this.dmc.sample ]; this.output.writeSample( pulseOut + tndOut ); this.sampleCounter -= this.sampleCounterMax; } this.sampleCounter += 1; } }
[ "function", "(", ")", "{", "var", "tndOut", "=", "0", ",", "// triangle, noise, dmc", "pulseOut", "=", "0", ";", "this", ".", "pulse1", ".", "doTimer", "(", ")", ";", "this", ".", "pulse2", ".", "doTimer", "(", ")", ";", "this", ".", "triangle", ".",...
Update output sample.
[ "Update", "output", "sample", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/apu/index.js#L221-L244
31,836
koenkivits/nesnes
index.js
function( filename, autorun ) { var self = this; utils.readFile( filename, function( data ) { self.initCartridge( data ); if ( typeof autorun === "function" ) { autorun(); } else if ( autorun === true ) { self.run(); } }); }
javascript
function( filename, autorun ) { var self = this; utils.readFile( filename, function( data ) { self.initCartridge( data ); if ( typeof autorun === "function" ) { autorun(); } else if ( autorun === true ) { self.run(); } }); }
[ "function", "(", "filename", ",", "autorun", ")", "{", "var", "self", "=", "this", ";", "utils", ".", "readFile", "(", "filename", ",", "function", "(", "data", ")", "{", "self", ".", "initCartridge", "(", "data", ")", ";", "if", "(", "typeof", "auto...
Load a ROM and optionally run it. @param {string} filename - Path of ROM to run. @param autorun - If true, run ROM when loaded. If a function, call that function.
[ "Load", "a", "ROM", "and", "optionally", "run", "it", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/index.js#L51-L63
31,837
koenkivits/nesnes
index.js
function() { if ( this.interval ) { // once is enough return; } var self = this; this.interval = setInterval( function() { if ( !self.paused) { self.runFrame(); } }, 1000 / 60 ); this.output.video.run(); this.running = true; this.paused = false; }
javascript
function() { if ( this.interval ) { // once is enough return; } var self = this; this.interval = setInterval( function() { if ( !self.paused) { self.runFrame(); } }, 1000 / 60 ); this.output.video.run(); this.running = true; this.paused = false; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "interval", ")", "{", "// once is enough", "return", ";", "}", "var", "self", "=", "this", ";", "this", ".", "interval", "=", "setInterval", "(", "function", "(", ")", "{", "if", "(", "!", "self", ...
Turn on and run emulator.
[ "Turn", "on", "and", "run", "emulator", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/index.js#L68-L85
31,838
koenkivits/nesnes
system/cpu.js
doADC
function doADC( value ) { var t = A + value + flagC; flagV = !!((A ^ t) & (value ^ t) & 0x80) && 1; flagN = !!( t & 0x80 ); flagC = ( t > 255 ); flagZ = !( t & 0xff ); writeA( t & 0xff ); }
javascript
function doADC( value ) { var t = A + value + flagC; flagV = !!((A ^ t) & (value ^ t) & 0x80) && 1; flagN = !!( t & 0x80 ); flagC = ( t > 255 ); flagZ = !( t & 0xff ); writeA( t & 0xff ); }
[ "function", "doADC", "(", "value", ")", "{", "var", "t", "=", "A", "+", "value", "+", "flagC", ";", "flagV", "=", "!", "!", "(", "(", "A", "^", "t", ")", "&", "(", "value", "^", "t", ")", "&", "0x80", ")", "&&", "1", ";", "flagN", "=", "!...
Actually performe add with carry. Useful, as SBC is also a modified add-with-carry.
[ "Actually", "performe", "add", "with", "carry", ".", "Useful", "as", "SBC", "is", "also", "a", "modified", "add", "-", "with", "-", "carry", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cpu.js#L1069-L1078
31,839
koenkivits/nesnes
system/cpu.js
branch
function branch( flag ) { var offset = read(), prevHigh = PC & HIGH, curHigh = 0; if ( flag ) { // branching burns a cycle burn(1); if ( offset & 0x80 ) { offset = -complement( offset ); } PC += offset; curHigh = PC & HIGH; if ( prevHigh !== curHigh ) { // crossing page boundary, burns a cycle burn(1); } } }
javascript
function branch( flag ) { var offset = read(), prevHigh = PC & HIGH, curHigh = 0; if ( flag ) { // branching burns a cycle burn(1); if ( offset & 0x80 ) { offset = -complement( offset ); } PC += offset; curHigh = PC & HIGH; if ( prevHigh !== curHigh ) { // crossing page boundary, burns a cycle burn(1); } } }
[ "function", "branch", "(", "flag", ")", "{", "var", "offset", "=", "read", "(", ")", ",", "prevHigh", "=", "PC", "&", "HIGH", ",", "curHigh", "=", "0", ";", "if", "(", "flag", ")", "{", "// branching burns a cycle", "burn", "(", "1", ")", ";", "if"...
Helper function for all branching operations. @param {boolean} flag - If true, do branch. Otherwise do nothing.
[ "Helper", "function", "for", "all", "branching", "operations", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cpu.js#L1175-L1196
31,840
koenkivits/nesnes
system/cpu.js
xCMP
function xCMP( value ) { var readValue = read(), t = ( value - readValue ) & 0xff; flagN = ( t & 0x80 ) && 1; flagC = +( value >= readValue ); flagZ = +( t === 0 ); }
javascript
function xCMP( value ) { var readValue = read(), t = ( value - readValue ) & 0xff; flagN = ( t & 0x80 ) && 1; flagC = +( value >= readValue ); flagZ = +( t === 0 ); }
[ "function", "xCMP", "(", "value", ")", "{", "var", "readValue", "=", "read", "(", ")", ",", "t", "=", "(", "value", "-", "readValue", ")", "&", "0xff", ";", "flagN", "=", "(", "t", "&", "0x80", ")", "&&", "1", ";", "flagC", "=", "+", "(", "va...
Compare value with memory as if subtraction was carried out. @param {number} value - The value to compare with memory.
[ "Compare", "value", "with", "memory", "as", "if", "subtraction", "was", "carried", "out", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cpu.js#L1296-L1302
31,841
koenkivits/nesnes
system/cpu.js
peekWord
function peekWord( index ) { var low = peek( index ), high = peek( (index + 1) & 0xffff ) << 8; return ( low | high ); }
javascript
function peekWord( index ) { var low = peek( index ), high = peek( (index + 1) & 0xffff ) << 8; return ( low | high ); }
[ "function", "peekWord", "(", "index", ")", "{", "var", "low", "=", "peek", "(", "index", ")", ",", "high", "=", "peek", "(", "(", "index", "+", "1", ")", "&", "0xffff", ")", "<<", "8", ";", "return", "(", "low", "|", "high", ")", ";", "}" ]
Peek a 16-bit word from memory.
[ "Peek", "a", "16", "-", "bit", "word", "from", "memory", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cpu.js#L1677-L1682
31,842
koenkivits/nesnes
system/cpu.js
setFlags
function setFlags() { flagN = !!( P & 0x80 ); flagV = !!( P & 0x40 ); flagB = !!( P & 0x10 ); flagD = !!( P & 0x08 ); flagI = !!( P & 0x04 ); flagZ = !!( P & 0x02 ); flagC = !!( P & 0x01 ); }
javascript
function setFlags() { flagN = !!( P & 0x80 ); flagV = !!( P & 0x40 ); flagB = !!( P & 0x10 ); flagD = !!( P & 0x08 ); flagI = !!( P & 0x04 ); flagZ = !!( P & 0x02 ); flagC = !!( P & 0x01 ); }
[ "function", "setFlags", "(", ")", "{", "flagN", "=", "!", "!", "(", "P", "&", "0x80", ")", ";", "flagV", "=", "!", "!", "(", "P", "&", "0x40", ")", ";", "flagB", "=", "!", "!", "(", "P", "&", "0x10", ")", ";", "flagD", "=", "!", "!", "(",...
Set flags from value in P.
[ "Set", "flags", "from", "value", "in", "P", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cpu.js#L1709-L1717
31,843
koenkivits/nesnes
system/ppu/index.js
function( value ) { this.output.setGrayscale( value & 0x1 ); this.output.setIntensity( value & 0x20, value & 0x40, value & 0x80 ); this.sprites.toggle( value & 0x10 ); this.sprites.toggleLeft( value & 0x4 ); this.background.toggle( value & 0x8 ); this.background.toggleLeft( value & 0x2 ); this.enabled = ( this.sprites.enabled || this.background.enabled ); }
javascript
function( value ) { this.output.setGrayscale( value & 0x1 ); this.output.setIntensity( value & 0x20, value & 0x40, value & 0x80 ); this.sprites.toggle( value & 0x10 ); this.sprites.toggleLeft( value & 0x4 ); this.background.toggle( value & 0x8 ); this.background.toggleLeft( value & 0x2 ); this.enabled = ( this.sprites.enabled || this.background.enabled ); }
[ "function", "(", "value", ")", "{", "this", ".", "output", ".", "setGrayscale", "(", "value", "&", "0x1", ")", ";", "this", ".", "output", ".", "setIntensity", "(", "value", "&", "0x20", ",", "value", "&", "0x40", ",", "value", "&", "0x80", ")", ";...
Set various flags to control video output behavior.
[ "Set", "various", "flags", "to", "control", "video", "output", "behavior", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/ppu/index.js#L64-L75
31,844
koenkivits/nesnes
system/ppu/index.js
function( value ) { var nametableFlag = value & 0x3, incrementFlag = value & 0x4, spriteFlag = value & 0x8, backgroundFlag = value & 0x10, sizeFlag = value & 0x20, nmiFlag = value & 0x80; this.background.setNameTable( nametableFlag ); this.increment = incrementFlag ? 32 : 1; this.sprites.baseTable = spriteFlag ? 0x1000 : 0x0000; this.background.baseTable = backgroundFlag ? 0x1000 : 0x0000; this.sprites.spriteSize = sizeFlag ? 16 : 8; this.generateNMI = !!nmiFlag; // TODO multiple NMIs can occure when writing to PPUCONTROL without reading // PPUSTATUS }
javascript
function( value ) { var nametableFlag = value & 0x3, incrementFlag = value & 0x4, spriteFlag = value & 0x8, backgroundFlag = value & 0x10, sizeFlag = value & 0x20, nmiFlag = value & 0x80; this.background.setNameTable( nametableFlag ); this.increment = incrementFlag ? 32 : 1; this.sprites.baseTable = spriteFlag ? 0x1000 : 0x0000; this.background.baseTable = backgroundFlag ? 0x1000 : 0x0000; this.sprites.spriteSize = sizeFlag ? 16 : 8; this.generateNMI = !!nmiFlag; // TODO multiple NMIs can occure when writing to PPUCONTROL without reading // PPUSTATUS }
[ "function", "(", "value", ")", "{", "var", "nametableFlag", "=", "value", "&", "0x3", ",", "incrementFlag", "=", "value", "&", "0x4", ",", "spriteFlag", "=", "value", "&", "0x8", ",", "backgroundFlag", "=", "value", "&", "0x10", ",", "sizeFlag", "=", "...
Set various flags to control rendering behavior.
[ "Set", "various", "flags", "to", "control", "rendering", "behavior", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/ppu/index.js#L80-L98
31,845
koenkivits/nesnes
system/ppu/index.js
function() { var sprites = this.sprites, background = this.background; if ( this.inRenderScanline ) { if ( this.enabled ) { background.evaluate(); sprites.evaluate(); } if ( this.pixelInRange ) { if ( this.pixelInRange && sprites.sprite0InRange && sprites.scanlineSprite0[ this.lineCycle - 1 ] && !this.sprite0Hit ) { this.sprite0Hit = !!background.scanlineColors[ this.lineCycle - 1 ]; } } this.incrementRenderCycle(); } else { this.incrementIdleCycle(); } }
javascript
function() { var sprites = this.sprites, background = this.background; if ( this.inRenderScanline ) { if ( this.enabled ) { background.evaluate(); sprites.evaluate(); } if ( this.pixelInRange ) { if ( this.pixelInRange && sprites.sprite0InRange && sprites.scanlineSprite0[ this.lineCycle - 1 ] && !this.sprite0Hit ) { this.sprite0Hit = !!background.scanlineColors[ this.lineCycle - 1 ]; } } this.incrementRenderCycle(); } else { this.incrementIdleCycle(); } }
[ "function", "(", ")", "{", "var", "sprites", "=", "this", ".", "sprites", ",", "background", "=", "this", ".", "background", ";", "if", "(", "this", ".", "inRenderScanline", ")", "{", "if", "(", "this", ".", "enabled", ")", "{", "background", ".", "e...
A single PPU tick.
[ "A", "single", "PPU", "tick", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/ppu/index.js#L167-L192
31,846
que-etc/intersection-observer-polyfill
src/IntersectionObserverController.js
debounce
function debounce(callback, delay = 0) { let timeoutID = false; return function (...args) { if (timeoutID !== false) { clearTimeout(timeoutID); } timeoutID = setTimeout(() => { timeoutID = false; callback.apply(this, args); }, delay); }; }
javascript
function debounce(callback, delay = 0) { let timeoutID = false; return function (...args) { if (timeoutID !== false) { clearTimeout(timeoutID); } timeoutID = setTimeout(() => { timeoutID = false; callback.apply(this, args); }, delay); }; }
[ "function", "debounce", "(", "callback", ",", "delay", "=", "0", ")", "{", "let", "timeoutID", "=", "false", ";", "return", "function", "(", "...", "args", ")", "{", "if", "(", "timeoutID", "!==", "false", ")", "{", "clearTimeout", "(", "timeoutID", ")...
Creates a wrapper function that ensures that provided callback will be invoked only after the specified delay. @param {Function} callback @param {Number} [delay = 0] @returns {Function}
[ "Creates", "a", "wrapper", "function", "that", "ensures", "that", "provided", "callback", "will", "be", "invoked", "only", "after", "the", "specified", "delay", "." ]
39eae5569fe09ba840d2a4d92de5c0670bc11a71
https://github.com/que-etc/intersection-observer-polyfill/blob/39eae5569fe09ba840d2a4d92de5c0670bc11a71/src/IntersectionObserverController.js#L30-L44
31,847
koenkivits/nesnes
system/input/index.js
function() { var i, j, item, controls, config = this.config = this.system.config.input; for ( i = 0; i < config.length; i++ ) { item = config[ i ]; this.setController( i, item.type ); controls = item.controls; if ( !Array.isArray(controls) ) { controls = [ controls ]; } for ( j = 0; j < controls.length; j++ ) { this.configure( i, controls[ j ].type, controls[ j ].config ); } } }
javascript
function() { var i, j, item, controls, config = this.config = this.system.config.input; for ( i = 0; i < config.length; i++ ) { item = config[ i ]; this.setController( i, item.type ); controls = item.controls; if ( !Array.isArray(controls) ) { controls = [ controls ]; } for ( j = 0; j < controls.length; j++ ) { this.configure( i, controls[ j ].type, controls[ j ].config ); } } }
[ "function", "(", ")", "{", "var", "i", ",", "j", ",", "item", ",", "controls", ",", "config", "=", "this", ".", "config", "=", "this", ".", "system", ".", "config", ".", "input", ";", "for", "(", "i", "=", "0", ";", "i", "<", "config", ".", "...
Initialize total input config.
[ "Initialize", "total", "input", "config", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/input/index.js#L56-L74
31,848
koenkivits/nesnes
system/input/index.js
function( index, type, config ) { var currentHandler, InputHandler = inputHandlerMap[ type ], controller = this.controllers.get( index ); this.initInputHandlers( index ); currentHandler = this.inputHandlers[ index ][ type ]; if ( currentHandler ) { currentHandler.disable(); } this.inputHandlers[ index ][ type ] = new InputHandler( controller, config ); if ( this._enabled ) { this.inputHandlers[ index ][ type ].enable(); } }
javascript
function( index, type, config ) { var currentHandler, InputHandler = inputHandlerMap[ type ], controller = this.controllers.get( index ); this.initInputHandlers( index ); currentHandler = this.inputHandlers[ index ][ type ]; if ( currentHandler ) { currentHandler.disable(); } this.inputHandlers[ index ][ type ] = new InputHandler( controller, config ); if ( this._enabled ) { this.inputHandlers[ index ][ type ].enable(); } }
[ "function", "(", "index", ",", "type", ",", "config", ")", "{", "var", "currentHandler", ",", "InputHandler", "=", "inputHandlerMap", "[", "type", "]", ",", "controller", "=", "this", ".", "controllers", ".", "get", "(", "index", ")", ";", "this", ".", ...
Configure the input for a controller @param {number} index - Either 0 or 1 @param {string} type - Type of input handler (either 'keyboard' or 'gamepad') @param {object} config - Configuration for input handler (see config.json for examples)
[ "Configure", "the", "input", "for", "a", "controller" ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/input/index.js#L92-L108
31,849
koenkivits/nesnes
system/ppu/background.js
function() { var cartridge = this.memory.cartridge, attrAddress = attrAddresses[ this.loopyV ], attribute = cartridge.readNameTable( attrAddress & 0x1fff ), nametableAddress = 0x2000 | ( this.loopyV & 0x0fff ), tileIndex = cartridge.readNameTable( nametableAddress & 0x1fff ), tile = cartridge.readTile( this.baseTable, tileIndex, this.y ); if ( tile ) { this.renderTile( tile, palettes[ attribute & masks[ this.loopyV & 0xfff ] ] ); } this.incrementVX(); }
javascript
function() { var cartridge = this.memory.cartridge, attrAddress = attrAddresses[ this.loopyV ], attribute = cartridge.readNameTable( attrAddress & 0x1fff ), nametableAddress = 0x2000 | ( this.loopyV & 0x0fff ), tileIndex = cartridge.readNameTable( nametableAddress & 0x1fff ), tile = cartridge.readTile( this.baseTable, tileIndex, this.y ); if ( tile ) { this.renderTile( tile, palettes[ attribute & masks[ this.loopyV & 0xfff ] ] ); } this.incrementVX(); }
[ "function", "(", ")", "{", "var", "cartridge", "=", "this", ".", "memory", ".", "cartridge", ",", "attrAddress", "=", "attrAddresses", "[", "this", ".", "loopyV", "]", ",", "attribute", "=", "cartridge", ".", "readNameTable", "(", "attrAddress", "&", "0x1f...
Fetch background tile data.
[ "Fetch", "background", "tile", "data", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/ppu/background.js#L168-L186
31,850
koenkivits/nesnes
system/ppu/background.js
initAttrAddresses
function initAttrAddresses() { var i, result = new Uint16Array( 0x8000 ); for ( i = 0; i < 0x8000; i++ ) { result[ i ] = 0x23c0 | (i & 0x0c00) | ((i >> 4) & 0x38) | ((i >> 2) & 0x07); } return result; }
javascript
function initAttrAddresses() { var i, result = new Uint16Array( 0x8000 ); for ( i = 0; i < 0x8000; i++ ) { result[ i ] = 0x23c0 | (i & 0x0c00) | ((i >> 4) & 0x38) | ((i >> 2) & 0x07); } return result; }
[ "function", "initAttrAddresses", "(", ")", "{", "var", "i", ",", "result", "=", "new", "Uint16Array", "(", "0x8000", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "0x8000", ";", "i", "++", ")", "{", "result", "[", "i", "]", "=", "0x23c0", ...
Initialize attribute address lookup table. Maps loopy_v values to attribute addresses.
[ "Initialize", "attribute", "address", "lookup", "table", ".", "Maps", "loopy_v", "values", "to", "attribute", "addresses", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/ppu/background.js#L213-L222
31,851
koenkivits/nesnes
system/ppu/background.js
initMasks
function initMasks() { var i, mask, result = new Uint8Array( 0x10000 ); for ( i = 0; i < 0x10000; i++ ) { mask = 3; if ( i & 0x2 ) { // right mask <<= 2; } if ( i & 0x40 ) { // bottom mask <<= 4; } result[ i ] = mask; } return result; }
javascript
function initMasks() { var i, mask, result = new Uint8Array( 0x10000 ); for ( i = 0; i < 0x10000; i++ ) { mask = 3; if ( i & 0x2 ) { // right mask <<= 2; } if ( i & 0x40 ) { // bottom mask <<= 4; } result[ i ] = mask; } return result; }
[ "function", "initMasks", "(", ")", "{", "var", "i", ",", "mask", ",", "result", "=", "new", "Uint8Array", "(", "0x10000", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "0x10000", ";", "i", "++", ")", "{", "mask", "=", "3", ";", "if", "(...
Inititialze mask lookup table. Maps loopy_v values to bitmasks for attribute bytes to get the correct palette value.
[ "Inititialze", "mask", "lookup", "table", ".", "Maps", "loopy_v", "values", "to", "bitmasks", "for", "attribute", "bytes", "to", "get", "the", "correct", "palette", "value", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/ppu/background.js#L228-L247
31,852
koenkivits/nesnes
system/ppu/background.js
initTileCycles
function initTileCycles() { var i, result = new Uint8Array( 400 ); for ( i = 7; i < 256; i += 8 ) { result[ i ] = 1; } for ( i = 327; i < 336; i += 8 ) { result[ i ] = 1; } return result; }
javascript
function initTileCycles() { var i, result = new Uint8Array( 400 ); for ( i = 7; i < 256; i += 8 ) { result[ i ] = 1; } for ( i = 327; i < 336; i += 8 ) { result[ i ] = 1; } return result; }
[ "function", "initTileCycles", "(", ")", "{", "var", "i", ",", "result", "=", "new", "Uint8Array", "(", "400", ")", ";", "for", "(", "i", "=", "7", ";", "i", "<", "256", ";", "i", "+=", "8", ")", "{", "result", "[", "i", "]", "=", "1", ";", ...
Initialize tile fetch cycles. Returns a typed array containing a 1 at every cycle a background tile should be fetched.
[ "Initialize", "tile", "fetch", "cycles", ".", "Returns", "a", "typed", "array", "containing", "a", "1", "at", "every", "cycle", "a", "background", "tile", "should", "be", "fetched", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/ppu/background.js#L270-L282
31,853
koenkivits/nesnes
system/ppu/sprites.js
function() { var spriteIndex = this.currentSprite << 2, y = this.oam2[ spriteIndex ], tileIndex = this.oam2[ spriteIndex + 1 ], attributes = this.oam2[ spriteIndex + 2 ], x = this.oam2[ spriteIndex + 3 ], baseTable = this.baseTable, tile = 0, flipX = attributes & 0x40, flipY = 0, fineY = 0; flipY = attributes & 0x80; fineY = ( this.ppu.scanline - y ) & ( this.spriteSize - 1 ); // (the '& spriteSize' is needed because fineY can overflow due // to uninitialized tiles in secondary OAM) if ( this.spriteSize === 16 ) { // big sprite, select proper nametable and handle flipping baseTable = ( tileIndex & 1 ) ? 0x1000 : 0; tileIndex = tileIndex & ~1; if ( fineY > 7 ) { fineY -= 8; if ( !flipY ) { tileIndex++; } } else if ( flipY ) { tileIndex++; } } if ( flipY ) { fineY = 8 - fineY - 1; } tile = this.memory.cartridge.readTile( baseTable, tileIndex, fineY ); if ( flipX ) { tile = bitmap.reverseTile( tile ); } if ( this.currentSprite < this.nextSpriteCount ) { this.renderTile( x, tile, attributes ); } this.currentSprite += 1; }
javascript
function() { var spriteIndex = this.currentSprite << 2, y = this.oam2[ spriteIndex ], tileIndex = this.oam2[ spriteIndex + 1 ], attributes = this.oam2[ spriteIndex + 2 ], x = this.oam2[ spriteIndex + 3 ], baseTable = this.baseTable, tile = 0, flipX = attributes & 0x40, flipY = 0, fineY = 0; flipY = attributes & 0x80; fineY = ( this.ppu.scanline - y ) & ( this.spriteSize - 1 ); // (the '& spriteSize' is needed because fineY can overflow due // to uninitialized tiles in secondary OAM) if ( this.spriteSize === 16 ) { // big sprite, select proper nametable and handle flipping baseTable = ( tileIndex & 1 ) ? 0x1000 : 0; tileIndex = tileIndex & ~1; if ( fineY > 7 ) { fineY -= 8; if ( !flipY ) { tileIndex++; } } else if ( flipY ) { tileIndex++; } } if ( flipY ) { fineY = 8 - fineY - 1; } tile = this.memory.cartridge.readTile( baseTable, tileIndex, fineY ); if ( flipX ) { tile = bitmap.reverseTile( tile ); } if ( this.currentSprite < this.nextSpriteCount ) { this.renderTile( x, tile, attributes ); } this.currentSprite += 1; }
[ "function", "(", ")", "{", "var", "spriteIndex", "=", "this", ".", "currentSprite", "<<", "2", ",", "y", "=", "this", ".", "oam2", "[", "spriteIndex", "]", ",", "tileIndex", "=", "this", ".", "oam2", "[", "spriteIndex", "+", "1", "]", ",", "attribute...
Fetch sprite data and feed appropriate shifters, counters and latches.
[ "Fetch", "sprite", "data", "and", "feed", "appropriate", "shifters", "counters", "and", "latches", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/ppu/sprites.js#L185-L232
31,854
koenkivits/nesnes
system/output/audiooutput.js
function( sample ) { this.bufferData[ this.bufferIndex++ ] = sample; if ( this.bufferIndex === this.bufferLength ) { this.bufferIndex = 0; if ( this.playing ) { this.playing.stop(); } this.bufferSource.buffer = this.buffer; this.playing = this.bufferSource; this.playing.start( 0 ); this.initBuffer(); } }
javascript
function( sample ) { this.bufferData[ this.bufferIndex++ ] = sample; if ( this.bufferIndex === this.bufferLength ) { this.bufferIndex = 0; if ( this.playing ) { this.playing.stop(); } this.bufferSource.buffer = this.buffer; this.playing = this.bufferSource; this.playing.start( 0 ); this.initBuffer(); } }
[ "function", "(", "sample", ")", "{", "this", ".", "bufferData", "[", "this", ".", "bufferIndex", "++", "]", "=", "sample", ";", "if", "(", "this", ".", "bufferIndex", "===", "this", ".", "bufferLength", ")", "{", "this", ".", "bufferIndex", "=", "0", ...
Write sample to buffer.
[ "Write", "sample", "to", "buffer", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/audiooutput.js#L16-L32
31,855
koenkivits/nesnes
system/output/audiooutput.js
function() { this.context = new AudioContext(); this.sampleRate = this.context.sampleRate; this.gainNode = this.context.createGain(); this.gainNode.connect( this.context.destination ); }
javascript
function() { this.context = new AudioContext(); this.sampleRate = this.context.sampleRate; this.gainNode = this.context.createGain(); this.gainNode.connect( this.context.destination ); }
[ "function", "(", ")", "{", "this", ".", "context", "=", "new", "AudioContext", "(", ")", ";", "this", ".", "sampleRate", "=", "this", ".", "context", ".", "sampleRate", ";", "this", ".", "gainNode", "=", "this", ".", "context", ".", "createGain", "(", ...
Initialize audio context.
[ "Initialize", "audio", "context", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/audiooutput.js#L74-L79
31,856
koenkivits/nesnes
system/output/audiooutput.js
function() { this.buffer = this.context.createBuffer(1, this.bufferLength, this.context.sampleRate); this.bufferData = this.buffer.getChannelData( 0 ); this.bufferSource = this.context.createBufferSource(); this.bufferSource.connect( this.gainNode ); }
javascript
function() { this.buffer = this.context.createBuffer(1, this.bufferLength, this.context.sampleRate); this.bufferData = this.buffer.getChannelData( 0 ); this.bufferSource = this.context.createBufferSource(); this.bufferSource.connect( this.gainNode ); }
[ "function", "(", ")", "{", "this", ".", "buffer", "=", "this", ".", "context", ".", "createBuffer", "(", "1", ",", "this", ".", "bufferLength", ",", "this", ".", "context", ".", "sampleRate", ")", ";", "this", ".", "bufferData", "=", "this", ".", "bu...
Initialize audio buffer.
[ "Initialize", "audio", "buffer", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/audiooutput.js#L84-L90
31,857
que-etc/intersection-observer-polyfill
src/IntersectionObservation.js
isDetached
function isDetached(container, target) { const docElement = document.documentElement; return ( container !== docElement && !docElement.contains(container) || !container.contains(target) ); }
javascript
function isDetached(container, target) { const docElement = document.documentElement; return ( container !== docElement && !docElement.contains(container) || !container.contains(target) ); }
[ "function", "isDetached", "(", "container", ",", "target", ")", "{", "const", "docElement", "=", "document", ".", "documentElement", ";", "return", "(", "container", "!==", "docElement", "&&", "!", "docElement", ".", "contains", "(", "container", ")", "||", ...
Tells whether target is a descendant of container element and that both of them are present in DOM. @param {Element} container - Container element. @param {Element} target - Target element. @returns {Boolean}
[ "Tells", "whether", "target", "is", "a", "descendant", "of", "container", "element", "and", "that", "both", "of", "them", "are", "present", "in", "DOM", "." ]
39eae5569fe09ba840d2a4d92de5c0670bc11a71
https://github.com/que-etc/intersection-observer-polyfill/blob/39eae5569fe09ba840d2a4d92de5c0670bc11a71/src/IntersectionObservation.js#L15-L22
31,858
que-etc/intersection-observer-polyfill
src/IntersectionObservation.js
computeIntersection
function computeIntersection(rootRect, targetRect) { const left = Math.max(targetRect.left, rootRect.left); const right = Math.min(targetRect.right, rootRect.right); const top = Math.max(targetRect.top, rootRect.top); const bottom = Math.min(targetRect.bottom, rootRect.bottom); const width = right - left; const height = bottom - top; return createRectangle(left, top, width, height); }
javascript
function computeIntersection(rootRect, targetRect) { const left = Math.max(targetRect.left, rootRect.left); const right = Math.min(targetRect.right, rootRect.right); const top = Math.max(targetRect.top, rootRect.top); const bottom = Math.min(targetRect.bottom, rootRect.bottom); const width = right - left; const height = bottom - top; return createRectangle(left, top, width, height); }
[ "function", "computeIntersection", "(", "rootRect", ",", "targetRect", ")", "{", "const", "left", "=", "Math", ".", "max", "(", "targetRect", ".", "left", ",", "rootRect", ".", "left", ")", ";", "const", "right", "=", "Math", ".", "min", "(", "targetRect...
Computes intersection rectangle between two rectangles. @param {ClientRect} rootRect - Rectangle of container element. @param {ClientRect} targetRect - Rectangle of target element. @returns {ClientRect} Intersection rectangle.
[ "Computes", "intersection", "rectangle", "between", "two", "rectangles", "." ]
39eae5569fe09ba840d2a4d92de5c0670bc11a71
https://github.com/que-etc/intersection-observer-polyfill/blob/39eae5569fe09ba840d2a4d92de5c0670bc11a71/src/IntersectionObservation.js#L31-L41
31,859
que-etc/intersection-observer-polyfill
src/IntersectionObservation.js
getIntersection
function getIntersection(container, target, containterRect, targetRect) { let intersecRect = targetRect, parent = target.parentNode, rootReached = false; while (!rootReached) { let parentRect = null; if (parent === container || parent.nodeType !== 1) { rootReached = true; parentRect = containterRect; } else if (window.getComputedStyle(parent).overflow !== 'visible') { parentRect = getRectangle(parent); } if (parentRect) { intersecRect = computeIntersection(intersecRect, parentRect); } parent = parent.parentNode; } return intersecRect; }
javascript
function getIntersection(container, target, containterRect, targetRect) { let intersecRect = targetRect, parent = target.parentNode, rootReached = false; while (!rootReached) { let parentRect = null; if (parent === container || parent.nodeType !== 1) { rootReached = true; parentRect = containterRect; } else if (window.getComputedStyle(parent).overflow !== 'visible') { parentRect = getRectangle(parent); } if (parentRect) { intersecRect = computeIntersection(intersecRect, parentRect); } parent = parent.parentNode; } return intersecRect; }
[ "function", "getIntersection", "(", "container", ",", "target", ",", "containterRect", ",", "targetRect", ")", "{", "let", "intersecRect", "=", "targetRect", ",", "parent", "=", "target", ".", "parentNode", ",", "rootReached", "=", "false", ";", "while", "(", ...
Finds intersection rectangle of provided elements. @param {Element} container - Container element. @param {Element} target - Target element. @param {ClientRect} targetRect - Rectangle of target element. @param {ClientRect} containterRect - Rectangle of container element.
[ "Finds", "intersection", "rectangle", "of", "provided", "elements", "." ]
39eae5569fe09ba840d2a4d92de5c0670bc11a71
https://github.com/que-etc/intersection-observer-polyfill/blob/39eae5569fe09ba840d2a4d92de5c0670bc11a71/src/IntersectionObservation.js#L51-L74
31,860
koenkivits/nesnes
system/cartridge.js
function() { if ( !( this.header[0] === 0x4e && // 'N' this.header[1] === 0x45 && // 'E' this.header[2] === 0x53 && // 'S' this.header[3] === 0x1a // ending character )) { throw new Error("Invalid ROM!"); } if ( this.header[7] & 0xe ) { throw new Error("Bit 1-3 of byte 7 in ROM header must all be zeroes!"); } if ( this.header[9] & 0xfe ) { throw new Error("Bit 1-7 of byte 9 in header must all be zeroes!"); } var i; for ( i=10; i <= 15; i++ ) { if ( this.header[i] ) { throw new Error("Byte " + i + " in ROM header must be zero."); } } if ( this.header[6] & 0x4 ) { // TODO support trainers throw new Error("Trained ROMs are not supported"); } }
javascript
function() { if ( !( this.header[0] === 0x4e && // 'N' this.header[1] === 0x45 && // 'E' this.header[2] === 0x53 && // 'S' this.header[3] === 0x1a // ending character )) { throw new Error("Invalid ROM!"); } if ( this.header[7] & 0xe ) { throw new Error("Bit 1-3 of byte 7 in ROM header must all be zeroes!"); } if ( this.header[9] & 0xfe ) { throw new Error("Bit 1-7 of byte 9 in header must all be zeroes!"); } var i; for ( i=10; i <= 15; i++ ) { if ( this.header[i] ) { throw new Error("Byte " + i + " in ROM header must be zero."); } } if ( this.header[6] & 0x4 ) { // TODO support trainers throw new Error("Trained ROMs are not supported"); } }
[ "function", "(", ")", "{", "if", "(", "!", "(", "this", ".", "header", "[", "0", "]", "===", "0x4e", "&&", "// 'N'", "this", ".", "header", "[", "1", "]", "===", "0x45", "&&", "// 'E'", "this", ".", "header", "[", "2", "]", "===", "0x53", "&&",...
Validate INES header. Throws an exception if invalid.
[ "Validate", "INES", "header", ".", "Throws", "an", "exception", "if", "invalid", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cartridge.js#L31-L59
31,861
koenkivits/nesnes
system/cartridge.js
function() { var flags6 = this.header[6]; this.mirroring = ( flags6 & 0x1 ) ? VERTICAL : HORIZONTAL; this.battery = ( flags6 & 0x2 ); this.trainer = ( flags6 & 0x4 ); this.mirroring = ( flags6 & 0x8 ) ? FOUR_SCREEN : this.mirroring; var flags7 = this.header[7]; this.vs = (flags7 & 0x1); this.mapper = ( (( flags6 & 0xf0 ) >> 4) | ( flags7 & 0xf0 ) ); this.pal = (this.header[9] & 0x1); }
javascript
function() { var flags6 = this.header[6]; this.mirroring = ( flags6 & 0x1 ) ? VERTICAL : HORIZONTAL; this.battery = ( flags6 & 0x2 ); this.trainer = ( flags6 & 0x4 ); this.mirroring = ( flags6 & 0x8 ) ? FOUR_SCREEN : this.mirroring; var flags7 = this.header[7]; this.vs = (flags7 & 0x1); this.mapper = ( (( flags6 & 0xf0 ) >> 4) | ( flags7 & 0xf0 ) ); this.pal = (this.header[9] & 0x1); }
[ "function", "(", ")", "{", "var", "flags6", "=", "this", ".", "header", "[", "6", "]", ";", "this", ".", "mirroring", "=", "(", "flags6", "&", "0x1", ")", "?", "VERTICAL", ":", "HORIZONTAL", ";", "this", ".", "battery", "=", "(", "flags6", "&", "...
Init header flags.
[ "Init", "header", "flags", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cartridge.js#L64-L80
31,862
koenkivits/nesnes
system/cartridge.js
function() { this.prgRead = new Uint8Array( 0x8000 ); this.prgRead.set( this.prgData.subarray( 0, 0x2000 ) ); this.chrRead = new Uint8Array( 0x2000 ); this.chrRead.set( this.chrData.subarray( 0, 0x2000 ) ); mappers.init( this ); }
javascript
function() { this.prgRead = new Uint8Array( 0x8000 ); this.prgRead.set( this.prgData.subarray( 0, 0x2000 ) ); this.chrRead = new Uint8Array( 0x2000 ); this.chrRead.set( this.chrData.subarray( 0, 0x2000 ) ); mappers.init( this ); }
[ "function", "(", ")", "{", "this", ".", "prgRead", "=", "new", "Uint8Array", "(", "0x8000", ")", ";", "this", ".", "prgRead", ".", "set", "(", "this", ".", "prgData", ".", "subarray", "(", "0", ",", "0x2000", ")", ")", ";", "this", ".", "chrRead", ...
Init mapper data and logic. NESNES copies data around to a dedicated typed array to emulate mapper behavior. See also loadChrBank and loadPrgBank.
[ "Init", "mapper", "data", "and", "logic", ".", "NESNES", "copies", "data", "around", "to", "a", "dedicated", "typed", "array", "to", "emulate", "mapper", "behavior", ".", "See", "also", "loadChrBank", "and", "loadPrgBank", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cartridge.js#L113-L121
31,863
koenkivits/nesnes
system/cartridge.js
function( address, value ) { if ( address & 0x8000 ) { this.writeRegister( address, value ); } else if ( address >= 0x6000 ) { // writing RAM this.ramData[ address - 0x6000 ] = value; } return; }
javascript
function( address, value ) { if ( address & 0x8000 ) { this.writeRegister( address, value ); } else if ( address >= 0x6000 ) { // writing RAM this.ramData[ address - 0x6000 ] = value; } return; }
[ "function", "(", "address", ",", "value", ")", "{", "if", "(", "address", "&", "0x8000", ")", "{", "this", ".", "writeRegister", "(", "address", ",", "value", ")", ";", "}", "else", "if", "(", "address", ">=", "0x6000", ")", "{", "// writing RAM", "t...
Write program data. This is usually used to write to cartridge RAM or mapper registers. Cartridges don't have mappers by default, but mapperless cartridges can also not be written to. This method implements the most common mapper register locations.
[ "Write", "program", "data", ".", "This", "is", "usually", "used", "to", "write", "to", "cartridge", "RAM", "or", "mapper", "registers", ".", "Cartridges", "don", "t", "have", "mappers", "by", "default", "but", "mapperless", "cartridges", "can", "also", "not"...
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cartridge.js#L152-L161
31,864
koenkivits/nesnes
system/cartridge.js
function( address, bank, size ) { var offset = bank * size, bankData = this.prgData.subarray( offset, offset + size ); this.prgRead.set( bankData, address - 0x8000 ); }
javascript
function( address, bank, size ) { var offset = bank * size, bankData = this.prgData.subarray( offset, offset + size ); this.prgRead.set( bankData, address - 0x8000 ); }
[ "function", "(", "address", ",", "bank", ",", "size", ")", "{", "var", "offset", "=", "bank", "*", "size", ",", "bankData", "=", "this", ".", "prgData", ".", "subarray", "(", "offset", ",", "offset", "+", "size", ")", ";", "this", ".", "prgRead", "...
Load a PRG Bank at a specific addres. @param {number} address - The absolute address to load bank at (eg. 0x8000). @param {bank} bank - Index of bank to load at given address. @param {size} size - Size of all banks.
[ "Load", "a", "PRG", "Bank", "at", "a", "specific", "addres", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cartridge.js#L169-L174
31,865
koenkivits/nesnes
system/cartridge.js
function( address, bank, size ) { var offset = bank * size, bankData = this.chrData.subarray( offset, offset + size ); this.chrRead.set( bankData, address ); }
javascript
function( address, bank, size ) { var offset = bank * size, bankData = this.chrData.subarray( offset, offset + size ); this.chrRead.set( bankData, address ); }
[ "function", "(", "address", ",", "bank", ",", "size", ")", "{", "var", "offset", "=", "bank", "*", "size", ",", "bankData", "=", "this", ".", "chrData", ".", "subarray", "(", "offset", ",", "offset", "+", "size", ")", ";", "this", ".", "chrRead", "...
Load a CHR Bank at a specific addres. @param {number} address - The absolute address to load bank at (eg. 0x8000). @param {bank} bank - Index of bank to load at given address. @param {size} size - Size of all banks.
[ "Load", "a", "CHR", "Bank", "at", "a", "specific", "addres", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cartridge.js#L211-L216
31,866
koenkivits/nesnes
system/cartridge.js
function( address ) { switch( this.mirroring ) { case HORIZONTAL: if ( address >= 0x400 ) { address -= 0x400; } if ( address >= 0x800 ) { address -= 0x400; } break; case VERTICAL: address &= 0x07ff; break; case FOUR_SCREEN: // we still don't implement any mappers that support four screen mirrroring throw new Error("TODO, four screen mirroring"); case SINGLE_SCREEN_LOWER: case SINGLE_SCREEN_UPPER: address &= 0x3ff; if ( this.mirroring === 4 ) { address += 0x400; } break; } return address; }
javascript
function( address ) { switch( this.mirroring ) { case HORIZONTAL: if ( address >= 0x400 ) { address -= 0x400; } if ( address >= 0x800 ) { address -= 0x400; } break; case VERTICAL: address &= 0x07ff; break; case FOUR_SCREEN: // we still don't implement any mappers that support four screen mirrroring throw new Error("TODO, four screen mirroring"); case SINGLE_SCREEN_LOWER: case SINGLE_SCREEN_UPPER: address &= 0x3ff; if ( this.mirroring === 4 ) { address += 0x400; } break; } return address; }
[ "function", "(", "address", ")", "{", "switch", "(", "this", ".", "mirroring", ")", "{", "case", "HORIZONTAL", ":", "if", "(", "address", ">=", "0x400", ")", "{", "address", "-=", "0x400", ";", "}", "if", "(", "address", ">=", "0x800", ")", "{", "a...
Map a nametable address to our internal memory, taking mirroring into account.
[ "Map", "a", "nametable", "address", "to", "our", "internal", "memory", "taking", "mirroring", "into", "account", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cartridge.js#L221-L248
31,867
koenkivits/nesnes
system/output/renderer/canvas2d.js
function() { this.width = 256; this.height = 224; this.data = new Uint8Array( this.width * this.height * 4 ); for ( var i = 0; i < this.data.length; i++ ) { this.data[ i ] = 0xff; } this.context = getContext( this.el ); this.image = this.context.getImageData( 0, 0, this.width, this.height ); this.index = 0; }
javascript
function() { this.width = 256; this.height = 224; this.data = new Uint8Array( this.width * this.height * 4 ); for ( var i = 0; i < this.data.length; i++ ) { this.data[ i ] = 0xff; } this.context = getContext( this.el ); this.image = this.context.getImageData( 0, 0, this.width, this.height ); this.index = 0; }
[ "function", "(", ")", "{", "this", ".", "width", "=", "256", ";", "this", ".", "height", "=", "224", ";", "this", ".", "data", "=", "new", "Uint8Array", "(", "this", ".", "width", "*", "this", ".", "height", "*", "4", ")", ";", "for", "(", "var...
Initialize the video output.
[ "Initialize", "the", "video", "output", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/renderer/canvas2d.js#L52-L65
31,868
koenkivits/nesnes
system/output/renderer/canvas2d.js
function() { var color = 0, i = 0, address = 0, view = palette, buffer = new ArrayBuffer( 0xc0 ), splitPalette = new Uint8Array( buffer ); // first, re-arrange RGB values in a single array (first reds, then blues, then greens) for ( color = 0; color < 3; color +=1 ) { for ( i = 0; i < 192; i += 3 ) { splitPalette[ address ] = view[ i + color ]; address += 1; } } // then, make color values separately available in separate arrays: this.palette = view; this.reds = new Uint8Array( buffer, 0, 0x40 ); this.greens = new Uint8Array( buffer, 0x40, 0x40 ); this.blues = new Uint8Array( buffer, 0x80, 0x40 ); }
javascript
function() { var color = 0, i = 0, address = 0, view = palette, buffer = new ArrayBuffer( 0xc0 ), splitPalette = new Uint8Array( buffer ); // first, re-arrange RGB values in a single array (first reds, then blues, then greens) for ( color = 0; color < 3; color +=1 ) { for ( i = 0; i < 192; i += 3 ) { splitPalette[ address ] = view[ i + color ]; address += 1; } } // then, make color values separately available in separate arrays: this.palette = view; this.reds = new Uint8Array( buffer, 0, 0x40 ); this.greens = new Uint8Array( buffer, 0x40, 0x40 ); this.blues = new Uint8Array( buffer, 0x80, 0x40 ); }
[ "function", "(", ")", "{", "var", "color", "=", "0", ",", "i", "=", "0", ",", "address", "=", "0", ",", "view", "=", "palette", ",", "buffer", "=", "new", "ArrayBuffer", "(", "0xc0", ")", ",", "splitPalette", "=", "new", "Uint8Array", "(", "buffer"...
Initialize palette for video output.
[ "Initialize", "palette", "for", "video", "output", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/renderer/canvas2d.js#L70-L91
31,869
koenkivits/nesnes
system/output/videooutput.js
function( background, sprites, priorities ) { this.bgBuffer.set( background, this.index ); this.spriteBuffer.set( sprites, this.index ); this.prioBuffer.set( priorities, this.index ); this.index += 256; }
javascript
function( background, sprites, priorities ) { this.bgBuffer.set( background, this.index ); this.spriteBuffer.set( sprites, this.index ); this.prioBuffer.set( priorities, this.index ); this.index += 256; }
[ "function", "(", "background", ",", "sprites", ",", "priorities", ")", "{", "this", ".", "bgBuffer", ".", "set", "(", "background", ",", "this", ".", "index", ")", ";", "this", ".", "spriteBuffer", ".", "set", "(", "sprites", ",", "this", ".", "index",...
Output a scanline. @param {Uint8Array} background - Scanline background buffer @param {Uint8Array} sprites - Scanline sprite buffer @param {Uint8Array} priorities - Scanline sprite priority buffer
[ "Output", "a", "scanline", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/videooutput.js#L66-L71
31,870
koenkivits/nesnes
system/output/videooutput.js
function() { if ( !this.force2D && WebGLRenderer.isSupported( this.el ) ) { this.renderer = new WebGLRenderer( this.el ); } else if ( Canvas2DRenderer.isSupported( this.el ) ) { this.renderer = new Canvas2DRenderer( this.el ); } else { throw new Error( "No supported renderer!" ); } }
javascript
function() { if ( !this.force2D && WebGLRenderer.isSupported( this.el ) ) { this.renderer = new WebGLRenderer( this.el ); } else if ( Canvas2DRenderer.isSupported( this.el ) ) { this.renderer = new Canvas2DRenderer( this.el ); } else { throw new Error( "No supported renderer!" ); } }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "force2D", "&&", "WebGLRenderer", ".", "isSupported", "(", "this", ".", "el", ")", ")", "{", "this", ".", "renderer", "=", "new", "WebGLRenderer", "(", "this", ".", "el", ")", ";", "}", "else"...
Initialize renderer.
[ "Initialize", "renderer", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/videooutput.js#L85-L93
31,871
koenkivits/nesnes
system/output/renderer/webgl.js
function() { var gl = this.gl; var buffer = this.buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array([ -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0 ]), gl.STATIC_DRAW ); }
javascript
function() { var gl = this.gl; var buffer = this.buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array([ -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0 ]), gl.STATIC_DRAW ); }
[ "function", "(", ")", "{", "var", "gl", "=", "this", ".", "gl", ";", "var", "buffer", "=", "this", ".", "buffer", "=", "gl", ".", "createBuffer", "(", ")", ";", "gl", ".", "bindBuffer", "(", "gl", ".", "ARRAY_BUFFER", ",", "buffer", ")", ";", "gl...
Initialize the quad to draw to.
[ "Initialize", "the", "quad", "to", "draw", "to", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/renderer/webgl.js#L69-L86
31,872
koenkivits/nesnes
system/output/renderer/webgl.js
function() { var gl = this.gl, program = this.program; // initialize pixel textures this.bgTexture = createTexture( 0, "bgTexture" ); this.spriteTexture = createTexture( 1, "spriteTexture" ); this.prioTexture = createTexture( 2, "prioTexture" ); // initialize palette texture this.paletteTexture = createTexture( 3, "paletteTexture" ); gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 64, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, palette ); function createTexture( index, name ) { var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.uniform1i(gl.getUniformLocation(program, name), index); return texture; } }
javascript
function() { var gl = this.gl, program = this.program; // initialize pixel textures this.bgTexture = createTexture( 0, "bgTexture" ); this.spriteTexture = createTexture( 1, "spriteTexture" ); this.prioTexture = createTexture( 2, "prioTexture" ); // initialize palette texture this.paletteTexture = createTexture( 3, "paletteTexture" ); gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 64, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, palette ); function createTexture( index, name ) { var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.uniform1i(gl.getUniformLocation(program, name), index); return texture; } }
[ "function", "(", ")", "{", "var", "gl", "=", "this", ".", "gl", ",", "program", "=", "this", ".", "program", ";", "// initialize pixel textures", "this", ".", "bgTexture", "=", "createTexture", "(", "0", ",", "\"bgTexture\"", ")", ";", "this", ".", "spri...
Initialize textures. One 'dynamic' texture that contains the screen pixel data, and one fixed texture containing the system palette.
[ "Initialize", "textures", ".", "One", "dynamic", "texture", "that", "contains", "the", "screen", "pixel", "data", "and", "one", "fixed", "texture", "containing", "the", "system", "palette", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/renderer/webgl.js#L93-L120
31,873
koenkivits/nesnes
system/output/renderer/webgl.js
function() { var gl = this.gl; var fragmentShaderSource = [ "precision mediump float;", "uniform sampler2D bgTexture;", "uniform sampler2D spriteTexture;", "uniform sampler2D prioTexture;", "uniform sampler2D paletteTexture;", "uniform vec4 bgColor;", "varying vec2 texCoord;", "void main(void) {", "float bgIndex = texture2D(bgTexture, texCoord).r;", "float spriteIndex = texture2D(spriteTexture, texCoord).r;", "float prioIndex = texture2D(prioTexture, texCoord).r;", "float colorIndex = ((spriteIndex > 0.0 && (prioIndex == 0.0 || bgIndex == 0.0)) ? spriteIndex : bgIndex);", "vec4 color = texture2D(paletteTexture, vec2( colorIndex * 4.0 + 0.0078, 0.5));", // 0.0078 == ( 0.5 * 3 / 192 ) === ( 0.5 * [RGB colors] / [palette width] ) "if ( colorIndex > 0.0 ) {", "gl_FragColor = color;", "} else {", "gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);", "gl_FragColor = bgColor;", "}", "}" ].join("\n"); var vertexShaderSource = [ "attribute vec2 vertCoord;", "varying vec2 texCoord;", "void main() {", "gl_Position = vec4(vertCoord, 0, 1);", "texCoord = vec2( 0.5 * ( vertCoord.x + 1.0 ), 0.5 * (1.0 - vertCoord.y));", "}" ].join(""); this.fragmentShader = compileShader( gl.FRAGMENT_SHADER, fragmentShaderSource ); this.vertexShader = compileShader( gl.VERTEX_SHADER, vertexShaderSource ); function compileShader( shaderType, shaderSource ) { var shader = gl.createShader( shaderType ); gl.shaderSource( shader, shaderSource ); gl.compileShader( shader ); if ( !gl.getShaderParameter( shader, gl.COMPILE_STATUS ) ) { throw ( "An error occurred compiling the shaders: " + gl.getShaderInfoLog( shader ) ); } return shader; } }
javascript
function() { var gl = this.gl; var fragmentShaderSource = [ "precision mediump float;", "uniform sampler2D bgTexture;", "uniform sampler2D spriteTexture;", "uniform sampler2D prioTexture;", "uniform sampler2D paletteTexture;", "uniform vec4 bgColor;", "varying vec2 texCoord;", "void main(void) {", "float bgIndex = texture2D(bgTexture, texCoord).r;", "float spriteIndex = texture2D(spriteTexture, texCoord).r;", "float prioIndex = texture2D(prioTexture, texCoord).r;", "float colorIndex = ((spriteIndex > 0.0 && (prioIndex == 0.0 || bgIndex == 0.0)) ? spriteIndex : bgIndex);", "vec4 color = texture2D(paletteTexture, vec2( colorIndex * 4.0 + 0.0078, 0.5));", // 0.0078 == ( 0.5 * 3 / 192 ) === ( 0.5 * [RGB colors] / [palette width] ) "if ( colorIndex > 0.0 ) {", "gl_FragColor = color;", "} else {", "gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);", "gl_FragColor = bgColor;", "}", "}" ].join("\n"); var vertexShaderSource = [ "attribute vec2 vertCoord;", "varying vec2 texCoord;", "void main() {", "gl_Position = vec4(vertCoord, 0, 1);", "texCoord = vec2( 0.5 * ( vertCoord.x + 1.0 ), 0.5 * (1.0 - vertCoord.y));", "}" ].join(""); this.fragmentShader = compileShader( gl.FRAGMENT_SHADER, fragmentShaderSource ); this.vertexShader = compileShader( gl.VERTEX_SHADER, vertexShaderSource ); function compileShader( shaderType, shaderSource ) { var shader = gl.createShader( shaderType ); gl.shaderSource( shader, shaderSource ); gl.compileShader( shader ); if ( !gl.getShaderParameter( shader, gl.COMPILE_STATUS ) ) { throw ( "An error occurred compiling the shaders: " + gl.getShaderInfoLog( shader ) ); } return shader; } }
[ "function", "(", ")", "{", "var", "gl", "=", "this", ".", "gl", ";", "var", "fragmentShaderSource", "=", "[", "\"precision mediump float;\"", ",", "\"uniform sampler2D bgTexture;\"", ",", "\"uniform sampler2D spriteTexture;\"", ",", "\"uniform sampler2D prioTexture;\"", "...
Initialize WebGL shaders.
[ "Initialize", "WebGL", "shaders", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/renderer/webgl.js#L125-L176
31,874
koenkivits/nesnes
system/output/renderer/webgl.js
function() { var gl = this.gl; var program = gl.createProgram(); gl.attachShader( program, this.vertexShader ); gl.attachShader( program, this.fragmentShader ); gl.linkProgram( program ); gl.useProgram( program ); this.program = program; }
javascript
function() { var gl = this.gl; var program = gl.createProgram(); gl.attachShader( program, this.vertexShader ); gl.attachShader( program, this.fragmentShader ); gl.linkProgram( program ); gl.useProgram( program ); this.program = program; }
[ "function", "(", ")", "{", "var", "gl", "=", "this", ".", "gl", ";", "var", "program", "=", "gl", ".", "createProgram", "(", ")", ";", "gl", ".", "attachShader", "(", "program", ",", "this", ".", "vertexShader", ")", ";", "gl", ".", "attachShader", ...
Initialize WebGL program.
[ "Initialize", "WebGL", "program", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/renderer/webgl.js#L181-L191
31,875
gmrutilus/rutilus-logger-node
utils/trackedUsersCache.js
update
function update(sessionId, info) { sessionIdCache[sessionId] = info; db.collection('trackedUsersCache').update({ _id: sessionId, }, { $set: { info: info, }}, { upsert: true }, (err) => { if (errorHandler.dbErrorCatcher(err)) { return false; } return true; }); }
javascript
function update(sessionId, info) { sessionIdCache[sessionId] = info; db.collection('trackedUsersCache').update({ _id: sessionId, }, { $set: { info: info, }}, { upsert: true }, (err) => { if (errorHandler.dbErrorCatcher(err)) { return false; } return true; }); }
[ "function", "update", "(", "sessionId", ",", "info", ")", "{", "sessionIdCache", "[", "sessionId", "]", "=", "info", ";", "db", ".", "collection", "(", "'trackedUsersCache'", ")", ".", "update", "(", "{", "_id", ":", "sessionId", ",", "}", ",", "{", "$...
Adding the id and the information in the cache. If we already have it, we update it
[ "Adding", "the", "id", "and", "the", "information", "in", "the", "cache", ".", "If", "we", "already", "have", "it", "we", "update", "it" ]
797c6283f5c26d9677c60afa80ac99f8cfd00edc
https://github.com/gmrutilus/rutilus-logger-node/blob/797c6283f5c26d9677c60afa80ac99f8cfd00edc/utils/trackedUsersCache.js#L13-L27
31,876
gmrutilus/rutilus-logger-node
utils/trackedUsersCache.js
has
function has(id, cb) { // Do we have it in the local cache? if (sessionIdCache[id]) { cb(true); } // Looking in the database else { db.collection('trackedUsersCache').find({ _id: id }) .toArray((err, docs) => { if (errorHandler.dbErrorCatcher(err)) { return; } // We did not find anything if (!docs || docs.length < 1) { cb(false); } // We found it. Let's cache it and return true else { sessionIdCache[id] = docs[0].info; cb(true); } }); } }
javascript
function has(id, cb) { // Do we have it in the local cache? if (sessionIdCache[id]) { cb(true); } // Looking in the database else { db.collection('trackedUsersCache').find({ _id: id }) .toArray((err, docs) => { if (errorHandler.dbErrorCatcher(err)) { return; } // We did not find anything if (!docs || docs.length < 1) { cb(false); } // We found it. Let's cache it and return true else { sessionIdCache[id] = docs[0].info; cb(true); } }); } }
[ "function", "has", "(", "id", ",", "cb", ")", "{", "// Do we have it in the local cache?", "if", "(", "sessionIdCache", "[", "id", "]", ")", "{", "cb", "(", "true", ")", ";", "}", "// Looking in the database", "else", "{", "db", ".", "collection", "(", "'t...
Do we have this user's information recorded? If yes, we already tracked it at least once
[ "Do", "we", "have", "this", "user", "s", "information", "recorded?", "If", "yes", "we", "already", "tracked", "it", "at", "least", "once" ]
797c6283f5c26d9677c60afa80ac99f8cfd00edc
https://github.com/gmrutilus/rutilus-logger-node/blob/797c6283f5c26d9677c60afa80ac99f8cfd00edc/utils/trackedUsersCache.js#L32-L58
31,877
gmrutilus/rutilus-logger-node
utils/trackedUsersCache.js
get
function get(sessionId, cb) { has(sessionId, (hasId) => { if (hasId) { cb(sessionIdCache[sessionId]); } else { cb(); } }); }
javascript
function get(sessionId, cb) { has(sessionId, (hasId) => { if (hasId) { cb(sessionIdCache[sessionId]); } else { cb(); } }); }
[ "function", "get", "(", "sessionId", ",", "cb", ")", "{", "has", "(", "sessionId", ",", "(", "hasId", ")", "=>", "{", "if", "(", "hasId", ")", "{", "cb", "(", "sessionIdCache", "[", "sessionId", "]", ")", ";", "}", "else", "{", "cb", "(", ")", ...
What is the latest tracked information for the user? We get it from the local cache, if we have it, otherwise we fetch it from the database and record in the local cache
[ "What", "is", "the", "latest", "tracked", "information", "for", "the", "user?", "We", "get", "it", "from", "the", "local", "cache", "if", "we", "have", "it", "otherwise", "we", "fetch", "it", "from", "the", "database", "and", "record", "in", "the", "loca...
797c6283f5c26d9677c60afa80ac99f8cfd00edc
https://github.com/gmrutilus/rutilus-logger-node/blob/797c6283f5c26d9677c60afa80ac99f8cfd00edc/utils/trackedUsersCache.js#L64-L73
31,878
gmrutilus/rutilus-logger-node
utils/parsing.js
toObjectOrUndefined
function toObjectOrUndefined(input) { let object = input; if (typeof input === 'string') { try { object = JSON.parse(input); } catch (e) {} } if (typeof object === 'object') { return object; } return undefined; }
javascript
function toObjectOrUndefined(input) { let object = input; if (typeof input === 'string') { try { object = JSON.parse(input); } catch (e) {} } if (typeof object === 'object') { return object; } return undefined; }
[ "function", "toObjectOrUndefined", "(", "input", ")", "{", "let", "object", "=", "input", ";", "if", "(", "typeof", "input", "===", "'string'", ")", "{", "try", "{", "object", "=", "JSON", ".", "parse", "(", "input", ")", ";", "}", "catch", "(", "e",...
Accepts anything and tries to parse into a JSON object. If it fails, returns undefined. @param {*} input @returns {{}|[]|undefined}
[ "Accepts", "anything", "and", "tries", "to", "parse", "into", "a", "JSON", "object", ".", "If", "it", "fails", "returns", "undefined", "." ]
797c6283f5c26d9677c60afa80ac99f8cfd00edc
https://github.com/gmrutilus/rutilus-logger-node/blob/797c6283f5c26d9677c60afa80ac99f8cfd00edc/utils/parsing.js#L98-L108
31,879
gmrutilus/rutilus-logger-node
utils/parsing.js
toArrayOrUndefined
function toArrayOrUndefined(str) { if (validation.isArray(str) && str.length < 1) { return undefined; } try { let parsedArray = str; if (typeof str !== 'object') { parsedArray = JSON.parse(str); } if (validation.isArray(parsedArray) && parsedArray.length > 0) { return parsedArray; } else { return undefined; } } catch (e) { return undefined; } }
javascript
function toArrayOrUndefined(str) { if (validation.isArray(str) && str.length < 1) { return undefined; } try { let parsedArray = str; if (typeof str !== 'object') { parsedArray = JSON.parse(str); } if (validation.isArray(parsedArray) && parsedArray.length > 0) { return parsedArray; } else { return undefined; } } catch (e) { return undefined; } }
[ "function", "toArrayOrUndefined", "(", "str", ")", "{", "if", "(", "validation", ".", "isArray", "(", "str", ")", "&&", "str", ".", "length", "<", "1", ")", "{", "return", "undefined", ";", "}", "try", "{", "let", "parsedArray", "=", "str", ";", "if"...
Receives anything and parses it into an array. If it is a stringified array, it gets parsed, stringified and returned; if it is not either of these, it returns undefined @param {*} str @returns {[]|undefined}
[ "Receives", "anything", "and", "parses", "it", "into", "an", "array", ".", "If", "it", "is", "a", "stringified", "array", "it", "gets", "parsed", "stringified", "and", "returned", ";", "if", "it", "is", "not", "either", "of", "these", "it", "returns", "u...
797c6283f5c26d9677c60afa80ac99f8cfd00edc
https://github.com/gmrutilus/rutilus-logger-node/blob/797c6283f5c26d9677c60afa80ac99f8cfd00edc/utils/parsing.js#L251-L273
31,880
gmrutilus/rutilus-logger-node
utils/parsing.js
fromExtra
function fromExtra(value, type) { const t = (type + '').toLowerCase(); switch (t) { case 'number': return toNumberOrUndefined(value); break; case 'boolean': return toTrueOrUndefined(value); break; case 'objectarray': return toObjectArrayOrUndefined(value); break; case 'date': return toDate(value); break; case 'array': return toArrayOrUndefined(value); break; case 'object': return toObjectOrUndefined(value); break; case 'string': default: return toStringOrUndefined(value); break; } }
javascript
function fromExtra(value, type) { const t = (type + '').toLowerCase(); switch (t) { case 'number': return toNumberOrUndefined(value); break; case 'boolean': return toTrueOrUndefined(value); break; case 'objectarray': return toObjectArrayOrUndefined(value); break; case 'date': return toDate(value); break; case 'array': return toArrayOrUndefined(value); break; case 'object': return toObjectOrUndefined(value); break; case 'string': default: return toStringOrUndefined(value); break; } }
[ "function", "fromExtra", "(", "value", ",", "type", ")", "{", "const", "t", "=", "(", "type", "+", "''", ")", ".", "toLowerCase", "(", ")", ";", "switch", "(", "t", ")", "{", "case", "'number'", ":", "return", "toNumberOrUndefined", "(", "value", ")"...
Parses an ExtraInformation piece @param {*} value @param {String} type @returns {*}
[ "Parses", "an", "ExtraInformation", "piece" ]
797c6283f5c26d9677c60afa80ac99f8cfd00edc
https://github.com/gmrutilus/rutilus-logger-node/blob/797c6283f5c26d9677c60afa80ac99f8cfd00edc/utils/parsing.js#L368-L401
31,881
Mostafa-Samir/zip-local
main.js
augment
function augment(_opts) { var opts = _opts || {}; opts.createFolders = opts.createFolders || true; return opts; }
javascript
function augment(_opts) { var opts = _opts || {}; opts.createFolders = opts.createFolders || true; return opts; }
[ "function", "augment", "(", "_opts", ")", "{", "var", "opts", "=", "_opts", "||", "{", "}", ";", "opts", ".", "createFolders", "=", "opts", ".", "createFolders", "||", "true", ";", "return", "opts", ";", "}" ]
augments the options object with a 'createFolders' option
[ "augments", "the", "options", "object", "with", "a", "createFolders", "option" ]
938853444377beccee57865c96b2a7cead3a437b
https://github.com/Mostafa-Samir/zip-local/blob/938853444377beccee57865c96b2a7cead3a437b/main.js#L16-L20
31,882
cmap/morpheus.js
src/algorithm/kmeans.js
cluster
function cluster(points) { // number of clusters has to be smaller or equal the number of data points if (points.length < k) { throw 'Too many clusters'; } // create the initial clusters var clusters = chooseInitialCenters(points); // create an array containing the latest assignment of a point to a cluster // no need to initialize the array, as it will be filled with the first assignment var assignments = new Int32Array(points.length); assignPointsToClusters(clusters, points, assignments); // iterate through updating the centers until we're done var max = (maxIterations < 0) ? Number.MAX_VALUE : maxIterations; for (var count = 0; count < max; count++) { var emptyCluster = false; var newClusters = []; for (var clusterIndex = 0; clusterIndex < clusters.length; clusterIndex++) { var cluster = clusters[clusterIndex]; var newCenter; if (cluster.getPoints().length === 0) { newCenter = getPointFromLargestVarianceCluster(clusters); emptyCluster = true; } else { newCenter = centroidOf(cluster.getPoints(), cluster.getCenter().getPoint().size()); } newClusters.push(new CentroidCluster(newCenter)); } var changes = assignPointsToClusters(newClusters, points, assignments); clusters = newClusters; // if there were no more changes in the point-to-cluster assignment // and there are no empty clusters left, return the current clusters if (changes === 0 && !emptyCluster) { return clusters; } } return clusters; }
javascript
function cluster(points) { // number of clusters has to be smaller or equal the number of data points if (points.length < k) { throw 'Too many clusters'; } // create the initial clusters var clusters = chooseInitialCenters(points); // create an array containing the latest assignment of a point to a cluster // no need to initialize the array, as it will be filled with the first assignment var assignments = new Int32Array(points.length); assignPointsToClusters(clusters, points, assignments); // iterate through updating the centers until we're done var max = (maxIterations < 0) ? Number.MAX_VALUE : maxIterations; for (var count = 0; count < max; count++) { var emptyCluster = false; var newClusters = []; for (var clusterIndex = 0; clusterIndex < clusters.length; clusterIndex++) { var cluster = clusters[clusterIndex]; var newCenter; if (cluster.getPoints().length === 0) { newCenter = getPointFromLargestVarianceCluster(clusters); emptyCluster = true; } else { newCenter = centroidOf(cluster.getPoints(), cluster.getCenter().getPoint().size()); } newClusters.push(new CentroidCluster(newCenter)); } var changes = assignPointsToClusters(newClusters, points, assignments); clusters = newClusters; // if there were no more changes in the point-to-cluster assignment // and there are no empty clusters left, return the current clusters if (changes === 0 && !emptyCluster) { return clusters; } } return clusters; }
[ "function", "cluster", "(", "points", ")", "{", "// number of clusters has to be smaller or equal the number of data points", "if", "(", "points", ".", "length", "<", "k", ")", "{", "throw", "'Too many clusters'", ";", "}", "// create the initial clusters", "var", "cluste...
Runs the K-means++ clustering algorithm. @param points the points to cluster @return a list of clusters containing the points
[ "Runs", "the", "K", "-", "means", "++", "clustering", "algorithm", "." ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/src/algorithm/kmeans.js#L54-L93
31,883
cmap/morpheus.js
src/algorithm/kmeans.js
chooseInitialCenters
function chooseInitialCenters(points) { // Convert to list for indexed access. Make it unmodifiable, since removal of items // would screw up the logic of this method. var pointList = points; // The number of points in the list. var numPoints = pointList.length; // Set the corresponding element in this array to indicate when // elements of pointList are no longer available. var taken = new Array(numPoints); for (var i = 0; i < taken.length; i++) { taken[i] = false; } // The resulting list of initial centers. var resultSet = []; // Choose one center uniformly at random from among the data points. var firstPointIndex = nextInt(numPoints); var firstPoint = pointList[firstPointIndex]; resultSet.push(new CentroidCluster(firstPoint)); // Must mark it as taken taken[firstPointIndex] = true; // To keep track of the minimum distance squared of elements of // pointList to elements of resultSet. var minDistSquared = new Float32Array(numPoints); // Initialize the elements. Since the only point in resultSet is firstPoint, // this is very easy. for (var i = 0; i < numPoints; i++) { if (i !== firstPointIndex) { // That point isn't considered var d = distance(firstPoint, pointList[i]); minDistSquared[i] = d * d; } } while (resultSet.length < k) { // Sum up the squared distances for the points in pointList not // already taken. var distSqSum = 0.0; for (var i = 0; i < numPoints; i++) { if (!taken[i]) { distSqSum += minDistSquared[i]; } } // Add one new data point as a center. Each point x is chosen with // probability proportional to D(x)2 var r = nextDouble() * distSqSum; // The index of the next point to be added to the resultSet. var nextPointIndex = -1; // Sum through the squared min distances again, stopping when // sum >= r. var sum = 0.0; for (var i = 0; i < numPoints; i++) { if (!taken[i]) { sum += minDistSquared[i]; if (sum >= r) { nextPointIndex = i; break; } } } // If it's not set to >= 0, the point wasn't found in the previous // for loop, probably because distances are extremely small. Just pick // the last available point. if (nextPointIndex === -1) { for (var i = numPoints - 1; i >= 0; i--) { if (!taken[i]) { nextPointIndex = i; break; } } } // We found one. if (nextPointIndex >= 0) { var p = pointList[nextPointIndex]; resultSet.push(new CentroidCluster(p)); // Mark it as taken. taken[nextPointIndex] = true; if (resultSet.length < k) { // Now update elements of minDistSquared. We only have to compute // the distance to the new center to do this. for (var j = 0; j < numPoints; j++) { // Only have to worry about the points still not taken. if (!taken[j]) { var d = distance(p, pointList[j]); var d2 = d * d; if (d2 < minDistSquared[j]) { minDistSquared[j] = d2; } } } } } else { // None found -- // Break from the while loop to prevent // an infinite loop. break; } } return resultSet; }
javascript
function chooseInitialCenters(points) { // Convert to list for indexed access. Make it unmodifiable, since removal of items // would screw up the logic of this method. var pointList = points; // The number of points in the list. var numPoints = pointList.length; // Set the corresponding element in this array to indicate when // elements of pointList are no longer available. var taken = new Array(numPoints); for (var i = 0; i < taken.length; i++) { taken[i] = false; } // The resulting list of initial centers. var resultSet = []; // Choose one center uniformly at random from among the data points. var firstPointIndex = nextInt(numPoints); var firstPoint = pointList[firstPointIndex]; resultSet.push(new CentroidCluster(firstPoint)); // Must mark it as taken taken[firstPointIndex] = true; // To keep track of the minimum distance squared of elements of // pointList to elements of resultSet. var minDistSquared = new Float32Array(numPoints); // Initialize the elements. Since the only point in resultSet is firstPoint, // this is very easy. for (var i = 0; i < numPoints; i++) { if (i !== firstPointIndex) { // That point isn't considered var d = distance(firstPoint, pointList[i]); minDistSquared[i] = d * d; } } while (resultSet.length < k) { // Sum up the squared distances for the points in pointList not // already taken. var distSqSum = 0.0; for (var i = 0; i < numPoints; i++) { if (!taken[i]) { distSqSum += minDistSquared[i]; } } // Add one new data point as a center. Each point x is chosen with // probability proportional to D(x)2 var r = nextDouble() * distSqSum; // The index of the next point to be added to the resultSet. var nextPointIndex = -1; // Sum through the squared min distances again, stopping when // sum >= r. var sum = 0.0; for (var i = 0; i < numPoints; i++) { if (!taken[i]) { sum += minDistSquared[i]; if (sum >= r) { nextPointIndex = i; break; } } } // If it's not set to >= 0, the point wasn't found in the previous // for loop, probably because distances are extremely small. Just pick // the last available point. if (nextPointIndex === -1) { for (var i = numPoints - 1; i >= 0; i--) { if (!taken[i]) { nextPointIndex = i; break; } } } // We found one. if (nextPointIndex >= 0) { var p = pointList[nextPointIndex]; resultSet.push(new CentroidCluster(p)); // Mark it as taken. taken[nextPointIndex] = true; if (resultSet.length < k) { // Now update elements of minDistSquared. We only have to compute // the distance to the new center to do this. for (var j = 0; j < numPoints; j++) { // Only have to worry about the points still not taken. if (!taken[j]) { var d = distance(p, pointList[j]); var d2 = d * d; if (d2 < minDistSquared[j]) { minDistSquared[j] = d2; } } } } } else { // None found -- // Break from the while loop to prevent // an infinite loop. break; } } return resultSet; }
[ "function", "chooseInitialCenters", "(", "points", ")", "{", "// Convert to list for indexed access. Make it unmodifiable, since removal of items", "// would screw up the logic of this method.", "var", "pointList", "=", "points", ";", "// The number of points in the list.", "var", "num...
Use K-means++ to choose the initial centers. @param points the points to choose the initial centers from @return the initial centers
[ "Use", "K", "-", "means", "++", "to", "choose", "the", "initial", "centers", "." ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/src/algorithm/kmeans.js#L127-L242
31,884
cmap/morpheus.js
src/algorithm/kmeans.js
centroidOf
function centroidOf(points, dimension) { var centroid = new Float32Array(dimension); for (var i = 0; i < centroid.length; i++) { var sum = 0; var count = 0; for (var pointIndex = 0; pointIndex < points.length; pointIndex++) { var p = points[pointIndex]; var point = p.getPoint(); var val = point.getValue(i); if (!isNaN(val)) { sum += val; count++; } } centroid[i] = (sum / count); } return new PointWrapper(morpheus.VectorUtil.arrayAsVector(centroid)); }
javascript
function centroidOf(points, dimension) { var centroid = new Float32Array(dimension); for (var i = 0; i < centroid.length; i++) { var sum = 0; var count = 0; for (var pointIndex = 0; pointIndex < points.length; pointIndex++) { var p = points[pointIndex]; var point = p.getPoint(); var val = point.getValue(i); if (!isNaN(val)) { sum += val; count++; } } centroid[i] = (sum / count); } return new PointWrapper(morpheus.VectorUtil.arrayAsVector(centroid)); }
[ "function", "centroidOf", "(", "points", ",", "dimension", ")", "{", "var", "centroid", "=", "new", "Float32Array", "(", "dimension", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "centroid", ".", "length", ";", "i", "++", ")", "{", "v...
Computes the centroid for a set of points. @param points the set of points @param dimension the point dimension @return the computed centroid for the set of points
[ "Computes", "the", "centroid", "for", "a", "set", "of", "points", "." ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/src/algorithm/kmeans.js#L354-L371
31,885
cmap/morpheus.js
src/ui/file_picker.js
createPicker
function createPicker() { if (pickerApiLoaded && oauthToken) { var picker = new google.picker.PickerBuilder().addView(google.picker.ViewId.DOCS) .setOAuthToken(oauthToken) .setDeveloperKey(developerKey) .setCallback(pickerCallback) .build(); picker.setVisible(true); $('.picker-dialog-bg').css('z-index', 1052); // make it appear above modals $('.picker-dialog').css('z-index', 1053); } }
javascript
function createPicker() { if (pickerApiLoaded && oauthToken) { var picker = new google.picker.PickerBuilder().addView(google.picker.ViewId.DOCS) .setOAuthToken(oauthToken) .setDeveloperKey(developerKey) .setCallback(pickerCallback) .build(); picker.setVisible(true); $('.picker-dialog-bg').css('z-index', 1052); // make it appear above modals $('.picker-dialog').css('z-index', 1053); } }
[ "function", "createPicker", "(", ")", "{", "if", "(", "pickerApiLoaded", "&&", "oauthToken", ")", "{", "var", "picker", "=", "new", "google", ".", "picker", ".", "PickerBuilder", "(", ")", ".", "addView", "(", "google", ".", "picker", ".", "ViewId", ".",...
Create and render a Picker object for picking user Photos.
[ "Create", "and", "render", "a", "Picker", "object", "for", "picking", "user", "Photos", "." ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/src/ui/file_picker.js#L179-L190
31,886
cmap/morpheus.js
src/util/events.js
function (evtStr, handler) { if (!handler) { throw Error('Handler not specified'); } if (!this.eventListeners) { this.eventListeners = {}; } var events = evtStr.split(' '), len = events.length, n, event, parts, baseEvent, name; /* * loop through types and attach event listeners to each one. eg. 'click * mouseover.namespace mouseout' will create three event bindings */ for (n = 0; n < len; n++) { event = events[n]; parts = event.split('.'); baseEvent = parts[0]; name = parts[1] || ''; // create events array if it doesn't exist if (!this.eventListeners[baseEvent]) { this.eventListeners[baseEvent] = []; } this.eventListeners[baseEvent].push({ name: name, handler: handler }); } return this; }
javascript
function (evtStr, handler) { if (!handler) { throw Error('Handler not specified'); } if (!this.eventListeners) { this.eventListeners = {}; } var events = evtStr.split(' '), len = events.length, n, event, parts, baseEvent, name; /* * loop through types and attach event listeners to each one. eg. 'click * mouseover.namespace mouseout' will create three event bindings */ for (n = 0; n < len; n++) { event = events[n]; parts = event.split('.'); baseEvent = parts[0]; name = parts[1] || ''; // create events array if it doesn't exist if (!this.eventListeners[baseEvent]) { this.eventListeners[baseEvent] = []; } this.eventListeners[baseEvent].push({ name: name, handler: handler }); } return this; }
[ "function", "(", "evtStr", ",", "handler", ")", "{", "if", "(", "!", "handler", ")", "{", "throw", "Error", "(", "'Handler not specified'", ")", ";", "}", "if", "(", "!", "this", ".", "eventListeners", ")", "{", "this", ".", "eventListeners", "=", "{",...
Pass in a string of events delimmited by a space to bind multiple events at once such as 'mousedown mouseup mousemove'. Include a namespace to bind an event by name such as 'click.foobar'. @param {String} evtStr e.g. 'click', 'mousedown touchstart', 'mousedown.foo touchstart.foo' @param {Function} handler The handler function is passed an event object
[ "Pass", "in", "a", "string", "of", "events", "delimmited", "by", "a", "space", "to", "bind", "multiple", "events", "at", "once", "such", "as", "mousedown", "mouseup", "mousemove", ".", "Include", "a", "namespace", "to", "bind", "an", "event", "by", "name",...
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/src/util/events.js#L16-L43
31,887
cmap/morpheus.js
src/util/events.js
function (evtStr, handler) { if (!this.eventListeners) { this.eventListeners = {}; } var events = (evtStr || '').split(' '), len = events.length, n, t, event, parts, baseEvent, name; if (!evtStr) { // remove all events for (t in this.eventListeners) { this._off(t, null, handler); } } for (n = 0; n < len; n++) { event = events[n]; parts = event.split('.'); baseEvent = parts[0]; name = parts[1]; if (baseEvent) { if (this.eventListeners[baseEvent]) { this._off(baseEvent, name, handler); } } else { for (t in this.eventListeners) { this._off(t, name, handler); } } } return this; }
javascript
function (evtStr, handler) { if (!this.eventListeners) { this.eventListeners = {}; } var events = (evtStr || '').split(' '), len = events.length, n, t, event, parts, baseEvent, name; if (!evtStr) { // remove all events for (t in this.eventListeners) { this._off(t, null, handler); } } for (n = 0; n < len; n++) { event = events[n]; parts = event.split('.'); baseEvent = parts[0]; name = parts[1]; if (baseEvent) { if (this.eventListeners[baseEvent]) { this._off(baseEvent, name, handler); } } else { for (t in this.eventListeners) { this._off(t, name, handler); } } } return this; }
[ "function", "(", "evtStr", ",", "handler", ")", "{", "if", "(", "!", "this", ".", "eventListeners", ")", "{", "this", ".", "eventListeners", "=", "{", "}", ";", "}", "var", "events", "=", "(", "evtStr", "||", "''", ")", ".", "split", "(", "' '", ...
Remove event bindings. Pass in a string of event types delimmited by a space to remove multiple event bindings at once such as 'mousedown mouseup mousemove'. include a namespace to remove an event binding by name such as 'click.foobar'. If you only give a name like '.foobar', all events in that namespace will be removed. @param {String} evtStr e.g. 'click', 'mousedown.foo touchstart', '.foobar'
[ "Remove", "event", "bindings", ".", "Pass", "in", "a", "string", "of", "event", "types", "delimmited", "by", "a", "space", "to", "remove", "multiple", "event", "bindings", "at", "once", "such", "as", "mousedown", "mouseup", "mousemove", ".", "include", "a", ...
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/src/util/events.js#L89-L116
31,888
cmap/morpheus.js
src/tools/open_file_tool.js
function (dataset, heatMap, isColumns, sets, setSourceFileName) { var promptTool = {}; var _this = this; promptTool.execute = function (options) { var metadataName = options.input.dataset_field_name; var vector = _this.annotateSets(dataset, isColumns, sets, metadataName, setSourceFileName); heatMap.getProject().trigger('trackChanged', { vectors: [vector], display: ['text'], columns: isColumns }); }; promptTool.toString = function () { return 'Select Fields To Match On'; }; promptTool.gui = function () { return [ { name: 'dataset_field_name', options: morpheus.MetadataUtil.getMetadataNames( isColumns ? dataset.getColumnMetadata() : dataset.getRowMetadata()), type: 'select', value: 'id', required: true }]; }; morpheus.HeatMap.showTool(promptTool, heatMap); }
javascript
function (dataset, heatMap, isColumns, sets, setSourceFileName) { var promptTool = {}; var _this = this; promptTool.execute = function (options) { var metadataName = options.input.dataset_field_name; var vector = _this.annotateSets(dataset, isColumns, sets, metadataName, setSourceFileName); heatMap.getProject().trigger('trackChanged', { vectors: [vector], display: ['text'], columns: isColumns }); }; promptTool.toString = function () { return 'Select Fields To Match On'; }; promptTool.gui = function () { return [ { name: 'dataset_field_name', options: morpheus.MetadataUtil.getMetadataNames( isColumns ? dataset.getColumnMetadata() : dataset.getRowMetadata()), type: 'select', value: 'id', required: true }]; }; morpheus.HeatMap.showTool(promptTool, heatMap); }
[ "function", "(", "dataset", ",", "heatMap", ",", "isColumns", ",", "sets", ",", "setSourceFileName", ")", "{", "var", "promptTool", "=", "{", "}", ";", "var", "_this", "=", "this", ";", "promptTool", ".", "execute", "=", "function", "(", "options", ")", ...
prompt for metadata field name in dataset
[ "prompt", "for", "metadata", "field", "name", "in", "dataset" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/src/tools/open_file_tool.js#L437-L468
31,889
cmap/morpheus.js
src/ui/heat_map.js
function (mode) { this._togglingInfoWindow = true; this.options.tooltipMode = mode; this.$tipInfoWindow.html(''); this.toolbar.$tip.html(''); this.$tipFollow.html('').css({ display: 'none' }); this.toolbar.$tip.css('display', mode === 0 ? '' : 'none'); this.setToolTip(-1, -1); if (this.options.tooltipMode === 1) { this.$tipInfoWindow.dialog('open'); } else { this.$tipInfoWindow.dialog('close'); } this._togglingInfoWindow = false; }
javascript
function (mode) { this._togglingInfoWindow = true; this.options.tooltipMode = mode; this.$tipInfoWindow.html(''); this.toolbar.$tip.html(''); this.$tipFollow.html('').css({ display: 'none' }); this.toolbar.$tip.css('display', mode === 0 ? '' : 'none'); this.setToolTip(-1, -1); if (this.options.tooltipMode === 1) { this.$tipInfoWindow.dialog('open'); } else { this.$tipInfoWindow.dialog('close'); } this._togglingInfoWindow = false; }
[ "function", "(", "mode", ")", "{", "this", ".", "_togglingInfoWindow", "=", "true", ";", "this", ".", "options", ".", "tooltipMode", "=", "mode", ";", "this", ".", "$tipInfoWindow", ".", "html", "(", "''", ")", ";", "this", ".", "toolbar", ".", "$tip",...
Set where the tooltip is shown @param mode 0 is formula bar, 1 is dialog, -1 is no tooltip
[ "Set", "where", "the", "tooltip", "is", "shown" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/src/ui/heat_map.js#L2526-L2542
31,890
cmap/morpheus.js
js/morpheus.js
function (e) { clipboardData.forEach(function (elem) { e.clipboardData.setData(elem.format, elem.data); }); e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); fakeElem.removeEventListener('copy', f); }
javascript
function (e) { clipboardData.forEach(function (elem) { e.clipboardData.setData(elem.format, elem.data); }); e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); fakeElem.removeEventListener('copy', f); }
[ "function", "(", "e", ")", "{", "clipboardData", ".", "forEach", "(", "function", "(", "elem", ")", "{", "e", ".", "clipboardData", ".", "setData", "(", "elem", ".", "format", ",", "elem", ".", "data", ")", ";", "}", ")", ";", "e", ".", "preventDef...
fakeElem.innerHTML = html;
[ "fakeElem", ".", "innerHTML", "=", "html", ";" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/morpheus.js#L562-L571
31,891
cmap/morpheus.js
js/morpheus.js
function (lines) { var regex = /[ ,]+/; // header= <num_data> <num_classes> 1 var header = lines[0].split(regex); if (header.length < 3) { throw new Error('Header line needs three numbers'); } var headerNumbers = []; try { for (var i = 0; i < 3; i++) { headerNumbers[i] = parseInt($.trim(header[i])); } } catch (e) { throw new Error('Header line element ' + i + ' is not a number'); } if (headerNumbers[0] <= 0) { throw new Error( 'Header line missing first number, number of data points'); } if (headerNumbers[1] <= 0) { throw new Error( 'Header line missing second number, number of classes'); } var numClasses = headerNumbers[1]; var numItems = headerNumbers[0]; var classDefinitionLine = lines[1]; classDefinitionLine = classDefinitionLine.substring(classDefinitionLine .indexOf('#') + 1); var classNames = $.trim(classDefinitionLine).split(regex); if (classNames.length < numClasses) { throw new Error('First line specifies ' + numClasses + ' classes, but found ' + classNames.length + '.'); } var dataLine = lines[2]; var assignments = dataLine.split(regex); // convert the assignments to names for (var i = 0; i < assignments.length; i++) { var assignment = $.trim(assignments[i]); var index = parseInt(assignment); var tmp = classNames[index]; if (tmp !== undefined) { assignments[i] = tmp; } } return assignments; }
javascript
function (lines) { var regex = /[ ,]+/; // header= <num_data> <num_classes> 1 var header = lines[0].split(regex); if (header.length < 3) { throw new Error('Header line needs three numbers'); } var headerNumbers = []; try { for (var i = 0; i < 3; i++) { headerNumbers[i] = parseInt($.trim(header[i])); } } catch (e) { throw new Error('Header line element ' + i + ' is not a number'); } if (headerNumbers[0] <= 0) { throw new Error( 'Header line missing first number, number of data points'); } if (headerNumbers[1] <= 0) { throw new Error( 'Header line missing second number, number of classes'); } var numClasses = headerNumbers[1]; var numItems = headerNumbers[0]; var classDefinitionLine = lines[1]; classDefinitionLine = classDefinitionLine.substring(classDefinitionLine .indexOf('#') + 1); var classNames = $.trim(classDefinitionLine).split(regex); if (classNames.length < numClasses) { throw new Error('First line specifies ' + numClasses + ' classes, but found ' + classNames.length + '.'); } var dataLine = lines[2]; var assignments = dataLine.split(regex); // convert the assignments to names for (var i = 0; i < assignments.length; i++) { var assignment = $.trim(assignments[i]); var index = parseInt(assignment); var tmp = classNames[index]; if (tmp !== undefined) { assignments[i] = tmp; } } return assignments; }
[ "function", "(", "lines", ")", "{", "var", "regex", "=", "/", "[ ,]+", "/", ";", "// header= <num_data> <num_classes> 1", "var", "header", "=", "lines", "[", "0", "]", ".", "split", "(", "regex", ")", ";", "if", "(", "header", ".", "length", "<", "3", ...
Parses the cls file. @param lines The lines to read. @throw Error If there is a problem with the data
[ "Parses", "the", "cls", "file", "." ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/morpheus.js#L2607-L2653
31,892
cmap/morpheus.js
js/morpheus.js
function () { var rowCounts = new Uint32Array(nrows); var columnCounts = new Uint32Array(ncols); for (var i = 0; i < nrows; i++) { var obj = matrix[i]; if (obj.values != null) { // trim to size var values = new Uint16Array(obj.length); var indices = new Uint32Array(obj.length); values.set(obj.values.slice(0, obj.length)); indices.set(obj.indices.slice(0, obj.length)); matrix[i] = {values: values, indices: indices}; rowCounts[i] = values.length; for (var j = 0; j < obj.length; j++) { columnCounts[indices[j]] += 1; } } } dataset = new morpheus.Dataset({ rows: nrows, columns: ncols, name: morpheus.Util.getBaseFileName(morpheus.Util .getFileName(fileOrUrl)), array: matrix, dataType: dataType, defaultValue: 0 }); dataset.getRowMetadata().add('count>0').array = rowCounts; dataset.getColumnMetadata().add('count>0').array = columnCounts; }
javascript
function () { var rowCounts = new Uint32Array(nrows); var columnCounts = new Uint32Array(ncols); for (var i = 0; i < nrows; i++) { var obj = matrix[i]; if (obj.values != null) { // trim to size var values = new Uint16Array(obj.length); var indices = new Uint32Array(obj.length); values.set(obj.values.slice(0, obj.length)); indices.set(obj.indices.slice(0, obj.length)); matrix[i] = {values: values, indices: indices}; rowCounts[i] = values.length; for (var j = 0; j < obj.length; j++) { columnCounts[indices[j]] += 1; } } } dataset = new morpheus.Dataset({ rows: nrows, columns: ncols, name: morpheus.Util.getBaseFileName(morpheus.Util .getFileName(fileOrUrl)), array: matrix, dataType: dataType, defaultValue: 0 }); dataset.getRowMetadata().add('count>0').array = rowCounts; dataset.getColumnMetadata().add('count>0').array = columnCounts; }
[ "function", "(", ")", "{", "var", "rowCounts", "=", "new", "Uint32Array", "(", "nrows", ")", ";", "var", "columnCounts", "=", "new", "Uint32Array", "(", "ncols", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "nrows", ";", "i", "++", ...
for each row we store values and indices
[ "for", "each", "row", "we", "store", "values", "and", "indices" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/morpheus.js#L4143-L4168
31,893
cmap/morpheus.js
js/morpheus.js
function (seriesIndex) { this.seriesArrays.splice(seriesIndex, 1); this.seriesNames.splice(seriesIndex, 1); this.seriesDataTypes.splice(seriesIndex, 1); }
javascript
function (seriesIndex) { this.seriesArrays.splice(seriesIndex, 1); this.seriesNames.splice(seriesIndex, 1); this.seriesDataTypes.splice(seriesIndex, 1); }
[ "function", "(", "seriesIndex", ")", "{", "this", ".", "seriesArrays", ".", "splice", "(", "seriesIndex", ",", "1", ")", ";", "this", ".", "seriesNames", ".", "splice", "(", "seriesIndex", ",", "1", ")", ";", "this", ".", "seriesDataTypes", ".", "splice"...
Removes the specified series. @param seriesIndex The series index.
[ "Removes", "the", "specified", "series", "." ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/morpheus.js#L5264-L5268
31,894
cmap/morpheus.js
js/morpheus.js
function (newDatasetMetadataNames, currentDatasetMetadataNames, heatMap, callback) { var tool = {}; tool.execute = function (options) { return options.input; }; tool.toString = function () { return 'Select Fields'; }; tool.gui = function () { var items = [ { name: 'current_dataset_annotation_name', options: currentDatasetMetadataNames, type: 'select', value: 'id', required: true }]; items.push({ name: 'new_dataset_annotation_name', type: 'select', value: 'id', options: newDatasetMetadataNames, required: true }); return items; }; morpheus.HeatMap.showTool(tool, heatMap, callback); }
javascript
function (newDatasetMetadataNames, currentDatasetMetadataNames, heatMap, callback) { var tool = {}; tool.execute = function (options) { return options.input; }; tool.toString = function () { return 'Select Fields'; }; tool.gui = function () { var items = [ { name: 'current_dataset_annotation_name', options: currentDatasetMetadataNames, type: 'select', value: 'id', required: true }]; items.push({ name: 'new_dataset_annotation_name', type: 'select', value: 'id', options: newDatasetMetadataNames, required: true }); return items; }; morpheus.HeatMap.showTool(tool, heatMap, callback); }
[ "function", "(", "newDatasetMetadataNames", ",", "currentDatasetMetadataNames", ",", "heatMap", ",", "callback", ")", "{", "var", "tool", "=", "{", "}", ";", "tool", ".", "execute", "=", "function", "(", "options", ")", "{", "return", "options", ".", "input"...
prompt for metadata field name in dataset and in file
[ "prompt", "for", "metadata", "field", "name", "in", "dataset", "and", "in", "file" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/morpheus.js#L16340-L16368
31,895
cmap/morpheus.js
js/morpheus.js
function () { var items = []; for (var i = 0, length = this.getFilteredItemCount(); i < length; i++) { items.push(this.items[this.convertViewIndexToModel(i)]); } return items; }
javascript
function () { var items = []; for (var i = 0, length = this.getFilteredItemCount(); i < length; i++) { items.push(this.items[this.convertViewIndexToModel(i)]); } return items; }
[ "function", "(", ")", "{", "var", "items", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "length", "=", "this", ".", "getFilteredItemCount", "(", ")", ";", "i", "<", "length", ";", "i", "++", ")", "{", "items", ".", "push", "(", ...
Gets the sorted, visible items
[ "Gets", "the", "sorted", "visible", "items" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/morpheus.js#L23791-L23797
31,896
cmap/morpheus.js
js/jquery.event.drag-2.3.0.js
function( obj ){ // read the interaction data var data = $.data( this, drag.datakey ), // read any passed options opts = obj.data || {}; // count another realted event data.related += 1; // extend data options bound with this event // don't iterate "opts" in case it is a node $.each( drag.defaults, function( key, def ){ if ( opts[ key ] !== undefined ) data[ key ] = opts[ key ]; }); }
javascript
function( obj ){ // read the interaction data var data = $.data( this, drag.datakey ), // read any passed options opts = obj.data || {}; // count another realted event data.related += 1; // extend data options bound with this event // don't iterate "opts" in case it is a node $.each( drag.defaults, function( key, def ){ if ( opts[ key ] !== undefined ) data[ key ] = opts[ key ]; }); }
[ "function", "(", "obj", ")", "{", "// read the interaction data", "var", "data", "=", "$", ".", "data", "(", "this", ",", "drag", ".", "datakey", ")", ",", "// read any passed options", "opts", "=", "obj", ".", "data", "||", "{", "}", ";", "// count anothe...
count bound related events
[ "count", "bound", "related", "events" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/jquery.event.drag-2.3.0.js#L52-L65
31,897
cmap/morpheus.js
js/jquery.event.drag-2.3.0.js
function(){ // check for related events if ( $.data( this, drag.datakey ) ) return; // initialize the drag data with copied defaults var data = $.extend({ related:0 }, drag.defaults ); // store the interaction data $.data( this, drag.datakey, data ); // bind the mousedown event, which starts drag interactions $event.add( this, "touchstart mousedown", drag.init, data ); // prevent image dragging in IE... if ( this.attachEvent ) this.attachEvent("ondragstart", drag.dontstart ); }
javascript
function(){ // check for related events if ( $.data( this, drag.datakey ) ) return; // initialize the drag data with copied defaults var data = $.extend({ related:0 }, drag.defaults ); // store the interaction data $.data( this, drag.datakey, data ); // bind the mousedown event, which starts drag interactions $event.add( this, "touchstart mousedown", drag.init, data ); // prevent image dragging in IE... if ( this.attachEvent ) this.attachEvent("ondragstart", drag.dontstart ); }
[ "function", "(", ")", "{", "// check for related events", "if", "(", "$", ".", "data", "(", "this", ",", "drag", ".", "datakey", ")", ")", "return", ";", "// initialize the drag data with copied defaults", "var", "data", "=", "$", ".", "extend", "(", "{", "r...
configure interaction, capture settings
[ "configure", "interaction", "capture", "settings" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/jquery.event.drag-2.3.0.js#L73-L86
31,898
cmap/morpheus.js
js/jquery.event.drag-2.3.0.js
function(){ var data = $.data( this, drag.datakey ) || {}; // check for related events if ( data.related ) return; // remove the stored data $.removeData( this, drag.datakey ); // remove the mousedown event $event.remove( this, "touchstart mousedown", drag.init ); // enable text selection drag.textselect( true ); // un-prevent image dragging in IE... if ( this.detachEvent ) this.detachEvent("ondragstart", drag.dontstart ); }
javascript
function(){ var data = $.data( this, drag.datakey ) || {}; // check for related events if ( data.related ) return; // remove the stored data $.removeData( this, drag.datakey ); // remove the mousedown event $event.remove( this, "touchstart mousedown", drag.init ); // enable text selection drag.textselect( true ); // un-prevent image dragging in IE... if ( this.detachEvent ) this.detachEvent("ondragstart", drag.dontstart ); }
[ "function", "(", ")", "{", "var", "data", "=", "$", ".", "data", "(", "this", ",", "drag", ".", "datakey", ")", "||", "{", "}", ";", "// check for related events", "if", "(", "data", ".", "related", ")", "return", ";", "// remove the stored data", "$", ...
destroy configured interaction
[ "destroy", "configured", "interaction" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/jquery.event.drag-2.3.0.js#L89-L103
31,899
cmap/morpheus.js
js/jquery.event.drag-2.3.0.js
function( event ){ // sorry, only one touch at a time if ( drag.touched ) return; // the drag/drop interaction data var dd = event.data, results; // check the which directive if ( event.which != 0 && dd.which > 0 && event.which != dd.which ) return; // check for suppressed selector if ( $( event.target ).is( dd.not ) ) return; // check for handle selector if ( dd.handle && !$( event.target ).closest( dd.handle, event.currentTarget ).length ) return; drag.touched = event.type == 'touchstart' ? this : null; dd.propagates = 1; dd.mousedown = this; dd.interactions = [ drag.interaction( this, dd ) ]; dd.target = event.target; dd.pageX = event.pageX; dd.pageY = event.pageY; dd.dragging = null; // handle draginit event... results = drag.hijack( event, "draginit", dd ); // early cancel if ( !dd.propagates ) return; // flatten the result set results = drag.flatten( results ); // insert new interaction elements if ( results && results.length ){ dd.interactions = []; $.each( results, function(){ dd.interactions.push( drag.interaction( this, dd ) ); }); } // remember how many interactions are propagating dd.propagates = dd.interactions.length; // locate and init the drop targets if ( dd.drop !== false && $special.drop ) $special.drop.handler( event, dd ); // disable text selection drag.textselect( false ); // bind additional events... if ( drag.touched ) $event.add( drag.touched, "touchmove touchend", drag.handler, dd ); else $event.add( document, "mousemove mouseup", drag.handler, dd ); // helps prevent text selection or scrolling if ( !drag.touched || dd.live ) return false; }
javascript
function( event ){ // sorry, only one touch at a time if ( drag.touched ) return; // the drag/drop interaction data var dd = event.data, results; // check the which directive if ( event.which != 0 && dd.which > 0 && event.which != dd.which ) return; // check for suppressed selector if ( $( event.target ).is( dd.not ) ) return; // check for handle selector if ( dd.handle && !$( event.target ).closest( dd.handle, event.currentTarget ).length ) return; drag.touched = event.type == 'touchstart' ? this : null; dd.propagates = 1; dd.mousedown = this; dd.interactions = [ drag.interaction( this, dd ) ]; dd.target = event.target; dd.pageX = event.pageX; dd.pageY = event.pageY; dd.dragging = null; // handle draginit event... results = drag.hijack( event, "draginit", dd ); // early cancel if ( !dd.propagates ) return; // flatten the result set results = drag.flatten( results ); // insert new interaction elements if ( results && results.length ){ dd.interactions = []; $.each( results, function(){ dd.interactions.push( drag.interaction( this, dd ) ); }); } // remember how many interactions are propagating dd.propagates = dd.interactions.length; // locate and init the drop targets if ( dd.drop !== false && $special.drop ) $special.drop.handler( event, dd ); // disable text selection drag.textselect( false ); // bind additional events... if ( drag.touched ) $event.add( drag.touched, "touchmove touchend", drag.handler, dd ); else $event.add( document, "mousemove mouseup", drag.handler, dd ); // helps prevent text selection or scrolling if ( !drag.touched || dd.live ) return false; }
[ "function", "(", "event", ")", "{", "// sorry, only one touch at a time", "if", "(", "drag", ".", "touched", ")", "return", ";", "// the drag/drop interaction data", "var", "dd", "=", "event", ".", "data", ",", "results", ";", "// check the which directive", "if", ...
initialize the interaction
[ "initialize", "the", "interaction" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/jquery.event.drag-2.3.0.js#L106-L159