<commit_before>/**
 * Copyright 2012 Riccardo Attilio Galli <riccardo@sideralis.org>
 * [http://www.sideralis.org]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Apply the returnExports.js UMD pattern
// See [https://github.com/umdjs/umd](https://github.com/umdjs/umd)
(function (root, factory) {
    if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like enviroments that support module.exports,
        // like Node.
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(factory);
    } else {
        // Browser globals
        root.valib = factory();
    }
}(this, function (/*dependencies*/) {

    // Detect a variable's type
    // (Refactoring of code found in jQuery 1.7.1)
    var getType = (function(){

        var classes = ["Boolean","Number","String","Function","Array",
                       "Date","RegExp","Object"],
            class2type = {};

        for (var i=0,il=classes.length;i<il;i++) {
          class2type[ "[object " + classes[i] + "]" ] = classes[i].toLowerCase();
        };

        return function(value){
            return value == null ? // match null and undefined
                   String( value ) :
                   class2type[ Object.prototype.toString.call(value) ] || "object";
        };

    })();

    // Even if they have String.prototype.trim, browsers discord
    // on the whitespace characters, so we use a custom trim
    var trim = function(str) {
        if (str == null) return ''; // null and undefined
        /* modified version of trim12 from
           http://blog.stevenlevithan.com/archives/faster-trim-javascript */
        str = str.replace(/^[\s\u200B\u0085]+/, '');
        var ws = /[\s\u200B\u0085]/,
            i = str.length;
        while (ws.test(str.charAt(--i)));
        return str.slice(0, i + 1);
    };

    var valib = {
        // Type Functions
        // --------------
        Type: {
            isNumber : function(value) {
                return !this.isNaN(value) && getType(value) === 'number';
            },
            isString: function(value) {
                return getType(value) === 'string';
            },
            isBoolean: function(value) {
                return getType(value) === 'boolean';
            },
            isArray: Array.isArray || function(value) {
                return getType(value) === 'array';
            },
            isObject: function(value) { // note: doesn't treat arrays as objects
                return getType(value) === 'object';
            },
            isFunction: function(value) {
                return getType(value) === 'function';
            },
            isUndefined: function(value) {
                return getType(value) === 'undefined';
            },
            isNull: function(value) {
                // not really a Javascript type, but certainly not an object
                // (typeof null === 'object')
                return getType(value) === 'null';
            },
            isNaN: function(value) {
                // Test if `value` is NaN, this is not the same as calling
                // the standard isNaN() (which checks if a value is coercible
                // to a number)

                // not really a Javascript type, but certainly not a number
                // (typeof NaN === 'number')
                return (typeof value === 'number') && ('NaN' == new String(value));
            },
            isDate: function(value) {
                return getType(value) === 'date';
            },
            isRegExp: function(value) {
                return getType(value) === 'regexp';
            }
        },
        // Number Functions
        // --------------
        Number: {
            isInteger : function(n){
              return n===+n && n===(n|0);
            },
            isFloat: function(n) {
              return n===+n && n!==(n|0);
            },
            isInfinity: function(n) {
                return n === Infinity || n === -Infinity;
            },
            isZero : function(n){
                return n === 0;
            },
            inRange : function(n,min,max,opts) {
                opts = opts || {l_exc : false, r_exc : false};
                return (opts.l_exc ? n > min : n >= min)
                        &&
                       (opts.r_exc ? n < max : n <= max);
            },
            lt : function(n,max) {
                return n < max;
            },
            lte : function(n,max) {
                return n <= max;
            },
            gt : function(n,min) {
                return n > min;
            },
            gte : function(n,min) {
                return n >= min;
            }
        },
        // String Functions
        // --------------
        String: {
            isNumeric : function(str,opts) {
                opts = opts || {};
                // This way the user can just pass {simple:true}
                if (opts.canBeSigned === undefined) opts.canBeSigned = true;
                if (opts.simple === undefined) opts.simple = false;

                str = trim(str);

                // Below isFinite() may choke with signed hexadecimals (Firefox
                // return NaN as the standard requires, others parse them, so
                // we remove the sign alltogether)

                var sign = null;
                if (str.length && str[0] === '-' || str[0] === '+') {
                    sign = str[0];
                    str = str.slice(1);
                }

                // see http://stackoverflow.com/questions/18082
                var isNumeric = !isNaN(parseFloat(str)) && isFinite(str);

                if (!isNumeric) return false;

                if (sign && !opts.canBeSigned) return false;

                if (opts.simple) return /^(0|[1-9][0-9]*)(\.[0-9]+)?$/.test(str);

                return true;
            },
            toNumber : function(str) {
                if (!this.isNumeric(str)) return NaN;

                if (str.toUpperCase().indexOf('X') !== -1) return parseInt(str); // hex number
                else if (/^\s*[+-]?0[1-9]/.test(str)) return parseInt(str); // oct number
                else return parseFloat(str);

            },
            isUrl : (function(){ // only http(s)/ftp urls, requires protocol
                // javascript version of the regexp found at
                // http://stackoverflow.com/questions/161738
                var reg = new RegExp(
                  "^(https?|ftp)://" +                                             // protocol
                  "(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+" +       // username
                  "(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+)?" +    // password
                  "@)?" +                                                          // auth requires @
                  "((([a-z0-9][a-z0-9-]*[a-z0-9]\\.)*" +                           // domain segments AND
                  "[a-z][a-z0-9-]*[a-z0-9]" +                                      // top level domain  OR
                  "|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}" +
                  "(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])" +                   // IP address
                  ")(:\\d+)?" +                                                    // port
                  ")(((/+([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)*" + // path
                  "(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)" +    // query string
                  "?)?)?" +                                                        // path and query string optional
                  "(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?" +     // fragment
                  "$"
                ,"i");

                return function(value){
                  return reg.test(value);
                };

            })(),
            isMD5 : function(value){
                return /^[0-9a-f]{32}$/i.test(value);
            },
            isSHA1 : function(value){
                return /^[0-9a-f]{40}$/i.test(value);
            },
            // check if it is similar to an e-mail (no hope to comply with the rfc and the mess that's the real world)
            isEmailLike : function(value){
                // something@something with no spaces, one and only one @
                return /^[^\s@]+@[^\s@]{3,}$/.test(value);
            },
            /**
            * If regOrString is a regular espression check if value match it
            * If regOrString is a string check if it's equal to value
            *
            * If the option {trim:true} is passed then trailing whitespaces will be ignored on 'value'
            */
            match: function(value,regOrString,opts){
                opts = opts || {trim:false};

                if (opts.trim) value = trim(value);

                if (valib.Type.isRegExp(regOrString)) {
                  return regOrString.test(value);
                }
                else return regOrString === value;
            },
            startsWith: function(str,starts){
                return str.length >= starts.length && str.substring(0, starts.length) === starts;
            },
            endsWith: function(str,ends){
                return str.length >= ends.length && str.substring(str.length - ends.length) === ends;
            },
            isEmpty : function(str){
                return !str;
            },
            trim : trim
        },
        // Array Functions
        // --------------
        Array : {
            'indexOf' : function(value,array) { // O(n)
                if (array == null) return -1; // null and undefined

                if (!Array.prototype.indexOf) {

                    for (var i=0,il=array.length;i<il;i++) {
                        // check if `i` is inside `array` to differentiate
                        // between deleted items and keys set to undefined
                        if (i in array && array[i] === value) return i;
                    }
                    return -1;

                } else return array.indexOf(value);
            },
            'in' : function(value,array) { // O(n)
                return -1 !== this.indexOf(value,array);
            },
            'isEmpty' : function(array){
                if (array == null) return true;
                return array.length === 0;
            }
        },
        // Object Functions
        // --------------
        Object : {
            'hasKey' : function(key,object){
                if (object == null) return false;
                return Object.prototype.hasOwnProperty.call(object,key);
            },
            'hasValue' : function(value,object){
                for (var key in object) {
                    if (object.hasOwnProperty(key) && object[key] === value) return true;
                }
                return false;
            },
            'isEmpty' : function(object){
                if (object == null) return true;
                for (var key in object) if (this.hasKey(key,object)) return false;
                return true;
            }
        }
    };

    return valib;

}));
<commit_msg>valib.String functions always use 'str' as variable name for the string input<commit_after>/**
 * Copyright 2012 Riccardo Attilio Galli <riccardo@sideralis.org>
 * [http://www.sideralis.org]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Apply the returnExports.js UMD pattern
// See [https://github.com/umdjs/umd](https://github.com/umdjs/umd)
(function (root, factory) {
    if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like enviroments that support module.exports,
        // like Node.
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(factory);
    } else {
        // Browser globals
        root.valib = factory();
    }
}(this, function (/*dependencies*/) {

    // Detect a variable's type
    // (Refactoring of code found in jQuery 1.7.1)
    var getType = (function(){

        var classes = ["Boolean","Number","String","Function","Array",
                       "Date","RegExp","Object"],
            class2type = {};

        for (var i=0,il=classes.length;i<il;i++) {
          class2type[ "[object " + classes[i] + "]" ] = classes[i].toLowerCase();
        };

        return function(value){
            return value == null ? // match null and undefined
                   String( value ) :
                   class2type[ Object.prototype.toString.call(value) ] || "object";
        };

    })();

    // Even if they have String.prototype.trim, browsers discord
    // on the whitespace characters, so we use a custom trim
    var trim = function(str) {
        if (str == null) return ''; // null and undefined
        /* modified version of trim12 from
           http://blog.stevenlevithan.com/archives/faster-trim-javascript */
        str = str.replace(/^[\s\u200B\u0085]+/, '');
        var ws = /[\s\u200B\u0085]/,
            i = str.length;
        while (ws.test(str.charAt(--i)));
        return str.slice(0, i + 1);
    };

    var valib = {
        // Type Functions
        // --------------
        Type: {
            isNumber : function(value) {
                return !this.isNaN(value) && getType(value) === 'number';
            },
            isString: function(value) {
                return getType(value) === 'string';
            },
            isBoolean: function(value) {
                return getType(value) === 'boolean';
            },
            isArray: Array.isArray || function(value) {
                return getType(value) === 'array';
            },
            isObject: function(value) { // note: doesn't treat arrays as objects
                return getType(value) === 'object';
            },
            isFunction: function(value) {
                return getType(value) === 'function';
            },
            isUndefined: function(value) {
                return getType(value) === 'undefined';
            },
            isNull: function(value) {
                // not really a Javascript type, but certainly not an object
                // (typeof null === 'object')
                return getType(value) === 'null';
            },
            isNaN: function(value) {
                // Test if `value` is NaN, this is not the same as calling
                // the standard isNaN() (which checks if a value is coercible
                // to a number)

                // not really a Javascript type, but certainly not a number
                // (typeof NaN === 'number')
                return (typeof value === 'number') && ('NaN' == new String(value));
            },
            isDate: function(value) {
                return getType(value) === 'date';
            },
            isRegExp: function(value) {
                return getType(value) === 'regexp';
            }
        },
        // Number Functions
        // --------------
        Number: {
            isInteger : function(n){
              return n===+n && n===(n|0);
            },
            isFloat: function(n) {
              return n===+n && n!==(n|0);
            },
            isInfinity: function(n) {
                return n === Infinity || n === -Infinity;
            },
            isZero : function(n){
                return n === 0;
            },
            inRange : function(n,min,max,opts) {
                opts = opts || {l_exc : false, r_exc : false};
                return (opts.l_exc ? n > min : n >= min)
                        &&
                       (opts.r_exc ? n < max : n <= max);
            },
            lt : function(n,max) {
                return n < max;
            },
            lte : function(n,max) {
                return n <= max;
            },
            gt : function(n,min) {
                return n > min;
            },
            gte : function(n,min) {
                return n >= min;
            }
        },
        // String Functions
        // --------------
        String: {
            isNumeric : function(str,opts) {
                opts = opts || {};
                // This way the user can just pass {simple:true}
                if (opts.canBeSigned === undefined) opts.canBeSigned = true;
                if (opts.simple === undefined) opts.simple = false;

                str = trim(str);

                // Below isFinite() may choke with signed hexadecimals (Firefox
                // return NaN as the standard requires, others parse them, so
                // we remove the sign alltogether)

                var sign = null;
                if (str.length && str[0] === '-' || str[0] === '+') {
                    sign = str[0];
                    str = str.slice(1);
                }

                // see http://stackoverflow.com/questions/18082
                var isNumeric = !isNaN(parseFloat(str)) && isFinite(str);

                if (!isNumeric) return false;

                if (sign && !opts.canBeSigned) return false;

                if (opts.simple) return /^(0|[1-9][0-9]*)(\.[0-9]+)?$/.test(str);

                return true;
            },
            toNumber : function(str) {
                if (!this.isNumeric(str)) return NaN;

                if (str.toUpperCase().indexOf('X') !== -1) return parseInt(str); // hex number
                else if (/^\s*[+-]?0[1-9]/.test(str)) return parseInt(str); // oct number
                else return parseFloat(str);

            },
            isUrl : (function(){ // only http(s)/ftp urls, requires protocol
                // javascript version of the regexp found at
                // http://stackoverflow.com/questions/161738
                var reg = new RegExp(
                  "^(https?|ftp)://" +                                             // protocol
                  "(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+" +       // username
                  "(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+)?" +    // password
                  "@)?" +                                                          // auth requires @
                  "((([a-z0-9][a-z0-9-]*[a-z0-9]\\.)*" +                           // domain segments AND
                  "[a-z][a-z0-9-]*[a-z0-9]" +                                      // top level domain  OR
                  "|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}" +
                  "(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])" +                   // IP address
                  ")(:\\d+)?" +                                                    // port
                  ")(((/+([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)*" + // path
                  "(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)" +    // query string
                  "?)?)?" +                                                        // path and query string optional
                  "(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?" +     // fragment
                  "$"
                ,"i");

                return function(str){
                  return reg.test(str);
                };

            })(),
            isMD5 : function(str){
                return /^[0-9a-f]{32}$/i.test(str);
            },
            isSHA1 : function(str){
                return /^[0-9a-f]{40}$/i.test(str);
            },
            // check if it is similar to an e-mail (no hope to comply with the rfc and the mess that's the real world)
            isEmailLike : function(str){
                // something@something with no spaces, one and only one @
                return /^[^\s@]+@[^\s@]{3,}$/.test(str);
            },
            /**
            * If regOrString is a regular espression check if value match it
            * If regOrString is a string check if it's equal to value
            *
            * If the option {trim:true} is passed then trailing whitespaces will be ignored on 'value'
            */
            match: function(str,regOrString,opts){
                opts = opts || {trim:false};

                if (opts.trim) str = trim(str);

                if (valib.Type.isRegExp(regOrString)) {
                  return regOrString.test(str);
                }
                else return regOrString === str;
            },
            startsWith: function(str,starts){
                return str.length >= starts.length && str.substring(0, starts.length) === starts;
            },
            endsWith: function(str,ends){
                return str.length >= ends.length && str.substring(str.length - ends.length) === ends;
            },
            isEmpty : function(str){
                return !str;
            },
            trim : trim
        },
        // Array Functions
        // --------------
        Array : {
            'indexOf' : function(value,array) { // O(n)
                if (array == null) return -1; // null and undefined

                if (!Array.prototype.indexOf) {

                    for (var i=0,il=array.length;i<il;i++) {
                        // check if `i` is inside `array` to differentiate
                        // between deleted items and keys set to undefined
                        if (i in array && array[i] === value) return i;
                    }
                    return -1;

                } else return array.indexOf(value);
            },
            'in' : function(value,array) { // O(n)
                return -1 !== this.indexOf(value,array);
            },
            'isEmpty' : function(array){
                if (array == null) return true;
                return array.length === 0;
            }
        },
        // Object Functions
        // --------------
        Object : {
            'hasKey' : function(key,object){
                if (object == null) return false;
                return Object.prototype.hasOwnProperty.call(object,key);
            },
            'hasValue' : function(value,object){
                for (var key in object) {
                    if (object.hasOwnProperty(key) && object[key] === value) return true;
                }
                return false;
            },
            'isEmpty' : function(object){
                if (object == null) return true;
                for (var key in object) if (this.hasKey(key,object)) return false;
                return true;
            }
        }
    };

    return valib;

}));
<|endoftext|>


