<commit_before>define([
    'specimenTools/glyphTable/GlyphTables'
  , 'specimenTools/loadFonts'
  , 'specimenTools/PubSub'
  , 'specimenTools/fontControl/FamilyControlInterface'
  , 'specimenTools/fontData/FontsData'
  , 'specimenTools/fontData/GenericFontDataWidget'
  , 'specimenTools/fontData/WebfontProvider'
  , 'specimenTools/fontData/CurrentWebFontWidget'
  , 'specimenTools/fontControl/TypeTesterWidget'
], function(
    GlyphTables
  , loadFonts
  , PubSub
  , FamilyControlInterface
  , FontsData
  , GenericFontDataWidget
  , WebFontProvider
  , CurrentWebFontWidget
  , TypeTesterWidget
) {
    "use strict";

    function main(document, fontFiles) {
        var options = {
                glyphTables: {
                    glyphTable: {
                        glyphClass: 'mdlfs-glyph-table__glyph'
                      , glyphActiveClass: 'mdlfs-glyph-table__glyph_active'
                    }
                }
              , familyControlInterface: {
                    italicSwitchContainerClasses: ['mdl-switch', 'mdl-js-switch', 'mdl-js-ripple-effect', 'mdlfs-family-switcher__italic-switch']
                  , italicSwitchCheckboxClasses: ['mdl-switch__input']
                  , italicSwitchLabelClasses: ['mdl-switch__label']
                  , setItalicSwitch: function setItalicSwitch(italicSwitch, enabled, checked) {
                        var fallback;
                        if(!italicSwitch.container.MaterialSwitch) {
                            fallback = this.constructor.defaultOptions.setItalicSwitch;
                            fallback.call(this, italicSwitch, enabled, checked);
                            return;
                        }
                        italicSwitch.container.MaterialSwitch[enabled ? 'enable' : 'disable']();
                        italicSwitch.container.MaterialSwitch[checked ? 'on' : 'off']();
                    }
                  , weightButtonClasses: 'mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--raised mdlfs-family-switcher__button'
                  , weightButtonActiveClass: 'mdl-button--colored'
                }
              , typeTesterWidget: {
                      fontSizeControlsClass: 'mdlfs-type-tester__font-size'
                    , fontSizeIndicatorClass: 'mdlfs-type-tester__font-size-indicator'
                    , optionalFeaturesControlsClass: 'mdlfs-type-tester__features--optional'
                    , defaultFeaturesControlsClass: 'mdlfs-type-tester__features--default'
                    , contentContainerClass: 'mdlfs-type-tester__content'
                    , fontSizeRangeInputClasses: 'mdl-slider mdl-js-slider'
                    , setFontSizeToInput: function(input, value) {
                            if('MaterialSlider' in input)
                                input.MaterialSlider.change(value);
                            else
                                input.value = value;
                      }

                     , optionalFeatureButtonClasses:  'mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--raised mdlfs-type-tester__feature-button'
                     , defaultFeatureButtonClasses: 'mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--raised mdlfs-type-tester__feature-button'
                     , featureButtonActiveClass: 'mdl-button--colored'

                }
              , FontData: {}
            }
          , pubsub = new PubSub()
          , factories, i, l , container, Constructor, instance, className, args
          , j, ll, containersForClass
          , containers = []
          , fontsData = new FontsData(pubsub, {useLaxDetection: true})
          , webFontProvider = new WebFontProvider(window, pubsub, fontsData)
          ;

        factories = [
            ['mdlfs-family-switcher', FamilyControlInterface, fontsData, options.familyControlInterface]
          , ['mdlfs-glyph-table', GlyphTables, options.glyphTables]
          , ['mdlfs-font-data', GenericFontDataWidget, fontsData,  options.FontData]
          , ['mdlfs-current-font', CurrentWebFontWidget, webFontProvider]
          , ['mdlfs-type-tester', TypeTesterWidget, fontsData, options.typeTesterWidget]
        ];

        for(i=0,l=factories.length;i<l;i++) {
            className = factories[i][0];
            containersForClass = document.getElementsByClassName(className);
            if(!containersForClass.length)
                continue;
            Constructor = factories[i][1];
            for(j=0,ll=containersForClass.length;j<ll;j++) {
                container = containersForClass[j];
                containers.push(container);
                args = [container, pubsub];
                Array.prototype.push.apply(args, factories[i].slice(2));
                // this way we can call the Constructor with a
                // dynamic arguments list, i.e. by circumvent the `new`
                // keyword via Object.create.
                instance = Object.create(Constructor.prototype);
                Constructor.apply(instance, args);
            }
        }

        pubsub.subscribe('allFontsLoaded', function() {
            // Init newly built MDL elements
            // componentHandler from material design lit is expected to be loaded
            // by now, though, there's no guarantee for this!
            // maybe mdl has an AMD interface? or at least a callback when
            // it is loaded.
            componentHandler.upgradeElements(containers);
            pubsub.publish('activateFont', 0);
        });

        loadFonts(fontFiles, pubsub);
    }

    return main;
});
<commit_msg>Rename modules following the changes in specimenTools<commit_after>define([
    'specimenTools/loadFonts'
  , 'specimenTools/services/PubSub'
  , 'specimenTools/services/FontsData'
  , 'specimenTools/services/WebfontProvider'
  , 'specimenTools/widgets/GlyphTables'
  , 'specimenTools/widgets/FamilyChooser'
  , 'specimenTools/widgets/GenericFontData'
  , 'specimenTools/widgets/CurrentWebFont'
  , 'specimenTools/widgets/TypeTester'
], function(
    loadFonts
  , PubSub
  , FontsData
  , WebFontProvider
  , GlyphTables
  , FamilyChooser
  , GenericFontData
  , CurrentWebFont
  , TypeTester
) {
    "use strict";

    function main(document, fontFiles) {
        var options = {
                glyphTables: {
                    glyphTable: {
                        glyphClass: 'mdlfs-glyph-table__glyph'
                      , glyphActiveClass: 'mdlfs-glyph-table__glyph_active'
                    }
                }
              , familyControlInterface: {
                    italicSwitchContainerClasses: ['mdl-switch', 'mdl-js-switch', 'mdl-js-ripple-effect', 'mdlfs-family-switcher__italic-switch']
                  , italicSwitchCheckboxClasses: ['mdl-switch__input']
                  , italicSwitchLabelClasses: ['mdl-switch__label']
                  , setItalicSwitch: function setItalicSwitch(italicSwitch, enabled, checked) {
                        var fallback;
                        if(!italicSwitch.container.MaterialSwitch) {
                            fallback = this.constructor.defaultOptions.setItalicSwitch;
                            fallback.call(this, italicSwitch, enabled, checked);
                            return;
                        }
                        italicSwitch.container.MaterialSwitch[enabled ? 'enable' : 'disable']();
                        italicSwitch.container.MaterialSwitch[checked ? 'on' : 'off']();
                    }
                  , weightButtonClasses: 'mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--raised mdlfs-family-switcher__button'
                  , weightButtonActiveClass: 'mdl-button--colored'
                }
              , typeTesterWidget: {
                      fontSizeControlsClass: 'mdlfs-type-tester__font-size'
                    , fontSizeIndicatorClass: 'mdlfs-type-tester__font-size-indicator'
                    , optionalFeaturesControlsClass: 'mdlfs-type-tester__features--optional'
                    , defaultFeaturesControlsClass: 'mdlfs-type-tester__features--default'
                    , contentContainerClass: 'mdlfs-type-tester__content'
                    , fontSizeRangeInputClasses: 'mdl-slider mdl-js-slider'
                    , setFontSizeToInput: function(input, value) {
                            if('MaterialSlider' in input)
                                input.MaterialSlider.change(value);
                            else
                                input.value = value;
                      }

                     , optionalFeatureButtonClasses:  'mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--raised mdlfs-type-tester__feature-button'
                     , defaultFeatureButtonClasses: 'mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--raised mdlfs-type-tester__feature-button'
                     , featureButtonActiveClass: 'mdl-button--colored'

                }
              , featureDisplayWidget: {
                    featureItemClasses: 'mdl-cell mdl-cell--4-col mdlfs-feature-display__item'
                }
              , FontData: {}
            }
          , pubsub = new PubSub()
          , factories, i, l , container, Constructor, instance, className, args
          , j, ll, containersForClass
          , containers = []
          , fontsData = new FontsData(pubsub, {useLaxDetection: true})
          , webFontProvider = new WebFontProvider(window, pubsub, fontsData)
          ;

        factories = [
            ['mdlfs-family-switcher', FamilyChooser, fontsData, options.familyControlInterface]
          , ['mdlfs-glyph-table', GlyphTables, options.glyphTables]
          , ['mdlfs-font-data', GenericFontData, fontsData,  options.FontData]
          , ['mdlfs-current-font', CurrentWebFont, webFontProvider]
          , ['mdlfs-type-tester', TypeTester, fontsData, options.typeTesterWidget]
        ];

        for(i=0,l=factories.length;i<l;i++) {
            className = factories[i][0];
            containersForClass = document.getElementsByClassName(className);
            if(!containersForClass.length)
                continue;
            Constructor = factories[i][1];
            for(j=0,ll=containersForClass.length;j<ll;j++) {
                container = containersForClass[j];
                containers.push(container);
                args = [container, pubsub];
                Array.prototype.push.apply(args, factories[i].slice(2));
                // this way we can call the Constructor with a
                // dynamic arguments list, i.e. by circumvent the `new`
                // keyword via Object.create.
                instance = Object.create(Constructor.prototype);
                Constructor.apply(instance, args);
            }
        }

        pubsub.subscribe('allFontsLoaded', function() {
            // Init newly built MDL elements
            // componentHandler from material design lit is expected to be loaded
            // by now, though, there's no guarantee for this!
            // maybe mdl has an AMD interface? or at least a callback when
            // it is loaded.
            componentHandler.upgradeElements(containers);
            pubsub.publish('activateFont', 0);
        });

        loadFonts(fontFiles, pubsub);
    }

    return main;
});
<|endoftext|>


<commit_before>var note_url = "http://service.sap.com/sap/support/notes/";
var search_url = "https://support.sap.com/content/sap-root/search-result-page.html?search=";

var { ToggleButton } = require("sdk/ui/button/toggle");
var tabs = require("sdk/tabs");
var panels = require("sdk/panel");
var self = require("sdk/self");

var button = ToggleButton({
    id: "sap-search",
    label: "Search SAP",
    icon: {
        "16": "./icon_16.png",
        "32": "./icon_32.png",
        "48": "./icon_48.png",
        "128": "./icon_128.png"
    },
    onChange: handleChange
});

var panel = panels.Panel({
    width: 220,
    height: 140,
    contentURL: self.data.url("search.html"),
    contentScriptFile: self.data.url("search.js"),
    contentStyleFile: self.data.url("styles.css"),
    onHide: handleHide
});

function handleHide() {
    button.state('window', { checked: false });
}

function handleChange(state) {
    if (state.checked) {
        panel.show({
            position: button
        });
    }
}

panel.on("show", function() {
    panel.port.emit("show");
});

panel.port.on("search", function (text) {
    console.log(text);
    if (isNaN(text))
        search(text);
    else
        openNote(text);
    panel.hide();
});

function openNote(noteNumber) {
    var note = note_url + noteNumber;
    tabs.open(note);
}

