<commit_before># Mozilla User Preferences

/* Do not edit this file.
 *
 * If you make changes to this file while the application is running,
 * the changes will be overwritten when the application exits.
 *
 * To make a manual change to preferences, you can visit the URL about:config
 * For more information, see http://www.mozilla.org/unix/customizing.html#prefs
 */

user_pref("app.update.auto", false);
user_pref("app.update.enabled", false);
user_pref("app.update.lastUpdateTime.addon-background-update-timer", 1216566538);
user_pref("app.update.lastUpdateTime.background-update-timer", 1216566535);
user_pref("app.update.lastUpdateTime.blocklist-background-update-timer", 1216566538);
user_pref("app.update.lastUpdateTime.microsummary-generator-update-timer", 1232574822);
user_pref("app.update.lastUpdateTime.search-engine-update-timer", 1216566539);
user_pref("browser.bookmarks.livemark_refresh_seconds", 31536000);
user_pref("browser.cache.disk.capacity", 0);
user_pref("browser.cache.disk.enable", false);
user_pref("browser.cache.disk.smart_size.enabled", false);
user_pref("browser.cache.disk.smart_size.first_run", false);
user_pref("browser.cache.offline.enable", false);
user_pref("browser.chrome.favicons", false);
user_pref("browser.chrome.image_icons.max_size", 0);
user_pref("browser.chrome.site_icons", false);
user_pref("browser.download.manager.retention", 1);
user_pref("browser.download.useDownloadDir", false);
user_pref("browser.formfill.enable", false);
user_pref("browser.history_expire_days.mirror", 0);
user_pref("browser.microsummary.updateGenerators", false);
user_pref("browser.migration.version", 5);
user_pref("browser.places.importBookmarksHTML", false);
user_pref("browser.places.importDefaults", false);
user_pref("browser.places.leftPaneFolderId", -1);
user_pref("browser.places.migratePostDataAnnotations", false);
user_pref("browser.places.smartBookmarksVersion", 2);
user_pref("browser.places.updateRecentTagsUri", false);
user_pref("browser.preferences.advanced.selectedTabIndex", 0);
user_pref("browser.privatebrowsing.autostart", true);
user_pref("browser.rights.3.shown", true);
user_pref("browser.safebrowsing.enabled", false);
user_pref("browser.safebrowsing.malware.enabled", false);
user_pref("browser.search.suggest.enabled", false);
user_pref("browser.search.update", false);
user_pref("browser.sessionstore.privacy_level", 2);
user_pref("browser.shell.checkDefaultBrowser", false);
user_pref("browser.startup.homepage", "https://check.torproject.org/?lang=en-US&small=1");
user_pref("browser.startup.homepage_override.buildID", "20110325121920");
user_pref("browser.startup.homepage_override.mstone", "rv:2.0");
user_pref("browser.urlbar.autocomplete.enabled", false);
user_pref("browser.zoom.siteSpecific", false);
user_pref("capability.policy.maonoscript.javascript.enabled", "allAccess");
user_pref("capability.policy.maonoscript.sites", "addons.mozilla.org about: about:addons about:blank about:blocked about:certerror about:config about:crashes about:credits about:home about:neterror about:plugins about:privatebrowsing about:sessionrestore chrome: resource:");
user_pref("dom.event.contextmenu.enabled", false);
user_pref("dom.storage.enabled", false);
user_pref("extensions.bootstrappedAddons", "{}");
user_pref("extensions.bprivacy.DataDir", "/Users/erinn/Library/Preferences/Macromedia");
user_pref("extensions.bprivacy.donotaskforfolder", true);
user_pref("extensions.bprivacy.donotaskonexit", true);
user_pref("extensions.bprivacy.initiated", true);
user_pref("extensions.checkCompatibility.4.*", false);
user_pref("extensions.checkUpdateSecurity", false);
user_pref("extensions.databaseSchema", 3);
user_pref("extensions.enabledAddons", "https-everywhere@eff.org:0.9.9.development.4,{73a6fe31-595d-460b-a920-fcc0f8843232}:2.1.0.3,{d40f5e7b-d2cf-4856-b441-cc613eeffbe3}:1.50,{e0204bd5-9d31-402b-a99d-a6aa8ffebdca}:1.3.3-alpha");
user_pref("extensions.enabledItems", "langpack-en-US@firefox.mozilla.org:,{73a6fe31-595d-460b-a920-fcc0f8843232}:1.9.9.57,{e0204bd5-9d31-402b-a99d-a6aa8ffebdca}:1.2.4,{972ce4c6-7e08-4474-a285-3208198ce6fd}:3.5.8");
user_pref("extensions.enabledScopes", 1);
user_pref("extensions.pendingOperations", false);
user_pref("extensions.torbutton.fresh_install", false);
user_pref("extensions.torbutton.locked_mode", true);
user_pref("extensions.torbutton.proxies_applied", true);
user_pref("extensions.torbutton.restore_tor", true);
user_pref("extensions.torbutton.saved.auto_update", false);
user_pref("extensions.torbutton.saved.share_proxy_settings", false);
user_pref("extensions.torbutton.saved.socks_version", 5);
user_pref("extensions.torbutton.settings_applied", true);
user_pref("extensions.torbutton.socks_host", "127.0.0.1");
user_pref("extensions.torbutton.socks_port", 9050);
user_pref("extensions.torbutton.tor_enabled", true);
user_pref("extensions.torbutton.tor_memory_jar", true);
user_pref("extensions.torbutton.tz_string", "UTC+00:00");
user_pref("extensions.update.enabled", false);
user_pref("extensions.update.notifyUser", false);
user_pref("general.appname.override", "Netscape");
user_pref("general.appversion.override", "5.0 (Windows; en-US)");
user_pref("general.buildID.override", "0");
user_pref("general.oscpu.override", "Windows NT 6.1");
user_pref("general.platform.override", "Win32");
user_pref("general.productSub.override", "20100401");
user_pref("general.useragent.override", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3");
user_pref("general.useragent.vendor", "");
user_pref("general.useragent.vendorSub", "");
user_pref("geo.enabled", false);
user_pref("geo.wifi.uri", "");
user_pref("intl.accept_languages", "en-us, en");
user_pref("intl.charsetmenu.browser.cache", "UTF-8");
user_pref("network.cookie.cookieBehavior", 1);
user_pref("network.cookie.lifetimePolicy", 2);
user_pref("network.cookie.prefsMigrated", true);
user_pref("network.hosts.pop_server", "");
user_pref("network.protocol-handler.external-default", false);
user_pref("network.protocol-handler.external.mailto", false);
user_pref("network.protocol-handler.external.news", false);
user_pref("network.protocol-handler.external.nntp", false);
user_pref("network.protocol-handler.external.snews", false);
user_pref("network.protocol-handler.warn-external.mailto", true);
user_pref("network.protocol-handler.warn-external.news", true);
user_pref("network.protocol-handler.warn-external.nntp", true);
user_pref("network.protocol-handler.warn-external.snews", true);
user_pref("network.proxy.socks", "127.0.0.1");
user_pref("network.proxy.socks_port", 9050);
user_pref("network.proxy.socks_remote_dns", true);
user_pref("network.proxy.type", 1);
user_pref("network.security.ports.banned", "8118,8123,9050,9051");
user_pref("noscript.ABE.enabled", false);
user_pref("noscript.ABE.notify", false);
user_pref("noscript.ABE.wanIpAsLocal", false);
user_pref("noscript.autoReload", false);
user_pref("noscript.contentBlocker", true);
user_pref("noscript.default", "about:blank about:credits addons.mozilla.org flashgot.net google.com gstatic.com googlesyndication.com informaction.com yahoo.com yimg.com maone.net noscript.net hotmail.com msn.com passport.com passport.net passportimages.com live.com");
user_pref("noscript.firstRunRedirection", false);
user_pref("noscript.global", true);
user_pref("noscript.gtemp", "");
user_pref("noscript.opacizeObject", 3);
user_pref("noscript.forbidWebGL", true);
user_pref("noscript.options.tabSelectedIndexes", "5,0,0");
user_pref("noscript.policynames", "");
user_pref("noscript.secureCookies", true);
user_pref("noscript.showAllowPage", false);
user_pref("noscript.showBaseDomain", false);
user_pref("noscript.showDistrust", false);
user_pref("noscript.showRecentlyBlocked", false);
user_pref("noscript.showRevokeTemp", false);
user_pref("noscript.showTemp", false);
user_pref("noscript.showTempAllowPage", false);
user_pref("noscript.showTempToPerm", false);
user_pref("noscript.showUntrusted", false);
user_pref("noscript.subscription.lastCheck", -142148139);
user_pref("noscript.temp", "");
user_pref("noscript.untrusted", "");
user_pref("places.history.enabled", false);
user_pref("places.history.expiration.transient_current_max_pages", 120795);
user_pref("plugin.disable_full_page_plugin_for_types", "application/asx,video/x-ms-asf-plugin,application/x-mplayer2,video/x-ms-asf,video/x-ms-wm,audio/x-ms-wma,audio/x-ms-wax,video/x-ms-wmv,video/x-ms-wvx,application/x-drm-v2,application/x-drm");
user_pref("plugin.expose_full_path", true);
user_pref("plugin.scan.4xPluginFolder", false);
user_pref("plugin.scan.Acrobat", "99.0");
user_pref("plugin.scan.Quicktime", "99.0");
user_pref("plugin.scan.SunJRE", "99.0");
user_pref("plugin.scan.WindowsMediaPlayer", "99.0");
user_pref("plugin.scan.plid.all", false);
user_pref("privacy.sanitize.migrateFx3Prefs", true);
user_pref("security.enable_java", false);
user_pref("signon.rememberSignons", false);
user_pref("urlclassifier.keyupdatetime.https://sb-ssl.google.com/safebrowsing/newkey", 1235166825);
user_pref("urlclassifier.tableversion.goog-black-enchash", "1.55536");
user_pref("urlclassifier.tableversion.goog-black-url", "1.23256");
user_pref("urlclassifier.tableversion.goog-white-domain", "1.481");
user_pref("urlclassifier.tableversion.goog-white-url", "1.371");
user_pref("xpinstall.whitelist.add", "");
user_pref("xpinstall.whitelist.add.36", "");
<commit_msg>re-enable addon update checking. closes #3554.<commit_after># Mozilla User Preferences

/* Do not edit this file.
 *
 * If you make changes to this file while the application is running,
 * the changes will be overwritten when the application exits.
 *
 * To make a manual change to preferences, you can visit the URL about:config
 * For more information, see http://www.mozilla.org/unix/customizing.html#prefs
 */

user_pref("app.update.auto", false);
user_pref("app.update.enabled", false);
user_pref("app.update.lastUpdateTime.addon-background-update-timer", 1216566538);
user_pref("app.update.lastUpdateTime.background-update-timer", 1216566535);
user_pref("app.update.lastUpdateTime.blocklist-background-update-timer", 1216566538);
user_pref("app.update.lastUpdateTime.microsummary-generator-update-timer", 1232574822);
user_pref("app.update.lastUpdateTime.search-engine-update-timer", 1216566539);
user_pref("browser.bookmarks.livemark_refresh_seconds", 31536000);
user_pref("browser.cache.disk.capacity", 0);
user_pref("browser.cache.disk.enable", false);
user_pref("browser.cache.disk.smart_size.enabled", false);
user_pref("browser.cache.disk.smart_size.first_run", false);
user_pref("browser.cache.offline.enable", false);
user_pref("browser.chrome.favicons", false);
user_pref("browser.chrome.image_icons.max_size", 0);
user_pref("browser.chrome.site_icons", false);
user_pref("browser.download.manager.retention", 1);
user_pref("browser.download.useDownloadDir", false);
user_pref("browser.formfill.enable", false);
user_pref("browser.history_expire_days.mirror", 0);
user_pref("browser.microsummary.updateGenerators", false);
user_pref("browser.migration.version", 5);
user_pref("browser.places.importBookmarksHTML", false);
user_pref("browser.places.importDefaults", false);
user_pref("browser.places.leftPaneFolderId", -1);
user_pref("browser.places.migratePostDataAnnotations", false);
user_pref("browser.places.smartBookmarksVersion", 2);
user_pref("browser.places.updateRecentTagsUri", false);
user_pref("browser.preferences.advanced.selectedTabIndex", 0);
user_pref("browser.privatebrowsing.autostart", true);
user_pref("browser.rights.3.shown", true);
user_pref("browser.safebrowsing.enabled", false);
user_pref("browser.safebrowsing.malware.enabled", false);
user_pref("browser.search.suggest.enabled", false);
user_pref("browser.search.update", false);
user_pref("browser.sessionstore.privacy_level", 2);
user_pref("browser.shell.checkDefaultBrowser", false);
user_pref("browser.startup.homepage", "https://check.torproject.org/?lang=en-US&small=1");
user_pref("browser.startup.homepage_override.buildID", "20110325121920");
user_pref("browser.startup.homepage_override.mstone", "rv:2.0");
user_pref("browser.urlbar.autocomplete.enabled", false);
user_pref("browser.zoom.siteSpecific", false);
user_pref("capability.policy.maonoscript.javascript.enabled", "allAccess");
user_pref("capability.policy.maonoscript.sites", "addons.mozilla.org about: about:addons about:blank about:blocked about:certerror about:config about:crashes about:credits about:home about:neterror about:plugins about:privatebrowsing about:sessionrestore chrome: resource:");
user_pref("dom.event.contextmenu.enabled", false);
user_pref("dom.storage.enabled", false);
user_pref("extensions.bootstrappedAddons", "{}");
user_pref("extensions.bprivacy.DataDir", "/Users/erinn/Library/Preferences/Macromedia");
user_pref("extensions.bprivacy.donotaskforfolder", true);
user_pref("extensions.bprivacy.donotaskonexit", true);
user_pref("extensions.bprivacy.initiated", true);
user_pref("extensions.checkCompatibility.4.*", false);
user_pref("extensions.checkUpdateSecurity", true);
user_pref("extensions.databaseSchema", 3);
user_pref("extensions.enabledAddons", "https-everywhere@eff.org:0.9.9.development.4,{73a6fe31-595d-460b-a920-fcc0f8843232}:2.1.0.3,{d40f5e7b-d2cf-4856-b441-cc613eeffbe3}:1.50,{e0204bd5-9d31-402b-a99d-a6aa8ffebdca}:1.3.3-alpha");
user_pref("extensions.enabledItems", "langpack-en-US@firefox.mozilla.org:,{73a6fe31-595d-460b-a920-fcc0f8843232}:1.9.9.57,{e0204bd5-9d31-402b-a99d-a6aa8ffebdca}:1.2.4,{972ce4c6-7e08-4474-a285-3208198ce6fd}:3.5.8");
user_pref("extensions.enabledScopes", 1);
user_pref("extensions.pendingOperations", false);
user_pref("extensions.torbutton.fresh_install", false);
user_pref("extensions.torbutton.locked_mode", true);
user_pref("extensions.torbutton.proxies_applied", true);
user_pref("extensions.torbutton.restore_tor", true);
user_pref("extensions.torbutton.saved.auto_update", false);
user_pref("extensions.torbutton.saved.share_proxy_settings", false);
user_pref("extensions.torbutton.saved.socks_version", 5);
user_pref("extensions.torbutton.settings_applied", true);
user_pref("extensions.torbutton.socks_host", "127.0.0.1");
user_pref("extensions.torbutton.socks_port", 9050);
user_pref("extensions.torbutton.tor_enabled", true);
user_pref("extensions.torbutton.tor_memory_jar", true);
user_pref("extensions.torbutton.tz_string", "UTC+00:00");
user_pref("extensions.update.enabled", true);
user_pref("extensions.update.notifyUser", false);
user_pref("general.appname.override", "Netscape");
user_pref("general.appversion.override", "5.0 (Windows; en-US)");
user_pref("general.buildID.override", "0");
user_pref("general.oscpu.override", "Windows NT 6.1");
user_pref("general.platform.override", "Win32");
user_pref("general.productSub.override", "20100401");
user_pref("general.useragent.override", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3");
user_pref("general.useragent.vendor", "");
user_pref("general.useragent.vendorSub", "");
user_pref("geo.enabled", false);
user_pref("geo.wifi.uri", "");
user_pref("intl.accept_languages", "en-us, en");
user_pref("intl.charsetmenu.browser.cache", "UTF-8");
user_pref("network.cookie.cookieBehavior", 1);
user_pref("network.cookie.lifetimePolicy", 2);
user_pref("network.cookie.prefsMigrated", true);
user_pref("network.hosts.pop_server", "");
user_pref("network.protocol-handler.external-default", false);
user_pref("network.protocol-handler.external.mailto", false);
user_pref("network.protocol-handler.external.news", false);
user_pref("network.protocol-handler.external.nntp", false);
user_pref("network.protocol-handler.external.snews", false);
user_pref("network.protocol-handler.warn-external.mailto", true);
user_pref("network.protocol-handler.warn-external.news", true);
user_pref("network.protocol-handler.warn-external.nntp", true);
user_pref("network.protocol-handler.warn-external.snews", true);
user_pref("network.proxy.socks", "127.0.0.1");
user_pref("network.proxy.socks_port", 9050);
user_pref("network.proxy.socks_remote_dns", true);
user_pref("network.proxy.type", 1);
user_pref("network.security.ports.banned", "8118,8123,9050,9051");
user_pref("noscript.ABE.enabled", false);
user_pref("noscript.ABE.notify", false);
user_pref("noscript.ABE.wanIpAsLocal", false);
user_pref("noscript.autoReload", false);
user_pref("noscript.contentBlocker", true);
user_pref("noscript.default", "about:blank about:credits addons.mozilla.org flashgot.net google.com gstatic.com googlesyndication.com informaction.com yahoo.com yimg.com maone.net noscript.net hotmail.com msn.com passport.com passport.net passportimages.com live.com");
user_pref("noscript.firstRunRedirection", false);
user_pref("noscript.global", true);
user_pref("noscript.gtemp", "");
user_pref("noscript.opacizeObject", 3);
user_pref("noscript.forbidWebGL", true);
user_pref("noscript.options.tabSelectedIndexes", "5,0,0");
user_pref("noscript.policynames", "");
user_pref("noscript.secureCookies", true);
user_pref("noscript.showAllowPage", false);
user_pref("noscript.showBaseDomain", false);
user_pref("noscript.showDistrust", false);
user_pref("noscript.showRecentlyBlocked", false);
user_pref("noscript.showRevokeTemp", false);
user_pref("noscript.showTemp", false);
user_pref("noscript.showTempAllowPage", false);
user_pref("noscript.showTempToPerm", false);
user_pref("noscript.showUntrusted", false);
user_pref("noscript.subscription.lastCheck", -142148139);
user_pref("noscript.temp", "");
user_pref("noscript.untrusted", "");
user_pref("places.history.enabled", false);
user_pref("places.history.expiration.transient_current_max_pages", 120795);
user_pref("plugin.disable_full_page_plugin_for_types", "application/asx,video/x-ms-asf-plugin,application/x-mplayer2,video/x-ms-asf,video/x-ms-wm,audio/x-ms-wma,audio/x-ms-wax,video/x-ms-wmv,video/x-ms-wvx,application/x-drm-v2,application/x-drm");
user_pref("plugin.expose_full_path", true);
user_pref("plugin.scan.4xPluginFolder", false);
user_pref("plugin.scan.Acrobat", "99.0");
user_pref("plugin.scan.Quicktime", "99.0");
user_pref("plugin.scan.SunJRE", "99.0");
user_pref("plugin.scan.WindowsMediaPlayer", "99.0");
user_pref("plugin.scan.plid.all", false);
user_pref("privacy.sanitize.migrateFx3Prefs", true);
user_pref("security.enable_java", false);
user_pref("signon.rememberSignons", false);
user_pref("urlclassifier.keyupdatetime.https://sb-ssl.google.com/safebrowsing/newkey", 1235166825);
user_pref("urlclassifier.tableversion.goog-black-enchash", "1.55536");
user_pref("urlclassifier.tableversion.goog-black-url", "1.23256");
user_pref("urlclassifier.tableversion.goog-white-domain", "1.481");
user_pref("urlclassifier.tableversion.goog-white-url", "1.371");
user_pref("xpinstall.whitelist.add", "");
user_pref("xpinstall.whitelist.add.36", "");
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            Portions ©2008-2009 Apple Inc. All rights reserved.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================

/**
  @class

  Displays a progress bar.  You can display both a defined and an
  indeterminate progressbar.  The progress bar itself is designed to be styled
  using CSS classes with the following structure:

  The outer can form the boundary of the bar while the inner will be adjusted
  to fit the percentage of the progress.

  Creating a ProgressView accepts a number of properties, for example:
  {
    value: 50,
    minimum: 0,
    maximum: 100,
    isIndeterminate: NO,
    isEnabled: YES
  }

  Default isEnabled value is YES.

  @extends SC.View
  @extends SC.Control
  @since SproutCore 1.0
*/
SC.ProgressView = SC.View.extend(SC.Control, {

  // ........................................
  // PROPERTIES
  //

  /**
    Bind this to the current value of the progress bar.  Note that by default
    an empty value will disable the progress bar and a multiple value will make
    it indeterminate.
  */
  value: 0.50,
  valueBindingDefault: SC.Binding.single().notEmpty(),

  /**
    The minimum value of the progress.
  */
  minimum: 0,
  minimumBindingDefault: SC.Binding.single().notEmpty(),

  /**
    Optionally specify the key used to extract the minimum progress value
    from the content object.  If this is set to null then the minimum value
    will not be derived from the content object.

    @property {String}
  */
  contentMinimumKey: null,

  /**
    The maximum value of the progress bar.
  */
  maximum: 1.0,
  maximumBindingDefault: SC.Binding.single().notEmpty(),

  /**
    The value of the progress inner offset range. Should be the same as width
    of image. Default it to 24

    @type Integer
  */
  offsetRange: 24,

  /**
    Optionally specify the key used to extract the maximum progress value
    from the content object.  If this is set to null then the maximum value
    will not be derived from the content object.

    @property {String}
  */
  contentMaximumKey: null,

  /**
    Set to true if the item in progress is indeterminate.  This may be
    overridden by the actual value.
    @returns {Boolean}
  */
  isIndeterminate: NO,
  isIndeterminateBindingDefault: SC.Binding.bool(),

  /**
    Set to YES when the process is currently running.  This will cause the
    progress bar to animate, especially if it is indeterminate.
  */
  isRunning: NO,
  isRunningBindingDefault: SC.Binding.bool(),

  /**
    Set to the matrix used for background image position for animation.
    [1st image y-location, offset, total number of images]
    @property {Array}
  */
  animatedBackgroundMatrix: [],

  /**
    Optionally specify the key used to extract the isIndeterminate value
    from the content object.  If this is set to null then the isIndeterminate
    value will not be derived from the content object.

    @property {String}
  */
  contentIsIndeterminateKey: null,

  // ........................................
  // STRUCTURE
  //

  classNames: 'sc-progress-view',

  // ........................................
  // INTERNAL SUPPORT
  //

  _backgroundOffset: 0,
  _currentBackground: 1,
  _nextBackground: 1,

  // start animating at the end of the init() method.  note that we call this
  // here because we want this to make sure this function is called anytime
  // the progress view is instantiated.
  init: function() {
    sc_super();
    this.animateProgressBar(); // start animating...
  },

  // start/stop running animation based on isRunning state.
  animateProgressBar: function() {
    if (this.get('isRunning') && this.get('isVisibleInWindow')) {
      this._animateProgressBar(500); // wait to start to avoid probs
    }
  }.observes('isRunning', 'isVisibleInWindow'),

  _animateProgressBar: function(delay) {
    if (delay===0) delay = 1000/30;
    if (this.get('isRunning') && this.get('isVisibleInWindow')) {
      this.displayDidChange();
      this.invokeLater(this._animateProgressBar, delay, 30);
    }
  },

  displayProperties: 'value minimum maximum isIndeterminate'.w(),

  render: function(context, firstTime) {
    var inner, animatedBackground, value, cssString, backPosition,
        isIndeterminate = this.get('isIndeterminate'),
        isRunning = this.get('isRunning'),
        isEnabled = this.get('isEnabled'),
        offsetRange = this.get('offsetRange'),
        offset = (isIndeterminate && isRunning) ?
                (Math.floor(Date.now()/75)%offsetRange-offsetRange) : 0;

    // compute value for setting the width of the inner progress
    if (!isEnabled) {
      value = "0%" ;
    } else if (isIndeterminate) {
      value = "120%";
    } else {
      var minimum = this.get('minimum') || 0.0;
      var maximum = this.get('maximum') || 1.0;
      value = this.get('value') || 0.0;
      value = (value - minimum) / (maximum - minimum);
      if (value > 1.0) value = 1.0;

      if(isNaN(value)) value = 0.0;
      // cannot be smaller then minimum
      if(value<minimum) value = 0.0;
      // cannot be larger then maximum
      if(value>maximum) value = 1.0;
      value = (value * 100) + "%";
    }

    var classNames = {
      'sc-indeterminate': isIndeterminate,
      'sc-empty': (value <= 0),
      'sc-complete': (value >= 100)
    };

    if(firstTime) {
      var classString = this._createClassNameString(classNames);
      context.push('
',
                    '
','
',
                    '

',
                    '

',
                    '

');
    }
    else {
      context.setClass(classNames);
      inner = this.$('.sc-inner');
      animatedBackground = this.get('animatedBackgroundMatrix');
      inner.css('width', value).css('left',offset);
      if (animatedBackground.length === 3 ) {
        inner.css('backgroundPosition', '0px -'+
                (animatedBackground[0] +
                animatedBackground[1]*this._currentBackground)+'px');
        if(this._currentBackground===animatedBackground[2]-1
           || this._currentBackground===0){
          this._nextBackground *= -1;
        }
        this._currentBackground += this._nextBackground;

      }
    }

  },

  contentPropertyDidChange: function(target, key) {
    var content = this.get('content');
    this.beginPropertyChanges()
      .updatePropertyFromContent('value', key, 'contentValueKey', content)
      .updatePropertyFromContent('minimum', key, 'contentMinimumKey', content)
      .updatePropertyFromContent('maximum', key, 'contentMaximumKey', content)
      .updatePropertyFromContent('isIndeterminate', key, 'contentIsIndeterminateKey', content)
    .endPropertyChanges();
  },

  _createClassNameString: function(classNames) {
    var classNameArray = [], key;
    for(key in classNames) {
      if(!classNames.hasOwnProperty(key)) continue;
      if(classNames[key]) classNameArray.push(key);
    }
    return classNameArray.join(" ");
  }

}) ;<commit_msg>Optimize and reduce the refresh rate of progress bars<commit_after>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            Portions ©2008-2009 Apple Inc. All rights reserved.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================

/**
  @class

  Displays a progress bar.  You can display both a defined and an
  indeterminate progressbar.  The progress bar itself is designed to be styled
  using CSS classes with the following structure:

  The outer can form the boundary of the bar while the inner will be adjusted
  to fit the percentage of the progress.

  Creating a ProgressView accepts a number of properties, for example:
  {
    value: 50,
    minimum: 0,
    maximum: 100,
    isIndeterminate: NO,
    isEnabled: YES
  }

  Default isEnabled value is YES.

  @extends SC.View
  @extends SC.Control
  @since SproutCore 1.0
*/
SC.ProgressView = SC.View.extend(SC.Control, {

  // ........................................
  // PROPERTIES
  //

  /**
    Bind this to the current value of the progress bar.  Note that by default
    an empty value will disable the progress bar and a multiple value will make
    it indeterminate.
  */
  value: 0.50,
  valueBindingDefault: SC.Binding.single().notEmpty(),

  /**
    The minimum value of the progress.
  */
  minimum: 0,
  minimumBindingDefault: SC.Binding.single().notEmpty(),

  /**
    Optionally specify the key used to extract the minimum progress value
    from the content object.  If this is set to null then the minimum value
    will not be derived from the content object.

    @property {String}
  */
  contentMinimumKey: null,

  /**
    The maximum value of the progress bar.
  */
  maximum: 1.0,
  maximumBindingDefault: SC.Binding.single().notEmpty(),

  /**
    The value of the progress inner offset range. Should be the same as width
    of image. Default it to 24

    @type Integer
  */
  offsetRange: 24,

  /**
    Optionally specify the key used to extract the maximum progress value
    from the content object.  If this is set to null then the maximum value
    will not be derived from the content object.

    @property {String}
  */
  contentMaximumKey: null,

  /**
    Set to true if the item in progress is indeterminate.  This may be
    overridden by the actual value.
    @returns {Boolean}
  */
  isIndeterminate: NO,
  isIndeterminateBindingDefault: SC.Binding.bool(),

  /**
    Set to YES when the process is currently running.  This will cause the
    progress bar to animate, especially if it is indeterminate.
  */
  isRunning: NO,
  isRunningBindingDefault: SC.Binding.bool(),

  /**
    Set to the matrix used for background image position for animation.
    [1st image y-location, offset, total number of images]
    @property {Array}
  */
  animatedBackgroundMatrix: [],

  /**
    Optionally specify the key used to extract the isIndeterminate value
    from the content object.  If this is set to null then the isIndeterminate
    value will not be derived from the content object.

    @property {String}
  */
  contentIsIndeterminateKey: null,

  // ........................................
  // STRUCTURE
  //

  classNames: 'sc-progress-view',

  // ........................................
  // INTERNAL SUPPORT
  //

  _backgroundOffset: 0,
  _currentBackground: 1,
  _nextBackground: 1,

  // start animating at the end of the init() method.  note that we call this
  // here because we want this to make sure this function is called anytime
  // the progress view is instantiated.
  init: function() {
    sc_super();
    this.animateProgressBar(); // start animating...
  },

  // start/stop running animation based on isRunning state.
  animateProgressBar: function() {
    if (this.get('isRunning') && this.get('isVisibleInWindow')) {
      this._animateProgressBar(500); // wait to start to avoid probs
    }
  }.observes('isRunning', 'isVisibleInWindow'),

  _animateProgressBar: function(delay) {
    if (delay===0) delay = 1000/30;
    if (this.get('isRunning') && this.get('isVisibleInWindow')) {
      this.displayDidChange();
      this.invokeLater(this._animateProgressBar, delay, 600);
    }
  },

  displayProperties: 'value minimum maximum isIndeterminate'.w(),

  render: function(context, firstTime) {
    var inner, animatedBackground, value, cssString, backPosition,
        isIndeterminate = this.get('isIndeterminate'),
        isRunning = this.get('isRunning'),
        isEnabled = this.get('isEnabled'),
        offsetRange = this.get('offsetRange'),
        offset = (isIndeterminate && isRunning) ?
                (Math.floor(Date.now()/75)%offsetRange-offsetRange) : 0;

    // compute value for setting the width of the inner progress
    if (!isEnabled) {
      value = "0%" ;
    } else if (isIndeterminate) {
      value = "120%";
    } else {
      value = (this.get("_percentageNumeric") * 100) + "%";
    }

    var classNames = {
      'sc-indeterminate': isIndeterminate,
      'sc-empty': (value <= 0),
      'sc-complete': (value >= 100)
    };

    if(firstTime) {
      var classString = this._createClassNameString(classNames);
      context.push('
',
                    '
','
',
                    '

',
                    '

',
                    '

');
    }
    else {
      context.setClass(classNames);
      inner = this.$('.sc-inner');
      animatedBackground = this.get('animatedBackgroundMatrix');
      inner.css('width', value).css('left',offset);
      if (animatedBackground.length === 3 ) {
        inner.css('backgroundPosition', '0px -'+
                (animatedBackground[0] +
                animatedBackground[1]*this._currentBackground)+'px');
        if(this._currentBackground===animatedBackground[2]-1
           || this._currentBackground===0){
          this._nextBackground *= -1;
        }
        this._currentBackground += this._nextBackground;

      }
    }

  },

  contentPropertyDidChange: function(target, key) {
    var content = this.get('content');
    this.beginPropertyChanges()
      .updatePropertyFromContent('value', key, 'contentValueKey', content)
      .updatePropertyFromContent('minimum', key, 'contentMinimumKey', content)
      .updatePropertyFromContent('maximum', key, 'contentMaximumKey', content)
      .updatePropertyFromContent('isIndeterminate', key, 'contentIsIndeterminateKey', content)
    .endPropertyChanges();
  },

  _percentageNumeric: function(){
    var minimum = this.get('minimum') || 0.0,
        maximum = this.get('maximum') || 1.0,
        value = this.get('value') || 0.0;
    value = (value - minimum) / (maximum - minimum);
    if (value > 1.0) value = 1.0;

    if(isNaN(value)) value = 0.0;
    // cannot be smaller then minimum
    if(value<minimum) value = 0.0;
    // cannot be larger then maximum
    if(value>maximum) value = 1.0;
    return value;
  }.property('value').cacheable(),

  _createClassNameString: function(classNames) {
    var classNameArray = [], key;
    for(key in classNames) {
      if(!classNames.hasOwnProperty(key)) continue;
      if(classNames[key]) classNameArray.push(key);
    }
    return classNameArray.join(" ");
  }

}) ;<|endoftext|>


<commit_before>/**
 * hive.js
 * Copyright (C) 2013-2015 Marcel Klehr <mklehr@gmx.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
"use strict";
var gulf = require('gulf')
  , WaterlineAdapter = require('./lib/waterline-adapter')

module.exports = setup
module.exports.consumes = ['orm', 'ot', 'queue', 'broadcast']
module.exports.provides = ['sync']

function setup(plugin, imports, register) {
  var orm = imports.orm
    , ot = imports.ot
    , queue = imports.queue
    , broadcast = imports.broadcast

  var sync = {
    documents: {}
  , createDocument: function*(type) {
      var ottype = ot.getOTType(type)
      if(!ottype) throw new Error('Specified document type is not available')

      var content = ottype.create()
        , adapter = new WaterlineAdapter(orm.collections)
      var doc = yield function(cb) {
        gulf.Document.create(adapter, ottype, content, cb)
      }
      wireDocument(adapter.documentId, doc)
      this.documents[adapter.documentId] = doc

      yield orm.collections.document.update({id: adapter.documentId}, {type: type})

      return yield Document.findOne({id: doc.id})
    }
  , getDocument: function*(docId) {
      if(this.documents[docId]) return this.documents[docId]
      var doc = yield orm.collections.document.findOne({id: docId})
        , ottype = ot.getOTType(doc.type)
      var document = gulf.Document.load(
        new WaterlineAdapter(orm.collections)
      , ottype
      , docId
      , function(er){
        if(er) throw er
      })
      this.documents[docId] = document
      wireDocument(docId, document)
      return document
    }
  }

  function wireDocument(docId, doc) {
    // Use worker queue
    doc.queue = queue.document(docId)

    var b = broadcast.sync(docId)
    // send edits to other workers
    doc.on('edit', function(edit) {
      b.write(edit.pack())
    })
    // listen to, apply and distribute edits of other workers
    b.on('readable', function() {
      var chunk
      while(chunk = broadcast.read()) {
        var edit = gulf.Edit.unpack(chunk.toString(), doc.ottype)
        try {
          doc.applyEdit(edit)
        }catch(e) {
          console.warn('Applying foreign edit failed', edit, e.stack)
        }
        doc.distributeEdit(edit)
      }
    })
  }

  register(null, {sync: sync})
}
<commit_msg>sync: Fix createDocument<commit_after>/**
 * hive.js
 * Copyright (C) 2013-2015 Marcel Klehr <mklehr@gmx.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
"use strict";
var gulf = require('gulf')
  , WaterlineAdapter = require('./lib/waterline-adapter')

module.exports = setup
module.exports.consumes = ['orm', 'ot', 'queue', 'broadcast']
module.exports.provides = ['sync']

function setup(plugin, imports, register) {
  var orm = imports.orm
    , ot = imports.ot
    , queue = imports.queue
    , broadcast = imports.broadcast

  var sync = {
    documents: {}
  , createDocument: function*(type) {
      var ottype = ot.getOTType(type)
      if(!ottype) throw new Error('Specified document type is not available')

      var content = ottype.create()
        , adapter = new WaterlineAdapter(orm.collections)
      var doc = yield function(cb) {
        gulf.Document.create(adapter, ottype, content, cb)
      }
      wireDocument(adapter.documentId, doc)
      this.documents[adapter.documentId] = doc

      yield orm.collections.document.update({id: adapter.documentId}, {type: type})

      return yield orm.collections.document.findOne({id: doc.id})
    }
  , getDocument: function*(docId) {
      if(this.documents[docId]) return this.documents[docId]
      var doc = yield orm.collections.document.findOne({id: docId})
        , ottype = ot.getOTType(doc.type)
      var document = gulf.Document.load(
        new WaterlineAdapter(orm.collections)
      , ottype
      , docId
      , function(er){
        if(er) throw er
      })
      this.documents[docId] = document
      wireDocument(docId, document)
      return document
    }
  }

  function wireDocument(docId, doc) {
    // Use worker queue
    doc.queue = queue.document(docId)

    var b = broadcast.sync(docId)
    // send edits to other workers
    doc.on('edit', function(edit) {
      b.write(edit.pack())
    })
    // listen to, apply and distribute edits of other workers
    b.on('readable', function() {
      var chunk
      while(chunk = broadcast.read()) {
        var edit = gulf.Edit.unpack(chunk.toString(), doc.ottype)
        try {
          doc.applyEdit(edit)
        }catch(e) {
          console.warn('Applying foreign edit failed', edit, e.stack)
        }
        doc.distributeEdit(edit)
      }
    })
  }

  register(null, {sync: sync})
}
<|endoftext|>


<commit_before>"use strict";
/**
 *
 */
App.ApplicationController = Ember.ArrayController.extend(
{
  needs: ['user', 'application', 'category', 'products', 'pairing',
          'action', 'program', 'sync'],

  glomeid: false,
  password: '',
  loggedin: false,
  inProgress: false,
  notification: false,
  token: false,

  actions:
  {
    /**
     * should be called from the application route before model
     */
    connect: function()
    {
      console.log('here we start?');
      if (! window.localStorage.getItem('loggedin'))
      {
        window.localStorage.setItem('loggedin', false);
      }

      if (window.localStorage.getItem('glomeid') && typeof window.localStorage.getItem('glomeid') != 'undefined')
      {
        console.log('glomeid exists: ' + window.localStorage.getItem('glomeid'));
        this.set('glomeid', window.localStorage.getItem('glomeid'));
        console.log('lets login');
        this.get('controllers.user').send('auth', this.get('glomeid'), this.get('password'));
      }
      else
      {
        if (App.apiKey)
        {
          this.send('generateGlomeId');
        }
        else
        {
          console.log('It is not a Glome enabled application.');
        }
      }
    },
    loadCategories: function(category)
    {
      var self = this;
      var controller = this.get('controllers.products');
      // load categories
      controller.set('categories', this.store.find('category', { display: 'tree', filter: 'all', maxlevel: 1 }));
      // map out categories
      controller.get('categories').then(function(data)
      {
        data.content.forEach(function(item, index, enumerable)
        {
          controller.get('categoryMap')[item.get('urlName')] = item;
          item.get('subcategories').forEach(function(_item, _index, _enum)
          {
            controller.get('categoryMap')[_item.get('urlName')] = _item;
          }, item);
        });

        console.log('category: ' + category);
        if (category)
        {
          controller.set('currentCategory', controller.get('categoryMap')[category]);
        }

        console.log('loaded categories');

        var prevT = self.get('controllers.application').get('previousTransition');
        if (prevT)
        {
          console.log('go to');
          console.log('target:');
          console.log(prevT.targetName);
          console.log('params:');
          console.log(prevT.params);

          switch (prevT.targetName)
          {
            case 'index':
              self.transitionToRoute(prevT.targetName);
              break;
            case 'products.index':
              self.transitionToRoute(prevT.targetName, prevT.params.category);
              break;
            case 'products.show':
              self.transitionToRoute(prevT.targetName, prevT.params.category, prevT.params.product_id);
              break;
          }
        }
      });

      return controller.get('categories');
    },
    /**
     * Shows a notification message
     */
    notify: function(message)
    {
      this.set('notification', message);
      Ember.$('div.server.notifications').fadeIn(400, function()
      {
        Ember.$('div.server.notifications').fadeOut(5000);
      });
    },
    /**
     * Set some variables used in all view
     */
    setGlobals: function()
    {
      console.log('start here ---');
      this.set('inProgress', false);
      this.set('glomeid', window.localStorage.getItem('glomeid'));
      this.set('loggedin', window.localStorage.getItem('loggedin') == 'true');
      console.log('globals: glomeid: ' + this.get('glomeid') + ', loggedin: ' + this.get('loggedin'));
    },
    open: function()
    {
      console.log(this);
    },
    /**
     * Requests a new Glome ID from the server
     */
    generateGlomeId: function()
    {
      console.log('user:generateGlomeId');
      if (! App.apiKey || App.apiKey == '') return;
      var self = this;
      var url = App.apiHost + App.generateGlomeIdPost;
      var data =
      {
        application:
        {
          uid: App.apiHost,
          apikey: App.apiKey
        }
      };

      return Ember.$.ajax(
      {
        url: url,
        data: data,
        type: 'post',
        dataType: 'json',
        xhrFields: { withCredentials: true }
      }).then(function(data)
      {
        console.log('glome id created: ' + data.glomeid);
        window.localStorage.setItem('glomeid', data.glomeid);
        self.get('controllers.application').send('setGlobals');
        self.get('controllers.user').send('auth', data.glomeid, '');
      });
    }
  }
});
<commit_msg>use the enumerable array properly<commit_after>"use strict";
/**
 *
 */
App.ApplicationController = Ember.ArrayController.extend(
{
  needs: ['user', 'application', 'category', 'products', 'pairing',
          'action', 'program', 'sync'],

  glomeid: false,
  password: '',
  loggedin: false,
  inProgress: false,
  notification: false,
  token: false,

  actions:
  {
    /**
     * should be called from the application route before model
     */
    connect: function()
    {
      console.log('here we start?');
      if (! window.localStorage.getItem('loggedin'))
      {
        window.localStorage.setItem('loggedin', false);
      }

      if (window.localStorage.getItem('glomeid') && typeof window.localStorage.getItem('glomeid') != 'undefined')
      {
        console.log('glomeid exists: ' + window.localStorage.getItem('glomeid'));
        this.set('glomeid', window.localStorage.getItem('glomeid'));
        console.log('lets login');
        this.get('controllers.user').send('auth', this.get('glomeid'), this.get('password'));
      }
      else
      {
        if (App.apiKey)
        {
          this.send('generateGlomeId');
        }
        else
        {
          console.log('It is not a Glome enabled application.');
        }
      }
    },
    loadCategories: function(category)
    {
      var self = this;
      var controller = this.get('controllers.products');
      // load categories
      controller.set('categories', this.store.find('category', { display: 'tree', filter: 'all', maxlevel: 1 }));
      // map out categories
      controller.get('categories').then(function(data)
      {
        data.content.forEach(function(item, index, enumerable)
        {
          controller.get('categoryMap').pushObject(item);
          item.get('subcategories').forEach(function(_item, _index, _enum)
          {
            controller.get('categoryMap').pushObject(_item);
          }, item);
        });

        controller.get('categoryMap').forEach(
          function(item, index, enumerable)
          {
            // fetch all programs who have content in this category
            var vars =
            {
              catid: item.get('id'),
              application:
              {
                master_uid: App.apiHost,
                master_apikey: App.apiKey
              }
            };

            controller.get('categoryMap').objectAt(index)['programs'] = self.store.find('program', vars);
          });

        if (category)
        {
          controller.set('currentCategory', controller.get('categoryMap').findBy('urlName', category));
        }

        console.log('loaded categories');

        var prevT = self.get('controllers.application').get('previousTransition');
        if (prevT)
        {
          console.log('go to');
          console.log('target:');
          console.log(prevT.targetName);
          console.log('params:');
          console.log(prevT.params);

          switch (prevT.targetName)
          {
            case 'index':
              self.transitionToRoute(prevT.targetName);
              break;
            case 'products.index':
              self.transitionToRoute(prevT.targetName, prevT.params.category);
              break;
            case 'products.show':
              self.transitionToRoute(prevT.targetName, prevT.params.category, prevT.params.product_id);
              break;
          }
        }
      });

      return controller.get('categories');
    },
    /**
     * Shows a notification message
     */
    notify: function(message)
    {
      this.set('notification', message);
      Ember.$('div.server.notifications').fadeIn(400, function()
      {
        Ember.$('div.server.notifications').fadeOut(5000);
      });
    },
    /**
     * Set some variables used in all view
     */
    setGlobals: function()
    {
      console.log('start here ---');
      this.set('inProgress', false);
      this.set('glomeid', window.localStorage.getItem('glomeid'));
      this.set('loggedin', window.localStorage.getItem('loggedin') == 'true');
      console.log('globals: glomeid: ' + this.get('glomeid') + ', loggedin: ' + this.get('loggedin'));
    },
    open: function()
    {
      console.log(this);
    },
    /**
     * Requests a new Glome ID from the server
     */
    generateGlomeId: function()
    {
      console.log('user:generateGlomeId');
      if (! App.apiKey || App.apiKey == '') return;
      var self = this;
      var url = App.apiHost + App.generateGlomeIdPost;
      var data =
      {
        application:
        {
          uid: App.apiHost,
          apikey: App.apiKey
        }
      };

      return Ember.$.ajax(
      {
        url: url,
        data: data,
        type: 'post',
        dataType: 'json',
        xhrFields: { withCredentials: true }
      }).then(function(data)
      {
        console.log('glome id created: ' + data.glomeid);
        window.localStorage.setItem('glomeid', data.glomeid);
        self.get('controllers.application').send('setGlobals');
        self.get('controllers.user').send('auth', data.glomeid, '');
      });
    }
  }
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

app.get('/', function(req, res) {
  console.log('hello')
  res.send('Hello world')
})

app.listen(8000, function() {
  console.log('listening on port 8000')
});<commit_msg>changed port number<commit_after>var express = require('express');
var app = express();

app.get('/', function(req, res) {
  console.log('hello')
  res.send('Hello world')
})

app.listen(process.env.port || 8000, function() {
  console.log('listening on port 8000')
});<|endoftext|>


<commit_before>//the javascript for the game logic
jQuery(document).ready(function(){
	jQuery('body').on('click', '.game_butt', function () {
		nextPage();
	});
	jQuery('body').on('click', '#wolf_butt', function(){
		//var arr = jQuery('#wolf_kill').selectivity('data');
		for (var i=0; i<players.length; i++){
			for (var j=0; j< arr.length; j++){
				var role = players[i].role;
				if(players[i].role=="witch" || players[i].role=="hunter" ||  players[i].role=="cupid" ||  players[i].role=="prophet") {
					role = "god";
				}
				if (i==arr[j].id){
					data.role_count[role] -= 1;
					players[i].die();
				} else {
					if(players[i].live_status==false){
						data.role_count[role] +=1;
					}
					players[i].reset();
				}
			}
		}

	});
});

function activeCardName(){
	return jQuery('.swiper-slide-active')[0].className;
}

function nextPage(){
	swiper.slideNext();
	num_wolf = data.role_count.werewolf;
	num_god = data.role_count.god;
	num_people = data.role_count.people;
	num_total = parseInt(num_wolf)+ parseInt(num_god) + parseInt(num_people);
	if(activeCardName().includes("wolf")){
		//we are at the wolf page
		//count the numeber of wolves and populate the option box
		document.getElementById('wolf_identity').innerHTML = "<optgroup disabled hidden></optgroup>";
		document.getElementById('wolf_kill').innerHTML = "";
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('wolf_identity').appendChild(opt);
		}
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('wolf_kill').appendChild(opt);
		}
	} else if (activeCardName().includes("witch")){
		//we are at the witch page
		document.getElementById('witch_identity').innerHTML = "";
		document.getElementById('witch_save').innerHTML = "";
		document.getElementById('witch_kill').innerHTML = "";
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('witch_identity').appendChild(opt);
		}
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('witch_save').appendChild(opt);
		}
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('witch_kill').appendChild(opt);
		}
	} else if (activeCardName().includes("prophet")) {
		document.getElementById('prophet_identity').innerHTML = "";
		document.getElementById('prophet_check').innerHTML = "";
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('prophet_identity').appendChild(opt);
		}
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('prophet_check').appendChild(opt);
		}
	}
}<commit_msg>update<commit_after>//the javascript for the game logic
jQuery(document).ready(function(){
	jQuery('body').on('click', '.game_butt', function () {
		nextPage();
	});

	jQuery('body').on('click', '#wolf_butt', function(){
		var arr =  [];
		jQuery('#wolf_identity:selected').each(function(){
	        arr.push(jQuery(this).val());
	    });
	    console.log(arr);
		for (var i=0; i<data.players.length; i++){
			for (var j=0; j< arr.length; j++){
				var role = data.players[i].role;
				if(data.players[i].role=="witch" || data.players[i].role=="hunter" ||  data.players[i].role=="cupid" ||  data.players[i].role=="prophet") {
					role = "god";
				}
				if (i==arr[j].id){
					data.role_count[role] -= 1;
					players[i].die();
				} else {
					if(data.players[i].live_status==false){
						data.role_count[role] +=1;
					}
					data.players[i].reset();
				}
			}
		}

	});
});