<commit_before>/*!
* Copyright (c) 2015 Carrot Creative
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

(function (win, doc) {

  function __() {

    var RegexpValue = /[\-+]?[\d]*\.?[\d]+/g
      , ParseWildcard = '{?}'
      , ParseWildcardRegexp = /\{\?\}/g;

    var Animation = function (component) {
      var tweens = []
        , points = component.points
        , current, next;
      for (var i=0; i<points.length; i++) {
        current = points[i];
        next = points[i+1];
        tweens.push(new Tween(component.property, current, next));
      }
      this.tweens = tweens;
    }

    Animation.prototype = {
      current: function (Y) {
        var tweens = this.tweens
          , len = tweens.length
          , tween
          , current;
        for (var i=0; i<len; i++) {
          tween = tweens[i];
          if (Y >= tween.fromY || (Y <= tween.fromY && i == 0)){
            current = tween.current(Y);
          }
        }
        return current;
      }
    }

    var Tweener = {};

    Tweener.default = function (fromValue, toValue) {
      this.fromValue = ParseValue(fromValue);
      this.toValue = ParseValue(toValue);
    }

    Tweener.default.prototype = {
      tween: function (pct) {
        var fromValue = this.fromValue
          , toValue = this.toValue;
        return CompileValues(fromValue, toValue, pct);
      }
    }

    var Tween = function (property, fromPoint, toPoint) {
      if (!toPoint) toPoint = fromPoint;
      this.tweener = new (Tweener[property] || Tweener.default)(fromPoint.value, toPoint.value);
      this.fromY = fromPoint.Y;
      this.toY = toPoint.Y;
    }

    Tween.prototype = {
      current: function (Y) {
        var pct = 0
          , fromY = this.fromY
          , toY = this.toY;
        if (Y >= fromY && Y <= toY) {
          pct = (Y - fromY) / (toY - fromY);
        } else if (Y > toY) {
          pct = 1;
        }
        return this.tweener.tween(pct);
      }
    }

    function ParseValue (value) {
      var nums = [];
      value = new String(value).replace(RegexpValue, function (num) {
        nums.push(parseFloat(num));
        return ParseWildcard;
      });
      return [value, nums]
    }

    function CompileValues (fromValue, toValue, pct) {
      var i = 0
        , fromNum
        , toNum;
      return fromValue[0].replace(ParseWildcardRegexp, function () {
        from = fromValue[1][i];
        to = toValue[1][i];
        i++;
        return (from + ((to - from) * pct));
      });
    }

    var Style = function (component) {
      this.points = component.points;
    }

    Style.prototype = {
      current: function (Y) {
        var points = this.points
          , current = new String();
        for (var i=0; i<points.length; i++) {
          point = points[i];
          if (Y >= point.Y) current = point.value;
        }
        return current;
      }
    }

    var Point = function (Y, value) {
      this.Y = Y;
      this.value = value;
    }

    var Collection = function (object) {
      object = object || {};
      this.points = [];
      for (var Y in object) {
        this.add(Y, object[Y]);
      }
    }

    Collection.prototype = {
      add: function (Y, value) {
        var points = this.points.slice(0)
          , point = new Point(parseInt(Y), value)
          , isAdded = false;
        for (var i=0; i<this.points.length; i++) {
          if (this.points[i].Y > point.Y) {
            points.splice(i, 0, point);
            isAdded = true;
          }
        }
        if (!isAdded) points.push(point);
        this.points = points;
        return this;
      },
      merge: function (at, collection) {
        var points = collection.points
          , value;
        for (var i=0; i<points.length; i++) {
          action = points[i];
          this.add((at + action.Y), action.value);
        }
        return this;
      }
    }

    var Action = function (Klass, property, points) {
      var points = this.points = (new Collection(points)).points;
      this.max = points[points.length - 1].Y;
      this.property = property;
      this.klass = new Klass(this);
    }

    Action.prototype = {
      current: function (Y) {
        return this.klass.current(Y);
      }
    }

    function SetElementStyle (object, property, value) {
      if (object instanceof NodeList || object instanceof Array) {
        for (var i=0; i<object.length; i++) SetElementStyle(object[i], property, value);
      } else {
        object.style[property] = value;
      }
    }

    var Element = function (selector) {
      this.selector = selector;
      this.actions = {};
    }

    Element.prototype = {
      $: function () {
        var $ = this.selector;
        if ($.nodeName) {
          $ = [$];
        } else if ('string' === typeof $) {
          $ = doc.querySelectorAll($);
        }
        return $;
      },
      add: function (Y, action) {
        var property = action.property
          , collection;
        if (!(collection = this.actions[property])) collection = new Collection();
        collection.add(Y, action);
        this.actions[property] = collection;
        return this;
      },
      set: function (wY) {
        var $ = this.$()
          , actions = this.actions
          , collection, points
          , point, action, Y;
        for (var property in actions) {
          collection = actions[property];
          points = collection.points;
          for (var x=0; x<points.length; x++) {
            point = points[x];
            action = point.value;
            Y = (wY - point.Y);
            if ( (Y > 0) || (Y < 0 && x == 0) ) {
              SetElementStyle($, property, action.current(Y));
            }
          }
        }
        return this;
      },
      unset: function () {
        var actions = this.actions
          , $ = this.$();
        for (var property in actions) {
          for (var i=0; i<$.length; i++) $[i].style[property] = '';
        }
        return this;
      }
    }

    var Storyboard = function () {
      this.elements = [];
      this.max = 0;
    }

    Storyboard.prototype = {
      add: function (Y, selector, action) {
        var elements = this.elements
          , element
          , max;
        for (var i=0; i<elements.length; i++) {
          if (elements[i].selector == selector) {
            element = elements[i];
            break;
          }
        }
        if (!element) {
          element = new Element(selector);
          elements.push(element);
        }
        if (action) {
          element.add(Y, action);
          max = Y + action.max;
          if (max > this.max) this.max = max;
        }
        this.elements = elements;
        return this;
      },
      merge: function (at, storyboard) {
        var elements = storyboard.elements
          , element, actions, collection
          , points, point;
        for (var x=0; x<elements.length; x++) {
          element = elements[x];
          actions = element.actions;
          for (var property in actions) {
            collection = actions[property];
            points = collection.points;
            for (var i=0; i<points.length; i++) {
              point = points[i];
              this.add((parseInt(at) + point.Y), element.selector, point.value);
            }
          }
        }
        return this;
      },
      set: function (Y) {
        var elements = this.elements
          , element;
        for (var i=0; i<elements.length; i++) {
          element = elements[i];
          element.set(Y);
        }
      },
      unset: function () {
        var elements = this.elements
          , element;
        for (var i=0; i<elements.length; i++) {
          element = elements[i];
          element.unset();
        }
      }
    }

    function SetStoryboardFunction (storyboard) {
      return function () {
        var wY = win.pageYOffset;
        storyboard.set(wY);
      }
    }

    function SetBodyMinHeightFunction (storyboard) {
      return function () {
        SetElementStyle(doc.body, 'minHeight', ((storyboard.max + win.innerHeight) + 'px'));
      }
    }

    function AddEvent (roll, string, callback) {
      var events = string.split(' ')
        , ev;
      for (var i=0; i<events.length; i++) {
        ev = events[i];
        if (!roll.events[ev]) roll.events[ev] = [];
        roll.events[ev].push(callback);
        win.addEventListener(ev, callback);
      }
      callback();
    }

    function RemoveEvents (roll, string) {
      var events = string.split(' ')
        , ev, callbacks, callback;
      for (var x=0; x<events.length; x++) {
        ev = events[x];
        callbacks = roll.events[ev];
        for (var y=0; x<callbacks.length; x++) {
          callback = callbacks[y];
          win.removeEventListener(ev, callback);
        }
        roll.events[ev] = [];
      }
    }

    function RemoveAllEvents (roll) {
      for (var ev in roll.events) RemoveEvents(roll, ev);
      roll.events = {};
    }

    var Roll = function () {
      this.scenes = {};
      this.ats = {};
      this.events = {};
    }

    Roll.prototype = {
      add: function (name, scene) {
        if ('function' === typeof scene) {
          var fn = scene;
          scene = new Scene();
          fn(scene);
        }
        this.scenes[name] = scene;
        return this;
      },
      at: function (Y, name) {
        var ats = this.ats[Y] || [];
        ats.push(name);
        this.ats[Y] = ats;
        return this;
      },
      init: function () {
        var storyboard, names, scene;
        storyboard = this.storyboard = new Storyboard();
        for (var Y in this.ats) {
          names = this.ats[Y];
          for (var i=0; i<names.length; i++) {
            scene = this.scenes[names[i]];
            storyboard.merge(Y, scene.storyboard);
          }
        }
        this.bind();
        return this;
      },
      remove: function () {
        var storyboard;
        if (storyboard = this.storyboard) {
          storyboard.unset();
          this.storyboard = null;
        }
        SetElementStyle(doc.body, 'minHeight', '');
        this.unbind();
        return this;
      },
      bind: function () {
        if (this.storyboard) {
          AddEvent(this, 'scroll resize', SetStoryboardFunction(this.storyboard));
          AddEvent(this, 'resize', SetBodyMinHeightFunction(this.storyboard));
        }
        return this;
      },
      unbind: function () {
        RemoveAllEvents(this);
        return this;
      }
    }

    var Scene = Roll.Scene = function () {
      this.storyboard = new Storyboard();
    }

    Scene.prototype = {
      animate: function ($el, property, points) {
        return this.action(Animation, $el, property, points);
      },
      style: function ($el, property, points) {
        return this.action(Style, $el, property, points);
      },
      action: function (Klass, $el, property, points) {
        var properties;
        if ('undefined' === typeof points) {
          properties = property;
        } else {
          (properties = {})[property] = points;
        }
        for (property in properties) {
          action = new Action(Klass, property, properties[property]);
          this.storyboard.add(0, $el, action);
        }
        return this;
      }
    }

    return Roll;

  }

  if ('function' === typeof define && define.amd) {
    define(__);
  } else {
    win.Roll = __();
  };

}(window, document));
<commit_msg>Autoprefix properties; closes #9. - Caches the document's computed style properties as a string. - Uses a regular expression to search for property in computed style string. - Caches matches.<commit_after>/*!
* Copyright (c) 2015 Carrot Creative
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

(function (win, doc) {

  function __() {

    var RegexpValue = /[\-+]?[\d]*\.?[\d]+/g
      , ParseWildcard = '{?}'
      , ParseWildcardRegexp = /\{\?\}/g;

    var Animation = function (component) {
      var tweens = []
        , points = component.points
        , current, next;
      for (var i=0; i<points.length; i++) {
        current = points[i];
        next = points[i+1];
        tweens.push(new Tween(component.property, current, next));
      }
      this.tweens = tweens;
    }

    Animation.prototype = {
      current: function (Y) {
        var tweens = this.tweens
          , len = tweens.length
          , tween
          , current;
        for (var i=0; i<len; i++) {
          tween = tweens[i];
          if (Y >= tween.fromY || (Y <= tween.fromY && i == 0)){
            current = tween.current(Y);
          }
        }
        return current;
      }
    }

    var Tweener = {};

    Tweener.default = function (fromValue, toValue) {
      this.fromValue = ParseValue(fromValue);
      this.toValue = ParseValue(toValue);
    }

    Tweener.default.prototype = {
      tween: function (pct) {
        var fromValue = this.fromValue
          , toValue = this.toValue;
        return CompileValues(fromValue, toValue, pct);
      }
    }

    var Tween = function (property, fromPoint, toPoint) {
      if (!toPoint) toPoint = fromPoint;
      this.tweener = new (Tweener[property] || Tweener.default)(fromPoint.value, toPoint.value);
      this.fromY = fromPoint.Y;
      this.toY = toPoint.Y;
    }

    Tween.prototype = {
      current: function (Y) {
        var pct = 0
          , fromY = this.fromY
          , toY = this.toY;
        if (Y >= fromY && Y <= toY) {
          pct = (Y - fromY) / (toY - fromY);
        } else if (Y > toY) {
          pct = 1;
        }
        return this.tweener.tween(pct);
      }
    }

    function ParseValue (value) {
      var nums = [];
      value = new String(value).replace(RegexpValue, function (num) {
        nums.push(parseFloat(num));
        return ParseWildcard;
      });
      return [value, nums]
    }

    function CompileValues (fromValue, toValue, pct) {
      var i = 0
        , fromNum
        , toNum;
      return fromValue[0].replace(ParseWildcardRegexp, function () {
        from = fromValue[1][i];
        to = toValue[1][i];
        i++;
        return (from + ((to - from) * pct));
      });
    }

    var Style = function (component) {
      this.points = component.points;
    }

    Style.prototype = {
      current: function (Y) {
        var points = this.points
          , current = new String();
        for (var i=0; i<points.length; i++) {
          point = points[i];
          if (Y >= point.Y) current = point.value;
        }
        return current;
      }
    }

    var Point = function (Y, value) {
      this.Y = Y;
      this.value = value;
    }

    var Collection = function (object) {
      object = object || {};
      this.points = [];
      for (var Y in object) {
        this.add(Y, object[Y]);
      }
    }

    Collection.prototype = {
      add: function (Y, value) {
        var points = this.points.slice(0)
          , point = new Point(parseInt(Y), value)
          , isAdded = false;
        for (var i=0; i<this.points.length; i++) {
          if (this.points[i].Y > point.Y) {
            points.splice(i, 0, point);
            isAdded = true;
          }
        }
        if (!isAdded) points.push(point);
        this.points = points;
        return this;
      },
      merge: function (at, collection) {
        var points = collection.points
          , value;
        for (var i=0; i<points.length; i++) {
          action = points[i];
          this.add((at + action.Y), action.value);
        }
        return this;
      }
    }

    var Action = function (Klass, property, points) {
      var points = this.points = (new Collection(points)).points;
      this.max = points[points.length - 1].Y;
      this.property = property;
      this.klass = new Klass(this);
    }

    Action.prototype = {
      current: function (Y) {
        return this.klass.current(Y);
      }
    }

    var VendorPrefixProperties = {}, StyleDeclaration;

    function VendorPrefixProperty (property) {
      var matches;
      if (!StyleDeclaration) StyleDeclaration = '|' + Array.prototype.slice.call(win.getComputedStyle(doc.documentElement, '')).join('|') + '|'
      if (VendorPrefixProperties[property]) {
        return VendorPrefixProperties[property];
      } else if (matches = (new RegExp('\\|(-(moz|webkit|ms)-' + property + ')\\|')).exec(StyleDeclaration)) {
        return VendorPrefixProperties[property] = matches[1];
      }
      return property;
    }

    function SetElementStyle (object, property, value) {
      if (object instanceof NodeList || object instanceof Array) {
        for (var i=0; i<object.length; i++) SetElementStyle(object[i], property, value);
      } else {
        object.style[VendorPrefixProperty(property)] = value;
      }
    }

    var Element = function (selector) {
      this.selector = selector;
      this.actions = {};
    }

    Element.prototype = {
      $: function () {
        var $ = this.selector;
        if ($.nodeName) {
          $ = [$];
        } else if ('string' === typeof $) {
          $ = doc.querySelectorAll($);
        }
        return $;
      },
      add: function (Y, action) {
        var property = action.property
          , collection;
        if (!(collection = this.actions[property])) collection = new Collection();
        collection.add(Y, action);
        this.actions[property] = collection;
        return this;
      },
      set: function (wY) {
        var $ = this.$()
          , actions = this.actions
          , collection, points
          , point, action, Y;
        for (var property in actions) {
          collection = actions[property];
          points = collection.points;
          for (var x=0; x<points.length; x++) {
            point = points[x];
            action = point.value;
            Y = (wY - point.Y);
            if ( (Y > 0) || (Y < 0 && x == 0) ) {
              SetElementStyle($, property, action.current(Y));
            }
          }
        }
        return this;
      },
      unset: function () {
        var actions = this.actions
          , $ = this.$();
        for (var property in actions) {
          for (var i=0; i<$.length; i++) $[i].style[property] = '';
        }
        return this;
      }
    }

    var Storyboard = function () {
      this.elements = [];
      this.max = 0;
    }

    Storyboard.prototype = {
      add: function (Y, selector, action) {
        var elements = this.elements
          , element
          , max;
        for (var i=0; i<elements.length; i++) {
          if (elements[i].selector == selector) {
            element = elements[i];
            break;
          }
        }
        if (!element) {
          element = new Element(selector);
          elements.push(element);
        }
        if (action) {
          element.add(Y, action);
          max = Y + action.max;
          if (max > this.max) this.max = max;
        }
        this.elements = elements;
        return this;
      },
      merge: function (at, storyboard) {
        var elements = storyboard.elements
          , element, actions, collection
          , points, point;
        for (var x=0; x<elements.length; x++) {
          element = elements[x];
          actions = element.actions;
          for (var property in actions) {
            collection = actions[property];
            points = collection.points;
            for (var i=0; i<points.length; i++) {
              point = points[i];
              this.add((parseInt(at) + point.Y), element.selector, point.value);
            }
          }
        }
        return this;
      },
      set: function (Y) {
        var elements = this.elements
          , element;
        for (var i=0; i<elements.length; i++) {
          element = elements[i];
          element.set(Y);
        }
      },
      unset: function () {
        var elements = this.elements
          , element;
        for (var i=0; i<elements.length; i++) {
          element = elements[i];
          element.unset();
        }
      }
    }

    function SetStoryboardFunction (storyboard) {
      return function () {
        var wY = win.pageYOffset;
        storyboard.set(wY);
      }
    }

    function SetBodyMinHeightFunction (storyboard) {
      return function () {
        SetElementStyle(doc.body, 'minHeight', ((storyboard.max + win.innerHeight) + 'px'));
      }
    }

    function AddEvent (roll, string, callback) {
      var events = string.split(' ')
        , ev;
      for (var i=0; i<events.length; i++) {
        ev = events[i];
        if (!roll.events[ev]) roll.events[ev] = [];
        roll.events[ev].push(callback);
        win.addEventListener(ev, callback);
      }
      callback();
    }

    function RemoveEvents (roll, string) {
      var events = string.split(' ')
        , ev, callbacks, callback;
      for (var x=0; x<events.length; x++) {
        ev = events[x];
        callbacks = roll.events[ev];
        for (var y=0; x<callbacks.length; x++) {
          callback = callbacks[y];
          win.removeEventListener(ev, callback);
        }
        roll.events[ev] = [];
      }
    }

    function RemoveAllEvents (roll) {
      for (var ev in roll.events) RemoveEvents(roll, ev);
      roll.events = {};
    }

    var Roll = function () {
      this.scenes = {};
      this.ats = {};
      this.events = {};
    }

    Roll.prototype = {
      add: function (name, scene) {
        if ('function' === typeof scene) {
          var fn = scene;
          scene = new Scene();
          fn(scene);
        }
        this.scenes[name] = scene;
        return this;
      },
      at: function (Y, name) {
        var ats = this.ats[Y] || [];
        ats.push(name);
        this.ats[Y] = ats;
        return this;
      },
      init: function () {
        var storyboard, names, scene;
        storyboard = this.storyboard = new Storyboard();
        for (var Y in this.ats) {
          names = this.ats[Y];
          for (var i=0; i<names.length; i++) {
            scene = this.scenes[names[i]];
            storyboard.merge(Y, scene.storyboard);
          }
        }
        this.bind();
        return this;
      },
      remove: function () {
        var storyboard;
        if (storyboard = this.storyboard) {
          storyboard.unset();
          this.storyboard = null;
        }
        SetElementStyle(doc.body, 'minHeight', '');
        this.unbind();
        return this;
      },
      bind: function () {
        if (this.storyboard) {
          AddEvent(this, 'scroll resize', SetStoryboardFunction(this.storyboard));
          AddEvent(this, 'resize', SetBodyMinHeightFunction(this.storyboard));
        }
        return this;
      },
      unbind: function () {
        RemoveAllEvents(this);
        return this;
      }
    }

    var Scene = Roll.Scene = function () {
      this.storyboard = new Storyboard();
    }

    Scene.prototype = {
      animate: function ($el, property, points) {
        return this.action(Animation, $el, property, points);
      },
      style: function ($el, property, points) {
        return this.action(Style, $el, property, points);
      },
      action: function (Klass, $el, property, points) {
        var properties;
        if ('undefined' === typeof points) {
          properties = property;
        } else {
          (properties = {})[property] = points;
        }
        for (property in properties) {
          action = new Action(Klass, property, properties[property]);
          this.storyboard.add(0, $el, action);
        }
        return this;
      }
    }

    return Roll;

  }

  if ('function' === typeof define && define.amd) {
    define(__);
  } else {
    win.Roll = __();
  };

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


<commit_before>module.exports = {
    username: function(username) {
        var re = /^[^_-][a-zA-Z0-9\-_]{2,30}$/;
        if (re.test(username)) {
            return;
        }
        console.log('Username may only contain alphanumeric characters, underscores or dashes and cannot begin with a dash or underscore.'.red);
        // must be over 2 characters
        process.exit();
    },
    email: function(email) {
        var re = /\S+@\S+\.\S+/;
        if (re.test(email)) {
            return;
        }
        console.log('Email format is invalid.'.red);
        process.exit();
    },
    passwords: function(password1, password2) {
        if (password1 === password2) {
            return;
        }
        console.log('Your passwords did not match, try again.'.red);
        process.exit();
    }
};
<commit_msg>Improve validation message<commit_after>module.exports = {
    username: function(username) {
        var re = /^[^_-][a-zA-Z0-9\-_]{2,30}$/;
        if (re.test(username)) {
            return;
        }
        console.log('Username may only contain alphanumeric characters, underscores or dashes, must be at least 3 characters, and cannot begin with a dash or underscore.'.red);
        // must be over 2 characters
        process.exit();
    },
    email: function(email) {
        var re = /\S+@\S+\.\S+/;
        if (re.test(email)) {
            return;
        }
        console.log('Email format is invalid.'.red);
        process.exit();
    },
    passwords: function(password1, password2) {
        if (password1 === password2) {
            return;
        }
        console.log('Your passwords did not match, try again.'.red);
        process.exit();
    }
};
<|endoftext|>


<commit_before>/*jshint laxcomma: true, smarttabs: true, node:true */
'use strict';
/**
 * A Resource for interacting with the Mongoose ODM for mongodb
 * @module tastypie/lib/resource/mongoose
 * @author Eric Satterwhite
 * @since 0.0.1
 * @requires util
 * @requires tastypie/lib/class
 * @requires tastypie/lib/class/options
 * @requires tastypie/lib/resource
 * @requires joi
 */