function search(searchText) {
    var terms = encodeURIComponent(searchText);
    tabs.open(
        search_url + terms + "&_charset=UTF-8"
    );
}
<commit_msg>Remove console print to resolve #1<commit_after>var note_url = "http://service.sap.com/sap/support/notes/";
var search_url = "https://support.sap.com/content/sap-root/search-result-page.html?search=";

var { ToggleButton } = require("sdk/ui/button/toggle");
var tabs = require("sdk/tabs");
var panels = require("sdk/panel");
var self = require("sdk/self");

var button = ToggleButton({
    id: "sap-search",
    label: "Search SAP",
    icon: {
        "16": "./icon_16.png",
        "32": "./icon_32.png",
        "48": "./icon_48.png",
        "128": "./icon_128.png"
    },
    onChange: handleChange
});

var panel = panels.Panel({
    width: 220,
    height: 140,
    contentURL: self.data.url("search.html"),
    contentScriptFile: self.data.url("search.js"),
    contentStyleFile: self.data.url("styles.css"),
    onHide: handleHide
});

function handleHide() {
    button.state('window', { checked: false });
}

function handleChange(state) {
    if (state.checked) {
        panel.show({
            position: button
        });
    }
}

panel.on("show", function() {
    panel.port.emit("show");
});

panel.port.on("search", function (text) {
    if (isNaN(text))
        search(text);
    else
        openNote(text);
    panel.hide();
});

function openNote(noteNumber) {
    var note = note_url + noteNumber;
    tabs.open(note);
}

function search(searchText) {
    var terms = encodeURIComponent(searchText);
    tabs.open(
        search_url + terms + "&_charset=UTF-8"
    );
}
<|endoftext|>


<commit_before>/** @babel */

import {Disposable, CompositeDisposable} from 'atom'

const ViewURI = 'atom://deprecation-cop'
let DeprecationCopView

class DeprecationCopPackage {
  activate () {
    this.disposables = new CompositeDisposable()
    this.disposables.add(atom.workspace.addOpener((uri) => {
      if (uri === ViewURI) {
        return this.deserializeDeprecationCopView({uri})
      }
    }))
    this.disposables.add(atom.commands.add('atom-workspace', 'deprecation-cop:view', () => {
      atom.workspace.open(ViewURI)
    }))
  }

  deactivate () {
    this.disposables.dispose()
    const pane = atom.workspace.paneForURI(ViewURI)
    if (pane) {
      pane.destroyItem(pane.itemForURI(ViewURI))
    }
  }

  deserializeDeprecationCopView (state) {
    if (!DeprecationCopView) {
      DeprecationCopView = require('./deprecation-cop-view')
    }
    return new DeprecationCopView(state)
  }

  consumeStatusBar (statusBar) {
    const DeprecationCopStatusBarView = require('./deprecation-cop-status-bar-view')
    const statusBarView = new DeprecationCopStatusBarView()
    const statusBarTile = statusBar.addRightTile({item: statusBarView, priority: 150})
    this.disposables.add(new Disposable(() => { statusBarView.destroy() }))
    this.disposables.add(new Disposable(() => { statusBarTile.destroy() }))
  }
}

const instance = new DeprecationCopPackage()
export default instance
<commit_msg>Don't defer requires unnecessarily<commit_after>const {Disposable, CompositeDisposable} = require('atom')
const DeprecationCopView = require('./deprecation-cop-view')
const DeprecationCopStatusBarView = require('./deprecation-cop-status-bar-view')
const ViewURI = 'atom://deprecation-cop'

class DeprecationCopPackage {
  activate () {
    this.disposables = new CompositeDisposable()
    this.disposables.add(atom.workspace.addOpener((uri) => {
      if (uri === ViewURI) {
        return this.deserializeDeprecationCopView({uri})
      }
    }))
    this.disposables.add(atom.commands.add('atom-workspace', 'deprecation-cop:view', () => {
      atom.workspace.open(ViewURI)
    }))
  }

  deactivate () {
    this.disposables.dispose()
    const pane = atom.workspace.paneForURI(ViewURI)
    if (pane) {
      pane.destroyItem(pane.itemForURI(ViewURI))
    }
  }

  deserializeDeprecationCopView (state) {
    return new DeprecationCopView(state)
  }

  consumeStatusBar (statusBar) {
    const statusBarView = new DeprecationCopStatusBarView()
    const statusBarTile = statusBar.addRightTile({item: statusBarView, priority: 150})
    this.disposables.add(new Disposable(() => { statusBarView.destroy() }))
    this.disposables.add(new Disposable(() => { statusBarTile.destroy() }))
  }
}

module.exports = new DeprecationCopPackage()
<|endoftext|>


<commit_before>'use babel';
/* globals atom */

import { CompositeDisposable } from 'atom';
import helpers from 'atom-linter';
import { parseString } from './xml2js-promise';
import _ from 'underscore';

export default {
  activate: () => {
    require('atom-package-deps').install('linter-cflint', true);
    atom.config.unset('linter-cflint.cflintPath');
    atom.config.unset('linter-cflint.javaPath');
    this.subscriptions = new CompositeDisposable;
  },

  deactivate: () => {
    return this.subscriptions.dispose();
  },

  provideLinter: () => {
    return {
      name: 'cflint',
      grammarScopes: [
        'text.html.cfml',
        'source.cfscript.embedded',
        'punctuation.definition.tag.cfml',
        'source.cfscript',
      ],
      scope: 'file',
      lintOnFly: true,
      lint: (textEditor) => {
        return new Promise(resolve => {
          require('find-java-home')((err, home) => {
            if (err) {
              if (!this.errorDisplayed) {
                atom.notifications.addError('JAVA_HOME is unset or incorrectly setup: ' + err, {
                  dismissable: true,
                });
                this.errorDisplayed = true;
              }
              return [];
            }
            const filePath = textEditor.getPath();
            const cflintPath = atom.packages.resolvePackagePath('linter-cflint').trim() + '/bin/CFLint-0.5.0-all.jar';
            const javaPath = home.trim() + '/bin/java';
            const javaArgs = [ '-jar', cflintPath, '-q', '-stdout', '-stdin', '-xml'];
            helpers.exec(javaPath, javaArgs, {
              stdin: textEditor.getText(),
              stdio: 'pipe',
              encoding: 'utf8',
              throwOnStdErr: false,
            })
            .then(xmlResult => {
              let lintXML = xmlResult;
              if (lintXML.trim()[0] !== '<') {
                lintXML = lintXML.split('\n').slice(1).join('\n');
              }
              return parseString(lintXML);
            })
            .then(result => {
              const messages =
                _.chain(result.issues.issue)
                .map(issue => {
                  const line = parseInt(issue.location[0].$.line, 10);
                  return {
                    filePath: filePath,
                    type: issue.$.severity in ['FATAL', 'CRITICAL', 'ERROR'] ? 'Error' : 'Warning',
                    text: issue.location[0].$.message,
                    line: parseInt(issue.location[0].$.line, 10) - 1,
                    range: helpers.rangeFromLineNumber(textEditor, line - 1, issue.location[0].$.column),
                  };
                })
                .sortBy(issue => issue.line)
                .value();
              resolve(messages);
            });
          });
        });
      },
    };
  },
};
<commit_msg>Allow config of java.exe path<commit_after>'use babel';
/* globals atom */

import { CompositeDisposable } from 'atom';
import helpers from 'atom-linter';
import { parseString } from './xml2js-promise';
import _ from 'underscore';

export default {
  config: {
    javaPath: {
      type: 'string',
      'default': '',
      description: 'Path to the Java 7+ executable (JRE or JDK)',
    },
  },

  activate: () => {
    require('atom-package-deps').install('linter-cflint', true);
    atom.config.unset('linter-cflint.cflintPath');
    this.subscriptions = new CompositeDisposable;
  },

  deactivate: () => {
    return this.subscriptions.dispose();
  },

  provideLinter: () => {
    return {
      name: 'cflint',
      grammarScopes: [
        'text.html.cfml',
        'source.cfscript.embedded',
        'punctuation.definition.tag.cfml',
        'source.cfscript',
      ],
      scope: 'file',
      lintOnFly: true,
      lint: (textEditor) => {
        return new Promise(resolve => {
          require('find-java-home')((err, home) => {
            let javaPath = atom.config.get('linter-cflint.javaPath');
            if (!javaPath) {
              if (err) {
                if (!this.errorDisplayed) {
                  atom.notifications.addError('JAVA_HOME is unset or incorrectly setup: ' + err, {
                    dismissable: true,
                  });
                  this.errorDisplayed = true;
                }
                return [];
              }
              javaPath = home.trim() + '/bin/java';
            }
            const filePath = textEditor.getPath();
            const cflintPath = atom.packages.resolvePackagePath('linter-cflint').trim() + '/bin/CFLint-0.5.0-all.jar';
            const javaArgs = [ '-jar', cflintPath, '-q', '-stdout', '-stdin', '-xml'];
            helpers.exec(javaPath, javaArgs, {
              stdin: textEditor.getText(),
              stdio: 'pipe',
              encoding: 'utf8',
              throwOnStdErr: false,
            })
            .then(xmlResult => {
              let lintXML = xmlResult;
              if (lintXML.trim()[0] !== '<') {
                lintXML = lintXML.split('\n').slice(1).join('\n');
              }
              return parseString(lintXML);
            })
            .then(result => {
              const messages =
                _.chain(result.issues.issue)
                .map(issue => {
                  const line = parseInt(issue.location[0].$.line, 10);
                  return {
                    filePath: filePath,
                    type: issue.$.severity in ['FATAL', 'CRITICAL', 'ERROR'] ? 'Error' : 'Warning',
                    text: issue.location[0].$.message,
                    line: parseInt(issue.location[0].$.line, 10) - 1,
                    range: helpers.rangeFromLineNumber(textEditor, line - 1, issue.location[0].$.column),
                  };
                })
                .sortBy(issue => issue.line)
                .value();
              resolve(messages);
            });
          });
        });
      },
    };
  },
};
<|endoftext|>


<commit_before>/*#ifndef(UMD)*/
"use strict";
/*#endif*/

var
    /**
     * Shortcut on Array.prototype.slice
     *
     * @type {Function}
     * @private
     */
    _gpfArraySlice = Array.prototype.slice;

if (undefined === Array.prototype.indexOf) {

    // Introduced with JavaScript 1.5
    Array.prototype.indexOf = function (value) {
        var idx = this.length;
        while (idx--) {
            if (this[idx] === value) {
                return idx;
            }
        }
        return -1;
    };

}

if (undefined === Function.prototype.bind) {

    // Introduced with JavaScript 1.8.5
    Function.prototype.bind = function (thisArg) {
        var thisFn = this,
            prependArgs = _gpfArraySlice.apply(arguments, [1]);
        return function() {
            thisFn.apply(thisArg, prependArgs.concat(arguments));
        };
    };

}

if (undefined === Object.defineProperty) {

    /**
     * If possible, defines a read-only property
     *
     * @param {Object} obj
     * @param {String} name
     * @param {*} value
     * @return {Object}
     * @chainable
     */
    gpf.setReadOnlyProperty = function (obj, name, value) {
        obj[name] = value;
        return obj;
    };

} else {

    gpf.setReadOnlyProperty = function (obj, name, value) {
        Object.defineProperty(obj, name, {
            enumerable: true,
            configurable: false,
            writable: false,
            value: value
        });
        return obj;
    };

}
<commit_msg>Improved Array.indexOf<commit_after>/*#ifndef(UMD)*/
"use strict";
/*#endif*/

