<commit_before>// @flow
/* eslint-disable no-use-before-define, no-underscore-dangle */
import React from 'react'
import Editable from 'src/editor/components/Editable'
import Controls from 'src/editor/components/Controls'
import createStore from './store'
import { isProduction } from './const'
import { connectToRaven } from './raven'
import * as plugins from './plugins'
import PluginService from 'src/editor/service/plugin'
import ServerContext from 'src/editor/components/ServerContext'
import ReactDOMServer from 'react-dom/server'
import { createInitialState } from 'src/editor/plugins/content/slate/hooks'
import uuid from 'node-uuid'

import type Store from 'types/redux'

if (!isProduction && typeof window !== 'undefined') {
  window.Perf = require('react-addons-perf')
}
let instance: Editor
const initialState = {
  editables: {
    past: [],
    present: [],
    future: []
  }
}

/**
 * Editor is the core interface for dealing with the editor.
 */
class Editor {
  store: Store
  plugins: PluginService
  middleware: []
  errorReporting: bool

  constructor({
    plugins = new PluginService(),
    errorReporting = true,
    middleware = []
  }: {
    plugins: PluginService,
    errorReporting: boolean,
    middleware: []
  } = {}) {
    if (instance) {
      throw new Error('Only one instance of Editor is allowed')
    }

    instance = this
    this.store = createStore(initialState, middleware)
    this.plugins = plugins
    this.errorReporting = errorReporting
    this.middleware = middleware

    connectToRaven(errorReporting)
  }

  renderToHtml = (state: any) => ReactDOMServer.renderToStaticMarkup(
    <ServerContext>
      <Editable editor={{
        plugins: this.plugins,
        store: createStore(initialState, this.middleware)
      }} state={state}
      />
    </ServerContext>
  )
}

console.log(plugins)

export {
  PluginService,
  Editable,
  Controls,
  plugins
}

export const createEmptyState = () => ({
  id: uuid.v4(),
  cells: [{
    content: {
      plugin: { name: 'ory/editor/core/content/slate' },
      state: {
        serialized: createInitialState()
      }
    }
  }]
})

export default Editor
<commit_msg>core: remove stray console.log<commit_after>// @flow
/* eslint-disable no-use-before-define, no-underscore-dangle */
import React from 'react'
import Editable from 'src/editor/components/Editable'
import Controls from 'src/editor/components/Controls'
import createStore from './store'
import { isProduction } from './const'
import { connectToRaven } from './raven'
import * as plugins from './plugins'
import PluginService from 'src/editor/service/plugin'
import ServerContext from 'src/editor/components/ServerContext'
import ReactDOMServer from 'react-dom/server'
import { createInitialState } from 'src/editor/plugins/content/slate/hooks'
import uuid from 'node-uuid'

import type Store from 'types/redux'

if (!isProduction && typeof window !== 'undefined') {
  window.Perf = require('react-addons-perf')
}
let instance: Editor
const initialState = {
  editables: {
    past: [],
    present: [],
    future: []
  }
}

/**
 * Editor is the core interface for dealing with the editor.
 */
class Editor {
  store: Store
  plugins: PluginService
  middleware: []
  errorReporting: bool

  constructor({
    plugins = new PluginService(),
    errorReporting = true,
    middleware = []
  }: {
    plugins: PluginService,
    errorReporting: boolean,
    middleware: []
  } = {}) {
    if (instance) {
      throw new Error('Only one instance of Editor is allowed')
    }

    instance = this
    this.store = createStore(initialState, middleware)
    this.plugins = plugins
    this.errorReporting = errorReporting
    this.middleware = middleware

    connectToRaven(errorReporting)
  }

  renderToHtml = (state: any) => ReactDOMServer.renderToStaticMarkup(
    <ServerContext>
      <Editable editor={{
        plugins: this.plugins,
        store: createStore(initialState, this.middleware)
      }} state={state}
      />
    </ServerContext>
  )
}

export {
  PluginService,
  Editable,
  Controls,
  plugins
}

export const createEmptyState = () => ({
  id: uuid.v4(),
  cells: [{
    content: {
      plugin: { name: 'ory/editor/core/content/slate' },
      state: {
        serialized: createInitialState()
      }
    }
  }]
})

export default Editor
<|endoftext|>


<commit_before>

import SimpleMDE from 'simplemde';

import {addSentenceMode} from './sentence';
import {addReplaceMode} from './replace';
import {addHardWordMode} from './hardWords';

export const setup = () => {
  var simplemde = new SimpleMDE({
  	autofocus: true,
  	autosave: {
  		enabled: false,
  		uniqueId: "MyUniqueID",
  		delay: 1000,
  	},
  	blockStyles: {
  		bold: "__",
  		italic: "_"
  	},
  	element: document.getElementById("main_editor"),
  	forceSync: true,
  	hideIcons: ["fullscreen","table","code","side-by-side"],
  	indentWithTabs: false,
  	initialValue: "",
  	insertTexts: {
  		horizontalRule: ["", "\n\n-----\n\n"],
  		image: ["![](http://", ")"],
  		link: ["[", "](http://)"],
  		table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text     | Text      | Text     |\n\n"],
  	},
  	lineWrapping: true,
  	parsingConfig: {
  		allowAtxHeaderWithoutSpace: true,
  		strikethrough: false,
  		underscoresBreakWords: true,
  	},
  	placeholder: "",

  	promptURLs: true,
  	renderingConfig: {
  		singleLineBreaks: false,
  		codeSyntaxHighlighting: false,
  	},
  	shortcuts: {
  		drawTable: "Cmd-Alt-T"
  	},
  	showIcons: ["code", "table"],
  	spellChecker: true,
  	status: ["words"],
  	styleSelectedText: false,
  	tabSize: 4,
    //toolbar: false,
  	toolbarTips: true
  });
  addSentenceMode(simplemde);
  addReplaceMode(simplemde);
  addHardWordMode(simplemde);

  simplemde.codemirror.on("update", function() {
    setupReplaceHandler();
    setupReadabilityHandler();
  });

  return simplemde;
};
<commit_msg>Use language files from previous commit Added XHR hook to redirect urls for US language -> AU language<commit_after>

import SimpleMDE from 'simplemde';

import {addSentenceMode} from './sentence';
import {addReplaceMode} from './replace';
import {addHardWordMode} from './hardWords';

export const setup = () => {
  captureLanguageXHR();
  var simplemde = new SimpleMDE({
  	autofocus: true,
  	autosave: {
  		enabled: false,
  		uniqueId: "MyUniqueID",
  		delay: 1000,
  	},
  	blockStyles: {
  		bold: "__",
  		italic: "_"
  	},
  	element: document.getElementById("main_editor"),
  	forceSync: true,
  	hideIcons: ["fullscreen","table","code","side-by-side"],
  	indentWithTabs: false,
  	initialValue: "",
  	insertTexts: {
  		horizontalRule: ["", "\n\n-----\n\n"],
  		image: ["![](http://", ")"],
  		link: ["[", "](http://)"],
  		table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text     | Text      | Text     |\n\n"],
  	},
  	lineWrapping: true,
  	parsingConfig: {
  		allowAtxHeaderWithoutSpace: true,
  		strikethrough: false,
  		underscoresBreakWords: true,
  	},
  	placeholder: "",

  	promptURLs: true,
  	renderingConfig: {
  		singleLineBreaks: false,
  		codeSyntaxHighlighting: false,
  	},
  	shortcuts: {
  		drawTable: "Cmd-Alt-T"
  	},
  	showIcons: ["code", "table"],
  	spellChecker: true,
  	status: ["words"],
  	styleSelectedText: false,
  	tabSize: 4,
    //toolbar: false,
  	toolbarTips: true
  });
  addSentenceMode(simplemde);
  addReplaceMode(simplemde);
  addHardWordMode(simplemde);

  simplemde.codemirror.on("update", function() {
    setupReplaceHandler();
    setupReadabilityHandler();
  });

  return simplemde;
};

function captureLanguageXHR(){
  (function(open) {

    XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {

        console.log(url);
        if(url == 'https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.aff'){
          url = 'https://gitcdn.xyz/cdn/colugo/jameson/master/lang/en_AU.aff';
        }
        if(url == 'https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.dic'){
          url = 'https://gitcdn.xyz/cdn/colugo/jameson/master/lang/en_AU.dic';
        }
        open.call(this, method, url, async, user, pass);
    };

  })(XMLHttpRequest.prototype.open);
}
<|endoftext|>


<commit_before>// template storage

var TemplateStorage = {
    set: function (data, callback) {
        chrome.storage.local.set(data, callback);
    },
    get: function (k, callback) {
        chrome.storage.local.get(k, callback);
    },
    remove: function (k, callback) {
        chrome.storage.local.remove(k, callback);
    },
    clear: function (callback) {
        chrome.storage.local.clear(callback);
    }
};

// Settings
var _localStorageSettings = {
    get: function (key, def, callback) {
        if (key in window.localStorage && window.localStorage[key] !== '') {
            return callback(JSON.parse(window.localStorage[key]));
        } else {
            if (!def) { // return the default in the Settings
                return callback(Settings.defaults[key]);
            } else {
                // return the supplied default
                return callback(def);
            }
        }
    },
    set: function (key, value, callback) {
        if (_.isEqual(value, Settings.defaults[key])) {
            return callback(this.clear(key));
        } else {
            window.localStorage[key] = JSON.stringify(value);
            return callback(window.localStorage[key]);
        }
    },
    clear: function (key) {
        return delete window.localStorage[key];
    }
};