var util = require( 'util' )
  , Class = require( '../class' )
  , Options = require( '../class/options' )
  , Resource = require('./index')
  , joi = require('joi')
  , MongoResource
  ;

/**
 * Description
 * @constructor
 * @alias module:tastypie/lib/resource/mongoose
 * @extends module:tastypie/lib/resource
 * @mixes module:tastypie/lib/class/options
 * @param {Object} options
 */
module.exports = MongoResource = new Class({
	inherits:Resource
	,options:{
		queryset: null
	}
	,constructor: function( options ){

		debugger;
		joi.assert(options.queryset, joi.required(),'querset is required')
		var instance = new options.queryset
		this.options.objectTpl = instance.model;
		this.parent( 'constructor', options )
		instance = null;

	}
	, _get_list: function( bundle, callback ){
		var query = new this.options.queryset();

		query.exec( callback )
	}
	,method: function(){

		/**
		 * @name module:tastypie/lib/resource/mongoose#event
		 * @event
		 * @param {TYPE} name description
		 **/
		this.emit('event', arg1, arg2)
	}
});
<commit_msg>[PIE-4] Start of filtering and sorting logic for Mongo resource<commit_after>/*jshint laxcomma: true, smarttabs: true, node:true */
'use strict';
/**
 * A Resource for interacting with the Mongoose ODM for mongodb
 * @module tastypie/lib/resource/mongoose
 * @author Eric Satterwhite
 * @since 0.0.1
 * @requires util
 * @requires tastypie/lib/class
 * @requires tastypie/lib/class/options
 * @requires tastypie/lib/resource
 * @requires joi
 */