function activeCardName(){
	return jQuery('.swiper-slide-active')[0].className;
}

function nextPage(){
	swiper.slideNext();
	num_wolf = data.role_count.werewolf;
	num_god = data.role_count.god;
	num_people = data.role_count.people;
	num_total = parseInt(num_wolf)+ parseInt(num_god) + parseInt(num_people);
	if(activeCardName().includes("wolf")){
		//we are at the wolf page
		//count the numeber of wolves and populate the option box
		document.getElementById('wolf_identity').innerHTML = "<optgroup disabled hidden></optgroup>";
		document.getElementById('wolf_kill').innerHTML = "";
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('wolf_identity').appendChild(opt);
		}
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('wolf_kill').appendChild(opt);
		}
	} else if (activeCardName().includes("witch")){
		//we are at the witch page
		document.getElementById('witch_identity').innerHTML = "";
		document.getElementById('witch_save').innerHTML = "";
		document.getElementById('witch_kill').innerHTML = "";
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('witch_identity').appendChild(opt);
		}
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('witch_save').appendChild(opt);
		}
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('witch_kill').appendChild(opt);
		}
	} else if (activeCardName().includes("prophet")) {
		document.getElementById('prophet_identity').innerHTML = "";
		document.getElementById('prophet_check').innerHTML = "";
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('prophet_identity').appendChild(opt);
		}
		for (var i=0;i<num_total;i++){
		    var opt = document.createElement('option');
		    opt.value = i+1;
		    opt.innerHTML = (i+1).toString() + " 号";
		 	document.getElementById('prophet_check').appendChild(opt);
		}
	}
}<|endoftext|>


