text:
(function (root, factory) {
	root.Remotes = factory();
}(this, function () {

//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*jslint sloppy: true */
/*global setTimeout: false */

var requirejs, require, define;
(function (undef) {
    var defined = {},
        waiting = {},
        config = {},
        defining = {},
        aps = [].slice,
        main, req;

    /**
     * Given a relative module name, like ./something, normalize it to
     * a real name that can be mapped to a path.
     * @param {String} name the relative name
     * @param {String} baseName a real name that the name arg is relative
     * to.
     * @returns {String} normalized name
     */
    function normalize(name, baseName) {
        var baseParts = baseName && baseName.split("/"),
            map = config.map,
            starMap = (map && map['*']) || {},
            nameParts, nameSegment, mapValue, foundMap,
            foundI, foundStarMap, starI, i, j, part;

        //Adjust any relative paths.
        if (name && name.charAt(0) === ".") {
            //If have a base name, try to normalize against it,
            //otherwise, assume it is a top-level require that will
            //be relative to baseUrl in the end.
            if (baseName) {
                //Convert baseName to array, and lop off the last part,
                //so that . matches that "directory" and not name of the baseName's
                //module. For instance, baseName of "one/two/three", maps to
                //"one/two/three.js", but we want the directory, "one/two" for
                //this normalization.
                baseParts = baseParts.slice(0, baseParts.length - 1);

                name = baseParts.concat(name.split("/"));

                //start trimDots
                for (i = 0; (part = name[i]); i++) {
                    if (part === ".") {
                        name.splice(i, 1);
                        i -= 1;
                    } else if (part === "..") {
                        if (i === 1 && (name[2] === '..' || name[0] === '..')) {
                            //End of the line. Keep at least one non-dot
                            //path segment at the front so it can be mapped
                            //correctly to disk. Otherwise, there is likely
                            //no path mapping for a path starting with '..'.
                            //This can still fail, but catches the most reasonable
                            //uses of ..
                            return true;
                        } else if (i > 0) {
                            name.splice(i - 1, 2);
                            i -= 2;
                        }
                    }
                }
                //end trimDots

                name = name.join("/");
            }
        }

        //Apply map config if available.
        if ((baseParts || starMap) && map) {
            nameParts = name.split('/');

            for (i = nameParts.length; i > 0; i -= 1) {
                nameSegment = nameParts.slice(0, i).join("/");

                if (baseParts) {
                    //Find the longest baseName segment match in the config.
                    //So, do joins on the biggest to smallest lengths of baseParts.
                    for (j = baseParts.length; j > 0; j -= 1) {
                        mapValue = map[baseParts.slice(0, j).join('/')];

                        //baseName segment has  config, find if it has one for
                        //this name.
                        if (mapValue) {
                            mapValue = mapValue[nameSegment];
                            if (mapValue) {
                                //Match, update name to the new value.
                                foundMap = mapValue;
                                foundI = i;
                                break;
                            }
                        }
                    }
                }

                if (foundMap) {
                    break;
                }

                //Check for a star map match, but just hold on to it,
                //if there is a shorter segment match later in a matching
                //config, then favor over this star map.
                if (!foundStarMap && starMap && starMap[nameSegment]) {
                    foundStarMap = starMap[nameSegment];
                    starI = i;
                }
            }

            if (!foundMap && foundStarMap) {
                foundMap = foundStarMap;
                foundI = starI;
            }

            if (foundMap) {
                nameParts.splice(0, foundI, foundMap);
                name = nameParts.join('/');
            }
        }

        return name;
    }

    function makeRequire(relName, forceSync) {
        return function () {
            //A version of a require function that passes a moduleName
            //value for items that may need to
            //look up paths relative to the moduleName
            return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
        };
    }

    function makeNormalize(relName) {
        return function (name) {
            return normalize(name, relName);
        };
    }

    function makeLoad(depName) {
        return function (value) {
            defined[depName] = value;
        };
    }

    function callDep(name) {
        if (waiting.hasOwnProperty(name)) {
            var args = waiting[name];
            delete waiting[name];
            defining[name] = true;
            main.apply(undef, args);
        }

        if (!defined.hasOwnProperty(name)) {
            throw new Error('No ' + name);
        }
        return defined[name];
    }

    /**
     * Makes a name map, normalizing the name, and using a plugin
     * for normalization if necessary. Grabs a ref to plugin
     * too, as an optimization.
     */
    function makeMap(name, relName) {
        var prefix, plugin,
            index = name.indexOf('!');

        if (index !== -1) {
            prefix = normalize(name.slice(0, index), relName);
            name = name.slice(index + 1);
            plugin = callDep(prefix);

            //Normalize according
            if (plugin && plugin.normalize) {
                name = plugin.normalize(name, makeNormalize(relName));
            } else {
                name = normalize(name, relName);
            }
        } else {
            name = normalize(name, relName);
        }

        //Using ridiculous property names for space reasons
        return {
            f: prefix ? prefix + '!' + name : name, //fullName
            n: name,
            p: plugin
        };
    }

    function makeConfig(name) {
        return function () {
            return (config && config.config && config.config[name]) || {};
        };
    }

    main = function (name, deps, callback, relName) {
        var args = [],
            usingExports,
            cjsModule, depName, ret, map, i;

        //Use name if no relName
        relName = relName || name;

        //Call the callback to define the module, if necessary.
        if (typeof callback === 'function') {

            //Pull out the defined dependencies and pass the ordered
            //values to the callback.
            //Default to [require, exports, module] if no deps
            deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
            for (i = 0; i < deps.length; i++) {
                map = makeMap(deps[i], relName);
                depName = map.f;

                //Fast path CommonJS standard dependencies.
                if (depName === "require") {
                    args[i] = makeRequire(name);
                } else if (depName === "exports") {
                    //CommonJS module spec 1.1
                    args[i] = defined[name] = {};
                    usingExports = true;
                } else if (depName === "module") {
                    //CommonJS module spec 1.1
                    cjsModule = args[i] = {
                        id: name,
                        uri: '',
                        exports: defined[name],
                        config: makeConfig(name)
                    };
                } else if (defined.hasOwnProperty(depName) || waiting.hasOwnProperty(depName)) {
                    args[i] = callDep(depName);
                } else if (map.p) {
                    map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
                    args[i] = defined[depName];
                } else if (!defining[depName]) {
                    throw new Error(name + ' missing ' + depName);
                }
            }

            ret = callback.apply(defined[name], args);

            if (name) {
                //If setting exports via "module" is in play,
                //favor that over return value and exports. After that,
                //favor a non-undefined return value over exports use.
                if (cjsModule && cjsModule.exports !== undef &&
                    cjsModule.exports !== defined[name]) {
                    defined[name] = cjsModule.exports;
                } else if (ret !== undef || !usingExports) {
                    //Use the return value from the function.
                    defined[name] = ret;
                }
            }
        } else if (name) {
            //May just be an object definition for the module. Only
            //worry about defining if have a module name.
            defined[name] = callback;
        }
    };

    requirejs = require = req = function (deps, callback, relName, forceSync) {
        if (typeof deps === "string") {
            //Just return the module wanted. In this scenario, the
            //deps arg is the module name, and second arg (if passed)
            //is just the relName.
            //Normalize module name, if it contains . or ..
            return callDep(makeMap(deps, callback).f);
        } else if (!deps.splice) {
            //deps is a config object, not an array.
            config = deps;
            if (callback.splice) {
                //callback is an array, which means it is a dependency list.
                //Adjust args if there are dependencies
                deps = callback;
                callback = relName;
                relName = null;
            } else {
                deps = undef;
            }
        }

        //Support require(['a'])
        callback = callback || function () {};

        //Simulate async callback;
        if (forceSync) {
            main(undef, deps, callback, relName);
        } else {
            setTimeout(function () {
                main(undef, deps, callback, relName);
            }, 15);
        }

        return req;
    };

    /**
     * Just drops the config on the floor, but returns req in case
     * the config return value is used.
     */
    req.config = function (cfg) {
        config = cfg;
        return req;
    };

    define = function (name, deps, callback) {

        //This module may not have dependencies
        if (!deps.splice) {
            //deps is not an array, so probably means
            //an object literal or factory function for
            //the value. Adjust args.
            callback = deps;
            deps = [];
        }

        waiting[name] = [name, deps, callback];
    };

    define.amd = {
        jQuery: true
    };
}());

define("libs/almond", function(){});

//     Underscore.js 1.3.3
//     (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
//     Underscore is freely distributable under the MIT license.
//     Portions of Underscore are inspired or borrowed from Prototype,
//     Oliver Steele's Functional, and John Resig's Micro-Templating.
//     For all details and documentation:
//     http://documentcloud.github.com/underscore

(function() {

  // Baseline setup
  // --------------

  // Establish the root object, `window` in the browser, or `global` on the server.
  var root = this;

  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;

  // Establish the object that gets returned to break out of a loop iteration.
  var breaker = {};

  // Save bytes in the minified (but not gzipped) version:
  var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;

  // Create quick reference variables for speed access to core prototypes.
  var slice            = ArrayProto.slice,
      unshift          = ArrayProto.unshift,
      toString         = ObjProto.toString,
      hasOwnProperty   = ObjProto.hasOwnProperty;

  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var
    nativeForEach      = ArrayProto.forEach,
    nativeMap          = ArrayProto.map,
    nativeReduce       = ArrayProto.reduce,
    nativeReduceRight  = ArrayProto.reduceRight,
    nativeFilter       = ArrayProto.filter,
    nativeEvery        = ArrayProto.every,
    nativeSome         = ArrayProto.some,
    nativeIndexOf      = ArrayProto.indexOf,
    nativeLastIndexOf  = ArrayProto.lastIndexOf,
    nativeIsArray      = Array.isArray,
    nativeKeys         = Object.keys,
    nativeBind         = FuncProto.bind;

  // Create a safe reference to the Underscore object for use below.
  var _ = function(obj) { return new wrapper(obj); };

  // Export the Underscore object for **Node.js**, with
  // backwards-compatibility for the old `require()` API. If we're in
  // the browser, add `_` as a global object via a string identifier,
  // for Closure Compiler "advanced" mode.
  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root['_'] = _;
  }

  // Current version.
  _.VERSION = '1.3.3';

  // Collection Functions
  // --------------------

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects with the built-in `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return;
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, l = obj.length; i < l; i++) {
        if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
      }
    } else {
      for (var key in obj) {
        if (_.has(obj, key)) {
          if (iterator.call(context, obj[key], key, obj) === breaker) return;
        }
      }
    }
  };

  // Return the results of applying the iterator to each element.
  // Delegates to **ECMAScript 5**'s native `map` if available.
  _.map = _.collect = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
    each(obj, function(value, index, list) {
      results[results.length] = iterator.call(context, value, index, list);
    });
    if (obj.length === +obj.length) results.length = obj.length;
    return results;
  };

  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
    var initial = arguments.length > 2;
    if (obj == null) obj = [];
    if (nativeReduce && obj.reduce === nativeReduce) {
      if (context) iterator = _.bind(iterator, context);
      return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
    }
    each(obj, function(value, index, list) {
      if (!initial) {
        memo = value;
        initial = true;
      } else {
        memo = iterator.call(context, memo, value, index, list);
      }
    });
    if (!initial) throw new TypeError('Reduce of empty array with no initial value');
    return memo;
  };

  // The right-associative version of reduce, also known as `foldr`.
  // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
    var initial = arguments.length > 2;
    if (obj == null) obj = [];
    if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
      if (context) iterator = _.bind(iterator, context);
      return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
    }
    var reversed = _.toArray(obj).reverse();
    if (context && !initial) iterator = _.bind(iterator, context);
    return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
  };

  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function(obj, iterator, context) {
    var result;
    any(obj, function(value, index, list) {
      if (iterator.call(context, value, index, list)) {
        result = value;
        return true;
      }
    });
    return result;
  };

  // Return all the elements that pass a truth test.
  // Delegates to **ECMAScript 5**'s native `filter` if available.
  // Aliased as `select`.
  _.filter = _.select = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
    each(obj, function(value, index, list) {
      if (iterator.call(context, value, index, list)) results[results.length] = value;
    });
    return results;
  };

  // Return all the elements for which a truth test fails.
  _.reject = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    each(obj, function(value, index, list) {
      if (!iterator.call(context, value, index, list)) results[results.length] = value;
    });
    return results;
  };

  // Determine whether all of the elements match a truth test.
  // Delegates to **ECMAScript 5**'s native `every` if available.
  // Aliased as `all`.
  _.every = _.all = function(obj, iterator, context) {
    var result = true;
    if (obj == null) return result;
    if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
    each(obj, function(value, index, list) {
      if (!(result = result && iterator.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };

  // Determine if at least one element in the object matches a truth test.
  // Delegates to **ECMAScript 5**'s native `some` if available.
  // Aliased as `any`.
  var any = _.some = _.any = function(obj, iterator, context) {
    iterator || (iterator = _.identity);
    var result = false;
    if (obj == null) return result;
    if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
    each(obj, function(value, index, list) {
      if (result || (result = iterator.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };

  // Determine if a given value is included in the array or object using `===`.
  // Aliased as `contains`.
  _.include = _.contains = function(obj, target) {
    var found = false;
    if (obj == null) return found;
    if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
    found = any(obj, function(value) {
      return value === target;
    });
    return found;
  };

  // Invoke a method (with arguments) on every item in a collection.
  _.invoke = function(obj, method) {
    var args = slice.call(arguments, 2);
    return _.map(obj, function(value) {
      return (_.isFunction(method) ? method || value : value[method]).apply(value, args);
    });
  };

  // Convenience version of a common use case of `map`: fetching a property.
  _.pluck = function(obj, key) {
    return _.map(obj, function(value){ return value[key]; });
  };

  // Return the maximum element or (element-based computation).
  _.max = function(obj, iterator, context) {
    if (!iterator && _.isArray(obj) && obj[0] === +obj[0]) return Math.max.apply(Math, obj);
    if (!iterator && _.isEmpty(obj)) return -Infinity;
    var result = {computed : -Infinity};
    each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      computed >= result.computed && (result = {value : value, computed : computed});
    });
    return result.value;
  };

  // Return the minimum element (or element-based computation).
  _.min = function(obj, iterator, context) {
    if (!iterator && _.isArray(obj) && obj[0] === +obj[0]) return Math.min.apply(Math, obj);
    if (!iterator && _.isEmpty(obj)) return Infinity;
    var result = {computed : Infinity};
    each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      computed < result.computed && (result = {value : value, computed : computed});
    });
    return result.value;
  };

  // Shuffle an array.
  _.shuffle = function(obj) {
    var shuffled = [], rand;
    each(obj, function(value, index, list) {
      rand = Math.floor(Math.random() * (index + 1));
      shuffled[index] = shuffled[rand];
      shuffled[rand] = value;
    });
    return shuffled;
  };

  // Sort the object's values by a criterion produced by an iterator.
  _.sortBy = function(obj, val, context) {
    var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
    return _.pluck(_.map(obj, function(value, index, list) {
      return {
        value : value,
        criteria : iterator.call(context, value, index, list)
      };
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      if (a === void 0) return 1;
      if (b === void 0) return -1;
      return a < b ? -1 : a > b ? 1 : 0;
    }), 'value');
  };

  // Groups the object's values by a criterion. Pass either a string attribute
  // to group by, or a function that returns the criterion.
  _.groupBy = function(obj, val) {
    var result = {};
    var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
    each(obj, function(value, index) {
      var key = iterator(value, index);
      (result[key] || (result[key] = [])).push(value);
    });
    return result;
  };

  // Use a comparator function to figure out at what index an object should
  // be inserted so as to maintain order. Uses binary search.
  _.sortedIndex = function(array, obj, iterator) {
    iterator || (iterator = _.identity);
    var low = 0, high = array.length;
    while (low < high) {
      var mid = (low + high) >> 1;
      iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
    }
    return low;
  };

  // Safely convert anything iterable into a real, live array.
  _.toArray = function(obj) {
    if (!obj)                                     return [];
    if (_.isArray(obj))                           return slice.call(obj);
    if (_.isArguments(obj))                       return slice.call(obj);
    if (obj.toArray && _.isFunction(obj.toArray)) return obj.toArray();
    return _.values(obj);
  };

  // Return the number of elements in an object.
  _.size = function(obj) {
    return _.isArray(obj) ? obj.length : _.keys(obj).length;
  };

  // Array Functions
  // ---------------

  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head` and `take`. The **guard** check
  // allows it to work with `_.map`.
  _.first = _.head = _.take = function(array, n, guard) {
    return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  };

  // Returns everything but the last entry of the array. Especcialy useful on
  // the arguments object. Passing **n** will return all the values in
  // the array, excluding the last N. The **guard** check allows it to work with
  // `_.map`.
  _.initial = function(array, n, guard) {
    return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
  };

  // Get the last element of an array. Passing **n** will return the last N
  // values in the array. The **guard** check allows it to work with `_.map`.
  _.last = function(array, n, guard) {
    if ((n != null) && !guard) {
      return slice.call(array, Math.max(array.length - n, 0));
    } else {
      return array[array.length - 1];
    }
  };

  // Returns everything but the first entry of the array. Aliased as `tail`.
  // Especially useful on the arguments object. Passing an **index** will return
  // the rest of the values in the array from that index onward. The **guard**
  // check allows it to work with `_.map`.
  _.rest = _.tail = function(array, index, guard) {
    return slice.call(array, (index == null) || guard ? 1 : index);
  };

  // Trim out all falsy values from an array.
  _.compact = function(array) {
    return _.filter(array, function(value){ return !!value; });
  };

  // Return a completely flattened version of an array.
  _.flatten = function(array, shallow) {
    return _.reduce(array, function(memo, value) {
      if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
      memo[memo.length] = value;
      return memo;
    }, []);
  };

  // Return a version of the array that does not contain the specified value(s).
  _.without = function(array) {
    return _.difference(array, slice.call(arguments, 1));
  };

  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  // Aliased as `unique`.
  _.uniq = _.unique = function(array, isSorted, iterator) {
    var initial = iterator ? _.map(array, iterator) : array;
    var results = [];
    // The `isSorted` flag is irrelevant if the array only contains two elements.
    if (array.length < 3) isSorted = true;
    _.reduce(initial, function (memo, value, index) {
      if (isSorted ? _.last(memo) !== value || !memo.length : !_.include(memo, value)) {
        memo.push(value);
        results.push(array[index]);
      }
      return memo;
    }, []);
    return results;
  };

  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  _.union = function() {
    return _.uniq(_.flatten(arguments, true));
  };

  // Produce an array that contains every item shared between all the
  // passed-in arrays. (Aliased as "intersect" for back-compat.)
  _.intersection = _.intersect = function(array) {
    var rest = slice.call(arguments, 1);
    return _.filter(_.uniq(array), function(item) {
      return _.every(rest, function(other) {
        return _.indexOf(other, item) >= 0;
      });
    });
  };

  // Take the difference between one array and a number of other arrays.
  // Only the elements present in just the first array will remain.
  _.difference = function(array) {
    var rest = _.flatten(slice.call(arguments, 1), true);
    return _.filter(array, function(value){ return !_.include(rest, value); });
  };

  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  _.zip = function() {
    var args = slice.call(arguments);
    var length = _.max(_.pluck(args, 'length'));
    var results = new Array(length);
    for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
    return results;
  };

  // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  // we need this function. Return the position of the first occurrence of an
  // item in an array, or -1 if the item is not included in the array.
  // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  _.indexOf = function(array, item, isSorted) {
    if (array == null) return -1;
    var i, l;
    if (isSorted) {
      i = _.sortedIndex(array, item);
      return array[i] === item ? i : -1;
    }
    if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
    for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
    return -1;
  };

  // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  _.lastIndexOf = function(array, item) {
    if (array == null) return -1;
    if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
    var i = array.length;
    while (i--) if (i in array && array[i] === item) return i;
    return -1;
  };

  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](http://docs.python.org/library/functions.html#range).
  _.range = function(start, stop, step) {
    if (arguments.length <= 1) {
      stop = start || 0;
      start = 0;
    }
    step = arguments[2] || 1;

    var len = Math.max(Math.ceil((stop - start) / step), 0);
    var idx = 0;
    var range = new Array(len);

    while(idx < len) {
      range[idx++] = start;
      start += step;
    }

    return range;
  };

  // Function (ahem) Functions
  // ------------------

  // Reusable constructor function for prototype setting.
  var ctor = function(){};

  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally). Binding with arguments is also known as `curry`.
  // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
  // We check for `func.bind` first, to fail fast when `func` is undefined.
  _.bind = function bind(func, context) {
    var bound, args;
    if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
    if (!_.isFunction(func)) throw new TypeError;
    args = slice.call(arguments, 2);
    return bound = function() {
      if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
      ctor.prototype = func.prototype;
      var self = new ctor;
      var result = func.apply(self, args.concat(slice.call(arguments)));
      if (Object(result) === result) return result;
      return self;
    };
  };

  // Bind all of an object's methods to that object. Useful for ensuring that
  // all callbacks defined on an object belong to it.
  _.bindAll = function(obj) {
    var funcs = slice.call(arguments, 1);
    if (funcs.length == 0) funcs = _.functions(obj);
    each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
    return obj;
  };

  // Memoize an expensive function by storing its results.
  _.memoize = function(func, hasher) {
    var memo = {};
    hasher || (hasher = _.identity);
    return function() {
      var key = hasher.apply(this, arguments);
      return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
    };
  };

  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  _.delay = function(func, wait) {
    var args = slice.call(arguments, 2);
    return setTimeout(function(){ return func.apply(null, args); }, wait);
  };

  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  _.defer = function(func) {
    return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  };

  // Returns a function, that, when invoked, will only be triggered at most once
  // during a given window of time.
  _.throttle = function(func, wait) {
    var context, args, timeout, throttling, more, result;
    var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
    return function() {
      context = this; args = arguments;
      var later = function() {
        timeout = null;
        if (more) func.apply(context, args);
        whenDone();
      };
      if (!timeout) timeout = setTimeout(later, wait);
      if (throttling) {
        more = true;
      } else {
        result = func.apply(context, args);
      }
      whenDone();
      throttling = true;
      return result;
    };
  };

  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds. If `immediate` is passed, trigger the function on the
  // leading edge, instead of the trailing.
  _.debounce = function(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      if (immediate && !timeout) func.apply(context, args);
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  };

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = function(func) {
    var ran = false, memo;
    return function() {
      if (ran) return memo;
      ran = true;
      return memo = func.apply(this, arguments);
    };
  };

  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  _.wrap = function(func, wrapper) {
    return function() {
      var args = [func].concat(slice.call(arguments, 0));
      return wrapper.apply(this, args);
    };
  };

  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  _.compose = function() {
    var funcs = arguments;
    return function() {
      var args = arguments;
      for (var i = funcs.length - 1; i >= 0; i--) {
        args = [funcs[i].apply(this, args)];
      }
      return args[0];
    };
  };

  // Returns a function that will only be executed after being called N times.
  _.after = function(times, func) {
    if (times <= 0) return func();
    return function() {
      if (--times < 1) { return func.apply(this, arguments); }
    };
  };

  // Object Functions
  // ----------------

  // Retrieve the names of an object's properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`
  _.keys = nativeKeys || function(obj) {
    if (obj !== Object(obj)) throw new TypeError('Invalid object');
    var keys = [];
    for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
    return keys;
  };

  // Retrieve the values of an object's properties.
  _.values = function(obj) {
    return _.map(obj, _.identity);
  };

  // Return a sorted list of the function names available on the object.
  // Aliased as `methods`
  _.functions = _.methods = function(obj) {
    var names = [];
    for (var key in obj) {
      if (_.isFunction(obj[key])) names.push(key);
    }
    return names.sort();
  };

  // Extend a given object with all the properties in passed-in object(s).
  _.extend = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      for (var prop in source) {
        obj[prop] = source[prop];
      }
    });
    return obj;
  };

  // Return a copy of the object only containing the whitelisted properties.
  _.pick = function(obj) {
    var result = {};
    each(_.flatten(slice.call(arguments, 1)), function(key) {
      if (key in obj) result[key] = obj[key];
    });
    return result;
  };

  // Fill in a given object with default properties.
  _.defaults = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      for (var prop in source) {
        if (obj[prop] == null) obj[prop] = source[prop];
      }
    });
    return obj;
  };

  // Create a (shallow-cloned) duplicate of an object.
  _.clone = function(obj) {
    if (!_.isObject(obj)) return obj;
    return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };

  // Invokes interceptor with the obj, and then returns obj.
  // The primary purpose of this method is to "tap into" a method chain, in
  // order to perform operations on intermediate results within the chain.
  _.tap = function(obj, interceptor) {
    interceptor(obj);
    return obj;
  };

  // Internal recursive comparison function.
  function eq(a, b, stack) {
    // Identical objects are equal. `0 === -0`, but they aren't identical.
    // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
    if (a === b) return a !== 0 || 1 / a == 1 / b;
    // A strict comparison is necessary because `null == undefined`.
    if (a == null || b == null) return a === b;
    // Unwrap any wrapped objects.
    if (a._chain) a = a._wrapped;
    if (b._chain) b = b._wrapped;
    // Invoke a custom `isEqual` method if one is provided.
    if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
    if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
    // Compare `[[Class]]` names.
    var className = toString.call(a);
    if (className != toString.call(b)) return false;
    switch (className) {
      // Strings, numbers, dates, and booleans are compared by value.
      case '[object String]':
        // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
        // equivalent to `new String("5")`.
        return a == String(b);
      case '[object Number]':
        // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
        // other numeric values.
        return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
      case '[object Date]':
      case '[object Boolean]':
        // Coerce dates and booleans to numeric primitive values. Dates are compared by their
        // millisecond representations. Note that invalid dates with millisecond representations
        // of `NaN` are not equivalent.
        return +a == +b;
      // RegExps are compared by their source patterns and flags.
      case '[object RegExp]':
        return a.source == b.source &&
               a.global == b.global &&
               a.multiline == b.multiline &&
               a.ignoreCase == b.ignoreCase;
    }
    if (typeof a != 'object' || typeof b != 'object') return false;
    // Assume equality for cyclic structures. The algorithm for detecting cyclic
    // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
    var length = stack.length;
    while (length--) {
      // Linear search. Performance is inversely proportional to the number of
      // unique nested structures.
      if (stack[length] == a) return true;
    }
    // Add the first object to the stack of traversed objects.
    stack.push(a);
    var size = 0, result = true;
    // Recursively compare objects and arrays.
    if (className == '[object Array]') {
      // Compare array lengths to determine if a deep comparison is necessary.
      size = a.length;
      result = size == b.length;
      if (result) {
        // Deep compare the contents, ignoring non-numeric properties.
        while (size--) {
          // Ensure commutative equality for sparse arrays.
          if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
        }
      }
    } else {
      // Objects with different constructors are not equivalent.
      if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
      // Deep compare objects.
      for (var key in a) {
        if (_.has(a, key)) {
          // Count the expected number of properties.
          size++;
          // Deep compare each member.
          if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;
        }
      }
      // Ensure that both objects contain the same number of properties.
      if (result) {
        for (key in b) {
          if (_.has(b, key) && !(size--)) break;
        }
        result = !size;
      }
    }
    // Remove the first object from the stack of traversed objects.
    stack.pop();
    return result;
  }

  // Perform a deep comparison to check if two objects are equal.
  _.isEqual = function(a, b) {
    return eq(a, b, []);
  };

  // Is a given array, string, or object empty?
  // An "empty" object has no enumerable own-properties.
  _.isEmpty = function(obj) {
    if (obj == null) return true;
    if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
    for (var key in obj) if (_.has(obj, key)) return false;
    return true;
  };

  // Is a given value a DOM element?
  _.isElement = function(obj) {
    return !!(obj && obj.nodeType == 1);
  };

  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  _.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) == '[object Array]';
  };

  // Is a given variable an object?
  _.isObject = function(obj) {
    return obj === Object(obj);
  };

  // Is a given variable an arguments object?
  _.isArguments = function(obj) {
    return toString.call(obj) == '[object Arguments]';
  };
  if (!_.isArguments(arguments)) {
    _.isArguments = function(obj) {
      return !!(obj && _.has(obj, 'callee'));
    };
  }

  // Is a given value a function?
  _.isFunction = function(obj) {
    return toString.call(obj) == '[object Function]';
  };

  // Is a given value a string?
  _.isString = function(obj) {
    return toString.call(obj) == '[object String]';
  };

  // Is a given value a number?
  _.isNumber = function(obj) {
    return toString.call(obj) == '[object Number]';
  };

  // Is a given object a finite number?
  _.isFinite = function(obj) {
    return _.isNumber(obj) && isFinite(obj);
  };

  // Is the given value `NaN`?
  _.isNaN = function(obj) {
    // `NaN` is the only value for which `===` is not reflexive.
    return obj !== obj;
  };

  // Is a given value a boolean?
  _.isBoolean = function(obj) {
    return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
  };

  // Is a given value a date?
  _.isDate = function(obj) {
    return toString.call(obj) == '[object Date]';
  };

  // Is the given value a regular expression?
  _.isRegExp = function(obj) {
    return toString.call(obj) == '[object RegExp]';
  };

  // Is a given value equal to null?
  _.isNull = function(obj) {
    return obj === null;
  };

  // Is a given variable undefined?
  _.isUndefined = function(obj) {
    return obj === void 0;
  };

  // Has own property?
  _.has = function(obj, key) {
    return hasOwnProperty.call(obj, key);
  };

  // Utility Functions
  // -----------------

  // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  // previous owner. Returns a reference to the Underscore object.
  _.noConflict = function() {
    root._ = previousUnderscore;
    return this;
  };

  // Keep the identity function around for default iterators.
  _.identity = function(value) {
    return value;
  };

  // Run a function **n** times.
  _.times = function (n, iterator, context) {
    for (var i = 0; i < n; i++) iterator.call(context, i);
  };

  // Escape a string for HTML interpolation.
  _.escape = function(string) {
    return (''+string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
  };

  // If the value of the named property is a function then invoke it;
  // otherwise, return it.
  _.result = function(object, property) {
    if (object == null) return null;
    var value = object[property];
    return _.isFunction(value) ? value.call(object) : value;
  };

  // Add your own custom functions to the Underscore object, ensuring that
  // they're correctly added to the OOP wrapper as well.
  _.mixin = function(obj) {
    each(_.functions(obj), function(name){
      addToWrapper(name, _[name] = obj[name]);
    });
  };

  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  _.uniqueId = function(prefix) {
    var id = idCounter++;
    return prefix ? prefix + id : id;
  };

  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
    evaluate    : /<%([\s\S]+?)%>/g,
    interpolate : /<%=([\s\S]+?)%>/g,
    escape      : /<%-([\s\S]+?)%>/g
  };

  // When customizing `templateSettings`, if you don't want to define an
  // interpolation, evaluation or escaping regex, we need one that is
  // guaranteed not to match.
  var noMatch = /.^/;

  // Certain characters need to be escaped so that they can be put into a
  // string literal.
  var escapes = {
    '\\': '\\',
    "'": "'",
    'r': '\r',
    'n': '\n',
    't': '\t',
    'u2028': '\u2028',
    'u2029': '\u2029'
  };

  for (var p in escapes) escapes[escapes[p]] = p;
  var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
  var unescaper = /\\(\\|'|r|n|t|u2028|u2029)/g;

  // Within an interpolation, evaluation, or escaping, remove HTML escaping
  // that had been previously added.
  var unescape = function(code) {
    return code.replace(unescaper, function(match, escape) {
      return escapes[escape];
    });
  };

  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  _.template = function(text, data, settings) {
    settings = _.defaults(settings || {}, _.templateSettings);

    // Compile the template source, taking care to escape characters that
    // cannot be included in a string literal and then unescape them in code
    // blocks.
    var source = "__p+='" + text
      .replace(escaper, function(match) {
        return '\\' + escapes[match];
      })
      .replace(settings.escape || noMatch, function(match, code) {
        return "'+\n_.escape(" + unescape(code) + ")+\n'";
      })
      .replace(settings.interpolate || noMatch, function(match, code) {
        return "'+\n(" + unescape(code) + ")+\n'";
      })
      .replace(settings.evaluate || noMatch, function(match, code) {
        return "';\n" + unescape(code) + "\n;__p+='";
      }) + "';\n";

    // If a variable is not specified, place data values in local scope.
    if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

    source = "var __p='';" +
      "var print=function(){__p+=Array.prototype.join.call(arguments, '')};\n" +
      source + "return __p;\n";

    var render = new Function(settings.variable || 'obj', '_', source);
    if (data) return render(data, _);
    var template = function(data) {
      return render.call(this, data, _);
    };

    // Provide the compiled function source as a convenience for build time
    // precompilation.
    template.source = 'function(' + (settings.variable || 'obj') + '){\n' +
      source + '}';

    return template;
  };

  // Add a "chain" function, which will delegate to the wrapper.
  _.chain = function(obj) {
    return _(obj).chain();
  };

  // The OOP Wrapper
  // ---------------

  // If Underscore is called as a function, it returns a wrapped object that
  // can be used OO-style. This wrapper holds altered versions of all the
  // underscore functions. Wrapped objects may be chained.
  var wrapper = function(obj) { this._wrapped = obj; };

  // Expose `wrapper.prototype` as `_.prototype`
  _.prototype = wrapper.prototype;

  // Helper function to continue chaining intermediate results.
  var result = function(obj, chain) {
    return chain ? _(obj).chain() : obj;
  };

  // A method to easily add functions to the OOP wrapper.
  var addToWrapper = function(name, func) {
    wrapper.prototype[name] = function() {
      var args = slice.call(arguments);
      unshift.call(args, this._wrapped);
      return result(func.apply(_, args), this._chain);
    };
  };

  // Add all of the Underscore functions to the wrapper object.
  _.mixin(_);

  // Add all mutator Array functions to the wrapper.
  each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
    var method = ArrayProto[name];
    wrapper.prototype[name] = function() {
      var wrapped = this._wrapped;
      method.apply(wrapped, arguments);
      var length = wrapped.length;
      if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];
      return result(wrapped, this._chain);
    };
  });

  // Add all accessor Array functions to the wrapper.
  each(['concat', 'join', 'slice'], function(name) {
    var method = ArrayProto[name];
    wrapper.prototype[name] = function() {
      return result(method.apply(this._wrapped, arguments), this._chain);
    };
  });

  // Start chaining a wrapped Underscore object.
  wrapper.prototype.chain = function() {
    this._chain = true;
    return this;
  };

  // Extracts the result from a wrapped and chained object.
  wrapper.prototype.value = function() {
    return this._wrapped;
  };

}).call(this);