var
    /**
     * Shortcut on Array.prototype.slice
     *
     * @type {Function}
     * @private
     */
    _gpfArraySlice = Array.prototype.slice;

if (undefined === Array.prototype.indexOf) {

    // Introduced with JavaScript 1.5
    Array.prototype.indexOf = function (searchElement, fromIndex) {
        var idx,
            len = this.length;
        if (undefined !== fromIndex) {
            idx = fromIndex;
        } else {
            fromIndex = 0;
        }
        while (idx < len) {
            if (this[idx] === searchElement) {
                return idx;
            }
        }
        return -1;
    };

}

if (undefined === Function.prototype.bind) {

    // Introduced with JavaScript 1.8.5
    Function.prototype.bind = function (thisArg) {
        var thisFn = this,
            prependArgs = _gpfArraySlice.apply(arguments, [1]);
        return function() {
            thisFn.apply(thisArg, prependArgs.concat(arguments));
        };
    };

}

if (undefined === Object.defineProperty) {

    /**
     * If possible, defines a read-only property
     *
     * @param {Object} obj
     * @param {String} name
     * @param {*} value
     * @return {Object}
     * @chainable
     */
    gpf.setReadOnlyProperty = function (obj, name, value) {
        obj[name] = value;
        return obj;
    };

} else {

    gpf.setReadOnlyProperty = function (obj, name, value) {
        Object.defineProperty(obj, name, {
            enumerable: true,
            configurable: false,
            writable: false,
            value: value
        });
        return obj;
    };

}
<|endoftext|>


<commit_before>/*#ifndef(UMD)*/
"use strict";
/*#endif*/

var
    /**
     * Shortcut on Array.prototype.slice
     *
     * @type {Function}
     * @private
     */
    _gpfArraySlice = Array.prototype.slice;

if (undefined === Array.prototype.every) {

    // Introduced with JavaScript 1.6
    Array.prototype.every = function (callback, thisArg) {
        var len = this.length,
            idx;
        for (idx = 0; idx < len; ++idx) {
            if (!callback.apply(thisArg, [this[idx], idx, this])) {
                return false;
            }
        }
        return true;
    };
}

if (undefined === Array.prototype.forEach) {

    // Introduced with JavaScript 1.6
    Array.prototype.forEach = function (callback, thisArg) {
        var len = this.length,
            idx;
        for (idx = 0; idx < len; ++idx) {
            callback.apply(thisArg, [this[idx], idx, this]);
        }
    };
}

if (undefined === Array.prototype.indexOf) {

    // Introduced with JavaScript 1.5
    Array.prototype.indexOf = function (searchElement, fromIndex) {
        var idx,
            len = this.length;
        if (undefined !== fromIndex) {
            idx = fromIndex;
        } else {
            idx = 0;
        }
        while (idx < len) {
            if (this[idx] === searchElement) {
                return idx;
            }
            ++idx;
        }
        return -1;
    };

}

if (undefined === Array.prototype.map) {

    // Introduced with JavaScript 1.6
    Array.prototype.map = function (callback, thisArg) {
        var len = this.length,
            result = new Array(len),
            idx;
        for (idx = 0; idx < len; ++idx) {
            result[idx] = callback.apply(thisArg, [this[idx], idx, this]);
        }
        return result;
    };

}

if (undefined === Function.prototype.bind) {

    // Introduced with JavaScript 1.8.5
    Function.prototype.bind = function (thisArg) {
        var thisFn = this,
            prependArgs = _gpfArraySlice.apply(arguments, [1]);
        return function() {
            var args = _gpfArraySlice.apply(arguments, [0]);
            thisFn.apply(thisArg, prependArgs.concat(args));
        };
    };

}

// Handling function name properly
if ((function () {
    function functionName() {}
    if (functionName.name !== "functionName") {
        return true;
    } else {
        return false;
    }
})()) {

    Function.prototype.compatibleName = function () {
        // Use simple parsing as a first step
        // TODO leverage JS parser to implement this properly
        var src = "" + this,
            pos = src.indexOf("function"),
            paramList = src.indexOf("(", pos);
        return src.substr(pos + 9, paramList - pos - 9).trim();
    };

} else {

    /**
     * Return function name
     *
     * @returns {String}
     */
    Function.prototype.compatibleName = function () {
        return this.name;
    };

}

if (undefined === Object.defineProperty) {

    /**
     * If possible, defines a read-only property
     *
     * @param {Object} obj
     * @param {String} name
     * @param {*} value
     * @return {Object}
     * @chainable
     */
    gpf.setReadOnlyProperty = function (obj, name, value) {
        obj[name] = value;
        return obj;
    };

} else {

    gpf.setReadOnlyProperty = function (obj, name, value) {
        Object.defineProperty(obj, name, {
            enumerable: true,
            configurable: false,
            writable: false,
            value: value
        });
        return obj;
    };

}

if (undefined === String.prototype.trim) {

    // Introduced with JavaScript 1.8.1
    (function () {
        var rtrim = new RegExp("^[\\s\uFEFF\xA0]+|[\\s\uFEFF\xA0]+$", "g");
        String.prototype.trim = function() {
            return this.replace(rtrim, "");
        };
    }());

}<commit_msg>Fixed issue on compatibleName with comments<commit_after>/*#ifndef(UMD)*/
"use strict";
/*#endif*/

var
    /**
     * Shortcut on Array.prototype.slice
     *
     * @type {Function}
     * @private
     */
    _gpfArraySlice = Array.prototype.slice;

if (undefined === Array.prototype.every) {

    // Introduced with JavaScript 1.6
    Array.prototype.every = function (callback, thisArg) {
        var len = this.length,
            idx;
        for (idx = 0; idx < len; ++idx) {
            if (!callback.apply(thisArg, [this[idx], idx, this])) {
                return false;
            }
        }
        return true;
    };
}

if (undefined === Array.prototype.forEach) {

    // Introduced with JavaScript 1.6
    Array.prototype.forEach = function (callback, thisArg) {
        var len = this.length,
            idx;
        for (idx = 0; idx < len; ++idx) {
            callback.apply(thisArg, [this[idx], idx, this]);
        }
    };
}

if (undefined === Array.prototype.indexOf) {

    // Introduced with JavaScript 1.5
    Array.prototype.indexOf = function (searchElement, fromIndex) {
        var idx,
            len = this.length;
        if (undefined !== fromIndex) {
            idx = fromIndex;
        } else {
            idx = 0;
        }
        while (idx < len) {
            if (this[idx] === searchElement) {
                return idx;
            }
            ++idx;
        }
        return -1;
    };

}

if (undefined === Array.prototype.map) {

    // Introduced with JavaScript 1.6
    Array.prototype.map = function (callback, thisArg) {
        var len = this.length,
            result = new Array(len),
            idx;
        for (idx = 0; idx < len; ++idx) {
            result[idx] = callback.apply(thisArg, [this[idx], idx, this]);
        }
        return result;
    };

}

if (undefined === Function.prototype.bind) {

    // Introduced with JavaScript 1.8.5
    Function.prototype.bind = function (thisArg) {
        var thisFn = this,
            prependArgs = _gpfArraySlice.apply(arguments, [1]);
        return function() {
            var args = _gpfArraySlice.apply(arguments, [0]);
            thisFn.apply(thisArg, prependArgs.concat(args));
        };
    };

}

// Handling function name properly
if ((function () {
    function functionName() {}
    if (functionName.name !== "functionName") {
        return true;
    } else {
        return false;
    }
})()) {

    (function () {
        Function.prototype.compatibleName = function () {
            // Use simple parsing as a first step
            // TODO leverage JS parser to implement this properly
            var src = "" + this,
                pos = src.indexOf("function"),
                paramList = src.indexOf("(", pos);
            return src.substr(pos + 9, paramList - pos - 9)
                    .trim();
        };

    }());

} else {

    /**
     * Return function name
     *
     * @returns {String}
     */
    Function.prototype.compatibleName = function () {
        return this.name;
    };

}

if (undefined === Object.defineProperty) {

    /**
     * If possible, defines a read-only property
     *
     * @param {Object} obj
     * @param {String} name
     * @param {*} value
     * @return {Object}
     * @chainable
     */
    gpf.setReadOnlyProperty = function (obj, name, value) {
        obj[name] = value;
        return obj;
    };

} else {

    gpf.setReadOnlyProperty = function (obj, name, value) {
        Object.defineProperty(obj, name, {
            enumerable: true,
            configurable: false,
            writable: false,
            value: value
        });
        return obj;
    };

}

if (undefined === String.prototype.trim) {

    // Introduced with JavaScript 1.8.1
    (function () {
        var rtrim = new RegExp("^[\\s\uFEFF\xA0]+|[\\s\uFEFF\xA0]+$", "g");
        String.prototype.trim = function() {
            return this.replace(rtrim, "");
        };
    }());

}<|endoftext|>


<commit_before>'use strict';

// For now, we're not using babel or ES6 features like `let` and `const` in
// this file, because `apm` requires this file directly in order to pre-warm
// Atom's compile-cache when installing or updating packages, using an older
// version of node.js

const path = require('path');
const fs = require('fs-plus');
const sourceMapSupport = require('@atom/source-map-support');

const PackageTranspilationRegistry = require('./package-transpilation-registry');
let CSON = null;

const packageTranspilationRegistry = new PackageTranspilationRegistry();

const COMPILERS = {
  '.js': packageTranspilationRegistry.wrapTranspiler(require('./babel')),
  '.ts': packageTranspilationRegistry.wrapTranspiler(require('./typescript')),
  '.tsx': packageTranspilationRegistry.wrapTranspiler(require('./typescript')),
  '.coffee': packageTranspilationRegistry.wrapTranspiler(
    require('./coffee-script')
  )
};

exports.addTranspilerConfigForPath = function(
  packagePath,
  packageName,
  packageMeta,
  config
) {
  packagePath = fs.realpathSync(packagePath);
  packageTranspilationRegistry.addTranspilerConfigForPath(
    packagePath,
    packageName,
    packageMeta,
    config
  );
};

exports.removeTranspilerConfigForPath = function(packagePath) {
  packagePath = fs.realpathSync(packagePath);
  packageTranspilationRegistry.removeTranspilerConfigForPath(packagePath);
};

const cacheStats = {};
let cacheDirectory = null;

exports.setAtomHomeDirectory = function(atomHome) {
  let cacheDir = path.join(atomHome, 'compile-cache');
  if (
    process.env.USER === 'root' &&
    process.env.SUDO_USER &&
    process.env.SUDO_USER !== process.env.USER
  ) {
    cacheDir = path.join(cacheDir, 'root');
  }
  this.setCacheDirectory(cacheDir);
};

exports.setCacheDirectory = function(directory) {
  cacheDirectory = directory;
};

exports.getCacheDirectory = function() {
  return cacheDirectory;
};

exports.addPathToCache = function(filePath, atomHome) {
  this.setAtomHomeDirectory(atomHome);
  const extension = path.extname(filePath);

  if (extension === '.cson') {
    if (!CSON) {
      CSON = require('season');
      CSON.setCacheDir(this.getCacheDirectory());
    }
    return CSON.readFileSync(filePath);
  } else {
    const compiler = COMPILERS[extension];
    if (compiler) {
      return compileFileAtPath(compiler, filePath, extension);
    }
  }
};

exports.getCacheStats = function() {
  return cacheStats;
};

exports.resetCacheStats = function() {
  Object.keys(COMPILERS).forEach(function(extension) {
    cacheStats[extension] = {
      hits: 0,
      misses: 0
    };
  });
};