var _chromeStorageSettings = {
    get: function (key, def, callback) {
        chrome.storage.sync.get(key, function (data) {
            if (chrome.runtime.lastError || _.isEmpty(data)) {
                if (!def) {
                    return callback(Settings.defaults[key]);
                } else {
                    return callback(def);
                }
            } else {
                return callback(data[key]);
            }
        });
    },
    set: function (key, value, callback) {
        var data = {};
        data[key] = value;

        chrome.storage.sync.set(data, function () {
            chrome.storage.sync.get(key, function (data) {
                return callback(data);
            });
        });
    }
};

var Settings = {
    get: function (key, def, callback) {
        if (chrome && chrome.storage) {
            return _chromeStorageSettings.get(key, def, callback);
        } else {
            return _localStorageSettings.get(key, def, callback);
        }
    },
    set: function (key, value, callback) {
        if (chrome && chrome.storage) {
            return _chromeStorageSettings.set(key, value, callback);
        } else {
            return _localStorageSettings.set(key, value, callback);
        }
    },
    defaults: {
        baseURL: "https://gorgias.io/",
        //apiBaseURL: "https://gorgias.io/api/1/",
        apiBaseURL: "http://localhost:5000/api/1/",

        settings: { // settings for the settings view

            dialog: {
                enabled: true,
                shortcut: 'ctrl+space', // shortcut that triggers the complete dialog
                auto: false, //trigger automatically while typing - should be disabled cause it's annoying sometimes
                delay: 1000, // if we want to trigger it automatically
                limit: 5 // how many templates are shown in the dialog
            },
            qaBtn: {
                enabled: true
            },
            keyboard: {
                enabled: true,
                shortcut: 'tab'
            },
            stats: {
                enabled: true  // send anonymous statistics
            },
            blacklist: [],
            fields: {
                subject: false,
                tags: false
            },
            editor: {
                enabled: false // disable by default for new users - numerous complaints
            },
            migration_head: 0,
            sidebar: { // this sidebar to the right
                enabled: true,
                url: ""
            },
            suggestions: { // automatic suggestions from the server
                enabled: true
            }
        },
        // refactor this into 'local' and 'remote'
        isLoggedIn: false,
        syncEnabled: false,
        words: 0,
        syncedWords: 0,
        lastStatsSync: null,
        lastSync: null,
        shownInstallHint: false
    }
};
<commit_msg>Fixed api url<commit_after>// template storage

var TemplateStorage = {
    set: function (data, callback) {
        chrome.storage.local.set(data, callback);
    },
    get: function (k, callback) {
        chrome.storage.local.get(k, callback);
    },
    remove: function (k, callback) {
        chrome.storage.local.remove(k, callback);
    },
    clear: function (callback) {
        chrome.storage.local.clear(callback);
    }
};

// Settings
var _localStorageSettings = {
    get: function (key, def, callback) {
        if (key in window.localStorage && window.localStorage[key] !== '') {
            return callback(JSON.parse(window.localStorage[key]));
        } else {
            if (!def) { // return the default in the Settings
                return callback(Settings.defaults[key]);
            } else {
                // return the supplied default
                return callback(def);
            }
        }
    },
    set: function (key, value, callback) {
        if (_.isEqual(value, Settings.defaults[key])) {
            return callback(this.clear(key));
        } else {
            window.localStorage[key] = JSON.stringify(value);
            return callback(window.localStorage[key]);
        }
    },
    clear: function (key) {
        return delete window.localStorage[key];
    }
};

var _chromeStorageSettings = {
    get: function (key, def, callback) {
        chrome.storage.sync.get(key, function (data) {
            if (chrome.runtime.lastError || _.isEmpty(data)) {
                if (!def) {
                    return callback(Settings.defaults[key]);
                } else {
                    return callback(def);
                }
            } else {
                return callback(data[key]);
            }
        });
    },
    set: function (key, value, callback) {
        var data = {};
        data[key] = value;

        chrome.storage.sync.set(data, function () {
            chrome.storage.sync.get(key, function (data) {
                return callback(data);
            });
        });
    }
};

var Settings = {
    get: function (key, def, callback) {
        if (chrome && chrome.storage) {
            return _chromeStorageSettings.get(key, def, callback);
        } else {
            return _localStorageSettings.get(key, def, callback);
        }
    },
    set: function (key, value, callback) {
        if (chrome && chrome.storage) {
            return _chromeStorageSettings.set(key, value, callback);
        } else {
            return _localStorageSettings.set(key, value, callback);
        }
    },
    defaults: {
        baseURL: "https://gorgias.io/",
        apiBaseURL: "https://gorgias.io/api/1/",
        //apiBaseURL: "http://localhost:5000/api/1/",

        settings: { // settings for the settings view

            dialog: {
                enabled: true,
                shortcut: 'ctrl+space', // shortcut that triggers the complete dialog
                auto: false, //trigger automatically while typing - should be disabled cause it's annoying sometimes
                delay: 1000, // if we want to trigger it automatically
                limit: 5 // how many templates are shown in the dialog
            },
            qaBtn: {
                enabled: true
            },
            keyboard: {
                enabled: true,
                shortcut: 'tab'
            },
            stats: {
                enabled: true  // send anonymous statistics
            },
            blacklist: [],
            fields: {
                subject: false,
                tags: false
            },
            editor: {
                enabled: false // disable by default for new users - numerous complaints
            },
            migration_head: 0,
            sidebar: { // this sidebar to the right
                enabled: true,
                url: ""
            },
            suggestions: { // automatic suggestions from the server
                enabled: true
            }
        },
        // refactor this into 'local' and 'remote'
        isLoggedIn: false,
        syncEnabled: false,
        words: 0,
        syncedWords: 0,
        lastStatsSync: null,
        lastSync: null,
        shownInstallHint: false
    }
};
<|endoftext|>


<commit_before>/*
 * cem.shell.js
 * Shell for Cemetery Project CMP343
*/

cem.shell = (function () {
  'use strict';
  //---------------- BEGIN MODULE SCOPE VARIABLES --------------
  var
    configMap = {
      anchor_schema_map : {
        chat  : { opened : true, closed : true }
      },
      resize_interval : 200,
      main_html : String()
        + '
'
          + '
'
            + '
CEM/SPA
'
            + '
The past is a gift to the future . .
'
          + '
'
          + '

'
        + '
'
        + '
'
	  // Display main menu; this needs to be done with code
          + '
'
	  + '
Temporary Menu:
'
	  + 'Geolocation Point Data'
	  + '
'
          +  'Cemetery Data Input
'
	  +  '
'
	  +  'Marker Details
'
	  + '
'
	  +  ' PWI Plugin
'
	  +  '
'
	  +  'Show PWI Data
'
          + '
'
          +  'Clear All

'
          + '

'
	  + '

'
	  + '

'
	  + '

'
        + '
'
        + '

'
        + '

'
    },
    stateMap = {
      $container  : undefined,
      anchor_map  : {},
      resize_idto : undefined
    },
    jqueryMap = {},

    copyAnchorMap,    setJqueryMap,   changeAnchorPart,
    onResize,         onHashchange,   onTapList,
    onTapAcct,        onLogin,        onLogout,
    setChatAnchor,    initModule,     $activeDiv,
    $divToHide,	      cemValid,	      geoValid,
    markerValid,      pwiValid,	      routes,
    router, 	      geopoint,
    swapDivs;
  //----------------- END MODULE SCOPE VARIABLES ---------------

  //------------------- BEGIN UTILITY METHODS ------------------
  // Returns copy of stored anchor map; minimizes overhead
  copyAnchorMap = function () {
    return $.extend( true, {}, stateMap.anchor_map );
  };
  //-------------------- END UTILITY METHODS -------------------

  //--------------------- BEGIN DOM METHODS --------------------
  // Begin DOM method /setJqueryMap/
  setJqueryMap = function () {
    var $container = stateMap.$container;

    // I added several valures here for divs I need to manipulate
    jqueryMap = {
      $container : $container,
      $acct      : $container.find('.cem-shell-head-acct'),
      $nav       : $container.find('.cem-shell-main-nav'),
      $cem	 : $container.find('.cem-shell-cem-content'),
      $pwi	 : $container.find('.cem-shell-plugin-content'),
      $geo	 : $container.find('.cem-shell-geo-content'),
      $marker	 : $container.find('.cem-shell-marker-content'),
      $menu	 : $container.find('.cem-shell-list-menu'),
      $footer 	 : $container.find('.cem-shell-foot')
    };
  };
  // End DOM method /setJqueryMap/

  // swapDivs: convenience function when switching screens
  swapDivs = function($newDiv) {
          if ( $activeDiv == $newDiv ) return;
          $divToHide = $activeDiv;
          $activeDiv = $newDiv;
          if (typeof($divToHide) != 'undefined') $divToHide.hide();
          $newDiv.show();
          return;
          }
  // route stuff
  geopoint = function() {
	  console.log('In geopoint');
          swapDivs(jqueryMap.$geo);
          if ( geoValid == false || pwiValid == true ) {
            geoValid = true;
            jqueryMap.$geo.empty();
            jqueryMap.$geo.append(geo_form(pwi.returnDataMap,'Marker'));
            }
	}

  routes = {
	'geopoint': geopoint };

  //--------------------- END DOM METHODS ----------------------

  //------------------- BEGIN EVENT HANDLERS -------------------

  // Begin Event handler /onResize/
  onResize = function () {
    if ( stateMap.resize_idto ) { return true; }

    stateMap.resize_idto = setTimeout(
      function () { stateMap.resize_idto = undefined; },
      configMap.resize_interval
    );

    return true;
  };
  // End Event handler /onResize/

  onTapAcct = function ( event ) {
      // React to mouse click w/temporary message
      jqueryMap.$acct.text( '... coming soon ...' );
      setTimeout(function(){
  	jqueryMap.$acct.text( 'Click to sign in' );
      },3000);
      return false;
  };

  // Event handler /onTapList/
  onTapList = function ( event ) {
    // React to taps on menu in nav div
    var menu_item  = $(this).data("id");
    // console.log('Tapped on ' + menu_item);
    switch(menu_item) {

	case 'cemetery':
	  document.location.hash="";
	  swapDivs(jqueryMap.$cem);
          if (  cemValid  == false ) {
            cemValid = true;
	    jqueryMap.$cem.append(cem_form());
	    }
	  break;

	case 'geopoint':
	  swapDivs(jqueryMap.$geo);
          if ( geoValid == false || pwiValid == true ) {
            geoValid = true;
	    jqueryMap.$geo.empty();
            jqueryMap.$geo.append(geo_form(pwi.returnDataMap,'Marker'));
            }
	  break;

	case 'marker':
	  document.location.hash="";
	  swapDivs(jqueryMap.$marker);
          if ( ! markerValid ) {
            markerValid = true;
            jqueryMap.$marker.append(marker_form());
            }
          break;

	case 'pwi':
	  document.location.hash="";
	  swapDivs(jqueryMap.$pwi);
          if ( ! pwiValid ) {
            pwiValid = true;
            jqueryMap.$geo.append(pwi_form());
            }
          break;

	case 'pwi-get':
	  jqueryMap.$footer.empty();
	  jqueryMap.$footer.append(JSON.stringify(pwi.returnDataMap));
	  // console.log(JSON.stringify(pwi.returnDataMap));
	  break;
	case 'clear':
	  document.location.hash="";
	  // Set everything back to starting state . .
	  cemValid = geoValid = markerValid = pwiValid = false;
	  jqueryMap.$footer.empty();
	  jqueryMap.$cem.empty();
	  jqueryMap.$geo.empty();
	  jqueryMap.$pwi.empty();
	  jqueryMap.$marker.empty();
	  $activeDiv.hide();
	  // Unset any lingering coordinates, too
	  if ( typeof(returnDataMap) == 'object')
	    delete pwi.returnDataMap['coordinates'];
	  break;
	}
    return false;
    };

  //-------------------- END EVENT HANDLERS --------------------

  //------------------- BEGIN PUBLIC METHODS -------------------
  // Begin Public method /initModule/
  // Example   : cem.shell.initModule( $('#app_div_id') );
  // Purpose   :
  //   Directs the Shell to offer its capability to the user
  // Arguments :
  //   * $container (example: $('#app_div_id')).
  //     A jQuery collection that should represent
  //     a single DOM container
  // Action    :
  //   Populates $container with the shell of the UI
  //   and then configures and initializes feature modules.
  //   The Shell is also responsible for browser-wide issues
  //   such as URI anchor and cookie management
  // Returns   : none
  // Throws    : none
  initModule = function ( $container ) {
    // load HTML and map jQuery collections
    stateMap.$container = $container;
    $container.html( configMap.main_html );
    setJqueryMap();
    jqueryMap.$cem.hide();
    jqueryMap.$geo.hide();
    jqueryMap.$marker.hide();
    jqueryMap.$pwi.hide();
    cemValid = geoValid = markerValid = pwiValid = false;

    // Can we do the routing this easily?
    router = Router(routes);
    router.init();
    // $.gevent.subscribe( $container, 'spa-login',  onLogin  );
    // $.gevent.subscribe( $container, 'spa-logout', onLogout );

    // Set up for user login
    jqueryMap.$acct
      .text( 'Click to sign in')
      .bind( 'click', onTapAcct );

    jqueryMap.$menu.bind( 'click', onTapList   );
    // configure and initialize feature modules
    // This is where the action will soon be
    // spa.input.initModule( jqueryMap.$container );

  // End PUBLIC method /initModule/
  };
  return { initModule : initModule };

  //------------------- END PUBLIC METHODS ---------------------
}());
<commit_msg>Fix bug on same div after clear<commit_after>/*
 * cem.shell.js
 * Shell for Cemetery Project CMP343
*/

