<commit_before>    /*
    Copyright (C) 2015 Tony Mobily

    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 ( define ){

      "use strict";
      /*jslint node: true */

      define( function( require, exports, module ){

        function getObjectBase( o, fn ){

          var found = false, currentPoint = o;
          var k, i, l;

          while( currentPoint ){

            var objMethods = Object.getOwnPropertyNames( currentPoint );
            for( i = 0, l = objMethods.length; i < l; i ++ ){
              k = objMethods[ i ];

              if( currentPoint.hasOwnProperty( k ) && currentPoint[ k ] === fn ){
                found = true;
                break;
              }
            }
            // If found, break out of the cycle. Otherwise, keep looking in the next proto up
            if( found ) break;
            currentPoint = Object.getPrototypeOf( currentPoint );
          }

          // Return crrentPoint. Note that if the search was unsccessful,
          // currentPoint will be `null`
          return { base: currentPoint, key: k };
        }

        // This will become a method call, so `this` is the object
        var getInherited = function( fn ){

          // Get the object's base
          var objectBase = getObjectBase( this, fn );

          // If the function is not found anywhere in the prototype chain
          // there is a pretty big problem
          if( ! objectBase.base ) throw new Error( "inherited coun't find method in chain (getInherited)" );

          // At this point, I know the key. To look for the super method, I
          // only have to check if one of the parent __proto__ has a matching key `k`
          var p = Object.getPrototypeOf( objectBase.base );
          return p[ objectBase.key ];
        };

        var makeInheritedFunction = function( type ){

          // This will become a method call, so `this` is the object
          return function( fn, args, cb ){

            // Get the inherited function
            var fnUp = this.getInherited( fn );

            // No inherited function in the chain, just call the callback (async) or return nothing
            if( ! fnUp  ){
              if( type === 'async' ) return cb.call( this, null );
              if( type === 'sync' ) return;
            }

            // Call the function. It could be sync or async
            if( type == 'async' ){
              var argsMinusCallback = Array.prototype.slice.call(args, 0, -1 ).concat( cb );
              return fnUp.apply( this, argsMinusCallback );
            } else {
              return fnUp.apply( this, args );
            }
          };
        };

        // This will be added as a Constructor-wide method
        // of constructor created with simpleDeclare (only if needed)
        var extend = function(){

          // Normalise the arguments passed
          var r = workoutDeclareArguments( arguments );
          r.SuperCtorList.unshift( this );

          // Will run declare with the 2-parameter signature
          return declare( r.SuperCtorList, r.protoMixin );
        };

        // Look for Ctor.prototype anywhere in the __proto__ chain.
        // Unlike Javascript's plain instanceof, this method attempts
        // to compare
        var instanceOf = function( Ctor ){

          var searchedProto = Ctor.OriginalConstructor ? Ctor.OriginalConstructor.prototype : Ctor.prototype;
          var current = this;
          var compare;

          while( ( current = Object.getPrototypeOf( current ) ) ){

            // It will compare either with OriginalConstructor.prototype or plain prototype
            compare = current.constructor.OriginalConstructor ?
                      current.constructor.OriginalConstructor.prototype :
                      current.constructor.prototype;

            // Actually run the comparison
            if( compare === searchedProto ) return true;
          }
          return false;
        };

        var makeConstructor = function( FromCtor, protoMixin, SourceOfProto ){

          var ActualConstructor;

          var ReturnedCtor = function(){

            // The object's main constructor is being run. It will be responsible of
            // running all of the constructors in the prototype chain, starting from
            // the innermost and moving all the way out, except the last one
            // (which is itself)
            if( Object.getPrototypeOf( this ).constructor === ReturnedCtor ){

              // Goes through the prototype chain and execute every single constructor.
              // If the constructor has the ActualConstructor attribute, then it's a SimpleDeclare
              // constructor
              var l = [];
              var o = this;
              while( ( o = Object.getPrototypeOf( o ) ) ){
                l.push( o.constructor );
              }
              for( var i = l.length - 1; i >=1; i -- ){
                l[ i ].apply( this, arguments );
              }
            }

            // Itself. Since I *know* this is a SimpleDeclare constructor,
            // run ActualConstructor if available
            if( ActualConstructor ) ActualConstructor.apply( this, arguments );
          };

          // protoMixin MUST be a valid, not-null object
          if( typeof( protoMixin ) !== 'object' || protoMixin === null) protoMixin = {};

          // Create the new function's prototype. It's a new object, which happens to
          // have its own prototype (__proto__) set as the superclass' prototype and the
          // `constructor` attribute set as FromCtor (the one we are about to return)
          ReturnedCtor.prototype = Object.create(FromCtor.prototype, {
            constructor: {
              value: ReturnedCtor,
              enumerable: false,
              writable: true,
              configurable: true
            }
          });

          // Copy every element in protoMixin into the prototype.
          // Note that `constructor` is special: it's _not_ copied over.
          // Instead, it's placed in ReturnedCtor.ActualConstructor.
          // It can either come:
          //   * from protoMixin, in cases where SourceOfProto is not defined
          //     (which means that it's what the developer passed herself in `protoMixin` as `constructor`)
          //   * from the source of protoMixin, in cases where SourceOfProto is defined
          //     (which means that we are taking it from the SourceOfProto, since the goal
          //      is to mimic it completely creating a working copy of the original constructor)
          var ownProps = Object.getOwnPropertyNames( protoMixin );
          for( var i = 0, l = ownProps.length; i < l; i ++ ){
            var k = ownProps[ i ];

            if( k !== 'constructor' ) ReturnedCtor.prototype[ k ] = protoMixin[ k ];
          }

          // We are not cloning a constructor, but creating a brand new one (using protoMixin as
          // a source of methods that just got added to the prototype).
          // ActualConstructor will be set to the `constructor` property of protoMixin
          if( ! SourceOfProto ){
            if( protoMixin.hasOwnProperty( 'constructor' ) ) ActualConstructor = protoMixin.constructor;
          }

          // We are in the process of cloning an existing constructor.
          // When doing that:
          // * ReturnedCtor's ActualConstructor will be set to the Source's ActualConstructor.
          //   This will ensure that the stock constructor (that just invokes ActualConstructor) works.
          // * ReturnedCtor's OriginalConstructor will be set to the Source's ActualConstructor (or the souce itself).
          //   This will ensure that we have a path to the actual constructor we actually cloned,
          //   so that instanceOf() will work (by checking ActualConstructor whenever possible)
          if( SourceOfProto ){
            ActualConstructor = SourceOfProto;
            ReturnedCtor.OriginalConstructor = SourceOfProto.OriginalConstructor || SourceOfProto;
          }

          // That's it!
          return ReturnedCtor;
        };

        var copyClassMethods = function( Source, Dest ){

          // Source class needs to be a function
          if( typeof( Source) !== 'function' ) throw new Error("Error: source constructor must be a function");

          // Copy class methods over, EXCEPT if it's Object (the base class) which is ALWAYS
          // gracefully ignored
          if( Source !== Object ){

            var ownProps = Object.getOwnPropertyNames( Source );
            for( var i = 0, l = ownProps.length; i < l; i ++){
              var property = ownProps[ i ];

              // This statement is there so that strict mode still works -- even accessing these
              // automatically like this will cause an error!
              if( property !== 'arguments' && property !== 'callee' && property !== 'caller' ){

                // It's one of the attributes' in Function()'s prototype: skip
                if( Function.prototype[ property ] === Source[ property ] || property === 'prototype' ) continue;
                // It's one of the attributes managed by simpleDeclare: skip
                if( [ 'extend', 'OriginalConstructor' ].indexOf( property ) !== -1 ) continue;
                Dest[ property ] = Source[ property ];
              }
            }
          }
        };

        // This method will be attached to `list` in `declare()`,
        // and it will be used to make sure that only fresh prototypes
        // are added
        var constructorAlreadyInList = function( Ctor, list ){

          var CtorConstructor = Ctor.OriginalConstructor ||  Ctor;
          var protoConstructor;

          var found = false;
          for( var i = 0, l = list.length; i < l; i ++ ){
            var proto = list[ i ];

            protoConstructor = proto.constructor.OriginalConstructor || proto.constructor;
            if( protoConstructor === CtorConstructor ){
              found = true;
              break;
            }
          }

          return found;
        };

        // Normalise arguments passed to declare(): the end result will always be
        // an object with two values:
        //  * SuperCtorList - an array of constructors
        //  * protoMixin - an object with prototype attributes
        // This implies that you can actually throw basically anything that makes sense
        // to declare: declare(), declare( A ), declare( )
        var workoutDeclareArguments = function( args ){

          var arg;

          // No arguments at all: inheriting straight from Object, nothing in the prototype
          if( args.length === 0 ) return { SuperCtorList: [], protoMixin: {} };

          // One argument: it could be:
          //   * An array of constructors
          //   * A protoMixin
          //   * A single constructor
          //  Act accordingly
          if( args.length === 1 ){

            arg = args[ 0 ];
            // It's an array of constructors
            if( Array.isArray( arg ) )
              return { SuperCtorList: arg, protoMixin: {} };
            // It's a protoMixin
            else if( typeof arg === 'object' && arg !== null )
              return { SuperCtorList: [], protoMixin: arg };
            // It's a constructor
            else if( typeof arg === 'function' )
              return { SuperCtorList: [ arg ], protoMixin: {} };
            else
              throw new Error( "Invalid lone argument to declare(), needs to be array, function or pure object" );
          }

          // Two arguments. Only check if the first one is an array. If it is, then it's the list of
          // constructors, with second argument POSSIBLY being protoMixin
          if( args.length === 2 ){
            var a = args[ 0 ];
            var b = args[ 1 ];

            // First parameter is an array: that's the list of ctors
            if( Array.isArray( a ) ){
              // Normalise b
              if( typeof b !== 'object' || b === null ) b = {};
              return { SuperCtorList: a, protoMixin: b };
            }
          }

          // CHECK POINT: at this point, there are 2 or more arguments, and the "array as first proto" is
          // out of the picture. So, will go through args and make up the array based on it
          var lastIndex = args.length - 1;
          var list = [];
          // This cycle will deal with all items except the last one, which might be either a
          // constructor or a protoMixin
          for( var i = 0; i < lastIndex; i ++ ){
            var item = args[ i ];

            // Check that it's the right type, allowing for the last one to be an exception
            if( typeof item !== 'function' )
              throw new Error("Parameters to declare() must be constructor functions (except the last one which can be an object for the prototype)");
            list.push( item );
          }

          // The last one might be either a constructor function, or a protoMixin.
          // Deal with either case
          var lastOne = args[ lastIndex ];
          if( typeof lastOne === 'function' ){
            list.push( lastOne );
            return { SuperCtorList: list, protoMixin: {} };
          } else if( typeof lastOne === 'object' && lastOne !== null ) {
            return { SuperCtorList: list, protoMixin: lastOne };
          } else throw new Error("Last argument of declare() must be either a function or a mixin object");
        };

        // Parameters are very variable
        var declare = function(){

          // These will be worked out from `arguments`
          var SuperCtorList, protoMixin;

          var MixedClass, ResultClass;
          var list = [];
          var i, l, ii, ll;
          var proto;

          var r = workoutDeclareArguments( arguments );
          SuperCtorList = r.SuperCtorList;
          protoMixin = r.protoMixin;

          // No parameters: inheriting from Object directly, no multiple inheritance
          if( SuperCtorList.length === 0 ){
            MixedClass = Object;
          }
          // Only one parameter: straght single inheritance.
          else if( SuperCtorList.length === 1 ){
            MixedClass = SuperCtorList[ 0 ];

          // More than one parameter: multiple inheritance at work
          // MixedClass will end up being an artificially made constructor
          // where the prototype chain is the sum of _every_ prototype in
          // every element of SuperCtorList (taking out duplicates)
          } else {
            MixedClass = Object;

            // NOW:
            // Go through every __proto__ of every derivative class, and augment
            // MixedClass by inheriting from A COPY OF each one of them.

            list = [];
            for( i = 0, l = SuperCtorList.length; i < l; i ++ ){

              // Get the prototype list, in the right order
              // (the reversed discovery order)
              // The result will be placed in `subList`
              var subList = [];
              proto = SuperCtorList[ i ].prototype;
              while( proto ){
                if( proto.constructor !== Object ) subList.push( proto );
                proto = Object.getPrototypeOf( proto );
              }
              subList = subList.reverse();

              // Add each element of sublist as long as it's not already in the main `list`
              for( ii = 0, ll = subList.length; ii < ll; ii ++ ){
                if( ! constructorAlreadyInList( subList[ ii ].constructor, list ) ) list.push( subList[ ii ] );
              }
            }

            // For each element in the prototype list that isn't Object(),
            // augment MixedClass with a copy of the new prototype
            for( ii = 0, ll = list.length; ii < ll; ii ++ ){
              proto = list[ ii ];

              var M = MixedClass;

              if( proto.constructor !== Object ){

                MixedClass = makeConstructor( MixedClass, proto, proto.constructor );
                copyClassMethods( M, MixedClass ); // Methods previously inherited

                copyClassMethods( proto.constructor, MixedClass ); // Extra methods from the father constructor
              }
            }
          }

          // Finally, inherit from the MixedClass, and add
          // class methods over
          // MixedClass might be:
          // * Object (coming from no inheritance),
          // * SuperCtorList[0] (coming from single inheritance)
          // * A constructor with the appropriate prototype chain (multiple inheritance)
          ResultClass = makeConstructor( MixedClass, protoMixin );
          copyClassMethods( MixedClass, ResultClass );

          // Add getInherited, inherited() and inheritedAsync() to the prototype
          // (only if they are not already there)
          if( ! ResultClass.prototype.getInherited ) {
            ResultClass.prototype.getInherited = getInherited;
          }
          if( ! ResultClass.prototype.inherited ) {
            ResultClass.prototype.inherited = makeInheritedFunction( 'sync' );
          }
          if( ! ResultClass.prototype.inheritedAsync ) {
            ResultClass.prototype.inheritedAsync = makeInheritedFunction( 'async' );
          }

          // Add instanceOf
          if( ! ResultClass.prototype.instanceOf ) {
            ResultClass.prototype.instanceOf = instanceOf;
          }

          // Add class-wide method `extend`
          ResultClass.extend = function(){
            return extend.apply( this, arguments );
          };

          // That's it!
          return ResultClass;
        };

        // Returned extra: declarableObject
        declare.extendableObject = declare( Object );

        exports = module.exports = declare;

      });
    }(
        typeof define == 'function' && define.amd ?
            define :
            function ( factory ) { factory( require, exports, module); }
    ));<commit_msg>Debugging line added<commit_after>    /*
    Copyright (C) 2015 Tony Mobily

    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 ( define ){

      "use strict";
      /*jslint node: true */

      define( function( require, exports, module ){

        function getObjectBase( o, fn ){

          var found = false, currentPoint = o;
          var k, i, l;

          while( currentPoint ){

            var objMethods = Object.getOwnPropertyNames( currentPoint );
            for( i = 0, l = objMethods.length; i < l; i ++ ){
              k = objMethods[ i ];

              if( currentPoint.hasOwnProperty( k ) && currentPoint[ k ] === fn ){
                found = true;
                break;
              }
            }
            // If found, break out of the cycle. Otherwise, keep looking in the next proto up
            if( found ) break;
            currentPoint = Object.getPrototypeOf( currentPoint );
          }

          // Return crrentPoint. Note that if the search was unsccessful,
          // currentPoint will be `null`
          return { base: currentPoint, key: k };
        }

        // This will become a method call, so `this` is the object
        var getInherited = function( fn ){

          // Get the object's base
          var objectBase = getObjectBase( this, fn );

          // If the function is not found anywhere in the prototype chain
          // there is a pretty big problem
          if( ! objectBase.base ) throw new Error( "inherited coun't find method in chain (getInherited)" );

          // At this point, I know the key. To look for the super method, I
          // only have to check if one of the parent __proto__ has a matching key `k`
          var p = Object.getPrototypeOf( objectBase.base );
          return p[ objectBase.key ];
        };

        var makeInheritedFunction = function( type ){

          // This will become a method call, so `this` is the object
          return function( fn, args, cb ){

            // Get the inherited function
            var fnUp = this.getInherited( fn );

            // No inherited function in the chain, just call the callback (async) or return nothing
            if( ! fnUp  ){
              if( type === 'async' ) return cb.call( this, null );
              if( type === 'sync' ) return;
            }

            // Call the function. It could be sync or async
            if( type == 'async' ){
              var argsMinusCallback = Array.prototype.slice.call(args, 0, -1 ).concat( cb );
              return fnUp.apply( this, argsMinusCallback );
            } else {
              return fnUp.apply( this, args );
            }
          };
        };

        // This will be added as a Constructor-wide method
        // of constructor created with simpleDeclare (only if needed)
        var extend = function(){

          // Normalise the arguments passed
          var r = workoutDeclareArguments( arguments );
          r.SuperCtorList.unshift( this );

          // Will run declare with the 2-parameter signature
          return declare( r.SuperCtorList, r.protoMixin );
        };

        // Look for Ctor.prototype anywhere in the __proto__ chain.
        // Unlike Javascript's plain instanceof, this method attempts
        // to compare
        var instanceOf = function( Ctor ){

          var searchedProto = Ctor.OriginalConstructor ? Ctor.OriginalConstructor.prototype : Ctor.prototype;
          var current = this;
          var compare;

          while( ( current = Object.getPrototypeOf( current ) ) ){

            // It will compare either with OriginalConstructor.prototype or plain prototype
            compare = current.constructor.OriginalConstructor ?
                      current.constructor.OriginalConstructor.prototype :
                      current.constructor.prototype;

            // Actually run the comparison
            if( compare === searchedProto ) return true;
          }
          return false;
        };

        var makeConstructor = function( FromCtor, protoMixin, SourceOfProto ){

          var ActualConstructor;

          var ReturnedCtor = function(){

            // The object's main constructor is being run. It will be responsible of
            // running all of the constructors in the prototype chain, starting from
            // the innermost and moving all the way out, except the last one
            // (which is itself)
            if( Object.getPrototypeOf( this ).constructor === ReturnedCtor ){

              // Goes through the prototype chain and execute every single constructor.
              // If the constructor has the ActualConstructor attribute, then it's a SimpleDeclare
              // constructor
              var l = [];
              var o = this;
              while( ( o = Object.getPrototypeOf( o ) ) ){
                l.push( o.constructor );
              }
              for( var i = l.length - 1; i >=1; i -- ){
                l[ i ].apply( this, arguments );
              }
            }

            // Itself. Since I *know* this is a SimpleDeclare constructor,
            // run ActualConstructor if available
            if( ActualConstructor ) ActualConstructor.apply( this, arguments );
          };

          // protoMixin MUST be a valid, not-null object
          if( typeof( protoMixin ) !== 'object' || protoMixin === null) protoMixin = {};

          // Create the new function's prototype. It's a new object, which happens to
          // have its own prototype (__proto__) set as the superclass' prototype and the
          // `constructor` attribute set as FromCtor (the one we are about to return)
          ReturnedCtor.prototype = Object.create(FromCtor.prototype, {
            constructor: {
              value: ReturnedCtor,
              enumerable: false,
              writable: true,
              configurable: true
            }
          });

          // Copy every element in protoMixin into the prototype.
          // Note that `constructor` is special: it's _not_ copied over.
          // Instead, it's placed in ReturnedCtor.ActualConstructor.
          // It can either come:
          //   * from protoMixin, in cases where SourceOfProto is not defined
          //     (which means that it's what the developer passed herself in `protoMixin` as `constructor`)
          //   * from the source of protoMixin, in cases where SourceOfProto is defined
          //     (which means that we are taking it from the SourceOfProto, since the goal
          //      is to mimic it completely creating a working copy of the original constructor)
          var ownProps = Object.getOwnPropertyNames( protoMixin );
          for( var i = 0, l = ownProps.length; i < l; i ++ ){
            var k = ownProps[ i ];

            if( k !== 'constructor' ) ReturnedCtor.prototype[ k ] = protoMixin[ k ];
          }

          // We are not cloning a constructor, but creating a brand new one (using protoMixin as
          // a source of methods that just got added to the prototype).
          // ActualConstructor will be set to the `constructor` property of protoMixin
          if( ! SourceOfProto ){
            if( protoMixin.hasOwnProperty( 'constructor' ) ) ActualConstructor = protoMixin.constructor;
          }

          // We are in the process of cloning an existing constructor.
          // When doing that:
          // * ReturnedCtor's ActualConstructor will be set to the Source's ActualConstructor.
          //   This will ensure that the stock constructor (that just invokes ActualConstructor) works.
          // * ReturnedCtor's OriginalConstructor will be set to the Source's ActualConstructor (or the souce itself).
          //   This will ensure that we have a path to the actual constructor we actually cloned,
          //   so that instanceOf() will work (by checking ActualConstructor whenever possible)
          if( SourceOfProto ){
            ActualConstructor = SourceOfProto;
            ReturnedCtor.OriginalConstructor = SourceOfProto.OriginalConstructor || SourceOfProto;
          }

          // That's it!
          return ReturnedCtor;
        };

        var copyClassMethods = function( Source, Dest ){

          // Source class needs to be a function
          if( typeof( Source) !== 'function' ) throw new Error("Error: source constructor must be a function");

          // Copy class methods over, EXCEPT if it's Object (the base class) which is ALWAYS
          // gracefully ignored
          if( Source !== Object ){

            var ownProps = Object.getOwnPropertyNames( Source );
            for( var i = 0, l = ownProps.length; i < l; i ++){
              var property = ownProps[ i ];

              // This statement is there so that strict mode still works -- even accessing these
              // automatically like this will cause an error!
              if( property !== 'arguments' && property !== 'callee' && property !== 'caller' ){

                // It's one of the attributes' in Function()'s prototype: skip
                if( Function.prototype[ property ] === Source[ property ] || property === 'prototype' ) continue;
                // It's one of the attributes managed by simpleDeclare: skip
                if( [ 'extend', 'OriginalConstructor' ].indexOf( property ) !== -1 ) continue;
                Dest[ property ] = Source[ property ];
              }
            }
          }
        };

        // This method will be attached to `list` in `declare()`,
        // and it will be used to make sure that only fresh prototypes
        // are added
        var constructorAlreadyInList = function( Ctor, list ){

          var CtorConstructor = Ctor.OriginalConstructor ||  Ctor;
          var protoConstructor;

          var found = false;
          for( var i = 0, l = list.length; i < l; i ++ ){
            var proto = list[ i ];

            protoConstructor = proto.constructor.OriginalConstructor || proto.constructor;
            if( protoConstructor === CtorConstructor ){
              found = true;
              break;
            }
          }

          return found;
        };

        // Normalise arguments passed to declare(): the end result will always be
        // an object with two values:
        //  * SuperCtorList - an array of constructors
        //  * protoMixin - an object with prototype attributes
        // This implies that you can actually throw basically anything that makes sense
        // to declare: declare(), declare( A ), declare( )
        var workoutDeclareArguments = function( args ){

          var arg;

          // No arguments at all: inheriting straight from Object, nothing in the prototype
          if( args.length === 0 ) return { SuperCtorList: [], protoMixin: {} };

          // One argument: it could be:
          //   * An array of constructors
          //   * A protoMixin
          //   * A single constructor
          //  Act accordingly
          if( args.length === 1 ){

            arg = args[ 0 ];
            // It's an array of constructors
            if( Array.isArray( arg ) )
              return { SuperCtorList: arg, protoMixin: {} };
            // It's a protoMixin
            else if( typeof arg === 'object' && arg !== null )
              return { SuperCtorList: [], protoMixin: arg };
            // It's a constructor
            else if( typeof arg === 'function' )
              return { SuperCtorList: [ arg ], protoMixin: {} };
            else
              throw new Error( "Invalid lone argument to declare(), needs to be array, function or pure object" );
          }

          // Two arguments. Only check if the first one is an array. If it is, then it's the list of
          // constructors, with second argument POSSIBLY being protoMixin
          if( args.length === 2 ){
            var a = args[ 0 ];
            var b = args[ 1 ];

            // First parameter is an array: that's the list of ctors
            if( Array.isArray( a ) ){
              // Normalise b
              if( typeof b !== 'object' || b === null ) b = {};
              return { SuperCtorList: a, protoMixin: b };
            }
          }

          // CHECK POINT: at this point, there are 2 or more arguments, and the "array as first proto" is
          // out of the picture. So, will go through args and make up the array based on it
          var lastIndex = args.length - 1;
          var list = [];
          // This cycle will deal with all items except the last one, which might be either a
          // constructor or a protoMixin
          for( var i = 0; i < lastIndex; i ++ ){
            var item = args[ i ];

            // Check that it's the right type, allowing for the last one to be an exception
            if( typeof item !== 'function' )
              //console.err( "ITEM: ", item );
              throw new Error("Parameters to declare() must be constructor functions (except the last one which can be an object for the prototype)");
            list.push( item );
          }

          // The last one might be either a constructor function, or a protoMixin.
          // Deal with either case
          var lastOne = args[ lastIndex ];
          if( typeof lastOne === 'function' ){
            list.push( lastOne );
            return { SuperCtorList: list, protoMixin: {} };
          } else if( typeof lastOne === 'object' && lastOne !== null ) {
            return { SuperCtorList: list, protoMixin: lastOne };
          } else throw new Error("Last argument of declare() must be either a function or a mixin object");
        };

        // Parameters are very variable
        var declare = function(){

          // These will be worked out from `arguments`
          var SuperCtorList, protoMixin;

          var MixedClass, ResultClass;
          var list = [];
          var i, l, ii, ll;
          var proto;

          var r = workoutDeclareArguments( arguments );
          SuperCtorList = r.SuperCtorList;
          protoMixin = r.protoMixin;

          // No parameters: inheriting from Object directly, no multiple inheritance
          if( SuperCtorList.length === 0 ){
            MixedClass = Object;
          }
          // Only one parameter: straght single inheritance.
          else if( SuperCtorList.length === 1 ){
            MixedClass = SuperCtorList[ 0 ];

          // More than one parameter: multiple inheritance at work
          // MixedClass will end up being an artificially made constructor
          // where the prototype chain is the sum of _every_ prototype in
          // every element of SuperCtorList (taking out duplicates)
          } else {
            MixedClass = Object;

            // NOW:
            // Go through every __proto__ of every derivative class, and augment
            // MixedClass by inheriting from A COPY OF each one of them.

            list = [];
            for( i = 0, l = SuperCtorList.length; i < l; i ++ ){

              // Get the prototype list, in the right order
              // (the reversed discovery order)
              // The result will be placed in `subList`
              var subList = [];
              proto = SuperCtorList[ i ].prototype;
              while( proto ){
                if( proto.constructor !== Object ) subList.push( proto );
                proto = Object.getPrototypeOf( proto );
              }
              subList = subList.reverse();

              // Add each element of sublist as long as it's not already in the main `list`
              for( ii = 0, ll = subList.length; ii < ll; ii ++ ){
                if( ! constructorAlreadyInList( subList[ ii ].constructor, list ) ) list.push( subList[ ii ] );
              }
            }

            // For each element in the prototype list that isn't Object(),
            // augment MixedClass with a copy of the new prototype
            for( ii = 0, ll = list.length; ii < ll; ii ++ ){
              proto = list[ ii ];

              var M = MixedClass;

              if( proto.constructor !== Object ){

                MixedClass = makeConstructor( MixedClass, proto, proto.constructor );
                copyClassMethods( M, MixedClass ); // Methods previously inherited

                copyClassMethods( proto.constructor, MixedClass ); // Extra methods from the father constructor
              }
            }
          }

          // Finally, inherit from the MixedClass, and add
          // class methods over
          // MixedClass might be:
          // * Object (coming from no inheritance),
          // * SuperCtorList[0] (coming from single inheritance)
          // * A constructor with the appropriate prototype chain (multiple inheritance)
          ResultClass = makeConstructor( MixedClass, protoMixin );
          copyClassMethods( MixedClass, ResultClass );

          // Add getInherited, inherited() and inheritedAsync() to the prototype
          // (only if they are not already there)
          if( ! ResultClass.prototype.getInherited ) {
            ResultClass.prototype.getInherited = getInherited;
          }
          if( ! ResultClass.prototype.inherited ) {
            ResultClass.prototype.inherited = makeInheritedFunction( 'sync' );
          }
          if( ! ResultClass.prototype.inheritedAsync ) {
            ResultClass.prototype.inheritedAsync = makeInheritedFunction( 'async' );
          }

          // Add instanceOf
          if( ! ResultClass.prototype.instanceOf ) {
            ResultClass.prototype.instanceOf = instanceOf;
          }

          // Add class-wide method `extend`
          ResultClass.extend = function(){
            return extend.apply( this, arguments );
          };

          // That's it!
          return ResultClass;
        };

        // Returned extra: declarableObject
        declare.extendableObject = declare( Object );

        exports = module.exports = declare;

      });
    }(
        typeof define == 'function' && define.amd ?
            define :
            function ( factory ) { factory( require, exports, module); }
    ));<|endoftext|>