function compileFileAtPath(compiler, filePath, extension) {
  const sourceCode = fs.readFileSync(filePath, 'utf8');
  if (compiler.shouldCompile(sourceCode, filePath)) {
    const cachePath = compiler.getCachePath(sourceCode, filePath);
    let compiledCode = readCachedJavaScript(cachePath);
    if (compiledCode != null) {
      cacheStats[extension].hits++;
    } else {
      cacheStats[extension].misses++;
      compiledCode = compiler.compile(sourceCode, filePath);
      writeCachedJavaScript(cachePath, compiledCode);
    }
    return compiledCode;
  }
  return sourceCode;
}

function readCachedJavaScript(relativeCachePath) {
  const cachePath = path.join(cacheDirectory, relativeCachePath);
  if (fs.isFileSync(cachePath)) {
    try {
      return fs.readFileSync(cachePath, 'utf8');
    } catch (error) {}
  }
  return null;
}

function writeCachedJavaScript(relativeCachePath, code) {
  const cachePath = path.join(cacheDirectory, relativeCachePath);
  fs.writeFileSync(cachePath, code, 'utf8');
}

const INLINE_SOURCE_MAP_REGEXP = /\/\/[#@]\s*sourceMappingURL=([^'"\n]+)\s*$/gm;

exports.install = function(resourcesPath, nodeRequire) {
  const snapshotSourceMapConsumer = {
    originalPositionFor({ line, column }) {
      const { relativePath, row } = snapshotResult.translateSnapshotRow(line);
      return {
        column,
        line: row,
        source: path.join(resourcesPath, 'app', 'static', relativePath),
        name: null
      };
    }
  };

  sourceMapSupport.install({
    handleUncaughtExceptions: false,

    // Most of this logic is the same as the default implementation in the
    // source-map-support module, but we've overridden it to read the javascript
    // code from our cache directory.
    retrieveSourceMap: function(filePath) {
      if (filePath === '<embedded>') {
        return { map: snapshotSourceMapConsumer };
      }

      if (!cacheDirectory || !fs.isFileSync(filePath)) {
        return null;
      }

      try {
        var sourceCode = fs.readFileSync(filePath, 'utf8');
      } catch (error) {
        console.warn('Error reading source file', error.stack);
        return null;
      }

      let compiler = COMPILERS[path.extname(filePath)];
      if (!compiler) compiler = COMPILERS['.js'];

      try {
        var fileData = readCachedJavaScript(
          compiler.getCachePath(sourceCode, filePath)
        );
      } catch (error) {
        console.warn('Error reading compiled file', error.stack);
        return null;
      }

      if (fileData == null) {
        return null;
      }

      let match, lastMatch;
      INLINE_SOURCE_MAP_REGEXP.lastIndex = 0;
      while ((match = INLINE_SOURCE_MAP_REGEXP.exec(fileData))) {
        lastMatch = match;
      }
      if (lastMatch == null) {
        return null;
      }

      const sourceMappingURL = lastMatch[1];
      const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);

      try {
        var sourceMap = JSON.parse(Buffer.from(rawData, 'base64'));
      } catch (error) {
        console.warn('Error parsing source map', error.stack);
        return null;
      }

      return {
        map: sourceMap,
        url: null
      };
    }
  });

  const prepareStackTraceWithSourceMapping = Error.prepareStackTrace;
  var prepareStackTrace = prepareStackTraceWithSourceMapping;

  function prepareStackTraceWithRawStackAssignment(error, frames) {
    if (error.rawStack) {
      // avoid infinite recursion
      return prepareStackTraceWithSourceMapping(error, frames);
    } else {
      error.rawStack = frames;
      return prepareStackTrace(error, frames);
    }
  }

  Error.stackTraceLimit = 30;

  Object.defineProperty(Error, 'prepareStackTrace', {
    get: function() {
      return prepareStackTraceWithRawStackAssignment;
    },

    set: function(newValue) {
      prepareStackTrace = newValue;
      process.nextTick(function() {
        prepareStackTrace = prepareStackTraceWithSourceMapping;
      });
    }
  });

  // eslint-disable-next-line no-extend-native
  Error.prototype.getRawStack = function() {
    // Access this.stack to ensure prepareStackTrace has been run on this error
    // because it assigns this.rawStack as a side-effect
    this.stack; // eslint-disable-line no-unused-expressions
    return this.rawStack;
  };

  Object.keys(COMPILERS).forEach(function(extension) {
    const compiler = COMPILERS[extension];

    Object.defineProperty(nodeRequire.extensions, extension, {
      enumerable: true,
      writable: false,
      value: function(module, filePath) {
        const code = compileFileAtPath(compiler, filePath, extension);
        return module._compile(code, filePath);
      }
    });
  });
};

exports.supportedExtensions = Object.keys(COMPILERS);
exports.resetCacheStats();
<commit_msg>Fix old comment<commit_after>'use strict';

// Atom's compile-cache when installing or updating packages, called by apm's Node-js

const path = require('path');
const fs = require('fs-plus');
const sourceMapSupport = require('@atom/source-map-support');

const PackageTranspilationRegistry = require('./package-transpilation-registry');
let CSON = null;

const packageTranspilationRegistry = new PackageTranspilationRegistry();

const COMPILERS = {
  '.js': packageTranspilationRegistry.wrapTranspiler(require('./babel')),
  '.ts': packageTranspilationRegistry.wrapTranspiler(require('./typescript')),
  '.tsx': packageTranspilationRegistry.wrapTranspiler(require('./typescript')),
  '.coffee': packageTranspilationRegistry.wrapTranspiler(
    require('./coffee-script')
  )
};

exports.addTranspilerConfigForPath = function(
  packagePath,
  packageName,
  packageMeta,
  config
) {
  packagePath = fs.realpathSync(packagePath);
  packageTranspilationRegistry.addTranspilerConfigForPath(
    packagePath,
    packageName,
    packageMeta,
    config
  );
};

exports.removeTranspilerConfigForPath = function(packagePath) {
  packagePath = fs.realpathSync(packagePath);
  packageTranspilationRegistry.removeTranspilerConfigForPath(packagePath);
};

const cacheStats = {};
let cacheDirectory = null;

exports.setAtomHomeDirectory = function(atomHome) {
  let cacheDir = path.join(atomHome, 'compile-cache');
  if (
    process.env.USER === 'root' &&
    process.env.SUDO_USER &&
    process.env.SUDO_USER !== process.env.USER
  ) {
    cacheDir = path.join(cacheDir, 'root');
  }
  this.setCacheDirectory(cacheDir);
};

exports.setCacheDirectory = function(directory) {
  cacheDirectory = directory;
};

exports.getCacheDirectory = function() {
  return cacheDirectory;
};

exports.addPathToCache = function(filePath, atomHome) {
  this.setAtomHomeDirectory(atomHome);
  const extension = path.extname(filePath);

  if (extension === '.cson') {
    if (!CSON) {
      CSON = require('season');
      CSON.setCacheDir(this.getCacheDirectory());
    }
    return CSON.readFileSync(filePath);
  } else {
    const compiler = COMPILERS[extension];
    if (compiler) {
      return compileFileAtPath(compiler, filePath, extension);
    }
  }
};

exports.getCacheStats = function() {
  return cacheStats;
};

exports.resetCacheStats = function() {
  Object.keys(COMPILERS).forEach(function(extension) {
    cacheStats[extension] = {
      hits: 0,
      misses: 0
    };
  });
};

function compileFileAtPath(compiler, filePath, extension) {
  const sourceCode = fs.readFileSync(filePath, 'utf8');
  if (compiler.shouldCompile(sourceCode, filePath)) {
    const cachePath = compiler.getCachePath(sourceCode, filePath);
    let compiledCode = readCachedJavaScript(cachePath);
    if (compiledCode != null) {
      cacheStats[extension].hits++;
    } else {
      cacheStats[extension].misses++;
      compiledCode = compiler.compile(sourceCode, filePath);
      writeCachedJavaScript(cachePath, compiledCode);
    }
    return compiledCode;
  }
  return sourceCode;
}

function readCachedJavaScript(relativeCachePath) {
  const cachePath = path.join(cacheDirectory, relativeCachePath);
  if (fs.isFileSync(cachePath)) {
    try {
      return fs.readFileSync(cachePath, 'utf8');
    } catch (error) {}
  }
  return null;
}

function writeCachedJavaScript(relativeCachePath, code) {
  const cachePath = path.join(cacheDirectory, relativeCachePath);
  fs.writeFileSync(cachePath, code, 'utf8');
}

const INLINE_SOURCE_MAP_REGEXP = /\/\/[#@]\s*sourceMappingURL=([^'"\n]+)\s*$/gm;

exports.install = function(resourcesPath, nodeRequire) {
  const snapshotSourceMapConsumer = {
    originalPositionFor({ line, column }) {
      const { relativePath, row } = snapshotResult.translateSnapshotRow(line);
      return {
        column,
        line: row,
        source: path.join(resourcesPath, 'app', 'static', relativePath),
        name: null
      };
    }
  };

  sourceMapSupport.install({
    handleUncaughtExceptions: false,

    // Most of this logic is the same as the default implementation in the
    // source-map-support module, but we've overridden it to read the javascript
    // code from our cache directory.
    retrieveSourceMap: function(filePath) {
      if (filePath === '<embedded>') {
        return { map: snapshotSourceMapConsumer };
      }

      if (!cacheDirectory || !fs.isFileSync(filePath)) {
        return null;
      }

      try {
        var sourceCode = fs.readFileSync(filePath, 'utf8');
      } catch (error) {
        console.warn('Error reading source file', error.stack);
        return null;
      }

      let compiler = COMPILERS[path.extname(filePath)];
      if (!compiler) compiler = COMPILERS['.js'];

      try {
        var fileData = readCachedJavaScript(
          compiler.getCachePath(sourceCode, filePath)
        );
      } catch (error) {
        console.warn('Error reading compiled file', error.stack);
        return null;
      }

      if (fileData == null) {
        return null;
      }

      let match, lastMatch;
      INLINE_SOURCE_MAP_REGEXP.lastIndex = 0;
      while ((match = INLINE_SOURCE_MAP_REGEXP.exec(fileData))) {
        lastMatch = match;
      }
      if (lastMatch == null) {
        return null;
      }

      const sourceMappingURL = lastMatch[1];
      const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);

      try {
        var sourceMap = JSON.parse(Buffer.from(rawData, 'base64'));
      } catch (error) {
        console.warn('Error parsing source map', error.stack);
        return null;
      }

      return {
        map: sourceMap,
        url: null
      };
    }
  });

  const prepareStackTraceWithSourceMapping = Error.prepareStackTrace;
  var prepareStackTrace = prepareStackTraceWithSourceMapping;

  function prepareStackTraceWithRawStackAssignment(error, frames) {
    if (error.rawStack) {
      // avoid infinite recursion
      return prepareStackTraceWithSourceMapping(error, frames);
    } else {
      error.rawStack = frames;
      return prepareStackTrace(error, frames);
    }
  }

  Error.stackTraceLimit = 30;

  Object.defineProperty(Error, 'prepareStackTrace', {
    get: function() {
      return prepareStackTraceWithRawStackAssignment;
    },

    set: function(newValue) {
      prepareStackTrace = newValue;
      process.nextTick(function() {
        prepareStackTrace = prepareStackTraceWithSourceMapping;
      });
    }
  });

  // eslint-disable-next-line no-extend-native
  Error.prototype.getRawStack = function() {
    // Access this.stack to ensure prepareStackTrace has been run on this error
    // because it assigns this.rawStack as a side-effect
    this.stack; // eslint-disable-line no-unused-expressions
    return this.rawStack;
  };

  Object.keys(COMPILERS).forEach(function(extension) {
    const compiler = COMPILERS[extension];

    Object.defineProperty(nodeRequire.extensions, extension, {
      enumerable: true,
      writable: false,
      value: function(module, filePath) {
        const code = compileFileAtPath(compiler, filePath, extension);
        return module._compile(code, filePath);
      }
    });
  });
};