define("underscore", (function (global) {
    return function () {
        return global._;
    }
}(this)));

/*
	Alternative approach (not using a custom event dispatcher )
		-- create a dedicated dom element to act as an event dispatcher
		-- addEventListener, removeEventListener API
		-- dispatching event
			var event = document.createEvent( "HTMLEvents", 1, 2 );
			event.initEvent( type, true, true );
			extend( event, properties );
			eventDispatcher.dispatchEvent( event );
*/

define('oats/events',["underscore"], function(_){

	// event dispatcher is stolen from Backbone.js

	// Regular expression used to split event strings
	var eventSplitter = /\s+/;

	// A module that can be mixed in to *any object* in order to provide it with
	// custom events. You may bind with `on` or remove with `off` callback functions
	// to an event; `trigger`-ing an event fires all callbacks in succession.
	//
	//     var object = {};
	//     _.extend(object, Backbone.Events);
	//     object.on('expand', function(){ alert('expanded'); });
	//     object.trigger('expand');
	//

	var Events = {

		// Bind one or more space separated events, `events`, to a `callback`
		// function. Passing `"all"` will bind the callback to all events fired.
		on: function(events, callback, context) {
			var calls, event, list;
			if (!callback) return this;

			events = events.split(eventSplitter);
			calls = this._callbacks || (this._callbacks = {});

			while (event = events.shift()) {
			list = calls[event] || (calls[event] = []);
			list.push(callback, context);
			}

			return this;
		},

		// Remove one or many callbacks. If `context` is null, removes all callbacks
		// with that function. If `callback` is null, removes all callbacks for the
		// event. If `events` is null, removes all bound callbacks for all events.
		off: function(events, callback, context) {
			var event, calls, list, i;

			// No events, or removing *all* events.
			if (!(calls = this._callbacks)) return this;

			if (!(events || callback || context)) {
				delete this._callbacks;
				return this;
			}

			events = events ? events.split(eventSplitter) : _.keys(calls);

			// Loop through the callback list, splicing where appropriate.
			while (event = events.shift()) {
				if (!(list = calls[event]) || !(callback || context)) {
					delete calls[event];
					continue;
				}

				for (i = list.length - 2; i >= 0; i -= 2) {
					if (!(callback && list[i] !== callback || context && list[i + 1] !== context)) {
						list.splice(i, 2);
					}
				}
			}

			return this;
		},

		// Trigger one or many events, firing all bound callbacks. Callbacks are
		// passed the same arguments as `trigger` is, apart from the event name
		// (unless you're listening on `"all"`, which will cause your callback to
		// receive the true name of the event as the first argument).
		trigger: function(events) {
			var event, calls, list, i, length, args, all, rest;

			if (!(calls = this._callbacks)) return this;

			rest = [];
			events = events.split(eventSplitter);

			// Fill up `rest` with the callback arguments.  Since we're only copying
			// the tail of `arguments`, a loop is much faster than Array#slice.
			for (i = 1, length = arguments.length; i < length; i++) {
				rest[i - 1] = arguments[i];
			}

			// For each event, walk through the list of callbacks twice, first to
			// trigger the event, then to trigger any `"all"` callbacks.
			while (event = events.shift()) {
				// Copy callback lists to prevent modification.
				if (all = calls.all) all = all.slice();
				if (list = calls[event]) list = list.slice();

				// Execute event callbacks.
				if (list) {
					for (i = 0, length = list.length; i < length; i += 2) {
						list[i].apply(list[i + 1] || this, rest);
					}
				}

				// Execute "all" callbacks.
				if (all) {
					args = [event].concat(rest);
					for (i = 0, length = all.length; i < length; i += 2) {
						all[i].apply(all[i + 1] || this, args);
					}
				}
			}

			return this;
		}
	};

	return Events;

});
define('oats/Channels/local.receiver',["underscore","oats/events"], function(_,Events){

	var localMessageFilter = function(message){ return message.destination === "oats"; };

	function timestampData(data, attributeName){

		if(typeof data[attributeName] !== 'undefined'){
			throw new Error("Timestamping over existing attribute: " + attributeName);
		}

		var now = new Date();

		data[attributeName] = Date.UTC(
			now.getUTCFullYear(),now.getUTCMonth(),
			now.getUTCDate(),now.getUTCHours(), now.getUTCMinutes(),
			now.getUTCSeconds(), now.getUTCMilliseconds()
		);

		return data;
	}

	function LocalReceiver(){
		var that = this;
		window.addEventListener("message", _.bind(function(event) {
			// TODO: add a way to verify where the message comes from
			//if (event.source != window) return;

			if(localMessageFilter(event.data)){
				var data = timestampData(event.data,"t_dispatch_rcvd");
				console.log("[LOCAL RECEIVER] got data", data);
				this.trigger("Receive", data);
			}

		},this), false);
	}

	_.extend(LocalReceiver.prototype, Events, {

	});

	return LocalReceiver;
});
define('oats/api.specification',[], function(){

	return {

		isValidAction : function(action){
			return this.actions.indexOf(action) !== -1;
		},

		actions : [
			"swipe-left",
			"swipe-right",
			"swipe-up",
			"swipe-down",
			"tap",
			"hold",
			"release",
			"zoom-in",
			"zoom-out"
			// "drag-start",
			// "drag-end",
			// "dragging",
		],

		signals : {

			CLIENT_REGISTER : "oats.client.register",
			CLIENT_REGISTERED : "oats.client.registered",
			CLIENT_SYNCED : "oats.client.synced",
			CLIENT_OUT_OF_SYNC : "oats.client.out_of_sync"
 		},

 		isValidSignal : function(signal){
			return [
					this.signals.CLIENT_REGISTER,
					this.signals.CLIENT_REGISTERED,
					this.signals.CLIENT_SYNCED,
					this.signals.CLIENT_OUT_OF_SYNC
			].indexOf(signal) !== -1;

		}

	};

});
define('settings',[], function(){
	return {
		applicationKey : "1234567890",
		authenticationCheckUrl : "http://www.remot.io/auth/check/",
		channelResolutionUrl : "http://www.remot.io/auth/channel/resolve/",
		pusherAuthEndpoint : 'http://www.remot.io/pusher/auth/',
		pusherApplicationKey : "0b6ee8539603f52808dd",
		actionEventName : "client-action",
		loginUrl : "http://www.remot.io/auth/login/",
		installationWidgetUrl : "http://www.remot.io/widgets/install/",
		widgetRegistrationUrl : "http://www.remot.io/extension/register/",
		syncWidgetUrl : "http://www.remot.io/widgets/sync/",
		controllerUrl : "http://www.remot.io/c/",
		extensionCheckTimeout : 3000,
		debug : false
	};
});
define('oats/client.bootstrap',["oats/api.specification","settings"], function(ApiSpecification, settings){

	function isExtensionInstalled(){
		return document.getElementById("remoats-plugin-installed") != null;
	}

	function getExtensionId(){
		var el = document.getElementById("remoats-plugin-installed");
		return el != null ? el.getAttribute("data-extension-id") : null;
	}

	function getWidgetUrl(){
		var el = document.getElementById("remoats-plugin-installed");
		return el != null ? el.getAttribute("data-widget-url") : null;
	}

	function Widget(widgetUrl){
		this.widget  = document.createElement("iframe");

		var widget = this.widget;

		widget.setAttribute("style", "border: none; position:fixed; z-index:10000; right:0; top:90px; width: 46px; height: 49px;");
		widget.setAttribute("id", "remotes-widget");
		widget.setAttribute("scrolling", "no");
		widget.setAttribute("src", widgetUrl);

		window.addEventListener("message", function(event) {
			if(typeof event.data.destination !== 'undefined'){
				if(event.data.destination === "widget"){
					widget.style.width = event.data.size.width;
					widget.style.height = event.data.size.height;
				}

				if(event.data.destination === "page"){
					widget.contentWindow.postMessage(event.data,"*");
				}

			}
		}, false);
	}

	Widget.prototype = {

		render : function(){
			document.body.appendChild(this.widget);
		}

	};

	function Bootstrap(){ }

	Bootstrap.prototype = {

		check : function(){
			var that = this;
			setTimeout(function(){
				new Widget(settings.syncWidgetUrl).render();
				that.registerClient();
				that.onReady();
				// if(isExtensionInstalled()){
				// 	new Widget(getWidgetUrl()).render();

				// 	that.registerClient();
				// 	that.onReady();
				// } else {
				// 	new Widget(settings.installationWidgetUrl).render();
				// }
			}, settings.extensionCheckTimeout);
		},

		registerClient : function(){
			window.postMessage({signal : ApiSpecification.signals.CLIENT_REGISTER }, "*");
		},

		onReady : function(){
    	}

	};

	return Bootstrap;
});
define('oats/client',[ "underscore",
		 "oats/events",
		 "oats/Channels/local.receiver",
		 "oats/api.specification",
		 "oats/client.bootstrap"
		 ], function(_, Events, Receiver, ApiSpecification, ClientBootstrap){

		function Client(applicationKey){
			var that = this;
			var bootstrap = new ClientBootstrap();

			bootstrap.onReady = function(){
				that.__setupClient();
			};

			bootstrap.check();
		}

		_.extend(Client.prototype, Events, {
			__setupClient : function(){
				new Receiver().on("Receive", function(data){

					if(typeof data.action !== 'undefined'){

						if(!ApiSpecification.isValidAction(data.action)){
							throw new Error("Invalid action: " + data.action);
						}

						this.trigger(data.action, data.actionArgs);
					}

					if(typeof data.signal !== 'undefined'){

						if(!ApiSpecification.isValidSignal(data.signal)){
							throw new Error("Invalid signal: " + data.signal);
						}

						switch(data.signal){
							case ApiSpecification.signals.CLIENT_REGISTERED:
								this.trigger("ready");
								break;

							case ApiSpecification.signals.CLIENT_SYNCED:
								this.trigger("synced");
								break;

							case ApiSpecification.signals.CLIENT_OUT_OF_SYNC:
								this.trigger("out-of-sync");
								break;
						}

					}

				}, this);
			},

			onNotAuthenticated : function(){
				alert("please log in");
			}
		});

		return Client;

	}
);    return require("oats/client");
}));


