<commit_before>import Vue from 'vue';
import Vuex from 'vuex';
import VueGtag from 'vue-gtag';
import {library} from '@fortawesome/fontawesome-svg-core';
import {
  FontAwesomeIcon,
  FontAwesomeLayers,
  FontAwesomeLayersText,
} from '@fortawesome/vue-fontawesome';
import VueMq from 'vue-mq';

import {
  faUser,
  faEnvelope,
  faSearch,
  faSignOutAlt,
  faHome,
  faPaw,
  faBookmark,
  faExclamationTriangle,
  faGraduationCap,
  faBars,
  faLocationArrow,
  faSquareFull,
  faCaretRight,
  faCaretDown,
  faSquare as fasSquare,
  faTimes,
  faPencilAlt,
  faCheck,
  faPlus,
  faCheckCircle,
  faChevronRight,
} from '@fortawesome/free-solid-svg-icons';

import {
  faEdit,
  faCreditCard,
  faCalendarAlt,
  faCalendarCheck,
  faSquare,
  faCircle,
} from '@fortawesome/free-regular-svg-icons';

// bootstrap vue plugins
import {
  AlertPlugin,
  BadgePlugin,
  ButtonPlugin,
  CardPlugin,
  CollapsePlugin,
  FormPlugin,
  FormGroupPlugin,
  FormInputPlugin,
  FormSelectPlugin,
  InputGroupPlugin,
  LayoutPlugin,
  LinkPlugin,
  NavPlugin,
  SpinnerPlugin,
  TabsPlugin,
  VBTogglePlugin,
  ModalPlugin,
  TablePlugin ,
} from 'bootstrap-vue';

// Mixins
import outlink from './mixins/outlink';
import utils from './mixins/utils';
import courses from './mixins/courses';

// myuw custom theming and global styles
import '../css/myuw/custom.scss';
import '../css/myuw/global.scss';

library.add(faUser);
library.add(faEnvelope);
library.add(faSearch);
library.add(faSignOutAlt);
library.add(faHome);
library.add(faPaw);
library.add(faGraduationCap);
library.add(faEdit);
library.add(faCreditCard);
library.add(faCalendarAlt);
library.add(faCalendarCheck);
library.add(faBookmark);
library.add(faExclamationTriangle);
library.add(faSquare);
library.add(faSquareFull);
library.add(fasSquare);
library.add(faBars);
library.add(faLocationArrow);
library.add(faCaretRight);
library.add(faCaretDown);
library.add(faTimes);
library.add(faPencilAlt);
library.add(faCheck);
library.add(faPlus);
library.add(faCheckCircle);
library.add(faCircle);
library.add(faChevronRight);

// MARK: google analytics data stream measurement_id
const gaCode = document.body.getAttribute('data-gtag');
const hashId = document.body.getAttribute('data-hashid');
const trackingEnabled = document.body.getAttribute('data-tracking-enabled');

// fontawesome 5
Vue.component('font-awesome-icon', FontAwesomeIcon);
Vue.component('font-awesome-layers', FontAwesomeLayers);
Vue.component('font-awesome-layers-text', FontAwesomeLayersText);

// bootstrap-vue components as plugins
Vue.use(AlertPlugin);
Vue.use(BadgePlugin);
Vue.use(ButtonPlugin);
Vue.use(CardPlugin);
Vue.use(CollapsePlugin);
Vue.use(FormPlugin);
Vue.use(FormGroupPlugin);
Vue.use(FormInputPlugin);
Vue.use(FormSelectPlugin);
Vue.use(InputGroupPlugin);
Vue.use(LayoutPlugin);
Vue.use(LinkPlugin);
Vue.use(NavPlugin);
Vue.use(SpinnerPlugin);
Vue.use(TabsPlugin);
Vue.use(VBTogglePlugin);
Vue.use(ModalPlugin);
Vue.use(TablePlugin );

// vuex
Vue.use(Vuex);

// vue-gtag
Vue.use(VueGtag, {
  config: {
    id: gaCode,
    params: {
      anonymize_ip: true,
      user_id: hashId,
    },
  },
  enabled: trackingEnabled == 'true',
});

// vue-mq (media queries)
Vue.use(VueMq, {
  breakpoints: {
    // breakpoints == min-widths of next size
    mobile: 768, // tablet begins 768px
    tablet: 992, // desktop begins 992px
    desktop: Infinity,
  },
});

const store = new Vuex.Store({
  state: {
    user: JSON.parse(document.getElementById('user').innerHTML),
    staticUrl: JSON.parse(document.getElementById('static_url').innerHTML),
    disableActions: JSON.parse(
        document.getElementById('disable_actions').innerHTML,
    ),
    bannerMessages: JSON.parse(
      document.getElementById('banner_messages').innerHTML,
    ),
    displayOnboardMessage: JSON.parse(
      document.getElementById('display_onboard_message').innerHTML,
    ),
    displayPopUp: JSON.parse(
      document.getElementById('display_pop_up').innerHTML,
    ),
    csrfToken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
  },
  mutations: {
    addVarToState(state, {name, value}) {
      state[name] = value;
    },
  },
});

Vue.config.devtools = true;

Vue.mixin(outlink);
Vue.mixin(utils);
Vue.mixin(courses);

const vueConf = {
  el: '#vue_root',
  created: function() {
    document.title = 'MyUW: ' + store.state['pageTitle'];
    document.getElementById('vue_root').hidden = false;
  },
  store: store,
};

vueConf.store.commit('addVarToState', {
  name: 'termData',
  value: window.term_data,
});
vueConf.store.commit('addVarToState', {
  name: 'nextTerm',
  value: window.next_term,
});
vueConf.store.commit('addVarToState', {
  name: 'cardDisplayDates',
  value: JSON.parse(document.getElementById('card_display_dates').innerHTML),
});
export {Vue, vueConf};
<commit_msg>Add plugins<commit_after>import Vue from 'vue';
import Vuex from 'vuex';
import VueGtag from 'vue-gtag';
import {library} from '@fortawesome/fontawesome-svg-core';
import {
  FontAwesomeIcon,
  FontAwesomeLayers,
  FontAwesomeLayersText,
} from '@fortawesome/vue-fontawesome';
import VueMq from 'vue-mq';

import {
  faUser,
  faEnvelope,
  faSearch,
  faSignOutAlt,
  faHome,
  faPaw,
  faBookmark,
  faExclamationTriangle,
  faGraduationCap,
  faBars,
  faLocationArrow,
  faSquareFull,
  faCaretRight,
  faCaretDown,
  faSquare as fasSquare,
  faTimes,
  faPencilAlt,
  faCheck,
  faPlus,
  faCheckCircle,
  faChevronRight,
} from '@fortawesome/free-solid-svg-icons';

import {
  faEdit,
  faCreditCard,
  faCalendarAlt,
  faCalendarCheck,
  faSquare,
  faCircle,
} from '@fortawesome/free-regular-svg-icons';

// bootstrap vue plugins
import {
  AlertPlugin,
  BadgePlugin,
  ButtonPlugin,
  CardPlugin,
  CollapsePlugin,
  FormPlugin,
  FormGroupPlugin,
  FormInputPlugin,
  FormSelectPlugin,
  IconsPlugin,
  InputGroupPlugin,
  ModalPlugin,
  LayoutPlugin,
  LinkPlugin,
  NavPlugin,
  SpinnerPlugin,
  TablePlugin ,
  TabsPlugin,
  VBTogglePlugin,
} from 'bootstrap-vue';

// Mixins
import outlink from './mixins/outlink';
import utils from './mixins/utils';
import courses from './mixins/courses';

// myuw custom theming and global styles
import '../css/myuw/custom.scss';
import '../css/myuw/global.scss';

library.add(faUser);
library.add(faEnvelope);
library.add(faSearch);
library.add(faSignOutAlt);
library.add(faHome);
library.add(faPaw);
library.add(faGraduationCap);
library.add(faEdit);
library.add(faCreditCard);
library.add(faCalendarAlt);
library.add(faCalendarCheck);
library.add(faBookmark);
library.add(faExclamationTriangle);
library.add(faSquare);
library.add(faSquareFull);
library.add(fasSquare);
library.add(faBars);
library.add(faLocationArrow);
library.add(faCaretRight);
library.add(faCaretDown);
library.add(faTimes);
library.add(faPencilAlt);
library.add(faCheck);
library.add(faPlus);
library.add(faCheckCircle);
library.add(faCircle);
library.add(faChevronRight);

// MARK: google analytics data stream measurement_id
const gaCode = document.body.getAttribute('data-gtag');
const hashId = document.body.getAttribute('data-hashid');
const trackingEnabled = document.body.getAttribute('data-tracking-enabled');

// fontawesome 5
Vue.component('font-awesome-icon', FontAwesomeIcon);
Vue.component('font-awesome-layers', FontAwesomeLayers);
Vue.component('font-awesome-layers-text', FontAwesomeLayersText);

// bootstrap-vue components as plugins
Vue.use(AlertPlugin);
Vue.use(BadgePlugin);
Vue.use(ButtonPlugin);
Vue.use(CardPlugin);
Vue.use(CollapsePlugin);
Vue.use(FormPlugin);
Vue.use(FormGroupPlugin);
Vue.use(FormInputPlugin);
Vue.use(FormSelectPlugin);
Vue.use(InputGroupPlugin);
Vue.use(LayoutPlugin);
Vue.use(LinkPlugin);
Vue.use(NavPlugin);
Vue.use(SpinnerPlugin);
Vue.use(TabsPlugin);
Vue.use(VBTogglePlugin);
Vue.use(ModalPlugin);
Vue.use(TablePlugin );
Vue.use(IconsPlugin);

// vuex
Vue.use(Vuex);

// vue-gtag
Vue.use(VueGtag, {
  config: {
    id: gaCode,
    params: {
      anonymize_ip: true,
      user_id: hashId,
    },
  },
  enabled: trackingEnabled == 'true',
});

// vue-mq (media queries)
Vue.use(VueMq, {
  breakpoints: {
    // breakpoints == min-widths of next size
    mobile: 768, // tablet begins 768px
    tablet: 992, // desktop begins 992px
    desktop: Infinity,
  },
});

const store = new Vuex.Store({
  state: {
    user: JSON.parse(document.getElementById('user').innerHTML),
    staticUrl: JSON.parse(document.getElementById('static_url').innerHTML),
    disableActions: JSON.parse(
        document.getElementById('disable_actions').innerHTML,
    ),
    bannerMessages: JSON.parse(
      document.getElementById('banner_messages').innerHTML,
    ),
    displayOnboardMessage: JSON.parse(
      document.getElementById('display_onboard_message').innerHTML,
    ),
    displayPopUp: JSON.parse(
      document.getElementById('display_pop_up').innerHTML,
    ),
    csrfToken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
  },
  mutations: {
    addVarToState(state, {name, value}) {
      state[name] = value;
    },
  },
});