var util       = require( 'util' )
  , Class      = require( '../class' )
  , Options    = require( '../class/options' )
  , object     = require('mout/object')
  , Resource   = require('./index')
  , joi        = require('joi')
  , isFunction = require('mout/lang/isFunction')
  , typecast   = require('mout/string/typecast')
  , compact    = require('mout/array/map')
  , set        = require('mout/object/set')
  , orderExp   = /^(\-)?([\w]+)/
  , SEP        = '__'
  , MongoResource
  , terms
  ;

function quickmap( array, mapFunction ){
	var arrayLen = array.length;
	 var newArray = new Array(arrayLen);
	 for(var i = 0; i < arrayLen; i++) {
	   newArray[i] = mapFunction(array[i], i, array);
	 }

	 return newArray;
};

terms = {
	'gt'          : '$gt'
  , 'gte'         : '$gte'
  , 'in'          : '$in'
  , 'lt'          : '$lt'
  , 'lte'         : '$lte'
  , 'ne'          : '$ne'
  , 'nin'         : '$nin'
  , 'regex'       : '$regex'
  , 'all'         : '$all'
  , 'size'        : '$size'
  , 'match'       : '$elemMatch'
  , 'contains'    : { key:'$regex', value: function( term ){ return new RegExp( term )}}
  , 'icontains'   : { key:'$regex', value: function( term ){ return new RegExp(term, 'i')}}
  , 'startswith'  : { key:'$regex', value: function( term ){ return new RegExp( '^' + term ) }}
  , 'istartswith' : { key:'$regex', value: function( term ){ return new RegExp( '^' + term, 'i' )}}
  , 'endswith'    : { key:'$regex', value: function( term ){ return new RegExp( term + '$' ) }}
  , 'iendswith'   : { key:'$regex', value: function( term ){ return new RegExp( term + '$', 'i') }}
}
/**
 * Description
 * @constructor
 * @alias module:tastypie/lib/resource/mongoose
 * @extends module:tastypie/lib/resource
 * @mixes module:tastypie/lib/class/options
 * @param {Object} options
 */