<commit_before>'use strict'

class Cluster {
  static clean () {
    var clusters = Cluster.listAll()
    for (var clustername of clusters) {
      var cluster = new Cluster(clustername)
      if (cluster.getCreeps().length <= 0) {
        delete Memory.clusters[clustername]
      }
    }
  }

  static listAll () {
    if (!Memory.clusters) {
      return []
    }
    return Object.keys(Memory.clusters)
  }

  constructor (name, room = false) {
    this.name = name
    this.room = room
    if (!Memory.clusters) {
      Memory.clusters = {}
    }
    if (!Memory.clusters[name]) {
      Memory.clusters[name] = {
        'creeps': []
      }
    }
    this.memory = Memory.clusters[name]
    this.creeps = []
    for (var creepname of this.memory.creeps) {
      if (Game.creeps[creepname]) {
        this.creeps.push(Game.creeps[creepname])
        continue
      }
      if (room) {
        if (!room.isQueued(creepname)) {
          this.memory.creeps.indexOf.splice(this.memory.creeps.indexOf(creepname), 1)
        }
      } else if (!Room.isQueued(creepname)) {
        this.memory.creeps.indexOf.splice(this.memory.creeps.indexOf(creepname), 1)
      }
    }
  }

  sizeCluster (role, quantity, options = {}, room = false) {
    if (this.memory.creeps.length >= quantity) {
      return true
    }
    var spawnroom = room || this.room
    while (this.memory.creeps.length < quantity) {
      this.memory.creeps.push(spawnroom.queueCreep(role, options))
    }
    return false
  }