Vue.config.devtools = true;

Vue.mixin(outlink);
Vue.mixin(utils);
Vue.mixin(courses);

const vueConf = {
  el: '#vue_root',
  created: function() {
    document.title = 'MyUW: ' + store.state['pageTitle'];
    document.getElementById('vue_root').hidden = false;
  },
  store: store,
};

vueConf.store.commit('addVarToState', {
  name: 'termData',
  value: window.term_data,
});
vueConf.store.commit('addVarToState', {
  name: 'nextTerm',
  value: window.next_term,
});
vueConf.store.commit('addVarToState', {
  name: 'cardDisplayDates',
  value: JSON.parse(document.getElementById('card_display_dates').innerHTML),
});
export {Vue, vueConf};
<|endoftext|>


<commit_before>var t = require("../../types");
var _ = require("lodash");

exports.XJSAttribute = function (node, print) {
  print(node.name);
  if (node.value) {
    this.push("=");
    print(node.value);
  }
};

exports.XJSIdentifier = function (node) {
  this.push(node.name);
};

exports.XJSNamespacedName = function (node, print) {
  print(node.namespace);
  this.push(":");
  print(node.name);
};

exports.XJSMemberExpression = function (node, print) {
  print(node.object);
  this.push(".");
  print(node.property);
};

exports.XJSSpreadAttribute = function (node, print) {
  this.push("{...");
  print(node.argument);
  this.push("}");
};

exports.XJSExpressionContainer = function (node, print) {
  this.push("{");
  print(node.expression);
  this.push("}");
};

exports.XJSElement = function (node, print) {
  var self = this;

  var open = node.openingElement;
  print(open);
  if (open.selfClosing) return;

  this.indent();
  _.each(node.children, function (child) {
    if (t.isLiteral(child) && typeof child.value === "string") {
      if (/\S/.test(child.value)) {
        return self.push(child.value.replace(/^\s+|\s+$/g, ""));
      } else if (/\n/.test(child.value)) {
        return self.newline();
      }
    }

    print(child);
  });
  this.dedent();

  print(node.closingElement);
};

exports.XJSOpeningElement = function (node, print) {
  this.push("<");
  print(node.name);
  if (node.attributes.length > 0) {
    this.space();
    print.join(node.attributes, { separator: " " });
  }
  this.push(node.selfClosing ? " />" : ">");
};

exports.XJSClosingElement = function (node, print) {
  this.push("</");
  print(node.name);
  this.push(">");
};

exports.XJSEmptyExpression = function () {
  this.push("null");
};
<commit_msg>fix jsx literal generator - closes #143<commit_after>var t = require("../../types");
var _ = require("lodash");

exports.XJSAttribute = function (node, print) {
  print(node.name);
  if (node.value) {
    this.push("=");
    print(node.value);
  }
};

exports.XJSIdentifier = function (node) {
  this.push(node.name);
};

exports.XJSNamespacedName = function (node, print) {
  print(node.namespace);
  this.push(":");
  print(node.name);
};

exports.XJSMemberExpression = function (node, print) {
  print(node.object);
  this.push(".");
  print(node.property);
};

exports.XJSSpreadAttribute = function (node, print) {
  this.push("{...");
  print(node.argument);
  this.push("}");
};

exports.XJSExpressionContainer = function (node, print) {
  this.push("{");
  print(node.expression);
  this.push("}");
};

exports.XJSElement = function (node, print) {
  var self = this;

  var open = node.openingElement;
  print(open);
  if (open.selfClosing) return;

  this.indent();
  _.each(node.children, function (child) {
    if (t.isLiteral(child)) {
      self.push(child.value);
    } else {
      print(child);
    }
  });
  this.dedent();

  print(node.closingElement);
};

exports.XJSOpeningElement = function (node, print) {
  this.push("<");
  print(node.name);
  if (node.attributes.length > 0) {
    this.space();
    print.join(node.attributes, { separator: " " });
  }
  this.push(node.selfClosing ? " />" : ">");
};

exports.XJSClosingElement = function (node, print) {
  this.push("</");
  print(node.name);
  this.push(">");
};

exports.XJSEmptyExpression = function () {
  this.push("null");
};
<|endoftext|>


<commit_before>/*global define*/
define([
    'Source/ThirdParty/when',
    'Specs/addDefaultMatchers',
    'Specs/equalsMethodEqualityTester'
], function (when,
             addDefaultMatchers,
             equalsMethodEqualityTester) {
    "use strict";

    return function (env, includedCategories, excludedCategories) {
        window.defineSuite = function(deps, name, suite, categories) {
            /*global define,describe*/
            if (typeof suite === 'object' || typeof suite === 'string') {
                categories = suite;
            }

            if (typeof name === 'function') {
                suite = name;
                name = deps[0];
            }

            // exclude this test if we're filtering by category and it's not the selected category
            // otherwise if we have not categories, excluded if the category matches
            if (includedCategories && categories !== includedCategories) {
                return;
            } else if (excludedCategories && categories === excludedCategories) {
                return;
            }

            define(deps, function() {
                var args = arguments;
                describe(name, function() {
                    suite.apply(null, args);
                }, categories);
            });
        };

        // Override beforeEach(), afterEach(), beforeAll(), afterAll(), and it() to automatically
        // call done() when a returned promise resolves.
        var originalIt = window.it;

        window.it = function(description, f, timeout, categories) {
            originalIt(description, function(done) {
                var result = f();
                when(result, function() {
                    done();
                }, function(e) {
                    done.fail('promise rejected: ' + e.toString());
                });
            }, timeout, categories);
        };

        var originalBeforeEach = window.beforeEach;

        window.beforeEach = function(f) {
            originalBeforeEach(function(done) {
                var result = f();
                when(result, function() {
                    done();
                }, function(e) {
                    done.fail('promise rejected: ' + e.toString());
                });
            });
        };

        var originalAfterEach = window.afterEach;

        window.afterEach = function(f) {
            originalAfterEach(function(done) {
                var result = f();
                when(result, function() {
                    done();
                }, function(e) {
                    done.fail('promise rejected: ' + e.toString());
                });
            });
        };

        var originalBeforeAll = window.beforeAll;

        window.beforeAll = function(f) {
            originalBeforeAll(function(done) {
                var result = f();
                when(result, function() {
                    done();
                }, function(e) {
                    done.fail('promise rejected: ' + e.toString());
                });
            });
        };

        var originalAfterAll = window.afterAll;

        window.afterAll = function(f) {
            originalAfterAll(function(done) {
                var result = f();
                when(result, function() {
                    done();
                }, function(e) {
                    done.fail('promise rejected: ' + e.toString());
                });
            });
        };

        //env.catchExceptions(true);

        env.beforeEach(function () {
            addDefaultMatchers(true).call(env);
            env.addCustomEqualityTester(equalsMethodEqualityTester);
        });
    };
});
<commit_msg>Updated comment<commit_after>/*global define*/
define([
    'Source/ThirdParty/when',
    'Specs/addDefaultMatchers',
    'Specs/equalsMethodEqualityTester'
], function (when,
             addDefaultMatchers,
             equalsMethodEqualityTester) {
    "use strict";

    return function (env, includedCategories, excludedCategories) {
        window.defineSuite = function(deps, name, suite, categories) {
            /*global define,describe*/
            if (typeof suite === 'object' || typeof suite === 'string') {
                categories = suite;
            }

            if (typeof name === 'function') {
                suite = name;
                name = deps[0];
            }

            // exclude this test if we're filtering by category and it's not the selected category
            // otherwise if we have exlcuded categories, exclude this test if the category matches
            if (includedCategories && categories !== includedCategories) {
                return;
            } else if (excludedCategories && categories === excludedCategories) {
                return;
            }

            define(deps, function() {
                var args = arguments;
                describe(name, function() {
                    suite.apply(null, args);
                }, categories);
            });
        };

        // Override beforeEach(), afterEach(), beforeAll(), afterAll(), and it() to automatically
        // call done() when a returned promise resolves.
        var originalIt = window.it;

        window.it = function(description, f, timeout, categories) {
            originalIt(description, function(done) {
                var result = f();
                when(result, function() {
                    done();
                }, function(e) {
                    done.fail('promise rejected: ' + e.toString());
                });
            }, timeout, categories);
        };

        var originalBeforeEach = window.beforeEach;

        window.beforeEach = function(f) {
            originalBeforeEach(function(done) {
                var result = f();
                when(result, function() {
                    done();
                }, function(e) {
                    done.fail('promise rejected: ' + e.toString());
                });
            });
        };

        var originalAfterEach = window.afterEach;

        window.afterEach = function(f) {
            originalAfterEach(function(done) {
                var result = f();
                when(result, function() {
                    done();
                }, function(e) {
                    done.fail('promise rejected: ' + e.toString());
                });
            });
        };

        var originalBeforeAll = window.beforeAll;

        window.beforeAll = function(f) {
            originalBeforeAll(function(done) {
                var result = f();
                when(result, function() {
                    done();
                }, function(e) {
                    done.fail('promise rejected: ' + e.toString());
                });
            });
        };

        var originalAfterAll = window.afterAll;

        window.afterAll = function(f) {
            originalAfterAll(function(done) {
                var result = f();
                when(result, function() {
                    done();
                }, function(e) {
                    done.fail('promise rejected: ' + e.toString());
                });
            });
        };

        //env.catchExceptions(true);

        env.beforeEach(function () {
            addDefaultMatchers(true).call(env);
            env.addCustomEqualityTester(equalsMethodEqualityTester);
        });
    };
});
<|endoftext|>


<commit_before>import Phaser from 'phaser'

var about;

export default class extends Phaser.State {

  init() {
    //  About information text
    about = game.add.text(this.world.centerX, this.world.centerY + 100,"Name that object: game made with Phaser for Ubykuo   ", {font:"Bangers", fontSize: 22,fill:"#000",align:"center"});
    about.visible = false;
    about.anchor.setTo(0.5, 0.5);
  }

  preload () {
    //  Images and sprites
    game.load.image('volumeon', 'assets/images/volumeon.png');
    game.load.image('menubutton', 'assets/images/menubutton.png');
    game.load.image('whitesquare', 'assets/images/whitesquare.png');
    game.load.image('dog', 'assets/images/dog.png');
    game.load.image('house', 'assets/images/house.png');
    game.load.image('happycar', 'assets/images/happycar.png');
    game.load.spritesheet('letter','assets/images/alphabetspritesheet.png',150,212);

    //  Sound
    game.load.audio('levelcompleted','assets/audio/levelcompleted.mp3');
    game.load.audio('error','assets/audio/error.mp3');
    game.load.audio('youwon','assets/audio/youwon.mp3')

    //  Music
  }