module.exports = MongoResource = new Class({
	inherits:Resource
	,options:{
		queryset: null
	}
	,constructor: function( options ){
		var instance;
		joi.assert(options.queryset, joi.required(),'querset is required')
		this.parent( 'constructor', options );

		instance = new options.queryset;
		this.options.objectTpl = this.options.objectTpl || instance.model;
		instance = null;

	}
	, get_list: function get_list( bundle ){
		var query = new this.options.queryset();

		query.model.count(function(err, cnt ){
			this._get_list( bundle,function( e, objects ){
				var that = this;
				objects = objects || [];
				var paginator = new this.options.paginator({
					limit:bundle.req.limit
					,req:bundle.req
					,res:bundle.res
					,collectionName:this.options.collection
					,objects:objects
					,count: cnt
					,offset: bundle.req.query.offset
				});
				var to_be_serialize = paginator.page();
				debug('serializing')
				to_be_serialize[ this.options.collection ] = to_be_serialize[ this.options.collection ].map( function( item ){
					return that.full_dehydrate( item, bundle )
				});
				bundle.data = to_be_serialize
				debug('responding')
				return this.respond( bundle )
			}.bind( this ));
		})
	}
	, _get_list: function( bundle, callback ){
		var query = new this.options.queryset();
		   , filters = this.buildFilters( bundle.req.query )
		this.sort( query, bundle.req.query )
		query.where( filters )
		query.exec( callback )
	}

	,buildFilters: function buildFilters( qs ){
		var query = new this.options.queryset();
		  , remaining = {};

		for( var key in qs ){
			var bits = key.split( SEP )
			   , filter = {}
			   , value
			   , fieldname
			   , filtertype
			   , last

			value     = qs[key];
			fieldname = bits.shift();

			bits = quickmap(bits, function( bit ){
				if( terms.hasOwnProperty( bit ) ){
					return terms[ bit ];
				}
				return bit;
			});

			filtertype = bits.length > 0 && isFunction( bits[ bits.length -1 ] )  ? bits.pop() : filtertype
			// should be defined on resource instance
			if( allowablepaths.indexOf( fieldname ) >=0 ){
				bits.unshift( fieldname );
				filter = bits.length ? set( filter, join( bits, '.' ),  isFunction( last.value ) ? last.value( value ) : typecast( value ) ) : typecast( value );
				remaining[ fieldname ] = filter;
			}
		}
		return remaining;
	}

	, sort: function sort( mquery, rquery ){
		var ordering = {};
		toArray( rquery.orderby ).forEach( function( param ){
			var bits = orderExp.exec( param );

			if( !bits ){
				return;
			}

			ordering[ bits[2] ] = bits[1] ? -1 : 1;
		});

		mquery.sort( ordering );
		return mquery;
	}
});
<|endoftext|>