  getCreeps () {
    return this.creeps
  }

  forEach (creepAction) {
    return this.getCreeps().forEach(creepAction)
  }
}

module.exports = Cluster
<commit_msg>fix bug removing dead creeps from cluster<commit_after>'use strict'

class Cluster {
  static clean () {
    var clusters = Cluster.listAll()
    for (var clustername of clusters) {
      var cluster = new Cluster(clustername)
      if (cluster.getCreeps().length <= 0) {
        delete Memory.clusters[clustername]
      }
    }
  }

  static listAll () {
    if (!Memory.clusters) {
      return []
    }
    return Object.keys(Memory.clusters)
  }

  constructor (name, room = false) {
    this.name = name
    this.room = room
    if (!Memory.clusters) {
      Memory.clusters = {}
    }
    if (!Memory.clusters[name]) {
      Memory.clusters[name] = {
        'creeps': []
      }
    }
    this.memory = Memory.clusters[name]
    this.creeps = []
    for (var creepname of this.memory.creeps) {
      if (Game.creeps[creepname]) {
        this.creeps.push(Game.creeps[creepname])
        continue
      }
      if (room) {
        if (!room.isQueued(creepname)) {
          this.memory.creeps.splice(this.memory.creeps.indexOf(creepname), 1)
        }
      } else if (!Room.isQueued(creepname)) {
        this.memory.creeps.splice(this.memory.creeps.indexOf(creepname), 1)
      }
    }
  }

