<commit_before>'use strict'
var Event = require('../event')

exports.properties = {
  triggerEvent: { val: true }
}

exports.define = {
  getTriggerEvent: function (key) {
    return this.triggerEvent
  },
  emit: function (event, meta, bind, key, ignore) {
    var trigger

    if (event === false) {
      return
    }

    if (event === void 0) {
      if (ignore) {
        return
      }
      if (!key) {
        key = this.key
      }
      event = new Event(this, key)
      trigger = true
    }

    if (
      (trigger ||
      event.origin === this &&
      event.type === key &&
      event.context == this._context) &&
      !event.isTriggered
    ) {
      if (this.getTriggerEvent(key)) {
        trigger = event.isTriggered = true
      }
    }

    if (this.emitInternal(event, bind, meta, key, trigger, ignore)) {
      event.trigger()
    }

    return this
  },
  emitInternal: function (event, bind, meta, key, trigger, ignore) {
    this.push(bind, event.push(this))
    return trigger
  }
}
<commit_msg>cleaning up<commit_after>'use strict'
var Event = require('../event')

exports.properties = {
  triggerEvent: { val: true }
}

exports.define = {
  getTriggerEvent: function (key) {
    return this.triggerEvent
  },
  emit: function (event, meta, bind, key, ignore) {
    // do last stamp check hier saves calls

    var trigger

    if (event === false) {
      return
    }

    if (event === void 0) {
      if (ignore) {
        return
      }
      if (!key) {
        key = this.key
      }
      event = new Event(this, key)
      trigger = true
    }

    if (
      !event.isTriggered &&
      (trigger ||
      event.origin === this &&
      event.type === key &&
      // JSstandard: want to use type coercion check here
      event.context == this._context)
    ) {
      if (this.getTriggerEvent(key)) {
        trigger = event.isTriggered = true
      }
    }

    if (this.emitInternal(event, bind, meta, key, trigger, ignore)) {
      event.trigger()
    }

    return this
  },
  emitInternal: function (event, bind, meta, key, trigger, ignore) {
    this.push(bind, event.push(this))
    return trigger
  }
}
<|endoftext|>


<commit_before>/**
 * Created by ema.ingkoul on 22/01/14.
 */
var calendar = {
    createEvent: function(title, location, notes, startDate, endDate, successCallback, errorCallback){
    cordova.exec(
        successCallback, // success callback function
        errorCallback, // error callback function
        'Calendar', // mapped to our native Java class called "Calendar"
        'addCalendarEntry', // with this action name
        [{                  // and this array of custom arguments to create our entry
            "title": title,
            "description": notes,
            "eventLocation": location,
            "startTimeMillis": startDate.getTime(),
            "endTimeMillis": endDate.getTime()
        }]
    );
}
}
module.exports = calendar;
<commit_msg>Delete Calendar.js<commit_after><|endoftext|>