  create () {
    //  Play button
    this.createButton(game, this.world.centerX, this.world.centerY, 200, 50, 'Play Game', function () {
      this.state.start('Game')});

    //  About button
    this.createButton(game, this.world.centerX, this.world.centerY + 50, 200, 50, 'About', function () {
      about.visible ? about.visible = false : about.visible = true;
    });
  }

  createButton(game, x , y, w, h, title, callback) {
    var button = game.add.button(x, y,'menubutton', callback, this, 2, 1, 0);
    button.anchor.setTo(0.5,0.5);
    button.height = h;
    button.width = w;
    var txt = game.add.text(button.x,button.y,title, {font:"Bangers", fill:"#fff",align:"center"});
    txt.anchor.setTo(0.5,0.5);
  }
}<commit_msg>Added game title to the menu <commit_after>import Phaser from 'phaser'

var about;

export default class extends Phaser.State {

  init() {
    //  About information text
    about = game.add.text(this.world.centerX, this.world.centerY + 120,"Name that object: game made for Ubykuo   ", {font:"Bangers", fontSize: 22,fill:"#000",align:"center"});
    about.visible = false;
    about.anchor.setTo(0.5, 0.5);
  }

  preload () {
    //  Images and sprites
    game.load.image('volumeon', 'assets/images/volumeon.png');
    game.load.image('menubutton', 'assets/images/menubutton.png');
    game.load.image('whitesquare', 'assets/images/whitesquare.png');
    game.load.image('dog', 'assets/images/dog.png');
    game.load.image('house', 'assets/images/house.png');
    game.load.image('happycar', 'assets/images/happycar.png');
    game.load.image('bluebuttondown', 'assets/images/bluebuttondown.png');

    game.load.spritesheet('letter','assets/images/alphabetspritesheet.png',150,212);

    //  Sound
    game.load.audio('levelcompleted','assets/audio/levelcompleted.mp3');
    game.load.audio('error','assets/audio/error.mp3');
    game.load.audio('youwon','assets/audio/youwon.mp3')

    //  Music

  }

  create () {

    //  Game title
    var title = game.add.sprite(game.world.centerX,game.world.centerY-500 ,'gametitle');
    title.anchor.set(0.5);
    game.add.tween(title).to( { y: game.world.centerY-200 }, 2000, Phaser.Easing.Back.Out, true);

    //  Play button
    this.createButton(game, this.world.centerX, this.world.centerY, 200, 50, 'Play Game', function () {
      this.state.start('Game')});

    //  About button
    this.createButton(game, this.world.centerX, this.world.centerY + 60, 200, 50, 'About', function () {
      about.visible ? about.visible = false : about.visible = true;
    });
  }

  createButton(game, x , y, w, h, title, callback) {
    var button = game.add.button(x, y,'bluebuttondown', callback, this, 2, 1, 0);
    button.anchor.setTo(0.5,0.5);
    button.height = h;
    button.width = w;
    var txt = game.add.text(button.x,button.y+3,title, {fontFamily:"Bangers", fontSize:16, fill:"#fff",align:"center"});
    txt.anchor.setTo(0.5,0.5);
  }
}<|endoftext|>


<commit_before>// tokens.js
// 2009-05-17

// (c) 2006 Douglas Crockford

// Produce an array of simple token objects from a string.
// A simple token object contains these members:
//      type: 'name', 'string', 'number', 'symbol'
//      value: string or number value of the token
//      from: index of first character of the token
//      to: index of the last character + 1

// Comments of the // type are ignored.

// Operators are by default single characters. Multicharacter
// symbols can be made by supplying a string of prefix and
// suffix characters.
// characters. For example,
//      '<>+-&', '=>&:'
// will match any of these:
//      <=  >>  >>>  <>  >=  +: -: &: &&: &&

var fs = require('fs'),
    sys = require('sys'),
	util = require('./util')

exports.tokenize = util.intercept('TokenizeError', doTokenize)

var TokenizeError = function(file, line, column, msg) {
	this.name = 'TokenizeError';
	this.message = ['on line', line + ',', 'column', column, 'of', '"'+file+'":', msg].join(' ')
}
TokenizeError.prototype = Error.prototype

var keywords = 'import,let,set,for,in,if,else,template,handler'.split(',')
function doTokenize (inputFile) {
    var c;                      // The current character.
    var from;                   // The index of the start of the token.
    var i = 0;                  // The index of the current character.
    var line = 1;               // The line of the current character.
    var lineStart = 0;          // The index at the beginning of the line
    var inputString;            // The string to tokenize
    var length;                 // The length of the input string
    var n;                      // The number value.
    var q;                      // The quote character.
    var str;                    // The string value.
    var prefix = '!=<>';
    var suffix = '=';

    var result = [];            // An array to hold the results.

    var halt = function (msg) {
        var col = from - lineStart + 1
        sys.puts(util.grabLine(inputFile, line, col, i - from));
        throw new TokenizeError(inputFile, line, col, msg);
    }

    var make = function (type, value) {

// Make a token object.

        return {
            type: type,
            value: value,
            from: from,
            span: i - from,
            line: line,
            column: from - lineStart + 1,
            file: inputFile
        };
    };

// Allow for keyword lookup with "if (str in keywords) { ... }"

    for (var kWord, keyI=0; kWord = keywords[keyI]; keyI++) {
        keywords[kWord] = true;
    }

// If prefix and suffix strings are not provided, supply defaults.

    if (typeof prefix !== 'string') {
        prefix = '<>+-&';
    }
    if (typeof suffix !== 'string') {
        suffix = '=>&:';
    }

// Loop through the text, one character at a time.

    inputString = fs.readFileSync(inputFile).toString()
    length = inputString.length

    c = inputString.charAt(i);
    while (c) {
        from = i;

        if (c == '\n') {

// Keep track of the line number

            line += 1;
            i += 1;
            lineStart = i;
            c = inputString.charAt(i);

// Ignore whitespace.

        } else if (c <= ' ') {
            i += 1;
            c = inputString.charAt(i);

// name.

        } else if (c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
            str = c;
            i += 1;
            for (;;) {
                c = inputString.charAt(i);
                if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
                        (c >= '0' && c <= '9') || c === '_') {
                    str += c;
                    i += 1;
                } else {
                    break;
                }
            }
            result.push(make(str in keywords ? 'keyword' : 'name', str));

// number.

// A number cannot start with a decimal point. It must start with a digit,
// possibly '0'.

        } else if (c >= '0' && c <= '9') {
            str = c;
            i += 1;

// Look for more digits.

            for (;;) {
                c = inputString.charAt(i);
                if (c < '0' || c > '9') {
                    break;
                }
                i += 1;
                str += c;
            }

// Look for a decimal fraction part.

            if (c === '.') {
                i += 1;
                str += c;
                for (;;) {
                    c = inputString.charAt(i);
                    if (c < '0' || c > '9') {
                        break;
                    }
                    i += 1;
                    str += c;
                }
            }

// Look for an exponent part.

            if (c === 'e' || c === 'E') {
                i += 1;
                str += c;
                c = inputString.charAt(i);
                if (c === '-' || c === '+') {
                    i += 1;
                    str += c;
                    c = inputString.charAt(i);
                }
                if (c < '0' || c > '9') {
                    halt("Bad exponent");
                }
                do {
                    i += 1;
                    str += c;
                    c = inputString.charAt(i);
                } while (c >= '0' && c <= '9');
            }

// Make sure the next character is not a letter.

            if (c >= 'a' && c <= 'z') {
                str += c;
                i += 1;
                halt("Bad number - should not end in a letter");
            }

// Convert the string value to a number. If it is finite, then it is a good
// token.

            n = +str;
            if (isFinite(n)) {
                result.push(make('number', n));
            } else {
                halt("Bad number");
            }

// string

        } else if (c === '\'' || c === '"') {
            str = '';
            q = c;
            i += 1;
            for (;;) {
                c = inputString.charAt(i);
                if (c < ' ') {
                    halt(c === '\n' || c === '\r' || c === '' ?
                        "Unterminated string." :
                        "Control character in string.", make('', str));
                }

// Look for the closing quote.

                if (c === q) {
                    break;
                }

// Look for escapement.

                if (c === '\\') {
                    i += 1;
                    if (i >= length) {
                        halt("Unterminated string");
                    }
                    c = inputString.charAt(i);
                    switch (c) {
                    case 'b':
                        c = '\b';
                        break;
                    case 'f':
                        c = '\f';
                        break;
                    case 'n':
                        c = '\n';
                        break;
                    case 'r':
                        c = '\r';
                        break;
                    case 't':
                        c = '\t';
                        break;
                    case 'u':
                        if (i >= length) {
                            halt("Unterminated string");
                        }
                        c = parseInt(inputString.substr(i + 1, 4), 16);
                        if (!isFinite(c) || c < 0) {
                            halt("Unterminated string");
                        }
                        c = String.fromCharCode(c);
                        i += 4;
                        break;
                    }
                }
                str += c;
                i += 1;
            }
            i += 1;
            result.push(make('string', str));
            c = inputString.charAt(i);

// comment.

        } else if (c === '/' && inputString.charAt(i + 1) === '/') {
            i += 1;
            for (;;) {
                c = inputString.charAt(i);
                if (c === '\n' || c === '\r' || c === '') {
                    break;
                }
                i += 1;
            }

// combining

        } else if (prefix.indexOf(c) >= 0) {
            str = c;
            i += 1;
            while (i < length) {
                c = inputString.charAt(i);
                if (suffix.indexOf(c) < 0) {
                    break;
                }
                str += c;
                i += 1;
            }
            result.push(make('symbol', str));

// single-character symbol

        } else {
            i += 1;
            result.push(make('symbol', c));
            c = inputString.charAt(i);
        }
    }
    return result;
};
<commit_msg>Remove the unused section of default prefix/suffix strings, and add the + operator prefix<commit_after>// tokens.js
// 2009-05-17

// (c) 2006 Douglas Crockford

// Produce an array of simple token objects from a string.
// A simple token object contains these members:
//      type: 'name', 'string', 'number', 'symbol'
//      value: string or number value of the token
//      from: index of first character of the token
//      to: index of the last character + 1

// Comments of the // type are ignored.

// Operators are by default single characters. Multicharacter
// symbols can be made by supplying a string of prefix and
// suffix characters.
// characters. For example,
//      '<>+-&', '=>&:'
// will match any of these:
//      <=  >>  >>>  <>  >=  +: -: &: &&: &&

