repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
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", "===", "'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", ";", "}", ")", ";", "}" ]
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
train
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
train
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
train
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
train
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
train
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
train
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", ";", "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", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
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
train
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", ")", "{", "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", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
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
train
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", ":", "options", ".", "details", ",", "code", ":", "options", ".", "code", "||", "options", ".", "status", "||", "500", ",", "toString", ":", "function", "(", ")", "{", "return", "this", ".", "name", "+", "' ['", "+", "this", ".", "status", "+", "'] - '", "+", "this", ".", "message", ";", "}", "}", ";", "}" ]
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
train
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", ")", ";", "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", ")", ";", "}", ")", ";", "}" ]
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
train
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", "[", "key", "]", "==", "null", ")", "?", "trueVal", ":", "falseVal", ";", "}" ]
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
train
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", "]", "]", "=", "{", "'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", ";", "}" ]
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
train
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", "(", "prop", "&&", "prop", "[", "behavior", "]", "!==", "undefined", ")", "{", "return", "prop", "[", "behavior", "]", ";", "}", "else", "{", "if", "(", "defaultProp", "&&", "defaultProp", "[", "behavior", "]", "!==", "undefined", ")", "{", "return", "defaultProp", "[", "behavior", "]", ";", "}", "}", "}", "}" ]
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
train
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", ",", "12", ")", "+", "'-'", "+", "uuid", ".", "substring", "(", "12", ",", "16", ")", "+", "'-'", "+", "uuid", ".", "substring", "(", "16", ",", "20", ")", "+", "'-'", "+", "uuid", ".", "substring", "(", "20", ")", ")", ";", "}" ]
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
train
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", "]", ";", "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", ")", ";", "}" ]
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
train
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", "(", "!", "thresholds", ".", "length", ")", "{", "result", "=", "[", "0", "]", ";", "}", "return", "result", ".", "map", "(", "threshold", "=>", "{", "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", "(", ")", ";", "}" ]
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
train
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", ")", "|", "(", "(", "!", "!", "this", ".", "triangle", ".", "lengthCounter", ")", "<<", "2", ")", "|", "(", "(", "!", "!", "this", ".", "noise", ".", "lengthCounter", ")", "<<", "3", ")", "|", "(", "(", "!", "!", "this", ".", "dmc", ".", "sampleBytesLeft", ")", "<<", "4", ")", ")", ";", "}" ]
Read channel status.
[ "Read", "channel", "status", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/apu/index.js#L53-L61
train
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", ")", "{", "this", ".", "pulse1", ".", "writeRegister", "(", "address", ",", "value", ")", ";", "}", "else", "if", "(", "address", "<", "0x8", ")", "{", "this", ".", "pulse2", ".", "writeRegister", "(", "address", "-", "0x4", ",", "value", ")", ";", "}", "else", "if", "(", "address", "<", "0xc", ")", "{", "this", ".", "triangle", ".", "writeRegister", "(", "address", "-", "0x8", ",", "value", ")", ";", "}", "else", "if", "(", "address", "<", "0x10", ")", "{", "this", ".", "noise", ".", "writeRegister", "(", "address", "-", "0xc", ",", "value", ")", ";", "}", "else", "if", "(", "address", "<", "0x14", ")", "{", "this", ".", "dmc", ".", "writeRegister", "(", "address", "-", "0x10", ",", "value", ")", ";", "}", "else", "if", "(", "address", "===", "0x15", ")", "{", "this", ".", "writeStatus", "(", "value", ")", ";", "}", "else", "if", "(", "address", "===", "0x17", ")", "{", "this", ".", "frameCounterMode", "=", "+", "!", "!", "(", "value", "&", "0x80", ")", ";", "this", ".", "frameCounterInterrupt", "=", "!", "(", "value", "&", "0x40", ")", ";", "this", ".", "cycles", "=", "0", ";", "if", "(", "this", ".", "frameCounterMode", ")", "{", "this", ".", "doQuarterFrame", "(", ")", ";", "this", ".", "doHalfFrame", "(", ")", ";", "}", "}", "}" ]
Write to APU registers.
[ "Write", "to", "APU", "registers", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/apu/index.js#L66-L107
train
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", ".", "cycles", ")", "{", "case", "7457", ":", "case", "14915", ":", "this", ".", "doHalfFrame", "(", ")", ";", "break", ";", "}", "if", "(", "this", ".", "cycles", ">=", "14915", ")", "{", "this", ".", "cycles", "=", "0", ";", "if", "(", "this", ".", "frameCounterInterrupt", ")", "{", "this", ".", "system", ".", "cpu", ".", "requestIRQ", "(", ")", ";", "}", "}", "}" ]
Tick for framecounter mode 0.
[ "Tick", "for", "framecounter", "mode", "0", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/apu/index.js#L141-L165
train
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", ",", "pulseOut", "=", "0", ";", "this", ".", "pulse1", ".", "doTimer", "(", ")", ";", "this", ".", "pulse2", ".", "doTimer", "(", ")", ";", "this", ".", "triangle", ".", "doTimer", "(", ")", ";", "this", ".", "noise", ".", "doTimer", "(", ")", ";", "this", ".", "dmc", ".", "doTimer", "(", ")", ";", "if", "(", "this", ".", "output", ".", "enabled", ")", "{", "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", ";", "}", "}" ]
Update output sample.
[ "Update", "output", "sample", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/apu/index.js#L221-L244
train
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", "autorun", "===", "\"function\"", ")", "{", "autorun", "(", ")", ";", "}", "else", "if", "(", "autorun", "===", "true", ")", "{", "self", ".", "run", "(", ")", ";", "}", "}", ")", ";", "}" ]
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
train
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", ")", "{", "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", ";", "}" ]
Turn on and run emulator.
[ "Turn", "on", "and", "run", "emulator", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/index.js#L68-L85
train
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", "=", "!", "!", "(", "t", "&", "0x80", ")", ";", "flagC", "=", "(", "t", ">", "255", ")", ";", "flagZ", "=", "!", "(", "t", "&", "0xff", ")", ";", "writeA", "(", "t", "&", "0xff", ")", ";", "}" ]
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
train
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", ")", "{", "burn", "(", "1", ")", ";", "if", "(", "offset", "&", "0x80", ")", "{", "offset", "=", "-", "complement", "(", "offset", ")", ";", "}", "PC", "+=", "offset", ";", "curHigh", "=", "PC", "&", "HIGH", ";", "if", "(", "prevHigh", "!==", "curHigh", ")", "{", "burn", "(", "1", ")", ";", "}", "}", "}" ]
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
train
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", "=", "+", "(", "value", ">=", "readValue", ")", ";", "flagZ", "=", "+", "(", "t", "===", "0", ")", ";", "}" ]
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
train
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
train
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", "=", "!", "!", "(", "P", "&", "0x08", ")", ";", "flagI", "=", "!", "!", "(", "P", "&", "0x04", ")", ";", "flagZ", "=", "!", "!", "(", "P", "&", "0x02", ")", ";", "flagC", "=", "!", "!", "(", "P", "&", "0x01", ")", ";", "}" ]
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
train
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", ")", ";", "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", ")", ";", "}" ]
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
train
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", "=", "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", ";", "}" ]
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
train
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", ".", "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", "(", ")", ";", "}", "}" ]
A single PPU tick.
[ "A", "single", "PPU", "tick", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/ppu/index.js#L167-L192
train
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", ")", ";", "}", "timeoutID", "=", "setTimeout", "(", "(", ")", "=>", "{", "timeoutID", "=", "false", ";", "callback", ".", "apply", "(", "this", ",", "args", ")", ";", "}", ",", "delay", ")", ";", "}", ";", "}" ]
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
train
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", ".", "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", ")", ";", "}", "}", "}" ]
Initialize total input config.
[ "Initialize", "total", "input", "config", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/input/index.js#L56-L74
train
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", ".", "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", "(", ")", ";", "}", "}" ]
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
train
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", "&", "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", "(", ")", ";", "}" ]
Fetch background tile data.
[ "Fetch", "background", "tile", "data", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/ppu/background.js#L168-L186
train
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", "|", "(", "i", "&", "0x0c00", ")", "|", "(", "(", "i", ">>", "4", ")", "&", "0x38", ")", "|", "(", "(", "i", ">>", "2", ")", "&", "0x07", ")", ";", "}", "return", "result", ";", "}" ]
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
train
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", "(", "i", "&", "0x2", ")", "{", "mask", "<<=", "2", ";", "}", "if", "(", "i", "&", "0x40", ")", "{", "mask", "<<=", "4", ";", "}", "result", "[", "i", "]", "=", "mask", ";", "}", "return", "result", ";", "}" ]
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
train
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", ";", "}", "for", "(", "i", "=", "327", ";", "i", "<", "336", ";", "i", "+=", "8", ")", "{", "result", "[", "i", "]", "=", "1", ";", "}", "return", "result", ";", "}" ]
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
train
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", "]", ",", "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", ")", ";", "if", "(", "this", ".", "spriteSize", "===", "16", ")", "{", "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", ";", "}" ]
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
train
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", ";", "if", "(", "this", ".", "playing", ")", "{", "this", ".", "playing", ".", "stop", "(", ")", ";", "}", "this", ".", "bufferSource", ".", "buffer", "=", "this", ".", "buffer", ";", "this", ".", "playing", "=", "this", ".", "bufferSource", ";", "this", ".", "playing", ".", "start", "(", "0", ")", ";", "this", ".", "initBuffer", "(", ")", ";", "}", "}" ]
Write sample to buffer.
[ "Write", "sample", "to", "buffer", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/audiooutput.js#L16-L32
train
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", "(", ")", ";", "this", ".", "gainNode", ".", "connect", "(", "this", ".", "context", ".", "destination", ")", ";", "}" ]
Initialize audio context.
[ "Initialize", "audio", "context", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/audiooutput.js#L74-L79
train
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", ".", "buffer", ".", "getChannelData", "(", "0", ")", ";", "this", ".", "bufferSource", "=", "this", ".", "context", ".", "createBufferSource", "(", ")", ";", "this", ".", "bufferSource", ".", "connect", "(", "this", ".", "gainNode", ")", ";", "}" ]
Initialize audio buffer.
[ "Initialize", "audio", "buffer", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/audiooutput.js#L84-L90
train
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", ")", "||", "!", "container", ".", "contains", "(", "target", ")", ")", ";", "}" ]
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
train
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", ".", "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", ")", ";", "}" ]
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
train
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", "(", "!", "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", ";", "}" ]
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
train
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", "&&", "this", ".", "header", "[", "1", "]", "===", "0x45", "&&", "this", ".", "header", "[", "2", "]", "===", "0x53", "&&", "this", ".", "header", "[", "3", "]", "===", "0x1a", ")", ")", "{", "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", ")", "{", "throw", "new", "Error", "(", "\"Trained ROMs are not supported\"", ")", ";", "}", "}" ]
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
train
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", "&", "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", ")", ";", "}" ]
Init header flags.
[ "Init", "header", "flags", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cartridge.js#L64-L80
train
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", "=", "new", "Uint8Array", "(", "0x2000", ")", ";", "this", ".", "chrRead", ".", "set", "(", "this", ".", "chrData", ".", "subarray", "(", "0", ",", "0x2000", ")", ")", ";", "mappers", ".", "init", "(", "this", ")", ";", "}" ]
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
train
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", ")", "{", "this", ".", "ramData", "[", "address", "-", "0x6000", "]", "=", "value", ";", "}", "return", ";", "}" ]
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", "be", "written", "to", ".", "This", "method", "implements", "the", "most", "common", "mapper", "register", "locations", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/cartridge.js#L152-L161
train
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", ".", "set", "(", "bankData", ",", "address", "-", "0x8000", ")", ";", "}" ]
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
train
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", ".", "set", "(", "bankData", ",", "address", ")", ";", "}" ]
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
train
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", ")", "{", "address", "-=", "0x400", ";", "}", "break", ";", "case", "VERTICAL", ":", "address", "&=", "0x07ff", ";", "break", ";", "case", "FOUR_SCREEN", ":", "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", ";", "}" ]
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
train
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", "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", ";", "}" ]
Initialize the video output.
[ "Initialize", "the", "video", "output", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/renderer/canvas2d.js#L52-L65
train
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", ")", ";", "for", "(", "color", "=", "0", ";", "color", "<", "3", ";", "color", "+=", "1", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "192", ";", "i", "+=", "3", ")", "{", "splitPalette", "[", "address", "]", "=", "view", "[", "i", "+", "color", "]", ";", "address", "+=", "1", ";", "}", "}", "this", ".", "palette", "=", "view", ";", "this", ".", "reds", "=", "new", "Uint8Array", "(", "buffer", ",", "0", ",", "0x40", ")", ";", "this", ".", "greens", "=", "new", "Uint8Array", "(", "buffer", ",", "0x40", ",", "0x40", ")", ";", "this", ".", "blues", "=", "new", "Uint8Array", "(", "buffer", ",", "0x80", ",", "0x40", ")", ";", "}" ]
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
train
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", ")", ";", "this", ".", "prioBuffer", ".", "set", "(", "priorities", ",", "this", ".", "index", ")", ";", "this", ".", "index", "+=", "256", ";", "}" ]
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
train
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", "if", "(", "Canvas2DRenderer", ".", "isSupported", "(", "this", ".", "el", ")", ")", "{", "this", ".", "renderer", "=", "new", "Canvas2DRenderer", "(", "this", ".", "el", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"No supported renderer!\"", ")", ";", "}", "}" ]
Initialize renderer.
[ "Initialize", "renderer", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/videooutput.js#L85-L93
train
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", ".", "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", ")", ";", "}" ]
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
train
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", ";", "this", ".", "bgTexture", "=", "createTexture", "(", "0", ",", "\"bgTexture\"", ")", ";", "this", ".", "spriteTexture", "=", "createTexture", "(", "1", ",", "\"spriteTexture\"", ")", ";", "this", ".", "prioTexture", "=", "createTexture", "(", "2", ",", "\"prioTexture\"", ")", ";", "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", ";", "}", "}" ]
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
train
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;\"", ",", "\"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));\"", ",", "\"if ( colorIndex > 0.0 ) {\"", ",", "\"gl_FragColor = color;\"", ",", "\"} else {\"", ",", "\"gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\"", ",", "\"gl_FragColor = bgColor;\"", ",", "\"}\"", ",", "\"}\"", "]", ".", "join", "(", "\"\\n\"", ")", ";", "\\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", ")", ";", "}" ]
Initialize WebGL shaders.
[ "Initialize", "WebGL", "shaders", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/renderer/webgl.js#L125-L176
train
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", "(", "program", ",", "this", ".", "fragmentShader", ")", ";", "gl", ".", "linkProgram", "(", "program", ")", ";", "gl", ".", "useProgram", "(", "program", ")", ";", "this", ".", "program", "=", "program", ";", "}" ]
Initialize WebGL program.
[ "Initialize", "WebGL", "program", "." ]
bc11a7c34f3ccf45179bf16c0241b698b36df980
https://github.com/koenkivits/nesnes/blob/bc11a7c34f3ccf45179bf16c0241b698b36df980/system/output/renderer/webgl.js#L181-L191
train
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", ",", "}", ",", "{", "$set", ":", "{", "info", ":", "info", ",", "}", "}", ",", "{", "upsert", ":", "true", "}", ",", "(", "err", ")", "=>", "{", "if", "(", "errorHandler", ".", "dbErrorCatcher", "(", "err", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", ")", ";", "}" ]
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
train
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", ")", "{", "if", "(", "sessionIdCache", "[", "id", "]", ")", "{", "cb", "(", "true", ")", ";", "}", "else", "{", "db", ".", "collection", "(", "'trackedUsersCache'", ")", ".", "find", "(", "{", "_id", ":", "id", "}", ")", ".", "toArray", "(", "(", "err", ",", "docs", ")", "=>", "{", "if", "(", "errorHandler", ".", "dbErrorCatcher", "(", "err", ")", ")", "{", "return", ";", "}", "if", "(", "!", "docs", "||", "docs", ".", "length", "<", "1", ")", "{", "cb", "(", "false", ")", ";", "}", "else", "{", "sessionIdCache", "[", "id", "]", "=", "docs", "[", "0", "]", ".", "info", ";", "cb", "(", "true", ")", ";", "}", "}", ")", ";", "}", "}" ]
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
train
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", "local", "cache" ]
797c6283f5c26d9677c60afa80ac99f8cfd00edc
https://github.com/gmrutilus/rutilus-logger-node/blob/797c6283f5c26d9677c60afa80ac99f8cfd00edc/utils/trackedUsersCache.js#L64-L73
train
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", ")", "{", "}", "}", "if", "(", "typeof", "object", "===", "'object'", ")", "{", "return", "object", ";", "}", "return", "undefined", ";", "}" ]
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
train
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", "(", "typeof", "str", "!==", "'object'", ")", "{", "parsedArray", "=", "JSON", ".", "parse", "(", "str", ")", ";", "}", "if", "(", "validation", ".", "isArray", "(", "parsedArray", ")", "&&", "parsedArray", ".", "length", ">", "0", ")", "{", "return", "parsedArray", ";", "}", "else", "{", "return", "undefined", ";", "}", "}", "catch", "(", "e", ")", "{", "return", "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 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", "undefined" ]
797c6283f5c26d9677c60afa80ac99f8cfd00edc
https://github.com/gmrutilus/rutilus-logger-node/blob/797c6283f5c26d9677c60afa80ac99f8cfd00edc/utils/parsing.js#L251-L273
train
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", ")", ";", "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", ";", "}", "}" ]
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
train
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
train
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", ")", "{", "if", "(", "points", ".", "length", "<", "k", ")", "{", "throw", "'Too many clusters'", ";", "}", "var", "clusters", "=", "chooseInitialCenters", "(", "points", ")", ";", "var", "assignments", "=", "new", "Int32Array", "(", "points", ".", "length", ")", ";", "assignPointsToClusters", "(", "clusters", ",", "points", ",", "assignments", ")", ";", "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", "(", "changes", "===", "0", "&&", "!", "emptyCluster", ")", "{", "return", "clusters", ";", "}", "}", "return", "clusters", ";", "}" ]
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
train
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", ")", "{", "var", "pointList", "=", "points", ";", "var", "numPoints", "=", "pointList", ".", "length", ";", "var", "taken", "=", "new", "Array", "(", "numPoints", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "taken", ".", "length", ";", "i", "++", ")", "{", "taken", "[", "i", "]", "=", "false", ";", "}", "var", "resultSet", "=", "[", "]", ";", "var", "firstPointIndex", "=", "nextInt", "(", "numPoints", ")", ";", "var", "firstPoint", "=", "pointList", "[", "firstPointIndex", "]", ";", "resultSet", ".", "push", "(", "new", "CentroidCluster", "(", "firstPoint", ")", ")", ";", "taken", "[", "firstPointIndex", "]", "=", "true", ";", "var", "minDistSquared", "=", "new", "Float32Array", "(", "numPoints", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPoints", ";", "i", "++", ")", "{", "if", "(", "i", "!==", "firstPointIndex", ")", "{", "var", "d", "=", "distance", "(", "firstPoint", ",", "pointList", "[", "i", "]", ")", ";", "minDistSquared", "[", "i", "]", "=", "d", "*", "d", ";", "}", "}", "while", "(", "resultSet", ".", "length", "<", "k", ")", "{", "var", "distSqSum", "=", "0.0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPoints", ";", "i", "++", ")", "{", "if", "(", "!", "taken", "[", "i", "]", ")", "{", "distSqSum", "+=", "minDistSquared", "[", "i", "]", ";", "}", "}", "var", "r", "=", "nextDouble", "(", ")", "*", "distSqSum", ";", "var", "nextPointIndex", "=", "-", "1", ";", "var", "sum", "=", "0.0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numPoints", ";", "i", "++", ")", "{", "if", "(", "!", "taken", "[", "i", "]", ")", "{", "sum", "+=", "minDistSquared", "[", "i", "]", ";", "if", "(", "sum", ">=", "r", ")", "{", "nextPointIndex", "=", "i", ";", "break", ";", "}", "}", "}", "if", "(", "nextPointIndex", "===", "-", "1", ")", "{", "for", "(", "var", "i", "=", "numPoints", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "!", "taken", "[", "i", "]", ")", "{", "nextPointIndex", "=", "i", ";", "break", ";", "}", "}", "}", "if", "(", "nextPointIndex", ">=", "0", ")", "{", "var", "p", "=", "pointList", "[", "nextPointIndex", "]", ";", "resultSet", ".", "push", "(", "new", "CentroidCluster", "(", "p", ")", ")", ";", "taken", "[", "nextPointIndex", "]", "=", "true", ";", "if", "(", "resultSet", ".", "length", "<", "k", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "numPoints", ";", "j", "++", ")", "{", "if", "(", "!", "taken", "[", "j", "]", ")", "{", "var", "d", "=", "distance", "(", "p", ",", "pointList", "[", "j", "]", ")", ";", "var", "d2", "=", "d", "*", "d", ";", "if", "(", "d2", "<", "minDistSquared", "[", "j", "]", ")", "{", "minDistSquared", "[", "j", "]", "=", "d2", ";", "}", "}", "}", "}", "}", "else", "{", "break", ";", "}", "}", "return", "resultSet", ";", "}" ]
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
train
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", "++", ")", "{", "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", ")", ")", ";", "}" ]
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
train
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", ".", "DOCS", ")", ".", "setOAuthToken", "(", "oauthToken", ")", ".", "setDeveloperKey", "(", "developerKey", ")", ".", "setCallback", "(", "pickerCallback", ")", ".", "build", "(", ")", ";", "picker", ".", "setVisible", "(", "true", ")", ";", "$", "(", "'.picker-dialog-bg'", ")", ".", "css", "(", "'z-index'", ",", "1052", ")", ";", "$", "(", "'.picker-dialog'", ")", ".", "css", "(", "'z-index'", ",", "1053", ")", ";", "}", "}" ]
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
train
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", "=", "{", "}", ";", "}", "var", "events", "=", "evtStr", ".", "split", "(", "' '", ")", ",", "len", "=", "events", ".", "length", ",", "n", ",", "event", ",", "parts", ",", "baseEvent", ",", "name", ";", "for", "(", "n", "=", "0", ";", "n", "<", "len", ";", "n", "++", ")", "{", "event", "=", "events", "[", "n", "]", ";", "parts", "=", "event", ".", "split", "(", "'.'", ")", ";", "baseEvent", "=", "parts", "[", "0", "]", ";", "name", "=", "parts", "[", "1", "]", "||", "''", ";", "if", "(", "!", "this", ".", "eventListeners", "[", "baseEvent", "]", ")", "{", "this", ".", "eventListeners", "[", "baseEvent", "]", "=", "[", "]", ";", "}", "this", ".", "eventListeners", "[", "baseEvent", "]", ".", "push", "(", "{", "name", ":", "name", ",", "handler", ":", "handler", "}", ")", ";", "}", "return", "this", ";", "}" ]
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", "such", "as", "click", ".", "foobar", "." ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/src/util/events.js#L16-L43
train
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", "(", "' '", ")", ",", "len", "=", "events", ".", "length", ",", "n", ",", "t", ",", "event", ",", "parts", ",", "baseEvent", ",", "name", ";", "if", "(", "!", "evtStr", ")", "{", "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", ";", "}" ]
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", "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", "." ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/src/util/events.js#L89-L116
train
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", ")", "{", "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", ")", ";", "}" ]
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
train
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", ".", "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", ";", "}" ]
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
train
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", ".", "preventDefault", "(", ")", ";", "e", ".", "stopPropagation", "(", ")", ";", "e", ".", "stopImmediatePropagation", "(", ")", ";", "fakeElem", ".", "removeEventListener", "(", "'copy'", ",", "f", ")", ";", "}" ]
fakeElem.innerHTML = html;
[ "fakeElem", ".", "innerHTML", "=", "html", ";" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/morpheus.js#L562-L571
train
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", "=", "/", "[ ,]+", "/", ";", "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", ")", ";", "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", ";", "}" ]
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
train
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", "++", ")", "{", "var", "obj", "=", "matrix", "[", "i", "]", ";", "if", "(", "obj", ".", "values", "!=", "null", ")", "{", "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", ";", "}" ]
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
train
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", "(", "seriesIndex", ",", "1", ")", ";", "}" ]
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
train
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", ";", "}", ";", "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", ")", ";", "}" ]
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
train
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", "(", "this", ".", "items", "[", "this", ".", "convertViewIndexToModel", "(", "i", ")", "]", ")", ";", "}", "return", "items", ";", "}" ]
Gets the sorted, visible items
[ "Gets", "the", "sorted", "visible", "items" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/morpheus.js#L23791-L23797
train
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", ")", "{", "var", "data", "=", "$", ".", "data", "(", "this", ",", "drag", ".", "datakey", ")", ",", "opts", "=", "obj", ".", "data", "||", "{", "}", ";", "data", ".", "related", "+=", "1", ";", "$", ".", "each", "(", "drag", ".", "defaults", ",", "function", "(", "key", ",", "def", ")", "{", "if", "(", "opts", "[", "key", "]", "!==", "undefined", ")", "data", "[", "key", "]", "=", "opts", "[", "key", "]", ";", "}", ")", ";", "}" ]
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
train
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", "(", ")", "{", "if", "(", "$", ".", "data", "(", "this", ",", "drag", ".", "datakey", ")", ")", "return", ";", "var", "data", "=", "$", ".", "extend", "(", "{", "related", ":", "0", "}", ",", "drag", ".", "defaults", ")", ";", "$", ".", "data", "(", "this", ",", "drag", ".", "datakey", ",", "data", ")", ";", "$event", ".", "add", "(", "this", ",", "\"touchstart mousedown\"", ",", "drag", ".", "init", ",", "data", ")", ";", "if", "(", "this", ".", "attachEvent", ")", "this", ".", "attachEvent", "(", "\"ondragstart\"", ",", "drag", ".", "dontstart", ")", ";", "}" ]
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
train
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", ")", "||", "{", "}", ";", "if", "(", "data", ".", "related", ")", "return", ";", "$", ".", "removeData", "(", "this", ",", "drag", ".", "datakey", ")", ";", "$event", ".", "remove", "(", "this", ",", "\"touchstart mousedown\"", ",", "drag", ".", "init", ")", ";", "drag", ".", "textselect", "(", "true", ")", ";", "if", "(", "this", ".", "detachEvent", ")", "this", ".", "detachEvent", "(", "\"ondragstart\"", ",", "drag", ".", "dontstart", ")", ";", "}" ]
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
train
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", ")", "{", "if", "(", "drag", ".", "touched", ")", "return", ";", "var", "dd", "=", "event", ".", "data", ",", "results", ";", "if", "(", "event", ".", "which", "!=", "0", "&&", "dd", ".", "which", ">", "0", "&&", "event", ".", "which", "!=", "dd", ".", "which", ")", "return", ";", "if", "(", "$", "(", "event", ".", "target", ")", ".", "is", "(", "dd", ".", "not", ")", ")", "return", ";", "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", ";", "results", "=", "drag", ".", "hijack", "(", "event", ",", "\"draginit\"", ",", "dd", ")", ";", "if", "(", "!", "dd", ".", "propagates", ")", "return", ";", "results", "=", "drag", ".", "flatten", "(", "results", ")", ";", "if", "(", "results", "&&", "results", ".", "length", ")", "{", "dd", ".", "interactions", "=", "[", "]", ";", "$", ".", "each", "(", "results", ",", "function", "(", ")", "{", "dd", ".", "interactions", ".", "push", "(", "drag", ".", "interaction", "(", "this", ",", "dd", ")", ")", ";", "}", ")", ";", "}", "dd", ".", "propagates", "=", "dd", ".", "interactions", ".", "length", ";", "if", "(", "dd", ".", "drop", "!==", "false", "&&", "$special", ".", "drop", ")", "$special", ".", "drop", ".", "handler", "(", "event", ",", "dd", ")", ";", "drag", ".", "textselect", "(", "false", ")", ";", "if", "(", "drag", ".", "touched", ")", "$event", ".", "add", "(", "drag", ".", "touched", ",", "\"touchmove touchend\"", ",", "drag", ".", "handler", ",", "dd", ")", ";", "else", "$event", ".", "add", "(", "document", ",", "\"mousemove mouseup\"", ",", "drag", ".", "handler", ",", "dd", ")", ";", "if", "(", "!", "drag", ".", "touched", "||", "dd", ".", "live", ")", "return", "false", ";", "}" ]
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
train
cmap/morpheus.js
js/jquery.event.drag-2.3.0.js
function( elem, dd ){ var offset = (elem && elem.ownerDocument) ? $( elem )[ dd.relative ? "position" : "offset" ]() || { top:0, left:0 } : { top: 0, left: 0 }; return { drag: elem, callback: new drag.callback(), droppable: [], offset: offset }; }
javascript
function( elem, dd ){ var offset = (elem && elem.ownerDocument) ? $( elem )[ dd.relative ? "position" : "offset" ]() || { top:0, left:0 } : { top: 0, left: 0 }; return { drag: elem, callback: new drag.callback(), droppable: [], offset: offset }; }
[ "function", "(", "elem", ",", "dd", ")", "{", "var", "offset", "=", "(", "elem", "&&", "elem", ".", "ownerDocument", ")", "?", "$", "(", "elem", ")", "[", "dd", ".", "relative", "?", "\"position\"", ":", "\"offset\"", "]", "(", ")", "||", "{", "top", ":", "0", ",", "left", ":", "0", "}", ":", "{", "top", ":", "0", ",", "left", ":", "0", "}", ";", "return", "{", "drag", ":", "elem", ",", "callback", ":", "new", "drag", ".", "callback", "(", ")", ",", "droppable", ":", "[", "]", ",", "offset", ":", "offset", "}", ";", "}" ]
returns an interaction object
[ "returns", "an", "interaction", "object" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/jquery.event.drag-2.3.0.js#L162-L172
train
cmap/morpheus.js
js/jquery.event.drag-2.3.0.js
function( event, type, dd, x, elem ){ // not configured if ( !dd ) return; // remember the original event and type var orig = { event:event.originalEvent, type:event.type }, // is the event drag related or drog related? mode = type.indexOf("drop") ? "drag" : "drop", // iteration vars result, i = x || 0, ia, $elems, callback, len = !isNaN( x ) ? x : dd.interactions.length; // modify the event type event.type = type; // protects originalEvent from side-effects var noop = function(){}; event.originalEvent = new jQuery.Event(orig.event, { preventDefault: noop, stopPropagation: noop, stopImmediatePropagation: noop }); // initialize the results dd.results = []; // handle each interacted element do if ( ia = dd.interactions[ i ] ){ // validate the interaction if ( type !== "dragend" && ia.cancelled ) continue; // set the dragdrop properties on the event object callback = drag.properties( event, dd, ia ); // prepare for more results ia.results = []; // handle each element $( elem || ia[ mode ] || dd.droppable ).each(function( p, subject ){ // identify drag or drop targets individually callback.target = subject; // force propagtion of the custom event event.isPropagationStopped = function(){ return false; }; // handle the event result = subject ? $event.dispatch.call( subject, event, callback ) : null; // stop the drag interaction for this element if ( result === false ){ if ( mode == "drag" ){ ia.cancelled = true; dd.propagates -= 1; } if ( type == "drop" ){ ia[ mode ][p] = null; } } // assign any dropinit elements else if ( type == "dropinit" ) ia.droppable.push( drag.element( result ) || subject ); // accept a returned proxy element if ( type == "dragstart" ) ia.proxy = $( drag.element( result ) || ia.drag )[0]; // remember this result ia.results.push( result ); // forget the event result, for recycling delete event.result; // break on cancelled handler if ( type !== "dropinit" ) return result; }); // flatten the results dd.results[ i ] = drag.flatten( ia.results ); // accept a set of valid drop targets if ( type == "dropinit" ) ia.droppable = drag.flatten( ia.droppable ); // locate drop targets if ( type == "dragstart" && !ia.cancelled ) callback.update(); } while ( ++i < len ) // restore the original event & type event.type = orig.type; event.originalEvent = orig.event; // return all handler results return drag.flatten( dd.results ); }
javascript
function( event, type, dd, x, elem ){ // not configured if ( !dd ) return; // remember the original event and type var orig = { event:event.originalEvent, type:event.type }, // is the event drag related or drog related? mode = type.indexOf("drop") ? "drag" : "drop", // iteration vars result, i = x || 0, ia, $elems, callback, len = !isNaN( x ) ? x : dd.interactions.length; // modify the event type event.type = type; // protects originalEvent from side-effects var noop = function(){}; event.originalEvent = new jQuery.Event(orig.event, { preventDefault: noop, stopPropagation: noop, stopImmediatePropagation: noop }); // initialize the results dd.results = []; // handle each interacted element do if ( ia = dd.interactions[ i ] ){ // validate the interaction if ( type !== "dragend" && ia.cancelled ) continue; // set the dragdrop properties on the event object callback = drag.properties( event, dd, ia ); // prepare for more results ia.results = []; // handle each element $( elem || ia[ mode ] || dd.droppable ).each(function( p, subject ){ // identify drag or drop targets individually callback.target = subject; // force propagtion of the custom event event.isPropagationStopped = function(){ return false; }; // handle the event result = subject ? $event.dispatch.call( subject, event, callback ) : null; // stop the drag interaction for this element if ( result === false ){ if ( mode == "drag" ){ ia.cancelled = true; dd.propagates -= 1; } if ( type == "drop" ){ ia[ mode ][p] = null; } } // assign any dropinit elements else if ( type == "dropinit" ) ia.droppable.push( drag.element( result ) || subject ); // accept a returned proxy element if ( type == "dragstart" ) ia.proxy = $( drag.element( result ) || ia.drag )[0]; // remember this result ia.results.push( result ); // forget the event result, for recycling delete event.result; // break on cancelled handler if ( type !== "dropinit" ) return result; }); // flatten the results dd.results[ i ] = drag.flatten( ia.results ); // accept a set of valid drop targets if ( type == "dropinit" ) ia.droppable = drag.flatten( ia.droppable ); // locate drop targets if ( type == "dragstart" && !ia.cancelled ) callback.update(); } while ( ++i < len ) // restore the original event & type event.type = orig.type; event.originalEvent = orig.event; // return all handler results return drag.flatten( dd.results ); }
[ "function", "(", "event", ",", "type", ",", "dd", ",", "x", ",", "elem", ")", "{", "if", "(", "!", "dd", ")", "return", ";", "var", "orig", "=", "{", "event", ":", "event", ".", "originalEvent", ",", "type", ":", "event", ".", "type", "}", ",", "mode", "=", "type", ".", "indexOf", "(", "\"drop\"", ")", "?", "\"drag\"", ":", "\"drop\"", ",", "result", ",", "i", "=", "x", "||", "0", ",", "ia", ",", "$elems", ",", "callback", ",", "len", "=", "!", "isNaN", "(", "x", ")", "?", "x", ":", "dd", ".", "interactions", ".", "length", ";", "event", ".", "type", "=", "type", ";", "var", "noop", "=", "function", "(", ")", "{", "}", ";", "event", ".", "originalEvent", "=", "new", "jQuery", ".", "Event", "(", "orig", ".", "event", ",", "{", "preventDefault", ":", "noop", ",", "stopPropagation", ":", "noop", ",", "stopImmediatePropagation", ":", "noop", "}", ")", ";", "dd", ".", "results", "=", "[", "]", ";", "do", "if", "(", "ia", "=", "dd", ".", "interactions", "[", "i", "]", ")", "{", "if", "(", "type", "!==", "\"dragend\"", "&&", "ia", ".", "cancelled", ")", "continue", ";", "callback", "=", "drag", ".", "properties", "(", "event", ",", "dd", ",", "ia", ")", ";", "ia", ".", "results", "=", "[", "]", ";", "$", "(", "elem", "||", "ia", "[", "mode", "]", "||", "dd", ".", "droppable", ")", ".", "each", "(", "function", "(", "p", ",", "subject", ")", "{", "callback", ".", "target", "=", "subject", ";", "event", ".", "isPropagationStopped", "=", "function", "(", ")", "{", "return", "false", ";", "}", ";", "result", "=", "subject", "?", "$event", ".", "dispatch", ".", "call", "(", "subject", ",", "event", ",", "callback", ")", ":", "null", ";", "if", "(", "result", "===", "false", ")", "{", "if", "(", "mode", "==", "\"drag\"", ")", "{", "ia", ".", "cancelled", "=", "true", ";", "dd", ".", "propagates", "-=", "1", ";", "}", "if", "(", "type", "==", "\"drop\"", ")", "{", "ia", "[", "mode", "]", "[", "p", "]", "=", "null", ";", "}", "}", "else", "if", "(", "type", "==", "\"dropinit\"", ")", "ia", ".", "droppable", ".", "push", "(", "drag", ".", "element", "(", "result", ")", "||", "subject", ")", ";", "if", "(", "type", "==", "\"dragstart\"", ")", "ia", ".", "proxy", "=", "$", "(", "drag", ".", "element", "(", "result", ")", "||", "ia", ".", "drag", ")", "[", "0", "]", ";", "ia", ".", "results", ".", "push", "(", "result", ")", ";", "delete", "event", ".", "result", ";", "if", "(", "type", "!==", "\"dropinit\"", ")", "return", "result", ";", "}", ")", ";", "dd", ".", "results", "[", "i", "]", "=", "drag", ".", "flatten", "(", "ia", ".", "results", ")", ";", "if", "(", "type", "==", "\"dropinit\"", ")", "ia", ".", "droppable", "=", "drag", ".", "flatten", "(", "ia", ".", "droppable", ")", ";", "if", "(", "type", "==", "\"dragstart\"", "&&", "!", "ia", ".", "cancelled", ")", "callback", ".", "update", "(", ")", ";", "}", "while", "(", "++", "i", "<", "len", ")", "event", ".", "type", "=", "orig", ".", "type", ";", "event", ".", "originalEvent", "=", "orig", ".", "event", ";", "return", "drag", ".", "flatten", "(", "dd", ".", "results", ")", ";", "}" ]
re-use event object for custom events
[ "re", "-", "use", "event", "object", "for", "custom", "events" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/jquery.event.drag-2.3.0.js#L229-L307
train
cmap/morpheus.js
js/jquery.event.drag-2.3.0.js
function( arr ){ return $.map( arr, function( member ){ return member && member.jquery ? $.makeArray( member ) : member && member.length ? drag.flatten( member ) : member; }); }
javascript
function( arr ){ return $.map( arr, function( member ){ return member && member.jquery ? $.makeArray( member ) : member && member.length ? drag.flatten( member ) : member; }); }
[ "function", "(", "arr", ")", "{", "return", "$", ".", "map", "(", "arr", ",", "function", "(", "member", ")", "{", "return", "member", "&&", "member", ".", "jquery", "?", "$", ".", "makeArray", "(", "member", ")", ":", "member", "&&", "member", ".", "length", "?", "drag", ".", "flatten", "(", "member", ")", ":", "member", ";", "}", ")", ";", "}" ]
flatten nested jquery objects and arrays into a single dimension array
[ "flatten", "nested", "jquery", "objects", "and", "arrays", "into", "a", "single", "dimension", "array" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/jquery.event.drag-2.3.0.js#L340-L345
train
cmap/morpheus.js
js/tsne.js
function (n) { if (typeof(n) === 'undefined' || isNaN(n)) { return []; } if (typeof ArrayBuffer === 'undefined') { // lacking browser support var arr = new Array(n); for (var i = 0; i < n; i++) { arr[i] = 0; } return arr; } else { return new Float64Array(n); // typed arrays are faster } }
javascript
function (n) { if (typeof(n) === 'undefined' || isNaN(n)) { return []; } if (typeof ArrayBuffer === 'undefined') { // lacking browser support var arr = new Array(n); for (var i = 0; i < n; i++) { arr[i] = 0; } return arr; } else { return new Float64Array(n); // typed arrays are faster } }
[ "function", "(", "n", ")", "{", "if", "(", "typeof", "(", "n", ")", "===", "'undefined'", "||", "isNaN", "(", "n", ")", ")", "{", "return", "[", "]", ";", "}", "if", "(", "typeof", "ArrayBuffer", "===", "'undefined'", ")", "{", "var", "arr", "=", "new", "Array", "(", "n", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "arr", "[", "i", "]", "=", "0", ";", "}", "return", "arr", ";", "}", "else", "{", "return", "new", "Float64Array", "(", "n", ")", ";", "}", "}" ]
utilitity that creates contiguous vector of zeros of size n
[ "utilitity", "that", "creates", "contiguous", "vector", "of", "zeros", "of", "size", "n" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L45-L59
train
cmap/morpheus.js
js/tsne.js
function (n, d, s) { var uses = typeof s !== 'undefined'; var x = []; for (var i = 0; i < n; i++) { var xhere = []; for (var j = 0; j < d; j++) { if (uses) { xhere.push(s); } else { xhere.push(randn(0.0, 1e-4)); } } x.push(xhere); } return x; }
javascript
function (n, d, s) { var uses = typeof s !== 'undefined'; var x = []; for (var i = 0; i < n; i++) { var xhere = []; for (var j = 0; j < d; j++) { if (uses) { xhere.push(s); } else { xhere.push(randn(0.0, 1e-4)); } } x.push(xhere); } return x; }
[ "function", "(", "n", ",", "d", ",", "s", ")", "{", "var", "uses", "=", "typeof", "s", "!==", "'undefined'", ";", "var", "x", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "var", "xhere", "=", "[", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "d", ";", "j", "++", ")", "{", "if", "(", "uses", ")", "{", "xhere", ".", "push", "(", "s", ")", ";", "}", "else", "{", "xhere", ".", "push", "(", "randn", "(", "0.0", ",", "1e-4", ")", ")", ";", "}", "}", "x", ".", "push", "(", "xhere", ")", ";", "}", "return", "x", ";", "}" ]
utility that returns 2d array filled with random numbers or with value s, if provided
[ "utility", "that", "returns", "2d", "array", "filled", "with", "random", "numbers", "or", "with", "value", "s", "if", "provided" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L63-L78
train
cmap/morpheus.js
js/tsne.js
function (x1, x2) { var D = x1.length; var d = 0; for (var i = 0; i < D; i++) { var x1i = x1[i]; var x2i = x2[i]; d += (x1i - x2i) * (x1i - x2i); } return d; }
javascript
function (x1, x2) { var D = x1.length; var d = 0; for (var i = 0; i < D; i++) { var x1i = x1[i]; var x2i = x2[i]; d += (x1i - x2i) * (x1i - x2i); } return d; }
[ "function", "(", "x1", ",", "x2", ")", "{", "var", "D", "=", "x1", ".", "length", ";", "var", "d", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "D", ";", "i", "++", ")", "{", "var", "x1i", "=", "x1", "[", "i", "]", ";", "var", "x2i", "=", "x2", "[", "i", "]", ";", "d", "+=", "(", "x1i", "-", "x2i", ")", "*", "(", "x1i", "-", "x2i", ")", ";", "}", "return", "d", ";", "}" ]
compute L2 distance between two vectors
[ "compute", "L2", "distance", "between", "two", "vectors" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L81-L90
train
cmap/morpheus.js
js/tsne.js
function (X) { var N = X.length; var dist = zeros(N * N); // allocate contiguous array for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { var d = L2(X[i], X[j]); dist[i * N + j] = d; dist[j * N + i] = d; } } return dist; }
javascript
function (X) { var N = X.length; var dist = zeros(N * N); // allocate contiguous array for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { var d = L2(X[i], X[j]); dist[i * N + j] = d; dist[j * N + i] = d; } } return dist; }
[ "function", "(", "X", ")", "{", "var", "N", "=", "X", ".", "length", ";", "var", "dist", "=", "zeros", "(", "N", "*", "N", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "i", "+", "1", ";", "j", "<", "N", ";", "j", "++", ")", "{", "var", "d", "=", "L2", "(", "X", "[", "i", "]", ",", "X", "[", "j", "]", ")", ";", "dist", "[", "i", "*", "N", "+", "j", "]", "=", "d", ";", "dist", "[", "j", "*", "N", "+", "i", "]", "=", "d", ";", "}", "}", "return", "dist", ";", "}" ]
compute pairwise distance in all vectors in X
[ "compute", "pairwise", "distance", "in", "all", "vectors", "in", "X" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L93-L104
train
cmap/morpheus.js
js/tsne.js
function (X) { var N = X.length; var D = X[0].length; assert(N > 0, " X is empty? You must have some data!"); assert(D > 0, " X[0] is empty? Where is the data?"); var dists = xtod(X); // convert X to distances using gaussian kernel this.P = d2p(dists, this.perplexity, 1e-4); // attach to object this.N = N; // back up the size of the dataset this.initSolution(); // refresh this }
javascript
function (X) { var N = X.length; var D = X[0].length; assert(N > 0, " X is empty? You must have some data!"); assert(D > 0, " X[0] is empty? Where is the data?"); var dists = xtod(X); // convert X to distances using gaussian kernel this.P = d2p(dists, this.perplexity, 1e-4); // attach to object this.N = N; // back up the size of the dataset this.initSolution(); // refresh this }
[ "function", "(", "X", ")", "{", "var", "N", "=", "X", ".", "length", ";", "var", "D", "=", "X", "[", "0", "]", ".", "length", ";", "assert", "(", "N", ">", "0", ",", "\" X is empty? You must have some data!\"", ")", ";", "assert", "(", "D", ">", "0", ",", "\" X[0] is empty? Where is the data?\"", ")", ";", "var", "dists", "=", "xtod", "(", "X", ")", ";", "this", ".", "P", "=", "d2p", "(", "dists", ",", "this", ".", "perplexity", ",", "1e-4", ")", ";", "this", ".", "N", "=", "N", ";", "this", ".", "initSolution", "(", ")", ";", "}" ]
this function takes a set of high-dimensional points and creates matrix P from them using gaussian kernel
[ "this", "function", "takes", "a", "set", "of", "high", "-", "dimensional", "points", "and", "creates", "matrix", "P", "from", "them", "using", "gaussian", "kernel" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L217-L226
train
cmap/morpheus.js
js/tsne.js
function (D) { var N = D.length; assert(N > 0, " X is empty? You must have some data!"); // convert D to a (fast) typed array version var dists = zeros(N * N); // allocate contiguous array for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { var d = D[i][j]; dists[i * N + j] = d; dists[j * N + i] = d; } } this.P = d2p(dists, this.perplexity, 1e-4); this.N = N; this.initSolution(); // refresh this }
javascript
function (D) { var N = D.length; assert(N > 0, " X is empty? You must have some data!"); // convert D to a (fast) typed array version var dists = zeros(N * N); // allocate contiguous array for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { var d = D[i][j]; dists[i * N + j] = d; dists[j * N + i] = d; } } this.P = d2p(dists, this.perplexity, 1e-4); this.N = N; this.initSolution(); // refresh this }
[ "function", "(", "D", ")", "{", "var", "N", "=", "D", ".", "length", ";", "assert", "(", "N", ">", "0", ",", "\" X is empty? You must have some data!\"", ")", ";", "var", "dists", "=", "zeros", "(", "N", "*", "N", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "i", "+", "1", ";", "j", "<", "N", ";", "j", "++", ")", "{", "var", "d", "=", "D", "[", "i", "]", "[", "j", "]", ";", "dists", "[", "i", "*", "N", "+", "j", "]", "=", "d", ";", "dists", "[", "j", "*", "N", "+", "i", "]", "=", "d", ";", "}", "}", "this", ".", "P", "=", "d2p", "(", "dists", ",", "this", ".", "perplexity", ",", "1e-4", ")", ";", "this", ".", "N", "=", "N", ";", "this", ".", "initSolution", "(", ")", ";", "}" ]
this function takes a given distance matrix and creates matrix P from them. D is assumed to be provided as a list of lists, and should be symmetric
[ "this", "function", "takes", "a", "given", "distance", "matrix", "and", "creates", "matrix", "P", "from", "them", ".", "D", "is", "assumed", "to", "be", "provided", "as", "a", "list", "of", "lists", "and", "should", "be", "symmetric" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L231-L246
train
cmap/morpheus.js
js/tsne.js
function () { this.iter += 1; var N = this.N; var cg = this.costGrad(this.Y); // evaluate gradient var cost = cg.cost; var grad = cg.grad; // perform gradient step var ymean = zeros(this.dim); for (var i = 0; i < N; i++) { for (var d = 0; d < this.dim; d++) { var gid = grad[i][d]; var sid = this.ystep[i][d]; var gainid = this.gains[i][d]; // compute gain update var newgain = sign(gid) === sign(sid) ? gainid * 0.8 : gainid + 0.2; if (newgain < 0.01) newgain = 0.01; // clamp this.gains[i][d] = newgain; // store for next turn // compute momentum step direction var momval = this.iter < 250 ? 0.5 : 0.8; var newsid = momval * sid - this.epsilon * newgain * grad[i][d]; this.ystep[i][d] = newsid; // remember the step we took // step! this.Y[i][d] += newsid; ymean[d] += this.Y[i][d]; // accumulate mean so that we can center later } } // reproject Y to be zero mean for (var i = 0; i < N; i++) { for (var d = 0; d < this.dim; d++) { this.Y[i][d] -= ymean[d] / N; } } //if(this.iter%100===0) console.log('iter ' + this.iter + ', cost: ' + cost); return cost; // return current cost }
javascript
function () { this.iter += 1; var N = this.N; var cg = this.costGrad(this.Y); // evaluate gradient var cost = cg.cost; var grad = cg.grad; // perform gradient step var ymean = zeros(this.dim); for (var i = 0; i < N; i++) { for (var d = 0; d < this.dim; d++) { var gid = grad[i][d]; var sid = this.ystep[i][d]; var gainid = this.gains[i][d]; // compute gain update var newgain = sign(gid) === sign(sid) ? gainid * 0.8 : gainid + 0.2; if (newgain < 0.01) newgain = 0.01; // clamp this.gains[i][d] = newgain; // store for next turn // compute momentum step direction var momval = this.iter < 250 ? 0.5 : 0.8; var newsid = momval * sid - this.epsilon * newgain * grad[i][d]; this.ystep[i][d] = newsid; // remember the step we took // step! this.Y[i][d] += newsid; ymean[d] += this.Y[i][d]; // accumulate mean so that we can center later } } // reproject Y to be zero mean for (var i = 0; i < N; i++) { for (var d = 0; d < this.dim; d++) { this.Y[i][d] -= ymean[d] / N; } } //if(this.iter%100===0) console.log('iter ' + this.iter + ', cost: ' + cost); return cost; // return current cost }
[ "function", "(", ")", "{", "this", ".", "iter", "+=", "1", ";", "var", "N", "=", "this", ".", "N", ";", "var", "cg", "=", "this", ".", "costGrad", "(", "this", ".", "Y", ")", ";", "var", "cost", "=", "cg", ".", "cost", ";", "var", "grad", "=", "cg", ".", "grad", ";", "var", "ymean", "=", "zeros", "(", "this", ".", "dim", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{", "for", "(", "var", "d", "=", "0", ";", "d", "<", "this", ".", "dim", ";", "d", "++", ")", "{", "var", "gid", "=", "grad", "[", "i", "]", "[", "d", "]", ";", "var", "sid", "=", "this", ".", "ystep", "[", "i", "]", "[", "d", "]", ";", "var", "gainid", "=", "this", ".", "gains", "[", "i", "]", "[", "d", "]", ";", "var", "newgain", "=", "sign", "(", "gid", ")", "===", "sign", "(", "sid", ")", "?", "gainid", "*", "0.8", ":", "gainid", "+", "0.2", ";", "if", "(", "newgain", "<", "0.01", ")", "newgain", "=", "0.01", ";", "this", ".", "gains", "[", "i", "]", "[", "d", "]", "=", "newgain", ";", "var", "momval", "=", "this", ".", "iter", "<", "250", "?", "0.5", ":", "0.8", ";", "var", "newsid", "=", "momval", "*", "sid", "-", "this", ".", "epsilon", "*", "newgain", "*", "grad", "[", "i", "]", "[", "d", "]", ";", "this", ".", "ystep", "[", "i", "]", "[", "d", "]", "=", "newsid", ";", "this", ".", "Y", "[", "i", "]", "[", "d", "]", "+=", "newsid", ";", "ymean", "[", "d", "]", "+=", "this", ".", "Y", "[", "i", "]", "[", "d", "]", ";", "}", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{", "for", "(", "var", "d", "=", "0", ";", "d", "<", "this", ".", "dim", ";", "d", "++", ")", "{", "this", ".", "Y", "[", "i", "]", "[", "d", "]", "-=", "ymean", "[", "d", "]", "/", "N", ";", "}", "}", "return", "cost", ";", "}" ]
perform a single step of optimization to improve the embedding
[ "perform", "a", "single", "step", "of", "optimization", "to", "improve", "the", "embedding" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L263-L305
train
cmap/morpheus.js
js/tsne.js
function (Y) { var N = this.N; var dim = this.dim; // dim of output space var P = this.P; var pmul = this.iter < 100 ? 4 : 1; // trick that helps with local optima // compute current Q distribution, unnormalized first var Qu = zeros(N * N); var qsum = 0.0; for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { var dsum = 0.0; for (var d = 0; d < dim; d++) { var dhere = Y[i][d] - Y[j][d]; dsum += dhere * dhere; } var qu = 1.0 / (1.0 + dsum); // Student t-distribution Qu[i * N + j] = qu; Qu[j * N + i] = qu; qsum += 2 * qu; } } // normalize Q distribution to sum to 1 var NN = N * N; var Q = zeros(NN); for (var q = 0; q < NN; q++) { Q[q] = Math.max(Qu[q] / qsum, 1e-100); } var cost = 0.0; var grad = []; for (var i = 0; i < N; i++) { var gsum = new Array(dim); // init grad for point i for (var d = 0; d < dim; d++) { gsum[d] = 0.0; } for (var j = 0; j < N; j++) { cost += -P[i * N + j] * Math.log(Q[i * N + j]); // accumulate cost (the non-constant portion at least...) var premult = 4 * (pmul * P[i * N + j] - Q[i * N + j]) * Qu[i * N + j]; for (var d = 0; d < dim; d++) { gsum[d] += premult * (Y[i][d] - Y[j][d]); } } grad.push(gsum); } return { cost: cost, grad: grad }; }
javascript
function (Y) { var N = this.N; var dim = this.dim; // dim of output space var P = this.P; var pmul = this.iter < 100 ? 4 : 1; // trick that helps with local optima // compute current Q distribution, unnormalized first var Qu = zeros(N * N); var qsum = 0.0; for (var i = 0; i < N; i++) { for (var j = i + 1; j < N; j++) { var dsum = 0.0; for (var d = 0; d < dim; d++) { var dhere = Y[i][d] - Y[j][d]; dsum += dhere * dhere; } var qu = 1.0 / (1.0 + dsum); // Student t-distribution Qu[i * N + j] = qu; Qu[j * N + i] = qu; qsum += 2 * qu; } } // normalize Q distribution to sum to 1 var NN = N * N; var Q = zeros(NN); for (var q = 0; q < NN; q++) { Q[q] = Math.max(Qu[q] / qsum, 1e-100); } var cost = 0.0; var grad = []; for (var i = 0; i < N; i++) { var gsum = new Array(dim); // init grad for point i for (var d = 0; d < dim; d++) { gsum[d] = 0.0; } for (var j = 0; j < N; j++) { cost += -P[i * N + j] * Math.log(Q[i * N + j]); // accumulate cost (the non-constant portion at least...) var premult = 4 * (pmul * P[i * N + j] - Q[i * N + j]) * Qu[i * N + j]; for (var d = 0; d < dim; d++) { gsum[d] += premult * (Y[i][d] - Y[j][d]); } } grad.push(gsum); } return { cost: cost, grad: grad }; }
[ "function", "(", "Y", ")", "{", "var", "N", "=", "this", ".", "N", ";", "var", "dim", "=", "this", ".", "dim", ";", "var", "P", "=", "this", ".", "P", ";", "var", "pmul", "=", "this", ".", "iter", "<", "100", "?", "4", ":", "1", ";", "var", "Qu", "=", "zeros", "(", "N", "*", "N", ")", ";", "var", "qsum", "=", "0.0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "i", "+", "1", ";", "j", "<", "N", ";", "j", "++", ")", "{", "var", "dsum", "=", "0.0", ";", "for", "(", "var", "d", "=", "0", ";", "d", "<", "dim", ";", "d", "++", ")", "{", "var", "dhere", "=", "Y", "[", "i", "]", "[", "d", "]", "-", "Y", "[", "j", "]", "[", "d", "]", ";", "dsum", "+=", "dhere", "*", "dhere", ";", "}", "var", "qu", "=", "1.0", "/", "(", "1.0", "+", "dsum", ")", ";", "Qu", "[", "i", "*", "N", "+", "j", "]", "=", "qu", ";", "Qu", "[", "j", "*", "N", "+", "i", "]", "=", "qu", ";", "qsum", "+=", "2", "*", "qu", ";", "}", "}", "var", "NN", "=", "N", "*", "N", ";", "var", "Q", "=", "zeros", "(", "NN", ")", ";", "for", "(", "var", "q", "=", "0", ";", "q", "<", "NN", ";", "q", "++", ")", "{", "Q", "[", "q", "]", "=", "Math", ".", "max", "(", "Qu", "[", "q", "]", "/", "qsum", ",", "1e-100", ")", ";", "}", "var", "cost", "=", "0.0", ";", "var", "grad", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{", "var", "gsum", "=", "new", "Array", "(", "dim", ")", ";", "for", "(", "var", "d", "=", "0", ";", "d", "<", "dim", ";", "d", "++", ")", "{", "gsum", "[", "d", "]", "=", "0.0", ";", "}", "for", "(", "var", "j", "=", "0", ";", "j", "<", "N", ";", "j", "++", ")", "{", "cost", "+=", "-", "P", "[", "i", "*", "N", "+", "j", "]", "*", "Math", ".", "log", "(", "Q", "[", "i", "*", "N", "+", "j", "]", ")", ";", "var", "premult", "=", "4", "*", "(", "pmul", "*", "P", "[", "i", "*", "N", "+", "j", "]", "-", "Q", "[", "i", "*", "N", "+", "j", "]", ")", "*", "Qu", "[", "i", "*", "N", "+", "j", "]", ";", "for", "(", "var", "d", "=", "0", ";", "d", "<", "dim", ";", "d", "++", ")", "{", "gsum", "[", "d", "]", "+=", "premult", "*", "(", "Y", "[", "i", "]", "[", "d", "]", "-", "Y", "[", "j", "]", "[", "d", "]", ")", ";", "}", "}", "grad", ".", "push", "(", "gsum", ")", ";", "}", "return", "{", "cost", ":", "cost", ",", "grad", ":", "grad", "}", ";", "}" ]
return cost and gradient, given an arrangement
[ "return", "cost", "and", "gradient", "given", "an", "arrangement" ]
566784e9d77dea811c43b39dd6ed6a156d28c751
https://github.com/cmap/morpheus.js/blob/566784e9d77dea811c43b39dd6ed6a156d28c751/js/tsne.js#L336-L387
train
forbesmyester/SyncIt
makeAsync.js
function() { var args = Array.prototype.slice.call(arguments); args.unshift(null); var Factory = classFunc.bind.apply( classFunc, args ); this._inst = new Factory(); }
javascript
function() { var args = Array.prototype.slice.call(arguments); args.unshift(null); var Factory = classFunc.bind.apply( classFunc, args ); this._inst = new Factory(); }
[ "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "args", ".", "unshift", "(", "null", ")", ";", "var", "Factory", "=", "classFunc", ".", "bind", ".", "apply", "(", "classFunc", ",", "args", ")", ";", "this", ".", "_inst", "=", "new", "Factory", "(", ")", ";", "}" ]
This will create the constructor
[ "This", "will", "create", "the", "constructor" ]
f1e8e7eda7552b11f083a779e01c4fab5f073167
https://github.com/forbesmyester/SyncIt/blob/f1e8e7eda7552b11f083a779e01c4fab5f073167/makeAsync.js#L40-L48
train
rtc-io/rtc-screenshare
electron.js
simpleSelector
function simpleSelector(sources, callback) { var options = crel('select', { style: 'margin: 0.5rem' }, sources.map(function(source) { return crel('option', {id: source.id, value: source.id}, source.name); })); var selector = crel('div', { style: 'position: absolute; padding: 1rem; z-index: 999999; background: #ffffff; width: 100%; font-family: \'Lucida Sans Unicode\', \'Lucida Grande\', sans-serif; box-shadow: 0px 2px 4px #dddddd;' }, crel('label', { style: 'margin: 0.5rem' }, 'Share screen:'), options, crel('span', { style: 'margin: 0.5rem; display: inline-block' }, button('Share', function() { close(); var selected = sources.filter(function(source) { return source && source.id === options.value; })[0]; return callback(null, options.value, { title: selected.name }); }), button('Cancel', close) ) ); function button(text, fn) { var button = crel('button', { style: 'background: #555555; color: #ffffff; padding: 0.5rem 1rem; margin: 0rem 0.2rem;' }, text); button.addEventListener('click', fn); return button; } function close() { document.body.removeChild(selector); } document.body.appendChild(selector); }
javascript
function simpleSelector(sources, callback) { var options = crel('select', { style: 'margin: 0.5rem' }, sources.map(function(source) { return crel('option', {id: source.id, value: source.id}, source.name); })); var selector = crel('div', { style: 'position: absolute; padding: 1rem; z-index: 999999; background: #ffffff; width: 100%; font-family: \'Lucida Sans Unicode\', \'Lucida Grande\', sans-serif; box-shadow: 0px 2px 4px #dddddd;' }, crel('label', { style: 'margin: 0.5rem' }, 'Share screen:'), options, crel('span', { style: 'margin: 0.5rem; display: inline-block' }, button('Share', function() { close(); var selected = sources.filter(function(source) { return source && source.id === options.value; })[0]; return callback(null, options.value, { title: selected.name }); }), button('Cancel', close) ) ); function button(text, fn) { var button = crel('button', { style: 'background: #555555; color: #ffffff; padding: 0.5rem 1rem; margin: 0rem 0.2rem;' }, text); button.addEventListener('click', fn); return button; } function close() { document.body.removeChild(selector); } document.body.appendChild(selector); }
[ "function", "simpleSelector", "(", "sources", ",", "callback", ")", "{", "var", "options", "=", "crel", "(", "'select'", ",", "{", "style", ":", "'margin: 0.5rem'", "}", ",", "sources", ".", "map", "(", "function", "(", "source", ")", "{", "return", "crel", "(", "'option'", ",", "{", "id", ":", "source", ".", "id", ",", "value", ":", "source", ".", "id", "}", ",", "source", ".", "name", ")", ";", "}", ")", ")", ";", "var", "selector", "=", "crel", "(", "'div'", ",", "{", "style", ":", "'position: absolute; padding: 1rem; z-index: 999999; background: #ffffff; width: 100%; font-family: \\'Lucida Sans Unicode\\', \\'Lucida Grande\\', sans-serif; box-shadow: 0px 2px 4px #dddddd;'", "}", ",", "\\'", ",", "\\'", ",", "\\'", ")", ";", "\\'", "crel", "(", "'label'", ",", "{", "style", ":", "'margin: 0.5rem'", "}", ",", "'Share screen:'", ")", "options", "}" ]
This is just a simple default screen selector implementation
[ "This", "is", "just", "a", "simple", "default", "screen", "selector", "implementation" ]
0a160e73031a8b0f43111c22f48db6dbde3be305
https://github.com/rtc-io/rtc-screenshare/blob/0a160e73031a8b0f43111c22f48db6dbde3be305/electron.js#L84-L123
train
InvokIT/js-untar
src/untar.js
untar
function untar(arrayBuffer) { if (!(arrayBuffer instanceof ArrayBuffer)) { throw new TypeError("arrayBuffer is not an instance of ArrayBuffer."); } if (!global.Worker) { throw new Error("Worker implementation is not available in this environment."); } return new ProgressivePromise(function(resolve, reject, progress) { var worker = new Worker(workerScriptUri); var files = []; worker.onerror = function(err) { reject(err); }; worker.onmessage = function(message) { message = message.data; switch (message.type) { case "log": console[message.data.level]("Worker: " + message.data.msg); break; case "extract": var file = decorateExtractedFile(message.data); files.push(file); progress(file); break; case "complete": worker.terminate(); resolve(files); break; case "error": //console.log("error message"); worker.terminate(); reject(new Error(message.data.message)); break; default: worker.terminate(); reject(new Error("Unknown message from worker: " + message.type)); break; } }; //console.info("Sending arraybuffer to worker for extraction."); worker.postMessage({ type: "extract", buffer: arrayBuffer }, [arrayBuffer]); }); }
javascript
function untar(arrayBuffer) { if (!(arrayBuffer instanceof ArrayBuffer)) { throw new TypeError("arrayBuffer is not an instance of ArrayBuffer."); } if (!global.Worker) { throw new Error("Worker implementation is not available in this environment."); } return new ProgressivePromise(function(resolve, reject, progress) { var worker = new Worker(workerScriptUri); var files = []; worker.onerror = function(err) { reject(err); }; worker.onmessage = function(message) { message = message.data; switch (message.type) { case "log": console[message.data.level]("Worker: " + message.data.msg); break; case "extract": var file = decorateExtractedFile(message.data); files.push(file); progress(file); break; case "complete": worker.terminate(); resolve(files); break; case "error": //console.log("error message"); worker.terminate(); reject(new Error(message.data.message)); break; default: worker.terminate(); reject(new Error("Unknown message from worker: " + message.type)); break; } }; //console.info("Sending arraybuffer to worker for extraction."); worker.postMessage({ type: "extract", buffer: arrayBuffer }, [arrayBuffer]); }); }
[ "function", "untar", "(", "arrayBuffer", ")", "{", "if", "(", "!", "(", "arrayBuffer", "instanceof", "ArrayBuffer", ")", ")", "{", "throw", "new", "TypeError", "(", "\"arrayBuffer is not an instance of ArrayBuffer.\"", ")", ";", "}", "if", "(", "!", "global", ".", "Worker", ")", "{", "throw", "new", "Error", "(", "\"Worker implementation is not available in this environment.\"", ")", ";", "}", "return", "new", "ProgressivePromise", "(", "function", "(", "resolve", ",", "reject", ",", "progress", ")", "{", "var", "worker", "=", "new", "Worker", "(", "workerScriptUri", ")", ";", "var", "files", "=", "[", "]", ";", "worker", ".", "onerror", "=", "function", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", ";", "worker", ".", "onmessage", "=", "function", "(", "message", ")", "{", "message", "=", "message", ".", "data", ";", "switch", "(", "message", ".", "type", ")", "{", "case", "\"log\"", ":", "console", "[", "message", ".", "data", ".", "level", "]", "(", "\"Worker: \"", "+", "message", ".", "data", ".", "msg", ")", ";", "break", ";", "case", "\"extract\"", ":", "var", "file", "=", "decorateExtractedFile", "(", "message", ".", "data", ")", ";", "files", ".", "push", "(", "file", ")", ";", "progress", "(", "file", ")", ";", "break", ";", "case", "\"complete\"", ":", "worker", ".", "terminate", "(", ")", ";", "resolve", "(", "files", ")", ";", "break", ";", "case", "\"error\"", ":", "worker", ".", "terminate", "(", ")", ";", "reject", "(", "new", "Error", "(", "message", ".", "data", ".", "message", ")", ")", ";", "break", ";", "default", ":", "worker", ".", "terminate", "(", ")", ";", "reject", "(", "new", "Error", "(", "\"Unknown message from worker: \"", "+", "message", ".", "type", ")", ")", ";", "break", ";", "}", "}", ";", "worker", ".", "postMessage", "(", "{", "type", ":", "\"extract\"", ",", "buffer", ":", "arrayBuffer", "}", ",", "[", "arrayBuffer", "]", ")", ";", "}", ")", ";", "}" ]
Returns a ProgressivePromise.
[ "Returns", "a", "ProgressivePromise", "." ]
49e639cf82e8d58dccb3458cbd08768afee8b41c
https://github.com/InvokIT/js-untar/blob/49e639cf82e8d58dccb3458cbd08768afee8b41c/src/untar.js#L12-L61
train
sidorares/hot-module-replacement
index.js
collectDependencies
function collectDependencies(module) { let paths = []; function pathsToAcceptingModules(path, root) { const requiredMe = parents[root.filename]; if (module.hot._selfAccepted) { paths.push(path.concat(root.filename)); return; } if (module.hot._selfDeclined) { return; } for (let next in requiredMe) { let parentHotRuntime = requiredMe[next].hot; if (parentHotRuntime._acceptedDependencies[root.filename]) { paths.push(path.concat(root.filename)); continue; } if (parentHotRuntime._declinedDependencies[root.filename]) { continue; } pathsToAcceptingModules(path.concat(root.filename), requiredMe[next]); } } pathsToAcceptingModules([], module); return paths; }
javascript
function collectDependencies(module) { let paths = []; function pathsToAcceptingModules(path, root) { const requiredMe = parents[root.filename]; if (module.hot._selfAccepted) { paths.push(path.concat(root.filename)); return; } if (module.hot._selfDeclined) { return; } for (let next in requiredMe) { let parentHotRuntime = requiredMe[next].hot; if (parentHotRuntime._acceptedDependencies[root.filename]) { paths.push(path.concat(root.filename)); continue; } if (parentHotRuntime._declinedDependencies[root.filename]) { continue; } pathsToAcceptingModules(path.concat(root.filename), requiredMe[next]); } } pathsToAcceptingModules([], module); return paths; }
[ "function", "collectDependencies", "(", "module", ")", "{", "let", "paths", "=", "[", "]", ";", "function", "pathsToAcceptingModules", "(", "path", ",", "root", ")", "{", "const", "requiredMe", "=", "parents", "[", "root", ".", "filename", "]", ";", "if", "(", "module", ".", "hot", ".", "_selfAccepted", ")", "{", "paths", ".", "push", "(", "path", ".", "concat", "(", "root", ".", "filename", ")", ")", ";", "return", ";", "}", "if", "(", "module", ".", "hot", ".", "_selfDeclined", ")", "{", "return", ";", "}", "for", "(", "let", "next", "in", "requiredMe", ")", "{", "let", "parentHotRuntime", "=", "requiredMe", "[", "next", "]", ".", "hot", ";", "if", "(", "parentHotRuntime", ".", "_acceptedDependencies", "[", "root", ".", "filename", "]", ")", "{", "paths", ".", "push", "(", "path", ".", "concat", "(", "root", ".", "filename", ")", ")", ";", "continue", ";", "}", "if", "(", "parentHotRuntime", ".", "_declinedDependencies", "[", "root", ".", "filename", "]", ")", "{", "continue", ";", "}", "pathsToAcceptingModules", "(", "path", ".", "concat", "(", "root", ".", "filename", ")", ",", "requiredMe", "[", "next", "]", ")", ";", "}", "}", "pathsToAcceptingModules", "(", "[", "]", ",", "module", ")", ";", "return", "paths", ";", "}" ]
module is changed, which dependency needs to be reloaded?
[ "module", "is", "changed", "which", "dependency", "needs", "to", "be", "reloaded?" ]
2af226b9e8fd1ce75b40b96c0920f053e92db450
https://github.com/sidorares/hot-module-replacement/blob/2af226b9e8fd1ce75b40b96c0920f053e92db450/index.js#L22-L47
train
dstreet/dependsOn
src/dependency.js
getFieldState
function getFieldState($ele) { var val = $ele.val() // If dependency is a radio group, then filter by `:checked` if ($ele.attr('type') === 'radio') { val = $ele.filter(':checked').val() } return { value: val, checked: $ele.is(':checked'), disabled: $ele.is(':disabled'), selected: $ele.is(':selected') } }
javascript
function getFieldState($ele) { var val = $ele.val() // If dependency is a radio group, then filter by `:checked` if ($ele.attr('type') === 'radio') { val = $ele.filter(':checked').val() } return { value: val, checked: $ele.is(':checked'), disabled: $ele.is(':disabled'), selected: $ele.is(':selected') } }
[ "function", "getFieldState", "(", "$ele", ")", "{", "var", "val", "=", "$ele", ".", "val", "(", ")", "if", "(", "$ele", ".", "attr", "(", "'type'", ")", "===", "'radio'", ")", "{", "val", "=", "$ele", ".", "filter", "(", "':checked'", ")", ".", "val", "(", ")", "}", "return", "{", "value", ":", "val", ",", "checked", ":", "$ele", ".", "is", "(", "':checked'", ")", ",", "disabled", ":", "$ele", ".", "is", "(", "':disabled'", ")", ",", "selected", ":", "$ele", ".", "is", "(", "':selected'", ")", "}", "}" ]
Get the current state of a field @param {jQuery} $ele The element @return {Object} @private
[ "Get", "the", "current", "state", "of", "a", "field" ]
a40100652aa6a6f7748bf3cd761578b34b82d547
https://github.com/dstreet/dependsOn/blob/a40100652aa6a6f7748bf3cd761578b34b82d547/src/dependency.js#L311-L325
train