<commit_before>/*
 * sweave.js
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */
define("mode/sweave", ["require", "exports", "module"], function(require, exports, module) {

var oop = require("ace/lib/oop");
var TextMode = require("ace/mode/text").Mode;
var Tokenizer = require("ace/tokenizer").Tokenizer;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var BackgroundHighlighter = require("mode/background_highlighter").BackgroundHighlighter;
var SweaveHighlightRules = require("mode/sweave_highlight_rules").SweaveHighlightRules;
var RCodeModel = require("mode/r_code_model").RCodeModel;
var MatchingBraceOutdent = require("ace/mode/matching_brace_outdent").MatchingBraceOutdent;
var RMatchingBraceOutdent = require("mode/r_matching_brace_outdent").RMatchingBraceOutdent;
var unicode = require("ace/unicode");
var Utils = require("mode/utils");

var Mode = function(suppressHighlighting, session) {
   if (suppressHighlighting)
      this.$tokenizer = new Tokenizer(new TextHighlightRules().getRules());
   else
      this.$tokenizer = new Tokenizer(new SweaveHighlightRules().getRules());

   this.$outdent = new MatchingBraceOutdent();

   this.codeModel = new RCodeModel(
      session,
      this.$tokenizer,
      /^r-/,
      /<<(.*?)>>/,
      /^\s*@\s*$/
   );
   this.$r_outdent = new RMatchingBraceOutdent(this.codeModel);

   this.foldingRules = this.codeModel;
   this.$sweaveBackgroundHighlighter = new BackgroundHighlighter(
         session,
         /^\s*<<.*>>=.*$/,
         /^\s*@(?:\s.*)?$/
   );
   this.$session = session;
};
oop.inherits(Mode, TextMode);

(function() {

   this.tokenRe = new RegExp("^["
       + unicode.packages.L
       + unicode.packages.Mn + unicode.packages.Mc
       + unicode.packages.Nd
       + unicode.packages.Pc + "._]+", "g"
   );

   this.nonTokenRe = new RegExp("^(?:[^"
       + unicode.packages.L
       + unicode.packages.Mn + unicode.packages.Mc
       + unicode.packages.Nd
       + unicode.packages.Pc + "._]|\\s])+", "g"
   );

   this.$complements = {
            "(": ")",
            "[": "]",
            '"': '"',
            "'": "'",
            "{": "}"
         };
   this.$reOpen = /^[(["'{]$/;
   this.$reClose = /^[)\]"'}]$/;

   this.insertChunkInfo = {
      value: "<<>>=\n\n@\n",
      position: {row: 0, column: 2}
   };

   this.getLanguageMode = function(position)
   {
      var state = Utils.getPrimaryState(this.$session, position.row);
      return state.match(/^r-/) ? 'R' : 'TeX';
   };

   this.$getNextLineIndent = this.getNextLineIndent;
   this.getNextLineIndent = function(state, line, tab, row)
   {
      var mode = Utils.activeMode(state, "tex");
      if (mode === "r")
         return this.codeModel.getNextLineIndent(state, line, tab, row);
      else
         return this.$getNextLineIndent(state, line, tab);
   };

   this.checkOutdent = function(state, line, input)
   {
      var mode = Utils.activeMode(state, "tex");
      if (mode === "r")
         return this.$r_outdent.checkOutdent(state, line, input);
      else
         return this.$outdent.checkOutdent(line, input);
   };

   this.autoOutdent = function(state, session, row)
   {
      var mode = Utils.activeMode(state, "tex");
      if (mode === "r")
         return this.$r_outdent.autoOutdent(state, session, row);
      else
         return this.$outdent.autoOutdent(session, row);
   };

   this.allowAutoInsert = this.smartAllowAutoInsert;

   this.$id = "mode/sweave";

}).call(Mode.prototype);

exports.Mode = Mode;
});
<commit_msg>ensure 'AutoBraceInsert' initialized for sweave<commit_after>/*
 * sweave.js
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */
define("mode/sweave", ["require", "exports", "module"], function(require, exports, module) {

var oop = require("ace/lib/oop");
var TextMode = require("ace/mode/text").Mode;
var Tokenizer = require("ace/tokenizer").Tokenizer;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var BackgroundHighlighter = require("mode/background_highlighter").BackgroundHighlighter;
var SweaveHighlightRules = require("mode/sweave_highlight_rules").SweaveHighlightRules;
var RCodeModel = require("mode/r_code_model").RCodeModel;
var MatchingBraceOutdent = require("ace/mode/matching_brace_outdent").MatchingBraceOutdent;
var RMatchingBraceOutdent = require("mode/r_matching_brace_outdent").RMatchingBraceOutdent;
var unicode = require("ace/unicode");
var Utils = require("mode/utils");
var AutoBraceInsert = require("mode/auto_brace_insert").AutoBraceInsert;

var Mode = function(suppressHighlighting, session) {
   if (suppressHighlighting)
      this.$tokenizer = new Tokenizer(new TextHighlightRules().getRules());
   else
      this.$tokenizer = new Tokenizer(new SweaveHighlightRules().getRules());

   this.$outdent = new MatchingBraceOutdent();

   this.codeModel = new RCodeModel(
      session,
      this.$tokenizer,
      /^r-/,
      /<<(.*?)>>/,
      /^\s*@\s*$/
   );
   this.$r_outdent = new RMatchingBraceOutdent(this.codeModel);

   this.foldingRules = this.codeModel;
   this.$sweaveBackgroundHighlighter = new BackgroundHighlighter(
         session,
         /^\s*<<.*>>=.*$/,
         /^\s*@(?:\s.*)?$/
   );
   this.$session = session;
};
oop.inherits(Mode, TextMode);

(function() {

   this.tokenRe = new RegExp("^["
       + unicode.packages.L
       + unicode.packages.Mn + unicode.packages.Mc
       + unicode.packages.Nd
       + unicode.packages.Pc + "._]+", "g"
   );

   this.nonTokenRe = new RegExp("^(?:[^"
       + unicode.packages.L
       + unicode.packages.Mn + unicode.packages.Mc
       + unicode.packages.Nd
       + unicode.packages.Pc + "._]|\\s])+", "g"
   );

   this.$complements = {
            "(": ")",
            "[": "]",
            '"': '"',
            "'": "'",
            "{": "}"
         };
   this.$reOpen = /^[(["'{]$/;
   this.$reClose = /^[)\]"'}]$/;

   this.insertChunkInfo = {
      value: "<<>>=\n\n@\n",
      position: {row: 0, column: 2}
   };

   this.getLanguageMode = function(position)
   {
      var state = Utils.getPrimaryState(this.$session, position.row);
      return state.match(/^r-/) ? 'R' : 'TeX';
   };

   this.$getNextLineIndent = this.getNextLineIndent;
   this.getNextLineIndent = function(state, line, tab, row)
   {
      var mode = Utils.activeMode(state, "tex");
      if (mode === "r")
         return this.codeModel.getNextLineIndent(state, line, tab, row);
      else
         return this.$getNextLineIndent(state, line, tab);
   };

   this.checkOutdent = function(state, line, input)
   {
      var mode = Utils.activeMode(state, "tex");
      if (mode === "r")
         return this.$r_outdent.checkOutdent(state, line, input);
      else
         return this.$outdent.checkOutdent(line, input);
   };

   this.autoOutdent = function(state, session, row)
   {
      var mode = Utils.activeMode(state, "tex");
      if (mode === "r")
         return this.$r_outdent.autoOutdent(state, session, row);
      else
         return this.$outdent.autoOutdent(session, row);
   };

   this.allowAutoInsert = this.smartAllowAutoInsert;

   this.$id = "mode/sweave";

}).call(Mode.prototype);

exports.Mode = Mode;
});
<|endoftext|>


<commit_before>/*
 * react pattern engine for patternlab-node - v0.1.0 - 2016
 *
 * Geoffrey Pursell, Brian Muenzenmeyer, and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

/*
 * ENGINE SUPPORT LEVEL:
 *
 * Full + extensions. Partial calls and lineage hunting are supported. Style
 * modifiers and pattern parameters are used to extend the core feature set of
 * React templates.
 *
 */

"use strict";

const fs = require('fs');
const path = require('path');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const Babel = require('babel-core');
const Hogan = require('hogan.js');
const beautify = require('js-beautify');
const cheerio = require('cheerio');

const outputTemplate = Hogan.compile(
  fs.readFileSync(
    path.join(__dirname, './outputTemplate.mustache'),
    'utf8'
  )
);

var engine_react = {
  engine: React,
  engineName: 'react',
  engineFileExtension: '.jsx',

  // hell no
  expandPartials: false,

  // regexes, stored here so they're only compiled once
  findPartialsRE: null,
  findPartialsWithStyleModifiersRE: null,
  findPartialsWithPatternParametersRE: null,
  findListItemsRE: null,
  findPartialRE: null,

  // render it
  renderPattern(pattern, data, partials) {
    try {
      /* eslint-disable no-eval */
      const componentString = pattern.template || pattern.extendedTemplate;
      const nodeComponent = Babel.transform(componentString, {
        presets: [ require('babel-preset-react') ],
        plugins: [ require('babel-plugin-transform-es2015-modules-commonjs') ]
      });
      const runtimeComponent = Babel.transform(componentString, {
        presets: [ require('babel-preset-react') ],
        plugins: [[require('babel-plugin-transform-es2015-modules-umd'), {
          globals: {
            "react": "React"
          }
        }]]
      });
      const Component = React.createFactory(eval(nodeComponent.code));

      return outputTemplate.render({
        patternPartial: pattern.patternPartial,
        json: JSON.stringify(data),
        htmlOutput: ReactDOMServer.renderToStaticMarkup(Component(data)),
        runtimeCode: runtimeComponent.code
      });
    }
    catch (e) {
	    console.log("Error rendering React pattern.", e);
	    return "";
    }
  },

  /**
   * Find regex matches within both pattern strings and pattern objects.
   *
   * @param {string|object} pattern Either a string or a pattern object.
   * @param {object} regex A JavaScript RegExp object.
   * @returns {array|null} An array if a match is found, null if not.
   */
  patternMatcher(pattern, regex) {
    var matches;
    if (typeof pattern === 'string') {
      matches = pattern.match(regex);
    } else if (typeof pattern === 'object' && typeof pattern.template === 'string') {
      matches = pattern.template.match(regex);
    }
    return matches;
  },

  // find and return any {{> template-name }} within pattern
  findPartials(pattern) {
    return [];
  },
  findPartialsWithStyleModifiers(pattern) {
    return [];
  },

  // returns any patterns that match {{> value(foo:"bar") }} or {{>
  // value:mod(foo:"bar") }} within the pattern
  findPartialsWithPatternParameters(pattern) {
    return [];
  },
  findListItems(pattern) {
    return [];
  },

  // given a pattern, and a partial string, tease out the "pattern key" and
  // return it.
  findPartial(partialString) {
    return [];
  },

  rawTemplateCodeFormatter(unformattedString) {
    return beautify(unformattedString, {e4x: true, indent_size: 2});
  },

  renderedCodeFormatter(unformattedString) {
    return unformattedString;
  },

  markupOnlyCodeFormatter(unformattedString, pattern) {
    const $ = cheerio.load(unformattedString);
    return beautify.html($('.reactPatternContainer').html(), {indent_size: 2});
  },

  /**
   * Add custom output files to the pattern output
   * @param {object} patternlab - the global state object
   * @returns {(object|object[])} - an object or array of objects,
   * each with two properties: path, and content
   */
  addOutputFiles(paths, patternlab) {
    return [];
  }
};

module.exports = engine_react;
<commit_msg>comment cleanup<commit_after>/*
 * react pattern engine for patternlab-node - v0.1.0 - 2016
 *
 * Geoffrey Pursell, Brian Muenzenmeyer, and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

"use strict";

const fs = require('fs');
const path = require('path');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const Babel = require('babel-core');
const Hogan = require('hogan.js');
const beautify = require('js-beautify');
const cheerio = require('cheerio');

const outputTemplate = Hogan.compile(
  fs.readFileSync(
    path.join(__dirname, './outputTemplate.mustache'),
    'utf8'
  )
);

var engine_react = {
  engine: React,
  engineName: 'react',
  engineFileExtension: '.jsx',

  // hell no
  expandPartials: false,

  // regexes, stored here so they're only compiled once
  findPartialsRE: null,
  findPartialsWithStyleModifiersRE: null,
  findPartialsWithPatternParametersRE: null,
  findListItemsRE: null,
  findPartialRE: null,

  // render it
  renderPattern(pattern, data, partials) {
    try {
      /* eslint-disable no-eval */
      const componentString = pattern.template || pattern.extendedTemplate;
      const nodeComponent = Babel.transform(componentString, {
        presets: [ require('babel-preset-react') ],
        plugins: [ require('babel-plugin-transform-es2015-modules-commonjs') ]
      });
      const runtimeComponent = Babel.transform(componentString, {
        presets: [ require('babel-preset-react') ],
        plugins: [[require('babel-plugin-transform-es2015-modules-umd'), {
          globals: {
            "react": "React"
          }
        }]]
      });
      const Component = React.createFactory(eval(nodeComponent.code));

      return outputTemplate.render({
        patternPartial: pattern.patternPartial,
        json: JSON.stringify(data),
        htmlOutput: ReactDOMServer.renderToStaticMarkup(Component(data)),
        runtimeCode: runtimeComponent.code
      });
    }
    catch (e) {
	    console.log("Error rendering React pattern.", e);
	    return "";
    }
  },

  /**
   * Find regex matches within both pattern strings and pattern objects.
   *
   * @param {string|object} pattern Either a string or a pattern object.
   * @param {object} regex A JavaScript RegExp object.
   * @returns {array|null} An array if a match is found, null if not.
   */
  patternMatcher(pattern, regex) {
    var matches;
    if (typeof pattern === 'string') {
      matches = pattern.match(regex);
    } else if (typeof pattern === 'object' && typeof pattern.template === 'string') {
      matches = pattern.template.match(regex);
    }
    return matches;
  },

  // find and return any {{> template-name }} within pattern
  findPartials(pattern) {
    return [];
  },
  findPartialsWithStyleModifiers(pattern) {
    return [];
  },

  // returns any patterns that match {{> value(foo:"bar") }} or {{>
  // value:mod(foo:"bar") }} within the pattern
  findPartialsWithPatternParameters(pattern) {
    return [];
  },
  findListItems(pattern) {
    return [];
  },

  // given a pattern, and a partial string, tease out the "pattern key" and
  // return it.
  findPartial(partialString) {
    return [];
  },

  rawTemplateCodeFormatter(unformattedString) {
    return beautify(unformattedString, {e4x: true, indent_size: 2});
  },

  renderedCodeFormatter(unformattedString) {
    return unformattedString;
  },

  markupOnlyCodeFormatter(unformattedString, pattern) {
    const $ = cheerio.load(unformattedString);
    return beautify.html($('.reactPatternContainer').html(), {indent_size: 2});
  },

  /**
   * Add custom output files to the pattern output
   * @param {object} patternlab - the global state object
   * @returns {(object|object[])} - an object or array of objects,
   * each with two properties: path, and content
   */
  addOutputFiles(paths, patternlab) {
    return [];
  }
};

module.exports = engine_react;
<|endoftext|>


<commit_before>/**
 * Base for all chart types. The methods in Chartist.Base are inherited to all chart types.
 *
 * @module Chartist.Base
 */
/* global Chartist */
(function(window, document, Chartist) {
  'use strict';

  // TODO: Currently we need to re-draw the chart on window resize. This is usually very bad and will affect performance.
  // This is done because we can't work with relative coordinates when drawing the chart because SVG Path does not
  // work with relative positions yet. We need to check if we can do a viewBox hack to switch to percentage.
  // See http://mozilla.6506.n7.nabble.com/Specyfing-paths-with-percentages-unit-td247474.html
  // Update: can be done using the above method tested here: http://codepen.io/gionkunz/pen/KDvLj
  // The problem is with the label offsets that can't be converted into percentage and affecting the chart container
  /**
   * Updates the chart which currently does a full reconstruction of the SVG DOM
   *
   * @param {Object} [data] Optional data you'd like to set for the chart before it will update. If not specified the update method will use the data that is already configured with the chart.
   * @memberof Chartist.Base
   */
  function update(data) {
    this.data = data || this.data;
    this.createChart(this.optionsProvider.currentOptions);
    return this;
  }

  /**
   * This method can be called on the API object of each chart and will un-register all event listeners that were added to other components. This currently includes a window.resize listener as well as media query listeners if any responsive options have been provided. Use this function if you need to destroy and recreate Chartist charts dynamically.
   *
   * @memberof Chartist.Base
   */
  function detach() {
    window.removeEventListener('resize', this.resizeListener);
    this.optionsProvider.removeMediaQueryListeners();
    return this;
  }

  /**
   * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop.
   *
   * @memberof Chartist.Base
   * @param {String} event Name of the event. Check the examples for supported events.
   * @param {Function} handler The handler function that will be called when an event with the given name was emitted. This function will receive a data argument which contains event data. See the example for more details.
   */
  function on(event, handler) {
    this.eventEmitter.addEventHandler(event, handler);
    return this;
  }

  /**
   * Use this function to un-register event handlers. If the handler function parameter is omitted all handlers for the given event will be un-registered.
   *
   * @memberof Chartist.Base
   * @param {String} event Name of the event for which a handler should be removed
   * @param {Function} [handler] The handler function that that was previously used to register a new event handler. This handler will be removed from the event handler list. If this parameter is omitted then all event handlers for the given event are removed from the list.
   */
  function off(event, handler) {
    this.eventEmitter.removeEventHandler(event, handler);
    return this;
  }

  function initialize() {
    // Add window resize listener that re-creates the chart
    window.addEventListener('resize', this.resizeListener);

    // Obtain current options based on matching media queries (if responsive options are given)
    // This will also register a listener that is re-creating the chart based on media changes
    this.optionsProvider = Chartist.optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);

    // Before the first chart creation we need to register us with all plugins that are configured
    // Initialize all relevant plugins with our chart object and the plugin options specified in the config
    if(this.options.plugins) {
      this.options.plugins.forEach(function(plugin) {
        if(plugin instanceof Array) {
          plugin[0](this, plugin[1]);
        } else {
          plugin(this);
        }
      }.bind(this));
    }

    // Create the first chart
    this.createChart(this.optionsProvider.currentOptions);

    // As chart is initialized from the event loop now we can reset our timeout reference
    // This is important if the chart gets initialized on the same element twice
    this.initializeTimeoutId = undefined;
  }

  /**
   * Constructor of chart base class.
   *
   * @param query
   * @param data
   * @param options
   * @param responsiveOptions
   * @constructor
   */
  function Base(query, data, options, responsiveOptions) {
    this.container = Chartist.querySelector(query);
    this.data = data;
    this.options = options;
    this.responsiveOptions = responsiveOptions;
    this.eventEmitter = Chartist.EventEmitter();
    this.supportsForeignObject = Chartist.Svg.isSupported('Extensibility');
    this.supportsAnimations = Chartist.Svg.isSupported('AnimationEventsAttribute');
    this.resizeListener = function resizeListener(){
      this.update();
    }.bind(this);

    if(this.container) {
      // If chartist was already initialized in this container we are detaching all event listeners first
      if(this.container.__chartist__) {
        if(this.container.__chartist__.initializeTimeoutId) {
          // If the initializeTimeoutId is still set we can safely assume that the initialization function has not
          // been called yet from the event loop. Therefore we should cancel the timeout and don't need to detach
          window.clearTimeout(this.container.__chartist__.initializeTimeoutId);
        } else {
          // The timeout reference has already been reset which means we need to detach the old chart first
          this.container.__chartist__.detach();
        }
      }

      this.container.__chartist__ = this;
    }

    // Using event loop for first draw to make it possible to register event listeners in the same call stack where
    // the chart was created.
    this.initializeTimeoutId = setTimeout(initialize.bind(this), 0);
  }

  // Creating the chart base class
  Chartist.Base = Chartist.Class.extend({
    constructor: Base,
    optionsProvider: undefined,
    container: undefined,
    svg: undefined,
    eventEmitter: undefined,
    createChart: function() {
      throw new Error('Base chart type can\'t be instantiated!');
    },
    update: update,
    detach: detach,
    on: on,
    off: off,
    version: Chartist.version,
    supportsForeignObject: false
  });

}(window, document, Chartist));
<commit_msg>Add options param to update() to extend options<commit_after>/**
 * Base for all chart types. The methods in Chartist.Base are inherited to all chart types.
 *
 * @module Chartist.Base
 */