exports.supportedExtensions = Object.keys(COMPILERS);
exports.resetCacheStats();
<|endoftext|>


<commit_before>// vim: ts=4 sw=4 et :
class Menu {
    constructor(choices) {
        this.choices = choices; // save menu options
        this.selected = 0;
        this.unselected_pics = this.choices.map(name => makeImage(`img/menu_${name}.png`))
        this.selected_pics = this.choices.map(name => makeImage(`img/menu_${name}_sel.png`))
        this.dudes_img = makeImage("img/p2.png")
        this.age = 0
    }
    update(dt, delta) {
        for (let sp_key of ['ENTER', 'LEFT', 'RIGHT']) {
            if (app.keys.is_new_press(sp_key)) {
                let ev_name = `${this.choices[this.selected]}_${sp_key}`
                if (this[ev_name])
                    this[ev_name]()
            }
            if (app.keys.is_new_press('DOWN')) {
                if (this.selected < this.choices.length - 1) {
                    this.selected = this.selected + 1;
                }
            } else if (app.keys.is_new_press("UP")) {
                if (this.selected > 0) {
                    this.selected = this.selected - 1;
                }
            }
        }
    }
    draw(dt, delta) {
        app.display.context.save()
        let fade_time = 3
        let globalAlpha = 1
        if (this.age < fade_time) {
            globalAlpha = this.age/fade_time
            this.age += delta
            if (this.age > fade_time) this.age = fade_time
        }
        app.display.context.globalAlpha = globalAlpha;
        let i = 0,
            x = 100,
            y = 100,
            factor = 0;
        app.display.context.translate(-100*(fade_time-this.age), 0)
        for (i = 0; i < this.choices.length; i++) {
            if (this.selected == i) {
                factor = Math.max(0.15, Math.abs(Math.sin((dt / 725) % Math.PI)))
                app.display.context.globalAlpha = globalAlpha * (1 - factor);
                app.display.context.drawImage(this.unselected_pics[i], x, y);
                app.display.context.globalAlpha = globalAlpha * factor;
                app.display.context.drawImage(this.selected_pics[i], x, y);
                app.display.context.globalAlpha = globalAlpha;
            } else {
                app.display.context.drawImage(this.unselected_pics[i], x, y);
            }
            y += 125;
        }
        y = 250;
        x = 500;
        for (i = 0; i < app.config.DUDES; i++) {
            app.display.context.drawImage(this.dudes_img, x, y);
            x += 50;
        }
        app.display.context.restore()
    }
}
class MainMenu extends Menu {
    constructor() {
        super(["NewGame", "Enemies"]);
    }
    NewGame_ENTER() {
        app.menus[0].restart()
        app.menus[0].running = true
        app.pop_menu()
    }
    Enemies_RIGHT() {
        if (app.config.DUDES < 10) app.config.DUDES += 1;
    }
    Enemies_LEFT() {
        if (app.config.DUDES > 1) app.config.DUDES -= 1;
    }
    update(dt, delta) {
        super.update(dt, delta);
        if (app.keys.is_new_press("ESC")) {
            app.pop_menu();
            app.menus[0].running = true
        }
    }
    draw(dt, delta) {
        // add a semi transparent background
        app.display.context.fillStyle = "rgba(100, 120, 150, 0.4)";
        app.display.context.fillRect(0, 0, app.display.width, app.display.height);
        app.display.context.fillStyle = "white";
        super.draw(dt, delta);
    }
}
<commit_msg>Move specific code out of Menu<commit_after>// vim: ts=4 sw=4 et :
class Menu {
    constructor(choices) {
        this.choices = choices; // save menu options
        this.selected = 0;
        this.unselected_pics = this.choices.map(name => makeImage(`img/menu_${name}.png`))
        this.selected_pics = this.choices.map(name => makeImage(`img/menu_${name}_sel.png`))
        this.dudes_img = makeImage("img/p2.png")
        this.age = 0
    }
    update(dt, delta) {
        for (let sp_key of ['ENTER', 'LEFT', 'RIGHT']) {
            if (app.keys.is_new_press(sp_key)) {
                let ev_name = `${this.choices[this.selected]}_${sp_key}`
                if (this[ev_name])
                    this[ev_name]()
            }
            if (app.keys.is_new_press('DOWN')) {
                if (this.selected < this.choices.length - 1) {
                    this.selected = this.selected + 1;
                }
            } else if (app.keys.is_new_press("UP")) {
                if (this.selected > 0) {
                    this.selected = this.selected - 1;
                }
            }
        }
    }
    draw(dt, delta) {
        app.display.context.save()
        let fade_time = 3
        let globalAlpha = 1
        if (this.age < fade_time) {
            globalAlpha = this.age/fade_time
            this.age += delta
            if (this.age > fade_time) this.age = fade_time
        }
        app.display.context.globalAlpha = globalAlpha;
        let i = 0,
            x = 100,
            y = 100,
            factor = 0;
        app.display.context.translate(-100*(fade_time-this.age), 0)
        for (i = 0; i < this.choices.length; i++) {
            if (this.selected == i) {
                factor = Math.max(0.15, Math.abs(Math.sin((dt / 725) % Math.PI)))
                app.display.context.globalAlpha = globalAlpha * (1 - factor);
                app.display.context.drawImage(this.unselected_pics[i], x, y);
                app.display.context.globalAlpha = globalAlpha * factor;
                app.display.context.drawImage(this.selected_pics[i], x, y);
                app.display.context.globalAlpha = globalAlpha;
            } else {
                app.display.context.drawImage(this.unselected_pics[i], x, y);
            }
            y += 125;
        }
        this.draw_extra()
        app.display.context.restore()
    }
}
class MainMenu extends Menu {
    constructor() {
        super(["NewGame", "Enemies"]);
    }
    NewGame_ENTER() {
        app.menus[0].restart()
        app.menus[0].running = true
        app.pop_menu()
    }
    Enemies_RIGHT() {
        if (app.config.DUDES < 10) app.config.DUDES += 1;
    }
    Enemies_LEFT() {
        if (app.config.DUDES > 1) app.config.DUDES -= 1;
    }
    update(dt, delta) {
        super.update(dt, delta);
        if (app.keys.is_new_press("ESC")) {
            app.pop_menu();
            app.menus[0].running = true
        }
    }
    draw(dt, delta) {
        // add a semi transparent background
        app.display.context.fillStyle = "rgba(100, 120, 150, 0.4)";
        app.display.context.fillRect(0, 0, app.display.width, app.display.height);
        app.display.context.fillStyle = "white";
        super.draw(dt, delta);
    }
    draw_extra() {
        let y = 250;
        let x = 500;
        for (let i = 0; i < app.config.DUDES; i++) {
            app.display.context.drawImage(this.dudes_img, x, y);
            x += 50;
        }
    }
}
<|endoftext|>


<commit_before>/******** Project - Final *********************************
Authors: Eric Wooley, Tandra Felly, Lauryn Loudermilk
Description: Javascript automata engine.
**********************************************************/

function changeCursor(id){
	var elem = document.getElementById("main");
	switch(id)
	{
		case "move":
			elem.style.cursor = "move";
			break;
		case "newState":
			elem.style.cursor = "crosshair";
			addState();
			break;
		case "delete":
			elem.style.cursor = "not-allowed";
			break;
		case "rename":
			elem.style.cursor = "text";
			break;
		case "transition":
			elem.style.cursor = "e-resize";
			break;
		case "clear":
			clearscreen();
		default:
			alert("this button has no purpose");
	}
}

function moveState(){
	//ondragstart or ondrag

}

function addState(){
	var elem = document.getElementById("main");

	elem.addEventListener('click', makeCircle, false);

	function makeCircle() {
	  var circle = new Kinetic.Circle({
          x: e.center.x,
          y: e.center.y,
          radius: e.radius,
          fill: 'red',
          stroke: 'black',
          strokeWidth: 4
        });
	  // This adds a node to circle for the engine to work with.
        var state = {geo: circle, node: aut.add_node()};
        dfa_layer.add(circle);
        dfa_layer.draw(); //called to draw the layer after changes
        states.push(state);
	}
}

function addTransition(){

}

function removeObject(){

}

function rename(){

}

function clearscreen(){

	var answer = confirm("Are you sure you want to clear the screen?")
	if (answer){
       // eventually this will clear the screen
	}
	else{
        // eventually this will exit
	}

}<commit_msg>clear screen working<commit_after>/******** Project - Final *********************************
Authors: Eric Wooley, Tandra Felly, Lauryn Loudermilk
Description: Javascript automata engine.
**********************************************************/

function changeCursor(id){
	var elem = document.getElementById("main");
	switch(id)
	{
		case "move":
			elem.style.cursor = "move";
			break;
		case "newState":
			elem.style.cursor = "crosshair";
			addState();
			break;
		case "delete":
			elem.style.cursor = "not-allowed";
			break;
		case "rename":
			elem.style.cursor = "text";
			break;
		case "transition":
			elem.style.cursor = "e-resize";
			break;
		case "clear":
			clearscreen();
			break;
		default:
			alert("this button has no purpose");
	}
}

function moveState(){
	//ondragstart or ondrag

}

function addState(){
	var elem = document.getElementById("main");

	elem.addEventListener('click', makeCircle, false);

	function makeCircle() {
	  var circle = new Kinetic.Circle({
          x: e.center.x,
          y: e.center.y,
          radius: e.radius,
          fill: 'red',
          stroke: 'black',
          strokeWidth: 4
        });
	  // This adds a node to circle for the engine to work with.
        var state = {geo: circle, node: aut.add_node()};
        dfa_layer.add(circle);
        dfa_layer.draw(); //called to draw the layer after changes
        states.push(state);
	}
}

function addTransition(){

}

function removeObject(){

}

function rename(){

}

function clearscreen(){

	var answer = confirm("Are you sure you want to clear the screen?")
	if (answer){
       dfa_layer.clear()
	}
	else{
        return
	}

}<|endoftext|>


<commit_before>
var occ = require('./bindings');

function toArray(meshBuffer)
{
   var res = [];
   for (var i =0;i< meshBuffer.length;i++) {
      res.push(parseFloat(meshBuffer[i].toFixed(3)));
   }
   return res;
}
exports.init= function() {

  var assert = require('assert');
  console.log('adding occ.Mesh.prototype.toJSON function');
  occ.Mesh.prototype.toJSON = function() {

    // see https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3.1
  var json = {
      metadata: { "formatVersion" : 3 },
      materials: [ {
        DbgColor : 15658734, // => 0xeeeeee
        DbgIndex : 0,
        DbgName : "dummy",
        colorDiffuse : [ 1, 0, 0 ]
      } ],
      vertices: [],
      normals: [],
      faces: []
  };

   json.vertices = toArray(this.vertices);
   json.normals  = toArray(this.normals);

   json.uvs = [];

   json.faces = [];

   var f ;
   var j =0;
   for (var i=0; i < this.numTriangles; i++) {

        json.faces.push(0+ 2*2*2*2*2 ); // vertex + normal index

        var i1 = this.triangles[i*3+0];
        var i2 = this.triangles[i*3+1];
        var i3 = this.triangles[i*3+2];

        json.faces.push(i1);
        json.faces.push(i2);
        json.faces.push(i3);
        json.faces.push(i1);
        json.faces.push(i2);
        json.faces.push(i3);

   }
  return json;
};

};
<commit_msg>cleanup<commit_after>var assert = require('assert');
var occ = require('./bindings');