<commit_before>module("event");

test("toggle(Function, Function) - add toggle event and fake a few clicks", function() {
	expect(1);
	var count = 0,
		fn1 = function(e) { count++; },
		fn2 = function(e) { count--; },
		preventDefault = function(e) { e.preventDefault() },
		link = $('#mark');
	if ( $.browser.msie || $.browser.opera || /konquerer/i.test(navigator.userAgent) )
		ok( false, "click() on link gets executed in IE/Opera/Konquerer, not intended behaviour!" );
	else
		link.click(preventDefault).click().toggle(fn1, fn2).click().click().click().click().click();
	ok( count == 1, "Check for toggle(fn, fn)" );
});

test("unbind(event)", function() {
	expect(6);
	var el = $("#firstp");
	el.click(function() {
		ok( true, "Fake normal bind" );
	});
	el.click(function(event) {
		el.unbind(event);
		ok( true, "Fake onebind" );
	});
	el.click().click();

	el.click(function() { return; });
	el.unbind('click');
	ok( !el[0].onclick, "Handler is removed" ); // Bug #964

	el.click(function() { return; });
	el.unbind('change',function(){ return; });
	ok( el[0].onclick, "Extra handlers weren't accidentally removed." );

	el.unbind('click');
	ok( !el[0].$events, "Removed the events expando after all handlers are unbound." );
});