/* global Chartist */
(function(window, document, Chartist) {
  'use strict';

  // TODO: Currently we need to re-draw the chart on window resize. This is usually very bad and will affect performance.
  // This is done because we can't work with relative coordinates when drawing the chart because SVG Path does not
  // work with relative positions yet. We need to check if we can do a viewBox hack to switch to percentage.
  // See http://mozilla.6506.n7.nabble.com/Specyfing-paths-with-percentages-unit-td247474.html
  // Update: can be done using the above method tested here: http://codepen.io/gionkunz/pen/KDvLj
  // The problem is with the label offsets that can't be converted into percentage and affecting the chart container
  /**
   * Updates the chart which currently does a full reconstruction of the SVG DOM
   *
   * @param {Object} [data] Optional data you'd like to set for the chart before it will update. If not specified the update method will use the data that is already configured with the chart.
   * @param {Object} [options] Optional options you'd like to add to the previous options for the chart before it will update. If not specified the update method will use the options that have been already configured with the chart.
   * @memberof Chartist.Base
   */
  function update(data, options) {
    this.data = data || this.data;
    if (typeof options !== 'undefined') {
      this.options = Chartist.extend({}, this.options, options);
      this.optionsProvider = Chartist.optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);
    }
    this.createChart(this.optionsProvider.currentOptions);
    return this;
  }

  /**
   * This method can be called on the API object of each chart and will un-register all event listeners that were added to other components. This currently includes a window.resize listener as well as media query listeners if any responsive options have been provided. Use this function if you need to destroy and recreate Chartist charts dynamically.
   *
   * @memberof Chartist.Base
   */
  function detach() {
    window.removeEventListener('resize', this.resizeListener);
    this.optionsProvider.removeMediaQueryListeners();
    return this;
  }

  /**
   * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop.
   *
   * @memberof Chartist.Base
   * @param {String} event Name of the event. Check the examples for supported events.
   * @param {Function} handler The handler function that will be called when an event with the given name was emitted. This function will receive a data argument which contains event data. See the example for more details.
   */
  function on(event, handler) {
    this.eventEmitter.addEventHandler(event, handler);
    return this;
  }

  /**
   * Use this function to un-register event handlers. If the handler function parameter is omitted all handlers for the given event will be un-registered.
   *
   * @memberof Chartist.Base
   * @param {String} event Name of the event for which a handler should be removed
   * @param {Function} [handler] The handler function that that was previously used to register a new event handler. This handler will be removed from the event handler list. If this parameter is omitted then all event handlers for the given event are removed from the list.
   */
  function off(event, handler) {
    this.eventEmitter.removeEventHandler(event, handler);
    return this;
  }

  function initialize() {
    // Add window resize listener that re-creates the chart
    window.addEventListener('resize', this.resizeListener);

    // Obtain current options based on matching media queries (if responsive options are given)
    // This will also register a listener that is re-creating the chart based on media changes
    this.optionsProvider = Chartist.optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);

    // Before the first chart creation we need to register us with all plugins that are configured
    // Initialize all relevant plugins with our chart object and the plugin options specified in the config
    if(this.options.plugins) {
      this.options.plugins.forEach(function(plugin) {
        if(plugin instanceof Array) {
          plugin[0](this, plugin[1]);
        } else {
          plugin(this);
        }
      }.bind(this));
    }

    // Create the first chart
    this.createChart(this.optionsProvider.currentOptions);

    // As chart is initialized from the event loop now we can reset our timeout reference
    // This is important if the chart gets initialized on the same element twice
    this.initializeTimeoutId = undefined;
  }

  /**
   * Constructor of chart base class.
   *
   * @param query
   * @param data
   * @param options
   * @param responsiveOptions
   * @constructor
   */
  function Base(query, data, options, responsiveOptions) {
    this.container = Chartist.querySelector(query);
    this.data = data;
    this.options = options;
    this.responsiveOptions = responsiveOptions;
    this.eventEmitter = Chartist.EventEmitter();
    this.supportsForeignObject = Chartist.Svg.isSupported('Extensibility');
    this.supportsAnimations = Chartist.Svg.isSupported('AnimationEventsAttribute');
    this.resizeListener = function resizeListener(){
      this.update();
    }.bind(this);

    if(this.container) {
      // If chartist was already initialized in this container we are detaching all event listeners first
      if(this.container.__chartist__) {
        if(this.container.__chartist__.initializeTimeoutId) {
          // If the initializeTimeoutId is still set we can safely assume that the initialization function has not
          // been called yet from the event loop. Therefore we should cancel the timeout and don't need to detach
          window.clearTimeout(this.container.__chartist__.initializeTimeoutId);
        } else {
          // The timeout reference has already been reset which means we need to detach the old chart first
          this.container.__chartist__.detach();
        }
      }

      this.container.__chartist__ = this;
    }

    // Using event loop for first draw to make it possible to register event listeners in the same call stack where
    // the chart was created.
    this.initializeTimeoutId = setTimeout(initialize.bind(this), 0);
  }

  // Creating the chart base class
  Chartist.Base = Chartist.Class.extend({
    constructor: Base,
    optionsProvider: undefined,
    container: undefined,
    svg: undefined,
    eventEmitter: undefined,
    createChart: function() {
      throw new Error('Base chart type can\'t be instantiated!');
    },
    update: update,
    detach: detach,
    on: on,
    off: off,
    version: Chartist.version,
    supportsForeignObject: false
  });

}(window, document, Chartist));
<|endoftext|>


<commit_before>'use strict';

let EPGPCharacter = require('./models/character');
let EPGPItem = require('./models/item');
let EPGPRaid = require('./models/raid');
let characterService = require('../character/service');
let guildService = require('../guild/service');
let _ = require('lodash');
let ItemString = require('wow-itemstring');

function getEPGP(guildId, characterName) {
  return new Promise((resolve, reject) => {
    characterService
      .getCharacters(guildId, characterName)
      .then((character) => {
        if(!character) {
          reject({error: {message: `Unable to find character: ${character}`}});
        }

        EPGPCharacter
          .find({characterId: character._id})
          .exec()
          .then((epgpData) => {
            resolve(epgpData);
          }, (err) => {
            reject({error: {message: err}});
          });
      }, (err) => {
        reject({error: {message: err}});
      });
  });
}

function getLoot(guildId, raidDate) {
  return new Promise((resolve, reject) => {
    let LATEST = 'latest';
    let populateItemPromises = [];
    let raids = [];
    let raidIndex = 0;

    getRaids(guildId)
      .then((raidData) => {
        let query = null;
        raids = raidData;

        if (raids.length === 0) {
          return reject({error: {message: 'No raids have been uploaded yet.'}});
        }

        let raidId = raids[0]._id;

        if (raidDate !== LATEST) {
          raidIndex = _.findIndex(raids, {raidDate: raidDate});

          if (raidIndex === -1) {
            return reject({error: {message: 'Unable to find loot for the requested raid.'}});
          }

          raidId = raids[raidIndex]._id;
        }

        return EPGPItem
          .find({raidId: raidId})
          .populate({
            path: 'characterId',
            select: 'name'
          })
          .populate({
            path: 'itemId',
            select: 'item' // 'name context level itemLevel stats quality icon isWeapon weaponInfo itemClass inventoryType'
          })
          .exec();
      }, (err) => {
        reject({error: {message: err}});
      })
      .then((items) => {
        if (raidIndex === -1) {
          return Promise.reject();
        }

        _.forEach(items, (item) => {

          populateItemPromises.push(
            new Promise((resolve, reject) => {
              new ItemString()
                .populate(item.itemId.item)
                .then((itemObj) => {

                  resolve({
                    characterId: item.characterId,
                    cost: item.cost,
                    raidId: item.raidId,
                    timestamp: item.timestamp,
                    itemId: {
                      itemClass: itemObj.getClass(),
                      context: itemObj.getContext(),
                      icon: itemObj.getIcon(),
                      id: itemObj.getId(),
                      inventoryType: itemObj.getInventoryType(),
                      isItemSet: itemObj.isItemSet(),
                      isWeapon: itemObj.isWeapon(),
                      itemLevel: itemObj.getItemLevel(),
                      itemSet: itemObj.getItemSet(),
                      itemString: itemObj._itemString,
                      level: itemObj.getLevel(),
                      name: itemObj.getName(),
                      quality: itemObj.getQuality(),
                      stats: itemObj.getStats(),
                      weaponInfo: itemObj.getWeaponInfo()
                    }
                  });
                }, (err) => {
                  reject({error: {message: err}});
                });
            })
          );
        });

        return Promise.all(populateItemPromises);
      }, (err) => {
        reject({error: {message: err}});
      })
      .then((items) => {
        if (raidIndex === -1) {
          reject({error: {message: 'Unable to determine raid index'}});
        }

        resolve({
          nextRaidDate: (raidIndex === 0) ? null : items.nextRaidDate = raids[raidIndex - 1].raidDate,
          prevRaidDate: (raidIndex === raids.length - 1) ? null : items.nextRaidDate = raids[raidIndex + 1].raidDate,
          raidDate: raids[raidIndex].raidDate,
          items: items
        });
      }, (err) => {
        reject({error: {message: err}});
      });
  });
}