var fs = require('fs'),
    sys = require('sys'),
	util = require('./util')

exports.tokenize = util.intercept('TokenizeError', doTokenize)

var TokenizeError = function(file, line, column, msg) {
	this.name = 'TokenizeError';
	this.message = ['on line', line + ',', 'column', column, 'of', '"'+file+'":', msg].join(' ')
}
TokenizeError.prototype = Error.prototype

var keywords = 'import,let,set,for,in,if,else,template,handler'.split(',')
function doTokenize (inputFile) {
    var c;                      // The current character.
    var from;                   // The index of the start of the token.
    var i = 0;                  // The index of the current character.
    var line = 1;               // The line of the current character.
    var lineStart = 0;          // The index at the beginning of the line
    var inputString;            // The string to tokenize
    var length;                 // The length of the input string
    var n;                      // The number value.
    var q;                      // The quote character.
    var str;                    // The string value.
    var prefix = '+!=<>';
    var suffix = '=';

    var result = [];            // An array to hold the results.

    var halt = function (msg) {
        var col = from - lineStart + 1
        sys.puts(util.grabLine(inputFile, line, col, i - from));
        throw new TokenizeError(inputFile, line, col, msg);
    }

    var make = function (type, value) {

// Make a token object.

        return {
            type: type,
            value: value,
            from: from,
            span: i - from,
            line: line,
            column: from - lineStart + 1,
            file: inputFile
        };
    };

// Allow for keyword lookup with "if (str in keywords) { ... }"

    for (var kWord, keyI=0; kWord = keywords[keyI]; keyI++) {
        keywords[kWord] = true;
    }

// Loop through the text, one character at a time.

    inputString = fs.readFileSync(inputFile).toString()
    length = inputString.length

    c = inputString.charAt(i);
    while (c) {
        from = i;

        if (c == '\n') {

// Keep track of the line number

            line += 1;
            i += 1;
            lineStart = i;
            c = inputString.charAt(i);

// Ignore whitespace.

        } else if (c <= ' ') {
            i += 1;
            c = inputString.charAt(i);

// name.

        } else if (c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
            str = c;
            i += 1;
            for (;;) {
                c = inputString.charAt(i);
                if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
                        (c >= '0' && c <= '9') || c === '_') {
                    str += c;
                    i += 1;
                } else {
                    break;
                }
            }
            result.push(make(str in keywords ? 'keyword' : 'name', str));

// number.

// A number cannot start with a decimal point. It must start with a digit,
// possibly '0'.

        } else if (c >= '0' && c <= '9') {
            str = c;
            i += 1;

// Look for more digits.

            for (;;) {
                c = inputString.charAt(i);
                if (c < '0' || c > '9') {
                    break;
                }
                i += 1;
                str += c;
            }

// Look for a decimal fraction part.

            if (c === '.') {
                i += 1;
                str += c;
                for (;;) {
                    c = inputString.charAt(i);
                    if (c < '0' || c > '9') {
                        break;
                    }
                    i += 1;
                    str += c;
                }
            }

// Look for an exponent part.

            if (c === 'e' || c === 'E') {
                i += 1;
                str += c;
                c = inputString.charAt(i);
                if (c === '-' || c === '+') {
                    i += 1;
                    str += c;
                    c = inputString.charAt(i);
                }
                if (c < '0' || c > '9') {
                    halt("Bad exponent");
                }
                do {
                    i += 1;
                    str += c;
                    c = inputString.charAt(i);
                } while (c >= '0' && c <= '9');
            }

// Make sure the next character is not a letter.

            if (c >= 'a' && c <= 'z') {
                str += c;
                i += 1;
                halt("Bad number - should not end in a letter");
            }

// Convert the string value to a number. If it is finite, then it is a good
// token.

            n = +str;
            if (isFinite(n)) {
                result.push(make('number', n));
            } else {
                halt("Bad number");
            }

// string

        } else if (c === '\'' || c === '"') {
            str = '';
            q = c;
            i += 1;
            for (;;) {
                c = inputString.charAt(i);
                if (c < ' ') {
                    halt(c === '\n' || c === '\r' || c === '' ?
                        "Unterminated string." :
                        "Control character in string.", make('', str));
                }

// Look for the closing quote.

                if (c === q) {
                    break;
                }

// Look for escapement.

                if (c === '\\') {
                    i += 1;
                    if (i >= length) {
                        halt("Unterminated string");
                    }
                    c = inputString.charAt(i);
                    switch (c) {
                    case 'b':
                        c = '\b';
                        break;
                    case 'f':
                        c = '\f';
                        break;
                    case 'n':
                        c = '\n';
                        break;
                    case 'r':
                        c = '\r';
                        break;
                    case 't':
                        c = '\t';
                        break;
                    case 'u':
                        if (i >= length) {
                            halt("Unterminated string");
                        }
                        c = parseInt(inputString.substr(i + 1, 4), 16);
                        if (!isFinite(c) || c < 0) {
                            halt("Unterminated string");
                        }
                        c = String.fromCharCode(c);
                        i += 4;
                        break;
                    }
                }
                str += c;
                i += 1;
            }
            i += 1;
            result.push(make('string', str));
            c = inputString.charAt(i);

// comment.

        } else if (c === '/' && inputString.charAt(i + 1) === '/') {
            i += 1;
            for (;;) {
                c = inputString.charAt(i);
                if (c === '\n' || c === '\r' || c === '') {
                    break;
                }
                i += 1;
            }

// combining

        } else if (prefix.indexOf(c) >= 0) {
            str = c;
            i += 1;
            while (i < length) {
                c = inputString.charAt(i);
                if (suffix.indexOf(c) < 0) {
                    break;
                }
                str += c;
                i += 1;
            }
            result.push(make('symbol', str));

// single-character symbol

        } else {
            i += 1;
            result.push(make('symbol', c));
            c = inputString.charAt(i);
        }
    }
    return result;
};
<|endoftext|>


<commit_before>/**
 * The Group Manager provides functions to manage groups in the database
 */

/*
 * 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var ERR = require("async-stacktrace");
var customError = require("../utils/customError");
var randomString = require("../utils/randomstring");
var db = require("./DB").db;
var async = require("async");
var padManager = require("./PadManager");
var sessionManager = require("./SessionManager");

exports.deleteGroup = function(groupID, callback)
{
  var group;

  async.series([
    //ensure group exists
    function (callback)
    {
      //try to get the group entry
      db.get("group:" + groupID, function (err, _group)
      {
        if(ERR(err, callback)) return;

        //group does not exist
        if(_group == null)
        {
          callback(new customError("groupID does not exist","apierror"));
        }
        //group exists, everything is fine
        else
        {
          group = _group;
          callback();
        }
      });
    },
    //iterate trough all pads of this groups and delete them
    function(callback)
    {
      //collect all padIDs in an array, that allows us to use async.forEach
      var padIDs = [];
      for(var i in group.pads)
      {
        padIDs.push(i);
      }

      //loop trough all pads and delete them
      async.forEach(padIDs, function(padID, callback)
      {
        padManager.getPad(padID, function(err, pad)
        {
          if(ERR(err, callback)) return;

          pad.remove(callback);
        });
      }, callback);
    },
    //iterate trough group2sessions and delete all sessions
    function(callback)
    {
      //try to get the group entry
      db.get("group2sessions:" + groupID, function (err, group2sessions)
      {
        if(ERR(err, callback)) return;

        //skip if there is no group2sessions entry
        if(group2sessions == null) {callback(); return}

        //collect all sessions in an array, that allows us to use async.forEach
        var sessions = [];
        for(var i in group2sessions.sessionsIDs)
        {
          sessions.push(i);
        }

        //loop trough all sessions and delete them
        async.forEach(sessions, function(session, callback)
        {
          sessionManager.deleteSession(session, callback);
        }, callback);
      });
    },
    //remove group and group2sessions entry
    function(callback)
    {
      db.remove("group2sessions:" + groupID);
      db.remove("group:" + groupID);
      callback();
    }
  ], function(err)
  {
    if(ERR(err, callback)) return;
    callback();
  });
}

exports.doesGroupExist = function(groupID, callback)
{
  //try to get the group entry
  db.get("group:" + groupID, function (err, group)
  {
    if(ERR(err, callback)) return;
    callback(null, group != null);
  });
}

exports.createGroup = function(callback)
{
  //search for non existing groupID
  var groupID = "g." + randomString(16);

  //create the group
  db.set("group:" + groupID, {pads: {}});
  callback(null, {groupID: groupID});
}

exports.createGroupIfNotExistsFor = function(groupMapper, callback)
{
  //ensure mapper is optional
  if(typeof groupMapper != "string")
  {
    callback(new customError("groupMapper is no string","apierror"));
    return;
  }

  //try to get a group for this mapper
  db.get("mapper2group:"+groupMapper, function(err, groupID)
  {
     if(ERR(err, callback)) return;

     //there is no group for this mapper, let's create a group
     if(groupID == null)
     {
       exports.createGroup(function(err, responseObj)
       {
         if(ERR(err, callback)) return;

         //create the mapper entry for this group
         db.set("mapper2group:"+groupMapper, responseObj.groupID);

         callback(null, responseObj);
       });
     }
     //there is a group for this mapper, let's return it
     else
     {
       if(ERR(err, callback)) return;
       callback(null, {groupID: groupID});
     }
  });
}

exports.createGroupPad = function(groupID, padName, text, callback)
{
  //create the padID
  var padID = groupID + "$" + padName;

  async.series([
    //ensure group exists
    function (callback)
    {
      exports.doesGroupExist(groupID, function(err, exists)
      {
        if(ERR(err, callback)) return;

        //group does not exist
        if(exists == false)
        {
          callback(new customError("groupID does not exist","apierror"));
        }
        //group exists, everything is fine
        else
        {
          callback();
        }
      });
    },
    //ensure pad does not exists
    function (callback)
    {
      padManager.doesPadExists(padID, function(err, exists)
      {
        if(ERR(err, callback)) return;

        //pad exists already
        if(exists == true)
        {
          callback(new customError("padName does already exist","apierror"));
        }
        //pad does not exist, everything is fine
        else
        {
          callback();
        }
      });
    },
    //create the pad
    function (callback)
    {
      padManager.getPad(padID, text, function(err)
      {
        if(ERR(err, callback)) return;
        callback();
      });
    },
    //create an entry in the group for this pad
    function (callback)
    {
      db.setSub("group:" + groupID, ["pads", padID], 1);
      callback();
    }
  ], function(err)
  {
    if(ERR(err, callback)) return;
    callback(null, {padID: padID});
  });
}

exports.listPads = function(groupID, callback)
{
  exports.doesGroupExist(groupID, function(err, exists)
  {
    if(ERR(err, callback)) return;

    //group does not exist
    if(exists == false)
    {
      callback(new customError("groupID does not exist","apierror"));
    }
    //group exists, let's get the pads
    else
    {
      db.getSub("group:" + groupID, ["pads"], function(err, pads)
      {
        if(ERR(err, callback)) return;
        callback(null, {padIDs: pads});
      });
    }
  });
}
<commit_msg>HTTP API listPads should return an array<commit_after>/**
 * The Group Manager provides functions to manage groups in the database
 */