test("trigger(event, [data]", function() {
	expect(3);
	var handler = function(event, a, b, c) {
		ok( a == 1, "check passed data" );
		ok( b == "2", "check passed data" );
		ok( c == "abc", "check passed data" );
	}
	$("#firstp").bind("click", handler).trigger("click", [1, "2", "abc"]);
});

test("bind() with data", function() {
	expect(2);
	var handler = function(event) {
		ok( event.data, "check passed data exists" );
		ok( event.data.foo == "bar", "Check value of passed data" );
	}
	$("#firstp").bind("click", {foo: "bar"}, handler).click();
});

test("bind() with data and trigger() with data", function() {
	expect(4);
	var handler = function(event, data) {
		ok( event.data, "check passed data exists" );
		ok( event.data.foo == "bar", "Check value of passed data" );
		ok( data, "Check trigger data" );
		ok( data.bar == "foo", "Check value of trigger data" );
	}
	$("#firstp").bind("click", {foo: "bar"}, handler).trigger("click", [{bar: "foo"}]);
});

test("toggle(Function,Function) assigned from within one('xxx'), see #1054", function() {
	expect(4);
	var first = 0;
	$("#simon1").one("click", function() {
		ok( true, "Execute event only once" );
		$(this).toggle(function() {
			ok( first++ == 0 );
		}, function() {
			ok( first == 1 );
		});
		return false;
	}).click().click().click();
	ok( false, "Seems like this doesn't work (that is, it doesn't fail) when triggering the event programmatically" );
});