function getMembersEPGP(guildId, ranks) {
  return new Promise((resolve, reject) => {
    characterService
      .getCharacters(guildId)
      .then((character) => {

        let populate = {
          path: 'characterId',
          select: 'name rank thumbnail level gender race class items spec'
        };

        if (ranks) {
          let parsed = ranks.split(',');

          populate.match = {
            rank: { $in: parsed }
          }
        }

        return EPGPCharacter
          .find()
          .populate(populate)
          .exec();
      }, (err) => {
        reject({error: {message: err}});
      })
      .then((epgpData) => {
        resolve(
          _.sortBy(
            _.filter(epgpData, (o) => { return o.characterId; }),
            function(item) {
              return [item.characterId.name];
            }
          )
        );
      }, (err) => {
        reject({error: {message: err}});
      });
  });
}

function getRaid(guildName, raidDate) {
  return new Promise((resolve, reject) => {
    guildService
      .getGuild(guildName)
      .then((guild) => {
        if(!guild) {
          reject({error: {message: `Unable to find guild: ${guildName}`}});
        }

        return EPGPRaid
          .findOne({raidDate: raidDate})
          .exec();
      })
      .then((raid) => {
        resolve(raid);
      }, (err) => {
        reject({error: {message: err}});
      });
  });
};

function getRaids(guildId) {
  return EPGPRaid
          .find()
          .sort('-raidDate')
          .exec();
};

function getRaidersEPGP(guildId) {
  return new Promise((resolve, reject) => {
    characterService
      .getCharacters(guildId)
      .then((characters) => {

        return EPGPCharacter
          .find()
          .populate({
            path: 'characterId',
            select: 'name rank thumbnail level gender race class items spec',
            match: {
              rank: { $in: [0, 1, 4, 5] }
            }
          })
          .exec();
      }, (err) => {
        reject({error: {message: err}});
      })
      .then((epgpData) => {
        resolve(
          _.sortBy(
            _.filter(epgpData, (o) => { return o.characterId; }),
            function(item) {
              return [item.characterId.name];
            }
          )
        );
      }, (err) => {
        reject({error: {message: err}});
      });
  });
}

function updateGuildConfig(epgpData) {
  return new Promise((resolve, reject) => {
    resolve(epgpData);
  });
}

module.exports = {
  getEPGP: getEPGP,
  getLoot: getLoot,
  getMembersEPGP: getMembersEPGP,
  getRaid: getRaid,
  getRaidersEPGP: getRaidersEPGP,
  updateGuildConfig: updateGuildConfig
};
<commit_msg>Hide isdeleted characters<commit_after>'use strict';

let EPGPCharacter = require('./models/character');
let EPGPItem = require('./models/item');
let EPGPRaid = require('./models/raid');
let characterService = require('../character/service');
let guildService = require('../guild/service');
let _ = require('lodash');
let ItemString = require('wow-itemstring');

function getEPGP(guildId, characterName) {
  return new Promise((resolve, reject) => {
    characterService
      .getCharacters(guildId, characterName)
      .then((character) => {
        if(!character) {
          reject({error: {message: `Unable to find character: ${character}`}});
        }

        EPGPCharacter
          .find({characterId: character._id})
          .exec()
          .then((epgpData) => {
            resolve(epgpData);
          }, (err) => {
            reject({error: {message: err}});
          });
      }, (err) => {
        reject({error: {message: err}});
      });
  });
}

function getLoot(guildId, raidDate) {
  return new Promise((resolve, reject) => {
    let LATEST = 'latest';
    let populateItemPromises = [];
    let raids = [];
    let raidIndex = 0;

    getRaids(guildId)
      .then((raidData) => {
        let query = null;
        raids = raidData;

        if (raids.length === 0) {
          return reject({error: {message: 'No raids have been uploaded yet.'}});
        }

        let raidId = raids[0]._id;

        if (raidDate !== LATEST) {
          raidIndex = _.findIndex(raids, {raidDate: raidDate});

          if (raidIndex === -1) {
            return reject({error: {message: 'Unable to find loot for the requested raid.'}});
          }

          raidId = raids[raidIndex]._id;
        }

        return EPGPItem
          .find({raidId: raidId})
          .populate({
            path: 'characterId',
            select: 'name'
          })
          .populate({
            path: 'itemId',
            select: 'item' // 'name context level itemLevel stats quality icon isWeapon weaponInfo itemClass inventoryType'
          })
          .exec();
      }, (err) => {
        reject({error: {message: err}});
      })
      .then((items) => {
        if (raidIndex === -1) {
          return Promise.reject();
        }

        _.forEach(items, (item) => {

          populateItemPromises.push(
            new Promise((resolve, reject) => {
              new ItemString()
                .populate(item.itemId.item)
                .then((itemObj) => {

                  resolve({
                    characterId: item.characterId,
                    cost: item.cost,
                    raidId: item.raidId,
                    timestamp: item.timestamp,
                    itemId: {
                      itemClass: itemObj.getClass(),
                      context: itemObj.getContext(),
                      icon: itemObj.getIcon(),
                      id: itemObj.getId(),
                      inventoryType: itemObj.getInventoryType(),
                      isItemSet: itemObj.isItemSet(),
                      isWeapon: itemObj.isWeapon(),
                      itemLevel: itemObj.getItemLevel(),
                      itemSet: itemObj.getItemSet(),
                      itemString: itemObj._itemString,
                      level: itemObj.getLevel(),
                      name: itemObj.getName(),
                      quality: itemObj.getQuality(),
                      stats: itemObj.getStats(),
                      weaponInfo: itemObj.getWeaponInfo()
                    }
                  });
                }, (err) => {
                  reject({error: {message: err}});
                });
            })
          );
        });

        return Promise.all(populateItemPromises);
      }, (err) => {
        reject({error: {message: err}});
      })
      .then((items) => {
        if (raidIndex === -1) {
          reject({error: {message: 'Unable to determine raid index'}});
        }

        resolve({
          nextRaidDate: (raidIndex === 0) ? null : items.nextRaidDate = raids[raidIndex - 1].raidDate,
          prevRaidDate: (raidIndex === raids.length - 1) ? null : items.nextRaidDate = raids[raidIndex + 1].raidDate,
          raidDate: raids[raidIndex].raidDate,
          items: items
        });
      }, (err) => {
        reject({error: {message: err}});
      });
  });
}

function getMembersEPGP(guildId, ranks) {
  return new Promise((resolve, reject) => {
    characterService
      .getCharacters(guildId)
      .then((character) => {

        let populate = {
          path: 'characterId',
          select: 'name rank thumbnail level gender race class items spec'
        };

        if (ranks) {
          let parsed = ranks.split(',');

          populate.match = {
            rank: { $in: parsed },
            isDeleted: false
          }
        }

        return EPGPCharacter
          .find()
          .populate(populate)
          .exec();
      }, (err) => {
        reject({error: {message: err}});
      })
      .then((epgpData) => {
        resolve(
          _.sortBy(
            _.filter(epgpData, (o) => { return o.characterId; }),
            function(item) {
              return [item.characterId.name];
            }
          )
        );
      }, (err) => {
        reject({error: {message: err}});
      });
  });
}

function getRaid(guildName, raidDate) {
  return new Promise((resolve, reject) => {
    guildService
      .getGuild(guildName)
      .then((guild) => {
        if(!guild) {
          reject({error: {message: `Unable to find guild: ${guildName}`}});
        }

        return EPGPRaid
          .findOne({raidDate: raidDate})
          .exec();
      })
      .then((raid) => {
        resolve(raid);
      }, (err) => {
        reject({error: {message: err}});
      });
  });
};

function getRaids(guildId) {
  return EPGPRaid
          .find()
          .sort('-raidDate')
          .exec();
};

function getRaidersEPGP(guildId) {
  return new Promise((resolve, reject) => {
    characterService
      .getCharacters(guildId)
      .then((characters) => {

        return EPGPCharacter
          .find()
          .populate({
            path: 'characterId',
            select: 'name rank thumbnail level gender race class items spec',
            match: {
              rank: { $in: [0, 1, 4, 5] },
              isDeleted: false
            }
          })
          .exec();
      }, (err) => {
        reject({error: {message: err}});
      })
      .then((epgpData) => {
        resolve(
          _.sortBy(
            _.filter(epgpData, (o) => { return o.characterId; }),
            function(item) {
              return [item.characterId.name];
            }
          )
        );
      }, (err) => {
        reject({error: {message: err}});
      });
  });
}

function updateGuildConfig(epgpData) {
  return new Promise((resolve, reject) => {
    resolve(epgpData);
  });
}

module.exports = {
  getEPGP: getEPGP,
  getLoot: getLoot,
  getMembersEPGP: getMembersEPGP,
  getRaid: getRaid,
  getRaidersEPGP: getRaidersEPGP,
  updateGuildConfig: updateGuildConfig
};
<|endoftext|>


<commit_before>// Description:
//   misc
//
// Commands:
//   hubot poem - オサレポエム
//   hubot 炎上 <text> <text> - ババーン
//   なんだと・・・
//   hubot goma - やればわかる
//   hubot isao - やればわかる
//

"use strict"

const uuid = require("node-uuid");
const json = require('../../settings/poems.json')
const Levenshtein = require("levenshtein");

const gomas = [
    () => `http://yamiga.waka.ru.com/images/goma/01.jpg?cb=${uuid.v4()}`,
    () => `http://yamiga.waka.ru.com/images/goma/02.jpg?cb=${uuid.v4()}`,
    () => `http://yamiga.waka.ru.com/images/goma/03.jpg?cb=${uuid.v4()}`,
    () => `http://yamiga.waka.ru.com/images/goma/04.jpg?cb=${uuid.v4()}`,
    () => `http://yamiga.waka.ru.com/images/goma/05.jpg?cb=${uuid.v4()}`,
    () => "```\n　　　CH \n　　　／＼ \n　　／　＼＼ \nHC／　　　＼＼CH \n ｜｜C6H6　　｜ \n ｜｜　´д｀｜ \nHC＼　　　／／CH \n　　＼　／／ \n　　　＼／ \n　　　CH\n```"
];
const isaos = [
    () => `https://36.media.tumblr.com/3df68abdd9a1eb7a0fbda4dacb9930af/tumblr_ns5chdb0Vm1un4u6lo1_1280.jpg?cb=${uuid.v4()}`,
    () => `https://camo.githubusercontent.com/4a011f97909b89a26822ee21e921eb7012e9df18/68747470733a2f2f34302e6d656469612e74756d626c722e636f6d2f31346231333736396364336238303235623163653338626238626238626261352f74756d626c725f6e75313538697269536c31756e3475366c6f315f313238302e6a7067?cb=${uuid.v4()}`
];