cem.shell = (function () {
  'use strict';
  //---------------- BEGIN MODULE SCOPE VARIABLES --------------
  var
    configMap = {
      anchor_schema_map : {
        chat  : { opened : true, closed : true }
      },
      resize_interval : 200,
      main_html : String()
        + '
'
          + '
'
            + '
CEM/SPA
'
            + '
The past is a gift to the future . .
'
          + '
'
          + '

'
        + '
'
        + '
'
	  // Display main menu; this needs to be done with code
          + '
'
	  + '
Temporary Menu:
'
	  + 'Geolocation Point Data'
	  + '
'
          +  'Cemetery Data Input
'
	  +  '
'
	  +  'Marker Details
'
	  + '
'
	  +  ' PWI Plugin
'
	  +  '
'
	  +  'Show PWI Data
'
          + '
'
          +  'Clear All

'
          + '

'
	  + '

'
	  + '

'
	  + '

'
        + '
'
        + '

'
        + '

'
    },
    stateMap = {
      $container  : undefined,
      anchor_map  : {},
      resize_idto : undefined
    },
    jqueryMap = {},

    copyAnchorMap,    setJqueryMap,   changeAnchorPart,
    onResize,         onHashchange,   onTapList,
    onTapAcct,        onLogin,        onLogout,
    setChatAnchor,    initModule,     $activeDiv,
    $divToHide,	      cemValid,	      geoValid,
    markerValid,      pwiValid,	      routes,
    router, 	      geopoint,
    swapDivs;
  //----------------- END MODULE SCOPE VARIABLES ---------------

  //------------------- BEGIN UTILITY METHODS ------------------
  // Returns copy of stored anchor map; minimizes overhead
  copyAnchorMap = function () {
    return $.extend( true, {}, stateMap.anchor_map );
  };
  //-------------------- END UTILITY METHODS -------------------

  //--------------------- BEGIN DOM METHODS --------------------
  // Begin DOM method /setJqueryMap/
  setJqueryMap = function () {
    var $container = stateMap.$container;

    // I added several valures here for divs I need to manipulate
    jqueryMap = {
      $container : $container,
      $acct      : $container.find('.cem-shell-head-acct'),
      $nav       : $container.find('.cem-shell-main-nav'),
      $cem	 : $container.find('.cem-shell-cem-content'),
      $pwi	 : $container.find('.cem-shell-plugin-content'),
      $geo	 : $container.find('.cem-shell-geo-content'),
      $marker	 : $container.find('.cem-shell-marker-content'),
      $menu	 : $container.find('.cem-shell-list-menu'),
      $footer 	 : $container.find('.cem-shell-foot')
    };
  };
  // End DOM method /setJqueryMap/

  // swapDivs: convenience function when switching screens
  swapDivs = function($newDiv) {
	  // Old is same as new
          if ( $activeDiv == $newDiv ) {
	    $newDiv.show();
            return
	    };

	  // Swap new one in
	  $divToHide = $activeDiv;
          $activeDiv = $newDiv;
          if (typeof($divToHide) != 'undefined') $divToHide.hide();
          $newDiv.show();
          return;
          }
  // route stuff
  geopoint = function() {
	  console.log('In geopoint');
          swapDivs(jqueryMap.$geo);
          if ( geoValid == false || pwiValid == true ) {
            geoValid = true;
            jqueryMap.$geo.empty();
            jqueryMap.$geo.append(geo_form(pwi.returnDataMap,'Marker'));
            }
	}

  routes = {
	'geopoint': geopoint };

  //--------------------- END DOM METHODS ----------------------

  //------------------- BEGIN EVENT HANDLERS -------------------

  // Begin Event handler /onResize/
  onResize = function () {
    if ( stateMap.resize_idto ) { return true; }

    stateMap.resize_idto = setTimeout(
      function () { stateMap.resize_idto = undefined; },
      configMap.resize_interval
    );

    return true;
  };
  // End Event handler /onResize/

  onTapAcct = function ( event ) {
      // React to mouse click w/temporary message
      jqueryMap.$acct.text( '... coming soon ...' );
      setTimeout(function(){
  	jqueryMap.$acct.text( 'Click to sign in' );
      },3000);
      return false;
  };

  // Event handler /onTapList/
  onTapList = function ( event ) {
    // React to taps on menu in nav div
    var menu_item  = $(this).data("id");
    // console.log('Tapped on ' + menu_item);
    switch(menu_item) {

	case 'cemetery':
	  document.location.hash="";
	  swapDivs(jqueryMap.$cem);
          if (  cemValid  == false ) {
            cemValid = true;
	    jqueryMap.$cem.append(cem_form());
	    }
	  break;

	case 'geopoint':
	  swapDivs(jqueryMap.$geo);
          if ( geoValid == false || pwiValid == true ) {
            geoValid = true;
	    jqueryMap.$geo.empty();
            jqueryMap.$geo.append(geo_form(pwi.returnDataMap,'Marker'));
            }
	  break;

	case 'marker':
	  document.location.hash="";
	  swapDivs(jqueryMap.$marker);
          if ( ! markerValid ) {
            markerValid = true;
            jqueryMap.$marker.append(marker_form());
            }
          break;

	case 'pwi':
	  document.location.hash="";
	  swapDivs(jqueryMap.$pwi);
          if ( ! pwiValid ) {
            pwiValid = true;
            jqueryMap.$geo.append(pwi_form());
            }
          break;

	case 'pwi-get':
	  jqueryMap.$footer.empty();
	  jqueryMap.$footer.append(JSON.stringify(pwi.returnDataMap));
	  // console.log(JSON.stringify(pwi.returnDataMap));
	  break;
	case 'clear':
	  // Set everything back to starting state . .
	  cemValid = geoValid = markerValid = pwiValid = false;
	  jqueryMap.$footer.empty();
	  jqueryMap.$cem.empty();
	  jqueryMap.$geo.empty();
	  jqueryMap.$pwi.empty();
	  jqueryMap.$marker.empty();
	  $activeDiv.hide();
	  // if (typeof($activeDiv) != 'undefined') delete self.$activeDiv;
	  // Unset any lingering coordinates, too
	  if ( typeof(returnDataMap) == 'object')
	    delete pwi.returnDataMap['coordinates'];
	  document.location.hash="";
	  break;
	}
    return false;
    };

  //-------------------- END EVENT HANDLERS --------------------

  //------------------- BEGIN PUBLIC METHODS -------------------
  // Begin Public method /initModule/
  // Example   : cem.shell.initModule( $('#app_div_id') );
  // Purpose   :
  //   Directs the Shell to offer its capability to the user
  // Arguments :
  //   * $container (example: $('#app_div_id')).
  //     A jQuery collection that should represent
  //     a single DOM container
  // Action    :
  //   Populates $container with the shell of the UI
  //   and then configures and initializes feature modules.
  //   The Shell is also responsible for browser-wide issues
  //   such as URI anchor and cookie management
  // Returns   : none
  // Throws    : none
  initModule = function ( $container ) {
    // load HTML and map jQuery collections
    stateMap.$container = $container;
    $container.html( configMap.main_html );
    setJqueryMap();
    jqueryMap.$cem.hide();
    jqueryMap.$geo.hide();
    jqueryMap.$marker.hide();
    jqueryMap.$pwi.hide();
    cemValid = geoValid = markerValid = pwiValid = false;

    // Can we do the routing this easily?
    router = Router(routes);
    router.init();
    // $.gevent.subscribe( $container, 'spa-login',  onLogin  );
    // $.gevent.subscribe( $container, 'spa-logout', onLogout );

    // Set up for user login
    jqueryMap.$acct
      .text( 'Click to sign in')
      .bind( 'click', onTapAcct );

    jqueryMap.$menu.bind( 'click', onTapList   );
    // configure and initialize feature modules
    // This is where the action will soon be
    // spa.input.initModule( jqueryMap.$container );

  // End PUBLIC method /initModule/
  };
  return { initModule : initModule };

  //------------------- END PUBLIC METHODS ---------------------
}());
<|endoftext|>