/*
 * 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var ERR = require("async-stacktrace");
var customError = require("../utils/customError");
var randomString = require("../utils/randomstring");
var db = require("./DB").db;
var async = require("async");
var padManager = require("./PadManager");
var sessionManager = require("./SessionManager");

exports.deleteGroup = function(groupID, callback)
{
  var group;

  async.series([
    //ensure group exists
    function (callback)
    {
      //try to get the group entry
      db.get("group:" + groupID, function (err, _group)
      {
        if(ERR(err, callback)) return;

        //group does not exist
        if(_group == null)
        {
          callback(new customError("groupID does not exist","apierror"));
        }
        //group exists, everything is fine
        else
        {
          group = _group;
          callback();
        }
      });
    },
    //iterate trough all pads of this groups and delete them
    function(callback)
    {
      //collect all padIDs in an array, that allows us to use async.forEach
      var padIDs = [];
      for(var i in group.pads)
      {
        padIDs.push(i);
      }

      //loop trough all pads and delete them
      async.forEach(padIDs, function(padID, callback)
      {
        padManager.getPad(padID, function(err, pad)
        {
          if(ERR(err, callback)) return;

          pad.remove(callback);
        });
      }, callback);
    },
    //iterate trough group2sessions and delete all sessions
    function(callback)
    {
      //try to get the group entry
      db.get("group2sessions:" + groupID, function (err, group2sessions)
      {
        if(ERR(err, callback)) return;

        //skip if there is no group2sessions entry
        if(group2sessions == null) {callback(); return}

        //collect all sessions in an array, that allows us to use async.forEach
        var sessions = [];
        for(var i in group2sessions.sessionsIDs)
        {
          sessions.push(i);
        }

        //loop trough all sessions and delete them
        async.forEach(sessions, function(session, callback)
        {
          sessionManager.deleteSession(session, callback);
        }, callback);
      });
    },
    //remove group and group2sessions entry
    function(callback)
    {
      db.remove("group2sessions:" + groupID);
      db.remove("group:" + groupID);
      callback();
    }
  ], function(err)
  {
    if(ERR(err, callback)) return;
    callback();
  });
}

exports.doesGroupExist = function(groupID, callback)
{
  //try to get the group entry
  db.get("group:" + groupID, function (err, group)
  {
    if(ERR(err, callback)) return;
    callback(null, group != null);
  });
}

exports.createGroup = function(callback)
{
  //search for non existing groupID
  var groupID = "g." + randomString(16);

  //create the group
  db.set("group:" + groupID, {pads: {}});
  callback(null, {groupID: groupID});
}

exports.createGroupIfNotExistsFor = function(groupMapper, callback)
{
  //ensure mapper is optional
  if(typeof groupMapper != "string")
  {
    callback(new customError("groupMapper is no string","apierror"));
    return;
  }

  //try to get a group for this mapper
  db.get("mapper2group:"+groupMapper, function(err, groupID)
  {
     if(ERR(err, callback)) return;

     //there is no group for this mapper, let's create a group
     if(groupID == null)
     {
       exports.createGroup(function(err, responseObj)
       {
         if(ERR(err, callback)) return;

         //create the mapper entry for this group
         db.set("mapper2group:"+groupMapper, responseObj.groupID);

         callback(null, responseObj);
       });
     }
     //there is a group for this mapper, let's return it
     else
     {
       if(ERR(err, callback)) return;
       callback(null, {groupID: groupID});
     }
  });
}

exports.createGroupPad = function(groupID, padName, text, callback)
{
  //create the padID
  var padID = groupID + "$" + padName;

  async.series([
    //ensure group exists
    function (callback)
    {
      exports.doesGroupExist(groupID, function(err, exists)
      {
        if(ERR(err, callback)) return;

        //group does not exist
        if(exists == false)
        {
          callback(new customError("groupID does not exist","apierror"));
        }
        //group exists, everything is fine
        else
        {
          callback();
        }
      });
    },
    //ensure pad does not exists
    function (callback)
    {
      padManager.doesPadExists(padID, function(err, exists)
      {
        if(ERR(err, callback)) return;

        //pad exists already
        if(exists == true)
        {
          callback(new customError("padName does already exist","apierror"));
        }
        //pad does not exist, everything is fine
        else
        {
          callback();
        }
      });
    },
    //create the pad
    function (callback)
    {
      padManager.getPad(padID, text, function(err)
      {
        if(ERR(err, callback)) return;
        callback();
      });
    },
    //create an entry in the group for this pad
    function (callback)
    {
      db.setSub("group:" + groupID, ["pads", padID], 1);
      callback();
    }
  ], function(err)
  {
    if(ERR(err, callback)) return;
    callback(null, {padID: padID});
  });
}

exports.listPads = function(groupID, callback)
{
  exports.doesGroupExist(groupID, function(err, exists)
  {
    if(ERR(err, callback)) return;

    //group does not exist
    if(exists == false)
    {
      callback(new customError("groupID does not exist","apierror"));
    }
    //group exists, let's get the pads
    else
    {
      db.getSub("group:" + groupID, ["pads"], function(err, result)
      {
        if(ERR(err, callback)) return;
        var pads = [];
        for ( var padId in result ) {
          pads.push(padId);
        }
        callback(null, {padIDs: pads});
      });
    }
  });
}
<|endoftext|>


<commit_before>/*
given a sorted array, find the index of an element
using a binary search algorithm.

Test for linear vs binary by applying a data set that
exhibits the desired characteristics.
*/

/**
 * example usage
 * var index = binarySearch([1, 2, 3, 4, 5], 4);
 * console.log(index); // [3]
**/

var binarySearch = function(array, target) {

  var recurse = function(low, high){
    // if low is also high, then index isn't found
    if( low === high ){ return null; }

    var mid = Math.floor( (high - low)/2 + low );

    console.log( low, mid, high );

    // if target found, return index
    if( array[mid] === target ){
      return mid;
    // if not, recurse on corresponding side
    } else if( array[mid] > target ){
      console.log('left');
      recurse( low, mid );
    } else {
      console.log('right');
      recurse( mid, high );
    }
  };

  return recurse(0, array.length);
};<commit_msg>binarySearchArray mostly done<commit_after>/*
given a sorted array, find the index of an element
using a binary search algorithm.

Test for linear vs binary by applying a data set that
exhibits the desired characteristics.
*/

/**
 * example usage
 * var index = binarySearch([1, 2, 3, 4, 5], 4);
 * console.log(index); // [3]
**/

var binarySearch = function(array, target) {

  var recurse = function(low, high){
    // if low is also high, then index isn't found
    if( high === low ){ return null; }

    var mid = Math.floor((high - low)/2) + low;

    // if target found, return index
    if( array[mid] === target ){
      return mid;

    // if not, recurse on corresponding side
    } else if( array[mid] > target ){
      return recurse( low, mid );

    } else {
      return recurse( mid, high );
    }
  };

  return recurse(0, array.length);
};<|endoftext|>


<commit_before>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *
 *  Javascript/jQuery functions to initialize UI on page
 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

$(".menu-link").click(
	function() {
		show_page();
	}
);
$(".home").click(
	function() {
		hide_page();
	}
);
$(".resume").click(
	function() {
		if (!($(this).hasClass('active'))) {
			$('*').removeClass('active');
			$('#nav-resume').addClass('active');
			clear_section();
			load_page_to_section('page-content','resume');
			load_cards();
		}
	}
);
$(".about").click(
	function() {
		if (!($(this).hasClass('active'))) {
			$('*').removeClass('active');
			$('#nav-about').addClass('active');
			clear_section();
			load_page_to_section('page-content','about');
			load_cards();
		}
	}
);
$(".projects").click(
	function() {
		if (!($(this).hasClass('active'))) {
			$('*').removeClass('active');
			$('#nav-projects').addClass('active');
			clear_section();
			load_page_to_section('page-content','projects');
			load_cards();
		}
	}
);
$(".contact").click(
	function() {
		if (!($(this).hasClass('active'))) {
			$('*').removeClass('active');
			$('#nav-contact').addClass('active');
			clear_section();
			console.log("load");
			load_page_to_section('page-content','contact');
			load_cards();
		}
	}
);

function sneaky() {
	return Dajaxice.content.sneaky(sneaky_callback);
}

function sneaky_callback(json) {
	window.location = json.cargo;
};

$(window).mousemove(adjustBackground);

<commit_msg>mail javascript updated<commit_after>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *
 *  Javascript/jQuery functions to initialize UI on page
 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

$(".menu-link").click(
	function() {
		show_page();
	}
);
$(".home").click(
	function() {
		hide_page();
	}
);
$(".resume").click(
	function() {
		if (!($(this).hasClass('active'))) {
			$('*').removeClass('active');
			$('#nav-resume').addClass('active');
			clear_section();
			load_page_to_section('page-content','resume');
			load_cards();
		}
	}
);
$(".about").click(
	function() {
		if (!($(this).hasClass('active'))) {
			$('*').removeClass('active');
			$('#nav-about').addClass('active');
			clear_section();
			load_page_to_section('page-content','about');
			load_cards();
		}
	}
);
$(".projects").click(
	function() {
		if (!($(this).hasClass('active'))) {
			$('*').removeClass('active');
			$('#nav-projects').addClass('active');
			clear_section();
			load_page_to_section('page-content','projects');
			load_cards();
		}
	}
);
$(".contact").click(
	function() {
		if (!($(this).hasClass('active'))) {
			$('*').removeClass('active');
			$('#nav-contact').addClass('active');
			clear_section();
			console.log("load");
			load_page_to_section('page-content','contact');
			load_cards();
		}
	}
);

function sneaky() {
	return Dajaxice.content.sneaky(sneaky_callback);
}

function sneaky_callback(json) {
	window.location = json.cargo;
	return void(0);
};

$(window).mousemove(adjustBackground);

<|endoftext|>


<commit_before>function PreferencesAssistant() {}