module.exports = (robot) => {

    robot.respond(/poem$/i, (res) => {
        res.send(res.random(json.poem))
    })

    robot.hear(/なん(\.|。|・)*だと(\.|。|・)*$/i, (res) => {
        res.send(`http://yamiga.waka.ru.com/images/nandato.png?cb=${uuid.v4()}`);
    })

    robot.respond(/炎上 (.+) (.+)/i, (res) => {
        const text1 = encodeURIComponent(res.match[1])
        const text2 = encodeURIComponent(res.match[2])
        res.send(`https://enjo-generator.herokuapp.com/api/create-enjo?text1=${text1}&text2=${text2}`);
    })

    robot.respond(/距離 (.+) (.+)/i, (res) => {
        const l = new Levenshtein(res.match[1],res.match[2]);
        res.send(`距離: ${l.distance}`);
    });

    robot.respond(/goma$/i, (res) => {
        res.send((res.random(gomas))())
    })

    robot.respond(/isao$/i, (res) => {
        res.send((res.random(isaos))())
    })

    robot.respond(/PAPIX$/i, (res) => {
        const req = robot.http("https://ngineerxiv-dark.appspot.com/api/v1/kusokora").get();
        req((err, response, body) => {
            err && hubot.logger.error(err);
            const json = JSON.parse(body);
            if( json.kusokora ) {
                const url = res.random(json.kusokora);
                res.send(`${url}?cb=${uuid.v4()}`);
            } else {
                res.send("ray ruby `curl -X POST https://ngineerxiv-dark.appspot.com/api/v1/kusokora -H 'Content-Length: 0'`");
            }

        });
    });

}
<commit_msg>Fix query params<commit_after>// Description:
//   misc
//
// Commands:
//   hubot poem - オサレポエム
//   hubot 炎上 <text> <text> - ババーン
//   なんだと・・・
//   hubot goma - やればわかる
//   hubot isao - やればわかる
//

"use strict"

const uuid = require("node-uuid");
const json = require('../../settings/poems.json')
const Levenshtein = require("levenshtein");

const gomas = [
    () => `http://yamiga.waka.ru.com/images/goma/01.jpg?cb=${uuid.v4()}`,
    () => `http://yamiga.waka.ru.com/images/goma/02.jpg?cb=${uuid.v4()}`,
    () => `http://yamiga.waka.ru.com/images/goma/03.jpg?cb=${uuid.v4()}`,
    () => `http://yamiga.waka.ru.com/images/goma/04.jpg?cb=${uuid.v4()}`,
    () => `http://yamiga.waka.ru.com/images/goma/05.jpg?cb=${uuid.v4()}`,
    () => "```\n　　　CH \n　　　／＼ \n　　／　＼＼ \nHC／　　　＼＼CH \n ｜｜C6H6　　｜ \n ｜｜　´д｀｜ \nHC＼　　　／／CH \n　　＼　／／ \n　　　＼／ \n　　　CH\n```"
];
const isaos = [
    () => `https://36.media.tumblr.com/3df68abdd9a1eb7a0fbda4dacb9930af/tumblr_ns5chdb0Vm1un4u6lo1_1280.jpg?cb=${uuid.v4()}`,
    () => `https://camo.githubusercontent.com/4a011f97909b89a26822ee21e921eb7012e9df18/68747470733a2f2f34302e6d656469612e74756d626c722e636f6d2f31346231333736396364336238303235623163653338626238626238626261352f74756d626c725f6e75313538697269536c31756e3475366c6f315f313238302e6a7067?cb=${uuid.v4()}`
];

module.exports = (robot) => {

    robot.respond(/poem$/i, (res) => {
        res.send(res.random(json.poem))
    })

    robot.hear(/なん(\.|。|・)*だと(\.|。|・)*$/i, (res) => {
        res.send(`http://yamiga.waka.ru.com/images/nandato.png?cb=${uuid.v4()}`);
    })

    robot.respond(/炎上 (.+) (.+)/i, (res) => {
        const text1 = encodeURIComponent(res.match[1])
        const text2 = encodeURIComponent(res.match[2])
        res.send(`https://enjo-generator.herokuapp.com/api/create-enjo?text1=${text1}&text2=${text2}`);
    })

    robot.respond(/距離 (.+) (.+)/i, (res) => {
        const l = new Levenshtein(res.match[1],res.match[2]);
        res.send(`距離: ${l.distance}`);
    });

    robot.respond(/goma$/i, (res) => {
        res.send((res.random(gomas))())
    })

    robot.respond(/isao$/i, (res) => {
        res.send((res.random(isaos))())
    })

    robot.respond(/PAPIX$/i, (res) => {
        const req = robot.http("https://ngineerxiv-dark.appspot.com/api/v1/kusokora").get();
        req((err, response, body) => {
            err && hubot.logger.error(err);
            const json = JSON.parse(body);
            if( json.kusokora ) {
                const url = res.random(json.kusokora);
                res.send(`${url}#cb=${uuid.v4()}`);
            } else {
                res.send("ray ruby `curl -X POST https://ngineerxiv-dark.appspot.com/api/v1/kusokora -H 'Content-Length: 0'`");
            }

        });
    });

}
<|endoftext|>


<commit_before>(function() {
  let currentService, currentPlatform;

  const serviceLinks = $$('.service-select a');
  const platformLinks = $$('.platform-select a');

  // Header animation
  setInterval(function() {
    let serviceLink = serviceLinks[Math.floor(Math.random()*serviceLinks.length)];
    let platformLink = platformLinks[Math.floor(Math.random()*platformLinks.length)];
    $('.getstarted-heading__service').innerHTML = serviceLink.getAttribute('data-name');
    $('.getstarted-heading__platform').innerHTML = platformLink.getAttribute('data-name');
  }, 1000)

  // Steps with Markdown docs
  let initialSetup = function (links, type) {
    for (let i = links.length - 1; i >= 0; i--) {
      links[i].addEventListener('click', function (e) {
        e.preventDefault();
        if(type === 'service') currentService = {name: e.currentTarget.getAttribute('data-name'), doc: e.currentTarget.getAttribute('data-doc')};
        if(type === 'platform') currentPlatform = {name: e.currentTarget.getAttribute('data-name'), doc: e.currentTarget.getAttribute('data-doc')};
        nextStep();
      });
    }
  }

  initialSetup(serviceLinks, 'service');
  initialSetup(platformLinks, 'platform');

  $('.step1').setAttribute('style', 'pointer-events: none;');
  $('.step2').setAttribute('style', 'pointer-events: none;');

  $('.step1').addEventListener('click', function(e) {
    e.preventDefault();
    $('.step1').setAttribute('style', 'pointer-events: none;');
    $('.step2').setAttribute('style', 'pointer-events: none;');
    $('.step1 h3').innerHTML = 'Select a service';
    $('.step2 h3').innerHTML = 'Select a platform';

    $('.service-select').removeAttribute('style');
    $('.platform-select').setAttribute('style', 'display: none;');
    $('.install').setAttribute('style', 'display: none;');

    $('.step1').removeClassName('step-inactive');
    $('.step2').addClassName('step-inactive');
    $('.step3').addClassName('step-inactive');

    currentService = undefined;
    currentPlatform = undefined;
  });

  $('.step2').addEventListener('click', function(e) {
    e.preventDefault();
    $('.step2').setAttribute('style', 'pointer-events: none;');
    $('.step2 h3').innerHTML = 'Select a platform';

    $('.platform-select').removeAttribute('style');
    $('.install').setAttribute('style', 'display: none;');

    $('.step2').removeClassName('step-inactive');
    $('.step3').addClassName('step-inactive');

    currentPlatform = undefined;
  });

  let getDocs = function(servicePath, platformPath) {
    return new Promise(function(resolve, reject) {
      let serviceDoc, platformDoc;
      let gotADoc = function () {
        if(serviceDoc != undefined && platformDoc != undefined) resolve({service: serviceDoc, platform: platformDoc});
      }

      fetch(`/docs/${servicePath}`)
        .then(response => response.text())
        .then(body => {
          serviceDoc = body;
          gotADoc()
        })

      fetch(`/docs/${platformPath}`)
        .then(response => response.text())
        .then(body => {
          platformDoc = body;
          gotADoc()
        })
    })
  }

  let nextStep = function () {
    if(currentService != undefined && currentPlatform === undefined) {
      // show platform
      $('.service-select').setAttribute('style', 'display: none;');
      $('.platform-select').removeAttribute('style');
      $('.install').setAttribute('style', 'display: none;');
      $('.step1').removeAttribute('style');

      $('.step1').addClassName('step-inactive');
      $('.step2').removeClassName('step-inactive');
      $('.step1 h3').innerHTML = currentService.name;
    } else if(currentService != undefined && currentPlatform != undefined) {
      // show docs
      $('.service-select').setAttribute('style', 'display: none;');
      $('.platform-select').setAttribute('style', 'display: none;');
      $('.install').removeAttribute('style');
      $('.step2').removeAttribute('style');

      $('.step2').addClassName('step-inactive');
      $('.step3').removeClassName('step-inactive');
      $('.step2 h3').innerHTML = currentPlatform.name;

      getDocs(currentService.doc, currentPlatform.doc)
        .then(docs => {
          $('.install').innerHTML = `${docs.service}\n${docs.platform}`;
        })
    }
  }

})();

Element.prototype.hasClassName = function(name) {
  return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)").test(this.className);
};

Element.prototype.addClassName = function(name) {
  if (!this.hasClassName(name)) {
    this.className = this.className ? [this.className, name].join(' ') : name;
  }
};

Element.prototype.removeClassName = function(name) {
  if (this.hasClassName(name)) {
    var c = this.className;
    this.className = c.replace(new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g"), "");
  }
};<commit_msg>Add routes<commit_after>Element.prototype.hasClassName = function(name) {
  return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)").test(this.className);
};

Element.prototype.addClassName = function(name) {
  if (!this.hasClassName(name)) {
    this.className = this.className ? [this.className, name].join(' ') : name;
  }
};