<commit_before>import _ from '../utils/underscore.js';
import Events from '../events.js';

/**
 * @name Two.Stop
 * @class
 * @param {Number} [offset] - The offset percentage of the stop represented as a zero-to-one value. Default value flip flops from zero-to-one as new stops are created.
 * @param {String} [color] - The color of the stop. Default value flip flops from white to black as new stops are created.
 * @param {Number} [opacity] - The opacity value. Default value is 1, cannot be lower than 0.
 * @nota-bene Used specifically in conjunction with {@link Two.Gradient}s to control color graduation.
 */
function Stop(offset, color, opacity) {

  /**
   * @name Two.Stop#renderer
   * @property {Object}
   * @description Object access to store relevant renderer specific variables. Warning: manipulating this object can create unintended consequences.
   * @nota-bene With the {@link Two.SvgRenderer} you can access the underlying SVG element created via `shape.renderer.elem`.
   */
  this.renderer = {};
  this._renderer.type = 'stop';

  /**
   * @name Two.Stop#offset
   * @property {Number} - The offset percentage of the stop represented as a zero-to-one value.
   */
  this.offset = typeof offset === 'number' ? offset
    : Stop.Index <= 0 ? 0 : 1;

  /**
   * @name Two.Stop#opacity
   * @property {Number} - The alpha percentage of the stop represented as a zero-to-one value.
   */
  this.opacity = typeof opacity === 'number' ? opacity : 1;

  /**
   * @name Two.Stop#color
   * @property {String} - The color of the stop.
   */
  this.color = (typeof color === 'string') ? color
    : Stop.Index <= 0 ? '#fff' : '#000';

  Stop.Index = (Stop.Index + 1) % 2;

}

_.extend(Stop, {

  /**
   * @name Two.Stop.Index
   * @property {Number} - The current index being referenced for calculating a stop's default offset value.
   */
  Index: 0,

  /**
   * @name Two.Stop.Properties
   * @property {String[]} - A list of properties that are on every {@link Two.Stop}.
   */
  Properties: [
    'offset',
    'opacity',
    'color'
  ],

  /**
   * @name Two.Stop.MakeObservable
   * @function
   * @param {Object} object - The object to make observable.
   * @description Convenience function to apply observable qualities of a {@link Two.Stop} to any object. Handy if you'd like to extend the {@link Two.Stop} class on a custom class.
   */
  MakeObservable: function(object) {

    _.each(Stop.Properties, function(property) {

      var object = this;
      var secret = '_' + property;
      var flag = '_flag' + property.charAt(0).toUpperCase() + property.slice(1);

      Object.defineProperty(object, property, {
        enumerable: true,
        get: function() {
          return this[secret];
        },
        set: function(v) {
          this[secret] = v;
          this[flag] = true;
          if (this.parent) {
            this.parent._flagStops = true;
          }
        }
      });

    }, object);

    Object.defineProperty(object, 'renderer', {

      enumerable: false,

      get: function() {
        return this._renderer;
      },

      set: function(obj) {
        this._renderer = obj;
      }

    });

  }

});

_.extend(Stop.prototype, Events, {

  constructor: Stop,

  /**
   * @name Two.Stop#clone
   * @function
   * @param {Two.Group} [parent] - The parent group or scene to add the clone to.
   * @returns {Two.Stop}
   * @description Create a new instance of {@link Two.Stop} with the same properties of the current path.
   */
  clone: function() {

    var clone = new Stop();

    _.each(Stop.Properties, function(property) {
      clone[property] = this[property];
    }, this);

    return clone;

  },

  /**
   * @name Two.Stop#toObject
   * @function
   * @returns {Object}
   * @description Return a JSON compatible plain object that represents the path.
   */
  toObject: function() {

    var result = {};

    _.each(Stop.Properties, function(k) {
      result[k] = this[k];
    }, this);

    return result;

  },

  /**
   * @name Two.Stop#flagReset
   * @function
   * @private
   * @description Called internally to reset all flags. Ensures that only properties that change are updated before being sent to the renderer.
   */
  flagReset: function() {

    this._flagOffset = this._flagColor = this._flagOpacity = false;

    return this;

  }

});

Stop.MakeObservable(Stop.prototype);

export default Stop;
<commit_msg>Converted Two.Stop to ES6 Class<commit_after>import { _ } from '../utils/underscore.js';
import { Events } from '../events.js';

/**
 * @name Two.Stop
 * @class
 * @param {Number} [offset] - The offset percentage of the stop represented as a zero-to-one value. Default value flip flops from zero-to-one as new stops are created.
 * @param {String} [color] - The color of the stop. Default value flip flops from white to black as new stops are created.
 * @param {Number} [opacity] - The opacity value. Default value is 1, cannot be lower than 0.
 * @nota-bene Used specifically in conjunction with {@link Two.Gradient}s to control color graduation.
 */
export class Stop extends Events {

  constructor(offset, color, opacity) {

    super();

    for (let prop in proto) {
      Object.defineProperty(this, prop, proto[prop]);
    }

    /**
     * @name Two.Stop#renderer
     * @property {Object}
     * @description Object access to store relevant renderer specific variables. Warning: manipulating this object can create unintended consequences.
     * @nota-bene With the {@link Two.SvgRenderer} you can access the underlying SVG element created via `shape.renderer.elem`.
     */
    this.renderer = {};
    this._renderer.type = 'stop';

    /**
     * @name Two.Stop#offset
     * @property {Number} - The offset percentage of the stop represented as a zero-to-one value.
     */
    this.offset = typeof offset === 'number' ? offset
      : Stop.Index <= 0 ? 0 : 1;

    /**
     * @name Two.Stop#opacity
     * @property {Number} - The alpha percentage of the stop represented as a zero-to-one value.
     */
    this.opacity = typeof opacity === 'number' ? opacity : 1;

    /**
     * @name Two.Stop#color
     * @property {String} - The color of the stop.
     */
    this.color = (typeof color === 'string') ? color
      : Stop.Index <= 0 ? '#fff' : '#000';

    Stop.Index = (Stop.Index + 1) % 2;

  }

  /**
   * @name Two.Stop.Index
   * @property {Number} - The current index being referenced for calculating a stop's default offset value.
   */
  static Index = 0;

  /**
   * @name Two.Stop.Properties
   * @property {String[]} - A list of properties that are on every {@link Two.Stop}.
   */
  static Properties = ['offset', 'opacity', 'color'];

  /**
   * @name Two.Stop#clone
   * @function
   * @param {Two.Group} [parent] - The parent group or scene to add the clone to.
   * @returns {Two.Stop}
   * @description Create a new instance of {@link Two.Stop} with the same properties of the current path.
   */
  clone() {

    const clone = new Stop();

    _.each(Stop.Properties, function(property) {
      clone[property] = this[property];
    }, this);

    return clone;

  }

  /**
   * @name Two.Stop#toObject
   * @function
   * @returns {Object}
   * @description Return a JSON compatible plain object that represents the path.
   */
  toObject() {

    const result = {};

    _.each(Stop.Properties, function(k) {
      result[k] = this[k];
    }, this);

    return result;

  }

  /**
   * @name Two.Stop#flagReset
   * @function
   * @private
   * @description Called internally to reset all flags. Ensures that only properties that change are updated before being sent to the renderer.
   */
  flagReset() {

    this._flagOffset = this._flagColor = this._flagOpacity = false;

    return this;

  }

}

const proto = {
  offset: {
    enumerable: true,
    get: function() {
      return this._offset;
    },
    set: function(v) {
      this._offset = v;
      this._flagOffset = v;
      if (this.parent) {
        this.parent._flagStops = true;
      }
    }
  },
  opacity: {
    enumerable: true,
    get: function() {
      return this._opacity;
    },
    set: function(v) {
      this._opacity = v;
      this._flagOpacity = v;
      if (this.parent) {
        this.parent._flagStops = true;
      }
    }
  },
  color: {
    enumerable: true,
    get: function() {
      return this._color;
    },
    set: function(v) {
      this._color = v;
      this._flagColor = v;
      if (this.parent) {
        this.parent._flagStops = true;
      }
    }
  },
  renderer: {
    enumerable: false,
    get: function() {
      return this._renderer;
    },
    set: function(obj) {
      this._renderer = obj;
    }
  }
};
<|endoftext|>