PreferencesAssistant.prototype.setup = function() {
    this.logOutputNum = 0;

    // Toggle for enabling debug messages, helpful when pairing devices
    this.controller.setupWidget("debugToggle",
				{},
				this.debugToggleModel = {
				    value: Main.debugEnable
				});
    // Toggle for enabling the volume keys sending page-up/page-down events
    this.controller.setupWidget("enableVolumekeys",
				{},
				this.enableVolumekeysModel = {
				    value: Main.enableVolumekeys
				});

    // Toggle for disabling power-saving for this app
    this.controller.setupWidget("inhibitPowerOff",
				{},
				this.inhibitPowerOffModel = {
				    value: Main.inhibitPowerOff
				});

    // Toggle sending Mouse events
    this.controller.setupWidget("useMouse",
				{},
				this.useMouseModel = {
				    value: Main.useMouse
				});

    // Mapping values to display text for custom buttons
    this.displayMapping = {
	"": "<nothing>",
	"enter": "Enter",
	"pgup": "Page Up",
	"pgdn": "Page Down",
	"crup": "Cursor Up",
	"crdn": "Cursor Down",
	"crlt": "Cursor Left",
	"crrt": "Cursor Right",
	"alttab": "Alt-Tab"
    };

    // Customize "forward swipe" and the four on-screen buttons
    this.selectorChoices = [];
    this.selectorChoices.push({label: this.displayMapping[""], value: ""});
    this.selectorChoices.push({label: this.displayMapping["enter"], value: "enter"});
    this.selectorChoices.push({label: this.displayMapping["pgup"], value: "pgup"});
    this.selectorChoices.push({label: this.displayMapping["pgdn"], value: "pgdn"});
    this.selectorChoices.push({label: this.displayMapping["crup"], value: "crup"});
    this.selectorChoices.push({label: this.displayMapping["crdn"], value: "crdn"});
    this.selectorChoices.push({label: this.displayMapping["crlt"], value: "crlt"});
    this.selectorChoices.push({label: this.displayMapping["crrt"], value: "crrt"});
    this.selectorChoices.push({label: this.displayMapping["alttab"], value: "alttab"});

    // Setup "forward-swipe" action
    this.ForwardModel = {value: Main.specialKeys["forwardEvent"].code, choices: this.selectorChoices};
    this.forwardswipeSelectorAttributes = {label: 'Fwd swipe key', modelProperty:'value' };
    this.controller.setupWidget("forwardSelector", this.forwardswipeSelectorAttributes, this.ForwardModel);

    // Setup the preferences for the four on-screen buttons
    this.button1Model = {value: Main.specialKeys["button_1_el"].code,
			 choices: this.selectorChoices};
    this.button2Model = {value: Main.specialKeys["button_2_el"].code,
			 choices: this.selectorChoices};
    this.button3Model = {value: Main.specialKeys["button_3_el"].code,
			 choices: this.selectorChoices};
    this.button4Model = {value: Main.specialKeys["button_4_el"].code,
			 choices: this.selectorChoices};

    this.button1SelectorAttributes = {label: '1st onscr btn', modelProperty:'value' };
    this.button2SelectorAttributes = {label: '2nd onscr btn', modelProperty:'value' };
    this.button3SelectorAttributes = {label: '3rd onscr btn', modelProperty:'value' };
    this.button4SelectorAttributes = {label: '4th onscr btn', modelProperty:'value' };

    this.controller.setupWidget("button1Selector",
				this.button1SelectorAttributes,
				this.button1Model);
    this.controller.setupWidget("button2Selector",
				this.button2SelectorAttributes,
				this.button2Model);
    this.controller.setupWidget("button3Selector",
				this.button3SelectorAttributes,
				this.button3Model);
    this.controller.setupWidget("button4Selector",
				this.button4SelectorAttributes,
				this.button4Model);

    // Setup volume keys
    this.volumeUpModel = {value: Main.specialKeys["volume_up"].code, choices: this.selectorChoices};
    this.volumeDnModel = {value: Main.specialKeys["volume_down"].code, choices: this.selectorChoices};
    this.volumeUpSelectorAttributes = {label: 'Volume up', modelProperty:'value' };
    this.volumeDnSelectorAttributes = {label: 'Volume dn', modelProperty:'value' };
    this.controller.setupWidget("volumeUpSelector",
				this.volumeUpSelectorAttributes,
				this.volumeUpModel);
    this.controller.setupWidget("volumeDnSelector",
				this.volumeDnSelectorAttributes,
				this.volumeDnModel);

    this.changeDebugHandler = this.changeDebug.bindAsEventListener(this);
    this.changeEnableVolumekeysHandler = this.changeEnableVolumekeys.bindAsEventListener(this);
    this.changeInhibitPowerOffHandler = this.changeInhibitPowerOff.bindAsEventListener(this);
    this.useMouseHandler = this.changeUseMouse.bindAsEventListener(this);
    this.forwardActionHandler = this.changeForwardAction.bindAsEventListener(this);
    this.button1ActionHandler = this.changeButton1Action.bindAsEventListener(this);
    this.button2ActionHandler = this.changeButton2Action.bindAsEventListener(this);
    this.button3ActionHandler = this.changeButton3Action.bindAsEventListener(this);
    this.button4ActionHandler = this.changeButton4Action.bindAsEventListener(this);
    this.volumeUpActionHandler = this.changeVolumeUpAction.bindAsEventListener(this);
    this.volumeDnActionHandler = this.changeVolumeDnAction.bindAsEventListener(this);
}

PreferencesAssistant.prototype.changeForwardAction = function(event) {
    // event triggerd by user: value changed
    Main.specialKeys["forwardEvent"].code = this.ForwardModel.value;
    Main.specialKeys["forwardEvent"].label = this.displayMapping[this.ForwardModel.value];
}

PreferencesAssistant.prototype.changeButton1Action = function(event) {
    Main.specialKeys["button_1_el"].code = this.button1Model.value;
    Main.specialKeys["button_1_el"].label = this.displayMapping[this.button1Model.value];
}

PreferencesAssistant.prototype.changeButton2Action = function(event) {
    Main.specialKeys["button_2_el"].code = this.button2Model.value;
    Main.specialKeys["button_2_el"].label = this.displayMapping[this.button2Model.value];
}

PreferencesAssistant.prototype.changeButton3Action = function(event) {
    Main.specialKeys["button_3_el"].code = this.button3Model.value;
    Main.specialKeys["button_3_el"].label = this.displayMapping[this.button3Model.value];
}

PreferencesAssistant.prototype.changeButton4Action = function(event) {
    Main.specialKeys["button_4_el"].code = this.button4Model.value;
    Main.specialKeys["button_4_el"].label = this.displayMapping[this.button4Model.value];
}

PreferencesAssistant.prototype.changeVolumeUpAction = function(event) {
    Main.specialKeys["volume_up"].code = this.volumeUpModel.value;
    Main.specialKeys["volume_up"].label = this.displayMapping[this.volumeUpModel.value];
}

PreferencesAssistant.prototype.changeVolumeDnAction = function(event) {
    Main.specialKeys["volume_down"].code = this.volumeDnModel.value;
    Main.specialKeys["volume_down"].label = this.displayMapping[this.volumeDnModel.value];
}

PreferencesAssistant.prototype.changeDebug = function(event) {
    // event triggerd by user: value changed
    Mojo.Log.info("Preferences changeDebug; value = ", this.debugToggleModel.value);
    Main.debugEnable = this.debugToggleModel.value;
    Mojo.Log.info("Main.debugEnable = ", Main.debugEnable);
    if (Main.debugEnable === false) {
	this.controller.get('log-output').innerHTML = "";
    }
}

PreferencesAssistant.prototype.changeEnableVolumekeys = function(event) {
    // event triggerd by user: value changed
    this.logInfo("Preferences changEnableVolumekeys; value = ", this.enableVolumekeysModel.value);
    Main.enableVolumekeys = this.enableVolumekeysModel.value;
    this.logInfo("Main.enableVolumekeys = ", Main.enableVolumekeys);
}

PreferencesAssistant.prototype.changeUseMouse = function(event) {
    // event triggerd by user: value changed
    this.logInfo("Preferences changeUseMouse; value = ", this.useMouseModel.value);
    Main.useMouse = this.useMouseModel.value;
    this.logInfo("Main.useMouse = ", Main.useMouse);
}

PreferencesAssistant.prototype.changeInhibitPowerOff = function(event) {
    // event triggerd by user: value changed
    var that = this; // scoping of this
    this.logInfo("Preferences changeInhibitPowerOff; value = ", this.inhibitPowerOffModel.value);
    if (this.inhibitPowerOffModel.value === true) {
	this.controller.serviceRequest("palm://com.palm.power/com/palm/power", {
	    method: "activityStart",
	    parameters: {
		id: "com.henschkowski.app.bluetoothpresenter",
		duration_ms: 900000
	    },
	    onSuccess: function() { that.logInfo("power activate OK");},
	    onFailure: function() { that.logInfo("power activate NOK");}
	});
    } else {
	this.controller.serviceRequest("palm://com.palm.power/com/palm/power", {
	    method: "activityEnd",
	    parameters: {
		id: "com.henschkowski.app.bluetoothpresenter",
	    },
	    onSuccess: function() { that.logInfo("power deactivate OK");},
	    onFailure: function() { that.logInfo("power deactivate NOK");}
	});
    }
}

PreferencesAssistant.prototype.activate = function(event) {
    if (Main.debugEnable === false) {
	this.controller.get('log-output').innerHTML = "";
    }
    this.controller.listen("debugToggle", Mojo.Event.propertyChange, this.changeDebugHandler);
    this.controller.listen("forwardSelector", Mojo.Event.propertyChange, this.forwardActionHandler);
    this.controller.listen("button1Selector", Mojo.Event.propertyChange, this.button1ActionHandler);
    this.controller.listen("button2Selector", Mojo.Event.propertyChange, this.button2ActionHandler);
    this.controller.listen("button3Selector", Mojo.Event.propertyChange, this.button3ActionHandler);
    this.controller.listen("button4Selector", Mojo.Event.propertyChange, this.button4ActionHandler);
    this.controller.listen("volumeUpSelector", Mojo.Event.propertyChange, this.volumeUpActionHandler);
    this.controller.listen("volumeDnSelector", Mojo.Event.propertyChange, this.volumeDnActionHandler);
    this.controller.listen("enableVolumekeys", Mojo.Event.propertyChange, this.changeEnableVolumekeysHandler);
    this.controller.listen("inhibitPowerOff", Mojo.Event.propertyChange, this.changeInhibitPowerOffHandler);
    this.controller.listen("useMouse", Mojo.Event.propertyChange, this.useMouseHandler);
}

PreferencesAssistant.prototype.deactivate = function(event) {
    // save preferences to cookie
    var specialKeysCookie = new Mojo.Model.Cookie('specialkeys');
    specialKeysCookie.put(Main.specialKeys);
}