Element.prototype.removeClassName = function(name) {
  if (this.hasClassName(name)) {
    var c = this.className;
    this.className = c.replace(new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g"), "");
  }
};

(function() {
  let currentService, currentPlatform;

  const serviceLinks = $$('.service-select a');
  const platformLinks = $$('.platform-select a');

  // Header animation
  setInterval(function() {
    let serviceLink = serviceLinks[Math.floor(Math.random()*serviceLinks.length)];
    let platformLink = platformLinks[Math.floor(Math.random()*platformLinks.length)];
    $('.getstarted-heading__service').innerHTML = serviceLink.getAttribute('data-name');
    $('.getstarted-heading__platform').innerHTML = platformLink.getAttribute('data-name');
  }, 1000)

  // Steps with Markdown docs
  let addClickHandlers = function(links, type) {
    for (let i = links.length - 1; i >= 0; i--) {
      links[i].addEventListener('click', function (e) {
        e.preventDefault();
        if(type === 'service') currentService = {name: e.currentTarget.getAttribute('data-name'), doc: e.currentTarget.getAttribute('data-doc')};
        if(type === 'platform') currentPlatform = {name: e.currentTarget.getAttribute('data-name'), doc: e.currentTarget.getAttribute('data-doc')};
        nextStep();
      });
    }
  }

  addClickHandlers(serviceLinks, 'service');
  addClickHandlers(platformLinks, 'platform');
  $('.step1').setAttribute('style', 'pointer-events: none;');
  $('.step2').setAttribute('style', 'pointer-events: none;');

  let findItemIn = function(links, term) {
    for (let i = links.length - 1; i >= 0; i--) {
      if(links[i].getAttribute('data-name').toLowerCase() === term) {
        return links[i];
      } else {
        return undefined;
      }
    }
  }

  $('.step1').addEventListener('click', function(e) {
    e.preventDefault();
    $('.step1').setAttribute('style', 'pointer-events: none;');
    $('.step2').setAttribute('style', 'pointer-events: none;');
    $('.step1 h3').innerHTML = 'Select a service';
    $('.step2 h3').innerHTML = 'Select a platform';

    $('.service-select').removeAttribute('style');
    $('.platform-select').setAttribute('style', 'display: none;');
    $('.install').setAttribute('style', 'display: none;');

    $('.step1').removeClassName('step-inactive');
    $('.step2').addClassName('step-inactive');
    $('.step3').addClassName('step-inactive');

    currentService = undefined;
    currentPlatform = undefined;
    window.location.hash = '!';
  });

  $('.step2').addEventListener('click', function(e) {
    e.preventDefault();
    $('.step2').setAttribute('style', 'pointer-events: none;');
    $('.step2 h3').innerHTML = 'Select a platform';

    $('.platform-select').removeAttribute('style');
    $('.install').setAttribute('style', 'display: none;');

    $('.step2').removeClassName('step-inactive');
    $('.step3').addClassName('step-inactive');

    currentPlatform = undefined;

    window.location.hash = `${currentService.name}`.toLowerCase();
  });

  let getDocs = function(servicePath, platformPath) {
    return new Promise(function(resolve, reject) {
      let serviceDoc, platformDoc;
      let gotADoc = function () {
        if(serviceDoc != undefined && platformDoc != undefined) resolve({service: serviceDoc, platform: platformDoc});
      }

      fetch(`/docs/${servicePath}`)
        .then(response => response.text())
        .then(body => {
          serviceDoc = body;
          gotADoc()
        })

      fetch(`/docs/${platformPath}`)
        .then(response => response.text())
        .then(body => {
          platformDoc = body;
          gotADoc()
        })
    })
  }

  let step = function(c) {
    if(c === 1) {
      // show platform
      $('.service-select').setAttribute('style', 'display: none;');
      $('.platform-select').removeAttribute('style');
      $('.install').setAttribute('style', 'display: none;');
      $('.step1').removeAttribute('style');

      $('.step1').addClassName('step-inactive');
      $('.step2').removeClassName('step-inactive');

      $('.step1 h3').innerHTML = currentService.name;
      window.location.hash = `${currentService.name}`.toLowerCase();
    } else if(c === 2) {
      // show docs
      $('.service-select').setAttribute('style', 'display: none;');
      $('.platform-select').setAttribute('style', 'display: none;');
      $('.install').removeAttribute('style');
      $('.step2').removeAttribute('style');

      $('.step1').addClassName('step-inactive');
      $('.step2').addClassName('step-inactive');
      $('.step3').removeClassName('step-inactive');

      $('.step1 h3').innerHTML = currentService.name;
      $('.step2 h3').innerHTML = currentPlatform.name;
      window.location.hash = `${currentService.name}#${currentPlatform.name}`.toLowerCase();

      getDocs(currentService.doc, currentPlatform.doc)
        .then(docs => {
          $('.install').innerHTML = `${docs.service}\n${docs.platform}`;
        })
    }
  }

  let nextStep = function () {
    if(currentService != undefined && currentPlatform === undefined) {
      step(1);
    } else if(currentService != undefined && currentPlatform != undefined) {
      step(2);
    }
  }

  if(window.location.hash != "") {
    let serviceHash = window.location.hash.split('#')[1];
    let platformHash = window.location.hash.split('#')[2];
    if(serviceHash) {
      let result = findItemIn(serviceLinks, serviceHash);
      if(result) currentService = {name: result.getAttribute('data-name'), doc: result.getAttribute('data-doc')};
      $('.step1').removeAttribute('style');
    }
    if(platformHash) {
       let result = findItemIn(platformLinks, platformHash);
       if(result) currentPlatform = {name: result.getAttribute('data-name'), doc: result.getAttribute('data-doc')};
       $('.step2').removeAttribute('style');
    }
    nextStep();
  }

})();<|endoftext|>


<commit_before>
(function(){
  Express = {
    version : '0.0.1',
    routes  : [],
    response : {
      body : null,
      status : 200,
      headers : {}
    },

    defaultRoute : {
      callback : function() {
        Express.status('Not Found')
        return 'Not Found'
      }
    },

    /**
     * Start express, binding to _port_.
     *
     * @param {int} port
     * @api public
     */

    start : function(port) {
      this.server.listen(port || 3000, function(request, response){
        request.headers = Express.arrayToHash(request.headers)
        request.uri.params = Express.parseNestedParams(request.uri.params)
        request.uri.path = Express.normalizePath(request.uri.path)
        Express.request = request
        Express.response.body = Express.callRouteFor(request)
        response.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))
        response.sendBody(Express.response.body || '')
        response.finish()
      })
    },

    server : {

      /**
       * Listen to _port_ with _callback_.
       *
       * @param {int} port
       * @param {function} callback
       * @api private
       */

      listen : function(port, callback) {
        new node.http.Server(callback).listen(port)
        puts('Express listening to http://localhost:' + port)
      }
    },

    /**
     * Return an associative array generated
     * from the key / value pairs in _hash_.
     *
     * @param  {hash} hash
     * @return {array}
     * @api public
     */

    hashToArray : function(hash) {
      var array = []
      for (var key in hash)
        if (hash.hasOwnProperty(key))
          array.push([key, hash[key]])
      return array
    },

    /**
     * Return hash generated from an
     * associative array.
     *
     * @param  {array} array
     * @return {hash}
     * @api public
     */

    arrayToHash : function(array) {
      var hash = {}
      for (i = 0, len = array.length; i < len; ++i)
        hash[array[i][0]] = array[i][1]
      return hash
    },

    /**
     * Set response status to _value_. Where value may be
     * a case-insensitive string such as 'Not Found', 'forbidden',
     * or a numeric HTTP response status code.
     *
     * @param  {int, string} value
     * @return {int}
     * @api public
     */

    status : function(value) {
      if (typeof value == 'number') return this.response.status = value
      for (var code in node.http.STATUS_CODES)
        if (node.http.STATUS_CODES.hasOwnProperty(code))
          if (node.http.STATUS_CODES[code].toLowerCase() == value.toLowerCase())
            return this.response.status = code
    },

    /**
     * Sets _name_ header to _value_. When _value_
     * is not present the value of the header _name_
     * will be returned (if available).
     *
     * @param {string} name
     * @param {string} value
     * @api public
     */

    header : function(name, value) {
      return value ? this.response.headers[name] = value :
               this.response.headers[name]
    },

    /**
     * Return param _key_'s value or _defaultValue_ when
     * the param has not been set.
     *
     * @param  {string} key
     * @param  {mixed} defaultValue
     * @return {mixed}
     * @api public
     */

    param : function(key, defaultValue) {
      return this.request.uri.params[key] || defaultValue
    },

    parseNestedParams : function(params) {
      for (var key in params)
        if (params.hasOwnProperty(key))
          if (parts = key.split('['))
            if (parts.length > 1)
              for (i = 0, prop = params, len = parts.length; i < len; ++i) {
                if (i == len - 1) {
                  var name = parts[i].replace(']', '')
                  prop[name] = params[key]
                  prop = params, delete params[key]
                }
                else {
                  var name = parts[i].replace(']', '')
                  prop = prop[name] = prop[name] || {}
                }
              }

      return params
    },

    /**
     * Normalize a path. Strips trailing / leading whitespace
     * and slashes ('/').
     *
     * @param  {string} path
     * @return {string}
     * @api public
     */

    normalizePath : function(path) {
      if (typeof path != 'string') return path
      return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')
    },

    /**
     * Normalize _path_. When a RegExp it is simply returned,
     * otherwise a string is converted to a regular expression
     * surrounded by ^$. So /user/:id/edit would become:
     *
     * \^/user/(.*?)\/edit\$/
     *
     * Each param key (:id) will be captured and placed in the
     * params array, so param('id') would give the string captured.
     *
     * @param  {string} path
     * @return {regexp}
     * @api public
     */

    pathToRegexp : function(path) {
      Express.regexpKeys = []
      if (path.constructor == RegExp) return path
      path = path.replace(/:(\w+)/g, function(_, key){
        Express.regexpKeys.push(key)
        return '(.*?)'
      })
      return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')
    },

    /**
     * Escape RegExp _chars_ in _string_. Where _chars_
     * defaults to regular expression special characters.
     *
     * _chars_ should be a space delimited list of characters,
     * for example '[ ] ( )'.
     *
     * @param  {string} string
     * @param  {string} chars
     * @return {Type}
     * @api public
     */

    escapeRegexp : function(string, chars) {
      var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')
      return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')
    },

    /**
     * Return the contents of a function body.
     *
     * @param  {function} body
     * @return {string}
     * @api public
     */

    contentsOf : function(body) {
      return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]
    },

    /**
     * Eval _string_ in context of Express.
     *
     * @param  {string} string
     * @return {mixed}
     * @api public
     */

    eval : function(string) {
      return eval('function(){ with (Express){' + string + '}}')
    },

    /**
     * Escape special characters in _html_.
     *
     * @param  {string} html
     * @return {string}
     * @api public
     */

    escape : function(html) {
      return html.
        replace(/&/g, '&').
        replace(/"/g, '"').
        replace(/</g, '<').
        replace(/>/g, '>')
    },

    /**
     * Convert native arguments object into an
     * array with optional _offset_.
     *
     * @param  {arguments} args
     * @param  {int} offset
     * @return {array}
     * @api public
     */

    argsArray : function(args, offset) {
      return Array.prototype.slice.call(args, offset)
    },

    /**
     * Attept to match and call a route for
     * the given _request_, returning the data
     * returned by the route callback.
     *
     * @param  {object} request
     * @return {mixed}
     * @api public
     */

    callRouteFor : function(request) {
      var route = this.findRouteFor(request) || this.defaultRoute
      if (route.keys)
        for (i = 0, len = route.keys.length; i < len; ++i)
          this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null
      return this.eval(Express.contentsOf(route.callback))()
    },

    /**
     * Attemp to find and return a route matching _request_.
     *
     * @param  {object} request
     * @return {object}
     * @api public
     */

    findRouteFor : function(request) {
      for (i = 0, len = this.routes.length; i < len; ++i)
        if (this.routeMatches(this.routes[i], request))
          return this.routes[i]
    },

    /**
     * Check if _route_ matches _request_
     *
     * @param  {object} route
     * @param  {object} request
     * @return {bool}
     * @api public
     */

    routeMatches : function(route, request) {
      if (route.method.toUpperCase() != request.method) return false
      switch (route.path.constructor) {
        case String: return route.path == request.uri.path
        case RegExp: return !! (Express.captures = request.uri.path.match(route.path))
      }
    },

    /**
     * Return a routing function for _method_.
     *
     * @param  {string} method
     * @return {function}
     * @api private
     */

    routeFunctionFor : function(method) {
      return function(path, callback) {
        path = Express.pathToRegexp(Express.normalizePath(path))
        Express.routes.push({
          keys : Express.regexpKeys,
          path : path,
          method : method,
          callback : callback
        })
      }
    },

    readFile : function(path, callback, errorCallback) {
      node.fs.cat(path, 'utf8', function(status, content){
        if (status < 0)
          if (errorCallback) errorCallback(status)
          else throw "failed to read file `" + path + "'"
        else
          callback(content)
      })
    }
  }

  get = Express.routeFunctionFor('get')
  post = Express.routeFunctionFor('post')
  del = Express.routeFunctionFor('delete')
  put = Express.routeFunctionFor('put')

})()