<commit_before>var request = require('request');
var funkit = require('funkit');

function api(url, cb) {
    getMeta(url, function(err, d) {
        if(err) cb(err);
        else cb(null, constructAPI(url, d));
    });
}
exports.api = api;

function getMeta(url, cb) {
    request.get(url, function(err, d) {
        if(err || d.statusCode != 200) cb(err || d.body);
        else cb(null, JSON.parse(d.body));
    });
}
exports.getMeta = getMeta;

function constructAPI(url, d) {
    var ret = {};
    var parts = url.split('?');
    url = funkit.rtrim(parts[0], '/') + '/';
    var q = QtoOb(parts[1]);

    for(var k in d) {
        var v = d[k];
        var r = url + k;

        // TODO: collection ops (ie. boards(id).columns.<op>)
        ret[k] = {};
        ret[k].get = op('get', r, q);
        ret[k].count = op('get', r + '/count', q);
        ret[k].create = op('post', r, q);
        ret[k].update = op('put', r, q);
        ret[k]['delete'] = op('del', r, q);
    }

    return ret;
}

function op(method, r, q) {
    return function(o, cb) {
        if(funkit.isObject(o)) {
            o.method = method;
            var id = o.id || '';
            delete o.id;
            o = funkit.merge(o, q);

            request.get({url: r + '/' + id, qs: o},
                handle(cb));
        }
        else {
            o = o? o: '';
            request.get({url: r + o, qs: {method: method}},
                handle(cb));
        }
    };
}

function handle(cb) {
    return function(err, d) {
        if(err || d.statusCode != 200) cb(err || d.body);
        else cb(null, JSON.parse(d.body));
    };
}

function QtoOb(q) {
    q = q? q.split('&'): [];
    return funkit.ziptoo(q.map(funkit.partial(funkit.split, '=')));
}
exports.QtoOb = QtoOb;

function toQ(o) {
    var fields = o.fields? o.fields.join(','): '';
    delete o.fields;

    return fields + funkit.otozip(o).map(function(v) {
        return v[0] + '=' + v[1].split(' ').join('+');
    }).join('&');
}

<commit_msg>Make it possible to pass cb as the first param<commit_after>var request = require('request');
var funkit = require('funkit');

function api(url, cb) {
    getMeta(url, function(err, d) {
        if(err) cb(err);
        else cb(null, constructAPI(url, d));
    });
}
exports.api = api;

function getMeta(url, cb) {
    request.get(url, function(err, d) {
        if(err || d.statusCode != 200) cb(err || d.body);
        else cb(null, JSON.parse(d.body));
    });
}
exports.getMeta = getMeta;

function constructAPI(url, d) {
    var ret = {};
    var parts = url.split('?');
    url = funkit.rtrim(parts[0], '/') + '/';
    var q = QtoOb(parts[1]);

    for(var k in d) {
        var v = d[k];
        var r = url + k;

        // TODO: collection ops (ie. boards(id).columns.<op>)
        ret[k] = {};
        ret[k].get = op('get', r, q);
        ret[k].count = op('get', r + '/count', q);
        ret[k].create = op('post', r, q);
        ret[k].update = op('put', r, q);
        ret[k]['delete'] = op('del', r, q);
    }

    return ret;
}

function op(method, r, q) {
    return function(o, cb) {
        if(funkit.isObject(o)) {
            o.method = method;
            var id = o.id || '';
            delete o.id;
            o = funkit.merge(o, q);

            request.get({url: r + '/' + id, qs: o},
                handle(cb));
        }
        else if(funkit.isFunction(o)) {
            request.get({url: r, qs: {method: method}},
                handle(cb));
        }
        else {
            o = o? o: '';
            request.get({url: r + o, qs: {method: method}},
                handle(cb));
        }
    };
}

function handle(cb) {
    return function(err, d) {
        if(err || d.statusCode != 200) cb(err || d.body);
        else cb(null, JSON.parse(d.body));
    };
}

function QtoOb(q) {
    q = q? q.split('&'): [];
    return funkit.ziptoo(q.map(funkit.partial(funkit.split, '=')));
}
exports.QtoOb = QtoOb;

function toQ(o) {
    var fields = o.fields? o.fields.join(','): '';
    delete o.fields;

    return fields + funkit.otozip(o).map(function(v) {
        return v[0] + '=' + v[1].split(' ').join('+');
    }).join('&');
}

<|endoftext|>


<commit_before>var addon = require('./build/Release/addon');

var obj = new addon.FireFlyWrap(10);

console.log( 'num cameras' , obj.getNumCameras())
console.log("start Camera 0 ", obj.startCamera())
console.log( obj.getCamInfo() )
console.log("auto gain is ", obj.autoGain(true) )
console.log("auto gain is ", obj.autoGain(false) )
console.log("auto exposure is ", obj.autoExposure(true) )
console.log("auto exposure is ", obj.autoExposure(false) )
console.log("auto exposure is ", obj.autoExposure(false) )
console.log("auto exposure is ", obj.autoExposure(false) )
console.log("exposure value is ", obj.getExposure())
console.log("setting exposure value to 48 : ", obj.exposure(48))

console.log("set gain to ", obj.gain(24) )
console.log("frame rate", obj.frameRate() )

var pic = obj.takePhoto()
console.log( "take photo ", pic )
console.log( "take grey photo", obj.takePhoto('rgb') )
console.log(obj.getWidth(), obj.getHeight())
console.log("pic length",pic.length, pic[1])
<commit_msg>fixed up for npm<commit_after>
module.exports = require('./build/Release/addon');

/*
 *
 *
 *
 var obj = new addon.FireFlyWrap(10);

 console.log( 'num cameras' , obj.getNumCameras())
console.log("start Camera 0 ", obj.startCamera())
console.log( obj.getCamInfo() )

console.log("auto gain is ", obj.autoGain(true) )
console.log("auto gain is ", obj.autoGain(false) )
console.log("auto exposure is ", obj.autoExposure(true) )
console.log("auto exposure is ", obj.autoExposure(false) )
console.log("auto exposure is ", obj.autoExposure(false) )
console.log("auto exposure is ", obj.autoExposure(false) )
console.log("exposure value is ", obj.getExposure())
console.log("setting exposure value to 48 : ", obj.exposure(48))

console.log("set gain to ", obj.gain(24) )
console.log("frame rate", obj.frameRate() )

var pic = obj.takePhoto()
console.log( "take photo ", pic )
console.log( "take grey photo", obj.takePhoto('rgb') )
console.log(obj.getWidth(), obj.getHeight())
console.log("pic length",pic.length, pic[1])

return obj
*/<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

(function (context) {
    // Replace navigator before any modules are required(), to ensure it happens as soon as possible.
    // We replace it so that properties that can't be clobbered can instead be overridden.
    if (context.navigator) {
        var CordovaNavigator = function() {};
        CordovaNavigator.prototype = context.navigator;
        context.navigator = new CordovaNavigator();
    }

    var channel = require("cordova/channel"),
        _self = {
            boot: function () {
                /**
                 * Create all cordova objects once page has fully loaded and native side is ready.
                 */
                channel.join(function() {
                    var builder = require('cordova/builder'),
                        platform = require('cordova/platform');

                    builder.buildIntoButDoNotClobber(platform.defaults, context);
                    builder.buildIntoAndClobber(platform.clobbers, context);
                    builder.buildIntoAndMerge(platform.merges, context);

                    // Call the platform-specific initialization
                    platform.initialize();

                    // Fire event to notify that all objects are created
                    channel.onCordovaReady.fire();

                    // Fire onDeviceReady event once all constructors have run and
                    // cordova info has been received from native side.
                    channel.join(function() {
                        require('cordova').fireDocumentEvent('deviceready');
                    }, channel.deviceReadyChannelsArray);

                }, [ channel.onDOMContentLoaded, channel.onNativeReady ]);
            }
        };

    // boot up once native side is ready
    channel.onNativeReady.subscribe(_self.boot);

    // _nativeReady is global variable that the native side can set
    // to signify that the native code is ready. It is a global since
    // it may be called before any cordova JS is ready.
    if (window._nativeReady) {
        channel.onNativeReady.fire();
    }

}(window));
<commit_msg>[all] Remove remaining usage of builder.<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