  sizeCluster (role, quantity, options = {}, room = false) {
    if (this.memory.creeps.length >= quantity) {
      return true
    }
    var spawnroom = room || this.room
    while (this.memory.creeps.length < quantity) {
      this.memory.creeps.push(spawnroom.queueCreep(role, options))
    }
    return false
  }

  getCreeps () {
    return this.creeps
  }

  forEach (creepAction) {
    return this.getCreeps().forEach(creepAction)
  }
}

module.exports = Cluster
<|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2021, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

import async from 'async';
import csv from 'babyparse';
import sundial from 'sundial';

import TZOUtil from '../../TimezoneOffsetUtil';
import annotate from '../../eventAnnotations';

const isBrowser = typeof window !== 'undefined';
const debug = isBrowser ? require('bows')('LibreViewDriver') : console.log;

function addOutOfRangeAnnotation(recordBuilder, low, high, step, type) {
  if (low !== null && recordBuilder.value < low + step) {
    recordBuilder.with_value(low);
    annotate.annotateEvent(recordBuilder, {
      code: `${type}/out-of-range`,
      value: 'low',
      threshold: low + step,
    });
  } else if (high !== null && recordBuilder.value > high - step) {
    recordBuilder.with_value(high);
    annotate.annotateEvent(recordBuilder, {
      code: `${type}/out-of-range`,
      value: 'high',
      threshold: high - step,
    });
  }
}