get('user/:name/:operation', function(){
  // ["Accept","application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"],["Accept-Language","en-us"],["Accept-Encoding","gzip, deflate"]
 p(request.headers['User-Agent'])
 p(request.headers['Accept'])
 p(request.headers['Accept-Encoding'])
 p(request.headers['Cookie'])
 return param('operation') + 'ing ' + param('name')
})

get('articles', function(){
  return 'list of articles'
})

get(/articles\/(\d+)/, function(){
  return 'article id ' + captures[1]
})

get('articles/:name', function(){
  return 'article name ' + param('name')
})

Express.start()<commit_msg>Added options for routes<commit_after>
(function(){
  Express = {
    version : '0.0.1',
    routes  : [],
    response : {
      body : null,
      status : 200,
      headers : {}
    },

    defaultRoute : {
      callback : function() {
        Express.status('Not Found')
        return 'Not Found'
      }
    },

    /**
     * Start express, binding to _port_.
     *
     * @param {int} port
     * @api public
     */

    start : function(port) {
      this.server.listen(port || 3000, function(request, response){
        request.headers = Express.arrayToHash(request.headers)
        request.uri.params = Express.parseNestedParams(request.uri.params)
        request.uri.path = Express.normalizePath(request.uri.path)
        Express.request = request
        Express.response.body = Express.callRouteFor(request)
        response.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))
        response.sendBody(Express.response.body || '')
        response.finish()
      })
    },

    server : {

      /**
       * Listen to _port_ with _callback_.
       *
       * @param {int} port
       * @param {function} callback
       * @api private
       */

      listen : function(port, callback) {
        new node.http.Server(callback).listen(port)
        puts('Express listening to http://localhost:' + port)
      }
    },

    /**
     * Return an associative array generated
     * from the key / value pairs in _hash_.
     *
     * @param  {hash} hash
     * @return {array}
     * @api public
     */

    hashToArray : function(hash) {
      var array = []
      for (var key in hash)
        if (hash.hasOwnProperty(key))
          array.push([key, hash[key]])
      return array
    },

    /**
     * Return hash generated from an
     * associative array.
     *
     * @param  {array} array
     * @return {hash}
     * @api public
     */

    arrayToHash : function(array) {
      var hash = {}
      for (i = 0, len = array.length; i < len; ++i)
        hash[array[i][0]] = array[i][1]
      return hash
    },

    /**
     * Set response status to _value_. Where value may be
     * a case-insensitive string such as 'Not Found', 'forbidden',
     * or a numeric HTTP response status code.
     *
     * @param  {int, string} value
     * @return {int}
     * @api public
     */

    status : function(value) {
      if (typeof value == 'number') return this.response.status = value
      for (var code in node.http.STATUS_CODES)
        if (node.http.STATUS_CODES.hasOwnProperty(code))
          if (node.http.STATUS_CODES[code].toLowerCase() == value.toLowerCase())
            return this.response.status = code
    },

    /**
     * Sets _name_ header to _value_. When _value_
     * is not present the value of the header _name_
     * will be returned (if available).
     *
     * @param {string} name
     * @param {string} value
     * @api public
     */

    header : function(name, value) {
      return value ? this.response.headers[name] = value :
               this.response.headers[name]
    },

    /**
     * Return param _key_'s value or _defaultValue_ when
     * the param has not been set.
     *
     * @param  {string} key
     * @param  {mixed} defaultValue
     * @return {mixed}
     * @api public
     */

    param : function(key, defaultValue) {
      return this.request.uri.params[key] || defaultValue
    },

    parseNestedParams : function(params) {
      for (var key in params)
        if (params.hasOwnProperty(key))
          if (parts = key.split('['))
            if (parts.length > 1)
              for (i = 0, prop = params, len = parts.length; i < len; ++i) {
                if (i == len - 1) {
                  var name = parts[i].replace(']', '')
                  prop[name] = params[key]
                  prop = params, delete params[key]
                }
                else {
                  var name = parts[i].replace(']', '')
                  prop = prop[name] = prop[name] || {}
                }
              }

      return params
    },

    /**
     * Normalize a path. Strips trailing / leading whitespace
     * and slashes ('/').
     *
     * @param  {string} path
     * @return {string}
     * @api public
     */

    normalizePath : function(path) {
      if (typeof path != 'string') return path
      return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')
    },

    /**
     * Normalize _path_. When a RegExp it is simply returned,
     * otherwise a string is converted to a regular expression
     * surrounded by ^$. So /user/:id/edit would become:
     *
     * \^/user/(.*?)\/edit\$/
     *
     * Each param key (:id) will be captured and placed in the
     * params array, so param('id') would give the string captured.
     *
     * @param  {string} path
     * @return {regexp}
     * @api public
     */

    pathToRegexp : function(path) {
      Express.regexpKeys = []
      if (path.constructor == RegExp) return path
      path = path.replace(/:(\w+)/g, function(_, key){
        Express.regexpKeys.push(key)
        return '(.*?)'
      })
      return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')
    },

    /**
     * Escape RegExp _chars_ in _string_. Where _chars_
     * defaults to regular expression special characters.
     *
     * _chars_ should be a space delimited list of characters,
     * for example '[ ] ( )'.
     *
     * @param  {string} string
     * @param  {string} chars
     * @return {Type}
     * @api public
     */

    escapeRegexp : function(string, chars) {
      var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')
      return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')
    },

    /**
     * Return the contents of a function body.
     *
     * @param  {function} body
     * @return {string}
     * @api public
     */

    contentsOf : function(body) {
      return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]
    },

    /**
     * Eval _string_ in context of Express.
     *
     * @param  {string} string
     * @return {mixed}
     * @api public
     */

    eval : function(string) {
      return eval('function(){ with (Express){' + string + '}}')
    },

    /**
     * Escape special characters in _html_.
     *
     * @param  {string} html
     * @return {string}
     * @api public
     */

    escape : function(html) {
      return html.
        replace(/&/g, '&').
        replace(/"/g, '"').
        replace(/</g, '<').
        replace(/>/g, '>')
    },

    /**
     * Convert native arguments object into an
     * array with optional _offset_.
     *
     * @param  {arguments} args
     * @param  {int} offset
     * @return {array}
     * @api public
     */

    argsArray : function(args, offset) {
      return Array.prototype.slice.call(args, offset)
    },

    /**
     * Attept to match and call a route for
     * the given _request_, returning the data
     * returned by the route callback.
     *
     * @param  {object} request
     * @return {mixed}
     * @api public
     */

    callRouteFor : function(request) {
      var route = this.findRouteFor(request) || this.defaultRoute
      if (route.keys)
        for (i = 0, len = route.keys.length; i < len; ++i)
          this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null
      return this.eval(Express.contentsOf(route.callback))()
    },

    /**
     * Attemp to find and return a route matching _request_.
     *
     * @param  {object} request
     * @return {object}
     * @api public
     */

    findRouteFor : function(request) {
      for (i = 0, len = this.routes.length; i < len; ++i)
        if (this.routeMatches(this.routes[i], request))
          return this.routes[i]
    },

    /**
     * Check if _route_ matches _request_
     *
     * @param  {object} route
     * @param  {object} request
     * @return {bool}
     * @api public
     */

    routeMatches : function(route, request) {
      if (route.method.toUpperCase() != request.method) return false
      switch (route.path.constructor) {
        case String: return route.path == request.uri.path
        case RegExp: return !! (Express.captures = request.uri.path.match(route.path))
      }
    },

    /**
     * Return a routing function for _method_.
     *
     * @param  {string} method
     * @return {function}
     * @api private
     */

    routeFunctionFor : function(method) {
      return function(path, options, callback) {
        if (options.constructor == Function) callback = options, options = {}
        path = Express.pathToRegexp(Express.normalizePath(path))
        Express.routes.push({
          keys : Express.regexpKeys,
          path : path,
          method : method,
          options : options,
          callback : callback
        })
      }
    },

    readFile : function(path, callback, errorCallback) {
      node.fs.cat(path, 'utf8', function(status, content){
        if (status < 0)
          if (errorCallback) errorCallback(status)
          else throw "failed to read file `" + path + "'"
        else
          callback(content)
      })
    }
  }

  get = Express.routeFunctionFor('get')
  post = Express.routeFunctionFor('post')
  del = Express.routeFunctionFor('delete')
  put = Express.routeFunctionFor('put')

})()