function toArray(meshBuffer) {
    var res = [];
    for (var i = 0; i < meshBuffer.length; i++) {
        res.push(parseFloat(meshBuffer[i].toFixed(3)));
    }
    return res;
}
exports.init = function () {

    occ.Mesh.prototype.toJSON = function () {

        // see https://github.com/mrdoob/three.js/wiki/JSON-Model-format-3.1
        var json = {
            metadata: {"formatVersion": 3},
            materials: [{
                DbgColor: 15658734, // => 0xeeeeee
                DbgIndex: 0,
                DbgName: "dummy",
                colorDiffuse: [1, 0, 0]
            }],
            vertices: [],
            normals: [],
            faces: []
        };

        json.vertices = toArray(this.vertices);
        json.normals = toArray(this.normals);

        json.uvs = [];

        json.faces = [];

        var f;
        var j = 0;
        for (var i = 0; i < this.numTriangles; i++) {

            json.faces.push(0 + 2 * 2 * 2 * 2 * 2); // vertex + normal index

            var i1 = this.triangles[i * 3 + 0];
            var i2 = this.triangles[i * 3 + 1];
            var i3 = this.triangles[i * 3 + 2];

            json.faces.push(i1);
            json.faces.push(i2);
            json.faces.push(i3);
            json.faces.push(i1);
            json.faces.push(i2);
            json.faces.push(i3);
        }
        return json;
    };

};
<|endoftext|>


<commit_before>var path = require('path')
var fs = require('fs')
var concat = require('concat-stream')
var extend = require('extend')
var request = require('request')
var debug = require('debug')('dat.meta')

module.exports = Meta

function Meta(dat, ready) {
  var self = this
  if (!(this instanceof Meta)) return new Meta(dat, ready)
  if (!ready) ready = function noop() {}
  this.dat = dat
  this.reserved = ['_id', '_seq', '_rev', '_deleted']
  this.file = path.join(this.dat.dir, '.dat', 'dat.json')

  this.read(function(err, json) {
    if (err) json = {}
    if (!json.columns) json.columns = []
    self.json = json
    ready(err)
  })
}

Meta.prototype.read = function(cb) {
  debug('read', this.file)
  fs.readFile(this.file, function(err, buf) {
    if (err) return cb(err)
    cb(null, JSON.parse(buf))
  })
}

Meta.prototype.write = function(json, cb) {
  var self = this
  debug('write', this.file)
  fs.writeFile(this.file, JSON.stringify(json, null, '  ') + '\n', function(err) {
    self.json = json
    cb(err)
  })
}

Meta.prototype.update = function(json, cb) {
  var self = this
  self.read(function(err, obj) {
    if (err) obj = {}
    var updated = extend({}, obj, json)
    self.write(updated, cb)
  })
}

Meta.prototype.addColumns = function(columns, cb) {
  var self = this
  if (!(columns instanceof Array)) columns = [columns]
  this.json.columns = this.json.columns.concat(columns)
  this.dat.db.put('config', this.json, {valueEncoding: 'json'}, function(err) {
    if (err) return cb(err)
    self.update(self.json, cb)
  })
}

Meta.prototype.getNewColumns = function(b, opts) {
  if (!opts) opts = { strict: false }
  var existing = this.json.columns

  // remove reserved columns
  var incoming = []
  for (var i = 0; i < b.length; i++) {
    if (this.reserved.indexOf(b[i]) > -1) continue
    incoming.push(b[i])
  }

  // return early if there aren't any existing columns
  if (existing.length === 0) return incoming

  existing.sort()
  incoming.sort()

  var newColumns = []

  // strict mode matches based on order. non strict matches based on indexOf
  if (opts.strict) {
    // loop over all potentially new columns
    for (var y = 0; y < incoming.length; y++) {
      var newer = incoming[y]
      var older = existing[y]

      if (y >= existing.length) {
        newColumns.push(newer)
      } else if (newer === older) {
        continue
      } else {
        var err = {
          message: 'Incoming data has different schema than existing data',
          type: 'columnMismatch',
          existing: existing,
          incoming: incoming,
          error: true
        }
        return err
      }
    }
  } else {
    for (var y = 0; y < incoming.length; y++) {
      var col = incoming[y]
      if (existing.indexOf(col) === -1) newColumns.push(col)
    }
  }

  return newColumns
}

Meta.prototype.pullSchema = function(remote, cb) {
  var self = this
  request({ json: true, url: remote + '/_schema' }, function(err, resp, json) {
    if (err || resp.statusCode > 299) {
      return cb(err || new Error(resp.statusCode), "Remote schema request failed")
    }
    var existing = self.json.columns
    var incoming = json.columns

    // if they match return early
    if (JSON.stringify(existing) === JSON.stringify(incoming)) return cb(null)

    var conflict = false
    var newColumns = []
    var mismatch = new Error('Remote schema mismatch')

    if (incoming.length < existing.length) return cb(mismatch)
    if (JSON.stringify(existing) !== JSON.stringify(incoming.slice(0, existing.length))) return cb(mismatch)

    var newColumns = incoming.slice(existing.length)

    self.addColumns(newColumns, function(err) {
      if (err) return cb(err)
      cb(null)
    })
  })
}
<commit_msg>do not mutate existing columns<commit_after>var path = require('path')
var fs = require('fs')
var concat = require('concat-stream')
var extend = require('extend')
var request = require('request')
var debug = require('debug')('dat.meta')

module.exports = Meta

function Meta(dat, ready) {
  var self = this
  if (!(this instanceof Meta)) return new Meta(dat, ready)
  if (!ready) ready = function noop() {}
  this.dat = dat
  this.reserved = ['_id', '_seq', '_rev', '_deleted']
  this.file = path.join(this.dat.dir, '.dat', 'dat.json')

  this.read(function(err, json) {
    if (err) json = {}
    if (!json.columns) json.columns = []
    self.json = json
    ready(err)
  })
}

Meta.prototype.read = function(cb) {
  debug('read', this.file)
  fs.readFile(this.file, function(err, buf) {
    if (err) return cb(err)
    cb(null, JSON.parse(buf))
  })
}

Meta.prototype.write = function(json, cb) {
  var self = this
  debug('write', this.file)
  fs.writeFile(this.file, JSON.stringify(json, null, '  ') + '\n', function(err) {
    self.json = json
    cb(err)
  })
}

Meta.prototype.update = function(json, cb) {
  var self = this
  self.read(function(err, obj) {
    if (err) obj = {}
    var updated = extend({}, obj, json)
    self.write(updated, cb)
  })
}

Meta.prototype.addColumns = function(columns, cb) {
  var self = this
  if (!(columns instanceof Array)) columns = [columns]
  this.json.columns = this.json.columns.concat(columns)
  this.dat.db.put('config', this.json, {valueEncoding: 'json'}, function(err) {
    if (err) return cb(err)
    self.update(self.json, cb)
  })
}

Meta.prototype.getNewColumns = function(b, opts) {
  if (!opts) opts = { strict: false }
  var existing = [].concat(this.json.columns)

  // remove reserved columns
  var incoming = []
  for (var i = 0; i < b.length; i++) {
    if (this.reserved.indexOf(b[i]) > -1) continue
    incoming.push(b[i])
  }

  // return early if there aren't any existing columns
  if (existing.length === 0) return incoming

  existing.sort()
  incoming.sort()

  var newColumns = []

  // strict mode matches based on order. non strict matches based on indexOf
  if (opts.strict) {
    // loop over all potentially new columns
    for (var y = 0; y < incoming.length; y++) {
      var newer = incoming[y]
      var older = existing[y]

      if (y >= existing.length) {
        newColumns.push(newer)
      } else if (newer === older) {
        continue
      } else {
        var err = {
          message: 'Incoming data has different schema than existing data',
          type: 'columnMismatch',
          existing: existing,
          incoming: incoming,
          error: true
        }
        return err
      }
    }
  } else {
    for (var y = 0; y < incoming.length; y++) {
      var col = incoming[y]
      if (existing.indexOf(col) === -1) newColumns.push(col)
    }
  }

  return newColumns
}

Meta.prototype.pullSchema = function(remote, cb) {
  var self = this
  request({ json: true, url: remote + '/_schema' }, function(err, resp, json) {
    if (err || resp.statusCode > 299) {
      return cb(err || new Error(resp.statusCode), "Remote schema request failed")
    }
    var existing = self.json.columns
    var incoming = json.columns

    // if they match return early
    if (JSON.stringify(existing) === JSON.stringify(incoming)) return cb(null)

    var conflict = false
    var newColumns = []
    var mismatch = new Error('Remote schema mismatch')

    if (incoming.length < existing.length) return cb(mismatch)
    if (JSON.stringify(existing) !== JSON.stringify(incoming.slice(0, existing.length))) return cb(mismatch)

    var newColumns = incoming.slice(existing.length)

    self.addColumns(newColumns, function(err) {
      if (err) return cb(err)
      cb(null)
    })
  })
}
<|endoftext|>


<commit_before>import React from 'react';
import AvatarIcon from '/imports/ui/components/avatar/AvatarIcon';
import FontIcon from 'material-ui/FontIcon';
import FlatButton from 'material-ui/FlatButton';
import _ from 'lodash';

/*
	BEGIN CommentUpperLeft
*/
const CommentUpperLeft = props => (

{props.title}

);
CommentUpperLeft.propTypes = {
	title: React.PropTypes.string.isRequired,
};
/*
	END CommentUpperLeft
*/

/*
	BEGIN CommentUpperRight
*/
const CommentUpperRight = props => (

		{_.every(props.commenters, commenter => props.userCanEditCommenters.indexOf(commenter._id) > -1) ?
			<FlatButton
				label="Edit comment"
				href={`/commentary/${props.commentId}/edit`}
				icon={<FontIcon className="mdi mdi-pen" />}
			/>
			:
			''
		}
		{props.commenters.map(commenter => (

					<a href={`/commenters/${commenter.slug}`}>
						{commenter.name}

						{props.updateDate}

					<a href={`/commenters/${commenter.slug}`}>
						<AvatarIcon
							avatar={
								(commenter && 'avatar' in commenter) ?
								commenter.avatar.src
								: null
							}
						/>

		))}

);
CommentUpperRight.propTypes = {
	commenters: React.PropTypes.arrayOf(React.PropTypes.shape({
		_id: React.PropTypes.string.isRequired,
		slug: React.PropTypes.string.isRequired,
		name: React.PropTypes.string.isRequired,
		avatar: React.PropTypes.shape({
			src: React.PropTypes.string.isRequired,
		})
	})).isRequired,
	commentId: React.PropTypes.string.isRequired,
	updateDate: React.PropTypes.string.isRequired,
	userCanEditCommenters: React.PropTypes.arrayOf(React.PropTypes.string),
};
CommentUpperRight.defaultProps = {
	userCanEditCommenters: [],
};
/*
	END CommentUpperRight
*/