module.exports = (config) => {
  const LIBREVIEW_TS_FORMAT = 'DD/MM/YYYY HH:mm';

  const RECORD_TYPE_HISTORIC = 0;
  const RECORD_TYPE_SCAN = 1;
  const RECORD_TYPE_STRIP = 2;
  const RECORD_TYPE_KETONE = 3;

  const GLUCOSE_HI = {
    'mg/dL': 500,
    'mmol/L': 27.8,
  };

  const GLUCOSE_LO = {
    'mg/dL': 40,
    'mmol/L': 2.2,
  };

  const KETONE_HI = 8.0;
  const KETONE_LO = null; // ketone value cannot be low

  const TYPES_TO_READ = {
    0: 'Historic Glucose',
    1: 'Scan Glucose',
    2: 'Strip Glucose',
    3: 'Ketone',

    4: false, // Rapid-Acting Insulin (units) OR Non-numeric Long-Acting Insulin
    5: false, // Non-numeric Food
    6: false, // ?
  };

  const typesUnits = {
    'Historic Glucose': '',
    'Scan Glucose': '',
    'Strip Glucose': '',
    Ketone: '',
  };

  return {
    detect: (obj, cb) => {
      debug('LibreView Detect!');
      cb(null, obj);
    },

    setup: (deviceInfo, progress, cb) => {
      debug('LibreView Setup!');
      progress(100);
      deviceInfo = deviceInfo || {};
      cb(null, { devices: deviceInfo });
    },

    connect: (progress, payload, cb) => {
      debug('LibreView Connect!');
      progress(100);
      cb(null, payload);
    },

    getConfigInfo: (progress, payload, cb) => {
      debug('LibreView GetConfigInfo!');
      progress(100);
      cb(null, payload);
    },

    fetchData: (progress, payload, cb) => {
      debug('LibreView FetchData!');
      let data = config.filedata;
      payload.filedata = config.filedata; // to store as blob

      if (typeof config.filedata !== 'string') {
        data = new TextDecoder().decode(new Uint8Array(config.filedata));
      }

      debug('LibreView data', data.length);

      const endOfPreamble = data.indexOf('\n') + 1;
      // Setup the preamble to have everything up to the header line
      payload.preamble = csv.parse(data.substr(0, endOfPreamble), {});

      // Store the rest of the data
      const parsed = csv.parse(data.substr(endOfPreamble), {
        header: true,
        dynamicTyping: true,
      });

      parsed.meta.fields.forEach((field) => {
        Object.keys(typesUnits).forEach((key) => {
          if (field.startsWith(key)) {
            typesUnits[key] = field.replace(`${key} `, '');
          }
        });
      });

      for (const recordType of [RECORD_TYPE_HISTORIC, RECORD_TYPE_SCAN, RECORD_TYPE_STRIP]) {
        const units = typesUnits[TYPES_TO_READ[recordType]];
        if (GLUCOSE_HI[units] === undefined) {
          const error = `Unexpected units for ${TYPES_TO_READ[recordType]}: ${units}`;
          debug('Error:', error);
          return cb(new Error(error));
        }
      }

      const ketoneUnits = typesUnits[TYPES_TO_READ[RECORD_TYPE_KETONE]];
      if (ketoneUnits !== 'mmol/L') {
        const error = `Unexpected units for ${TYPES_TO_READ[RECORD_TYPE_KETONE]}: ${ketoneUnits}`;
        debug('Error:', error);
        return cb(new Error(error));
      }

      const rows = [];
      for (let i = parsed.data.length - 1; i >= 0; --i) {
        const datum = parsed.data[i];

        if (datum.Device === '') {
          /* eslint-disable-next-line no-continue */
          continue;
        }

        datum.jsDate = sundial.parseFromFormat(datum['Device Timestamp'],
          LIBREVIEW_TS_FORMAT);

        datum.deviceTime = sundial.formatDeviceTime(datum.jsDate);
        datum.csvIndex = i;

        const recordType = datum['Record Type'];
        if (!TYPES_TO_READ[recordType]) {
          /* eslint-disable-next-line no-continue */
          continue;
        }
        datum.device = `${datum.Device} ${datum['Serial Number']}`;
        datum.type = TYPES_TO_READ[recordType];
        datum.units = typesUnits[datum.type];
        datum.value = datum[`${datum.type} ${datum.units}`];

        rows.push(datum);
      }

      payload.theData = rows;

      debug(`Read ${rows.length} entries`);

      debug('Separate into per-device arrays');
      for (let k = 0; k < payload.theData.length; ++k) {
        const key = payload.theData[k].device;
        let device = payload.devices[key];
        if (device == null) {
          device = {};
          payload.devices[key] = device;

          device.data = [];

          device.info = {
            serialNumber: payload.theData[k]['Serial Number'],
            deviceId: key,
          };
        }
        device.data.push(payload.theData[k]);
      }

      delete payload.theData;

      let entryCount = 0;
      Object.keys(payload.devices).forEach((key) => {
        const device = payload.devices[key];
        debug(`Device ${key}: ${device.data.length} entries`);
        entryCount += device.data.length;
      });

      if (entryCount === 0) {
        debug('Error reading file, no data parsed.');
        return cb(new Error('Error reading file, no data parsed.'));
      }

      return cb(null, payload);
    },

    processData: (progress, payload, cb) => {
      debug('LibreView ProcessData!');
      progress(20);

      let ts = 0;
      Object.keys(payload.devices).forEach((key) => {
        const device = payload.devices[key];
        const mostRecentDatum = device.data[0];
        if (mostRecentDatum.jsDate > ts) {
          ts = mostRecentDatum.jsDate;
        }
      });

      const mostRecent = sundial.applyTimezone(ts, config.timezone).toISOString();

      Object.keys(payload.devices).forEach((key) => {
        const device = payload.devices[key];
        const events = device.data;

        const postRecords = [];
        payload.postRecords = postRecords;

        config.tzoUtil = new TZOUtil(config.timezone, mostRecent, postRecords);
        device.postRecords = postRecords;
        config.builder.setDefaults({ deviceId: device.info.deviceId });

        events.filter(elem => elem['Record Type'] === RECORD_TYPE_HISTORIC)
          .forEach((record) => {
            const cbg = config.builder.makeCBG()
              .with_value(record.value)
              .with_units(record.units)
              .with_deviceTime(sundial.formatDeviceTime(record.jsDate))
              .set('index', record.csvIndex);

            config.tzoUtil.fillInUTCInfo(cbg, record.jsDate);

            addOutOfRangeAnnotation(cbg, GLUCOSE_LO, GLUCOSE_HI, 1, 'bg');
            postRecords.push(cbg.done());
          });
        events.filter(elem => (elem['Record Type'] === RECORD_TYPE_STRIP || elem['Record Type'] === RECORD_TYPE_SCAN))
          .forEach((record) => {
            const smbg = config.builder.makeSMBG()
              .with_value(record.value)
              .with_units(record.units)
              .with_deviceTime(sundial.formatDeviceTime(record.jsDate))
              .set('index', record.csvIndex);

            if (record['Record Type'] === RECORD_TYPE_SCAN) {
              smbg.with_subType('scanned');
            }

            addOutOfRangeAnnotation(smbg, GLUCOSE_LO[record.units], GLUCOSE_HI[record.units], 1, 'bg');
            config.tzoUtil.fillInUTCInfo(smbg, record.jsDate);

            postRecords.push(smbg.done());
          });
        events.filter(elem => elem['Record Type'] === RECORD_TYPE_KETONE)
          .forEach((record) => {
            const ketone = config.builder.makeBloodKetone()
              .with_value(record.value)
              .with_units(record.units)
              .with_deviceTime(sundial.formatDeviceTime(record.jsDate))
              .set('index', record.csvIndex);

            addOutOfRangeAnnotation(ketone, KETONE_LO, KETONE_HI, 1, 'ketone');
            config.tzoUtil.fillInUTCInfo(ketone, record.jsDate);
            postRecords.push(ketone.done());
          });
      });
      progress(100);
      cb(null, payload);
    },

    uploadData: (progress, payload, cb) => {
      progress(0);
      payload.post_records = [];

      async.eachSeries(Object.keys(payload.devices), (key, done) => {
        const device = payload.devices[key];
        const deviceRecords = device.postRecords;

        const sessionInfo = {
          deviceTags: ['bgm', 'cgm'],
          deviceManufacturers: ['Abbott'],

          deviceModel: key,
          deviceSerialNumber: device.info.serialNumber,
          deviceId: device.info.deviceId,

          start: sundial.utcDateString(),
          timeProcessing: config.tzoUtil.type,
          tzName: config.timezone,
          version: config.version,
          blobId: payload.blobId,
          source: 'LibreView', // to be able to distinguish from direct uploads
        };

        if (device.info.annotations) {
          annotate.annotateEvent(sessionInfo, device.info.annotations);
        }

        config.api.upload.toPlatform(
          deviceRecords, sessionInfo, progress, config.groupId,
          (err) => {
            if (err) {
              debug(err);
              return done(err);
            }

            payload.post_records = payload.post_records.concat(deviceRecords);
            return done();
          }, 'dataservices',
        );
      }, (err) => {
        if (err) {
          progress(100);
          cb(err);
        }
        progress(100);
        cb(null, payload);
      });
    },

    disconnect: (progress, payload, cb) => {
      debug('LibreView Disconnect!');
      progress(100);
      cb(null, payload);
    },

    cleanup: (progress, payload, cb) => {
      debug('LibreView Cleanup!');
      progress(100);
      cb(null, payload);
    },
  };
};
<commit_msg>lib/drivers/abbott/libreViewDriver.js: improve deviceModel and deviceId<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2021, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