get('user/:name/:operation', function(){
 p(request.headers['User-Agent'])
 p(request.headers['Accept'])
 p(request.headers['Accept-Encoding'])
 p(request.headers['Cookie'])
 return param('operation') + 'ing ' + param('name')
})

get('articles', { provides : 'text/html' }, function(){
  return 'list of articles'
})

get(/articles\/(\d+)/, function(){
  return 'article id ' + captures[1]
})

get('articles/:name', function(){
  return 'article name ' + param('name')
})

Express.start()<|endoftext|>


<commit_before>window.log  = console.log.bind( console );
window.err  = console.error.bind( console );
window.glog = function( msg ) { log( '%c' + msg, 'color: green' ); }

window.DEBUG_MODE = false;

//
//  MODULE
//
window.CTDS = angular.module( 'CTDS', [ 'ngRoute', 'LocalStorageModule', 'ngClipboard' ]).config([
    '$compileProvider', function($compileProvider) {
        return $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|rdar|mailto|chrome-extension):/);
    }
]).config([
    'ngClipProvider', function(ngClipProvider) {
        ngClipProvider.setPath('flash/ZeroClipboard.swf');
    }
]);

//
//  CONTROLLER
//
CTDS.controller( 'mainController', function($scope, localStorageService, $rootScope, $filter, $http, $timeout, $sce) {

    var $$ = $scope;
    window.scope = $$;

    $$.debug_mode = DEBUG_MODE;

    $$.heading = "Here are some colors that don't suck.";
    $$.linkText = "Actually, those kinda sucked ... hit me again.";

    var store = localStorageService;

    $$.init = function() {
        $$.generateColors();
    };

    // Refresh color choices
    $$.refresh = function() {
        $$.randomizeMessaging();
        $$.generateColors();
    };

    // Generate random number between ceiling and floor
    window.random = function(ceiling, floor) {
        var floor = floor || 0;
        return (Math.random() * (ceiling - floor)) + floor;
    }

    $$.please = window.Please;

    $$.lastIndex = null;

    $$.randomizeMessaging = function() {

        var headers = [
            "What about these ones?",
            "Try these on some buttons.",
            "You won't find these in Bootstrap.",
            "If these came on sneakers - I'd wear em.",
            "These would make some bitchin' Crayons.",
            "These might do the trick.",
            "If these don't work - you'd better revisit those wireframes.",
            "Hot damn! These are ready to go.",
            "These look pretty slick.",
            "How bout these ones?"
        ], links = [
            "Those actually sucked worse than before.",
            "Ehh, I'd be better off going Aqua.",
            "I actually prefer theirs. Let's see some more.",
            "Yeah, I bet you would.",
            "You must've eaten glue as a kid. Hit me again.",
            "Maybe ... if my clients were baboons.",
            "Actually, my wireframes are just fine.",
            "Nah, I think we can do better.",
            "Yeah, but let's try another set.",
            "Maybe if I was still in design school."
        ]

        var index = $$.lastIndex;

        while (index === $$.lastIndex) {
            index = Math.floor(Math.random()*headers.length);
        };

        $$.lastIndex =  index;

        $$.heading = headers[index];
        $$.linkText = links[index];
    };

    var randomSchemeType = function() {
        var types = [
            // "mono",
            "triadic",
            "complementary",
            // "double-complementary",
            // "split-complementary",
            // "analogous"
        ];
        return types[Math.floor(Math.random()*types.length)]
    };

    $$.shadeColor = function(color, percent) {
        var num = parseInt(color.split('#').join(''),16), amt = Math.round(2.55 * percent), R = (num >> 16) + amt, G = (num >> 8 & 0x00FF) + amt, B = (num & 0x0000FF) + amt;
        return "#" + (0x1000000 + (R<255?R<1?0:R:255)*0x10000 + (G<255?G<1?0:G:255)*0x100 + (B<255?B<1?0:B:255)).toString(16).slice(1);
    };

    $$.formatValue = function(val) {
        return Math.round(val * 100) / 100;
    };

    $$.generateColors = function() {

        $$.type = randomSchemeType();
        $$.hue  = random(360);
        $$.saturation = random(0.8,0.6),
        $$.value = random(0.8,0.6)

        $$.colors = Please.make_scheme(
        {
            h: $$.hue,
            s: $$.saturation,
            v: $$.value
        },{
            scheme_type: $$.type,
            format: 'hex'
        });

        if (DEBUG_MODE) {
            logColorSettings();
        }

        $timeout( function() { morphie() });
        $timeout( function() { $('button')[0].click() } )
    }

    $$.copiedSASS = function() {
        $$.justCopiedSASS = true;
        $timeout( function() {
            $$.justCopiedSASS = false;
        }, 1500);
    };

    $$.copiedLESS = function() {
        $$.justCopiedLESS = true;
        $timeout( function() {
            $$.justCopiedLESS = false;
        }, 1500);
    };

    $$.copiedJS = function() {
        $$.justCopiedJS = true;
        $timeout( function() {
            $$.justCopiedJS = false;
        }, 1500);
    };

    function logColorSettings() {
        log('Hue:', $$.formatValue( $$.hue ));
        log('Sat:', $$.formatValue( $$.saturation ));
        log('Val:', $$.formatValue( $$.value ));
        log($$.colors);
    }

    $$.getCode = function(color, format) {
        switch( format ) {
            case 'sass': return '$my-color: ' + color + ';';
            case 'less': return '@my-color: ' + color + ';';
            case 'js':   return 'var myColor = ' + color + ';';
        }
    }

    $$.init();
    // $$.api.getPictures(17993529);
});
<commit_msg>removed debug line<commit_after>window.log  = console.log.bind( console );
window.err  = console.error.bind( console );
window.glog = function( msg ) { log( '%c' + msg, 'color: green' ); }

window.DEBUG_MODE = false;

//
//  MODULE
//
window.CTDS = angular.module( 'CTDS', [ 'ngRoute', 'LocalStorageModule', 'ngClipboard' ]).config([
    '$compileProvider', function($compileProvider) {
        return $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|rdar|mailto|chrome-extension):/);
    }
]).config([
    'ngClipProvider', function(ngClipProvider) {
        ngClipProvider.setPath('flash/ZeroClipboard.swf');
    }
]);

//
//  CONTROLLER
//
CTDS.controller( 'mainController', function($scope, localStorageService, $rootScope, $filter, $http, $timeout, $sce) {

    var $$ = $scope;
    window.scope = $$;

    $$.debug_mode = DEBUG_MODE;

    $$.heading = "Here are some colors that don't suck.";
    $$.linkText = "Actually, those kinda sucked ... hit me again.";

    var store = localStorageService;

    $$.init = function() {
        $$.generateColors();
    };

    // Refresh color choices
    $$.refresh = function() {
        $$.randomizeMessaging();
        $$.generateColors();
    };

    // Generate random number between ceiling and floor
    window.random = function(ceiling, floor) {
        var floor = floor || 0;
        return (Math.random() * (ceiling - floor)) + floor;
    }

    $$.please = window.Please;

    $$.lastIndex = null;

    $$.randomizeMessaging = function() {

        var headers = [
            "What about these ones?",
            "Try these on some buttons.",
            "You won't find these in Bootstrap.",
            "If these came on sneakers - I'd wear em.",
            "These would make some bitchin' Crayons.",
            "These might do the trick.",
            "If these don't work - you'd better revisit those wireframes.",
            "Hot damn! These are ready to go.",
            "These look pretty slick.",
            "How bout these ones?"
        ], links = [
            "Those actually sucked worse than before.",
            "Ehh, I'd be better off going Aqua.",
            "I actually prefer theirs. Let's see some more.",
            "Yeah, I bet you would.",
            "You must've eaten glue as a kid. Hit me again.",
            "Maybe ... if my clients were baboons.",
            "Actually, my wireframes are just fine.",
            "Nah, I think we can do better.",
            "Yeah, but let's try another set.",
            "Maybe if I was still in design school."
        ]

        var index = $$.lastIndex;

        while (index === $$.lastIndex) {
            index = Math.floor(Math.random()*headers.length);
        };

        $$.lastIndex =  index;

        $$.heading = headers[index];
        $$.linkText = links[index];
    };

    var randomSchemeType = function() {
        var types = [
            // "mono",
            "triadic",
            "complementary",
            // "double-complementary",
            // "split-complementary",
            // "analogous"
        ];
        return types[Math.floor(Math.random()*types.length)]
    };

    $$.shadeColor = function(color, percent) {
        var num = parseInt(color.split('#').join(''),16), amt = Math.round(2.55 * percent), R = (num >> 16) + amt, G = (num >> 8 & 0x00FF) + amt, B = (num & 0x0000FF) + amt;
        return "#" + (0x1000000 + (R<255?R<1?0:R:255)*0x10000 + (G<255?G<1?0:G:255)*0x100 + (B<255?B<1?0:B:255)).toString(16).slice(1);
    };

    $$.formatValue = function(val) {
        return Math.round(val * 100) / 100;
    };

    $$.generateColors = function() {

        $$.type = randomSchemeType();
        $$.hue  = random(360);
        $$.saturation = random(0.8,0.6),
        $$.value = random(0.8,0.6)

        $$.colors = Please.make_scheme(
        {
            h: $$.hue,
            s: $$.saturation,
            v: $$.value
        },{
            scheme_type: $$.type,
            format: 'hex'
        });

        if (DEBUG_MODE) {
            logColorSettings();
        }

        $timeout( function() { morphie() });
        // $timeout( function() { $('button')[0].click() } )
    }

    $$.copiedSASS = function() {
        $$.justCopiedSASS = true;
        $timeout( function() {
            $$.justCopiedSASS = false;
        }, 1500);
    };

    $$.copiedLESS = function() {
        $$.justCopiedLESS = true;
        $timeout( function() {
            $$.justCopiedLESS = false;
        }, 1500);
    };

    $$.copiedJS = function() {
        $$.justCopiedJS = true;
        $timeout( function() {
            $$.justCopiedJS = false;
        }, 1500);
    };

    function logColorSettings() {
        log('Hue:', $$.formatValue( $$.hue ));
        log('Sat:', $$.formatValue( $$.saturation ));
        log('Val:', $$.formatValue( $$.value ));
        log($$.colors);
    }

    $$.getCode = function(color, format) {
        switch( format ) {
            case 'sass': return '$my-color: ' + color + ';';
            case 'less': return '@my-color: ' + color + ';';
            case 'js':   return 'var myColor = ' + color + ';';
        }
    }

    $$.init();
    // $$.api.getPictures(17993529);
});
<|endoftext|>