<commit_before>/*
	$Id: thermal_sensors.js
*/
/* ====================================================================
 *	Copyright (c)  2004-2015  Electric Sheep Fencing, LLC. All rights reserved.
 *
 *	Redistribution and use in source and binary forms, with or without modification,
 *	are permitted provided that the following conditions are met:
 *
 *	1. Redistributions of source code must retain the above copyright notice,
 *		this list of conditions and the following disclaimer.
 *
 *	2. 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.
 *
 *	3. All advertising materials mentioning features or use of this software
 *		must display the following acknowledgment:
 *		"This product includes software developed by the pfSense Project
 *		 for use in the pfSense software distribution. (http://www.pfsense.org/).
 *
 *	4. The names "pfSense" and "pfSense Project" must not be used to
 *		 endorse or promote products derived from this software without
 *		 prior written permission. For written permission, please contact
 *		 coreteam@pfsense.org.
 *
 *	5. Products derived from this software may not be called "pfSense"
 *		nor may "pfSense" appear in their names without prior written
 *		permission of the Electric Sheep Fencing, LLC.
 *
 *	6. Redistributions of any form whatsoever must retain the following
 *		acknowledgment:
 *
 *	"This product includes software developed by the pfSense Project
 *	for use in the pfSense software distribution (http://www.pfsense.org/).
 *
 *	THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
 *	EXPRESSED 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 pfSense PROJECT OR
 *	ITS 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.
 *
 *	====================================================================
 *
 */

warningTemp = 9999;
criticalTemp = 100;

//should be called from "thermal_sensors.widget.php"
function showThermalSensorsData() {

	//get data from thermal_sensors.widget.php
	url = "/widgets/widgets/thermal_sensors.widget.php?getThermalSensorsData=1"
			//IE fix to disable cache when using http:// , just append timespan
			+ new Date().getTime();

	jQuery.ajax(url, {
		type: 'get',
		success: function(data) {
			var thermalSensorsData = data || "";
			buildThermalSensorsData(thermalSensorsData);
		},
		error: function(jqXHR, status, error) {
			buildThermalSensorsDataRaw(
				"Error getting data from [thermal_sensors.widget.php] - |" +
				"status: [" + (status || "") + "]|" +
				"error: [" + (error || "") + "]");
		}
	});

	//call itself in 11 seconds
	window.setTimeout(showThermalSensorsData, 11000);
}

function buildThermalSensorsData(thermalSensorsData) {
	//NOTE: variable thermal_sensors_widget_showRawOutput is declared/set in "thermal_sensors.widget.php"
	if (thermal_sensors_widget_showRawOutput) {
		buildThermalSensorsDataRaw(thermalSensorsData);
	} else {
		if(warningTemp == 9999) {
			buildThermalSensorsDataGraph(thermalSensorsData);
		}

		updateThermalSensorsDataGraph(thermalSensorsData);
	}
}