PreferencesAssistant.prototype.cleanup = function(event) {
    this.controller.stopListening("debugToggle", Mojo.Event.propertyChange,
				  this.changeDebugHandler);
    this.controller.stopListening("forwardSelector", Mojo.Event.propertyChange,
				  this.changeForwardAction);
    this.controller.stopListening("button1Selector", Mojo.Event.propertyChange,
    				  this.changeButton1Action);
    this.controller.stopListening("button2Selector", Mojo.Event.propertyChange,
    				  this.changeButton2Action);
    this.controller.stopListening("button3Selector", Mojo.Event.propertyChange,
    				  this.changeButton3Action);
    this.controller.stopListening("button4Selector", Mojo.Event.propertyChange,
    				  this.changeButton4Action);
    this.controller.stopListening("volumeUpSelector", Mojo.Event.propertyChange,
    				  this.volumeUpActionHandler);
    this.controller.stopListening("volumeDnSelector", Mojo.Event.propertyChange,
    				  this.volumeDnActionHandler);
    this.controller.stopListening("enableVolumekeys", Mojo.Event.propertyChange,
				  this.changeEnableVolumekeysHandler);
    this.controller.stopListening("inhibitPowerOff", Mojo.Event.propertyChange,
				  this.changeInhibitPowerOffHandler);
    this.controller.stopListening("useMouse", Mojo.Event.propertyChange,
				  this.useMouseHandler);

}

PreferencesAssistant.prototype.logInfo = function(logText) {
    if(Main.debugEnable === true) {
	this.controller.get('log-output').innerHTML = "" +
	    this.logOutputNum++ + ": " + logText +
	    "
" +
	    this.controller.get('log-output').innerHTML +
	    "

";
    }
}

<commit_msg>added ESC and function keys for onscreen buttons<commit_after>function PreferencesAssistant() {}

PreferencesAssistant.prototype.setup = function() {
    this.logOutputNum = 0;

    // Toggle for enabling debug messages, helpful when pairing devices
    this.controller.setupWidget("debugToggle",
				{},
				this.debugToggleModel = {
				    value: Main.debugEnable
				});
    // Toggle for enabling the volume keys sending page-up/page-down events
    this.controller.setupWidget("enableVolumekeys",
				{},
				this.enableVolumekeysModel = {
				    value: Main.enableVolumekeys
				});

    // Toggle for disabling power-saving for this app
    this.controller.setupWidget("inhibitPowerOff",
				{},
				this.inhibitPowerOffModel = {
				    value: Main.inhibitPowerOff
				});

    // Toggle sending Mouse events
    this.controller.setupWidget("useMouse",
				{},
				this.useMouseModel = {
				    value: Main.useMouse
				});

    // Mapping values to display text for custom buttons
    this.displayMapping = {
	"": "<nothing>",
	"enter": "Enter",
	"pgup": "Page Up",
	"pgdn": "Page Down",
	"crup": "Cursor Up",
	"crdn": "Cursor Down",
	"crlt": "Cursor Left",
	"crrt": "Cursor Right",
	"alttab": "Alt-Tab",
	"esc": "Escape",
	"f1": "F1",
	"f2": "F2",
	"f3": "F3",
	"f4": "F4",
	"f5": "F5",
	"f6": "F6",
	"f7": "F7",
	"f8": "F8",
	"f9": "F9",
	"f10": "F10",
	"f11": "F11",
	"f12": "F12",
    };

    // Customize "forward swipe" and the four on-screen buttons
    this.selectorChoices = [];
    this.selectorChoices.push({label: this.displayMapping[""], value: ""});
    this.selectorChoices.push({label: this.displayMapping["enter"], value: "enter"});
    this.selectorChoices.push({label: this.displayMapping["pgup"], value: "pgup"});
    this.selectorChoices.push({label: this.displayMapping["pgdn"], value: "pgdn"});
    this.selectorChoices.push({label: this.displayMapping["crup"], value: "crup"});
    this.selectorChoices.push({label: this.displayMapping["crdn"], value: "crdn"});
    this.selectorChoices.push({label: this.displayMapping["crlt"], value: "crlt"});
    this.selectorChoices.push({label: this.displayMapping["crrt"], value: "crrt"});
    this.selectorChoices.push({label: this.displayMapping["alttab"], value: "alttab"});
    this.selectorChoices.push({label: this.displayMapping["esc"], value: "esc"});
    this.selectorChoices.push({label: this.displayMapping["f1"], value: "f1"});
    this.selectorChoices.push({label: this.displayMapping["f2"], value: "f2"});
    this.selectorChoices.push({label: this.displayMapping["f3"], value: "f3"});
    this.selectorChoices.push({label: this.displayMapping["f4"], value: "f4"});
    this.selectorChoices.push({label: this.displayMapping["f5"], value: "f5"});
    this.selectorChoices.push({label: this.displayMapping["f6"], value: "f6"});
    this.selectorChoices.push({label: this.displayMapping["f7"], value: "f7"});
    this.selectorChoices.push({label: this.displayMapping["f8"], value: "f8"});
    this.selectorChoices.push({label: this.displayMapping["f9"], value: "f9"});
    this.selectorChoices.push({label: this.displayMapping["f10"], value: "f10"});
    this.selectorChoices.push({label: this.displayMapping["f11"], value: "f11"});
    this.selectorChoices.push({label: this.displayMapping["f12"], value: "f12"});

    // Setup "forward-swipe" action
    this.ForwardModel = {value: Main.specialKeys["forwardEvent"].code, choices: this.selectorChoices};
    this.forwardswipeSelectorAttributes = {label: 'Fwd swipe key', modelProperty:'value' };
    this.controller.setupWidget("forwardSelector", this.forwardswipeSelectorAttributes, this.ForwardModel);

    // Setup the preferences for the four on-screen buttons
    this.button1Model = {value: Main.specialKeys["button_1_el"].code,
			 choices: this.selectorChoices};
    this.button2Model = {value: Main.specialKeys["button_2_el"].code,
			 choices: this.selectorChoices};
    this.button3Model = {value: Main.specialKeys["button_3_el"].code,
			 choices: this.selectorChoices};
    this.button4Model = {value: Main.specialKeys["button_4_el"].code,
			 choices: this.selectorChoices};

    this.button1SelectorAttributes = {label: '1st onscr btn', modelProperty:'value' };
    this.button2SelectorAttributes = {label: '2nd onscr btn', modelProperty:'value' };
    this.button3SelectorAttributes = {label: '3rd onscr btn', modelProperty:'value' };
    this.button4SelectorAttributes = {label: '4th onscr btn', modelProperty:'value' };

    this.controller.setupWidget("button1Selector",
				this.button1SelectorAttributes,
				this.button1Model);
    this.controller.setupWidget("button2Selector",
				this.button2SelectorAttributes,
				this.button2Model);
    this.controller.setupWidget("button3Selector",
				this.button3SelectorAttributes,
				this.button3Model);
    this.controller.setupWidget("button4Selector",
				this.button4SelectorAttributes,
				this.button4Model);

    // Setup volume keys
    this.volumeUpModel = {value: Main.specialKeys["volume_up"].code, choices: this.selectorChoices};
    this.volumeDnModel = {value: Main.specialKeys["volume_down"].code, choices: this.selectorChoices};
    this.volumeUpSelectorAttributes = {label: 'Volume up', modelProperty:'value' };
    this.volumeDnSelectorAttributes = {label: 'Volume dn', modelProperty:'value' };
    this.controller.setupWidget("volumeUpSelector",
				this.volumeUpSelectorAttributes,
				this.volumeUpModel);
    this.controller.setupWidget("volumeDnSelector",
				this.volumeDnSelectorAttributes,
				this.volumeDnModel);

    this.changeDebugHandler = this.changeDebug.bindAsEventListener(this);
    this.changeEnableVolumekeysHandler = this.changeEnableVolumekeys.bindAsEventListener(this);
    this.changeInhibitPowerOffHandler = this.changeInhibitPowerOff.bindAsEventListener(this);
    this.useMouseHandler = this.changeUseMouse.bindAsEventListener(this);
    this.forwardActionHandler = this.changeForwardAction.bindAsEventListener(this);
    this.button1ActionHandler = this.changeButton1Action.bindAsEventListener(this);
    this.button2ActionHandler = this.changeButton2Action.bindAsEventListener(this);
    this.button3ActionHandler = this.changeButton3Action.bindAsEventListener(this);
    this.button4ActionHandler = this.changeButton4Action.bindAsEventListener(this);
    this.volumeUpActionHandler = this.changeVolumeUpAction.bindAsEventListener(this);
    this.volumeDnActionHandler = this.changeVolumeDnAction.bindAsEventListener(this);
}

PreferencesAssistant.prototype.changeForwardAction = function(event) {
    // event triggerd by user: value changed
    Main.specialKeys["forwardEvent"].code = this.ForwardModel.value;
    Main.specialKeys["forwardEvent"].label = this.displayMapping[this.ForwardModel.value];
}

PreferencesAssistant.prototype.changeButton1Action = function(event) {
    Main.specialKeys["button_1_el"].code = this.button1Model.value;
    Main.specialKeys["button_1_el"].label = this.displayMapping[this.button1Model.value];
}

PreferencesAssistant.prototype.changeButton2Action = function(event) {
    Main.specialKeys["button_2_el"].code = this.button2Model.value;
    Main.specialKeys["button_2_el"].label = this.displayMapping[this.button2Model.value];
}

PreferencesAssistant.prototype.changeButton3Action = function(event) {
    Main.specialKeys["button_3_el"].code = this.button3Model.value;
    Main.specialKeys["button_3_el"].label = this.displayMapping[this.button3Model.value];
}

PreferencesAssistant.prototype.changeButton4Action = function(event) {
    Main.specialKeys["button_4_el"].code = this.button4Model.value;
    Main.specialKeys["button_4_el"].label = this.displayMapping[this.button4Model.value];
}

PreferencesAssistant.prototype.changeVolumeUpAction = function(event) {
    Main.specialKeys["volume_up"].code = this.volumeUpModel.value;
    Main.specialKeys["volume_up"].label = this.displayMapping[this.volumeUpModel.value];
}

PreferencesAssistant.prototype.changeVolumeDnAction = function(event) {
    Main.specialKeys["volume_down"].code = this.volumeDnModel.value;
    Main.specialKeys["volume_down"].label = this.displayMapping[this.volumeDnModel.value];
}

PreferencesAssistant.prototype.changeDebug = function(event) {
    // event triggerd by user: value changed
    Mojo.Log.info("Preferences changeDebug; value = ", this.debugToggleModel.value);
    Main.debugEnable = this.debugToggleModel.value;
    Mojo.Log.info("Main.debugEnable = ", Main.debugEnable);
    if (Main.debugEnable === false) {
	this.controller.get('log-output').innerHTML = "";
    }
}