(function (context) {
    // Replace navigator before any modules are required(), to ensure it happens as soon as possible.
    // We replace it so that properties that can't be clobbered can instead be overridden.
    if (context.navigator) {
        var CordovaNavigator = function() {};
        CordovaNavigator.prototype = context.navigator;
        context.navigator = new CordovaNavigator();
    }

    var channel = require("cordova/channel"),
        _self = {
            boot: function () {
                /**
                 * Create all cordova objects once page has fully loaded and native side is ready.
                 */
                channel.join(function() {
                    var platform = require('cordova/platform');

                    // Call the platform-specific initialization
                    platform.initialize();

                    // Fire event to notify that all objects are created
                    channel.onCordovaReady.fire();

                    // Fire onDeviceReady event once all constructors have run and
                    // cordova info has been received from native side.
                    channel.join(function() {
                        require('cordova').fireDocumentEvent('deviceready');
                    }, channel.deviceReadyChannelsArray);

                }, [ channel.onDOMContentLoaded, channel.onNativeReady ]);
            }
        };

    // boot up once native side is ready
    channel.onNativeReady.subscribe(_self.boot);

    // _nativeReady is global variable that the native side can set
    // to signify that the native code is ready. It is a global since
    // it may be called before any cordova JS is ready.
    if (window._nativeReady) {
        channel.onNativeReady.fire();
    }

}(window));
<|endoftext|>