text:
{{service.title}}
                    service

                    About

Azure Redis Cache is based on the popular open-source Redis cache. It gives you access to a secure, dedicated Redis cache, managed by Microsoft and accessible from any application within Azure.

Azure Redis Cache is easy to use. Just provision a cache using the Microsoft Azure portal and call into its end point using any client that supports Redis. If you've used Redis before, you already know how to use Azure Redis Cache.

                    High performance

Azure Redis Cache helps your application become more responsive even as user load increases. It leverages the low-latency, high-throughput capabilities of the Redis engine. This separate, distributed cache layer allows your data tier to scale independently for more efficient use of compute resources in your application layer.

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Шаблонизация с помощью PHP
 * @link http://boolive.ru/createcms/making-page
 * @version 2.0
 * @author Vladimir Shestakov <boolive@yandex.ru>
 */
namespace boolive\core\template\php;

class PHPTemplate
{
    /**
     * Создание текста из шаблона
     * В шаблон вставляются переданные значения
     * При обработки шаблона могут довыбираться значения из $entity и создаваться команды в $request
     * @param string $entity Полный путь на файл шаблона
     * @param array $v Значения для шаблона
     * @throws \Exception
     * @return string
     */
    function render($template, $v)
    {
        try{
            // Массив $v достпуен в php-файле шаблона, подключамом ниже
            $v = new PHPTemplateValues($v, null);
            ob_start();
                include($template);
                $result = ob_get_contents();
            ob_end_clean();
        }catch (\Exception $e){
            ob_end_clean();
//          if ($e->getCode() == 2){
//              echo "Template file '{$entity->file()}' not found";
//          }else{
                throw $e;
//          }
        }
        return $result;
    }
}