import async from 'async';
import csv from 'babyparse';
import sundial from 'sundial';

import TZOUtil from '../../TimezoneOffsetUtil';
import annotate from '../../eventAnnotations';

const isBrowser = typeof window !== 'undefined';
const debug = isBrowser ? require('bows')('LibreViewDriver') : console.log;

function addOutOfRangeAnnotation(recordBuilder, low, high, step, type) {
  if (low !== null && recordBuilder.value < low + step) {
    recordBuilder.with_value(low);
    annotate.annotateEvent(recordBuilder, {
      code: `${type}/out-of-range`,
      value: 'low',
      threshold: low + step,
    });
  } else if (high !== null && recordBuilder.value > high - step) {
    recordBuilder.with_value(high);
    annotate.annotateEvent(recordBuilder, {
      code: `${type}/out-of-range`,
      value: 'high',
      threshold: high - step,
    });
  }
}

module.exports = (config) => {
  const LIBREVIEW_TS_FORMAT = 'DD/MM/YYYY HH:mm';

  const RECORD_TYPE_HISTORIC = 0;
  const RECORD_TYPE_SCAN = 1;
  const RECORD_TYPE_STRIP = 2;
  const RECORD_TYPE_KETONE = 3;

  const GLUCOSE_HI = {
    'mg/dL': 500,
    'mmol/L': 27.8,
  };

  const GLUCOSE_LO = {
    'mg/dL': 40,
    'mmol/L': 2.2,
  };

  const KETONE_HI = 8.0;
  const KETONE_LO = null; // ketone value cannot be low

  const TYPES_TO_READ = {
    0: 'Historic Glucose',
    1: 'Scan Glucose',
    2: 'Strip Glucose',
    3: 'Ketone',

    4: false, // Rapid-Acting Insulin (units) OR Non-numeric Long-Acting Insulin
    5: false, // Non-numeric Food
    6: false, // ?
  };

  const typesUnits = {
    'Historic Glucose': '',
    'Scan Glucose': '',
    'Strip Glucose': '',
    Ketone: '',
  };

  return {
    detect: (obj, cb) => {
      debug('LibreView Detect!');
      cb(null, obj);
    },

    setup: (deviceInfo, progress, cb) => {
      debug('LibreView Setup!');
      progress(100);
      deviceInfo = deviceInfo || {};
      cb(null, { devices: deviceInfo });
    },

    connect: (progress, payload, cb) => {
      debug('LibreView Connect!');
      progress(100);
      cb(null, payload);
    },

    getConfigInfo: (progress, payload, cb) => {
      debug('LibreView GetConfigInfo!');
      progress(100);
      cb(null, payload);
    },

    fetchData: (progress, payload, cb) => {
      debug('LibreView FetchData!');
      let data = config.filedata;
      payload.filedata = config.filedata; // to store as blob

      if (typeof config.filedata !== 'string') {
        data = new TextDecoder().decode(new Uint8Array(config.filedata));
      }

      debug('LibreView data', data.length);

      const endOfPreamble = data.indexOf('\n') + 1;
      // Setup the preamble to have everything up to the header line
      payload.preamble = csv.parse(data.substr(0, endOfPreamble), {});

      // Store the rest of the data
      const parsed = csv.parse(data.substr(endOfPreamble), {
        header: true,
        dynamicTyping: true,
      });

      parsed.meta.fields.forEach((field) => {
        Object.keys(typesUnits).forEach((key) => {
          if (field.startsWith(key)) {
            typesUnits[key] = field.replace(`${key} `, '');
          }
        });
      });

      for (const recordType of [RECORD_TYPE_HISTORIC, RECORD_TYPE_SCAN, RECORD_TYPE_STRIP]) {
        const units = typesUnits[TYPES_TO_READ[recordType]];
        if (GLUCOSE_HI[units] === undefined) {
          const error = `Unexpected units for ${TYPES_TO_READ[recordType]}: ${units}`;
          debug('Error:', error);
          return cb(new Error(error));
        }
      }

      const ketoneUnits = typesUnits[TYPES_TO_READ[RECORD_TYPE_KETONE]];
      if (ketoneUnits !== 'mmol/L') {
        const error = `Unexpected units for ${TYPES_TO_READ[RECORD_TYPE_KETONE]}: ${ketoneUnits}`;
        debug('Error:', error);
        return cb(new Error(error));
      }

      const rows = [];
      for (let i = parsed.data.length - 1; i >= 0; --i) {
        const datum = parsed.data[i];

        if (datum.Device === '') {
          /* eslint-disable-next-line no-continue */
          continue;
        }

        datum.jsDate = sundial.parseFromFormat(datum['Device Timestamp'],
          LIBREVIEW_TS_FORMAT);

        datum.deviceTime = sundial.formatDeviceTime(datum.jsDate);
        datum.csvIndex = i;

        const recordType = datum['Record Type'];
        if (!TYPES_TO_READ[recordType]) {
          /* eslint-disable-next-line no-continue */
          continue;
        }
        datum.device = `${datum.Device} ${datum['Serial Number']}`;
        datum.type = TYPES_TO_READ[recordType];
        datum.units = typesUnits[datum.type];
        datum.value = datum[`${datum.type} ${datum.units}`];

        rows.push(datum);
      }

      payload.theData = rows;

      debug(`Read ${rows.length} entries`);

      debug('Separate into per-device arrays');
      for (let k = 0; k < payload.theData.length; ++k) {
        const key = payload.theData[k].device;
        let device = payload.devices[key];
        if (device == null) {
          device = {};
          payload.devices[key] = device;

          device.data = [];

          device.info = {
            deviceModel: payload.theData[k]['Device'],
            serialNumber: payload.theData[k]['Serial Number'],
          };
          device.info.deviceId = ("Abbott" +
                             device.info.deviceModel +
                             device.info.serialNumber
                            ).replace(/ /g, '');
            debug(device.info.deviceId)
        }
        device.data.push(payload.theData[k]);
      }

      delete payload.theData;

      let entryCount = 0;
      Object.keys(payload.devices).forEach((key) => {
        const device = payload.devices[key];
        debug(`Device ${key}: ${device.data.length} entries`);
        entryCount += device.data.length;
      });

      if (entryCount === 0) {
        debug('Error reading file, no data parsed.');
        return cb(new Error('Error reading file, no data parsed.'));
      }

      return cb(null, payload);
    },

    processData: (progress, payload, cb) => {
      debug('LibreView ProcessData!');
      progress(20);

      let ts = 0;
      Object.keys(payload.devices).forEach((key) => {
        const device = payload.devices[key];
        const mostRecentDatum = device.data[0];
        if (mostRecentDatum.jsDate > ts) {
          ts = mostRecentDatum.jsDate;
        }
      });

      const mostRecent = sundial.applyTimezone(ts, config.timezone).toISOString();

      Object.keys(payload.devices).forEach((key) => {
        const device = payload.devices[key];
        const events = device.data;

        const postRecords = [];
        payload.postRecords = postRecords;

        config.tzoUtil = new TZOUtil(config.timezone, mostRecent, postRecords);
        device.postRecords = postRecords;
        config.builder.setDefaults({ deviceId: device.info.deviceId });

        events.filter(elem => elem['Record Type'] === RECORD_TYPE_HISTORIC)
          .forEach((record) => {
            const cbg = config.builder.makeCBG()
              .with_value(record.value)
              .with_units(record.units)
              .with_deviceTime(sundial.formatDeviceTime(record.jsDate))
              .set('index', record.csvIndex);

            config.tzoUtil.fillInUTCInfo(cbg, record.jsDate);

            addOutOfRangeAnnotation(cbg, GLUCOSE_LO, GLUCOSE_HI, 1, 'bg');
            postRecords.push(cbg.done());
          });
        events.filter(elem => (elem['Record Type'] === RECORD_TYPE_STRIP || elem['Record Type'] === RECORD_TYPE_SCAN))
          .forEach((record) => {
            const smbg = config.builder.makeSMBG()
              .with_value(record.value)
              .with_units(record.units)
              .with_deviceTime(sundial.formatDeviceTime(record.jsDate))
              .set('index', record.csvIndex);

            if (record['Record Type'] === RECORD_TYPE_SCAN) {
              smbg.with_subType('scanned');
            }

            addOutOfRangeAnnotation(smbg, GLUCOSE_LO[record.units], GLUCOSE_HI[record.units], 1, 'bg');
            config.tzoUtil.fillInUTCInfo(smbg, record.jsDate);

            postRecords.push(smbg.done());
          });
        events.filter(elem => elem['Record Type'] === RECORD_TYPE_KETONE)
          .forEach((record) => {
            const ketone = config.builder.makeBloodKetone()
              .with_value(record.value)
              .with_units(record.units)
              .with_deviceTime(sundial.formatDeviceTime(record.jsDate))
              .set('index', record.csvIndex);

            addOutOfRangeAnnotation(ketone, KETONE_LO, KETONE_HI, 1, 'ketone');
            config.tzoUtil.fillInUTCInfo(ketone, record.jsDate);
            postRecords.push(ketone.done());
          });
      });
      progress(100);
      cb(null, payload);
    },

    uploadData: (progress, payload, cb) => {
      progress(0);
      payload.post_records = [];

      async.eachSeries(Object.keys(payload.devices), (key, done) => {
        const device = payload.devices[key];
        const deviceRecords = device.postRecords;

        const sessionInfo = {
          deviceTags: ['bgm', 'cgm'],
          deviceManufacturers: ['Abbott'],

          deviceModel: device.info.deviceModel,
          deviceSerialNumber: device.info.serialNumber,
          deviceId: device.info.deviceId,

          start: sundial.utcDateString(),
          timeProcessing: config.tzoUtil.type,
          tzName: config.timezone,
          version: config.version,
          blobId: payload.blobId,
          source: 'LibreView', // to be able to distinguish from direct uploads
        };

        if (device.info.annotations) {
          annotate.annotateEvent(sessionInfo, device.info.annotations);
        }

        config.api.upload.toPlatform(
          deviceRecords, sessionInfo, progress, config.groupId,
          (err) => {
            if (err) {
              debug(err);
              return done(err);
            }

            payload.post_records = payload.post_records.concat(deviceRecords);
            return done();
          }, 'dataservices',
        );
      }, (err) => {
        if (err) {
          progress(100);
          cb(err);
        }
        progress(100);
        cb(null, payload);
      });
    },

    disconnect: (progress, payload, cb) => {
      debug('LibreView Disconnect!');
      progress(100);
      cb(null, payload);
    },

    cleanup: (progress, payload, cb) => {
      debug('LibreView Cleanup!');
      progress(100);
      cb(null, payload);
    },
  };
};
<|endoftext|>