test("events don't work with iframes, see #939", function() {
	expect(2);
	var iframe = document.getElementById('iframe');
    var doc = iframe.contentDocument;
    doc.addEventListener('click', function() {
    	ok( true, "Event handling via DOM 2 methods" );
    }, false);
    $(doc).click(function() {
    	ok( true, "Event handling via jQuery's handler" );
    }).click();
});
<commit_msg>Added test for #935<commit_after>module("event");

test("toggle(Function, Function) - add toggle event and fake a few clicks", function() {
	expect(1);
	var count = 0,
		fn1 = function(e) { count++; },
		fn2 = function(e) { count--; },
		preventDefault = function(e) { e.preventDefault() },
		link = $('#mark');
	if ( $.browser.msie || $.browser.opera || /konquerer/i.test(navigator.userAgent) )
		ok( false, "click() on link gets executed in IE/Opera/Konquerer, not intended behaviour!" );
	else
		link.click(preventDefault).click().toggle(fn1, fn2).click().click().click().click().click();
	ok( count == 1, "Check for toggle(fn, fn)" );
});

test("unbind(event)", function() {
	expect(6);
	var el = $("#firstp");
	el.click(function() {
		ok( true, "Fake normal bind" );
	});
	el.click(function(event) {
		el.unbind(event);
		ok( true, "Fake onebind" );
	});
	el.click().click();

	el.click(function() { return; });
	el.unbind('click');
	ok( !el[0].onclick, "Handler is removed" ); // Bug #964

	el.click(function() { return; });
	el.unbind('change',function(){ return; });
	ok( el[0].onclick, "Extra handlers weren't accidentally removed." );

	el.unbind('click');
	ok( !el[0].$events, "Removed the events expando after all handlers are unbound." );
});

test("trigger(event, [data]", function() {
	expect(3);
	var handler = function(event, a, b, c) {
		ok( a == 1, "check passed data" );
		ok( b == "2", "check passed data" );
		ok( c == "abc", "check passed data" );
	}
	$("#firstp").bind("click", handler).trigger("click", [1, "2", "abc"]);
});

test("bind() with data", function() {
	expect(2);
	var handler = function(event) {
		ok( event.data, "check passed data exists" );
		ok( event.data.foo == "bar", "Check value of passed data" );
	}
	$("#firstp").bind("click", {foo: "bar"}, handler).click();
});

test("bind() with data and trigger() with data", function() {
	expect(4);
	var handler = function(event, data) {
		ok( event.data, "check passed data exists" );
		ok( event.data.foo == "bar", "Check value of passed data" );
		ok( data, "Check trigger data" );
		ok( data.bar == "foo", "Check value of trigger data" );
	}
	$("#firstp").bind("click", {foo: "bar"}, handler).trigger("click", [{bar: "foo"}]);
});

test("toggle(Function,Function) assigned from within one('xxx'), see #1054", function() {
	expect(4);
	var first = 0;
	$("#simon1").one("click", function() {
		ok( true, "Execute event only once" );
		$(this).toggle(function() {
			ok( first++ == 0 );
		}, function() {
			ok( first == 1 );
		});
		return false;
	}).click().click().click();
	ok( false, "Seems like this doesn't work (that is, it doesn't fail) when triggering the event programmatically" );
});

test("events don't work with iframes, see #939", function() {
	expect(2);
	var iframe = document.getElementById('iframe');
    var doc = iframe.contentDocument;
    doc.addEventListener('click', function() {
    	ok( true, "Event handling via DOM 2 methods" );
    }, false);
    $(doc).click(function() {
    	ok( true, "Event handling via jQuery's handler" );
    }).click();
});

test("Event.data is a global event object", function() {
	expect(3);
	var counter = 0;
	function selectOnChange(event) {
		equals( event.data, counter++ );
	}
	$("select").each(function(i){
		$(this).bind('change', i, selectOnChange);
	}).trigger('change');
});<|endoftext|>


<commit_before>var util = require('../src/util/seeds');