function buildThermalSensorsDataRaw(thermalSensorsData) {

	var thermalSensorsContent = "";

	if (thermalSensorsData && thermalSensorsData != "") {
		thermalSensorsContent = thermalSensorsData.replace(/\|/g, "
");
		//rawData = thermalSensorsData.split("|").join("
");
	}

	loadThermalSensorsContainer(thermalSensorsContent);
}

function loadThermalSensorsContainer (thermalSensorsContent) {

	if (thermalSensorsContent && thermalSensorsContent != "") {
		//load generated graph (or raw data) into thermalSensorsContainer (thermalSensorsContainer DIV defined in "thermal_sensors.widget.php")
		jQuery('#thermalSensorsContainer').html(thermalSensorsContent);
	} else {
		jQuery('#thermalSensorsContainer').html("No Thermal Sensors data available.

");
		jQuery('
').html(
				"* You can configure a proper Thermal Sensor / Module under
" +
				"   System > Advanced > Miscellaneous : Thermal Sensors section."
				).appendTo('#thermalSensorsContainer');
	}
}

function buildThermalSensorsDataGraph(thermalSensorsData) {

	var thermalSensorsArray = new Array();

	if (thermalSensorsData && thermalSensorsData != "") {
		thermalSensorsArray = thermalSensorsData.split("|");
	}

	var thermalSensorsHTMLContent = "";

	//generate graph for each temperature sensor and append to thermalSensorsHTMLContent string
	for (var i = 0; i < thermalSensorsArray.length; i++) {

		var sensorDataArray = thermalSensorsArray[i].split(":");
		var sensorName = sensorDataArray[0].trim();
		var thermalSensorValue = getThermalSensorValue(sensorDataArray[1]);

		//set thresholds
		if (sensorName.indexOf("cpu") > -1) { //check CPU Threshold config settings
			warningTemp = thermal_sensors_widget_coreWarningTempThreshold;
			criticalTemp = thermal_sensors_widget_coreCriticalTempThreshold;
		} else { //assuming sensor is for a zone, check Zone Threshold config settings
			warningTemp = thermal_sensors_widget_zoneWarningTempThreshold;
			criticalTemp = thermal_sensors_widget_zoneCriticalTempThreshold;
		}

		//NOTE: variable thermal_sensors_widget_showFullSensorName is declared/set in "thermal_sensors.widget.php"
		if (!thermal_sensors_widget_showFullSensorName) {
			sensorName = getSensorFriendlyName(sensorName);
		}

		//build temperature item/row for a sensor

		var thermalSensorRow =	'
' +
									'

' +
									'

' +
									'

' +
								'
' +
								'' + sensorName + ': ' + '' + thermalSensorValue + ' °C';

		thermalSensorsHTMLContent = thermalSensorsHTMLContent + thermalSensorRow;

	}

	//load generated graph into thermalSensorsContainer (DIV defined in "thermal_sensors.widget.php")
	loadThermalSensorsContainer(thermalSensorsHTMLContent);

}

function updateThermalSensorsDataGraph(thermalSensorsData) {
	var thermalSensorsArray = new Array();

	if (thermalSensorsData && thermalSensorsData != "") {
		thermalSensorsArray = thermalSensorsData.split("|");
	}

	//generate graph for each temperature sensor and append to thermalSensorsHTMLContent string
	for (var i = 0; i < thermalSensorsArray.length; i++) {

		var sensorDataArray = thermalSensorsArray[i].split(":");
		var sensorName = sensorDataArray[0].trim();
		var thermalSensorValue = getThermalSensorValue(sensorDataArray[1]);

		//set thresholds
		if (sensorName.indexOf("cpu") > -1) { //check CPU Threshold config settings
			warningTemp = thermal_sensors_widget_coreWarningTempThreshold;
			criticalTemp = thermal_sensors_widget_coreCriticalTempThreshold;
		} else { //assuming sensor is for a zone, check Zone Threshold config settings
			warningTemp = thermal_sensors_widget_zoneWarningTempThreshold;
			criticalTemp = thermal_sensors_widget_zoneCriticalTempThreshold;
		}

		//NOTE: variable thermal_sensors_widget_showFullSensorName is declared/set in "thermal_sensors.widget.php"
		if (!thermal_sensors_widget_showFullSensorName) {
			sensorName = getSensorFriendlyName(sensorName);
		}

	setTempProgress(i, thermalSensorValue);
	}
}

function getSensorFriendlyName(sensorFullName) {
	var rzone = /^hw\.acpi\.thermal\.tz([0-9]+)\.temperature$/;
	var rcore = /^dev\.cpu\.([0-9]+)\.temperature$/;

	if (rzone.test(sensorFullName)) {
		return "Zone " + rzone.exec(sensorFullName)[1];
	}

	if (rcore.test(sensorFullName)) {
		return "Core " + rcore.exec(sensorFullName)[1];
	}

	return sensorFullName;
}

function getThermalSensorValue(stringValue) {
	return (+parseFloat(stringValue) || 0).toFixed(1);
}

// Update the progress indicator
// transition = true allows the bar to move at default speed, false = instantaneous
function setTempProgress(bar, percent) {
	var barTempL, barTempM, barTempH;

	if(percent <= warningTemp) {
		barTempL = percent;
		barTempM = 0;
		barTempH = 0;
	} else if(percent <= criticalTemp) {
		barTempL = warningTemp;
		barTempM = percent - warningTemp;
		barTempH = 0;
	} else {
		barTempL = warningTemp;
		barTempM = criticalTemp - warningTemp;
		barTempH = percent - criticalTemp;
	}

	$('#' + 'temperaturebarL' + bar).css('width', barTempL + '%').attr('aria-valuenow', barTempL);
	$('#' + 'temperaturebarM' + bar).css('width', barTempM + '%').attr('aria-valuenow', barTempM);
	$('#' + 'temperaturebarH' + bar).css('width', barTempH + '%').attr('aria-valuenow', barTempH);

	$('#' + 'temperaturemsg' + bar).html(percent + ' °C');
}<commit_msg>Added automatic error recovery and ajax busy flag<commit_after>/*
	$Id: thermal_sensors.js
*/
/* ====================================================================
 *	Copyright (c)  2004-2015  Electric Sheep Fencing, LLC. All rights reserved.
 *
 *	Redistribution and use in source and binary forms, with or without modification,
 *	are permitted provided that the following conditions are met:
 *
 *	1. Redistributions of source code must retain the above copyright notice,
 *		this list of conditions and the following disclaimer.
 *
 *	2. 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.
 *
 *	3. All advertising materials mentioning features or use of this software
 *		must display the following acknowledgment:
 *		"This product includes software developed by the pfSense Project
 *		 for use in the pfSense software distribution. (http://www.pfsense.org/).
 *
 *	4. The names "pfSense" and "pfSense Project" must not be used to
 *		 endorse or promote products derived from this software without
 *		 prior written permission. For written permission, please contact
 *		 coreteam@pfsense.org.
 *
 *	5. Products derived from this software may not be called "pfSense"
 *		nor may "pfSense" appear in their names without prior written
 *		permission of the Electric Sheep Fencing, LLC.
 *
 *	6. Redistributions of any form whatsoever must retain the following
 *		acknowledgment:
 *
 *	"This product includes software developed by the pfSense Project
 *	for use in the pfSense software distribution (http://www.pfsense.org/).
 *
 *	THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
 *	EXPRESSED 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 pfSense PROJECT OR
 *	ITS 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.
 *
 *	====================================================================
 *
 */

warningTemp = 9999;
criticalTemp = 100;
ajaxBusy = false;

//should be called from "thermal_sensors.widget.php"
function showThermalSensorsData() {
	if(!ajaxBusy) {
		ajaxBusy = true;
		//get data from thermal_sensors.widget.php
		url = "/widgets/widgets/thermal_sensors.widget.php?getThermalSensorsData=1"
				//IE fix to disable cache when using http:// , just append timespan
				+ new Date().getTime();

		jQuery.ajax(url, {
			type: 'get',
			success: function(data) {
				var thermalSensorsData = data || "";
				buildThermalSensorsData(thermalSensorsData);
			},
			error: function(jqXHR, status, error) {
				warningTemp = 9999;
				buildThermalSensorsDataRaw('Temperature data could not be read.');
			}
		});

		ajaxBusy = false;
	}
	//call itself in 11 seconds
	window.setTimeout(showThermalSensorsData, 11000);
}

function buildThermalSensorsData(thermalSensorsData) {
	//NOTE: variable thermal_sensors_widget_showRawOutput is declared/set in "thermal_sensors.widget.php"
	if (thermal_sensors_widget_showRawOutput) {
		buildThermalSensorsDataRaw(thermalSensorsData);
	} else {
		if(warningTemp == 9999) {
			buildThermalSensorsDataGraph(thermalSensorsData);
		}

		updateThermalSensorsDataGraph(thermalSensorsData);
	}
}

function buildThermalSensorsDataRaw(thermalSensorsData) {

	var thermalSensorsContent = "";

	if (thermalSensorsData && thermalSensorsData != "") {
		thermalSensorsContent = thermalSensorsData.replace(/\|/g, "
");
		//rawData = thermalSensorsData.split("|").join("
");
	}

	loadThermalSensorsContainer(thermalSensorsContent);
}

function loadThermalSensorsContainer (thermalSensorsContent) {

	if (thermalSensorsContent && thermalSensorsContent != "") {
		//load generated graph (or raw data) into thermalSensorsContainer (thermalSensorsContainer DIV defined in "thermal_sensors.widget.php")
		jQuery('#thermalSensorsContainer').html(thermalSensorsContent);
	} else {
		jQuery('#thermalSensorsContainer').html("No Thermal Sensors data available.

");
		jQuery('
').html(
				"* You can configure a proper Thermal Sensor / Module under
" +
				"   System > Advanced > Miscellaneous : Thermal Sensors section."
				).appendTo('#thermalSensorsContainer');
	}
}

function buildThermalSensorsDataGraph(thermalSensorsData) {

	var thermalSensorsArray = new Array();

	if (thermalSensorsData && thermalSensorsData != "") {
		thermalSensorsArray = thermalSensorsData.split("|");
	}

	var thermalSensorsHTMLContent = "";

	//generate graph for each temperature sensor and append to thermalSensorsHTMLContent string
	for (var i = 0; i < thermalSensorsArray.length; i++) {

		var sensorDataArray = thermalSensorsArray[i].split(":");
		var sensorName = sensorDataArray[0].trim();
		var thermalSensorValue = getThermalSensorValue(sensorDataArray[1]);

		//set thresholds
		if (sensorName.indexOf("cpu") > -1) { //check CPU Threshold config settings
			warningTemp = thermal_sensors_widget_coreWarningTempThreshold;
			criticalTemp = thermal_sensors_widget_coreCriticalTempThreshold;
		} else { //assuming sensor is for a zone, check Zone Threshold config settings
			warningTemp = thermal_sensors_widget_zoneWarningTempThreshold;
			criticalTemp = thermal_sensors_widget_zoneCriticalTempThreshold;
		}

		//NOTE: variable thermal_sensors_widget_showFullSensorName is declared/set in "thermal_sensors.widget.php"
		if (!thermal_sensors_widget_showFullSensorName) {
			sensorName = getSensorFriendlyName(sensorName);
		}

		//build temperature item/row for a sensor

		var thermalSensorRow =	'
' +
									'

' +
									'

' +
									'

' +
								'
' +
								'' + sensorName + ': ' + '' + thermalSensorValue + ' °C';

		thermalSensorsHTMLContent = thermalSensorsHTMLContent + thermalSensorRow;

	}

	//load generated graph into thermalSensorsContainer (DIV defined in "thermal_sensors.widget.php")
	loadThermalSensorsContainer(thermalSensorsHTMLContent);

}

function updateThermalSensorsDataGraph(thermalSensorsData) {
	var thermalSensorsArray = new Array();

	if (thermalSensorsData && thermalSensorsData != "") {
		thermalSensorsArray = thermalSensorsData.split("|");
	}

	//generate graph for each temperature sensor and append to thermalSensorsHTMLContent string
	for (var i = 0; i < thermalSensorsArray.length; i++) {

		var sensorDataArray = thermalSensorsArray[i].split(":");
		var sensorName = sensorDataArray[0].trim();
		var thermalSensorValue = getThermalSensorValue(sensorDataArray[1]);

		//set thresholds
		if (sensorName.indexOf("cpu") > -1) { //check CPU Threshold config settings
			warningTemp = thermal_sensors_widget_coreWarningTempThreshold;
			criticalTemp = thermal_sensors_widget_coreCriticalTempThreshold;
		} else { //assuming sensor is for a zone, check Zone Threshold config settings
			warningTemp = thermal_sensors_widget_zoneWarningTempThreshold;
			criticalTemp = thermal_sensors_widget_zoneCriticalTempThreshold;
		}

		//NOTE: variable thermal_sensors_widget_showFullSensorName is declared/set in "thermal_sensors.widget.php"
		if (!thermal_sensors_widget_showFullSensorName) {
			sensorName = getSensorFriendlyName(sensorName);
		}

	setTempProgress(i, thermalSensorValue);
	}
}

function getSensorFriendlyName(sensorFullName) {
	var rzone = /^hw\.acpi\.thermal\.tz([0-9]+)\.temperature$/;
	var rcore = /^dev\.cpu\.([0-9]+)\.temperature$/;

	if (rzone.test(sensorFullName)) {
		return "Zone " + rzone.exec(sensorFullName)[1];
	}

	if (rcore.test(sensorFullName)) {
		return "Core " + rcore.exec(sensorFullName)[1];
	}

	return sensorFullName;
}

function getThermalSensorValue(stringValue) {
	return (+parseFloat(stringValue) || 0).toFixed(1);
}

// Update the progress indicator
// transition = true allows the bar to move at default speed, false = instantaneous
function setTempProgress(bar, percent) {
	var barTempL, barTempM, barTempH;

	if(percent <= warningTemp) {
		barTempL = percent;
		barTempM = 0;
		barTempH = 0;
	} else if(percent <= criticalTemp) {
		barTempL = warningTemp;
		barTempM = percent - warningTemp;
		barTempH = 0;
	} else {
		barTempL = warningTemp;
		barTempM = criticalTemp - warningTemp;
		barTempH = percent - criticalTemp;
	}

	$('#' + 'temperaturebarL' + bar).css('width', barTempL + '%').attr('aria-valuenow', barTempL);
	$('#' + 'temperaturebarM' + bar).css('width', barTempM + '%').attr('aria-valuenow', barTempM);
	$('#' + 'temperaturebarH' + bar).css('width', barTempH + '%').attr('aria-valuenow', barTempH);

	$('#' + 'temperaturemsg' + bar).html(percent + ' °C');
}<|endoftext|>


<commit_before>function cited(text) {
    return Citation.find(text, {
        context: {
            dc_code: {
                source: 'dc_code'
            }
        },
        excerpt: 40,
        types: ['dc_code', 'dc_register', 'dc_law', 'law', 'stat'],
        replace: {
            dc_code: codeCited,
            law: lawCited,
            dc_register: dcrCited,
            stat: statCited,
            dc_law: dcLawCited
        }
    }).text;

    function linked(url, text) {
        return "" + text + "";
    }

    // The detected citation is a DC "Law" - a slip law number, assigned
    // to an act after it becomes law.
    //
    // However, DC's legislative portal, LIMS, does not know law numbers,
    // only act numbers. @vdavez and @adamturoff created a crosswalk between
    // the two.
    //
    // The crosswalk is a JSON object, loaded into the global namespace as "dc_laws".
    // At cite time, this function does a quick lookup in that crosswalk and links
    // the user to the act which became the cited law.
    function dcLawCited(cite) {
        var lawNumber = cite.dc_law.period + "-" + cite.dc_law.number;
        var prefixedLawNumber = cite.dc_law.period + "-" + zeroPrefix(cite.dc_law.number, 3);
        console.log("lawNumber: " + lawNumber);
        console.log("prefixedLawNumber: " + prefixedLawNumber);

        var billNumber = dc_laws[prefixedLawNumber];
        if (!billNumber) // leave unlinked
            return cite.match;

        var pieces = billNumber.split("-");
        billNumber = pieces[0] + "-" + zeroPrefix(pieces[1], 4);

        var text = "D.C. Law " + lawNumber;
        var url = "http://dcclims1.dccouncil.us/lims/legislation.aspx?LegNo=B" + billNumber;
        return linked(url, text);
    }

    // what in Ruby would be:
    // "0" * 5 => "00000"
    function repeated(num, string) {
        return new Array(num + 1).join(string);
    }

    // handles a max of 4
    function zeroPrefix(number, zeroes) {
        var toAdd;
        if (number < 10)
            toAdd = zeroes - 1;
        else if (number < 100)
            toAdd = zeroes - 2;
        else if (number < 1000)
            toAdd = zeroes - 3;
        else
            toAdd = zeroes - 4;

        if (toAdd < 0) toAdd = 0;

        return repeated(toAdd, "0") + number;
    }

    function statCited(cite) {
        if (parseInt(cite.stat.volume, 10) < 65)
            return;

        return linked('http://api.fdsys.gov/link?collection=statute&volume=' + cite.stat.volume + '&page=' + cite.stat.page,
            cite.match);
    }

    // is this a current DC Code cite (something we should cross-link),
    // or is it to a prior version of the DC Code?
    function codeCited(cite) {
        var index = cite.excerpt.search(/ior\s+codifications\s+1981\s+Ed\.?\,?/i);
        if (index > 0 && index < 40) // found, and to the left of the cite
            return;

        return linked("#/" + cite.dc_code.title + "/" + cite.dc_code.title + "-" + cite.dc_code.section,
            cite.match);
    }

    function lawCited(cite) {
        var lawName = cite.law.type + " law " + cite.law.congress + "-" + cite.law.number;
        var url = 'http://www.govtrack.us/search?q=' + encodeURIComponent(lawName);
        return linked(url, cite.match);
    }

    // just link to that year's copy on the DC Register website
    function dcrCited(cite) {
        if (parseInt(cite.dc_register.volume, 10) < 57)
            return;

        var year = parseInt(cite.dc_register.volume, 10) + 1953;
        return linked('http://www.dcregs.dc.gov/Gateway/IssueList.aspx?IssueYear=' + year,
            cite.match);
    }
}
<commit_msg>left some console log statements in there, super cool<commit_after>function cited(text) {
    return Citation.find(text, {
        context: {
            dc_code: {
                source: 'dc_code'
            }
        },
        excerpt: 40,
        types: ['dc_code', 'dc_register', 'dc_law', 'law', 'stat'],
        replace: {
            dc_code: codeCited,
            law: lawCited,
            dc_register: dcrCited,
            stat: statCited,
            dc_law: dcLawCited
        }
    }).text;

    function linked(url, text) {
        return "" + text + "";
    }

    // The detected citation is a DC "Law" - a slip law number, assigned
    // to an act after it becomes law.
    //
    // However, DC's legislative portal, LIMS, does not know law numbers,
    // only act numbers. @vdavez and @adamturoff created a crosswalk between
    // the two.
    //
    // The crosswalk is a JSON object, loaded into the global namespace as "dc_laws".
    // At cite time, this function does a quick lookup in that crosswalk and links
    // the user to the act which became the cited law.
    function dcLawCited(cite) {
        var lawNumber = cite.dc_law.period + "-" + cite.dc_law.number;
        var prefixedLawNumber = cite.dc_law.period + "-" + zeroPrefix(cite.dc_law.number, 3);

        var billNumber = dc_laws[prefixedLawNumber];
        if (!billNumber) // leave unlinked
            return cite.match;

        var pieces = billNumber.split("-");
        billNumber = pieces[0] + "-" + zeroPrefix(pieces[1], 4);

        var text = "D.C. Law " + lawNumber;
        var url = "http://dcclims1.dccouncil.us/lims/legislation.aspx?LegNo=B" + billNumber;
        return linked(url, text);
    }

    // what in Ruby would be:
    // "0" * 5 => "00000"
    function repeated(num, string) {
        return new Array(num + 1).join(string);
    }

    // handles a max of 4
    function zeroPrefix(number, zeroes) {
        var toAdd;
        if (number < 10)
            toAdd = zeroes - 1;
        else if (number < 100)
            toAdd = zeroes - 2;
        else if (number < 1000)
            toAdd = zeroes - 3;
        else
            toAdd = zeroes - 4;

        if (toAdd < 0) toAdd = 0;

        return repeated(toAdd, "0") + number;
    }

    function statCited(cite) {
        if (parseInt(cite.stat.volume, 10) < 65)
            return;

        return linked('http://api.fdsys.gov/link?collection=statute&volume=' + cite.stat.volume + '&page=' + cite.stat.page,
            cite.match);
    }

    // is this a current DC Code cite (something we should cross-link),
    // or is it to a prior version of the DC Code?
    function codeCited(cite) {
        var index = cite.excerpt.search(/ior\s+codifications\s+1981\s+Ed\.?\,?/i);
        if (index > 0 && index < 40) // found, and to the left of the cite
            return;

        return linked("#/" + cite.dc_code.title + "/" + cite.dc_code.title + "-" + cite.dc_code.section,
            cite.match);
    }

    function lawCited(cite) {
        var lawName = cite.law.type + " law " + cite.law.congress + "-" + cite.law.number;
        var url = 'http://www.govtrack.us/search?q=' + encodeURIComponent(lawName);
        return linked(url, cite.match);
    }

    // just link to that year's copy on the DC Register website
    function dcrCited(cite) {
        if (parseInt(cite.dc_register.volume, 10) < 57)
            return;

        var year = parseInt(cite.dc_register.volume, 10) + 1953;
        return linked('http://www.dcregs.dc.gov/Gateway/IssueList.aspx?IssueYear=' + year,
            cite.match);
    }
}
<|endoftext|>


<commit_before>import CLI from '../../../components/shared/cli'
import Grid from '../../../components/ui/grid'

const AutomationSDKSection = () => (

      <Grid wrap>

          <CLI />

The Syncano CLI

Manage the entire process of building and deploying from a simple, powerful and local tool on your computer. With the Syncano Command Line Interface (CLI), you never have to leave your local working environment, and the synchronization and deployment process dynamically occurs in the background. Save time and build more, faster.

Syncano CLI docs

Join CLI project on GitHub

Download CLI now

Syncano Automation SDK

Syncano's serverless platform and your development environment (through SDKs) dynamically  assembles and deploys your app’s backend to the cloud, all while you build your app.

The technology accelerates the software development process by greatly reducing time spent deploying DevOps and managing your backend through a leaner and more dynamic building phase.

              Automation SDK docs

Assembling your Syncano backend instance

Assemble functions called Syncano Sockets to customize your backend through the Automation SDK. This process happens locally, on your computer, and the Syncano Automation SDK dynamically and continuously synchronises and deploys your changes to the  {
                window.scroll(0, document.getElementById('CloudOsSection').offsetTop)
              }}>Syncano Cloud OS. Your customized backend lives inside your private and unique instance of the Syncano Platform, operationalized by the Syncano Cloud OS.

Building more IDE plugins

We want to bring the Automation SDK into your IDE on more platforms and technologies, and you’re our best advocate. Join our Automation SDK project to influence what we prioritize, or to simply learn more about our roadmap.

Wouldn't AI powered backends be great?

We’re just getting started on making the development process automated and autonomous, and we’re eager to leverage Artificial Intelligence to make it even more efficient. Join our AI and Machine Learning project to learn more about our software development roadmap.

      </Grid>

)

export default AutomationSDKSection
<commit_msg>chore(component): add npm link<commit_after>import CLI from '../../../components/shared/cli'
import Grid from '../../../components/ui/grid'

const AutomationSDKSection = () => (

      <Grid wrap>

          <CLI />

The Syncano CLI

Manage the entire process of building and deploying from a simple, powerful and local tool on your computer. With the Syncano Command Line Interface (CLI), you never have to leave your local working environment, and the synchronization and deployment process dynamically occurs in the background. Save time and build more, faster.

Syncano CLI docs

Join CLI project on GitHub

Download CLI now

Syncano Automation SDK

Syncano's serverless platform and your development environment (through SDKs) dynamically  assembles and deploys your app’s backend to the cloud, all while you build your app.

The technology accelerates the software development process by greatly reducing time spent deploying DevOps and managing your backend through a leaner and more dynamic building phase.

              Automation SDK docs

Assembling your Syncano backend instance

Assemble functions called Syncano Sockets to customize your backend through the Automation SDK. This process happens locally, on your computer, and the Syncano Automation SDK dynamically and continuously synchronises and deploys your changes to the  {
                window.scroll(0, document.getElementById('CloudOsSection').offsetTop)
              }}>Syncano Cloud OS. Your customized backend lives inside your private and unique instance of the Syncano Platform, operationalized by the Syncano Cloud OS.

Building more IDE plugins

We want to bring the Automation SDK into your IDE on more platforms and technologies, and you’re our best advocate. Join our Automation SDK project to influence what we prioritize, or to simply learn more about our roadmap.

Wouldn't AI powered backends be great?

We’re just getting started on making the development process automated and autonomous, and we’re eager to leverage Artificial Intelligence to make it even more efficient. Join our AI and Machine Learning project to learn more about our software development roadmap.

      </Grid>

)

export default AutomationSDKSection
<|endoftext|>


<commit_before>var vid = document.getElementById('videoel');
var overlay = document.getElementById('overlay');
var overlayCC = overlay.getContext('2d');

var ctrack = new clm.tracker({useWebGL : true});
ctrack.init(pModel);

stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
document.getElementById('container').appendChild( stats.domElement );

function enablestart() {
  var startbutton = document.getElementById('startbutton');
  startbutton.value = "start";
  startbutton.disabled = null;
}

var insertAltVideo = function(video) {
  if (supports_video()) {
    if (supports_ogg_theora_video()) {
      video.src = "./media/cap12_edit.ogv";
    } else if (supports_h264_baseline_video()) {
      video.src = "./media/cap12_edit.mp4";
    } else {
      return false;
    }
    //video.play();
    return true;
  } else return false;
}
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.msURL || window.mozURL;

// check for camerasupport
if (navigator.getUserMedia) {
  // set up stream
  var videoSelector = {video : true};
  if (window.navigator.appVersion.match(/Chrome\/(.*?) /)) {
    var chromeVersion = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
    if (chromeVersion < 20) {
      videoSelector = "video";
    }
  };

  navigator.getUserMedia(videoSelector, function( stream ) {
    if (vid.mozCaptureStream) {
      vid.mozSrcObject = stream;
    } else {
      vid.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
    }
    vid.play();
  }, function() {
       insertAltVideo(vid);
       document.getElementById('gum').className = "hide";
       document.getElementById('nogum').className = "nohide";
       alert("There was some problem trying to fetch video from your webcam, using a fallback video instead.");
     });
} else {
  insertAltVideo(vid);
  document.getElementById('gum').className = "hide";
  document.getElementById('nogum').className = "nohide";
  alert("Your browser does not seem to support getUserMedia, using a fallback video instead.");
}

vid.addEventListener('canplay', enablestart, false);

var noseLength;
function startVideo() {
  //load nose length first
  firebase.child("noseLength").on("value", function(snapshot) {
    noseLength = snapshot.val();

    // start video
    vid.play();
    // start tracking
    ctrack.start(vid);
    // start loop to draw face
    drawLoop();
  });
}

var calibrateModeOn = false; //determine if calibrating or testing
var calibratedInstances = [];
var scale = 1;
var paths = []; //paths[frame number][point][x or y]
var closedTimer = 0;
var spokenTimer = 0;
var prevIsOpen = false;
var CLOSED_LIMIT = 25*1; //1 "second" worth of frames
var SPOKEN_LIMIT = 25*.6;
var MIN_PATHS_LENGTH = 25;
function drawLoop() {
  requestAnimFrame(drawLoop);
  overlayCC.clearRect(0, 0, 400, 300);

  var currPos = ctrack.getCurrentPosition()
  if (currPos) {
    drawLips(overlay, currPos);
    displayPoints(currPos);

    if(paths.length < MIN_PATHS_LENGTH || spokenTimer > 0) //fill to 25 or currently speaking
      addPoints(paths, currPos);
    else { //more than 25 frames
      while(paths.length >= MIN_PATHS_LENGTH)
        paths.shift() //get rid of oldest by removing from front
      addPoints(paths, currPos); //insert newest frame
    }
    document.getElementById('message').innerHTML = paths.length;

    var isOpen = getMouthDistances(currPos);

    if(isOpen) { //currently speaking, increment
      spokenTimer++;
      if(prevIsOpen == false) //went from closed to open
        spokenTimer += closedTimer; //b/c closed interval counts as speaking

      closedTimer = 0;
    }
    if(prevIsOpen == true && isOpen == false) { //goes from open to closed
      //increment both timers
      spokenTimer++; //could possibly still be speaking, increment
      closedTimer++; //mouth is closed, so increment
    } else if(isOpen == false && closedTimer > 0) { //mouth is closed and closedTimer has begun
      if(closedTimer < CLOSED_LIMIT)
        closedTimer++;
      else { //reached threshold of closedTimer, assume mouth is closed indefinitely now
        //code executes when user finishes speaking!
        if(spokenTimer > SPOKEN_LIMIT) {
          var pathStr = document.getElementById('paths');
          pathStr.innerHTML = "";
          for(var i = 0; i < paths[0].length; i++) { //first frame, 18 points
            pathStr.innerHTML += "Point " + i + ": " + ptToString(paths[0][i][0], paths[0][i][1]);
          }

          //deep copy of paths
          var pathsCopy = [];
          while(paths.length > 0)
            pathsCopy.push(paths.shift());

          if(calibrateModeOn) { //calibration mode
            var inputWord = prompt("What word spoken?");
            askSaveCalibrationMatrix(inputWord, pathsCopy);
          } else { //testing mode
            getBestWord(pathsCopy);
          }
        }
        closedTimer = spokenTimer = 0;
      }
    }

    prevIsOpen = isOpen;
    document.getElementById('spokenTimer').innerHTML = spokenTimer;
    document.getElementById('closedTimer').innerHTML = closedTimer;
  }
}

// update stats on every iteration
document.addEventListener('clmtrackrIteration', function(event) {
  stats.update();
}, false);
<commit_msg>fixing scaling<commit_after>var vid = document.getElementById('videoel');
var overlay = document.getElementById('overlay');
var overlayCC = overlay.getContext('2d');

var ctrack = new clm.tracker({useWebGL : true});
ctrack.init(pModel);

stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
document.getElementById('container').appendChild( stats.domElement );

function enablestart() {
  var startbutton = document.getElementById('startbutton');
  startbutton.value = "start";
  startbutton.disabled = null;
}

var insertAltVideo = function(video) {
  if (supports_video()) {
    if (supports_ogg_theora_video()) {
      video.src = "./media/cap12_edit.ogv";
    } else if (supports_h264_baseline_video()) {
      video.src = "./media/cap12_edit.mp4";
    } else {
      return false;
    }
    //video.play();
    return true;
  } else return false;
}
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.msURL || window.mozURL;

// check for camerasupport
if (navigator.getUserMedia) {
  // set up stream
  var videoSelector = {video : true};
  if (window.navigator.appVersion.match(/Chrome\/(.*?) /)) {
    var chromeVersion = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
    if (chromeVersion < 20) {
      videoSelector = "video";
    }
  };

  navigator.getUserMedia(videoSelector, function( stream ) {
    if (vid.mozCaptureStream) {
      vid.mozSrcObject = stream;
    } else {
      vid.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
    }
    vid.play();
  }, function() {
       insertAltVideo(vid);
       document.getElementById('gum').className = "hide";
       document.getElementById('nogum').className = "nohide";
       alert("There was some problem trying to fetch video from your webcam, using a fallback video instead.");
     });
} else {
  insertAltVideo(vid);
  document.getElementById('gum').className = "hide";
  document.getElementById('nogum').className = "nohide";
  alert("Your browser does not seem to support getUserMedia, using a fallback video instead.");
}

vid.addEventListener('canplay', enablestart, false);

var noseLength;
function startVideo() {
  //load nose length first
  firebase.child("noseLength").on("value", function(snapshot) {
    noseLength = snapshot.val();

    // start video
    vid.play();
    // start tracking
    ctrack.start(vid);
    // start loop to draw face
    drawLoop();
  });
}

var calibrateModeOn = false; //determine if calibrating or testing
var calibratedInstances = [];
var scale = 1;
var paths = []; //paths[frame number][point][x or y]
var closedTimer = 0;
var spokenTimer = 0;
var prevIsOpen = false;
var CLOSED_LIMIT = 25*1; //1 "second" worth of frames
var SPOKEN_LIMIT = 25*.6;
var MIN_PATHS_LENGTH = 25;
function drawLoop() {
  requestAnimFrame(drawLoop);
  overlayCC.clearRect(0, 0, 400, 300);

  var currPos = ctrack.getCurrentPosition()

	if (currPos) {
		drawLips(overlay, currPos);
		displayPoints(currPos);

		if(calibrateModeOn)
			scale = 1;
		else
			scale = noseLength / Math.abs(currPos[33][1] - currPos[62][1]);

		if(paths.length < MIN_PATHS_LENGTH || spokenTimer > 0) //fill to 25 or currently speaking
			addPoints(paths, currPos);
		else //more than 25 frames
		{
			while(paths.length >= MIN_PATHS_LENGTH)
				paths.shift() //get rid of oldest by removing from front
			addPoints(paths, currPos); //insert newest frame
		}
		document.getElementById('message').innerHTML = paths.length;

		var isOpen = getMouthDistances(currPos);

		if(isOpen) //currently speaking, increment
		{
			spokenTimer++;
			if(prevIsOpen == false) //went from closed to open
				spokenTimer += closedTimer; //b/c closed interval counts as speaking

			closedTimer = 0;
		}
		if(prevIsOpen == true && isOpen == false) //goes from open to closed
		{
			//increment both timers
			spokenTimer++; //could possibly still be speaking, increment
			closedTimer++; //mouth is closed, so increment
		}
		else if(isOpen == false && closedTimer > 0) //mouth is closed and closedTimer has begun
		{
			if(closedTimer < CLOSED_LIMIT)
				closedTimer++;
			else //reached threshold of closedTimer, assume mouth is closed indefinitely now
			{
				//code executes when user finishes speaking!
				if(spokenTimer > SPOKEN_LIMIT)
				{
					var pathStr = document.getElementById('paths');
					pathStr.innerHTML = "";
					for(var i = 0; i < paths[0].length; i++) //first frame, 18 points
					{
						pathStr.innerHTML += "Point " + i + ": " + ptToString(paths[0][i][0], paths[0][i][1]);
					}

					//deep copy of paths
					var pathsCopy = [];
					while(paths.length > 0)
						pathsCopy.push(paths.shift());

					if(calibrateModeOn) //calibration mode
					{
						var inputWord = prompt("What word spoken?");
						askSaveCalibrationMatrix(inputWord, pathsCopy);
					}
					else //testing mode
					{
						console.log("displaying");
						getBestWord(pathsCopy);
					}
				}
				closedTimer = spokenTimer = 0;
			}

		}

		prevIsOpen = isOpen;
		document.getElementById('spokenTimer').innerHTML = spokenTimer + "
";
		document.getElementById('closedTimer').innerHTML = closedTimer + "
";
	}

}

// update stats on every iteration
document.addEventListener('clmtrackrIteration', function(event) {
  stats.update();
}, false);
<|endoftext|>