<commit_before>/*
 * Copyright 2014, Gregg Tavares.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Gregg Tavares. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

"use strict";

var settingsOptionSpec = {
      option: 'settings',         type: 'String',     description: 'settings: key=value, ',
};

var optionSpec = {
  options: [
    { option: 'help', alias: 'h', type: 'Boolean',    description: 'displays help'},
    { option: 'config-path',      type: 'String',     description: 'config path'},
    { option: 'settings-path',    type: 'String',     description: 'settings path'},
    { option: 'private-server',   type: 'Boolean',    description: 'do not inform happyfuntimes.net about this server. Users will not be able to use happyfuntimes.net to connect to your games'},
    { option: 'debug',            type: 'Boolean',    description: 'check more things'},
    { option: 'verbose',          type: 'Boolean',    description: 'print more stuff'},
    settingsOptionSpec,
  ].concat(require('./common-cli-options').options),
  helpStyle: {
    typeSeparator: '=',
    descriptionSeparator: ' : ',
    initialIndent: 4,
  },
};

var config     = require('../lib/config');
var log        = require('../lib/log');
var optionator = require('optionator')(optionSpec);

try {
  var args = optionator.parse(process.argv);
} catch (e) {
  console.error(e);
  process.exit(1);
}

var printHelp = function() {
  var settings = [];
  Object.keys(require('../lib/config').getSettings().settings).forEach(function(key) {
    settings.push(key);
  });
  settingsOptionSpec.description += settings.join(", ");

  console.log(optionator.generateHelp());
  process.exit(0);
};

if (args.help) {
  printHelp();
}

log.config(args);
config.setup(args);
if (args.settings) {
  var settings = config.getSettings().settings
  args.settings.split(",").forEach(function(setting) {
    var keyValue = setting.split("=");
    var key = keyValue[0];
    var value = keyValue[1];
    if (!settings[key]) {
      console.error("no setting: '" + key + "'");
      printHelp();
    }
    settings[key] = value;
  });
}

if (args.appMode) {
  require('../lib/games').init();
}

var browser   = require('../lib/browser');
var debug     = require('debug')('server');
var DNSServer = require('./dnsserver');
var iputils   = require('../lib/iputils');
var Promise   = require('promise');
var HFTServer = require('./hft-server');

if (!args.address) {
  var addresses = iputils.getIpAddress();

  if (addresses.length < 1) {
    console.error("No IP address found for DNS");
  }
  args.address = addresses[0];
  if (addresses.length > 1) {
    console.log("more than 1 IP address found: " + addresses);
  }
}
console.log("using ip address: " + args.address);

var server;
var launchBrowser = function(err) {
  var next = function() {
    if (err) {
      console.error(err);
      process.exit(1);
    } else {
      if (args.appMode) {
        console.log([
          "",
          "---==> HappyFunTimes Running <==---",
          "",
        ].join("\n"))
      }
    }
  };

  var p;
  if (args.appMode || args.show) {
    var name = args.show || "games";
    p = browser.launch("http://localhost:" + server.getSettings().port + "/" + name + ".html", config.getConfig().preferredBrowser);
  } else {
    p = Promise.resolve();
  }
  p.then(function() {
     next();
  }).catch(function(err) {
    console.error(err);
    next();
  });
}

server = new HFTServer(args, launchBrowser);

if (args.dns) {
  var dnsServer = new DNSServer({address: args.address});
}

<commit_msg>make hft fail if --dns is used but can't get port 80<commit_after>/*
 * Copyright 2014, Gregg Tavares.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Gregg Tavares. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

"use strict";

var settingsOptionSpec = {
      option: 'settings',         type: 'String',     description: 'settings: key=value, ',
};

var optionSpec = {
  options: [
    { option: 'help', alias: 'h', type: 'Boolean',    description: 'displays help'},
    { option: 'config-path',      type: 'String',     description: 'config path'},
    { option: 'settings-path',    type: 'String',     description: 'settings path'},
    { option: 'private-server',   type: 'Boolean',    description: 'do not inform happyfuntimes.net about this server. Users will not be able to use happyfuntimes.net to connect to your games'},
    { option: 'debug',            type: 'Boolean',    description: 'check more things'},
    { option: 'verbose',          type: 'Boolean',    description: 'print more stuff'},
    settingsOptionSpec,
  ].concat(require('./common-cli-options').options),
  helpStyle: {
    typeSeparator: '=',
    descriptionSeparator: ' : ',
    initialIndent: 4,
  },
};

var config     = require('../lib/config');
var log        = require('../lib/log');
var optionator = require('optionator')(optionSpec);

try {
  var args = optionator.parse(process.argv);
} catch (e) {
  console.error(e);
  process.exit(1);
}

var printHelp = function() {
  var settings = [];
  Object.keys(require('../lib/config').getSettings().settings).forEach(function(key) {
    settings.push(key);
  });
  settingsOptionSpec.description += settings.join(", ");

  console.log(optionator.generateHelp());
  process.exit(0);
};

if (args.help) {
  printHelp();
}

log.config(args);
config.setup(args);
if (args.settings) {
  var settings = config.getSettings().settings
  args.settings.split(",").forEach(function(setting) {
    var keyValue = setting.split("=");
    var key = keyValue[0];
    var value = keyValue[1];
    if (!settings[key]) {
      console.error("no setting: '" + key + "'");
      printHelp();
    }
    settings[key] = value;
  });
}

if (args.appMode) {
  require('../lib/games').init();
}

var browser   = require('../lib/browser');
var debug     = require('debug')('server');
var DNSServer = require('./dnsserver');
var iputils   = require('../lib/iputils');
var Promise   = require('promise');
var HFTServer = require('./hft-server');

if (!args.address) {
  var addresses = iputils.getIpAddress();

  if (addresses.length < 1) {
    console.error("No IP address found for DNS");
  }
  args.address = addresses[0];
  if (addresses.length > 1) {
    console.log("more than 1 IP address found: " + addresses);
  }
}
console.log("using ip address: " + args.address);

var server;
var launchBrowser = function(err) {
  var next = function() {
    if (err) {
      console.error(err);
      process.exit(1);
    } else {
      if (args.appMode) {
        console.log([
          "",
          "---==> HappyFunTimes Running <==---",
          "",
        ].join("\n"))
      }
    }
  };

  var p;
  if (args.appMode || args.show) {
    var name = args.show || "games";
    p = browser.launch("http://localhost:" + server.getSettings().port + "/" + name + ".html", config.getConfig().preferredBrowser);
  } else {
    p = Promise.resolve();
  }
  p.then(function() {
     next();
  }).catch(function(err) {
    console.error(err);
    next();
  });
}

server = new HFTServer(args, launchBrowser);

if (args.dns) {
  var dnsServer = new DNSServer({address: args.address});
  server.on('ports', function(ports) {
    if (ports.indexOf("80") < 0 && ports.indexOf(80) < 0) {
      console.error("You specified --dns but happyFunTimes could not use port 80.");
      console.error("Do you need to run this as admin or use sudo?");
      process.exit(1);
    }
  });
}

<|endoftext|>


<commit_before>/**
 * Render theme stylescheets
 *
 * usage: {{{render-stylesheet-tags}}}
 *
 */

module.exports = function(we, view) {
  return function renderStylesheetTags() {
    var tags = '';
    var themeName = this.theme;

    if (we.env == 'prod') {
      if (this.isAdmin) {
        tags = tags + view.themeStylesheetTag( '/public/min/admin.production.css' );
      } else {
        tags = tags + view.themeStylesheetTag( '/public/min/production.css' );
      }

    } else {
      var files = [];

      if (!we.config.disableCoreCssApp)
        files.push('/public/plugin/we-core/files/css/app.css');

      if (this.isAdmin) {
        files.push(
          '/public/theme/'+ view.themes[themeName].name +'/'+ view.themes[themeName].configs.stylesheet
          .replace('files/public', '')
        )
      } else {
        files.push(
          '/public/theme/'+ view.themes[themeName].name + view.themes[themeName].configs.stylesheet
          .replace('files/public', '')
        )
      }

      for (var i = 0; i < files.length; i++) {
        tags = tags + view.themeStylesheetTag(files[i]);
      }
    }

    return tags;
  }
}<commit_msg>disable prod assets build<commit_after>/**
 * Render theme stylescheets
 *
 * usage: {{{render-stylesheet-tags}}}
 *
 */

module.exports = function(we, view) {
  return function renderStylesheetTags() {
    var tags = '';
    var themeName = this.theme;

    // if (we.env == 'prod') {
    //   if (this.isAdmin) {
    //     tags = tags + view.themeStylesheetTag( '/public/min/admin.production.css' );
    //   } else {
    //     tags = tags + view.themeStylesheetTag( '/public/min/production.css' );
    //   }

    // } else {
      var files = [];

      if (!we.config.disableCoreCssApp)
        files.push('/public/plugin/we-core/files/css/app.css');

      if (this.isAdmin) {
        files.push(
          '/public/theme/'+ view.themes[themeName].name +'/'+ view.themes[themeName].configs.stylesheet
          .replace('files/public', '')
        )
      } else {
        files.push(
          '/public/theme/'+ view.themes[themeName].name + view.themes[themeName].configs.stylesheet
          .replace('files/public', '')
        )
      }

      for (var i = 0; i < files.length; i++) {
        tags = tags + view.themeStylesheetTag(files[i]);
      }
    // }

    return tags;
  }
}<|endoftext|>