exports.seed = function(knex, Promise) {
  const cities = {};

  return knex('cities').select('*')
  .then(rows => {
    rows.forEach(city => {
      cities[city.name] = city.id;
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 1,
      city_id: cities['Tampere'],
      name: 'TiTe',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/tite.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 2,
      city_id: cities['Tampere'],
      name: 'Skilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/skilta.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 3,
      city_id: cities['Tampere'],
      name: 'Autek',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/autek.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 4,
      city_id: cities['Tampere'],
      name: 'Bioner',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/bioner.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 5,
      city_id: cities['Tampere'],
      name: 'Hiukkanen',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/hiukkanen.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 6,
      city_id: cities['Tampere'],
      name: 'Indecs',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/indecs.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 7,
      city_id: cities['Tampere'],
      name: 'KoRK',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/kork.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 8,
      city_id: cities['Tampere'],
      name: 'Man@ger',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/manager.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 9,
      city_id: cities['Tampere'],
      name: 'MIK',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/mik.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 10,
      city_id: cities['Tampere'],
      name: 'TamArk',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/tamark.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 11,
      city_id: cities['Tampere'],
      name: 'TARAKI',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/taraki.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 12,
      city_id: cities['Tampere'],
      name: 'YKI',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/yki.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 13,
      city_id: cities['Tampere'],
      name: 'TeLE',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/tele.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 14,
      city_id: cities['Tampere'],
      name: 'ESN INTO',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/esn.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 15,
      city_id: cities['Tampere'],
      name: 'Wapputiimi',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/wapputiimi.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 16,
      city_id: cities['Otaniemi'],
      name: 'Arkkitehtikilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/ak.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 17,
      city_id: cities['Otaniemi'],
      name: 'Athene',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/athene.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 18,
      city_id: cities['Otaniemi'],
      name: 'Automaatio- ja systeemitekniikan kilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/as.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 19,
      city_id: cities['Otaniemi'],
      name: 'Fyysikkokilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/fk.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 20,
      city_id: cities['Otaniemi'],
      name: 'Inkubio',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/inkubio.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 21,
      city_id: cities['Otaniemi'],
      name: 'Kemistikilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/kk.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 22,
      city_id: cities['Otaniemi'],
      name: 'Koneinsinöörikilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/kik.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 23,
      city_id: cities['Otaniemi'],
      name: 'Kauppatieteiden ylioppilaat',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/ky.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 24,
      city_id: cities['Otaniemi'],
      name: 'Maanmittarikilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/mk.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 25,
      city_id: cities['Otaniemi'],
      name: 'Puunjalostajakilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/pjk.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 26,
      city_id: cities['Otaniemi'],
      name: 'Prodeko',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/prodeko.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 27,
      city_id: cities['Otaniemi'],
      name: 'Prosessiteekkarit',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/pt.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 28,
      city_id: cities['Otaniemi'],
      name: 'Rakennusinsinöörikilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/ik.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 29,
      city_id: cities['Otaniemi'],
      name: 'Sähköinsinöörikilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/sik.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 30,
      city_id: cities['Otaniemi'],
      name: 'Teknologföreningen',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/tf.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 31,
      city_id: cities['Otaniemi'],
      name: 'Tietokilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/tik.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 32,
      city_id: cities['Otaniemi'],
      name: 'Vuorimieskilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/vk.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 33,
      city_id: cities['Otaniemi'],
      name: 'TOKYO',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/tokyo.png',
    });
  });
};
<commit_msg>Renamed Kauppatieteiden ylioppilaat to KY<commit_after>var util = require('../src/util/seeds');

exports.seed = function(knex, Promise) {
  const cities = {};

  return knex('cities').select('*')
  .then(rows => {
    rows.forEach(city => {
      cities[city.name] = city.id;
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 1,
      city_id: cities['Tampere'],
      name: 'TiTe',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/tite.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 2,
      city_id: cities['Tampere'],
      name: 'Skilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/skilta.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 3,
      city_id: cities['Tampere'],
      name: 'Autek',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/autek.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 4,
      city_id: cities['Tampere'],
      name: 'Bioner',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/bioner.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 5,
      city_id: cities['Tampere'],
      name: 'Hiukkanen',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/hiukkanen.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 6,
      city_id: cities['Tampere'],
      name: 'Indecs',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/indecs.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 7,
      city_id: cities['Tampere'],
      name: 'KoRK',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/kork.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 8,
      city_id: cities['Tampere'],
      name: 'Man@ger',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/manager.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 9,
      city_id: cities['Tampere'],
      name: 'MIK',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/mik.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 10,
      city_id: cities['Tampere'],
      name: 'TamArk',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/tamark.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 11,
      city_id: cities['Tampere'],
      name: 'TARAKI',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/taraki.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 12,
      city_id: cities['Tampere'],
      name: 'YKI',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/yki.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 13,
      city_id: cities['Tampere'],
      name: 'TeLE',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/tele.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 14,
      city_id: cities['Tampere'],
      name: 'ESN INTO',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/esn.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 15,
      city_id: cities['Tampere'],
      name: 'Wapputiimi',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/wapputiimi.png'
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 16,
      city_id: cities['Otaniemi'],
      name: 'Arkkitehtikilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/ak.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 17,
      city_id: cities['Otaniemi'],
      name: 'Athene',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/athene.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 18,
      city_id: cities['Otaniemi'],
      name: 'Automaatio- ja systeemitekniikan kilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/as.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 19,
      city_id: cities['Otaniemi'],
      name: 'Fyysikkokilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/fk.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 20,
      city_id: cities['Otaniemi'],
      name: 'Inkubio',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/inkubio.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 21,
      city_id: cities['Otaniemi'],
      name: 'Kemistikilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/kk.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 22,
      city_id: cities['Otaniemi'],
      name: 'Koneinsinöörikilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/kik.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 23,
      city_id: cities['Otaniemi'],
      name: 'KY',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/ky.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 24,
      city_id: cities['Otaniemi'],
      name: 'Maanmittarikilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/mk.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 25,
      city_id: cities['Otaniemi'],
      name: 'Puunjalostajakilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/pjk.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 26,
      city_id: cities['Otaniemi'],
      name: 'Prodeko',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/prodeko.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 27,
      city_id: cities['Otaniemi'],
      name: 'Prosessiteekkarit',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/pt.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 28,
      city_id: cities['Otaniemi'],
      name: 'Rakennusinsinöörikilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/ik.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 29,
      city_id: cities['Otaniemi'],
      name: 'Sähköinsinöörikilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/sik.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 30,
      city_id: cities['Otaniemi'],
      name: 'Teknologföreningen',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/tf.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 31,
      city_id: cities['Otaniemi'],
      name: 'Tietokilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/tik.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 32,
      city_id: cities['Otaniemi'],
      name: 'Vuorimieskilta',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/vk.png',
    });
  })
  .then(() => {
    return util.insertOrUpdate(knex, 'teams', {
      id: 33,
      city_id: cities['Otaniemi'],
      name: 'TOKYO',
      image_path: 'https://storage.googleapis.com/wappuapp/assets/tokyo.png',
    });
  });
};
<|endoftext|>