PreferencesAssistant.prototype.changeEnableVolumekeys = function(event) {
    // event triggerd by user: value changed
    this.logInfo("Preferences changEnableVolumekeys; value = ", this.enableVolumekeysModel.value);
    Main.enableVolumekeys = this.enableVolumekeysModel.value;
    this.logInfo("Main.enableVolumekeys = ", Main.enableVolumekeys);
}

PreferencesAssistant.prototype.changeUseMouse = function(event) {
    // event triggerd by user: value changed
    this.logInfo("Preferences changeUseMouse; value = ", this.useMouseModel.value);
    Main.useMouse = this.useMouseModel.value;
    this.logInfo("Main.useMouse = ", Main.useMouse);
}

PreferencesAssistant.prototype.changeInhibitPowerOff = function(event) {
    // event triggerd by user: value changed
    var that = this; // scoping of this
    this.logInfo("Preferences changeInhibitPowerOff; value = ", this.inhibitPowerOffModel.value);
    if (this.inhibitPowerOffModel.value === true) {
	this.controller.serviceRequest("palm://com.palm.power/com/palm/power", {
	    method: "activityStart",
	    parameters: {
		id: "com.henschkowski.app.bluetoothpresenter",
		duration_ms: 900000
	    },
	    onSuccess: function() { that.logInfo("power activate OK");},
	    onFailure: function() { that.logInfo("power activate NOK");}
	});
    } else {
	this.controller.serviceRequest("palm://com.palm.power/com/palm/power", {
	    method: "activityEnd",
	    parameters: {
		id: "com.henschkowski.app.bluetoothpresenter",
	    },
	    onSuccess: function() { that.logInfo("power deactivate OK");},
	    onFailure: function() { that.logInfo("power deactivate NOK");}
	});
    }
}

PreferencesAssistant.prototype.activate = function(event) {
    if (Main.debugEnable === false) {
	this.controller.get('log-output').innerHTML = "";
    }
    this.controller.listen("debugToggle", Mojo.Event.propertyChange, this.changeDebugHandler);
    this.controller.listen("forwardSelector", Mojo.Event.propertyChange, this.forwardActionHandler);
    this.controller.listen("button1Selector", Mojo.Event.propertyChange, this.button1ActionHandler);
    this.controller.listen("button2Selector", Mojo.Event.propertyChange, this.button2ActionHandler);
    this.controller.listen("button3Selector", Mojo.Event.propertyChange, this.button3ActionHandler);
    this.controller.listen("button4Selector", Mojo.Event.propertyChange, this.button4ActionHandler);
    this.controller.listen("volumeUpSelector", Mojo.Event.propertyChange, this.volumeUpActionHandler);
    this.controller.listen("volumeDnSelector", Mojo.Event.propertyChange, this.volumeDnActionHandler);
    this.controller.listen("enableVolumekeys", Mojo.Event.propertyChange, this.changeEnableVolumekeysHandler);
    this.controller.listen("inhibitPowerOff", Mojo.Event.propertyChange, this.changeInhibitPowerOffHandler);
    this.controller.listen("useMouse", Mojo.Event.propertyChange, this.useMouseHandler);
}

PreferencesAssistant.prototype.deactivate = function(event) {
    // save preferences to cookie
    var specialKeysCookie = new Mojo.Model.Cookie('specialkeys');
    specialKeysCookie.put(Main.specialKeys);
}

PreferencesAssistant.prototype.cleanup = function(event) {
    this.controller.stopListening("debugToggle", Mojo.Event.propertyChange,
				  this.changeDebugHandler);
    this.controller.stopListening("forwardSelector", Mojo.Event.propertyChange,
				  this.changeForwardAction);
    this.controller.stopListening("button1Selector", Mojo.Event.propertyChange,
    				  this.changeButton1Action);
    this.controller.stopListening("button2Selector", Mojo.Event.propertyChange,
    				  this.changeButton2Action);
    this.controller.stopListening("button3Selector", Mojo.Event.propertyChange,
    				  this.changeButton3Action);
    this.controller.stopListening("button4Selector", Mojo.Event.propertyChange,
    				  this.changeButton4Action);
    this.controller.stopListening("volumeUpSelector", Mojo.Event.propertyChange,
    				  this.volumeUpActionHandler);
    this.controller.stopListening("volumeDnSelector", Mojo.Event.propertyChange,
    				  this.volumeDnActionHandler);
    this.controller.stopListening("enableVolumekeys", Mojo.Event.propertyChange,
				  this.changeEnableVolumekeysHandler);
    this.controller.stopListening("inhibitPowerOff", Mojo.Event.propertyChange,
				  this.changeInhibitPowerOffHandler);
    this.controller.stopListening("useMouse", Mojo.Event.propertyChange,
				  this.useMouseHandler);

}

PreferencesAssistant.prototype.logInfo = function(logText) {
    if(Main.debugEnable === true) {
	this.controller.get('log-output').innerHTML = "" +
	    this.logOutputNum++ + ": " + logText +
	    "
" +
	    this.controller.get('log-output').innerHTML +
	    "

";
    }
}

<|endoftext|>


<commit_before>var Hypergraph = (function(builder) {

	/**
	 * Whether the animation is playing.
	 *
	 * @type {boolean}
	 * @private
	 */
	var _isPlaying = false;

	/**
	 * The animations interval.
	 *
	 * @type {number}
	 * @private
	 */
	var _velocity = 2500;

	/**
	 * The lower threshold to display/hide subgraphs.
	 *
	 * @type {number}
	 * @private
	 */
	var _threshold = 6.25;

	/**
	 * If an animation is in progress, this is the current interval.
	 *
	 * @type {number}
	 * @private
	 */
	var _currentInterval = 0;

	/**
	 * Interval ID which can be used to clear the interval.
	 *
	 * @type {number}
	 * @private
	 */
	var _interval = null;

	/**
	 * This is the maximum number of intervals in the animation.
	 *
	 * @type {number}
	 * @private
	 */
	var _noOfIntervals = 0;

	var _graphBuilder = null;

	/**
	 * Loads JSON
	 */
	function load() {
		var xhr = new XMLHttpRequest();
		xhr.open('GET', 'data_arr.json', true);

		xhr.onload = function() {
			if (this.status >= 200 && this.status < 400) {
				var data = JSON.parse(this.response);

				data.forEach(function(subgraph) {
					var frequency = subgraph[subgraph.length - 1];;
					_noOfIntervals = frequency.intervals.length > _noOfIntervals ? frequency.intervals.length : _noOfIntervals;
				});

				_graphBuilder.buildFromArray(data);
				draw();
			}
		};

		xhr.send();
	}

	function draw() {
		var nodes = _graphBuilder.getNodes();
		var links = _graphBuilder.getLinks();
	}

	/**
	 * Starts the animation.
	 */
	function play() {
		if (!_isPlaying) {
			_isPlaying = !_isPlaying;

			_interval = window.setInterval(function() { console.info('Interval Step! ' + _velocity); }, _velocity);
		}
	}

	/**
	 * Pauses the animation.
	 */
	function pause() {
		if (_isPlaying) {
			_isPlaying = !_isPlaying;

			window.clearInterval(_interval);
			_interval = null;
		}
	}

	/**
	 * Sets a new velocity and restarts animation interval if in progress.
	 *
	 * @param velocity
	 * @returns {number}
	 */
	function changeVelocity(velocity) {
		_velocity = velocity;

		if (_isPlaying) {
			pause();
		}

		play();

		return _velocity;
	}

	return {
		start: load,
		isPlaying: function() { return _isPlaying; },
		play: play,
		pause: pause,
		changeVelocity: changeVelocity,
		setThreshold: function(threshold) { return _threshold = threshold; }
	}
})(GraphBuilder);<commit_msg>Only restart interval if it wasn't paused<commit_after>var Hypergraph = (function(builder) {

	/**
	 * Whether the animation is playing.
	 *
	 * @type {boolean}
	 * @private
	 */
	var _isPlaying = false;

	/**
	 * The animations interval.
	 *
	 * @type {number}
	 * @private
	 */
	var _velocity = 2500;

	/**
	 * The lower threshold to display/hide subgraphs.
	 *
	 * @type {number}
	 * @private
	 */
	var _threshold = 6.25;

	/**
	 * If an animation is in progress, this is the current interval.
	 *
	 * @type {number}
	 * @private
	 */
	var _currentInterval = 0;

	/**
	 * Interval ID which can be used to clear the interval.
	 *
	 * @type {number}
	 * @private
	 */
	var _interval = null;

	/**
	 * This is the maximum number of intervals in the animation.
	 *
	 * @type {number}
	 * @private
	 */
	var _noOfIntervals = 0;

	var _graphBuilder = GraphBuilder;

	/**
	 * Loads JSON
	 */
	function load(file) {

		if (!file) {
			file = 'data.json';
		}

		var xhr = new XMLHttpRequest();
		xhr.open('GET', file, true);

		xhr.onload = function() {
			if (this.status >= 200 && this.status < 400) {
				var data = JSON.parse(this.response);

				data.forEach(function(subgraph) {
					var frequency = subgraph[subgraph.length - 1];;
					_noOfIntervals = frequency.intervals.length > _noOfIntervals ? frequency.intervals.length : _noOfIntervals;
				});

				_graphBuilder.buildFromArray(data);
				draw();
			}
		};

		xhr.send();
	}

	function draw() {
		var nodes = _graphBuilder.getNodes();
		var links = _graphBuilder.getLinks();
	}

	/**
	 * Starts the animation.
	 */
	function play() {
		if (!_isPlaying) {
			_isPlaying = !_isPlaying;

			_interval = window.setInterval(function() { console.info('Interval Step! ' + _velocity); }, _velocity);
		}
	}

	/**
	 * Pauses the animation.
	 */
	function pause() {
		if (_isPlaying) {
			_isPlaying = !_isPlaying;

			window.clearInterval(_interval);
			_interval = null;
		}
	}

	/**
	 * Sets a new velocity and restarts animation interval if in progress.
	 *
	 * @param velocity
	 * @returns {number}
	 */
	function changeVelocity(velocity) {
		_velocity = velocity;

		if (_isPlaying) {
			pause();
			play();
		}

		return _velocity;
	}

	return {
		start: load,
		isPlaying: function() { return _isPlaying; },
		play: play,
		pause: pause,
		changeVelocity: changeVelocity,
		setThreshold: function(threshold) { return _threshold = threshold; }
	}
})(GraphBuilder);<|endoftext|>