/*
	BEGIN CommentUpper
*/
const CommentUpper = props => (

		{!props.hideTitle && <CommentUpperLeft
			title={props.title}
		/>}
		{!props.hideCommenters && <CommentUpperRight
			commenters={props.commenters}
			commentId={props.commentId}
			updateDate={props.updateDate}
			userCanEditCommenters={props.userCanEditCommenters}
		/>}

);
CommentUpper.propTypes = {
	title: React.PropTypes.string.isRequired,
	commentId: React.PropTypes.string.isRequired,
	commenters: React.PropTypes.arrayOf(React.PropTypes.shape({
		_id: React.PropTypes.string.isRequired,
		slug: React.PropTypes.string.isRequired,
		name: React.PropTypes.string.isRequired,
		avatar: React.PropTypes.shape({
			src: React.PropTypes.string.isRequired,
		})
	})).isRequired,
	updateDate: React.PropTypes.string.isRequired,
	userCanEditCommenters: React.PropTypes.arrayOf(React.PropTypes.string),
	hideTitle: React.PropTypes.bool,
	hideCommenters: React.PropTypes.bool,
};
CommentUpper.defaultProps = {
	userCanEditCommenters: [],
	hideTitle: false,
	hideCommenters: false,
};
/*
	END CommentUpper
*/

export default CommentUpper;
export { CommentUpperLeft, CommentUpperRight };
<commit_msg>wrap CommentUpper buttons in Link component<commit_after>import React from 'react';
import AvatarIcon from '/imports/ui/components/avatar/AvatarIcon';
import FontIcon from 'material-ui/FontIcon';
import FlatButton from 'material-ui/FlatButton';
import _ from 'lodash';
import { Link } from 'react-router-dom';
/*
	BEGIN CommentUpperLeft
*/
const CommentUpperLeft = props => (

{props.title}

);
CommentUpperLeft.propTypes = {
	title: React.PropTypes.string.isRequired,
};
/*
	END CommentUpperLeft
*/

/*
	BEGIN CommentUpperRight
*/
const CommentUpperRight = props => (

		{_.every(props.commenters, commenter => props.userCanEditCommenters.indexOf(commenter._id) > -1) ?
			<Link to={`/commentary/${props.commentId}/edit`}>
				<FlatButton
					label="Edit comment"
					icon={<FontIcon className="mdi mdi-pen"/>}
				/>
			</Link>
			:
			''
		}
		{props.commenters.map(commenter => (

					<a href={`/commenters/${commenter.slug}`}>
						{commenter.name}

						{props.updateDate}

					<a href={`/commenters/${commenter.slug}`}>
						<AvatarIcon
							avatar={
								(commenter && 'avatar' in commenter) ?
								commenter.avatar.src
								: null
							}
						/>

		))}

);
CommentUpperRight.propTypes = {
	commenters: React.PropTypes.arrayOf(React.PropTypes.shape({
		_id: React.PropTypes.string.isRequired,
		slug: React.PropTypes.string.isRequired,
		name: React.PropTypes.string.isRequired,
		avatar: React.PropTypes.shape({
			src: React.PropTypes.string.isRequired,
		})
	})).isRequired,
	commentId: React.PropTypes.string.isRequired,
	updateDate: React.PropTypes.string.isRequired,
	userCanEditCommenters: React.PropTypes.arrayOf(React.PropTypes.string),
};
CommentUpperRight.defaultProps = {
	userCanEditCommenters: [],
};
/*
	END CommentUpperRight
*/

/*
	BEGIN CommentUpper
*/
const CommentUpper = props => (

		{!props.hideTitle && <CommentUpperLeft
			title={props.title}
		/>}
		{!props.hideCommenters && <CommentUpperRight
			commenters={props.commenters}
			commentId={props.commentId}
			updateDate={props.updateDate}
			userCanEditCommenters={props.userCanEditCommenters}
		/>}

);
CommentUpper.propTypes = {
	title: React.PropTypes.string.isRequired,
	commentId: React.PropTypes.string.isRequired,
	commenters: React.PropTypes.arrayOf(React.PropTypes.shape({
		_id: React.PropTypes.string.isRequired,
		slug: React.PropTypes.string.isRequired,
		name: React.PropTypes.string.isRequired,
		avatar: React.PropTypes.shape({
			src: React.PropTypes.string.isRequired,
		})
	})).isRequired,
	updateDate: React.PropTypes.string.isRequired,
	userCanEditCommenters: React.PropTypes.arrayOf(React.PropTypes.string),
	hideTitle: React.PropTypes.bool,
	hideCommenters: React.PropTypes.bool,
};
CommentUpper.defaultProps = {
	userCanEditCommenters: [],
	hideTitle: false,
	hideCommenters: false,
};
/*
	END CommentUpper
*/

export default CommentUpper;
export { CommentUpperLeft, CommentUpperRight };
<|endoftext|>


<commit_before>var auth = require('./auth');
var logger = require('./logger');
var sessions = require('./sessions');

const timeDelay = 30 * 1000;
const helpMessage = `Here's what you can ask Cinnabot!\n\n
/bus                      - check bus timings for UTown and Dover road\n
/bus <busstop>   - check bus timings for <busstop>\n
/dining                  - tell us how the food was\n
/events                 - view upcoming USP events\n
/fault                     - report building faults in Cinnamon\n
/feedback             - send suggestions and complaints\n
/links                     - view useful links\n
/nusbus                - check bus timings for NUS buses\n
/psi                       - get the psi and weather conditions\n
/register               - register your NUS account!\n
/spaces                - view upcoming activities in USP spaces\n
/stats                    - view key statistics`;

function start_feedback(chatId, callback) {
    var feedbackMsg = "Thanks for using Cinnabot 😁\n";
    feedbackMsg += "Feel free to tell us how cinnabot can be improved.\n";
    feedbackMsg += "Type /done to end the feedback session.\n";
    feedbackMsg += "Type /cancel to cancel feedback";
    var remindDone = function() {
        callback("Please remember to type /done when you are done.");
        setTimeout(remindDone, timeDelay);
    };
    setTimeout(remindDone, timeDelay);
    var feedbackSession = sessions.createFeedbackSession(chatId);
    return callback(feedbackMsg);
}

function continue_feedback(body, chatId, msg, callback) {
    var feedbackSession = sessions.getFeedbackSession(chatId);
    feedbackSession.feedbackMsg += body + "\n";
    if (body.endsWith("/done")) {
        return done_feedback(chatId, msg, callback);
    }
    return;
}

function done_feedback(chatId, msg, callback) {
    var feedbackSession = sessions.getFeedbackSession(chatId);
    var feedbackMsg = feedbackSession.feedbackMsg;
    feedbackMsg = feedbackMsg.substring(0, feedbackMsg.length - 6);
    logger.feedback(feedbackMsg, msg, callback);
    sessions.deleteFeedbackSession(chatId);
    var doneMsg = "Thanks for the feedback 😁";
    return callback(doneMsg);
}

function help(callback) {
    callback(helpMessage);
}

function getLinks(chatId, bot) {
    var linkText = "USEFUL LINKS:\n==============\n\n";

    function authCallback(row) {
        if (!row) {
            return bot.sendMessage(chatId, "Sorry you're not registered. Type /register to register.");
        } else {
            // if (!row.isCinnamonResident) {
            linkText += `Check your NUS library account:\n
            https://linc.nus.edu.sg/patroninfo/\n\n`;
            // }
            // if (row.isCinnamonResident) {
            linkText +=
                `Check the USP reading room catalogue:\n
                https://myaces.nus.edu.sg/libms_isis/login.jsp\n\n
                Check your meal credits:\n
                https://bit.ly/hungrycinnamon\n\n
                Report faults in Cinnamon:\n
                https://bit.ly/faultycinnamon\n\n
                Check your air-con credits:\n
                https://bit.ly/chillycinnamon`;
                // }
        }
        bot.sendMessage(chatId, linkText, {
            disable_web_page_preview: true
        });
    }
    auth.isCinnamonResident(chatId, authCallback);
}

module.exports = {
    start_feedback, continue_feedback, done_feedback, help, getLinks
};
<commit_msg>fix linting errors<commit_after>var auth = require('./auth');
var logger = require('./logger');
var sessions = require('./sessions');

const timeDelay = 30 * 1000;
const helpMessage = `Here's what you can ask Cinnabot!\n\n
/bus                      - check bus timings for UTown and Dover road\n
/bus <busstop>   - check bus timings for <busstop>\n
/dining                  - tell us how the food was\n
/events                 - view upcoming USP events\n
/fault                     - report building faults in Cinnamon\n
/feedback             - send suggestions and complaints\n
/links                     - view useful links\n
/nusbus                - check bus timings for NUS buses\n
/psi                       - get the psi and weather conditions\n
/register               - register your NUS account!\n
/spaces                - view upcoming activities in USP spaces\n
/stats                    - view key statistics`;

function start_feedback(chatId, callback) {
    var feedbackMsg = 'Thanks for using Cinnabot 😁\n';
    feedbackMsg += 'Feel free to tell us how cinnabot can be improved.\n';
    feedbackMsg += 'Type /done to end the feedback session.\n';
    feedbackMsg += 'Type /cancel to cancel feedback';
    var remindDone = function() {
        callback('Please remember to type /done when you are done.');
        setTimeout(remindDone, timeDelay);
    };
    setTimeout(remindDone, timeDelay);
    var feedbackSession = sessions.createFeedbackSession(chatId);
    return callback(feedbackMsg);
}

function continue_feedback(body, chatId, msg, callback) {
    var feedbackSession = sessions.getFeedbackSession(chatId);
    feedbackSession.feedbackMsg += body + '\n';
    if (body.endsWith('/done')) {
        return done_feedback(chatId, msg, callback);
    }
    return;
}

function done_feedback(chatId, msg, callback) {
    var feedbackSession = sessions.getFeedbackSession(chatId);
    var feedbackMsg = feedbackSession.feedbackMsg;
    feedbackMsg = feedbackMsg.substring(0, feedbackMsg.length - 6);
    logger.feedback(feedbackMsg, msg, callback);
    sessions.deleteFeedbackSession(chatId);
    var doneMsg = 'Thanks for the feedback 😁';
    return callback(doneMsg);
}

function help(callback) {
    callback(helpMessage);
}