<commit_before>define(module, function(exports, require) {

  var code = {
    hex: [
      '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
      '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
      '\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
      '\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
      '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
      '\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
      '\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
      '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
      '\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
      '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
      '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007E', '\u007F'
    ],
    key: [
      'NULL', 'SOH', 'STX', 'ETX', 'EOT', 'ENQ', 'ACK', 'BEL', 'BS', 'HT', 'LF', 'VT',
      'FF', 'CR', 'SO', 'SI', 'DLE', 'DC1', 'DC2', 'DC3', 'DC4', 'NAK', 'SYN', 'ETB',
      'CAN', 'EM', 'SUB', 'ESC', 'FS', 'GS', 'RS', 'US', 'space', '!', '"', '#',
      '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/',
      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';',
      '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
      'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
      'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
      '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
      'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
      'x', 'y', 'z', '{', '|', '}', '~', 'delete'
    ]
  };

  function get_key(hex) {
    var index = code.hex.indexOf(hex);
    return index > -1 ? code.key[index] : '';
  }

  function get_hex(key) {
    var index = code.key.indexOf(key);
    return index > -1 ? code.hex[index] : '';
  }

  var child_process = require('child_process');

  exports({

    exit: function(code) { process.exit(code || 0); },

    set_title: function(title) {
      process.stdout.write(String.fromCharCode(27) + ']0;' + title + String.fromCharCode(7));
    },

    clear: function() {
      if (process.platform === 'win32') {
        process.stdout.write('\033c');
      } else {
        process.stdout.write('\u001B[2J\u001B[0;0f');
      }
    },

    log_title: function() { console.log('\x1b[47m\x1b[34m ' + Array.prototype.slice.call(arguments).join('') + ' \x1b[0m\x1b[0m'); },
    log: function(text) { console.log.apply(console, arguments); },
    error: function() { console.error.apply(console, arguments); },

    done: function(error) {
      if (typeof error === 'string') {
        console.error.apply(console, arguments);
      } else if (typeof error === 'object') {
        console.error(error.message);
      } else {
        console.log('Process Complete');
      }
      process.exit(error ? -1 : 0);
    },

    run: function(command, options) {
      child_process.execSync(command, Object.assign({ stdio: [0,1,2] }, options));
    },

    keypress: function(handler) {
      process.stdin.setRawMode(true);
      process.stdin.setEncoding('utf8');
      process.stdin.on('data', chr => {
        var key = get_key(chr);
        if (key === 'ETX') process.exit(0);
        handler(key, chr);
      });
      process.stdin.resume();
    }

  });

});
<commit_msg>term; user input system<commit_after>define(module, function(exports, require) {

  var code = {
    hex: [
      '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
      '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
      '\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
      '\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
      '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
      '\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
      '\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
      '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
      '\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
      '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
      '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007E', '\u007F'
    ],
    key: [
      'NULL', 'SOH', 'STX', 'ETX', 'EOT', 'ENQ', 'ACK', 'BEL', 'BS', 'HT', 'LF', 'VT',
      'FF', 'CR', 'SO', 'SI', 'DLE', 'DC1', 'DC2', 'DC3', 'DC4', 'NAK', 'SYN', 'ETB',
      'CAN', 'EM', 'SUB', 'ESC', 'FS', 'GS', 'RS', 'US', 'space', '!', '"', '#',
      '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/',
      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';',
      '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
      'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
      'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
      '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
      'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
      'x', 'y', 'z', '{', '|', '}', '~', 'delete'
    ]
  };

  function blue_white(s) { return `\x1b[47m\x1b[34m${s}\x1b[0m\x1b[0m`; }
  function red(s)        { return `\x1b[31m${s}\x1b[0m`; }
  function green(s)      { return `\x1b[32m${s}\x1b[0m`; }
  function blue(s)       { return `\x1b[34m${s}\x1b[0m`; }

  function get_key(hex) {
    var index = code.hex.indexOf(hex);
    return index > -1 ? code.key[index] : '';
  }

  function get_hex(key) {
    var index = code.key.indexOf(key);
    return index > -1 ? code.hex[index] : '';
  }

  var child_process = require('child_process');
  var readline = require('readline');
  var qp = require('qp-utility');

  qp.module(exports, {

    blue_white: blue_white,
    red: red,
    green: green,
    blue: blue,

    exit: function(code) { process.exit(code || 0); },

    set_title: function(title) {
      process.stdout.write(String.fromCharCode(27) + ']0;' + title + String.fromCharCode(7));
    },

    clear: function() {
      if (process.platform === 'win32') {
        process.stdout.write('\033c');
      } else {
        process.stdout.write('\u001B[2J\u001B[0;0f');
      }
    },

    log_title: function() { console.log(blue_white(qp.arg(arguments).join(''))); },
    log: function() { console.log.apply(console, arguments); },
    error: function() { console.error.apply(console, arguments); },
    line: function() { console.log(); },

    done: function(error) {
      if (typeof error === 'string') {
        console.error.apply(console, arguments);
      } else if (typeof error === 'object') {
        console.error(error.message);
      } else {
        console.log('Process Complete');
      }
      process.exit(error ? -1 : 0);
    },

    run: function(command, options) {
      child_process.execSync(command, Object.assign({ stdio: [0,1,2] }, options));
    },

    keypress: function(handler) {
      process.stdin.setRawMode(true);
      process.stdin.setEncoding('utf8');
      process.stdin.on('data', chr => {
        var key = get_key(chr);
        if (key === 'ETX') process.exit(0);
        handler(key, chr);
      });
      process.stdin.resume();
    },

    /* USER INPUT */

    input: function() {
      var items = qp.arg(arguments);
      var done = items.pop();
      var results = {};
      var next_input = () => {
        if (items.length) {
          var item = items.shift();
          var action = item.key === 'confirm' ? 'confirm' : item.options ? 'pick' : 'ask';
          this[action](item, (error, result) => {
            qp.override(results, result);
            if (error) return done(error, results); else next_input();
          });
        } else {
          done(null, results);
        }
      };
      next_input();
    },

    confirm: function(data, done) {
      var prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
      if (data.default) data.default_text =` (${data.default})? `;
      prompt.question(blue(data.question + (data.default_text || '? ')), (answer) => {
        prompt.close();
        answer = qp.lower(answer || (data.default || 'n')).slice(0, 1);
        done(null, { [data.key]: answer === 'y' });
      });
    },

    ask: function(data, done) {
      var prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
      if (data.default) data.default_text =` (${data.default}): `;
      prompt.question(green(data.question + (data.default_text || ': ')), (answer) => {
        prompt.close();
        done(null, { [data.key]: answer || data.default || '' });
      });
    },

    pick: function(data, done) {
      if (data.title) console.log(data.title);
      data.default = {
        option: null,
        text: data.default ? ` (${data.default}): ` : ': ',
        value: data.default
      };
      data.options.forEach((option, i) => {
        option.key = option.key || i + 1;
        console.log(`${option.key} - ${option.text}`);
        if (option.default) {
          data.default.option = option;
          data.default.text = ` (${option.text}): `;
        }
      });
      var prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
      prompt.question(green(data.question + data.default.text), (answer) => {
        prompt.close();
        if (data.multi) {
          if (answer === '') answer = data.default.value || '';
          var options = qp.select(answer.split(''), key => {
            var option = data.options.find(option => qp.lower(option.key) === qp.lower(key));
            return qp.get(option, 'value', option);
          });
          done(null, { [data.key]: options });
        } else {
          var option = data.options.find(option => qp.lower(option.key) === qp.lower(answer)) || null;
          if (data.default.option && !option) {
            done(null, { [data.key]: qp.get(data.default.option, 'value', data.default.option) });
          } else {
            done(null, { [data.key]: qp.get(option, 'value', option) });
          }
        }
      });
    },

  });

});
<|endoftext|>


<commit_before>const StickyNotes = {};
StickyNotes.Result = {
  Success: 'Success',
  Failure: 'Failure'
};

StickyNotes.postMessage = function(message) {
  var stickynotes = window.webkit.messageHandlers.stickynotes;
  if (stickynotes.postMessage) {
    stickynotes.postMessage(JSON.stringify(message));
  }
};

document.addEventListener('touchstart', function(e) {
  var isCanceled = false;
  var touches = e.changedTouches;
  if (touches.length === 0) {
    return;
  }
  var touch  = touches[0];
  var dom    = e.target;
  var origX  = dom.offsetLeft;
  var origY  = dom.offsetTop;
  var startX = touch.clientX;
  var startY = touch.clientY;
  setTimeout(function() {
    if (!isCanceled) {
      StickyNotes.postMessage({type: 'create-sticky', x: origX + startX, y: origY + startY });
    }
  }, 1000);
  function cancel() {
    isCanceled = true;
    document.removeEventListener(cancel);
  }
  document.addEventListener('touchend',    cancel);
  document.addEventListener('touchcancel', cancel);
});

StickyNotes.PREFIX = '__stickynotes_';
StickyNotes.stickies = [];
StickyNotes.getDom = function(sticky) {
  return document.getElementById(StickyNotes.PREFIX + sticky.id);
};

StickyNotes.addSticky = function(sticky) {
  if (StickyNotes.getDom(sticky)) {
    return StickyNotes.Result.Failure;
  }
  var dom = document.createElement('div');
  dom.id = StickyNotes.PREFIX + sticky.id;
  dom.style.position = 'absolute';
  dom.style.top    = sticky.top + 'px';
  dom.style.left   = sticky.left + 'px';
  dom.style.minWidth  = '50px';
  dom.style.minHeight = '10px';
  dom.textContent  = sticky.content;
  dom.style.backgroundColor = sticky.color;
  dom.style.borderRadius = '10px';
  dom.style.textOverflow = 'ellipsis';
  dom.style.padding = '10px';
  dom.addEventListener('click', function() {
    StickyNotes.postMessage({ type: 'select-sticky', sticky: sticky });
  });
  var startX;
  var startY;
  var origX;
  var origY;
  var deltaX;
  var deltaY;
  function onTouchStart(e) {
    var touches = e.changedTouches;
    if (touches.length === 0) {
      return;
    }
    var touch = touches[0];
    e.stopPropagation();
    origX  = dom.offsetLeft;
    origY  = dom.offsetTop;
    startX = touch.clientX;
    startY = touch.clientY;
    deltaX = startX - origX;
    deltaY = startY - origY;
    dom.addEventListener('touchmove', onTouchMove);
    dom.addEventListener('touchend', onTouchEnd);
  };

  function onTouchMove(e) {
    var touches = e.changedTouches;
    if (touches.length === 0) {
      cancel();
      return;
    }
    var touch = touches[0];
    e.stopPropagation();
    e.preventDefault();
    dom.style.left = (touch.clientX - deltaX) + 'px';
    dom.style.top  = (touch.clientY - deltaY) + 'px';
  };

  function onTouchEnd(e) {
    e.stopPropagation();
    cancel();
    sticky.top = parseInt(dom.style.top);
    sticky.left = parseInt(dom.style.left);
    StickyNotes.postMessage({type: 'update-sticky', sticky: sticky});
  };
  function cancel() {
    dom.removeEventListener('touchmove', onTouchMove);
    dom.removeEventListener('touchup', onTouchEnd);
  }
  document.body.appendChild(dom);
  dom.addEventListener('touchstart', onTouchStart);
  sticky.dom = dom;
  StickyNotes.stickies.push(sticky);
  return StickyNotes.Result.Success;
};

StickyNotes.removeSticky = function(sticky) {
  if (sticky.dom) {
    document.body.removeChild(sticky.dom);
    sticky.dom = null;
    return StickyNotes.Result.Success;
  }
  return StickyNotes.Result.Failure;
};