text:
<?php

namespace HMS\Entities\Lighting;

class Pattern
{
    /**
     * @var int
     */
    protected $id;

    /**
     * @var string
     */
    protected $name;

    /**
     * @var Pattern|null
     */
    protected $nextPattern;

    /**
     * @var int|null
     */
    protected $timeout;

    /**
     * Gets the value of id.
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     *
     * @return self
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @return Pattern|null
     */
    public function getNextPattern()
    {
        return $this->nextPattern;
    }

    /**
     * @param Pattern|null $nextPattern
     *
     * @return self
     */
    public function setNextPattern($nextPattern)
    {
        $this->nextPattern = $nextPattern;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getTimeout()
    {
        return $this->timeout;
    }

    /**
     * @param int|null $timeout
     *
     * @return self
     */
    public function setTimeout($timeout)
    {
        $this->timeout = $timeout;

        return $this;
    }
}


text:
/**
 * Created by jphet on 23/05/2017.
 */
import React from "react";

export default class CVInfoComposent extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        const {infos}       = this.props;
        const infoComposent = infos.map((info) => {
            const {titre, url} = info;

            if (titre) {
                if (url) {
                    return
{titre}
                        {url}

;
                }
            }
            return
{info}
;
        });
        return

            {infoComposent}

    }
}