<commit_before>module.exports.Factory = function(Sequelize, sequelize) {
  var Factory = {
    addManyToManyMethods: function(table1, table2, assocName, backAssocName) {
      table1.prototype[Sequelize.Helper.SQL.addPrefix('get', assocName)] = Factory.createManyToManyGetter(table1, table2, assocName, backAssocName)
      table1.prototype[Sequelize.Helper.SQL.addPrefix('set', assocName)] = Factory.createManyToManySetter(table1, table2, assocName, backAssocName)
    },

    addOneToManyMethods: function(table1, table2, assocName, methodName) {
      var setterName = Sequelize.Helper.SQL.addPrefix('set', methodName || assocName),
          getterName = Sequelize.Helper.SQL.addPrefix('get', methodName || assocName)

      table1.prototype[setterName] = Factory.createOneToManySetter(table1, assocName, methodName)
      table1.prototype[getterName] = Factory.createOneToManyGetter(table1, table2, assocName)
    },

    addOneToOneMethods: function(table1, table2, assocName, backAssocName) {
      var setterName = Sequelize.Helper.SQL.addPrefix('set', backAssocName || assocName, true),
          getterName = Sequelize.Helper.SQL.addPrefix('get', backAssocName || assocName, true)

      // getter
      table1.prototype[getterName] = function(callback) {
        var whereConditions = {}
        whereConditions[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = this.id
        table2.find(whereConditions, callback)
      }

      // setter
      table1.prototype[setterName] = function(object, callback) {
        var self = this

        this[Sequelize.Helper.SQL.addPrefix('get', backAssocName, true)](function(currentAssociation) {
          var attr = {}

          if(currentAssociation == null) {
            attr[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = self.id
            object.updateAttributes(attr, callback)
          } else {
            if(object.id == currentAssociation.id) callback(currentAssociation)
            else {
              // first update the currently associated item to have no association any more
              attr[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = null
              currentAssociation.updateAttributes(attr, function() {
                // now update the object itself to set the new association
                attr[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = self.id
                object.updateAttributes(attr, callback)
              })
            }
          }
        })
      }
    },

    createManyToManyGetter: function(table1, table2, assocName, backAssocName) {
      return function(callback) {
        var Association = sequelize.tables[Sequelize.Helper.SQL.manyToManyTableName(assocName, backAssocName)].klass,
            assocNameAsTableIdentifier = Sequelize.Helper.SQL.asTableIdentifier(backAssocName),
            whereConditions = [assocNameAsTableIdentifier, this.id].join("=")

        Association.findAll({ where: whereConditions }, function(result) {
          if(result.length > 0) {
            var ids = Sequelize.Helper.Array.map(result, function(resultSet) {
              return resultSet[Sequelize.Helper.SQL.asTableIdentifier(assocName)]
            })

            table2.findAll({where: "id IN (" + ids.join(",") + ")"}, callback)
          } else {
            if(callback) callback([])
          }
        })
      }
    },
    createManyToManySetter: function(table1, table2, assocName, backAssocName) {
      return function(objects, callback) {
        var self = this,
            Association = sequelize.tables[Sequelize.Helper.SQL.manyToManyTableName(assocName, backAssocName)].klass,
            objectIds = Sequelize.Helper.Array.map(objects, function(obj) { return obj.id })

        var getAssociatedObjects = function(callback) {
          self[Sequelize.Helper.SQL.addPrefix('get', assocName)](callback)
        }

        var deleteObsoleteAssociations = function(currentAssociations, callback) {
          var obsoleteAssociations = Sequelize.Helper.Array.select(currentAssociations, function(assoc) { return objectIds.indexOf(assoc.id) == -1 }),
              obsoleteIds = Sequelize.Helper.Array.map(obsoleteAssociations, function(assoc) { return assoc.id })

          if(obsoleteIds.length == 0)
            callback([])
          else {
            var deleteOptions = {
              table: Association.tableName,
              where: Sequelize.Helper.SQL.asTableIdentifier(assocName) + " IN (" + obsoleteIds.join(",") + ") AND " +
                Sequelize.Helper.SQL.asTableIdentifier(backAssocName) + " = " + self.id,
              limit: null
            }
            sequelize.query( Sequelize.sqlQueryFor('delete', deleteOptions), function(){ callback(obsoleteIds) } )
          }

        }

        var createNewAssociations = function(currentAssociations, obsoleteIds) {
          var currentIds = Sequelize.Helper.Array.map(currentAssociations, function(assoc) { return assoc.id }),
              withoutExisting = Sequelize.Helper.Array.select(objects, function(o) { return currentIds.indexOf(o.id) == -1 }),
              savings = []

          withoutExisting.forEach(function(o) {
            if((o instanceof table2) && (self.id != null) && (o.id != null)) {
              var attributes = {}
              attributes[Sequelize.Helper.SQL.asTableIdentifier(backAssocName)] = self.id
              attributes[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = o.id
              savings.push({save: new Association(attributes)})
            }
          })

          Sequelize.chainQueries(savings, function() {
            getAssociatedObjects(callback)
          })
        }

        getAssociatedObjects(function(associatedObjects) {
          deleteObsoleteAssociations(associatedObjects, function(obsolete) {
            createNewAssociations(associatedObjects, obsolete)
          })
        })
      }
    },
    createOneToManyGetter: function(table1, table2, assocName) {
      return function(callback) {
        var whereConditions = [Sequelize.Helper.SQL.asTableIdentifier(assocName), this.id].join("=")
        table2.findAll({where: whereConditions}, callback)
      }
    },
    createOneToManySetter: function(table1, assocName, methodName) {
      return function(objects, callback) {
        var self = this,
            objectIds = Sequelize.Helper.Array.map(objects, function(obj) { return obj.id })

        this[Sequelize.Helper.SQL.addPrefix('get', methodName)](function(currentAssociations) {
          var currentIds = Sequelize.Helper.Array.map(currentAssociations, function(assoc) { return assoc.id }),
              obsoleteAssociations = Sequelize.Helper.Array.select(currentAssociations, function(assoc) { return objectsIds.indexOf(assoc.id) == -1 }),
              queries = []

          obsoleteAssociations.forEach(function(assoc) {
            var attr = {}
            attr[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = null
            queries.push({updateAttributes: assoc, params: [attr]})
          })

          var newAssociations = Sequelize.Helper.Array.select(objects, function(o) { return currentIds.indexOf(o.id) == -1 })
          newAssociations.forEach(function(assoc) {
            var attr = {}
            attr[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = self.id
            queries.push({updateAttributes: assoc, params: [attr]})
          })

          Sequelize.chainQueries(queries, function() {
            self[Sequelize.Helper.SQL.addPrefix('get', methodName)](callback)
          })
        })
      }
    }
  }

  return Factory
}<commit_msg>always force the refetch of associated data when setting them; one-to-many association storage works<commit_after>module.exports.Factory = function(Sequelize, sequelize) {
  var Factory = {
    addManyToManyMethods: function(table1, table2, assocName, backAssocName) {
      table1.prototype[Sequelize.Helper.SQL.addPrefix('get', assocName)] = Factory.createManyToManyGetter(table1, table2, assocName, backAssocName)
      table1.prototype[Sequelize.Helper.SQL.addPrefix('set', assocName)] = Factory.createManyToManySetter(table1, table2, assocName, backAssocName)
    },

    addOneToManyMethods: function(table1, table2, assocName, methodName) {
      var setterName = Sequelize.Helper.SQL.addPrefix('set', methodName || assocName),
          getterName = Sequelize.Helper.SQL.addPrefix('get', methodName || assocName)

      table1.prototype[setterName] = Factory.createOneToManySetter(table1, assocName, methodName)
      table1.prototype[getterName] = Factory.createOneToManyGetter(table1, table2, assocName, methodName)
    },

    addOneToOneMethods: function(table1, table2, assocName, backAssocName) {
      var setterName = Sequelize.Helper.SQL.addPrefix('set', backAssocName || assocName, true),
          getterName = Sequelize.Helper.SQL.addPrefix('get', backAssocName || assocName, true)

      // getter
      table1.prototype[getterName] = function(callback) {
        var whereConditions = {}
        whereConditions[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = this.id
        table2.find(whereConditions, callback)
      }

      // setter
      table1.prototype[setterName] = function(object, callback) {
        var self = this

        this[Sequelize.Helper.SQL.addPrefix('get', backAssocName, true)](function(currentAssociation) {
          var attr = {}

          if(currentAssociation == null) {
            attr[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = self.id
            object.updateAttributes(attr, callback)
          } else {
            if(object.id == currentAssociation.id) callback(currentAssociation)
            else {
              // first update the currently associated item to have no association any more
              attr[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = null
              currentAssociation.updateAttributes(attr, function() {
                // now update the object itself to set the new association
                attr[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = self.id
                object.updateAttributes(attr, callback)
              })
            }
          }
        })
      }
    },

    createManyToManyGetter: function(table1, table2, assocName, backAssocName) {
      return function(options, callback) {
        var _callback   = ((typeof options == 'object') ? callback : options),
            _options    = (typeof options == 'object') ? options : {},
            self        = this

        if(_options.force || !this.hasFetchedAssociationFor(assocName)) {
          var Association = sequelize.tables[Sequelize.Helper.SQL.manyToManyTableName(assocName, backAssocName)].klass,
              assocNameAsTableIdentifier = Sequelize.Helper.SQL.asTableIdentifier(backAssocName),
              whereConditions = [assocNameAsTableIdentifier, this.id].join("=")

          Association.findAll({ where: whereConditions }, function(result) {
            if(result.length > 0) {
              var ids = Sequelize.Helper.Array.map(result, function(resultSet) {
                return resultSet[Sequelize.Helper.SQL.asTableIdentifier(assocName)]
              })

              table2.findAll({where: "id IN (" + ids.join(",") + ")"}, function(objects) {
//                self.fetchedAssociations[assocName] =
                if(_callback) _callback(objects)
              })
            } else {
              if(_callback) _callback([])
            }
          })
        } else {
          if(_callback) _callback(this.fetchedAssociations[assocName])
        }
      }
    },
    createManyToManySetter: function(table1, table2, assocName, backAssocName) {
      return function(objects, callback) {
        var self = this,
            Association = sequelize.tables[Sequelize.Helper.SQL.manyToManyTableName(assocName, backAssocName)].klass,
            objectIds = Sequelize.Helper.Array.map(objects, function(obj) { return obj.id })

        var getAssociatedObjects = function(callback) {
          self[Sequelize.Helper.SQL.addPrefix('get', assocName)](callback)
        }

        var deleteObsoleteAssociations = function(currentAssociations, callback) {
          var obsoleteAssociations = Sequelize.Helper.Array.select(currentAssociations, function(assoc) { return objectIds.indexOf(assoc.id) == -1 }),
              obsoleteIds = Sequelize.Helper.Array.map(obsoleteAssociations, function(assoc) { return assoc.id })

          if(obsoleteIds.length == 0)
            callback([])
          else {
            var deleteOptions = {
              table: Association.tableName,
              where: Sequelize.Helper.SQL.asTableIdentifier(assocName) + " IN (" + obsoleteIds.join(",") + ") AND " +
                Sequelize.Helper.SQL.asTableIdentifier(backAssocName) + " = " + self.id,
              limit: null
            }
            sequelize.query( Sequelize.sqlQueryFor('delete', deleteOptions), function(){ callback(obsoleteIds) } )
          }

        }

        var createNewAssociations = function(currentAssociations, obsoleteIds) {
          var currentIds = Sequelize.Helper.Array.map(currentAssociations, function(assoc) { return assoc.id }),
              withoutExisting = Sequelize.Helper.Array.select(objects, function(o) { return currentIds.indexOf(o.id) == -1 }),
              savings = []

          withoutExisting.forEach(function(o) {
            if((o instanceof table2) && (self.id != null) && (o.id != null)) {
              var attributes = {}
              attributes[Sequelize.Helper.SQL.asTableIdentifier(backAssocName)] = self.id
              attributes[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = o.id
              savings.push({save: new Association(attributes)})
            }
          })

          Sequelize.chainQueries(savings, function() {
            getAssociatedObjects(callback)
          })
        }

        getAssociatedObjects(function(associatedObjects) {
          deleteObsoleteAssociations(associatedObjects, function(obsolete) {
            createNewAssociations(associatedObjects, obsolete)
          })
        })
      }
    },
    createOneToManyGetter: function(table1, table2, assocName, methodName) {
      return function(options, callback) {
        var _callback = ((typeof options == 'object') ? callback : options),
            _options  = (typeof options == 'object') ? options : {},
            accessKey = methodName || assocName,
            self      = this

        if(_options.refetchAssociations || !this.hasFetchedAssociationFor(accessKey)) {
          var whereConditions = [Sequelize.Helper.SQL.asTableIdentifier(assocName), this.id].join("=")
          table2.findAll({where: whereConditions}, function(result) {
            self.setAssociationDataFor(accessKey, result)
            if(_callback) _callback(result)
          })
        } else {
          var result = self.getAssociationDataFor(accessKey)
          if(_callback) _callback(result)
        }
      }
    },
    createOneToManySetter: function(table1, assocName, methodName) {
      return function(objects, callback) {
        var self       = this,
            objectIds  = Sequelize.Helper.Array.map(objects, function(obj) { return obj.id }),
            getterName = Sequelize.Helper.SQL.addPrefix('get', methodName)

        this[getterName]({refetchAssociations: true}, function(currentAssociations) {
          var currentIds = Sequelize.Helper.Array.map(currentAssociations, function(assoc) { return assoc.id }),
              obsoleteAssociations = Sequelize.Helper.Array.select(currentAssociations, function(assoc) { return objectIds.indexOf(assoc.id) == -1 }),
              queries = []

          obsoleteAssociations.forEach(function(assoc) {
            var attr = {}
            attr[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = null
            queries.push({updateAttributes: assoc, params: [attr]})
          })

          var newAssociations = Sequelize.Helper.Array.select(objects, function(o) { return currentIds.indexOf(o.id) == -1 })
          newAssociations.forEach(function(assoc) {
            var attr = {}
            attr[Sequelize.Helper.SQL.asTableIdentifier(assocName)] = self.id
            queries.push({updateAttributes: assoc, params: [attr]})
          })

          Sequelize.chainQueries(queries, function() {
            self[getterName]({refetchAssociations: true}, callback)
          })
        })
      }
    }
  }

  return Factory
}<|endoftext|>


<commit_before>"use strict";

var express = require('express')
  , _s = require('underscore.string');

module.exports.parserWrap = function(req, res, next) {
  // wd.js sends us http POSTs with empty body which will make bodyParser fail.
  var cLen = req.get('content-length');
  if (typeof cLen === "undefined" || parseInt(cLen, 10) <= 0) {
    req.headers['content-length'] = 0;
    next();
  } else {
    // allow guineapig
    if (!_s.startsWith(req.path, "/test")) {
      // hack because python client library sux
      if (req.headers['content-type'] === 'application/x-www-form-urlencoded') {
        req.headers['content-type'] = 'application/json';
      }
    }
    next();
  }
};
<commit_msg>Don't set Content-Length header for http POSTs with empty body.<commit_after>"use strict";

var express = require('express')
  , _s = require('underscore.string');

module.exports.parserWrap = function(req, res, next) {
  // allow guineapig
  if (!_s.startsWith(req.path, "/test")) {
    // hack because python client library sux
    if (req.headers['content-type'] === 'application/x-www-form-urlencoded') {
      req.headers['content-type'] = 'application/json';
    }
  }

  next();
};
<|endoftext|>


<commit_before>(function() {
    'use strict';

    module.exports  = function tryRequire(name, options) {
        var result,
            o       = options || {},

            error   = tryCatch(function() {
                result = require(name);
            });

        if (error) {
            if (o.log)
                console.error([
                    module.parent.filename + ':',
                    error.code,
                    '\'' + name + '\'',
                ].join(' '));
            else if (o.callback)
                result = exec.bind(null, error);

            if (o.exit)
                process.exit(1);
        }

        return result;
    };

    function exec(error, callback) {
        callback(error);
    }

    function tryCatch(fn) {
        var error;

        try {
            fn();
        } catch(err) {
            error = err;
        }

        return error;
    }
})();
<commit_msg>feature(tryRequire) rm module.parent.filename<commit_after>(function() {
    'use strict';

    module.exports  = function tryRequire(name, options) {
        var result,
            o       = options || {},

            error   = tryCatch(function() {
                result = require(name);
            });

        if (error) {
            if (o.log)
                console.error(error.message);
            else if (o.callback)
                result = exec.bind(null, error);

            if (o.exit)
                process.exit(1);
        }

        return result;
    };

    function exec(error, callback) {
        callback(error);
    }

    function tryCatch(fn) {
        var error;

        try {
            fn();
        } catch(err) {
            error = err;
        }

        return error;
    }
})();
<|endoftext|>