StickyNotes.cleanStickies = function() {
  StickyNotes.stickies.forEach(StickyNotes.removeSticky);
  StickyNotes.stickies = [];
  return StickyNotes.Result.Success;
};

StickyNotes.reloadStickies = function(stickies) {
  StickyNotes.cleanStickies();
  stickies.forEach(StickyNotes.addSticky);
  return StickyNotes.Result.Success;
};

StickyNotes.jumpToSticky = function(sticky) {
  var dom = StickyNotes.getDom(sticky);
  if (!dom) {
    return StickyNotes.Result.Failure;
  }
  dom.scrollIntoView({block: 'end', behavior: 'smooth'});
  return StickyNotes.Result.Success;
};
<commit_msg>Create sticky by triple tap<commit_after>const StickyNotes = {};
StickyNotes.Result = {
  Success: 'Success',
  Failure: 'Failure'
};

StickyNotes.postMessage = function(message) {
  var stickynotes = window.webkit.messageHandlers.stickynotes;
  if (stickynotes.postMessage) {
    stickynotes.postMessage(JSON.stringify(message));
  }
};

var touchCount = 0;

document.addEventListener('touchstart', function(e) {
  var touches = e.changedTouches;
  if (touches.length === 0) {
    return;
  }
  var touch  = touches[0];
  var dom    = e.target;
  var origX  = dom.offsetLeft;
  var origY  = dom.offsetTop;
  var startX = touch.clientX;
  var startY = touch.clientY;
  touchCount++;
  if (touchCount >= 3) {
    StickyNotes.postMessage({
      type: 'create-sticky',
      x: origX + startX,
      y: origY + startY
    });
  }
  setTimeout(function() {
    touchCount = 0;
  }, 500);
});

StickyNotes.PREFIX = '__stickynotes_';
StickyNotes.stickies = [];
StickyNotes.getDom = function(sticky) {
  return document.getElementById(StickyNotes.PREFIX + sticky.id);
};

StickyNotes.addSticky = function(sticky) {
  if (StickyNotes.getDom(sticky)) {
    return StickyNotes.Result.Failure;
  }
  var dom = document.createElement('div');
  dom.id = StickyNotes.PREFIX + sticky.id;
  dom.style.position = 'absolute';
  dom.style.top    = sticky.top + 'px';
  dom.style.left   = sticky.left + 'px';
  dom.style.minWidth  = '50px';
  dom.style.minHeight = '10px';
  dom.textContent  = sticky.content;
  dom.style.backgroundColor = sticky.color;
  dom.style.borderRadius = '10px';
  dom.style.textOverflow = 'ellipsis';
  dom.style.padding = '10px';
  var startX;
  var startY;
  var origX;
  var origY;
  var deltaX;
  var deltaY;
  function onTouchStart(e) {
    var touches = e.changedTouches;
    if (touches.length === 0) {
      return;
    }
    var touch = touches[0];
    e.preventDefault();
    e.stopPropagation();
    origX  = dom.offsetLeft;
    origY  = dom.offsetTop;
    startX = touch.clientX;
    startY = touch.clientY;
    deltaX = startX - origX;
    deltaY = startY - origY;
    dom.addEventListener('touchmove', onTouchMove);
    dom.addEventListener('touchend', onTouchEnd);
  };

  function onTouchMove(e) {
    var touches = e.changedTouches;
    if (touches.length === 0) {
      cancel();
      return;
    }
    var touch = touches[0];
    e.stopPropagation();
    e.preventDefault();
    dom.style.left = (touch.clientX - deltaX) + 'px';
    dom.style.top  = (touch.clientY - deltaY) + 'px';
  };

  function onTouchEnd(e) {
    e.preventDefault();
    e.stopPropagation();
    cancel();
    if (Math.abs(sticky.top - parseInt(dom.style.top)) < 5 &&
        Math.abs(sticky.left - parseInt(dom.style.left)) < 5) {
      StickyNotes.postMessage({ type: 'select-sticky', sticky: sticky });
    } else {
      sticky.top = parseInt(dom.style.top);
      sticky.left = parseInt(dom.style.left);
      StickyNotes.postMessage({type: 'update-sticky', sticky: sticky});
    }
  };
  function cancel() {
    dom.removeEventListener('touchmove', onTouchMove);
    dom.removeEventListener('touchup', onTouchEnd);
  }
  document.body.appendChild(dom);
  dom.addEventListener('touchstart', onTouchStart);
  sticky.dom = dom;
  StickyNotes.stickies.push(sticky);
  return StickyNotes.Result.Success;
};

StickyNotes.removeSticky = function(sticky) {
  if (sticky.dom) {
    document.body.removeChild(sticky.dom);
    sticky.dom = null;
    return StickyNotes.Result.Success;
  }
  return StickyNotes.Result.Failure;
};

StickyNotes.cleanStickies = function() {
  StickyNotes.stickies.forEach(StickyNotes.removeSticky);
  StickyNotes.stickies = [];
  return StickyNotes.Result.Success;
};

StickyNotes.reloadStickies = function(stickies) {
  StickyNotes.cleanStickies();
  stickies.forEach(StickyNotes.addSticky);
  return StickyNotes.Result.Success;
};

StickyNotes.jumpToSticky = function(sticky) {
  var dom = StickyNotes.getDom(sticky);
  if (!dom) {
    return StickyNotes.Result.Failure;
  }
  dom.scrollIntoView({block: 'end', behavior: 'smooth'});
  return StickyNotes.Result.Success;
};
<|endoftext|>


<commit_before>var Discord = require("discord.js");
var config = require("./config");
var cmds = require("./commands/commands")

var client = new Discord.Client({autoReconnect: true});
var botUser;

client.on("message", function(message) {
	if(message.content.toLowerCase().indexOf("hello") > -1 && message.isMentioned(botUser)) {
		return client.sendMessage(message.channel, 'Hello ' + message.author);
	}
	else if(message.content.toLowerCase().indexOf("who gta") > -1) {
		return message.reply("oooh oooh me! I'll play!")
	}

	else if(message.content.charAt(0) == config.cmdprefix) {
		var spacePos = message.content.indexOf(" ");
		//var cmd = spacePos > -1 ? message.content.substring(1, spacePos) : message.content.substring(1);

		var cmdArray = message.content.substring(1).split(" ");
		var cmdStr = cmdArray[0];

		var cmd = cmds.get(cmdStr);

		if(cmd != null) {
			cmd.action(message);
		}

	}
});

//Called once the bot is logged in and ready to use.
client.on("ready", function() {
	client.setPlayingGame(config.playing);
	botUser = client.users.get("username", "DeixBot");
	cmds.setUp(client, config);
	/*for (var i = 0; i < client.servers.length; i++) {
		var server = client.servers[i];
		var msg = "S'up " + server.name + "!";
		client.sendMessage(server.defaultChannel, msg);
	}*/
});

//Handle a CTRL+C to actually shutdown somewhat cleanly
process.on("SIGINT", function() {
	client.logout();
	/*for (var i = 0; i < client.servers.length; i++){
		var server = client.servers[i];
		client.sendMessage(server.defaultChannel, "Peace out!", function(i){
			if(i + 1 == client.servers.length){
				client.logout();
			}
		});
	}*/
});

client.loginWithToken(config.discord.key);
<commit_msg>Randomised playing with messages<commit_after>var Discord = require("discord.js");
var config = require("./config");
var cmds = require("./commands/commands")

var client = new Discord.Client({autoReconnect: true});
var botUser;

client.on("message", function(message) {
	if(message.content.toLowerCase().indexOf("hello") > -1 && message.isMentioned(botUser)) {
		return client.sendMessage(message.channel, 'Hello ' + message.author);
	}
	else if(message.content.toLowerCase().indexOf("who gta") > -1) {
		return message.reply("oooh oooh me! I'll play!")
	}

	else if(message.content.charAt(0) == config.cmdprefix) {
		var spacePos = message.content.indexOf(" ");
		//var cmd = spacePos > -1 ? message.content.substring(1, spacePos) : message.content.substring(1);

		var cmdArray = message.content.substring(1).split(" ");
		var cmdStr = cmdArray[0];

		var cmd = cmds.get(cmdStr);

		if(cmd != null) {
			cmd.action(message);
		}

	}
});

//Called once the bot is logged in and ready to use.
client.on("ready", function() {
	client.setPlayingGame(config.playing[Math.floor(Math.random() * config.playing.length]));
	botUser = client.users.get("username", "DeixBot");
	cmds.setUp(client, config);
	/*for (var i = 0; i < client.servers.length; i++) {
		var server = client.servers[i];
		var msg = "S'up " + server.name + "!";
		client.sendMessage(server.defaultChannel, msg);
	}*/
});

//Handle a CTRL+C to actually shutdown somewhat cleanly
process.on("SIGINT", function() {
	client.logout();
	/*for (var i = 0; i < client.servers.length; i++){
		var server = client.servers[i];
		client.sendMessage(server.defaultChannel, "Peace out!", function(i){
			if(i + 1 == client.servers.length){
				client.logout();
			}
		});
	}*/
});

client.loginWithToken(config.discord.key);
<|endoftext|>


<commit_before>'use strict'