text:
import * as mongoose from 'mongoose';

const courseSchema = new mongoose.Schema({
  place: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Place'
  },
  title: String,
  description: String,
  cost: Number
});

const Course = mongoose.model('Course', courseSchema);
export default Course;


text:
'use strict';

import React, { Component } from "react";
import ReactDOM from "react-dom";
import Pane from './Pane';
import Resizer from './Resizer';
import Radium from "radium";

const styles = {
  base: {
    display: 'flex',
    flex: 1,
    outline: 'none',
    overflow: 'hidden',
    userSelect: 'none',
    position: 'absolute'
  },
  vertical: {
    flexDirection: 'row',
    height: '100%',
    left: 0,
    right: 0
  },
  horizontal: {
    flexDirection: 'column',
    height: '100%',
    minHeight: '100%',
    top: 0,
    bottom: 0,
    width: '100%'
  }
}

@Radium
class SplitPane extends Component {

    constructor() {
      super();
      let self = this;
      self.state = {
        active: false,
        resized: false,
        windowWidth: window.innerWidth,
        windowHeight: window.innerHeight
      };
      self.lastReportedRef = null;
      window.addEventListener('resize', self, false);
    }

    handleResize() {
      let self = this;
      self.setState({windowWidth: window.innerWidth, windowHeight: window.innerHeight});
      if(self.props.onSetSize) {
        let ref = self.refs.pane1;
        if(ref) {
          let refSize = self.getRefSize(ref);
          self.onSetSize(refSize);
        }
      }
    }

    onSetSize(refSize) {
      let self = this;
      if(self.props.onSetSize) {
        if(refSize != self.lastReportedRef) {
          self.lastReportedRef = refSize;
          self.props.onSetSize(refSize);
        }
      }
    }

    componentDidMount() {
        let self = this;
        const ref = self.refs.pane1;
        if (ref && self.props.defaultSize && !self.state.resized) {
          let defaultSize = self.props.defaultSize;
          if(defaultSize === 'auto') {
            let element = ReactDOM.findDOMNode(ref);
            let total_height = 0;
            for (var i in element.children) {
              total_height += element.children[i].clientHeight || 0;
            }
            ref.setState({
              size: total_height
            });
            self.setState({
              refSize: total_height
            });
          } else {
            ref.setState({
              size: defaultSize
            });
          }
        }
    }

    handleEvent(event) {
      let self = this;
      switch(event.type) {
        case 'mouseup':
          self.onMouseUp(event);
          break;
        case 'mousemove':
          self.onMouseMove(event);
          break;
        case 'resize':
          self.handleResize(event);
          break;
      }
    }

    componentWillUnmount() {
      let self = this;
      window.removeEventListener('resize', self, false);
    }

    onMouseDown(event) {
      let self = this;
      if(self.props.resizable === true) {
        let position = self.props.split === 'vertical' ? event.screenX : event.screenY;
        let ref = self.refs.pane1;
        let size = self.getRefSize(ref);
        self.setState({
          active: true,
          startPosition: position,
          startSize: size
        });
        document.addEventListener('mouseup', self, false);
        document.addEventListener('mousemove', self, false);
      }
    }

    onMouseUp() {
      let self = this;
      document.removeEventListener('mouseup', self, false);
      document.removeEventListener('mousemove', self, false);
      self.setState({
        active: false
      });
      if(self.props.onSetSize) {
        let ref = self.refs.pane1;
        if(ref) {
          self.onSetSize(self.getRefSize(ref));
        }
      }
    }

    getRefSize(ref) {
      let self = this;
      if (ref) {
        const element = ReactDOM.findDOMNode(ref);
        const styles = element.currentStyle ? element.currentStyle : window.getComputedStyle(element, null);
        const width = styles.width.replace('px', '');
        const height = styles.height.replace('px', '');
        const size = self.props.split === 'vertical' ? width : height;
        return size;
      } else {
        return 0;
      }
    }