function getLinks(chatId, bot) {
    var linkText = 'USEFUL LINKS:\n==============\n\n';

    function authCallback(row) {
        if (!row) {
            return bot.sendMessage(chatId, 'Sorry you're not registered. Type /register to register.');
        } else {
            // if (!row.isCinnamonResident) {
            linkText +=
                'Check your NUS library account:\n' +
                'https://linc.nus.edu.sg/patroninfo/\n\n';
                    // }
                    // if (row.isCinnamonResident) {
            linkText +=
                'Check the USP reading room catalogue:\n' +
                'https://myaces.nus.edu.sg/libms_isis/login.jsp\n\n' +
                'Check your meal credits:\n' +
                'https://bit.ly/hungrycinnamon\n\n' +
                'Report faults in Cinnamon:\n' +
                'https://bit.ly/faultycinnamon\n\n' +
                'Check your air-con credits:\n' +
                'https://bit.ly/chillycinnamon';
                // }
        }
        bot.sendMessage(chatId, linkText, {
            disable_web_page_preview: true
        });
    }
}

module.exports = {
    start_feedback, continue_feedback, done_feedback, help, getLinks
};
<|endoftext|>


<commit_before>var cx = require('classnames');
var React = require('react');

var Node = React.createClass({
  displayName: 'UITreeNode',

  componentDidMount: function () {
    this.props.registerNode && this.props.registerNode(this);
  },

  renderCollapse: function () {
    var index = this.props.index;

    if (index.children && index.children.length) {
      var collapsed = index.node.collapsed;

      return (

      );
    }

    return null;
  },

  renderChildren: function () {
    var index = this.props.index;
    var tree = this.props.tree;
    var dragging = this.props.dragging;
    var childrenStyles = {};

    if (index.children && index.children.length) {
      if (index.node.collapsed) {
        childrenStyles.display = 'none';
      }

      childrenStyles['paddingLeft'] = this.props.paddingLeft + 'px';

      return (

          {index.children.map(function (child) {
            var childIndex = tree.getIndex(child);

            return (
              <Node tree={tree}
                    index={childIndex}
                    key={childIndex.id}
                    dragging={dragging}
                    registerNode={this.props.registerNode}
                    paddingLeft={this.props.paddingLeft}
                    onCollapse={this.props.onCollapse}
                    onDragStart={this.props.onDragStart} />
            );
          }.bind(this))}

      );
    }

    return null;
  },

  render: function () {
    var tree = this.props.tree;
    var index = this.props.index;
    var dragging = this.props.dragging;
    var node = index.node;
    var styles = {};

    return (

          {this.renderCollapse()}
          {tree.renderNode(node)}

        {this.renderChildren()}

    );
  },

  handleCollapse: function (e) {
    var nodeId = this.props.index.id;

    e.stopPropagation();

    if (this.props.onCollapse) {
      this.props.onCollapse(nodeId);
    }
  },

  handleMouseDown: function (e) {
    var nodeId = this.props.index.id;
    var dom = this.refs.inner.getDOMNode();
    var evt = Object.assign({}, e);

    this.dragDelay = setTimeout(function() {
      if (this.props.onDragStart) {
        this.props.onDragStart(nodeId, dom, evt);
      }

      this.dragDelay = null;
    }.bind(this), 200);
  },

  handleMouseUp: function () {
    if (this.dragDelay) {
      clearTimeout(this.dragDelay);
    }
  }
});

module.exports = Node;
<commit_msg>fix ref calling getDOMNode()<commit_after>var cx = require('classnames');
var React = require('react');

var Node = React.createClass({
  displayName: 'UITreeNode',

  componentDidMount: function () {
    this.props.registerNode && this.props.registerNode(this);
  },

  renderCollapse: function () {
    var index = this.props.index;

    if (index.children && index.children.length) {
      var collapsed = index.node.collapsed;

      return (

      );
    }

    return null;
  },

  renderChildren: function () {
    var index = this.props.index;
    var tree = this.props.tree;
    var dragging = this.props.dragging;
    var childrenStyles = {};

    if (index.children && index.children.length) {
      if (index.node.collapsed) {
        childrenStyles.display = 'none';
      }

      childrenStyles['paddingLeft'] = this.props.paddingLeft + 'px';

      return (

          {index.children.map(function (child) {
            var childIndex = tree.getIndex(child);

            return (
              <Node tree={tree}
                    index={childIndex}
                    key={childIndex.id}
                    dragging={dragging}
                    registerNode={this.props.registerNode}
                    paddingLeft={this.props.paddingLeft}
                    onCollapse={this.props.onCollapse}
                    onDragStart={this.props.onDragStart} />
            );
          }.bind(this))}

      );
    }

    return null;
  },

  render: function () {
    var tree = this.props.tree;
    var index = this.props.index;
    var dragging = this.props.dragging;
    var node = index.node;
    var styles = {};

    return (

          {this.renderCollapse()}
          {tree.renderNode(node)}

        {this.renderChildren()}

    );
  },

  handleCollapse: function (e) {
    var nodeId = this.props.index.id;

    e.stopPropagation();

    if (this.props.onCollapse) {
      this.props.onCollapse(nodeId);
    }
  },

  handleMouseDown: function (e) {
    var nodeId = this.props.index.id;
    var dom = this.refs.inner;
    var evt = Object.assign({}, e);

    this.dragDelay = setTimeout(function() {
      if (this.props.onDragStart) {
        this.props.onDragStart(nodeId, dom, evt);
      }

      this.dragDelay = null;
    }.bind(this), 200);
  },

  handleMouseUp: function () {
    if (this.dragDelay) {
      clearTimeout(this.dragDelay);
    }
  }
});

module.exports = Node;
<|endoftext|>


<commit_before>import Global from './global';

export default {
    hold: hold,
    release: release,
    get: get,
    set: set,
    invalidate: invalidate,
    waitFor: waitFor
}

var DATA = {},              // uuid => {stale: false/true, value: object data (whatever Model.loadFromRemote returns)}
    HOLDING = false,
    HOLD_QUEUE = [],
    INFLIGHT = new Set(),
    WAITERS = {};           // uuid => fn

function waitFor (model, fn) {
    if (!WAITERS.hasOwnProperty(model.uuid)) {
        WAITERS[model.uuid] = [];
    }
    WAITERS[model.uuid].push(fn);
}

function callWaiters (model) {
    if (WAITERS.hasOwnProperty(model.uuid)) {
        let waiters = WAITERS[model.uuid].slice();
        WAITERS[model.uuid].length = 0;
        waiters.forEach(fn => fn());
    }
}

/**
 * TODO: Default behavior is to look at DATA::valid and return stale data anyways (while dispatching to remote).
 * Perhaps we can add a strict mode to never return stale data, but what would be the point?
 */
function get (...models) {
    // First return anything that's cached
    var missed = new Set();
    models.forEach(function (model) {
        if (!model.$local) {
            if (model.uuid && DATA.hasOwnProperty(model.uuid)) {
                model.onLoad(DATA[model.uuid].value);
                callWaiters(model);

                if (DATA[model.uuid].stale) {
                    missed.add(model);
                }
            } else {
                missed.add(model);
            }
        }
    });

    // Filter missed by excluding uuid's already inflight
    let needs = new Set([...missed].filter(x => !INFLIGHT.has(x.uuid)));

    if (HOLDING) {
        // Holding, just push back everything to the hold queue.
        HOLD_QUEUE = HOLD_QUEUE.concat([...needs]);
    } else {
        processQueue([...needs]);
    }
}

function set (model, cacheArgs) {
    DATA[model.uuid] = {stale: false, value: cacheArgs};
    INFLIGHT.delete(model.uuid);
}

function invalidate (model) {
    if (DATA.hasOwnProperty(model.uuid)) {
        DATA[model.uuid].stale = true;
    }
}

function hold () {
    HOLDING = true;
}

function release () {
    HOLDING = false;
    if (HOLD_QUEUE.length > 0) {
        var models = HOLD_QUEUE.slice(0);
        HOLD_QUEUE.length = 0;
        processQueue(models);
    }
}

function processQueue(models) {
    // Group the models into classes. We can't use constructor.name since its not guaranteed to exist,
    // but we can compare constructors to check for class equivalence instead.
    var bucketHandles = [];
    var buckets = {};

    models.forEach(function (model) {
        var thisHandle = model.constructor, i;
        for (i = 0; i < bucketHandles.length; i++) {
            if (bucketHandles[i] === thisHandle) break;
        }

        if (i == bucketHandles.length) {
            bucketHandles.push(thisHandle);
            buckets[i] = [model];
        } else {
            buckets[i].push(model);
        }

        // Add to INFLIGHT set
        INFLIGHT.add(model.uuid);
    });

    // Load from remote then invalidate
    Promise.all(bucketHandles.map((cls, i) => cls.loadFromRemote(...buckets[i]))).then(() => {
        // For all models that are loaded, call waiters
        models.forEach(model => {
            if (model.$loaded) {
                callWaiters(model);
            }
        });

        Global.requestInvalidate();
    });
}
<commit_msg>Add debugging hooks.<commit_after>import Global from './global';

export default {
    hold: hold,
    release: release,
    get: get,
    set: set,
    invalidate: invalidate,
    waitFor: waitFor,

    // Debugging hooks
    _inspect: _inspect
}

var DATA = {},              // uuid => {stale: false/true, value: object data (whatever Model.loadFromRemote returns)}
    HOLDING = false,
    HOLD_QUEUE = [],
    INFLIGHT = new Set(),
    WAITERS = {};           // uuid => fn

function _inspect () {
    return DATA;
}

function waitFor (model, fn) {
    if (!WAITERS.hasOwnProperty(model.uuid)) {
        WAITERS[model.uuid] = [];
    }
    WAITERS[model.uuid].push(fn);
}

function callWaiters (model) {
    if (WAITERS.hasOwnProperty(model.uuid)) {
        let waiters = WAITERS[model.uuid].slice();
        WAITERS[model.uuid].length = 0;
        waiters.forEach(fn => fn());
    }
}

/**
 * TODO: Default behavior is to look at DATA::valid and return stale data anyways (while dispatching to remote).
 * Perhaps we can add a strict mode to never return stale data, but what would be the point?
 */
function get (...models) {
    // First return anything that's cached
    var missed = new Set();
    models.forEach(function (model) {
        if (!model.$local) {
            if (model.uuid && DATA.hasOwnProperty(model.uuid)) {
                model.onLoad(DATA[model.uuid].value);
                callWaiters(model);

                if (DATA[model.uuid].stale) {
                    missed.add(model);
                }
            } else {
                missed.add(model);
            }
        }
    });

    // Filter missed by excluding uuid's already inflight
    let needs = new Set([...missed].filter(x => !INFLIGHT.has(x.uuid)));

    if (HOLDING) {
        // Holding, just push back everything to the hold queue.
        HOLD_QUEUE = HOLD_QUEUE.concat([...needs]);
    } else {
        processQueue([...needs]);
    }
}

function set (model, cacheArgs) {
    DATA[model.uuid] = {stale: false, value: cacheArgs};
    INFLIGHT.delete(model.uuid);
}

function invalidate (model) {
    if (DATA.hasOwnProperty(model.uuid)) {
        DATA[model.uuid].stale = true;
    }
}

function hold () {
    HOLDING = true;
}

function release () {
    HOLDING = false;
    if (HOLD_QUEUE.length > 0) {
        var models = HOLD_QUEUE.slice(0);
        HOLD_QUEUE.length = 0;
        processQueue(models);
    }
}

function processQueue(models) {
    // Group the models into classes. We can't use constructor.name since its not guaranteed to exist,
    // but we can compare constructors to check for class equivalence instead.
    var bucketHandles = [];
    var buckets = {};

    models.forEach(function (model) {
        var thisHandle = model.constructor, i;
        for (i = 0; i < bucketHandles.length; i++) {
            if (bucketHandles[i] === thisHandle) break;
        }

        if (i == bucketHandles.length) {
            bucketHandles.push(thisHandle);
            buckets[i] = [model];
        } else {
            buckets[i].push(model);
        }

        // Add to INFLIGHT set
        INFLIGHT.add(model.uuid);
    });

    // Load from remote then invalidate
    Promise.all(bucketHandles.map((cls, i) => cls.loadFromRemote(...buckets[i]))).then(() => {
        // For all models that are loaded, call waiters
        models.forEach(model => {
            if (model.$loaded) {
                callWaiters(model);
            }
        });

        Global.requestInvalidate();
    });
}
<|endoftext|>