/*  ------------------------------------------------------------------------ */

const { deepExtend, groupBy, filterBy, omit, sum, sortBy } = require ('../../../../ccxt')
const { strictEqual: equal, deepEqual } = require ('assert')

/*  ------------------------------------------------------------------------ */

function testDeepExtend() {

    let count = 0

    const values = [{
        a: 1,
        b: 2,
        d: {
            a: 1,
            b: [],
            c: { test1: 123, test2: 321 }},
        f: 5,
        g: 123,
        i: 321,
        j: [1, 2],
    },
    {
        b: 3,
        c: 5,
        d: {
            b: { first: 'one', second: 'two' },
            c: { test2: 222 }},
        e: { one: 1, two: 2 },
        f: [{ 'foo': 'bar' }],
        g: (void 0),
        h: /abc/g,
        i: null,
        j: [3, 4]
    }]

    const extended = deepExtend (...values)
    deepEqual (extended, {
        a: 1,
        b: 3,
        d: {
            a: 1,
            b: { first: 'one', second: 'two' },
            c: { test1: 123, test2: 222 }
        },
        f: [{ 'foo': 'bar' }],
        g: undefined,
        c: 5,
        e: { one: 1, two: 2 },
        h: /abc/g,
        i: null,
        j: [3, 4]
    })

    deepEqual (deepExtend (undefined, undefined, {'foo': 'bar' }), { 'foo': 'bar' })
}

/*  ------------------------------------------------------------------------ */

function testGroupBy() {

    const array = [
        { 'foo': 'a' },
        { 'foo': 'b' },
        { 'foo': 'c' },
        { 'foo': 'b' },
        { 'foo': 'c' },
        { 'foo': 'c' },
    ]

    deepEqual (groupBy (array, 'foo'), {
        'a': [ { 'foo': 'a' } ],
        'b': [ { 'foo': 'b' }, { 'foo': 'b' } ],
        'c': [ { 'foo': 'c' }, { 'foo': 'c' }, { 'foo': 'c' } ],
    })
}

/*  ------------------------------------------------------------------------ */

function testFilterBy() {

    const array = [
        { 'foo': 'a' },
        { 'foo': undefined },
        { 'foo': 'b' },
        { },
        { 'foo': 'a', 'bar': 'b' },
        { 'foo': 'c' },
        { 'foo': 'd' },
        { 'foo': 'b' },
        { 'foo': 'c' },
        { 'foo': 'c' },
    ]

    deepEqual (filterBy (array, 'foo', 'a'), [
        { 'foo': 'a' },
        { 'foo': 'a', 'bar': 'b' },
    ])
}

/*  ------------------------------------------------------------------------ */

function testOmit() {

    deepEqual (omit ({ }, 'foo'), {})
    deepEqual (omit ({ foo: 2 }, 'foo'), { })
    deepEqual (omit ({ foo: 2, bar: 3 }, 'foo'), { bar: 3 })
    deepEqual (omit ({ foo: 2, bar: 3 }, ['foo']), { bar: 3 })
    deepEqual (omit ({ foo: 2, bar: 3 }), { foo: 2, bar: 3 })
    deepEqual (omit ({ foo: 2, bar: 3 }, 'foo', 'bar'), {})
    deepEqual (omit ({ foo: 2, bar: 3 }, ['foo'], 'bar'), {})
    deepEqual (omit ({ 5: 2, bar: 3 }, [ 5 ]), { bar: 3 })
    deepEqual (omit ({ 5: 2, bar: 3 }, 5), { bar: 3 })
}

/*  ------------------------------------------------------------------------ */

function testSum() {

    equal (undefined, sum ())
    equal (2,   sum (2))
    equal (432, sum (2, 30, 400))
    equal (432, sum (2, undefined, [ 88 ], 30, '7', 400, null))
}

/*  ------------------------------------------------------------------------ */

function testSortBy() {

    const arr = [{ 'x': 5 }, { 'x': 2 }, { 'x': 4 }, { 'x': 0 }, { 'x': 1 }, { 'x': 3 }]
    sortBy (arr, 'x')

    deepEqual (arr, [
        { 'x': 0 },
        { 'x': 1 },
        { 'x': 2 },
        { 'x': 3 },
        { 'x': 4 },
        { 'x': 5 },
    ])

    deepEqual (sortBy (arr, 'x', true), [
        { 'x': 5 },
        { 'x': 4 },
        { 'x': 3 },
        { 'x': 2 },
        { 'x': 1 },
        { 'x': 0 },
    ])

    deepEqual (sortBy ([], 'x'), [])
}

/*  ------------------------------------------------------------------------ */

function testGeneric() {
	testDeepExtend()
	testGroupBy()
	testFilterBy()
	testOmit()
	testSum()
	testSortBy()
}

/*  ------------------------------------------------------------------------ */

testGeneric()
<commit_msg>test.generic.js edits<commit_after>'use strict'

const { deepExtend, groupBy, filterBy, omit, sum, sortBy } = require ('../../../base/functions/generic')
const { strictEqual: equal, deepEqual } = require ('assert')

function testDeepExtend() {

    let count = 0

    const values = [{
        a: 1,
        b: 2,
        d: {
            a: 1,
            b: [],
            c: { test1: 123, test2: 321 }},
        f: 5,
        g: 123,
        i: 321,
        j: [1, 2],
    },
    {
        b: 3,
        c: 5,
        d: {
            b: { first: 'one', second: 'two' },
            c: { test2: 222 }},
        e: { one: 1, two: 2 },
        f: [{ 'foo': 'bar' }],
        g: (void 0),
        h: /abc/g,
        i: null,
        j: [3, 4]
    }]

    const extended = deepExtend (...values)
    deepEqual (extended, {
        a: 1,
        b: 3,
        d: {
            a: 1,
            b: { first: 'one', second: 'two' },
            c: { test1: 123, test2: 222 }
        },
        f: [{ 'foo': 'bar' }],
        g: undefined,
        c: 5,
        e: { one: 1, two: 2 },
        h: /abc/g,
        i: null,
        j: [3, 4]
    })

    deepEqual (deepExtend (undefined, undefined, {'foo': 'bar' }), { 'foo': 'bar' })
}

function testGroupBy() {

    const array = [
        { 'foo': 'a' },
        { 'foo': 'b' },
        { 'foo': 'c' },
        { 'foo': 'b' },
        { 'foo': 'c' },
        { 'foo': 'c' },
    ]

    deepEqual (groupBy (array, 'foo'), {
        'a': [ { 'foo': 'a' } ],
        'b': [ { 'foo': 'b' }, { 'foo': 'b' } ],
        'c': [ { 'foo': 'c' }, { 'foo': 'c' }, { 'foo': 'c' } ],
    })
}

function testFilterBy() {

    const array = [
        { 'foo': 'a' },
        { 'foo': undefined },
        { 'foo': 'b' },
        { },
        { 'foo': 'a', 'bar': 'b' },
        { 'foo': 'c' },
        { 'foo': 'd' },
        { 'foo': 'b' },
        { 'foo': 'c' },
        { 'foo': 'c' },
    ]

    deepEqual (filterBy (array, 'foo', 'a'), [
        { 'foo': 'a' },
        { 'foo': 'a', 'bar': 'b' },
    ])
}

function testOmit() {

    deepEqual (omit ({ }, 'foo'), {})
    deepEqual (omit ({ foo: 2 }, 'foo'), { })
    deepEqual (omit ({ foo: 2, bar: 3 }, 'foo'), { bar: 3 })
    deepEqual (omit ({ foo: 2, bar: 3 }, ['foo']), { bar: 3 })
    deepEqual (omit ({ foo: 2, bar: 3 }), { foo: 2, bar: 3 })
    deepEqual (omit ({ foo: 2, bar: 3 }, 'foo', 'bar'), {})
    deepEqual (omit ({ foo: 2, bar: 3 }, ['foo'], 'bar'), {})
    deepEqual (omit ({ 5: 2, bar: 3 }, [ 5 ]), { bar: 3 })
    deepEqual (omit ({ 5: 2, bar: 3 }, 5), { bar: 3 })
}

function testSum() {

    equal (undefined, sum ())
    equal (2,   sum (2))
    equal (432, sum (2, 30, 400))
    equal (432, sum (2, undefined, [ 88 ], 30, '7', 400, null))
}

function testSortBy() {

    const arr = [{ 'x': 5 }, { 'x': 2 }, { 'x': 4 }, { 'x': 0 }, { 'x': 1 }, { 'x': 3 }]
    sortBy (arr, 'x')

    deepEqual (arr, [
        { 'x': 0 },
        { 'x': 1 },
        { 'x': 2 },
        { 'x': 3 },
        { 'x': 4 },
        { 'x': 5 },
    ])

    deepEqual (sortBy (arr, 'x', true), [
        { 'x': 5 },
        { 'x': 4 },
        { 'x': 3 },
        { 'x': 2 },
        { 'x': 1 },
        { 'x': 0 },
    ])

    deepEqual (sortBy ([], 'x'), [])
}

function testGeneric() {
	testDeepExtend()
	testGroupBy()
	testFilterBy()
	testOmit()
	testSum()
	testSortBy()
}

testGeneric()
<|endoftext|>