    onMouseMove(event) {
      let self = this;
      let ref = self.refs.pane1;
      if (self.state.active && ref) {

        const current = self.props.split === 'vertical' ? event.screenX : event.screenY;
        const starting = self.state.startPosition;
        const newSize = self.state.startSize - (starting - current);

        let maxSize;
        let minSize;

        if(!self.props.maxSize){
          maxSize = self.props.split === 'vertical' ? self.state.windowHeight - 11 : self.state.windowWidth - 11;
        } else {
          maxSize = self.props.maxSize;
        }

        if(!self.props.minSize){
          minSize = 5;
        } else {
          minSize = self.props.minSize;
        }

        let finalSize = newSize;

        if(newSize < self.props.minSize) { finalSize = self.props.minSize; }
        if(newSize > self.props.maxSize) { finalSize = self.props.maxSize; }

        self.setState({
          position: current,
          resized: true,
          refSize: finalSize
        });

        ref.setState({
          size: finalSize
        });
      }
    }

    render() {
        let self = this;
        const split = self.props.split || 'vertical';
        const children = self.props.children;
        const classes = ['SplitPane', split, self.props.className];
        return (
            <div className={classes.join(' ')} style={[styles.base, styles[split]]} ref="splitPane">
                <Pane ref="pane1" key="pane1" split={split}>{children[0]}</Pane>
                <Resizer ref="resizer" key="resizer" onMouseDown={self.onMouseDown.bind(self)} split={split} resizable={self.props.resizable} resizerGripWidth={self.props.resizerGripWidth} resizerBorderWidth={self.props.resizerBorderWidth} />
                <Pane ref="pane2" key="pane2" split={split}>{children[1]}</Pane>
            </div>
        );
    }
}

SplitPane.defaultProps = {
  minSize: 0,
  maxSize: Infinity,
  defaultSize: 'auto',
  resizable: true,
  resizerBorderWidth: 1,
  resizerGripWidth: 5
};

export default SplitPane;


text:
using Newtonsoft.Json;

namespace Vault.Models.Auth.Token
{
    public class LookupAccessorRequest
    {
        [JsonProperty("accessor")]
        public string Accessor { get; set; }
    }
}


text:
package com.microsoft.awt.routes

import org.scalajs.nodejs.console
import org.scalajs.sjs.OptionHelper._

import scala.language.implicitConversions
import scala.scalajs.js
import scala.scalajs.js.JSConverters._

/**
  * Shared Content Processor
  * @author lawrence.daniels@gmail.com
  */
object SharedContentProcessor {
  private[this] val expandables = List(""" -> "\"", "'" -> "'") ::: (27 to 383).map(n => s"&#$n;" -> f"$n%c").toList

  /**
    * Parses Social media metadata
    * @param metadata the given news/article URL
    * @return the aggregated Social media metadata
    */
  def parseMetaData(metadata: Map[String, String]): Option[SharedContent] = {
    // gather as much meta data as possible
    val results = metadata.toSeq // extractTitle(doc) ++ extractMetaData(doc, keyName = "name") ++ extractMetaData(doc, keyName = "property")
    val props = Map(results: _*)
    results.foreach { case (k, v) => console.log(s"meta: $k => $v") }

    // build the list of metadata sources
    val sources = (
      extractArticleMetaData(results, props) :: extractFacebookMetaData(results, props) ::
        extractGenericMetaData(results, props) :: extractLinkedInMetaData(results, props) ::
        extractOpenGraphMetaData(results, props) :: extractSailthruMetaData(results, props) ::
        extractShareaholicMetaData(results, props) :: extractTwitterMetaData(results, props) :: Nil
      ).flatten

    // if there's isn't at least one source that 80% complete or more, also include JSON_LD
    //if (!sources.exists(_.completeness >= 0.80d)) sources = extractJsonLD(url).toList ::: sources

    // create a composite web page summary; using the most complete summary as the template
    sources.sortBy(-_.completeness).headOption map { initialSummary =>
      sources.foldLeft[SharedContent](initialSummary) { (compositeSummary, summary) =>
        compositeSummary.copy(
          author = compositeSummary.author ?? summary.author,
          description = compositeSummary.description ?? summary.description,
          locale = compositeSummary.locale ?? summary.locale,
          publishedTime = compositeSummary.publishedTime ?? summary.publishedTime,
          section = compositeSummary.source ?? summary.section,
          source = compositeSummary.source ?? summary.source,
          tags = (compositeSummary.tags.getOrElse(Nil) ::: summary.tags.getOrElse(Nil)).map(_.trim.toLowerCase).distinct,
          thumbnailUrl = compositeSummary.thumbnailUrl ?? summary.thumbnailUrl,
          title = compositeSummary.title ?? summary.title,
          updatedTime = compositeSummary.updatedTime ?? summary.updatedTime,
          url = compositeSummary.url ?? summary.url
        )
      }
    }
  }

  ///////////////////////////////////////////////////////////////////////////
  //      HTMLx meta-data functions
  ///////////////////////////////////////////////////////////////////////////

  /**
    * Parses Google (Article, etc.) SEO metadata
    *

    * article:author => http://www.businessinsider.com/author/drake-baer
    * article:modified_time => 2015-10-28T11:12:34+00:00
    * article:publisher => businessinsider
    * article:published_time => 2015-10-28T11:10:20+00:00
    * article:section => Job Hunting
    * article:tag => Job Hunting
    * article:tag => Job Skills
    * article:tag => Unemployment
    *

    */
  private def extractArticleMetaData(results: Seq[(String, String)], props: Map[String, String]) = {
    val author = props.get("article:author")
    val tags = results.filter(_._1 == "article:tag").map(_._2).toList
    val modified_time = props.get("article:modified_time").flatMap(parseDate(_, format = "yyyy-MM-dd'T'HH:mm:ssZ"))
    val published_time = props.get("article:published_time").flatMap(parseDate(_, format = "yyyy-MM-dd'T'HH:mm:ssZ"))
    val section = props.get("article:section")
    Option(SharedContent(author = author, section = section, thumbnailUrl = None, publishedTime = published_time, tags = tags, updatedTime = modified_time))
  }

  /**
    * Parses Facebook SEO metadata
    *

    * fb:app_id => 155043519637
    *

    */
  private def extractFacebookMetaData(results: Seq[(String, String)], props: Map[String, String]): Option[SharedContent] = None

  /**
    * Parses Generic (legacy) SEO metadata
    *

    * author => Drake Baer
    * date => 2015-10-22
    * description => Learning strategies that really work.
    * news_keywords => Learning, Cognitive Function, Education, Productivity, Psychology, Features, Drake Baer,
    * title => 4 strategies for remembering everything you learn
    *

    */
  private def extractGenericMetaData(results: Seq[(String, String)], props: Map[String, String]) = {
    val author = props.get("author")
    val date = props.get("date").flatMap(parseDate(_, format = "yyyy-MM-dd"))
    val description = props.get("description")
    val keywords = props.get("news_keywords").map(parseTags)
    val title = props.get("title")
    Option(SharedContent(author = author, description = description, thumbnailUrl = None, publishedTime = date, tags = keywords, title = title))
  }

  /**
    * Parses LinkedIn SEO metadata
    *

    * linkedin:owner => mid:1d5f7b
    *

    */
  private def extractLinkedInMetaData(results: Seq[(String, String)], props: Map[String, String]) = None

  /**
    * Parses Open Graph SEO metadata
    *

    * og:locale => en_US
    * og:type => article
    * og:title => Tech Unemployment Rises In Some Categories - Dice Insights
    * og:description => The technology industry's unemployment rate crept up to 3.0 percent in the third quarter of 2015, according to the U.S. Bureau of Labor Statistics (BLS).
    * og:url => http://insights.dice.com/2015/10/28/tech-unemployment-rises-in-some-categories/
    * og:site_name => Dice Insights
    * og:updated_time => 2015-10-28T11:12:34+00:00
    * og:image => http://insights.dice.com/wp-content/uploads/2015/10/2015-Q3_Full_Report_Image1.png
    *

    */
  private def extractOpenGraphMetaData(results: Seq[(String, String)], props: Map[String, String]) = {
    for {
      image <- props.get("og:image")
      description = props.get("og:description")
      locale = props.get("og:locale")
      site_name = props.get("og:site_name")
      title = props.get("og:title")
      url = props.get("og:url")
      updated_time = props.get("og:updated_time").flatMap(parseDate(_, format = "yyyy-MM-dd'T'HH:mm:ssZ"))
    } yield SharedContent(description = description, locale = locale, thumbnailUrl = image, title = title, source = site_name, url = url, updatedTime = updated_time)
  }

  /**
    * Parses Sailthru SEO metadata
    *

    * sailthru.author => Drake Baer
    * sailthru.date => 2015-10-22
    * sailthru.description => Learning strategies that really work.
    * sailthru.image.full => http://static5.businessinsider.com/image/56292a629dd7cc1b008c4139/4-strategies-for-remembering-everything-you-learn.jpg
    * sailthru.image.thumb => http://static2.businessinsider.com/image/56292a629dd7cc1b008c4139-50-50/4-strategies-for-remembering-everything-you-learn.jpg
    * sailthru.tags => Learning, Cognitive Function, Education, Productivity, Psychology, Features, Drake Baer,
    * sailthru.title => 4 strategies for remembering everything you learn
    * sailthru.verticals => warroom,education,science
    *

    * @param results the given collection of key-value pairs
    */
  private def extractSailthruMetaData(results: Seq[(String, String)], props: Map[String, String]) = {
    for {
      imageThumb <- props.get("sailthru.image.thumb")
      imageFull = props.get("sailthru.image.full")
      author = props.get("sailthru.author")
      date = props.get("sailthru.date").flatMap(parseDate(_, "yyyy-MM-dd"))
      description = props.get("sailthru.description")
      tags = props.get("sailthru.tags").map(parseTags)
      title = props.get("sailthru.title")
      url = props.get("sailthru.url")
    } yield SharedContent(author = author, description = description, tags = tags, thumbnailUrl = imageFull, title = title, url = url, publishedTime = date)
  }

  /**
    * Parses Shareaholic SEO metadata
    *

    * shareaholic:site_name => Dice Insights
    * shareaholic:language => en-US
    * shareaholic:url => http://insights.dice.com/2015/10/28/tech-unemployment-rises-in-some-categories/
    * shareaholic:keywords => job hunting, job skills, unemployment, technology, industry
    * shareaholic:article_published_time => 2015-10-28T15:10:20+00:00
    * shareaholic:article_modified_time => 2015-11-23T16:16:26+00:00
    * shareaholic:shareable_page => true
    * shareaholic:article_author_name => Dice Staff
    * shareaholic:site_id => 95e918a36eb505f905f5ad1d1c1400ee
    * shareaholic:wp_version => 7.6.1.8
    * shareaholic:image => http://insights.dice.com/wp-content/uploads/2015/10/2015-Q3_Full_Report_Image1-1024x665.png
    *

    */
  private def extractShareaholicMetaData(results: Seq[(String, String)], props: Map[String, String]) = {
    for {
      image <- props.get("shareaholic:image")
      keywords = props.get("shareaholic:keywords").map(parseTags)
      language = props.get("shareaholic:language")
      modified_time = props.get("shareaholic:article_modified_time").flatMap(parseDate(_, format = "yyyy-MM-dd'T'HH:mm:ssZ"))
      published_time = props.get("shareaholic:article_published_time").flatMap(parseDate(_, format = "yyyy-MM-dd'T'HH:mm:ssZ"))
      site_name = props.get("shareaholic:site_name")
      url = props.get("shareaholic:url")
    } yield SharedContent(locale = language, thumbnailUrl = image, source = site_name, url = url, tags = keywords, publishedTime = published_time, updatedTime = modified_time)
  }

  /**
    * Parses Twitter SEO metadata
    *

    * twitter:card => summary_large_image
    * twitter:creator => drake_baer
    * twitter:description => The technology industry's unemployment rate crept up to 3.0 percent in the third quarter of 2015, according to the U.S. Bureau of Labor Statistics (BLS).
    * twitter:title => Tech Unemployment Rises In Some Categories - Dice Insights
    * twitter:domain => Dice Insights
    * twitter:image => http://insights.dice.com/wp-content/uploads/2015/10/2015-Q3_Full_Report_Image1.png
    * twitter:site => bi_strategy
    *

    */
  private def extractTwitterMetaData(results: Seq[(String, String)], props: Map[String, String]) = {
    for {
      image <- props.get("twitter:image")
      creator = props.get("twitter:creator")
      description = props.get("twitter:description")
      domain = props.get("twitter:domain")
      site = props.get("twitter:site")
      title = props.get("twitter:title")
    } yield SharedContent(author = creator, description = description, thumbnailUrl = image, title = title, source = site)
  }

  ///////////////////////////////////////////////////////////////////////////
  //      Utility functions
  ///////////////////////////////////////////////////////////////////////////

  /**
    * Parses the given text and returns its date equivalent
    * @param text the given text string
    * @return the [[java.util.Date date]]
    */
  private def parseDate(text: String, format: String) = Option(new js.Date(js.Date.parse(text)))

  /**
    * Parses the given tag string into a collection of tags
    * @param tagList the given tag string
    * @return a collection of tags
    */
  private def parseTags(tagList: String) = tagList.trim.split("[,]").toList

  implicit def value2Option[T](value: T): Option[T] = Option(value)

  /**
    * Represents Shared Content; usually posted from a news site, etc.
    * @author lawrence.daniels@gmail.com
    */
  case class SharedContent(author: Option[String] = None,
                           description: Option[String] = None,
                           locale: Option[String] = None,
                           publishedTime: Option[js.Date] = None,
                           section: Option[String] = None,
                           source: Option[String] = None,
                           tags: Option[List[String]] = None,
                           thumbnailUrl: Option[String],
                           title: Option[String] = None,
                           updatedTime: Option[js.Date] = None,
                           url: Option[String] = None) {

    def completeness = {
      val values = Seq(author, description, locale, publishedTime, section, source, tags, thumbnailUrl, title, updatedTime, url)
      val count = values.foldLeft[Int](0) { (total, value) => total + value.map(_ => 1).getOrElse(0) }
      count / values.length.toDouble
    }

    def toJson = {
      js.Dictionary(
        "author" -> author.map(_.expandMarkup).orUndefined,
        "description" -> description.map(_.expandMarkup).orUndefined,
        "locale" -> locale.map(_.expandMarkup).orUndefined,
        "publishedTime" -> publishedTime.orUndefined,
        "section" -> section.orUndefined,
        "source" -> source.orUndefined,
        "tags" -> tags.map(js.Array(_: _*)).orUndefined,
        "thumbnailUrl" -> thumbnailUrl.orUndefined,
        "title" -> title.map(_.expandMarkup).orUndefined,
        "updatedTime" -> updatedTime.orUndefined,
        "url" -> url.orUndefined
      )
    }

  }

  /**
    * String Extensions
    * @author lawrence.daniels@gmail.com
    */
  implicit class StringExtensions(val text: String) extends AnyVal {

    def expandMarkup: String = {
      expandables.foldLeft(text) { case (s, (expandable, replacement)) =>
        s.replaceAll(expandable, replacement)
      }
    }

  }

}


text:
package com.xiaogua.better.basic;

import java.util.HashSet;
import java.util.Set;

import org.junit.Test;

public class TestSetCode {

	@Test
	public void testHashSetAddAll() {
		Set<String> set = new HashSet<String>(0);
		Set<String> set2 = new HashSet<String>();
		set2.add("test_1");
		set2.add("test_2");
		set.addAll(set2);
		System.out.println(set);
	}
}


text:
package com.iluwatar.aggregator.microservices;

import static java.util.Objects.requireNonNullElse;

import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * The aggregator aggregates calls on various micro-services, collects data and further publishes
 * them under a REST endpoint.
 */
@RestController
public class Aggregator {

  @Resource
  private ProductInformationClient informationClient;

  @Resource
  private ProductInventoryClient inventoryClient;

  /**
   * Retrieves product data.
   *
   * @return a Product.
   */
  @RequestMapping(path = "/product", method = RequestMethod.GET)
  public Product getProduct() {

    var product = new Product();
    var productTitle = informationClient.getProductTitle();
    var productInventory = inventoryClient.getProductInventories();

    //Fallback to error message
    product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed"));

    //Fallback to default error inventory
    product.setProductInventories(requireNonNullElse(productInventory, -1));

    return product;
  }

}


text:
class BlurbsController < ApplicationController
  before_filter :authorize

  def destroy
    blurb = Blurb.find(params[:id])
    blurb.destroy
    flash[:notice] = 'Blurb successfully deleted'
    redirect_to blurb.project
  end
end


text: <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">


text:
/**
\file	RbOrganism.cpp

\brief	Implements the vortex organism class.
**/

#include "StdAfx.h"
#include "RbMovableItem.h"
#include "RbBody.h"
#include "RbRigidBody.h"
#include "RbJoint.h"
#include "RbOrganism.h"
#include "RbSimulator.h"

namespace RoboticsAnimatSim
{
	namespace Environment
	{

/**
\brief	Default constructor.

\author	dcofer
\date	8/27/2011
**/
RbOrganism::RbOrganism()
{
	m_lpRbBody = NULL;
	SetThisPointers();
}

RbOrganism::~RbOrganism()
{
}

void RbOrganism::Body(RigidBody *lpBody)
{
	Organism::Body(lpBody);
	m_lpRbBody = dynamic_cast<RbMovableItem *>(lpBody);

	if(!m_lpRbBody)
		THROW_TEXT_ERROR(Rb_Err_lUnableToConvertToVsRigidBody, Rb_Err_strUnableToConvertToVsRigidBody, "ID: " + lpBody->Name());
}

void RbOrganism::SetThisPointers()
{
	RbMovableItem::SetThisPointers();

	m_lpThisST = dynamic_cast<Structure *>(this);
	if(!m_lpThisST)
		THROW_TEXT_ERROR(Rb_Err_lThisPointerNotDefined, Rb_Err_strThisPointerNotDefined, "m_lpThisST, " + m_lpThisAB->Name());

	m_lpThisOG = dynamic_cast<Organism *>(this);
	if(!m_lpThisOG)
		THROW_TEXT_ERROR(Rb_Err_lThisPointerNotDefined, Rb_Err_strThisPointerNotDefined, "m_lpThisOG, " + m_lpThisAB->Name());
}

void RbOrganism::Create()
{
	CreateItem();

	Organism::Create();
}

void RbOrganism::ResetSimulation()
{
	RbMovableItem::Physics_ResetSimulation();

	Organism::ResetSimulation();
}

    }			// Environment
}				//RoboticsAnimatSim


text:
#include "../src/utils/err.c"
#include "../src/utils/list.c"
#include "../src/utils/hash.c"
#include "../src/utils/alloc.c"

int main ()
{
    struct grid_hash hash;
    uint32_t k;
    struct grid_hash_item *item;
    struct grid_hash_item *item5000 = NULL;

    grid_hash_init (&hash);

    /*  Insert 10000 elements into the hash table. */
    for (k = 0; k != 10000; ++k) {
        item = grid_alloc (sizeof (struct grid_hash_item), "item");
        grid_assert (item);
        if (k == 5000)
            item5000 = item;
        grid_hash_item_init (item);
        grid_hash_insert (&hash, k, item);
    }

    /*  Find one element and check whether it is the correct one. */
    grid_assert (grid_hash_get (&hash, 5000) == item5000);

    /*  Remove all the elements from the hash table and terminate it. */
    for (k = 0; k != 10000; ++k) {
        item = grid_hash_get (&hash, k);
        grid_hash_erase (&hash, item);
        grid_free (item);
    }
    grid_hash_term (&hash);

    return 0;
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<link rel="shortcut icon" href="../favicon.ico" />
	<title>CrossedUp</title>
	<link rel="stylesheet" type="text/css" href="../stylesheets/stylesheet.css">
	<link rel="stylesheet" type="text/css" href="../fonts/stylesheet.css">
	<link rel="stylesheet" href="http://code.cdn.mozilla.net/fonts/fira.css">

Crossed
up

Home

Projects

Twitter

On Wireframing CrossedUp

Sunday, July 20th 2014

Initial plan and design

This being the blog of an aspiring dev, it's safe to assume that most people that would be potentially be interested are either other devs or at the very least what is considered "power users". That makes the target audience pretty small, but it means I can more or less safely ignore older browsers (specifically older versions of IE). From my limited experience with dev blogs, they tend to be either very fancy or very simple, but always usuable. Given my current technical skill, I'm going with the latter approach, which suits me fine. Keep the site clean and easy to read, that's the main focus.

©2014 Raphael Ho


text: Follow Liz on Twitter.


text:
<?php
/**
 * Plugin Name: Team  Builder
 * Version: 1.1.2
 * Description:  Team Builder is most flexible WordPress plugin available to create and manage your Team page with drag and drop feature.
 * Author: wpshopmart
 * Author URI: http://www.wpshopmart.com
 * Plugin URI: http://www.wpshopmart.com
 */

if ( ! defined( 'ABSPATH' ) ) exit;
 /**
 * DEFINE PATHS
 */
define("wpshopmart_team_b_directory_url", plugin_dir_url(__FILE__));
define("wpshopmart_team_b_text_domain", "wpsm_team_b");

require_once("ink/install.php");

function wpsm_team_b_default_data() {

	$Settings_Array = serialize( array(
				"team_mb_name_clr" 	 => "#000000",
				"team_mb_pos_clr" => "#000000",
				"team_mb_desc_clr" => "#000000",
				"team_mb_social_icon_clr"   => "#4f4f4f",
				"team_mb_social_icon_clr_bg"   => "#e5e5e5",
				"team_mb_name_ft_size"   => 18,
				"team_mb_pos_ft_size"   => 14,
				"team_mb_desc_ft_size"   => 14,
				"font_family"   => "Open Sans",
				"team_layout"   => 4,
				"custom_css"   => "",
				"team_mb_wrap_bg_clr"   => "#ffffff",
				"design"   => 1,
		) );

	add_option('Team_B_default_Settings', $Settings_Array);
}
register_activation_hook( __FILE__, 'wpsm_team_b_default_data' );

add_action('admin_menu' , 'wpsm_team_b_recom_menu');
function wpsm_team_b_recom_menu() {
	$submenu = add_submenu_page('edit.php?post_type=team_builder', __('More_Free_Plugins', wpshopmart_team_b_text_domain), __('More Free Plugins', wpshopmart_team_b_text_domain), 'administrator', 'wpsm_team_b_recom_page', 'wpsm_team_b_recom_page_funct');

	//add hook to add styles and scripts for Responsive Accordion plugin admin page
    add_action( 'admin_print_styles-' . $submenu, 'wpsm_team_b_recom_js_css' );
	}
	function wpsm_team_b_recom_js_css(){
		wp_enqueue_style('wpsm_team_b_bootstrap_css_recom', wpshopmart_team_b_directory_url.'assets/css/bootstrap.css');
		wp_enqueue_style('wpsm_ac_help_css', wpshopmart_team_b_directory_url.'assets/css/help.css');
	}
function wpsm_team_b_recom_page_funct(){
	require_once('ink/admin/free.php');
}

/**
 * CPT CLASS
 */

require_once("ink/admin/menu.php");

/**
 * SHORTCODE
 */

 require_once("template/shortcode.php");
?>


text:
/**
*	Construct a new example object
*	@class
*	@constructor
*	@extends LilyObjectBase
*/
function $example(param)
{
	var thisPtr=this;
	var args=param||null;

	this.outlet1 = new this.outletClass("outlet1",this,"help text describing this outlet");
	this.inlet1=new this.inletClass("inlet1",this,"help text describing this inlet");

	//custom method
	this.inlet1["doIt"]=function(msg) {
		thisPtr.outlet1.doOutlet("doing it " + msg);
	}

	//bang method
	this.inlet1["bang"]=function() {
		thisPtr.outlet1.doOutlet("responding to a bang...");
	}

	//anything else
	this.inlet1["anything"]=function(msg) {
		thisPtr.outlet1.doOutlet(msg);
	}

	return this;
}

var $exampleMetaData = {
	textName:"example",
	htmlName:"example",
	objectCategory:"example",
	objectSummary:"",
	objectArguments:""

}


text:
import { TestBed, inject } from '@angular/core/testing';

import { ContactsService } from './contacts.service';
import {HttpClientModule} from '@angular/common/http';

describe('ContactsService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [ContactsService],
      imports: [
        HttpClientModule
      ]
    });
  });

  it('should be created', inject([ContactsService], (service: ContactsService) => {
    expect(service).toBeTruthy();
  }));
});


text:
package api

import (
	"net/http"
	"net/url"
	"regexp"
	"strings"
	"time"

	"github.com/af83/edwig/config"
	"github.com/af83/edwig/core"
	"github.com/af83/edwig/logger"
	"github.com/af83/edwig/model"
	"github.com/af83/edwig/version"
)

type Server struct {
	model.UUIDConsumer
	model.ClockConsumer
	core.ReferentialsConsumer

	bind        string
	startedTime time.Time
}

type RequestData struct {
	Filters     url.Values
	Body        []byte
	Method      string
	Referential string
	Resource    string
	Id          string
	Action      string
	Url         string
}

func NewRequestDataFromContent(params []string) *RequestData {
	requestFiller := make([]string, 15)

	copy(requestFiller, params)

	return &RequestData{
		Referential: requestFiller[1],
		Resource:    requestFiller[2],
		Id:          requestFiller[3],
		Action:      requestFiller[4],
	}
}

func NewServer(bind string) *Server {
	server := Server{bind: bind}
	server.startedTime = server.Clock().Now()

	return &server
}

func (server *Server) ListenAndServe() error {
	http.HandleFunc("/", server.HandleFlow)

	logger.Log.Debugf("Starting server on %s", server.bind)
	return http.ListenAndServe(server.bind, nil)
}

func (server *Server) handleControllers(response http.ResponseWriter, request *http.Request, requestData *RequestData) {
	newController, ok := newControllerMap[requestData.Referential]
	if !ok {
		http.Error(response, "Invalid ressource", http.StatusBadRequest)
		return
	}

	logger.Log.Debugf("%s controller request: %v", requestData.Resource, request)

	controller := newController(server)
	controller.serve(response, request, requestData)
}

func (server *Server) parse(response http.ResponseWriter, request *http.Request) (*RequestData, bool) {
	path := request.URL.RequestURI()

	pathRegexp := "/([0-9a-zA-Z-_]+)(?:/([0-9a-zA-Z-_]+))?(?:/([0-9a-zA-Z-]+(?::[0-9a-zA-Z-:]+)?))?/?([0-9a-zA-Z-_]+)?"
	pattern := regexp.MustCompile(pathRegexp)
	foundStrings := pattern.FindStringSubmatch(path)
	if foundStrings == nil || foundStrings[1] == "" {
		http.Error(response, "Invalid request", http.StatusBadRequest)
		return nil, false
	}

	requestData := NewRequestDataFromContent(foundStrings)
	requestData.Method = request.Method
	requestData.Url = request.URL.Path
	requestData.Filters = request.URL.Query()

	response.Header().Set("Content-Type", "application/json")
	response.Header().Set("Server", version.ApplicationName())
	return requestData, true
}

func (server *Server) getToken(r *http.Request) string {
	const prefix = "Token"
	auth := r.Header.Get("Authorization")

	if !strings.HasPrefix(auth, prefix) {
		return ""
	}
	s := strings.IndexByte(auth, '=')

	return auth[s+1:]
}

func (server *Server) isAdmin(r *http.Request) bool {
	return server.getToken(r) == config.Config.ApiKey
}

func (server *Server) isAuth(referential *core.Referential, request *http.Request) bool {
	authToken := server.getToken(request)

	if authToken == "" {
		return false
	}

	for _, token := range referential.Tokens {
		if authToken == token {
			return true
		}
	}
	return false
}

func (server *Server) handleRoutes(response http.ResponseWriter, request *http.Request, requestData *RequestData) {
	if requestData.Resource == "siri" {
		server.handleSIRI(response, request, requestData)
	} else if requestData.Resource == "push" {
		server.handlePush(response, request, requestData)
	} else if strings.HasPrefix(requestData.Referential, "_") {
		if !server.isAdmin(request) {
			http.Error(response, "Unauthorized request", http.StatusUnauthorized)
			logger.Log.Debugf("Tried to access ressource admin without autorization token \n%v", request)
			return
		}
		if requestData.Referential == "_referentials" {
			requestData.Id = requestData.Resource
		}
		server.handleControllers(response, request, requestData)
	} else {
		server.handleWithReferentialControllers(response, request, requestData)
	}
}

func (server *Server) HandleFlow(response http.ResponseWriter, request *http.Request) {
	requestData, ok := server.parse(response, request)
	if !ok {
		return
	}

	server.handleRoutes(response, request, requestData)
}

func (server *Server) handleWithReferentialControllers(response http.ResponseWriter, request *http.Request, requestData *RequestData) {

	foundReferential := server.CurrentReferentials().FindBySlug(core.ReferentialSlug(requestData.Referential))
	if foundReferential == nil {
		http.Error(response, "Referential not found", http.StatusNotFound)
		return
	}
	if !server.isAuth(foundReferential, request) {
		http.Error(response, "Unauthorized request", http.StatusUnauthorized)
		return
	}
	newController, ok := newWithReferentialControllerMap[requestData.Resource]
	if !ok {
		http.Error(response, "Invalid ressource", http.StatusBadRequest)
		return
	}

	logger.Log.Debugf("%s controller request: %v", requestData.Resource, request)

	controller := newController(foundReferential)
	controller.serve(response, request, requestData)
}

func (server *Server) handleSIRI(response http.ResponseWriter, request *http.Request, requestData *RequestData) {
	foundReferential := server.CurrentReferentials().FindBySlug(core.ReferentialSlug(requestData.Referential))

	logger.Log.Debugf("SIRI request: %v", request)

	siriHandler := NewSIRIHandler(foundReferential)
	siriHandler.serve(response, request)
}

func (server *Server) handlePush(response http.ResponseWriter, request *http.Request, requestData *RequestData) {
	foundReferential := server.CurrentReferentials().FindBySlug(core.ReferentialSlug(requestData.Referential))

	logger.Log.Debugf("Push request: %v", request)

	pushHandler := NewPushHandler(foundReferential, server.getToken(request))
	pushHandler.serve(response, request)
}


text:
package com.ubikgs.androidsensors.persistence.repositories.imu;

import com.ubikgs.androidsensors.persistence.DaggerTestBedComponent;
import com.ubikgs.androidsensors.persistence.repositories.RecordRepositoryIntegrationTest;
import com.ubikgs.androidsensors.records.imu.GravityRecord;

import org.junit.Before;

import javax.inject.Inject;

import static com.ubikgs.androidsensors.persistence.testutils.TestEntityProvider.createGravityRecord;

public class GravityRepositoryIntegrationTest extends RecordRepositoryIntegrationTest<GravityRecord> {

    @Inject
    GravityRepository gravityRepository;

    @Before
    public void setUp() throws Exception {
        DaggerTestBedComponent.create().inject(this);
        recordRepository = gravityRepository;
    }

    @Override
    protected GravityRecord createSensorRecord() {
        return createGravityRecord();
    }
}